xref: /haiku/src/add-ons/screen_savers/gravity/GravitySource.cpp (revision 21258e2674226d6aa732321b6f8494841895af5f)
1 /*
2  * Copyright 2012-2013 Tri-Edge AI <triedgeai@gmail.com>
3  * Copyright 2014 Haiku, Inc. All rights reserved.
4  *
5  * Distributed under the terms of the MIT license.
6  *
7  * Authors:
8  *		Tri-Edge AI
9  *		John Scipione, jscipione@gmail.com
10  */
11 
12 
13 
14 #include "GravitySource.h"
15 
16 #include "Particle.h"
17 
18 #include <stdlib.h>
19 
20 
21 #define frand() ((float)rand() / (float)RAND_MAX)
22 
23 
24 GravitySource::GravitySource()
25 {
26 	x = 0.0f;
27 	y = 0.0f;
28 	z = 0.0f;
29 	r = 0.0f;
30 
31 	vx = 0.0f;
32 	vy = 0.0f;
33 	vz = 0.0f;
34 
35 	tx = frand() * 30.0f - 15.0f;
36 	ty = frand() * 30.0f - 15.0f;
37 	tz = frand() * 10.0f - 5.0f;
38 }
39 
40 
41 void
42 GravitySource::Tick()
43 {
44 	float dx = tx - x;
45 	float dy = ty - y;
46 	float dz = tz - z;
47 
48 	float d = dx * dx + dy * dy + dz * dz;
49 
50 	vx += dx * 0.003f;
51 	vy += dy * 0.003f;
52 	vz += dz * 0.003f;
53 
54 	x += vx;
55 	y += vy;
56 	z += vz;
57 
58 	vx *= 0.98f;
59 	vy *= 0.98f;
60 	vz *= 0.98f;
61 
62 	if (dx * dx + dy * dy + dz * dz < 1.0f) {
63 		tx = frand() * 20.0f - 10.0f;
64 		ty = frand() * 20.0f - 10.0f;
65 		tz = frand() * 10.0f - 5.0f;
66 	}
67 
68 	for (int32 i = 0; i < Particle::list->CountItems(); i++) {
69 		Particle* p = Particle::list->ItemAt(i);
70 		dx = x - p->x;
71 		dy = y - p->y;
72 		dz = z - p->z;
73 
74 		d = dx * dx + dy * dy + dz * dz;
75 
76 		p->vx += dx / d * 0.25f;
77 		p->vy += dy / d * 0.25f;
78 		p->vz += dz / d * 0.25f;
79 		p->vr += 1.0f / d;
80 	}
81 }
82