I'm trying to create a galaxy simulation using opengl with the compute shader and when I start my simulation, the galaxy with the spiral arms doesn't form, instead it goes into chaos. I noticed that the particles in the center are not spinning fast enough Does anyone had this problem before ?

I tried to:

  • change mass and smooth value
  • using verlet integration
  • change velocity initial value
  • change the number of particles

here is the code:

#version 430 core

layout (local_size_x = 128, local_size_y = 1, local_size_z = 1) in;

struct Particle
    vec4 position;
    vec4 velocity;
    vec4 acceleration;

layout (std430, binding = 0) buffer ParticleBuffer {
    Particle p[];

uniform float dt;
uniform float accuracy;

  const float mass = 1e-5;
  const float csmooth = 1e-6;

vec3 compute_force(vec3 posi){
    vec3 f = vec3(0);
    for(int i = 0; i<accuracy*p.length(); i++){
        if(posi != p[i].position.xyz){
            vec3 v = p[i].position.xyz - posi;
            float d = length(v);
            f+= mass*v/(pow(d,3)+csmooth);
    return f;

void main() {
    uint index = gl_GlobalInvocationID.x;

    vec3 pos = p[index].position.xyz;
    vec3 vel = p[index].velocity.xyz;
    vec3 accel = p[index].acceleration.xyz;

    vec3 newPos = pos+vel*dt + accel*(dt*dt*0.5);
    vec3 newAccel = compute_force(pos);
    vec3 newVel = vel + (accel+newAccel) *(dt*0.5);

    p[index].position.xyz = newPos;
    p[index].velocity.xyz = newVel;
    p[index].acceleration.xyz = newAccel;
  • 1
    $\begingroup$ I am not sure, but please try to delete the accelerations term out of the newPos calculation... $\endgroup$
    – Thomas
    Commented Nov 4, 2022 at 23:04
  • $\begingroup$ seems like nothing really changed $\endgroup$
    – Sedenion
    Commented Nov 6, 2022 at 12:10
  • $\begingroup$ Can you go more into detail, how the particles behavior is? Are they 'jumping' or are they all go through a single position? $\endgroup$
    – Thomas
    Commented Nov 6, 2022 at 13:40
  • $\begingroup$ The velocity therm also looks strange to me: only add one acceleration value. I think 'accel' is the correct one. $\endgroup$
    – Thomas
    Commented Nov 6, 2022 at 13:45
  • $\begingroup$ BTW you are using the Euler numeric integration algorithm. It's accuracy is very bad... A better integrater is the 'Runge-Kutta' algorithm $\endgroup$
    – Thomas
    Commented Nov 6, 2022 at 13:49


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.