#include #include #include #include #include #define NUM_BODIES 500 #define PARTSIZE 10 #define WIDTH 512 #define HEIGHT 512 struct body { double x, y, dx, dy; }; typedef struct vec { float x, y; } vector; struct body B[NUM_BODIES]; void init() { srand(time(NULL)); for(int i = 0; i < NUM_BODIES; i++) { B[i].x = WIDTH/2 + rand() % 20 - 40; B[i].y = HEIGHT/2 + rand() % 20 - 40; B[i].dx = rand() % 50 - 100; B[i].dy = rand() % 50 - 100; } } float geomdist(int i, int j) { return sqrt(pow( B[i].x - B[j].x, 2 ) + pow( B[i].y - B[j].y, 2 )); } void updatePos() { for(int i = 0; i < NUM_BODIES; i++) { B[i].x += B[i].dx; B[i].y += B[i].dy; printf("%f %f |", B[i].dx, B[i].dy); vector mass_centre_vec; for(int j = 0; j < NUM_BODIES; j++) { if(i == j) continue; mass_centre_vec.x += (B[j].x - B[i].x) /geomdist(i, j); mass_centre_vec.y += (B[j].y - B[i].y) /geomdist(i, j); } mass_centre_vec.x /= NUM_BODIES - 1; mass_centre_vec.y /= NUM_BODIES - 1; B[i].dx = mass_centre_vec.x; B[i].dy = mass_centre_vec.y; } } int processEvents(SDL_Window *window) { SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_WINDOWEVENT_CLOSE: if(window) { SDL_DestroyWindow(window); window = NULL; return 1; } break; case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_ESCAPE: return 1; } } } return 0; } void render(SDL_Renderer *renderer, SDL_Rect particles[NUM_BODIES]) { SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // фон SDL_RenderClear(renderer); SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255); for(int i = 0; i < NUM_BODIES; i++) { particles[i].h = PARTSIZE; particles[i].w = PARTSIZE; particles[i].x = B[i].x - PARTSIZE/2; particles[i].y = B[i].y - PARTSIZE/2; SDL_RenderDrawRect(renderer, &particles[i]); } SDL_RenderPresent(renderer); } int main(int argc, char *argv[]) { SDL_Window *window = NULL; SDL_Renderer *renderer = NULL; init(); SDL_Init(SDL_INIT_VIDEO); SDL_Rect particles[NUM_BODIES]; window = SDL_CreateWindow("Universe simulation", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIDTH, HEIGHT, 0); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); while(1) { if(processEvents(window) == 1) break; render(renderer, particles); updatePos(renderer); SDL_Delay(10); } return 0; }