threers 0.1.0

Drop-in three.js replacement for Rust and WebAssembly (wgpu) — THREE.* API, scene graph, PBR, post-fx, mesh BVH, CSG, an OpenSCAD front end with a watertight exact-CSG kernel, headless render, and native media codecs
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
//! Density fields: kernels summed offscreen, then mapped through a ramp.

use super::gpu;
use super::{Column, ColumnFormat, KindUniforms, Mark, MarkCommon, MarkKind, PrepareContext};
use crate::math::ColorRamp;

/// The field's format. Half float sums thousands of overlapping kernels
/// without saturating and is a blendable render target on WebGL2 as well
/// (`EXT_color_buffer_float`), which a 32-bit float is not without a further
/// extension.
pub(crate) const FIELD_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;

/// A heatmap: every row adds a Gaussian kernel to a field, and the field is
/// coloured through a ramp — deck.gl's `HeatmapLayer`.
///
/// Two passes. The kernels are summed additively into an offscreen float
/// target; then one fullscreen pass samples that field, filtered, maps each
/// pixel's sum through [`ramp`](Self::set_ramp) and blends it over the frame.
/// Both are render passes, so it runs on WebGL2.
///
/// The sum is smooth, so the field need not be as sharp as the screen:
/// by default it is just fine enough for a kernel to span twelve texels of
/// radius, where it stays within 2 % of the full-resolution field, and never
/// coarser than a quarter of the viewport. Kernels 30 px in radius then sum
/// into a field with a sixth of the screen's pixels, 48 px and over a
/// sixteenth. [`resolution`](Self::resolution) overrides the choice.
///
/// The radius is [`MarkStyle::size_scale`](super::MarkStyle::size_scale), in
/// pixels or world units; each row's weight is its `weights` entry (1 by
/// default). The sum that reaches the top of the ramp is
/// [`max_weight`](Self::max_weight) — fixed rather than measured, so the colour
/// of a place does not change as other places scroll in and out of view — or,
/// with [`auto_max`](Self::auto_max), the densest pixel on screen, measured on
/// the GPU each frame and never read back.
#[derive(Debug)]
pub struct DensityMarks {
    pub common: MarkCommon,
    positions: Column,
    weights: Column,
    /// The summed weight that maps to the top of the ramp.
    pub max_weight: f32,
    /// Scale to the field instead of [`max_weight`](Self::max_weight): the
    /// top of the ramp is this fraction of the densest pixel drawn this
    /// frame — deck.gl's automatic colour domain. 1 puts the peak at the top;
    /// less saturates the peaks to show the sparse parts. The colour of a
    /// place then depends on what else is in view.
    pub auto_max: Option<f32>,
    /// Fraction of the ramp over which the field fades in from transparent.
    pub threshold: f32,
    /// The field's size as a fraction of the viewport's, per axis, in
    /// `0.05..=1`. `None` picks it from the kernel size: full resolution for
    /// kernels up to 12 px in radius, down to a quarter from 48 px.
    pub resolution: Option<f32>,
    /// The field's extent in viewport widths and heights about the
    /// viewport's centre (1 by default): past the edges too, so that kernels
    /// beyond them count towards [`auto_max`](Self::auto_max)'s densest
    /// place — as deck.gl's `HeatmapLayer` measures it over its 2048-texel
    /// weights texture, wider than the view.
    pub extent: [f32; 2],
    /// Kernels lie flat on the ground, their radius
    /// [`MarkStyle::size_scale`](super::MarkStyle::size_scale) in world
    /// units — foreshortened in a tilted view, as deck.gl's `HeatmapLayer`
    /// sums them on the ground — rather than facing the camera.
    pub ground: bool,
    /// Draw only the pixels whose centres lie in this rectangle, in the
    /// target's pixels from its top left (`[x0, y0, x1, y1]`): the quad a
    /// deck.gl `HeatmapLayer` draws its field on, which can stop short of
    /// the view's edges.
    pub cover: Option<[f32; 4]>,
    /// Fade in linearly, `min(t / threshold, 1)`, as deck.gl's
    /// `HeatmapLayer` does, rather than along a smoothstep.
    pub linear_fade: bool,
    /// Show each place's mean weight rather than its summed weight: the
    /// weights of the kernels covering it over their coverage (deck.gl's
    /// `aggregation: 'MEAN'`). Coverage below a floor counts as the floor,
    /// so a lone kernel's edge fades rather than showing its full weight.
    pub mean: bool,
    ramp: Vec<[u8; 4]>,
    ramp_dirty: bool,
    gpu: Option<DensityGpu>,
}

#[derive(Debug)]
struct DensityGpu {
    size: (u32, u32),
    field: gpu::TextureView,
    ramp: gpu::Texture,
    bind_group: gpu::BindGroup,
    /// The max reduction, field to one texel.
    levels: Vec<ReduceLevel>,
}

/// One step of the field's max reduction.
#[doc(hidden)]
#[derive(Debug)]
pub struct ReduceLevel {
    pub(crate) target: gpu::TextureView,
    /// Reads the level before (the field, for the first).
    pub(crate) bind_group: gpu::BindGroup,
}

/// Each level a quarter of the last per axis, down to one texel.
fn reduce_sizes(mut size: (u32, u32)) -> Vec<(u32, u32)> {
    let mut out = Vec::new();
    loop {
        size = (size.0.div_ceil(4).max(1), size.1.div_ceil(4).max(1));
        out.push(size);
        if size == (1, 1) {
            return out;
        }
    }
}

impl Default for DensityMarks {
    fn default() -> Self {
        Self::new()
    }
}

impl DensityMarks {
    pub fn new() -> Self {
        let mut weights = Column::float(1);
        weights.set_default_f32(&[1.0]);
        let mut common = MarkCommon::default();
        common.style.size_scale = 30.0;
        common.style.depth_test = false;
        common.style.pickable = false;
        let mut s = Self {
            common,
            positions: Column::new(ColumnFormat::PositionF64),
            weights,
            max_weight: 4.0,
            auto_max: None,
            threshold: 0.05,
            resolution: None,
            extent: [1.0; 2],
            ground: false,
            cover: None,
            linear_fade: false,
            mean: false,
            ramp: Vec::new(),
            ramp_dirty: true,
            gpu: None,
        };
        s.set_ramp(&ColorRamp::inferno());
        s
    }

    /// The field's size relative to the viewport this frame.
    pub fn field_scale(&self) -> f32 {
        if let Some(r) = self.resolution {
            return r.clamp(0.05, 1.0);
        }
        let s = &self.common.style;
        if s.units == super::SizeUnits::World {
            // The kernel's size on screen varies with depth; split the
            // difference.
            return 0.5;
        }
        let radius = s.size_scale.clamp(s.min_pixels, s.max_pixels);
        // Twelve texels across the radius: filtering between coarse texels
        // shaves a lone kernel's peak by about 4.5 / (2 n²), 1.6 % here.
        (12.0 / radius.max(1e-3)).clamp(0.25, 1.0)
    }

    pub fn set_positions(&mut self, p: &[[f64; 3]]) {
        self.common.local_origin = None;
        self.positions.set_positions(p);
    }
    /// Positions relative to `origin` — half the memory of absolute ones,
    /// and what a tile decoder produces. See
    /// [`ColumnFormat::PositionLocal`](super::ColumnFormat::PositionLocal).
    pub fn set_local_positions(&mut self, origin: [f64; 3], p: &[[f32; 3]]) {
        self.common.local_origin = Some(origin);
        self.positions.set_local_positions(p);
    }
    pub fn update_local_positions(&mut self, start: usize, p: &[[f32; 3]]) {
        self.positions.update_local_positions(start, p);
    }
    pub fn update_positions(&mut self, start: usize, p: &[[f64; 3]]) {
        self.positions.update_positions(start, p);
    }
    pub fn set_weights(&mut self, w: &[f32]) {
        self.weights.set_f32(w);
    }
    pub fn update_weights(&mut self, start: usize, w: &[f32]) {
        self.weights.update_f32(start, w);
    }

    /// The ramp as sRGB-encoded bytes from no density to
    /// [`max_weight`](Self::max_weight), sampled as a texture of that many
    /// texels with linear filtering samples it: the first colour up to half
    /// a texel in, the last from half a texel before the end, blended on
    /// the encoded values between — as deck.gl's `HeatmapLayer` samples its
    /// colour range.
    pub fn set_ramp_srgb8(&mut self, ramp: &[[u8; 4]]) {
        let n = ramp.len();
        self.ramp = (0..256)
            .map(|k| {
                if n == 0 {
                    return [0, 0, 0, 255];
                }
                let x = ((k as f32 + 0.5) / 256.0 * n as f32 - 0.5).clamp(0.0, (n - 1) as f32);
                let (i, f) = (x.floor() as usize, x.fract());
                let (a, b) = (ramp[i], ramp[(i + 1).min(n - 1)]);
                std::array::from_fn(|c| {
                    (a[c] as f32 + (b[c] as f32 - a[c] as f32) * f).round() as u8
                })
            })
            .collect();
        self.ramp_dirty = true;
    }

    /// The colours from no density to [`max_weight`](Self::max_weight).
    pub fn set_ramp(&mut self, ramp: &ColorRamp) {
        self.ramp = ramp
            .sample(256)
            .into_iter()
            .map(|c| {
                let e = |v: f32| {
                    let v = v.clamp(0.0, 1.0);
                    let s = if v <= 0.003_130_8 {
                        v * 12.92
                    } else {
                        1.055 * v.powf(1.0 / 2.4) - 0.055
                    };
                    (s * 255.0 + 0.5) as u8
                };
                [e(c.r), e(c.g), e(c.b), 255]
            })
            .collect();
        self.ramp_dirty = true;
    }
}

impl Mark for DensityMarks {
    fn kind(&self) -> MarkKind {
        MarkKind::Splat
    }
    fn common(&self) -> &MarkCommon {
        &self.common
    }
    fn common_mut(&mut self) -> &mut MarkCommon {
        &mut self.common
    }
    fn instance_count(&self) -> usize {
        self.positions.len()
    }
    fn kind_extra(&self) -> [f32; 4] {
        self.cover
            .unwrap_or([f32::MIN, f32::MIN, f32::MAX, f32::MAX])
    }
    fn kind_uniforms(&self) -> KindUniforms {
        // style3: what the composite maps to the ramp.
        let (auto, fraction) = match self.auto_max {
            Some(k) => (1.0, k.max(1e-6)),
            None => (0.0, 1.0),
        };
        (
            [
                if self.linear_fade { 1.0 } else { 0.0 },
                if self.mean { 1.0 } else { 0.0 },
                0.0,
                0.0,
            ],
            [self.max_weight, self.threshold, auto, fraction],
            // stroke: the extent, on the ground.
            [
                self.extent[0].max(1.0),
                self.extent[1].max(1.0),
                if self.ground { 1.0 } else { 0.0 },
                0.0,
            ],
        )
    }
    fn prepare(&mut self, ctx: &PrepareContext) {
        let scale = self.field_scale();
        let vp = ctx.view.viewport;
        let [ex, ey] = self.extent.map(|e| e.max(1.0));
        let size = (
            ((vp.0 as f32 * scale * ex).ceil() as u32)
                .clamp(1, ctx.device.limits().max_texture_dimension_2d),
            ((vp.1 as f32 * scale * ey).ceil() as u32)
                .clamp(1, ctx.device.limits().max_texture_dimension_2d),
        );
        let stale = self.gpu.as_ref().is_none_or(|g| g.size != size);
        if stale {
            let field = ctx.device.create_texture(&wgpu::TextureDescriptor {
                label: Some("threers density field"),
                size: wgpu::Extent3d {
                    width: size.0,
                    height: size.1,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: FIELD_FORMAT,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                    | wgpu::TextureUsages::TEXTURE_BINDING,
                view_formats: &[],
            });
            let ramp = match self.gpu.take() {
                Some(g) => g.ramp,
                None => ctx.device.create_texture(&wgpu::TextureDescriptor {
                    label: Some("threers density ramp"),
                    size: wgpu::Extent3d {
                        width: 256,
                        height: 1,
                        depth_or_array_layers: 1,
                    },
                    mip_level_count: 1,
                    sample_count: 1,
                    dimension: wgpu::TextureDimension::D2,
                    // sRGB bytes; sampling decodes them to linear.
                    format: wgpu::TextureFormat::Rgba8UnormSrgb,
                    usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                    view_formats: &[],
                }),
            };
            let field_view = field.create_view(&Default::default());
            let ramp_view = ramp.create_view(&Default::default());
            let mut levels = Vec::new();
            let mut src = field_view.clone();
            for (w, h) in reduce_sizes(size) {
                let tex = ctx.device.create_texture(&wgpu::TextureDescriptor {
                    label: Some("threers density max"),
                    size: wgpu::Extent3d {
                        width: w,
                        height: h,
                        depth_or_array_layers: 1,
                    },
                    mip_level_count: 1,
                    sample_count: 1,
                    dimension: wgpu::TextureDimension::D2,
                    format: FIELD_FORMAT,
                    usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                        | wgpu::TextureUsages::TEXTURE_BINDING,
                    view_formats: &[],
                });
                let target = tex.create_view(&Default::default());
                let bind_group = ctx.device.create_bind_group(&gpu::BindGroupDescriptor {
                    label: Some("threers density reduce bind group"),
                    layout: &ctx.resources.reduce_layout,
                    entries: &[
                        gpu::BindGroupEntry {
                            binding: 0,
                            resource: gpu::BindingResource::TextureView(&src),
                        },
                        gpu::BindGroupEntry {
                            binding: 1,
                            resource: gpu::BindingResource::Sampler(&ctx.resources.nearest_sampler),
                        },
                    ],
                });
                src = target.clone();
                levels.push(ReduceLevel { target, bind_group });
            }
            let bind_group = ctx.device.create_bind_group(&gpu::BindGroupDescriptor {
                label: Some("threers density composite bind group"),
                layout: &ctx.resources.density_layout,
                entries: &[
                    gpu::BindGroupEntry {
                        binding: 0,
                        resource: gpu::BindingResource::TextureView(&field_view),
                    },
                    gpu::BindGroupEntry {
                        binding: 1,
                        resource: gpu::BindingResource::TextureView(&ramp_view),
                    },
                    gpu::BindGroupEntry {
                        binding: 2,
                        resource: gpu::BindingResource::Sampler(&ctx.resources.linear_sampler),
                    },
                    gpu::BindGroupEntry {
                        binding: 3,
                        resource: gpu::BindingResource::TextureView(&src),
                    },
                ],
            });
            self.gpu = Some(DensityGpu {
                size,
                field: field_view,
                ramp,
                bind_group,
                levels,
            });
        }
        if self.ramp_dirty || stale {
            let g = self.gpu.as_ref().unwrap();
            let bytes: Vec<u8> = self.ramp.iter().flatten().copied().collect();
            ctx.queue.write_texture(
                gpu::TexelCopyTextureInfo {
                    texture: &g.ramp,
                    mip_level: 0,
                    origin: wgpu::Origin3d::ZERO,
                    aspect: wgpu::TextureAspect::All,
                },
                &bytes,
                wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(256 * 4),
                    rows_per_image: Some(1),
                },
                wgpu::Extent3d {
                    width: 256,
                    height: 1,
                    depth_or_array_layers: 1,
                },
            );
            self.ramp_dirty = false;
        }
    }
    fn release_gpu(&mut self) {
        self.gpu = None;
        self.ramp_dirty = true;
        super::release_columns(self);
    }
    fn gpu_bytes(&mut self) -> u64 {
        // The field: four half floats a texel.
        let field = self
            .gpu
            .as_ref()
            .map_or(0, |g| g.size.0 as u64 * g.size.1 as u64 * 8);
        super::column_bytes(self) + field
    }
    fn columns(&mut self) -> Vec<&mut Column> {
        vec![&mut self.positions, &mut self.weights]
    }
    fn density(&self) -> Option<(&gpu::TextureView, &gpu::BindGroup)> {
        self.gpu.as_ref().map(|g| (&g.field, &g.bind_group))
    }
    fn density_reduction(&self) -> Option<&[ReduceLevel]> {
        self.auto_max?;
        self.gpu.as_ref().map(|g| g.levels.as_slice())
    }
}