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.

650 lines
20 KiB

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