Skip to main content

qualia_core_db/render/
rdf_holograph.rs

1//! RDF / NQuin → holographic semantic-graph layout.
2//!
3//! Hot path is zero-heap: stack `QuinCollector`, open-addressed id table, and a
4//! caller-owned [`RdfHolographScene`] of fixed arrays. GPU residency (SSBO /
5//! RGBA32F) is the larger graphics budget; this file does not `Vec` / `BTreeMap`
6//! / `String` on layout, atlas pack, or framing.
7//!
8//! Projects 48-byte NQuins into the 96-byte [`HolographicNodeGpu`] contract used by
9//! the Holographic 3D Engine (WebGPU SSBO) and the WebGL2 GLSL ES 300 theatre
10//! (RGBA32F node texture, 6 texels per node). No new `.10d` / `.emf` magics.
11
12use std::io::Cursor;
13
14use crate::render::gpu::holographic::{HolographicNodeGpu, HolographicPrimitive};
15use crate::sparql_library::rdf_formats::{parse_rdf, QuinCollector, RdfFormat};
16use crate::{q_hash, NQuin};
17
18/// Six RGBA32F texels pack one 96-byte holographic node.
19pub const HOLOGRAPH_TEXELS_PER_NODE: usize = 6;
20/// Mobile-safe instance cap for the WebGL2 RGBA32F atlas (height = node count).
21pub const MAX_HOLOGRAPH_NODES: usize = 2048;
22const ID_HASH_CAP: usize = 4096;
23const ID_HASH_EMPTY: u16 = u16::MAX;
24
25const RDF_TYPE: u64 = q_hash("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
26
27const COLOR_CLASS: [f32; 4] = [0.52, 0.68, 1.0, 1.0];
28const COLOR_INSTANCE: [f32; 4] = [0.28, 0.88, 1.0, 1.0];
29const COLOR_LITERAL: [f32; 4] = [1.0, 0.78, 0.32, 1.0];
30const COLOR_TYPE_EDGE: [f32; 4] = [1.0, 0.86, 0.34, 1.0];
31
32/// One labelled holographic entity after 10D → 3D projection.
33#[derive(Debug, Clone, Copy)]
34pub struct RdfHolographLabel {
35    pub id: u64,
36    pub kind: &'static str,
37    pub degree: u32,
38    pub position: [f32; 3],
39    pub name: [u8; 24],
40    pub name_len: u8,
41}
42
43impl Default for RdfHolographLabel {
44    fn default() -> Self {
45        Self {
46            id: 0,
47            kind: "",
48            degree: 0,
49            position: [0.0; 3],
50            name: [0; 24],
51            name_len: 0,
52        }
53    }
54}
55
56impl RdfHolographLabel {
57    fn with_kind(id: u64, kind: &'static str, degree: u32, position: [f32; 3]) -> Self {
58        Self {
59            id,
60            kind,
61            degree,
62            position,
63            name: [0; 24],
64            name_len: 0,
65        }
66    }
67
68    /// UTF-8 display name filled at ingest; empty when unknown.
69    pub fn name_str(&self) -> &str {
70        let n = self.name_len as usize;
71        core::str::from_utf8(&self.name[..n.min(24)]).unwrap_or("")
72    }
73
74    /// Copy a display name. Ingest only; ignored when already set.
75    pub fn set_name(&mut self, s: &str) {
76        if self.name_len != 0 || s.is_empty() {
77            return;
78        }
79        let b = s.as_bytes();
80        let n = b.len().min(24);
81        self.name[..n].copy_from_slice(&b[..n]);
82        self.name_len = n as u8;
83    }
84}
85
86/// Laid-out holographic RDF scene. Fixed arrays; caller owns residency.
87pub struct RdfHolographScene {
88    nodes: [HolographicNodeGpu; MAX_HOLOGRAPH_NODES],
89    labels: [RdfHolographLabel; MAX_HOLOGRAPH_NODES],
90    node_count: u16,
91    label_count: u16,
92    pub triple_count: u32,
93    pub truncated: bool,
94}
95
96impl RdfHolographScene {
97    /// Zeroed resident scene. One-time fill; not a per-frame allocation.
98    pub fn empty() -> Self {
99        Self {
100            nodes: [HolographicNodeGpu::default(); MAX_HOLOGRAPH_NODES],
101            labels: [RdfHolographLabel::default(); MAX_HOLOGRAPH_NODES],
102            node_count: 0,
103            label_count: 0,
104            triple_count: 0,
105            truncated: false,
106        }
107    }
108
109    /// Heap-resident scene for WASM portal construction (avoids a 261 KiB stack frame).
110    pub fn empty_box() -> Box<Self> {
111        Box::new(Self::empty())
112    }
113
114    /// Drops occupancy; keeps the resident arrays.
115    pub fn clear(&mut self) {
116        self.node_count = 0;
117        self.label_count = 0;
118        self.triple_count = 0;
119        self.truncated = false;
120    }
121
122    #[inline]
123    pub fn node_count(&self) -> usize {
124        self.node_count as usize
125    }
126
127    #[inline]
128    pub fn is_empty(&self) -> bool {
129        self.node_count == 0
130    }
131
132    #[inline]
133    pub fn nodes(&self) -> &[HolographicNodeGpu] {
134        &self.nodes[..self.node_count as usize]
135    }
136
137    #[inline]
138    pub fn labels(&self) -> &[RdfHolographLabel] {
139        &self.labels[..self.label_count as usize]
140    }
141
142    /// Mutable labels for ingest name fill. Not a paint-path API.
143    #[inline]
144    pub fn labels_mut(&mut self) -> &mut [RdfHolographLabel] {
145        &mut self.labels[..self.label_count as usize]
146    }
147
148    #[inline]
149    fn push_node(&mut self, node: HolographicNodeGpu, label: RdfHolographLabel) -> bool {
150        let i = self.node_count as usize;
151        if i >= MAX_HOLOGRAPH_NODES {
152            self.truncated = true;
153            return false;
154        }
155        self.nodes[i] = node;
156        self.labels[i] = label;
157        self.node_count += 1;
158        self.label_count += 1;
159        true
160    }
161}
162
163fn unit(id: u64, salt: u64) -> f32 {
164    let x = id.wrapping_mul(0x9E37_79B9_7F4A_7C15).wrapping_add(salt);
165    (x >> 40) as f32 / 16_777_215.0
166}
167
168/// 10D address [q,v,w,x,y,z,t,α,μ,σ] folded to a cinematic 3-space with context as height.
169pub fn project_10d(id: u64, context: u64, degree: u32) -> [f32; 3] {
170    let u = unit(id, 0xA11CE);
171    let v = unit(id, 0xB0B);
172    let w = unit(context, 0xC0DE);
173    let theta = u * std::f32::consts::TAU;
174    let phi = (2.0 * v - 1.0).clamp(-1.0, 1.0).acos();
175    let radius = 2.15 + (degree as f32 + 1.0).ln() * 0.28 + w * 0.35;
176    let x = radius * phi.sin() * theta.cos();
177    let y = radius * phi.cos() * 0.58 + (w - 0.5) * 0.70;
178    let z = radius * phi.sin() * theta.sin();
179    [x, y, z]
180}
181
182fn cool_predicate_color(pred: u64) -> [f32; 4] {
183    let t = unit(pred, 0xC01A);
184    [
185        0.18 + t * 0.22,
186        0.55 + unit(pred, 0x5EED) * 0.35,
187        0.82 + unit(pred, 0xF00D) * 0.16,
188        1.0,
189    ]
190}
191
192struct IdTable {
193    slot: [u16; ID_HASH_CAP],
194    id: [u64; MAX_HOLOGRAPH_NODES],
195    degree: [u32; MAX_HOLOGRAPH_NODES],
196    context: [u64; MAX_HOLOGRAPH_NODES],
197    flags: [u8; MAX_HOLOGRAPH_NODES],
198    count: u16,
199}
200
201impl IdTable {
202    fn new() -> Self {
203        Self {
204            slot: [ID_HASH_EMPTY; ID_HASH_CAP],
205            id: [0; MAX_HOLOGRAPH_NODES],
206            degree: [0; MAX_HOLOGRAPH_NODES],
207            context: [0; MAX_HOLOGRAPH_NODES],
208            flags: [0; MAX_HOLOGRAPH_NODES],
209            count: 0,
210        }
211    }
212
213    fn lookup_or_insert(&mut self, id: u64) -> Option<usize> {
214        let mut h = (id as usize) & (ID_HASH_CAP - 1);
215        for _ in 0..ID_HASH_CAP {
216            let s = self.slot[h];
217            if s == ID_HASH_EMPTY {
218                if self.count as usize >= MAX_HOLOGRAPH_NODES {
219                    return None;
220                }
221                let i = self.count as usize;
222                self.slot[h] = self.count;
223                self.id[i] = id;
224                self.count += 1;
225                return Some(i);
226            }
227            if self.id[s as usize] == id {
228                return Some(s as usize);
229            }
230            h = (h + 1) & (ID_HASH_CAP - 1);
231        }
232        None
233    }
234
235    fn get(&self, id: u64) -> Option<usize> {
236        let mut h = (id as usize) & (ID_HASH_CAP - 1);
237        for _ in 0..ID_HASH_CAP {
238            let s = self.slot[h];
239            if s == ID_HASH_EMPTY {
240                return None;
241            }
242            if self.id[s as usize] == id {
243                return Some(s as usize);
244            }
245            h = (h + 1) & (ID_HASH_CAP - 1);
246        }
247        None
248    }
249}
250
251const FLAG_SUBJECT: u8 = 1;
252const FLAG_CLASS: u8 = 2;
253
254fn kind_of(flags: u8, degree: u32) -> (&'static str, HolographicPrimitive, [f32; 4], f32) {
255    if flags & FLAG_SUBJECT == 0 && flags & FLAG_CLASS == 0 {
256        ("literal", HolographicPrimitive::RoundedBox, COLOR_LITERAL, 0.20)
257    } else if flags & FLAG_CLASS != 0 || degree >= 6 {
258        (
259            "class",
260            HolographicPrimitive::RoundedBox,
261            COLOR_CLASS,
262            0.46 + (degree as f32).ln_1p() * 0.06,
263        )
264    } else {
265        (
266            "instance",
267            HolographicPrimitive::Sphere,
268            COLOR_INSTANCE,
269            0.30 + (degree as f32).ln_1p() * 0.04,
270        )
271    }
272}
273
274/// Push overlapping resource crystals apart. Zero-heap Jacobi; n ≤ 2048.
275fn separate_resources(scene: &mut RdfHolographScene, resource_count: usize) {
276    let n = resource_count.min(scene.node_count as usize);
277    for _ in 0..4 {
278        for i in 0..n {
279            for j in (i + 1)..n {
280                let pi = scene.nodes[i].position_scale;
281                let pj = scene.nodes[j].position_scale;
282                let dx = pi[0] - pj[0];
283                let dy = pi[1] - pj[1];
284                let dz = pi[2] - pj[2];
285                let dist = (dx * dx + dy * dy + dz * dz).sqrt();
286                let min_d = (pi[3] + pj[3]) * 1.18 + 0.22;
287                if dist >= min_d {
288                    continue;
289                }
290                let inv = ((min_d - dist) * 0.42) / dist.max(1e-4) * 0.5;
291                scene.nodes[i].position_scale[0] += dx * inv;
292                scene.nodes[i].position_scale[1] += dy * inv;
293                scene.nodes[i].position_scale[2] += dz * inv;
294                scene.nodes[j].position_scale[0] -= dx * inv;
295                scene.nodes[j].position_scale[1] -= dy * inv;
296                scene.nodes[j].position_scale[2] -= dz * inv;
297                scene.labels[i].position = [
298                    scene.nodes[i].position_scale[0],
299                    scene.nodes[i].position_scale[1],
300                    scene.nodes[i].position_scale[2],
301                ];
302                scene.labels[j].position = [
303                    scene.nodes[j].position_scale[0],
304                    scene.nodes[j].position_scale[1],
305                    scene.nodes[j].position_scale[2],
306                ];
307            }
308        }
309    }
310}
311
312/// Layout NQuins into a caller-owned scene. No heap.
313pub fn layout_nquins_into(quins: &[NQuin], scene: &mut RdfHolographScene) {
314    scene.clear();
315    scene.triple_count = quins.len() as u32;
316
317    let mut table = IdTable::new();
318    for q in quins {
319        match table.lookup_or_insert(q.subject) {
320            Some(i) => {
321                table.degree[i] = table.degree[i].saturating_add(1);
322                if table.context[i] == 0 {
323                    table.context[i] = q.context;
324                }
325                table.flags[i] |= FLAG_SUBJECT;
326            }
327            None => scene.truncated = true,
328        }
329        match table.lookup_or_insert(q.object) {
330            Some(i) => {
331                table.degree[i] = table.degree[i].saturating_add(1);
332                if table.context[i] == 0 {
333                    table.context[i] = q.context;
334                }
335                if q.predicate == RDF_TYPE {
336                    table.flags[i] |= FLAG_CLASS;
337                }
338            }
339            None => scene.truncated = true,
340        }
341    }
342
343    for i in 0..table.count as usize {
344        if !scene.push_node(
345            {
346                let id = table.id[i];
347                let deg = table.degree[i].max(1);
348                let pos = project_10d(id, table.context[i], deg);
349                let (kind, prim, color, scale) = kind_of(table.flags[i], deg);
350                let mut node = HolographicNodeGpu::new(
351                    pos,
352                    scale,
353                    [scale, scale, if kind == "literal" { scale * 1.8 } else { scale }],
354                    prim,
355                    0.35 + unit(id, 7) * 0.9,
356                    0.85,
357                    unit(id, 13) * std::f32::consts::TAU,
358                    1.15,
359                    unit(id, 0xE915),
360                    color,
361                );
362                node.manifold_tensor[1] = manifold_code(kind, false);
363                let _ = kind;
364                node
365            },
366            {
367                let id = table.id[i];
368                let deg = table.degree[i].max(1);
369                let pos = project_10d(id, table.context[i], deg);
370                let (kind, _, _, _) = kind_of(table.flags[i], deg);
371                RdfHolographLabel::with_kind(id, kind, deg, pos)
372            },
373        ) {
374            break;
375        }
376    }
377
378    separate_resources(scene, table.count as usize);
379
380    for q in quins {
381        let Some(si) = table.get(q.subject) else {
382            continue;
383        };
384        let Some(oi) = table.get(q.object) else {
385            continue;
386        };
387        let from = [
388            scene.nodes[si].position_scale[0],
389            scene.nodes[si].position_scale[1],
390            scene.nodes[si].position_scale[2],
391        ];
392        let to = [
393            scene.nodes[oi].position_scale[0],
394            scene.nodes[oi].position_scale[1],
395            scene.nodes[oi].position_scale[2],
396        ];
397        let mid = [
398            (from[0] + to[0]) * 0.5,
399            (from[1] + to[1]) * 0.5,
400            (from[2] + to[2]) * 0.5,
401        ];
402        let dx = to[0] - from[0];
403        let dy = to[1] - from[1];
404        let dz = to[2] - from[2];
405        let span = (dx * dx + dy * dy + dz * dz).sqrt().max(0.2);
406        let is_type = q.predicate == RDF_TYPE;
407        let color = if is_type {
408            COLOR_TYPE_EDGE
409        } else {
410            cool_predicate_color(q.predicate)
411        };
412        let radius = if is_type { 0.10 } else { 0.062 };
413        // Tight capsule AABB plus a halo pad. Fat isotropic padding drew ghost cubes.
414        let pad = 0.42;
415        let hx = dx.abs() * 0.5 + radius + pad;
416        let hy = dy.abs() * 0.5 + radius + pad;
417        let hz = dz.abs() * 0.5 + radius + pad;
418        let mut node = HolographicNodeGpu::new(
419            mid,
420            span * 0.5,
421            [hx.max(0.18), hy.max(0.18), hz.max(0.18)],
422            HolographicPrimitive::InterferenceBridge,
423            0.8 + unit(q.predicate, 3) * 1.4,
424            1.0,
425            (q.metadata & 0xFFFF_FFFF) as f32 * 0.0001,
426            0.7,
427            0.35,
428            color,
429        )
430        .with_interference_bridge(to, 0.9);
431        node.manifold_tensor[1] = manifold_code("predicate", is_type);
432        if !scene.push_node(
433            node,
434            RdfHolographLabel::with_kind(q.predicate, "predicate", 1, mid),
435        ) {
436            break;
437        }
438    }
439    recenter_on_resource_centroid(scene);
440
441    let resource_end = (table.count as usize).min(scene.node_count as usize);
442    for i in 0..resource_end {
443        if scene.labels[i].kind != "class" {
444            continue;
445        }
446        let pos = [
447            scene.nodes[i].position_scale[0],
448            scene.nodes[i].position_scale[1],
449            scene.nodes[i].position_scale[2],
450        ];
451        let well = (scene.nodes[i].position_scale[3] * 2.2).max(1.4);
452        let mut node = HolographicNodeGpu::new(
453            pos,
454            well,
455            [well, well, well],
456            HolographicPrimitive::Metaball,
457            0.12,
458            0.40,
459            0.0,
460            0.40,
461            0.20,
462            [0.16, 0.24, 0.55, 0.35],
463        );
464        node.manifold_tensor[1] = manifold_code("plane", false);
465        if !scene.push_node(
466            node,
467            RdfHolographLabel::with_kind(
468                scene.labels[i].id,
469                "plane",
470                scene.labels[i].degree,
471                pos,
472            ),
473        ) {
474            break;
475        }
476    }
477}
478
479/// Test helper: stack/box scene filled from quins.
480pub fn layout_nquins(quins: &[NQuin]) -> Box<RdfHolographScene> {
481    let mut scene = Box::new(RdfHolographScene::empty());
482    layout_nquins_into(quins, &mut scene);
483    scene
484}
485
486fn recenter_on_resource_centroid(scene: &mut RdfHolographScene) {
487    let mut cx = 0.0f32;
488    let mut cy = 0.0f32;
489    let mut cz = 0.0f32;
490    let mut n = 0.0f32;
491    for i in 0..scene.label_count as usize {
492        let label = &scene.labels[i];
493        if label.kind == "predicate" || label.kind == "plane" {
494            continue;
495        }
496        cx += label.position[0];
497        cy += label.position[1];
498        cz += label.position[2];
499        n += 1.0;
500    }
501    if n <= 0.0 {
502        return;
503    }
504    cx /= n;
505    cy /= n;
506    cz /= n;
507    for i in 0..scene.node_count as usize {
508        scene.nodes[i].position_scale[0] -= cx;
509        scene.nodes[i].position_scale[1] -= cy;
510        scene.nodes[i].position_scale[2] -= cz;
511        scene.nodes[i].connection_endpoint[0] -= cx;
512        scene.nodes[i].connection_endpoint[1] -= cy;
513        scene.nodes[i].connection_endpoint[2] -= cz;
514    }
515    for i in 0..scene.label_count as usize {
516        scene.labels[i].position[0] -= cx;
517        scene.labels[i].position[1] -= cy;
518        scene.labels[i].position[2] -= cz;
519    }
520}
521
522/// Orbit distance that fits resource crystals in the vertical FOV.
523/// Predicate capsules store half-span in `position_scale.w`; counting that as a
524/// sphere radius pulled the camera so far the field collapsed to a cluster.
525/// k=1.22 with a 4.2–16 clamp keeps a small constellation (FOAF/Star) in frame
526/// instead of filling the viewport with a single glass close-up.
527pub fn framing_zoom(scene: &RdfHolographScene) -> f32 {
528    let mut max_r = 1.0f32;
529    for (i, node) in scene.nodes().iter().enumerate() {
530        if scene
531            .labels()
532            .get(i)
533            .is_some_and(|l| l.kind == "predicate" || l.kind == "plane")
534        {
535            continue;
536        }
537        let r = (node.position_scale[0].hypot(node.position_scale[2]))
538            .hypot(node.position_scale[1])
539            + node.position_scale[3] * 1.05
540            + 0.22;
541        max_r = max_r.max(r);
542    }
543    (max_r / crate::render::camera::CAMERA_TAN_HALF_FOV * 1.22).clamp(4.2, 16.0)
544}
545
546/// Classify a resource for packing. Quoted lexical forms that never appear as
547/// a subject are literals; rdf:type objects / high-degree hubs are classes;
548/// remaining IRIs are instances even when they only appear as objects.
549pub fn classify_resource_kind(
550    is_subject: bool,
551    is_class: bool,
552    degree: u32,
553    quoted_literal: bool,
554) -> &'static str {
555    if is_class || degree >= 6 {
556        "class"
557    } else if quoted_literal && !is_subject {
558        "literal"
559    } else {
560        "instance"
561    }
562}
563
564/// Intern a vibe/JS kind string to a `'static` label used on the hot path.
565pub fn intern_kind(kind: &str) -> &'static str {
566    match kind {
567        "class" => "class",
568        "literal" => "literal",
569        "predicate" | "edge" | "filament" => "predicate",
570        "plane" | "well" => "plane",
571        _ => "instance",
572    }
573}
574
575/// Shader `manifold_tensor[1]` code for an interned kind.
576/// 0 instance, 1 class, 2 literal, 3 rdf:type filament, 4 property filament, 5 plane.
577pub fn manifold_code(kind: &str, is_type: bool) -> f32 {
578    match intern_kind(kind) {
579        "class" => 1.0,
580        "literal" => 2.0,
581        "predicate" => {
582            if is_type {
583                3.0
584            } else {
585                4.0
586            }
587        }
588        "plane" => 5.0,
589        _ => 0.0,
590    }
591}
592
593/// Local display token of an expanded IRI or literal lexical form.
594pub fn display_local_name(lexical: &str) -> &str {
595    lexical
596        .rsplit(['#', '/'])
597        .next()
598        .unwrap_or(lexical)
599        .split(':')
600        .next_back()
601        .unwrap_or(lexical)
602}
603
604/// Y-rotate a world point by the holographic W-angle.
605pub fn rotate_y_w(p: [f32; 3], angle: f32) -> [f32; 3] {
606    let c = angle.cos();
607    let s = angle.sin();
608    [p[0] * c - p[2] * s, p[1], p[0] * s + p[2] * c]
609}
610
611/// Rotate by W then project to NDC. `None` when clip.w is degenerate.
612pub fn project_world_ndc(
613    world: [f32; 3],
614    view_projection: &[[f32; 4]; 4],
615    w_angle: f32,
616) -> Option<[f32; 3]> {
617    let p = rotate_y_w(world, w_angle);
618    let clip = mul_col(view_projection, [p[0], p[1], p[2], 1.0]);
619    if clip[3].abs() < 1e-5 {
620        return None;
621    }
622    Some([clip[0] / clip[3], clip[1] / clip[3], clip[2] / clip[3]])
623}
624
625/// NDC xy → canvas pixels (origin top-left).
626pub fn ndc_to_canvas(ndc_x: f32, ndc_y: f32, canvas_w: f32, canvas_h: f32) -> [f32; 2] {
627    [
628        (ndc_x * 0.5 + 0.5) * canvas_w,
629        (0.5 - ndc_y * 0.5) * canvas_h,
630    ]
631}
632
633/// Fill empty label names at ingest. Already-set names win.
634pub fn fill_label_names<'a>(
635    scene: &mut RdfHolographScene,
636    mut name_of: impl FnMut(u64) -> Option<&'a str>,
637) {
638    for label in scene.labels_mut() {
639        if let Some(n) = name_of(label.id) {
640            label.set_name(n);
641        }
642    }
643}
644
645/// One in-field name chip after camera projection. Caller owns the output slot.
646#[derive(Debug, Clone, Copy)]
647pub struct HolographOverlay {
648    pub index: u16,
649    pub kind: &'static str,
650    pub sx: f32,
651    pub sy: f32,
652    pub name: [u8; 24],
653    pub name_len: u8,
654}
655
656impl Default for HolographOverlay {
657    fn default() -> Self {
658        Self {
659            index: 0,
660            kind: "",
661            sx: 0.0,
662            sy: 0.0,
663            name: [0; 24],
664            name_len: 0,
665        }
666    }
667}
668
669impl HolographOverlay {
670    pub fn name_str(&self) -> &str {
671        let n = self.name_len as usize;
672        core::str::from_utf8(&self.name[..n.min(24)]).unwrap_or("")
673    }
674}
675
676/// Project named resource crystals to canvas pixels. Skips filaments and wells.
677/// `out` is caller-owned; returns the number of chips written.
678pub fn overlay_chips_into(
679    scene: &RdfHolographScene,
680    view_projection: &[[f32; 4]; 4],
681    w_angle: f32,
682    canvas_w: f32,
683    canvas_h: f32,
684    out: &mut [HolographOverlay],
685) -> usize {
686    if canvas_w < 1.0 || canvas_h < 1.0 || out.is_empty() {
687        return 0;
688    }
689    let mut n = 0usize;
690    for (i, label) in scene.labels().iter().enumerate() {
691        if n >= out.len() {
692            break;
693        }
694        if label.kind == "predicate" || label.kind == "plane" || label.name_len == 0 {
695            continue;
696        }
697        let Some(ndc) = project_world_ndc(label.position, view_projection, w_angle) else {
698            continue;
699        };
700        if ndc[0].abs() > 1.15 || ndc[1].abs() > 1.15 {
701            continue;
702        }
703        let xy = ndc_to_canvas(ndc[0], ndc[1], canvas_w, canvas_h);
704        let mut chip = HolographOverlay {
705            index: i as u16,
706            kind: label.kind,
707            sx: xy[0],
708            sy: xy[1],
709            name: [0; 24],
710            name_len: label.name_len,
711        };
712        let len = label.name_len as usize;
713        chip.name[..len.min(24)].copy_from_slice(&label.name[..len.min(24)]);
714        out[n] = chip;
715        n += 1;
716    }
717    n
718}
719
720/// One vibe-placed holographic entity. Ingest may allocate the slice; packing
721/// into [`RdfHolographScene`] stays on the caller-owned fixed arrays.
722#[derive(Debug, Clone, Copy)]
723pub struct PlacedHolograph {
724    pub id: u64,
725    pub kind: &'static str,
726    pub degree: u32,
727    pub position: [f32; 3],
728    pub endpoint: [f32; 3],
729    pub scale: f32,
730    pub is_type: bool,
731    pub name: [u8; 24],
732    pub name_len: u8,
733}
734
735impl Default for PlacedHolograph {
736    fn default() -> Self {
737        Self {
738            id: 0,
739            kind: "instance",
740            degree: 1,
741            position: [0.0; 3],
742            endpoint: [0.0; 3],
743            scale: 0.30,
744            is_type: false,
745            name: [0; 24],
746            name_len: 0,
747        }
748    }
749}
750
751impl PlacedHolograph {
752    /// Fill the 24-byte display name from ingest.
753    pub fn set_name(&mut self, s: &str) {
754        if self.name_len != 0 || s.is_empty() {
755            return;
756        }
757        let b = s.as_bytes();
758        let n = b.len().min(24);
759        self.name[..n].copy_from_slice(&b[..n]);
760        self.name_len = n as u8;
761    }
762}
763
764fn pack_placed(placed: &PlacedHolograph) -> (HolographicNodeGpu, RdfHolographLabel) {
765    let kind = intern_kind(placed.kind);
766    let scale = placed.scale.max(0.05);
767    let pos = placed.position;
768    let manifold = manifold_code(kind, placed.is_type);
769    let (prim, color, half) = match kind {
770        "class" => (
771            HolographicPrimitive::RoundedBox,
772            COLOR_CLASS,
773            [scale, scale, scale],
774        ),
775        "literal" => (
776            HolographicPrimitive::RoundedBox,
777            COLOR_LITERAL,
778            [scale, scale, scale * 1.8],
779        ),
780        "predicate" => {
781            let color = if placed.is_type {
782                COLOR_TYPE_EDGE
783            } else {
784                cool_predicate_color(placed.id)
785            };
786            (
787                HolographicPrimitive::InterferenceBridge,
788                color,
789                [scale, scale, scale],
790            )
791        }
792        "plane" => (
793            HolographicPrimitive::Metaball,
794            [0.16, 0.24, 0.55, 0.35],
795            [scale, scale, scale],
796        ),
797        _ => (
798            HolographicPrimitive::Sphere,
799            COLOR_INSTANCE,
800            [scale, scale, scale],
801        ),
802    };
803    let mut node = if kind == "predicate" {
804        let to = placed.endpoint;
805        let from = [
806            2.0 * pos[0] - to[0],
807            2.0 * pos[1] - to[1],
808            2.0 * pos[2] - to[2],
809        ];
810        let dx = to[0] - from[0];
811        let dy = to[1] - from[1];
812        let dz = to[2] - from[2];
813        let span = (dx * dx + dy * dy + dz * dz).sqrt().max(0.2);
814        let radius = if placed.is_type { 0.10 } else { 0.062 };
815        let pad = 0.42;
816        let hx = dx.abs() * 0.5 + radius + pad;
817        let hy = dy.abs() * 0.5 + radius + pad;
818        let hz = dz.abs() * 0.5 + radius + pad;
819        HolographicNodeGpu::new(
820            pos,
821            span * 0.5,
822            [hx.max(0.18), hy.max(0.18), hz.max(0.18)],
823            prim,
824            0.8 + unit(placed.id, 3) * 1.4,
825            1.0,
826            0.0,
827            0.7,
828            0.35,
829            color,
830        )
831        .with_interference_bridge(to, 0.9)
832    } else if kind == "plane" {
833        HolographicNodeGpu::new(
834            pos,
835            scale,
836            half,
837            prim,
838            0.12,
839            0.40,
840            0.0,
841            0.40,
842            0.20,
843            color,
844        )
845    } else {
846        HolographicNodeGpu::new(
847            pos,
848            scale,
849            half,
850            prim,
851            0.35 + unit(placed.id, 7) * 0.9,
852            0.85,
853            unit(placed.id, 13) * std::f32::consts::TAU,
854            1.15,
855            unit(placed.id, 0xE915),
856            color,
857        )
858    };
859    node.manifold_tensor[1] = manifold;
860    let mut label = RdfHolographLabel::with_kind(placed.id, kind, placed.degree.max(1), pos);
861    if placed.name_len > 0 {
862        let n = placed.name_len as usize;
863        label.name[..n.min(24)].copy_from_slice(&placed.name[..n.min(24)]);
864        label.name_len = placed.name_len;
865    }
866    (node, label)
867}
868
869/// Pack vibe-placed records into a caller-owned scene. No heap.
870pub fn layout_placed_into(
871    placed: &[PlacedHolograph],
872    triple_count: u32,
873    scene: &mut RdfHolographScene,
874) {
875    scene.clear();
876    scene.triple_count = triple_count;
877    for p in placed {
878        let (node, label) = pack_placed(p);
879        if !scene.push_node(node, label) {
880            break;
881        }
882    }
883    recenter_on_resource_centroid(scene);
884}
885
886fn mul_col(m: &[[f32; 4]; 4], v: [f32; 4]) -> [f32; 4] {
887    [
888        m[0][0] * v[0] + m[1][0] * v[1] + m[2][0] * v[2] + m[3][0] * v[3],
889        m[0][1] * v[0] + m[1][1] * v[1] + m[2][1] * v[2] + m[3][1] * v[3],
890        m[0][2] * v[0] + m[1][2] * v[1] + m[2][2] * v[2] + m[3][2] * v[3],
891        m[0][3] * v[0] + m[1][3] * v[1] + m[2][3] * v[2] + m[3][3] * v[3],
892    ]
893}
894
895/// Screen-space pick of a resource crystal. Skips filaments and semantic planes.
896/// `w_angle` matches the shader / overlay Y-rotation about W.
897pub fn pick_resource_at(
898    scene: &RdfHolographScene,
899    view_projection: &[[f32; 4]; 4],
900    w_angle: f32,
901    canvas_x: f32,
902    canvas_y: f32,
903    canvas_w: f32,
904    canvas_h: f32,
905) -> i32 {
906    if canvas_w < 1.0 || canvas_h < 1.0 {
907        return -1;
908    }
909    let mut best = -1i32;
910    let mut best_d = 44.0f32;
911    for (i, node) in scene.nodes().iter().enumerate() {
912        if scene
913            .labels()
914            .get(i)
915            .is_some_and(|l| l.kind == "predicate" || l.kind == "plane")
916        {
917            continue;
918        }
919        let world = [
920            node.position_scale[0],
921            node.position_scale[1],
922            node.position_scale[2],
923        ];
924        let Some(ndc) = project_world_ndc(world, view_projection, w_angle) else {
925            continue;
926        };
927        if ndc[0].abs() > 1.35 || ndc[1].abs() > 1.35 {
928            continue;
929        }
930        let xy = ndc_to_canvas(ndc[0], ndc[1], canvas_w, canvas_h);
931        let dist = (xy[0] - canvas_x).hypot(xy[1] - canvas_y);
932        if dist < best_d {
933            best_d = dist;
934            best = i as i32;
935        }
936    }
937    best
938}
939
940/// Parse an RDF document into a caller-owned scene. Parse errors are static.
941pub fn layout_rdf_into(
942    format: RdfFormat,
943    payload: &[u8],
944    scene: &mut RdfHolographScene,
945) -> Result<(), &'static str> {
946    let mut collector = QuinCollector::new();
947    parse_rdf(format, Cursor::new(payload), 0, &mut collector)
948        .map_err(|_| "rdf_holograph_parse_failed")?;
949    layout_nquins_into(collector.as_slice(), scene);
950    scene.truncated = scene.truncated || collector.truncated;
951    Ok(())
952}
953
954/// Parse by Content-Type or Qualia format id (`turtle`, `text/turtle`, …).
955pub fn layout_rdf_bytes_into(
956    content_type: &str,
957    payload: &[u8],
958    scene: &mut RdfHolographScene,
959) -> Result<(), &'static str> {
960    let format = RdfFormat::from_media_type(content_type)
961        .or_else(|| RdfFormat::from_str(content_type))
962        .ok_or("unsupported RDF Content-Type / format")?;
963    layout_rdf_into(format, payload, scene)
964}
965
966/// Parse a UTF-8 RDF document by Content-Type or Qualia format id.
967pub fn layout_rdf_str_into(
968    content_type: &str,
969    payload: &str,
970    scene: &mut RdfHolographScene,
971) -> Result<(), &'static str> {
972    layout_rdf_bytes_into(content_type, payload.as_bytes(), scene)
973}
974
975#[cfg(test)]
976mod tests {
977    use super::*;
978    use super::mul_col;
979
980    fn triple(s: u64, p: u64, o: u64) -> NQuin {
981        NQuin {
982            subject: s,
983            predicate: p,
984            object: o,
985            context: 7,
986            metadata: 3,
987            parity: NQuin::calculate_parity(s, p, o, 7, 3),
988        }
989    }
990
991    #[test]
992    fn empty_layout_is_empty() {
993        let scene = layout_nquins(&[]);
994        assert_eq!(scene.node_count(), 0);
995        assert_eq!(scene.triple_count, 0);
996        assert!(scene.nodes().is_empty());
997    }
998
999    #[test]
1000    fn one_triple_emits_two_resources_and_one_bridge() {
1001        let scene = layout_nquins(&[triple(11, 22, 33)]);
1002        assert_eq!(scene.triple_count, 1);
1003        assert_eq!(scene.node_count(), 3);
1004        assert_eq!(
1005            scene.labels().iter().filter(|l| l.kind != "predicate").count(),
1006            2
1007        );
1008        assert_eq!(
1009            scene.labels().iter().filter(|l| l.kind == "predicate").count(),
1010            1
1011        );
1012        let prim = scene.nodes()[2].half_extents_primitive[3] as u32;
1013        assert_eq!(prim, HolographicPrimitive::InterferenceBridge as u32);
1014        assert!(scene
1015            .nodes()
1016            .iter()
1017            .all(|n| n.position_scale.iter().all(|v| v.is_finite())));
1018        let mut cx = 0.0f32;
1019        let mut cy = 0.0f32;
1020        let mut cz = 0.0f32;
1021        let mut n = 0.0f32;
1022        for label in scene.labels().iter().filter(|l| l.kind != "predicate") {
1023            cx += label.position[0];
1024            cy += label.position[1];
1025            cz += label.position[2];
1026            n += 1.0;
1027        }
1028        cx /= n;
1029        cy /= n;
1030        cz /= n;
1031        assert!(cx.abs() < 1e-5 && cy.abs() < 1e-5 && cz.abs() < 1e-5);
1032        let zoom = framing_zoom(&scene);
1033        assert!(zoom >= 4.2 && zoom <= 16.0);
1034        let packed: &[f32] = bytemuck::cast_slice(scene.nodes());
1035        assert_eq!(packed.len(), scene.node_count() * 24);
1036    }
1037
1038    #[test]
1039    fn cinema_framing_places_resources_in_ndc() {
1040        let ttl = br#"@prefix foaf: <http://xmlns.com/foaf/0.1/> .
1041<http://ex/alice> foaf:knows <http://ex/bob> .
1042<http://ex/bob> foaf:knows <http://ex/carol> .
1043<http://ex/carol> foaf:knows <http://ex/alice> .
1044<http://ex/alice> foaf:name "Alice" .
1045"#;
1046        let mut scene = Box::new(RdfHolographScene::empty());
1047        layout_rdf_into(RdfFormat::Turtle, ttl, &mut scene).expect("turtle");
1048        let zoom = framing_zoom(&scene);
1049        let vp = crate::render::camera::orbit_view_projection_with_near(
1050            0.55,
1051            0.38,
1052            zoom,
1053            [0.0, 0.0, 0.0],
1054            16.0 / 9.0,
1055            0.05,
1056        );
1057        let mut in_frame = 0u32;
1058        for (i, node) in scene.nodes().iter().enumerate() {
1059            if scene.labels()[i].kind == "predicate" {
1060                let he = node.half_extents_primitive;
1061                let mid = node.position_scale;
1062                let end = node.connection_endpoint;
1063                assert!(
1064                    (end[0] - mid[0]).abs() <= he[0] + 0.02
1065                        && (end[1] - mid[1]).abs() <= he[1] + 0.02
1066                        && (end[2] - mid[2]).abs() <= he[2] + 0.02,
1067                    "bridge AABB must cover the capsule endpoint"
1068                );
1069                continue;
1070            }
1071            let clip = mul_col(&vp, [node.position_scale[0], node.position_scale[1], node.position_scale[2], 1.0]);
1072            assert!(clip[3].abs() > 1e-5, "clip.w");
1073            let ndc = [clip[0] / clip[3], clip[1] / clip[3], clip[2] / clip[3]];
1074            if ndc[0].abs() < 1.25 && ndc[1].abs() < 1.25 && (0.0..1.0).contains(&ndc[2]) {
1075                in_frame += 1;
1076            }
1077        }
1078        assert!(
1079            in_frame >= 3,
1080            "cinema framing must put resource crystals in frame (in_frame={in_frame}, zoom={zoom})"
1081        );
1082    }
1083
1084    #[test]
1085    fn turtle_layout_parses_and_projects() {
1086        let ttl = br#"@prefix foaf: <http://xmlns.com/foaf/0.1/> .
1087<http://ex/alice> foaf:knows <http://ex/bob> .
1088<http://ex/bob> foaf:knows <http://ex/carol> .
1089"#;
1090        let mut scene = Box::new(RdfHolographScene::empty());
1091        layout_rdf_into(RdfFormat::Turtle, ttl, &mut scene).expect("turtle");
1092        assert!(scene.triple_count >= 2);
1093        assert!(scene.node_count() >= 5);
1094        let packed: &[f32] = bytemuck::cast_slice(scene.nodes());
1095        assert_eq!(packed.len(), scene.node_count() * HOLOGRAPH_TEXELS_PER_NODE * 4);
1096    }
1097
1098    #[test]
1099    fn class_hub_emits_semantic_plane() {
1100        let ttl = br#"@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
1101<http://ex/n> rdf:type <http://ex/Core> .
1102"#;
1103        let mut scene = Box::new(RdfHolographScene::empty());
1104        layout_rdf_into(RdfFormat::Turtle, ttl, &mut scene).expect("turtle");
1105        assert!(scene.labels().iter().any(|l| l.kind == "class"));
1106        assert_eq!(
1107            scene.labels().iter().filter(|l| l.kind == "plane").count(),
1108            1
1109        );
1110        let plane = scene
1111            .nodes()
1112            .iter()
1113            .zip(scene.labels())
1114            .find(|(_, l)| l.kind == "plane")
1115            .unwrap()
1116            .0;
1117        assert!((plane.manifold_tensor[1] - 5.0).abs() < 1e-5);
1118        assert!(plane.position_scale[3] >= 1.4);
1119    }
1120
1121    #[test]
1122    fn project_10d_is_stable_and_bounded() {
1123        let a = project_10d(42, 1, 3);
1124        let b = project_10d(42, 1, 3);
1125        assert_eq!(a, b);
1126        assert!(a.iter().all(|v| v.is_finite() && v.abs() < 20.0));
1127        let c = project_10d(42, 99, 3);
1128        assert_ne!(a[1], c[1]);
1129    }
1130
1131    #[test]
1132    fn layout_nquins_into_reuses_resident_scene() {
1133        let mut scene = Box::new(RdfHolographScene::empty());
1134        layout_nquins_into(&[triple(1, 2, 3)], &mut scene);
1135        let first = scene.node_count();
1136        layout_nquins_into(&[triple(4, 5, 6), triple(6, 7, 4)], &mut scene);
1137        assert_eq!(first, 3);
1138        // 4 and 6 are resources; two predicates. 7 is a predicate, not a node.
1139        assert_eq!(scene.node_count(), 4);
1140        assert_eq!(scene.triple_count, 2);
1141    }
1142
1143    #[test]
1144    fn layout_placed_into_packs_named_triangle() {
1145        let mut a = PlacedHolograph {
1146            id: 1,
1147            kind: "instance",
1148            degree: 2,
1149            position: [1.0, 0.0, 0.0],
1150            scale: 0.30,
1151            ..PlacedHolograph::default()
1152        };
1153        a.set_name("alice");
1154        let mut b = PlacedHolograph {
1155            id: 2,
1156            kind: "instance",
1157            degree: 2,
1158            position: [-0.5, 0.0, 0.87],
1159            scale: 0.30,
1160            ..PlacedHolograph::default()
1161        };
1162        b.set_name("bob");
1163        let mut e = PlacedHolograph {
1164            id: 9,
1165            kind: "predicate",
1166            degree: 1,
1167            position: [0.25, 0.0, 0.435],
1168            endpoint: [-0.5, 0.0, 0.87],
1169            scale: 0.05,
1170            ..PlacedHolograph::default()
1171        };
1172        e.set_name("knows");
1173        let mut scene = Box::new(RdfHolographScene::empty());
1174        layout_placed_into(&[a, b, e], 1, &mut scene);
1175        assert_eq!(scene.node_count(), 3);
1176        assert_eq!(scene.triple_count, 1);
1177        assert_eq!(scene.labels()[0].name_str(), "alice");
1178        assert_eq!(scene.labels()[1].name_str(), "bob");
1179        assert_eq!(scene.labels()[2].kind, "predicate");
1180        let pa = scene.labels()[0].position;
1181        let pb = scene.labels()[1].position;
1182        let dx = pa[0] - pb[0];
1183        let dz = pa[2] - pb[2];
1184        assert!(dx * dx + dz * dz > 0.5, "placed resources stay apart");
1185        let zoom = framing_zoom(&scene);
1186        assert!(zoom >= 4.2 && zoom <= 16.0);
1187        let vp = crate::render::camera::orbit_view_projection_with_near(
1188            0.55,
1189            0.48,
1190            zoom,
1191            [0.0, 0.0, 0.0],
1192            16.0 / 9.0,
1193            0.05,
1194        );
1195        let mut chips = [HolographOverlay::default(); 8];
1196        let n = overlay_chips_into(&scene, &vp, 0.0, 1280.0, 720.0, &mut chips);
1197        assert_eq!(n, 2);
1198        assert_eq!(chips[0].name_str(), "alice");
1199        assert_eq!(intern_kind("filament"), "predicate");
1200        assert_eq!(intern_kind("well"), "plane");
1201        assert_eq!(
1202            classify_resource_kind(false, false, 1, true),
1203            "literal"
1204        );
1205        assert_eq!(
1206            classify_resource_kind(false, false, 1, false),
1207            "instance"
1208        );
1209        assert_eq!(classify_resource_kind(false, true, 1, false), "class");
1210        assert_eq!(display_local_name("http://ex/alice"), "alice");
1211        assert_eq!(manifold_code("class", false), 1.0);
1212        assert_eq!(manifold_code("filament", true), 3.0);
1213        assert_eq!(manifold_code("well", false), 5.0);
1214        let hit = pick_resource_at(&scene, &vp, 0.0, chips[0].sx, chips[0].sy, 1280.0, 720.0);
1215        assert_eq!(hit, chips[0].index as i32);
1216        fill_label_names(&mut scene, |_| Some("skip-set"));
1217        assert_eq!(scene.labels()[0].name_str(), "alice");
1218        fill_label_names(&mut scene, |id| if id == 9 { Some("knows") } else { None });
1219        assert_eq!(scene.labels()[2].name_str(), "knows");
1220    }
1221}