3 * @author Sam Moore (20503628) 2012
4 * @purpose N-Body simulator - Definition of simulation functions; single threaded version
17 * Prints the body on screen
19 void Body_Print(Body * a)
21 printf("Body %p M=%f X=%f Y=%f Z=%f Fx=%f Fy=%f Fz=%f Vx=%f Vy=%f Vz=%f\n",
22 (void*)a, a->mass, a->x[0], a->x[1], a->x[2], a->F[0], a->F[1], a->F[2], a->v[0], a->v[1], a->v[2]);
28 void Body_Force(Body * a, System * s)
34 for (unsigned i = 0; i < DIMENSIONS; ++i)
37 for (unsigned index = 0; index < s->N; ++index)
39 Body * b = s->body+index;
44 for (unsigned i = 0; i < DIMENSIONS; ++i)
45 distance += square(b->x[i] - a->x[i]);
46 distance = sqrt(distance);
47 con = G * a->mass * b->mass / square(distance);
49 for (unsigned i = 0; i < DIMENSIONS; ++i)
50 a->F[i] += gd * (b->x[i] - a->x[i]);
57 void Body_Velocity(Body * a)
59 for (unsigned i = 0; i < DIMENSIONS; ++i)
60 a->v[i] += a->F[i] / a->mass * DELTA_T;
66 void Body_Position(Body * a)
68 for (unsigned i = 0; i < DIMENSIONS; ++i)
69 a->x[i] += a->v[i] * DELTA_T;
73 * Main compute function
75 void System_Compute(System * s)
77 // clock_t start, finish;
81 for (unsigned i = 0; i < s->N; ++i)
83 Body_Force(s->body+i, s);
84 Body_Velocity(s->body+i);
85 Body_Position(s->body+i);
94 * This function reads an input file. You can change it if you choose a
95 * different file format
97 #define LINE_SIZE BUFSIZ
98 void System_Init(System * s, char *fileName)
100 char line[LINE_SIZE];
104 file = fopen(fileName, "rt");
105 s->N = atoi(fgets(line, LINE_SIZE, file));
106 s->body = (Body*) calloc((size_t)s->N, sizeof(Body));
108 //printf("----------------------Initial field-------------------------------\n");
110 for (unsigned i = 0; i < s->N; ++i)
112 if (fgets(line, LINE_SIZE, file) != NULL)
114 Body * a = s->body+i;
115 token = strtok(line, ",; ");
116 a->mass = atof(token);
118 for (unsigned j = 0; j < DIMENSIONS; ++j)
120 token = strtok(NULL, ",; ");
121 a->x[j] = atof(token);
123 for (unsigned j = 0; j < DIMENSIONS; ++j)
125 token = strtok(NULL, ",; ");
126 a->v[j] = atof(token);
132 //printf("--------------------------------------------------------------\n");
138 * Cleans up the universe by freeing all memory
140 void Universe_Cleanup()
147 * Thread - Continuously computes steps for a system of bodies
149 void * Compute_Thread(void * s)
153 if (terminate) pthread_exit(NULL);
154 System_Compute((System*)s);