/
komarovdd
/
GraphViz
Обзор
Документация
Войти
/
komarovdd
/
GraphViz
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
scripts/physics.js
95 строк
3 KB
komarovdd
new project
09 фев 2026, 14:29
Верифицирован
09 фев 2026, 14:29
966388e
Код
Авторство
О чём код?
/** * Physics implementation based on Fruchterman-Reingold (Force-Directed) */ class PhysicsEngine { constructor() { this.params = { attraction: 0.1, repulsion: 400, gravity: 0.1, damping: 0.9, timeScale: 1.0 }; this.running = false; } /** * Updates node positions based on forces. * @param {Graph} graph * @param {number} deltaTime */ update(graph, deltaTime = 0.016) { if (!graph.nodes.size) return; const nodes = Array.from(graph.nodes.values()); const speed = this.params.timeScale; // 1. Repulsion between all pairs of nodes (1 / distance^2) for (let i = 0; i < nodes.length; i++) { const nodeA = nodes[i]; for (let j = i + 1; j < nodes.length; j++) { const nodeB = nodes[j]; const dx = nodeA.x - nodeB.x; const dy = nodeA.y - nodeB.y; const distanceSq = dx * dx + dy * dy + 0.01; const force = this.params.repulsion / distanceSq; const fx = (dx / Math.sqrt(distanceSq)) * force; const fy = (dy / Math.sqrt(distanceSq)) * force; nodeA.vx += fx * speed; nodeA.vy += fy * speed; nodeB.vx -= fx * speed; nodeB.vy -= fy * speed; } // 2. Central Gravity (pull towards center 0,0) nodeA.vx -= nodeA.x * this.params.gravity * speed; nodeA.vy -= nodeA.y * this.params.gravity * speed; } // 3. Attraction between connected nodes (Hooke's Law) graph.edges.forEach(edge => { const nodeA = graph.nodes.get(edge.source); const nodeB = graph.nodes.get(edge.target); if (!nodeA || !nodeB) return; const dx = nodeB.x - nodeA.x; const dy = nodeB.y - nodeA.y; const distance = Math.sqrt(dx * dx + dy * dy) + 0.01; // Force proportional to weight and distance const force = this.params.attraction * edge.weight * (distance / 100); const fx = (dx / distance) * force; const fy = (dy / distance) * force; nodeA.vx += fx * speed; nodeA.vy += fy * speed; nodeB.vx -= fx * speed; nodeB.vy -= fy * speed; }); // 4. Update positions and apply damping nodes.forEach(node => { if (node.isDragging) { node.vx = 0; node.vy = 0; return; } node.x += node.vx * deltaTime * 60; node.y += node.vy * deltaTime * 60; node.vx *= this.params.damping; node.vy *= this.params.damping; }); } setParams(newParams) { this.params = { ...this.params, ...newParams }; } } export { PhysicsEngine };