summaryrefslogtreecommitdiff
path: root/2d/softbody/softbody_1/damped.cpp
blob: f56f3469d35903e3debe69ff23f70f93c572bd29 (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
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
#include "damped.h"
#include "undamped.h"
#include "../../../shared_cpp/Renderer2d.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>

namespace Damped {
    struct DampedSpringWeight {
        Mesh2d shape;
        float32 radius;
        float32 mass = 1.f;

        void load(Renderer2d* renderer, float32 inRadius, Vector4 startColor, Vector4 endColor);
        void update(float32 dtSeconds);
        void render(Renderer2d* renderer);
        void unload();
    };

	enum DampedSpringType {
		None = 0,
		Overdamped = 1,
		Underdamped = 2,
		Critical = 3
	};

    struct DampedSpring {
        DampedSpringWeight* weight;

        Mesh2d shape;

        Vertex2d* vertices = NULL;
        int32 numSegments = 0;
        int32 numVertices = 0;

        // Initialization variables
		float32 initialDisplacement = 0.f;
        float32 k = 4;        // DampedSpring Constant, in N / m (Hooke's Law)
        float32 c = 1.f;      // Viscous damping coefficient (Damping force)

		// Discovered during initialization
		DampedSpringType type = DampedSpringType::None;
        float32 R = 2.f;
        float32 gamma = 6.2;
        float32 discriminant = 0.f;
        float32 omega1       = 0.f;
		float32 c1 = 0.f;
		float32 c2 = 0.f;
		float32 r1 = 0.f;
		float32 r2 = 0.f;

        // Update variables
        float32 displacement = 0.f;
        float32 timeElapsed  = 0.f;
        

        void load(Renderer2d* renderer, DampedSpringWeight* inWieight, float32 length, float32 loopRadius, float32 initialDisplacement, float32 inK, float32 inC);
        void update(float32 dtSeconds);
        void render(Renderer2d* renderer);
        void unload();
    };

    DampedInitVariables initVariables;
    void setInitVariables(DampedInitVariables newVariables) { initVariables = newVariables; }
    DampedInitVariables getInitVariables() { return initVariables; }

    WebglContext* context;
    Renderer2d renderer;
    MainLoop mainLoop;
    DampedSpringWeight weight;
    DampedSpring spring;

    EM_BOOL onPlayClicked(int eventType, const EmscriptenMouseEvent* mouseEvent, void* userData);
    EM_BOOL onStopClicked(int eventType, const EmscriptenMouseEvent* mouseEvent, void* userData);
    void load();
    void update(float32 deltaTimeSeconds, void* userData);
    void unload();

    void init(WebglContext* inContext) {
        context = inContext;
        emscripten_set_click_callback("#gl_canvas_play_damped", NULL, false, onPlayClicked);
        emscripten_set_click_callback("#gl_canvas_stop_damped", NULL, false, onStopClicked);
    }

    void load() {
        context->init("#gl_canvas_damped");

        renderer.load(context);

        weight.load(&renderer, initVariables.mass, Vector4 { 55.f, 235.f, 35.f, 255.f }, Vector4 { 235.f, 5.f, 235.f, 255.f });
        spring.load(&renderer, &weight, initVariables.springLength, 16.f, initVariables.initialDisplacement, initVariables.k, initVariables.c);

        mainLoop.run(update);
    }

    void update(float32 deltaTimeSeconds, void* userData) {
        // -- Update
        spring.update(deltaTimeSeconds);
        weight.update(deltaTimeSeconds);
	
        // -- Render
        renderer.render();
        weight.render(&renderer);
        spring.render(&renderer);
    }

    void unload() {
        mainLoop.stop();
        renderer.unload();
        weight.unload();
        spring.unload();
        context->destroy();
    }

    void DampedSpringWeight::load(Renderer2d* renderer, float32 inMass, Vector4 startColor, Vector4 endColor) {
        mass = inMass;
        radius = mass * 16.f;
        const int32 numSegments = 96;
        const float32 radiansPerSegment = (2.f * PI) / static_cast<float>(numSegments);
        const int32 numVertices = numSegments * 3;

        float32 t = 0.f;
        float32 tIncrement = 1.f / (numSegments / 2.f);
        startColor = startColor.toNormalizedColor();
        endColor = endColor.toNormalizedColor();

        Vertex2d vertices[numVertices];
        for (int idx = 0; idx < numSegments; idx++) {
            int vIdx = idx * 3;
        
            Vector4 color = lerp(startColor, endColor, t);
            if (idx >= numSegments / 2) {
                t -= tIncrement; 
            } else {
                t += tIncrement;
            }
        
            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);
    }

    void DampedSpringWeight::update(float32 dtSeconds) {
    
    }

    void DampedSpringWeight::render(Renderer2d* renderer) {
        shape.render(renderer);
    }

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

    const float32 epsilon = 0.0001f;

    void DampedSpring::load(Renderer2d* renderer, DampedSpringWeight* inWeight, float32 length, float32 loopRadius, float32 inInitialDisplacement, float32 inK, float32 inC) {
		initialDisplacement = inInitialDisplacement;
        weight = inWeight;
		k = inK;
		c = inC;

		// Set the quadratic terms to something that we're familiar with.
		float32 A = weight->mass;
		float32 B = c;
		float32 C = k;
		

		discriminant = B * B - (4 * A * C);
		timeElapsed = 0;
		displacement = 0;

        if (discriminant < epsilon && discriminant > -epsilon) {
			// Real repeated root (~ zero): Critically damped motion
			printf("Critically damped motion.\n");
			
			type = DampedSpringType::Critical;

			r1 = -B / (2 * A);
			r2 = r1;

			// Solve for the initial displacement.
			c2 = (initialDisplacement - r1) / (r2);
			c2 = r2 * c2;
			c1 = r1;
			printf("Equation: %f e^(%f t) + %f t e^(%f t)\n", c1, r1, c2, r2);
        }
        else if (discriminant > 0) {
			// Two real roots (greater than zero): Overdamped motion
			printf("Overdamped motion.\n");
			
			type = DampedSpringType::Overdamped;

			// Discover the two treal roots. Both of these WILL be negative.
			float32 sqrtDis = sqrtf(discriminant);
			r1 = (-B + sqrtDis) / (2 * A);
			r2 = (-B - sqrtDis) / (2 * A);

			// Now, solve for c1 and c2 given the initial displacement. The equation is:
			// x(0) = r1 * c1 * e^(r1 * t) + r2 * c2 * e^(r2 * t)   ->
			// x(0) = r1 * c1 + r2 * c2                             ->
			// initialDisplacement  = r1 * c1 + r2 * c2;            -> if abs(r1) > abs(r2) => c1 = 1, else c2 = 1
			if (r1 < r2) {
				c2 = (initialDisplacement - r1) / (r2);
				c2 = r2 * c2;
				c1 = r1;
			}
			else {
				c1 = (initialDisplacement - r2) / (r1);
				c1 = r1 * c1;
				c2 = r2;
			}

			printf("Equation: %f e^(%f t) + %f e^(%f t)\n", c1, r1, c2, r2);
        }
        else {
			// Complex pair (less than zero): Underdamped motion
			printf("Underdamped motion.\n");
			
			type = DampedSpringType::Underdamped;
			float32 sqrtDis = sqrtf(-discriminant);
            omega1 = sqrtf(sqrtDis) / (2.f * A); // Note that we negate the discriminant to get the REAL positive part.

			r1 = (-B + sqrtDis) / (2 * A);
			r2 = (-B - sqrtDis) / (2 * A);

			// Now, solve for c1 and c2 given the initial displacement. The equation is:
			// x(0) = r1 * c1 * e^(r1 * t) + r2 * c2 * e^(r2 * t)   ->
			// x(0) = r1 * c1 + r2 * c2                             ->
			// initialDisplacement  = r1 * c1 + r2 * c2;            -> if abs(r1) > abs(r2) => c1 = 1, else c2 = 1
			if (r1 < r2) {
				c2 = (initialDisplacement - r1) / (r2);
				c2 = r2 * c2;
				c1 = r1;
			}
			else {
				c1 = (initialDisplacement - r2) / (r1);
				c1 = r1 * c1;
				c2 = r2;
			}

			// At this point, we have:
			// x(t) = c1 cos(omega1 t) + c2 cos(omega1 t)     ->
			// x(t) = A cos(omega1 t - Φ)                     ->
			// Now we need to solve for A and Φ for our initial displacement, so:
			// initialDisplacement = c1
			R = sqrtf(c1 * c1 + c2 * c2);
			if (initialDisplacement < 0) {
				R = -R;
			}
			gamma = atanf(c2 / c1);

			printf("Equation: %f e^(-(%f / %f) t) * cos(%f t - %f)\n", R, c, weight->mass, omega1, gamma);
        }

        const int32 verticesPerSegment = 6;
        numSegments = 256;
        numVertices = numSegments * verticesPerSegment;
        vertices = new Vertex2d[numVertices];

        float32 lengthIncrement = length / static_cast<float32>(numSegments);

        const float32 frequency = 0.25f;
        const float32 loopWidth = 20.f;
        const float32 offset = 0.25f;

        int32 vidx = 0;
        for (int pidx = 0; pidx < numSegments; pidx++) {
            float32 y1 = lengthIncrement * pidx;
            float32 x1 = loopWidth * sinf(frequency * y1 + offset);

            float32 y2 = y1 + lengthIncrement;
            float32 x2 = loopWidth * sinf(frequency * y2 + offset);
        
            vertices[vidx++].position = Vector2(x1, y1);
            vertices[vidx++].position = Vector2(x1, y2);
            vertices[vidx++].position = Vector2(x2, y1);
            vertices[vidx++].position = Vector2(x2, y1);
            vertices[vidx++].position = Vector2(x1, y2);
            vertices[vidx++].position = Vector2(x2, y2);
        }

        shape.load(vertices, numVertices, renderer, GL_DYNAMIC_DRAW);
        shape.model = Mat4x4().translateByVec2(Vector2(400, 300));

        weight->shape.model = shape.model.translateByVec2(Vector2(0, -weight->radius));
    }

    void DampedSpring::update(float32 dtSeconds) {
        timeElapsed += dtSeconds;

		float32 lastDisplacement = displacement;

		switch (type) {
		case DampedSpringType::Critical:
			displacement = c1 * pow(E, r1 * timeElapsed) + c2 * timeElapsed * pow(E, r2 * timeElapsed);
			break;
		case DampedSpringType::Overdamped:
			displacement = c1 * pow(E, r1 * timeElapsed) + c2 * pow(E, r2 * timeElapsed);
			break;
		case DampedSpringType::Underdamped:  {
			float32 exponent = -(c / (2 * weight->mass)) * timeElapsed;
            displacement = R * pow(E, exponent) * (cosf(omega1 * timeElapsed - gamma));
			break;
		}
		default:
			break;
		}

		float32 dx = displacement - lastDisplacement;
        int32 vidx = 0;
        for (int pidx = 0; pidx < numSegments; pidx++) {
            float32 y1Offset = dx * (1.f - pidx / static_cast<float32>(numSegments));
            float32 y2Offset = dx * (1.f - (pidx + 1) / static_cast<float32>(numSegments));
            vertices[vidx++].position.y += y1Offset;
            vertices[vidx++].position.y += y2Offset;
            vertices[vidx++].position.y += y1Offset;
            vertices[vidx++].position.y += y1Offset;
            vertices[vidx++].position.y += y2Offset;
            vertices[vidx++].position.y += y2Offset;
        }

        weight->shape.model = weight->shape.model.translateByVec2(Vector2(0, dx));
    }

    void DampedSpring::render(Renderer2d* renderer) {
        glBindBuffer(GL_ARRAY_BUFFER, shape.vbo);
        glBufferSubData(GL_ARRAY_BUFFER, 0, numVertices * sizeof(Vertex2d), &vertices[0]);

        shape.render(renderer);
    }

    void DampedSpring::unload() {
        shape.unload();
        delete[] vertices;
    }


    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;
    }
}