/
DatabasePager.cpp
2109 lines (1694 loc) · 75.4 KB
/
DatabasePager.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
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library 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
* OpenSceneGraph Public License for more details.
*/
#include <osgDB/DatabasePager>
#include <osgDB/WriteFile>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#include <osgDB/Registry>
#include <osg/Geode>
#include <osg/Timer>
#include <osg/Texture>
#include <osg/Notify>
#include <osg/ProxyNode>
#include <osg/ApplicationUsage>
#include <OpenThreads/ScopedLock>
#include <algorithm>
#include <functional>
#include <set>
#ifdef WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
using namespace osgDB;
using namespace OpenThreads;
static osg::ApplicationUsageProxy DatabasePager_e0(osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_DO_PRE_COMPILE <ON/OFF>","Switch on or off the pre compile of OpenGL object database pager.");
static osg::ApplicationUsageProxy DatabasePager_e1(osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_MINIMUM_COMPILE_TIME_PER_FRAME <float>","minimum compile time alloted to compiling OpenGL objects per frame in database pager.");
static osg::ApplicationUsageProxy DatabasePager_e2(osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_MAXIMUM_OBJECTS_TO_COMPILE_PER_FRAME <int>","maximum number of OpenGL objects to compile per frame in database pager.");
static osg::ApplicationUsageProxy DatabasePager_e3(osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_DATABASE_PAGER_DRAWABLE <mode>","Set the drawable policy for setting of loaded drawable to specified type. mode can be one of DoNotModify, DisplayList, VBO or VertexArrays>.");
static osg::ApplicationUsageProxy DatabasePager_e4(osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_DATABASE_PAGER_PRIORITY <mode>", "Set the thread priority to DEFAULT, MIN, LOW, NOMINAL, HIGH or MAX.");
static osg::ApplicationUsageProxy DatabasePager_e7(osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_EXPIRY_DELAY <float> ","Set the length of time a PagedLOD child is kept in memory, without being used, before its tagged as expired, and ear marked to deletion.");
static osg::ApplicationUsageProxy DatabasePager_e8(osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_EXPIRY_FRAMES <int> ","Set number of frames a PagedLOD child is kept in memory, without being used, before its tagged as expired, and ear marked to deletion.");
static osg::ApplicationUsageProxy DatabasePager_e9(osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_RELEASE_DELAY <float> ","Set the length of time a PagedLOD child's OpenGL objects are kept in memory, without being used, before be released (setting to OFF disables this feature.)");
static osg::ApplicationUsageProxy DatabasePager_e10(osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_RELEASE_FRAMES <int> ","Set number of frames a PagedLOD child's OpenGL objects are kept in memory, without being used, before be released.");
static osg::ApplicationUsageProxy DatabasePager_e11(osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_MAX_PAGEDLOD <num>","Set the target maximum number of PagedLOD to maintain.");
// Convert function objects that take pointer args into functions that a
// reference to an osg::ref_ptr. This is quite useful for doing STL
// operations on lists of ref_ptr. This code assumes that a function
// with an argument const Foo* should be composed into a function of
// argument type ref_ptr<Foo>&, not ref_ptr<const Foo>&. Some support
// for that should be added to make this more general.
namespace
{
template <typename U>
struct PointerTraits
{
typedef class NullType {} PointeeType;
};
template <typename U>
struct PointerTraits<U*>
{
typedef U PointeeType;
};
template <typename U>
struct PointerTraits<const U*>
{
typedef U PointeeType;
};
template <typename FuncObj>
class RefPtrAdapter
: public std::unary_function<const osg::ref_ptr<typename PointerTraits<typename FuncObj::argument_type>::PointeeType>,
typename FuncObj::result_type>
{
public:
typedef typename PointerTraits<typename FuncObj::argument_type>::PointeeType PointeeType;
typedef osg::ref_ptr<PointeeType> RefPtrType;
explicit RefPtrAdapter(const FuncObj& funcObj) : _func(funcObj) {}
typename FuncObj::result_type operator()(const RefPtrType& refPtr) const
{
return _func(refPtr.get());
}
protected:
FuncObj _func;
};
template <typename FuncObj>
RefPtrAdapter<FuncObj> refPtrAdapt(const FuncObj& func)
{
return RefPtrAdapter<FuncObj>(func);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// FindCompileableGLObjectsVisitor
//
class DatabasePager::FindCompileableGLObjectsVisitor : public osg::NodeVisitor
{
public:
FindCompileableGLObjectsVisitor(DatabasePager::DataToCompile& dataToCompile,
bool changeAutoUnRef, bool valueAutoUnRef,
bool changeAnisotropy, float valueAnisotropy,
DatabasePager::DrawablePolicy drawablePolicy,
const DatabasePager* pager):
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
_dataToCompile(dataToCompile),
_changeAutoUnRef(changeAutoUnRef), _valueAutoUnRef(valueAutoUnRef),
_changeAnisotropy(changeAnisotropy), _valueAnisotropy(valueAnisotropy),
_drawablePolicy(drawablePolicy), _pager(pager)
{
if (osgDB::Registry::instance()->getBuildKdTreesHint()==osgDB::ReaderWriter::Options::BUILD_KDTREES &&
osgDB::Registry::instance()->getKdTreeBuilder())
{
_kdTreeBuilder = osgDB::Registry::instance()->getKdTreeBuilder()->clone();
}
}
virtual void apply(osg::Node& node)
{
apply(node.getStateSet());
traverse(node);
}
virtual void apply(osg::Geode& geode)
{
apply(geode.getStateSet());
for(unsigned int i=0;i<geode.getNumDrawables();++i)
{
apply(geode.getDrawable(i));
}
traverse(geode);
if (_kdTreeBuilder.valid())
{
geode.accept(*_kdTreeBuilder);
}
}
inline void apply(osg::StateSet* stateset)
{
if (stateset)
{
// search for the existance of any texture object
// attributes
// if texture object attributes exist and need to be
// compiled, add the state to the list for later
// compilation.
bool compileStateSet = false;
for(unsigned int i=0;i<stateset->getTextureAttributeList().size();++i)
{
osg::Texture* texture = dynamic_cast<osg::Texture*>(stateset->getTextureAttribute(i,osg::StateAttribute::TEXTURE));
// Has this texture already been encountered?
if (texture && !_textureSet.count(texture))
{
_textureSet.insert(texture);
if (_changeAutoUnRef) texture->setUnRefImageDataAfterApply(_valueAutoUnRef);
if ((_changeAnisotropy
&& texture->getMaxAnisotropy() != _valueAnisotropy))
{
if (_changeAnisotropy)
texture->setMaxAnisotropy(_valueAnisotropy);
}
if (!_pager->isCompiled(texture))
{
compileStateSet = true;
if (osg::getNotifyLevel() >= osg::DEBUG_INFO)
{
osg::notify(osg::DEBUG_INFO)
<<"Found compilable texture " << texture << " ";
osg::Image* image = texture->getImage(0);
if (image) osg::notify(osg::DEBUG_INFO) << image->getFileName();
osg::notify(osg::DEBUG_INFO) << std:: endl;
}
break;
}
}
}
if (compileStateSet)
{
_dataToCompile.first.insert(stateset);
}
}
}
inline void apply(osg::Drawable* drawable)
{
if (_drawableSet.count(drawable))
return;
_drawableSet.insert(drawable);
apply(drawable->getStateSet());
switch(_drawablePolicy)
{
case DatabasePager::DO_NOT_MODIFY_DRAWABLE_SETTINGS:
// do nothing, leave settings as they came in from loaded database.
// osg::notify(osg::NOTICE)<<"DO_NOT_MODIFY_DRAWABLE_SETTINGS"<<std::endl;
break;
case DatabasePager::USE_DISPLAY_LISTS:
drawable->setUseDisplayList(true);
drawable->setUseVertexBufferObjects(false);
break;
case DatabasePager::USE_VERTEX_BUFFER_OBJECTS:
drawable->setUseDisplayList(true);
drawable->setUseVertexBufferObjects(true);
// osg::notify(osg::NOTICE)<<"USE_VERTEX_BUFFER_OBJECTS"<<std::endl;
break;
case DatabasePager::USE_VERTEX_ARRAYS:
drawable->setUseDisplayList(false);
drawable->setUseVertexBufferObjects(false);
// osg::notify(osg::NOTICE)<<"USE_VERTEX_ARRAYS"<<std::endl;
break;
}
// Don't compile if already compiled. This can happen if the
// subgraph is shared with already-loaded nodes.
//
// XXX This "compiles" VBOs too, but compilation doesn't do
// anything for VBOs, does it?
if (drawable->getUseDisplayList() && !_pager->isCompiled(drawable))
{
// osg::notify(osg::NOTICE)<<" Found compilable drawable"<<std::endl;
_dataToCompile.second.push_back(drawable);
}
}
DatabasePager::DataToCompile& _dataToCompile;
bool _changeAutoUnRef;
bool _valueAutoUnRef;
bool _changeAnisotropy;
float _valueAnisotropy;
DatabasePager::DrawablePolicy _drawablePolicy;
const DatabasePager* _pager;
std::set<osg::ref_ptr<osg::Texture> > _textureSet;
std::set<osg::ref_ptr<osg::Drawable> > _drawableSet;
osg::ref_ptr<osg::KdTreeBuilder> _kdTreeBuilder;
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// SortFileRequestFunctor
//
struct DatabasePager::SortFileRequestFunctor
{
bool operator() (const osg::ref_ptr<DatabasePager::DatabaseRequest>& lhs,const osg::ref_ptr<DatabasePager::DatabaseRequest>& rhs) const
{
if (lhs->_timestampLastRequest>rhs->_timestampLastRequest) return true;
else if (lhs->_timestampLastRequest<rhs->_timestampLastRequest) return false;
else return (lhs->_priorityLastRequest>rhs->_priorityLastRequest);
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// ReadQueue
//
void DatabasePager::RequestQueue::sort()
{
std::sort(_requestList.begin(),_requestList.end(),SortFileRequestFunctor());
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// ReadQueue
//
DatabasePager::ReadQueue::ReadQueue(DatabasePager* pager, const std::string& name):
_pager(pager),
_name(name)
{
_block = new osg::RefBlock;
}
void DatabasePager::ReadQueue::clear()
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_requestMutex);
for(RequestList::iterator citr = _requestList.begin();
citr != _requestList.end();
++citr)
{
(*citr)->_loadedModel = 0;
(*citr)->_requestQueue = 0;
}
_requestList.clear();
updateBlock();
}
void DatabasePager::ReadQueue::add(DatabasePager::DatabaseRequest* databaseRequest)
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_requestMutex);
_requestList.push_back(databaseRequest);
databaseRequest->_requestQueue = this;
updateBlock();
}
void DatabasePager::ReadQueue::takeFirst(osg::ref_ptr<DatabaseRequest>& databaseRequest)
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_requestMutex);
if (!_requestList.empty())
{
sort();
databaseRequest = _requestList.front();
databaseRequest->_requestQueue = 0;
_requestList.erase(_requestList.begin());
updateBlock();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// DatabaseThread
//
DatabasePager::DatabaseThread::DatabaseThread(DatabasePager* pager, Mode mode, const std::string& name):
_done(false),
_active(false),
_pager(pager),
_mode(mode),
_name(name)
{
}
DatabasePager::DatabaseThread::DatabaseThread(const DatabaseThread& dt, DatabasePager* pager):
_done(false),
_active(false),
_pager(pager),
_mode(dt._mode),
_name(dt._name)
{
}
DatabasePager::DatabaseThread::~DatabaseThread()
{
cancel();
}
int DatabasePager::DatabaseThread::cancel()
{
int result = 0;
if( isRunning() )
{
_done = true;
switch(_mode)
{
case(HANDLE_ALL_REQUESTS):
_pager->_fileRequestQueue->release();
break;
case(HANDLE_NON_HTTP):
_pager->_fileRequestQueue->release();
break;
case(HANDLE_ONLY_HTTP):
_pager->_httpRequestQueue->release();
break;
}
// release the frameBlock and _databasePagerThreadBlock in case its holding up thread cancellation.
// _databasePagerThreadBlock->release();
// then wait for the the thread to stop running.
while(isRunning())
{
// commenting out debug info as it was cashing crash on exit, presumable
// due to osg::notify or std::cout destructing earlier than this destructor.
// osg::notify(osg::DEBUG_INFO)<<"Waiting for DatabasePager to cancel"<<std::endl;
OpenThreads::Thread::YieldCurrentThread();
}
// _startThreadCalled = false;
}
//std::cout<<"DatabasePager::~DatabasePager() stopped running"<<std::endl;
return result;
}
void DatabasePager::DatabaseThread::run()
{
osg::notify(osg::INFO)<<_name<<": DatabasePager::DatabaseThread::run"<<std::endl;
#if 1
// need to set the texture object manager to be able to reuse textures
osg::Texture::setMinimumNumberOfTextureObjectsToRetainInCache(100);
// need to set the display list manager to be able to reuse display lists
osg::Drawable::setMinimumNumberOfDisplayListsToRetainInCache(100);
#else
// need to set the texture object manager to be able to reuse textures
osg::Texture::setMinimumNumberOfTextureObjectsToRetainInCache(0);
// need to set the display list manager to be able to reuse display lists
osg::Drawable::setMinimumNumberOfDisplayListsToRetainInCache(0);
#endif
bool firstTime = true;
osg::ref_ptr<DatabasePager::ReadQueue> read_queue;
osg::ref_ptr<DatabasePager::ReadQueue> out_queue;
switch(_mode)
{
case(HANDLE_ALL_REQUESTS):
read_queue = _pager->_fileRequestQueue;
break;
case(HANDLE_NON_HTTP):
read_queue = _pager->_fileRequestQueue;
out_queue = _pager->_httpRequestQueue;
break;
case(HANDLE_ONLY_HTTP):
read_queue = _pager->_httpRequestQueue;
break;
}
//Getting CURL Environment Variables (If found rewrite OSG Options)
osg::ref_ptr<FileCache> fileCache = osgDB::Registry::instance()->getFileCache();
do
{
_active = false;
read_queue->block();
_active = true;
osg::notify(osg::INFO)<<_name<<": _pager->_requestList.size()= "<<read_queue->_requestList.size()<<" to delete = "<<read_queue->_childrenToDeleteList.size()<<std::endl;
//
// delete any children if required.
//
if (_pager->_deleteRemovedSubgraphsInDatabaseThread && !(read_queue->_childrenToDeleteList.empty()))
{
ObjectList deleteList;
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(read_queue->_childrenToDeleteListMutex);
deleteList.swap(read_queue->_childrenToDeleteList);
read_queue->updateBlock();
}
}
//
// load any subgraphs that are required.
//
osg::ref_ptr<DatabaseRequest> databaseRequest;
read_queue->takeFirst(databaseRequest);
bool readFromFileCache = false;
if (databaseRequest.valid())
{
// check if databaseRequest is still relevant
if ((_pager->_frameNumber-databaseRequest->_frameNumberLastRequest)<=1)
{
// now check to see if this request is appropriate for this thread
switch(_mode)
{
case(HANDLE_ALL_REQUESTS):
// do nothing as this thread can handle the load
if (osgDB::containsServerAddress(databaseRequest->_fileName))
{
if (fileCache.valid() && fileCache->existsInCache(databaseRequest->_fileName))
{
readFromFileCache = true;
}
}
break;
case(HANDLE_NON_HTTP):
// check the cache first
if (osgDB::containsServerAddress(databaseRequest->_fileName))
{
if (fileCache.valid() && fileCache->existsInCache(databaseRequest->_fileName))
{
readFromFileCache = true;
}
else
{
osg::notify(osg::INFO)<<_name<<": Passing http requests over "<<databaseRequest->_fileName<<std::endl;
out_queue->add(databaseRequest.get());
databaseRequest = 0;
}
}
break;
case(HANDLE_ONLY_HTTP):
// make sure the request is a http request
if (!osgDB::containsServerAddress(databaseRequest->_fileName))
{
osg::notify(osg::NOTICE)<<_name<<": Help we have request we shouldn't have "<<databaseRequest->_fileName<<std::endl;
databaseRequest = 0;
}
break;
}
}
else
{
databaseRequest = 0;
}
}
if (databaseRequest.valid())
{
// load the data, note safe to write to the databaseRequest since once
// it is created this thread is the only one to write to the _loadedModel pointer.
//osg::notify(osg::NOTICE)<<"In DatabasePager thread readNodeFile("<<databaseRequest->_fileName<<")"<<std::endl;
//osg::Timer_t before = osg::Timer::instance()->tick();
// assume that readNode is thread safe...
ReaderWriter::ReadResult rr = readFromFileCache ?
fileCache->readNode(databaseRequest->_fileName, databaseRequest->_loadOptions.get(), false) :
Registry::instance()->readNode(databaseRequest->_fileName, databaseRequest->_loadOptions.get(), false);
if (rr.validNode()) databaseRequest->_loadedModel = rr.getNode();
if (rr.error()) osg::notify(osg::WARN)<<"Error in reading file "<<databaseRequest->_fileName<<" : "<<rr.message() << std::endl;
if (databaseRequest->_loadedModel.valid() &&
osgDB::containsServerAddress(databaseRequest->_fileName) &&
fileCache.valid() &&
!readFromFileCache)
{
fileCache->writeNode(*(databaseRequest->_loadedModel), databaseRequest->_fileName, databaseRequest->_loadOptions.get());
}
if ((_pager->_frameNumber-databaseRequest->_frameNumberLastRequest)>1)
{
osg::notify(osg::INFO)<<_name<<": Warning DatabaseRquest no longer required."<<std::endl;
databaseRequest->_loadedModel = 0;
}
osg::ref_ptr<osg::Group> groupForAddingLoadedSubgraph = databaseRequest->_groupForAddingLoadedSubgraph.get();
if (!groupForAddingLoadedSubgraph)
{
osg::notify(osg::INFO)<<_name<<": Warning parent of loaded subgraph, deleted."<<std::endl;
databaseRequest->_loadedModel = 0;
}
//osg::notify(osg::NOTICE)<<" node read in "<<osg::Timer::instance()->delta_m(before,osg::Timer::instance()->tick())<<" ms"<<std::endl;
bool loadedObjectsNeedToBeCompiled = false;
if (databaseRequest->_loadedModel.valid())
{
databaseRequest->_loadedModel->getBound();
osg::NodePath nodePath;
osg::NodePathList nodePathList = groupForAddingLoadedSubgraph->getParentalNodePaths();
if (!nodePathList.empty()) nodePath = nodePathList.front();
nodePath.push_back(groupForAddingLoadedSubgraph.get());
#if 1
// force a compute of the loaded model's bounding volume, so that when the subgraph
// merged with the main scene graph and large computeBound() isn't incurred.
ActiveGraphicsContexts::iterator itr = _pager->_activeGraphicsContexts.begin();
DataToCompile& dtc = databaseRequest->_dataToCompileMap[*itr];
++itr;
// find all the compileable rendering objects
DatabasePager::FindCompileableGLObjectsVisitor frov(dtc,
_pager->_changeAutoUnRef, _pager->_valueAutoUnRef,
_pager->_changeAnisotropy, _pager->_valueAnisotropy,
_pager->_drawablePolicy,
_pager);
// push the soon to be parent on the nodepath of the NodeVisitor so that
// during traversal one can test for where it'll be in the overall scene graph
for(osg::NodePath::iterator nitr = nodePath.begin();
nitr != nodePath.end();
++nitr)
{
frov.pushOntoNodePath(*nitr);
}
databaseRequest->_loadedModel->accept(frov);
if (_pager->_doPreCompile &&
!_pager->_activeGraphicsContexts.empty())
{
if (!dtc.first.empty() || !dtc.second.empty())
{
loadedObjectsNeedToBeCompiled = true;
// copy the objects from the compile list to the other graphics context list.
for(;
itr != _pager->_activeGraphicsContexts.end();
++itr)
{
databaseRequest->_dataToCompileMap[*itr] = dtc;
}
}
}
#else
if (_pager->_doPreCompile &&
!_pager->_activeGraphicsContexts.empty())
{
// force a compute of the loaded model's bounding volume, so that when the subgraph
// merged with the main scene graph and large computeBound() isn't incurred.
ActiveGraphicsContexts::iterator itr = _pager->_activeGraphicsContexts.begin();
DataToCompile& dtc = databaseRequest->_dataToCompileMap[*itr];
++itr;
// find all the compileable rendering objects
DatabasePager::FindCompileableGLObjectsVisitor frov(dtc,
_pager->_changeAutoUnRef, _pager->_valueAutoUnRef,
_pager->_changeAnisotropy, _pager->_valueAnisotropy,
_pager->_drawablePolicy,
_pager);
// push the soon to be parent on the nodepath of the NodeVisitor so that
// during traversal one can test for where it'll be in the overall scene graph
for(osg::NodePath::iterator nitr = nodePath.begin();
nitr != nodePath.end();
++nitr)
{
frov.pushOntoNodePath(*nitr);
}
databaseRequest->_loadedModel->accept(frov);
if (!dtc.first.empty() || !dtc.second.empty())
{
loadedObjectsNeedToBeCompiled = true;
// copy the objects from the compile list to the other graphics context list.
for(;
itr != _pager->_activeGraphicsContexts.end();
++itr)
{
databaseRequest->_dataToCompileMap[*itr] = dtc;
}
}
}
else
{
// check to see if we need to run the KdTreeBuilder
if (osgDB::Registry::instance()->getBuildKdTreesHint()==osgDB::ReaderWriter::Options::BUILD_KDTREES &&
osgDB::Registry::instance()->getKdTreeBuilder())
{
//osg::Timer_t before = osg::Timer::instance()->tick();
//osg::notify(osg::NOTICE)<<"osgTerrain::GeometryTechnique::build kd tree"<<std::endl;
osg::ref_ptr<osg::KdTreeBuilder> builder = osgDB::Registry::instance()->getKdTreeBuilder()->clone();
for(osg::NodePath::iterator nitr = nodePath.begin();
nitr != nodePath.end();
++nitr)
{
builder->pushOntoNodePath(*nitr);
}
databaseRequest->_loadedModel->accept(*builder);
//osg::Timer_t after = osg::Timer::instance()->tick();
//osg::notify(osg::NOTICE)<<"KdTree build time "<<osg::Timer::instance()->delta_m(before, after)<<std::endl;
}
}
#endif
// move the databaseRequest from the front of the fileRequest to the end of
// dataToCompile or dataToMerge lists.
if (loadedObjectsNeedToBeCompiled)
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_pager->_dataToCompileList->_requestMutex);
databaseRequest->_requestQueue = _pager->_dataToCompileList.get();
_pager->_dataToCompileList->_requestList.push_back(databaseRequest);
}
else
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_pager->_dataToMergeList->_requestMutex);
databaseRequest->_requestQueue = _pager->_dataToMergeList.get();
_pager->_dataToMergeList->_requestList.push_back(databaseRequest);
}
}
// Prepare and prune the to-be-compiled list here in
// the pager thread rather than in the draw or
// graphics context thread(s).
if (loadedObjectsNeedToBeCompiled)
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_pager->_dataToCompileList->_requestMutex);
_pager->_dataToCompileList->sort();
// Prune all the old entries.
RequestQueue::RequestList::iterator tooOld
= std::find_if(_pager->_dataToCompileList->_requestList.begin(),
_pager->_dataToCompileList->_requestList.end(),
refPtrAdapt(std::not1(std::bind2nd(std::mem_fun(&DatabaseRequest::isRequestCurrent),
_pager->_frameNumber))));
// This is the database thread, so just delete
for(RequestQueue::RequestList::iterator citr = tooOld;
citr != _pager->_dataToCompileList->_requestList.end();
++citr)
{
osg::notify(osg::INFO)<<_name<<": pruning from compile list"<<std::endl;
(*citr)->_loadedModel = 0;
(*citr)->_requestQueue = 0;
}
_pager->_dataToCompileList->_requestList.erase(tooOld, _pager->_dataToCompileList->_requestList.end());
loadedObjectsNeedToBeCompiled = !_pager->_dataToCompileList->_requestList.empty();
}
if (loadedObjectsNeedToBeCompiled && !_pager->_activeGraphicsContexts.empty())
{
for(ActiveGraphicsContexts::iterator itr = _pager->_activeGraphicsContexts.begin();
itr != _pager->_activeGraphicsContexts.end();
++itr)
{
osg::GraphicsContext* gc = osg::GraphicsContext::getCompileContext(*itr);
if (gc)
{
osg::GraphicsThread* gt = gc->getGraphicsThread();
if (gt)
{
gt->add(new DatabasePager::CompileOperation(_pager));
}
else
{
gc->makeCurrent();
_pager->compileAllGLObjects(*(gc->getState()));
gc->releaseContext();
}
}
}
// osg::notify(osg::NOTICE)<<"Done compiling in paging thread"<<std::endl;
}
}
else
{
OpenThreads::Thread::YieldCurrentThread();
}
// go to sleep till our the next time our thread gets scheduled.
if (firstTime)
{
// do a yield to get round a peculiar thread hang when testCancel() is called
// in certain circumstances - of which there is no particular pattern.
YieldCurrentThread();
firstTime = false;
}
} while (!testCancel() && !_done);
}
DatabasePager::DatabasePager()
{
//osg::notify(osg::INFO)<<"Constructing DatabasePager()"<<std::endl;
_startThreadCalled = false;
_done = false;
_acceptNewRequests = true;
_databasePagerThreadPaused = false;
_numFramesActive = 0;
_frameNumber = 0;
const char* str = getenv("OSG_DATABASE_PAGER_PRIORITY");
if (str)
{
if (strcmp(str,"DEFAULT")==0)
{
setSchedulePriority(OpenThreads::Thread::THREAD_PRIORITY_DEFAULT);
}
else if (strcmp(str,"MIN")==0)
{
setSchedulePriority(OpenThreads::Thread::THREAD_PRIORITY_MIN);
}
else if (strcmp(str,"LOW")==0)
{
setSchedulePriority(OpenThreads::Thread::THREAD_PRIORITY_LOW);
}
else if (strcmp(str,"NOMINAL")==0)
{
setSchedulePriority(OpenThreads::Thread::THREAD_PRIORITY_NOMINAL);
}
else if (strcmp(str,"HIGH")==0)
{
setSchedulePriority(OpenThreads::Thread::THREAD_PRIORITY_HIGH);
}
else if (strcmp(str,"MAX")==0)
{
setSchedulePriority(OpenThreads::Thread::THREAD_PRIORITY_MAX);
}
}
#if __APPLE__
// OSX really doesn't like compiling display lists, and performs poorly when they are used,
// so apply this hack to make up for its short comings.
_drawablePolicy = USE_VERTEX_ARRAYS;
#else
_drawablePolicy = DO_NOT_MODIFY_DRAWABLE_SETTINGS;
#endif
str = getenv("OSG_DATABASE_PAGER_GEOMETRY");
if (!str) str = getenv("OSG_DATABASE_PAGER_DRAWABLE");
if (str)
{
if (strcmp(str,"DoNotModify")==0)
{
_drawablePolicy = DO_NOT_MODIFY_DRAWABLE_SETTINGS;
}
else if (strcmp(str,"DisplayList")==0 || strcmp(str,"DL")==0)
{
_drawablePolicy = USE_DISPLAY_LISTS;
}
else if (strcmp(str,"VBO")==0)
{
_drawablePolicy = USE_VERTEX_BUFFER_OBJECTS;
}
else if (strcmp(str,"VertexArrays")==0 || strcmp(str,"VA")==0 )
{
_drawablePolicy = USE_VERTEX_ARRAYS;
}
}
_changeAnisotropy = false;
_valueAnisotropy = 1.0f;
const char* ptr=0;
_deleteRemovedSubgraphsInDatabaseThread = true;
if( (ptr = getenv("OSG_DELETE_IN_DATABASE_THREAD")) != 0)
{
_deleteRemovedSubgraphsInDatabaseThread = strcmp(ptr,"yes")==0 || strcmp(ptr,"YES")==0 ||
strcmp(ptr,"on")==0 || strcmp(ptr,"ON")==0;
}
_expiryDelay = 10.0;
if( (ptr = getenv("OSG_EXPIRY_DELAY")) != 0)
{
_expiryDelay = atof(ptr);
osg::notify(osg::NOTICE)<<"Expiry delay = "<<_expiryDelay<<std::endl;
}
_expiryFrames = 1; // Last frame will not be expired
if( (ptr = getenv("OSG_EXPIRY_FRAMES")) != 0)
{
_expiryFrames = atoi(ptr);
osg::notify(osg::NOTICE)<<"Expiry frames = "<<_expiryFrames<<std::endl;
}
if( (ptr = getenv("OSG_RELEASE_DELAY")) != 0)
{
if (strcmp(ptr,"OFF")==0 || strcmp(ptr,"Off")==0 || strcmp(ptr,"off")==0)
{
setReleaseDelay(DBL_MAX);
}
else
{
setReleaseDelay(atof(ptr));
}
osg::notify(osg::NOTICE)<<"Release delay = "<<_releaseDelay<<std::endl;
}
else
{
setReleaseDelay(DBL_MAX);
}
_releaseFrames = 1; // Last frame will not be release
if( (ptr = getenv("OSG_RELEASE_FRAMES")) != 0)
{
_releaseFrames = atoi(ptr);
osg::notify(osg::NOTICE)<<"Release frames = "<<_releaseFrames<<std::endl;
}
_targetMaximumNumberOfPageLOD = 0;
if( (ptr = getenv("OSG_MAX_PAGEDLOD")) != 0)
{
_targetMaximumNumberOfPageLOD = atoi(ptr);
osg::notify(osg::NOTICE)<<"_targetMaximumNumberOfPageLOD = "<<_targetMaximumNumberOfPageLOD<<std::endl;
}
_doPreCompile = true;
if( (ptr = getenv("OSG_DO_PRE_COMPILE")) != 0)
{
_doPreCompile = strcmp(ptr,"yes")==0 || strcmp(ptr,"YES")==0 ||
strcmp(ptr,"on")==0 || strcmp(ptr,"ON")==0;
}
_targetFrameRate = 100.0;
_minimumTimeAvailableForGLCompileAndDeletePerFrame = 0.001; // 1ms.
_maximumNumOfObjectsToCompilePerFrame = 4;
if( (ptr = getenv("OSG_MINIMUM_COMPILE_TIME_PER_FRAME")) != 0)
{
_minimumTimeAvailableForGLCompileAndDeletePerFrame = atof(ptr);
}
if( (ptr = getenv("OSG_MAXIMUM_OBJECTS_TO_COMPILE_PER_FRAME")) != 0)
{
_maximumNumOfObjectsToCompilePerFrame = atoi(ptr);
}
// initialize the stats variables
resetStats();
// make sure a SharedStateManager exists.
//osgDB::Registry::instance()->getOrCreateSharedStateManager();
//if (osgDB::Registry::instance()->getSharedStateManager())
//osgDB::Registry::instance()->setUseObjectCacheHint(true);
_fileRequestQueue = new ReadQueue(this,"fileRequestQueue");
_httpRequestQueue = new ReadQueue(this,"httpRequestQueue");
_dataToCompileList = new RequestQueue;
_dataToMergeList = new RequestQueue;
setUpThreads(
osg::DisplaySettings::instance()->getNumOfDatabaseThreadsHint(),
osg::DisplaySettings::instance()->getNumOfHttpDatabaseThreadsHint());
}
DatabasePager::DatabasePager(const DatabasePager& rhs)
{
//osg::notify(osg::INFO)<<"Constructing DatabasePager(const DatabasePager& )"<<std::endl;
_startThreadCalled = false;
_done = false;
_acceptNewRequests = true;
_databasePagerThreadPaused = false;
_numFramesActive = 0;
_frameNumber = 0;
_drawablePolicy = rhs._drawablePolicy;
_changeAutoUnRef = rhs._changeAutoUnRef;
_valueAutoUnRef = rhs._valueAutoUnRef;
_changeAnisotropy = rhs._changeAnisotropy;
_valueAnisotropy = rhs._valueAnisotropy;
_deleteRemovedSubgraphsInDatabaseThread = rhs._deleteRemovedSubgraphsInDatabaseThread;
_expiryDelay = rhs._expiryDelay;
_expiryFrames = rhs._expiryFrames;
_releaseDelay = rhs._releaseDelay;
_releaseFrames = rhs._releaseFrames;
_targetMaximumNumberOfPageLOD = rhs._targetMaximumNumberOfPageLOD;
_doPreCompile = rhs._doPreCompile;
_targetFrameRate = rhs._targetFrameRate;
_minimumTimeAvailableForGLCompileAndDeletePerFrame = rhs._minimumTimeAvailableForGLCompileAndDeletePerFrame;
_maximumNumOfObjectsToCompilePerFrame = rhs._maximumNumOfObjectsToCompilePerFrame;