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