]> git.mxchange.org Git - simgear.git/blob - simgear/scene/material/TextureBuilder.cxx
#348: Missing model/texture files not reported properly
[simgear.git] / simgear / scene / material / TextureBuilder.cxx
1 // Copyright (C) 2009  Tim Moore timoore@redhat.com
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Library General Public
5 // License as published by the Free Software Foundation; either
6 // version 2 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Library General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with this program; if not, write to the Free Software
15 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
16
17 #ifdef HAVE_CONFIG_H
18 #  include <simgear_config.h>
19 #endif
20
21 #include "TextureBuilder.hxx"
22 #include "mipmap.hxx"
23
24 #include "Pass.hxx"
25
26 #include <osg/TexEnv>
27 #include <osg/TexEnvCombine>
28 #include <osg/TexGen>
29 #include <osg/Texture1D>
30 #include <osg/Texture2D>
31 #include <osg/Texture3D>
32 #include <osg/TextureRectangle>
33 #include <osg/TextureCubeMap>
34 #include <osgDB/FileUtils>
35
36 #include <boost/lexical_cast.hpp>
37 #include <boost/tuple/tuple.hpp>
38 #include <boost/tuple/tuple_comparison.hpp>
39
40 #include <simgear/scene/model/SGReaderWriterXMLOptions.hxx>
41 #include <simgear/scene/util/SGSceneFeatures.hxx>
42 #include <simgear/scene/util/StateAttributeFactory.hxx>
43 #include <simgear/math/SGMath.hxx>
44 #include <simgear/structure/OSGUtils.hxx>
45
46 #include "Noise.hxx"
47
48 namespace simgear
49 {
50 using namespace std;
51 using namespace osg;
52
53 using namespace effect;
54
55 TexEnvCombine* buildTexEnvCombine(Effect* effect,
56                                   const SGPropertyNode* envProp,
57                                   const SGReaderWriterXMLOptions* options);
58 TexGen* buildTexGen(Effect* Effect, const SGPropertyNode* tgenProp);
59
60 // Hack to force inclusion of TextureBuilder.cxx in library
61 osg::Texture* TextureBuilder::buildFromType(Effect* effect, const string& type,
62                                             const SGPropertyNode*props,
63                                             const SGReaderWriterXMLOptions*
64                                             options)
65 {
66     return EffectBuilder<Texture>::buildFromType(effect, type, props, options);
67 }
68
69 typedef boost::tuple<string, Texture::FilterMode, Texture::FilterMode,
70                      Texture::WrapMode, Texture::WrapMode, Texture::WrapMode,
71                      string, MipMapTuple> TexTuple;
72
73 EffectNameValue<TexEnv::Mode> texEnvModesInit[] =
74 {
75     {"add", TexEnv::ADD},
76     {"blend", TexEnv::BLEND},
77     {"decal", TexEnv::DECAL},
78     {"modulate", TexEnv::MODULATE},
79     {"replace", TexEnv::REPLACE}
80 };
81 EffectPropertyMap<TexEnv::Mode> texEnvModes(texEnvModesInit);
82
83 TexEnv* buildTexEnv(Effect* effect, const SGPropertyNode* prop)
84 {
85     const SGPropertyNode* modeProp = getEffectPropertyChild(effect, prop,
86                                                             "mode");
87     const SGPropertyNode* colorProp = getEffectPropertyChild(effect, prop,
88                                                              "color");
89     if (!modeProp)
90         return 0;
91     TexEnv::Mode mode = TexEnv::MODULATE;
92     findAttr(texEnvModes, modeProp, mode);
93     if (mode == TexEnv::MODULATE) {
94         return StateAttributeFactory::instance()->getStandardTexEnv();
95     }
96     TexEnv* env = new TexEnv(mode);
97     if (colorProp)
98         env->setColor(toOsg(colorProp->getValue<SGVec4d>()));
99     return env;
100 }
101
102
103 void TextureUnitBuilder::buildAttribute(Effect* effect, Pass* pass,
104                                         const SGPropertyNode* prop,
105                                         const SGReaderWriterXMLOptions* options)
106 {
107     if (!isAttributeActive(effect, prop))
108         return;
109     // Decode the texture unit
110     int unit = 0;
111     const SGPropertyNode* pUnit = prop->getChild("unit");
112     if (pUnit) {
113         unit = pUnit->getValue<int>();
114     } else {
115         const SGPropertyNode* pName = prop->getChild("name");
116         if (pName)
117             try {
118                 unit = boost::lexical_cast<int>(pName->getStringValue());
119             } catch (boost::bad_lexical_cast& lex) {
120                 SG_LOG(SG_INPUT, SG_ALERT, "can't decode name as texture unit "
121                        << lex.what());
122             }
123     }
124     const SGPropertyNode* pType = getEffectPropertyChild(effect, prop, "type");
125     string type;
126     if (!pType)
127         type = "2d";
128     else
129         type = pType->getStringValue();
130     Texture* texture = 0;
131     try {
132         texture = TextureBuilder::buildFromType(effect, type, prop,
133                                                 options);
134     }
135     catch (BuilderException& e) {
136         SG_LOG(SG_INPUT, SG_ALERT, e.getFormattedMessage() << ", "
137             << "maybe the reader did not set the filename attribute, "
138             << "using white for type '" << type << "' on '" << pass->getName() << "', in " << prop->getPath() );
139         texture = StateAttributeFactory::instance()->getWhiteTexture();
140     }
141     pass->setTextureAttributeAndModes(unit, texture);
142     const SGPropertyNode* envProp = prop->getChild("environment");
143     if (envProp) {
144         TexEnv* env = buildTexEnv(effect, envProp);
145         if (env)
146             pass->setTextureAttributeAndModes(unit, env);
147     }
148     const SGPropertyNode* combineProp = prop->getChild("texenv-combine");
149     TexEnvCombine* combiner = 0;
150     if (combineProp && ((combiner = buildTexEnvCombine(effect, combineProp,
151                                                        options))))
152         pass->setTextureAttributeAndModes(unit, combiner);
153     const SGPropertyNode* tgenProp = prop->getChild("texgen");
154     TexGen* tgen = 0;
155     if (tgenProp && (tgen = buildTexGen(effect, tgenProp)))
156         pass->setTextureAttributeAndModes(unit, tgen);
157 }
158
159 // InstallAttributeBuilder call is in Effect.cxx to force this file to
160 // be linked in.
161
162 namespace
163 {
164 EffectNameValue<Texture::FilterMode> filterModesInit[] =
165 {
166     { "linear", Texture::LINEAR },
167     { "linear-mipmap-linear", Texture::LINEAR_MIPMAP_LINEAR},
168     { "linear-mipmap-nearest", Texture::LINEAR_MIPMAP_NEAREST},
169     { "nearest", Texture::NEAREST},
170     { "nearest-mipmap-linear", Texture::NEAREST_MIPMAP_LINEAR},
171     { "nearest-mipmap-nearest", Texture::NEAREST_MIPMAP_NEAREST}
172 };
173 EffectPropertyMap<Texture::FilterMode> filterModes(filterModesInit);
174
175 EffectNameValue<Texture::WrapMode> wrapModesInit[] =
176 {
177     {"clamp", Texture::CLAMP},
178     {"clamp-to-border", Texture::CLAMP_TO_BORDER},
179     {"clamp-to-edge", Texture::CLAMP_TO_EDGE},
180     {"mirror", Texture::MIRROR},
181     {"repeat", Texture::REPEAT}
182 };
183 EffectPropertyMap<Texture::WrapMode> wrapModes(wrapModesInit);
184
185 TexTuple makeTexTuple(Effect* effect, const SGPropertyNode* props,
186                       const SGReaderWriterXMLOptions* options,
187                       const string& texType)
188 {
189     Texture::FilterMode minFilter = Texture::LINEAR_MIPMAP_LINEAR;
190     const SGPropertyNode* ep = 0;
191     if ((ep = getEffectPropertyChild(effect, props, "filter")))
192         findAttr(filterModes, ep, minFilter);
193     Texture::FilterMode magFilter = Texture::LINEAR;
194     if ((ep = getEffectPropertyChild(effect, props, "mag-filter")))
195         findAttr(filterModes, ep, magFilter);
196     const SGPropertyNode* pWrapS
197         = getEffectPropertyChild(effect, props, "wrap-s");
198     Texture::WrapMode sWrap = Texture::CLAMP;
199     if (pWrapS)
200         findAttr(wrapModes, pWrapS, sWrap);
201     const SGPropertyNode* pWrapT
202         = getEffectPropertyChild(effect, props, "wrap-t");
203     Texture::WrapMode tWrap = Texture::CLAMP;
204     if (pWrapT)
205         findAttr(wrapModes, pWrapT, tWrap);
206     const SGPropertyNode* pWrapR
207         = getEffectPropertyChild(effect, props, "wrap-r");
208     Texture::WrapMode rWrap = Texture::CLAMP;
209     if (pWrapR)
210         findAttr(wrapModes, pWrapR, rWrap);
211     const SGPropertyNode* pImage
212         = getEffectPropertyChild(effect, props, "image");
213     string imageName;
214     string absFileName;
215     if (pImage)
216     {
217         imageName = pImage->getStringValue();
218         absFileName = SGModelLib::findDataFile(imageName, options);
219         if (absFileName.empty())
220         {
221             SG_LOG(SG_INPUT, SG_ALERT, "Texture file not found: '"
222                    << imageName << "'");
223         }
224     }
225
226     const SGPropertyNode* pMipmapControl
227         = getEffectPropertyChild(effect, props, "mipmap-control");
228     MipMapTuple mipmapFunctions( AUTOMATIC, AUTOMATIC, AUTOMATIC, AUTOMATIC ); 
229     if ( pMipmapControl )
230         mipmapFunctions = makeMipMapTuple(effect, pMipmapControl, options);
231
232     return TexTuple(absFileName, minFilter, magFilter, sWrap, tWrap, rWrap,
233                     texType, mipmapFunctions);
234 }
235
236 void setAttrs(const TexTuple& attrs, Texture* tex,
237               const SGReaderWriterXMLOptions* options)
238 {
239     const string& imageName = attrs.get<0>();
240     if (imageName.empty()) {
241         throw BuilderException("no image file");
242     } else {
243         osgDB::ReaderWriter::ReadResult result
244             = osgDB::Registry::instance()->readImage(imageName, options);
245         if (result.success()) {
246             osg::ref_ptr<osg::Image> image = result.getImage();
247             image = computeMipmap( image.get(), attrs.get<7>() );
248             tex->setImage(GL_FRONT_AND_BACK, image.get());
249             int s = image->s();
250             int t = image->t();
251             if (s <= t && 32 <= s) {
252                 SGSceneFeatures::instance()->setTextureCompression(tex);
253             } else if (t < s && 32 <= t) {
254                 SGSceneFeatures::instance()->setTextureCompression(tex);
255             }
256             tex->setMaxAnisotropy(SGSceneFeatures::instance()
257                                   ->getTextureFilter());
258         } else {
259             SG_LOG(SG_INPUT, SG_ALERT, "failed to load effect texture file "
260                    << imageName);
261         }
262     }
263     // texture->setDataVariance(osg::Object::STATIC);
264     tex->setFilter(Texture::MIN_FILTER, attrs.get<1>());
265     tex->setFilter(Texture::MAG_FILTER, attrs.get<2>());
266     tex->setWrap(Texture::WRAP_S, attrs.get<3>());
267     tex->setWrap(Texture::WRAP_T, attrs.get<4>());
268     tex->setWrap(Texture::WRAP_R, attrs.get<5>());
269 }
270 }
271
272 template<typename T>
273 class TexBuilder : public TextureBuilder
274 {
275 public:
276     TexBuilder(const string& texType) : _type(texType) {}
277     Texture* build(Effect* effect, const SGPropertyNode*,
278                    const SGReaderWriterXMLOptions* options);
279 protected:
280     typedef map<TexTuple, ref_ptr<T> > TexMap;
281     TexMap texMap;
282     const string _type;
283 };
284
285 template<typename T>
286 Texture* TexBuilder<T>::build(Effect* effect, const SGPropertyNode* props,
287                               const SGReaderWriterXMLOptions* options)
288 {
289     TexTuple attrs = makeTexTuple(effect, props, options, _type);
290     typename TexMap::iterator itr = texMap.find(attrs);
291     if (itr != texMap.end())
292         return itr->second.get();
293     T* tex = new T;
294     setAttrs(attrs, tex, options);
295     texMap.insert(make_pair(attrs, tex));
296     return tex;
297 }
298
299
300 namespace
301 {
302 TextureBuilder::Registrar install1D("1d", new TexBuilder<Texture1D>("1d"));
303 TextureBuilder::Registrar install2D("2d", new TexBuilder<Texture2D>("2d"));
304 TextureBuilder::Registrar install3D("3d", new TexBuilder<Texture3D>("3d"));
305 }
306
307 class WhiteTextureBuilder : public TextureBuilder
308 {
309 public:
310     Texture* build(Effect* effect, const SGPropertyNode*,
311                    const SGReaderWriterXMLOptions* options);
312 };
313
314 Texture* WhiteTextureBuilder::build(Effect* effect, const SGPropertyNode*,
315                                     const SGReaderWriterXMLOptions* options)
316 {
317     return StateAttributeFactory::instance()->getWhiteTexture();
318 }
319
320 namespace
321 {
322 TextureBuilder::Registrar installWhite("white", new WhiteTextureBuilder);
323 }
324
325 class TransparentTextureBuilder : public TextureBuilder
326 {
327 public:
328     Texture* build(Effect* effect, const SGPropertyNode*,
329                    const SGReaderWriterXMLOptions* options);
330 };
331
332 Texture* TransparentTextureBuilder::build(Effect* effect, const SGPropertyNode*,
333                                     const SGReaderWriterXMLOptions* options)
334 {
335     return StateAttributeFactory::instance()->getTransparentTexture();
336 }
337
338 namespace
339 {
340 TextureBuilder::Registrar installTransparent("transparent",
341                                              new TransparentTextureBuilder);
342 }
343
344 osg::Image* make3DNoiseImage(int texSize)
345 {
346     osg::Image* image = new osg::Image;
347     image->setImage(texSize, texSize, texSize,
348                     4, GL_RGBA, GL_UNSIGNED_BYTE,
349                     new unsigned char[4 * texSize * texSize * texSize],
350                     osg::Image::USE_NEW_DELETE);
351
352     const int startFrequency = 4;
353     const int numOctaves = 4;
354
355     int f, i, j, k, inc;
356     double ni[3];
357     double inci, incj, inck;
358     int frequency = startFrequency;
359     GLubyte *ptr;
360     double amp = 0.5;
361
362     osg::notify(osg::WARN) << "creating 3D noise texture... ";
363
364     for (f = 0, inc = 0; f < numOctaves; ++f, frequency *= 2, ++inc, amp *= 0.5)
365     {
366         SetNoiseFrequency(frequency);
367         ptr = image->data();
368         ni[0] = ni[1] = ni[2] = 0;
369
370         inci = 1.0 / (texSize / frequency);
371         for (i = 0; i < texSize; ++i, ni[0] += inci)
372         {
373             incj = 1.0 / (texSize / frequency);
374             for (j = 0; j < texSize; ++j, ni[1] += incj)
375             {
376                 inck = 1.0 / (texSize / frequency);
377                 for (k = 0; k < texSize; ++k, ni[2] += inck, ptr += 4)
378                 {
379                     *(ptr+inc) = (GLubyte) (((noise3(ni) + 1.0) * amp) * 128.0);
380                 }
381             }
382         }
383     }
384
385     osg::notify(osg::WARN) << "DONE" << std::endl;
386     return image;
387 }
388
389 class NoiseBuilder : public TextureBuilder
390 {
391 public:
392     Texture* build(Effect* effect, const SGPropertyNode*,
393                    const SGReaderWriterXMLOptions* options);
394 protected:
395     typedef map<int, ref_ptr<Texture3D> > NoiseMap;
396     NoiseMap _noises;
397 };
398
399 Texture* NoiseBuilder::build(Effect* effect, const SGPropertyNode* props,
400                              const SGReaderWriterXMLOptions* options)
401 {
402     int texSize = 64;
403     const SGPropertyNode* sizeProp = getEffectPropertyChild(effect, props,
404                                                             "size");
405     if (sizeProp)
406         texSize = sizeProp->getValue<int>();
407     NoiseMap::iterator itr = _noises.find(texSize);
408     if (itr != _noises.end())
409         return itr->second.get();
410     Texture3D* noiseTexture = new osg::Texture3D;
411     noiseTexture->setFilter(osg::Texture3D::MIN_FILTER, osg::Texture3D::LINEAR);
412     noiseTexture->setFilter(osg::Texture3D::MAG_FILTER, osg::Texture3D::LINEAR);
413     noiseTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture3D::REPEAT);
414     noiseTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture3D::REPEAT);
415     noiseTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture3D::REPEAT);
416     noiseTexture->setImage( make3DNoiseImage(texSize) );
417     _noises.insert(make_pair(texSize, noiseTexture));
418     return noiseTexture;
419 }
420
421 namespace
422 {
423 TextureBuilder::Registrar installNoise("noise", new NoiseBuilder);
424 }
425
426
427
428 // Image names for all sides
429 typedef boost::tuple<string, string, string, string, string, string> CubeMapTuple;
430
431 CubeMapTuple makeCubeMapTuple(Effect* effect, const SGPropertyNode* props)
432 {
433     const SGPropertyNode* ep = 0;
434
435     string positive_x;
436     if ((ep = getEffectPropertyChild(effect, props, "positive-x")))
437         positive_x = ep->getStringValue();
438     string negative_x;
439     if ((ep = getEffectPropertyChild(effect, props, "negative-x")))
440         negative_x = ep->getStringValue();
441     string positive_y;
442     if ((ep = getEffectPropertyChild(effect, props, "positive-y")))
443         positive_y = ep->getStringValue();
444     string negative_y;
445     if ((ep = getEffectPropertyChild(effect, props, "negative-y")))
446         negative_y = ep->getStringValue();
447     string positive_z;
448     if ((ep = getEffectPropertyChild(effect, props, "positive-z")))
449         positive_z = ep->getStringValue();
450     string negative_z;
451     if ((ep = getEffectPropertyChild(effect, props, "negative-z")))
452         negative_z = ep->getStringValue();
453     return CubeMapTuple(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z);
454 }
455
456
457 class CubeMapBuilder : public TextureBuilder
458 {
459 public:
460     Texture* build(Effect* effect, const SGPropertyNode*,
461                    const SGReaderWriterXMLOptions* options);
462 protected:
463     typedef map<CubeMapTuple, ref_ptr<TextureCubeMap> > CubeMap;
464     typedef map<string, ref_ptr<TextureCubeMap> > CrossCubeMap;
465     CubeMap _cubemaps;
466     CrossCubeMap _crossmaps;
467 };
468
469 // I use this until osg::CopyImage is fixed
470 // This one assumes images are the same format and sizes are correct
471 void copySubImage(const osg::Image* srcImage, int src_s, int src_t, int width, int height, 
472                  osg::Image* destImage, int dest_s, int dest_t)
473 {
474     for(int row = 0; row<height; ++row)
475     {
476         const unsigned char* srcData = srcImage->data(src_s, src_t+row, 0);
477         unsigned char* destData = destImage->data(dest_s, dest_t+row, 0);
478         memcpy(destData, srcData, (width*destImage->getPixelSizeInBits())/8);
479     }
480 }
481
482
483 Texture* CubeMapBuilder::build(Effect* effect, const SGPropertyNode* props,
484                                const SGReaderWriterXMLOptions* options)
485 {
486     // First check that there is a <images> tag
487     const SGPropertyNode* texturesProp = getEffectPropertyChild(effect, props, "images");
488     const SGPropertyNode* crossProp = getEffectPropertyChild(effect, props, "image");
489     if (!texturesProp && !crossProp) {
490         throw BuilderException("no images defined for cube map");
491         return NULL; // This is redundant
492     }
493
494     // Using 6 separate images
495     if(texturesProp) {
496
497         SG_LOG(SG_INPUT, SG_DEBUG, "try 6 images ");
498
499         CubeMapTuple _tuple = makeCubeMapTuple(effect, texturesProp);
500
501         CubeMap::iterator itr = _cubemaps.find(_tuple);
502         if (itr != _cubemaps.end())
503             return itr->second.get();
504
505         TextureCubeMap* cubeTexture = new osg::TextureCubeMap;
506
507         // TODO: Read these from effect file? Maybe these are sane for all cuebmaps?
508         cubeTexture->setFilter(osg::Texture3D::MIN_FILTER, osg::Texture::LINEAR_MIPMAP_LINEAR);
509         cubeTexture->setFilter(osg::Texture3D::MAG_FILTER, osg::Texture::LINEAR);
510         cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
511         cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
512         cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
513
514         osgDB::ReaderWriter::ReadResult result =
515             osgDB::Registry::instance()->readImage(_tuple.get<0>(), options);
516         if(result.success()) {
517             osg::Image* image = result.getImage();
518             cubeTexture->setImage(TextureCubeMap::POSITIVE_X, image);
519         }
520         result = osgDB::Registry::instance()->readImage(_tuple.get<1>(), options);
521         if(result.success()) {
522             osg::Image* image = result.getImage();
523             cubeTexture->setImage(TextureCubeMap::NEGATIVE_X, image);
524         }
525         result = osgDB::Registry::instance()->readImage(_tuple.get<2>(), options);
526         if(result.success()) {
527             osg::Image* image = result.getImage();
528             cubeTexture->setImage(TextureCubeMap::POSITIVE_Y, image);
529         }
530         result = osgDB::Registry::instance()->readImage(_tuple.get<3>(), options);
531         if(result.success()) {
532             osg::Image* image = result.getImage();
533             cubeTexture->setImage(TextureCubeMap::NEGATIVE_Y, image);
534         }
535         result = osgDB::Registry::instance()->readImage(_tuple.get<4>(), options);
536         if(result.success()) {
537             osg::Image* image = result.getImage();
538             cubeTexture->setImage(TextureCubeMap::POSITIVE_Z, image);
539         }
540         result = osgDB::Registry::instance()->readImage(_tuple.get<5>(), options);
541         if(result.success()) {
542             osg::Image* image = result.getImage();
543             cubeTexture->setImage(TextureCubeMap::NEGATIVE_Z, image);
544         }
545
546         _cubemaps[_tuple] = cubeTexture;
547
548         return cubeTexture;
549     }
550
551
552     // Using 1 cross image
553     else if(crossProp) {
554         SG_LOG(SG_INPUT, SG_DEBUG, "try cross map ");
555
556         std::string texname = crossProp->getStringValue();
557
558         // Try to find existing cube map
559         CrossCubeMap::iterator itr = _crossmaps.find(texname);
560         if (itr != _crossmaps.end())
561             return itr->second.get();
562
563         osgDB::ReaderWriter::ReadResult result =
564             osgDB::Registry::instance()->readImage(texname, options);
565         if(result.success()) {
566             osg::Image* image = result.getImage();
567             image->flipVertical();   // Seems like the image coordinates are somewhat funny, flip to get better ones
568
569             //cubeTexture->setResizeNonPowerOfTwoHint(false);
570
571             // Size of a single image, 4 rows and 3 columns
572             int width = image->s() / 3;
573             int height = image->t() / 4;
574             int depth = image->r();
575
576             TextureCubeMap* cubeTexture = new osg::TextureCubeMap;
577
578             // Copy the 6 sub-images and push them
579             for(int n=0; n<6; n++) {
580
581                 SG_LOG(SG_INPUT, SG_DEBUG, "Copying the " << n << "th sub-images and pushing it" );
582
583                 osg::ref_ptr<osg::Image> subimg = new osg::Image();
584                 subimg->allocateImage(width, height, depth, image->getPixelFormat(), image->getDataType());  // Copy attributes
585
586                 // Choose correct image
587                 switch(n) {
588                 case 0:  // Front
589                     copySubImage(image, width, 0, width, height, subimg.get(), 0, 0);
590                     cubeTexture->setImage(TextureCubeMap::POSITIVE_Y, subimg.get());
591                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
592                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
593                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
594                     break;
595                 case 1:  // Left
596                     copySubImage(image, 0, height, width, height, subimg.get(), 0, 0);
597                     cubeTexture->setImage(TextureCubeMap::NEGATIVE_X, subimg.get());
598                     cubeTexture->setWrap(osg::Texture2D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
599                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
600                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
601                     break;
602                 case 2:  // Top
603                     copySubImage(image, width, height, width, height, subimg.get(), 0, 0);
604                     cubeTexture->setImage(TextureCubeMap::POSITIVE_Z, subimg.get());
605                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
606                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
607                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
608                     break;
609                 case 3:  // Right
610                     copySubImage(image, width*2, height, width, height, subimg.get(), 0, 0);
611                     cubeTexture->setImage(TextureCubeMap::POSITIVE_X, subimg.get());
612                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
613                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
614                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
615                     break;
616                 case 4:  // Back
617                     copySubImage(image, width, height*2, width, height, subimg.get(), 0, 0);
618                     cubeTexture->setImage(TextureCubeMap::NEGATIVE_Y, subimg.get());
619                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
620                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
621                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
622                     break;
623                 case 5:  // Bottom
624                     copySubImage(image, width, height*3, width, height, subimg.get(), 0, 0);
625                     cubeTexture->setImage(TextureCubeMap::NEGATIVE_Z, subimg.get());
626                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
627                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
628                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
629                     break;
630                 };
631
632             }
633
634             _crossmaps[texname] = cubeTexture;
635
636             return cubeTexture;
637
638         } else {
639             throw BuilderException("Could not load cube cross");
640         }
641     }
642
643     return NULL;
644 }
645
646 namespace {
647 TextureBuilder::Registrar installCubeMap("cubemap", new CubeMapBuilder);
648 }
649
650 EffectNameValue<TexEnvCombine::CombineParam> combineParamInit[] =
651 {
652     {"replace", TexEnvCombine::REPLACE},
653     {"modulate", TexEnvCombine::MODULATE},
654     {"add", TexEnvCombine::ADD},
655     {"add-signed", TexEnvCombine::ADD_SIGNED},
656     {"interpolate", TexEnvCombine::INTERPOLATE},
657     {"subtract", TexEnvCombine::SUBTRACT},
658     {"dot3-rgb", TexEnvCombine::DOT3_RGB},
659     {"dot3-rgba", TexEnvCombine::DOT3_RGBA}
660 };
661
662 EffectPropertyMap<TexEnvCombine::CombineParam> combineParams(combineParamInit);
663
664 EffectNameValue<TexEnvCombine::SourceParam> sourceParamInit[] =
665 {
666     {"constant", TexEnvCombine::CONSTANT},
667     {"primary_color", TexEnvCombine::PRIMARY_COLOR},
668     {"previous", TexEnvCombine::PREVIOUS},
669     {"texture", TexEnvCombine::TEXTURE},
670     {"texture0", TexEnvCombine::TEXTURE0},
671     {"texture1", TexEnvCombine::TEXTURE1},
672     {"texture2", TexEnvCombine::TEXTURE2},
673     {"texture3", TexEnvCombine::TEXTURE3},
674     {"texture4", TexEnvCombine::TEXTURE4},
675     {"texture5", TexEnvCombine::TEXTURE5},
676     {"texture6", TexEnvCombine::TEXTURE6},
677     {"texture7", TexEnvCombine::TEXTURE7}
678 };
679
680 EffectPropertyMap<TexEnvCombine::SourceParam> sourceParams(sourceParamInit);
681
682 EffectNameValue<TexEnvCombine::OperandParam> opParamInit[] =
683 {
684     {"src-color", TexEnvCombine::SRC_COLOR},
685     {"one-minus-src-color", TexEnvCombine::ONE_MINUS_SRC_COLOR},
686     {"src-alpha", TexEnvCombine::SRC_ALPHA},
687     {"one-minus-src-alpha", TexEnvCombine::ONE_MINUS_SRC_ALPHA}
688 };
689
690 EffectPropertyMap<TexEnvCombine::OperandParam> operandParams(opParamInit);
691
692 TexEnvCombine* buildTexEnvCombine(Effect* effect, const SGPropertyNode* envProp,
693                                   const SGReaderWriterXMLOptions* options)
694 {
695     if (!isAttributeActive(effect, envProp))
696         return 0;
697     TexEnvCombine* result = new TexEnvCombine;
698     const SGPropertyNode* p = 0;
699     if ((p = getEffectPropertyChild(effect, envProp, "combine-rgb"))) {
700         TexEnvCombine::CombineParam crgb = TexEnvCombine::MODULATE;
701         findAttr(combineParams, p, crgb);
702         result->setCombine_RGB(crgb);
703     }
704     if ((p = getEffectPropertyChild(effect, envProp, "combine-alpha"))) {
705         TexEnvCombine::CombineParam calpha = TexEnvCombine::MODULATE;
706         findAttr(combineParams, p, calpha);
707         result->setCombine_Alpha(calpha);
708     }
709     if ((p = getEffectPropertyChild(effect, envProp, "source0-rgb"))) {
710         TexEnvCombine::SourceParam source = TexEnvCombine::TEXTURE;
711         findAttr(sourceParams, p, source);
712         result->setSource0_RGB(source);
713     }
714     if ((p = getEffectPropertyChild(effect, envProp, "source1-rgb"))) {
715         TexEnvCombine::SourceParam source = TexEnvCombine::PREVIOUS;
716         findAttr(sourceParams, p, source);
717         result->setSource1_RGB(source);
718     }
719     if ((p = getEffectPropertyChild(effect, envProp, "source2-rgb"))) {
720         TexEnvCombine::SourceParam source = TexEnvCombine::CONSTANT;
721         findAttr(sourceParams, p, source);
722         result->setSource2_RGB(source);
723     }
724     if ((p = getEffectPropertyChild(effect, envProp, "source0-alpha"))) {
725         TexEnvCombine::SourceParam source = TexEnvCombine::TEXTURE;
726         findAttr(sourceParams, p, source);
727         result->setSource0_Alpha(source);
728     }
729     if ((p = getEffectPropertyChild(effect, envProp, "source1-alpha"))) {
730         TexEnvCombine::SourceParam source = TexEnvCombine::PREVIOUS;
731         findAttr(sourceParams, p, source);
732         result->setSource1_Alpha(source);
733     }
734     if ((p = getEffectPropertyChild(effect, envProp, "source2-alpha"))) {
735         TexEnvCombine::SourceParam source = TexEnvCombine::CONSTANT;
736         findAttr(sourceParams, p, source);
737         result->setSource2_Alpha(source);
738     }
739     if ((p = getEffectPropertyChild(effect, envProp, "operand0-rgb"))) {
740         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_COLOR;
741         findAttr(operandParams, p, op);
742         result->setOperand0_RGB(op);
743     }
744     if ((p = getEffectPropertyChild(effect, envProp, "operand1-rgb"))) {
745         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_COLOR;
746         findAttr(operandParams, p, op);
747         result->setOperand1_RGB(op);
748     }
749     if ((p = getEffectPropertyChild(effect, envProp, "operand2-rgb"))) {
750         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_ALPHA;
751         findAttr(operandParams, p, op);
752         result->setOperand2_RGB(op);
753     }
754     if ((p = getEffectPropertyChild(effect, envProp, "operand0-alpha"))) {
755         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_ALPHA;
756         findAttr(operandParams, p, op);
757         result->setOperand0_Alpha(op);
758     }
759     if ((p = getEffectPropertyChild(effect, envProp, "operand1-alpha"))) {
760         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_ALPHA;
761         findAttr(operandParams, p, op);
762         result->setOperand1_Alpha(op);
763     }
764     if ((p = getEffectPropertyChild(effect, envProp, "operand2-alpha"))) {
765         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_ALPHA;
766         findAttr(operandParams, p, op);
767         result->setOperand2_Alpha(op);
768     }
769     if ((p = getEffectPropertyChild(effect, envProp, "scale-rgb"))) {
770         result->setScale_RGB(p->getValue<float>());
771     }
772     if ((p = getEffectPropertyChild(effect, envProp, "scale-alpha"))) {
773         result->setScale_Alpha(p->getValue<float>());
774     }
775 #if 0
776     if ((p = getEffectPropertyChild(effect, envProp, "constant-color"))) {
777         SGVec4d color = p->getValue<SGVec4d>();
778         result->setConstantColor(toOsg(color));
779     } else if ((p = getEffectPropertyChild(effect, envProp,
780                                            "light-direction"))) {
781         SGVec3d direction = p->getValue<SGVec3d>();
782         result->setConstantColorAsLightDirection(toOsg(direction));
783     }
784 #endif
785     const SGPropertyNode* colorNode = envProp->getChild("constant-color");
786     if (colorNode)
787         initFromParameters(effect, colorNode, result,
788                            &TexEnvCombine::setConstantColor, colorFields,
789                            options);
790     return result;
791 }
792
793 EffectNameValue<TexGen::Mode> tgenModeInit[] =
794 {
795     { "object-linear", TexGen::OBJECT_LINEAR},
796     { "eye-linear", TexGen::EYE_LINEAR},
797     { "sphere-map", TexGen::SPHERE_MAP},
798     { "normal-map", TexGen::NORMAL_MAP},
799     { "reflection-map", TexGen::REFLECTION_MAP}
800 };
801
802 EffectPropertyMap<TexGen::Mode> tgenModes(tgenModeInit);
803
804 EffectNameValue<TexGen::Coord> tgenCoordInit[] =
805 {
806     {"s", TexGen::S},
807     {"t", TexGen::T},
808     {"r", TexGen::R},
809     {"q", TexGen::Q}
810 };
811
812 EffectPropertyMap<TexGen::Coord> tgenCoords(tgenCoordInit);
813
814 TexGen* buildTexGen(Effect* effect, const SGPropertyNode* tgenProp)
815 {
816     if (!isAttributeActive(effect, tgenProp))
817         return 0;
818     TexGen* result = new TexGen;
819     TexGen::Mode mode = TexGen::OBJECT_LINEAR;
820     findAttr(tgenModes, getEffectPropertyChild(effect, tgenProp, "mode"), mode);
821     result->setMode(mode);
822     const SGPropertyNode* planesNode = tgenProp->getChild("planes");
823     if (planesNode) {
824         for (int i = 0; i < planesNode->nChildren(); ++i) {
825             const SGPropertyNode* planeNode = planesNode->getChild(i);
826             TexGen::Coord coord;
827             findAttr(tgenCoords, planeNode->getName(), coord);
828             const SGPropertyNode* realNode
829                 = getEffectPropertyNode(effect, planeNode);
830             SGVec4d plane = realNode->getValue<SGVec4d>();
831             result->setPlane(coord, toOsg(plane));
832         }
833     }
834     return result;
835 }
836
837 bool makeTextureParameters(SGPropertyNode* paramRoot, const StateSet* ss)
838 {
839     SGPropertyNode* texUnit = makeChild(paramRoot, "texture");
840     const Texture* tex = getStateAttribute<Texture>(0, ss);
841     const Texture2D* texture = dynamic_cast<const Texture2D*>(tex);
842     makeChild(texUnit, "unit")->setValue(0);
843     if (!tex) {
844         // The default shader-based technique ignores active
845         makeChild(texUnit, "active")->setValue(false);
846         return false;
847     }
848     const Image* image = texture->getImage();
849     string imageName;
850     if (image) {
851         imageName = image->getFileName();
852     } else {
853         makeChild(texUnit, "active")->setValue(false);
854         makeChild(texUnit, "type")->setValue("white");
855         return false;
856     }
857     makeChild(texUnit, "active")->setValue(true);
858     makeChild(texUnit, "type")->setValue("2d");
859     string filter = findName(filterModes,
860                              texture->getFilter(Texture::MIN_FILTER));
861     string magFilter = findName(filterModes,
862                              texture->getFilter(Texture::MAG_FILTER));
863     string wrapS = findName(wrapModes, texture->getWrap(Texture::WRAP_S));
864     string wrapT = findName(wrapModes, texture->getWrap(Texture::WRAP_T));
865     string wrapR = findName(wrapModes, texture->getWrap(Texture::WRAP_R));
866     makeChild(texUnit, "image")->setStringValue(imageName);
867     makeChild(texUnit, "filter")->setStringValue(filter);
868     makeChild(texUnit, "mag-filter")->setStringValue(magFilter);
869     makeChild(texUnit, "wrap-s")->setStringValue(wrapS);
870     makeChild(texUnit, "wrap-t")->setStringValue(wrapT);
871     makeChild(texUnit, "wrap-r")->setStringValue(wrapR);
872     return true;
873 }
874
875 }