Skip to main content

xpict_core/
depict.rs

1//! Single-molecule depiction: [`MoleculeIn`] → [`Scene`].
2//!
3//! Caller supplies SVG-space coords (+ optional shade / atom labels). Shade uses
4//! the xenosite rainbow LUT; halo knocks out white channels through shade for
5//! bond/label ink. Publication circles are [`crate::doc`] chrome on `MolNode`.
6
7use std::collections::HashMap;
8
9use crate::bonds::{bond_strokes, join_centered_multibonds, DrawnBond, StrokePath};
10use crate::colormap::colormap_rgb;
11use crate::debug_align::paint_align_debug;
12use crate::debug_box::{label_debug_rect, mol_debug_rect, scene_debug_rect};
13use crate::font::FaceStyle;
14use crate::labels::{self, place_backbone};
15use crate::metrics::{
16    halo_gap_for_weight, halo_stroke_for_weight, label_weight_grow_px, stroke_px_for_weight,
17    BOND_PX, FONT_PX, HALO_OPACITY, PAD_PX, SHADE_BOTH_FRAC, SHADE_FRAC,
18};
19use crate::plotdot::PlotDot;
20use crate::rings::{aromatic_ring_circles, bond_interior_normals, find_sssr, kekule_paint_orders};
21use crate::scene::{
22    AromaticStyle, AtomIn, Layer, LayerName, MoleculeIn, Primitive, Scene, Viewport,
23};
24
25/// Paint one molecule into a single-viewport [`Scene`].
26///
27/// Layers (bottom → top): shading → halo → bonds → labels. Chrome annotations
28/// (regions, circles, callouts) join those layers on the same viewport so a
29/// mol-group transform applies to the whole tree. [`depict_molecule`] scales
30/// after chem paint; the document path scales once after chrome + captions.
31pub fn frame_offset(mol: &MoleculeIn) -> (f64, f64) {
32    let mut min_x = f64::INFINITY;
33    let mut min_y = f64::INFINITY;
34    let mut max_x = f64::NEG_INFINITY;
35    let mut max_y = f64::NEG_INFINITY;
36    for a in &mol.atoms {
37        min_x = min_x.min(a.x);
38        min_y = min_y.min(a.y);
39        max_x = max_x.max(a.x);
40        max_y = max_y.max(a.y);
41    }
42    if mol.atoms.is_empty() {
43        min_x = 0.0;
44        min_y = 0.0;
45        max_x = 0.0;
46        max_y = 0.0;
47    }
48    let label_pad = FONT_PX * 0.85;
49    for a in &mol.atoms {
50        if display_label(a).is_some() {
51            min_x = min_x.min(a.x - label_pad);
52            max_x = max_x.max(a.x + label_pad * 1.6);
53            min_y = min_y.min(a.y - label_pad);
54            max_y = max_y.max(a.y + label_pad);
55        }
56    }
57    let pad = PAD_PX;
58    (pad - min_x, pad - min_y)
59}
60
61pub fn depict_molecule(mol: &MoleculeIn) -> Scene {
62    depict_chem(mol).scale_uniform(mol.diagram_scale())
63}
64
65/// Chem ink in framed SVG space, **unscaled**. Document paint applies chrome
66/// and captions here, then one [`Scene::scale_uniform`] so annotations share
67/// `mol.scale`.
68pub(crate) fn depict_chem(mol: &MoleculeIn) -> Scene {
69    let color = mol.color.as_deref().unwrap_or("#111");
70    let face = FaceStyle::Regular;
71    // User-facing weight (default 1 = house). Helpers convert via diagram_weight.
72    let weight = mol.weight;
73    let _ = mol.diagram_weight(); // validate early
74    let stroke_px = stroke_px_for_weight(weight);
75    let label_grow = label_weight_grow_px(weight);
76    let by_index: HashMap<i32, usize> = mol
77        .atoms
78        .iter()
79        .enumerate()
80        .map(|(i, a)| (a.index, i))
81        .collect();
82
83    let (dx, dy) = frame_offset(mol);
84    let mut min_x = f64::INFINITY;
85    let mut min_y = f64::INFINITY;
86    let mut max_x = f64::NEG_INFINITY;
87    let mut max_y = f64::NEG_INFINITY;
88    for a in &mol.atoms {
89        min_x = min_x.min(a.x);
90        min_y = min_y.min(a.y);
91        max_x = max_x.max(a.x);
92        max_y = max_y.max(a.y);
93    }
94    if mol.atoms.is_empty() {
95        min_x = 0.0;
96        min_y = 0.0;
97        max_x = 0.0;
98        max_y = 0.0;
99    }
100    let label_pad = FONT_PX * 0.85;
101    for a in &mol.atoms {
102        if display_label(a).is_some() {
103            min_x = min_x.min(a.x - label_pad);
104            max_x = max_x.max(a.x + label_pad * 1.6);
105            min_y = min_y.min(a.y - label_pad);
106            max_y = max_y.max(a.y + label_pad);
107        }
108    }
109    let pad = PAD_PX;
110    let mut width = (max_x - min_x) + 2.0 * pad;
111    let mut height = (max_y - min_y) + 2.0 * pad;
112
113    let label_atoms: Vec<labels::AtomIn> = mol
114        .atoms
115        .iter()
116        .map(|a| labels::AtomIn {
117            x: a.x + dx,
118            y: a.y + dy,
119            label: display_label(a),
120        })
121        .collect();
122    let label_bonds: Vec<labels::BondIn> = mol
123        .bonds
124        .iter()
125        .map(|b| labels::BondIn {
126            begin: *by_index.get(&b.begin).unwrap_or(&0),
127            end: *by_index.get(&b.end).unwrap_or(&0),
128        })
129        .collect();
130    let (shortened, placed) = place_backbone(&label_atoms, &label_bonds, FONT_PX, face, weight);
131
132    // Ring bonds get interior normals → short inside offsets (not acyclic extend).
133    let ring_coords: HashMap<i32, (f64, f64)> = mol
134        .atoms
135        .iter()
136        .map(|a| (a.index, (a.x + dx, a.y + dy)))
137        .collect();
138    let rings = find_sssr(mol, 8);
139    let ring_normals = bond_interior_normals(&rings, &ring_coords);
140    let paint_orders = match mol.aromatic {
141        AromaticStyle::Kekule => Some(kekule_paint_orders(mol, &rings)),
142        AromaticStyle::Circle => None,
143    };
144
145    let mut prepared: Vec<DrawnBond> = Vec::new();
146    for (bond, ends) in mol.bonds.iter().zip(shortened.iter()) {
147        if !by_index.contains_key(&bond.begin) || !by_index.contains_key(&bond.end) {
148            continue;
149        }
150        let i0 = by_index[&bond.begin];
151        let i1 = by_index[&bond.end];
152        let key = if bond.begin < bond.end {
153            (bond.begin, bond.end)
154        } else {
155            (bond.end, bond.begin)
156        };
157        let order = paint_orders
158            .as_ref()
159            .and_then(|m| m.get(&key).copied())
160            .unwrap_or(bond.order);
161        let mut db = DrawnBond::new(
162            bond.index, bond.begin, bond.end, ends.x1, ends.y1, ends.x2, ends.y2, order,
163        );
164        db.stereo = bond.stereo.clone();
165        // Ring membership overrules centered/extend; else keep caller interior.
166        db.interior = ring_normals.get(&key).copied().or(bond.interior);
167        db.begin_labeled = placed[i0].is_some();
168        db.end_labeled = placed[i1].is_some();
169        prepared.push(db);
170    }
171    join_centered_multibonds(&mut prepared);
172
173    let mut bond_prims: Vec<Primitive> = Vec::new();
174    let mut bond_strokes_for_halo: Vec<StrokePath> = Vec::new();
175    for bond in &prepared {
176        let strokes = bond_strokes(
177            bond.x1,
178            bond.y1,
179            bond.x2,
180            bond.y2,
181            bond.order,
182            bond.interior,
183            bond.stereo.as_deref(),
184            bond.trims.as_ref(),
185            Some(stroke_px),
186        );
187        let tag = format!("bond-{} atom-{} atom-{}", bond.index, bond.begin, bond.end);
188        for sp in strokes.paint_order() {
189            bond_strokes_for_halo.push((*sp).clone());
190        }
191        for mut p in strokes.into_primitives(color) {
192            if let Primitive::Path { ref mut class, .. } = p {
193                if let Some(c) = class.take() {
194                    *class = Some(format!("{tag} {c}"));
195                } else {
196                    *class = Some(tag.clone());
197                }
198            }
199            bond_prims.push(p);
200        }
201    }
202    if mol.aromatic == AromaticStyle::Circle {
203        for (cx, cy, r) in aromatic_ring_circles(mol, &rings, &ring_coords) {
204            bond_prims.push(Primitive::Circle {
205                cx,
206                cy,
207                r,
208                fill: None,
209                stroke: Some(color.to_string()),
210                stroke_width: stroke_px,
211                opacity: 1.0,
212                class: Some("aromatic".into()),
213            });
214        }
215    }
216
217    let mut label_prims: Vec<Primitive> = Vec::new();
218    let mut label_ink_for_halo: Vec<crate::geom::Shape> = Vec::new();
219    for (slot, pl) in placed.iter().enumerate() {
220        let Some(pl) = pl else { continue };
221        let atom_index = mol.atoms[slot].index;
222        // Grow canvas if traveling text spills past the initial pad.
223        width =
224            width.max(pl.origin_x + FONT_PX * pl.text.chars().count() as f64 * 0.65 + pad * 0.25);
225        height = height.max(pl.y + FONT_PX * 0.35 + pad * 0.25);
226        if matches!(pl.side, labels::LabelSide::North | labels::LabelSide::South) {
227            height = height.max(pl.atom_y + FONT_PX * 1.6 + pad * 0.25);
228        }
229        let Some(mut ink) = labels::label_ink_shape(pl, FONT_PX, face) else {
230            continue;
231        };
232        if label_grow > 1e-9 {
233            ink = ink.buffer(label_grow);
234        }
235        let d = ink.to_svg_d();
236        label_ink_for_halo.push(ink);
237        if d.is_empty() {
238            continue;
239        }
240        label_prims.push(Primitive::Path {
241            d,
242            stroke: Some("none".into()),
243            fill: Some(color.to_string()),
244            stroke_width: 0.0,
245            opacity: 1.0,
246            stroke_dasharray: None,
247            stroke_linecap: None,
248            class: Some(format!("atom-{atom_index} label")),
249            data_text: Some(pl.text.clone()),
250        });
251    }
252
253    let shade_prims = paint_shade(mol, &by_index, dx, dy);
254    let halo_prims = paint_halo(
255        &bond_strokes_for_halo,
256        &label_ink_for_halo,
257        stroke_px,
258        weight,
259    );
260
261    let mut debug_prims: Vec<Primitive> = Vec::new();
262    if mol.debug_box {
263        // Label ink AABBs only — never wrap bond/atom stroke primitives.
264        // `label_ink_for_halo` is pushed in the same order as non-None `placed`.
265        let mut ink_i = 0usize;
266        for (slot, pl) in placed.iter().enumerate() {
267            if pl.is_none() {
268                continue;
269            }
270            if ink_i >= label_ink_for_halo.len() {
271                break;
272            }
273            let ink = &label_ink_for_halo[ink_i];
274            ink_i += 1;
275            if let Some((x0, y0, x1, y1)) = ink.bounds() {
276                debug_prims.push(label_debug_rect(x0, y0, x1, y1, mol.atoms[slot].index));
277            }
278        }
279        debug_prims.push(mol_debug_rect(width, height));
280    }
281    if mol.debug_align {
282        if let Some(ref ad) = mol.align_debug {
283            debug_prims.extend(paint_align_debug(&mol.atoms, ad, dx, dy, FONT_PX * 0.55));
284        }
285    }
286
287    let mut layers = Vec::new();
288    if !shade_prims.is_empty() {
289        layers.push(Layer {
290            name: LayerName::Shading,
291            primitives: shade_prims,
292        });
293    }
294    if !halo_prims.is_empty() {
295        layers.push(Layer {
296            name: LayerName::Halo,
297            primitives: halo_prims,
298        });
299    }
300    if !bond_prims.is_empty() {
301        layers.push(Layer {
302            name: LayerName::Bonds,
303            primitives: bond_prims,
304        });
305    }
306    if !label_prims.is_empty() {
307        layers.push(Layer {
308            name: LayerName::Labels,
309            primitives: label_prims,
310        });
311    }
312    if !debug_prims.is_empty() {
313        layers.push(Layer {
314            name: LayerName::Overlay,
315            primitives: debug_prims,
316        });
317    }
318    layers.sort_by_key(|l| l.name.paint_order());
319
320    let mut overlays = Vec::new();
321    if mol.debug_box {
322        // Document box for the single-mol scene (compose adds one for multi-mol).
323        overlays.push(scene_debug_rect(width, height));
324    }
325    let scene = Scene {
326        width,
327        height,
328        x: 0.0,
329        y: 0.0,
330        viewports: vec![Viewport {
331            id: mol.id.clone(),
332            x: 0.0,
333            y: 0.0,
334            ox: 0.0,
335            oy: 0.0,
336            width,
337            height,
338            layers,
339        }],
340        overlays,
341        halo: Vec::new(),
342    };
343    scene
344}
345
346/// Explicit ``label``, else heteroatom / charged symbol (carbons stay silent).
347///
348/// `label: Some("")` is an **explicit silence** (no element-symbol fallback).
349/// `label: None` still invents heteroatom / charged carbon text. Chem text is
350/// not owned by chrome annotations — replace via `star_labels` on `*` atoms.
351///
352/// Appends a charge suffix when the label body does not already include one
353/// (matches Python ``display_text``).
354fn display_label(a: &AtomIn) -> Option<String> {
355    let mut body = if let Some(ref l) = a.label {
356        let t = l.trim();
357        if t.is_empty() {
358            // Explicit empty silence.
359            return None;
360        }
361        Some(t.to_string())
362    } else {
363        None
364    };
365    if body.is_none() {
366        let sym = a.symbol();
367        if sym == "C" && a.charge == 0 {
368            return None;
369        }
370        body = Some(sym.to_string());
371    }
372    let mut body = body.unwrap();
373    let parsed_chg = labels::split_label(&body).charge;
374    if a.charge != 0 && parsed_chg == 0 {
375        let sign = if a.charge > 0 { "+" } else { "−" };
376        let mag = a.charge.unsigned_abs();
377        if mag == 1 {
378            body.push_str(sign);
379        } else {
380            body.push_str(&format!("{mag}{sign}"));
381        }
382    }
383    Some(body)
384}
385
386fn paint_shade(
387    mol: &MoleculeIn,
388    by_index: &HashMap<i32, usize>,
389    dx: f64,
390    dy: f64,
391) -> Vec<Primitive> {
392    let atom_zs = mol.atom_shade.as_deref().unwrap_or(&[]);
393    let bond_zs = mol.bond_shade.as_deref().unwrap_or(&[]);
394    if atom_zs.is_empty() && bond_zs.is_empty() {
395        return Vec::new();
396    }
397    // Fixed window by default — never auto-scale to the data range.
398    let vmin = mol.shade_vmin.unwrap_or(0.0);
399    let vmax = mol.shade_vmax.unwrap_or(1.0);
400    let diverging = vmin < 0.0 && vmax > 0.0;
401    let base_r = shade_base_radius_px(!atom_zs.is_empty(), !bond_zs.is_empty());
402    let plot = PlotDot::default();
403    // Atom + bond scores share one PlotDot pass so overlapping rings stack by
404    // strength (weak first → strong on top), matching xenopict shade().
405    let mut zs: Vec<f64> = Vec::new();
406    let mut coords: Vec<(f64, f64)> = Vec::new();
407    if !atom_zs.is_empty() {
408        for (a, &z) in mol.atoms.iter().zip(atom_zs.iter()) {
409            zs.push(z);
410            coords.push((a.x + dx, a.y + dy));
411        }
412    }
413    if !bond_zs.is_empty() {
414        for (bond, &z) in mol.bonds.iter().zip(bond_zs.iter()) {
415            let Some(&i0) = by_index.get(&bond.begin) else {
416                continue;
417            };
418            let Some(&i1) = by_index.get(&bond.end) else {
419                continue;
420            };
421            let a0 = &mol.atoms[i0];
422            let a1 = &mol.atoms[i1];
423            zs.push(z);
424            coords.push(((a0.x + a1.x) * 0.5 + dx, (a0.y + a1.y) * 0.5 + dy));
425        }
426    }
427    let norm = normalize_shade_scores(&zs, vmin, vmax);
428    let n = norm.len().min(coords.len());
429    let mut out = Vec::new();
430    for d in plot.disks(&norm[..n], &coords[..n]) {
431        if d.color_z.abs() < 0.05 && d.radius_frac < 0.35 {
432            continue;
433        }
434        if d.color_z.abs() < 0.02 {
435            continue;
436        }
437        out.push(Primitive::Circle {
438            cx: d.x,
439            cy: d.y,
440            r: base_r * d.radius_frac,
441            fill: Some(colormap_rgb(d.color_z, diverging)),
442            stroke: None,
443            stroke_width: 0.0,
444            opacity: 1.0,
445            class: Some("shade".into()),
446        });
447    }
448    out
449}
450
451pub(crate) fn normalize_shade_scores(zs: &[f64], vmin: f64, vmax: f64) -> Vec<f64> {
452    if vmin >= 0.0 && vmax > 0.0 {
453        return zs.iter().map(|&z| (z / vmax).clamp(0.0, 1.0)).collect();
454    }
455    if vmax <= 0.0 && vmin < 0.0 {
456        return zs
457            .iter()
458            .map(|&z| (z / vmin.abs()).clamp(-1.0, 0.0))
459            .collect();
460    }
461    let scale = vmin.abs().max(vmax.abs()).max(1e-9);
462    zs.iter().map(|&z| (z / scale).clamp(-1.0, 1.0)).collect()
463}
464
465/// Base radius for PlotDot shade (matches [`paint_shade`]).
466pub(crate) fn shade_base_radius_px(has_atom_shade: bool, has_bond_shade: bool) -> f64 {
467    BOND_PX
468        * (if has_atom_shade && has_bond_shade {
469            SHADE_BOTH_FRAC
470        } else {
471            SHADE_FRAC
472        })
473}
474
475/// Outer painted shade radius for one normalized score, or `None` if paint skips it.
476///
477/// Clash / Halo must use this — not the house max `SHADE_FRAC` disk.
478pub(crate) fn shade_outer_radius_px(norm_z: f64, base_r: f64) -> Option<f64> {
479    let plot = PlotDot::default();
480    let max_frac = plot
481        .rings(norm_z)
482        .into_iter()
483        .filter(|(r, c)| !(c.abs() < 0.05 && *r < 0.35) && c.abs() >= 0.02)
484        .map(|(r, _)| r)
485        .fold(0.0_f64, f64::max);
486    if max_frac <= 0.0 {
487        None
488    } else {
489        Some(base_r * max_frac)
490    }
491}
492
493/// White knockout under bonds/labels so shade disks don't cover ink.
494///
495/// xenopict: union of per-ink buffers at a weight-scaled gap (√weight vs linear
496/// ink), with a floor from halo stroke thickness. Requires the `geom` feature
497/// (WASM enables it via `font`).
498#[cfg(feature = "geom")]
499fn paint_halo(
500    bond_strokes: &[StrokePath],
501    label_ink: &[crate::geom::Shape],
502    stroke_px: f64,
503    weight: f64,
504) -> Vec<Primitive> {
505    use crate::geom::Shape;
506
507    let mut ink: Option<Shape> = None;
508    let mut absorb = |piece: Shape| {
509        if piece.is_empty() {
510            return;
511        }
512        ink = Some(match ink.take() {
513            Some(acc) => acc.union(&piece),
514            None => piece,
515        });
516    };
517
518    for sp in bond_strokes {
519        let pts = &sp.pts;
520        if pts.len() < 2 {
521            continue;
522        }
523        let ink_r = sp.stroke_width.max(stroke_px) * 0.5;
524        // Filled wedges: treat the polygon as ink; stroked lines → capsules.
525        if sp.fill.as_deref().is_some_and(|f| f != "none") && pts.len() >= 3 {
526            let poly = Shape::from_ring(&pts);
527            if !poly.is_empty() {
528                let grown = if ink_r > 0.0 {
529                    poly.buffer(ink_r)
530                } else {
531                    poly
532                };
533                absorb(grown);
534            }
535            continue;
536        }
537        for w in pts.windows(2) {
538            let (x1, y1) = w[0];
539            let (x2, y2) = w[1];
540            if (x1 - x2).hypot(y1 - y2) < 1e-6 {
541                continue;
542            }
543            absorb(Shape::capsule(x1, y1, x2, y2, ink_r));
544        }
545    }
546
547    for shape in label_ink {
548        absorb(shape.clone());
549    }
550
551    let Some(ink) = ink.filter(|s| !s.is_empty()) else {
552        return Vec::new();
553    };
554    // Match Python BondsDrawable: max(halo_gap(w), 0.25*halo_stroke(w) - ink_r).
555    let ink_r = stroke_px * 0.5;
556    let halo_stroke = halo_stroke_for_weight(weight);
557    let dist = halo_gap_for_weight(weight).max(0.25 * halo_stroke - ink_r);
558    let grown = ink.halo(dist);
559    if grown.is_empty() {
560        return Vec::new();
561    }
562    let d = grown.to_svg_d();
563    if d.is_empty() {
564        return Vec::new();
565    }
566    vec![Primitive::Path {
567        d,
568        stroke: Some("none".into()),
569        fill: Some("#fff".into()),
570        stroke_width: 0.0,
571        opacity: HALO_OPACITY,
572        stroke_dasharray: None,
573        stroke_linecap: None,
574        class: Some("halo".into()),
575        data_text: None,
576    }]
577}
578
579#[cfg(not(feature = "geom"))]
580fn paint_halo(
581    _bond_strokes: &[StrokePath],
582    _label_ink: &[crate::geom::Shape],
583    _stroke_px: f64,
584    _weight: f64,
585) -> Vec<Primitive> {
586    Vec::new()
587}
588
589#[cfg(test)]
590mod tests {
591    use super::*;
592    use crate::scene::{AtomIn, BondIn};
593
594    fn atom(index: i32, element: &str, x: f64, y: f64, label: Option<&str>) -> AtomIn {
595        AtomIn {
596            index,
597            element: Some(element.into()),
598            z: None,
599            x,
600            y,
601            label: label.map(str::to_string),
602            charge: 0,
603            mapno: None,
604        }
605    }
606
607    fn ethanol() -> MoleculeIn {
608        MoleculeIn {
609            id: Some("etoh".into()),
610            atoms: vec![
611                atom(0, "C", 0.0, 0.0, None),
612                atom(1, "C", 20.0, 0.0, None),
613                atom(2, "O", 30.0, 10.0, Some("OH")),
614            ],
615            bonds: vec![
616                BondIn {
617                    index: 0,
618                    begin: 0,
619                    end: 1,
620                    order: 1.0,
621                    stereo: None,
622                    interior: None,
623                },
624                BondIn {
625                    index: 1,
626                    begin: 1,
627                    end: 2,
628                    order: 1.0,
629                    stereo: None,
630                    interior: None,
631                },
632            ],
633            color: None,
634            atom_shade: None,
635            bond_shade: None,
636            shade_vmin: None,
637            shade_vmax: None,
638            weight: 1.0,
639            scale: 1.0,
640            aromatic: Default::default(),
641            debug_box: false,
642            debug_align: false,
643            align_debug: None,
644            ..Default::default()
645        }
646    }
647
648    fn acetone() -> MoleculeIn {
649        MoleculeIn {
650            id: Some("acetone".into()),
651            atoms: vec![
652                atom(0, "C", -20.0, 8.0, None),
653                atom(1, "C", 0.0, 0.0, None),
654                atom(2, "O", 0.0, -20.0, Some("O")),
655                atom(3, "C", 20.0, 8.0, None),
656            ],
657            bonds: vec![
658                BondIn {
659                    index: 0,
660                    begin: 0,
661                    end: 1,
662                    order: 1.0,
663                    stereo: None,
664                    interior: None,
665                },
666                BondIn {
667                    index: 1,
668                    begin: 1,
669                    end: 2,
670                    order: 2.0,
671                    stereo: None,
672                    interior: None,
673                },
674                BondIn {
675                    index: 2,
676                    begin: 1,
677                    end: 3,
678                    order: 1.0,
679                    stereo: None,
680                    interior: None,
681                },
682            ],
683            color: Some("#336699".into()),
684            atom_shade: None,
685            bond_shade: None,
686            shade_vmin: None,
687            shade_vmax: None,
688            weight: 1.0,
689            scale: 1.0,
690            aromatic: Default::default(),
691            debug_box: false,
692            debug_align: false,
693            align_debug: None,
694            ..Default::default()
695        }
696    }
697
698    #[test]
699    fn z_only_atoms_resolve_symbols() {
700        let mol = MoleculeIn {
701            id: Some("z".into()),
702            atoms: vec![
703                AtomIn {
704                    index: 0,
705                    element: None,
706                    z: Some(6),
707                    x: 0.0,
708                    y: 0.0,
709                    label: None,
710                    charge: 0,
711                    mapno: None,
712                },
713                AtomIn {
714                    index: 1,
715                    element: None,
716                    z: Some(8),
717                    x: 20.0,
718                    y: 0.0,
719                    label: Some("O".into()),
720                    charge: 0,
721                    mapno: None,
722                },
723            ],
724            bonds: vec![BondIn {
725                index: 0,
726                begin: 0,
727                end: 1,
728                order: 1.0,
729                stereo: None,
730                interior: None,
731            }],
732            color: None,
733            atom_shade: None,
734            bond_shade: None,
735            shade_vmin: None,
736            shade_vmax: None,
737            weight: 1.0,
738            scale: 1.0,
739            aromatic: Default::default(),
740            debug_box: false,
741            debug_align: false,
742            align_debug: None,
743            ..Default::default()
744        };
745        assert_eq!(mol.atoms[0].symbol(), "C");
746        assert_eq!(mol.atoms[1].symbol(), "O");
747        let scene = depict_molecule(&mol);
748        assert_eq!(scene.viewports.len(), 1);
749        assert_eq!(scene.viewports[0].id.as_deref(), Some("z"));
750        let bonds = scene.viewports[0]
751            .layers
752            .iter()
753            .find(|l| l.name == LayerName::Bonds)
754            .expect("bonds");
755        assert_eq!(bonds.primitives.len(), 1);
756        let labels = scene.viewports[0]
757            .layers
758            .iter()
759            .find(|l| l.name == LayerName::Labels)
760            .expect("labels");
761        let texts: Vec<_> = labels
762            .primitives
763            .iter()
764            .filter_map(|p| match p {
765                Primitive::Path {
766                    data_text: Some(t), ..
767                } => Some(t.as_str()),
768                _ => None,
769            })
770            .collect();
771        assert!(
772            texts.iter().any(|t| *t == "O"),
773            "expected O label from z=8 atom, got {texts:?}"
774        );
775    }
776
777    #[test]
778    fn ethanol_emits_oh_label() {
779        let scene = depict_molecule(&ethanol());
780        let labels = scene.viewports[0]
781            .layers
782            .iter()
783            .find(|l| l.name == LayerName::Labels)
784            .expect("labels layer");
785        let texts: Vec<_> = labels
786            .primitives
787            .iter()
788            .filter_map(|p| match p {
789                Primitive::Path {
790                    data_text: Some(t), ..
791                } => Some(t.as_str()),
792                _ => None,
793            })
794            .collect();
795        assert!(
796            texts.iter().any(|t| *t == "OH" || *t == "HO"),
797            "expected OH/HO path data-text, got {texts:?}"
798        );
799        assert!(
800            labels
801                .primitives
802                .iter()
803                .all(|p| matches!(p, Primitive::Path { .. })),
804            "labels must be glyph paths, not text nodes"
805        );
806    }
807
808    #[test]
809    fn ethanol_has_bond_layer() {
810        let scene = depict_molecule(&ethanol());
811        assert_eq!(scene.viewports.len(), 1);
812        let bonds = scene.viewports[0]
813            .layers
814            .iter()
815            .find(|l| l.name == LayerName::Bonds)
816            .expect("bonds");
817        assert_eq!(bonds.primitives.len(), 2);
818        assert!(scene.width > PAD_PX);
819        assert!(scene.height > PAD_PX);
820    }
821
822    #[test]
823    fn mol_weight_thickens_bond_stroke() {
824        use crate::metrics::{stroke_px_for_weight, STROKE_PX};
825        let mut mol = ethanol();
826        mol.weight = 2.0;
827        let scene = depict_molecule(&mol);
828        let bonds = scene.viewports[0]
829            .layers
830            .iter()
831            .find(|l| l.name == LayerName::Bonds)
832            .expect("bonds");
833        let sw = bonds
834            .primitives
835            .iter()
836            .find_map(|p| match p {
837                Primitive::Path { stroke_width, .. } if *stroke_width > 0.0 => Some(*stroke_width),
838                _ => None,
839            })
840            .expect("bond stroke");
841        let expected = stroke_px_for_weight(2.0);
842        assert!(
843            (sw - expected).abs() < 0.02,
844            "weight stroke {sw} vs {expected}"
845        );
846        assert!(sw > STROKE_PX + 0.3);
847    }
848
849    #[test]
850    fn mol_scale_doubles_scene_size_and_stroke() {
851        let base = depict_molecule(&ethanol());
852        let mut mol = ethanol();
853        mol.scale = 2.0;
854        let scaled = depict_molecule(&mol);
855        assert!((scaled.width - 2.0 * base.width).abs() < 1e-6);
856        assert!((scaled.height - 2.0 * base.height).abs() < 1e-6);
857        let base_sw = base.viewports[0]
858            .layers
859            .iter()
860            .find(|l| l.name == LayerName::Bonds)
861            .unwrap()
862            .primitives
863            .iter()
864            .find_map(|p| match p {
865                Primitive::Path { stroke_width, .. } if *stroke_width > 0.0 => Some(*stroke_width),
866                _ => None,
867            })
868            .unwrap();
869        let scaled_sw = scaled.viewports[0]
870            .layers
871            .iter()
872            .find(|l| l.name == LayerName::Bonds)
873            .unwrap()
874            .primitives
875            .iter()
876            .find_map(|p| match p {
877                Primitive::Path { stroke_width, .. } if *stroke_width > 0.0 => Some(*stroke_width),
878                _ => None,
879            })
880            .unwrap();
881        assert!((scaled_sw - 2.0 * base_sw).abs() < 1e-6);
882    }
883
884    #[test]
885    fn acetone_centered_double_has_two_offsets() {
886        let scene = depict_molecule(&acetone());
887        let bonds = scene.viewports[0]
888            .layers
889            .iter()
890            .find(|l| l.name == LayerName::Bonds)
891            .expect("bonds");
892        let offset_count = bonds
893            .primitives
894            .iter()
895            .filter(|p| match p {
896                Primitive::Path { class: Some(c), .. } => c.contains("bond-offset"),
897                _ => false,
898            })
899            .count();
900        assert_eq!(
901            offset_count, 2,
902            "centered C=O must emit exactly two offsets"
903        );
904        assert!(
905            bonds.primitives.iter().all(|p| match p {
906                Primitive::Path {
907                    stroke: Some(s), ..
908                } => s == "#336699",
909                _ => true,
910            }),
911            "all bond strokes must use molecule color #336699"
912        );
913    }
914
915    #[test]
916    fn benzene_ring_doubles_are_single_sided_short() {
917        // Regular hexagon — without ring interiors, join_centered would extend
918        // doubles onto singles and emit two parallel offsets per double.
919        let mut atoms = Vec::new();
920        for i in 0..6 {
921            let ang = std::f64::consts::PI / 2.0 + i as f64 * std::f64::consts::TAU / 6.0;
922            atoms.push(AtomIn {
923                index: i,
924                element: Some("C".into()),
925                z: None,
926                x: 20.0 * ang.cos(),
927                y: -20.0 * ang.sin(),
928                label: None,
929                charge: 0,
930                mapno: None,
931            });
932        }
933        let orders = [1.0, 2.0, 1.0, 2.0, 1.0, 2.0];
934        let mut bonds = Vec::new();
935        for i in 0..6 {
936            bonds.push(BondIn {
937                index: i,
938                begin: i,
939                end: (i + 1) % 6,
940                order: orders[i as usize],
941                stereo: None,
942                interior: None,
943            });
944        }
945        let mol = MoleculeIn {
946            id: Some("phh".into()),
947            atoms,
948            bonds,
949            color: None,
950            atom_shade: None,
951            bond_shade: None,
952            shade_vmin: None,
953            shade_vmax: None,
954            weight: 1.0,
955            scale: 1.0,
956            aromatic: Default::default(),
957            debug_box: false,
958            debug_align: false,
959            align_debug: None,
960            ..Default::default()
961        };
962        let scene = depict_molecule(&mol);
963        let layer = scene.viewports[0]
964            .layers
965            .iter()
966            .find(|l| l.name == LayerName::Bonds)
967            .expect("bonds");
968        let offset_count = layer
969            .primitives
970            .iter()
971            .filter(|p| match p {
972                Primitive::Path { class: Some(c), .. } => c.contains("bond-offset"),
973                _ => false,
974            })
975            .count();
976        // Three ring doubles → one interior offset each (not two centered lines).
977        assert_eq!(offset_count, 3, "ring doubles should be single-sided");
978    }
979
980    fn regular_hexagon_mol(orders: [f64; 6]) -> MoleculeIn {
981        let mut atoms = Vec::new();
982        for i in 0..6 {
983            let ang = std::f64::consts::PI / 2.0 + i as f64 * std::f64::consts::TAU / 6.0;
984            atoms.push(AtomIn {
985                index: i,
986                element: Some("C".into()),
987                z: None,
988                x: 20.0 * ang.cos(),
989                y: -20.0 * ang.sin(),
990                label: None,
991                charge: 0,
992                mapno: None,
993            });
994        }
995        let mut bonds = Vec::new();
996        for i in 0..6 {
997            bonds.push(BondIn {
998                index: i,
999                begin: i,
1000                end: (i + 1) % 6,
1001                order: orders[i as usize],
1002                stereo: None,
1003                interior: None,
1004            });
1005        }
1006        MoleculeIn {
1007            id: Some("hex".into()),
1008            atoms,
1009            bonds,
1010            color: None,
1011            atom_shade: None,
1012            bond_shade: None,
1013            shade_vmin: None,
1014            shade_vmax: None,
1015            weight: 1.0,
1016            scale: 1.0,
1017            aromatic: AromaticStyle::Circle,
1018            debug_box: false,
1019            debug_align: false,
1020            align_debug: None,
1021            ..Default::default()
1022        }
1023    }
1024
1025    #[test]
1026    fn benzene_aromatic_orders_draw_ring_circle() {
1027        // CTAB/Chematic aromatic encoding (order 4) — not Kekulé doubles.
1028        let mol = regular_hexagon_mol([4.0; 6]);
1029        let scene = depict_molecule(&mol);
1030        let layer = scene.viewports[0]
1031            .layers
1032            .iter()
1033            .find(|l| l.name == LayerName::Bonds)
1034            .expect("bonds");
1035        let aromatic_circles: Vec<_> = layer
1036            .primitives
1037            .iter()
1038            .filter(|p| match p {
1039                Primitive::Circle {
1040                    class: Some(c),
1041                    fill: None,
1042                    ..
1043                } => c.contains("aromatic"),
1044                _ => false,
1045            })
1046            .collect();
1047        assert_eq!(
1048            aromatic_circles.len(),
1049            1,
1050            "aromatic hexagon must draw one ring circle, got {:?}",
1051            layer.primitives.len()
1052        );
1053        match aromatic_circles[0] {
1054            Primitive::Circle { r, .. } => {
1055                // Inradius of regular hexagon with R=20 is ≈17.32; circle ≈ 0.60× ≈ 10.4.
1056                assert!(
1057                    *r > 9.0 && *r < 12.0,
1058                    "circle should sit inside ring, r={r}"
1059                );
1060            }
1061            _ => unreachable!(),
1062        }
1063    }
1064
1065    #[test]
1066    fn debug_box_draws_label_mol_and_scene_rects() {
1067        let mut mol = acetone();
1068        mol.debug_box = true;
1069        let scene = depict_molecule(&mol);
1070        let overlay = scene.viewports[0]
1071            .layers
1072            .iter()
1073            .find(|l| l.name == LayerName::Overlay)
1074            .expect("overlay layer");
1075        let classes: Vec<&str> = overlay
1076            .primitives
1077            .iter()
1078            .filter_map(|p| match p {
1079                Primitive::Path { class: Some(c), .. } => Some(c.as_str()),
1080                _ => None,
1081            })
1082            .collect();
1083        assert!(
1084            classes.iter().any(|c| c.contains("debug-box-label")),
1085            "expected label debug box, got {classes:?}"
1086        );
1087        assert!(
1088            classes.iter().any(|c| c.contains("debug-box-mol")),
1089            "expected mol debug box, got {classes:?}"
1090        );
1091        // Bond paths must not be wrapped as debug boxes.
1092        let bond_layer = scene.viewports[0]
1093            .layers
1094            .iter()
1095            .find(|l| l.name == LayerName::Bonds)
1096            .expect("bonds");
1097        assert!(bond_layer.primitives.iter().all(|p| match p {
1098            Primitive::Path { class: Some(c), .. } => !c.contains("debug-box"),
1099            _ => true,
1100        }));
1101        assert!(
1102            scene.overlays.iter().any(|p| match p {
1103                Primitive::Path { class: Some(c), .. } => c.contains("debug-box-scene"),
1104                _ => false,
1105            }),
1106            "expected scene debug box in overlays"
1107        );
1108    }
1109
1110    #[test]
1111    fn debug_box_off_by_default() {
1112        let scene = depict_molecule(&acetone());
1113        assert!(scene.viewports[0]
1114            .layers
1115            .iter()
1116            .all(|l| l.name != LayerName::Overlay
1117                || l.primitives.is_empty()
1118                || l.primitives.iter().all(|p| match p {
1119                    Primitive::Path { class: Some(c), .. } => !c.contains("debug-box"),
1120                    _ => true,
1121                })));
1122        assert!(scene.overlays.iter().all(|p| match p {
1123            Primitive::Path { class: Some(c), .. } => !c.contains("debug-box"),
1124            _ => true,
1125        }));
1126    }
1127
1128    #[test]
1129    fn debug_align_paints_tags_and_badge() {
1130        use crate::scene::{AlignDebug, AlignDebugRole};
1131        let mut mol = acetone();
1132        mol.debug_align = true;
1133        mol.align_debug = Some(AlignDebug {
1134            role: AlignDebugRole::Query,
1135            peer_id: Some("m0".into()),
1136            tags: vec![(0, 5), (1, 1)],
1137        });
1138        let scene = depict_molecule(&mol);
1139        let overlay = scene.viewports[0]
1140            .layers
1141            .iter()
1142            .find(|l| l.name == LayerName::Overlay)
1143            .expect("overlay layer");
1144        let classes: Vec<&str> = overlay
1145            .primitives
1146            .iter()
1147            .filter_map(|p| match p {
1148                Primitive::Circle { class: Some(c), .. }
1149                | Primitive::Text { class: Some(c), .. } => Some(c.as_str()),
1150                _ => None,
1151            })
1152            .collect();
1153        assert!(
1154            classes.iter().any(|c| c.contains("debug-align-atom")),
1155            "expected atom tags, got {classes:?}"
1156        );
1157        assert!(
1158            classes.iter().any(|c| c.contains("debug-align-badge")),
1159            "expected badge, got {classes:?}"
1160        );
1161        let texts: Vec<&str> = overlay
1162            .primitives
1163            .iter()
1164            .filter_map(|p| match p {
1165                Primitive::Text { text, .. } => Some(text.as_str()),
1166                _ => None,
1167            })
1168            .collect();
1169        assert!(
1170            texts.iter().any(|t| *t == "5"),
1171            "tag text 5 missing: {texts:?}"
1172        );
1173        assert!(
1174            texts.iter().any(|t| t.contains("align→Q")),
1175            "query badge missing: {texts:?}"
1176        );
1177    }
1178
1179    #[test]
1180    fn benzene_kekule_style_skips_circle_uses_doubles() {
1181        let mut mol = regular_hexagon_mol([4.0; 6]);
1182        mol.aromatic = AromaticStyle::Kekule;
1183        let scene = depict_molecule(&mol);
1184        let layer = scene.viewports[0]
1185            .layers
1186            .iter()
1187            .find(|l| l.name == LayerName::Bonds)
1188            .expect("bonds");
1189        assert!(
1190            !layer.primitives.iter().any(|p| matches!(
1191                p,
1192                Primitive::Circle {
1193                    class: Some(c),
1194                    ..
1195                } if c.contains("aromatic")
1196            )),
1197            "kekule style must not draw aromatic circles"
1198        );
1199        let offset_count = layer
1200            .primitives
1201            .iter()
1202            .filter(|p| match p {
1203                Primitive::Path { class: Some(c), .. } => c.contains("bond-offset"),
1204                _ => false,
1205            })
1206            .count();
1207        assert_eq!(offset_count, 3, "kekule paint should invent three doubles");
1208    }
1209
1210    #[test]
1211    fn shade_layers() {
1212        let mut mol = ethanol();
1213        mol.atom_shade = Some(vec![0.0, 0.0, 0.9]);
1214        let scene = depict_molecule(&mol);
1215        let names: Vec<_> = scene.viewports[0].layers.iter().map(|l| l.name).collect();
1216        assert!(names.contains(&LayerName::Shading));
1217        assert!(names.contains(&LayerName::Bonds));
1218        // Rainbow LUT (not the old coral stub): high score → hot orange-red.
1219        let shade = scene.viewports[0]
1220            .layers
1221            .iter()
1222            .find(|l| l.name == LayerName::Shading)
1223            .expect("shading");
1224        assert!(shade.primitives.iter().any(|p| match p {
1225            Primitive::Circle { fill: Some(f), .. } =>
1226                f.starts_with("rgb(") && !f.starts_with("rgb(255,222"),
1227            _ => false,
1228        }));
1229        let has_halo = scene.viewports[0]
1230            .layers
1231            .iter()
1232            .any(|l| l.name == LayerName::Halo && !l.primitives.is_empty());
1233        assert!(
1234            has_halo,
1235            "expected bond/label halo knockout in mol Halo layer"
1236        );
1237    }
1238
1239    #[test]
1240    fn shade_atom_and_bond_share_one_sorted_layer() {
1241        let mut mol = ethanol();
1242        // Strong bond mid + weaker atoms → bond disk should paint after (on top).
1243        mol.atom_shade = Some(vec![0.3, 0.3, 0.3]);
1244        mol.bond_shade = Some(vec![1.0, 0.2]);
1245        let scene = depict_molecule(&mol);
1246        let shade = scene.viewports[0]
1247            .layers
1248            .iter()
1249            .find(|l| l.name == LayerName::Shading)
1250            .expect("shading");
1251        let fills: Vec<_> = shade
1252            .primitives
1253            .iter()
1254            .filter_map(|p| match p {
1255                Primitive::Circle {
1256                    fill: Some(f), r, ..
1257                } => Some((f.clone(), *r)),
1258                _ => None,
1259            })
1260            .collect();
1261        assert!(
1262            fills.len() >= 4,
1263            "atom+bond shade should emit multiple disks, got {}",
1264            fills.len()
1265        );
1266        // Combined atom+bond uses the smaller shared base, not SHADE_FRAC.
1267        let max_r = fills.iter().map(|(_, r)| *r).fold(0.0_f64, f64::max);
1268        assert!(
1269            (max_r - BOND_PX * SHADE_BOTH_FRAC).abs() < 0.05,
1270            "expected SHADE_BOTH_FRAC×bond when both atom+bond shaded, got {max_r}"
1271        );
1272    }
1273
1274    #[test]
1275    fn shade_full_strength_outer_is_house_frac() {
1276        let mut mol = ethanol();
1277        mol.atom_shade = Some(vec![1.0, 0.0, 0.0]);
1278        let scene = depict_molecule(&mol);
1279        let shade = scene.viewports[0]
1280            .layers
1281            .iter()
1282            .find(|l| l.name == LayerName::Shading)
1283            .expect("shading");
1284        let max_r = shade
1285            .primitives
1286            .iter()
1287            .filter_map(|p| match p {
1288                Primitive::Circle {
1289                    r, class: Some(c), ..
1290                } if c == "shade" => Some(*r),
1291                _ => None,
1292            })
1293            .fold(0.0_f64, f64::max);
1294        assert!(
1295            (max_r - BOND_PX * SHADE_FRAC).abs() < 1e-6,
1296            "full-score outer r={max_r}, expected {}×bond",
1297            SHADE_FRAC
1298        );
1299    }
1300
1301    #[test]
1302    fn scene_json_roundtrips() {
1303        let scene = depict_molecule(&acetone());
1304        let json = serde_json::to_string(&scene).expect("ser");
1305        let back: Scene = serde_json::from_str(&json).expect("de");
1306        assert_eq!(back.viewports[0].id.as_deref(), Some("acetone"));
1307        let orig_names: Vec<_> = scene.viewports[0].layers.iter().map(|l| l.name).collect();
1308        let back_names: Vec<_> = back.viewports[0].layers.iter().map(|l| l.name).collect();
1309        assert_eq!(back_names, orig_names);
1310        assert!(back_names.contains(&LayerName::Bonds));
1311        assert!(back_names.contains(&LayerName::Labels));
1312        let bond_count = |s: &Scene| {
1313            s.viewports[0]
1314                .layers
1315                .iter()
1316                .find(|l| l.name == LayerName::Bonds)
1317                .map(|l| l.primitives.len())
1318                .unwrap_or(0)
1319        };
1320        assert_eq!(bond_count(&back), bond_count(&scene));
1321        assert_eq!(bond_count(&back), 4);
1322        let bond_colors = |s: &Scene| -> Vec<String> {
1323            s.viewports[0]
1324                .layers
1325                .iter()
1326                .find(|l| l.name == LayerName::Bonds)
1327                .into_iter()
1328                .flat_map(|l| l.primitives.iter())
1329                .filter_map(|p| match p {
1330                    Primitive::Path {
1331                        stroke: Some(s), ..
1332                    } => Some(s.clone()),
1333                    _ => None,
1334                })
1335                .collect()
1336        };
1337        let colors = bond_colors(&back);
1338        assert_eq!(colors, bond_colors(&scene));
1339        assert!(colors.iter().all(|c| c == "#336699"));
1340    }
1341
1342    /// Parity: Python ``test_depict_molecule_ethanol_two_bonds``.
1343    #[test]
1344    fn ethanol_viewport_id_and_two_bonds() {
1345        let scene = depict_molecule(&ethanol());
1346        assert_eq!(scene.viewports[0].id.as_deref(), Some("etoh"));
1347        let bonds = scene.viewports[0]
1348            .layers
1349            .iter()
1350            .find(|l| l.name == LayerName::Bonds)
1351            .expect("bonds");
1352        assert_eq!(bonds.primitives.len(), 2);
1353        assert!(scene.width.is_finite() && scene.height.is_finite());
1354        assert!(scene.width > PAD_PX);
1355        assert!(scene.height > PAD_PX);
1356        let labels = scene.viewports[0]
1357            .layers
1358            .iter()
1359            .find(|l| l.name == LayerName::Labels)
1360            .expect("labels");
1361        let texts: Vec<_> = labels
1362            .primitives
1363            .iter()
1364            .filter_map(|p| match p {
1365                Primitive::Path {
1366                    data_text: Some(t), ..
1367                } => Some(t.as_str()),
1368                _ => None,
1369            })
1370            .collect();
1371        assert!(
1372            texts.iter().any(|t| *t == "OH" || *t == "HO"),
1373            "expected OH/HO data-text, got {texts:?}"
1374        );
1375    }
1376
1377    /// Parity: Python ``test_depict_acetone_centered_double_offsets`` + joined offsets.
1378    #[test]
1379    fn acetone_joined_offsets_and_color() {
1380        let scene = depict_molecule(&acetone());
1381        let bonds = scene.viewports[0]
1382            .layers
1383            .iter()
1384            .find(|l| l.name == LayerName::Bonds)
1385            .expect("bonds");
1386        let offsets: Vec<_> = bonds
1387            .primitives
1388            .iter()
1389            .filter(|p| match p {
1390                Primitive::Path { class: Some(c), .. } => c.contains("bond-offset"),
1391                _ => false,
1392            })
1393            .collect();
1394        assert_eq!(
1395            offsets.len(),
1396            2,
1397            "centered C=O must emit exactly two offsets"
1398        );
1399        assert!(bonds.primitives.iter().all(|p| match p {
1400            Primitive::Path {
1401                stroke: Some(s), ..
1402            } => s == "#336699",
1403            _ => true,
1404        }));
1405        assert_eq!(crate::metrics::OFFSET_PX, 4.5);
1406    }
1407
1408    /// Parity: Python ``test_depict_marks_and_shade_layers``.
1409    #[test]
1410    fn marks_and_shade_co_o_fixture() {
1411        let mol = MoleculeIn {
1412            id: None,
1413            atoms: vec![
1414                atom(0, "C", 0.0, 0.0, None),
1415                atom(1, "O", 20.0, 0.0, Some("O")),
1416            ],
1417            bonds: vec![BondIn {
1418                index: 0,
1419                begin: 0,
1420                end: 1,
1421                order: 1.0,
1422                stereo: None,
1423                interior: None,
1424            }],
1425            color: None,
1426            atom_shade: Some(vec![0.0, 0.85]),
1427            bond_shade: None,
1428            shade_vmin: None,
1429            shade_vmax: None,
1430            weight: 1.0,
1431            scale: 1.0,
1432            aromatic: Default::default(),
1433            debug_box: false,
1434            debug_align: false,
1435            align_debug: None,
1436            ..Default::default()
1437        };
1438        let scene = depict_molecule(&mol);
1439        let names: std::collections::HashSet<_> =
1440            scene.viewports[0].layers.iter().map(|l| l.name).collect();
1441        assert!(names.contains(&LayerName::Shading));
1442        assert!(names.contains(&LayerName::Bonds));
1443
1444        let shade = scene.viewports[0]
1445            .layers
1446            .iter()
1447            .find(|l| l.name == LayerName::Shading)
1448            .expect("shading");
1449        let disks: Vec<_> = shade
1450            .primitives
1451            .iter()
1452            .filter_map(|p| match p {
1453                Primitive::Circle {
1454                    cx,
1455                    cy,
1456                    r,
1457                    class: Some(c),
1458                    ..
1459                } if c == "shade" => Some((*cx, *cy, *r)),
1460                _ => None,
1461            })
1462            .collect();
1463        // z=0 filtered; z=0.85 on fixed 0..1 window → 4 PlotDot rings at O.
1464        assert_eq!(disks.len(), 4);
1465        let base_r = BOND_PX * SHADE_FRAC;
1466        let max_r = disks.iter().map(|(_, _, r)| *r).fold(0.0_f64, f64::max);
1467        // PlotDot outer ring for |z|=0.85 is ~0.922×base — not stretched to 1.0.
1468        let expected = base_r * (0.85_f64).sqrt(); // rings use sqrt steps; 0.85→√0.85
1469        assert!(
1470            (max_r - expected).abs() < 1e-6,
1471            "outer shade radius = {max_r}, expected {expected}"
1472        );
1473        assert!(
1474            max_r < base_r - 1e-6,
1475            "0.85 must not auto-window to full strength (got {max_r} vs base {base_r})"
1476        );
1477        let (sx, sy, _) = disks[0];
1478        assert!(disks
1479            .iter()
1480            .all(|(x, y, _)| (*x - sx).abs() < 1e-9 && (*y - sy).abs() < 1e-9));
1481    }
1482
1483    #[test]
1484    fn empty_molecule_and_hetero_auto_label() {
1485        let empty = MoleculeIn {
1486            id: Some("empty".into()),
1487            atoms: vec![],
1488            bonds: vec![],
1489            color: None,
1490            atom_shade: None,
1491            bond_shade: None,
1492            shade_vmin: None,
1493            shade_vmax: None,
1494            weight: 1.0,
1495            scale: 1.0,
1496            aromatic: Default::default(),
1497            debug_box: false,
1498            debug_align: false,
1499            align_debug: None,
1500            ..Default::default()
1501        };
1502        let scene = depict_molecule(&empty);
1503        assert_eq!(scene.viewports[0].id.as_deref(), Some("empty"));
1504        assert!(scene.viewports[0].layers.is_empty());
1505
1506        // Heteroatom without explicit label still gets a glyph path.
1507        let mol = MoleculeIn {
1508            id: None,
1509            atoms: vec![atom(0, "C", 0.0, 0.0, None), atom(1, "N", 20.0, 0.0, None)],
1510            bonds: vec![BondIn {
1511                index: 0,
1512                begin: 0,
1513                end: 1,
1514                order: 1.0,
1515                stereo: None,
1516                interior: None,
1517            }],
1518            color: None,
1519            atom_shade: None,
1520            bond_shade: None,
1521            shade_vmin: None,
1522            shade_vmax: None,
1523            weight: 1.0,
1524            scale: 1.0,
1525            aromatic: Default::default(),
1526            debug_box: false,
1527            debug_align: false,
1528            align_debug: None,
1529            ..Default::default()
1530        };
1531        let scene = depict_molecule(&mol);
1532        let labels = scene.viewports[0]
1533            .layers
1534            .iter()
1535            .find(|l| l.name == LayerName::Labels)
1536            .expect("labels");
1537        assert!(labels.primitives.iter().any(|p| match p {
1538            Primitive::Path {
1539                data_text: Some(t), ..
1540            } => t == "N",
1541            _ => false,
1542        }));
1543    }
1544
1545    #[test]
1546    fn charged_label_and_empty_label_string() {
1547        let mut charged = atom(0, "N", 0.0, 0.0, Some("N"));
1548        charged.charge = 1;
1549        let mut anion = atom(1, "O", 20.0, 0.0, None);
1550        anion.charge = -2;
1551        let blank = AtomIn {
1552            index: 2,
1553            element: Some("C".into()),
1554            z: None,
1555            x: 40.0,
1556            y: 0.0,
1557            label: Some("  ".into()),
1558            charge: 0,
1559            mapno: None,
1560        };
1561        let mol = MoleculeIn {
1562            id: None,
1563            atoms: vec![charged, anion, blank],
1564            bonds: vec![
1565                BondIn {
1566                    index: 0,
1567                    begin: 0,
1568                    end: 1,
1569                    order: 1.0,
1570                    stereo: None,
1571                    interior: None,
1572                },
1573                BondIn {
1574                    index: 1,
1575                    begin: 1,
1576                    end: 2,
1577                    order: 1.0,
1578                    stereo: None,
1579                    interior: None,
1580                },
1581            ],
1582            color: None,
1583            atom_shade: None,
1584            bond_shade: None,
1585            shade_vmin: None,
1586            shade_vmax: None,
1587            weight: 1.0,
1588            scale: 1.0,
1589            aromatic: Default::default(),
1590            debug_box: false,
1591            debug_align: false,
1592            align_debug: None,
1593            ..Default::default()
1594        };
1595        let scene = depict_molecule(&mol);
1596        let labels = scene.viewports[0]
1597            .layers
1598            .iter()
1599            .find(|l| l.name == LayerName::Labels)
1600            .expect("labels");
1601        let texts: Vec<_> = labels
1602            .primitives
1603            .iter()
1604            .filter_map(|p| match p {
1605                Primitive::Path {
1606                    data_text: Some(t), ..
1607                } => Some(t.as_str()),
1608                _ => None,
1609            })
1610            .collect();
1611        assert!(texts.iter().any(|t| t.contains('⁺') || t.contains('+')));
1612        assert!(texts
1613            .iter()
1614            .any(|t| t.contains('⁻') || t.contains('−') || t.contains('-')));
1615    }
1616
1617    #[test]
1618    fn north_south_label_grows_canvas() {
1619        // Degree-2 steep neighbors → North/South orientation for NH2.
1620        let mol = MoleculeIn {
1621            id: None,
1622            atoms: vec![
1623                atom(0, "C", 0.0, 20.0, None),
1624                atom(1, "C", 0.0, -20.0, None),
1625                atom(2, "N", 0.0, 0.0, Some("NH2")),
1626            ],
1627            bonds: vec![
1628                BondIn {
1629                    index: 0,
1630                    begin: 2,
1631                    end: 0,
1632                    order: 1.0,
1633                    stereo: None,
1634                    interior: None,
1635                },
1636                BondIn {
1637                    index: 1,
1638                    begin: 2,
1639                    end: 1,
1640                    order: 1.0,
1641                    stereo: None,
1642                    interior: None,
1643                },
1644            ],
1645            color: None,
1646            atom_shade: None,
1647            bond_shade: None,
1648            shade_vmin: None,
1649            shade_vmax: None,
1650            weight: 1.0,
1651            scale: 1.0,
1652            aromatic: Default::default(),
1653            debug_box: false,
1654            debug_align: false,
1655            align_debug: None,
1656            ..Default::default()
1657        };
1658        let scene = depict_molecule(&mol);
1659        assert!(scene.height > PAD_PX * 2.0);
1660        let labels = scene.viewports[0]
1661            .layers
1662            .iter()
1663            .find(|l| l.name == LayerName::Labels)
1664            .expect("labels");
1665        let texts: Vec<_> = labels
1666            .primitives
1667            .iter()
1668            .filter_map(|p| match p {
1669                Primitive::Path {
1670                    data_text: Some(t), ..
1671                } => Some(t.as_str()),
1672                _ => None,
1673            })
1674            .collect();
1675        assert!(
1676            texts.iter().any(|t| t.contains("NH") || t.contains("HN")),
1677            "expected NH2/HN2 label, got {texts:?}"
1678        );
1679    }
1680
1681    #[test]
1682    fn shade_negative_and_diverging() {
1683        let mut mol = ethanol();
1684        // Explicit diverging window — defaults are vmin=0, vmax=1 (no auto-window).
1685        mol.shade_vmin = Some(-1.0);
1686        mol.shade_vmax = Some(1.0);
1687        mol.atom_shade = Some(vec![-0.8, -0.2, 0.0]);
1688        let scene = depict_molecule(&mol);
1689        let shade = scene.viewports[0]
1690            .layers
1691            .iter()
1692            .find(|l| l.name == LayerName::Shading)
1693            .expect("shading");
1694        assert!(
1695            shade.primitives.len() >= 2,
1696            "negative scores should still paint shade disks"
1697        );
1698
1699        mol.atom_shade = Some(vec![-0.9, 0.0, 0.9]);
1700        let scene2 = depict_molecule(&mol);
1701        let shade2 = scene2.viewports[0]
1702            .layers
1703            .iter()
1704            .find(|l| l.name == LayerName::Shading)
1705            .expect("shading");
1706        let fills: Vec<_> = shade2
1707            .primitives
1708            .iter()
1709            .filter_map(|p| match p {
1710                Primitive::Circle { fill: Some(f), .. } => Some(f.as_str()),
1711                _ => None,
1712            })
1713            .collect();
1714        assert!(fills.len() >= 2);
1715        assert!(
1716            fills.iter().any(|f| f.starts_with("rgb(")),
1717            "diverging colormap must emit rgb() fills"
1718        );
1719    }
1720
1721    #[test]
1722    fn shade_default_window_is_zero_to_one() {
1723        let mut mol = ethanol();
1724        // Peak score 0.45 must stay mid-strength — not stretched to vmax of data.
1725        mol.atom_shade = Some(vec![0.0, 0.0, 0.45]);
1726        let scene = depict_molecule(&mol);
1727        let shade = scene.viewports[0]
1728            .layers
1729            .iter()
1730            .find(|l| l.name == LayerName::Shading)
1731            .expect("shading");
1732        assert!(
1733            !shade.primitives.is_empty(),
1734            "0.45 on a 0..1 window should still paint"
1735        );
1736        // Auto-windowing to max=0.45 would normalize to 1.0 and grow the disk;
1737        // with fixed vmax=1 the radius stays clearly below a full-strength hit.
1738        let mut mol_hot = ethanol();
1739        mol_hot.atom_shade = Some(vec![0.0, 0.0, 1.0]);
1740        let hot = depict_molecule(&mol_hot);
1741        let hot_shade = hot.viewports[0]
1742            .layers
1743            .iter()
1744            .find(|l| l.name == LayerName::Shading)
1745            .expect("shading");
1746        let max_r = |scene_shade: &crate::scene::Layer| {
1747            scene_shade
1748                .primitives
1749                .iter()
1750                .filter_map(|p| match p {
1751                    Primitive::Circle { r, .. } => Some(r),
1752                    _ => None,
1753                })
1754                .fold(0.0_f64, |a, b| a.max(*b))
1755        };
1756        assert!(
1757            max_r(shade) < max_r(hot_shade) * 0.85,
1758            "0.45 must not be auto-stretched to full strength (got {} vs hot {})",
1759            max_r(shade),
1760            max_r(hot_shade)
1761        );
1762    }
1763
1764    #[test]
1765    fn skips_bonds_with_missing_indices() {
1766        let mut mol = ethanol();
1767        mol.bonds.push(BondIn {
1768            index: 99,
1769            begin: 0,
1770            end: 999,
1771            order: 1.0,
1772            stereo: None,
1773            interior: None,
1774        });
1775        let scene = depict_molecule(&mol);
1776        assert!(scene.viewports[0]
1777            .layers
1778            .iter()
1779            .any(|l| l.name == LayerName::Bonds && !l.primitives.is_empty()));
1780    }
1781
1782    #[test]
1783    fn wedge_stereo_fills_halo_from_polygon() {
1784        let mol = MoleculeIn {
1785            id: None,
1786            atoms: vec![atom(0, "C", 0.0, 0.0, None), atom(1, "C", 20.0, 0.0, None)],
1787            bonds: vec![BondIn {
1788                index: 0,
1789                begin: 0,
1790                end: 1,
1791                order: 1.0,
1792                stereo: Some("up".into()),
1793                interior: None,
1794            }],
1795            color: None,
1796            atom_shade: Some(vec![0.5, 0.5]),
1797            bond_shade: None,
1798            shade_vmin: None,
1799            shade_vmax: None,
1800            weight: 1.0,
1801            scale: 1.0,
1802            aromatic: Default::default(),
1803            debug_box: false,
1804            debug_align: false,
1805            align_debug: None,
1806            ..Default::default()
1807        };
1808        let scene = depict_molecule(&mol);
1809        let has_halo = scene.viewports[0]
1810            .layers
1811            .iter()
1812            .any(|l| l.name == LayerName::Halo && !l.primitives.is_empty());
1813        assert!(has_halo, "expected mol Halo layer");
1814        let bonds = scene.viewports[0]
1815            .layers
1816            .iter()
1817            .find(|l| l.name == LayerName::Bonds)
1818            .expect("bonds");
1819        let wedges: Vec<_> = bonds
1820            .primitives
1821            .iter()
1822            .filter(|p| match p {
1823                Primitive::Path { class: Some(c), .. } => c.contains("wedge"),
1824                _ => false,
1825            })
1826            .collect();
1827        assert_eq!(wedges.len(), 1);
1828        match wedges[0] {
1829            Primitive::Path {
1830                d, fill: Some(f), ..
1831            } => {
1832                assert!(d.starts_with("M "), "wedge path starts with move: {d}");
1833                assert!(d.contains('Z'), "wedge must be closed");
1834                assert_eq!(f, "#111");
1835            }
1836            _ => panic!("expected filled wedge path"),
1837        }
1838    }
1839
1840    #[test]
1841    fn shade_bond_only_and_tiny_scores_filtered() {
1842        let mut mol = ethanol();
1843        mol.atom_shade = None;
1844        mol.bond_shade = Some(vec![0.9, 0.01]);
1845        let scene = depict_molecule(&mol);
1846        let shade = scene.viewports[0]
1847            .layers
1848            .iter()
1849            .find(|l| l.name == LayerName::Shading)
1850            .expect("shading");
1851        // Only bond 0 score 0.9 survives the 0.01 filter.
1852        assert!(!shade.primitives.is_empty());
1853        assert!(shade.primitives.iter().all(|p| matches!(
1854            p,
1855            Primitive::Circle {
1856                class: Some(c),
1857                ..
1858            } if c == "shade"
1859        )));
1860
1861        // Near-zero-only scores: either no shading layer or only filtered disks.
1862        mol.bond_shade = Some(vec![0.0, 0.0]);
1863        mol.atom_shade = Some(vec![0.0, 0.0, 0.0]);
1864        let scene2 = depict_molecule(&mol);
1865        let shade2 = scene2.viewports[0]
1866            .layers
1867            .iter()
1868            .find(|l| l.name == LayerName::Shading);
1869        assert!(
1870            shade2.is_none() || shade2.unwrap().primitives.is_empty(),
1871            "expected no shade disks for zero scores"
1872        );
1873    }
1874
1875    #[test]
1876    fn shade_skips_bond_with_unknown_endpoints() {
1877        let mut mol = ethanol();
1878        mol.bond_shade = Some(vec![0.8, 0.8, 0.8]);
1879        mol.bonds.push(BondIn {
1880            index: 50,
1881            begin: 0,
1882            end: 999,
1883            order: 1.0,
1884            stereo: None,
1885            interior: None,
1886        });
1887        let scene = depict_molecule(&mol);
1888        assert!(scene.viewports[0]
1889            .layers
1890            .iter()
1891            .any(|l| l.name == LayerName::Shading));
1892    }
1893}