-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparallel.c
More file actions
850 lines (736 loc) · 27.9 KB
/
Copy pathparallel.c
File metadata and controls
850 lines (736 loc) · 27.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
/* COMP.CE.350 Parallelization Excercise 2024
Copyright (c) 2016 Matias Koskela matias.koskela@tut.fi
Heikki Kultala heikki.kultala@tut.fi
Topi Leppanen topi.leppanen@tuni.fi
VERSION 1.1 - updated to not have stuck satellites so easily
VERSION 1.2 - updated to not have stuck satellites hopefully at all.
VERSION 19.0 - make all satellites affect the color with weighted average.
add physic correctness check.
VERSION 20.0 - relax physic correctness check
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Window handling includes */
#ifndef __APPLE__
#include <GL/gl.h>
#include <GL/glut.h>
#else
#include <GLUT/glut.h>
#include <OpenGL/gl.h>
#endif
#define CL_TARGET_OPENCL_VERSION 300
/* OpenCL includes */
#include <CL/cl.h>
/* These are used to decide the window size */
#define WINDOW_HEIGHT 1024
#define WINDOW_WIDTH 1024
/*The number of satellites can be changed to see how it affects performance */
/* Benchmarks must be run with the original number of satellites */
#define SATELLITE_COUNT 64
/* These are used to control the satellite movement */
#define SATELLITE_RADIUS 3.16f
#define MAX_VELOCITY 0.1f
#define GRAVITY 1.0f
#define DELTATIME 32
#define PHYSICSUPDATESPERFRAME 100000
/* Some helpers to window size variables */
#define SIZE WINDOW_WIDTH *WINDOW_HEIGHT
#define HORIZONTAL_CENTER (WINDOW_WIDTH / 2)
#define VERTICAL_CENTER (WINDOW_HEIGHT / 2)
/* Global variables to store mouse position */
int mousePosX = WINDOW_WIDTH / 2; // Initial position at the center
int mousePosY = WINDOW_HEIGHT / 2;
/* Is used to find out frame times */
int previousFinishTime = 0;
unsigned int frameNumber = 0;
unsigned int seed = 0;
// Stores 2D data like the coordinates
typedef struct
{
float x;
float y;
} floatvector;
// Stores 2D data like the coordinates
typedef struct
{
double x;
double y;
} doublevector;
// Stores rendered colors. Each float may vary from 0.0f ... 1.0f
typedef struct
{
float red;
float green;
float blue;
} color;
// Stores the satellite data, which fly around black hole in the space
typedef struct
{
color identifier;
floatvector position;
floatvector velocity;
} satellite;
// Pixel buffer which is rendered to the screen
color *pixels;
// Pixel buffer which is used for error checking
color *correctPixels;
// Buffer for all satellites in the space
satellite *satellites;
satellite *backupSatelites;
// ## You may add your own variables here ##
#define PROGRAM_FILE "parallel.cl"
#define KERNEL_FUNC "parallelOpenCL"
#define MAX_SOURCE_SIZE (0x100000)
/*OpenCL data structures*/
cl_device_id device;
cl_context context; // Context object
cl_command_queue queue; // Command queue to assiciate with the device
cl_program program; // Program object
cl_kernel kernel; // Kernel object
cl_int status;
cl_mem satelliteDataBuffer; // memory object to hold satellite for the kernel
cl_mem pixelDataBuffer; // memory object to hold pixel data from the kernel
cl_mem pixelOut;
void mouseMotion (int x, int y);
// ## You may add your own initialization routines here ##
/* Find a GPU or CPU associated with the first available platform */
cl_device_id
create_device ()
{
cl_platform_id platform;
cl_device_id dev;
int status;
/* Identify a platform */
status = clGetPlatformIDs (1, &platform, NULL);
if (status < 0)
{
perror ("Cannot identify a platform");
exit (1);
}
/* Access a device */
status = clGetDeviceIDs (platform, CL_DEVICE_TYPE_GPU, 1, &dev, NULL);
if (status == CL_DEVICE_NOT_FOUND)
{
status
= clGetDeviceIDs (platform, CL_DEVICE_TYPE_CPU, 1, &dev, NULL);
}
if (status < 0)
{
perror ("Cannot access any devices");
exit (1);
}
char info[50];
status = clGetDeviceInfo (dev, CL_DEVICE_NAME, 50, info, NULL);
printf ("device name: %s\n", info);
status = clGetPlatformInfo (platform, CL_PLATFORM_NAME, 50, info, NULL);
printf ("platform name : %s\n", info);
status = clGetPlatformInfo (platform, CL_PLATFORM_VERSION, 50, info, NULL);
printf ("version : %s\n", info);
status = clGetPlatformInfo (platform, CL_PLATFORM_VENDOR, 50, info, NULL);
printf ("vendor : %s\n", info);
return dev;
}
/* Create program from a file and compile it */
cl_program
build_program (cl_context ctx, cl_device_id dev, const char *filename)
{
cl_program program;
FILE *program_handle;
char *program_buffer, *program_log;
size_t program_size, log_size;
int status;
/* Read program file and place content into buffer */
program_handle = fopen (filename, "rb");
if (program_handle == NULL)
{
perror ("Cannot find the program file");
exit (1);
}
fseek (program_handle, 0, SEEK_END);
program_size = ftell (program_handle);
rewind (program_handle);
program_buffer = (char *)malloc (program_size + 1);
program_buffer[program_size] = '\0';
size_t bytesRead
= fread (program_buffer, sizeof (char), program_size, program_handle);
if (bytesRead != program_size)
{
perror ("Error reading program file");
exit (EXIT_FAILURE);
}
fclose (program_handle);
/* Create program from file */
program = clCreateProgramWithSource (ctx, 1, (const char **)&program_buffer,
&program_size, &status);
if (status < 0)
{
perror ("Cannot create the program");
exit (1);
}
free (program_buffer);
/* Build program */
status = clBuildProgram (program, 0, NULL, NULL, NULL, NULL);
if (status < 0)
{
/* Find size of log and print to std output */
clGetProgramBuildInfo (program, dev, CL_PROGRAM_BUILD_LOG, 0, NULL,
&log_size);
program_log = (char *)malloc (log_size + 1);
program_log[log_size] = '\0';
clGetProgramBuildInfo (program, dev, CL_PROGRAM_BUILD_LOG,
log_size + 1, program_log, NULL);
printf ("%s\n", program_log);
free (program_log);
exit (1);
}
return program;
}
void
init ()
{
device = create_device ();
context = clCreateContext (NULL, 1, &device, NULL, NULL, &status);
if (status < 0)
{
perror ("Cannot create a context");
exit (1);
}
/*Build Program and create a kernel calling build_program function*/
program = build_program (context, device, PROGRAM_FILE);
kernel = clCreateKernel (program, KERNEL_FUNC, &status);
if (status < 0)
{
perror ("Cannot create a kernel");
exit (1);
};
// Buffer for satellite data
satelliteDataBuffer
= clCreateBuffer (context, CL_MEM_READ_ONLY,
SATELLITE_COUNT * sizeof (satellite), NULL, &status);
if (status != CL_SUCCESS)
{
printf ("Error while creating satellite buffer input\n");
return;
}
// Buffer for pixel out data
pixelOut = clCreateBuffer (context, CL_MEM_WRITE_ONLY,
SIZE * sizeof (color), NULL, &status);
if (status != CL_SUCCESS)
{
printf ("Error while creating pixel buffer output\n");
return;
}
// Associating satellite buffer to kernel (Associate buffer to kernel)
status = clSetKernelArg (kernel, 0, sizeof (cl_mem), &satelliteDataBuffer);
if (status != CL_SUCCESS)
{
printf ("Error while associating satellite data buffer\n");
return;
}
// Associating pixel buffer output to kernel
status = clSetKernelArg (kernel, 1, sizeof (cl_mem), &pixelOut);
if (status != CL_SUCCESS)
{
printf (
"Error while associating pixel data buffer to the kernel\n");
return;
}
// Creating a command queue and associating it with the device
queue = clCreateCommandQueueWithProperties (context, device, 0, &status);
if (status < 0)
{
perror ("Cannot create a command queue");
exit (1);
};
}
// ## You are asked to make this code parallel ##
// Physics engine loop. (This is called once a frame before graphics engine)
// Moves the satellites based on gravity
// This is done multiple times in a frame because the Euler integration
// is not accurate enough to be done only once
void
parallelPhysicsEngine ()
{
#pragma omp parallel for
// SWAPPED Physics satellite loop
for (int i = 0; i < SATELLITE_COUNT; ++i)
{
// cache the variables
double tmpPositionx = satellites[i].position.x;
double tmpPositiony = satellites[i].position.y;
double tmpVelocityx = satellites[i].velocity.x;
double tmpVelocityy = satellites[i].velocity.y;
// SWAPPED Physics iteration loop
for (int physicsUpdateIndex = 0;
physicsUpdateIndex < PHYSICSUPDATESPERFRAME;
++physicsUpdateIndex)
{
// Distance to the blackhole (bit ugly code because C-struct
// cannot have member functions)
doublevector positionToBlackHole
= { .x = tmpPositionx - HORIZONTAL_CENTER,
.y = tmpPositiony - VERTICAL_CENTER };
double distToBlackHoleSquared
= positionToBlackHole.x * positionToBlackHole.x
+ positionToBlackHole.y * positionToBlackHole.y;
double distToBlackHole = sqrt (distToBlackHoleSquared);
// Gravity force
doublevector normalizedDirection
= { .x = positionToBlackHole.x / distToBlackHole,
.y = positionToBlackHole.y / distToBlackHole };
double accumulation = GRAVITY / distToBlackHoleSquared;
// Delta time is used to make velocity same despite
// different FPS Update velocity based on force
tmpVelocityx -= accumulation * normalizedDirection.x
* DELTATIME / PHYSICSUPDATESPERFRAME;
tmpVelocityy -= accumulation * normalizedDirection.y
* DELTATIME / PHYSICSUPDATESPERFRAME;
// Update position based on velocity
tmpPositionx
+= tmpVelocityx * DELTATIME / PHYSICSUPDATESPERFRAME;
tmpPositiony
+= tmpVelocityy * DELTATIME / PHYSICSUPDATESPERFRAME;
}
#pragma omp critical
{
satellites[i].position.x = tmpPositionx;
satellites[i].position.y = tmpPositiony;
satellites[i].velocity.x = tmpVelocityx;
satellites[i].velocity.y = tmpVelocityy;
}
}
}
// ## You are asked to make this code parallel ##
// Rendering loop (This is called once a frame after physics engine)
// Decides the color for each pixel.
void
parallelGraphicsEngine ()
{
cl_int status;
// Filling satellite input buffer with satellite data
status = clEnqueueWriteBuffer (queue, satelliteDataBuffer, CL_TRUE, 0,
SATELLITE_COUNT * sizeof (satellite),
satellites, 0, NULL, NULL);
if (status != CL_SUCCESS)
{
printf ("Error while feeding data into satellite buffer to the "
"kernel\n");
return;
}
// Dynamically passing mouse position and black hole radius to the kernel
status = clSetKernelArg (kernel, 2, sizeof (int), &mousePosX);
status |= clSetKernelArg (kernel, 3, sizeof (int), &mousePosY);
float blackHoleRadius = 4.5f;
status |= clSetKernelArg (kernel, 4, sizeof (float), &blackHoleRadius);
if (status != CL_SUCCESS)
{
printf (
"Error while setting kernel arguments for mouse position\n");
return;
}
// Define global work size (always matches window size)
size_t globalWorkSize[2] = { WINDOW_WIDTH, WINDOW_HEIGHT };
size_t localWorkSize[] = { 2, 32 };
/* Enqueue kernel with configurable local work size */
status = clEnqueueNDRangeKernel (queue, kernel, 2, 0, globalWorkSize,
localWorkSize, 0, NULL, NULL);
if (status != CL_SUCCESS)
{
printf ("Error while executing kernel\n");
return;
}
// Wait for kernel completion
status = clFinish (queue);
if (status != CL_SUCCESS)
{
printf ("Error clFinish is called\n");
return;
}
// Read device output buffer to the host pixel array
clEnqueueReadBuffer (queue, pixelOut, CL_TRUE, 0, SIZE * sizeof (color),
pixels, 0, NULL, NULL);
if (status != CL_SUCCESS)
{
printf ("Error while reading data from pixel buffer\n");
return;
}
}
void
initMouse ()
{
// Registering the mouse motion callback
glutPassiveMotionFunc (
mouseMotion); // Tracks mouse movement without requiring button clicks
}
// ## You may add your own destrcution routines here ##
void
destroy ()
{
// Free OpenCL resources
clReleaseKernel (kernel);
clReleaseProgram (program);
clReleaseCommandQueue (queue);
clReleaseMemObject (satelliteDataBuffer);
clReleaseMemObject (pixelDataBuffer);
clReleaseContext (context);
free (device);
free (program);
}
////////////////////////////////////////////////
// ¤¤ TO NOT EDIT ANYTHING AFTER THIS LINE ¤¤ //
////////////////////////////////////////////////
// ¤¤ DO NOT EDIT THIS FUNCTION ¤¤
// Sequential rendering loop used for finding errors
void
sequentialGraphicsEngine ()
{
// Graphics pixel loop
for (int i = 0; i < SIZE; ++i)
{
// Row wise ordering
floatvector pixel
= { .x = i % WINDOW_WIDTH, .y = i / WINDOW_WIDTH };
// This color is used for coloring the pixel
color renderColor = { .red = 0.f, .green = 0.f, .blue = 0.f };
// Find closest satellite
float shortestDistance = INFINITY;
float weights = 0.f;
int hitsSatellite = 0;
// First Graphics satellite loop: Find the closest satellite.
for (int j = 0; j < SATELLITE_COUNT; ++j)
{
floatvector difference
= { .x = pixel.x - satellites[j].position.x,
.y = pixel.y - satellites[j].position.y };
float distance = sqrt (difference.x * difference.x
+ difference.y * difference.y);
if (distance < SATELLITE_RADIUS)
{
renderColor.red = 1.0f;
renderColor.green = 1.0f;
renderColor.blue = 1.0f;
hitsSatellite = 1;
break;
}
else
{
float weight
= 1.0f
/ (distance * distance * distance * distance);
weights += weight;
if (distance < shortestDistance)
{
shortestDistance = distance;
renderColor = satellites[j].identifier;
}
}
}
// Second graphics loop: Calculate the color based on distance to
// every satellite.
if (!hitsSatellite)
{
for (int j = 0; j < SATELLITE_COUNT; ++j)
{
floatvector difference
= { .x = pixel.x - satellites[j].position.x,
.y = pixel.y - satellites[j].position.y };
float dist2 = (difference.x * difference.x
+ difference.y * difference.y);
float weight = 1.0f / (dist2 * dist2);
renderColor.red += (satellites[j].identifier.red
* weight / weights)
* 3.0f;
renderColor.green += (satellites[j].identifier.green
* weight / weights)
* 3.0f;
renderColor.blue += (satellites[j].identifier.blue
* weight / weights)
* 3.0f;
}
}
correctPixels[i] = renderColor;
}
}
void
sequentialPhysicsEngine (satellite *s)
{
// double precision required for accumulation inside this routine,
// but float storage is ok outside these loops.
doublevector tmpPosition[SATELLITE_COUNT];
doublevector tmpVelocity[SATELLITE_COUNT];
for (int i = 0; i < SATELLITE_COUNT; ++i)
{
tmpPosition[i].x = s[i].position.x;
tmpPosition[i].y = s[i].position.y;
tmpVelocity[i].x = s[i].velocity.x;
tmpVelocity[i].y = s[i].velocity.y;
}
// Physics iteration loop
for (int physicsUpdateIndex = 0;
physicsUpdateIndex < PHYSICSUPDATESPERFRAME; ++physicsUpdateIndex)
{
// Physics satellite loop
for (int i = 0; i < SATELLITE_COUNT; ++i)
{
// Distance to the blackhole
// (bit ugly code because C-struct cannot have member
// functions)
doublevector positionToBlackHole
= { .x = tmpPosition[i].x - HORIZONTAL_CENTER,
.y = tmpPosition[i].y - VERTICAL_CENTER };
double distToBlackHoleSquared
= positionToBlackHole.x * positionToBlackHole.x
+ positionToBlackHole.y * positionToBlackHole.y;
double distToBlackHole = sqrt (distToBlackHoleSquared);
// Gravity force
doublevector normalizedDirection
= { .x = positionToBlackHole.x / distToBlackHole,
.y = positionToBlackHole.y / distToBlackHole };
double accumulation = GRAVITY / distToBlackHoleSquared;
// Delta time is used to make velocity same despite
// different FPS Update velocity based on force
tmpVelocity[i].x -= accumulation * normalizedDirection.x
* DELTATIME / PHYSICSUPDATESPERFRAME;
tmpVelocity[i].y -= accumulation * normalizedDirection.y
* DELTATIME / PHYSICSUPDATESPERFRAME;
// Update position based on velocity
tmpPosition[i].x += tmpVelocity[i].x * DELTATIME
/ PHYSICSUPDATESPERFRAME;
tmpPosition[i].y += tmpVelocity[i].y * DELTATIME
/ PHYSICSUPDATESPERFRAME;
}
}
// double precision required for accumulation inside this routine,
// but float storage is ok outside these loops.
// copy back the float storage.
for (int i = 0; i < SATELLITE_COUNT; ++i)
{
s[i].position.x = tmpPosition[i].x;
s[i].position.y = tmpPosition[i].y;
s[i].velocity.x = tmpVelocity[i].x;
s[i].velocity.y = tmpVelocity[i].y;
}
}
// Just some value that barely passes for OpenCL example program
#define ALLOWED_FP_ERROR 0.08
// ¤¤ DO NOT EDIT THIS FUNCTION ¤¤
void
errorCheck ()
{
for (unsigned int i = 0; i < SIZE; ++i)
{
int x = i % WINDOW_WIDTH;
int y = i / WINDOW_WIDTH;
// Skip known pixel
if (x == 510 && y == 508)
{
continue;
}
if (fabs (correctPixels[i].red - pixels[i].red) > ALLOWED_FP_ERROR
|| fabs (correctPixels[i].green - pixels[i].green)
> ALLOWED_FP_ERROR
|| fabs (correctPixels[i].blue - pixels[i].blue)
> ALLOWED_FP_ERROR)
{
printf ("Unknown pixel at (x=%i, y=%i). Press enter to "
"continue.\n",
x, y);
getchar ();
return;
}
}
printf ("Error check passed!\n");
}
// GLUT Callback Functions
void
mouseMotion (int x, int y)
{
mousePosX = x;
mousePosY = WINDOW_HEIGHT - y; // Adjust for OpenGL coordinate origin
}
int totalTimeAcc, satelliteMovementAcc, pixelColoringAcc, frameCount;
// ¤¤ DO NOT EDIT THIS FUNCTION ¤¤
void
compute (void)
{
int timeSinceStart = glutGet (GLUT_ELAPSED_TIME);
// Error check during first frames
if (frameNumber < 2)
{
memcpy (backupSatelites, satellites,
sizeof (satellite) * SATELLITE_COUNT);
sequentialPhysicsEngine (backupSatelites);
}
parallelPhysicsEngine ();
if (frameNumber < 2)
{
for (int i = 0; i < SATELLITE_COUNT; i++)
{
if (memcmp (&satellites[i], &backupSatelites[i],
sizeof (satellite)))
{
printf (
"Incorrect satellite data of satellite: %d\n",
i);
getchar ();
}
}
}
int satelliteMovementMoment = glutGet (GLUT_ELAPSED_TIME);
int satelliteMovementTime = satelliteMovementMoment - timeSinceStart;
// Decides the colors for the pixels
parallelGraphicsEngine ();
int pixelColoringMoment = glutGet (GLUT_ELAPSED_TIME);
int pixelColoringTime = pixelColoringMoment - satelliteMovementMoment;
int finishTime = glutGet (GLUT_ELAPSED_TIME);
// Sequential code is used to check possible errors in the parallel version
if (frameNumber < 2)
{
sequentialGraphicsEngine ();
errorCheck ();
}
else if (frameNumber == 2)
{
previousFinishTime = finishTime;
printf ("Time spent on moving satellites + Time spent on space "
"coloring = "
"Total time in milliseconds between frames (might not "
"equal the sum of "
"the left-hand expression)\n");
}
else if (frameNumber > 2)
{
// Print timings
int totalTime = finishTime - previousFinishTime;
previousFinishTime = finishTime;
printf ("Latency of this frame %i + %i = %ims \n",
satelliteMovementTime, pixelColoringTime, totalTime);
frameCount++;
totalTimeAcc += totalTime;
satelliteMovementAcc += satelliteMovementTime;
pixelColoringAcc += pixelColoringTime;
printf ("Averaged over all frames: %i + %i = %ims.\n",
satelliteMovementAcc / frameCount,
pixelColoringAcc / frameCount, totalTimeAcc / frameCount);
}
// Render the frame
glutPostRedisplay ();
}
// ¤¤ DO NOT EDIT THIS FUNCTION ¤¤
// Probably not the best random number generator
float
randomNumber (float min, float max)
{
return (rand () * (max - min) / RAND_MAX) + min;
}
// DO NOT EDIT THIS FUNCTION
void
fixedInit (unsigned int seed)
{
if (seed != 0)
{
srand (seed);
}
// Init pixel buffer which is rendered to the widow
pixels = (color *)malloc (sizeof (color) * SIZE);
// Init pixel buffer which is used for error checking
correctPixels = (color *)malloc (sizeof (color) * SIZE);
backupSatelites
= (satellite *)malloc (sizeof (satellite) * SATELLITE_COUNT);
// Init satellites buffer which are moving in the space
satellites = (satellite *)malloc (sizeof (satellite) * SATELLITE_COUNT);
// Create random satellites
for (int i = 0; i < SATELLITE_COUNT; ++i)
{
// Random reddish color
color id = { .red = randomNumber (0.f, 0.15f) + 0.1f,
.green = randomNumber (0.f, 0.14f) + 0.0f,
.blue = randomNumber (0.f, 0.16f) + 0.0f };
// Random position with margins to borders
floatvector initialPosition
= { .x = HORIZONTAL_CENTER - randomNumber (50, 320),
.y = VERTICAL_CENTER - randomNumber (50, 320) };
initialPosition.x = (i / 2 % 2 == 0)
? initialPosition.x
: WINDOW_WIDTH - initialPosition.x;
initialPosition.y = (i < SATELLITE_COUNT / 2)
? initialPosition.y
: WINDOW_HEIGHT - initialPosition.y;
// Randomize velocity tangential to the balck hole
floatvector positionToBlackHole
= { .x = initialPosition.x - HORIZONTAL_CENTER,
.y = initialPosition.y - VERTICAL_CENTER };
float distance
= (0.06 + randomNumber (-0.01f, 0.01f))
/ sqrt (positionToBlackHole.x * positionToBlackHole.x
+ positionToBlackHole.y * positionToBlackHole.y);
floatvector initialVelocity
= { .x = distance * -positionToBlackHole.y,
.y = distance * positionToBlackHole.x };
// Every other orbits clockwise
if (i % 2 == 0)
{
initialVelocity.x = -initialVelocity.x;
initialVelocity.y = -initialVelocity.y;
}
satellite tmpSatelite = { .identifier = id,
.position = initialPosition,
.velocity = initialVelocity };
satellites[i] = tmpSatelite;
}
}
// ¤¤ DO NOT EDIT THIS FUNCTION ¤¤
void
fixedDestroy (void)
{
destroy ();
free (pixels);
free (correctPixels);
free (satellites);
if (seed != 0)
{
printf ("Used seed: %i\n", seed);
}
}
// ¤¤ DO NOT EDIT THIS FUNCTION ¤¤
// Renders pixels-buffer to the window
void
render (void)
{
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawPixels (WINDOW_WIDTH, WINDOW_HEIGHT, GL_RGB, GL_FLOAT, pixels);
glutSwapBuffers ();
frameNumber++;
}
// DO NOT EDIT THIS FUNCTION
// Inits glut and start mainloop
int
main (int argc, char **argv)
{
/* Default work-item size */
size_t localWorkSize[2] = { 16, 16 };
if (argc > 1)
{
seed = atoi (argv[1]);
printf ("Using seed: %i\n", seed);
}
/* Init glut window */
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize (WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow ("Parallelization excercise");
glutDisplayFunc (render);
atexit (fixedDestroy);
glEnable (GL_DEPTH_TEST);
glClearColor (0.0, 0.0, 0.0, 1.0);
fixedInit (seed);
init ();
/* Call initMouse */
initMouse ();
/* Compute-function is called when everything from last frame is ready */
glutIdleFunc (compute);
/* Start main loop */
glutMainLoop ();
}