1use std::collections::HashMap;
41use std::fs::File;
42use std::io::{BufReader, Read};
43use std::path::{Path, PathBuf};
44
45const MAGIC: &[u8; 4] = b"BC5D";
47
48const SUPPORTED_VERSION: u32 = 2;
50
51const HEADER_SIZE: usize = 80;
53
54#[derive(Debug)]
56pub struct Bc5dTable {
57 caliber: f32,
59 data: Vec<f32>,
61 weight_bins: Vec<f32>,
63 bc_bins: Vec<f32>,
65 muzzle_vel_bins: Vec<f32>,
67 current_vel_bins: Vec<f32>,
69 num_drag_types: usize,
71 version: u32,
73 api_version: String,
75 timestamp: u64,
77}
78
79#[derive(Debug, Default)]
81pub struct Bc5dTableManager {
82 table_dir: Option<PathBuf>,
84 tables: HashMap<i32, Bc5dTable>,
86}
87
88#[derive(Debug)]
90pub enum Bc5dError {
91 IoError(std::io::Error),
92 InvalidMagic,
93 UnsupportedVersion(u32),
94 ChecksumMismatch { expected: u32, actual: u32 },
95 InvalidDimensions,
96 TableNotFound(f64),
97 NoTableDirectory,
98}
99
100impl std::fmt::Display for Bc5dError {
101 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102 match self {
103 Bc5dError::IoError(e) => write!(f, "IO error: {}", e),
104 Bc5dError::InvalidMagic => write!(f, "Invalid file magic (expected 'BC5D')"),
105 Bc5dError::UnsupportedVersion(v) => write!(f, "Unsupported table version: {}", v),
106 Bc5dError::ChecksumMismatch { expected, actual } => {
107 write!(f, "Checksum mismatch: expected {:08x}, got {:08x}", expected, actual)
108 }
109 Bc5dError::InvalidDimensions => write!(f, "Invalid table dimensions"),
110 Bc5dError::TableNotFound(cal) => write!(f, "No BC5D table found for caliber {:.3}", cal),
111 Bc5dError::NoTableDirectory => write!(f, "No BC table directory configured"),
112 }
113 }
114}
115
116impl std::error::Error for Bc5dError {}
117
118impl From<std::io::Error> for Bc5dError {
119 fn from(e: std::io::Error) -> Self {
120 Bc5dError::IoError(e)
121 }
122}
123
124impl Bc5dTable {
125 pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, Bc5dError> {
127 let file = File::open(&path)?;
128 let mut reader = BufReader::new(file);
129
130 let mut magic = [0u8; 4];
132 reader.read_exact(&mut magic)?;
133 if &magic != MAGIC {
134 return Err(Bc5dError::InvalidMagic);
135 }
136
137 let version = read_u32(&mut reader)?;
139 if version != SUPPORTED_VERSION {
140 return Err(Bc5dError::UnsupportedVersion(version));
141 }
142
143 let caliber = read_f32(&mut reader)?;
144 let _flags = read_u32(&mut reader)?;
145 let _padding = read_u32(&mut reader)?;
146
147 let dim_weight = read_u32(&mut reader)? as usize;
148 let dim_bc = read_u32(&mut reader)? as usize;
149 let dim_muzzle_vel = read_u32(&mut reader)? as usize;
150 let dim_current_vel = read_u32(&mut reader)? as usize;
151 let dim_drag_types = read_u32(&mut reader)? as usize;
152
153 let timestamp = read_u64(&mut reader)?;
154 let stored_checksum = read_u32(&mut reader)?;
155
156 let mut api_version_bytes = [0u8; 16];
158 reader.read_exact(&mut api_version_bytes)?;
159 let api_version = String::from_utf8_lossy(&api_version_bytes)
160 .trim_end_matches('\0')
161 .to_string();
162
163 let mut reserved = [0u8; 12];
165 reader.read_exact(&mut reserved)?;
166
167 if dim_weight == 0 || dim_bc == 0 || dim_muzzle_vel == 0 || dim_current_vel == 0 || dim_drag_types == 0 {
169 return Err(Bc5dError::InvalidDimensions);
170 }
171
172 let weight_bins = read_f32_array(&mut reader, dim_weight)?;
174 let bc_bins = read_f32_array(&mut reader, dim_bc)?;
175 let muzzle_vel_bins = read_f32_array(&mut reader, dim_muzzle_vel)?;
176 let current_vel_bins = read_f32_array(&mut reader, dim_current_vel)?;
177
178 let total_cells = dim_drag_types * dim_weight * dim_bc * dim_muzzle_vel * dim_current_vel;
180 let data = read_f32_array(&mut reader, total_cells)?;
181
182 let mut checksum_data = Vec::new();
184 for &v in &weight_bins {
185 checksum_data.extend_from_slice(&v.to_le_bytes());
186 }
187 for &v in &bc_bins {
188 checksum_data.extend_from_slice(&v.to_le_bytes());
189 }
190 for &v in &muzzle_vel_bins {
191 checksum_data.extend_from_slice(&v.to_le_bytes());
192 }
193 for &v in ¤t_vel_bins {
194 checksum_data.extend_from_slice(&v.to_le_bytes());
195 }
196 for &v in &data {
197 checksum_data.extend_from_slice(&v.to_le_bytes());
198 }
199
200 let calculated_checksum = crc32_ieee(&checksum_data);
201 if calculated_checksum != stored_checksum {
202 return Err(Bc5dError::ChecksumMismatch {
203 expected: stored_checksum,
204 actual: calculated_checksum,
205 });
206 }
207
208 Ok(Bc5dTable {
209 caliber,
210 data,
211 weight_bins,
212 bc_bins,
213 muzzle_vel_bins,
214 current_vel_bins,
215 num_drag_types: dim_drag_types,
216 version,
217 api_version,
218 timestamp,
219 })
220 }
221
222 pub fn lookup(
235 &self,
236 weight_grains: f64,
237 base_bc: f64,
238 muzzle_velocity: f64,
239 current_velocity: f64,
240 drag_type: &str,
241 ) -> f64 {
242 let drag_idx = if drag_type.eq_ignore_ascii_case("G7") { 1 } else { 0 };
244
245 let drag_idx = drag_idx.min(self.num_drag_types - 1);
247
248 let (weight_idx, weight_w) = self.interp_idx(weight_grains as f32, &self.weight_bins);
250 let (bc_idx, bc_w) = self.interp_idx(base_bc as f32, &self.bc_bins);
251 let (muzzle_idx, muzzle_w) = self.interp_idx(muzzle_velocity as f32, &self.muzzle_vel_bins);
252 let (current_idx, current_w) = self.interp_idx(current_velocity as f32, &self.current_vel_bins);
253
254 let mut result = 0.0f64;
256
257 for dw in 0..2 {
258 for db in 0..2 {
259 for dm in 0..2 {
260 for dc in 0..2 {
261 let weight = (if dw == 0 { 1.0 - weight_w } else { weight_w })
263 * (if db == 0 { 1.0 - bc_w } else { bc_w })
264 * (if dm == 0 { 1.0 - muzzle_w } else { muzzle_w })
265 * (if dc == 0 { 1.0 - current_w } else { current_w });
266
267 let wi = (weight_idx + dw).min(self.weight_bins.len() - 1);
269 let bi = (bc_idx + db).min(self.bc_bins.len() - 1);
270 let mi = (muzzle_idx + dm).min(self.muzzle_vel_bins.len() - 1);
271 let ci = (current_idx + dc).min(self.current_vel_bins.len() - 1);
272
273 let idx = self.flat_index(drag_idx, wi, bi, mi, ci);
275 result += weight * self.data[idx] as f64;
276 }
277 }
278 }
279 }
280
281 result.max(0.5).min(1.5)
283 }
284
285 pub fn get_effective_bc(
289 &self,
290 weight_grains: f64,
291 base_bc: f64,
292 muzzle_velocity: f64,
293 current_velocity: f64,
294 drag_type: &str,
295 ) -> f64 {
296 let correction = self.lookup(weight_grains, base_bc, muzzle_velocity, current_velocity, drag_type);
297 base_bc * correction
298 }
299
300 fn interp_idx(&self, value: f32, bins: &[f32]) -> (usize, f64) {
302 if bins.is_empty() {
303 return (0, 0.0);
304 }
305
306 if value <= bins[0] {
308 return (0, 0.0);
309 }
310 if value >= bins[bins.len() - 1] {
311 return (bins.len().saturating_sub(2), 1.0);
312 }
313
314 let idx = match bins.binary_search_by(|probe| {
316 probe.partial_cmp(&value).unwrap_or(std::cmp::Ordering::Equal)
317 }) {
318 Ok(i) => i.saturating_sub(1).min(bins.len() - 2),
319 Err(i) => i.saturating_sub(1).min(bins.len() - 2),
320 };
321
322 let low = bins[idx];
324 let high = bins[idx + 1];
325 let weight = if high > low {
326 ((value - low) / (high - low)) as f64
327 } else {
328 0.0
329 };
330
331 (idx, weight)
332 }
333
334 fn flat_index(&self, drag_idx: usize, weight_idx: usize, bc_idx: usize, muzzle_idx: usize, current_idx: usize) -> usize {
336 let n_weight = self.weight_bins.len();
337 let n_bc = self.bc_bins.len();
338 let n_muzzle = self.muzzle_vel_bins.len();
339 let n_current = self.current_vel_bins.len();
340
341 drag_idx * (n_weight * n_bc * n_muzzle * n_current)
342 + weight_idx * (n_bc * n_muzzle * n_current)
343 + bc_idx * (n_muzzle * n_current)
344 + muzzle_idx * n_current
345 + current_idx
346 }
347
348 pub fn caliber(&self) -> f32 {
350 self.caliber
351 }
352
353 pub fn version(&self) -> u32 {
355 self.version
356 }
357
358 pub fn api_version(&self) -> &str {
360 &self.api_version
361 }
362
363 pub fn timestamp(&self) -> u64 {
365 self.timestamp
366 }
367
368 pub fn total_cells(&self) -> usize {
370 self.data.len()
371 }
372
373 pub fn dimensions_str(&self) -> String {
375 format!(
376 "{}x{}x{}x{}x{} (weight x bc x muzzle_vel x current_vel x drag_types)",
377 self.weight_bins.len(),
378 self.bc_bins.len(),
379 self.muzzle_vel_bins.len(),
380 self.current_vel_bins.len(),
381 self.num_drag_types
382 )
383 }
384
385 pub fn weight_range(&self) -> (f32, f32) {
387 (*self.weight_bins.first().unwrap_or(&0.0), *self.weight_bins.last().unwrap_or(&0.0))
388 }
389
390 pub fn velocity_range(&self) -> (f32, f32) {
392 (*self.current_vel_bins.first().unwrap_or(&0.0), *self.current_vel_bins.last().unwrap_or(&0.0))
393 }
394}
395
396impl Bc5dTableManager {
397 pub fn new<P: AsRef<Path>>(table_dir: P) -> Self {
399 Bc5dTableManager {
400 table_dir: Some(table_dir.as_ref().to_path_buf()),
401 tables: HashMap::new(),
402 }
403 }
404
405 pub fn empty() -> Self {
407 Bc5dTableManager {
408 table_dir: None,
409 tables: HashMap::new(),
410 }
411 }
412
413 pub fn get_table(&mut self, caliber: f64) -> Result<&Bc5dTable, Bc5dError> {
417 let caliber_key = caliber_to_key(caliber);
418
419 if self.tables.contains_key(&caliber_key) {
421 return Ok(self.tables.get(&caliber_key).unwrap());
422 }
423
424 let table_dir = self.table_dir.as_ref().ok_or(Bc5dError::NoTableDirectory)?;
426 let table_path = find_table_file(table_dir, caliber)?;
427 let table = Bc5dTable::load(&table_path)?;
428 self.tables.insert(caliber_key, table);
429 Ok(self.tables.get(&caliber_key).unwrap())
430 }
431
432 pub fn lookup(
434 &mut self,
435 caliber: f64,
436 weight_grains: f64,
437 base_bc: f64,
438 muzzle_velocity: f64,
439 current_velocity: f64,
440 drag_type: &str,
441 ) -> Result<f64, Bc5dError> {
442 let table = self.get_table(caliber)?;
443 Ok(table.lookup(weight_grains, base_bc, muzzle_velocity, current_velocity, drag_type))
444 }
445
446 pub fn get_effective_bc(
448 &mut self,
449 caliber: f64,
450 weight_grains: f64,
451 base_bc: f64,
452 muzzle_velocity: f64,
453 current_velocity: f64,
454 drag_type: &str,
455 ) -> Result<f64, Bc5dError> {
456 let table = self.get_table(caliber)?;
457 Ok(table.get_effective_bc(weight_grains, base_bc, muzzle_velocity, current_velocity, drag_type))
458 }
459
460 pub fn has_table(&self, caliber: f64) -> bool {
462 if let Some(ref table_dir) = self.table_dir {
463 find_table_file(table_dir, caliber).is_ok()
464 } else {
465 false
466 }
467 }
468
469 pub fn available_calibers(&self) -> Vec<f64> {
471 let mut calibers = Vec::new();
472 if let Some(ref table_dir) = self.table_dir {
473 if let Ok(entries) = std::fs::read_dir(table_dir) {
474 for entry in entries.flatten() {
475 let path = entry.path();
476 if let Some(ext) = path.extension() {
477 if ext == "bin" {
478 if let Some(stem) = path.file_stem() {
479 let name = stem.to_string_lossy();
480 if name.starts_with("bc5d_") {
481 if let Ok(cal_int) = name[5..].parse::<i32>() {
483 calibers.push(cal_int as f64 / 1000.0);
484 }
485 }
486 }
487 }
488 }
489 }
490 }
491 }
492 calibers.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
493 calibers
494 }
495}
496
497fn caliber_to_key(caliber: f64) -> i32 {
499 (caliber * 1000.0).round() as i32
500}
501
502fn find_table_file(table_dir: &Path, caliber: f64) -> Result<PathBuf, Bc5dError> {
504 let caliber_int = (caliber * 1000.0).round() as i32;
505 let filename = format!("bc5d_{}.bin", caliber_int);
506 let path = table_dir.join(&filename);
507
508 if path.exists() {
509 return Ok(path);
510 }
511
512 let variations = [
514 format!("bc5d_{:03}.bin", caliber_int),
515 format!("bc5d_0{}.bin", caliber_int),
516 ];
517
518 for var in &variations {
519 let var_path = table_dir.join(var);
520 if var_path.exists() {
521 return Ok(var_path);
522 }
523 }
524
525 Err(Bc5dError::TableNotFound(caliber))
526}
527
528fn read_u32<R: Read>(reader: &mut R) -> Result<u32, std::io::Error> {
531 let mut buf = [0u8; 4];
532 reader.read_exact(&mut buf)?;
533 Ok(u32::from_le_bytes(buf))
534}
535
536fn read_u64<R: Read>(reader: &mut R) -> Result<u64, std::io::Error> {
537 let mut buf = [0u8; 8];
538 reader.read_exact(&mut buf)?;
539 Ok(u64::from_le_bytes(buf))
540}
541
542fn read_f32<R: Read>(reader: &mut R) -> Result<f32, std::io::Error> {
543 let mut buf = [0u8; 4];
544 reader.read_exact(&mut buf)?;
545 Ok(f32::from_le_bytes(buf))
546}
547
548fn read_f32_array<R: Read>(reader: &mut R, count: usize) -> Result<Vec<f32>, std::io::Error> {
549 let mut data = vec![0f32; count];
550 let mut buf = vec![0u8; count * 4];
551 reader.read_exact(&mut buf)?;
552
553 for (i, chunk) in buf.chunks_exact(4).enumerate() {
554 data[i] = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
555 }
556
557 Ok(data)
558}
559
560fn crc32_ieee(data: &[u8]) -> u32 {
562 const TABLE: [u32; 256] = make_crc32_table();
563 let mut crc = 0xFFFFFFFFu32;
564 for &byte in data {
565 let idx = ((crc ^ byte as u32) & 0xFF) as usize;
566 crc = (crc >> 8) ^ TABLE[idx];
567 }
568 !crc
569}
570
571const fn make_crc32_table() -> [u32; 256] {
572 const POLY: u32 = 0xEDB88320;
573 let mut table = [0u32; 256];
574 let mut i = 0;
575 while i < 256 {
576 let mut crc = i as u32;
577 let mut j = 0;
578 while j < 8 {
579 if crc & 1 != 0 {
580 crc = (crc >> 1) ^ POLY;
581 } else {
582 crc >>= 1;
583 }
584 j += 1;
585 }
586 table[i] = crc;
587 i += 1;
588 }
589 table
590}
591
592#[cfg(test)]
593mod tests {
594 use super::*;
595
596 fn create_test_table() -> Bc5dTable {
597 let weight_bins = vec![100.0, 150.0, 200.0];
599 let bc_bins = vec![0.3, 0.4, 0.5];
600 let muzzle_vel_bins = vec![2500.0, 3000.0];
601 let current_vel_bins = vec![1000.0, 2000.0, 3000.0];
602 let num_drag_types = 2;
603
604 let total = num_drag_types * weight_bins.len() * bc_bins.len() * muzzle_vel_bins.len() * current_vel_bins.len();
606 let mut data = vec![1.0f32; total];
607
608 data[0] = 0.95; data[total - 1] = 1.05; Bc5dTable {
615 caliber: 0.308,
616 data,
617 weight_bins,
618 bc_bins,
619 muzzle_vel_bins,
620 current_vel_bins,
621 num_drag_types,
622 version: 2,
623 api_version: "test".to_string(),
624 timestamp: 0,
625 }
626 }
627
628 #[test]
629 fn test_interp_idx_in_range() {
630 let table = create_test_table();
631
632 let (idx, weight) = table.interp_idx(125.0, &table.weight_bins);
634 assert_eq!(idx, 0);
635 assert!((weight - 0.5).abs() < 0.01);
636
637 let (idx, weight) = table.interp_idx(150.0, &table.weight_bins);
639 assert_eq!(idx, 0);
640 assert!((weight - 1.0).abs() < 0.01);
641 }
642
643 #[test]
644 fn test_interp_idx_out_of_range() {
645 let table = create_test_table();
646
647 let (idx, weight) = table.interp_idx(50.0, &table.weight_bins);
649 assert_eq!(idx, 0);
650 assert_eq!(weight, 0.0);
651
652 let (idx, weight) = table.interp_idx(250.0, &table.weight_bins);
654 assert_eq!(idx, 1); assert_eq!(weight, 1.0);
656 }
657
658 #[test]
659 fn test_lookup_returns_valid_range() {
660 let table = create_test_table();
661
662 let correction = table.lookup(150.0, 0.4, 2750.0, 2000.0, "G1");
663 assert!(correction >= 0.5 && correction <= 1.5);
664
665 let correction = table.lookup(150.0, 0.4, 2750.0, 2000.0, "G7");
666 assert!(correction >= 0.5 && correction <= 1.5);
667 }
668
669 #[test]
670 fn test_effective_bc() {
671 let table = create_test_table();
672
673 let base_bc = 0.4;
674 let effective = table.get_effective_bc(150.0, base_bc, 2750.0, 2000.0, "G1");
675
676 assert!(effective >= base_bc * 0.5 && effective <= base_bc * 1.5);
678 }
679
680 #[test]
681 fn test_caliber_to_key() {
682 assert_eq!(caliber_to_key(0.308), 308);
683 assert_eq!(caliber_to_key(0.224), 224);
684 assert_eq!(caliber_to_key(0.338), 338);
685 }
686
687 #[test]
688 fn test_table_metadata() {
689 let table = create_test_table();
690 assert!((table.caliber() - 0.308).abs() < 0.001);
691 assert_eq!(table.version(), 2);
692 assert_eq!(table.api_version(), "test");
693 }
694
695 #[test]
696 fn test_crc32() {
697 let data = b"123456789";
699 let crc = crc32_ieee(data);
700 assert_eq!(crc, 0xCBF43926);
701 }
702}