Commit dd4de4f3 authored by Rick Gruber-Riemer's avatar Rick Gruber-Riemer

* Renamed setup.py to prepare_elev.py

* Moved utility methods from tools.py and setup.py to new module utilities.py
* Corrected absolute path to atlas
parent a8ae7e31
......@@ -13,8 +13,7 @@ from _io import open
import calc_tile
import parameters
import setup
import tools
import utils.utilities as util
OSM_FILE_NAME = "data.osm"
......@@ -23,10 +22,10 @@ def _get_file_name(name, tile_name):
"""
Returns a command file (Extension cmd for windows)
"""
my_os_type = setup.get_os_type()
if my_os_type is setup.OSType.windows:
my_os_type = util.get_os_type()
if my_os_type is util.OSType.windows:
extension = ".cmd"
elif my_os_type is setup.OSType.linux or my_os_type is setup.OSType.mac:
elif my_os_type is util.OSType.linux or my_os_type is util.OSType.mac:
extension = ".sh"
else:
extension = ""
......@@ -38,7 +37,7 @@ def _open_file(name, directory):
def _write_to_file(command, file_handle, python_exe, params_out):
file_handle.write(python_exe + ' ' + tools.get_osm2city_directory() + os.sep + command)
file_handle.write(python_exe + ' ' + util.get_osm2city_directory() + os.sep + command)
file_handle.write(' -f ' + params_out)
if BASH_PARALLEL_PROCESS:
file_handle.write(' &' + os.linesep + 'parallel_wait $max_parallel_process' + os.linesep)
......@@ -140,7 +139,7 @@ if __name__ == '__main__':
# Check if necessary to add parallel processing code
BASH_PARALLEL_PROCESS = False
is_linux_or_mac = setup.is_linux_or_mac()
is_linux_or_mac = util.is_linux_or_mac()
if args.parallel:
if is_linux_or_mac:
BASH_PARALLEL_PROCESS = True
......@@ -197,7 +196,7 @@ done
sources.write(line)
if args.new_download:
download_command = '%s %s%sdownload_tile.py -f %s/params.ini -d "%s"' % (python_exe,
tools.get_osm2city_directory(),
util.get_osm2city_directory(),
os.sep,
path, OSM_FILE_NAME)
download_file.write(download_command + os.linesep)
......
......@@ -12,7 +12,6 @@ from math import sin, cos, radians, tan, sqrt, pi
import os
import random
import re
import string
import matplotlib.pyplot as plt
import numpy as np
......
......@@ -9,7 +9,7 @@ import shutil
import sys
import parameters
import tools
import utils.utilities as util
def main():
......@@ -31,7 +31,7 @@ def main():
logging.error("The scenery path does not seem to have necessary sub-directories in %s", scenery_path)
sys.exit(1)
else:
orig_tex_dir = tools.get_osm2city_directory() + os.sep + "tex"
orig_tex_dir = util.get_osm2city_directory() + os.sep + "tex"
tex_content_list = os.listdir(orig_tex_dir)
if not os.path.exists(orig_tex_dir):
logging.error("The original tex dir seems to be missing: %s", orig_tex_dir)
......
......@@ -85,7 +85,7 @@ As described in chapter :ref:`Getting OpenStreetMap data <chapter-getting-data-l
The default work flow is based on the sub-chapters of :ref:`Preparation <chapter-preparation-label>`:
#. :ref:`Run setup.py <chapter-run-setup-label>` depending on your chosen :ref:`Elevation Probing Mode <chapter-elev-modes-label>`.
#. :ref:`Run prepare_elev.py <chapter-run-prepare_elev-label>` depending on your chosen :ref:`Elevation Probing Mode <chapter-elev-modes-label>`.
#. Adapt ``params.ini``. This will get copied to several subdirectories as part of the next process steps. Most importantly apapt the parameter ``PATH_TO_OUTPUT`` (in the example below "/home/fg_customscenery/CH_OSM"). The ``PREFIX`` and ``BOUNDARY_*`` parameters will automatically be updated.
#. :ref:`Call build_tiles.py <chapter-build-tiles-label>`. This step creates sub-directories including a set of shell / command scripts. The top directory will be created in your ``WORKING_DIRECTORY`` and have the same name as the lon/lat area specified with argument ``-t``
#. If needed adapt the params.ini files in the sub-directories if you need to change specific characteristics within one tile (e.g. parameters for building height etc.). In most situations this will not be needed.
......
......@@ -174,11 +174,11 @@ Available Elevation Probing Modes
There are a few different possibilities to generate elevation data, each of which is discussed in details in sub-chapters below. This is what is specified in parameter ``ELEV_MODE`` in the ``params.ini`` file:
* :ref:`ELEV_MODE = "FgelevCaching" <chapter-elev-fgelevcaching-label>`: most automated and convenient
* :ref:`ELEV_MODE = "Fgelev" <chapter-elev-fgelev-label>`: use this instead of ``FgelevCaching`` if you have clear memory or speed limitations
* :ref:`ELEV_MODE = "Fgelev" <chapter-elev-fgelev-label>`: use this instead of ``FgelevCaching`` if you have memory or speed limitations
* :ref:`ELEV_MODE = "Telnet" <chapter-elev-telnet-label>`: use this if you cannot compile C++ or use an older FlightGear version
* :ref:`ELEV_MODE = "Manual" <chapter-elev-manual-label>`: fallback method — doing a lot of stuff manually
The two methods using ``Fgelev`` require a bit less manual setup and intervention, however you need to be able to compile a C++ class with dependencies. ``FgelevCaching`` might give the best accuracy, be fastest and most automated. However memory requirements, speed etc. might vary depending on your parameter settings (e.g. ``ELEV_RASTER_*``) and the ratio between scenery area and the number of OSM objects.
The two methods using ``Fgelev*`` require a bit less manual setup and intervention. ``FgelevCaching`` might give the best accuracy, be fastest and most automated. However memory requirements, speed etc. might vary depending on your parameter settings (e.g. ``ELEV_RASTER_*``) and the ratio between scenery area and the number of OSM objects. In order to use one of the two ``Fgelev*`` methods, you need to have a FlightGear version 3.4 (released February 17 2015) or newer.
All methods apart from ``FgelevCaching`` will generate a file ``elev.out`` to be put into your input folder. ``FgelevCaching`` can also keep data cached (in a file called ``elev.pkl`` in the input directory) — so from a caching perspective there is not much of a difference [#]_.
......@@ -194,7 +194,6 @@ ELEV_MODE = "FgelevCaching"
---------------------------
In this mode elevation probing happens while running ``osm2city`` related scenery generation — instead of a data preparation task. There are 2 pre-requisites:
#. :ref:`Compile a patched fgelev program <chapter-compile-fgelev-label>`
#. :ref:`Setting parameter FG_ELEV <chapter-set-fgelev-path-label>`
#. :ref:`Setting environment variable FG_ROOT <chapter-set-fgroot-label>`
......@@ -207,7 +206,6 @@ ELEV_MODE = "Fgelev"
This elevation probing mode and the next modes generate a file ``elev.out``, which is put or needs to be put into your input folder. Use the following steps:
#. :ref:`Compile a patched fgelev program <chapter-compile-fgelev-label>`
#. :ref:`Setting parameter FG_ELEV <chapter-set-fgelev-path-label>`
#. :ref:`Setting parameters ELEV_RASTER_* <chapter-set-elev-raster-label>`
#. :ref:`Setting environment variable FG_ROOT <chapter-set-fgroot-label>`
......@@ -225,7 +223,7 @@ This mode requires FlightGear to be running and uses a data connection to get el
#. :ref:`Hide scenery objects <chapter-hide-label>`
#. :ref:`Setting parameters ELEV_RASTER_* <chapter-set-elev-raster-label>`
#. :ref:`Setting parameter TELNET_PORT <chapter-set-telnet-port-label>`
#. :ref:`Run setup.py to prepare elevation probing through Nasal <chapter-run-setup-label>`
#. :ref:`Run prepare_elev.py to prepare elevation probing through Nasal <chapter-run-prepare_elev-label>`
#. :ref:`Start FlightGear <chapter-start-fgfs-label>`
#. :ref:`Run tools.py to generate elevation data <chapter-run-tools-label>`
#. Exit FlightGear
......@@ -274,30 +272,6 @@ Detailed Description of Sub-Tasks
(Note: you need to follow only those sub-tasks, which were specified for the specific elevation probing mode as described above.)
.. _chapter-compile-fgelev-label:
++++++++++++++++++++++
Compile Patched fgelev
++++++++++++++++++++++
``osm2city`` comes with a patched version of ``fgelev``, which by means of a parameter ``expire`` drastically can improve the speed and avoid hanging. The patched version can be found in
``osm2city`` subdirectory ``fgelev`` as source file ``fgelev.cxx``. Before using it, you need to compile it and then replace the version, which comes with your FlightGear installation in the same directory as ``fgfs``/``fgfs.exe``. In Windows it might be in "D:/Program Files/FlightGear/bin/Win64/fgelev.exe".
Compilation depends on your operating system and hardware. On a Linux Debian derivative you might use the following:
#. Download and compile according to `Scripted Compilation on Linux Debian/Ubuntu`_
#. Replace ``fgelev.cxx`` in e.g. ``./next/flightgear/utils/fgelev`` with the one from ``osm2city/fgelev``
#. Recompile e.g. using the following command:
::
./download_and_compile.sh -p n -d n -r n FGFS
.. _`Scripted Compilation on Linux Debian/Ubuntu`: http://wiki.flightgear.org/Scripted_Compilation_on_Linux_Debian/Ubuntu
.. _chapter-set-fgelev-path-label:
+++++++++++++++++++++++++
......@@ -393,19 +367,19 @@ Change the work directory to e.g. ``fg_customscenery/projects`` and then run too
At the end of the process there is a new file ``elev.out`` containing the elevation data. If you use command-line option ``-o``, then existing data is not overwritten.
.. _chapter-run-setup-label:
.. _chapter-run-prepare_elev-label:
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Run setup.py to Prepare Elevation Probing through Nasal
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Run prepare_elev.py to Prepare Elevation Probing through Nasal
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Change the work directory to e.g. ``fg_customscenery/projects`` and then run setup.py. On Linux this might look like the following:
Change the work directory to e.g. ``fg_customscenery/projects`` and then run prepare_elev.py. On Linux this might look like the following:
::
$ cd fg_customscenery/projects
$ /usr/bin/python3 /home/pingu/development/osm2city/setup.py --fg_root=/home/pingu/bin/fgfs_git/next/install/flightgear/fgdata
$ /usr/bin/python3 /home/pingu/development/osm2city/prepare_elev.py --fg_root=/home/pingu/bin/fgfs_git/next/install/flightgear/fgdata
...
The command-line option ``--fg_root`` is essential and points to `$FG_ROOT`_ (see also :ref:`Setting environment variable $FG_ROOT <chapter-set-fgroot-label>`).
......@@ -425,10 +399,10 @@ Then open ``elev.nas`` in a text editor. Change the ``in`` variable as well as t
::
var get_elevation = func {
#Set via setup.py
#Set via prepare_elev.py
setprop("/osm2city/tiles", 0);
var in = "WILL_BE_SET_BY_SETUP.PY";
var out = "WILL_BE_SET_BY_SETUP.PY";
var in = "WILL_BE_SET_BY_PREPARE_ELEV.PY";
var out = "WILL_BE_SET_BY_PREPARE_ELEV.PY";
print( "Checking if tile is loaded");
...
......@@ -456,7 +430,7 @@ AFTER editing ``elev.nas`` might look as follows on Linux:
.. _$FG_HOME: http://wiki.flightgear.org/$FG_HOME
.. _$FG_ROOT: http://wiki.flightgear.org/$FG_ROOT
(Note: the description in this sub-task is basically what :ref:`running setup.py <chapter-run-setup-label>` does automatically.)
(Note: the description in this sub-task is basically what :ref:`running prepare_elev.py <chapter-run-prepare_elev-label>` does automatically.)
.. _chapter-elev.in-label:
......
var get_elevation = func {
#Set via setup.py
#Set via prepare_elev.py
setprop("/osm2city/tiles", 0);
var in = "WILL_BE_SET_BY_SETUP.PY";
var out = "WILL_BE_SET_BY_SETUP.PY";
var in = "WILL_BE_SET_BY_PREPARE_ELEV.PY";
var out = "WILL_BE_SET_BY_PREPARE_ELEV.PY";
print( "Checking if tile is loaded");
......
A patched version of fgelev.
I added a cmd line flag "--expire". Usage:
fgelev --expire <INTEGER>
I *THINK* fgelev expires the loaded scenery part once it hasn't been accessed
in the last $expire probes. By default this value is rather small (10),
and automated elevation probing by osm2city was painfully slow due to frequent
terrain reloads.
Increasing $expire to O(10^7) solves this problem.
// fgelev.cxx -- compute scenery elevation
//
// Copyright (C) 2009 - 2012 Mathias Froehlich
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <osg/ArgumentParser>
#include <osg/Image>
#include <simgear/props/props.hxx>
#include <simgear/props/props_io.hxx>
#include <simgear/misc/sg_path.hxx>
#include <simgear/misc/ResourceManager.hxx>
#include <simgear/bvh/BVHNode.hxx>
#include <simgear/bvh/BVHLineSegmentVisitor.hxx>
#include <simgear/bvh/BVHPager.hxx>
#include <simgear/bvh/BVHPageNode.hxx>
#include <simgear/scene/material/matlib.hxx>
#include <simgear/scene/model/BVHPageNodeOSG.hxx>
#include <simgear/scene/model/ModelRegistry.hxx>
#include <simgear/scene/util/SGReaderWriterOptions.hxx>
#include <simgear/scene/util/OptionsReadFileCallback.hxx>
#include <simgear/scene/tgdb/userdata.hxx>
namespace sg = simgear;
class Visitor : public sg::BVHLineSegmentVisitor {
public:
Visitor(const SGLineSegmentd& lineSegment, sg::BVHPager& pager) :
BVHLineSegmentVisitor(lineSegment, 0),
_pager(pager)
{ }
virtual ~Visitor()
{ }
virtual void apply(sg::BVHPageNode& node)
{
// we have a non threaded pager so load just right here.
_pager.use(node);
BVHLineSegmentVisitor::apply(node);
}
private:
sg::BVHPager& _pager;
};
// Short circuit reading image files.
class ReadFileCallback : public sg::OptionsReadFileCallback {
public:
virtual ~ReadFileCallback()
{ }
virtual osgDB::ReaderWriter::ReadResult readImage(const std::string& name, const osgDB::Options*)
{ return new osg::Image; }
};
static bool
intersect(sg::BVHNode& node, sg::BVHPager& pager,
const SGVec3d& start, SGVec3d& end, double offset)
{
SGVec3d perp = offset*perpendicular(start - end);
Visitor visitor(SGLineSegmentd(start + perp, end + perp), pager);
node.accept(visitor);
if (visitor.empty())
return false;
end = visitor.getLineSegment().getEnd();
return true;
}
int
main(int argc, char** argv)
{
/// Read arguments and environment variables.
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc, argv);
unsigned expire;
if (arguments.read("--expire", expire)) {
} else expire = 10;
std::string fg_root;
if (arguments.read("--fg-root", fg_root)) {
} else if (const char *fg_root_env = std::getenv("FG_ROOT")) {
fg_root = fg_root_env;
} else {
fg_root = PKGLIBDIR;
}
std::string fg_scenery;
if (arguments.read("--fg-scenery", fg_scenery)) {
} else if (const char *fg_scenery_env = std::getenv("FG_SCENERY")) {
fg_scenery = fg_scenery_env;
} else {
SGPath path(fg_root);
path.append("Scenery");
fg_scenery = path.str();
}
SGSharedPtr<SGPropertyNode> props = new SGPropertyNode;
try {
SGPath preferencesFile = fg_root;
preferencesFile.append("preferences.xml");
readProperties(preferencesFile.str(), props);
} catch (...) {
// In case of an error, at least make summer :)
props->getNode("sim/startup/season", true)->setStringValue("summer");
SG_LOG(SG_GENERAL, SG_ALERT, "Problems loading FlightGear preferences.\n"
<< "Probably FG_ROOT is not properly set.");
}
/// now set up the simgears required model stuff
simgear::ResourceManager::instance()->addBasePath(fg_root, simgear::ResourceManager::PRIORITY_DEFAULT);
// Just reference simgears reader writer stuff so that the globals get
// pulled in by the linker ...
simgear::ModelRegistry::instance();
sgUserDataInit(props.get());
SGMaterialLibPtr ml = new SGMaterialLib;
SGPath mpath(fg_root);
mpath.append("Materials/default/materials.xml");
try {
ml->load(fg_root, mpath.str(), props);
} catch (...) {
SG_LOG(SG_GENERAL, SG_ALERT, "Problems loading FlightGear materials.\n"
<< "Probably FG_ROOT is not properly set.");
}
simgear::SGModelLib::init(fg_root, props);
// Set up the reader/writer options
osg::ref_ptr<simgear::SGReaderWriterOptions> options;
if (osgDB::Options* ropt = osgDB::Registry::instance()->getOptions())
options = new simgear::SGReaderWriterOptions(*ropt);
else
options = new simgear::SGReaderWriterOptions;
osgDB::convertStringPathIntoFilePathList(fg_scenery,
options->getDatabasePathList());
options->setMaterialLib(ml);
options->setPropertyNode(props);
options->setReadFileCallback(new ReadFileCallback);
options->setPluginStringData("SimGear::FG_ROOT", fg_root);
// we do not need the builtin boundingvolumes
options->setPluginStringData("SimGear::BOUNDINGVOLUMES", "OFF");
// And we only want terrain, no objects on top.
options->setPluginStringData("SimGear::FG_ONLY_TERRAIN", "ON");
props->getNode("sim/rendering/random-objects", true)->setBoolValue(false);
props->getNode("sim/rendering/random-vegetation", true)->setBoolValue(false);
// Here, all arguments are processed
arguments.reportRemainingOptionsAsUnrecognized();
arguments.writeErrorMessages(std::cerr);
// Get the whole world bvh tree
SGSharedPtr<sg::BVHNode> node;
node = sg::BVHPageNodeOSG::load("w180s90-360x180.spt", options);
// if no model has been successfully loaded report failure.
if (!node.valid()) {
SG_LOG(SG_GENERAL, SG_ALERT, arguments.getApplicationName()
<< ": No data loaded");
return EXIT_FAILURE;
}
// We assume that the above is a paged database.
sg::BVHPager pager;
while (std::cin.good()) {
// Increment the paging relevant number
pager.setUseStamp(1 + pager.getUseStamp());
// and expire everything not accessed for the past 30 requests
pager.update(expire);
std::string id;
std::cin >> id;
double lon, lat;
std::cin >> lon >> lat;
if (std::cin.fail())
return EXIT_FAILURE;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
SGVec3d start = SGVec3d::fromGeod(SGGeod::fromDegM(lon, lat, 10000));
SGVec3d end = SGVec3d::fromGeod(SGGeod::fromDegM(lon, lat, -1000));
// Try to find an intersection
bool found = intersect(*node, pager, start, end, 0);
double scale = 1e-5;
while (!found && scale <= 1) {
found = intersect(*node, pager, start, end, scale);
scale *= 2;
}
if (1e-5 < scale)
std::cerr << "Found hole of minimum diameter "
<< scale << "m at lon = " << lon
<< "deg lat = " << lat << "deg" << std::endl;
std::cout << id << ": ";
if (!found) {
std::cout << "-1000" << std::endl;
} else {
SGGeod geod = SGGeod::fromCart(end);
std::cout << std::fixed << std::setprecision(3) << geod.getElevationM() << std::endl;
}
}
return EXIT_SUCCESS;
}
......@@ -76,6 +76,7 @@ import stg_io2
import textures.manager as tex_manager
from textures.manager import TextureManager, FacadeManager # this is needed to make pickle know the context
import tools
import utils.utilities as util
import troubleshoot
import vec2d as v
......@@ -649,7 +650,7 @@ if __name__ == "__main__":
tools.init(coordinates.Transformation(center, hdg=0))
tex_manager.init(tools.get_osm2city_directory(), args.create_atlas)
tex_manager.init(util.get_osm2city_directory(), args.create_atlas)
logging.info("reading elevation data")
elev = tools.get_interpolator(fake=parameters.NO_ELEV)
......
"""
Created on 10.05.2014
@author: keith.paterson
"""
import argparse
import logging
import os
import sys
import utils.utilities as util
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser(description="prepare_elev will set some properties and copy the elev.nas")
parser.add_argument("-fg", "--fg_root", dest="fg_root",
help="$FG_ROOT see http://wiki.flightgear.org/$FG_ROOT. \
Typically '.../data' or '.../fgdata'."
, required=True)
args = parser.parse_args()
if args.fg_root is not None:
nasalDir = os.path.abspath(args.fg_root) + os.sep + "Nasal"
if not os.path.exists(nasalDir):
logging.error("Directory not found %s", nasalDir)
sys.exit(1)
fg_home_path = util.get_fg_home()
if fg_home_path is None:
logging.error("Operating system unknown and therefore FGHome unknown.")
os._exit(1)
with open(util.get_original_elev_nas_path(), "r") as sources:
lines = sources.readlines()
with open(nasalDir + os.sep + "elev.nas", "w") as sources:
for line in lines:
if "var in " in line:
line = ' var in = "' + util.get_elev_in_path(fg_home_path) + '";\n'
if "var out" in line:
line = ' var out = "' + util.get_elev_out_dir(fg_home_path) + '";\n'
sources.write(line)
logging.info('Successfully installed elev.nas')
......@@ -103,6 +103,7 @@ import stg_io2
import textures.road
import tools
import troubleshoot
import utils.utilities as util
from vec2d import vec2d
from cluster import Clusters
......@@ -1171,7 +1172,7 @@ def main():
# copy roads.eff into scenery folders
for stg_path in stg_paths:
roads_eff_file_name = tools.get_osm2city_directory() + os.sep + 'roads.eff'
roads_eff_file_name = util.get_osm2city_directory() + os.sep + 'roads.eff'
tools.install_files([roads_eff_file_name], stg_path)
roads.debug_plot(show=True, plot_junctions=False, clusters=roads.clusters) #, label_nodes=self.nodes_dict.keys())#, label_nodes=[1132288594, 1132288612])
......
......@@ -32,6 +32,7 @@ from textures import atlas
import img2np
import parameters
import tools
import utils.utilities as util
from textures.texture import Texture
atlas_file_name = None
......@@ -43,7 +44,7 @@ def _next_pow2(value):
return 2**(int(math.log(value) / math.log(2)) + 1)
def _make_texture_atlas(texture_list, atlas_filename, ext, tex_prefix, size_x=256, pad_y=0,
def _make_texture_atlas(texture_list, atlas_filename, ext, size_x=256, pad_y=0,
lightmap=False, ambient_occlusion=False):
"""
Create texture atlas from all textures. Update all our item coordinates.
......@@ -466,32 +467,32 @@ def init(tex_prefix='', create_atlas=False): # in most situations tex_prefix sh
if tools.stats is None: # if e.g. manager.init is called from osm2city, then tools.init does not need to be called
tools.init(None)
my_tex_prefix = tools.assert_trailing_slash(tex_prefix)
atlas_file_name = my_tex_prefix + "tex" + os.sep + "atlas_facades"
my_tex_prefix += 'tex.src'
Texture.tex_prefix = my_tex_prefix # need to set static variable so managers get full path
my_tex_prefix = util.assert_trailing_slash(tex_prefix)
atlas_file_name = "tex" + os.sep + "atlas_facades"
my_tex_prefix_src = my_tex_prefix + 'tex.src'
Texture.tex_prefix = my_tex_prefix_src # need to set static variable so managers get full path
pkl_fname = atlas_file_name + '.pkl'
pkl_fname = my_tex_prefix + "tex" + os.sep + "atlas_facades.pkl"
if create_atlas:
facades = FacadeManager('facade')
roofs = TextureManager('roof')
# read registration
_append_roofs(roofs, my_tex_prefix)
_append_dynamic(facades, my_tex_prefix)
_append_roofs(roofs, my_tex_prefix_src)
_append_dynamic(facades, my_tex_prefix_src)
texture_list = facades.get_list() + roofs.get_list()
# warn for missed out textures
_check_missed_input_textures(my_tex_prefix, texture_list)
_check_missed_input_textures(my_tex_prefix_src, texture_list)
# -- make texture atlas
if parameters.ATLAS_SUFFIX_DATE:
now = datetime.datetime.now()
atlas_file_name += "_%04i%02i%02i" % (now.year, now.month, now.day)
_make_texture_atlas(texture_list, atlas_file_name, '.png', my_tex_prefix,
_make_texture_atlas(texture_list, my_tex_prefix + atlas_file_name, '.png',
lightmap=True, ambient_occlusion=parameters.BUILDING_FAKE_AMBIENT_OCCLUSION)
params = dict()
......@@ -532,4 +533,4 @@ if __name__ == "__main__":
parameters.read_from_file(args.filename)
parameters.set_loglevel(args.loglevel) # -- must go after reading params file
init(tools.get_osm2city_directory(), args.a)
init(util.get_osm2city_directory(), args.a)
......@@ -13,7 +13,6 @@ import csv
import logging
import math
import os
import os.path as osp
import queue
import shutil
import subprocess
......@@ -28,7 +27,7 @@ import batch_processing.fg_telnet as telnet
import calc_tile
import coordinates
import parameters
import setup
import utils.utilities as util
import vec2d as ve
from _collections import defaultdict
......@@ -38,25 +37,6 @@ stats = None
transform = None
def get_osm2city_directory():
"""Determines the absolute path of the osm2city root directory.
Used e.g. when copying roads.eff, elev.nas and other resources.
"""
my_file = osp.realpath(__file__)
my_dir = osp.split(my_file)[0]
return my_dir
def assert_trailing_slash(path):
"""Takes a path and makes sure it has an os_specific trailing slash unless the path is empty."""
my_path = path
if len(my_path) > 0:
if not my_path.endswith(os.sep):
my_path += os.sep
return my_path
class Interpolator(object):
"""load elevation data from file, interpolate"""
def __init__(self, filename, fake=False, clamp=False):
......@@ -282,8 +262,8 @@ class Probe_fgelev(object):
if empty_lines > 1:
logging.fatal("Skipped %i lines" % empty_lines)
logging.fatal("%i %g %g" % (self.record, position.lon, position.lat))
logging.fatal("fgelev returned <%s>, resulting in %s. Did fgelev start OK (Record : %i)?"
, line, reason, self.record)
logging.fatal("fgelev returned <%s>, resulting in %s. Did fgelev start OK (Record : %i)?",
line, reason, self.record)
raise RuntimeError("fgelev errors are fatal.")
return elev
......@@ -415,12 +395,12 @@ def raster_glob(prevent_overwrite=False):
def _raster_telnet(transform, fname, x0, y0, size_x=1000, size_y=1000, step_x=5, step_y=5):
"""Writes elev.in and elev.out using Telnet to a running FlightGear instance."""
fg_home_path = setup.getFGHome()
fg_home_path = util.get_fg_home()
if fg_home_path is None:
logging.error("Operating system unknown and therefore FGHome unknown.")
sys.exit(1)
logging.info("Writing elev.in")
f = open(setup.get_elev_in_path(fg_home_path), "w")
f = open(util.get_elev_in_path(fg_home_path), "w")
f.write("# %g %g %g %g %g %g\n" % (x0, y0, size_x, size_y, step_x, step_y))
for y in np.arange(y0, y0 + size_y, step_y):
for x in np.arange(x0, x0 + size_x, step_x):
......@@ -444,7 +424,7 @@ def _raster_telnet(transform, fname, x0, y0, size_x=1000, size_y=1000, step_x=5,
logging.error("Process in FG timed out")
else:
logging.info("Success")
shutil.copy2(setup.get_elev_out_path(fg_home_path), fname)
shutil.copy2(util.get_elev_out_path(fg_home_path), fname)
fg.close()
......@@ -766,7 +746,7 @@ def install_files(file_list, dst, from_osm2city_root=False):
for the_file in file_list:
my_file = the_file
if from_osm2city_root:
my_file = get_osm2city_directory() + os.sep + the_file
my_file = util.get_osm2city_directory() + os.sep + the_file
the_dst = dst
logging.info("cp %s %s", my_file, the_dst)
if os.path.exists(the_dst + the_file):
......
"""
Created on 10.05.2014
@author: keith.paterson
"""
import argparse
import enum
import logging
import os
import os.path as osp
import sys
import tools
def getFGHome():
"""Constructs the path to FGHome.
See also http://wiki.flightgear.org/$FG_HOME
If the operating system cannot be determined the function returns None.
Otherwise a platform specific path.
"""
home_dir = osp.expanduser("~")
my_os_type = get_os_type()
if my_os_type is OSType.windows:
home = os.getenv("APPDATA", "APPDATA_NOT_FOUND") + os.sep + "flightgear.org" + os.sep
return home.replace("\\", "/")
elif my_os_type is OSType.linux:
return home_dir + "/.fgfs/"
elif my_os_type is OSType.mac:
return home_dir + "/Library/Application Support/FlightGear/"
else:
return None
@enum.unique
class OSType(enum.IntEnum):
windows = 1
linux = 2
mac = 3
other = 4
def get_os_type():
if sys.platform.startswith("win"):
return OSType.windows
elif sys.platform.startswith("linux"):
return OSType.linux
elif sys.platform.startswith("darwin"):
return OSType.mac
else:
return OSType.other