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

Revision 439, 18.3 KB checked in by mattausch, 19 years ago (diff)

added vview cell manager functionality

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