forked from jdlubrano/cad_volume
-
Notifications
You must be signed in to change notification settings - Fork 0
/
volume.py
247 lines (203 loc) · 7.45 KB
/
volume.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
# coding=utf-8
import getopt
import json
import math
import pdb
import sys
from OCC.Bnd import Bnd_Box
from OCC.BRepMesh import BRepMesh_IncrementalMesh
from OCC.BRepBndLib import brepbndlib_Add
from OCC.GProp import GProp_GProps
from OCC.gp import *
from OCC.BRepGProp import brepgprop_VolumeProperties
from OCC.BRepAlgoAPI import BRepAlgoAPI_Cut
from OCC.BRepPrimAPI import BRepPrimAPI_MakeCylinder
from OCC.TColStd import TColStd_SequenceOfAsciiString
from OCC.STEPControl import STEPControl_Reader
from OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity
def display_shapes(shapes):
from OCC.Display.SimpleGui import init_display
display, start_display, add_menu, add_function_to_menu = init_display()
[display.DisplayShape(shape, update=True) for shape in shapes]
start_display()
def calculate_bnd_box(bbox):
xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()
x = xmax - xmin
y = ymax - ymin
z = zmax - zmin
return {
'volume': x * y * z,
'x_length': x,
'y_length': y,
'z_length': z,
'x_min': xmin,
'x_max': xmax,
'y_min': ymin,
'y_max': ymax,
'z_min': zmin,
'z_max': zmax
}
def pick_lengths(bounding_box):
lengths = [ i for i in bounding_box.keys() if i.endswith('length') ]
return { key: bounding_box[key] for key in lengths }
def get_longest_dimension(bounding_box):
lengths_only = pick_lengths(bounding_box)
longest = max(pick_lengths(bounding_box).values())
longest_length = lengths_only.keys()[lengths_only.values().index(longest)]
return longest, longest_length[0]
def x_axis(bounding_box):
axis_direction = gp_Dir(gp_XYZ(1,0,0))
axis_origin = gp_Pnt(
bounding_box['x_min'],
(bounding_box['y_min'] + bounding_box['y_max']) / 2,
(bounding_box['z_min'] + bounding_box['z_max']) / 2
)
return gp_Ax2(axis_origin, axis_direction)
def y_axis(bounding_box):
axis_direction = gp_Dir(gp_XYZ(0,1,0))
axis_origin = gp_Pnt(
(bounding_box['x_min'] + bounding_box['x_max']) / 2,
bounding_box['y_min'],
(bounding_box['z_min'] + bounding_box['z_max']) / 2
)
return gp_Ax2(axis_origin, axis_direction)
def z_axis(bounding_box):
axis_direction = gp_Dir(gp_XYZ(0,0,1))
axis_origin = gp_Pnt(
(bounding_box['x_min'] + bounding_box['x_max']) / 2,
(bounding_box['y_min'] + bounding_box['y_max']) / 2,
bounding_box['z_min']
)
return gp_Ax2(axis_origin, axis_direction)
def determine_axis(bounding_box):
l, longest_dimension = get_longest_dimension(bounding_box)
axis = None
if longest_dimension == 'x_length':
axis = x_axis(bounding_box)
elif longest_dimension == 'y_length':
axis = y_axis(bounding_box)
else:
axis = z_axis(bounding_box)
return axis
def get_axis(dimension, bounding_box):
axis_fn = dimension + '_axis'
return globals()[axis_fn](bounding_box)
def cylinder_dict(cylinder, cut, radius, height):
return {
'radius': radius,
'height': height,
'cylinder_volume': calculate_volume(cylinder.Shape()),
'cylinder': cylinder,
'cut': cut,
'cut_vol': calculate_volume(cut.Shape())
}
def min_cylinder(height_dimension, shape, bounding_box):
axis = get_axis(height_dimension, bounding_box)
lengths = pick_lengths(bounding_box)
height_length = height_dimension + '_length'
height = bounding_box[height_length]
radius = max([ value for key, value in lengths.iteritems() if key != height_length ]) / 2
cylinder = BRepPrimAPI_MakeCylinder(axis, radius, height)
cut = BRepAlgoAPI_Cut(shape, cylinder.Shape())
return cylinder_dict(cylinder, cut, radius, height)
def try_min_cylinders(shape, bounding_box):
x = min_cylinder('x', shape, bounding_box)
y = min_cylinder('y', shape, bounding_box)
z = min_cylinder('z', shape, bounding_box)
bounding = [ i for i in [x,y,z] if i['cut_vol'] == 0.0 ]
if bounding:
min_volume = min([ i['cylinder_volume'] for i in bounding ])
min_bounding = [ i for i in bounding if i['cylinder_volume'] == min_volume ]
return min_bounding[0]
else:
return None
def smallest_max_cylinder(shape, bounding_box):
# cylinder with diagonal of smaller face of bounding box
height, longest_dimension = get_longest_dimension(bounding_box)
longest_length = longest_dimension + '_length'
lengths = pick_lengths(bounding_box)
face_sides = [ value for key, value in lengths.iteritems() if key != longest_length ]
radius = math.sqrt(sum([i ** 2 for i in face_sides])) / 2 # diagonal / 2
axis = get_axis(longest_dimension, bounding_box)
cylinder = BRepPrimAPI_MakeCylinder(axis, radius, height)
cut = BRepAlgoAPI_Cut(shape, cylinder.Shape())
return cylinder_dict(cylinder, cut, radius, height)
def calculate_bounding_cylinder(shape, bounding_box):
cylinder = try_min_cylinders(shape, bounding_box)
if cylinder:
return cylinder
else:
return smallest_max_cylinder(shape, bounding_box)
def calculate_volume(shape):
props = GProp_GProps()
brepgprop_VolumeProperties(shape, props)
return props.Mass()
def analyze_file(filename):
step_reader = STEPControl_Reader()
status = step_reader.ReadFile(filename)
result = None
if status == IFSelect_RetDone: # check status
number_of_roots = step_reader.NbRootsForTransfer()
ok = False
i = 1
while i <= number_of_roots and not ok:
ok = step_reader.TransferRoot(i)
i += 1
if (not ok):
return { 'error': 'Failed to find a suitable root for the STEP file' }
number_of_shapes = step_reader.NbShapes()
if (number_of_shapes > 1):
return { 'error': 'Cannot handle more than one shape in a file' }
aResShape = step_reader.Shape(1)
# Units
length = TColStd_SequenceOfAsciiString()
angles = TColStd_SequenceOfAsciiString()
solid_angles = TColStd_SequenceOfAsciiString()
step_reader.FileUnits(length, angles, solid_angles)
# bounding box
bbox = Bnd_Box()
deflection = 0.01
BRepMesh_IncrementalMesh(aResShape, deflection)
brepbndlib_Add(aResShape, bbox)
xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()
bounding_box = calculate_bnd_box(bbox)
bounding_cylinder = calculate_bounding_cylinder(aResShape, bounding_box)
result = {'bounding_box_volume': bounding_box['volume'],
'bounding_box_x_length': bounding_box['x_length'],
'bounding_box_y_length': bounding_box['y_length'],
'bounding_box_z_length': bounding_box['z_length'],
'mesh_volume': calculate_volume(aResShape),
'mesh_surface_area': None,
'cylinder_volume': bounding_cylinder['cylinder_volume'],
'cylinder_diameter': bounding_cylinder['radius'] * 2,
'cylinder_length': bounding_cylinder['height'],
'convex_hull_volume': None,
'euler_number': None,
'units': length.First().ToCString().lower()}
else:
result = { 'error': 'Cannot read file' }
return result
def usage():
print('volume.py -f <inputfile>')
sys.exit(0)
def main(filename):
# try:
# opts, args = getopt.getopt(argv, "hf:", ["file="])
# except getopt.GetoptError:
# usage()
# filename = None
# for opt, arg in opts:
# if opt in ("-f", "--file"):
# filename = arg
if filename != None:
try:
result = analyze_file(filename)
except RuntimeError as e:
result = { 'error': e.message, 'filename': filename }
print(json.dumps(result))
else:
result = { 'error': 'No filename provided' }
print(json.dumps(result))
sys.exit(0)
if __name__ == '__main__':
main("C:\Users\lenovo\Desktop\张工精确项目\图纸\jg.STEP")