summaryrefslogtreecommitdiff
path: root/2d/rigidbody/rigidbody_2/main.cpp
blob: 123cf7e5cab889b6d8acb9e5192f238ebc25656d (plain)
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
#include "../../../shared_cpp/OrthographicRenderer.h"
#include "../../../shared_cpp/types.h"
#include "../../../shared_cpp/WebglContext.h"
#include "../../../shared_cpp/mathlib.h"
#include "../../../shared_cpp/MainLoop.h"
#include <cstdio>
#include <cmath>
#include <emscripten/html5.h>
#include <unistd.h>
#include <pthread.h>
#include <cmath>
#include <cfloat>

struct Impulse {
    Vector2 force = { 0, 0 };
    Vector2 pointOfApplication = { 0, 0 };
    float32 timeOfApplicationSeconds = 0.25f;
    float32 timeAppliedSeconds = 0.f;
    bool isDead = false;
};

const int32 NUM_IMPULSES = 4;

struct Rigidbody {
    int32 numImpulses = 0;
    Impulse activeImpulses[NUM_IMPULSES];
    Vector2 velocity = { 0, 0 };
    Vector2 position = { 0, 0 };
    float32 mass = 1.f;

	float32 rotationalVelocity = 0.f;
	float32 rotation = 0.f;
	float32 momentOfInertia = 1.f;

    void reset() {
        numImpulses = 0;
        velocity = { 0, 0 };
		rotationalVelocity = 0.f;
		rotation = 0.f;
    }

    void applyImpulse(Impulse i) {
        if (numImpulses > NUM_IMPULSES) {
            printf("Unable to apply impulse. Buffer full.\n");
            return;
        }

        activeImpulses[numImpulses] = i;
        numImpulses++;
    }

    void applyGravity(float32 deltaTimeSeconds) {
        velocity += (Vector2 { 0.f, -9.8f } * deltaTimeSeconds);
    }

    void update(float32 deltaTimeSeconds) {
        applyGravity(deltaTimeSeconds);

        Vector2 force;
        float32 torque = 0.f;
        for (int32 idx = 0; idx < numImpulses; idx++) {
            Impulse& i = activeImpulses[idx];

            float32 nextTimeAppliedSeconds = i.timeAppliedSeconds + deltaTimeSeconds;
            if (nextTimeAppliedSeconds >= i.timeOfApplicationSeconds) {
                nextTimeAppliedSeconds = i.timeOfApplicationSeconds;
                i.isDead = true;
            }
            
            float32 impulseDtSeconds = nextTimeAppliedSeconds - i.timeAppliedSeconds;
            Vector2 forceToApply = i.force * (impulseDtSeconds / i.timeOfApplicationSeconds);
            force += forceToApply * impulseDtSeconds;

            // New! Increment the torque for each force
            torque += i.pointOfApplication.getPerp().dot(forceToApply);

            i.timeAppliedSeconds = nextTimeAppliedSeconds;
        }
        
        Vector2 acceleration = force / mass;
        velocity += (acceleration * deltaTimeSeconds);
        position += (velocity * deltaTimeSeconds);

        // New! Update the rotational velocity as well
		float32 rotationalAcceleration = torque / momentOfInertia;
		rotationalVelocity += (rotationalAcceleration * deltaTimeSeconds);
		rotation += (rotationalVelocity * deltaTimeSeconds);

        for (int32 idx = 0; idx < numImpulses; idx++) {
            if (activeImpulses[idx].isDead) {
                for (int j = idx + 1; j < numImpulses; j++) {
                    activeImpulses[j - 1] = activeImpulses[j];
                }

                idx = idx - 1;
                numImpulses--;
            }
        }
    }
};

struct Rectangle {
	OrthographicShape shape;
    Rigidbody body;
	Vector2 originalPoints[4];
	Vector2 transformedPoints[4];

	void load(OrthographicRenderer* renderer, Vector4 color, float32 width, float32 height) {
        color = color.toNormalizedColor();

		float32 halfWidth = width / 2.f;
		float32 halfHeight = height / 2.f;

	    OrthographicVertex vertices[6];
		vertices[0].position = Vector2 { -halfWidth, -halfHeight };
		vertices[1].position = Vector2 { -halfWidth, halfHeight };
		vertices[2].position = Vector2 { halfWidth, halfHeight };
		vertices[3].position = Vector2 { -halfWidth, -halfHeight };
		vertices[4].position = Vector2 { halfWidth, -halfHeight };
		vertices[5].position = Vector2 { halfWidth, halfHeight };
		
		for (int32 i = 0; i < 6; i++) {
			vertices[i].color = color;
		}

		originalPoints[0] = vertices[0].position;
		originalPoints[1] = vertices[1].position;
		originalPoints[2] = vertices[2].position;
		originalPoints[3] = vertices[4].position;
		
		shape.load(vertices, 6, renderer);
		body.reset();

		body.momentOfInertia = (width * width + height * height) * (body.mass / 12.f);
	}

	void update(float32 dtSeconds) {
		body.update(dtSeconds);
		shape.model = Mat4x4().translateByVec2(body.position).rotate2D(body.rotation);

		// Note: This helps us check if the cursor is within the bounds of the
		// rectangle later on.
		for (int idx = 0; idx < 4; idx++) {
			transformedPoints[idx] = shape.model * originalPoints[idx];
		}
	}

	void render(OrthographicRenderer* renderer) {
		shape.render(renderer);
	}

	void unload() {
		shape.unload();
	}
};

struct Circle {
	OrthographicShape shape;
    Rigidbody body;
    Vector2 force;

	float32 radius = 5.f;

	void load(OrthographicRenderer* renderer, Vector4 color) {
		const int32 numSegments = 36;
		const float32 radiansPerSegment = (2.f * PI) / static_cast<float>(numSegments);
		const int32 numVertices = numSegments * 3;
		
        color = color.toNormalizedColor();

		OrthographicVertex vertices[numSegments * 3];
		for (int idx = 0; idx < numSegments; idx++) {
			int vIdx = idx * 3;
			
			vertices[vIdx].color = color;
			vertices[vIdx].position = Vector2 { radius * cosf(radiansPerSegment * idx), radius * sinf(radiansPerSegment * idx) };
			vertices[vIdx + 1].color = color;
			vertices[vIdx + 1].position = Vector2 { 0.f, 0.f };
			vertices[vIdx + 2].color = color;
			vertices[vIdx + 2].position = Vector2 { radius * cosf(radiansPerSegment * (idx + 1)), radius * sinf(radiansPerSegment * (idx + 1)) };
		}

		shape.load(vertices, numVertices, renderer);
		body.reset();
	}

	void update(float32 dtSeconds) {
		shape.model = Mat4x4().translateByVec2(body.position);
	}

	void render(OrthographicRenderer* renderer) {
		shape.render(renderer);
	}

	void unload() {
		shape.unload();
	}
};

EM_BOOL onPlayClicked(int eventType, const EmscriptenMouseEvent* mouseEvent, void* userData);
EM_BOOL onStopClicked(int eventType, const EmscriptenMouseEvent* mouseEvent, void* userData);
EM_BOOL onMouseMove(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData);

void load();
void update(float32 time, void* userData);
void unload();

WebglContext context;
OrthographicRenderer renderer;
MainLoop mainLoop;
Rectangle rectangle;
Circle pointer;
bool isIntersectingPointer = false;

int main() {
	context.init("#gl_canvas");
    emscripten_set_click_callback("#gl_canvas_play", NULL, false, onPlayClicked);
    emscripten_set_click_callback("#gl_canvas_stop", NULL, false, onStopClicked);
    emscripten_set_mousemove_callback("#gl_canvas", NULL, false, onMouseMove);
	
    return 0;
}

void load() {
    renderer.load(&context);

	rectangle.load(&renderer, Vector4 { 55.f, 235.f, 35.f, 255.f }, 128.f, 64.f);
	rectangle.body.position = Vector2 { context.width / 3.f, context.height / 3.f };
	rectangle.body.velocity = Vector2 { 100.f, 250.f };

	pointer.load(&renderer, Vector4 { 25.f, 235.f, 235.f, 255.f });

    mainLoop.run(update);
}

bool isPointInRectangle(Vector2 p, Rectangle r) {
	// https://math.stackexchange.com/a/190373
	Vector2 A = r.transformedPoints[0];
	Vector2 B = r.transformedPoints[1];
	Vector2 D = r.transformedPoints[3];

	float32 amDotAb = (p - A).dot(B - A);
	float32 abDotAb = (B - A).dot(B - A);

	float32 amDotAd = (p - A).dot(D - A);
	float32 aDDotAd = (D - A).dot(D - A);

	return amDotAb > 0 && amDotAb < abDotAb && amDotAd > 0 && amDotAd < aDDotAd;
	
}

void update(float32 deltaTimeSeconds, void* userData) {
    rectangle.update(deltaTimeSeconds);
	pointer.update(deltaTimeSeconds);

	if (isPointInRectangle(pointer.body.position, rectangle)) {
		if (!isIntersectingPointer) {
			isIntersectingPointer = true;
			Vector2 pointOfApplication = pointer.body.position - rectangle.body.position;
            Impulse i;
            i.force = pointer.force;
            i.pointOfApplication = pointOfApplication;
			rectangle.body.applyImpulse(i);
		}
	} else if (isIntersectingPointer) {
		isIntersectingPointer = false;
	}
		

    // Check collisions with walls so we don't go out of the scene. Simply reflect here.
    if (rectangle.body.position.x <= 0.f) {
        rectangle.body.position.x = 0.f;
        rectangle.body.velocity = rectangle.body.velocity - Vector2 { 1.f, 0.f } * (2 * (rectangle.body.velocity.dot(Vector2 { 1.f, 0.f })));
    }
    if (rectangle.body.position.y <= 0.f) {
        rectangle.body.position.y = 0.f;
        rectangle.body.velocity = rectangle.body.velocity - Vector2 { 0.f, 1.f } * (2 * (rectangle.body.velocity.dot(Vector2 { 0.f, 1.f })));
    } 
    if (rectangle.body.position.x >= 800.f) {
        rectangle.body.position.x = 800.f;
        rectangle.body.velocity = rectangle.body.velocity - Vector2 { -1.f, 0.f } * (2 * (rectangle.body.velocity.dot(Vector2{ -1.f, 0.f })));
    }
    if (rectangle.body.position.y >= 600.f) {
        rectangle.body.position.y = 600.f;
        rectangle.body.velocity = rectangle.body.velocity - Vector2 { 0.f, -1.f } * (2 * (rectangle.body.velocity.dot(Vector2 { 0.f, -1.f }))) ;
    }
	
	// Renderer
	renderer.render();
    rectangle.render(&renderer);
	pointer.render(&renderer);
}

void unload() {
    mainLoop.stop();
    renderer.unload();
    rectangle.unload();
	pointer.unload();
}

//
// Interactions with DOM handled below
//
EM_BOOL onPlayClicked(int eventType, const EmscriptenMouseEvent* mouseEvent, void* userData) {
    printf("Play clicked\n");
    
    load();
    return true;
}

EM_BOOL onStopClicked(int eventType, const EmscriptenMouseEvent* mouseEvent, void* userData) {
    printf("Stop clicked\n");
    unload();
    return true;
}

EM_BOOL onMouseMove(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData) {
	if (!mainLoop.isRunning) {
		return true;
	}

    pointer.force.x = static_cast<float32>(mouseEvent->movementX) * 1000.f;
	pointer.force.y = static_cast<float32>(-mouseEvent->movementY) * 1000.f;

	pointer.body.position.x = static_cast<float32>(mouseEvent->targetX);
	pointer.body.position.y = static_cast<float32>(600.f - mouseEvent->targetY);

	return true;
}