forked from EmGi96/TrailPrint3D
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexport.py
More file actions
367 lines (290 loc) · 12.1 KB
/
Copy pathexport.py
File metadata and controls
367 lines (290 loc) · 12.1 KB
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
# Copyright (C) 2026 EmGi
# You are free to modify it under the terms of the GNU General Public License as published by the Free Software Foundation.
# You are free to use any models Generated by this Addon Commercially
import bpy # type: ignore
import os
import tempfile
from mathutils import Vector # type: ignore
try:
from bl_ext.blender_org.ThreeMF_io.api import export_3mf
from bl_ext.blender_org.ThreeMF_io.api import is_available
except ImportError:
export_3mf = None
is_available = None
from . import progress as _progress
from . import addon_preferences
from . import temp
def export_to_STL(zobj, force="STL"):
exportPath = bpy.context.scene.tp3d.get('export_path', None)
if not exportPath:
exportPath = addon_preferences.get_prefs().default_export_folder
bpy.ops.object.select_all(action='DESELECT')
zobj.select_set(True)
bpy.context.view_layer.objects.active = zobj
if zobj.material_slots and force != "STL":
bpy.ops.wm.obj_export(filepath=exportPath + zobj.name + ".obj",
export_selected_objects=True,
export_triangulated_mesh=True,
apply_modifiers=True,
export_materials=True,
forward_axis="Y",
up_axis="Z",
)
else:
bpy.ops.wm.stl_export(filepath=exportPath + zobj.name + ".stl", export_selected_objects=True)
zobj.select_set(False) # Select the object
def export_selected_to_STL(force="STL"):
from .utils import show_message_box
exportPath = bpy.context.scene.tp3d.get('export_path', None)
if not exportPath:
exportPath = addon_preferences.get_prefs().default_export_folder
selected_objects = bpy.context.selected_objects
active_obj = bpy.context.active_object
if not selected_objects:
show_message_box("No objects selected")
return{'FINISHED'}
for zobj in selected_objects:
bpy.ops.object.select_all(action='DESELECT')
zobj.select_set(True)
bpy.context.view_layer.objects.active = zobj
if (zobj.material_slots or force == "OBJ") and force != "STL":
bpy.ops.wm.obj_export(filepath=exportPath + zobj.name + ".obj",
export_selected_objects=True,
export_triangulated_mesh=True,
apply_modifiers=True,
export_materials=True,
forward_axis="Y",
up_axis="Z",
)
#show_message_box("File Exported as OBJ because it contains Materials","INFO","OBJ File Exported")
_progress.WarningsOverlay.add_warning("Exported as OBJ", "ok")
else:
bpy.ops.wm.stl_export(filepath=exportPath + zobj.name + ".stl", export_selected_objects=True)
_progress.WarningsOverlay.add_warning("Exported as STL", "ok")
bpy.ops.object.select_all(action='DESELECT')
for zobj in selected_objects:
zobj.select_set(True)
bpy.context.view_layer.objects.active = active_obj
active_obj = bpy.context.active_object
def export_selected_to_3mf():
from .utils import show_message_box
exportPath = bpy.context.scene.tp3d.get('export_path', "")
if not exportPath:
exportPath = addon_preferences.get_prefs().default_export_folder
selected_objects = bpy.context.selected_objects
active_obj = bpy.context.active_object
if not selected_objects:
show_message_box("No objects selected")
return {'FINISHED'}
# 1. Selection & Duplication (to avoid messing up the original scene)
# Note: We duplicate BEFORE generating the thumbnail so the thumbnail
# shows exactly what is being exported at 0,0,0
# Collect selected objects + all their children recursively
all_to_export = list(selected_objects)
for obj in selected_objects:
for child in obj.children_recursive:
if child not in all_to_export:
all_to_export.append(child)
# Duplicate via data API — works regardless of visibility or collection state
original_to_dup = {}
duplicates = []
scene_col = bpy.context.scene.collection
for obj in all_to_export:
dup = obj.copy()
dup.data = obj.data.copy() if obj.data else None
scene_col.objects.link(dup)
original_to_dup[obj] = dup
duplicates.append(dup)
print(f"Object to Export: {obj.name}")
# Re-establish parent relationships among duplicates
for orig, dup in original_to_dup.items():
if orig.parent in original_to_dup:
dup.parent = original_to_dup[orig.parent]
dup.matrix_parent_inverse = orig.matrix_parent_inverse.copy()
else:
dup.parent = None
dup.matrix_world = orig.matrix_world.copy()
center = get_selection_center(duplicates)
offset = Vector((-center.x, -center.y, -center.z))
for obj in duplicates:
#if not obj.parent: # Only move the 'roots' to keep hierarchy intact
obj.location += offset
# Convert any curve objects to mesh (3mf exporter doesn't support curves)
for obj in duplicates:
if obj.type == 'CURVE':
bpy.ops.object.select_all(action='DESELECT')
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
bpy.ops.object.convert(target='MESH')
# 2. Sort duplicates into groups based on "ExportGroup"
groups = {} # Key: ID, Value: List of Objs
ungrouped = []
for obj in duplicates:
group_id = obj.get("ExportGroup", 0)
if group_id > 0:
if group_id not in groups:
groups[group_id] = []
groups[group_id].append(obj)
else:
ungrouped.append(obj)
GROUP_NAMES = ["Map", "Plate"]
# 3. Create Empties for Groups and center everything
export_roots = [] # These are the "Top Level" objects the exporter will see
temp_empties = [] # Track empties so we can delete them in cleanup
# Handle Grouped Objects
for idx, (g_id, members) in enumerate(sorted(groups.items())):
# If only one member, no need for a group empty — add it directly
if len(members) == 1:
export_roots.append(members[0])
continue
group_name = GROUP_NAMES[idx] if idx < len(GROUP_NAMES) else f"Group_{g_id}"
empty = bpy.data.objects.new(group_name, None)
bpy.context.collection.objects.link(empty)
temp_empties.append(empty)
export_roots.append(empty)
for member in members:
member.parent = empty
# If you want the individual parts to also reset to 0 relative to the group:
# member.location = (0,0,0)
# Handle Ungrouped Objects
for obj in ungrouped:
#obj.location = (0, 0, 0)
export_roots.append(obj)
# 4. Thumbnail & Export
# Reselect ONLY our new hierarchy for the thumbnail and exporter
bpy.ops.object.select_all(action='DESELECT')
for root in export_roots:
root.select_set(True)
# We also need to select children for the API 'use_selection' to see them
for child in root.children_recursive:
child.select_set(True)
thumbnail_path = os.path.join(tempfile.gettempdir(), "tp3d_thumbnail.png")
# Call your custom thumbnail function on the centered duplicates
customThumbnail(bpy.context.selected_objects, thumbnail_path)
full_path = exportPath + bpy.context.scene.tp3d.modelname + ".3mf"
if export_3mf is None:
_progress.WarningsOverlay.add_warning("3MF Addon not installed", "error")
return
try:
result = export_3mf(
filepath=full_path,
use_selection=True,
use_mesh_modifiers=True,
global_scale=0.001,
coordinate_precision=4,
thumbnail_mode="CUSTOM",
thumbnail_resolution=256,
thumbnail_image=thumbnail_path
)
print(f"Successfully exported to: {full_path}")
_progress.WarningsOverlay.add_warning("Exported as 3mf", "ok")
except Exception as e:
print(f"Export Error: {e}")
_progress.WarningsOverlay.add_warning("Exporting as 3mf Failed", "error")
# 5. Cleanup (Delete the duplicates and temporary empties)
# Use the data API directly — not affected by selection state or context
for obj in duplicates + temp_empties:
if obj is None:
continue
for col in obj.users_collection:
pass
col.objects.unlink(obj)
bpy.data.objects.remove(obj)
return {'FINISHED'}
def customThumbnail(objects, output_path, resolution=256):
scene = bpy.context.scene
# 1. Setup Render Resolution
orig_x = scene.render.resolution_x
orig_y = scene.render.resolution_y
scene.render.resolution_x = resolution
scene.render.resolution_y = resolution
scene.render.resolution_percentage = 100
# 2. Find 3D View (Crucial for saving state)
area = next((a for a in bpy.context.screen.areas if a.type == 'VIEW_3D'), None)
if not area:
return # Safety exit
space = area.spaces.active
rv3d = space.region_3d
# 3. SAVE INITIAL STATE (Pixel-perfect)
old_camera = scene.camera
old_shading = space.shading.type
old_overlay = space.overlay.show_overlays
old_view_matrix = rv3d.view_matrix.copy() # Saves rotation/zoom
old_perspective = rv3d.view_perspective
# 4. Setup Temporary Camera
tmp_cam_data = bpy.data.cameras.new("TempTopCam")
tmp_cam_data.type = 'ORTHO'
tmp_cam_obj = bpy.data.objects.new("TempTopCam", tmp_cam_data)
scene.collection.objects.link(tmp_cam_obj)
# Position: High up, looking straight down
tmp_cam_obj.location = (0, 0, 100)
tmp_cam_obj.rotation_euler = (0, 0, 0)
scene.camera = tmp_cam_obj
# 5. Set Viewport for Render
space.shading.type = 'MATERIAL'
space.overlay.show_overlays = False
# 6. Selection & Framing
bpy.ops.object.select_all(action='DESELECT')
for obj in objects:
obj.select_set(True)
# 7. Execute Render with Override
with bpy.context.temp_override(area=area, region=area.regions[-1]):
# Snap view to the temp camera
rv3d.view_perspective = 'CAMERA'
# Zoom camera to fit objects
bpy.ops.view3d.camera_to_view_selected()
# Render the viewport
scene.render.filepath = output_path
bpy.ops.render.opengl(write_still=True, view_context=True)
# 8. RESTORE INITIAL STATE
scene.camera = old_camera
space.shading.type = old_shading
space.overlay.show_overlays = old_overlay
# Use the saved matrix to teleport the view back
rv3d.view_matrix = old_view_matrix
rv3d.view_perspective = old_perspective
# Update resolution
scene.render.resolution_x = orig_x
scene.render.resolution_y = orig_y
# Cleanup camera data
bpy.data.objects.remove(tmp_cam_obj, do_unlink=True)
bpy.data.cameras.remove(tmp_cam_data, do_unlink=True)
def get_selection_center(objects):
if not objects:
return Vector((0, 0, 0))
all_coords = []
for obj in objects:
# Get all 8 corners of the bounding box in World Space
# matrix_world @ corner converts local box to world position
bbox_corners = [obj.matrix_world @ Vector(corner) for corner in obj.bound_box]
all_coords.extend(bbox_corners)
# Find the min and max for each axis across ALL objects
min_x = min(c.x for c in all_coords)
max_x = max(c.x for c in all_coords)
min_y = min(c.y for c in all_coords)
max_y = max(c.y for c in all_coords)
min_z = min(c.z for c in all_coords)
center = Vector((
(min_x + max_x) / 2,
(min_y + max_y) / 2,
min_z,
))
return center
def is_3mf_extension_installed():
#is_installed, is_enabled = addon_utils.check("bl_ext.blender_org.ThreeMF_io")
if is_available is None:
temp.has3mf = False
return False
is_en = is_available()
#has_ex = has_capability("global_scale")
#print(f"has Capability: {has_ex}")
temp.has3mf = is_en
return is_en
#Install 3mf Addon
def install_3mf_extension():
try:
bpy.ops.extensions.package_install(package_id="ThreeMF_io")
return True
except Exception as e:
print(f"Installation failed: {e}")
return False