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.

890 lines
28 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. this.updateWorkerFixed();
  354. // adaptivity means the timestep adapts to the situation, only applicable for stabilization
  355. if (this.adaptiveTimestep === true && this.adaptiveTimestepEnabled === true) {
  356. // this is the factor for increasing the timestep on success.
  357. let factor = 1.2;
  358. // we assume the adaptive interval is
  359. if (this.adaptiveCounter % this.adaptiveInterval === 0) { // we leave the timestep stable for "interval" iterations.
  360. // first the big step and revert. Revert saves the reference state.
  361. this.timestep = 2 * this.timestep;
  362. this.calculateForces();
  363. this.moveNodes();
  364. this.revert();
  365. // now the normal step. Since this is the last step, it is the more stable one and we will take this.
  366. this.timestep = 0.5 * this.timestep;
  367. // since it's half the step, we do it twice.
  368. this.calculateForces();
  369. this.moveNodes();
  370. this.calculateForces();
  371. this.moveNodes();
  372. // we compare the two steps. if it is acceptable we double the step.
  373. if (this._evaluateStepQuality() === true) {
  374. this.timestep = factor * this.timestep;
  375. }
  376. else {
  377. // if not, we decrease the step to a minimum of the options timestep.
  378. // if the decreased timestep is smaller than the options step, we do not reset the counter
  379. // we assume that the options timestep is stable enough.
  380. if (this.timestep/factor < this.options.timestep) {
  381. this.timestep = this.options.timestep;
  382. }
  383. else {
  384. // if the timestep was larger than 2 times the option one we check the adaptivity again to ensure
  385. // that large instabilities do not form.
  386. this.adaptiveCounter = -1; // check again next iteration
  387. this.timestep = Math.max(this.options.timestep, this.timestep/factor);
  388. }
  389. }
  390. }
  391. else {
  392. // normal step, keeping timestep constant
  393. this.calculateForces();
  394. this.moveNodes();
  395. }
  396. // increment the counter
  397. this.adaptiveCounter += 1;
  398. }
  399. else {
  400. // case for the static timestep, we reset it to the one in options and take a normal step.
  401. this.timestep = this.options.timestep;
  402. if (this.physicsWorker) {
  403. // console.log('asking working to do a physics iteration');
  404. this.physicsWorker.postMessage({type: 'calculateForces'});
  405. } else {
  406. this.calculateForces();
  407. this.moveNodes();
  408. }
  409. }
  410. // determine if the network has stabilzied
  411. if (this.stabilized === true) {
  412. this.revert();
  413. }
  414. this.stabilizationIterations++;
  415. }
  416. }
  417. /**
  418. * 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.
  419. *
  420. * @private
  421. */
  422. updatePhysicsData() {
  423. let nodes = this.body.nodes;
  424. let edges = this.body.edges;
  425. this.physicsBody.forces = {};
  426. this.physicsBody.physicsNodeIndices = [];
  427. this.physicsBody.physicsEdgeIndices = [];
  428. if (this.physicsWorker) {
  429. this.physicsWorkerNodes = {};
  430. var physicsWorkerEdges = {};
  431. for (let nodeId in nodes) {
  432. if (nodes.hasOwnProperty(nodeId)) {
  433. let node = nodes[nodeId];
  434. if (node.options.physics === true) {
  435. // for updating fixed later
  436. this.physicsBody.physicsNodeIndices.push(nodeId);
  437. this.physicsWorkerNodes[nodeId] = {
  438. id: node.id,
  439. x: node.x,
  440. y: node.y,
  441. options: {
  442. fixed: {
  443. x: node.options.fixed.x,
  444. y: node.options.fixed.y
  445. },
  446. mass: node.options.mass
  447. }
  448. }
  449. }
  450. }
  451. }
  452. for (let edgeId in edges) {
  453. if (edges.hasOwnProperty(edgeId)) {
  454. let edge = edges[edgeId];
  455. if (edge.options.physics === true && edge.connected === true) {
  456. physicsWorkerEdges[edgeId] = {
  457. connected: edge.connected,
  458. id: edge.id,
  459. edgeType: {},
  460. toId: edge.toId,
  461. fromId: edge.fromId,
  462. to: {
  463. id: edge.to.id
  464. },
  465. from: {
  466. id: edge.from.id
  467. },
  468. options: {
  469. length: edge.length
  470. }
  471. };
  472. if (edge.edgeType.via) {
  473. physicsWorkerEdges[edgeId].edgeType = {
  474. via: {
  475. id: edge.edgeType.via.id
  476. }
  477. }
  478. }
  479. }
  480. }
  481. }
  482. this.physicsWorker.postMessage({
  483. type: 'physicsObjects',
  484. data: {
  485. nodes: this.physicsWorkerNodes,
  486. edges: physicsWorkerEdges
  487. }
  488. });
  489. } else {
  490. // get node indices for physics
  491. for (let nodeId in nodes) {
  492. if (nodes.hasOwnProperty(nodeId)) {
  493. if (nodes[nodeId].options.physics === true) {
  494. this.physicsBody.physicsNodeIndices.push(nodeId);
  495. }
  496. }
  497. }
  498. // get edge indices for physics
  499. for (let edgeId in edges) {
  500. if (edges.hasOwnProperty(edgeId)) {
  501. if (edges[edgeId].options.physics === true) {
  502. this.physicsBody.physicsEdgeIndices.push(edgeId);
  503. }
  504. }
  505. }
  506. // get the velocity and the forces vector
  507. for (let i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) {
  508. let nodeId = this.physicsBody.physicsNodeIndices[i];
  509. this.physicsBody.forces[nodeId] = {x: 0, y: 0};
  510. // forces can be reset because they are recalculated. Velocities have to persist.
  511. if (this.physicsBody.velocities[nodeId] === undefined) {
  512. this.physicsBody.velocities[nodeId] = {x: 0, y: 0};
  513. }
  514. }
  515. // clean deleted nodes from the velocity vector
  516. for (let nodeId in this.physicsBody.velocities) {
  517. if (nodes[nodeId] === undefined) {
  518. delete this.physicsBody.velocities[nodeId];
  519. }
  520. }
  521. }
  522. }
  523. updateWorkerPositions() {
  524. if (this.physicsWorker) {
  525. for (let i = 0; i < this.draggingNodes.length; i++) {
  526. let nodeId = this.draggingNodes[i];
  527. let node = this.body.nodes[nodeId];
  528. this.physicsWorker.postMessage({
  529. type: 'updatePositions',
  530. data: {
  531. id: nodeId,
  532. x: node.x,
  533. y: node.y
  534. }
  535. });
  536. }
  537. }
  538. }
  539. updateWorkerFixed() {
  540. if (this.physicsWorker) {
  541. for (let i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) {
  542. let nodeId = this.physicsBody.physicsNodeIndices[i];
  543. let physicsNode = this.physicsWorkerNodes[nodeId];
  544. let node = this.body.nodes[nodeId];
  545. if (physicsNode.options.fixed.x !== node.options.fixed.x ||
  546. physicsNode.options.fixed.y !== node.options.fixed.y)
  547. {
  548. let fixed = {
  549. x: node.options.fixed.x,
  550. y: node.options.fixed.y
  551. };
  552. physicsNode.options.fixed.x = fixed.x;
  553. physicsNode.options.fixed.y = fixed.y;
  554. this.physicsWorker.postMessage({
  555. type: 'updateFixed',
  556. data: {
  557. id: nodeId,
  558. x: node.x,
  559. y: node.y,
  560. fixed: fixed
  561. }
  562. });
  563. }
  564. }
  565. }
  566. }
  567. /**
  568. * Revert the simulation one step. This is done so after stabilization, every new start of the simulation will also say stabilized.
  569. */
  570. revert() {
  571. var nodeIds = Object.keys(this.previousStates);
  572. var nodes = this.body.nodes;
  573. var velocities = this.physicsBody.velocities;
  574. this.referenceState = {};
  575. for (let i = 0; i < nodeIds.length; i++) {
  576. let nodeId = nodeIds[i];
  577. if (nodes[nodeId] !== undefined) {
  578. if (nodes[nodeId].options.physics === true) {
  579. this.referenceState[nodeId] = {
  580. positions: {x:nodes[nodeId].x, y:nodes[nodeId].y}
  581. };
  582. velocities[nodeId].x = this.previousStates[nodeId].vx;
  583. velocities[nodeId].y = this.previousStates[nodeId].vy;
  584. nodes[nodeId].x = this.previousStates[nodeId].x;
  585. nodes[nodeId].y = this.previousStates[nodeId].y;
  586. }
  587. }
  588. else {
  589. delete this.previousStates[nodeId];
  590. }
  591. }
  592. }
  593. /**
  594. * This compares the reference state to the current state
  595. */
  596. _evaluateStepQuality() {
  597. let dx, dy, dpos;
  598. let nodes = this.body.nodes;
  599. let reference = this.referenceState;
  600. let posThreshold = 0.3;
  601. for (let nodeId in this.referenceState) {
  602. if (this.referenceState.hasOwnProperty(nodeId) && nodes[nodeId] !== undefined) {
  603. dx = nodes[nodeId].x - reference[nodeId].positions.x;
  604. dy = nodes[nodeId].y - reference[nodeId].positions.y;
  605. dpos = Math.sqrt(Math.pow(dx,2) + Math.pow(dy,2))
  606. if (dpos > posThreshold) {
  607. return false;
  608. }
  609. }
  610. }
  611. return true;
  612. }
  613. /**
  614. * move the nodes one timestap and check if they are stabilized
  615. * @returns {boolean}
  616. */
  617. moveNodes() {
  618. var nodeIndices = this.physicsBody.physicsNodeIndices;
  619. var maxVelocity = this.options.maxVelocity ? this.options.maxVelocity : 1e9;
  620. var maxNodeVelocity = 0;
  621. var averageNodeVelocity = 0;
  622. // the velocity threshold (energy in the system) for the adaptivity toggle
  623. var velocityAdaptiveThreshold = 5;
  624. for (let i = 0; i < nodeIndices.length; i++) {
  625. let nodeId = nodeIndices[i];
  626. let nodeVelocity = this._performStep(nodeId, maxVelocity);
  627. // stabilized is true if stabilized is true and velocity is smaller than vmin --> all nodes must be stabilized
  628. maxNodeVelocity = Math.max(maxNodeVelocity,nodeVelocity);
  629. averageNodeVelocity += nodeVelocity;
  630. }
  631. // evaluating the stabilized and adaptiveTimestepEnabled conditions
  632. this.adaptiveTimestepEnabled = (averageNodeVelocity/nodeIndices.length) < velocityAdaptiveThreshold;
  633. this.stabilized = maxNodeVelocity < this.options.minVelocity;
  634. }
  635. /**
  636. * Perform the actual step
  637. *
  638. * @param nodeId
  639. * @param maxVelocity
  640. * @returns {number}
  641. * @private
  642. */
  643. _performStep(nodeId,maxVelocity) {
  644. let node = this.body.nodes[nodeId];
  645. let timestep = this.timestep;
  646. let forces = this.physicsBody.forces;
  647. let velocities = this.physicsBody.velocities;
  648. // store the state so we can revert
  649. this.previousStates[nodeId] = {x:node.x, y:node.y, vx:velocities[nodeId].x, vy:velocities[nodeId].y};
  650. if (node.options.fixed.x === false) {
  651. let dx = this.modelOptions.damping * velocities[nodeId].x; // damping force
  652. let ax = (forces[nodeId].x - dx) / node.options.mass; // acceleration
  653. velocities[nodeId].x += ax * timestep; // velocity
  654. velocities[nodeId].x = (Math.abs(velocities[nodeId].x) > maxVelocity) ? ((velocities[nodeId].x > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].x;
  655. node.x += velocities[nodeId].x * timestep; // position
  656. }
  657. else {
  658. forces[nodeId].x = 0;
  659. velocities[nodeId].x = 0;
  660. }
  661. if (node.options.fixed.y === false) {
  662. let dy = this.modelOptions.damping * velocities[nodeId].y; // damping force
  663. let ay = (forces[nodeId].y - dy) / node.options.mass; // acceleration
  664. velocities[nodeId].y += ay * timestep; // velocity
  665. velocities[nodeId].y = (Math.abs(velocities[nodeId].y) > maxVelocity) ? ((velocities[nodeId].y > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].y;
  666. node.y += velocities[nodeId].y * timestep; // position
  667. }
  668. else {
  669. forces[nodeId].y = 0;
  670. velocities[nodeId].y = 0;
  671. }
  672. let totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x,2) + Math.pow(velocities[nodeId].y,2));
  673. return totalVelocity;
  674. }
  675. /**
  676. * calculate the forces for one physics iteration.
  677. */
  678. calculateForces() {
  679. this.gravitySolver.solve();
  680. this.nodesSolver.solve();
  681. this.edgesSolver.solve();
  682. }
  683. /**
  684. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  685. * because only the supportnodes for the smoothCurves have to settle.
  686. *
  687. * @private
  688. */
  689. _freezeNodes() {
  690. var nodes = this.body.nodes;
  691. for (var id in nodes) {
  692. if (nodes.hasOwnProperty(id)) {
  693. if (nodes[id].x && nodes[id].y) {
  694. this.freezeCache[id] = {x:nodes[id].options.fixed.x,y:nodes[id].options.fixed.y};
  695. nodes[id].options.fixed.x = true;
  696. nodes[id].options.fixed.y = true;
  697. }
  698. }
  699. }
  700. }
  701. /**
  702. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  703. *
  704. * @private
  705. */
  706. _restoreFrozenNodes() {
  707. var nodes = this.body.nodes;
  708. for (var id in nodes) {
  709. if (nodes.hasOwnProperty(id)) {
  710. if (this.freezeCache[id] !== undefined) {
  711. nodes[id].options.fixed.x = this.freezeCache[id].x;
  712. nodes[id].options.fixed.y = this.freezeCache[id].y;
  713. }
  714. }
  715. }
  716. this.freezeCache = {};
  717. }
  718. /**
  719. * Find a stable position for all nodes
  720. * @private
  721. */
  722. stabilize(iterations = this.options.stabilization.iterations) {
  723. if (typeof iterations !== 'number') {
  724. console.log('The stabilize method needs a numeric amount of iterations. Switching to default: ', this.options.stabilization.iterations);
  725. iterations = this.options.stabilization.iterations;
  726. }
  727. if (this.physicsBody.physicsNodeIndices.length === 0) {
  728. this.ready = true;
  729. return;
  730. }
  731. // enable adaptive timesteps
  732. this.adaptiveTimestep = true && this.options.adaptiveTimestep;
  733. // this sets the width of all nodes initially which could be required for the avoidOverlap
  734. this.body.emitter.emit("_resizeNodes");
  735. // stop the render loop
  736. this.stopSimulation();
  737. // set stabilze to false
  738. this.stabilized = false;
  739. // block redraw requests
  740. this.body.emitter.emit('_blockRedraw');
  741. this.targetIterations = iterations;
  742. // start the stabilization
  743. if (this.options.stabilization.onlyDynamicEdges === true) {
  744. this._freezeNodes();
  745. }
  746. this.stabilizationIterations = 0;
  747. setTimeout(() => this._stabilizationBatch(),0);
  748. }
  749. /**
  750. * One batch of stabilization
  751. * @private
  752. */
  753. _stabilizationBatch() {
  754. // this is here to ensure that there is at least one start event.
  755. if (this.startedStabilization === false) {
  756. this.body.emitter.emit('startStabilizing');
  757. this.startedStabilization = true;
  758. }
  759. var count = 0;
  760. while (this.stabilized === false && count < this.options.stabilization.updateInterval && this.stabilizationIterations < this.targetIterations) {
  761. this.physicsTick();
  762. count++;
  763. }
  764. if (this.stabilized === false && this.stabilizationIterations < this.targetIterations) {
  765. this.body.emitter.emit('stabilizationProgress', {iterations: this.stabilizationIterations, total: this.targetIterations});
  766. setTimeout(this._stabilizationBatch.bind(this),0);
  767. }
  768. else {
  769. this._finalizeStabilization();
  770. }
  771. }
  772. /**
  773. * Wrap up the stabilization, fit and emit the events.
  774. * @private
  775. */
  776. _finalizeStabilization() {
  777. this.body.emitter.emit('_allowRedraw');
  778. if (this.options.stabilization.fit === true) {
  779. this.body.emitter.emit('fit');
  780. }
  781. if (this.options.stabilization.onlyDynamicEdges === true) {
  782. this._restoreFrozenNodes();
  783. }
  784. this.body.emitter.emit('stabilizationIterationsDone');
  785. this.body.emitter.emit('_requestRedraw');
  786. if (this.stabilized === true) {
  787. this._emitStabilized();
  788. }
  789. else {
  790. this.startSimulation();
  791. }
  792. this.ready = true;
  793. }
  794. }
  795. export default PhysicsEngine;