我首先使用蛮力进行了 2D n 体模拟,但随后按照 http://arborjs.org/docs/barnes-hut 我实现了 Barnes-Hut 近似算法。然而,这并没有给我带来我想要的效果。
例如:
巴恩斯小屋 -> 2000 具尸体;平均帧时间32 毫秒和 5000; 164 毫秒
暴力破解 -> 2000 具尸体;平均帧时间31 毫秒和 5000; 195 毫秒
这些值是渲染关闭时的值。
我是否正确地假设我没有正确实现该算法,因此性能没有得到实质性提高?
Theta 当前设置为 s/d < 0.5. Changing this value to e.g. 1 does increase performance, but it's quite obvious why this isn't preferred.
单线程
我的代码大致如下:
while(!close)
{
long newTime = System.currentTimeMillis();
long frameTime = newTime-currentTime;
System.out.println(frameTime);
currentTime = newTime;
update the bodies
}
在更新主体的函数中:
first insert all bodies into the quadtree with all its subnodes
for all bodies
{
compute the physics using Barnes-Hut which yields a net force per planet (doPhysics(body))
calculate instantaneous acceleration from net force
update the instantaneous velocity
}
barneshut 功能:
doPhysics(body)
{
if(node is external (contains 1 body) and that body is not itself)
{
calculate the force between those two bodies
}else if(node is internal and s/d < 0.5)
{
create a pseudobody at the COM with the nodes total mass
calculate the force between the body and pseudobody
}else (if is it internal but s/d >= 0.5)
{
(this is where recursion comes in)
doPhysics on same body but on the NorthEast subnode
doPhysics on same body but on the NorthWest subnode
doPhysics on same body but on the SouthEast subnode
doPhysics on same body but on the SouthWest subnode
}
}
实际计算力:
calculateforce(body, otherbody)
{
if(body is not at exactly the same position (avoid division by 0))
{
calculate force using newtons law of gravitation in vector form
add the force to the bodies' net force in this frame
}
}
您的代码仍然不完整(请阅读SSCCEs),深入调试不完整的代码不是该网站的目的。然而,这就是我接下来的步骤,以找出错误所在(如果有的话):