3 * Copyright (C) 2008 Stuart Buchanan
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License as
7 * published by the Free Software Foundation; either version 2 of the
8 * License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
27 #include <boost/tuple/tuple_comparison.hpp>
29 #include <osg/AlphaFunc>
30 #include <osg/Billboard>
31 #include <osg/BlendFunc>
33 #include <osg/Geometry>
34 #include <osg/Material>
36 #include <osg/MatrixTransform>
38 #include <osg/StateSet>
39 #include <osg/Texture2D>
42 #include <osgDB/ReadFile>
43 #include <osgDB/FileUtils>
45 #include <simgear/misc/sg_path.hxx>
46 #include <simgear/scene/util/QuadTreeBuilder.hxx>
47 #include <simgear/scene/util/RenderConstants.hxx>
48 #include <simgear/scene/util/StateAttributeFactory.hxx>
50 #include "ShaderGeometry.hxx"
51 #include "TreeBin.hxx"
53 #define SG_TREE_QUAD_TREE_DEPTH 3
55 // Comments from Tim Moore:
56 // Some work remains for this code. Stuart's enhancement for multiple
57 // textures per forest should be integrated. We should try to use one
58 // ShaderGeometry for *all* the trees in the scene graph and do the
59 // rotation and scale with a MatrixTransform above the trees quad
60 // tree. The positions would of course have to be transformed by the
61 // inverse of that transform. Also, we should investigate whether it
62 // would be better to instantiate trees as polygons in a osg::Geometry
63 // object instead of using the ShaderGeometry instancing technique.
71 typedef boost::tuple<float, float, int> ForestTuple;
72 typedef std::map<ForestTuple, ref_ptr<Geometry> > OrthQuadMap;
74 osg::Geometry* createOrthQuads(float w, float h, int varieties, const osg::Matrix& rotate)
76 static OrthQuadMap orthQuadMap;
77 OrthQuadMap::iterator giter
78 = orthQuadMap.find(ForestTuple(w, h, varieties));
79 if (giter != orthQuadMap.end())
80 return giter->second.get();
82 //const osg::Vec3& pos = osg::Vec3(0.0f,0.0f,0.0f),
84 // Create front and back polygons so we don't need to screw around
85 // with two-sided lighting in the shader.
86 osg::Vec3Array& v = *(new osg::Vec3Array(8));
87 osg::Vec3Array& n = *(new osg::Vec3Array(8));
88 osg::Vec2Array& t = *(new osg::Vec2Array(8));
92 v[0].set(0.0f,-cw,0.0f);
93 v[1].set(0.0f, cw,0.0f);
97 v[4].set(-cw,0.0f,0.0f);
98 v[5].set( cw,0.0f,0.0f);
100 v[7].set(-cw,0.0f,h);
102 // The texture coordinate range is not the
103 // entire coordinate space - as the texture
104 // has a number of different trees on it.
105 float tx = 1.0f/varieties;
117 // For now the normal is normal to the quad. If we want to get
118 // fancier and approximate a cylindrical tree or something, then
119 // we would really want more geometry.
120 std::fill(n.begin(), n.begin() + 4, Vec3f(1.0f, 0.0f, 0.0f));
121 std::fill(n.begin() + 4, n.end(), Vec3f(0.0f, -1.0f, 0.0f));
122 for (unsigned int i = 0; i < 8; i++) {
123 v[i] = v[i] * rotate;
124 // Should be the inverse transpose, but assume that rotate is
126 n[i] = n[i] * rotate;
129 osg::Geometry *geom = new osg::Geometry;
131 geom->setVertexArray(&v);
132 geom->setTexCoordArray(0, &t);
133 geom->setNormalArray(&n);
134 geom->setNormalBinding(Geometry::BIND_PER_VERTEX);
135 // No color for now; that's used to pass the position.
136 geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,8));
138 orthQuadMap.insert(std::make_pair(ForestTuple(w, h, varieties), geom));
142 static char vertexShaderSource[] =
143 "varying float fogFactor;\n"
144 "attribute float textureIndex;\n"
148 " gl_TexCoord[0] = gl_MultiTexCoord0 + vec4(textureIndex, 0.0, 0.0, 0.0);\n"
149 " vec3 position = gl_Vertex.xyz * gl_Color.w + gl_Color.xyz;\n"
150 " gl_Position = gl_ModelViewProjectionMatrix * vec4(position,1.0);\n"
151 " vec3 ecPosition = vec3(gl_ModelViewMatrix * vec4(position, 1.0));\n"
152 " float n = dot(normalize(gl_LightSource[0].position.xyz), normalize(-ecPosition));\n"
153 " vec3 diffuse = gl_FrontMaterial.diffuse.rgb * max(0.1, n);\n"
154 " vec4 ambientColor = gl_FrontLightModelProduct.sceneColor + gl_LightSource[0].ambient * gl_FrontMaterial.ambient;\n"
155 " gl_FrontColor = ambientColor + gl_LightSource[0].diffuse * vec4(diffuse, 1.0);\n"
156 " gl_BackColor = gl_FrontColor;\n"
157 " float fogCoord = abs(ecPosition.z);\n"
158 " fogFactor = exp( -gl_Fog.density * gl_Fog.density * fogCoord * fogCoord);\n"
159 " fogFactor = clamp(fogFactor, 0.0, 1.0);\n"
162 static char fragmentShaderSource[] =
163 "uniform sampler2D baseTexture; \n"
164 "varying float fogFactor;\n"
168 " vec4 base = texture2D( baseTexture, gl_TexCoord[0].st);\n"
169 " vec4 finalColor = base * gl_Color;\n"
170 " gl_FragColor = mix(gl_Fog.color, finalColor, fogFactor );\n"
173 typedef std::map<std::string, osg::ref_ptr<StateSet> > StateSetMap;
175 static StateSetMap treeTextureMap;
177 // Helper classes for creating the quad tree
182 MakeTreesLeaf(float range, Geometry* geometry, int varieties) :
183 _range(range), _geometry(geometry), _varieties(varieties)
185 MakeTreesLeaf(const MakeTreesLeaf& rhs) :
186 _range(rhs._range), _geometry(rhs._geometry), _varieties(rhs._varieties) {}
187 LOD* operator() () const
189 LOD* result = new LOD;
190 Geode* geode = new Geode;
191 ShaderGeometry* sg = new ShaderGeometry(_varieties);
192 sg->setGeometry(_geometry);
193 geode->addDrawable(sg);
194 result->addChild(geode, 0, _range);
202 struct AddTreesLeafObject
204 void operator() (LOD* lod, const TreeBin::Tree& tree) const
206 Geode* geode = static_cast<Geode*>(lod->getChild(0));
208 = static_cast<ShaderGeometry*>(geode->getDrawable(0));
215 Vec3 operator() (const TreeBin::Tree& tree) const
217 return tree.position.osg();
221 typedef QuadTreeBuilder<LOD*, TreeBin::Tree, MakeTreesLeaf, AddTreesLeafObject,
222 GetTreeCoord> ShaderGeometryQuadtree;
225 struct TreeTransformer
227 TreeTransformer(Matrix& mat_) : mat(mat_) {}
228 TreeBin::Tree operator()(const TreeBin::Tree& tree) const
230 const Vec3& pos = tree.position.osg();
231 return TreeBin::Tree(SGVec3f(pos * mat), tree.texture_index,
237 // This actually returns a MatrixTransform node. If we rotate the whole
238 // forest into the local Z-up coordinate system we can reuse the
239 // primitive tree geometry for all the forests of the same type.
241 osg::Group* createForest(TreeBin& forest, const osg::Matrix& transform)
243 Matrix transInv = Matrix::inverse(transform);
245 // Set up some shared structures.
246 osg::Geometry* shared_geometry = createOrthQuads(forest.width,
248 forest.texture_varieties,
251 ref_ptr<Group> group;
253 osg::StateSet* stateset = 0;
254 StateSetMap::iterator iter = treeTextureMap.find(forest.texture);
255 if (iter == treeTextureMap.end()) {
256 osg::Texture2D *tex = new osg::Texture2D;
257 tex->setWrap( osg::Texture2D::WRAP_S, osg::Texture2D::CLAMP );
258 tex->setWrap( osg::Texture2D::WRAP_T, osg::Texture2D::CLAMP );
259 tex->setImage(osgDB::readImageFile(forest.texture));
261 static ref_ptr<AlphaFunc> alphaFunc;
262 static ref_ptr<Program> program;
263 static ref_ptr<Uniform> baseTextureSampler;
264 static ref_ptr<Material> material;
266 stateset = new osg::StateSet;
267 stateset->setTextureAttributeAndModes(0, tex, osg::StateAttribute::ON );
268 stateset->setRenderBinDetails(RANDOM_OBJECTS_BIN, "DepthSortedBin");
269 if (!program.valid()) {
270 alphaFunc = new AlphaFunc;
271 alphaFunc->setFunction(AlphaFunc::GEQUAL,0.33f);
272 program = new Program;
273 baseTextureSampler = new osg::Uniform("baseTexture", 0);
274 Shader* vertex_shader = new Shader(Shader::VERTEX, vertexShaderSource);
275 program->addShader(vertex_shader);
276 program->addBindAttribLocation("textureIndex", 1);
278 Shader* fragment_shader = new Shader(Shader::FRAGMENT,
279 fragmentShaderSource);
280 program->addShader(fragment_shader);
281 material = new Material;
282 // DonĀ“t track vertex color
283 material->setColorMode(Material::OFF);
284 material->setAmbient(Material::FRONT_AND_BACK,
285 Vec4(1.0f, 1.0f, 1.0f, 1.0f));
286 material->setDiffuse(Material::FRONT_AND_BACK,
287 Vec4(1.0f, 1.0f, 1.0f, 1.0f));
289 stateset->setAttributeAndModes(alphaFunc.get());
290 stateset->setAttribute(program.get());
291 stateset->addUniform(baseTextureSampler.get());
292 stateset->setMode(GL_VERTEX_PROGRAM_TWO_SIDE, StateAttribute::ON);
293 stateset->setAttribute(material.get());
295 treeTextureMap.insert(StateSetMap::value_type(forest.texture,
298 stateset = iter->second.get();
300 // Now, create a quadtree for the forest.
302 ShaderGeometryQuadtree quadtree(GetTreeCoord(),
303 AddTreesLeafObject(),
304 SG_TREE_QUAD_TREE_DEPTH,
305 MakeTreesLeaf(forest.range,
307 forest.texture_varieties));
308 // Transform tree positions from the "geocentric" positions we
309 // get from the scenery polys into the local Z-up coordinate
311 std::vector<TreeBin::Tree> rotatedTrees;
312 rotatedTrees.reserve(forest._trees.size());
313 std::transform(forest._trees.begin(), forest._trees.end(),
314 std::back_inserter(rotatedTrees),
315 TreeTransformer(transInv));
316 quadtree.buildQuadTree(rotatedTrees.begin(), rotatedTrees.end());
317 group = quadtree.getRoot();
319 MatrixTransform* mt = new MatrixTransform(transform);
320 for (int i = 0; i < group->getNumChildren(); ++i)
321 mt->addChild(group->getChild(i));
322 mt->setStateSet(stateset);