-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
50 lines (40 loc) · 1.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"use strict";
const parser = require('cellular-automata-rule-parser');
const moore = require('moore');
const vonNeumann = require('von-neumann');
const unconventionalNeighbours = require('unconventional-neighbours');
const generateGlsl = require('./lib/cellular-automata-voxel-shader-glsl');
const neighbourhoodFunctions = {
moore: moore,
'von-neumann': vonNeumann,
axis: unconventionalNeighbours.axis,
corner: unconventionalNeighbours.corner,
edge: unconventionalNeighbours.edge,
face: unconventionalNeighbours.face
};
/**
* Sort the neighbourhood from left to right, top to bottom, ...
* @param {Array} a First neighbour
* @param {Array} b Second neighbour
* @returns {number}
*/
function neighbourhoodSorter (a, b) {
a = a.join(',');
b = b.join(',');
return a > b ? 1 : a < b ? -1 : 0;
}
function getNeighbourhood (neighbourhoodType, neighbourhoodRange) {
neighbourhoodType = !!neighbourhoodFunctions[neighbourhoodType] ? neighbourhoodType : 'moore';
neighbourhoodRange = neighbourhoodRange || 1;
const neighbourhood = neighbourhoodFunctions[neighbourhoodType](neighbourhoodRange, 3);
neighbourhood.sort(neighbourhoodSorter);
return neighbourhood;
}
module.exports = function generate (ruleString, outOfBoundValue) {
const rule = parser(ruleString);
if (!rule) {
throw Error('Invalid ruleString : "' + ruleString + '"');
}
const neighbourhood = getNeighbourhood(rule.neighbourhoodType, rule.neighbourhoodRange);
return generateGlsl(rule, neighbourhood, outOfBoundValue);
};