-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathVisualModel.cppm
More file actions
3880 lines (3427 loc) · 181 KB
/
Copy pathVisualModel.cppm
File metadata and controls
3880 lines (3427 loc) · 181 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
/*!
* \file
*
* Declares a VisualModel base class to hold the vertices that make up some individual model object
* that can be part of an OpenGL scene.
*
* GL function calls are added in VisualModel.h
*
* \author Seb James
* \date March 2025
*/
module;
#if defined __gl3_h_ || defined __gl_h_
// GL headers have been externally included
#else
# include <mplot/glad/gl.h>
#endif
#include <cstdint>
#include <type_traits>
#include <iostream>
#include <vector>
#include <array>
#include <algorithm>
#include <iterator>
#include <string>
#include <memory>
#include <functional>
#include <cstddef>
#include <cmath>
#include <bitset>
#include <map>
#include <set>
#include <tuple>
export module mplot.visualmodel;
export import sm.mathconst;
import sm.geometry;
import sm.geometry_polyhedra;
export import sm.quaternion;
export import sm.mat;
export import sm.vec;
export import sm.vvec;
export import sm.interval;
import sm.algo;
import sm.flags;
import sm.base64;
// Need to import common here
export import mplot.gl.version;
export import mplot.visualcommon;
export import mplot.visualresources;
export import mplot.visualtextmodel;
export import mplot.colour;
import mplot.gl.util;
import mplot.tools;
export import :navmesh;
export namespace mplot
{
union float_bytes // for gltf output
{
float f;
std::uint8_t bytes[sizeof(float)];
};
/*!
* An OpenGL model class
*
* This class is the 'OpenGL model' class. It has the common code to create the vertices for
* some individual OpenGL model which is to be rendered in a 3-D scene.
*
* Some OpenGL models are derived directly from VisualModel; see for example mplot::CoordArrows.
*
* Other models in mathplot are derived via mplot::VisualDataModel, which adds a common
* mechanism for managing the data which is to be visualised by the final 'Visual' object (such
* as mplot::HexGridVisual or mplot::ScatterVisual)
*
* This class contains some common 'object primitives' code, such as computeSphere and
* computeCone, which compute the vertices that will make up sphere and cone, respectively.
*/
template <std::int32_t glver = mplot::gl::version_4_1>
struct VisualModel
{
VisualModel() {}
VisualModel (const sm::vec<float> _offset) { this->viewmatrix.translate (_offset); }
//! destroy gl buffers in the deconstructor
virtual ~VisualModel() // clang gives -Wdelete-non-abstract-non-virtual-dtor without virtual
{
// Explicitly clear owned VisualTextModels
this->texts.clear();
if (this->vbos != nullptr) {
GladGLContext* glfn = mplot::VisualResources<glver>::i().get_glfn (this->parentVis);
if (glfn) {
glfn->DeleteBuffers (this->numVBO, this->vbos.get());
glfn->DeleteVertexArrays (1, &this->vao);
}
}
}
//! Common code to call after the vertices have been set up. GL has to have been initialised.
void postVertexInit()
{
if (this->parentVis == std::numeric_limits<std::uint32_t>::max()) {
throw std::runtime_error ("parentVis is unset");
}
GladGLContext* glfn = mplot::VisualResources<glver>::i().get_glfn (this->parentVis);
// Do gl memory allocation of vertex array once only
if (this->vbos == nullptr) {
// Create vertex array object
glfn->GenVertexArrays (1, &this->vao); // Safe for OpenGL 4.4-
}
glfn->BindVertexArray (this->vao);
// Create the vertex buffer objects (once only)
if (this->vbos == nullptr) {
this->vbos = std::make_unique<std::uint32_t[]>(this->numVBO);
glfn->GenBuffers (this->numVBO, this->vbos.get()); // OpenGL 4.4- safe
}
// Set up the indices buffer - bind and buffer the data in this->indices
glfn->BindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->vbos[this->idxVBO]);
std::size_t sz = this->indices.size() * sizeof(std::uint32_t);
glfn->BufferData (GL_ELEMENT_ARRAY_BUFFER, sz, this->indices.data(), GL_STATIC_DRAW);
// Binds data from the "C++ world" to the OpenGL shader world for
// "position", "normalin" and "color"
// (bind, buffer and set vertex array object attribute)
this->setupVBO (this->vbos[this->posnVBO], this->vertexPositions, visgl::posnLoc);
this->setupVBO (this->vbos[this->normVBO], this->vertexNormals, visgl::normLoc);
this->setupVBO (this->vbos[this->colVBO], this->vertexColors, visgl::colLoc);
// Unbind only the vertex array (not the buffers, that causes GL_INVALID_ENUM errors)
glfn->BindVertexArray(0); // carefully unbind and rebind
mplot::gl::Util::checkError (__FILE__, __LINE__, glfn);
if (this->flags.test (vm_bools::instanced)) {
// Here, we cause the SSBOs to be intialized if they haven't already, and we reserve
// some space in the SSBOs for *this model*
this->instance_start = mplot::VisualResources<glver>::i().init_instance_ssbo (this->parentVis, this->max_instances);
if (this->instance_start == std::numeric_limits<std::uint32_t>::max()) {
throw std::runtime_error ("Failed to reserve space in SSBO");
}
}
/*
* Now do the same for the bounding box
*/
if (this->flags.test (vm_bools::compute_bb)) {
if (this->vbos_bb == nullptr) { glfn->GenVertexArrays (1, &this->vao_bb); }
glfn->BindVertexArray (this->vao_bb);
// Create the vertex buffer objects (once only)
if (this->vbos_bb == nullptr) {
this->vbos_bb = std::make_unique<std::uint32_t[]>(this->numVBO);
glfn->GenBuffers (this->numVBO, this->vbos_bb.get());
}
// Set up the indices buffer - bind and buffer the data in this->indices
glfn->BindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->vbos_bb[this->idxVBO]);
std::size_t sz = this->indices_bb.size() * sizeof(std::uint32_t);
glfn->BufferData (GL_ELEMENT_ARRAY_BUFFER, sz, this->indices_bb.data(), GL_STATIC_DRAW);
// Binds data from the "C++ world" to the OpenGL shader world for
// "position", "normalin" and "color"
// (bind, buffer and set vertex array object attribute)
this->setupVBO (this->vbos_bb[this->posnVBO], this->vpos_bb, visgl::posnLoc);
this->setupVBO (this->vbos_bb[this->normVBO], this->vnorm_bb, visgl::normLoc);
this->setupVBO (this->vbos_bb[this->colVBO], this->vcol_bb, visgl::colLoc);
// Unbind only the vertex array (not the buffers, that causes GL_INVALID_ENUM errors)
glfn->BindVertexArray(0); // carefully unbind and rebind
mplot::gl::Util::checkError (__FILE__, __LINE__, glfn);
}
this->flags.set (vm_bools::postVertexInitRequired, false);
}
//! Initialize vertex buffer objects and vertex array object. Empty for 'text only' VisualModels.
virtual void initializeVertices() {};
/*!
* Helper to make a VisualTextModel and bind it ready for use.
*
* You could write it out explicitly as:
*
* std::unique_ptr<mplot::VisualTextModel<glver>> vtm1 = this->makeVisualTextModel (tfca);
*
* Or use auto to help:
*
* auto vtm1 = this->makeVisualTextModel (tfca);
*
* See GraphVisual.h for examples.
*/
std::unique_ptr<mplot::VisualTextModel<glver>> makeVisualTextModel(const mplot::TextFeatures& tfeatures)
{
// No longer really worth having, as there is only the make_unique call
auto tmup = std::make_unique<mplot::VisualTextModel<glver>> (tfeatures);
tmup->set_parent (this->parentVis);
return tmup;
}
/*!
* Add a text label to the model at location (within the model coordinates)
* toffset. Return the text geometry of the added label so caller can place
* associated text correctly. Control font size, resolution, colour and font
* face with tfeatures.
*/
mplot::TextGeometry addLabel (const std::string& _text,
const sm::vec<float, 3>& _toffset,
const mplot::TextFeatures& tfeatures = mplot::TextFeatures())
{
if (mplot::VisualResources<glver>::i().get_tprog (this->parentVis) == 0) {
throw std::runtime_error ("No text shader prog. Did your VisualModel-derived class set it up?");
}
mplot::VisualResources<glver>::i().setContext (this->parentVis); // For VisualTextModel
auto tmup = this->makeVisualTextModel (tfeatures);
if (tfeatures.centre_horz == true) {
mplot::TextGeometry tg = tmup->getTextGeometry(_text);
sm::vec<float, 3> centred_locn = _toffset;
centred_locn[0] -= tg.half_width();
tmup->setupText (_text, centred_locn + this->viewmatrix.translation(), tfeatures.colour);
} else {
tmup->setupText (_text, _toffset + this->viewmatrix.translation(), tfeatures.colour);
}
this->texts.push_back (std::move(tmup));
// As this is a setup function, release the context
mplot::VisualResources<glver>::i().releaseContext();
return this->texts.back()->getTextGeometry();
}
/*!
* Add a text label, with given offset _toffset and the specified tfeatures. The
* reference to a pointer, tm, allows client code to change the text of the
* VisualTextModel as necessary, after the label has been added.
*/
mplot::TextGeometry addLabel (const std::string& _text,
const sm::vec<float, 3>& _toffset,
mplot::VisualTextModel<glver>*& tm,
const mplot::TextFeatures& tfeatures = mplot::TextFeatures())
{
if (mplot::VisualResources<glver>::i().get_tprog (this->parentVis) == 0) {
throw std::runtime_error ("No text shader prog. Did your VisualModel-derived class set it up?");
}
mplot::VisualResources<glver>::i().setContext (this->parentVis); // For VisualTextModel
auto tmup = this->makeVisualTextModel (tfeatures);
if (tfeatures.centre_horz == true) {
mplot::TextGeometry tg = tmup->getTextGeometry(_text);
sm::vec<float, 3> centred_locn = _toffset;
centred_locn[0] -= tg.half_width();
tmup->setupText (_text, centred_locn + this->viewmatrix.translation(), tfeatures.colour);
} else {
tmup->setupText (_text, _toffset + this->viewmatrix.translation(), tfeatures.colour);
}
this->texts.push_back (std::move(tmup));
tm = this->texts.back().get();
// As this is a setup function, release the context
mplot::VisualResources<glver>::i().releaseContext();
return this->texts.back()->getTextGeometry();
}
void setSceneMatrixTexts (const sm::mat<float, 4>& sv)
{
auto ti = this->texts.begin();
while (ti != this->texts.end()) { (*ti)->setSceneMatrix (sv); ti++; }
}
void setSceneTranslationTexts (const sm::vec<float>& v0)
{
auto ti = this->texts.begin();
while (ti != this->texts.end()) { (*ti)->setSceneTranslation (v0); ti++; }
}
void setViewRotationTexts (const sm::quaternion<float>& r)
{
// When rotating a model that contains texts, we need to rotate the scene
// for the texts and also inverse-rotate the view of the texts.
auto ti = this->texts.begin();
while (ti != this->texts.end()) {
// Rotate the scene. Note this won't work if the VisualModel has a
// translation away from the origin.
(*ti)->setSceneRotation (r); // Need this to rotate about _offset. BUT the
// translation is already there in the text,
// but in the MODEL view.
// Rotate the view of the text an opposite amount, to keep it facing forwards
(*ti)->setViewRotation (r.invert());
ti++;
}
}
void addViewRotationTexts (const sm::quaternion<float>& r)
{
auto ti = this->texts.begin();
while (ti != this->texts.end()) { (*ti)->addViewRotation (r); ti++; }
}
//! Process vertices and find the bounding box
void update_bb()
{
if (this->flags.test (vm_bools::compute_bb) == false) { return; }
if (this->vertexPositions.size() % 3 != 0) {
throw std::runtime_error ("VisualModelBase: vertexPositions size is not divisible by 3");
}
this->bb.search_init();
for (std::size_t i = 0; i < this->vertexPositions.size(); i += 3) {
this->bb.update (sm::vec<float>{ vertexPositions[i], vertexPositions[i+1], vertexPositions[i+2] });
}
// Construct the half-extent axis vectors, too.
const sm::vec<float> bb_ext = this->bb.span() / 2.0f;
this->bb_x = { bb_ext[0], 0, 0 }; // i.e. bb_ext[0] * sm::vec<>::ux();
this->bb_y = { 0, bb_ext[1], 0 };
this->bb_z = { 0, 0, bb_ext[2] };
// After finding the bounding box, make up the vertices to display it:
this->computeBoundingBox();
}
/*!
* Re-initialize the buffers. Client code might have appended to
* vertexPositions/Colors/Normals and indices before calling this method.
*/
void reinit_buffers()
{
GladGLContext* glfn = mplot::VisualResources<glver>::i().get_glfn (this->parentVis);
mplot::VisualResources<glver>::i().setContext (this->parentVis);
if (this->flags.test (vm_bools::postVertexInitRequired) == true) { this->postVertexInit(); }
// Now re-set up the VBOs
glfn->BindVertexArray (this->vao); // carefully unbind and rebind
glfn->BindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->vbos[this->idxVBO]); // carefully unbind and rebind
std::size_t sz = this->indices.size() * sizeof(std::uint32_t);
glfn->BufferData (GL_ELEMENT_ARRAY_BUFFER, sz, this->indices.data(), GL_STATIC_DRAW);
this->setupVBO (this->vbos[this->posnVBO], this->vertexPositions, visgl::posnLoc);
this->setupVBO (this->vbos[this->normVBO], this->vertexNormals, visgl::normLoc);
this->setupVBO (this->vbos[this->colVBO], this->vertexColors, visgl::colLoc);
glfn->BindVertexArray(0); // carefully unbind and rebind
mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); // carefully unbind and rebind
// Optional bounding box
if (this->flags.test (vm_bools::compute_bb)) {
glfn->BindVertexArray (this->vao_bb);
glfn->BindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->vbos_bb[this->idxVBO]);
std::size_t sz = this->indices_bb.size() * sizeof(std::uint32_t);
glfn->BufferData (GL_ELEMENT_ARRAY_BUFFER, sz, this->indices_bb.data(), GL_STATIC_DRAW);
this->setupVBO (this->vbos_bb[this->posnVBO], this->vpos_bb, visgl::posnLoc);
this->setupVBO (this->vbos_bb[this->normVBO], this->vnorm_bb, visgl::normLoc);
this->setupVBO (this->vbos_bb[this->colVBO], this->vcol_bb, visgl::colLoc);
glfn->BindVertexArray(0);
mplot::gl::Util::checkError (__FILE__, __LINE__, glfn);
}
}
//! reinit ONLY vertexColors buffer
void reinit_colour_buffer()
{
mplot::VisualResources<glver>::i().setContext (this->parentVis);
if (this->flags.test (vm_bools::postVertexInitRequired) == true) { this->postVertexInit(); }
GladGLContext* glfn = mplot::VisualResources<glver>::i().get_glfn (this->parentVis);
// Now re-set up the VBOs
glfn->BindVertexArray (this->vao); // carefully unbind and rebind
this->setupVBO (this->vbos[this->colVBO], this->vertexColors, visgl::colLoc);
glfn->BindVertexArray(0); // carefully unbind and rebind
mplot::gl::Util::checkError (__FILE__, __LINE__, glfn);
}
void clearTexts() { this->texts.clear(); }
//! Clear out the model, *including text models*
void clear()
{
this->vertexPositions.clear();
this->vertexNormals.clear();
this->vertexColors.clear();
this->indices.clear();
this->clearTexts();
this->idx = 0u;
// Clear bounding box
this->vpos_bb.clear();
this->vnorm_bb.clear();
this->vcol_bb.clear();
this->indices_bb.clear();
this->idx_bb = 0u;
this->reinit_buffers();
}
//! Re-create the model - called after updating data
void reinit()
{
mplot::VisualResources<glver>::i().setContext (this->parentVis);
// Fixme: Better not to clear, then repeatedly pushback here:
this->vertexPositions.clear();
this->vertexNormals.clear();
this->vertexColors.clear();
this->indices.clear();
// Clear any bounding box too
this->vpos_bb.clear();
this->vnorm_bb.clear();
this->vcol_bb.clear();
this->indices_bb.clear();
this->idx_bb = 0u;
// NB: Do NOT call clearTexts() here! We're only updating the model itself.
this->idx = 0u;
this->initializeVertices();
// Add additional meshgroups
for (auto mg : this->extra_meshgroups) { this->computeMeshgroup (mg); }
this->update_bb();
this->reinit_buffers();
}
/*!
* For some models it's important to clear the texts when reinitialising. This is NOT the
* same as VisualModel::clear() followed by initializeVertices(). For the same effect, you
* can call clearTexts() then reinit().
*/
void reinit_with_clearTexts()
{
mplot::VisualResources<glver>::i().setContext (this->parentVis);
this->vertexPositions.clear();
this->vertexNormals.clear();
this->vertexColors.clear();
this->indices.clear();
this->clearTexts();
this->idx = 0u;
// Clear any bounding box too
this->vpos_bb.clear();
this->vnorm_bb.clear();
this->vcol_bb.clear();
this->indices_bb.clear();
this->idx_bb = 0u;
this->initializeVertices();
for (auto mg : this->extra_meshgroups) { this->computeMeshgroup (mg); }
this->update_bb();
this->reinit_buffers();
}
void reserve_vertices (std::size_t n_vertices)
{
this->vertexPositions.reserve (3u * n_vertices);
this->vertexNormals.reserve (3u * n_vertices);
this->vertexColors.reserve (3u * n_vertices);
this->indices.reserve (6u * n_vertices);
}
// Make a hash of vertexPositions, etc as an identifier for this model. The hash identifies
// the model's mesh geometry for NavMesh and so the vertexColors are not important.
std::size_t hash() const
{
std::size_t h = 17;
for (std::size_t i = 0u; i < this->vertexPositions.size(); ++i) {
h = (h << 5) - 1 + std::hash<float>{}(this->vertexPositions[i]);
}
for (std::size_t i = 0u; i < this->vertexNormals.size(); ++i) {
h = (h << 5) - 1 + std::hash<float>{}(this->vertexNormals[i]);
}
for (std::size_t i = 0u; i < this->indices.size(); ++i) {
h = (h << 5) - 1 + std::hash<std::uint32_t>{}(this->indices[i]);
}
return h;
}
// Get a single position from vertexPositions, using the index into the vector<vec>
// interpretation of vertexPositions
sm::vec<float, 3> get_position (const std::uint32_t vec_idx) const
{
auto vp = reinterpret_cast<const std::vector<sm::vec<float, 3>>*>(&this->vertexPositions);
return (*vp)[vec_idx];
}
// Get a single normal from vertexNormals, using the index into the vector<vec>
// interpretation of vertexNormals
sm::vec<float, 3> get_normal (const std::uint32_t vec_idx) const
{
auto vn = reinterpret_cast<const std::vector<sm::vec<float, 3>>*>(&this->vertexNormals);
return (*vn)[vec_idx];
}
// Get the area of the triangle whose start index is vec_idx
float get_area (const std::uint32_t vec_idx0, const std::uint32_t vec_idx1, const std::uint32_t vec_idx2) const
{
auto vp = reinterpret_cast<const std::vector<sm::vec<float, 3>>*>(&this->vertexPositions);
auto t0 = (*vp)[vec_idx0];
auto t1 = (*vp)[vec_idx1];
auto t2 = (*vp)[vec_idx2];
return sm::geometry::tri_area (t0, t1, t2);
}
/**
* Neighbour vertex mesh code.
*/
// Our navigation mesh data struct
std::unique_ptr<mplot::NavMesh> navmesh;
void build_navmesh()
{
constexpr bool debug_mn = false;
if constexpr (debug_mn) { std::cout << __func__ << " called" << std::endl; }
if (!this->navmesh) { return; }
// Copy the bounding box
navmesh->bb = this->bb;
// Treat vertexPositions as a vector of vec:
auto vp = reinterpret_cast<const std::vector<sm::vec<float, 3>>*>(&this->vertexPositions);
std::uint32_t vps = vp->size();
std::unordered_map<sm::vec<float, 3>, std::set<std::uint32_t>, sm::vec<float, 3>::hash> equiv_v;
std::uint32_t i = 0;
for (auto p : *vp) { equiv_v[p].insert (i++); }
std::map<std::uint32_t, std::set<std::uint32_t>> equiv;
for (auto e : equiv_v) { equiv[*e.second.begin()] = e.second; }
if constexpr (debug_mn) {
for (auto e : equiv) {
std::cout << "build_navmesh: equiv[" << e.first << "] = ";
for (auto idx : e.second) { std::cout << idx << ","; }
std::cout << std::endl;
}
std::cout << "build_navmesh: Populated equiv which has " << equiv.size() << " vvecs" << std::endl;
}
// Make inverse of equiv to translate from original (indices, vertexPositions) index to
// new topographic mesh index
sm::vvec<std::uint32_t> navmesh_idx (vps, 0);
std::uint32_t vcount = 0;
i = 0;
for (auto eqs : equiv) {
vcount += eqs.second.size();
for (auto ev : eqs.second) {
if constexpr (debug_mn) {
std::cout << "build_navmesh: set navmesh_idx[" << ev << "] = " << i << std::endl;
}
navmesh_idx[ev] = i;
}
++i;
}
if constexpr (debug_mn) { std::cout << "build_navmesh: Created equiv inverse" << std::endl; }
if (vcount != vps) {
std::cout << "build_navmesh: WARNING: Vertex count from equiv is " << vcount
<< " which should (but does not) equal " << vps << std::endl;
}
// Can now populate vertex, a vector of coordinates, if required, or simply access (*vp)
// as needed using equiv.first
navmesh->vertex.resize (equiv.size(), mesh::vertex{});
i = 0;
for (auto eq : equiv) {
navmesh->vertex[i++] = { (*vp)[eq.first], std::numeric_limits<std::uint32_t>::max() };
}
// We're turing a triangle mesh into a navmesh. Don't know what to do if there are stray vertices.
if (this->indices.size() % 3u != 0u) {
throw std::runtime_error ("Uh oh, indices size not divisible by 3!!!! Call the cops!");
}
// Lastly, generate edges. For which we require use of indices, which is expressed in
// terms of the old indices. That lookup is navmesh_idx.
for (std::uint32_t i = 0; i < this->indices.size(); i += 3) {
// Add three halfedges for the triangle
const std::uint32_t hesz = navmesh->halfedge.size();
const std::uint32_t he0 = hesz;
const std::uint32_t he1 = hesz + 1;
const std::uint32_t he2 = hesz + 2;
if constexpr (debug_mn) {
std::cout << "setting halfedge["<< he0 << "] to { {"
<< navmesh_idx[indices[i]] << ", " << navmesh_idx[indices[i + 1]]
<< "}, nullptr, " << he1 << ", " << he2 << " }" << std::endl;
std::cout << "setting halfedge[" << he1 << "] to { {"
<< navmesh_idx[indices[i + 1]] << ", " << navmesh_idx[indices[i + 2]]
<< "}, nullptr, " << he2 << ", " << he0 << " }" << std::endl;
std::cout << "setting halfedge[" << he2 << "] to { {"
<< navmesh_idx[indices[i + 2]] << ", " << navmesh_idx[indices[i]]
<< "}, nullptr, " << he0 << ", " << he1 << " }" << std::endl;
}
navmesh->halfedge.resize (hesz + 3, {});
// Now, could also try to identify LINES
navmesh->halfedge[he0] = { {navmesh_idx[indices[i ]], navmesh_idx[indices[i + 1]]}, std::numeric_limits<std::uint32_t>::max(), he1, he2, 0u };
navmesh->halfedge[he1] = { {navmesh_idx[indices[i + 1]], navmesh_idx[indices[i + 2]]}, std::numeric_limits<std::uint32_t>::max(), he2, he0, 0u };
navmesh->halfedge[he2] = { {navmesh_idx[indices[i + 2]], navmesh_idx[indices[i ]]}, std::numeric_limits<std::uint32_t>::max(), he0, he1, 0u };
if constexpr (debug_mn) {
std::cout << "halfedge["<< hesz << "] contains: vi:"
<< navmesh->halfedge[hesz].vi
<< ", twin:" << navmesh->halfedge[hesz].twin
<< ", next:" << navmesh->halfedge[hesz].next
<< ", prev:" << navmesh->halfedge[hesz].prev << std::endl;
}
// A face contains just the first half edge index
mesh::face<> t = { he0 };
// The normal vector for this triangle could be obtained from the mesh normals, but
// we can't trust them (though they're easy to get, as we're dealing with indices
// already). However, use this to ensure that our triangle indices order is in
// agreement with mesh normal as far as direction goes.
sm::vec<float> tn = this->get_normal (indices[i]) + this->get_normal (indices[i + 1]) + this->get_normal (indices[i + 2]) ;
tn.renormalize();
// Compute trinorm as well and compare with the one from the mesh - perhaps it's
// different? We really want the right normal.
const sm::vec<float>& tv0 = navmesh->vertex[navmesh_idx[indices[i]]].p;
const sm::vec<float>& tv1 = navmesh->vertex[navmesh_idx[indices[i + 1]]].p;
const sm::vec<float>& tv2 = navmesh->vertex[navmesh_idx[indices[i + 2]]].p;
sm::vec<float> nx = (tv1 - tv0);
sm::vec<float> ny = (tv2 - tv0);
sm::vec<float> n = nx.cross (ny);
n.renormalize();
// Check rotational sense of triangles
if (n.dot (tn) < 0.0f) {
std::cout << "Swap order of triangle with he " << he0 << std::endl;
// Swap first and last half edge
navmesh->halfedge[he0].vi.rotate();
navmesh->halfedge[he1].vi.rotate();
navmesh->halfedge[he2].vi.rotate();
}
navmesh->triangles.push_back (t);
}
if constexpr (debug_mn) {
std::cout << "build_navmesh: Created triangles (" << navmesh->halfedge.size() << " halfedges)" << std::endl;
}
navmesh->compute_neighbour_relations(); // finds the halfedge twins
}
/*!
* Post-process vertices to generate a neighbour relationship mesh suitable for navigation.
*
* \param navmesh_dir The directory into which to store/read the navmesh data file.
*/
void make_navmesh (std::string navmesh_dir = "")
{
if (this->navmesh) { return; } // already made it
if (this->flags.test (vm_bools::compute_bb) == false) {
throw std::runtime_error ("make_navmesh requires compute_bb flag to be true");
}
this->update_bb();
// Create a new navmesh
this->navmesh = std::make_unique<mplot::NavMesh>();
// Have we got a pre-computed navmesh file for the halfedge twin relationships?
std::uint64_t h = this->hash();
if (navmesh_dir.empty()) {
navmesh_dir = mplot::tools::getTmpPath();
} else {
if (navmesh_dir.back() != '/') { navmesh_dir += "/"; }
}
std::string filename = navmesh_dir + std::string("navmesh_") + std::to_string (h);
std::string filename_pre_boundary = filename + ".pre";
constexpr bool just_mark = true;
if (mplot::tools::fileExists (filename)) {
this->navmesh->load (filename);
std::cout << "Full test...\n";
this->navmesh->test();
} else if (mplot::tools::fileExists (filename_pre_boundary)) {
std::cout << "Pre-boundary navmesh\n";
this->navmesh->load (filename_pre_boundary);
this->navmesh->add_boundary_halfedges();
this->navmesh->test (just_mark);
this->navmesh->save (filename);
} else {
std::cout << "Building NavMesh to save into file " << filename << std::endl;
this->build_navmesh();
this->navmesh->save (filename_pre_boundary);
this->navmesh->add_boundary_halfedges();
this->navmesh->test (just_mark);
this->navmesh->save (filename);
}
}
/**
* End neighbour vertex mesh code
*/
/*!
* A function to call initialiseVertices and postVertexInit after any necessary attributes
* have been set (see, for example, setting the colour maps up in VisualDataModel).
*/
void finalize()
{
mplot::VisualResources<glver>::i().setContext (this->parentVis); // need context? yes for text.
this->initializeVertices();
for (auto mg : this->extra_meshgroups) { this->computeMeshgroup (mg); }
this->update_bb();
this->flags.set (vm_bools::postVertexInitRequired, true);
// Release context after creating and finalizing this VisualModel. On Visual::render(),
// context will be re-acquired.
mplot::VisualResources<glver>::i().releaseContext();
}
static constexpr bool debug_render = false;
//! Render the VisualModel. Note that it is assumed that the OpenGL context has been
//! obtained by the parent Visual::render call.
virtual void render() // not final
{
if (this->hidden() == true) { return; }
// Execute post-vertex init at render, as GL should be available.
if (this->flags.test (vm_bools::postVertexInitRequired) == true) { this->postVertexInit(); }
std::int32_t prev_shader = 0;
GladGLContext* glfn = mplot::VisualResources<glver>::i().get_glfn (this->parentVis);
glfn->GetIntegerv (GL_CURRENT_PROGRAM, &prev_shader);
// Ensure the correct program is in play for this VisualModel
std::uint32_t gprog = mplot::VisualResources<glver>::i().get_gprog (this->parentVis);
glfn->UseProgram (gprog);
if (!this->indices.empty()) {
// glPolygonMode is OpenGL only and not supported on GL ES
if constexpr (mplot::gl::version::gles (glver) == false) {
// Enable/disable wireframe mode per-model on each render call
if (this->flags.test (vm_bools::wireframe)) {
glfn->PolygonMode (GL_FRONT_AND_BACK, GL_LINE);
} else {
glfn->PolygonMode (GL_FRONT_AND_BACK, GL_FILL);
}
}
// It is only necessary to bind the vertex array object before rendering
// (not the vertex buffer objects)
glfn->BindVertexArray (this->vao);
// Pass this->float to GLSL so the model can have an alpha value.
std::int32_t loc_a = glfn->GetUniformLocation (gprog, static_cast<const char*>("alpha"));
if (loc_a != -1) { glfn->Uniform1f (loc_a, this->alpha); }
std::int32_t loc_gr = glfn->GetUniformLocation (gprog, static_cast<const char*>("greyscale"));
if (loc_gr != -1) { glfn->Uniform1i (loc_gr, (this->flags.test (vm_bools::greyscale) ? 1 : 0)); }
std::int32_t loc_gam = glfn->GetUniformLocation (gprog, static_cast<const char*>("gamma"));
if (loc_gam != -1) { glfn->Uniform1f (loc_gam, this->gamma); }
// The scene-view matrix
std::int32_t loc_v = glfn->GetUniformLocation (gprog, static_cast<const char*>("v_matrix"));
if (loc_v != -1) { glfn->UniformMatrix4fv (loc_v, 1, GL_FALSE, this->scenematrix.arr.data()); }
// the model-view matrix
std::int32_t loc_m = glfn->GetUniformLocation (gprog, static_cast<const char*>("m_matrix"));
if (loc_m != -1) { glfn->UniformMatrix4fv (loc_m, 1, GL_FALSE, this->viewmatrix.arr.data()); }
// the instance scaling matrix (applied to all instances)
std::int32_t loc_s = glfn->GetUniformLocation (gprog, static_cast<const char*>("s_matrix"));
if (loc_s != -1) { glfn->UniformMatrix4fv (loc_s, 1, GL_FALSE, this->instscale.arr.data()); }
if constexpr (debug_render) {
std::cout << "VisualModel::render: scenematrix:\n" << this->scenematrix << std::endl;
std::cout << "VisualModel::render: model viewmatrix:\n" << this->viewmatrix << std::endl;
}
// Draw the triangles
std::int32_t loc_is = glfn->GetUniformLocation (gprog, static_cast<const char*>("instance_start"));
std::int32_t loc_ic = glfn->GetUniformLocation (gprog, static_cast<const char*>("instance_count"));
std::int32_t loc_ipc = glfn->GetUniformLocation (gprog, static_cast<const char*>("instparam_count"));
if (this->flags.test (vm_bools::instanced)) {
if (loc_is != -1) { glfn->Uniform1i (loc_is, this->instance_start); }
if (loc_ic != -1) { glfn->Uniform1i (loc_ic, this->instance_count); }
if (loc_ipc != -1) { glfn->Uniform1i (loc_ipc, this->instparam_count); }
glfn->DrawElementsInstanced (GL_TRIANGLES, static_cast<std::uint32_t>(this->indices.size()), GL_UNSIGNED_INT, 0, this->instance_count);
} else {
if (loc_is != -1) { glfn->Uniform1i (loc_is, -1); }
if (loc_ic != -1) { glfn->Uniform1i (loc_ic, -1); }
glfn->DrawElements (GL_TRIANGLES, static_cast<std::uint32_t>(this->indices.size()), GL_UNSIGNED_INT, 0);
}
// Unbind the VAO
glfn->BindVertexArray(0);
// Do the bounding box optionally
if (this->flags.test (vm_bools::compute_bb) && this->flags.test (vm_bools::show_bb) && !this->indices_bb.empty()) {
glfn->BindVertexArray (this->vao_bb);
glfn->DrawElements (GL_TRIANGLES, static_cast<std::uint32_t>(this->indices_bb.size()), GL_UNSIGNED_INT, 0);
glfn->BindVertexArray(0);
}
}
mplot::gl::Util::checkError (__FILE__, __LINE__, glfn);
// Now render any VisualTextModels
if constexpr (mplot::gl::version::gles (glver) == false) {
glfn->PolygonMode (GL_FRONT_AND_BACK, GL_FILL);
}
auto ti = this->texts.begin();
while (ti != this->texts.end()) { (*ti)->render(); ti++; }
glfn->UseProgram (prev_shader);
mplot::gl::Util::checkError (__FILE__, __LINE__, glfn);
}
//! Setter for the viewmatrix
void setViewMatrix (const sm::mat<float, 4>& mv) { this->viewmatrix = mv; }
//! And a getter
sm::mat<float, 4> getViewMatrix() const { return this->viewmatrix; }
//! Pre or post-multiply
void postmultViewMatrix (const sm::mat<float, 4>& m) { this->viewmatrix = this->viewmatrix * m; }
void premultViewMatrix (const sm::mat<float, 4>& m) { this->viewmatrix = m * this->viewmatrix; }
void scaleViewMatrix (const float by) { this->viewmatrix.scale (by); }
//! When setting the scene matrix, also have to set the text's scene matrices.
void setSceneMatrix (const sm::mat<float, 4>& sv)
{
this->scenematrix = sv;
this->setSceneMatrixTexts (sv);
}
//! Set a translation into the scene and into any child texts
template <std::size_t N = 3> requires (N == 3) || (N == 4)
void setSceneTranslation (const sm::vec<float, N>& v0)
{
this->scenematrix.set_identity();
this->scenematrix.translate (v0);
if constexpr (N == 4) {
this->setSceneTranslationTexts (v0.less_one_dim());
} else {
this->setSceneTranslationTexts (v0);
}
}
//! Set a translation (only) into the scene view matrix
template <std::size_t N = 3> requires (N == 3) || (N == 4)
void addSceneTranslation (const sm::vec<float, N>& v0) { this->scenematrix.pretranslate (v0); }
//! Set a rotation (only) into the scene view matrix
void setSceneRotation (const sm::quaternion<float>& r)
{
this->scenematrix.set_identity();
this->scenematrix.rotate (r);
}
//! Add a rotation to the scene view matrix
void addSceneRotation (const sm::quaternion<float>& r) { this->scenematrix.rotate (r); }
//! Set a translation to the model view matrix
template <std::size_t N = 3> requires (N == 3) || (N == 4)
void setViewTranslation (const sm::vec<float, N>& v0)
{
this->viewmatrix.set_identity();
this->viewmatrix.translate (v0);
}
//! Add a translation to the model view matrix
template <std::size_t N = 3> requires (N == 3) || (N == 4)
void addViewTranslation (const sm::vec<float, N>& v0) { this->viewmatrix.pretranslate (v0); }
//! Set a rotation (only) into the view, but keep texts fixed
void setViewRotationFixTexts (const sm::quaternion<float>& r)
{
sm::vec<> os = this->viewmatrix.translation();
this->viewmatrix.set_identity();
this->viewmatrix.translate (os);
this->viewmatrix.rotate (r);
}
//! Set a rotation (only) into the view
void setViewRotation (const sm::quaternion<float>& r)
{
sm::vec<> os = this->viewmatrix.translation();
this->viewmatrix.set_identity();
this->viewmatrix.translate (os);
this->viewmatrix.rotate (r);
this->setViewRotationTexts (r);
}
//! Apply a further rotation to the model view matrix
void addViewRotation (const sm::quaternion<float>& r)
{
this->viewmatrix.rotate (r);
this->addViewRotationTexts (r);
}
//! Apply a further rotation to the model view matrix, but keep texts fixed
void addViewRotationFixTexts (const sm::quaternion<float>& r)
{
this->viewmatrix.rotate (r);
}
// The alpha attribute accessors
void setAlpha (const float _a) { this->alpha = _a; }
float getAlpha() const { return this->alpha; }
void incAlpha()
{
this->alpha += 0.1f;
this->alpha = this->alpha > 1.0f ? 1.0f : this->alpha;
}
void decAlpha()
{
this->alpha -= 0.1f;
this->alpha = this->alpha < 0.0f ? 0.0f : this->alpha;
}
void setGamma (const float _g) { this->gamma = _g; }
float getGamma () const { return this->gamma; }
// The hide attribute accessors
void setHide (const bool _h = true) { this->flags.set (vm_bools::hide, _h); }
void toggleHide() { this->flags.flip (vm_bools::hide); }
bool hidden() const { return this->flags.test (vm_bools::hide); }
/*
* Methods used by Visual::savegltf()
*/
//! Get model translation in a json-friendly string
std::string translation_str() { return this->viewmatrix.translation().str_mat(); }
//! A getter for the viewmatrix translation of the origin (would be same as viewmatrix.translation)
sm::vec<float> get_viewmatrix_origin() const
{
return (this->viewmatrix * sm::vec<float, 3>{0,0,0}).less_one_dim();
}
//! The centre of mass of the bounding box may not be the VisualModel's origin
sm::vec<float> get_viewmatrix_bb_centre() const
{
return (this->viewmatrix * this->bb.mid()).less_one_dim();
}
//! Apply the viewmatrix to the model's bounding box and return it. You probably don't want
//! this, instead, get_viewmatrix_obb gets the oriented bounding box, and with that you can
//! collision detect with the separarating axis theorem.
sm::interval<sm::vec<float>> get_viewmatrix_modelbb() const
{
sm::interval<sm::vec<float>> vmbb;
vmbb.min = (this->viewmatrix * this->bb.min).less_one_dim();
vmbb.max = (this->viewmatrix * this->bb.max).less_one_dim();
return vmbb;
}
/*!
* Returns a 3x4 matrix whose columns are the vectors obb_centre, obb_x, obb_y and obb_z
* (the half-extent vectors) for the axis aligned bounding box *after* it has been
* transformed (oriented) with the passed in @_viewmatrix.
*
* The returned mat can be passed to Visual::collision_detect(obb1, obb2)
*/
sm::mat<float, 3, 4> get_viewmatrix_obb (const sm::mat<float, 4>& _viewmatrix) const
{
const sm::vec<float> bb_centre = this->bb.mid();
const sm::vec<float> obb_x_end = (_viewmatrix * (bb_centre + this->bb_x)).less_one_dim();
const sm::vec<float> obb_y_end = (_viewmatrix * (bb_centre + this->bb_y)).less_one_dim();
const sm::vec<float> obb_z_end = (_viewmatrix * (bb_centre + this->bb_z)).less_one_dim();
const sm::vec<float> obb_centre = (_viewmatrix * bb_centre).less_one_dim();
sm::mat<float, 3, 4> obb;
obb.set_col (0, obb_centre);
obb.set_col (1, obb_x_end - obb_centre);
obb.set_col (2, obb_y_end - obb_centre);
obb.set_col (3, obb_z_end - obb_centre);
return obb;
}
/*!
* Returns a 3x4 matrix whose columns are the vectors obb_centre, obb_x, obb_y and obb_z for
* the axis aligned bounding box *after* it has been oriented with this model's viewmatrix.
*/
sm::mat<float, 3, 4> get_viewmatrix_obb() const { return this->get_viewmatrix_obb (this->viewmatrix); }
/*!
* Find collision between this model's oriented bounding box and another oriented bounding box.