server.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. const express = require('express');
  2. const dgram = require('dgram');
  3. const oscParser = require('./osc-parser');
  4. const bodyParser = require('body-parser');
  5. const { Bundle, Client } = require('node-osc');
  6. const path = require('path');
  7. const config = require('../frontend/assets/config.json');
  8. const app = express();
  9. app.use(bodyParser.json());
  10. app.use(bodyParser.urlencoded({extended:true}));
  11. app.use(express.static('./frontend/assets'));
  12. app.get('/', function (req, res) {
  13. res.sendFile('./frontend/index.html', {
  14. root: path.resolve(__dirname + '/..')
  15. });
  16. });
  17. const httpServer = require('http').Server(app);
  18. /* --------
  19. * RECEIVER
  20. * --------
  21. */
  22. const receiverIo = require('socket.io')(httpServer, {
  23. transports: ['websocket']
  24. });
  25. const onSocketListening = function() {
  26. const address = receiverUdpSocket.address();
  27. console.log('Serveur TUIO en écoute sur : ' + address.address + ':' + address.port);
  28. };
  29. const onSocketConnection = function(socket) {
  30. receiverUdpSocket.on('message', function(msg) {
  31. socket.emit('osc', oscParser.decode(msg));
  32. });
  33. };
  34. const receiverUdpSocket = dgram.createSocket('udp4');
  35. receiverUdpSocket.on('listening', onSocketListening);
  36. receiverUdpSocket.bind(config.app.oscUdpPort, '127.0.0.1');
  37. app.get('/receiver/json', function (req, res) {
  38. res.status(200).send();
  39. });
  40. receiverIo.sockets.on('connection', (socket) =>{
  41. console.log(`Connecté au client ${socket.id}`);
  42. const dgramCallback = function (buf) {
  43. if (config.app.debug && config.app.debugLog.backend.receiver.oscDatagram) {
  44. console.log(oscParser.decode(buf));
  45. }
  46. socket.emit('osc', oscParser.decode(buf));
  47. };
  48. // forward UDP packets via socket.io
  49. receiverUdpSocket.on('message', dgramCallback);
  50. // prevent memory leak on disconnect
  51. socket.on('disconnect', function (socket) {
  52. receiverUdpSocket.removeListener('message', dgramCallback);
  53. });
  54. });
  55. /* -------
  56. * EMITTER
  57. * -------
  58. */
  59. const emitterOscClient = new Client('127.0.0.1', config.app.oscUdpPort);
  60. let alive = [];
  61. let fseq;
  62. let objectsAlive = [] ;
  63. let lastDots = [];
  64. function getHypotenuse(touch1, touch2) {
  65. const x = Math.abs(touch1.x - touch2.x);
  66. const y = Math.abs(touch1.y - touch2.y);
  67. return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
  68. }
  69. function getTop(dotTrio) {
  70. const dist01 = getHypotenuse(dotTrio[0], dotTrio[1]);
  71. const dist02 = getHypotenuse(dotTrio[0], dotTrio[2]);
  72. const dist12 = getHypotenuse(dotTrio[1], dotTrio[2]);
  73. const diff01m02 = Math.abs(dist01 - dist02);
  74. const diff01m12 = Math.abs(dist01 - dist12);
  75. const diff02m12 = Math.abs(dist02 - dist12);
  76. if (diff01m02 < diff02m12 && diff01m02 < diff01m12) {
  77. return 0;
  78. }
  79. else if (diff01m12 < diff01m02 && diff01m12 < diff02m12) {
  80. return 1;
  81. }
  82. else if (diff02m12 < diff01m02 && diff02m12 < diff01m12) {
  83. return 2;
  84. }
  85. }
  86. function getAngleApex(dotTrio, topIndex) {
  87. let dotA;
  88. let dotB;
  89. let dotC;
  90. dotB = dotTrio[topIndex];
  91. if (topIndex == 0) {
  92. dotA = dotTrio[1];
  93. dotC = dotTrio[2];
  94. }
  95. else if (topIndex == 1) {
  96. dotA = dotTrio[0];
  97. dotC = dotTrio[2];
  98. }
  99. else if (topIndex == 2) {
  100. dotA = dotTrio[0];
  101. dotC = dotTrio[1];
  102. }
  103. const AB = [dotB.x - dotA.x, dotB.y - dotA.y];
  104. const CB = [dotB.x - dotC.x, dotB.y - dotC.y];
  105. const dotProd = (AB[0] * CB[0] + AB[1] * CB[1]);
  106. const crossProd = (AB[0] * CB[1] - AB[1] * CB[0]);
  107. const alpha = Math.atan2(crossProd, dotProd);
  108. //return alpha ;
  109. return Math.abs(Math.floor(alpha * 180. / Math.PI + 0.5)) ;
  110. }
  111. function getOrientation(dotTrio, topIndex) {
  112. let dotA;
  113. let dotB;
  114. let dotC;
  115. dotB = dotTrio[topIndex];
  116. if (topIndex == 0) {
  117. dotA = dotTrio[1];
  118. dotC = dotTrio[2];
  119. }
  120. else if (topIndex == 1) {
  121. dotA = dotTrio[0];
  122. dotC = dotTrio[2];
  123. }
  124. else if (topIndex == 2) {
  125. dotA = dotTrio[0];
  126. dotC = dotTrio[1];
  127. }
  128. const middlePt = [(dotA.x + dotC.x) / 2, (dotA.y + dotC.y) / 2 ] ;
  129. let diff = [dotB.x - middlePt[0], dotB.y - middlePt[1]] ;
  130. //const length = Math.sqrt(Math.pow(diff[0], 2) + Math.pow(diff[1], 2) ) ;
  131. //normalize diff
  132. //diff = [diff[0] / length, diff[1] / length];
  133. const rad = Math.atan2(diff[1], diff[0]) ;
  134. return Math.floor(rad * 180 / Math.PI) ;
  135. //return length ;
  136. }
  137. function objectGarbageCollector(){
  138. //si un point dans last dots est detecté dans un des triangle alors on ne réduit pas sa duration
  139. for(const triangle of objectsAlive){
  140. if(triangle.dots.some(dot => lastDots.some(lastDot => lastDot.x == dot.x))){
  141. } else {
  142. triangle.remainingDuration -= 1;
  143. }
  144. };
  145. objectsAlive = objectsAlive.filter(triangle => triangle.remainingDuration > 0);
  146. createBundle();
  147. }
  148. setInterval(objectGarbageCollector, config.app.garbageCollectorInterval);
  149. let currentOscBundle = null;
  150. let hasPending = false;
  151. function createBundle(){
  152. currentOscBundle = new Bundle ;
  153. currentOscBundle.append([ '/tuio/2Dobj', 'alive'].concat(objectsAlive.map(t => t.matchingObject.apexAngle) ));
  154. for(const triangle of objectsAlive){
  155. currentOscBundle.append([
  156. '/tuio/2Dobj',
  157. 'set',
  158. triangle.matchingObject.apexAngle,
  159. triangle.matchingObject.apexAngle,
  160. triangle.center[0],
  161. triangle.center[1],
  162. triangle.orientation,
  163. 0.0,
  164. 0.0,
  165. 0.0,
  166. 0.0,
  167. 0.0
  168. ]);
  169. }
  170. currentOscBundle.append(['/tuio/2Dobj', 'fseq', fseq]);
  171. hasPending = true;
  172. }
  173. function listDots(touches){
  174. const dots = [];
  175. for(const touch of touches){
  176. dots.push({
  177. id: touch.identifier,
  178. x: touch.clientX,
  179. y: touch.clientY
  180. });
  181. };
  182. if (config.app.debug && config.app.debugLog.backend.emitter.dots) {
  183. console.log('-- dots --', dots);
  184. }
  185. return dots
  186. }
  187. function listSegments(dots){
  188. const segments = [];
  189. if (dots.length > 2) {
  190. for (var i = 0; i < dots.length; i++) {
  191. for (var j = 0; j < dots.length; j++) {
  192. if (j !== i) {
  193. /* on vérifie que le segment n'est pas déjà listé */
  194. const alreadyExists = segments.find(segment => {
  195. return segment.identifiers.includes(i) && segment.identifiers.includes(j);
  196. });
  197. /* on calcule la taille du segment (l'hypoténuse) */
  198. var hyp = getHypotenuse(dots[i], dots[j]);
  199. /* on garde uniquement les segments inférieurs à 750px (valeur par défaut)
  200. * cette valeur est la variable de configuration "maxDistanceBetweenPoints" */
  201. if (!alreadyExists && hyp <= config.app.maxDistanceBetweenPoints) {
  202. segments.push({
  203. identifiers: [i, j],
  204. x1: dots[i].x,
  205. x2: dots[j].x,
  206. y1: dots[i].y,
  207. y2: dots[j].y,
  208. hyp
  209. });
  210. }
  211. }
  212. }
  213. }
  214. }
  215. if (config.app.debug && config.app.debugLog.backend.emitter.segments) {
  216. console.log('-- segments --', segments);
  217. }
  218. return segments;
  219. }
  220. function listTriangles(segments){
  221. const triangles = [];
  222. /* on boucle sur les segments */
  223. for(const segment of segments) {
  224. const dot1 = segment.identifiers[0];
  225. const dot2 = segment.identifiers[1];
  226. /* on vérifie que le triangle n'est pas déjà listé */
  227. const alreadyExists = triangles.find(triangle => {
  228. return triangle.includes(dot1) && triangle.includes(dot2);
  229. });
  230. if (!alreadyExists) {
  231. /* on cherche les segments qui contiennent un des 2 points du segment actuel
  232. * ex: si le segment actuel est AB, on cherche un segment contenant A (pour AC) et un autre contenant B (pour BC) */
  233. const found1 = segments.findIndex(seg => {
  234. return (seg.identifiers.includes(dot1) && !seg.identifiers.includes(dot2));
  235. });
  236. const found2 = segments.findIndex(seg => {
  237. return (seg.identifiers.includes(dot2) && !seg.identifiers.includes(dot1));
  238. });
  239. /* si on trouve bien les 2 segments (AC et BC), on peut créer un triangle */
  240. if (found1 !== -1 && found2 !== -1) {
  241. /* on devine quel est le 3ème point du triangle par rapport au segment actuel (le point C par rapport au segment AB) */
  242. const dot3 = segments[found1].identifiers.find(identifier => {
  243. return identifier !== dot1 && identifier !== dot2;
  244. });
  245. triangles.push([dot1, dot2, dot3]);
  246. }
  247. }
  248. };
  249. if (config.app.debug && config.app.debugLog.backend.emitter.triangles) {
  250. console.log('-- triangles --', triangles);
  251. }
  252. return triangles
  253. }
  254. function filterTriangles(dots, triangles){
  255. const filteredTriangles = [];
  256. /* Définition de l'apex, de la position du centre et de l'orientation */
  257. for(const triangle of triangles){
  258. const objTriangle = {} ;
  259. objTriangle.dots = [];
  260. objTriangle.dots[0] = dots[triangle[0]];
  261. objTriangle.dots[1] = dots[triangle[1]];
  262. objTriangle.dots[2] = dots[triangle[2]];
  263. objTriangle.apex = getTop(objTriangle.dots);
  264. objTriangle.center = [
  265. (objTriangle.dots[0].x + objTriangle.dots[1].x + objTriangle.dots[2].x) / 3,
  266. (objTriangle.dots[0].y + objTriangle.dots[1].y + objTriangle.dots[2].y) / 3
  267. ];
  268. objTriangle.angleApex = getAngleApex(objTriangle.dots, objTriangle.apex);
  269. objTriangle.orientation = getOrientation(objTriangle.dots, objTriangle.apex);
  270. if (config.app.debug && config.app.debugLog.backend.emitter.apex) {
  271. console.log('-- apex --', objTriangle.apex);
  272. console.log('angle: ', objTriangle.angleApex);
  273. console.log('centerPos: ' + objTriangle.center);
  274. console.log('orientation: ' + objTriangle.orientation);
  275. }
  276. //verify if triangle has a corresponding triangle in config
  277. const matchingObject = config.objects.find(item => {
  278. return objTriangle.angleApex > item.apexAngle - config.app.matchingTolerance && objTriangle.angleApex < item.apexAngle + config.app.matchingTolerance;
  279. });
  280. if (matchingObject) {
  281. objTriangle.matchingObject = matchingObject;
  282. filteredTriangles.push(objTriangle);
  283. if (config.app.debug && config.app.debugLog.backend.emitter.matchingObject) {
  284. console.log('-- matchingObject --', objTriangle);
  285. }
  286. }
  287. };
  288. return filteredTriangles;
  289. }
  290. function updateAliveTriangles(filteredTriangles) {
  291. for (const triangle of filteredTriangles) {
  292. let idx = objectsAlive.findIndex(item => {
  293. return triangle.matchingObject.name == item.matchingObject.name;
  294. });
  295. if (idx == -1) {
  296. triangle.remainingDuration = config.app.remainingDuration;
  297. objectsAlive.push(triangle);
  298. } else {
  299. triangle.remainingDuration = config.app.remainingDuration;
  300. objectsAlive[idx] = triangle;
  301. }
  302. }
  303. if (config.app.debug && config.app.debugLog.backend.emitter.aliveTriangles) {
  304. console.log('-- aliveTriangles --', objectsAlive);
  305. }
  306. }
  307. const sendBundle = () => {
  308. if (hasPending) {
  309. emitterOscClient.send(currentOscBundle, () => {
  310. hasPending = false;
  311. });
  312. }
  313. setTimeout(() => {
  314. sendBundle();
  315. }, config.app.timerRefresh);
  316. };
  317. sendBundle();
  318. app.post('/emitter/json', function (req, res) {
  319. if (config.app.debug && config.app.debugLog.backend.emitter.httpRequest) {
  320. console.log('### Emitter POST request ###');
  321. }
  322. let oscBundle;
  323. // if (req.body.type === 'touchend') {
  324. // fseq = fseq ? fseq + 1 : 1;
  325. // const aliveMessage = [ '/tuio/2Dcur', 'alive' ].concat(alive);
  326. // currentOscBundle = new Bundle(
  327. // [ '/tuio/2Dcur', 'source', `tangibles${req.body.section.toString()}@127.0.0.1` ],
  328. // aliveMessage,
  329. // [ '/tuio/2Dcur', 'fseq', fseq ],
  330. // [
  331. // '/tuio/2Dcur',
  332. // 'del',
  333. // req.body.touches[0].identifier
  334. // ]
  335. // );
  336. // emitterOscClient.send(currentOscBundle, () => {
  337. // const index = alive.indexOf(req.body.touches[0].identifier);
  338. // alive.splice(index, 1);
  339. // if (alive.length === 0) {
  340. // currentOscBundle = new Bundle(
  341. // [ '/tuio/2Dcur', 'source', `tangibles${req.body.section.toString()}@127.0.0.1` ],
  342. // [ '/tuio/2Dcur', 'alive' ],
  343. // [ '/tuio/2Dcur', 'fseq', fseq ]
  344. // );
  345. // emitterOscClient.send(currentOscBundle, () => {
  346. // res.status(200).send();
  347. // fseq = 0;
  348. // hasPending = false;
  349. // });
  350. // } else {
  351. // res.status(200).send();
  352. // }
  353. // });
  354. // } else {
  355. if (req.body.touches && req.body.touches.length && req.body.touches.length > 0) {
  356. fseq = fseq ? fseq + 1 : 1;
  357. const touches = Object.keys(req.body.touches);
  358. const aliveMessage = [ '/tuio/2Dcur', 'alive' ].concat(alive);
  359. touches.forEach(touch => {
  360. const id = req.body.touches[touch].identifier;
  361. if (!alive.includes(id)) {
  362. alive.push(id);
  363. aliveMessage.push(id);
  364. }
  365. });
  366. /* Listage de tous les points */
  367. const dots = listDots(req.body.touches);
  368. lastDots = dots;
  369. const segments = listSegments(dots);
  370. const triangles = listTriangles(segments);
  371. const filteredTriangles = filterTriangles(dots, triangles);
  372. updateAliveTriangles(filteredTriangles);
  373. createBundle();
  374. res.status(200).send();
  375. } else {
  376. lastDots = [];
  377. res.status(200).send();
  378. }
  379. });
  380. httpServer.listen(config.app.httpPort, function () {
  381. console.log(`Votre app est disponible sur http://localhost:${config.app.httpPort} !`)
  382. });