chiark / gitweb /
curveopt: wip, observe a bug
[moebius3.git] / curveopt.py
1
2 from __future__ import print_function
3
4 import numpy as np
5 from numpy import cos, sin
6
7 import six
8 import sys
9 import subprocess
10 import math
11
12 from moedebug import *
13 from moenp import *
14 from moebez import *
15
16 from math import atan2, atan, sqrt
17
18 import symbolic
19
20 findcurve_subprocs = { }
21
22 class OptimisedCurve():
23   def __init__(oc, cp, nt):
24     db = DiscreteBezier(cp, nt, bezier_constructor=BezierSegment)
25
26     fc_input = map(db.point_at_it, range(0, nt+1))
27     dbg(repr(fc_input))
28
29     for end in (False,True):
30       ei = nt if end else 0
31       fi = nt-1 if end else 1
32       cp0i = 3 if end else 0
33       cp1i = 2 if end else 1
34       e = np.array(cp[cp0i])
35       ef_dirn = unit_v(cp[cp1i] - cp[cp0i])
36       ef_len = np.linalg.norm(np.array(fc_input[fi]) - np.array(fc_input[ei]))
37       f = e + ef_dirn * ef_len
38       fc_input[ei] = e
39       fc_input[fi] = f
40
41     findcurve_epsilon = 0.01
42
43     try:
44       subproc = findcurve_subprocs[nt]
45     except KeyError:
46       cl = ['./findcurve', '%d' % (nt+1), '%.18g' % findcurve_epsilon]
47       dbg('STARTING FINDCURVE %s' % cl)
48       subproc = subprocess.Popen(
49         cl,
50         bufsize=1,
51         stdin=subprocess.PIPE,
52         stdout=subprocess.PIPE,
53         stderr=None,
54         close_fds=False,
55         # restore_signals=True, // want python2 compat, nnng
56         universal_newlines=True,
57       )
58       findcurve_subprocs[nt] = subproc
59
60     dbg('RUNNING FINDCURVE')
61
62     fc_input = np.hstack(fc_input)
63     s = ' '.join(map(str, fc_input))
64
65     dbg(('>> %s' % s))
66
67     print(s, file=subproc.stdin)
68     subproc.stdin.flush()
69
70     commentary = ''
71
72     while True:
73       l = subproc.stdout.readline()
74       l = l.rstrip()
75       dbg('<< ', l)
76       if not l: vdbg().crashing('findcurve EOF')
77       if not l.startswith('['):
78         commentary += ' '
79         commentary += l
80         continue
81
82       l = eval(l)
83       if not l: break
84
85       dbg('[%s] %s' % (l, commentary))
86       commentary = ''
87
88       findcurve_result = l
89
90     oc.nt = nt
91     oc._result = np.reshape(findcurve_result, (-1,3), 'C')
92     dbg(repr(oc._result))
93
94     vdbg().curve( oc.point_at_t )
95
96   def point_at_it(oc, it):
97     dbg(repr((it,)))
98     return oc._result[it]
99
100   def point_at_t(oc, t):
101     itd = t * oc.nt
102     it0 = int(math.floor(itd))
103     it1 = int(math.ceil(itd))
104     p0 = oc.point_at_it(it0)
105     p1 = oc.point_at_it(it1)
106     return p0 + (p1-p0) * (itd-it0)
107