Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
npm-debug.log
Binary file added Images/BioCrowds_vimeoLink.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Images/MarkerInfluenceWeighting1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Images/MarkerInfluenceWeighting2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Images/eventualMovement.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Images/velocityCalculation.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
81 changes: 42 additions & 39 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,40 +1,43 @@
# 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.

## 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

## 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

[![](Images/BioCrowds_vimeoLink.png)](https://vimeo.com/231603963)

## Overview

BioCrowds is a space colonization algorithm for crowd simulation. This algorithm is 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".

## Algorithm overview
### Setup and defined behaviours

- Markers (just points) are scattered throughout the simulation space, on the ground.
- Agents can travel only over pre-defined viable paths that are demarcated by being littered with markers.
- Agents move in the space by owning a collection of markers in a radius around them. The markers help determine a vector toward the goal while avoiding obstacles.
- At each simulation frame, each marker becomes "owned" by the agent closest to it (with some max distance representing an agent's perception).

### Summary of steps

1) Distribute markers in a uniform stratified manner.
2) Create a uniform grid acceleration structure and place markers in each cell of the grid. Ensure that the grid cell size is equal to the agent search distance (this makes it possible to only search 9 grid cells while looking for markers to influence the agent).
3) Place agents on the grid structure.
4) At every step of the simulation for every agent find the grid cell it is currently inside and search that cell and the surounding 8 grid cells for markers.
5) Accumulate a list of markers for each agent.
6) Use the agents to determine a direction vector towards the goal.
7) Update position and velocity for the agents.

### Computing Velocities

Agent velocity at the next frame is then computed using an averaged 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 (a cell will own all of the markers it is hovering over and so no other agent can be over those markers plus some buffer distance).

![](Images/MarkerInfluenceWeighting1.png)
![](Images/MarkerInfluenceWeighting2.png)
![](Images/velocityCalculation.png)
![](Images/eventualMovement.png)

_pictures obtained from Austin Eng's brilliant ppt on the same topic, linked in the references section_

### Uniform Grid Acceleration

By placing markers in a uniform grid we can drastically reduce the number of markers the agent has to search through to find the markers that influence it. This spatial acceleration structure makes the demo run in real-time. This optimization also scales really well to larger and larger scenarios.

## References:
- https://cis700-procedural-graphics.github.io/files/biocrowds_3_21_17.pdf
38 changes: 38 additions & 0 deletions deploy.js
Original file line number Diff line number Diff line change
@@ -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);
}
})
})
})
71 changes: 71 additions & 0 deletions framework.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
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);
}, false);

// 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
}
19 changes: 19 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<head>
<title>BioCrowds</title>
<style>
html, body {
margin: 0;
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
32 changes: 32 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"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-obj-loader": "^1.0.2",
"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"
}
}
115 changes: 115 additions & 0 deletions src/agent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
const THREE = require('three')
var RAND = require('random-seed').create(Math.random());

var cylindergeo = new THREE.CylinderGeometry( 1, 2, 1 );
var totalWeight = 0;
var distToMarker = 0;
var distToGoal = 0;
var distToGoal1 = 0;
var totalVelocity = new THREE.Vector3(0,0,0);
var distBtwOldNewPos = 0;

export default class Agent
{
constructor(pos, vel, _goal, mat, _color) //, _orientation)
{
this.position = pos;
this.velocity = vel;
this.color = _color;
this.mesh = new THREE.Mesh( cylindergeo, mat );
this.goal = _goal;
this.markers = [];
this.oldposition = new THREE.Vector3(pos.x,pos.y,pos.z);
this.active = true;
this.drawn = false;
}

drawagent(scene)
{
this.mesh.scale.set( 0.15, 0.15, 0.15 );
this.mesh.position.set( this.position.x, this.position.y + 0.1, this.position.z );
scene.add(this.mesh);
this.drawn = true;
}

stopDrawingAgent(scene)
{
this.mesh.scale.set( 0.00001, 0.00001, 0.00001 );
this.drawn = false;
}

updateAgent(markernum)
{
var displacements = [];
var markerweights = [];
totalWeight = 0.0;

var temp_vector_to_goal = (new THREE.Vector3(0, 0, 0)).subVectors(this.goal, this.position);
temp_vector_to_goal.y = 0.0;
distToGoal = temp_vector_to_goal.length();
temp_vector_to_goal = temp_vector_to_goal.normalize();

if (distToGoal < 0.15)
{
this.active = false;
return;
}

// sum and record all weights
for(var i=0; i<this.markers.length; i++)
{
var temp_vector_to_marker = (new THREE.Vector3(0, 0, 0)).subVectors(this.markers[i].position, this.position);
temp_vector_to_marker.y = 0.0;
distToMarker = temp_vector_to_marker.length();
temp_vector_to_marker = temp_vector_to_marker.normalize();

var markerweight = (1.0 + temp_vector_to_marker.dot(temp_vector_to_goal))/(1 + distToMarker);

totalWeight += markerweight;
markerweights.push(markerweight);
displacements.push(temp_vector_to_marker);
}

totalVelocity.x =0;
totalVelocity.y =0;
totalVelocity.z =0;

var temp1_vector_to_goal = (new THREE.Vector3(0, 0, 0)).subVectors(this.goal, this.position);
temp1_vector_to_goal.y = 0.0;
distToGoal1 = temp1_vector_to_goal.length();

if (totalWeight == 0.0)
{
this.velocity = temp_vector_to_goal.multiplyScalar(0.05);
}
else
{
for(var i=0; i<markerweights.length; i++)
{
displacements[i].multiplyScalar(markerweights[i] / totalWeight);
totalVelocity.add(displacements[i]);
}

this.velocity = totalVelocity.multiplyScalar(0.2);
}

this.oldposition.x = this.position.x;
this.oldposition.x = this.position.y;
this.oldposition.x = this.position.z;

this.position.x = this.position.x + this.velocity.x;
this.position.z = this.position.z + this.velocity.z;

distBtwOldNewPos = this.oldposition.distanceTo(this.position);

if(distBtwOldNewPos < 1.0)
{
markernum=markernum+10;
markernum = markernum%250;
return;
}

this.mesh.scale.set(0.15, 0.15, 0.15);
this.mesh.position.set( this.position.x, this.position.y + 0.1, this.position.z );
}
}
Loading