-
Notifications
You must be signed in to change notification settings - Fork 51
/
Ogre2GpuRays.cc
1406 lines (1237 loc) · 48.8 KB
/
Ogre2GpuRays.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) 2018 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 <ignition/math/Vector2.hh>
#include <ignition/math/Vector3.hh>
#include <ignition/common/Console.hh>
#include <ignition/math/Helpers.hh>
#include "ignition/rendering/ogre2/Ogre2Camera.hh"
#include "ignition/rendering/ogre2/Ogre2GpuRays.hh"
#include "ignition/rendering/ogre2/Ogre2RenderEngine.hh"
#include "ignition/rendering/RenderTypes.hh"
#include "ignition/rendering/ogre2/Ogre2Conversions.hh"
#include "ignition/rendering/ogre2/Ogre2ParticleEmitter.hh"
#include "ignition/rendering/ogre2/Ogre2RenderTarget.hh"
#include "ignition/rendering/ogre2/Ogre2RenderTypes.hh"
#include "ignition/rendering/ogre2/Ogre2Scene.hh"
#include "ignition/rendering/ogre2/Ogre2Sensor.hh"
#include "ignition/rendering/ogre2/Ogre2Visual.hh"
#include "Ogre2IgnHlmsCustomizations.hh"
#include "Ogre2ParticleNoiseListener.hh"
#ifdef _MSC_VER
#pragma warning(push, 0)
#endif
#include <Compositor/OgreCompositorManager2.h>
#include <Compositor/OgreCompositorWorkspace.h>
#include <Compositor/Pass/PassQuad/OgreCompositorPassQuadDef.h>
#include <Compositor/Pass/PassScene/OgreCompositorPassSceneDef.h>
#include <OgreDepthBuffer.h>
#include <OgreItem.h>
#include <OgreRoot.h>
#include <OgreSceneManager.h>
#include <OgreTechnique.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
namespace ignition
{
namespace rendering
{
inline namespace IGNITION_RENDERING_VERSION_NAMESPACE {
//
/// \brief Helper class for switching the ogre item's material to laser retro
/// source material when a thermal camera is being rendered.
class Ogre2LaserRetroMaterialSwitcher : public Ogre::Camera::Listener
{
/// \brief constructor
/// \param[in] _scene the scene manager responsible for rendering
public: explicit Ogre2LaserRetroMaterialSwitcher(Ogre2ScenePtr _scene);
/// \brief destructor
public: ~Ogre2LaserRetroMaterialSwitcher() = default;
/// \brief Callback when a camera is about to be rendered
/// \param[in] _evt Ogre camera which is about to render
private: virtual void cameraPreRenderScene(
Ogre::Camera *_cam) override;
/// \brief Callback when a camera is finisned being rendered
/// \param[in] _evt Ogre camera which has already rendered
private: virtual void cameraPostRenderScene(
Ogre::Camera *_cam) override;
/// \brief Scene manager
private: Ogre2ScenePtr scene = nullptr;
/// \brief Pointer to the laser retro source material
private: Ogre::MaterialPtr laserRetroSourceMaterial;
/// \brief Custom parameter index of laser retro value in an ogre subitem.
/// This has to match the custom index specifed in LaserRetroSource material
/// script in media/materials/scripts/gpu_rays.material
private: const unsigned int customParamIdx = 10u;
/// \brief A map of ogre sub item pointer to their original hlms material
private: std::map<Ogre::SubItem *, Ogre::HlmsDatablock *> datablockMap;
};
}
}
}
/// \internal
/// \brief Private data for the Ogre2GpuRays class
class ignition::rendering::Ogre2GpuRaysPrivate
{
/// \brief Event triggered when new gpu rays range data are available.
/// \param[in] _frame New frame containing raw gpu rays data.
/// \param[in] _width Width of frame.
/// \param[in] _height Height of frame.
/// \param[in] _channel Number of channels
/// \param[in] _format Format of frame.
public: ignition::common::EventT<void(const float *,
unsigned int, unsigned int, unsigned int,
const std::string &)> newGpuRaysFrame;
/// \brief Raw buffer of gpu rays data.
public: float *gpuRaysBuffer = nullptr;
/// \brief Outgoing gpu rays data, used by newGpuRaysFrame event.
public: float *gpuRaysScan = nullptr;
/// \brief Pointer to Ogre material for the first rendering pass.
public: Ogre::MaterialPtr matFirstPass;
/// \brief Pointer to Ogre material for the second rendering pass.
public: Ogre::MaterialPtr matSecondPass;
/// \brief Cubemap cameras
public: Ogre::Camera *cubeCam[6];
/// \brief Texture packed with cubemap face and uv data
public: Ogre::TextureGpu *cubeUVTexture = nullptr;
/// \brief Set of cubemap faces that are needed to generate the final
/// range data
public: std::set<unsigned int> cubeFaceIdx;
/// \brief 1st pass compositor workspace definition
public: std::string ogreCompositorWorkspaceDef1st;
/// \brief 1st pass compositor node definition
public: std::string ogreCompositorNodeDef1st;
/// \brief 1st pass compositor workspace. One for each cubemap camera
public: Ogre::CompositorWorkspace *ogreCompositorWorkspace1st[6];
/// \brief 2nd pass compositor workspace definition
public: std::string ogreCompositorWorkspaceDef2nd;
/// \brief 1st pass compositor node definition
public: std::string ogreCompositorNodeDef2nd;
/// \brief 2nd pass compositor workspace.
public: Ogre::CompositorWorkspace *ogreCompositorWorkspace2nd = nullptr;
/// \brief An array of first pass textures. One for each cubemap camera.
public: Ogre::TextureGpu * firstPassTextures[6];
/// \brief Second pass texture.
public: Ogre::TextureGpu * secondPassTexture = nullptr;
/// \brief Pointer to the ogre camera
public: Ogre::Camera *ogreCamera = nullptr;
/// \brief Image width of first pass.
public: unsigned int w1st = 0u;
/// \brief Image height of first pass.
public: unsigned int h1st = 0u;
/// \brief Image width of second pass.
public: unsigned int w2nd = 0u;
/// \brief Image height of second pass.
public: unsigned int h2nd = 0u;
/// \brief Dummy render texture for the gpu rays
public: RenderTexturePtr renderTexture;
/// \brief Pointer to material switcher
public: std::unique_ptr<Ogre2LaserRetroMaterialSwitcher>
laserRetroMaterialSwitcher[6];
/// \brief standard deviation of particle noise
public: double particleStddev = 0.01;
/// \brief Listener for setting particle noise value based on particle
/// emitter region
public: std::unique_ptr<Ogre2ParticleNoiseListener> particleNoiseListener[6];
/// \brief Near clip plane for cube camera
public: float nearClipCube = 0.0;
/// \brief Min allowed angle in radians;
public: const math::Angle kMinAllowedAngle = 1e-4;
};
using namespace ignition;
using namespace rendering;
//////////////////////////////////////////////////
Ogre2LaserRetroMaterialSwitcher::Ogre2LaserRetroMaterialSwitcher(
Ogre2ScenePtr _scene)
{
this->scene = _scene;
// plain opaque material
Ogre::ResourcePtr res =
Ogre::MaterialManager::getSingleton().load("LaserRetroSource",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
this->laserRetroSourceMaterial = res.staticCast<Ogre::Material>();
this->laserRetroSourceMaterial->load();
}
//////////////////////////////////////////////////
void Ogre2LaserRetroMaterialSwitcher::cameraPreRenderScene(
Ogre::Camera * /*_cam*/)
{
{
auto engine = Ogre2RenderEngine::Instance();
Ogre2IgnHlmsCustomizations &hlmsCustomizations =
engine->HlmsCustomizations();
Ogre::Pass *pass =
this->laserRetroSourceMaterial->getBestTechnique()->getPass(0u);
pass->getVertexProgramParameters()->setNamedConstant(
"ignMinClipDistance", hlmsCustomizations.minDistanceClip );
}
// swap item to use v1 shader material
// Note: keep an eye out for performance impact on switching materials
// on the fly. We are not doing this often so should be ok.
this->datablockMap.clear();
auto itor = this->scene->OgreSceneManager()->getMovableObjectIterator(
Ogre::ItemFactory::FACTORY_TYPE_NAME);
while (itor.hasMoreElements())
{
Ogre::MovableObject *object = itor.peekNext();
Ogre::Item *item = static_cast<Ogre::Item *>(object);
std::string laserRetroKey = "laser_retro";
float retroValue = 0.0f;
// get visual
Ogre::Any userAny = item->getUserObjectBindings().getUserAny();
if (!userAny.isEmpty() && userAny.getType() == typeid(unsigned int))
{
VisualPtr result;
try
{
result = this->scene->VisualById(Ogre::any_cast<unsigned int>(userAny));
}
catch(Ogre::Exception &e)
{
ignerr << "Ogre Error:" << e.getFullDescription() << "\n";
}
Ogre2VisualPtr ogreVisual =
std::dynamic_pointer_cast<Ogre2Visual>(result);
if (ogreVisual->HasUserData(laserRetroKey))
{
// get laser_retro
Variant tempLaserRetro = ogreVisual->UserData(laserRetroKey);
try
{
retroValue = std::get<float>(tempLaserRetro);
}
catch(...)
{
try
{
retroValue = static_cast<float>(std::get<double>(tempLaserRetro));
}
catch(...)
{
try
{
retroValue = std::get<int>(tempLaserRetro);
}
catch(std::bad_variant_access &e)
{
ignerr << "Error casting user data: " << e.what() << "\n";
}
}
}
}
// only accept positive laser retro value
retroValue = std::max(retroValue, 0.0f);
}
for (unsigned int i = 0; i < item->getNumSubItems(); ++i)
{
Ogre::SubItem *subItem = item->getSubItem(i);
// limit laser retro value to 2000 (as in gazebo)
if (retroValue > 2000.0f)
{
retroValue = 2000.0f;
}
float color = retroValue / 2000.0f;
subItem->setCustomParameter(this->customParamIdx,
Ogre::Vector4(color, color, color, 1.0));
Ogre::HlmsDatablock *datablock = subItem->getDatablock();
this->datablockMap[subItem] = datablock;
subItem->setMaterial(this->laserRetroSourceMaterial);
}
itor.moveNext();
}
}
//////////////////////////////////////////////////
void Ogre2LaserRetroMaterialSwitcher::cameraPostRenderScene(
Ogre::Camera * /*_cam*/)
{
// restore item to use hlms material
for (auto it : this->datablockMap)
{
Ogre::SubItem *subItem = it.first;
subItem->setDatablock(it.second);
}
Ogre::Pass *pass =
this->laserRetroSourceMaterial->getBestTechnique()->getPass(0u);
pass->getVertexProgramParameters()->setNamedConstant(
"ignMinClipDistance", 0.0f );
}
//////////////////////////////////////////////////
Ogre2GpuRays::Ogre2GpuRays()
: dataPtr(new Ogre2GpuRaysPrivate)
{
// r = depth, g = retro, and b = n/a
this->channels = 3u;
for (unsigned int i = 0; i < 6u; ++i)
{
this->dataPtr->cubeCam[i] = nullptr;
this->dataPtr->ogreCompositorWorkspace1st[i] = nullptr;
this->dataPtr->laserRetroMaterialSwitcher[i] = nullptr;
}
}
//////////////////////////////////////////////////
Ogre2GpuRays::~Ogre2GpuRays()
{
this->Destroy();
}
//////////////////////////////////////////////////
void Ogre2GpuRays::Init()
{
BaseGpuRays::Init();
// create internal camera
this->CreateCamera();
// create dummy render texture
this->CreateRenderTexture();
}
//////////////////////////////////////////////////
void Ogre2GpuRays::Destroy()
{
if (this->dataPtr->gpuRaysBuffer)
{
delete [] this->dataPtr->gpuRaysBuffer;
this->dataPtr->gpuRaysBuffer = nullptr;
}
if (this->dataPtr->gpuRaysScan)
{
delete [] this->dataPtr->gpuRaysScan;
this->dataPtr->gpuRaysScan = nullptr;
}
auto engine = Ogre2RenderEngine::Instance();
auto ogreRoot = engine->OgreRoot();
if (this->dataPtr->cubeUVTexture)
{
ogreRoot->getRenderSystem()->getTextureGpuManager()->destroyTexture(
this->dataPtr->cubeUVTexture);
this->dataPtr->cubeUVTexture = nullptr;
}
Ogre::CompositorManager2 *ogreCompMgr = ogreRoot->getCompositorManager2();
// remove 1st pass textures, material, compositors
for (auto i : this->dataPtr->cubeFaceIdx)
{
if (this->dataPtr->firstPassTextures[i])
{
ogreRoot->getRenderSystem()->getTextureGpuManager()->destroyTexture(
this->dataPtr->firstPassTextures[i]);
this->dataPtr->firstPassTextures[i] = nullptr;
}
if (this->dataPtr->ogreCompositorWorkspace1st[i])
{
ogreCompMgr->removeWorkspace(
this->dataPtr->ogreCompositorWorkspace1st[i]);
this->dataPtr->ogreCompositorWorkspace1st[i] = nullptr;
}
}
if (this->dataPtr->matFirstPass)
{
Ogre::MaterialManager::getSingleton().remove(
this->dataPtr->matFirstPass->getName());
this->dataPtr->matFirstPass.reset();
}
if (!this->dataPtr->ogreCompositorWorkspaceDef1st.empty())
{
ogreCompMgr->removeWorkspaceDefinition(
this->dataPtr->ogreCompositorWorkspaceDef1st);
ogreCompMgr->removeNodeDefinition(
this->dataPtr->ogreCompositorNodeDef1st);
this->dataPtr->ogreCompositorWorkspaceDef1st.clear();
}
// remove 2nd pass texture, material, compositor
if (this->dataPtr->secondPassTexture)
{
ogreRoot->getRenderSystem()->getTextureGpuManager()->destroyTexture(
this->dataPtr->secondPassTexture);
this->dataPtr->secondPassTexture = nullptr;
}
if (this->dataPtr->matSecondPass)
{
Ogre::MaterialManager::getSingleton().remove(
this->dataPtr->matSecondPass->getName());
this->dataPtr->matSecondPass.reset();
}
if (!this->dataPtr->ogreCompositorWorkspaceDef2nd.empty())
{
ogreCompMgr->removeWorkspace(this->dataPtr->ogreCompositorWorkspace2nd);
ogreCompMgr->removeWorkspaceDefinition(
this->dataPtr->ogreCompositorWorkspaceDef2nd);
ogreCompMgr->removeNodeDefinition(
this->dataPtr->ogreCompositorNodeDef2nd);
this->dataPtr->ogreCompositorWorkspaceDef2nd.clear();
}
}
/////////////////////////////////////////////////
void Ogre2GpuRays::CreateRenderTexture()
{
RenderTexturePtr base = this->scene->CreateRenderTexture();
this->dataPtr->renderTexture =
std::dynamic_pointer_cast<Ogre2RenderTexture>(base);
this->dataPtr->renderTexture->SetWidth(1);
this->dataPtr->renderTexture->SetHeight(1);
}
/////////////////////////////////////////////////
void Ogre2GpuRays::CreateCamera()
{
// Create ogre camera object
Ogre::SceneManager *ogreSceneManager = this->scene->OgreSceneManager();
if (ogreSceneManager == nullptr)
{
ignerr << "Scene manager cannot be obtained" << std::endl;
return;
}
this->dataPtr->ogreCamera = ogreSceneManager->createCamera(
this->Name() + "_Camera");
if (this->dataPtr->ogreCamera == nullptr)
{
ignerr << "Ogre camera cannot be created" << std::endl;
return;
}
// by default, ogre2 cameras are attached to root scene node
this->dataPtr->ogreCamera->detachFromParent();
this->ogreNode->attachObject(this->dataPtr->ogreCamera);
this->dataPtr->ogreCamera->setFixedYawAxis(false);
this->dataPtr->ogreCamera->yaw(Ogre::Degree(-90));
this->dataPtr->ogreCamera->roll(Ogre::Degree(-90));
this->dataPtr->ogreCamera->setAutoAspectRatio(true);
}
/////////////////////////////////////////////////
void Ogre2GpuRays::ConfigureCamera()
{
// horizontal gpu rays setup
auto hfovAngle = this->AngleMax() - this->AngleMin();
hfovAngle = std::max(this->dataPtr->kMinAllowedAngle, hfovAngle);
this->SetHFOV(hfovAngle);
// vertical laser setup
double vfovAngle;
if (this->VerticalRangeCount() > 1)
{
vfovAngle = std::max(this->dataPtr->kMinAllowedAngle.Radian(),
(this->VerticalAngleMax() - this->VerticalAngleMin()).Radian());
}
else
{
vfovAngle = 0;
if (this->VerticalAngleMax() != this->VerticalAngleMin())
{
ignwarn << "Only one vertical ray but vertical min. and max. angle "
"are not equal. Min. angle is used.\n";
this->SetVerticalAngleMax(this->VerticalAngleMin().Radian());
}
}
this->SetVFOV(vfovAngle);
// Configure first pass texture size
// Each cubemap texture covers 90 deg FOV so determine number of samples
// within the view for both horizontal and vertical FOV
unsigned int hs = static_cast<unsigned int>(
IGN_PI * 0.5 / hfovAngle.Radian() * this->RangeCount());
unsigned int vs = static_cast<unsigned int>(
IGN_PI * 0.5 / vfovAngle * this->VerticalRangeCount());
// get the max number from the two
unsigned int v = std::max(hs, vs);
// round to next highest power of 2
// https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
// limit min texture size to 128
// This is needed for large fov with low sample count,
// e.g. 360 degrees and only 4 samples. Otherwise the depth data returned are
// inaccurate.
// \todo(anyone) For small fov, we shouldn't need such a high min texture size
// requirement, e.g. a single ray lidar only needs 1x1 texture. Look for ways
// to compute the optimal min texture size
unsigned int min1stPassSamples = 128u;
// limit max texture size to 1024
unsigned int max1stPassSamples = 1024u;
unsigned int samples1stPass =
std::clamp(v, min1stPassSamples, max1stPassSamples);
this->Set1stTextureSize(samples1stPass, samples1stPass);
// Configure second pass texture size
this->SetRangeCount(this->RangeCount(), this->VerticalRangeCount());
// Set ogre cam properties
this->dataPtr->ogreCamera->setNearClipDistance(this->dataPtr->nearClipCube);
this->dataPtr->ogreCamera->setFarClipDistance(this->FarClipPlane());
}
/////////////////////////////////////////////////////////
math::Vector2d Ogre2GpuRays::SampleCubemap(const math::Vector3d &_v,
unsigned int &_faceIndex)
{
math::Vector3d vAbs = _v.Abs();
double ma;
math::Vector2d uv;
if (vAbs.Z() >= vAbs.X() && vAbs.Z() >= vAbs.Y())
{
_faceIndex = _v.Z() < 0.0 ? 5.0 : 4.0;
ma = 0.5 / vAbs.Z();
uv = math::Vector2d(_v.Z() < 0.0 ? -_v.X() : _v.X(), -_v.Y());
}
else if (vAbs.Y() >= vAbs.X())
{
_faceIndex = _v.Y() < 0.0 ? 3.0 : 2.0;
ma = 0.5 / vAbs.Y();
uv = math::Vector2d(_v.X(), _v.Y() < 0.0 ? -_v.Z() : _v.Z());
}
else
{
_faceIndex = _v.X() < 0.0 ? 1.0 : 0.0;
ma = 0.5 / vAbs.X();
uv = math::Vector2d(_v.X() < 0.0 ? _v.Z() : -_v.Z(), -_v.Y());
}
return uv * ma + 0.5;
}
/////////////////////////////////////////////////////////
void Ogre2GpuRays::CreateSampleTexture()
{
double min = this->AngleMin().Radian();
double max = this->AngleMax().Radian();
double vmin = this->VerticalAngleMin().Radian();
double vmax = this->VerticalAngleMax().Radian();
double hAngle = std::max(this->dataPtr->kMinAllowedAngle.Radian(), max - min);
double vAngle = std::max(this->dataPtr->kMinAllowedAngle.Radian(),
vmax - vmin);
double hStep = hAngle / static_cast<double>(this->dataPtr->w2nd-1);
double vStep = 1.0;
// non-planar case
if (this->dataPtr->h2nd > 1)
vStep = vAngle / static_cast<double>(this->dataPtr->h2nd-1);
// create an RGB texture (cubeUVTex) to pack info that tells the shaders how
// to sample from the cubemap textures.
// Each pixel packs the follow data:
// R: u coordinate on the cubemap face
// G: v coordinate on the cubemap face
// B: cubemap face index
// A: unused
// this texture is passed to the 2nd pass fragment shader
auto engine = Ogre2RenderEngine::Instance();
auto ogreRoot = engine->OgreRoot();
Ogre::TextureGpuManager *textureMgr =
ogreRoot->getRenderSystem()->getTextureGpuManager();
std::string texName = this->Name() + "_samplerTex";
this->dataPtr->cubeUVTexture =
textureMgr->createOrRetrieveTexture(
texName,
Ogre::GpuPageOutStrategy::SaveToSystemRam,
Ogre::TextureFlags::ManualTexture,
Ogre::TextureTypes::Type2D,
Ogre::BLANKSTRING,
0u);
this->dataPtr->cubeUVTexture->setTextureType(Ogre::TextureTypes::Type2D);
this->dataPtr->cubeUVTexture->setResolution(
this->dataPtr->w2nd, this->dataPtr->h2nd);
this->dataPtr->cubeUVTexture->setNumMipmaps(1u);
this->dataPtr->cubeUVTexture->setPixelFormat(Ogre::PFG_RGBA32_FLOAT);
const Ogre::uint32 rowAlignment = 1u;
const size_t dataSize = Ogre::PixelFormatGpuUtils::getSizeBytes(
this->dataPtr->cubeUVTexture->getWidth(),
this->dataPtr->cubeUVTexture->getHeight(),
this->dataPtr->cubeUVTexture->getDepth(),
this->dataPtr->cubeUVTexture->getNumSlices(),
this->dataPtr->cubeUVTexture->getPixelFormat(),
rowAlignment);
const size_t bytesPerRow =
this->dataPtr->cubeUVTexture->_getSysRamCopyBytesPerRow( 0 );
float *pDest = reinterpret_cast<float*>(
OGRE_MALLOC_SIMD(dataSize, Ogre::MEMCATEGORY_RESOURCE));
double v = vmin;
int index = 0;
for (unsigned int i = 0; i < this->dataPtr->h2nd; ++i)
{
double h = min;
for (unsigned int j = 0; j < this->dataPtr->w2nd; ++j)
{
// set up dir vector to sample from a standard Y up cubemap
math::Vector3d ray(0, 0, 1);
ray.Normalize();
math::Quaterniond pitch(math::Vector3d(1, 0, 0), -v);
math::Quaterniond yaw(math::Vector3d(0, 1, 0), -h);
math::Vector3d dir = yaw * pitch * ray;
unsigned int faceIdx;
math::Vector2d uv = this->SampleCubemap(dir, faceIdx);
this->dataPtr->cubeFaceIdx.insert(faceIdx);
// igndbg << "p(" << pitch << ") y(" << yaw << "): " << dir << " | "
// << uv << " | " << faceIdx << std::endl;
// u
pDest[index++] = uv.X();
// v
pDest[index++] = uv.Y();
// face
pDest[index++] = faceIdx;
// unused
pDest[index++] = 1.0;
h += hStep;
}
v += vStep;
}
this->dataPtr->cubeUVTexture->_transitionTo(
Ogre::GpuResidency::Resident,
reinterpret_cast<Ogre::uint8*>(pDest) );
this->dataPtr->cubeUVTexture->_setNextResidencyStatus(
Ogre::GpuResidency::Resident);
// We have to upload the data via a StagingTexture, which acts as an
// intermediate stash memory that is both visible to CPU and GPU.
Ogre::StagingTexture *stagingTexture = textureMgr->getStagingTexture(
this->dataPtr->cubeUVTexture->getWidth(),
this->dataPtr->cubeUVTexture->getHeight(),
this->dataPtr->cubeUVTexture->getDepth(),
this->dataPtr->cubeUVTexture->getNumSlices(),
this->dataPtr->cubeUVTexture->getPixelFormat() );
stagingTexture->startMapRegion();
// Map region of the staging texture. This function can be called from
// any thread after startMapRegion has already been called.
Ogre::TextureBox texBox = stagingTexture->mapRegion(
this->dataPtr->cubeUVTexture->getWidth(),
this->dataPtr->cubeUVTexture->getHeight(),
this->dataPtr->cubeUVTexture->getDepth(),
this->dataPtr->cubeUVTexture->getNumSlices(),
this->dataPtr->cubeUVTexture->getPixelFormat());
texBox.copyFrom(
pDest,
this->dataPtr->cubeUVTexture->getWidth(),
this->dataPtr->cubeUVTexture->getHeight(),
bytesPerRow);
stagingTexture->stopMapRegion();
stagingTexture->upload(texBox, this->dataPtr->cubeUVTexture, 0, 0, 0, true);
// Tell the TextureGpuManager we're done with this StagingTexture.
// Otherwise it will leak.
textureMgr->removeStagingTexture(stagingTexture);
stagingTexture = 0;
// Do not free the pointer if texture's paging strategy is
// GpuPageOutStrategy::AlwaysKeepSystemRamCopy
this->dataPtr->cubeUVTexture->notifyDataIsReady();
}
/////////////////////////////////////////////////////////
void Ogre2GpuRays::Setup1stPass()
{
// Load 1st pass material
// The GpuRaysScan1st material is defined in script (gpu_rays.material).
// We need to clone it since we are going to modify its uniform variables
std::string mat1stName = "GpuRaysScan1st";
Ogre::MaterialPtr mat1st =
Ogre::MaterialManager::getSingleton().getByName(mat1stName);
this->dataPtr->matFirstPass = mat1st->clone(this->Name() + "_" + mat1stName);
this->dataPtr->matFirstPass->load();
Ogre::Pass *pass = this->dataPtr->matFirstPass->getTechnique(0)->getPass(0);
Ogre::GpuProgramParametersSharedPtr psParams =
pass->getFragmentProgramParameters();
// Set the uniform variables (see gpu_rays_1st_pass_fs.glsl).
// The projectParams is used to linearize depth buffer data
// The other params are used to clamp the range output
Ogre::Vector2 projectionAB =
this->dataPtr->ogreCamera->getProjectionParamsAB();
double projectionA = projectionAB.x;
double projectionB = projectionAB.y;
projectionB /= this->FarClipPlane();
psParams->setNamedConstant("projectionParams",
Ogre::Vector2(projectionA, projectionB));
psParams->setNamedConstant("near",
static_cast<float>(this->NearClipPlane()));
psParams->setNamedConstant("far",
static_cast<float>(this->FarClipPlane()));
psParams->setNamedConstant("max",
static_cast<float>(this->dataMaxVal));
psParams->setNamedConstant("min",
static_cast<float>(this->dataMinVal));
psParams->setNamedConstant("particleStddev",
static_cast<float>(this->dataPtr->particleStddev));
// Create 1st pass compositor
auto engine = Ogre2RenderEngine::Instance();
auto ogreRoot = engine->OgreRoot();
Ogre::CompositorManager2 *ogreCompMgr = ogreRoot->getCompositorManager2();
// We need to programmatically create the compositor because we need to
// configure it to use the cloned 1st pass material created earlier.
// The compositor workspace definition is equivalent to the following
// ogre compositor script:
// compositor_node GpuRays1stPass
// {
// in 0 rt_input
// texture depthTexture target_width target_height PFG_D32_FLOAT
// texture colorTexture target_width target_height PF_R8G8B8
// texture particleTexture target_width target_height PF_L8
// texture particleDepthTexture target_width target_height PF_D32_FLOAT
// target colorTexture
// {
// pass clear
// {
// colour_value 0.0 0.0 0.0 1.0
// }
// pass render_scene
// {
// visibility_mask 0x11011111
// }
// }
// target particleTexture
// {
// pass clear
// {
// colour_value 0.0 0.0 0.0 1.0
// }
// pass render_scene
// {
// visibility_mask 0.00100000
// }
// }
// target rt_input
// {
// pass clear
// {
// colour_value 0.0 0.0 0.0 1.0
// }
// pass render_quad
// {
// material GpuRaysScan1st // Use copy instead of original
// input 0 depthTexture
// input 1 colorTexture
// quad_normals camera_far_corners_view_space
// }
// }
// out 0 rt_input
// }
std::string wsDefName = "GpuRays1stPassWorkspace_" + this->Name();
this->dataPtr->ogreCompositorWorkspaceDef1st = wsDefName;
if (!ogreCompMgr->hasWorkspaceDefinition(wsDefName))
{
std::string nodeDefName = wsDefName + "/Node";
this->dataPtr->ogreCompositorNodeDef1st = nodeDefName;
Ogre::CompositorNodeDef *nodeDef =
ogreCompMgr->addNodeDefinition(nodeDefName);
// Input texture
nodeDef->addTextureSourceName("rt_input", 0,
Ogre::TextureDefinitionBase::TEXTURE_INPUT);
Ogre::TextureDefinitionBase::TextureDefinition *depthTexDef =
nodeDef->addTextureDefinition("depthTexture");
depthTexDef->textureType = Ogre::TextureTypes::Type2D;
depthTexDef->width = 0;
depthTexDef->height = 0;
depthTexDef->depthOrSlices = 1;
depthTexDef->numMipmaps = 0;
depthTexDef->widthFactor = 1;
depthTexDef->heightFactor = 1;
depthTexDef->fsaa = "0";
depthTexDef->format = Ogre::PFG_D32_FLOAT;
depthTexDef->textureFlags &= ~Ogre::TextureFlags::Uav;
depthTexDef->depthBufferId = Ogre::DepthBuffer::POOL_DEFAULT;
depthTexDef->depthBufferFormat = Ogre::PFG_UNKNOWN;
Ogre::TextureDefinitionBase::TextureDefinition *colorTexDef =
nodeDef->addTextureDefinition("colorTexture");
colorTexDef->textureType = Ogre::TextureTypes::Type2D;
colorTexDef->width = 0;
colorTexDef->height = 0;
colorTexDef->depthOrSlices = 1;
colorTexDef->widthFactor = 1;
colorTexDef->heightFactor = 1;
// We need at least 16-bit because otherwise 256 values are not enough to
// store all retro value range
colorTexDef->format = Ogre::PFG_R16_UNORM;
colorTexDef->fsaa = "0";
colorTexDef->textureFlags &= ~Ogre::TextureFlags::Uav;
colorTexDef->depthBufferId = Ogre::DepthBuffer::POOL_DEFAULT;
colorTexDef->depthBufferFormat = Ogre::PFG_D32_FLOAT;
colorTexDef->preferDepthTexture = true;
// Auto setup the RTV then manually override the depth buffer so
// it uses the one we created (and thus we can sample from it later)
Ogre::RenderTargetViewDef *rtv =
nodeDef->addRenderTextureView("colorTexture");
rtv->setForTextureDefinition("colorTexture", colorTexDef);
rtv->depthAttachment.textureName = "depthTexture";
Ogre::TextureDefinitionBase::TextureDefinition *particleTexDef =
nodeDef->addTextureDefinition("particleTexture");
particleTexDef->textureType = Ogre::TextureTypes::Type2D;
particleTexDef->width = 0;
particleTexDef->height = 0;
particleTexDef->depthOrSlices = 1;
particleTexDef->numMipmaps = 0;
particleTexDef->widthFactor = 0.5;
particleTexDef->heightFactor = 0.5;
particleTexDef->format = Ogre::PFG_RGBA8_UNORM;
particleTexDef->fsaa = "0";
particleTexDef->textureFlags &= ~Ogre::TextureFlags::Uav;
particleTexDef->depthBufferId = Ogre::DepthBuffer::POOL_DEFAULT;
particleTexDef->depthBufferFormat = Ogre::PFG_D32_FLOAT;
particleTexDef->preferDepthTexture = true;
Ogre::TextureDefinitionBase::TextureDefinition *particleDepthTexDef =
nodeDef->addTextureDefinition("particleDepthTexture");
particleDepthTexDef->textureType = Ogre::TextureTypes::Type2D;
particleDepthTexDef->width = 0;
particleDepthTexDef->height = 0;
particleDepthTexDef->depthOrSlices = 1;
particleDepthTexDef->numMipmaps = 0;
particleDepthTexDef->widthFactor = 0.5;
particleDepthTexDef->heightFactor = 0.5;
particleDepthTexDef->format = Ogre::PFG_D32_FLOAT;
particleDepthTexDef->fsaa = "0";
particleDepthTexDef->depthBufferId = Ogre::DepthBuffer::POOL_NON_SHAREABLE;
particleDepthTexDef->textureFlags &= ~Ogre::TextureFlags::Uav;
particleDepthTexDef->depthBufferFormat = Ogre::PFG_UNKNOWN;
// Auto setup the RTV then manually override the depth buffer so
// it uses the one we created (and thus we can sample from it later)
Ogre::RenderTargetViewDef *rtvParticleTexture =
nodeDef->addRenderTextureView("particleTexture");
rtvParticleTexture->setForTextureDefinition("particleTexture",
particleTexDef);
rtvParticleTexture->depthAttachment.textureName = "particleDepthTexture";
nodeDef->setNumTargetPass(3);
Ogre::CompositorTargetDef *colorTargetDef =
nodeDef->addTargetPass("colorTexture");
colorTargetDef->setNumPasses(1);
{
// scene pass
Ogre::CompositorPassSceneDef *passScene =
static_cast<Ogre::CompositorPassSceneDef *>(
colorTargetDef->addPass(Ogre::PASS_SCENE));
passScene->setAllLoadActions(Ogre::LoadAction::Clear);
passScene->setAllClearColours(Ogre::ColourValue(0, 0, 0));
// set camera custom visibility mask when rendering laser retro
// todo(anyone) currently in this color + depth pass, lidar sees all
// objects, including ones without laser_retro set. So the lidar outputs
// data containing depth data + some non-zero retro value for all
// objects. If we want to output a retro value of zero for objects
// without laser_retro, one possible approach could be to separate out
// the color and depth pass:
// 1: color pass that see only objects with laser_retro by using custom
// visibility mask
// 2: depth pass that see all objects
// Then assemble these data in the final quad pass.
passScene->mVisibilityMask = IGN_VISIBILITY_ALL &
~Ogre2ParticleEmitter::kParticleVisibilityFlags;
}
Ogre::CompositorTargetDef *particleTargetDef =
nodeDef->addTargetPass("particleTexture");
particleTargetDef->setNumPasses(1);
{
// scene pass
Ogre::CompositorPassSceneDef *passScene =
static_cast<Ogre::CompositorPassSceneDef *>(
particleTargetDef->addPass(Ogre::PASS_SCENE));
passScene->setAllLoadActions(Ogre::LoadAction::Clear);
passScene->setAllClearColours(Ogre::ColourValue::Black);
// set camera custom visibility mask when rendering particles
passScene->mVisibilityMask =
Ogre2ParticleEmitter::kParticleVisibilityFlags;
}
// rt_input target - converts depth to range
Ogre::CompositorTargetDef *inputTargetDef =
nodeDef->addTargetPass("rt_input");
inputTargetDef->setNumPasses(1);
{
// quad pass
Ogre::CompositorPassQuadDef *passQuad =
static_cast<Ogre::CompositorPassQuadDef *>(
inputTargetDef->addPass(Ogre::PASS_QUAD));
passQuad->setAllLoadActions(Ogre::LoadAction::Clear);
passQuad->setAllClearColours(Ogre::ColourValue(
this->dataMaxVal, 0, 1.0));
passQuad->mMaterialName = this->dataPtr->matFirstPass->getName();
passQuad->addQuadTextureSource(0, "depthTexture");
passQuad->addQuadTextureSource(1, "colorTexture");
passQuad->addQuadTextureSource(2, "particleDepthTexture");
passQuad->addQuadTextureSource(3, "particleTexture");
passQuad->mFrustumCorners =
Ogre::CompositorPassQuadDef::VIEW_SPACE_CORNERS;
}
nodeDef->mapOutputChannel(0, "rt_input");
Ogre::CompositorWorkspaceDef *workDef =
ogreCompMgr->addWorkspaceDefinition(wsDefName);
workDef->connectExternal(0, nodeDef->getName(), 0);
}
Ogre::CompositorWorkspaceDef *wsDef =
ogreCompMgr->getWorkspaceDefinition(wsDefName);
if (!wsDef)
{
ignerr << "Unable to add workspace definition [" << wsDefName << "] "
<< " for " << this->Name();
}
// create cubemap cameras and render to texture using 1st pass compositor
Ogre::SceneManager *ogreSceneManager = this->scene->OgreSceneManager();
for (auto i : this->dataPtr->cubeFaceIdx)
{
this->dataPtr->cubeCam[i] = ogreSceneManager->createCamera(
this->Name() + "_env" + std::to_string(i));
this->dataPtr->cubeCam[i]->detachFromParent();
this->ogreNode->attachObject(this->dataPtr->cubeCam[i]);
this->dataPtr->cubeCam[i]->setFOVy(Ogre::Degree(90));
this->dataPtr->cubeCam[i]->setAspectRatio(1);
this->dataPtr->cubeCam[i]->setNearClipDistance(this->dataPtr->nearClipCube);
this->dataPtr->cubeCam[i]->setFarClipDistance(this->FarClipPlane());
this->dataPtr->cubeCam[i]->setFixedYawAxis(false);
this->dataPtr->cubeCam[i]->yaw(Ogre::Degree(-90));
this->dataPtr->cubeCam[i]->roll(Ogre::Degree(-90));
// orient camera to create cubemap
if (i == 0)
this->dataPtr->cubeCam[i]->yaw(Ogre::Degree(-90));
else if (i == 1)
this->dataPtr->cubeCam[i]->yaw(Ogre::Degree(90));
else if (i == 2)
this->dataPtr->cubeCam[i]->pitch(Ogre::Degree(90));
else if (i == 3)
this->dataPtr->cubeCam[i]->pitch(Ogre::Degree(-90));
else if (i == 5)
this->dataPtr->cubeCam[i]->yaw(Ogre::Degree(180));