]> git.lizzy.rs Git - dragonblocks_alpha.git/blob - src/mapgen.c
f06c6f14d0782bf4d179231eba1155a9f0da9ee6
[dragonblocks_alpha.git] / src / mapgen.c
1 #include <stdlib.h>
2 #include <perlin/perlin.h>
3 #include "mapgen.h"
4
5 int seed = 0;
6 static Server *server = NULL;
7
8 // mapgen prototype
9 static void generate_block(MapBlock *block)
10 {
11         for (u8 x = 0; x < 16; x++) {
12                 s32 abs_x = x + block->pos.x * 16;
13                 for (u8 z = 0; z < 16; z++) {
14                         s32 abs_z = z + block->pos.z * 16;
15                         s32 height = noise2d(abs_x / 16, abs_z / 16, 1, seed) * 16;
16                         for (u8 y = 0; y < 16; y++) {
17                                 s32 abs_y = y + block->pos.y * 16;
18                                 Node type;
19                                 if (abs_y > height)
20                                         type = NODE_AIR;
21                                 else if (abs_y == height)
22                                         type = NODE_GRASS;
23                                 else if (abs_y >= height - 4)
24                                         type = NODE_DIRT;
25                                 else
26                                         type = NODE_STONE;
27                                 block->data[x][y][z] = map_node_create(type);
28                         }
29                 }
30         }
31         ITERATE_LIST(&server->clients, pair) {
32                 Client *client = pair->value;
33                 if (client->state == CS_ACTIVE) {
34                         pthread_mutex_lock(&client->mtx);
35                         (void) (write_u32(client->fd, CC_BLOCK) && map_serialize_block(client->fd, block));
36                         pthread_mutex_unlock(&client->mtx);
37                 }
38         }
39         block->ready = true;
40 }
41
42 void mapgen_init(Server *srv)
43 {
44         server = srv;
45         server->map->on_block_create = &generate_block;
46 }
47
48 static void *mapgen_thread(void *cliptr)
49 {
50         Client *client = cliptr;
51
52         while (client->state != CS_DISCONNECTED) {
53                 v3s32 pos = map_node_to_block_pos((v3s32) {client->pos.x, client->pos.y, client->pos.z}, NULL);
54                 for (s32 x = pos.x - 5; x < pos.x + 5; x++)
55                         for (s32 y = pos.y - 5; y < pos.y + 5; y++)
56                                 for (s32 z = pos.z - 5; z < pos.z + 5; z++)
57                                         map_get_block(client->server->map, (v3s32) {x, y, z}, true);
58         }
59
60         return NULL;
61 }
62
63 void mapgen_start_thread(Client *client)
64 {
65         (void) client;
66         (void) mapgen_thread;
67         pthread_t thread;
68         pthread_create(&thread, NULL, &mapgen_thread, client);
69 }