-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathOgreHeightmap.cc
2848 lines (2394 loc) · 89.8 KB
/
OgreHeightmap.cc
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
/*
* Copyright (C) 2020 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <chrono>
#include <gz/common/Console.hh>
#include <gz/common/Util.hh>
#include "gz/rendering/ogre/OgreCamera.hh"
#include "gz/rendering/ogre/OgreConversions.hh"
#include "gz/rendering/ogre/OgreHeightmap.hh"
#include "gz/rendering/ogre/OgreLight.hh"
#include "gz/rendering/ogre/OgreMaterial.hh"
#include "gz/rendering/ogre/OgreRenderEngine.hh"
#include "gz/rendering/ogre/OgreRTShaderSystem.hh"
#include "gz/rendering/ogre/OgreScene.hh"
#if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR >= 11
// Since OGRE 1.11, the once public
// Ogre::TerrainMaterialGeneratorA::SM2Profile::ShaderHelper
// class and its descendant are now private classes of OGRE, see
// * https://github.com/OGRECave/ogre/blob/master/Docs/1.11-Notes.md#other
// * https://github.com/OGRECave/ogre/pull/722
//
// As these classes are heavily used in the Heightmap class implementation
// (by accessing a protected Ogre class) we need to disable the definition
// of the custom terrain generator, and just use the Ogre default one.
using Ogre::TechniqueType;
#endif
#if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR < 11
/// \internal
/// \brief Custom terrain material generator for GLSL terrains.
/// A custom material generator that lets Gazebo use GLSL shaders
/// (as opposed to the default Cg shaders provided by Ogre) for rendering
/// terrain.
class GzTerrainMatGen : public Ogre::TerrainMaterialGeneratorA
{
/// \brief Constructor
public: GzTerrainMatGen();
/// \brief Destructor
public: virtual ~GzTerrainMatGen();
/// \brief Shader model 2 profile target.
public: class SM2Profile :
public Ogre::TerrainMaterialGeneratorA::SM2Profile
{
/// \brief Constructor
public: SM2Profile(Ogre::TerrainMaterialGenerator *_parent,
const Ogre::String &_name, const Ogre::String &_desc);
/// \brief Destructor
public: virtual ~SM2Profile();
public: Ogre::MaterialPtr generate(const Ogre::Terrain *_terrain);
public: Ogre::MaterialPtr generateForCompositeMap(
const Ogre::Terrain *_terrain);
public: void UpdateParams(const Ogre::MaterialPtr &_mat,
const Ogre::Terrain *_terrain);
public: void UpdateParamsForCompositeMap(const Ogre::MaterialPtr &_mat,
const Ogre::Terrain *_terrain);
protected: virtual void addTechnique(const Ogre::MaterialPtr &_mat,
const Ogre::Terrain *_terrain, TechniqueType _tt);
/// \brief Utility class to help with generating shaders for GLSL.
/// The class contains a collection of functions that are used to
/// dynamically generate a complete vertex or fragment shader program
/// in a string format.
protected: class ShaderHelperGLSL :
public Ogre::TerrainMaterialGeneratorA::SM2Profile::ShaderHelperGLSL
{
public: ShaderHelperGLSL()
{
auto capabilities =
Ogre::Root::getSingleton().getRenderSystem()->getCapabilities();
Ogre::DriverVersion glVersion;
glVersion.build = 0;
glVersion.major = 3;
glVersion.minor = 0;
glVersion.release = 0;
if (capabilities->isDriverOlderThanVersion(glVersion))
{
this->glslVersion = "120";
this->vpInStr = "attribute";
this->vpOutStr = "varying";
this->fpInStr = "varying";
this->textureStr = "texture2D";
}
};
public: virtual Ogre::HighLevelGpuProgramPtr generateVertexProgram(
const SM2Profile *_prof, const Ogre::Terrain *_terrain,
TechniqueType _tt);
public: virtual Ogre::HighLevelGpuProgramPtr generateFragmentProgram(
const SM2Profile *_prof, const Ogre::Terrain *_terrain,
TechniqueType _tt);
public: virtual void updateParams(const SM2Profile *_prof,
const Ogre::MaterialPtr &_mat,
const Ogre::Terrain *_terrain, bool _compositeMap);
protected: virtual void generateVpHeader(const SM2Profile *_prof,
const Ogre::Terrain *_terrain, TechniqueType _tt,
Ogre::StringStream &_outStream);
protected: virtual void generateVpFooter(const SM2Profile *_prof,
const Ogre::Terrain *_terrain, TechniqueType _tt,
Ogre::StringStream &_outStream);
protected: virtual void generateVertexProgramSource(
const SM2Profile *_prof, const Ogre::Terrain *_terrain,
TechniqueType _tt,
Ogre::StringStream &_outStream);
protected: virtual void defaultVpParams(const SM2Profile *_prof,
const Ogre::Terrain *_terrain, TechniqueType _tt,
const Ogre::HighLevelGpuProgramPtr &_prog);
protected: virtual unsigned int generateVpDynamicShadowsParams(
unsigned int _texCoordStart, const SM2Profile *_prof,
const Ogre::Terrain *_terrain, TechniqueType _tt,
Ogre::StringStream &_outStream);
protected: virtual void generateVpDynamicShadows(
const SM2Profile *_prof, const Ogre::Terrain *_terrain,
TechniqueType _tt,
Ogre::StringStream &_outStream);
protected: virtual void generateFpHeader(const SM2Profile *_prof,
const Ogre::Terrain *_terrain,
TechniqueType tt,
Ogre::StringStream &_outStream);
protected: virtual void generateFpLayer(const SM2Profile *_prof,
const Ogre::Terrain *_terrain, TechniqueType tt,
Ogre::uint _layer,
Ogre::StringStream &_outStream);
protected: virtual void generateFpFooter(const SM2Profile *_prof,
const Ogre::Terrain *_terrain,
TechniqueType tt,
Ogre::StringStream &_outStream);
protected: virtual void generateFpDynamicShadowsParams(
Ogre::uint *_texCoord, Ogre::uint *_sampler,
const SM2Profile *_prof, const Ogre::Terrain *_terrain,
TechniqueType _tt,
Ogre::StringStream &_outStream);
protected: virtual void generateFpDynamicShadowsHelpers(
const SM2Profile *_prof,
const Ogre::Terrain *_terrain,
TechniqueType tt,
Ogre::StringStream &_outStream);
protected: void generateFpDynamicShadows(const SM2Profile *_prof,
const Ogre::Terrain *_terrain, TechniqueType _tt,
Ogre::StringStream &_outStream);
protected: virtual void generateFragmentProgramSource(
const SM2Profile *_prof,
const Ogre::Terrain *_terrain,
TechniqueType _tt,
Ogre::StringStream &_outStream);
protected: virtual void updateVpParams(const SM2Profile *_prof,
const Ogre::Terrain *_terrain, TechniqueType _tt,
const Ogre::GpuProgramParametersSharedPtr &_params);
private: Ogre::String GetChannel(Ogre::uint _idx);
/// \brief Capabilities
private: std::string glslVersion = "130";
private: std::string vpInStr = "in";
private: std::string vpOutStr = "out";
private: std::string fpInStr = "in";
private: std::string fpOutStr = "out";
private: std::string textureStr = "texture";
};
// Needed to allow access from ShaderHelperGLSL to protected members
// of SM2Profile.
friend ShaderHelperGLSL;
};
};
// #if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR < 11
#endif
/// \internal
/// \brief Custom terrain material generator.
/// A custom material generator that lets user specify their own material
/// script for rendering the heightmap.
class TerrainMaterial : public Ogre::TerrainMaterialGenerator
{
/// \brief Constructor
/// \param[in] _materialName Name of material
public: explicit TerrainMaterial(const std::string &_materialName);
/// \brief Set terrain material
/// \param[in] _materialName Name of material
public: void setMaterialByName(const std::string &_materialname);
/// \brief Set the grid size of the terrain, i.e. Number of terrain slots.
/// This will be used to determined how the texture will be mapped to the
/// terrain
/// \param[in] _size Grid size of the terrain
public: void setGridSize(const unsigned int _size);
/// \brief Subclassed to provide profile-specific material generation
class Profile : public Ogre::TerrainMaterialGenerator::Profile
{
/// \brief Constructor
/// \param[in] _parent Ogre terrain material generator object
/// \param[in] _name Name of the profile
/// \param[on] _desc Profile description
public: Profile(Ogre::TerrainMaterialGenerator *_parent,
const Ogre::String &_name, const Ogre::String &_desc);
/// \brief Destructor.
public: ~Profile();
// Documentation Inherited
public: bool isVertexCompressionSupported() const override;
// Documentation Inherited
public: Ogre::MaterialPtr generate(const Ogre::Terrain *_terrain) override;
// Documentation Inherited
public: Ogre::MaterialPtr generateForCompositeMap(
const Ogre::Terrain *_terrain) override;
// Documentation Inherited
public: void setLightmapEnabled(bool _enabled) override;
// Documentation Inherited
public: Ogre::uint8 getMaxLayers(const Ogre::Terrain *_terrain) const
override;
// Documentation Inherited
public: void updateParams(const Ogre::MaterialPtr& mat,
const Ogre::Terrain *_terrain) override;
// Documentation Inherited
public: void updateParamsForCompositeMap(const Ogre::MaterialPtr& mat,
const Ogre::Terrain *_terrain) override;
// Documentation Inherited
public: void requestOptions(Ogre::Terrain *_terrain) override;
};
/// \brief Name of material
protected: std::string materialName;
/// \brief Size of grid
protected: unsigned int gridSize = 1u;
};
/// \internal
/// \brief Pretends to provide procedural page content to avoid page loading
class DummyPageProvider : public Ogre::PageProvider
{
/// \brief Give a provider the opportunity to prepare page content
/// procedurally. The parameters are not used.
public: bool prepareProceduralPage(Ogre::Page *, Ogre::PagedWorldSection *)
{
return true;
}
/// \brief Give a provider the opportunity to load page content
/// procedurally. The parameters are not used.
public: bool loadProceduralPage(Ogre::Page *, Ogre::PagedWorldSection *)
{
return true;
}
/// \brief Give a provider the opportunity to unload page content
/// procedurally. The parameters are not used.
public: bool unloadProceduralPage(Ogre::Page *, Ogre::PagedWorldSection *)
{
return true;
}
/// \brief Give a provider the opportunity to unprepare page content
/// procedurally. The parameters are not used.
public: bool unprepareProceduralPage(Ogre::Page *, Ogre::PagedWorldSection *)
{
return true;
}
};
//////////////////////////////////////////////////
class gz::rendering::OgreHeightmapPrivate
{
/// \brief Global options - in some Ogre versions, this is enforced as a
/// singleton.
public: static Ogre::TerrainGlobalOptions *terrainGlobals;
/// \brief The raw height values.
public: std::vector<float> heights;
/// \brief Size of the heightmap data.
public: unsigned int dataSize{0u};
/// \brief True if the terrain need to be split into subterrains
public: bool splitTerrain{false};
/// \brief Number of pieces in which a terrain is subdivided. Used
/// for paging and also when heighmap is too large for LOD to work.
public: unsigned int numTerrainSubdivisions{16u};
/// \brief Max pixel error allowed for rendering the heightmap. This
/// affects the transitions between LOD levels.
public: double maxPixelError{0.0};
/// \brief Group of terrains.
public: Ogre::TerrainGroup *terrainGroup{nullptr};
/// \brief Skirt length on LOD tiles
public: double skirtLength{1.0};
/// \brief Terrain casts shadows
/// \todo(chapulina) Use Material? Expose through descriptor?
public: bool castShadows{false};
/// \brief True if the terrain's hash does not match the image's hash
public: bool terrainHashChanged{true};
/// \brief Hash file name that should be present for every terrain file
/// loaded using paging.
public: const std::string kHashFilename{"ignterrain.SHA1"};
/// \brief Collection of terrains. Every terrain might be paged.
public: std::vector<std::vector<float>> subTerrains;
/// \brief When the terrain paging is enabled, the terrain information
/// for every piece of terrain is stored in disk. This is the path of
/// the top level directory where these files are located.
public: std::string pagingDir;
/// \brief Name of the top level directory where all the paging info is
/// stored
public: const std::string pagingDirname{"ogre-paging"};
/// \brief Central registration point for extension classes,
/// such as the PageStrategy, PageContentFactory.
public: Ogre::PageManager *pageManager{nullptr};
/// \brief A page provider is needed to use the paging system.
public: DummyPageProvider dummyPageProvider;
/// \brief Collection of world content
public: Ogre::PagedWorld *world{nullptr};
/// \brief Type of paging applied
public: Ogre::TerrainPaging *terrainPaging{nullptr};
/// \brief The terrain pages are loaded if the distance from the camera is
/// within the loadRadius. See Ogre::TerrainPaging::createWorldSection().
/// LoadRadiusFactor is a multiplier applied to the terrain size to create
/// a load radius that depends on the terrain size.
public: const double loadRadiusFactor{1.0};
/// \brief The terrain pages are held in memory but not loaded if they
/// are not ready when the camera is within holdRadius distance. See
/// Ogre::TerrainPaging::createWorldSection(). HoldRadiusFactor is a
/// multiplier applied to the terrain size to create a hold radius that
/// depends on the terrain size.
public: const double holdRadiusFactor{1.15};
/// \brief True if the terrain was loaded from the cache.
public: bool loadedFromCache{false};
/// \brief True if the terrain was saved to the cache.
public: bool savedToCache{false};
/// \brief Used to iterate over all the terrains
public: int terrainIdx{0};
/// \brief Name of custom material to use for the terrain. If empty,
/// default material with glsl shader will be used.
/// \todo(chapulina) Will we ever use this?
public: std::string materialName;
#if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR < 11
/// \brief Pointer to the terrain material generator.
public: GzTerrainMatGen *gzMatGen{nullptr};
#endif
};
Ogre::TerrainGlobalOptions
*gz::rendering::OgreHeightmapPrivate::terrainGlobals = nullptr;
using namespace gz;
using namespace rendering;
//////////////////////////////////////////////////
OgreHeightmap::OgreHeightmap(const HeightmapDescriptor &_desc)
: BaseHeightmap(_desc), dataPtr(std::make_unique<OgreHeightmapPrivate>())
{
std::string home;
gz::common::env(GZ_HOMEDIR, home);
this->dataPtr->pagingDir =
common::joinPaths(home, ".gz", "rendering",
this->dataPtr->pagingDirname);
}
//////////////////////////////////////////////////
OgreHeightmap::~OgreHeightmap()
{
}
//////////////////////////////////////////////////
void OgreHeightmap::Init()
{
OgreObject::Init();
if (this->descriptor.Data() == nullptr)
{
gzerr << "Failed to initialize: null heightmap data." << std::endl;
return;
}
if (this->descriptor.Name().empty())
this->descriptor.SetName(this->Name());
// Add paths
for (auto i = 0u; i < this->descriptor.TextureCount(); ++i)
{
auto texture = this->descriptor.TextureByIndex(i);
OgreRenderEngine::Instance()->AddResourcePath(texture->Diffuse());
OgreRenderEngine::Instance()->AddResourcePath(texture->Normal());
}
// The terraingGroup is composed by a number of terrains (1 by default)
int nTerrains = 1;
// There is an issue with OGRE terrain LOD if heights are not relative to 0.
// So we move the heightmap so that its min elevation = 0 before feeding to
// ogre. It is later translated back by the setOrigin call.
double minElevation = this->descriptor.Data()->MinElevation();
double heightmapSizeZ =
this->descriptor.Data()->MaxElevation() - minElevation;
// \todo These parameters shouldn't be hardcoded, and instead parametrized so
// that they can be made consistent across different libraries (like
// gz-physics)
bool flipY = false;
// sampling size along image width and height
unsigned int vertSize = (this->descriptor.Data()->Width() *
this->descriptor.Sampling()) - this->descriptor.Sampling() + 1;
math::Vector3d scale;
scale.X(this->descriptor.Size().X() / vertSize);
scale.Y(this->descriptor.Size().Y() / vertSize);
if (math::equal(heightmapSizeZ, 0.0))
scale.Z(1.0);
else
scale.Z(fabs(this->descriptor.Size().Z()) / heightmapSizeZ);
// Construct the heightmap lookup table
std::vector<float> lookup;
this->descriptor.Data()->FillHeightMap(this->descriptor.Sampling(),
vertSize, this->descriptor.Size(), scale, flipY, lookup);
for (unsigned int y = 0; y < vertSize; ++y)
{
for (unsigned int x = 0; x < vertSize; ++x)
{
int index = (vertSize - y - 1) * vertSize + x;
// Sanity check in case we get NaNs from gz-common, this prevents a crash
// in Ogre
auto value = lookup[index];
if (!std::isfinite(value))
value = minElevation;
this->dataPtr->heights.push_back(value - minElevation);
}
}
this->dataPtr->dataSize = vertSize;
if (this->dataPtr->heights.empty())
{
gzerr << "Failed to load terrain. Heightmap data is empty" << std::endl;
return;
}
if (!math::isPowerOfTwo(this->dataPtr->dataSize - 1))
{
gzerr << "Heightmap final sampling must satisfy 2^n+1."
<< std::endl << "size = (width * sampling) = sampling + 1"
<< std::endl << "[" << this->dataPtr->dataSize << "] = (["
<< this->descriptor.Data()->Width() << "] * ["
<< this->descriptor.Sampling() << "]) = ["
<< this->descriptor.Sampling() << "] + 1: "
<< std::endl;
return;
}
// Get the full path of the image heightmap
// \todo(anyone) Name is generated at runtime and depends on the number of
// objects, so it's impossible to make sure it's the same across runs
auto terrainDirPath = common::joinPaths(this->dataPtr->pagingDir,
this->descriptor.Name());
// Add the top level terrain paging directory to the OGRE
// ResourceGroupManager
if (!Ogre::ResourceGroupManager::getSingleton().resourceLocationExists(
this->dataPtr->pagingDir, "General"))
{
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
this->dataPtr->pagingDir, "FileSystem", "General", true);
Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup(
"General");
}
std::string terrainNameSuffix = "";
if (static_cast<unsigned int>(this->dataPtr->maxPixelError) == 0)
{
terrainNameSuffix = "_LOD0";
}
// If the paging is enabled we modify the number of subterrains
std::string prefix;
if (this->descriptor.UseTerrainPaging())
{
this->dataPtr->splitTerrain = true;
nTerrains = this->dataPtr->numTerrainSubdivisions;
std::string terrainName = "gazebo_terrain_cache" +
terrainNameSuffix;
prefix = common::joinPaths(terrainDirPath, terrainName.c_str());
}
else
{
// Note: ran into problems with LOD height glitches if heightmap size is
// larger than 4096 so split it into chunks
// Note: dataSize should be 2^n + 1
if (this->dataPtr->maxPixelError > 0 && this->dataPtr->dataSize > 4096u)
{
this->dataPtr->splitTerrain = true;
if (this->dataPtr->dataSize == 4097u)
this->dataPtr->numTerrainSubdivisions = 4u;
else
this->dataPtr->numTerrainSubdivisions = 16u;
nTerrains = this->dataPtr->numTerrainSubdivisions;
gzmsg << "Large heightmap used with LOD. It will be subdivided into " <<
this->dataPtr->numTerrainSubdivisions << " terrains." << std::endl;
}
std::string terrainName = "gazebo_terrain" + terrainNameSuffix;
prefix = common::joinPaths(terrainDirPath, terrainName.c_str());
}
double sqrtN = sqrt(nTerrains);
// Create terrain group, which holds all the individual terrain instances.
// Param 1: Pointer to the scene manager
// Param 2: Alignment plane
// Param 3: Number of vertices along one edge of the terrain (2^n+1).
// Terrains must be square, with each side a power of 2 in size
// Param 4: World size of each terrain instance, in meters.
auto ogreScene = std::dynamic_pointer_cast<OgreScene>(this->Scene());
this->dataPtr->terrainGroup = new Ogre::TerrainGroup(
ogreScene->OgreSceneManager(), Ogre::Terrain::ALIGN_X_Y,
1 + ((this->dataPtr->dataSize - 1) / static_cast<unsigned int>(sqrtN)),
this->descriptor.Size().X() / (sqrtN));
this->dataPtr->terrainGroup->setFilenameConvention(
Ogre::String(prefix), Ogre::String("dat"));
math::Vector3d pos(
this->descriptor.Position().X() - 0.5 * this->descriptor.Size().X() +
0.5 * this->descriptor.Size().X() / sqrtN,
this->descriptor.Position().Y() - 0.5 * this->descriptor.Size().X() +
0.5 * this->descriptor.Size().X() / sqrtN,
this->descriptor.Position().Z() + minElevation);
this->dataPtr->terrainGroup->setOrigin(OgreConversions::Convert(pos));
this->ConfigureTerrainDefaults();
// Configure import settings
auto &defaultimp = this->dataPtr->terrainGroup->getDefaultImportSettings();
defaultimp.terrainSize = this->dataPtr->dataSize;
defaultimp.worldSize = this->descriptor.Size().X();
defaultimp.inputScale = 1.0;
defaultimp.minBatchSize = 17;
defaultimp.maxBatchSize = 65;
// textures. The default material generator takes two materials per layer.
// 1. diffuse_specular - diffuse texture with a specular map in the
// alpha channel
// 2. normal_height - normal map with a height map in the alpha channel
{
// number of texture layers
defaultimp.layerList.resize(this->descriptor.TextureCount());
// The worldSize decides how big each splat of textures will be.
// A smaller value will increase the resolution
for (unsigned int i = 0; i < this->descriptor.TextureCount(); ++i)
{
auto texture = this->descriptor.TextureByIndex(i);
defaultimp.layerList[i].worldSize = texture->Size();
defaultimp.layerList[i].textureNames.push_back(texture->Diffuse());
defaultimp.layerList[i].textureNames.push_back(texture->Normal());
}
}
this->dataPtr->terrainHashChanged = this->PrepareTerrain(terrainDirPath);
if (this->descriptor.UseTerrainPaging())
{
if (this->dataPtr->terrainHashChanged)
{
// Split the terrain. Every subterrain will be saved on disk and paged
this->SplitHeights(this->dataPtr->heights, nTerrains,
this->dataPtr->subTerrains);
}
this->dataPtr->pageManager = OGRE_NEW Ogre::PageManager();
this->dataPtr->pageManager->setPageProvider(
&this->dataPtr->dummyPageProvider);
// Add cameras
for (unsigned int i = 0; i < ogreScene->NodeCount(); ++i)
{
auto cam = std::dynamic_pointer_cast<OgreCamera>(
ogreScene->NodeByIndex(i));
if (nullptr != cam)
{
this->dataPtr->pageManager->addCamera(cam->Camera());
}
}
this->dataPtr->terrainPaging =
OGRE_NEW Ogre::TerrainPaging(this->dataPtr->pageManager);
this->dataPtr->world = this->dataPtr->pageManager->createWorld();
this->dataPtr->terrainPaging->createWorldSection(
this->dataPtr->world, this->dataPtr->terrainGroup,
this->dataPtr->loadRadiusFactor * this->descriptor.Size().X(),
this->dataPtr->holdRadiusFactor * this->descriptor.Size().X(),
0, 0, static_cast<unsigned int>(sqrtN) - 1,
static_cast<unsigned int>(sqrtN) - 1);
}
gzmsg << "Loading heightmap: " << this->descriptor.Name() << std::endl;
auto time = std::chrono::steady_clock::now();
for (int y = 0; y <= sqrtN - 1; ++y)
for (int x = 0; x <= sqrtN - 1; ++x)
this->DefineTerrain(x, y);
// use Gazebo shaders
this->CreateMaterial();
// Sync load since we want everything in place when we start
this->dataPtr->terrainGroup->loadAllTerrains(true);
gzmsg << "Heightmap loaded. Process took "
<< std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - time).count()
<< " ms." << std::endl;
// Calculate blend maps
if (!this->dataPtr->loadedFromCache)
{
auto ti = this->dataPtr->terrainGroup->getTerrainIterator();
while (ti.hasMoreElements())
{
this->InitBlendMaps(ti.getNext()->instance);
}
}
this->dataPtr->terrainGroup->freeTemporaryResources();
}
//////////////////////////////////////////////////
void OgreHeightmap::PreRender()
{
if (nullptr == this->dataPtr->terrainGroup)
{
return;
}
// Make sure the heightmap finishes loading by processing responses until all
// derived data and terrains are loaded
if (this->dataPtr->terrainGroup->isDerivedDataUpdateInProgress())
{
Ogre::Root::getSingleton().getWorkQueue()->processResponses();
return;
}
auto ti = this->dataPtr->terrainGroup->getTerrainIterator();
while (ti.hasMoreElements())
{
auto *t = ti.getNext()->instance;
if (!t->isLoaded())
{
Ogre::Root::getSingleton().getWorkQueue()->processResponses();
return;
}
}
// save the terrain once its loaded
if (this->dataPtr->loadedFromCache || this->dataPtr->savedToCache)
{
return;
}
// saving an ogre terrain data file can take quite some time for large
// terrains.
gzmsg << "Saving heightmap cache data to "
<< common::joinPaths(this->dataPtr->pagingDir, this->descriptor.Name())
<< std::endl;
auto time = std::chrono::steady_clock::now();
bool saved{false};
try
{
this->dataPtr->terrainGroup->saveAllTerrains(true);
saved = true;
}
catch(Ogre::Exception &_e)
{
gzerr << "Failed to save heightmap: " << _e.what() << std::endl;
}
if (saved)
{
gzmsg << "Heightmap cache data saved. Process took "
<< std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - time).count()
<< " ms." << std::endl;
}
this->dataPtr->savedToCache = true;
}
///////////////////////////////////////////////////
void OgreHeightmap::ConfigureTerrainDefaults()
{
if (this->dataPtr->terrainGlobals != nullptr)
return;
// Configure global
this->dataPtr->terrainGlobals = new Ogre::TerrainGlobalOptions();
// Vertex compression breaks anything, e.g. Gpu laser, that tries to build
// a depth map.
this->dataPtr->terrainGlobals->setUseVertexCompressionWhenAvailable(false);
// MaxPixelError: Decides how precise our terrain is going to be.
// A lower number will mean a more accurate terrain, at the cost of
// performance (because of more vertices)
this->dataPtr->terrainGlobals->setMaxPixelError(this->dataPtr->maxPixelError);
// CompositeMapDistance: decides how far the Ogre terrain will render
// the lightmapped terrain.
this->dataPtr->terrainGlobals->setCompositeMapDistance(2000);
// Vertex compression breaks anything, e.g. Gpu laser, that tries to build
// a depth map.
this->dataPtr->terrainGlobals->setUseVertexCompressionWhenAvailable(false);
this->dataPtr->terrainGlobals->setSkirtSize(this->dataPtr->skirtLength);
this->dataPtr->terrainGlobals->setCastsDynamicShadows(
this->dataPtr->castShadows);
auto ogreScene = std::dynamic_pointer_cast<OgreScene>(this->Scene());
this->dataPtr->terrainGlobals->setCompositeMapAmbient(
ogreScene->OgreSceneManager()->getAmbientLight());
// Get the first directional light
OgreDirectionalLightPtr directionalLight;
for (unsigned int i = 0; i < this->Scene()->LightCount(); ++i)
{
auto light = std::dynamic_pointer_cast<OgreDirectionalLight>(
this->Scene()->LightByIndex(i));
if (nullptr != light)
{
directionalLight = light;
break;
}
}
// Important to set these so that the terrain knows what to use for
// derived (non-realtime) data
if (directionalLight)
{
this->dataPtr->terrainGlobals->setLightMapDirection(
OgreConversions::Convert(directionalLight->Direction()));
auto const &lightDiffuse = directionalLight->DiffuseColor();
this->dataPtr->terrainGlobals->setCompositeMapDiffuse(
OgreConversions::Convert(lightDiffuse));
}
else
{
this->dataPtr->terrainGlobals->setLightMapDirection(
Ogre::Vector3(0, 0, -1));
this->dataPtr->terrainGlobals->setCompositeMapDiffuse(
Ogre::ColourValue(0.6f, 0.6f, 0.6f, 1.0f));
}
}
//////////////////////////////////////////////////
bool OgreHeightmap::PrepareTerrain(
const std::string &_terrainDirPath)
{
// Compute the original heightmap's image.
auto heightmapHash = common::sha1<std::vector<float>>(this->dataPtr->heights);
// Check if the terrain hash exists
auto terrainHashFullPath = common::joinPaths(_terrainDirPath,
this->dataPtr->kHashFilename);
bool updateHash = true;
if (common::exists(terrainHashFullPath))
{
try
{
// Read the terrain hash
std::ifstream in(terrainHashFullPath.c_str());
std::stringstream buffer;
buffer << in.rdbuf();
std::string terrainHash(buffer.str());
updateHash = terrainHash != heightmapHash;
}
catch(std::ifstream::failure &_e)
{
gzerr << "Terrain paging error: Unable to read terrain hash ["
<< _e.what() << "]" << std::endl;
}
}
// Update the terrain hash and split the terrain into small pieces
if (updateHash)
{
this->UpdateTerrainHash(heightmapHash, _terrainDirPath);
}
return updateHash;
}
//////////////////////////////////////////////////
void OgreHeightmap::UpdateTerrainHash(const std::string &_hash,
const std::string &_terrainDir)
{
// Create the subdirectories if they do not exist
common::createDirectories(_terrainDir);
auto terrainHashFullPath = common::joinPaths(_terrainDir,
this->dataPtr->kHashFilename);
// Update the terrain hash
std::ofstream terrainHashFile;
terrainHashFile.open(terrainHashFullPath.c_str());
// Throw an error if we couldn't open the file for writing.
if (terrainHashFile.is_open())
{
terrainHashFile << _hash;
terrainHashFile.close();
}
else
{
gzerr << "Unable to open file for creating a terrain hash: [" +
terrainHashFullPath + "]" << std::endl;
}
}
//////////////////////////////////////////////////
void OgreHeightmap::SplitHeights(const std::vector<float> &_heightmap,
int _n, std::vector<std::vector<float>> &_v)
{
// We support splitting the terrain in 4 or 16 pieces
if (_n != 4 && _n != 16)
{
gzerr << "Invalid number of terrain divisions [" << _n
<< "]. It should be 4 or 16." << std::endl;
return;
}
int count = 0;
int width = static_cast<int>(sqrt(_heightmap.size()));
int newWidth = static_cast<int>(1 + (width - 1) / sqrt(_n));
// Memory allocation
_v.resize(_n);
for (int tileR = 0; tileR < sqrt(_n); ++tileR)
{
int tileIndex = static_cast<int>(tileR * sqrt(_n));
for (int row = 0; row < newWidth - 1; ++row)
{
for (int tileC = 0; tileC < sqrt(_n); ++tileC)
{
for (int col = 0; col < newWidth - 1; ++col)
{
_v[tileIndex].push_back(_heightmap[count]);
++count;
}
// Copy last value into the last column
_v[tileIndex].push_back(_v[tileIndex].back());
tileIndex = static_cast<int>(tileR * sqrt(_n) +
(tileIndex + 1) % static_cast<int>(sqrt(_n)));
}
++count;
}
// Copy the last row
for (int i = 0; i < sqrt(_n); ++i)
{
tileIndex = static_cast<int>(tileR * sqrt(_n) + i);
std::vector<float> lastRow(_v[tileIndex].end() - newWidth,
_v[tileIndex].end());
_v[tileIndex].insert(_v[tileIndex].end(),
lastRow.begin(), lastRow.end());
}
}
}
/////////////////////////////////////////////////
void OgreHeightmap::DefineTerrain(int _x, int _y)
{
Ogre::String filename = this->dataPtr->terrainGroup->generateFilename(_x, _y);
bool resourceExists =
Ogre::ResourceGroupManager::getSingleton().resourceExists(
this->dataPtr->terrainGroup->getResourceGroup(), filename);
if (resourceExists && !this->dataPtr->terrainHashChanged)
{
gzmsg << "Loading heightmap cache data: " << filename << std::endl;
this->dataPtr->terrainGroup->defineTerrain(_x, _y);
this->dataPtr->loadedFromCache = true;
}
else
{
if (this->dataPtr->splitTerrain)
{
// generate the subterrains if needed
if (this->dataPtr->subTerrains.empty())
{
this->SplitHeights(this->dataPtr->heights,
this->dataPtr->numTerrainSubdivisions,
this->dataPtr->subTerrains);
}
this->dataPtr->terrainGroup->defineTerrain(_x, _y,
&this->dataPtr->subTerrains[this->dataPtr->terrainIdx][0]);
++this->dataPtr->terrainIdx;
}
else
{
this->dataPtr->terrainGroup->defineTerrain(_x, _y,
&this->dataPtr->heights[0]);
}
}
}
/////////////////////////////////////////////////
void OgreHeightmap::CreateMaterial()
{
if (!this->dataPtr->materialName.empty())
{
// init custom material generator
Ogre::TerrainMaterialGeneratorPtr terrainMaterialGenerator;
TerrainMaterial *terrainMaterial = OGRE_NEW TerrainMaterial(