]> git.lizzy.rs Git - shadowclad.git/blob - src/engine/scene.c
e1a4cee5f5c39101168ccf98e665f43266d769d2
[shadowclad.git] / src / engine / scene.c
1 #include <stdlib.h>
2
3 #include "engine/logger.h"
4
5 #include "scene.h"
6
7 Scene* currentScene = NULL;
8
9 static Transform identity = { .a1 = 1.0f, .a2 = 0.0f, .a3 = 0.0f, .a4 = 0.0f,
10                               .b1 = 0.0f, .b2 = 1.0f, .b3 = 0.0f, .b4 = 0.0f,
11                               .c1 = 0.0f, .c2 = 0.0f, .c3 = 1.0f, .c4 = 0.0f,
12                               .d1 = 0.0f, .d2 = 0.0f, .d3 = 0.0f, .d4 = 1.0f };
13
14 void multiply(Transform* transform, Transform by) {
15         GLfloat* a = (GLfloat*) &by;
16         GLfloat* b = (GLfloat*) transform;
17
18         for (size_t row = 0; row < 4; ++row) {
19                 for (size_t col = 0; col < 4; ++col) {
20                         b[(row * 4) + col] =
21                                 a[(row * 4) + 0] * b[(0 * 4) + col]
22                                 + a[(row * 4) + 1] * b[(1 * 4) + col]
23                                 + a[(row * 4) + 2] * b[(2 * 4) + col]
24                                 + a[(row * 4) + 3] * b[(3 * 4) + col];
25                 }
26         }
27 }
28
29 void translate(Transform* transform, Vector3D vec) {
30         multiply(transform, (Transform) { .a1 = 1.0f, .a2 = 0.0f, .a3 = 0.0f, .a4 = vec.x,
31                                       .b1 = 0.0f, .b2 = 1.0f, .b3 = 0.0f, .b4 = vec.y,
32                                       .c1 = 0.0f, .c2 = 0.0f, .c3 = 1.0f, .c4 = vec.z,
33                                       .d1 = 0.0f, .d2 = 0.0f, .d3 = 0.0f, .d4 = 1.0f });
34 }
35
36 Scene* newScene() {
37         Scene* scene = malloc(sizeof(Scene));
38         *scene = (Scene) { .parent = NULL,
39                            .numChildren = 0u,
40                            .children = NULL,
41                            .transform = identity,
42                            .solid = NULL };
43         return scene;
44 }
45
46 void insertChildScene(Scene* scene, Scene* newChild) {
47         if (!scene || !newChild) {
48                 return;
49         }
50         if (newChild->parent) {
51                 logError(
52                         "Cannot insert scene 0x%p as child of 0x%p, because it is already child of 0x%p",
53                         newChild,
54                         scene,
55                         newChild->parent);
56                 return;
57         }
58
59         scene->children = realloc(scene->children, ++(scene->numChildren) * sizeof(Scene*));
60         scene->children[scene->numChildren - 1] = newChild;
61
62         newChild->parent = scene;
63 }