diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f04ff02..2a54453 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,7 +6,7 @@ on: paths-ignore: - "**.md" - "assets/**" - - "c_ref/**" + - "legacy/**" - "tools/**" - "benchmarks/**" - "LICENSE*" @@ -15,7 +15,7 @@ on: paths-ignore: - "**.md" - "assets/**" - - "c_ref/**" + - "legacy/**" - "tools/**" - "benchmarks/**" - "LICENSE*" diff --git a/c_ref/README.md b/legacy/README.md similarity index 77% rename from c_ref/README.md rename to legacy/README.md index 255234e..71c52f7 100644 --- a/c_ref/README.md +++ b/legacy/README.md @@ -1,4 +1,4 @@ -# Legacy C99 / Meson Reference Archive (`c_ref/`) +# Legacy C99 / Meson Reference Archive (`legacy/`) This directory preserves a read-only archival copy of the original `skyborn-plot` `0.1.0` C99 extension modules, Meson build definitions, and `setup.py` build script (with full git history preserved at tag `v0.1.0`). @@ -6,9 +6,9 @@ It is excluded from Pure-Rust binary wheels and source distributions via `[tool. ## Archived Modules to Pure-Rust Crate Mapping -| Legacy Archive Path (`c_ref/`) | Pure-Rust Module (`rust/skybornplot-core/src/`) | Python Shim (`src/skybornplot/`) | +| Legacy Archive Path (`legacy/`) | Pure-Rust Module (`rust/skybornplot-core/src/`) | Python Shim (`src/skybornplot/`) | | :--- | :--- | :--- | | `_core/contour_arrows_core.c`, `_core/meson.build` | `contour_arrows.rs` | `_core/contour_arrows_core.py` | | `contour_core/_contour_core.c`, `contour_core/meson.build` | `contour.rs` | `contour_core/_contour_core.py` | -| `nclcurly_core/_ncl_curly_core.c`, `nclcurly_core/meson.build` | `ncl_curly.rs` | `nclcurly_core/_ncl_curly_core.py` | +| `nclcurly_core/_ncl_curly_core.c`, `nclcurly_core/meson.build` | `ncl_curly/` | `nclcurly_core/_ncl_curly_core.py` | | `setup.py` | Workspace `Cargo.toml` + `rust/skybornplot-py` | `pyproject.toml` (`maturin`) | diff --git a/c_ref/_core/contour_arrows_core.c b/legacy/_core/contour_arrows_core.c similarity index 100% rename from c_ref/_core/contour_arrows_core.c rename to legacy/_core/contour_arrows_core.c diff --git a/c_ref/_core/meson.build b/legacy/_core/meson.build similarity index 100% rename from c_ref/_core/meson.build rename to legacy/_core/meson.build diff --git a/c_ref/contour_core/_contour_core.c b/legacy/contour_core/_contour_core.c similarity index 100% rename from c_ref/contour_core/_contour_core.c rename to legacy/contour_core/_contour_core.c diff --git a/c_ref/contour_core/meson.build b/legacy/contour_core/meson.build similarity index 100% rename from c_ref/contour_core/meson.build rename to legacy/contour_core/meson.build diff --git a/c_ref/nclcurly_core/_ncl_curly_core.c b/legacy/nclcurly_core/_ncl_curly_core.c similarity index 100% rename from c_ref/nclcurly_core/_ncl_curly_core.c rename to legacy/nclcurly_core/_ncl_curly_core.c diff --git a/c_ref/nclcurly_core/meson.build b/legacy/nclcurly_core/meson.build similarity index 100% rename from c_ref/nclcurly_core/meson.build rename to legacy/nclcurly_core/meson.build diff --git a/c_ref/setup.py b/legacy/setup.py similarity index 100% rename from c_ref/setup.py rename to legacy/setup.py diff --git a/pyproject.toml b/pyproject.toml index 70fbc47..911558f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -63,7 +63,7 @@ dev = [ module-name = "skybornplot._plot_rs" manifest-path = "rust/skybornplot-py/Cargo.toml" python-source = "src" -exclude = ["c_ref/**", "tools/**", "rust/target/**", "target/**"] +exclude = ["legacy/**", "tools/**", "benchmarks/**", "rust/target/**", "target/**", "assets/**"] [tool.black] line-length = 88 diff --git a/rust/skybornplot-core/src/ncl_curly.rs b/rust/skybornplot-core/src/ncl_curly.rs deleted file mode 100644 index 26afd04..0000000 --- a/rust/skybornplot-core/src/ncl_curly.rs +++ /dev/null @@ -1,2984 +0,0 @@ -//! Pure-Rust NCL-like curly-vector tracing, grid sampling, thinning, and arrow geometry kernels. - -use std::fmt; - -use rayon::prelude::*; - -const PARALLEL_SAMPLE_THRESHOLD: usize = 2048; -const PARALLEL_CELL_VALID_THRESHOLD: usize = 4096; -const PARALLEL_THIN_THRESHOLD: usize = 16384; -const PARALLEL_CELL_CANDIDATE_THRESHOLD: usize = 4096; -const PARALLEL_ARROW_THRESHOLD: usize = 512; -const PARALLEL_BATCH_TRACE_THRESHOLD: usize = 8; - -const MIN_ACCEPTED_TRACE_STEP_PX: f64 = 0.2; -const MAX_NATIVE_TRACE_STEPS: usize = 4096; - -/// Error returned when an `ncl_curly` kernel receives invalid array dimensions or parameters. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct NclCurlyError { - /// Human-readable description of the validation error. - pub message: String, -} - -impl NclCurlyError { - fn new(message: impl Into) -> Self { - Self { - message: message.into(), - } - } -} - -impl fmt::Display for NclCurlyError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.message) - } -} - -impl std::error::Error for NclCurlyError {} - -impl From<&str> for NclCurlyError { - fn from(message: &str) -> Self { - Self::new(message) - } -} - -impl From for NclCurlyError { - fn from(message: String) -> Self { - Self::new(message) - } -} - -/// Anchor mode controlling how each glyph is integrated from its seed point. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum TraceAnchor { - /// Integrate both backward and forward by half the target length and stitch around the center. - Center, - /// Integrate forward only from the seed point. - Tail, - /// Integrate backward only from the seed point and reverse into flow direction. - Head, -} - -impl TraceAnchor { - /// Parse an anchor string (`"center"`, `"tail"`, or `"head"`). - pub fn parse(value: &str) -> Result { - match value { - "center" => Ok(Self::Center), - "tail" => Ok(Self::Tail), - "head" => Ok(Self::Head), - _ => Err(NclCurlyError::new(format!( - "{value:?} is not a valid value for anchor; supported values are center, tail, head" - ))), - } - } -} - -/// Result of tracing a single forward or backward curly-vector branch. -#[derive(Debug, Clone, PartialEq)] -pub struct TraceDirectionResult { - /// Flat `(N, 2)` data-space polyline coordinates `[x0, y0, x1, y1, ...]`. - pub curve: Vec, - /// Optional flat `(N, 2)` display-space polyline coordinates when `return_display` is true. - pub display_curve: Option>, -} - -/// Result of sampling mapped display positions and optional local Jacobians on a display grid. -#[derive(Debug, Clone, PartialEq)] -pub struct SampleDisplayGridResult { - /// Flat `(N, 2)` mapped display coordinates (`NaN` for invalid rows). - pub display_points: Vec, - /// Optional flat `(N, 2, 2)` local Jacobians `[j00, j01, j10, j11]` when requested. - pub jacobians: Option>, - /// Per-point validity mask of length `N`. - pub valid: Vec, -} - -/// Result of expanding selected cells into interior candidate coordinates. -#[derive(Debug, Clone, PartialEq)] -pub struct CellCandidatesResult { - /// Flat `(K, 2)` data-space candidate coordinates. - pub candidate_points: Vec, - /// Source cell index in `0..N` for each generated candidate. - pub source_positions: Vec, -} - -/// Result of building open-arrow polylines or filled-arrow triangles in display space. -#[derive(Debug, Clone, PartialEq)] -pub struct ArrowGeometryResult { - /// Flat `(K, 3, 2)` vertex coordinates `[x0, y0, x1, y1, x2, y2, ...]`. - pub vertices: Vec, - /// Source curve index in `0..n_curves` for each valid arrow. - pub source_positions: Vec, -} - -/// Result of tracing a batch of curly-vector glyphs in parallel. -#[derive(Debug, Clone, PartialEq)] -pub struct BatchTraceResult { - /// Flat packed `(total_points, 2)` data-space curve vertices across all valid glyphs. - pub data_points: Vec, - /// Flat packed `(total_points, 2)` display-space curve vertices across all valid glyphs. - pub display_points: Vec, - /// Monotonic vertex offsets of length `valid_indices.len() + 1` (starts at `0`). - pub curve_offsets: Vec, - /// Original center indices in deterministic ascending order for each valid glyph. - pub valid_indices: Vec, - /// Number of direction-tracing branch calls truncated at `max_steps` before reaching target length. - pub truncated_count: usize, -} - -#[derive(Clone, Copy)] -struct GridInfo { - nx: usize, - ny: usize, - x_origin: f64, - y_origin: f64, - dx_safe: f64, - dy_safe: f64, - inv_dx: f64, - inv_dy: f64, - max_x_index: f64, - max_y_index: f64, - max_cell_x: f64, - max_cell_y: f64, -} - -impl GridInfo { - #[inline] - fn new(ny: usize, nx: usize, x_origin: f64, y_origin: f64, dx: f64, dy: f64) -> Self { - let dx_abs = dx.abs(); - let dy_abs = dy.abs(); - let dx_safe = if dx_abs > 1e-12 { dx_abs } else { 1e-12 }; - let dy_safe = if dy_abs > 1e-12 { dy_abs } else { 1e-12 }; - Self { - nx, - ny, - x_origin, - y_origin, - dx_safe, - dy_safe, - inv_dx: 1.0 / dx_safe, - inv_dy: 1.0 / dy_safe, - max_x_index: nx.saturating_sub(1) as f64, - max_y_index: ny.saturating_sub(1) as f64, - max_cell_x: nx.saturating_sub(2) as f64, - max_cell_y: ny.saturating_sub(2) as f64, - } - } - - #[inline] - fn contains_data(&self, x: f64, y: f64) -> bool { - let xi = (x - self.x_origin) * self.inv_dx; - let yi = (y - self.y_origin) * self.inv_dy; - 0.0 <= xi && xi <= self.max_x_index && 0.0 <= yi && yi <= self.max_y_index - } -} - -#[derive(Clone, Copy)] -struct SampleState { - display_x: f64, - display_y: f64, - j00: f64, - j01: f64, - j10: f64, - j11: f64, - dir_x: f64, - dir_y: f64, - speed: f64, -} - -#[inline] -fn sample_state( - grid: &GridInfo, - u_data: &[f64], - v_data: &[f64], - display_data: &[f64], - cell_valid: &[bool], - x: f64, - y: f64, -) -> Option { - if grid.nx < 2 || grid.ny < 2 { - return None; - } - - let xi = (x - grid.x_origin) * grid.inv_dx; - let yi = (y - grid.y_origin) * grid.inv_dy; - if !(0.0 <= xi && xi <= grid.max_x_index && 0.0 <= yi && yi <= grid.max_y_index) { - return None; - } - - let ix = xi.max(0.0).min(grid.max_cell_x).floor() as usize; - let iy = yi.max(0.0).min(grid.max_cell_y).floor() as usize; - if !cell_valid[iy * (grid.nx - 1) + ix] { - return None; - } - - let sx = xi - ix as f64; - let sy = yi - iy as f64; - let one_minus_sx = 1.0 - sx; - let one_minus_sy = 1.0 - sy; - let nx = grid.nx; - - let idx00 = iy * nx + ix; - let idx01 = iy * nx + (ix + 1); - let idx10 = (iy + 1) * nx + ix; - let idx11 = (iy + 1) * nx + (ix + 1); - - let u00 = u_data[idx00]; - let u01 = u_data[idx01]; - let u10 = u_data[idx10]; - let u11 = u_data[idx11]; - let v00 = v_data[idx00]; - let v01 = v_data[idx01]; - let v10 = v_data[idx10]; - let v11 = v_data[idx11]; - - let u_value = - (u00 * one_minus_sx + u01 * sx) * one_minus_sy + (u10 * one_minus_sx + u11 * sx) * sy; - let v_value = - (v00 * one_minus_sx + v01 * sx) * one_minus_sy + (v10 * one_minus_sx + v11 * sx) * sy; - if !u_value.is_finite() || !v_value.is_finite() { - return None; - } - - let d00 = idx00 * 2; - let d01 = idx01 * 2; - let d10 = idx10 * 2; - let d11 = idx11 * 2; - - let p00x = display_data[d00]; - let p00y = display_data[d00 + 1]; - let p01x = display_data[d01]; - let p01y = display_data[d01 + 1]; - let p10x = display_data[d10]; - let p10y = display_data[d10 + 1]; - let p11x = display_data[d11]; - let p11y = display_data[d11 + 1]; - - let display_x = p00x * one_minus_sx * one_minus_sy - + p01x * sx * one_minus_sy - + p10x * one_minus_sx * sy - + p11x * sx * sy; - let display_y = p00y * one_minus_sx * one_minus_sy - + p01y * sx * one_minus_sy - + p10y * one_minus_sx * sy - + p11y * sx * sy; - let j00 = ((p01x - p00x) * one_minus_sy + (p11x - p10x) * sy) / grid.dx_safe; - let j10 = ((p01y - p00y) * one_minus_sy + (p11y - p10y) * sy) / grid.dx_safe; - let j01 = ((p10x - p00x) * one_minus_sx + (p11x - p01x) * sx) / grid.dy_safe; - let j11 = ((p10y - p00y) * one_minus_sx + (p11y - p01y) * sx) / grid.dy_safe; - - let det = j00 * j11 - j01 * j10; - if !display_x.is_finite() || !display_y.is_finite() || !det.is_finite() || det.abs() <= 1e-12 - { - return None; - } - - let vec_x = j00 * u_value + j01 * v_value; - let vec_y = j10 * u_value + j11 * v_value; - let vec_norm = vec_x.hypot(vec_y); - if !vec_norm.is_finite() || vec_norm <= 1e-12 { - return None; - } - - let speed = u_value.hypot(v_value); - if !speed.is_finite() { - return None; - } - - Some(SampleState { - display_x, - display_y, - j00, - j01, - j10, - j11, - dir_x: vec_x / vec_norm, - dir_y: vec_y / vec_norm, - speed, - }) -} - -#[inline] -fn display_step_to_data( - j00: f64, - j01: f64, - j10: f64, - j11: f64, - step_x: f64, - step_y: f64, -) -> Option<(f64, f64)> { - let det = j00 * j11 - j01 * j10; - if !det.is_finite() || det.abs() <= 1e-12 { - return None; - } - let data_x = (j11 * step_x - j01 * step_y) / det; - let data_y = (-j10 * step_x + j00 * step_y) / det; - if data_x.is_finite() && data_y.is_finite() { - Some((data_x, data_y)) - } else { - None - } -} - -#[inline] -fn ncl_step_length_px(base_step_px: f64, _local_speed: f64, _speed_scale: f64) -> f64 { - base_step_px -} - -#[inline] -fn viewport_contains(x0: f64, y0: f64, x1: f64, y1: f64, x: f64, y: f64) -> bool { - x.is_finite() && y.is_finite() && x0 <= x && x <= x1 && y0 <= y && y <= y1 -} - -#[inline] -fn clip_display_step_to_viewport( - start_x: f64, - start_y: f64, - end_x: &mut f64, - end_y: &mut f64, - viewport_x0: f64, - viewport_y0: f64, - viewport_x1: f64, - viewport_y1: f64, -) -> bool { - if viewport_contains( - viewport_x0, - viewport_y0, - viewport_x1, - viewport_y1, - *end_x, - *end_y, - ) { - return false; - } - - let delta_x = *end_x - start_x; - let delta_y = *end_y - start_y; - if !delta_x.is_finite() || !delta_y.is_finite() { - *end_x = start_x; - *end_y = start_y; - return true; - } - - let mut factor = 1.0; - if delta_x < -1e-12 { - let candidate = (viewport_x0 - start_x) / delta_x; - if candidate < factor { - factor = candidate; - } - } else if delta_x > 1e-12 { - let candidate = (viewport_x1 - start_x) / delta_x; - if candidate < factor { - factor = candidate; - } - } - - if delta_y < -1e-12 { - let candidate = (viewport_y0 - start_y) / delta_y; - if candidate < factor { - factor = candidate; - } - } else if delta_y > 1e-12 { - let candidate = (viewport_y1 - start_y) / delta_y; - if candidate < factor { - factor = candidate; - } - } - - factor = factor.clamp(0.0, 1.0); - *end_x = start_x + delta_x * factor; - *end_y = start_y + delta_y * factor; - true -} - -struct ProposedStep { - candidate_x: f64, - candidate_y: f64, - candidate_display_x: f64, - candidate_display_y: f64, - clipped: bool, -} - -#[inline] -#[allow(clippy::too_many_arguments)] -fn propose_trace_step( - grid: &GridInfo, - current_data_x: f64, - current_data_y: f64, - current_display_x: f64, - current_display_y: f64, - corrected_display_x: f64, - corrected_display_y: f64, - step_dir_x: f64, - step_dir_y: f64, - step_length: f64, - remaining: f64, - j00: f64, - j01: f64, - j10: f64, - j11: f64, - viewport_x0: f64, - viewport_y0: f64, - viewport_x1: f64, - viewport_y1: f64, -) -> Option { - let mut candidate_display_x = corrected_display_x + step_dir_x * step_length; - let mut candidate_display_y = corrected_display_y + step_dir_y * step_length; - let clipped = clip_display_step_to_viewport( - corrected_display_x, - corrected_display_y, - &mut candidate_display_x, - &mut candidate_display_y, - viewport_x0, - viewport_y0, - viewport_x1, - viewport_y1, - ); - - let mut display_step_x = candidate_display_x - current_display_x; - let mut display_step_y = candidate_display_y - current_display_y; - if display_step_x * step_dir_x + display_step_y * step_dir_y <= 0.0 { - return None; - } - - let net_step = display_step_x.hypot(display_step_y); - if !net_step.is_finite() { - return None; - } - if net_step > remaining && net_step > 1e-12 { - let scale = remaining / net_step; - display_step_x *= scale; - display_step_y *= scale; - candidate_display_x = current_display_x + display_step_x; - candidate_display_y = current_display_y + display_step_y; - } - - let (data_step_x, data_step_y) = - display_step_to_data(j00, j01, j10, j11, display_step_x, display_step_y)?; - let candidate_x = current_data_x + data_step_x; - let candidate_y = current_data_y + data_step_y; - if !candidate_x.is_finite() - || !candidate_y.is_finite() - || !grid.contains_data(candidate_x, candidate_y) - { - return None; - } - - Some(ProposedStep { - candidate_x, - candidate_y, - candidate_display_x, - candidate_display_y, - clipped, - }) -} - -struct TraceBranchOutput { - curve: Vec, - display_curve: Option>, - truncated: bool, -} - -#[allow(clippy::too_many_arguments)] -fn trace_ncl_direction_core( - grid: &GridInfo, - u_data: &[f64], - v_data: &[f64], - display_data: &[f64], - cell_valid_data: &[bool], - start_x: f64, - start_y: f64, - max_length_px: f64, - direction_sign: f64, - step_px: f64, - speed_scale: f64, - viewport_x0: f64, - viewport_y0: f64, - viewport_x1: f64, - viewport_y1: f64, - max_steps: usize, - return_display: bool, -) -> Option { - if grid.ny < 2 || grid.nx < 2 { - return None; - } - - let max_steps = max_steps.clamp(1, MAX_NATIVE_TRACE_STEPS); - let initial_state = sample_state( - grid, - u_data, - v_data, - display_data, - cell_valid_data, - start_x, - start_y, - )?; - - if !max_length_px.is_finite() || max_length_px <= 1e-6 { - return None; - } - - let initial_cap = (max_steps + 1).min(64) * 2; - let mut curve = Vec::with_capacity(initial_cap); - curve.push(start_x); - curve.push(start_y); - - let mut display_curve = if return_display { - let mut buf = Vec::with_capacity(initial_cap); - buf.push(initial_state.display_x); - buf.push(initial_state.display_y); - Some(buf) - } else { - None - }; - - let mut current_data_x = start_x; - let mut current_data_y = start_y; - let mut previous_display_x = 0.0; - let mut previous_display_y = 0.0; - let mut has_previous_display = false; - let mut travelled = 0.0; - - for step_index in 0..max_steps { - let remaining = max_length_px - travelled; - if !remaining.is_finite() || remaining <= 1e-6 { - break; - } - - let state = if step_index == 0 { - initial_state - } else { - match sample_state( - grid, - u_data, - v_data, - display_data, - cell_valid_data, - current_data_x, - current_data_y, - ) { - Some(s) => s, - None => break, - } - }; - - let current_display_x = state.display_x; - let current_display_y = state.display_y; - let (corrected_display_x, corrected_display_y, back_len) = if has_previous_display { - let cx = current_display_x - (current_display_x - previous_display_x) / 3.0; - let cy = current_display_y - (current_display_y - previous_display_y) / 3.0; - let bl = (current_display_x - cx).hypot(current_display_y - cy); - (cx, cy, bl) - } else { - (current_display_x, current_display_y, 0.0) - }; - - let mut step_length = ncl_step_length_px(step_px, state.speed, speed_scale); - if step_length > remaining + back_len { - step_length = remaining + back_len; - } - if step_length <= 1e-6 { - break; - } - - let mut chosen = match propose_trace_step( - grid, - current_data_x, - current_data_y, - current_display_x, - current_display_y, - corrected_display_x, - corrected_display_y, - direction_sign * state.dir_x, - direction_sign * state.dir_y, - step_length, - remaining, - state.j00, - state.j01, - state.j10, - state.j11, - viewport_x0, - viewport_y0, - viewport_x1, - viewport_y1, - ) { - Some(step) => step, - None => break, - }; - - if let Some(next_state) = sample_state( - grid, - u_data, - v_data, - display_data, - cell_valid_data, - chosen.candidate_x, - chosen.candidate_y, - ) { - let average_direction_x = direction_sign * (state.dir_x + next_state.dir_x); - let average_direction_y = direction_sign * (state.dir_y + next_state.dir_y); - let average_norm = average_direction_x.hypot(average_direction_y); - if average_norm > 1e-12 { - let avg_dir_x = average_direction_x / average_norm; - let avg_dir_y = average_direction_y / average_norm; - let average_speed = 0.5 * (state.speed + next_state.speed); - let mut average_step = ncl_step_length_px(step_px, average_speed, speed_scale); - if average_step > remaining + back_len { - average_step = remaining + back_len; - } - let avg_j00 = 0.5 * (state.j00 + next_state.j00); - let avg_j01 = 0.5 * (state.j01 + next_state.j01); - let avg_j10 = 0.5 * (state.j10 + next_state.j10); - let avg_j11 = 0.5 * (state.j11 + next_state.j11); - - chosen = match propose_trace_step( - grid, - current_data_x, - current_data_y, - current_display_x, - current_display_y, - corrected_display_x, - corrected_display_y, - avg_dir_x, - avg_dir_y, - average_step, - remaining, - avg_j00, - avg_j01, - avg_j10, - avg_j11, - viewport_x0, - viewport_y0, - viewport_x1, - viewport_y1, - ) { - Some(step) => step, - None => break, - }; - } - } - - let actual_step = (chosen.candidate_display_x - current_display_x) - .hypot(chosen.candidate_display_y - current_display_y); - if actual_step <= MIN_ACCEPTED_TRACE_STEP_PX { - break; - } - - curve.push(chosen.candidate_x); - curve.push(chosen.candidate_y); - if let Some(ref mut disp_buf) = display_curve { - disp_buf.push(chosen.candidate_display_x); - disp_buf.push(chosen.candidate_display_y); - } - - previous_display_x = current_display_x; - previous_display_y = current_display_y; - has_previous_display = true; - current_data_x = chosen.candidate_x; - current_data_y = chosen.candidate_y; - travelled += actual_step; - - if chosen.clipped { - break; - } - } - - let point_count = curve.len() / 2; - if point_count < 2 { - return None; - } - - let truncated = point_count == max_steps + 1 && travelled + 1e-6 < max_length_px; - Some(TraceBranchOutput { - curve, - display_curve, - truncated, - }) -} - -fn validate_trace_grid_inputs( - u: &[f64], - v: &[f64], - display_grid: &[f64], - cell_valid: &[bool], - ny: usize, - nx: usize, -) -> Result { - let expected_nodes = ny - .checked_mul(nx) - .ok_or_else(|| NclCurlyError::new("grid dimensions overflow"))?; - if u.len() != expected_nodes || v.len() != expected_nodes { - return Err(NclCurlyError::new("u and v must share the same shape")); - } - let expected_display = expected_nodes - .checked_mul(2) - .ok_or_else(|| NclCurlyError::new("display_grid dimensions overflow"))?; - if display_grid.len() != expected_display { - return Err(NclCurlyError::new( - "display_grid must match the u/v grid shape", - )); - } - if ny < 2 || nx < 2 { - return Ok(false); - } - let expected_cells = (ny - 1) - .checked_mul(nx - 1) - .ok_or_else(|| NclCurlyError::new("cell_valid dimensions overflow"))?; - if cell_valid.len() != expected_cells { - return Err(NclCurlyError::new( - "cell_valid must have shape (ny-1, nx-1)", - )); - } - Ok(true) -} - -/// Trace a single forward or backward curly-vector branch on regular gridded fields. -#[allow(clippy::too_many_arguments)] -pub fn trace_ncl_direction( - u: &[f64], - v: &[f64], - display_grid: &[f64], - cell_valid: &[bool], - ny: usize, - nx: usize, - x_origin: f64, - y_origin: f64, - dx: f64, - dy: f64, - start_x: f64, - start_y: f64, - max_length_px: f64, - direction_sign: f64, - step_px: f64, - speed_scale: f64, - viewport_x0: f64, - viewport_y0: f64, - viewport_x1: f64, - viewport_y1: f64, - max_steps: usize, - return_display: bool, -) -> Result, NclCurlyError> { - if !validate_trace_grid_inputs(u, v, display_grid, cell_valid, ny, nx)? { - return Ok(None); - } - - let grid = GridInfo::new(ny, nx, x_origin, y_origin, dx, dy); - Ok(trace_ncl_direction_core( - &grid, - u, - v, - display_grid, - cell_valid, - start_x, - start_y, - max_length_px, - direction_sign, - step_px, - speed_scale, - viewport_x0, - viewport_y0, - viewport_x1, - viewport_y1, - max_steps, - return_display, - ) - .map(|branch| TraceDirectionResult { - curve: branch.curve, - display_curve: branch.display_curve, - })) -} - -#[inline] -fn sample_scalar_field(grid: &GridInfo, field_data: &[f64], x: f64, y: f64) -> Option { - if grid.nx < 1 || grid.ny < 1 { - return None; - } - - let xi = (x - grid.x_origin) * grid.inv_dx; - let yi = (y - grid.y_origin) * grid.inv_dy; - if !(0.0 <= xi && xi <= grid.max_x_index && 0.0 <= yi && yi <= grid.max_y_index) { - return None; - } - - let ix = xi as usize; - let iy = yi as usize; - let ix_next = if ix == grid.nx - 1 { ix } else { ix + 1 }; - let iy_next = if iy == grid.ny - 1 { iy } else { iy + 1 }; - - let sx = xi - ix as f64; - let sy = yi - iy as f64; - - let a00 = field_data[iy * grid.nx + ix]; - let a01 = field_data[iy * grid.nx + ix_next]; - let a10 = field_data[iy_next * grid.nx + ix]; - let a11 = field_data[iy_next * grid.nx + ix_next]; - - let value = (a00 * (1.0 - sx) + a01 * sx) * (1.0 - sy) + (a10 * (1.0 - sx) + a11 * sx) * sy; - if value.is_finite() { - Some(value) - } else { - None - } -} - -/// Bilinearly sample one scalar value from a 2D regular grid `(ny, nx)`. -#[allow(clippy::too_many_arguments)] -pub fn sample_grid_field( - field: &[f64], - ny: usize, - nx: usize, - x_origin: f64, - y_origin: f64, - dx: f64, - dy: f64, - x: f64, - y: f64, -) -> Result, NclCurlyError> { - let expected = ny - .checked_mul(nx) - .ok_or_else(|| NclCurlyError::new("field dimensions overflow"))?; - if field.len() != expected { - return Err(NclCurlyError::new("field shape does not match (ny, nx)")); - } - let grid = GridInfo::new(ny, nx, x_origin, y_origin, dx, dy); - Ok(sample_scalar_field(&grid, field, x, y)) -} - -/// Bilinearly sample a 2D scalar field `(ny, nx)` at a flat `(N, 2)` array of coordinates. -/// -/// Out-of-bounds or non-finite samples yield `f64::NAN`. -#[allow(clippy::too_many_arguments)] -pub fn sample_grid_field_array( - field: &[f64], - ny: usize, - nx: usize, - x_origin: f64, - y_origin: f64, - dx: f64, - dy: f64, - points: &[f64], -) -> Result, NclCurlyError> { - let expected = ny - .checked_mul(nx) - .ok_or_else(|| NclCurlyError::new("field dimensions overflow"))?; - if field.len() != expected { - return Err(NclCurlyError::new("field shape does not match (ny, nx)")); - } - if points.len() % 2 != 0 { - return Err(NclCurlyError::new("points must have shape (N, 2) or (2,)")); - } - - let point_count = points.len() / 2; - let mut output = vec![f64::NAN; point_count]; - if point_count == 0 { - return Ok(output); - } - - let grid = GridInfo::new(ny, nx, x_origin, y_origin, dx, dy); - if point_count >= PARALLEL_SAMPLE_THRESHOLD { - output - .par_chunks_mut(512) - .enumerate() - .for_each(|(chunk_idx, out_chunk)| { - let start = chunk_idx * 512; - for (offset, out_val) in out_chunk.iter_mut().enumerate() { - let idx = start + offset; - if let Some(value) = - sample_scalar_field(&grid, field, points[idx * 2], points[idx * 2 + 1]) - { - *out_val = value; - } - } - }); - } else { - for (idx, out_val) in output.iter_mut().enumerate() { - if let Some(value) = - sample_scalar_field(&grid, field, points[idx * 2], points[idx * 2 + 1]) - { - *out_val = value; - } - } - } - - Ok(output) -} - -/// Compute per-cell validity mask `(ny - 1, nx - 1)` for a mapped display grid `(ny, nx, 2)`. -/// -/// A cell is valid when all four corner coordinates are finite and none of its four -/// edge lengths exceeds the projection seam jump threshold (`12 * median(lower half)`). -pub fn compute_display_cell_valid( - display_grid: &[f64], - ny: usize, - nx: usize, -) -> Result, NclCurlyError> { - if ny < 2 || nx < 2 { - return Err(NclCurlyError::new( - "display_grid must contain at least one cell", - )); - } - let expected = ny - .checked_mul(nx) - .and_then(|n| n.checked_mul(2)) - .ok_or_else(|| NclCurlyError::new("display_grid dimensions overflow"))?; - if display_grid.len() != expected { - return Err(NclCurlyError::new("display_grid must have shape (ny, nx, 2)")); - } - - let n_edges = ny * (nx - 1) + (ny - 1) * nx; - let mut edges = Vec::with_capacity(n_edges); - - for iy in 0..ny { - for ix in 0..(nx - 1) { - let left_idx = (iy * nx + ix) * 2; - let right_idx = (iy * nx + ix + 1) * 2; - let length = (display_grid[right_idx] - display_grid[left_idx]) - .hypot(display_grid[right_idx + 1] - display_grid[left_idx + 1]); - if length.is_finite() && length > 1e-9 { - edges.push(length); - } - } - } - for iy in 0..(ny - 1) { - for ix in 0..nx { - let top_idx = (iy * nx + ix) * 2; - let bottom_idx = ((iy + 1) * nx + ix) * 2; - let length = (display_grid[bottom_idx] - display_grid[top_idx]) - .hypot(display_grid[bottom_idx + 1] - display_grid[top_idx + 1]); - if length.is_finite() && length > 1e-9 { - edges.push(length); - } - } - } - - let jump_limit = if !edges.is_empty() { - let lower_count = (edges.len() / 2).max(1); - let mid = lower_count / 2; - edges.select_nth_unstable_by(mid, f64::total_cmp); - let median = if lower_count % 2 == 1 { - edges[mid] - } else { - let left_max = edges[..mid] - .iter() - .copied() - .fold(f64::NEG_INFINITY, f64::max); - 0.5 * (left_max + edges[mid]) - }; - Some((median * 12.0).max(1e-6)) - } else { - None - }; - - let cell_nx = nx - 1; - let cell_ny = ny - 1; - let total_cells = cell_ny * cell_nx; - let mut cell_valid = vec![false; total_cells]; - - let eval_row = |iy: usize, row_out: &mut [bool]| { - for (ix, out_flag) in row_out.iter_mut().enumerate() { - let idx00 = (iy * nx + ix) * 2; - let idx01 = (iy * nx + ix + 1) * 2; - let idx10 = ((iy + 1) * nx + ix) * 2; - let idx11 = ((iy + 1) * nx + ix + 1) * 2; - - let finite_cell = display_grid[idx00].is_finite() - && display_grid[idx00 + 1].is_finite() - && display_grid[idx01].is_finite() - && display_grid[idx01 + 1].is_finite() - && display_grid[idx10].is_finite() - && display_grid[idx10 + 1].is_finite() - && display_grid[idx11].is_finite() - && display_grid[idx11 + 1].is_finite(); - - if !finite_cell { - *out_flag = false; - continue; - } - let Some(limit) = jump_limit else { - *out_flag = true; - continue; - }; - - let top_edge = (display_grid[idx01] - display_grid[idx00]) - .hypot(display_grid[idx01 + 1] - display_grid[idx00 + 1]); - let bottom_edge = (display_grid[idx11] - display_grid[idx10]) - .hypot(display_grid[idx11 + 1] - display_grid[idx10 + 1]); - let left_edge = (display_grid[idx10] - display_grid[idx00]) - .hypot(display_grid[idx10 + 1] - display_grid[idx00 + 1]); - let right_edge = (display_grid[idx11] - display_grid[idx01]) - .hypot(display_grid[idx11 + 1] - display_grid[idx01 + 1]); - let max_edge = top_edge.max(bottom_edge).max(left_edge.max(right_edge)); - *out_flag = max_edge.is_finite() && max_edge <= limit; - } - }; - - if total_cells >= PARALLEL_CELL_VALID_THRESHOLD { - cell_valid - .par_chunks_mut(cell_nx) - .enumerate() - .for_each(|(iy, row_out)| eval_row(iy, row_out)); - } else { - for (iy, row_out) in cell_valid.chunks_mut(cell_nx).enumerate() { - eval_row(iy, row_out); - } - } - - Ok(cell_valid) -} - -#[inline] -fn sample_display_point( - grid: &GridInfo, - display: &[f64], - cell_valid: &[bool], - point_x: f64, - point_y: f64, - include_jacobian: bool, -) -> Option<(f64, f64, [f64; 4])> { - let xi = (point_x - grid.x_origin) * grid.inv_dx; - let yi = (point_y - grid.y_origin) * grid.inv_dy; - if !(0.0 <= xi && xi <= grid.max_x_index && 0.0 <= yi && yi <= grid.max_y_index) { - return None; - } - - let ix = xi.max(0.0).min(grid.max_cell_x).floor() as usize; - let iy = yi.max(0.0).min(grid.max_cell_y).floor() as usize; - if !cell_valid[iy * (grid.nx - 1) + ix] { - return None; - } - - let sx = xi - ix as f64; - let sy = yi - iy as f64; - let one_minus_sx = 1.0 - sx; - let one_minus_sy = 1.0 - sy; - let idx00 = (iy * grid.nx + ix) * 2; - let idx01 = (iy * grid.nx + ix + 1) * 2; - let idx10 = ((iy + 1) * grid.nx + ix) * 2; - let idx11 = ((iy + 1) * grid.nx + ix + 1) * 2; - - let p00x = display[idx00]; - let p00y = display[idx00 + 1]; - let p01x = display[idx01]; - let p01y = display[idx01 + 1]; - let p10x = display[idx10]; - let p10y = display[idx10 + 1]; - let p11x = display[idx11]; - let p11y = display[idx11 + 1]; - - let display_x = p00x * one_minus_sx * one_minus_sy - + p01x * sx * one_minus_sy - + p10x * one_minus_sx * sy - + p11x * sx * sy; - let display_y = p00y * one_minus_sx * one_minus_sy - + p01y * sx * one_minus_sy - + p10y * one_minus_sx * sy - + p11y * sx * sy; - if !display_x.is_finite() || !display_y.is_finite() { - return None; - } - - if !include_jacobian { - return Some((display_x, display_y, [0.0; 4])); - } - - let dfdx_x = ((p01x - p00x) * one_minus_sy + (p11x - p10x) * sy) / grid.dx_safe; - let dfdx_y = ((p01y - p00y) * one_minus_sy + (p11y - p10y) * sy) / grid.dx_safe; - let dfdy_x = ((p10x - p00x) * one_minus_sx + (p11x - p01x) * sx) / grid.dy_safe; - let dfdy_y = ((p10y - p00y) * one_minus_sx + (p11y - p01y) * sx) / grid.dy_safe; - let det = dfdx_x * dfdy_y - dfdy_x * dfdx_y; - - if !dfdx_x.is_finite() - || !dfdx_y.is_finite() - || !dfdy_x.is_finite() - || !dfdy_y.is_finite() - || !det.is_finite() - || det.abs() <= 1e-12 - { - return None; - } - - Some((display_x, display_y, [dfdx_x, dfdy_x, dfdx_y, dfdy_y])) -} - -/// Bilinearly sample display-grid positions and optional local Jacobians for a batch of data-space points. -#[allow(clippy::too_many_arguments)] -pub fn sample_display_grid( - display_grid: &[f64], - ny: usize, - nx: usize, - cell_valid: &[bool], - x_origin: f64, - y_origin: f64, - dx: f64, - dy: f64, - points: &[f64], - include_jacobian: bool, -) -> Result { - if ny == 0 || nx == 0 { - return Err(NclCurlyError::new("display_grid must have non-zero shape")); - } - let expected_display = ny - .checked_mul(nx) - .and_then(|n| n.checked_mul(2)) - .ok_or_else(|| NclCurlyError::new("display_grid dimensions overflow"))?; - if display_grid.len() != expected_display { - return Err(NclCurlyError::new("display_grid must have shape (ny, nx, 2)")); - } - let expected_cells = (ny - 1) - .checked_mul(nx - 1) - .ok_or_else(|| NclCurlyError::new("cell_valid dimensions overflow"))?; - if cell_valid.len() != expected_cells { - return Err(NclCurlyError::new( - "cell_valid must have shape (ny-1, nx-1)", - )); - } - if points.len() % 2 != 0 { - return Err(NclCurlyError::new("points must have shape (N, 2) or (2,)")); - } - - let point_count = points.len() / 2; - let mut display_points = vec![f64::NAN; point_count * 2]; - let mut valid = vec![false; point_count]; - let mut jacobians = if include_jacobian { - Some(vec![f64::NAN; point_count * 4]) - } else { - None - }; - - if point_count == 0 || ny < 2 || nx < 2 { - return Ok(SampleDisplayGridResult { - display_points, - jacobians, - valid, - }); - } - - let grid = GridInfo::new(ny, nx, x_origin, y_origin, dx, dy); - - if point_count >= PARALLEL_SAMPLE_THRESHOLD { - if let Some(ref mut jacs) = jacobians { - display_points - .par_chunks_mut(1024) - .zip(valid.par_chunks_mut(512)) - .zip(jacs.par_chunks_mut(2048)) - .enumerate() - .for_each(|(chunk_idx, ((dp_chunk, v_chunk), j_chunk))| { - let start = chunk_idx * 512; - for i in 0..v_chunk.len() { - let idx = start + i; - if let Some((dx_val, dy_val, jac)) = sample_display_point( - &grid, - display_grid, - cell_valid, - points[idx * 2], - points[idx * 2 + 1], - true, - ) { - dp_chunk[i * 2] = dx_val; - dp_chunk[i * 2 + 1] = dy_val; - j_chunk[i * 4..i * 4 + 4].copy_from_slice(&jac); - v_chunk[i] = true; - } - } - }); - } else { - display_points - .par_chunks_mut(1024) - .zip(valid.par_chunks_mut(512)) - .enumerate() - .for_each(|(chunk_idx, (dp_chunk, v_chunk))| { - let start = chunk_idx * 512; - for i in 0..v_chunk.len() { - let idx = start + i; - if let Some((dx_val, dy_val, _)) = sample_display_point( - &grid, - display_grid, - cell_valid, - points[idx * 2], - points[idx * 2 + 1], - false, - ) { - dp_chunk[i * 2] = dx_val; - dp_chunk[i * 2 + 1] = dy_val; - v_chunk[i] = true; - } - } - }); - } - } else { - for idx in 0..point_count { - if let Some((dx_val, dy_val, jac)) = sample_display_point( - &grid, - display_grid, - cell_valid, - points[idx * 2], - points[idx * 2 + 1], - include_jacobian, - ) { - display_points[idx * 2] = dx_val; - display_points[idx * 2 + 1] = dy_val; - if let Some(ref mut jacs) = jacobians { - jacs[idx * 4..idx * 4 + 4].copy_from_slice(&jac); - } - valid[idx] = true; - } - } - } - - Ok(SampleDisplayGridResult { - display_points, - jacobians, - valid, - }) -} - -#[derive(Clone, Copy)] -struct BucketEntry { - bx: i64, - by: i64, - idx: usize, -} - -#[derive(Clone, Copy)] -struct BucketSpan { - bx: i64, - by: i64, - start: usize, - end: usize, -} - -#[inline] -fn clamp_f64_to_i64(value: f64) -> i64 { - const MIN_VAL: f64 = -9223372036854774784.0; - const MAX_VAL: f64 = 9223372036854774784.0; - if !value.is_finite() { - 0 - } else if value < MIN_VAL { - i64::MIN + 2 - } else if value > MAX_VAL { - i64::MAX - 2 - } else { - value as i64 - } -} - -#[inline] -fn hash_bucket_coords(bx: i64, by: i64) -> usize { - let mut h = (bx as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) - ^ (by as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9); - h ^= h >> 30; - h = h.wrapping_mul(0xBF58_476D_1CE4_E5B9); - h ^= h >> 27; - h as usize -} - -fn thin_scaled_points( - points: &[f64], - origin_x: f64, - origin_y: f64, - inv_width: f64, - inv_height: f64, - spacing_frac: f64, -) -> Vec { - let point_count = points.len() / 2; - if point_count == 0 { - return Vec::new(); - } - - let spacing_frac = spacing_frac.max(1e-6); - let spacing_sq = spacing_frac * spacing_frac; - let bucket_scale = 1.0 / spacing_frac; - let bucket_scale_x = inv_width * bucket_scale; - let bucket_scale_y = inv_height * bucket_scale; - - let origin_scales_finite = origin_x.is_finite() - && origin_y.is_finite() - && bucket_scale_x.is_finite() - && bucket_scale_y.is_finite(); - if !origin_scales_finite { - return Vec::new(); - } - - let mut culled = vec![false; point_count]; - let mut entries = vec![ - BucketEntry { - bx: 0, - by: 0, - idx: 0, - }; - point_count - ]; - - const CHUNK_PTS: usize = 2048; - if point_count >= PARALLEL_THIN_THRESHOLD { - entries - .par_chunks_mut(CHUNK_PTS) - .zip(culled.par_chunks_mut(CHUNK_PTS)) - .zip(points.par_chunks(CHUNK_PTS * 2)) - .enumerate() - .for_each(|(chunk_idx, ((e_chunk, c_chunk), p_chunk))| { - let base_idx = chunk_idx * CHUNK_PTS; - for i in 0..e_chunk.len() { - let px = p_chunk[i * 2]; - let py = p_chunk[i * 2 + 1]; - let idx = base_idx + i; - if !px.is_finite() || !py.is_finite() { - c_chunk[i] = true; - e_chunk[i] = BucketEntry { - bx: 0, - by: 0, - idx, - }; - } else { - e_chunk[i] = BucketEntry { - bx: clamp_f64_to_i64(((px - origin_x) * bucket_scale_x).floor()), - by: clamp_f64_to_i64(((py - origin_y) * bucket_scale_y).floor()), - idx, - }; - } - } - }); - } else { - for idx in 0..point_count { - let px = points[idx * 2]; - let py = points[idx * 2 + 1]; - if !px.is_finite() || !py.is_finite() { - culled[idx] = true; - entries[idx] = BucketEntry { - bx: 0, - by: 0, - idx, - }; - } else { - entries[idx] = BucketEntry { - bx: clamp_f64_to_i64(((px - origin_x) * bucket_scale_x).floor()), - by: clamp_f64_to_i64(((py - origin_y) * bucket_scale_y).floor()), - idx, - }; - } - } - } - - let cmp_entry = |a: &BucketEntry, b: &BucketEntry| { - a.bx.cmp(&b.bx) - .then_with(|| a.by.cmp(&b.by)) - .then_with(|| a.idx.cmp(&b.idx)) - }; - if entries.len() >= PARALLEL_THIN_THRESHOLD { - entries.par_sort_unstable_by(cmp_entry); - } else { - entries.sort_unstable_by(cmp_entry); - } - - let mut buckets: Vec = Vec::new(); - let mut run_start = 0; - while run_start < entries.len() { - let bx = entries[run_start].bx; - let by = entries[run_start].by; - let mut run_end = run_start + 1; - while run_end < entries.len() && entries[run_end].bx == bx && entries[run_end].by == by { - run_end += 1; - } - buckets.push(BucketSpan { - bx, - by, - start: run_start, - end: run_end, - }); - run_start = run_end; - } - - let table_cap = (buckets.len() * 2).max(16).next_power_of_two(); - let table_mask = table_cap - 1; - let mut table = vec![usize::MAX; table_cap]; - for (b_idx, span) in buckets.iter().enumerate() { - let mut slot = hash_bucket_coords(span.bx, span.by) & table_mask; - while table[slot] != usize::MAX { - slot = (slot + 1) & table_mask; - } - table[slot] = b_idx; - } - - let mut selected_indices = Vec::new(); - for idx in 0..point_count { - if culled[idx] { - continue; - } - - let base_x = points[idx * 2]; - let base_y = points[idx * 2 + 1]; - let bx = clamp_f64_to_i64(((base_x - origin_x) * bucket_scale_x).floor()); - let by = clamp_f64_to_i64(((base_y - origin_y) * bucket_scale_y).floor()); - - selected_indices.push(idx); - - for search_x in (bx - 1)..=(bx + 1) { - for search_y in (by - 1)..=(by + 1) { - let mut slot = hash_bucket_coords(search_x, search_y) & table_mask; - let mut found_bucket = usize::MAX; - loop { - let b_idx = table[slot]; - if b_idx == usize::MAX { - break; - } - let span = &buckets[b_idx]; - if span.bx == search_x && span.by == search_y { - found_bucket = b_idx; - break; - } - slot = (slot + 1) & table_mask; - } - if found_bucket == usize::MAX { - continue; - } - - let span = &mut buckets[found_bucket]; - while span.start < span.end - && (entries[span.start].idx <= idx || culled[entries[span.start].idx]) - { - span.start += 1; - } - - for entry in &entries[span.start..span.end] { - let other_idx = entry.idx; - if other_idx <= idx || culled[other_idx] { - continue; - } - let dx_value = (base_x - points[other_idx * 2]) * inv_width; - let dy_value = (base_y - points[other_idx * 2 + 1]) * inv_height; - if dx_value * dx_value + dy_value * dy_value < spacing_sq { - culled[other_idx] = true; - } - } - } - } - } - - selected_indices -} - -/// Thin already-normalized `(N, 2)` viewport candidates in scan order using a spacing lattice. -pub fn thin_mapped_candidates( - mapped_points: &[f64], - spacing_frac: f64, -) -> Result, NclCurlyError> { - if mapped_points.len() % 2 != 0 { - return Err(NclCurlyError::new("mapped_points must have shape (N, 2)")); - } - Ok(thin_scaled_points( - mapped_points, - 0.0, - 0.0, - 1.0, - 1.0, - spacing_frac, - )) -} - -/// Thin display/pixel `(N, 2)` candidates in scan order after normalizing by the active viewport. -pub fn thin_display_candidates( - display_points: &[f64], - viewport_x0: f64, - viewport_y0: f64, - viewport_width: f64, - viewport_height: f64, - spacing_frac: f64, -) -> Result, NclCurlyError> { - if display_points.len() % 2 != 0 { - return Err(NclCurlyError::new("display_points must have shape (N, 2)")); - } - let width = if viewport_width > 1.0 { - viewport_width - } else { - 1.0 - }; - let height = if viewport_height > 1.0 { - viewport_height - } else { - 1.0 - }; - Ok(thin_scaled_points( - display_points, - viewport_x0, - viewport_y0, - 1.0 / width, - 1.0 / height, - spacing_frac, - )) -} - -#[inline] -fn cell_subdivision_counts(mapped: &[f64], spacing: f64) -> Option<(usize, usize)> { - let mut min_x = mapped[0]; - let mut max_x = mapped[0]; - let mut min_y = mapped[1]; - let mut max_y = mapped[1]; - - for corner in 0..4 { - let x = mapped[corner * 2]; - let y = mapped[corner * 2 + 1]; - if !x.is_finite() || !y.is_finite() { - return None; - } - if x < min_x { - min_x = x; - } - if x > max_x { - max_x = x; - } - if y < min_y { - min_y = y; - } - if y > max_y { - max_y = y; - } - } - - let raw_sub_x = ((max_x - min_x) / spacing).ceil(); - let raw_sub_y = ((max_y - min_y) / spacing).ceil(); - let sub_x = if !raw_sub_x.is_finite() || raw_sub_x < 1.0 { - 1 - } else if raw_sub_x > 12.0 { - 12 - } else { - raw_sub_x as usize - }; - let sub_y = if !raw_sub_y.is_finite() || raw_sub_y < 1.0 { - 1 - } else if raw_sub_y > 12.0 { - 12 - } else { - raw_sub_y as usize - }; - Some((sub_x, sub_y)) -} - -/// Expand selected scatter cells into interior stipple candidate lattices. -/// -/// `corners` and `mapped_corners` have flat shape `(N, 4, 2)` and `source_points` has shape `(N, 2)`. -pub fn generate_cell_candidates( - corners: &[f64], - mapped_corners: &[f64], - source_points: &[f64], - spacing_frac: f64, -) -> Result { - if source_points.len() % 2 != 0 { - return Err(NclCurlyError::new("source_points must have shape (N, 2)")); - } - let n_cells = source_points.len() / 2; - let expected_corners = n_cells - .checked_mul(8) - .ok_or_else(|| NclCurlyError::new("corners dimensions overflow"))?; - if corners.len() != expected_corners { - return Err(NclCurlyError::new( - "corners must have shape (N, 4, 2) matching source_points", - )); - } - if mapped_corners.len() != expected_corners { - return Err(NclCurlyError::new( - "mapped_corners must have shape (N, 4, 2) matching source_points", - )); - } - - let mut spacing = if spacing_frac.is_finite() { - spacing_frac - } else { - 0.03 - }; - if spacing < 1e-6 { - spacing = 1e-6; - } - - let mut cell_plans: Vec> = Vec::with_capacity(n_cells); - let mut total_count = 0usize; - for cell in 0..n_cells { - let mapped = &mapped_corners[cell * 8..cell * 8 + 8]; - let plan = cell_subdivision_counts(mapped, spacing); - total_count += match plan { - Some((sx, sy)) => sx * sy, - None => 1, - }; - cell_plans.push(plan); - } - - let mut candidate_points = vec![0.0; total_count * 2]; - let mut source_positions = vec![0usize; total_count]; - - let fill_cell = |cell: usize, - plan: Option<(usize, usize)>, - pts_out: &mut [f64], - pos_out: &mut [usize]| { - match plan { - None => { - pts_out[0] = source_points[cell * 2]; - pts_out[1] = source_points[cell * 2 + 1]; - pos_out[0] = cell; - } - Some((sub_x, sub_y)) => { - let corner_data = &corners[cell * 8..cell * 8 + 8]; - let mut k = 0; - for row in 0..sub_y { - let vv = (row as f64 + 0.5) / sub_y as f64; - let one_minus_v = 1.0 - vv; - for col in 0..sub_x { - let uu = (col as f64 + 0.5) / sub_x as f64; - let one_minus_u = 1.0 - uu; - let w00 = one_minus_u * one_minus_v; - let w10 = uu * one_minus_v; - let w11 = uu * vv; - let w01 = one_minus_u * vv; - pts_out[k * 2] = w00 * corner_data[0] - + w10 * corner_data[2] - + w11 * corner_data[4] - + w01 * corner_data[6]; - pts_out[k * 2 + 1] = w00 * corner_data[1] - + w10 * corner_data[3] - + w11 * corner_data[5] - + w01 * corner_data[7]; - pos_out[k] = cell; - k += 1; - } - } - } - } - }; - - if n_cells >= PARALLEL_CELL_CANDIDATE_THRESHOLD { - let mut offsets = Vec::with_capacity(n_cells + 1); - let mut acc = 0usize; - offsets.push(0); - for &plan in &cell_plans { - acc += match plan { - Some((sx, sy)) => sx * sy, - None => 1, - }; - offsets.push(acc); - } - let pts_ptr = candidate_points.as_mut_ptr() as usize; - let pos_ptr = source_positions.as_mut_ptr() as usize; - cell_plans.par_iter().enumerate().for_each(|(cell, &plan)| { - let start = offsets[cell]; - let end = offsets[cell + 1]; - let count = end - start; - // Safety: disjoint [start, end) slices per cell. - let pts_slice = unsafe { - std::slice::from_raw_parts_mut((pts_ptr as *mut f64).add(start * 2), count * 2) - }; - let pos_slice = unsafe { - std::slice::from_raw_parts_mut((pos_ptr as *mut usize).add(start), count) - }; - fill_cell(cell, plan, pts_slice, pos_slice); - }); - } else { - let mut out_pos = 0usize; - for (cell, &plan) in cell_plans.iter().enumerate() { - let count = match plan { - Some((sx, sy)) => sx * sy, - None => 1, - }; - fill_cell( - cell, - plan, - &mut candidate_points[out_pos * 2..(out_pos + count) * 2], - &mut source_positions[out_pos..out_pos + count], - ); - out_pos += count; - } - } - - Ok(CellCandidatesResult { - candidate_points, - source_positions, - }) -} - -#[inline] -fn validate_display_curve_slice( - curve: &[f64], - viewport_width: f64, - viewport_height: f64, -) -> bool { - let n_points = curve.len() / 2; - if n_points < 2 { - return false; - } - if curve.iter().any(|v| !v.is_finite()) { - return false; - } - - let viewport_diag = viewport_width.hypot(viewport_height); - let use_jump_limit = viewport_diag.is_finite() && viewport_diag > 0.0; - let jump_limit = if use_jump_limit { - (viewport_diag * 0.35).max(1e-6) - } else { - 0.0 - }; - - let mut valid_count = 0usize; - let mut arc_length = 0.0; - let mut max_turn = 0.0; - let mut total_turn = 0.0; - let mut previous_turn_sign = 0i32; - let mut sign_changes = 0usize; - let mut prev_dir: Option<(f64, f64)> = None; - - for idx in 0..(n_points - 1) { - let dx = curve[(idx + 1) * 2] - curve[idx * 2]; - let dy = curve[(idx + 1) * 2 + 1] - curve[idx * 2 + 1]; - let length = dx.hypot(dy); - if use_jump_limit && length > jump_limit { - return false; - } - if length > 1e-6 { - let cur_x = dx / length; - let cur_y = dy / length; - if let Some((px, py)) = prev_dir { - let dot = (px * cur_x + py * cur_y).clamp(-1.0, 1.0); - let angle = dot.acos() * 180.0 / std::f64::consts::PI; - if angle > max_turn { - max_turn = angle; - } - total_turn += angle; - - let cross = px * cur_y - py * cur_x; - if cross.abs() > 1e-6 { - let current_turn_sign = if cross > 0.0 { 1 } else { -1 }; - if previous_turn_sign != 0 && current_turn_sign * previous_turn_sign < 0 { - sign_changes += 1; - } - previous_turn_sign = current_turn_sign; - } - } - prev_dir = Some((cur_x, cur_y)); - arc_length += length; - valid_count += 1; - } - } - - if valid_count < 1 { - return false; - } - - let chord_length = (curve[(n_points - 1) * 2] - curve[0]) - .hypot(curve[(n_points - 1) * 2 + 1] - curve[1]); - if arc_length <= 1e-6 || chord_length <= 1e-6 { - return false; - } - - let tortuosity = arc_length / chord_length; - if tortuosity > 1.28 { - return false; - } - if max_turn > 52.0 { - return false; - } - if total_turn > 120.0 { - return false; - } - if sign_changes > 0 && total_turn > 70.0 { - return false; - } - true -} - -/// Validate display-space curly-vector geometry against jump, tortuosity, and turn-angle limits. -pub fn validate_display_curve( - display_curve: &[f64], - viewport_width: f64, - viewport_height: f64, -) -> Result { - if display_curve.len() % 2 != 0 { - return Err(NclCurlyError::new("display_curve must have shape (N, 2)")); - } - Ok(validate_display_curve_slice( - display_curve, - viewport_width, - viewport_height, - )) -} - -#[derive(Clone, Copy)] -enum ArrowStyle { - Open, - Filled, -} - -#[inline] -fn resolve_curve_tip_direction(curve: &[f64], backoff_px: f64) -> Option<(f64, f64, f64, f64)> { - let n_points = curve.len() / 2; - if n_points < 2 || !backoff_px.is_finite() { - return None; - } - if curve.iter().any(|v| !v.is_finite()) { - return None; - } - - let tip_x = curve[(n_points - 1) * 2]; - let tip_y = curve[(n_points - 1) * 2 + 1]; - let mut tail_x = curve[0]; - let mut tail_y = curve[1]; - let mut remaining = backoff_px.max(0.0); - - for idx in (1..n_points).rev() { - let right_x = curve[idx * 2]; - let right_y = curve[idx * 2 + 1]; - let left_x = curve[(idx - 1) * 2]; - let left_y = curve[(idx - 1) * 2 + 1]; - let seg_x = right_x - left_x; - let seg_y = right_y - left_y; - let seg_length = seg_x.hypot(seg_y); - - if seg_length <= 1e-12 { - continue; - } - if remaining <= seg_length { - let fraction = remaining / seg_length; - tail_x = right_x - seg_x * fraction; - tail_y = right_y - seg_y * fraction; - break; - } - remaining -= seg_length; - } - - let dir_x = tip_x - tail_x; - let dir_y = tip_y - tail_y; - let dir_norm = dir_x.hypot(dir_y); - if !dir_norm.is_finite() || dir_norm <= 1e-12 { - return None; - } - - Some((tip_x, tip_y, dir_x / dir_norm, dir_y / dir_norm)) -} - -#[inline] -fn build_arrow_vertices_for_curve( - curve: &[f64], - head_length_px: f64, - head_width_px: f64, - style: ArrowStyle, -) -> Option<[f64; 6]> { - if !head_length_px.is_finite() || !head_width_px.is_finite() { - return None; - } - let backoff_factor = match style { - ArrowStyle::Open => 1.35, - ArrowStyle::Filled => 1.25, - }; - let (tip_x, tip_y, unit_x, unit_y) = - resolve_curve_tip_direction(curve, head_length_px * backoff_factor)?; - - let base_x = tip_x - unit_x * head_length_px; - let base_y = tip_y - unit_y * head_length_px; - let normal_x = -unit_y; - let normal_y = unit_x; - let left_x = base_x + normal_x * head_width_px * 0.5; - let left_y = base_y + normal_y * head_width_px * 0.5; - let right_x = base_x - normal_x * head_width_px * 0.5; - let right_y = base_y - normal_y * head_width_px * 0.5; - - match style { - ArrowStyle::Open => Some([left_x, left_y, tip_x, tip_y, right_x, right_y]), - ArrowStyle::Filled => Some([tip_x, tip_y, left_x, left_y, right_x, right_y]), - } -} - -fn build_arrow_geometry( - display_points: &[f64], - curve_offsets: &[usize], - head_lengths_px: &[f64], - head_widths_px: &[f64], - style: ArrowStyle, -) -> Result { - if display_points.len() % 2 != 0 { - return Err(NclCurlyError::new("display_points must have shape (M, 2)")); - } - let n_curves = head_lengths_px.len(); - if head_widths_px.len() != n_curves { - return Err(NclCurlyError::new( - "head_lengths_px and head_widths_px must have the same length", - )); - } - if curve_offsets.len() != n_curves + 1 { - return Err(NclCurlyError::new( - "curve_offsets must have length len(head_lengths_px) + 1", - )); - } - - let n_points = display_points.len() / 2; - for idx in 0..n_curves { - if curve_offsets[idx] > curve_offsets[idx + 1] || curve_offsets[idx + 1] > n_points { - return Err(NclCurlyError::new( - "curve_offsets must be monotonic and stay within display_points", - )); - } - } - - if n_curves == 0 { - return Ok(ArrowGeometryResult { - vertices: Vec::new(), - source_positions: Vec::new(), - }); - } - - let mut vertices = Vec::with_capacity(n_curves * 6); - let mut source_positions = Vec::with_capacity(n_curves); - - if n_curves >= PARALLEL_ARROW_THRESHOLD { - let computed: Vec> = (0..n_curves) - .into_par_iter() - .map(|curve_idx| { - let start = curve_offsets[curve_idx]; - let end = curve_offsets[curve_idx + 1]; - build_arrow_vertices_for_curve( - &display_points[start * 2..end * 2], - head_lengths_px[curve_idx], - head_widths_px[curve_idx], - style, - ) - }) - .collect(); - - for (curve_idx, verts_opt) in computed.into_iter().enumerate() { - if let Some(verts) = verts_opt { - vertices.extend_from_slice(&verts); - source_positions.push(curve_idx); - } - } - } else { - for curve_idx in 0..n_curves { - let start = curve_offsets[curve_idx]; - let end = curve_offsets[curve_idx + 1]; - if let Some(verts) = build_arrow_vertices_for_curve( - &display_points[start * 2..end * 2], - head_lengths_px[curve_idx], - head_widths_px[curve_idx], - style, - ) { - vertices.extend_from_slice(&verts); - source_positions.push(curve_idx); - } - } - } - - Ok(ArrowGeometryResult { - vertices, - source_positions, - }) -} - -/// Build batched open-arrow head V-polylines `(K, 3, 2)` in display space. -pub fn build_open_arrow_segments( - display_points: &[f64], - curve_offsets: &[usize], - head_lengths_px: &[f64], - head_widths_px: &[f64], -) -> Result { - build_arrow_geometry( - display_points, - curve_offsets, - head_lengths_px, - head_widths_px, - ArrowStyle::Open, - ) -} - -/// Build batched filled-arrow triangle polygons `(K, 3, 2)` in display space. -pub fn build_filled_arrow_polygons( - display_points: &[f64], - curve_offsets: &[usize], - head_lengths_px: &[f64], - head_widths_px: &[f64], -) -> Result { - build_arrow_geometry( - display_points, - curve_offsets, - head_lengths_px, - head_widths_px, - ArrowStyle::Filled, - ) -} - -#[inline] -fn trace_step_budget(max_length_px: f64) -> usize { - if !max_length_px.is_finite() || max_length_px <= 0.0 { - return 1; - } - let required_steps = ((max_length_px / MIN_ACCEPTED_TRACE_STEP_PX).ceil() as usize) - .saturating_add(1) - .max(1); - required_steps.min(MAX_NATIVE_TRACE_STEPS) -} - -#[inline] -fn reverse_xy_in_place(coords: &mut [f64]) { - let n = coords.len() / 2; - for i in 0..(n / 2) { - let j = n - 1 - i; - coords.swap(i * 2, j * 2); - coords.swap(i * 2 + 1, j * 2 + 1); - } -} - -#[allow(clippy::too_many_arguments)] -fn trace_single_glyph( - grid: &GridInfo, - u_data: &[f64], - v_data: &[f64], - display_data: &[f64], - cell_valid_data: &[bool], - start_x: f64, - start_y: f64, - total_length_px: f64, - anchor: TraceAnchor, - step_px: f64, - speed_scale: f64, - viewport_x0: f64, - viewport_y0: f64, - viewport_x1: f64, - viewport_y1: f64, - viewport_width: f64, - viewport_height: f64, -) -> (Option<(Vec, Vec)>, usize) { - let mut current_length_px = total_length_px; - let mut truncated_count = 0usize; - - for _attempt in 0..4 { - let traced = if current_length_px <= 0.0 { - None - } else { - match anchor { - TraceAnchor::Center => { - let half_len = current_length_px / 2.0; - let max_steps = trace_step_budget(half_len); - let backward = trace_ncl_direction_core( - grid, - u_data, - v_data, - display_data, - cell_valid_data, - start_x, - start_y, - half_len, - -1.0, - step_px, - speed_scale, - viewport_x0, - viewport_y0, - viewport_x1, - viewport_y1, - max_steps, - true, - ); - if let Some(ref b) = backward { - if b.truncated { - truncated_count += 1; - } - } - - let forward = trace_ncl_direction_core( - grid, - u_data, - v_data, - display_data, - cell_valid_data, - start_x, - start_y, - half_len, - 1.0, - step_px, - speed_scale, - viewport_x0, - viewport_y0, - viewport_x1, - viewport_y1, - max_steps, - true, - ); - if let Some(ref f) = forward { - if f.truncated { - truncated_count += 1; - } - } - - match (backward, forward) { - (None, None) => None, - (None, Some(f)) => { - let disp = f.display_curve.unwrap_or_default(); - Some((f.curve, disp)) - } - (Some(mut b), None) => { - reverse_xy_in_place(&mut b.curve); - let mut disp = b.display_curve.unwrap_or_default(); - reverse_xy_in_place(&mut disp); - Some((b.curve, disp)) - } - (Some(mut b), Some(f)) => { - reverse_xy_in_place(&mut b.curve); - b.curve.extend_from_slice(&f.curve[2..]); - let mut disp = b.display_curve.unwrap_or_default(); - reverse_xy_in_place(&mut disp); - let f_disp = f.display_curve.unwrap_or_default(); - disp.extend_from_slice(&f_disp[2..]); - Some((b.curve, disp)) - } - } - } - TraceAnchor::Tail => { - let max_steps = trace_step_budget(current_length_px); - trace_ncl_direction_core( - grid, - u_data, - v_data, - display_data, - cell_valid_data, - start_x, - start_y, - current_length_px, - 1.0, - step_px, - speed_scale, - viewport_x0, - viewport_y0, - viewport_x1, - viewport_y1, - max_steps, - true, - ) - .map(|f| { - if f.truncated { - truncated_count += 1; - } - (f.curve, f.display_curve.unwrap_or_default()) - }) - } - TraceAnchor::Head => { - let max_steps = trace_step_budget(current_length_px); - trace_ncl_direction_core( - grid, - u_data, - v_data, - display_data, - cell_valid_data, - start_x, - start_y, - current_length_px, - -1.0, - step_px, - speed_scale, - viewport_x0, - viewport_y0, - viewport_x1, - viewport_y1, - max_steps, - true, - ) - .map(|mut b| { - if b.truncated { - truncated_count += 1; - } - reverse_xy_in_place(&mut b.curve); - let mut disp = b.display_curve.unwrap_or_default(); - reverse_xy_in_place(&mut disp); - (b.curve, disp) - }) - } - } - }; - - if let Some((curve, display_curve)) = traced { - if curve.len() / 2 >= 2 - && validate_display_curve_slice(&display_curve, viewport_width, viewport_height) - { - return (Some((curve, display_curve)), truncated_count); - } - } - - current_length_px *= 0.78; - if current_length_px <= step_px { - break; - } - } - - (None, truncated_count) -} - -/// Trace, stitch, validate, and retry a batch of curly-vector glyphs in parallel via Rayon. -/// -/// Mirrors the Python `_build_ncl_curve` + `_trace_ncl_curve_with_display` + `validate_display_curve` -/// loop across `M` seed centers while preserving deterministic ascending center order. -#[allow(clippy::too_many_arguments)] -pub fn trace_ncl_glyphs_batch( - u: &[f64], - v: &[f64], - display_grid: &[f64], - cell_valid: &[bool], - ny: usize, - nx: usize, - x_origin: f64, - y_origin: f64, - dx: f64, - dy: f64, - centers: &[f64], - target_lengths_px: &[f64], - anchor: TraceAnchor, - step_px: f64, - speed_scale: f64, - viewport_x0: f64, - viewport_y0: f64, - viewport_x1: f64, - viewport_y1: f64, -) -> Result { - if centers.len() % 2 != 0 { - return Err(NclCurlyError::new("centers must have shape (M, 2)")); - } - let n_centers = centers.len() / 2; - if target_lengths_px.len() != n_centers { - return Err(NclCurlyError::new( - "target_lengths_px must have the same length as centers", - )); - } - - let has_cells = validate_trace_grid_inputs(u, v, display_grid, cell_valid, ny, nx)?; - if !has_cells || n_centers == 0 { - return Ok(BatchTraceResult { - data_points: Vec::new(), - display_points: Vec::new(), - curve_offsets: vec![0], - valid_indices: Vec::new(), - truncated_count: 0, - }); - } - - let grid = GridInfo::new(ny, nx, x_origin, y_origin, dx, dy); - let viewport_width = viewport_x1 - viewport_x0; - let viewport_height = viewport_y1 - viewport_y0; - - let run_one = |idx: usize| -> (Option<(Vec, Vec)>, usize) { - trace_single_glyph( - &grid, - u, - v, - display_grid, - cell_valid, - centers[idx * 2], - centers[idx * 2 + 1], - target_lengths_px[idx], - anchor, - step_px, - speed_scale, - viewport_x0, - viewport_y0, - viewport_x1, - viewport_y1, - viewport_width, - viewport_height, - ) - }; - - let per_center: Vec<(Option<(Vec, Vec)>, usize)> = - if n_centers >= PARALLEL_BATCH_TRACE_THRESHOLD { - (0..n_centers).into_par_iter().map(run_one).collect() - } else { - (0..n_centers).map(run_one).collect() - }; - - let mut total_points = 0usize; - let mut valid_count = 0usize; - let mut truncated_count = 0usize; - for (curve_opt, trunc) in &per_center { - truncated_count += *trunc; - if let Some((curve, _)) = curve_opt { - total_points += curve.len() / 2; - valid_count += 1; - } - } - - let mut data_points = Vec::with_capacity(total_points * 2); - let mut display_points = Vec::with_capacity(total_points * 2); - let mut curve_offsets = Vec::with_capacity(valid_count + 1); - let mut valid_indices = Vec::with_capacity(valid_count); - curve_offsets.push(0); - - let mut point_cursor = 0usize; - for (idx, (curve_opt, _)) in per_center.into_iter().enumerate() { - if let Some((curve, display_curve)) = curve_opt { - let n_pts = curve.len() / 2; - data_points.extend_from_slice(&curve); - display_points.extend_from_slice(&display_curve); - point_cursor += n_pts; - curve_offsets.push(point_cursor); - valid_indices.push(idx); - } - } - - Ok(BatchTraceResult { - data_points, - display_points, - curve_offsets, - valid_indices, - truncated_count, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn make_uniform_flow_fixture( - ny: usize, - nx: usize, - u_fn: impl Fn(f64, f64) -> (f64, f64), - map_fn: impl Fn(f64, f64) -> (f64, f64), - ) -> (Vec, Vec, Vec, Vec) { - let mut u = Vec::with_capacity(ny * nx); - let mut v = Vec::with_capacity(ny * nx); - let mut display_grid = Vec::with_capacity(ny * nx * 2); - for iy in 0..ny { - for ix in 0..nx { - let x = ix as f64; - let y = iy as f64; - let (ux, vy) = u_fn(x, y); - let (dx, dy) = map_fn(x, y); - u.push(ux); - v.push(vy); - display_grid.push(dx); - display_grid.push(dy); - } - } - let cell_valid = compute_display_cell_valid(&display_grid, ny, nx).unwrap(); - (u, v, display_grid, cell_valid) - } - - #[test] - fn test_sample_grid_field_and_array_parity() { - let ny = 4; - let nx = 5; - let mut field = vec![0.0; ny * nx]; - for iy in 0..ny { - for ix in 0..nx { - field[iy * nx + ix] = (ix as f64) * 2.0 + (iy as f64) * 10.0; - } - } - field[2 * nx + 3] = f64::NAN; - - // Interior point: (1.5, 0.5) => x=1.5*2 + y=0.5*10 = 8.0 - let s = sample_grid_field(&field, ny, nx, 0.0, 0.0, 1.0, 1.0, 1.5, 0.5).unwrap(); - assert!((s.unwrap() - 8.0).abs() < 1e-12); - - // Right-top boundary point: (4.0, 3.0) => 4*2 + 3*10 = 38.0 - let edge = sample_grid_field(&field, ny, nx, 0.0, 0.0, 1.0, 1.0, 4.0, 3.0).unwrap(); - assert!((edge.unwrap() - 38.0).abs() < 1e-12); - - // Out of bounds and NaN-touching cell - assert!(sample_grid_field(&field, ny, nx, 0.0, 0.0, 1.0, 1.0, -0.1, 0.5) - .unwrap() - .is_none()); - assert!(sample_grid_field(&field, ny, nx, 0.0, 0.0, 1.0, 1.0, 2.5, 1.5) - .unwrap() - .is_none()); - - // Large batch exercises Rayon parallel path and matches scalar calls - let mut pts = Vec::with_capacity(2500 * 2); - for i in 0..2500 { - let t = i as f64 / 2499.0; - pts.push(-0.2 + t * 4.4); - pts.push(-0.2 + t * 3.4); - } - let arr = sample_grid_field_array(&field, ny, nx, 0.0, 0.0, 1.0, 1.0, &pts).unwrap(); - assert_eq!(arr.len(), 2500); - for i in 0..2500 { - let expected = - sample_grid_field(&field, ny, nx, 0.0, 0.0, 1.0, 1.0, pts[i * 2], pts[i * 2 + 1]) - .unwrap(); - match expected { - Some(val) => assert!((arr[i] - val).abs() < 1e-14), - None => assert!(arr[i].is_nan()), - } - } - } - - #[test] - fn test_compute_display_cell_valid_seam_and_nan() { - let ny = 4; - let nx = 5; - let mut display_grid = Vec::with_capacity(ny * nx * 2); - for iy in 0..ny { - for ix in 0..nx { - // Inject a huge antimeridian seam jump at ix >= 3 - let px = if ix >= 3 { - (ix as f64) * 10.0 + 500.0 - } else { - (ix as f64) * 10.0 - }; - let py = (iy as f64) * 10.0; - display_grid.push(px); - display_grid.push(py); - } - } - // Inject a NaN at (iy=0, ix=0) - display_grid[0] = f64::NAN; - - let valid = compute_display_cell_valid(&display_grid, ny, nx).unwrap(); - assert_eq!(valid.len(), (ny - 1) * (nx - 1)); - // (0, 0) touches NaN - assert!(!valid[0]); - // (1, 0) is clean - assert!(valid[1 * (nx - 1)]); - // (iy, 2) spans ix=2 -> ix=3 seam jump - for iy in 0..(ny - 1) { - assert!(!valid[iy * (nx - 1) + 2]); - assert!(valid[iy * (nx - 1) + 3]); - } - } - - #[test] - fn test_sample_display_grid_jacobian_and_parallel() { - let ny = 4; - let nx = 4; - let mut display_grid = Vec::with_capacity(ny * nx * 2); - for iy in 0..ny { - for ix in 0..nx { - // Linear affine map: dx = 100 + 20*x + 5*y, dy = 50 - 3*x + 15*y - let x = ix as f64 * 2.0; - let y = iy as f64 * 3.0; - display_grid.push(100.0 + 20.0 * x + 5.0 * y); - display_grid.push(50.0 - 3.0 * x + 15.0 * y); - } - } - let cell_valid = compute_display_cell_valid(&display_grid, ny, nx).unwrap(); - - let mut pts = Vec::with_capacity(2200 * 2); - for i in 0..2200 { - let f = i as f64 / 2199.0; - pts.push(0.5 + f * 5.0); - pts.push(0.5 + f * 8.0); - } - pts[0] = -1.0; // out of bounds - - let res = sample_display_grid( - &display_grid, - ny, - nx, - &cell_valid, - 0.0, - 0.0, - 2.0, - 3.0, - &pts, - true, - ) - .unwrap(); - assert!(!res.valid[0]); - assert!(res.display_points[0].is_nan()); - let jacs = res.jacobians.as_ref().unwrap(); - assert!(jacs[0].is_nan()); - - for i in 1..2200 { - assert!(res.valid[i]); - let x = pts[i * 2]; - let y = pts[i * 2 + 1]; - assert!((res.display_points[i * 2] - (100.0 + 20.0 * x + 5.0 * y)).abs() < 1e-11); - assert!((res.display_points[i * 2 + 1] - (50.0 - 3.0 * x + 15.0 * y)).abs() < 1e-11); - assert!((jacs[i * 4] - 20.0).abs() < 1e-11); - assert!((jacs[i * 4 + 1] - 5.0).abs() < 1e-11); - assert!((jacs[i * 4 + 2] - (-3.0)).abs() < 1e-11); - assert!((jacs[i * 4 + 3] - 15.0).abs() < 1e-11); - } - } - - #[test] - fn test_thin_candidates_exact_scan_order_parity() { - // Deterministic pseudo-random cloud plus NaNs and exact duplicates - let mut pts = Vec::new(); - let mut seed: u64 = 0x1234_5678_9ABC_DEF0; - for i in 0..500 { - if i == 7 || i == 111 { - pts.push(f64::NAN); - pts.push(0.5); - continue; - } - seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); - let x = ((seed >> 33) as f64) / ((1u64 << 31) as f64); - seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); - let y = ((seed >> 33) as f64) / ((1u64 << 31) as f64); - pts.push(x); - pts.push(y); - } - - let spacing = 0.08; - let selected = thin_mapped_candidates(&pts, spacing).unwrap(); - - // Brute-force O(N^2) reference oracle in exact scan order - let n = pts.len() / 2; - let mut culled = vec![false; n]; - let mut oracle = Vec::new(); - let spacing_sq = spacing * spacing; - for i in 0..n { - if culled[i] || !pts[i * 2].is_finite() || !pts[i * 2 + 1].is_finite() { - continue; - } - oracle.push(i); - for j in (i + 1)..n { - if culled[j] || !pts[j * 2].is_finite() || !pts[j * 2 + 1].is_finite() { - continue; - } - let dx = pts[i * 2] - pts[j * 2]; - let dy = pts[i * 2 + 1] - pts[j * 2 + 1]; - if dx * dx + dy * dy < spacing_sq { - culled[j] = true; - } - } - } - assert_eq!(selected, oracle); - - // Verify thin_display_candidates viewport normalization matches thin_mapped_candidates - let disp: Vec = pts - .chunks_exact(2) - .flat_map(|p| [10.0 + p[0] * 200.0, 20.0 + p[1] * 100.0]) - .collect(); - let selected_disp = - thin_display_candidates(&disp, 10.0, 20.0, 200.0, 100.0, spacing).unwrap(); - assert_eq!(selected_disp, oracle); - } - - #[test] - fn test_generate_cell_candidates_parity() { - let corners = vec![ - 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, // cell 0 - 2.0, 0.0, 3.0, 0.0, 3.0, 1.0, 2.0, 1.0, // cell 1 (invalid mapped) - ]; - let mapped_corners = vec![ - 0.0, 0.0, 0.05, 0.0, 0.05, 0.02, 0.0, 0.02, // ceil(0.05/0.03)=2, ceil(0.02/0.03)=1 - 0.1, 0.0, f64::NAN, 0.0, 0.2, 0.1, 0.1, 0.1, // invalid corner - ]; - let source_points = vec![0.5, 0.5, 2.5, 0.5]; - let res = generate_cell_candidates(&corners, &mapped_corners, &source_points, 0.03).unwrap(); - assert_eq!(res.source_positions, vec![0, 0, 1]); - assert!((res.candidate_points[0] - 0.25).abs() < 1e-12); - assert!((res.candidate_points[1] - 0.5).abs() < 1e-12); - assert!((res.candidate_points[2] - 0.75).abs() < 1e-12); - assert!((res.candidate_points[3] - 0.5).abs() < 1e-12); - assert!((res.candidate_points[4] - 2.5).abs() < 1e-12); - assert!((res.candidate_points[5] - 0.5).abs() < 1e-12); - } - - #[test] - fn test_validate_display_curve_thresholds() { - // Straight horizontal line - let straight = vec![0.0, 0.0, 10.0, 0.0, 20.0, 0.0]; - assert!(validate_display_curve(&straight, 100.0, 100.0).unwrap()); - - // Jump exceeding 0.35 * viewport_diag - let jumped = vec![0.0, 0.0, 60.0, 0.0]; - assert!(!validate_display_curve(&jumped, 100.0, 100.0).unwrap()); - - // Sharp turn > 52 degrees - let sharp = vec![0.0, 0.0, 10.0, 0.0, 10.0, 10.0]; - assert!(!validate_display_curve(&sharp, 500.0, 500.0).unwrap()); - - // S-curve with sign change and total_turn > 70 deg - let s_curve = vec![ - 0.0, 0.0, 10.0, 0.0, 17.0, 7.0, 27.0, 7.0, - ]; - assert!(!validate_display_curve(&s_curve, 500.0, 500.0).unwrap()); - } - - #[test] - fn test_arrow_geometry_builders() { - let display_points = vec![ - 0.0, 0.0, 10.0, 0.0, 20.0, 0.0, // curve 0: horizontal right - 0.0, 0.0, // curve 1: too short (1 point) - 5.0, 5.0, 5.0, 15.0, // curve 2: vertical up - ]; - let curve_offsets = vec![0, 3, 4, 6]; - let head_lengths = vec![4.0, 4.0, 6.0]; - let head_widths = vec![2.0, 2.0, 4.0]; - - let open = build_open_arrow_segments( - &display_points, - &curve_offsets, - &head_lengths, - &head_widths, - ) - .unwrap(); - assert_eq!(open.source_positions, vec![0, 2]); - // Curve 0 open head: base at (16, 0), normal=(0, 1) -> left=(16, 1), tip=(20, 0), right=(16, -1) - assert!((open.vertices[0] - 16.0).abs() < 1e-12); - assert!((open.vertices[1] - 1.0).abs() < 1e-12); - assert!((open.vertices[2] - 20.0).abs() < 1e-12); - assert!((open.vertices[3] - 0.0).abs() < 1e-12); - assert!((open.vertices[4] - 16.0).abs() < 1e-12); - assert!((open.vertices[5] - (-1.0)).abs() < 1e-12); - - let filled = build_filled_arrow_polygons( - &display_points, - &curve_offsets, - &head_lengths, - &head_widths, - ) - .unwrap(); - assert_eq!(filled.source_positions, vec![0, 2]); - // Curve 0 filled head: tip=(20, 0), left=(16, 1), right=(16, -1) - assert!((filled.vertices[0] - 20.0).abs() < 1e-12); - assert!((filled.vertices[1] - 0.0).abs() < 1e-12); - assert!((filled.vertices[2] - 16.0).abs() < 1e-12); - assert!((filled.vertices[3] - 1.0).abs() < 1e-12); - assert!((filled.vertices[4] - 16.0).abs() < 1e-12); - assert!((filled.vertices[5] - (-1.0)).abs() < 1e-12); - } - - #[test] - fn test_trace_ncl_direction_and_batch_parity() { - let ny = 15; - let nx = 15; - // Rotational vortex around (7, 7) mapped to display [0..1400, 0..1400] - let (u, v, display_grid, cell_valid) = make_uniform_flow_fixture( - ny, - nx, - |x, y| (-(y - 7.0), x - 7.0), - |x, y| (x * 100.0, y * 100.0), - ); - - let single = trace_ncl_direction( - &u, - &v, - &display_grid, - &cell_valid, - ny, - nx, - 0.0, - 0.0, - 1.0, - 1.0, - 7.0, - 3.0, - 30.0, - 1.0, - 3.0, - 10.0, - 0.0, - 0.0, - 1400.0, - 1400.0, - 512, - true, - ) - .unwrap() - .unwrap(); - let n_pts = single.curve.len() / 2; - assert!(n_pts >= 4); - assert_eq!(single.display_curve.as_ref().unwrap().len(), single.curve.len()); - - // Batch trace 16 centers across all three anchor modes and verify exact match with sequential single-branch calls - let mut centers = Vec::new(); - let mut lengths = Vec::new(); - for iy in 2..6 { - for ix in 2..6 { - centers.push(ix as f64 * 2.0); - centers.push(iy as f64 * 2.0); - lengths.push(28.0); - } - } - // Add one out-of-bounds center to verify valid_indices preserves alignment - centers.push(99.0); - centers.push(99.0); - lengths.push(28.0); - - for anchor in [TraceAnchor::Center, TraceAnchor::Tail, TraceAnchor::Head] { - let batch = trace_ncl_glyphs_batch( - &u, - &v, - &display_grid, - &cell_valid, - ny, - nx, - 0.0, - 0.0, - 1.0, - 1.0, - ¢ers, - &lengths, - anchor, - 3.0, - 10.0, - 0.0, - 0.0, - 1400.0, - 1400.0, - ) - .unwrap(); - - assert!(!batch.valid_indices.is_empty()); - assert!(!batch.valid_indices.contains(&16)); - assert_eq!(batch.curve_offsets.len(), batch.valid_indices.len() + 1); - assert_eq!( - *batch.curve_offsets.last().unwrap() * 2, - batch.data_points.len() - ); - assert_eq!(batch.display_points.len(), batch.data_points.len()); - - // Check exact stitch parity against trace_ncl_direction for the first valid glyph - let first_idx = batch.valid_indices[0]; - let sx = centers[first_idx * 2]; - let sy = centers[first_idx * 2 + 1]; - let start = batch.curve_offsets[0] * 2; - let end = batch.curve_offsets[1] * 2; - let got_curve = &batch.data_points[start..end]; - - match anchor { - TraceAnchor::Tail => { - let fwd = trace_ncl_direction( - &u, - &v, - &display_grid, - &cell_valid, - ny, - nx, - 0.0, - 0.0, - 1.0, - 1.0, - sx, - sy, - lengths[first_idx], - 1.0, - 3.0, - 10.0, - 0.0, - 0.0, - 1400.0, - 1400.0, - trace_step_budget(lengths[first_idx]), - true, - ) - .unwrap() - .unwrap(); - assert_eq!(got_curve, fwd.curve.as_slice()); - } - TraceAnchor::Head => { - let mut bwd = trace_ncl_direction( - &u, - &v, - &display_grid, - &cell_valid, - ny, - nx, - 0.0, - 0.0, - 1.0, - 1.0, - sx, - sy, - lengths[first_idx], - -1.0, - 3.0, - 10.0, - 0.0, - 0.0, - 1400.0, - 1400.0, - trace_step_budget(lengths[first_idx]), - true, - ) - .unwrap() - .unwrap(); - reverse_xy_in_place(&mut bwd.curve); - assert_eq!(got_curve, bwd.curve.as_slice()); - } - TraceAnchor::Center => { - // Seed center point must appear along the stitched curve - let has_seed = got_curve - .chunks_exact(2) - .any(|p| (p[0] - sx).abs() < 1e-12 && (p[1] - sy).abs() < 1e-12); - assert!(has_seed); - } - } - } - } - - #[test] - fn test_trace_ncl_glyphs_batch_truncation_count() { - let ny = 10; - let nx = 10; - let (u, v, display_grid, cell_valid) = make_uniform_flow_fixture( - ny, - nx, - |_x, _y| (1.0, 0.0), - |x, y| (x * 1000.0, y * 1000.0), - ); - // With 1/3 backward correction, steady-state net step is ~(2/3)*step_px. - // Using step_px=0.36 gives net step ~0.24 > 0.2, so 4096 steps reach ~983 px < 2000.0. - let batch = trace_ncl_glyphs_batch( - &u, - &v, - &display_grid, - &cell_valid, - ny, - nx, - 0.0, - 0.0, - 1.0, - 1.0, - &[0.5, 4.5], - &[2000.0], - TraceAnchor::Tail, - 0.36, - 1.0, - 0.0, - 0.0, - 9000.0, - 9000.0, - ) - .unwrap(); - assert!(batch.truncated_count >= 1); - assert_eq!(batch.valid_indices, vec![0]); - assert_eq!(batch.curve_offsets[1], 4097); - } - - #[test] - fn test_trace_viewport_clipping_and_edge_cases() { - let ny = 6; - let nx = 6; - let (u, v, display_grid, cell_valid) = make_uniform_flow_fixture( - ny, - nx, - |_x, _y| (1.0, 0.0), - |x, y| (x * 100.0, y * 100.0), - ); - // Viewport right boundary at x=250.0, starting at x=2.0 (display 200.0) - let clipped = trace_ncl_direction( - &u, - &v, - &display_grid, - &cell_valid, - ny, - nx, - 0.0, - 0.0, - 1.0, - 1.0, - 2.0, - 2.0, - 200.0, - 1.0, - 20.0, - 1.0, - 0.0, - 0.0, - 250.0, - 500.0, - 512, - true, - ) - .unwrap() - .unwrap(); - let disp = clipped.display_curve.unwrap(); - let last_x = disp[disp.len() - 2]; - assert!((last_x - 250.0).abs() < 1e-11); - - // 1xN grid returns None gracefully - let tiny = trace_ncl_direction( - &[1.0, 1.0], - &[0.0, 0.0], - &[0.0, 0.0, 1.0, 0.0], - &[], - 1, - 2, - 0.0, - 0.0, - 1.0, - 1.0, - 0.5, - 0.0, - 10.0, - 1.0, - 2.0, - 1.0, - 0.0, - 0.0, - 10.0, - 10.0, - 64, - false, - ) - .unwrap(); - assert!(tiny.is_none()); - } - - #[test] - fn test_parallel_thresholds_thin_cells_valid_and_arrows() { - // 1) compute_display_cell_valid above PARALLEL_CELL_VALID_THRESHOLD (70x70 = 4761 cells) - let ny = 70; - let nx = 70; - let mut display_grid = Vec::with_capacity(ny * nx * 2); - for iy in 0..ny { - for ix in 0..nx { - display_grid.push(ix as f64 * 5.0); - display_grid.push(iy as f64 * 5.0); - } - } - let valid = compute_display_cell_valid(&display_grid, ny, nx).unwrap(); - assert_eq!(valid.len(), (ny - 1) * (nx - 1)); - assert!(valid.iter().all(|&v| v)); - - // 2) thin_mapped_candidates above PARALLEL_THIN_THRESHOLD (17000 points) - let n_thin = 17_000usize; - let mut pts = Vec::with_capacity(n_thin * 2); - let mut seed: u64 = 0xCAFE_BABE_1234_5678; - for _ in 0..n_thin { - seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); - let x = ((seed >> 33) as f64) / ((1u64 << 31) as f64); - seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); - let y = ((seed >> 33) as f64) / ((1u64 << 31) as f64); - pts.push(x); - pts.push(y); - } - let selected = thin_mapped_candidates(&pts, 0.04).unwrap(); - assert!(!selected.is_empty()); - // Verify all selected pairs respect spacing >= 0.04 and remain strictly increasing - for w in selected.windows(2) { - assert!(w[0] < w[1]); - } - for i in 0..selected.len().min(200) { - for j in (i + 1)..selected.len().min(200) { - let a = selected[i]; - let b = selected[j]; - let dx = pts[a * 2] - pts[b * 2]; - let dy = pts[a * 2 + 1] - pts[b * 2 + 1]; - assert!(dx * dx + dy * dy >= 0.04 * 0.04 - 1e-15); - } - } - - // 3) generate_cell_candidates above PARALLEL_CELL_CANDIDATE_THRESHOLD (4200 cells) - let n_cells = 4200usize; - let mut corners = Vec::with_capacity(n_cells * 8); - let mut mapped_corners = Vec::with_capacity(n_cells * 8); - let mut source_points = Vec::with_capacity(n_cells * 2); - for c in 0..n_cells { - let x0 = c as f64; - corners.extend_from_slice(&[x0, 0.0, x0 + 1.0, 0.0, x0 + 1.0, 1.0, x0, 1.0]); - mapped_corners.extend_from_slice(&[0.0, 0.0, 0.04, 0.0, 0.04, 0.02, 0.0, 0.02]); - source_points.extend_from_slice(&[x0 + 0.5, 0.5]); - } - let cand = generate_cell_candidates(&corners, &mapped_corners, &source_points, 0.03).unwrap(); - assert_eq!(cand.source_positions.len(), n_cells * 2); - assert_eq!(cand.candidate_points.len(), n_cells * 4); - - // 4) build_open_arrow_segments & build_filled_arrow_polygons above PARALLEL_ARROW_THRESHOLD (600 curves) - let n_curves = 600usize; - let mut curve_pts = Vec::with_capacity(n_curves * 4); - let mut offsets = Vec::with_capacity(n_curves + 1); - offsets.push(0); - for c in 0..n_curves { - curve_pts.extend_from_slice(&[0.0, c as f64, 10.0, c as f64]); - offsets.push((c + 1) * 2); - } - let hl = vec![4.0; n_curves]; - let hw = vec![2.0; n_curves]; - let open = build_open_arrow_segments(&curve_pts, &offsets, &hl, &hw).unwrap(); - let filled = build_filled_arrow_polygons(&curve_pts, &offsets, &hl, &hw).unwrap(); - assert_eq!(open.source_positions.len(), n_curves); - assert_eq!(filled.source_positions.len(), n_curves); - } -} diff --git a/rust/skybornplot-core/src/ncl_curly/arrows.rs b/rust/skybornplot-core/src/ncl_curly/arrows.rs new file mode 100644 index 0000000..6ba4dfc --- /dev/null +++ b/rust/skybornplot-core/src/ncl_curly/arrows.rs @@ -0,0 +1,208 @@ +//! Display-space arrowhead geometry builders for open and filled curly vectors. + +use rayon::prelude::*; + +use super::{ArrowGeometryResult, NclCurlyError}; + +const PARALLEL_ARROW_THRESHOLD: usize = 512; + +#[derive(Clone, Copy)] +enum ArrowStyle { + Open, + Filled, +} + +#[inline] +fn resolve_curve_tip_direction(curve: &[f64], backoff_px: f64) -> Option<(f64, f64, f64, f64)> { + let n_points = curve.len() / 2; + if n_points < 2 || !backoff_px.is_finite() { + return None; + } + if curve.iter().any(|v| !v.is_finite()) { + return None; + } + + let tip_x = curve[(n_points - 1) * 2]; + let tip_y = curve[(n_points - 1) * 2 + 1]; + let mut tail_x = curve[0]; + let mut tail_y = curve[1]; + let mut remaining = backoff_px.max(0.0); + + for idx in (1..n_points).rev() { + let right_x = curve[idx * 2]; + let right_y = curve[idx * 2 + 1]; + let left_x = curve[(idx - 1) * 2]; + let left_y = curve[(idx - 1) * 2 + 1]; + let seg_x = right_x - left_x; + let seg_y = right_y - left_y; + let seg_length = seg_x.hypot(seg_y); + + if seg_length <= 1e-12 { + continue; + } + if remaining <= seg_length { + let fraction = remaining / seg_length; + tail_x = right_x - seg_x * fraction; + tail_y = right_y - seg_y * fraction; + break; + } + remaining -= seg_length; + } + + let dir_x = tip_x - tail_x; + let dir_y = tip_y - tail_y; + let dir_norm = dir_x.hypot(dir_y); + if !dir_norm.is_finite() || dir_norm <= 1e-12 { + return None; + } + + Some((tip_x, tip_y, dir_x / dir_norm, dir_y / dir_norm)) +} + +#[inline] +fn build_arrow_vertices_for_curve( + curve: &[f64], + head_length_px: f64, + head_width_px: f64, + style: ArrowStyle, +) -> Option<[f64; 6]> { + if !head_length_px.is_finite() || !head_width_px.is_finite() { + return None; + } + let backoff_factor = match style { + ArrowStyle::Open => 1.35, + ArrowStyle::Filled => 1.25, + }; + let (tip_x, tip_y, unit_x, unit_y) = + resolve_curve_tip_direction(curve, head_length_px * backoff_factor)?; + + let base_x = tip_x - unit_x * head_length_px; + let base_y = tip_y - unit_y * head_length_px; + let normal_x = -unit_y; + let normal_y = unit_x; + let left_x = base_x + normal_x * head_width_px * 0.5; + let left_y = base_y + normal_y * head_width_px * 0.5; + let right_x = base_x - normal_x * head_width_px * 0.5; + let right_y = base_y - normal_y * head_width_px * 0.5; + + match style { + ArrowStyle::Open => Some([left_x, left_y, tip_x, tip_y, right_x, right_y]), + ArrowStyle::Filled => Some([tip_x, tip_y, left_x, left_y, right_x, right_y]), + } +} + +fn build_arrow_geometry( + display_points: &[f64], + curve_offsets: &[usize], + head_lengths_px: &[f64], + head_widths_px: &[f64], + style: ArrowStyle, +) -> Result { + if display_points.len() % 2 != 0 { + return Err(NclCurlyError::new("display_points must have shape (M, 2)")); + } + let n_curves = head_lengths_px.len(); + if head_widths_px.len() != n_curves { + return Err(NclCurlyError::new( + "head_lengths_px and head_widths_px must have the same length", + )); + } + if curve_offsets.len() != n_curves + 1 { + return Err(NclCurlyError::new( + "curve_offsets must have length len(head_lengths_px) + 1", + )); + } + + let n_points = display_points.len() / 2; + for idx in 0..n_curves { + if curve_offsets[idx] > curve_offsets[idx + 1] || curve_offsets[idx + 1] > n_points { + return Err(NclCurlyError::new( + "curve_offsets must be monotonic and stay within display_points", + )); + } + } + + if n_curves == 0 { + return Ok(ArrowGeometryResult { + vertices: Vec::new(), + source_positions: Vec::new(), + }); + } + + let mut vertices = Vec::with_capacity(n_curves * 6); + let mut source_positions = Vec::with_capacity(n_curves); + + if n_curves >= PARALLEL_ARROW_THRESHOLD { + let computed: Vec> = (0..n_curves) + .into_par_iter() + .map(|curve_idx| { + let start = curve_offsets[curve_idx]; + let end = curve_offsets[curve_idx + 1]; + build_arrow_vertices_for_curve( + &display_points[start * 2..end * 2], + head_lengths_px[curve_idx], + head_widths_px[curve_idx], + style, + ) + }) + .collect(); + + for (curve_idx, verts_opt) in computed.into_iter().enumerate() { + if let Some(verts) = verts_opt { + vertices.extend_from_slice(&verts); + source_positions.push(curve_idx); + } + } + } else { + for curve_idx in 0..n_curves { + let start = curve_offsets[curve_idx]; + let end = curve_offsets[curve_idx + 1]; + if let Some(verts) = build_arrow_vertices_for_curve( + &display_points[start * 2..end * 2], + head_lengths_px[curve_idx], + head_widths_px[curve_idx], + style, + ) { + vertices.extend_from_slice(&verts); + source_positions.push(curve_idx); + } + } + } + + Ok(ArrowGeometryResult { + vertices, + source_positions, + }) +} + +/// Build batched open-arrow head V-polylines `(K, 3, 2)` in display space. +pub fn build_open_arrow_segments( + display_points: &[f64], + curve_offsets: &[usize], + head_lengths_px: &[f64], + head_widths_px: &[f64], +) -> Result { + build_arrow_geometry( + display_points, + curve_offsets, + head_lengths_px, + head_widths_px, + ArrowStyle::Open, + ) +} + +/// Build batched filled-arrow triangle polygons `(K, 3, 2)` in display space. +pub fn build_filled_arrow_polygons( + display_points: &[f64], + curve_offsets: &[usize], + head_lengths_px: &[f64], + head_widths_px: &[f64], +) -> Result { + build_arrow_geometry( + display_points, + curve_offsets, + head_lengths_px, + head_widths_px, + ArrowStyle::Filled, + ) +} diff --git a/rust/skybornplot-core/src/ncl_curly/grid.rs b/rust/skybornplot-core/src/ncl_curly/grid.rs new file mode 100644 index 0000000..7dd2cf6 --- /dev/null +++ b/rust/skybornplot-core/src/ncl_curly/grid.rs @@ -0,0 +1,631 @@ +//! Regular-grid bilinear sampling, display-cell validity, and Jacobian evaluation. + +use rayon::prelude::*; + +use super::{NclCurlyError, SampleDisplayGridResult}; + +const PARALLEL_SAMPLE_THRESHOLD: usize = 2048; +const PARALLEL_CELL_VALID_THRESHOLD: usize = 4096; + +#[derive(Clone, Copy)] +pub(super) struct GridInfo { + pub(super) nx: usize, + pub(super) ny: usize, + x_origin: f64, + y_origin: f64, + dx_safe: f64, + dy_safe: f64, + inv_dx: f64, + inv_dy: f64, + max_x_index: f64, + max_y_index: f64, + max_cell_x: f64, + max_cell_y: f64, +} + +impl GridInfo { + #[inline] + pub(super) fn new( + ny: usize, + nx: usize, + x_origin: f64, + y_origin: f64, + dx: f64, + dy: f64, + ) -> Self { + let dx_abs = dx.abs(); + let dy_abs = dy.abs(); + let dx_safe = if dx_abs > 1e-12 { dx_abs } else { 1e-12 }; + let dy_safe = if dy_abs > 1e-12 { dy_abs } else { 1e-12 }; + Self { + nx, + ny, + x_origin, + y_origin, + dx_safe, + dy_safe, + inv_dx: 1.0 / dx_safe, + inv_dy: 1.0 / dy_safe, + max_x_index: nx.saturating_sub(1) as f64, + max_y_index: ny.saturating_sub(1) as f64, + max_cell_x: nx.saturating_sub(2) as f64, + max_cell_y: ny.saturating_sub(2) as f64, + } + } + + #[inline] + pub(super) fn contains_data(&self, x: f64, y: f64) -> bool { + let xi = (x - self.x_origin) * self.inv_dx; + let yi = (y - self.y_origin) * self.inv_dy; + 0.0 <= xi && xi <= self.max_x_index && 0.0 <= yi && yi <= self.max_y_index + } +} + +#[derive(Clone, Copy)] +pub(super) struct SampleState { + pub(super) display_x: f64, + pub(super) display_y: f64, + pub(super) j00: f64, + pub(super) j01: f64, + pub(super) j10: f64, + pub(super) j11: f64, + pub(super) dir_x: f64, + pub(super) dir_y: f64, + pub(super) speed: f64, +} + +#[inline] +pub(super) fn sample_state( + grid: &GridInfo, + u_data: &[f64], + v_data: &[f64], + display_data: &[f64], + cell_valid: &[bool], + x: f64, + y: f64, +) -> Option { + if grid.nx < 2 || grid.ny < 2 { + return None; + } + + let xi = (x - grid.x_origin) * grid.inv_dx; + let yi = (y - grid.y_origin) * grid.inv_dy; + if !(0.0 <= xi && xi <= grid.max_x_index && 0.0 <= yi && yi <= grid.max_y_index) { + return None; + } + + let ix = xi.max(0.0).min(grid.max_cell_x).floor() as usize; + let iy = yi.max(0.0).min(grid.max_cell_y).floor() as usize; + if !cell_valid[iy * (grid.nx - 1) + ix] { + return None; + } + + let sx = xi - ix as f64; + let sy = yi - iy as f64; + let one_minus_sx = 1.0 - sx; + let one_minus_sy = 1.0 - sy; + let nx = grid.nx; + + let idx00 = iy * nx + ix; + let idx01 = iy * nx + (ix + 1); + let idx10 = (iy + 1) * nx + ix; + let idx11 = (iy + 1) * nx + (ix + 1); + + let u00 = u_data[idx00]; + let u01 = u_data[idx01]; + let u10 = u_data[idx10]; + let u11 = u_data[idx11]; + let v00 = v_data[idx00]; + let v01 = v_data[idx01]; + let v10 = v_data[idx10]; + let v11 = v_data[idx11]; + + let u_value = + (u00 * one_minus_sx + u01 * sx) * one_minus_sy + (u10 * one_minus_sx + u11 * sx) * sy; + let v_value = + (v00 * one_minus_sx + v01 * sx) * one_minus_sy + (v10 * one_minus_sx + v11 * sx) * sy; + if !u_value.is_finite() || !v_value.is_finite() { + return None; + } + + let d00 = idx00 * 2; + let d01 = idx01 * 2; + let d10 = idx10 * 2; + let d11 = idx11 * 2; + + let p00x = display_data[d00]; + let p00y = display_data[d00 + 1]; + let p01x = display_data[d01]; + let p01y = display_data[d01 + 1]; + let p10x = display_data[d10]; + let p10y = display_data[d10 + 1]; + let p11x = display_data[d11]; + let p11y = display_data[d11 + 1]; + + let display_x = p00x * one_minus_sx * one_minus_sy + + p01x * sx * one_minus_sy + + p10x * one_minus_sx * sy + + p11x * sx * sy; + let display_y = p00y * one_minus_sx * one_minus_sy + + p01y * sx * one_minus_sy + + p10y * one_minus_sx * sy + + p11y * sx * sy; + let j00 = ((p01x - p00x) * one_minus_sy + (p11x - p10x) * sy) / grid.dx_safe; + let j10 = ((p01y - p00y) * one_minus_sy + (p11y - p10y) * sy) / grid.dx_safe; + let j01 = ((p10x - p00x) * one_minus_sx + (p11x - p01x) * sx) / grid.dy_safe; + let j11 = ((p10y - p00y) * one_minus_sx + (p11y - p01y) * sx) / grid.dy_safe; + + let det = j00 * j11 - j01 * j10; + if !display_x.is_finite() || !display_y.is_finite() || !det.is_finite() || det.abs() <= 1e-12 + { + return None; + } + + let vec_x = j00 * u_value + j01 * v_value; + let vec_y = j10 * u_value + j11 * v_value; + let vec_norm = vec_x.hypot(vec_y); + if !vec_norm.is_finite() || vec_norm <= 1e-12 { + return None; + } + + let speed = u_value.hypot(v_value); + if !speed.is_finite() { + return None; + } + + Some(SampleState { + display_x, + display_y, + j00, + j01, + j10, + j11, + dir_x: vec_x / vec_norm, + dir_y: vec_y / vec_norm, + speed, + }) +} + +#[inline] +fn sample_scalar_field(grid: &GridInfo, field_data: &[f64], x: f64, y: f64) -> Option { + if grid.nx < 1 || grid.ny < 1 { + return None; + } + + let xi = (x - grid.x_origin) * grid.inv_dx; + let yi = (y - grid.y_origin) * grid.inv_dy; + if !(0.0 <= xi && xi <= grid.max_x_index && 0.0 <= yi && yi <= grid.max_y_index) { + return None; + } + + let ix = xi as usize; + let iy = yi as usize; + let ix_next = if ix == grid.nx - 1 { ix } else { ix + 1 }; + let iy_next = if iy == grid.ny - 1 { iy } else { iy + 1 }; + + let sx = xi - ix as f64; + let sy = yi - iy as f64; + + let a00 = field_data[iy * grid.nx + ix]; + let a01 = field_data[iy * grid.nx + ix_next]; + let a10 = field_data[iy_next * grid.nx + ix]; + let a11 = field_data[iy_next * grid.nx + ix_next]; + + let value = (a00 * (1.0 - sx) + a01 * sx) * (1.0 - sy) + (a10 * (1.0 - sx) + a11 * sx) * sy; + if value.is_finite() { + Some(value) + } else { + None + } +} + +/// Bilinearly sample one scalar value from a 2D regular grid `(ny, nx)`. +#[allow(clippy::too_many_arguments)] +pub fn sample_grid_field( + field: &[f64], + ny: usize, + nx: usize, + x_origin: f64, + y_origin: f64, + dx: f64, + dy: f64, + x: f64, + y: f64, +) -> Result, NclCurlyError> { + let expected = ny + .checked_mul(nx) + .ok_or_else(|| NclCurlyError::new("field dimensions overflow"))?; + if field.len() != expected { + return Err(NclCurlyError::new("field shape does not match (ny, nx)")); + } + let grid = GridInfo::new(ny, nx, x_origin, y_origin, dx, dy); + Ok(sample_scalar_field(&grid, field, x, y)) +} + +/// Bilinearly sample a 2D scalar field `(ny, nx)` at a flat `(N, 2)` array of coordinates. +/// +/// Out-of-bounds or non-finite samples yield `f64::NAN`. +#[allow(clippy::too_many_arguments)] +pub fn sample_grid_field_array( + field: &[f64], + ny: usize, + nx: usize, + x_origin: f64, + y_origin: f64, + dx: f64, + dy: f64, + points: &[f64], +) -> Result, NclCurlyError> { + let expected = ny + .checked_mul(nx) + .ok_or_else(|| NclCurlyError::new("field dimensions overflow"))?; + if field.len() != expected { + return Err(NclCurlyError::new("field shape does not match (ny, nx)")); + } + if points.len() % 2 != 0 { + return Err(NclCurlyError::new("points must have shape (N, 2) or (2,)")); + } + + let point_count = points.len() / 2; + let mut output = vec![f64::NAN; point_count]; + if point_count == 0 { + return Ok(output); + } + + let grid = GridInfo::new(ny, nx, x_origin, y_origin, dx, dy); + if point_count >= PARALLEL_SAMPLE_THRESHOLD { + output + .par_chunks_mut(512) + .enumerate() + .for_each(|(chunk_idx, out_chunk)| { + let start = chunk_idx * 512; + for (offset, out_val) in out_chunk.iter_mut().enumerate() { + let idx = start + offset; + if let Some(value) = + sample_scalar_field(&grid, field, points[idx * 2], points[idx * 2 + 1]) + { + *out_val = value; + } + } + }); + } else { + for (idx, out_val) in output.iter_mut().enumerate() { + if let Some(value) = + sample_scalar_field(&grid, field, points[idx * 2], points[idx * 2 + 1]) + { + *out_val = value; + } + } + } + + Ok(output) +} + +/// Compute per-cell validity mask `(ny - 1, nx - 1)` for a mapped display grid `(ny, nx, 2)`. +/// +/// A cell is valid when all four corner coordinates are finite and none of its four +/// edge lengths exceeds the projection seam jump threshold (`12 * median(lower half)`). +pub fn compute_display_cell_valid( + display_grid: &[f64], + ny: usize, + nx: usize, +) -> Result, NclCurlyError> { + if ny < 2 || nx < 2 { + return Err(NclCurlyError::new( + "display_grid must contain at least one cell", + )); + } + let expected = ny + .checked_mul(nx) + .and_then(|n| n.checked_mul(2)) + .ok_or_else(|| NclCurlyError::new("display_grid dimensions overflow"))?; + if display_grid.len() != expected { + return Err(NclCurlyError::new("display_grid must have shape (ny, nx, 2)")); + } + + let n_edges = ny * (nx - 1) + (ny - 1) * nx; + let mut edges = Vec::with_capacity(n_edges); + + for iy in 0..ny { + for ix in 0..(nx - 1) { + let left_idx = (iy * nx + ix) * 2; + let right_idx = (iy * nx + ix + 1) * 2; + let length = (display_grid[right_idx] - display_grid[left_idx]) + .hypot(display_grid[right_idx + 1] - display_grid[left_idx + 1]); + if length.is_finite() && length > 1e-9 { + edges.push(length); + } + } + } + for iy in 0..(ny - 1) { + for ix in 0..nx { + let top_idx = (iy * nx + ix) * 2; + let bottom_idx = ((iy + 1) * nx + ix) * 2; + let length = (display_grid[bottom_idx] - display_grid[top_idx]) + .hypot(display_grid[bottom_idx + 1] - display_grid[top_idx + 1]); + if length.is_finite() && length > 1e-9 { + edges.push(length); + } + } + } + + let jump_limit = if !edges.is_empty() { + let lower_count = (edges.len() / 2).max(1); + let mid = lower_count / 2; + edges.select_nth_unstable_by(mid, f64::total_cmp); + let median = if lower_count % 2 == 1 { + edges[mid] + } else { + let left_max = edges[..mid] + .iter() + .copied() + .fold(f64::NEG_INFINITY, f64::max); + 0.5 * (left_max + edges[mid]) + }; + Some((median * 12.0).max(1e-6)) + } else { + None + }; + + let cell_nx = nx - 1; + let cell_ny = ny - 1; + let total_cells = cell_ny * cell_nx; + let mut cell_valid = vec![false; total_cells]; + + let eval_row = |iy: usize, row_out: &mut [bool]| { + for (ix, out_flag) in row_out.iter_mut().enumerate() { + let idx00 = (iy * nx + ix) * 2; + let idx01 = (iy * nx + ix + 1) * 2; + let idx10 = ((iy + 1) * nx + ix) * 2; + let idx11 = ((iy + 1) * nx + ix + 1) * 2; + + let finite_cell = display_grid[idx00].is_finite() + && display_grid[idx00 + 1].is_finite() + && display_grid[idx01].is_finite() + && display_grid[idx01 + 1].is_finite() + && display_grid[idx10].is_finite() + && display_grid[idx10 + 1].is_finite() + && display_grid[idx11].is_finite() + && display_grid[idx11 + 1].is_finite(); + + if !finite_cell { + *out_flag = false; + continue; + } + let Some(limit) = jump_limit else { + *out_flag = true; + continue; + }; + + let top_edge = (display_grid[idx01] - display_grid[idx00]) + .hypot(display_grid[idx01 + 1] - display_grid[idx00 + 1]); + let bottom_edge = (display_grid[idx11] - display_grid[idx10]) + .hypot(display_grid[idx11 + 1] - display_grid[idx10 + 1]); + let left_edge = (display_grid[idx10] - display_grid[idx00]) + .hypot(display_grid[idx10 + 1] - display_grid[idx00 + 1]); + let right_edge = (display_grid[idx11] - display_grid[idx01]) + .hypot(display_grid[idx11 + 1] - display_grid[idx01 + 1]); + let max_edge = top_edge.max(bottom_edge).max(left_edge.max(right_edge)); + *out_flag = max_edge.is_finite() && max_edge <= limit; + } + }; + + if total_cells >= PARALLEL_CELL_VALID_THRESHOLD { + cell_valid + .par_chunks_mut(cell_nx) + .enumerate() + .for_each(|(iy, row_out)| eval_row(iy, row_out)); + } else { + for (iy, row_out) in cell_valid.chunks_mut(cell_nx).enumerate() { + eval_row(iy, row_out); + } + } + + Ok(cell_valid) +} + +#[inline] +fn sample_display_point( + grid: &GridInfo, + display: &[f64], + cell_valid: &[bool], + point_x: f64, + point_y: f64, + include_jacobian: bool, +) -> Option<(f64, f64, [f64; 4])> { + let xi = (point_x - grid.x_origin) * grid.inv_dx; + let yi = (point_y - grid.y_origin) * grid.inv_dy; + if !(0.0 <= xi && xi <= grid.max_x_index && 0.0 <= yi && yi <= grid.max_y_index) { + return None; + } + + let ix = xi.max(0.0).min(grid.max_cell_x).floor() as usize; + let iy = yi.max(0.0).min(grid.max_cell_y).floor() as usize; + if !cell_valid[iy * (grid.nx - 1) + ix] { + return None; + } + + let sx = xi - ix as f64; + let sy = yi - iy as f64; + let one_minus_sx = 1.0 - sx; + let one_minus_sy = 1.0 - sy; + let idx00 = (iy * grid.nx + ix) * 2; + let idx01 = (iy * grid.nx + ix + 1) * 2; + let idx10 = ((iy + 1) * grid.nx + ix) * 2; + let idx11 = ((iy + 1) * grid.nx + ix + 1) * 2; + + let p00x = display[idx00]; + let p00y = display[idx00 + 1]; + let p01x = display[idx01]; + let p01y = display[idx01 + 1]; + let p10x = display[idx10]; + let p10y = display[idx10 + 1]; + let p11x = display[idx11]; + let p11y = display[idx11 + 1]; + + let display_x = p00x * one_minus_sx * one_minus_sy + + p01x * sx * one_minus_sy + + p10x * one_minus_sx * sy + + p11x * sx * sy; + let display_y = p00y * one_minus_sx * one_minus_sy + + p01y * sx * one_minus_sy + + p10y * one_minus_sx * sy + + p11y * sx * sy; + if !display_x.is_finite() || !display_y.is_finite() { + return None; + } + + if !include_jacobian { + return Some((display_x, display_y, [0.0; 4])); + } + + let dfdx_x = ((p01x - p00x) * one_minus_sy + (p11x - p10x) * sy) / grid.dx_safe; + let dfdx_y = ((p01y - p00y) * one_minus_sy + (p11y - p10y) * sy) / grid.dx_safe; + let dfdy_x = ((p10x - p00x) * one_minus_sx + (p11x - p01x) * sx) / grid.dy_safe; + let dfdy_y = ((p10y - p00y) * one_minus_sx + (p11y - p01y) * sx) / grid.dy_safe; + let det = dfdx_x * dfdy_y - dfdy_x * dfdx_y; + + if !dfdx_x.is_finite() + || !dfdx_y.is_finite() + || !dfdy_x.is_finite() + || !dfdy_y.is_finite() + || !det.is_finite() + || det.abs() <= 1e-12 + { + return None; + } + + Some((display_x, display_y, [dfdx_x, dfdy_x, dfdx_y, dfdy_y])) +} + +/// Bilinearly sample display-grid positions and optional local Jacobians for a batch of data-space points. +#[allow(clippy::too_many_arguments)] +pub fn sample_display_grid( + display_grid: &[f64], + ny: usize, + nx: usize, + cell_valid: &[bool], + x_origin: f64, + y_origin: f64, + dx: f64, + dy: f64, + points: &[f64], + include_jacobian: bool, +) -> Result { + if ny == 0 || nx == 0 { + return Err(NclCurlyError::new("display_grid must have non-zero shape")); + } + let expected_display = ny + .checked_mul(nx) + .and_then(|n| n.checked_mul(2)) + .ok_or_else(|| NclCurlyError::new("display_grid dimensions overflow"))?; + if display_grid.len() != expected_display { + return Err(NclCurlyError::new("display_grid must have shape (ny, nx, 2)")); + } + let expected_cells = (ny - 1) + .checked_mul(nx - 1) + .ok_or_else(|| NclCurlyError::new("cell_valid dimensions overflow"))?; + if cell_valid.len() != expected_cells { + return Err(NclCurlyError::new( + "cell_valid must have shape (ny-1, nx-1)", + )); + } + if points.len() % 2 != 0 { + return Err(NclCurlyError::new("points must have shape (N, 2) or (2,)")); + } + + let point_count = points.len() / 2; + let mut display_points = vec![f64::NAN; point_count * 2]; + let mut valid = vec![false; point_count]; + let mut jacobians = if include_jacobian { + Some(vec![f64::NAN; point_count * 4]) + } else { + None + }; + + if point_count == 0 || ny < 2 || nx < 2 { + return Ok(SampleDisplayGridResult { + display_points, + jacobians, + valid, + }); + } + + let grid = GridInfo::new(ny, nx, x_origin, y_origin, dx, dy); + + if point_count >= PARALLEL_SAMPLE_THRESHOLD { + if let Some(ref mut jacs) = jacobians { + display_points + .par_chunks_mut(1024) + .zip(valid.par_chunks_mut(512)) + .zip(jacs.par_chunks_mut(2048)) + .enumerate() + .for_each(|(chunk_idx, ((dp_chunk, v_chunk), j_chunk))| { + let start = chunk_idx * 512; + for i in 0..v_chunk.len() { + let idx = start + i; + if let Some((dx_val, dy_val, jac)) = sample_display_point( + &grid, + display_grid, + cell_valid, + points[idx * 2], + points[idx * 2 + 1], + true, + ) { + dp_chunk[i * 2] = dx_val; + dp_chunk[i * 2 + 1] = dy_val; + j_chunk[i * 4..i * 4 + 4].copy_from_slice(&jac); + v_chunk[i] = true; + } + } + }); + } else { + display_points + .par_chunks_mut(1024) + .zip(valid.par_chunks_mut(512)) + .enumerate() + .for_each(|(chunk_idx, (dp_chunk, v_chunk))| { + let start = chunk_idx * 512; + for i in 0..v_chunk.len() { + let idx = start + i; + if let Some((dx_val, dy_val, _)) = sample_display_point( + &grid, + display_grid, + cell_valid, + points[idx * 2], + points[idx * 2 + 1], + false, + ) { + dp_chunk[i * 2] = dx_val; + dp_chunk[i * 2 + 1] = dy_val; + v_chunk[i] = true; + } + } + }); + } + } else { + for idx in 0..point_count { + if let Some((dx_val, dy_val, jac)) = sample_display_point( + &grid, + display_grid, + cell_valid, + points[idx * 2], + points[idx * 2 + 1], + include_jacobian, + ) { + display_points[idx * 2] = dx_val; + display_points[idx * 2 + 1] = dy_val; + if let Some(ref mut jacs) = jacobians { + jacs[idx * 4..idx * 4 + 4].copy_from_slice(&jac); + } + valid[idx] = true; + } + } + } + + Ok(SampleDisplayGridResult { + display_points, + jacobians, + valid, + }) +} diff --git a/rust/skybornplot-core/src/ncl_curly/mod.rs b/rust/skybornplot-core/src/ncl_curly/mod.rs new file mode 100644 index 0000000..88d798e --- /dev/null +++ b/rust/skybornplot-core/src/ncl_curly/mod.rs @@ -0,0 +1,133 @@ +//! Pure-Rust NCL-like curly-vector tracing, grid sampling, thinning, and arrow geometry kernels. + +use std::fmt; + +mod arrows; +mod grid; +mod stipple; +mod thinning; +mod trace; + +#[cfg(test)] +mod tests; + +pub use arrows::{build_filled_arrow_polygons, build_open_arrow_segments}; +pub use grid::{ + compute_display_cell_valid, sample_display_grid, sample_grid_field, sample_grid_field_array, +}; +pub use stipple::generate_cell_candidates; +pub use thinning::{thin_display_candidates, thin_mapped_candidates}; +pub use trace::{trace_ncl_direction, trace_ncl_glyphs_batch, validate_display_curve}; + +/// Error returned when an `ncl_curly` kernel receives invalid array dimensions or parameters. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NclCurlyError { + /// Human-readable description of the validation error. + pub message: String, +} + +impl NclCurlyError { + fn new(message: impl Into) -> Self { + Self { + message: message.into(), + } + } +} + +impl fmt::Display for NclCurlyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for NclCurlyError {} + +impl From<&str> for NclCurlyError { + fn from(message: &str) -> Self { + Self::new(message) + } +} + +impl From for NclCurlyError { + fn from(message: String) -> Self { + Self::new(message) + } +} + +/// Anchor mode controlling how each glyph is integrated from its seed point. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TraceAnchor { + /// Integrate both backward and forward by half the target length and stitch around the center. + Center, + /// Integrate forward only from the seed point. + Tail, + /// Integrate backward only from the seed point and reverse into flow direction. + Head, +} + +impl TraceAnchor { + /// Parse an anchor string (`"center"`, `"tail"`, or `"head"`). + pub fn parse(value: &str) -> Result { + match value { + "center" => Ok(Self::Center), + "tail" => Ok(Self::Tail), + "head" => Ok(Self::Head), + _ => Err(NclCurlyError::new(format!( + "{value:?} is not a valid value for anchor; supported values are center, tail, head" + ))), + } + } +} + +/// Result of tracing a single forward or backward curly-vector branch. +#[derive(Debug, Clone, PartialEq)] +pub struct TraceDirectionResult { + /// Flat `(N, 2)` data-space polyline coordinates `[x0, y0, x1, y1, ...]`. + pub curve: Vec, + /// Optional flat `(N, 2)` display-space polyline coordinates when `return_display` is true. + pub display_curve: Option>, +} + +/// Result of sampling mapped display positions and optional local Jacobians on a display grid. +#[derive(Debug, Clone, PartialEq)] +pub struct SampleDisplayGridResult { + /// Flat `(N, 2)` mapped display coordinates (`NaN` for invalid rows). + pub display_points: Vec, + /// Optional flat `(N, 2, 2)` local Jacobians `[j00, j01, j10, j11]` when requested. + pub jacobians: Option>, + /// Per-point validity mask of length `N`. + pub valid: Vec, +} + +/// Result of expanding selected cells into interior candidate coordinates. +#[derive(Debug, Clone, PartialEq)] +pub struct CellCandidatesResult { + /// Flat `(K, 2)` data-space candidate coordinates. + pub candidate_points: Vec, + /// Source cell index in `0..N` for each generated candidate. + pub source_positions: Vec, +} + +/// Result of building open-arrow polylines or filled-arrow triangles in display space. +#[derive(Debug, Clone, PartialEq)] +pub struct ArrowGeometryResult { + /// Flat `(K, 3, 2)` vertex coordinates `[x0, y0, x1, y1, x2, y2, ...]`. + pub vertices: Vec, + /// Source curve index in `0..n_curves` for each valid arrow. + pub source_positions: Vec, +} + +/// Result of tracing a batch of curly-vector glyphs in parallel. +#[derive(Debug, Clone, PartialEq)] +pub struct BatchTraceResult { + /// Flat packed `(total_points, 2)` data-space curve vertices across all valid glyphs. + pub data_points: Vec, + /// Flat packed `(total_points, 2)` display-space curve vertices across all valid glyphs. + pub display_points: Vec, + /// Monotonic vertex offsets of length `valid_indices.len() + 1` (starts at `0`). + pub curve_offsets: Vec, + /// Original center indices in deterministic ascending order for each valid glyph. + pub valid_indices: Vec, + /// Number of direction-tracing branch calls truncated at `max_steps` before reaching target length. + pub truncated_count: usize, +} diff --git a/rust/skybornplot-core/src/ncl_curly/stipple.rs b/rust/skybornplot-core/src/ncl_curly/stipple.rs new file mode 100644 index 0000000..059d486 --- /dev/null +++ b/rust/skybornplot-core/src/ncl_curly/stipple.rs @@ -0,0 +1,192 @@ +//! Interior cell-lattice stipple candidate generation. + +use rayon::prelude::*; + +use super::{CellCandidatesResult, NclCurlyError}; + +const PARALLEL_CELL_CANDIDATE_THRESHOLD: usize = 4096; + +#[inline] +fn cell_subdivision_counts(mapped: &[f64], spacing: f64) -> Option<(usize, usize)> { + let mut min_x = mapped[0]; + let mut max_x = mapped[0]; + let mut min_y = mapped[1]; + let mut max_y = mapped[1]; + + for corner in 0..4 { + let x = mapped[corner * 2]; + let y = mapped[corner * 2 + 1]; + if !x.is_finite() || !y.is_finite() { + return None; + } + if x < min_x { + min_x = x; + } + if x > max_x { + max_x = x; + } + if y < min_y { + min_y = y; + } + if y > max_y { + max_y = y; + } + } + + let raw_sub_x = ((max_x - min_x) / spacing).ceil(); + let raw_sub_y = ((max_y - min_y) / spacing).ceil(); + let sub_x = if !raw_sub_x.is_finite() || raw_sub_x < 1.0 { + 1 + } else if raw_sub_x > 12.0 { + 12 + } else { + raw_sub_x as usize + }; + let sub_y = if !raw_sub_y.is_finite() || raw_sub_y < 1.0 { + 1 + } else if raw_sub_y > 12.0 { + 12 + } else { + raw_sub_y as usize + }; + Some((sub_x, sub_y)) +} + +/// Expand selected scatter cells into interior stipple candidate lattices. +/// +/// `corners` and `mapped_corners` have flat shape `(N, 4, 2)` and `source_points` has shape `(N, 2)`. +pub fn generate_cell_candidates( + corners: &[f64], + mapped_corners: &[f64], + source_points: &[f64], + spacing_frac: f64, +) -> Result { + if source_points.len() % 2 != 0 { + return Err(NclCurlyError::new("source_points must have shape (N, 2)")); + } + let n_cells = source_points.len() / 2; + let expected_corners = n_cells + .checked_mul(8) + .ok_or_else(|| NclCurlyError::new("corners dimensions overflow"))?; + if corners.len() != expected_corners { + return Err(NclCurlyError::new( + "corners must have shape (N, 4, 2) matching source_points", + )); + } + if mapped_corners.len() != expected_corners { + return Err(NclCurlyError::new( + "mapped_corners must have shape (N, 4, 2) matching source_points", + )); + } + + let mut spacing = if spacing_frac.is_finite() { + spacing_frac + } else { + 0.03 + }; + if spacing < 1e-6 { + spacing = 1e-6; + } + + let mut cell_plans: Vec> = Vec::with_capacity(n_cells); + let mut total_count = 0usize; + for cell in 0..n_cells { + let mapped = &mapped_corners[cell * 8..cell * 8 + 8]; + let plan = cell_subdivision_counts(mapped, spacing); + total_count += match plan { + Some((sx, sy)) => sx * sy, + None => 1, + }; + cell_plans.push(plan); + } + + let mut candidate_points = vec![0.0; total_count * 2]; + let mut source_positions = vec![0usize; total_count]; + + let fill_cell = |cell: usize, + plan: Option<(usize, usize)>, + pts_out: &mut [f64], + pos_out: &mut [usize]| { + match plan { + None => { + pts_out[0] = source_points[cell * 2]; + pts_out[1] = source_points[cell * 2 + 1]; + pos_out[0] = cell; + } + Some((sub_x, sub_y)) => { + let corner_data = &corners[cell * 8..cell * 8 + 8]; + let mut k = 0; + for row in 0..sub_y { + let vv = (row as f64 + 0.5) / sub_y as f64; + let one_minus_v = 1.0 - vv; + for col in 0..sub_x { + let uu = (col as f64 + 0.5) / sub_x as f64; + let one_minus_u = 1.0 - uu; + let w00 = one_minus_u * one_minus_v; + let w10 = uu * one_minus_v; + let w11 = uu * vv; + let w01 = one_minus_u * vv; + pts_out[k * 2] = w00 * corner_data[0] + + w10 * corner_data[2] + + w11 * corner_data[4] + + w01 * corner_data[6]; + pts_out[k * 2 + 1] = w00 * corner_data[1] + + w10 * corner_data[3] + + w11 * corner_data[5] + + w01 * corner_data[7]; + pos_out[k] = cell; + k += 1; + } + } + } + } + }; + + if n_cells >= PARALLEL_CELL_CANDIDATE_THRESHOLD { + let mut offsets = Vec::with_capacity(n_cells + 1); + let mut acc = 0usize; + offsets.push(0); + for &plan in &cell_plans { + acc += match plan { + Some((sx, sy)) => sx * sy, + None => 1, + }; + offsets.push(acc); + } + let pts_ptr = candidate_points.as_mut_ptr() as usize; + let pos_ptr = source_positions.as_mut_ptr() as usize; + cell_plans.par_iter().enumerate().for_each(|(cell, &plan)| { + let start = offsets[cell]; + let end = offsets[cell + 1]; + let count = end - start; + // Safety: disjoint [start, end) slices per cell. + let pts_slice = unsafe { + std::slice::from_raw_parts_mut((pts_ptr as *mut f64).add(start * 2), count * 2) + }; + let pos_slice = unsafe { + std::slice::from_raw_parts_mut((pos_ptr as *mut usize).add(start), count) + }; + fill_cell(cell, plan, pts_slice, pos_slice); + }); + } else { + let mut out_pos = 0usize; + for (cell, &plan) in cell_plans.iter().enumerate() { + let count = match plan { + Some((sx, sy)) => sx * sy, + None => 1, + }; + fill_cell( + cell, + plan, + &mut candidate_points[out_pos * 2..(out_pos + count) * 2], + &mut source_positions[out_pos..out_pos + count], + ); + out_pos += count; + } + } + + Ok(CellCandidatesResult { + candidate_points, + source_positions, + }) +} diff --git a/rust/skybornplot-core/src/ncl_curly/tests.rs b/rust/skybornplot-core/src/ncl_curly/tests.rs new file mode 100644 index 0000000..e857f2f --- /dev/null +++ b/rust/skybornplot-core/src/ncl_curly/tests.rs @@ -0,0 +1,659 @@ +use super::trace::{reverse_xy_in_place, trace_step_budget}; +use super::*; + +fn make_uniform_flow_fixture( + ny: usize, + nx: usize, + u_fn: impl Fn(f64, f64) -> (f64, f64), + map_fn: impl Fn(f64, f64) -> (f64, f64), +) -> (Vec, Vec, Vec, Vec) { + let mut u = Vec::with_capacity(ny * nx); + let mut v = Vec::with_capacity(ny * nx); + let mut display_grid = Vec::with_capacity(ny * nx * 2); + for iy in 0..ny { + for ix in 0..nx { + let x = ix as f64; + let y = iy as f64; + let (ux, vy) = u_fn(x, y); + let (dx, dy) = map_fn(x, y); + u.push(ux); + v.push(vy); + display_grid.push(dx); + display_grid.push(dy); + } + } + let cell_valid = compute_display_cell_valid(&display_grid, ny, nx).unwrap(); + (u, v, display_grid, cell_valid) +} + +#[test] +fn test_sample_grid_field_and_array_parity() { + let ny = 4; + let nx = 5; + let mut field = vec![0.0; ny * nx]; + for iy in 0..ny { + for ix in 0..nx { + field[iy * nx + ix] = (ix as f64) * 2.0 + (iy as f64) * 10.0; + } + } + field[2 * nx + 3] = f64::NAN; + + // Interior point: (1.5, 0.5) => x=1.5*2 + y=0.5*10 = 8.0 + let s = sample_grid_field(&field, ny, nx, 0.0, 0.0, 1.0, 1.0, 1.5, 0.5).unwrap(); + assert!((s.unwrap() - 8.0).abs() < 1e-12); + + // Right-top boundary point: (4.0, 3.0) => 4*2 + 3*10 = 38.0 + let edge = sample_grid_field(&field, ny, nx, 0.0, 0.0, 1.0, 1.0, 4.0, 3.0).unwrap(); + assert!((edge.unwrap() - 38.0).abs() < 1e-12); + + // Out of bounds and NaN-touching cell + assert!(sample_grid_field(&field, ny, nx, 0.0, 0.0, 1.0, 1.0, -0.1, 0.5) + .unwrap() + .is_none()); + assert!(sample_grid_field(&field, ny, nx, 0.0, 0.0, 1.0, 1.0, 2.5, 1.5) + .unwrap() + .is_none()); + + // Large batch exercises Rayon parallel path and matches scalar calls + let mut pts = Vec::with_capacity(2500 * 2); + for i in 0..2500 { + let t = i as f64 / 2499.0; + pts.push(-0.2 + t * 4.4); + pts.push(-0.2 + t * 3.4); + } + let arr = sample_grid_field_array(&field, ny, nx, 0.0, 0.0, 1.0, 1.0, &pts).unwrap(); + assert_eq!(arr.len(), 2500); + for i in 0..2500 { + let expected = + sample_grid_field(&field, ny, nx, 0.0, 0.0, 1.0, 1.0, pts[i * 2], pts[i * 2 + 1]) + .unwrap(); + match expected { + Some(val) => assert!((arr[i] - val).abs() < 1e-14), + None => assert!(arr[i].is_nan()), + } + } +} + +#[test] +fn test_compute_display_cell_valid_seam_and_nan() { + let ny = 4; + let nx = 5; + let mut display_grid = Vec::with_capacity(ny * nx * 2); + for iy in 0..ny { + for ix in 0..nx { + // Inject a huge antimeridian seam jump at ix >= 3 + let px = if ix >= 3 { + (ix as f64) * 10.0 + 500.0 + } else { + (ix as f64) * 10.0 + }; + let py = (iy as f64) * 10.0; + display_grid.push(px); + display_grid.push(py); + } + } + // Inject a NaN at (iy=0, ix=0) + display_grid[0] = f64::NAN; + + let valid = compute_display_cell_valid(&display_grid, ny, nx).unwrap(); + assert_eq!(valid.len(), (ny - 1) * (nx - 1)); + // (0, 0) touches NaN + assert!(!valid[0]); + // (1, 0) is clean + assert!(valid[1 * (nx - 1)]); + // (iy, 2) spans ix=2 -> ix=3 seam jump + for iy in 0..(ny - 1) { + assert!(!valid[iy * (nx - 1) + 2]); + assert!(valid[iy * (nx - 1) + 3]); + } +} + +#[test] +fn test_sample_display_grid_jacobian_and_parallel() { + let ny = 4; + let nx = 4; + let mut display_grid = Vec::with_capacity(ny * nx * 2); + for iy in 0..ny { + for ix in 0..nx { + // Linear affine map: dx = 100 + 20*x + 5*y, dy = 50 - 3*x + 15*y + let x = ix as f64 * 2.0; + let y = iy as f64 * 3.0; + display_grid.push(100.0 + 20.0 * x + 5.0 * y); + display_grid.push(50.0 - 3.0 * x + 15.0 * y); + } + } + let cell_valid = compute_display_cell_valid(&display_grid, ny, nx).unwrap(); + + let mut pts = Vec::with_capacity(2200 * 2); + for i in 0..2200 { + let f = i as f64 / 2199.0; + pts.push(0.5 + f * 5.0); + pts.push(0.5 + f * 8.0); + } + pts[0] = -1.0; // out of bounds + + let res = sample_display_grid( + &display_grid, + ny, + nx, + &cell_valid, + 0.0, + 0.0, + 2.0, + 3.0, + &pts, + true, + ) + .unwrap(); + assert!(!res.valid[0]); + assert!(res.display_points[0].is_nan()); + let jacs = res.jacobians.as_ref().unwrap(); + assert!(jacs[0].is_nan()); + + for i in 1..2200 { + assert!(res.valid[i]); + let x = pts[i * 2]; + let y = pts[i * 2 + 1]; + assert!((res.display_points[i * 2] - (100.0 + 20.0 * x + 5.0 * y)).abs() < 1e-11); + assert!((res.display_points[i * 2 + 1] - (50.0 - 3.0 * x + 15.0 * y)).abs() < 1e-11); + assert!((jacs[i * 4] - 20.0).abs() < 1e-11); + assert!((jacs[i * 4 + 1] - 5.0).abs() < 1e-11); + assert!((jacs[i * 4 + 2] - (-3.0)).abs() < 1e-11); + assert!((jacs[i * 4 + 3] - 15.0).abs() < 1e-11); + } +} + +#[test] +fn test_thin_candidates_exact_scan_order_parity() { + // Deterministic pseudo-random cloud plus NaNs and exact duplicates + let mut pts = Vec::new(); + let mut seed: u64 = 0x1234_5678_9ABC_DEF0; + for i in 0..500 { + if i == 7 || i == 111 { + pts.push(f64::NAN); + pts.push(0.5); + continue; + } + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); + let x = ((seed >> 33) as f64) / ((1u64 << 31) as f64); + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); + let y = ((seed >> 33) as f64) / ((1u64 << 31) as f64); + pts.push(x); + pts.push(y); + } + + let spacing = 0.08; + let selected = thin_mapped_candidates(&pts, spacing).unwrap(); + + // Brute-force O(N^2) reference oracle in exact scan order + let n = pts.len() / 2; + let mut culled = vec![false; n]; + let mut oracle = Vec::new(); + let spacing_sq = spacing * spacing; + for i in 0..n { + if culled[i] || !pts[i * 2].is_finite() || !pts[i * 2 + 1].is_finite() { + continue; + } + oracle.push(i); + for j in (i + 1)..n { + if culled[j] || !pts[j * 2].is_finite() || !pts[j * 2 + 1].is_finite() { + continue; + } + let dx = pts[i * 2] - pts[j * 2]; + let dy = pts[i * 2 + 1] - pts[j * 2 + 1]; + if dx * dx + dy * dy < spacing_sq { + culled[j] = true; + } + } + } + assert_eq!(selected, oracle); + + // Verify thin_display_candidates viewport normalization matches thin_mapped_candidates + let disp: Vec = pts + .chunks_exact(2) + .flat_map(|p| [10.0 + p[0] * 200.0, 20.0 + p[1] * 100.0]) + .collect(); + let selected_disp = + thin_display_candidates(&disp, 10.0, 20.0, 200.0, 100.0, spacing).unwrap(); + assert_eq!(selected_disp, oracle); +} + +#[test] +fn test_generate_cell_candidates_parity() { + let corners = vec![ + 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, // cell 0 + 2.0, 0.0, 3.0, 0.0, 3.0, 1.0, 2.0, 1.0, // cell 1 (invalid mapped) + ]; + let mapped_corners = vec![ + 0.0, 0.0, 0.05, 0.0, 0.05, 0.02, 0.0, 0.02, // ceil(0.05/0.03)=2, ceil(0.02/0.03)=1 + 0.1, 0.0, f64::NAN, 0.0, 0.2, 0.1, 0.1, 0.1, // invalid corner + ]; + let source_points = vec![0.5, 0.5, 2.5, 0.5]; + let res = generate_cell_candidates(&corners, &mapped_corners, &source_points, 0.03).unwrap(); + assert_eq!(res.source_positions, vec![0, 0, 1]); + assert!((res.candidate_points[0] - 0.25).abs() < 1e-12); + assert!((res.candidate_points[1] - 0.5).abs() < 1e-12); + assert!((res.candidate_points[2] - 0.75).abs() < 1e-12); + assert!((res.candidate_points[3] - 0.5).abs() < 1e-12); + assert!((res.candidate_points[4] - 2.5).abs() < 1e-12); + assert!((res.candidate_points[5] - 0.5).abs() < 1e-12); +} + +#[test] +fn test_validate_display_curve_thresholds() { + // Straight horizontal line + let straight = vec![0.0, 0.0, 10.0, 0.0, 20.0, 0.0]; + assert!(validate_display_curve(&straight, 100.0, 100.0).unwrap()); + + // Jump exceeding 0.35 * viewport_diag + let jumped = vec![0.0, 0.0, 60.0, 0.0]; + assert!(!validate_display_curve(&jumped, 100.0, 100.0).unwrap()); + + // Sharp turn > 52 degrees + let sharp = vec![0.0, 0.0, 10.0, 0.0, 10.0, 10.0]; + assert!(!validate_display_curve(&sharp, 500.0, 500.0).unwrap()); + + // S-curve with sign change and total_turn > 70 deg + let s_curve = vec![ + 0.0, 0.0, 10.0, 0.0, 17.0, 7.0, 27.0, 7.0, + ]; + assert!(!validate_display_curve(&s_curve, 500.0, 500.0).unwrap()); +} + +#[test] +fn test_arrow_geometry_builders() { + let display_points = vec![ + 0.0, 0.0, 10.0, 0.0, 20.0, 0.0, // curve 0: horizontal right + 0.0, 0.0, // curve 1: too short (1 point) + 5.0, 5.0, 5.0, 15.0, // curve 2: vertical up + ]; + let curve_offsets = vec![0, 3, 4, 6]; + let head_lengths = vec![4.0, 4.0, 6.0]; + let head_widths = vec![2.0, 2.0, 4.0]; + + let open = build_open_arrow_segments( + &display_points, + &curve_offsets, + &head_lengths, + &head_widths, + ) + .unwrap(); + assert_eq!(open.source_positions, vec![0, 2]); + // Curve 0 open head: base at (16, 0), normal=(0, 1) -> left=(16, 1), tip=(20, 0), right=(16, -1) + assert!((open.vertices[0] - 16.0).abs() < 1e-12); + assert!((open.vertices[1] - 1.0).abs() < 1e-12); + assert!((open.vertices[2] - 20.0).abs() < 1e-12); + assert!((open.vertices[3] - 0.0).abs() < 1e-12); + assert!((open.vertices[4] - 16.0).abs() < 1e-12); + assert!((open.vertices[5] - (-1.0)).abs() < 1e-12); + + let filled = build_filled_arrow_polygons( + &display_points, + &curve_offsets, + &head_lengths, + &head_widths, + ) + .unwrap(); + assert_eq!(filled.source_positions, vec![0, 2]); + // Curve 0 filled head: tip=(20, 0), left=(16, 1), right=(16, -1) + assert!((filled.vertices[0] - 20.0).abs() < 1e-12); + assert!((filled.vertices[1] - 0.0).abs() < 1e-12); + assert!((filled.vertices[2] - 16.0).abs() < 1e-12); + assert!((filled.vertices[3] - 1.0).abs() < 1e-12); + assert!((filled.vertices[4] - 16.0).abs() < 1e-12); + assert!((filled.vertices[5] - (-1.0)).abs() < 1e-12); +} + +#[test] +fn test_trace_ncl_direction_and_batch_parity() { + let ny = 15; + let nx = 15; + // Rotational vortex around (7, 7) mapped to display [0..1400, 0..1400] + let (u, v, display_grid, cell_valid) = make_uniform_flow_fixture( + ny, + nx, + |x, y| (-(y - 7.0), x - 7.0), + |x, y| (x * 100.0, y * 100.0), + ); + + let single = trace_ncl_direction( + &u, + &v, + &display_grid, + &cell_valid, + ny, + nx, + 0.0, + 0.0, + 1.0, + 1.0, + 7.0, + 3.0, + 30.0, + 1.0, + 3.0, + 10.0, + 0.0, + 0.0, + 1400.0, + 1400.0, + 512, + true, + ) + .unwrap() + .unwrap(); + let n_pts = single.curve.len() / 2; + assert!(n_pts >= 4); + assert_eq!(single.display_curve.as_ref().unwrap().len(), single.curve.len()); + + // Batch trace 16 centers across all three anchor modes and verify exact match with sequential single-branch calls + let mut centers = Vec::new(); + let mut lengths = Vec::new(); + for iy in 2..6 { + for ix in 2..6 { + centers.push(ix as f64 * 2.0); + centers.push(iy as f64 * 2.0); + lengths.push(28.0); + } + } + // Add one out-of-bounds center to verify valid_indices preserves alignment + centers.push(99.0); + centers.push(99.0); + lengths.push(28.0); + + for anchor in [TraceAnchor::Center, TraceAnchor::Tail, TraceAnchor::Head] { + let batch = trace_ncl_glyphs_batch( + &u, + &v, + &display_grid, + &cell_valid, + ny, + nx, + 0.0, + 0.0, + 1.0, + 1.0, + ¢ers, + &lengths, + anchor, + 3.0, + 10.0, + 0.0, + 0.0, + 1400.0, + 1400.0, + ) + .unwrap(); + + assert!(!batch.valid_indices.is_empty()); + assert!(!batch.valid_indices.contains(&16)); + assert_eq!(batch.curve_offsets.len(), batch.valid_indices.len() + 1); + assert_eq!( + *batch.curve_offsets.last().unwrap() * 2, + batch.data_points.len() + ); + assert_eq!(batch.display_points.len(), batch.data_points.len()); + + // Check exact stitch parity against trace_ncl_direction for the first valid glyph + let first_idx = batch.valid_indices[0]; + let sx = centers[first_idx * 2]; + let sy = centers[first_idx * 2 + 1]; + let start = batch.curve_offsets[0] * 2; + let end = batch.curve_offsets[1] * 2; + let got_curve = &batch.data_points[start..end]; + + match anchor { + TraceAnchor::Tail => { + let fwd = trace_ncl_direction( + &u, + &v, + &display_grid, + &cell_valid, + ny, + nx, + 0.0, + 0.0, + 1.0, + 1.0, + sx, + sy, + lengths[first_idx], + 1.0, + 3.0, + 10.0, + 0.0, + 0.0, + 1400.0, + 1400.0, + trace_step_budget(lengths[first_idx]), + true, + ) + .unwrap() + .unwrap(); + assert_eq!(got_curve, fwd.curve.as_slice()); + } + TraceAnchor::Head => { + let mut bwd = trace_ncl_direction( + &u, + &v, + &display_grid, + &cell_valid, + ny, + nx, + 0.0, + 0.0, + 1.0, + 1.0, + sx, + sy, + lengths[first_idx], + -1.0, + 3.0, + 10.0, + 0.0, + 0.0, + 1400.0, + 1400.0, + trace_step_budget(lengths[first_idx]), + true, + ) + .unwrap() + .unwrap(); + reverse_xy_in_place(&mut bwd.curve); + assert_eq!(got_curve, bwd.curve.as_slice()); + } + TraceAnchor::Center => { + // Seed center point must appear along the stitched curve + let has_seed = got_curve + .chunks_exact(2) + .any(|p| (p[0] - sx).abs() < 1e-12 && (p[1] - sy).abs() < 1e-12); + assert!(has_seed); + } + } + } +} + +#[test] +fn test_trace_ncl_glyphs_batch_truncation_count() { + let ny = 10; + let nx = 10; + let (u, v, display_grid, cell_valid) = make_uniform_flow_fixture( + ny, + nx, + |_x, _y| (1.0, 0.0), + |x, y| (x * 1000.0, y * 1000.0), + ); + // With 1/3 backward correction, steady-state net step is ~(2/3)*step_px. + // Using step_px=0.36 gives net step ~0.24 > 0.2, so 4096 steps reach ~983 px < 2000.0. + let batch = trace_ncl_glyphs_batch( + &u, + &v, + &display_grid, + &cell_valid, + ny, + nx, + 0.0, + 0.0, + 1.0, + 1.0, + &[0.5, 4.5], + &[2000.0], + TraceAnchor::Tail, + 0.36, + 1.0, + 0.0, + 0.0, + 9000.0, + 9000.0, + ) + .unwrap(); + assert!(batch.truncated_count >= 1); + assert_eq!(batch.valid_indices, vec![0]); + assert_eq!(batch.curve_offsets[1], 4097); +} + +#[test] +fn test_trace_viewport_clipping_and_edge_cases() { + let ny = 6; + let nx = 6; + let (u, v, display_grid, cell_valid) = make_uniform_flow_fixture( + ny, + nx, + |_x, _y| (1.0, 0.0), + |x, y| (x * 100.0, y * 100.0), + ); + // Viewport right boundary at x=250.0, starting at x=2.0 (display 200.0) + let clipped = trace_ncl_direction( + &u, + &v, + &display_grid, + &cell_valid, + ny, + nx, + 0.0, + 0.0, + 1.0, + 1.0, + 2.0, + 2.0, + 200.0, + 1.0, + 20.0, + 1.0, + 0.0, + 0.0, + 250.0, + 500.0, + 512, + true, + ) + .unwrap() + .unwrap(); + let disp = clipped.display_curve.unwrap(); + let last_x = disp[disp.len() - 2]; + assert!((last_x - 250.0).abs() < 1e-11); + + // 1xN grid returns None gracefully + let tiny = trace_ncl_direction( + &[1.0, 1.0], + &[0.0, 0.0], + &[0.0, 0.0, 1.0, 0.0], + &[], + 1, + 2, + 0.0, + 0.0, + 1.0, + 1.0, + 0.5, + 0.0, + 10.0, + 1.0, + 2.0, + 1.0, + 0.0, + 0.0, + 10.0, + 10.0, + 64, + false, + ) + .unwrap(); + assert!(tiny.is_none()); +} + +#[test] +fn test_parallel_thresholds_thin_cells_valid_and_arrows() { + // 1) compute_display_cell_valid above PARALLEL_CELL_VALID_THRESHOLD (70x70 = 4761 cells) + let ny = 70; + let nx = 70; + let mut display_grid = Vec::with_capacity(ny * nx * 2); + for iy in 0..ny { + for ix in 0..nx { + display_grid.push(ix as f64 * 5.0); + display_grid.push(iy as f64 * 5.0); + } + } + let valid = compute_display_cell_valid(&display_grid, ny, nx).unwrap(); + assert_eq!(valid.len(), (ny - 1) * (nx - 1)); + assert!(valid.iter().all(|&v| v)); + + // 2) thin_mapped_candidates above PARALLEL_THIN_THRESHOLD (17000 points) + let n_thin = 17_000usize; + let mut pts = Vec::with_capacity(n_thin * 2); + let mut seed: u64 = 0xCAFE_BABE_1234_5678; + for _ in 0..n_thin { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); + let x = ((seed >> 33) as f64) / ((1u64 << 31) as f64); + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); + let y = ((seed >> 33) as f64) / ((1u64 << 31) as f64); + pts.push(x); + pts.push(y); + } + let selected = thin_mapped_candidates(&pts, 0.04).unwrap(); + assert!(!selected.is_empty()); + // Verify all selected pairs respect spacing >= 0.04 and remain strictly increasing + for w in selected.windows(2) { + assert!(w[0] < w[1]); + } + for i in 0..selected.len().min(200) { + for j in (i + 1)..selected.len().min(200) { + let a = selected[i]; + let b = selected[j]; + let dx = pts[a * 2] - pts[b * 2]; + let dy = pts[a * 2 + 1] - pts[b * 2 + 1]; + assert!(dx * dx + dy * dy >= 0.04 * 0.04 - 1e-15); + } + } + + // 3) generate_cell_candidates above PARALLEL_CELL_CANDIDATE_THRESHOLD (4200 cells) + let n_cells = 4200usize; + let mut corners = Vec::with_capacity(n_cells * 8); + let mut mapped_corners = Vec::with_capacity(n_cells * 8); + let mut source_points = Vec::with_capacity(n_cells * 2); + for c in 0..n_cells { + let x0 = c as f64; + corners.extend_from_slice(&[x0, 0.0, x0 + 1.0, 0.0, x0 + 1.0, 1.0, x0, 1.0]); + mapped_corners.extend_from_slice(&[0.0, 0.0, 0.04, 0.0, 0.04, 0.02, 0.0, 0.02]); + source_points.extend_from_slice(&[x0 + 0.5, 0.5]); + } + let cand = generate_cell_candidates(&corners, &mapped_corners, &source_points, 0.03).unwrap(); + assert_eq!(cand.source_positions.len(), n_cells * 2); + assert_eq!(cand.candidate_points.len(), n_cells * 4); + + // 4) build_open_arrow_segments & build_filled_arrow_polygons above PARALLEL_ARROW_THRESHOLD (600 curves) + let n_curves = 600usize; + let mut curve_pts = Vec::with_capacity(n_curves * 4); + let mut offsets = Vec::with_capacity(n_curves + 1); + offsets.push(0); + for c in 0..n_curves { + curve_pts.extend_from_slice(&[0.0, c as f64, 10.0, c as f64]); + offsets.push((c + 1) * 2); + } + let hl = vec![4.0; n_curves]; + let hw = vec![2.0; n_curves]; + let open = build_open_arrow_segments(&curve_pts, &offsets, &hl, &hw).unwrap(); + let filled = build_filled_arrow_polygons(&curve_pts, &offsets, &hl, &hw).unwrap(); + assert_eq!(open.source_positions.len(), n_curves); + assert_eq!(filled.source_positions.len(), n_curves); +} diff --git a/rust/skybornplot-core/src/ncl_curly/thinning.rs b/rust/skybornplot-core/src/ncl_curly/thinning.rs new file mode 100644 index 0000000..3b933e6 --- /dev/null +++ b/rust/skybornplot-core/src/ncl_curly/thinning.rs @@ -0,0 +1,282 @@ +//! Spatial-hash candidate thinning in scan order. + +use rayon::prelude::*; + +use super::NclCurlyError; + +const PARALLEL_THIN_THRESHOLD: usize = 16384; + +#[derive(Clone, Copy)] +struct BucketEntry { + bx: i64, + by: i64, + idx: usize, +} + +#[derive(Clone, Copy)] +struct BucketSpan { + bx: i64, + by: i64, + start: usize, + end: usize, +} + +#[inline] +fn clamp_f64_to_i64(value: f64) -> i64 { + const MIN_VAL: f64 = -9223372036854774784.0; + const MAX_VAL: f64 = 9223372036854774784.0; + if !value.is_finite() { + 0 + } else if value < MIN_VAL { + i64::MIN + 2 + } else if value > MAX_VAL { + i64::MAX - 2 + } else { + value as i64 + } +} + +#[inline] +fn hash_bucket_coords(bx: i64, by: i64) -> usize { + let mut h = (bx as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) + ^ (by as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9); + h ^= h >> 30; + h = h.wrapping_mul(0xBF58_476D_1CE4_E5B9); + h ^= h >> 27; + h as usize +} + +fn thin_scaled_points( + points: &[f64], + origin_x: f64, + origin_y: f64, + inv_width: f64, + inv_height: f64, + spacing_frac: f64, +) -> Vec { + let point_count = points.len() / 2; + if point_count == 0 { + return Vec::new(); + } + + let spacing_frac = spacing_frac.max(1e-6); + let spacing_sq = spacing_frac * spacing_frac; + let bucket_scale = 1.0 / spacing_frac; + let bucket_scale_x = inv_width * bucket_scale; + let bucket_scale_y = inv_height * bucket_scale; + + let origin_scales_finite = origin_x.is_finite() + && origin_y.is_finite() + && bucket_scale_x.is_finite() + && bucket_scale_y.is_finite(); + if !origin_scales_finite { + return Vec::new(); + } + + let mut culled = vec![false; point_count]; + let mut entries = vec![ + BucketEntry { + bx: 0, + by: 0, + idx: 0, + }; + point_count + ]; + + const CHUNK_PTS: usize = 2048; + if point_count >= PARALLEL_THIN_THRESHOLD { + entries + .par_chunks_mut(CHUNK_PTS) + .zip(culled.par_chunks_mut(CHUNK_PTS)) + .zip(points.par_chunks(CHUNK_PTS * 2)) + .enumerate() + .for_each(|(chunk_idx, ((e_chunk, c_chunk), p_chunk))| { + let base_idx = chunk_idx * CHUNK_PTS; + for i in 0..e_chunk.len() { + let px = p_chunk[i * 2]; + let py = p_chunk[i * 2 + 1]; + let idx = base_idx + i; + if !px.is_finite() || !py.is_finite() { + c_chunk[i] = true; + e_chunk[i] = BucketEntry { + bx: 0, + by: 0, + idx, + }; + } else { + e_chunk[i] = BucketEntry { + bx: clamp_f64_to_i64(((px - origin_x) * bucket_scale_x).floor()), + by: clamp_f64_to_i64(((py - origin_y) * bucket_scale_y).floor()), + idx, + }; + } + } + }); + } else { + for idx in 0..point_count { + let px = points[idx * 2]; + let py = points[idx * 2 + 1]; + if !px.is_finite() || !py.is_finite() { + culled[idx] = true; + entries[idx] = BucketEntry { + bx: 0, + by: 0, + idx, + }; + } else { + entries[idx] = BucketEntry { + bx: clamp_f64_to_i64(((px - origin_x) * bucket_scale_x).floor()), + by: clamp_f64_to_i64(((py - origin_y) * bucket_scale_y).floor()), + idx, + }; + } + } + } + + let cmp_entry = |a: &BucketEntry, b: &BucketEntry| { + a.bx.cmp(&b.bx) + .then_with(|| a.by.cmp(&b.by)) + .then_with(|| a.idx.cmp(&b.idx)) + }; + if entries.len() >= PARALLEL_THIN_THRESHOLD { + entries.par_sort_unstable_by(cmp_entry); + } else { + entries.sort_unstable_by(cmp_entry); + } + + let mut buckets: Vec = Vec::new(); + let mut run_start = 0; + while run_start < entries.len() { + let bx = entries[run_start].bx; + let by = entries[run_start].by; + let mut run_end = run_start + 1; + while run_end < entries.len() && entries[run_end].bx == bx && entries[run_end].by == by { + run_end += 1; + } + buckets.push(BucketSpan { + bx, + by, + start: run_start, + end: run_end, + }); + run_start = run_end; + } + + let table_cap = (buckets.len() * 2).max(16).next_power_of_two(); + let table_mask = table_cap - 1; + let mut table = vec![usize::MAX; table_cap]; + for (b_idx, span) in buckets.iter().enumerate() { + let mut slot = hash_bucket_coords(span.bx, span.by) & table_mask; + while table[slot] != usize::MAX { + slot = (slot + 1) & table_mask; + } + table[slot] = b_idx; + } + + let mut selected_indices = Vec::new(); + for idx in 0..point_count { + if culled[idx] { + continue; + } + + let base_x = points[idx * 2]; + let base_y = points[idx * 2 + 1]; + let bx = clamp_f64_to_i64(((base_x - origin_x) * bucket_scale_x).floor()); + let by = clamp_f64_to_i64(((base_y - origin_y) * bucket_scale_y).floor()); + + selected_indices.push(idx); + + for search_x in (bx - 1)..=(bx + 1) { + for search_y in (by - 1)..=(by + 1) { + let mut slot = hash_bucket_coords(search_x, search_y) & table_mask; + let mut found_bucket = usize::MAX; + loop { + let b_idx = table[slot]; + if b_idx == usize::MAX { + break; + } + let span = &buckets[b_idx]; + if span.bx == search_x && span.by == search_y { + found_bucket = b_idx; + break; + } + slot = (slot + 1) & table_mask; + } + if found_bucket == usize::MAX { + continue; + } + + let span = &mut buckets[found_bucket]; + while span.start < span.end + && (entries[span.start].idx <= idx || culled[entries[span.start].idx]) + { + span.start += 1; + } + + for entry in &entries[span.start..span.end] { + let other_idx = entry.idx; + if other_idx <= idx || culled[other_idx] { + continue; + } + let dx_value = (base_x - points[other_idx * 2]) * inv_width; + let dy_value = (base_y - points[other_idx * 2 + 1]) * inv_height; + if dx_value * dx_value + dy_value * dy_value < spacing_sq { + culled[other_idx] = true; + } + } + } + } + } + + selected_indices +} + +/// Thin already-normalized `(N, 2)` viewport candidates in scan order using a spacing lattice. +pub fn thin_mapped_candidates( + mapped_points: &[f64], + spacing_frac: f64, +) -> Result, NclCurlyError> { + if mapped_points.len() % 2 != 0 { + return Err(NclCurlyError::new("mapped_points must have shape (N, 2)")); + } + Ok(thin_scaled_points( + mapped_points, + 0.0, + 0.0, + 1.0, + 1.0, + spacing_frac, + )) +} + +/// Thin display/pixel `(N, 2)` candidates in scan order after normalizing by the active viewport. +pub fn thin_display_candidates( + display_points: &[f64], + viewport_x0: f64, + viewport_y0: f64, + viewport_width: f64, + viewport_height: f64, + spacing_frac: f64, +) -> Result, NclCurlyError> { + if display_points.len() % 2 != 0 { + return Err(NclCurlyError::new("display_points must have shape (N, 2)")); + } + let width = if viewport_width > 1.0 { + viewport_width + } else { + 1.0 + }; + let height = if viewport_height > 1.0 { + viewport_height + } else { + 1.0 + }; + Ok(thin_scaled_points( + display_points, + viewport_x0, + viewport_y0, + 1.0 / width, + 1.0 / height, + spacing_frac, + )) +} diff --git a/rust/skybornplot-core/src/ncl_curly/trace.rs b/rust/skybornplot-core/src/ncl_curly/trace.rs new file mode 100644 index 0000000..70f3e8b --- /dev/null +++ b/rust/skybornplot-core/src/ncl_curly/trace.rs @@ -0,0 +1,929 @@ +//! Curly-vector streamline integration, curve validation, and parallel batch tracing. + +use rayon::prelude::*; + +use super::grid::{sample_state, GridInfo}; +use super::{BatchTraceResult, NclCurlyError, TraceAnchor, TraceDirectionResult}; + +const PARALLEL_BATCH_TRACE_THRESHOLD: usize = 8; + +const MIN_ACCEPTED_TRACE_STEP_PX: f64 = 0.2; +const MAX_NATIVE_TRACE_STEPS: usize = 4096; + +#[inline] +fn display_step_to_data( + j00: f64, + j01: f64, + j10: f64, + j11: f64, + step_x: f64, + step_y: f64, +) -> Option<(f64, f64)> { + let det = j00 * j11 - j01 * j10; + if !det.is_finite() || det.abs() <= 1e-12 { + return None; + } + let data_x = (j11 * step_x - j01 * step_y) / det; + let data_y = (-j10 * step_x + j00 * step_y) / det; + if data_x.is_finite() && data_y.is_finite() { + Some((data_x, data_y)) + } else { + None + } +} + +#[inline] +fn ncl_step_length_px(base_step_px: f64, _local_speed: f64, _speed_scale: f64) -> f64 { + base_step_px +} + +#[inline] +fn viewport_contains(x0: f64, y0: f64, x1: f64, y1: f64, x: f64, y: f64) -> bool { + x.is_finite() && y.is_finite() && x0 <= x && x <= x1 && y0 <= y && y <= y1 +} + +#[inline] +#[allow(clippy::too_many_arguments)] +fn clip_display_step_to_viewport( + start_x: f64, + start_y: f64, + end_x: &mut f64, + end_y: &mut f64, + viewport_x0: f64, + viewport_y0: f64, + viewport_x1: f64, + viewport_y1: f64, +) -> bool { + if viewport_contains( + viewport_x0, + viewport_y0, + viewport_x1, + viewport_y1, + *end_x, + *end_y, + ) { + return false; + } + + let delta_x = *end_x - start_x; + let delta_y = *end_y - start_y; + if !delta_x.is_finite() || !delta_y.is_finite() { + *end_x = start_x; + *end_y = start_y; + return true; + } + + let mut factor = 1.0; + if delta_x < -1e-12 { + let candidate = (viewport_x0 - start_x) / delta_x; + if candidate < factor { + factor = candidate; + } + } else if delta_x > 1e-12 { + let candidate = (viewport_x1 - start_x) / delta_x; + if candidate < factor { + factor = candidate; + } + } + + if delta_y < -1e-12 { + let candidate = (viewport_y0 - start_y) / delta_y; + if candidate < factor { + factor = candidate; + } + } else if delta_y > 1e-12 { + let candidate = (viewport_y1 - start_y) / delta_y; + if candidate < factor { + factor = candidate; + } + } + + factor = factor.clamp(0.0, 1.0); + *end_x = start_x + delta_x * factor; + *end_y = start_y + delta_y * factor; + true +} + +struct ProposedStep { + candidate_x: f64, + candidate_y: f64, + candidate_display_x: f64, + candidate_display_y: f64, + clipped: bool, +} + +#[inline] +#[allow(clippy::too_many_arguments)] +fn propose_trace_step( + grid: &GridInfo, + current_data_x: f64, + current_data_y: f64, + current_display_x: f64, + current_display_y: f64, + corrected_display_x: f64, + corrected_display_y: f64, + step_dir_x: f64, + step_dir_y: f64, + step_length: f64, + remaining: f64, + j00: f64, + j01: f64, + j10: f64, + j11: f64, + viewport_x0: f64, + viewport_y0: f64, + viewport_x1: f64, + viewport_y1: f64, +) -> Option { + let mut candidate_display_x = corrected_display_x + step_dir_x * step_length; + let mut candidate_display_y = corrected_display_y + step_dir_y * step_length; + let clipped = clip_display_step_to_viewport( + corrected_display_x, + corrected_display_y, + &mut candidate_display_x, + &mut candidate_display_y, + viewport_x0, + viewport_y0, + viewport_x1, + viewport_y1, + ); + + let mut display_step_x = candidate_display_x - current_display_x; + let mut display_step_y = candidate_display_y - current_display_y; + if display_step_x * step_dir_x + display_step_y * step_dir_y <= 0.0 { + return None; + } + + let net_step = display_step_x.hypot(display_step_y); + if !net_step.is_finite() { + return None; + } + if net_step > remaining && net_step > 1e-12 { + let scale = remaining / net_step; + display_step_x *= scale; + display_step_y *= scale; + candidate_display_x = current_display_x + display_step_x; + candidate_display_y = current_display_y + display_step_y; + } + + let (data_step_x, data_step_y) = + display_step_to_data(j00, j01, j10, j11, display_step_x, display_step_y)?; + let candidate_x = current_data_x + data_step_x; + let candidate_y = current_data_y + data_step_y; + if !candidate_x.is_finite() + || !candidate_y.is_finite() + || !grid.contains_data(candidate_x, candidate_y) + { + return None; + } + + Some(ProposedStep { + candidate_x, + candidate_y, + candidate_display_x, + candidate_display_y, + clipped, + }) +} + +struct TraceBranchOutput { + curve: Vec, + display_curve: Option>, + truncated: bool, +} + +#[allow(clippy::too_many_arguments)] +fn trace_ncl_direction_core( + grid: &GridInfo, + u_data: &[f64], + v_data: &[f64], + display_data: &[f64], + cell_valid_data: &[bool], + start_x: f64, + start_y: f64, + max_length_px: f64, + direction_sign: f64, + step_px: f64, + speed_scale: f64, + viewport_x0: f64, + viewport_y0: f64, + viewport_x1: f64, + viewport_y1: f64, + max_steps: usize, + return_display: bool, +) -> Option { + if grid.ny < 2 || grid.nx < 2 { + return None; + } + + let max_steps = max_steps.clamp(1, MAX_NATIVE_TRACE_STEPS); + let initial_state = sample_state( + grid, + u_data, + v_data, + display_data, + cell_valid_data, + start_x, + start_y, + )?; + + if !max_length_px.is_finite() || max_length_px <= 1e-6 { + return None; + } + + let initial_cap = (max_steps + 1).min(64) * 2; + let mut curve = Vec::with_capacity(initial_cap); + curve.push(start_x); + curve.push(start_y); + + let mut display_curve = if return_display { + let mut buf = Vec::with_capacity(initial_cap); + buf.push(initial_state.display_x); + buf.push(initial_state.display_y); + Some(buf) + } else { + None + }; + + let mut current_data_x = start_x; + let mut current_data_y = start_y; + let mut previous_display_x = 0.0; + let mut previous_display_y = 0.0; + let mut has_previous_display = false; + let mut travelled = 0.0; + + for step_index in 0..max_steps { + let remaining = max_length_px - travelled; + if !remaining.is_finite() || remaining <= 1e-6 { + break; + } + + let state = if step_index == 0 { + initial_state + } else { + match sample_state( + grid, + u_data, + v_data, + display_data, + cell_valid_data, + current_data_x, + current_data_y, + ) { + Some(s) => s, + None => break, + } + }; + + let current_display_x = state.display_x; + let current_display_y = state.display_y; + let (corrected_display_x, corrected_display_y, back_len) = if has_previous_display { + let cx = current_display_x - (current_display_x - previous_display_x) / 3.0; + let cy = current_display_y - (current_display_y - previous_display_y) / 3.0; + let bl = (current_display_x - cx).hypot(current_display_y - cy); + (cx, cy, bl) + } else { + (current_display_x, current_display_y, 0.0) + }; + + let mut step_length = ncl_step_length_px(step_px, state.speed, speed_scale); + if step_length > remaining + back_len { + step_length = remaining + back_len; + } + if step_length <= 1e-6 { + break; + } + + let mut chosen = match propose_trace_step( + grid, + current_data_x, + current_data_y, + current_display_x, + current_display_y, + corrected_display_x, + corrected_display_y, + direction_sign * state.dir_x, + direction_sign * state.dir_y, + step_length, + remaining, + state.j00, + state.j01, + state.j10, + state.j11, + viewport_x0, + viewport_y0, + viewport_x1, + viewport_y1, + ) { + Some(step) => step, + None => break, + }; + + if let Some(next_state) = sample_state( + grid, + u_data, + v_data, + display_data, + cell_valid_data, + chosen.candidate_x, + chosen.candidate_y, + ) { + let average_direction_x = direction_sign * (state.dir_x + next_state.dir_x); + let average_direction_y = direction_sign * (state.dir_y + next_state.dir_y); + let average_norm = average_direction_x.hypot(average_direction_y); + if average_norm > 1e-12 { + let avg_dir_x = average_direction_x / average_norm; + let avg_dir_y = average_direction_y / average_norm; + let average_speed = 0.5 * (state.speed + next_state.speed); + let mut average_step = ncl_step_length_px(step_px, average_speed, speed_scale); + if average_step > remaining + back_len { + average_step = remaining + back_len; + } + let avg_j00 = 0.5 * (state.j00 + next_state.j00); + let avg_j01 = 0.5 * (state.j01 + next_state.j01); + let avg_j10 = 0.5 * (state.j10 + next_state.j10); + let avg_j11 = 0.5 * (state.j11 + next_state.j11); + + chosen = match propose_trace_step( + grid, + current_data_x, + current_data_y, + current_display_x, + current_display_y, + corrected_display_x, + corrected_display_y, + avg_dir_x, + avg_dir_y, + average_step, + remaining, + avg_j00, + avg_j01, + avg_j10, + avg_j11, + viewport_x0, + viewport_y0, + viewport_x1, + viewport_y1, + ) { + Some(step) => step, + None => break, + }; + } + } + + let actual_step = (chosen.candidate_display_x - current_display_x) + .hypot(chosen.candidate_display_y - current_display_y); + if actual_step <= MIN_ACCEPTED_TRACE_STEP_PX { + break; + } + + curve.push(chosen.candidate_x); + curve.push(chosen.candidate_y); + if let Some(ref mut disp_buf) = display_curve { + disp_buf.push(chosen.candidate_display_x); + disp_buf.push(chosen.candidate_display_y); + } + + previous_display_x = current_display_x; + previous_display_y = current_display_y; + has_previous_display = true; + current_data_x = chosen.candidate_x; + current_data_y = chosen.candidate_y; + travelled += actual_step; + + if chosen.clipped { + break; + } + } + + let point_count = curve.len() / 2; + if point_count < 2 { + return None; + } + + let truncated = point_count == max_steps + 1 && travelled + 1e-6 < max_length_px; + Some(TraceBranchOutput { + curve, + display_curve, + truncated, + }) +} + +fn validate_trace_grid_inputs( + u: &[f64], + v: &[f64], + display_grid: &[f64], + cell_valid: &[bool], + ny: usize, + nx: usize, +) -> Result { + let expected_nodes = ny + .checked_mul(nx) + .ok_or_else(|| NclCurlyError::new("grid dimensions overflow"))?; + if u.len() != expected_nodes || v.len() != expected_nodes { + return Err(NclCurlyError::new("u and v must share the same shape")); + } + let expected_display = expected_nodes + .checked_mul(2) + .ok_or_else(|| NclCurlyError::new("display_grid dimensions overflow"))?; + if display_grid.len() != expected_display { + return Err(NclCurlyError::new( + "display_grid must match the u/v grid shape", + )); + } + if ny < 2 || nx < 2 { + return Ok(false); + } + let expected_cells = (ny - 1) + .checked_mul(nx - 1) + .ok_or_else(|| NclCurlyError::new("cell_valid dimensions overflow"))?; + if cell_valid.len() != expected_cells { + return Err(NclCurlyError::new( + "cell_valid must have shape (ny-1, nx-1)", + )); + } + Ok(true) +} + +/// Trace a single forward or backward curly-vector branch on regular gridded fields. +#[allow(clippy::too_many_arguments)] +pub fn trace_ncl_direction( + u: &[f64], + v: &[f64], + display_grid: &[f64], + cell_valid: &[bool], + ny: usize, + nx: usize, + x_origin: f64, + y_origin: f64, + dx: f64, + dy: f64, + start_x: f64, + start_y: f64, + max_length_px: f64, + direction_sign: f64, + step_px: f64, + speed_scale: f64, + viewport_x0: f64, + viewport_y0: f64, + viewport_x1: f64, + viewport_y1: f64, + max_steps: usize, + return_display: bool, +) -> Result, NclCurlyError> { + if !validate_trace_grid_inputs(u, v, display_grid, cell_valid, ny, nx)? { + return Ok(None); + } + + let grid = GridInfo::new(ny, nx, x_origin, y_origin, dx, dy); + Ok(trace_ncl_direction_core( + &grid, + u, + v, + display_grid, + cell_valid, + start_x, + start_y, + max_length_px, + direction_sign, + step_px, + speed_scale, + viewport_x0, + viewport_y0, + viewport_x1, + viewport_y1, + max_steps, + return_display, + ) + .map(|branch| TraceDirectionResult { + curve: branch.curve, + display_curve: branch.display_curve, + })) +} + +#[inline] +fn validate_display_curve_slice( + curve: &[f64], + viewport_width: f64, + viewport_height: f64, +) -> bool { + let n_points = curve.len() / 2; + if n_points < 2 { + return false; + } + if curve.iter().any(|v| !v.is_finite()) { + return false; + } + + let viewport_diag = viewport_width.hypot(viewport_height); + let use_jump_limit = viewport_diag.is_finite() && viewport_diag > 0.0; + let jump_limit = if use_jump_limit { + (viewport_diag * 0.35).max(1e-6) + } else { + 0.0 + }; + + let mut valid_count = 0usize; + let mut arc_length = 0.0; + let mut max_turn = 0.0; + let mut total_turn = 0.0; + let mut previous_turn_sign = 0i32; + let mut sign_changes = 0usize; + let mut prev_dir: Option<(f64, f64)> = None; + + for idx in 0..(n_points - 1) { + let dx = curve[(idx + 1) * 2] - curve[idx * 2]; + let dy = curve[(idx + 1) * 2 + 1] - curve[idx * 2 + 1]; + let length = dx.hypot(dy); + if use_jump_limit && length > jump_limit { + return false; + } + if length > 1e-6 { + let cur_x = dx / length; + let cur_y = dy / length; + if let Some((px, py)) = prev_dir { + let dot = (px * cur_x + py * cur_y).clamp(-1.0, 1.0); + let angle = dot.acos() * 180.0 / std::f64::consts::PI; + if angle > max_turn { + max_turn = angle; + } + total_turn += angle; + + let cross = px * cur_y - py * cur_x; + if cross.abs() > 1e-6 { + let current_turn_sign = if cross > 0.0 { 1 } else { -1 }; + if previous_turn_sign != 0 && current_turn_sign * previous_turn_sign < 0 { + sign_changes += 1; + } + previous_turn_sign = current_turn_sign; + } + } + prev_dir = Some((cur_x, cur_y)); + arc_length += length; + valid_count += 1; + } + } + + if valid_count < 1 { + return false; + } + + let chord_length = (curve[(n_points - 1) * 2] - curve[0]) + .hypot(curve[(n_points - 1) * 2 + 1] - curve[1]); + if arc_length <= 1e-6 || chord_length <= 1e-6 { + return false; + } + + let tortuosity = arc_length / chord_length; + if tortuosity > 1.28 { + return false; + } + if max_turn > 52.0 { + return false; + } + if total_turn > 120.0 { + return false; + } + if sign_changes > 0 && total_turn > 70.0 { + return false; + } + true +} + +/// Validate display-space curly-vector geometry against jump, tortuosity, and turn-angle limits. +pub fn validate_display_curve( + display_curve: &[f64], + viewport_width: f64, + viewport_height: f64, +) -> Result { + if display_curve.len() % 2 != 0 { + return Err(NclCurlyError::new("display_curve must have shape (N, 2)")); + } + Ok(validate_display_curve_slice( + display_curve, + viewport_width, + viewport_height, + )) +} + +#[inline] +pub(super) fn trace_step_budget(max_length_px: f64) -> usize { + if !max_length_px.is_finite() || max_length_px <= 0.0 { + return 1; + } + let required_steps = ((max_length_px / MIN_ACCEPTED_TRACE_STEP_PX).ceil() as usize) + .saturating_add(1) + .max(1); + required_steps.min(MAX_NATIVE_TRACE_STEPS) +} + +#[inline] +pub(super) fn reverse_xy_in_place(coords: &mut [f64]) { + let n = coords.len() / 2; + for i in 0..(n / 2) { + let j = n - 1 - i; + coords.swap(i * 2, j * 2); + coords.swap(i * 2 + 1, j * 2 + 1); + } +} + +#[allow(clippy::too_many_arguments)] +fn trace_single_glyph( + grid: &GridInfo, + u_data: &[f64], + v_data: &[f64], + display_data: &[f64], + cell_valid_data: &[bool], + start_x: f64, + start_y: f64, + total_length_px: f64, + anchor: TraceAnchor, + step_px: f64, + speed_scale: f64, + viewport_x0: f64, + viewport_y0: f64, + viewport_x1: f64, + viewport_y1: f64, + viewport_width: f64, + viewport_height: f64, +) -> (Option<(Vec, Vec)>, usize) { + let mut current_length_px = total_length_px; + let mut truncated_count = 0usize; + + for _attempt in 0..4 { + let traced = if current_length_px <= 0.0 { + None + } else { + match anchor { + TraceAnchor::Center => { + let half_len = current_length_px / 2.0; + let max_steps = trace_step_budget(half_len); + let backward = trace_ncl_direction_core( + grid, + u_data, + v_data, + display_data, + cell_valid_data, + start_x, + start_y, + half_len, + -1.0, + step_px, + speed_scale, + viewport_x0, + viewport_y0, + viewport_x1, + viewport_y1, + max_steps, + true, + ); + if let Some(ref b) = backward { + if b.truncated { + truncated_count += 1; + } + } + + let forward = trace_ncl_direction_core( + grid, + u_data, + v_data, + display_data, + cell_valid_data, + start_x, + start_y, + half_len, + 1.0, + step_px, + speed_scale, + viewport_x0, + viewport_y0, + viewport_x1, + viewport_y1, + max_steps, + true, + ); + if let Some(ref f) = forward { + if f.truncated { + truncated_count += 1; + } + } + + match (backward, forward) { + (None, None) => None, + (None, Some(f)) => { + let disp = f.display_curve.unwrap_or_default(); + Some((f.curve, disp)) + } + (Some(mut b), None) => { + reverse_xy_in_place(&mut b.curve); + let mut disp = b.display_curve.unwrap_or_default(); + reverse_xy_in_place(&mut disp); + Some((b.curve, disp)) + } + (Some(mut b), Some(f)) => { + reverse_xy_in_place(&mut b.curve); + b.curve.extend_from_slice(&f.curve[2..]); + let mut disp = b.display_curve.unwrap_or_default(); + reverse_xy_in_place(&mut disp); + let f_disp = f.display_curve.unwrap_or_default(); + disp.extend_from_slice(&f_disp[2..]); + Some((b.curve, disp)) + } + } + } + TraceAnchor::Tail => { + let max_steps = trace_step_budget(current_length_px); + trace_ncl_direction_core( + grid, + u_data, + v_data, + display_data, + cell_valid_data, + start_x, + start_y, + current_length_px, + 1.0, + step_px, + speed_scale, + viewport_x0, + viewport_y0, + viewport_x1, + viewport_y1, + max_steps, + true, + ) + .map(|f| { + if f.truncated { + truncated_count += 1; + } + (f.curve, f.display_curve.unwrap_or_default()) + }) + } + TraceAnchor::Head => { + let max_steps = trace_step_budget(current_length_px); + trace_ncl_direction_core( + grid, + u_data, + v_data, + display_data, + cell_valid_data, + start_x, + start_y, + current_length_px, + -1.0, + step_px, + speed_scale, + viewport_x0, + viewport_y0, + viewport_x1, + viewport_y1, + max_steps, + true, + ) + .map(|mut b| { + if b.truncated { + truncated_count += 1; + } + reverse_xy_in_place(&mut b.curve); + let mut disp = b.display_curve.unwrap_or_default(); + reverse_xy_in_place(&mut disp); + (b.curve, disp) + }) + } + } + }; + + if let Some((curve, display_curve)) = traced { + if curve.len() / 2 >= 2 + && validate_display_curve_slice(&display_curve, viewport_width, viewport_height) + { + return (Some((curve, display_curve)), truncated_count); + } + } + + current_length_px *= 0.78; + if current_length_px <= step_px { + break; + } + } + + (None, truncated_count) +} + +/// Trace, stitch, validate, and retry a batch of curly-vector glyphs in parallel via Rayon. +/// +/// Mirrors the Python `_build_ncl_curve` + `_trace_ncl_curve_with_display` + `validate_display_curve` +/// loop across `M` seed centers while preserving deterministic ascending center order. +#[allow(clippy::too_many_arguments)] +pub fn trace_ncl_glyphs_batch( + u: &[f64], + v: &[f64], + display_grid: &[f64], + cell_valid: &[bool], + ny: usize, + nx: usize, + x_origin: f64, + y_origin: f64, + dx: f64, + dy: f64, + centers: &[f64], + target_lengths_px: &[f64], + anchor: TraceAnchor, + step_px: f64, + speed_scale: f64, + viewport_x0: f64, + viewport_y0: f64, + viewport_x1: f64, + viewport_y1: f64, +) -> Result { + if centers.len() % 2 != 0 { + return Err(NclCurlyError::new("centers must have shape (M, 2)")); + } + let n_centers = centers.len() / 2; + if target_lengths_px.len() != n_centers { + return Err(NclCurlyError::new( + "target_lengths_px must have the same length as centers", + )); + } + + let has_cells = validate_trace_grid_inputs(u, v, display_grid, cell_valid, ny, nx)?; + if !has_cells || n_centers == 0 { + return Ok(BatchTraceResult { + data_points: Vec::new(), + display_points: Vec::new(), + curve_offsets: vec![0], + valid_indices: Vec::new(), + truncated_count: 0, + }); + } + + let grid = GridInfo::new(ny, nx, x_origin, y_origin, dx, dy); + let viewport_width = viewport_x1 - viewport_x0; + let viewport_height = viewport_y1 - viewport_y0; + + let run_one = |idx: usize| -> (Option<(Vec, Vec)>, usize) { + trace_single_glyph( + &grid, + u, + v, + display_grid, + cell_valid, + centers[idx * 2], + centers[idx * 2 + 1], + target_lengths_px[idx], + anchor, + step_px, + speed_scale, + viewport_x0, + viewport_y0, + viewport_x1, + viewport_y1, + viewport_width, + viewport_height, + ) + }; + + let per_center: Vec<(Option<(Vec, Vec)>, usize)> = + if n_centers >= PARALLEL_BATCH_TRACE_THRESHOLD { + (0..n_centers).into_par_iter().map(run_one).collect() + } else { + (0..n_centers).map(run_one).collect() + }; + + let mut total_points = 0usize; + let mut valid_count = 0usize; + let mut truncated_count = 0usize; + for (curve_opt, trunc) in &per_center { + truncated_count += *trunc; + if let Some((curve, _)) = curve_opt { + total_points += curve.len() / 2; + valid_count += 1; + } + } + + let mut data_points = Vec::with_capacity(total_points * 2); + let mut display_points = Vec::with_capacity(total_points * 2); + let mut curve_offsets = Vec::with_capacity(valid_count + 1); + let mut valid_indices = Vec::with_capacity(valid_count); + curve_offsets.push(0); + + let mut point_cursor = 0usize; + for (idx, (curve_opt, _)) in per_center.into_iter().enumerate() { + if let Some((curve, display_curve)) = curve_opt { + let n_pts = curve.len() / 2; + data_points.extend_from_slice(&curve); + display_points.extend_from_slice(&display_curve); + point_cursor += n_pts; + curve_offsets.push(point_cursor); + valid_indices.push(idx); + } + } + + Ok(BatchTraceResult { + data_points, + display_points, + curve_offsets, + valid_indices, + truncated_count, + }) +} diff --git a/src/skybornplot/__init__.py b/src/skybornplot/__init__.py index fda740e..88e37b8 100644 --- a/src/skybornplot/__init__.py +++ b/src/skybornplot/__init__.py @@ -5,16 +5,24 @@ Created: 2026-03-01 14:58:56 """ -from .contour import arrow_contour, arrow_contour_clabel, shadow_contourf -from .plotting import ( - GradientFillBetween, - add_centered_axes, - add_equal_axes, - createFigure, - gradient_fill_between, -) -from .scatter import scatter -from .vector import curly_vector, curly_vector_key +from __future__ import annotations + +import importlib +import sys +import types +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from .contour import arrow_contour, arrow_contour_clabel, shadow_contourf + from .plotting import ( + GradientFillBetween, + add_centered_axes, + add_equal_axes, + createFigure, + gradient_fill_between, + ) + from .scatter import scatter + from .vector import curly_vector, curly_vector_key __version__ = "0.2.0" @@ -32,3 +40,46 @@ "scatter", "shadow_contourf", ] + +_LAZY_EXPORTS: dict[str, tuple[str, str]] = { + "GradientFillBetween": (".plotting", "GradientFillBetween"), + "add_equal_axes": (".plotting", "add_equal_axes"), + "add_centered_axes": (".plotting", "add_centered_axes"), + "arrow_contour": (".contour", "arrow_contour"), + "arrow_contour_clabel": (".contour", "arrow_contour_clabel"), + "createFigure": (".plotting", "createFigure"), + "curly_vector": (".vector", "curly_vector"), + "curly_vector_key": (".vector", "curly_vector_key"), + "gradient_fill_between": (".plotting", "gradient_fill_between"), + "scatter": (".scatter", "scatter"), + "shadow_contourf": (".contour", "shadow_contourf"), +} + + +class _SkybornPlotModule(types.ModuleType): + """Package module type preserving exported callables across submodule imports.""" + + def __setattr__(self, name: str, value: Any) -> None: + # Prevent `import skybornplot.scatter` from shadowing the exported + # `scatter` function in `__all__` with the submodule object. + if name in _LAZY_EXPORTS and isinstance(value, types.ModuleType): + return + super().__setattr__(name, value) + + +def __getattr__(name: str) -> Any: + target = _LAZY_EXPORTS.get(name) + if target is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + module_name, attr_name = target + module = importlib.import_module(module_name, __name__) + value = getattr(module, attr_name) + globals()[name] = value + return value + + +def __dir__() -> list[str]: + return sorted(set(globals()) | set(__all__)) + + +sys.modules[__name__].__class__ = _SkybornPlotModule diff --git a/src/skybornplot/_core/native.py b/src/skybornplot/_core/native.py index c9c1108..dcfd50a 100644 --- a/src/skybornplot/_core/native.py +++ b/src/skybornplot/_core/native.py @@ -7,10 +7,49 @@ import numpy as np +from .._plot_rs.nclcurly import ( + build_filled_arrow_polygons as _rs_build_filled_arrow_polygons, +) +from .._plot_rs.nclcurly import ( + build_open_arrow_segments as _rs_build_open_arrow_segments, +) +from .._plot_rs.nclcurly import ( + generate_cell_candidates as _rs_generate_cell_candidates, +) +from .._plot_rs.nclcurly import sample_grid_field as _rs_sample_grid_field +from .._plot_rs.nclcurly import ( + sample_grid_field_array as _rs_sample_grid_field_array, +) +from .._plot_rs.nclcurly import ( + thin_display_candidates as _rs_thin_display_candidates, +) +from .._plot_rs.nclcurly import ( + thin_mapped_candidates as _rs_thin_mapped_candidates, +) +from .._plot_rs.nclcurly import trace_ncl_direction as _rs_trace_ncl_direction +from .._plot_rs.nclcurly import ( + trace_ncl_glyphs_batch as _rs_trace_ncl_glyphs_batch, +) +from .._plot_rs.nclcurly import ( + validate_display_curve as _rs_validate_display_curve, +) + _MIN_ACCEPTED_TRACE_STEP_PX = 0.2 _MAX_NATIVE_TRACE_STEPS = 4096 +def _as_f64(arr): + if isinstance(arr, np.ndarray) and arr.dtype == np.float64: + return arr + return np.asarray(arr, dtype=np.float64) + + +def _as_intp(arr): + if isinstance(arr, np.ndarray) and arr.dtype == np.intp: + return arr + return np.asarray(arr, dtype=np.intp) + + def _trace_step_budget(max_length_px): """Return enough native steps to cover the requested display length.""" max_length_px = float(max_length_px) @@ -26,11 +65,22 @@ def _trace_step_budget(max_length_px): def _native_field_array(field): if np.ma.isMaskedArray(field): - return np.asarray(np.ma.filled(field, np.nan), dtype=float) - return np.asarray(field, dtype=float) + return np.asarray(np.ma.filled(field, np.nan), dtype=np.float64) + return _as_f64(field) def _call_native_sample_grid_field(native_sampler, grid, field, xd, yd): + if native_sampler is _rs_sample_grid_field: + return _rs_sample_grid_field( + _native_field_array(field), + float(grid.x_origin), + float(grid.y_origin), + float(grid.dx), + float(grid.dy), + float(xd), + float(yd), + ) + value = native_sampler( field=_native_field_array(field), x_origin=float(grid.x_origin), @@ -54,6 +104,19 @@ def _call_native_sample_grid_field_array( points, expected_shape, ): + if native_sampler is _rs_sample_grid_field_array: + sampled = _rs_sample_grid_field_array( + _native_field_array(field), + float(grid.x_origin), + float(grid.y_origin), + float(grid.dx), + float(grid.dy), + _as_f64(points), + ) + if sampled.shape != tuple(expected_shape): + return None + return sampled + sampled = native_sampler( field=_native_field_array(field), x_origin=float(grid.x_origin), @@ -77,6 +140,12 @@ def _call_native_thin_ncl_mapped_candidates( mapped_points, spacing_frac, ): + if native_thinner is _rs_thin_mapped_candidates: + return _rs_thin_mapped_candidates( + _as_f64(mapped_points), + float(spacing_frac), + ).tolist() + selected = native_thinner( mapped_points=np.asarray(mapped_points, dtype=float), spacing_frac=float(spacing_frac), @@ -92,6 +161,16 @@ def _call_native_thin_ncl_display_candidates( viewport, spacing_frac, ): + if native_thinner is _rs_thin_display_candidates: + return _rs_thin_display_candidates( + _as_f64(display_points), + float(viewport.x0), + float(viewport.y0), + float(viewport.width), + float(viewport.height), + float(spacing_frac), + ).tolist() + selected = native_thinner( display_points=np.asarray(display_points, dtype=float), viewport_x0=float(viewport.x0), @@ -112,6 +191,14 @@ def _call_native_generate_cell_candidates( source_points, spacing_fraction, ): + if native_generator is _rs_generate_cell_candidates: + return _rs_generate_cell_candidates( + _as_f64(corners), + _as_f64(mapped_corners), + _as_f64(source_points), + float(spacing_fraction), + ) + generated = native_generator( corners=np.asarray(corners, dtype=float), mapped_corners=np.asarray(mapped_corners, dtype=float), @@ -133,6 +220,13 @@ def _call_native_build_open_arrow_segments( head_widths_px, ): """Build compact batched open-arrow display polylines ``(K, 3, 2)`` through the native kernel.""" + if native_builder is _rs_build_open_arrow_segments: + return _rs_build_open_arrow_segments( + _as_f64(display_points), + _as_intp(curve_offsets), + _as_f64(head_lengths_px), + _as_f64(head_widths_px), + ) segments, source_positions = native_builder( display_points=np.asarray(display_points, dtype=float), @@ -157,6 +251,13 @@ def _call_native_build_filled_arrow_polygons( head_widths_px, ): """Build compact batched filled-arrow polygons through the native kernel.""" + if native_builder is _rs_build_filled_arrow_polygons: + return _rs_build_filled_arrow_polygons( + _as_f64(display_points), + _as_intp(curve_offsets), + _as_f64(head_lengths_px), + _as_f64(head_widths_px), + ) polygons, source_positions = native_builder( display_points=np.asarray(display_points, dtype=float), @@ -185,6 +286,40 @@ def _call_native_trace_ncl_direction( if native_trace_context is None: return None + if native_tracer is _rs_trace_ncl_direction: + max_steps = _trace_step_budget(max_length_px) + curve = _rs_trace_ncl_direction( + native_trace_context.u, + native_trace_context.v, + native_trace_context.display_grid, + native_trace_context.cell_valid, + native_trace_context.x_origin, + native_trace_context.y_origin, + native_trace_context.dx, + native_trace_context.dy, + float(start_point[0]), + float(start_point[1]), + float(max_length_px), + float(direction_sign), + float(step_px), + float(speed_scale), + native_trace_context.viewport_x0, + native_trace_context.viewport_y0, + native_trace_context.viewport_x1, + native_trace_context.viewport_y1, + max_steps, + ) + if curve is None: + return None + if curve.shape[0] == max_steps + 1: + warnings.warn( + "curly-vector tracing reached max_steps; the returned curve may " + "be truncated", + RuntimeWarning, + stacklevel=3, + ) + return curve if curve.shape[0] >= 2 else None + trace_kwargs = _trace_kwargs( native_trace_context, start_point, @@ -254,6 +389,48 @@ def _call_native_trace_ncl_direction_with_display( if native_trace_context is None: return None + if native_tracer is _rs_trace_ncl_direction: + max_steps = _trace_step_budget(max_length_px) + traced = _rs_trace_ncl_direction( + native_trace_context.u, + native_trace_context.v, + native_trace_context.display_grid, + native_trace_context.cell_valid, + native_trace_context.x_origin, + native_trace_context.y_origin, + native_trace_context.dx, + native_trace_context.dy, + float(start_point[0]), + float(start_point[1]), + float(max_length_px), + float(direction_sign), + float(step_px), + float(speed_scale), + native_trace_context.viewport_x0, + native_trace_context.viewport_y0, + native_trace_context.viewport_x1, + native_trace_context.viewport_y1, + max_steps, + True, + ) + if traced is None: + return None + curve, display_curve = traced + if curve.shape[0] < 2: + return None + if curve.shape[0] == max_steps + 1: + travelled_px = np.linalg.norm( + np.diff(display_curve, axis=0), axis=1 + ).sum() + if travelled_px + 1e-6 < float(max_length_px): + warnings.warn( + "curly-vector tracing reached max_steps before the requested " + "display length; the returned curve is truncated", + RuntimeWarning, + stacklevel=3, + ) + return curve, display_curve + trace_kwargs = _trace_kwargs( native_trace_context, start_point, @@ -294,6 +471,13 @@ def _call_native_trace_ncl_direction_with_display( def _call_native_validate_display_curve(native_validator, display_curve, viewport): + if native_validator is _rs_validate_display_curve: + return _rs_validate_display_curve( + _as_f64(display_curve), + float(viewport.width) if viewport is not None else 0.0, + float(viewport.height) if viewport is not None else 0.0, + ) + return bool( native_validator( display_curve=np.asarray(display_curve, dtype=float), @@ -316,6 +500,52 @@ def _call_native_trace_ncl_glyphs_batch( if native_trace_context is None: return [], [], [] + if native_batch_tracer is _rs_trace_ncl_glyphs_batch: + centers_arr = _as_f64(centers) + if centers_arr.ndim != 2 or centers_arr.shape[0] == 0: + return [], [], [] + + data_points, display_points, curve_offsets, valid_indices, truncated_count = ( + _rs_trace_ncl_glyphs_batch( + native_trace_context.u, + native_trace_context.v, + native_trace_context.display_grid, + native_trace_context.cell_valid, + native_trace_context.x_origin, + native_trace_context.y_origin, + native_trace_context.dx, + native_trace_context.dy, + centers_arr, + _as_f64(target_lengths_px), + str(anchor), + float(step_px), + float(speed_scale), + native_trace_context.viewport_x0, + native_trace_context.viewport_y0, + native_trace_context.viewport_x1, + native_trace_context.viewport_y1, + ) + ) + + if truncated_count > 0: + warnings.warn( + "curly-vector tracing reached max_steps before the requested " + "display length; the returned curve is truncated", + RuntimeWarning, + stacklevel=3, + ) + + offsets = curve_offsets.tolist() + valid_list = valid_indices.tolist() + n_valid = len(valid_list) + curves = [ + data_points[offsets[i] : offsets[i + 1]] for i in range(n_valid) + ] + display_curves = [ + display_points[offsets[i] : offsets[i + 1]] for i in range(n_valid) + ] + return valid_list, curves, display_curves + centers_arr = np.asarray(centers, dtype=float) if centers_arr.ndim != 2 or centers_arr.shape[0] == 0: return [], [], [] diff --git a/src/skybornplot/_plot_rs.pyi b/src/skybornplot/_plot_rs.pyi new file mode 100644 index 0000000..aee912a --- /dev/null +++ b/src/skybornplot/_plot_rs.pyi @@ -0,0 +1,196 @@ +"""Type stubs for the Pure-Rust ``skybornplot._plot_rs`` extension module.""" + +from __future__ import annotations + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +__version__: str + +class nclcurly: + @staticmethod + def trace_ncl_direction( + u: ArrayLike, + v: ArrayLike, + display_grid: ArrayLike, + cell_valid: ArrayLike, + x_origin: float, + y_origin: float, + dx: float, + dy: float, + start_x: float, + start_y: float, + max_length_px: float, + direction_sign: float, + step_px: float, + speed_scale: float, + viewport_x0: float, + viewport_y0: float, + viewport_x1: float, + viewport_y1: float, + max_steps: int = 512, + return_display: bool | None = None, + ) -> NDArray[np.float64] | tuple[NDArray[np.float64], NDArray[np.float64]] | None: ... + + @staticmethod + def sample_grid_field( + field: ArrayLike, + x_origin: float, + y_origin: float, + dx: float, + dy: float, + x: float, + y: float, + ) -> float | None: ... + + @staticmethod + def sample_grid_field_array( + field: ArrayLike, + x_origin: float, + y_origin: float, + dx: float, + dy: float, + points: ArrayLike, + ) -> NDArray[np.float64]: ... + + @staticmethod + def compute_display_cell_valid( + display_grid: ArrayLike, + ) -> NDArray[np.bool_]: ... + + @staticmethod + def sample_display_grid( + display_grid: ArrayLike, + cell_valid: ArrayLike, + x_origin: float, + y_origin: float, + dx: float, + dy: float, + points: ArrayLike, + include_jacobian: bool | None = None, + ) -> tuple[NDArray[np.float64], NDArray[np.float64] | None, NDArray[np.bool_]]: ... + + @staticmethod + def thin_mapped_candidates( + mapped_points: ArrayLike, + spacing_frac: float, + ) -> NDArray[np.intp]: ... + + @staticmethod + def thin_display_candidates( + display_points: ArrayLike, + viewport_x0: float, + viewport_y0: float, + viewport_width: float, + viewport_height: float, + spacing_frac: float, + ) -> NDArray[np.intp]: ... + + @staticmethod + def generate_cell_candidates( + corners: ArrayLike, + mapped_corners: ArrayLike, + source_points: ArrayLike, + spacing_frac: float, + ) -> tuple[NDArray[np.float64], NDArray[np.intp]]: ... + + @staticmethod + def validate_display_curve( + display_curve: ArrayLike, + viewport_width: float = 0.0, + viewport_height: float = 0.0, + ) -> bool: ... + + @staticmethod + def build_open_arrow_segments( + display_points: ArrayLike, + curve_offsets: ArrayLike, + head_lengths_px: ArrayLike, + head_widths_px: ArrayLike, + ) -> tuple[NDArray[np.float64], NDArray[np.intp]]: ... + + @staticmethod + def build_filled_arrow_polygons( + display_points: ArrayLike, + curve_offsets: ArrayLike, + head_lengths_px: ArrayLike, + head_widths_px: ArrayLike, + ) -> tuple[NDArray[np.float64], NDArray[np.intp]]: ... + + @staticmethod + def trace_ncl_glyphs_batch( + u: ArrayLike, + v: ArrayLike, + display_grid: ArrayLike, + cell_valid: ArrayLike, + x_origin: float, + y_origin: float, + dx: float, + dy: float, + centers: ArrayLike, + target_lengths_px: ArrayLike, + anchor: str, + step_px: float, + speed_scale: float, + viewport_x0: float, + viewport_y0: float, + viewport_x1: float, + viewport_y1: float, + ) -> tuple[ + NDArray[np.float64], + NDArray[np.float64], + NDArray[np.intp], + NDArray[np.intp], + int, + ]: ... + +class contour_arrows: + @staticmethod + def point_at_distance( + vertices: NDArray[np.float64], + distance: float, + ) -> NDArray[np.float64] | None: ... + + @staticmethod + def local_tangent_at_distance( + vertices: NDArray[np.float64], + distance: float, + total_length: float, + probe: float, + ) -> NDArray[np.float64] | None: ... + + @staticmethod + def local_straightness_score( + vertices: NDArray[np.float64], + distance: float, + arrow_length: float, + ) -> float: ... + + @staticmethod + def select_arrow_end_distances( + vertices: NDArray[np.float64], + total_length: float, + arrow_count: int, + arrow_length: float, + min_spacing_override: float | None = None, + ) -> NDArray[np.float64]: ... + +class contour: + @staticmethod + def build_arrow_segments( + vertices: ArrayLike, + arrow_count: int, + arrow_length: float, + arrow_size: float = 0.45, + ) -> tuple[NDArray[np.float64], NDArray[np.float64]]: ... + + @staticmethod + def build_swept_arrow_segments( + vertices: ArrayLike, + total_length: float, + arrow_count: int, + arrow_length: float, + arrow_size: float, + arrow_angle: float = 22.5, + min_spacing_override: float | None = None, + ) -> tuple[NDArray[np.float64], NDArray[np.float64]]: ... diff --git a/src/skybornplot/py.typed b/src/skybornplot/py.typed new file mode 100644 index 0000000..e69de29