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

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