system_assignation/hub/exports/formats/obj.py

58 lines
1.7 KiB
Python
Raw Normal View History

2021-03-16 20:14:40 -04:00
"""
export a city into Obj format
SPDX - License - Identifier: LGPL - 3.0 - or -later
Copyright © 2022 Concordia CERC group
Project Coder Guille Gutierrez guillermo.gutierrezmorote@concordia.ca
2021-03-16 20:14:40 -04:00
"""
2021-03-16 16:58:52 -04:00
from pathlib import Path
2023-03-16 10:51:41 -04:00
class Obj:
2021-08-26 13:27:43 -04:00
"""
Export to obj format
"""
def __init__(self, city, path):
2023-03-16 10:51:41 -04:00
self._city = city
self._path = path
self._export()
def _to_vertex(self, coordinate):
x = coordinate[0] - self._city.lower_corner[0]
y = coordinate[1] - self._city.lower_corner[1]
z = coordinate[2] - self._city.lower_corner[2]
return f'v {x} {y} {z}\n'
def _export(self):
if self._city.name is None:
self._city.name = 'unknown_city'
file_name = self._city.name + '.obj'
file_path = (Path(self._path).resolve() / file_name).resolve()
vertices = {}
2023-05-31 13:51:35 -04:00
with open(file_path, 'w', encoding='utf-8') as obj:
2023-03-16 10:51:41 -04:00
obj.write("# cerc-hub export\n")
vertex_index = 0
faces = []
for building in self._city.buildings:
obj.write(f'# building {building.name}\n')
2023-03-17 13:36:43 -04:00
obj.write(f'g {building.name}\n')
obj.write('s off\n')
2023-03-16 10:51:41 -04:00
for surface in building.surfaces:
obj.write(f'# surface {surface.name}\n')
face = 'f '
for coordinate in surface.perimeter_polygon.coordinates:
vertex = self._to_vertex(coordinate)
2023-05-31 13:51:35 -04:00
if vertex not in vertices:
2023-03-16 10:51:41 -04:00
vertex_index += 1
vertices[vertex] = vertex_index
current = vertex_index
obj.write(vertex)
else:
current = vertices[vertex]
face = f'{face} {current}'
faces.append(f'{face} {face.split(" ")[1]}\n')
obj.writelines(faces)
faces = []