-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathlinked_mesh.rs
More file actions
4826 lines (4308 loc) · 151 KB
/
Copy pathlinked_mesh.rs
File metadata and controls
4826 lines (4308 loc) · 151 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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::borrow::Cow;
use std::{f32::consts::PI, fmt::Debug, hash::Hash, marker::PhantomData, num::NonZeroU32};
use arrayvec::ArrayVec;
use bitvec::{bitarr, slice::BitSlice};
use fxhash::{FxBuildHasher, FxHashMap, FxHashSet};
use nalgebra::{Matrix3, Matrix4, Vector3};
use slotmap::{new_key_type, Key, SecondaryMap, SlotMap};
use smallvec::SmallVec;
use crate::attrs;
use crate::bvh::{Aabb, TriBvh};
#[cfg(not(target_arch = "wasm32"))]
use crate::models::{
stanford_bunny::{STANFORD_BUNNY_INDICES, STANFORD_BUNNY_VERTICES},
utah_teapot::{UTAH_TEAPOT_INDICES, UTAH_TEAPOT_VERTICES},
};
use crate::{
slotmap_utils::{
build_slotmap_from_iter, build_slotmap_from_iter_with_key, ekey_ix, fkey_ix,
slotmap_insert_dense, slotmap_insert_dense_with_key, vkey, vkey_ix, vkey_ix_mut, vkey_version,
LocalKeyData, LocalSlotMap,
},
OwnedIndexedMesh, OwnedIndexedMeshBuilder, OwnedMesh, Triangle,
};
pub type Vec3 = Vector3<f32>;
pub type Mat4 = Matrix4<f32>;
new_key_type! {
pub struct VertexKey;
pub struct FaceKey;
pub struct EdgeKey;
}
#[derive(Clone, Debug, Default)]
pub struct Vertex {
pub position: Vec3,
pub edges: SmallVec<[EdgeKey; 9]>,
}
impl Vertex {
pub fn new(position: Vec3) -> Self {
Vertex {
position,
edges: SmallVec::new(),
}
}
}
#[derive(Clone, Debug)]
pub struct Face<T> {
/// Counter-clockwise winding
pub vertices: [VertexKey; 3],
/// Unordered
pub edges: [EdgeKey; 3],
pub data: T,
}
static mut GRAPHVIZ_PRINT_INNER: fn(&str) -> () = |s| {
println!("{}", s);
};
fn graphviz_print(s: &str) {
unsafe {
GRAPHVIZ_PRINT_INNER(s);
}
}
pub fn set_graphviz_print(f: fn(&str) -> ()) {
unsafe {
GRAPHVIZ_PRINT_INNER = f;
}
}
static mut DEBUG_PRINT_INNER: fn(&str) -> () = |s| {
println!("{s}");
};
#[allow(dead_code)]
fn debug_print(s: &str) {
unsafe {
DEBUG_PRINT_INNER(s);
}
}
pub fn set_debug_print(f: fn(&str) -> ()) {
unsafe {
DEBUG_PRINT_INNER = f;
}
}
// /// Same as Vec::retain but it doesn't preserve order of elements and can possibly work a bit
// faster /// if only removing a few elements.
// fn swap_retain<T>(vec: &mut Vec<T>, mut f: impl FnMut(&mut T) -> bool) {
// let mut i = 0;
// while i < vec.len() {
// if !f(&mut vec[i]) {
// vec.swap_remove(i);
// } else {
// i += 1;
// }
// }
// }
/// Same as SmallVec::retain but it doesn't preserve order of elements and can possibly work a bit
/// faster if only removing a few elements.
fn swap_retain_sv<T: smallvec::Array>(
vec: &mut SmallVec<T>,
mut f: impl FnMut(&mut <T as smallvec::Array>::Item) -> bool,
) {
let mut i = 0;
while i < vec.len() {
if !f(&mut vec[i]) {
vec.swap_remove(i);
} else {
i += 1;
}
}
}
impl<T> Face<T> {
pub fn vertex_positions(&self, verts: &SlotMap<VertexKey, Vertex>) -> [Vec3; 3] {
[
verts[self.vertices[0]].position,
verts[self.vertices[1]].position,
verts[self.vertices[2]].position,
]
}
pub fn iter_vtx_positions<'a>(
&'a self,
verts: &'a SlotMap<VertexKey, Vertex>,
) -> impl Iterator<Item = &'a Vec3> + 'a {
self
.vertices
.iter()
.map(move |&vtx_key| &verts[vtx_key].position)
}
pub fn normal(&self, verts: &SlotMap<VertexKey, Vertex>) -> Vector3<f32> {
let [a, b, c] = self.vertex_positions(verts);
(b - a).cross(&(c - a)).normalize()
}
pub fn area(&self, verts: &SlotMap<VertexKey, Vertex>) -> f32 {
let [a, b, c] = self.vertex_positions(verts);
0.5 * (b - a).cross(&(c - a)).magnitude()
}
pub fn center(&self, verts: &SlotMap<VertexKey, Vertex>) -> Vector3<f32> {
let [a, b, c] = self.vertex_positions(verts);
(a + b + c) / 3.
}
pub fn compute_angle_at_vertex(&self, vtx_ix: usize, verts: &SlotMap<VertexKey, Vertex>) -> f32 {
let (target_vtx_key, b, c) = match vtx_ix {
0 => (self.vertices[0], self.vertices[1], self.vertices[2]),
1 => (self.vertices[1], self.vertices[2], self.vertices[0]),
2 => (self.vertices[2], self.vertices[0], self.vertices[1]),
_ => panic!("Vertex index {vtx_ix} out of bounds for triangle with 3 vertices"),
};
let [target_vtx_pos, b_vtx_pos, c_vtx_pos] = [
verts[target_vtx_key].position,
verts[b].position,
verts[c].position,
];
let edge_0 = b_vtx_pos - target_vtx_pos;
let edge_1 = c_vtx_pos - target_vtx_pos;
edge_0.angle(&edge_1)
}
pub fn compute_angle_at_vertex_key(
&self,
vtx_key: VertexKey,
verts: &SlotMap<VertexKey, Vertex>,
) -> f32 {
let vtx_ix = self
.vertices
.iter()
.position(|&v| v == vtx_key)
.unwrap_or_else(|| panic!("Vertex key {vtx_key:?} not found in face"));
self.compute_angle_at_vertex(vtx_ix, verts)
}
pub fn to_triangle(&self, verts: &SlotMap<VertexKey, Vertex>) -> Triangle {
Triangle {
a: verts[self.vertices[0]].position,
b: verts[self.vertices[1]].position,
c: verts[self.vertices[2]].position,
}
}
pub fn is_degenerate(&self, verts: &SlotMap<VertexKey, Vertex>) -> bool {
self.to_triangle(verts).is_degenerate()
}
}
#[derive(Clone, Debug)]
pub struct Edge {
// Ordered such that the first vertex key is always less than the second
pub vertices: [VertexKey; 2],
pub faces: SmallVec<[FaceKey; 2]>,
pub sharp: bool,
}
impl Edge {
pub fn length(&self, verts: &SlotMap<VertexKey, Vertex>) -> f32 {
let a = verts[self.vertices[0]].position;
let b = verts[self.vertices[1]].position;
(a - b).magnitude()
}
pub fn other_vtx(&self, vtx_key: VertexKey) -> VertexKey {
if self.vertices[0] == vtx_key {
self.vertices[1]
} else if self.vertices[1] == vtx_key {
self.vertices[0]
} else {
panic!("Vertex key {vtx_key:?} not found in edge");
}
}
}
fn distance(p0: Vec3, p1: Vec3) -> f32 {
(p0 - p1).magnitude()
}
/// Fast `acos` approximation (Abramowitz & Stegun 4.4.45), max abs error ~6.7e-5 rad. Much cheaper
/// than libm `acos`, which has no hardware support on wasm.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
#[inline]
fn fast_acos(x: f32) -> f32 {
let neg = if x < 0. { 1.0f32 } else { 0.0 };
let x = x.abs();
let mut ret = -0.0187293;
ret = ret * x + 0.074261;
ret = ret * x - 0.2121144;
ret = ret * x + 1.5707288;
ret *= (1.0 - x).sqrt();
ret -= 2. * neg * ret;
neg * PI + ret
}
/// SIMD 4-lane `fast_acos`.
#[cfg(target_arch = "wasm32")]
#[inline]
fn fast_acos_x4(x: core::arch::wasm32::v128) -> core::arch::wasm32::v128 {
use core::arch::wasm32::*;
let neg = v128_and(f32x4_lt(x, f32x4_splat(0.)), f32x4_splat(1.0));
let x = f32x4_abs(x);
let mut ret = f32x4_splat(-0.0187293);
ret = f32x4_add(f32x4_mul(ret, x), f32x4_splat(0.074261));
ret = f32x4_add(f32x4_mul(ret, x), f32x4_splat(-0.2121144));
ret = f32x4_add(f32x4_mul(ret, x), f32x4_splat(1.5707288));
ret = f32x4_mul(ret, f32x4_sqrt(f32x4_sub(f32x4_splat(1.0), x)));
ret = f32x4_sub(ret, f32x4_mul(f32x4_mul(f32x4_splat(2.0), neg), ret));
f32x4_add(f32x4_mul(neg, f32x4_splat(PI)), ret)
}
#[inline]
fn batch_acos(cos0: &[f32; 4], cos1: &[f32; 4]) -> ([f32; 4], [f32; 4]) {
#[cfg(target_arch = "wasm32")]
{
use core::arch::wasm32::*;
let (mut a0, mut a1) = ([0f32; 4], [0f32; 4]);
unsafe {
v128_store(
a0.as_mut_ptr().cast(),
fast_acos_x4(v128_load(cos0.as_ptr().cast())),
);
v128_store(
a1.as_mut_ptr().cast(),
fast_acos_x4(v128_load(cos1.as_ptr().cast())),
);
}
(a0, a1)
}
#[cfg(not(target_arch = "wasm32"))]
{
(cos0.map(fast_acos), cos1.map(fast_acos))
}
}
/// Batches 4 faces' corner cosines so each `acos` resolves via one SIMD `fast_acos_x4`. The third
/// corner angle is derived from `a0 + a1 + a2 == PI`, saving a third `acos`.
#[derive(Default)]
struct AcosBatch {
n: usize,
key: [FaceKey; 4],
normal: [Vec3; 4],
cos0: [f32; 4],
cos1: [f32; 4],
}
impl AcosBatch {
#[inline]
fn push(&mut self, key: FaceKey, normal: Vec3, cos0: f32, cos1: f32, data: &mut [FaceShading]) {
let n = self.n;
self.key[n] = key;
self.normal[n] = normal;
self.cos0[n] = cos0;
self.cos1[n] = cos1;
self.n = n + 1;
if self.n == 4 {
self.flush(data);
}
}
#[inline]
fn flush(&mut self, data: &mut [FaceShading]) {
let (a0s, a1s) = batch_acos(&self.cos0, &self.cos1);
for i in 0..self.n {
let a2 = (PI - a0s[i] - a1s[i]).max(0.);
data[fkey_ix(&self.key[i]) as usize] = FaceShading {
normal: self.normal[i],
angles: [a0s[i], a1s[i], a2],
};
}
self.n = 0;
}
}
/// Mesh representation that maintains topological information between vertices,
/// edges, and faces.
///
/// Similar to a half-edge data structure, but with a some differences such as
/// all faces being triangles and no intrinsic directionality to edges.
/// Instead, faces store their vertices directly in-order.
#[derive(Clone, Default)]
pub struct LinkedMesh<FaceData = ()> {
pub vertices: SlotMap<VertexKey, Vertex>,
pub faces: SlotMap<FaceKey, Face<FaceData>>,
pub edges: SlotMap<EdgeKey, Edge>,
pub transform: Option<Mat4>,
/// Per-vertex normal used for shading/lighting. Sparse: absence = no normal.
pub shading_normals: SecondaryMap<VertexKey, Vec3>,
/// Per-vertex normal used for displacement mapping.
pub displacement_normals: SecondaryMap<VertexKey, Vec3>,
/// Per-edge normal used for displacement mapping.
pub edge_displacement_normals: SecondaryMap<EdgeKey, Vec3>,
/// Generic passive per-vertex attribute channels (uv, tangent, color, user-defined), keyed by
/// channel name.
pub vertex_channels: FxHashMap<String, Channel<VertexKey>>,
/// Generic passive per-edge attribute channels.
pub edge_channels: FxHashMap<String, Channel<EdgeKey>>,
/// `mesh_flags` bitset controlling the render finalize pass. Default 0 = full default treatment.
pub flags: u32,
}
/// Opt-in per-mesh flags. Whether to recompute shading normals is decided from ground truth (are
/// the `shading_normals` complete), but welding coincident vertices can't be inferred that way — a
/// mesh with attribute seams (UV cuts, duplicated boundary rings) has position-coincident verts
/// that must stay distinct. Ops that author such seams set `NO_WELD` to opt out of the
/// distance-weld.
pub mod mesh_flags {
/// Skip `merge_vertices_by_distance` at render finalize.
pub const NO_WELD: u32 = 1 << 0;
}
impl<FaceData> LinkedMesh<FaceData> {
#[inline]
pub fn has_flag(&self, flag: u32) -> bool {
self.flags & flag != 0
}
pub fn shading_normal(&self, key: VertexKey) -> Option<Vec3> {
self.shading_normals.get(key).copied()
}
pub fn displacement_normal(&self, key: VertexKey) -> Option<Vec3> {
self.displacement_normals.get(key).copied()
}
pub fn edge_displacement_normal(&self, key: EdgeKey) -> Option<Vec3> {
self.edge_displacement_normals.get(key).copied()
}
pub fn set_shading_normal(&mut self, key: VertexKey, normal: Option<Vec3>) {
set_channel(&mut self.shading_normals, key, normal);
}
pub fn set_displacement_normal(&mut self, key: VertexKey, normal: Option<Vec3>) {
set_channel(&mut self.displacement_normals, key, normal);
}
pub fn set_edge_displacement_normal(&mut self, key: EdgeKey, normal: Option<Vec3>) {
set_channel(&mut self.edge_displacement_normals, key, normal);
}
/// Removes a vertex along with any per-vertex channel data keyed to it. All vertex removals
/// should go through here so the attribute channels don't accumulate stale entries as the mesh
/// is edited.
pub fn remove_vertex(&mut self, key: VertexKey) -> Option<Vertex> {
self.shading_normals.remove(key);
self.displacement_normals.remove(key);
for ch in self.vertex_channels.values_mut() {
ch.store.remove(key);
}
self.vertices.remove(key)
}
/// Removes an edge along with any per-edge channel data keyed to it.
pub fn remove_edge(&mut self, key: EdgeKey) -> Option<Edge> {
self.edge_displacement_normals.remove(key);
for ch in self.edge_channels.values_mut() {
ch.store.remove(key);
}
self.edges.remove(key)
}
/// Inserts a fresh vertex, cloning every passive channel value from `src` (the seam-duplicate
/// case). Named normals are the caller's responsibility — they're recomputed/assigned bespoke.
pub fn add_vertex_cloned_from(&mut self, src: VertexKey, position: Vec3) -> VertexKey {
let key = self.vertices.insert(Vertex::new(position));
for ch in self.vertex_channels.values_mut() {
ch.store.clone_slot(key, src);
}
key
}
/// Inserts a fresh vertex, blending every passive channel from the weighted `srcs` per the
/// channel's interp rule (the split/cut case). Named normals stay the caller's responsibility.
pub fn add_vertex_interpolated(
&mut self,
srcs: &[(VertexKey, f32)],
position: Vec3,
) -> VertexKey {
let key = self.vertices.insert(Vertex::new(position));
for ch in self.vertex_channels.values_mut() {
ch.store.interp_slot(key, srcs, ch.interp);
}
key
}
/// Clones `src` into a fresh vertex inheriting its position, normals, and passive channels, then
/// repoints `faces` onto the clone. Introduces a UV/material seam at a shared vertex *without*
/// recomputing or creasing the smooth normal — the caller typically then overrides a channel
/// (e.g. the UV `V` of a closed-profile wrap) on the returned clone. `faces` must reference
/// `src`.
pub fn split_off_faces(&mut self, src: VertexKey, faces: &[FaceKey]) -> VertexKey
where
FaceData: Default,
{
let position = self.vertices[src].position;
let clone = self.add_vertex_cloned_from(src, position);
let shading_normal = self.shading_normal(src);
self.set_shading_normal(clone, shading_normal);
let displacement_normal = self.displacement_normal(src);
self.set_displacement_normal(clone, displacement_normal);
for &face_key in faces {
self.replace_vertex_in_face(face_key, src, clone);
}
clone
}
}
fn set_channel<K: Key>(channel: &mut SecondaryMap<K, Vec3>, key: K, value: Option<Vec3>) {
match value {
Some(v) => {
channel.insert(key, v);
}
None => {
channel.remove(key);
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Arity {
Scalar,
Vec2,
Vec3,
Vec4,
}
/// How a passive channel's value at a newly-created vertex/edge is derived from its sources.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Interp {
/// Weighted average of the sources (uv, color, …).
Lerp,
/// Weighted average, then renormalized — for unit-length data like tangents.
LerpNormalize,
}
/// How a passive channel transforms when the surface is flipped/inverted (winding reversed).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum FlipXform {
Identity,
Negate,
}
/// How a passive channel responds to a spatial (affine) transform baked into the mesh.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SpatialXform {
/// Not a spatial quantity (uv, color, …); left unchanged.
Identity,
/// A direction lying in the surface (tangent); its `xyz` lanes are multiplied by the transform's
/// linear part.
Direction,
}
/// Tight per-arity SoA storage for one passive attribute channel.
#[derive(Clone, Debug)]
pub enum ChannelStore<K: Key> {
Scalar(SecondaryMap<K, f32>),
Vec2(SecondaryMap<K, [f32; 2]>),
Vec3(SecondaryMap<K, [f32; 3]>),
Vec4(SecondaryMap<K, [f32; 4]>),
}
impl<K: Key> ChannelStore<K> {
pub fn new(arity: Arity) -> Self {
match arity {
Arity::Scalar => ChannelStore::Scalar(SecondaryMap::new()),
Arity::Vec2 => ChannelStore::Vec2(SecondaryMap::new()),
Arity::Vec3 => ChannelStore::Vec3(SecondaryMap::new()),
Arity::Vec4 => ChannelStore::Vec4(SecondaryMap::new()),
}
}
pub fn arity(&self) -> usize {
match self {
ChannelStore::Scalar(_) => 1,
ChannelStore::Vec2(_) => 2,
ChannelStore::Vec3(_) => 3,
ChannelStore::Vec4(_) => 4,
}
}
/// Reads a slot as a fixed-width float vector (unused lanes zeroed) so the propagation math can
/// stay arity-agnostic; `set` writes back only the lanes this arity actually stores.
fn get(&self, key: K) -> Option<[f32; 4]> {
match self {
ChannelStore::Scalar(m) => m.get(key).map(|&v| [v, 0., 0., 0.]),
ChannelStore::Vec2(m) => m.get(key).map(|&[a, b]| [a, b, 0., 0.]),
ChannelStore::Vec3(m) => m.get(key).map(|&[a, b, c]| [a, b, c, 0.]),
ChannelStore::Vec4(m) => m.get(key).copied(),
}
}
fn set(&mut self, key: K, v: [f32; 4]) {
match self {
ChannelStore::Scalar(m) => {
m.insert(key, v[0]);
}
ChannelStore::Vec2(m) => {
m.insert(key, [v[0], v[1]]);
}
ChannelStore::Vec3(m) => {
m.insert(key, [v[0], v[1], v[2]]);
}
ChannelStore::Vec4(m) => {
m.insert(key, v);
}
}
}
fn remove(&mut self, key: K) {
match self {
ChannelStore::Scalar(m) => {
m.remove(key);
}
ChannelStore::Vec2(m) => {
m.remove(key);
}
ChannelStore::Vec3(m) => {
m.remove(key);
}
ChannelStore::Vec4(m) => {
m.remove(key);
}
}
}
fn clone_slot(&mut self, dst: K, src: K) {
if let Some(v) = self.get(src) {
self.set(dst, v);
}
}
/// Weighted blend of `srcs`; `None` if any source lacks a value (matches the named-normal `zip`
/// semantics).
fn blend(&self, srcs: &[(K, f32)], interp: Interp) -> Option<[f32; 4]> {
let arity = self.arity();
let mut acc = [0f32; 4];
for &(key, weight) in srcs {
let v = self.get(key)?;
for i in 0..4 {
acc[i] += v[i] * weight;
}
}
if interp == Interp::LerpNormalize && arity >= 2 {
let norm = (0..arity).map(|i| acc[i] * acc[i]).sum::<f32>().sqrt();
if norm > 1e-12 {
for x in acc.iter_mut().take(arity) {
*x /= norm;
}
}
}
Some(acc)
}
fn interp_slot(&mut self, dst: K, srcs: &[(K, f32)], interp: Interp) {
if let Some(v) = self.blend(srcs, interp) {
self.set(dst, v);
}
}
fn flip_slot(&mut self, key: K, flip: FlipXform) {
if flip == FlipXform::Negate {
if let Some(mut v) = self.get(key) {
for x in &mut v {
*x = -*x;
}
self.set(key, v);
}
}
}
fn flip_all(&mut self, flip: FlipXform) {
if flip != FlipXform::Negate {
return;
}
match self {
ChannelStore::Scalar(m) => m.values_mut().for_each(|v| *v = -*v),
ChannelStore::Vec2(m) => m
.values_mut()
.for_each(|v| v.iter_mut().for_each(|x| *x = -*x)),
ChannelStore::Vec3(m) => m
.values_mut()
.for_each(|v| v.iter_mut().for_each(|x| *x = -*x)),
ChannelStore::Vec4(m) => m
.values_mut()
.for_each(|v| v.iter_mut().for_each(|x| *x = -*x)),
}
}
/// Multiplies the `xyz` lanes of every value by `m`, renormalizing to preserve unit length. Used
/// to carry direction channels (tangents) through a spatial transform; no-op for scalar/vec2.
fn transform_directions(&mut self, m: &Matrix3<f32>) {
let apply = |xyz: Vec3| {
let out = m * xyz;
let n = out.norm();
if n > 1e-12 {
out / n
} else {
out
}
};
let write = |v: &mut [f32]| {
let t = apply(Vec3::new(v[0], v[1], v[2]));
v[0] = t.x;
v[1] = t.y;
v[2] = t.z;
};
match self {
ChannelStore::Scalar(_) | ChannelStore::Vec2(_) => {}
ChannelStore::Vec3(map) => map.values_mut().for_each(|v| write(v)),
ChannelStore::Vec4(map) => map.values_mut().for_each(|v| write(v)),
}
}
}
/// A passive (non-normal) attribute channel: arity-tagged SoA storage plus the rules for how it
/// propagates through vertex/edge creation and surface flips.
#[derive(Clone, Debug)]
pub struct Channel<K: Key> {
pub interp: Interp,
pub flip: FlipXform,
pub spatial: SpatialXform,
pub store: ChannelStore<K>,
}
impl<K: Key> Channel<K> {
pub fn new(arity: Arity, interp: Interp, flip: FlipXform, spatial: SpatialXform) -> Self {
Channel {
interp,
flip,
spatial,
store: ChannelStore::new(arity),
}
}
/// Carries a `Direction` channel through a spatial transform via its linear part; no-op
/// otherwise.
pub fn transform_directions(&mut self, m: &Matrix3<f32>) {
if self.spatial == SpatialXform::Direction {
self.store.transform_directions(m);
}
}
/// Weighted blend of `srcs` per this channel's interp rule; `None` if any source lacks a value.
pub fn blend(&self, srcs: &[(K, f32)]) -> Option<[f32; 4]> {
self.store.blend(srcs, self.interp)
}
pub fn transform_direction_slot(&mut self, key: K, m: &Matrix3<f32>) {
if self.spatial != SpatialXform::Direction {
return;
}
if let Some(mut v) = self.store.get(key) {
let out = m * Vec3::new(v[0], v[1], v[2]);
let n = out.norm();
let out = if n > 1e-12 { out / n } else { out };
v[0] = out.x;
v[1] = out.y;
v[2] = out.z;
self.store.set(key, v);
}
}
/// Applies this channel's flip rule to one slot (surface winding reversed there).
pub fn flip_slot(&mut self, key: K) {
self.store.flip_slot(key, self.flip);
}
/// Writes `value` for `key`; lanes above this channel's arity are ignored, so callers pass
/// `[x, y, 0., 0.]` for a `Vec2` channel, etc.
pub fn set(&mut self, key: K, value: [f32; 4]) {
self.store.set(key, value);
}
/// Reads `key` as a fixed-width vector; lanes above this channel's arity are zero.
pub fn get(&self, key: K) -> Option<[f32; 4]> {
self.store.get(key)
}
/// An empty channel sharing this one's arity, interp, and flip rules.
pub fn empty_like(&self) -> Self {
let store = match &self.store {
ChannelStore::Scalar(_) => ChannelStore::Scalar(SecondaryMap::new()),
ChannelStore::Vec2(_) => ChannelStore::Vec2(SecondaryMap::new()),
ChannelStore::Vec3(_) => ChannelStore::Vec3(SecondaryMap::new()),
ChannelStore::Vec4(_) => ChannelStore::Vec4(SecondaryMap::new()),
};
Channel {
interp: self.interp,
flip: self.flip,
spatial: self.spatial,
store,
}
}
}
impl<T> Debug for LinkedMesh<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"LinkedMesh {{ vertices: {}, faces: {}, edges: {} }}",
self.vertices.len(),
self.faces.len(),
self.edges.len()
)
}
}
fn sort_edge(v0: VertexKey, v1: VertexKey) -> [VertexKey; 2] {
let v0_ix = vkey_ix(&v0);
let v1_ix = vkey_ix(&v1);
if v0_ix < v1_ix {
[v0, v1]
} else {
[v1, v0]
}
}
fn sort_edge_inplace<const DENSE: bool>(vtxs: &mut [VertexKey; 2]) {
if DENSE {
let [vtx0, vtx1] = vtxs;
debug_assert_eq!(vkey_version(vtx0), 1);
debug_assert_eq!(vkey_version(vtx1), 1);
let v0_ix = vkey_ix_mut(vtx0);
let v1_ix = vkey_ix_mut(vtx1);
if *v0_ix > *v1_ix {
std::mem::swap(v0_ix, v1_ix);
}
} else {
let v0_ix = vkey_ix(&vtxs[0]);
let v1_ix = vkey_ix(&vtxs[1]);
if v0_ix > v1_ix {
vtxs.swap(0, 1);
}
}
}
/// Per-face shading data precomputed once before fan-walking. Indexed by `fkey_ix`. A degenerate
/// face is flagged by an all-zero `normal` (a valid face normal is unit).
#[derive(Clone, Default)]
struct FaceShading {
normal: Vec3,
/// Corner angle at the owning face's i-th vertex; the normal's accumulation weight.
angles: [f32; 3],
}
impl FaceShading {
/// Angle-weighted normal at `center`; zero for degenerate faces (a no-op when accumulated).
#[inline]
fn weighted_at(&self, verts: &[VertexKey; 3], center: VertexKey) -> Vec3 {
let corner = if verts[0] == center {
0
} else if verts[1] == center {
1
} else {
2
};
self.normal * self.angles[corner]
}
}
#[derive(Debug)]
struct NormalAcc {
pub accumulated_normal: Vec3,
}
impl NormalAcc {
pub fn get(&self) -> Option<Vec3> {
if self.accumulated_normal == Vec3::zeros() {
None
} else {
let normalized = self.accumulated_normal.normalize();
if normalized.x.is_nan() || normalized.y.is_nan() || normalized.z.is_nan() {
panic!("Non-zero but still NaN normalized: {self:?}");
}
Some(normalized)
}
}
fn new() -> Self {
Self {
accumulated_normal: Vec3::zeros(),
}
}
}
struct SmoothFan {
pub old_key: VertexKey,
pub face_keys: SmallVec<[FaceKey; 8]>,
pub normal: Vec3,
}
/// Determines the method used to compute displacement normals for new vertices
/// produced when splitting edges
#[repr(u32)]
#[derive(Clone, Copy)]
pub enum DisplacementNormalMethod {
/// Displacement normals are generated by mixing the normals of the vertices
/// of edges when splitting them
Interpolate = 0,
/// Displacement normals are assigned from the normal of the edge when
/// splitting them
EdgeNormal = 1,
}
impl TryFrom<u32> for DisplacementNormalMethod {
type Error = ();
fn try_from(value: u32) -> Result<Self, Self::Error> {
match value {
0 => Ok(DisplacementNormalMethod::Interpolate),
1 => Ok(DisplacementNormalMethod::EdgeNormal),
_ => Err(()),
}
}
}
#[derive(Debug, Clone)]
pub enum NonManifoldError {
/// No faces in the mesh
EmptyMesh,
/// Edge is not connected to any faces
LooseEdge { edge_key: EdgeKey },
/// Vertex is either not connected to any edges or not used in any faces
LooseVertex { vtx_key: VertexKey },
/// Edge is connected to more than two faces
NonManifoldEdge {
edge_key: EdgeKey,
face_count: usize,
},
/// Vertex has more than one fan of faces around it
MultipleFans {
vtx_key: VertexKey,
incident_face_count: usize,
visited_face_count: usize,
},
/// The fan of faces around a vertex is not closed
NonClosedFan { vtx_key: VertexKey },
}
pub struct EdgeSplitPos {
/// Number from 0. to 1. representing the position along the edge from the
/// starting vertex to split at
pub pos: f32,
pub start_vtx_key: VertexKey,
}
impl EdgeSplitPos {
fn get(&self, v0_key: VertexKey) -> f32 {
if v0_key == self.start_vtx_key {
self.pos
} else {
1. - self.pos
}
}
pub fn middle() -> Self {
Self {
pos: 0.5,
start_vtx_key: VertexKey::null(),
}
}
}
const EPSILON: f32 = 1e-5;
#[derive(Clone, Debug)]
pub struct Plane {
pub normal: Vec3,
pub w: f32,
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum PolygonClass {
Coplanar = 0,
Front = 1,
Back = 2,
Spanning = 3,
}
impl From<u8> for PolygonClass {
fn from(val: u8) -> Self {
match val {
0 => PolygonClass::Coplanar,
1 => PolygonClass::Front,
2 => PolygonClass::Back,
3 => PolygonClass::Spanning,
_ => panic!("Invalid PolygonClass value"),
}
}
}
impl std::ops::BitOr for PolygonClass {
type Output = Self;
fn bitor(self, rhs: Self) -> Self::Output {
let out = self as u8 | rhs as u8;
out.into()
}
}
/// Generates vertices arranged in rings at different heights.
///
/// Creates `height_segments + 1` rings, each with `radial_segments` vertices.
/// - `radius_fn(h)`: returns the radius at normalized height `h` (0.0 to 1.0)
/// - `y_fn(h)`: returns the y-coordinate at normalized height `h` (0.0 to 1.0)
fn generate_radial_vertices(
vertices: &mut Vec<Vec3>,
radial_segments: usize,
height_segments: usize,
radius_fn: impl Fn(f32) -> f32,
y_fn: impl Fn(f32) -> f32,
) {
for h in 0..=height_segments {
let h_norm = h as f32 / height_segments as f32;
let y = y_fn(h_norm);
let radius = radius_fn(h_norm);
for r in 0..radial_segments {
let theta = (r as f32 / radial_segments as f32) * 2. * PI;
let x = radius * theta.cos();
let z = radius * theta.sin();
vertices.push(Vec3::new(x, y, z));
}
}
}
/// Generates quad (two triangle) indices connecting adjacent height rings.
///
/// Connects rings of vertices arranged in the pattern created by `generate_radial_vertices`.
fn generate_radial_side_indices(
indices: &mut Vec<u32>,
radial_segments: usize,
height_segments: usize,
) {
for h in 0..height_segments {
for r in 0..radial_segments {
let v0 = h * radial_segments + r;
let v1 = v0 + radial_segments;
let next_r = (r + 1) % radial_segments;
let v0_next = h * radial_segments + next_r;
let v1_next = v0_next + radial_segments;
indices.push(v0 as u32);
indices.push(v1 as u32);
indices.push(v0_next as u32);
indices.push(v1 as u32);
indices.push(v1_next as u32);
indices.push(v0_next as u32);
}