From 3b8c370b39b1c1bf87363cdc83f0b26aa56e9c52 Mon Sep 17 00:00:00 2001 From: "Glitch (a4-thearst3rd)" Date: Thu, 26 Sep 2019 16:20:10 +0000 Subject: [PATCH 01/10] Initial commit: express app + formatting --- .gitignore | 7 +++++ GLITCH-README.md | 27 ++++++++++++++++++ package.json | 27 ++++++++++++++++++ public/client.js | 46 +++++++++++++++++++++++++++++++ public/style.css | 71 ++++++++++++++++++++++++++++++++++++++++++++++++ server.js | 24 ++++++++++++++++ views/index.html | 58 +++++++++++++++++++++++++++++++++++++++ 7 files changed, 260 insertions(+) create mode 100644 .gitignore create mode 100644 GLITCH-README.md create mode 100644 package.json create mode 100644 public/client.js create mode 100644 public/style.css create mode 100644 server.js create mode 100644 views/index.html diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..9694ede20 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +*.DS_Store +node_modules/ +package-lock.json +.gitconfig +.glitch-assets +shrinkwrap.yaml +db.json diff --git a/GLITCH-README.md b/GLITCH-README.md new file mode 100644 index 000000000..cb1061b9b --- /dev/null +++ b/GLITCH-README.md @@ -0,0 +1,27 @@ +Welcome to Glitch +================= + +Click `Show` in the header to see your app live. Updates to your code will instantly deploy and update live. + +**Glitch** is the friendly community where you'll build the app of your dreams. Glitch lets you instantly create, remix, edit, and host an app, bot or site, and you can invite collaborators or helpers to simultaneously edit code with you. + +Find out more [about Glitch](https://glitch.com/about). + + +Your Project +------------ + +On the front-end, +- edit `public/client.js`, `public/style.css` and `views/index.html` +- drag in `assets`, like images or music, to add them to your project + +On the back-end, +- your app starts at `server.js` +- add frameworks and packages in `package.json` +- safely store app secrets in `.env` (nobody can see this but you and people you invite) + + +Made by [Glitch](https://glitch.com/) +------------------- + +\ 悜o悜)惎 diff --git a/package.json b/package.json new file mode 100644 index 000000000..725480982 --- /dev/null +++ b/package.json @@ -0,0 +1,27 @@ +{ + "//1": "describes your app and its dependencies", + "//2": "https://docs.npmjs.com/files/package.json", + "//3": "updating this file will download and update your packages", + "name": "hello-express", + "version": "0.0.1", + "description": "A simple Node app built on Express, instantly up and running.", + "main": "server.js", + "scripts": { + "start": "node server.js" + }, + "dependencies": { + "express": "^4.16.4" + }, + "engines": { + "node": "8.x" + }, + "repository": { + "url": "https://glitch.com/edit/#!/hello-express" + }, + "license": "MIT", + "keywords": [ + "node", + "glitch", + "express" + ] +} diff --git a/public/client.js b/public/client.js new file mode 100644 index 000000000..e767431a9 --- /dev/null +++ b/public/client.js @@ -0,0 +1,46 @@ +// client-side js +// run by the browser each time your view template is loaded + +console.log("hello world :o") + +// our default array of dreams +const dreams = +[ + "Find and count some sheep", + "Climb a really tall mountain", + "Wash the dishes", +] + +// define variables that reference elements on our page +const dreamsList = document.getElementById("dreams") +const dreamsForm = document.forms[0] +const dreamInput = dreamsForm.elements["dream"] + +// a helper function that creates a list item for a given dream +const appendNewDream = function(dream) +{ + const newListItem = document.createElement("li") + newListItem.innerHTML = dream + dreamsList.appendChild(newListItem) +} + +// iterate through every dream and add it to our page +dreams.forEach(function(dream) +{ + appendNewDream(dream) +}) + +// listen for the form to be submitted and add a new dream when it is +dreamsForm.onsubmit = function(event) +{ + // stop our form submission from refreshing the page + event.preventDefault() + + // get dream value and add it to the list + dreams.push(dreamInput.value) + appendNewDream(dreamInput.value) + + // reset form + dreamInput.value = ""; + dreamInput.focus() +} diff --git a/public/style.css b/public/style.css new file mode 100644 index 000000000..38c55f6be --- /dev/null +++ b/public/style.css @@ -0,0 +1,71 @@ +/* styles */ +/* called by your view template */ + +* { + box-sizing: border-box; +} + +body { + font-family: "Benton Sans", "Helvetica Neue", helvetica, arial, sans-serif; + margin: 2em; +} + +h1 { + font-style: italic; + color: #373fff; +} + +.bold { + font-weight: bold; +} + +p { + max-width: 600px; +} + +form { + margin-bottom: 25px; + padding: 15px; + background-color: cyan; + display: inline-block; + width: 100%; + max-width: 340px; + border-radius: 3px; +} + +input { + display: block; + margin-bottom: 10px; + padding: 5px; + width: 100%; + border: 1px solid lightgrey; + border-radius: 3px; + font-size: 16px; +} + +button { + font-size: 16px; + border-radius: 3px; + background-color: lightgrey; + border: 1px solid grey; + box-shadow: 2px 2px teal; + cursor: pointer; +} + +button:hover { + background-color: yellow; +} + +button:active { + box-shadow: none; +} + +li { + margin-bottom: 5px; +} + +footer { + margin-top: 50px; + padding-top: 25px; + border-top: 1px solid lightgrey; +} diff --git a/server.js b/server.js new file mode 100644 index 000000000..d5890b54b --- /dev/null +++ b/server.js @@ -0,0 +1,24 @@ +// server.js +// where your node app starts + +// init project +const express = require("express"), + app = express() + +// we've started you off with Express, +// but feel free to use whatever libs or frameworks you'd like through `package.json`. + +// http://expressjs.com/en/starter/static-files.html +app.use(express.static("public")) + +// http://expressjs.com/en/starter/basic-routing.html +app.get('/', function(request, response) +{ + response.sendFile(__dirname + "/views/index.html") +}) + +// listen for requests :) +const listener = app.listen(process.env.PORT, function() +{ + console.log("Your app is listening on port " + listener.address().port) +}) diff --git a/views/index.html b/views/index.html new file mode 100644 index 000000000..57a266df7 --- /dev/null +++ b/views/index.html @@ -0,0 +1,58 @@ + + + + + + + + + + + + + Welcome to Glitch! + + + + + + + + + + + + + +
+

+ A Dream of the Future +

+
+ +
+

Oh hi,

+ +

Tell me your hopes and dreams:

+ +
+ + +
+ +
+
    +
    +
    + + + + +
    + + + + From 2301899d3ba79437a11d1174fc0cd92bedaca690 Mon Sep 17 00:00:00 2001 From: Terry Hearst Date: Thu, 26 Sep 2019 23:18:48 -0400 Subject: [PATCH 02/10] Linting + added helmet middleware --- public/client.js | 31 ++++++++++++++----------------- server.js | 39 ++++++++++++++++++++++----------------- 2 files changed, 36 insertions(+), 34 deletions(-) diff --git a/public/client.js b/public/client.js index e767431a9..04c67a36c 100644 --- a/public/client.js +++ b/public/client.js @@ -1,46 +1,43 @@ // client-side js // run by the browser each time your view template is loaded -console.log("hello world :o") +console.log('hello world :o') // our default array of dreams const dreams = [ - "Find and count some sheep", - "Climb a really tall mountain", - "Wash the dishes", + 'Find and count some sheep', + 'Climb a really tall mountain', + 'Wash the dishes' ] // define variables that reference elements on our page -const dreamsList = document.getElementById("dreams") +const dreamsList = document.getElementById('dreams') const dreamsForm = document.forms[0] -const dreamInput = dreamsForm.elements["dream"] +const dreamInput = dreamsForm.elements.dream // a helper function that creates a list item for a given dream -const appendNewDream = function(dream) -{ - const newListItem = document.createElement("li") +const appendNewDream = function (dream) { + const newListItem = document.createElement('li') newListItem.innerHTML = dream dreamsList.appendChild(newListItem) } // iterate through every dream and add it to our page -dreams.forEach(function(dream) -{ +dreams.forEach(function (dream) { appendNewDream(dream) }) // listen for the form to be submitted and add a new dream when it is -dreamsForm.onsubmit = function(event) -{ +dreamsForm.onsubmit = function (event) { // stop our form submission from refreshing the page event.preventDefault() - + // get dream value and add it to the list dreams.push(dreamInput.value) appendNewDream(dreamInput.value) - - // reset form - dreamInput.value = ""; + + // reset form + dreamInput.value = '' dreamInput.focus() } diff --git a/server.js b/server.js index d5890b54b..b9b3045c3 100644 --- a/server.js +++ b/server.js @@ -1,24 +1,29 @@ -// server.js -// where your node app starts +/* + * Server file for CS 4241 Assignment 4 + * by Terry Hearst + */ -// init project -const express = require("express"), - app = express() +// ####################### +// ## INITIALIZE SERVER ## +// ####################### -// we've started you off with Express, -// but feel free to use whatever libs or frameworks you'd like through `package.json`. +const express = require('express') +const app = express() +const helmet = require('helmet') +const path = require('path') -// http://expressjs.com/en/starter/static-files.html -app.use(express.static("public")) +// Helmet middleware +app.use(helmet()) -// http://expressjs.com/en/starter/basic-routing.html -app.get('/', function(request, response) -{ - response.sendFile(__dirname + "/views/index.html") +// Host static files +app.use(express.static('public')) + +// Route '/' to main page +app.get('/', function (request, response) { + response.sendFile(path.join(__dirname, 'views', 'index.html')) }) -// listen for requests :) -const listener = app.listen(process.env.PORT, function() -{ - console.log("Your app is listening on port " + listener.address().port) +// Listen for requests +const listener = app.listen(process.env.PORT, function () { + console.log('Your app is listening on port ' + listener.address().port) }) From f6884d8ff73187d385fdbfbff5ac8c6155954f43 Mon Sep 17 00:00:00 2001 From: Terry Hearst Date: Fri, 27 Sep 2019 00:57:36 -0400 Subject: [PATCH 03/10] Minor changes --- README.md | 0 package.json | 3 ++- server.js | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) mode change 100755 => 100644 README.md diff --git a/README.md b/README.md old mode 100755 new mode 100644 diff --git a/package.json b/package.json index 725480982..5574fad6d 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,8 @@ "start": "node server.js" }, "dependencies": { - "express": "^4.16.4" + "express": "^4.16.4", + "helmet": "^3.21.1" }, "engines": { "node": "8.x" diff --git a/server.js b/server.js index b9b3045c3..10975c8ca 100644 --- a/server.js +++ b/server.js @@ -24,6 +24,6 @@ app.get('/', function (request, response) { }) // Listen for requests -const listener = app.listen(process.env.PORT, function () { +const listener = app.listen(process.env.PORT || 3000, function () { console.log('Your app is listening on port ' + listener.address().port) }) From 5bd318294b99a85e015538e779c9b06be73fe0a5 Mon Sep 17 00:00:00 2001 From: Terry Hearst Date: Fri, 27 Sep 2019 16:42:17 -0400 Subject: [PATCH 04/10] BIG commit - browserify, standard, three all implemented --- .gitignore | 1 + package.json | 4 +- public/client.js | 124 ++++++++++++++++++++++++++++++++--------------- public/style.css | 105 ++++++++++++++++++++++++--------------- server.js | 4 ++ views/index.html | 83 +++++++++++-------------------- 6 files changed, 187 insertions(+), 134 deletions(-) diff --git a/.gitignore b/.gitignore index 9694ede20..61120e942 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ package-lock.json .glitch-assets shrinkwrap.yaml db.json +public/bundle.js diff --git a/package.json b/package.json index 5574fad6d..7d279dd69 100644 --- a/package.json +++ b/package.json @@ -10,8 +10,10 @@ "start": "node server.js" }, "dependencies": { + "compression": "^1.7.4", "express": "^4.16.4", - "helmet": "^3.21.1" + "helmet": "^3.21.1", + "three": "^0.108.0" }, "engines": { "node": "8.x" diff --git a/public/client.js b/public/client.js index 04c67a36c..56f50e0b4 100644 --- a/public/client.js +++ b/public/client.js @@ -1,43 +1,91 @@ -// client-side js -// run by the browser each time your view template is loaded - -console.log('hello world :o') - -// our default array of dreams -const dreams = -[ - 'Find and count some sheep', - 'Climb a really tall mountain', - 'Wash the dishes' -] - -// define variables that reference elements on our page -const dreamsList = document.getElementById('dreams') -const dreamsForm = document.forms[0] -const dreamInput = dreamsForm.elements.dream - -// a helper function that creates a list item for a given dream -const appendNewDream = function (dream) { - const newListItem = document.createElement('li') - newListItem.innerHTML = dream - dreamsList.appendChild(newListItem) -} +/* + * Client-side JS for CS 4241 Assignment 4 + * by Terry Hearst + */ + +const THREE = require('three') + +// ########################### +// ## SETUP THREE.JS CANVAS ## +// ########################### + +const viewportElement = document.getElementById('viewport') + +const renderer = new THREE.WebGLRenderer() +const canvas = renderer.domElement + +viewportElement.appendChild(canvas) + +const w = canvas.clientWidth +const h = canvas.clientHeight + +console.log('CANVAS SIZE: ', w, h) + +renderer.setSize(w, h) + +// ########################### +// ## SETUP ACTUAL 3D SCENE ## +// ########################### + +// Setup Scene and Camera objs +const scene = new THREE.Scene() +const camera = new THREE.PerspectiveCamera(75, w / h, 0.1, 1000) -// iterate through every dream and add it to our page -dreams.forEach(function (dream) { - appendNewDream(dream) -}) +camera.position.z = 10 -// listen for the form to be submitted and add a new dream when it is -dreamsForm.onsubmit = function (event) { - // stop our form submission from refreshing the page - event.preventDefault() +// Create knot +const geo1 = new THREE.TorusKnotGeometry(1, 0.4, 64, 8, 2, 3) +const mat1 = new THREE.MeshStandardMaterial({ color: 0x0000FF }) +const mesh1 = new THREE.Mesh(geo1, mat1) - // get dream value and add it to the list - dreams.push(dreamInput.value) - appendNewDream(dreamInput.value) +scene.add(mesh1) - // reset form - dreamInput.value = '' - dreamInput.focus() +// Define lighting +const ambLight = new THREE.AmbientLight(0x404040) +const dirLight = new THREE.DirectionalLight(0xFFFFFF) + +scene.add(ambLight) +scene.add(dirLight) + +// Grid +var gridHelper = new THREE.GridHelper(10, 20) +gridHelper.rotation.x = Math.PI / 2 +scene.add(gridHelper) + +// ############################## +// ## MAIN RENDERING FUNCTIONS ## +// ############################## + +// Checks to see if the canvas was resized and handles that properly +function resize () { + const width = viewportElement.clientWidth + const height = viewportElement.clientHeight + if (canvas.width !== width || canvas.height !== height) { + // console.log("Canvas resized from ", canvas.width, canvas.height, " to ", width, height) + canvas.clientWidth = width + canvas.clientHeight = height + canvas.width = width + canvas.height = height + + camera.aspect = (width / height) + camera.updateProjectionMatrix() + renderer.setSize(width, height) + } } + +// Update the geometry every frame +function update () { + resize() + + mesh1.rotation.x += 0.01 + mesh1.rotation.y += 0.01 +} + +// MAIN render function. This is what should requestAnimationFrame +function render () { + update() + renderer.render(scene, camera) + window.requestAnimationFrame(render) +} + +window.requestAnimationFrame(render) diff --git a/public/style.css b/public/style.css index 38c55f6be..71804416a 100644 --- a/public/style.css +++ b/public/style.css @@ -1,71 +1,96 @@ -/* styles */ -/* called by your view template */ +/* + * Stylesheet for CS 4241 Assignment 4 + * by Terry Hearst + */ -* { - box-sizing: border-box; + +/* -- DEFAULT GLITCH STYLESHEET (for the most part) -- */ + +html { + height: 100%; + box-sizing: border-box; +} + +*, *:before, *:after { + box-sizing: inherit; } body { - font-family: "Benton Sans", "Helvetica Neue", helvetica, arial, sans-serif; - margin: 2em; + font-family: "Benton Sans", "Helvetica Neue", helvetica, arial, sans-serif; + margin: 0; + height: 100%; } h1 { - font-style: italic; - color: #373fff; + font-style: italic; + color: #FFFFFF; } .bold { - font-weight: bold; + font-weight: bold; } p { - max-width: 600px; -} - -form { - margin-bottom: 25px; - padding: 15px; - background-color: cyan; - display: inline-block; - width: 100%; - max-width: 340px; - border-radius: 3px; + max-width: 600px; } input { - display: block; - margin-bottom: 10px; - padding: 5px; - width: 100%; - border: 1px solid lightgrey; - border-radius: 3px; - font-size: 16px; + display: block; + margin-bottom: 10px; + padding: 5px; + width: 100%; + /* border: 1px solid lightgrey; */ + border-radius: 3px; + font-size: 16px; } button { - font-size: 16px; - border-radius: 3px; - background-color: lightgrey; - border: 1px solid grey; - box-shadow: 2px 2px teal; - cursor: pointer; + font-size: 16px; + color: #FFFFFF; + border-radius: 3px; + background-color: #804040; + border: 0px; + box-shadow: 2px 2px red; + cursor: pointer; } button:hover { - background-color: yellow; + background-color: #C08080; } button:active { - box-shadow: none; + background-color: #402020; } li { - margin-bottom: 5px; + margin-bottom: 5px; +} + + +/* -- ELEMENT SIZE CONTROL -- */ +/* Much of this is thanks to WebGLFundamentals on how to make a viewport fill a screen */ +/* https://webglfundamentals.org/webgl/lessons/webgl-anti-patterns.html */ + +#editor { + color: white; + padding: 0.5em; + position: absolute; + right: 0px; + top: 0px; + width: 30%; + height: 100%; + + background-color: #202020; +} + +#viewport { + width: 70%; + height: 100%; + background-color: blue; + display: block; } -footer { - margin-top: 50px; - padding-top: 25px; - border-top: 1px solid lightgrey; +canvas { + width: 100%; + height: 100%; } diff --git a/server.js b/server.js index 10975c8ca..aac43a819 100644 --- a/server.js +++ b/server.js @@ -11,10 +11,14 @@ const express = require('express') const app = express() const helmet = require('helmet') const path = require('path') +const compression = require('compression') // Helmet middleware app.use(helmet()) +// Compression middleware +app.use(compression()) + // Host static files app.use(express.static('public')) diff --git a/views/index.html b/views/index.html index 57a266df7..2b44304e2 100644 --- a/views/index.html +++ b/views/index.html @@ -1,58 +1,31 @@ - - - - - - - - - - - Welcome to Glitch! - - - - - - - - - - - - - -
    -

    - A Dream of the Future -

    -
    - -
    -

    Oh hi,

    - -

    Tell me your hopes and dreams:

    - -
    - - -
    - -
    -
      -
      -
      - - - - -
      - - - + + + CS 4241 Assignment 4 + + + + + + + + + + + + + + + + + +
      +
      +

      LifeGrid

      + + + +
      + From 6d2efc9b40e08c1b5f5b683f8810084e345897f0 Mon Sep 17 00:00:00 2001 From: Terry Hearst Date: Fri, 27 Sep 2019 18:11:56 -0400 Subject: [PATCH 05/10] Removed editor div, replaced with dat.gui --- package.json | 1 + public/client.js | 33 ++++++++++++++++++++++++++++++++- public/style.css | 4 +++- views/index.html | 4 ++-- 4 files changed, 38 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index 7d279dd69..d19cb6933 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ }, "dependencies": { "compression": "^1.7.4", + "dat.gui": "^0.7.6", "express": "^4.16.4", "helmet": "^3.21.1", "three": "^0.108.0" diff --git a/public/client.js b/public/client.js index 56f50e0b4..28d6ece54 100644 --- a/public/client.js +++ b/public/client.js @@ -4,6 +4,37 @@ */ const THREE = require('three') +const dat = require('dat.gui') + +// ######################## +// ## SETUP GAME OF LIFE ## +// ######################## + +const GameOfLifeClass = function () { + this.running = false + this.speed = 3 + this.edit = function () { + window.alert('Button pressed') + } + this.showHelp = function () { + window.alert('Show help') + } +} + +const gameOfLife = new GameOfLifeClass() + +// ################### +// ## SETUP DAT.GUI ## +// ################### + +window.onload = function () { + const gui = new dat.GUI() + + gui.add(gameOfLife, 'running').name('Running') + gui.add(gameOfLife, 'speed', 1, 20).name('Iterations/sec').step(1) + gui.add(gameOfLife, 'edit').name('Edit board contents') + gui.add(gameOfLife, 'showHelp').name('Show help') +} // ########################### // ## SETUP THREE.JS CANVAS ## @@ -31,7 +62,7 @@ renderer.setSize(w, h) const scene = new THREE.Scene() const camera = new THREE.PerspectiveCamera(75, w / h, 0.1, 1000) -camera.position.z = 10 +camera.position.z = 8 // Create knot const geo1 = new THREE.TorusKnotGeometry(1, 0.4, 64, 8, 2, 3) diff --git a/public/style.css b/public/style.css index 71804416a..a459fe4b0 100644 --- a/public/style.css +++ b/public/style.css @@ -71,6 +71,7 @@ li { /* Much of this is thanks to WebGLFundamentals on how to make a viewport fill a screen */ /* https://webglfundamentals.org/webgl/lessons/webgl-anti-patterns.html */ +/* #editor { color: white; padding: 0.5em; @@ -82,9 +83,10 @@ li { background-color: #202020; } +*/ #viewport { - width: 70%; + width: 100%; height: 100%; background-color: blue; display: block; diff --git a/views/index.html b/views/index.html index 2b44304e2..5348539b8 100644 --- a/views/index.html +++ b/views/index.html @@ -21,11 +21,11 @@
      -
      + From 1754ee0415a000736ae73773acb59d712ecf75c7 Mon Sep 17 00:00:00 2001 From: Terry Hearst Date: Fri, 27 Sep 2019 19:07:47 -0400 Subject: [PATCH 06/10] Checkpoint - removed unneeded css, started seperating out materials and geometries --- public/client.js | 34 ++++++++++++++++++++---- public/style.css | 68 ------------------------------------------------ 2 files changed, 29 insertions(+), 73 deletions(-) diff --git a/public/client.js b/public/client.js index 28d6ece54..93a45823c 100644 --- a/public/client.js +++ b/public/client.js @@ -10,6 +10,8 @@ const dat = require('dat.gui') // ## SETUP GAME OF LIFE ## // ######################## +const gridSize = 3 + const GameOfLifeClass = function () { this.running = false this.speed = 3 @@ -64,10 +66,31 @@ const camera = new THREE.PerspectiveCamera(75, w / h, 0.1, 1000) camera.position.z = 8 -// Create knot -const geo1 = new THREE.TorusKnotGeometry(1, 0.4, 64, 8, 2, 3) -const mat1 = new THREE.MeshStandardMaterial({ color: 0x0000FF }) -const mesh1 = new THREE.Mesh(geo1, mat1) +// Create different geometries +const geos = +[ + new THREE.Geometry(), // Blank + new THREE.SphereGeometry(1.3/(gridSize/2), 8, 6), // Sphere + new THREE.TorusGeometry(1.3/(gridSize/2), 0.5/(gridSize/2), 8, 16), // Simple torus + new THREE.TorusKnotGeometry(1.3/(gridSize/2), 0.6/(gridSize/2), 64, 8, 2, 3), // Torus knot 1 + new THREE.TorusKnotGeometry(1.5/(gridSize/2), 0.45/(gridSize/2), 64, 8, 3, 4) // Torus knot 2 +] +const mats = +[ + new THREE.MeshStandardMaterial({ color: 0xFF0000 }), + new THREE.MeshStandardMaterial({ color: 0xFFFF00 }), + new THREE.MeshToonMaterial({ color: 0x30FF30 }), + new THREE.MeshNormalMaterial(/*{ color: 0x4040FF }*/), +] + +const meshes = [] +for (let i = 0; i < gridSize; i++) { + meshes[i] = [] + for (let j = 0; j < gridSize; j++) { + meshes[i][j] = new THREE.Mesh(geos[0], mats[0]) + } +} +const mesh1 = new THREE.Mesh(geos[4], mats[3]) scene.add(mesh1) @@ -79,7 +102,8 @@ scene.add(ambLight) scene.add(dirLight) // Grid -var gridHelper = new THREE.GridHelper(10, 20) +const gridColor = 0x808080 +const gridHelper = new THREE.GridHelper(10, gridSize, gridColor, gridColor) gridHelper.rotation.x = Math.PI / 2 scene.add(gridHelper) diff --git a/public/style.css b/public/style.css index a459fe4b0..ddf571308 100644 --- a/public/style.css +++ b/public/style.css @@ -3,9 +3,6 @@ * by Terry Hearst */ - -/* -- DEFAULT GLITCH STYLESHEET (for the most part) -- */ - html { height: 100%; box-sizing: border-box; @@ -16,75 +13,10 @@ html { } body { - font-family: "Benton Sans", "Helvetica Neue", helvetica, arial, sans-serif; margin: 0; height: 100%; } -h1 { - font-style: italic; - color: #FFFFFF; -} - -.bold { - font-weight: bold; -} - -p { - max-width: 600px; -} - -input { - display: block; - margin-bottom: 10px; - padding: 5px; - width: 100%; - /* border: 1px solid lightgrey; */ - border-radius: 3px; - font-size: 16px; -} - -button { - font-size: 16px; - color: #FFFFFF; - border-radius: 3px; - background-color: #804040; - border: 0px; - box-shadow: 2px 2px red; - cursor: pointer; -} - -button:hover { - background-color: #C08080; -} - -button:active { - background-color: #402020; -} - -li { - margin-bottom: 5px; -} - - -/* -- ELEMENT SIZE CONTROL -- */ -/* Much of this is thanks to WebGLFundamentals on how to make a viewport fill a screen */ -/* https://webglfundamentals.org/webgl/lessons/webgl-anti-patterns.html */ - -/* -#editor { - color: white; - padding: 0.5em; - position: absolute; - right: 0px; - top: 0px; - width: 30%; - height: 100%; - - background-color: #202020; -} -*/ - #viewport { width: 100%; height: 100%; From f03aca7a81d154e691453d0b7003fc52c6008528 Mon Sep 17 00:00:00 2001 From: Terry Hearst Date: Fri, 27 Sep 2019 22:04:49 -0400 Subject: [PATCH 07/10] Significant progress. All I gotta do is actually implement GOL --- public/client.js | 222 +++++++++++++++++++++++++++++++++++++++-------- public/style.css | 43 +++++++++ views/index.html | 36 ++++---- 3 files changed, 252 insertions(+), 49 deletions(-) diff --git a/public/client.js b/public/client.js index 93a45823c..4c6f0e964 100644 --- a/public/client.js +++ b/public/client.js @@ -10,17 +10,19 @@ const dat = require('dat.gui') // ## SETUP GAME OF LIFE ## // ######################## -const gridSize = 3 +const gridSize = 10 + +function showHelp () { + const popup = document.getElementById('help-popup') + popup.classList.toggle('show') +} const GameOfLifeClass = function () { this.running = false this.speed = 3 - this.edit = function () { - window.alert('Button pressed') - } - this.showHelp = function () { - window.alert('Show help') - } + this.rotSpeed = 0.6 + this.editMode = false + this.showHelp = showHelp } const gameOfLife = new GameOfLifeClass() @@ -33,9 +35,13 @@ window.onload = function () { const gui = new dat.GUI() gui.add(gameOfLife, 'running').name('Running') - gui.add(gameOfLife, 'speed', 1, 20).name('Iterations/sec').step(1) - gui.add(gameOfLife, 'edit').name('Edit board contents') - gui.add(gameOfLife, 'showHelp').name('Show help') + gui.add(gameOfLife, 'speed', 1, 20).name('Iterations/Sec').step(1) + gui.add(gameOfLife, 'rotSpeed', 0, 5).name('Rotation Speed') + gui.add(gameOfLife, 'editMode').name('Edit Mode') + gui.add(gameOfLife, 'showHelp').name('Toggle Help') + + // Show the help screen at the start + showHelp() } // ########################### @@ -62,51 +68,176 @@ renderer.setSize(w, h) // Setup Scene and Camera objs const scene = new THREE.Scene() -const camera = new THREE.PerspectiveCamera(75, w / h, 0.1, 1000) +const camera = new THREE.PerspectiveCamera(60, w / h, 0.1, 1000) -camera.position.z = 8 +camera.position.z = 11 -// Create different geometries +// Create different geometries (and make them all the correct size) const geos = [ - new THREE.Geometry(), // Blank - new THREE.SphereGeometry(1.3/(gridSize/2), 8, 6), // Sphere - new THREE.TorusGeometry(1.3/(gridSize/2), 0.5/(gridSize/2), 8, 16), // Simple torus - new THREE.TorusKnotGeometry(1.3/(gridSize/2), 0.6/(gridSize/2), 64, 8, 2, 3), // Torus knot 1 - new THREE.TorusKnotGeometry(1.5/(gridSize/2), 0.45/(gridSize/2), 64, 8, 3, 4) // Torus knot 2 + /* Blank */ new THREE.Geometry(), + /* Sphere */ new THREE.SphereGeometry(1.3 / (gridSize / 2), 8, 6), + /* Torus */ new THREE.TorusGeometry(1.3 / (gridSize / 2), 0.5 / (gridSize / 2), 8, 16), + /* Knot 1 */ new THREE.TorusKnotGeometry(1.3 / (gridSize / 2), 0.5 / (gridSize / 2), 64, 8, 2, 3), + /* Knot 2 */ new THREE.TorusKnotGeometry(1.5 / (gridSize / 2), 0.45 / (gridSize / 2), 64, 8, 3, 4) ] + +// Create different materials const mats = [ new THREE.MeshStandardMaterial({ color: 0xFF0000 }), new THREE.MeshStandardMaterial({ color: 0xFFFF00 }), - new THREE.MeshToonMaterial({ color: 0x30FF30 }), - new THREE.MeshNormalMaterial(/*{ color: 0x4040FF }*/), + new THREE.MeshStandardMaterial({ color: 0x30FF30 }), + new THREE.MeshNormalMaterial(/* { color: 0x4040FF } */) ] +// HELPER - Maps a value from one range to another +function map (x, low1, high1, low2, high2) { + const r1 = high1 - low1 + const r2 = high2 - low2 + return ((x - low1) * (r2 / r1)) + low2 +} + +// HELPER - Calculate x, y position of cell based on i, j index +function calcCellPosition (i, j) { + return { + x: map(i, 0, gridSize - 1, 5 * (-(gridSize - 1) / gridSize), 5 * ((gridSize - 1) / gridSize)), + y: -map(j, 0, gridSize - 1, 5 * (-(gridSize - 1) / gridSize), 5 * ((gridSize - 1) / gridSize)) + } +} + +// Create a mesh for each cell const meshes = [] -for (let i = 0; i < gridSize; i++) { - meshes[i] = [] - for (let j = 0; j < gridSize; j++) { - meshes[i][j] = new THREE.Mesh(geos[0], mats[0]) +for (let j = 0; j < gridSize; j++) { + meshes[j] = [] + for (let i = 0; i < gridSize; i++) { + const rand1 = Math.floor(Math.random() * 5) + + const mesh = new THREE.Mesh(geos[rand1], mats[rand1 >= 0 ? rand1 - 1 : 0]) + + // Position all meshes in the center of that mesh's square + const cellPosition = calcCellPosition(i, j) + mesh.position.x = cellPosition.x + mesh.position.y = cellPosition.y + + const rotationOffset = Math.random() * Math.PI * 2 + mesh.rotation.x = rotationOffset + mesh.rotation.y = rotationOffset + + scene.add(mesh) + + meshes[j][i] = mesh } } -const mesh1 = new THREE.Mesh(geos[4], mats[3]) -scene.add(mesh1) +// TEST - make mesh for the corners of the board +/* +const meshCornerTopLeft = new THREE.Mesh(geos[2], mats[3]) +const meshCornerBottomRight = new THREE.Mesh(geos[3], mats[3]) -// Define lighting -const ambLight = new THREE.AmbientLight(0x404040) -const dirLight = new THREE.DirectionalLight(0xFFFFFF) +meshCornerTopLeft.position.x = -5 +meshCornerTopLeft.position.y = 5 +meshCornerBottomRight.position.x = 5 +meshCornerBottomRight.position.y = -5 + +scene.add(meshCornerTopLeft) +scene.add(meshCornerBottomRight) +*/ +// Define lighting +const ambLight = new THREE.AmbientLight(0x303030) scene.add(ambLight) + +const dirLight = new THREE.DirectionalLight(0xFFFFFF) +const lightTarget = new THREE.Object3D() +lightTarget.position.x = -5 +lightTarget.position.z = -5 +lightTarget.position.y = -5 +scene.add(lightTarget) scene.add(dirLight) +dirLight.target = lightTarget -// Grid +// Make grid const gridColor = 0x808080 const gridHelper = new THREE.GridHelper(10, gridSize, gridColor, gridColor) gridHelper.rotation.x = Math.PI / 2 scene.add(gridHelper) +// Make mesh for the object that will assist you in edit mode +const s = 3 / (gridSize / 2) +const editGeo = new THREE.CubeGeometry(s, s, s) +const editMat = new THREE.MeshBasicMaterial({color: 0xFFFFFF, transparent: true, opacity: 0.3}) + +const editMesh = new THREE.Mesh(editGeo, editMat) +scene.add(editMesh) + +// ############################ +// ## HANDLE MOUSE MOVEMENTS ## +// ############################ + +// Get screen coords for the board +// Taken from https://stackoverflow.com/questions/27409074/converting-3d-position-to-2d-screen-position-r69 +/* + * NOTE: + * I originally was trying to use the above solution which *apparently* you're supposed to be able to give it an object + * or position (there were variations) that would return the screen space coords. I tried all of them. All of them gave + * me positions of +/- infinity for both x and y. So I use this janky method that WILL WORK assuming that you don't + * change the camera's position. Whatever. + */ +const boardBoundaries = {x1: 0, y1: 0, x2: 0, y2: 0} +function calculateBoardCornerScreenCoordinates () { + // uhh yeah, I just measured these... + // they work in all resolutions I promise... at least they're close enough + + const top = map(138, 0, 1287, 0, canvas.clientHeight) + const distFromCenter = (canvas.clientHeight / 2) - top + + boardBoundaries.x1 = Math.round((canvas.clientWidth / 2) - distFromCenter) + boardBoundaries.y1 = Math.round((canvas.clientHeight / 2) - distFromCenter) + + boardBoundaries.x2 = Math.round((canvas.clientWidth / 2) + distFromCenter) + boardBoundaries.y2 = Math.round((canvas.clientHeight / 2) + distFromCenter) + + console.log('New board screen coordinates:') + console.log('x1: ', boardBoundaries.x1) + console.log('y1: ', boardBoundaries.y1) + console.log('x2: ', boardBoundaries.x2) + console.log('y2: ', boardBoundaries.y2) +} + +calculateBoardCornerScreenCoordinates() + +window.onmousemove = function (event) { + if (gameOfLife.editMode) { + editMat.opacity = 0.3 + + const i = Math.round(map(event.x, boardBoundaries.x1, boardBoundaries.x2, 0, gridSize)) + const j = Math.round(map(event.y, boardBoundaries.y1, boardBoundaries.y2, 0, gridSize)) + + //console.log(i, j) + + const cellPosition = calcCellPosition(i, j) + + editMesh.position.x = cellPosition.x + editMesh.position.y = cellPosition.y + } else { + editMat.opacity = 0 + } +} + +window.onmouseclick = function (event) { + if (gameOfLife.editMode) { + + const i = Math.round(map(event.x, boardBoundaries.x1, boardBoundaries.x2, 0, gridSize)) + const j = Math.round(map(event.y, boardBoundaries.y1, boardBoundaries.y2, 0, gridSize)) + + console.log("Clicked at ", i, j) + + // TODO + //gameOfLife.cells[j][i] = + } +} + // ############################## // ## MAIN RENDERING FUNCTIONS ## // ############################## @@ -125,20 +256,43 @@ function resize () { camera.aspect = (width / height) camera.updateProjectionMatrix() renderer.setSize(width, height) + + calculateBoardCornerScreenCoordinates() } } // Update the geometry every frame -function update () { +// dt - time in seconds since last frame +function update (dt) { resize() - mesh1.rotation.x += 0.01 - mesh1.rotation.y += 0.01 + // Rotate all meshes + for (let j = 0; j < gridSize; j++) { + for (let i = 0; i < gridSize; i++) { + const mesh = meshes[j][i] + mesh.rotation.x += (gameOfLife.rotSpeed * dt) + mesh.rotation.y += (gameOfLife.rotSpeed * dt) + } + } } +// Get the timestamp from the previous frame to ensure consistent times even with different framerates +// CODE TAKEN FROM: +// https://codeincomplete.com/posts/javascript-game-foundations-the-game-loop/ +function timestamp () { + return window.performance && window.performance.now ? window.performance.now() : new Date().getTime() +} +let now, dt +let last = timestamp() + // MAIN render function. This is what should requestAnimationFrame function render () { - update() + now = timestamp() + dt = (now - last) / 1000 // to get time in seconds + if (dt > 1 / 20) dt = (1 / 20) // will slow down time if framerate dips below 20fps + last = now + + update(dt) renderer.render(scene, camera) window.requestAnimationFrame(render) } diff --git a/public/style.css b/public/style.css index ddf571308..d7a6d9826 100644 --- a/public/style.css +++ b/public/style.css @@ -3,6 +3,9 @@ * by Terry Hearst */ + +/* -- CANVAS STYLING -- */ + html { height: 100%; box-sizing: border-box; @@ -13,6 +16,7 @@ html { } body { + font-family: monospace; margin: 0; height: 100%; } @@ -28,3 +32,42 @@ canvas { width: 100%; height: 100%; } + + +/* -- POPUP STYLING -- */ +/* Mostly taken from: */ +/* https://www.w3schools.com/howto/howto_js_popup.asp */ + +.popup { + position: absolute; + display: inline-block; +} + +.popup .popup-text { + visibility: hidden; + width: 400px; + background-color: #555; + color: #fff; + text-align: center; + border-radius: 6px; + padding: 8px; + position: absolute; + z-index: 1; + top: 100px; + left: 100px; +} + +.popup .popuptext::after { + content: ""; + position: relative; + top: 100%; + left: 50%; + margin-left: -5px; + border-width: 5px; + border-style: solid; + border-color: #555 transparent transparent transparent; +} + +.popup .show { + visibility: visible; +} diff --git a/views/index.html b/views/index.html index 5348539b8..da7b627d2 100644 --- a/views/index.html +++ b/views/index.html @@ -4,14 +4,6 @@ CS 4241 Assignment 4 - - - - - - - - @@ -20,12 +12,26 @@ -
      - + +
      From f19499822824973f886d401dbbe4cfb426f95c5d Mon Sep 17 00:00:00 2001 From: Terry Hearst Date: Fri, 27 Sep 2019 23:07:57 -0400 Subject: [PATCH 08/10] Project completed --- public/client.js | 113 +++++++++++++++++++++++++++++++------------ public/gameoflife.js | 86 ++++++++++++++++++++++++++++++++ 2 files changed, 169 insertions(+), 30 deletions(-) create mode 100644 public/gameoflife.js diff --git a/public/client.js b/public/client.js index 4c6f0e964..498e01658 100644 --- a/public/client.js +++ b/public/client.js @@ -5,12 +5,13 @@ const THREE = require('three') const dat = require('dat.gui') +const golBoard = require('./gameoflife.js') // ######################## // ## SETUP GAME OF LIFE ## // ######################## -const gridSize = 10 +const gridSize = 20 function showHelp () { const popup = document.getElementById('help-popup') @@ -23,6 +24,13 @@ const GameOfLifeClass = function () { this.rotSpeed = 0.6 this.editMode = false this.showHelp = showHelp + this.singleStep = function () { + golBoard.runIteration() + this.changed = true + } + + golBoard.setupBoard(gridSize) + this.changed = true } const gameOfLife = new GameOfLifeClass() @@ -35,6 +43,7 @@ window.onload = function () { const gui = new dat.GUI() gui.add(gameOfLife, 'running').name('Running') + gui.add(gameOfLife, 'singleStep').name('Single Step') gui.add(gameOfLife, 'speed', 1, 20).name('Iterations/Sec').step(1) gui.add(gameOfLife, 'rotSpeed', 0, 5).name('Rotation Speed') gui.add(gameOfLife, 'editMode').name('Edit Mode') @@ -166,7 +175,7 @@ scene.add(gridHelper) // Make mesh for the object that will assist you in edit mode const s = 3 / (gridSize / 2) const editGeo = new THREE.CubeGeometry(s, s, s) -const editMat = new THREE.MeshBasicMaterial({color: 0xFFFFFF, transparent: true, opacity: 0.3}) +const editMat = new THREE.MeshBasicMaterial({ color: 0xFFFFFF, transparent: true, opacity: 0.3 }) const editMesh = new THREE.Mesh(editGeo, editMat) scene.add(editMesh) @@ -184,18 +193,18 @@ scene.add(editMesh) * me positions of +/- infinity for both x and y. So I use this janky method that WILL WORK assuming that you don't * change the camera's position. Whatever. */ -const boardBoundaries = {x1: 0, y1: 0, x2: 0, y2: 0} +const boardBoundaries = { x1: 0, y1: 0, x2: 0, y2: 0 } function calculateBoardCornerScreenCoordinates () { // uhh yeah, I just measured these... // they work in all resolutions I promise... at least they're close enough - - const top = map(138, 0, 1287, 0, canvas.clientHeight) + + const top = map(140, 0, 1287, 0, canvas.clientHeight) const distFromCenter = (canvas.clientHeight / 2) - top - - boardBoundaries.x1 = Math.round((canvas.clientWidth / 2) - distFromCenter) + + boardBoundaries.x1 = Math.round((canvas.clientWidth / 2) - distFromCenter) boardBoundaries.y1 = Math.round((canvas.clientHeight / 2) - distFromCenter) - boardBoundaries.x2 = Math.round((canvas.clientWidth / 2) + distFromCenter) + boardBoundaries.x2 = Math.round((canvas.clientWidth / 2) + distFromCenter) boardBoundaries.y2 = Math.round((canvas.clientHeight / 2) + distFromCenter) console.log('New board screen coordinates:') @@ -209,32 +218,35 @@ calculateBoardCornerScreenCoordinates() window.onmousemove = function (event) { if (gameOfLife.editMode) { - editMat.opacity = 0.3 - - const i = Math.round(map(event.x, boardBoundaries.x1, boardBoundaries.x2, 0, gridSize)) - const j = Math.round(map(event.y, boardBoundaries.y1, boardBoundaries.y2, 0, gridSize)) - - //console.log(i, j) - - const cellPosition = calcCellPosition(i, j) - - editMesh.position.x = cellPosition.x - editMesh.position.y = cellPosition.y + const i = Math.floor(map(event.x, boardBoundaries.x1, boardBoundaries.x2, 0, gridSize)) + const j = Math.floor(map(event.y, boardBoundaries.y1, boardBoundaries.y2, 0, gridSize)) + + // console.log(i, j) + + if (i >= 0 && i < gridSize && j >= 0 && j < gridSize) { + const cellPosition = calcCellPosition(i, j) + editMat.opacity = 0.3 + + editMesh.position.x = cellPosition.x + editMesh.position.y = cellPosition.y + } else { + editMat.opacity = 0 + } } else { editMat.opacity = 0 } } -window.onmouseclick = function (event) { - if (gameOfLife.editMode) { - - const i = Math.round(map(event.x, boardBoundaries.x1, boardBoundaries.x2, 0, gridSize)) - const j = Math.round(map(event.y, boardBoundaries.y1, boardBoundaries.y2, 0, gridSize)) - - console.log("Clicked at ", i, j) - - // TODO - //gameOfLife.cells[j][i] = +window.onmousedown = function (event) { + if (gameOfLife.editMode) { + const i = Math.floor(map(event.x, boardBoundaries.x1, boardBoundaries.x2, 0, gridSize)) + const j = Math.floor(map(event.y, boardBoundaries.y1, boardBoundaries.y2, 0, gridSize)) + + if (i >= 0 && i < gridSize && j >= 0 && j < gridSize) { + console.log('Clicked at ', i, j) + golBoard.toggleCell(i, j) + gameOfLife.changed = true + } } } @@ -256,16 +268,57 @@ function resize () { camera.aspect = (width / height) camera.updateProjectionMatrix() renderer.setSize(width, height) - + calculateBoardCornerScreenCoordinates() } } // Update the geometry every frame // dt - time in seconds since last frame +let elapsed = 0 + function update (dt) { resize() + if (gameOfLife.running) { + elapsed += dt + // console.log(elapsed) + } + + if (elapsed >= (1 / gameOfLife.speed)) { + gameOfLife.changed = true + elapsed -= (1 / gameOfLife.speed) + golBoard.runIteration() + } + + // Set each mesh's properties + if (gameOfLife.changed) { + gameOfLife.changed = false + for (let j = 0; j < gridSize; j++) { + for (let i = 0; i < gridSize; i++) { + const mesh = meshes[j][i] + const cell = golBoard.getCell(i, j) + if (cell.alive) { + if (cell.count < 5) { + mesh.geometry = geos[1] + mesh.material = mats[0] + } else if (cell.count < 8) { + mesh.geometry = geos[2] + mesh.material = mats[1] + } else if (cell.count < 11) { + mesh.geometry = geos[3] + mesh.material = mats[2] + } else /* if (cell.count < 16) */ { + mesh.geometry = geos[4] + mesh.material = mats[3] + } + } else { + mesh.geometry = geos[0] + } + } + } + } + // Rotate all meshes for (let j = 0; j < gridSize; j++) { for (let i = 0; i < gridSize; i++) { diff --git a/public/gameoflife.js b/public/gameoflife.js new file mode 100644 index 000000000..b26deedab --- /dev/null +++ b/public/gameoflife.js @@ -0,0 +1,86 @@ +/* + * Implementation of Conway's Game of Life + * by Terry Hearst + */ + +let gridSize +let board + +// HELPER: returns the number of neighbors of a cell +function getNeighbors (i, j) { + let neighbors = 0 + for (let jj = j - 1; jj < j + 2; jj++) { + for (let ii = i - 1; ii < i + 2; ii++) { + if (ii >= 0 && ii < gridSize && jj >= 0 && jj < gridSize && !(ii === i && jj === j)) { + neighbors += board[jj][ii].alive ? 1 : 0 + } + } + } + return neighbors +} + +// Actual functions exposed by module +module.exports = { + setupBoard: function (_gridSize) { + gridSize = _gridSize + board = [] + for (let j = 0; j < gridSize; j++) { + board[j] = [] + for (let i = 0; i < gridSize; i++) { + const cell = { alive: false, count: 0 } + board[j][i] = cell + } + } + }, + + getCell: function (i, j) { + return board[j][i] + }, + + setCell: function (i, j, alive, count) { + const cell = board[j][i] + cell.alive = alive + if (count !== undefined) { + cell.count = count + } + }, + + toggleCell: function (i, j) { + const cell = board[j][i] + cell.count = 0 + if (cell.alive) { + cell.alive = false + } else { + cell.alive = true + } + }, + + runIteration: function () { + const newBoard = [] + for (let j = 0; j < gridSize; j++) { + newBoard[j] = [] + for (let i = 0; i < gridSize; i++) { + let newCell + const neighbors = getNeighbors(i, j) + if (board[j][i].alive) { + if (neighbors < 2 || neighbors > 3) { + newCell = { alive: false, count: 0 } + } else { + newCell = { alive: true, count: board[j][i].count + 1 } + } + } else { + if (neighbors === 3) { + newCell = { alive: true, count: 1 } + } else { + newCell = { alive: false, count: 0 } + } + } + newBoard[j][i] = newCell + } + } + + board = newBoard + }, + + getNeighbors: getNeighbors +} From 42499ab88d21a0c7154e04fff38b9c6d846b70ca Mon Sep 17 00:00:00 2001 From: Terry Hearst Date: Sat, 28 Sep 2019 04:00:14 +0000 Subject: [PATCH 09/10] Final touches --- .standard-v14-cache/.cache_1avryc9 | 1 + README.md | 72 +++++------------------------- package.json | 2 + public/client.js | 21 ++++----- public/gameoflife.js | 32 ++++++------- public/mydat.js | 25 +++++++++++ public/style.css | 4 ++ views/index.html | 5 +-- 8 files changed, 70 insertions(+), 92 deletions(-) create mode 100644 .standard-v14-cache/.cache_1avryc9 create mode 100644 public/mydat.js diff --git a/.standard-v14-cache/.cache_1avryc9 b/.standard-v14-cache/.cache_1avryc9 new file mode 100644 index 000000000..7ff5085f3 --- /dev/null +++ b/.standard-v14-cache/.cache_1avryc9 @@ -0,0 +1 @@ +[{"/app/public/client.js":"1","/app/public/gameoflife.js":"2","/app/server.js":"3"},{"size":10825,"mtime":1569642173000,"results":"4","hashOfConfig":"5"},{"size":2061,"mtime":1569642173000,"results":"6","hashOfConfig":"5"},{"size":765,"mtime":1569640137000,"results":"7","hashOfConfig":"5"},{"filePath":"8","messages":"9","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"1h9vp9t",{"filePath":"10","messages":"11","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"12","messages":"13","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"/app/public/client.js",[],"/app/public/gameoflife.js",[],"/app/server.js",[]] \ No newline at end of file diff --git a/README.md b/README.md index 7f170cdb2..ac28b1141 100644 --- a/README.md +++ b/README.md @@ -1,72 +1,20 @@ -Assignment 4 - Creative Coding: Interactive Multimedia Experiences +LifeGrid === -Due: September 27th, by 11:59 PM. +https://a4-thearst3rd.glitch.me/ -For this assignment we will focus on client-side development using popular audio/graphics/visualization technologies; the server requirements are minimal. The goal of this assignment is to refine our JavaScript knowledge while exploring the multimedia capabilities of the browser. +LifeGrid is an implementation of Conway's Game of Life using three.js to render each cell as an object. This object grows with complexity the longer the cell is alive, growing from a simple sphere to a complex torus knot. -Baseline Requirements ---- +Some challenges I faced: It took me a while to figure out how to go from 2D mouse coordinates to the 3D world coordinates into `(i, j)` coordinates. In fact, I am totally cheesing it based on numbers that _should_ be correct. I tested it out with multiple different window sizes though and it seems to work perfectly. -Your application is required to implement the following functionalities: +Figuring out how to line up all of the mesh elements on the grid took a some time. Eventually I got it, but figuring out the equations and making them all work properly was challenging, because sometimes I would mess it up and all of the elements would be totally off screen and I could not see them at all. -- A server created using Express (you can also use an alternative server framework such as Koa) for basic file delivery and middleware. Your middleware stack should include the `compression` and `helmet` [middlewares]((https://expressjs.com/en/resources/middleware.html)) by default. You are not required to use Glitch for this assignment (but using Glitch is fine!); [Heroku](https://www.heroku.com) is another excellent option to explore. The course staff can't be resposible for helping with all other hosting options outside of Glitch, but some of us do have experience with other systems. It also never hurts to ask on Slack, as there's 99 other classmates who might have the experience you're looking for! -- A client-side interactive experience using at least one of the web technologies frameworks we discussed in class over the past week. - - [Three.js](https://threejs.org/): A library for 3D graphics / VR experiences - - [D3.js](https://d3js.org): A library that is primarily used for interactive data visualizations - - [Canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API): A 2D raster drawing API included in all modern browsers - - [SVG](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API): A 2D vector drawing framework that enables shapes to be defined via XML. - - [Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API): An API for audio synthesis, analysis, processing, and file playback. -- A user interface for interaction with your project, which must expose at least six parameters for user control. [dat.gui](https://workshop.chromeexperiments.com/examples/gui/#1--Basic-Usage) is highly recommended for this. You might also explore interaction by tracking mouse movement via the `window.onmousemove` event handler in tandem with the `event.clientX` and `event.clientY` properties. Consider using the [Pointer Events API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events) to ensure that that mouse and touch events will both be supported in your app. -- Your application should display basic documentation for the user interface when the application first loads. This documentation should be dismissable, however, users should be able to redisplay it via either a help buton (this could, for example, be inside a dat.gui interface) or via a keyboard shortcut (commonly the question mark). -- Your application should feature at least two different ES6 modules that you write ([read about ES6 modules](https://www.sitepoint.com/understanding-es6-modules/)) and include into a main JavaScript file. This means that you will need to author *at least three JavaScript files* (a `app.js` or `main.js` file and two modules). We'll discuss modules in class on Monday 9/23; for this assignment modules should contain at least two functions. -- You are required to use a linter for your JavaScript. There are plugins for most IDEs, however it will be difficult to run the linter directly in Glitch. If you haven't moved to developing on your personal laptop and then uploading to Glitch when your project is completed, this is the assignment to do so! -- Your HTML and CSS should validate. There are options/plugins for most IDEs to check validation. - -The interactive experience should possess a reasonable level of complexity. Some examples: -### Three.js -- A generative algorithm creates simple agents that move through a virtual world. Your interface controls the behavior / appearance of these agents. -- A simple 3D game -- An 3D audio visualization of a song of your choosing. User interaction should control aspects of the visualization. -### Canvas -- Implement a generative algorithm such as [Conway's Game of Life](https://bitstorm.org/gameoflife/) (or 1D cellular automata) and provide interactive controls. Note that the Game of Life has been created by 100s of people using ; we'll be checking to ensure that your implementation is not a copy of these. -- Design a 2D audio visualizer of a song of your choosing. User interaction should control visual aspects of the experience. -### Web Audio API -- Create a screen-based musical instrument using the Web Audio API. You can use projects such as [Interface.js](http://charlie-roberts.com/interface/) or [Nexus UI](https://nexus-js.github.io/ui/api/#Piano) to provide common musical interface elements, or use dat.GUI in combination with mouse/touch events (use the Pointer Events API). Your GUI should enable users to control aspects of sound synthesis. -### D3.js -- Create visualizations using the datasets found at [Awesome JSON Datasets](https://github.com/jdorfman/Awesome-JSON-Datasets). Experiment with providing different visualizations of the same data set, and providing users interactive control over visualization parameters and/or data filtering. Alternatively, create a single visualization with using one of the more complicated techniques shown at [d3js.org](d3js.org) and provide meaningful points of interaction for users. - -Deliverables ---- - -Do the following to complete this assignment: - -1. Implement your project with the above requirements. -3. Test your project to make sure that when someone goes to your main page on Glitch/Heroku/etc., it displays correctly. -4. Ensure that your project has the proper naming scheme `a4-yourname` so we can find it. -5. Fork this repository and modify the README to the specifications below. *NOTE: If you don't use Glitch for hosting (where we can see the files) then you must include all project files that you author in your repo for this assignment*. -6. Create and submit a Pull Request to the original repo. Name the pull request using the following template: `a4-gitname-firstname-lastname`. - -Sample Readme (delete the above when you're ready to submit, and modify the below so with your links and descriptions) ---- - -## Your Web Application Title - -your hosting link e.g. http://a4-charlieroberts.glitch.me - -Include a very brief summary of your project here. Images are encouraged, along with concise, high-level text. Be sure to include: - -- the goal of the application -- challenges you faced in realizing the application -- a brief description of the JS linter you used and what rules it follows (we'll be looking at your JS files for consistency) +I used `standard.js` for my linting. All of the javascript files are properly linted as of this submission. It follows a bunch of rules that I actually really do not prefer but it was easy to set up so whatever... ## Technical Achievements -- **Tech Achievement 1**: I wrote my own custom GLSL shaders to use as a material for my Three.js objects. -- **Tech Achievement 2**: My audiovisualizer uses both FFT and amplitude analysis to drive visualization. -- **Tech Achievement 3**: I optimized the efficiency of my reaction-diffusion algorithm by... -- **Tech Achievement 4**: I visualized the dataset X using three different visualization technqiues provided by D3, andprovided +- **Complete Implementation of Conway's Game of Life**: The game is fully, properly implemented. You can change the rules using a dat.GUI menu which allows for some interesting results. +- **Full board layout using three.js**: I create a small number of geometry and material objects, and then reuse those throughout the board for more efficient memory usage and faster performance. ### Design/Evaluation Achievements -- **Design Achievement 1**: I ensured that my application would run on both desktops / mobile devices by changing X -- **Design Achievement 2**: I followed best practices for accessibility, including providing alt attributes for images and using semantic HTML. There are no `
      ` or `` elements in my document. -- **Design Achievement 3**: We tested the application with n=X users, finding that... +- **Best Practices**: I followed best practices for accessibility, including providing alt attributes for images and using semantic HTML. There are no `
      ` or `` elements in my document. This one was actually quite annoying to do because a lot of the examples had full-screen canvases using a `div`. Also, with the popup element, the HTML validator gave me trouble if I kept them all as a `p` element and I needed to split them up into headers without using a `div` or `span`. +- **Different Models for Each Cell**: I gave different lifespans of each cell a new model and material, so that the board looks much more dynamic. You can observe how long a cell has been alive just by looking at the model and color. \ No newline at end of file diff --git a/package.json b/package.json index d19cb6933..2314fa961 100644 --- a/package.json +++ b/package.json @@ -10,10 +10,12 @@ "start": "node server.js" }, "dependencies": { + "browserify": "^16.5.0", "compression": "^1.7.4", "dat.gui": "^0.7.6", "express": "^4.16.4", "helmet": "^3.21.1", + "standard": "^14.3.1", "three": "^0.108.0" }, "engines": { diff --git a/public/client.js b/public/client.js index 498e01658..a743343ac 100644 --- a/public/client.js +++ b/public/client.js @@ -4,8 +4,10 @@ */ const THREE = require('three') -const dat = require('dat.gui') -const golBoard = require('./gameoflife.js') +const GameOfLifeModule = require('./gameoflife.js') +const MyDatModule = require('./mydat.js') + +const golBoard = new GameOfLifeModule() // ######################## // ## SETUP GAME OF LIFE ## @@ -14,8 +16,10 @@ const golBoard = require('./gameoflife.js') const gridSize = 20 function showHelp () { - const popup = document.getElementById('help-popup') - popup.classList.toggle('show') + const popups = document.getElementsByClassName('popup-text') + for (let i = 0; i < popups.length; i++) { + popups[i].classList.toggle('show') + } } const GameOfLifeClass = function () { @@ -40,14 +44,7 @@ const gameOfLife = new GameOfLifeClass() // ################### window.onload = function () { - const gui = new dat.GUI() - - gui.add(gameOfLife, 'running').name('Running') - gui.add(gameOfLife, 'singleStep').name('Single Step') - gui.add(gameOfLife, 'speed', 1, 20).name('Iterations/Sec').step(1) - gui.add(gameOfLife, 'rotSpeed', 0, 5).name('Rotation Speed') - gui.add(gameOfLife, 'editMode').name('Edit Mode') - gui.add(gameOfLife, 'showHelp').name('Toggle Help') + const myDat = new MyDatModule(gameOfLife, golBoard) // Show the help screen at the start showHelp() diff --git a/public/gameoflife.js b/public/gameoflife.js index b26deedab..622fd6d92 100644 --- a/public/gameoflife.js +++ b/public/gameoflife.js @@ -20,8 +20,12 @@ function getNeighbors (i, j) { } // Actual functions exposed by module -module.exports = { - setupBoard: function (_gridSize) { +module.exports = function () { + this.starvation = 2 + this.overpopulation = 3 + this.birth = 3 + + this.setupBoard = function (_gridSize) { gridSize = _gridSize board = [] for (let j = 0; j < gridSize; j++) { @@ -31,21 +35,21 @@ module.exports = { board[j][i] = cell } } - }, + } - getCell: function (i, j) { + this.getCell = function (i, j) { return board[j][i] - }, + } - setCell: function (i, j, alive, count) { + this.setCell = function (i, j, alive, count) { const cell = board[j][i] cell.alive = alive if (count !== undefined) { cell.count = count } - }, + } - toggleCell: function (i, j) { + this.toggleCell = function (i, j) { const cell = board[j][i] cell.count = 0 if (cell.alive) { @@ -53,9 +57,9 @@ module.exports = { } else { cell.alive = true } - }, + } - runIteration: function () { + this.runIteration = function () { const newBoard = [] for (let j = 0; j < gridSize; j++) { newBoard[j] = [] @@ -63,13 +67,13 @@ module.exports = { let newCell const neighbors = getNeighbors(i, j) if (board[j][i].alive) { - if (neighbors < 2 || neighbors > 3) { + if (neighbors < this.starvation || neighbors > this.overpopulation) { newCell = { alive: false, count: 0 } } else { newCell = { alive: true, count: board[j][i].count + 1 } } } else { - if (neighbors === 3) { + if (neighbors === this.birth) { newCell = { alive: true, count: 1 } } else { newCell = { alive: false, count: 0 } @@ -80,7 +84,5 @@ module.exports = { } board = newBoard - }, - - getNeighbors: getNeighbors + } } diff --git a/public/mydat.js b/public/mydat.js new file mode 100644 index 000000000..6ff61e1a0 --- /dev/null +++ b/public/mydat.js @@ -0,0 +1,25 @@ +/* + * Module to set up my dat.GUI + * by Terry Hearst + */ + +const dat = require('dat.gui') + +module.exports = function (gameOfLife, golBoard) { + const gui = new dat.GUI() + + const f1 = gui.addFolder('Main') + f1.add(gameOfLife, 'running').name('Running') + f1.add(gameOfLife, 'singleStep').name('Single Step') + f1.add(gameOfLife, 'speed', 1, 20).name('Iterations/Sec').step(1) + f1.add(gameOfLife, 'rotSpeed', 0, 5).name('Rotation Speed') + f1.add(gameOfLife, 'editMode').name('Edit Mode') + f1.add(gameOfLife, 'showHelp').name('Toggle Help') + + // f1.open() + + const f2 = gui.addFolder('Change the Rules') + f2.add(golBoard, 'starvation', 0, 8).step(1) + f2.add(golBoard, 'overpopulation', 0, 8).step(1) + f2.add(golBoard, 'birth', 0, 8).step(1) +} \ No newline at end of file diff --git a/public/style.css b/public/style.css index d7a6d9826..81f357e0d 100644 --- a/public/style.css +++ b/public/style.css @@ -57,6 +57,10 @@ canvas { left: 100px; } +#popup-text-paragraph { + top: 150px; +} + .popup .popuptext::after { content: ""; position: relative; diff --git a/views/index.html b/views/index.html index da7b627d2..cdcdd0ac6 100644 --- a/views/index.html +++ b/views/index.html @@ -13,9 +13,8 @@