-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcityjson2ifc.py
473 lines (416 loc) · 22.5 KB
/
cityjson2ifc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# ifccityjson - Python CityJSON to IFC converter
# Copyright (C) 2021 Laurens J.N. Oostwegel <[email protected]>
# Copyright (C) 2023 Balázs Dukai <[email protected]>
#
# This file is part of ifccityjson.
#
# ifccityjson is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ifccityjson 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with ifccityjson. If not, see <http://www.gnu.org/licenses/>.
import os
import ifcopenshell
import ifcopenshell.api
import ifcopenshell.guid
from datetime import datetime,timezone
from geometry import GeometryIO
JSON_TO_IFC = {
"Building": ["IfcBuilding"],
"BuildingPart": ["IfcBuilding", {"CompositionType": "PARTIAL"}],
"BuildingInstallation": ["IfcBuildingElementProxy"],
"BuildingConstructiveElement": ["IfcBuildingElementProxy"],
"BuildingFurniture": ["IfcFurniture"],
"BuildingStorey": ["IfcBuildingStorey", {"CompositionType": "PARTIAL"}],
"BuildingRoom": ["IfcSpace", {"CompositionType": "ELEMENT"}],
"BuildingUnit": ["IfcSpace", {"CompositionType": "ELEMENT"}],
"Road": ["IfcCivilElement"], # Update for IFC4.3
"Railway": ["IfcCivilElement"], # Update for IFC4.3
"TransportationSquare": ["IfcCivilElement"], # Update for IFC4.3
"TINRelief": ["IfcGeographicElement", {"PredefinedType": "TERRAIN"}],
"WaterBody": [
"IfcGeographicElement",
{"PredefinedType": "USERDEFINED", "ObjectType": "WaterBody"},
], # Update for IFC4.3
"LandUse": ["IfcGeographicElement", {"PredefinedType": "USERDEFINED", "ObjectType": "LandUse"}],
"PlantCover": ["IfcGeographicElement", {"PredefinedType": "USERDEFINED", "ObjectType": "Plantcover"}],
"SolitaryVegetationObject": [
"IfcGeographicElement",
{"PredefinedType": "USERDEFINED", "ObjectType": "SolitaryVegetationObject"},
],
"CityFurniture": ["IfcFurnishingElement"],
"OtherConstruction": ["IfcCivilElement"],
"+GenericCityObject": [
"IfcCivilElement"
], # We make an exception here, because GenericCityObject is a remnant from CityJSON v1.0, which was moved to an extension in v1.1 and it is commonly used.
"Bridge": ["IfcCivilElement"], # Update for IFC4.3
"BridgePart": ["IfcCivilElement"], # Update for IFC4.3
"BridgeInstallation": ["IfcCivilElement"], # Update for IFC4.3
"BridgeConstructiveElement": ["IfcCivilElement"], # Update for IFC4.3
"BridgeRoom": ["IfcCivilElement"], # Update for IFC4.3
"BridgeFurniture": ["IfcCivilElement"], # Update for IFC4.3
"Tunnel": ["IfcCivilElement"], # Update for IFC4.3
"TunnelPart": ["IfcCivilElement"], # Update for IFC4.3
"TunnelInstallation": ["IfcCivilElement"], # Update for IFC4.3
"TunnelConstructiveElement": ["IfcCivilElement"], # Update for IFC4.3
"TunnelHollowSpace": ["IfcCivilElement"], # Update for IFC4.3
"TunnelFurniture": ["IfcCivilElement"], # Update for IFC4.3
"CityObjectGroup": ["IfcBuilding"], # Update for IFC4.3
"GroundSurface": ["IfcSlab", {"PredefinedType": "BASESLAB"}],
"RoofSurface": ["IfcRoof"],
"WallSurface": ["IfcWall"],
"ClosureSurface": ["IfcSpace"],
"OuterCeilingSurface": ["IfcCovering", {"PredefinedType": "CEILING"}],
"OuterFloorSurface": ["IfcSlab", {"PredefinedType": "FLOOR"}],
"Window": ["IfcWindow"],
"Door": ["IfcDoor"],
"InteriorWallSurface": ["IfcWall"],
"CeilingSurface": ["IfcCovering", {"PredefinedType": "CEILING"}],
"FloorSurface": ["IfcSlab", {"PredefinedType": "FLOOR"}],
"WaterSurface": [
"IfcGeographicElement",
{"PredefinedType": "USERDEFINED", "ObjectType": "WaterSurface"},
], # Update for IFC4.3
"WaterGroundSurface": [
"IfcGeographicElement",
{"PredefinedType": "USERDEFINED", "ObjectType": "WaterGroundSurface"},
], # Update for IFC4.3
"WaterClosureSurface": [
"IfcGeographicElement",
{"PredefinedType": "USERDEFINED", "ObjectType": "WaterClosureSurface"},
], # Update for IFC4.3
"TrafficArea": ["IfcCivilElement"], # Update for IFC4.3
"AuxiliaryTrafficArea": ["IfcCivilElement"], # Update for IFC4.3
"TransportationMarking": ["IfcCivilElement"], # Update for IFC4.3
"TransportationHole": ["IfcCivilElement"], # Update for IFC4.3
}
class Cityjson2ifc:
def __init__(self):
self.city_model = None
self.IFC_model = None
self.properties = {}
self.geometry = GeometryIO()
self.configuration()
def configuration(
self,
file_destination="output.ifc",
name_attribute=None,
split=True,
lod=None,
name_project=None,
name_site=None,
name_person_family=None,
name_person_given=None,
):
self.properties["file_destination"], self.properties["file_extension"] = os.path.splitext(file_destination)
self.properties["name_attribute"] = name_attribute
self.properties["split"] = split
self.properties["lod"] = lod
self.properties["name_project"] = name_project
self.properties["name_site"] = name_site
self.properties["name_person_family"] = name_person_family
self.properties["name_person_given"] = name_person_given
def convert(self, city_model):
self.city_model = city_model
self.create_new_file()
self.create_metadata()
self.geometry.set_scale(self.properties["local_scale"],self.properties["verticalT"])
# self.geometry.build_vertices(self.IFC_model,
# coords=city_model.j["vertices"],
# scale=self.properties["local_scale"])
# self.build_vertices()
self.create_IFC_classes()
if self.properties["lod"]:
self.write_file()
elif self.properties["split"]:
self.write_files()
else:
self.write_file()
def create_metadata(self):
# Georeferencing
self.properties["local_translation"] = {}
self.properties["local_scale"] = None
self.properties["local_scale"] = self.city_model.transform["scale"]
self.properties["verticalT"] = self.city_model.transform["translate"][2]
local_translation = self.city_model.transform["translate"]
self.properties["local_translation"] = {
"Eastings": local_translation[0],
"Northings": local_translation[1],
"OrthogonalHeight": 0,
}
epsg = self.city_model.get_epsg()
if epsg:
# Meter is assumed as unit for now
unit = self.IFC_model.createIfcSIUnit(None, "LENGTHUNIT", None, "METRE")
self.properties["local_translation"]["TargetCRS"] = self.IFC_model.create_entity(
"IfcProjectedCrs", Name=f"EPSG:{epsg}"
)
self.properties["local_translation"]["SourceCRS"] = self.IFC_representation_context
self.IFC_model.create_entity("IfcMapConversion", **self.properties["local_translation"])
def create_new_file(self):
self.IFC_model = self.create_file()
self.IFC_project = ifcopenshell.api.run(
"root.create_entity",
self.IFC_model,
**{"ifc_class": "IfcProject", "name": self.properties.get("name_project", "My Project")},
)
ifcopenshell.api.run("unit.assign_unit", self.IFC_model, length={"is_metric": True, "raw": "METERS"})
self.properties["owner_history"] = self.create_owner_history()
self.IFC_representation_context = ifcopenshell.api.run(
"context.add_context", self.IFC_model, **{"context_type": "Model"}
)
if not self.city_model.has_metadata() or "presentLoDs" not in self.city_model.j["metadata"]:
self.city_model.update_metadata()
# create IFC representation subcontexts from lods
self.create_representation_sub_contexts()
self.IFC_site = ifcopenshell.api.run(
"root.create_entity",
self.IFC_model,
**{"ifc_class": "IfcSite", "name": self.properties.get("name_site", "My Site")},
)
self.IFC_model.create_entity(
"IfcRelAggregates",
**{
"GlobalId": ifcopenshell.guid.new(),
"RelatedObjects": [self.IFC_site],
"RelatingObject": self.IFC_project,
},
)
def create_representation_sub_contexts(self):
self.IFC_representation_sub_contexts = {}
# for lod in self.city_model.j["metadata"]["presentLoDs"]:
# self.IFC_representation_sub_contexts[str(lod)] = self.create_representation_sub_context(lod)
def create_representation_sub_context(self, lod):
# TODO in ifcopenshell.api.context.add_context add support for UserDefinedTargetView
# self.IFC_representation_sub_contexts[str(lod)] = ifcopenshell.api.run("context.add_context", self.IFC_model,
# **{"context": "Model",
# "subcontext": "Body",
# "target_view": "USERDEFINED",
# "UserDefinedTargetView":str(lod)})
return self.IFC_model.create_entity(
"IfcGeometricRepresentationSubContext",
**{
"ContextType": "Model",
"ContextIdentifier": "Body",
"TargetView": "USERDEFINED",
"ParentContext": self.IFC_representation_context,
"UserDefinedTargetView": "LOD" + lod,
},
)
def create_owner_history(self):
actor = self.IFC_model.createIfcActorRole("ENGINEER", None, None)
person = self.IFC_model.createIfcPerson(
self.properties.get("name_person_family", "FamilyName"),
self.properties.get("name_person_given", "GivenName"),
None,
None,
None,
None,
(actor,),
)
organization = self.IFC_model.createIfcOrganization(
None,
"IfcOpenShell",
"IfcOpenShell, an open source (LGPL) software library that helps users and software developers to work with the IFC file format.",
)
p_o = self.IFC_model.createIfcPersonAndOrganization(person, organization)
application = self.IFC_model.createIfcApplication(organization, "0.1.0", "ifccityjson", "ifccityjson")
timestamp = int(datetime.now().timestamp())
ownerHistory = self.IFC_model.createIfcOwnerHistory(
p_o, application, "READWRITE", None, None, None, None, timestamp
)
return ownerHistory
def write_file(self):
file = self.properties["file_destination"] + self.properties["file_extension"]
self.IFC_model.write(file)
def write_files(self):
for lod, IFC_representation_sub_context in self.IFC_representation_sub_contexts.items():
sub_context_id = IFC_representation_sub_context.id()
# TODO this method makes a copy of the IFC_model by writing it and importing it,
# TODO but maybe there is a better method.
file = self.properties["file_destination"] + lod + self.properties["file_extension"]
self.IFC_model.write(file)
IFC_copied_model = ifcopenshell.open(file)
IFC_copied_model_sub_contexts = IFC_copied_model.by_type("IfcGeometricRepresentationSubContext")
for sub_context in IFC_copied_model_sub_contexts:
if sub_context.id() == sub_context_id:
continue
representations_in_context = sub_context.RepresentationsInContext
for element in representations_in_context:
IFC_copied_model.remove(element)
# slow:
# ifcopenshell.api.run("geometry.remove_representation", IFC_copied_model, representation=element)
ifcopenshell.api.run("context.remove_context", IFC_copied_model, context=sub_context)
IFC_copied_model.write(file)
del IFC_copied_model
def create_IFC_classes(self):
parents_children_relations = {"IfcSite": {"Parent": self.IFC_site, "Children": []}}
geometries = {}
existing_placements = self.IFC_model.by_type("IfcAxis2Placement3D")
target_placement = None
for placement in existing_placements:
if placement.Location.Coordinates == [0.0, 0.0, 0.0]:
target_placement = placement
break
if not target_placement:
placement_origin = self.IFC_model.create_entity("IfcCartesianPoint", [0.0, 0.0, 0.0]) # Example origin
target_placement = self.IFC_model.create_entity("IfcAxis2Placement3D", Location=placement_origin)
local_placement = self.IFC_model.create_entity("IfcLocalPlacement", PlacementRelTo=None, RelativePlacement=target_placement)
for obj_id, obj in self.city_model.get_cityobjects().items():
# CityJSON type to class
try:
mapping = JSON_TO_IFC[obj.type]
except KeyError:
# skip CityObject types that are not supported, eg. from extensions
continue
IFC_class = mapping[0]
data = {}
# Add attributes if it is specified in mapping
# Example: BuildingPart to IfcBuilding with CompositionType: Partial
if len(mapping) > 1:
data.update(mapping[1])
# attributes
IFC_name = obj_id
if "name_attribute" in self.properties and self.properties["name_attribute"] in obj.attributes:
IFC_name = obj.attributes[self.properties["name_attribute"]]
if len(obj.geometry) == 0:
print(f"Warning: Object {obj_id} has no geometry.")
IFC_semantic_surface_children = []
IFC_shape_representations = []
for geometry in obj.geometry:
lod = geometry.lod
if self.properties["lod"] is not None and lod != self.properties["lod"]:
continue
if lod not in self.IFC_representation_sub_contexts:
self.IFC_representation_sub_contexts[lod] = self.create_representation_sub_context(lod)
IFC_geometry, shape_representation_type = None, None
if geometry and geometry.surfaces:
IFC_semantic_surface_children.extend(self.create_IFC_semantic_surface_children(geometry, lod, local_placement))
elif geometry:
IFC_geometry, shape_representation_type = self.geometry.create_IFC_geometry(
self.IFC_model, geometry
)
if IFC_geometry:
IFC_shape_representation = self.create_IFC_shape_representation(
IFC_geometry, shape_representation_type, lod
)
IFC_shape_representations.append(IFC_shape_representation)
if len(IFC_shape_representations) > 0:
IFC_child_class = "IfcBuildingElementProxy"
child_data = {"GlobalId": ifcopenshell.guid.new(), "Name": IFC_child_class}
child_data["Representation"] = self.IFC_model.create_entity("IfcProductDefinitionShape", Representations=IFC_shape_representations)
child_data["ObjectPlacement"] = local_placement
IFC_semantic_surface_children.append(self.IFC_model.create_entity(IFC_child_class, **child_data))
data["GlobalId"] = ifcopenshell.guid.new()
data["Name"] = IFC_name
IFC_object = self.IFC_model.create_entity(IFC_class, **data)
# Define aggregation
parents_children_relations["IfcSite"]["Children"].append(IFC_object)
for parent in obj.parents:
if parent not in parents_children_relations:
parents_children_relations[parent] = {"Parent": None, "Children": [], "ChildrenID": []}
parents_children_relations[parent]["Children"].append(IFC_object)
parents_children_relations[parent]["ChildrenID"].append(obj.id)
if obj_id not in parents_children_relations:
parents_children_relations[obj_id] = {"ParentID": parent}
if len(obj.children) > 0:
if obj_id not in parents_children_relations:
parents_children_relations[obj_id] = {"Parent": None, "Children": [], "ChildrenID": []}
for child in obj.children:
if child not in parents_children_relations:
parents_children_relations[child] = {"ParentID": None}
parents_children_relations[child]["ParentID"] = obj_id
parents_children_relations[obj_id]["Parent"] = IFC_object
if "ParentID" not in parents_children_relations[obj_id]:
self.create_property_set(obj.attributes, IFC_object)
else:
objParentId = parents_children_relations[obj_id]["ParentID"]
attributes = self.city_model.cityobjects[objParentId].attributes
self.create_property_set(attributes, IFC_object)
if IFC_semantic_surface_children:
self.IFC_model.create_entity(
"IfcRelContainedInSpatialStructure",
**{
"GlobalId": ifcopenshell.guid.new(),
"RelatedElements": IFC_semantic_surface_children,
"RelatingStructure": IFC_object,
},
)
for parent, parent_children in parents_children_relations.items():
if parent == 'IfcSite':
self.IFC_model.create_entity(
"IfcRelAggregates",
**{
"GlobalId": ifcopenshell.guid.new(),
"RelatedObjects": parent_children["Children"],
"RelatingObject": parent_children["Parent"],
},
)
def create_IFC_semantic_surface_children(self, geometry, lod, local_placement):
IFC_semantic_surface_children = []
for surface_id in geometry.surfaces:
IFC_child_class = JSON_TO_IFC[geometry.surfaces[surface_id]["type"]][0]
child_data = {"GlobalId": ifcopenshell.guid.new(), "Name": IFC_child_class}
# CREATE ENTITY
surface_geometry = self.geometry.create_IFC_surface(self.IFC_model, geometry, surface_id)
if surface_geometry:
IFC_shape_representation = self.create_IFC_shape_representation(surface_geometry, "SurfaceModel", lod)
child_data["Representation"] = self.IFC_model.create_entity(
"IfcProductDefinitionShape", Representations=[IFC_shape_representation]
)
child_data["ObjectPlacement"] = local_placement
IFC_semantic_surface_children.append(self.IFC_model.create_entity(IFC_child_class, **child_data))
return IFC_semantic_surface_children
def create_IFC_shape_representation(self, IFC_geometry, shape_representation_type, lod):
if not isinstance(IFC_geometry, list):
IFC_geometry = [IFC_geometry]
shape_representation = self.IFC_model.create_entity(
"IfcShapeRepresentation",
self.IFC_representation_sub_contexts[lod],
"Body",
shape_representation_type,
IFC_geometry,
)
return shape_representation
def create_property_set(self, CJ_attributes, IFC_entity):
if len(CJ_attributes) == 0:
return
pset = ifcopenshell.api.run("pset.add_pset", self.IFC_model, product=IFC_entity, name="3DBAG_attributes")
ifcopenshell.api.run("pset.edit_pset", self.IFC_model, pset=pset, properties=CJ_attributes)
psetPand = ifcopenshell.api.run("pset.add_pset", self.IFC_model, product=IFC_entity, name="Pset_BuildingCommon")
if "identificatie" in CJ_attributes:
value = CJ_attributes["identificatie"]
value = value[len("NL.IMBAG.Pand."):]
properties_to_add = {"BuildingID": value}
if "oorspronkelijkbouwjaar" in CJ_attributes:
properties_to_add["NumberOfStories"] = CJ_attributes["b3_bouwlagen"]
if "b3_bouwlagen" in CJ_attributes:
properties_to_add["YearOfConstruction"] = CJ_attributes["oorspronkelijkbouwjaar"]
ifcopenshell.api.run(
"pset.edit_pset",
self.IFC_model,
pset=psetPand,
properties=properties_to_add
)
def create_file(self) -> ifcopenshell.file:
version: str = "IFC4"
settings = {"version": version}
file = ifcopenshell.file(schema=settings["version"])
file.wrapped_data.header.file_name.name = "\\"+ self.properties["file_destination"]+ ".ifc"
file.wrapped_data.header.file_name.time_stamp = (
datetime.utcnow().replace(tzinfo=timezone.utc).astimezone().replace(microsecond=0).isoformat()
)
file.wrapped_data.header.file_name.preprocessor_version = "IfcOpenShell {}".format(ifcopenshell.version)
file.wrapped_data.header.file_name.originating_system = "IfcOpenShell {}".format(ifcopenshell.version)
file.wrapped_data.header.file_name.authorization = "3dgeoinfo/3DGI"
file.wrapped_data.header.file_description.description = ("ViewDefinition[DesignTransferView]",)
file.wrapped_data.header.file_name.organization = "H"
file.wrapped_data.header.file_name.author = "A"
return file