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.

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