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.

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