]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/TreeBin.cxx
Reduce the height of tree UV coordinates to work around mipmap issues.
[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 #ifdef HAVE_CONFIG_H
23 #  include <simgear_config.h>
24 #endif
25
26 #include <algorithm>
27 #include <vector>
28 #include <string>
29 #include <map>
30
31 #include <boost/tuple/tuple_comparison.hpp>
32
33 #include <osg/Geode>
34 #include <osg/Geometry>
35 #include <osg/Math>
36 #include <osg/MatrixTransform>
37 #include <osg/Matrix>
38 #include <osg/NodeVisitor>
39
40 #include <osgDB/ReadFile>
41 #include <osgDB/FileUtils>
42
43 #include <simgear/debug/logstream.hxx>
44 #include <simgear/math/sg_random.h>
45 #include <simgear/misc/sg_path.hxx>
46 #include <simgear/scene/material/Effect.hxx>
47 #include <simgear/scene/material/EffectGeode.hxx>
48 #include <simgear/props/props.hxx>
49 #include <simgear/scene/util/QuadTreeBuilder.hxx>
50 #include <simgear/scene/util/RenderConstants.hxx>
51 #include <simgear/scene/util/StateAttributeFactory.hxx>
52 #include <simgear/structure/OSGUtils.hxx>
53
54 #include "ShaderGeometry.hxx"
55 #include "TreeBin.hxx"
56
57 #define SG_TREE_QUAD_TREE_DEPTH 3
58 #define SG_TREE_FADE_OUT_LEVELS 10
59
60 using namespace osg;
61
62 namespace simgear
63 {
64
65 // Tree instance scheme:
66 // vertex - local position of quad vertex.
67 // normal - x y scaling, z number of varieties
68 // fog coord - rotation
69 // color - xyz of tree quad origin, replicated 4 times.
70 //
71 // The tree quad is rendered twice, with different rotations, to
72 // create the crossed tree geometry.
73
74 struct TreesBoundingBoxCallback : public Drawable::ComputeBoundingBoxCallback
75 {
76     TreesBoundingBoxCallback() {}
77     TreesBoundingBoxCallback(const TreesBoundingBoxCallback&, const CopyOp&) {}
78     META_Object(simgear, TreesBoundingBoxCallback);
79     virtual BoundingBox computeBound(const Drawable&) const;
80 };
81
82 BoundingBox
83 TreesBoundingBoxCallback::computeBound(const Drawable& drawable) const
84 {
85     BoundingBox bb;
86     const Geometry* geom = static_cast<const Geometry*>(&drawable);
87     const Vec3Array* v = static_cast<const Vec3Array*>(geom->getVertexArray());
88     const Vec3Array* pos = static_cast<const Vec3Array*>(geom->getColorArray());
89     const Vec3Array* params
90         = static_cast<const Vec3Array*>(geom->getNormalArray());
91     const FloatArray* rot
92         = static_cast<const FloatArray*>(geom->getFogCoordArray());
93     float w = (*params)[0].x();
94     float h = (*params)[0].y();
95     Geometry::PrimitiveSetList primSets = geom->getPrimitiveSetList();
96     FloatArray::const_iterator rotitr = rot->begin();
97     for (Geometry::PrimitiveSetList::const_iterator psitr = primSets.begin(),
98              psend = primSets.end();
99          psitr != psend;
100          ++psitr, ++rotitr) {
101         Matrixd trnsfrm = (Matrixd::scale(w, w, h)
102                            * Matrixd::rotate(*rotitr, Vec3(0.0f, 0.0f, 1.0f)));
103         DrawArrays* da = static_cast<DrawArrays*>(psitr->get());
104         GLint psFirst = da->getFirst();
105         GLint psEndVert = psFirst + da->getCount();
106         for (GLint i = psFirst;i < psEndVert; ++i) {
107             Vec3 pt = (*v)[i];
108             pt = pt * trnsfrm;
109             pt += (*pos)[i];
110             bb.expandBy(pt);
111         }
112     }
113     return bb;
114 }
115
116 Geometry* makeSharedTreeGeometry(int numQuads)
117 {
118     // generate a repeatable random seed
119     mt seed;
120     mt_init(&seed, unsigned(123));
121     // set up the coords
122     osg::Vec3Array* v = new osg::Vec3Array;
123     osg::Vec2Array* t = new osg::Vec2Array;
124     v->reserve(numQuads * 4);
125     t->reserve(numQuads * 4);
126     for (int i = 0; i < numQuads; ++i) {
127         // Apply a random scaling factor and texture index.
128         float h = (mt_rand(&seed) + mt_rand(&seed)) / 2.0f + 0.5f;
129         float cw = h * .5;
130         v->push_back(Vec3(0.0f, -cw, 0.0f));
131         v->push_back(Vec3(0.0f, cw, 0.0f));
132         v->push_back(Vec3(0.0f, cw, h));
133         v->push_back(Vec3(0.0f,-cw, h));
134         // The texture coordinate range is not the entire coordinate
135         // space, as the texture has a number of different trees on
136         // it. Here we assign random coordinates and let the shader
137         // choose the variety.
138         // Height isn't quite 0.25 to allow for UV map bleeding when
139         // mipmaps are generated.
140         float variety = mt_rand(&seed);
141         t->push_back(Vec2(variety, 0.0f));
142         t->push_back(Vec2(variety + 1.0f, 0.0f));
143         t->push_back(Vec2(variety + 1.0f, 0.246f));
144         t->push_back(Vec2(variety, 0.246f));
145     }
146     Geometry* result = new Geometry;
147     result->setVertexArray(v);
148     result->setTexCoordArray(0, t);
149     result->setComputeBoundingBoxCallback(new TreesBoundingBoxCallback);
150     result->setUseDisplayList(false);
151     return result;
152 }
153
154 ref_ptr<Geometry> sharedTreeGeometry;
155
156 Geometry* createTreeGeometry(float width, float height, int varieties)
157 {
158     if (!sharedTreeGeometry)
159         sharedTreeGeometry = makeSharedTreeGeometry(1600);
160     Geometry* quadGeom = simgear::clone(sharedTreeGeometry.get(),
161                                         CopyOp::SHALLOW_COPY);
162     Vec3Array* params = new Vec3Array;
163     params->push_back(Vec3(width, height, (float)varieties));
164     quadGeom->setNormalArray(params);
165     quadGeom->setNormalBinding(Geometry::BIND_OVERALL);
166     // Positions
167     quadGeom->setColorArray(new Vec3Array);
168     quadGeom->setColorBinding(Geometry::BIND_PER_VERTEX);
169     FloatArray* rotation = new FloatArray(2);
170     (*rotation)[0] = 0.0;
171     (*rotation)[1] = PI_2;
172     quadGeom->setFogCoordArray(rotation);
173     quadGeom->setFogCoordBinding(Geometry::BIND_PER_PRIMITIVE_SET);
174     // The primitive sets render the same geometry, but the second
175     // will rotated 90 degrees by the vertex shader, which uses the
176     // fog coordinate as a rotation.
177     for (int i = 0; i < 2; ++i)
178         quadGeom->addPrimitiveSet(new DrawArrays(PrimitiveSet::QUADS));
179     return quadGeom;
180 }
181
182 EffectGeode* createTreeGeode(float width, float height, int varieties)
183 {
184     EffectGeode* result = new EffectGeode;
185     result->addDrawable(createTreeGeometry(width, height, varieties));
186     return result;
187 }
188
189 void addTreeToLeafGeode(Geode* geode, const SGVec3f& p)
190 {
191     Vec3 pos = toOsg(p);
192     unsigned int numDrawables = geode->getNumDrawables();
193     Geometry* geom
194         = static_cast<Geometry*>(geode->getDrawable(numDrawables - 1));
195     Vec3Array* posArray = static_cast<Vec3Array*>(geom->getColorArray());
196     if (posArray->size()
197         >= static_cast<Vec3Array*>(geom->getVertexArray())->size()) {
198         Vec3Array* paramsArray
199             = static_cast<Vec3Array*>(geom->getNormalArray());
200         Vec3 params = (*paramsArray)[0];
201         geom = createTreeGeometry(params.x(), params.y(), params.z());
202         posArray = static_cast<Vec3Array*>(geom->getColorArray());
203         geode->addDrawable(geom);
204     }
205     posArray->insert(posArray->end(), 4, pos);
206     size_t numVerts = posArray->size();
207     for (int i = 0; i < 2; ++i) {
208         DrawArrays* primSet
209             = static_cast<DrawArrays*>(geom->getPrimitiveSet(i));
210         primSet->setCount(numVerts);
211     }
212 }
213
214 typedef std::map<std::string, osg::observer_ptr<Effect> > EffectMap;
215
216 static EffectMap treeEffectMap;
217
218 // Helper classes for creating the quad tree
219 namespace
220 {
221 struct MakeTreesLeaf
222 {
223     MakeTreesLeaf(float range, int varieties, float width, float height,
224         Effect* effect) :
225         _range(range),  _varieties(varieties),
226         _width(width), _height(height), _effect(effect) {}
227
228     MakeTreesLeaf(const MakeTreesLeaf& rhs) :
229         _range(rhs._range),
230         _varieties(rhs._varieties), _width(rhs._width), _height(rhs._height),
231         _effect(rhs._effect)
232     {}
233
234     LOD* operator() () const
235     {
236         LOD* result = new LOD;
237         
238         // Create a series of LOD nodes so trees cover decreases slightly
239         // gradually with distance from _range to 2*_range
240         for (float i = 0.0; i < SG_TREE_FADE_OUT_LEVELS; i++)
241         {        
242             EffectGeode* geode = createTreeGeode(_width, _height, _varieties);
243             geode->setEffect(_effect.get());
244             result->addChild(geode, 0, _range * (1.0 + i / (SG_TREE_FADE_OUT_LEVELS - 1.0)));
245         }
246         return result;
247     }
248     float _range;
249     int _varieties;
250     float _width;
251     float _height;
252     ref_ptr<Effect> _effect;
253 };
254
255 struct AddTreesLeafObject
256 {
257     void operator() (LOD* lod, const TreeBin::Tree& tree) const
258     {
259         Geode* geode = static_cast<Geode*>(lod->getChild(int(tree.position.x() * 10.0f) % lod->getNumChildren()));
260         addTreeToLeafGeode(geode, tree.position);
261     }
262 };
263
264 struct GetTreeCoord
265 {
266     Vec3 operator() (const TreeBin::Tree& tree) const
267     {
268         return toOsg(tree.position);
269     }
270 };
271
272 typedef QuadTreeBuilder<LOD*, TreeBin::Tree, MakeTreesLeaf, AddTreesLeafObject,
273                         GetTreeCoord> ShaderGeometryQuadtree;
274 }
275
276 struct TreeTransformer
277 {
278     TreeTransformer(Matrix& mat_) : mat(mat_) {}
279     TreeBin::Tree operator()(const TreeBin::Tree& tree) const
280     {
281         Vec3 pos = toOsg(tree.position);
282         return TreeBin::Tree(toSG(pos * mat));
283     }
284     Matrix mat;
285 };
286
287 // We may end up with a quadtree with many empty leaves. One might say
288 // that we should avoid constructing the leaves in the first place,
289 // but this node visitor tries to clean up after the fact.
290
291 struct QuadTreeCleaner : public osg::NodeVisitor
292 {
293     QuadTreeCleaner() : NodeVisitor(NodeVisitor::TRAVERSE_ALL_CHILDREN)
294     {
295     }
296     void apply(LOD& lod)
297     {
298         for (int i  = lod.getNumChildren() - 1; i >= 0; --i) {
299             EffectGeode* geode = dynamic_cast<EffectGeode*>(lod.getChild(i));
300             if (!geode)
301                 continue;
302             bool geodeEmpty = true;
303             for (unsigned j = 0; j < geode->getNumDrawables(); ++j) {
304                 const Geometry* geom = dynamic_cast<Geometry*>(geode->getDrawable(j));
305                 if (!geom) {
306                     geodeEmpty = false;
307                     break;
308                 }
309                 for (unsigned k = 0; k < geom->getNumPrimitiveSets(); k++) {
310                     const PrimitiveSet* ps = geom->getPrimitiveSet(k);
311                     if (ps->getNumIndices() > 0) {
312                         geodeEmpty = false;
313                         break;
314                     }
315                 }
316             }
317             if (geodeEmpty)
318                 lod.removeChildren(i, 1);
319         }
320     }
321 };
322
323 // This actually returns a MatrixTransform node. If we rotate the whole
324 // forest into the local Z-up coordinate system we can reuse the
325 // primitive tree geometry for all the forests of the same type.
326
327 osg::Group* createForest(SGTreeBinList& forestList, const osg::Matrix& transform,
328                          const SGReaderWriterOptions* options)
329 {
330     Matrix transInv = Matrix::inverse(transform);
331     static Matrix ident;
332     // Set up some shared structures.
333     ref_ptr<Group> group;
334     MatrixTransform* mt = new MatrixTransform(transform);
335
336     SGTreeBinList::iterator i;
337
338     for (i = forestList.begin(); i != forestList.end(); ++i) {
339         TreeBin* forest = *i;
340       
341         ref_ptr<Effect> effect;
342         EffectMap::iterator iter = treeEffectMap.find(forest->texture);
343
344         if ((iter == treeEffectMap.end())||
345             (!iter->second.lock(effect)))
346         {
347             SGPropertyNode_ptr effectProp = new SGPropertyNode;
348             makeChild(effectProp, "inherits-from")->setStringValue("Effects/tree");
349             SGPropertyNode* params = makeChild(effectProp, "parameters");
350             // emphasize n = 0
351             params->getChild("texture", 0, true)->getChild("image", 0, true)
352                 ->setStringValue(forest->texture);
353             effect = makeEffect(effectProp, true, options);
354             if (iter == treeEffectMap.end())
355                 treeEffectMap.insert(EffectMap::value_type(forest->texture, effect));
356             else
357                 iter->second = effect; // update existing, but empty observer
358         }
359
360         // Now, create a quadtree for the forest.
361         ShaderGeometryQuadtree
362             quadtree(GetTreeCoord(), AddTreesLeafObject(),
363                      SG_TREE_QUAD_TREE_DEPTH,
364                      MakeTreesLeaf(forest->range, forest->texture_varieties,
365                                    forest->width, forest->height, effect));
366         // Transform tree positions from the "geocentric" positions we
367         // get from the scenery polys into the local Z-up coordinate
368         // system.
369         std::vector<TreeBin::Tree> rotatedTrees;
370         rotatedTrees.reserve(forest->_trees.size());
371         std::transform(forest->_trees.begin(), forest->_trees.end(),
372                        std::back_inserter(rotatedTrees),
373                        TreeTransformer(transInv));
374         quadtree.buildQuadTree(rotatedTrees.begin(), rotatedTrees.end());
375         group = quadtree.getRoot();
376
377         for (size_t i = 0; i < group->getNumChildren(); ++i)
378             mt->addChild(group->getChild(i));
379             
380         delete forest;
381     }
382     
383     forestList.clear();
384     QuadTreeCleaner cleaner;
385     mt->accept(cleaner);
386     return mt;
387 }
388
389
390 }