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();
73 iter = controllers.erase(iter);
76 glm::vec3 diff(reference.AbsoluteDifference(e));
77 if (dot(diff, diff) > despawn_range) {
80 iter = controllers.erase(iter);
87 void Spawner::TrySpawn() {
88 if (controllers.size() >= max_entities) return;
91 (rand() % (chunk_range * 2 + 1)) - chunk_range,
92 (rand() % (chunk_range * 2 + 1)) - chunk_range,
93 (rand() % (chunk_range * 2 + 1)) - chunk_range
97 rand() % Chunk::width,
98 rand() % Chunk::height,
104 glm::vec3 diff(glm::vec3(chunk * Chunk::Extent() - pos) + world.Player().Position());
105 float dist = dot(diff, diff);
106 if (dist > despawn_range || dist < spawn_distance) {
110 // check if the spawn block and the one above it are loaded and inhabitable
111 BlockLookup spawn_block(&world.PlayerChunk(), chunk * Chunk::Extent() + pos);
112 if (!spawn_block || spawn_block.GetType().collide_block) {
116 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
117 if (!head_block || head_block.GetType().collide_block) {
121 Spawn(world.Player().ChunkCoords() + chunk, glm::vec3(pos) + glm::vec3(0.5f));
124 void Spawner::Spawn(const glm::ivec3 &chunk, const glm::vec3 &pos) {
125 glm::vec3 rot(0.000001f);
126 rot.x *= (rand() % 1024);
127 rot.y *= (rand() % 1024);
128 rot.z *= (rand() % 1024);
130 Entity &e = world.AddEntity();
132 e.Position(chunk, pos);
133 e.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
134 e.WorldCollidable(true);
135 e.GetModel().SetNodeModel(&models[rand() % 3]);
136 e.AngularVelocity(rot);
139 ctrl = new RandomWalk(e);
141 ctrl = new Chaser(world, e, world.Player());
143 controllers.emplace_back(ctrl);