star-sim

Barnes-Hut gravity simulation.
git clone git://git.amin.space/star-sim.git
Log | Files | Refs | README | LICENSE

star.c (1795B)


      1 #include "star.h"
      2 
      3 #include <math.h>
      4 #include <stdlib.h>
      5 
      6 
      7 // TODO: Test whether making this function return a struct (rather than a
      8 // struct pointer) makes a significant performance difference.
      9 struct Vec2d *vec2d_add(float angle1, float length1, float angle2, float length2)
     10 {
     11     float x = sinf(angle1) * length1 + sinf(angle2) * length2;
     12     float y = cosf(angle1) * length1 + cosf(angle2) * length2;
     13 
     14     struct Vec2d *new_vec = (struct Vec2d*)malloc(sizeof(struct Vec2d));
     15     new_vec->angle = 0.5 * M_PI - atan2f(y, x);
     16     new_vec->length = hypotf(x, y);
     17     return new_vec;
     18 }
     19 
     20 
     21 void star_accelerate(struct Star *s, float angle, float acceleration)
     22 {
     23     struct Vec2d *new_vec = vec2d_add(s->angle, s->speed, angle, acceleration);
     24     s->angle = new_vec->angle;
     25     s->speed = new_vec->length;
     26     free(new_vec);
     27 }
     28 
     29 
     30 float star_calc_size(float mass)
     31 {
     32     return 0.5 * (powf(mass, 0.5));
     33 }
     34 
     35 
     36 void star_attract(struct Star *s1, struct Star *s2)
     37 {
     38     float dx = s1->x - s2->x;
     39     float dy = s1->y - s2->y;
     40     float distance = hypotf(dx, dy);
     41 
     42     if (distance > s1->size + s2->size)
     43     {
     44         float theta = atan2f(dy, dx);
     45         float force = GRAVITATION * (s1->mass * s2->mass / powf(distance, 2));
     46         star_accelerate(s1, theta - (0.5 * M_PI), force / s1->mass);
     47         star_accelerate(s2, theta + (0.5 * M_PI), force / s2->mass);
     48         //printf("%f\n", force);
     49     }
     50 }
     51 
     52 
     53 void star_attract_to_mass(struct Star *star, float mass, float mass_x, float mass_y)
     54 {
     55     float dx = star->x - mass_x;
     56     float dy = star->y - mass_y;
     57     float distance = hypotf(dx, dy);
     58 
     59     float theta = atan2f(dy, dx);
     60     float force = GRAVITATION * (star->mass * mass / powf(distance, 2));
     61     star_accelerate(star, theta - (0.5 * M_PI), force / star->mass);
     62     //printf("%f\n", force);
     63 }