/
IGPluginModelComposition.cpp
1465 lines (1220 loc) · 56.3 KB
/
IGPluginModelComposition.cpp
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) 2015 Compro Computer Services
//#* http://openig.compro.net
//#*
//#* Source available at: https://github.com/CCSI-CSSI/MuseOpenIG
//#*
//#* This software is released under the LGPL.
//#*
//#* This software is free software; you can redistribute it and/or modify
//#* it under the terms of the GNU Lesser General Public License as published
//#* by the Free Software Foundation; either version 2.1 of the License, or
//#* (at your option) any later version.
//#*
//#* This software is distributed in the hope that it will be useful,
//#* but WITHOUT ANY WARRANTY; without even the implied warranty of
//#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
//#* the GNU Lesser General Public License for more details.
//#*
//#* You should have received a copy of the GNU Lesser General Public License
//#* along with this library; if not, write to the Free Software
//#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//#*
//#* Please direct any questions or comments to the OpenIG Forums
//#* Email address: openig@compro.net
//#*
//#*
//#* Please direct any questions or comments to the OpenIG Forums
//#* Email address: openig@compro.net
//#*
//#*
//#*****************************************************************************
#include <Core-PluginBase/Plugin.h>
#include <Core-PluginBase/PluginContext.h>
#include <Core-Base/ImageGenerator.h>
#include <Core-Base/StringUtils.h>
#include <Core-Base/Mathematics.h>
#include <Core-Base/Animation.h>
#include <Core-Base/Configuration.h>
#include <Core-Base/IDPool.h>
#include <Core-Base/FileSystem.h>
#include <Core-Utils/TextureCache.h>
#include <Core-OpenIG/RenderBins.h>
#include <Core-OpenIG/Engine.h>
#include <osg/Version>
#include <osg/ValueObject>
#include <osg/Image>
#include <osg/Texture2D>
#include <osg/TextureCubeMap>
#include <osg/Point>
#include <osg/BlendFunc>
#include <osg/Material>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#include <osgDB/ReadFile>
#include <osgDB/XmlParser>
#include <osgSim/LightPointNode>
#include <osgSim/LightPoint>
#include <boost/thread.hpp>
#include <sstream>
using namespace osg;
namespace OpenIG { namespace Plugins {
class ModelCompositionPlugin : public OpenIG::PluginBase::Plugin
{
public:
ModelCompositionPlugin()
: _subentityId(10000)
, _environmentalMapSlot(2)
, _diffuseSlot(0)
, _aoSlot(3)
, _autoLightId(1000)
, _todBasedEnvironmentalLightingFactor(1.0)
{
std::string resourcePath = OpenIG::Base::FileSystem::path(OpenIG::Base::FileSystem::Resources, "../resources");
_textureCache.addPath(resourcePath);
_textureCubeMapCache.addPath(resourcePath);
}
virtual std::string getName() { return "ModelComposition"; }
virtual std::string getDescription( ) { return "Compose model based on xml defintion"; }
virtual std::string getVersion() { return "2.0.0"; }
virtual std::string getAuthor() { return "ComPro, Nick"; }
virtual void update(OpenIG::PluginBase::PluginContext& context)
{
if (_dayMaterial.valid() && _nightMaterial.valid() && _runtimeMaterial.valid())
{
osg::Vec4 day_ambient;
osg::Vec4 day_diffuse;
osg::Vec4 day_specular;
float day_shininess;
osg::Vec4 night_ambient;
osg::Vec4 night_diffuse;
osg::Vec4 night_specular;
float night_shininess;
osg::Vec4 ambient;
osg::Vec4 diffuse;
osg::Vec4 specular;
float shininess;
_todBasedEnvironmentalLightingFactor = 1.0;
day_ambient = _dayMaterial->getAmbient(osg::Material::FRONT_AND_BACK);
day_diffuse = _dayMaterial->getDiffuse(osg::Material::FRONT_AND_BACK);
day_specular = _dayMaterial->getSpecular(osg::Material::FRONT_AND_BACK);
day_shininess = _dayMaterial->getShininess(osg::Material::FRONT_AND_BACK);
night_ambient = _nightMaterial->getAmbient(osg::Material::FRONT_AND_BACK);
night_diffuse = _nightMaterial->getDiffuse(osg::Material::FRONT_AND_BACK);
night_specular = _nightMaterial->getSpecular(osg::Material::FRONT_AND_BACK);
night_shininess = _nightMaterial->getShininess(osg::Material::FRONT_AND_BACK);
float factor = context.getImageGenerator()->getSunOrMoonLight()->getLight()->getAmbient().g();
ambient = day_ambient*factor + night_ambient*(1.f - factor);
diffuse = day_diffuse*factor + night_diffuse*(1.f - factor);
specular = day_specular*factor + night_specular*(1.f - factor);
shininess = day_shininess*factor + night_shininess*(1.f - factor);
_runtimeMaterial->setAmbient(osg::Material::FRONT_AND_BACK, ambient);
_runtimeMaterial->setDiffuse(osg::Material::FRONT_AND_BACK, diffuse);
_runtimeMaterial->setSpecular(osg::Material::FRONT_AND_BACK, specular);
_runtimeMaterial->setShininess(osg::Material::FRONT_AND_BACK, shininess);
_runtimeMaterial->setEmission(osg::Material::FRONT_AND_BACK,osg::Vec4(0,0,0,1));
}
}
// Some models does not come with a texture, only material
// we need to know this and not let override the global
// model material and set a flag (define) for the shader
class PreserveMaterialNodeVisitor : public osg::NodeVisitor
{
public:
PreserveMaterialNodeVisitor() : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) {}
virtual void apply(osg::Node& node)
{
osg::ref_ptr<osg::StateSet> ss = node.getOrCreateStateSet();
osg::ref_ptr<osg::StateAttribute> attr = ss->getAttribute(osg::StateAttribute::MATERIAL);
if (attr.valid())
{
ss->setAttributeAndModes(attr, osg::StateAttribute::ON | osg::StateAttribute::PROTECTED);
}
attr = ss->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
if (attr.valid())
{
// Here we protect the found materil
// and set the flag for the shader
ss->setTextureAttributeAndModes(0, attr, osg::StateAttribute::ON | osg::StateAttribute::PROTECTED);
ss->setDefine("TEXTURING", osg::StateAttribute::ON | osg::StateAttribute::PROTECTED);
}
traverse(node);
}
};
virtual void databaseRead(const std::string& fileName, osg::Node* node, const osgDB::Options*)
{
// Check or model definition if exists
// if not silently quit
if (!osgDB::fileExists(fileName + ".xml")) return;
// say it lod we have a XML file
osg::notify(osg::NOTICE) << "ModelComposition: (" << fileName << ") reading XML config:" << fileName + ".xml" << std::endl;
// we have some xml definition file and we process it
osgDB::XmlNode* root = osgDB::readXmlFile(fileName + ".xml");
if (!root || !root->children.size() || root->children.at(0)->name != "OpenIg-Model-Composition") return;
// a flag we read from the XML
bool preserveMaterial = false;
osgDB::XmlNode::Children::iterator itr = root->children.at(0)->children.begin();
for (; itr != root->children.at(0)->children.end(); ++itr)
{
if ((**itr).name == "PreserveMaterial")
{
preserveMaterial = (**itr).contents == "yes";
}
}
// Ok. We then process the model to
// set it all to use its materials
// without texture
if (preserveMaterial)
{
PreserveMaterialNodeVisitor nv;
node->accept(nv);
}
}
// we process lots of different tags here,
// so let keep them organizied into a map
struct TagValue
{
std::string value;
osgDB::XmlNode* node;
TagValue() : node(0) {}
};
typedef std::map< const std::string, TagValue > TagValueMap;
typedef std::multimap< const std::string, TagValue > TagValueMultiMap;
// Handy method that will fill a tagvalue map
// for an XmlNode
void readXmlNode(osgDB::XmlNode& node, TagValueMap& tags, TagValueMultiMap& mmtags)
{
osgDB::XmlNode::Children::iterator itr = node.children.begin();
for (; itr != node.children.end(); ++itr)
{
TagValue value;
value.value = (**itr).contents;
value.node = *itr;
tags[(**itr).name] = value;
mmtags.insert(std::pair<std::string, TagValue>((**itr).name, value));
}
}
void readXmlNode(osgDB::XmlNode& node, TagValueMap& tags)
{
osgDB::XmlNode::Children::iterator itr = node.children.begin();
for (; itr != node.children.end(); ++itr)
{
TagValue value;
value.value = (**itr).contents;
value.node = *itr;
tags[(**itr).name] = value;
}
}
void readXmlNode(osgDB::XmlNode& node, TagValueMultiMap& tags)
{
osgDB::XmlNode::Children::iterator itr = node.children.begin();
for (; itr != node.children.end(); ++itr)
{
TagValue value;
value.value = (**itr).contents;
value.node = *itr;
tags.insert(std::pair<std::string,TagValue>((**itr).name,value));
}
}
// We triger the ENVIRONMENTAL_FACTOR for
// the environmental mapping by the
// amount of light from the sun/moon to get
// better visual at darker times
struct UpdateEnvironmentalFactor : public osg::StateSet::Callback
{
UpdateEnvironmentalFactor(OpenIG::Base::ImageGenerator* ig, float factor)
: _ig(ig), _factor(factor)
{
}
virtual void operator() (osg::StateSet* ss, osg::NodeVisitor*)
{
std::ostringstream oss;
oss << _factor * _ig->getSunOrMoonLight()->getLight()->getDiffuse().r();
ss->setDefine("ENVIRONMENTAL_FACTOR", oss.str());
}
protected:
OpenIG::Base::ImageGenerator* _ig;
float _factor;
};
// Handy callback for update float uniforms
struct UpdateFloatUniformCallback : public osg::UniformCallback
{
UpdateFloatUniformCallback(float& value)
: _value(value)
{
}
virtual void operator () (osg::Uniform* u, osg::NodeVisitor*)
{
u->set(_value);
}
protected:
float& _value;
};
// a hook when an entity is added
// called from the IG
virtual void entityAdded(OpenIG::PluginBase::PluginContext& context, unsigned int id, osg::Node& entity, const std::string& fileName)
{
// entity was added. If the file does not exists
// we quit silently
if (!osgDB::fileExists(fileName + ".xml")) return;
// Say it loud, we have an XML model definition
osg::notify(osg::NOTICE) << "ModelComposition: Parsing XML for " << fileName << std::endl;
// We save these
_entity = &entity;
_ss = new osg::StateSet;
// Here a bit of paranoia
osgDB::XmlNode* root = osgDB::readXmlFile(fileName + ".xml");
if (!root || !root->children.size() || root->children.at(0)->name != "OpenIg-Model-Composition") return;
// we get the path and save
// it for texture lookup from the cache
_path = osgDB::getFilePath(fileName);
_textureCache.addPath(_path);
_textureCubeMapCache.addPath(_path);
// A sub-entities map. We need
// to keep track of all the
// submodels added
SubModelMap smm;
// Our tags with values
TagValueMultiMap mmtags;
TagValueMap tags;
// Read all the children
readXmlNode(*root->children.at(0), tags, mmtags);
// Iterate over lights
TagValueMultiMap::iterator itr = mmtags.find("Light");
while (itr != mmtags.end())
{
readLight((itr++)->second.node, entity, context, id);
if (itr == mmtags.end() || itr->first != "Light") break;
}
// Read the material
itr = mmtags.find("Material");
while (itr != mmtags.end())
{
readMaterial((itr++)->second.node);
if (itr == mmtags.end() || itr->first != "Material") break;
}
// Read the submodels
itr = mmtags.find("Sub-model");
while (itr != mmtags.end())
{
readSubmodel((itr++)->second.node, context, id, smm);
if (itr == mmtags.end() || itr->first != "Sub-model") break;
}
// Read animations
_entityWithSubmodels[id] = smm;
itr = mmtags.find("Animation");
while (itr != mmtags.end())
{
readAnimation((itr++)->second.node, context, id);
if (itr == mmtags.end() || itr->first != "Animation") break;
}
// Some other
_diffuseSlot = atoi(tags["Diffuse-Slot"].value.c_str());
_aoSlot = atoi(tags["Pre-Baked-Ambient-Occlusion-Texture-Slot"].value.c_str());
_environmentalMapSlot = atoi(tags["Environmental-Slot"].value.c_str());
_diffuseTextureName = tags["Diffuse-Texture"].value;
// setup ambiento occlusion
bool ao = tags["Ambient-Occlusion"].value == "yes";
if (ao)
{
std::string aotexture = tags["Pre-Baked-Ambient-Occlusion-Texture"].value;
float factor = atof(tags["Ambient-Occlusion-Factor"].value.c_str());
Texture2DPointer texture = _textureCache.get(aotexture);
if (texture.valid())
{
osg::notify(osg::NOTICE) << "ModelComposition: (" << fileName << ")" << " ao texture:" << aotexture << ", slot:" << _aoSlot << std::endl;
_ss->setDefine("AO");
_ss->setTextureAttributeAndModes(_aoSlot, texture, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
_ss->addUniform(new osg::Uniform("ambientOcclusionTexture", (int)_aoSlot), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE | osg::StateAttribute::PROTECTED);
_ss->addUniform(new osg::Uniform("ambientOcclusionFactor", factor), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE | osg::StateAttribute::PROTECTED);
}
}
// setup environmental mapping
// Read the 6 images of the env map
OpenIG::Base::StringUtils::StringList environmentalMaps;
environmentalMaps.push_back(tags["Environmental-Texture-Right"].value);
environmentalMaps.push_back(tags["Environmental-Texture-Left"].value);
environmentalMaps.push_back(tags["Environmental-Texture-Bottom"].value);
environmentalMaps.push_back(tags["Environmental-Texture-Top"].value);
environmentalMaps.push_back(tags["Environmental-Texture-Back"].value);
environmentalMaps.push_back(tags["Environmental-Texture-Front"].value);
TextureCubeMapPointer texture = _textureCubeMapCache.get(environmentalMaps);
if (texture.valid())
{
_ss->addUniform(new osg::Uniform("environmentalMapTexture", (int)_environmentalMapSlot), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE | osg::StateAttribute::PROTECTED);
_ss->setTextureAttributeAndModes(_environmentalMapSlot, texture, osg::StateAttribute::ON);
bool envmapping = tags["Environmental"].value == "yes";
osg::StateAttribute::OverrideValue value = 0;
switch (envmapping)
{
case true:
value = osg::StateAttribute::ON;
break;
case false:
value = osg::StateAttribute::OFF;
break;
}
_ss->setDefine("ENVIRONMENTAL", value);
_ss->setDefine("ENVIRONMENTAL_FACTOR", tags["Environmental-Factor"].value, value);
_ss->setUpdateCallback(new UpdateEnvironmentalFactor(context.getImageGenerator(), atof(tags["Environmental-Factor"].value.c_str())));
osg::Uniform* u = new osg::Uniform(osg::Uniform::FLOAT, "todBasedEnvironmentalLightingFactor", 1.f);
u->setUpdateCallback(new UpdateFloatUniformCallback(_todBasedEnvironmentalLightingFactor));
_ss->addUniform(u);
texture->setInternalFormat(GL_RGB);
texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
texture->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
texture->setFilter(osg::TextureCubeMap::MIN_FILTER, osg::TextureCubeMap::LINEAR);
texture->setFilter(osg::TextureCubeMap::MAG_FILTER, osg::TextureCubeMap::LINEAR);
}
// setup diffuse
Texture2DPointer diffuseTexture = _textureCache.get(_diffuseTextureName);
if (diffuseTexture.valid())
{
osg::notify(osg::NOTICE) << "ModelComposition: (" << fileName << ")" << " diffuse texture:" << _diffuseTextureName << ", slot:" << _diffuseSlot << std::endl;
_ss->setTextureAttributeAndModes(_diffuseSlot, diffuseTexture, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
_ss->addUniform(new osg::Uniform("baseTexture", (int)_diffuseSlot), osg::StateAttribute::ON | osg::StateAttribute::PROTECTED | osg::StateAttribute::OVERRIDE);
}
TagValueMap::const_iterator iterNormalMap = tags.find("NormalMap");
TagValueMap::const_iterator iterNormalMapSlot = tags.find("NormalMapSlot");
if (iterNormalMap!=tags.end()&&iterNormalMapSlot!=tags.end())
{
const std::string& normalMap = iterNormalMap->second.value;
int normalMapSlot = atoi(iterNormalMapSlot->second.value.c_str());
if (normalMap!="")
{
Texture2DPointer normalMapTexture = _textureCache.get(normalMap);
if (normalMapTexture.valid())
{
osg::notify(osg::NOTICE) << "ModelComposition: (" << fileName << ")" << " normal map texture:" << normalMap << ", slot:" << normalMapSlot << std::endl;
_ss->setTextureAttributeAndModes(normalMapSlot, normalMapTexture, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
_ss->addUniform(new osg::Uniform("normalMapSampler", (int)normalMapSlot), osg::StateAttribute::ON | osg::StateAttribute::PROTECTED | osg::StateAttribute::OVERRIDE);
_ss->setDefine("HAS_NORMAL_MAP");
}
}
}
// shadowing, set deffault to casting
int ReceivesShadowTraversalMask = 0x1;
int CastsShadowTraversalMask = 0x2;
int NoShadow = 0x4;
entity.setNodeMask(NoShadow);
bool shadowing = tags["Shadowing"].value == "yes";
if (shadowing)
{
_ss->setDefine("SHADOWING", osg::StateAttribute::ON);
}
else
_ss->setDefine("SHADOWING", osg::StateAttribute::OFF);
std::string shadow = tags["Shadow"].value;
if (shadow == "CAST")
entity.setNodeMask(CastsShadowTraversalMask);
if (shadow == "RECEIVE")
entity.setNodeMask(ReceivesShadowTraversalMask);
if (shadow == "CAST-AND-RECEIVE")
entity.setNodeMask(CastsShadowTraversalMask | ReceivesShadowTraversalMask);
// setup the material if valid
#if 0
if (_dayMaterial.valid() && _nightMaterial.valid())
{
_runtimeMaterial = new osg::Material(*_dayMaterial);
entity.getOrCreateStateSet()->setAttributeAndModes(_runtimeMaterial,osg::StateAttribute::ON|osg::StateAttribute::PROTECTED|osg::StateAttribute::OVERRIDE);
}
_ss->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
_ss->setMode(GL_BLEND, osg::StateAttribute::ON);
#endif
// set our stateset
entity.asGroup()->getChild(0)->setStateSet(_ss);
}
protected:
unsigned int _subentityId;
std::string _path;
osg::observer_ptr<osg::Node> _entity;
osg::ref_ptr<osg::StateSet> _ss;
osg::ref_ptr<osg::Material> _dayMaterial;
osg::ref_ptr<osg::Material> _nightMaterial;
osg::ref_ptr<osg::Material> _runtimeMaterial;
osg::ref_ptr<osg::Program> _spriteProgram;
osg::ref_ptr<osg::Program> _lightPointProgram;
unsigned int _autoLightId;
std::string _diffuseTextureName;
unsigned int _diffuseSlot;
bool _aoOcclustion;
unsigned int _aoSlot;
float _environmentalFactor;
unsigned int _environmentalMapSlot;
bool _normalmapslot;
float _todBasedEnvironmentalLightingFactor;
// This is struct we keep for sub-entity definition
struct SubModelEntry
{
std::string _name;
std::string _fileName;
std::string _position;
std::string _orientation;
std::string _limits;
unsigned int _id;
osg::Vec3 _originalOrientation;
osg::Vec3 _originalPosition;
bool _environmental;
std::string _diffuse;
std::string _ambient;
std::string _specular;
std::string _shininess;
bool _environmentalSet;
float _environmentalFactor;
bool _materialSet;
osg::ref_ptr<osg::Material> _material;
SubModelEntry() : _id(0), _environmental(true), _environmentalFactor(0.5f), _environmentalSet(false), _materialSet(false) {}
bool isValid() const
{
return _name.size() && _fileName.size()!=0 && _position.size()!=0 && _orientation.size()!=0 && _limits.size()!=0;
}
};
typedef std::map< std::string, SubModelEntry > SubModelMap;
typedef std::map< std::string, SubModelEntry >::iterator SubModelMapIterator;
typedef std::map< std::string, SubModelEntry >::const_iterator SubModelMapConstIterator;
typedef std::map< unsigned int, SubModelMap > EntityWithSubmodelsMap;
typedef std::map< unsigned int, SubModelMap >::iterator EntityWithSubmodelsMapIterator;
typedef std::map< unsigned int, SubModelMap >::const_iterator EntityWithSubmodelsMapConstIterator;
EntityWithSubmodelsMap _entityWithSubmodels;
// Struct for animation blinking pulses
struct LightAnimationPulses
{
double _duration;
osg::Vec4 _color;
LightAnimationPulses()
: _duration(0.0)
{
}
};
typedef std::vector<LightAnimationPulses> LightAnimationPulsesList;
// Light attributes
struct LightAttribs
{
osg::Vec3 _position;
osg::Vec4 _color;
osg::Vec3 _orientation;
osg::Vec3 _offset;
bool _animated;
LightAnimationPulsesList _pulses;
bool _real;
double _minPixelSize;
double _maxPixelSize;
double _minPixelSizeMultiplierForSprites;
float _radius;
double _brightness;
double _constAttenuation;
double _fStartRange;
double _fEndRange;
double _fSpotInnerAngle;
double _fSpotOuterAngle;
std::string _spriteTexture;
LightAttribs()
: _animated(false)
, _real(false)
, _minPixelSize(2)
, _minPixelSizeMultiplierForSprites(1)
, _maxPixelSize(5)
, _brightness(1)
, _constAttenuation(5)
, _radius(1)
{
}
};
// Callback for Lights blinking
struct LightBlinkUpdateCallback : public osg::NodeCallback
{
LightBlinkUpdateCallback(const LightAttribs& light, OpenIG::Base::ImageGenerator* ig)
: _firstFrame(true)
, _light(light)
, _ig(ig)
, _currentPulse(0)
{
}
virtual void operator()(osg::Node* node, osg::NodeVisitor*)
{
if (_light._pulses.size() == 0) return;
osg::Timer_t now = osg::Timer::instance()->tick();
if (_firstFrame)
{
_lastUpdateTime = now;
_firstFrame = false;
}
double dt = osg::Timer::instance()->delta_s(_lastUpdateTime,now);
if (dt >= _light._pulses.at(_currentPulse)._duration)
{
unsigned int lightId = 0;
node->getUserValue("lightId",lightId);
if (lightId == 0) return;
bool on = true;
node->getUserValue("lightOn",on);
on = !on;
_ig->enableLight(lightId,on,false);
node->setUserValue("lightOn",(bool)on);
osgSim::LightPointNode* lpn = dynamic_cast<osgSim::LightPointNode*>(node);
if (lpn)
{
osgSim::LightPoint& lp = lpn->getLightPoint(0);
lp._on = on;
}
_lastUpdateTime = now;
_currentPulse = (_currentPulse+1) % _light._pulses.size();
}
}
bool _firstFrame;
osg::Timer_t _lastUpdateTime;
LightAttribs _light;
OpenIG::Base::ImageGenerator* _ig;
unsigned int _currentPulse;
};
void setUpSpriteStateSetProgram()
{
static bool checkedProgram = false;
if (checkedProgram)
{
return;
}
checkedProgram = true;
#if defined(_WIN32)
std::string resourcesPath = OpenIG::Base::FileSystem::path(OpenIG::Base::FileSystem::Resources, "../resources");
#else
std::string resourcesPath = OpenIG::Base::FileSystem::path(OpenIG::Base::FileSystem::Resources, "../../openig/resources");
#endif
std::string strVS = OpenIG::Base::FileSystem::readFileIntoString(resourcesPath + "/shaders/sprite_bb_vs.glsl");
std::string strGS = OpenIG::Base::FileSystem::readFileIntoString(resourcesPath + "/shaders/sprite_bb_gs.glsl");
std::string strPS = OpenIG::Base::FileSystem::readFileIntoString(resourcesPath + "/shaders/sprite_bb_ps.glsl");
if (strVS!=""&&strPS!=""&&strGS!="")
{
osg::notify(osg::NOTICE)<<"Model Composition: Loaded sprite programs (vs, gs, ps)"<<std::endl;
_spriteProgram = new osg::Program;
_spriteProgram->addShader(new osg::Shader(osg::Shader::VERTEX , strVS));
_spriteProgram->addShader(new osg::Shader(osg::Shader::GEOMETRY, strGS));
_spriteProgram->addShader(new osg::Shader(osg::Shader::FRAGMENT, strPS));
}
else
{
osg::notify(osg::NOTICE)<<"Model Composition: Error: could not load sprite programs (vs, gs, ps)"<<std::endl;
}
}
TextureCache _textureCache;
TextureCubeMapCache _textureCubeMapCache;
static bool useLogZDepthBuffer(void)
{
std::string strLogZDepthBuffer = OpenIG::Base::Configuration::instance()->getConfig("LogZDepthBuffer","yes");
if (strLogZDepthBuffer.compare(0, 3, "yes") == 0)
return true;
else
return false;
}
void setUpSpriteStateSet(osgSim::LightPointNode& lpn, const LightAttribs& def, OpenIG::Base::ImageGenerator* ig)
{
if (def._spriteTexture.empty())
{
osg::notify(osg::NOTICE)<<"Empty sprite texture!"<<std::endl;
return;
}
setUpSpriteStateSetProgram();
if (_spriteProgram.valid()==false)
{
osg::notify(osg::NOTICE)<<"Empty sprite program!"<<std::endl;
return;
}
osg::ref_ptr<osg::Texture2D> spriteTexture = _textureCache.get(def._spriteTexture);
osg::StateSet* stateSet = new osg::StateSet();
stateSet->setRenderBinDetails(MOVING_SPRITE_LIGHT_POINTS_RENDER_BIN, "DepthSortedBin");
// Turn off our lighting. We will use our own shader, primarily because we use logarithmic depth buffer,
// but also because we could have an optional sprite texture
stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF|osg::StateAttribute::PROTECTED|osg::StateAttribute::OVERRIDE);
osg::StateAttribute::OverrideValue val = osg::StateAttribute::ON|osg::StateAttribute::PROTECTED;
stateSet->setTextureAttributeAndModes(0, spriteTexture, val);
stateSet->addUniform(new osg::Uniform("spriteTexture", 0), val);
if (useLogZDepthBuffer())
{
stateSet->setDefine("USE_LOG_DEPTH_BUFFER");
}
static const float radiusMultiplier = 0.25f;
osg::Vec4f vSpriteDimensions(def._minPixelSize*def._minPixelSizeMultiplierForSprites, def._maxPixelSize, def._radius*radiusMultiplier, 0);
stateSet->addUniform(new osg::Uniform("spriteDimensions", vSpriteDimensions), val);
stateSet->setAttributeAndModes(_spriteProgram, val);
// Override the state set because the LightPoint node uses an internal singleton stateset
lpn.setStateSet(stateSet);
}
void setUpLightPointStateSetProgram()
{
static bool checkedProgram = false;
if (checkedProgram)
{
return;
}
checkedProgram = true;
#if defined(_WIN32)
std::string resourcesPath = OpenIG::Base::FileSystem::path(OpenIG::Base::FileSystem::Resources, "../resources");
#else
std::string resourcesPath = OpenIG::Base::FileSystem::path(OpenIG::Base::FileSystem::Resources, "../../openig/resources");
#endif
std::string strVS = OpenIG::Base::FileSystem::readFileIntoString(resourcesPath+"/shaders/lightpoint_vs.glsl");
std::string strPS = OpenIG::Base::FileSystem::readFileIntoString(resourcesPath+"/shaders/lightpoint_ps.glsl");
if (strVS!=""&&strPS!="")
{
osg::notify(osg::NOTICE)<<"Model Composition: Loaded light point (fallback) programs"<<std::endl;
_lightPointProgram = new osg::Program;
_lightPointProgram->addShader(new osg::Shader(osg::Shader::VERTEX , strVS));
_lightPointProgram->addShader(new osg::Shader(osg::Shader::FRAGMENT, strPS));
}
else
{
osg::notify(osg::NOTICE)<<"Model Composition: Error: could not load light point (fallback) programs"<<std::endl;
}
}
void setUpLightPointStateSet(osgSim::LightPointNode& lpn, const LightAttribs& def, OpenIG::Base::ImageGenerator* ig)
{
setUpLightPointStateSetProgram();
if (_lightPointProgram.valid()==false)
{
std::cerr<<"Empty light point program!"<<std::endl;
return;
}
osg::StateSet* stateSet = lpn.getOrCreateStateSet();
stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF|osg::StateAttribute::PROTECTED|osg::StateAttribute::OVERRIDE);
stateSet->setAttributeAndModes(_lightPointProgram, osg::StateAttribute::ON|osg::StateAttribute::PROTECTED|osg::StateAttribute::OVERRIDE);
if (useLogZDepthBuffer())
{
stateSet->setDefine("USE_LOG_DEPTH_BUFFER");
}
}
void readLight(osgDB::XmlNode* node, osg::Node& entity, OpenIG::PluginBase::PluginContext& context, unsigned int entityId)
{
LightAttribs light;
OpenIG::Base::LightType lightType = OpenIG::Base::LT_POINT;
TagValueMap tags;
readXmlNode(*node, tags);
// Read the color
std::string color = tags["Color"].value;
OpenIG::Base::StringUtils::Tokens tokens = OpenIG::Base::StringUtils::instance()->tokenize(color);
if (tokens.size() == 4)
{
float r = atof(tokens.at(0).c_str());
float g = atof(tokens.at(1).c_str());
float b = atof(tokens.at(2).c_str());
float a = atof(tokens.at(3).c_str());
light._color = osg::Vec4(r, g, b, a);
}
// POsition
std::string position = tags["Position"].value;
tokens = OpenIG::Base::StringUtils::instance()->tokenize(position);
if (tokens.size() == 3)
{
float x = atof(tokens.at(0).c_str());
float y = atof(tokens.at(1).c_str());
float z = atof(tokens.at(2).c_str());
light._position = osg::Vec3(x, y, z);
}
// Animation pulses
std::string pulses = tags["Animation-Pulses"].value;
tokens = OpenIG::Base::StringUtils::instance()->tokenize(pulses, ",");
for (size_t i = 0; i < tokens.size(); ++i)
{
OpenIG::Base::StringUtils::Tokens ltokens = OpenIG::Base::StringUtils::instance()->tokenize(tokens.at(i));
if (ltokens.size() == 5)
{
LightAnimationPulses pulse;
pulse._duration = atof(ltokens.at(0).c_str());
float r = atof(ltokens.at(1).c_str());
float g = atof(ltokens.at(2).c_str());
float b = atof(ltokens.at(3).c_str());
float a = atof(ltokens.at(4).c_str());
pulse._color = osg::Vec4(r, g, b, a);
light._pulses.push_back(pulse);
}
light._animated = light._pulses.size() != 0;
}
// Orientation
tokens = OpenIG::Base::StringUtils::instance()->tokenize(tags["Orientation"].value);
if (tokens.size() == 3)
{
float x = atof(tokens.at(0).c_str());
float y = atof(tokens.at(1).c_str());
float z = atof(tokens.at(2).c_str());
light._orientation = osg::Vec3(x, y, z);
lightType = OpenIG::Base::LT_SPOT;
}
// Offset for the OpenIG light
tokens = OpenIG::Base::StringUtils::instance()->tokenize(tags["Real-Light-Offset"].value);
if (tokens.size() == 3)
{
float x = atof(tokens.at(0).c_str());
float y = atof(tokens.at(1).c_str());
float z = atof(tokens.at(2).c_str());
light._offset = osg::Vec3(x, y, z);
}
// The sprite texture with its world size
tokens = OpenIG::Base::StringUtils::instance()->tokenize(tags["SpriteTexture"].value);
if (tokens.size() == 1)
{
light._spriteTexture = tokens.at(0);
//std::cerr<<"Sprite Texture: "<<light._spriteTexture<<std::endl;
}
tokens = OpenIG::Base::StringUtils::instance()->tokenize(tags["Radius"].value);
if (tokens.size() == 1)
{
light._radius = atof(tokens.at(0).c_str());
}
// Some other tags
light._real = tags["Use-Real-Light"].value == "yes";
light._brightness = atof(tags["Brightness"].value.c_str());
light._minPixelSize = osg::maximum(atof(tags["MinPixelSize"].value.c_str()),1.0);
light._maxPixelSize = osg::maximum(atof(tags["MaxPixelSize"].value.c_str()), 1.0);
light._minPixelSizeMultiplierForSprites = osg::maximum(atof(tags["MinPixelSizeMultiplierForSprites"].value.c_str()),1.0);
light._constAttenuation = atof(tags["ConstAttenuation"].value.c_str());
light._fStartRange = atof(tags["StartRange"].value.c_str());
light._fEndRange = atof(tags["EndRange"].value.c_str());
light._fSpotInnerAngle = atof(tags["SpotInnerAngle"].value.c_str());
light._fSpotOuterAngle = atof(tags["SpotOuterAngle"].value.c_str());
// Setup the light point
osg::ref_ptr<osgSim::LightPointNode> lpn = new osgSim::LightPointNode;
lpn->setCullingActive(false);
// Let find if we have foward+ available
// if not, no sprites either, till fixed
bool forwardPlusPluginAvailable = false;
// Look up for the F+ plugin
OpenIG::Engine* openIG = dynamic_cast<OpenIG::Engine*>(context.getImageGenerator());
if (openIG)
{
const OpenIG::PluginBase::PluginHost::PluginsMap& plugins = openIG->getPlugins();
OpenIG::PluginBase::PluginHost::PluginsMap::const_iterator itr = plugins.begin();
for (; itr != plugins.end(); ++itr)
{
if (itr->second->getName() == "ForwardPlusLighting")
{
forwardPlusPluginAvailable = true;
break;
}
}
}
//lpn->setPointSprite();
//if (light._spriteTexture != std::string("") && forwardPlusPluginAvailable)
if (light._spriteTexture != std::string(""))
{
setUpSpriteStateSet(*lpn, light, context.getImageGenerator());
}
else
{
setUpLightPointStateSet(*lpn, light, context.getImageGenerator());
}
if (light._animated)
{
lpn->setUpdateCallback(new LightBlinkUpdateCallback(light,context.getImageGenerator()));
}
lpn->setMinPixelSize(light._minPixelSize);
lpn->setMaxPixelSize(light._maxPixelSize);
osgSim::LightPoint lp(true,light._position,light._color);
lp._blendingMode = osgSim::LightPoint::ADDITIVE;
lpn->addLightPoint(lp);
entity.asGroup()->addChild(lpn);
OpenIG::Base::IDPool::instance()->getNextId("Real-Lights",_autoLightId);
lpn->setUserValue("lightId",(unsigned int)_autoLightId);
lpn->setUserValue("lightOn",(bool)true);
if (light._real)
{
OpenIG::Base::LightAttributes la;
la.diffuse = light._color;
la.ambient = osg::Vec4(0,0,0,1);
la.specular = osg::Vec4(0,0,0,1);
la.constantAttenuation = light._constAttenuation;
la.brightness = light._brightness;
la.spotCutoff = 20;
// PPP:
la.fStartRange = light._fStartRange;
la.fEndRange = light._fEndRange;
la.fSpotInnerAngle = light._fSpotInnerAngle;
la.fSpotOuterAngle = light._fSpotOuterAngle;
la.lightType = lightType;