qualia_client_core/chora/layers/
mesh_gen.rs1use qualia_core_db::render::assets::Mesh;
2
3pub fn generate_sphere_mesh(segments: u32, rings: u32) -> Mesh {
5 let mut positions = Vec::new();
6 let mut triangles = Vec::new();
7
8 for r in 0..=rings {
9 let phi = std::f32::consts::PI * (r as f32) / (rings as f32);
10 let y = phi.cos();
11 let radius = phi.sin();
12 for s in 0..=segments {
13 let theta = 2.0 * std::f32::consts::PI * (s as f32) / (segments as f32);
14 let x = radius * theta.cos();
15 let z = radius * theta.sin();
16 positions.push([x, y, z]);
17 }
18 }
19
20 for r in 0..rings {
21 for s in 0..segments {
22 let a = r * (segments + 1) + s;
23 let b = a + segments + 1;
24 if r > 0 {
25 triangles.push([a, b, a + 1]);
26 }
27 if r < rings - 1 {
28 triangles.push([a + 1, b, b + 1]);
29 }
30 }
31 }
32
33 let min = [-1.0, -1.0, -1.0];
34 let max = [1.0, 1.0, 1.0];
35 Mesh {
36 positions,
37 triangles,
38 min,
39 max,
40 }
41}
42
43pub fn generate_sphere_mesh_colored(
45 segments: u32,
46 rings: u32,
47 color_sampler: impl Fn(f32, f32) -> [f32; 3],
48) -> (Vec<[f32; 3]>, Vec<[f32; 4]>, Vec<u32>) {
49 let mesh = generate_sphere_mesh(segments, rings);
50 let mut colors = Vec::with_capacity(mesh.positions.len());
51 for &p in &mesh.positions {
52 let lat = p[1].asin().to_degrees();
53 let lon = p[0].atan2(p[2]).to_degrees();
54 let [r, g, b] = color_sampler(lat, lon);
55 colors.push([r, g, b, 1.0]);
56 }
57 let indices: Vec<u32> = mesh
58 .triangles
59 .iter()
60 .flat_map(|t| [t[0], t[1], t[2]])
61 .collect();
62 (mesh.positions, colors, indices)
63}
64
65pub fn generate_starfield_mesh(positions: &[[f32; 3]], colors: &[[f32; 4]]) -> Mesh {
67 let triangles: Vec<[u32; 3]> = (0..positions.len() as u32)
68 .step_by(1)
69 .map(|i| [i, i, i])
70 .collect();
71 let _ = colors;
72 let min = [-1e6, -1e6, -1e6];
73 let max = [1e6, 1e6, 1e6];
74 Mesh {
75 positions: positions.to_vec(),
76 triangles,
77 min,
78 max,
79 }
80}
81
82pub fn generate_terrain_mesh(heightfield: &[f32], width: u32, height: u32, scale: f32) -> Mesh {
84 let mut positions = Vec::with_capacity((width * height) as usize);
85 let mut triangles = Vec::new();
86
87 for y in 0..height {
88 for x in 0..width {
89 let idx = (y * width + x) as usize;
90 let h = heightfield.get(idx).copied().unwrap_or(0.0) * scale;
91 let px = (x as f32 / width as f32 - 0.5) * 2.0;
92 let pz = (y as f32 / height as f32 - 0.5) * 2.0;
93 positions.push([px, h, pz]);
94 }
95 }
96
97 for y in 0..height - 1 {
98 for x in 0..width - 1 {
99 let a = (y * width + x) as u32;
100 let b = a + 1;
101 let c = a + width;
102 let d = c + 1;
103 triangles.push([a, c, b]);
104 triangles.push([b, c, d]);
105 }
106 }
107
108 let min = [-1.0, 0.0, -1.0];
109 let max = [1.0, scale, 1.0];
110 Mesh {
111 positions,
112 triangles,
113 min,
114 max,
115 }
116}