reve/src/renderer.rs 18.6 KiB raw
1
mod mesh;
2
mod scene;
3
mod shaders;
4
5
use std::ops::Not;
6
7
use ombre::derive::Packed;
8
use ombre::prelude::*;
9
10
pub use mesh::*;
11
pub use scene::*;
12
13
use crate::camera::Camera;
14
15
#[derive(Debug)]
16
pub enum Error<T> {
17
    InvalidVertexId(u32),
18
    Backend(T),
19
}
20
21
impl<T> From<T> for Error<T> {
22
    fn from(e: T) -> Self {
23
        Self::Backend(e)
24
    }
25
}
26
27
impl<T> std::fmt::Display for Error<T>
28
where
29
    T: std::fmt::Display,
30
{
31
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32
        match self {
33
            Self::InvalidVertexId(id) => write!(f, "invalid vertex id {id}"),
34
            Self::Backend(e) => e.fmt(f),
35
        }
36
    }
37
}
38
39
struct Pipeline<U> {
40
    id: gfx::PipelineId,
41
    uniforms: U,
42
}
43
44
impl<U> Pipeline<U> {
45
    fn new(id: gfx::PipelineId, uniforms: U) -> Self {
46
        Self { id, uniforms }
47
    }
48
}
49
50
struct Pipelines {
51
    offscreen: Pipeline<shaders::default::Uniforms>,
52
    display: Pipeline<shaders::display::Uniforms>,
53
    gizmo: Pipeline<shaders::constant::Uniforms>,
54
}
55
56
struct Passes {
57
    offscreen: OffscreenPass,
58
    default: DefaultPass,
59
}
60
61
struct OffscreenPass {
62
    id: PassId,
63
}
64
65
struct DefaultPass {
66
    bindings: gfx::Bindings<0, 1>,
67
}
68
69
#[derive(Debug, Copy, Clone)]
70
pub enum Component {
71
    Point(i32),
72
    Polygon(i32),
73
    Edge(i32),
74
}
75
76
impl From<Component> for i32 {
77
    fn from(value: Component) -> Self {
78
        match value {
79
            Component::Point(id) => id,
80
            Component::Polygon(id) => id,
81
            Component::Edge(id) => id,
82
        }
83
    }
84
}
85
86
struct ActiveState {
87
    pub node: NodeId,
88
    pub component: Option<Component>,
89
}
90
91
pub struct Renderer<T> {
92
    pub scene: scene::Graph,
93
94
    pipelines: Pipelines,
95
    passes: Passes,
96
    viewport: Size<f64>,
97
    active: Option<ActiveState>,
98
    backend: T,
99
}
100
101
impl<T: gfx::RenderBackend> Renderer<T> {
102
    pub fn init(viewport: platform::LogicalSize, mut backend: T) -> Result<Self, T::Error> {
103
        let viewport = Size::new(viewport.width, viewport.height);
104
        let passes = {
105
            let default = backend.texture(gfx::Texture {
106
                data: gfx::Empty,
107
                target: TextureKind::default(),
108
                size: viewport.map(|n| n.floor() as u32),
109
                access: gfx::TextureAccess::RenderTarget,
110
                wrap: gfx::TextureWrap::Clamp,
111
                format: gfx::TextureFormat::Rgba8,
112
                min_filter: FilterMode::Nearest,
113
                mag_filter: FilterMode::Nearest,
114
            })?;
115
            let ids = backend.texture(gfx::Texture {
116
                data: gfx::Empty,
117
                target: TextureKind::default(),
118
                size: viewport.map(|n| n.floor() as u32),
119
                access: gfx::TextureAccess::RenderTarget,
120
                wrap: gfx::TextureWrap::Clamp,
121
                format: gfx::TextureFormat::Signed,
122
                min_filter: FilterMode::Nearest,
123
                mag_filter: FilterMode::Nearest,
124
            })?;
125
            let depth = backend.texture(gfx::Texture {
126
                data: gfx::Empty,
127
                access: gfx::TextureAccess::RenderTarget,
128
                size: viewport.map(|n| n.floor() as u32),
129
                format: gfx::TextureFormat::Depth,
130
                ..Default::default()
131
            })?;
132
            let offscreen = backend.pass(gfx::PassDescriptor {
133
                color_attachments: &[default, ids],
134
                depth_attachment: Some(depth),
135
            })?;
136
            let bindings = gfx::Bindings {
137
                vertex: [],
138
                index: None,
139
                textures: [default],
140
            };
141
142
            Passes {
143
                offscreen: OffscreenPass { id: offscreen },
144
                default: DefaultPass { bindings },
145
            }
146
        };
147
148
        // Default pipeline for shading models.
149
        let default_shader =
150
            backend.shader(shaders::default::source(), shaders::default::description())?;
151
        let default_pipeline = backend.pipeline(
152
            default_shader,
153
            gfx::PipelineDescriptor {
154
                layout: &[
155
                    gfx::BufferLayout {
156
                        attrs: &shaders::default::attributes()[0..=5],
157
                        stride: Some(mesh::Vertex::stride()),
158
                        ..gfx::BufferLayout::default()
159
                    },
160
                    gfx::BufferLayout {
161
                        attrs: &shaders::default::attributes()[6..=6],
162
                        stride: None,
163
                        ..gfx::BufferLayout::default()
164
                    },
165
                ],
166
                depth: Some(gfx::DepthState {
167
                    compare: gfx::Comparison::LessOrEqual,
168
                    offset: None,
169
                }),
170
                culling: gfx::CullMode::Nothing,
171
                ..gfx::PipelineDescriptor::default()
172
            },
173
        )?;
174
175
        // Pipeline for rendering gizmos, like for manipulating objects.
176
        let gizmo_shader = backend.shader(
177
            shaders::constant::source(),
178
            shaders::constant::description(),
179
        )?;
180
        let gizmo_pipeline = backend.pipeline(
181
            gizmo_shader,
182
            gfx::PipelineDescriptor {
183
                layout: &[gfx::BufferLayout {
184
                    attrs: &shaders::constant::attributes(),
185
                    stride: Some(mesh::Vertex::stride()),
186
                    ..gfx::BufferLayout::default()
187
                }],
188
                depth: Some(gfx::DepthState {
189
                    compare: gfx::Comparison::LessOrEqual,
190
                    offset: None,
191
                }),
192
                culling: gfx::CullMode::Nothing,
193
                ..gfx::PipelineDescriptor::default()
194
            },
195
        )?;
196
197
        // Pipeline for rendering backbuffer to the screen.
198
        let display_shader =
199
            backend.shader(shaders::display::source(), shaders::display::description())?;
200
        let display_pipeline = backend.pipeline(
201
            display_shader,
202
            gfx::PipelineDescriptor {
203
                layout: &[],
204
                depth: None,
205
                culling: gfx::CullMode::Nothing,
206
                ..gfx::PipelineDescriptor::default()
207
            },
208
        )?;
209
210
        Ok(Self {
211
            pipelines: Pipelines {
212
                offscreen: Pipeline::new(
213
                    default_pipeline,
214
                    shaders::default::Uniforms {
215
                        model: Transform3D::default(),
216
                        view: Transform3D::default(),
217
                        proj: Transform3D::default(),
218
                        light: Vector3D::new(5., 3., 2.),
219
                        window_size: viewport.map(|n| n.floor() as f32),
220
                        enable_tomemap: 0,
221
                        render_mode: 1,
222
                        object_id: 0,
223
                        interaction_mode: InteractionMode::default().into(),
224
                        vertex_hovered: -1,
225
                    },
226
                ),
227
                display: Pipeline::new(display_pipeline, ()),
228
                gizmo: Pipeline::new(
229
                    gizmo_pipeline,
230
                    shaders::constant::Uniforms {
231
                        model: Transform3D::default(),
232
                        view: Transform3D::default(),
233
                        proj: Transform3D::default(),
234
                    },
235
                ),
236
            },
237
            passes,
238
            active: None,
239
            scene: scene::Graph::default(),
240
            viewport,
241
            backend,
242
        })
243
    }
244
245
    pub fn frame(&mut self, camera: &Camera) -> Result<(), Error<T::Error>> {
246
        let mut frame = self.backend.frame();
247
        let proj = camera.projection(self.viewport.map(|n| n.floor() as f32));
248
        let view = camera.view();
249
        let model = Transform3D::rotation(30., Vector3D::new(0., 1., 0.))
250
            * Transform3D::<f32>::rotation(30., Vector3D::new(1., 0., 0.));
251
252
        //
253
        // Offscreen pass.
254
        //
255
        self.pipelines.offscreen.uniforms.model = model;
256
        self.pipelines.offscreen.uniforms.view = view;
257
        self.pipelines.offscreen.uniforms.proj = proj;
258
        self.pipelines.offscreen.uniforms.window_size = self.viewport.map(|n| n.floor() as f32);
259
260
        frame.begin_pass(self.passes.offscreen.id, gfx::PassAction::default());
261
        frame.apply_pipeline(&self.pipelines.offscreen.id)?;
262
263
        for node in self.scene.iter() {
264
            if let scene::Object::Mesh {
265
                bindings,
266
                elements,
267
                style,
268
                mode,
269
                ..
270
            } = &node.object
271
            {
272
                self.pipelines.offscreen.uniforms.object_id = node.id.into();
273
                self.pipelines.offscreen.uniforms.render_mode = style.into();
274
                self.pipelines.offscreen.uniforms.interaction_mode = (*mode).into();
275
276
                if let Some(hover) = &self.active {
277
                    if hover.node == node.id {
278
                        if let Some(c) = hover.component {
279
                            self.pipelines.offscreen.uniforms.vertex_hovered = c.into();
280
                        } else {
281
                            self.pipelines.offscreen.uniforms.vertex_hovered = -1;
282
                        }
283
                    }
284
                }
285
286
                frame.apply_uniforms(&self.pipelines.offscreen.uniforms)?;
287
                frame.apply_bindings(bindings)?;
288
                frame.draw(0, *elements, 1)?;
289
            }
290
        }
291
        frame.end_pass();
292
293
        //
294
        // Default pass.
295
        //
296
        frame.begin_default_pass(gfx::PassAction::default(), self.viewport.map(|n| n as u32));
297
        frame.apply_pipeline(&self.pipelines.display.id)?;
298
        frame.apply_uniforms(&self.pipelines.display.uniforms)?;
299
        frame.apply_bindings(&self.passes.default.bindings)?;
300
        frame.draw(0, 6, 1)?;
301
302
        //
303
        // Gizmo pipeline
304
        //
305
        self.pipelines.gizmo.uniforms.model = model;
306
        self.pipelines.gizmo.uniforms.view = view;
307
        self.pipelines.gizmo.uniforms.proj = proj;
308
309
        frame.apply_pipeline(&self.pipelines.gizmo.id)?;
310
        frame.apply_uniforms(&self.pipelines.gizmo.uniforms)?;
311
312
        for node in self.scene.iter() {
313
            if let scene::Object::Null = &node.object {
314
                // TODO
315
            }
316
        }
317
        frame.end_pass();
318
        frame.commit();
319
320
        Ok(())
321
    }
322
323
    pub fn active(&mut self, node: NodeId, component: Option<Component>) {
324
        self.active = Some(ActiveState { node, component });
325
    }
326
327
    #[allow(dead_code)]
328
    pub fn inactive(&mut self) {
329
        self.active = None;
330
    }
331
332
    pub fn model(&mut self, builder: ModelBuilder) -> Result<scene::NodeId, Error<T::Error>> {
333
        let bindings = {
334
            let vbo = self.backend.buffer(
335
                gfx::BufferKind::Vertex,
336
                gfx::BufferUsage::Immutable,
337
                gfx::BufferSource::slice(&builder.mesh.vertices),
338
            )?;
339
            let svbo = self.backend.buffer(
340
                gfx::BufferKind::Vertex,
341
                gfx::BufferUsage::Dynamic,
342
                gfx::BufferSource::<Flag>::zero(builder.mesh.vertices.len()),
343
            )?;
344
            let ibo = builder
345
                .mesh
346
                .indices
347
                .as_ref()
348
                .map(|i| {
349
                    self.backend.buffer(
350
                        gfx::BufferKind::Index,
351
                        gfx::BufferUsage::Immutable,
352
                        gfx::BufferSource::slice(i),
353
                    )
354
                })
355
                .transpose()?;
356
            let blank = self.backend.texture(gfx::Texture {
357
                data: [Rgba8::WHITE].as_slice(),
358
                size: Size::new(1, 1),
359
                wrap: gfx::TextureWrap::Repeat,
360
                ..gfx::Texture::default()
361
            })?;
362
363
            gfx::Bindings {
364
                vertex: [vbo, svbo],
365
                index: ibo,
366
                textures: [blank, blank],
367
            }
368
        };
369
370
        let node = Node::new(scene::Object::Mesh {
371
            bindings,
372
            selection: vec![Flag::NO; builder.mesh.vertices.len()],
373
            elements: builder.mesh.elements(),
374
            vertices: builder.mesh.vertices,
375
            style: RenderStyle::default(),
376
            mode: InteractionMode::default(),
377
        });
378
        let id = node.id;
379
        let parent = self.scene.root().id;
380
381
        self.scene.insert(node, parent);
382
383
        Ok(id)
384
    }
385
386
    #[allow(dead_code)]
387
    pub fn color_at(
388
        &mut self,
389
        point: Point2D<f32, Screen>,
390
    ) -> Result<Option<Rgba<f32>>, Error<T::Error>> {
391
        if let Some(color) = self.at::<Rgba<f32>>(point, 0)? {
392
            return Ok(Some(color));
393
        }
394
        Ok(None)
395
    }
396
397
    pub fn vertex_at(
398
        &mut self,
399
        point: Point2D<f32, Screen>,
400
    ) -> Result<Option<u32>, Error<T::Error>> {
401
        if let Some(id) = self.at::<u32>(point, 1)? {
402
            return Ok(id.checked_sub(1));
403
        }
404
        Ok(None)
405
    }
406
407
    pub fn polygon_at(
408
        &mut self,
409
        point: Point2D<f32, Screen>,
410
    ) -> Result<Option<u32>, Error<T::Error>> {
411
        if let Some(id) = self.at::<u32>(point, 1)? {
412
            if id.is_zero() {
413
                return Ok(None);
414
            }
415
            return Ok(Some(id));
416
        }
417
        Ok(None)
418
    }
419
420
    pub fn node_at(
421
        &mut self,
422
        point: Point2D<f32, Screen>,
423
    ) -> Result<Option<NodeId>, Error<T::Error>> {
424
        if let Some(pixel) = self.at::<u32>(point, 1)? {
425
            return Ok(NodeId::new(pixel));
426
        }
427
        Ok(None)
428
    }
429
430
    pub fn window_resized(&mut self, size: platform::LogicalSize) -> Result<(), Error<T::Error>> {
431
        self.backend.window_resized(size);
432
        self.backend.pass_resize_attachments(
433
            self.passes.offscreen.id,
434
            Size::new(size.width as u32, size.height as u32),
435
        )?;
436
        self.viewport = Size::new(size.width, size.height);
437
438
        Ok(())
439
    }
440
441
    pub fn at<S: Default + Clone + Copy>(
442
        &mut self,
443
        point: Point2D<f32, Screen>,
444
        index: usize,
445
    ) -> Result<Option<S>, Error<T::Error>> {
446
        // TODO: Use `MaybeUninit` (measure)?
447
        let mut output = vec![S::default(); self.viewport.area() as usize];
448
        self.backend
449
            .pass_read_color_attachment(self.passes.offscreen.id, index, &mut output)?;
450
451
        // TODO: Use conversion functions instead.
452
        let y = self.viewport.h as usize - point.y as usize;
453
        let pixels =
454
            pixels::Pixels::new(&output, self.viewport.w as usize, self.viewport.h as usize);
455
        let pixel = pixels.get(point.x.floor() as usize, self.viewport.h as usize - y);
456
457
        if let Some(pixel) = pixel {
458
            return Ok(Some(*pixel));
459
        }
460
        Ok(None)
461
    }
462
463
    pub fn select_vertices(&mut self, ixs: &[u32], node: NodeId) -> Result<(), Error<T::Error>> {
464
        if let Some(node) = self.scene.get_mut(&node) {
465
            match &mut node.object {
466
                Object::Mesh {
467
                    bindings,
468
                    selection,
469
                    vertices,
470
                    ..
471
                } => {
472
                    for ix in ixs.iter() {
473
                        // Find all vertices at this position, and select them.
474
                        let pos = vertices
475
                            .get(*ix as usize)
476
                            .ok_or(Error::InvalidVertexId(*ix))?
477
                            .position;
478
                        for (i, v) in vertices.iter().enumerate() {
479
                            if v.position == pos {
480
                                selection[i] = Flag::YES;
481
                            }
482
                        }
483
                    }
484
                    // Update the selection buffer for this mesh.
485
                    self.backend
486
                        .buffer_update(bindings.vertex[1], BufferKind::Vertex, 0, selection)
487
                        .map_err(Error::Backend)?;
488
                }
489
                _ => {}
490
            }
491
        }
492
        Ok(())
493
    }
494
495
    pub fn select_polygons(&mut self, ids: &[u32], node: NodeId) -> Result<(), Error<T::Error>> {
496
        if let Some(node) = self.scene.get_mut(&node) {
497
            match &mut node.object {
498
                Object::Mesh {
499
                    bindings,
500
                    selection,
501
                    vertices,
502
                    ..
503
                } => {
504
                    for id in ids.iter() {
505
                        for (i, v) in vertices.iter().enumerate() {
506
                            if v.polygon == *id {
507
                                selection[i] = Flag::YES;
508
                            }
509
                        }
510
                    }
511
                    // Update the selection buffer for this mesh.
512
                    self.backend
513
                        .buffer_update(bindings.vertex[1], BufferKind::Vertex, 0, selection)
514
                        .map_err(Error::Backend)?;
515
                }
516
                _ => {}
517
            }
518
        }
519
        Ok(())
520
    }
521
}
522
523
pub struct ModelBuilder {
524
    mesh: Mesh,
525
}
526
527
impl ModelBuilder {
528
    pub fn cube(size: f32) -> Self {
529
        Self {
530
            mesh: Mesh::<u16>::cube(size),
531
        }
532
    }
533
534
    pub fn sphere() -> Self {
535
        Self {
536
            mesh: Mesh::<u16>::sphere(Rgba8::new(130, 47, 61, 255), 1.0, 12, 12),
537
        }
538
    }
539
}
540
541
/// On/off flag. Essentially a boolean in disguise, since GLSL shaders
542
/// do not support booleans as input.
543
#[derive(Debug, Copy, Clone, PartialEq, Default, Packed)]
544
#[repr(C)]
545
pub struct Flag(f32);
546
547
impl Flag {
548
    pub const YES: Flag = Flag(1.0);
549
    pub const NO: Flag = Flag(0.0);
550
}
551
552
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
553
#[repr(u8)]
554
pub enum InteractionMode {
555
    #[default]
556
    Objects = 0,
557
    Edges = 1,
558
    Points = 2,
559
    Polygons = 3,
560
}
561
562
impl InteractionMode {
563
    pub fn toggle(&mut self, mode: Self) {
564
        if *self == mode {
565
            *self = Self::Objects;
566
        } else {
567
            *self = mode;
568
        }
569
    }
570
}
571
572
impl From<InteractionMode> for u32 {
573
    fn from(rm: InteractionMode) -> Self {
574
        rm as u32
575
    }
576
}
577
578
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
579
pub struct RenderStyle(u32);
580
581
impl RenderStyle {
582
    pub const DIFFUSE: Self = Self(0b00000001);
583
    pub const FLAT_SHADED: Self = Self(0b00000010);
584
    pub const SPECULAR: Self = Self(0b00000100);
585
    pub const TEXTURED: Self = Self(0b00001000);
586
    pub const WIREFRAME: Self = Self(0b00010000);
587
588
    pub fn remove(&mut self, other: Self) {
589
        self.0 &= other.0.not();
590
    }
591
}
592
593
impl std::ops::BitOr for RenderStyle {
594
    type Output = Self;
595
596
    fn bitor(self, rhs: Self) -> Self::Output {
597
        Self(self.0 | rhs.0)
598
    }
599
}
600
601
impl std::ops::BitOrAssign for RenderStyle {
602
    fn bitor_assign(&mut self, rhs: Self) {
603
        self.0 |= rhs.0
604
    }
605
}
606
607
impl From<&RenderStyle> for u32 {
608
    fn from(rs: &RenderStyle) -> Self {
609
        rs.0
610
    }
611
}
612
613
impl Default for RenderStyle {
614
    fn default() -> Self {
615
        Self::DIFFUSE | Self::SPECULAR
616
    }
617
}