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

Revision 294, 18.5 KB checked in by mattausch, 19 years ago (diff)

vertical splitr criterium

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