-
Notifications
You must be signed in to change notification settings - Fork 18
/
mesh.go
1855 lines (1361 loc) · 49.8 KB
/
mesh.go
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
package tetra3d
import (
"errors"
"fmt"
"log"
"math"
)
// Dimensions represents the minimum and maximum spatial dimensions of a Mesh arranged in a 2-space Vector slice.
type Dimensions struct {
Min, Max Vector
}
func NewEmptyDimensions() Dimensions {
return Dimensions{
Vector{math.MaxFloat64, math.MaxFloat64, math.MaxFloat64, 0},
Vector{-math.MaxFloat64, -math.MaxFloat64, -math.MaxFloat64, 0},
}
}
// MaxDimension returns the maximum value from all of the axes in the Dimensions. For example, if the Dimensions have a min of [-1, -2, -2],
// and a max of [6, 1.5, 1], Max() will return 7 for the X axis, as it's the largest distance between all axes.
func (dim Dimensions) MaxDimension() float64 {
return math.Max(math.Max(dim.Width(), dim.Height()), dim.Depth())
}
// MaxSpan returns the maximum span between the corners of the dimension set.
func (dim Dimensions) MaxSpan() float64 {
return dim.Max.Sub(dim.Min).Magnitude()
}
// Center returns the center point inbetween the two corners of the dimension set.
func (dim Dimensions) Center() Vector {
return Vector{
(dim.Max.X + dim.Min.X) / 2,
(dim.Max.Y + dim.Min.Y) / 2,
(dim.Max.Z + dim.Min.Z) / 2,
0,
}
}
// Width returns the total difference between the minimum and maximum X values.
func (dim Dimensions) Width() float64 {
return dim.Max.X - dim.Min.X
}
// Height returns the total difference between the minimum and maximum Y values.
func (dim Dimensions) Height() float64 {
return dim.Max.Y - dim.Min.Y
}
// Depth returns the total difference between the minimum and maximum Z values.
func (dim Dimensions) Depth() float64 {
return dim.Max.Z - dim.Min.Z
}
// Clamp limits the provided position vector to be within the dimensions set.
func (dim Dimensions) Clamp(position Vector) Vector {
if position.X < dim.Min.X {
position.X = dim.Min.X
} else if position.X > dim.Max.X {
position.X = dim.Max.X
}
if position.Y < dim.Min.Y {
position.Y = dim.Min.Y
} else if position.Y > dim.Max.Y {
position.Y = dim.Max.Y
}
if position.Z < dim.Min.Z {
position.Z = dim.Min.Z
} else if position.Z > dim.Max.Z {
position.Z = dim.Max.Z
}
return position
}
// Inside returns if a position is inside a set of dimensions.
func (dim Dimensions) Inside(position Vector) bool {
if position.X < dim.Min.X ||
position.X > dim.Max.X ||
position.Y < dim.Min.Y ||
position.Y > dim.Max.Y ||
position.Z < dim.Min.Z ||
position.Z > dim.Max.Z {
return false
}
return true
}
func (dim Dimensions) Size() Vector {
return Vector{dim.Width(), dim.Height(), dim.Depth(), 0}
}
// func (dim Dimensions) reform() {
// if dim.Min.X > dim.Max.X {
// swap := dim.Mi
// }
// for i := 0; i < 3; i++ {
// if dim.Min[i] > dim.Max[i] {
// swap := dim.Max[i]
// dim.Max[i] = dim.Min[i]
// dim.Min[i] = swap
// }
// }
// }
// NewDimensionsFromPoints creates a new Dimensions struct from the given series of positions.
func NewDimensionsFromPoints(points ...Vector) Dimensions {
if len(points) == 0 {
panic("error: no points passed to NewDimensionsFromPoints()")
}
dim := NewEmptyDimensions()
for _, point := range points {
if dim.Min.X > point.X {
dim.Min.X = point.X
}
if dim.Min.Y > point.Y {
dim.Min.Y = point.Y
}
if dim.Min.Z > point.Z {
dim.Min.Z = point.Z
}
if dim.Max.X < point.X {
dim.Max.X = point.X
}
if dim.Max.Y < point.Y {
dim.Max.Y = point.Y
}
if dim.Max.Z < point.Z {
dim.Max.Z = point.Z
}
}
return dim
}
type MeshUniqueType int
const (
MeshUniqueFalse MeshUniqueType = iota
MeshUniqueMesh
MeshUniqueMeshAndMaterials
)
// Mesh represents a mesh that can be represented visually in different locations via Models. By default, a new Mesh has no MeshParts (so you would need to add one
// manually if you want to construct a Mesh via code).
type Mesh struct {
Name string // The name of the Mesh resource
library *Library // A reference to the Library this Mesh came from.
MeshParts []*MeshPart // The various mesh parts (collections of triangles, rendered with a single material).
Triangles []*Triangle // The various triangles composing the Mesh.
triIndex int
// Vertices are stored as a struct-of-arrays for simplified and faster rendering.
// Each vertex property (position, normal, UV, colors, weights, bones, etc) is stored
// here and indexed in order of vertex index.
vertexTransforms []Vector
VertexPositions []Vector
VertexNormals []Vector
vertexSkinnedNormals []Vector
vertexSkinnedPositions []Vector
vertexTransformedNormals []Vector
VertexUVs []Vector // The UV values for each vertex
VertexUVOriginalValues []Vector // The original UV values for each vertex
VertexColors [][]Color
VertexActiveColorChannel []int // VertexActiveColorChannel is the active vertex color used for coloring the vertex in the index given.
VertexGroupNames []string // The names of the vertex groups applies to the Mesh; this is only populated if the Mesh is affected by an armature
VertexWeights [][]float32 // TODO: Replace this with [][8]float32 (or however many the maximum is for GLTF)
VertexBones [][]uint16 // TODO: Replace this with [][8]uint16 (or however many the maximum number of bones affecting a single vertex is for GLTF)
visibleVertices []bool
maxTriangleSpan float64
vertexLights []Color
vertsAddStart int
vertsAddEnd int
VertexColorChannelNames map[string]int // VertexColorChannelNames is a map allowing you to get the index of a mesh's vertex color channel by its name.
Dimensions Dimensions
properties Properties
// If Unique is set to a value other than MeshUniqueNone, whenever a Mesh is used for a Model and the Model is cloned,
// the Mesh or Mesh and Materials are cloned with it. Useful for things like sprites.
Unique MeshUniqueType
}
// NewMesh takes a name and a slice of *Vertex instances, and returns a new Mesh. If you provide *Vertex instances, the number must be divisible by 3,
// or NewMesh will panic.
func NewMesh(name string, verts ...VertexInfo) *Mesh {
mesh := &Mesh{
Name: name,
MeshParts: []*MeshPart{},
Dimensions: Dimensions{Vector{0, 0, 0, 0}, Vector{0, 0, 0, 0}},
VertexColorChannelNames: map[string]int{},
properties: NewProperties(),
vertexTransforms: []Vector{},
VertexPositions: []Vector{},
visibleVertices: []bool{},
VertexNormals: []Vector{},
vertexSkinnedNormals: []Vector{},
vertexSkinnedPositions: []Vector{},
vertexTransformedNormals: []Vector{},
vertexLights: []Color{},
VertexUVs: []Vector{},
VertexColors: [][]Color{},
VertexActiveColorChannel: []int{},
VertexBones: [][]uint16{},
VertexWeights: [][]float32{},
}
if len(verts) > 0 {
mesh.AddVertices(verts...)
}
return mesh
}
// Clone clones the Mesh, creating a new Mesh that has cloned MeshParts.
func (mesh *Mesh) Clone() *Mesh {
newMesh := NewMesh(mesh.Name)
newMesh.library = mesh.library
newMesh.properties = mesh.properties.Clone()
newMesh.triIndex = mesh.triIndex
newMesh.allocateVertexBuffers(len(mesh.VertexPositions))
for i := range mesh.VertexPositions {
newMesh.VertexPositions = append(newMesh.VertexPositions, mesh.VertexPositions[i])
newMesh.visibleVertices = append(newMesh.visibleVertices, false)
}
for i := range mesh.VertexNormals {
newMesh.VertexNormals = append(newMesh.VertexNormals, mesh.VertexNormals[i])
}
for i := range mesh.vertexLights {
newMesh.vertexLights = append(newMesh.vertexLights, mesh.vertexLights[i])
}
for i := range mesh.VertexUVs {
newMesh.VertexUVs = append(newMesh.VertexUVs, mesh.VertexUVs[i])
newMesh.VertexUVOriginalValues = append(newMesh.VertexUVOriginalValues, mesh.VertexUVs[i])
}
for i := range mesh.VertexColors {
newMesh.VertexColors = append(newMesh.VertexColors, make([]Color, len(mesh.VertexColors[i])))
for channelIndex := range mesh.VertexColors[i] {
newMesh.VertexColors[i][channelIndex] = mesh.VertexColors[i][channelIndex]
}
}
for c := range mesh.VertexActiveColorChannel {
newMesh.VertexActiveColorChannel = append(newMesh.VertexActiveColorChannel, mesh.VertexActiveColorChannel[c])
}
for c := range mesh.VertexBones {
newMesh.VertexBones = append(newMesh.VertexBones, []uint16{})
for v := range mesh.VertexBones[c] {
newMesh.VertexBones[c] = append(newMesh.VertexBones[c], mesh.VertexBones[c][v])
}
}
for c := range mesh.VertexWeights {
newMesh.VertexWeights = append(newMesh.VertexWeights, []float32{})
for v := range mesh.VertexWeights[c] {
newMesh.VertexWeights[c] = append(newMesh.VertexWeights[c], mesh.VertexWeights[c][v])
}
}
for v := range mesh.vertexTransforms {
newMesh.vertexTransforms = append(newMesh.vertexTransforms, mesh.vertexTransforms[v])
}
for v := range mesh.vertexSkinnedNormals {
newMesh.vertexSkinnedNormals = append(newMesh.vertexSkinnedNormals, mesh.vertexSkinnedNormals[v])
}
for v := range mesh.vertexTransformedNormals {
newMesh.vertexTransformedNormals = append(newMesh.vertexTransformedNormals, mesh.vertexTransformedNormals[v])
}
for v := range mesh.vertexSkinnedPositions {
newMesh.vertexSkinnedPositions = append(newMesh.vertexSkinnedPositions, mesh.vertexSkinnedPositions[v])
}
newMesh.Triangles = make([]*Triangle, 0, len(mesh.Triangles))
for _, part := range mesh.MeshParts {
newPart := part.Clone()
newPart.ForEachTri(
func(tri *Triangle) {
newTri := tri.Clone()
newTri.MeshPart = newPart
newMesh.Triangles = append(newMesh.Triangles, newTri)
},
)
newPart.AssignToMesh(newMesh)
}
newMesh.vertsAddEnd = mesh.vertsAddEnd
newMesh.vertsAddStart = mesh.vertsAddStart
for channelName, index := range mesh.VertexColorChannelNames {
newMesh.VertexColorChannelNames[channelName] = index
}
newMesh.Dimensions = mesh.Dimensions
newMesh.Unique = mesh.Unique
if newMesh.Unique == MeshUniqueMeshAndMaterials {
for _, meshPart := range newMesh.MeshParts {
meshPart.Material = meshPart.Material.Clone()
}
}
newMesh.maxTriangleSpan = mesh.maxTriangleSpan
newMesh.VertexGroupNames = append(newMesh.VertexGroupNames, mesh.VertexGroupNames...)
return newMesh
}
// allocateVertexBuffers allows us to allocate the slices for vertex properties all at once rather than resizing multiple times as
// we append to a slice and have its backing buffer automatically expanded (which is slower).
func (mesh *Mesh) allocateVertexBuffers(vertexCount int) {
if cap(mesh.VertexPositions) >= vertexCount {
return
}
mesh.VertexPositions = append(make([]Vector, 0, vertexCount), mesh.VertexPositions...)
if len(mesh.visibleVertices) < vertexCount {
mesh.visibleVertices = make([]bool, vertexCount)
}
mesh.VertexNormals = append(make([]Vector, 0, vertexCount), mesh.VertexNormals...)
mesh.vertexLights = append(make([]Color, 0, vertexCount), mesh.vertexLights...)
mesh.VertexUVs = append(make([]Vector, 0, vertexCount), mesh.VertexUVs...)
mesh.VertexUVOriginalValues = append(make([]Vector, 0, vertexCount), mesh.VertexUVs...)
mesh.VertexColors = append(make([][]Color, 0, vertexCount), mesh.VertexColors...)
mesh.VertexActiveColorChannel = append(make([]int, 0, vertexCount), mesh.VertexActiveColorChannel...)
mesh.VertexBones = append(make([][]uint16, 0, vertexCount), mesh.VertexBones...)
mesh.VertexWeights = append(make([][]float32, 0, vertexCount), mesh.VertexWeights...)
mesh.vertexTransforms = append(make([]Vector, 0, vertexCount), mesh.vertexTransforms...)
mesh.vertexSkinnedNormals = append(make([]Vector, 0, vertexCount), mesh.vertexSkinnedNormals...)
mesh.vertexTransformedNormals = append(make([]Vector, 0, vertexCount), mesh.vertexTransformedNormals...)
mesh.vertexSkinnedPositions = append(make([]Vector, 0, vertexCount), mesh.vertexSkinnedPositions...)
}
func (mesh *Mesh) ensureEnoughVertexColorChannels(channelIndex int) {
for i := range mesh.VertexColors {
for len(mesh.VertexColors[i]) <= channelIndex {
mesh.VertexColors[i] = append(mesh.VertexColors[i], NewColor(1, 1, 1, 1))
}
}
}
// CombineVertexColors allows you to combine vertex color channels together. The targetChannel is the channel that will hold
// the result, and multiplicative controls whether the combination is multiplicative (true) or additive (false). The sourceChannels
// ...int is the vertex color channel indices to combine together.
// If the channel indices provided in the sourceChannels ...int are too high for the number of channels on each vertex in the mesh,
// then those indices will be skipped.
func (mesh *Mesh) CombineVertexColors(targetChannel int, multiplicative bool, sourceChannels ...int) {
if len(sourceChannels) == 0 {
return
}
for i := range mesh.VertexColors {
base := NewColor(0, 0, 0, 1)
if multiplicative {
base = NewColor(1, 1, 1, 1)
}
for _, c := range sourceChannels {
if len(mesh.VertexColors[i]) <= c {
continue
}
if multiplicative {
base = base.Multiply(mesh.VertexColors[i][c])
} else {
base = base.Add(mesh.VertexColors[i][c])
}
}
mesh.ensureEnoughVertexColorChannels(targetChannel)
mesh.VertexColors[i][targetChannel] = base
}
}
// SetVertexColor sets the specified vertex color for all vertices in the mesh for the target color channel.
func (mesh *Mesh) SetVertexColor(targetChannel int, color Color) {
NewVertexSelection().SelectAll(mesh).SetColor(targetChannel, color)
}
// SetActiveColorChannel sets the active color channel for all vertices in the mesh to the specified channel index.
func (mesh *Mesh) SetActiveColorChannel(targetChannel int) {
NewVertexSelection().SelectAll(mesh).SetActiveColorChannel(targetChannel)
}
// Materials returns a slice of the materials present in the Mesh's MeshParts.
func (mesh *Mesh) Materials() []*Material {
mats := []*Material{}
for _, mp := range mesh.MeshParts {
if mp.Material != nil {
mats = append(mats, mp.Material)
}
}
return mats
}
// AddMeshPart allows you to add a new MeshPart to the Mesh with the given Material (with a nil Material reference also being valid).
func (mesh *Mesh) AddMeshPart(material *Material, indices ...int) *MeshPart {
mp := NewMeshPart(mesh, material)
mesh.MeshParts = append(mesh.MeshParts, mp)
if len(indices) > 0 {
mp.AddTriangles(indices...)
}
return mp
}
// FindMeshPart allows you to retrieve a MeshPart by its material's name. If no material with the provided name is given, the function returns nil.
func (mesh *Mesh) FindMeshPart(materialName string) *MeshPart {
for _, mp := range mesh.MeshParts {
if mp.Material != nil && mp.Material.Name == materialName {
return mp
}
}
return nil
}
func (mesh *Mesh) AddVertices(verts ...VertexInfo) {
mesh.vertsAddStart = len(mesh.VertexPositions)
mesh.vertsAddEnd = mesh.vertsAddStart + len(verts)
if len(verts) == 0 {
panic("Error: Mesh.AddVertices() given 0 vertices.")
}
mesh.allocateVertexBuffers(len(mesh.VertexPositions) + len(verts))
for i := 0; i < len(verts); i++ {
vertInfo := verts[i]
mesh.VertexPositions = append(mesh.VertexPositions, Vector{vertInfo.X, vertInfo.Y, vertInfo.Z, 0})
mesh.VertexNormals = append(mesh.VertexNormals, Vector{vertInfo.NormalX, vertInfo.NormalY, vertInfo.NormalZ, 0})
mesh.VertexUVs = append(mesh.VertexUVs, Vector{vertInfo.U, vertInfo.V, 0, 0})
mesh.VertexUVOriginalValues = append(mesh.VertexUVOriginalValues, Vector{vertInfo.U, vertInfo.V, 0, 0})
mesh.VertexColors = append(mesh.VertexColors, vertInfo.Colors)
mesh.VertexActiveColorChannel = append(mesh.VertexActiveColorChannel, vertInfo.ActiveColorChannel)
mesh.VertexBones = append(mesh.VertexBones, vertInfo.Bones)
mesh.VertexWeights = append(mesh.VertexWeights, vertInfo.Weights)
mesh.vertexLights = append(mesh.vertexLights, NewColor(0, 0, 0, 1))
mesh.vertexTransforms = append(mesh.vertexTransforms, Vector{0, 0, 0, 0}) // x, y, z, w
mesh.vertexSkinnedNormals = append(mesh.vertexSkinnedNormals, Vector{0, 0, 0, 0})
mesh.vertexTransformedNormals = append(mesh.vertexTransformedNormals, Vector{0, 0, 0, 0})
mesh.vertexSkinnedPositions = append(mesh.vertexSkinnedPositions, Vector{0, 0, 0, 0})
}
}
// Library returns the Library from which this Mesh was loaded. If it was created through code, this function will return nil.
func (mesh *Mesh) Library() *Library {
return mesh.library
}
// UpdateBounds updates the mesh's dimensions; call this after manually changing vertex positions.
func (mesh *Mesh) UpdateBounds() {
mesh.Dimensions = NewEmptyDimensions()
for _, position := range mesh.VertexPositions {
if mesh.Dimensions.Min.X > position.X {
mesh.Dimensions.Min.X = position.X
}
if mesh.Dimensions.Min.Y > position.Y {
mesh.Dimensions.Min.Y = position.Y
}
if mesh.Dimensions.Min.Z > position.Z {
mesh.Dimensions.Min.Z = position.Z
}
if mesh.Dimensions.Max.X < position.X {
mesh.Dimensions.Max.X = position.X
}
if mesh.Dimensions.Max.Y < position.Y {
mesh.Dimensions.Max.Y = position.Y
}
if mesh.Dimensions.Max.Z < position.Z {
mesh.Dimensions.Max.Z = position.Z
}
}
}
// AutoNormal automatically recalculates the normals for the triangles contained within the Mesh and sets the vertex normals for
// all triangles to the triangles' surface normal.
func (mesh *Mesh) AutoNormal() {
for _, tri := range mesh.Triangles {
tri.RecalculateNormal()
for i := 0; i < 3; i++ {
mesh.VertexNormals[tri.VertexIndices[i]] = tri.Normal
}
}
}
// SelectVertices generates a new vertex selection for the current Mesh.
// This selection should generally be retained to operate on sequentially.
// func (mesh *Mesh) SelectVertices() VertexSelection {
// return VertexSelection{Indices: newSet[int](), Mesh: mesh}
// }
// Properties returns this Mesh object's game Properties struct.
func (mesh *Mesh) Properties() Properties {
return mesh.properties
}
// VertexSelectionSet represents a selection set of indices for a given Mesh.
type VertexSelectionSet struct {
Indices Set[int]
SelectAll bool
}
// VertexSelection represents a selection of vertices on a Mesh.
type VertexSelection struct {
SelectionSet map[*Mesh]*VertexSelectionSet
}
// NewVertexSelection selects all
func NewVertexSelection() VertexSelection {
return VertexSelection{
SelectionSet: map[*Mesh]*VertexSelectionSet{},
}
}
const ErrorVertexChannelOutsideRange = "error: vertex color channel not found by given name"
func (vs VertexSelection) ensureSelectionSetExists(mesh *Mesh) {
if _, ok := vs.SelectionSet[mesh]; !ok {
vs.SelectionSet[mesh] = &VertexSelectionSet{
Indices: newSet[int](),
}
}
}
// SelectInVertexColorChannel selects all vertices in the Mesh that have a non-pure black color in the vertex color channel
// with the specified index. If the index is over the number of vertex colors currently on the Mesh, then the function
// will not alter the VertexSelection and will return an error.
func (vs VertexSelection) SelectInVertexColorChannel(mesh *Mesh, channelNames ...string) (VertexSelection, error) {
vs.ensureSelectionSetExists(mesh)
var err error
for _, groupName := range channelNames {
if channelIndex, ok := mesh.VertexColorChannelNames[groupName]; ok {
for vertexIndex := range mesh.VertexColors {
color := mesh.VertexColors[vertexIndex][channelIndex]
if color.R > 0.01 || color.G > 0.01 || color.B > 0.01 {
vs.SelectionSet[mesh].Indices.Add(vertexIndex)
}
}
} else {
err = errors.New(ErrorVertexChannelOutsideRange)
continue
}
}
return vs, err
}
const ErrorVertexGroupNotFound = "error: vertex channel name not found"
// SelectInVertexGroup selects all vertices in the Mesh that are assigned to the specifiefd vertex groups.
// If any of the vertex groups are not found, the function will return an error.
func (vs VertexSelection) SelectInVertexGroup(mesh *Mesh, vertexGroupNames ...string) (VertexSelection, error) {
vs.ensureSelectionSetExists(mesh)
var err error
for _, groupName := range vertexGroupNames {
vertexGroupIndex := -1
for i, g := range mesh.VertexGroupNames {
if g == groupName {
vertexGroupIndex = i
}
}
if vertexGroupIndex < 0 {
// return vs, errors.New(ErrorVertexGroupNotFound)
err = errors.New(ErrorVertexGroupNotFound)
continue
}
for vertexIndex := range mesh.VertexBones {
boneSet := mesh.VertexBones[vertexIndex]
for _, b := range boneSet {
if b == uint16(vertexGroupIndex) {
vs.SelectionSet[mesh].Indices.Add(vertexIndex)
}
}
}
}
return vs, err
}
// SelectAll selects all vertices on the target meshes.
func (vs VertexSelection) SelectAll(meshes ...*Mesh) VertexSelection {
for _, mesh := range meshes {
vs.ensureSelectionSetExists(mesh)
vs.SelectionSet[mesh].Indices.Clear()
vs.SelectionSet[mesh].SelectAll = true
}
return vs
}
func (vs VertexSelection) Clear() VertexSelection {
for m := range vs.SelectionSet {
delete(vs.SelectionSet, m)
}
return vs
}
// SelectMeshPart selects all vertices in the Mesh belonging to any of the specified MeshParts.
func (vs VertexSelection) SelectMeshPart(meshParts ...*MeshPart) VertexSelection {
for _, meshPart := range meshParts {
meshPart.ForEachTri(
func(tri *Triangle) {
vs.ensureSelectionSetExists(meshPart.Mesh)
for _, index := range tri.VertexIndices {
vs.SelectionSet[meshPart.Mesh].Indices.Add(index)
}
},
)
}
return vs
}
// SelectMeshPartByIndex selects all vertices in the Mesh belonging to the specified MeshPart by
// index.
// If the MeshPart doesn't exist, this function will panic.
func (vs VertexSelection) SelectMeshPartByIndex(mesh *Mesh, indexNumber int) VertexSelection {
vs.ensureSelectionSetExists(mesh)
vs.SelectMeshPart(mesh.MeshParts[indexNumber])
return vs
}
// SelectMeshpartByName selects all vertices in the Mesh belonging to the specified material.
func (vs VertexSelection) SelectMeshpartByName(mesh *Mesh, materialNames ...string) VertexSelection {
vs.ensureSelectionSetExists(mesh)
for _, matName := range materialNames {
if mp := mesh.FindMeshPart(matName); mp != nil {
vs.SelectMeshPart(mp)
}
}
return vs
}
// SelectIndices selects the passed vertex indices in the Mesh.
// This is syntactic sugar for VertexSelection.Indices.Add(indices...)
func (vs VertexSelection) SelectIndices(mesh *Mesh, indices ...int) VertexSelection {
vs.ensureSelectionSetExists(mesh)
for _, i := range indices {
vs.SelectionSet[mesh].Indices.Add(i)
}
return vs
}
// SelectTriangles selects the vertex indices composing the triangles passed.
func (vs VertexSelection) SelectTriangles(mesh *Mesh, triangles ...*Triangle) VertexSelection {
vs.ensureSelectionSetExists(mesh)
for _, t := range triangles {
for _, i := range t.VertexIndices {
vs.SelectionSet[mesh].Indices.Add(i)
}
}
return vs
}
// SelectTriangles selects vertices that share positions with already-selected vertices.
func (vs VertexSelection) SelectSharedVertices() VertexSelection {
for mesh, set := range vs.SelectionSet {
for index := range set.Indices {
for i, vp := range mesh.VertexPositions {
if index == i {
continue
}
if vp.Equals(mesh.VertexPositions[index]) {
set.Indices.Add(i)
}
}
}
}
return vs
}
// SetColor sets the color of the specified channel in all vertices contained within the VertexSelection to the provided Color.
// If the channelIndex provided is greater than the number of channels in the Mesh minus one, vertex color channels will be created for all vertices
// up to the index provided (e.g. VertexSelection.SetColor(2, colors.White()) will make it so that the mesh has at least three color channels - 0, 1, and 2).
func (vs VertexSelection) SetColor(channelIndex int, color Color) {
for mesh := range vs.SelectionSet {
mesh.ensureEnoughVertexColorChannels(channelIndex)
}
vs.ForEachIndex(func(mesh *Mesh, index int) {
mesh.VertexColors[index][channelIndex] = NewColor(color.ToFloat32s())
})
}
// SetNormal sets the normal of all vertices contained within the VertexSelection to the provided normal vector.
func (vs VertexSelection) SetNormal(normal Vector) {
vs.ForEachIndex(func(mesh *Mesh, index int) {
mesh.VertexNormals[index].X = normal.X
mesh.VertexNormals[index].Y = normal.Y
mesh.VertexNormals[index].Z = normal.Z
})
}
// MoveUVs moves the UV values by the values specified.
func (vs VertexSelection) MoveUVs(dx, dy float64) {
vs.ForEachIndex(func(mesh *Mesh, index int) {
mesh.VertexUVs[index].X += dx
mesh.VertexUVs[index].Y += dy
})
}
// ScaleUVs scales the UV values by the percentages specified.
func (vs VertexSelection) ScaleUVs(px, py float64) {
vs.ForEachIndex(func(mesh *Mesh, index int) {
mesh.VertexUVs[index].X *= px
mesh.VertexUVs[index].Y *= py
})
}
// MoveUVsVec moves the UV values by the Vector values specified.
func (vs *VertexSelection) MoveUVsVec(vec Vector) {
vs.MoveUVs(vec.X, vec.Y)
}
// SetUVOffset moves all UV values for vertices selected to be offset by the values specified, with [0, 0] being their original locations.
// Note that for this to work, you would need to store and work with the same vertex selection over multiple frames.
func (vs VertexSelection) SetUVOffset(x, y float64) {
vs.ForEachIndex(func(mesh *Mesh, index int) {
mesh.VertexUVs[index].X = x + mesh.VertexUVOriginalValues[index].X
mesh.VertexUVs[index].Y = y + mesh.VertexUVOriginalValues[index].Y
})
}
// RotateUVs rotates the UV values around the center of the UV values for the mesh in radians
func (vs VertexSelection) RotateUVs(rotation float64) {
center := Vector{}
vs.ForEachIndex(func(mesh *Mesh, index int) {
center = center.Add(mesh.VertexUVs[index])
})
center = center.Divide(float64(vs.Count()))
vs.ForEachIndex(func(mesh *Mesh, index int) {
diff := mesh.VertexUVs[index].Sub(center)
mesh.VertexUVs[index] = center.Add(diff.Rotate(0, 0, 1, rotation))
})
}
// SetActiveColorChannel sets the active color channel in all vertices contained within the VertexSelection to the channel with the
// specified index.
// If the channelIndex provided is greater than the number of vertex color channels in the Mesh minus one, vertex color channels will be created for all vertices
// up to the index provided (e.g. VertexSelection.SetActiveColorChannel(3) will make it so that the mesh has at least four color channels - 0, 1, 2, and 3).
func (vs VertexSelection) SetActiveColorChannel(channelIndex int) {
for mesh := range vs.SelectionSet {
mesh.ensureEnoughVertexColorChannels(channelIndex)
vs.ForEachIndex(func(mesh *Mesh, i int) {
mesh.VertexActiveColorChannel[i] = channelIndex
})
}
}
// ApplyMatrix applies a Matrix4 to the position of all vertices contained within the VertexSelection.
func (vs VertexSelection) ApplyMatrix(matrix Matrix4) {
vs.ForEachIndex(func(mesh *Mesh, index int) {
mesh.VertexPositions[index] = matrix.MultVec(mesh.VertexPositions[index])
})
}
// Move moves all vertices contained within the VertexSelection by the provided x, y, and z values.
func (vs VertexSelection) Move(x, y, z float64) {
vs.ForEachIndex(func(mesh *Mesh, index int) {
mesh.VertexPositions[index].X += x
mesh.VertexPositions[index].Y += y
mesh.VertexPositions[index].Z += z
})
}
// Move moves all vertices contained within the VertexSelection by the provided 3D vector.
func (vs VertexSelection) MoveVec(vec Vector) {
vs.ForEachIndex(func(mesh *Mesh, index int) {
mesh.VertexPositions[index].X += vec.X
mesh.VertexPositions[index].Y += vec.Y
mesh.VertexPositions[index].Z += vec.Z
})
}
// ForEachIndex calls the provided function for each index selected in the VertexSelection.
func (vs VertexSelection) ForEachIndex(forEach func(mesh *Mesh, index int)) {
for mesh, set := range vs.SelectionSet {
if set.SelectAll {
for index := range mesh.VertexPositions {
forEach(mesh, index)
}
} else {
for index := range set.Indices {
forEach(mesh, index)
}
}
}
}
// Count returns the number of indices selected in the VertexSelection.
func (vs VertexSelection) Count() int {
count := 0
for _, set := range vs.SelectionSet {
count += len(set.Indices)
}
return count
}
// NewCubeMesh creates a new 2x2x2 Cube Mesh and gives it a new material (suitably named "Cube").
func NewCubeMesh() *Mesh {
mesh := NewMesh("Cube",
// Top
NewVertex(-1, 1, -1, 0, 0),
NewVertex(1, 1, 1, 1, 1),
NewVertex(1, 1, -1, 1, 0),
NewVertex(-1, 1, 1, 0, 1),
// Bottom
NewVertex(1, -1, -1, 1, 0),
NewVertex(1, -1, 1, 1, 1),
NewVertex(-1, -1, -1, 0, 0),
NewVertex(-1, -1, 1, 0, 1),
// Front
NewVertex(-1, 1, 1, 0, 0),
NewVertex(1, -1, 1, 1, 1),
NewVertex(1, 1, 1, 1, 0),
NewVertex(-1, -1, 1, 0, 1),
// Back
NewVertex(1, 1, -1, 1, 0),
NewVertex(1, -1, -1, 1, 1),
NewVertex(-1, 1, -1, 0, 0),
NewVertex(-1, -1, -1, 0, 1),
// Right
NewVertex(1, 1, -1, 1, 0),
NewVertex(1, 1, 1, 1, 1),
NewVertex(1, -1, -1, 0, 0),
NewVertex(1, -1, 1, 0, 1),
// Left