Debian Codegraph @

texmf-dist/doc/latex/figput/javascript/development/tikz.ts

raw
1 /*
2 Code necessary to output tikz for figures. It spoofs the normal canvas
3 drawing code so that the output comes here, and is then converted to
4 tizk output.
5
6 One problem with JS is that there is no path interator. You can't obtain
7 the segments that make up an entire path. I don't see any way around this
8 other than writing my own wrapper around Path2D. It might be possible to
9 somehow hack the internals of Path2D, but that would be brittle, even if
10 it works.
11
12 BUG: The long-term solution is to eliminate use of the JS Path2D class,
13 but it's not possible to entirely eliminate it since it's the only way to
14 draw to the browser window. What I *could* do is sub-class
15 CanvasRenderingContext2D so that this sub-class take my own path class
16 objects and converts them to Path2D for drawing. Another hurdle is
17 isPointInPath(), which is used in a few places. I could provide a separate
18 implementation of that, but it's fiddly. isPointInStroke() is a bit harder.
19
20 BUG: It's tempting to come up with a framework under which a "path"
21 is closer to our intuition of something that can be drawn as a continuous
22 thing, without lifting your pencil. Then, have a second-order thing that
23 may hold several of these continuous paths. Intuitively one wants a "path"
24 to have a clear start-point and end-point, but you also need to be able
25 to handle things like winding number for multiple paths when filling.
26
27 BUG: There are many cases where you might want the online version to be
28 different from what is printed. I just gave the example of filling a path,
29 and color is similar. There's lots of things that might make sense on a
30 computer screen, but wouldn't work well on printed paper.
31
32 */
33
34
35 // Turns out that Point used to be part of js, but was deprecated, and
36 // seems not to exist any longer.
37
38 class Point2D {
39
40 private _x : number;
41 private _y : number;
42
43 constructor(x : number,y : number) {
44 this._x = x;
45 this._y = y;
46 }
47
48 public toString() : string {
49
50 // May be handy for debugging.
51 return "( " + this._x.toFixed(2) + "," + this._y.toFixed(2) + ")";
52 }
53
54 public get x() : number {
55 return this._x;
56 }
57
58 public get y() : number {
59 return this._y;
60 }
61
62 public copy() : Point2D {
63 return new Point2D( this._x , this._y );
64 }
65
66 public negate() : Point2D {
67 // return -this.
68 return new Point2D(-this._x,-this.y);
69 }
70
71 public negateSelf() : void {
72
73 this._x = -this.x;
74 this._y = -this.y;
75 }
76
77 public minus(p : Point2D) : Point2D {
78
79 // return this - p. Redunant since it's just a form of translation.
80 return new Point2D( this._x - p.x , this._y - p.y );
81 }
82
83 public minusSelf(p : Point2D) : void {
84
85 this._x -= p._x;
86 this._y -= p._y;
87 }
88
89 public translate2(u : number, v : number) : Point2D {
90 return new Point2D( u + this._x , v + this._y );
91 }
92
93 public translate(p : Point2D) : Point2D {
94 return new Point2D( p.x + this._x , p.y + this._y );
95 }
96
97 public translateSelf2(u : number, v : number) : void {
98
99 this._x += u;
100 this._y += v;
101 }
102
103 public translateSelf(p : Point2D) : void {
104
105 this._x += p.x;
106 this._y += p.y;
107 }
108
109 public scale(s : number) : Point2D {
110 return new Point2D( s * this._x , s * this._y );
111 }
112
113 public scaleSelf(s : number) : void {
114
115 // As above, but it's done in-place rather than returning a copy.
116 this._x *= s
117 this._y *= s;
118 }
119
120 public rotate(theta : number) : Point2D {
121
122 // Apply rotation matrix in the usual (RH) way. theta in radians.
123 let c = Math.cos(theta);
124 let s = Math.sin(theta);
125 return new Point2D (
126 c * this._x - s * this._y ,
127 s * this._x + c * this._y
128 );
129 }
130
131 public rotateSelf(theta : number) : void {
132
133 let c = Math.cos(theta);
134 let s = Math.sin(theta);
135
136 let u = c * this._x - s * this._y ;
137 let v = s * this._x + c * this._y ;
138
139 this._x = u;
140 this._y = v;
141 }
142
143 public rotateAbout(c : Point2D , theta : number ) : Point2D {
144
145 // Rotate this about c by angle theta, returning the result.
146 let answer = new Point2D(this.x - c.x , this.y - c.y );
147 answer = answer.rotate( theta );
148 answer._x += c.x;
149 answer._y += c.y;
150 return answer;
151 }
152
153 public dot(a : Point2D) : number {
154
155 // Return this dot a.
156 return a.x * this._x + a.y * this._y;
157 }
158
159 public length() : number {
160 return Math.sqrt(this._x**2 + this._y**2);
161 }
162
163 public static dot(a: Point2D , b : Point2D) : number {
164 // This looks like Java-style overloading, but it's not. One dot()
165 // is static and the other is not.
166 return a.dot(b);
167 }
168
169 public angleBetween( a : Point2D ) : number {
170
171 // Return angle between this and a, based on
172 // this dot a = |this| |a| cos angle
173 // This is the angle between the two, without any orientation.
174 let cos = this.dot(a) / (this.length() * a.length() );
175 return Math.acos(cos);
176 }
177
178 public cliffordBetween( a : Point2D) : number {
179
180 // The "clifford angle," which is like angleBetween(), but it takes
181 // orientation into account. The angle is given relative to ("from") this.
182 return Math.atan2( this.x * a.y - a.x * this.y ,
183 this.x * a.x + this.y * a.y );
184 }
185 }
186
187 // Used for a function of the form f(t) = ( x(t) , y(t) ).
188 type Parametric2DFunction = (t : number) => Point2D;
189
190 // BUG: Really, these should be based on Point2D. E.g., bezier should be three Point2D objects.
191 type CloseSegment = {};
192
193 type MoveToSegment = {
194 x : number;
195 y : number;
196 }
197
198 type LineToSegment = {
199 x : number;
200 y : number;
201 }
202
203 type BezierToSegment = {
204 cx1 : number;
205 cy1 : number;
206 cx2 : number;
207 cy2 : number;
208 x : number;
209 y : number;
210 }
211
212 type QuadToSegment = {
213 cx : number;
214 cy : number;
215 x : number;
216 y : number;
217 }
218
219 type ArcSegment = {
220 x : number;
221 y : number;
222 r : number;
223 a0 : number;
224 a1 : number;
225 ccw : boolean;
226 }
227
228 type ArcToSegment = {
229 x1 : number;
230 y1 : number;
231 x2 : number;
232 y2 : number;
233 r : number;
234 }
235
236 type EllipseSegment = {
237 x : number;
238 y : number;
239 rx : number;
240 ry : number;
241 rot : number;
242 a0 : number;
243 a1 : number;
244 ccw : boolean;
245 }
246
247 type RectSegment = {
248 x : number;
249 y : number;
250 w : number;
251 h : number;
252 }
253
254 type SegmentData = CloseSegment | MoveToSegment | LineToSegment | BezierToSegment |
255 ArcSegment | ArcToSegment | EllipseSegment | RectSegment;
256
257
258 // Almost everything here is static because this is essentially a factory for the
259 // various segment types.
260
261 class PathSegment {
262
263 // The various kinds of segment.
264 // I'm being sloppy about typing here since the use is uncomplicated and
265 // private. Some kind of enumerated type would be better in the abstract.
266
267 // BUG: I should get rid of anything after the QUADRATIC type. The
268 // mathematically clean way to do this is to convert *everything* to beziers,
269 // including ellipses. In fact (?) is a quadratic just a cubic where the
270 // control points coincide? If so, I could get rid of QUADRATIC too.
271 static readonly MOVE_TO = 1;
272 static readonly LINE_TO = 2;
273 static readonly BEZIER = 3;
274 static readonly QUADRATIC = 4;
275 static readonly ARC = 5;
276 static readonly ARC_TO = 6;
277 static readonly ELLIPSE = 7;
278 static readonly RECT = 8;
279 static readonly CLOSE = 9;
280 static readonly UNKNOWN = -1
281
282 // One of the values above.
283 public type = PathSegment.UNKNOWN;
284
285 // The relevant data.
286 // BUG: change variable name to seg.
287 s : SegmentData;
288
289 private constructor(kind : number , d : SegmentData) {
290 this.type = kind;
291 this.s = d;
292 }
293
294 static getClose() : PathSegment {
295 let d : CloseSegment = {};
296 return new PathSegment(PathSegment.CLOSE,d);
297 }
298
299 static getMoveTo(x : number , y : number ) : PathSegment {
300 let d : MoveToSegment = { x : x , y : y };
301 return new PathSegment(PathSegment.MOVE_TO,d);
302 }
303
304 static getLineTo( x : number, y : number ) : PathSegment {
305 let d : LineToSegment = {x : x , y : y }
306 return new PathSegment(PathSegment.LINE_TO,d);
307 }
308
309 static getBezier(cx1 : number , cy1 : number , cx2 : number , cy2 : number ,
310 x : number , y : number ) : PathSegment {
311 let d : BezierToSegment =
312 {cx1 : cx1 , cy1 : cy1 , cx2 : cx2 , cy2 : cy2 , x : x , y : y};
313 return new PathSegment(PathSegment.BEZIER, d );
314 }
315
316 static getQuadratic(cx : number , cy : number , x : number , y : number ) : PathSegment {
317 let d : QuadToSegment = { cx : cx , cy : cy , x : x , y : y };
318 return new PathSegment(PathSegment.QUADRATIC , d );
319 }
320
321 static getArc(x : number , y : number , r : number , a0 : number , a1 : number ,
322 ccw : boolean) : PathSegment {
323 let d : ArcSegment = { x : x , y : y , r : r , a0 : a0 , a1 : a1 , ccw : ccw };
324 return new PathSegment(PathSegment.ARC , d );
325 }
326
327 static getArcTo(x1 : number , y1 : number , x2 : number , y2 : number ,
328 r : number ) : PathSegment {
329 let d : ArcToSegment = { x1 : x1 , y1 : y1 , x2 : x2 , y2 : y2 , r : r };
330 return new PathSegment(PathSegment.ARC_TO , d );
331 }
332
333 static getEllipse(x : number , y : number , rx : number , ry : number , rot : number ,
334 a0 : number , a1 : number , ccw : boolean ) : PathSegment {
335 // BUG: If I convert everything to bezier, then many of these static
336 // methods can be eliminated.
337 // YES. THIS IS A BAD IDEA IN EVERY WAY. ONLY BEZIER CURVES SHOULD
338 // BE ALLOWED INTERNALLY.
339 // OTOH, there are certain shapes, like an ellipse or rectangle, that
340 // should be treated as a single unitary thing.
341 // What I should probably do is sub-class FPath for these. Interally, they
342 // can be represented as a messy bezier thing, but that would be hidden from the user.
343 // At the same time, one might want to add an ellipse or rect to an existing path to
344 // obtain various fill effects. So, the ellipse sub-class will need something like
345 // a toFPath() method so that it can be added to a normal FPath.
346 let d : EllipseSegment = { x : x , y : y , rx : rx , ry : ry , rot : rot , a0 : a0 ,
347 a1 : a1 , ccw : ccw };
348 return new PathSegment(PathSegment.ELLIPSE , d );
349 }
350
351 static getRect(x : number , y : number , w : number , h : number ) : PathSegment {
352 let d : RectSegment = { x : x , y : y , w : w , h : h };
353 return new PathSegment(PathSegment.RECT , d );
354 }
355
356 }
357
358
359 // BUG: Add some flags so that things could be drawn or not drawn based
360 // on whether the output is going to tikz or to the screen.
361
362 class FPath extends Path2D {
363
364 // An array of PathSegments.
365 segs : PathSegment[] = [];
366
367
368 constructor() {
369 super();
370 }
371
372 addPath(p : FPath ) : void {
373
374 // Append the elements of p to this.
375 for (let i = 0; i < p.segs.length; i++)
376 this.segs.push(p.segs[i]);
377 }
378
379 closePath () : void {
380 super.closePath();
381 this.segs.push(PathSegment.getClose());
382 }
383
384 moveTo(x : number , y : number) : void {
385 super.moveTo(x,y);
386 this.segs.push(PathSegment.getMoveTo(x,y));
387 }
388
389 frontLineTo(x : number , y : number ) : void {
390
391 // To tack a line segment to the *begining* of an existing path.
392 // This assumes that segs[0] is a moveTo() -- as I think (?) it must be
393 // in any reasonable case.
394 // So, you start with a path that looks like
395 // moveTo(a,b) ...whatever
396 // and it becomes
397 // moveTo(x,y) lineTo(a,b) ...whatever.
398 // You're basically drawing as usual, but "from the wrong end."
399 let s = this.segs[0];
400 if (s.type != PathSegment.MOVE_TO)
401 console.log("ERROR: frontLineTo() doesn't start with moveTo(): " +s.type);
402
403 let newfirst = PathSegment.getMoveTo(x,y);
404
405 // Convert the initial moveto to a lineto.
406 // In fact, this is sort of pointless, and is only done this way to respect
407 // the type-checker. It's (x,y) whether it's a lineto or a moveto.
408 let m = <MoveToSegment> s.s;
409 let newsecond = PathSegment.getLineTo(m.x,m.y);
410
411 this.segs[0] = newsecond;
412 this.segs.unshift(newfirst);
413 }
414
415 lineTo(x : number , y : number ) : void {
416 super.lineTo(x,y);
417 this.segs.push(PathSegment.getLineTo(x,y));
418 }
419
420 bezierCurveTo(cx1 : number , cy1 : number , cx2 : number , cy2 : number ,
421 x : number , y : number ) : void {
422 super.bezierCurveTo(cx1,cy1,cx2,cy2,x,y);
423 this.segs.push(PathSegment.getBezier(cx1,cy1,cx2,cy2,x,y));
424 }
425
426 quadraticCurveTo(cx : number , cy : number , x : number , y : number ) : void {
427 super.quadraticCurveTo(cx,cy,x,y);
428 this.segs.push(PathSegment.getQuadratic(cx,cy,x,y));
429 }
430
431 translate(p : Point2D) : FPath {
432
433 // Translate this entire path by the given point.
434
435 // BUG: Not implemented for every possible type of segment.
436
437 let answer = new FPath();
438 for (let i = 0; i < this.segs.length; i++)
439 {
440 let s = this.segs[i];
441 if (s.type == PathSegment.MOVE_TO)
442 {
443 let m = <MoveToSegment> s.s;
444 answer.moveTo(m.x + p.x,m.y + p.y);
445 }
446 else if (s.type == PathSegment.LINE_TO)
447 {
448 let m = <LineToSegment> s.s;
449 answer.lineTo(m.x + p.x,m.y + p.y);
450 }
451 else if (s.type == PathSegment.BEZIER)
452 {
453 let m = <BezierToSegment> s.s;
454 answer.bezierCurveTo( m.cx1 + p.x , m.cy1 + p.y ,
455 m.cx2 + p.x , m.cy2 + p.y , m.x + p.x , m.y + p.y );
456 }
457 else if (s.type == PathSegment.ELLIPSE)
458 {
459 let m = <EllipseSegment> s.s;
460 answer.ellipse(m.x+p.x,m.y+p.y , m.rx, m.ry, m.rot , m.a0 , m.a1 , m.ccw);
461 }
462 else
463 {
464 console.log("whatever translattion you want, it's not done.");
465 }
466 }
467
468 return answer;
469 }
470
471 rotate( a : number ) : FPath {
472
473 // Rotate this entire path about the origin and return the result.
474
475 // BUG: I have only implemented this for bezier curves and lines.
476 // Expanding this probably doesn't make sense until I settle on a
477 // framework to more fully replace Path2D.
478
479 let answer = new FPath();
480 for (let i = 0; i < this.segs.length; i++)
481 {
482 let s = this.segs[i];
483 if (s.type == PathSegment.MOVE_TO)
484 {
485 let m = <MoveToSegment> s.s;
486 let p = new Point2D( m.x , m.y ).rotate( a );
487 answer.moveTo(p.x,p.y);
488 }
489 else if (s.type == PathSegment.LINE_TO)
490 {
491 let m = <LineToSegment> s.s;
492 let p = new Point2D( m.x , m.y ).rotate( a );
493 answer.lineTo(p.x , p.y);
494 }
495 else if (s.type == PathSegment.BEZIER)
496 {
497 let m = <BezierToSegment> s.s;
498 let c1 = new Point2D( m.cx1 , m.cy1 ).rotate( a );
499 let c2 = new Point2D( m.cx2 , m.cy2 ).rotate( a );
500 let e = new Point2D( m.x , m.y ).rotate( a );
501 answer.bezierCurveTo(c1.x,c1.y,c2.x,c2.y,e.x,e.y);
502 }
503 else
504 {
505 console.log("whatever rotation you want, it's not done.");
506 }
507 }
508
509 return answer;
510 }
511
512 scale( r : number ) : FPath {
513
514 // Scale this entire path about the origin and return the result.
515
516 // BUG: I have only implemented this for bezier curves and lines.
517
518 let answer = new FPath();
519 for (let i = 0; i < this.segs.length; i++)
520 {
521 let s = this.segs[i];
522 if (s.type == PathSegment.MOVE_TO)
523 {
524 let m = <MoveToSegment> s.s;
525 let p = new Point2D( r * m.x , r * m.y );
526 answer.moveTo(p.x,p.y);
527 }
528 else if (s.type == PathSegment.LINE_TO)
529 {
530 let m = <LineToSegment> s.s;
531
532 // BUG:
533 console.log("scale not done for lines");
534 }
535 else if (s.type == PathSegment.BEZIER)
536 {
537 let m = <BezierToSegment> s.s;
538 let c1 = new Point2D( r * m.cx1 , r* m.cy1 );
539 let c2 = new Point2D( r * m.cx2 , r * m.cy2 );
540 let p = new Point2D( r * m.x , r * m.y );
541 answer.bezierCurveTo(c1.x,c1.y,c2.x,c2.y,p.x,p.y);
542 }
543 else
544 {
545 console.log("whatever scale you want, it's not done.");
546 }
547 }
548
549 return answer;
550 }
551
552 reflectX() : FPath {
553
554 // Reflect this entire path about the x-axis and return the result.
555
556 // BUG: not implemented for every case.
557
558 let answer = new FPath();
559 for (let i = 0; i < this.segs.length; i++)
560 {
561 let s = this.segs[i];
562 if (s.type == PathSegment.MOVE_TO)
563 {
564 let m = <MoveToSegment> s.s;
565 let p = new Point2D( m.x , -m.y );
566 answer.moveTo(p.x,p.y);
567 }
568 else if (s.type == PathSegment.LINE_TO)
569 {
570 let m = <LineToSegment> s.s;
571 let p = new Point2D( m.x , -m.y);
572 answer.lineTo(p.x,p.y);
573 }
574 else if (s.type == PathSegment.BEZIER)
575 {
576 let m = <BezierToSegment> s.s;
577 let c1 = new Point2D( m.cx1 , -m.cy1 );
578 let c2 = new Point2D( m.cx2 , -m.cy2 );
579 let p = new Point2D( m.x , -m.y );
580 answer.bezierCurveTo(c1.x,c1.y,c2.x,c2.y,p.x,p.y);
581 }
582 else if (s.type == PathSegment.ELLIPSE)
583 {
584 let m = <EllipseSegment> s.s;
585 answer.ellipse(m.x,-m.y,m.rx,m.ry,m.rot,m.a0,m.a1,m.ccw);
586 }
587 else
588 {
589 console.log("whatever reflect you want, it's not done.");
590 }
591 }
592
593 return answer;
594 }
595
596 reflectXY() : FPath {
597
598 // Reflect this entire path about the x-axis AND y-axis.
599
600 // BUG: not implemented for every case.
601 // BUG: Also, what about reflectY()?
602
603 let answer = new FPath();
604 for (let i = 0; i < this.segs.length; i++)
605 {
606 let s = this.segs[i];
607 if (s.type == PathSegment.MOVE_TO)
608 {
609 let m = <MoveToSegment> s.s;
610 let p = new Point2D( -m.x , -m.y );
611 answer.moveTo(p.x,p.y);
612 }
613 else if (s.type == PathSegment.LINE_TO)
614 {
615 let m = <LineToSegment> s.s;
616 // BUG:
617 console.log("reflect not done for lines");
618 }
619 else if (s.type == PathSegment.BEZIER)
620 {
621 let m = <BezierToSegment> s.s;
622 let c1 = new Point2D( -m.cx1 , -m.cy1 );
623 let c2 = new Point2D( -m.cx2 , -m.cy2 );
624 let p = new Point2D( -m.x , -m.y );
625 answer.bezierCurveTo(c1.x,c1.y,c2.x,c2.y,p.x,p.y);
626 }
627 else
628 {
629 console.log("whatever reflect you want, it's not done.");
630 }
631 }
632
633 return answer;
634 }
635
636 rotateAbout(a : number , p : Point2D ) : FPath {
637
638 // Rotate this entire path about p and return the result.
639 let t1 = this.translate(new Point2D(-p.x,-p.y));
640 let t2 = t1.rotate(a);
641 return t2.translate(p);
642 }
643
644
645 static arcToBezierNEW( r : number , a0 : number , a1 : number ) : FPath {
646
647 // Generate a series of bezier curves to represent an arc. The result
648 // represents an arc of a circle of radius r, centered
649 // at (0,0), going from angle a0 to a1, in radians.
650
651 // Each step should subtend no more than pi/4 radians. Most of the
652 // time pi/2 would be accurate enough, but pi/4 is better, and not that
653 // much extra work.
654 let totalAngle = a1 - a0;
655 if (totalAngle < 0)
656 totalAngle += 2*Math.PI;
657
658 let numCurves = Math.ceil(4 * totalAngle / Math.PI);
659
660 let subtend = totalAngle / numCurves;
661
662 // See the manual for where this comes from. It's the crucial constant
663 // for approximating arcs of circles by cubics.
664 let k = (4/3) * Math.tan(subtend/4);
665
666 // Everything is built out of a single arc for a circle of radius r,
667 // going cw, starting at (1,0) and angle subtend.
668 let s = Math.sin(subtend);
669 let c = Math.cos(subtend);
670
671 let p1 = new Point2D (r,0);
672 let p2 = new Point2D (r,r*k);
673 let p3 = new Point2D (r*(c+k*s),r*(s-k*c));
674 let p4 = new Point2D (r*c,r*s);
675
676 // The arc determined by the p_i above must be rotated to create
677 // a series of sub-arcs to get the total arc we want.
678 let answer = new FPath();
679
680 answer.moveTo(p1.x,p1.y);
681 for (let i = 0; i < numCurves; i++)
682 {
683 answer.bezierCurveTo(p2.x,p2.y,p3.x,p3.y,p4.x,p4.y);
684
685 p2.rotateSelf(subtend);
686 p3.rotateSelf(subtend);
687 p4.rotateSelf(subtend);
688 }
689
690 // Rotate the entire thing so that it starts at a0.
691 answer = answer.rotate(a0);
692
693 return answer;
694 }
695
696 arc(x : number , y : number , r : number , a0 : number , a1 : number , ccw : boolean) : void {
697
698 // BUG: I am pretty sure this isn't right. There are things about
699 // being cw/cww and things like that. It needs to be tested.
700
701 // A circular arc, centered at (x,y) and radius r, from angle
702 // a0 to angle a1 (in radians), going cw or ccw. Like ellipse, this
703 // is basically independent of the surrounding segments. Actually,
704 // the documentation I've found is a little vague on this point,
705 // but it looks like that is how it works.
706 //
707 // Another issue is the fact that these angles, a0 and a1, may
708 // have "extra" multiples of 2pi in them and whether a1>a0.
709 // The first thing this does is reduce the angles to be in [0,2pi).
710 //
711 // The whole cw versus ccw issue amounts to whether you're getting
712 // the "large" arc or the "small" arc. If a1 > a0, then the ccw arc
713 // is the small arc and the cw arc is the large arc. If a1 < a0,
714 // then the ccw arc is the large arc and the cw arc is the small arc.
715 // To untangle this, assume that the arc will be treated ccw, and
716 // swap a1 and a0, if necessary, to make that the case.
717 //
718 // Finally, there's the issue of what cw and ccw mean when in
719 // left or right handed coordinate systems. Ugh.
720 //
721 // See
722 // https://pomax.github.io/bezierinfo/#circles_cubic
723 // for an explanation of the math, which is just HS algrbra.
724 //
725 //
726 // BUG: Seems like this is a special case of an arc of an ellipse.
727
728 if (ccw === undefined)
729 ccw = false;
730
731 // Reduce angles to be in [0,2pi).
732 while (a0 < 0)
733 a0 += 2*Math.PI;
734 while (a1 < 0)
735 a1 += 2*Math.PI;
736
737 while (a0 >= 2*Math.PI)
738 a0 -= 2*Math.PI;
739 while (a1 >= 2*Math.PI)
740 a1 -= 2*Math.PI;
741
742 // If the user asked for cw, then swap the angles so that we only
743 // need to consider the ccw case below.
744 if (ccw === true)
745 {
746 let temp = a1;
747 a1 = a0;
748 a0 = temp;
749 }
750
751 // Get the various arcs for a circle centered at zero.
752 let arcs = FPath.arcToBezierNEW(r,a0,a1);
753
754 // Translate them all by (x,y).
755 arcs = arcs.translate(new Point2D(x,y));
756
757 this.addPath(arcs);
758 }
759
760 ellipse(x : number , y : number , rx : number , ry : number , rot : number ,
761 a0 : number , a1 : number , ccw : boolean) : void {
762
763 // BUG: Long-term, the right thing to do here is convert it (internally)
764 // to a series of bezier curves.
765 if (ccw === undefined)
766 ccw = false;
767 super.ellipse(x,y,rx,ry,rot,a0,a1,ccw);
768 this.segs.push(PathSegment.getEllipse(x,y,rx,ry,rot,a0,a1,ccw));
769 }
770
771 rect(x : number , y : number , w : number , h : number ) : void {
772
773 // BUG: As above, make into a series of line segments. This one is easy.
774 super.rect(x,y,w,h);
775 this.segs.push(PathSegment.getRect(x,y,w,h));
776 }
777
778 static circArcToBezier(r : number , a0 : number , a1 : number ) : FPath {
779
780 // Return a series of n bezier curves for a circle of radius r, extending
781 // from r(cos a0,sin a0) to r (cos a1,sin a1).
782 //
783 // BUG: This should really be part of ellipse().
784
785 let answer = FPath.arcToBezierNEW(r,a0,a1);
786
787 return answer;
788 }
789
790 static parametricToBezier(f : Parametric2DFunction ,
791 t0 : number , t1 : number ,n : number) : FPath {
792
793 // Given a 2D parametric curve, f(t) = x(t),y(t)), this returns a bezier
794 // approximation from t=t0 to t=t1 by taking n time-steps. Obviously,
795 // f must be a function returning f.x and f.y.
796 //
797 // This works by sampling f (n+1) times, plus n times at the in
798 // between points, and fitting a Bezier to each trio of points. It
799 // follows the notes in the "main" manual. This is a hard problem -- or
800 // a messy one. There are various strategies. The one used here is to
801 // choose the tangent at the intermediate point (which I call B) to be
802 // parallel to the line between the two end-points of the Bezier segment.
803 // This is relatively straightforward, but one problem with this is that
804 // the slopes where these segments meet need not be the same -- the
805 // resulting curve is not G_1. I'm pretty sure that I worked out a method
806 // once that was based (somehow?) on the way MetaPost works, but it's
807 // complicated and messy and uses complex numbers.
808 let p = new FPath();
809
810 let p1 : Point2D = f(t0);
811 p.moveTo(p1.x,p1.y);
812
813 for (let i = 0; i < n; i++)
814 {
815 let p4 : Point2D = f(t0 + (i+1)*(t1-t0)/n);
816 let B = f(t0 + (i+0.5)*(t1-t0)/n);
817
818 // Work out an appropriate value for t based on relative distances.
819 let d1 = Math.sqrt((B.x-p1.x)**2 + (B.y-p1.y)**2);
820 let d2 = Math.sqrt((B.x-p4.x)**2 + (B.y-p4.y)**2);
821 let t = d1 / (d1+d2);
822
823 // The p4 to p1 vector:
824 let V = new Point2D(p4.x - p1.x,p4.y-p1.y);
825
826 // e1 = B - (1-t)(p4-p1)/3 and e2 = B + t(p4-p1)/3.
827 let e1 = new Point2D(B.x - (1-t)*V.x/3,B.y - (1-t)*V.y/3);
828 let e2 = new Point2D(B.x + t*V.x/3,B.y +t*V.y/3);
829
830 // Run de Casteljau's algorithm backwards. I call this alpha too,
831 // but r is a better name since it's a ratio.
832 let r = 1 - 1 / (t**3 + (1-t)**3);
833 let u = (1-r)*(1-t)**3;
834 let C = new Point2D(p1.x*u + p4.x*(1-u),p1.y*u + p4.y*(1-u));
835 let A = new Point2D(B.x + (C.x-B.x)/r,B.y + (C.y-B.y)/r);
836 let v1 = new Point2D((e1.x - A.x*t)/(1-t),(e1.y - A.y*t)/(1-t));
837 let v2 = new Point2D((e2.x - A.x*(1-t))/t,(e2.y - A.y*(1-t))/t);
838 let p2 = new Point2D((v1.x - p1.x*(1-t))/t,(v1.y - p1.y*(1-t))/t);
839 let p3 = new Point2D((v2.x - p4.x*t)/(1-t),(v2.y - p4.y*t)/(1-t));
840
841 p.bezierCurveTo(p2.x,p2.y,p3.x,p3.y,p4.x,p4.y);
842
843 p1 = p4.copy();
844 }
845
846 return p;
847 }
848 }
849
850 // Text is a special case because it expects a LH coordinate system, but
851 // everything else is set up for a RH coordinate system. The end-user
852 // shouldn't make a direct call to ctx.fillText(). If he does, then the
853 // the text will be upside-down. So, call this instead.
854 //
855 // Getting the placement of the js to match the placement of the tikz exactly
856 // is difficult because they're using two different fonts. So the tikz
857 // is drawn at (x+dx,y+dy). The dx and dy are optional and default to zero.
858 //
859 // BUG: I *could* create a class, something like FPath, to handle all drawing
860 // of text, which may be more natural to the user. But I would probably have
861 // to extend CanvasRenderingContext2D somehow and use that everywhere, not
862 // just when creating TikZ. For now, this is a sufficient solution.
863 // Another approach would be to overwrite the existing
864 // CanvasRenderingContext2D.fillText method to call the function below.
865 // In some ways, that's the "right" thing to do, but my gut is that
866 // it could lead to various problems and make the code generally brittle.
867
868 function drawText(ctx : CanvasRenderingContext2D, txt : string,
869 x : number , y : number , dx = 0 , dy = 0) : void {
870
871 let saveT = ctx.getTransform();
872
873 if (ctx instanceof CTX)
874 {
875 // Don't fool around. Just write it to the .tikz file.
876 // BUG: The ts compiler complains about this, but it works fine.
877 ctx.fillText(txt , x + dx , y + dy );
878 ctx.setTransform(saveT);
879 return;
880 }
881
882 // Get the measurements -- all we really care about is the baseline.
883 // Transform the ctx so that the horizontal line at y becomes the
884 // origin, flip the scale, and draw at (x,0).
885 //
886 // Recapitulating the info on MDN, we care about m.actualBoundingBoxAscent
887 // and m.actualBoundBoxDescent, which give distances from ctx.textBaseline
888 // to the relevant side of the bounding box of the text. The baseline
889 // defaults to the 'alphabetic' setting, which puts the baseline just
890 // under where you normally draw the letter -- B sits on the baseline,
891 // while p hangs below it.
892 let m : TextMetrics = ctx.measureText(txt);
893
894 ctx.translate(0,y);
895 ctx.scale(1,-1);
896 ctx.textBaseline = 'bottom';
897 ctx.fillText(txt , x , 0 );
898
899 ctx.setTransform(saveT);
900 }
901
902 // As above, but these to draw the text in only one scenario or
903 // the other. This could be handled with boolean arguments to the
904 // above, but this seems clearer for the user.
905 function drawTextBrowserOnly(ctx : CanvasRenderingContext2D | CTX, txt : string,
906 x : number , y : number , dx = 0 , dy = 0) : void {
907
908 if (ctx instanceof CTX)
909 // Skip it.
910 return;
911
912 drawText(ctx,txt,x,y,dx,dy);
913 }
914
915 function drawTextTikZOnly(ctx : CanvasRenderingContext2D | CTX, txt : string,
916 x : number , y : number , dx = 0 , dy = 0) : void {
917
918 if (ctx instanceof CTX)
919 ctx.fillText(txt , x + dx , y + dy );
920 }
921
922
923 // This is to act much like the object returned from
924 // canvas.getContext('2d').
925 // Only a few elements of the standard context class are needed.
926 // I purposely did *not* make this extend CanvasRenderingContext2D.
927 // By not extending, you can't accidentally make use of some feature
928 // of the normal ctx framework and have it silently fail.
929 //
930 // This is one major difference. Each time you want to render a figure,
931 // you need a new one of these since the tikz text goes out to a file
932 // with a different name. In principle, it would be possible to allow
933 // reusing these, but there's no value in allowing for that.
934
935 // I had hoped not to need to deal with transformation matricies, and
936 // just (implicitly) use the identity matrix. However, certain things
937 // are easier for the user if they are permitted. See
938 // www.alanzucconi.com/2016/02/10/tranfsormation-matrix
939 // for a brief summary of how these work.
940 //
941 // Think of the matrix as R in the upper left, for rotation etc, and
942 // (tx,ty,1) in the right column for translation, with M as the overall
943 // matrix. The bottom row is always (0 0 1). If the user gives (x y) as
944 // some position relative to M, then the "real" position is M(x y 1).
945 // By "real" I mean that position relative to the identity matrix.
946 //
947 // BUG: I think I am doing this the wrong way. As things stand, I store
948 // the thing the user does (the path and any points or whatever that
949 // specify) in terms given by the user. Then I convert those values to
950 // their "unadjusted" values when written to tikz output. Instead, I should
951 // convert things as they come in. For one thing, as things stand, if
952 // the user adjusts the t-matrix as things are drawn, it would mess up
953 // everything. This would also side-step certain questions like what
954 // a shear transformation should mean for something like an ellipse. If
955 // we correct things as just described, then an ellipse is an ellipse,
956 // and it is not shear-transformed, although the points where ellipse
957 // is located would be shear-transformed.
958 //
959 // BUG: Add a flag, like CTX.paper, and set is to true here.
960 // That way, the rendering process can output something different on paper.
961 // This flag will be undefined when run in a browser.
962
963 class CTX {
964
965 // Transformation matrix.
966 // BUG: Try to get rid of this. I think that, now that all drawing is
967 // done with a RH system, this is unnecessary. Everything related to
968 // tmatrix is private and I think it's effectively unused.
969 private tmatrix = [[1,0,0],[0,1,0],[0,0,1]];
970
971 // BUG: This is *not* the right way to do things, but it's easier.
972 // The problem is in scaling lengths, which are not points. This is a
973 // particular problem with radii. The proper solution is to work this value
974 // out from the tmatrix, but that's messy.
975 // This is why things like ellipses should be treated as beziers.
976 private netScale = 1.0;
977
978 // To allow the user to set the linewidth. Otherwise, tikz uses a
979 // default value of 0.4pt. Tikz has certained named line widths, like
980 // 'semithick' and 'ultra thin' but I don't care about those. It's better
981 // to stick with numerical values to be consistent with js.
982 // This name matches what's used in a "normal" ctx.
983 // The way to specify line width in tikz is as an option to \draw:
984 // \draw[line width = 1mm] ...whatever...
985 // for example.
986 lineWidth = 1.0;
987
988 // File name (without the '.tizk') for the figure.
989 figureName = "";
990
991 // This holds the output as it is generated.
992 tikzstr = "";
993
994
995 constructor(name : string) {
996
997 // Provide the name of the figure whose tikz is being generated.
998 // This goes to a file, which is fiddly with js. The contents of the
999 // file will be sent to the server, and it is assumed that the server
1000 // knows what to do. A normal HTTP server will choke on it (really,
1001 // it will just ignore it).
1002 //
1003 // As each call to stroke(), fill(), and so forth is made, the corresponding
1004 // tikz is noted. When all these are calls are done, call close() to write it out.
1005 this.figureName = name;
1006 this.tikzstr = "";
1007
1008 // The tikz file needs a bit of a heading.
1009 this.tikzstr += "\\begin{tikzpicture}\n";
1010
1011 // And everything is clipped to the permitted drawing area. To obtain
1012 // that area, we need to look at the figure specification.
1013 let myFunc : AugmentedDrawingFunction = getAugmentedFunction ( name );
1014 let fpc : FigurePanel = myFunc.figurePanelClass !;
1015
1016 // Neither one really seems to give the right thing.
1017 // Maybe use \clip as an option to
1018 // \begin{tikzpicture}[\clip something?]
1019 //this.tikzstr += "\\clip (0bp,0bp) rectangle (" +fpc.textWidth+
1020 // "bp," + fpc.h+ "bp);\n";
1021 this.tikzstr += "\\useasboundingbox (0bp,0bp) rectangle (" +fpc.textWidth.toFixed(2)+
1022 "bp," + (fpc.h - fpc.lowerPadding - fpc.upperPadding).toFixed(2)+ "bp);\n";
1023 }
1024
1025 close() {
1026
1027 // Finalize the tikz specification, and write it out.
1028 //
1029 // Note that, under Firefox, this generates an error on the console:
1030 //
1031 // XML Parsing Error: no root element found
1032 // Location: http://localhost:8000/geartest01.tikz
1033 // Line Number 1, Column 1:
1034 //
1035 // or whatever the file name is that's saved. Apparently this is a
1036 // "known issue" (aka, a bug) with Firefox. No such message appears
1037 // with MS Edge. It works the same either way.
1038 this.tikzstr += "\\end{tikzpicture}\n";
1039
1040 // BUG: No doubt there is a more modern fetch() way to do this.
1041 let req = new XMLHttpRequest();
1042
1043 // This is *really* not the standard way to do things.
1044 // Pass the file name to save under, then the text to save.
1045 // I *should* be passing some cgi script that takes input, but
1046 // I've tweaked the http server so that it's non-standard,
1047 // and does what I want instead of what it is supposed to do.
1048 let fname = this.figureName + ".tikz";
1049 req.open("POST",fname);
1050
1051 // I have no idea whether this is really necessary.
1052 req.setRequestHeader("Content-Type","text/plain;charset=UTF-8");
1053
1054 req.send(this.tikzstr);
1055 }
1056
1057 private static clone3x3Matrix(m : number[][]) : number[][] {
1058
1059 // JS seems not to have a standard way of creating a copy of a matrix.
1060 // This does it for a 3x3 matrix and returns the result.
1061 let a : number[][] = [];
1062 a[0] = [];
1063 a[0][0] = m[0][0];
1064 a[0][1] = m[0][1];
1065 a[0][2] = m[0][2];
1066
1067 a[1] = [];
1068 a[1][0] = m[1][0];
1069 a[1][1] = m[1][1];
1070 a[1][2] = m[1][2];
1071
1072 a[2] = [];
1073 a[2][0] = m[2][0];
1074 a[2][1] = m[2][1];
1075 a[2][2] = m[2][2];
1076
1077 return a;
1078 }
1079
1080 private getTransform() : number[][] {
1081 return CTX.clone3x3Matrix(this.tmatrix);
1082 }
1083
1084 private setTransform(t : number[][]) : void {
1085 this.tmatrix = CTX.clone3x3Matrix(t);
1086 }
1087
1088 private translate(tx : number , ty : number ) : void {
1089
1090 // Adjust the transformation matrix. Going forward, this will have the
1091 // effect of converting (x,y) to (tx + x,ty+y) whenever the user
1092 // refers to (x,y).
1093 this.tmatrix[0][2] += tx;
1094 this.tmatrix[1][2] += ty;
1095 }
1096
1097 private scale(sx : number , sy : number ) : void {
1098
1099 // Scale the transformation matrix.
1100 // Let S = diag(sx,sy,1). The new t-matrix is the old t-matrix times S.
1101 //
1102 // BUG: I am not sure. Maybe it should be S times old t-matrix, and
1103 // I have the order wrong. For the time being it doesn't matter since
1104 // every case I care about has sx=sy and the matrices commute in that
1105 // special case.
1106 this.tmatrix[0][0] *= sx;
1107 this.tmatrix[0][1] *= sy;
1108
1109 this.tmatrix[1][0] *= sx;
1110 this.tmatrix[1][1] *= sy;
1111
1112 // Track this here too.
1113 // BUG: This assumes that sx = xy.
1114 this.netScale *= sx;
1115 }
1116
1117 private applyTMatrix(x : number , y : number ) : {x : number , y : number } {
1118
1119 // Return tmatrix times (x,y). As a matrix operation, this is
1120 // tmatrix x (x y 1), but we only return the first two entries.
1121 let ax = this.tmatrix[0][0] * x + this.tmatrix[0][1] * y + this.tmatrix[0][2];
1122 let ay = this.tmatrix[1][0] * x + this.tmatrix[1][1] * y + this.tmatrix[1][2];
1123
1124 return {x: ax, y: ay};
1125 }
1126
1127 handlePath(path : FPath ) : void {
1128
1129 // Called by either fill() or stroke().
1130 var segs = path.segs;
1131
1132 for (let i = 0; i < segs.length; i++)
1133 {
1134 // s is a PathSegment object.
1135 let s = segs[i];
1136
1137 if (s.type == PathSegment.MOVE_TO)
1138 {
1139 let m = <MoveToSegment> s.s;
1140 let t = this.applyTMatrix(m.x,m.y);
1141 //this.tikzstr += "(" +s.x+ "pt, " + s.y+ "pt) ";
1142 this.tikzstr += "(" +t.x.toFixed(2)+ "bp, " + t.y.toFixed(2)+ "bp) ";
1143 }
1144 else if (s.type == PathSegment.LINE_TO)
1145 {
1146 // Lines are drawn with the tikz \draw command. It takes the form
1147 // \draw [options] (x1,y1) -- (x2,y2);
1148 // Note that I include "bp" for the dimensions. I think that tikz
1149 // defaults to cm if no dimension is given, so I should specify
1150 // something. Note also that I use bp, not pt.
1151 //
1152 // BUG: I am not sure whether the tikz point is 72ppi or 72.27 ppi
1153 // to match latex.
1154 //
1155 // BUG: For the time being, I will ignore these options, but they
1156 // can be things like fill or dashed, or to set the color or line
1157 // width, and probably a mess of other stuff.
1158 let m = <LineToSegment> s.s;
1159 let t = this.applyTMatrix(m.x,m.y);
1160 this.tikzstr += "-- (" +t.x.toFixed(2)+ "bp, " + t.y.toFixed(2)+ "bp) ";
1161 }
1162 else if (s.type == PathSegment.BEZIER)
1163 {
1164 // The sources I found aren't very explicit about exactly how
1165 // this is implemented. I assume it's done in the usual way.
1166 // We have
1167 // P(t) = B(3,0)*CP + B(3,1)*P1 + B(3,2)*P2 + B(3,3)*P3,
1168 // where t\in [0,1] and B are the usual Bernstein polynomials (the
1169 // functions of t):
1170 // B(n,m) = C(n,m) t^m (1-t)^(n-m),
1171 // and C is the choice function.
1172
1173 // See also the tikz/pgf manual (v3.1.9a), p. 156, for the output.
1174 // However the manual is wrong, or not clear. Use 'and' between
1175 // the control points.
1176 //
1177 // The gist is that CP is fixed point where the curve starts;
1178 // it's implicit for both Java and tikz. P1 and P2 are the control
1179 // points and P3 is where the curve terminates. Fortunately this
1180 // matches up nicely with the tikz syntax.
1181 let m = <BezierToSegment> s.s;
1182 let t1 = this.applyTMatrix( m.cx1 , m.cy1);
1183 let t2 = this.applyTMatrix( m.cx2 , m.cy2);
1184 let t3 = this.applyTMatrix( m.x , m.y);
1185
1186 this.tikzstr +=
1187 ".. controls (" +t1.x.toFixed(2)+ "bp, " +t1.y.toFixed(2)+ "bp) and (" +
1188 t2.x.toFixed(2)+ "bp, " +t2.y.toFixed(2)+ "bp) .. (" +
1189 t3.x.toFixed(2)+ "bp, " +t3.y.toFixed(2)+ "bp)";
1190 }
1191 else if (s.type == PathSegment.QUADRATIC)
1192 {
1193 // BUG: Put this back.
1194 console.log("quadratic does not work");
1195 // Tikz has this too (whew). Oddly, it's part of the pgf stuff.
1196 // Everything else is drawn with \draw (or \fill), but this
1197 // uses \pgfpathquadraticcurveto. I'm not sure if that matters,
1198 // and I hope that you can mix these freely in the middle of
1199 // a \draw command. The tikz/pgf manual isn't very clear on
1200 // mixing these.
1201 // BUG: I wonder if I should be using commands like \pgflineto,
1202 // \pgfcurveto, and so forth, throughout what I've done.
1203 // See the tikz/pgf manul (v3.1.9a), p. 1095.
1204 //
1205 // BUG: I'm going to code this hoping that it works, but I suspect
1206 // that it will not, and will need to go back and change to
1207 // something other than \draw or \fill to start with.
1208 // Maybe I need to define an entire path and then \draw or \fill
1209 // it? It looks like you define that path, then say
1210 // \pgfusepath{fill} or whatever.
1211 //
1212 // BUG: Maybe I could convert this to a cubic here and avoid this
1213 // entire messy issue?
1214 //
1215 // NOTE: pgf has some nice commands for drawing only *part* of
1216 // a Bezier curve. See p. 1097 for \pgfpathcurvebetweentime.
1217
1218 // BUG: Maybe I'll be lucky and this is never called.
1219 // I think (?) it must be that the only time this type of
1220 // segment ever arises is if the user users a QuadCurve2D, which
1221 // seems (?) unlikely.
1222 /*
1223 let t1 = this.applyTMatrix(s.cx,s.cy);
1224 let t2 = this.applyTMatrix(s.x,s.y);
1225
1226 //this.tikzstr +=
1227 // "\\pgfpathquadraticcurveto {\\pgfpoint{" +
1228 // s.cx+ "pt}{" +x.cy+ "pt}}{\\pgfpoint{" +
1229 // s.x+ "pt}{" +s.y+ "pt}}";
1230 this.tikzstr +=
1231 "\\pgfpathquadraticcurveto {\\pgfpoint{" +
1232 t1.x+ "bp}{" +t1.y+ "bp}}{\\pgfpoint{" +
1233 t2.x+ "bp}{" +t2.y+ "bp}}";
1234 */
1235 }
1236 else if (s.type == PathSegment.ARC)
1237 {
1238 console.log("arc");
1239 // This is a circular arc of a circle
1240 // centered at (x,y) over a given range of angles (cw or ccw).
1241 //
1242 // BUG: For the remaining cases, I may need to do something
1243 // special. It's not clear exactly what the browser is doing
1244 // with these. Are they converted, internally, to bezier
1245 // curves or are they somehow rendered more directly.
1246
1247 this.tikzstr += "no arc implemented";
1248 }
1249 else if (s.type == PathSegment.ARC_TO)
1250 {
1251 console.log("arc to not done");
1252 // This is essentially a bezier curve.
1253 // You have two control points and a radius. It is not
1254 // clear exactly how it works.
1255
1256 this.tikzstr += "no arcTo implemented";
1257 }
1258 else if (s.type == PathSegment.ELLIPSE)
1259 {
1260 // BUG: This will only draw a complete ellipse, not an arc of
1261 // an ellipse.
1262 // BUG: The foolishness with netScale is another reason not
1263 // to allow an ellipse type. If an ellipse were really a series
1264 // of bezier curves, then this would be a non-issue.
1265 let m = <EllipseSegment> s.s;
1266
1267 let c = this.applyTMatrix( m.x , m.y );
1268
1269 //console.log(s.x+ "," +s.y+ " becomes " +c.x+ " " +c.y);
1270
1271 //this.tikzstr += "(" +c.x+ "pt," +c.y+
1272 // "pt) ellipse [x radius=" +s.rx*this.netScale+
1273 // "pt,y radius =" + s.ry*this.netScale+ "pt]";
1274
1275 this.tikzstr += "(" +c.x.toFixed(2)+ "bp," +c.y.toFixed(2)+
1276 "bp) ellipse [x radius=" + (m.rx * this.netScale).toFixed(2)+
1277 "bp,y radius =" + (m.ry * this.netScale).toFixed(2)+ "bp]";
1278 }
1279 else if (s.type == PathSegment.RECT)
1280 {
1281 console.log("rect not done");
1282 this.tikzstr += "no rect implemented";
1283 }
1284 else if (s.type == PathSegment.CLOSE)
1285 {
1286 this.tikzstr += "-- cycle";
1287 }
1288 else
1289 {
1290 console.log("unknown FPath: " +s.type);
1291 }
1292 }
1293
1294 this.tikzstr += ";\n";
1295 }
1296
1297 stroke(path : FPath ) : void {
1298
1299 let segs = path.segs;
1300 if (segs.length === 0)
1301 return;
1302
1303 this.tikzstr += "\\draw[line width=" +this.lineWidth.toFixed(2)+ "bp] ";
1304
1305 this.handlePath(path);
1306 }
1307
1308 fill(path : FPath ) : void {
1309
1310 let segs = path.segs;
1311 if (segs.length === 0)
1312 return;
1313
1314 this.tikzstr += "\\fill ";
1315
1316 this.handlePath(path);
1317 }
1318
1319 fillText(s : string , x : number , y : number ) : void {
1320
1321 // BUG: This is now done with top-level functions now and shouldn't
1322 // be called (or callable) by outside code.
1323 //
1324 // BUG: I have my doubts about including this one. It needs to be done
1325 // *somehow*, but I am concerned about a mismatch between the JS
1326 // font and the fonts used by latex.
1327 //
1328 // BUG: I am ignoring the ctx.font setting. It does seem that if you
1329 // set it to '10px san-serif' you get something reasonable for the
1330 // browswer that doesn't look too different than latex.
1331 //
1332 // BUG: This is so fussy that I suspect that any drawing that is at
1333 // all tricky will require that the user provide different placement for
1334 // text on the browser and text on the page. Getting things to match
1335 // up *exactly* may be impossible.
1336
1337 let t = this.applyTMatrix(x,y);
1338 // I had this as 'anchor=south west', but 'base west' seems closer
1339 // to what latex does.
1340 // BUG: It's all a mystery.
1341 this.tikzstr +=
1342 "\\node [anchor=base west] at (" +t.x.toFixed(2)+ "pt, " +t.y.toFixed(2)+ "pt) {" +s+ "};\n";
1343
1344
1345 }
1346
1347 }
1348
1349
1350
1351 // A grab-bag of numerical techniques.
1352 // BUG: This doesn't really belong in this file.
1353
1354 type FunctionRealtoReal = ( x : number ) => number;
1355
1356 class Numerical {
1357
1358 static newton(f : FunctionRealtoReal , g : number, a : number , b : number ,
1359 y : number , e : number ) : number {
1360
1361 // Given a function, f, and an initial guess, g, bracketed between a and b,
1362 // for the argument to f, and a target value, y, this returns x such that
1363 // f(x) = y to within error, e.
1364 //
1365 // A crude off-the-cuff implementation of Newton-Raphson.
1366 // This will only work in the tamest situations.
1367 //
1368 // Recall that the idea is that
1369 // f(x0 + dx) ~ f(x0) + f'(x0) dx
1370 // We want y = f(x + dx) and that is approximately equivalent to
1371 // y = f(x0) + f'(x0) dx or dx = ( y - f(x0) ) / f'(x0)
1372 // so that x0 becomes x1 = x0 + dx = x0 + ( y - f(x0) ) / f'(x0)
1373 //
1374 // NOTE: I had hoped to avoid the need to bracket entirely, and for
1375 // some functions (and sufficiently good initial guesses), you could,
1376 // but it's too easy for the algorithm to get lost among local extrema
1377 // if there is no bracket.
1378 //
1379 // In fact, here is a good example of why bracketing is needed.
1380 // Let f = cos x + x sin x, which happens to be the x-coordinate for
1381 // the parameterization of the unit involute. Suppose that you want
1382 // to find x for which f(x) = 1.5, and you start off with a guess of
1383 // x = 0.5. The slope of f at 0.5 is small so that Newton-Raphson
1384 // sends x1 to a value that is beyond the inflection point near x = 3.
1385 // At that point things go haywire.
1386
1387 let x0 = g;
1388 let y0 = f(x0);
1389
1390 let i = 0;
1391
1392 while (Math.abs(y-y0) > e)
1393 {
1394 let fplus = f(x0+e);
1395 let fminus = f(x0-e);
1396 let fprime = (fplus - fminus) / (2*e);
1397
1398 let dx = (y - y0) / fprime;
1399 let x1 = x0 + dx;
1400
1401 // Make sure we haven't passed a bracket. Just subdivide if we have.
1402 if (x1 > b)
1403 x1 = (x1-x0)/2;
1404 if (x1 < a)
1405 x1 = (x0-x1)/2;
1406
1407 x0 = x1;
1408 y0 = f(x0);
1409
1410 // Don't allow an infinite loop
1411 ++i;
1412 if (i > 100)
1413 return x0;
1414 }
1415
1416 return x0;
1417 }
1418
1419 }