瀏覽代碼

Delete GCODE_EXPORT.PY

0000OOOO0000 5 年之前
父節點
當前提交
58ca202e17
沒有帳戶連結到提交者的電子郵件

+ 0
- 488
◯ᴥᗱᗴᗝИNᗱᗴᙁ⚭ⵙ⚭ᙁᗱᗴИNᗝᗱᗴᴥ◯/2.90/SCRIPTS/ADDONS/TISSUE-MASTER/GCODE_EXPORT.PY 查看文件

@@ -1,488 +0,0 @@
1
-import bpy, os
2
-import numpy as np
3
-import mathutils
4
-from mathutils import Vector
5
-from math import pi
6
-from bpy.types import (
7
-        Operator,
8
-        Panel,
9
-        PropertyGroup,
10
-        )
11
-from bpy.props import (
12
-        BoolProperty,
13
-        EnumProperty,
14
-        FloatProperty,
15
-        IntProperty,
16
-        StringProperty,
17
-        PointerProperty
18
-        )
19
-from .utils import *
20
-
21
-def change_speed_mode(self, context):
22
-    props = context.scene.tissue_gcode
23
-    if props.previous_speed_mode != props.speed_mode:
24
-        if props.speed_mode == 'SPEED':
25
-            props.speed = props.feed/60
26
-            props.speed_vertical = props.feed_vertical/60
27
-            props.speed_horizontal = props.feed_horizontal/60
28
-        else:
29
-            props.feed = props.speed*60
30
-            props.feed_vertical = props.speed_vertical*60
31
-            props.feed_horizontal = props.speed_horizontal*60
32
-    props.previous_speed_mode == props.speed_mode
33
-    return
34
-
35
-class tissue_gcode_prop(PropertyGroup):
36
-    last_e : FloatProperty(name="Pull", default=5.0, min=0, soft_max=10)
37
-    path_length : FloatProperty(name="Pull", default=5.0, min=0, soft_max=10)
38
-
39
-    folder : StringProperty(
40
-        name="File", default="", subtype='FILE_PATH',
41
-        description = 'Destination folder.\nIf missing, the file folder will be used'
42
-        )
43
-    pull : FloatProperty(
44
-        name="Pull", default=5.0, min=0, soft_max=10,
45
-        description='Pull material before lift'
46
-        )
47
-    push : FloatProperty(
48
-        name="Push", default=5.0, min=0, soft_max=10,
49
-        description='Push material before start extruding'
50
-        )
51
-    dz : FloatProperty(
52
-        name="dz", default=2.0, min=0, soft_max=20,
53
-        description='Z movement for lifting the nozzle before travel'
54
-        )
55
-    flow_mult : FloatProperty(
56
-        name="Flow Mult", default=1.0, min=0, soft_max=3,
57
-        description = 'Flow multiplier.\nUse a single value or a list of values for changing it during the printing path'
58
-        )
59
-    feed : IntProperty(
60
-        name="Feed Rate (F)", default=3600, min=0, soft_max=20000,
61
-        description='Printing speed'
62
-        )
63
-    feed_horizontal : IntProperty(
64
-        name="Feed Horizontal", default=7200, min=0, soft_max=20000,
65
-        description='Travel speed'
66
-        )
67
-    feed_vertical : IntProperty(
68
-        name="Feed Vertical", default=3600, min=0, soft_max=20000,
69
-        description='Lift movements speed'
70
-        )
71
-
72
-    speed : IntProperty(
73
-        name="Speed", default=60, min=0, soft_max=100,
74
-        description='Printing speed'
75
-        )
76
-    speed_horizontal : IntProperty(
77
-        name="Travel", default=120, min=0, soft_max=200,
78
-        description='Travel speed'
79
-        )
80
-    speed_vertical : IntProperty(
81
-        name="Z-Lift", default=60, min=0, soft_max=200,
82
-        description='Lift movements speed'
83
-        )
84
-
85
-    esteps : FloatProperty(
86
-        name="E Steps/Unit", default=5, min=0, soft_max=100)
87
-    start_code : StringProperty(
88
-        name="Start", default='', description = 'Text block for starting code'
89
-        )
90
-    end_code : StringProperty(
91
-        name="End", default='', description = 'Text block for ending code'
92
-        )
93
-    auto_sort_layers : BoolProperty(
94
-        name="Auto Sort Layers", default=True,
95
-        description = 'Sort layers according to the Z of the median point'
96
-        )
97
-    auto_sort_points : BoolProperty(
98
-        name="Auto Sort Points", default=False,
99
-        description = 'Shift layer points trying to automatically reduce needed travel movements'
100
-        )
101
-    close_all : BoolProperty(
102
-        name="Close Shapes", default=False,
103
-        description = 'Repeat the starting point at the end of the vertices list for each layer'
104
-        )
105
-    nozzle : FloatProperty(
106
-        name="Nozzle", default=0.4, min=0, soft_max=10,
107
-        description='Nozzle diameter'
108
-        )
109
-    layer_height : FloatProperty(
110
-        name="Layer Height", default=0.1, min=0, soft_max=10,
111
-        description = 'Average layer height, needed for a correct extrusion'
112
-        )
113
-    filament : FloatProperty(
114
-        name="Filament (\u03A6)", default=1.75, min=0, soft_max=120,
115
-        description='Filament (or material container) diameter'
116
-        )
117
-
118
-    gcode_mode : EnumProperty(items=[
119
-            ("CONT", "Continuous", ""),
120
-            ("RETR", "Retraction", "")
121
-        ], default='CONT', name="Mode",
122
-        description = 'If retraction is used, then each separated list of vertices\nwill be considered as a different layer'
123
-        )
124
-    speed_mode : EnumProperty(items=[
125
-            ("SPEED", "Speed (mm/s)", ""),
126
-            ("FEED", "Feed (mm/min)", "")
127
-        ], default='SPEED', name="Speed Mode",
128
-        description = 'Speed control mode',
129
-        update = change_speed_mode
130
-        )
131
-    previous_speed_mode : StringProperty(
132
-        name="previous_speed_mode", default='', description = ''
133
-        )
134
-    retraction_mode : EnumProperty(items=[
135
-            ("FIRMWARE", "Firmware", ""),
136
-            ("GCODE", "Gcode", "")
137
-        ], default='GCODE', name="Retraction Mode",
138
-        description = 'If firmware retraction is used, then the retraction parameters will be controlled by the printer'
139
-        )
140
-    animate : BoolProperty(
141
-        name="Animate", default=False,
142
-        description = 'Show print progression according to current frame'
143
-        )
144
-
145
-
146
-class TISSUE_PT_gcode_exporter(Panel):
147
-    bl_category = "Tissue Gcode"
148
-    bl_space_type = "VIEW_3D"
149
-    bl_region_type = "UI"
150
-    #bl_space_type = 'PROPERTIES'
151
-    #bl_region_type = 'WINDOW'
152
-    #bl_context = "data"
153
-    bl_label = "Tissue Gcode Export"
154
-    #bl_options = {'DEFAULT_CLOSED'}
155
-
156
-    @classmethod
157
-    def poll(cls, context):
158
-        try: return context.object.type in ('CURVE','MESH')
159
-        except: return False
160
-
161
-    def draw(self, context):
162
-        props = context.scene.tissue_gcode
163
-
164
-        #addon = context.user_preferences.addons.get(sverchok.__name__)
165
-        #over_sized_buttons = addon.preferences.over_sized_buttons
166
-        layout = self.layout
167
-        col = layout.column(align=True)
168
-        row = col.row()
169
-        row.prop(props, 'folder', toggle=True, text='')
170
-        col = layout.column(align=True)
171
-        row = col.row()
172
-        row.prop(props, 'gcode_mode', expand=True, toggle=True)
173
-        #col = layout.column(align=True)
174
-        col = layout.column(align=True)
175
-        col.label(text="Extrusion:", icon='MOD_FLUIDSIM')
176
-        #col.prop(self, 'esteps')
177
-        col.prop(props, 'filament')
178
-        col.prop(props, 'nozzle')
179
-        col.prop(props, 'layer_height')
180
-        col.separator()
181
-        col.label(text="Speed (Feed Rate F):", icon='DRIVER')
182
-        col.prop(props, 'speed_mode', text='')
183
-        speed_prefix = 'feed' if props.speed_mode == 'FEED' else 'speed'
184
-        col.prop(props, speed_prefix, text='Print')
185
-        if props.gcode_mode == 'RETR':
186
-            col.prop(props, speed_prefix + '_vertical', text='Z Lift')
187
-            col.prop(props, speed_prefix + '_horizontal', text='Travel')
188
-        col.separator()
189
-        if props.gcode_mode == 'RETR':
190
-            col = layout.column(align=True)
191
-            col.label(text="Retraction Mode:", icon='NOCURVE')
192
-            row = col.row()
193
-            row.prop(props, 'retraction_mode', expand=True, toggle=True)
194
-            if props.retraction_mode == 'GCODE':
195
-                col.separator()
196
-                col.label(text="Retraction:", icon='PREFERENCES')
197
-                col.prop(props, 'pull', text='Retraction')
198
-                col.prop(props, 'dz', text='Z Hop')
199
-                col.prop(props, 'push', text='Preload')
200
-                col.separator()
201
-            #col.label(text="Layers options:", icon='ALIGN_JUSTIFY')
202
-        col.separator()
203
-        col.prop(props, 'auto_sort_layers', text="Sort Layers (Z)")
204
-        col.prop(props, 'auto_sort_points', text="Sort Points (XY)")
205
-        #col.prop(props, 'close_all')
206
-        col.separator()
207
-        col.label(text='Custom Code:', icon='TEXT')
208
-        col.prop_search(props, 'start_code', bpy.data, 'texts')
209
-        col.prop_search(props, 'end_code', bpy.data, 'texts')
210
-        col.separator()
211
-        row = col.row(align=True)
212
-        row.scale_y = 2.0
213
-        row.operator('scene.tissue_gcode_export')
214
-        #col.separator()
215
-        #col.prop(props, 'animate', icon='TIME')
216
-
217
-
218
-class tissue_gcode_export(Operator):
219
-    bl_idname = "scene.tissue_gcode_export"
220
-    bl_label = "Export Gcode"
221
-    bl_description = ("Export selected curve object as Gcode file")
222
-    bl_options = {'REGISTER', 'UNDO'}
223
-
224
-    @classmethod
225
-    def poll(cls, context):
226
-        try:
227
-            return context.object.type in ('CURVE', 'MESH')
228
-        except:
229
-            return False
230
-
231
-    def execute(self, context):
232
-        scene = context.scene
233
-        props = scene.tissue_gcode
234
-        # manage data
235
-        if props.speed_mode == 'SPEED':
236
-            props.feed = props.speed*60
237
-            props.feed_vertical = props.speed_vertical*60
238
-            props.feed_horizontal = props.speed_horizontal*60
239
-        feed = props.feed
240
-        feed_v = props.feed_vertical
241
-        feed_h = props.feed_horizontal
242
-        layer = props.layer_height
243
-        flow_mult = props.flow_mult
244
-        #if context.object.type != 'CURVE':
245
-        #    self.report({'ERROR'}, 'Please select a Curve object')
246
-        #    return {'CANCELLED'}
247
-        ob = context.object
248
-        matr = ob.matrix_world
249
-        if ob.type == 'MESH':
250
-            dg = context.evaluated_depsgraph_get()
251
-            mesh = ob.evaluated_get(dg).data
252
-            edges = [list(e.vertices) for e in mesh.edges]
253
-            verts = [v.co for v in mesh.vertices]
254
-            ordered_verts = find_curves(edges, len(mesh.vertices))
255
-            ob = curve_from_pydata(verts, ordered_verts, name='__temp_curve__', merge_distance=0.1, set_active=False)
256
-
257
-        vertices = [[matr @ p.co.xyz for p in s.points] for s in ob.data.splines]
258
-        cyclic_u = [s.use_cyclic_u for s in ob.data.splines]
259
-
260
-        if ob.name == '__temp_curve__': bpy.data.objects.remove(ob)
261
-
262
-        if len(vertices) == 1: props.gcode_mode = 'CONT'
263
-        export = True
264
-
265
-        # open file
266
-        if(export):
267
-            if props.folder == '':
268
-                folder = '//' + os.path.splitext(bpy.path.basename(bpy.context.blend_data.filepath))[0]
269
-            else:
270
-                folder = props.folder
271
-            if '.gcode' not in folder: folder += '.gcode'
272
-            path = bpy.path.abspath(folder)
273
-            file = open(path, 'w')
274
-            try:
275
-                for line in bpy.data.texts[props.start_code].lines:
276
-                    file.write(line.body + '\n')
277
-            except:
278
-                pass
279
-
280
-        #if props.gcode_mode == 'RETR':
281
-
282
-        # sort layers (Z)
283
-        if props.auto_sort_layers:
284
-            sorted_verts = []
285
-            for curve in vertices:
286
-                # mean z
287
-                listz = [v[2] for v in curve]
288
-                meanz = np.mean(listz)
289
-                # store curve and meanz
290
-                sorted_verts.append((curve, meanz))
291
-            vertices = [data[0] for data in sorted(sorted_verts, key=lambda height: height[1])]
292
-
293
-        # sort vertices (XY)
294
-        if props.auto_sort_points:
295
-            # curves median point
296
-            median_points = [np.mean(verts,axis=0) for verts in vertices]
297
-
298
-            # chose starting point for each curve
299
-            for j, curve in enumerate(vertices):
300
-                # for closed curves finds the best starting point
301
-                if cyclic_u[j]:
302
-                    # create kd tree
303
-                    kd = mathutils.kdtree.KDTree(len(curve))
304
-                    for i, v in enumerate(curve):
305
-                        kd.insert(v, i)
306
-                    kd.balance()
307
-
308
-                    if props.gcode_mode == 'RETR':
309
-                        if j==0:
310
-                            # close to next two curves median point
311
-                            co_find = np.mean(median_points[j+1:j+3],axis=0)
312
-                        elif j < len(vertices)-1:
313
-                            co_find = np.mean([median_points[j-1],median_points[j+1]],axis=0)
314
-                        else:
315
-                            co_find = np.mean(median_points[j-2:j],axis=0)
316
-                        #flow_mult[j] = flow_mult[j][index:]+flow_mult[j][:index]
317
-                        #layer[j] = layer[j][index:]+layer[j][:index]
318
-                    else:
319
-                        if j==0:
320
-                            # close to next two curves median point
321
-                            co_find = np.mean(median_points[j+1:j+3],axis=0)
322
-                        else:
323
-                            co_find = vertices[j-1][-1]
324
-                    co, index, dist = kd.find(co_find)
325
-                    vertices[j] = vertices[j][index:]+vertices[j][:index+1]
326
-                else:
327
-                    if j > 0:
328
-                        p0 = curve[0]
329
-                        p1 = curve[-1]
330
-                        last = vertices[j-1][-1]
331
-                        d0 = (last-p0).length
332
-                        d1 = (last-p1).length
333
-                        if d1 < d0: vertices[j].reverse()
334
-
335
-
336
-
337
-            '''
338
-            #  close shapes
339
-            if props.close_all:
340
-                for i in range(len(vertices)):
341
-                    vertices[i].append(vertices[i][0])
342
-                    #flow_mult[i].append(flow_mult[i][0])
343
-                    #layer[i].append(layer[i][0])
344
-            '''
345
-        # calc bounding box
346
-        min_corner = np.min(vertices[0],axis=0)
347
-        max_corner = np.max(vertices[0],axis=0)
348
-        for i in range(1,len(vertices)):
349
-            eval_points = vertices[i] + [min_corner]
350
-            min_corner = np.min(eval_points,axis=0)
351
-            eval_points = vertices[i] + [max_corner]
352
-            max_corner = np.max(eval_points,axis=0)
353
-
354
-        # initialize variables
355
-        e = 0
356
-        last_vert = Vector((0,0,0))
357
-        maxz = 0
358
-        path_length = 0
359
-        travel_length = 0
360
-
361
-        printed_verts = []
362
-        printed_edges = []
363
-        travel_verts = []
364
-        travel_edges = []
365
-
366
-        # write movements
367
-        for i in range(len(vertices)):
368
-            curve = vertices[i]
369
-            first_id = len(printed_verts)
370
-            for j in range(len(curve)):
371
-                v = curve[j]
372
-                v_flow_mult = flow_mult#[i][j]
373
-                v_layer = layer#[i][j]
374
-
375
-                # record max z
376
-                maxz = np.max((maxz,v[2]))
377
-                #maxz = max(maxz,v[2])
378
-
379
-                # first point of the gcode
380
-                if i == j == 0:
381
-                    printed_verts.append(v)
382
-                    if(export):
383
-                        file.write('G92 E0 \n')
384
-                        params = v[:3] + (feed,)
385
-                        to_write = 'G1 X{0:.4f} Y{1:.4f} Z{2:.4f} F{3:.0f}\n'.format(*params)
386
-                        file.write(to_write)
387
-                else:
388
-                    # start after retraction
389
-                    if j == 0 and props.gcode_mode == 'RETR':
390
-                        if(export):
391
-                            params = v[:2] + (maxz+props.dz,) + (feed_h,)
392
-                            to_write = 'G1 X{0:.4f} Y{1:.4f} Z{2:.4f} F{3:.0f}\n'.format(*params)
393
-                            file.write(to_write)
394
-                            params = v[:3] + (feed_v,)
395
-                            to_write = 'G1 X{0:.4f} Y{1:.4f} Z{2:.4f} F{3:.0f}\n'.format(*params)
396
-                            file.write(to_write)
397
-                            to_write = 'G1 F{:.0f}\n'.format(feed)
398
-                            file.write(to_write)
399
-                            if props.retraction_mode == 'GCODE':
400
-                                e += props.push
401
-                                file.write( 'G1 E' + format(e, '.4f') + '\n')
402
-                            else:
403
-                                file.write('G11\n')
404
-                        printed_verts.append((v[0], v[1], maxz+props.dz))
405
-                        travel_edges.append((len(printed_verts)-1, len(printed_verts)-2))
406
-                        travel_length += (Vector(printed_verts[-1])-Vector(printed_verts[-2])).length
407
-                        printed_verts.append(v)
408
-                        travel_edges.append((len(printed_verts)-1, len(printed_verts)-2))
409
-                        travel_length += maxz+props.dz - v[2]
410
-                    # regular extrusion
411
-                    else:
412
-                        printed_verts.append(v)
413
-                        v1 = Vector(v)
414
-                        v0 = Vector(curve[j-1])
415
-                        dist = (v1-v0).length
416
-                        area = v_layer * props.nozzle + pi*(v_layer/2)**2 # rectangle + circle
417
-                        cylinder = pi*(props.filament/2)**2
418
-                        flow = area / cylinder * (0 if j == 0 else 1)
419
-                        e += dist * v_flow_mult * flow
420
-                        params = v[:3] + (e,)
421
-                        if(export):
422
-                            to_write = 'G1 X{0:.4f} Y{1:.4f} Z{2:.4f} E{3:.4f}\n'.format(*params)
423
-                            file.write(to_write)
424
-                        path_length += dist
425
-                        printed_edges.append([len(printed_verts)-1, len(printed_verts)-2])
426
-            if props.gcode_mode == 'RETR':
427
-                v0 = Vector(curve[-1])
428
-                if props.close_all and False:
429
-                    #printed_verts.append(v0)
430
-                    printed_edges.append([len(printed_verts)-1, first_id])
431
-
432
-                    v1 = Vector(curve[0])
433
-                    dist = (v0-v1).length
434
-                    area = v_layer * props.nozzle + pi*(v_layer/2)**2 # rectangle + circle
435
-                    cylinder = pi*(props.filament/2)**2
436
-                    flow = area / cylinder
437
-                    e += dist * v_flow_mult * flow
438
-                    params = v1[:3] + (e,)
439
-                    if(export):
440
-                        to_write = 'G1 X{0:.4f} Y{1:.4f} Z{2:.4f} E{3:.4f}\n'.format(*params)
441
-                        file.write(to_write)
442
-                    path_length += dist
443
-                    v0 = v1
444
-                if i < len(vertices)-1:
445
-                    if(export):
446
-                        if props.retraction_mode == 'GCODE':
447
-                            e -= props.pull
448
-                            file.write('G0 E' + format(e, '.4f') + '\n')
449
-                        else:
450
-                            file.write('G10\n')
451
-                        params = v0[:2] + (maxz+props.dz,) + (feed_v,)
452
-                        to_write = 'G1 X{0:.4f} Y{1:.4f} Z{2:.4f} F{3:.0f}\n'.format(*params)
453
-                        file.write(to_write)
454
-                    printed_verts.append(v0.to_tuple())
455
-                    printed_verts.append((v0.x, v0.y, maxz+props.dz))
456
-                    travel_edges.append((len(printed_verts)-1, len(printed_verts)-2))
457
-                    travel_length += maxz+props.dz - v0.z
458
-        if(export):
459
-            # end code
460
-            try:
461
-                for line in bpy.data.texts[props.end_code].lines:
462
-                    file.write(line.body + '\n')
463
-            except:
464
-                pass
465
-            file.close()
466
-            print("Saved gcode to " + path)
467
-        bb = list(min_corner) + list(max_corner)
468
-        info = 'Bounding Box:\n'
469
-        info += '\tmin\tX: {0:.1f}\tY: {1:.1f}\tZ: {2:.1f}\n'.format(*bb)
470
-        info += '\tmax\tX: {3:.1f}\tY: {4:.1f}\tZ: {5:.1f}\n'.format(*bb)
471
-        info += 'Extruded Filament: ' + format(e, '.2f') + '\n'
472
-        info += 'Extruded Volume: ' + format(e*pi*(props.filament/2)**2, '.2f') + '\n'
473
-        info += 'Printed Path Length: ' + format(path_length, '.2f') + '\n'
474
-        info += 'Travel Length: ' + format(travel_length, '.2f')
475
-        '''
476
-        # animate
477
-        if scene.animate:
478
-            scene = bpy.context.scene
479
-            try:
480
-                param = (scene.frame_current - scene.frame_start)/(scene.frame_end - scene.frame_start)
481
-            except:
482
-                param = 1
483
-            last_vert = max(int(param*len(printed_verts)),1)
484
-            printed_verts = printed_verts[:last_vert]
485
-            printed_edges = [e for e in printed_edges if e[0] < last_vert and e[1] < last_vert]
486
-            travel_edges = [e for e in travel_edges if e[0] < last_vert and e[1] < last_vert]
487
-        '''
488
-        return {'FINISHED'}