chiark / gitweb /
curveopt: wip
[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 sys
8 import subprocess
9
10 from moedebug import *
11 from moenp import *
12 from moebez import *
13
14 from math import atan2, atan, sqrt
15
16 import symbolic
17
18 findcurve_subprocs = { }
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
26     for end in (False,True):
27       ei = nt if end else 0
28       fi = nt-1 if end else 1
29       cp0i = 0 if end else 3
30       cp1i = 1 if end else 2
31       e = np.array(cp[cp0i])
32       ef_dirn = unit_v(cp[cp1i] - cp[cp0i])
33       ef_len = np.linalg.norm(np.array(fc_input[fi]) - np.array(fc_input[ei]))
34       f = e + ef_dirn * ef_len
35       fc_input[ei] = e
36       fc_input[fi] = f
37
38     findcurve_epsilon = 0.01
39
40     try:
41       subproc = findcurve_subprocs[nt]
42     except KeyError:
43       cl = ['./findcurve', '%d' % nt, '%.18g' % findcurve_epsilon]
44       dbg('STARTING FINDCURVE %s' % cl)
45       subproc = subprocess.Popen(
46         cl,
47         bufsize=1,
48         stdin=subprocess.PIPE,
49         stdout=subprocess.PIPE,
50         stderr=None,
51         close_fds=False,
52         # restore_signals=True, // want python2 compat, nnng
53         universal_newlines=True,
54       )
55       findcurve_subprocs[nt] = subproc
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     commentary = ''
68
69     while True:
70       l = subproc.stdout.readline()
71       l = l.rstrip()
72       dbg('<< ', l)
73       if not l: vdbg().crashing('findcurve EOF')
74       if not l.startswith('['):
75         commentary += ' '
76         commentary += l
77         continue
78
79       l = eval(l)
80       if not l: break
81
82       dbg('[%s] %s' % (l, commentary))
83       commentary = ''
84
85       findcurve_result = l
86
87     oc._result = np.reshape(findcurve_result, (3,-1))
88
89   def point_at_it(oc, it):
90     return oc._result[it]