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