4 #include "RandomWalk.hpp"
5 #include "../world/BlockType.hpp"
6 #include "../world/BlockTypeRegistry.hpp"
7 #include "../world/Entity.hpp"
8 #include "../world/World.hpp"
13 Spawner::Spawner(World &world)
17 , despawn_range(128 * 128)
18 , spawn_distance(16 * 16)
21 EntityModel::Buffer buf;
22 for (size_t i = 0; i < 14; ++i) {
23 world.BlockTypes()[i + 1].FillEntityModel(buf);
24 models[i].Update(buf);
29 Spawn(world.Player().ChunkCoords(), { 0.5f, 0.5f, 0.5f });
33 for (auto &ctrl : controllers) {
39 void Spawner::Update(int dt) {
45 for (auto &ctrl : controllers) {
51 void Spawner::CheckDespawn() noexcept {
52 const Entity &reference = world.Player();
53 for (auto iter = controllers.begin(), end = controllers.end(); iter != end;) {
54 Entity &e = (*iter)->Controlled();
55 glm::vec3 diff(reference.AbsoluteDifference(e));
56 if (dot(diff, diff) > despawn_range) {
59 iter = controllers.erase(iter);
66 void Spawner::TrySpawn() {
67 if (controllers.size() >= max_entities) return;
70 (rand() % (chunk_range * 2 + 1)) - chunk_range,
71 (rand() % (chunk_range * 2 + 1)) - chunk_range,
72 (rand() % (chunk_range * 2 + 1)) - chunk_range
76 rand() % Chunk::width,
77 rand() % Chunk::height,
83 glm::vec3 diff(glm::vec3(chunk * Chunk::Extent() - pos) + world.Player().Position());
84 float dist = dot(diff, diff);
85 if (dist > despawn_range || dist < spawn_distance) {
90 // TODO: avoid force load, abort spawn if chunk unavailble
91 Chunk &tgt_chunk = world.Next(world.PlayerChunk(), chunk);
92 // TODO: don't use visibility for spawn check
93 // also, check for more than one block space
94 if (tgt_chunk.Type(tgt_chunk.BlockAt(pos)).visible) {
98 Spawn(world.Player().ChunkCoords() + chunk, glm::vec3(pos) + glm::vec3(0.5f));
101 void Spawner::Spawn(const glm::ivec3 &chunk, const glm::vec3 &pos) {
102 glm::vec3 rot(0.000001f);
103 rot.x *= (rand() % 1024);
104 rot.y *= (rand() % 1024);
105 rot.z *= (rand() % 1024);
107 Entity &e = world.AddEntity();
109 e.Position(chunk, pos);
110 e.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
111 e.WorldCollidable(true);
112 e.GetModel().SetNodeModel(&models[rand() % 14]);
113 e.AngularVelocity(rot);
116 ctrl = new RandomWalk(e);
118 ctrl = new Chaser(world, e, world.Player());
120 controllers.emplace_back(ctrl);