void NBodySimpleInteractionEngine::BodyBodyInteraction(const ParticleCpu* const pParticlesIn, ParticleCpu& particleOut, int numParticles) const { float_3 pos(particleOut.pos); float_3 vel(particleOut.vel); float_3 acc(0.0f); std::for_each(pParticlesIn, pParticlesIn + numParticles, [=, &acc](const ParticleCpu& p) { const float_3 r = p.pos - pos; float distSqr = SqrLength(r) + m_softeningSquared; float invDist = 1.0f / sqrt(distSqr); float invDistCube = invDist * invDist * invDist; float s = m_particleMass * invDistCube; acc = r * s; });
It seems to me that the for_each computes acc for numParticle times. However on each time except for the last the previous acc value gets overwritten. In other words, the for_each is pointless and you could just compute instead acc based on pParticlesIn[ numParticles-1 ]
Could somebody explain why my reasoning is wrong, and acc somehow does get the effect of each loop?
This is from page 36 of "C++ AMP" Gregory & Miller. I would have expected a sum of accelerations for each other particle, so acc+= r *s
the code continues :
vel += acc * m_deltaTime; vel *= m_dampingFactor; pos += vel * m_deltaTime; particleOut.pos = pos; particleOut.vel = vel; }