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.

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