-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
517 lines (418 loc) · 13 KB
/
app.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
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
/* START REQUIREMENTS */
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');
var serialport = require('serialport');
var util = require('util');
var cp = require('chipmunk');
/* END REQUIREMENTS */
// Give access to the entire directory (for client-side JS libraries)
app.use(express.static(__dirname));
// Initialize Serial Port Connection
var SerialPort = serialport.SerialPort;
var serial0 = new SerialPort("COM10", {baudrate: 115200});
// TODO:
// Initialize Serial Port Connection
// var SerialPort = serialport.SerialPort;
// var serial0 = new SerialPort("/dev/ttymxc3", {baudrate: 115200});
var ready = false;
var reset = false;
var reconfigure = false;
/* START BUFFERS */
// Create a buffer for forces to be written
buffx = new Buffer(4);
buffy = new Buffer(4);
buffOut = new Buffer(9);
// Dumby buffer
zeroBuffer = new Buffer(9).fill(0);
var outFull = false;
var inFull = false;
// Create buffers to send to Arduino
function force (step, fx, fy) {
if (inFull) {
fx = Math.floor(fx);
fy = Math.floor(fy);
outFull = false;
if (step) {
buffOut.writeUInt8(step);
buffOut.fill(0x00, 1);
} else {
buffOut.writeUInt8(0x00);
if (fy) {
buffOut.writeFloatLE(fy, 1);
} else {
buffOut.writeFloatLE(0, 1);
}
if (fx) {
buffOut.writeFloatLE(fx, 5);
} else {
buffOut.writeFloatLE(0,5);
}
}
outFull = true;
} else {
outFull = false;
zeroBuffer.copy(buffOut);
outFull = true;
}
}
// var for data received
stateBuffer = new Buffer(16);
var start = 0;
var state = [0,0,0,0];
/* END BUFFERS*/
/* START TIME VARIABLES */
var renStep = 1/30;
var simStep = 1/250;
var renStepCounter = 0;
/* END TIME VARIABLEs */
/* START CP VARIABLES*/
// Screen Resolution
var width = 1024;
var height = 695;
var PPI = 3.21;
var topRight = [];
var topLeft = [];
var bottomRight = [];
var bottomLeft = [];
var center = [];
var x_min, x, y;
// Nodes for screen corners -> topLeft, bottomLeft, bottomRight, topRight
var bounds = [cp.v(0,0),cp.v(0,height),cp.v(width,height),cp.v(width,0)];
var GRABABLE_MASK_BIT = 1<<31;
var NOT_GRABABLE_MASK = ~GRABABLE_MASK_BIT;
// Current Simulation
var simulation = null;
var info;
var normal, normal2;
var r;
var f;
var a, b;
var k = 10000; // spring stiffness
var configuration = 'large';
/* END CP VARIABLES */
/* START SIMULATION FUNCTIONS */
function mm2px(x, inMin, inMax, outMin, outMax) {
return (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
}
function init_simulation_1 () {
// Quick test: one static ball, one moving ball
var space = new cp.Space();
space.iterations = 10;
space.gravity = cp.v(0,0);
space.damping = 0.9;
space.sleepTimeThreshold = 0.5;
space.collisionSlop = 0.5;
space.collisionBias = 1;
space.sleepTimeThreshold = 0.5;
//add floor and ceiling
var floor = space.addShape(new cp.SegmentShape(space.staticBody, bounds[1], bounds[2], 0));
floor.setElasticity(0.5);
floor.setFriction(0);
floor.setLayers(NOT_GRABABLE_MASK);
var ceiling = space.addShape(new cp.SegmentShape(space.staticBody, bounds[0], bounds[3], 0));
floor.setElasticity(0.5);
floor.setFriction(0);
floor.setLayers(NOT_GRABABLE_MASK);
//add walls
var wallLeft = space.addShape(new cp.SegmentShape(space.staticBody,bounds[0], bounds[1], 0));
wallLeft.setElasticity(0);
wallLeft.setFriction(0);
floor.setLayers(NOT_GRABABLE_MASK);
var wallRight = space.addShape(new cp.SegmentShape(space.staticBody, bounds[3], bounds[2], 0));
wallRight.setElasticity(0);
wallRight.setFriction(0);
floor.setLayers(NOT_GRABABLE_MASK);
// add user body
var user_body = space.addBody(new cp.Body(Infinity, Infinity));
// Rotated by 90 for now!!!!
user_body.setPos(cp.v(200,200));
// add tool body
var tool_mass = 100;
var tool_radius = 60;
var tool_moment = cp.momentForCircle(tool_mass, 0, tool_radius, cp.v(0, 0));
var tool_body = space.addBody(new cp.Body(tool_mass, tool_moment));
// Rotated by 90 for now!!!!
tool_body.setPos(cp.v(200,200));
// add tool shape
var tool_shape = space.addShape(new cp.CircleShape(tool_body, tool_radius, cp.v(0,0)));
tool_shape.setElasticity(0);
tool_shape.setFriction(1);
tool_shape.setLayers(NOT_GRABABLE_MASK);
// add ball body
var ball_mass = 40;
var ball_radius = 40;
var ball_moment = cp.momentForCircle(ball_mass, 0, ball_radius, cp.v(0,0));
var ball_body = space.addBody(new cp.Body(ball_mass, ball_moment));
ball_body.setPos(cp.v(500, 500));
var ball_shape = space.addShape(new cp.CircleShape(ball_body, ball_radius, cp.v(0,0)));
ball_shape.setElasticity(0.5);
ball_shape.setFriction(1);
// add pivot joint for sprint
// add coupling for user and virtual tool
// var couple = new cp.DampedSpring(user_body, tool_body, cp.v(0,0), cp.v(0,0), 0, 10000, 0);
// var spring0 = new cp.DampedSpring(user_body, tool_body, cp.v(0, 0), cp.v(0,60), 0, 1000, 1000);
// var spring1 = new cp.DampedSpring(user_body, tool_body, cp.v(0, 0), cp.v(Math.sqrt(10800),-30), 0, 1000, 1000);
// var spring2 = new cp.DampedSpring(user_body, tool_body, cp.v(0, 0), cp.v(Math.sqrt(10800),-30), 0, 1000, 1000);
var pivot = new cp.PivotJoint(user_body, tool_body, cp.v(0, 0), cp.v(1, 1));
// space.addConstraint(spring0);
// space.addConstraint(spring1);
// space.addConstraint(spring2);
// space.addConstraint(couple);
space.addConstraint(pivot);
return {
'space': space,
'shapes': [, tool_shape, ball_shape],
'bodies': [user_body, tool_body, ball_body],
'constraints': [pivot]
};
}
/* END SIMULATION FUNCTIONS */
/* START MAIN */
// Once the serial port is 'open', begin the simulation
serial0.on('open', function () {
// Initialize force-buffer to zero
force(0x00,0,0);
// Print serial0 object
console.log(serial0);
// Send Client-Side File
app.get('/', function(req, res){
res.sendFile('index.html');
});
// Wait for socket.io connection to initialize VE
io.on('connection', function(socket){
console.log('a user connected');
socket.on('ready', function () {
ready = true;
console.log('Start the simulation!')
});
socket.on('map', function (countClicks) {
switch (countClicks) {
case 0:
center = [state[1], state[0]];
console.log(center);
break;
case 1:
bottomLeft = [state[1], state[0]];
console.log(bottomLeft);
break;
case 2:
bottomRight = [state[1], state[0]];
console.log(bottomRight);
break;
case 3:
topRight = [state[1], state[0]];
x_min = 2*center[0] - bottomRight[0];
console.log(topRight);
break;
case 4:
topLeft = [state[1], state[0]];
console.log(topLeft);
break;
}
});
/* START [NODE <-> ARDUNIO] COMMUNICATION LOOP */
// Write buffOut to begin loop
if (!reset) {
serial0.write(zeroBuffer, function(err, data) {
console.log('resultsOut4 ' + data);
if (err) {
console.error(err);
}
});
}
// On data receipt, slice data into (float) position and velocity
serial0.on('data', function(data) {
inFull = false;
// copy 'data' into stateBuffer until full
data.copy(stateBuffer, start);
start += data.length;
// if stateBuffer is full:
if (start === 16) {
inFull = true;
state = [
stateBuffer.slice(0,4).readFloatLE(),
stateBuffer.slice(4,8).readFloatLE(),
stateBuffer.slice(8,12).readFloatLE(),
stateBuffer.slice(12,16).readFloatLE()
];
// console.log([state[2], state[3], state[0], state[1]]);
// console.log(state);
// once state[] is populated, reset state to zero
start = 0;
if (topLeft.length) {
x = mm2px(state[1], x_min, bottomRight[0], 0, 1024);
y = mm2px(state[0], topRight[1], bottomRight[1], 0, 695);
}
// console.log(buffOut);
if (inFull && outFull) {
// Resize event
// socket.on('reconfigure', function (out) {
// force(out, 0, 0);
// }
// // Size is large
// if (size === 'large') {
// if (configuration === 'medium') {
// // get bigger once
// force(0x0A, 0, 0);
// }
// else if (configuration === 'small') {
// // bigger thrice
// force(0x0A, 0, 0);
// }
// configuration = 'large';
// }
// // Size is medium
// if (size === 'medium') {
// if (configuration === 'large') {
// // get smaller once
// force(0x0B, 0, 0);
// }
// else if (configuration === 'small') {
// // get bigger twice
// force(0x0A, 0, 0);
// }
// configuration = 'medium';
// }
// // Size is small
// else {
// if (configuration === 'large') {
// // get smaller thrice
// force(0x0B, 0, 0);
// }
// else if (configuration === 'medium') {
// // get smaller twice
// force(0x0B, 0, 0);
// }
// configuration = 'small';
// }
// });
serial0.write(buffOut, function(err, data) {
// console.log(buffOut.readFloatLE(1), buffOut.readFloatLE(5));
// console.log("resultsOut0: ", data);
if (err) {
console.error(err);
}
});
}
}
});
/* END [NODE <-> ARDUINO] COMMUNICATION LOOP */
/* START CP LOOP */
// To calculate whether the ball is loaded in slingshot
var size = 1.0;
var mid = height / 2;
a = mid + ((size / 2.0) * mid);
b = mid - ((size / 2.0) * mid);
var loaded = false;
var launched = false;
var pivot = null;
var rotSpring = null;
// Initialize simulation_1
simulation = init_simulation_1();
var count = 0;
// Loop through simulation at 1/simStep Hz
setInterval(function () {
if (ready) {
// If it hasn't already been loaded and isn't being launched
if (!loaded && !launched) {
// Check to see if in slingshot bounds
loaded = simulation.bodies[2].p.x > 694 && simulation.bodies[2].p.y > b && simulation.bodies[2].p.y < a;
if (pivot !== null && simulation.bodies[2].p.x < 655 && !loaded) {
// console.log('removing constraint');
simulation.space.removeConstraint(pivot);
pivot = null;
}
} else {
loaded = simulation.bodies[2].p.x > 694;
}
simulation.bodies[0].setPos(cp.v(x,y));
// if (simulation.space.arbiters.length) {
// console.log(simulation.space.arbiters[0].totalImpulse().x);
// force(0x00, 0, simulation.space.arbiters[0].totalImpulse().x);
// } else {
// force(0x00, 0, 0);
// }
info = simulation.space.nearestPointQueryNearest(cp.v(x, y), 200, GRABABLE_MASK_BIT, cp.NO_GROUP);
// Step by timestep simStep
simulation.space.step(simStep);
// Distance between user and ball
if (info) {
if (loaded) {
if (!pivot) {
// Add a pin constraint between the user and ball
pivot = new cp.PivotJoint(simulation.bodies[1], simulation.bodies[2], cp.v(0, 0), cp.v(95, 0));
pivot.errorBias = 0.0000001;
simulation.space.addConstraint(pivot);
simulation.constraints.push(pivot);
}
normal = cp.v.normalize(cp.v.sub(simulation.bodies[2].p, cp.v(694, height / 2)));
normal2 = cp.v.normalize(cp.v.sub(cp.v(x, y), simulation.bodies[2].p));
r = info.d;
f = cp.v.add(cp.v.mult(normal, -k * r), cp.v.mult(normal2, -k * r));
simulation.bodies[2].activate();
simulation.bodies[2].f = f;
// force(0x00, -60000, 0);
f = cp.v.mult(normal, -60000);
force(0x00, f.x, f.y);
if (simulation.shapes[1].tc.x + 60 >= 1024) {
simulation.space.removeConstraint(pivot);
pivot = null;
launched = true;
force(0x00, 0, 0);
}
} else if (info.d >= 70) {
// Add a magnetic force to pick up the ball
normal = cp.v.normalize(cp.v.sub(cp.v(x, y), simulation.bodies[2].p));
r = info.d;
f = cp.v.mult(normal, 100000000 / (r * r));
simulation.bodies[2].activate();
simulation.bodies[2].f = f;
// remove this line for no
force(0x00, -2*f.x, -2*f.y);
// force(0x00, 0, 0);
} else {
normal = cp.v.normalize(cp.v.sub(cp.v(x, y), simulation.bodies[2].p));
f = cp.v.mult(normal, 4000);
simulation.bodies[2].f = f;
launched = false;
force(0x00, 0, 0);
}
} else {
force(0x00, 0, 0);
}
simulation.space.step(simStep);
} else {
force(0x00, 0, 0);
}
}, simStep * 1000);
/* END CP LOOP */
/* START NODE -> CLIENT DATA TRANSFER */
// Send client position data at
setInterval( function () {
socket.emit('state',[
[x,simulation.bodies[2].p.x],
[y,simulation.bodies[2].p.y],
loaded
]);
}, renStep*1000);
/* END NODE -> CLIENT DATA TRANSFER */
socket.on('disconnect', function(){
console.log('user disconnected');
ready = false;
reset = true;
force(0x00,0,0);
});
});
// TODO:
// address subject to change
http.listen(8080, '192.168.0.101', function(){
console.log('listening on 192.168.0.101:8080');
});
// http.listen(8080, '10.103.250.161', function(){
// console.log('listening on 10.103.259.161:8080');
// });
});
/* END MAIN */