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.

850 lines
27 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
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. import PhysicsWorker from 'worker!./PhysicsWorkerWrapper';
  10. var util = require('../../util');
  11. class PhysicsEngine {
  12. constructor(body) {
  13. this.body = body;
  14. this.physicsBody = {physicsNodeIndices:[], physicsEdgeIndices:[], forces: {}, velocities: {}};
  15. this.physicsEnabled = true;
  16. this.simulationInterval = 1000 / 60;
  17. this.requiresTimeout = true;
  18. this.previousStates = {};
  19. this.referenceState = {};
  20. this.freezeCache = {};
  21. this.renderTimer = undefined;
  22. // parameters for the adaptive timestep
  23. this.adaptiveTimestep = false;
  24. this.adaptiveTimestepEnabled = false;
  25. this.adaptiveCounter = 0;
  26. this.adaptiveInterval = 3;
  27. this.stabilized = false;
  28. this.startedStabilization = false;
  29. this.stabilizationIterations = 0;
  30. this.ready = false; // will be set to true if the stabilize
  31. // default options
  32. this.options = {};
  33. this.defaultOptions = {
  34. enabled: true,
  35. useWorker: false,
  36. barnesHut: {
  37. theta: 0.5,
  38. gravitationalConstant: -2000,
  39. centralGravity: 0.3,
  40. springLength: 95,
  41. springConstant: 0.04,
  42. damping: 0.09,
  43. avoidOverlap: 0
  44. },
  45. forceAtlas2Based: {
  46. theta: 0.5,
  47. gravitationalConstant: -50,
  48. centralGravity: 0.01,
  49. springConstant: 0.08,
  50. springLength: 100,
  51. damping: 0.4,
  52. avoidOverlap: 0
  53. },
  54. repulsion: {
  55. centralGravity: 0.2,
  56. springLength: 200,
  57. springConstant: 0.05,
  58. nodeDistance: 100,
  59. damping: 0.09,
  60. avoidOverlap: 0
  61. },
  62. hierarchicalRepulsion: {
  63. centralGravity: 0.0,
  64. springLength: 100,
  65. springConstant: 0.01,
  66. nodeDistance: 120,
  67. damping: 0.09
  68. },
  69. maxVelocity: 50,
  70. minVelocity: 0.75, // px/s
  71. solver: 'barnesHut',
  72. stabilization: {
  73. enabled: true,
  74. iterations: 1000, // maximum number of iteration to stabilize
  75. updateInterval: 50,
  76. onlyDynamicEdges: false,
  77. fit: true
  78. },
  79. timestep: 0.5,
  80. adaptiveTimestep: true
  81. };
  82. util.extend(this.options, this.defaultOptions);
  83. this.timestep = 0.5;
  84. this.layoutFailed = false;
  85. this.draggingNodes = [];
  86. this.bindEventListeners();
  87. }
  88. bindEventListeners() {
  89. this.body.emitter.on('initPhysics', () => {this.initPhysics();});
  90. this.body.emitter.on('_layoutFailed', () => {this.layoutFailed = true;});
  91. this.body.emitter.on('resetPhysics', () => {this.stopSimulation(); this.ready = false;});
  92. this.body.emitter.on('disablePhysics', () => {this.physicsEnabled = false; this.stopSimulation();});
  93. this.body.emitter.on('restorePhysics', () => {
  94. this.setOptions(this.options);
  95. if (this.ready === true) {
  96. this.startSimulation();
  97. }
  98. });
  99. this.body.emitter.on('startSimulation', () => {
  100. if (this.ready === true) {
  101. this.startSimulation();
  102. }
  103. });
  104. this.body.emitter.on('stopSimulation', () => {this.stopSimulation();});
  105. this.body.emitter.on('destroy', () => {
  106. this.stopSimulation(false);
  107. this.body.emitter.off();
  108. });
  109. // For identifying which nodes to send to worker thread
  110. this.body.emitter.on('dragStart', (properties) => {this.draggingNodes = properties.nodes;});
  111. this.body.emitter.on('dragEnd', () => {this.draggingNodes = [];});
  112. this.body.emitter.on('destroy', () => {
  113. if (this.physicsWorker) {
  114. this.physicsWorker.terminate();
  115. this.physicsWorker = undefined;
  116. }
  117. });
  118. }
  119. /**
  120. * set the physics options
  121. * @param options
  122. */
  123. setOptions(options) {
  124. if (options !== undefined) {
  125. if (options === false) {
  126. this.options.enabled = false;
  127. this.physicsEnabled = false;
  128. this.stopSimulation();
  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. if (this.options.useWorker) {
  146. this.initPhysicsWorker();
  147. this.physicsWorker.postMessage({type: 'options', data: this.options});
  148. } else {
  149. this.initEmbeddedPhysics();
  150. }
  151. }
  152. /**
  153. * configure the engine.
  154. */
  155. initEmbeddedPhysics() {
  156. if (this.physicsWorker) {
  157. this.options.useWorker = false;
  158. this.physicsWorker.terminate();
  159. this.physicsWorker = undefined;
  160. this.updatePhysicsData();
  161. }
  162. var options;
  163. if (this.options.solver === 'forceAtlas2Based') {
  164. options = this.options.forceAtlas2Based;
  165. this.nodesSolver = new ForceAtlas2BasedRepulsionSolver(this.body, this.physicsBody, options);
  166. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  167. this.gravitySolver = new ForceAtlas2BasedCentralGravitySolver(this.body, this.physicsBody, options);
  168. }
  169. else if (this.options.solver === 'repulsion') {
  170. options = this.options.repulsion;
  171. this.nodesSolver = new Repulsion(this.body, this.physicsBody, options);
  172. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  173. this.gravitySolver = new CentralGravitySolver(this.body, this.physicsBody, options);
  174. }
  175. else if (this.options.solver === 'hierarchicalRepulsion') {
  176. options = this.options.hierarchicalRepulsion;
  177. this.nodesSolver = new HierarchicalRepulsion(this.body, this.physicsBody, options);
  178. this.edgesSolver = new HierarchicalSpringSolver(this.body, this.physicsBody, options);
  179. this.gravitySolver = new CentralGravitySolver(this.body, this.physicsBody, options);
  180. }
  181. else { // barnesHut
  182. options = this.options.barnesHut;
  183. this.nodesSolver = new BarnesHutSolver(this.body, this.physicsBody, options);
  184. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  185. this.gravitySolver = new CentralGravitySolver(this.body, this.physicsBody, options);
  186. }
  187. this.modelOptions = options;
  188. }
  189. initPhysicsWorker() {
  190. if (!this.physicsWorker) {
  191. if (!__webpack_public_path__) {
  192. let parentScript = document.getElementById('visjs');
  193. if (parentScript) {
  194. let src = parentScript.getAttribute('src')
  195. __webpack_public_path__ = src.substr(0, src.lastIndexOf('/') + 1);
  196. } else {
  197. let scripts = document.getElementsByTagName('script');
  198. for (let i = 0; i < scripts.length; i++) {
  199. let src = scripts[i].getAttribute('src');
  200. if (src && src.length >= 6) {
  201. let position = src.length - 6;
  202. let index = src.indexOf('vis.js', position);
  203. if (index === position) {
  204. __webpack_public_path__ = src.substr(0, src.lastIndexOf('/') + 1);
  205. break;
  206. }
  207. }
  208. }
  209. }
  210. }
  211. this.physicsWorker = new PhysicsWorker();
  212. this.physicsWorker.addEventListener('message', (event) => {
  213. this.physicsWorkerMessageHandler(event);
  214. });
  215. this.physicsWorker.onerror = (event) => {
  216. console.error('Falling back to embedded physics engine');
  217. this.initEmbeddedPhysics();
  218. // throw new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
  219. };
  220. }
  221. }
  222. physicsWorkerMessageHandler(event) {
  223. var msg = event.data;
  224. switch (msg.type) {
  225. case 'positions':
  226. this.stabilized = msg.data.stabilized;
  227. var positions = msg.data.positions;
  228. // console.log('received positions', positions);
  229. for (let i = 0; i < this.draggingNodes; i++) {
  230. delete positions[this.draggingNodes[i]];
  231. }
  232. let nodeIds = Object.keys(positions);
  233. for (let i = 0; i < nodeIds.length; i++) {
  234. let nodeId = nodeIds[i];
  235. let node = this.body.nodes[nodeId];
  236. // handle case where we get a positions from an old physicsObject
  237. if (node) {
  238. node.x = positions[nodeId].x;
  239. node.y = positions[nodeId].y;
  240. }
  241. }
  242. break;
  243. default:
  244. console.warn('unhandled physics worker message:', msg);
  245. }
  246. }
  247. /**
  248. * initialize the engine
  249. */
  250. initPhysics() {
  251. if (this.physicsEnabled === true && this.options.enabled === true) {
  252. if (this.options.stabilization.enabled === true) {
  253. this.stabilize();
  254. }
  255. else {
  256. this.stabilized = false;
  257. this.ready = true;
  258. this.body.emitter.emit('fit', {}, this.layoutFailed); // if the layout failed, we use the approximation for the zoom
  259. this.startSimulation();
  260. }
  261. }
  262. else {
  263. this.ready = true;
  264. this.body.emitter.emit('fit');
  265. }
  266. }
  267. /**
  268. * Start the simulation
  269. */
  270. startSimulation() {
  271. if (this.physicsEnabled === true && this.options.enabled === true) {
  272. if (this.physicsWorker) {
  273. for(let i = 0; i < this.draggingNodes.length; i++) {
  274. let nodeId = this.draggingNodes[i];
  275. let node = this.body.nodes[nodeId];
  276. this.physicsWorker.postMessage({
  277. type: 'update',
  278. data: {
  279. id: nodeId,
  280. x: node.x,
  281. y: node.y
  282. }
  283. });
  284. }
  285. }
  286. this.stabilized = false;
  287. // when visible, adaptivity is disabled.
  288. this.adaptiveTimestep = false;
  289. // this sets the width of all nodes initially which could be required for the avoidOverlap
  290. this.body.emitter.emit("_resizeNodes");
  291. if (this.viewFunction === undefined) {
  292. this.viewFunction = this.simulationStep.bind(this);
  293. this.body.emitter.on('initRedraw', this.viewFunction);
  294. this.body.emitter.emit('_startRendering');
  295. }
  296. }
  297. else {
  298. this.body.emitter.emit('_redraw');
  299. }
  300. }
  301. /**
  302. * Stop the simulation, force stabilization.
  303. */
  304. stopSimulation(emit = true) {
  305. this.stabilized = true;
  306. if (emit === true) {
  307. this._emitStabilized();
  308. }
  309. if (this.viewFunction !== undefined) {
  310. this.body.emitter.off('initRedraw', this.viewFunction);
  311. this.viewFunction = undefined;
  312. if (emit === true) {
  313. this.body.emitter.emit('_stopRendering');
  314. }
  315. }
  316. }
  317. /**
  318. * The viewFunction inserts this step into each renderloop. It calls the physics tick and handles the cleanup at stabilized.
  319. *
  320. */
  321. simulationStep() {
  322. // check if the physics have settled
  323. var startTime = Date.now();
  324. this.physicsTick();
  325. var physicsTime = Date.now() - startTime;
  326. // run double speed if it is a little graph
  327. if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed === true) && this.stabilized === false) {
  328. this.physicsTick();
  329. // this makes sure there is no jitter. The decision is taken once to run it at double speed.
  330. this.runDoubleSpeed = true;
  331. }
  332. if (this.stabilized === true) {
  333. this.stopSimulation();
  334. }
  335. }
  336. /**
  337. * trigger the stabilized event.
  338. * @private
  339. */
  340. _emitStabilized(amountOfIterations = this.stabilizationIterations) {
  341. if (this.stabilizationIterations > 1 || this.startedStabilization === true) {
  342. setTimeout(() => {
  343. this.body.emitter.emit('stabilized', {iterations: amountOfIterations});
  344. this.startedStabilization = false;
  345. this.stabilizationIterations = 0;
  346. }, 0);
  347. }
  348. }
  349. /**
  350. * A single simulation step (or 'tick') in the physics simulation
  351. *
  352. * @private
  353. */
  354. physicsTick() {
  355. // this is here to ensure that there is no start event when the network is already stable.
  356. if (this.startedStabilization === false) {
  357. this.body.emitter.emit('startStabilizing');
  358. this.startedStabilization = true;
  359. }
  360. if (this.stabilized === false) {
  361. // adaptivity means the timestep adapts to the situation, only applicable for stabilization
  362. if (this.adaptiveTimestep === true && this.adaptiveTimestepEnabled === true) {
  363. // this is the factor for increasing the timestep on success.
  364. let factor = 1.2;
  365. // we assume the adaptive interval is
  366. if (this.adaptiveCounter % this.adaptiveInterval === 0) { // we leave the timestep stable for "interval" iterations.
  367. // first the big step and revert. Revert saves the reference state.
  368. this.timestep = 2 * this.timestep;
  369. this.calculateForces();
  370. this.moveNodes();
  371. this.revert();
  372. // now the normal step. Since this is the last step, it is the more stable one and we will take this.
  373. this.timestep = 0.5 * this.timestep;
  374. // since it's half the step, we do it twice.
  375. this.calculateForces();
  376. this.moveNodes();
  377. this.calculateForces();
  378. this.moveNodes();
  379. // we compare the two steps. if it is acceptable we double the step.
  380. if (this._evaluateStepQuality() === true) {
  381. this.timestep = factor * this.timestep;
  382. }
  383. else {
  384. // if not, we decrease the step to a minimum of the options timestep.
  385. // if the decreased timestep is smaller than the options step, we do not reset the counter
  386. // we assume that the options timestep is stable enough.
  387. if (this.timestep/factor < this.options.timestep) {
  388. this.timestep = this.options.timestep;
  389. }
  390. else {
  391. // if the timestep was larger than 2 times the option one we check the adaptivity again to ensure
  392. // that large instabilities do not form.
  393. this.adaptiveCounter = -1; // check again next iteration
  394. this.timestep = Math.max(this.options.timestep, this.timestep/factor);
  395. }
  396. }
  397. }
  398. else {
  399. // normal step, keeping timestep constant
  400. this.calculateForces();
  401. this.moveNodes();
  402. }
  403. // increment the counter
  404. this.adaptiveCounter += 1;
  405. }
  406. else {
  407. // case for the static timestep, we reset it to the one in options and take a normal step.
  408. this.timestep = this.options.timestep;
  409. if (this.physicsWorker) {
  410. // console.log('asking working to do a physics iteration');
  411. this.physicsWorker.postMessage({type: 'calculateForces'});
  412. } else {
  413. this.calculateForces();
  414. this.moveNodes();
  415. }
  416. }
  417. // determine if the network has stabilzied
  418. if (this.stabilized === true) {
  419. this.revert();
  420. }
  421. this.stabilizationIterations++;
  422. }
  423. }
  424. /**
  425. * 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.
  426. *
  427. * @private
  428. */
  429. updatePhysicsData() {
  430. let nodes = this.body.nodes;
  431. let edges = this.body.edges;
  432. if (this.physicsWorker) {
  433. var physicsWorkerNodes = {};
  434. var physicsWorkerEdges = {};
  435. for (let nodeId in nodes) {
  436. if (nodes.hasOwnProperty(nodeId)) {
  437. let node = nodes[nodeId];
  438. if (node.options.physics === true) {
  439. physicsWorkerNodes[nodeId] = {
  440. id: node.id,
  441. x: node.x,
  442. y: node.y,
  443. options: {
  444. fixed: {
  445. x: node.options.fixed.x,
  446. y: node.options.fixed.y
  447. },
  448. mass: node.options.mass
  449. }
  450. }
  451. }
  452. }
  453. }
  454. for (let edgeId in edges) {
  455. if (edges.hasOwnProperty(edgeId)) {
  456. let edge = edges[edgeId];
  457. if (edge.options.physics === true) {
  458. physicsWorkerEdges[edgeId] = {
  459. connected: edge.connected,
  460. id: edge.id,
  461. edgeType: {},
  462. toId: edge.toId,
  463. fromId: edge.fromId,
  464. to: {
  465. id: edge.to.id
  466. },
  467. from: {
  468. id: edge.from.id
  469. },
  470. options: {
  471. length: edge.length
  472. }
  473. };
  474. if (edge.edgeType.via) {
  475. physicsWorkerEdges[edgeId].edgeType = {
  476. via: {
  477. id: edge.edgeType.via.id
  478. }
  479. }
  480. }
  481. }
  482. }
  483. }
  484. this.physicsWorker.postMessage({
  485. type: 'physicsObjects',
  486. data: {
  487. nodes: physicsWorkerNodes,
  488. edges: physicsWorkerEdges
  489. }
  490. });
  491. } else {
  492. this.physicsBody.forces = {};
  493. this.physicsBody.physicsNodeIndices = [];
  494. this.physicsBody.physicsEdgeIndices = [];
  495. // get node indices for physics
  496. for (let nodeId in nodes) {
  497. if (nodes.hasOwnProperty(nodeId)) {
  498. if (nodes[nodeId].options.physics === true) {
  499. this.physicsBody.physicsNodeIndices.push(nodeId);
  500. }
  501. }
  502. }
  503. // get edge indices for physics
  504. for (let edgeId in edges) {
  505. if (edges.hasOwnProperty(edgeId)) {
  506. if (edges[edgeId].options.physics === true) {
  507. this.physicsBody.physicsEdgeIndices.push(edgeId);
  508. }
  509. }
  510. }
  511. // get the velocity and the forces vector
  512. for (let i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) {
  513. let nodeId = this.physicsBody.physicsNodeIndices[i];
  514. this.physicsBody.forces[nodeId] = {x: 0, y: 0};
  515. // forces can be reset because they are recalculated. Velocities have to persist.
  516. if (this.physicsBody.velocities[nodeId] === undefined) {
  517. this.physicsBody.velocities[nodeId] = {x: 0, y: 0};
  518. }
  519. }
  520. // clean deleted nodes from the velocity vector
  521. for (let nodeId in this.physicsBody.velocities) {
  522. if (nodes[nodeId] === undefined) {
  523. delete this.physicsBody.velocities[nodeId];
  524. }
  525. }
  526. }
  527. }
  528. /**
  529. * Revert the simulation one step. This is done so after stabilization, every new start of the simulation will also say stabilized.
  530. */
  531. revert() {
  532. var nodeIds = Object.keys(this.previousStates);
  533. var nodes = this.body.nodes;
  534. var velocities = this.physicsBody.velocities;
  535. this.referenceState = {};
  536. for (let i = 0; i < nodeIds.length; i++) {
  537. let nodeId = nodeIds[i];
  538. if (nodes[nodeId] !== undefined) {
  539. if (nodes[nodeId].options.physics === true) {
  540. this.referenceState[nodeId] = {
  541. positions: {x:nodes[nodeId].x, y:nodes[nodeId].y}
  542. };
  543. velocities[nodeId].x = this.previousStates[nodeId].vx;
  544. velocities[nodeId].y = this.previousStates[nodeId].vy;
  545. nodes[nodeId].x = this.previousStates[nodeId].x;
  546. nodes[nodeId].y = this.previousStates[nodeId].y;
  547. }
  548. }
  549. else {
  550. delete this.previousStates[nodeId];
  551. }
  552. }
  553. }
  554. /**
  555. * This compares the reference state to the current state
  556. */
  557. _evaluateStepQuality() {
  558. let dx, dy, dpos;
  559. let nodes = this.body.nodes;
  560. let reference = this.referenceState;
  561. let posThreshold = 0.3;
  562. for (let nodeId in this.referenceState) {
  563. if (this.referenceState.hasOwnProperty(nodeId) && nodes[nodeId] !== undefined) {
  564. dx = nodes[nodeId].x - reference[nodeId].positions.x;
  565. dy = nodes[nodeId].y - reference[nodeId].positions.y;
  566. dpos = Math.sqrt(Math.pow(dx,2) + Math.pow(dy,2))
  567. if (dpos > posThreshold) {
  568. return false;
  569. }
  570. }
  571. }
  572. return true;
  573. }
  574. /**
  575. * move the nodes one timestap and check if they are stabilized
  576. * @returns {boolean}
  577. */
  578. moveNodes() {
  579. var nodeIndices = this.physicsBody.physicsNodeIndices;
  580. var maxVelocity = this.options.maxVelocity ? this.options.maxVelocity : 1e9;
  581. var maxNodeVelocity = 0;
  582. var averageNodeVelocity = 0;
  583. // the velocity threshold (energy in the system) for the adaptivity toggle
  584. var velocityAdaptiveThreshold = 5;
  585. for (let i = 0; i < nodeIndices.length; i++) {
  586. let nodeId = nodeIndices[i];
  587. let nodeVelocity = this._performStep(nodeId, maxVelocity);
  588. // stabilized is true if stabilized is true and velocity is smaller than vmin --> all nodes must be stabilized
  589. maxNodeVelocity = Math.max(maxNodeVelocity,nodeVelocity);
  590. averageNodeVelocity += nodeVelocity;
  591. }
  592. // evaluating the stabilized and adaptiveTimestepEnabled conditions
  593. this.adaptiveTimestepEnabled = (averageNodeVelocity/nodeIndices.length) < velocityAdaptiveThreshold;
  594. this.stabilized = maxNodeVelocity < this.options.minVelocity;
  595. }
  596. /**
  597. * Perform the actual step
  598. *
  599. * @param nodeId
  600. * @param maxVelocity
  601. * @returns {number}
  602. * @private
  603. */
  604. _performStep(nodeId,maxVelocity) {
  605. let node = this.body.nodes[nodeId];
  606. let timestep = this.timestep;
  607. let forces = this.physicsBody.forces;
  608. let velocities = this.physicsBody.velocities;
  609. // store the state so we can revert
  610. this.previousStates[nodeId] = {x:node.x, y:node.y, vx:velocities[nodeId].x, vy:velocities[nodeId].y};
  611. if (node.options.fixed.x === false) {
  612. let dx = this.modelOptions.damping * velocities[nodeId].x; // damping force
  613. let ax = (forces[nodeId].x - dx) / node.options.mass; // acceleration
  614. velocities[nodeId].x += ax * timestep; // velocity
  615. velocities[nodeId].x = (Math.abs(velocities[nodeId].x) > maxVelocity) ? ((velocities[nodeId].x > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].x;
  616. node.x += velocities[nodeId].x * timestep; // position
  617. }
  618. else {
  619. forces[nodeId].x = 0;
  620. velocities[nodeId].x = 0;
  621. }
  622. if (node.options.fixed.y === false) {
  623. let dy = this.modelOptions.damping * velocities[nodeId].y; // damping force
  624. let ay = (forces[nodeId].y - dy) / node.options.mass; // acceleration
  625. velocities[nodeId].y += ay * timestep; // velocity
  626. velocities[nodeId].y = (Math.abs(velocities[nodeId].y) > maxVelocity) ? ((velocities[nodeId].y > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].y;
  627. node.y += velocities[nodeId].y * timestep; // position
  628. }
  629. else {
  630. forces[nodeId].y = 0;
  631. velocities[nodeId].y = 0;
  632. }
  633. let totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x,2) + Math.pow(velocities[nodeId].y,2));
  634. return totalVelocity;
  635. }
  636. /**
  637. * calculate the forces for one physics iteration.
  638. */
  639. calculateForces() {
  640. this.gravitySolver.solve();
  641. this.nodesSolver.solve();
  642. this.edgesSolver.solve();
  643. }
  644. /**
  645. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  646. * because only the supportnodes for the smoothCurves have to settle.
  647. *
  648. * @private
  649. */
  650. _freezeNodes() {
  651. var nodes = this.body.nodes;
  652. for (var id in nodes) {
  653. if (nodes.hasOwnProperty(id)) {
  654. if (nodes[id].x && nodes[id].y) {
  655. this.freezeCache[id] = {x:nodes[id].options.fixed.x,y:nodes[id].options.fixed.y};
  656. nodes[id].options.fixed.x = true;
  657. nodes[id].options.fixed.y = true;
  658. }
  659. }
  660. }
  661. }
  662. /**
  663. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  664. *
  665. * @private
  666. */
  667. _restoreFrozenNodes() {
  668. var nodes = this.body.nodes;
  669. for (var id in nodes) {
  670. if (nodes.hasOwnProperty(id)) {
  671. if (this.freezeCache[id] !== undefined) {
  672. nodes[id].options.fixed.x = this.freezeCache[id].x;
  673. nodes[id].options.fixed.y = this.freezeCache[id].y;
  674. }
  675. }
  676. }
  677. this.freezeCache = {};
  678. }
  679. /**
  680. * Find a stable position for all nodes
  681. * @private
  682. */
  683. stabilize(iterations = this.options.stabilization.iterations) {
  684. if (typeof iterations !== 'number') {
  685. console.log('The stabilize method needs a numeric amount of iterations. Switching to default: ', this.options.stabilization.iterations);
  686. iterations = this.options.stabilization.iterations;
  687. }
  688. if (this.physicsBody.physicsNodeIndices.length === 0) {
  689. this.ready = true;
  690. return;
  691. }
  692. // enable adaptive timesteps
  693. this.adaptiveTimestep = true && this.options.adaptiveTimestep;
  694. // this sets the width of all nodes initially which could be required for the avoidOverlap
  695. this.body.emitter.emit("_resizeNodes");
  696. // stop the render loop
  697. this.stopSimulation();
  698. // set stabilze to false
  699. this.stabilized = false;
  700. // block redraw requests
  701. this.body.emitter.emit('_blockRedraw');
  702. this.targetIterations = iterations;
  703. // start the stabilization
  704. if (this.options.stabilization.onlyDynamicEdges === true) {
  705. this._freezeNodes();
  706. }
  707. this.stabilizationIterations = 0;
  708. setTimeout(() => this._stabilizationBatch(),0);
  709. }
  710. /**
  711. * One batch of stabilization
  712. * @private
  713. */
  714. _stabilizationBatch() {
  715. // this is here to ensure that there is at least one start event.
  716. if (this.startedStabilization === false) {
  717. this.body.emitter.emit('startStabilizing');
  718. this.startedStabilization = true;
  719. }
  720. var count = 0;
  721. while (this.stabilized === false && count < this.options.stabilization.updateInterval && this.stabilizationIterations < this.targetIterations) {
  722. this.physicsTick();
  723. count++;
  724. }
  725. if (this.stabilized === false && this.stabilizationIterations < this.targetIterations) {
  726. this.body.emitter.emit('stabilizationProgress', {iterations: this.stabilizationIterations, total: this.targetIterations});
  727. setTimeout(this._stabilizationBatch.bind(this),0);
  728. }
  729. else {
  730. this._finalizeStabilization();
  731. }
  732. }
  733. /**
  734. * Wrap up the stabilization, fit and emit the events.
  735. * @private
  736. */
  737. _finalizeStabilization() {
  738. this.body.emitter.emit('_allowRedraw');
  739. if (this.options.stabilization.fit === true) {
  740. this.body.emitter.emit('fit');
  741. }
  742. if (this.options.stabilization.onlyDynamicEdges === true) {
  743. this._restoreFrozenNodes();
  744. }
  745. this.body.emitter.emit('stabilizationIterationsDone');
  746. this.body.emitter.emit('_requestRedraw');
  747. if (this.stabilized === true) {
  748. this._emitStabilized();
  749. }
  750. else {
  751. this.startSimulation();
  752. }
  753. this.ready = true;
  754. }
  755. }
  756. export default PhysicsEngine;