source: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsParser.cpp @ 975

Revision 975, 19.7 KB checked in by mattausch, 18 years ago (diff)
Line 
1// ---------------------------------------------------------------------------
2//  Includes for all the program files to see
3// ---------------------------------------------------------------------------
4#include <string.h>
5#include <stdlib.h>
6#include <iostream>
7using namespace std;
8#include <xercesc/util/PlatformUtils.hpp>
9
10// ---------------------------------------------------------------------------
11//  Includes
12// ---------------------------------------------------------------------------
13#include <xercesc/framework/StdInInputSource.hpp>
14#include <xercesc/parsers/SAXParser.hpp>
15#include <xercesc/util/OutOfMemoryException.hpp>
16
17// ---------------------------------------------------------------------------
18//  Includes
19// ---------------------------------------------------------------------------
20#include <xercesc/sax/AttributeList.hpp>
21#include <xercesc/sax/SAXParseException.hpp>
22#include <xercesc/sax/SAXException.hpp>
23
24#include "ViewCellsParser.h"
25
26#include "ViewCellsParserXerces.h"
27#include "Mesh.h"
28#include "VspBspTree.h"
29#include "ViewCellBsp.h"
30#include "VspKdTree.h"
31#include "ViewCellsManager.h"
32#include "GzFileInputSource.h"
33
34namespace GtpVisibilityPreprocessor {
35
36
37// ---------------------------------------------------------------------------
38//  Local data
39//
40//  doNamespaces
41//      Indicates whether namespace processing should be enabled or not.
42//      The default is no, but -n overrides that.
43//
44//  doSchema
45//      Indicates whether schema processing should be enabled or not.
46//      The default is no, but -s overrides that.
47//
48//  schemaFullChecking
49//      Indicates whether full schema constraint checking should be enabled or not.
50//      The default is no, but -s overrides that.
51//
52//  valScheme
53//      Indicates what validation scheme to use. It defaults to 'auto', but
54//      can be set via the -v= command.
55// ---------------------------------------------------------------------------
56static bool     doNamespaces       = false;
57static bool     doSchema           = false;
58static bool     schemaFullChecking = false;
59static SAXParser::ValSchemes    valScheme       = SAXParser::Val_Auto;
60
61
62
63
64
65// ---------------------------------------------------------------------------
66//  StdInParseHandlers: Constructors and Destructor
67// ---------------------------------------------------------------------------
68ViewCellsParseHandlers::ViewCellsParseHandlers(ObjectContainer *objects,
69                                                                                           BoundingBoxConverter *bconverter,
70                                                                                           Environment *env):
71  mElementCount(0)
72  , mAttrCount(0)
73  , mCharacterCount(0)
74  , mSpaceCount(0)
75  , mViewCellsManager(NULL)
76  , mVspBspTree(NULL)
77  , mBspTree(NULL)
78  , mViewCellsTree(NULL)
79  , mParseViewCells(true)
80  , mCurrentViewCell(NULL)
81  , mCurrentBspNode(NULL)
82  , mObjects(objects)
83  , mBoundingBoxConverter(bconverter)
84  , mEnvironment(env)
85{
86}
87
88
89ViewCellsParseHandlers::~ViewCellsParseHandlers()
90{
91}
92
93
94// ---------------------------------------------------------------------------
95//  StdInParseHandlers: Implementation of the SAX DocumentHandler interface
96// ---------------------------------------------------------------------------
97
98
99void ViewCellsParseHandlers::endElement(const XMLCh* const name)
100{
101  StrX lname(name);
102  string element(lname.LocalForm());
103
104  if (element == "ViewCells")
105          EndViewCells();
106
107  if (element == "BoundingBoxes")
108          EndBoundingBoxes();
109
110  // inside the view cell description
111  if (mParseViewCells)
112  {
113          if (element == "Interior")
114                  EndViewCellInterior();
115  }
116  else
117  {
118          if (element == "Interior")
119                  EndBspInterior();
120  }
121}
122
123
124void ViewCellsParseHandlers::EndBspInterior()
125{
126        // go one up in the tree
127        if (mCurrentBspNode->GetParent())
128        {       Debug << "]";
129                mCurrentBspNode = mCurrentBspNode->GetParent();
130        }
131}
132
133
134void ViewCellsParseHandlers::EndViewCellInterior()
135{
136        // go one up in the tree
137        if (mCurrentViewCell->GetParent())
138        {       Debug << "]";
139                mCurrentViewCell = mCurrentViewCell->GetParent();
140        }
141}
142
143
144inline static bool vlt(ViewCell *v1, ViewCell *v2)
145{
146        return v1->mId < v2->mId;
147}
148
149
150void ViewCellsParseHandlers::EndViewCells()
151{
152        // sort view cells to help associating view cells according to their id
153        stable_sort(mViewCells.begin(), mViewCells.end(), vlt);
154        mParseViewCells = false;
155}
156
157
158void ViewCellsParseHandlers::EndBoundingBoxes()
159{
160        // all bounding boxes gathered in this step =>
161        // associate object ids with bounding boxes
162        long startTime = GetTime();
163       
164        if (mBoundingBoxConverter)
165                mBoundingBoxConverter->IdentifyObjects(mIBoundingBoxes, *mObjects);
166
167        Debug << "\nconverted bounding boxes to objects in "
168                  << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
169}
170
171
172void ViewCellsParseHandlers::StartHierarchy(AttributeList&  attributes)
173{
174        int len = attributes.getLength();
175 
176        for (int i = 0; i < len; ++ i)
177        {
178                string attrName(StrX(attributes.getName(i)).LocalForm());
179               
180                if (attrName == "name")
181                {
182                        StrX attrValue(attributes.getValue(i));
183                       
184                        const char *ptr = attrValue.LocalForm();
185                       
186                        //-- the view cells manager is created here
187                        CreateViewCellsManager(ptr);
188                }
189        }
190}
191
192
193void ViewCellsParseHandlers::startBspElement(string element,
194                                                                                         AttributeList& attributes)
195{
196        if (element == "Interior")
197        {
198                Debug << "[";
199                StartBspInterior(attributes);
200        }
201
202        if (element == "Leaf")
203        {
204                Debug << "l";
205                StartBspLeaf(attributes);
206        }
207}
208
209
210void ViewCellsParseHandlers::startElement(const XMLCh* const name,
211                                                                                  AttributeList& attributes)
212{
213        StrX lname(name);
214        string element(lname.LocalForm());
215
216
217        if (element == "ViewCells")
218        {
219                Debug << "parsing view cells" << endl;
220                mParseViewCells = true;
221        }
222
223        // decides about the view cell hierarchy
224        if (element == "HierarchyType")
225        //if (element == "Hierarchy")
226        {
227                //Debug << "parsing spatial hierarchy" << endl;
228                //mParseViewCells = false;
229                StartHierarchy(attributes);
230        }
231       
232        // decides the used view cell hierarchy
233        if (element == "ViewSpaceBox")
234        {
235                Debug << "v";
236                StartViewSpaceBox(attributes);
237        }
238
239        // decides the used view cell hierarchy
240        if (element == "BoundingBox")
241        {
242                Debug << "b";
243                StartBoundingBox(attributes);
244        }
245
246       
247        if (!mParseViewCells)
248        {
249                //-- use different methods for the given view cell hierarchy types
250                if (mViewCellsManager)
251                {
252                        switch (mViewCellsManager->GetType())
253                        {
254                        case ViewCellsManager::BSP:
255                        case ViewCellsManager::VSP_BSP:
256                                startBspElement(element, attributes);
257                                break;
258       
259                        default:
260                                Debug << "not implemented" << endl;
261                                break;
262                        }
263                }
264        }
265        else
266        {
267                // interiors + leaves interpreted view cells else
268                if (element == "Interior")
269                {
270                        Debug << "[";
271                        StartViewCellInterior(attributes);
272                }
273
274                if (element == "Leaf")
275                {
276                        Debug << "l";
277                        StartViewCellLeaf(attributes);
278                }
279        }
280
281        ++ mElementCount;
282        mAttrCount += attributes.getLength();
283}
284
285
286inline bool ilt(Intersectable *obj1, Intersectable *obj2)
287{
288        return obj1->mId < obj2->mId;
289}
290
291
292void ViewCellsParseHandlers::StartViewCell(ViewCell *viewCell, AttributeList&  attributes)
293{
294        int len = attributes.getLength();
295        vector<int> objIndices;
296
297        for (int i = 0; i < len; ++ i)
298        {
299                string attrName(StrX(attributes.getName(i)).LocalForm());
300               
301                if (attrName == "pvs")
302                {
303                        StrX attrValue(attributes.getValue(i));
304                       
305                        // handle coordIndex
306                        objIndices.clear();
307                        const char *ptr = attrValue.LocalForm();
308                        char *endptr;
309                       
310                        while (1)
311                        {
312                                int index = strtol(ptr, &endptr, 10);
313
314                                if (ptr == endptr)
315                                        break;
316
317                                objIndices.push_back(index);
318
319                                ptr = endptr;
320                        }
321
322                        //TODO: find objects and add them to pvs
323                        // TODO: get view cell with specified id
324                        MeshInstance dummyInst(NULL);
325
326                        vector<int>::const_iterator it, it_end = objIndices.end();
327                        for (it = objIndices.begin(); it != it_end; ++ it)
328                        {
329                                const int objId = *it; 
330                                dummyInst.SetId(objId);
331
332                                ObjectContainer::iterator oit =
333                                  lower_bound(mObjects->begin(), mObjects->end(), (Intersectable *)&dummyInst, ilt);
334                               
335                                                       
336                                if ((oit != mObjects->end()) && ((*oit)->GetId() == objId))
337                                {
338                                        // $$JB we should store a float a per object which corresponds
339                                        // to sumof pdfs, i.e. its relative visibility
340                                        // temporarily set to 1.0f
341                                        viewCell->GetPvs().AddSample(*oit, 1.0f);                               
342                                }
343                                else
344                                {
345                                        Debug << "error: object with id " << objId << " does not exist" << endl;
346                                }
347                        }
348                }
349                else if (attrName == "id")
350                {
351                        StrX attrValue(attributes.getValue(i));
352                       
353                        const char *ptr = attrValue.LocalForm();
354                        char *endptr = NULL;
355                        const int id = strtol(ptr, &endptr, 10);
356
357                        viewCell->SetId(id);
358                }
359                /*else if (attrName == "active")
360                {
361                        StrX attrValue(attributes.getValue(i));
362                       
363                        const char *ptr = attrValue.LocalForm();
364                        char *endptr = NULL;
365                        const bool isActive = (bool)strtol(ptr, &endptr, 10);
366
367                        if (isActive)
368                                viewCell->SetActive();
369                }*/
370                else if (attrName == "mergecost")
371                {
372                        StrX attrValue(attributes.getValue(i));
373                       
374                        const char *ptr = attrValue.LocalForm();
375                        char *endptr = NULL;
376                        const float cost = (float)strtod(ptr, &endptr);
377
378                        viewCell->SetMergeCost(cost);
379                }
380        }
381}
382
383
384void ViewCellsParseHandlers::StartViewSpaceBox(AttributeList& attributes)
385{
386        int len = attributes.getLength();
387
388        Vector3 bmin, bmax;
389
390        for (int i = 0; i < len; ++ i)
391        {
392                string attrName(StrX(attributes.getName(i)).LocalForm());
393                StrX attrValue(attributes.getValue(i));
394                const char *ptr = attrValue.LocalForm();
395
396                if (attrName == "min")
397                {
398                        sscanf(ptr, "%f %f %f",
399                                   &bmin.x, &bmin.y, &bmin.z);
400                }
401                else if (attrName == "max")
402                {
403                        sscanf(ptr, "%f %f %f",
404                                   &bmax.x, &bmax.y, &bmax.z);
405                }
406        }
407
408        mViewSpaceBox = AxisAlignedBox3(bmin, bmax);
409
410        Debug << "\nview space box: " << mViewSpaceBox << endl;
411}
412
413
414void ViewCellsParseHandlers::StartBoundingBox(AttributeList& attributes)
415{
416        int len = attributes.getLength();
417
418        Vector3 bmin, bmax;
419        int id;
420
421        for (int i = 0; i < len; ++ i)
422        {
423                string attrName(StrX(attributes.getName(i)).LocalForm());
424                StrX attrValue(attributes.getValue(i));
425                const char *ptr = attrValue.LocalForm();
426
427
428                if (attrName == "id")
429                {
430                        sscanf(ptr, "%d", &id);
431                }
432
433                if (attrName == "min")
434                {
435                        sscanf(ptr, "%f %f %f",
436                                   &bmin.x, &bmin.y, &bmin.z);
437                }
438                else if (attrName == "max")
439                {
440                        sscanf(ptr, "%f %f %f",
441                                   &bmax.x, &bmax.y, &bmax.z);
442                }
443        }
444
445        AxisAlignedBox3 box(bmin, bmax);
446        mIBoundingBoxes.push_back(IndexedBoundingBox(id, box));
447
448        //Debug << "bbox: " << box << endl;
449}
450
451
452void ViewCellsParseHandlers::StartBspLeaf(AttributeList& attributes)
453{
454        BspLeaf * leaf =
455                new BspLeaf(dynamic_cast<BspInterior *>(mCurrentBspNode), NULL);
456
457        if (mCurrentBspNode) // replace front or (if not NULL) back child
458        {
459                dynamic_cast<BspInterior *>(mCurrentBspNode)->ReplaceChildLink(NULL, leaf);
460        }
461        else
462        {
463                if (mViewCellsManager->GetType() == ViewCellsManager::BSP)
464                {
465                        mBspTree->mRoot = leaf;
466                }
467                else if (mViewCellsManager->GetType() == ViewCellsManager::VSP_BSP)
468                {
469                        mVspBspTree->mRoot = leaf;
470                }
471        }
472
473        //-- find associated view cell
474        int viewCellId;
475       
476        int len = attributes.getLength();
477         
478        for (int i = 0; i < len; ++ i)
479        {
480                string attrName(StrX(attributes.getName(i)).LocalForm());
481                StrX attrValue(attributes.getValue(i));
482
483                const char *ptr = attrValue.LocalForm();
484                char *endptr = NULL;
485
486                if (attrName == "viewCellId")
487                {
488                        viewCellId = strtol(ptr, &endptr, 10);
489                }
490        }
491
492       
493        if (viewCellId >= 0) // valid view cell
494        {
495                // TODO: get view cell with specified id
496                ViewCellInterior dummyVc;
497                dummyVc.SetId(viewCellId);
498
499                ViewCellContainer::iterator vit =
500                        lower_bound(mViewCells.begin(), mViewCells.end(), &dummyVc, vlt);
501                       
502                BspViewCell *viewCell = dynamic_cast<BspViewCell *>(*vit);
503
504       
505                if (viewCell->GetId() == viewCellId)
506                {
507                        leaf->SetViewCell(viewCell);
508                        viewCell->mLeaf = leaf;
509                }
510                else
511                {
512                        Debug << "error: view cell does not exist" << endl;
513                }
514        }
515        else
516        {
517                // add to invalid view space
518                if (mViewCellsManager->GetType() == ViewCellsManager::VSP_BSP)
519                {
520                        leaf->SetViewCell(mVspBspTree->GetOrCreateOutOfBoundsCell());
521                        leaf->SetTreeValid(false);
522                        mVspBspTree->PropagateUpValidity(leaf);
523                }
524        }
525}
526
527
528void ViewCellsParseHandlers::StartBspInterior(AttributeList& attributes)
529{
530        Plane3 plane;
531        int len = attributes.getLength();
532
533        for (int i = 0; i < len; ++ i)
534        {
535                string attrName(StrX(attributes.getName(i)).LocalForm());
536                StrX attrValue(attributes.getValue(i));
537                const char *ptr = attrValue.LocalForm();
538
539                if (attrName == "plane")
540                {
541                        sscanf(ptr, "%f %f %f %f",
542                                   &plane.mNormal.x, &plane.mNormal.y, &plane.mNormal.z, &plane.mD);
543                }
544        }
545
546        BspInterior* interior = new BspInterior(plane);
547       
548        if (mCurrentBspNode) // replace NULL child of parent with current node
549        {
550                BspInterior *current = dynamic_cast<BspInterior *>(mCurrentBspNode);
551
552                current->ReplaceChildLink(NULL, interior);
553                interior->SetParent(current);
554        }
555        else
556        {
557                if (mViewCellsManager->GetType() == ViewCellsManager::BSP)
558                {
559                        mBspTree->mRoot = interior;
560                }
561                else
562                {
563                        mVspBspTree->mRoot = interior;
564                }
565        }
566
567        mCurrentBspNode = interior;
568}
569
570
571void ViewCellsParseHandlers::StartViewCellLeaf(AttributeList& attributes)
572{
573        BspViewCell *viewCell = new BspViewCell();
574
575        if (mCurrentViewCell) // replace front or (if not NULL) back child
576        {
577                ViewCellInterior *interior = dynamic_cast<ViewCellInterior *>(mCurrentViewCell);
578                interior->SetupChildLink(viewCell);
579        }
580        else // root
581        {
582                mViewCellsTree->SetRoot(viewCell);
583        }
584
585        StartViewCell(viewCell, attributes);
586
587        // collect leaves
588        mViewCells.push_back(viewCell);
589}
590
591
592void ViewCellsParseHandlers::StartViewCellInterior(AttributeList& attributes)
593{
594        ViewCellInterior* interior = new ViewCellInterior();
595       
596        if (mCurrentViewCell) // replace NULL child of parent with current node
597        {
598                ViewCellInterior *current = dynamic_cast<ViewCellInterior *>(mCurrentViewCell);
599
600                current->SetupChildLink(interior);
601        }
602        else
603        {
604                mViewCellsTree->SetRoot(interior);
605        }
606
607        mCurrentViewCell = interior;
608
609        StartViewCell(interior, attributes);
610}
611
612
613
614void ViewCellsParseHandlers::CreateViewCellsManager(const char *name)
615{
616        if (strcmp(name, "bspTree") == 0)
617        {
618                Debug << "view cell type: Bsp" << endl;
619
620                mBspTree = new BspTree();
621                mBspTree->mBox = mViewSpaceBox;
622                //mCurrentBspNode = mBspTree->GetRoot();
623
624                mViewCellsManager = new BspViewCellsManager(mBspTree, mEnvironment);
625        }
626       
627        else if (strcmp(name, "vspKdTree") == 0)
628        {
629                // TODO
630                Debug << "view cell type: VspKd" << endl;
631                mVspKdTree = new VspKdTree();   
632                mViewCellsManager = new VspKdViewCellsManager(mVspKdTree, mEnvironment);
633        }
634        else // vspBspTree
635        {
636                Debug << "view cell type: VspBsp" << endl;
637
638                mVspBspTree = new VspBspTree();
639                //mCurrentBspNode = mVspBspTree->GetRoot();
640                mViewCellsManager = new VspBspViewCellsManager(mVspBspTree, mEnvironment);
641
642                mVspBspTree->mBox = mViewSpaceBox;
643        }
644
645        mViewCellsTree = mViewCellsManager->GetViewCellsTree();
646        mViewCellsManager->SetViewSpaceBox(mViewSpaceBox);
647}
648
649
650void ViewCellsParseHandlers::characters(const XMLCh* const chars,
651                                                                                const unsigned int length)
652{
653        mCharacterCount += length;
654}
655
656
657void ViewCellsParseHandlers::ignorableWhitespace(const XMLCh* const chars,
658                                                                                                 const unsigned int length)
659{
660        mSpaceCount += length;
661}
662
663
664void ViewCellsParseHandlers::resetDocument()
665{
666        mAttrCount = 0;
667        mCharacterCount = 0;
668        mElementCount = 0;
669        mSpaceCount = 0;
670}
671
672
673// ---------------------------------------------------------------------------
674//  StdInParseHandlers: Overrides of the SAX ErrorHandler interface
675// ---------------------------------------------------------------------------
676void
677ViewCellsParseHandlers::error(const SAXParseException& e)
678{
679  XERCES_STD_QUALIFIER cerr << "\nError at (file " << StrX(e.getSystemId())
680                            << ", line " << e.getLineNumber()
681                            << ", char " << e.getColumnNumber()
682                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
683}
684
685void
686ViewCellsParseHandlers::fatalError(const SAXParseException& e)
687{
688  XERCES_STD_QUALIFIER cerr << "\nFatal Error at (file " << StrX(e.getSystemId())
689                            << ", line " << e.getLineNumber()
690                            << ", char " << e.getColumnNumber()
691                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
692}
693
694void
695ViewCellsParseHandlers::warning(const SAXParseException& e)
696{
697  XERCES_STD_QUALIFIER cerr << "\nWarning at (file " << StrX(e.getSystemId())
698                            << ", line " << e.getLineNumber()
699                            << ", char " << e.getColumnNumber()
700                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
701}
702
703
704bool ViewCellsParser::ParseFile(const string filename,
705                                                                ViewCellsManager **viewCells,
706                                                                ObjectContainer *objects,
707                                                                BoundingBoxConverter *bconverter,
708                                                                Environment *env)
709{
710  // Initialize the XML4C system
711  try {
712    XMLPlatformUtils::Initialize();
713  }
714 
715  catch (const XMLException& toCatch)
716    {
717      XERCES_STD_QUALIFIER cerr << "Error during initialization! Message:\n"
718                                << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
719      return false;
720    }
721 
722  //
723  //  Create a SAX parser object. Then, according to what we were told on
724  //  the command line, set the options.
725  //
726  SAXParser* parser = new SAXParser;
727  parser->setValidationScheme(valScheme);
728  parser->setDoNamespaces(doNamespaces);
729  parser->setDoSchema(doSchema);
730  parser->setValidationSchemaFullChecking(schemaFullChecking);
731 
732
733  //
734  //  Create our SAX handler object and install it on the parser, as the
735  //  document and error handler. We are responsible for cleaning them
736  //  up, but since its just stack based here, there's nothing special
737  //  to do.
738  //
739  ViewCellsParseHandlers handler(objects, bconverter, env);
740  parser->setDocumentHandler(&handler);
741  parser->setErrorHandler(&handler);
742 
743  unsigned long duration;
744  int errorCount = 0;
745  // create a faux scope so that 'src' destructor is called before
746  // XMLPlatformUtils::Terminate
747  {
748    //
749    //  Kick off the parse and catch any exceptions. Create a standard
750    //  input input source and tell the parser to parse from that.
751    //
752    //    StdInInputSource src;
753    try
754      {
755        const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
756#if ZIPPED_VIEWCELLS
757        XMLCh *myFilePath = XMLString::transcode(filename.c_str());
758       
759        GzFileInputSource isource(myFilePath);
760        parser->parse(isource);
761
762#else
763        parser->parse(filename.c_str());
764#endif
765
766        const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
767        duration = endMillis - startMillis;
768        errorCount = parser->getErrorCount();
769      }
770    catch (const OutOfMemoryException&)
771      {
772        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
773        errorCount = 2;
774        return false;
775      }
776    catch (const XMLException& e)
777      {
778                        XERCES_STD_QUALIFIER cerr << "\nError during parsing: \n"
779                                  << StrX(e.getMessage())
780                                  << "\n" << XERCES_STD_QUALIFIER endl;
781                        errorCount = 1;
782                        return false;
783      }
784
785   
786    // Print out the stats that we collected and time taken
787    if (!errorCount) {
788                XERCES_STD_QUALIFIER cerr << filename << ": " << duration << " ms ("
789                                << handler.GetElementCount() << " elems, "
790                                << handler.GetAttrCount() << " attrs, "
791                                << handler.GetSpaceCount() << " spaces, "
792                                << handler.GetCharacterCount() << " chars)" << XERCES_STD_QUALIFIER endl;
793    }
794  }
795 
796  //
797  //  Delete the parser itself.  Must be done prior to calling Terminate, below.
798  //
799  delete parser;
800 
801  XMLPlatformUtils::Terminate();
802 
803  //-- assign new view cells manager
804  *viewCells = handler.mViewCellsManager;
805 
806  if (errorCount > 0)
807    return false;
808  else
809    return true;
810}
811
812}
Note: See TracBrowser for help on using the repository browser.