zenith-scene 0.0.7

Zenith backend-neutral scene IR and compilation (geometry, text wrap, anchors, opacity, clip).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! `group` container compilation: translate + opacity cascade with optional
//! rotation / blend / blur brackets, plus the bounding-box helpers that
//! determine a group's rotation pivot.

use std::collections::BTreeMap;

use zenith_core::{Diagnostic, GroupNode, Node, Point, ResolvedToken, dim_to_px};

use crate::ir::SceneCommand;

use super::super::paint::{
    NodeEffect, resolve_property_filter, resolve_property_mask, resolve_property_shadow,
};
use super::super::util::{blend_mode_ir, resolve_geometry_px, rotation_degrees};
use super::super::{NodeCtx, RenderCtx, compile_node};
use super::wrap::emit_wrapped_container;

// NOTE: compile_group → compile_node → compile_group recursion has no depth
// guard.  Pathologically deep group trees can overflow the stack.  This is a
// known v0 limitation; a guard will be added when nested documents are tested.
pub(in crate::compile) fn compile_group(
    group: &GroupNode,
    cx: NodeCtx,
    commands: &mut Vec<SceneCommand>,
    diagnostics: &mut Vec<Diagnostic>,
    connector_strokes: &mut Vec<usize>,
    ctx: RenderCtx,
) {
    // Entire subtree excluded when visible=false.
    if group.visible == Some(false) {
        return;
    }

    // Cascade opacity: multiply the group's own opacity into the inherited ctx.
    // With a non-normal blend the group's opacity instead rides the PushLayer
    // (emitted after the rotation push below) and children inherit `ctx.opacity`
    // unmultiplied, so opacity is applied exactly once. No-blend path unchanged.
    let group_opacity = group.opacity.unwrap_or(1.0).clamp(0.0, 1.0);
    let blend = blend_mode_ir(group.blend_mode.as_deref());
    let child_opacity = match blend {
        Some(_) => ctx.opacity,
        None => ctx.opacity * group_opacity,
    };

    // Resolve group x/y to pixels; absent or unsupported-unit → 0.0 (no diagnostic).
    let group_x_px = resolve_geometry_px(group.x.as_ref(), cx.resolved).unwrap_or(0.0);
    let group_y_px = resolve_geometry_px(group.y.as_ref(), cx.resolved).unwrap_or(0.0);

    let child_dx = ctx.dx + group_x_px;
    let child_dy = ctx.dy + group_y_px;

    // Rotation bracket — outermost, wrapping all child commands.
    // Determine the pivot center:
    //   1. If the group has BOTH w and h declared → use the declared box center.
    //   2. Otherwise → compute the union bbox of direct children in device space.
    //   3. If neither yields a center (empty / geometry-less group) → skip
    //      the bracket entirely (v0 limitation, commented below).
    let group_rot = rotation_degrees(group.rotate.as_ref());
    let rot_center: Option<(f64, f64)> = if group_rot.is_some() {
        // Try declared box first.
        let declared = resolve_geometry_px(group.w.as_ref(), cx.resolved)
            .zip(resolve_geometry_px(group.h.as_ref(), cx.resolved))
            .map(|(gw, gh)| (child_dx + gw / 2.0, child_dy + gh / 2.0));
        if declared.is_some() {
            declared
        } else {
            // Fall back to union bbox of direct children in device space.
            // v0 limitation: if the group is empty or contains only
            // geometry-less nodes no center is computable → rotation is
            // silently skipped.
            group_children_center(&group.children, child_dx, child_dy, cx.resolved)
        }
    } else {
        None
    };

    if let (Some(angle), Some((cx_pivot, cy_pivot))) = (group_rot, rot_center) {
        commands.push(SceneCommand::PushTransform {
            angle_deg: angle,
            cx: cx_pivot,
            cy: cy_pivot,
        });
    }

    // Blend-mode layer bracket (inside the rotation, around all children). The
    // layer composites back with the group's full opacity cascade.
    if let Some(blend_mode) = blend {
        commands.push(SceneCommand::PushLayer {
            opacity: ctx.opacity * group_opacity,
            blend_mode: Some(blend_mode),
        });
    }

    // Attached visual effect (inside blend, around all children). The entire
    // group ink (all children composited) is affected as one unit. Precedence
    // matches leaf nodes: blur > shadow > filter.
    let blur_sigma = group
        .blur
        .as_ref()
        .and_then(|d| dim_to_px(d.value, &d.unit))
        .filter(|&s| s > 0.0);
    let effect: Option<NodeEffect> = if let Some(sigma) = blur_sigma {
        Some(NodeEffect::Blur(sigma))
    } else if let Some(shadows) = group
        .shadow
        .as_ref()
        .and_then(|p| resolve_property_shadow(p, cx.resolved, &group.id))
    {
        Some(NodeEffect::Shadow(shadows))
    } else {
        group
            .filter
            .as_ref()
            .and_then(|p| resolve_property_filter(p, cx.resolved, &group.id))
            .map(NodeEffect::Filter)
    };
    let mask = group
        .mask
        .as_ref()
        .and_then(|p| resolve_group_mask(group, p, child_dx, child_dy, cx));

    // Emit children in source order; the group itself produces no command.
    let child_ctx = RenderCtx {
        opacity: child_opacity,
        dx: child_dx,
        dy: child_dy,
        // Page baseline grid cascades unchanged so all text shares one grid.
        baseline_grid: ctx.baseline_grid,
    };
    if effect.is_none() && mask.is_none() {
        for child in &group.children {
            compile_node(
                child,
                cx,
                commands,
                diagnostics,
                connector_strokes,
                child_ctx,
            );
        }
    } else {
        let mut draws = Vec::new();
        let mut local_connector_strokes = Vec::new();
        for child in &group.children {
            compile_node(
                child,
                cx,
                &mut draws,
                diagnostics,
                &mut local_connector_strokes,
                child_ctx,
            );
        }
        emit_wrapped_container(
            commands,
            draws,
            effect,
            mask,
            connector_strokes,
            local_connector_strokes,
        );
    }

    if blend.is_some() {
        commands.push(SceneCommand::PopLayer);
    }

    if group_rot.is_some() && rot_center.is_some() {
        commands.push(SceneCommand::PopTransform);
    }
}

fn resolve_group_mask(
    group: &GroupNode,
    prop: &zenith_core::PropertyValue,
    group_x: f64,
    group_y: f64,
    cx: NodeCtx,
) -> Option<crate::ir::MaskSpec> {
    let w = resolve_geometry_px(group.w.as_ref(), cx.resolved)?;
    let h = resolve_geometry_px(group.h.as_ref(), cx.resolved)?;
    resolve_property_mask(prop, cx.resolved, (group_x, group_y, w, h))
}

/// Compute the axis-aligned bounding box of a `Point` list in authored coords.
///
/// Returns `(x_min, y_min, w, h)` in authored (pre-`base_dx`/`base_dy`) space,
/// or `None` when the list is empty or every point has a missing / unsupported-
/// unit coordinate.  Used by both the `Polygon` and `Polyline` arms of
/// [`group_children_center`] to avoid duplicating the accumulation loop.
fn points_bbox(pts: &[Point]) -> Option<(f64, f64, f64, f64)> {
    let mut px_min = f64::INFINITY;
    let mut py_min = f64::INFINITY;
    let mut px_max = f64::NEG_INFINITY;
    let mut py_max = f64::NEG_INFINITY;
    for pt in pts {
        let (Some(xd), Some(yd)) = (&pt.x, &pt.y) else {
            continue;
        };
        let (Some(px), Some(py)) = (dim_to_px(xd.value, &xd.unit), dim_to_px(yd.value, &yd.unit))
        else {
            continue;
        };
        px_min = px_min.min(px);
        py_min = py_min.min(py);
        px_max = px_max.max(px);
        py_max = py_max.max(py);
    }
    if px_min.is_finite() {
        Some((px_min, py_min, px_max - px_min, py_max - py_min))
    } else {
        None
    }
}

/// Compute the device-space center of a group's direct-child union bounding box.
///
/// `base_dx`/`base_dy` are the device-space origin of the group (i.e.
/// `ctx.dx + group_x_px` and `ctx.dy + group_y_px`).  Children are positioned
/// relative to those origins.
///
/// Returns `None` when no child yields a computable bbox (e.g. an empty group
/// or one containing only unknown/geometry-less nodes).
fn group_children_center(
    children: &[Node],
    base_dx: f64,
    base_dy: f64,
    resolved: &BTreeMap<String, ResolvedToken>,
) -> Option<(f64, f64)> {
    // Accumulate min/max in device space.
    let mut min_x = f64::INFINITY;
    let mut min_y = f64::INFINITY;
    let mut max_x = f64::NEG_INFINITY;
    let mut max_y = f64::NEG_INFINITY;

    for child in children {
        // Helper: expand accumulated bounds by a device-space rect.
        macro_rules! expand {
            ($x:expr, $y:expr, $w:expr, $h:expr) => {
                if $w > 0.0 || $h > 0.0 {
                    min_x = min_x.min($x);
                    min_y = min_y.min($y);
                    max_x = max_x.max($x + $w);
                    max_y = max_y.max($y + $h);
                }
            };
        }

        match child {
            Node::Rect(n) => {
                let (Some(xd), Some(yd), Some(wd), Some(hd)) = (&n.x, &n.y, &n.w, &n.h) else {
                    continue;
                };
                let (Some(x), Some(y), Some(w), Some(h)) = (
                    resolve_geometry_px(Some(xd), resolved),
                    resolve_geometry_px(Some(yd), resolved),
                    resolve_geometry_px(Some(wd), resolved),
                    resolve_geometry_px(Some(hd), resolved),
                ) else {
                    continue;
                };
                expand!(base_dx + x, base_dy + y, w, h);
            }
            Node::Ellipse(n) => {
                let (Some(xd), Some(yd), Some(wd), Some(hd)) = (&n.x, &n.y, &n.w, &n.h) else {
                    continue;
                };
                let (Some(x), Some(y), Some(w), Some(h)) = (
                    resolve_geometry_px(Some(xd), resolved),
                    resolve_geometry_px(Some(yd), resolved),
                    resolve_geometry_px(Some(wd), resolved),
                    resolve_geometry_px(Some(hd), resolved),
                ) else {
                    continue;
                };
                expand!(base_dx + x, base_dy + y, w, h);
            }
            Node::Text(n) => {
                let (Some(xd), Some(yd), Some(wd), Some(hd)) = (&n.x, &n.y, &n.w, &n.h) else {
                    continue;
                };
                let (Some(x), Some(y), Some(w), Some(h)) = (
                    resolve_geometry_px(Some(xd), resolved),
                    resolve_geometry_px(Some(yd), resolved),
                    resolve_geometry_px(Some(wd), resolved),
                    resolve_geometry_px(Some(hd), resolved),
                ) else {
                    continue;
                };
                expand!(base_dx + x, base_dy + y, w, h);
            }
            Node::Code(n) => {
                let (Some(xd), Some(yd), Some(wd), Some(hd)) = (&n.x, &n.y, &n.w, &n.h) else {
                    continue;
                };
                let (Some(x), Some(y), Some(w), Some(h)) = (
                    resolve_geometry_px(Some(xd), resolved),
                    resolve_geometry_px(Some(yd), resolved),
                    resolve_geometry_px(Some(wd), resolved),
                    resolve_geometry_px(Some(hd), resolved),
                ) else {
                    continue;
                };
                expand!(base_dx + x, base_dy + y, w, h);
            }
            Node::Image(n) => {
                let (Some(xd), Some(yd), Some(wd), Some(hd)) = (&n.x, &n.y, &n.w, &n.h) else {
                    continue;
                };
                let (Some(x), Some(y), Some(w), Some(h)) = (
                    resolve_geometry_px(Some(xd), resolved),
                    resolve_geometry_px(Some(yd), resolved),
                    resolve_geometry_px(Some(wd), resolved),
                    resolve_geometry_px(Some(hd), resolved),
                ) else {
                    continue;
                };
                expand!(base_dx + x, base_dy + y, w, h);
            }
            Node::Frame(n) => {
                let (Some(xd), Some(yd), Some(wd), Some(hd)) = (&n.x, &n.y, &n.w, &n.h) else {
                    continue;
                };
                let (Some(x), Some(y), Some(w), Some(h)) = (
                    resolve_geometry_px(Some(xd), resolved),
                    resolve_geometry_px(Some(yd), resolved),
                    resolve_geometry_px(Some(wd), resolved),
                    resolve_geometry_px(Some(hd), resolved),
                ) else {
                    continue;
                };
                expand!(base_dx + x, base_dy + y, w, h);
            }
            Node::Line(n) => {
                // Line bbox is the degenerate rect spanning (x1,y1)-(x2,y2).
                let (Some(x1d), Some(y1d), Some(x2d), Some(y2d)) = (&n.x1, &n.y1, &n.x2, &n.y2)
                else {
                    continue;
                };
                let (Some(x1), Some(y1), Some(x2), Some(y2)) = (
                    dim_to_px(x1d.value, &x1d.unit),
                    dim_to_px(y1d.value, &y1d.unit),
                    dim_to_px(x2d.value, &x2d.unit),
                    dim_to_px(y2d.value, &y2d.unit),
                ) else {
                    continue;
                };
                let lx = x1.min(x2);
                let ly = y1.min(y2);
                let lw = (x2 - x1).abs();
                let lh = (y2 - y1).abs();
                expand!(base_dx + lx, base_dy + ly, lw, lh);
            }
            Node::Polygon(n) => {
                if let Some((x, y, w, h)) = points_bbox(&n.points) {
                    expand!(base_dx + x, base_dy + y, w, h);
                }
            }
            Node::Polyline(n) => {
                if let Some((x, y, w, h)) = points_bbox(&n.points) {
                    expand!(base_dx + x, base_dy + y, w, h);
                }
            }
            Node::Group(n) => {
                // Nested group: use its declared w/h if available, else skip.
                let (Some(xd), Some(yd), Some(wd), Some(hd)) = (&n.x, &n.y, &n.w, &n.h) else {
                    continue;
                };
                let (Some(x), Some(y), Some(w), Some(h)) = (
                    resolve_geometry_px(Some(xd), resolved),
                    resolve_geometry_px(Some(yd), resolved),
                    resolve_geometry_px(Some(wd), resolved),
                    resolve_geometry_px(Some(hd), resolved),
                ) else {
                    continue;
                };
                expand!(base_dx + x, base_dy + y, w, h);
            }
            Node::Table(n) => {
                let (Some(xd), Some(yd), Some(wd), Some(hd)) = (&n.x, &n.y, &n.w, &n.h) else {
                    continue;
                };
                let (Some(x), Some(y), Some(w), Some(h)) = (
                    resolve_geometry_px(Some(xd), resolved),
                    resolve_geometry_px(Some(yd), resolved),
                    resolve_geometry_px(Some(wd), resolved),
                    resolve_geometry_px(Some(hd), resolved),
                ) else {
                    continue;
                };
                expand!(base_dx + x, base_dy + y, w, h);
            }
            Node::Shape(n) => {
                let (Some(xd), Some(yd), Some(wd), Some(hd)) = (&n.x, &n.y, &n.w, &n.h) else {
                    continue;
                };
                let (Some(x), Some(y), Some(w), Some(h)) = (
                    resolve_geometry_px(Some(xd), resolved),
                    resolve_geometry_px(Some(yd), resolved),
                    resolve_geometry_px(Some(wd), resolved),
                    resolve_geometry_px(Some(hd), resolved),
                ) else {
                    continue;
                };
                expand!(base_dx + x, base_dy + y, w, h);
            }
            Node::Light(n) => {
                let (Some(xd), Some(yd), Some(rd)) = (&n.x, &n.y, &n.radius) else {
                    continue;
                };
                let (Some(x), Some(y), Some(r)) = (
                    resolve_geometry_px(Some(xd), resolved),
                    resolve_geometry_px(Some(yd), resolved),
                    resolve_geometry_px(Some(rd), resolved),
                ) else {
                    continue;
                };
                expand!(base_dx + x - r, base_dy + y - r, r * 2.0, r * 2.0);
            }
            Node::Mesh(n) => {
                let (Some(xd), Some(yd), Some(wd), Some(hd)) = (&n.x, &n.y, &n.w, &n.h) else {
                    continue;
                };
                let (Some(x), Some(y), Some(w), Some(h)) = (
                    resolve_geometry_px(Some(xd), resolved),
                    resolve_geometry_px(Some(yd), resolved),
                    resolve_geometry_px(Some(wd), resolved),
                    resolve_geometry_px(Some(hd), resolved),
                ) else {
                    continue;
                };
                expand!(base_dx + x, base_dy + y, w, h);
            }
            // Instances have no authoritative bbox (their expanded subtree is
            // the geometry); a field's/toc's box is resolved at projection time,
            // not here; unknown nodes have no geometry — skip all.
            // A footnote has no authored bbox (it renders in the footnote zone).
            Node::Instance(_)
            | Node::Field(_)
            | Node::Toc(_)
            | Node::Footnote(_)
            | Node::Connector(_)
            | Node::Pattern(_)
            | Node::Chart(_)
            | Node::Unknown(_) => {}
        }
    }

    if min_x.is_finite() && min_y.is_finite() && max_x.is_finite() && max_y.is_finite() {
        Some(((min_x + max_x) / 2.0, (min_y + max_y) / 2.0))
    } else {
        None
    }
}