Skip to main content

brep_render/sheets/
pdf3d.rs

1//! The live 3D model a sheet PDF can carry — a U3D stream ([`super::u3d`]) and
2//! the PDF 1.7 dictionaries that show it (ISO 32000-1 §13.6).
3//!
4//! # What the reader sees
5//!
6//! One U3D stream holds the whole scene, shared by every 3D annotation in the
7//! file:
8//!
9//! - each drawn solid as a MESH node named for the solid, and its edges as a
10//!   dark LINE SET node beside it (`{solid} edges`), so the model reads as a
11//!   CAD model and not a smooth blob;
12//! - each enabled, resolved annotation of each saved view with a camera as a
13//!   LINE SET node (`PMI {view} {annotation}`: dimension, extension and leader
14//!   lines, frames, and the text STROKED with the PMI font — the same
15//!   [`pmi_present`] layout the viewport and the STEP presentation use, sized
16//!   as the viewport drew it when the view was saved), plus a small MESH node
17//!   for its filled arrowheads (`… fill`).
18//!
19//! Each saved view is a `/3DView` in the stream's `/VA` list: its camera as the
20//! camera-to-world matrix, its projection, and a `/NA` node list that shows
21//! THAT view's annotations and hides every other view's, and hides the solids
22//! the view hides. A reader's view menu is therefore the document's PMI view
23//! list, and picking one shows exactly that view's PMI.
24//!
25//! Only readers that implement 3D annotations draw any of this — Adobe
26//! Acrobat / Reader (with 3D enabled) and Foxit. Every other reader shows the
27//! annotation's appearance, which is why the sheet's own vector drawing stays
28//! on the page beneath a placement, and why the full 3D page draws the default
29//! view as a hidden-line drawing under its 3D box.
30//!
31//! # The camera
32//!
33//! A view's `/C2W` maps camera coordinates to world coordinates: its columns
34//! are the camera's x axis (right), y axis and z axis (the viewing direction,
35//! eye → target), then the eye. ISO 32000-1 §13.6.5 states the camera's y axis
36//! points UP; [`CAMERA_Y_UP`] records which way this writer points it, because
37//! the claim is checked in a real reader, not taken from the text.
38
39use brep_kernel::{
40    pmi_present, PmiAnnotationReport, PmiCamera, PmiGeometry, PmiLayoutStyle, PmiPlane, PmiPose, PmiProjection,
41    PmiReport, PmiState, PmiStatus, PmiView,
42};
43
44use super::pdf::{string_literal, PT_PER_MM};
45use super::u3d::{self, Geometry, Lines, Material, Mesh, Model, Scene};
46
47/// The camera's y axis is the view's UP vector (true) or its down vector
48/// (false). See the module doc.
49pub const CAMERA_Y_UP: bool = true;
50
51use crate::engine_state::pmi_overlay::{ARROW_PX, TEXT_PX_AT_12PT};
52
53/// Model units per viewport pixel under a saved camera, in the viewport the
54/// view was saved from — `ViewCamera::world_per_pixel`'s rule.
55pub fn world_per_pixel(camera: &PmiCamera) -> f64 {
56    let height = camera.viewport[1].max(1.0);
57    match camera.projection {
58        PmiProjection::Orthographic { half_height } => 2.0 * half_height / height,
59        PmiProjection::Perspective { fov_y_deg } => {
60            let d = sub(camera.target, camera.eye);
61            2.0 * (fov_y_deg.to_radians() * 0.5).tan() * dot(d, d).sqrt() / height
62        }
63    }
64}
65
66/// Edge lines: near-black, so they read on any body colour.
67const EDGE_RGB: [u8; 3] = [0x20, 0x20, 0x24];
68/// PMI: a deep orange — the viewport's amber darkened enough to read on the
69/// PDF's white background, and clear of the blues and greys bodies default
70/// to (a blue first drawn here vanished into a blue cube in Acrobat).
71const PMI_RGB: [u8; 3] = [0xD9, 0x68, 0x00];
72
73/// One solid, gathered by the engine from the display scene.
74#[derive(Debug, Clone)]
75pub struct Body {
76    pub name: String,
77    pub positions: Vec<[f32; 3]>,
78    pub normals: Vec<[f32; 3]>,
79    /// Three per triangle.
80    pub indices: Vec<u32>,
81    /// sRGB per triangle.
82    pub triangle_colors: Vec<[u8; 3]>,
83    /// World polylines of the solid's real edges.
84    pub edges: Vec<Vec<[f32; 3]>>,
85}
86
87/// How a view projects.
88#[derive(Debug, Clone, Copy, PartialEq)]
89pub enum Projection3d {
90    /// Points of the annotation per model unit.
91    Orthographic { scale: f64 },
92    /// Vertical field of view, degrees.
93    Perspective { fov_y_deg: f64 },
94}
95
96/// A saved view as the reader will show it.
97#[derive(Debug, Clone, PartialEq)]
98pub struct View3d {
99    /// The PMI view id (`VIEW1`) — the dictionary's internal name.
100    pub id: String,
101    /// What the reader's view menu lists.
102    pub name: String,
103    pub camera: PmiCamera,
104    pub wireframe: bool,
105    /// Visibility per [`Model3d::nodes`] entry.
106    pub visible: Vec<bool>,
107    /// Per [`Model3d::nodes`] entry, the node's `/M` in this view: a solid
108    /// an explode step moves, as its composed stages ([`stage_matrix`]).
109    /// `None` leaves the node where the stream put it.
110    pub poses: Vec<Option<[f64; 12]>>,
111    /// The view's section plane, `(point, normal)`, kept where
112    /// `(p − point)·normal ≥ 0` as in the viewport. A half section's further
113    /// planes are not carried: a `/3DCrossSection` cannot keep what either
114    /// plane keeps, so the reader cuts the first plane only.
115    pub section: Option<([f64; 3], [f64; 3])>,
116}
117
118/// The file's 3D content: the U3D bytes, the node names in stream order, and
119/// every saved view that has a camera.
120#[derive(Debug, Clone, PartialEq)]
121pub struct Model3d {
122    pub u3d: Vec<u8>,
123    pub nodes: Vec<String>,
124    pub views: Vec<View3d>,
125    /// How many annotations are drawn, over every view.
126    pub annotations: usize,
127}
128
129impl Model3d {
130    pub fn view(&self, id: &str) -> Option<&View3d> {
131        self.views.iter().find(|view| view.id == id)
132    }
133}
134
135/// A node name a PDF `/3DNode /N` can match exactly: printable ASCII, unique.
136fn node_name(wanted: &str, taken: &mut std::collections::HashSet<String>) -> String {
137    let base: String = wanted
138        .chars()
139        .map(|c| if (' '..='~').contains(&c) { c } else { '_' })
140        .collect::<String>()
141        .trim()
142        .to_string();
143    let base = if base.is_empty() { "node".to_string() } else { base };
144    let mut name = base.clone();
145    let mut n = 2;
146    while !taken.insert(name.clone()) {
147        name = format!("{base} #{n}");
148        n += 1;
149    }
150    name
151}
152
153fn material_for(rgb: [u8; 3], lit_line: bool) -> Material {
154    let c = rgb.map(|v| f32::from(v) / 255.0);
155    Material {
156        name: format!("C{:02X}{:02X}{:02X}{}", rgb[0], rgb[1], rgb[2], if lit_line { "L" } else { "" }),
157        ambient: c.map(|v| v * 0.3),
158        diffuse: c,
159        specular: [0.15; 3],
160        // A line has no surface to light: it shows its own colour.
161        emissive: if lit_line { c } else { [0.0; 3] },
162        reflectivity: 0.1,
163        opacity: 1.0,
164    }
165}
166
167/// The index of `rgb`'s material, added once.
168fn material_index(scene: &mut Scene, rgb: [u8; 3], line: bool) -> usize {
169    let wanted = material_for(rgb, line);
170    if let Some(index) = scene.materials.iter().position(|m| m.name == wanted.name) {
171        return index;
172    }
173    scene.materials.push(wanted);
174    scene.materials.len() - 1
175}
176
177fn to_f32(p: [f64; 3]) -> [f32; 3] {
178    [p[0] as f32, p[1] as f32, p[2] as f32]
179}
180
181/// Polylines as one line set: consecutive points joined, zero-length steps
182/// dropped.
183fn line_set(polylines: &[Vec<[f32; 3]>]) -> Option<Lines> {
184    let mut lines = Lines::default();
185    for polyline in polylines {
186        let mut previous: Option<u32> = None;
187        for p in polyline {
188            if !p.iter().all(|c| c.is_finite()) {
189                previous = None;
190                continue;
191            }
192            if let Some(prev) = previous {
193                if lines.positions[prev as usize] == *p {
194                    continue;
195                }
196            }
197            let index = lines.positions.len() as u32;
198            lines.positions.push(*p);
199            if let Some(prev) = previous {
200                lines.segments.push(([prev, index], 0));
201            }
202            previous = Some(index);
203        }
204    }
205    (!lines.segments.is_empty()).then_some(lines)
206}
207
208/// Triangles as a flat-shaded mesh: three vertices each, carrying the face
209/// normal.
210fn triangle_mesh(triangles: &[[[f64; 3]; 3]]) -> Option<Mesh> {
211    let mut mesh = Mesh::default();
212    for t in triangles {
213        let u = [t[1][0] - t[0][0], t[1][1] - t[0][1], t[1][2] - t[0][2]];
214        let v = [t[2][0] - t[0][0], t[2][1] - t[0][1], t[2][2] - t[0][2]];
215        let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
216        let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
217        if !(len > 1e-12) {
218            continue;
219        }
220        let normal = to_f32([n[0] / len, n[1] / len, n[2] / len]);
221        let base = mesh.positions.len() as u32;
222        for corner in t {
223            mesh.positions.push(to_f32(*corner));
224            mesh.normals.push(normal);
225        }
226        mesh.triangles.push(([base, base + 1, base + 2], 0));
227    }
228    (!mesh.triangles.is_empty()).then_some(mesh)
229}
230
231use crate::geometry3d::sub3 as sub;
232use crate::geometry3d::cross3 as cross;
233use crate::geometry3d::dot3 as dot;
234use crate::geometry3d::normalize3 as unit;
235
236/// The camera's right, up and forward (eye → target) unit vectors; `None`
237/// for a degenerate camera (eye on target, or up along the view).
238pub fn camera_frame(camera: &PmiCamera) -> Option<([f64; 3], [f64; 3], [f64; 3])> {
239    let forward = unit(sub(camera.target, camera.eye))?;
240    let right = unit(cross(forward, camera.up))?;
241    let up = cross(right, forward);
242    Some((right, up, forward))
243}
244
245/// Build the 3D model: the solids, then every saved view's annotations.
246pub fn build(bodies: &[Body], pmi: &PmiState, report: Option<&PmiReport>) -> Result<Model3d, String> {
247    let mut scene = Scene::default();
248    let mut taken = std::collections::HashSet::new();
249    // Per node: the scene object it belongs to (a solid name) or the view it
250    // annotates — what decides its visibility in each view.
251    enum Owner {
252        Solid(String),
253        View(String),
254    }
255    let mut owners: Vec<Owner> = Vec::new();
256
257    for body in bodies {
258        if body.indices.len() < 3 || body.positions.is_empty() {
259            continue;
260        }
261        let mut shaders: Vec<usize> = Vec::new();
262        let mut mesh = Mesh { positions: body.positions.clone(), normals: body.normals.clone(), triangles: Vec::new() };
263        for (index, corners) in body.indices.chunks_exact(3).enumerate() {
264            let rgb = body.triangle_colors.get(index).copied().unwrap_or([0xB0, 0xB4, 0xBC]);
265            let material = material_index(&mut scene, rgb, false);
266            let shading = match shaders.iter().position(|m| *m == material) {
267                Some(slot) => slot,
268                None => {
269                    shaders.push(material);
270                    shaders.len() - 1
271                }
272            };
273            mesh.triangles.push(([corners[0], corners[1], corners[2]], shading as u32));
274        }
275        if mesh.triangles.is_empty() {
276            continue;
277        }
278        let name = node_name(&body.name, &mut taken);
279        scene.models.push(Model { name, geometry: Geometry::Mesh(mesh), shaders, two_sided: false });
280        owners.push(Owner::Solid(body.name.clone()));
281        if let Some(lines) = line_set(&body.edges) {
282            let material = material_index(&mut scene, EDGE_RGB, true);
283            let name = node_name(&format!("{} edges", body.name), &mut taken);
284            scene.models.push(Model { name, geometry: Geometry::Lines(lines), shaders: vec![material], two_sided: false });
285            owners.push(Owner::Solid(body.name.clone()));
286        }
287    }
288    if scene.models.is_empty() {
289        return Err("the scene has no solid to show in 3D".into());
290    }
291
292    let mut annotations = 0;
293    let cameras: Vec<(&PmiView, &PmiCamera)> =
294        pmi.views.iter().filter_map(|view| view.camera.as_ref().map(|camera| (view, camera))).collect();
295    for (view, camera) in &cameras {
296        let Some(rows) = report.and_then(|report| report.view(&view.id)) else { continue };
297        for (row, drawn) in view_annotations(view, camera, rows) {
298            let polylines: Vec<Vec<[f32; 3]>> = drawn.lines.iter().map(|line| line.iter().copied().map(to_f32).collect()).collect();
299            let lines = line_set(&polylines);
300            let fill = triangle_mesh(&drawn.arrows);
301            if lines.is_none() && fill.is_none() {
302                continue;
303            }
304            annotations += 1;
305            let base = format!("PMI {} {}", view.id, row.id);
306            if let Some(lines) = lines {
307                let material = material_index(&mut scene, PMI_RGB, true);
308                let name = node_name(&base, &mut taken);
309                scene.models.push(Model { name, geometry: Geometry::Lines(lines), shaders: vec![material], two_sided: false });
310                owners.push(Owner::View(view.id.clone()));
311            }
312            if let Some(fill) = fill {
313                let material = material_index(&mut scene, PMI_RGB, true);
314                let name = node_name(&format!("{base} fill"), &mut taken);
315                scene.models.push(Model { name, geometry: Geometry::Mesh(fill), shaders: vec![material], two_sided: true });
316                owners.push(Owner::View(view.id.clone()));
317            }
318        }
319    }
320
321    let u3d = u3d::write(&scene)?;
322    let nodes: Vec<String> = scene.models.iter().map(|model| model.name.clone()).collect();
323    let mut views: Vec<View3d> = cameras
324        .iter()
325        .map(|(view, camera)| {
326            // The stream holds every solid where it was modelled; a view that
327            // explodes moves them by node, with the same resolved rows the
328            // viewport and the sheets pose by, step after step.
329            let rows = report.and_then(|report| report.view(&view.id));
330            let mut stages: std::collections::HashMap<&str, Vec<PmiPose>> = std::collections::HashMap::new();
331            for row in rows.into_iter().flat_map(|rows| &rows.annotations) {
332                if !row.enabled || row.status != PmiStatus::Ok {
333                    continue;
334                }
335                if let PmiGeometry::Explode { solids, translate, rotate_deg, scale, center, .. } = &row.geometry {
336                    for solid in solids {
337                        stages.entry(solid.as_str()).or_default().push(PmiPose {
338                            center: *center,
339                            translate: *translate,
340                            rotate_deg: *rotate_deg,
341                            scale: *scale,
342                        });
343                    }
344                }
345            }
346            View3d {
347                id: view.id.clone(),
348                name: if view.name.trim().is_empty() { view.id.clone() } else { view.name.clone() },
349                camera: (*camera).clone(),
350                wireframe: view.display.wireframe,
351                visible: owners
352                    .iter()
353                    .map(|owner| match owner {
354                        Owner::Solid(solid) => !view.hides(solid),
355                        Owner::View(id) => *id == view.id,
356                    })
357                    .collect(),
358                poses: owners
359                    .iter()
360                    .map(|owner| match owner {
361                        Owner::Solid(solid) => stages.get(solid.as_str()).map(|stages| stage_matrix(stages)),
362                        Owner::View(_) => None,
363                    })
364                    .collect(),
365                section: view.section_plane_in(rows),
366            }
367        })
368        .collect();
369    // A document with no saved view still opens on SOMETHING: an isometric
370    // view fitted to the solids, every solid shown.
371    if views.is_empty() {
372        views.push(View3d {
373            id: ISOMETRIC.into(),
374            name: "Isometric".into(),
375            camera: isometric_camera(bodies),
376            wireframe: false,
377            visible: owners.iter().map(|owner| matches!(owner, Owner::Solid(_))).collect(),
378            poses: vec![None; owners.len()],
379            section: None,
380        });
381    }
382    Ok(Model3d { u3d, nodes, views, annotations })
383}
384
385/// One annotation laid out in world space as a 3D view draws it.
386#[derive(Debug, Clone, Default, PartialEq)]
387pub struct DrawnAnnotation {
388    /// Dimension, extension and leader lines, frames, and the text stroked
389    /// with the PMI font, as open polylines.
390    pub lines: Vec<Vec<[f64; 3]>>,
391    /// The filled arrowheads, as triangles.
392    pub arrows: Vec<[[f64; 3]; 3]>,
393}
394
395/// Every drawable annotation of a saved view (`rows`, its report) laid out
396/// for a 3D model shown from `camera`: sized as the viewport sized them when
397/// the view was saved (the overlay's pixel sizes times the saved camera's
398/// world per pixel; a model-unit line cannot stay a constant size on screen,
399/// so this is exact at the view's own framing and scales with the model when
400/// the reader zooms), a view-aligned row laid out in the view-parallel plane
401/// through its label, facing the camera, as the STEP presentation lays it
402/// out. The 3D PDF and the instructions player both draw these.
403pub fn view_annotations<'a>(view: &PmiView, camera: &PmiCamera, rows: &'a brep_kernel::PmiViewReport) -> Vec<(&'a PmiAnnotationReport, DrawnAnnotation)> {
404    let Some((right, _, forward)) = camera_frame(camera) else { return Vec::new() };
405    let wpp = world_per_pixel(camera);
406    let text_height = TEXT_PX_AT_12PT * wpp * (view.display.text_size_pt / 12.0);
407    let style = PmiLayoutStyle { arrow: ARROW_PX * wpp, text_height, view_dir: forward, view_up: camera.up, plane: None };
408    let mut out = Vec::new();
409    for row in &rows.annotations {
410        if !drawable(row) {
411            continue;
412        }
413        let row_style = PmiLayoutStyle {
414            plane: row.plane.or(Some(PmiPlane { origin: row.label_world, normal: [-forward[0], -forward[1], -forward[2]], x_axis: right })),
415            ..style
416        };
417        // A weld callout draws its weld symbol, as the 3D view does.
418        let drawn = brep_kernel::feature_pipeline::pmi::weld_symbol::present_row(row, &row_style)
419            .unwrap_or_else(|| pmi_present(&row.geometry, row.label_world, &row.text, &row_style));
420        let mut lines: Vec<Vec<[f64; 3]>> = drawn.polylines.iter().chain(&drawn.frames).cloned().collect();
421        for run in &drawn.texts {
422            lines.extend(run.strokes());
423        }
424        lines.retain(|line| line.len() >= 2);
425        if lines.is_empty() && drawn.arrows.is_empty() {
426            continue;
427        }
428        out.push((row, DrawnAnnotation { lines, arrows: drawn.arrows }));
429    }
430    out
431}
432
433/// A solid's explode stages as a `/3DNode /M`: the matrix's three columns,
434/// then its translation, the order `/C2W` is written in. Every stage is
435/// affine, so the composition is read off where it takes the origin and the
436/// three unit points.
437pub fn stage_matrix(stages: &[PmiPose]) -> [f64; 12] {
438    let apply = |point: [f64; 3]| stages.iter().fold(point, |p, stage| stage.apply(p));
439    let origin = apply([0.0; 3]);
440    let mut matrix = [0.0; 12];
441    for (axis, unit) in [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]].into_iter().enumerate() {
442        let column = sub(apply(unit), origin);
443        matrix[axis * 3..axis * 3 + 3].copy_from_slice(&column);
444    }
445    matrix[9..].copy_from_slice(&origin);
446    matrix
447}
448
449/// A sectioned view's cut as the `/3DCrossSection` its `/SA` lists (PDF
450/// 1.7): centred on `point`, the default plane (normal +x) turned by `/O
451/// [null β γ]`, β about y then γ about z, onto `normal`. The plane itself is
452/// not drawn (`/PO 0`); its intersection with the model is. Which side a
453/// reader removes is not stated by the standard and has not been checked in
454/// a reader here.
455fn cross_section(point: [f64; 3], normal: [f64; 3]) -> String {
456    let n = unit(normal).unwrap_or([1.0, 0.0, 0.0]);
457    let beta = (-n[2]).clamp(-1.0, 1.0).asin().to_degrees();
458    let gamma = n[1].atan2(n[0]).to_degrees();
459    format!(
460        "<< /Type /3DCrossSection /C [{} {} {}] /O [null {} {}] /PO 0 /IV true >>",
461        num(point[0]),
462        num(point[1]),
463        num(point[2]),
464        num(beta),
465        num(gamma)
466    )
467}
468
469/// The id of the view a document without saved views opens on.
470pub const ISOMETRIC: &str = "ISOMETRIC";
471
472/// Looking down the (−1, −1, −1) diagonal at the solids' box centre, +Y up
473/// (the application's), orthographic, the bounding sphere filling the height.
474pub fn isometric_camera(bodies: &[Body]) -> PmiCamera {
475    let mut min = [f64::INFINITY; 3];
476    let mut max = [f64::NEG_INFINITY; 3];
477    for p in bodies.iter().flat_map(|body| body.positions.iter()) {
478        for axis in 0..3 {
479            min[axis] = min[axis].min(f64::from(p[axis]));
480            max[axis] = max[axis].max(f64::from(p[axis]));
481        }
482    }
483    if !min[0].is_finite() {
484        (min, max) = ([-1.0; 3], [1.0; 3]);
485    }
486    let centre = [(min[0] + max[0]) * 0.5, (min[1] + max[1]) * 0.5, (min[2] + max[2]) * 0.5];
487    let radius = (dot(sub(max, min), sub(max, min)).sqrt() * 0.5).max(1e-3);
488    let d = radius * 4.0 / 3f64.sqrt();
489    PmiCamera {
490        eye: [centre[0] + d, centre[1] + d, centre[2] + d],
491        target: centre,
492        up: [0.0, 1.0, 0.0],
493        projection: PmiProjection::Orthographic { half_height: radius * 1.1 },
494        viewport: [1280.0, 800.0],
495    }
496}
497
498/// A report row the 3D model draws: enabled, resolved, and not an explode
499/// or hide step (which move or hide solids rather than annotating them, and
500/// which the STEP presentation leaves out for the same reason).
501fn drawable(row: &PmiAnnotationReport) -> bool {
502    row.enabled && row.status == PmiStatus::Ok && !matches!(row.geometry, PmiGeometry::Explode { .. } | PmiGeometry::Hide { .. })
503}
504
505// ---------------------------------------------------------------------------
506// The PDF dictionaries
507// ---------------------------------------------------------------------------
508
509fn num(value: f64) -> String {
510    let text = format!("{value:.6}");
511    let text = text.trim_end_matches('0').trim_end_matches('.');
512    if text == "-0" || text.is_empty() {
513        "0".into()
514    } else {
515        text.into()
516    }
517}
518
519/// The 12-element camera-to-world matrix and the distance to the centre of
520/// orbit (the camera's target).
521pub fn c2w(camera: &PmiCamera) -> Option<([f64; 12], f64)> {
522    let (right, up, forward) = camera_frame(camera)?;
523    let y = if CAMERA_Y_UP { up } else { [-up[0], -up[1], -up[2]] };
524    let e = camera.eye;
525    let m = [right[0], right[1], right[2], y[0], y[1], y[2], forward[0], forward[1], forward[2], e[0], e[1], e[2]];
526    Some((m, dot(sub(camera.target, camera.eye), forward)))
527}
528
529/// A view's projection: a perspective camera keeps its field of view; an
530/// orthographic one is scaled so its saved half height fills half of a 3D
531/// box `box_height_pt` tall, unless `scale` fixes it.
532pub fn projection(camera: &PmiCamera, box_height_pt: f64, scale: Option<f64>) -> Projection3d {
533    match (&camera.projection, scale) {
534        (_, Some(scale)) => Projection3d::Orthographic { scale },
535        (PmiProjection::Perspective { fov_y_deg }, None) => Projection3d::Perspective { fov_y_deg: *fov_y_deg },
536        (PmiProjection::Orthographic { half_height }, None) => {
537            Projection3d::Orthographic { scale: box_height_pt * 0.5 / half_height.max(1e-9) }
538        }
539    }
540}
541
542/// A `/3DView` dictionary: `name` in the reader's menu, the view's camera,
543/// `projection`, its render mode, a CAD lighting scheme, and every node's
544/// visibility.
545pub fn view_dict(model: &Model3d, view: &View3d, name: &str, projection: Projection3d) -> String {
546    let (matrix, orbit) = c2w(&view.camera).unwrap_or(([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], 1.0));
547    let matrix: Vec<String> = matrix.iter().map(|v| num(*v)).collect();
548    let projection = match projection {
549        Projection3d::Orthographic { scale } => format!("<< /Subtype /O /OS {} >>", num(scale)),
550        Projection3d::Perspective { fov_y_deg } => {
551            format!("<< /Subtype /P /FOV {} /PS /H >>", num(fov_y_deg.clamp(1.0, 179.0)))
552        }
553    };
554    let nodes: Vec<String> = model
555        .nodes
556        .iter()
557        .zip(&view.visible)
558        .zip(view.poses.iter().chain(std::iter::repeat(&None)))
559        .map(|((node, visible), pose)| match pose {
560            Some(pose) => {
561                let pose: Vec<String> = pose.iter().map(|v| num(*v)).collect();
562                format!("<< /Type /3DNode /N ({}) /V {visible} /M [{}] >>", string_literal(node), pose.join(" "))
563            }
564            None => format!("<< /Type /3DNode /N ({}) /V {visible} >>", string_literal(node)),
565        })
566        .collect();
567    let section = view
568        .section
569        .map(|(point, normal)| format!(" /SA [{}]", cross_section(point, normal)))
570        .unwrap_or_default();
571    format!(
572        "<< /Type /3DView /XN ({}) /IN ({}) /MS /M /C2W [{}] /CO {} /P {} \
573         /BG << /Type /3DBG /Subtype /SC /C [1 1 1] >> \
574         /RM << /Type /3DRenderMode /Subtype /{} >> \
575         /LS << /Type /3DLightingScheme /Subtype /Hard >>{} /NR true /NA [{}] >>",
576        string_literal(name),
577        string_literal(&view.id),
578        matrix.join(" "),
579        num(orbit.max(0.0)),
580        projection,
581        if view.wireframe { "Wireframe" } else { "Solid" },
582        section,
583        nodes.join(" ")
584    )
585}
586
587/// The 3D stream: every saved view in `/VA`, the default the first, and the
588/// U3D bytes ASCII85-encoded so the file stays ASCII (the PDF writer's
589/// contract).
590pub fn stream_object(model: &Model3d, va_box_height_pt: f64) -> String {
591    let views: Vec<String> = model
592        .views
593        .iter()
594        .map(|view| view_dict(model, view, &view.name, projection(&view.camera, va_box_height_pt, None)))
595        .collect();
596    // The stream's data ends with its own newline, counted in /Length — the
597    // PDF writer's convention for every stream it writes.
598    let data = ascii85(&model.u3d) + "\n";
599    format!(
600        "<< /Type /3D /Subtype /U3D /Filter /ASCII85Decode /DV 0 /VA [{}] /Length {} >>\nstream\n{}endstream",
601        views.join(" "),
602        data.len(),
603        data
604    )
605}
606
607/// ASCII85 (ISO 32000-1 §7.4.3), `~>`-terminated, in 76-character lines.
608pub fn ascii85(bytes: &[u8]) -> String {
609    let mut out = String::with_capacity(bytes.len() * 5 / 4 + bytes.len() / 60 + 4);
610    let mut column = 0;
611    let mut push = |c: char, out: &mut String| {
612        out.push(c);
613        column += 1;
614        if column == 76 {
615            out.push('\n');
616            column = 0;
617        }
618    };
619    for chunk in bytes.chunks(4) {
620        let mut word = [0u8; 4];
621        word[..chunk.len()].copy_from_slice(chunk);
622        let value = u32::from_be_bytes(word);
623        if chunk.len() == 4 && value == 0 {
624            push('z', &mut out);
625            continue;
626        }
627        let mut digits = [0u8; 5];
628        let mut v = value;
629        for digit in digits.iter_mut().rev() {
630            *digit = (v % 85) as u8;
631            v /= 85;
632        }
633        for digit in &digits[..chunk.len() + 1] {
634            push((b'!' + digit) as char, &mut out);
635        }
636    }
637    out.push_str("~>");
638    out
639}
640
641/// A 3D annotation's rectangle in PDF points: centred on `centre_mm` (sheet
642/// millimetres from the top-left), `half_mm` either way, on a page
643/// `page_height_mm` tall.
644pub fn rect_pt(centre_mm: [f64; 2], half_mm: [f64; 2], page_height_mm: f64) -> [f64; 4] {
645    [
646        (centre_mm[0] - half_mm[0]) * PT_PER_MM,
647        (page_height_mm - centre_mm[1] - half_mm[1]) * PT_PER_MM,
648        (centre_mm[0] + half_mm[0]) * PT_PER_MM,
649        (page_height_mm - centre_mm[1] + half_mm[1]) * PT_PER_MM,
650    ]
651}
652
653// ---------------------------------------------------------------------------
654// Where the model is shown
655// ---------------------------------------------------------------------------
656
657/// Everything 3D a sheet PDF carries.
658#[derive(Debug, Clone)]
659pub struct Pdf3d {
660    pub model: Model3d,
661    pub placements: Vec<Placement3d>,
662    /// A last page given over to the model.
663    pub page: Option<Page3d>,
664}
665
666/// A placement drawn live: a 3D box over the placement's drawing, opening on
667/// the placement's own camera at the placement's own scale, so activating it
668/// changes nothing until the reader turns the model.
669#[derive(Debug, Clone, PartialEq)]
670pub struct Placement3d {
671    /// The sheet's index among the file's pages.
672    pub page: usize,
673    /// The placement id (`SV2`).
674    pub id: String,
675    /// The saved view it places (`VIEW1`).
676    pub view: String,
677    /// Sheet millimetres from the top-left: the camera target's point, and the
678    /// box's half extents about it.
679    pub centre_mm: [f64; 2],
680    pub half_mm: [f64; 2],
681    /// Paper millimetres per model unit.
682    pub scale: f64,
683}
684
685/// A view button on the 3D page.
686#[derive(Debug, Clone, PartialEq)]
687pub struct Button {
688    /// `[x0, y0, x1, y1]`, sheet millimetres from the top-left.
689    pub rect_mm: [f64; 4],
690    pub label: String,
691    /// The view's index in [`Model3d::views`] (and so in `/VA`).
692    pub view: usize,
693}
694
695/// The 3D page: a title, the 3D box, a button per saved view, a caption.
696#[derive(Debug, Clone)]
697pub struct Page3d {
698    pub width_mm: f64,
699    pub height_mm: f64,
700    pub title: String,
701    pub title_at: [f64; 2],
702    pub title_mm: f64,
703    /// `[x0, y0, x1, y1]` of the 3D box, sheet millimetres from the top-left.
704    pub box_mm: [f64; 4],
705    /// The view the box opens on — the first saved view with a camera.
706    pub default_view: usize,
707    /// The default view drawn as a sheet placement at the centre of the box —
708    /// what a reader without 3D shows. `None` when there is nothing to draw.
709    pub poster: Option<ViewDrawing>,
710    /// The poster's scale (paper millimetres per model unit): the box opens at
711    /// it, so activating the model does not jump.
712    pub poster_scale: Option<f64>,
713    pub buttons: Vec<Button>,
714    pub button_text_mm: f64,
715    pub caption: Vec<String>,
716    pub caption_at: Vec<[f64; 2]>,
717    pub caption_mm: f64,
718}
719
720use super::project::ViewDrawing;
721
722const PAGE_MARGIN_MM: f64 = 12.0;
723const TITLE_MM: f64 = 5.0;
724const BUTTON_H_MM: f64 = 8.0;
725const BUTTON_GAP_MM: f64 = 3.0;
726const BUTTON_TEXT_MM: f64 = 2.8;
727const BUTTONS_PER_ROW: usize = 8;
728const CAPTION_MM: f64 = 2.8;
729
730/// The paragraph under the 3D box — the truth about who can show it.
731pub const CAPTION: [&str; 2] = [
732    "Interactive 3D model: open this file in Adobe Acrobat or Reader (with 3D content enabled) or in Foxit to rotate, zoom and switch PMI views.",
733    "Other PDF viewers show the drawing above in place of the model.",
734];
735
736impl Page3d {
737    /// The page laid out on paper `width_mm` × `height_mm`: the title at the
738    /// top, the caption at the foot, a row of buttons above it (wrapping
739    /// every `BUTTONS_PER_ROW`), and the box filling what is left.
740    pub fn layout(width_mm: f64, height_mm: f64, title: &str, model: &Model3d) -> Page3d {
741        let (w, h) = (width_mm.max(100.0), height_mm.max(100.0));
742        let inner = w - 2.0 * PAGE_MARGIN_MM;
743        let caption_at: Vec<[f64; 2]> = (0..CAPTION.len())
744            .map(|line| [w * 0.5, h - PAGE_MARGIN_MM - (CAPTION.len() - 1 - line) as f64 * CAPTION_MM * 1.8])
745            .collect();
746        let rows = model.views.len().div_ceil(BUTTONS_PER_ROW);
747        let per_row = model.views.len().min(BUTTONS_PER_ROW).max(1);
748        let button_w = ((inner - (per_row - 1) as f64 * BUTTON_GAP_MM) / per_row as f64).min(48.0);
749        let buttons_bottom = caption_at[0][1] - CAPTION_MM * 2.0;
750        let buttons_top = buttons_bottom - rows as f64 * (BUTTON_H_MM + BUTTON_GAP_MM) + BUTTON_GAP_MM;
751        let buttons = model
752            .views
753            .iter()
754            .enumerate()
755            .map(|(index, view)| {
756                let (row, column) = (index / BUTTONS_PER_ROW, index % BUTTONS_PER_ROW);
757                let in_row = (model.views.len() - row * BUTTONS_PER_ROW).min(BUTTONS_PER_ROW);
758                let row_w = in_row as f64 * button_w + (in_row - 1) as f64 * BUTTON_GAP_MM;
759                let x0 = (w - row_w) * 0.5 + column as f64 * (button_w + BUTTON_GAP_MM);
760                let y0 = buttons_top + row as f64 * (BUTTON_H_MM + BUTTON_GAP_MM);
761                Button { rect_mm: [x0, y0, x0 + button_w, y0 + BUTTON_H_MM], label: view.name.clone(), view: index }
762            })
763            .collect();
764        let box_top = PAGE_MARGIN_MM + TITLE_MM * 2.0;
765        let box_bottom = if rows > 0 { buttons_top - BUTTON_GAP_MM * 2.0 } else { buttons_bottom };
766        Page3d {
767            width_mm: w,
768            height_mm: h,
769            title: title.to_string(),
770            title_at: [w * 0.5, PAGE_MARGIN_MM + TITLE_MM * 0.5],
771            title_mm: TITLE_MM,
772            box_mm: [PAGE_MARGIN_MM, box_top, w - PAGE_MARGIN_MM, box_bottom.max(box_top + 20.0)],
773            default_view: 0,
774            poster: None,
775            poster_scale: None,
776            buttons,
777            button_text_mm: BUTTON_TEXT_MM,
778            caption: CAPTION.iter().map(|line| line.to_string()).collect(),
779            caption_at,
780            caption_mm: CAPTION_MM,
781        }
782    }
783
784    pub fn box_centre_mm(&self) -> [f64; 2] {
785        [(self.box_mm[0] + self.box_mm[2]) * 0.5, (self.box_mm[1] + self.box_mm[3]) * 0.5]
786    }
787
788    pub fn box_half_mm(&self) -> [f64; 2] {
789        [(self.box_mm[2] - self.box_mm[0]) * 0.5, (self.box_mm[3] - self.box_mm[1]) * 0.5]
790    }
791}
792
793/// The object numbers of every 3D object, assigned before any is written so
794/// the page dictionaries can name their annotations.
795#[derive(Debug, Clone)]
796pub struct Plan {
797    stream: usize,
798    /// Per placement: (annotation, appearance).
799    placements: Vec<(usize, usize)>,
800    /// The 3D page's (annotation, appearance, links).
801    page: Option<(usize, usize, Vec<usize>)>,
802    /// Which page each placement sits on.
803    placement_pages: Vec<usize>,
804    /// The 3D page's index among the file's pages.
805    page_index: usize,
806}
807
808fn rect_text(r: [f64; 4]) -> String {
809    format!("[{:.4} {:.4} {:.4} {:.4}]", r[0], r[1], r[2], r[3])
810}
811
812/// An appearance that draws nothing: the page's own marks show through until
813/// the reader activates the model.
814fn empty_appearance(rect: [f64; 4]) -> String {
815    format!(
816        "<< /Type /XObject /Subtype /Form /BBox [0 0 {:.4} {:.4}] /Length 1 >>\nstream\n\nendstream",
817        rect[2] - rect[0],
818        rect[3] - rect[1]
819    )
820}
821
822impl Plan {
823    /// Numbers from `next` on, for the 3D content of `three_d` in a file of
824    /// `sheets` sheet pages (the 3D page, when there is one, follows them).
825    pub fn new(three_d: &Pdf3d, mut next: usize, sheets: usize) -> Plan {
826        let stream = next;
827        next += 1;
828        let placements = three_d
829            .placements
830            .iter()
831            .map(|_| {
832                next += 2;
833                (next - 2, next - 1)
834            })
835            .collect();
836        let page = three_d.page.as_ref().map(|page| {
837            let annot = next;
838            let links = (0..page.buttons.len()).map(|i| annot + 2 + i).collect::<Vec<_>>();
839            next += 2 + page.buttons.len();
840            (annot, annot + 1, links)
841        });
842        Plan {
843            stream,
844            placements,
845            page,
846            placement_pages: three_d.placements.iter().map(|p| p.page).collect(),
847            page_index: sheets,
848        }
849    }
850
851    /// ` /Annots […]` for page `index` (a sheet, or — one past the sheets —
852    /// the 3D page), or nothing when it carries none.
853    pub fn annots_on(&self, index: usize) -> String {
854        let mut refs: Vec<String> = self
855            .placements
856            .iter()
857            .zip(&self.placement_pages)
858            .filter(|(_, page)| **page == index)
859            .map(|((annot, _), _)| format!("{annot} 0 R"))
860            .collect();
861        if let Some((annot, _, links)) = &self.page {
862            if index == self.page_index {
863                refs.push(format!("{annot} 0 R"));
864                refs.extend(links.iter().map(|link| format!("{link} 0 R")));
865            }
866        }
867        if refs.is_empty() {
868            String::new()
869        } else {
870            format!(" /Annots [{}]", refs.join(" "))
871        }
872    }
873
874    /// Every 3D object, in object-number order: the stream, each placement's
875    /// annotation and appearance, the 3D page's.
876    pub fn objects(&self, three_d: &Pdf3d, pages: &[&super::project::SheetDrawing], first_page: usize) -> Vec<(usize, String)> {
877        let model = &three_d.model;
878        let placement_box_pt = three_d
879            .placements
880            .iter()
881            .map(|placement| placement.half_mm[1] * 2.0 * PT_PER_MM)
882            .fold(0.0f64, f64::max);
883        let va_box_pt = match &three_d.page {
884            Some(page) => page.box_half_mm()[1] * 2.0 * PT_PER_MM,
885            None if placement_box_pt > 0.0 => placement_box_pt,
886            None => 400.0,
887        };
888        let mut out = vec![(self.stream, stream_object(model, va_box_pt))];
889        for (placement, (annot, appearance)) in three_d.placements.iter().zip(&self.placements) {
890            let page_h = pages.get(placement.page).map_or(297.0, |page| page.height_mm.max(1.0));
891            let rect = rect_pt(placement.centre_mm, placement.half_mm, page_h);
892            let view = model.view(&placement.view);
893            let default = match view {
894                Some(view) => view_dict(
895                    model,
896                    view,
897                    &format!("{} {}", placement.id, view.name),
898                    Projection3d::Orthographic { scale: placement.scale * PT_PER_MM },
899                ),
900                None => "0".to_string(),
901            };
902            out.push((
903                *annot,
904                format!(
905                    "<< /Type /Annot /Subtype /3D /Rect {} /F 4 /P {} 0 R /NM ({}) \
906                     /Contents (Click to turn this view in 3D: {}) /3DD {} 0 R /3DV {} \
907                     /3DA << /A /XA /D /PC /TB true /NP false >> /AP << /N {} 0 R >> >>",
908                    rect_text(rect),
909                    first_page + placement.page * 2,
910                    string_literal(&placement.id),
911                    string_literal(&view.map_or(placement.view.clone(), |view| view.name.clone())),
912                    self.stream,
913                    default,
914                    appearance
915                ),
916            ));
917            out.push((*appearance, empty_appearance(rect)));
918        }
919        if let (Some(page), Some((annot, appearance, links))) = (&three_d.page, &self.page) {
920            let page_number = first_page + self.page_index * 2;
921            let rect = rect_pt(page.box_centre_mm(), page.box_half_mm(), page.height_mm);
922            let default = match (model.views.get(page.default_view), page.poster_scale) {
923                (Some(view), Some(scale)) => {
924                    view_dict(model, view, &view.name, Projection3d::Orthographic { scale: scale * PT_PER_MM })
925                }
926                _ => page.default_view.to_string(),
927            };
928            out.push((
929                *annot,
930                format!(
931                    "<< /Type /Annot /Subtype /3D /Rect {} /F 4 /P {page_number} 0 R /NM (MODEL3D) \
932                     /Contents (The 3D model with its PMI views) /3DD {} 0 R /3DV {default} \
933                     /3DA << /A /PO /D /PC /TB true /NP true >> /AP << /N {appearance} 0 R >> >>",
934                    rect_text(rect),
935                    self.stream
936                ),
937            ));
938            out.push((*appearance, empty_appearance(rect)));
939            for (button, link) in page.buttons.iter().zip(links) {
940                let [x0, y0, x1, y1] = button.rect_mm;
941                let r = rect_pt([(x0 + x1) * 0.5, (y0 + y1) * 0.5], [(x1 - x0) * 0.5, (y1 - y0) * 0.5], page.height_mm);
942                out.push((
943                    *link,
944                    format!(
945                        "<< /Type /Annot /Subtype /Link /Rect {} /Border [0 0 0] /P {page_number} 0 R \
946                         /A << /S /GoTo3DView /TA {annot} 0 R /V {} >> >>",
947                        rect_text(r),
948                        button.view
949                    ),
950                ));
951            }
952        }
953        out
954    }
955}
956
957/// What a PDF carries in 3D, read back from its bytes: the count of 3D
958/// annotations, of views in the stream's `/VA`, of view links, and the U3D
959/// stream's decoded size — what the export door reports about the file.
960#[derive(Debug, Clone, Default, PartialEq, serde::Serialize)]
961pub struct Summary {
962    pub annotations: usize,
963    pub views: usize,
964    pub links: usize,
965    #[serde(rename = "u3dBytes")]
966    pub u3d_bytes: usize,
967}
968
969/// [`Summary`] of a file this module wrote; `None` when it carries no 3D.
970pub fn summary(pdf: &[u8]) -> Option<Summary> {
971    let text = String::from_utf8_lossy(pdf);
972    let stream_at = text.find("/Subtype /U3D")?;
973    let dict_end = text[stream_at..].find("\nstream\n")? + stream_at;
974    let dict = &text[stream_at..dict_end];
975    let data_start = dict_end + "\nstream\n".len();
976    let data_end = text[data_start..].find("~>")? + data_start;
977    let data = &text[data_start..data_end];
978    let mut u3d_bytes = 0;
979    let mut group = 0;
980    for c in data.chars().filter(|c| !c.is_whitespace()) {
981        if c == 'z' {
982            u3d_bytes += 4;
983        } else {
984            group += 1;
985            if group == 5 {
986                u3d_bytes += 4;
987                group = 0;
988            }
989        }
990    }
991    if group > 0 {
992        u3d_bytes += group - 1;
993    }
994    Some(Summary {
995        annotations: text.matches("/Subtype /3D /Rect").count(),
996        views: dict.matches("/Type /3DView").count(),
997        links: text.matches("/S /GoTo3DView").count(),
998        u3d_bytes,
999    })
1000}
1001