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.

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