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.

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