root/OpenSceneGraph/trunk/src/osgPlugins/txp/TXPNode.cpp @ 13041

Revision 13041, 9.5 kB (checked in by robert, 2 years ago)

Ran script to remove trailing spaces and tabs

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osg/Notify>
2#include <osg/BoundingBox>
3#include <osg/PagedLOD>
4#include <osg/Timer>
5#include <osg/MatrixTransform>
6#include <osgUtil/CullVisitor>
7#include <osgDB/Registry>
8#include <osgDB/ReaderWriter>
9
10#include <iostream>
11#include <vector>
12#include <algorithm>
13#include <stdio.h>
14
15#include "TileMapper.h"
16#include "TXPNode.h"
17#include "TXPPagedLOD.h"
18#include "ReaderWriterTXP.h"
19
20
21using namespace txp;
22using namespace osg;
23
24
25
26class RetestCallback : public osg::NodeCallback
27{
28
29public:
30    RetestCallback()
31    {
32        timer = osg::Timer::instance(); // get static timer
33        prevTime = 0; // should this be instantiated with current time?
34    }
35
36    virtual void operator () ( osg::Node * node, osg::NodeVisitor * nv )
37    {
38        osg::Group *pLOD = (osg::Group *) node;
39        osg::Group *n = NULL;
40        if ((pLOD->getNumChildren() > 0) &&
41            (n = (osg::Group *) pLOD->getChild(0)) &&
42            (n->getNumChildren() == 0))
43        {
44            osg::Timer_t curTime = timer->tick();
45            if ((prevTime + 2.0/timer->getSecondsPerTick() ) < curTime)
46            {
47                prevTime = curTime;
48                pLOD->removeChildren( 0, pLOD->getNumChildren());
49            }
50        }
51
52        NodeCallback::traverse( node, nv );
53    }
54
55protected:
56    const osg::Timer* timer;
57    osg::Timer_t prevTime;
58};
59
60
61
62#define TXPNodeERROR(s) OSG_NOTICE << "txp::TXPNode::" << (s) << " error: "
63
64TXPNode::TXPNode():
65osg::Group(),
66_originX(0.0),
67_originY(0.0)
68{
69    setNumChildrenRequiringUpdateTraversal(1);
70    setCullingActive(false);
71}
72
73TXPNode::TXPNode(const TXPNode& txpNode,const osg::CopyOp& copyop):
74osg::Group(txpNode,copyop),
75_originX(txpNode._originX),
76_originY(txpNode._originY)
77{
78    setNumChildrenRequiringUpdateTraversal(1);
79}
80
81TXPNode::~TXPNode()
82{
83   if (_archive.get())
84   {
85      if (osgDB::ReaderWriter * rw =
86          osgDB::Registry::instance()->getReaderWriterForExtension("txp"))
87      {
88         if (ReaderWriterTXP * rwTXP =
89             dynamic_cast< ReaderWriterTXP * >(rw))
90         {
91            const int id = _archive->getId();
92            if (!rwTXP->removeArchive(id))
93            {
94               TXPNodeERROR("Failed to remove archive ") << id << std::endl;
95            }
96         }
97      }
98   }
99}
100
101void TXPNode::traverse(osg::NodeVisitor& nv)
102{
103    switch(nv.getVisitorType())
104    {
105    case osg::NodeVisitor::CULL_VISITOR:
106    {
107
108        OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
109
110        osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(&nv);
111        if (cv)
112        {
113//#define PRINT_TILEMAPP_TIMEINFO
114#ifdef PRINT_TILEMAPP_TIMEINFO
115            const osg::Timer& timer = *osg::Timer::instance();
116            osg::Timer_t start = timer.tick();
117            std::cout<<"Doing visible tile search"<<std::endl;
118#endif // PRINT_TILEMAPP_TIMEINFO
119
120            osg::ref_ptr<TileMapper> tileMapper = new TileMapper;
121            tileMapper->setLODScale(cv->getLODScale());
122            tileMapper->pushReferenceViewPoint(cv->getReferenceViewPoint());
123            tileMapper->pushViewport(cv->getViewport());
124            tileMapper->pushProjectionMatrix((cv->getProjectionMatrix()));
125            tileMapper->pushModelViewMatrix((cv->getModelViewMatrix()), osg::Transform::RELATIVE_RF);
126
127            // traverse the scene graph to search for valid tiles
128            accept(*tileMapper);
129
130            tileMapper->popModelViewMatrix();
131            tileMapper->popProjectionMatrix();
132            tileMapper->popViewport();
133            tileMapper->popReferenceViewPoint();
134
135            //std::cout<<"   found " << tileMapper._tileMap.size() << std::endl;
136
137            cv->setUserData(tileMapper.get());
138
139#ifdef PRINT_TILEMAPP_TIMEINFO
140            std::cout<<"Completed visible tile search in "<<timer.delta_m(start,timer.tick())<<std::endl;
141#endif // PRINT_TILEMAPP_TIMEINFO
142
143        }
144
145        updateEye(nv);
146        break;
147    }
148    case osg::NodeVisitor::UPDATE_VISITOR:
149    {
150        OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
151
152        updateSceneGraph();
153        break;
154    }
155    default:
156        break;
157    }
158    Group::traverse(nv);
159}
160
161osg::BoundingSphere TXPNode::computeBound() const
162{
163#if 1
164
165    // Steve Lunsford 10/28/05 : - Had to avoid using the child group nodes for bounds calculation
166    // because apparently the loader doesn't load all the sub-tiles for this node, resulting in a Group::computeBounds
167    // call which returns a size smaller than the actual size represented by this node so consequently this node gets culled out.
168    // note, submission merged and rearranged by Robert Osfield as an #if #else just in case we need to revert.
169    return osg::BoundingSphere( _extents );
170#else
171    // original code which uses the extents of the children when one is available.
172    if (getNumChildren() == 0)
173    {
174        return osg::BoundingSphere( _extents );
175    }
176    return Group::computeBound();
177#endif
178}
179
180void TXPNode::setArchiveName(const std::string& archiveName)
181{
182    _archiveName = archiveName;
183}
184
185void TXPNode::setOptions(const std::string& options)
186{
187    _options = options;
188}
189
190const std::string& TXPNode::getOptions() const
191{
192    return _options;
193}
194
195const std::string& TXPNode::getArchiveName() const
196{
197    return _archiveName;
198}
199
200bool TXPNode::loadArchive(TXPArchive* archive)
201{
202    //if (_archive.get())
203    //{
204    //    TXPNodeERROR("loadArchive()") << "archive already open" << std::endl;
205    //    return false;
206    //}
207
208
209   //modified by Brad Anderegg on May-27-08
210   //if NULL is passed in we will create a new archive and open the database
211   //otherwise we will use the archive provided which should have already been loaded
212   //by ReaderWriterTXP::getArchive(). See line 57-77 of ReaderWriterTXP.cpp.
213   if(archive == NULL)
214   {
215       _archive = new TXPArchive;
216       if (_archive->openFile(_archiveName) == false)
217       {
218           TXPNodeERROR("loadArchive()") << "failed to load archive: \"" << _archiveName << "\"" << std::endl;
219           return false;
220       }
221   }
222   else
223   {
224      _archive = archive;
225   }
226
227    _archive->getOrigin(_originX,_originY);
228    _archive->getExtents(_extents);
229
230    int32 numLod;
231    _archive->GetHeader()->GetNumLods(numLod);
232
233    trpg2iPoint tileSize;
234    _archive->GetHeader()->GetLodSize(0,tileSize);
235
236    _pageManager = new TXPPageManager;
237
238    // We are going to use _pageManager to manage lod 0 only, all other lod
239    // are managed by this OSG plugin
240    _pageManager->Init(_archive.get(), 1);
241
242    return true;
243}
244
245void TXPNode::updateEye(osg::NodeVisitor& nv)
246{
247    if (!_pageManager)
248    {
249        OSG_NOTICE<<"TXPNode::updateEye() no pageManager created"<<std::endl;
250        return;
251    }
252
253    trpg2dPoint loc;
254    loc.x = nv.getEyePoint().x() - _originX;
255    loc.y = nv.getEyePoint().y() - _originY;
256
257    if (_pageManager->SetLocation(loc))
258    {
259        trpgManagedTile *tile=NULL;
260
261        while((tile = _pageManager->GetNextUnload()))
262        {
263            int x,y,lod;
264            tile->GetTileLoc(x,y,lod);
265            if (lod == 0)
266            {
267                osg::Node* node = (osg::Node*)(tile->GetLocalData());
268                _nodesToRemove.push_back(node);
269
270                //OSG_NOTICE << "Tile unload: " << x << " " << y << " " << lod << std::endl;
271            }
272            _pageManager->AckUnload();
273        }
274
275        while ((tile = _pageManager->GetNextLoad()))
276        {
277            int x,y,lod;
278            tile->GetTileLoc(x,y,lod);
279            if (lod==0)
280            {
281                osg::Node* node = addPagedLODTile(x,y);
282                tile->SetLocalData(node);
283                //OSG_NOTICE << "Tile load: " << x << " " << y << " " << lod << std::endl;
284            }
285            _pageManager->AckLoad();
286
287        }
288    }
289}
290
291osg::Node* TXPNode::addPagedLODTile(int x, int y)
292{
293    // For TerraPage 2.1 and over this method must only be use with lod = 0.
294    // If you look at the code that calls it, it is effectively called only when
295    // lod = 0. So all is OK
296    int lod = 0;
297    char pagedLODfile[1024];
298    sprintf(pagedLODfile,"%s\\tile%d_%dx%d_%d.txp",_archive->getDir(),lod,x,y,_archive->getId());
299
300
301    TXPArchive::TileInfo info;
302    _archive->getTileInfo(x,y,lod,info);
303
304    osg::PagedLOD* pagedLOD = new osg::PagedLOD;
305    pagedLOD->setFileName(0,pagedLODfile);
306    pagedLOD->setPriorityOffset(0,_archive->getNumLODs());
307    pagedLOD->setPriorityScale(0,1.0f);
308    pagedLOD->setRange(0,0.0,info.maxRange);
309    pagedLOD->setCenter(info.center);
310    pagedLOD->setRadius(info.radius);
311    pagedLOD->setNumChildrenThatCannotBeExpired(1);
312    pagedLOD->setUpdateCallback(new RetestCallback);
313
314    const trpgHeader* header = _archive->GetHeader();
315    trpgHeader::trpgTileType tileType;
316    header->GetTileOriginType(tileType);
317    if(tileType == trpgHeader::TileLocal)
318    {
319        // add in MatrixTransform node with Matrixd offsets
320        // get offsets from tile.bbox
321        osg::Vec3d sw(info.bbox._min);
322        sw[2] = 0.0;
323        osg::Matrix offset;
324        offset.setTrans(sw);
325        osg::MatrixTransform *tform = new osg::MatrixTransform(offset);
326        pagedLOD->setCenter(info.center - sw);
327        tform->addChild(pagedLOD);
328        _nodesToAdd.push_back(tform);
329        return tform;
330    }
331    else
332    {
333        _nodesToAdd.push_back(pagedLOD);
334
335        return pagedLOD;
336    }
337}
338
339void TXPNode::updateSceneGraph()
340{
341    if (!_nodesToRemove.empty())
342    {
343        for (unsigned int i = 0; i < _nodesToRemove.size(); i++)
344        {
345            removeChild(_nodesToRemove[i]);
346        }
347        _nodesToRemove.clear();
348    }
349
350    if (!_nodesToAdd.empty())
351    {
352        for (unsigned int i = 0; i < _nodesToAdd.size(); i++)
353        {
354            addChild(_nodesToAdd[i]);
355        }
356        _nodesToAdd.clear();
357
358    }
359}
360
Note: See TracBrowser for help on using the browser.