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.

480 lines
15 KiB

  1. /**
  2. * Barnes Hut Solver
  3. */
  4. class BarnesHutSolver {
  5. /**
  6. * @param {Object} body
  7. * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
  8. * @param {Object} options
  9. */
  10. constructor(body, physicsBody, options) {
  11. this.body = body;
  12. this.physicsBody = physicsBody;
  13. this.barnesHutTree;
  14. this.setOptions(options);
  15. this.randomSeed = 5;
  16. // debug: show grid
  17. //this.body.emitter.on("afterDrawing", (ctx) => {this._debug(ctx,'#ff0000')})
  18. }
  19. /**
  20. *
  21. * @param {Object} options
  22. */
  23. setOptions(options) {
  24. this.options = options;
  25. this.thetaInversed = 1 / this.options.theta;
  26. this.overlapAvoidanceFactor = 1 - Math.max(0, Math.min(1,this.options.avoidOverlap)); // if 1 then min distance = 0.5, if 0.5 then min distance = 0.5 + 0.5*node.shape.radius
  27. }
  28. /**
  29. *
  30. * @returns {number} random integer
  31. */
  32. seededRandom() {
  33. var x = Math.sin(this.randomSeed++) * 10000;
  34. return x - Math.floor(x);
  35. }
  36. /**
  37. * This function calculates the forces the nodes apply on each other based on a gravitational model.
  38. * The Barnes Hut method is used to speed up this N-body simulation.
  39. *
  40. * @private
  41. */
  42. solve() {
  43. if (this.options.gravitationalConstant !== 0 && this.physicsBody.physicsNodeIndices.length > 0) {
  44. let node;
  45. let nodes = this.body.nodes;
  46. let nodeIndices = this.physicsBody.physicsNodeIndices;
  47. let nodeCount = nodeIndices.length;
  48. // create the tree
  49. let barnesHutTree = this._formBarnesHutTree(nodes, nodeIndices);
  50. // for debugging
  51. this.barnesHutTree = barnesHutTree;
  52. // place the nodes one by one recursively
  53. for (let i = 0; i < nodeCount; i++) {
  54. node = nodes[nodeIndices[i]];
  55. if (node.options.mass > 0) {
  56. // starting with root is irrelevant, it never passes the BarnesHutSolver condition
  57. this._getForceContribution(barnesHutTree.root.children.NW, node);
  58. this._getForceContribution(barnesHutTree.root.children.NE, node);
  59. this._getForceContribution(barnesHutTree.root.children.SW, node);
  60. this._getForceContribution(barnesHutTree.root.children.SE, node);
  61. }
  62. }
  63. }
  64. }
  65. /**
  66. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  67. * If a region contains a single node, we check if it is not itself, then we apply the force.
  68. *
  69. * @param {Object} parentBranch
  70. * @param {Node} node
  71. * @private
  72. */
  73. _getForceContribution(parentBranch, node) {
  74. // we get no force contribution from an empty region
  75. if (parentBranch.childrenCount > 0) {
  76. let dx, dy, distance;
  77. // get the distance from the center of mass to the node.
  78. dx = parentBranch.centerOfMass.x - node.x;
  79. dy = parentBranch.centerOfMass.y - node.y;
  80. distance = Math.sqrt(dx * dx + dy * dy);
  81. // BarnesHutSolver condition
  82. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  83. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  84. if (distance * parentBranch.calcSize > this.thetaInversed) {
  85. this._calculateForces(distance, dx, dy, node, parentBranch);
  86. }
  87. else {
  88. // Did not pass the condition, go into children if available
  89. if (parentBranch.childrenCount === 4) {
  90. this._getForceContribution(parentBranch.children.NW, node);
  91. this._getForceContribution(parentBranch.children.NE, node);
  92. this._getForceContribution(parentBranch.children.SW, node);
  93. this._getForceContribution(parentBranch.children.SE, node);
  94. }
  95. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  96. if (parentBranch.children.data.id != node.id) { // if it is not self
  97. this._calculateForces(distance, dx, dy, node, parentBranch);
  98. }
  99. }
  100. }
  101. }
  102. }
  103. /**
  104. * Calculate the forces based on the distance.
  105. *
  106. * @param {number} distance
  107. * @param {number} dx
  108. * @param {number} dy
  109. * @param {Node} node
  110. * @param {Object} parentBranch
  111. * @private
  112. */
  113. _calculateForces(distance, dx, dy, node, parentBranch) {
  114. if (distance === 0) {
  115. distance = 0.1;
  116. dx = distance;
  117. }
  118. if (this.overlapAvoidanceFactor < 1 && node.shape.radius) {
  119. distance = Math.max(0.1 + (this.overlapAvoidanceFactor * node.shape.radius), distance - node.shape.radius);
  120. }
  121. // the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines
  122. // it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce
  123. let gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass / Math.pow(distance,3);
  124. let fx = dx * gravityForce;
  125. let fy = dy * gravityForce;
  126. this.physicsBody.forces[node.id].x += fx;
  127. this.physicsBody.forces[node.id].y += fy;
  128. }
  129. /**
  130. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  131. *
  132. * @param {Array.<Node>} nodes
  133. * @param {Array.<number>} nodeIndices
  134. * @returns {{root: {centerOfMass: {x: number, y: number}, mass: number, range: {minX: number, maxX: number, minY: number, maxY: number}, size: number, calcSize: number, children: {data: null}, maxWidth: number, level: number, childrenCount: number}}} BarnesHutTree
  135. * @private
  136. */
  137. _formBarnesHutTree(nodes, nodeIndices) {
  138. let node;
  139. let nodeCount = nodeIndices.length;
  140. let minX = nodes[nodeIndices[0]].x;
  141. let minY = nodes[nodeIndices[0]].y;
  142. let maxX = nodes[nodeIndices[0]].x;
  143. let maxY = nodes[nodeIndices[0]].y;
  144. // get the range of the nodes
  145. for (let i = 1; i < nodeCount; i++) {
  146. let x = nodes[nodeIndices[i]].x;
  147. let y = nodes[nodeIndices[i]].y;
  148. if (nodes[nodeIndices[i]].options.mass > 0) {
  149. if (x < minX) {
  150. minX = x;
  151. }
  152. if (x > maxX) {
  153. maxX = x;
  154. }
  155. if (y < minY) {
  156. minY = y;
  157. }
  158. if (y > maxY) {
  159. maxY = y;
  160. }
  161. }
  162. }
  163. // make the range a square
  164. let sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  165. if (sizeDiff > 0) {
  166. minY -= 0.5 * sizeDiff;
  167. maxY += 0.5 * sizeDiff;
  168. } // xSize > ySize
  169. else {
  170. minX += 0.5 * sizeDiff;
  171. maxX -= 0.5 * sizeDiff;
  172. } // xSize < ySize
  173. let minimumTreeSize = 1e-5;
  174. let rootSize = Math.max(minimumTreeSize, Math.abs(maxX - minX));
  175. let halfRootSize = 0.5 * rootSize;
  176. let centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  177. // construct the barnesHutTree
  178. let barnesHutTree = {
  179. root: {
  180. centerOfMass: {x: 0, y: 0},
  181. mass: 0,
  182. range: {
  183. minX: centerX - halfRootSize, maxX: centerX + halfRootSize,
  184. minY: centerY - halfRootSize, maxY: centerY + halfRootSize
  185. },
  186. size: rootSize,
  187. calcSize: 1 / rootSize,
  188. children: {data: null},
  189. maxWidth: 0,
  190. level: 0,
  191. childrenCount: 4
  192. }
  193. };
  194. this._splitBranch(barnesHutTree.root);
  195. // place the nodes one by one recursively
  196. for (let i = 0; i < nodeCount; i++) {
  197. node = nodes[nodeIndices[i]];
  198. if (node.options.mass > 0) {
  199. this._placeInTree(barnesHutTree.root, node);
  200. }
  201. }
  202. // make global
  203. return barnesHutTree
  204. }
  205. /**
  206. * this updates the mass of a branch. this is increased by adding a node.
  207. *
  208. * @param {Object} parentBranch
  209. * @param {Node} node
  210. * @private
  211. */
  212. _updateBranchMass(parentBranch, node) {
  213. let totalMass = parentBranch.mass + node.options.mass;
  214. let totalMassInv = 1 / totalMass;
  215. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.options.mass;
  216. parentBranch.centerOfMass.x *= totalMassInv;
  217. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.options.mass;
  218. parentBranch.centerOfMass.y *= totalMassInv;
  219. parentBranch.mass = totalMass;
  220. let biggestSize = Math.max(Math.max(node.height, node.radius), node.width);
  221. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  222. }
  223. /**
  224. * determine in which branch the node will be placed.
  225. *
  226. * @param {Object} parentBranch
  227. * @param {Node} node
  228. * @param {boolean} skipMassUpdate
  229. * @private
  230. */
  231. _placeInTree(parentBranch, node, skipMassUpdate) {
  232. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  233. // update the mass of the branch.
  234. this._updateBranchMass(parentBranch, node);
  235. }
  236. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  237. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  238. this._placeInRegion(parentBranch, node, "NW");
  239. }
  240. else { // in SW
  241. this._placeInRegion(parentBranch, node, "SW");
  242. }
  243. }
  244. else { // in NE or SE
  245. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  246. this._placeInRegion(parentBranch, node, "NE");
  247. }
  248. else { // in SE
  249. this._placeInRegion(parentBranch, node, "SE");
  250. }
  251. }
  252. }
  253. /**
  254. * actually place the node in a region (or branch)
  255. *
  256. * @param {Object} parentBranch
  257. * @param {Node} node
  258. * @param {'NW'| 'NE' | 'SW' | 'SE'} region
  259. * @private
  260. */
  261. _placeInRegion(parentBranch, node, region) {
  262. switch (parentBranch.children[region].childrenCount) {
  263. case 0: // place node here
  264. parentBranch.children[region].children.data = node;
  265. parentBranch.children[region].childrenCount = 1;
  266. this._updateBranchMass(parentBranch.children[region], node);
  267. break;
  268. case 1: // convert into children
  269. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  270. // we move one node a little bit and we do not put it in the tree.
  271. if (parentBranch.children[region].children.data.x === node.x &&
  272. parentBranch.children[region].children.data.y === node.y) {
  273. node.x += this.seededRandom();
  274. node.y += this.seededRandom();
  275. }
  276. else {
  277. this._splitBranch(parentBranch.children[region]);
  278. this._placeInTree(parentBranch.children[region], node);
  279. }
  280. break;
  281. case 4: // place in branch
  282. this._placeInTree(parentBranch.children[region], node);
  283. break;
  284. }
  285. }
  286. /**
  287. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  288. * after the split is complete.
  289. *
  290. * @param {Object} parentBranch
  291. * @private
  292. */
  293. _splitBranch(parentBranch) {
  294. // if the branch is shaded with a node, replace the node in the new subset.
  295. let containedNode = null;
  296. if (parentBranch.childrenCount === 1) {
  297. containedNode = parentBranch.children.data;
  298. parentBranch.mass = 0;
  299. parentBranch.centerOfMass.x = 0;
  300. parentBranch.centerOfMass.y = 0;
  301. }
  302. parentBranch.childrenCount = 4;
  303. parentBranch.children.data = null;
  304. this._insertRegion(parentBranch, "NW");
  305. this._insertRegion(parentBranch, "NE");
  306. this._insertRegion(parentBranch, "SW");
  307. this._insertRegion(parentBranch, "SE");
  308. if (containedNode != null) {
  309. this._placeInTree(parentBranch, containedNode);
  310. }
  311. }
  312. /**
  313. * This function subdivides the region into four new segments.
  314. * Specifically, this inserts a single new segment.
  315. * It fills the children section of the parentBranch
  316. *
  317. * @param {Object} parentBranch
  318. * @param {'NW'| 'NE' | 'SW' | 'SE'} region
  319. * @private
  320. */
  321. _insertRegion(parentBranch, region) {
  322. let minX, maxX, minY, maxY;
  323. let childSize = 0.5 * parentBranch.size;
  324. switch (region) {
  325. case "NW":
  326. minX = parentBranch.range.minX;
  327. maxX = parentBranch.range.minX + childSize;
  328. minY = parentBranch.range.minY;
  329. maxY = parentBranch.range.minY + childSize;
  330. break;
  331. case "NE":
  332. minX = parentBranch.range.minX + childSize;
  333. maxX = parentBranch.range.maxX;
  334. minY = parentBranch.range.minY;
  335. maxY = parentBranch.range.minY + childSize;
  336. break;
  337. case "SW":
  338. minX = parentBranch.range.minX;
  339. maxX = parentBranch.range.minX + childSize;
  340. minY = parentBranch.range.minY + childSize;
  341. maxY = parentBranch.range.maxY;
  342. break;
  343. case "SE":
  344. minX = parentBranch.range.minX + childSize;
  345. maxX = parentBranch.range.maxX;
  346. minY = parentBranch.range.minY + childSize;
  347. maxY = parentBranch.range.maxY;
  348. break;
  349. }
  350. parentBranch.children[region] = {
  351. centerOfMass: {x: 0, y: 0},
  352. mass: 0,
  353. range: {minX: minX, maxX: maxX, minY: minY, maxY: maxY},
  354. size: 0.5 * parentBranch.size,
  355. calcSize: 2 * parentBranch.calcSize,
  356. children: {data: null},
  357. maxWidth: 0,
  358. level: parentBranch.level + 1,
  359. childrenCount: 0
  360. };
  361. }
  362. //--------------------------- DEBUGGING BELOW ---------------------------//
  363. /**
  364. * This function is for debugging purposed, it draws the tree.
  365. *
  366. * @param {CanvasRenderingContext2D} ctx
  367. * @param {string} color
  368. * @private
  369. */
  370. _debug(ctx, color) {
  371. if (this.barnesHutTree !== undefined) {
  372. ctx.lineWidth = 1;
  373. this._drawBranch(this.barnesHutTree.root, ctx, color);
  374. }
  375. }
  376. /**
  377. * This function is for debugging purposes. It draws the branches recursively.
  378. *
  379. * @param {Object} branch
  380. * @param {CanvasRenderingContext2D} ctx
  381. * @param {string} color
  382. * @private
  383. */
  384. _drawBranch(branch, ctx, color) {
  385. if (color === undefined) {
  386. color = "#FF0000";
  387. }
  388. if (branch.childrenCount === 4) {
  389. this._drawBranch(branch.children.NW, ctx);
  390. this._drawBranch(branch.children.NE, ctx);
  391. this._drawBranch(branch.children.SE, ctx);
  392. this._drawBranch(branch.children.SW, ctx);
  393. }
  394. ctx.strokeStyle = color;
  395. ctx.beginPath();
  396. ctx.moveTo(branch.range.minX, branch.range.minY);
  397. ctx.lineTo(branch.range.maxX, branch.range.minY);
  398. ctx.stroke();
  399. ctx.beginPath();
  400. ctx.moveTo(branch.range.maxX, branch.range.minY);
  401. ctx.lineTo(branch.range.maxX, branch.range.maxY);
  402. ctx.stroke();
  403. ctx.beginPath();
  404. ctx.moveTo(branch.range.maxX, branch.range.maxY);
  405. ctx.lineTo(branch.range.minX, branch.range.maxY);
  406. ctx.stroke();
  407. ctx.beginPath();
  408. ctx.moveTo(branch.range.minX, branch.range.maxY);
  409. ctx.lineTo(branch.range.minX, branch.range.minY);
  410. ctx.stroke();
  411. /*
  412. if (branch.mass > 0) {
  413. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  414. ctx.stroke();
  415. }
  416. */
  417. }
  418. }
  419. export default BarnesHutSolver;