diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..5171c540 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules +npm-debug.log \ No newline at end of file diff --git a/README.md b/README.md index 40864757..5c526558 100644 --- a/README.md +++ b/README.md @@ -1,40 +1,5 @@ -# BioCrowds -Biocrowds is a crowd simulation algorithm based on the formation of veination patterns on leaves. It prevents agents from colliding with each other on their way to their goal points using a notion of "personal space". Personal space is modelled with a space colonization algorithm. Markers (just points) are scattered throughout the simulation space, on the ground. At each simulation frame, each marker becomes "owned" by the agent closest to it (with some max distance representing an agent's perception). Agent velocity at the next frame is then computed using a sum of the displacement vectors to each of its markers. Because a marker can only be owned by one agent at a time, this technique prevents agents from colliding. +# Bio crowds -## Agent Representation (15 pts) -Create an agent class to hold properties used for simulating and drawing the agent. Some properties you may want to consider include the following: -- Position -- Velocity -- Goal -- Orientation -- Size -- Markers +A small implementation of the biocrowds algorithm. It currently supports obstacle maps, where pixels are considered weights for each marker. It currently runs with 750 agents and around 64k markers. -## Grid/Marker Representation (25 pts) -Markers should be scattered randomly across a uniform grid. You should implement an efficient way of determining the nearest agent to a given marker. Based on an marker's location, you should be able to get the nearest four grid cells and loop through all the agents contained in them. - -## Setup (10 pts) -- Create a scene (standard, with camera controls) and scatter markers across the entire ground plane -- Spawn agents with specified goal points - -## Per Frame (35 pts) -- Assign markers to the nearest agent within a given radius. Be sure that a marker is only assigned to a single, unique agent. -- Compute velocity for each agent -- New velocity is determined by summing contributions from all the markers the agent "owns". Each marker contribution consists of the displacement vector between the agent and the marker multiplied by some (non-negative) weight. The weighting is based on - - Similarity between the displacement vector and the vector to agent's goal (the more similar, the higher the weight. A dot product works well) - - Distance from agent (the further away, the less contribution) -Each contribution is normalized by the total marker contributions (divide each contribution by sum total) - - Clamp velocity to some maximum (you probably want to choose a max speed such that you agent will never move further than its marker radius) -- Move agents by their newly computed velocity * time step -- Draw a ground plane and cylinders to represent the agents. -- For a more thorough explanation, see [HERE](http://www.inf.pucrs.br/~smusse/Animacao/2016/CrowdTalk.pdf) and [HERE](http://www.sciencedirect.com/science/article/pii/S0097849311001713) and [HERE](https://books.google.com/books?id=3Adh_2ZNGLAC&pg=PA146&lpg=PA146&dq=biocrowds%20algorithm&source=bl&ots=zsM86iYTot&sig=KQJU7_NagMK4rbpY0oYc3bwCh9o&hl=en&sa=X&ved=0ahUKEwik9JfPnubSAhXIxVQKHUybCxUQ6AEILzAE#v=onepage&q=biocrowds%20algorithm&f=false) and [HERE](https://cis700-procedural-graphics.github.io/files/biocrowds_3_21_17.pdf) - -## Two scenarios -- Create two different scenarios (initial agent placement, goals) to show off the collision avoidance. Try to pick something interesting! Classics include two opposing lines of agents with goals on opposite sides, or agents that spawn in a circle, which each agent's goal directly across. -- Provide some way to switch between scenarios - -## Deploy your code! (5 pts) -- Your demo should run on your gh-pages branch - -## Extra credit -- Add obstacles to your scene, such that agents avoid them \ No newline at end of file +Because one of the problems with this algorithm is its inability to plan ahead of obstacles, the target moves so agents have the chance to get out of local minima. \ No newline at end of file diff --git a/deploy.js b/deploy.js new file mode 100644 index 00000000..9defe7c3 --- /dev/null +++ b/deploy.js @@ -0,0 +1,38 @@ +var colors = require('colors'); +var path = require('path'); +var git = require('simple-git')(__dirname); +var deploy = require('gh-pages-deploy'); +var packageJSON = require('require-module')('./package.json'); + +var success = 1; +git.fetch('origin', 'master', function(err) { + if (err) throw err; + git.status(function(err, status) { + if (err) throw err; + if (!status.isClean()) { + success = 0; + console.error('Error: You have uncommitted changes! Please commit them first'.red); + } + + if (status.current !== 'master') { + success = 0; + console.warn('Warning: Please deploy from the master branch!'.yellow) + } + + git.diffSummary(['origin/master'], function(err, diff) { + if (err) throw err; + + if (diff.files.length || diff.insertions || diff.deletions) { + success = 0; + console.error('Error: Current branch is different from origin/master! Please push all changes first'.red) + } + + if (success) { + var cfg = packageJSON['gh-pages-deploy'] || {}; + var buildCmd = deploy.getFullCmd(cfg); + deploy.displayCmds(deploy.getFullCmd(cfg)); + deploy.execBuild(buildCmd, cfg); + } + }) + }) +}) \ No newline at end of file diff --git a/images/map1.png b/images/map1.png new file mode 100644 index 00000000..3898415b Binary files /dev/null and b/images/map1.png differ diff --git a/images/map2.png b/images/map2.png new file mode 100644 index 00000000..8d4345a0 Binary files /dev/null and b/images/map2.png differ diff --git a/images/map3.png b/images/map3.png new file mode 100644 index 00000000..ee5aa4e7 Binary files /dev/null and b/images/map3.png differ diff --git a/index.html b/index.html new file mode 100644 index 00000000..3f747ad2 --- /dev/null +++ b/index.html @@ -0,0 +1,19 @@ + + + + Biocrowds + + + + + + diff --git a/package.json b/package.json new file mode 100644 index 00000000..be683fcb --- /dev/null +++ b/package.json @@ -0,0 +1,31 @@ +{ + "scripts": { + "start": "webpack-dev-server --hot --inline", + "build": "webpack", + "deploy": "node deploy.js" + }, + "gh-pages-deploy": { + "prep": [ + "build" + ], + "noprompt": true + }, + "dependencies": { + "dat-gui": "^0.5.0", + "gl-matrix": "^2.3.2", + "stats-js": "^1.0.0-alpha1", + "three": "^0.82.1", + "three-orbit-controls": "^82.1.0" + }, + "devDependencies": { + "babel-core": "^6.18.2", + "babel-loader": "^6.2.8", + "babel-preset-es2015": "^6.18.0", + "colors": "^1.1.2", + "gh-pages-deploy": "^0.4.2", + "simple-git": "^1.65.0", + "webpack": "^1.13.3", + "webpack-dev-server": "^1.16.2", + "webpack-glsl-loader": "^1.0.1" + } +} diff --git a/src/framework.js b/src/framework.js new file mode 100644 index 00000000..5841832a --- /dev/null +++ b/src/framework.js @@ -0,0 +1,76 @@ + +const THREE = require('three'); +const OrbitControls = require('three-orbit-controls')(THREE) + +import Stats from 'stats-js' +import DAT from 'dat-gui' + +// when the scene is done initializing, the function passed as `callback` will be executed +// then, every frame, the function passed as `update` will be executed +function init(callback, update) { + var stats = new Stats(); + stats.setMode(1); + stats.domElement.style.position = 'absolute'; + stats.domElement.style.left = '0px'; + stats.domElement.style.top = '0px'; + document.body.appendChild(stats.domElement); + + var gui = new DAT.GUI(); + + var framework = { + gui: gui, + stats: stats + }; + + // run this function after the window loads + window.addEventListener('load', function() { + + var scene = new THREE.Scene(); + var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 ); + var renderer = new THREE.WebGLRenderer( { antialias: true } ); + renderer.setPixelRatio(window.devicePixelRatio); + renderer.setSize(window.innerWidth, window.innerHeight); + renderer.setClearColor(0x020202, 0); + + var controls = new OrbitControls(camera, renderer.domElement); + controls.enableDamping = true; + controls.enableZoom = true; + controls.target.set(0, 0, 0); + controls.rotateSpeed = 0.3; + controls.zoomSpeed = 1.0; + controls.panSpeed = 2.0; + + document.body.appendChild(renderer.domElement); + + // resize the canvas when the window changes + window.addEventListener('resize', function() { + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + renderer.setSize(window.innerWidth, window.innerHeight); + }); + + // assign THREE.js objects to the object we will return + framework.scene = scene; + framework.camera = camera; + framework.renderer = renderer; + + // begin the animation loop + (function tick() { + stats.begin(); + update(framework); // perform any requested updates + renderer.render(scene, camera); // render the scene + stats.end(); + requestAnimationFrame(tick); // register to call this again when the browser renders a new frame + })(); + + // we will pass the scene, gui, renderer, camera, etc... to the callback function + return callback(framework); + }); +} + +export default { + init: init +} + +export const PI = 3.14159265 +export const e = 2.7181718 \ No newline at end of file diff --git a/src/main.js b/src/main.js new file mode 100644 index 00000000..a3c25bad --- /dev/null +++ b/src/main.js @@ -0,0 +1,464 @@ +const THREE = require('three'); +const Random = require("random-js"); +const Ease = require("ease-component") + +import Framework from './framework' + +class Engine +{ + constructor(density, gridSize, agentCount, texture, texturePixels) + { + this.map = new Map(density, gridSize, texture, texturePixels); + this.time = 0.0; + this.clock = new THREE.Clock(); + this.agentCount = agentCount; + this.target = new THREE.Vector2(); + this.movingTarget = true; + this.targetMesh = null; + this.container = new THREE.Object3D(); + + } + + initialize(scene) + { + var target = new THREE.Vector2( this.map.width, this.map.height ); + this.map.initializeAgents(this.agentCount, this.container, target); + this.initializeScene(this.container); + this.container.position.set(-this.map.width * .5, 0, -this.map.height*.5); + scene.add(this.container); + } + + initializeScene(scene) + { + var pointsGeometry = new THREE.Geometry(); + var markersMaterial = new THREE.PointsMaterial( { color: 0x00ee00 } ) + markersMaterial.size = .1; + markersMaterial.vertexColors = true; + var markers = this.map.markers; + + for(var m = 0; m < markers.length; m += 3) + { + var x = markers[m]; + var y = markers[m + 1]; + var w = markers[m + 2]; + pointsGeometry.vertices.push(new THREE.Vector3( x, 0, y )); + pointsGeometry.colors.push(new THREE.Color(w,w,w)); + } + + var markerPoints = new THREE.Points( pointsGeometry, markersMaterial ); + scene.add( markerPoints ); + + var lineGeo = new THREE.Geometry(); + + for(var x = 0; x <= this.map.width; x++) + { + lineGeo.vertices.push(new THREE.Vector3( x, 0, 0 )); + lineGeo.vertices.push(new THREE.Vector3( x, 0, this.map.height )); + } + + for(var x = 0; x <= this.map.width; x++) + { + lineGeo.vertices.push(new THREE.Vector3( 0, 0, x )); + lineGeo.vertices.push(new THREE.Vector3( this.map.width, 0, x )); + } + + var lineMaterial = new THREE.LineBasicMaterial({ color: 0x444444 }); + lineMaterial.linewidth = 2; + var lineMesh = new THREE.LineSegments(lineGeo, lineMaterial); + scene.add(lineMesh); + + var targetCylinder = new THREE.CylinderBufferGeometry( .5, .5, .1, 16 ); + var targetMaterial = new THREE.MeshBasicMaterial( { color: 0xff00ff } ); + this.targetMesh = new THREE.Mesh( targetCylinder, targetMaterial ); + scene.add( this.targetMesh ); + } + + update() + { + if(this.movingTarget) + { + this.target.x = Math.cos(this.time * .1) * this.map.width * .5 + this.map.width * .5; + this.target.y = Math.sin(this.time * .1) * this.map.height * .5 + this.map.height * .5; + + if(this.targetMesh != null) + this.targetMesh.position.set(this.target.x, 0, this.target.y); + } + + var deltaTime = Math.min(this.clock.getDelta(), 1.0 / 30.0); + this.time += deltaTime; + this.map.update(deltaTime, this.target) + } +} + +class Map +{ + constructor(density, gridSize, texture, texturePixels) + { + this.density = density; + this.grid = [] + this.width = gridSize; + this.height = gridSize; + this.agents = []; // The raw array + this.generator = Random.engines.mt19937(); + this.markers = new Float32Array(this.density * this.width * this.height * 3); + + this.texture = texture; + this.texturePixels = texturePixels; + + for(var i = 0; i < this.width * this.height; i++) + this.grid.push(new Array()); + + this.initializeMarkers(); + } + + initializeAgents(agentCount, scene, target) + { + var cylinder = new THREE.CylinderBufferGeometry( .075, .075, .05, 8 ); + var material = new THREE.MeshBasicMaterial( { color: 0xff0000 } ); + + var r = new Random(this.generator); + + for(var i = 0; i < agentCount; i++) + { + var mesh = new THREE.Mesh( cylinder, material ); + scene.add( mesh ); + + var pos = new THREE.Vector2( i * this.width / agentCount, .5 + r.real(-.2, .2)); + var agent = new Agent(.1, mesh, pos, target); + this.addAgent(agent); + } + } + + addAgent(agent) + { + this.agents.push(agent); + + var currentIndex = this.getCellIndex(agent.position); + + if(currentIndex != -1) + { + this.grid[currentIndex].push(agent); + agent.currentCellIndex = currentIndex; + } + } + + getCellIndex(position) + { + var x = Math.floor(position.x); + var y = Math.floor(position.y); + + var index = y * this.width + x; + + if(x >= 0 && x < this.width && y >= 0 && y < this.height) + return index; + + return -1; + } + + update(deltaTime, target) + { + // Update our agent data structure + for(var a = 0; a < this.agents.length; a++) + this.agents[a].cleanMarkerContribution(); + + this.updateMarkers(); + + // Update our agent data structure + for(var a = 0; a < this.agents.length; a++) + { + var agent = this.agents[a]; + agent.target = target; + + if(agent.isValid()) + agent.update(deltaTime); + + var currentIndex = this.getCellIndex(agent.position); + + if(agent.currentCellIndex != currentIndex) + { + if(agent.currentCellIndex != -1) + { + var agentIndex = this.grid[agent.currentCellIndex].indexOf(agent); + this.grid[agent.currentCellIndex].splice(agentIndex, 1); + } + + if(currentIndex != -1) + this.grid[currentIndex].push(agent); + + // console.log("Moved from " + agent.currentCellIndex + " to " + currentIndex); + agent.currentCellIndex = currentIndex; + + } + } + } + + // Initially, these were evaluated in runtime, but + // when the user wants high density markers it becomes very inefficient + initializeMarkers() + { + for(var x = 0; x < this.width; x++) + { + for(var y = 0; y < this.height; y++) + { + var seed = y * this.width + x; + this.generator.seed(seed); + + var r = new Random(this.generator); + + var textureIndex = (y/this.height) * this.texture.image.height * this.texture.image.width + (x/this.width) * this.texture.image.width; + var pixel = this.texturePixels[textureIndex]; + + for(var s = 0; s < this.density; s++) + { + var u = r.real(0, 1, true); + var v = r.real(0, 1, true); + + var index = seed * this.density + s; + + this.markers[index * 3] = x + u; + this.markers[index * 3 + 1] = y + v; + this.markers[index * 3 + 2] = pixel; + } + } + } + } + + // TODO: Only iterate markers on occupied cells and adjacent... + updateMarkers() + { + var marker = new THREE.Vector2(); + var size = this.width * this.height * this.density; + + for(var m = 0; m < size; m++) + { + //if(this.markers[m*3+2] > .5) + { + marker.x = this.markers[m * 3]; + marker.y = this.markers[m * 3 + 1]; + var weight = this.markers[m * 3 + 2]; + var agent = this.getNearestAgent(marker); + + if(agent != null) + agent.assignMarker(marker, weight); + } + } + } + + getNearestAgent(position) + { + var minDistance = this.width * this.height; + var minAgent = null; + + // Average case is O(1), although if all the agents are in the same + // cell, it degenerates to O(n)... if we expect this, we can use a + // quad tree per cell + for(var x = -1; x <= 1; x++) + { + for(var y = -1; y <= 1; y++) + { + var cellX = Math.floor(position.x + x); + var cellY = Math.floor(position.y + y); + + if(cellX >= 0 && cellX < this.width && cellY >= 0 && cellY < this.height) + { + var index = cellY * this.width + cellX; + var cellAgents = this.grid[index]; + + for(var a = 0; a < cellAgents.length; a++) + { + var agent = cellAgents[a]; + + if(agent.isValid()) + { + var length = position.distanceTo(agent.position) - agent.radius; + + if(length < minDistance) + { + minDistance = length; + minAgent = agent; + } + } + } + } + } + } + + return minAgent; + } +} + +class Agent +{ + constructor(radius, mesh, startPosition, target, scene) + { + this.mesh = mesh; + this.position = startPosition.clone(); + this.maxSpeed = 5.0; + this.velocity = new THREE.Vector2(); + this.velocityTarget = new THREE.Vector2(); + this.target = target; + this.radius = radius; + this.currentContribution = new THREE.Vector2(); + this.currentCellIndex = -1; + + this.toTarget = startPosition.clone().sub(target); + this.toTarget.normalize(); + + // this.lineGeo = new THREE.Geometry(); + // this.lineMaterial = new THREE.LineBasicMaterial({ color: 0xffffff }); + // this.lineMesh = new THREE.Line(this.lineGeo, this.lineMaterial); + // this.mesh.add(this.lineMesh); + } + + isValid() + { + return this.currentCellIndex != -1; + } + + cleanMarkerContribution() + { + this.velocityTarget = new THREE.Vector2(); + // this.lineGeo = new THREE.Geometry(); + // this.lineMesh.geometry = this.lineGeo; + } + + assignMarker(markerPosition, markerWeight) + { + var toMarker = markerPosition.clone().sub(this.position); + var distance = toMarker.length() - this.radius; + + // We don't want contribution from inner markers, + // they will distort the velocity + if(distance < 0) + return; + + // this.lineGeo.vertices.push(new THREE.Vector3()); + // this.lineGeo.vertices.push(new THREE.Vector3(toMarker.x, 0, toMarker.y)); + + if(toMarker.length() > 0) + toMarker.normalize(); + + var weight = toMarker.dot(this.toTarget) * .5 + .5; + var distanceFalloff = Math.max(0.0, 1.0 - distance); + this.velocityTarget.add(toMarker.clone().multiplyScalar(markerWeight * weight * distanceFalloff * distanceFalloff)); + } + + update(deltaTime) + { + if(this.velocityTarget.length() < .1) + this.velocityTarget = new THREE.Vector2(); + + this.velocity.lerp(this.velocityTarget, .15); + + // Clamp velocity + var currentSpeed = this.velocity.length(); + currentSpeed = Math.min(currentSpeed, this.maxSpeed); + + if(this.velocity.length() > 0) + this.velocity.normalize(); + + this.velocity.multiplyScalar(currentSpeed); + + // Update position + this.position.add(this.velocity.clone().multiplyScalar(deltaTime)); + this.toTarget = this.target.clone().sub(this.position); + + if(this.toTarget.length() > 0) + this.toTarget.normalize(); + + this.mesh.position.set(this.position.x, 0, this.position.y); + this.mesh.material.color = !this.isValid() ? new THREE.Color(0xffff00) : new THREE.Color( 0xff0000 ); + } +} + +var engine = null; + +function getPixelFlat( imagedata, index ) +{ + var position = index * 4; + var data = imagedata.data; + return { r: data[ position ], g: data[ position + 1 ], b: data[ position + 2 ] }; +} + +function loadTexturePixels(texture) +{ + var canvas = document.createElement('canvas'); + canvas.width = texture.image.width; + canvas.height = texture.image.height; + + var context = canvas.getContext( '2d' ); + context.drawImage( texture.image, 0, 0 ); + + var data = context.getImageData( 0, 0, texture.image.width, texture.image.height ); + var pixels = new Float32Array(texture.image.width * texture.image.height); + + for(var i = 0; i < pixels.length; i++) + { + var pixel = getPixelFlat(data, i); + pixels[i] = pixel.r / 255; + } + + return pixels; +} + +var UserSettings = +{ + map : "Map1" +} + +function onLoad(framework) +{ + var scene = framework.scene; + var camera = framework.camera; + var renderer = framework.renderer; + var gui = framework.gui; + var stats = framework.stats; + + // Choose from accepted values + gui.add(UserSettings, 'map', [ 'Map1', 'Map2', 'Map3' ] ).onChange(function(value) { + + var path = 'images/map1.png'; + + if(value == 'Map2') + path = 'images/map2.png'; + else if(value == 'Map3') + path = 'images/map3.png'; + + var txLoader = new THREE.TextureLoader(); + txLoader.load(path, function(texture) { + + if(engine != null) + scene.remove(engine.container); + + var texturePixels = loadTexturePixels(texture); + engine = new Engine(16, 64, 750, texture, texturePixels); + engine.initialize(scene); + }); + }); + + var txLoader = new THREE.TextureLoader(); + txLoader.load('images/map2.png', function(texture) { + var texturePixels = loadTexturePixels(texture); + engine = new Engine(16, 64, 750, texture, texturePixels); + engine.initialize(scene); + }); + + // set camera position + camera.position.set(20, 20, 20); + camera.lookAt(new THREE.Vector3(0,0,0)); + camera.fov = 35; + camera.updateProjectionMatrix(); +} + +function onResize(framework) +{ +} + +// called on frame updates +function onUpdate(framework) +{ + if(engine != null) + engine.update(); +} + +Framework.init(onLoad, onUpdate, onResize); diff --git a/webpack.config.js b/webpack.config.js new file mode 100644 index 00000000..57dce485 --- /dev/null +++ b/webpack.config.js @@ -0,0 +1,28 @@ +const path = require('path'); + +module.exports = { + entry: path.join(__dirname, "src/main"), + output: { + filename: "./bundle.js" + }, + module: { + loaders: [ + { + test: /\.js$/, + exclude: /(node_modules|bower_components)/, + loader: 'babel', + query: { + presets: ['es2015'] + } + }, + { + test: /\.glsl$/, + loader: "webpack-glsl" + }, + ] + }, + devtool: 'source-map', + devServer: { + port: 7000 + } +} \ No newline at end of file