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.

453 lines
14 KiB

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