vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

719 lines
23 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. import BarnesHutSolver from './components/physics/BarnesHutSolver';
  2. import Repulsion from './components/physics/RepulsionSolver';
  3. import HierarchicalRepulsion from './components/physics/HierarchicalRepulsionSolver';
  4. import SpringSolver from './components/physics/SpringSolver';
  5. import HierarchicalSpringSolver from './components/physics/HierarchicalSpringSolver';
  6. import CentralGravitySolver from './components/physics/CentralGravitySolver';
  7. import ForceAtlas2BasedRepulsionSolver from './components/physics/FA2BasedRepulsionSolver';
  8. import ForceAtlas2BasedCentralGravitySolver from './components/physics/FA2BasedCentralGravitySolver';
  9. var util = require('../../util');
  10. class PhysicsEngine {
  11. constructor(body) {
  12. this.body = body;
  13. this.physicsBody = {physicsNodeIndices:[], physicsEdgeIndices:[], forces: {}, velocities: {}};
  14. this.physicsEnabled = true;
  15. this.simulationInterval = 1000 / 60;
  16. this.requiresTimeout = true;
  17. this.previousStates = {};
  18. this.referenceState = {};
  19. this.freezeCache = {};
  20. this.renderTimer = undefined;
  21. // parameters for the adaptive timestep
  22. this.adaptiveTimestep = false;
  23. this.adaptiveTimestepEnabled = false;
  24. this.adaptiveCounter = 0;
  25. this.adaptiveInterval = 3;
  26. this.stabilized = false;
  27. this.startedStabilization = false;
  28. this.stabilizationIterations = 0;
  29. this.ready = false; // will be set to true if the stabilize
  30. // default options
  31. this.options = {};
  32. this.defaultOptions = {
  33. enabled: true,
  34. barnesHut: {
  35. theta: 0.5,
  36. gravitationalConstant: -2000,
  37. centralGravity: 0.3,
  38. springLength: 95,
  39. springConstant: 0.04,
  40. damping: 0.09,
  41. avoidOverlap: 0
  42. },
  43. forceAtlas2Based: {
  44. theta: 0.5,
  45. gravitationalConstant: -50,
  46. centralGravity: 0.01,
  47. springConstant: 0.08,
  48. springLength: 100,
  49. damping: 0.4,
  50. avoidOverlap: 0
  51. },
  52. repulsion: {
  53. centralGravity: 0.2,
  54. springLength: 200,
  55. springConstant: 0.05,
  56. nodeDistance: 100,
  57. damping: 0.09,
  58. avoidOverlap: 0
  59. },
  60. hierarchicalRepulsion: {
  61. centralGravity: 0.0,
  62. springLength: 100,
  63. springConstant: 0.01,
  64. nodeDistance: 120,
  65. damping: 0.09
  66. },
  67. maxVelocity: 50,
  68. minVelocity: 0.75, // px/s
  69. solver: 'barnesHut',
  70. stabilization: {
  71. enabled: true,
  72. iterations: 1000, // maximum number of iteration to stabilize
  73. updateInterval: 50,
  74. onlyDynamicEdges: false,
  75. fit: true
  76. },
  77. timestep: 0.5,
  78. adaptiveTimestep: true
  79. };
  80. util.extend(this.options, this.defaultOptions);
  81. this.timestep = 0.5;
  82. this.layoutFailed = false;
  83. this.bindEventListeners();
  84. }
  85. bindEventListeners() {
  86. this.body.emitter.on('initPhysics', () => {this.initPhysics();});
  87. this.body.emitter.on('_layoutFailed', () => {this.layoutFailed = true;});
  88. this.body.emitter.on('resetPhysics', () => {this.stopSimulation(); this.ready = false;});
  89. this.body.emitter.on('disablePhysics', () => {this.physicsEnabled = false; this.stopSimulation();});
  90. this.body.emitter.on('restorePhysics', () => {
  91. this.setOptions(this.options);
  92. if (this.ready === true) {
  93. this.startSimulation();
  94. }
  95. });
  96. this.body.emitter.on('startSimulation', () => {
  97. if (this.ready === true) {
  98. this.startSimulation();
  99. }
  100. });
  101. this.body.emitter.on('stopSimulation', () => {this.stopSimulation();});
  102. this.body.emitter.on('destroy', () => {
  103. this.stopSimulation(false);
  104. this.body.emitter.off();
  105. });
  106. // this event will trigger a rebuilding of the cache everything. Used when nodes or edges have been added or removed.
  107. this.body.emitter.on("_dataChanged", () => {
  108. // update shortcut lists
  109. this.updatePhysicsData();
  110. });
  111. // debug: show forces
  112. // this.body.emitter.on("afterDrawing", (ctx) => {this._drawForces(ctx);});
  113. }
  114. /**
  115. * set the physics options
  116. * @param options
  117. */
  118. setOptions(options) {
  119. if (options !== undefined) {
  120. if (options === false) {
  121. this.options.enabled = false;
  122. this.physicsEnabled = false;
  123. this.stopSimulation();
  124. }
  125. else {
  126. this.physicsEnabled = true;
  127. util.selectiveNotDeepExtend(['stabilization'], this.options, options);
  128. util.mergeOptions(this.options, options, 'stabilization');
  129. if (options.enabled === undefined) {
  130. this.options.enabled = true;
  131. }
  132. if (this.options.enabled === false) {
  133. this.physicsEnabled = false;
  134. this.stopSimulation();
  135. }
  136. // set the timestep
  137. this.timestep = this.options.timestep;
  138. }
  139. }
  140. this.init();
  141. }
  142. /**
  143. * configure the engine.
  144. */
  145. init() {
  146. var options;
  147. if (this.options.solver === 'forceAtlas2Based') {
  148. options = this.options.forceAtlas2Based;
  149. this.nodesSolver = new ForceAtlas2BasedRepulsionSolver(this.body, this.physicsBody, options);
  150. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  151. this.gravitySolver = new ForceAtlas2BasedCentralGravitySolver(this.body, this.physicsBody, options);
  152. }
  153. else if (this.options.solver === 'repulsion') {
  154. options = this.options.repulsion;
  155. this.nodesSolver = new Repulsion(this.body, this.physicsBody, options);
  156. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  157. this.gravitySolver = new CentralGravitySolver(this.body, this.physicsBody, options);
  158. }
  159. else if (this.options.solver === 'hierarchicalRepulsion') {
  160. options = this.options.hierarchicalRepulsion;
  161. this.nodesSolver = new HierarchicalRepulsion(this.body, this.physicsBody, options);
  162. this.edgesSolver = new HierarchicalSpringSolver(this.body, this.physicsBody, options);
  163. this.gravitySolver = new CentralGravitySolver(this.body, this.physicsBody, options);
  164. }
  165. else { // barnesHut
  166. options = this.options.barnesHut;
  167. this.nodesSolver = new BarnesHutSolver(this.body, this.physicsBody, options);
  168. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  169. this.gravitySolver = new CentralGravitySolver(this.body, this.physicsBody, options);
  170. }
  171. this.modelOptions = options;
  172. }
  173. /**
  174. * initialize the engine
  175. */
  176. initPhysics() {
  177. if (this.physicsEnabled === true && this.options.enabled === true) {
  178. if (this.options.stabilization.enabled === true) {
  179. this.stabilize();
  180. }
  181. else {
  182. this.stabilized = false;
  183. this.ready = true;
  184. this.body.emitter.emit('fit', {}, this.layoutFailed); // if the layout failed, we use the approximation for the zoom
  185. this.startSimulation();
  186. }
  187. }
  188. else {
  189. this.ready = true;
  190. this.body.emitter.emit('fit');
  191. }
  192. }
  193. /**
  194. * Start the simulation
  195. */
  196. startSimulation() {
  197. if (this.physicsEnabled === true && this.options.enabled === true) {
  198. this.stabilized = false;
  199. // when visible, adaptivity is disabled.
  200. this.adaptiveTimestep = false;
  201. // this sets the width of all nodes initially which could be required for the avoidOverlap
  202. this.body.emitter.emit("_resizeNodes");
  203. if (this.viewFunction === undefined) {
  204. this.viewFunction = this.simulationStep.bind(this);
  205. this.body.emitter.on('initRedraw', this.viewFunction);
  206. this.body.emitter.emit('_startRendering');
  207. }
  208. }
  209. else {
  210. this.body.emitter.emit('_redraw');
  211. }
  212. }
  213. /**
  214. * Stop the simulation, force stabilization.
  215. */
  216. stopSimulation(emit = true) {
  217. this.stabilized = true;
  218. if (emit === true) {
  219. this._emitStabilized();
  220. }
  221. if (this.viewFunction !== undefined) {
  222. this.body.emitter.off('initRedraw', this.viewFunction);
  223. this.viewFunction = undefined;
  224. if (emit === true) {
  225. this.body.emitter.emit('_stopRendering');
  226. }
  227. }
  228. }
  229. /**
  230. * The viewFunction inserts this step into each render loop. It calls the physics tick and handles the cleanup at stabilized.
  231. *
  232. */
  233. simulationStep() {
  234. // check if the physics have settled
  235. var startTime = Date.now();
  236. this.physicsTick();
  237. var physicsTime = Date.now() - startTime;
  238. // run double speed if it is a little graph
  239. if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed === true) && this.stabilized === false) {
  240. this.physicsTick();
  241. // this makes sure there is no jitter. The decision is taken once to run it at double speed.
  242. this.runDoubleSpeed = true;
  243. }
  244. if (this.stabilized === true) {
  245. this.stopSimulation();
  246. }
  247. }
  248. /**
  249. * trigger the stabilized event.
  250. * @private
  251. */
  252. _emitStabilized(amountOfIterations = this.stabilizationIterations) {
  253. if (this.stabilizationIterations > 1 || this.startedStabilization === true) {
  254. setTimeout(() => {
  255. this.body.emitter.emit('stabilized', {iterations: amountOfIterations});
  256. this.startedStabilization = false;
  257. this.stabilizationIterations = 0;
  258. }, 0);
  259. }
  260. }
  261. /**
  262. * A single simulation step (or 'tick') in the physics simulation
  263. *
  264. * @private
  265. */
  266. physicsTick() {
  267. // this is here to ensure that there is no start event when the network is already stable.
  268. if (this.startedStabilization === false) {
  269. this.body.emitter.emit('startStabilizing');
  270. this.startedStabilization = true;
  271. }
  272. if (this.stabilized === false) {
  273. // adaptivity means the timestep adapts to the situation, only applicable for stabilization
  274. if (this.adaptiveTimestep === true && this.adaptiveTimestepEnabled === true) {
  275. // this is the factor for increasing the timestep on success.
  276. let factor = 1.2;
  277. // we assume the adaptive interval is
  278. if (this.adaptiveCounter % this.adaptiveInterval === 0) { // we leave the timestep stable for "interval" iterations.
  279. // first the big step and revert. Revert saves the reference state.
  280. this.timestep = 2 * this.timestep;
  281. this.calculateForces();
  282. this.moveNodes();
  283. this.revert();
  284. // now the normal step. Since this is the last step, it is the more stable one and we will take this.
  285. this.timestep = 0.5 * this.timestep;
  286. // since it's half the step, we do it twice.
  287. this.calculateForces();
  288. this.moveNodes();
  289. this.calculateForces();
  290. this.moveNodes();
  291. // we compare the two steps. if it is acceptable we double the step.
  292. if (this._evaluateStepQuality() === true) {
  293. this.timestep = factor * this.timestep;
  294. }
  295. else {
  296. // if not, we decrease the step to a minimum of the options timestep.
  297. // if the decreased timestep is smaller than the options step, we do not reset the counter
  298. // we assume that the options timestep is stable enough.
  299. if (this.timestep/factor < this.options.timestep) {
  300. this.timestep = this.options.timestep;
  301. }
  302. else {
  303. // if the timestep was larger than 2 times the option one we check the adaptivity again to ensure
  304. // that large instabilities do not form.
  305. this.adaptiveCounter = -1; // check again next iteration
  306. this.timestep = Math.max(this.options.timestep, this.timestep/factor);
  307. }
  308. }
  309. }
  310. else {
  311. // normal step, keeping timestep constant
  312. this.calculateForces();
  313. this.moveNodes();
  314. }
  315. // increment the counter
  316. this.adaptiveCounter += 1;
  317. }
  318. else {
  319. // case for the static timestep, we reset it to the one in options and take a normal step.
  320. this.timestep = this.options.timestep;
  321. this.calculateForces();
  322. this.moveNodes();
  323. }
  324. // determine if the network has stabilzied
  325. if (this.stabilized === true) {
  326. this.revert();
  327. }
  328. this.stabilizationIterations++;
  329. }
  330. }
  331. /**
  332. * Nodes and edges can have the physics toggles on or off. A collection of indices is created here so we can skip the check all the time.
  333. *
  334. * @private
  335. */
  336. updatePhysicsData() {
  337. this.physicsBody.forces = {};
  338. this.physicsBody.physicsNodeIndices = [];
  339. this.physicsBody.physicsEdgeIndices = [];
  340. let nodes = this.body.nodes;
  341. let edges = this.body.edges;
  342. // get node indices for physics
  343. for (let nodeId in nodes) {
  344. if (nodes.hasOwnProperty(nodeId)) {
  345. if (nodes[nodeId].options.physics === true) {
  346. this.physicsBody.physicsNodeIndices.push(nodes[nodeId].id);
  347. }
  348. }
  349. }
  350. // get edge indices for physics
  351. for (let edgeId in edges) {
  352. if (edges.hasOwnProperty(edgeId)) {
  353. if (edges[edgeId].options.physics === true) {
  354. this.physicsBody.physicsEdgeIndices.push(edges[edgeId].id);
  355. }
  356. }
  357. }
  358. // get the velocity and the forces vector
  359. for (let i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) {
  360. let nodeId = this.physicsBody.physicsNodeIndices[i];
  361. this.physicsBody.forces[nodeId] = {x:0,y:0};
  362. // forces can be reset because they are recalculated. Velocities have to persist.
  363. if (this.physicsBody.velocities[nodeId] === undefined) {
  364. this.physicsBody.velocities[nodeId] = {x:0,y:0};
  365. }
  366. }
  367. // clean deleted nodes from the velocity vector
  368. for (let nodeId in this.physicsBody.velocities) {
  369. if (nodes[nodeId] === undefined) {
  370. delete this.physicsBody.velocities[nodeId];
  371. }
  372. }
  373. }
  374. /**
  375. * Revert the simulation one step. This is done so after stabilization, every new start of the simulation will also say stabilized.
  376. */
  377. revert() {
  378. var nodeIds = Object.keys(this.previousStates);
  379. var nodes = this.body.nodes;
  380. var velocities = this.physicsBody.velocities;
  381. this.referenceState = {};
  382. for (let i = 0; i < nodeIds.length; i++) {
  383. let nodeId = nodeIds[i];
  384. if (nodes[nodeId] !== undefined) {
  385. if (nodes[nodeId].options.physics === true) {
  386. this.referenceState[nodeId] = {
  387. positions: {x:nodes[nodeId].x, y:nodes[nodeId].y}
  388. };
  389. velocities[nodeId].x = this.previousStates[nodeId].vx;
  390. velocities[nodeId].y = this.previousStates[nodeId].vy;
  391. nodes[nodeId].x = this.previousStates[nodeId].x;
  392. nodes[nodeId].y = this.previousStates[nodeId].y;
  393. }
  394. }
  395. else {
  396. delete this.previousStates[nodeId];
  397. }
  398. }
  399. }
  400. /**
  401. * This compares the reference state to the current state
  402. */
  403. _evaluateStepQuality() {
  404. let dx, dy, dpos;
  405. let nodes = this.body.nodes;
  406. let reference = this.referenceState;
  407. let posThreshold = 0.3;
  408. for (let nodeId in this.referenceState) {
  409. if (this.referenceState.hasOwnProperty(nodeId) && nodes[nodeId] !== undefined) {
  410. dx = nodes[nodeId].x - reference[nodeId].positions.x;
  411. dy = nodes[nodeId].y - reference[nodeId].positions.y;
  412. dpos = Math.sqrt(Math.pow(dx,2) + Math.pow(dy,2))
  413. if (dpos > posThreshold) {
  414. return false;
  415. }
  416. }
  417. }
  418. return true;
  419. }
  420. /**
  421. * move the nodes one timestep and check if they are stabilized
  422. * @returns {boolean}
  423. */
  424. moveNodes() {
  425. var nodeIndices = this.physicsBody.physicsNodeIndices;
  426. var maxVelocity = this.options.maxVelocity ? this.options.maxVelocity : 1e9;
  427. var maxNodeVelocity = 0;
  428. var averageNodeVelocity = 0;
  429. // the velocity threshold (energy in the system) for the adaptivity toggle
  430. var velocityAdaptiveThreshold = 5;
  431. for (let i = 0; i < nodeIndices.length; i++) {
  432. let nodeId = nodeIndices[i];
  433. let nodeVelocity = this._performStep(nodeId, maxVelocity);
  434. // stabilized is true if stabilized is true and velocity is smaller than vmin --> all nodes must be stabilized
  435. maxNodeVelocity = Math.max(maxNodeVelocity,nodeVelocity);
  436. averageNodeVelocity += nodeVelocity;
  437. }
  438. // evaluating the stabilized and adaptiveTimestepEnabled conditions
  439. this.adaptiveTimestepEnabled = (averageNodeVelocity/nodeIndices.length) < velocityAdaptiveThreshold;
  440. this.stabilized = maxNodeVelocity < this.options.minVelocity;
  441. }
  442. /**
  443. * Perform the actual step
  444. *
  445. * @param nodeId
  446. * @param maxVelocity
  447. * @returns {number}
  448. * @private
  449. */
  450. _performStep(nodeId,maxVelocity) {
  451. let node = this.body.nodes[nodeId];
  452. let timestep = this.timestep;
  453. let forces = this.physicsBody.forces;
  454. let velocities = this.physicsBody.velocities;
  455. // store the state so we can revert
  456. this.previousStates[nodeId] = {x:node.x, y:node.y, vx:velocities[nodeId].x, vy:velocities[nodeId].y};
  457. if (node.options.fixed.x === false) {
  458. let dx = this.modelOptions.damping * velocities[nodeId].x; // damping force
  459. let ax = (forces[nodeId].x - dx) / node.options.mass; // acceleration
  460. velocities[nodeId].x += ax * timestep; // velocity
  461. velocities[nodeId].x = (Math.abs(velocities[nodeId].x) > maxVelocity) ? ((velocities[nodeId].x > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].x;
  462. node.x += velocities[nodeId].x * timestep; // position
  463. }
  464. else {
  465. forces[nodeId].x = 0;
  466. velocities[nodeId].x = 0;
  467. }
  468. if (node.options.fixed.y === false) {
  469. let dy = this.modelOptions.damping * velocities[nodeId].y; // damping force
  470. let ay = (forces[nodeId].y - dy) / node.options.mass; // acceleration
  471. velocities[nodeId].y += ay * timestep; // velocity
  472. velocities[nodeId].y = (Math.abs(velocities[nodeId].y) > maxVelocity) ? ((velocities[nodeId].y > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].y;
  473. node.y += velocities[nodeId].y * timestep; // position
  474. }
  475. else {
  476. forces[nodeId].y = 0;
  477. velocities[nodeId].y = 0;
  478. }
  479. let totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x,2) + Math.pow(velocities[nodeId].y,2));
  480. return totalVelocity;
  481. }
  482. /**
  483. * calculate the forces for one physics iteration.
  484. */
  485. calculateForces() {
  486. this.gravitySolver.solve();
  487. this.nodesSolver.solve();
  488. this.edgesSolver.solve();
  489. }
  490. /**
  491. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  492. * because only the supportnodes for the smoothCurves have to settle.
  493. *
  494. * @private
  495. */
  496. _freezeNodes() {
  497. var nodes = this.body.nodes;
  498. for (var id in nodes) {
  499. if (nodes.hasOwnProperty(id)) {
  500. if (nodes[id].x && nodes[id].y) {
  501. this.freezeCache[id] = {x:nodes[id].options.fixed.x,y:nodes[id].options.fixed.y};
  502. nodes[id].options.fixed.x = true;
  503. nodes[id].options.fixed.y = true;
  504. }
  505. }
  506. }
  507. }
  508. /**
  509. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  510. *
  511. * @private
  512. */
  513. _restoreFrozenNodes() {
  514. var nodes = this.body.nodes;
  515. for (var id in nodes) {
  516. if (nodes.hasOwnProperty(id)) {
  517. if (this.freezeCache[id] !== undefined) {
  518. nodes[id].options.fixed.x = this.freezeCache[id].x;
  519. nodes[id].options.fixed.y = this.freezeCache[id].y;
  520. }
  521. }
  522. }
  523. this.freezeCache = {};
  524. }
  525. /**
  526. * Find a stable position for all nodes
  527. */
  528. stabilize(iterations = this.options.stabilization.iterations) {
  529. if (typeof iterations !== 'number') {
  530. console.log('The stabilize method needs a numeric amount of iterations. Switching to default: ', this.options.stabilization.iterations);
  531. iterations = this.options.stabilization.iterations;
  532. }
  533. if (this.physicsBody.physicsNodeIndices.length === 0) {
  534. this.ready = true;
  535. return;
  536. }
  537. // enable adaptive timesteps
  538. this.adaptiveTimestep = true && this.options.adaptiveTimestep;
  539. // this sets the width of all nodes initially which could be required for the avoidOverlap
  540. this.body.emitter.emit("_resizeNodes");
  541. // stop the render loop
  542. this.stopSimulation();
  543. // set stabilze to false
  544. this.stabilized = false;
  545. // block redraw requests
  546. this.body.emitter.emit('_blockRedraw');
  547. this.targetIterations = iterations;
  548. // start the stabilization
  549. if (this.options.stabilization.onlyDynamicEdges === true) {
  550. this._freezeNodes();
  551. }
  552. this.stabilizationIterations = 0;
  553. setTimeout(() => this._stabilizationBatch(),0);
  554. }
  555. /**
  556. * One batch of stabilization
  557. * @private
  558. */
  559. _stabilizationBatch() {
  560. // this is here to ensure that there is at least one start event.
  561. if (this.startedStabilization === false) {
  562. this.body.emitter.emit('startStabilizing');
  563. this.startedStabilization = true;
  564. }
  565. var count = 0;
  566. while (this.stabilized === false && count < this.options.stabilization.updateInterval && this.stabilizationIterations < this.targetIterations) {
  567. this.physicsTick();
  568. count++;
  569. }
  570. if (this.stabilized === false && this.stabilizationIterations < this.targetIterations) {
  571. this.body.emitter.emit('stabilizationProgress', {iterations: this.stabilizationIterations, total: this.targetIterations});
  572. setTimeout(this._stabilizationBatch.bind(this),0);
  573. }
  574. else {
  575. this._finalizeStabilization();
  576. }
  577. }
  578. /**
  579. * Wrap up the stabilization, fit and emit the events.
  580. * @private
  581. */
  582. _finalizeStabilization() {
  583. this.body.emitter.emit('_allowRedraw');
  584. if (this.options.stabilization.fit === true) {
  585. this.body.emitter.emit('fit');
  586. }
  587. if (this.options.stabilization.onlyDynamicEdges === true) {
  588. this._restoreFrozenNodes();
  589. }
  590. this.body.emitter.emit('stabilizationIterationsDone');
  591. this.body.emitter.emit('_requestRedraw');
  592. if (this.stabilized === true) {
  593. this._emitStabilized();
  594. }
  595. else {
  596. this.startSimulation();
  597. }
  598. this.ready = true;
  599. }
  600. _drawForces(ctx) {
  601. for (var i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) {
  602. let node = this.body.nodes[this.physicsBody.physicsNodeIndices[i]];
  603. let force = this.physicsBody.forces[this.physicsBody.physicsNodeIndices[i]];
  604. let factor = 20;
  605. let colorFactor = 0.03;
  606. let forceSize = Math.sqrt(Math.pow(force.x,2) + Math.pow(force.x,2));
  607. let size = Math.min(Math.max(5,forceSize),15);
  608. let arrowSize = 3*size;
  609. let color = util.HSVToHex((180 - Math.min(1,Math.max(0,colorFactor*forceSize))*180) / 360,1,1);
  610. ctx.lineWidth = size;
  611. ctx.strokeStyle = color;
  612. ctx.beginPath();
  613. ctx.moveTo(node.x,node.y);
  614. ctx.lineTo(node.x+factor*force.x, node.y+factor*force.y);
  615. ctx.stroke();
  616. let angle = Math.atan2(force.y, force.x);
  617. ctx.fillStyle = color;
  618. ctx.arrow(node.x + factor*force.x + Math.cos(angle)*arrowSize, node.y + factor*force.y+Math.sin(angle)*arrowSize, angle, arrowSize);
  619. ctx.fill();
  620. }
  621. }
  622. }
  623. export default PhysicsEngine;