4 #include "RandomWalk.hpp"
5 #include "../model/shapes.hpp"
6 #include "../world/BlockLookup.hpp"
7 #include "../world/BlockType.hpp"
8 #include "../world/Entity.hpp"
9 #include "../world/World.hpp"
14 Spawner::Spawner(World &world)
18 , despawn_range(128 * 128)
19 , spawn_distance(16 * 16)
22 EntityModel::Buffer buf;
24 CuboidShape shape({{ -0.25f, -0.5f, -0.25f }, { 0.25f, 0.5f, 0.25f }});
25 shape.Vertices(buf, 1.0f);
26 buf.colors.resize(shape.VertexCount(), { 1.0f, 1.0f, 0.0f });
27 models[0].Update(buf);
30 CuboidShape shape({{ -0.5f, -0.25f, -0.5f }, { 0.5f, 0.25f, 0.5f }});
32 shape.Vertices(buf, 2.0f);
33 buf.colors.resize(shape.VertexCount(), { 0.0f, 1.0f, 1.0f });
34 models[1].Update(buf);
37 StairShape shape({{ -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f }}, { 0.4f, 0.4f });
39 shape.Vertices(buf, 3.0f);
40 buf.colors.resize(shape.VertexCount(), { 1.0f, 0.0f, 1.0f });
41 models[2].Update(buf);
45 Spawn(world.Player().ChunkCoords(), { 0.5f, 0.5f, 0.5f });
49 for (auto &ctrl : controllers) {
55 void Spawner::Update(int dt) {
61 for (auto &ctrl : controllers) {
67 void Spawner::CheckDespawn() noexcept {
68 const Entity &reference = world.Player();
69 for (auto iter = controllers.begin(), end = controllers.end(); iter != end;) {
70 Entity &e = (*iter)->Controlled();
71 glm::vec3 diff(reference.AbsoluteDifference(e));
72 if (dot(diff, diff) > despawn_range) {
75 iter = controllers.erase(iter);
82 void Spawner::TrySpawn() {
83 if (controllers.size() >= max_entities) return;
86 (rand() % (chunk_range * 2 + 1)) - chunk_range,
87 (rand() % (chunk_range * 2 + 1)) - chunk_range,
88 (rand() % (chunk_range * 2 + 1)) - chunk_range
92 rand() % Chunk::width,
93 rand() % Chunk::height,
99 glm::vec3 diff(glm::vec3(chunk * Chunk::Extent() - pos) + world.Player().Position());
100 float dist = dot(diff, diff);
101 if (dist > despawn_range || dist < spawn_distance) {
105 // check if the spawn block and the one above it are loaded and inhabitable
106 BlockLookup spawn_block(&world.PlayerChunk(), chunk * Chunk::Extent() + pos);
107 if (!spawn_block || spawn_block.GetType().collide_block) {
111 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
112 if (!head_block || head_block.GetType().collide_block) {
116 Spawn(world.Player().ChunkCoords() + chunk, glm::vec3(pos) + glm::vec3(0.5f));
119 void Spawner::Spawn(const glm::ivec3 &chunk, const glm::vec3 &pos) {
120 glm::vec3 rot(0.000001f);
121 rot.x *= (rand() % 1024);
122 rot.y *= (rand() % 1024);
123 rot.z *= (rand() % 1024);
125 Entity &e = world.AddEntity();
127 e.Position(chunk, pos);
128 e.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
129 e.WorldCollidable(true);
130 e.GetModel().SetNodeModel(&models[rand() % 3]);
131 e.AngularVelocity(rot);
134 ctrl = new RandomWalk(e);
136 ctrl = new Chaser(world, e, world.Player());
138 controllers.emplace_back(ctrl);