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.

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