1 // ReaderWriterSPT.cxx -- Provide a paged database for flightgear scenery.
3 // Copyright (C) 2010 - 2013 Mathias Froehlich
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, MA 02110-1301, USA.
21 # include <simgear_config.h>
24 #include "ReaderWriterSPT.hxx"
28 #include <osg/CullFace>
29 #include <osg/PagedLOD>
30 #include <osg/MatrixTransform>
31 #include <osg/Texture2D>
33 #include <osgDB/FileNameUtils>
34 #include <osgDB/FileUtils>
35 #include <osgDB/ReadFile>
37 #include <simgear/scene/util/OsgMath.hxx>
39 #include "BucketBox.hxx"
43 // Cull away tiles that we watch from downside
44 struct ReaderWriterSPT::CullCallback : public osg::NodeCallback {
45 virtual ~CullCallback()
47 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
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())
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.
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
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;
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();
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)))
114 ReaderWriterSPT::ReaderWriterSPT()
116 supportsExtension("spt", "SimGear paged terrain meta database.");
119 ReaderWriterSPT::~ReaderWriterSPT()
124 ReaderWriterSPT::className() const
126 return "simgear::ReaderWriterSPT";
129 osgDB::ReaderWriter::ReadResult
130 ReaderWriterSPT::readObject(const std::string& fileName, const osgDB::Options* options) const
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);
139 osg::StateSet* stateSet = new osg::StateSet;
140 stateSet->setAttributeAndModes(new osg::CullFace);
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");
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);
160 osgDB::ReaderWriter::ReadResult
161 ReaderWriterSPT::readNode(const std::string& fileName, const osgDB::Options* options) const
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));
168 std::stringstream ss(strippedFileName);
172 return ReadResult::FILE_NOT_FOUND;
174 BucketBox bucketBoxList[2];
175 unsigned bucketBoxListSize = bucketBox.periodicSplit(bucketBoxList);
176 if (bucketBoxListSize == 0)
177 return ReadResult::FILE_NOT_FOUND;
179 if (bucketBoxListSize == 1)
180 return ReadResult(createTree(bucketBoxList[0], options, true));
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);
189 osg::ref_ptr<osg::Node>
190 ReaderWriterSPT::createTree(const BucketBox& bucketBox, const osgDB::Options* options, bool topLevel) const
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);
209 BucketBox bucketBoxList[100];
210 unsigned numTiles = bucketBox.getSubDivision(bucketBoxList, 100);
215 return createTree(bucketBoxList[0], options, false);
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);
222 group->addChild(node.get());
224 if (!group->getNumChildren())
231 osg::ref_ptr<osg::Node>
232 ReaderWriterSPT::createPagedLOD(const BucketBox& bucketBox, const osgDB::Options* options) const
234 osg::PagedLOD* pagedLOD = new osg::PagedLOD;
236 pagedLOD->setCenterMode(osg::PagedLOD::USER_DEFINED_CENTER);
237 SGSpheref sphere = bucketBox.getBoundingSphere();
238 pagedLOD->setCenter(toOsg(sphere.getCenter()));
239 pagedLOD->setRadius(sphere.getRadius());
241 pagedLOD->setCullCallback(new CullCallback);
243 osg::ref_ptr<osgDB::Options> localOptions;
244 localOptions = static_cast<osgDB::Options*>(options->clone(osg::CopyOp()));
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());
252 float range = 3*sphere.getRadius();
254 // Add the static sea level textured shell
255 osg::ref_ptr<osg::Node> tile = createSeaLevelTile(bucketBox, options);
257 pagedLOD->addChild(tile.get(), range, std::numeric_limits<float>::max());
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);
268 osg::ref_ptr<osg::Node>
269 ReaderWriterSPT::createSeaLevelTile(const BucketBox& bucketBox, const osgDB::Options* options) const
271 if (options->getPluginStringData("SimGear::FG_EARTH") != "ON")
274 SGSpheref sphere = bucketBox.getBoundingSphere();
275 osg::Matrixd transform;
276 transform.makeTranslate(toOsg(-sphere.getCenter()));
278 osg::Vec3Array* vertices = new osg::Vec3Array;
279 osg::Vec3Array* normals = new osg::Vec3Array;
280 osg::Vec2Array* texCoords = new osg::Vec2Array;
282 unsigned widthLevel = bucketBox.getWidthLevel();
283 unsigned heightLevel = bucketBox.getHeightLevel();
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;) {
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]));
300 incy = std::min(incy, bucketBox.getSize(1) - j);
303 incx = std::min(incx, bucketBox.getSize(0) - i);
306 osg::Vec4Array* colors = new osg::Vec4Array;
307 colors->push_back(osg::Vec4(1, 1, 1, 1));
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);
317 osg::DrawArrays* drawArrays = new osg::DrawArrays(osg::DrawArrays::TRIANGLES, 0, vertices->size());
318 drawArrays->setDataVariance(osg::Object::STATIC);
319 geometry->addPrimitiveSet(drawArrays);
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());
327 transform.makeTranslate(toOsg(sphere.getCenter()));
328 osg::MatrixTransform* matrixTransform = new osg::MatrixTransform(transform);
329 matrixTransform->setDataVariance(osg::Object::STATIC);
330 matrixTransform->addChild(geode);
332 return matrixTransform;
335 osg::ref_ptr<osg::StateSet>
336 ReaderWriterSPT::getLowLODStateSet(const osgDB::Options* options) const
338 osg::ref_ptr<osgDB::Options> localOptions;
339 localOptions = static_cast<osgDB::Options*>(options->clone(osg::CopyOp()));
340 localOptions->setObjectCacheHint(osgDB::Options::CACHE_ALL);
342 osg::ref_ptr<osg::Object> object = osgDB::readRefObjectFile("state.spt", localOptions.get());
343 if (!dynamic_cast<osg::StateSet*>(object.get()))
346 return static_cast<osg::StateSet*>(object.get());
349 } // namespace simgear