openscenegraph
CullVisitor
Go to the documentation of this file.
1/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2008 Robert Osfield
2 *
3 * This library is open source and may be redistributed and/or modified under
4 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
5 * (at your option) any later version. The full license is in LICENSE file
6 * included with this distribution, and on the openscenegraph.org website.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * OpenSceneGraph Public License for more details.
12*/
13
14#ifndef OSGUTIL_CULLVISITOR
15#define OSGUTIL_CULLVISITOR 1
16
17#include <map>
18#include <vector>
19
20#include <osg/NodeVisitor>
21#include <osg/BoundingSphere>
22#include <osg/BoundingBox>
23#include <osg/Matrix>
24#include <osg/Drawable>
25#include <osg/StateSet>
26#include <osg/State>
27#include <osg/ClearNode>
28#include <osg/Camera>
29#include <osg/Notify>
30
31#include <osg/CullStack>
32
33#include <osgUtil/StateGraph>
34#include <osgUtil/RenderStage>
35
36#include <osg/Vec3>
37
38namespace osgUtil {
39
40/**
41 * Basic NodeVisitor implementation for rendering a scene.
42 * This visitor traverses the scene graph, collecting transparent and
43 * opaque osg::Drawables into a depth sorted transparent bin and a state
44 * sorted opaque bin. The opaque bin is rendered first, and then the
45 * transparent bin is rendered in order from the furthest osg::Drawable
46 * from the eye to the one nearest the eye.
47 */
48class OSGUTIL_EXPORT CullVisitor : public osg::NodeVisitor, public osg::CullStack
49{
50 public:
51
52 typedef osg::Matrix::value_type value_type;
53
54
55 CullVisitor();
56
57 /// Copy constructor that does a shallow copy.
58 CullVisitor(const CullVisitor&);
59
60 META_NodeVisitor(osgUtil, CullVisitor)
61
62 /** Convert 'this' into a osgUtil::CullVisitor pointer if Object is a osgUtil::CullVisitor, otherwise return 0.
63 * Equivalent to dynamic_cast<osgUtil::CullVisitor*>(this).*/
64 virtual osgUtil::CullVisitor* asCullVisitor() { return this; }
65
66 /** convert 'const this' into a const osgUtil::CullVisitor pointer if Object is a osgUtil::CullVisitor, otherwise return 0.
67 * Equivalent to dynamic_cast<const osgUtil::CullVisitor*>(this).*/
68 virtual const osgUtil::CullVisitor* asCullVisitor() const { return this; }
69
70 /** Convert 'this' into a osg::CullStack pointer if Object is a osg::CullStack, otherwise return 0.
71 * Equivalent to dynamic_cast<osg::CullStack*>(this).*/
72 virtual osg::CullStack* asCullStack() { return static_cast<osg::CullStack*>(this); }
73
74 /** convert 'const this' into a const osg::CullStack pointer if Object is a osg::CullStack, otherwise return 0.
75 * Equivalent to dynamic_cast<const osg::CullStack*>(this).*/
76 virtual const osg::CullStack* asCullStack() const { return static_cast<const osg::CullStack*>(this); }
77
78
79 using osg::NodeVisitor::clone;
80
81 /** Create a shallow copy of the CullVisitor, used by CullVisitor::create() to clone the prototype. */
82 virtual CullVisitor* clone() const { return new CullVisitor(*this); }
83
84 /** get the prototype singleton used by CullVisitor::create().*/
85 static osg::ref_ptr<CullVisitor>& prototype();
86
87 /** create a CullVisitor by cloning CullVisitor::prototype().*/
88 static CullVisitor* create();
89
90 virtual void reset();
91
92 struct Identifier : public osg::Referenced
93 {
94 Identifier() {}
95 virtual ~Identifier() {}
96 };
97
98 void setIdentifier(Identifier* identifier) { _identifier = identifier; }
99 Identifier* getIdentifier() { return _identifier.get(); }
100 const Identifier* getIdentifier() const { return _identifier.get(); }
101
102 virtual osg::Vec3 getEyePoint() const { return getEyeLocal(); }
103 virtual osg::Vec3 getViewPoint() const { return getViewPointLocal(); }
104
105 virtual float getDistanceToEyePoint(const osg::Vec3& pos, bool withLODScale) const;
106 virtual float getDistanceFromEyePoint(const osg::Vec3& pos, bool withLODScale) const;
107
108 virtual float getDistanceToViewPoint(const osg::Vec3& pos, bool withLODScale) const;
109
110 virtual void apply(osg::Node&);
111 virtual void apply(osg::Geode& node);
112 virtual void apply(osg::Drawable& drawable);
113 virtual void apply(osg::Billboard& node);
114 virtual void apply(osg::LightSource& node);
115 virtual void apply(osg::ClipNode& node);
116 virtual void apply(osg::TexGenNode& node);
117
118 virtual void apply(osg::Group& node);
119 virtual void apply(osg::Transform& node);
120 virtual void apply(osg::Projection& node);
121 virtual void apply(osg::Switch& node);
122 virtual void apply(osg::LOD& node);
123 virtual void apply(osg::ClearNode& node);
124 virtual void apply(osg::Camera& node);
125 virtual void apply(osg::OccluderNode& node);
126 virtual void apply(osg::OcclusionQueryNode& node);
127
128 /** Push state set on the current state group.
129 * If the state exists in a child state group of the current
130 * state group then move the current state group to that child.
131 * Otherwise, create a new state group for the state set, add
132 * it to the current state group then move the current state
133 * group pointer to the new state group.
134 */
135 inline void pushStateSet(const osg::StateSet* ss)
136 {
137 _currentStateGraph = _currentStateGraph->find_or_insert(ss);
138
139 bool useRenderBinDetails = (ss->useRenderBinDetails() && !ss->getBinName().empty()) &&
140 (_numberOfEncloseOverrideRenderBinDetails==0 || (ss->getRenderBinMode()&osg::StateSet::PROTECTED_RENDERBIN_DETAILS)!=0);
141
142 if (useRenderBinDetails)
143 {
144 _renderBinStack.push_back(_currentRenderBin);
145
146 _currentRenderBin = ss->getNestRenderBins() ?
147 _currentRenderBin->find_or_insert(ss->getBinNumber(),ss->getBinName()) :
148 _currentRenderBin->getStage()->find_or_insert(ss->getBinNumber(),ss->getBinName());
149 }
150
151 if ((ss->getRenderBinMode()&osg::StateSet::OVERRIDE_RENDERBIN_DETAILS)!=0)
152 {
153 ++_numberOfEncloseOverrideRenderBinDetails;
154 }
155 }
156
157 /** Pop the top state set and hence associated state group.
158 * Move the current state group to the parent of the popped
159 * state group.
160 */
161 inline void popStateSet()
162 {
163 const osg::StateSet* ss = _currentStateGraph->getStateSet();
164 if ((ss->getRenderBinMode()&osg::StateSet::OVERRIDE_RENDERBIN_DETAILS)!=0)
165 {
166 --_numberOfEncloseOverrideRenderBinDetails;
167 }
168
169 bool useRenderBinDetails = (ss->useRenderBinDetails() && !ss->getBinName().empty()) &&
170 (_numberOfEncloseOverrideRenderBinDetails==0 || (ss->getRenderBinMode()&osg::StateSet::PROTECTED_RENDERBIN_DETAILS)!=0);
171
172 if (useRenderBinDetails)
173 {
174 if (_renderBinStack.empty())
175 {
176 _currentRenderBin = _currentRenderBin->getStage();
177 }
178 else
179 {
180 _currentRenderBin = _renderBinStack.back();
181 _renderBinStack.pop_back();
182 }
183 }
184 _currentStateGraph = _currentStateGraph->_parent;
185 }
186
187 inline void setStateGraph(StateGraph* rg)
188 {
189 _rootStateGraph = rg;
190 _currentStateGraph = rg;
191 }
192
193 inline StateGraph* getRootStateGraph()
194 {
195 return _rootStateGraph.get();
196 }
197
198 inline StateGraph* getCurrentStateGraph()
199 {
200 return _currentStateGraph;
201 }
202
203 inline void setRenderStage(RenderStage* rg)
204 {
205 _rootRenderStage = rg;
206 _currentRenderBin = rg;
207 }
208
209 inline RenderStage* getRenderStage()
210 {
211 return _rootRenderStage.get();
212 }
213
214 inline RenderStage* getCurrentRenderStage()
215 {
216 return _currentRenderBin->getStage();
217 }
218
219 inline osg::Camera* getCurrentCamera()
220 {
221 return getCurrentRenderStage()->getCamera();
222 }
223
224 inline RenderBin* getCurrentRenderBin()
225 {
226 return _currentRenderBin;
227 }
228
229 inline void setCurrentRenderBin(RenderBin* rb)
230 {
231 _currentRenderBin = rb;
232 }
233
234 void setCalculatedNearPlane(value_type value) { _computed_znear = value; }
235 inline value_type getCalculatedNearPlane() const { return _computed_znear; }
236
237 void setCalculatedFarPlane(value_type value) { _computed_zfar = value; }
238 inline value_type getCalculatedFarPlane() const { return _computed_zfar; }
239
240 value_type computeNearestPointInFrustum(const osg::Matrix& matrix, const osg::Polytope::PlaneList& planes,const osg::Drawable& drawable);
241 value_type computeFurthestPointInFrustum(const osg::Matrix& matrix, const osg::Polytope::PlaneList& planes,const osg::Drawable& drawable);
242
243 bool updateCalculatedNearFar(const osg::Matrix& matrix,const osg::BoundingBox& bb);
244
245 bool updateCalculatedNearFar(const osg::Matrix& matrix,const osg::Drawable& drawable, bool isBillboard=false);
246
247 void updateCalculatedNearFar(const osg::Vec3& pos);
248
249 /** Add a drawable to current render graph.*/
250 inline void addDrawable(osg::Drawable* drawable,osg::RefMatrix* matrix);
251
252 /** Add a drawable and depth to current render graph.*/
253 inline void addDrawableAndDepth(osg::Drawable* drawable,osg::RefMatrix* matrix,float depth);
254
255 /** Add an attribute which is positioned relative to the modelview matrix.*/
256 inline void addPositionedAttribute(osg::RefMatrix* matrix,const osg::StateAttribute* attr);
257
258 /** Add an attribute which is positioned relative to the modelview matrix.*/
259 inline void addPositionedTextureAttribute(unsigned int textureUnit, osg::RefMatrix* matrix,const osg::StateAttribute* attr);
260
261
262 /** compute near plane based on the polgon intersection of primtives in near plane candidate list of drawables.
263 * Note, you have to set ComputeNearFarMode to COMPUTE_NEAR_FAR_USING_PRIMITIVES to be able to near plane candidate drawables to be recorded by the cull traversal. */
264 void computeNearPlane();
265
266 /** Re-implement CullStack's popProjectionMatrix() adding clamping of the projection matrix to
267 * the computed near and far.*/
268 virtual void popProjectionMatrix();
269
270
271 /** CullVisitor's default clamping of the projection float matrix to computed near and far values.
272 * Note, do not call this method directly, use clampProjectionMatrix(..) instead, unless you want to bypass the callback.*/
273 virtual bool clampProjectionMatrixImplementation(osg::Matrixf& projection, double& znear, double& zfar) const;
274
275 /** CullVisitor's default clamping of the projection double matrix to computed near and far values.
276 * Note, do not call this method directly, use clampProjectionMatrix(..) instead, unless you want to bypass the callback.*/
277 virtual bool clampProjectionMatrixImplementation(osg::Matrixd& projection, double& znear, double& zfar) const;
278
279 /** Clamp the projection float matrix to computed near and far values, use callback if it exists,
280 * otherwise use default CullVisitor implementation.*/
281 inline bool clampProjectionMatrix(osg::Matrixf& projection, value_type& znear, value_type& zfar) const
282 {
283 double zn = znear;
284 double zf = zfar;
285 bool result = false;
286 if (_clampProjectionMatrixCallback.valid()) result = _clampProjectionMatrixCallback->clampProjectionMatrixImplementation(projection, zn, zf);
287 else result = clampProjectionMatrixImplementation(projection, zn, zf);
288
289 if (result)
290 {
291 znear = zn;
292 zfar = zf;
293 return true;
294 }
295 else
296 return false;
297 }
298
299 /** Clamp the projection double matrix to computed near and far values, use callback if it exists,
300 * otherwise use default CullVisitor implementation.*/
301 inline bool clampProjectionMatrix(osg::Matrixd& projection, value_type& znear, value_type& zfar) const
302 {
303 double zn = znear;
304 double zf = zfar;
305 bool result = false;
306
307 if (_clampProjectionMatrixCallback.valid()) result = _clampProjectionMatrixCallback->clampProjectionMatrixImplementation(projection, zn, zf);
308 else result = clampProjectionMatrixImplementation(projection, zn, zf);
309
310 if (result)
311 {
312 znear = zn;
313 zfar = zf;
314 return true;
315 }
316 else
317 return false;
318 }
319
320
321 void setState(osg::State* state) { _renderInfo.setState(state); }
322 osg::State* getState() { return _renderInfo.getState(); }
323 const osg::State* getState() const { return _renderInfo.getState(); }
324
325 void setRenderInfo(osg::RenderInfo& renderInfo) { _renderInfo = renderInfo; }
326 osg::RenderInfo& getRenderInfo() { return _renderInfo; }
327 const osg::RenderInfo& getRenderInfo() const { return _renderInfo; }
328
329 protected:
330
331 virtual ~CullVisitor();
332
333 /** Prevent unwanted copy operator.*/
334 CullVisitor& operator = (const CullVisitor&) { return *this; }
335
336 inline void handle_cull_callbacks_and_traverse(osg::Node& node)
337 {
338 osg::Callback* callback = node.getCullCallback();
339 if (callback) callback->run(&node,this);
340 else traverse(node);
341 }
342
343 inline void handle_cull_callbacks_and_accept(osg::Node& node,osg::Node* acceptNode)
344 {
345 osg::Callback* callback = node.getCullCallback();
346 if (callback) callback->run(&node,this);
347 else acceptNode->accept(*this);
348 }
349
350 osg::ref_ptr<StateGraph> _rootStateGraph;
351 StateGraph* _currentStateGraph;
352
353 osg::ref_ptr<RenderStage> _rootRenderStage;
354 RenderBin* _currentRenderBin;
355 std::vector<RenderBin*> _renderBinStack;
356
357 value_type _computed_znear;
358 value_type _computed_zfar;
359
360 unsigned int _traversalOrderNumber;
361
362
363 typedef std::vector< osg::ref_ptr<RenderLeaf> > RenderLeafList;
364 RenderLeafList _reuseRenderLeafList;
365 unsigned int _currentReuseRenderLeafIndex;
366
367 inline RenderLeaf* createOrReuseRenderLeaf(osg::Drawable* drawable,osg::RefMatrix* projection,osg::RefMatrix* matrix, float depth=0.0f);
368
369 unsigned int _numberOfEncloseOverrideRenderBinDetails;
370
371 osg::RenderInfo _renderInfo;
372
373
374 struct MatrixPlanesDrawables
375 {
376 MatrixPlanesDrawables():
377 _drawable(0)
378 {
379 }
380
381 void set(const osg::Matrix& matrix, const osg::Drawable* drawable, const osg::Polytope& frustum)
382 {
383 _matrix = matrix;
384 _drawable = drawable;
385 if (!_planes.empty()) _planes.clear();
386
387 // create a new list of planes from the active walls of the frustum.
388 osg::Polytope::ClippingMask result_mask = frustum.getResultMask();
389 osg::Polytope::ClippingMask selector_mask = 0x1;
390 for(osg::Polytope::PlaneList::const_iterator itr=frustum.getPlaneList().begin();
391 itr!=frustum.getPlaneList().end();
392 ++itr)
393 {
394 if (result_mask&selector_mask) _planes.push_back(*itr);
395 selector_mask <<= 1;
396 }
397 }
398
399 MatrixPlanesDrawables(const MatrixPlanesDrawables& mpd):
400 _matrix(mpd._matrix),
401 _drawable(mpd._drawable),
402 _planes(mpd._planes) {}
403
404 MatrixPlanesDrawables& operator = (const MatrixPlanesDrawables& mpd)
405 {
406 _matrix = mpd._matrix;
407 _drawable = mpd._drawable;
408 _planes = mpd._planes;
409 return *this;
410 }
411
412 osg::Matrix _matrix;
413 const osg::Drawable* _drawable;
414 osg::Polytope::PlaneList _planes;
415 };
416
417 typedef std::multimap<value_type, MatrixPlanesDrawables> DistanceMatrixDrawableMap;
418 DistanceMatrixDrawableMap _nearPlaneCandidateMap;
419 DistanceMatrixDrawableMap _farPlaneCandidateMap;
420
421 osg::ref_ptr<Identifier> _identifier;
422};
423
424inline void CullVisitor::addDrawable(osg::Drawable* drawable,osg::RefMatrix* matrix)
425{
426 if (_currentStateGraph->leaves_empty())
427 {
428 // this is first leaf to be added to StateGraph
429 // and therefore should not already know to current render bin,
430 // so need to add it.
431 _currentRenderBin->addStateGraph(_currentStateGraph);
432 }
433 //_currentStateGraph->addLeaf(new RenderLeaf(drawable,matrix));
434 _currentStateGraph->addLeaf(createOrReuseRenderLeaf(drawable,_projectionStack.back().get(),matrix));
435}
436
437/** Add a drawable and depth to current render graph.*/
438inline void CullVisitor::addDrawableAndDepth(osg::Drawable* drawable,osg::RefMatrix* matrix,float depth)
439{
440 if (_currentStateGraph->leaves_empty())
441 {
442 // this is first leaf to be added to StateGraph
443 // and therefore should not already know to current render bin,
444 // so need to add it.
445 _currentRenderBin->addStateGraph(_currentStateGraph);
446 }
447 //_currentStateGraph->addLeaf(new RenderLeaf(drawable,matrix,depth));
448 _currentStateGraph->addLeaf(createOrReuseRenderLeaf(drawable,_projectionStack.back().get(),matrix,depth));
449}
450
451/** Add an attribute which is positioned relative to the modelview matrix.*/
452inline void CullVisitor::addPositionedAttribute(osg::RefMatrix* matrix,const osg::StateAttribute* attr)
453{
454 _currentRenderBin->getStage()->addPositionedAttribute(matrix,attr);
455}
456
457/** Add an attribute which is positioned relative to the modelview matrix.*/
458inline void CullVisitor::addPositionedTextureAttribute(unsigned int textureUnit, osg::RefMatrix* matrix,const osg::StateAttribute* attr)
459{
460 _currentRenderBin->getStage()->addPositionedTextureAttribute(textureUnit,matrix,attr);
461}
462
463inline RenderLeaf* CullVisitor::createOrReuseRenderLeaf(osg::Drawable* drawable,osg::RefMatrix* projection,osg::RefMatrix* matrix, float depth)
464{
465 // Skips any already reused renderleaf.
466 while (_currentReuseRenderLeafIndex<_reuseRenderLeafList.size() &&
467 _reuseRenderLeafList[_currentReuseRenderLeafIndex]->referenceCount()>1)
468 {
469 osg::notify(osg::INFO)<<"CullVisitor:createOrReuseRenderLeaf() skipping multiply referenced entry. _reuseRenderLeafList.size()="<< _reuseRenderLeafList.size()<<" _reuseRenderLeafList["<<_currentReuseRenderLeafIndex<<"]->referenceCount()="<<_reuseRenderLeafList[_currentReuseRenderLeafIndex]->referenceCount()<<std::endl;
470 ++_currentReuseRenderLeafIndex;
471 }
472
473 // If still within list, element must be singularly referenced then return it to be reused.
474 if (_currentReuseRenderLeafIndex<_reuseRenderLeafList.size())
475 {
476 RenderLeaf* renderleaf = _reuseRenderLeafList[_currentReuseRenderLeafIndex++].get();
477 renderleaf->set(drawable,projection,matrix,depth,_traversalOrderNumber++);
478 return renderleaf;
479 }
480
481
482 // Otherwise need to create new renderleaf.
483 RenderLeaf* renderleaf = new RenderLeaf(drawable,projection,matrix,depth,_traversalOrderNumber++);
484 _reuseRenderLeafList.push_back(renderleaf);
485
486 ++_currentReuseRenderLeafIndex;
487 return renderleaf;
488}
489
490}
491
492#endif