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

Revision 1194, 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 "ViewCellsManager.h"
31#include "GzFileInputSource.h"
32#include "VspOspTree.h"
33
34
35namespace GtpVisibilityPreprocessor {
36
37
38// ---------------------------------------------------------------------------
39//  Local data
40//
41//  doNamespaces
42//      Indicates whether namespace processing should be enabled or not.
43//      The default is no, but -n overrides that.
44//
45//  doSchema
46//      Indicates whether schema processing should be enabled or not.
47//      The default is no, but -s overrides that.
48//
49//  schemaFullChecking
50//      Indicates whether full schema constraint checking should be enabled or not.
51//      The default is no, but -s overrides that.
52//
53//  valScheme
54//      Indicates what validation scheme to use. It defaults to 'auto', but
55//      can be set via the -v= command.
56// ---------------------------------------------------------------------------
57static bool     doNamespaces       = false;
58static bool     doSchema           = false;
59static bool     schemaFullChecking = false;
60static SAXParser::ValSchemes    valScheme       = SAXParser::Val_Auto;
61
62
63
64
65
66// ---------------------------------------------------------------------------
67//  StdInParseHandlers: Constructors and Destructor
68// ---------------------------------------------------------------------------
69ViewCellsParseHandlers::ViewCellsParseHandlers(ObjectContainer *objects,
70                                                                                           BoundingBoxConverter *bconverter):
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{
85}
86
87
88ViewCellsParseHandlers::~ViewCellsParseHandlers()
89{
90}
91
92
93// ---------------------------------------------------------------------------
94//  StdInParseHandlers: Implementation of the SAX DocumentHandler interface
95// ---------------------------------------------------------------------------
96
97
98void ViewCellsParseHandlers::endElement(const XMLCh* const name)
99{
100  StrX lname(name);
101  string element(lname.LocalForm());
102
103  if (element == "ViewCells")
104          EndViewCells();
105
106  if (element == "BoundingBoxes")
107          EndBoundingBoxes();
108
109  // inside the view cell description
110  if (mParseViewCells)
111  {
112          if (element == "Interior")
113                  EndViewCellInterior();
114  }
115  else
116  {
117          if (element == "Interior")
118                  EndBspInterior();
119  }
120}
121
122
123void ViewCellsParseHandlers::EndBspInterior()
124{
125        // go one up in the tree
126        if (mCurrentBspNode->GetParent())
127        {       Debug << "]";
128                mCurrentBspNode = mCurrentBspNode->GetParent();
129        }
130}
131
132
133void ViewCellsParseHandlers::EndViewCellInterior()
134{
135        // go one up in the tree
136        if (mCurrentViewCell->GetParent())
137        {       Debug << "]";
138                mCurrentViewCell = mCurrentViewCell->GetParent();
139        }
140}
141
142
143inline static bool vlt(ViewCell *v1, ViewCell *v2)
144{
145        return v1->mId < v2->mId;
146}
147
148
149void ViewCellsParseHandlers::EndViewCells()
150{
151        // sort view cells to help associating view cells according to their id
152        stable_sort(mViewCells.begin(), mViewCells.end(), vlt);
153        mParseViewCells = false;
154}
155
156
157void ViewCellsParseHandlers::EndBoundingBoxes()
158{
159        // all bounding boxes gathered in this step =>
160        // associate object ids with bounding boxes
161        long startTime = GetTime();
162       
163        if (mBoundingBoxConverter)
164                mBoundingBoxConverter->IdentifyObjects(mIBoundingBoxes, *mObjects);
165
166        Debug << "\nconverted bounding boxes to objects in "
167                  << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
168}
169
170
171void ViewCellsParseHandlers::StartHierarchy(AttributeList&  attributes)
172{
173        int len = attributes.getLength();
174 
175        for (int i = 0; i < len; ++ i)
176        {
177                string attrName(StrX(attributes.getName(i)).LocalForm());
178               
179                if (attrName == "name")
180                {
181                        StrX attrValue(attributes.getValue(i));
182                       
183                        const char *ptr = attrValue.LocalForm();
184                       
185                        //-- the view cells manager is created here
186                        CreateViewCellsManager(ptr);
187                }
188        }
189}
190
191
192void ViewCellsParseHandlers::startBspElement(string element,
193                                                                                         AttributeList& attributes)
194{
195        if (element == "Interior")
196        {
197                Debug << "[";
198                StartBspInterior(attributes);
199        }
200
201        if (element == "Leaf")
202        {
203                Debug << "l";
204                StartBspLeaf(attributes);
205        }
206}
207
208
209void ViewCellsParseHandlers::startElement(const XMLCh* const name,
210                                                                                  AttributeList& attributes)
211{
212        StrX lname(name);
213        string element(lname.LocalForm());
214
215
216        if (element == "ViewCells")
217        {
218                Debug << "parsing view cells" << endl;
219                mParseViewCells = true;
220        }
221
222        // decides about the view cell hierarchy
223        if (element == "HierarchyType")
224        //if (element == "Hierarchy")
225        {
226                //Debug << "parsing spatial hierarchy" << endl;
227                //mParseViewCells = false;
228                StartHierarchy(attributes);
229        }
230       
231        // decides the used view cell hierarchy
232        if (element == "ViewSpaceBox")
233        {
234                Debug << "v";
235                StartViewSpaceBox(attributes);
236        }
237
238        // decides the used view cell hierarchy
239        if (element == "BoundingBox")
240        {
241                Debug << "b";
242                StartBoundingBox(attributes);
243        }
244
245       
246        if (!mParseViewCells)
247        {
248                //-- use different methods for the given view cell hierarchy types
249                if (mViewCellsManager)
250                {
251                        switch (mViewCellsManager->GetType())
252                        {
253                        case ViewCellsManager::BSP:
254                        case ViewCellsManager::VSP_BSP:
255                                startBspElement(element, attributes);
256                                break;
257       
258                        default:
259                                Debug << "not implemented" << endl;
260                                break;
261                        }
262                }
263        }
264        else
265        {
266                // interiors + leaves interpreted view cells else
267                if (element == "Interior")
268                {
269                        Debug << "[";
270                        StartViewCellInterior(attributes);
271                }
272
273                if (element == "Leaf")
274                {
275                        Debug << "l";
276                        StartViewCellLeaf(attributes);
277                }
278        }
279
280        ++ mElementCount;
281        mAttrCount += attributes.getLength();
282}
283
284
285inline bool ilt(Intersectable *obj1, Intersectable *obj2)
286{
287        return obj1->mId < obj2->mId;
288}
289
290
291void ViewCellsParseHandlers::StartViewCell(ViewCell *viewCell,
292                                                                                   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);
625        }
626        else if (strcmp(name, "vspBspTree") == 0) //
627        {
628                Debug << "view cell type: VspBsp" << endl;
629
630                mVspBspTree = new VspBspTree();
631                //mCurrentBspNode = mVspBspTree->GetRoot();
632                mViewCellsManager = new VspBspViewCellsManager(mVspBspTree);
633
634                mVspBspTree->mBox = mViewSpaceBox;
635        }
636        else if (strcmp(name, "vspOspTree") == 0)
637        {
638                Debug << "view cell type: VspOsp" << endl;
639
640                mVspTree = new VspTree();
641                mOspTree = new OspTree();
642
643                // hack
644                mViewCellsManager = new VspOspViewCellsManager(mVspTree, mOspTree);
645
646                mVspTree->mBoundingBox = mViewSpaceBox;
647        }
648
649
650        mViewCellsTree = mViewCellsManager->GetViewCellsTree();
651        mViewCellsManager->SetViewSpaceBox(mViewSpaceBox);
652}
653
654
655void ViewCellsParseHandlers::characters(const XMLCh* const chars,
656                                                                                const unsigned int length)
657{
658        mCharacterCount += length;
659}
660
661
662void ViewCellsParseHandlers::ignorableWhitespace(const XMLCh* const chars,
663                                                                                                 const unsigned int length)
664{
665        mSpaceCount += length;
666}
667
668
669void ViewCellsParseHandlers::resetDocument()
670{
671        mAttrCount = 0;
672        mCharacterCount = 0;
673        mElementCount = 0;
674        mSpaceCount = 0;
675}
676
677
678// ---------------------------------------------------------------------------
679//  StdInParseHandlers: Overrides of the SAX ErrorHandler interface
680// ---------------------------------------------------------------------------
681void
682ViewCellsParseHandlers::error(const SAXParseException& e)
683{
684  XERCES_STD_QUALIFIER cerr << "\nError at (file " << StrX(e.getSystemId())
685                            << ", line " << e.getLineNumber()
686                            << ", char " << e.getColumnNumber()
687                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
688}
689
690void
691ViewCellsParseHandlers::fatalError(const SAXParseException& e)
692{
693  XERCES_STD_QUALIFIER cerr << "\nFatal Error at (file " << StrX(e.getSystemId())
694                            << ", line " << e.getLineNumber()
695                            << ", char " << e.getColumnNumber()
696                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
697}
698
699void
700ViewCellsParseHandlers::warning(const SAXParseException& e)
701{
702  XERCES_STD_QUALIFIER cerr << "\nWarning at (file " << StrX(e.getSystemId())
703                            << ", line " << e.getLineNumber()
704                            << ", char " << e.getColumnNumber()
705                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
706}
707
708
709bool ViewCellsParser::ParseFile(const string filename,
710                                                                ViewCellsManager **viewCells,
711                                                                ObjectContainer *objects,
712                                                                BoundingBoxConverter *bconverter)
713{
714  // Initialize the XML4C system
715  try {
716    XMLPlatformUtils::Initialize();
717  }
718 
719  catch (const XMLException& toCatch)
720    {
721      XERCES_STD_QUALIFIER cerr << "Error during initialization! Message:\n"
722                                << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
723      return false;
724    }
725 
726  //
727  //  Create a SAX parser object. Then, according to what we were told on
728  //  the command line, set the options.
729  //
730  SAXParser* parser = new SAXParser;
731  parser->setValidationScheme(valScheme);
732  parser->setDoNamespaces(doNamespaces);
733  parser->setDoSchema(doSchema);
734  parser->setValidationSchemaFullChecking(schemaFullChecking);
735 
736
737  //
738  //  Create our SAX handler object and install it on the parser, as the
739  //  document and error handler. We are responsible for cleaning them
740  //  up, but since its just stack based here, there's nothing special
741  //  to do.
742  //
743  ViewCellsParseHandlers handler(objects, bconverter);
744  parser->setDocumentHandler(&handler);
745  parser->setErrorHandler(&handler);
746 
747  unsigned long duration;
748  int errorCount = 0;
749  // create a faux scope so that 'src' destructor is called before
750  // XMLPlatformUtils::Terminate
751  {
752    //
753    //  Kick off the parse and catch any exceptions. Create a standard
754    //  input input source and tell the parser to parse from that.
755    //
756    //    StdInInputSource src;
757    try
758      {
759        const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
760#if ZIPPED_VIEWCELLS
761        XMLCh *myFilePath = XMLString::transcode(filename.c_str());
762       
763        GzFileInputSource isource(myFilePath);
764        parser->parse(isource);
765
766#else
767        parser->parse(filename.c_str());
768#endif
769
770        const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
771        duration = endMillis - startMillis;
772        errorCount = parser->getErrorCount();
773      }
774    catch (const OutOfMemoryException&)
775      {
776        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
777        errorCount = 2;
778        return false;
779      }
780    catch (const XMLException& e)
781      {
782                        XERCES_STD_QUALIFIER cerr << "\nError during parsing: \n"
783                                  << StrX(e.getMessage())
784                                  << "\n" << XERCES_STD_QUALIFIER endl;
785                        errorCount = 1;
786                        return false;
787      }
788
789   
790    // Print out the stats that we collected and time taken
791    if (!errorCount) {
792                XERCES_STD_QUALIFIER cerr << filename << ": " << duration << " ms ("
793                                << handler.GetElementCount() << " elems, "
794                                << handler.GetAttrCount() << " attrs, "
795                                << handler.GetSpaceCount() << " spaces, "
796                                << handler.GetCharacterCount() << " chars)" << XERCES_STD_QUALIFIER endl;
797    }
798  }
799 
800  //
801  //  Delete the parser itself.  Must be done prior to calling Terminate, below.
802  //
803  delete parser;
804 
805  XMLPlatformUtils::Terminate();
806 
807  //-- assign new view cells manager
808  *viewCells = handler.mViewCellsManager;
809 
810  if (errorCount > 0)
811    return false;
812  else
813    return true;
814}
815
816}
Note: See TracBrowser for help on using the repository browser.