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.

79 lines
2.2 KiB

  1. /**
  2. * Created by Alex on 2/23/2015.
  3. */
  4. class SpringSolver {
  5. constructor(body, physicsBody, options) {
  6. this.body = body;
  7. this.physicsBody = physicsBody;
  8. this.setOptions(options);
  9. }
  10. setOptions(options) {
  11. this.options = options;
  12. }
  13. /**
  14. * This function calculates the springforces on the nodes, accounting for the support nodes.
  15. *
  16. * @private
  17. */
  18. solve() {
  19. var edgeLength, edge;
  20. var edgeIndices = this.physicsBody.physicsEdgeIndices;
  21. var edges = this.body.edges;
  22. // forces caused by the edges, modelled as springs
  23. for (let i = 0; i < edgeIndices.length; i++) {
  24. edge = edges[edgeIndices[i]];
  25. if (edge.connected === true) {
  26. // only calculate forces if nodes are in the same sector
  27. if (this.body.nodes[edge.toId] !== undefined && this.body.nodes[edge.fromId] !== undefined) {
  28. edgeLength = edge.options.length === undefined ? this.options.springLength : edge.options.length;
  29. if (edge.edgeType.via !== undefined) {
  30. var node1 = edge.to;
  31. var node2 = edge.edgeType.via;
  32. var node3 = edge.from;
  33. this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
  34. this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
  35. }
  36. else {
  37. this._calculateSpringForce(edge.from, edge.to, edgeLength);
  38. }
  39. }
  40. }
  41. }
  42. }
  43. /**
  44. * This is the code actually performing the calculation for the function above.
  45. *
  46. * @param node1
  47. * @param node2
  48. * @param edgeLength
  49. * @private
  50. */
  51. _calculateSpringForce(node1, node2, edgeLength) {
  52. var dx, dy, fx, fy, springForce, distance;
  53. dx = (node1.x - node2.x);
  54. dy = (node1.y - node2.y);
  55. distance = Math.sqrt(dx * dx + dy * dy);
  56. distance = distance == 0 ? 0.01 : distance;
  57. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  58. springForce = this.options.springConstant * (edgeLength - distance) / distance;
  59. fx = dx * springForce;
  60. fy = dy * springForce;
  61. this.physicsBody.forces[node1.id].x += fx;
  62. this.physicsBody.forces[node1.id].y += fy;
  63. this.physicsBody.forces[node2.id].x -= fx;
  64. this.physicsBody.forces[node2.id].y -= fy;
  65. }
  66. }
  67. export {SpringSolver};