forked from STORM-IRIT/Radium-Engine
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMesh.hpp
More file actions
1171 lines (984 loc) · 41.7 KB
/
Copy pathMesh.hpp
File metadata and controls
1171 lines (984 loc) · 41.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
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
#pragma once
#include <Core/Asset/GeometryData.hpp>
#include <Core/Containers/VectorArray.hpp>
#include <Core/Geometry/MeshPrimitives.hpp>
#include <Core/Geometry/StandardAttribNames.hpp>
#include <Core/Geometry/TriangleMesh.hpp>
#include <Core/Utils/BijectiveAssociation.hpp>
#include <Core/Utils/Color.hpp>
#include <Core/Utils/Log.hpp>
#include <Core/Utils/ObjectWithSemantic.hpp>
#include <Engine/Data/DisplayableObject.hpp>
#include <Engine/Data/ShaderProgram.hpp>
#include <Engine/RaEngine.hpp>
#include <globjects/Buffer.h>
#include <globjects/Program.h>
#include <globjects/VertexArray.h>
#include <globjects/VertexAttributeBinding.h>
#include <array>
#include <iterator>
#include <map>
#include <vector>
namespace Ra {
namespace Engine {
namespace Data {
class ShaderProgram;
using namespace Ra::Core::Utils;
/// VAO + VBO attributes management,
/// also manage draw calls
class RA_ENGINE_API Vao
{
/// \todo not used for now ... but may be if we allow multiple vao per mesh
std::unique_ptr<globjects::VertexArray> m_vao;
std::vector<std::unique_ptr<globjects::Buffer>> m_vbos;
std::vector<bool> m_dataDirty;
std::map<std::string, int> m_handleToBuffer;
};
/**
* A class representing an openGL general mesh to be displayed.
* It stores the vertex attributes, indices, and can be rendered
* with a specific render mode (e.g. GL_TRIANGLES or GL_LINES).
* It maintains the attributes and keeps them in sync with the GPU.
* \note Attribute names are used to automatic location binding when using shaders.
*/
class RA_ENGINE_API AttribArrayDisplayable : public Displayable
{
public:
/// Render mode enum used when render()/
/// values taken from OpenGL specification
/// \see https://www.khronos.org/registry/OpenGL/api/GL/glcorearb.h
enum MeshRenderMode : uint {
RM_POINTS = 0x0000,
RM_LINES = 0x0001, // decimal value: 1
RM_LINE_LOOP = 0x0002, // decimal value: 2
RM_LINE_STRIP = 0x0003, // decimal value: 3
RM_TRIANGLES = 0x0004, // decimal value: 4
RM_TRIANGLE_STRIP = 0x0005, // decimal value: 5
RM_TRIANGLE_FAN = 0x0006, // decimal value: 6
RM_QUADS = 0x0007, // decimal value: 7
RM_QUAD_STRIP = 0x0008, // decimal value: 8
RM_POLYGON = 0x0009, // decimal value: 9
RM_LINES_ADJACENCY = 0x000A, // decimal value: 10
RM_LINE_STRIP_ADJACENCY = 0x000B, // decimal value: 11
RM_TRIANGLES_ADJACENCY = 0x000C, // decimal value: 12
RM_TRIANGLE_STRIP_ADJACENCY = 0x000D, // decimal value: 13
RM_PATCHES = 0x000E, // decimal value: 14
};
public:
explicit AttribArrayDisplayable( const std::string& name,
MeshRenderMode renderMode = RM_TRIANGLES );
AttribArrayDisplayable( const AttribArrayDisplayable& rhs ) = delete;
void operator=( const AttribArrayDisplayable& rhs ) = delete;
~AttribArrayDisplayable() {}
using Displayable::getName;
/// Set the render mode.
inline void setRenderMode( MeshRenderMode mode );
/// Get the render mode.
inline MeshRenderMode getRenderMode() const;
/// \name
/// Mark attrib data as dirty, forcing an update of the OpenGL buffer.
///\{
/// Use g_attribName to find the corresponding name and call setDirty(const std::string& name).
/// \param type: the data to set to MeshAttrib
void setDirty( const Core::Geometry::MeshAttrib& type );
/// \param name: data buffer name to set to dirty
void setDirty( const std::string& name );
/// If index is greater than then number of buffer, this function as no effect.
/// \param index: the data buffer index to set to dirty.
void setDirty( unsigned int index );
///\}
/// This function is called at the start of the rendering.
/// It will update the necessary openGL buffers.
void updateGL() override = 0;
/// \name
/// Core::Geometry getters.
///\{
virtual const Core::Geometry::AttribArrayGeometry& getAttribArrayGeometry() const = 0;
virtual Core::Geometry::AttribArrayGeometry& getAttribArrayGeometry() = 0;
///\}
/// \brief Get opengl's vbo handle (uint) corresponding to attrib \b name.
///
/// If vbo is not initialized or name do not correponds to an actual attrib name, the returned
/// optional is empty
Ra::Core::Utils::optional<gl::GLuint> getVboHandle( const std::string& name );
/// \brief Get opengl's vao handle (uint).
///
/// If vao is not initialized, the returned optional is empty
Ra::Core::Utils::optional<gl::GLuint> getVaoHandle();
protected:
/// Update the picking render mode according to the object render mode
void updatePickingRenderMode();
class AttribObserver
{
public:
explicit AttribObserver( AttribArrayDisplayable* displayable, int idx ) :
m_displayable( displayable ), m_idx( idx ) {}
void operator()() {
if ( m_idx < int( m_displayable->m_dataDirty.size() ) ) {
m_displayable->m_dataDirty[m_idx] = true;
m_displayable->m_isDirty = true;
}
else {
/// \todo Should never be here
LOG( logDEBUG ) << "Invalid dirty bit notified on " << m_displayable->getName();
}
}
private:
AttribArrayDisplayable* m_displayable;
int m_idx;
};
protected:
std::unique_ptr<globjects::VertexArray> m_vao;
MeshRenderMode m_renderMode { MeshRenderMode::RM_TRIANGLES };
// m_vbos and m_dataDirty have the same size and are indexed thru m_handleToBuffer[attribName]
std::vector<std::unique_ptr<globjects::Buffer>> m_vbos;
std::vector<bool> m_dataDirty;
// Geometry attrib name (std::string) to buffer id (int)
// buffer id are indices in m_vbos and m_dataDirty
std::map<std::string, unsigned int> m_handleToBuffer;
/// \brief General dirty bit of the mesh.
///
/// Must be equivalent of the "or" of the other dirty flags. An empty mesh is not dirty
bool m_isDirty { false };
};
/// Concept class to ensure consistent naming of VaoIndices accross derived classes.
class RA_ENGINE_API VaoIndices
{
public:
/// Tag the indices as dirty, asking for a update to gpu.
inline void setIndicesDirty();
///\todo Add test for Indices observer
class IndicesObserver
{
public:
/// not tested
explicit IndicesObserver( VaoIndices* displayable ) : m_displayable { displayable } {}
/// not tested
void operator()() { m_displayable->m_indicesDirty = true; }
private:
VaoIndices* m_displayable;
};
protected:
std::unique_ptr<globjects::Buffer> m_indices { nullptr };
bool m_indicesDirty { true };
/// number of elements to draw (i.e number of indices to use)
/// automatically set by updateGL(), not meaningfull if m_indicesDirty.
size_t m_numElements { 0 };
};
/// This class handles an attrib array displayable on gpu only, without core
/// geometry. Use only when you don't need to access the cpu geometry again, or
/// when you need to specify special indices.
template <typename I>
class IndexedAttribArrayDisplayable : public AttribArrayDisplayable, public VaoIndices
{
using IndexType = I;
using IndexContainerType = Ra::Core::AlignedStdVector<IndexType>;
template <typename T>
inline void addAttrib( const std::string& name,
const typename Ra::Core::Utils::Attrib<T>::Container& data );
template <typename T>
inline void addAttrib( const std::string& name,
const typename Ra::Core ::Utils::Attrib<T>::Container&& data );
inline void updateGL() override;
inline void render( const ShaderProgram* prog ) override;
protected:
/// assume m_vao is bound.
inline void autoVertexAttribPointer( const ShaderProgram* prog );
IndexContainerType m_cpu_indices;
AttribManager m_attribManager;
};
/// Template class to manage the Displayable aspect of a Core Geomertry, such as TriangleMesh.
template <typename T>
class CoreGeometryDisplayable : public AttribArrayDisplayable
{
public:
using base = AttribArrayDisplayable;
using CoreGeometry = T;
explicit CoreGeometryDisplayable( const std::string& name,
MeshRenderMode renderMode = RM_TRIANGLES );
// no need to detach observer in dtor since CoreGeometry is owned by this, and CoreGeometry dtor
// will detachAll observers.
/// \name
/// Core::Geometry getters
///\{
inline const Core::Geometry::AbstractGeometry& getAbstractGeometry() const override;
inline Core::Geometry::AbstractGeometry& getAbstractGeometry() override;
inline const Core::Geometry::AttribArrayGeometry& getAttribArrayGeometry() const override;
inline Core::Geometry::AttribArrayGeometry& getAttribArrayGeometry() override;
inline const CoreGeometry& getCoreGeometry() const;
inline CoreGeometry& getCoreGeometry();
///\}
/// Helper function that calls Ra::Core::CoreGeometry::addAttrib()
template <typename A>
inline Ra::Core::Utils::AttribHandle<A> addAttrib( const std::string& name,
const typename Core::VectorArray<A>& data );
inline size_t getNumVertices() const override;
/// Use the given geometry as base for a display mesh.
/// This will move \p mesh and *this will take the ownership
/// of the data.
/// The currently owned mesh is deleted, if any.
/// This method should be called to set or replace the CoreGeometry, if you
/// want to update attributes or indices, use getCoreGeometry and
/// Core::Geometry::AttribArrayGeometry setters instead.
/// \warning For indices, you must call setIndicesDirty after modification.
/// \todo add observer mecanism for indices.
virtual void loadGeometry( CoreGeometry&& mesh );
/// Update (i.e. send to GPU) the buffers marked as dirty
void updateGL() override;
/// Bind meshAttribName to shaderAttribName.
/// meshAttribName is a vertex attrib added to the underlying CoreGeometry
/// shaderAttribName is the name of the input paramter of the shader.
/// By default the same name is used, but this mecanism allows to override
/// this behavior.
/// Only one shaderAttribName can be bound to a meshAttribName and the other
/// way round.
/// \param meshAttribName: name of the attribute on the CoreGeomtry side
/// \param shaderAttribName: name of the input vertex attribute on the
/// shader side.
void setAttribNameCorrespondance( const std::string& meshAttribName,
const std::string& shaderAttribName );
void autoVertexAttribCheck( const ShaderProgram* prog );
protected:
virtual void updateGL_specific_impl() {}
void loadGeometry_common( CoreGeometry&& mesh );
void setupCoreMeshObservers();
/// assume m_vao is bound.
void autoVertexAttribPointer( const ShaderProgram* prog );
/// m_mesh Observer method, called whenever an attrib is added or removed from
/// m_mesh.
/// it adds an observer to the new attrib.
void addAttribObserver( const std::string& name );
void addToTranslationTable( const std::string& name );
/// Core::Mesh attrib name to Render::Mesh attrib name
/// key: core mesh name, value: shader name
BijectiveAssociation<std::string, std::string> m_translationTable {};
CoreGeometry m_mesh;
};
/// A PointCloud without indices
class RA_ENGINE_API PointCloud : public CoreGeometryDisplayable<Core::Geometry::PointCloud>
{
using base = CoreGeometryDisplayable<Core::Geometry::PointCloud>;
public:
using base::CoreGeometryDisplayable;
inline explicit PointCloud(
const std::string& name,
typename base::CoreGeometry&& geom,
typename base::MeshRenderMode renderMode = base::MeshRenderMode::RM_POINTS );
inline explicit PointCloud( const std::string& name, MeshRenderMode renderMode = RM_POINTS );
/// use glDrawArrays to draw all the points in the point cloud
void render( const ShaderProgram* prog ) override;
void loadGeometry( Core::Geometry::PointCloud&& mesh ) override;
protected:
void updateGL_specific_impl() override;
};
/// An engine mesh owning CoreGeometry, with indices
template <typename T>
class IndexedGeometry : public CoreGeometryDisplayable<T>, public VaoIndices
{
public:
using base = CoreGeometryDisplayable<T>;
using CoreGeometryDisplayable<T>::CoreGeometryDisplayable;
explicit IndexedGeometry(
const std::string& name,
typename base::CoreGeometry&& geom,
typename base::MeshRenderMode renderMode = base::MeshRenderMode::RM_TRIANGLES );
void render( const ShaderProgram* prog ) override;
void loadGeometry( T&& mesh ) override;
protected:
void updateGL_specific_impl() override;
};
/// An engine mesh owning a MultiIndexedCoreGeometry, with multiple indices layer.
/// \todo Work in progress.
template <typename T>
class MultiIndexedGeometry : public CoreGeometryDisplayable<T>
{
public:
using base = CoreGeometryDisplayable<T>;
using CoreGeometryDisplayable<T>::CoreGeometryDisplayable;
explicit MultiIndexedGeometry(
const std::string& name,
typename base::CoreGeometry&& geom,
typename base::MeshRenderMode renderMode = base::MeshRenderMode::RM_TRIANGLES );
void render( const ShaderProgram* prog ) override;
void loadGeometry( T&& mesh ) override;
protected:
void updateGL_specific_impl() override;
using LayerSemanticCollection = Core::Utils::ObjectWithSemantic::SemanticNameCollection;
using LayerSemantic = Core::Utils::ObjectWithSemantic::SemanticName;
using LayerKeyType = std::pair<LayerSemanticCollection, std::string>;
using EntryType = std::pair<bool, VaoIndices*>;
struct KeyHash {
std::size_t operator()( const LayerKeyType& k )
const { // Mix semantic collection into a single identifier string
std::ostringstream stream;
std::copy(
k.first.begin(), k.first.end(), std::ostream_iterator<std::string>( stream, "" ) );
std::string result = stream.str();
std::sort( result.begin(), result.end() );
// Combine with layer name hash
return std::hash<std::string> {}( result ) ^
( std::hash<std::string> {}( k.second ) << 1 );
}
};
std::unordered_map<LayerKeyType, EntryType, KeyHash> m_indices;
};
/// LineMesh, own a Core::Geometry::LineMesh
class RA_ENGINE_API LineMesh : public IndexedGeometry<Core::Geometry::LineMesh>
{
using base = IndexedGeometry<Core::Geometry::LineMesh>;
public:
using base::IndexedGeometry;
inline explicit LineMesh(
const std::string& name,
typename base::CoreGeometry&& geom,
typename base::MeshRenderMode renderMode = base::MeshRenderMode::RM_LINES );
inline explicit LineMesh(
const std::string& name,
typename base::MeshRenderMode renderMode = base::MeshRenderMode::RM_LINES );
protected:
private:
};
/// Mesh, own a Core::Geometry::TriangleMesh
class RA_ENGINE_API Mesh : public IndexedGeometry<Core::Geometry::TriangleMesh>
{
using base = IndexedGeometry<Core::Geometry::TriangleMesh>;
public:
using base::IndexedGeometry;
size_t getNumFaces() const override;
/**
* Use the given vertices and indices to build a display mesh according to
* the MeshRenderMode.
* \note This has to be used for non RM_TRIANGLES meshes only.
* \note Also removes all vertex attributes.
* \warning This will disappear as soon as old code will be removed.
*/
using base::loadGeometry;
[[deprecated]] void loadGeometry( const Core::Vector3Array& vertices,
const std::vector<uint>& indices );
protected:
private:
};
/// GeneralMesh, own a Mesh of type T ( e.g. Core::Geometry::PolyMesh or Core::Geometry::QuadMesh)
/// This class handle the GPU representation of a polyhedron mesh.
/// Each face of the polyhedron (typically quads) are assume to be planar and convex.
/// Simple triangulation is performed on the fly before sending data to the GPU.
template <typename T>
class RA_ENGINE_API GeneralMesh : public IndexedGeometry<T>
{
using base = IndexedGeometry<T>;
using IndexType = Core::Vector3ui;
public:
using base::IndexedGeometry;
inline size_t getNumFaces() const override;
protected:
inline void updateGL_specific_impl() override;
private:
inline void triangulate();
Core::AlignedStdVector<IndexType> m_triangleIndices;
};
using PolyMesh = GeneralMesh<Core::Geometry::PolyMesh>;
using QuadMesh = GeneralMesh<Core::Geometry::QuadMesh>;
/// create a TriangleMesh, PolyMesh or other Core::*Mesh from GeometryData
/// \todo replace the copy of all geometry data by reference to original data.
template <typename CoreMeshType>
CoreMeshType createCoreMeshFromGeometryData( const Ra::Core::Asset::GeometryData* data ) {
CoreMeshType mesh;
typename CoreMeshType::IndexContainerType indices;
if ( !data->isLineMesh() ) {
auto& geo = data->getGeometry();
const auto& [layerKeyType, layerBase] =
geo.getFirstLayerOccurrence( mesh.getLayerKey().first );
const auto& layer = static_cast<
const Core::Geometry::GeometryIndexLayer<typename CoreMeshType::IndexType>&>(
layerBase );
const auto& faces = layer.collection();
indices.reserve( faces.size() );
std::copy( faces.begin(), faces.end(), std::back_inserter( indices ) );
}
#if 0
// TODO manage line meshes in a "usual" way, i.e. as an indexed geometry with specific
// rendering properties (i.e. shader, as it is the case for point clouds)
// Create a degenerated triangle to handle edges case.
else {
const auto& edges = ... access the LineIndexLayer
indices.reserve( edges.size() );
std::transform(
edges.begin(), edges.end(), std::back_inserter( indices ), []( Ra::Core::Vector2ui v ) {
return ( Ra::Core::Vector3ui { v( 0 ), v( 1 ), v( 1 ) } );
} );
}
#endif
mesh.setIndices( std::move( indices ) );
// This copy only "usual" attributes. See Core::Geometry::AttribManager::copyAllAttributes
mesh.vertexAttribs().copyAllAttributes( data->getGeometry().vertexAttribs() );
return mesh;
}
/// Helpers to get RenderMesh type from CoreMesh Type
namespace RenderMeshType {
template <class CoreMeshT>
struct getType {};
template <>
struct getType<Ra::Core::Geometry::LineMesh> {
using Type = Ra::Engine::Data::LineMesh;
};
template <>
struct getType<Ra::Core::Geometry::TriangleMesh> {
using Type = Ra::Engine::Data::Mesh;
};
template <>
struct getType<Ra::Core::Geometry::QuadMesh> {
using Type = Ra::Engine::Data::QuadMesh;
};
template <>
struct getType<Ra::Core::Geometry::PolyMesh> {
using Type = Ra::Engine::Data::PolyMesh;
};
} // namespace RenderMeshType
/// create Mesh, PolyMesh Engine::Data::*Mesh * from GeometryData
template <typename CoreMeshType>
typename RenderMeshType::getType<CoreMeshType>::Type*
createMeshFromGeometryData( const std::string& name, const Ra::Core::Asset::GeometryData* data ) {
using MeshType = typename RenderMeshType::getType<CoreMeshType>::Type;
auto mesh = createCoreMeshFromGeometryData<CoreMeshType>( data );
MeshType* ret = new MeshType { name };
ret->loadGeometry( std::move( mesh ) );
return ret;
}
//////////////// AttribArrayDisplayable ///////////////////////////////
void AttribArrayDisplayable::setRenderMode( MeshRenderMode mode ) {
m_renderMode = mode;
updatePickingRenderMode();
}
AttribArrayDisplayable::MeshRenderMode AttribArrayDisplayable::getRenderMode() const {
return m_renderMode;
}
///////////////// VaoIndices ///////////////////////
void VaoIndices::setIndicesDirty() {
m_indicesDirty = true;
}
///////////////// IndexedAttribArrayDisplayable ///////////////////////
template <typename I>
template <typename T>
void IndexedAttribArrayDisplayable<I>::addAttrib(
const std::string& name,
const typename Ra::Core::Utils::Attrib<T>::Container& data ) {
auto handle = m_attribManager.addAttrib<T>( name );
m_attribManager.getAttrib( handle ).setData( data );
m_handleToBuffer[name] = m_dataDirty.size();
m_dataDirty.push_back( true );
m_vbos.emplace_back( nullptr );
m_isDirty = true;
}
template <typename I>
template <typename T>
void IndexedAttribArrayDisplayable<I>::addAttrib(
const std::string& name,
const typename Ra::Core ::Utils::Attrib<T>::Container&& data ) {
auto handle = m_attribManager.addAttrib<T>( name );
m_attribManager.getAttrib( handle ).setData( std::move( data ) );
m_handleToBuffer[name] = m_dataDirty.size();
m_dataDirty.push_back( true );
m_vbos.emplace_back( nullptr );
m_isDirty = true;
}
template <typename I>
void IndexedAttribArrayDisplayable<I>::updateGL() {
if ( m_isDirty ) {
// Check that our dirty bits are consistent.
ON_ASSERT( bool dirtyTest = false;
for ( const auto& d : m_dataDirty ) { dirtyTest = dirtyTest || d; } );
CORE_ASSERT( dirtyTest == m_isDirty, "Dirty flags inconsistency" );
if ( !m_indices ) {
m_indices = globjects::Buffer::create();
m_indicesDirty = true;
}
if ( m_indicesDirty ) {
m_indices->setData(
static_cast<gl::GLsizeiptr>( m_cpu_indices.size() * sizeof( IndexType ) ),
m_cpu_indices.data(),
GL_STATIC_DRAW );
m_indicesDirty = false;
}
m_numElements = m_cpu_indices.size();
if ( !m_vao ) { m_vao = globjects::VertexArray::create(); }
m_vao->bind();
m_vao->bindElementBuffer( m_indices.get() );
m_vao->unbind();
auto func = [this]( Ra::Core::Utils::AttribBase* b ) {
auto idx = m_handleToBuffer[b->getName()];
if ( m_dataDirty[idx] ) {
if ( !m_vbos[idx] ) { m_vbos[idx] = globjects::Buffer::create(); }
m_vbos[idx]->setData( b->getBufferSize(), b->dataPtr(), GL_DYNAMIC_DRAW );
m_dataDirty[idx] = false;
}
};
m_attribManager.for_each_attrib( func );
GL_CHECK_ERROR;
m_isDirty = false;
}
}
template <typename I>
void IndexedAttribArrayDisplayable<I>::autoVertexAttribPointer( const ShaderProgram* prog ) {
auto glprog = prog->getProgramObject();
gl::GLint attribCount = glprog->get( GL_ACTIVE_ATTRIBUTES );
for ( GLint idx = 0; idx < attribCount; ++idx ) {
const gl::GLsizei bufSize = 256;
gl::GLchar name[bufSize];
gl::GLsizei length;
gl::GLint size;
gl::GLenum type;
glprog->getActiveAttrib( idx, bufSize, &length, &size, &type, name );
auto loc = glprog->getAttributeLocation( name );
auto attribName = name; // m_translationTableShaderToMesh[name];
auto attrib = m_attribManager.getAttribBase( attribName );
if ( attrib && attrib->getSize() > 0 ) {
m_vao->enable( loc );
auto binding = m_vao->binding( idx );
binding->setAttribute( loc );
CORE_ASSERT( m_vbos[m_handleToBuffer[attribName]].get(), "vbo is nullptr" );
#ifdef CORE_USE_DOUBLE
binding->setBuffer( m_vbos[m_handleToBuffer[attribName]].get(),
0,
attrib->getNumberOfComponents() * sizeof( float ) );
#else
binding->setBuffer(
m_vbos[m_handleToBuffer[attribName]].get(), 0, attrib->getStride() );
#endif
binding->setFormat( attrib->getNumberOfComponents(), GL_SCALAR );
}
else { m_vao->disable( loc ); }
}
}
template <typename I>
void IndexedAttribArrayDisplayable<I>::render( const ShaderProgram* prog ) {
if ( m_vao ) {
autoVertexAttribPointer( prog );
m_vao->bind();
m_vao->drawElements( static_cast<GLenum>( m_renderMode ),
GLsizei( m_numElements ),
GL_UNSIGNED_INT,
nullptr );
m_vao->unbind();
}
}
//////////////// CoreGeometryDisplayable ///////////////////////////////
template <typename CoreGeometry>
CoreGeometryDisplayable<CoreGeometry>::CoreGeometryDisplayable( const std::string& name,
MeshRenderMode renderMode ) :
base( name, renderMode ) {
setupCoreMeshObservers();
}
template <typename CoreGeometry>
const Ra::Core::Geometry::AbstractGeometry&
CoreGeometryDisplayable<CoreGeometry>::getAbstractGeometry() const {
return m_mesh;
}
template <typename CoreGeometry>
Ra::Core::Geometry::AbstractGeometry& CoreGeometryDisplayable<CoreGeometry>::getAbstractGeometry() {
return m_mesh;
}
template <typename CoreGeometry>
const Ra::Core::Geometry::AttribArrayGeometry&
CoreGeometryDisplayable<CoreGeometry>::getAttribArrayGeometry() const {
return m_mesh;
}
template <typename CoreGeometry>
Ra::Core::Geometry::AttribArrayGeometry&
CoreGeometryDisplayable<CoreGeometry>::getAttribArrayGeometry() {
return m_mesh;
}
template <typename CoreGeometry>
const CoreGeometry& CoreGeometryDisplayable<CoreGeometry>::getCoreGeometry() const {
return m_mesh;
}
template <typename CoreGeometry>
CoreGeometry& CoreGeometryDisplayable<CoreGeometry>::getCoreGeometry() {
return m_mesh;
}
template <typename CoreGeometry>
void CoreGeometryDisplayable<CoreGeometry>::addToTranslationTable( const std::string& name ) {
m_translationTable.insert( name, name );
}
template <typename CoreGeometry>
void CoreGeometryDisplayable<CoreGeometry>::addAttribObserver( const std::string& name ) {
// this observer is called each time an attrib is added or removed from m_mesh
auto attrib = m_mesh.getAttribBase( name );
// if attrib not nullptr, then it's an attrib add, so attach an observer to it
if ( attrib ) {
auto itr = m_handleToBuffer.find( name );
if ( itr == m_handleToBuffer.end() ) {
m_handleToBuffer[name] = m_dataDirty.size();
addToTranslationTable( name );
m_dataDirty.push_back( true );
m_vbos.emplace_back( nullptr );
}
auto idx = m_handleToBuffer[name];
attrib->attach( AttribObserver( this, idx ) );
}
// else it's an attrib remove, do nothing, cleanup will be done in updateGL()
else {}
}
template <typename CoreGeometry>
void CoreGeometryDisplayable<CoreGeometry>::autoVertexAttribPointer( const ShaderProgram* prog ) {
auto glprog = prog->getProgramObject();
gl::GLint attribCount = glprog->get( GL_ACTIVE_ATTRIBUTES );
for ( GLint idx = 0; idx < attribCount; ++idx ) {
const gl::GLsizei bufSize = 256;
gl::GLchar name[bufSize];
gl::GLsizei length;
gl::GLint size;
gl::GLenum type;
glprog->getActiveAttrib( idx, bufSize, &length, &size, &type, name );
auto loc = glprog->getAttributeLocation( name );
auto attribNameOpt = m_translationTable.keyIfExists( name );
if ( attribNameOpt ) {
auto attribName = *attribNameOpt;
auto attrib = m_mesh.getAttribBase( attribName );
if ( attrib && attrib->getSize() > 0 ) {
m_vao->enable( loc );
auto binding = m_vao->binding( idx );
binding->setAttribute( loc );
CORE_ASSERT( m_vbos[m_handleToBuffer[attribName]].get(), "vbo is nullptr" );
#ifdef CORE_USE_DOUBLE
binding->setBuffer( m_vbos[m_handleToBuffer[attribName]].get(),
0,
attrib->getNumberOfComponents() * sizeof( float ) );
#else
binding->setBuffer(
m_vbos[m_handleToBuffer[attribName]].get(), 0, attrib->getStride() );
#endif
binding->setFormat( attrib->getNumberOfComponents(), GL_SCALAR );
}
else { m_vao->disable( loc ); }
}
else { m_vao->disable( loc ); }
}
}
template <typename CoreGeometry>
void CoreGeometryDisplayable<CoreGeometry>::autoVertexAttribCheck( const ShaderProgram* prog ) {
auto glprog = prog->getProgramObject();
gl::GLint attribCount = glprog->get( GL_ACTIVE_ATTRIBUTES );
for ( GLint idx = 0; idx < attribCount; ++idx ) {
const gl::GLsizei bufSize = 256;
gl::GLchar name[bufSize];
gl::GLsizei length;
gl::GLint size;
gl::GLenum type;
glprog->getActiveAttrib( idx, bufSize, &length, &size, &type, name );
auto loc = glprog->getAttributeLocation( name );
auto attribNameOpt = m_translationTable.keyIfExists( name );
if ( attribNameOpt ) {
auto attribName = *attribNameOpt;
auto attrib = m_mesh.getAttribBase( attribName );
if ( attrib && attrib->getSize() > 0 ) {
LOG( logINFO ) << "enable " << attribName << " to " << name << " " << loc;
}
else {
LOG( logINFO ) << "attribName not vaild " << attribName << " disable " << name
<< " " << loc;
}
}
else { LOG( logINFO ) << "attrib not found in table, disable " << name << " " << loc; }
}
}
template <typename T>
void CoreGeometryDisplayable<T>::loadGeometry_common( T&& mesh ) {
m_mesh = std::move( mesh );
setupCoreMeshObservers();
}
template <typename T>
void CoreGeometryDisplayable<T>::setupCoreMeshObservers() {
int idx = 0;
m_dataDirty.resize( m_mesh.vertexAttribs().getNumAttribs() );
m_vbos.resize( m_mesh.vertexAttribs().getNumAttribs() );
// here capture ref to idx to propagate idx incrementation
m_mesh.vertexAttribs().for_each_attrib( [&idx, this]( Ra::Core::Utils::AttribBase* b ) {
auto name = b->getName();
m_handleToBuffer[name] = idx;
m_dataDirty[idx] = true;
// create a identity translation if name is not already translated.
addToTranslationTable( name );
b->attach( AttribObserver( this, idx ) );
++idx;
} );
// add an observer on attrib manipulation.
m_mesh.vertexAttribs().attachMember(
this, &CoreGeometryDisplayable<CoreGeometry>::addAttribObserver );
m_isDirty = true;
}
/// Helper function that calls Ra::Core::CoreGeometry::addAttrib()
template <typename CoreGeometry>
template <typename A>
Ra::Core::Utils::AttribHandle<A>
CoreGeometryDisplayable<CoreGeometry>::addAttrib( const std::string& name,
const typename Core::VectorArray<A>& data ) {
return m_mesh.addAttrib( name, data );
}
template <typename CoreGeometry>
size_t CoreGeometryDisplayable<CoreGeometry>::getNumVertices() const {
return m_mesh.vertices().size();
}
template <typename CoreGeometry>
void CoreGeometryDisplayable<CoreGeometry>::loadGeometry( CoreGeometry&& /*mesh*/ ) {
CORE_ASSERT( false, "must be specialized" );
}
template <typename CoreGeometry>
void CoreGeometryDisplayable<CoreGeometry>::updateGL() {
if ( m_isDirty ) {
// Check that our dirty bits are consistent.
ON_ASSERT( bool dirtyTest = false;
for ( auto d : m_dataDirty ) { dirtyTest = dirtyTest || d; } );
CORE_ASSERT( dirtyTest == m_isDirty, "Dirty flags inconsistency" );
CORE_ASSERT( !( m_mesh.vertices().empty() ), "No vertex." );
updateGL_specific_impl();
#ifdef CORE_USE_DOUBLE
// need convserion
auto func = [this]( Ra::Core::Utils::AttribBase* b ) {
auto idx = m_handleToBuffer[b->getName()];
if ( m_dataDirty[idx] ) {
if ( !m_vbos[idx] ) { m_vbos[idx] = globjects::Buffer::create(); }
auto stride = b->getStride();
auto eltSize = b->getNumberOfComponents();
auto size = b->getSize();
auto data = std::make_unique<float[]>( size * eltSize );
const void* ptr = b->dataPtr();
const char* cptr = reinterpret_cast<const char*>( ptr );
for ( size_t i = 0; i < size; i++ ) {
auto tptr = reinterpret_cast<const Scalar*>( cptr + i * stride );
for ( size_t j = 0; j < eltSize; ++j ) {
data[i * eltSize + j] = tptr[j];
}
}
m_vbos[idx]->setData(
size * eltSize * sizeof( float ), data.get(), GL_DYNAMIC_DRAW );
m_dataDirty[idx] = false;
}
};
#else
auto func = [this]( Ra::Core::Utils::AttribBase* b ) {
auto idx = m_handleToBuffer[b->getName()];
if ( m_dataDirty[idx] ) {
if ( !m_vbos[idx] ) { m_vbos[idx] = globjects::Buffer::create(); }
m_vbos[idx]->setData( b->getBufferSize(), b->dataPtr(), GL_DYNAMIC_DRAW );
m_dataDirty[idx] = false;
}
};
#endif
m_mesh.vertexAttribs().for_each_attrib( func );
// cleanup removed attrib
for ( auto buffer : m_handleToBuffer ) {
// do not remove name from handleToBuffer to keep index ...
// we could also update handleToBuffer, m_vbos, m_dataDirty
if ( !m_mesh.hasAttrib( buffer.first ) && m_vbos[buffer.second] ) {
m_vbos[buffer.second].reset( nullptr );
m_dataDirty[buffer.second] = false;
}
}
GL_CHECK_ERROR;
m_isDirty = false;
}
}
template <typename CoreGeometry>
void CoreGeometryDisplayable<CoreGeometry>::setAttribNameCorrespondance(
const std::string& meshAttribName,
const std::string& shaderAttribName ) {
m_translationTable.replace( meshAttribName, shaderAttribName );
}
//////////////// IndexedGeometry ///////////////////////////////
template <typename T>
IndexedGeometry<T>::IndexedGeometry( const std::string& name,
typename base::CoreGeometry&& geom,
typename base::MeshRenderMode renderMode ) :
base( name, renderMode ) {
loadGeometry( std::move( geom ) );
}
template <typename T>
void IndexedGeometry<T>::loadGeometry( T&& mesh ) {
setIndicesDirty();
base::loadGeometry_common( std::move( mesh ) );
// indices
base::m_mesh.attach( IndicesObserver( this ) );
}
template <typename T>
void IndexedGeometry<T>::updateGL_specific_impl() {
if ( !m_indices ) {
m_indices = globjects::Buffer::create();
m_indicesDirty = true;
}
if ( m_indicesDirty ) {
/// this one do not work since m_indices is not a std::vector
// m_indices->setData( m_mesh.m_indices, GL_DYNAMIC_DRAW );
m_numElements =
base::m_mesh.getIndices().size() * base::CoreGeometry::IndexType::RowsAtCompileTime;
m_indices->setData(
static_cast<gl::GLsizeiptr>( base::m_mesh.getIndices().size() *
sizeof( typename base::CoreGeometry::IndexType ) ),
base::m_mesh.getIndices().data(),
GL_STATIC_DRAW );
m_indicesDirty = false;
}
if ( !base::m_vao ) { base::m_vao = globjects::VertexArray::create(); }
base::m_vao->bind();
base::m_vao->bindElementBuffer( m_indices.get() );
base::m_vao->unbind();
}
template <typename T>
void IndexedGeometry<T>::render( const ShaderProgram* prog ) {
if ( base::m_vao ) {
GL_CHECK_ERROR;
base::m_vao->bind();
base::autoVertexAttribPointer( prog );
GL_CHECK_ERROR;
base::m_vao->drawElements( static_cast<GLenum>( base::m_renderMode ),
GLsizei( m_numElements ),