maps4fs 1.8.172__tar.gz → 1.8.174__tar.gz

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.

Potentially problematic release.


This version of maps4fs might be problematic. Click here for more details.

Files changed (56) hide show
  1. {maps4fs-1.8.172 → maps4fs-1.8.174}/PKG-INFO +2 -2
  2. {maps4fs-1.8.172 → maps4fs-1.8.174}/README.md +1 -1
  3. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/component/background.py +9 -11
  4. maps4fs-1.8.174/maps4fs/generator/component/base/component_mesh.py +242 -0
  5. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/settings.py +1 -1
  6. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs.egg-info/PKG-INFO +2 -2
  7. {maps4fs-1.8.172 → maps4fs-1.8.174}/pyproject.toml +1 -1
  8. {maps4fs-1.8.172 → maps4fs-1.8.174}/tests/test_generator.py +12 -3
  9. maps4fs-1.8.172/maps4fs/generator/component/base/component_mesh.py +0 -125
  10. {maps4fs-1.8.172 → maps4fs-1.8.174}/LICENSE.md +0 -0
  11. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/__init__.py +0 -0
  12. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/__init__.py +0 -0
  13. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/component/__init__.py +0 -0
  14. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/component/base/__init__.py +0 -0
  15. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/component/base/component.py +0 -0
  16. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/component/base/component_image.py +0 -0
  17. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/component/base/component_xml.py +0 -0
  18. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/component/config.py +0 -0
  19. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/component/grle.py +0 -0
  20. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/component/i3d.py +0 -0
  21. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dem.py +0 -0
  22. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/__init__.py +0 -0
  23. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/base/wcs.py +0 -0
  24. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/base/wms.py +0 -0
  25. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/bavaria.py +0 -0
  26. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/canada.py +0 -0
  27. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/dtm.py +0 -0
  28. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/england.py +0 -0
  29. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/finland.py +0 -0
  30. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/flanders.py +0 -0
  31. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/france.py +0 -0
  32. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/hessen.py +0 -0
  33. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/italy.py +0 -0
  34. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/niedersachsen.py +0 -0
  35. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/norway.py +0 -0
  36. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/nrw.py +0 -0
  37. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/scotland.py +0 -0
  38. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/spain.py +0 -0
  39. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/srtm.py +0 -0
  40. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/usgs.py +0 -0
  41. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/dtm/utils.py +0 -0
  42. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/game.py +0 -0
  43. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/map.py +0 -0
  44. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/qgis.py +0 -0
  45. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/satellite.py +0 -0
  46. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/generator/texture.py +0 -0
  47. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/logger.py +0 -0
  48. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/toolbox/__init__.py +0 -0
  49. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/toolbox/background.py +0 -0
  50. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/toolbox/custom_osm.py +0 -0
  51. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs/toolbox/dem.py +0 -0
  52. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs.egg-info/SOURCES.txt +0 -0
  53. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs.egg-info/dependency_links.txt +0 -0
  54. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs.egg-info/requires.txt +0 -0
  55. {maps4fs-1.8.172 → maps4fs-1.8.174}/maps4fs.egg-info/top_level.txt +0 -0
  56. {maps4fs-1.8.172 → maps4fs-1.8.174}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: maps4fs
3
- Version: 1.8.172
3
+ Version: 1.8.174
4
4
  Summary: Generate map templates for Farming Simulator from real places.
5
5
  Author-email: iwatkot <iwatkot@gmail.com>
6
6
  License: MIT License
@@ -582,7 +582,7 @@ You can also apply some advanced settings to the map generation process.<br>
582
582
 
583
583
  - Resize factor - the factor by which the background terrain will be resized. It will be used as 1 / resize_factor while generating the models. Which means that the larger the value the more the terrain will be resized. The lowest value is 1, in this case background terrain will not be resized. Note, than low values will lead to long processing and enormous size of the obj files.
584
584
 
585
- - Remove center - if enabled, the playable region (map terrain) will be removed from the background terrain. Note, that it will require low resize factors, to avoid gaps between the map and the background terrain.
585
+ - Remove center - if enabled, the playable region (map terrain) will be removed from the background terrain. By default, it's set to True.
586
586
 
587
587
  - Apply decimation - if enabled, the mesh will be simplified to reduce the number of faces.
588
588
 
@@ -556,7 +556,7 @@ You can also apply some advanced settings to the map generation process.<br>
556
556
 
557
557
  - Resize factor - the factor by which the background terrain will be resized. It will be used as 1 / resize_factor while generating the models. Which means that the larger the value the more the terrain will be resized. The lowest value is 1, in this case background terrain will not be resized. Note, than low values will lead to long processing and enormous size of the obj files.
558
558
 
559
- - Remove center - if enabled, the playable region (map terrain) will be removed from the background terrain. Note, that it will require low resize factors, to avoid gaps between the map and the background terrain.
559
+ - Remove center - if enabled, the playable region (map terrain) will be removed from the background terrain. By default, it's set to True.
560
560
 
561
561
  - Apply decimation - if enabled, the mesh will be simplified to reduce the number of faces.
562
562
 
@@ -235,24 +235,16 @@ class Background(MeshComponent, ImageComponent):
235
235
  This setting is used for a Background Terrain, where the center part where the
236
236
  playable area is will be cut out.
237
237
  """
238
- resize_factor = 1 / self.map.background_settings.resize_factor
239
- dem_data = cv2.resize(dem_data, (0, 0), fx=resize_factor, fy=resize_factor)
240
- if remove_center:
241
- half_size = int(self.map_size // 2 * resize_factor)
242
- dem_data = self.cut_out_np(dem_data, half_size, set_zeros=True)
243
- self.logger.debug("Center removed from DEM data.")
244
- self.logger.debug(
245
- "DEM data resized to shape: %s with factor: %s", dem_data.shape, resize_factor
246
- )
247
-
248
238
  mesh = self.mesh_from_np(
249
239
  dem_data,
250
240
  include_zeros=include_zeros,
251
241
  z_scaling_factor=self.get_z_scaling_factor(),
252
- resize_factor=resize_factor,
242
+ resize_factor=self.map.background_settings.resize_factor,
253
243
  apply_decimation=self.map.background_settings.apply_decimation,
254
244
  decimation_percent=self.map.background_settings.decimation_percent,
255
245
  decimation_agression=self.map.background_settings.decimation_agression,
246
+ remove_center=remove_center,
247
+ remove_size=self.map_size,
256
248
  )
257
249
 
258
250
  mesh.export(save_path)
@@ -440,6 +432,12 @@ class Background(MeshComponent, ImageComponent):
440
432
 
441
433
  # Single channeled 8 bit image, where the water have values of 255, and the rest 0.
442
434
  plane_water = cv2.imread(self.water_resources_path, cv2.IMREAD_UNCHANGED)
435
+
436
+ # Check if the image contains non-zero values.
437
+ if not np.any(plane_water):
438
+ self.logger.warning("Water resources image is empty, skipping water generation.")
439
+ return
440
+
443
441
  dilated_plane_water = cv2.dilate(
444
442
  plane_water.astype(np.uint8), np.ones((5, 5), np.uint8), iterations=5
445
443
  ).astype(np.uint8)
@@ -0,0 +1,242 @@
1
+ """Base class for all components that primarily used to work with meshes."""
2
+
3
+ import cv2
4
+ import numpy as np
5
+ import trimesh
6
+ from tqdm import tqdm
7
+
8
+ from maps4fs.generator.component.base.component import Component
9
+ from maps4fs.generator.settings import Parameters
10
+
11
+
12
+ class MeshComponent(Component):
13
+ """Base class for all components that primarily used to work with meshes."""
14
+
15
+ @staticmethod
16
+ def validate_np_for_mesh(image_path: str, map_size: int) -> None:
17
+ """Checks if the given image is a valid for mesh generation.
18
+
19
+ Arguments:
20
+ image_path (str): The path to the custom background image.
21
+ map_size (int): The size of the map.
22
+
23
+ Raises:
24
+ ValueError: If the custom background image does not meet the requirements.
25
+ """
26
+ image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
27
+ if image.shape[0] != image.shape[1]:
28
+ raise ValueError("The custom background image must be a square.")
29
+
30
+ if image.shape[0] != map_size + Parameters.BACKGROUND_DISTANCE * 2:
31
+ raise ValueError("The custom background image must have the size of the map + 4096.")
32
+
33
+ if len(image.shape) != 2:
34
+ raise ValueError("The custom background image must be a grayscale image.")
35
+
36
+ if image.dtype != np.uint16:
37
+ raise ValueError("The custom background image must be a 16-bit grayscale image.")
38
+
39
+ @staticmethod
40
+ def mesh_to_stl(mesh: trimesh.Trimesh, save_path: str) -> None:
41
+ """Converts the mesh to an STL file and saves it in the previews directory.
42
+ Uses powerful simplification to reduce the size of the file since it will be used
43
+ only for the preview.
44
+
45
+ Arguments:
46
+ mesh (trimesh.Trimesh) -- The mesh to convert to an STL file.
47
+ """
48
+ mesh = mesh.simplify_quadric_decimation(face_count=len(mesh.faces) // 2**6)
49
+ mesh.export(save_path)
50
+
51
+ @staticmethod
52
+ def mesh_from_np(
53
+ image: np.ndarray,
54
+ include_zeros: bool,
55
+ z_scaling_factor: float,
56
+ resize_factor: int,
57
+ apply_decimation: bool,
58
+ decimation_percent: int,
59
+ decimation_agression: int,
60
+ remove_center: bool,
61
+ remove_size: int,
62
+ ) -> trimesh.Trimesh:
63
+ """Generates a mesh from the given numpy array.
64
+
65
+ Arguments:
66
+ image (np.ndarray): The numpy array to generate the mesh from.
67
+ include_zeros (bool): Whether to include zero values in the mesh.
68
+ z_scaling_factor (float): The scaling factor for the Z-axis.
69
+ resize_factor (int): The resizing factor.
70
+ apply_decimation (bool): Whether to apply decimation to the mesh.
71
+ decimation_percent (int): The percent of the decimation.
72
+ decimation_agression (int): The agression of the decimation.
73
+ remove_center (bool): Whether to remove the center from the mesh.
74
+ remove_size (int): The size of the center to remove.
75
+
76
+ Returns:
77
+ trimesh.Trimesh: The generated mesh.
78
+ """
79
+ output_x_size, _ = image.shape
80
+ image = image.max() - image
81
+
82
+ image = image[::resize_factor, ::resize_factor]
83
+
84
+ rows, cols = image.shape
85
+ x = np.linspace(0, cols - 1, cols)
86
+ y = np.linspace(0, rows - 1, rows)
87
+ x, y = np.meshgrid(x, y)
88
+ z = image
89
+
90
+ ground = z.max()
91
+
92
+ vertices = np.column_stack([x.ravel(), y.ravel(), z.ravel()])
93
+ faces = []
94
+
95
+ skipped = 0
96
+
97
+ for i in tqdm(range(rows - 1), desc="Generating mesh", unit="row"):
98
+ for j in range(cols - 1):
99
+ top_left = i * cols + j
100
+ top_right = top_left + 1
101
+ bottom_left = top_left + cols
102
+ bottom_right = bottom_left + 1
103
+
104
+ if (
105
+ ground in [z[i, j], z[i, j + 1], z[i + 1, j], z[i + 1, j + 1]]
106
+ and not include_zeros
107
+ ):
108
+ skipped += 1
109
+ continue
110
+
111
+ faces.append([top_left, bottom_left, bottom_right])
112
+ faces.append([top_left, bottom_right, top_right])
113
+
114
+ faces_np = np.array(faces)
115
+ mesh = trimesh.Trimesh(vertices=vertices, faces=faces_np)
116
+ mesh = MeshComponent.rotate_mesh(mesh)
117
+
118
+ if apply_decimation:
119
+ percent = decimation_percent / 100
120
+ mesh = mesh.simplify_quadric_decimation(
121
+ percent=percent, aggression=decimation_agression
122
+ )
123
+
124
+ try:
125
+ if not mesh.is_watertight:
126
+ mesh = MeshComponent.fix_mesh(mesh)
127
+ except Exception:
128
+ pass
129
+
130
+ mesh = MeshComponent.mesh_to_output_size(
131
+ mesh,
132
+ resize_factor,
133
+ z_scaling_factor,
134
+ output_x_size,
135
+ skip_resize_to_expected_size=not include_zeros,
136
+ )
137
+
138
+ if remove_center:
139
+ mesh = MeshComponent.remove_center_from_mesh(mesh, remove_size)
140
+
141
+ return mesh
142
+
143
+ @staticmethod
144
+ def rotate_mesh(mesh: trimesh.Trimesh) -> trimesh.Trimesh:
145
+ """Rotates the given mesh by 180 degrees around the Y-axis and Z-axis.
146
+
147
+ Arguments:
148
+ mesh (trimesh.Trimesh): The mesh to rotate.
149
+
150
+ Returns:
151
+ trimesh.Trimesh: The rotated mesh.
152
+ """
153
+ mesh_copy = mesh.copy()
154
+
155
+ rotation_matrices = [
156
+ trimesh.transformations.rotation_matrix(np.pi, [0, 1, 0]),
157
+ trimesh.transformations.rotation_matrix(np.pi, [0, 0, 1]),
158
+ ]
159
+
160
+ for rotation_matrix in tqdm(rotation_matrices, desc="Rotating mesh", unit="rotation"):
161
+ mesh_copy.apply_transform(rotation_matrix)
162
+
163
+ return mesh_copy
164
+
165
+ @staticmethod
166
+ def fix_mesh(mesh: trimesh.Trimesh) -> trimesh.Trimesh:
167
+ """Fixes the given mesh by filling holes, fixing normals, fixing winding, fixing inversion,
168
+ fixing broken faces, and stitching.
169
+
170
+ Arguments:
171
+ mesh (trimesh.Trimesh): The mesh to fix.
172
+
173
+ Returns:
174
+ trimesh.Trimesh: The fixed mesh.
175
+ """
176
+ mesh_copy = mesh.copy()
177
+
178
+ fix_methods = [
179
+ trimesh.repair.fill_holes,
180
+ trimesh.repair.fix_normals,
181
+ trimesh.repair.fix_winding,
182
+ trimesh.repair.fix_inversion,
183
+ trimesh.repair.broken_faces,
184
+ trimesh.repair.stitch,
185
+ ]
186
+
187
+ for method in tqdm(fix_methods, desc="Fixing mesh", unit="method"):
188
+ method(mesh_copy) # type: ignore
189
+
190
+ return mesh_copy
191
+
192
+ @staticmethod
193
+ def mesh_to_output_size(
194
+ mesh: trimesh.Trimesh,
195
+ resize_factor: int,
196
+ z_scaling_factor: float,
197
+ expected_size: int,
198
+ skip_resize_to_expected_size: bool = False,
199
+ ) -> trimesh.Trimesh:
200
+ """Resizes the given mesh to the expected size.
201
+
202
+ Arguments:
203
+ mesh (trimesh.Trimesh): The mesh to resize.
204
+ resize_factor (int): The resizing factor.
205
+ z_scaling_factor (float): The scaling factor for the Z-axis.
206
+ expected_size (int): The expected size.
207
+ skip_resize_to_expected_size (bool): Whether to skip resizing to the expected size.
208
+
209
+ Returns:
210
+ trimesh.Trimesh: The resized mesh.
211
+ """
212
+ mesh_copy = mesh.copy()
213
+
214
+ mesh_copy.apply_scale([resize_factor / 1, resize_factor / 1, z_scaling_factor])
215
+
216
+ if not skip_resize_to_expected_size:
217
+ x_size, y_size, _ = mesh_copy.extents
218
+ x_resize_factor = expected_size / x_size
219
+ y_resize_factor = expected_size / y_size
220
+
221
+ mesh_copy.apply_scale([x_resize_factor, y_resize_factor, 1])
222
+ return mesh_copy
223
+
224
+ @staticmethod
225
+ def remove_center_from_mesh(mesh: trimesh.Trimesh, remove_size: int) -> trimesh.Trimesh:
226
+ """Removes the center from the given mesh.
227
+
228
+ Arguments:
229
+ mesh (trimesh.Trimesh): The mesh to remove the center from.
230
+ remove_size (int): The size of the center to remove.
231
+
232
+ Returns:
233
+ trimesh.Trimesh: The mesh with the center removed.
234
+ """
235
+ mesh_copy = mesh.copy()
236
+
237
+ _, _, z_size = mesh_copy.extents
238
+
239
+ cube_mesh = trimesh.creation.box([remove_size, remove_size, z_size * 4])
240
+ cube_mesh.apply_translation(mesh_copy.centroid - cube_mesh.centroid)
241
+
242
+ return trimesh.boolean.difference([mesh_copy, cube_mesh], check_volume=False)
@@ -133,7 +133,7 @@ class BackgroundSettings(SettingsModel):
133
133
  generate_background: bool = False
134
134
  generate_water: bool = False
135
135
  resize_factor: int = 8
136
- remove_center: bool = False
136
+ remove_center: bool = True
137
137
  apply_decimation: bool = False
138
138
  decimation_percent: int = 25
139
139
  decimation_agression: int = 3
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: maps4fs
3
- Version: 1.8.172
3
+ Version: 1.8.174
4
4
  Summary: Generate map templates for Farming Simulator from real places.
5
5
  Author-email: iwatkot <iwatkot@gmail.com>
6
6
  License: MIT License
@@ -582,7 +582,7 @@ You can also apply some advanced settings to the map generation process.<br>
582
582
 
583
583
  - Resize factor - the factor by which the background terrain will be resized. It will be used as 1 / resize_factor while generating the models. Which means that the larger the value the more the terrain will be resized. The lowest value is 1, in this case background terrain will not be resized. Note, than low values will lead to long processing and enormous size of the obj files.
584
584
 
585
- - Remove center - if enabled, the playable region (map terrain) will be removed from the background terrain. Note, that it will require low resize factors, to avoid gaps between the map and the background terrain.
585
+ - Remove center - if enabled, the playable region (map terrain) will be removed from the background terrain. By default, it's set to True.
586
586
 
587
587
  - Apply decimation - if enabled, the mesh will be simplified to reduce the number of faces.
588
588
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "maps4fs"
7
- version = "1.8.172"
7
+ version = "1.8.174"
8
8
  description = "Generate map templates for Farming Simulator from real places."
9
9
  authors = [{name = "iwatkot", email = "iwatkot@gmail.com"}]
10
10
  license = {text = "MIT License"}
@@ -39,6 +39,14 @@ dtm_provider = DTMProvider.get_provider_by_code(dtm_provider_code)
39
39
  dtm_settings = SRTM30ProviderSettings()
40
40
 
41
41
 
42
+ background_settings = BackgroundSettings(
43
+ generate_background=True,
44
+ generate_water=True,
45
+ resize_factor=16,
46
+ remove_center=False,
47
+ )
48
+
49
+
42
50
  def get_random_size() -> tuple[int, int]:
43
51
  """Return random size.
44
52
 
@@ -85,10 +93,13 @@ def test_map():
85
93
  height, width = get_random_size()
86
94
  directory = map_directory(game_code)
87
95
 
96
+ print(f"Generating map for {game_code} at {coordinates} with size {height}x{width}...")
97
+
88
98
  map = Map(
89
99
  game=game,
90
100
  dtm_provider=dtm_provider,
91
101
  dtm_provider_settings=dtm_settings,
102
+ background_settings=background_settings,
92
103
  coordinates=coordinates,
93
104
  size=height,
94
105
  rotation=0,
@@ -151,6 +162,7 @@ def test_map_preview():
151
162
  game=game,
152
163
  dtm_provider=dtm_provider,
153
164
  dtm_provider_settings=dtm_settings,
165
+ background_settings=background_settings,
154
166
  coordinates=case,
155
167
  size=height,
156
168
  rotation=0,
@@ -178,9 +190,6 @@ def test_map_pack():
178
190
 
179
191
  dem_settings = DEMSettings(multiplier=2, blur_radius=15, plateau=1000, water_depth=500)
180
192
 
181
- background_settings = BackgroundSettings(
182
- generate_background=True, generate_water=True, resize_factor=16
183
- )
184
193
  satellite_settings = SatelliteSettings(download_images=True, satellite_margin=0, zoom_level=14)
185
194
 
186
195
  directory = map_directory(game_code)
@@ -1,125 +0,0 @@
1
- """Base class for all components that primarily used to work with meshes."""
2
-
3
- import cv2
4
- import numpy as np
5
- import trimesh
6
- from tqdm import tqdm
7
-
8
- from maps4fs.generator.component.base.component import Component
9
- from maps4fs.generator.settings import Parameters
10
-
11
-
12
- class MeshComponent(Component):
13
- """Base class for all components that primarily used to work with meshes."""
14
-
15
- @staticmethod
16
- def validate_np_for_mesh(image_path: str, map_size: int) -> None:
17
- """Checks if the given image is a valid for mesh generation.
18
-
19
- Arguments:
20
- image_path (str): The path to the custom background image.
21
- map_size (int): The size of the map.
22
-
23
- Raises:
24
- ValueError: If the custom background image does not meet the requirements.
25
- """
26
- image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
27
- if image.shape[0] != image.shape[1]:
28
- raise ValueError("The custom background image must be a square.")
29
-
30
- if image.shape[0] != map_size + Parameters.BACKGROUND_DISTANCE * 2:
31
- raise ValueError("The custom background image must have the size of the map + 4096.")
32
-
33
- if len(image.shape) != 2:
34
- raise ValueError("The custom background image must be a grayscale image.")
35
-
36
- if image.dtype != np.uint16:
37
- raise ValueError("The custom background image must be a 16-bit grayscale image.")
38
-
39
- @staticmethod
40
- def mesh_to_stl(mesh: trimesh.Trimesh, save_path: str) -> None:
41
- """Converts the mesh to an STL file and saves it in the previews directory.
42
- Uses powerful simplification to reduce the size of the file since it will be used
43
- only for the preview.
44
-
45
- Arguments:
46
- mesh (trimesh.Trimesh) -- The mesh to convert to an STL file.
47
- """
48
- mesh = mesh.simplify_quadric_decimation(face_count=len(mesh.faces) // 2**6)
49
- mesh.export(save_path)
50
-
51
- @staticmethod
52
- def mesh_from_np(
53
- image: np.ndarray,
54
- include_zeros: bool,
55
- z_scaling_factor: float,
56
- resize_factor: float,
57
- apply_decimation: bool,
58
- decimation_percent: int,
59
- decimation_agression: int,
60
- ) -> trimesh.Trimesh:
61
- """Generates a mesh from the given numpy array.
62
-
63
- Arguments:
64
- image (np.ndarray): The numpy array to generate the mesh from.
65
- include_zeros (bool): Whether to include zero values in the mesh.
66
- z_scaling_factor (float): The scaling factor for the Z-axis.
67
- resize_factor (float): The resizing factor.
68
- apply_decimation (bool): Whether to apply decimation to the mesh.
69
- decimation_percent (int): The percent of the decimation.
70
- decimation_agression (int): The agression of the decimation.
71
-
72
- Returns:
73
- trimesh.Trimesh: The generated mesh.
74
- """
75
- image = image.max() - image
76
-
77
- rows, cols = image.shape
78
- x = np.linspace(0, cols - 1, cols)
79
- y = np.linspace(0, rows - 1, rows)
80
- x, y = np.meshgrid(x, y)
81
- z = image
82
-
83
- ground = z.max()
84
-
85
- vertices = np.column_stack([x.ravel(), y.ravel(), z.ravel()])
86
- faces = []
87
-
88
- skipped = 0
89
-
90
- for i in tqdm(range(rows - 1), desc="Generating mesh", unit="row"):
91
- for j in range(cols - 1):
92
- top_left = i * cols + j
93
- top_right = top_left + 1
94
- bottom_left = top_left + cols
95
- bottom_right = bottom_left + 1
96
-
97
- if (
98
- ground in [z[i, j], z[i, j + 1], z[i + 1, j], z[i + 1, j + 1]]
99
- and not include_zeros
100
- ):
101
- skipped += 1
102
- continue
103
-
104
- faces.append([top_left, bottom_left, bottom_right])
105
- faces.append([top_left, bottom_right, top_right])
106
-
107
- faces_np = np.array(faces)
108
- mesh = trimesh.Trimesh(vertices=vertices, faces=faces_np)
109
-
110
- # Apply rotation: 180 degrees around Y-axis and Z-axis
111
- rotation_matrix_y = trimesh.transformations.rotation_matrix(np.pi, [0, 1, 0])
112
- rotation_matrix_z = trimesh.transformations.rotation_matrix(np.pi, [0, 0, 1])
113
- mesh.apply_transform(rotation_matrix_y)
114
- mesh.apply_transform(rotation_matrix_z)
115
-
116
- # if not include_zeros:
117
- mesh.apply_scale([1 / resize_factor, 1 / resize_factor, z_scaling_factor])
118
-
119
- if apply_decimation:
120
- percent = decimation_percent / 100
121
- mesh = mesh.simplify_quadric_decimation(
122
- percent=percent, aggression=decimation_agression
123
- )
124
-
125
- return mesh
File without changes
File without changes
File without changes
File without changes