// ================================================================ // $Id: lsds_kdtree.cpp,v 1.18 2005/04/16 09:34:21 bittner Exp $ // **************************************************************** /** The KD tree based LSDS */ // Initial coding by /** @author Jiri Bittner */ // Standard headers #include #include #include #include #include #include "RssTree.h" #include "Environment.h" #include "VssRay.h" #include "Intersectable.h" #include "Ray.h" #include "Containers.h" #define DEBUG_SPLIT_COST 0 #define DEBUG_SPLITS 0 // Static variables int RssTreeLeaf::mailID = 0; inline void AddObject2Pvs(Intersectable *object, const int side, int &pvsBack, int &pvsFront) { if (!object) return; if (side <= 0) { if (!object->Mailed() && !object->Mailed(2)) { pvsBack++; if (object->Mailed(1)) object->Mail(2); else object->Mail(); } } if (side >= 0) { if (!object->Mailed(1) && !object->Mailed(2)) { pvsFront++; if (object->Mailed()) object->Mail(2); else object->Mail(1); } } } // Constructor RssTree::RssTree() { environment->GetIntValue("RssTree.maxDepth", termMaxDepth); environment->GetIntValue("RssTree.minPvs", termMinPvs); environment->GetIntValue("RssTree.minRays", termMinRays); environment->GetFloatValue("RssTree.maxRayContribution", termMaxRayContribution); environment->GetFloatValue("RssTree.maxCostRatio", termMaxCostRatio); environment->GetFloatValue("RssTree.minSize", termMinSize); termMinSize = sqr(termMinSize); environment->GetFloatValue("RssTree.refDirBoxMaxSize", refDirBoxMaxSize); refDirBoxMaxSize = sqr(refDirBoxMaxSize); environment->GetFloatValue("RssTree.epsilon", epsilon); environment->GetFloatValue("RssTree.ct_div_ci", ct_div_ci); environment->GetFloatValue("RssTree.maxTotalMemory", maxTotalMemory); environment->GetFloatValue("RssTree.maxStaticMemory", maxStaticMemory); float refDirAngle; environment->GetFloatValue("RssTree.refDirAngle", refDirAngle); environment->GetIntValue("RssTree.accessTimeThreshold", accessTimeThreshold); //= 1000; environment->GetIntValue("RssTree.minCollapseDepth", minCollapseDepth); // int minCollapseDepth = 4; // pRefDirThresh = cos(0.5*M_PI - M_PI*refDirAngle/180.0); // cosRefDir = cos(M_PI*refDirAngle/180.0); // sinRefDir = sin(M_PI*refDirAngle/180.0); // split type char sname[128]; environment->GetStringValue("RssTree.splitType", sname); string name(sname); if (name.compare("regular") == 0) splitType = ESplitRegular; else if (name.compare("heuristic") == 0) splitType = ESplitHeuristic; else if (name.compare("hybrid") == 0) splitType = ESplitHybrid; else { cerr<<"Invalid RssTree split type "<GetBoolValue("RssTree.randomize", randomize); environment->GetBoolValue("RssTree.splitUseOnlyDrivingAxis", mSplitUseOnlyDrivingAxis); environment->GetBoolValue("RssTree.useRss", mUseRss); environment->GetBoolValue("RssTree.interleaveDirSplits", mInterleaveDirSplits); environment->GetIntValue("RssTree.dirSplitDepth", mDirSplitDepth); root = NULL; splitCandidates = new vector; } RssTree::~RssTree() { if (root) delete root; } void RssStatistics::Print(ostream &app) const { app << "===== RssTree statistics ===============\n"; app << "#N_RAYS ( Number of rays )\n" << rays <IsActive()) { Intersectable *object; #if BIDIRECTIONAL_RAY object = (*ri).mRay->mOriginObject; if (object && !object->Mailed()) { pvsSize++; object->Mail(); } #endif object = (*ri).mRay->mTerminationObject; if (object && !object->Mailed()) { pvsSize++; object->Mail(); } } ComputeEntropyImportance(); mPvsSize = pvsSize; mValidPvs = true; } } bool RssTree::ClipRay( RssTreeNode::RayInfo &rayInfo, const AxisAlignedBox3 &box ) { float tmin, tmax; static Ray ray; ray.Init(rayInfo.mRay->GetOrigin(), rayInfo.mRay->GetDir(), Ray::LINE_SEGMENT); box.ComputeMinMaxT(ray, &tmin, &tmax); if (tmin >= tmax) return false; // now check if the ray origin lies inside the box if ( tmax < rayInfo.mRay->GetSize() ) { // this ray does not leave the box rayInfo.mRay->SetupEndPoints( ray.Extrap(tmax), rayInfo.mRay->mTermination ); return true; } return false; } void RssTree::Construct( VssRayContainer &rays, // forced bounding box is only used when computing from-box // visibility AxisAlignedBox3 *forcedBoundingBox ) { stat.Start(); maxMemory = maxStaticMemory; if (root) delete root; root = new RssTreeLeaf(NULL, rays.size()); // first construct a leaf that will get subdivide RssTreeLeaf *leaf = (RssTreeLeaf *) root; stat.nodes = 1; bbox.Initialize(); dirBBox.Initialize(); if (mUseRss) forcedBoundingBox = NULL; for(VssRayContainer::const_iterator ri = rays.begin(); ri != rays.end(); ri++) { RssTreeNode::RayInfo info(*ri); if (forcedBoundingBox) if (!ClipRay(info, *forcedBoundingBox)) continue; leaf->AddRay(info); bbox.Include((*ri)->GetOrigin()); bbox.Include((*ri)->GetTermination()); dirBBox.Include(Vector3( (*ri)->GetDirParametrization(0), (*ri)->GetDirParametrization(1), 0 ) ); } if ( forcedBoundingBox ) bbox = *forcedBoundingBox; cout<<"Bbox = "< maxMemory ) { // count statistics on unprocessed leafs while (!tStack.empty()) { // EvaluateLeafStats(tStack.top()); tStack.pop(); } break; } TraversalData data = tStack.top(); tStack.pop(); if (data.node->IsLeaf()) { RssTreeNode *node = SubdivideNode((RssTreeLeaf *) data.node, data.bbox, backBox, frontBox ); if (!node->IsLeaf()) { subdivided++; RssTreeInterior *interior = (RssTreeInterior *) node; // push the children on the stack tStack.push(TraversalData(interior->back, backBox, data.depth+1)); tStack.push(TraversalData(interior->front, frontBox, data.depth+1)); } else { // EvaluateLeafStats(data); } } else { RssTreeInterior *interior = (RssTreeInterior *) data.node; tStack.push(TraversalData(interior->back, GetBBox(interior->back), data.depth+1)); tStack.push(TraversalData(interior->front, GetBBox(interior->front), data.depth+1)); } } return subdivided; } RssTreeNode * RssTree::Subdivide(const TraversalData &tdata) { RssTreeNode *result = NULL; priority_queue tStack; // stack tStack; tStack.push(tdata); AxisAlignedBox3 backBox; AxisAlignedBox3 frontBox; int lastMem = 0; while (!tStack.empty()) { float mem = GetMemUsage(); if ( lastMem/10 != ((int)mem)/10) { cout< maxMemory ) { // count statistics on unprocessed leafs while (!tStack.empty()) { EvaluateLeafStats(tStack.top()); tStack.pop(); } break; } TraversalData data = tStack.top(); tStack.pop(); #if DEBUG_SPLITS Debug<<"#Splitting node"<Print(Debug); #endif RssTreeNode *node = SubdivideNode((RssTreeLeaf *) data.node, data.bbox, backBox, frontBox ); if (result == NULL) result = node; if (!node->IsLeaf()) { RssTreeInterior *interior = (RssTreeInterior *) node; // push the children on the stack tStack.push(TraversalData(interior->back, backBox, data.depth+1)); tStack.push(TraversalData(interior->front, frontBox, data.depth+1)); #if DEBUG_SPLITS Debug<<"#New nodes"<back->Print(Debug); interior->front->Print(Debug); Debug<<"#####################################"<rays.size(); // cout<<"ratio="<depth < mDirSplitDepth || mInterleaveDirSplits)) || (axis >= 3 && (leaf->depth >= mDirSplitDepth)) ) { if (!mSplitUseOnlyDrivingAxis || axis == sAxis || axis == dAxis) { if (splitType == ESplitRegular) { if (axis < 3) nPosition[axis] = (sBox.Min()[axis] + sBox.Max()[axis])*0.5f; else nPosition[axis] = (dBox.Min()[axis-3] + dBox.Max()[axis-3])*0.5f; nCostRatio[axis] = EvalCostRatio(leaf, axis, nPosition[axis], nRaysBack[axis], nRaysFront[axis], nPvsBack[axis], nPvsFront[axis] ); } else if (splitType == ESplitHeuristic) { nCostRatio[axis] = EvalCostRatioHeuristic( leaf, axis, nPosition[axis], nRaysBack[axis], nRaysFront[axis], nPvsBack[axis], nPvsFront[axis]); } else if (splitType == ESplitHybrid) { if (leaf->depth > 7) nCostRatio[axis] = EvalCostRatioHeuristic( leaf, axis, nPosition[axis], nRaysBack[axis], nRaysFront[axis], nPvsBack[axis], nPvsFront[axis]); else { if (axis < 3) nPosition[axis] = (sBox.Min()[axis] + sBox.Max()[axis])*0.5f; else nPosition[axis] = (dBox.Min()[axis-3] + dBox.Max()[axis-3])*0.5f; nCostRatio[axis] = EvalCostRatio(leaf, axis, nPosition[axis], nRaysBack[axis], nRaysFront[axis], nPvsBack[axis], nPvsFront[axis] ); } } else { cerr<<"RssTree: Unknown split heuristics\n"; exit(1); } if ( bestAxis == -1) bestAxis = axis; else if ( nCostRatio[axis] < nCostRatio[bestAxis] ) bestAxis = axis; } } axis = bestAxis; position = nPosition[bestAxis]; raysBack = nRaysBack[bestAxis]; raysFront = nRaysFront[bestAxis]; pvsBack = nPvsBack[bestAxis]; pvsFront = nPvsFront[bestAxis]; return nCostRatio[bestAxis]; } float RssTree::EvalCostRatioHeuristic( RssTreeLeaf *leaf, const int axis, float &bestPosition, int &raysBack, int &raysFront, int &pvsBack, int &pvsFront ) { AxisAlignedBox3 box; float minBox, maxBox; if (axis < 3) { box = GetBBox(leaf); minBox = box.Min(axis); maxBox = box.Max(axis); } else { box = GetDirBBox(leaf); minBox = box.Min(axis-3); maxBox = box.Max(axis-3); } SortSplitCandidates(leaf, axis); // go through the lists, count the number of objects left and right // and evaluate the following cost funcion: // C = ct_div_ci + (ql*rl + qr*rr)/queries int rl=0, rr = leaf->rays.size(); int pl=0, pr = leaf->GetPvsSize(); float sizeBox = maxBox - minBox; float minBand = minBox + 0.1*(maxBox - minBox); float maxBand = minBox + 0.9*(maxBox - minBox); float minRatio = 1e20; Intersectable::NewMail(); // set all object as belonging to the fron pvs for(RssTreeNode::RayInfoContainer::iterator ri = leaf->rays.begin(); ri != leaf->rays.end(); ri++) if ((*ri).mRay->IsActive()) { Intersectable *object = (*ri).mRay->mTerminationObject; if (object) if (!object->Mailed()) { object->Mail(); object->mCounter = 1; } else object->mCounter++; } Intersectable::NewMail(); for(vector::const_iterator ci = splitCandidates->begin(); ci < splitCandidates->end(); ci++) { VssRay *ray; switch ((*ci).type) { case SortableEntry::ERayMin: { rr--; rl++; ray = (VssRay *) (*ci).data; Intersectable *object = ray->mTerminationObject; if (object) { if (!object->Mailed()) { object->Mail(); pl++; } if (--object->mCounter == 0) pr--; } break; } } float position = (*ci).value; if (position > minBand && position < maxBand) { float ratio = GetCostRatio( leaf, axis, position, rl, rr, pl, pr); // cout<<"pos="<<(*ci).value<<"\t q=("<clear(); int requestedSize = 2*(node->rays.size()); // creates a sorted split candidates array if (splitCandidates->capacity() > 500000 && requestedSize < (int)(splitCandidates->capacity()/10) ) { delete splitCandidates; splitCandidates = new vector; } splitCandidates->reserve(requestedSize); // insert all queries for(RssTreeNode::RayInfoContainer::const_iterator ri = node->rays.begin(); ri < node->rays.end(); ri++) { if ((*ri).mRay->IsActive()) { if (axis < 3) { splitCandidates->push_back(SortableEntry(SortableEntry::ERayMin, (*ri).ExtrapOrigin(axis), (void *)(*ri).mRay) ); } else { float pos = (*ri).mRay->GetDirParametrization(axis-3); splitCandidates->push_back(SortableEntry(SortableEntry::ERayMin, pos, (void *)(*ri).mRay) ); } } } stable_sort(splitCandidates->begin(), splitCandidates->end()); } void RssTree::EvaluateLeafStats(const TraversalData &data) { // the node became a leaf -> evaluate stats for leafs RssTreeLeaf *leaf = (RssTreeLeaf *)data.node; if (data.depth >= termMaxDepth) stat.maxDepthNodes++; // if ( (int)(leaf->rays.size()) < termMinCost) // stat.minCostNodes++; if ( leaf->GetPvsSize() < termMinPvs) stat.minPvsNodes++; if ( leaf->GetPvsSize() < termMinRays) stat.minRaysNodes++; if (leaf->GetAvgRayContribution() > termMaxRayContribution ) stat.maxRayContribNodes++; if (SqrMagnitude(data.bbox.Size()) <= termMinSize) { stat.minSizeNodes++; } if ( (int)(leaf->rays.size()) > stat.maxRayRefs) stat.maxRayRefs = leaf->rays.size(); } bool RssTree::TerminationCriteriaSatisfied(RssTreeLeaf *leaf) { return ( (leaf->GetPvsSize() < termMinPvs) || (leaf->rays.size() < termMinRays) || // (leaf->GetAvgRayContribution() > termMaxRayContribution ) || (leaf->depth >= termMaxDepth) || (SqrMagnitude(GetBBox(leaf).Size()) <= termMinSize) || (mUseRss && leaf->mPassingRays == leaf->rays.size()) ); } RssTreeNode * RssTree::SubdivideNode( RssTreeLeaf *leaf, const AxisAlignedBox3 &box, AxisAlignedBox3 &backBBox, AxisAlignedBox3 &frontBBox ) { if (TerminationCriteriaSatisfied(leaf)) { #if 0 if (leaf->depth >= termMaxDepth) { cout<<"Warning: max depth reached depth="<<(int)leaf->depth<<" rays="<rays.size()<mT << endl; // determine the side of this ray with respect to the plane int side = node->ComputeRaySide(*ri); if (side == 0) { if ((*ri).mRay->HasPosDir(axis)) { back->AddRay(*ri); front->AddRay(*ri); } else { back->AddRay(*ri); front->AddRay(*ri); } } else if (side == 1) front->AddRay(*ri); else back->AddRay(*ri); } else (*ri).mRay->Unref(); } } else { // rays front/back for(RssTreeNode::RayInfoContainer::iterator ri = leaf->rays.begin(); ri != leaf->rays.end(); ri++) { if ((*ri).mRay->IsActive()) { // first unref ray from the former leaf (*ri).mRay->Unref(); int side; if ((*ri).mRay->GetDirParametrization(axis - 3) <= position) side = -1; else side = 1; if (side == 1) front->AddRay(*ri); else back->AddRay(*ri); } else (*ri).mRay->Unref(); } } #if 0 front->SetPvsSize(pvsFront); back->SetPvsSize(pvsBack); // compute entropy as well front->ComputeEntropyImportance(); back->ComputeEntropyImportance(); #else front->UpdatePvsSize(); back->UpdatePvsSize(); #endif // update stats stat.rayRefs -= leaf->rays.size(); stat.rayRefs += raysBack + raysFront; delete leaf; return node; } int RssTree::ReleaseMemory(const int time) { stack tstack; // find a node in the tree which subtree will be collapsed int maxAccessTime = time - accessTimeThreshold; int released; tstack.push(root); while (!tstack.empty()) { RssTreeNode *node = tstack.top(); tstack.pop(); if (!node->IsLeaf()) { RssTreeInterior *in = (RssTreeInterior *)node; // cout<<"depth="<<(int)in->depth<<" time="<lastAccessTime<depth >= minCollapseDepth && in->lastAccessTime <= maxAccessTime) { released = CollapseSubtree(node, time); break; } if (in->back->GetAccessTime() < in->front->GetAccessTime()) { tstack.push(in->front); tstack.push(in->back); } else { tstack.push(in->back); tstack.push(in->front); } } } while (tstack.empty()) { // could find node to collaps... // cout<<"Could not find a node to release "< maxTotalMemory) { ReleaseMemory( pass ); } AxisAlignedBox3 backBBox, frontBBox; // subdivide the node node = SubdivideNode(leaf, leafBBox, backBBox, frontBBox ); } return node; } void RssTree::UpdateRays(VssRayContainer &remove, VssRayContainer &add ) { RssTreeLeaf::NewMail(); // schedule rays for removal for(VssRayContainer::const_iterator ri = remove.begin(); ri != remove.end(); ri++) { (*ri)->ScheduleForRemoval(); } int inactive=0; for(VssRayContainer::const_iterator ri = remove.begin(); ri != remove.end(); ri++) { if ((*ri)->ScheduledForRemoval()) // RemoveRay(*ri, NULL, false); // !!! BUG - with true it does not work correctly - aggreated delete RemoveRay(*ri, NULL, true); else inactive++; } // cout<<"all/inactive"< *affectedLeaves, const bool removeAllScheduledRays ) { stack tstack; tstack.push(RayTraversalData(root, RssTreeNode::RayInfo(ray))); RayTraversalData data; // cout<<"Number of ray refs = "<RefCount()<IsLeaf()) { // split the set of rays in two groups intersecting the // two subtrees TraverseInternalNode(data, tstack); } else { // remove the ray from the leaf // find the ray in the leaf and swap it with the last ray... RssTreeLeaf *leaf = (RssTreeLeaf *)data.node; if (!leaf->Mailed()) { leaf->Mail(); if (affectedLeaves) affectedLeaves->push_back(leaf); if (removeAllScheduledRays) { int tail = leaf->rays.size()-1; for (int i=0; i < (int)(leaf->rays.size()); i++) { if (leaf->rays[i].mRay->ScheduledForRemoval()) { // find a ray to replace it with while (tail >= i && leaf->rays[tail].mRay->ScheduledForRemoval()) { stat.removedRayRefs++; leaf->rays[tail].mRay->Unref(); leaf->rays.pop_back(); tail--; } if (tail < i) break; stat.removedRayRefs++; leaf->rays[i].mRay->Unref(); leaf->rays[i] = leaf->rays[tail]; leaf->rays.pop_back(); tail--; } } } } if (!removeAllScheduledRays) for (int i=0; i < (int)leaf->rays.size(); i++) { if (leaf->rays[i].mRay == ray) { stat.removedRayRefs++; ray->Unref(); leaf->rays[i] = leaf->rays[leaf->rays.size()-1]; leaf->rays.pop_back(); // check this ray again break; } } } } if (ray->RefCount() != 0) { cerr<<"Error: Number of remaining refs = "<RefCount()< tstack; tstack.push(RayTraversalData(root, info)); RayTraversalData data; while (!tstack.empty()) { data = tstack.top(); tstack.pop(); if (!data.node->IsLeaf()) { TraverseInternalNode(data, tstack); } else { // remove the ray from the leaf // find the ray in the leaf and swap it with the last ray... RssTreeLeaf *leaf = (RssTreeLeaf *)data.node; leaf->AddRay(data.rayData); stat.addedRayRefs++; } } } void RssTree::TraverseInternalNode( RayTraversalData &data, stack &tstack) { RssTreeInterior *in = (RssTreeInterior *) data.node; if (in->axis <= RssTreeNode::SPLIT_Z) { // determine the side of this ray with respect to the plane int side = in->ComputeRaySide(data.rayData ); if (side == 0) { if (data.rayData.mRay->HasPosDir(in->axis)) { tstack.push(RayTraversalData(in->back, data.rayData) ); tstack.push(RayTraversalData(in->front, data.rayData) ); } else { tstack.push(RayTraversalData(in->back, data.rayData ) ); tstack.push(RayTraversalData(in->front, data.rayData) ); } } else if (side == 1) tstack.push(RayTraversalData(in->front, data.rayData)); else tstack.push(RayTraversalData(in->back, data.rayData)); } else { // directional split if (data.rayData.mRay->GetDirParametrization(in->axis - 3) <= in->position) tstack.push(RayTraversalData(in->back, data.rayData)); else tstack.push(RayTraversalData(in->front, data.rayData)); } } int RssTree::CollapseSubtree(RssTreeNode *sroot, const int time) { // first count all rays in the subtree // use mail 1 for this purpose stack tstack; int rayCount = 0; int totalRayCount = 0; int collapsedNodes = 0; #if DEBUG_COLLAPSE cout<<"Collapsing subtree"< tstack; tstack.push(root); Intersectable::NewMail(); int pvsSize = 0; while (!tstack.empty()) { RssTreeNode *node = tstack.top(); tstack.pop(); if (node->IsLeaf()) { RssTreeLeaf *leaf = (RssTreeLeaf *)node; for(RssTreeNode::RayInfoContainer::iterator ri = leaf->rays.begin(); ri != leaf->rays.end(); ri++) if ((*ri).mRay->IsActive()) { Intersectable *object; #if BIDIRECTIONAL_RAY object = (*ri).mRay->mOriginObject; if (object && !object->Mailed()) { pvsSize++; object->Mail(); } #endif object = (*ri).mRay->mTerminationObject; if (object && !object->Mailed()) { pvsSize++; object->Mail(); } } } else { RssTreeInterior *in = (RssTreeInterior *)node; if (in->axis < 3) { if (box.Max(in->axis) >= in->position ) tstack.push(in->front); if (box.Min(in->axis) <= in->position ) tstack.push(in->back); } else { // both nodes for directional splits tstack.push(in->front); tstack.push(in->back); } } } return pvsSize; } int RssTree::CollectPvs(const AxisAlignedBox3 &box, ObjectContainer &pvs ) const { stack tstack; tstack.push(root); Intersectable::NewMail(); while (!tstack.empty()) { RssTreeNode *node = tstack.top(); tstack.pop(); if (node->IsLeaf()) { RssTreeLeaf *leaf = (RssTreeLeaf *)node; for(RssTreeNode::RayInfoContainer::iterator ri = leaf->rays.begin(); ri != leaf->rays.end(); ri++) if ((*ri).mRay->IsActive()) { Intersectable *object; object = (*ri).mRay->mTerminationObject; if (object && !object->Mailed()) { pvs.push_back(object); object->Mail(); } } } else { RssTreeInterior *in = (RssTreeInterior *)node; if (in->axis < 3) { if (box.Max(in->axis) >= in->position ) tstack.push(in->front); if (box.Min(in->axis) <= in->position ) tstack.push(in->back); } else { // both nodes for directional splits tstack.push(in->front); tstack.push(in->back); } } } return pvs.size(); } void RssTree::GetTreeStatistics( float &avgPvsSize, float &avgRayContribution, float &avgPvsEntropy, float &avgRayLengthEntropy, float &avgImportance ) { stack tstack; tstack.push(root); float sumPvsSize = 0.0f; float sumRayContribution = 0.0f; float sumImportance = 0.0f; float sumPvsEntropy = 0.0f; float sumRayLengthEntropy = 0.0f; int leaves = 0; while (!tstack.empty()) { RssTreeNode *node = tstack.top(); tstack.pop(); if (node->IsLeaf()) { leaves++; RssTreeLeaf *leaf = (RssTreeLeaf *)node; sumPvsSize += leaf->GetPvsSize(); sumRayContribution += leaf->GetAvgRayContribution(); sumPvsEntropy += leaf->mPvsEntropy; sumRayLengthEntropy += leaf->mRayLengthEntropy; float imp = leaf->GetImportance(); if (imp > 1.0f) cout<<"warning imp > 1.0f:"<front); tstack.push(in->back); } } avgPvsSize = sumPvsSize/(float)leaves; avgRayContribution = sumRayContribution/(float)leaves; avgPvsEntropy = sumPvsEntropy/(float)leaves; avgRayLengthEntropy = sumRayLengthEntropy/(float)leaves; avgImportance = sumImportance/(float)leaves; } int RssTree::GenerateRays(const float ratioPerLeaf, SimpleRayContainer &rays) { stack tstack; tstack.push(root); while (!tstack.empty()) { RssTreeNode *node = tstack.top(); tstack.pop(); if (node->IsLeaf()) { RssTreeLeaf *leaf = (RssTreeLeaf *)node; float c = leaf->GetImportance(); int num = (c*ratioPerLeaf + 0.5); // cout<GetImportance(); int num = (c*ratioPerLeaf + 0.5); GenerateLeafRays(leaf, num, rays); } return rays.size(); } float RssTree::GetAvgPvsSize() { stack tstack; tstack.push(root); int sumPvs = 0; int leaves = 0; while (!tstack.empty()) { RssTreeNode *node = tstack.top(); tstack.pop(); if (node->IsLeaf()) { RssTreeLeaf *leaf = (RssTreeLeaf *)node; // update pvs size leaf->UpdatePvsSize(); sumPvs += leaf->GetPvsSize(); leaves++; } else { RssTreeInterior *in = (RssTreeInterior *)node; // both nodes for directional splits tstack.push(in->front); tstack.push(in->back); } } return sumPvs/(float)leaves; } float RssTreeLeaf::GetImportance() const { if (1) { return GetAvgRayContribution(); // return GetPvsSize(); } else { // return GetAvgRayContribution()*mEntropyImportance; //return GetAvgRayContribution(); return mEntropyImportance; } } float RssTreeLeaf::ComputePvsEntropy() { int samples = 0; Intersectable::NewMail(); // set all object as belonging to the fron pvs for(RssTreeNode::RayInfoContainer::iterator ri = rays.begin(); ri != rays.end(); ri++) if ((*ri).mRay->IsActive()) { Intersectable *object = (*ri).mRay->mTerminationObject; if (object) { if (!object->Mailed()) { object->Mail(); object->mCounter = 1; } else object->mCounter++; samples++; } } float entropy = 0.0f; if (samples > 1) { Intersectable::NewMail(); for(RayInfoContainer::const_iterator ri = rays.begin(); ri != rays.end(); ri++) if ((*ri).mRay->IsActive()) { Intersectable *object = (*ri).mRay->mTerminationObject; if (object) { if (!object->Mailed()) { object->Mail(); float p = object->mCounter/(float)samples; entropy -= p*log(p); } } } entropy = entropy/log((float)samples); } else entropy = 1.0f; return entropy; } float RssTreeLeaf::ComputeRayLengthEntropy() { // get sum of all ray lengths // consider only passing rays or originating rays float sum = 0.0f; int samples = 0; int i=0; for(RayInfoContainer::const_iterator ri = rays.begin(); ri != rays.end(); ri++) if ((*ri).mRay->IsActive()) { // float s; // if (i == 0) // s = 200; // else // s = 100; // i++; sum += (*ri).mRay->GetSize(); samples++; } float entropy = 0.0f; if (samples > 1) { i = 0; for(RayInfoContainer::const_iterator ri = rays.begin(); ri != rays.end(); ri++) if ((*ri).mRay->IsActive()) { // float s; // if (i==0) // s = 200; // else // s = 100; // i++; // float p = s/sum; float p = (*ri).mRay->GetSize()/sum; entropy -= p*log(p); } entropy = entropy/log((float)samples); } else entropy = 1.0f; return entropy; } void RssTreeLeaf::ComputeEntropyImportance() { mPvsEntropy = ComputePvsEntropy(); mRayLengthEntropy = ComputeRayLengthEntropy(); // mEntropy = 1.0f - ComputeRayLengthEntropy(); mEntropyImportance = 1.0f - ComputePvsEntropy(); // cout<<"ei="<parent == NULL) return bbox; if (!node->IsLeaf()) return ((RssTreeInterior *)node)->bbox; // evaluate bounding box from the ray origins AxisAlignedBox3 box; box.Initialize(); RssTreeLeaf *leaf = (RssTreeLeaf *)node; for(RssTreeNode::RayInfoContainer::iterator ri = leaf->rays.begin(); ri != leaf->rays.end(); ri++) if ((*ri).mRay->IsActive()) { box.Include((*ri).GetOrigin()); } return box; }