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.

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