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

Revision 944, 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        {       cout << "]";
129                mCurrentBspNode = mCurrentBspNode->GetParent();
130        }
131}
132
133
134void ViewCellsParseHandlers::EndViewCellInterior()
135{
136        // go one up in the tree
137        if (mCurrentViewCell->GetParent())
138        {       cout << "]";
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        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                cout << "[";
198                StartBspInterior(attributes);
199        }
200
201        if (element == "Leaf")
202        {
203                cout << "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        // decides the used view cell hierarchy
216        if (element == "ViewCells")
217        {
218                cout << "parsing view cells" << endl;
219                mParseViewCells = true;
220        }
221
222        if (element == "Hierarchy")
223        {
224                cout << "parsing spatial hierarchy" << endl;
225                mParseViewCells = false;
226                StartHierarchy(attributes);
227        }
228       
229        // decides the used view cell hierarchy
230        if (element == "ViewSpaceBox")
231        {
232                cout << "v";
233                StartViewSpaceBox(attributes);
234        }
235
236        // decides the used view cell hierarchy
237        if (element == "BoundingBox")
238        {
239                cout << "b";
240                StartBoundingBox(attributes);
241        }
242
243        // use different methods for the given view cell hierarchy types
244        if (!mParseViewCells)
245        {
246                if (mViewCellsManager)
247                {
248                        switch (mViewCellsManager->GetType())
249                        {
250                        case ViewCellsManager::BSP:
251                        case ViewCellsManager::VSP_BSP:
252                                startBspElement(element, attributes);
253                                break;
254       
255                        default:
256                                Debug << "not implemented" << endl;
257                                break;
258                        }
259                }
260        }
261        else
262        {
263                if (element == "Interior")
264                {
265                        cout << "[";
266                        StartViewCellInterior(attributes);
267                }
268
269                if (element == "Leaf")
270                {
271                        cout << "l";
272                        StartViewCellLeaf(attributes);
273                }
274        }
275
276        ++ mElementCount;
277        mAttrCount += attributes.getLength();
278}
279
280
281inline bool ilt(Intersectable *obj1, Intersectable *obj2)
282{
283        return obj1->mId < obj2->mId;
284}
285
286
287void ViewCellsParseHandlers::StartViewCell(ViewCell *viewCell, AttributeList&  attributes)
288{
289        int len = attributes.getLength();
290        vector<int> objIndices;
291
292        for (int i = 0; i < len; ++ i)
293        {
294                string attrName(StrX(attributes.getName(i)).LocalForm());
295               
296                if (attrName == "pvs")
297                {
298                        StrX attrValue(attributes.getValue(i));
299                       
300                        // handle coordIndex
301                        objIndices.clear();
302                        const char *ptr = attrValue.LocalForm();
303                        char *endptr;
304                       
305                        while (1)
306                        {
307                                int index = strtol(ptr, &endptr, 10);
308
309                                if (ptr == endptr)
310                                        break;
311
312                                objIndices.push_back(index);
313
314                                ptr = endptr;
315                        }
316
317                        //TODO: find objects and add them to pvs
318                        // TODO: get view cell with specified id
319                        MeshInstance dummyInst(NULL);
320
321                        vector<int>::const_iterator it, it_end = objIndices.end();
322                        for (it = objIndices.begin(); it != it_end; ++ it)
323                        {
324                                const int objId = *it; 
325                                dummyInst.SetId(objId);
326
327                                ObjectContainer::iterator oit =
328                                  lower_bound(mObjects->begin(), mObjects->end(), (Intersectable *)&dummyInst, ilt);
329                               
330                                                       
331                                if ((oit != mObjects->end()) && ((*oit)->GetId() == objId))
332                                {
333                                        // $$JB we should store a float a per object which corresponds
334                                        // to sumof pdfs, i.e. its relative visibility
335                                        // temporarily set to 1.0f
336                                        viewCell->GetPvs().AddSample(*oit, 1.0f);                               
337                                }
338                                else
339                                {
340                                        Debug << "error: object with id " << objId << " does not exist" << endl;
341                                }
342                        }
343                }
344                else if (attrName == "id")
345                {
346                        StrX attrValue(attributes.getValue(i));
347                       
348                        const char *ptr = attrValue.LocalForm();
349                        char *endptr = NULL;
350                        const int id = strtol(ptr, &endptr, 10);
351
352                        viewCell->SetId(id);
353                }
354                /*else if (attrName == "active")
355                {
356                        StrX attrValue(attributes.getValue(i));
357                       
358                        const char *ptr = attrValue.LocalForm();
359                        char *endptr = NULL;
360                        const bool isActive = (bool)strtol(ptr, &endptr, 10);
361
362                        if (isActive)
363                                viewCell->SetActive();
364                }*/
365                else if (attrName == "mergecost")
366                {
367                        StrX attrValue(attributes.getValue(i));
368                       
369                        const char *ptr = attrValue.LocalForm();
370                        char *endptr = NULL;
371                        const float cost = (float)strtod(ptr, &endptr);
372
373                        viewCell->SetMergeCost(cost);
374                }
375        }
376}
377
378
379void ViewCellsParseHandlers::StartViewSpaceBox(AttributeList& attributes)
380{
381        int len = attributes.getLength();
382
383        Vector3 bmin, bmax;
384
385        for (int i = 0; i < len; ++ i)
386        {
387                string attrName(StrX(attributes.getName(i)).LocalForm());
388                StrX attrValue(attributes.getValue(i));
389                const char *ptr = attrValue.LocalForm();
390
391                if (attrName == "min")
392                {
393                        sscanf(ptr, "%f %f %f",
394                                   &bmin.x, &bmin.y, &bmin.z);
395                }
396                else if (attrName == "max")
397                {
398                        sscanf(ptr, "%f %f %f",
399                                   &bmax.x, &bmax.y, &bmax.z);
400                }
401        }
402
403        mViewSpaceBox = AxisAlignedBox3(bmin, bmax);
404
405        Debug << "\nview space box: " << mViewSpaceBox << endl;
406}
407
408
409void ViewCellsParseHandlers::StartBoundingBox(AttributeList& attributes)
410{
411        int len = attributes.getLength();
412
413        Vector3 bmin, bmax;
414        int id;
415
416        for (int i = 0; i < len; ++ i)
417        {
418                string attrName(StrX(attributes.getName(i)).LocalForm());
419                StrX attrValue(attributes.getValue(i));
420                const char *ptr = attrValue.LocalForm();
421
422
423                if (attrName == "id")
424                {
425                        sscanf(ptr, "%d", &id);
426                }
427
428                if (attrName == "min")
429                {
430                        sscanf(ptr, "%f %f %f",
431                                   &bmin.x, &bmin.y, &bmin.z);
432                }
433                else if (attrName == "max")
434                {
435                        sscanf(ptr, "%f %f %f",
436                                   &bmax.x, &bmax.y, &bmax.z);
437                }
438        }
439
440        AxisAlignedBox3 box(bmin, bmax);
441        mIBoundingBoxes.push_back(IndexedBoundingBox(id, box));
442
443        //Debug << "bbox: " << box << endl;
444}
445
446
447void ViewCellsParseHandlers::StartBspLeaf(AttributeList& attributes)
448{
449        BspLeaf * leaf =
450                new BspLeaf(dynamic_cast<BspInterior *>(mCurrentBspNode), NULL);
451
452        if (mCurrentBspNode) // replace front or (if not NULL) back child
453        {
454                dynamic_cast<BspInterior *>(mCurrentBspNode)->ReplaceChildLink(NULL, leaf);
455        }
456        else
457        {
458                if (mViewCellsManager->GetType() == ViewCellsManager::BSP)
459                {
460                        mBspTree->mRoot = leaf;
461                }
462                else if (mViewCellsManager->GetType() == ViewCellsManager::VSP_BSP)
463                {
464                        mVspBspTree->mRoot = leaf;
465                }
466        }
467
468        //-- find associated view cell
469        int viewCellId;
470       
471        int len = attributes.getLength();
472         
473        for (int i = 0; i < len; ++ i)
474        {
475                string attrName(StrX(attributes.getName(i)).LocalForm());
476                StrX attrValue(attributes.getValue(i));
477
478                const char *ptr = attrValue.LocalForm();
479                char *endptr = NULL;
480
481                if (attrName == "viewCellId")
482                {
483                        viewCellId = strtol(ptr, &endptr, 10);
484                }
485        }
486
487       
488        if (viewCellId >= 0) // valid view cell
489        {
490                // TODO: get view cell with specified id
491                ViewCellInterior dummyVc;
492                dummyVc.SetId(viewCellId);
493
494                ViewCellContainer::iterator vit =
495                        lower_bound(mViewCells.begin(), mViewCells.end(), &dummyVc, vlt);
496                       
497                BspViewCell *viewCell = dynamic_cast<BspViewCell *>(*vit);
498
499       
500                if (viewCell->GetId() == viewCellId)
501                {
502                        leaf->SetViewCell(viewCell);
503                        viewCell->mLeaf = leaf;
504                }
505                else
506                {
507                        Debug << "error: view cell does not exist" << endl;
508                }
509        }
510        else
511        {
512                // add to invalid view space
513                if (mViewCellsManager->GetType() == ViewCellsManager::VSP_BSP)
514                {
515                        leaf->SetViewCell(mVspBspTree->GetOrCreateOutOfBoundsCell());
516                        leaf->SetTreeValid(false);
517                        mVspBspTree->PropagateUpValidity(leaf);
518                }
519        }
520}
521
522
523void ViewCellsParseHandlers::StartBspInterior(AttributeList& attributes)
524{
525        Plane3 plane;
526        int len = attributes.getLength();
527
528        for (int i = 0; i < len; ++ i)
529        {
530                string attrName(StrX(attributes.getName(i)).LocalForm());
531                StrX attrValue(attributes.getValue(i));
532                const char *ptr = attrValue.LocalForm();
533
534                if (attrName == "plane")
535                {
536                        sscanf(ptr, "%f %f %f %f",
537                                   &plane.mNormal.x, &plane.mNormal.y, &plane.mNormal.z, &plane.mD);
538                }
539        }
540
541        BspInterior* interior = new BspInterior(plane);
542       
543        if (mCurrentBspNode) // replace NULL child of parent with current node
544        {
545                BspInterior *current = dynamic_cast<BspInterior *>(mCurrentBspNode);
546
547                current->ReplaceChildLink(NULL, interior);
548                interior->SetParent(current);
549        }
550        else
551        {
552                if (mViewCellsManager->GetType() == ViewCellsManager::BSP)
553                {
554                        mBspTree->mRoot = interior;
555                }
556                else
557                {
558                        mVspBspTree->mRoot = interior;
559                }
560        }
561
562        mCurrentBspNode = interior;
563}
564
565
566void ViewCellsParseHandlers::StartViewCellLeaf(AttributeList& attributes)
567{
568        BspViewCell *viewCell = new BspViewCell();
569
570        if (mCurrentViewCell) // replace front or (if not NULL) back child
571        {
572                ViewCellInterior *interior = dynamic_cast<ViewCellInterior *>(mCurrentViewCell);
573                interior->SetupChildLink(viewCell);
574        }
575        else // root
576        {
577                mViewCellsTree->SetRoot(viewCell);
578        }
579
580        StartViewCell(viewCell, attributes);
581
582        // collect leaves
583        mViewCells.push_back(viewCell);
584}
585
586
587void ViewCellsParseHandlers::StartViewCellInterior(AttributeList& attributes)
588{
589        ViewCellInterior* interior = new ViewCellInterior();
590       
591        if (mCurrentViewCell) // replace NULL child of parent with current node
592        {
593                ViewCellInterior *current = dynamic_cast<ViewCellInterior *>(mCurrentViewCell);
594
595                current->SetupChildLink(interior);
596        }
597        else
598        {
599                mViewCellsTree->SetRoot(interior);
600        }
601
602        mCurrentViewCell = interior;
603
604        StartViewCell(interior, attributes);
605}
606
607
608
609void ViewCellsParseHandlers::CreateViewCellsManager(const char *name)
610{
611        if (strcmp(name, "bspTree") == 0)
612        {
613                Debug << "view cell type: Bsp" << endl;
614
615                mBspTree = new BspTree();
616                mBspTree->mBox = mViewSpaceBox;
617                //mCurrentBspNode = mBspTree->GetRoot();
618
619                mViewCellsManager = new BspViewCellsManager(mBspTree, mEnvironment);
620        }
621        else if (strcmp(name, "vspBspTree") == 0)
622        {
623                Debug << "view cell type: VspBsp" << endl;
624
625                mVspBspTree = new VspBspTree();
626                //mCurrentBspNode = mVspBspTree->GetRoot();
627                mViewCellsManager = new VspBspViewCellsManager(mVspBspTree, mEnvironment);
628
629                mVspBspTree->mBox = mViewSpaceBox;
630        }
631        else if (strcmp(name, "vspKdTree") == 0)
632        {
633                // TODO
634                Debug << "view cell type: VspKd" << endl;
635                mVspKdTree = new VspKdTree();   
636                mViewCellsManager = new VspKdViewCellsManager(mVspKdTree, mEnvironment);
637        }
638        else
639        {
640                cerr << "Wrong view cells type: " << name << endl;
641                exit(1);
642        }
643
644        mViewCellsTree = mViewCellsManager->GetViewCellsTree();
645        mViewCellsManager->SetViewSpaceBox(mViewSpaceBox);
646}
647
648
649void ViewCellsParseHandlers::characters(const XMLCh* const chars,
650                                                                                const unsigned int length)
651{
652        mCharacterCount += length;
653}
654
655
656void ViewCellsParseHandlers::ignorableWhitespace(const XMLCh* const chars,
657                                                                                                 const unsigned int length)
658{
659        mSpaceCount += length;
660}
661
662
663void ViewCellsParseHandlers::resetDocument()
664{
665        mAttrCount = 0;
666        mCharacterCount = 0;
667        mElementCount = 0;
668        mSpaceCount = 0;
669}
670
671
672// ---------------------------------------------------------------------------
673//  StdInParseHandlers: Overrides of the SAX ErrorHandler interface
674// ---------------------------------------------------------------------------
675void
676ViewCellsParseHandlers::error(const SAXParseException& e)
677{
678  XERCES_STD_QUALIFIER cerr << "\nError at (file " << StrX(e.getSystemId())
679                            << ", line " << e.getLineNumber()
680                            << ", char " << e.getColumnNumber()
681                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
682}
683
684void
685ViewCellsParseHandlers::fatalError(const SAXParseException& e)
686{
687  XERCES_STD_QUALIFIER cerr << "\nFatal Error at (file " << StrX(e.getSystemId())
688                            << ", line " << e.getLineNumber()
689                            << ", char " << e.getColumnNumber()
690                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
691}
692
693void
694ViewCellsParseHandlers::warning(const SAXParseException& e)
695{
696  XERCES_STD_QUALIFIER cerr << "\nWarning at (file " << StrX(e.getSystemId())
697                            << ", line " << e.getLineNumber()
698                            << ", char " << e.getColumnNumber()
699                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
700}
701
702
703bool ViewCellsParser::ParseFile(const string filename,
704                                                                ViewCellsManager **viewCells,
705                                                                ObjectContainer *objects,
706                                                                BoundingBoxConverter *bconverter,
707                                                                Environment *env)
708{
709  // Initialize the XML4C system
710  try {
711    XMLPlatformUtils::Initialize();
712  }
713 
714  catch (const XMLException& toCatch)
715    {
716      XERCES_STD_QUALIFIER cerr << "Error during initialization! Message:\n"
717                                << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
718      return false;
719    }
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        parser->parse(filename.c_str());
757        const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
758        duration = endMillis - startMillis;
759        errorCount = parser->getErrorCount();
760      }
761    catch (const OutOfMemoryException&)
762      {
763        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
764        errorCount = 2;
765        return false;
766      }
767    catch (const XMLException& e)
768      {
769                        XERCES_STD_QUALIFIER cerr << "\nError during parsing: \n"
770                                  << StrX(e.getMessage())
771                                  << "\n" << XERCES_STD_QUALIFIER endl;
772                        errorCount = 1;
773                        return false;
774      }
775
776   
777    // Print out the stats that we collected and time taken
778    if (!errorCount) {
779                XERCES_STD_QUALIFIER cerr << filename << ": " << duration << " ms ("
780                                << handler.GetElementCount() << " elems, "
781                                << handler.GetAttrCount() << " attrs, "
782                                << handler.GetSpaceCount() << " spaces, "
783                                << handler.GetCharacterCount() << " chars)" << XERCES_STD_QUALIFIER endl;
784    }
785  }
786 
787  //
788  //  Delete the parser itself.  Must be done prior to calling Terminate, below.
789  //
790  delete parser;
791 
792  XMLPlatformUtils::Terminate();
793 
794  //-- assign new view cells manager
795  *viewCells = handler.mViewCellsManager;
796 
797  if (errorCount > 0)
798    return false;
799  else
800    return true;
801}
802
803}
Note: See TracBrowser for help on using the repository browser.