]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/ReaderWriterSPT.cxx
spt: The bucket size case is already handled above.
[simgear.git] / simgear / scene / tgdb / ReaderWriterSPT.cxx
1 // ReaderWriterSPT.cxx -- Provide a paged database for flightgear scenery.
2 //
3 // Copyright (C) 2010 - 2013  Mathias Froehlich
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, MA  02110-1301, USA.
18 //
19
20 #ifdef HAVE_CONFIG_H
21 #  include <simgear_config.h>
22 #endif
23
24 #include "ReaderWriterSPT.hxx"
25
26 #include <cassert>
27
28 #include <osg/CullFace>
29 #include <osg/PagedLOD>
30 #include <osg/MatrixTransform>
31 #include <osg/Texture2D>
32
33 #include <osgDB/FileNameUtils>
34 #include <osgDB/FileUtils>
35 #include <osgDB/ReadFile>
36
37 #include <simgear/scene/util/OsgMath.hxx>
38
39 #include "BucketBox.hxx"
40
41 namespace simgear {
42
43 // Cull away tiles that we watch from downside
44 struct ReaderWriterSPT::CullCallback : public osg::NodeCallback {
45     virtual ~CullCallback()
46     { }
47     virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
48     {
49         const osg::BoundingSphere& nodeBound = node->getBound();
50         // If the bounding sphere of the node is empty, there is nothing to do
51         if (!nodeBound.valid())
52             return;
53
54         // Culling away tiles that we look at from the downside.
55         // This is done by computing the maximum distance we can
56         // see something from the current eyepoint. If the sphere
57         // that is defined by this radius does no intersects the
58         // nodes sphere, then this tile is culled away.
59         // Computing this radius happens by two rectangular triangles:
60         // Let r be the view point. rmin is the minimum radius we find
61         // a ground surface we need to look above. rmax is the
62         // maximum object radius we expect any object.
63         //
64         //    d1   d2
65         //  x----x----x
66         //  r\  rmin /rmax
67         //    \  |  /
68         //     \ | /
69         //      \|/
70         //
71         // The distance from the eyepoint to the point
72         // where the line of sight is perpandicular to
73         // the radius vector with minimal height is
74         // d1 = sqrt(r^2 - rmin^2).
75         // The distance from the point where the line of sight
76         // is perpandicular to the radius vector with minimal height
77         // to the highest possible object on earth with radius rmax is 
78         // d2 = sqrt(rmax^2 - rmin^2).
79         // So the maximum distance we can see something on the earth
80         // from a viewpoint r is
81         // d = d1 + d2
82
83         // This is the equatorial earth radius minus 450m,
84         // little lower than Dead Sea.
85         float rmin = 6378137 - 450;
86         float rmin2 = rmin*rmin;
87         // This is the equatorial earth radius plus 9000m,
88         // little higher than Mount Everest.
89         float rmax = 6378137 + 9000;
90         float rmax2 = rmax*rmax;
91
92         // Check if we are looking from below any ground
93         osg::Vec3 viewPoint = nv->getViewPoint();
94         // blow the viewpoint up to a spherical earth with equatorial radius:
95         osg::Vec3 sphericViewPoint = viewPoint;
96         sphericViewPoint[2] *= 1.0033641;
97         float r2 = sphericViewPoint.length2();
98         if (r2 <= rmin2)
99             return;
100
101         // Due to this line of sight computation, the visible tiles
102         // are limited to be within a sphere with radius d1 + d2.
103         float d1 = sqrtf(r2 - rmin2);
104         float d2 = sqrtf(rmax2 - rmin2);
105         // Note that we again base the sphere around elliptic view point,
106         // but use the radius from the spherical computation.
107         if (!nodeBound.intersects(osg::BoundingSphere(viewPoint, d1 + d2)))
108             return;
109
110         traverse(node, nv);
111     }
112 };
113
114 ReaderWriterSPT::ReaderWriterSPT()
115 {
116     supportsExtension("spt", "SimGear paged terrain meta database.");
117 }
118
119 ReaderWriterSPT::~ReaderWriterSPT()
120 {
121 }
122
123 const char*
124 ReaderWriterSPT::className() const
125 {
126     return "simgear::ReaderWriterSPT";
127 }
128
129 osgDB::ReaderWriter::ReadResult
130 ReaderWriterSPT::readObject(const std::string& fileName, const osgDB::Options* options) const
131 {
132     // We get called with different extensions. To make sure search continues,
133     // we need to return FILE_NOT_HANDLED in this case.
134     if (osgDB::getLowerCaseFileExtension(fileName) != "spt")
135         return ReadResult(ReadResult::FILE_NOT_HANDLED);
136     if (fileName != "state.spt")
137         return ReadResult(ReadResult::FILE_NOT_FOUND);
138
139     osg::StateSet* stateSet = new osg::StateSet;
140     stateSet->setAttributeAndModes(new osg::CullFace);
141
142     std::string imageFileName = options->getPluginStringData("SimGear::FG_WORLD_TEXTURE");
143     if (imageFileName.empty()) {
144         imageFileName = options->getPluginStringData("SimGear::FG_ROOT");
145         imageFileName = osgDB::concatPaths(imageFileName, "Textures");
146         imageFileName = osgDB::concatPaths(imageFileName, "Globe");
147         imageFileName = osgDB::concatPaths(imageFileName, "world.topo.bathy.200407.3x4096x2048.png");
148     }
149     if (osg::Image* image = osgDB::readImageFile(imageFileName, options)) {
150         osg::Texture2D* texture = new osg::Texture2D;
151         texture->setImage(image);
152         texture->setWrap(osg::Texture2D::WRAP_S, osg::Texture2D::REPEAT);
153         texture->setWrap(osg::Texture2D::WRAP_T, osg::Texture2D::CLAMP);
154         stateSet->setTextureAttributeAndModes(0, texture);
155     }
156
157     return stateSet;
158 }
159
160 osgDB::ReaderWriter::ReadResult
161 ReaderWriterSPT::readNode(const std::string& fileName, const osgDB::Options* options) const
162 {
163     // The file name without path and without the spt extension
164     std::string strippedFileName = osgDB::getStrippedName(fileName);
165     if (strippedFileName == "earth")
166         return ReadResult(createTree(BucketBox(-180, -90, 360, 180), options, true));
167
168     std::stringstream ss(strippedFileName);
169     BucketBox bucketBox;
170     ss >> bucketBox;
171     if (ss.fail())
172         return ReadResult::FILE_NOT_FOUND;
173
174     BucketBox bucketBoxList[2];
175     unsigned bucketBoxListSize = bucketBox.periodicSplit(bucketBoxList);
176     if (bucketBoxListSize == 0)
177         return ReadResult::FILE_NOT_FOUND;
178
179     if (bucketBoxListSize == 1)
180         return ReadResult(createTree(bucketBoxList[0], options, true));
181
182     assert(bucketBoxListSize == 2);
183     osg::ref_ptr<osg::Group> group = new osg::Group;
184     group->addChild(createTree(bucketBoxList[0], options, true));
185     group->addChild(createTree(bucketBoxList[1], options, true));
186     return ReadResult(group);
187 }
188
189 osg::ref_ptr<osg::Node>
190 ReaderWriterSPT::createTree(const BucketBox& bucketBox, const osgDB::Options* options, bool topLevel) const
191 {
192     if (bucketBox.getIsBucketSize()) {
193         std::string fileName;
194         fileName = bucketBox.getBucket().gen_index_str() + std::string(".stg");
195         return osgDB::readRefNodeFile(fileName, options);
196     } else if (!topLevel && bucketBox.getStartLevel() == 3) {
197         // We want an other level of indirection for paging
198         // Here we get about 12x12 deg tiles
199         return createPagedLOD(bucketBox, options);
200     } else if (!topLevel && bucketBox.getStartLevel() == 5) {
201         // We want an other level of indirection for paging
202         // Here we get about 2x2 deg tiles
203         return createPagedLOD(bucketBox, options);
204     } else if (!topLevel && bucketBox.getStartLevel() == 7) {
205         // We want an other level of indirection for paging
206         // Here we get about 0.5x0.5 deg tiles
207         return createPagedLOD(bucketBox, options);
208     } else {
209         BucketBox bucketBoxList[100];
210         unsigned numTiles = bucketBox.getSubDivision(bucketBoxList, 100);
211         if (numTiles == 0)
212             return 0;
213
214         if (numTiles == 1)
215             return createTree(bucketBoxList[0], options, false);
216
217         osg::ref_ptr<osg::Group> group = new osg::Group;
218         for (unsigned i = 0; i < numTiles; ++i) {
219             osg::ref_ptr<osg::Node> node = createTree(bucketBoxList[i], options, false);
220             if (!node.valid())
221                 continue;
222             group->addChild(node.get());
223         }
224         if (!group->getNumChildren())
225             return 0;
226
227         return group;
228     }
229 }
230
231 osg::ref_ptr<osg::Node>
232 ReaderWriterSPT::createPagedLOD(const BucketBox& bucketBox, const osgDB::Options* options) const
233 {
234     osg::PagedLOD* pagedLOD = new osg::PagedLOD;
235
236     pagedLOD->setCenterMode(osg::PagedLOD::USER_DEFINED_CENTER);
237     SGSpheref sphere = bucketBox.getBoundingSphere();
238     pagedLOD->setCenter(toOsg(sphere.getCenter()));
239     pagedLOD->setRadius(sphere.getRadius());
240
241     pagedLOD->setCullCallback(new CullCallback);
242
243     osg::ref_ptr<osgDB::Options> localOptions;
244     localOptions = static_cast<osgDB::Options*>(options->clone(osg::CopyOp()));
245     // FIXME:
246     // The particle systems have nodes with culling disabled.
247     // PagedLOD nodes with childnodes like this will never expire.
248     // So, for now switch them off.
249     localOptions->setPluginStringData("SimGear::PARTICLESYSTEM", "OFF");
250     pagedLOD->setDatabaseOptions(localOptions.get());
251         
252     float range = 3*sphere.getRadius();
253
254     // Add the static sea level textured shell
255     osg::ref_ptr<osg::Node> tile = createSeaLevelTile(bucketBox, options);
256     if (tile.valid())
257         pagedLOD->addChild(tile.get(), range, std::numeric_limits<float>::max());
258
259     // Add the paged file name that creates the subtrees on demand
260     std::stringstream ss;
261     ss << bucketBox << ".spt";
262     pagedLOD->setFileName(pagedLOD->getNumChildren(), ss.str());
263     pagedLOD->setRange(pagedLOD->getNumChildren(), 0.0, range);
264
265     return pagedLOD;
266 }
267
268 osg::ref_ptr<osg::Node>
269 ReaderWriterSPT::createSeaLevelTile(const BucketBox& bucketBox, const osgDB::Options* options) const
270 {
271     if (options->getPluginStringData("SimGear::FG_EARTH") != "ON")
272         return 0;
273
274     SGSpheref sphere = bucketBox.getBoundingSphere();
275     osg::Matrixd transform;
276     transform.makeTranslate(toOsg(-sphere.getCenter()));
277
278     osg::Vec3Array* vertices = new osg::Vec3Array;
279     osg::Vec3Array* normals = new osg::Vec3Array;
280     osg::Vec2Array* texCoords = new osg::Vec2Array;
281         
282     unsigned widthLevel = bucketBox.getWidthLevel();
283     unsigned heightLevel = bucketBox.getHeightLevel();
284
285     unsigned incx = bucketBox.getWidthIncrement(widthLevel + 2);
286     incx = std::min(incx, bucketBox.getSize(0));
287     for (unsigned i = 0; incx != 0;) {
288         unsigned incy = bucketBox.getHeightIncrement(heightLevel + 2);
289         incy = std::min(incy, bucketBox.getSize(1));
290         for (unsigned j = 0; incy != 0;) {
291             SGVec3f v[6], n[6];
292             SGVec2f t[6];
293             unsigned num = bucketBox.getTileTriangles(i, j, incx, incy, v, n, t);
294             for (unsigned k = 0; k < num; ++k) {
295                 vertices->push_back(transform.preMult(toOsg(v[k])));
296                 normals->push_back(toOsg(n[k]));
297                 texCoords->push_back(toOsg(t[k]));
298             }
299             j += incy;
300             incy = std::min(incy, bucketBox.getSize(1) - j);
301         }
302         i += incx;
303         incx = std::min(incx, bucketBox.getSize(0) - i);
304     }
305         
306     osg::Vec4Array* colors = new osg::Vec4Array;
307     colors->push_back(osg::Vec4(1, 1, 1, 1));
308         
309     osg::Geometry* geometry = new osg::Geometry;
310     geometry->setVertexArray(vertices);
311     geometry->setNormalArray(normals);
312     geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
313     geometry->setColorArray(colors);
314     geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
315     geometry->setTexCoordArray(0, texCoords);
316         
317     osg::DrawArrays* drawArrays = new osg::DrawArrays(osg::DrawArrays::TRIANGLES, 0, vertices->size());
318     drawArrays->setDataVariance(osg::Object::STATIC);
319     geometry->addPrimitiveSet(drawArrays);
320         
321     osg::Geode* geode = new osg::Geode;
322     geode->setDataVariance(osg::Object::STATIC);
323     geode->addDrawable(geometry);
324     osg::ref_ptr<osg::StateSet> stateSet = getLowLODStateSet(options);
325     geode->setStateSet(stateSet.get());
326
327     transform.makeTranslate(toOsg(sphere.getCenter()));
328     osg::MatrixTransform* matrixTransform = new osg::MatrixTransform(transform);
329     matrixTransform->setDataVariance(osg::Object::STATIC);
330     matrixTransform->addChild(geode);
331
332     return matrixTransform;
333 }
334
335 osg::ref_ptr<osg::StateSet>
336 ReaderWriterSPT::getLowLODStateSet(const osgDB::Options* options) const
337 {
338     osg::ref_ptr<osgDB::Options> localOptions;
339     localOptions = static_cast<osgDB::Options*>(options->clone(osg::CopyOp()));
340     localOptions->setObjectCacheHint(osgDB::Options::CACHE_ALL);
341
342     osg::ref_ptr<osg::Object> object = osgDB::readRefObjectFile("state.spt", localOptions.get());
343     if (!dynamic_cast<osg::StateSet*>(object.get()))
344         return 0;
345
346     return static_cast<osg::StateSet*>(object.get());
347 }
348
349 } // namespace simgear
350