maps4fs 0.7.9__py3-none-any.whl → 0.8.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- maps4fs/generator/background.py +292 -0
- maps4fs/generator/component.py +66 -0
- maps4fs/generator/config.py +4 -2
- maps4fs/generator/dem.py +115 -32
- maps4fs/generator/game.py +24 -1
- maps4fs/generator/i3d.py +89 -0
- maps4fs/generator/map.py +43 -27
- maps4fs/generator/path_steps.py +72 -0
- maps4fs/generator/texture.py +86 -29
- maps4fs/generator/tile.py +55 -0
- {maps4fs-0.7.9.dist-info → maps4fs-0.8.3.dist-info}/METADATA +172 -25
- maps4fs-0.8.3.dist-info/RECORD +18 -0
- maps4fs-0.7.9.dist-info/RECORD +0 -14
- {maps4fs-0.7.9.dist-info → maps4fs-0.8.3.dist-info}/LICENSE.md +0 -0
- {maps4fs-0.7.9.dist-info → maps4fs-0.8.3.dist-info}/WHEEL +0 -0
- {maps4fs-0.7.9.dist-info → maps4fs-0.8.3.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,292 @@
|
|
1
|
+
"""This module contains the Background component, which generates 3D obj files based on DEM data
|
2
|
+
around the map."""
|
3
|
+
|
4
|
+
from __future__ import annotations
|
5
|
+
|
6
|
+
import os
|
7
|
+
|
8
|
+
import cv2
|
9
|
+
import numpy as np
|
10
|
+
import trimesh # type: ignore
|
11
|
+
from pyproj import Transformer
|
12
|
+
|
13
|
+
from maps4fs.generator.component import Component
|
14
|
+
from maps4fs.generator.path_steps import DEFAULT_DISTANCE, get_steps
|
15
|
+
from maps4fs.generator.tile import Tile
|
16
|
+
|
17
|
+
RESIZE_FACTOR = 1 / 4
|
18
|
+
|
19
|
+
|
20
|
+
class Background(Component):
|
21
|
+
"""Component for creating 3D obj files based on DEM data around the map.
|
22
|
+
|
23
|
+
Args:
|
24
|
+
coordinates (tuple[float, float]): The latitude and longitude of the center of the map.
|
25
|
+
map_height (int): The height of the map in pixels.
|
26
|
+
map_width (int): The width of the map in pixels.
|
27
|
+
map_directory (str): The directory where the map files are stored.
|
28
|
+
logger (Any, optional): The logger to use. Must have at least three basic methods: debug,
|
29
|
+
info, warning. If not provided, default logging will be used.
|
30
|
+
"""
|
31
|
+
|
32
|
+
def preprocess(self) -> None:
|
33
|
+
"""Prepares the component for processing. Registers the tiles around the map by moving
|
34
|
+
clockwise from North, then clockwise."""
|
35
|
+
self.tiles: list[Tile] = []
|
36
|
+
origin = self.coordinates
|
37
|
+
|
38
|
+
# Getting a list of 8 tiles around the map starting from the N(North) tile.
|
39
|
+
for path_step in get_steps(self.map_height, self.map_width):
|
40
|
+
# Getting the destination coordinates for the current tile.
|
41
|
+
tile_coordinates = path_step.get_destination(origin)
|
42
|
+
|
43
|
+
# Create a Tile component, which is needed to save the DEM image.
|
44
|
+
tile = Tile(
|
45
|
+
game=self.game,
|
46
|
+
coordinates=tile_coordinates,
|
47
|
+
map_height=path_step.size[1],
|
48
|
+
map_width=path_step.size[0],
|
49
|
+
map_directory=self.map_directory,
|
50
|
+
logger=self.logger,
|
51
|
+
tile_code=path_step.code,
|
52
|
+
auto_process=False,
|
53
|
+
blur_radius=self.kwargs.get("blur_radius"),
|
54
|
+
multiplier=1,
|
55
|
+
)
|
56
|
+
|
57
|
+
# Update the origin for the next tile.
|
58
|
+
origin = tile_coordinates
|
59
|
+
self.tiles.append(tile)
|
60
|
+
self.logger.debug(
|
61
|
+
"Registered tile: %s, coordinates: %s, size: %s",
|
62
|
+
tile.code,
|
63
|
+
tile_coordinates,
|
64
|
+
path_step.size,
|
65
|
+
)
|
66
|
+
|
67
|
+
def process(self) -> None:
|
68
|
+
"""Launches the component processing. Iterates over all tiles and processes them
|
69
|
+
as a result the DEM files will be saved, then based on them the obj files will be
|
70
|
+
generated."""
|
71
|
+
for tile in self.tiles:
|
72
|
+
tile.process()
|
73
|
+
|
74
|
+
self.generate_obj_files()
|
75
|
+
|
76
|
+
def info_sequence(self) -> dict[str, dict[str, str | float | int]]:
|
77
|
+
"""Returns a dictionary with information about the tiles around the map.
|
78
|
+
Adds the EPSG:3857 string to the data for convenient usage in QGIS.
|
79
|
+
|
80
|
+
Returns:
|
81
|
+
dict[str, dict[str, float | int]] -- A dictionary with information about the tiles.
|
82
|
+
"""
|
83
|
+
data = {}
|
84
|
+
for tile in self.tiles:
|
85
|
+
north, south, east, west = tile.bbox
|
86
|
+
|
87
|
+
# The default CMS in library is EPSG:4326.
|
88
|
+
# It needed to be converted to EPSG:3857 for convinient usage in QGIS.
|
89
|
+
|
90
|
+
transformer = Transformer.from_crs("epsg:4326", "epsg:3857")
|
91
|
+
epsg3857_north, epsg3857_west = transformer.transform(north, west)
|
92
|
+
epsg3857_south, epsg3857_east = transformer.transform(south, east)
|
93
|
+
|
94
|
+
epsg3857_string = (
|
95
|
+
f"{epsg3857_north},{epsg3857_south},{epsg3857_east},{epsg3857_west} [EPSG:3857]"
|
96
|
+
)
|
97
|
+
|
98
|
+
tile_entry = {
|
99
|
+
"center_latitude": tile.coordinates[0],
|
100
|
+
"center_longitude": tile.coordinates[1],
|
101
|
+
"epsg3857_string": epsg3857_string,
|
102
|
+
"height": tile.map_height,
|
103
|
+
"width": tile.map_width,
|
104
|
+
"north": north,
|
105
|
+
"south": south,
|
106
|
+
"east": east,
|
107
|
+
"west": west,
|
108
|
+
}
|
109
|
+
if tile.code is not None:
|
110
|
+
data[tile.code] = tile_entry
|
111
|
+
|
112
|
+
return data # type: ignore
|
113
|
+
|
114
|
+
def generate_obj_files(self) -> None:
|
115
|
+
"""Iterates over all tiles and generates 3D obj files based on DEM data.
|
116
|
+
If at least one DEM file is missing, the generation will be stopped at all.
|
117
|
+
"""
|
118
|
+
for tile in self.tiles:
|
119
|
+
# Read DEM data from the tile.
|
120
|
+
dem_path = tile.dem_path
|
121
|
+
if not os.path.isfile(dem_path):
|
122
|
+
self.logger.warning("DEM file not found, generation will be stopped: %s", dem_path)
|
123
|
+
return
|
124
|
+
|
125
|
+
self.logger.info("DEM file for tile %s found: %s", tile.code, dem_path)
|
126
|
+
|
127
|
+
base_directory = os.path.dirname(dem_path)
|
128
|
+
save_path = os.path.join(base_directory, f"{tile.code}.obj")
|
129
|
+
self.logger.debug("Generating obj file for tile %s in path: %s", tile.code, save_path)
|
130
|
+
|
131
|
+
dem_data = cv2.imread(tile.dem_path, cv2.IMREAD_UNCHANGED) # pylint: disable=no-member
|
132
|
+
self.plane_from_np(dem_data, save_path)
|
133
|
+
|
134
|
+
# pylint: disable=too-many-locals
|
135
|
+
def plane_from_np(self, dem_data: np.ndarray, save_path: str) -> None:
|
136
|
+
"""Generates a 3D obj file based on DEM data.
|
137
|
+
|
138
|
+
Arguments:
|
139
|
+
dem_data (np.ndarray) -- The DEM data as a numpy array.
|
140
|
+
save_path (str) -- The path where the obj file will be saved.
|
141
|
+
"""
|
142
|
+
dem_data = cv2.resize( # pylint: disable=no-member
|
143
|
+
dem_data, (0, 0), fx=RESIZE_FACTOR, fy=RESIZE_FACTOR
|
144
|
+
)
|
145
|
+
self.logger.debug(
|
146
|
+
"DEM data resized to shape: %s with factor: %s", dem_data.shape, RESIZE_FACTOR
|
147
|
+
)
|
148
|
+
|
149
|
+
rows, cols = dem_data.shape
|
150
|
+
x = np.linspace(0, cols - 1, cols)
|
151
|
+
y = np.linspace(0, rows - 1, rows)
|
152
|
+
x, y = np.meshgrid(x, y)
|
153
|
+
z = dem_data
|
154
|
+
|
155
|
+
vertices = np.column_stack([x.ravel(), y.ravel(), z.ravel()])
|
156
|
+
faces = []
|
157
|
+
|
158
|
+
for i in range(rows - 1):
|
159
|
+
for j in range(cols - 1):
|
160
|
+
top_left = i * cols + j
|
161
|
+
top_right = top_left + 1
|
162
|
+
bottom_left = top_left + cols
|
163
|
+
bottom_right = bottom_left + 1
|
164
|
+
|
165
|
+
# Invert the order of vertices to flip the normals
|
166
|
+
faces.append([top_left, bottom_right, bottom_left])
|
167
|
+
faces.append([top_left, top_right, bottom_right])
|
168
|
+
|
169
|
+
faces = np.array(faces) # type: ignore
|
170
|
+
mesh = trimesh.Trimesh(vertices=vertices, faces=faces)
|
171
|
+
|
172
|
+
# Simplify the mesh to reduce the number of faces.
|
173
|
+
mesh = mesh.simplify_quadric_decimation(face_count=len(faces) // 10)
|
174
|
+
self.logger.debug("Mesh simplified to %s faces", len(mesh.faces))
|
175
|
+
|
176
|
+
mesh.export(save_path)
|
177
|
+
self.logger.info("Obj file saved: %s", save_path)
|
178
|
+
|
179
|
+
def previews(self) -> list[str]:
|
180
|
+
"""Generates a preview by combining all tiles into one image.
|
181
|
+
NOTE: The map itself is not included in the preview, so it will be empty.
|
182
|
+
|
183
|
+
Returns:
|
184
|
+
list[str] -- A list of paths to the preview images."""
|
185
|
+
|
186
|
+
self.logger.info("Generating a preview image for the background DEM")
|
187
|
+
|
188
|
+
image_height = self.map_height + DEFAULT_DISTANCE * 2
|
189
|
+
image_width = self.map_width + DEFAULT_DISTANCE * 2
|
190
|
+
self.logger.debug("Full size of the preview image: %s x %s", image_width, image_height)
|
191
|
+
|
192
|
+
image = np.zeros((image_height, image_width), np.uint16) # pylint: disable=no-member
|
193
|
+
self.logger.debug("Empty image created: %s", image.shape)
|
194
|
+
|
195
|
+
for tile in self.tiles:
|
196
|
+
# pylint: disable=no-member
|
197
|
+
tile_image = cv2.imread(tile.dem_path, cv2.IMREAD_UNCHANGED)
|
198
|
+
|
199
|
+
self.logger.debug(
|
200
|
+
"Tile %s image shape: %s, dtype: %s, max: %s, min: %s",
|
201
|
+
tile.code,
|
202
|
+
tile_image.shape,
|
203
|
+
tile_image.dtype,
|
204
|
+
tile_image.max(),
|
205
|
+
tile_image.min(),
|
206
|
+
)
|
207
|
+
|
208
|
+
tile_height, tile_width = tile_image.shape
|
209
|
+
self.logger.debug("Tile %s size: %s x %s", tile.code, tile_width, tile_height)
|
210
|
+
|
211
|
+
# Calculate the position based on the tile code
|
212
|
+
if tile.code == "N":
|
213
|
+
x = DEFAULT_DISTANCE
|
214
|
+
y = 0
|
215
|
+
elif tile.code == "NE":
|
216
|
+
x = self.map_width + DEFAULT_DISTANCE
|
217
|
+
y = 0
|
218
|
+
elif tile.code == "E":
|
219
|
+
x = self.map_width + DEFAULT_DISTANCE
|
220
|
+
y = DEFAULT_DISTANCE
|
221
|
+
elif tile.code == "SE":
|
222
|
+
x = self.map_width + DEFAULT_DISTANCE
|
223
|
+
y = self.map_height + DEFAULT_DISTANCE
|
224
|
+
elif tile.code == "S":
|
225
|
+
x = DEFAULT_DISTANCE
|
226
|
+
y = self.map_height + DEFAULT_DISTANCE
|
227
|
+
elif tile.code == "SW":
|
228
|
+
x = 0
|
229
|
+
y = self.map_height + DEFAULT_DISTANCE
|
230
|
+
elif tile.code == "W":
|
231
|
+
x = 0
|
232
|
+
y = DEFAULT_DISTANCE
|
233
|
+
elif tile.code == "NW":
|
234
|
+
x = 0
|
235
|
+
y = 0
|
236
|
+
|
237
|
+
# pylint: disable=possibly-used-before-assignment
|
238
|
+
x2 = x + tile_width
|
239
|
+
y2 = y + tile_height
|
240
|
+
|
241
|
+
self.logger.debug(
|
242
|
+
"Tile %s position. X from %s to %s, Y from %s to %s", tile.code, x, x2, y, y2
|
243
|
+
)
|
244
|
+
|
245
|
+
# pylint: disable=possibly-used-before-assignment
|
246
|
+
image[y:y2, x:x2] = tile_image
|
247
|
+
|
248
|
+
# Save image to the map directory.
|
249
|
+
preview_path = os.path.join(self.previews_directory, "background_dem.png")
|
250
|
+
|
251
|
+
# pylint: disable=no-member
|
252
|
+
image = cv2.normalize(image, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U) # type: ignore
|
253
|
+
image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) # type: ignore
|
254
|
+
cv2.imwrite(preview_path, image)
|
255
|
+
|
256
|
+
return [preview_path]
|
257
|
+
|
258
|
+
|
259
|
+
# Creates tiles around the map.
|
260
|
+
# The one on corners 2048x2048, on sides and in the middle map_size x 2048.
|
261
|
+
# So 2048 is a distance FROM the edge of the map, but the other size depends on the map size.
|
262
|
+
# But for corner tiles it's always 2048.
|
263
|
+
|
264
|
+
# In the beginning we have coordinates of the central point of the map and it's size.
|
265
|
+
# We need to calculate the coordinates of central points all 8 tiles around the map.
|
266
|
+
|
267
|
+
# Latitude is a vertical line, Longitude is a horizontal line.
|
268
|
+
|
269
|
+
# 2048
|
270
|
+
# | |
|
271
|
+
# ____________________|_________|___
|
272
|
+
# | | | |
|
273
|
+
# | NW | N | NE | 2048
|
274
|
+
# |_________|_________|_________|___
|
275
|
+
# | | | |
|
276
|
+
# | W | C | E |
|
277
|
+
# |_________|_________|_________|
|
278
|
+
# | | | |
|
279
|
+
# | SW | S | SE |
|
280
|
+
# |_________|_________|_________|
|
281
|
+
#
|
282
|
+
# N = C map_height / 2 + 1024; N_width = map_width; N_height = 2048
|
283
|
+
# NW = N - map_width / 2 - 1024; NW_width = 2048; NW_height = 2048
|
284
|
+
# and so on...
|
285
|
+
|
286
|
+
# lat, lon = 45.28565000315636, 20.237121355049904
|
287
|
+
# dst = 1024
|
288
|
+
|
289
|
+
# # N
|
290
|
+
# destination = distance(meters=dst).destination((lat, lon), 0)
|
291
|
+
# lat, lon = destination.latitude, destination.longitude
|
292
|
+
# print(lat, lon)
|
maps4fs/generator/component.py
CHANGED
@@ -2,6 +2,9 @@
|
|
2
2
|
|
3
3
|
from __future__ import annotations
|
4
4
|
|
5
|
+
import json
|
6
|
+
import os
|
7
|
+
from copy import deepcopy
|
5
8
|
from typing import TYPE_CHECKING, Any
|
6
9
|
|
7
10
|
import osmnx as ox # type: ignore
|
@@ -15,6 +18,7 @@ class Component:
|
|
15
18
|
"""Base class for all map generation components.
|
16
19
|
|
17
20
|
Args:
|
21
|
+
game (Game): The game instance for which the map is generated.
|
18
22
|
coordinates (tuple[float, float]): The latitude and longitude of the center of the map.
|
19
23
|
map_height (int): The height of the map in pixels.
|
20
24
|
map_width (int): The width of the map in pixels.
|
@@ -41,6 +45,8 @@ class Component:
|
|
41
45
|
self.logger = logger
|
42
46
|
self.kwargs = kwargs
|
43
47
|
|
48
|
+
os.makedirs(self.previews_directory, exist_ok=True)
|
49
|
+
|
44
50
|
self.save_bbox()
|
45
51
|
self.preprocess()
|
46
52
|
|
@@ -68,6 +74,66 @@ class Component:
|
|
68
74
|
"""
|
69
75
|
raise NotImplementedError
|
70
76
|
|
77
|
+
@property
|
78
|
+
def previews_directory(self) -> str:
|
79
|
+
"""The directory where the preview images are stored.
|
80
|
+
|
81
|
+
Returns:
|
82
|
+
str: The directory where the preview images are stored.
|
83
|
+
"""
|
84
|
+
return os.path.join(self.map_directory, "previews")
|
85
|
+
|
86
|
+
@property
|
87
|
+
def generation_info_path(self) -> str:
|
88
|
+
"""The path to the generation info JSON file.
|
89
|
+
|
90
|
+
Returns:
|
91
|
+
str: The path to the generation info JSON file.
|
92
|
+
"""
|
93
|
+
return os.path.join(self.map_directory, "generation_info.json")
|
94
|
+
|
95
|
+
def info_sequence(self) -> dict[Any, Any]:
|
96
|
+
"""Returns the information sequence for the component. Must be implemented in the child
|
97
|
+
class. If the component does not have an information sequence, an empty dictionary must be
|
98
|
+
returned.
|
99
|
+
|
100
|
+
Returns:
|
101
|
+
dict[Any, Any]: The information sequence for the component.
|
102
|
+
"""
|
103
|
+
return {}
|
104
|
+
|
105
|
+
def commit_generation_info(self) -> None:
|
106
|
+
"""Commits the generation info to the generation info JSON file."""
|
107
|
+
self.update_generation_info(self.info_sequence())
|
108
|
+
|
109
|
+
def update_generation_info(self, data: dict[Any, Any]) -> None:
|
110
|
+
"""Updates the generation info with the provided data.
|
111
|
+
If the generation info file does not exist, it will be created.
|
112
|
+
|
113
|
+
Args:
|
114
|
+
data (dict[Any, Any]): The data to update the generation info with.
|
115
|
+
"""
|
116
|
+
if os.path.isfile(self.generation_info_path):
|
117
|
+
with open(self.generation_info_path, "r", encoding="utf-8") as file:
|
118
|
+
generation_info = json.load(file)
|
119
|
+
self.logger.debug("Loaded generation info from %s", self.generation_info_path)
|
120
|
+
else:
|
121
|
+
self.logger.debug(
|
122
|
+
"Generation info file does not exist, creating a new one in %s",
|
123
|
+
self.generation_info_path,
|
124
|
+
)
|
125
|
+
generation_info = {}
|
126
|
+
|
127
|
+
updated_generation_info = deepcopy(generation_info)
|
128
|
+
updated_generation_info[self.__class__.__name__] = data
|
129
|
+
|
130
|
+
self.logger.debug("Updated generation info, now contains %s fields", len(data))
|
131
|
+
|
132
|
+
with open(self.generation_info_path, "w", encoding="utf-8") as file:
|
133
|
+
json.dump(updated_generation_info, file, indent=4)
|
134
|
+
|
135
|
+
self.logger.debug("Saved updated generation info to %s", self.generation_info_path)
|
136
|
+
|
71
137
|
def get_bbox(self, project_utm: bool = False) -> tuple[int, int, int, int]:
|
72
138
|
"""Calculates the bounding box of the map from the coordinates and the height and
|
73
139
|
width of the map.
|
maps4fs/generator/config.py
CHANGED
@@ -22,13 +22,15 @@ class Config(Component):
|
|
22
22
|
"""
|
23
23
|
|
24
24
|
def preprocess(self) -> None:
|
25
|
+
"""Gets the path to the map XML file and saves it to the instance variable."""
|
25
26
|
self._map_xml_path = self.game.map_xml_path(self.map_directory)
|
26
27
|
self.logger.debug("Map XML path: %s.", self._map_xml_path)
|
27
28
|
|
28
|
-
def process(self):
|
29
|
+
def process(self) -> None:
|
30
|
+
"""Sets the map size in the map.xml file."""
|
29
31
|
self._set_map_size()
|
30
32
|
|
31
|
-
def _set_map_size(self):
|
33
|
+
def _set_map_size(self) -> None:
|
32
34
|
"""Edits map.xml file to set correct map size."""
|
33
35
|
if not os.path.isfile(self._map_xml_path):
|
34
36
|
self.logger.warning("Map XML file not found: %s.", self._map_xml_path)
|
maps4fs/generator/dem.py
CHANGED
@@ -14,12 +14,12 @@ from maps4fs.generator.component import Component
|
|
14
14
|
|
15
15
|
SRTM = "https://elevation-tiles-prod.s3.amazonaws.com/skadi/{latitude_band}/{tile_name}.hgt.gz"
|
16
16
|
DEFAULT_MULTIPLIER = 1
|
17
|
-
DEFAULT_BLUR_RADIUS =
|
17
|
+
DEFAULT_BLUR_RADIUS = 35
|
18
18
|
|
19
19
|
|
20
20
|
# pylint: disable=R0903
|
21
21
|
class DEM(Component):
|
22
|
-
"""Component for
|
22
|
+
"""Component for processing Digital Elevation Model data.
|
23
23
|
|
24
24
|
Args:
|
25
25
|
coordinates (tuple[float, float]): The latitude and longitude of the center of the map.
|
@@ -40,19 +40,33 @@ class DEM(Component):
|
|
40
40
|
|
41
41
|
self.multiplier = self.kwargs.get("multiplier", DEFAULT_MULTIPLIER)
|
42
42
|
blur_radius = self.kwargs.get("blur_radius", DEFAULT_BLUR_RADIUS)
|
43
|
-
if blur_radius
|
43
|
+
if blur_radius is None or blur_radius <= 0:
|
44
|
+
# We'll disable blur if the radius is 0 or negative.
|
45
|
+
blur_radius = 0
|
46
|
+
elif blur_radius % 2 == 0:
|
44
47
|
blur_radius += 1
|
45
48
|
self.blur_radius = blur_radius
|
46
49
|
self.logger.debug(
|
47
50
|
"DEM value multiplier is %s, blur radius is %s.", self.multiplier, self.blur_radius
|
48
51
|
)
|
49
52
|
|
50
|
-
|
51
|
-
|
52
|
-
|
53
|
-
|
54
|
-
|
53
|
+
self.auto_process = self.kwargs.get("auto_process", False)
|
54
|
+
|
55
|
+
@property
|
56
|
+
def dem_path(self) -> str:
|
57
|
+
"""Returns path to the DEM file.
|
55
58
|
|
59
|
+
Returns:
|
60
|
+
str: Path to the DEM file.
|
61
|
+
"""
|
62
|
+
return self._dem_path
|
63
|
+
|
64
|
+
def get_output_resolution(self) -> tuple[int, int]:
|
65
|
+
"""Get output resolution for DEM data.
|
66
|
+
|
67
|
+
Returns:
|
68
|
+
tuple[int, int]: Output resolution for DEM data.
|
69
|
+
"""
|
56
70
|
dem_height = int((self.map_height / 2) * self.game.dem_multipliyer + 1)
|
57
71
|
dem_width = int((self.map_width / 2) * self.game.dem_multipliyer + 1)
|
58
72
|
self.logger.debug(
|
@@ -61,7 +75,15 @@ class DEM(Component):
|
|
61
75
|
dem_height,
|
62
76
|
dem_width,
|
63
77
|
)
|
64
|
-
|
78
|
+
return dem_width, dem_height
|
79
|
+
|
80
|
+
# pylint: disable=no-member
|
81
|
+
def process(self) -> None:
|
82
|
+
"""Reads SRTM file, crops it to map size, normalizes and blurs it,
|
83
|
+
saves to map directory."""
|
84
|
+
north, south, east, west = self.bbox
|
85
|
+
|
86
|
+
dem_output_resolution = self.get_output_resolution()
|
65
87
|
self.logger.debug("DEM output resolution: %s.", dem_output_resolution)
|
66
88
|
|
67
89
|
tile_path = self._srtm_tile()
|
@@ -105,15 +127,12 @@ class DEM(Component):
|
|
105
127
|
resampled_data.min(),
|
106
128
|
)
|
107
129
|
|
108
|
-
|
109
|
-
|
110
|
-
|
111
|
-
|
112
|
-
|
113
|
-
resampled_data.
|
114
|
-
resampled_data.min(),
|
115
|
-
resampled_data.max(),
|
116
|
-
)
|
130
|
+
if self.auto_process:
|
131
|
+
self.logger.debug("Auto processing is enabled, will normalize DEM data.")
|
132
|
+
resampled_data = self._normalize_dem(resampled_data)
|
133
|
+
else:
|
134
|
+
self.logger.debug("Auto processing is disabled, DEM data will not be normalized.")
|
135
|
+
resampled_data = resampled_data * self.multiplier
|
117
136
|
|
118
137
|
self.logger.debug(
|
119
138
|
"DEM data was resampled. Shape: %s, dtype: %s. Min: %s, max: %s.",
|
@@ -123,11 +142,15 @@ class DEM(Component):
|
|
123
142
|
resampled_data.max(),
|
124
143
|
)
|
125
144
|
|
126
|
-
|
127
|
-
|
128
|
-
|
129
|
-
|
130
|
-
|
145
|
+
if self.blur_radius > 0:
|
146
|
+
resampled_data = cv2.GaussianBlur(
|
147
|
+
resampled_data, (self.blur_radius, self.blur_radius), sigmaX=40, sigmaY=40
|
148
|
+
)
|
149
|
+
self.logger.debug(
|
150
|
+
"Gaussion blur applied to DEM data with kernel size %s.",
|
151
|
+
self.blur_radius,
|
152
|
+
)
|
153
|
+
|
131
154
|
self.logger.debug(
|
132
155
|
"DEM data was blurred. Shape: %s, dtype: %s. Min: %s, max: %s.",
|
133
156
|
resampled_data.shape,
|
@@ -140,10 +163,20 @@ class DEM(Component):
|
|
140
163
|
self.logger.debug("DEM data was saved to %s.", self._dem_path)
|
141
164
|
|
142
165
|
if self.game.additional_dem_name is not None:
|
143
|
-
|
144
|
-
|
145
|
-
|
146
|
-
|
166
|
+
self.make_copy(self.game.additional_dem_name)
|
167
|
+
|
168
|
+
def make_copy(self, dem_name: str) -> None:
|
169
|
+
"""Copies DEM data to additional DEM file.
|
170
|
+
|
171
|
+
Args:
|
172
|
+
dem_name (str): Name of the additional DEM file.
|
173
|
+
"""
|
174
|
+
dem_directory = os.path.dirname(self._dem_path)
|
175
|
+
|
176
|
+
additional_dem_path = os.path.join(dem_directory, dem_name)
|
177
|
+
|
178
|
+
shutil.copyfile(self._dem_path, additional_dem_path)
|
179
|
+
self.logger.debug("Additional DEM data was copied to %s.", additional_dem_path)
|
147
180
|
|
148
181
|
def _tile_info(self, lat: float, lon: float) -> tuple[str, str]:
|
149
182
|
"""Returns latitude band and tile name for SRTM tile from coordinates.
|
@@ -233,14 +266,15 @@ class DEM(Component):
|
|
233
266
|
Returns:
|
234
267
|
str: Path to the preview image.
|
235
268
|
"""
|
236
|
-
rgb_dem_path = self._dem_path.replace(".png", "_grayscale.png")
|
269
|
+
# rgb_dem_path = self._dem_path.replace(".png", "_grayscale.png")
|
270
|
+
grayscale_dem_path = os.path.join(self.previews_directory, "dem_grayscale.png")
|
237
271
|
|
238
|
-
self.logger.debug("Creating grayscale preview of DEM data in %s.",
|
272
|
+
self.logger.debug("Creating grayscale preview of DEM data in %s.", grayscale_dem_path)
|
239
273
|
|
240
274
|
dem_data = cv2.imread(self._dem_path, cv2.IMREAD_GRAYSCALE)
|
241
275
|
dem_data_rgb = cv2.cvtColor(dem_data, cv2.COLOR_GRAY2RGB)
|
242
|
-
cv2.imwrite(
|
243
|
-
return
|
276
|
+
cv2.imwrite(grayscale_dem_path, dem_data_rgb)
|
277
|
+
return grayscale_dem_path
|
244
278
|
|
245
279
|
def colored_preview(self) -> str:
|
246
280
|
"""Converts DEM image to colored RGB image and saves it to the map directory.
|
@@ -250,7 +284,8 @@ class DEM(Component):
|
|
250
284
|
list[str]: List with a single path to the DEM file
|
251
285
|
"""
|
252
286
|
|
253
|
-
colored_dem_path = self._dem_path.replace(".png", "_colored.png")
|
287
|
+
# colored_dem_path = self._dem_path.replace(".png", "_colored.png")
|
288
|
+
colored_dem_path = os.path.join(self.previews_directory, "dem_colored.png")
|
254
289
|
|
255
290
|
self.logger.debug("Creating colored preview of DEM data in %s.", colored_dem_path)
|
256
291
|
|
@@ -289,3 +324,51 @@ class DEM(Component):
|
|
289
324
|
"""
|
290
325
|
self.logger.debug("Starting DEM previews generation.")
|
291
326
|
return [self.grayscale_preview(), self.colored_preview()]
|
327
|
+
|
328
|
+
def _get_scaling_factor(self, maximum_deviation: int) -> float:
|
329
|
+
"""Calculate scaling factor for DEM data normalization.
|
330
|
+
NOTE: Needs reconsideration for the implementation.
|
331
|
+
|
332
|
+
Args:
|
333
|
+
maximum_deviation (int): Maximum deviation in DEM data.
|
334
|
+
|
335
|
+
Returns:
|
336
|
+
float: Scaling factor for DEM data normalization.
|
337
|
+
"""
|
338
|
+
ESTIMATED_MAXIMUM_DEVIATION = 1000 # pylint: disable=C0103
|
339
|
+
scaling_factor = maximum_deviation / ESTIMATED_MAXIMUM_DEVIATION
|
340
|
+
return scaling_factor if scaling_factor < 1 else 1
|
341
|
+
|
342
|
+
def _normalize_dem(self, data: np.ndarray) -> np.ndarray:
|
343
|
+
"""Normalize DEM data to 16-bit unsigned integer using max height from settings.
|
344
|
+
Args:
|
345
|
+
data (np.ndarray): DEM data from SRTM file after cropping.
|
346
|
+
Returns:
|
347
|
+
np.ndarray: Normalized DEM data.
|
348
|
+
"""
|
349
|
+
self.logger.debug("Starting DEM data normalization.")
|
350
|
+
# Calculate the difference between the maximum and minimum values in the DEM data.
|
351
|
+
|
352
|
+
max_height = data.max() # 1800
|
353
|
+
min_height = data.min() # 1700
|
354
|
+
max_dev = max_height - min_height # 100
|
355
|
+
self.logger.debug(
|
356
|
+
"Maximum deviation: %s with maximum at %s and minimum at %s.",
|
357
|
+
max_dev,
|
358
|
+
max_height,
|
359
|
+
min_height,
|
360
|
+
)
|
361
|
+
|
362
|
+
scaling_factor = self._get_scaling_factor(max_dev)
|
363
|
+
adjusted_max_height = int(65535 * scaling_factor)
|
364
|
+
self.logger.debug(
|
365
|
+
f"Maximum deviation: {max_dev}. Scaling factor: {scaling_factor}. "
|
366
|
+
f"Adjusted max height: {adjusted_max_height}."
|
367
|
+
)
|
368
|
+
normalized_data = (
|
369
|
+
(data - data.min()) / (data.max() - data.min()) * adjusted_max_height
|
370
|
+
).astype("uint16")
|
371
|
+
self.logger.debug(
|
372
|
+
f"DEM data was normalized to {normalized_data.min()} - {normalized_data.max()}."
|
373
|
+
)
|
374
|
+
return normalized_data
|
maps4fs/generator/game.py
CHANGED
@@ -6,8 +6,10 @@ from __future__ import annotations
|
|
6
6
|
|
7
7
|
import os
|
8
8
|
|
9
|
+
from maps4fs.generator.background import Background
|
9
10
|
from maps4fs.generator.config import Config
|
10
11
|
from maps4fs.generator.dem import DEM
|
12
|
+
from maps4fs.generator.i3d import I3d
|
11
13
|
from maps4fs.generator.texture import Texture
|
12
14
|
|
13
15
|
working_directory = os.getcwd()
|
@@ -34,7 +36,7 @@ class Game:
|
|
34
36
|
_map_template_path: str | None = None
|
35
37
|
_texture_schema: str | None = None
|
36
38
|
|
37
|
-
components = [Config, Texture, DEM]
|
39
|
+
components = [Config, Texture, DEM, I3d, Background]
|
38
40
|
|
39
41
|
def __init__(self, map_template_path: str | None = None):
|
40
42
|
if map_template_path:
|
@@ -113,6 +115,16 @@ class Game:
|
|
113
115
|
str: The path to the weights directory."""
|
114
116
|
raise NotImplementedError
|
115
117
|
|
118
|
+
def i3d_file_path(self, map_directory: str) -> str:
|
119
|
+
"""Returns the path to the i3d file.
|
120
|
+
|
121
|
+
Arguments:
|
122
|
+
map_directory (str): The path to the map directory.
|
123
|
+
|
124
|
+
Returns:
|
125
|
+
str: The path to the i3d file."""
|
126
|
+
raise NotImplementedError
|
127
|
+
|
116
128
|
@property
|
117
129
|
def additional_dem_name(self) -> str | None:
|
118
130
|
"""Returns the name of the additional DEM file.
|
@@ -122,6 +134,7 @@ class Game:
|
|
122
134
|
return self._additional_dem_name
|
123
135
|
|
124
136
|
|
137
|
+
# pylint: disable=W0223
|
125
138
|
class FS22(Game):
|
126
139
|
"""Class used to define the game version FS22."""
|
127
140
|
|
@@ -189,3 +202,13 @@ class FS25(Game):
|
|
189
202
|
Returns:
|
190
203
|
str: The path to the weights directory."""
|
191
204
|
return os.path.join(map_directory, "mapUS", "data")
|
205
|
+
|
206
|
+
def i3d_file_path(self, map_directory: str) -> str:
|
207
|
+
"""Returns the path to the i3d file.
|
208
|
+
|
209
|
+
Arguments:
|
210
|
+
map_directory (str): The path to the map directory.
|
211
|
+
|
212
|
+
Returns:
|
213
|
+
str: The path to the i3d file."""
|
214
|
+
return os.path.join(map_directory, "mapUS", "mapUS.i3d")
|