]> git.mxchange.org Git - simgear.git/blob - simgear/scene/material/TextureBuilder.cxx
track-to animation: 2dof rotation for slave object.
[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 #include <osgDB/ReadFile>
36
37 #include <boost/lexical_cast.hpp>
38 #include <boost/tuple/tuple.hpp>
39 #include <boost/tuple/tuple_comparison.hpp>
40
41 #include <simgear/scene/util/OsgMath.hxx>
42 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
43 #include <simgear/scene/util/SGSceneFeatures.hxx>
44 #include <simgear/scene/util/StateAttributeFactory.hxx>
45 #include <simgear/structure/OSGUtils.hxx>
46 #include <simgear/props/vectorPropTemplates.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 SGReaderWriterOptions* 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, Pass* pass, const string& type,
62                                             const SGPropertyNode*props,
63                                             const SGReaderWriterOptions*
64                                             options)
65 {
66     return EffectBuilder<Texture>::buildFromType(effect, pass, 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 SGReaderWriterOptions* 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, pass, type, prop,
133                                                 options);
134     }
135     catch (BuilderException& e) {
136         SG_LOG(SG_INPUT, SG_DEBUG, 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 SGReaderWriterOptions* 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 SGReaderWriterOptions* 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         result = osgDB::readImageFile(imageName, options);
245         osg::ref_ptr<osg::Image> image;
246         if (result.success())
247             image = result.getImage();
248         if (image.valid())
249         {
250             image = computeMipmap( image.get(), attrs.get<7>() );
251             tex->setImage(GL_FRONT_AND_BACK, image.get());
252             int s = image->s();
253             int t = image->t();
254             if (s <= t && 32 <= s) {
255                 SGSceneFeatures::instance()->setTextureCompression(tex);
256             } else if (t < s && 32 <= t) {
257                 SGSceneFeatures::instance()->setTextureCompression(tex);
258             }
259             tex->setMaxAnisotropy(SGSceneFeatures::instance()
260                                   ->getTextureFilter());
261         } else {
262             SG_LOG(SG_INPUT, SG_ALERT, "failed to load effect texture file "
263                    << imageName);
264         }
265     }
266     // texture->setDataVariance(osg::Object::STATIC);
267     tex->setFilter(Texture::MIN_FILTER, attrs.get<1>());
268     tex->setFilter(Texture::MAG_FILTER, attrs.get<2>());
269     tex->setWrap(Texture::WRAP_S, attrs.get<3>());
270     tex->setWrap(Texture::WRAP_T, attrs.get<4>());
271     tex->setWrap(Texture::WRAP_R, attrs.get<5>());
272 }
273 }
274
275 template<typename T>
276 class TexBuilder : public TextureBuilder
277 {
278 public:
279     TexBuilder(const string& texType) : _type(texType) {}
280     Texture* build(Effect* effect, Pass* pass, const SGPropertyNode*,
281                    const SGReaderWriterOptions* options);
282 protected:
283     typedef map<TexTuple, observer_ptr<T> > TexMap;
284     TexMap texMap;
285     const string _type;
286 };
287
288 template<typename T>
289 Texture* TexBuilder<T>::build(Effect* effect, Pass* pass, const SGPropertyNode* props,
290                               const SGReaderWriterOptions* options)
291 {
292     TexTuple attrs = makeTexTuple(effect, props, options, _type);
293     typename TexMap::iterator itr = texMap.find(attrs);
294
295     ref_ptr<T> tex;
296     if ((itr != texMap.end())&&
297         (itr->second.lock(tex)))
298     {
299         return tex.release();
300     }
301
302     tex = new T;
303     setAttrs(attrs, tex, options);
304     if (itr == texMap.end())
305         texMap.insert(make_pair(attrs, tex));
306     else
307         itr->second = tex; // update existing, but empty observer
308     return tex.release();
309 }
310
311
312 namespace
313 {
314 TextureBuilder::Registrar install1D("1d", new TexBuilder<Texture1D>("1d"));
315 TextureBuilder::Registrar install2D("2d", new TexBuilder<Texture2D>("2d"));
316 TextureBuilder::Registrar install3D("3d", new TexBuilder<Texture3D>("3d"));
317 }
318
319 class WhiteTextureBuilder : public TextureBuilder
320 {
321 public:
322     Texture* build(Effect* effect, Pass* pass, const SGPropertyNode*,
323                    const SGReaderWriterOptions* options);
324 };
325
326 Texture* WhiteTextureBuilder::build(Effect* effect, Pass* pass, const SGPropertyNode*,
327                                     const SGReaderWriterOptions* options)
328 {
329     return StateAttributeFactory::instance()->getWhiteTexture();
330 }
331
332 namespace
333 {
334 TextureBuilder::Registrar installWhite("white", new WhiteTextureBuilder);
335 }
336
337 class TransparentTextureBuilder : public TextureBuilder
338 {
339 public:
340     Texture* build(Effect* effect, Pass* pass, const SGPropertyNode*,
341                    const SGReaderWriterOptions* options);
342 };
343
344 Texture* TransparentTextureBuilder::build(Effect* effect, Pass* pass, const SGPropertyNode*,
345                                     const SGReaderWriterOptions* options)
346 {
347     return StateAttributeFactory::instance()->getTransparentTexture();
348 }
349
350 namespace
351 {
352 TextureBuilder::Registrar installTransparent("transparent",
353                                              new TransparentTextureBuilder);
354 }
355
356 class NoiseBuilder : public TextureBuilder
357 {
358 public:
359     Texture* build(Effect* effect, Pass* pass, const SGPropertyNode*,
360                    const SGReaderWriterOptions* options);
361 protected:
362     typedef map<int, ref_ptr<Texture3D> > NoiseMap;
363     NoiseMap _noises;
364 };
365
366 Texture* NoiseBuilder::build(Effect* effect, Pass* pass, const SGPropertyNode* props,
367                              const SGReaderWriterOptions* options)
368 {
369     int texSize = 64;
370     const SGPropertyNode* sizeProp = getEffectPropertyChild(effect, props,
371                                                             "size");
372     if (sizeProp)
373         texSize = sizeProp->getValue<int>();
374
375     return StateAttributeFactory::instance()->getNoiseTexture(texSize);
376 }
377
378 namespace
379 {
380 TextureBuilder::Registrar installNoise("noise", new NoiseBuilder);
381 }
382
383
384
385 // Image names for all sides
386 typedef boost::tuple<string, string, string, string, string, string> CubeMapTuple;
387
388 CubeMapTuple makeCubeMapTuple(Effect* effect, const SGPropertyNode* props)
389 {
390     const SGPropertyNode* ep = 0;
391
392     string positive_x;
393     if ((ep = getEffectPropertyChild(effect, props, "positive-x")))
394         positive_x = ep->getStringValue();
395     string negative_x;
396     if ((ep = getEffectPropertyChild(effect, props, "negative-x")))
397         negative_x = ep->getStringValue();
398     string positive_y;
399     if ((ep = getEffectPropertyChild(effect, props, "positive-y")))
400         positive_y = ep->getStringValue();
401     string negative_y;
402     if ((ep = getEffectPropertyChild(effect, props, "negative-y")))
403         negative_y = ep->getStringValue();
404     string positive_z;
405     if ((ep = getEffectPropertyChild(effect, props, "positive-z")))
406         positive_z = ep->getStringValue();
407     string negative_z;
408     if ((ep = getEffectPropertyChild(effect, props, "negative-z")))
409         negative_z = ep->getStringValue();
410     return CubeMapTuple(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z);
411 }
412
413
414 class CubeMapBuilder : public TextureBuilder
415 {
416 public:
417     Texture* build(Effect* effect, Pass* pass, const SGPropertyNode*,
418                    const SGReaderWriterOptions* options);
419 protected:
420     typedef map<CubeMapTuple, ref_ptr<TextureCubeMap> > CubeMap;
421     typedef map<string, ref_ptr<TextureCubeMap> > CrossCubeMap;
422     CubeMap _cubemaps;
423     CrossCubeMap _crossmaps;
424 };
425
426 // I use this until osg::CopyImage is fixed
427 // This one assumes images are the same format and sizes are correct
428 void copySubImage(const osg::Image* srcImage, int src_s, int src_t, int width, int height, 
429                  osg::Image* destImage, int dest_s, int dest_t)
430 {
431     for(int row = 0; row<height; ++row)
432     {
433         const unsigned char* srcData = srcImage->data(src_s, src_t+row, 0);
434         unsigned char* destData = destImage->data(dest_s, dest_t+row, 0);
435         memcpy(destData, srcData, (width*destImage->getPixelSizeInBits())/8);
436     }
437 }
438
439
440 Texture* CubeMapBuilder::build(Effect* effect, Pass* pass, const SGPropertyNode* props,
441                                const SGReaderWriterOptions* options)
442 {
443     // First check that there is a <images> tag
444     const SGPropertyNode* texturesProp = getEffectPropertyChild(effect, props, "images");
445     const SGPropertyNode* crossProp = getEffectPropertyChild(effect, props, "image");
446     if (!texturesProp && !crossProp) {
447         throw BuilderException("no images defined for cube map");
448         return NULL; // This is redundant
449     }
450
451     // Using 6 separate images
452     if(texturesProp) {
453
454         SG_LOG(SG_INPUT, SG_DEBUG, "try 6 images ");
455
456         CubeMapTuple _tuple = makeCubeMapTuple(effect, texturesProp);
457
458         CubeMap::iterator itr = _cubemaps.find(_tuple);
459         if (itr != _cubemaps.end())
460             return itr->second.get();
461
462         TextureCubeMap* cubeTexture = new osg::TextureCubeMap;
463
464         // TODO: Read these from effect file? Maybe these are sane for all cuebmaps?
465         cubeTexture->setFilter(osg::Texture3D::MIN_FILTER, osg::Texture::LINEAR_MIPMAP_LINEAR);
466         cubeTexture->setFilter(osg::Texture3D::MAG_FILTER, osg::Texture::LINEAR);
467         cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
468         cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
469         cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
470
471         osgDB::ReaderWriter::ReadResult result;
472         result = osgDB::readImageFile(_tuple.get<0>(), options);
473         if(result.success()) {
474             osg::Image* image = result.getImage();
475             cubeTexture->setImage(TextureCubeMap::POSITIVE_X, image);
476         }
477         result = osgDB::readImageFile(_tuple.get<1>(), options);
478         if(result.success()) {
479             osg::Image* image = result.getImage();
480             cubeTexture->setImage(TextureCubeMap::NEGATIVE_X, image);
481         }
482         result = osgDB::readImageFile(_tuple.get<2>(), options);
483         if(result.success()) {
484             osg::Image* image = result.getImage();
485             cubeTexture->setImage(TextureCubeMap::POSITIVE_Y, image);
486         }
487         result = osgDB::readImageFile(_tuple.get<3>(), options);
488         if(result.success()) {
489             osg::Image* image = result.getImage();
490             cubeTexture->setImage(TextureCubeMap::NEGATIVE_Y, image);
491         }
492         result = osgDB::readImageFile(_tuple.get<4>(), options);
493         if(result.success()) {
494             osg::Image* image = result.getImage();
495             cubeTexture->setImage(TextureCubeMap::POSITIVE_Z, image);
496         }
497         result = osgDB::readImageFile(_tuple.get<5>(), options);
498         if(result.success()) {
499             osg::Image* image = result.getImage();
500             cubeTexture->setImage(TextureCubeMap::NEGATIVE_Z, image);
501         }
502
503         _cubemaps[_tuple] = cubeTexture;
504
505         return cubeTexture;
506     }
507
508
509     // Using 1 cross image
510     else if(crossProp) {
511         SG_LOG(SG_INPUT, SG_DEBUG, "try cross map ");
512
513         std::string texname = crossProp->getStringValue();
514
515         // Try to find existing cube map
516         CrossCubeMap::iterator itr = _crossmaps.find(texname);
517         if (itr != _crossmaps.end())
518             return itr->second.get();
519
520         osgDB::ReaderWriter::ReadResult result;
521         result = osgDB::readImageFile(texname, options);
522         if(result.success()) {
523             osg::Image* image = result.getImage();
524             image->flipVertical();   // Seems like the image coordinates are somewhat funny, flip to get better ones
525
526             //cubeTexture->setResizeNonPowerOfTwoHint(false);
527
528             // Size of a single image, 4 rows and 3 columns
529             int width = image->s() / 3;
530             int height = image->t() / 4;
531             int depth = image->r();
532
533             TextureCubeMap* cubeTexture = new osg::TextureCubeMap;
534
535             // Copy the 6 sub-images and push them
536             for(int n=0; n<6; n++) {
537
538                 SG_LOG(SG_INPUT, SG_DEBUG, "Copying the " << n << "th sub-images and pushing it" );
539
540                 osg::ref_ptr<osg::Image> subimg = new osg::Image();
541                 subimg->allocateImage(width, height, depth, image->getPixelFormat(), image->getDataType());  // Copy attributes
542
543                 // Choose correct image
544                 switch(n) {
545                 case 0:  // Front
546                     copySubImage(image, width, 0, width, height, subimg.get(), 0, 0);
547                     cubeTexture->setImage(TextureCubeMap::POSITIVE_Y, subimg.get());
548                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
549                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
550                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
551                     break;
552                 case 1:  // Left
553                     copySubImage(image, 0, height, width, height, subimg.get(), 0, 0);
554                     cubeTexture->setImage(TextureCubeMap::NEGATIVE_X, subimg.get());
555                     cubeTexture->setWrap(osg::Texture2D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
556                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
557                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
558                     break;
559                 case 2:  // Top
560                     copySubImage(image, width, height, width, height, subimg.get(), 0, 0);
561                     cubeTexture->setImage(TextureCubeMap::POSITIVE_Z, subimg.get());
562                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
563                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
564                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
565                     break;
566                 case 3:  // Right
567                     copySubImage(image, width*2, height, width, height, subimg.get(), 0, 0);
568                     cubeTexture->setImage(TextureCubeMap::POSITIVE_X, subimg.get());
569                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
570                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
571                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
572                     break;
573                 case 4:  // Back
574                     copySubImage(image, width, height*2, width, height, subimg.get(), 0, 0);
575                     cubeTexture->setImage(TextureCubeMap::NEGATIVE_Y, subimg.get());
576                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
577                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
578                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
579                     break;
580                 case 5:  // Bottom
581                     copySubImage(image, width, height*3, width, height, subimg.get(), 0, 0);
582                     cubeTexture->setImage(TextureCubeMap::NEGATIVE_Z, subimg.get());
583                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
584                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
585                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
586                     break;
587                 };
588
589             }
590
591             _crossmaps[texname] = cubeTexture;
592
593             return cubeTexture;
594
595         } else {
596             throw BuilderException("Could not load cube cross");
597         }
598     }
599
600     return NULL;
601 }
602
603 namespace {
604 TextureBuilder::Registrar installCubeMap("cubemap", new CubeMapBuilder);
605 }
606
607 EffectNameValue<TexEnvCombine::CombineParam> combineParamInit[] =
608 {
609     {"replace", TexEnvCombine::REPLACE},
610     {"modulate", TexEnvCombine::MODULATE},
611     {"add", TexEnvCombine::ADD},
612     {"add-signed", TexEnvCombine::ADD_SIGNED},
613     {"interpolate", TexEnvCombine::INTERPOLATE},
614     {"subtract", TexEnvCombine::SUBTRACT},
615     {"dot3-rgb", TexEnvCombine::DOT3_RGB},
616     {"dot3-rgba", TexEnvCombine::DOT3_RGBA}
617 };
618
619 EffectPropertyMap<TexEnvCombine::CombineParam> combineParams(combineParamInit);
620
621 EffectNameValue<TexEnvCombine::SourceParam> sourceParamInit[] =
622 {
623     {"constant", TexEnvCombine::CONSTANT},
624     {"primary_color", TexEnvCombine::PRIMARY_COLOR},
625     {"previous", TexEnvCombine::PREVIOUS},
626     {"texture", TexEnvCombine::TEXTURE},
627     {"texture0", TexEnvCombine::TEXTURE0},
628     {"texture1", TexEnvCombine::TEXTURE1},
629     {"texture2", TexEnvCombine::TEXTURE2},
630     {"texture3", TexEnvCombine::TEXTURE3},
631     {"texture4", TexEnvCombine::TEXTURE4},
632     {"texture5", TexEnvCombine::TEXTURE5},
633     {"texture6", TexEnvCombine::TEXTURE6},
634     {"texture7", TexEnvCombine::TEXTURE7}
635 };
636
637 EffectPropertyMap<TexEnvCombine::SourceParam> sourceParams(sourceParamInit);
638
639 EffectNameValue<TexEnvCombine::OperandParam> opParamInit[] =
640 {
641     {"src-color", TexEnvCombine::SRC_COLOR},
642     {"one-minus-src-color", TexEnvCombine::ONE_MINUS_SRC_COLOR},
643     {"src-alpha", TexEnvCombine::SRC_ALPHA},
644     {"one-minus-src-alpha", TexEnvCombine::ONE_MINUS_SRC_ALPHA}
645 };
646
647 EffectPropertyMap<TexEnvCombine::OperandParam> operandParams(opParamInit);
648
649 TexEnvCombine* buildTexEnvCombine(Effect* effect, const SGPropertyNode* envProp,
650                                   const SGReaderWriterOptions* options)
651 {
652     if (!isAttributeActive(effect, envProp))
653         return 0;
654     TexEnvCombine* result = new TexEnvCombine;
655     const SGPropertyNode* p = 0;
656     if ((p = getEffectPropertyChild(effect, envProp, "combine-rgb"))) {
657         TexEnvCombine::CombineParam crgb = TexEnvCombine::MODULATE;
658         findAttr(combineParams, p, crgb);
659         result->setCombine_RGB(crgb);
660     }
661     if ((p = getEffectPropertyChild(effect, envProp, "combine-alpha"))) {
662         TexEnvCombine::CombineParam calpha = TexEnvCombine::MODULATE;
663         findAttr(combineParams, p, calpha);
664         result->setCombine_Alpha(calpha);
665     }
666     if ((p = getEffectPropertyChild(effect, envProp, "source0-rgb"))) {
667         TexEnvCombine::SourceParam source = TexEnvCombine::TEXTURE;
668         findAttr(sourceParams, p, source);
669         result->setSource0_RGB(source);
670     }
671     if ((p = getEffectPropertyChild(effect, envProp, "source1-rgb"))) {
672         TexEnvCombine::SourceParam source = TexEnvCombine::PREVIOUS;
673         findAttr(sourceParams, p, source);
674         result->setSource1_RGB(source);
675     }
676     if ((p = getEffectPropertyChild(effect, envProp, "source2-rgb"))) {
677         TexEnvCombine::SourceParam source = TexEnvCombine::CONSTANT;
678         findAttr(sourceParams, p, source);
679         result->setSource2_RGB(source);
680     }
681     if ((p = getEffectPropertyChild(effect, envProp, "source0-alpha"))) {
682         TexEnvCombine::SourceParam source = TexEnvCombine::TEXTURE;
683         findAttr(sourceParams, p, source);
684         result->setSource0_Alpha(source);
685     }
686     if ((p = getEffectPropertyChild(effect, envProp, "source1-alpha"))) {
687         TexEnvCombine::SourceParam source = TexEnvCombine::PREVIOUS;
688         findAttr(sourceParams, p, source);
689         result->setSource1_Alpha(source);
690     }
691     if ((p = getEffectPropertyChild(effect, envProp, "source2-alpha"))) {
692         TexEnvCombine::SourceParam source = TexEnvCombine::CONSTANT;
693         findAttr(sourceParams, p, source);
694         result->setSource2_Alpha(source);
695     }
696     if ((p = getEffectPropertyChild(effect, envProp, "operand0-rgb"))) {
697         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_COLOR;
698         findAttr(operandParams, p, op);
699         result->setOperand0_RGB(op);
700     }
701     if ((p = getEffectPropertyChild(effect, envProp, "operand1-rgb"))) {
702         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_COLOR;
703         findAttr(operandParams, p, op);
704         result->setOperand1_RGB(op);
705     }
706     if ((p = getEffectPropertyChild(effect, envProp, "operand2-rgb"))) {
707         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_ALPHA;
708         findAttr(operandParams, p, op);
709         result->setOperand2_RGB(op);
710     }
711     if ((p = getEffectPropertyChild(effect, envProp, "operand0-alpha"))) {
712         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_ALPHA;
713         findAttr(operandParams, p, op);
714         result->setOperand0_Alpha(op);
715     }
716     if ((p = getEffectPropertyChild(effect, envProp, "operand1-alpha"))) {
717         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_ALPHA;
718         findAttr(operandParams, p, op);
719         result->setOperand1_Alpha(op);
720     }
721     if ((p = getEffectPropertyChild(effect, envProp, "operand2-alpha"))) {
722         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_ALPHA;
723         findAttr(operandParams, p, op);
724         result->setOperand2_Alpha(op);
725     }
726     if ((p = getEffectPropertyChild(effect, envProp, "scale-rgb"))) {
727         result->setScale_RGB(p->getValue<float>());
728     }
729     if ((p = getEffectPropertyChild(effect, envProp, "scale-alpha"))) {
730         result->setScale_Alpha(p->getValue<float>());
731     }
732 #if 0
733     if ((p = getEffectPropertyChild(effect, envProp, "constant-color"))) {
734         SGVec4d color = p->getValue<SGVec4d>();
735         result->setConstantColor(toOsg(color));
736     } else if ((p = getEffectPropertyChild(effect, envProp,
737                                            "light-direction"))) {
738         SGVec3d direction = p->getValue<SGVec3d>();
739         result->setConstantColorAsLightDirection(toOsg(direction));
740     }
741 #endif
742     const SGPropertyNode* colorNode = envProp->getChild("constant-color");
743     if (colorNode)
744         initFromParameters(effect, colorNode, result,
745                            &TexEnvCombine::setConstantColor, colorFields,
746                            options);
747     return result;
748 }
749
750 EffectNameValue<TexGen::Mode> tgenModeInit[] =
751 {
752     { "object-linear", TexGen::OBJECT_LINEAR},
753     { "eye-linear", TexGen::EYE_LINEAR},
754     { "sphere-map", TexGen::SPHERE_MAP},
755     { "normal-map", TexGen::NORMAL_MAP},
756     { "reflection-map", TexGen::REFLECTION_MAP}
757 };
758
759 EffectPropertyMap<TexGen::Mode> tgenModes(tgenModeInit);
760
761 EffectNameValue<TexGen::Coord> tgenCoordInit[] =
762 {
763     {"s", TexGen::S},
764     {"t", TexGen::T},
765     {"r", TexGen::R},
766     {"q", TexGen::Q}
767 };
768
769 EffectPropertyMap<TexGen::Coord> tgenCoords(tgenCoordInit);
770
771 TexGen* buildTexGen(Effect* effect, const SGPropertyNode* tgenProp)
772 {
773     if (!isAttributeActive(effect, tgenProp))
774         return 0;
775     TexGen* result = new TexGen;
776     TexGen::Mode mode = TexGen::OBJECT_LINEAR;
777     findAttr(tgenModes, getEffectPropertyChild(effect, tgenProp, "mode"), mode);
778     result->setMode(mode);
779     const SGPropertyNode* planesNode = tgenProp->getChild("planes");
780     if (planesNode) {
781         for (int i = 0; i < planesNode->nChildren(); ++i) {
782             const SGPropertyNode* planeNode = planesNode->getChild(i);
783             TexGen::Coord coord;
784             findAttr(tgenCoords, planeNode->getName(), coord);
785             const SGPropertyNode* realNode
786                 = getEffectPropertyNode(effect, planeNode);
787             SGVec4d plane = realNode->getValue<SGVec4d>();
788             result->setPlane(coord, toOsg(plane));
789         }
790     }
791     return result;
792 }
793
794 bool makeTextureParameters(SGPropertyNode* paramRoot, const StateSet* ss)
795 {
796     SGPropertyNode* texUnit = makeChild(paramRoot, "texture");
797     const Texture* tex = getStateAttribute<Texture>(0, ss);
798     const Texture2D* texture = dynamic_cast<const Texture2D*>(tex);
799     makeChild(texUnit, "unit")->setValue(0);
800     if (!tex) {
801         // The default shader-based technique ignores active
802         makeChild(texUnit, "active")->setValue(false);
803         return false;
804     }
805     const Image* image = texture->getImage();
806     string imageName;
807     if (image) {
808         imageName = image->getFileName();
809     } else {
810         makeChild(texUnit, "active")->setValue(false);
811         makeChild(texUnit, "type")->setValue("white");
812         return false;
813     }
814     makeChild(texUnit, "active")->setValue(true);
815     makeChild(texUnit, "type")->setValue("2d");
816     string filter = findName(filterModes,
817                              texture->getFilter(Texture::MIN_FILTER));
818     string magFilter = findName(filterModes,
819                              texture->getFilter(Texture::MAG_FILTER));
820     string wrapS = findName(wrapModes, texture->getWrap(Texture::WRAP_S));
821     string wrapT = findName(wrapModes, texture->getWrap(Texture::WRAP_T));
822     string wrapR = findName(wrapModes, texture->getWrap(Texture::WRAP_R));
823     makeChild(texUnit, "image")->setStringValue(imageName);
824     makeChild(texUnit, "filter")->setStringValue(filter);
825     makeChild(texUnit, "mag-filter")->setStringValue(magFilter);
826     makeChild(texUnit, "wrap-s")->setStringValue(wrapS);
827     makeChild(texUnit, "wrap-t")->setStringValue(wrapT);
828     makeChild(texUnit, "wrap-r")->setStringValue(wrapR);
829     return true;
830 }
831
832 class GBufferBuilder : public TextureBuilder
833 {
834 public:
835     GBufferBuilder() {}
836     Texture* build(Effect* effect, Pass* pass, const SGPropertyNode*,
837                    const SGReaderWriterOptions* options);
838 private:
839     string buffer;
840 };
841
842 class BufferNameChangeListener : public SGPropertyChangeListener, public InitializeWhenAdded,
843       public Effect::Updater {
844 public:
845     BufferNameChangeListener(Pass* p, int u, const std::string& pn) : pass(p), unit(u)
846     {
847         propName = new std::string(pn);
848     }
849     ~BufferNameChangeListener()
850     {
851         delete propName;
852         propName = 0;
853     }
854     void valueChanged(SGPropertyNode* node)
855     {
856         const char* buffer = node->getStringValue();
857         pass->setBufferUnit(unit, buffer);
858     }
859     void initOnAddImpl(Effect* effect, SGPropertyNode* propRoot)
860     {
861         SGPropertyNode* listenProp = makeNode(propRoot, *propName);
862         delete propName;
863         propName = 0;
864         if (listenProp)
865             listenProp->addChangeListener(this, true);
866     }
867
868 private:
869     ref_ptr<Pass> pass;
870     int unit;
871     std::string* propName;
872 };
873
874 Texture* GBufferBuilder::build(Effect* effect, Pass* pass, const SGPropertyNode* prop,
875                                     const SGReaderWriterOptions* options)
876 {
877     int unit = 0;
878     const SGPropertyNode* pUnit = prop->getChild("unit");
879     if (pUnit) {
880         unit = pUnit->getValue<int>();
881     } else {
882         SG_LOG(SG_INPUT, SG_ALERT, "no texture unit");
883     }
884     const SGPropertyNode* nameProp = getEffectPropertyChild(effect, prop,
885                                                             "name");
886     if (!nameProp)
887         return 0;
888
889     if (nameProp->nChildren() == 0) {
890         buffer = nameProp->getStringValue();
891         pass->setBufferUnit( unit, buffer );
892     } else {
893         std::string propName = getGlobalProperty(nameProp, options);
894         BufferNameChangeListener* listener = new BufferNameChangeListener(pass, unit, propName);
895         effect->addUpdater(listener);
896     }
897
898     // Return white for now. Would be overridden in Technique::ProcessDrawable
899     return StateAttributeFactory::instance()->getWhiteTexture();
900 }
901
902 namespace
903 {
904     TextureBuilder::Registrar installBuffer("buffer", new GBufferBuilder);
905 }
906
907 }