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.

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