chiark / gitweb /
e07e7250626349cd37838000d81881ba3ff90460
[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 class OptimisedCurve():
21   def __init__(oc, cp, nt):
22     db = DiscreteBezier(cp, nt, bezier_constructor=BezierSegment)
23
24     fc_input = map(db.point_at_it, range(0, nt+1))
25     dbg(repr(fc_input))
26
27     for end in (False,True):
28       ei = nt if end else 0
29       fi = nt-1 if end else 1
30       cp0i = 3 if end else 0
31       cp1i = 2 if end else 1
32       e = np.array(cp[cp0i])
33       ef_dirn = unit_v(cp[cp1i] - cp[cp0i])
34       ef_len = np.linalg.norm(np.array(fc_input[fi]) - np.array(fc_input[ei]))
35       f = e + ef_dirn * ef_len
36       dbg(repr((end, e,f, ef_dirn, ef_len)))
37       fc_input[ei] = e
38       fc_input[fi] = f
39
40     dbg(repr(fc_input))
41
42     findcurve_epsilon = 0.01
43
44     cl = ['./findcurve', '%d' % (nt+1), '%.18g' % findcurve_epsilon]
45     dbg('STARTING FINDCURVE %s' % cl)
46     subproc = subprocess.Popen(
47       cl,
48       bufsize=1,
49       stdin=subprocess.PIPE,
50       stdout=subprocess.PIPE,
51       stderr=None,
52       close_fds=False,
53       # restore_signals=True, // want python2 compat, nnng
54       universal_newlines=True,
55     )
56
57     dbg('RUNNING FINDCURVE')
58
59     fc_input = np.hstack(fc_input)
60     s = ' '.join(map(str, fc_input))
61
62     dbg(('>> %s' % s))
63
64     print(s, file=subproc.stdin)
65     subproc.stdin.flush()
66
67     oc.subproc = subproc
68     oc.nt = nt
69
70   def _await_subproc(oc):
71     subproc = oc.subproc
72     if subproc is None: return
73
74     dbg('(awaiting)')
75     commentary = ''
76
77     while True:
78       l = subproc.stdout.readline()
79       l = l.rstrip()
80       dbg('<< ', l)
81       if not l: vdbg().crashing('findcurve EOF')
82       if not l.startswith('['):
83         commentary += ' '
84         commentary += l
85         continue
86
87       l = eval(l)
88       if not l: break
89
90       dbg('[%s] %s' % (l, commentary))
91       commentary = ''
92
93       findcurve_result = l
94
95     subproc.stdin.close()
96     subproc.wait()
97     assert(subproc.returncode == 0)
98     oc.subproc = None
99
100     oc._result = np.reshape(findcurve_result, (-1,3), 'C')
101     dbg(repr(oc._result))
102
103     vdbg().curve( oc.point_at_t )
104
105   def point_at_it(oc, it):
106     oc._await_subproc()
107     dbg(repr((it,)))
108     return oc._result[it]
109
110   def point_at_t(oc, t):
111     itd = t * oc.nt
112     it0 = int(math.floor(itd))
113     it1 = int(math.ceil(itd))
114     p0 = oc.point_at_it(it0)
115     p1 = oc.point_at_it(it1)
116     return p0 + (p1-p0) * (itd-it0)
117