1use super::envelope::*;
8use super::types::*;
9
10pub const PV_RECORD_STRIDE: u32 = 64;
11
12pub const PV_VALID_PRESSURE: u32 = 1 << 0;
13pub const PV_VALID_VELOCITY: u32 = 1 << 1;
14pub const PV_VALID_ENERGY: u32 = 1 << 2;
15pub const PV_VALID_INTENSITY: u32 = 1 << 3;
16pub const PV_VALID_ALL: u32 =
17 PV_VALID_PRESSURE | PV_VALID_VELOCITY | PV_VALID_ENERGY | PV_VALID_INTENSITY;
18
19#[derive(Debug, Clone, Copy, PartialEq)]
21pub struct PressureVelocityRecord {
22 pub position_m: [f32; 3],
23 pub pressure_pa: f32,
24 pub particle_velocity_m_s: [f32; 3],
25 pub energy_density_j_m3: f32,
26 pub intensity_w_m2: [f32; 3],
27 pub material_ref: u32,
28 pub validity_bits: u32,
29}
30
31impl PressureVelocityRecord {
32 pub fn validate(&self, externally_valid: bool) -> Result<(), ProfileError> {
33 for c in self.position_m {
34 if !c.is_finite() {
35 return Err(ProfileError::NonFiniteFloat);
36 }
37 }
38 if !self.pressure_pa.is_finite()
39 || !self.energy_density_j_m3.is_finite()
40 || self.particle_velocity_m_s.iter().any(|v| !v.is_finite())
41 || self.intensity_w_m2.iter().any(|v| !v.is_finite())
42 {
43 return Err(ProfileError::NonFiniteFloat);
44 }
45 if self.validity_bits & !PV_VALID_ALL != 0 {
46 return Err(ProfileError::InvalidValidityBits);
47 }
48 if !externally_valid {
49 if self.validity_bits != 0
50 || self.position_m.iter().any(|v| v.to_bits() != 0)
51 || self.pressure_pa.to_bits() != 0
52 || self.particle_velocity_m_s.iter().any(|v| v.to_bits() != 0)
53 || self.energy_density_j_m3.to_bits() != 0
54 || self.intensity_w_m2.iter().any(|v| v.to_bits() != 0)
55 {
56 return Err(ProfileError::MaskedLaneNonZero);
57 }
58 return Ok(());
59 }
60 require_zero_when_masked((self.validity_bits & PV_VALID_PRESSURE) != 0, self.pressure_pa)?;
61 require_zero_vec3_when_masked(
62 (self.validity_bits & PV_VALID_VELOCITY) != 0,
63 self.particle_velocity_m_s,
64 )?;
65 require_zero_when_masked(
66 (self.validity_bits & PV_VALID_ENERGY) != 0,
67 self.energy_density_j_m3,
68 )?;
69 require_zero_vec3_when_masked(
70 (self.validity_bits & PV_VALID_INTENSITY) != 0,
71 self.intensity_w_m2,
72 )?;
73 if (self.validity_bits & PV_VALID_ENERGY) != 0 && self.energy_density_j_m3 < 0.0 {
74 return Err(ProfileError::InvalidMetadata("energy_density_j_m3 must be >= 0"));
75 }
76 Ok(())
77 }
78
79 pub fn decode(bytes: &[u8], externally_valid: bool) -> Result<Self, ProfileError> {
80 if bytes.len() != PV_RECORD_STRIDE as usize {
81 return Err(ProfileError::InvalidPayloadLength);
82 }
83 ensure_zero_bytes(&bytes[52..64])?;
84 let rec = Self {
85 position_m: read_f32_3(bytes, 0)?,
86 pressure_pa: read_f32_finite(bytes, 12)?,
87 particle_velocity_m_s: read_f32_3(bytes, 16)?,
88 energy_density_j_m3: read_f32_finite(bytes, 28)?,
89 intensity_w_m2: read_f32_3(bytes, 32)?,
90 material_ref: read_u32(bytes, 44)?,
91 validity_bits: read_u32(bytes, 48)?,
92 };
93 rec.validate(externally_valid)?;
94 Ok(rec)
95 }
96
97 pub fn encode_into(&self, out: &mut [u8], externally_valid: bool) -> Result<(), ProfileError> {
98 if out.len() != PV_RECORD_STRIDE as usize {
99 return Err(ProfileError::InvalidPayloadLength);
100 }
101 self.validate(externally_valid)?;
102 out.fill(0);
103 write_f32_slice(out, 0, &self.position_m)?;
104 write_f32_finite(out, 12, self.pressure_pa)?;
105 write_f32_slice(out, 16, &self.particle_velocity_m_s)?;
106 write_f32_finite(out, 28, self.energy_density_j_m3)?;
107 write_f32_slice(out, 32, &self.intensity_w_m2)?;
108 write_u32(out, 44, self.material_ref);
109 write_u32(out, 48, self.validity_bits);
110 Ok(())
111 }
112}
113
114pub struct PressureVelocityChunkView<'a> {
116 bytes: &'a [u8],
117 mask: Option<&'a [u8]>,
118}
119
120impl<'a> PressureVelocityChunkView<'a> {
121 pub fn len(&self) -> usize {
122 self.bytes.len() / PV_RECORD_STRIDE as usize
123 }
124
125 pub fn is_empty(&self) -> bool {
126 self.bytes.is_empty()
127 }
128
129 pub fn get(&self, index: usize) -> Result<PressureVelocityRecord, ProfileError> {
130 let start = index
131 .checked_mul(PV_RECORD_STRIDE as usize)
132 .ok_or(ProfileError::Overflow)?;
133 let end = start
134 .checked_add(PV_RECORD_STRIDE as usize)
135 .ok_or(ProfileError::Overflow)?;
136 let slice = self
137 .bytes
138 .get(start..end)
139 .ok_or(ProfileError::OutOfBoundsIndex("pv record index"))?;
140 let ext_valid = self.mask.map_or(true, |m| m[index] != 0);
141 PressureVelocityRecord::decode(slice, ext_valid)
142 }
143}
144
145#[derive(Debug, Clone, PartialEq)]
147pub enum FluidMediumModel {
148 FluidLinear {
150 density_kg_m3: f64,
151 bulk_modulus_pa: f64,
152 temperature_k: Option<f64>,
153 ambient_pressure_pa: Option<f64>,
154 flow_m_s: Option<[f64; 3]>,
155 matter_digest: Option<[u8; 32]>,
156 material_table_digest: Option<[u8; 32]>,
157 material_table_epoch: Option<u64>,
158 material_ids: Vec<u64>,
159 },
160 VacuumMask { mask_entry_index: u32 },
162 UnknownMedium,
164 ExtendedConstitutive {
166 model_uri: String,
167 viscosity_pa_s: Option<f64>,
168 dispersion_model_uri: Option<String>,
169 anisotropy_uri: Option<String>,
170 poroelastic_uri: Option<String>,
171 material_ids: Vec<u64>,
172 },
173}
174
175impl FluidMediumModel {
176 pub fn air_20c() -> Self {
177 Self::FluidLinear {
178 density_kg_m3: 1.204,
179 bulk_modulus_pa: 142_000.0,
180 temperature_k: Some(293.15),
181 ambient_pressure_pa: Some(101_325.0),
182 flow_m_s: None,
183 matter_digest: None,
184 material_table_digest: None,
185 material_table_epoch: None,
186 material_ids: Vec::new(),
187 }
188 }
189
190 pub fn validate(&self) -> Result<(), ProfileError> {
191 match self {
192 Self::FluidLinear {
193 density_kg_m3,
194 bulk_modulus_pa,
195 temperature_k,
196 ambient_pressure_pa,
197 flow_m_s,
198 material_table_digest,
199 material_table_epoch,
200 ..
201 } => {
202 if !density_kg_m3.is_finite() || *density_kg_m3 <= 0.0 {
203 return Err(ProfileError::MediumMissingOrUnknown(
204 "fluid density must be finite > 0 (use VacuumMask for vacuum)",
205 ));
206 }
207 if !bulk_modulus_pa.is_finite() || *bulk_modulus_pa <= 0.0 {
208 return Err(ProfileError::MediumMissingOrUnknown(
209 "fluid bulk modulus must be finite > 0",
210 ));
211 }
212 if let Some(t) = temperature_k {
213 if !t.is_finite() || *t <= 0.0 {
214 return Err(ProfileError::MediumMissingOrUnknown("temperature must be > 0 K"));
215 }
216 }
217 if let Some(p0) = ambient_pressure_pa {
218 if !p0.is_finite() || *p0 <= 0.0 {
219 return Err(ProfileError::MediumMissingOrUnknown("ambient pressure must be > 0 Pa"));
220 }
221 }
222 if let Some(flow) = flow_m_s {
223 if flow.iter().any(|v| !v.is_finite()) {
224 return Err(ProfileError::NonFiniteFloat);
225 }
226 }
227 if material_table_digest.is_some() ^ material_table_epoch.is_some() {
228 return Err(ProfileError::InvalidMetadata("table_digest and epoch must pair"));
229 }
230 Ok(())
231 }
232 Self::VacuumMask { mask_entry_index } => {
233 if *mask_entry_index == 0 {
234 return Err(ProfileError::MediumMissingOrUnknown("vacuum mask entry must be >= 1"));
235 }
236 Ok(())
237 }
238 Self::UnknownMedium => Ok(()),
239 Self::ExtendedConstitutive {
240 model_uri,
241 viscosity_pa_s,
242 ..
243 } => {
244 validate_identifier_str(model_uri, "medium.model_uri")?;
245 if let Some(mu) = viscosity_pa_s {
246 if !mu.is_finite() || *mu < 0.0 {
247 return Err(ProfileError::InvalidMetadata("viscosity_pa_s"));
248 }
249 }
250 Ok(())
251 }
252 }
253 }
254
255 pub fn speed_of_sound_m_s(&self) -> Result<f64, ProfileError> {
256 match self {
257 Self::FluidLinear {
258 density_kg_m3,
259 bulk_modulus_pa,
260 ..
261 } => {
262 self.validate()?;
263 Ok((bulk_modulus_pa / density_kg_m3).sqrt())
264 }
265 Self::VacuumMask { .. } => Err(ProfileError::MediumMissingOrUnknown(
266 "vacuum cannot propagate linear acoustic pressure waves",
267 )),
268 Self::UnknownMedium => Err(ProfileError::MediumMissingOrUnknown(
269 "unknown medium cannot supply speed of sound",
270 )),
271 Self::ExtendedConstitutive { .. } => Err(ProfileError::UnsupportedConstitutiveModel(
272 "extended viscous/dispersive/anisotropic/poroelastic medium requires dedicated solver profile",
273 )),
274 }
275 }
276
277 pub fn impedance_rayl(&self) -> Result<f64, ProfileError> {
278 match self {
279 Self::FluidLinear {
280 density_kg_m3,
281 bulk_modulus_pa,
282 ..
283 } => {
284 self.validate()?;
285 Ok((density_kg_m3 * bulk_modulus_pa).sqrt())
286 }
287 _ => Err(ProfileError::MediumMissingOrUnknown(
288 "impedance undefined outside FluidLinear",
289 )),
290 }
291 }
292
293 fn push_schema_200(&self, meta: &mut MetadataBuilder, id: u32) -> Result<u32, ProfileError> {
294 self.validate()?;
295 let mut fields = Vec::new();
296 match self {
297 Self::FluidLinear {
298 density_kg_m3,
299 bulk_modulus_pa,
300 temperature_k,
301 ambient_pressure_pa,
302 flow_m_s,
303 matter_digest,
304 material_table_digest,
305 material_table_epoch,
306 material_ids,
307 } => {
308 fields.push(OwnedField::crit(
309 1,
310 OwnedValue::Utf8("fluid-linear".to_owned()),
311 ));
312 fields.push(OwnedField::crit(2, OwnedValue::F64(vec![*density_kg_m3])));
313 fields.push(OwnedField::crit(3, OwnedValue::F64(vec![*bulk_modulus_pa])));
314 if let Some(t) = temperature_k {
315 fields.push(OwnedField::opt(5, OwnedValue::F64(vec![*t])));
316 }
317 if let Some(p) = ambient_pressure_pa {
318 fields.push(OwnedField::opt(6, OwnedValue::F64(vec![*p])));
319 }
320 if let Some(flow) = flow_m_s {
321 fields.push(OwnedField::opt(7, OwnedValue::F64(flow.to_vec())));
322 }
323 if let Some(d) = matter_digest {
324 fields.push(OwnedField::opt(8, OwnedValue::Bytes(d.to_vec())));
325 }
326 if let Some(td) = material_table_digest {
327 fields.push(OwnedField::opt(9, OwnedValue::Bytes(td.to_vec())));
328 }
329 if let Some(te) = material_table_epoch {
330 fields.push(OwnedField::opt(10, OwnedValue::U64(vec![*te])));
331 }
332 if !material_ids.is_empty() {
333 fields.push(OwnedField::opt(11, OwnedValue::U64(material_ids.clone())));
334 }
335 }
336 Self::VacuumMask { mask_entry_index } => {
337 fields.push(OwnedField::crit(
338 1,
339 OwnedValue::Utf8("vacuum-mask".to_owned()),
340 ));
341 fields.push(OwnedField::crit(
342 13,
343 OwnedValue::EntryRefs(vec![*mask_entry_index]),
344 ));
345 }
346 Self::UnknownMedium => {
347 fields.push(OwnedField::crit(
348 1,
349 OwnedValue::Utf8("unknown-medium".to_owned()),
350 ));
351 }
352 Self::ExtendedConstitutive {
353 model_uri,
354 material_ids,
355 ..
356 } => {
357 fields.push(OwnedField::crit(1, OwnedValue::Utf8(model_uri.clone())));
358 if !material_ids.is_empty() {
359 fields.push(OwnedField::opt(11, OwnedValue::U64(material_ids.clone())));
360 }
361 }
362 }
363 meta.push_block(OwnedBlock {
364 id,
365 schema_type: 200,
366 revision: 1,
367 critical: true,
368 fields,
369 })
370 }
371}
372
373#[derive(Debug, Clone, PartialEq)]
375pub struct StaggeringOffsetsPV {
376 pub component_offsets_xyz: [f64; 12],
378 pub time_offset_num: [i64; 4],
380 pub time_offset_den: [u64; 4],
382}
383
384impl Default for StaggeringOffsetsPV {
385 fn default() -> Self {
386 Self::collocated()
387 }
388}
389
390impl StaggeringOffsetsPV {
391 pub fn collocated() -> Self {
392 Self {
393 component_offsets_xyz: [0.0; 12],
394 time_offset_num: [0; 4],
395 time_offset_den: [1; 4],
396 }
397 }
398
399 pub fn yee_staggered(dx: f64, dy: f64, dz: f64) -> Self {
400 Self {
401 component_offsets_xyz: [
402 0.0, 0.0, 0.0,
403 0.5 * dx, 0.0, 0.0,
404 0.0, 0.5 * dy, 0.0,
405 0.0, 0.0, 0.5 * dz,
406 ],
407 time_offset_num: [0, 1, 1, 1],
408 time_offset_den: [1, 2, 2, 2],
409 }
410 }
411
412 pub fn is_collocated(&self) -> bool {
413 let p_xyz = &self.component_offsets_xyz[0..3];
414 let same_space = self.component_offsets_xyz.chunks_exact(3).all(|c| c == p_xyz);
415 let same_time = self
416 .time_offset_num
417 .iter()
418 .zip(self.time_offset_den)
419 .all(|(&n, d)| n * (self.time_offset_den[0] as i64) == self.time_offset_num[0] * (d as i64));
420 same_space && same_time
421 }
422}
423
424pub fn derive_collocated_intensity(
426 rec: &PressureVelocityRecord,
427 medium: &FluidMediumModel,
428 staggering: &StaggeringOffsetsPV,
429 collocated_after_interpolation: bool,
430) -> Result<[f64; 3], ProfileError> {
431 rec.validate(true)?;
432 let _ = medium.speed_of_sound_m_s()?;
433 if (rec.validity_bits & (PV_VALID_PRESSURE | PV_VALID_VELOCITY)) != (PV_VALID_PRESSURE | PV_VALID_VELOCITY) {
434 return Err(ProfileError::InvalidValidityBits);
435 }
436 if !staggering.is_collocated() && !collocated_after_interpolation {
437 return Err(ProfileError::NonCollocatedProduct(
438 "cannot form instantaneous p * v across staggered components without explicit interpolation",
439 ));
440 }
441 let p = f64::from(rec.pressure_pa);
442 Ok([
443 p * f64::from(rec.particle_velocity_m_s[0]),
444 p * f64::from(rec.particle_velocity_m_s[1]),
445 p * f64::from(rec.particle_velocity_m_s[2]),
446 ])
447}
448
449pub fn derive_collocated_energy_density(
451 rec: &PressureVelocityRecord,
452 medium: &FluidMediumModel,
453 staggering: &StaggeringOffsetsPV,
454 collocated_after_interpolation: bool,
455) -> Result<f64, ProfileError> {
456 rec.validate(true)?;
457 let (rho, bulk) = match medium {
458 FluidMediumModel::FluidLinear {
459 density_kg_m3,
460 bulk_modulus_pa,
461 ..
462 } => {
463 medium.validate()?;
464 (*density_kg_m3, *bulk_modulus_pa)
465 }
466 _ => {
467 let _ = medium.speed_of_sound_m_s()?;
468 unreachable!()
469 }
470 };
471 if (rec.validity_bits & (PV_VALID_PRESSURE | PV_VALID_VELOCITY)) != (PV_VALID_PRESSURE | PV_VALID_VELOCITY) {
472 return Err(ProfileError::InvalidValidityBits);
473 }
474 if !staggering.is_collocated() && !collocated_after_interpolation {
475 return Err(ProfileError::NonCollocatedProduct(
476 "cannot form energy density across staggered p and v without explicit interpolation",
477 ));
478 }
479 let p = f64::from(rec.pressure_pa);
480 let vx = f64::from(rec.particle_velocity_m_s[0]);
481 let vy = f64::from(rec.particle_velocity_m_s[1]);
482 let vz = f64::from(rec.particle_velocity_m_s[2]);
483 let v2 = vx * vx + vy * vy + vz * vz;
484 Ok(0.5 * rho * v2 + (p * p) / (2.0 * bulk))
485}
486
487pub fn plane_wave_record(
489 pos_m: [f32; 3],
490 t_s: f64,
491 amp_pa: f64,
492 dir: UnitDirection3,
493 freq_hz: f64,
494 rho: f64,
495 bulk_modulus_pa: f64,
496) -> PressureVelocityRecord {
497 let c = (bulk_modulus_pa / rho).sqrt();
498 let z = rho * c;
499 let omega = 2.0 * std::f64::consts::PI * freq_hz;
500 let k = omega / c;
501 let dot = f64::from(pos_m[0]) * f64::from(dir.0[0])
502 + f64::from(pos_m[1]) * f64::from(dir.0[1])
503 + f64::from(pos_m[2]) * f64::from(dir.0[2]);
504 let p = amp_pa * (k * dot - omega * t_s).cos();
505 let v_mag = p / z;
506 let vx = v_mag * f64::from(dir.0[0]);
507 let vy = v_mag * f64::from(dir.0[1]);
508 let vz = v_mag * f64::from(dir.0[2]);
509 let e = 0.5 * rho * (vx * vx + vy * vy + vz * vz) + (p * p) / (2.0 * bulk_modulus_pa);
510 PressureVelocityRecord {
511 position_m: pos_m,
512 pressure_pa: p as f32,
513 particle_velocity_m_s: [vx as f32, vy as f32, vz as f32],
514 energy_density_j_m3: e as f32,
515 intensity_w_m2: [(p * vx) as f32, (p * vy) as f32, (p * vz) as f32],
516 material_ref: 0,
517 validity_bits: PV_VALID_ALL,
518 }
519}
520
521pub fn write_pressure_velocity_qac(
523 records: &[PressureVelocityRecord],
524 medium: &FluidMediumModel,
525 staggering: &StaggeringOffsetsPV,
526 clock: &ClockSpec,
527 sample_rate: RationalRate,
528 frame: &FrameSpec<'_>,
529 provenance: &ProvenanceSpec<'_>,
530 validity_mask: Option<&[u8]>,
531 limits: ProfileLimits,
532) -> Result<Vec<u8>, ProfileError> {
533 if records.is_empty() {
534 return Err(ProfileError::InvalidPayloadLength);
535 }
536 if matches!(medium, FluidMediumModel::VacuumMask { .. }) && validity_mask.is_none() {
537 return Err(ProfileError::MediumMissingOrUnknown(
538 "VacuumMask requires an accompanying validity_mask entry",
539 ));
540 }
541 if let Some(m) = validity_mask {
542 if m.len() != records.len() || m.iter().any(|&b| b > 1) {
543 return Err(ProfileError::InvalidValidityBits);
544 }
545 }
546 let mut payload = vec![0u8; records.len() * PV_RECORD_STRIDE as usize];
547 for (idx, rec) in records.iter().enumerate() {
548 let ext_valid = validity_mask.map_or(true, |m| m[idx] != 0);
549 let off = idx * PV_RECORD_STRIDE as usize;
550 rec.encode_into(&mut payload[off..off + PV_RECORD_STRIDE as usize], ext_valid)?;
551 }
552
553 let mut meta = MetadataBuilder::new();
554 meta.push_clock(1, clock)?;
555 meta.push_frame(2, frame)?;
556 meta.push_provenance(3, provenance)?;
557 medium.push_schema_200(&mut meta, 4)?;
558 let shape = [records.len() as u64];
559 meta.push_model_grid(
560 5,
561 &ModelGridSpec {
562 model_uri: "urn:qac:model:pressure-velocity-continuum:v1",
563 model_version: "1",
564 discretization: Some("fdtd-continuum"),
565 component_offsets_xyz: &staggering.component_offsets_xyz,
566 component_time_offset_num: &staggering.time_offset_num,
567 component_time_offset_den: &staggering.time_offset_den,
568 timestep: Some(sample_rate),
569 tolerance_abs: Some(1e-6),
570 tolerance_rel: Some(1e-5),
571 tensor_shape: &shape,
572 component_names: "p,vx,vy,vz",
573 },
574 )?;
575
576 let valid_count = validity_mask.map(|m| m.iter().filter(|&&b| b == 1).count() as u64);
577 let mask_entry_idx = if validity_mask.is_some() { Some(2) } else { None };
578 let ext = [5u32];
579 meta.push_descriptor(
580 6,
581 &DescriptorSpec {
582 clock_id: Some(1),
583 frame_id: Some(2),
584 provenance_id: 3,
585 medium_id: Some(4),
586 transform_id: None,
587 calibration_id: None,
588 quantity: "acoustic-pressure-velocity",
589 units: "mixed:mode-registry",
590 channels: None,
591 layout: None,
592 scalar: None,
593 model_uri: "urn:qac:mode:0x0000:v1",
594 sample_rate: Some(sample_rate),
595 valid_record_count: valid_count,
596 validity_mask_entry: mask_entry_idx,
597 source_entries: &[],
598 extension_metadata: &ext,
599 },
600 )?;
601
602 let mut entries = vec![OwnedEntry {
603 mode: MODE_PRESSURE_VELOCITY,
604 flags: 3, stream_id: 1,
606 frame_id: 2,
607 start_tick: 0,
608 time_count: 1,
609 spatial_key: 0,
610 record_count: records.len() as u64,
611 stride: PV_RECORD_STRIDE,
612 descriptor_id: 6,
613 payload,
614 }];
615 if let Some(mask) = validity_mask {
616 let mask_entry = push_validity_mask_entry(&mut meta, 7, 3, 1, 0, 1, mask)?;
617 entries.push(mask_entry);
618 }
619 assemble_qac_v1(&meta, &entries, limits)
620}
621
622pub struct PressureVelocityView<'a> {
624 pub records: PressureVelocityChunkView<'a>,
625 pub medium: FluidMediumModel,
626 pub staggering: StaggeringOffsetsPV,
627}
628
629pub fn read_pressure_velocity_qac<'a>(
630 bytes: &'a [u8],
631 entry_index: u32,
632 limits: ProfileLimits,
633) -> Result<PressureVelocityView<'a>, ProfileError> {
634 let env = AdmittedEnvelope::open_alloc(bytes, limits)?;
635 let (_entry, desc, payload, mask) = env.check_structured_entry(
636 entry_index,
637 MODE_PRESSURE_VELOCITY,
638 PV_RECORD_STRIDE,
639 true,
640 Some(205),
641 )?;
642 let med_id = field_u32(field_req(desc, 4)?)?;
643 let med_blk = env.block(med_id)?;
644 let model = field_str(field_req(med_blk, 1)?)?;
645 let medium = match model {
646 "fluid-linear" => FluidMediumModel::FluidLinear {
647 density_kg_m3: field_f64(field_req(med_blk, 2)?)?,
648 bulk_modulus_pa: field_f64(field_req(med_blk, 3)?)?,
649 temperature_k: field_opt(med_blk, 5).map(field_f64).transpose()?,
650 ambient_pressure_pa: field_opt(med_blk, 6).map(field_f64).transpose()?,
651 flow_m_s: match field_opt(med_blk, 7) {
652 Some(f) => {
653 let v = field_f64_vec(f)?;
654 if v.len() != 3 {
655 return Err(ProfileError::InvalidMetadata("flow_m_s must have 3 components"));
656 }
657 Some([v[0], v[1], v[2]])
658 }
659 None => None,
660 },
661 matter_digest: field_opt(med_blk, 8).map(field_bytes32).transpose()?,
662 material_table_digest: field_opt(med_blk, 9).map(field_bytes32).transpose()?,
663 material_table_epoch: field_opt(med_blk, 10).map(field_u64).transpose()?,
664 material_ids: field_opt(med_blk, 11).map(field_u64_vec).transpose()?.unwrap_or_default(),
665 },
666 "vacuum-mask" => FluidMediumModel::VacuumMask {
667 mask_entry_index: field_u32(field_req(med_blk, 13)?)?,
668 },
669 "unknown-medium" => FluidMediumModel::UnknownMedium,
670 other => FluidMediumModel::ExtendedConstitutive {
671 model_uri: other.to_owned(),
672 viscosity_pa_s: None,
673 dispersion_model_uri: None,
674 anisotropy_uri: None,
675 poroelastic_uri: None,
676 material_ids: field_opt(med_blk, 11).map(field_u64_vec).transpose()?.unwrap_or_default(),
677 },
678 };
679 let grid = env
680 .extension_block(desc, 205)?
681 .ok_or(ProfileError::MissingRequiredSchema(205))?;
682 let mut staggering = StaggeringOffsetsPV::collocated();
683 if let Some(f) = field_opt(grid, 4) {
684 let vals = field_f64_vec(f)?;
685 if vals.len() == 12 {
686 staggering.component_offsets_xyz.copy_from_slice(&vals);
687 }
688 }
689 if let (Some(fn_), Some(fd)) = (field_opt(grid, 5), field_opt(grid, 16)) {
690 let nums = field_i64_vec(fn_)?;
691 let dens = field_u64_vec(fd)?;
692 if nums.len() == 4 && dens.len() == 4 {
693 staggering.time_offset_num.copy_from_slice(&nums);
694 staggering.time_offset_den.copy_from_slice(&dens);
695 }
696 }
697 let chunk = PressureVelocityChunkView {
698 bytes: payload,
699 mask,
700 };
701 for i in 0..chunk.len() {
703 let _ = chunk.get(i)?;
704 }
705 Ok(PressureVelocityView {
706 records: chunk,
707 medium,
708 staggering,
709 })
710}