4 #include "RandomWalk.hpp"
5 #include "../world/BlockLookup.hpp"
6 #include "../world/BlockType.hpp"
7 #include "../world/BlockTypeRegistry.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;
23 for (size_t i = 0; i < 14; ++i) {
24 world.BlockTypes()[i + 1].FillEntityModel(buf);
25 models[i].Update(buf);
30 Spawn(world.Player().ChunkCoords(), { 0.5f, 0.5f, 0.5f });
34 for (auto &ctrl : controllers) {
40 void Spawner::Update(int dt) {
46 for (auto &ctrl : controllers) {
52 void Spawner::CheckDespawn() noexcept {
53 const Entity &reference = world.Player();
54 for (auto iter = controllers.begin(), end = controllers.end(); iter != end;) {
55 Entity &e = (*iter)->Controlled();
56 glm::vec3 diff(reference.AbsoluteDifference(e));
57 if (dot(diff, diff) > despawn_range) {
60 iter = controllers.erase(iter);
67 void Spawner::TrySpawn() {
68 if (controllers.size() >= max_entities) return;
71 (rand() % (chunk_range * 2 + 1)) - chunk_range,
72 (rand() % (chunk_range * 2 + 1)) - chunk_range,
73 (rand() % (chunk_range * 2 + 1)) - chunk_range
77 rand() % Chunk::width,
78 rand() % Chunk::height,
84 glm::vec3 diff(glm::vec3(chunk * Chunk::Extent() - pos) + world.Player().Position());
85 float dist = dot(diff, diff);
86 if (dist > despawn_range || dist < spawn_distance) {
90 // check if the spawn block and the one above it are loaded and inhabitable
91 BlockLookup spawn_block(&world.PlayerChunk(), chunk * Chunk::Extent() + pos);
92 if (!spawn_block || spawn_block.GetType().collide_block) {
96 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
97 if (!head_block || head_block.GetType().collide_block) {
101 Spawn(world.Player().ChunkCoords() + chunk, glm::vec3(pos) + glm::vec3(0.5f));
104 void Spawner::Spawn(const glm::ivec3 &chunk, const glm::vec3 &pos) {
105 glm::vec3 rot(0.000001f);
106 rot.x *= (rand() % 1024);
107 rot.y *= (rand() % 1024);
108 rot.z *= (rand() % 1024);
110 Entity &e = world.AddEntity();
112 e.Position(chunk, pos);
113 e.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
114 e.WorldCollidable(true);
115 e.GetModel().SetNodeModel(&models[rand() % 14]);
116 e.AngularVelocity(rot);
119 ctrl = new RandomWalk(e);
121 ctrl = new Chaser(world, e, world.Player());
123 controllers.emplace_back(ctrl);