Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / games / voxels / src / main / rust / src / entity_part1.rs

entity_part1.rs274 lines · 12.5 KiBRaw
1// Append humanoid avatars for remote players (multiplayer). Each is drawn with the biped model — we
2// reuse the mob mesh path rather than a bespoke skeleton, so remote players read as villager-shaped
3// figures at the reported position/facing. `poses` is (position, yaw).
4pub fn append_remote_players(verts: &mut Vec<Vertex>, indices: &mut Vec<u32>, poses: &[(Vec3, f32)]) {
5 for &(pos, yaw) in poses {
6 let mut m = Mob::new(MobKind::Villager, pos, 1);
7 m.yaw = yaw;
8 m.append_mesh(verts, indices);
9 }
10}
11
12// ---- Projectiles: flying attacks (blaze fireballs, shulker bullets) and firework rockets. ----
13#[derive(Clone, Copy, PartialEq, Eq)]
14pub enum ProjKind { Fireball, ShulkerBullet, Firework, Snowball, EnderPearl }
15
16pub struct Projectile {
17 pub pos: Vec3,
18 pub vel: Vec3,
19 pub life: f32,
20 pub kind: ProjKind,
21 pub from_player: bool, // fired by the player (doesn't hurt the player)
22 pub damage: f32,
23 pub explosive: bool, // fireball detonates terrain on impact (ghast) vs. just bursting (blaze)
24}
25
26impl Projectile {
27 pub fn color(&self) -> [f32; 3] {
28 match self.kind {
29 ProjKind::Fireball => [1.0, 0.55, 0.12],
30 ProjKind::ShulkerBullet => [0.75, 0.55, 0.85],
31 ProjKind::Firework => [1.0, 0.9, 0.5],
32 ProjKind::Snowball => [0.95, 0.98, 1.0],
33 ProjKind::EnderPearl => [0.25, 0.85, 0.7],
34 }
35 }
36 pub fn size(&self) -> f32 { match self.kind { ProjKind::Fireball => 0.28, ProjKind::ShulkerBullet => 0.18, ProjKind::Firework => 0.16, ProjKind::Snowball => 0.14, ProjKind::EnderPearl => 0.16 } }
37 // Snowballs/ender pearls fall under gravity; the rest fly straight.
38 pub fn gravity(&self) -> f32 { match self.kind { ProjKind::Snowball | ProjKind::EnderPearl => 14.0, _ => 0.0 } }
39}
40
41// Render projectiles as bright, un-fading billboard quads (reuses the particle white-swatch UV).
42pub fn append_projectiles(verts: &mut Vec<Vertex>, indices: &mut Vec<u32>, ps: &[Projectile], right: Vec3, up: Vec3) {
43 for p in ps {
44 let s = p.size();
45 let c = p.color();
46 let (r, u) = (right * s, up * s);
47 let corners = [p.pos - r - u, p.pos + r - u, p.pos + r + u, p.pos - r + u];
48 let base = verts.len() as u32;
49 for cc in corners {
50 verts.push(Vertex { pos: [cc.x, cc.y, cc.z], uv: [PARTICLE_UV, PARTICLE_UV], color: c, ao: 1.0, tile_idx: 0.0, normal: [0.0, 1.0, 0.0], light: 0.0 });
51 }
52 indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
53 }
54}
55
56// ---- Particles: short-lived billboarded quads (block break, hits, explosions). ----
57pub struct Particle {
58 pub pos: Vec3,
59 pub vel: Vec3,
60 pub life: f32,
61 pub max_life: f32,
62 pub size: f32,
63 pub color: [f32; 3],
64 /// Downward acceleration. Debris uses `BURST_GRAVITY`; snow drifts at almost nothing.
65 pub gravity: f32,
66}
67
68pub const BURST_GRAVITY: f32 = 14.0;
69
70pub fn tick_particles(ps: &mut Vec<Particle>, dt: f32) {
71 for p in ps.iter_mut() {
72 p.vel.y -= p.gravity * dt;
73 p.pos += p.vel * dt;
74 p.life -= dt;
75 }
76 ps.retain(|p| p.life > 0.0);
77}
78
79// UV of the white swatch baked into the entity atlas (cell 15); particles tint it via vertex color.
80const PARTICLE_UV: f32 = 0.766;
81pub fn append_particles(verts: &mut Vec<Vertex>, indices: &mut Vec<u32>, ps: &[Particle], right: Vec3, up: Vec3) {
82 for p in ps {
83 let f = (p.life / p.max_life).clamp(0.0, 1.0);
84 let s = p.size * (0.35 + 0.65 * f);
85 let c = [p.color[0] * (0.4 + 0.6 * f), p.color[1] * (0.4 + 0.6 * f), p.color[2] * (0.4 + 0.6 * f)];
86 let (r, u) = (right * s, up * s);
87 let corners = [p.pos - r - u, p.pos + r - u, p.pos + r + u, p.pos - r + u];
88 let base = verts.len() as u32;
89 for cc in corners {
90 verts.push(Vertex { pos: [cc.x, cc.y, cc.z], uv: [PARTICLE_UV, PARTICLE_UV], color: c, ao: 1.0, tile_idx: 0.0, normal: [0.0, 1.0, 0.0], light: 0.0 });
91 }
92 indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
93 }
94}
95
96#[cfg(test)]
97mod tests {
98 use super::*;
99 use crate::world::block::Block;
100 use crate::world::ChunkMap;
101
102 // Terrain never reaches this high, so the test platform sits in clear air.
103 const SKY: i32 = 200;
104
105 fn world() -> ChunkMap {
106 let dir = std::env::temp_dir().join("voxels_mob_test").to_string_lossy().into_owned();
107 ChunkMap::new(3, dir)
108 }
109
110 /// A wide platform so a wandering mob can't stroll off it during the test.
111 fn platform(w: &mut ChunkMap, id: Id, meta: u8) {
112 for x in -6..=6 { for z in -6..=6 { w.set_block_meta_world(x, SKY, z, id, meta); } }
113 }
114
115 fn settle(w: &ChunkMap, kind: MobKind, from_y: f32) -> Mob {
116 let terrain = Terrain {
117 solid: &|x, y, z| w.solid_at(x, y, z),
118 surface: &|x, z, ceiling| w.surface_below(x, z, ceiling, 2),
119 };
120 let mut m = Mob::new(kind, Vec3::new(0.5, from_y, 0.5), 7);
121 // A player far away, so passive mobs just wander and hostiles don't charge off the platform.
122 let player = Vec3::new(0.5, from_y, 400.0);
123 for _ in 0..180 { m.tick(1.0 / 60.0, player, &terrain); }
124 m
125 }
126
127 // A mob standing on a slab must rest on its surface, not float at the cell boundary.
128 #[test]
129 fn a_mob_rests_on_a_slabs_surface() {
130 let mut w = world();
131 platform(&mut w, Block::StoneSlab as Id, 0);
132 let m = settle(&w, MobKind::Pig, SKY as f32 + 3.0);
133 assert!(m.on_ground, "the pig should have landed");
134 assert!((m.pos.y - (SKY as f32 + 0.5)).abs() < 1e-3,
135 "expected to stand on the slab top at {}, got {}", SKY as f32 + 0.5, m.pos.y);
136 }
137
138 // The same fall onto full blocks rests a whole block up, so the slab case really follows shape.
139 #[test]
140 fn a_mob_rests_a_whole_block_up_on_cubes() {
141 let mut w = world();
142 platform(&mut w, Block::Stone as Id, 0);
143 let m = settle(&w, MobKind::Pig, SKY as f32 + 3.0);
144 assert!((m.pos.y - (SKY as f32 + 1.0)).abs() < 1e-3, "got {}", m.pos.y);
145 }
146
147 // A top slab's solid half is its upper half, so a mob stands at the cell ceiling.
148 #[test]
149 fn a_mob_stands_on_top_of_a_top_slab() {
150 let mut w = world();
151 platform(&mut w, Block::StoneSlab as Id, crate::world::block::META_TOP);
152 let m = settle(&w, MobKind::Pig, SKY as f32 + 3.0);
153 assert!((m.pos.y - (SKY as f32 + 1.0)).abs() < 1e-3, "got {}", m.pos.y);
154 }
155
156 // Mobs step up half a block onto a slab rather than the full block they used to.
157 #[test]
158 fn a_mob_steps_up_onto_a_slab() {
159 let mut w = world();
160 // A long floor so the chase never runs off the end, with a slab ledge across the path.
161 for x in -3..=3 { for z in -20..=3 { w.set_block_world(x, SKY, z, Block::Stone as Id); } }
162 for x in -3..=3 { w.set_block_meta_world(x, SKY + 1, -3, Block::StoneSlab as Id, 0); }
163
164 let terrain = Terrain {
165 solid: &|x, y, z| w.solid_at(x, y, z),
166 surface: &|x, z, ceiling| w.surface_below(x, z, ceiling, 2),
167 };
168 let mut m = Mob::new(MobKind::Zombie, Vec3::new(0.5, SKY as f32 + 1.0, 0.5), 11);
169 // A hostile chases the player, who stands beyond the ledge.
170 let player = Vec3::new(0.5, SKY as f32 + 1.5, -8.0);
171 for _ in 0..240 { m.tick(1.0 / 60.0, player, &terrain); }
172
173 assert!(m.pos.z < -2.0, "the zombie should have reached the ledge, z = {}", m.pos.z);
174 assert!(m.pos.y >= SKY as f32 + 1.0, "and never sunk below the floor, y = {}", m.pos.y);
175 assert!(m.pos.y <= SKY as f32 + 2.0, "nor been launched onto a phantom full block, y = {}", m.pos.y);
176 }
177
178 // Matcha retunes hostiles per type rather than leaving them all on vanilla's flat 20 HP. This is a
179 // sanity net, not a spec: it catches a zero, a negative, and a stat typo an order of magnitude out.
180 #[test]
181 fn every_mob_has_plausible_stats() {
182 for &k in MobKind::ALL.iter() {
183 let (hp, sp) = (k.max_health(), k.speed());
184 assert!(hp > 0.0, "{k:?} spawns dead");
185 assert!(sp >= 0.0, "{k:?} walks backwards");
186 assert!(k.height() > 0.0 && k.hit_radius() > 0.0, "{k:?} can't be hit");
187 if k.is_boss() {
188 assert!(hp >= 100.0, "{k:?} is a boss with only {hp} HP");
189 } else {
190 assert!(hp <= 40.0, "{k:?} has boss-tier health at {hp}");
191 assert!(sp <= 3.0, "{k:?} moves at {sp}, faster than the player can react");
192 }
193 // Creepers do all their damage by detonating, and Ghasts by fireball, so neither needs a
194 // contact hit. Everything else hostile has to hurt you for walking into it.
195 if k.hostile() && k != MobKind::Creeper && !k.flies() {
196 assert!(k.contact_damage() > 0.0, "{k:?} is hostile but harmless");
197 }
198 if !k.hostile() { assert_eq!(k.contact_damage(), 0.0, "{k:?} is passive but hurts on touch"); }
199 }
200 // Zombies are the pressure mob and must out-pace the wandering livestock.
201 assert!(MobKind::Zombie.speed() > MobKind::Cow.speed());
202 }
203
204 // Variation has to be real but bounded, and deterministic for a given spawn seed.
205 #[test]
206 fn spawn_variation_stays_inside_its_bounds() {
207 for &k in MobKind::ALL.iter() {
208 let base = k.max_health();
209 let mut elites = 0;
210 let mut distinct = std::collections::HashSet::new();
211 let mut s = 0xDEAD_BEEFu32;
212 let rolls = 3000;
213 for _ in 0..rolls {
214 s ^= s << 13; s ^= s >> 17; s ^= s << 5;
215 let v = roll_variation(k, s);
216 assert_eq!(v.health, roll_variation(k, s).health, "{k:?} rolls differently for the same seed");
217 let cap = base * (1.0 + HEALTH_JITTER) * if v.elite { ELITE_HEALTH } else { 1.0 };
218 let floor = base * (1.0 - HEALTH_JITTER);
219 assert!(v.health >= floor - 1e-3 && v.health <= cap + 1e-3, "{k:?} rolled {} HP against a {base} base", v.health);
220 assert!(v.speed >= 0.0);
221 if v.elite { elites += 1; }
222 distinct.insert(v.health.to_bits());
223 }
224 if k.is_boss() {
225 assert_eq!(elites, 0, "{k:?} is a boss and must never roll elite");
226 assert_eq!(distinct.len(), 1, "{k:?} is a set-piece fight and must not vary");
227 } else {
228 assert!(distinct.len() > rolls / 2, "{k:?} barely varies: {} distinct rolls", distinct.len());
229 if k.hostile() {
230 let rate = elites as f32 / rolls as f32;
231 assert!((rate - ELITE_CHANCE).abs() < 0.03, "{k:?} elite rate {rate} is off target");
232 } else {
233 assert_eq!(elites, 0, "{k:?} is passive; an elite cow is just confusing");
234 }
235 }
236 }
237 }
238
239 // Anubis has to actually push the undead away, not merely stop them closing in.
240 #[test]
241 fn a_warded_mob_backs_off() {
242 let mut w = world();
243 for x in -6..=6 { for z in -6..=20 { w.set_block_world(x, SKY, z, Block::Stone as Id); } }
244 let terrain = Terrain {
245 solid: &|x, y, z| w.solid_at(x, y, z),
246 surface: &|x, z, ceiling| w.surface_below(x, z, ceiling, 2),
247 };
248 let player = Vec3::new(0.5, SKY as f32 + 1.5, 0.5);
249 let start = Vec3::new(0.5, SKY as f32 + 1.0, 5.5);
250
251 let mut chaser = Mob::new(MobKind::Zombie, start, 21);
252 for _ in 0..180 { chaser.tick(1.0 / 60.0, player, &terrain); }
253 let chased = (chaser.pos - player).length();
254
255 let mut warded = Mob::new(MobKind::Zombie, start, 21);
256 warded.repelled = 6.0;
257 for _ in 0..180 { warded.tick(1.0 / 60.0, player, &terrain); }
258 let kept = (warded.pos - player).length();
259
260 assert!(chased < 4.0, "an unwarded zombie should have closed in, dist = {chased}");
261 assert!(kept > 5.0, "a warded zombie should have backed off, dist = {kept}");
262 }
263
264 #[test]
265 fn an_elite_is_visibly_different() {
266 let mut elite = Mob::new(MobKind::Zombie, Vec3::ZERO, 7);
267 elite.elite = true;
268 let plain = Mob::new(MobKind::Zombie, Vec3::ZERO, 7);
269 assert_ne!(elite.tint(), plain.tint(), "an elite has to be readable before it reaches you");
270 // A villager's profession colour wins over the elite tint; villagers are never hostile.
271 let v = Mob::new(MobKind::Villager, Vec3::ZERO, 7);
272 assert_eq!(v.tint(), crate::villager::Profession::from_index(v.profession as usize).tint());
273 }
274}