1use qualia_core_db::container_10d::provenance_section::ProvenanceSidecar;
2use qualia_core_db::render::assets::Mesh;
3use qualia_core_db::render::compile_10d::compile_mesh_to_10d_with_provenance;
4
5use super::layers::{
6 catalog::{find_layer, LayerDefinition, LayerSource},
7 mesh_gen, nasa_gibs, starfield,
8};
9
10pub struct CompiledLayerAsset {
11 pub layer_id: String,
12 pub container_10d: Vec<u8>,
13 pub vertex_count: u32,
14 pub triangle_count: u32,
15 pub positions: Vec<[f32; 3]>,
16 pub colors: Vec<[f32; 4]>,
17 pub indices: Vec<u32>,
18 pub source_format: String,
19 pub license: String,
20}
21
22pub async fn download_and_compile_layer(
24 layer_id: &str,
25 resolution: u32,
26) -> Result<CompiledLayerAsset, String> {
27 let layer = find_layer(layer_id).ok_or_else(|| format!("Unknown layer: {layer_id}"))?;
28
29 match &layer.source {
30 LayerSource::NasaGibs {
31 layer: gibs_layer,
32 projection,
33 } => download_and_compile_earth(gibs_layer, projection, resolution, layer).await,
34 LayerSource::YaleBrightStars => compile_bright_stars(layer),
35 LayerSource::HipparcosCatalog => compile_synthetic_stars(layer, resolution),
36 LayerSource::WmsImagery {
37 layer: wms_layer, ..
38 } if layer_id.starts_with("mars") || layer_id.starts_with("moon") => {
39 compile_planetary(layer, wms_layer, resolution)
40 }
41 _ => Err(format!(
42 "Layer '{}' source not yet supported for download",
43 layer_id
44 )),
45 }
46}
47
48async fn download_and_compile_earth(
49 gibs_layer: &str,
50 projection: &str,
51 resolution: u32,
52 layer_def: &LayerDefinition,
53) -> Result<CompiledLayerAsset, String> {
54 let req = nasa_gibs::GibsRequest {
55 layer: gibs_layer.to_string(),
56 projection: projection.to_string(),
57 width: resolution,
58 height: resolution / 2,
59 };
60
61 let texture = nasa_gibs::download_gibs_texture(&req)
62 .await
63 .map_err(|e| {
64 format!(
65 "GIBS download failed (layer: {gibs_layer}): {e}. Falling back to synthetic Earth."
66 )
67 })
68 .or_else(|e| {
69 eprintln!("GIBS download error: {e}");
70 Err(e)
71 });
72
73 let texture = match texture {
74 Ok(t) => Some(t),
75 Err(_) => None,
76 };
77
78 let segments = (resolution / 4).max(32).min(256);
79 let rings = segments / 2;
80
81 let (positions, colors, indices) =
82 mesh_gen::generate_sphere_mesh_colored(segments, rings, |lat, lon| {
83 if let Some(ref tex) = texture {
84 tex.sample(lat, lon)
85 } else {
86 let ocean = lat.abs() < 60.0;
87 let land = (lon.sin() * lat.cos() * 3.0).fract() > 0.3;
88 if ocean && land {
89 [0.2, 0.5, 0.2]
90 } else if ocean {
91 [0.1, 0.2, 0.5]
92 } else {
93 [0.9, 0.9, 0.95]
94 }
95 }
96 });
97
98 let mesh = Mesh {
99 positions: positions.clone(),
100 triangles: indices.chunks(3).map(|c| [c[0], c[1], c[2]]).collect(),
101 min: [-1.0, -1.0, -1.0],
102 max: [1.0, 1.0, 1.0],
103 };
104
105 let provenance = ProvenanceSidecar {
106 source_bytes: format!("NASA GIBS WMS: {gibs_layer}").into_bytes(),
107 source_media_type: "image/jpeg".to_string(),
108 licence: layer_def.license.to_string(),
109 vc: Vec::new(),
110 semantic_metadata: Vec::new(),
111 timestamp_epoch_s: std::time::SystemTime::now()
112 .duration_since(std::time::UNIX_EPOCH)
113 .unwrap_or_default()
114 .as_secs(),
115 version_hash: [0u8; 32],
116 };
117
118 let container_10d = compile_mesh_to_10d_with_provenance(&mesh, Some(&provenance))
119 .map_err(|e| format!("10D compilation: {e:?}"))?;
120
121 Ok(CompiledLayerAsset {
122 layer_id: layer_def.id.to_string(),
123 container_10d,
124 vertex_count: positions.len() as u32,
125 triangle_count: (indices.len() / 3) as u32,
126 positions,
127 colors,
128 indices,
129 source_format: "NASA GIBS WMS JPEG".to_string(),
130 license: layer_def.license.to_string(),
131 })
132}
133
134fn compile_bright_stars(layer_def: &LayerDefinition) -> Result<CompiledLayerAsset, String> {
135 let radius = 100.0f64;
136 let (positions, colors) = starfield::bright_stars_mesh(radius);
137
138 let indices: Vec<u32> = (0..positions.len() as u32).collect();
139
140 let mesh = Mesh {
141 positions: positions.clone(),
142 triangles: indices.chunks(1).map(|c| [c[0], c[0], c[0]]).collect(),
143 min: [-radius as f32, -radius as f32, -radius as f32],
144 max: [radius as f32, radius as f32, radius as f32],
145 };
146
147 let provenance = ProvenanceSidecar {
148 source_bytes: b"Yale Bright Star Catalog (embedded)".to_vec(),
149 source_media_type: "text/csv".to_string(),
150 licence: layer_def.license.to_string(),
151 vc: Vec::new(),
152 semantic_metadata: Vec::new(),
153 timestamp_epoch_s: 0,
154 version_hash: [0u8; 32],
155 };
156
157 let container_10d = compile_mesh_to_10d_with_provenance(&mesh, Some(&provenance))
158 .map_err(|e| format!("10D compilation: {e:?}"))?;
159
160 Ok(CompiledLayerAsset {
161 layer_id: layer_def.id.to_string(),
162 container_10d,
163 vertex_count: positions.len() as u32,
164 triangle_count: positions.len() as u32,
165 positions,
166 colors,
167 indices,
168 source_format: "Yale Bright Star Catalog".to_string(),
169 license: layer_def.license.to_string(),
170 })
171}
172
173fn compile_synthetic_stars(
174 layer_def: &LayerDefinition,
175 count: u32,
176) -> Result<CompiledLayerAsset, String> {
177 let radius = 200.0f64;
178 let count = count.min(50_000);
179 let (positions, colors) = starfield::generate_synthetic_starfield(count, radius, 42);
180
181 let indices: Vec<u32> = (0..positions.len() as u32).collect();
182
183 let mesh = Mesh {
184 positions: positions.clone(),
185 triangles: indices.chunks(1).map(|c| [c[0], c[0], c[0]]).collect(),
186 min: [-radius as f32, -radius as f32, -radius as f32],
187 max: [radius as f32, radius as f32, radius as f32],
188 };
189
190 let provenance = ProvenanceSidecar {
191 source_bytes: b"Synthetic starfield (procedural generation)".to_vec(),
192 source_media_type: "application/octet-stream".to_string(),
193 licence: layer_def.license.to_string(),
194 vc: Vec::new(),
195 semantic_metadata: Vec::new(),
196 timestamp_epoch_s: 0,
197 version_hash: [0u8; 32],
198 };
199
200 let container_10d = compile_mesh_to_10d_with_provenance(&mesh, Some(&provenance))
201 .map_err(|e| format!("10D compilation: {e:?}"))?;
202
203 Ok(CompiledLayerAsset {
204 layer_id: layer_def.id.to_string(),
205 container_10d,
206 vertex_count: positions.len() as u32,
207 triangle_count: positions.len() as u32,
208 positions,
209 colors,
210 indices,
211 source_format: "Synthetic procedural starfield".to_string(),
212 license: layer_def.license.to_string(),
213 })
214}
215
216fn compile_planetary(
217 layer_def: &LayerDefinition,
218 _wms_layer: &str,
219 resolution: u32,
220) -> Result<CompiledLayerAsset, String> {
221 let segments = (resolution / 4).max(32).min(128);
222 let rings = segments / 2;
223
224 let base_color = layer_def.preview_color;
225 let body_id = layer_def.id;
226
227 let (positions, colors, indices) =
228 mesh_gen::generate_sphere_mesh_colored(segments, rings, |lat, lon| {
229 let crater_noise = ((lat * 7.0).sin() * (lon * 5.0).cos()
230 + (lat * 3.0).cos() * (lon * 11.0).sin())
231 * 0.15;
232 let r = (base_color[0] + crater_noise).clamp(0.0, 1.0);
233 let g = (base_color[1] + crater_noise * 0.8).clamp(0.0, 1.0);
234 let b = (base_color[2] + crater_noise * 0.6).clamp(0.0, 1.0);
235 let _ = body_id;
236 [r, g, b]
237 });
238
239 let mesh = Mesh {
240 positions: positions.clone(),
241 triangles: indices.chunks(3).map(|c| [c[0], c[1], c[2]]).collect(),
242 min: [-1.0, -1.0, -1.0],
243 max: [1.0, 1.0, 1.0],
244 };
245
246 let provenance = ProvenanceSidecar {
247 source_bytes: format!("Planetary body: {}", layer_def.name).into_bytes(),
248 source_media_type: "model/gltf-binary".to_string(),
249 licence: layer_def.license.to_string(),
250 vc: Vec::new(),
251 semantic_metadata: Vec::new(),
252 timestamp_epoch_s: 0,
253 version_hash: [0u8; 32],
254 };
255
256 let container_10d = compile_mesh_to_10d_with_provenance(&mesh, Some(&provenance))
257 .map_err(|e| format!("10D compilation: {e:?}"))?;
258
259 Ok(CompiledLayerAsset {
260 layer_id: layer_def.id.to_string(),
261 container_10d,
262 vertex_count: positions.len() as u32,
263 triangle_count: (indices.len() / 3) as u32,
264 positions,
265 colors,
266 indices,
267 source_format: "Procedural planetary surface".to_string(),
268 license: layer_def.license.to_string(),
269 })
270}