]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/TreeBin.cxx
Build trees under a transform note that is rotated to Z-up.
[simgear.git] / simgear / scene / tgdb / TreeBin.cxx
1 /* -*-c++-*-
2  *
3  * Copyright (C) 2008 Stuart Buchanan
4  *
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.
9  *
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.
14  *
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,
18  * MA 02110-1301, USA.
19  *
20  */
21
22 #include <algorithm>
23 #include <vector>
24 #include <string>
25 #include <map>
26
27 #include <boost/tuple/tuple_comparison.hpp>
28
29 #include <osg/AlphaFunc>
30 #include <osg/Billboard>
31 #include <osg/BlendFunc>
32 #include <osg/Geode>
33 #include <osg/Geometry>
34 #include <osg/Material>
35 #include <osg/Math>
36 #include <osg/MatrixTransform>
37 #include <osg/Matrix>
38 #include <osg/StateSet>
39 #include <osg/Texture2D>
40 #include <osg/TexEnv>
41
42 #include <osgDB/ReadFile>
43 #include <osgDB/FileUtils>
44
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>
49
50 #include "ShaderGeometry.hxx"
51 #include "TreeBin.hxx"
52
53 #define SG_TREE_QUAD_TREE_DEPTH 3
54
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.
64
65 using namespace osg;
66
67 namespace simgear
68 {
69
70 // memoize geometry
71 typedef boost::tuple<float, float, int> ForestTuple;
72 typedef std::map<ForestTuple, ref_ptr<Geometry> > OrthQuadMap;
73
74 osg::Geometry* createOrthQuads(float w, float h, int varieties, const osg::Matrix& rotate)
75 {
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();
81
82     //const osg::Vec3& pos = osg::Vec3(0.0f,0.0f,0.0f),
83     // set up the coords
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));
89     
90     float cw = w*0.5f;
91
92     v[0].set(0.0f,-cw,0.0f);
93     v[1].set(0.0f, cw,0.0f);
94     v[2].set(0.0f, cw,h);
95     v[3].set(0.0f,-cw,h);
96
97     v[4].set(-cw,0.0f,0.0f);
98     v[5].set( cw,0.0f,0.0f);
99     v[6].set( cw,0.0f,h);
100     v[7].set(-cw,0.0f,h);
101
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;
106
107     t[0].set(0.0f,0.0f);
108     t[1].set(  tx,0.0f);
109     t[2].set(  tx,1.0f);
110     t[3].set(0.0f,1.0f);
111
112     t[4].set(0.0f,0.0f);
113     t[5].set(  tx,0.0f);
114     t[6].set(  tx,1.0f);
115     t[7].set(0.0f,1.0f);
116
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
125         // orthonormal.
126         n[i] = n[i] * rotate;     
127     }
128
129     osg::Geometry *geom = new osg::Geometry;
130
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));
137
138     orthQuadMap.insert(std::make_pair(ForestTuple(w, h, varieties), geom));
139     return geom;
140 }
141
142  static char vertexShaderSource[] = 
143     "varying float fogFactor;\n"
144     "attribute float textureIndex;\n"
145     "\n"
146     "void main(void)\n"
147     "{\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     "  vec3 N = normalize(gl_NormalMatrix * gl_Normal);\n"
153     "  vec3 diffuse = gl_FrontMaterial.diffuse.rgb * max(0.0, dot(N, gl_LightSource[0].position.xyz));\n"
154     "  vec3 backDiffuse = gl_FrontMaterial.diffuse.rgb * max(0.0, dot(-N, gl_LightSource[0].position.xyz));\n"
155     " vec4 ambientColor = gl_FrontLightModelProduct.sceneColor + gl_LightSource[0].ambient * gl_FrontMaterial.ambient;\n"
156     " gl_FrontColor = ambientColor + gl_LightSource[0].diffuse * vec4(diffuse, 1.0);\n"
157     " gl_BackColor = ambientColor + gl_LightSource[0].diffuse * vec4(backDiffuse, 1.0)\n;"
158 //    "  gl_TexCoord[0] = gl_MultiTexCoord0;\n"
159     " float fogCoord = abs(ecPosition.z);\n"
160     "  fogFactor = exp( -gl_Fog.density * gl_Fog.density * fogCoord * fogCoord);\n"
161     "  fogFactor = clamp(fogFactor, 0.0, 1.0);\n"
162     "}\n";
163
164 static char fragmentShaderSource[] = 
165     "uniform sampler2D baseTexture; \n"
166     "varying float fogFactor;\n"
167     "\n"
168     "void main(void) \n"
169     "{ \n"
170     "  vec4 base = texture2D( baseTexture, gl_TexCoord[0].st);\n"
171     "  vec4 finalColor = base * gl_Color;\n"
172     "  gl_FragColor = mix(gl_Fog.color, finalColor, fogFactor );\n"
173     "}\n";
174
175 typedef std::map<std::string, osg::ref_ptr<StateSet> > StateSetMap;
176
177 static StateSetMap treeTextureMap;
178
179 // Helper classes for creating the quad tree
180 namespace
181 {
182 struct MakeTreesLeaf
183 {
184     MakeTreesLeaf(float range, Geometry* geometry, int varieties) :
185         _range(range), _geometry(geometry), _varieties(varieties)
186     {}
187     MakeTreesLeaf(const MakeTreesLeaf& rhs) :
188         _range(rhs._range), _geometry(rhs._geometry), _varieties(rhs._varieties) {}
189     LOD* operator() () const
190     {
191         LOD* result = new LOD;
192         Geode* geode = new Geode;
193         ShaderGeometry* sg = new ShaderGeometry(_varieties);
194         sg->setGeometry(_geometry);
195         geode->addDrawable(sg);
196         result->addChild(geode, 0, _range);
197         return result;
198     }
199     float _range;
200     int _varieties;
201     Geometry* _geometry;
202 };
203
204 struct AddTreesLeafObject
205 {
206     void operator() (LOD* lod, const TreeBin::Tree& tree) const
207     {
208         Geode* geode = static_cast<Geode*>(lod->getChild(0));
209         ShaderGeometry* sg
210             = static_cast<ShaderGeometry*>(geode->getDrawable(0));
211         sg->addTree(tree);
212     }
213 };
214
215 struct GetTreeCoord
216 {
217     Vec3 operator() (const TreeBin::Tree& tree) const
218     {
219         return tree.position.osg();
220     }
221 };
222
223 typedef QuadTreeBuilder<LOD*, TreeBin::Tree, MakeTreesLeaf, AddTreesLeafObject,
224                         GetTreeCoord> ShaderGeometryQuadtree;
225 }
226
227 struct TreeTransformer
228 {
229     TreeTransformer(Matrix& mat_) : mat(mat_) {}
230     TreeBin::Tree operator()(const TreeBin::Tree& tree) const
231     {
232         const Vec3& pos = tree.position.osg();
233         return TreeBin::Tree(SGVec3f(pos * mat), tree.texture_index,
234                              tree.scale);
235     }
236     Matrix mat;
237 };
238
239 // This actually returns a MatrixTransform node. If we rotate the whole
240 // forest into the local Z-up coordinate system we can reuse the
241 // primitive tree geometry for all the forests of the same type.
242
243 osg::Group* createForest(TreeBin& forest, const osg::Matrix& transform)
244 {
245     Matrix transInv = Matrix::inverse(transform);
246     static Matrix ident;
247     // Set up some shared structures. 
248     osg::Geometry* shared_geometry = createOrthQuads(forest.width, 
249                                                      forest.height, 
250                                                      forest.texture_varieties,
251                                                      ident);
252
253     ref_ptr<Group> group;
254
255     osg::StateSet* stateset = 0;
256     StateSetMap::iterator iter = treeTextureMap.find(forest.texture);
257     if (iter == treeTextureMap.end()) {
258         osg::Texture2D *tex = new osg::Texture2D;
259         tex->setWrap( osg::Texture2D::WRAP_S, osg::Texture2D::CLAMP );
260         tex->setWrap( osg::Texture2D::WRAP_T, osg::Texture2D::CLAMP );
261         tex->setImage(osgDB::readImageFile(forest.texture));
262
263         static ref_ptr<AlphaFunc> alphaFunc;
264         static ref_ptr<Program> program;
265         static ref_ptr<Uniform> baseTextureSampler;
266         static ref_ptr<Material> material;
267     
268         stateset = new osg::StateSet;
269         stateset->setTextureAttributeAndModes(0, tex, osg::StateAttribute::ON );
270         stateset->setRenderBinDetails(RANDOM_OBJECTS_BIN, "DepthSortedBin");
271         if (!program.valid()) {
272             alphaFunc = new AlphaFunc;
273             alphaFunc->setFunction(AlphaFunc::GEQUAL,0.33f);
274             program  = new Program;
275             baseTextureSampler = new osg::Uniform("baseTexture", 0);
276             Shader* vertex_shader = new Shader(Shader::VERTEX, vertexShaderSource);
277             program->addShader(vertex_shader);
278             program->addBindAttribLocation("textureIndex", 1);
279
280             Shader* fragment_shader = new Shader(Shader::FRAGMENT,
281                                                  fragmentShaderSource);
282             program->addShader(fragment_shader);
283             material = new Material;
284             // DonĀ“t track vertex color
285             material->setColorMode(Material::OFF);
286             material->setAmbient(Material::FRONT_AND_BACK,
287                                  Vec4(.8f, .8f, .8f, 1.0f));
288             material->setDiffuse(Material::FRONT_AND_BACK,
289                                  Vec4(.2f, .2f, .2f, 1.0f));
290         }
291         stateset->setAttributeAndModes(alphaFunc.get());
292         stateset->setAttribute(program.get());
293         stateset->addUniform(baseTextureSampler.get());
294         stateset->setMode(GL_VERTEX_PROGRAM_TWO_SIDE, StateAttribute::ON);
295         stateset->setAttribute(material.get());
296
297         treeTextureMap.insert(StateSetMap::value_type(forest.texture,
298                                                       stateset));
299     } else {
300         stateset = iter->second.get();
301     }
302     // Now, create a quadtree for the forest.
303     {
304         ShaderGeometryQuadtree quadtree(GetTreeCoord(),
305                                         AddTreesLeafObject(),
306                                         SG_TREE_QUAD_TREE_DEPTH,
307                                         MakeTreesLeaf(forest.range,
308                                                       shared_geometry,
309                                                       forest.texture_varieties));
310         // Transform tree positions from the "geocentric" positions we
311         // get from the scenery polys into the local Z-up coordinate
312         // system.
313         std::vector<TreeBin::Tree> rotatedTrees;
314         rotatedTrees.reserve(forest._trees.size());
315         std::transform(forest._trees.begin(), forest._trees.end(),
316                        std::back_inserter(rotatedTrees),
317                        TreeTransformer(transInv));
318         quadtree.buildQuadTree(rotatedTrees.begin(), rotatedTrees.end());
319         group = quadtree.getRoot();
320     }
321     MatrixTransform* mt = new MatrixTransform(transform);
322     for (int i = 0; i < group->getNumChildren(); ++i)
323         mt->addChild(group->getChild(i));
324     mt->setStateSet(stateset);
325     return mt;
326 }
327
328 }