source: trunk/VUT/GtpVisibilityPreprocessor/src/X3dParser.cpp @ 508

Revision 508, 18.5 KB checked in by mattausch, 18 years ago (diff)

implemented view cells exporting / loading
improved vsp bsp tree (only axis aligbed until a level), reuse results from Plane
testing, collectmergeneighbors
implemented view cell meshes

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 "X3dParser.h"
25
26#include "X3dParserXerces.h"
27#include "Mesh.h"
28#include "SceneGraph.h"
29#include "Triangle3.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// ---------------------------------------------------------------------------
63X3dParseHandlers::X3dParseHandlers(SceneGraphNode *root) :
64  mElementCount(0)
65  , mAttrCount(0)
66  , mCharacterCount(0)
67  , mSpaceCount(0)
68 // , mCurrentObjectId(0)
69{
70  mCurrentNode = root;
71}
72
73X3dParseHandlers::~X3dParseHandlers()
74{
75}
76
77
78// ---------------------------------------------------------------------------
79//  StdInParseHandlers: Implementation of the SAX DocumentHandler interface
80// ---------------------------------------------------------------------------
81void X3dParseHandlers::endElement(const XMLCh* const name)
82{
83  StrX lname(name);
84  string element(lname.LocalForm());
85  if (element == "Shape")
86    EndShape();
87}
88
89void
90X3dParseHandlers::EndShape()
91{
92  if (mCurrentMesh->mFaces.size()) {
93    mCurrentMesh->Preprocess();
94    // make an instance of this mesh
95    MeshInstance *mi = new MeshInstance(mCurrentMesh);
96    mCurrentNode->mGeometry.push_back(mi);
97        // set the object id to a unique value
98        //mi->SetId(mCurrentObjectId ++);
99  } else {
100    cout<<"X";
101    delete mCurrentMesh;
102  }
103  mCurrentMesh = NULL;
104}
105
106void
107X3dParseHandlers::StartIndexedFaceSet(
108                                                                          AttributeList&  attributes)
109{
110  int len = attributes.getLength();
111  int i;
112  VertexIndexContainer vertices;
113 
114  for (i=0; i < len; i++) {
115    string attrName(StrX(attributes.getName(i)).LocalForm());
116    if (attrName == "coordIndex") {
117      StrX attrValue(attributes.getValue(i));
118      // handle coordIndex
119      vertices.clear();
120      const char *ptr = attrValue.LocalForm();
121      char *endptr;
122      while(1) {
123        int index = strtol(ptr, &endptr, 10);
124        if (ptr == endptr || index == -1) {
125          if (vertices.size() > 2) {
126            Face *face = new Face(vertices);
127            mCurrentMesh->mFaces.push_back(face);
128          }
129          vertices.clear();
130          if (ptr == endptr)
131            break;
132        } else {
133          vertices.push_back(index);
134        }
135        ptr = endptr;
136          }
137    }
138  }
139}
140
141void
142X3dParseHandlers::StartMaterial(
143                                AttributeList&  attributes)
144{
145  int len = attributes.getLength();
146  int i;
147  if (!mCurrentMesh->mMaterial)
148    mCurrentMesh->mMaterial = new Material;
149  for (i=0; i < len; i++) {
150    string attrName(StrX(attributes.getName(i)).LocalForm());
151    StrX attrValue(attributes.getValue(i));
152    const char *ptr = attrValue.LocalForm();
153    if (attrName == "diffuseColor") {
154      float r, g, b;
155      if (sscanf(ptr, "%f %f %f", &r, &g, &b) == 3)
156        mCurrentMesh->mMaterial->mDiffuseColor = RgbColor(r, g, b);
157    }
158  }
159}
160
161void
162X3dParseHandlers::StartCoordinate(
163                                  AttributeList&  attributes)
164{
165  int len = attributes.getLength();
166  int i;
167  VertexContainer vertices;
168  for (i=0; i < len; i++) {
169    string attrName(StrX(attributes.getName(i)).LocalForm());
170    if (attrName == "point") {
171      StrX attrValue(attributes.getValue(i));
172      const char *ptr = attrValue.LocalForm();
173      char *endptr;
174      while(1) {
175        float x = (float)strtod(ptr, &endptr);
176        if (ptr == endptr)
177          break;
178        ptr = endptr;
179        float y = (float)strtod(ptr, &endptr);
180        if (ptr == endptr)
181          break;
182        ptr = endptr;
183        float z = (float)strtod(ptr, &endptr);
184        if (ptr == endptr)
185          break;
186        ptr = endptr;
187        if (*ptr == ',')
188          ptr++;
189        Vector3 v(x, y, z);
190        vertices.push_back(v);
191      }
192      mCurrentMesh->mVertices = vertices;
193    }
194  }
195}
196
197
198void
199X3dParseHandlers::startElement(const XMLCh* const name,
200                                                           AttributeList&  attributes)
201{
202  StrX lname(name);
203  string element(lname.LocalForm());
204 
205  if (element == "IndexedFaceSet") {
206    // create a new mesh node in the scene graph
207    StartIndexedFaceSet(attributes);
208  }
209
210  if (element == "Shape") {
211    cout<<"+";
212    mCurrentMesh = new Mesh;
213  }
214 
215  if (element == "Coordinate") {
216    if (mCurrentMesh)
217      StartCoordinate(attributes);
218  }
219 
220  if (element == "Material") {
221    StartMaterial(attributes);
222  }
223
224  mElementCount++;
225  mAttrCount += attributes.getLength();
226}
227
228void
229X3dParseHandlers::characters(const XMLCh* const chars,
230                             const unsigned int length)
231{
232  mCharacterCount += length;
233}
234
235void
236X3dParseHandlers::ignorableWhitespace(const XMLCh* const chars,
237                                      const unsigned int length)
238{
239  mSpaceCount += length;
240}
241
242void
243X3dParseHandlers::resetDocument()
244{
245  mAttrCount = 0;
246  mCharacterCount = 0;
247  mElementCount = 0;
248  mSpaceCount = 0;
249}
250
251
252
253// ---------------------------------------------------------------------------
254//  StdInParseHandlers: Overrides of the SAX ErrorHandler interface
255// ---------------------------------------------------------------------------
256void
257X3dParseHandlers::error(const SAXParseException& e)
258{
259  XERCES_STD_QUALIFIER cerr << "\nError at (file " << StrX(e.getSystemId())
260                            << ", line " << e.getLineNumber()
261                            << ", char " << e.getColumnNumber()
262                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
263}
264
265void
266X3dParseHandlers::fatalError(const SAXParseException& e)
267{
268  XERCES_STD_QUALIFIER cerr << "\nFatal Error at (file " << StrX(e.getSystemId())
269                            << ", line " << e.getLineNumber()
270                            << ", char " << e.getColumnNumber()
271                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
272}
273
274void
275X3dParseHandlers::warning(const SAXParseException& e)
276{
277  XERCES_STD_QUALIFIER cerr << "\nWarning at (file " << StrX(e.getSystemId())
278                            << ", line " << e.getLineNumber()
279                            << ", char " << e.getColumnNumber()
280                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
281}
282
283
284bool
285X3dParser::ParseFile(const string filename,
286                     SceneGraphNode **root)
287{
288  // Initialize the XML4C system
289  try {
290    XMLPlatformUtils::Initialize();
291  }
292 
293  catch (const XMLException& toCatch)
294    {
295      XERCES_STD_QUALIFIER cerr << "Error during initialization! Message:\n"
296                                << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
297      return false;
298    }
299 
300 
301  //
302  //  Create a SAX parser object. Then, according to what we were told on
303  //  the command line, set the options.
304  //
305  SAXParser* parser = new SAXParser;
306  parser->setValidationScheme(valScheme);
307  parser->setDoNamespaces(doNamespaces);
308  parser->setDoSchema(doSchema);
309  parser->setValidationSchemaFullChecking(schemaFullChecking);
310 
311
312  //
313  //  Create our SAX handler object and install it on the parser, as the
314  //  document and error handler. We are responsible for cleaning them
315  //  up, but since its just stack based here, there's nothing special
316  //  to do.
317  //
318  *root = new SceneGraphNode;
319  X3dParseHandlers handler(*root);
320  parser->setDocumentHandler(&handler);
321  parser->setErrorHandler(&handler);
322 
323  unsigned long duration;
324  int errorCount = 0;
325  // create a faux scope so that 'src' destructor is called before
326  // XMLPlatformUtils::Terminate
327  {
328    //
329    //  Kick off the parse and catch any exceptions. Create a standard
330    //  input input source and tell the parser to parse from that.
331    //
332    //    StdInInputSource src;
333    try
334      {
335        const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
336        parser->parse(filename.c_str());
337        const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
338        duration = endMillis - startMillis;
339        errorCount = parser->getErrorCount();
340      }
341    catch (const OutOfMemoryException&)
342      {
343        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
344        errorCount = 2;
345        return false;
346      }
347    catch (const XMLException& e)
348      {
349        XERCES_STD_QUALIFIER cerr << "\nError during parsing: \n"
350                                  << StrX(e.getMessage())
351                                  << "\n" << XERCES_STD_QUALIFIER endl;
352        errorCount = 1;
353        return false;
354      }
355
356   
357    // Print out the stats that we collected and time taken
358    if (!errorCount) {
359      XERCES_STD_QUALIFIER cout << filename << ": " << duration << " ms ("
360                                << handler.GetElementCount() << " elems, "
361                                << handler.GetAttrCount() << " attrs, "
362                                << handler.GetSpaceCount() << " spaces, "
363                                << handler.GetCharacterCount() << " chars)" << XERCES_STD_QUALIFIER endl;
364    }
365  }
366 
367  //
368  //  Delete the parser itself.  Must be done prior to calling Terminate, below.
369  //
370  delete parser;
371 
372  XMLPlatformUtils::Terminate();
373 
374  if (errorCount > 0)
375    return false;
376  else
377    return true;
378}
379
380
381
382/************************************************************************/
383/*             class X3dViewCellsParseHandlers implementation           */
384/************************************************************************/
385
386
387// ---------------------------------------------------------------------------
388//  StdInParseHandlers: Constructors and Destructor
389// ---------------------------------------------------------------------------
390X3dViewCellsParseHandlers::X3dViewCellsParseHandlers(ViewCellsManager *viewCellsManager,
391                                                                                                         float viewCellHeight):
392mElementCount(0),
393mAttrCount(0),
394mCharacterCount(0),
395mSpaceCount(0),
396mViewCellsManager(viewCellsManager),
397mViewCellHeight(viewCellHeight)
398{
399}
400
401X3dViewCellsParseHandlers::~X3dViewCellsParseHandlers()
402{
403}
404
405
406// ---------------------------------------------------------------------------
407//  StdInParseHandlers: Implementation of the SAX DocumentHandler interface
408// ---------------------------------------------------------------------------
409void X3dViewCellsParseHandlers::endElement(const XMLCh* const name)
410{
411  StrX lname(name);
412  string element(lname.LocalForm());
413  if (element == "Shape")
414    EndShape();
415}
416
417void
418X3dViewCellsParseHandlers::EndShape()
419{
420}
421
422void
423X3dViewCellsParseHandlers::StartIndexedFaceSet(
424                                      AttributeList&  attributes)
425{
426        int len = attributes.getLength();
427        int i;
428        // clear previous vertex indices
429        mCurrentVertexIndices.clear();
430        for (i=0; i < len; i++)
431        {
432                string attrName(StrX(attributes.getName(i)).LocalForm());
433           
434                if (attrName == "coordIndex")
435                {
436                        StrX attrValue(attributes.getValue(i));
437                       
438                        // handle coordIndex
439                        const char *ptr = attrValue.LocalForm();
440                        char *endptr;
441               
442                        while (1)
443                        {
444                                int index = strtol(ptr, &endptr, 10);
445                               
446                                if (ptr == endptr)
447                                        break;
448
449                                if (index != -1)
450                                {
451                                        mCurrentVertexIndices.push_back(index);
452                                }
453                   
454                                ptr = endptr;
455                        }
456                }
457        }
458}
459
460
461void
462X3dViewCellsParseHandlers::StartCoordinate(AttributeList&  attributes)
463{
464        int len = attributes.getLength();
465       
466        VertexContainer vertices;
467        int i;
468        for (i=0; i < len; i++)
469        {
470                string attrName(StrX(attributes.getName(i)).LocalForm());
471               
472                if (attrName == "point")
473                {
474                        StrX attrValue(attributes.getValue(i));
475                       
476                        const char *ptr = attrValue.LocalForm();
477                       
478                        char *endptr;
479                       
480                        while (1)
481                        {
482                                float x = (float)strtod(ptr, &endptr);
483               
484                                if (ptr == endptr)
485                                        break;
486                                ptr = endptr;
487                               
488                                float y = (float)(float)strtod(ptr, &endptr);
489
490                               
491                                if (ptr == endptr)
492                                        break;
493                                ptr = endptr;
494
495                                float z = (float)(float)strtod(ptr, &endptr);
496
497                                if (ptr == endptr)
498                                        break;
499
500                                ptr = endptr;
501                                if (*ptr == ',')
502                                        ptr++;
503
504                                Vector3 v(x, y, z);
505                                vertices.push_back(v);                         
506                        }
507                }
508        }
509
510        for (i = 0; i < mCurrentVertexIndices.size(); i += 3)
511        {
512                Triangle3 baseTri(vertices[mCurrentVertexIndices[i + 0]],
513                                                  vertices[mCurrentVertexIndices[i + 1]],
514                                                  vertices[mCurrentVertexIndices[i + 2]]);
515
516                // create view cell from base triangle
517                mViewCellsManager->AddViewCell(
518                        mViewCellsManager->ExtrudeViewCell(baseTri,
519                        mViewCellHeight));
520        }
521}
522
523
524void
525X3dViewCellsParseHandlers::startElement(const XMLCh* const name,
526                                                                                AttributeList&  attributes)
527{
528  StrX lname(name);
529  string element(lname.LocalForm());
530 
531  if (element == "IndexedFaceSet") {
532    // create the viewcells from individual triangles
533    StartIndexedFaceSet(attributes);
534  }
535       
536  if (element == "Coordinate") {
537          // add coordinates to the triangles
538      StartCoordinate(attributes);
539  }
540  // do nothing
541  //if (element == "Shape") {}
542  // ignore material
543  //if (element == "Material") {}
544
545  ++ mElementCount;
546  mAttrCount += attributes.getLength();
547}
548
549void
550X3dViewCellsParseHandlers::characters(const XMLCh* const chars,
551                             const unsigned int length)
552{
553  mCharacterCount += length;
554}
555
556void
557X3dViewCellsParseHandlers::ignorableWhitespace(const XMLCh* const chars,
558                                      const unsigned int length)
559{
560  mSpaceCount += length;
561}
562
563void
564X3dViewCellsParseHandlers::resetDocument()
565{
566  mAttrCount = 0;
567  mCharacterCount = 0;
568  mElementCount = 0;
569  mSpaceCount = 0;
570}
571
572
573
574// ---------------------------------------------------------------------------
575//  StdInParseHandlers: Overrides of the SAX ErrorHandler interface
576// ---------------------------------------------------------------------------
577void
578X3dViewCellsParseHandlers::error(const SAXParseException& e)
579{
580  XERCES_STD_QUALIFIER cerr << "\nError at (file " << StrX(e.getSystemId())
581                            << ", line " << e.getLineNumber()
582                            << ", char " << e.getColumnNumber()
583                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
584}
585
586void
587X3dViewCellsParseHandlers::fatalError(const SAXParseException& e)
588{
589  XERCES_STD_QUALIFIER cerr << "\nFatal Error at (file " << StrX(e.getSystemId())
590                            << ", line " << e.getLineNumber()
591                            << ", char " << e.getColumnNumber()
592                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
593}
594
595void
596X3dViewCellsParseHandlers::warning(const SAXParseException& e)
597{
598  XERCES_STD_QUALIFIER cerr << "\nWarning at (file " << StrX(e.getSystemId())
599                            << ", line " << e.getLineNumber()
600                            << ", char " << e.getColumnNumber()
601                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
602}
603
604
605bool
606X3dParser::ParseFile(const string filename, ViewCellsManager &viewCells)
607{
608  // Initialize the XML4C system
609  try {
610    XMLPlatformUtils::Initialize();
611  }
612 
613  catch (const XMLException& toCatch)
614    {
615      XERCES_STD_QUALIFIER cerr << "Error during initialization! Message:\n"
616                                << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
617      return false;
618    }
619 
620 
621  //
622  //  Create a SAX parser object. Then, according to what we were told on
623  //  the command line, set the options.
624  //
625  SAXParser* parser = new SAXParser;
626  parser->setValidationScheme(valScheme);
627  parser->setDoNamespaces(doNamespaces);
628  parser->setDoSchema(doSchema);
629  parser->setValidationSchemaFullChecking(schemaFullChecking);
630 
631
632  //
633  //  Create our SAX handler object and install it on the parser, as the
634  //  document and error handler. We are responsible for cleaning them
635  //  up, but since its just stack based here, there's nothing special
636  //  to do.
637  //
638  X3dViewCellsParseHandlers handler(&viewCells, mViewCellHeight);
639  parser->setDocumentHandler(&handler);
640  parser->setErrorHandler(&handler);
641 
642  unsigned long duration;
643  int errorCount = 0;
644  // create a faux scope so that 'src' destructor is called before
645  // XMLPlatformUtils::Terminate
646  {
647    //
648    //  Kick off the parse and catch any exceptions. Create a standard
649    //  input input source and tell the parser to parse from that.
650    //
651    //    StdInInputSource src;
652    try
653      {
654        const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
655        parser->parse(filename.c_str());
656        const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
657        duration = endMillis - startMillis;
658        errorCount = parser->getErrorCount();
659      }
660    catch (const OutOfMemoryException&)
661      {
662        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
663        errorCount = 2;
664        return false;
665      }
666    catch (const XMLException& e)
667      {
668        XERCES_STD_QUALIFIER cerr << "\nError during parsing: \n"
669                                  << StrX(e.getMessage())
670                                  << "\n" << XERCES_STD_QUALIFIER endl;
671        errorCount = 1;
672        return false;
673      }
674
675   
676    // Print out the stats that we collected and time taken
677    if (!errorCount) {
678      XERCES_STD_QUALIFIER cout << filename << ": " << duration << " ms ("
679                                << handler.GetElementCount() << " elems, "
680                                << handler.GetAttrCount() << " attrs, "
681                                << handler.GetSpaceCount() << " spaces, "
682                                << handler.GetCharacterCount() << " chars)" << XERCES_STD_QUALIFIER endl;
683    }
684  }
685 
686  //
687  //  Delete the parser itself.  Must be done prior to calling Terminate, below.
688  //
689  delete parser;
690 
691  XMLPlatformUtils::Terminate();
692 
693  if (errorCount > 0)
694    return false;
695  else
696    return true;
697}
Note: See TracBrowser for help on using the repository browser.