forked from zanoni-mbdyn/blendyn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblendyn.py
2764 lines (2389 loc) · 101 KB
/
blendyn.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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# --------------------------------------------------------------------------
# Blendyn -- file blendyn.py
# Copyright (C) 2015 -- 2021 Andrea Zanoni -- andrea.zanoni@polimi.it
# --------------------------------------------------------------------------
# ***** BEGIN GPL LICENSE BLOCK *****
#
# This file is part of Blendyn, add-on script for Blender.
#
# Blendyn 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.
#
# Blendyn 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 Blendyn. If not, see <http://www.gnu.org/licenses/>.
#
# ***** END GPL LICENCE BLOCK *****
# --------------------------------------------------------------------------
import os, atexit
import bpy
import bmesh
from bpy.props import *
from bpy.app.handlers import persistent
from bpy_extras.io_utils import ImportHelper
import logging
baseLogger = logging.getLogger()
baseLogger.setLevel(logging.DEBUG)
from mathutils import *
from math import *
import shutil
import numpy as np
import subprocess
import json
try:
from netCDF4 import Dataset
except ImportError as ierr:
print("BLENDYN::base.py: could not enable the netCDF module. NetCDF import "\
+ "will be disabled. The reported error was:")
print("{0}".format(ierr))
HAVE_PSUTIL = False
try:
import psutil
HAVE_PSUTIL = True
except ImportError as ierr:
print("BLENDYN::base.py: could not enable the MBDyn control module. "\
+ "Stopping MBDyn from the Blender UI will be disabled.")
print("{0}".format(ierr))
from . baselib import *
from . elements import *
from . components import *
from . eigenlib import *
from . rfmlib import *
from . logwatcher import *
from . utilslib import set_active_collection
HAVE_PLOT = True
try:
from .plotlib import *
except (ImportError, OSError, ModuleNotFoundError) as ierr:
print("BLENDYN::base.py: could not enable the plotting module. Plotting "\
+ "will be disabled. The reported error was:")
print("{0}".format(ierr))
HAVE_PLOT = False
## Nodes Dictionary: contains nodes informations
class BLENDYN_PG_nodes_dictionary(bpy.types.PropertyGroup):
mbclass: StringProperty(
name = "Class of MBDyn element",
description = ""
)
int_label: IntProperty(
name = "node integer label",
description = "Node integer label",
)
string_label: StringProperty(
name = "node string label",
description = "Node string label",
default = "none"
)
blender_object: StringProperty(
name = "blender object label",
description = "Blender object",
default = "none"
)
initial_pos: FloatVectorProperty(
name = "node initial position",
description = "Initial position",
size = 3,
precision = 6
)
initial_rot: FloatVectorProperty(
name = "node initial orientation",
description = "Node initial orientation (quaternion)",
size = 4,
precision = 6
)
parametrization: EnumProperty(
items = [("EULER123", "euler123", "euler123", '', 1),\
("EULER321", "euler321", "euler321", '', 2),\
("PHI", "phi", "phi", '', 3),\
("MATRIX", "mat", "mat", '', 4)],
name = "rotation parametrization",
default = "EULER123"
)
is_imported: BoolProperty(
name = "Is imported flag",
description = "Flag set to true at the end of the import process"
)
output: BoolProperty(
name = "node output state",
description = "False if node output is disabled",
default = False
)
# -----------------------------------------------------------
# end of BLENDYN_PG_nodes_dictionary class
bpy.utils.register_class(BLENDYN_PG_nodes_dictionary)
class BLENDYN_PG_reference_dictionary(bpy.types.PropertyGroup):
int_label: IntProperty(
name = "reference integer label",
description = "Reference integer label"
)
string_label: StringProperty(
name = "reference string label",
description = "Reference string label",
default = "none"
)
blender_object: StringProperty(
name = "blender object label",
description = "Blender Object",
default = "none"
)
is_imported: BoolProperty(
name = "Is imported flag",
description = "Flag set to true at the end of the import process"
)
pos: FloatVectorProperty(
name = "position",
description = "Reference Position",
size = 3,
precision = 6
)
rot: FloatVectorProperty(
name = "orientation",
description = "Reference Orientation",
size = 4,
precision = 6
)
vel: FloatVectorProperty(
name = "velocity",
description = "Reference Velocity",
size = 3,
precision = 6
)
angvel: FloatVectorProperty(
name = "angular velocity",
description = "Reference Angular Velocity",
size = 3,
precision = 6
)
# -----------------------------------------------------------
# end of BLENDYN_PG_reference_dictionary class
bpy.utils.register_class(BLENDYN_PG_reference_dictionary)
## Time PropertyGroup for animation
class BLENDYN_PG_mbtime(bpy.types.PropertyGroup):
time: FloatProperty(
name = "simulation time",
description = "simulation time of animation frame"
)
# -----------------------------------------------------------
# end of BLENDYN_PG_mbtime class
bpy.utils.register_class(BLENDYN_PG_mbtime)
## PropertyGroup of Render Variables
class BLENDYN_PG_render_vars_dictionary(bpy.types.PropertyGroup):
idx: IntProperty(
name = "Render Variable index",
description = "Index of the NetCDF variable to be set for display in rendering"
)
varname: StringProperty(
name = "Display name",
description = "Display name of the rendered variable"
)
variable: StringProperty(
name = "NetCDF variable",
description = "NetCDF variable to be rendered"
)
components: BoolVectorProperty(
name = "Components",
description = "Components of the variable to be displayed",
size = 9
)
# -----------------------------------------------------------
# end of BLENDYN_PG_render_vars_dictionary class
bpy.utils.register_class(BLENDYN_PG_render_vars_dictionary)
## PropertyGroup of Driver Variables
class BLENDYN_PG_driver_vars_dictionary(bpy.types.PropertyGroup):
variable: StringProperty(
name = "Variable",
description = "NetCDF variable to be rendered"
)
components: BoolVectorProperty(
name = "Components",
description = "Components of the variable to be displayed",
size = 9
)
values: FloatVectorProperty(
name = "Values",
description = "Values of the variable at current frame"
)
# -----------------------------------------------------------
# end of BLENDYN_PG_driver_vars_dictionary class
bpy.utils.register_class(BLENDYN_PG_driver_vars_dictionary)
class BLENDYN_PG_display_vars_dictionary(bpy.types.PropertyGroup):
name: StringProperty(
name = "Group of Display Variables",
description = ""
)
group: CollectionProperty(
name = "Actual collection group",
type = BLENDYN_PG_render_vars_dictionary
)
# -----------------------------------------------------------
# end of BLENDYN_PG_display_vars_dictionary class
bpy.utils.register_class(BLENDYN_PG_display_vars_dictionary)
## PropertyGroup of Environment Variables
class BLENDYN_PG_environment_vars_dictionary(bpy.types.PropertyGroup):
variable: StringProperty(
name = "Environment variables",
description = 'Variables to be set'
)
value: StringProperty(
name = "Values of Environment variables",
description = "Values of variables to be set"
)
# -----------------------------------------------------------
# end of BLENDYN_PG_environment_vars_dictionary class
bpy.utils.register_class(BLENDYN_PG_environment_vars_dictionary)
## PropertyGroup of MBDyn plottable variables
class BLENDYN_PG_plot_vars(bpy.types.PropertyGroup):
name: StringProperty(
name = "Plottable variable"
)
plot_comps: BoolVectorProperty(
name = "components",
description = "Components of property to plot",
default = [True for i in range(9)],
size = 9
)
as_driver: BoolProperty(
name = "Use as driver variable",
default = False,
update = update_driver_variables
)
plot_frequency: IntProperty(
name = "frequency",
description = "Frequency in plotting",
default = 1
)
fft_remove_mean: BoolProperty(
name = "Subtract mean",
description = "Subtract the mean value before calculating the FFT",
default = False
)
plot_xrange_min: FloatProperty(
name = "minimum X value",
description = "Minimum value for abscissa",
default = 0.0
)
plot_xrange_max: FloatProperty(
name = "maximum X value",
description = "Maximum value for abscissa",
default = 0.0
)
# -----------------------------------------------------------
# end of BLENDYN_PG_plot_vars class
bpy.utils.register_class(BLENDYN_PG_plot_vars)
## Set scene properties
class BLENDYN_PG_settings_scene(bpy.types.PropertyGroup):
# Base path of the module
addon_path: StringProperty(
name = "Addon path",
description = "Base path of addon files",
default = os.path.dirname(__file__)
)
# Boolean: is the .mov (or .nc) file loaded properly?
is_loaded: BoolProperty(
name = "MBDyn files loaded",
description = "True if MBDyn files are loaded correctly"
)
# MBDyn's imported files path
file_path: StringProperty(
name = "MBDyn file path",
description = "Path of MBDyn's imported files",
default = "",
subtype = 'DIR_PATH'
)
# Base name of MBDyn's imported files
file_basename: StringProperty(
name = "MBDyn base file name",
description = "Base file name of MBDyn's imported files",
default = "not yet loaded"
)
# Use text output even when NetCDF is available?
# This property is used when a simulation is run from Blender
force_text_import: BoolProperty(
name = "Always use text output",
description = "Use text output even when NetCDF output is available",
default = False
)
# Path of MBDyn input file (to run simulation from Blender)
input_path: StringProperty(
name = "Input File Path",
description = "Path of MBDyn input files",
default = "not yet selected"
)
# MBDyn input file (to run simulation from Blender)
input_basename: StringProperty(
name = "Input File basename",
description = "Base name of Input File",
default = "not yet selected"
)
# String representing path of MBDyn Installation
install_path: StringProperty(
name = "Installation path of MBDyn",
description = "Installation path of MBDyn",
subtype = 'DIR_PATH',
default = 'not yet set'
)
# Integer representing the current simulation
sim_num: IntProperty(
name = "Number of Simulation",
default = 0
)
final_time: FloatProperty(
name = "Previous State of Simulation",
default = 0.0
)
ui_time: FloatProperty(
name = "Final time from user",
default = 0.0
)
mbdyn_running: BoolProperty(
name = 'MBDyn running',
default = False
)
sim_status: IntProperty(
name = "Progress of Simulation",
default = 0
)
# Command-line options to be specified in MBDyn simulation
cmd_options: StringProperty(
name = "Command-line Options",
default = ''
)
# Boolean representing whether user wants to overwrite existing output files
overwrite: BoolProperty(
name = "Overwrite Property",
description = "True if the user wants to overwrite the existing output files",
default = False
)
del_log: BoolProperty(
name = "Log property",
description = "True if the user wants to delete log files on exit",
default = False,
update = update_del_log
)
render_nc_vars: EnumProperty(
items = get_render_vars,
name = "Text overlay variables",
)
render_var_name: StringProperty(
name = "Name of variable",
default = ''
)
render_vars: CollectionProperty(
name = "RenderVars",
description = "MBDyn render variables collection",
type = BLENDYN_PG_render_vars_dictionary
)
driver_vars: CollectionProperty(
name = "DriverVars",
description = "Variables set to track NetCDF variables",
type = BLENDYN_PG_driver_vars_dictionary
)
display_vars_group: CollectionProperty(
name = "MBDyn Display variables group collection",
type = BLENDYN_PG_display_vars_dictionary
)
display_enum_group: EnumProperty(
items = get_display_group,
name = 'Display Enum Group'
)
group_name: StringProperty(
name = "Name of Display Variables Group"
)
plot_group: BoolProperty(
name = "Plot List of variables as group",
default = False
)
# Collection of Environment variables and corresponding values
env_vars: CollectionProperty(
name = "MBDyn environment variables collection",
type = BLENDYN_PG_environment_vars_dictionary
)
# Environment Variables index, holds the index for displaying the Envrionment variables in a list
env_index: IntProperty(
name = "MBDyn Environment variables collection index",
default = 0
)
render_index: IntProperty(
name = "MBDyn Render Variables collection index",
default = 0
)
# Name of the Environment Variable
env_variable: StringProperty(
name = "MBDyn environment variables",
description = "Environment variables used in MBDyn simulation"
)
# Value associated with the Environment Variable
env_value: StringProperty(
name = "Values of MBDyn environment values",
description = "Values of the environment variables used in MBDyn simulation"
)
# Number of rows (output time steps * number of nodes) in MBDyn's .mov file
num_rows: IntProperty(
name = "MBDyn .mov file number of rows",
description = "Total number of rows in MBDyn .mov file, corresponding (total time steps * number of nodes)"
)
# Load frequency: if different than 1, the .mov file is read every N time steps
load_frequency: FloatProperty(
name = "frequency",
description = "If this value is X, different than 1, then the MBDyn output is loaded every X time steps",
min = 1.0,
default = 1.0
)
#Start time
start_time: FloatProperty(
name = "Start Time",
description = "If this value is X, different than 0, the import starts at X seconds",
min = 0.0,
default = 0.0,
update = update_start_time
)
end_time: FloatProperty(
name = "End Time",
description = "If this value is X, different than total simulation time, the import stops at X seconds",
min = 0.0,
update = update_end_time
)
time_step: FloatProperty(
name = "Time Step",
description = "Simulation time step"
)
# Reference dictionary -- holds the associations between MBDyn references and blender
# objects
references: CollectionProperty(
name = "MBDyn references",
type = BLENDYN_PG_reference_dictionary
)
# Reference dictionary index -- holds the index for displaying the Reference
# Dictionary in a UI List
ref_index: IntProperty(
name = "References collection index",
default = 0
)
# Nodes dictionary -- holds the association between MBDyn nodes and blender objects
nodes: CollectionProperty(
name = "MBDyn nodes",
type = BLENDYN_PG_nodes_dictionary
)
# Do we use 'free' or 'structured' labels?
free_labels: BoolProperty(
name = "Use free labels",
description = "Do not check variable name when parsing labels"
# update = bpy.ops.blendyn.free_labels_warning
)
# Nodes dictionary index -- holds the index for displaying the Nodes Dictionary in a UI List
nd_index: IntProperty(
name = "MBDyn nodes collection index",
default = 0
)
# Default object representing a node, when imported automatically
node_object: EnumProperty(
items = [("ARROWS", "Arrows", "Empty - arrows", 'OUTLINER_OB_EMPTY', 1),\
("AXES", "Axes", "Empty - axes", 'EMPTY_DATA', 2),\
("CUBE", "Cube", "", 'MESH_CUBE', 3),\
("UVSPHERE", "UV Sphere", "", 'MESH_UVSPHERE', 4),\
("NSPHERE", "Nurbs Sphere", "", 'SURFACE_NSPHERE', 5),\
("CONE", "Cone", "", 'MESH_CONE', 6)],
name = "Import nodes as",
default = "ARROWS"
)
missing: EnumProperty(
items = [("DO_NOTHING", "Do Nothing","","" ,1),\
("HIDE", "Hide", "","" ,2),\
("DELETE", "Delete", "", "", 3)],
name = "Handling of missing nodes/elements",
default = "HIDE"
)
# Behavior for importing shells and beams: get a single mesh or separate mesh objects?
mesh_import_mode: EnumProperty(
items = [("SEPARATED_OBJECTS", "Separated mesh objects", "", 'UNLINKED', 1),\
("SINGLE_MESH", "Joined in single mesh", "", 'LINKED', 2)],
name = "Mesh objects",
default = "SEPARATED_OBJECTS"
)
# Elements dictionary -- holds the collection of the elements found in the .log file
elems: CollectionProperty(
name = "MBDyn elements collection",
type = BLENDYN_PG_elems_dictionary
)
# Elements to be updated -- holds the keys to elements that need to update their configuration
# when the scene changes
elems_to_update: CollectionProperty(
type = BLENDYN_PG_elem_to_be_updated,
name = "Elements that require update",
description = "Collection of indexes of the elements that need to be updated when \
the scene is changed"
)
# Current Simulation Time
simtime: CollectionProperty(
name = "MBDyn simulation time",
type = BLENDYN_PG_mbtime
)
# Current simulation time
time: FloatProperty(
name = "time: ",
description = "Current MBDyn simulation time",
default = 0.0
)
# Elements dictionary index -- holds the index for displaying the Elements Dictionary in a
# UI List
ed_index: IntProperty(
name = "MBDyn elements collection index",
default = 0
)
# MBDyn's node count
num_nodes: IntProperty(
name = "MBDyn nodes number",
description = "MBDyn node count"
)
# MBDyn's time steps count
num_timesteps: IntProperty(
name = "MBDyn time steps",
description = "MBDyn time steps count"
)
# Flag that indicates if we are to use NETCDF results format
use_netcdf: BoolProperty(
name = "Use netCDF",
description = "Import results in netCDF format",
default = False
)
# Flag that indicates if the .mov (or .nc) file is loaded correctly and the
# nodes dictionary is ready, used to indicate that all is ready for the object's
# to be animated
is_ready: BoolProperty(
name = "ready to animate",
description = "True if .mov (or .nc) file and nodes dictionary loaded correctly",
)
# If we want to hook vertices in creating mesh from nodes
is_vertshook: BoolProperty(
name = "Hook vertices",
description = "Hook directly the vertices to the nodes in creating a mesh object?",
default = False
)
# Lower limit of range import for nodes
min_node_import: IntProperty(
name = "first node to import",
description = "Lower limit of integer labels for range import for nodes",
default = 0
)
# Higher limit of range import for nodes
max_node_import: IntProperty(
name = "last node to import",
description = "Higher limit of integer labels for range import for nodes",
default = 0
)
node_scale_slider: FloatProperty(
name = "Scaling factor",
default = 1.0
)
# Type filter for elements import
elem_type_import: EnumProperty(
items = get_elems_types,
name = "Elements to import",
)
elem_scale_slider: FloatProperty(
name = "Scaling Factor",
default = 1.0
)
# Lower limit of range import for elements
min_elem_import: IntProperty(
name = "first element to import",
description = "Lower limit of integer labels for range import for elements",
default = 0
)
# Higher limit of range import for elements
max_elem_import: IntProperty(
name = "last element to import",
description = "Higher limit of integer labels for range import for elements",
default = 2**31 - 1
)
components: CollectionProperty(
name = "Components",
description = "Components structural and geometrical data",
type = BLENDYN_PG_components_dictionary
)
adding_component: BoolProperty(
description = "Are we adding a new component?",
default = False
)
editing_component: BoolProperty(
description = "Are we editing an existing component?",
default = False
)
# Components dictionary index -- holds the index for displaying the
# Components Dictionary in a UI List
cd_index: IntProperty(
name = "MBDyn components collection index",
default = 0,
min = 0,
update = update_cd_index,
)
comp_selected_elem: EnumProperty(
items = get_deformable_elems,
name = "Selected element",
description = "Selected element in deformable elements list"
)
eigensolutions: CollectionProperty(
name = "Eigensolutions",
description = "Parameters of the eigensolutions found in the MBDyn output",
type = BLENDYN_PG_eigenanalysis
)
curr_eigsol: IntProperty(
name = "current eigensolution",
description = "Index of the currently selected eigensolution",
default = 0,
update = update_curr_eigsol
)
plot_vars: CollectionProperty(
name = "MBDyn variables available for plotting",
type = BLENDYN_PG_plot_vars
)
plot_var_index: IntProperty(
name = "Plot variable index",
description = "index of the current variable to be plotted",
default = 0
)
plot_engine: EnumProperty(
items=[("PYGAL", "Pygal", "Pygal", '', 2), \
("MATPLOTLIB", "Matplotlib", "Matplotlib", '', 1), \
("BOKEH", "Bokeh", "bokeh", '', 3)], \
name="plot engine",
default="MATPLOTLIB"
)
plot_type: EnumProperty(
items=[("TIME_HISTORY", "Time history", "Time history", '', 1), \
("AUTOSPECTRUM", "Autospectrum", "Autospectrum", '', 2), \
("TRAJECTORY", "Trajectory", "Trajectory", '', 3)], \
name="plot type",
default="TIME_HISTORY"
)
show_in_localhost: BoolProperty(
description = "Are you want to show your plot in localhost?",
default = False
)
save_as_png: BoolProperty(
description = "Are you want to save your plot as png?",
default = False
)
if HAVE_PLOT:
plot_sxy_varX: StringProperty(
name = "Cross-spectrum X variable",
description = "variable to be used as input in cross-spectrum",
default = "none"
)
plot_sxy_varY: StringProperty(
name = "Cross-spectrum Y variable",
description = "variable to be used as output in cross-spectrum",
default = "none"
)
# -----------------------------------------------------------
# end of BLENDYN_PG_settings_scene class
## MBDyn Settings for Blender Object
class BLENDYN_PG_settings_object(bpy.types.PropertyGroup):
""" Properties of the current Blender Object related to MBDyn """
# Type of MBDyn entity
type: StringProperty(
name = "MBDyn entity type",
description = "Type of MBDyn entity associated with object",
default = 'none'
)
# Dictionary key
dkey: StringProperty(
name = "MBDyn dictionary index",
description = "Index of the entry of the MBDyn dictionary relative to the object",
default = 'none'
)
# Specific for plotting
if HAVE_PLOT:
plot_var_index: IntProperty(
name = "Plot variable index",
description = "index of the current variable to be plotted",
default = 0
)
# -----------------------------------------------------------
# end of BLENDYN_PG_settings_object class
bpy.utils.register_class(BLENDYN_PG_settings_object)
bpy.utils.register_class(BLENDYN_PG_settings_scene)
bpy.types.Scene.mbdyn = PointerProperty(type=BLENDYN_PG_settings_scene)
bpy.types.Object.mbdyn = PointerProperty(type=BLENDYN_PG_settings_object)
# Handler to update the current time of simulation
@persistent
def update_time(scene):
try:
scene.mbdyn.time = scene.mbdyn.simtime[scene.frame_current].time
except IndexError:
pass
bpy.app.handlers.frame_change_pre.append(update_time)
@persistent
def render_variables(scene):
mbs = scene.mbdyn
if len(mbs.render_vars):
try:
ncfile = os.path.join(os.path.dirname(mbs.file_path), \
mbs.file_basename + '.nc')
nc = Dataset(ncfile, "r")
string = [ '{0} : {1}'.format(var.variable, \
parse_render_string(netcdf_helper(nc, scene, var.variable), var.components)) \
for var in mbs.render_vars ]
string = '\n'.join(string)
if len(mbs.render_vars):
bpy.data.scenes['Scene'].render.stamp_note_text = string
except IndexError:
pass
if HAVE_PLOT:
bpy.app.handlers.frame_change_pre.append(render_variables)
@persistent
def update_driver_vars(scene):
mbs = scene.mbdyn
ncfile = os.path.join(os.path.dirname(mbs.file_path), \
mbs.file_basename + '.nc')
if (mbs.is_loaded and mbs.use_netcdf):
nc = Dataset(ncfile, "r")
for dvar in mbs.driver_vars:
ncvar = netcdf_helper(nc, scene, dvar.variable)
dim = len(ncvar.shape)
if dim == 1:
for ii in range(len(ncvar)):
dvar.values[ii] = ncvar[ii] if dvar.components[ii] else 0.0
else:
for ii in range(3):
for jj in range(3):
dvar.values[ii + jj] = ncvar[ii,jj] if dvar.components[ii+jj] else 0.0
bpy.app.handlers.frame_change_pre.append(update_driver_vars)
@persistent
def close_log(scene):
baseLogger.handlers = []
bpy.app.handlers.load_pre.append(close_log)
bpy.app.handlers.save_pre.append(close_log)
@persistent
def set_mbdyn_path_startup(scene):
mbs = bpy.context.scene.mbdyn
try:
with open(os.path.join(mbs.addon_path, 'config.json'), 'r') as f:
mbs.install_path = json.load(f)['mbdyn_path']
except FileNotFoundError:
if shutil.which('mbdyn'):
mbs.install_path = os.path.dirname(shutil.which('mbdyn'))
pass
bpy.app.handlers.load_post.append(set_mbdyn_path_startup)
@persistent
def blend_log(scene):
mbs = bpy.context.scene.mbdyn
if mbs.file_path:
log_messages(mbs, baseLogger, False)
bpy.app.handlers.load_post.append(blend_log)
@persistent
def rename_log(scene):
mbs = bpy.context.scene.mbdyn
logFile = ('{0}_{1}.bylog').format(mbs.file_path + 'untitled', mbs.file_basename)
newBlend = path_leaf(bpy.data.filepath)[1]
newLog = ('{0}_{1}.bylog').format(mbs.file_path + newBlend, mbs.file_basename)
try:
os.rename(logFile, newLog)
except FileNotFoundError:
pass
if os.path.basename(logFile) != "untitled_not yet loaded.bylog":
try:
bpy.data.texts[os.path.basename(logFile)].name = os.path.basename(newLog)
log_messages(mbs, baseLogger, True)
except KeyError:
pass
bpy.app.handlers.save_post.append(rename_log)
class BLENDYN_OT_standard_import(bpy.types.Operator):
""" Automatically import nodes and elements at once """
bl_idname = "blendyn.standard_import"
bl_label = "MBDyn Standard Import"
def execute(self, context):
selftag = 'BLENDYN_OT_standard_import::execute(): '
try:
bpy.ops.blendyn.read_mbdyn_log_file('EXEC_DEFAULT')
bpy.ops.blendyn.node_import_all('EXEC_DEFAULT')
bpy.ops.blendyn.elements_import_all('EXEC_DEFAULT')
except RuntimeError as re:
message = "BLENDYN_OT_standard_import::modal(): something went wrong during the automatic import. "\
+ " See the .bylog file for details"
self.report({'ERROR'}, message)
baseLogger.error(selftag + message)
return {'CANCELLED'}
message = "BLENDYN_OT_standard_import::modal(): Done."
self.report({'INFO'}, message)
baseLogger.info(selftag + message)
bpy.ops.object.select_all(action = 'DESELECT')
return {'FINISHED'}
def invoke(self, context, event):
return self.execute(context)
# -----------------------------------------------------------
# end of BLENDYN_OT_stardard_import class
class BLENDYN_OT_read_mbdyn_log_file(bpy.types.Operator):
""" Imports MBDyn nodes and elements by parsing the .log file """
bl_idname = "blendyn.read_mbdyn_log_file"
bl_label = "MBDyn .log file parsing"
def execute(self, context):
mbs = context.scene.mbdyn
ret_val, obj_names = parse_log_file(context)
missing = context.scene.mbdyn.missing
selftag = 'BLENDYN_OT_read_mbdyn_log_file::execute(): '
if len(obj_names) > 0:
message = "Some of the nodes/elements are missing in the new .log file"
self.report({'WARNING'}, message)
baseLogger.warning(selftag + message)
hide_or_delete(obj_names, missing)
return {'FINISHED'}
if ret_val == {'LOG_NOT_FOUND'}:
message = ".log file not found"
self.report({'ERROR'}, message)
baseLogger.error(selftag + message)
return {'CANCELLED'}
elif ret_val == {'NODES_NOT_FOUND'}:
message = "The .log file selected does not contain node definitions"
self.report({'ERROR'}, message)
baseLogger.error(selftag + message)
return {'CANCELLED'}
elif ret_val == {'MODEL_INCONSISTENT'}:
message = "Contents of .log file are not onsistent with "\
+ "current Blender scene."
self.report({'WARNING'}, message)
baseLogger.warning(selftag + message)
return {'FINISHED'}
elif ret_val == {'NODES_INCONSISTENT'}:
message = "Nodes in .log file are not consistent with "\
+ "current Blender scene"
self.report({'WARNING'}, message)
baseLogger.warning(selftag + message)
return {'FINISHED'}
elif ret_val == {'ELEMS_INCONSISTENT'}:
message = "Elements in .log file are not consistent with "\
+ "curren Blender scene"
self.report({'WARNING'}, message)
baseLogger.warning(selftag + message)
return {'FINISHED'}
elif ret_val == {'OUT_NOT_FOUND'}:
message = "Could not locate the .out file"
self.report({'WARNING'}, message)
baseLogger.warning(selftag + message)
return {'FINISHED'}
elif ret_val == {'ROTATION_ERROR'}:
message = "Output rotation parametrization is not supported by Blender"
self.report({'ERROR'}, message)
baseLogger.error(selftag + message)
return {'CANCELLED'}
elif ret_val == {'FINISHED'}:
message = "MBDyn model imported successfully"
bpy.context.scene.render.use_stamp = True
bpy.context.scene.render.use_stamp_note = True
self.report({'INFO'}, message)
baseLogger.info(selftag + message)
return {'FINISHED'}
else:
# should not be reached
message = "Unknown error in reading .log file."\
+ "The return value of parse_log_file() was: {}".format(ret_val)
self.report({'ERROR'}, message)
baseLogger.info(selftag + message)
return {'CANCELLED'}
def invoke(self, context, event):
return self.execute(context)
# -----------------------------------------------------------
# end of BLENDYN_OT_read_mbdyn_log_file class
class BLENDYN_OT_select_output_file(bpy.types.Operator, ImportHelper):
""" Sets MBDyn's output files path and basename """
bl_idname = "blendyn.select_output_file"
bl_label = "Select MBDyn results file"
filter_glob: StringProperty(
default = "*.mov;*.nc",
options = {'HIDDEN'},
)
def execute(self, context):
mbs = context.scene.mbdyn
# removes keyframes before importing a new file
remove_oldframes(context)
si_retval = setup_import(self.filepath, context)
selftag = "BLENDYN_OT_select_output_file::execute(): "
if si_retval == {'NETCDF_ERROR'}:
message = "NetCDF module not imported correctly"
self.report({'ERROR'}, message)
baseLogger.error(selftag + message)
return {'CANCELLED'}
elif si_retval == {'FILE_ERROR'}:
message = "Output file not set correctly (no file selected?)"
self.report({'ERROR'}, message)
baseLogger.error(selftag + message)
elif si_retval == {'FINISHED'}:
mbs.file_path, mbs.file_basename = path_leaf(self.filepath)
baseLogger.handlers = []
log_messages(mbs, baseLogger, False)
return si_retval
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
# -----------------------------------------------------------
# end of BLENDYN_OT_select_output_file class
class BLENDYN_OT_assign_labels(bpy.types.Operator):
""" Assigns 'recognisable' labels to MBDyn nodes and elements by
parsing the .log file """