source: trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellsParser.cpp @ 575

Revision 575, 14.2 KB checked in by mattausch, 18 years ago (diff)

changed view cell parser. warning, not working yet!!

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
32// ---------------------------------------------------------------------------
33//  Local data
34//
35//  doNamespaces
36//      Indicates whether namespace processing should be enabled or not.
37//      The default is no, but -n overrides that.
38//
39//  doSchema
40//      Indicates whether schema processing should be enabled or not.
41//      The default is no, but -s overrides that.
42//
43//  schemaFullChecking
44//      Indicates whether full schema constraint checking should be enabled or not.
45//      The default is no, but -s overrides that.
46//
47//  valScheme
48//      Indicates what validation scheme to use. It defaults to 'auto', but
49//      can be set via the -v= command.
50// ---------------------------------------------------------------------------
51static bool     doNamespaces       = false;
52static bool     doSchema           = false;
53static bool     schemaFullChecking = false;
54static SAXParser::ValSchemes    valScheme       = SAXParser::Val_Auto;
55
56
57
58
59
60// ---------------------------------------------------------------------------
61//  StdInParseHandlers: Constructors and Destructor
62// ---------------------------------------------------------------------------
63ViewCellsParseHandlers::ViewCellsParseHandlers(ViewCellsManager **viewCells,
64                                                                                           ObjectContainer *objects):
65  mElementCount(0)
66  , mAttrCount(0)
67  , mCharacterCount(0)
68  , mSpaceCount(0)
69{
70        mObjects = objects;
71        viewCells = &mViewCellsManager;
72        //mPreprocessor = preprocessor;
73}
74
75
76ViewCellsParseHandlers::~ViewCellsParseHandlers()
77{
78}
79
80
81// ---------------------------------------------------------------------------
82//  StdInParseHandlers: Implementation of the SAX DocumentHandler interface
83// ---------------------------------------------------------------------------
84
85
86void ViewCellsParseHandlers::endElement(const XMLCh* const name)
87{
88  StrX lname(name);
89  string element(lname.LocalForm());
90  if (element == "Interior")
91          EndBspInterior();
92  if (element == "ViewCells")
93          EndViewCells();
94}
95
96
97void ViewCellsParseHandlers::EndBspInterior()
98{
99        // go one up in the tree
100        if (mCurrentNode->GetParent())
101        {       cout << "]";
102                mCurrentNode = mCurrentNode->GetParent();
103        }
104}
105
106
107inline bool vlt(ViewCell *v1, ViewCell *v2)
108{
109        return v1->mId < v2->mId;
110}
111
112
113void ViewCellsParseHandlers::EndViewCells()
114{
115        // sort view cells to help associating view cells according to their id
116        stable_sort(mViewCells.begin(), mViewCells.end(), vlt);
117}
118
119
120
121void ViewCellsParseHandlers::StartHierarchy(AttributeList&  attributes)
122{
123        int len = attributes.getLength();
124 
125        for (int i = 0; i < len; ++ i)
126        {
127                string attrName(StrX(attributes.getName(i)).LocalForm());
128               
129                if (attrName == "name")
130                {
131                        StrX attrValue(attributes.getValue(i));
132                       
133                        const char *ptr = attrValue.LocalForm();
134                       
135                        CreateViewCellsManager(ptr);
136                }
137        }
138}
139
140
141void ViewCellsParseHandlers::startBspElement(string element,
142                                                                                         AttributeList& attributes)
143{
144        if (element == "ViewCell")
145        {
146                cout << "v";
147                StartViewCell(attributes);
148        }
149
150        if (element == "Interior")
151        {
152                cout << "[";
153                StartBspInterior(attributes);
154        }
155
156        if (element == "Leaf")
157        {
158                StartBspLeaf(attributes);
159        }
160}
161
162
163void ViewCellsParseHandlers::startElement(const XMLCh* const name,
164                                                                                  AttributeList& attributes)
165{
166        StrX lname(name);
167        string element(lname.LocalForm());
168       
169        if (element == "Hierarchy")
170        {
171                cout << "h";
172                StartHierarchy(attributes);
173        }
174
175        switch (mViewCellsManager->GetType())
176        {
177        case ViewCellsManager::BSP:
178        case ViewCellsManager::VSP_BSP:
179                startBspElement(element, attributes);
180                break;
181       
182        default:
183                Debug << "not implemented" << endl;
184                break;
185
186        }
187       
188        ++ mElementCount;
189        mAttrCount += attributes.getLength();
190}
191
192
193inline bool ilt(Intersectable *obj1, Intersectable *obj2)
194{
195        return obj1->mId < obj2->mId;
196}
197
198
199void ViewCellsParseHandlers::StartViewCell(AttributeList&  attributes)
200{
201        int len = attributes.getLength();
202        vector<int> objIndices;
203 
204        ViewCell *viewCell = mViewCellsManager->GenerateViewCell();
205        mViewCells.push_back(viewCell);
206
207        for (int i = 0; i < len; ++ i)
208        {
209                string attrName(StrX(attributes.getName(i)).LocalForm());
210               
211                if (attrName == "pvs")
212                {
213                        StrX attrValue(attributes.getValue(i));
214                       
215                        // handle coordIndex
216                        objIndices.clear();
217                        const char *ptr = attrValue.LocalForm();
218                        char *endptr;
219                       
220                        while (1)
221                        {
222                                int index = strtol(ptr, &endptr, 10);
223
224                                if (ptr == endptr)
225                                        break;
226
227                                objIndices.push_back(index);
228
229                                ptr = endptr;
230                        }
231
232                        //TODO: find objects and add them to pvs
233                        // TODO: get view cell with specified id
234                        MeshInstance dummyInst(NULL);
235
236                        vector<int>::const_iterator it, it_end = objIndices.end();
237                        for (it = objIndices.begin(); it != it_end; ++ it)
238                        {
239                                const int objId = *it; 
240                                dummyInst.SetId(objId);
241
242                                ObjectContainer::iterator oit =
243                                  lower_bound(mObjects->begin(), mObjects->end(), &dummyInst, ilt);
244                               
245                                Intersectable *obj = *oit;
246                               
247                                if (obj->GetId() == objId)
248                                {
249                                  // $$JB we should store a float a per object which corresponds
250                                  // to sumof pdfs, i.e. its relative visibility
251                                  // temporarily set to 1.0f
252                                        viewCell->GetPvs().AddSample(obj, 1.0f);
253                                }
254                                else
255                                {
256                                        Debug << "error: object does not exist" << endl;
257                                }
258                        }
259                }
260                else if (attrName == "id")
261                {
262                        StrX attrValue(attributes.getValue(i));
263                       
264                        const char *ptr = attrValue.LocalForm();
265                        char *endptr = NULL;
266                        const int id = strtol(ptr, &endptr, 10);
267
268                        viewCell->SetId(id);
269                }
270        }
271}
272
273
274void ViewCellsParseHandlers::StartBspLeaf(AttributeList& attributes)
275{
276        BspLeaf * leaf =
277                new BspLeaf(dynamic_cast<BspInterior *>(mCurrentNode), NULL);
278
279        if (mCurrentNode) // replace front or (if not NULL) back child
280        {
281                dynamic_cast<BspInterior *>(mCurrentNode)->ReplaceChildLink(NULL, leaf);
282        }
283        else
284        {
285                if (mViewCellsManager->GetType() == ViewCellsManager::BSP)
286                        mBspTree->mRoot = leaf;
287                else
288                        mVspBspTree->mRoot = leaf;
289        }
290
291        //-- find associated view cell
292        int viewCellId;
293       
294        int len = attributes.getLength();
295         
296        for (int i = 0; i < len; ++ i)
297        {
298                string attrName(StrX(attributes.getName(i)).LocalForm());
299                StrX attrValue(attributes.getValue(i));
300
301                const char *ptr = attrValue.LocalForm();
302                char *endptr = NULL;
303
304                if (attrName == "viewCellId")
305                {
306                        viewCellId = strtol(ptr, &endptr, 10);
307                }
308        }
309
310        if (viewCellId >= 0) // valid view cell
311        {
312                // TODO: get view cell with specified id
313                ViewCell dummyVc;
314                dummyVc.SetId(viewCellId);
315
316                ViewCellContainer::iterator vit =
317                        lower_bound(mViewCells.begin(), mViewCells.end(), &dummyVc, vlt);
318                       
319                BspViewCell *viewCell = dynamic_cast<BspViewCell *>(*vit);
320                if (viewCell->GetId() == viewCellId)
321                {
322                        leaf->SetViewCell(viewCell);
323                }
324                else
325                {
326                        Debug << "error: view cell does not exist" << endl;
327                }
328        }
329        else
330        {
331                if (mViewCellsManager->GetType() == ViewCellsManager::VSP_BSP)
332                {
333                        leaf->SetViewCell(mVspBspTree->GetOrCreateOutOfBoundsCell());
334                        leaf->SetTreeValid(false);
335                        mVspBspTree->PropagateUpValidity(leaf);
336                }
337        }
338}
339
340
341void ViewCellsParseHandlers::StartBspInterior(AttributeList& attributes)
342{
343        Plane3 plane;
344        int len = attributes.getLength();
345
346        for (int i = 0; i < len; ++ i)
347        {
348                string attrName(StrX(attributes.getName(i)).LocalForm());
349                StrX attrValue(attributes.getValue(i));
350                const char *ptr = attrValue.LocalForm();
351
352                if (attrName == "plane")
353                {
354                        sscanf(ptr, "%f %f %f %f",
355                                   &plane.mNormal.x, &plane.mNormal.y, &plane.mNormal.z, &plane.mD);
356                }
357        }
358
359        BspInterior* interior = new BspInterior(plane);
360       
361        if (mCurrentNode) // replace NULL child of parent with current node
362        {
363                BspInterior *current = dynamic_cast<BspInterior *>(mCurrentNode);
364
365                current->ReplaceChildLink(NULL, interior);
366                interior->SetParent(current);
367        }
368        else
369        {
370                if (mViewCellsManager->GetType() == ViewCellsManager::BSP)
371                        mBspTree->mRoot = interior;
372                else
373                        mVspBspTree->mRoot = interior;
374        }
375
376        mCurrentNode = interior;
377}
378
379
380
381void ViewCellsParseHandlers::CreateViewCellsManager(const char *name)
382{
383       
384        if (strcmp(name, "bspTree") == 0)
385        {
386                mBspTree = new BspTree();
387
388                Debug << "view cell type: Bsp" << endl;
389
390                mCurrentNode = mBspTree->GetRoot();
391
392                mViewCellsManager = new BspViewCellsManager(mBspTree);
393        }
394        else if (strcmp(name, "vspBspTree") == 0)
395        {
396                mVspBspTree = new VspBspTree();
397
398                Debug << "view cell type: VspBsp" << endl;
399                mCurrentNode = mVspBspTree->GetRoot();
400
401                mViewCellsManager = new VspBspViewCellsManager(mVspBspTree);
402        }
403        /*else if (strcmp(name, "vspKdTree") == 0)
404        {
405                mVspKdTree = new VspKdTree();           
406       
407                mViewCellsManager = VspKdViewCellsManager(mVspKdTree);
408        }*/
409        else
410        {
411                cerr<<"Wrong view cells type" << name << endl;
412                exit(1);
413        }
414}
415
416
417void ViewCellsParseHandlers::characters(const XMLCh* const chars,
418                                                                                const unsigned int length)
419{
420        mCharacterCount += length;
421}
422
423
424void ViewCellsParseHandlers::ignorableWhitespace(const XMLCh* const chars,
425                                                                                                 const unsigned int length)
426{
427        mSpaceCount += length;
428}
429
430
431void ViewCellsParseHandlers::resetDocument()
432{
433        mAttrCount = 0;
434        mCharacterCount = 0;
435        mElementCount = 0;
436        mSpaceCount = 0;
437}
438
439
440// ---------------------------------------------------------------------------
441//  StdInParseHandlers: Overrides of the SAX ErrorHandler interface
442// ---------------------------------------------------------------------------
443void
444ViewCellsParseHandlers::error(const SAXParseException& e)
445{
446  XERCES_STD_QUALIFIER cerr << "\nError at (file " << StrX(e.getSystemId())
447                            << ", line " << e.getLineNumber()
448                            << ", char " << e.getColumnNumber()
449                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
450}
451
452void
453ViewCellsParseHandlers::fatalError(const SAXParseException& e)
454{
455  XERCES_STD_QUALIFIER cerr << "\nFatal Error at (file " << StrX(e.getSystemId())
456                            << ", line " << e.getLineNumber()
457                            << ", char " << e.getColumnNumber()
458                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
459}
460
461void
462ViewCellsParseHandlers::warning(const SAXParseException& e)
463{
464  XERCES_STD_QUALIFIER cerr << "\nWarning at (file " << StrX(e.getSystemId())
465                            << ", line " << e.getLineNumber()
466                            << ", char " << e.getColumnNumber()
467                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
468}
469
470
471bool ViewCellsParser::ParseFile(const string filename,
472                                                                ViewCellsManager **viewCells,
473                                                                ObjectContainer *objects)
474{
475  // Initialize the XML4C system
476  try {
477    XMLPlatformUtils::Initialize();
478  }
479 
480  catch (const XMLException& toCatch)
481    {
482      XERCES_STD_QUALIFIER cerr << "Error during initialization! Message:\n"
483                                << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
484      return false;
485    }
486 
487 
488  //
489  //  Create a SAX parser object. Then, according to what we were told on
490  //  the command line, set the options.
491  //
492  SAXParser* parser = new SAXParser;
493  parser->setValidationScheme(valScheme);
494  parser->setDoNamespaces(doNamespaces);
495  parser->setDoSchema(doSchema);
496  parser->setValidationSchemaFullChecking(schemaFullChecking);
497 
498
499  //
500  //  Create our SAX handler object and install it on the parser, as the
501  //  document and error handler. We are responsible for cleaning them
502  //  up, but since its just stack based here, there's nothing special
503  //  to do.
504  //
505  ViewCellsParseHandlers handler(viewCells, objects);
506  parser->setDocumentHandler(&handler);
507  parser->setErrorHandler(&handler);
508 
509  unsigned long duration;
510  int errorCount = 0;
511  // create a faux scope so that 'src' destructor is called before
512  // XMLPlatformUtils::Terminate
513  {
514    //
515    //  Kick off the parse and catch any exceptions. Create a standard
516    //  input input source and tell the parser to parse from that.
517    //
518    //    StdInInputSource src;
519    try
520      {
521        const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
522        parser->parse(filename.c_str());
523        const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
524        duration = endMillis - startMillis;
525        errorCount = parser->getErrorCount();
526      }
527    catch (const OutOfMemoryException&)
528      {
529        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
530        errorCount = 2;
531        return false;
532      }
533    catch (const XMLException& e)
534      {
535        XERCES_STD_QUALIFIER cerr << "\nError during parsing: \n"
536                                  << StrX(e.getMessage())
537                                  << "\n" << XERCES_STD_QUALIFIER endl;
538        errorCount = 1;
539        return false;
540      }
541
542   
543    // Print out the stats that we collected and time taken
544    if (!errorCount) {
545      XERCES_STD_QUALIFIER cout << filename << ": " << duration << " ms ("
546                                << handler.GetElementCount() << " elems, "
547                                << handler.GetAttrCount() << " attrs, "
548                                << handler.GetSpaceCount() << " spaces, "
549                                << handler.GetCharacterCount() << " chars)" << XERCES_STD_QUALIFIER endl;
550    }
551  }
552 
553  //
554  //  Delete the parser itself.  Must be done prior to calling Terminate, below.
555  //
556  delete parser;
557 
558  XMLPlatformUtils::Terminate();
559 
560  if (errorCount > 0)
561    return false;
562  else
563    return true;
564}
Note: See TracBrowser for help on using the repository browser.