/
operator.py
906 lines (757 loc) · 36.9 KB
/
operator.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
# BlenderBIM Add-on - OpenBIM Blender Add-on
# Copyright (C) 2020, 2021 Dion Moult <dion@thinkmoult.com>
#
# This file is part of BlenderBIM Add-on.
#
# BlenderBIM Add-on 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 3 of the License, or
# (at your option) any later version.
#
# BlenderBIM Add-on 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 BlenderBIM Add-on. If not, see <http://www.gnu.org/licenses/>.
import os
import bpy
import blenderbim.bim.helper
import blenderbim.bim.handler
import blenderbim.tool as tool
import blenderbim.core.style as core
import ifcopenshell.util.representation
from pathlib import Path
from mathutils import Vector
class UpdateStyleColours(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.update_style_colours"
bl_label = "Save Current Shading Style"
bl_description = (
"Update IfcSurfaceStyleShading based on current blender material shading graph.\n\n"
+ "ALT+CLICK to see saved values details"
)
bl_options = {"REGISTER", "UNDO"}
verbose: bpy.props.BoolProperty(default=False, options={"SKIP_SAVE"})
def invoke(self, context, event):
# verbose print to console on alt+click
# make sure to use SKIP_SAVE on property, otherwise it might get stuck
if event.type == "LEFTMOUSE" and event.alt:
self.verbose = True
return self.execute(context)
def _execute(self, context):
mat = context.active_object.active_material
core.update_style_colours(tool.Ifc, tool.Style, obj=mat, verbose=self.verbose)
if self.verbose:
self.report({"INFO"}, "Check the system console to see saved style properties")
class UpdateStyleTextures(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.update_style_textures"
bl_label = "Update Style Textures"
bl_description = "Update IfcSurfaceStyleWithTextures based on current blender material shading graph"
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
representation = ifcopenshell.util.representation.get_representation(
tool.Ifc.get_entity(context.active_object), "Model", "Body", "MODEL_VIEW"
)
if representation:
core.update_style_textures(
tool.Ifc, tool.Style, obj=context.active_object.active_material, representation=representation
)
class RemoveStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.remove_style"
bl_label = "Remove Style"
bl_options = {"REGISTER", "UNDO"}
style: bpy.props.IntProperty()
def _execute(self, context):
core.remove_style(tool.Ifc, tool.Material, tool.Style, style=tool.Ifc.get().by_id(self.style))
class AddStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.add_style"
bl_label = "Add Style"
bl_description = "Add IfcSurfaceStyle to the active material"
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
core.add_style(tool.Ifc, tool.Style, obj=context.active_object.active_material)
class UnlinkStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.unlink_style"
bl_label = "Unlink Style"
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
core.unlink_style(tool.Ifc, tool.Style, obj=context.active_object.active_material)
class EnableEditingStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.enable_editing_style"
bl_label = "Enable Editing Style"
bl_options = {"REGISTER", "UNDO"}
style: bpy.props.IntProperty(default=0)
def _execute(self, context):
props = bpy.context.scene.BIMStylesProperties
style = tool.Ifc.get().by_id(self.style)
props.is_editing_style = style.id()
props.is_editing_class = "IfcSurfaceStyle"
attributes = props.attributes
attributes.clear()
blenderbim.bim.helper.import_attributes2(style, attributes)
class DisableEditingStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.disable_editing_style"
bl_options = {"REGISTER", "UNDO"}
bl_label = "Disable Editing Style"
def _execute(self, context):
props = bpy.context.scene.BIMStylesProperties
style = tool.Ifc.get().by_id(props.is_editing_style)
material = tool.Ifc.get_object(style)
tool.Style.reload_material_from_ifc(material)
props.is_editing_style = 0
class EditStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.edit_style"
bl_label = "Edit Style"
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
props = bpy.context.scene.BIMStylesProperties
style = tool.Ifc.get().by_id(props.is_editing_style)
attributes = blenderbim.bim.helper.export_attributes(props.attributes)
ifcopenshell.api.run("style.edit_presentation_style", tool.Ifc.get(), style=style, attributes=attributes)
props.is_editing_style = 0
core.load_styles(tool.Style, style_type=props.style_type)
class UpdateCurrentStyle(bpy.types.Operator):
bl_idname = "bim.update_current_style"
bl_label = "Update Current Style"
bl_description = (
"Update style for all selected objects according to current style type\n(Shading/External).\n\n"
+ "SHIFT+CLICK to update ALL styles in the .ifc file to current style type"
)
bl_options = {"REGISTER", "UNDO"}
update_all: bpy.props.BoolProperty(name="Update All", default=False, options={"SKIP_SAVE"})
style_id: bpy.props.IntProperty(default=0, options={"SKIP_SAVE"})
@classmethod
def poll(cls, context):
if not context.selected_objects:
cls.poll_message_set("No objects selected")
return False
return True
def invoke(self, context, event):
# updating all styles on shift+click
# make sure to use SKIP_SAVE on property, otherwise it might get stuck
if event.type == "LEFTMOUSE" and event.shift:
self.update_all = True
return self.execute(context)
def execute(self, context):
style = tool.Ifc.get().by_id(self.style_id)
material = tool.Ifc.get_object(style)
current_style_type = material.BIMStyleProperties.active_style_type
if self.update_all:
context.scene.BIMStylesProperties.active_style_type = current_style_type
return {"FINISHED"}
for obj in context.selected_objects:
for mat in obj.data.materials:
if mat and mat.BIMMaterialProperties.ifc_style_id != 0:
mat.BIMStyleProperties.active_style_type = current_style_type
return {"FINISHED"}
class BrowseExternalStyle(bpy.types.Operator):
bl_idname = "bim.browse_external_style"
bl_label = "Browse External Style"
bl_options = {"REGISTER", "UNDO"}
filepath: bpy.props.StringProperty(
name="File Path", description="Filepath used to import from", maxlen=1024, default="", subtype="FILE_PATH"
)
filter_glob: bpy.props.StringProperty(
default="*.blend",
options={"HIDDEN"},
)
def get_data_block_types(self, context):
return [("materials", "materials", "materials")]
# NOTE: the code below can be used later when we'll be adding other data-blocks besides materials
l = [("0", "", "")]
SUPPORTED_DATA_BLOCKS = ("materials", "textures", "brushes")
if os.path.exists(self.filepath) and self.filepath.endswith(".blend"):
with bpy.data.libraries.load(self.filepath) as (data_from, data_to):
for data_block_type in dir(data_from):
if data_block_type not in SUPPORTED_DATA_BLOCKS:
continue
data = getattr(data_from, data_block_type)
if data:
item = (data_block_type,) * 3
l.append(item)
return l
def get_data_blocks(self, context):
l = [("", "", "")]
if self.data_block_type != "0" and os.path.exists(self.filepath) and self.filepath.endswith(".blend"):
with bpy.data.libraries.load(self.filepath) as (data_from, data_to):
objects = getattr(data_from, self.data_block_type)
for o in objects:
l.append((o, o, o))
return l
data_block_type: bpy.props.EnumProperty(
name="Data Block Type",
description="List of data blocks in the .blend file",
items=get_data_block_types,
)
data_block: bpy.props.EnumProperty(
name="List of objects in the .blend file",
description="List of objects in the .blend file",
items=get_data_blocks,
)
use_relative_path: bpy.props.BoolProperty(
name="Use Relative Path", description="Save path relative to IFC file", default=True
)
directory: bpy.props.StringProperty(
name="Directory",
description="Start file browsing directory",
default="",
)
active_surface_style_id: bpy.props.IntProperty(
description="Currently selected IfcSurfaceStyle ID to automatically select it in the file browser",
options={"HIDDEN", "SKIP_SAVE"},
)
def invoke(self, context, event):
external_style = None
if self.active_surface_style_id:
style = tool.Ifc.get().by_id(self.active_surface_style_id)
external_style = tool.Style.get_style_elements(style).get("IfcExternallyDefinedSurfaceStyle", None)
# automatically select previously selected external style in file browser
# if it exists in the file
if external_style and self.filepath == "":
style_path = Path(tool.Ifc.resolve_uri(external_style.Location))
self.directory = str(style_path.parent)
self.filepath = str(style_path)
data_block_type, data_block = external_style.Identification.split("/")
self.data_block_type = data_block_type
data_blocks = [d[0] for d in self.get_data_blocks(context)]
if data_block in data_blocks:
self.data_block = data_block
context.window_manager.fileselect_add(self)
return {"RUNNING_MODAL"}
def draw(self, context):
layout = self.layout
layout.label(text="Data Block Type")
layout.prop(self, "data_block_type", text="", icon="GROUP")
layout.label(text="Data Block")
layout.prop(self, "data_block", text="")
if Path(tool.Ifc.get_path()).is_file():
layout.prop(self, "use_relative_path")
else:
self.use_relative_path = False
layout.label(text="Save the .ifc file first ")
layout.label(text="to use relative paths.")
def execute(self, context):
if self.data_block_type == "0":
self.report({"ERROR"}, "Select a data block type in the side panel of the file browser")
return {"CANCELLED"}
if self.data_block == "":
self.report({"ERROR"}, "Select a data block in the side panel of the file browser")
return {"CANCELLED"}
if not os.path.exists(self.filepath):
self.report({"ERROR"}, f"File not found:\n'{self.filepath}'")
return {"CANCELLED"}
db = tool.Blender.append_data_block(self.filepath, self.data_block_type, self.data_block)
if not db["data_block"]:
self.report({"ERROR"}, db["msg"])
return {"CANCELLED"}
bpy.data.materials.remove(db["data_block"])
if self.use_relative_path:
filepath = os.path.relpath(self.filepath, Path(tool.Ifc.get_path()).parent)
else:
filepath = self.filepath
filepath = Path(filepath).as_posix()
attributes = context.scene.BIMStylesProperties.external_style_attributes
attributes["Location"].string_value = filepath
attributes["Identification"].string_value = f"{self.data_block_type}/{self.data_block}"
attributes["Name"].string_value = self.data_block
return {"FINISHED"}
class ActivateExternalStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.activate_external_style"
bl_label = "Activate External Style"
bl_options = {"REGISTER", "UNDO", "INTERNAL"}
material_name: bpy.props.StringProperty(name="Material Name", default="")
def _execute(self, context):
if not self.material_name:
material = context.active_object.active_material
else:
material = bpy.data.materials[self.material_name]
external_style = tool.Style.get_style_elements(material)["IfcExternallyDefinedSurfaceStyle"]
data_block_type, data_block = external_style.Identification.split("/")
style_path = Path(tool.Ifc.resolve_uri(external_style.Location))
if style_path.suffix != ".blend":
self.report(
{"ERROR"},
f"Error loading external style for \"{material.name}\" - only Blender external styles are supported",
)
return {"CANCELLED"}
if not style_path.exists():
self.report(
{"ERROR"}, f"Error loading external style for \"{material.name}\" - cannot find file: '{style_path}'"
)
return {"CANCELLED"}
db = tool.Blender.append_data_block(str(style_path), data_block_type, data_block)
if not db["data_block"]:
self.report({"ERROR"}, f"Error loading external style for \"{material.name}\" - {db['msg']}")
return {"CANCELLED"}
self.copy_material_attributes(db["data_block"], material)
if material.use_nodes:
tool.Blender.copy_node_graph(material, db["data_block"])
bpy.data.materials.remove(db["data_block"])
def copy_material_attributes(self, source, target):
ID_properties = bpy.types.ID.bl_rna.properties
material_props = bpy.types.Material.bl_rna.properties
allowed_prop_groups = ("grease_pencil", "lineart", "cycles")
def set_prop(prop_name):
# temporary workaround for Blender bug https://projects.blender.org/blender/blender/issues/116325
if prop_name == "paint_active_slot":
return
setattr(target, prop_name, getattr(source, prop_name))
def set_prop_group(prop_group):
source_prop_group = getattr(source, prop_group)
target_prop_group = getattr(target, prop_group)
if target_prop_group is None or target_prop_group is None:
return
for prop_name in source_prop_group.bl_rna.properties.keys():
prop = source_prop_group.bl_rna.properties[prop_name]
if prop.type in ("POINTER", "COLLECTION"):
continue
if prop.is_readonly:
continue
source_value = getattr(source_prop_group, prop_name)
setattr(target_prop_group, prop_name, source_value)
for prop_name in material_props.keys():
if prop_name in ID_properties:
continue
prop = material_props[prop_name]
if prop.type == "COLLECTION":
continue
if prop.type == "POINTER":
if prop_name in allowed_prop_groups:
set_prop_group(prop_name)
continue
if prop.is_readonly:
continue
set_prop(prop_name)
class DisableEditingStyles(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.disable_editing_styles"
bl_options = {"REGISTER", "UNDO"}
bl_label = "Disable Editing Styles"
def _execute(self, context):
core.disable_editing_styles(tool.Style)
class LoadStyles(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.load_styles"
bl_label = "Load Styles"
bl_options = {"REGISTER", "UNDO"}
style_type: bpy.props.StringProperty()
def _execute(self, context):
core.load_styles(tool.Style, style_type=self.style_type)
class SelectByStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.select_by_style"
bl_label = "Select By Style"
bl_options = {"REGISTER", "UNDO"}
style: bpy.props.IntProperty()
def _execute(self, context):
core.select_by_style(tool.Style, tool.Spatial, style=tool.Ifc.get().by_id(self.style))
class ChooseTextureMapPath(bpy.types.Operator):
bl_idname = "bim.choose_texture_map_path"
bl_label = "Choose Texture Map Path"
bl_options = {"REGISTER", "UNDO", "INTERNAL"}
texture_map_index: bpy.props.IntProperty(default=-1, options={"SKIP_SAVE"})
use_relative_path: bpy.props.BoolProperty(
name="Use Relative Path", description="Save path relative to IFC file", default=True
)
filepath: bpy.props.StringProperty(
name="File Path", description="Filepath used to import from", maxlen=1024, default="", subtype="FILE_PATH"
)
filter_image: bpy.props.BoolProperty(default=True, options={"HIDDEN", "SKIP_SAVE"})
filter_folder: bpy.props.BoolProperty(default=True, options={"HIDDEN", "SKIP_SAVE"})
def draw(self, context):
layout = self.layout
if Path(tool.Ifc.get_path()).is_file():
layout.prop(self, "use_relative_path")
else:
self.use_relative_path = False
layout.label(text="Save the .ifc file first ")
layout.label(text="to use relative paths.")
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {"RUNNING_MODAL"}
def execute(self, context):
if self.texture_map_index < 0:
self.report({"ERROR"}, "Provide a texture map index")
return {"CANCELLED"}
abs_path = Path(self.filepath)
if self.use_relative_path:
image_filepath = abs_path.relative_to(Path(tool.Ifc.get_path()).parent)
else:
image_filepath = abs_path
texture = context.scene.BIMStylesProperties.textures[self.texture_map_index]
texture.path = image_filepath.as_posix()
return {"FINISHED"}
class RemoveTextureMap(bpy.types.Operator):
bl_idname = "bim.remove_texture_map"
bl_label = "Remove Texture Map"
bl_options = {"REGISTER", "UNDO", "INTERNAL"}
texture_map_index: bpy.props.IntProperty(default=-1, options={"SKIP_SAVE"})
def execute(self, context):
if self.texture_map_index < 0:
self.report({"ERROR"}, "Provide a texture map index")
return {"CANCELLED"}
props = context.scene.BIMStylesProperties
props.textures.remove(self.texture_map_index)
# just to trigger shader graph update
props.surface_colour = props.surface_colour
return {"FINISHED"}
class EnableAddingPresentationStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.enable_adding_presentation_style"
bl_label = "Enable Add Presentation Style"
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
props = bpy.context.scene.BIMStylesProperties
props.is_adding = True
class DisableAddingPresentationStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.disable_adding_presentation_style"
bl_label = "Disable Add Presentation Style"
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
props = bpy.context.scene.BIMStylesProperties
props.is_adding = False
class AddPresentationStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.add_presentation_style"
bl_label = "Add Presentation Style"
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
props = bpy.context.scene.BIMStylesProperties
if props.style_type == "IfcSurfaceStyle":
style = ifcopenshell.api.run("style.add_style", tool.Ifc.get(), name=props.style_name)
# setup surface style element
surface_style = None
if props.surface_style_class in ("IfcSurfaceStyleShading", "IfcSurfaceStyleRendering"):
attributes = {
"SurfaceColour": {
"Name": None,
"Red": props.surface_colour[0],
"Green": props.surface_colour[1],
"Blue": props.surface_colour[2],
}
}
if props.surface_style_class == "IfcSurfaceStyleRendering":
attributes["ReflectanceMethod"] = "NOTDEFINED"
else:
# NOTE: for all other styles we produce just empty styles.
# In the future we might need to expose to adding presentation style UI
# LightingStyle colors and TextureStyle textures UI
# as they are required for those surface styles to keep IFC valid
attributes = {}
surface_style = ifcopenshell.api.run(
"style.add_surface_style",
tool.Ifc.get(),
style=style,
ifc_class=props.surface_style_class,
attributes=attributes,
)
# setup blender material
material = bpy.data.materials.new(style.Name)
tool.Ifc.link(style, material)
material.use_fake_user = True
if surface_style:
if surface_style.is_a("IfcSurfaceStyleRendering"):
tool.Loader.create_surface_style_rendering(material, surface_style)
elif surface_style.is_a("IfcSurfaceStyleShading"):
tool.Loader.create_surface_style_shading(material, surface_style)
else:
self.report({"INFO"}, f"Adding style of type {props.style_type} is not yet supported.")
props.is_adding = False
core.load_styles(tool.Style, style_type=props.style_type)
class EnableEditingSurfaceStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.enable_editing_surface_style"
bl_label = "Enable Editing Surface Style"
bl_options = {"REGISTER", "UNDO"}
style: bpy.props.IntProperty(default=0)
ifc_class: bpy.props.StringProperty(default="")
def _execute(self, context):
props = bpy.context.scene.BIMStylesProperties
style = tool.Ifc.get().by_id(self.style)
props.is_editing_style = self.style
props.is_editing_class = self.ifc_class
tool.Style.set_surface_style_props()
surface_style = tool.Style.get_style_elements(style).get(self.ifc_class, None)
attributes = tool.Style.get_style_ui_props_attributes(self.ifc_class)
# lighting style require special handling since Attribute doesn't support colors
callback = None
if self.ifc_class == "IfcSurfaceStyleLighting":
def callback(attribute_name, _, data):
color = attributes.add()
color.name = attribute_name
color_value = data[attribute_name]
if color_value is None:
return
color.color_name = color_value.Name or ""
color.color_value = (color_value.Red, color_value.Green, color_value.Blue)
if attributes is not None:
attributes.clear()
blenderbim.bim.helper.import_attributes2(surface_style or self.ifc_class, attributes, callback)
class EditSurfaceStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.edit_surface_style"
bl_label = "Edit Surface Style"
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
self.props = bpy.context.scene.BIMStylesProperties
self.style = tool.Ifc.get().by_id(self.props.is_editing_style)
style_elements = tool.Style.get_style_elements(self.style)
self.surface_style = style_elements.get(self.props.is_editing_class, None)
self.shading_style = style_elements.get("IfcSurfaceStyleShading", None)
self.rendering_style = style_elements.get("IfcSurfaceStyleRendering", None)
self.texture_style = style_elements.get("IfcSurfaceStyleWithTextures", None)
if self.surface_style:
self.edit_existing_style()
else:
self.add_new_style()
self.props.is_editing_style = 0
core.load_styles(tool.Style, style_type=self.props.style_type)
def edit_existing_style(self):
material = tool.Ifc.get_object(self.style)
if self.surface_style.is_a() == "IfcSurfaceStyleShading":
ifcopenshell.api.run(
"style.edit_surface_style",
tool.Ifc.get(),
style=self.surface_style,
attributes={
"SurfaceColour": self.color_to_dict(self.props.surface_colour),
"Transparency": self.props.transparency or None,
},
)
tool.Loader.create_surface_style_shading(material, self.surface_style)
elif self.surface_style.is_a() == "IfcSurfaceStyleRendering":
ifcopenshell.api.run(
"style.edit_surface_style",
tool.Ifc.get(),
style=self.surface_style,
attributes=self.get_rendering_attributes(),
)
tool.Loader.create_surface_style_rendering(material, self.surface_style)
elif self.props.is_editing_class == "IfcSurfaceStyleWithTextures":
# TODO: fix same issues as with creating new IfcSurfaceStyleWithTextures
material = tool.Ifc.get_object(self.style)
shading_style = self.rendering_style or self.shading_style
if self.rendering_style is None:
self.report(
{"ERROR"},
"Editing texture styles without defining shading/rendering style is not yet supported. "
"Define shading/render style first",
)
return {"CANCELLED"}
textures = tool.Ifc.run("style.add_surface_textures", textures=self.get_texture_attributes(), uv_maps=[])
texture_style = tool.Ifc.run(
"style.add_surface_style",
style=self.style,
ifc_class="IfcSurfaceStyleWithTextures",
attributes={"Textures": textures},
)
tool.Loader.create_surface_style_with_textures(material, shading_style, texture_style)
else:
attributes = tool.Style.get_style_ui_props_attributes(self.surface_style.is_a())
ifcopenshell.api.run(
"style.edit_surface_style",
tool.Ifc.get(),
style=self.surface_style,
attributes=blenderbim.bim.helper.export_attributes(attributes),
)
def add_new_style(self):
material = tool.Ifc.get_object(self.style)
if self.props.is_editing_class == "IfcSurfaceStyleShading":
surface_style = ifcopenshell.api.run(
"style.add_surface_style",
tool.Ifc.get(),
style=self.style,
ifc_class="IfcSurfaceStyleShading",
attributes=self.get_shading_attributes(),
)
tool.Loader.create_surface_style_shading(material, surface_style)
elif self.props.is_editing_class == "IfcSurfaceStyleRendering":
surface_style = ifcopenshell.api.run(
"style.add_surface_style",
tool.Ifc.get(),
style=self.style,
ifc_class="IfcSurfaceStyleRendering",
attributes=self.get_rendering_attributes(),
)
tool.Loader.create_surface_style_rendering(material, surface_style)
elif self.props.is_editing_class == "IfcSurfaceStyleWithTextures":
# TODO: provide `uv_maps` - need to rework .get_uv_maps not to depend on a single representation
material = tool.Ifc.get_object(self.style)
shading_style = self.rendering_style or self.shading_style
# TODO: support creating texture styles without defining rendering style first
if self.rendering_style is None:
self.report(
{"ERROR"},
"Creating texture styles without defining shading/rendering style is not yet supported. "
"Define shading/render style first",
)
return {"CANCELLED"}
textures = tool.Ifc.run("style.add_surface_textures", textures=self.get_texture_attributes(), uv_maps=[])
if textures:
texture_style = tool.Ifc.run(
"style.add_surface_style",
style=self.style,
ifc_class="IfcSurfaceStyleWithTextures",
attributes={"Textures": textures},
)
tool.Loader.create_surface_style_with_textures(material, shading_style, texture_style)
else:
attributes = tool.Style.get_style_ui_props_attributes(self.props.is_editing_class)
surface_style = ifcopenshell.api.run(
"style.add_surface_style",
tool.Ifc.get(),
style=self.style,
ifc_class=self.props.is_editing_class,
attributes=blenderbim.bim.helper.export_attributes(attributes),
)
def get_shading_attributes(self):
return {
"SurfaceColour": self.color_to_dict(self.props.surface_colour),
"Transparency": self.props.transparency or None,
}
def get_rendering_attributes(self):
if self.props.is_diffuse_colour_null:
diffuse_colour = None
elif self.props.diffuse_colour_class == "IfcColourRgb":
diffuse_colour = self.color_to_dict(self.props.diffuse_colour)
elif self.props.diffuse_colour_class == "IfcNormalisedRatioMeasure":
diffuse_colour = self.props.diffuse_colour_ratio
if self.props.is_specular_colour_null:
specular_colour = None
elif self.props.specular_colour_class == "IfcColourRgb":
specular_colour = self.color_to_dict(self.props.specular_colour)
elif self.props.specular_colour_class == "IfcNormalisedRatioMeasure":
specular_colour = self.props.specular_colour_ratio
if self.props.is_specular_highlight_null:
specular_highlight = None
else:
specular_highlight = {"IfcSpecularRoughness": self.props.specular_highlight}
return {
"SurfaceColour": self.color_to_dict(self.props.surface_colour),
"Transparency": self.props.transparency or None,
"ReflectanceMethod": self.props.reflectance_method,
"DiffuseColour": diffuse_colour,
"SpecularColour": specular_colour,
"SpecularHighlight": specular_highlight,
}
# TODO: support RepeatS/RepeatT params in UI:
# add it to prop.Texture and Style.get_texture_style_data_from_props
def get_texture_attributes(self):
textures = []
for texture in self.props.textures:
texture_data = {
"URLReference": texture.path,
"Mode": texture.mode,
"RepeatS": True,
"RepeatT": True,
"uv_mode": self.props.uv_mode,
}
textures.append(texture_data)
return textures
def color_to_dict(self, x):
return {"Red": x[0], "Green": x[1], "Blue": x[2]}
class AddSurfaceTexture(bpy.types.Operator):
bl_idname = "bim.add_surface_texture"
bl_label = "Add Surface Texture"
bl_options = {"REGISTER", "UNDO"}
@classmethod
def poll(cls, context):
if len(context.scene.BIMStylesProperties.textures) >= 8:
cls.poll_message_set("Only 8 texture maps available")
return False
return True
def execute(self, context):
props = context.scene.BIMStylesProperties
props.textures.add()
return {"FINISHED"}
class SaveUVToStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.save_uv_to_style"
bl_label = "Save UV To Style"
bl_options = {"REGISTER", "UNDO"}
def _execute(self, context):
context = bpy.context
ifc_file = tool.Ifc.get()
material = context.active_object.active_material
obj = context.active_object
# find active style item
style_id = material.BIMMaterialProperties.ifc_style_id
style = ifc_file.by_id(style_id)
def get_active_representation_items():
representation = tool.Geometry.get_active_representation(obj)
representation = ifcopenshell.util.representation.resolve_representation(representation)
items = []
for item in representation.Items:
if item.is_a("IfcMappedItem"):
items.extend(item.MappingSource.MappedRepresentation.Items)
items.append(item)
return items
all_styled_items = set(tool.Style.get_styled_items(style))
active_representation_items = set(get_active_representation_items())
if not active_representation_items.issubset(all_styled_items):
self.report(
{"ERROR"},
"Not all items of the current representation are styled by the active style, not yet supported",
)
return {"CANCELLED"}
if any(not i.is_a("IfcPolygonalFaceSet") for i in active_representation_items):
self.report({"ERROR"}, "One of the items is not IfcPolygonalFaceSet, not yet supported.")
return {"CANCELLED"}
for faceset in active_representation_items:
if any(len(f.CoordIndex) != 3 for f in faceset.Faces):
self.report({"ERROR"}, "One of the facesets is not triangulated, not yet supported.")
return {"CANCELLED"}
if len(active_representation_items) != 1:
self.report({"ERROR"}, "Only 1 faceset item is supported.")
return {"CANCELLED"}
texture_style = tool.Style.get_texture_style(material)
if not texture_style:
self.report({"ERROR"}, "No texture style found, not yet supported.")
return {"CANCELLED"}
# unmap preivously used IfcIndexedTextureMap
# TODO: remove orphaned data?
textures = set(texture_style.Textures)
coords = set()
for texture in textures:
coords.update(texture.IsMappedBy or [])
for coord in coords:
if coord.is_a("IfcIndexedTextureMap") and coord.MappedTo in active_representation_items:
coord.Maps = list(set(coord.Maps) - textures)
mesh = obj.data
uv_indices = []
uv_verts = [uv.vector for uv in mesh.uv_layers.active.uv]
si_conversion = ifcopenshell.util.unit.calculate_unit_scale(ifc_file)
for faceset in active_representation_items:
# remap the faceset CoordList index to the vertices in blender mesh
coordinates_remap = []
remap_failed = False
ifc_coordinates = faceset.Coordinates.CoordList
for co in ifc_coordinates:
co = Vector(co) * si_conversion
index = next((v.index for v in mesh.vertices if (v.co - co).length_squared < 1e-5), None)
coordinates_remap.append(index)
if index is None:
remap_failed = True
# ifc indices start with 1
remap_verts_to_blender = lambda ifc_verts: [coordinates_remap[i - 1] for i in ifc_verts]
if remap_failed or len(ifc_coordinates) != len(mesh.vertices):
self.report({"ERROR"}, "Mesh vertices doesn't match IFC faceset vertices.")
return {"CANCELLED"}
# safe check as I'm not sure indices in Blender and IFC match
faces_remap = [remap_verts_to_blender(triangle_face.CoordIndex) for triangle_face in faceset.Faces]
for ifc_face_remapped in faces_remap:
for blender_face in mesh.polygons:
blender_face_verts = blender_face.vertices[:]
# assume that blender verts order can be different
if set(blender_face_verts) == set(ifc_face_remapped):
blender_face_loops = blender_face.loop_indices[:]
face_uv_indices = [
blender_face_loops[blender_face_verts.index(i)] + 1 for i in ifc_face_remapped
]
uv_indices.append(face_uv_indices)
break
else:
self.report({"ERROR"}, "Couldn't find matching blender face for ifc face.")
return {"CANCELLED"}
texture_coord = ifc_file.create_entity("IfcIndexedTriangleTextureMap")
texture_coord.Maps = list(textures)
texture_coord.MappedTo = faceset
texture_coord.TexCoordIndex = uv_indices
uv_verts_list = ifc_file.create_entity("IfcTextureVertexList")
uv_verts_list.TexCoordsList = uv_verts
texture_coord.TexCoords = uv_verts_list
self.report({"INFO"}, f"UV saved to the style {style.Name}")
return {"FINISHED"}