-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparse_svg.py
178 lines (129 loc) · 5.59 KB
/
parse_svg.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
import svgpathtools.svgpathtools as svg
import json
import math
import argparse
import RationalBezier as rb
SAMPLE_MAX_DEPTH = 5
SAMPLE_ERROR = 1e-3
def complex_to_point(p):
return [p.real, p.imag]
def complex_to_vect(p):
return [p.real, p.imag]
def compute_samples(curve, start=0, end=1, error=SAMPLE_ERROR, max_depth=SAMPLE_MAX_DEPTH, depth=0):
return compute_samples_aux(curve, start, end, curve.point(start), curve.point(end), error, max_depth, depth)
def compute_samples_aux(curve, start, end, start_point, end_point, error, max_depth, depth):
"""Recursively approximates the length by straight lines"""
mid = (start + end)/2
mid_point = curve.point(mid)
length = abs(end_point - start_point)
first_half = abs(mid_point - start_point)
second_half = abs(end_point - mid_point)
length2 = first_half + second_half
res = [start, mid, end]
if abs(length) < 1e-10:
return []
if depth < 2 or ((abs(length2 - length) > error) and (depth <= max_depth)):
depth += 1
res1 = compute_samples_aux(curve, start, mid, start_point, mid_point, error, max_depth, depth)
res2 = compute_samples_aux(curve, mid, end, mid_point, end_point, error, max_depth, depth)
return sorted(set(res1 + res2))
else:
# This is accurate enough.
return res
def parse_args():
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("image", type=str, help="path to the input svg image")
parser.add_argument("output", type=str, help="path to the output file without extension")
return parser.parse_args()
def convert_svg(input_svg, output):
doc = svg.Document(input_svg)
paths = doc.flatten_all_paths()
vertices = ""
lines = ""
json_data = []
v_index = 1
c_index = 0
for ii in range(len(paths)):
tmp = paths[ii]
path = tmp.path
print(str(ii+1) + "/" + str(len(paths)) + " n sub paths: " + str(len(path)))
first = True
for pieces in path:
if isinstance(pieces, svg.path.Arc):
if first:
if abs(pieces.start - path[-1].end) < 1e-10:
pieces.start = path[-1].end
if abs(pieces.delta) > 120:
n_pices = math.ceil(abs(pieces.delta) / 120)
tmp = []
for p in range(n_pices):
t0 = float(p)/n_pices
t1 = float(p + 1) / n_pices
tmp.append(rb.RationalBezier(pieces, tstart=t0, tend=t1))
pieces = tmp
else:
pieces = [rb.RationalBezier(pieces)]
else:
pieces = [pieces]
first = False
for piece in pieces:
ts = compute_samples(piece)
if len(ts) <= 0:
continue
param_ts = []
iprev = None
for param_t in ts:
param_ts.append(param_t)
p = piece.point(param_t)
xy = complex_to_point(p)
if not iprev:
istart = v_index
vertices += "v " + str(xy[0]) + " " + str(xy[1]) + " 0\n"
if iprev:
lines += "l " + str(iprev) + " " + str(v_index) + "\n"
iprev = v_index
v_index += 1
json_obj = {}
json_obj["v_ids"] = list(range(istart-1, v_index-1))
istart = None
json_obj["paras"] = param_ts
json_obj["curve_id"] = c_index
c_index += 1
is_set = False
if isinstance(piece, svg.path.Line):
json_obj["type"] = "Line"
json_obj["start"] = complex_to_point(piece.start)
json_obj["end"] = complex_to_point(piece.end)
is_set = True
elif isinstance(piece, svg.path.QuadraticBezier):
json_obj["type"] = "BezierCurve"
json_obj["degree"] = 2
json_obj["poles"] = [complex_to_point(piece.start), complex_to_point(piece.control), complex_to_point(piece.end)]
is_set = True
elif isinstance(piece, svg.path.CubicBezier):
json_obj["type"] = "BezierCurve"
json_obj["degree"] = 3
json_obj["poles"] = [complex_to_point(piece.start), complex_to_point(piece.control1), complex_to_point(piece.control2), complex_to_point(piece.end)]
is_set = True
elif isinstance(piece, rb.RationalBezier):
json_obj["type"] = "RationalBezier"
json_obj["poles"] = [complex_to_point(piece.start), complex_to_point(piece.control), complex_to_point(piece.end)]
json_obj["weigths"] = [piece.weights[0], piece.weights[1], piece.weights[2]]
is_set = True
if is_set:
json_data.append(json_obj)
else:
print(type(piece))
print(piece)
assert(False)
lines += "\n"
with open(output + ".obj", "w") as file:
file.write(vertices)
file.write(lines)
with open(output + ".json", "w") as file:
file.write(json.dumps(json_data, indent=4))
if __name__ == '__main__':
args = parse_args()
convert_svg(args.image, args.output)