aboutsummaryrefslogtreecommitdiffstats
path: root/src/world.c
blob: 35130426e21b003162f00f2312358cc89541c18c (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
#include "world.h"
#include "game.h"

World createWorld(const Assets* assets)
{
  World world;
  world.size = (Vector3){1000.0, 20.0, 1000.0};
  world.image = &assets->images[HEIGHT_MAP_IMAGE];

  // Heightmap.
  Mesh mesh = GenMeshHeightmap(*world.image, world.size);
  world.heightmap = LoadModelFromMesh(mesh);
  world.heightmap.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture =
    assets->textures[HEIGHT_MAP_TEXTURE];

  uint32_t seed = 57;

  // Entities.
  for (int index = 0; index < WORLD_ENTITY_MAX; ++index)
  {
    FT_RANDOM16(seed);
    
    Entity entity = createEntity(seed % ENTITY_COUNT, Vector3Zero());
    FT_RANDOM16(seed);
    // It be funky and give negative numbers.
    entity.position.x = seed % (int)world.size.x;
    FT_RANDOM16(seed);
    entity.position.z = seed % (int)world.size.z;
    entity.position.y = getWorldHeightAtLocation(world, entity.position.x,
                                                 entity.position.z) + 1.0;
    world.entities[index] = entity;
  }

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

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

float getWorldPixelHeight(World world, int x, int y)
{
  int verticeStart = (y * (world.image->width - 1) + x) * 18;
  float height = 0.0;
  int count = 0;

  for (int index = 1; index < 18; index += 3)
  {
    height += world.heightmap.meshes[0].vertices[verticeStart + index];
    ++count;
  }

  return (float)height / count;
}

float getWorldHeightAtLocation(World world, float x, float y)
{
  float toMapX = (float)world.image->width / world.size.x;
  float toMapY = (float)world.image->height / world.size.z;
  int pixelX = roundf((float)x * toMapX);
  int pixelY = roundf((float)y * toMapY);

  return getWorldPixelHeight(world, pixelX, pixelY);
}

// Abortions are good. Get more abortions.