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.

435 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.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. thetaInverted: 1 / 0.5, // inverted to save time during calculation
  28. gravitationalConstant: -2000,
  29. centralGravity: 0.3,
  30. springLength: 95,
  31. springConstant: 0.04,
  32. damping: 0.09
  33. },
  34. repulsion: {
  35. centralGravity: 0.0,
  36. springLength: 200,
  37. springConstant: 0.05,
  38. nodeDistance: 100,
  39. damping: 0.09
  40. },
  41. hierarchicalRepulsion: {
  42. centralGravity: 0.0,
  43. springLength: 100,
  44. springConstant: 0.01,
  45. nodeDistance: 150,
  46. damping: 0.09
  47. },
  48. solver: 'BarnesHut',
  49. timestep: 0.5,
  50. maxVelocity: 50,
  51. minVelocity: 0.1, // px/s
  52. stabilization: {
  53. enabled: true,
  54. iterations: 1000, // maximum number of iteration to stabilize
  55. updateInterval: 100,
  56. onlyDynamicEdges: false,
  57. zoomExtent: true
  58. }
  59. }
  60. util.extend(this.options, this.defaultOptions);
  61. this.body.emitter.on("initPhysics", () => {this.initPhysics();});
  62. this.body.emitter.on("resetPhysics", () => {this.stopSimulation(); this.ready = false;});
  63. this.body.emitter.on("startSimulation", () => {
  64. if (this.ready === true) {
  65. this.stabilized = false;
  66. this.runSimulation();
  67. }
  68. })
  69. this.body.emitter.on("stopSimulation", () => {this.stopSimulation();});
  70. }
  71. setOptions(options) {
  72. if (options !== undefined) {
  73. util.selectiveNotDeepExtend(['stabilization'],this.options, options);
  74. util.mergeOptions(this.options, options, 'stabilization')
  75. }
  76. this.init();
  77. }
  78. init() {
  79. var options;
  80. if (this.options.solver == "repulsion") {
  81. options = this.options.repulsion;
  82. this.nodesSolver = new Repulsion(this.body, this.physicsBody, options);
  83. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  84. }
  85. else if (this.options.solver == "hierarchicalRepulsion") {
  86. options = this.options.hierarchicalRepulsion;
  87. this.nodesSolver = new HierarchicalRepulsion(this.body, this.physicsBody, options);
  88. this.edgesSolver = new HierarchicalSpringSolver(this.body, this.physicsBody, options);
  89. }
  90. else { // barnesHut
  91. options = this.options.barnesHut;
  92. this.nodesSolver = new BarnesHutSolver(this.body, this.physicsBody, options);
  93. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  94. }
  95. this.gravitySolver = new CentralGravitySolver(this.body, this.physicsBody, options);
  96. this.modelOptions = options;
  97. }
  98. initPhysics() {
  99. this.stabilized = false;
  100. if (this.options.stabilization.enabled === true) {
  101. this.stabilize();
  102. }
  103. else {
  104. this.ready = true;
  105. this.body.emitter.emit("zoomExtent", {duration:0}, true)
  106. this.runSimulation();
  107. }
  108. }
  109. stopSimulation() {
  110. this.stabilized = true;
  111. if (this.viewFunction !== undefined) {
  112. this.body.emitter.off("initRedraw", this.viewFunction);
  113. this.viewFunction = undefined;
  114. this.body.emitter.emit("_stopRendering");
  115. }
  116. }
  117. runSimulation() {
  118. if (this.viewFunction === undefined) {
  119. this.viewFunction = this.simulationStep.bind(this);
  120. this.body.emitter.on("initRedraw", this.viewFunction);
  121. this.body.emitter.emit("_startRendering");
  122. }
  123. }
  124. simulationStep() {
  125. // check if the physics have settled
  126. var startTime = Date.now();
  127. this.physicsTick();
  128. var physicsTime = Date.now() - startTime;
  129. // run double speed if it is a little graph
  130. if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed == true) && this.stabilized === false) {
  131. this.physicsTick();
  132. // this makes sure there is no jitter. The decision is taken once to run it at double speed.
  133. this.runDoubleSpeed = true;
  134. }
  135. if (this.stabilized === true) {
  136. if (this.stabilizationIterations > 1) {
  137. // trigger the "stabilized" event.
  138. // The event is triggered on the next tick, to prevent the case that
  139. // it is fired while initializing the Network, in which case you would not
  140. // be able to catch it
  141. var me = this;
  142. var params = {
  143. iterations: this.stabilizationIterations
  144. };
  145. this.stabilizationIterations = 0;
  146. this.startedStabilization = false;
  147. setTimeout(function () {
  148. me.body.emitter.emit("stabilized", params);
  149. }, 0);
  150. }
  151. else {
  152. this.stabilizationIterations = 0;
  153. }
  154. this.stopSimulation();
  155. }
  156. }
  157. /**
  158. * A single simulation step (or "tick") in the physics simulation
  159. *
  160. * @private
  161. */
  162. physicsTick() {
  163. if (this.stabilized === false) {
  164. this.calculateForces();
  165. this.stabilized = this.moveNodes();
  166. // determine if the network has stabilzied
  167. if (this.stabilized === true) {
  168. this.revert();
  169. }
  170. else {
  171. // this is here to ensure that there is no start event when the network is already stable.
  172. if (this.startedStabilization == false) {
  173. this.body.emitter.emit("startStabilizing");
  174. this.startedStabilization = true;
  175. }
  176. }
  177. this.stabilizationIterations++;
  178. }
  179. }
  180. /**
  181. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  182. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  183. * This function joins the datanodes and invisible (called support) nodes into one object.
  184. * We do this so we do not contaminate this.body.nodes with the support nodes.
  185. *
  186. * @private
  187. */
  188. updatePhysicsIndices() {
  189. this.physicsBody.forces = {};
  190. this.physicsBody.physicsNodeIndices = [];
  191. this.physicsBody.physicsEdgeIndices = [];
  192. let nodes = this.body.nodes;
  193. let edges = this.body.edges;
  194. // get node indices for physics
  195. for (let nodeId in nodes) {
  196. if (nodes.hasOwnProperty(nodeId)) {
  197. if (nodes[nodeId].options.physics === true) {
  198. this.physicsBody.physicsNodeIndices.push(nodeId);
  199. }
  200. }
  201. }
  202. // get edge indices for physics
  203. for (let edgeId in edges) {
  204. if (edges.hasOwnProperty(edgeId)) {
  205. if (edges[edgeId].options.physics === true) {
  206. this.physicsBody.physicsEdgeIndices.push(edgeId);
  207. }
  208. }
  209. }
  210. // get the velocity and the forces vector
  211. for (let i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) {
  212. let nodeId = this.physicsBody.physicsNodeIndices[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 (nodes[nodeId] === undefined) {
  222. delete this.physicsBody.velocities[nodeId];
  223. }
  224. }
  225. }
  226. revert() {
  227. var nodeIds = Object.keys(this.previousStates);
  228. var nodes = this.body.nodes;
  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.physicsNodeIndices;
  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.body.nodes[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.options.fixed.x === false) {
  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.options.fixed.y === false) {
  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 && nodes[id].y) {
  314. this.freezeCache[id] = {x:nodes[id].options.fixed.x,y:nodes[id].options.fixed.y};
  315. nodes[id].options.fixed.x = true;
  316. nodes[id].options.fixed.y = true;
  317. }
  318. }
  319. }
  320. }
  321. /**
  322. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  323. *
  324. * @private
  325. */
  326. _restoreFrozenNodes() {
  327. var nodes = this.body.nodes;
  328. for (var id in nodes) {
  329. if (nodes.hasOwnProperty(id)) {
  330. if (this.freezeCache[id] !== undefined) {
  331. nodes[id].options.fixed.x = this.freezeCache[id].x;
  332. nodes[id].options.fixed.y = this.freezeCache[id].y;
  333. }
  334. }
  335. }
  336. this.freezeCache = {};
  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. this.ready = true;
  374. }
  375. }
  376. export default PhysicsEngine;