3 #include "RandomWalk.hpp"
4 #include "../world/BlockType.hpp"
5 #include "../world/BlockTypeRegistry.hpp"
6 #include "../world/Entity.hpp"
7 #include "../world/World.hpp"
12 Spawner::Spawner(World &world)
16 , despawn_range(128 * 128)
17 , spawn_distance(16 * 16)
21 Spawn(world.Player().ChunkCoords(), { 0.5f, 0.5f, 0.5f });
29 void Spawner::Update(int dt) {
35 for (auto &ctrl : controllers) {
41 void Spawner::CheckDespawn() noexcept {
42 const Entity &reference = world.Player();
43 for (auto iter = controllers.begin(), end = controllers.end(); iter != end;) {
44 Entity &e = iter->Controlled();
45 glm::vec3 diff(reference.AbsoluteDifference(e));
46 if (dot(diff, diff) > despawn_range) {
48 iter = controllers.erase(iter);
55 void Spawner::TrySpawn() {
56 if (controllers.size() >= max_entities) return;
58 glm::tvec3<int> chunk(
59 (rand() % (chunk_range * 2 + 1)) - chunk_range,
60 (rand() % (chunk_range * 2 + 1)) - chunk_range,
61 (rand() % (chunk_range * 2 + 1)) - chunk_range
65 rand() % Chunk::width,
66 rand() % Chunk::height,
72 glm::vec3 diff(glm::vec3(chunk * Chunk::Extent() - pos) + world.Player().Position());
73 float dist = dot(diff, diff);
74 if (dist > despawn_range || dist < spawn_distance) {
79 // TODO: avoid force load, abort spawn if chunk unavailble
80 Chunk &tgt_chunk = world.Next(world.PlayerChunk(), chunk);
81 // TODO: don't use visibility for spawn check
82 // also, check for more than one block space
83 if (tgt_chunk.Type(tgt_chunk.BlockAt(pos)).visible) {
87 Spawn(world.Player().ChunkCoords() + chunk, glm::vec3(pos) + glm::vec3(0.5f));
90 void Spawner::Spawn(const glm::tvec3<int> &chunk, const glm::vec3 &pos) {
91 glm::vec3 color(rand() % 6, rand() % 6, rand() % 6);
92 color = color * 0.15f + 0.25f;
94 glm::vec3 rot(0.000001f);
95 rot.x *= (rand() % 32);
96 rot.y *= (rand() % 32);
97 rot.z *= (rand() % 32);
99 Entity &e = world.AddEntity();
101 e.Position(chunk, pos);
102 e.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
103 e.WorldCollidable(true);
104 e.SetShape(world.BlockTypes()[1].shape, color);
105 e.AngularVelocity(glm::quat(glm::vec3{ 0.00001f, 0.000006f, 0.000013f }));
106 controllers.emplace_back(e);