-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathsvg_shaders.py
607 lines (486 loc) · 21.4 KB
/
svg_shaders.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# <pep8 compliant>
# ----------------------------------------------------------
#
# Collection of SVG "Shaders" for the Various Draw Functions.
# Author: Kevan Cress
#
# ----------------------------------------------------------
import bpy
import bmesh
import time
import bpy_extras.object_utils as object_utils
import math
import svgwrite
from fontTools import ttLib
from math import fabs, sqrt
from mathutils import Vector, Matrix
from sys import getrecursionlimit, setrecursionlimit
from . import vector_utils
from .measureit_arch_utils import get_view, interpolate3d, get_camera_z_dist, recursionlimit, get_resolution, get_scale, pts_to_px, rgb_gamma_correct
def svg_line_shader(item, itemProps, coords, thickness, color, svg, parent=None, mat=Matrix.Identity(4)):
weight_scale_fac = 1.3333333333333333 * get_resolution()/96
if bpy.context.scene.MeasureItArchProps.illustrator_style_svgs:
weight_scale_fac = 1
idName = item.name + "_lines"
dash_id_name = idName = item.name + "_dashed_lines"
dashed = False
if "lineDrawDashed" in itemProps and itemProps.lineDrawDashed:
dashed = True
svgColor = get_svg_color(color)
cap = 'butt'
try:
if itemProps.pointPass:
cap = 'round'
except AttributeError:
pass
lines = svg.g(id=idName, stroke=svgColor,fill = 'none',
stroke_width="{}".format(thickness*weight_scale_fac), stroke_linecap=cap)
if parent:
parent.add(lines)
else:
svg.add(lines)
draw_hidden = 'lineDrawHidden' in itemProps and itemProps.lineDrawHidden
dash_col = svgColor
dash_weight = thickness
if draw_hidden:
dash_col = get_svg_color(itemProps.lineHiddenColor)
dash_weight = itemProps.lineHiddenWeight
dash_val = get_svg_dash(itemProps,weight_scale_fac)
dashed_lines = svg.g(id=dash_id_name, stroke=dash_col,fill = 'none', stroke_width="{}".format(dash_weight * weight_scale_fac),
stroke_dasharray=dash_val, stroke_linecap='butt')
if parent:
parent.add(dashed_lines)
else:
svg.add(dashed_lines)
if dashed:
lines = dashed_lines
for x in range(0, len(coords) - 1, 2):
draw_single_line(coords[x],coords[x+1],mat,itemProps,svg,lines,dashed_lines,cap,draw_hidden)
def draw_single_line(p1,p2,mat=Matrix.Identity(4),itemProps=None,svg=None,lines=None,dashed_lines=None,cap=None,draw_hidden=False,depth_test=True):
if depth_test:
line_segs = vector_utils.depth_test(p1, p2, mat, itemProps)
else: line_segs = [[1,p1,p2]]
for line in line_segs:
vis = line[0]
p1 = line[1]
p2 = line[2]
if vis == -1:
continue
if vis or draw_hidden:
p1ss = vector_utils.get_render_location(mat @ Vector(p1))
p2ss = vector_utils.get_render_location(mat @ Vector(p2))
line_draw = svg.line(start=tuple(p1ss), end=tuple(p2ss))
if vis:
lines.add(line_draw)
elif not vis and draw_hidden:
dashed_lines.add(line_draw)
def svg_fill_from_curve_shader(curve,svg,parent=None,mat =Matrix.Identity):
weight_scale_fac = 1.3333333333333333 * get_resolution()/96
if bpy.context.scene.MeasureItArchProps.illustrator_style_svgs:
weight_scale_fac = 1
for i in range(len(curve.material_slots)):
material = curve.material_slots[i].material
hatch = material.Hatch
if not hatch.visible:
continue
fillColor = get_svg_color(rgb_gamma_correct(hatch.fill_color))
svgColor = get_svg_color(rgb_gamma_correct(hatch.fill_color))
fill_idName = curve.name + "_fill_" + material.name
fillOpacity = hatch.fill_color[3]
lineColor = get_svg_color(hatch.line_color)
if hatch.lineWeight == 0:
lineColor = 'none'
dash_val='none'
if hatch.lineDrawDashed:
dash_val = get_svg_dash(hatch,weight_scale_fac)
fills = svg.g(id=fill_idName, stroke=lineColor, stroke_width="{}".format(hatch.lineWeight * weight_scale_fac),fill = fillColor, fill_opacity = fillOpacity,stroke_dasharray=dash_val)
if parent:
parent.add(fills)
else:
svg.add(fills)
for spline in curve.data.splines:
if spline.material_index != i:
continue
path_strings = []
hidden_path_strings = []
curve_segs = []
for j in range(len(spline.bezier_points)-1):
p1 = spline.bezier_points[j].co
p2 = spline.bezier_points[j+1].co
h1 = spline.bezier_points[j].handle_right
h2 = spline.bezier_points[j+1].handle_left
ss_p1 = vector_utils.get_render_location(mat@p1)
ss_p2 = vector_utils.get_render_location(mat@p2)
last_handle = h1
current_handle = h2
ss_last = vector_utils.get_render_location(mat@last_handle)
ss_current = vector_utils.get_render_location(mat@current_handle)
if j == 0:
path_strings.append('M {} {}'.format(ss_p1[0],ss_p1[1]))
path_strings.append('C {} {} {} {} {} {}'.format(ss_last[0], ss_last[1], ss_current[0], ss_current[1], ss_p2[0],ss_p2[1]))
if spline.use_cyclic_u or spline.use_cyclic_v:
p1 = spline.bezier_points[-1].co
p2 = spline.bezier_points[0].co
h1 = spline.bezier_points[-1].handle_right
h2 = spline.bezier_points[0].handle_left
ss_p2 = vector_utils.get_render_location(mat@p2)
last_handle = h1
current_handle = h2
ss_last = vector_utils.get_render_location(mat@last_handle)
ss_current = vector_utils.get_render_location(mat@current_handle)
path_strings.append('C {} {} {} {} {} {}'.format(ss_last[0], ss_last[1], ss_current[0], ss_current[1], ss_p2[0],ss_p2[1]))
path_string = ' '.join(path_strings)
path = svg.path(d=path_string)
fills.add(path)
def svg_path_from_curve_shader(curve, item, color, svg, parent=None, mat = Matrix.Identity(4)):
obj_mat = mat
weight_scale_fac = 1.3333333333333333 * get_resolution()/96
thickness = item.lineWeight
if bpy.context.scene.MeasureItArchProps.illustrator_style_svgs:
weight_scale_fac = 1
idName = item.name + "_lines"
dash_id_name = idName = item.name + "_dashed_lines"
dashed = False
if "lineDrawDashed" in item and item.lineDrawDashed:
dashed = True
svgColor = get_svg_color(color)
cap = 'butt'
try:
if item.pointPass:
cap = 'round'
except AttributeError:
pass
lines = svg.g(id=idName, stroke=svgColor,fill = 'none',
stroke_width="{}".format(thickness*weight_scale_fac), stroke_linecap=cap)
if parent:
parent.add(lines)
else:
svg.add(lines)
draw_hidden = 'lineDrawHidden' in item and item.lineDrawHidden
dash_col = svgColor
dash_weight = thickness
if draw_hidden:
dash_col = get_svg_color(item.lineHiddenColor)
dash_weight = item.lineHiddenWeight
dash_val = get_svg_dash(item,weight_scale_fac)
# Dashed lines
dashed_lines = svg.g(id=dash_id_name, stroke=dash_col,fill = 'none', stroke_width="{}".format(dash_weight * weight_scale_fac),
stroke_dasharray=dash_val, stroke_linecap='butt')
if parent:
parent.add(dashed_lines)
else:
svg.add(dashed_lines)
if dashed:
lines = dashed_lines
for spline in curve.data.splines:
path_strings = []
hidden_path_strings = []
curve_segs = []
for i in range(len(spline.bezier_points)-1):
p1 = spline.bezier_points[i].co
p2 = spline.bezier_points[i+1].co
h1 = spline.bezier_points[i].handle_right
h2 = spline.bezier_points[i+1].handle_left
curve_segs.extend(vector_utils.curve_depth_test(p1,p2,h1,h2,obj_mat, item))
if spline.use_cyclic_u or spline.use_cyclic_v:
p1 = spline.bezier_points[-1].co
p2 = spline.bezier_points[0].co
h1 = spline.bezier_points[-1].handle_right
h2 = spline.bezier_points[0].handle_left
curve_segs.extend(vector_utils.curve_depth_test(p1,p2,h1,h2,obj_mat, item))
try:
last_vis = not curve_segs[i][0]
except IndexError:
return
for i in range(len(curve_segs)):
visibility = curve_segs[i][0]
curve_chunk = curve_segs[i][1]
p1 = curve_chunk[0]
p2 = curve_chunk[1]
h1 = curve_chunk[2]
h2 = curve_chunk[3]
ss_p1 = vector_utils.get_render_location(obj_mat@p1)
ss_p2 = vector_utils.get_render_location(obj_mat@p2)
last_handle = h1
current_handle = h2
ss_last = vector_utils.get_render_location(obj_mat@last_handle)
ss_current = vector_utils.get_render_location(obj_mat@current_handle)
if visibility:
if visibility != last_vis:
path_strings.append('M {} {}'.format(ss_p1[0],ss_p1[1]))
path_strings.append('C {} {} {} {} {} {}'.format(ss_last[0], ss_last[1], ss_current[0], ss_current[1], ss_p2[0],ss_p2[1]))
else:
if visibility != last_vis:
hidden_path_strings.append('M {} {}'.format(ss_p1[0],ss_p1[1]))
hidden_path_strings.append('C {} {} {} {} {} {}'.format(ss_last[0], ss_last[1], ss_current[0], ss_current[1], ss_p2[0],ss_p2[1]))
last_vis = visibility
path_string = ' '.join(path_strings)
path = svg.path(d=path_string)
lines.add(path)
if draw_hidden:
hidden_path_string = ' '.join(hidden_path_strings)
hidden_path = svg.path(d=hidden_path_string)
dashed_lines.add(hidden_path)
pass
def svg_fill_shader(item, coords, color, svg, parent=None):
if vector_utils.camera_cull(coords):
print("No Points In front of Camera: {} Culled in Fill Shader")
return
coords_2d = []
idName = item.name + "_fills"
svgColor = svgwrite.rgb(color[0] * 100, color[1] * 100, color[2] * 100, '%')
fills = svg.g(id=idName, fill=svgColor)
parent.add(fills)
for coord in coords:
coords_2d.append(vector_utils.get_render_location(coord))
for x in range(0, len(coords_2d) - 1, 3):
tri = svg.polygon(
points=[coords_2d[x], coords_2d[x + 1], coords_2d[x + 2]])
fills.add(tri)
def svg_circle_shader(item, point, rad, color, svg, parent=None):
if vector_utils.camera_cull([point]):
print("No Points In front of Camera: {} Culled in Circle Shader")
return
idName = item.name + "_fills"
svgColor = svgwrite.rgb(color[0] * 100, color[1] * 100, color[2] * 100, '%')
fills = svg.g(id=idName, fill=svgColor)
parent.add(fills)
point_2d = vector_utils.get_render_location(point)
circle = svg.circle(center=point_2d,r=rad*2)
fills.add(circle)
def svg_poly_fill_shader(item, coords, color, svg, parent=None, line_color=(0, 0, 0,0), lineWeight=0, fillURL='', itemProps = None, closed=True, mat = Matrix.Identity(4)):
weight_scale_fac = 1.3333333333333333 * get_resolution()/96
if bpy.context.scene.MeasureItArchProps.illustrator_style_svgs:
weight_scale_fac = 1
if vector_utils.camera_cull(coords,mat):
print("No Points In front of Camera: {} Culled in Poly Fill Shader")
return
cap = 'butt'
try:
if itemProps.pointPass:
cap = 'round'
except AttributeError:
pass
coords_2d = []
idName = item.name + "_fills"
dashed = False
if itemProps==None: itemProps = item
if "lineDrawDashed" in itemProps and itemProps.lineDrawDashed:
dashed = True
dash_val = get_svg_dash(itemProps,weight_scale_fac)
fill = svgwrite.rgb(color[0] * 100, color[1] * 100, color[2] * 100, '%')
fillOpacity = color[3]
lineColor = svgwrite.rgb(
line_color[0] * 100, line_color[1] * 100, line_color[2] * 100, '%')
lineOpacity = lineColor[3]
if dashed:
solidfill = svg.g(id=idName, fill=fill, fill_opacity=fillOpacity,
stroke=lineColor, stroke_width="{}".format(lineWeight*weight_scale_fac), stroke_opacity=lineOpacity,stroke_linejoin="round", stroke_dasharray=dash_val, stroke_linecap= cap)
else:
solidfill = svg.g(id=idName, fill=fill, fill_opacity=fillOpacity,
stroke=lineColor, stroke_width="{}".format(lineWeight*weight_scale_fac), stroke_opacity=lineOpacity,stroke_linejoin="round", stroke_linecap= cap)
if parent:
parent.add(solidfill)
else:
svg.add(solidfill)
for coord in coords:
coords_2d.append(vector_utils.get_render_location(mat @ Vector(coord)))
if False:
coords_2d = polygon_occlusion(coords_2d)
if closed:
poly = svg.polygon(points=coords_2d)
else:
poly = svg.polyline(points=coords_2d)
solidfill.add(poly)
if fillURL != '':
fill = fillURL
patternfill = svg.g(id=idName, fill=fill, fill_opacity=item.patternOpacity,
stroke=0)
parent.add(patternfill)
patternfill.add(poly)
def svg_text_shader(item, style, text, mid, textCard, color, svg, parent=None):
# Card Indicies:
#
# 1----------------2
# | |
# | |
# 0----------------3
if vector_utils.camera_cull(textCard):
print("No Points In front of Camera: {} Culled Text Card")
return
svgColor = svgwrite.rgb(color[0] * 100, color[1] * 100, color[2] * 100, '%')
ssp0 = vector_utils.get_render_location(textCard[0])
ssp1 = vector_utils.get_render_location(textCard[1])
ssp2 = vector_utils.get_render_location(textCard[2])
ssp3 = vector_utils.get_render_location(textCard[3])
card = [Vector(ssp0),Vector(ssp1),Vector(ssp2),Vector(ssp3)]
xDirVec = card[3] - card[0]
yDirVec = card[1] - card[0]
# If either card direction is 0, don't draw any text
if xDirVec.length == 0 or yDirVec.length == 0:
return
# If the card is not ordered correctly on the page flip it
if yDirVec.dot(Vector((1,1000))) > 0:
card[0] = Vector(ssp1)
card[3] = Vector(ssp2)
card[1] = Vector(ssp0)
card[2] = Vector(ssp3)
if xDirVec.dot(Vector((10000,-1))) < 0:
temp = card[0]
card[0] = card[3]
card[3] = temp
temp2 = card[1]
card[1] = card[2]
card[2] = temp2
# Re Calc direction vectors aftor flips
xDirVec = card[3] - card[0]
yDirVec = card[1] - card[0]
center = card[0] + ((card[2] - card[0])/2)
cardHeight = yDirVec.length
# Get the rotation angle of the text card from horizontal
xvec = Vector((9999, -1)).normalized() #again we need to make this slightly off axis to make rotation consistent for orthogonal views
rotation = math.degrees(xDirVec.angle_signed(xvec))
# Define Anchor Points
leftVec = card[0]
rightVec = card[3]
midVec =card[0] + ((card[3]-card[0])/2)
# Set anchor point and positon
if style.textAlignment == 'L':
text_position = leftVec
text_anchor = 'start'
if style.textAlignment == 'C':
text_position = midVec
text_anchor = 'middle'
if style.textAlignment == 'R':
text_position = rightVec
text_anchor = 'end'
# Get resolution for text size
view = get_view()
res = get_resolution()
scale = get_scale()
# Try to get font
font_family = "Open Sans"
if style.font != None:
font_file = style.font.filepath
font_file = bpy.path.abspath(font_file)
try:
tt = ttLib.TTFont(font_file, verbose=1)
font_family = shortName(tt)[0]
except Exception as e:
font_family = style.font.name
print(e)
print(font_file)
print(font_family)
# Get Skew
#skewX = 90-math.degrees(yDirVec.angle_signed(xDirVec))
#print("Skew: {}".format(skew))
lines = text.split('\n')
# Draw the text
line_height = cardHeight / len(lines)
# Height Offset to match the raster texture shift
heightOffsetAmount = cardHeight - line_height * 0.8
heightOffset = yDirVec.copy().normalized() * heightOffsetAmount
offset_text_position = text_position + heightOffset
idx = 0
for line in lines:
offset_line_position = offset_text_position + Vector((0,line_height*1.1 * idx))
svg.add(svg.text(line, insert=tuple(offset_line_position), fill=svgColor, **{
#'transform-origin': '{}px {}px'.format(offset_text_position[0], offset_text_position[1]),
'transform': 'rotate({} {} {})'.format(
rotation,
offset_text_position[0],
offset_text_position[1]
),
'font-size': '{}px'.format(pts_to_px(style.fontSize)),
'font-family': font_family,
'text-anchor': text_anchor,
'text-align': text_anchor,
'xml:space' : "preserve"
}))
idx += 1
## Debug Draw Text Card for troubleshooting
if bpy.context.scene.MeasureItArchProps.show_text_cards:
svg.add(svg.line(start=tuple(ssp0), end=tuple(ssp1), stroke="blue", stroke_width="1pt"))
svg.add(svg.line(start=tuple(ssp1), end=tuple(ssp2), stroke="blue", stroke_width="1pt"))
svg.add(svg.line(start=tuple(ssp2), end=tuple(ssp3), stroke="blue", stroke_width="1pt"))
svg.add(svg.line(start=tuple(ssp0), end=tuple(ssp3), stroke="blue", stroke_width="1pt"))
svg.add(svg.line(start=tuple(card[0]), end=tuple(card[3]), stroke="red", stroke_width="2pt"))
svg.add(svg.line(start=tuple(card[0]), end=tuple(card[1]), stroke="green", stroke_width="2pt"))
svg.add(svg.line(start=tuple(midVec), end=tuple(center), stroke="blue", stroke_width="2pt"))
svg.add(svg.line(start=tuple(text_position), end=tuple(offset_text_position), stroke="yellow", stroke_width=2))
svg.add(svg.line(start=tuple((0,0)), end=tuple((50,0)), stroke="red", stroke_width="1pt"))
svg.add(svg.line(start=tuple((0,0)), end=tuple((0,50)), stroke="green", stroke_width="1pt"))
def svg_line_pattern_shader(pattern, svg, objs, weight, color, size):
weight_scale_fac = 1.3333333333333333 * get_resolution()/96
if bpy.context.scene.MeasureItArchProps.illustrator_style_svgs:
weight_scale_fac = 1
svgColor = svgwrite.rgb(color[0] * 100, color[1] * 100, color[2] * 100, '%')
for obj in objs:
mesh = obj.data
edges = mesh.edges
for edge in edges:
pair = []
for idx in edge.vertices:
ssp = (mesh.vertices[idx].co[0] * size,
mesh.vertices[idx].co[1] * size)
pair.append(ssp)
pattern.add(svg.line(start=tuple(pair[0]), end=tuple(
pair[1]), stroke_width="{}".format(weight*weight_scale_fac), stroke=svgColor, stroke_linecap='round'))
def get_svg_dash(item,weight_scale_fac):
try:
dash_val = ""
for i in range(item.num_dashes+1):
if i == 0: continue
if i > 1: dash_val += ","
dash_space = eval('item.d{}_length'.format(i))
gap_space = eval('item.g{}_length'.format(i))
dash_val += "{},{}".format(dash_space * weight_scale_fac, gap_space* weight_scale_fac)
except AttributeError:
if "dash_size" in item:
dash_val = "{},{}".format(item.dash_size*weight_scale_fac, item.gap_size*weight_scale_fac)
else:
dash_val = "5,5"
return dash_val
def polygon_subtract(source, cut):
return source
# From https://gist.github.com/pklaus/dce37521579513c574d0
FONT_SPECIFIER_NAME_ID = 4
FONT_SPECIFIER_FAMILY_ID = 1
def shortName(font):
"""Get the short name from the font's names table"""
name = ""
family = ""
for record in font['name'].names:
if record.nameID == FONT_SPECIFIER_NAME_ID and not name:
if b'\x00' in record.string:
name_str = record.string.decode('utf-16-be')
else:
name_str = record.string.decode('utf-8')
name = name_str
elif record.nameID == FONT_SPECIFIER_FAMILY_ID and not family:
if b'\x00' in record.string:
name_str = record.string.decode('utf-16-be')
else:
name_str = record.string.decode('utf-8')
family = name_str
if name and family: break
return name, family
def get_svg_color(color):
return svgwrite.rgb(color[0] * 100, color[1] * 100, color[2] * 100, '%')