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.

499 lines
15 KiB

  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. var util = require('../../util');
  8. class PhysicsEngine {
  9. constructor(body) {
  10. this.body = body;
  11. this.physicsBody = {physicsNodeIndices:[], physicsEdgeIndices:[], forces: {}, velocities: {}};
  12. this.physicsEnabled = true;
  13. this.simulationInterval = 1000 / 60;
  14. this.requiresTimeout = true;
  15. this.previousStates = {};
  16. this.freezeCache = {};
  17. this.renderTimer = undefined;
  18. this.stabilized = false;
  19. this.stabilizationIterations = 0;
  20. this.ready = false; // will be set to true if the stabilize
  21. // default options
  22. this.options = {};
  23. this.defaultOptions = {
  24. barnesHut: {
  25. theta: 0.5,
  26. gravitationalConstant: -2000,
  27. centralGravity: 0.3,
  28. springLength: 95,
  29. springConstant: 0.04,
  30. damping: 0.09
  31. },
  32. repulsion: {
  33. centralGravity: 0.2,
  34. springLength: 200,
  35. springConstant: 0.05,
  36. nodeDistance: 100,
  37. damping: 0.09
  38. },
  39. hierarchicalRepulsion: {
  40. centralGravity: 0.0,
  41. springLength: 100,
  42. springConstant: 0.01,
  43. nodeDistance: 120,
  44. damping: 0.09
  45. },
  46. maxVelocity: 50,
  47. minVelocity: 0.1, // px/s
  48. solver: 'barnesHut',
  49. stabilization: {
  50. enabled: true,
  51. iterations: 1000, // maximum number of iteration to stabilize
  52. updateInterval: 100,
  53. onlyDynamicEdges: false,
  54. zoomExtent: true
  55. },
  56. timestep: 0.5
  57. }
  58. util.extend(this.options, this.defaultOptions);
  59. this.body.emitter.on('initPhysics', () => {this.initPhysics();});
  60. this.body.emitter.on('resetPhysics', () => {this.stopSimulation(); this.ready = false;});
  61. this.body.emitter.on('disablePhysics', () => {this.physicsEnabled = false; this.stopSimulation();});
  62. this.body.emitter.on('restorePhysics', () => {
  63. this.setOptions(this.options);
  64. if (this.ready === true) {
  65. this.startSimulation();
  66. }
  67. });
  68. this.body.emitter.on('startSimulation', () => {
  69. if (this.ready === true) {
  70. this.startSimulation();
  71. }
  72. })
  73. this.body.emitter.on('stopSimulation', () => {this.stopSimulation();});
  74. }
  75. setOptions(options) {
  76. if (options === false) {
  77. this.physicsEnabled = false;
  78. this.stopSimulation();
  79. }
  80. else {
  81. this.physicsEnabled = true;
  82. if (options !== undefined) {
  83. util.selectiveNotDeepExtend(['stabilization'], this.options, options);
  84. util.mergeOptions(this.options, options, 'stabilization')
  85. }
  86. this.init();
  87. }
  88. }
  89. init() {
  90. var options;
  91. if (this.options.solver === 'repulsion') {
  92. options = this.options.repulsion;
  93. this.nodesSolver = new Repulsion(this.body, this.physicsBody, options);
  94. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  95. }
  96. else if (this.options.solver === 'hierarchicalRepulsion') {
  97. options = this.options.hierarchicalRepulsion;
  98. this.nodesSolver = new HierarchicalRepulsion(this.body, this.physicsBody, options);
  99. this.edgesSolver = new HierarchicalSpringSolver(this.body, this.physicsBody, options);
  100. }
  101. else { // barnesHut
  102. options = this.options.barnesHut;
  103. this.nodesSolver = new BarnesHutSolver(this.body, this.physicsBody, options);
  104. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  105. }
  106. this.gravitySolver = new CentralGravitySolver(this.body, this.physicsBody, options);
  107. this.modelOptions = options;
  108. }
  109. initPhysics() {
  110. if (this.physicsEnabled === true) {
  111. if (this.options.stabilization.enabled === true) {
  112. this.stabilize();
  113. }
  114. else {
  115. this.stabilized = false;
  116. this.ready = true;
  117. this.body.emitter.emit('zoomExtent', {duration: 0}, true)
  118. this.startSimulation();
  119. }
  120. }
  121. else {
  122. this.ready = true;
  123. this.body.emitter.emit('_redraw');
  124. }
  125. }
  126. /**
  127. * Start the simulation
  128. */
  129. startSimulation() {
  130. if (this.physicsEnabled === true) {
  131. this.stabilized = false;
  132. if (this.viewFunction === undefined) {
  133. this.viewFunction = this.simulationStep.bind(this);
  134. this.body.emitter.on('initRedraw', this.viewFunction);
  135. this.body.emitter.emit('_startRendering');
  136. }
  137. }
  138. else {
  139. this.body.emitter.emit('_redraw');
  140. }
  141. }
  142. /**
  143. * Stop the simulation, force stabilization.
  144. */
  145. stopSimulation() {
  146. this.stabilized = true;
  147. this._emitStabilized();
  148. if (this.viewFunction !== undefined) {
  149. this.body.emitter.off('initRedraw', this.viewFunction);
  150. this.viewFunction = undefined;
  151. this.body.emitter.emit('_stopRendering');
  152. }
  153. }
  154. /**
  155. * The viewFunction inserts this step into each renderloop. It calls the physics tick and handles the cleanup at stabilized.
  156. *
  157. */
  158. simulationStep() {
  159. // check if the physics have settled
  160. var startTime = Date.now();
  161. this.physicsTick();
  162. var physicsTime = Date.now() - startTime;
  163. // run double speed if it is a little graph
  164. if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed === true) && this.stabilized === false) {
  165. this.physicsTick();
  166. // this makes sure there is no jitter. The decision is taken once to run it at double speed.
  167. this.runDoubleSpeed = true;
  168. }
  169. if (this.stabilized === true) {
  170. if (this.stabilizationIterations > 1) {
  171. // trigger the 'stabilized' event.
  172. // The event is triggered on the next tick, to prevent the case that
  173. // it is fired while initializing the Network, in which case you would not
  174. // be able to catch it
  175. this.stabilizationIterations = 0;
  176. this.startedStabilization = false;
  177. this._emitStabilized();
  178. }
  179. else {
  180. this.stabilizationIterations = 0;
  181. }
  182. this.stopSimulation();
  183. }
  184. }
  185. _emitStabilized() {
  186. if (this.stabilizationIterations > 1) {
  187. setTimeout(() => {
  188. this.body.emitter.emit('stabilized', {iterations: this.stabilizationIterations});
  189. }, 0);
  190. }
  191. }
  192. /**
  193. * A single simulation step (or 'tick') in the physics simulation
  194. *
  195. * @private
  196. */
  197. physicsTick() {
  198. if (this.stabilized === false) {
  199. this.calculateForces();
  200. this.stabilized = this.moveNodes();
  201. // determine if the network has stabilzied
  202. if (this.stabilized === true) {
  203. this.revert();
  204. }
  205. else {
  206. // this is here to ensure that there is no start event when the network is already stable.
  207. if (this.startedStabilization === false) {
  208. this.body.emitter.emit('startStabilizing');
  209. this.startedStabilization = true;
  210. }
  211. }
  212. this.stabilizationIterations++;
  213. }
  214. }
  215. /**
  216. * 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.
  217. *
  218. * @private
  219. */
  220. updatePhysicsIndices() {
  221. this.physicsBody.forces = {};
  222. this.physicsBody.physicsNodeIndices = [];
  223. this.physicsBody.physicsEdgeIndices = [];
  224. let nodes = this.body.nodes;
  225. let edges = this.body.edges;
  226. // get node indices for physics
  227. for (let nodeId in nodes) {
  228. if (nodes.hasOwnProperty(nodeId)) {
  229. if (nodes[nodeId].options.physics === true) {
  230. this.physicsBody.physicsNodeIndices.push(nodeId);
  231. }
  232. }
  233. }
  234. // get edge indices for physics
  235. for (let edgeId in edges) {
  236. if (edges.hasOwnProperty(edgeId)) {
  237. if (edges[edgeId].options.physics === true) {
  238. this.physicsBody.physicsEdgeIndices.push(edgeId);
  239. }
  240. }
  241. }
  242. // get the velocity and the forces vector
  243. for (let i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) {
  244. let nodeId = this.physicsBody.physicsNodeIndices[i];
  245. this.physicsBody.forces[nodeId] = {x:0,y:0};
  246. // forces can be reset because they are recalculated. Velocities have to persist.
  247. if (this.physicsBody.velocities[nodeId] === undefined) {
  248. this.physicsBody.velocities[nodeId] = {x:0,y:0};
  249. }
  250. }
  251. // clean deleted nodes from the velocity vector
  252. for (let nodeId in this.physicsBody.velocities) {
  253. if (nodes[nodeId] === undefined) {
  254. delete this.physicsBody.velocities[nodeId];
  255. }
  256. }
  257. }
  258. /**
  259. * Revert the simulation one step. This is done so after stabilization, every new start of the simulation will also say stabilized.
  260. */
  261. revert() {
  262. var nodeIds = Object.keys(this.previousStates);
  263. var nodes = this.body.nodes;
  264. var velocities = this.physicsBody.velocities;
  265. for (let i = 0; i < nodeIds.length; i++) {
  266. let nodeId = nodeIds[i];
  267. if (nodes[nodeId] !== undefined) {
  268. if (nodes[nodeId].options.physics === true) {
  269. velocities[nodeId].x = this.previousStates[nodeId].vx;
  270. velocities[nodeId].y = this.previousStates[nodeId].vy;
  271. nodes[nodeId].x = this.previousStates[nodeId].x;
  272. nodes[nodeId].y = this.previousStates[nodeId].y;
  273. }
  274. }
  275. else {
  276. delete this.previousStates[nodeId];
  277. }
  278. }
  279. }
  280. /**
  281. * move the nodes one timestap and check if they are stabilized
  282. * @returns {boolean}
  283. */
  284. moveNodes() {
  285. var nodesPresent = false;
  286. var nodeIndices = this.physicsBody.physicsNodeIndices;
  287. var maxVelocity = this.options.maxVelocity ? this.options.maxVelocity : 1e9;
  288. var stabilized = true;
  289. var vminCorrected = this.options.minVelocity / Math.max(this.body.view.scale,0.05);
  290. for (let i = 0; i < nodeIndices.length; i++) {
  291. let nodeId = nodeIndices[i];
  292. let nodeVelocity = this._performStep(nodeId, maxVelocity);
  293. // stabilized is true if stabilized is true and velocity is smaller than vmin --> all nodes must be stabilized
  294. stabilized = nodeVelocity < vminCorrected && stabilized === true;
  295. nodesPresent = true;
  296. }
  297. if (nodesPresent === true) {
  298. if (vminCorrected > 0.5*this.options.maxVelocity) {
  299. return false;
  300. }
  301. else {
  302. return stabilized;
  303. }
  304. }
  305. return true;
  306. }
  307. /**
  308. * Perform the actual step
  309. *
  310. * @param nodeId
  311. * @param maxVelocity
  312. * @returns {number}
  313. * @private
  314. */
  315. _performStep(nodeId,maxVelocity) {
  316. var node = this.body.nodes[nodeId];
  317. var timestep = this.options.timestep;
  318. var forces = this.physicsBody.forces;
  319. var velocities = this.physicsBody.velocities;
  320. // store the state so we can revert
  321. this.previousStates[nodeId] = {x:node.x, y:node.y, vx:velocities[nodeId].x, vy:velocities[nodeId].y};
  322. if (node.options.fixed.x === false) {
  323. let dx = this.modelOptions.damping * velocities[nodeId].x; // damping force
  324. let ax = (forces[nodeId].x - dx) / node.options.mass; // acceleration
  325. velocities[nodeId].x += ax * timestep; // velocity
  326. velocities[nodeId].x = (Math.abs(velocities[nodeId].x) > maxVelocity) ? ((velocities[nodeId].x > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].x;
  327. node.x += velocities[nodeId].x * timestep; // position
  328. }
  329. else {
  330. forces[nodeId].x = 0;
  331. velocities[nodeId].x = 0;
  332. }
  333. if (node.options.fixed.y === false) {
  334. let dy = this.modelOptions.damping * velocities[nodeId].y; // damping force
  335. let ay = (forces[nodeId].y - dy) / node.options.mass; // acceleration
  336. velocities[nodeId].y += ay * timestep; // velocity
  337. velocities[nodeId].y = (Math.abs(velocities[nodeId].y) > maxVelocity) ? ((velocities[nodeId].y > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].y;
  338. node.y += velocities[nodeId].y * timestep; // position
  339. }
  340. else {
  341. forces[nodeId].y = 0;
  342. velocities[nodeId].y = 0;
  343. }
  344. var totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x,2) + Math.pow(velocities[nodeId].y,2));
  345. return totalVelocity;
  346. }
  347. /**
  348. * calculate the forces for one physics iteration.
  349. */
  350. calculateForces() {
  351. this.gravitySolver.solve();
  352. this.nodesSolver.solve();
  353. this.edgesSolver.solve();
  354. }
  355. /**
  356. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  357. * because only the supportnodes for the smoothCurves have to settle.
  358. *
  359. * @private
  360. */
  361. _freezeNodes() {
  362. var nodes = this.body.nodes;
  363. for (var id in nodes) {
  364. if (nodes.hasOwnProperty(id)) {
  365. if (nodes[id].x && nodes[id].y) {
  366. this.freezeCache[id] = {x:nodes[id].options.fixed.x,y:nodes[id].options.fixed.y};
  367. nodes[id].options.fixed.x = true;
  368. nodes[id].options.fixed.y = true;
  369. }
  370. }
  371. }
  372. }
  373. /**
  374. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  375. *
  376. * @private
  377. */
  378. _restoreFrozenNodes() {
  379. var nodes = this.body.nodes;
  380. for (var id in nodes) {
  381. if (nodes.hasOwnProperty(id)) {
  382. if (this.freezeCache[id] !== undefined) {
  383. nodes[id].options.fixed.x = this.freezeCache[id].x;
  384. nodes[id].options.fixed.y = this.freezeCache[id].y;
  385. }
  386. }
  387. }
  388. this.freezeCache = {};
  389. }
  390. /**
  391. * Find a stable position for all nodes
  392. * @private
  393. */
  394. stabilize() {
  395. // stop the render loop
  396. this.stopSimulation();
  397. // set stabilze to false
  398. this.stabilized = false;
  399. // block redraw requests
  400. this.body.emitter.emit('_blockRedrawRequests');
  401. this.body.emitter.emit('startStabilizing');
  402. this.startedStabilization = true;
  403. // start the stabilization
  404. if (this.options.stabilization.onlyDynamicEdges === true) {
  405. this._freezeNodes();
  406. }
  407. this.stabilizationIterations = 0;
  408. setTimeout(this._stabilizationBatch.bind(this),0);
  409. }
  410. _stabilizationBatch() {
  411. var count = 0;
  412. while (this.stabilized === false && count < this.options.stabilization.updateInterval && this.stabilizationIterations < this.options.stabilization.iterations) {
  413. this.physicsTick();
  414. this.stabilizationIterations++;
  415. count++;
  416. }
  417. if (this.stabilized === false && this.stabilizationIterations < this.options.stabilization.iterations) {
  418. this.body.emitter.emit('stabilizationProgress', {iterations: this.stabilizationIterations, total: this.options.stabilization.iterations});
  419. setTimeout(this._stabilizationBatch.bind(this),0);
  420. }
  421. else {
  422. this._finalizeStabilization();
  423. }
  424. }
  425. _finalizeStabilization() {
  426. this.body.emitter.emit('_allowRedrawRequests');
  427. if (this.options.stabilization.zoomExtent === true) {
  428. this.body.emitter.emit('zoomExtent', {duration:0});
  429. }
  430. if (this.options.stabilization.onlyDynamicEdges === true) {
  431. this._restoreFrozenNodes();
  432. }
  433. this.body.emitter.emit('stabilizationIterationsDone');
  434. this.body.emitter.emit('_requestRedraw');
  435. this.ready = true;
  436. }
  437. }
  438. export default PhysicsEngine;