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.

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