-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpixelwall.js
More file actions
108 lines (96 loc) · 2.85 KB
/
pixelwall.js
File metadata and controls
108 lines (96 loc) · 2.85 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// All the logic for getting / updating the pixel wall
var fn = require('./static/fn');
/* n
o o o o
m o o o
o o o o
*/
function Pixelwall(m, n) {
var pixelwall = {};
var STATE = 'pixelwall::state';
var getZeroedState = function() {
var arr = [];
var len = Math.ceil(m * n / 32);
for (var i = 0; i < len; i++) {
arr.push(0);
}
return arr;
}
// Initialize the database
pixelwall.initialize = function (redisclient) {
// Initialize
redisclient.get(STATE, function (err, obj) {
if (!obj) {
redisclient.set(STATE, getZeroedState());
}
});
}
// Setup the values for lattice coordinates (in miller indices)
// All units are in % of the total width of the lattice
var w = 16;
var d_10 = (100 - w) / (n-1);
var d_01 = d_10 / Math.sqrt(3);
var d_m = d_01 / 2;
var d_n = d_10;
var height = m * d_m + w / 2;
// rescale to be % of height
d_m = d_m * 100 / height;
var h = w * 100 / height;
// Colors
var dim = "#CCCCCC";
var light = "#FFD659";
pixelwall.getContext = function () {
var context = {
initial_state: getZeroedState(),
height: height,
m: m,
n: n,
w: w,
h: h,
d_m: d_m,
d_n: d_n,
dim: dim,
light: light
};
return context;
};
var getTap = function(redisclient, io) {
// Update the state with data from client. Data comes in with the form:
// 0 | (1 << index) if we are lighting up a circle (eg 01000000)
// or
// ~ (0 | (1 << index)) if we are dimming a circle (eg 11111011)
var tap = function (data) {
console.log(new Date() + ': pixelwall-tap: ' + data);
var light = fn.accumulate(data, fn.and) == 0;
var process = function (err, state) {
state = state.split(',');
// If it is lighting up, we simply || with the state
// If it is dimming, we simply && with the state
state = fn.map(state, data, light ? fn.or : fn.and);
console.log(new Date() + ': pixelwall-state: ' + state);
io.sockets.emit('pixelwall_update', state);
redisclient.set(STATE, state);
};
redisclient.get(STATE, process);
};
return tap;
}
// Hook up the pixelwall_tap event as well as update the client with
// the latest state on connection
pixelwall.onConnection = function (redisclient, io, fn) {
var tap = getTap(redisclient, io);
var connection = function (socket) {
socket.on('pixelwall_tap', tap);
redisclient.get(STATE, function(err, state) {
state = state.split(',');
socket.emit('pixelwall_update', state);
});
if (fn) {
fn(socket);
}
};
return connection;
}
return pixelwall;
};
exports.Pixelwall = Pixelwall;