root/OpenSceneGraph/trunk/src/osgPlugins/Inventor/ConvertToInventor.cpp @ 13041

Revision 13041, 77.3 kB (checked in by robert, 3 years ago)

Ran script to remove trailing spaces and tabs

  • Property svn:eol-style set to native
Line 
1//
2//  ConvertToInventor converts OSG scene graph to Inventor or VRML 1 scene graph
3//
4//  It requires OSG and Inventor compatible library, such as Coin,
5//  SGI Inventor , or TGS Inventor.
6//
7//
8//  Autor: PCJohn (peciva _at fit.vutbr.cz)
9//
10//  License: public domain
11//
12//
13//  THIS SOFTWARE IS NOT COPYRIGHTED
14//
15//  This source code is offered for use in the public domain.
16//  You may use, modify or distribute it freely.
17//
18//  This source code is distributed in the hope that it will be useful but
19//  WITHOUT ANY WARRANTY.  ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
20//  DISCLAIMED.  This includes but is not limited to warranties of
21//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
22//
23//  If you find the source code useful, authors will kindly welcome
24//  if you give them credit and keep their names with their source code,
25//  but you are not forced to do so.
26//
27
28
29#include <osg/BlendFunc>
30#include <osg/Billboard>
31#include <osg/Geode>
32#include <osg/Geometry>
33#include <osg/Group>
34#include <osg/LightModel>
35#include <osg/LOD>
36#include <osg/Material>
37#include <osg/MatrixTransform>
38#include <osg/Node>
39#include <osg/NodeVisitor>
40#include <osg/PositionAttitudeTransform>
41#include <osg/PrimitiveSet>
42#include <osg/ShapeDrawable>
43#include <osg/TexEnv>
44#include <osg/TexGen>
45#include <Inventor/nodes/SoBaseColor.h>
46#include <Inventor/nodes/SoCoordinate3.h>
47#include <Inventor/nodes/SoCoordinate4.h>
48#include <Inventor/nodes/SoCube.h>
49#include <Inventor/nodes/SoCone.h>
50#include <Inventor/nodes/SoCylinder.h>
51#include <Inventor/nodes/SoFaceSet.h>
52#include <Inventor/nodes/SoIndexedFaceSet.h>
53#include <Inventor/nodes/SoIndexedLineSet.h>
54#include <Inventor/nodes/SoIndexedTriangleStripSet.h>
55#include <Inventor/nodes/SoLightModel.h>
56#include <Inventor/nodes/SoLineSet.h>
57#include <Inventor/nodes/SoLOD.h>
58#include <Inventor/nodes/SoLevelOfDetail.h>
59#include <Inventor/nodes/SoMaterial.h>
60#include <Inventor/nodes/SoMatrixTransform.h>
61#include <Inventor/nodes/SoNode.h>
62#include <Inventor/nodes/SoNormal.h>
63#include <Inventor/nodes/SoNormalBinding.h>
64#include <Inventor/nodes/SoPointSet.h>
65#include <Inventor/nodes/SoSeparator.h>
66#include <Inventor/nodes/SoShapeHints.h>
67#include <Inventor/nodes/SoSphere.h>
68#include <Inventor/nodes/SoTexture2.h>
69#include <Inventor/nodes/SoTextureCoordinate2.h>
70#include <Inventor/nodes/SoTextureCoordinateEnvironment.h>
71#include <Inventor/nodes/SoTransform.h>
72#include <Inventor/nodes/SoTranslation.h>
73#include <Inventor/nodes/SoTriangleStripSet.h>
74#include <Inventor/fields/SoFields.h>
75#ifdef __COIN__
76#include <Inventor/nodes/SoTextureCoordinate3.h>
77#include <Inventor/nodes/SoTransparencyType.h>
78#include <Inventor/VRMLnodes/SoVRMLBillboard.h>
79#endif
80#include "ConvertToInventor.h"
81
82#include <assert.h>
83
84
85#define DEBUG_IV_WRITER 1
86
87
88// Considerations for VRML1 support:
89//
90// SoSeparator:                supported (only renderCulling field)
91// SoCoordinate3:              supported
92// SoCoordinate4:              no -> conversion to Coordinate3 required <---- missing
93// SoTextureCoordinate2:       supported
94// SoTextureCoordinate3:       no - 3D textures not supported by VRML1
95// SoTextureCoordinateEnvironment no <- should texturing be disabled in this case?
96// SoTextureCoordinateBinding: no -> indexing is probably mandatory
97// SoNormal:                   supported
98// SoNormalBinding:            supported (all modes supported, including non-indexed modes)
99// SoMaterial:                 supported
100// SoMaterialBinding:          supported (all modes supported, including non-indexed modes)
101// SoBaseColor:                no -> using SoMaterial instead
102// SoPointSet:                 supported
103// SoLineSet:                  no -> using SoIndexedListSet instead
104// SoIndexedLineSet:           supported
105// SoIndexedTriangleStripSet:  no -> using SoIndexedFaceSet instead
106// SoTriangleStripSet:         no -> using SoIndexedFaceSet instead
107// SoMatrixTransform:          supported
108// SoTransform:                supported
109// SoTransparencyType:         no   <---- missing
110// SoShapeHints:               supported
111// SoCone,SoCube,SoCylinder,SoSphere supported
112// SoTranslation               supported
113// SoLightModel:               ?
114// SoLOD:                      supported
115// SoLevelOfDetail:            no
116
117
118// Node list from VRML1 documentation:
119// shape nodes: AsciiText, Cone, Cube, Cylinder, IndexedFaceSet, IndexedLineSet, PointSet, Sphere
120// properties nodes: Coordinate3, FontStyle, Info, Material, MaterialBinding, Normal, NormalBinding,
121//                   Texture2, Texture2Transform, TextureCoordinate2, ShapeHints
122// transformantion nodes: MatrixTransform, Rotation, Scale, Transform, Translation
123// group nodes: Separator, Switch, WWWAnchor, LOD
124// cameras: OrthographicCamera, PerspectiveCamera
125// lights: DirectionalLight, PointLight, SpotLight
126// others: WWWInline
127
128
129
130ConvertToInventor::ConvertToInventor() : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
131{
132  // Enable/disable using of some extensions introduced by TGS and Coin.
133  //
134  // For instance, GL_REPLACE texturing mode is extension
135  // and it will not be used if extensions are not enabled.
136#ifdef __COIN__
137  useIvExtensions = true;
138#else
139  useIvExtensions = false;
140#endif
141  vrml1Conversion = false;
142  uniqueIdGenerator = 1;
143
144  // Scene root
145  ivRoot = new SoSeparator;
146  ivRoot->ref();
147
148  // OSG -> Inventor coordinate system conversion
149  SoMatrixTransform *mt = new SoMatrixTransform;
150  mt->matrix.setValue(1.f, 0.f,  0.f, 0.f,
151                      0.f, 0.f, -1.f, 0.f,
152                      0.f, 1.f,  0.f, 0.f,
153                      0.f, 0.f,  0.f, 1.f);
154  ivRoot->addChild(mt);
155
156#if 0 // Setting everything to defaults may not be correct option
157      // because the user may want to have model whose material,etc.
158      // will be specified up in the scene graph and he may, for instance,
159      // reuse the model with different materials.
160      // However, I am not sure anyway. PCJohn-2007-08-27
161
162  //              OSG defaults to:    Inventor defaults to:
163  // GL_LIGHTING   enabled             enabled
164  SoLightModel *lm = new SoLightModel;
165  lm->model = SoLightModel::PHONG;
166  ivRoot->addChild(lm);
167
168  //              OSG defaults to:    Inventor defaults to:
169  // lighting:     one side            one side lighting
170  // frontFace:    COUNTER_CLOCKWISE   COUNTER_CLOCKWISE
171  // culling:      DISABLED            DISABLED
172  // faceCulling:  GL_BACK             GL_BACK
173  SoShapeHints *sh = new SoShapeHints;
174  sh->vertexOrdering = SoShapeHints::UNKNOWN_ORDERING;
175  ivRoot->addChild(sh);
176
177  // Make sure texturing is OFF
178  ivRoot->addChild(new SoTexture2D);
179
180  // Put default material
181  ivRoot->addChild(new SoMaterial);
182#endif
183
184  // initialize Inventor state stack
185  ivStack.push(InventorState::createTopLevelState(ivRoot));
186}
187
188
189ConvertToInventor::~ConvertToInventor()
190{
191  assert(ivStack.size() == 1 && "Not all InventorStates were popped from ivStack.");
192  if (ivRoot)  ivRoot->unref();
193}
194
195
196SoNode* ConvertToInventor::getIvSceneGraph() const
197{
198  return ivRoot;
199}
200
201
202void ConvertToInventor::apply(osg::Node &node)
203{
204#ifdef DEBUG_IV_WRITER
205  OSG_INFO << "IvWriter: node traversed" << std::endl;
206#endif
207
208  traverse(node);
209}
210
211
212template<typename fieldClass, typename ivType, typename osgType>
213void osgArray2ivMField_template(const osg::Array *array, fieldClass &field, int startIndex = 0, int stopIndex = 0, int numItemsUntilMinusOne = 0)
214{
215  int i,num = array->getNumElements();
216  if (startIndex!=0 || stopIndex!=0) {
217    num = stopIndex - startIndex;
218    assert(stopIndex >= startIndex);
219    assert(startIndex >= 0 && stopIndex >= 0);
220    assert(stopIndex <= int(array->getNumElements()));
221  }
222
223  // update num if numItemsUntilMinusOne > 0
224  if (numItemsUntilMinusOne > 0 && num >= 1)
225    num += (num-1) / numItemsUntilMinusOne;
226
227  field.setNum(num);
228  ivType *a = field.startEditing();
229
230  osgType *ptr = (osgType*)array->getDataPointer() + startIndex;
231
232  if (numItemsUntilMinusOne <= 0)
233    for (i=0; i<num; i++, ptr++)
234      a[i] = ivType(*ptr);
235  else {
236    int z;
237    for (i=0, z=0; i<num; i++)
238      if (z == numItemsUntilMinusOne) {
239        a[i] = ivType(-1);
240        z = 0;
241      } else {
242        a[i] = ivType(*ptr);
243        ptr++;
244        z++;
245      }
246  }
247
248  field.finishEditing();
249}
250
251
252template<typename ivType, typename osgType, int shift>
253void osgArray2ivMField_composite_template_worker(ivType *dest, osgType *src, int num, int numItemsUntilMinusOne = 0)
254{
255  for (int i=0; i<num; i++, src+=shift)
256    dest[i] = ivType(src);
257}
258
259
260template<>
261void osgArray2ivMField_composite_template_worker<SbColor, GLubyte, 4>(SbColor *dest, GLubyte *src, int num, int numItemsUntilMinusOne)
262{
263  for (int i=0; i<num; i++, src+=4)
264    dest[i].setValue(src[0]/255.f, src[1]/255.f, src[2]/255.f);
265}
266
267
268template<>
269void osgArray2ivMField_composite_template_worker<SbVec3f, float, 2>(SbVec3f *dest, float *src, int num, int numItemsUntilMinusOne)
270{
271  for (int i=0; i<num; i++, src+=2)
272    dest[i].setValue(src[0], src[1], 0.f);
273}
274
275
276template<typename fieldClass, typename ivType, typename osgType, int shift>
277void osgArray2ivMField_composite_template(const osg::Array *array, fieldClass &field, int startIndex = 0, int stopIndex = 0, int numItemsUntilMinusOne = 0)
278{
279  int num = array->getNumElements();
280  if (startIndex!=0 || stopIndex!=0) {
281    num = stopIndex - startIndex;
282    assert(stopIndex >= startIndex);
283    assert(startIndex >= 0 && stopIndex >= 0);
284    assert(stopIndex <= int(array->getNumElements()));
285  }
286  assert(numItemsUntilMinusOne <= 0 && "Composite template must have numItemsUntilMinusOne set to 0.");
287  field.setNum(num);
288  ivType *a = field.startEditing();
289
290  osgType *ptr = (osgType*)array->getDataPointer() + startIndex;
291  osgArray2ivMField_composite_template_worker<ivType, osgType, shift>(a, ptr, num, 0);
292
293  field.finishEditing();
294}
295
296
297template<typename fieldClass, typename ivType, typename osgType, int numComponents>
298void osgArray2ivMField_pack_template(const osg::Array *array, fieldClass &field,
299                                            osgType mul, osgType max, osgType min,
300                                            int startIndex = 0, int stopIndex = 0, int numItemsUntilMinusOne = 0)
301{
302  int i,num = array->getNumElements();
303  if (startIndex!=0 || stopIndex!=0) {
304    num = stopIndex - startIndex;
305    assert(stopIndex >= startIndex);
306    assert(startIndex >= 0 && stopIndex >= 0);
307    assert(stopIndex <= int(array->getNumElements()));
308  }
309  assert(numItemsUntilMinusOne <= 0 && "Pack template must have numItemsUntilMinusOne set to 0.");
310  field.setNum(num);
311  ivType *a = field.startEditing();
312
313  osgType *ptr = (osgType*)array->getDataPointer() + startIndex;
314  for (i=0; i<num; i++, ptr++) {
315    a[i] = ivType(0);
316    for (int j=0; j<numComponents; j++) {
317      osgType tmp = ptr[j]*mul;
318      if (tmp > max)  tmp = max;
319      if (tmp < min)  tmp = min;
320      a[i] |= ivType(tmp) << (((numComponents-1)*8)-(j*8));
321    }
322  }
323
324  field.finishEditing();
325}
326
327
328template<typename fieldClass, typename fieldItemType>
329bool ivApplicateIntType(const osg::Array *array, fieldClass &field, int startIndex, int stopIndex, int numItemsUntilMinusOne)
330{
331  if (field.isOfType(fieldClass::getClassTypeId()))
332  {
333    switch (array->getType())
334    {
335      case osg::Array::ByteArrayType:   osgArray2ivMField_template<fieldClass, fieldItemType, int8_t>
336                                          (array, field, startIndex, stopIndex, numItemsUntilMinusOne); return true;
337      case osg::Array::UByteArrayType:  osgArray2ivMField_template<fieldClass, fieldItemType, uint8_t>
338                                          (array, field, startIndex, stopIndex, numItemsUntilMinusOne); return true;
339      case osg::Array::ShortArrayType:  osgArray2ivMField_template<fieldClass, fieldItemType, int16_t>
340                                          (array, field, startIndex, stopIndex, numItemsUntilMinusOne); return true;
341      case osg::Array::UShortArrayType: osgArray2ivMField_template<fieldClass, fieldItemType, uint16_t>
342                                          (array, field, startIndex, stopIndex, numItemsUntilMinusOne); return true;
343      case osg::Array::IntArrayType:    osgArray2ivMField_template<fieldClass, fieldItemType, int32_t>
344                                          (array, field, startIndex, stopIndex, numItemsUntilMinusOne); return true;
345      case osg::Array::UIntArrayType:   osgArray2ivMField_template<fieldClass, fieldItemType, uint32_t>
346                                          (array, field, startIndex, stopIndex, numItemsUntilMinusOne); return true;
347      case osg::Array::FloatArrayType:  osgArray2ivMField_template<fieldClass, fieldItemType, float>
348                                          (array, field, startIndex, stopIndex, numItemsUntilMinusOne); return true;
349      case osg::Array::Vec4bArrayType:  // FIXME: should signed values be handled differently? Like -128..127?
350      case osg::Array::Vec4ubArrayType: osgArray2ivMField_pack_template<fieldClass, fieldItemType, GLubyte, 4>
351                                          (array, field, 1, 255, 0, startIndex, stopIndex, numItemsUntilMinusOne); return true;
352      case osg::Array::Vec4ArrayType:   osgArray2ivMField_pack_template<fieldClass, fieldItemType, float, 4>
353                                          (array, field, 255.f, 255.f, 0.f, startIndex, stopIndex, numItemsUntilMinusOne); return true;
354      default: break;
355    }
356  }
357  return false;
358}
359
360
361static void osgArray2ivMField(const osg::Array *array, SoMField &field, int startIndex = 0, int stopIndex = 0, int numItemsUntilMinusOne = 0)
362{
363  if (field.isOfType(SoMFFloat::getClassTypeId()))
364  {
365    switch (array->getType())
366    {
367      case osg::Array::FloatArrayType:  osgArray2ivMField_template<SoMFFloat, float, float>
368                                          (array, (SoMFFloat&)field, startIndex, stopIndex, numItemsUntilMinusOne); return;
369      default: break;
370    }
371  }
372  else if (ivApplicateIntType<SoMFInt32,  int32_t>(array, (SoMFInt32&) field, startIndex, stopIndex, numItemsUntilMinusOne)) return;
373  else if (ivApplicateIntType<SoMFUInt32,uint32_t>(array, (SoMFUInt32&)field, startIndex, stopIndex, numItemsUntilMinusOne)) return;
374  else if (ivApplicateIntType<SoMFShort,  int16_t>(array, (SoMFShort&) field, startIndex, stopIndex, numItemsUntilMinusOne)) return;
375  else if (ivApplicateIntType<SoMFUShort,uint16_t>(array, (SoMFUShort&)field, startIndex, stopIndex, numItemsUntilMinusOne)) return;
376  else if (field.isOfType(SoMFVec2f::getClassTypeId()))
377  {
378    switch (array->getType())
379    {
380      case osg::Array::Vec2ArrayType:   osgArray2ivMField_composite_template<SoMFVec2f, SbVec2f, float, 2>
381                                          (array, (SoMFVec2f&)field, startIndex, stopIndex, numItemsUntilMinusOne); return;
382      default: break;
383    }
384  }
385  else if (field.isOfType(SoMFVec3f::getClassTypeId()))
386  {
387    switch (array->getType())
388    {
389      case osg::Array::Vec3ArrayType:   osgArray2ivMField_composite_template<SoMFVec3f, SbVec3f, float, 3>
390                                          (array, (SoMFVec3f&)field, startIndex, stopIndex, numItemsUntilMinusOne); return;
391      case osg::Array::Vec2ArrayType:   osgArray2ivMField_composite_template<SoMFVec3f, SbVec3f, float, 2>
392                                          (array, (SoMFVec3f&)field, startIndex, stopIndex, numItemsUntilMinusOne); return;
393      default: break;
394    }
395  }
396  else if (field.isOfType(SoMFVec4f::getClassTypeId()))
397  {
398    switch (array->getType()) {
399      case osg::Array::Vec4ArrayType:   osgArray2ivMField_composite_template<SoMFVec4f, SbVec4f, float, 4>
400                                          (array, (SoMFVec4f&)field, startIndex, stopIndex, numItemsUntilMinusOne); return;
401      default: break;
402    }
403  }
404  else if (field.isOfType(SoMFColor::getClassTypeId()))
405  {
406    switch (array->getType())
407    {
408      case osg::Array::Vec3ArrayType:   osgArray2ivMField_composite_template<SoMFColor, SbColor, float, 3>
409                                          (array, (SoMFColor&)field, startIndex, stopIndex, numItemsUntilMinusOne); return;
410      case osg::Array::Vec4ArrayType:   osgArray2ivMField_composite_template<SoMFColor, SbColor, float, 4>
411                                          (array, (SoMFColor&)field, startIndex, stopIndex, numItemsUntilMinusOne); return;
412      case osg::Array::Vec4ubArrayType: osgArray2ivMField_composite_template<SoMFColor, SbColor, GLubyte, 4>
413                                          (array, (SoMFColor&)field, startIndex, stopIndex, numItemsUntilMinusOne); return;
414      default: break;
415    }
416  };
417
418  OSG_WARN << "IvWriter: No direct conversion for array. "
419    << "The file may be broken." << std::endl;
420}
421
422
423template<typename variableType, typename indexType>
424bool ivDeindex(variableType *dest, const variableType *src, const int srcNum,
425                    const indexType *indices, const int numToProcess)
426{
427  for (int i=0; i<numToProcess; i++) {
428    int index = indices[i];
429    if (index<0 || index>=srcNum)  return false;
430    dest[i] = src[index];
431  }
432  return true;
433}
434
435
436template<typename variableType>
437bool ivDeindex(variableType *dest, const variableType *src, const int srcNum,
438                    const osg::Array *indices, const int numToProcess)
439{
440  if (int(indices->getNumElements()) < numToProcess) {
441    assert(0 && "Something is wrong: indices array is shorter than numToProcess.");
442    return false;
443  }
444
445  switch (indices->getType()) {
446  case osg::Array::ByteArrayType:
447  case osg::Array::UByteArrayType:
448      return ivDeindex<variableType, GLbyte>(dest, src, srcNum,
449                                           (GLbyte*)indices->getDataPointer(), numToProcess);
450      break;
451  case osg::Array::ShortArrayType:
452  case osg::Array::UShortArrayType:
453      return ivDeindex<variableType, GLshort>(dest, src, srcNum,
454                                            (GLshort*)indices->getDataPointer(), numToProcess);
455      break;
456  case osg::Array::IntArrayType:
457  case osg::Array::UIntArrayType:
458      return ivDeindex<variableType, GLint>(dest, src, srcNum,
459                                          (GLint*)indices->getDataPointer(), numToProcess);
460      break;
461  default:
462      assert(0 && "Index of strange type.");
463      return false;
464  }
465}
466
467
468template<typename variableType, typename fieldType>
469bool ivProcessArray(const osg::Array *indices, const osg::Array *drawElemIndices,
470                         fieldType *destField, const fieldType *srcField,
471                         int startIndex, int numToProcess)
472{
473  bool ok = true;
474
475  if (indices || drawElemIndices) {
476
477    // "deindex" original data
478    if (indices && !drawElemIndices)
479      ok = ivDeindex<variableType>(destField->startEditing(),
480                                 srcField->getValues(startIndex),
481                                 srcField->getNum(), indices, numToProcess); else
482    if (!indices && drawElemIndices)
483      ok = ivDeindex<variableType>(destField->startEditing(),
484                                 srcField->getValues(startIndex),
485                                 srcField->getNum(), drawElemIndices, numToProcess);
486    else {
487      OSG_WARN << "IvWriter: NOT IMPLEMENTED" << std::endl;
488      assert(0); // FIXME:
489    }
490
491    destField->finishEditing();
492    if (!ok)
493      OSG_WARN << "IvWriter: Can not deindex - bug in model: index out of range." << std::endl;
494
495  } else {
496
497    // copy required part of original data
498    const variableType *src = srcField->getValues(startIndex);
499    assert(startIndex+numToProcess <= srcField->getNum() && "Index out of bounds.");
500    variableType *dest = destField->startEditing();
501    for (int i=0; i<numToProcess; i++)
502      *(dest++) = *(src++);
503    destField->finishEditing();
504  }
505
506  return ok;
507}
508
509
510static void processIndices(const osg::Array *indices, const osg::Array *drawElemIndices,
511                           SoMFInt32 &ivIndices,
512                           int startIndex, int stopIndex, int numItemsUntilMinusOne)
513{
514  if (indices || drawElemIndices) {
515    if (indices && !drawElemIndices)
516      osgArray2ivMField(indices, ivIndices, startIndex, stopIndex, numItemsUntilMinusOne); else
517    if (!indices && drawElemIndices)
518      osgArray2ivMField(drawElemIndices, ivIndices, startIndex, stopIndex, numItemsUntilMinusOne);
519    else {
520      OSG_WARN << "IvWriter: NOT IMPLEMENTED" << std::endl;
521      assert(0); // FIXME:
522    }
523
524  } else {
525    int num = stopIndex-startIndex;
526    if (numItemsUntilMinusOne != 0 && num >= 1)
527      num += (num-1)/numItemsUntilMinusOne;
528    ivIndices.setNum(num);
529    int32_t *a = ivIndices.startEditing();
530    if (numItemsUntilMinusOne <= 0)
531      for (int i=0,j=startIndex; j<stopIndex; i++,j++)
532        a[i] = j;
533    else
534      for (int i=0,j=startIndex,k=0; j<stopIndex; i++)
535        if (k==numItemsUntilMinusOne) {
536          a[i]=-1;
537          k=0;
538        } else {
539          a[i] = j;
540          j++;
541          k++;
542        }
543    ivIndices.finishEditing();
544  }
545}
546
547
548static void postProcessDrawArrayLengths(const osg::DrawArrayLengths *drawArrayLengths, SoMFInt32 *field)
549{
550  int origNum = field->getNum();
551  int newNum = origNum + drawArrayLengths->size()-1;
552  field->setNum(newNum);
553  int32_t *a = field->startEditing();
554  int32_t *src = a + origNum;
555  int32_t *dst = a + newNum;
556  for (osg::DrawArrayLengths::const_reverse_iterator primItr = drawArrayLengths->rbegin();
557      primItr!=drawArrayLengths->rend()-1;
558      ++primItr) {
559    int c = *primItr;
560    src -= c;
561    dst -= c;
562    memmove(dst, src, sizeof(int32_t)*c);
563    dst--;
564    *dst = -1;
565  }
566  field->finishEditing();
567}
568
569
570static void postProcessField(const SbIntList &runLengths, osg::PrimitiveSet::Mode primType,
571                             SoMFInt32 *field, osg::Geometry::AttributeBinding binding)
572{
573  if (binding==osg::Geometry::BIND_OFF || binding==osg::Geometry::BIND_OVERALL ||
574      binding==osg::Geometry::BIND_PER_PRIMITIVE_SET)
575    return;
576
577  // make copy of array
578  const int32_t *fieldArray = field->getValues(0);
579  int origNum = field->getNum();
580  int32_t *tmpArray = new int32_t[origNum];
581  memcpy(tmpArray, fieldArray, origNum*sizeof(int32_t));
582
583  // compute new number of indices
584  int newNum = origNum;
585  const int l = runLengths.getLength();
586  switch (binding) {
587    case osg::Geometry::BIND_PER_VERTEX:
588      for (int i=0; i<l; i++)
589        newNum += (runLengths[i]-3)*3;
590      break;
591    case osg::Geometry::BIND_PER_PRIMITIVE:
592      for (int i=0; i<l; i++)
593        newNum += runLengths[i]-3;
594      break;
595    default:
596      assert(0);
597  }
598
599  // process indices
600  field->setNum(newNum);
601  int32_t *src = tmpArray;
602  int32_t *dst = field->startEditing();
603  // int32_t *dst2 = dst;
604  switch (binding) {
605    case osg::Geometry::BIND_PER_VERTEX:
606      for (int i=0; i<l; i++) {
607        int c = runLengths[i];
608        *(dst++) = *(src++);
609        *(dst++) = *(src++);
610        *(dst++) = *(src++);
611        bool even = true;
612        int32_t first = *(src-3);
613        for (int j=3; j<c; j++) {
614          *(dst++) = -1;
615          if (primType==osg::PrimitiveSet::TRIANGLE_STRIP) {
616            if (even) {
617              *(dst++) = *(src-1);
618              *(dst++) = *(src-2);
619            } else {
620              *(dst++) = *(src-2);
621              *(dst++) = *(src-1);
622            }
623            even = !even;
624          } else
625          if (primType==osg::PrimitiveSet::TRIANGLE_FAN) {
626            *(dst++) = first;
627            *(dst++) = *(src-1);
628          } // FIXME: are QUADS, QUAD_STRIP, and POLYGON requiring some handling here as well? PCJohn-2007-08-25
629          else {
630            *(dst++) = *(src-2);
631            *(dst++) = *(src-1);
632          }
633          *(dst++) = *(src++);
634        }
635        src++; // skip -1
636        if (i != l-1)
637          *(dst++) = -1;
638      }
639      break;
640
641    case osg::Geometry::BIND_PER_PRIMITIVE:
642      for (int i=0; i<l; i++,src++) {
643        int c = runLengths[i];
644        *(dst++) = *(src);
645        for (int j=3; j<c; j++)
646          *(dst++) = *(src);
647      }
648      break;
649
650    default:
651      assert(0);
652  }
653  field->finishEditing();
654
655  // free resources
656  delete [] tmpArray;
657}
658
659
660static void postProcessTriangleSeparation(SoIndexedShape *shape, osg::PrimitiveSet::Mode primType,
661                                          osg::Geometry::AttributeBinding normalBinding,
662                                          osg::Geometry::AttributeBinding colorBinding)
663{
664  // compute runLengths
665  SbIntList runLengths;
666  const int32_t *a = shape->coordIndex.getValues(0);
667  int origNum = shape->coordIndex.getNum();
668  int l = 0;
669  for (int i=0; i<origNum; i++,a++) {
670    if (*a == -1) {
671      runLengths.append(l);
672      l = 0;
673    } else
674      l++;
675  }
676  if (l != 0) // append final l if field is not finished by -1
677    runLengths.append(l);
678
679  postProcessField(runLengths, primType, &shape->coordIndex,        osg::Geometry::BIND_PER_VERTEX);
680  postProcessField(runLengths, primType, &shape->normalIndex,       normalBinding);
681  postProcessField(runLengths, primType, &shape->materialIndex,     colorBinding);
682  bool notUseTexCoords = shape->textureCoordIndex.getNum()==0 ||
683                         (shape->textureCoordIndex.getNum()==1 && shape->textureCoordIndex[0] == -1);
684  if (!notUseTexCoords)
685    postProcessField(runLengths, primType, &shape->textureCoordIndex, osg::Geometry::BIND_PER_VERTEX);
686
687}
688
689
690static SoMaterialBinding* createMaterialBinding(const osg::Geometry *g, bool isMaterialIndexed)
691{
692  SoMaterialBinding *materialBinding = new SoMaterialBinding;
693  switch (g->getColorBinding()) {
694  case osg::Geometry::BIND_OFF: // OFF means use material from state set (if any) for whole geometry
695  case osg::Geometry::BIND_OVERALL:
696  case osg::Geometry::BIND_PER_PRIMITIVE_SET: materialBinding->value = SoMaterialBinding::OVERALL; break;
697  case osg::Geometry::BIND_PER_PRIMITIVE:     materialBinding->value = (isMaterialIndexed) ? SoMaterialBinding::PER_PART_INDEXED   : SoMaterialBinding::PER_PART; break;
698  case osg::Geometry::BIND_PER_VERTEX:        materialBinding->value = (isMaterialIndexed) ? SoMaterialBinding::PER_VERTEX_INDEXED : SoMaterialBinding::PER_VERTEX; break;
699  default: assert(0);
700  }
701  return materialBinding;
702}
703
704
705static SoNormalBinding* createNormalBinding(const osg::Geometry *g, bool areNormalsIndexed)
706{
707  // Convert normal binding
708  SoNormalBinding *normalBinding = new SoNormalBinding;
709  switch (g->getNormalBinding()) {
710  case osg::Geometry::BIND_OFF: // FIXME: what to do with BIND_OFF value?
711  case osg::Geometry::BIND_OVERALL:
712  case osg::Geometry::BIND_PER_PRIMITIVE_SET: normalBinding->value = SoNormalBinding::OVERALL; break;
713  case osg::Geometry::BIND_PER_PRIMITIVE:     normalBinding->value = (areNormalsIndexed) ? SoNormalBinding::PER_PART_INDEXED   : SoNormalBinding::PER_PART; break;
714  case osg::Geometry::BIND_PER_VERTEX:        normalBinding->value = (areNormalsIndexed) ? SoNormalBinding::PER_VERTEX_INDEXED : SoNormalBinding::PER_VERTEX; break;
715  default: assert(0);
716  }
717  return normalBinding;
718}
719
720
721static SoTextureCoordinateBinding* createTexCoordBinding(SbBool useIndexing)
722{
723  SoTextureCoordinateBinding *b = new SoTextureCoordinateBinding;
724  b->value.setValue(useIndexing ? SoTextureCoordinateBinding::PER_VERTEX_INDEXED :
725                    SoTextureCoordinateBinding::PER_VERTEX);
726  return b;
727}
728
729
730static SoTexture2::Model convertTexEnvMode(osg::TexEnv::Mode osgMode, bool useIvExtensions)
731{
732  switch (osgMode) {
733  case GL_MODULATE: return SoTexture2::MODULATE;
734  case GL_REPLACEreturn (SoTexture2::Model)(useIvExtensions ? GL_REPLACE : GL_MODULATE);
735  case GL_BLEND:    return SoTexture2::BLEND;
736  case GL_DECAL:    return SoTexture2::DECAL;
737  default: assert(0); return SoTexture2::MODULATE;
738  }
739}
740
741
742
743static SoTexture2::Wrap convertTextureWrap(osg::Texture::WrapMode osgWrap)
744{
745  // notes on support of CLAMP_TO_BORDER, CLAMP_TO_EDGE, and MIRRORED_REPEAT:
746  // original SGI Inventor: no
747  // Coin: no (until current version Coin 2.5.0b3)
748  // TGS Inventor: introduced in TGS Inventor 5.0 (available in SoTexture class)
749
750  // note: Coin (since 2.0) uses CLAMP_TO_EDGE for rendering if SoTexture2::CLAMP is specified.
751
752  switch (osgWrap) {
753    case osg::Texture::CLAMP:
754    case osg::Texture::CLAMP_TO_BORDER:
755    case osg::Texture::CLAMP_TO_EDGE: return SoTexture2::CLAMP;
756    case osg::Texture::REPEAT:
757    case osg::Texture::MIRROR: return SoTexture2::REPEAT;
758    default: assert(0); return SoTexture2::REPEAT;
759  }
760}
761
762
763static void setSoTransform(SoTransform *tr, const osg::Vec3 &translation, const osg::Quat &rotation,
764                           const osg::Vec3 &scale = osg::Vec3(1.,1.,1.))
765{
766  tr->translation.setValue(translation.ptr());
767  tr->rotation.setValue(rotation.x(), rotation.y(), rotation.z(), rotation.w());
768  tr->scaleFactor.setValue(scale.ptr());
769  //tr->scaleCenter.setValue(osg::Vec3f(node.getPivotPoint())); <- testing required on this line
770}
771
772
773static bool updateMode(bool &flag, const osg::StateAttribute::GLModeValue value)
774{
775  if (value & osg::StateAttribute::INHERIT)  return flag;
776  else  return (flag = (value & osg::StateAttribute::ON));
777}
778
779
780ConvertToInventor::InventorState* ConvertToInventor::createInventorState(const osg::StateSet *ss)
781{
782  // Push on stack
783  const InventorState *ivPrevState = &ivStack.top();
784  ivStack.push(*ivPrevState);
785  InventorState *ivState = &ivStack.top();
786
787  // Inventor graph
788  ivState->ivHead = new SoSeparator;
789  ivPrevState->ivHead->addChild(ivState->ivHead);
790
791  if (ss) {
792
793    //
794    // Lighting
795    //
796
797    // enable/disable lighting
798    updateMode(ivState->osgLighting, ss->getMode(GL_LIGHTING));
799    if (ivState->osgLighting != ivPrevState->osgLighting) {
800      SoLightModel *lm = new SoLightModel;
801      lm->model = (ivState->osgLighting) ? SoLightModel::PHONG : SoLightModel::BASE_COLOR;
802      ivState->ivHead->addChild(lm);
803    }
804
805    // two-sided lighting
806    const osg::LightModel *osgLM = dynamic_cast<const osg::LightModel*>(ss->getAttribute(osg::StateAttribute::LIGHTMODEL));
807    if (osgLM)
808      ivState->osgTwoSided = osgLM->getTwoSided();
809
810    // front face
811    const osg::FrontFace *osgFF = dynamic_cast<const osg::FrontFace*>(ss->getAttribute(osg::StateAttribute::FRONTFACE));
812    if (osgFF)
813      ivState->osgFrontFace = osgFF->getMode();
814
815    // face culling
816    updateMode(ivState->osgCullFaceEnabled, ss->getMode(GL_CULL_FACE));
817    const osg::CullFace *osgCF = dynamic_cast<const osg::CullFace*>(ss->getAttribute(osg::StateAttribute::CULLFACE));
818    if (osgCF)
819      ivState->osgCullFace = osgCF->getMode();
820
821    // detect state change
822    if (ivState->osgTwoSided != ivPrevState->osgTwoSided ||
823        ivState->osgFrontFace != ivPrevState->osgFrontFace ||
824        ivState->osgCullFaceEnabled != ivPrevState->osgCullFaceEnabled ||
825        ivState->osgCullFace != ivPrevState->osgCullFace) {
826
827      // new SoShapeHints
828      SoShapeHints *sh = new SoShapeHints;
829      if (ivState->osgTwoSided) {
830        // warn if face culling is on
831        if (ivState->osgCullFaceEnabled)
832          OSG_WARN << "IvWriter: Using face culling and two-sided lighting together! "
833                                    "Ignoring face culling." << std::endl;
834
835        // set two-sided lighting and backface culling off
836        sh->vertexOrdering = ivState->osgFrontFace==osg::FrontFace::COUNTER_CLOCKWISE ?
837                             SoShapeHints::COUNTERCLOCKWISE : SoShapeHints::CLOCKWISE;
838        sh->shapeType = SoShapeHints::UNKNOWN_SHAPE_TYPE;
839      }
840      else {
841        // set one-sided lighting and backface optionally
842        if (ivState->osgCullFaceEnabled) {
843
844          // determine vertex ordering
845          bool ccw = ivState->osgFrontFace==osg::FrontFace::COUNTER_CLOCKWISE;
846          if (ivState->osgCullFace != osg::CullFace::BACK)  ccw = !ccw;
847
848          if (ccw)
849            // Warn if culling the lit faces while rendering unlit faces.
850            // Inventor does not support this setup and it lits the unculled faces only.
851            OSG_WARN << "IvWriter: Culling was set in a way that one-sided lighting will lit the culled sides of faces. "
852                                      "Using lighting on correct faces." << std::endl;
853
854          // face culling on
855          sh->vertexOrdering = ccw ? SoShapeHints::COUNTERCLOCKWISE : SoShapeHints::CLOCKWISE;
856          sh->shapeType = SoShapeHints::SOLID;
857        }
858        else
859          // no face culling
860          sh->shapeType = SoShapeHints::UNKNOWN_SHAPE_TYPE;
861      }
862      ivState->ivHead->addChild(sh);
863    }
864
865    //
866    // Texturing
867    //
868    // FIXME: handle 1D and 3D textures
869
870    // get OSG state
871    ivState->osgTexture = dynamic_cast<const osg::Texture*>(ss->getTextureAttribute(0, osg::StateAttribute::TEXTURE));
872    ivState->osgTexEnv = dynamic_cast<const osg::TexEnv*>(ss->getTextureAttribute(0, osg::StateAttribute::TEXENV));
873    updateMode(ivState->osgTexture2Enabled, ss->getTextureMode(0, GL_TEXTURE_2D));
874
875    // detect state changes
876    if (ivState->osgTexture2Enabled != ivPrevState->osgTexture2Enabled ||
877        ivState->osgTexture != ivPrevState->osgTexture ||
878        ivState->osgTexEnv != ivPrevState->osgTexEnv) {
879
880      if (!ivState->osgTexture2Enabled ||
881          ivState->osgTexture==NULL || ivState->osgTexture->getImage(0)==NULL)
882
883        // empty texture disables texturing
884        ivState->ivTexture = new SoTexture2;
885
886      else {
887
888        // reuse texture if possible
889        ivState->ivTexture = ivTexturesMap[ivState->osgTexture][ivState->osgTexEnv];
890
891        // if nothing for reusing, create new
892        if (!ivState->ivTexture) {
893
894          // create texture
895          ivState->ivTexture = new SoTexture2;
896          ivTexturesMap[ivState->osgTexture][ivState->osgTexEnv] = ivState->ivTexture;
897
898          // texture file name
899          const std::string &textureName = ivState->osgTexture->getImage(0)->getFileName();
900          ivState->ivTexture->filename.setValue(textureName.c_str()); // FIXME: handle inlined texture data in the files
901
902          // wrap
903          ivState->ivTexture->wrapS.setValue(convertTextureWrap(
904                                             ivState->osgTexture->getWrap(osg::Texture::WRAP_S)));
905          ivState->ivTexture->wrapT.setValue(convertTextureWrap(
906                                             ivState->osgTexture->getWrap(osg::Texture::WRAP_T)));
907
908          // texture environment
909          if (ivState->osgTexEnv) {
910            ivState->ivTexture->model.setValue(convertTexEnvMode(
911                                               ivState->osgTexEnv->getMode(), useIvExtensions));
912            osg::Vec4 color = ivState->osgTexEnv->getColor();
913            ivState->ivTexture->blendColor.setValue(color.r(), color.g(), color.b());
914          }
915
916          // notes on support of borderColor and borderWidth:
917          // original SGI Inventor: no
918          // Coin: no (until current version 2.5.0b3)
919          // TGS Inventor: introduced in version 5.0 (as SoTexture::borderColor)
920
921          // FIXME: implement support for texture filtering
922        }
923      }
924    }
925
926    // Texture coordinate generation
927    updateMode(ivState->osgTexGenS, ss->getTextureMode(0, GL_TEXTURE_GEN_S));
928    updateMode(ivState->osgTexGenT, ss->getTextureMode(0, GL_TEXTURE_GEN_T));
929    ivState->osgTexGen = dynamic_cast<const osg::TexGen*>(ss->getTextureAttribute(0, osg::StateAttribute::TEXGEN));
930
931    // Material parameters
932    const osg::Material *osgMaterial = dynamic_cast<const osg::Material*>(ss->getAttribute(osg::StateAttribute::MATERIAL));
933    if (osgMaterial)
934      ivState->osgMaterial = osgMaterial;
935
936    if (ivState->osgMaterial != ivPrevState->osgMaterial) {
937
938      ivState->ivMaterial = new SoMaterial;
939      assert(ivState->osgMaterial);
940
941      // Warn if using two side materials
942      // FIXME: The geometry can be probably doubled, or some estimation can be made
943      // whether only front or back faces are used.
944      if (ivState->osgMaterial->getAmbientFrontAndBack() == false ||
945          ivState->osgMaterial->getDiffuseFrontAndBack() == false ||
946          ivState->osgMaterial->getSpecularFrontAndBack() == false ||
947          ivState->osgMaterial->getEmissionFrontAndBack() == false ||
948          ivState->osgMaterial->getShininessFrontAndBack() == false)
949      {
950        OSG_WARN << "IvWriter: Model contains different materials for front and "
951                                  "back faces. This is not handled properly. Using front material only." << std::endl;
952      }
953
954      // Convert colors
955      // OSG represents colors by: Vec3, Vec4,Vec4ub
956      // Inventor by: uint32 (RGBA, by SoPackedColor), SbColor (Vec3f, by SoMaterial and SoBaseColor)
957      // note: Inventor can use DIFFUSE component inside a shape only. Material is set for whole shape.
958      // Although SoMaterial is used only, SoPackedColor may bring some possibilities on per-vertex
959      // alpha and SoBaseColor may be useful on pre-lit scene.
960      if (ivState->osgMaterial->getColorMode() != osg::Material::DIFFUSE &&
961          ivState->osgMaterial->getColorMode() != osg::Material::OFF)
962      {
963
964        if (ivState->osgMaterial->getColorMode() == osg::Material::AMBIENT_AND_DIFFUSE)
965        {
966            OSG_WARN << "IvWriter: The model is using AMBIENT_AND_DIFFUSE material "
967                                    "mode while Inventor supports DIFFUSE mode only. "
968                                    "The model colors may not much exactly." << std::endl;
969        }
970        else
971        {
972            OSG_WARN << "IvWriter: The model is not using DIFFUSE material mode and "
973                                    "Inventor supports DIFFUSE mode only. "
974                                    "The model colors may not be correct." << std::endl;
975        }
976      }
977
978      // Convert material components
979      // FIXME: Transparency can be specified for each component in OSG
980      // and just globally in Inventor.
981      // Solutions? It can be averaged or just diffuse can be used.
982      ((SoMaterial*)ivState->ivMaterial)->ambientColor.setValue(osgMaterial->getAmbient(
983        osgMaterial->getAmbientFrontAndBack()   ? osg::Material::FRONT_AND_BACK : osg::Material::FRONT).ptr());
984      ((SoMaterial*)ivState->ivMaterial)->diffuseColor.setValue(osgMaterial->getDiffuse(
985        osgMaterial->getDiffuseFrontAndBack()   ? osg::Material::FRONT_AND_BACK : osg::Material::FRONT).ptr());
986      ((SoMaterial*)ivState->ivMaterial)->specularColor.setValue(osgMaterial->getSpecular(
987        osgMaterial->getSpecularFrontAndBack()  ? osg::Material::FRONT_AND_BACK : osg::Material::FRONT).ptr());
988      ((SoMaterial*)ivState->ivMaterial)->emissiveColor.setValue(osgMaterial->getEmission(
989        osgMaterial->getEmissionFrontAndBack()  ? osg::Material::FRONT_AND_BACK : osg::Material::FRONT).ptr());
990      ((SoMaterial*)ivState->ivMaterial)->shininess.setValue(osgMaterial->getShininess(
991        osgMaterial->getShininessFrontAndBack() ? osg::Material::FRONT_AND_BACK : osg::Material::FRONT));
992      ((SoMaterial*)ivState->ivMaterial)->transparency.setValue(1.f - osgMaterial->getDiffuse(
993        osgMaterial->getDiffuseFrontAndBack()   ? osg::Material::FRONT_AND_BACK : osg::Material::FRONT).a());
994    }
995
996    // note on "headlight":
997    // OSG is using HEADLIGHT or SKY_LIGHT. In both cases it sets these defaults:
998    // osg::LightModel::ambientIntensity(0.1, 0.1, 0.1, 1.0);
999    // osg::Light::num(0)
1000    // osg::Light::ambient(0,0,0,1)
1001    // osg::Light::diffuse(0.8,0.8,0.8, 1)
1002    // osg::Light::specular(1,1,1,1)
1003    //
1004    // Inventor uses different settings:
1005    // SoEnvironment::ambientIntensity(0.2)
1006    // SoEnvironment::ambientColor(1,1,1)
1007    // SoDirectionalLight::intensity(1)
1008    // SoDirectionalLight::color(1,1,1)
1009    //
1010    // note on Inventor light handling:
1011    // ambient is set to 0,0,0,1
1012    // diffuse to color*intensity
1013    // specular to color*intensity
1014
1015
1016  #ifdef __COIN__
1017    //
1018    // Handle transparency
1019    //
1020    // OSG supports GL_BLEND and GL_ALPHA_TEST
1021    // Related classes: BlendFunc, BlendEquation, BlendColor, AlphaFunc
1022    //
1023    // Inventor is more difficult and not so robust. According to Inventor 2.1 standard,
1024    // just SoMaterial::transparency, SoTexture2 with alpha channel carry transparency information
1025    // that is controlled by SoGLRenderAction::transparency type that is set to SCREEN_DOOR by default
1026    // (dither pattern). So, if the user does not select better transparency type, there is no
1027    // possiblity to control transparency type from file format.
1028    //
1029    // However, SoTransparencyType node was introduced to overcome this historical limitation
1030    // because transparency was performance expensive long time ago.
1031    // Support by different Inventor branches:
1032    //
1033    // SGI Inventor: no
1034    // Coin: since 2.0
1035    // TGS Inventor: since 5.0
1036    //
1037    // Alpha test was introduced in TGS 4.0, but as SoGLRenderArea::setAlphaTest. So, no direct
1038    // control in the file format.
1039    //
1040    // Conclusion:
1041    // - Alpha test is not supported and all pixels will be drawn
1042    // - Blending - current strategy is following:
1043    //     ADD x BLEND - ADD is used if destination-blending-factor is GL_ONE
1044    //     DELAYED rendering is used if transparency bin is used by OSG
1045    //     SORTED_OBJECT is used if ...
1046    //
1047
1048    updateMode(ivState->osgBlendEnabled, ss->getMode(GL_BLEND));
1049    ivState->osgBlendFunc = dynamic_cast<const osg::BlendFunc*>(ss->getAttribute(osg::StateAttribute::BLENDFUNC));
1050
1051    if (useIvExtensions)
1052      if (ivState->osgBlendEnabled != ivPrevState->osgBlendEnabled ||
1053          ivState->osgBlendFunc != ivPrevState->osgBlendFunc ||
1054          (ivState->osgBlendFunc && ivPrevState->osgBlendFunc &&
1055          ivState->osgBlendFunc->getDestinationRGB() != ivPrevState->osgBlendFunc->getDestinationRGB())) {
1056
1057        const SoTransparencyType::Type transparencyTable[8] = {
1058          SoTransparencyType::BLEND,         SoTransparencyType::ADD,
1059          SoTransparencyType::DELAYED_BLEND, SoTransparencyType::DELAYED_ADD,
1060          // FIXME: add sorted modes and test previous four
1061        };
1062
1063        int index = 0;
1064        if (!ivState->osgBlendFunc)  index |= 0;
1065        else  index = (ivState->osgBlendFunc->getDestinationRGB() == osg::BlendFunc::ONE) ? 1 : 0;
1066        index |= (ss->getRenderingHint() == osg::StateSet::TRANSPARENT_BIN) ? 2 : 0;
1067
1068        SoTransparencyType *ivTransparencyType = new SoTransparencyType;
1069        ivTransparencyType->value = transparencyTable[index];
1070        ivState->ivHead->addChild(ivTransparencyType);
1071      }
1072  #endif
1073
1074  }
1075
1076  // ref Inventor nodes that are required when processing Drawables
1077  if (ivState->ivTexture)
1078    ivState->ivTexture->ref();
1079  if (ivState->ivMaterial)
1080    ivState->ivMaterial->ref();
1081
1082  return ivState;
1083}
1084
1085
1086void ConvertToInventor::popInventorState()
1087{
1088  InventorState *ivState = &ivStack.top();
1089
1090  // unref Inventor nodes
1091  if (ivState->ivTexture)
1092    ivState->ivTexture->unref();
1093  if (ivState->ivMaterial)
1094    ivState->ivMaterial->unref();
1095
1096  ivStack.pop();
1097}
1098
1099
1100static bool processPrimitiveSet(const osg::Geometry *g, const osg::PrimitiveSet *pset,
1101                                osg::UIntArray *drawElemIndices, bool needSeparateTriangles,
1102                                int elementsCount, int primSize, const int startIndex, int stopIndex,
1103                                int &normalIndex, int &colorIndex,
1104                                SoNode *ivCoords, SoNormal *ivNormals, SoNode *ivMaterial,
1105                                SoNode *ivTexCoords, SoNode *ivTexture, SoShape *shape,
1106                                SoSeparator *&indexedRoot, SoSeparator *&nonIndexedRoot)
1107{
1108  bool ok = true;
1109  const osg::DrawArrayLengths *drawArrayLengths =
1110    (elementsCount == -1) ? dynamic_cast<const osg::DrawArrayLengths*>(pset) : NULL;
1111
1112  int drawArrayLengthsElems = 0;
1113
1114  if (drawArrayLengths) {
1115
1116    // compute elementsCount
1117    elementsCount = 0;
1118    drawArrayLengthsElems = 0;
1119    for (osg::DrawArrayLengths::const_iterator primItr=drawArrayLengths->begin();
1120        primItr!=drawArrayLengths->end();
1121        ++primItr, drawArrayLengthsElems++)
1122      elementsCount += *primItr;
1123
1124    // update stopIndex
1125    stopIndex = startIndex + elementsCount;
1126  }
1127
1128  // NonIndexed data for nonIndexed shapes
1129  SoNode *nonIndexedCoords = NULL;
1130  SoNode *nonIndexedTexCoords = NULL;
1131  SoNormal *nonIndexedNormals = NULL;
1132  SoNode *nonIndexedMaterial = NULL;
1133
1134  // Normal indexing
1135  int normalStart = g->getNormalBinding() == osg::Geometry::BIND_PER_VERTEX ? startIndex : normalIndex;
1136  int numNormalsUsed = 0;
1137  switch (g->getNormalBinding()) {
1138  case osg::Geometry::BIND_OFF: // FIXME: what is meaning of OFF value?
1139  case osg::Geometry::BIND_OVERALL:           numNormalsUsed = 0; break;
1140  case osg::Geometry::BIND_PER_PRIMITIVE_SET: numNormalsUsed = 1; break;
1141  case osg::Geometry::BIND_PER_PRIMITIVE:     numNormalsUsed = primSize!=0 ? (stopIndex-startIndex)/primSize :
1142                                                (drawArrayLengths ? drawArrayLengths->size() : 1); break;
1143  case osg::Geometry::BIND_PER_VERTEX:        numNormalsUsed = stopIndex-startIndex; break;
1144  }
1145  normalIndex += numNormalsUsed;
1146
1147  // Color indexing
1148  int colorStart = g->getColorBinding() == osg::Geometry::BIND_PER_VERTEX ? startIndex : colorIndex;
1149  int numColorsUsed = 0;
1150  switch (g->getColorBinding()) {
1151  case osg::Geometry::BIND_OFF:
1152  case osg::Geometry::BIND_OVERALL:           numColorsUsed = 0; break;
1153  case osg::Geometry::BIND_PER_PRIMITIVE_SET: numColorsUsed = 1; break;
1154  case osg::Geometry::BIND_PER_PRIMITIVE:     numColorsUsed = primSize!=0 ? (stopIndex-startIndex)/primSize :
1155                                                (drawArrayLengths ? drawArrayLengths->size() : 1); break;
1156  case osg::Geometry::BIND_PER_VERTEX:        numColorsUsed = stopIndex-startIndex; break;
1157  }
1158  colorIndex += numColorsUsed;
1159
1160  if (shape->isOfType(SoIndexedShape::getClassTypeId())) {
1161
1162    // Convert to SoIndexedShape
1163    processIndices(g->getVertexIndices(), drawElemIndices, ((SoIndexedShape*)shape)->coordIndex,
1164                   startIndex, stopIndex, primSize);
1165
1166    if (ivNormals)
1167      processIndices(g->getNormalIndices(), drawElemIndices, ((SoIndexedShape*)shape)->normalIndex,
1168                     normalStart, normalStart+(numNormalsUsed==0 ? 1 : numNormalsUsed),
1169                     g->getNormalBinding()==osg::Geometry::BIND_PER_VERTEX ? primSize : 0);
1170
1171    if (ivMaterial)
1172      processIndices(g->getColorIndices(), drawElemIndices, ((SoIndexedShape*)shape)->materialIndex,
1173                     colorStart, colorStart+(numColorsUsed==0 ? 1 : numColorsUsed),
1174                     g->getColorBinding()==osg::Geometry::BIND_PER_VERTEX ? primSize : 0);
1175
1176    if (ivTexCoords && !ivTexCoords->isOfType(SoTextureCoordinateFunction::getClassTypeId()))
1177      processIndices(g->getTexCoordIndices(0), drawElemIndices, ((SoIndexedShape*)shape)->textureCoordIndex,
1178                     startIndex, stopIndex, primSize);
1179
1180    // Post-processing for DrawArrayLengths
1181    if (drawArrayLengths && primSize==0 && drawArrayLengths->size()>=2) {
1182
1183      postProcessDrawArrayLengths(drawArrayLengths, &((SoIndexedShape*)shape)->coordIndex);
1184
1185      if (ivNormals && g->getNormalBinding()==osg::Geometry::BIND_PER_VERTEX)
1186        postProcessDrawArrayLengths(drawArrayLengths, &((SoIndexedShape*)shape)->normalIndex);
1187
1188      if (ivMaterial && g->getColorBinding()==osg::Geometry::BIND_PER_VERTEX)
1189        postProcessDrawArrayLengths(drawArrayLengths, &((SoIndexedShape*)shape)->materialIndex);
1190
1191      if (ivTexCoords && !ivTexCoords->isOfType(SoTextureCoordinateFunction::getClassTypeId()))
1192        postProcessDrawArrayLengths(drawArrayLengths, &((SoIndexedShape*)shape)->textureCoordIndex);
1193    }
1194
1195    if (needSeparateTriangles)
1196      postProcessTriangleSeparation((SoIndexedShape*)shape, (osg::PrimitiveSet::Mode)pset->getMode(),
1197                                    g->getNormalBinding(), g->getColorBinding());
1198
1199  } else {
1200
1201    // Convert to SoNonIndexedShape
1202
1203    assert(shape->isOfType(SoNonIndexedShape::getClassTypeId()) && "Shape must be non-indexed.");
1204
1205    int i,n = stopIndex-startIndex;
1206
1207    // create alternate coordinates
1208    if (ivCoords->isOfType(SoCoordinate4::getClassTypeId()))
1209    {
1210      nonIndexedCoords = new SoCoordinate4;
1211      if (ok) {
1212        ((SoCoordinate4*)nonIndexedCoords)->point.setNum(n);
1213        ok = ivProcessArray<SbVec4f,SoMFVec4f>(g->getVertexIndices(),
1214                                             drawElemIndices,
1215                                             &((SoCoordinate4*)nonIndexedCoords)->point,
1216                                             &((SoCoordinate4*)ivCoords)->point,
1217                                             startIndex, n);
1218      }
1219    } else {
1220      nonIndexedCoords = new SoCoordinate3;
1221      if (ok) {
1222        ((SoCoordinate3*)nonIndexedCoords)->point.setNum(n);
1223        ok = ivProcessArray<SbVec3f,SoMFVec3f>(g->getVertexIndices(),
1224                                             drawElemIndices,
1225                                             &((SoCoordinate3*)nonIndexedCoords)->point,
1226                                             &((SoCoordinate3*)ivCoords)->point,
1227                                             startIndex, n);
1228      }
1229    }
1230
1231    // create alternate texture coordinates
1232    if (ivTexCoords)
1233    {
1234      if (ivTexCoords->isOfType(SoTextureCoordinate2::getClassTypeId()))
1235      {
1236        nonIndexedTexCoords = new SoTextureCoordinate2;
1237        if (ok)
1238        {
1239          ((SoTextureCoordinate2*)nonIndexedTexCoords)->point.setNum(n);
1240          ok = ivProcessArray<SbVec2f,SoMFVec2f>(g->getTexCoordIndices(0),
1241                                               drawElemIndices,
1242                                               &((SoTextureCoordinate2*)nonIndexedTexCoords)->point,
1243                                               &((SoTextureCoordinate2*)ivTexCoords)->point,
1244                                               startIndex, n);
1245        }
1246      } else
1247#ifdef __COIN__
1248      if (ivTexCoords->isOfType(SoTextureCoordinate3::getClassTypeId()))
1249      {
1250        nonIndexedTexCoords = new SoTextureCoordinate3;
1251        if (ok)
1252        {
1253          ((SoTextureCoordinate3*)nonIndexedTexCoords)->point.setNum(n);
1254          ok = ivProcessArray<SbVec3f,SoMFVec3f>(g->getTexCoordIndices(0),
1255                                               drawElemIndices,
1256                                               &((SoTextureCoordinate3*)nonIndexedTexCoords)->point,
1257                                               &((SoTextureCoordinate3*)ivCoords)->point,
1258                                               startIndex, n);
1259        }
1260      }
1261      else
1262#endif  // __COIN__
1263        nonIndexedTexCoords = ivTexCoords;
1264    }
1265
1266    // create alternate normals
1267    if (ivNormals) {
1268      nonIndexedNormals = new SoNormal;
1269      if (ok) {
1270        nonIndexedNormals->vector.setNum(numNormalsUsed==0 ? 1 : numNormalsUsed);
1271        ok = ivProcessArray<SbVec3f,SoMFVec3f>(g->getNormalIndices(),
1272                                             g->getNormalBinding()==osg::Geometry::BIND_PER_VERTEX ? drawElemIndices : NULL,
1273                                             &nonIndexedNormals->vector, &ivNormals->vector,
1274                                             normalStart, numNormalsUsed==0 ? 1 : numNormalsUsed);
1275      }
1276    }
1277
1278    // create alternate material
1279    if (ivMaterial) {
1280      SoMFColor *dstColorField;
1281      if (ivMaterial->isOfType(SoMaterial::getClassTypeId())) {
1282        nonIndexedMaterial = new SoMaterial;
1283        dstColorField = &((SoMaterial*)nonIndexedMaterial)->diffuseColor;
1284      } else {
1285        nonIndexedMaterial = new SoBaseColor;
1286        dstColorField = &((SoBaseColor*)nonIndexedMaterial)->rgb;
1287      }
1288      if (ok) {
1289        // FIXME: diffuse only?
1290        SoMFColor *srcColorField = (ivMaterial->isOfType(SoMaterial::getClassTypeId())) ?
1291                                   &((SoMaterial*)ivMaterial)->diffuseColor :
1292                                   &((SoBaseColor*)ivMaterial)->rgb;
1293        dstColorField->setNum(numColorsUsed==0 ? 1 : numColorsUsed);
1294        ok = ivProcessArray<SbColor,SoMFColor>(g->getColorIndices(),
1295                                            g->getColorBinding()==osg::Geometry::BIND_PER_VERTEX ? drawElemIndices : NULL,
1296                                            dstColorField, srcColorField,
1297                                            colorStart, numColorsUsed==0 ? 1 : numColorsUsed);
1298      }
1299    }
1300
1301    if (shape->isOfType(SoPointSet::getClassTypeId()))
1302      ((SoPointSet*)shape)->numPoints.setValue(elementsCount); else
1303
1304    if (shape->isOfType(SoLineSet::getClassTypeId())) {
1305      switch (pset->getMode()) {
1306      case GL_LINES:
1307          assert(elementsCount % 2 == 0 && "elementsCount is not multiple of 2.");
1308          n = elementsCount/2;
1309          ((SoLineSet*)shape)->numVertices.setNum(n);
1310          for (i=0; i<n; i++)
1311            ((SoLineSet*)shape)->numVertices.set1Value(i, 2);
1312          break;
1313      case GL_LINE_STRIP:
1314          if (drawArrayLengths) {
1315            ((SoLineSet*)shape)->numVertices.setNum(drawArrayLengthsElems);
1316            int i=0;
1317            for (osg::DrawArrayLengths::const_iterator primItr=drawArrayLengths->begin();
1318                primItr!=drawArrayLengths->end();
1319                ++primItr, i++)
1320              ((SoLineSet*)shape)->numVertices.set1Value(i, *primItr);
1321          } else {
1322            ((SoLineSet*)shape)->numVertices.setNum(1);
1323            ((SoLineSet*)shape)->numVertices.set1Value(0, elementsCount);
1324          }
1325          break;
1326      default:
1327          OSG_WARN << "IvWriter: NOT IMPLEMENTED" << std::endl;
1328          assert(0);
1329      }
1330    } else
1331
1332    if (shape->isOfType(SoTriangleStripSet::getClassTypeId())) {
1333      switch (pset->getMode()) {
1334      case GL_TRIANGLES:
1335          n = elementsCount/3;
1336          assert(n*3 == elementsCount && "elementsCount is not multiple of 3.");
1337          ((SoTriangleStripSet*)shape)->numVertices.setNum(n);
1338          for (i=0; i<n; i++)
1339            ((SoTriangleStripSet*)shape)->numVertices.set1Value(i, 3);
1340          break;
1341      case GL_TRIANGLE_STRIP:
1342          if (drawArrayLengths) {
1343            ((SoTriangleStripSet*)shape)->numVertices.setNum(drawArrayLengthsElems);
1344            int i=0;
1345            for (osg::DrawArrayLengths::const_iterator primItr=drawArrayLengths->begin();
1346                primItr!=drawArrayLengths->end();
1347                ++primItr, i++)
1348              ((SoTriangleStripSet*)shape)->numVertices.set1Value(i, *primItr);
1349          } else {
1350            ((SoTriangleStripSet*)shape)->numVertices.setNum(1);
1351            ((SoTriangleStripSet*)shape)->numVertices.set1Value(0, elementsCount);
1352          }
1353          break;
1354      case GL_TRIANGLE_FAN:
1355          OSG_WARN << "IvWriter: GL_TRIANGLE_FAN NOT IMPLEMENTED" << std::endl;
1356          ((SoTriangleStripSet*)shape)->numVertices.setNum(1);
1357          ((SoTriangleStripSet*)shape)->numVertices.set1Value(0, elementsCount);
1358          break;
1359      case GL_QUAD_STRIP:
1360          assert(elementsCount % 2 == 0 && "elementsCount is not multiple of 2.");
1361          if (drawArrayLengths) {
1362            ((SoTriangleStripSet*)shape)->numVertices.setNum(drawArrayLengthsElems);
1363            int i=0;
1364            for (osg::DrawArrayLengths::const_iterator primItr=drawArrayLengths->begin();
1365                primItr!=drawArrayLengths->end();
1366                ++primItr, i++)
1367              ((SoTriangleStripSet*)shape)->numVertices.set1Value(i, *primItr);
1368          } else {
1369            ((SoTriangleStripSet*)shape)->numVertices.setNum(1);
1370            ((SoTriangleStripSet*)shape)->numVertices.set1Value(0, elementsCount);
1371          }
1372          break;
1373      default:
1374          OSG_WARN << "IvWriter: NOT IMPLEMENTED" << std::endl;
1375          assert(0);
1376      }
1377    } else
1378
1379    if (shape->isOfType(SoFaceSet::getClassTypeId())) {
1380      switch (pset->getMode()) {
1381      case GL_QUADS:
1382          n = elementsCount/4;
1383          assert(n*4 == elementsCount && "elementsCount is not multiple of 4.");
1384          ((SoFaceSet*)shape)->numVertices.setNum(n);
1385          for (i=0; i<n; i++)
1386            ((SoFaceSet*)shape)->numVertices.set1Value(i, 4);
1387          break;
1388      case GL_POLYGON:
1389          if (drawArrayLengths) {
1390            ((SoFaceSet*)shape)->numVertices.setNum(drawArrayLengthsElems);
1391            int i=0;
1392            for (osg::DrawArrayLengths::const_iterator primItr=drawArrayLengths->begin();
1393                primItr!=drawArrayLengths->end();
1394                ++primItr, i++)
1395              ((SoFaceSet*)shape)->numVertices.set1Value(i, *primItr);
1396          } else {
1397            ((SoFaceSet*)shape)->numVertices.setNum(1);
1398            ((SoFaceSet*)shape)->numVertices.set1Value(0, elementsCount);
1399          }
1400          break;
1401      default:
1402          OSG_WARN << "IvWriter: NOT IMPLEMENTED" << std::endl;
1403          assert(0);
1404      }
1405    } else {
1406      OSG_WARN << "IvWriter: NOT IMPLEMENTED" << std::endl;
1407      assert(0 && "Unknown non-indexed shape type.");
1408    }
1409  }
1410
1411  // Construct graph
1412
1413  // Each osg::Drawable will have its own SoSeparator (render caching, culling, etc.)
1414  SoSeparator *sep = new SoSeparator;
1415  if (nonIndexedCoords) {
1416    assert(shape->isOfType(SoNonIndexedShape::getClassTypeId()) && "Not nonIndexed shape.");
1417
1418    if (!ok) {
1419
1420      // handle errors
1421      nonIndexedCoords->ref();
1422      nonIndexedCoords->unref();
1423      if (nonIndexedTexCoords) { nonIndexedTexCoords->ref(); nonIndexedTexCoords->unref(); }
1424      if (nonIndexedNormals) { nonIndexedNormals->ref(); nonIndexedNormals->unref(); }
1425      nonIndexedMaterial->ref();
1426      nonIndexedMaterial->unref();
1427      shape->ref();
1428      shape->unref();
1429      sep->ref();
1430      sep->unref();
1431    } else {
1432
1433      // make scene graph
1434      if (nonIndexedRoot == NULL) {
1435        nonIndexedRoot = new SoSeparator;
1436        if (ivTexture)  nonIndexedRoot->addChild(ivTexture);
1437        if (ivTexture)  nonIndexedRoot->addChild(createTexCoordBinding(FALSE));
1438        nonIndexedRoot->addChild(createMaterialBinding(g, FALSE));
1439        if (ivNormals)  nonIndexedRoot->addChild(createNormalBinding(g, FALSE));
1440      }
1441      if (nonIndexedMaterial)  sep->addChild(nonIndexedMaterial);
1442      sep->addChild(nonIndexedCoords);
1443      if (nonIndexedNormals)  sep->addChild(nonIndexedNormals);
1444      if (nonIndexedTexCoords)  sep->addChild(nonIndexedTexCoords);
1445      sep->addChild(shape);
1446      nonIndexedRoot->addChild(sep);
1447    }
1448  } else {
1449    assert(shape->isOfType(SoIndexedShape::getClassTypeId()) && "Not indexed shape.");
1450    assert(nonIndexedCoords==NULL && nonIndexedNormals==NULL && nonIndexedMaterial==NULL);
1451    if (indexedRoot == NULL) {
1452      indexedRoot = new SoSeparator;
1453      if (ivTexture)  indexedRoot->addChild(ivTexture);
1454      if (ivTexture)  indexedRoot->addChild(createTexCoordBinding(TRUE));
1455      if (ivMaterial)  indexedRoot->addChild(ivMaterial);
1456      indexedRoot->addChild(createMaterialBinding(g, TRUE));
1457      indexedRoot->addChild(ivCoords);
1458      if (ivNormals)  indexedRoot->addChild(ivNormals);
1459      if (ivNormals)  indexedRoot->addChild(createNormalBinding(g, TRUE));
1460      if (ivTexCoords)  indexedRoot->addChild(ivTexCoords);
1461    }
1462    sep->addChild(shape);
1463    indexedRoot->addChild(sep);
1464  }
1465
1466  return ok;
1467}
1468
1469
1470void ConvertToInventor::processGeometry(const osg::Geometry *g, InventorState *ivState)
1471{
1472  int normalIndex = 0;
1473  int colorIndex = 0;
1474
1475  // Inventor scene graph roots
1476  SoSeparator *indexedRoot = NULL;
1477  SoSeparator *nonIndexedRoot = NULL;
1478
1479  // Active material
1480  SoMaterial *ivStateMaterial = ivState->ivMaterial;
1481  SoNode *ivMaterial = NULL;
1482  if (ivState->osgLighting || vrml1Conversion)
1483    // SoMaterial
1484    if (g->getColorArray())
1485      if (ivStateMaterial)  ivMaterial = ivStateMaterial->copy();
1486      else  ivMaterial = new SoMaterial; // FIXME: check default values of SoMaterial and OSG lighting
1487    else
1488      if (ivStateMaterial)  ivMaterial = ivStateMaterial;
1489      else  ivMaterial = NULL;
1490  else
1491    // SoBaseColor
1492    if (g->getColorArray())
1493      if (ivStateMaterial) {
1494        ivMaterial = new SoBaseColor;
1495        ((SoBaseColor*)ivMaterial)->rgb.setValue(ivStateMaterial->diffuseColor[0]); // copy first value
1496      } else
1497        ivMaterial = new SoBaseColor; // FIXME: check default values of SoBaseColor and OSG pre-lit scene
1498    else
1499      if (ivStateMaterial) {
1500        ivMaterial = new SoBaseColor;
1501        ((SoBaseColor*)ivMaterial)->rgb.setValue(ivStateMaterial->diffuseColor[0]); // copy first value
1502      } else
1503        ivMaterial = NULL;
1504
1505  // Convert color array into the SoMaterial
1506  if (g->getColorArray()) {
1507    assert(ivMaterial);
1508
1509    // Choose correct color field
1510    SoMFColor *colorField;
1511    if (ivMaterial->isOfType(SoMaterial::getClassTypeId())) {
1512      if (vrml1Conversion && ivState->osgLighting==false) {
1513
1514        // special case of pre-lit VRML1 scene
1515        ((SoMaterial*)ivMaterial)->ambientColor.setValue(0.f,0.f,0.f);
1516        ((SoMaterial*)ivMaterial)->diffuseColor.setValue(0.f,0.f,0.f);
1517        ((SoMaterial*)ivMaterial)->specularColor.setValue(0.f,0.f,0.f);
1518        colorField = &((SoMaterial*)ivMaterial)->emissiveColor;
1519      } else
1520        // regular diffuse color
1521        colorField = &((SoMaterial*)ivMaterial)->diffuseColor;
1522    } else
1523      // Using of SoBaseColor
1524      colorField = &((SoBaseColor*)ivMaterial)->rgb;
1525
1526
1527    // Color array with material
1528    if (ivState->osgMaterial == NULL ||
1529        ivState->osgMaterial->getColorMode() == osg::Material::DIFFUSE ||
1530        ivState->osgMaterial->getColorMode() == osg::Material::AMBIENT_AND_DIFFUSE)
1531      osgArray2ivMField(g->getColorArray(), *colorField);
1532    else; // FIXME: implement some workaround for non-diffuse cases?
1533          // note: Warning was already shown in createInventorState().
1534          // note2: There is no effect to convert SoMaterial::[ambient|specular|emissive]color
1535          // here because Inventor does not set them per-vertex (performance reasons). See
1536          // Inventor documentation for more details.
1537  }
1538
1539
1540  // Convert coordinates
1541  // OSG represents coordinates by: Vec2, Vec3, Vec4
1542  // Inventor by: SbVec3f, SbVec4f
1543  SoNode *coords;
1544  if (g->getVertexArray()->getDataSize() == 4) {
1545    coords = new SoCoordinate4;
1546    osgArray2ivMField(g->getVertexArray(), ((SoCoordinate4*)coords)->point);
1547  } else {
1548    coords = new SoCoordinate3;
1549    osgArray2ivMField(g->getVertexArray(), ((SoCoordinate3*)coords)->point);
1550  }
1551  coords->ref();
1552
1553  // Convert texture coordinates
1554  SoNode *texCoords = NULL;
1555  if (ivState->ivTexture) {
1556    if (ivState->osgTexGenS && ivState->osgTexGenT &&
1557        ivState->osgTexGen && ivState->osgTexGen->getMode()==osg::TexGen::SPHERE_MAP)
1558      texCoords = new SoTextureCoordinateEnvironment;
1559    else
1560    if (g->getTexCoordArray(0)) {
1561      if (g->getTexCoordArray(0)->getDataSize() <= 2) {
1562        texCoords = new SoTextureCoordinate2;
1563        osgArray2ivMField(g->getTexCoordArray(0), ((SoTextureCoordinate2*)texCoords)->point);
1564      }
1565#ifdef __COIN__
1566      else {
1567        texCoords = new SoTextureCoordinate3;
1568        osgArray2ivMField(g->getTexCoordArray(0), ((SoTextureCoordinate3*)texCoords)->point);
1569      }
1570#endif   // __COIN__
1571    }
1572    if (texCoords)
1573      texCoords->ref();
1574  }
1575
1576  // Convert normals
1577  // OSG represents normals by: Vec3,Vec3s,Vec3b
1578  // and can handle: Vec4s,Vec4b by truncating them to three components
1579  // Inventor by: SbVec3f
1580  SoNormal *normals = NULL;
1581  if (g->getNormalArray()) {
1582    normals = new SoNormal;
1583    osgArray2ivMField(g->getNormalArray(), normals->vector);
1584    normals->ref();
1585  }
1586
1587  // Convert osg::PrimitiveSets to Inventor's SoShapes
1588  int psetIndex,numPsets = g->getNumPrimitiveSets();
1589  for (psetIndex=0; psetIndex<numPsets; psetIndex++) {
1590
1591    // Get PrimitiveSet
1592    const osg::PrimitiveSet *pset = g->getPrimitiveSet(psetIndex);
1593    osg::PrimitiveSet::Type type = pset->getType();
1594    GLenum mode = pset->getMode();
1595
1596    // Create appropriate SoShape
1597    bool useIndices = g->getVertexIndices() != NULL || vrml1Conversion;
1598    bool needSeparateTriangles = false;
1599    SoVertexShape *shape = NULL;
1600    switch (mode) {
1601      case GL_POINTS:         shape = new SoPointSet; break;
1602      case GL_LINES:
1603      case GL_LINE_STRIP:
1604      case GL_LINE_LOOP:      if (useIndices) shape = new SoIndexedLineSet;
1605                              else shape = new SoLineSet;
1606                              break;
1607      case GL_TRIANGLES:
1608      case GL_TRIANGLE_STRIP:
1609      case GL_QUAD_STRIP:     if (useIndices)
1610                                if (vrml1Conversion) {
1611                                  shape = new SoIndexedFaceSet;
1612                                  needSeparateTriangles = true;
1613                                } else
1614                                  shape = new SoIndexedTriangleStripSet;
1615                              else
1616                                shape = new SoTriangleStripSet;
1617                              break;
1618      case GL_TRIANGLE_FAN:   needSeparateTriangles = true;
1619                              shape = (vrml1Conversion) ? (SoVertexShape*)new SoIndexedFaceSet :
1620                                                          new SoIndexedTriangleStripSet;
1621                              break;
1622      case GL_QUADS:
1623      case GL_POLYGON:        if (useIndices) shape = new SoIndexedFaceSet;
1624                              else shape = new SoFaceSet;
1625                              break;
1626      default: assert(0);
1627    }
1628
1629    // Size of single geometric primitive
1630    int primSize;
1631    switch (mode) {
1632    case GL_LINES:          primSize = 2; break;
1633    case GL_TRIANGLES:      primSize = 3; break;
1634    case GL_QUADS:          primSize = 4; break;
1635    default: primSize = 0;
1636    };
1637
1638
1639    bool ok = true;
1640
1641    switch (type) {
1642
1643      case osg::PrimitiveSet::DrawArraysPrimitiveType:
1644      {
1645        const osg::DrawArrays *drawArrays = dynamic_cast<const osg::DrawArrays*>(pset);
1646
1647        int startIndex = drawArrays->getFirst();
1648        int stopIndex = startIndex + drawArrays->getCount();
1649
1650        // FIXME: Am I using startIndex for all bundles that are PER_VERTEX?
1651        ok = processPrimitiveSet(g, pset, NULL, needSeparateTriangles,
1652                                  drawArrays->getCount(), primSize,
1653                                  startIndex, stopIndex, normalIndex, colorIndex,
1654                                  coords, normals, ivMaterial, texCoords,
1655                                  ivState->ivTexture, shape, indexedRoot, nonIndexedRoot);
1656        if (!ok)
1657        {
1658            OSG_WARN<<"Inventor plugin, ConvertToInventor processPrimitiveSet() failed."<<std::endl;
1659        }
1660        break;
1661      }
1662
1663      case osg::PrimitiveSet::DrawArrayLengthsPrimitiveType:
1664      {
1665        const osg::DrawArrayLengths *drawArrayLengths =
1666          dynamic_cast<const osg::DrawArrayLengths*>(pset);
1667
1668        int startIndex = drawArrayLengths->getFirst();
1669
1670        ok = processPrimitiveSet(g, pset, NULL, needSeparateTriangles,
1671                                  -1, primSize, startIndex, -1, normalIndex, colorIndex,
1672                                  coords, normals, ivMaterial, texCoords,
1673                                  ivState->ivTexture, shape, indexedRoot, nonIndexedRoot);
1674        if (!ok)
1675        {
1676            OSG_WARN<<"Inventor plugin, ConvertToInventor processPrimitiveSet() failed."<<std::endl;
1677        }
1678
1679        break;
1680      }
1681
1682      case osg::PrimitiveSet::DrawElementsUBytePrimitiveType:
1683      case osg::PrimitiveSet::DrawElementsUShortPrimitiveType:
1684      case osg::PrimitiveSet::DrawElementsUIntPrimitiveType:
1685      {
1686        osg::ref_ptr<osg::UIntArray> drawElemIndices = new osg::UIntArray;
1687
1688        switch (type) {
1689        case osg::PrimitiveSet::DrawElementsUBytePrimitiveType:
1690          {
1691            const osg::DrawElementsUByte *drawElements =
1692              dynamic_cast<const osg::DrawElementsUByte*>(pset);
1693            for(osg::DrawElementsUByte::const_iterator primItr = drawElements->begin();
1694                primItr!=drawElements->end();
1695                ++primItr)
1696              drawElemIndices->push_back(*primItr);
1697            break;
1698          }
1699        case osg::PrimitiveSet::DrawElementsUShortPrimitiveType:
1700          {
1701            const osg::DrawElementsUShort *drawElements =
1702              dynamic_cast<const osg::DrawElementsUShort*>(pset);
1703            for(osg::DrawElementsUShort::const_iterator primItr = drawElements->begin();
1704                primItr!=drawElements->end();
1705                ++primItr)
1706              drawElemIndices->push_back(*primItr);
1707            break;
1708          }
1709        case osg::PrimitiveSet::DrawElementsUIntPrimitiveType:
1710          {
1711            const osg::DrawElementsUInt *drawElements =
1712              dynamic_cast<const osg::DrawElementsUInt*>(pset);
1713            for(osg::DrawElementsUInt::const_iterator primItr = drawElements->begin();
1714                primItr!=drawElements->end();
1715                ++primItr)
1716              drawElemIndices->push_back(*primItr);
1717            break;
1718          }
1719        default: assert(0);
1720        }
1721
1722        ok = processPrimitiveSet(g, pset, drawElemIndices.get(), needSeparateTriangles,
1723                                  drawElemIndices->getNumElements(), primSize,
1724                                  0, drawElemIndices->getNumElements(), normalIndex, colorIndex,
1725                                  coords, normals, ivMaterial, texCoords,
1726                                  ivState->ivTexture, shape, indexedRoot, nonIndexedRoot);
1727        if (!ok)
1728        {
1729            OSG_WARN<<"Inventor plugin, ConvertToInventor processPrimitiveSet() failed."<<std::endl;
1730        }
1731        break;
1732      }
1733
1734      default:
1735        OSG_WARN << "IvWriter: NOT IMPLEMENTED" << std::endl;
1736    }
1737  }
1738
1739  if (indexedRoot)  ivState->ivHead->addChild(indexedRoot);
1740  if (nonIndexedRoot)  ivState->ivHead->addChild(nonIndexedRoot);
1741
1742  coords->unref();
1743  if (texCoords)  texCoords->unref();
1744  if (normals)  normals->unref();
1745}
1746
1747
1748void ConvertToInventor::processShapeDrawable(const osg::ShapeDrawable *d, InventorState *ivState)
1749{
1750  // visitor for converting ShapeDrawables
1751  class MyShapeVisitor : public osg::ConstShapeVisitor {
1752  public:
1753    void processNode(SoNode *ivNode, const osg::Vec3& center, osg::Quat rotation,
1754                      SoGroup *root) {
1755      // convert rotation
1756      rotation = osg::Quat(-M_PI_2, osg::Vec3(0.,1.,0.)) * osg::Quat(M_PI_2, osg::Vec3(1.,0.,0.)) * rotation;
1757
1758      if (center.length2()==0. && rotation.zeroRotation() && ivState->ivTexture==NULL)
1759
1760        // optimized handling of single node
1761        root->addChild(ivNode);
1762
1763      else {
1764        SoSeparator *root2 = new SoSeparator;
1765
1766        // handle transformation
1767        if (center.length2()!=0. || !rotation.zeroRotation()) {
1768          SoTransform *ivTransform = new SoTransform;
1769          setSoTransform(ivTransform, center, rotation);
1770          root2->addChild(ivTransform);
1771        }
1772
1773        // handle texture
1774        if (ivState->ivTexture)
1775          root2->addChild(ivState->ivTexture);
1776
1777        // build graph
1778        root2->addChild(ivNode);
1779        root->addChild(root2);
1780      }
1781    }
1782
1783    virtual void apply(const osg::Sphere &s) {
1784      SoSphere *ivSphere = new SoSphere;
1785      ivSphere->radius.setValue(s.getRadius());
1786      processNode(ivSphere, s.getCenter(), osg::Quat(0., osg::Vec3(1.,0.,0.)), ivState->ivHead);
1787    }
1788    virtual void apply(const osg::Box &b) {
1789      SoCube *ivCube = new SoCube;
1790      ivCube->width  = 2 * b.getHalfLengths().y();
1791      ivCube->height = 2 * b.getHalfLengths().z();
1792      ivCube->depth  = 2 * b.getHalfLengths().x();
1793      processNode(ivCube, b.getCenter(), b.getRotation(), ivState->ivHead);
1794    }
1795    virtual void apply(const osg::Cone &c) {
1796      SoCone *ivCone = new SoCone;
1797      ivCone->bottomRadius = c.getRadius();
1798      ivCone->height = c.getHeight();
1799      osg::Vec3 newCenter(c.getCenter());
1800      newCenter.ptr()[2] -= c.getBaseOffset();
1801      processNode(ivCone, newCenter, c.getRotation(), ivState->ivHead);
1802    }
1803    virtual void apply(const osg::Cylinder &c) {
1804      SoCylinder *ivCylinder = new SoCylinder;
1805      ivCylinder->radius = c.getRadius();
1806      ivCylinder->height = c.getHeight();
1807      processNode(ivCylinder, c.getCenter(), c.getRotation(), ivState->ivHead);
1808    }
1809
1810    void warnNonSupported() {
1811      OSG_WARN << "IvWriter: Not supported ShapeDrawable found. Skipping it." << std::endl;
1812    }
1813    virtual void apply(const osg::Capsule&)        { warnNonSupported(); }
1814    virtual void apply(const osg::InfinitePlane&)  { warnNonSupported(); }
1815    virtual void apply(const osg::TriangleMesh&)   { warnNonSupported(); }
1816    virtual void apply(const osg::ConvexHull&)     { warnNonSupported(); }
1817    virtual void apply(const osg::HeightField&)    { warnNonSupported(); }
1818    virtual void apply(const osg::CompositeShape&) { warnNonSupported(); }
1819
1820    InventorState *ivState;
1821    MyShapeVisitor(InventorState *ivState) { this->ivState = ivState; }
1822  } shapeVisitor(ivState);
1823
1824  // convert ShapeDrawable
1825  const osg::Shape *shape = d->getShape();
1826  if (shape)
1827    shape->accept(shapeVisitor);
1828}
1829
1830
1831void ConvertToInventor::processDrawable(osg::Drawable *d)
1832{
1833  osg::Geometry *g = d->asGeometry(); // FIXME: other drawables have to be handled also
1834  osg::ShapeDrawable *sd;
1835
1836  // Create SoSeparator and convert StateSet for Drawable
1837  InventorState *ivDrawableState = createInventorState(d->getStateSet());
1838
1839  if (g != NULL)
1840    processGeometry(g, ivDrawableState);
1841  else
1842
1843  if ((sd = dynamic_cast<osg::ShapeDrawable*>(d)) != NULL) {
1844    processShapeDrawable(sd, ivDrawableState);
1845  }
1846  else
1847    OSG_WARN << "IvWriter: Unsupported drawable found: \"" << d->className() <<
1848                              "\". Skipping it." << std::endl;
1849
1850  // Restore state
1851  popInventorState();
1852}
1853
1854
1855void ConvertToInventor::apply(osg::Geode &node)
1856{
1857#ifdef DEBUG_IV_WRITER
1858  OSG_INFO << "IvWriter: Geode traversed" << std::endl;
1859#endif
1860
1861  // Create SoSeparator and convert StateSet for Geode
1862  /*InventorState *ivGeodeState = */createInventorState(node.getStateSet());
1863
1864  // Convert drawables
1865  const int numDrawables = node.getNumDrawables();
1866  for (int i=0; i<numDrawables; i++)
1867    processDrawable(node.getDrawable(i));
1868
1869  traverse(node);
1870
1871  // Restore state
1872  popInventorState();
1873}
1874
1875
1876void ConvertToInventor::apply(osg::Group &node)
1877{
1878#ifdef DEBUG_IV_WRITER
1879  OSG_INFO << "IvWriter: Group traversed" << std::endl;
1880#endif
1881
1882  // Create SoSeparator and convert StateSet
1883  /*InventorState *ivState = */createInventorState(node.getStateSet());
1884
1885  traverse(node);
1886
1887  popInventorState();
1888}
1889
1890
1891void ConvertToInventor::apply(osg::Billboard& node)
1892{
1893#ifdef DEBUG_IV_WRITER
1894  OSG_INFO << "IvWriter: Billboard traversed" << std::endl;
1895#endif
1896
1897#ifdef __COIN__
1898
1899  if (useIvExtensions) {
1900
1901    // Create SoSeparator and convert StateSet
1902    InventorState *ivState = createInventorState(node.getStateSet());
1903    SoGroup *root = ivState->ivHead;
1904
1905    // Process drawables
1906    const int numDrawables = node.getNumDrawables();
1907    for (int i=0; i<numDrawables; i++) {
1908
1909      SoVRMLBillboard *billboard = new SoVRMLBillboard;
1910
1911      // SoVRMLBillboard is VRML 2.0 node supported by Coin (?since 2.0?)
1912      // However, I am seeing bug in my Coin 2.4.5 so that if
1913      // SoVRMLBillboard::axisOfRotation is not 0,0,0, the billboard behaviour is strange.
1914      // As long as it is set to 0,0,0, POINT_ROT_EYE-style billboard works perfectly.
1915      // AXIAL_ROT seems not possible with the bug. And POINT_ROT_WORLD was not
1916      // investigated by me until now.
1917      // There is also billboard culling bug in Coin, so the billboards may not be
1918      // rendered properly from time to time. PCJohn-2007-09-08
1919    #if 0
1920      SbVec3f axis;
1921      switch (node.getMode()) {
1922        case osg::Billboard::POINT_ROT_EYE:   axis = SbVec3f(0.f,0.f,0.f); break;
1923        case osg::Billboard::POINT_ROT_WORLD: axis = SbVec3f(0.f,0.f,0.f); break;
1924        case osg::Billboard::AXIAL_ROT:       axis = node.getAxis().ptr(); break;
1925        default:
1926          axis = SbVec3f(0.f,0.f,0.f);
1927      };
1928      billboard->axisOfRotation.setValue(axis);
1929    #else
1930
1931      billboard->axisOfRotation.setValue(SbVec3f(0.f,0.f,0.f));
1932
1933    #endif
1934
1935      SoTranslation *translation = new SoTranslation;
1936      translation->translation.setValue(node.getPosition(i).ptr());
1937
1938      // Rotate billboard correctly (OSG->IV conversion)
1939      // Note: use SoTransform instead of SoRotation because SoRotation is not supported by VRML1.
1940      SoTransform *transform = new SoTransform;
1941      transform->rotation = SbRotation(SbVec3f(1.f,0.f,0.f), float(-M_PI_2));
1942
1943      SoSeparator *separator = new SoSeparator;
1944      separator->addChild(translation);
1945      separator->addChild(billboard);
1946      billboard->addChild(transform);
1947
1948      root->addChild(separator);
1949      ivState->ivHead = billboard;
1950
1951      processDrawable(node.getDrawable(i));
1952
1953      traverse((osg::Node&)node);
1954    }
1955
1956    popInventorState();
1957
1958  } else
1959    apply((osg::Geode&)node);
1960
1961#else
1962
1963  apply((osg::Geode&)node);
1964
1965#endif
1966}
1967
1968
1969void ConvertToInventor::apply(osg::MatrixTransform& node)
1970{
1971#ifdef DEBUG_IV_WRITER
1972  OSG_INFO << "IvWriter: MatrixTransform traversed" << std::endl;
1973#endif
1974
1975  // Convert matrix
1976  SoMatrixTransform *ivTransform = new SoMatrixTransform;
1977  SbMatrix ivMatrix;
1978  const osg::Matrix::value_type *src = node.getMatrix().ptr();
1979  float *dest = ivMatrix[0];
1980  for (int i=0; i<16; i++,dest++,src++)
1981    *dest = *src;
1982  ivTransform->matrix.setValue(ivMatrix);
1983
1984  // Create SoSeparator and convert StateSet
1985  InventorState *ivState = createInventorState(node.getStateSet());
1986  ivState->ivHead->addChild(ivTransform);
1987
1988  traverse((osg::Node&)node);
1989
1990  popInventorState();
1991}
1992
1993
1994void ConvertToInventor::apply(osg::PositionAttitudeTransform& node)
1995{
1996#ifdef DEBUG_IV_WRITER
1997  OSG_INFO << "IvWriter: PositionAttitudeTransform traversed" << std::endl;
1998#endif
1999
2000  // Convert matrix
2001  SoTransform *ivTransform = new SoTransform;
2002  setSoTransform(ivTransform, node.getPosition(), node.getAttitude(), node.getScale());
2003
2004  // Create SoSeparator and convert StateSet
2005  InventorState *ivState = createInventorState(node.getStateSet());
2006  ivState->ivHead->addChild(ivTransform);
2007
2008  traverse((osg::Node&)node);
2009
2010  popInventorState();
2011}
2012
2013
2014void ConvertToInventor::apply(osg::LOD& node)
2015{
2016#ifdef DEBUG_IV_WRITER
2017  OSG_INFO << "IvWriter: LOD traversed" << std::endl;
2018#endif
2019
2020  // Convert LOD
2021  SoGroup *ivLOD = NULL;
2022  osg::LOD::RangeMode rangeMode = node.getRangeMode();
2023  if (rangeMode == osg::LOD::DISTANCE_FROM_EYE_POINT) {
2024
2025    // use SoLOD for DISTANCE_FROM_EYE_POINT
2026    SoLOD *lod = new SoLOD;
2027
2028    // copy ranges
2029    int i,c=node.getNumRanges();
2030    for (i=0; i<c; i++)
2031       lod->range.set1Value(i, node.getMaxRange(i));
2032
2033    // set center
2034    osg::Vec3f center(node.getCenter());
2035    lod->center.setValue(center.ptr());
2036
2037    ivLOD = lod;
2038
2039  } else
2040  if (rangeMode == osg::LOD::PIXEL_SIZE_ON_SCREEN) {
2041
2042    // use SoLevelOfDetail for PIXEL_SIZE_ON_SCREEN
2043    SoLevelOfDetail *lod = new SoLevelOfDetail;
2044
2045    // copy ranges
2046    int i,c=node.getNumRanges();
2047    for (i=0; i<c; i++)
2048       lod->screenArea.set1Value(i, node.getMaxRange(i));
2049
2050    ivLOD = lod;
2051
2052  } else {
2053
2054    // undefined mode -> put warning
2055    OSG_WARN << "IvWriter: Undefined LOD::RangeMode value." << std::endl;
2056    ivLOD = new SoGroup;
2057  }
2058
2059  // Create SoSeparator and convert StateSet
2060  InventorState *ivState = createInventorState(node.getStateSet());
2061  ivState->ivHead->addChild(ivLOD);
2062  ivState->ivHead = ivLOD;
2063
2064  traverse((osg::Node&)node);
2065
2066  popInventorState();
2067}
Note: See TracBrowser for help on using the browser.