-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathforcelib.py
604 lines (500 loc) · 22.8 KB
/
forcelib.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
# --------------------------------------------------------------------------
# Blendyn -- file forcelib.py
# Copyright (C) 2015 -- 2021 Andrea Zanoni -- [email protected]
# --------------------------------------------------------------------------
# ***** 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 bpy
import os
from mathutils import *
from math import *
from .utilslib import *
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))
## Parses structural absolute force entry in the .log file
# (see section E.2.22 of input manual for details)
def parse_structural_absolute_force(rw, ed):
ret_val = True
# Debug message
try:
el = ed['structural_absolute_force_' + str(rw[3])]
eldbmsg({'PARSE_ELEM'}, "BLENDYN::parse_structural_absolute_force():", el)
eldbmsg({'FOUND_DICT'}, "BLENDYN::parse_structural_absolute_force():", el)
el.nodes[0].int_label = int(rw[4])
el.offsets[0].value = Vector(( float(rw[5]), float(rw[6]), float(rw[7]) ))
# FIXME: this is here to enhance backwards compatibility.
# Should disappear in future versions
el.mbclass = 'elem.force'
if el.name in bpy.data.objects.keys():
el.blender_object = el.name
el.is_imported = True
pass
except KeyError:
pass
el = ed.add()
el.mbclass = 'elem.force'
el.type = 'structural_absolute_force'
el.int_label = int(rw[3])
eldbmsg({'PARSE_ELEM'}, "BLENDYN::parse_structural_absolute_force():", el)
eldbmsg({'NOTFOUND_DICT'}, "BLENDYN::parse_structural_absolute_force():", el)
el.nodes.add()
el.nodes[0].int_label = int(rw[4])
el.offsets.add()
el.offsets[0].value = Vector(( float(rw[5]), float(rw[6]), float(rw[7]) ))
el.import_function = "blendyn.import_structural_absolute_force"
el.update = "update_structural_force"
el.name = el.type + "_" + str(el.int_label)
el.is_imported = True
ret_val = False
return ret_val
# -----------------------------------------------------------
# end of parse_structural_absolute_force(rw, ed) function
## Parses structural follower force entry in the .log file
# (see section E.2.22 of input manual for details)
def parse_structural_follower_force(rw, ed):
ret_val = True
try:
el = ed['structural_follower_force_' + str(rw[3])]
eldbmsg({'PARSE_ELEM'}, "BLENDYN::parse_structural_follower_force():", el)
eldbmsg({'FOUND_DICT'}, "BLENDYN::parse_structural_follower_force():", el)
el.nodes[0].int_label = int(rw[4])
el.offsets[0].value = Vector(( float(rw[5]), float(rw[6]), float(rw[7]) ))
# FIXME: this is here to enhance backwards compatibility.
# Should disappear in future versions
el.mbclass = 'elem.force'
if el.name in bpy.data.objects.keys():
el.blender_object = el.name
el.is_imported = True
pass
except KeyError:
pass
el = ed.add()
el.mbclass = 'elem.force'
el.type = 'structural_follower_force'
el.int_label = int(rw[3])
eldbmsg({'PARSE_ELEM'}, "BLENDYN::parse_structural_follower_force():", el)
eldbmsg({'NOTFOUND_DICT'}, "BLENDYN::parse_structural_follower_force():", el)
el.nodes.add()
el.nodes[0].int_label = int(rw[4])
el.offsets.add()
el.offsets[0].value = Vector(( float(rw[5]), float(rw[6]), float(rw[7]) ))
el.import_function = "blendyn.import_structural_follower_force"
el.update = "update_structural_force"
el.name = el.type + "_" + str(el.int_label)
el.is_imported = True
ret_val = False
return ret_val
# -----------------------------------------------------------
# end of parse_structural_follower_force(rw, ed) function
## Parses structural absolute couple entry in the .log file
# (see section E.2.22 of input manual for details)
def parse_structural_absolute_couple(rw, ed):
ret_val = True
try:
el = ed['structural_absolute_couple_' + str(rw[3])]
eldbmsg({'PARSE_ELEM'}, "BLENDYN::parse_structural_absolute_couple():", el)
eldbmsg({'FOUND_DICT'}, "BLENDYN::parse_structural_absolute_couple():", el)
el.nodes[0].int_label = int(rw[4])
el.offsets[0].value = Vector(( float(rw[5]), float(rw[6]), float(rw[7]) ))
# FIXME: this is here to enhance backwards compatibility.
# Should disappear in future versions
el.mbclass = 'elem.force'
if el.name in bpy.data.objects.keys():
el.blender_object = el.name
el.is_imported = True
pass
except KeyError:
pass
el = ed.add()
el.mbclass = 'elem.force'
el.type = 'structural_absolute_couple'
el.int_label = int(rw[3])
eldbmsg({'PARSE_ELEM'}, "BLENDYN::parse_structural_absolute_couple():", el)
eldbmsg({'NOTFOUND_DICT'}, "BLENDYN::parse_structural_absolute_couple():", el)
el.nodes.add()
el.nodes[0].int_label = int(rw[4])
el.offsets.add()
el.offsets[0].value = Vector(( float(rw[5]), float(rw[6]), float(rw[7]) ))
el.import_function = "blendyn.import_structural_absolute_couple"
el.update = "update_structural_couple"
el.name = el.type + "_" + str(el.int_label)
el.is_imported = True
ret_val = False
return ret_val
# -----------------------------------------------------------
# end of parse_structural_absolute_couple(rw, ed) function
## Parses structural follower couple entry in the .log file
# (see section E.2.22 of input manual for details)
def parse_structural_follower_couple(rw, ed):
ret_val = True
try:
el = ed['structural_follower_couple_' + str(rw[3])]
eldbmsg({'PARSE_ELEM'}, "BLENDYN::parse_structural_follower_couple():", el)
eldbmsg({'FOUND_DICT'}, "BLENDYN::parse_structural_follower_couple():", el)
el.nodes[0].int_label = int(rw[4])
el.offsets[0].value = Vector(( float(rw[5]), float(rw[6]), float(rw[7]) ))
# FIXME: this is here to enhance backwards compatibility.
# Should disappear in future versions
el.mbclass = 'elem.force'
if el.name in bpy.data.objects.keys():
el.blender_object = el.name
el.is_imported = True
pass
except KeyError:
pass
el = ed.add()
el.mbclass = 'elem.force'
el.type = 'structural_follower_couple'
el.int_label = int(rw[3])
eldbmsg({'PARSE_ELEM'}, "BLENDYN::parse_structural_follower_couple():", el)
eldbmsg({'NOTFOUND_DICT'}, "BLENDYN::parse_structural_follower_couple():", el)
el.nodes.add()
el.nodes[0].int_label = int(rw[4])
el.offsets.add()
el.offsets[0].value = Vector(( float(rw[5]), float(rw[6]), float(rw[7]) ))
el.import_function = "blendyn.import_structural_follower_couple"
el.update = "update_structural_couple"
el.name = el.type + "_" + str(el.int_label)
el.is_imported = True
ret_val = False
return ret_val
# -----------------------------------------------------------
# end of parse_structural_follower_couple(rw, ed) function
## Spawns a Blender object representing a structural absolute force element
def spawn_structural_force_element(elem, context):
""" Draws a structural force element, loading a wireframe
object from the addon library """
mbs = context.scene.mbdyn
nd = mbs.nodes
if any(obj == elem.blender_object for obj in context.scene.objects.keys()):
return {'OBJECT_EXISTS'}
try:
n1 = nd['node_' + str(elem.nodes[0].int_label)].blender_object
except KeyError:
return {'NODE1_NOTFOUND'}
# node object
n1OBJ = bpy.data.objects[n1]
try:
set_active_collection('forces')
elcol = bpy.data.collections.new(name = elem.name)
bpy.data.collections['forces'].children.link(elcol)
set_active_collection(elcol.name)
# load the wireframe force object from the library
bpy.ops.wm.append(directory = os.path.join(mbs.addon_path,\
'library', 'forces.blend', 'Object'), filename = 'force')
# the append operator leaves just the imported object selected
forceOBJ = bpy.context.selected_objects[0]
forceOBJ.name = elem.name
# offsets with respect to nodes
f1 = Vector(( elem.offsets[0].value[0:] ))
# project offsets in global frame
R1 = n1OBJ.rotation_quaternion.to_matrix()
p1 = n1OBJ.location + R1@f1
# place the joint object in the position defined relative to node 1
forceOBJ.location = p1
forceOBJ.rotation_mode = 'QUATERNION'
# set parenting of wireframe obj
parenting(forceOBJ, n1OBJ)
elem.blender_object = forceOBJ.name
forceOBJ.mbdyn.dkey = elem.name
forceOBJ.mbdyn.type = 'element'
# Flag the object to be updated
ude = bpy.context.scene.mbdyn.elems_to_update.add()
ude.dkey = elem.name
ude.name = elem.name
# link objects to element collection
elcol.objects.link(n1OBJ)
set_active_collection('Master Collection')
return {'FINISHED'}
except FileNotFoundError:
return {'LIBRARY_ERROR'}
except KeyError:
return {'COLLECTION_ERROR'}
# -----------------------------------------------------------
# end of spawn_structural_force_element(elem, layout) function
## Spawns a Blender object representing a structural absolute couple element
def spawn_structural_couple_element(elem, context):
""" Draws a structural couple element, loading a wireframe
object from the addon library """
mbs = context.scene.mbdyn
nd = mbs.nodes
if any(obj == elem.blender_object for obj in context.scene.objects.keys()):
return {'OBJECT_EXISTS'}
try:
n1 = nd['node_' + str(elem.nodes[0].int_label)].blender_object
except KeyError:
return {'NODE1_NOTFOUND'}
# node object
n1OBJ = bpy.data.objects[n1]
try:
set_active_collection('forces')
elcol = bpy.data.collections.new(name = elem.name)
bpy.data.collections['forces'].children.link(elcol)
set_active_collection(elcol.name)
bpy.ops.wm.append(directory = os.path.join(mbs.addon_path,\
'library', 'forces.blend', 'Object'), filename = 'couple')
# the append operator leaves just the imported object selected
coupleOBJ = bpy.context.selected_objects[0]
coupleOBJ.name = elem.name
# offsets with respect to nodes
f1 = Vector(( elem.offsets[0].value[0:] ))
# project offsets in global frame
R1 = n1OBJ.rotation_quaternion.to_matrix()
p1 = n1OBJ.location + R1@f1
# place the joint object in the position defined relative to node 1
coupleOBJ.location = p1
coupleOBJ.rotation_mode = 'QUATERNION'
# set parenting of wireframe obj
parenting(coupleOBJ, n1OBJ)
elem.blender_object = coupleOBJ.name
coupleOBJ.mbdyn.dkey = elem.name
coupleOBJ.mbdyn.type = 'element'
# Flag the object to be updated
ude = bpy.context.scene.mbdyn.elems_to_update.add()
ude.dkey = elem.name
ude.name = elem.name
# link objects to element collection
elcol.objects.link(n1OBJ)
set_active_collection('Master Collection')
return {'FINISHED'}
except FileNotFoundError:
return {'LIBRARY_ERROR'}
except KeyError:
return {'COLLECTION_ERROR'}
# -----------------------------------------------------------
# end of spawn_structural_couple_element(elem, layout) function
# Imports a Structural Absolute Force Element in the scene
class BLENDYN_OT_import_structural_absolute_force(bpy.types.Operator):
""" Imports a structural absolute force element
into the Blender scene """
bl_idname = "blendyn.import_structural_absolute_force"
bl_label = "Imports a structural absolute force element"
int_label: bpy.props.IntProperty()
def draw(self, context):
layout = self.layout
layout.alignment = 'LEFT'
def execute(self, context):
ed = bpy.context.scene.mbdyn.elems
nd = bpy.context.scene.mbdyn.nodes
try:
elem = ed['structural_absolute_force_' + str(self.int_label)]
retval = spawn_structural_force_element(elem, context)
if retval == {'OBJECT_EXISTS'}:
eldbmsg(retval, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
elif retval == {'NODE1_NOTFOUND'}:
eldbmsg(retval, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
elif retval == {'COLLECTION_ERROR'}:
eldbmsf(retval, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
elif retval == {'LIBRARY_ERROR'}:
eldbmsg(retval, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
elif retval == {'FINISHED'}:
eldbmsg({'IMPORT_SUCCESS'}, type(self).__name__ + '::execute()', elem)
return retval
else:
# Should not be reached
return retval
except KeyError:
eldbmsg({'DICT_ERROR'}, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
# -----------------------------------------------------------
# end of BLENDYN_OT_import_structural_absolute_force class
# Imports a Structural Follower Force Element in the scene
class BLENDYN_OT_import_structural_follower_force(bpy.types.Operator):
""" Imports a structural follower force element into the Blender scene """
bl_idname = "blendyn.import_structural_follower_force"
bl_label = "Imports a structural follower force element"
int_label: bpy.props.IntProperty()
def draw(self, context):
layout = self.layout
layout.alignment = 'LEFT'
def execute(self, context):
ed = bpy.context.scene.mbdyn.elems
nd = bpy.context.scene.mbdyn.nodes
try:
elem = ed['structural_follower_force_' + str(self.int_label)]
retval = spawn_structural_force_element(elem, context)
if retval == {'OBJECT_EXISTS'}:
eldbmsg(retval, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
elif retval == {'NODE1_NOTFOUND'}:
eldbmsg(retval, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
elif retval == {'COLLECTION_ERROR'}:
eldbmsf(retval, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
elif retval == {'LIBRARY_ERROR'}:
eldbmsg(retval, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
elif retval == {'FINISHED'}:
eldbmsg({'IMPORT_SUCCESS'}, type(self).__name__ + '::execute()', elem)
return retval
else:
# Should not be reached
return retval
except KeyError:
eldbmsg({'DICT_ERROR'}, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
# -----------------------------------------------------------
# end of BLENDYN_OT_import_structural_follower_force class
# Imports a Structural Absolute Couple Element in the scene
class BLENDYN_OT_import_structural_absolute_couple(bpy.types.Operator):
""" Imports a structural absolute couple element """
bl_idname = "blendyn.import_structural_absolute_couple"
bl_label = "Imports a structural absolute couple element"
int_label: bpy.props.IntProperty()
def draw(self, context):
layout = self.layout
layout.alignment = 'LEFT'
def execute(self, context):
ed = bpy.context.scene.mbdyn.elems
nd = bpy.context.scene.mbdyn.nodes
try:
elem = ed['structural_absolute_couple_' + str(self.int_label)]
retval = spawn_structural_couple_element(elem, context)
if retval == {'OBJECT_EXISTS'}:
eldbmsg(retval, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
elif retval == {'NODE1_NOTFOUND'}:
eldbmsg(retval, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
elif retval == {'COLLECTION_ERROR'}:
eldbmsf(retval, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
elif retval == {'LIBRARY_ERROR'}:
eldbmsg(retval, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
elif retval == {'FINISHED'}:
eldbmsg({'IMPORT_SUCCESS'}, type(self).__name__ + '::execute()', elem)
return retval
else:
# Should not be reached
return retval
except KeyError:
eldbmsg({'DICT_ERROR'}, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
# -----------------------------------------------------------
# end of BLENDYN_OT_import_structural_absolute_couple class
# Imports a Structural Follower Couple Element in the scene
class BLENDYN_OT_import_structural_follower_couple(bpy.types.Operator):
""" Imports a structural follower couple element """
bl_idname = "blendyn.import_structural_follower_couple"
bl_label = "Imports a structural follower couple element"
int_label: bpy.props.IntProperty()
def draw(self, context):
layout = self.layout
layout.alignment = 'LEFT'
def execute(self, context):
ed = bpy.context.scene.mbdyn.elems
nd = bpy.context.scene.mbdyn.nodes
try:
elem = ed['structural_follower_couple_' + str(self.int_label)]
retval = spawn_structural_couple_element(elem, context)
if retval == {'OBJECT_EXISTS'}:
eldbmsg(retval, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
elif retval == {'NODE1_NOTFOUND'}:
eldbmsg(retval, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
elif retval == {'LIBRARY_ERROR'}:
eldbmsg(retval, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
elif retval == {'COLLECTION_ERROR'}:
eldbmsf(retval, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
elif retval == {'FINISHED'}:
eldbmsg({'IMPORT_SUCCESS'}, type(self).__name__ + '::execute()', elem)
return retval
else:
return retval
except KeyError:
eldbmsg({'DICT_ERROR'}, type(self).__name__ + '::execute()', elem)
return {'CANCELLED'}
# -----------------------------------------------------------
# end of BLENDYN_OT_import_structural_follower_couple class
def update_structural_force(elem, insert_keyframe = False):
""" Updates the configuration of a structural force
by scaling and orienting the arrow in the correct way """
scene = bpy.context.scene
mbs = scene.mbdyn
nd = mbs.nodes
if mbs.use_netcdf:
tdx = int(scene.frame_current * mbs.load_frequency)
ncfile = os.path.join(os.path.dirname(mbs.file_path), \
mbs.file_basename + '.nc')
nc = Dataset(ncfile, "r")
node = nd['node_' + str(elem.nodes[0].int_label)]
nodeOBJ = bpy.data.objects[node.blender_object]
R0 = nodeOBJ.matrix_world.to_3x3().normalized()
obj = bpy.data.objects[elem.blender_object]
try:
F = Vector(( nc.variables['elem.force.' + str(elem.int_label) + '.F'][tdx,:] ))
Fl = R0.transposed()@F
obj.rotation_quaternion = (-Fl).to_track_quat('-Z', 'Y')
obj.scale = Vector(( 1, 1, Fl.magnitude ))
except IndexError:
if tdx >= nc.variables['elem.force.' + str(elem.int_label) + '.F'].shape[0]:
pass # we're requesting a value of the
# force beyond the last timestep
else:
raise
else:
pass
# -----------------------------------------------------------
# end of update_structural_force() function
def update_structural_couple(elem, insert_keyframe = False):
""" Updates the configuration of a structural couple
by scaling and orienting the arrow in the correct way """
scene = bpy.context.scene
mbs = scene.mbdyn
nd = mbs.nodes
if mbs.use_netcdf:
tdx = scene.frame_current * mbs.load_frequency
ncfile = os.path.join(os.path.dirname(mbs.file_path), \
mbs.file_basename + '.nc')
nc = Dataset(ncfile, "r")
node = nd['node_' + str(elem.nodes[0].int_label)]
nodeOBJ = bpy.data.objects[node.blender_object]
R0 = nodeOBJ.matrix_world.to_3x3().normalized()
obj = bpy.data.objects[elem.blender_object]
try:
M = Vector(( nc.variables['elem.couple.' + str(elem.int_label) + '.M'][tdx,:] ))
Ml = R0.transposed()@M
obj.rotation_quaternion = (-Ml).to_track_quat('-Z', 'Y')
# FIXME: This often results in very large objects!
obj.scale = Vector(( Ml.magnitude, Ml.magnitude, 1.0 ))
except IndexError:
if tdx >= nc.variables['elem.couple.' + str(elem.int_label) + '.M'].shape[0]:
pass # we're requesting a value of the
# couple beyond the last timestep
else:
raise
else:
pass
pass
# -----------------------------------------------------------
# end of update_structural_couple() function