20190516

stupid computer tricks

here’s an ecs simulation framework:

var ecs = {};
ecs._entity_counter = 0;
ecs.new_entity = function() { 
	ecs._entity_counter++;
	return ecs._entity_counter;
};
ecs.ComponentMap = function(ctor) { 
	this.entities = {};
	this.add = function(id) { 
		this.entities[id] = new ctor();
	};
	this.remove = function(id) { 
		delete this.entities[id];
	};
	this.get = function(id) { 
		return this.entities[id];
	};
};
ecs.component_intersect = function() { 
	var result = [];
	var ks = [];
	for(var i in arguments) { 
		var k = Object.keys(arguments[i].entities);
		ks.push(k);
	}
	result = ecs.intersection(ks);
	return result;
};
ecs.intersection = function() { 
	var result = [];
	var lists;
  	if(arguments.length === 1) {
		lists = arguments[0];
	} else {
		lists = arguments;
	}
	for(var i = 0; i < lists.length; i++) {
		var currentList = lists[i];
		for(var y = 0; y < currentList.length; y++) {
			var currentValue = currentList[y];
			if(result.indexOf(currentValue) === -1) {
				if(lists.filter(function(obj) { 
					return obj.indexOf(currentValue) == -1 
				}).length == 0) {
					result.push(currentValue);
				}
			}
		}
	}
	return result;
};

this expects the library user to implement systems_* methods, which mutate components in their ComponentMap objects.

app.system_updatePhysics = function(map) { 
	var entities = ecs.component_intersect(map.Positions,map.Velocities);
	for(var i in entities) { 
		var id = entities[i];
		var pos = map.Positions.get(id);
		var vel = map.Velocities.get(id);
		pos.x += vel.x;
		pos.y += vel.y;
	}
};

there are, clearly, flow control constructs that would make this nicer to work with.

Author: Mike Godfrey

tech in halifax ns

Leave a Reply

Your email address will not be published. Required fields are marked *