source: GTP/trunk/Lib/Vis/Preprocessing/src/X3dParser.cpp @ 870

Revision 870, 23.9 KB checked in by mattausch, 18 years ago (diff)

added pvs

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
32namespace GtpVisibilityPreprocessor {
33
34
35// ---------------------------------------------------------------------------
36//  Local data
37//
38//  doNamespaces
39//      Indicates whether namespace processing should be enabled or not.
40//      The default is no, but -n overrides that.
41//
42//  doSchema
43//      Indicates whether schema processing should be enabled or not.
44//      The default is no, but -s overrides that.
45//
46//  schemaFullChecking
47//      Indicates whether full schema constraint checking should be enabled or not.
48//      The default is no, but -s overrides that.
49//
50//  valScheme
51//      Indicates what validation scheme to use. It defaults to 'auto', but
52//      can be set via the -v= command.
53// ---------------------------------------------------------------------------
54static bool     doNamespaces       = false;
55static bool     doSchema           = false;
56static bool     schemaFullChecking = false;
57static SAXParser::ValSchemes    valScheme       = SAXParser::Val_Auto;
58
59#define ROTATE_SCENE 0
60
61
62static void RotateMesh(Mesh *mesh)
63{
64        VertexContainer::iterator it, it_end = mesh->mVertices.end();
65
66        const float angle = 30.0f * PI / 180.0f;
67        const Matrix4x4 rot = RotationYMatrix(angle);
68
69        for (it = mesh->mVertices.begin(); it != it_end; ++ it)
70        {
71                (*it) = rot * (*it);       
72        }
73}
74
75// ---------------------------------------------------------------------------
76//  StdInParseHandlers: Constructors and Destructor
77// ---------------------------------------------------------------------------
78X3dParseHandlers::X3dParseHandlers(SceneGraphNode *root, const bool loadPolygonsAsMeshes):
79  mElementCount(0)
80  , mAttrCount(0)
81  , mCharacterCount(0)
82  , mSpaceCount(0)
83  , mLoadPolygonsAsMeshes(loadPolygonsAsMeshes)
84{
85  mCurrentNode = root;
86  // this matrix should never be removed from stack
87  //mTransformations.push(IdentityMatrix());
88}
89
90X3dParseHandlers::~X3dParseHandlers()
91{
92        if (!mTransformations.empty())
93                cout << "error: transformation stack size: " << (int)mTransformations.size() << endl;
94}
95
96
97// ---------------------------------------------------------------------------
98//  StdInParseHandlers: Implementation of the SAX DocumentHandler interface
99// ---------------------------------------------------------------------------
100void X3dParseHandlers::endElement(const XMLCh* const name)
101{
102  StrX lname(name);
103  string element(lname.LocalForm());
104 
105  // only create new mesh instance if define mechanism was not used
106  if (element == "Shape")
107    EndShape();
108
109  if (element == "Transform")
110          EndTransform();
111}
112
113
114
115
116void X3dParseHandlers::ApplyTransformation(Mesh *mesh,
117                                                                                   const Matrix4x4 &m) const
118{
119        VertexContainer::iterator it, it_end = mesh->mVertices.end();
120
121        for (it = mesh->mVertices.begin(); it != it_end; ++ it)
122        {
123                (*it) = m * (*it);       
124        }
125}
126
127
128void X3dParseHandlers::ApplyTransformations(TrafoStack trafos, Mesh *mesh) const
129{
130        while (!trafos.empty())
131        {
132                const Matrix4x4 m = trafos.top();
133                trafos.pop();
134
135                ApplyTransformation(mesh, m);
136        }
137}
138
139void X3dParseHandlers::StartTransform(AttributeList&  attributes)
140{
141        Matrix4x4 currentTransform = IdentityMatrix();
142
143        const int len = attributes.getLength();
144    Matrix4x4 *rotm = NULL;
145        Matrix4x4 *scalem = NULL;
146        Matrix4x4 *translm = NULL;
147   
148        for (int i = 0; i < len; ++ i)
149        {
150                string attrName(StrX(attributes.getName(i)).LocalForm());
151                       
152                StrX attrValue(attributes.getValue(i));
153                const char *ptr = attrValue.LocalForm();
154                       
155                if (attrName == "rotation")
156                {
157                        Vector3 axis;
158                        float angle;
159                               
160                        if (sscanf(ptr, "%f %f %f %f", &axis.x, &axis.y, &axis.z, &angle) == 4)
161                        {
162                                rotm = new Matrix4x4(RotationAxisMatrix(axis, angle));
163                        }
164                }
165                else if (attrName == "translation")
166                {
167                        Vector3 transl;
168                                                       
169                        if (sscanf(ptr, "%f %f %f %f", &transl.x, &transl.y, &transl.z) == 3)
170                        {
171                                translm = new Matrix4x4(TranslationMatrix(transl));
172                        }
173                }
174                else if (attrName == "scale")
175                {
176                        Vector3 scale;
177
178                        if (sscanf(ptr, "%f %f %f %f", &scale.x, &scale.y, &scale.z) == 3)
179                        {
180                                scalem = new Matrix4x4(ScaleMatrix(scale.x, scale.y, scale.z));
181                        }
182                }
183                // todo: scale orientation
184        }
185       
186        if (scalem)
187                currentTransform *= (*scalem);
188        if (rotm)
189                currentTransform *= (*rotm);
190        if (translm)
191                currentTransform *= (*translm);
192
193        DEL_PTR(scalem);
194        DEL_PTR(rotm);
195        DEL_PTR(translm);
196
197        mTransformations.push(currentTransform);
198}
199
200
201void X3dParseHandlers::EndTransform()
202{
203        mTransformations.pop();
204}
205
206
207void X3dParseHandlers::EndShape()
208{
209        // this shape is a definition => don't create mesh instance
210        if (mIsMeshDefinition)
211{
212                mMeshDefinitions[mCurrentMeshName.c_str()] = mCurrentMesh;
213                //cout << "new definition: " << mCurrentMeshName << endl;
214               
215                return;
216        }
217
218        // each polygon is one single mesh
219        if (mLoadPolygonsAsMeshes)
220        {
221                //if (mCurrentMesh->mFaces.empty())     cout << "error!" << endl;
222
223                FaceContainer::const_iterator fit, fit_end = mCurrentMesh->mFaces.end();
224
225                cout << "m";
226                //cout << "m: " << mCurrentMesh->mFaces.size() << endl;
227                for (fit = mCurrentMesh->mFaces.begin(); fit != fit_end; ++ fit)
228                {
229                        cout << "f";
230
231                        Face *face = *fit;
232                        // only one face per mesh
233                        Mesh *mesh = new Mesh();
234                        VertexIndexContainer vc;
235                                       
236                        VertexIndexContainer::const_iterator vit, vit_end = face->mVertexIndices.end();
237                       
238                        int i = 0;
239                        for (vit = face->mVertexIndices.begin(); vit != vit_end; ++ vit, ++ i)
240                        {
241                                cout << "i";
242                                int index = (*vit);
243                                // add vertices
244                                mesh->mVertices.push_back(mCurrentMesh->mVertices[index]);
245                                vc.push_back(i);
246                        }
247
248                        mesh->mFaces.push_back(new Face(vc));
249
250                        // NOTE: should rather be written into trafo of mesh instance
251                        ApplyTransformations(mTransformations, mesh);
252
253                        mesh->Preprocess();
254                               
255                        // make an instance of this mesh
256                        MeshInstance *mi = new MeshInstance(mesh);
257                        mCurrentNode->mGeometry.push_back(mi);
258                }
259
260                // LEAK!! TODO: delete if not defd
261                if (!mUsingMeshDefinition)
262                        delete mCurrentMesh;
263
264                //mCurrentVertices.clear();
265                //mCurrentVertexIndices.clear();
266        }
267        else
268        {
269                if (!mCurrentMesh->mFaces.empty())
270                {
271                        // should rather be written into the transformation
272                        // of a mesh instance
273                        ApplyTransformations(mTransformations, mCurrentMesh);
274
275                        mCurrentMesh->Preprocess();
276                        // make an instance of this mesh
277                        MeshInstance *mi = new MeshInstance(mCurrentMesh);
278
279                        mCurrentNode->mGeometry.push_back(mi);
280                        // set the object id to a unique value
281                        //mi->SetId(mCurrentObjectId ++);
282                }
283                else
284                {
285                        // empty mesh => discard
286                        cout<<"X";
287
288                        delete mCurrentMesh;
289                }
290
291                mCurrentMesh = NULL;
292        }
293}
294
295
296void X3dParseHandlers::StartIndexedFaceSet(AttributeList&  attributes)
297{
298  int len = attributes.getLength();
299
300  int i;
301  VertexIndexContainer vertices;
302 
303        mIsMeshDefinition = false;
304        mUsingMeshDefinition = false;
305        for (i = 0; i < len; ++ i)
306        {
307                string attrName(StrX(attributes.getName(i)).LocalForm());
308         
309                // this is a definition of a mesh
310                if (attrName == "DEF")
311                {
312                        mIsMeshDefinition = true;
313                        StrX attrValue(attributes.getValue(i));
314                        const char *ptr = attrValue.LocalForm();
315                        mCurrentMeshName = ptr;
316
317                        cout << "d";
318                }
319               
320                // we use an already defined mesh
321                if (attrName == "USE")
322                {
323                        StrX attrValue(attributes.getValue(i));
324
325                        // discard new mesh and assign defined mesh
326                        DEL_PTR(mCurrentMesh);
327                        const char *ptr = attrValue.LocalForm();
328
329                        mCurrentMesh = mMeshDefinitions[ptr];
330                        mUsingMeshDefinition = true;
331                        cout << "u";
332                }
333               
334                if (attrName == "coordIndex")
335                {
336                        StrX attrValue(attributes.getValue(i));
337                        // handle coordIndex
338                        vertices.clear();
339                        const char *ptr = attrValue.LocalForm();
340                 
341                        char *endptr;
342         
343                        while (1)
344                        {
345                                int index = strtol(ptr, &endptr, 10);
346                                 
347                                if (ptr == endptr || index == -1)
348                                {
349                                        if (vertices.size() > 2)
350                                        {
351                                                Face *face = new Face(vertices);                 
352                                                mCurrentMesh->mFaces.push_back(face);
353                                        }
354                         
355                                        vertices.clear();
356                 
357                                        if (ptr == endptr)
358                                                break;
359                         
360                                  }
361                                  else
362                                  {
363                                          vertices.push_back(index);
364                                  }
365                                  ptr = endptr;
366                        }
367                }
368        }
369}
370
371
372void
373X3dParseHandlers::StartMaterial(
374                                AttributeList&  attributes)
375{
376  int len = attributes.getLength();
377  int i;
378  if (!mCurrentMesh->mMaterial)
379    mCurrentMesh->mMaterial = new Material;
380  for (i=0; i < len; i++) {
381    string attrName(StrX(attributes.getName(i)).LocalForm());
382    StrX attrValue(attributes.getValue(i));
383    const char *ptr = attrValue.LocalForm();
384    if (attrName == "diffuseColor") {
385      float r, g, b;
386      if (sscanf(ptr, "%f %f %f", &r, &g, &b) == 3)
387        mCurrentMesh->mMaterial->mDiffuseColor = RgbColor(r, g, b);
388    }
389  }
390}
391
392void
393X3dParseHandlers::StartCoordinate(
394                                  AttributeList&  attributes)
395{
396        int len = attributes.getLength();
397       
398        int i;
399        VertexContainer vertices;
400       
401        for (i=0; i < len; i++)
402        {
403                string attrName(StrX(attributes.getName(i)).LocalForm());
404         
405                if (attrName == "point")
406                {
407                        StrX attrValue(attributes.getValue(i));
408                 
409
410                        const char *ptr = attrValue.LocalForm();
411                        char *endptr;
412
413
414                        while (1)
415                        {
416                                float x = (float)strtod(ptr, &endptr);
417               
418                                if (ptr == endptr)
419                                  break;
420                         
421                                ptr = endptr;
422                               
423                                float y = (float)strtod(ptr, &endptr);
424                         
425                                if (ptr == endptr)
426                                        break;
427
428                                ptr = endptr;
429                         
430                                float z = (float)strtod(ptr, &endptr);
431                                if (ptr == endptr)
432                                        break;
433                         
434                                ptr = endptr;
435                         
436                                if (*ptr == ',')
437                                        ptr ++;
438
439                                Vector3 v(x, y, z);
440                                vertices.push_back(v);
441                        }
442                       
443                        mCurrentMesh->mVertices = vertices;
444                }
445        }
446}
447
448
449void
450X3dParseHandlers::startElement(const XMLCh* const name,
451                                                           AttributeList&  attributes)
452{
453  StrX lname(name);
454  string element(lname.LocalForm());
455 
456  if (element == "IndexedFaceSet") {
457    // create a new mesh node in the scene graph
458    StartIndexedFaceSet(attributes);
459  }
460 
461  if (element == "Shape") {
462    cout << "+";
463        mCurrentMesh = new Mesh;
464  }
465 
466  if (element == "Coordinate")
467  {
468    if (mCurrentMesh)
469      StartCoordinate(attributes);
470  }
471 
472  if (element == "Material") {
473    StartMaterial(attributes);
474  }
475 
476  if (element == "Transform") {
477          StartTransform(attributes);
478  }
479
480  mElementCount++;
481  mAttrCount += attributes.getLength();
482}
483
484void
485X3dParseHandlers::characters(const XMLCh* const chars,
486                             const unsigned int length)
487{
488  mCharacterCount += length;
489}
490
491void
492X3dParseHandlers::ignorableWhitespace(const XMLCh* const chars,
493                                      const unsigned int length)
494{
495  mSpaceCount += length;
496}
497
498void
499X3dParseHandlers::resetDocument()
500{
501  mAttrCount = 0;
502  mCharacterCount = 0;
503  mElementCount = 0;
504  mSpaceCount = 0;
505}
506
507
508
509// ---------------------------------------------------------------------------
510//  StdInParseHandlers: Overrides of the SAX ErrorHandler interface
511// ---------------------------------------------------------------------------
512void
513X3dParseHandlers::error(const SAXParseException& e)
514{
515  XERCES_STD_QUALIFIER cerr << "\nError at (file " << StrX(e.getSystemId())
516                            << ", line " << e.getLineNumber()
517                            << ", char " << e.getColumnNumber()
518                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
519}
520
521void
522X3dParseHandlers::fatalError(const SAXParseException& e)
523{
524  XERCES_STD_QUALIFIER cerr << "\nFatal Error at (file " << StrX(e.getSystemId())
525                            << ", line " << e.getLineNumber()
526                            << ", char " << e.getColumnNumber()
527                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
528}
529
530void
531X3dParseHandlers::warning(const SAXParseException& e)
532{
533  XERCES_STD_QUALIFIER cerr << "\nWarning at (file " << StrX(e.getSystemId())
534                            << ", line " << e.getLineNumber()
535                            << ", char " << e.getColumnNumber()
536                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
537}
538
539
540bool
541X3dParser::ParseFile(const string filename,
542                                         SceneGraphNode **root,
543                                         const bool loadPolygonsAsMeshes)
544{
545  // Initialize the XML4C system
546  try {
547    XMLPlatformUtils::Initialize();
548  }
549 
550  catch (const XMLException& toCatch)
551    {
552      XERCES_STD_QUALIFIER cerr << "Error during initialization! Message:\n"
553                                << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
554      return false;
555    }
556 
557 
558  //
559  //  Create a SAX parser object. Then, according to what we were told on
560  //  the command line, set the options.
561  //
562  SAXParser* parser = new SAXParser;
563  parser->setValidationScheme(valScheme);
564  parser->setDoNamespaces(doNamespaces);
565  parser->setDoSchema(doSchema);
566  parser->setValidationSchemaFullChecking(schemaFullChecking);
567 
568
569  //
570  //  Create our SAX handler object and install it on the parser, as the
571  //  document and error handler. We are responsible for cleaning them
572  //  up, but since its just stack based here, there's nothing special
573  //  to do.
574  //
575  *root = new SceneGraphNode;
576  X3dParseHandlers handler(*root, loadPolygonsAsMeshes);
577  parser->setDocumentHandler(&handler);
578  parser->setErrorHandler(&handler);
579 
580  unsigned long duration;
581  int errorCount = 0;
582  // create a faux scope so that 'src' destructor is called before
583  // XMLPlatformUtils::Terminate
584  {
585    //
586    //  Kick off the parse and catch any exceptions. Create a standard
587    //  input input source and tell the parser to parse from that.
588    //
589    //    StdInInputSource src;
590    try
591      {
592        const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
593        parser->parse(filename.c_str());
594        const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
595        duration = endMillis - startMillis;
596        errorCount = parser->getErrorCount();
597      }
598    catch (const OutOfMemoryException&)
599      {
600        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
601        errorCount = 2;
602        return false;
603      }
604    catch (const XMLException& e)
605      {
606        XERCES_STD_QUALIFIER cerr << "\nError during parsing: \n"
607                                  << StrX(e.getMessage())
608                                  << "\n" << XERCES_STD_QUALIFIER endl;
609        errorCount = 1;
610        return false;
611      }
612
613   
614    // Print out the stats that we collected and time taken
615    if (!errorCount) {
616      XERCES_STD_QUALIFIER cout << filename << ": " << duration << " ms ("
617                                << handler.GetElementCount() << " elems, "
618                                << handler.GetAttrCount() << " attrs, "
619                                << handler.GetSpaceCount() << " spaces, "
620                                << handler.GetCharacterCount() << " chars)" << XERCES_STD_QUALIFIER endl;
621    }
622  }
623 
624  //
625  //  Delete the parser itself.  Must be done prior to calling Terminate, below.
626  //
627  delete parser;
628 
629  XMLPlatformUtils::Terminate();
630 
631  if (errorCount > 0)
632    return false;
633  else
634    return true;
635}
636
637
638
639/************************************************************************/
640/*             class X3dViewCellsParseHandlers implementation           */
641/************************************************************************/
642
643
644// ---------------------------------------------------------------------------
645//  StdInParseHandlers: Constructors and Destructor
646// ---------------------------------------------------------------------------
647X3dViewCellsParseHandlers::X3dViewCellsParseHandlers(ViewCellsManager *viewCellsManager,
648                                                                                                         const float viewCellHeight):
649mElementCount(0),
650mAttrCount(0),
651mCharacterCount(0),
652mSpaceCount(0),
653mViewCellsManager(viewCellsManager),
654mViewCellHeight(viewCellHeight)
655{
656}
657
658X3dViewCellsParseHandlers::~X3dViewCellsParseHandlers()
659{
660}
661
662
663// ---------------------------------------------------------------------------
664//  StdInParseHandlers: Implementation of the SAX DocumentHandler interface
665// ---------------------------------------------------------------------------
666void X3dViewCellsParseHandlers::endElement(const XMLCh* const name)
667{
668  StrX lname(name);
669  string element(lname.LocalForm());
670 
671  if (element == "Shape")
672    EndShape();
673}
674
675void
676X3dViewCellsParseHandlers::EndShape()
677{
678        // currently processing no shape
679}
680
681void
682X3dViewCellsParseHandlers::StartIndexedFaceSet(
683                                      AttributeList&  attributes)
684{
685        int len = attributes.getLength();
686        int i;
687       
688        // clear previous vertex indices
689        mCurrentVertexIndices.clear();
690
691
692        for (i=0; i < len; i++)
693        {
694                string attrName(StrX(attributes.getName(i)).LocalForm());
695           
696
697                if (attrName == "coordIndex")
698                {
699                        StrX attrValue(attributes.getValue(i));
700                       
701                        // handle coordIndex
702                        const char *ptr = attrValue.LocalForm();
703                        char *endptr;
704               
705                        while (1)
706                        {
707                                int index = strtol(ptr, &endptr, 10);
708                               
709                                if (ptr == endptr)
710                                        break;
711
712                                if (index != -1)
713                                {
714                                        mCurrentVertexIndices.push_back(index);
715                                }
716                   
717                                ptr = endptr;
718                        }
719                }
720        }
721}
722
723
724void
725X3dViewCellsParseHandlers::StartCoordinate(AttributeList&  attributes)
726{
727        int len = attributes.getLength();
728       
729        VertexContainer vertices;
730        int i;
731        for (i=0; i < len; i++)
732        {
733                string attrName(StrX(attributes.getName(i)).LocalForm());
734               
735                if (attrName == "point")
736                {
737                        StrX attrValue(attributes.getValue(i));
738                       
739                        const char *ptr = attrValue.LocalForm();
740                       
741                        char *endptr;
742                       
743                        while (1)
744                        {
745                                float x = (float)strtod(ptr, &endptr);
746               
747                                if (ptr == endptr)
748                                        break;
749                                ptr = endptr;
750                               
751                                float y = (float)(float)strtod(ptr, &endptr);
752
753                               
754                                if (ptr == endptr)
755                                        break;
756                                ptr = endptr;
757
758                                float z = (float)(float)strtod(ptr, &endptr);
759
760                                if (ptr == endptr)
761                                        break;
762
763                                ptr = endptr;
764                                if (*ptr == ',')
765                                        ptr++;
766
767                                Vector3 v(x, y, z);
768                                vertices.push_back(v);                         
769                        }
770                }
771        }
772
773        for (i = 0; i < mCurrentVertexIndices.size(); i += 3)
774        {
775                Triangle3 baseTri(vertices[mCurrentVertexIndices[i + 0]],
776                                                  vertices[mCurrentVertexIndices[i + 1]],
777                                                  vertices[mCurrentVertexIndices[i + 2]]);
778
779                // create view cell from base triangle
780                mViewCellsManager->AddViewCell(
781                        mViewCellsManager->ExtrudeViewCell(baseTri,
782                        mViewCellHeight));
783        }
784}
785
786
787void
788X3dViewCellsParseHandlers::startElement(const XMLCh* const name,
789                                                                                AttributeList&  attributes)
790{
791  StrX lname(name);
792  string element(lname.LocalForm());
793 
794  if (element == "IndexedFaceSet") {
795    // create the viewcells from individual triangles
796    StartIndexedFaceSet(attributes);
797  }
798       
799  if (element == "Coordinate") {
800          // add coordinates to the triangles
801      StartCoordinate(attributes);
802  }
803  // do nothing
804  //if (element == "Shape") {}
805  // ignore material
806  //if (element == "Material") {}
807
808  ++ mElementCount;
809  mAttrCount += attributes.getLength();
810}
811
812void
813X3dViewCellsParseHandlers::characters(const XMLCh* const chars,
814                             const unsigned int length)
815{
816  mCharacterCount += length;
817}
818
819void
820X3dViewCellsParseHandlers::ignorableWhitespace(const XMLCh* const chars,
821                                      const unsigned int length)
822{
823  mSpaceCount += length;
824}
825
826void
827X3dViewCellsParseHandlers::resetDocument()
828{
829  mAttrCount = 0;
830  mCharacterCount = 0;
831  mElementCount = 0;
832  mSpaceCount = 0;
833}
834
835
836
837// ---------------------------------------------------------------------------
838//  StdInParseHandlers: Overrides of the SAX ErrorHandler interface
839// ---------------------------------------------------------------------------
840void
841X3dViewCellsParseHandlers::error(const SAXParseException& e)
842{
843  XERCES_STD_QUALIFIER cerr << "\nError at (file " << StrX(e.getSystemId())
844                            << ", line " << e.getLineNumber()
845                            << ", char " << e.getColumnNumber()
846                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
847}
848
849void
850X3dViewCellsParseHandlers::fatalError(const SAXParseException& e)
851{
852  XERCES_STD_QUALIFIER cerr << "\nFatal Error at (file " << StrX(e.getSystemId())
853                            << ", line " << e.getLineNumber()
854                            << ", char " << e.getColumnNumber()
855                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
856}
857
858void
859X3dViewCellsParseHandlers::warning(const SAXParseException& e)
860{
861  XERCES_STD_QUALIFIER cerr << "\nWarning at (file " << StrX(e.getSystemId())
862                            << ", line " << e.getLineNumber()
863                            << ", char " << e.getColumnNumber()
864                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
865}
866
867
868bool
869X3dParser::ParseFile(const string filename, ViewCellsManager &viewCells)
870{
871  // Initialize the XML4C system
872  try {
873    XMLPlatformUtils::Initialize();
874  }
875 
876  catch (const XMLException& toCatch)
877    {
878      XERCES_STD_QUALIFIER cerr << "Error during initialization! Message:\n"
879                                << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
880      return false;
881    }
882 
883 
884  //
885  //  Create a SAX parser object. Then, according to what we were told on
886  //  the command line, set the options.
887  //
888  SAXParser* parser = new SAXParser;
889  parser->setValidationScheme(valScheme);
890  parser->setDoNamespaces(doNamespaces);
891  parser->setDoSchema(doSchema);
892  parser->setValidationSchemaFullChecking(schemaFullChecking);
893 
894
895  //
896  //  Create our SAX handler object and install it on the parser, as the
897  //  document and error handler. We are responsible for cleaning them
898  //  up, but since its just stack based here, there's nothing special
899  //  to do.
900  //
901  X3dViewCellsParseHandlers handler(&viewCells, mViewCellHeight);
902  parser->setDocumentHandler(&handler);
903  parser->setErrorHandler(&handler);
904 
905  unsigned long duration;
906  int errorCount = 0;
907  // create a faux scope so that 'src' destructor is called before
908  // XMLPlatformUtils::Terminate
909  {
910    //
911    //  Kick off the parse and catch any exceptions. Create a standard
912    //  input input source and tell the parser to parse from that.
913    //
914    //    StdInInputSource src;
915    try
916      {
917        const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
918        parser->parse(filename.c_str());
919        const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
920        duration = endMillis - startMillis;
921        errorCount = parser->getErrorCount();
922      }
923    catch (const OutOfMemoryException&)
924      {
925        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
926        errorCount = 2;
927        return false;
928      }
929    catch (const XMLException& e)
930      {
931        XERCES_STD_QUALIFIER cerr << "\nError during parsing: \n"
932                                  << StrX(e.getMessage())
933                                  << "\n" << XERCES_STD_QUALIFIER endl;
934        errorCount = 1;
935        return false;
936      }
937
938   
939    // Print out the stats that we collected and time taken
940    if (!errorCount) {
941      XERCES_STD_QUALIFIER cout << filename << ": " << duration << " ms ("
942                                << handler.GetElementCount() << " elems, "
943                                << handler.GetAttrCount() << " attrs, "
944                                << handler.GetSpaceCount() << " spaces, "
945                                << handler.GetCharacterCount() << " chars)" << XERCES_STD_QUALIFIER endl;
946    }
947  }
948 
949  //
950  //  Delete the parser itself.  Must be done prior to calling Terminate, below.
951  //
952  delete parser;
953 
954  XMLPlatformUtils::Terminate();
955 
956  if (errorCount > 0)
957    return false;
958  else
959    return true;
960}
961
962}
Note: See TracBrowser for help on using the repository browser.