aboutsummaryrefslogtreecommitdiffstats
path: root/src/world.c
blob: 776c6b61945f21df70ba11c1b6571822ba09cce3 (plain) (blame)
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
#include "world.h"
#include "game.h"

size_t buildWorldBVHLeafs(BVHNode leafs[WORLD_ENTITY_MAX], const World* world)
{
  size_t leafsSize = 0;
  const Entity* entities = world->entities;
  bool grouped[WORLD_ENTITY_MAX];
  int ungroupedCount = WORLD_ENTITY_MAX;
  memset(grouped, 0, sizeof(grouped));

  while (ungroupedCount > 0)
  {
    BVHNode leaf;

    for (int leafIndex = 0; leafIndex < BVH_MAX; ++leafIndex)
    {
      int closest = -1;
      int closestGroupedIndex = 0;
      float closestDistance = world->size.x;

      // Find closest.
      for (int index = 0; index < WORLD_ENTITY_MAX; ++index)
      {
        if (grouped[index])
        {
          continue;
        }
        
        // First entity.
        if (leafIndex == 0)
        {
          closest = index;
          break;
        }

        float distance = 0.0;
        BoundingBox overlapBox;
        overlapBox.min = entities[index].position;
        overlapBox.max = overlapBox.min;

        for (int innerIndex = 0; innerIndex < leafIndex; ++innerIndex)
        {
          distance += Vector3Distance(
            entities[leaf.entities[innerIndex]].position,
            entities[index].position);
          overlapBox.min = Vector3Min(
            overlapBox.min,
            entities[leaf.entities[innerIndex]].box.min);
          overlapBox.min = Vector3Min(
            overlapBox.min,
            entities[index].box.min);
          overlapBox.max = Vector3Max(
            overlapBox.max,
            entities[leaf.entities[innerIndex]].box.max);
          overlapBox.max = Vector3Max(
            overlapBox.max,
            entities[index].box.max);
        }

        distance /= (float)leafIndex;

        bool overlaps = false;

        // Too big (will count it as a overlap).
        if (Vector3Distance(overlapBox.min, overlapBox.max) >= BVH_BOX_MAX)
        {
          overlaps = true;
        }

        // Check if overlap is already happening.
        for (int nodeIndex = 0; nodeIndex < leafsSize && !overlaps;
             ++nodeIndex)
        {
          if (CheckCollisionBoxes(overlapBox, leafs[nodeIndex].box))
          {
            overlaps = true;
            break;
          }
        }

        // Update distance.
        if (!overlaps && distance < closestDistance)
        {
          closestDistance = distance;
          closest = index;
        }
      }

      if (closest == -1)
      {
        leaf.entities[leafIndex] = -1;
      }
      else
      {
        leaf.entities[leafIndex] = closest;
        grouped[closest] = true;
        --ungroupedCount;
      }
    }

    // Get bounding box.
    leaf.box.min = world->entities[leaf.entities[0]].box.min;
    leaf.box.max = world->entities[leaf.entities[0]].box.max;

    for (int index = 1; index < BVH_MAX; ++index)
    {
      if (leaf.entities[index] == -1)
      {
        continue;
      }

      leaf.box.min = Vector3Min(
        leaf.box.min,
        world->entities[leaf.entities[index]].box.min);
      leaf.box.max = Vector3Max(
        leaf.box.max,
        world->entities[leaf.entities[index]].box.max);
    }

    memset(leaf.branches, 0, BVH_MAX_BRANCH_COUNT * sizeof(BVHNode*));
    leafs[leafsSize] = leaf;
    ++leafsSize;
  }

#ifdef FT_DEBUG_MODE
  // Test if everything is grouped.
  for (int index = 0; index < WORLD_ENTITY_MAX; ++index)
  {
    if (!grouped[index])
    {
      printf("Ungrouped: %d\n", index);
    }
  }

  // Test for leaf collision.
  for (int outer = 0; outer < leafsSize; ++outer)
  {
    for (int inner = 0; inner < leafsSize; ++inner)
    {
      if (outer != inner &&
          CheckCollisionBoxes(leafs[outer].box, leafs[inner].box))
      {
        printf("Leaf collision: %d and %d\n", outer, inner);
      }
    }
  }

  printf("leaf count: %ld\n", leafsSize);
#endif

  return leafsSize;
}

BVHNode buildWorldBVHTree(BVHNode* nodes, size_t nodesSize)
{
  BVHNode node;
  BVHNode usedNodes[nodesSize];
  size_t usedNodesSize = 0;
  memset(&node, 0, sizeof(BVHNode));

  // Add first node to branch.
  node.branches[0] = (BVHNode*)FT_MALLOC(sizeof(BVHNode));
  memcpy(node.branches[0], &nodes[0], sizeof(BVHNode));
  ++usedNodesSize;
  
  for (int index = 0; index < nodesSize; ++index)
  {
    
  }

  return node;
}

// Very messy right now. Mostly been playing around.
void buildWorldBVH(World* world)
{
  Entity* entities = world->entities;

  // Get leafs
  BVHNode leafs[WORLD_ENTITY_MAX];
  size_t leafsSize = buildWorldBVHLeafs(leafs, world);
  memcpy(world->bvhTest, leafs, sizeof(leafs));
  world->bvhTestSize = leafsSize;
}

World createWorld(int seed)
{
  World world;
  world.size = WORLD_SIZE;

  // Heightmap image.
  int offsetX = FT_RANDOM16(seed);
  int offsetY = FT_RANDOM16(seed);
  Image image = GenImagePerlinNoise(WORLD_IMAGE_WIDTH, WORLD_IMAGE_HEIGHT,
                                    offsetX, offsetY, WORLD_IMAGE_SCALE);

  // Heightmap.
  Mesh mesh = GenMeshHeightmap(image, world.size);
  world.heightmap = LoadModelFromMesh(mesh);
  world.texture = LoadTextureFromImage(image);
  world.heightmap.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture =
    world.texture;

  UnloadImage(image);

  // Entities.
  for (int index = 0; index < WORLD_ENTITY_MAX; ++index)
  {
    FT_RANDOM16(seed);
    
    Entity entity = createEntity(seed % ENTITY_COUNT, Vector3Zero());
    Vector3 position;
    position.x = FT_RANDOM16(seed) % (int)world.size.x;
    position.z = FT_RANDOM16(seed) % (int)world.size.z;
    position.y = getWorldHeightAtLocation(&world,
                                          position.x, position.z) + 1.0;
    setEntityPosition(&entity, position);
    
    world.entities[index] = entity;
  }

  double currentTime = GetTime();
  buildWorldBVH(&world);

#ifdef FT_DEBUG_MODE
  printf("BVH build time: %lf\n", GetTime() - currentTime);
#endif

  return world;
}

void updateWorld(World* world, Game* game)
{
  DrawModel(world->heightmap, Vector3Zero(), 1.0, WHITE);

  for (int index = 0; index < WORLD_ENTITY_MAX; ++index)
  {
    updateEntity(&world->entities[index], game);
  }

  // Draw BVH leafs.
#ifdef FT_DEBUG_MODE
  for (int index = 0; index < world->bvhTestSize; ++index)
  {
    Color colors[] = {RED, GREEN, BLUE, ORANGE, YELLOW, PINK};
    DrawBoundingBox(world->bvhTest[index].box, colors[index % 6]);
    DrawSphereEx(world->bvhTest[index].box.min, 0.3, 2, 2, BLUE);
    DrawSphereEx(world->bvhTest[index].box.max, 0.3, 2, 2, BLUE);
  }
#endif
}

void freeWorld(World world)
{
  UnloadTexture(world.texture);
  UnloadModel(world.heightmap);
}

float getWorldHeightAtLocation(const World* world, float x, float y)
{
  float mapX = (float)world->texture.width / world->size.x * x;
  float mapY = (float)world->texture.height / world->size.z * y;
  RayCollision result;

  for (int yOffset = -1; yOffset < 2; ++yOffset)
  {
    for (int xOffset = -1; xOffset < 2; ++xOffset)
    {
      int pixelX = mapX + xOffset;
      int pixelY = mapY + yOffset;

      if (pixelX < 0 || pixelX >= world->texture.width ||
          pixelY < 0 || pixelY >= world->texture.height)
      {
        continue;
      }

      int verticeStart = (pixelY * (world->texture.width - 1) + pixelX) * 18;
      float* vertices = &world->heightmap.meshes[0].vertices[verticeStart];

      // Cast to triangles at pixel. Really hacky indeed.
      Ray ray = (Ray){
        .position = (Vector3){x, world->size.y * 2.0, y},
        .direction = (Vector3){0.0, -1.0, 0.0}
      };

      result = GetRayCollisionTriangle(
        ray,
        (Vector3){vertices[0], vertices[1], vertices[2]},
        (Vector3){vertices[3], vertices[4], vertices[5]},
        (Vector3){vertices[6], vertices[7], vertices[8]});

      // Test other triangle.
      if (!result.hit)
      {
        result = GetRayCollisionTriangle(
          ray,
          (Vector3){vertices[9], vertices[10], vertices[11]},
          (Vector3){vertices[12], vertices[13], vertices[14]},
          (Vector3){vertices[15], vertices[16], vertices[17]});
      }

      if (result.hit)
      {
        return result.point.y;
      }
    }
  }

  return 0.0;
}

// Abortions are good. Get more abortions.