Fix T70724: PLY import fails with strings
[blender-addons.git] / io_export_paper_model.py
blob4edbea429db8bed2c4fce85f97c2a05739ccfc2e
1 # -*- coding: utf-8 -*-
2 # This script is Free software. Please share and reuse.
3 # ♡2010-2019 Adam Dominec <adominec@gmail.com>
5 ## Code structure
6 # This file consists of several components, in this order:
7 # * Unfolding and baking
8 # * Export (SVG or PDF)
9 # * User interface
10 # During the unfold process, the mesh is mirrored into a 2D structure: UVFace, UVEdge, UVVertex.
12 bl_info = {
13 "name": "Export Paper Model",
14 "author": "Addam Dominec",
15 "version": (1, 1),
16 "blender": (2, 80, 0),
17 "location": "File > Export > Paper Model",
18 "warning": "",
19 "description": "Export printable net of the active mesh",
20 "category": "Import-Export",
21 "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.6/Py/"
22 "Scripts/Import-Export/Paper_Model"
25 # Task: split into four files (SVG and PDF separately)
26 # does any portion of baking belong into the export module?
27 # sketch out the code for GCODE and two-sided export
29 # TODO:
30 # sanitize the constructors Edge, Face, UVFace so that they don't edit their parent object
31 # The Exporter classes should take parameters as a whole pack, and parse it themselves
32 # remember objects selected before baking (except selected to active)
33 # add 'estimated number of pages' to the export UI
34 # QuickSweepline is very much broken -- it throws GeometryError for all nets > ~15 faces
35 # rotate islands to minimize area -- and change that only if necessary to fill the page size
36 # Sticker.vertices should be of type Vector
38 # check conflicts in island naming and either:
39 # * append a number to the conflicting names or
40 # * enumerate faces uniquely within all islands of the same name (requires a check that both label and abbr. equals)
42 import bpy
43 import bl_operators
44 import bmesh
45 import mathutils as M
46 from re import compile as re_compile
47 from itertools import chain, repeat, product, combinations
48 from math import pi, ceil, asin, atan2
49 import os.path as os_path
51 default_priority_effect = {
52 'CONVEX': 0.5,
53 'CONCAVE': 1,
54 'LENGTH': -0.05
57 global_paper_sizes = [
58 ('USER', "User defined", "User defined paper size"),
59 ('A4', "A4", "International standard paper size"),
60 ('A3', "A3", "International standard paper size"),
61 ('US_LETTER', "Letter", "North American paper size"),
62 ('US_LEGAL', "Legal", "North American paper size")
66 def first_letters(text):
67 """Iterator over the first letter of each word"""
68 for match in first_letters.pattern.finditer(text):
69 yield text[match.start()]
70 first_letters.pattern = re_compile("((?<!\w)\w)|\d")
73 def is_upsidedown_wrong(name):
74 """Tell if the string would get a different meaning if written upside down"""
75 chars = set(name)
76 mistakable = set("69NZMWpbqd")
77 rotatable = set("80oOxXIl").union(mistakable)
78 return chars.issubset(rotatable) and not chars.isdisjoint(mistakable)
81 def pairs(sequence):
82 """Generate consecutive pairs throughout the given sequence; at last, it gives elements last, first."""
83 i = iter(sequence)
84 previous = first = next(i)
85 for this in i:
86 yield previous, this
87 previous = this
88 yield this, first
91 def fitting_matrix(v1, v2):
92 """Get a matrix that rotates v1 to the same direction as v2"""
93 return (1 / v1.length_squared) * M.Matrix((
94 (v1.x*v2.x + v1.y*v2.y, v1.y*v2.x - v1.x*v2.y),
95 (v1.x*v2.y - v1.y*v2.x, v1.x*v2.x + v1.y*v2.y)))
98 def z_up_matrix(n):
99 """Get a rotation matrix that aligns given vector upwards."""
100 b = n.xy.length
101 s = n.length
102 if b > 0:
103 return M.Matrix((
104 (n.x*n.z/(b*s), n.y*n.z/(b*s), -b/s),
105 (-n.y/b, n.x/b, 0),
106 (0, 0, 0)
108 else:
109 # no need for rotation
110 return M.Matrix((
111 (1, 0, 0),
112 (0, (-1 if n.z < 0 else 1), 0),
113 (0, 0, 0)
117 def cage_fit(points, aspect):
118 """Find rotation for a minimum bounding box with a given aspect ratio
119 returns a tuple: rotation angle, box height"""
120 def guesses(polygon):
121 """Yield all tentative extrema of the bounding box height wrt. polygon rotation"""
122 for a, b in pairs(polygon):
123 if a == b:
124 continue
125 direction = (b - a).normalized()
126 sinx, cosx = -direction.y, direction.x
127 rot = M.Matrix(((cosx, -sinx), (sinx, cosx)))
128 rot_polygon = [rot @ p for p in polygon]
129 left, right = [fn(rot_polygon, key=lambda p: p.to_tuple()) for fn in (min, max)]
130 bottom, top = [fn(rot_polygon, key=lambda p: p.yx.to_tuple()) for fn in (min, max)]
131 #print(f"{rot_polygon.index(left)}-{rot_polygon.index(right)}, {rot_polygon.index(bottom)}-{rot_polygon.index(top)}")
132 horz, vert = right - left, top - bottom
133 # solve (rot * a).y == (rot * b).y
134 yield max(aspect * horz.x, vert.y), sinx, cosx
135 # solve (rot * a).x == (rot * b).x
136 yield max(horz.x, aspect * vert.y), -cosx, sinx
137 # solve aspect * (rot * (right - left)).x == (rot * (top - bottom)).y
138 # using substitution t = tan(rot / 2)
139 q = aspect * horz.x - vert.y
140 r = vert.x + aspect * horz.y
141 t = ((r**2 + q**2)**0.5 - r) / q if q != 0 else 0
142 t = -1 / t if abs(t) > 1 else t # pick the positive solution
143 siny, cosy = 2 * t / (1 + t**2), (1 - t**2) / (1 + t**2)
144 rot = M.Matrix(((cosy, -siny), (siny, cosy)))
145 for p in rot_polygon:
146 p[:] = rot @ p # note: this also modifies left, right, bottom, top
147 #print(f"solve {aspect * (right - left).x} == {(top - bottom).y} with aspect = {aspect}")
148 if left.x < right.x and bottom.y < top.y and all(left.x <= p.x <= right.x and bottom.y <= p.y <= top.y for p in rot_polygon):
149 #print(f"yield {max(aspect * (right - left).x, (top - bottom).y)}")
150 yield max(aspect * (right - left).x, (top - bottom).y), sinx*cosy + cosx*siny, cosx*cosy - sinx*siny
151 polygon = [points[i] for i in M.geometry.convex_hull_2d(points)]
152 height, sinx, cosx = min(guesses(polygon))
153 return atan2(sinx, cosx), height
156 def create_blank_image(image_name, dimensions, alpha=1):
157 """Create a new image and assign white color to all its pixels"""
158 image_name = image_name[:64]
159 width, height = int(dimensions.x), int(dimensions.y)
160 image = bpy.data.images.new(image_name, width, height, alpha=True)
161 if image.users > 0:
162 raise UnfoldError(
163 "There is something wrong with the material of the model. "
164 "Please report this on the BlenderArtists forum. Export failed.")
165 image.pixels = [1, 1, 1, alpha] * (width * height)
166 image.file_format = 'PNG'
167 return image
170 class UnfoldError(ValueError):
171 def mesh_select(self):
172 if len(self.args) > 1:
173 elems, bm = self.args[1:3]
174 bpy.context.tool_settings.mesh_select_mode = [bool(elems[key]) for key in ("verts", "edges", "faces")]
175 for elem in chain(bm.verts, bm.edges, bm.faces):
176 elem.select = False
177 for elem in chain(*elems.values()):
178 elem.select_set(True)
179 bmesh.update_edit_mesh(bpy.context.object.data, False, False)
182 class Unfolder:
183 def __init__(self, ob):
184 self.do_create_uvmap = False
185 bm = bmesh.from_edit_mesh(ob.data)
186 self.mesh = Mesh(bm, ob.matrix_world)
187 self.mesh.copy_freestyle_marks(ob.data)
188 self.mesh.check_correct()
190 def __del__(self):
191 if not self.do_create_uvmap:
192 self.mesh.delete_uvmap()
194 def prepare(self, cage_size=None, priority_effect=default_priority_effect, scale=1, limit_by_page=False):
195 """Create the islands of the net"""
196 self.mesh.generate_cuts(cage_size / scale if limit_by_page and cage_size else None, priority_effect)
197 self.mesh.finalize_islands(cage_size or M.Vector((1, 1)))
198 self.mesh.enumerate_islands()
199 self.mesh.save_uv()
201 def copy_island_names(self, island_list):
202 """Copy island label and abbreviation from the best matching island in the list"""
203 orig_islands = [{face.id for face in item.faces} for item in island_list]
204 matching = list()
205 for i, island in enumerate(self.mesh.islands):
206 islfaces = {face.index for face in island.faces}
207 matching.extend((len(islfaces.intersection(item)), i, j) for j, item in enumerate(orig_islands))
208 matching.sort(reverse=True)
209 available_new = [True for island in self.mesh.islands]
210 available_orig = [True for item in island_list]
211 for face_count, i, j in matching:
212 if available_new[i] and available_orig[j]:
213 available_new[i] = available_orig[j] = False
214 self.mesh.islands[i].label = island_list[j].label
215 self.mesh.islands[i].abbreviation = island_list[j].abbreviation
217 def save(self, properties):
218 """Export the document"""
219 # Note about scale: input is directly in blender length
220 # Mesh.scale_islands multiplies everything by a user-defined ratio
221 # exporters (SVG or PDF) multiply everything by 1000 (output in millimeters)
222 Exporter = SVG if properties.file_format == 'SVG' else PDF
223 filepath = properties.filepath
224 extension = properties.file_format.lower()
225 filepath = bpy.path.ensure_ext(filepath, "." + extension)
226 # page size in meters
227 page_size = M.Vector((properties.output_size_x, properties.output_size_y))
228 # printable area size in meters
229 printable_size = page_size - 2 * properties.output_margin * M.Vector((1, 1))
230 unit_scale = bpy.context.scene.unit_settings.scale_length
231 ppm = properties.output_dpi * 100 / 2.54 # pixels per meter
233 # after this call, all dimensions will be in meters
234 self.mesh.scale_islands(unit_scale/properties.scale)
235 if properties.do_create_stickers:
236 self.mesh.generate_stickers(properties.sticker_width, properties.do_create_numbers)
237 elif properties.do_create_numbers:
238 self.mesh.generate_numbers_alone(properties.sticker_width)
240 text_height = properties.sticker_width if (properties.do_create_numbers and len(self.mesh.islands) > 1) else 0
241 # title height must be somewhat larger that text size, glyphs go below the baseline
242 self.mesh.finalize_islands(printable_size, title_height=text_height * 1.2)
243 self.mesh.fit_islands(printable_size)
245 if properties.output_type != 'NONE':
246 # bake an image and save it as a PNG to disk or into memory
247 image_packing = properties.image_packing if properties.file_format == 'SVG' else 'ISLAND_EMBED'
248 use_separate_images = image_packing in ('ISLAND_LINK', 'ISLAND_EMBED')
249 self.mesh.save_uv(cage_size=printable_size, separate_image=use_separate_images)
251 sce = bpy.context.scene
252 rd = sce.render
253 bk = rd.bake
254 # TODO: do we really need all this recollection?
255 recall = rd.engine, sce.cycles.bake_type, sce.cycles.samples, bk.use_selected_to_active, bk.margin, bk.cage_extrusion, bk.use_cage, bk.use_clear
256 rd.engine = 'CYCLES'
257 recall_pass = {p: getattr(bk, f"use_pass_{p}") for p in ('ambient_occlusion', 'color', 'diffuse', 'direct', 'emit', 'glossy', 'indirect', 'subsurface', 'transmission')}
258 for p in recall_pass:
259 setattr(bk, f"use_pass_{p}", (properties.output_type != 'TEXTURE'))
260 lookup = {'TEXTURE': 'DIFFUSE', 'AMBIENT_OCCLUSION': 'AO', 'RENDER': 'COMBINED', 'SELECTED_TO_ACTIVE': 'COMBINED'}
261 sce.cycles.bake_type = lookup[properties.output_type]
262 bk.use_selected_to_active = (properties.output_type == 'SELECTED_TO_ACTIVE')
263 bk.margin, bk.cage_extrusion, bk.use_cage, bk.use_clear = 1, 10, False, False
264 if properties.output_type == 'TEXTURE':
265 bk.use_pass_direct, bk.use_pass_indirect, bk.use_pass_color = False, False, True
266 sce.cycles.samples = 1
267 else:
268 sce.cycles.samples = properties.bake_samples
269 if sce.cycles.bake_type == 'COMBINED':
270 bk.use_pass_direct, bk.use_pass_indirect = True, True
271 bk.use_pass_diffuse, bk.use_pass_glossy, bk.use_pass_transmission, bk.use_pass_subsurface, bk.use_pass_ambient_occlusion, bk.use_pass_emit = True, False, False, True, True, True
273 if image_packing == 'PAGE_LINK':
274 self.mesh.save_image(printable_size * ppm, filepath)
275 elif image_packing == 'ISLAND_LINK':
276 image_dir = filepath[:filepath.rfind(".")]
277 self.mesh.save_separate_images(ppm, image_dir)
278 elif image_packing == 'ISLAND_EMBED':
279 self.mesh.save_separate_images(ppm, filepath, embed=Exporter.encode_image)
281 rd.engine, sce.cycles.bake_type, sce.cycles.samples, bk.use_selected_to_active, bk.margin, bk.cage_extrusion, bk.use_cage, bk.use_clear = recall
282 for p, v in recall_pass.items():
283 setattr(bk, f"use_pass_{p}", v)
285 exporter = Exporter(page_size, properties.style, properties.output_margin, (properties.output_type == 'NONE'), properties.angle_epsilon)
286 exporter.do_create_stickers = properties.do_create_stickers
287 exporter.text_size = properties.sticker_width
288 exporter.write(self.mesh, filepath)
291 class Mesh:
292 """Wrapper for Bpy Mesh"""
294 def __init__(self, bmesh, matrix):
295 self.data = bmesh
296 self.matrix = matrix.to_3x3()
297 self.looptex = bmesh.loops.layers.uv.new("Unfolded")
298 self.edges = {bmedge: Edge(bmedge) for bmedge in bmesh.edges}
299 self.islands = list()
300 self.pages = list()
301 for edge in self.edges.values():
302 edge.choose_main_faces()
303 if edge.main_faces:
304 edge.calculate_angle()
306 def delete_uvmap(self):
307 self.data.loops.layers.uv.remove(self.looptex) if self.looptex else None
309 def copy_freestyle_marks(self, mesh):
310 for bmedge, edge in self.edges.items():
311 edge.freestyle = mesh.edges[bmedge.index].use_freestyle_mark
313 def mark_cuts(self):
314 for bmedge, edge in self.edges.items():
315 if edge.is_main_cut and not bmedge.is_boundary:
316 bmedge.seam = True
318 def check_correct(self, epsilon=1e-6):
319 """Check for invalid geometry"""
320 def is_twisted(face):
321 if len(face.verts) > 3:
322 center = sum((vertex.co for vertex in face.verts), M.Vector((0, 0, 0))) / len(face.verts)
323 plane_d = center.dot(face.normal)
324 diameter = max((center - vertex.co).length for vertex in face.verts)
325 for vertex in face.verts:
326 # check coplanarity
327 if abs(vertex.co.dot(face.normal) - plane_d) > diameter * 0.01:
328 return True
329 return False
331 null_edges = {e for e in self.edges.keys() if e.calc_length() < epsilon and e.link_faces}
332 null_faces = {f for f in self.data.faces if f.calc_area() < epsilon}
333 twisted_faces = {f for f in self.data.faces if is_twisted(f)}
334 if not (null_edges or null_faces or twisted_faces):
335 return
336 disease = [("Remove Doubles", null_edges or null_faces), ("Triangulate", twisted_faces)]
337 cure = " and ".join(s for s, k in disease if k)
338 raise UnfoldError(
339 "The model contains:\n" +
340 (" {} zero-length edge(s)\n".format(len(null_edges)) if null_edges else "") +
341 (" {} zero-area face(s)\n".format(len(null_faces)) if null_faces else "") +
342 (" {} twisted polygon(s)\n".format(len(twisted_faces)) if twisted_faces else "") +
343 "The offenders are selected and you can use {} to fix them. Export failed.".format(cure),
344 {"verts": set(), "edges": null_edges, "faces": null_faces | twisted_faces}, self.data)
346 def generate_cuts(self, page_size, priority_effect):
347 """Cut the mesh so that it can be unfolded to a flat net."""
348 normal_matrix = self.matrix.inverted().transposed()
349 islands = {Island(self, face, self.matrix, normal_matrix) for face in self.data.faces}
350 uvfaces = {face: uvface for island in islands for face, uvface in island.faces.items()}
351 uvedges = {loop: uvedge for island in islands for loop, uvedge in island.edges.items()}
352 for loop, uvedge in uvedges.items():
353 self.edges[loop.edge].uvedges.append(uvedge)
354 # check for edges that are cut permanently
355 edges = [edge for edge in self.edges.values() if not edge.force_cut and edge.main_faces]
357 if edges:
358 average_length = sum(edge.vector.length for edge in edges) / len(edges)
359 for edge in edges:
360 edge.generate_priority(priority_effect, average_length)
361 edges.sort(reverse=False, key=lambda edge: edge.priority)
362 for edge in edges:
363 if not edge.vector:
364 continue
365 edge_a, edge_b = (uvedges[l] for l in edge.main_faces)
366 old_island = join(edge_a, edge_b, size_limit=page_size)
367 if old_island:
368 islands.remove(old_island)
370 self.islands = sorted(islands, reverse=True, key=lambda island: len(island.faces))
372 for edge in self.edges.values():
373 # some edges did not know until now whether their angle is convex or concave
374 if edge.main_faces and (uvfaces[edge.main_faces[0].face].flipped or uvfaces[edge.main_faces[1].face].flipped):
375 edge.calculate_angle()
376 # ensure that the order of faces corresponds to the order of uvedges
377 if edge.main_faces:
378 reordered = [None, None]
379 for uvedge in edge.uvedges:
380 try:
381 index = edge.main_faces.index(uvedge.loop)
382 reordered[index] = uvedge
383 except ValueError:
384 reordered.append(uvedge)
385 edge.uvedges = reordered
387 for island in self.islands:
388 # if the normals are ambiguous, flip them so that there are more convex edges than concave ones
389 if any(uvface.flipped for uvface in island.faces.values()):
390 island_edges = {self.edges[uvedge.edge] for uvedge in island.edges}
391 balance = sum((+1 if edge.angle > 0 else -1) for edge in island_edges if not edge.is_cut(uvedge.uvface.face))
392 if balance < 0:
393 island.is_inside_out = True
395 # construct a linked list from each island's boundary
396 # uvedge.neighbor_right is clockwise = forward = via uvedge.vb if not uvface.flipped
397 neighbor_lookup, conflicts = dict(), dict()
398 for uvedge in island.boundary:
399 uvvertex = uvedge.va if uvedge.uvface.flipped else uvedge.vb
400 if uvvertex not in neighbor_lookup:
401 neighbor_lookup[uvvertex] = uvedge
402 else:
403 if uvvertex not in conflicts:
404 conflicts[uvvertex] = [neighbor_lookup[uvvertex], uvedge]
405 else:
406 conflicts[uvvertex].append(uvedge)
408 for uvedge in island.boundary:
409 uvvertex = uvedge.vb if uvedge.uvface.flipped else uvedge.va
410 if uvvertex not in conflicts:
411 # using the 'get' method so as to handle single-connected vertices properly
412 uvedge.neighbor_right = neighbor_lookup.get(uvvertex, uvedge)
413 uvedge.neighbor_right.neighbor_left = uvedge
414 else:
415 conflicts[uvvertex].append(uvedge)
417 # resolve merged vertices with more boundaries crossing
418 def direction_to_float(vector):
419 return (1 - vector.x/vector.length) if vector.y > 0 else (vector.x/vector.length - 1)
420 for uvvertex, uvedges in conflicts.items():
421 def is_inwards(uvedge):
422 return uvedge.uvface.flipped == (uvedge.va is uvvertex)
424 def uvedge_sortkey(uvedge):
425 if is_inwards(uvedge):
426 return direction_to_float(uvedge.va.co - uvedge.vb.co)
427 else:
428 return direction_to_float(uvedge.vb.co - uvedge.va.co)
430 uvedges.sort(key=uvedge_sortkey)
431 for right, left in (
432 zip(uvedges[:-1:2], uvedges[1::2]) if is_inwards(uvedges[0])
433 else zip([uvedges[-1]] + uvedges[1::2], uvedges[:-1:2])):
434 left.neighbor_right = right
435 right.neighbor_left = left
436 return True
438 def generate_stickers(self, default_width, do_create_numbers=True):
439 """Add sticker faces where they are needed."""
440 def uvedge_priority(uvedge):
441 """Returns whether it is a good idea to stick something on this edge's face"""
442 # TODO: it should take into account overlaps with faces and with other stickers
443 face = uvedge.uvface.face
444 return face.calc_area() / face.calc_perimeter()
446 def add_sticker(uvedge, index, target_uvedge):
447 uvedge.sticker = Sticker(uvedge, default_width, index, target_uvedge)
448 uvedge.uvface.island.add_marker(uvedge.sticker)
450 def is_index_obvious(uvedge, target):
451 if uvedge in (target.neighbor_left, target.neighbor_right):
452 return True
453 if uvedge.neighbor_left.loop.edge is target.neighbor_right.loop.edge and uvedge.neighbor_right.loop.edge is target.neighbor_left.loop.edge:
454 return True
455 return False
457 for edge in self.edges.values():
458 index = None
459 if edge.is_main_cut and len(edge.uvedges) >= 2 and edge.vector.length_squared > 0:
460 target, source = edge.uvedges[:2]
461 if uvedge_priority(target) < uvedge_priority(source):
462 target, source = source, target
463 target_island = target.uvface.island
464 if do_create_numbers:
465 for uvedge in [source] + edge.uvedges[2:]:
466 if not is_index_obvious(uvedge, target):
467 # it will not be clear to see that these uvedges should be sticked together
468 # So, create an arrow and put the index on all stickers
469 target_island.sticker_numbering += 1
470 index = str(target_island.sticker_numbering)
471 if is_upsidedown_wrong(index):
472 index += "."
473 target_island.add_marker(Arrow(target, default_width, index))
474 break
475 add_sticker(source, index, target)
476 elif len(edge.uvedges) > 2:
477 target = edge.uvedges[0]
478 if len(edge.uvedges) > 2:
479 for source in edge.uvedges[2:]:
480 add_sticker(source, index, target)
482 def generate_numbers_alone(self, size):
483 global_numbering = 0
484 for edge in self.edges.values():
485 if edge.is_main_cut and len(edge.uvedges) >= 2:
486 global_numbering += 1
487 index = str(global_numbering)
488 if is_upsidedown_wrong(index):
489 index += "."
490 for uvedge in edge.uvedges:
491 uvedge.uvface.island.add_marker(NumberAlone(uvedge, index, size))
493 def enumerate_islands(self):
494 for num, island in enumerate(self.islands, 1):
495 island.number = num
496 island.generate_label()
498 def scale_islands(self, scale):
499 for island in self.islands:
500 vertices = set(island.vertices.values())
501 for point in chain((vertex.co for vertex in vertices), island.fake_vertices):
502 point *= scale
504 def finalize_islands(self, cage_size, title_height=0):
505 for island in self.islands:
506 if title_height:
507 island.title = "[{}] {}".format(island.abbreviation, island.label)
508 points = [vertex.co for vertex in set(island.vertices.values())] + island.fake_vertices
509 angle, _ = cage_fit(points, (cage_size.y - title_height) / cage_size.x)
510 rot = M.Matrix.Rotation(angle, 2)
511 for point in points:
512 # note: we need an in-place operation, and Vector.rotate() seems to work for 3d vectors only
513 point[:] = rot @ point
514 for marker in island.markers:
515 marker.rot = rot @ marker.rot
516 bottom_left = M.Vector((min(v.x for v in points), min(v.y for v in points) - title_height))
517 #DEBUG
518 top_right = M.Vector((max(v.x for v in points), max(v.y for v in points) - title_height))
519 #print(f"fitted aspect: {(top_right.y - bottom_left.y) / (top_right.x - bottom_left.x)}")
520 for point in points:
521 point -= bottom_left
522 island.bounding_box = M.Vector((max(v.x for v in points), max(v.y for v in points)))
524 def largest_island_ratio(self, cage_size):
525 return max(i / p for island in self.islands for (i, p) in zip(island.bounding_box, cage_size))
527 def fit_islands(self, cage_size):
528 """Move islands so that they fit onto pages, based on their bounding boxes"""
530 def try_emplace(island, page_islands, stops_x, stops_y, occupied_cache):
531 """Tries to put island to each pair from stops_x, stops_y
532 and checks if it overlaps with any islands present on the page.
533 Returns True and positions the given island on success."""
534 bbox_x, bbox_y = island.bounding_box.xy
535 for x in stops_x:
536 if x + bbox_x > cage_size.x:
537 continue
538 for y in stops_y:
539 if y + bbox_y > cage_size.y or (x, y) in occupied_cache:
540 continue
541 for i, obstacle in enumerate(page_islands):
542 # if this obstacle overlaps with the island, try another stop
543 if (x + bbox_x > obstacle.pos.x and
544 obstacle.pos.x + obstacle.bounding_box.x > x and
545 y + bbox_y > obstacle.pos.y and
546 obstacle.pos.y + obstacle.bounding_box.y > y):
547 if x >= obstacle.pos.x and y >= obstacle.pos.y:
548 occupied_cache.add((x, y))
549 # just a stupid heuristic to make subsequent searches faster
550 if i > 0:
551 page_islands[1:i+1] = page_islands[:i]
552 page_islands[0] = obstacle
553 break
554 else:
555 # if no obstacle called break, this position is okay
556 island.pos.xy = x, y
557 page_islands.append(island)
558 stops_x.append(x + bbox_x)
559 stops_y.append(y + bbox_y)
560 return True
561 return False
563 def drop_portion(stops, border, divisor):
564 stops.sort()
565 # distance from left neighbor to the right one, excluding the first stop
566 distances = [right - left for left, right in zip(stops, chain(stops[2:], [border]))]
567 quantile = sorted(distances)[len(distances) // divisor]
568 return [stop for stop, distance in zip(stops, chain([quantile], distances)) if distance >= quantile]
570 if any(island.bounding_box.x > cage_size.x or island.bounding_box.y > cage_size.y for island in self.islands):
571 raise UnfoldError(
572 "An island is too big to fit onto page of the given size. "
573 "Either downscale the model or find and split that island manually.\n"
574 "Export failed, sorry.")
575 # sort islands by their diagonal... just a guess
576 remaining_islands = sorted(self.islands, reverse=True, key=lambda island: island.bounding_box.length_squared)
577 page_num = 1 # TODO delete me
579 while remaining_islands:
580 # create a new page and try to fit as many islands onto it as possible
581 page = Page(page_num)
582 page_num += 1
583 occupied_cache = set()
584 stops_x, stops_y = [0], [0]
585 for island in remaining_islands:
586 try_emplace(island, page.islands, stops_x, stops_y, occupied_cache)
587 # if overwhelmed with stops, drop a quarter of them
588 if len(stops_x)**2 > 4 * len(self.islands) + 100:
589 stops_x = drop_portion(stops_x, cage_size.x, 4)
590 stops_y = drop_portion(stops_y, cage_size.y, 4)
591 remaining_islands = [island for island in remaining_islands if island not in page.islands]
592 self.pages.append(page)
594 def save_uv(self, cage_size=M.Vector((1, 1)), separate_image=False):
595 if separate_image:
596 for island in self.islands:
597 island.save_uv_separate(self.looptex)
598 else:
599 for island in self.islands:
600 island.save_uv(self.looptex, cage_size)
602 def save_image(self, page_size_pixels: M.Vector, filename):
603 for page in self.pages:
604 image = create_blank_image("Page {}".format(page.name), page_size_pixels, alpha=1)
605 image.filepath_raw = page.image_path = "{}_{}.png".format(filename, page.name)
606 faces = [face for island in page.islands for face in island.faces]
607 self.bake(faces, image)
608 image.save()
609 image.user_clear()
610 bpy.data.images.remove(image)
612 def save_separate_images(self, scale, filepath, embed=None):
613 for i, island in enumerate(self.islands):
614 image_name = "Island {}".format(i)
615 image = create_blank_image(image_name, island.bounding_box * scale, alpha=0)
616 self.bake(island.faces.keys(), image)
617 if embed:
618 island.embedded_image = embed(image)
619 else:
620 from os import makedirs
621 image_dir = filepath
622 makedirs(image_dir, exist_ok=True)
623 image_path = os_path.join(image_dir, "island{}.png".format(i))
624 image.filepath_raw = image_path
625 image.save()
626 island.image_path = image_path
627 image.user_clear()
628 bpy.data.images.remove(image)
630 def bake(self, faces, image):
631 if not self.looptex:
632 raise UnfoldError("The mesh has no UV Map slots left. Either delete a UV Map or export the net without textures.")
633 ob = bpy.context.active_object
634 me = ob.data
635 # in Cycles, the image for baking is defined by the active Image Node
636 temp_nodes = dict()
637 for mat in me.materials:
638 mat.use_nodes = True
639 img = mat.node_tree.nodes.new('ShaderNodeTexImage')
640 img.image = image
641 temp_nodes[mat] = img
642 mat.node_tree.nodes.active = img
643 # move all excess faces to negative numbers (that is the only way to disable them)
644 ignored_uvs = [loop[self.looptex].uv for f in self.data.faces if f not in faces for loop in f.loops]
645 for uv in ignored_uvs:
646 uv *= -1
647 bake_type = bpy.context.scene.cycles.bake_type
648 sta = bpy.context.scene.render.bake.use_selected_to_active
649 try:
650 ob.update_from_editmode()
651 me.uv_layers.active = me.uv_layers[self.looptex.name]
652 bpy.ops.object.bake(type=bake_type, margin=1, use_selected_to_active=sta, cage_extrusion=100, use_clear=False)
653 except RuntimeError as e:
654 raise UnfoldError(*e.args)
655 finally:
656 for mat, node in temp_nodes.items():
657 mat.node_tree.nodes.remove(node)
658 for uv in ignored_uvs:
659 uv *= -1
662 class Edge:
663 """Wrapper for BPy Edge"""
664 __slots__ = ('data', 'va', 'vb', 'main_faces', 'uvedges',
665 'vector', 'angle',
666 'is_main_cut', 'force_cut', 'priority', 'freestyle')
668 def __init__(self, edge):
669 self.data = edge
670 self.va, self.vb = edge.verts
671 self.vector = self.vb.co - self.va.co
672 # if self.main_faces is set, then self.uvedges[:2] must correspond to self.main_faces, in their order
673 # this constraint is assured at the time of finishing mesh.generate_cuts
674 self.uvedges = list()
676 self.force_cut = edge.seam # such edges will always be cut
677 self.main_faces = None # two faces that may be connected in the island
678 # is_main_cut defines whether the two main faces are connected
679 # all the others will be assumed to be cut
680 self.is_main_cut = True
681 self.priority = None
682 self.angle = None
683 self.freestyle = False
685 def choose_main_faces(self):
686 """Choose two main faces that might get connected in an island"""
687 from itertools import combinations
688 loops = self.data.link_loops
689 def score(pair):
690 return abs(pair[0].face.normal.dot(pair[1].face.normal))
691 if len(loops) == 2:
692 self.main_faces = list(loops)
693 elif len(loops) > 2:
694 # find (with brute force) the pair of indices whose loops have the most similar normals
695 self.main_faces = max(combinations(loops, 2), key=score)
696 if self.main_faces and self.main_faces[1].vert == self.va:
697 self.main_faces = self.main_faces[::-1]
699 def calculate_angle(self):
700 """Calculate the angle between the main faces"""
701 loop_a, loop_b = self.main_faces
702 normal_a, normal_b = (l.face.normal for l in self.main_faces)
703 if not normal_a or not normal_b:
704 self.angle = -3 # just a very sharp angle
705 else:
706 s = normal_a.cross(normal_b).dot(self.vector.normalized())
707 s = max(min(s, 1.0), -1.0) # deal with rounding errors
708 self.angle = asin(s)
709 if loop_a.link_loop_next.vert != loop_b.vert or loop_b.link_loop_next.vert != loop_a.vert:
710 self.angle = abs(self.angle)
712 def generate_priority(self, priority_effect, average_length):
713 """Calculate the priority value for cutting"""
714 angle = self.angle
715 if angle > 0:
716 self.priority = priority_effect['CONVEX'] * angle / pi
717 else:
718 self.priority = priority_effect['CONCAVE'] * (-angle) / pi
719 self.priority += (self.vector.length / average_length) * priority_effect['LENGTH']
721 def is_cut(self, face):
722 """Return False if this edge will the given face to another one in the resulting net
723 (useful for edges with more than two faces connected)"""
724 # Return whether there is a cut between the two main faces
725 if self.main_faces and face in {loop.face for loop in self.main_faces}:
726 return self.is_main_cut
727 # All other faces (third and more) are automatically treated as cut
728 else:
729 return True
731 def other_uvedge(self, this):
732 """Get an uvedge of this edge that is not the given one
733 causes an IndexError if case of less than two adjacent edges"""
734 return self.uvedges[1] if this is self.uvedges[0] else self.uvedges[0]
737 class Island:
738 """Part of the net to be exported"""
739 __slots__ = ('mesh', 'faces', 'edges', 'vertices', 'fake_vertices', 'boundary', 'markers',
740 'pos', 'bounding_box',
741 'image_path', 'embedded_image',
742 'number', 'label', 'abbreviation', 'title',
743 'has_safe_geometry', 'is_inside_out',
744 'sticker_numbering')
746 def __init__(self, mesh, face, matrix, normal_matrix):
747 """Create an Island from a single Face"""
748 self.mesh = mesh
749 self.faces = dict() # face -> uvface
750 self.edges = dict() # loop -> uvedge
751 self.vertices = dict() # loop -> uvvertex
752 self.fake_vertices = list()
753 self.markers = list()
754 self.label = None
755 self.abbreviation = None
756 self.title = None
757 self.pos = M.Vector((0, 0))
758 self.image_path = None
759 self.embedded_image = None
760 self.is_inside_out = False # swaps concave <-> convex edges
761 self.has_safe_geometry = True
762 self.sticker_numbering = 0
764 uvface = UVFace(face, self, matrix, normal_matrix)
765 self.vertices.update(uvface.vertices)
766 self.edges.update(uvface.edges)
767 self.faces[face] = uvface
768 # UVEdges on the boundary
769 self.boundary = list(self.edges.values())
771 def add_marker(self, marker):
772 self.fake_vertices.extend(marker.bounds)
773 self.markers.append(marker)
775 def generate_label(self, label=None, abbreviation=None):
776 """Assign a name to this island automatically"""
777 abbr = abbreviation or self.abbreviation or str(self.number)
778 # TODO: dots should be added in the last instant when outputting any text
779 if is_upsidedown_wrong(abbr):
780 abbr += "."
781 self.label = label or self.label or "Island {}".format(self.number)
782 self.abbreviation = abbr
784 def save_uv(self, tex, cage_size):
785 """Save UV Coordinates of all UVFaces to a given UV texture
786 tex: UV Texture layer to use (BMLayerItem)
787 page_size: size of the page in pixels (vector)"""
788 scale_x, scale_y = 1 / cage_size.x, 1 / cage_size.y
789 for loop, uvvertex in self.vertices.items():
790 uv = uvvertex.co + self.pos
791 loop[tex].uv = uv.x * scale_x, uv.y * scale_y
793 def save_uv_separate(self, tex):
794 """Save UV Coordinates of all UVFaces to a given UV texture, spanning from 0 to 1
795 tex: UV Texture layer to use (BMLayerItem)
796 page_size: size of the page in pixels (vector)"""
797 scale_x, scale_y = 1 / self.bounding_box.x, 1 / self.bounding_box.y
798 for loop, uvvertex in self.vertices.items():
799 loop[tex].uv = uvvertex.co.x * scale_x, uvvertex.co.y * scale_y
801 def join(uvedge_a, uvedge_b, size_limit=None, epsilon=1e-6):
803 Try to join other island on given edge
804 Returns False if they would overlap
807 class Intersection(Exception):
808 pass
810 class GeometryError(Exception):
811 pass
813 def is_below(self, other, correct_geometry=True):
814 if self is other:
815 return False
816 if self.top < other.bottom:
817 return True
818 if other.top < self.bottom:
819 return False
820 if self.max.tup <= other.min.tup:
821 return True
822 if other.max.tup <= self.min.tup:
823 return False
824 self_vector = self.max.co - self.min.co
825 min_to_min = other.min.co - self.min.co
826 cross_b1 = self_vector.cross(min_to_min)
827 cross_b2 = self_vector.cross(other.max.co - self.min.co)
828 if cross_b2 < cross_b1:
829 cross_b1, cross_b2 = cross_b2, cross_b1
830 if cross_b2 > 0 and (cross_b1 > 0 or (cross_b1 == 0 and not self.is_uvface_upwards())):
831 return True
832 if cross_b1 < 0 and (cross_b2 < 0 or (cross_b2 == 0 and self.is_uvface_upwards())):
833 return False
834 other_vector = other.max.co - other.min.co
835 cross_a1 = other_vector.cross(-min_to_min)
836 cross_a2 = other_vector.cross(self.max.co - other.min.co)
837 if cross_a2 < cross_a1:
838 cross_a1, cross_a2 = cross_a2, cross_a1
839 if cross_a2 > 0 and (cross_a1 > 0 or (cross_a1 == 0 and not other.is_uvface_upwards())):
840 return False
841 if cross_a1 < 0 and (cross_a2 < 0 or (cross_a2 == 0 and other.is_uvface_upwards())):
842 return True
843 if cross_a1 == cross_b1 == cross_a2 == cross_b2 == 0:
844 if correct_geometry:
845 raise GeometryError
846 elif self.is_uvface_upwards() == other.is_uvface_upwards():
847 raise Intersection
848 return False
849 if self.min.tup == other.min.tup or self.max.tup == other.max.tup:
850 return cross_a2 > cross_b2
851 raise Intersection
853 class QuickSweepline:
854 """Efficient sweepline based on binary search, checking neighbors only"""
855 def __init__(self):
856 self.children = list()
858 def add(self, item, cmp=is_below):
859 low, high = 0, len(self.children)
860 while low < high:
861 mid = (low + high) // 2
862 if cmp(self.children[mid], item):
863 low = mid + 1
864 else:
865 high = mid
866 self.children.insert(low, item)
868 def remove(self, item, cmp=is_below):
869 index = self.children.index(item)
870 self.children.pop(index)
871 if index > 0 and index < len(self.children):
872 # check for intersection
873 if cmp(self.children[index], self.children[index-1]):
874 raise GeometryError
876 class BruteSweepline:
877 """Safe sweepline which checks all its members pairwise"""
878 def __init__(self):
879 self.children = set()
881 def add(self, item, cmp=is_below):
882 for child in self.children:
883 if child.min is not item.min and child.max is not item.max:
884 cmp(item, child, False)
885 self.children.add(item)
887 def remove(self, item):
888 self.children.remove(item)
890 def sweep(sweepline, segments):
891 """Sweep across the segments and raise an exception if necessary"""
892 # careful, 'segments' may be a use-once iterator
893 events_add = sorted(segments, reverse=True, key=lambda uvedge: uvedge.min.tup)
894 events_remove = sorted(events_add, reverse=True, key=lambda uvedge: uvedge.max.tup)
895 while events_remove:
896 while events_add and events_add[-1].min.tup <= events_remove[-1].max.tup:
897 sweepline.add(events_add.pop())
898 sweepline.remove(events_remove.pop())
900 def root_find(value, tree):
901 """Find the root of a given value in a forest-like dictionary
902 also updates the dictionary using path compression"""
903 parent, relink = tree.get(value), list()
904 while parent is not None:
905 relink.append(value)
906 value, parent = parent, tree.get(parent)
907 tree.update(dict.fromkeys(relink, value))
908 return value
910 def slope_from(position):
911 def slope(uvedge):
912 vec = (uvedge.vb.co - uvedge.va.co) if uvedge.va.tup == position else (uvedge.va.co - uvedge.vb.co)
913 return (vec.y / vec.length + 1) if ((vec.x, vec.y) > (0, 0)) else (-1 - vec.y / vec.length)
914 return slope
916 island_a, island_b = (e.uvface.island for e in (uvedge_a, uvedge_b))
917 if island_a is island_b:
918 return False
919 elif len(island_b.faces) > len(island_a.faces):
920 uvedge_a, uvedge_b = uvedge_b, uvedge_a
921 island_a, island_b = island_b, island_a
922 # check if vertices and normals are aligned correctly
923 verts_flipped = uvedge_b.loop.vert is uvedge_a.loop.vert
924 flipped = verts_flipped ^ uvedge_a.uvface.flipped ^ uvedge_b.uvface.flipped
925 # determine rotation
926 # NOTE: if the edges differ in length, the matrix will involve uniform scaling.
927 # Such situation may occur in the case of twisted n-gons
928 first_b, second_b = (uvedge_b.va, uvedge_b.vb) if not verts_flipped else (uvedge_b.vb, uvedge_b.va)
929 if not flipped:
930 rot = fitting_matrix(first_b.co - second_b.co, uvedge_a.vb.co - uvedge_a.va.co)
931 else:
932 flip = M.Matrix(((-1, 0), (0, 1)))
933 rot = fitting_matrix(flip @ (first_b.co - second_b.co), uvedge_a.vb.co - uvedge_a.va.co) @ flip
934 trans = uvedge_a.vb.co - rot @ first_b.co
935 # preview of island_b's vertices after the join operation
936 phantoms = {uvvertex: UVVertex(rot @ uvvertex.co + trans) for uvvertex in island_b.vertices.values()}
938 # check the size of the resulting island
939 if size_limit:
940 points = [vert.co for vert in chain(island_a.vertices.values(), phantoms.values())]
941 left, right, bottom, top = (fn(co[i] for co in points) for i in (0, 1) for fn in (min, max))
942 bbox_width = right - left
943 bbox_height = top - bottom
944 if min(bbox_width, bbox_height)**2 > size_limit.x**2 + size_limit.y**2:
945 return False
946 if (bbox_width > size_limit.x or bbox_height > size_limit.y) and (bbox_height > size_limit.x or bbox_width > size_limit.y):
947 _, height = cage_fit(points, size_limit.y / size_limit.x)
948 if height > size_limit.y:
949 return False
951 distance_limit = uvedge_a.loop.edge.calc_length() * epsilon
952 # try and merge UVVertices closer than sqrt(distance_limit)
953 merged_uvedges = set()
954 merged_uvedge_pairs = list()
956 # merge all uvvertices that are close enough using a union-find structure
957 # uvvertices will be merged only in cases island_b->island_a and island_a->island_a
958 # all resulting groups are merged together to a uvvertex of island_a
959 is_merged_mine = False
960 shared_vertices = {loop.vert for loop in chain(island_a.vertices, island_b.vertices)}
961 for vertex in shared_vertices:
962 uvs_a = {island_a.vertices.get(loop) for loop in vertex.link_loops} - {None}
963 uvs_b = {island_b.vertices.get(loop) for loop in vertex.link_loops} - {None}
964 for a, b in product(uvs_a, uvs_b):
965 if (a.co - phantoms[b].co).length_squared < distance_limit:
966 phantoms[b] = root_find(a, phantoms)
967 for a1, a2 in combinations(uvs_a, 2):
968 if (a1.co - a2.co).length_squared < distance_limit:
969 a1, a2 = (root_find(a, phantoms) for a in (a1, a2))
970 if a1 is not a2:
971 phantoms[a2] = a1
972 is_merged_mine = True
973 for source, target in phantoms.items():
974 target = root_find(target, phantoms)
975 phantoms[source] = target
977 for uvedge in (chain(island_a.boundary, island_b.boundary) if is_merged_mine else island_b.boundary):
978 for loop in uvedge.loop.link_loops:
979 partner = island_b.edges.get(loop) or island_a.edges.get(loop)
980 if partner is not None and partner is not uvedge:
981 paired_a, paired_b = phantoms.get(partner.vb, partner.vb), phantoms.get(partner.va, partner.va)
982 if (partner.uvface.flipped ^ flipped) != uvedge.uvface.flipped:
983 paired_a, paired_b = paired_b, paired_a
984 if phantoms.get(uvedge.va, uvedge.va) is paired_a and phantoms.get(uvedge.vb, uvedge.vb) is paired_b:
985 # if these two edges will get merged, add them both to the set
986 merged_uvedges.update((uvedge, partner))
987 merged_uvedge_pairs.append((uvedge, partner))
988 break
990 if uvedge_b not in merged_uvedges:
991 raise UnfoldError("Export failed. Please report this error, including the model if you can.")
993 boundary_other = [
994 PhantomUVEdge(phantoms[uvedge.va], phantoms[uvedge.vb], flipped ^ uvedge.uvface.flipped)
995 for uvedge in island_b.boundary if uvedge not in merged_uvedges]
996 # TODO: if is_merged_mine, it might make sense to create a similar list from island_a.boundary as well
998 incidence = {vertex.tup for vertex in phantoms.values()}.intersection(vertex.tup for vertex in island_a.vertices.values())
999 incidence = {position: list() for position in incidence} # from now on, 'incidence' is a dict
1000 for uvedge in chain(boundary_other, island_a.boundary):
1001 if uvedge.va.co == uvedge.vb.co:
1002 continue
1003 for vertex in (uvedge.va, uvedge.vb):
1004 site = incidence.get(vertex.tup)
1005 if site is not None:
1006 site.append(uvedge)
1007 for position, segments in incidence.items():
1008 if len(segments) <= 2:
1009 continue
1010 segments.sort(key=slope_from(position))
1011 for right, left in pairs(segments):
1012 is_left_ccw = left.is_uvface_upwards() ^ (left.max.tup == position)
1013 is_right_ccw = right.is_uvface_upwards() ^ (right.max.tup == position)
1014 if is_right_ccw and not is_left_ccw and type(right) is not type(left) and right not in merged_uvedges and left not in merged_uvedges:
1015 return False
1016 if (not is_right_ccw and right not in merged_uvedges) ^ (is_left_ccw and left not in merged_uvedges):
1017 return False
1019 # check for self-intersections
1020 try:
1021 try:
1022 sweepline = QuickSweepline() if island_a.has_safe_geometry and island_b.has_safe_geometry else BruteSweepline()
1023 sweep(sweepline, (uvedge for uvedge in chain(boundary_other, island_a.boundary)))
1024 island_a.has_safe_geometry &= island_b.has_safe_geometry
1025 except GeometryError:
1026 sweep(BruteSweepline(), (uvedge for uvedge in chain(boundary_other, island_a.boundary)))
1027 island_a.has_safe_geometry = False
1028 except Intersection:
1029 return False
1031 # mark all edges that connect the islands as not cut
1032 for uvedge in merged_uvedges:
1033 island_a.mesh.edges[uvedge.loop.edge].is_main_cut = False
1035 # include all trasformed vertices as mine
1036 island_a.vertices.update({loop: phantoms[uvvertex] for loop, uvvertex in island_b.vertices.items()})
1038 # re-link uvedges and uvfaces to their transformed locations
1039 for uvedge in island_b.edges.values():
1040 uvedge.va = phantoms[uvedge.va]
1041 uvedge.vb = phantoms[uvedge.vb]
1042 uvedge.update()
1043 if is_merged_mine:
1044 for uvedge in island_a.edges:
1045 uvedge.va = phantoms.get(uvedge.va, uvedge.va)
1046 uvedge.vb = phantoms.get(uvedge.vb, uvedge.vb)
1047 island_a.edges.update(island_b.edges)
1049 for uvface in island_b.faces.values():
1050 uvface.island = island_a
1051 uvface.vertices = {loop: phantoms[uvvertex] for loop, uvvertex in uvface.vertices.items()}
1052 uvface.flipped ^= flipped
1053 if is_merged_mine:
1054 # there may be own uvvertices that need to be replaced by phantoms
1055 for uvface in island_a.faces.values():
1056 if any(uvvertex in phantoms for uvvertex in uvface.vertices):
1057 uvface.vertices = {loop: phantoms.get(uvvertex, uvvertex) for loop, uvvertex in uvface.vertices.items()}
1058 island_a.faces.update(island_b.faces)
1060 island_a.boundary = [
1061 uvedge for uvedge in chain(island_a.boundary, island_b.boundary)
1062 if uvedge not in merged_uvedges]
1064 for uvedge, partner in merged_uvedge_pairs:
1065 # make sure that main faces are the ones actually merged (this changes nothing in most cases)
1066 edge = island_a.mesh.edges[uvedge.loop.edge]
1067 edge.main_faces = uvedge.loop, partner.loop
1069 # everything seems to be OK
1070 return island_b
1073 class Page:
1074 """Container for several Islands"""
1075 __slots__ = ('islands', 'name', 'image_path')
1077 def __init__(self, num=1):
1078 self.islands = list()
1079 self.name = "page{}".format(num) # TODO delete me
1080 self.image_path = None
1083 class UVVertex:
1084 """Vertex in 2D"""
1085 __slots__ = ('co', 'tup')
1087 def __init__(self, vector):
1088 self.co = vector.xy
1089 self.tup = tuple(self.co)
1092 class UVEdge:
1093 """Edge in 2D"""
1094 # Every UVEdge is attached to only one UVFace
1095 # UVEdges are doubled as needed because they both have to point clockwise around their faces
1096 __slots__ = ('va', 'vb', 'uvface', 'loop',
1097 'min', 'max', 'bottom', 'top',
1098 'neighbor_left', 'neighbor_right', 'sticker')
1100 def __init__(self, vertex1: UVVertex, vertex2: UVVertex, uvface, loop):
1101 self.va = vertex1
1102 self.vb = vertex2
1103 self.update()
1104 self.uvface = uvface
1105 self.sticker = None
1106 self.loop = loop
1108 def update(self):
1109 """Update data if UVVertices have moved"""
1110 self.min, self.max = (self.va, self.vb) if (self.va.tup < self.vb.tup) else (self.vb, self.va)
1111 y1, y2 = self.va.co.y, self.vb.co.y
1112 self.bottom, self.top = (y1, y2) if y1 < y2 else (y2, y1)
1114 def is_uvface_upwards(self):
1115 return (self.va.tup < self.vb.tup) ^ self.uvface.flipped
1117 def __repr__(self):
1118 return "({0.va} - {0.vb})".format(self)
1121 class PhantomUVEdge:
1122 """Temporary 2D Segment for calculations"""
1123 __slots__ = ('va', 'vb', 'min', 'max', 'bottom', 'top')
1125 def __init__(self, vertex1: UVVertex, vertex2: UVVertex, flip):
1126 self.va, self.vb = (vertex2, vertex1) if flip else (vertex1, vertex2)
1127 self.min, self.max = (self.va, self.vb) if (self.va.tup < self.vb.tup) else (self.vb, self.va)
1128 y1, y2 = self.va.co.y, self.vb.co.y
1129 self.bottom, self.top = (y1, y2) if y1 < y2 else (y2, y1)
1131 def is_uvface_upwards(self):
1132 return self.va.tup < self.vb.tup
1134 def __repr__(self):
1135 return "[{0.va} - {0.vb}]".format(self)
1138 class UVFace:
1139 """Face in 2D"""
1140 __slots__ = ('vertices', 'edges', 'face', 'island', 'flipped')
1142 def __init__(self, face: bmesh.types.BMFace, island: Island, matrix=1, normal_matrix=1):
1143 self.face = face
1144 self.island = island
1145 self.flipped = False # a flipped UVFace has edges clockwise
1147 flatten = z_up_matrix(normal_matrix @ face.normal) @ matrix
1148 self.vertices = {loop: UVVertex(flatten @ loop.vert.co) for loop in face.loops}
1149 self.edges = {loop: UVEdge(self.vertices[loop], self.vertices[loop.link_loop_next], self, loop) for loop in face.loops}
1152 class Arrow:
1153 """Mark in the document: an arrow denoting the number of the edge it points to"""
1154 __slots__ = ('bounds', 'center', 'rot', 'text', 'size')
1156 def __init__(self, uvedge, size, index):
1157 self.text = str(index)
1158 edge = (uvedge.vb.co - uvedge.va.co) if not uvedge.uvface.flipped else (uvedge.va.co - uvedge.vb.co)
1159 self.center = (uvedge.va.co + uvedge.vb.co) / 2
1160 self.size = size
1161 tangent = edge.normalized()
1162 cos, sin = tangent
1163 self.rot = M.Matrix(((cos, -sin), (sin, cos)))
1164 normal = M.Vector((sin, -cos))
1165 self.bounds = [self.center, self.center + (1.2 * normal + tangent) * size, self.center + (1.2 * normal - tangent) * size]
1168 class Sticker:
1169 """Mark in the document: sticker tab"""
1170 __slots__ = ('bounds', 'center', 'rot', 'text', 'width', 'vertices')
1172 def __init__(self, uvedge, default_width, index, other: UVEdge):
1173 """Sticker is directly attached to the given UVEdge"""
1174 first_vertex, second_vertex = (uvedge.va, uvedge.vb) if not uvedge.uvface.flipped else (uvedge.vb, uvedge.va)
1175 edge = first_vertex.co - second_vertex.co
1176 sticker_width = min(default_width, edge.length / 2)
1177 other_first, other_second = (other.va, other.vb) if not other.uvface.flipped else (other.vb, other.va)
1178 other_edge = other_second.co - other_first.co
1180 # angle a is at vertex uvedge.va, b is at uvedge.vb
1181 cos_a = cos_b = 0.5
1182 sin_a = sin_b = 0.75**0.5
1183 # len_a is length of the side adjacent to vertex a, len_b likewise
1184 len_a = len_b = sticker_width / sin_a
1186 # fix overlaps with the most often neighbour - its sticking target
1187 if first_vertex == other_second:
1188 cos_a = max(cos_a, edge.dot(other_edge) / (edge.length_squared)) # angles between pi/3 and 0
1189 elif second_vertex == other_first:
1190 cos_b = max(cos_b, edge.dot(other_edge) / (edge.length_squared)) # angles between pi/3 and 0
1192 # Fix tabs for sticking targets with small angles
1193 try:
1194 other_face_neighbor_left = other.neighbor_left
1195 other_face_neighbor_right = other.neighbor_right
1196 other_edge_neighbor_a = other_face_neighbor_left.vb.co - other.vb.co
1197 other_edge_neighbor_b = other_face_neighbor_right.va.co - other.va.co
1198 # Adjacent angles in the face
1199 cos_a = max(cos_a, -other_edge.dot(other_edge_neighbor_a) / (other_edge.length*other_edge_neighbor_a.length))
1200 cos_b = max(cos_b, other_edge.dot(other_edge_neighbor_b) / (other_edge.length*other_edge_neighbor_b.length))
1201 except AttributeError: # neighbor data may be missing for edges with 3+ faces
1202 pass
1203 except ZeroDivisionError:
1204 pass
1206 # Calculate the lengths of the glue tab edges using the possibly smaller angles
1207 sin_a = abs(1 - cos_a**2)**0.5
1208 len_b = min(len_a, (edge.length * sin_a) / (sin_a * cos_b + sin_b * cos_a))
1209 len_a = 0 if sin_a == 0 else min(sticker_width / sin_a, (edge.length - len_b*cos_b) / cos_a)
1211 sin_b = abs(1 - cos_b**2)**0.5
1212 len_a = min(len_a, (edge.length * sin_b) / (sin_a * cos_b + sin_b * cos_a))
1213 len_b = 0 if sin_b == 0 else min(sticker_width / sin_b, (edge.length - len_a * cos_a) / cos_b)
1215 v3 = UVVertex(second_vertex.co + M.Matrix(((cos_b, -sin_b), (sin_b, cos_b))) @ edge * len_b / edge.length)
1216 v4 = UVVertex(first_vertex.co + M.Matrix(((-cos_a, -sin_a), (sin_a, -cos_a))) @ edge * len_a / edge.length)
1217 if v3.co != v4.co:
1218 self.vertices = [second_vertex, v3, v4, first_vertex]
1219 else:
1220 self.vertices = [second_vertex, v3, first_vertex]
1222 sin, cos = edge.y / edge.length, edge.x / edge.length
1223 self.rot = M.Matrix(((cos, -sin), (sin, cos)))
1224 self.width = sticker_width * 0.9
1225 if index and uvedge.uvface.island is not other.uvface.island:
1226 self.text = "{}:{}".format(other.uvface.island.abbreviation, index)
1227 else:
1228 self.text = index
1229 self.center = (uvedge.va.co + uvedge.vb.co) / 2 + self.rot @ M.Vector((0, self.width * 0.2))
1230 self.bounds = [v3.co, v4.co, self.center] if v3.co != v4.co else [v3.co, self.center]
1233 class NumberAlone:
1234 """Mark in the document: numbering inside the island denoting edges to be sticked"""
1235 __slots__ = ('bounds', 'center', 'rot', 'text', 'size')
1237 def __init__(self, uvedge, index, default_size=0.005):
1238 """Sticker is directly attached to the given UVEdge"""
1239 edge = (uvedge.va.co - uvedge.vb.co) if not uvedge.uvface.flipped else (uvedge.vb.co - uvedge.va.co)
1241 self.size = default_size
1242 sin, cos = edge.y / edge.length, edge.x / edge.length
1243 self.rot = M.Matrix(((cos, -sin), (sin, cos)))
1244 self.text = index
1245 self.center = (uvedge.va.co + uvedge.vb.co) / 2 - self.rot @ M.Vector((0, self.size * 1.2))
1246 self.bounds = [self.center]
1249 class SVG:
1250 """Simple SVG exporter"""
1252 def __init__(self, page_size: M.Vector, style, margin, pure_net=True, angle_epsilon=0.01):
1253 """Initialize document settings.
1254 page_size: document dimensions in meters
1255 pure_net: if True, do not use image"""
1256 self.page_size = page_size
1257 self.pure_net = pure_net
1258 self.style = style
1259 self.margin = margin
1260 self.text_size = 12
1261 self.angle_epsilon = angle_epsilon
1263 @classmethod
1264 def encode_image(cls, bpy_image):
1265 import tempfile
1266 import base64
1267 with tempfile.TemporaryDirectory() as directory:
1268 filename = directory + "/i.png"
1269 bpy_image.filepath_raw = filename
1270 bpy_image.save()
1271 return base64.encodebytes(open(filename, "rb").read()).decode('ascii')
1273 def format_vertex(self, vector, pos=M.Vector((0, 0))):
1274 """Return a string with both coordinates of the given vertex."""
1275 x, y = vector + pos
1276 return "{:.6f} {:.6f}".format((x + self.margin) * 1000, (self.page_size.y - y - self.margin) * 1000)
1278 def write(self, mesh, filename):
1279 """Write data to a file given by its name."""
1280 line_through = " L ".join # used for formatting of SVG path data
1281 rows = "\n".join
1283 dl = ["{:.2f}".format(length * self.style.line_width * 1000) for length in (2, 5, 10)]
1284 format_style = {
1285 'SOLID': "none", 'DOT': "{0},{1}".format(*dl), 'DASH': "{1},{2}".format(*dl),
1286 'LONGDASH': "{2},{1}".format(*dl), 'DASHDOT': "{2},{1},{0},{1}".format(*dl)}
1288 def format_color(vec):
1289 return "#{:02x}{:02x}{:02x}".format(round(vec[0] * 255), round(vec[1] * 255), round(vec[2] * 255))
1291 def format_matrix(matrix):
1292 return " ".join("{:.6f}".format(cell) for column in matrix for cell in column)
1294 def path_convert(string, relto=os_path.dirname(filename)):
1295 assert(os_path) # check the module was imported
1296 string = os_path.relpath(string, relto)
1297 if os_path.sep != '/':
1298 string = string.replace(os_path.sep, '/')
1299 return string
1301 styleargs = {
1302 name: format_color(getattr(self.style, name)) for name in (
1303 "outer_color", "outbg_color", "convex_color", "concave_color", "freestyle_color",
1304 "inbg_color", "sticker_fill", "text_color")}
1305 styleargs.update({
1306 name: format_style[getattr(self.style, name)] for name in
1307 ("outer_style", "convex_style", "concave_style", "freestyle_style")})
1308 styleargs.update({
1309 name: getattr(self.style, attr)[3] for name, attr in (
1310 ("outer_alpha", "outer_color"), ("outbg_alpha", "outbg_color"),
1311 ("convex_alpha", "convex_color"), ("concave_alpha", "concave_color"),
1312 ("freestyle_alpha", "freestyle_color"),
1313 ("inbg_alpha", "inbg_color"), ("sticker_alpha", "sticker_fill"),
1314 ("text_alpha", "text_color"))})
1315 styleargs.update({
1316 name: getattr(self.style, name) * self.style.line_width * 1000 for name in
1317 ("outer_width", "convex_width", "concave_width", "freestyle_width", "outbg_width", "inbg_width")})
1318 for num, page in enumerate(mesh.pages):
1319 page_filename = "{}_{}.svg".format(filename[:filename.rfind(".svg")], page.name) if len(mesh.pages) > 1 else filename
1320 with open(page_filename, 'w') as f:
1321 print(self.svg_base.format(width=self.page_size.x*1000, height=self.page_size.y*1000), file=f)
1322 print(self.css_base.format(**styleargs), file=f)
1323 if page.image_path:
1324 print(
1325 self.image_linked_tag.format(
1326 pos="{0:.6f} {0:.6f}".format(self.margin*1000),
1327 width=(self.page_size.x - 2 * self.margin)*1000,
1328 height=(self.page_size.y - 2 * self.margin)*1000,
1329 path=path_convert(page.image_path)),
1330 file=f)
1331 if len(page.islands) > 1:
1332 print("<g>", file=f)
1334 for island in page.islands:
1335 print("<g>", file=f)
1336 if island.image_path:
1337 print(
1338 self.image_linked_tag.format(
1339 pos=self.format_vertex(island.pos + M.Vector((0, island.bounding_box.y))),
1340 width=island.bounding_box.x*1000,
1341 height=island.bounding_box.y*1000,
1342 path=path_convert(island.image_path)),
1343 file=f)
1344 elif island.embedded_image:
1345 print(
1346 self.image_embedded_tag.format(
1347 pos=self.format_vertex(island.pos + M.Vector((0, island.bounding_box.y))),
1348 width=island.bounding_box.x*1000,
1349 height=island.bounding_box.y*1000,
1350 path=island.image_path),
1351 island.embedded_image, "'/>",
1352 file=f, sep="")
1353 if island.title:
1354 print(
1355 self.text_tag.format(
1356 size=1000 * self.text_size,
1357 x=1000 * (island.bounding_box.x*0.5 + island.pos.x + self.margin),
1358 y=1000 * (self.page_size.y - island.pos.y - self.margin - 0.2 * self.text_size),
1359 label=island.title),
1360 file=f)
1362 data_markers, data_stickerfill, data_outer, data_convex, data_concave, data_freestyle = (list() for i in range(6))
1363 for marker in island.markers:
1364 if isinstance(marker, Sticker):
1365 data_stickerfill.append("M {} Z".format(
1366 line_through(self.format_vertex(vertex.co, island.pos) for vertex in marker.vertices)))
1367 if marker.text:
1368 data_markers.append(self.text_transformed_tag.format(
1369 label=marker.text,
1370 pos=self.format_vertex(marker.center, island.pos),
1371 mat=format_matrix(marker.rot),
1372 size=marker.width * 1000))
1373 elif isinstance(marker, Arrow):
1374 size = marker.size * 1000
1375 position = marker.center + marker.size * marker.rot @ M.Vector((0, -0.9))
1376 data_markers.append(self.arrow_marker_tag.format(
1377 index=marker.text,
1378 arrow_pos=self.format_vertex(marker.center, island.pos),
1379 scale=size,
1380 pos=self.format_vertex(position, island.pos - marker.size*M.Vector((0, 0.4))),
1381 mat=format_matrix(size * marker.rot)))
1382 elif isinstance(marker, NumberAlone):
1383 data_markers.append(self.text_transformed_tag.format(
1384 label=marker.text,
1385 pos=self.format_vertex(marker.center, island.pos),
1386 mat=format_matrix(marker.rot),
1387 size=marker.size * 1000))
1388 if data_stickerfill and self.style.sticker_fill[3] > 0:
1389 print("<path class='sticker' d='", rows(data_stickerfill), "'/>", file=f)
1391 outer_edges = set(island.boundary)
1392 while outer_edges:
1393 data_loop = list()
1394 uvedge = outer_edges.pop()
1395 while 1:
1396 if uvedge.sticker:
1397 data_loop.extend(self.format_vertex(vertex.co, island.pos) for vertex in uvedge.sticker.vertices[1:])
1398 else:
1399 vertex = uvedge.vb if uvedge.uvface.flipped else uvedge.va
1400 data_loop.append(self.format_vertex(vertex.co, island.pos))
1401 uvedge = uvedge.neighbor_right
1402 try:
1403 outer_edges.remove(uvedge)
1404 except KeyError:
1405 break
1406 data_outer.append("M {} Z".format(line_through(data_loop)))
1408 visited_edges = set()
1409 for loop, uvedge in island.edges.items():
1410 edge = mesh.edges[loop.edge]
1411 if edge.is_cut(uvedge.uvface.face) and not uvedge.sticker:
1412 continue
1413 data_uvedge = "M {}".format(
1414 line_through(self.format_vertex(vertex.co, island.pos) for vertex in (uvedge.va, uvedge.vb)))
1415 if edge.freestyle:
1416 data_freestyle.append(data_uvedge)
1417 # each uvedge is in two opposite-oriented variants; we want to add each only once
1418 vertex_pair = frozenset((uvedge.va, uvedge.vb))
1419 if vertex_pair not in visited_edges:
1420 visited_edges.add(vertex_pair)
1421 if edge.angle > self.angle_epsilon:
1422 data_convex.append(data_uvedge)
1423 elif edge.angle < -self.angle_epsilon:
1424 data_concave.append(data_uvedge)
1425 if island.is_inside_out:
1426 data_convex, data_concave = data_concave, data_convex
1428 if data_freestyle:
1429 print("<path class='freestyle' d='", rows(data_freestyle), "'/>", file=f)
1430 if (data_convex or data_concave) and not self.pure_net and self.style.use_inbg:
1431 print("<path class='inner_background' d='", rows(data_convex + data_concave), "'/>", file=f)
1432 if data_convex:
1433 print("<path class='convex' d='", rows(data_convex), "'/>", file=f)
1434 if data_concave:
1435 print("<path class='concave' d='", rows(data_concave), "'/>", file=f)
1436 if data_outer:
1437 if not self.pure_net and self.style.use_outbg:
1438 print("<path class='outer_background' d='", rows(data_outer), "'/>", file=f)
1439 print("<path class='outer' d='", rows(data_outer), "'/>", file=f)
1440 if data_markers:
1441 print(rows(data_markers), file=f)
1442 print("</g>", file=f)
1444 if len(page.islands) > 1:
1445 print("</g>", file=f)
1446 print("</svg>", file=f)
1448 image_linked_tag = "<image transform='translate({pos})' width='{width:.6f}' height='{height:.6f}' xlink:href='{path}'/>"
1449 image_embedded_tag = "<image transform='translate({pos})' width='{width:.6f}' height='{height:.6f}' xlink:href='data:image/png;base64,"
1450 text_tag = "<text transform='translate({x} {y})' style='font-size:{size:.2f}'><tspan>{label}</tspan></text>"
1451 text_transformed_tag = "<text transform='matrix({mat} {pos})' style='font-size:{size:.2f}'><tspan>{label}</tspan></text>"
1452 arrow_marker_tag = "<g><path transform='matrix({mat} {arrow_pos})' class='arrow' d='M 0 0 L 1 1 L 0 0.25 L -1 1 Z'/>" \
1453 "<text transform='translate({pos})' style='font-size:{scale:.2f}'><tspan>{index}</tspan></text></g>"
1455 svg_base = """<?xml version='1.0' encoding='UTF-8' standalone='no'?>
1456 <svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.1'
1457 width='{width:.2f}mm' height='{height:.2f}mm' viewBox='0 0 {width:.2f} {height:.2f}'>"""
1459 css_base = """<style type="text/css">
1460 path {{
1461 fill: none;
1462 stroke-linecap: butt;
1463 stroke-linejoin: bevel;
1464 stroke-dasharray: none;
1466 path.outer {{
1467 stroke: {outer_color};
1468 stroke-dasharray: {outer_style};
1469 stroke-dashoffset: 0;
1470 stroke-width: {outer_width:.2};
1471 stroke-opacity: {outer_alpha:.2};
1473 path.convex {{
1474 stroke: {convex_color};
1475 stroke-dasharray: {convex_style};
1476 stroke-dashoffset:0;
1477 stroke-width:{convex_width:.2};
1478 stroke-opacity: {convex_alpha:.2}
1480 path.concave {{
1481 stroke: {concave_color};
1482 stroke-dasharray: {concave_style};
1483 stroke-dashoffset: 0;
1484 stroke-width: {concave_width:.2};
1485 stroke-opacity: {concave_alpha:.2}
1487 path.freestyle {{
1488 stroke: {freestyle_color};
1489 stroke-dasharray: {freestyle_style};
1490 stroke-dashoffset: 0;
1491 stroke-width: {freestyle_width:.2};
1492 stroke-opacity: {freestyle_alpha:.2}
1494 path.outer_background {{
1495 stroke: {outbg_color};
1496 stroke-opacity: {outbg_alpha};
1497 stroke-width: {outbg_width:.2}
1499 path.inner_background {{
1500 stroke: {inbg_color};
1501 stroke-opacity: {inbg_alpha};
1502 stroke-width: {inbg_width:.2}
1504 path.sticker {{
1505 fill: {sticker_fill};
1506 stroke: none;
1507 fill-opacity: {sticker_alpha:.2};
1509 path.arrow {{
1510 fill: {text_color};
1512 text {{
1513 font-style: normal;
1514 fill: {text_color};
1515 fill-opacity: {text_alpha:.2};
1516 stroke: none;
1518 text, tspan {{
1519 text-anchor:middle;
1521 </style>"""
1524 class PDF:
1525 """Simple PDF exporter"""
1527 mm_to_pt = 72 / 25.4
1528 character_width_packed = {
1529 191: "'", 222: 'ijl\x82\x91\x92', 278: '|¦\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !,./:;I[\\]ft\xa0·ÌÍÎÏìíîï',
1530 333: '()-`r\x84\x88\x8b\x93\x94\x98\x9b¡¨\xad¯²³´¸¹{}', 350: '\x7f\x81\x8d\x8f\x90\x95\x9d', 365: '"ºª*°', 469: '^', 500: 'Jcksvxyz\x9a\x9eçýÿ', 584: '¶+<=>~¬±×÷', 611: 'FTZ\x8e¿ßø',
1531 667: '&ABEKPSVXY\x8a\x9fÀÁÂÃÄÅÈÉÊËÝÞ', 722: 'CDHNRUwÇÐÑÙÚÛÜ', 737: '©®', 778: 'GOQÒÓÔÕÖØ', 833: 'Mm¼½¾', 889: '%æ', 944: 'W\x9c', 1000: '\x85\x89\x8c\x97\x99Æ', 1015: '@', }
1532 character_width = {c: value for (value, chars) in character_width_packed.items() for c in chars}
1534 def __init__(self, page_size: M.Vector, style, margin, pure_net=True, angle_epsilon=0.01):
1535 self.page_size = page_size
1536 self.style = style
1537 self.margin = M.Vector((margin, margin))
1538 self.pure_net = pure_net
1539 self.angle_epsilon = angle_epsilon
1541 def text_width(self, text, scale=None):
1542 return (scale or self.text_size) * sum(self.character_width.get(c, 556) for c in text) / 1000
1544 @classmethod
1545 def encode_image(cls, bpy_image):
1546 data = bytes(int(255 * px) for (i, px) in enumerate(bpy_image.pixels) if i % 4 != 3)
1547 image = {
1548 "Type": "XObject", "Subtype": "Image", "Width": bpy_image.size[0], "Height": bpy_image.size[1],
1549 "ColorSpace": "DeviceRGB", "BitsPerComponent": 8, "Interpolate": True,
1550 "Filter": ["ASCII85Decode", "FlateDecode"], "stream": data}
1551 return image
1553 def write(self, mesh, filename):
1554 def format_dict(obj, refs=tuple()):
1555 return "<< " + "".join("/{} {}\n".format(key, format_value(value, refs)) for (key, value) in obj.items()) + ">>"
1557 def line_through(seq):
1558 return "".join("{0.x:.6f} {0.y:.6f} {1} ".format(1000*v.co, c) for (v, c) in zip(seq, chain("m", repeat("l"))))
1560 def format_value(value, refs=tuple()):
1561 if value in refs:
1562 return "{} 0 R".format(refs.index(value) + 1)
1563 elif type(value) is dict:
1564 return format_dict(value, refs)
1565 elif type(value) in (list, tuple):
1566 return "[ " + " ".join(format_value(item, refs) for item in value) + " ]"
1567 elif type(value) is int:
1568 return str(value)
1569 elif type(value) is float:
1570 return "{:.6f}".format(value)
1571 elif type(value) is bool:
1572 return "true" if value else "false"
1573 else:
1574 return "/{}".format(value) # this script can output only PDF names, no strings
1576 def write_object(index, obj, refs, f, stream=None):
1577 byte_count = f.write("{} 0 obj\n".format(index))
1578 if type(obj) is not dict:
1579 stream, obj = obj, dict()
1580 elif "stream" in obj:
1581 stream = obj.pop("stream")
1582 if stream:
1583 if True or type(stream) is bytes:
1584 obj["Filter"] = ["ASCII85Decode", "FlateDecode"]
1585 stream = encode(stream)
1586 obj["Length"] = len(stream)
1587 byte_count += f.write(format_dict(obj, refs))
1588 if stream:
1589 byte_count += f.write("\nstream\n")
1590 byte_count += f.write(stream)
1591 byte_count += f.write("\nendstream")
1592 return byte_count + f.write("\nendobj\n")
1594 def encode(data):
1595 from base64 import a85encode
1596 from zlib import compress
1597 if hasattr(data, "encode"):
1598 data = data.encode()
1599 return a85encode(compress(data), adobe=True, wrapcol=250)[2:].decode()
1601 page_size_pt = 1000 * self.mm_to_pt * self.page_size
1602 root = {"Type": "Pages", "MediaBox": [0, 0, page_size_pt.x, page_size_pt.y], "Kids": list()}
1603 catalog = {"Type": "Catalog", "Pages": root}
1604 font = {
1605 "Type": "Font", "Subtype": "Type1", "Name": "F1",
1606 "BaseFont": "Helvetica", "Encoding": "MacRomanEncoding"}
1608 dl = [length * self.style.line_width * 1000 for length in (1, 4, 9)]
1609 format_style = {
1610 'SOLID': list(), 'DOT': [dl[0], dl[1]], 'DASH': [dl[1], dl[2]],
1611 'LONGDASH': [dl[2], dl[1]], 'DASHDOT': [dl[2], dl[1], dl[0], dl[1]]}
1612 styles = {
1613 "Gtext": {"ca": self.style.text_color[3], "Font": [font, 1000 * self.text_size]},
1614 "Gsticker": {"ca": self.style.sticker_fill[3]}}
1615 for name in ("outer", "convex", "concave", "freestyle"):
1616 gs = {
1617 "LW": self.style.line_width * 1000 * getattr(self.style, name + "_width"),
1618 "CA": getattr(self.style, name + "_color")[3],
1619 "D": [format_style[getattr(self.style, name + "_style")], 0]}
1620 styles["G" + name] = gs
1621 for name in ("outbg", "inbg"):
1622 gs = {
1623 "LW": self.style.line_width * 1000 * getattr(self.style, name + "_width"),
1624 "CA": getattr(self.style, name + "_color")[3],
1625 "D": [format_style['SOLID'], 0]}
1626 styles["G" + name] = gs
1628 objects = [root, catalog, font]
1629 objects.extend(styles.values())
1631 for page in mesh.pages:
1632 commands = ["{0:.6f} 0 0 {0:.6f} 0 0 cm".format(self.mm_to_pt)]
1633 resources = {"Font": {"F1": font}, "ExtGState": styles, "XObject": dict()}
1634 for island in page.islands:
1635 commands.append("q 1 0 0 1 {0.x:.6f} {0.y:.6f} cm".format(1000*(self.margin + island.pos)))
1636 if island.embedded_image:
1637 identifier = "Im{}".format(len(resources["XObject"]) + 1)
1638 commands.append(self.command_image.format(1000 * island.bounding_box, identifier))
1639 objects.append(island.embedded_image)
1640 resources["XObject"][identifier] = island.embedded_image
1642 if island.title:
1643 commands.append(self.command_label.format(
1644 size=1000*self.text_size,
1645 x=500 * (island.bounding_box.x - self.text_width(island.title)),
1646 y=1000 * 0.2 * self.text_size,
1647 label=island.title))
1649 data_markers, data_stickerfill, data_outer, data_convex, data_concave, data_freestyle = (list() for i in range(6))
1650 for marker in island.markers:
1651 if isinstance(marker, Sticker):
1652 data_stickerfill.append(line_through(marker.vertices) + "f")
1653 if marker.text:
1654 data_markers.append(self.command_sticker.format(
1655 label=marker.text,
1656 pos=1000*marker.center,
1657 mat=marker.rot,
1658 align=-500 * self.text_width(marker.text, marker.width),
1659 size=1000*marker.width))
1660 elif isinstance(marker, Arrow):
1661 size = 1000 * marker.size
1662 position = 1000 * (marker.center + marker.size * marker.rot @ M.Vector((0, -0.9)))
1663 data_markers.append(self.command_arrow.format(
1664 index=marker.text,
1665 arrow_pos=1000 * marker.center,
1666 pos=position - 1000 * M.Vector((0.5 * self.text_width(marker.text), 0.4 * self.text_size)),
1667 mat=size * marker.rot,
1668 size=size))
1669 elif isinstance(marker, NumberAlone):
1670 data_markers.append(self.command_number.format(
1671 label=marker.text,
1672 pos=1000*marker.center,
1673 mat=marker.rot,
1674 size=1000*marker.size))
1676 outer_edges = set(island.boundary)
1677 while outer_edges:
1678 data_loop = list()
1679 uvedge = outer_edges.pop()
1680 while 1:
1681 if uvedge.sticker:
1682 data_loop.extend(uvedge.sticker.vertices[1:])
1683 else:
1684 vertex = uvedge.vb if uvedge.uvface.flipped else uvedge.va
1685 data_loop.append(vertex)
1686 uvedge = uvedge.neighbor_right
1687 try:
1688 outer_edges.remove(uvedge)
1689 except KeyError:
1690 break
1691 data_outer.append(line_through(data_loop) + "s")
1693 for loop, uvedge in island.edges.items():
1694 edge = mesh.edges[loop.edge]
1695 if edge.is_cut(uvedge.uvface.face) and not uvedge.sticker:
1696 continue
1697 data_uvedge = line_through((uvedge.va, uvedge.vb)) + "S"
1698 if edge.freestyle:
1699 data_freestyle.append(data_uvedge)
1700 # each uvedge exists in two opposite-oriented variants; we want to add each only once
1701 if uvedge.sticker or uvedge.uvface.flipped != (id(uvedge.va) > id(uvedge.vb)):
1702 if edge.angle > self.angle_epsilon:
1703 data_convex.append(data_uvedge)
1704 elif edge.angle < -self.angle_epsilon:
1705 data_concave.append(data_uvedge)
1706 if island.is_inside_out:
1707 data_convex, data_concave = data_concave, data_convex
1709 if data_stickerfill and self.style.sticker_fill[3] > 0:
1710 commands.append("/Gsticker gs {0[0]:.3f} {0[1]:.3f} {0[2]:.3f} rg".format(self.style.sticker_fill))
1711 commands.extend(data_stickerfill)
1712 if data_freestyle:
1713 commands.append("/Gfreestyle gs {0[0]:.3f} {0[1]:.3f} {0[2]:.3f} RG".format(self.style.freestyle_color))
1714 commands.extend(data_freestyle)
1715 if (data_convex or data_concave) and not self.pure_net and self.style.use_inbg:
1716 commands.append("/Ginbg gs {0[0]:.3f} {0[1]:.3f} {0[2]:.3f} RG".format(self.style.inbg_color))
1717 commands.extend(chain(data_convex, data_concave))
1718 if data_convex:
1719 commands.append("/Gconvex gs {0[0]:.3f} {0[1]:.3f} {0[2]:.3f} RG".format(self.style.convex_color))
1720 commands.extend(data_convex)
1721 if data_concave:
1722 commands.append("/Gconcave gs {0[0]:.3f} {0[1]:.3f} {0[2]:.3f} RG".format(self.style.concave_color))
1723 commands.extend(data_concave)
1724 if data_outer:
1725 if not self.pure_net and self.style.use_outbg:
1726 commands.append("/Goutbg gs {0[0]:.3f} {0[1]:.3f} {0[2]:.3f} RG".format(self.style.outbg_color))
1727 commands.extend(data_outer)
1728 commands.append("/Gouter gs {0[0]:.3f} {0[1]:.3f} {0[2]:.3f} RG".format(self.style.outer_color))
1729 commands.extend(data_outer)
1730 commands.append("/Gtext gs {0[0]:.3f} {0[1]:.3f} {0[2]:.3f} rg".format(self.style.text_color))
1731 commands.extend(data_markers)
1732 commands.append("Q")
1733 content = "\n".join(commands)
1734 page = {"Type": "Page", "Parent": root, "Contents": content, "Resources": resources}
1735 root["Kids"].append(page)
1736 objects.extend((page, content))
1738 root["Count"] = len(root["Kids"])
1739 with open(filename, "w+") as f:
1740 xref_table = list()
1741 position = f.write("%PDF-1.4\n")
1742 for index, obj in enumerate(objects, 1):
1743 xref_table.append(position)
1744 position += write_object(index, obj, objects, f)
1745 xref_pos = position
1746 f.write("xref_table\n0 {}\n".format(len(xref_table) + 1))
1747 f.write("{:010} {:05} f\n".format(0, 65536))
1748 for position in xref_table:
1749 f.write("{:010} {:05} n\n".format(position, 0))
1750 f.write("trailer\n")
1751 f.write(format_dict({"Size": len(xref_table), "Root": catalog}, objects))
1752 f.write("\nstartxref\n{}\n%%EOF\n".format(xref_pos))
1754 command_label = "/Gtext gs BT {x:.6f} {y:.6f} Td ({label}) Tj ET"
1755 command_image = "q {0.x:.6f} 0 0 {0.y:.6f} 0 0 cm 1 0 0 -1 0 1 cm /{1} Do Q"
1756 command_sticker = "q {mat[0][0]:.6f} {mat[1][0]:.6f} {mat[0][1]:.6f} {mat[1][1]:.6f} {pos.x:.6f} {pos.y:.6f} cm BT {align:.6f} 0 Td /F1 {size:.6f} Tf ({label}) Tj ET Q"
1757 command_arrow = "q BT {pos.x:.6f} {pos.y:.6f} Td /F1 {size:.6f} Tf ({index}) Tj ET {mat[0][0]:.6f} {mat[1][0]:.6f} {mat[0][1]:.6f} {mat[1][1]:.6f} {arrow_pos.x:.6f} {arrow_pos.y:.6f} cm 0 0 m 1 -1 l 0 -0.25 l -1 -1 l f Q"
1758 command_number = "q {mat[0][0]:.6f} {mat[1][0]:.6f} {mat[0][1]:.6f} {mat[1][1]:.6f} {pos.x:.6f} {pos.y:.6f} cm BT /F1 {size:.6f} Tf ({label}) Tj ET Q"
1761 class Unfold(bpy.types.Operator):
1762 """Blender Operator: unfold the selected object."""
1764 bl_idname = "mesh.unfold"
1765 bl_label = "Unfold"
1766 bl_description = "Mark seams so that the mesh can be exported as a paper model"
1767 bl_options = {'REGISTER', 'UNDO'}
1768 edit: bpy.props.BoolProperty(default=False, options={'HIDDEN'})
1769 priority_effect_convex: bpy.props.FloatProperty(
1770 name="Priority Convex", description="Priority effect for edges in convex angles",
1771 default=default_priority_effect['CONVEX'], soft_min=-1, soft_max=10, subtype='FACTOR')
1772 priority_effect_concave: bpy.props.FloatProperty(
1773 name="Priority Concave", description="Priority effect for edges in concave angles",
1774 default=default_priority_effect['CONCAVE'], soft_min=-1, soft_max=10, subtype='FACTOR')
1775 priority_effect_length: bpy.props.FloatProperty(
1776 name="Priority Length", description="Priority effect of edge length",
1777 default=default_priority_effect['LENGTH'], soft_min=-10, soft_max=1, subtype='FACTOR')
1778 do_create_uvmap: bpy.props.BoolProperty(
1779 name="Create UVMap", description="Create a new UV Map showing the islands and page layout", default=False)
1780 object = None
1782 @classmethod
1783 def poll(cls, context):
1784 return context.active_object and context.active_object.type == "MESH"
1786 def draw(self, context):
1787 layout = self.layout
1788 col = layout.column()
1789 col.active = not self.object or len(self.object.data.uv_layers) < 8
1790 col.prop(self.properties, "do_create_uvmap")
1791 layout.label(text="Edge Cutting Factors:")
1792 col = layout.column(align=True)
1793 col.label(text="Face Angle:")
1794 col.prop(self.properties, "priority_effect_convex", text="Convex")
1795 col.prop(self.properties, "priority_effect_concave", text="Concave")
1796 layout.prop(self.properties, "priority_effect_length", text="Edge Length")
1798 def execute(self, context):
1799 sce = bpy.context.scene
1800 settings = sce.paper_model
1801 recall_mode = context.object.mode
1802 bpy.ops.object.mode_set(mode='EDIT')
1804 self.object = context.object
1806 cage_size = M.Vector((settings.output_size_x, settings.output_size_y))
1807 priority_effect = {
1808 'CONVEX': self.priority_effect_convex,
1809 'CONCAVE': self.priority_effect_concave,
1810 'LENGTH': self.priority_effect_length}
1811 try:
1812 unfolder = Unfolder(self.object)
1813 unfolder.do_create_uvmap = self.do_create_uvmap
1814 scale = sce.unit_settings.scale_length / settings.scale
1815 unfolder.prepare(cage_size, priority_effect, scale, settings.limit_by_page)
1816 unfolder.mesh.mark_cuts()
1817 except UnfoldError as error:
1818 self.report(type={'ERROR_INVALID_INPUT'}, message=error.args[0])
1819 error.mesh_select()
1820 bpy.ops.object.mode_set(mode=recall_mode)
1821 return {'CANCELLED'}
1822 mesh = self.object.data
1823 mesh.update()
1824 if mesh.paper_island_list:
1825 unfolder.copy_island_names(mesh.paper_island_list)
1826 island_list = mesh.paper_island_list
1827 attributes = {item.label: (item.abbreviation, item.auto_label, item.auto_abbrev) for item in island_list}
1828 island_list.clear() # remove previously defined islands
1829 for island in unfolder.mesh.islands:
1830 # add islands to UI list and set default descriptions
1831 list_item = island_list.add()
1832 # add faces' IDs to the island
1833 for face in island.faces:
1834 lface = list_item.faces.add()
1835 lface.id = face.index
1836 list_item["label"] = island.label
1837 list_item["abbreviation"], list_item["auto_label"], list_item["auto_abbrev"] = attributes.get(
1838 island.label,
1839 (island.abbreviation, True, True))
1840 island_item_changed(list_item, context)
1841 mesh.paper_island_index = -1
1843 del unfolder
1844 bpy.ops.object.mode_set(mode=recall_mode)
1845 return {'FINISHED'}
1848 class ClearAllSeams(bpy.types.Operator):
1849 """Blender Operator: clear all seams of the active Mesh and all its unfold data"""
1851 bl_idname = "mesh.clear_all_seams"
1852 bl_label = "Clear All Seams"
1853 bl_description = "Clear all the seams and unfolded islands of the active object"
1855 @classmethod
1856 def poll(cls, context):
1857 return context.active_object and context.active_object.type == 'MESH'
1859 def execute(self, context):
1860 ob = context.active_object
1861 mesh = ob.data
1863 for edge in mesh.edges:
1864 edge.use_seam = False
1865 mesh.paper_island_list.clear()
1867 return {'FINISHED'}
1870 def page_size_preset_changed(self, context):
1871 """Update the actual document size to correct values"""
1872 if hasattr(self, "limit_by_page") and not self.limit_by_page:
1873 return
1874 if self.page_size_preset == 'A4':
1875 self.output_size_x = 0.210
1876 self.output_size_y = 0.297
1877 elif self.page_size_preset == 'A3':
1878 self.output_size_x = 0.297
1879 self.output_size_y = 0.420
1880 elif self.page_size_preset == 'US_LETTER':
1881 self.output_size_x = 0.216
1882 self.output_size_y = 0.279
1883 elif self.page_size_preset == 'US_LEGAL':
1884 self.output_size_x = 0.216
1885 self.output_size_y = 0.356
1888 class PaperModelStyle(bpy.types.PropertyGroup):
1889 line_styles = [
1890 ('SOLID', "Solid (----)", "Solid line"),
1891 ('DOT', "Dots (. . .)", "Dotted line"),
1892 ('DASH', "Short Dashes (- - -)", "Solid line"),
1893 ('LONGDASH', "Long Dashes (-- --)", "Solid line"),
1894 ('DASHDOT', "Dash-dotted (-- .)", "Solid line")
1896 outer_color: bpy.props.FloatVectorProperty(
1897 name="Outer Lines", description="Color of net outline",
1898 default=(0.0, 0.0, 0.0, 1.0), min=0, max=1, subtype='COLOR', size=4)
1899 outer_style: bpy.props.EnumProperty(
1900 name="Outer Lines Drawing Style", description="Drawing style of net outline",
1901 default='SOLID', items=line_styles)
1902 line_width: bpy.props.FloatProperty(
1903 name="Base Lines Thickness", description="Base thickness of net lines, each actual value is a multiple of this length",
1904 default=1e-4, min=0, soft_max=5e-3, precision=5, step=1e-2, subtype="UNSIGNED", unit="LENGTH")
1905 outer_width: bpy.props.FloatProperty(
1906 name="Outer Lines Thickness", description="Relative thickness of net outline",
1907 default=3, min=0, soft_max=10, precision=1, step=10, subtype='FACTOR')
1908 use_outbg: bpy.props.BoolProperty(
1909 name="Highlight Outer Lines", description="Add another line below every line to improve contrast",
1910 default=True)
1911 outbg_color: bpy.props.FloatVectorProperty(
1912 name="Outer Highlight", description="Color of the highlight for outer lines",
1913 default=(1.0, 1.0, 1.0, 1.0), min=0, max=1, subtype='COLOR', size=4)
1914 outbg_width: bpy.props.FloatProperty(
1915 name="Outer Highlight Thickness", description="Relative thickness of the highlighting lines",
1916 default=5, min=0, soft_max=10, precision=1, step=10, subtype='FACTOR')
1918 convex_color: bpy.props.FloatVectorProperty(
1919 name="Inner Convex Lines", description="Color of lines to be folded to a convex angle",
1920 default=(0.0, 0.0, 0.0, 1.0), min=0, max=1, subtype='COLOR', size=4)
1921 convex_style: bpy.props.EnumProperty(
1922 name="Convex Lines Drawing Style", description="Drawing style of lines to be folded to a convex angle",
1923 default='DASH', items=line_styles)
1924 convex_width: bpy.props.FloatProperty(
1925 name="Convex Lines Thickness", description="Relative thickness of concave lines",
1926 default=2, min=0, soft_max=10, precision=1, step=10, subtype='FACTOR')
1927 concave_color: bpy.props.FloatVectorProperty(
1928 name="Inner Concave Lines", description="Color of lines to be folded to a concave angle",
1929 default=(0.0, 0.0, 0.0, 1.0), min=0, max=1, subtype='COLOR', size=4)
1930 concave_style: bpy.props.EnumProperty(
1931 name="Concave Lines Drawing Style", description="Drawing style of lines to be folded to a concave angle",
1932 default='DASHDOT', items=line_styles)
1933 concave_width: bpy.props.FloatProperty(
1934 name="Concave Lines Thickness", description="Relative thickness of concave lines",
1935 default=2, min=0, soft_max=10, precision=1, step=10, subtype='FACTOR')
1936 freestyle_color: bpy.props.FloatVectorProperty(
1937 name="Freestyle Edges", description="Color of lines marked as Freestyle Edge",
1938 default=(0.0, 0.0, 0.0, 1.0), min=0, max=1, subtype='COLOR', size=4)
1939 freestyle_style: bpy.props.EnumProperty(
1940 name="Freestyle Edges Drawing Style", description="Drawing style of Freestyle Edges",
1941 default='SOLID', items=line_styles)
1942 freestyle_width: bpy.props.FloatProperty(
1943 name="Freestyle Edges Thickness", description="Relative thickness of Freestyle edges",
1944 default=2, min=0, soft_max=10, precision=1, step=10, subtype='FACTOR')
1945 use_inbg: bpy.props.BoolProperty(
1946 name="Highlight Inner Lines", description="Add another line below every line to improve contrast",
1947 default=True)
1948 inbg_color: bpy.props.FloatVectorProperty(
1949 name="Inner Highlight", description="Color of the highlight for inner lines",
1950 default=(1.0, 1.0, 1.0, 1.0), min=0, max=1, subtype='COLOR', size=4)
1951 inbg_width: bpy.props.FloatProperty(
1952 name="Inner Highlight Thickness", description="Relative thickness of the highlighting lines",
1953 default=2, min=0, soft_max=10, precision=1, step=10, subtype='FACTOR')
1955 sticker_fill: bpy.props.FloatVectorProperty(
1956 name="Tabs Fill", description="Fill color of sticking tabs",
1957 default=(0.9, 0.9, 0.9, 1.0), min=0, max=1, subtype='COLOR', size=4)
1958 text_color: bpy.props.FloatVectorProperty(
1959 name="Text Color", description="Color of all text used in the document",
1960 default=(0.0, 0.0, 0.0, 1.0), min=0, max=1, subtype='COLOR', size=4)
1961 bpy.utils.register_class(PaperModelStyle)
1964 class ExportPaperModel(bpy.types.Operator):
1965 """Blender Operator: save the selected object's net and optionally bake its texture"""
1967 bl_idname = "export_mesh.paper_model"
1968 bl_label = "Export Paper Model"
1969 bl_description = "Export the selected object's net and optionally bake its texture"
1970 filepath: bpy.props.StringProperty(
1971 name="File Path", description="Target file to save the SVG", options={'SKIP_SAVE'})
1972 filename: bpy.props.StringProperty(
1973 name="File Name", description="Name of the file", options={'SKIP_SAVE'})
1974 directory: bpy.props.StringProperty(
1975 name="Directory", description="Directory of the file", options={'SKIP_SAVE'})
1976 page_size_preset: bpy.props.EnumProperty(
1977 name="Page Size", description="Size of the exported document",
1978 default='A4', update=page_size_preset_changed, items=global_paper_sizes)
1979 output_size_x: bpy.props.FloatProperty(
1980 name="Page Width", description="Width of the exported document",
1981 default=0.210, soft_min=0.105, soft_max=0.841, subtype="UNSIGNED", unit="LENGTH")
1982 output_size_y: bpy.props.FloatProperty(
1983 name="Page Height", description="Height of the exported document",
1984 default=0.297, soft_min=0.148, soft_max=1.189, subtype="UNSIGNED", unit="LENGTH")
1985 output_margin: bpy.props.FloatProperty(
1986 name="Page Margin", description="Distance from page borders to the printable area",
1987 default=0.005, min=0, soft_max=0.1, step=0.1, subtype="UNSIGNED", unit="LENGTH")
1988 output_type: bpy.props.EnumProperty(
1989 name="Textures", description="Source of a texture for the model",
1990 default='NONE', items=[
1991 ('NONE', "No Texture", "Export the net only"),
1992 ('TEXTURE', "From Materials", "Render the diffuse color and all painted textures"),
1993 ('AMBIENT_OCCLUSION', "Ambient Occlusion", "Render the Ambient Occlusion pass"),
1994 ('RENDER', "Full Render", "Render the material in actual scene illumination"),
1995 ('SELECTED_TO_ACTIVE', "Selected to Active", "Render all selected surrounding objects as a texture")
1997 do_create_stickers: bpy.props.BoolProperty(
1998 name="Create Tabs", description="Create gluing tabs around the net (useful for paper)",
1999 default=True)
2000 do_create_numbers: bpy.props.BoolProperty(
2001 name="Create Numbers", description="Enumerate edges to make it clear which edges should be sticked together",
2002 default=True)
2003 sticker_width: bpy.props.FloatProperty(
2004 name="Tabs and Text Size", description="Width of gluing tabs and their numbers",
2005 default=0.005, soft_min=0, soft_max=0.05, step=0.1, subtype="UNSIGNED", unit="LENGTH")
2006 angle_epsilon: bpy.props.FloatProperty(
2007 name="Hidden Edge Angle", description="Folds with angle below this limit will not be drawn",
2008 default=pi/360, min=0, soft_max=pi/4, step=0.01, subtype="ANGLE", unit="ROTATION")
2009 output_dpi: bpy.props.FloatProperty(
2010 name="Resolution (DPI)", description="Resolution of images in pixels per inch",
2011 default=90, min=1, soft_min=30, soft_max=600, subtype="UNSIGNED")
2012 bake_samples: bpy.props.IntProperty(
2013 name="Samples", description="Number of samples to render for each pixel",
2014 default=64, min=1, subtype="UNSIGNED")
2015 file_format: bpy.props.EnumProperty(
2016 name="Document Format", description="File format of the exported net",
2017 default='PDF', items=[
2018 ('PDF', "PDF", "Adobe Portable Document Format 1.4"),
2019 ('SVG', "SVG", "W3C Scalable Vector Graphics"),
2021 image_packing: bpy.props.EnumProperty(
2022 name="Image Packing Method", description="Method of attaching baked image(s) to the SVG",
2023 default='ISLAND_EMBED', items=[
2024 ('PAGE_LINK', "Single Linked", "Bake one image per page of output and save it separately"),
2025 ('ISLAND_LINK', "Linked", "Bake images separately for each island and save them in a directory"),
2026 ('ISLAND_EMBED', "Embedded", "Bake images separately for each island and embed them into the SVG")
2028 scale: bpy.props.FloatProperty(
2029 name="Scale", description="Divisor of all dimensions when exporting",
2030 default=1, soft_min=1.0, soft_max=10000.0, step=100, subtype='UNSIGNED', precision=1)
2031 do_create_uvmap: bpy.props.BoolProperty(
2032 name="Create UVMap", description="Create a new UV Map showing the islands and page layout",
2033 default=False, options={'SKIP_SAVE'})
2034 ui_expanded_document: bpy.props.BoolProperty(
2035 name="Show Document Settings Expanded", description="Shows the box 'Document Settings' expanded in user interface",
2036 default=True, options={'SKIP_SAVE'})
2037 ui_expanded_style: bpy.props.BoolProperty(
2038 name="Show Style Settings Expanded", description="Shows the box 'Colors and Style' expanded in user interface",
2039 default=False, options={'SKIP_SAVE'})
2040 style: bpy.props.PointerProperty(type=PaperModelStyle)
2042 unfolder = None
2044 @classmethod
2045 def poll(cls, context):
2046 return context.active_object and context.active_object.type == 'MESH'
2048 def prepare(self, context):
2049 sce = context.scene
2050 self.recall_mode = context.object.mode
2051 bpy.ops.object.mode_set(mode='EDIT')
2053 self.object = context.active_object
2054 self.unfolder = Unfolder(self.object)
2055 cage_size = M.Vector((sce.paper_model.output_size_x, sce.paper_model.output_size_y))
2056 self.unfolder.prepare(cage_size, scale=sce.unit_settings.scale_length/self.scale, limit_by_page=sce.paper_model.limit_by_page)
2057 if self.scale == 1:
2058 self.scale = ceil(self.get_scale_ratio(sce))
2060 def recall(self):
2061 if self.unfolder:
2062 del self.unfolder
2063 bpy.ops.object.mode_set(mode=self.recall_mode)
2065 def invoke(self, context, event):
2066 self.scale = context.scene.paper_model.scale
2067 try:
2068 self.prepare(context)
2069 except UnfoldError as error:
2070 self.report(type={'ERROR_INVALID_INPUT'}, message=error.args[0])
2071 error.mesh_select()
2072 self.recall()
2073 return {'CANCELLED'}
2074 wm = context.window_manager
2075 wm.fileselect_add(self)
2076 return {'RUNNING_MODAL'}
2078 def execute(self, context):
2079 if not self.unfolder:
2080 self.prepare(context)
2081 self.unfolder.do_create_uvmap = self.do_create_uvmap
2082 try:
2083 if self.object.data.paper_island_list:
2084 self.unfolder.copy_island_names(self.object.data.paper_island_list)
2085 self.unfolder.save(self.properties)
2086 self.report({'INFO'}, "Saved a {}-page document".format(len(self.unfolder.mesh.pages)))
2087 return {'FINISHED'}
2088 except UnfoldError as error:
2089 self.report(type={'ERROR_INVALID_INPUT'}, message=error.args[0])
2090 return {'CANCELLED'}
2091 finally:
2092 self.recall()
2094 def get_scale_ratio(self, sce):
2095 margin = self.output_margin + self.sticker_width
2096 if min(self.output_size_x, self.output_size_y) <= 2 * margin:
2097 return False
2098 output_inner_size = M.Vector((self.output_size_x - 2*margin, self.output_size_y - 2*margin))
2099 ratio = self.unfolder.mesh.largest_island_ratio(output_inner_size)
2100 return ratio * sce.unit_settings.scale_length / self.scale
2102 def draw(self, context):
2103 layout = self.layout
2105 layout.prop(self.properties, "do_create_uvmap")
2107 row = layout.row(align=True)
2108 row.menu("VIEW3D_MT_paper_model_presets", text=bpy.types.VIEW3D_MT_paper_model_presets.bl_label)
2109 row.operator("export_mesh.paper_model_preset_add", text="", icon='ADD')
2110 row.operator("export_mesh.paper_model_preset_add", text="", icon='REMOVE').remove_active = True
2112 # a little hack: this prints out something like "Scale: 1: 72"
2113 layout.prop(self.properties, "scale", text="Scale: 1")
2114 scale_ratio = self.get_scale_ratio(context.scene)
2115 if scale_ratio > 1:
2116 layout.label(
2117 text="An island is roughly {:.1f}x bigger than page".format(scale_ratio),
2118 icon="ERROR")
2119 elif scale_ratio > 0:
2120 layout.label(text="Largest island is roughly 1/{:.1f} of page".format(1 / scale_ratio))
2122 if context.scene.unit_settings.scale_length != 1:
2123 layout.label(
2124 text="Unit scale {:.1f} makes page size etc. not display correctly".format(
2125 context.scene.unit_settings.scale_length), icon="ERROR")
2126 box = layout.box()
2127 row = box.row(align=True)
2128 row.prop(
2129 self.properties, "ui_expanded_document", text="",
2130 icon=('TRIA_DOWN' if self.ui_expanded_document else 'TRIA_RIGHT'), emboss=False)
2131 row.label(text="Document Settings")
2133 if self.ui_expanded_document:
2134 box.prop(self.properties, "file_format", text="Format")
2135 box.prop(self.properties, "page_size_preset")
2136 col = box.column(align=True)
2137 col.active = self.page_size_preset == 'USER'
2138 col.prop(self.properties, "output_size_x")
2139 col.prop(self.properties, "output_size_y")
2140 box.prop(self.properties, "output_margin")
2141 col = box.column()
2142 col.prop(self.properties, "do_create_stickers")
2143 col.prop(self.properties, "do_create_numbers")
2144 col = box.column()
2145 col.active = self.do_create_stickers or self.do_create_numbers
2146 col.prop(self.properties, "sticker_width")
2147 box.prop(self.properties, "angle_epsilon")
2149 box.prop(self.properties, "output_type")
2150 col = box.column()
2151 col.active = (self.output_type != 'NONE')
2152 if len(self.object.data.uv_layers) == 8:
2153 col.label(text="No UV slots left, No Texture is the only option.", icon='ERROR')
2154 elif context.scene.render.engine != 'CYCLES' and self.output_type != 'NONE':
2155 col.label(text="Cycles will be used for texture baking.", icon='ERROR')
2156 row = col.row()
2157 row.active = self.output_type in ('AMBIENT_OCCLUSION', 'RENDER', 'SELECTED_TO_ACTIVE')
2158 row.prop(self.properties, "bake_samples")
2159 col.prop(self.properties, "output_dpi")
2160 row = col.row()
2161 row.active = self.file_format == 'SVG'
2162 row.prop(self.properties, "image_packing", text="Images")
2164 box = layout.box()
2165 row = box.row(align=True)
2166 row.prop(
2167 self.properties, "ui_expanded_style", text="",
2168 icon=('TRIA_DOWN' if self.ui_expanded_style else 'TRIA_RIGHT'), emboss=False)
2169 row.label(text="Colors and Style")
2171 if self.ui_expanded_style:
2172 box.prop(self.style, "line_width", text="Default line width")
2173 col = box.column()
2174 col.prop(self.style, "outer_color")
2175 col.prop(self.style, "outer_width", text="Relative width")
2176 col.prop(self.style, "outer_style", text="Style")
2177 col = box.column()
2178 col.active = self.output_type != 'NONE'
2179 col.prop(self.style, "use_outbg", text="Outer Lines Highlight:")
2180 sub = col.column()
2181 sub.active = self.output_type != 'NONE' and self.style.use_outbg
2182 sub.prop(self.style, "outbg_color", text="")
2183 sub.prop(self.style, "outbg_width", text="Relative width")
2184 col = box.column()
2185 col.prop(self.style, "convex_color")
2186 col.prop(self.style, "convex_width", text="Relative width")
2187 col.prop(self.style, "convex_style", text="Style")
2188 col = box.column()
2189 col.prop(self.style, "concave_color")
2190 col.prop(self.style, "concave_width", text="Relative width")
2191 col.prop(self.style, "concave_style", text="Style")
2192 col = box.column()
2193 col.prop(self.style, "freestyle_color")
2194 col.prop(self.style, "freestyle_width", text="Relative width")
2195 col.prop(self.style, "freestyle_style", text="Style")
2196 col = box.column()
2197 col.active = self.output_type != 'NONE'
2198 col.prop(self.style, "use_inbg", text="Inner Lines Highlight:")
2199 sub = col.column()
2200 sub.active = self.output_type != 'NONE' and self.style.use_inbg
2201 sub.prop(self.style, "inbg_color", text="")
2202 sub.prop(self.style, "inbg_width", text="Relative width")
2203 col = box.column()
2204 col.active = self.do_create_stickers
2205 col.prop(self.style, "sticker_fill")
2206 box.prop(self.style, "text_color")
2209 def menu_func_export(self, context):
2210 self.layout.operator("export_mesh.paper_model", text="Paper Model (.pdf/.svg)")
2213 def menu_func_unfold(self, context):
2214 self.layout.operator("mesh.unfold", text="Unfold")
2217 class SelectIsland(bpy.types.Operator):
2218 """Blender Operator: select all faces of the active island"""
2220 bl_idname = "mesh.select_paper_island"
2221 bl_label = "Select Island"
2222 bl_description = "Select an island of the paper model net"
2224 operation: bpy.props.EnumProperty(
2225 name="Operation", description="Operation with the current selection",
2226 default='ADD', items=[
2227 ('ADD', "Add", "Add to current selection"),
2228 ('REMOVE', "Remove", "Remove from selection"),
2229 ('REPLACE', "Replace", "Select only the ")
2232 @classmethod
2233 def poll(cls, context):
2234 return context.active_object and context.active_object.type == 'MESH' and context.mode == 'EDIT_MESH'
2236 def execute(self, context):
2237 ob = context.active_object
2238 me = ob.data
2239 bm = bmesh.from_edit_mesh(me)
2240 island = me.paper_island_list[me.paper_island_index]
2241 faces = {face.id for face in island.faces}
2242 edges = set()
2243 verts = set()
2244 if self.operation == 'REPLACE':
2245 for face in bm.faces:
2246 selected = face.index in faces
2247 face.select = selected
2248 if selected:
2249 edges.update(face.edges)
2250 verts.update(face.verts)
2251 for edge in bm.edges:
2252 edge.select = edge in edges
2253 for vert in bm.verts:
2254 vert.select = vert in verts
2255 else:
2256 selected = (self.operation == 'ADD')
2257 for index in faces:
2258 face = bm.faces[index]
2259 face.select = selected
2260 edges.update(face.edges)
2261 verts.update(face.verts)
2262 for edge in edges:
2263 edge.select = any(face.select for face in edge.link_faces)
2264 for vert in verts:
2265 vert.select = any(edge.select for edge in vert.link_edges)
2266 bmesh.update_edit_mesh(me, False, False)
2267 return {'FINISHED'}
2270 class VIEW3D_MT_paper_model_presets(bpy.types.Menu):
2271 bl_label = "Paper Model Presets"
2272 preset_subdir = "export_mesh"
2273 preset_operator = "script.execute_preset"
2274 draw = bpy.types.Menu.draw_preset
2277 class AddPresetPaperModel(bl_operators.presets.AddPresetBase, bpy.types.Operator):
2278 """Add or remove a Paper Model Preset"""
2279 bl_idname = "export_mesh.paper_model_preset_add"
2280 bl_label = "Add Paper Model Preset"
2281 preset_menu = "VIEW3D_MT_paper_model_presets"
2282 preset_subdir = "export_mesh"
2283 preset_defines = ["op = bpy.context.active_operator"]
2285 @property
2286 def preset_values(self):
2287 op = bpy.ops.export_mesh.paper_model
2288 properties = op.get_rna().bl_rna.properties.items()
2289 blacklist = bpy.types.Operator.bl_rna.properties.keys()
2290 return [
2291 "op.{}".format(prop_id) for (prop_id, prop) in properties
2292 if not (prop.is_hidden or prop.is_skip_save or prop_id in blacklist)]
2295 class VIEW3D_PT_paper_model_tools(bpy.types.Panel):
2296 bl_label = "Tools"
2297 bl_space_type = "VIEW_3D"
2298 bl_region_type = "TOOLS"
2299 bl_category = "Paper Model"
2301 def draw(self, context):
2302 layout = self.layout
2303 sce = context.scene
2304 obj = context.active_object
2305 mesh = obj.data if obj and obj.type == 'MESH' else None
2307 layout.operator("export_mesh.paper_model")
2309 col = layout.column(align=True)
2310 col.label(text="Customization:")
2311 col.operator("mesh.unfold")
2313 if context.mode == 'EDIT_MESH':
2314 row = layout.row(align=True)
2315 row.operator("mesh.mark_seam", text="Mark Seam").clear = False
2316 row.operator("mesh.mark_seam", text="Clear Seam").clear = True
2317 else:
2318 layout.operator("mesh.clear_all_seams")
2320 props = sce.paper_model
2321 layout.prop(props, "scale", text="Model Scale: 1")
2323 layout.prop(props, "limit_by_page")
2324 col = layout.column()
2325 col.active = props.limit_by_page
2326 col.prop(props, "page_size_preset")
2327 sub = col.column(align=True)
2328 sub.active = props.page_size_preset == 'USER'
2329 sub.prop(props, "output_size_x")
2330 sub.prop(props, "output_size_y")
2333 class DATA_PT_paper_model_islands(bpy.types.Panel):
2334 bl_space_type = 'PROPERTIES'
2335 bl_region_type = 'WINDOW'
2336 bl_context = "data"
2337 bl_label = "Paper Model Islands"
2338 COMPAT_ENGINES = {'BLENDER_RENDER', 'BLENDER_EEVEE', 'BLENDER_WORKBENCH'}
2340 def draw(self, context):
2341 layout = self.layout
2342 sce = context.scene
2343 obj = context.active_object
2344 mesh = obj.data if obj and obj.type == 'MESH' else None
2346 layout.operator("mesh.unfold", icon='FILE_REFRESH')
2347 if mesh and mesh.paper_island_list:
2348 layout.label(
2349 text="1 island:" if len(mesh.paper_island_list) == 1 else
2350 "{} islands:".format(len(mesh.paper_island_list)))
2351 layout.template_list(
2352 'UI_UL_list', 'paper_model_island_list', mesh,
2353 'paper_island_list', mesh, 'paper_island_index', rows=1, maxrows=5)
2354 sub = layout.split(align=True)
2355 sub.operator("mesh.select_paper_island", text="Select").operation = 'ADD'
2356 sub.operator("mesh.select_paper_island", text="Deselect").operation = 'REMOVE'
2357 sub.prop(sce.paper_model, "sync_island", icon='UV_SYNC_SELECT', toggle=True)
2358 if mesh.paper_island_index >= 0:
2359 list_item = mesh.paper_island_list[mesh.paper_island_index]
2360 sub = layout.column(align=True)
2361 sub.prop(list_item, "auto_label")
2362 sub.prop(list_item, "label")
2363 sub.prop(list_item, "auto_abbrev")
2364 row = sub.row()
2365 row.active = not list_item.auto_abbrev
2366 row.prop(list_item, "abbreviation")
2367 else:
2368 layout.box().label(text="Not unfolded")
2371 def label_changed(self, context):
2372 """The label of an island was changed"""
2373 # accessing properties via [..] to avoid a recursive call after the update
2374 self["auto_label"] = not self.label or self.label.isspace()
2375 island_item_changed(self, context)
2378 def island_item_changed(self, context):
2379 """The labelling of an island was changed"""
2380 def increment(abbrev, collisions):
2381 letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789"
2382 while abbrev in collisions:
2383 abbrev = abbrev.rstrip(letters[-1])
2384 abbrev = abbrev[:2] + letters[letters.find(abbrev[-1]) + 1 if len(abbrev) == 3 else 0]
2385 return abbrev
2387 # accessing properties via [..] to avoid a recursive call after the update
2388 island_list = context.active_object.data.paper_island_list
2389 if self.auto_label:
2390 self["label"] = "" # avoid self-conflict
2391 number = 1
2392 while any(item.label == "Island {}".format(number) for item in island_list):
2393 number += 1
2394 self["label"] = "Island {}".format(number)
2395 if self.auto_abbrev:
2396 self["abbreviation"] = "" # avoid self-conflict
2397 abbrev = "".join(first_letters(self.label))[:3].upper()
2398 self["abbreviation"] = increment(abbrev, {item.abbreviation for item in island_list})
2399 elif len(self.abbreviation) > 3:
2400 self["abbreviation"] = self.abbreviation[:3]
2401 self.name = "[{}] {} ({} {})".format(
2402 self.abbreviation, self.label, len(self.faces), "faces" if len(self.faces) > 1 else "face")
2405 def island_index_changed(self, context):
2406 """The active island was changed"""
2407 if context.scene.paper_model.sync_island and SelectIsland.poll(context):
2408 bpy.ops.mesh.select_paper_island(operation='REPLACE')
2411 class FaceList(bpy.types.PropertyGroup):
2412 id: bpy.props.IntProperty(name="Face ID")
2415 class IslandList(bpy.types.PropertyGroup):
2416 faces: bpy.props.CollectionProperty(
2417 name="Faces", description="Faces belonging to this island", type=FaceList)
2418 label: bpy.props.StringProperty(
2419 name="Label", description="Label on this island",
2420 default="", update=label_changed)
2421 abbreviation: bpy.props.StringProperty(
2422 name="Abbreviation", description="Three-letter label to use when there is not enough space",
2423 default="", update=island_item_changed)
2424 auto_label: bpy.props.BoolProperty(
2425 name="Auto Label", description="Generate the label automatically",
2426 default=True, update=island_item_changed)
2427 auto_abbrev: bpy.props.BoolProperty(
2428 name="Auto Abbreviation", description="Generate the abbreviation automatically",
2429 default=True, update=island_item_changed)
2432 class PaperModelSettings(bpy.types.PropertyGroup):
2433 sync_island: bpy.props.BoolProperty(
2434 name="Sync", description="Keep faces of the active island selected",
2435 default=False, update=island_index_changed)
2436 limit_by_page: bpy.props.BoolProperty(
2437 name="Limit Island Size", description="Do not create islands larger than given dimensions",
2438 default=False, update=page_size_preset_changed)
2439 page_size_preset: bpy.props.EnumProperty(
2440 name="Page Size", description="Maximal size of an island",
2441 default='A4', update=page_size_preset_changed, items=global_paper_sizes)
2442 output_size_x: bpy.props.FloatProperty(
2443 name="Width", description="Maximal width of an island",
2444 default=0.2, soft_min=0.105, soft_max=0.841, subtype="UNSIGNED", unit="LENGTH")
2445 output_size_y: bpy.props.FloatProperty(
2446 name="Height", description="Maximal height of an island",
2447 default=0.29, soft_min=0.148, soft_max=1.189, subtype="UNSIGNED", unit="LENGTH")
2448 scale: bpy.props.FloatProperty(
2449 name="Scale", description="Divisor of all dimensions when exporting",
2450 default=1, soft_min=1.0, soft_max=10000.0, step=100, subtype='UNSIGNED', precision=1)
2453 module_classes = (
2454 Unfold,
2455 ExportPaperModel,
2456 ClearAllSeams,
2457 SelectIsland,
2458 AddPresetPaperModel,
2459 FaceList,
2460 IslandList,
2461 PaperModelSettings,
2462 VIEW3D_MT_paper_model_presets,
2463 DATA_PT_paper_model_islands,
2464 #VIEW3D_PT_paper_model_tools,
2468 def register():
2469 for cls in module_classes:
2470 bpy.utils.register_class(cls)
2471 bpy.types.Scene.paper_model = bpy.props.PointerProperty(
2472 name="Paper Model", description="Settings of the Export Paper Model script",
2473 type=PaperModelSettings, options={'SKIP_SAVE'})
2474 bpy.types.Mesh.paper_island_list = bpy.props.CollectionProperty(
2475 name="Island List", type=IslandList)
2476 bpy.types.Mesh.paper_island_index = bpy.props.IntProperty(
2477 name="Island List Index",
2478 default=-1, min=-1, max=100, options={'SKIP_SAVE'}, update=island_index_changed)
2479 bpy.types.TOPBAR_MT_file_export.append(menu_func_export)
2480 bpy.types.VIEW3D_MT_edit_mesh.prepend(menu_func_unfold)
2483 def unregister():
2484 bpy.types.TOPBAR_MT_file_export.remove(menu_func_export)
2485 bpy.types.VIEW3D_MT_edit_mesh.remove(menu_func_unfold)
2486 for cls in reversed(module_classes):
2487 bpy.utils.unregister_class(cls)
2490 if __name__ == "__main__":
2491 register()