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.

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