-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmod.rs
More file actions
642 lines (576 loc) · 21.7 KB
/
mod.rs
File metadata and controls
642 lines (576 loc) · 21.7 KB
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
pub mod command;
pub mod material;
pub mod mesh_builder;
pub mod primitive;
pub mod transform;
use bevy::{
camera::visibility::RenderLayers,
ecs::system::SystemParam,
math::{Affine3A, Mat4, Vec4},
prelude::*,
};
use command::{CommandBuffer, DrawCommand};
use material::MaterialKey;
use primitive::{StrokeConfig, TessellationMode, box_mesh, empty_mesh, sphere_mesh};
use transform::TransformStack;
use crate::{
Flush,
geometry::Geometry,
gltf::GltfNodeTransform,
image::Image,
render::{material::UntypedMaterial, primitive::rect},
};
#[derive(Component)]
#[relationship(relationship_target = TransientMeshes)]
pub struct BelongsToGraphics(pub Entity);
#[derive(Component, Default)]
#[relationship_target(relationship = BelongsToGraphics)]
pub struct TransientMeshes(Vec<Entity>);
#[derive(SystemParam)]
pub struct RenderResources<'w, 's> {
commands: Commands<'w, 's>,
meshes: ResMut<'w, Assets<Mesh>>,
materials: ResMut<'w, Assets<StandardMaterial>>,
}
struct BatchState {
current_mesh: Option<Mesh>,
material_key: Option<MaterialKey>,
transform: Affine3A,
draw_index: u32,
render_layers: RenderLayers,
graphics_entity: Entity,
}
impl BatchState {
fn new(graphics_entity: Entity, render_layers: RenderLayers) -> Self {
Self {
current_mesh: None,
material_key: None,
transform: Affine3A::IDENTITY,
draw_index: 0,
render_layers,
graphics_entity,
}
}
}
#[derive(Debug, Component)]
pub struct RenderState {
pub fill_color: Option<Color>,
pub stroke_color: Option<Color>,
pub stroke_weight: f32,
pub stroke_config: StrokeConfig,
pub material_key: MaterialKey,
pub transform: TransformStack,
}
impl RenderState {
pub fn new() -> Self {
Self {
fill_color: Some(Color::WHITE),
stroke_color: Some(Color::BLACK),
stroke_weight: 1.0,
stroke_config: StrokeConfig::default(),
material_key: MaterialKey::Color {
transparent: false,
background_image: None,
},
transform: TransformStack::new(),
}
}
pub fn reset(&mut self) {
self.fill_color = Some(Color::WHITE);
self.stroke_color = Some(Color::BLACK);
self.stroke_weight = 1.0;
self.stroke_config = StrokeConfig::default();
self.material_key = MaterialKey::Color {
transparent: false,
background_image: None,
};
self.transform = TransformStack::new();
}
pub fn fill_is_transparent(&self) -> bool {
self.fill_color.map(|c| c.alpha() < 1.0).unwrap_or(false)
}
pub fn stroke_is_transparent(&self) -> bool {
self.stroke_color.map(|c| c.alpha() < 1.0).unwrap_or(false)
}
}
impl Default for RenderState {
fn default() -> Self {
Self::new()
}
}
pub fn flush_draw_commands(
mut res: RenderResources,
mut graphics: Query<
(
Entity,
&mut CommandBuffer,
&mut RenderState,
&RenderLayers,
&Projection,
&Transform,
),
With<Flush>,
>,
p_images: Query<&Image>,
p_geometries: Query<(&Geometry, Option<&GltfNodeTransform>)>,
p_material_handles: Query<&UntypedMaterial>,
) {
for (graphics_entity, mut cmd_buffer, mut state, render_layers, projection, camera_transform) in
graphics.iter_mut()
{
let clip_from_view = projection.get_clip_from_view();
let view_from_world = camera_transform.to_matrix().inverse();
let world_from_clip = (clip_from_view * view_from_world).inverse();
let draw_commands = std::mem::take(&mut cmd_buffer.commands);
let mut batch = BatchState::new(graphics_entity, render_layers.clone());
for cmd in draw_commands {
match cmd {
DrawCommand::Fill(color) => {
state.fill_color = Some(color);
}
DrawCommand::NoFill => {
state.fill_color = None;
}
DrawCommand::StrokeColor(color) => {
state.stroke_color = Some(color);
}
DrawCommand::NoStroke => {
state.stroke_color = None;
}
DrawCommand::StrokeWeight(weight) => {
state.stroke_weight = weight;
}
DrawCommand::StrokeCap(cap) => {
state.stroke_config.line_cap = cap;
}
DrawCommand::StrokeJoin(join) => {
state.stroke_config.line_join = join;
}
DrawCommand::Roughness(r) => {
state.material_key = match state.material_key {
MaterialKey::Pbr {
albedo,
metallic,
emissive,
..
} => MaterialKey::Pbr {
albedo,
roughness: (r * 255.0) as u8,
metallic,
emissive,
},
_ => MaterialKey::Pbr {
albedo: [255, 255, 255, 255],
roughness: (r * 255.0) as u8,
metallic: 0,
emissive: [0, 0, 0, 0],
},
};
}
DrawCommand::Metallic(m) => {
state.material_key = match state.material_key {
MaterialKey::Pbr {
albedo,
roughness,
emissive,
..
} => MaterialKey::Pbr {
albedo,
roughness,
metallic: (m * 255.0) as u8,
emissive,
},
_ => MaterialKey::Pbr {
albedo: [255, 255, 255, 255],
roughness: 128,
metallic: (m * 255.0) as u8,
emissive: [0, 0, 0, 0],
},
};
}
DrawCommand::Emissive(color) => {
let [r, g, b, a] = color.to_srgba().to_u8_array();
state.material_key = match state.material_key {
MaterialKey::Pbr {
albedo,
roughness,
metallic,
..
} => MaterialKey::Pbr {
albedo,
roughness,
metallic,
emissive: [r, g, b, a],
},
_ => MaterialKey::Pbr {
albedo: [255, 255, 255, 255],
roughness: 128,
metallic: 0,
emissive: [r, g, b, a],
},
};
}
DrawCommand::Unlit => {
state.material_key = MaterialKey::Color {
transparent: state.fill_is_transparent(),
background_image: None,
};
}
DrawCommand::Rect { x, y, w, h, radii } => {
let stroke_config = state.stroke_config;
add_fill(&mut res, &mut batch, &state, |mesh, color| {
rect(
mesh,
x,
y,
w,
h,
radii,
color,
TessellationMode::Fill,
&stroke_config,
)
});
add_stroke(&mut res, &mut batch, &state, |mesh, color, weight| {
rect(
mesh,
x,
y,
w,
h,
radii,
color,
TessellationMode::Stroke(weight),
&stroke_config,
)
});
}
DrawCommand::BackgroundColor(color) => {
flush_batch(&mut res, &mut batch);
let mesh = create_ndc_background_quad(world_from_clip, color, false);
let mesh_handle = res.meshes.add(mesh);
let material_key = MaterialKey::Color {
transparent: color.alpha() < 1.0,
background_image: None,
};
let material_handle = material_key.to_material(&mut res.materials);
res.commands.spawn((
Mesh3d(mesh_handle),
UntypedMaterial(material_handle),
BelongsToGraphics(batch.graphics_entity),
Transform::IDENTITY,
batch.render_layers.clone(),
));
batch.draw_index += 1;
}
DrawCommand::BackgroundImage(entity) => {
let Some(p_image) = p_images.get(entity).ok() else {
warn!("Could not find PImage for entity {:?}", entity);
continue;
};
flush_batch(&mut res, &mut batch);
let mesh = create_ndc_background_quad(world_from_clip, Color::WHITE, true);
let mesh_handle = res.meshes.add(mesh);
let material_key = MaterialKey::Color {
transparent: false,
background_image: Some(p_image.handle.clone()),
};
let material_handle = material_key.to_material(&mut res.materials);
res.commands.spawn((
Mesh3d(mesh_handle),
UntypedMaterial(material_handle),
BelongsToGraphics(batch.graphics_entity),
Transform::IDENTITY,
batch.render_layers.clone(),
));
batch.draw_index += 1;
}
DrawCommand::PushMatrix => state.transform.push(),
DrawCommand::PopMatrix => state.transform.pop(),
DrawCommand::ResetMatrix => state.transform.reset(),
DrawCommand::Translate { x, y } => state.transform.translate(x, y),
DrawCommand::Rotate { angle } => state.transform.rotate(angle),
DrawCommand::Scale { x, y } => state.transform.scale(x, y),
DrawCommand::ShearX { angle } => state.transform.shear_x(angle),
DrawCommand::ShearY { angle } => state.transform.shear_y(angle),
DrawCommand::Geometry(entity) => {
let Some((geometry, node_transform)) = p_geometries.get(entity).ok() else {
warn!("Could not find Geometry for entity {:?}", entity);
continue;
};
let material_key = material_key_with_fill(&state);
let material_handle = match &material_key {
MaterialKey::Custom(mat_entity) => {
let Some(handle) = p_material_handles.get(*mat_entity).ok() else {
warn!("Could not find material for entity {:?}", mat_entity);
continue;
};
handle.0.clone()
}
_ => material_key.to_material(&mut res.materials),
};
flush_batch(&mut res, &mut batch);
let z_offset = -(batch.draw_index as f32 * 0.001);
let mut transform = state.transform.to_bevy_transform();
// if the "source" geometry was parented in a gltf scene, we need to make sure that
// we apply the parent transform here to ensure the correct final transform
// TODO: think about how hierarchies should work, especially for retained
if let Some(nt) = node_transform {
transform =
Transform::from_matrix(transform.to_matrix() * nt.0.to_matrix());
}
transform.translation.z += z_offset;
res.commands.spawn((
Mesh3d(geometry.handle.clone()),
UntypedMaterial(material_handle),
BelongsToGraphics(batch.graphics_entity),
transform,
batch.render_layers.clone(),
));
batch.draw_index += 1;
}
DrawCommand::Material(entity) => {
state.material_key = MaterialKey::Custom(entity);
}
DrawCommand::Box {
width,
height,
depth,
} => {
add_shape3d(&mut res, &mut batch, &state, box_mesh(width, height, depth));
}
DrawCommand::Sphere {
radius,
sectors,
stacks,
} => {
add_shape3d(
&mut res,
&mut batch,
&state,
sphere_mesh(radius, sectors, stacks),
);
}
}
}
flush_batch(&mut res, &mut batch);
}
}
pub fn activate_cameras(mut cameras: Query<(&mut Camera, Option<&Flush>)>) {
for (mut camera, flush) in cameras.iter_mut() {
let active = flush.is_some();
camera.is_active = active;
}
}
pub fn clear_transient_meshes(
mut commands: Commands,
surfaces: Query<&TransientMeshes, With<Flush>>,
) {
for transient_meshes in surfaces.iter() {
for &mesh_entity in transient_meshes.0.iter() {
commands.entity(mesh_entity).despawn();
}
}
}
fn spawn_mesh(res: &mut RenderResources, batch: &mut BatchState, mesh: Mesh, z_offset: f32) {
let Some(key) = &batch.material_key else {
return;
};
let mesh_handle = res.meshes.add(mesh);
let (scale, rotation, translation) = batch.transform.to_scale_rotation_translation();
let transform = Transform {
translation: translation + Vec3::new(0.0, 0.0, z_offset),
rotation,
scale,
};
let material_handle = key.to_material(&mut res.materials);
res.commands.spawn((
Mesh3d(mesh_handle),
UntypedMaterial(material_handle),
BelongsToGraphics(batch.graphics_entity),
transform,
batch.render_layers.clone(),
));
}
fn needs_batch(batch: &BatchState, state: &RenderState, material_key: &MaterialKey) -> bool {
let material_changed = batch.material_key.as_ref() != Some(material_key);
let transform_changed = batch.transform != state.transform.current();
material_changed || transform_changed
}
fn start_batch(
res: &mut RenderResources,
batch: &mut BatchState,
state: &RenderState,
material_key: MaterialKey,
) {
flush_batch(res, batch);
batch.material_key = Some(material_key);
batch.transform = state.transform.current();
batch.current_mesh = Some(empty_mesh());
}
fn material_key_with_color(key: &MaterialKey, color: Color) -> MaterialKey {
match key {
MaterialKey::Color {
background_image, ..
} => MaterialKey::Color {
transparent: color.alpha() < 1.0,
background_image: background_image.clone(),
},
MaterialKey::Pbr {
roughness,
metallic,
emissive,
..
} => {
let [r, g, b, a] = color.to_srgba().to_u8_array();
MaterialKey::Pbr {
albedo: [r, g, b, a],
roughness: *roughness,
metallic: *metallic,
emissive: *emissive,
}
}
MaterialKey::Custom(e) => MaterialKey::Custom(*e),
}
}
fn material_key_with_fill(state: &RenderState) -> MaterialKey {
let color = state.fill_color.unwrap_or(Color::WHITE);
material_key_with_color(&state.material_key, color)
}
fn add_fill(
res: &mut RenderResources,
batch: &mut BatchState,
state: &RenderState,
tessellate: impl FnOnce(&mut Mesh, Color),
) {
let Some(color) = state.fill_color else {
return;
};
let material_key = material_key_with_color(&state.material_key, color);
if needs_batch(batch, state, &material_key) {
start_batch(res, batch, state, material_key);
}
if let Some(ref mut mesh) = batch.current_mesh {
tessellate(mesh, color);
}
}
fn add_stroke(
res: &mut RenderResources,
batch: &mut BatchState,
state: &RenderState,
tessellate: impl FnOnce(&mut Mesh, Color, f32),
) {
let Some(color) = state.stroke_color else {
return;
};
let stroke_weight = state.stroke_weight;
let material_key = material_key_with_color(&state.material_key, color);
if needs_batch(batch, state, &material_key) {
start_batch(res, batch, state, material_key);
}
if let Some(ref mut mesh) = batch.current_mesh {
tessellate(mesh, color, stroke_weight);
}
}
fn flush_batch(res: &mut RenderResources, batch: &mut BatchState) {
if let Some(mesh) = batch.current_mesh.take() {
let z_offset = -(batch.draw_index as f32 * 0.001);
spawn_mesh(res, batch, mesh, z_offset);
batch.draw_index += 1;
}
batch.material_key = None;
}
fn add_shape3d(res: &mut RenderResources, batch: &mut BatchState, state: &RenderState, mesh: Mesh) {
use bevy::pbr::wireframe::{Wireframe, WireframeColor, WireframeLineWidth, WireframeTopology};
flush_batch(res, batch);
let mesh_handle = res.meshes.add(mesh);
let fill_color = state.fill_color.unwrap_or(Color::WHITE);
let material_handle = match &state.material_key {
// TODO: in 2d, we use vertex colors. `to_material` becomes complicated if we also encode
// a base color in the material, so for simplicity we just create a new material here
// that is unlit and uses the fill color as the base color
MaterialKey::Color { transparent, .. } => {
let mat = StandardMaterial {
base_color: fill_color,
unlit: true,
cull_mode: None,
alpha_mode: if *transparent {
AlphaMode::Blend
} else {
AlphaMode::Opaque
},
..default()
};
res.materials.add(mat).untyped()
}
_ => {
let key = material_key_with_fill(state);
key.to_material(&mut res.materials)
}
};
let z_offset = -(batch.draw_index as f32 * 0.001);
let mut transform = state.transform.to_bevy_transform();
transform.translation.z += z_offset;
let mut entity = res.commands.spawn((
Mesh3d(mesh_handle),
UntypedMaterial(material_handle),
BelongsToGraphics(batch.graphics_entity),
transform,
batch.render_layers.clone(),
));
if let Some(stroke_color) = state.stroke_color {
entity.insert((
Wireframe,
WireframeColor {
color: stroke_color,
},
WireframeLineWidth {
width: state.stroke_weight,
},
WireframeTopology::Quads,
));
}
batch.draw_index += 1;
}
/// Creates a fullscreen quad by transforming NDC fullscreen by inverse of the clip-from-world matrix
/// so that when the vertex shader applies clip_from_world, the vertices end up correctly back in
/// NDC space.
fn create_ndc_background_quad(world_from_clip: Mat4, color: Color, with_uvs: bool) -> Mesh {
use bevy::asset::RenderAssetUsages;
use bevy::mesh::{Indices, PrimitiveTopology};
let ndc_z = 0.001; // near far plane (bevy uses reverse-z)
let ndc_corners = [
Vec4::new(-1.0, -1.0, ndc_z, 1.0), // bl
Vec4::new(1.0, -1.0, ndc_z, 1.0), // br
Vec4::new(1.0, 1.0, ndc_z, 1.0), // tr
Vec4::new(-1.0, 1.0, ndc_z, 1.0), // tl
];
let world_positions: Vec<[f32; 3]> = ndc_corners
.iter()
.map(|ndc| {
let world = world_from_clip * *ndc;
[world.x / world.w, world.y / world.w, world.z / world.w]
})
.collect();
let uvs: Vec<[f32; 2]> = vec![
[0.0, 1.0], // bl
[1.0, 1.0], // br
[1.0, 0.0], // tr
[0.0, 0.0], // tl
];
let color_array: [f32; 4] = color.to_linear().to_f32_array();
let colors: Vec<[f32; 4]> = vec![color_array; 4];
// two tris
let indices: Vec<u32> = vec![0, 1, 2, 0, 2, 3];
let mut mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
);
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, world_positions);
mesh.insert_attribute(Mesh::ATTRIBUTE_COLOR, colors);
if with_uvs {
mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
}
mesh.insert_indices(Indices::U32(indices));
mesh
}