1 /*
  2     Copyright 2008-2024
  3         Matthias Ehmann,
  4         Michael Gerhaeuser,
  5         Carsten Miller,
  6         Bianca Valentin,
  7         Alfred Wassermann,
  8         Peter Wilfahrt
  9 
 10     This file is part of JSXGraph.
 11 
 12     JSXGraph is free software dual licensed under the GNU LGPL or MIT License.
 13 
 14     You can redistribute it and/or modify it under the terms of the
 15 
 16       * GNU Lesser General Public License as published by
 17         the Free Software Foundation, either version 3 of the License, or
 18         (at your option) any later version
 19       OR
 20       * MIT License: https://github.com/jsxgraph/jsxgraph/blob/master/LICENSE.MIT
 21 
 22     JSXGraph is distributed in the hope that it will be useful,
 23     but WITHOUT ANY WARRANTY; without even the implied warranty of
 24     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 25     GNU Lesser General Public License for more details.
 26 
 27     You should have received a copy of the GNU Lesser General Public License and
 28     the MIT License along with JSXGraph. If not, see <https://www.gnu.org/licenses/>
 29     and <https://opensource.org/licenses/MIT/>.
 30  */
 31 
 32 /*global JXG: true, define: true*/
 33 /*jslint nomen: true, plusplus: true*/
 34 
 35 /**
 36  * @fileoverview In this file the geometry element Curve is defined.
 37  */
 38 
 39 import JXG from "../jxg.js";
 40 import Clip from "../math/clip.js";
 41 import Const from "./constants.js";
 42 import Coords from "./coords.js";
 43 import Geometry from "../math/geometry.js";
 44 import GeometryElement from "./element.js";
 45 import GeonextParser from "../parser/geonext.js";
 46 import ImplicitPlot from "../math/implicitplot.js";
 47 import Mat from "../math/math.js";
 48 import Metapost from "../math/metapost.js";
 49 import Numerics from "../math/numerics.js";
 50 import Plot from "../math/plot.js";
 51 import QDT from "../math/qdt.js";
 52 import Type from "../utils/type.js";
 53 
 54 /**
 55  * Curves are the common object for function graphs, parametric curves, polar curves, and data plots.
 56  * @class Creates a new curve object. Do not use this constructor to create a curve. Use {@link JXG.Board#create} with
 57  * type {@link Curve}, or {@link Functiongraph} instead.
 58  * @augments JXG.GeometryElement
 59  * @param {String|JXG.Board} board The board the new curve is drawn on.
 60  * @param {Array} parents defining terms An array with the function terms or the data points of the curve.
 61  * @param {Object} attributes Defines the visual appearance of the curve.
 62  * @see JXG.Board#generateName
 63  * @see JXG.Board#addCurve
 64  */
 65 JXG.Curve = function (board, parents, attributes) {
 66     this.constructor(board, attributes, Const.OBJECT_TYPE_CURVE, Const.OBJECT_CLASS_CURVE);
 67 
 68     this.points = [];
 69     /**
 70      * Number of points on curves. This value changes
 71      * between numberPointsLow and numberPointsHigh.
 72      * It is set in {@link JXG.Curve#updateCurve}.
 73      */
 74     this.numberPoints = this.evalVisProp('numberpointshigh');
 75 
 76     this.bezierDegree = 1;
 77 
 78     /**
 79      * Array holding the x-coordinates of a data plot.
 80      * This array can be updated during run time by overwriting
 81      * the method {@link JXG.Curve#updateDataArray}.
 82      * @type array
 83      */
 84     this.dataX = null;
 85 
 86     /**
 87      * Array holding the y-coordinates of a data plot.
 88      * This array can be updated during run time by overwriting
 89      * the method {@link JXG.Curve#updateDataArray}.
 90      * @type array
 91      */
 92     this.dataY = null;
 93 
 94     /**
 95      * Array of ticks storing all the ticks on this curve. Do not set this field directly and use
 96      * {@link JXG.Curve#addTicks} and {@link JXG.Curve#removeTicks} to add and remove ticks to and
 97      * from the curve.
 98      * @type Array
 99      * @see JXG.Ticks
100      */
101     this.ticks = [];
102 
103     /**
104      * Stores a quadtree if it is required. The quadtree is generated in the curve
105      * updates and can be used to speed up the hasPoint method.
106      * @type JXG.Math.Quadtree
107      */
108     this.qdt = null;
109 
110     if (Type.exists(parents[0])) {
111         this.varname = parents[0];
112     } else {
113         this.varname = "x";
114     }
115 
116     // function graphs: "x"
117     this.xterm = parents[1];
118     // function graphs: e.g. "x^2"
119     this.yterm = parents[2];
120 
121     // Converts GEONExT syntax into JavaScript syntax
122     this.generateTerm(this.varname, this.xterm, this.yterm, parents[3], parents[4]);
123     // First evaluation of the curve
124     this.updateCurve();
125 
126     this.id = this.board.setId(this, "G");
127     this.board.renderer.drawCurve(this);
128 
129     this.board.finalizeAdding(this);
130 
131     this.createGradient();
132     this.elType = "curve";
133     this.createLabel();
134 
135     if (Type.isString(this.xterm)) {
136         this.notifyParents(this.xterm);
137     }
138     if (Type.isString(this.yterm)) {
139         this.notifyParents(this.yterm);
140     }
141 
142     this.methodMap = Type.deepCopy(this.methodMap, {
143         generateTerm: "generateTerm",
144         setTerm: "generateTerm",
145         move: "moveTo",
146         moveTo: "moveTo",
147         MinX: "minX",
148         MaxX: "maxX"
149     });
150 };
151 
152 JXG.Curve.prototype = new GeometryElement();
153 
154 JXG.extend(
155     JXG.Curve.prototype,
156     /** @lends JXG.Curve.prototype */ {
157         /**
158          * Gives the default value of the left bound for the curve.
159          * May be overwritten in {@link JXG.Curve#generateTerm}.
160          * @returns {Number} Left bound for the curve.
161          */
162         minX: function () {
163             var leftCoords;
164 
165             if (this.evalVisProp('curvetype') === "polar") {
166                 return 0;
167             }
168 
169             leftCoords = new Coords(
170                 Const.COORDS_BY_SCREEN,
171                 [-this.board.canvasWidth * 0.1, 0],
172                 this.board,
173                 false
174             );
175             return leftCoords.usrCoords[1];
176         },
177 
178         /**
179          * Gives the default value of the right bound for the curve.
180          * May be overwritten in {@link JXG.Curve#generateTerm}.
181          * @returns {Number} Right bound for the curve.
182          */
183         maxX: function () {
184             var rightCoords;
185 
186             if (this.evalVisProp('curvetype') === "polar") {
187                 return 2 * Math.PI;
188             }
189             rightCoords = new Coords(
190                 Const.COORDS_BY_SCREEN,
191                 [this.board.canvasWidth * 1.1, 0],
192                 this.board,
193                 false
194             );
195 
196             return rightCoords.usrCoords[1];
197         },
198 
199         /**
200          * The parametric function which defines the x-coordinate of the curve.
201          * @param {Number} t A number between {@link JXG.Curve#minX} and {@link JXG.Curve#maxX}.
202          * @param {Boolean} suspendUpdate A boolean flag which is false for the
203          * first call of the function during a fresh plot of the curve and true
204          * for all subsequent calls of the function. This may be used to speed up the
205          * plotting of the curve, if the e.g. the curve depends on some input elements.
206          * @returns {Number} x-coordinate of the curve at t.
207          */
208         X: function (t) {
209             return NaN;
210         },
211 
212         /**
213          * The parametric function which defines the y-coordinate of the curve.
214          * @param {Number} t A number between {@link JXG.Curve#minX} and {@link JXG.Curve#maxX}.
215          * @param {Boolean} suspendUpdate A boolean flag which is false for the
216          * first call of the function during a fresh plot of the curve and true
217          * for all subsequent calls of the function. This may be used to speed up the
218          * plotting of the curve, if the e.g. the curve depends on some input elements.
219          * @returns {Number} y-coordinate of the curve at t.
220          */
221         Y: function (t) {
222             return NaN;
223         },
224 
225         /**
226          * Treat the curve as curve with homogeneous coordinates.
227          * @param {Number} t A number between {@link JXG.Curve#minX} and {@link JXG.Curve#maxX}.
228          * @returns {Number} Always 1.0
229          */
230         Z: function (t) {
231             return 1;
232         },
233 
234         /**
235          * Checks whether (x,y) is near the curve.
236          * @param {Number} x Coordinate in x direction, screen coordinates.
237          * @param {Number} y Coordinate in y direction, screen coordinates.
238          * @param {Number} start Optional start index for search on data plots.
239          * @returns {Boolean} True if (x,y) is near the curve, False otherwise.
240          */
241         hasPoint: function (x, y, start) {
242             var t, c, i, tX, tY,
243                 checkPoint, len, invMat, isIn,
244                 res = [],
245                 points,
246                 qdt,
247                 steps = this.evalVisProp('numberpointslow'),
248                 d = (this.maxX() - this.minX()) / steps,
249                 prec, type,
250                 dist = Infinity,
251                 ux2, uy2,
252                 ev_ct,
253                 mi, ma,
254                 suspendUpdate = true;
255 
256             if (Type.isObject(this.evalVisProp('precision'))) {
257                 type = this.board._inputDevice;
258                 prec = this.evalVisProp('precision.' + type);
259             } else {
260                 // 'inherit'
261                 prec = this.board.options.precision.hasPoint;
262             }
263 
264             // From now on, x,y are usrCoords
265             checkPoint = new Coords(Const.COORDS_BY_SCREEN, [x, y], this.board, false);
266             x = checkPoint.usrCoords[1];
267             y = checkPoint.usrCoords[2];
268 
269             // Handle inner points of the curve
270             if (this.bezierDegree === 1 && this.evalVisProp('hasinnerpoints')) {
271                 isIn = Geometry.windingNumber([1, x, y], this.points, true);
272                 if (isIn !== 0) {
273                     return true;
274                 }
275             }
276 
277             // We use usrCoords. Only in the final distance calculation
278             // screen coords are used
279             prec += this.evalVisProp('strokewidth') * 0.5;
280             prec *= prec; // We do not want to take sqrt
281             ux2 = this.board.unitX * this.board.unitX;
282             uy2 = this.board.unitY * this.board.unitY;
283 
284             mi = this.minX();
285             ma = this.maxX();
286             if (Type.exists(this._visibleArea)) {
287                 mi = this._visibleArea[0];
288                 ma = this._visibleArea[1];
289                 d = (ma - mi) / steps;
290             }
291 
292             ev_ct = this.evalVisProp('curvetype');
293             if (ev_ct === "parameter" || ev_ct === "polar") {
294                 // Transform the mouse/touch coordinates
295                 // back to the original position of the curve.
296                 // This is needed, because we work with the function terms, not the points.
297                 if (this.transformations.length > 0) {
298                     this.updateTransformMatrix();
299                     invMat = Mat.inverse(this.transformMat);
300                     c = Mat.matVecMult(invMat, [1, x, y]);
301                     x = c[1];
302                     y = c[2];
303                 }
304 
305                 // Brute force search for a point on the curve close to the mouse pointer
306                 for (i = 0, t = mi; i < steps; i++) {
307                     tX = this.X(t, suspendUpdate);
308                     tY = this.Y(t, suspendUpdate);
309 
310                     dist = (x - tX) * (x - tX) * ux2 + (y - tY) * (y - tY) * uy2;
311 
312                     if (dist <= prec) {
313                         return true;
314                     }
315 
316                     t += d;
317                 }
318             } else if (ev_ct === "plot" || ev_ct === "functiongraph") {
319                 // Here, we can ignore transformations of the curve,
320                 // since we are working directly with the points.
321 
322                 if (!Type.exists(start) || start < 0) {
323                     start = 0;
324                 }
325 
326                 if (
327                     Type.exists(this.qdt) &&
328                     this.evalVisProp('useqdt') &&
329                     this.bezierDegree !== 3
330                 ) {
331                     qdt = this.qdt.query(new Coords(Const.COORDS_BY_USER, [x, y], this.board));
332                     points = qdt.points;
333                     len = points.length;
334                 } else {
335                     points = this.points;
336                     len = this.numberPoints - 1;
337                 }
338 
339                 for (i = start; i < len; i++) {
340                     if (this.bezierDegree === 3) {
341                         //res.push(Geometry.projectCoordsToBeziersegment([1, x, y], this, i));
342                         res = Geometry.projectCoordsToBeziersegment([1, x, y], this, i);
343                     } else {
344                         if (qdt) {
345                             if (points[i].prev) {
346                                 res = Geometry.projectCoordsToSegment(
347                                     [1, x, y],
348                                     points[i].prev.usrCoords,
349                                     points[i].usrCoords
350                                 );
351                             }
352 
353                             // If the next point in the array is the same as the current points
354                             // next neighbor we don't have to project it onto that segment because
355                             // that will already be done in the next iteration of this loop.
356                             if (points[i].next && points[i + 1] !== points[i].next) {
357                                 res = Geometry.projectCoordsToSegment(
358                                     [1, x, y],
359                                     points[i].usrCoords,
360                                     points[i].next.usrCoords
361                                 );
362                             }
363                         } else {
364                             res = Geometry.projectCoordsToSegment(
365                                 [1, x, y],
366                                 points[i].usrCoords,
367                                 points[i + 1].usrCoords
368                             );
369                         }
370                     }
371 
372                     if (
373                         res[1] >= 0 &&
374                         res[1] <= 1 &&
375                         (x - res[0][1]) * (x - res[0][1]) * ux2 +
376                         (y - res[0][2]) * (y - res[0][2]) * uy2 <=
377                         prec
378                     ) {
379                         return true;
380                     }
381                 }
382                 return false;
383             }
384             return dist < prec;
385         },
386 
387         /**
388          * Allocate points in the Coords array this.points
389          */
390         allocatePoints: function () {
391             var i, len;
392 
393             len = this.numberPoints;
394 
395             if (this.points.length < this.numberPoints) {
396                 for (i = this.points.length; i < len; i++) {
397                     this.points[i] = new Coords(
398                         Const.COORDS_BY_USER,
399                         [0, 0],
400                         this.board,
401                         false
402                     );
403                 }
404             }
405         },
406 
407         /**
408          * Computes for equidistant points on the x-axis the values of the function
409          * @returns {JXG.Curve} Reference to the curve object.
410          * @see JXG.Curve#updateCurve
411          */
412         update: function () {
413             if (this.needsUpdate) {
414                 if (this.evalVisProp('trace')) {
415                     this.cloneToBackground(true);
416                 }
417                 this.updateCurve();
418             }
419 
420             return this;
421         },
422 
423         /**
424          * Updates the visual contents of the curve.
425          * @returns {JXG.Curve} Reference to the curve object.
426          */
427         updateRenderer: function () {
428             //var wasReal;
429 
430             if (!this.needsUpdate) {
431                 return this;
432             }
433 
434             if (this.visPropCalc.visible) {
435                 // wasReal = this.isReal;
436 
437                 this.isReal = Plot.checkReal(this.points);
438 
439                 if (
440                     //wasReal &&
441                     !this.isReal
442                 ) {
443                     this.updateVisibility(false);
444                 }
445             }
446 
447             if (this.visPropCalc.visible) {
448                 this.board.renderer.updateCurve(this);
449             }
450 
451             /* Update the label if visible. */
452             if (
453                 this.hasLabel &&
454                 this.visPropCalc.visible &&
455                 this.label &&
456                 this.label.visPropCalc.visible &&
457                 this.isReal
458             ) {
459                 this.label.update();
460                 this.board.renderer.updateText(this.label);
461             }
462 
463             // Update rendNode display
464             this.setDisplayRendNode();
465             // if (this.visPropCalc.visible !== this.visPropOld.visible) {
466             //     this.board.renderer.display(this, this.visPropCalc.visible);
467             //     this.visPropOld.visible = this.visPropCalc.visible;
468             //
469             //     if (this.hasLabel) {
470             //         this.board.renderer.display(this.label, this.label.visPropCalc.visible);
471             //     }
472             // }
473 
474             this.needsUpdate = false;
475             return this;
476         },
477 
478         /**
479          * For dynamic dataplots updateCurve can be used to compute new entries
480          * for the arrays {@link JXG.Curve#dataX} and {@link JXG.Curve#dataY}. It
481          * is used in {@link JXG.Curve#updateCurve}. Default is an empty method, can
482          * be overwritten by the user.
483          *
484          *
485          * @example
486          * // This example overwrites the updateDataArray method.
487          * // There, new values for the arrays JXG.Curve.dataX and JXG.Curve.dataY
488          * // are computed from the value of the slider N
489          *
490          * var N = board.create('slider', [[0,1.5],[3,1.5],[1,3,40]], {name:'n',snapWidth:1});
491          * var circ = board.create('circle',[[4,-1.5],1],{strokeWidth:1, strokecolor:'black', strokeWidth:2,
492          * 		fillColor:'#0055ff13'});
493          *
494          * var c = board.create('curve', [[0],[0]],{strokecolor:'red', strokeWidth:2});
495          * c.updateDataArray = function() {
496          *         var r = 1, n = Math.floor(N.Value()),
497          *             x = [0], y = [0],
498          *             phi = Math.PI/n,
499          *             h = r*Math.cos(phi),
500          *             s = r*Math.sin(phi),
501          *             i, j,
502          *             px = 0, py = 0, sgn = 1,
503          *             d = 16,
504          *             dt = phi/d,
505          *             pt;
506          *
507          *         for (i = 0; i < n; i++) {
508          *             for (j = -d; j <= d; j++) {
509          *                 pt = dt*j;
510          *                 x.push(px + r*Math.sin(pt));
511          *                 y.push(sgn*r*Math.cos(pt) - (sgn-1)*h*0.5);
512          *             }
513          *             px += s;
514          *             sgn *= (-1);
515          *         }
516          *         x.push((n - 1)*s);
517          *         y.push(h + (sgn - 1)*h*0.5);
518          *         this.dataX = x;
519          *         this.dataY = y;
520          *     }
521          *
522          * var c2 = board.create('curve', [[0],[0]],{strokecolor:'red', strokeWidth:1});
523          * c2.updateDataArray = function() {
524          *         var r = 1, n = Math.floor(N.Value()),
525          *             px = circ.midpoint.X(), py = circ.midpoint.Y(),
526          *             x = [px], y = [py],
527          *             phi = Math.PI/n,
528          *             s = r*Math.sin(phi),
529          *             i, j,
530          *             d = 16,
531          *             dt = phi/d,
532          *             pt = Math.PI*0.5+phi;
533          *
534          *         for (i = 0; i < n; i++) {
535          *             for (j= -d; j <= d; j++) {
536          *                 x.push(px + r*Math.cos(pt));
537          *                 y.push(py + r*Math.sin(pt));
538          *                 pt -= dt;
539          *             }
540          *             x.push(px);
541          *             y.push(py);
542          *             pt += dt;
543          *         }
544          *         this.dataX = x;
545          *         this.dataY = y;
546          *     }
547          *     board.update();
548          *
549          * </pre><div id="JXG20bc7802-e69e-11e5-b1bf-901b0e1b8723" class="jxgbox" style="width: 600px; height: 400px;"></div>
550          * <script type="text/javascript">
551          *     (function() {
552          *         var board = JXG.JSXGraph.initBoard('JXG20bc7802-e69e-11e5-b1bf-901b0e1b8723',
553          *             {boundingbox: [-1.5,2,8,-3], keepaspectratio: true, axis: true, showcopyright: false, shownavigation: false});
554          *             var N = board.create('slider', [[0,1.5],[3,1.5],[1,3,40]], {name:'n',snapWidth:1});
555          *             var circ = board.create('circle',[[4,-1.5],1],{strokeWidth:1, strokecolor:'black',
556          *             strokeWidth:2, fillColor:'#0055ff13'});
557          *
558          *             var c = board.create('curve', [[0],[0]],{strokecolor:'red', strokeWidth:2});
559          *             c.updateDataArray = function() {
560          *                     var r = 1, n = Math.floor(N.Value()),
561          *                         x = [0], y = [0],
562          *                         phi = Math.PI/n,
563          *                         h = r*Math.cos(phi),
564          *                         s = r*Math.sin(phi),
565          *                         i, j,
566          *                         px = 0, py = 0, sgn = 1,
567          *                         d = 16,
568          *                         dt = phi/d,
569          *                         pt;
570          *
571          *                     for (i=0;i<n;i++) {
572          *                         for (j=-d;j<=d;j++) {
573          *                             pt = dt*j;
574          *                             x.push(px+r*Math.sin(pt));
575          *                             y.push(sgn*r*Math.cos(pt)-(sgn-1)*h*0.5);
576          *                         }
577          *                         px += s;
578          *                         sgn *= (-1);
579          *                     }
580          *                     x.push((n-1)*s);
581          *                     y.push(h+(sgn-1)*h*0.5);
582          *                     this.dataX = x;
583          *                     this.dataY = y;
584          *                 }
585          *
586          *             var c2 = board.create('curve', [[0],[0]],{strokecolor:'red', strokeWidth:1});
587          *             c2.updateDataArray = function() {
588          *                     var r = 1, n = Math.floor(N.Value()),
589          *                         px = circ.midpoint.X(), py = circ.midpoint.Y(),
590          *                         x = [px], y = [py],
591          *                         phi = Math.PI/n,
592          *                         s = r*Math.sin(phi),
593          *                         i, j,
594          *                         d = 16,
595          *                         dt = phi/d,
596          *                         pt = Math.PI*0.5+phi;
597          *
598          *                     for (i=0;i<n;i++) {
599          *                         for (j=-d;j<=d;j++) {
600          *                             x.push(px+r*Math.cos(pt));
601          *                             y.push(py+r*Math.sin(pt));
602          *                             pt -= dt;
603          *                         }
604          *                         x.push(px);
605          *                         y.push(py);
606          *                         pt += dt;
607          *                     }
608          *                     this.dataX = x;
609          *                     this.dataY = y;
610          *                 }
611          *                 board.update();
612          *
613          *     })();
614          *
615          * </script><pre>
616          *
617          * @example
618          * // This is an example which overwrites updateDataArray and produces
619          * // a Bezier curve of degree three.
620          * var A = board.create('point', [-3,3]);
621          * var B = board.create('point', [3,-2]);
622          * var line = board.create('segment', [A,B]);
623          *
624          * var height = 0.5; // height of the curly brace
625          *
626          * // Curly brace
627          * var crl = board.create('curve', [[0],[0]], {strokeWidth:1, strokeColor:'black'});
628          * crl.bezierDegree = 3;
629          * crl.updateDataArray = function() {
630          *     var d = [B.X()-A.X(), B.Y()-A.Y()],
631          *         dl = Math.sqrt(d[0]*d[0]+d[1]*d[1]),
632          *         mid = [(A.X()+B.X())*0.5, (A.Y()+B.Y())*0.5];
633          *
634          *     d[0] *= height/dl;
635          *     d[1] *= height/dl;
636          *
637          *     this.dataX = [ A.X(), A.X()-d[1], mid[0], mid[0]-d[1], mid[0], B.X()-d[1], B.X() ];
638          *     this.dataY = [ A.Y(), A.Y()+d[0], mid[1], mid[1]+d[0], mid[1], B.Y()+d[0], B.Y() ];
639          * };
640          *
641          * // Text
642          * var txt = board.create('text', [
643          *                     function() {
644          *                         var d = [B.X()-A.X(), B.Y()-A.Y()],
645          *                             dl = Math.sqrt(d[0]*d[0]+d[1]*d[1]),
646          *                             mid = (A.X()+B.X())*0.5;
647          *
648          *                         d[1] *= height/dl;
649          *                         return mid-d[1]+0.1;
650          *                     },
651          *                     function() {
652          *                         var d = [B.X()-A.X(), B.Y()-A.Y()],
653          *                             dl = Math.sqrt(d[0]*d[0]+d[1]*d[1]),
654          *                             mid = (A.Y()+B.Y())*0.5;
655          *
656          *                         d[0] *= height/dl;
657          *                         return mid+d[0]+0.1;
658          *                     },
659          *                     function() { return "length=" + JXG.toFixed(B.Dist(A), 2); }
660          *                 ]);
661          *
662          *
663          * board.update(); // This update is necessary to call updateDataArray the first time.
664          *
665          * </pre><div id="JXGa61a4d66-e69f-11e5-b1bf-901b0e1b8723"  class="jxgbox" style="width: 300px; height: 300px;"></div>
666          * <script type="text/javascript">
667          *     (function() {
668          *      var board = JXG.JSXGraph.initBoard('JXGa61a4d66-e69f-11e5-b1bf-901b0e1b8723',
669          *             {boundingbox: [-4, 4, 4,-4], axis: true, showcopyright: false, shownavigation: false});
670          *     var A = board.create('point', [-3,3]);
671          *     var B = board.create('point', [3,-2]);
672          *     var line = board.create('segment', [A,B]);
673          *
674          *     var height = 0.5; // height of the curly brace
675          *
676          *     // Curly brace
677          *     var crl = board.create('curve', [[0],[0]], {strokeWidth:1, strokeColor:'black'});
678          *     crl.bezierDegree = 3;
679          *     crl.updateDataArray = function() {
680          *         var d = [B.X()-A.X(), B.Y()-A.Y()],
681          *             dl = Math.sqrt(d[0]*d[0]+d[1]*d[1]),
682          *             mid = [(A.X()+B.X())*0.5, (A.Y()+B.Y())*0.5];
683          *
684          *         d[0] *= height/dl;
685          *         d[1] *= height/dl;
686          *
687          *         this.dataX = [ A.X(), A.X()-d[1], mid[0], mid[0]-d[1], mid[0], B.X()-d[1], B.X() ];
688          *         this.dataY = [ A.Y(), A.Y()+d[0], mid[1], mid[1]+d[0], mid[1], B.Y()+d[0], B.Y() ];
689          *     };
690          *
691          *     // Text
692          *     var txt = board.create('text', [
693          *                         function() {
694          *                             var d = [B.X()-A.X(), B.Y()-A.Y()],
695          *                                 dl = Math.sqrt(d[0]*d[0]+d[1]*d[1]),
696          *                                 mid = (A.X()+B.X())*0.5;
697          *
698          *                             d[1] *= height/dl;
699          *                             return mid-d[1]+0.1;
700          *                         },
701          *                         function() {
702          *                             var d = [B.X()-A.X(), B.Y()-A.Y()],
703          *                                 dl = Math.sqrt(d[0]*d[0]+d[1]*d[1]),
704          *                                 mid = (A.Y()+B.Y())*0.5;
705          *
706          *                             d[0] *= height/dl;
707          *                             return mid+d[0]+0.1;
708          *                         },
709          *                         function() { return "length="+JXG.toFixed(B.Dist(A), 2); }
710          *                     ]);
711          *
712          *
713          *     board.update(); // This update is necessary to call updateDataArray the first time.
714          *
715          *     })();
716          *
717          * </script><pre>
718          *
719          *
720          */
721         updateDataArray: function () {
722             // this used to return this, but we shouldn't rely on the user to implement it.
723         },
724 
725         /**
726          * Computes the curve path
727          * @see JXG.Curve#update
728          * @returns {JXG.Curve} Reference to the curve object.
729          */
730         updateCurve: function () {
731             var i, len, mi, ma,
732                 x, y,
733                 version = this.visProp.plotversion,
734                 //t1, t2, l1,
735                 suspendUpdate = false;
736 
737             this.updateTransformMatrix();
738             this.updateDataArray();
739             mi = this.minX();
740             ma = this.maxX();
741 
742             // Discrete data points
743             // x-coordinates are in an array
744             if (Type.exists(this.dataX)) {
745                 this.numberPoints = this.dataX.length;
746                 len = this.numberPoints;
747 
748                 // It is possible, that the array length has increased.
749                 this.allocatePoints();
750 
751                 for (i = 0; i < len; i++) {
752                     x = i;
753 
754                     // y-coordinates are in an array
755                     if (Type.exists(this.dataY)) {
756                         y = i;
757                         // The last parameter prevents rounding in usr2screen().
758                         this.points[i].setCoordinates(
759                             Const.COORDS_BY_USER,
760                             [this.dataX[i], this.dataY[i]],
761                             false
762                         );
763                     } else {
764                         // discrete x data, continuous y data
765                         y = this.X(x);
766                         // The last parameter prevents rounding in usr2screen().
767                         this.points[i].setCoordinates(
768                             Const.COORDS_BY_USER,
769                             [this.dataX[i], this.Y(y, suspendUpdate)],
770                             false
771                         );
772                     }
773                     this.points[i]._t = i;
774 
775                     // this.updateTransform(this.points[i]);
776                     suspendUpdate = true;
777                 }
778                 // continuous x data
779             } else {
780                 if (this.evalVisProp('doadvancedplot')) {
781                     // console.time("plot");
782 
783                     if (version === 1 || this.evalVisProp('doadvancedplotold')) {
784                         Plot.updateParametricCurveOld(this, mi, ma);
785                     } else if (version === 2) {
786                         Plot.updateParametricCurve_v2(this, mi, ma);
787                     } else if (version === 3) {
788                         Plot.updateParametricCurve_v3(this, mi, ma);
789                     } else if (version === 4) {
790                         Plot.updateParametricCurve_v4(this, mi, ma);
791                     } else {
792                         Plot.updateParametricCurve_v2(this, mi, ma);
793                     }
794                     // console.timeEnd("plot");
795                 } else {
796                     if (this.board.updateQuality === this.board.BOARD_QUALITY_HIGH) {
797                         this.numberPoints = this.evalVisProp('numberpointshigh');
798                     } else {
799                         this.numberPoints = this.evalVisProp('numberpointslow');
800                     }
801 
802                     // It is possible, that the array length has increased.
803                     this.allocatePoints();
804                     Plot.updateParametricCurveNaive(this, mi, ma, this.numberPoints);
805                 }
806                 len = this.numberPoints;
807 
808                 if (
809                     this.evalVisProp('useqdt') &&
810                     this.board.updateQuality === this.board.BOARD_QUALITY_HIGH
811                 ) {
812                     this.qdt = new QDT(this.board.getBoundingBox());
813                     for (i = 0; i < this.points.length; i++) {
814                         this.qdt.insert(this.points[i]);
815 
816                         if (i > 0) {
817                             this.points[i].prev = this.points[i - 1];
818                         }
819 
820                         if (i < len - 1) {
821                             this.points[i].next = this.points[i + 1];
822                         }
823                     }
824                 }
825 
826                 // for (i = 0; i < len; i++) {
827                 //     this.updateTransform(this.points[i]);
828                 // }
829             }
830 
831             if (
832                 this.evalVisProp('curvetype') !== "plot" &&
833                 this.evalVisProp('rdpsmoothing')
834             ) {
835                 // console.time("rdp");
836                 this.points = Numerics.RamerDouglasPeucker(this.points, 0.2);
837                 this.numberPoints = this.points.length;
838                 // console.timeEnd("rdp");
839                 // console.log(this.numberPoints);
840             }
841 
842             len = this.numberPoints;
843             for (i = 0; i < len; i++) {
844                 this.updateTransform(this.points[i]);
845             }
846 
847             return this;
848         },
849 
850         updateTransformMatrix: function () {
851             var t,
852                 i,
853                 len = this.transformations.length;
854 
855             this.transformMat = [
856                 [1, 0, 0],
857                 [0, 1, 0],
858                 [0, 0, 1]
859             ];
860 
861             for (i = 0; i < len; i++) {
862                 t = this.transformations[i];
863                 t.update();
864                 this.transformMat = Mat.matMatMult(t.matrix, this.transformMat);
865             }
866 
867             return this;
868         },
869 
870         /**
871          * Applies the transformations of the curve to the given point <tt>p</tt>.
872          * Before using it, {@link JXG.Curve#updateTransformMatrix} has to be called.
873          * @param {JXG.Point} p
874          * @returns {JXG.Point} The given point.
875          */
876         updateTransform: function (p) {
877             var c,
878                 len = this.transformations.length;
879 
880             if (len > 0) {
881                 c = Mat.matVecMult(this.transformMat, p.usrCoords);
882                 p.setCoordinates(Const.COORDS_BY_USER, c, false, true);
883             }
884 
885             return p;
886         },
887 
888         /**
889          * Add transformations to this curve.
890          * @param {JXG.Transformation|Array} transform Either one {@link JXG.Transformation} or an array of {@link JXG.Transformation}s.
891          * @returns {JXG.Curve} Reference to the curve object.
892          */
893         addTransform: function (transform) {
894             var i,
895                 list = Type.isArray(transform) ? transform : [transform],
896                 len = list.length;
897 
898             for (i = 0; i < len; i++) {
899                 this.transformations.push(list[i]);
900             }
901 
902             return this;
903         },
904 
905         /**
906          * Generate the method curve.X() in case curve.dataX is an array
907          * and generate the method curve.Y() in case curve.dataY is an array.
908          * @private
909          * @param {String} which Either 'X' or 'Y'
910          * @returns {function}
911          **/
912         interpolationFunctionFromArray: function (which) {
913             var data = "data" + which,
914                 that = this;
915 
916             return function (t, suspendedUpdate) {
917                 var i,
918                     j,
919                     t0,
920                     t1,
921                     arr = that[data],
922                     len = arr.length,
923                     last,
924                     f = [];
925 
926                 if (isNaN(t)) {
927                     return NaN;
928                 }
929 
930                 if (t < 0) {
931                     if (Type.isFunction(arr[0])) {
932                         return arr[0]();
933                     }
934 
935                     return arr[0];
936                 }
937 
938                 if (that.bezierDegree === 3) {
939                     last = (len - 1) / 3;
940 
941                     if (t >= last) {
942                         if (Type.isFunction(arr[arr.length - 1])) {
943                             return arr[arr.length - 1]();
944                         }
945 
946                         return arr[arr.length - 1];
947                     }
948 
949                     i = Math.floor(t) * 3;
950                     t0 = t % 1;
951                     t1 = 1 - t0;
952 
953                     for (j = 0; j < 4; j++) {
954                         if (Type.isFunction(arr[i + j])) {
955                             f[j] = arr[i + j]();
956                         } else {
957                             f[j] = arr[i + j];
958                         }
959                     }
960 
961                     return (
962                         t1 * t1 * (t1 * f[0] + 3 * t0 * f[1]) +
963                         (3 * t1 * f[2] + t0 * f[3]) * t0 * t0
964                     );
965                 }
966 
967                 if (t > len - 2) {
968                     i = len - 2;
969                 } else {
970                     i = parseInt(Math.floor(t), 10);
971                 }
972 
973                 if (i === t) {
974                     if (Type.isFunction(arr[i])) {
975                         return arr[i]();
976                     }
977                     return arr[i];
978                 }
979 
980                 for (j = 0; j < 2; j++) {
981                     if (Type.isFunction(arr[i + j])) {
982                         f[j] = arr[i + j]();
983                     } else {
984                         f[j] = arr[i + j];
985                     }
986                 }
987                 return f[0] + (f[1] - f[0]) * (t - i);
988             };
989         },
990 
991         /**
992          * Converts the JavaScript/JessieCode/GEONExT syntax of the defining function term into JavaScript.
993          * New methods X() and Y() for the Curve object are generated, further
994          * new methods for minX() and maxX().
995          * If mi or ma are not supplied, default functions are set.
996          *
997          * @param {String} varname Name of the parameter in xterm and yterm, e.g. 'x' or 't'
998          * @param {String|Number|Function|Array} xterm Term for the x coordinate. Can also be an array consisting of discrete values.
999          * @param {String|Number|Function|Array} yterm Term for the y coordinate. Can also be an array consisting of discrete values.
1000          * @param {String|Number|Function} [mi] Lower bound on the parameter
1001          * @param {String|Number|Function} [ma] Upper bound on the parameter
1002          * @see JXG.GeonextParser.geonext2JS
1003          */
1004         generateTerm: function (varname, xterm, yterm, mi, ma) {
1005             var fx, fy;
1006 
1007             // Generate the methods X() and Y()
1008             if (Type.isArray(xterm)) {
1009                 // Discrete data
1010                 this.dataX = xterm;
1011 
1012                 this.numberPoints = this.dataX.length;
1013                 this.X = this.interpolationFunctionFromArray.apply(this, ["X"]);
1014                 this.visProp.curvetype = "plot";
1015                 this.isDraggable = true;
1016             } else {
1017                 // Continuous data
1018                 this.X = Type.createFunction(xterm, this.board, varname);
1019                 if (Type.isString(xterm)) {
1020                     this.visProp.curvetype = "functiongraph";
1021                 } else if (Type.isFunction(xterm) || Type.isNumber(xterm)) {
1022                     this.visProp.curvetype = "parameter";
1023                 }
1024 
1025                 this.isDraggable = true;
1026             }
1027 
1028             if (Type.isArray(yterm)) {
1029                 this.dataY = yterm;
1030                 this.Y = this.interpolationFunctionFromArray.apply(this, ["Y"]);
1031             } else {
1032                 this.Y = Type.createFunction(yterm, this.board, varname);
1033             }
1034 
1035             /**
1036              * Polar form
1037              * Input data is function xterm() and offset coordinates yterm
1038              */
1039             if (Type.isFunction(xterm) && Type.isArray(yterm)) {
1040                 // Xoffset, Yoffset
1041                 fx = Type.createFunction(yterm[0], this.board, "");
1042                 fy = Type.createFunction(yterm[1], this.board, "");
1043 
1044                 this.X = function (phi) {
1045                     return xterm(phi) * Math.cos(phi) + fx();
1046                 };
1047                 this.X.deps = fx.deps;
1048 
1049                 this.Y = function (phi) {
1050                     return xterm(phi) * Math.sin(phi) + fy();
1051                 };
1052                 this.Y.deps = fy.deps;
1053 
1054                 this.visProp.curvetype = "polar";
1055             }
1056 
1057             // Set the upper and lower bounds for the parameter of the curve.
1058             // If not defined, reset the bounds to the default values
1059             // given in Curve.prototype.minX, Curve.prototype.maxX
1060             if (Type.exists(mi)) {
1061                 this.minX = Type.createFunction(mi, this.board, "");
1062             } else {
1063                 delete this.minX;
1064             }
1065             if (Type.exists(ma)) {
1066                 this.maxX = Type.createFunction(ma, this.board, "");
1067             } else {
1068                 delete this.maxX;
1069             }
1070 
1071             this.addParentsFromJCFunctions([this.X, this.Y, this.minX, this.maxX]);
1072         },
1073 
1074         /**
1075          * Finds dependencies in a given term and notifies the parents by adding the
1076          * dependent object to the found objects child elements.
1077          * @param {String} contentStr String containing dependencies for the given object.
1078          */
1079         notifyParents: function (contentStr) {
1080             var fstr,
1081                 dep,
1082                 isJessieCode = false,
1083                 obj;
1084 
1085             // Read dependencies found by the JessieCode parser
1086             obj = { xterm: 1, yterm: 1 };
1087             for (fstr in obj) {
1088                 if (
1089                     obj.hasOwnProperty(fstr) &&
1090                     this.hasOwnProperty(fstr) &&
1091                     this[fstr].origin
1092                 ) {
1093                     isJessieCode = true;
1094                     for (dep in this[fstr].origin.deps) {
1095                         if (this[fstr].origin.deps.hasOwnProperty(dep)) {
1096                             this[fstr].origin.deps[dep].addChild(this);
1097                         }
1098                     }
1099                 }
1100             }
1101 
1102             if (!isJessieCode) {
1103                 GeonextParser.findDependencies(this, contentStr, this.board);
1104             }
1105         },
1106 
1107         // documented in geometry element
1108         getLabelAnchor: function () {
1109             var x, y, pos,
1110                 xy, lbda, e,
1111                 t, dx, dy, d,
1112                 dist = 1.5,
1113                 c,
1114                 ax = 0.05 * this.board.canvasWidth,
1115                 ay = 0.05 * this.board.canvasHeight,
1116                 bx = 0.95 * this.board.canvasWidth,
1117                 by = 0.95 * this.board.canvasHeight;
1118 
1119             if (!Type.exists(this.label)) {
1120                 return new Coords(Const.COORDS_BY_SCREEN, [NaN, NaN], this.board);
1121             }
1122             pos = this.label.evalVisProp('position');
1123             if (!Type.isString(pos)) {
1124                 return new Coords(Const.COORDS_BY_SCREEN, [NaN, NaN], this.board);
1125             }
1126 
1127             if (pos.indexOf('right') < 0 && pos.indexOf('left') < 0) {
1128                 switch (this.evalVisProp('label.position')) {
1129                     case "ulft":
1130                         x = ax;
1131                         y = ay;
1132                         break;
1133                     case "llft":
1134                         x = ax;
1135                         y = by;
1136                         break;
1137                     case "rt":
1138                         x = bx;
1139                         y = 0.5 * by;
1140                         break;
1141                     case "lrt":
1142                         x = bx;
1143                         y = by;
1144                         break;
1145                     case "urt":
1146                         x = bx;
1147                         y = ay;
1148                         break;
1149                     case "top":
1150                         x = 0.5 * bx;
1151                         y = ay;
1152                         break;
1153                     case "bot":
1154                         x = 0.5 * bx;
1155                         y = by;
1156                         break;
1157                     default:
1158                         // includes case 'lft'
1159                         x = ax;
1160                         y = 0.5 * by;
1161                 }
1162             } else {
1163                 // New positioning
1164                 xy = Type.parsePosition(pos);
1165                 lbda = Type.parseNumber(xy.pos, this.maxX() - this.minX(), 1);
1166 
1167                 if (xy.pos.indexOf('fr') < 0 &&
1168                     xy.pos.indexOf('%') < 0) {
1169                     // 'px' or numbers are not supported
1170                     lbda = 0;
1171                 }
1172 
1173                 t = this.minX() + lbda;
1174                 x = this.X(t);
1175                 y = this.Y(t);
1176                 c = (new Coords(Const.COORDS_BY_USER, [x, y], this.board)).scrCoords;
1177 
1178                 e = Mat.eps;
1179                 if (t < this.minX() + e) {
1180                     dx = (this.X(t + e) - this.X(t)) / e;
1181                     dy = (this.Y(t + e) - this.Y(t)) / e;
1182                 } else if (t > this.maxX() - e) {
1183                     dx = (this.X(t) - this.X(t - e)) / e;
1184                     dy = (this.Y(t) - this.Y(t - e)) / e;
1185                 } else {
1186                     dx = 0.5 * (this.X(t + e) - this.X(t - e)) / e;
1187                     dy = 0.5 * (this.Y(t + e) - this.Y(t - e)) / e;
1188                 }
1189                 d = Mat.hypot(dx, dy);
1190 
1191                 if (xy.side === 'left') {
1192                     dy *= -1;
1193                 } else {
1194                     dx *= -1;
1195                 }
1196 
1197                 // Position left or right
1198 
1199                 if (Type.exists(this.label)) {
1200                     dist = 0.5 * this.label.evalVisProp('distance') / d;
1201                 }
1202 
1203                 x = c[1] + dy * this.label.size[0] * dist;
1204                 y = c[2] - dx * this.label.size[1] * dist;
1205 
1206                 return new Coords(Const.COORDS_BY_SCREEN, [x, y], this.board);
1207 
1208             }
1209             c = new Coords(Const.COORDS_BY_SCREEN, [x, y], this.board, false);
1210             return Geometry.projectCoordsToCurve(
1211                 c.usrCoords[1], c.usrCoords[2], 0, this, this.board
1212             )[0];
1213         },
1214 
1215         // documented in geometry element
1216         cloneToBackground: function () {
1217             var er,
1218                 copy = Type.getCloneObject(this);
1219 
1220             copy.points = this.points.slice(0);
1221             copy.bezierDegree = this.bezierDegree;
1222             copy.numberPoints = this.numberPoints;
1223 
1224             er = this.board.renderer.enhancedRendering;
1225             this.board.renderer.enhancedRendering = true;
1226             this.board.renderer.drawCurve(copy);
1227             this.board.renderer.enhancedRendering = er;
1228             this.traces[copy.id] = copy.rendNode;
1229 
1230             return this;
1231         },
1232 
1233         // Already documented in GeometryElement
1234         bounds: function () {
1235             var minX = Infinity,
1236                 maxX = -Infinity,
1237                 minY = Infinity,
1238                 maxY = -Infinity,
1239                 l = this.points.length,
1240                 i,
1241                 bezier,
1242                 up;
1243 
1244             if (this.bezierDegree === 3) {
1245                 // Add methods X(), Y()
1246                 for (i = 0; i < l; i++) {
1247                     this.points[i].X = Type.bind(function () {
1248                         return this.usrCoords[1];
1249                     }, this.points[i]);
1250                     this.points[i].Y = Type.bind(function () {
1251                         return this.usrCoords[2];
1252                     }, this.points[i]);
1253                 }
1254                 bezier = Numerics.bezier(this.points);
1255                 up = bezier[3]();
1256                 minX = Numerics.fminbr(
1257                     function (t) {
1258                         return bezier[0](t);
1259                     },
1260                     [0, up]
1261                 );
1262                 maxX = Numerics.fminbr(
1263                     function (t) {
1264                         return -bezier[0](t);
1265                     },
1266                     [0, up]
1267                 );
1268                 minY = Numerics.fminbr(
1269                     function (t) {
1270                         return bezier[1](t);
1271                     },
1272                     [0, up]
1273                 );
1274                 maxY = Numerics.fminbr(
1275                     function (t) {
1276                         return -bezier[1](t);
1277                     },
1278                     [0, up]
1279                 );
1280 
1281                 minX = bezier[0](minX);
1282                 maxX = bezier[0](maxX);
1283                 minY = bezier[1](minY);
1284                 maxY = bezier[1](maxY);
1285                 return [minX, maxY, maxX, minY];
1286             }
1287 
1288             // Linear segments
1289             for (i = 0; i < l; i++) {
1290                 if (minX > this.points[i].usrCoords[1]) {
1291                     minX = this.points[i].usrCoords[1];
1292                 }
1293 
1294                 if (maxX < this.points[i].usrCoords[1]) {
1295                     maxX = this.points[i].usrCoords[1];
1296                 }
1297 
1298                 if (minY > this.points[i].usrCoords[2]) {
1299                     minY = this.points[i].usrCoords[2];
1300                 }
1301 
1302                 if (maxY < this.points[i].usrCoords[2]) {
1303                     maxY = this.points[i].usrCoords[2];
1304                 }
1305             }
1306 
1307             return [minX, maxY, maxX, minY];
1308         },
1309 
1310         // documented in element.js
1311         getParents: function () {
1312             var p = [this.xterm, this.yterm, this.minX(), this.maxX()];
1313 
1314             if (this.parents.length !== 0) {
1315                 p = this.parents;
1316             }
1317 
1318             return p;
1319         },
1320 
1321         /**
1322          * Shift the curve by the vector 'where'.
1323          *
1324          * @param {Array} where Array containing the x and y coordinate of the target location.
1325          * @returns {JXG.Curve} Reference to itself.
1326          */
1327         moveTo: function (where) {
1328             // TODO add animation
1329             var delta = [],
1330                 p;
1331             if (this.points.length > 0 && !this.evalVisProp('fixed')) {
1332                 p = this.points[0];
1333                 if (where.length === 3) {
1334                     delta = [
1335                         where[0] - p.usrCoords[0],
1336                         where[1] - p.usrCoords[1],
1337                         where[2] - p.usrCoords[2]
1338                     ];
1339                 } else {
1340                     delta = [where[0] - p.usrCoords[1], where[1] - p.usrCoords[2]];
1341                 }
1342                 this.setPosition(Const.COORDS_BY_USER, delta);
1343                 return this.board.update(this);
1344             }
1345             return this;
1346         },
1347 
1348         /**
1349          * If the curve is the result of a transformation applied
1350          * to a continuous curve, the glider projection has to be done
1351          * on the original curve. Otherwise there will be problems
1352          * when changing between high and low precision plotting,
1353          * since there number of points changes.
1354          *
1355          * @private
1356          * @returns {Array} [Boolean, curve]: Array contining 'true' if curve is result of a transformation,
1357          *   and the source curve of the transformation.
1358          */
1359         getTransformationSource: function () {
1360             var isTransformed, curve_org;
1361             if (Type.exists(this._transformationSource)) {
1362                 curve_org = this._transformationSource;
1363                 if (
1364                     curve_org.elementClass === Const.OBJECT_CLASS_CURVE //&&
1365                     //curve_org.evalVisProp('curvetype') !== 'plot'
1366                 ) {
1367                     isTransformed = true;
1368                 }
1369             }
1370             return [isTransformed, curve_org];
1371         }
1372 
1373         // See JXG.Math.Geometry.pnpoly
1374         // pnpoly: function (x_in, y_in, coord_type) {
1375         //     var i,
1376         //         j,
1377         //         len,
1378         //         x,
1379         //         y,
1380         //         crds,
1381         //         v = this.points,
1382         //         isIn = false;
1383 
1384         //     if (coord_type === Const.COORDS_BY_USER) {
1385         //         crds = new Coords(Const.COORDS_BY_USER, [x_in, y_in], this.board);
1386         //         x = crds.scrCoords[1];
1387         //         y = crds.scrCoords[2];
1388         //     } else {
1389         //         x = x_in;
1390         //         y = y_in;
1391         //     }
1392 
1393         //     len = this.points.length;
1394         //     for (i = 0, j = len - 2; i < len - 1; j = i++) {
1395         //         if (
1396         //             v[i].scrCoords[2] > y !== v[j].scrCoords[2] > y &&
1397         //             x <
1398         //                 ((v[j].scrCoords[1] - v[i].scrCoords[1]) * (y - v[i].scrCoords[2])) /
1399         //                     (v[j].scrCoords[2] - v[i].scrCoords[2]) +
1400         //                     v[i].scrCoords[1]
1401         //         ) {
1402         //             isIn = !isIn;
1403         //         }
1404         //     }
1405 
1406         //     return isIn;
1407         // }
1408     }
1409 );
1410 
1411 /**
1412  * @class  Curves can be defined by mappings or by discrete data sets.
1413  * In general, a curve is a mapping from R to R^2, where t maps to (x(t),y(t)). The graph is drawn for t in the interval [a,b].
1414  * <p>
1415  * The following types of curves can be plotted:
1416  * <ul>
1417  *  <li> parametric curves: t mapsto (x(t),y(t)), where x() and y() are univariate functions.
1418  *  <li> polar curves: curves commonly written with polar equations like spirals and cardioids.
1419  *  <li> data plots: plot line segments through a given list of coordinates.
1420  * </ul>
1421  * @pseudo
1422  * @name Curve
1423  * @augments JXG.Curve
1424  * @constructor
1425  * @type Object
1426  * @description JXG.Curve
1427 
1428  * @param {function,number_function,number_function,number_function,number}  x,y,a_,b_ Parent elements for Parametric Curves.
1429  *                     <p>
1430  *                     x describes the x-coordinate of the curve. It may be a function term in one variable, e.g. x(t).
1431  *                     In case of x being of type number, x(t) is set to  a constant function.
1432  *                     this function at the values of the array.
1433  *                     </p>
1434  *                     <p>
1435  *                     y describes the y-coordinate of the curve. In case of a number, y(t) is set to the constant function
1436  *                     returning this number.
1437  *                     </p>
1438  *                     <p>
1439  *                     Further parameters are an optional number or function for the left interval border a,
1440  *                     and an optional number or function for the right interval border b.
1441  *                     </p>
1442  *                     <p>
1443  *                     Default values are a=-10 and b=10.
1444  *                     </p>
1445  *
1446  * @param {array_array,function,number}
1447  *
1448  * @description x,y Parent elements for Data Plots.
1449  *                     <p>
1450  *                     x and y are arrays contining the x and y coordinates of the data points which are connected by
1451  *                     line segments. The individual entries of x and y may also be functions.
1452  *                     In case of x being an array the curve type is data plot, regardless of the second parameter and
1453  *                     if additionally the second parameter y is a function term the data plot evaluates.
1454  *                     </p>
1455  * @param {function_array,function,number_function,number_function,number}
1456  * @description r,offset_,a_,b_ Parent elements for Polar Curves.
1457  *                     <p>
1458  *                     The first parameter is a function term r(phi) describing the polar curve.
1459  *                     </p>
1460  *                     <p>
1461  *                     The second parameter is the offset of the curve. It has to be
1462  *                     an array containing numbers or functions describing the offset. Default value is the origin [0,0].
1463  *                     </p>
1464  *                     <p>
1465  *                     Further parameters are an optional number or function for the left interval border a,
1466  *                     and an optional number or function for the right interval border b.
1467  *                     </p>
1468  *                     <p>
1469  *                     Default values are a=-10 and b=10.
1470  *                     </p>
1471  * <p>
1472  * Additionally, a curve can be created by providing a curve and a transformation (or an array of transformations).
1473  * The result is a curve which is the transformation of the supplied curve.
1474  *
1475  * @see JXG.Curve
1476  * @example
1477  * // Parametric curve
1478  * // Create a curve of the form (t-sin(t), 1-cos(t), i.e.
1479  * // the cycloid curve.
1480  *   var graph = board.create('curve',
1481  *                        [function(t){ return t-Math.sin(t);},
1482  *                         function(t){ return 1-Math.cos(t);},
1483  *                         0, 2*Math.PI]
1484  *                     );
1485  * </pre><div class="jxgbox" id="JXGaf9f818b-f3b6-4c4d-8c4c-e4a4078b726d" style="width: 300px; height: 300px;"></div>
1486  * <script type="text/javascript">
1487  *   var c1_board = JXG.JSXGraph.initBoard('JXGaf9f818b-f3b6-4c4d-8c4c-e4a4078b726d', {boundingbox: [-1, 5, 7, -1], axis: true, showcopyright: false, shownavigation: false});
1488  *   var graph1 = c1_board.create('curve', [function(t){ return t-Math.sin(t);},function(t){ return 1-Math.cos(t);},0, 2*Math.PI]);
1489  * </script><pre>
1490  * @example
1491  * // Data plots
1492  * // Connect a set of points given by coordinates with dashed line segments.
1493  * // The x- and y-coordinates of the points are given in two separate
1494  * // arrays.
1495  *   var x = [0,1,2,3,4,5,6,7,8,9];
1496  *   var y = [9.2,1.3,7.2,-1.2,4.0,5.3,0.2,6.5,1.1,0.0];
1497  *   var graph = board.create('curve', [x,y], {dash:2});
1498  * </pre><div class="jxgbox" id="JXG7dcbb00e-b6ff-481d-b4a8-887f5d8c6a83" style="width: 300px; height: 300px;"></div>
1499  * <script type="text/javascript">
1500  *   var c3_board = JXG.JSXGraph.initBoard('JXG7dcbb00e-b6ff-481d-b4a8-887f5d8c6a83', {boundingbox: [-1,10,10,-1], axis: true, showcopyright: false, shownavigation: false});
1501  *   var x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1502  *   var y = [9.2, 1.3, 7.2, -1.2, 4.0, 5.3, 0.2, 6.5, 1.1, 0.0];
1503  *   var graph3 = c3_board.create('curve', [x,y], {dash:2});
1504  * </script><pre>
1505  * @example
1506  * // Polar plot
1507  * // Create a curve with the equation r(phi)= a*(1+phi), i.e.
1508  * // a cardioid.
1509  *   var a = board.create('slider',[[0,2],[2,2],[0,1,2]]);
1510  *   var graph = board.create('curve',
1511  *                        [function(phi){ return a.Value()*(1-Math.cos(phi));},
1512  *                         [1,0],
1513  *                         0, 2*Math.PI],
1514  *                         {curveType: 'polar'}
1515  *                     );
1516  * </pre><div class="jxgbox" id="JXGd0bc7a2a-8124-45ca-a6e7-142321a8f8c2" style="width: 300px; height: 300px;"></div>
1517  * <script type="text/javascript">
1518  *   var c2_board = JXG.JSXGraph.initBoard('JXGd0bc7a2a-8124-45ca-a6e7-142321a8f8c2', {boundingbox: [-3,3,3,-3], axis: true, showcopyright: false, shownavigation: false});
1519  *   var a = c2_board.create('slider',[[0,2],[2,2],[0,1,2]]);
1520  *   var graph2 = c2_board.create('curve', [function(phi){ return a.Value()*(1-Math.cos(phi));}, [1,0], 0, 2*Math.PI], {curveType: 'polar'});
1521  * </script><pre>
1522  *
1523  * @example
1524  *  // Draggable Bezier curve
1525  *  var col, p, c;
1526  *  col = 'blue';
1527  *  p = [];
1528  *  p.push(board.create('point',[-2, -1 ], {size: 5, strokeColor:col, fillColor:col}));
1529  *  p.push(board.create('point',[1, 2.5 ], {size: 5, strokeColor:col, fillColor:col}));
1530  *  p.push(board.create('point',[-1, -2.5 ], {size: 5, strokeColor:col, fillColor:col}));
1531  *  p.push(board.create('point',[2, -2], {size: 5, strokeColor:col, fillColor:col}));
1532  *
1533  *  c = board.create('curve', JXG.Math.Numerics.bezier(p),
1534  *              {strokeColor:'red', name:"curve", strokeWidth:5, fixed: false}); // Draggable curve
1535  *  c.addParents(p);
1536  * </pre><div class="jxgbox" id="JXG7bcc6280-f6eb-433e-8281-c837c3387849" style="width: 300px; height: 300px;"></div>
1537  * <script type="text/javascript">
1538  * (function(){
1539  *  var board, col, p, c;
1540  *  board = JXG.JSXGraph.initBoard('JXG7bcc6280-f6eb-433e-8281-c837c3387849', {boundingbox: [-3,3,3,-3], axis: true, showcopyright: false, shownavigation: false});
1541  *  col = 'blue';
1542  *  p = [];
1543  *  p.push(board.create('point',[-2, -1 ], {size: 5, strokeColor:col, fillColor:col}));
1544  *  p.push(board.create('point',[1, 2.5 ], {size: 5, strokeColor:col, fillColor:col}));
1545  *  p.push(board.create('point',[-1, -2.5 ], {size: 5, strokeColor:col, fillColor:col}));
1546  *  p.push(board.create('point',[2, -2], {size: 5, strokeColor:col, fillColor:col}));
1547  *
1548  *  c = board.create('curve', JXG.Math.Numerics.bezier(p),
1549  *              {strokeColor:'red', name:"curve", strokeWidth:5, fixed: false}); // Draggable curve
1550  *  c.addParents(p);
1551  * })();
1552  * </script><pre>
1553  *
1554  * @example
1555  *         // The curve cu2 is the reflection of cu1 against line li
1556  *         var li = board.create('line', [1,1,1], {strokeColor: '#aaaaaa'});
1557  *         var reflect = board.create('transform', [li], {type: 'reflect'});
1558  *         var cu1 = board.create('curve', [[-1, -1, -0.5, -1, -1, -0.5], [-3, -2, -2, -2, -2.5, -2.5]]);
1559  *         var cu2 = board.create('curve', [cu1, reflect], {strokeColor: 'red'});
1560  *
1561  * </pre><div id="JXG866dc7a2-d448-11e7-93b3-901b0e1b8723" class="jxgbox" style="width: 300px; height: 300px;"></div>
1562  * <script type="text/javascript">
1563  *     (function() {
1564  *         var board = JXG.JSXGraph.initBoard('JXG866dc7a2-d448-11e7-93b3-901b0e1b8723',
1565  *             {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false});
1566  *             var li = board.create('line', [1,1,1], {strokeColor: '#aaaaaa'});
1567  *             var reflect = board.create('transform', [li], {type: 'reflect'});
1568  *             var cu1 = board.create('curve', [[-1, -1, -0.5, -1, -1, -0.5], [-3, -2, -2, -2, -2.5, -2.5]]);
1569  *             var cu2 = board.create('curve', [cu1, reflect], {strokeColor: 'red'});
1570  *
1571  *     })();
1572  *
1573  * </script><pre>
1574  */
1575 JXG.createCurve = function (board, parents, attributes) {
1576     var obj,
1577         cu,
1578         attr = Type.copyAttributes(attributes, board.options, "curve");
1579 
1580     obj = board.select(parents[0], true);
1581     if (
1582         Type.isTransformationOrArray(parents[1]) &&
1583         Type.isObject(obj) &&
1584         (obj.type === Const.OBJECT_TYPE_CURVE ||
1585             obj.type === Const.OBJECT_TYPE_ANGLE ||
1586             obj.type === Const.OBJECT_TYPE_ARC ||
1587             obj.type === Const.OBJECT_TYPE_CONIC ||
1588             obj.type === Const.OBJECT_TYPE_SECTOR)
1589     ) {
1590         if (obj.type === Const.OBJECT_TYPE_SECTOR) {
1591             attr = Type.copyAttributes(attributes, board.options, "sector");
1592         } else if (obj.type === Const.OBJECT_TYPE_ARC) {
1593             attr = Type.copyAttributes(attributes, board.options, "arc");
1594         } else if (obj.type === Const.OBJECT_TYPE_ANGLE) {
1595             if (!Type.exists(attributes.withLabel)) {
1596                 attributes.withLabel = false;
1597             }
1598             attr = Type.copyAttributes(attributes, board.options, "angle");
1599         } else {
1600             attr = Type.copyAttributes(attributes, board.options, "curve");
1601         }
1602         attr = Type.copyAttributes(attr, board.options, "curve");
1603 
1604         cu = new JXG.Curve(board, ["x", [], []], attr);
1605         /**
1606          * @class
1607          * @ignore
1608          */
1609         cu.updateDataArray = function () {
1610             var i,
1611                 le = obj.numberPoints;
1612             this.bezierDegree = obj.bezierDegree;
1613             this.dataX = [];
1614             this.dataY = [];
1615             for (i = 0; i < le; i++) {
1616                 this.dataX.push(obj.points[i].usrCoords[1]);
1617                 this.dataY.push(obj.points[i].usrCoords[2]);
1618             }
1619             return this;
1620         };
1621         cu.addTransform(parents[1]);
1622         obj.addChild(cu);
1623         cu.setParents([obj]);
1624         cu._transformationSource = obj;
1625 
1626         return cu;
1627     }
1628     attr = Type.copyAttributes(attributes, board.options, "curve");
1629     return new JXG.Curve(board, ["x"].concat(parents), attr);
1630 };
1631 
1632 JXG.registerElement("curve", JXG.createCurve);
1633 
1634 /**
1635  * @class A functiongraph visualizes a map x → f(x).
1636  * The graph is displayed for x in the interval [a,b] and is a {@link Curve} element.
1637  * @pseudo
1638  * @name Functiongraph
1639  * @augments JXG.Curve
1640  * @constructor
1641  * @type JXG.Curve
1642  * @param {function_number,function_number,function} f,a_,b_ Parent elements are a function term f(x) describing the function graph.
1643  *         <p>
1644  *         Further, an optional number or function for the left interval border a,
1645  *         and an optional number or function for the right interval border b.
1646  *         <p>
1647  *         Default values are a=-10 and b=10.
1648  * @see JXG.Curve
1649  * @example
1650  * // Create a function graph for f(x) = 0.5*x*x-2*x
1651  *   var graph = board.create('functiongraph',
1652  *                        [function(x){ return 0.5*x*x-2*x;}, -2, 4]
1653  *                     );
1654  * </pre><div class="jxgbox" id="JXGefd432b5-23a3-4846-ac5b-b471e668b437" style="width: 300px; height: 300px;"></div>
1655  * <script type="text/javascript">
1656  *   var alex1_board = JXG.JSXGraph.initBoard('JXGefd432b5-23a3-4846-ac5b-b471e668b437', {boundingbox: [-3, 7, 5, -3], axis: true, showcopyright: false, shownavigation: false});
1657  *   var graph = alex1_board.create('functiongraph', [function(x){ return 0.5*x*x-2*x;}, -2, 4]);
1658  * </script><pre>
1659  * @example
1660  * // Create a function graph for f(x) = 0.5*x*x-2*x with variable interval
1661  *   var s = board.create('slider',[[0,4],[3,4],[-2,4,5]]);
1662  *   var graph = board.create('functiongraph',
1663  *                        [function(x){ return 0.5*x*x-2*x;},
1664  *                         -2,
1665  *                         function(){return s.Value();}]
1666  *                     );
1667  * </pre><div class="jxgbox" id="JXG4a203a84-bde5-4371-ad56-44619690bb50" style="width: 300px; height: 300px;"></div>
1668  * <script type="text/javascript">
1669  *   var alex2_board = JXG.JSXGraph.initBoard('JXG4a203a84-bde5-4371-ad56-44619690bb50', {boundingbox: [-3, 7, 5, -3], axis: true, showcopyright: false, shownavigation: false});
1670  *   var s = alex2_board.create('slider',[[0,4],[3,4],[-2,4,5]]);
1671  *   var graph = alex2_board.create('functiongraph', [function(x){ return 0.5*x*x-2*x;}, -2, function(){return s.Value();}]);
1672  * </script><pre>
1673  */
1674 JXG.createFunctiongraph = function (board, parents, attributes) {
1675     var attr,
1676         par = ["x", "x"].concat(parents); // variable name and identity function for x-coordinate
1677     // par = ["x", function(x) { return x; }].concat(parents);
1678 
1679     attr = Type.copyAttributes(attributes, board.options, "functiongraph");
1680     attr = Type.copyAttributes(attr, board.options, "curve");
1681     attr.curvetype = "functiongraph";
1682     return new JXG.Curve(board, par, attr);
1683 };
1684 
1685 JXG.registerElement("functiongraph", JXG.createFunctiongraph);
1686 JXG.registerElement("plot", JXG.createFunctiongraph);
1687 
1688 /**
1689  * @class The (natural) cubic spline curves (function graph) interpolating a set of points.
1690  * Create a dynamic spline interpolated curve given by sample points p_1 to p_n.
1691  * @pseudo
1692  * @name Spline
1693  * @augments JXG.Curve
1694  * @constructor
1695  * @type JXG.Curve
1696  * @param {JXG.Board} board Reference to the board the spline is drawn on.
1697  * @param {Array} parents Array of points the spline interpolates. This can be
1698  *   <ul>
1699  *   <li> an array of JSXGraph points</li>
1700  *   <li> an array of coordinate pairs</li>
1701  *   <li> an array of functions returning coordinate pairs</li>
1702  *   <li> an array consisting of an array with x-coordinates and an array of y-coordinates</li>
1703  *   </ul>
1704  *   All individual entries of coordinates arrays may be numbers or functions returning numbers.
1705  * @param {Object} attributes Define color, width, ... of the spline
1706  * @returns {JXG.Curve} Returns reference to an object of type JXG.Curve.
1707  * @see JXG.Curve
1708  * @example
1709  *
1710  * var p = [];
1711  * p[0] = board.create('point', [-2,2], {size: 4, face: 'o'});
1712  * p[1] = board.create('point', [0,-1], {size: 4, face: 'o'});
1713  * p[2] = board.create('point', [2,0], {size: 4, face: 'o'});
1714  * p[3] = board.create('point', [4,1], {size: 4, face: 'o'});
1715  *
1716  * var c = board.create('spline', p, {strokeWidth:3});
1717  * </pre><div id="JXG6c197afc-e482-11e5-b1bf-901b0e1b8723" style="width: 300px; height: 300px;"></div>
1718  * <script type="text/javascript">
1719  *     (function() {
1720  *         var board = JXG.JSXGraph.initBoard('JXG6c197afc-e482-11e5-b1bf-901b0e1b8723',
1721  *             {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false});
1722  *
1723  *     var p = [];
1724  *     p[0] = board.create('point', [-2,2], {size: 4, face: 'o'});
1725  *     p[1] = board.create('point', [0,-1], {size: 4, face: 'o'});
1726  *     p[2] = board.create('point', [2,0], {size: 4, face: 'o'});
1727  *     p[3] = board.create('point', [4,1], {size: 4, face: 'o'});
1728  *
1729  *     var c = board.create('spline', p, {strokeWidth:3});
1730  *     })();
1731  *
1732  * </script><pre>
1733  *
1734  */
1735 JXG.createSpline = function (board, parents, attributes) {
1736     var el, funcs, ret;
1737 
1738     funcs = function () {
1739         var D,
1740             x = [],
1741             y = [];
1742 
1743         return [
1744             function (t, suspended) {
1745                 // Function term
1746                 var i, j, c;
1747 
1748                 if (!suspended) {
1749                     x = [];
1750                     y = [];
1751 
1752                     // given as [x[], y[]]
1753                     if (
1754                         parents.length === 2 &&
1755                         Type.isArray(parents[0]) &&
1756                         Type.isArray(parents[1]) &&
1757                         parents[0].length === parents[1].length
1758                     ) {
1759                         for (i = 0; i < parents[0].length; i++) {
1760                             if (Type.isFunction(parents[0][i])) {
1761                                 x.push(parents[0][i]());
1762                             } else {
1763                                 x.push(parents[0][i]);
1764                             }
1765 
1766                             if (Type.isFunction(parents[1][i])) {
1767                                 y.push(parents[1][i]());
1768                             } else {
1769                                 y.push(parents[1][i]);
1770                             }
1771                         }
1772                     } else {
1773                         for (i = 0; i < parents.length; i++) {
1774                             if (Type.isPoint(parents[i])) {
1775                                 x.push(parents[i].X());
1776                                 y.push(parents[i].Y());
1777                                 // given as [[x1,y1], [x2, y2], ...]
1778                             } else if (Type.isArray(parents[i]) && parents[i].length === 2) {
1779                                 for (j = 0; j < parents.length; j++) {
1780                                     if (Type.isFunction(parents[j][0])) {
1781                                         x.push(parents[j][0]());
1782                                     } else {
1783                                         x.push(parents[j][0]);
1784                                     }
1785 
1786                                     if (Type.isFunction(parents[j][1])) {
1787                                         y.push(parents[j][1]());
1788                                     } else {
1789                                         y.push(parents[j][1]);
1790                                     }
1791                                 }
1792                             } else if (
1793                                 Type.isFunction(parents[i]) &&
1794                                 parents[i]().length === 2
1795                             ) {
1796                                 c = parents[i]();
1797                                 x.push(c[0]);
1798                                 y.push(c[1]);
1799                             }
1800                         }
1801                     }
1802 
1803                     // The array D has only to be calculated when the position of one or more sample points
1804                     // changes. Otherwise D is always the same for all points on the spline.
1805                     D = Numerics.splineDef(x, y);
1806                 }
1807 
1808                 return Numerics.splineEval(t, x, y, D);
1809             },
1810             // minX()
1811             function () {
1812                 return x[0];
1813             },
1814             //maxX()
1815             function () {
1816                 return x[x.length - 1];
1817             }
1818         ];
1819     };
1820 
1821     attributes = Type.copyAttributes(attributes, board.options, "curve");
1822     attributes.curvetype = "functiongraph";
1823     ret = funcs();
1824     el = new JXG.Curve(board, ["x", "x", ret[0], ret[1], ret[2]], attributes);
1825     el.setParents(parents);
1826     el.elType = "spline";
1827 
1828     return el;
1829 };
1830 
1831 /**
1832  * Register the element type spline at JSXGraph
1833  * @private
1834  */
1835 JXG.registerElement("spline", JXG.createSpline);
1836 
1837 /**
1838  * @class Cardinal spline curve through a given data set.
1839  * Create a dynamic cardinal spline interpolated curve given by sample points p_1 to p_n.
1840  * @pseudo
1841  * @name Cardinalspline
1842  * @augments JXG.Curve
1843  * @constructor
1844  * @type JXG.Curve
1845  * @param {Array} points Points array defining the cardinal spline. This can be
1846  *   <ul>
1847  *   <li> an array of JSXGraph points</li>
1848  *   <li> an array of coordinate pairs</li>
1849  *   <li> an array of functions returning coordinate pairs</li>
1850  *   <li> an array consisting of an array with x-coordinates and an array of y-coordinates</li>
1851  *   </ul>
1852  *   All individual entries of coordinates arrays may be numbers or functions returning numbers.
1853  * @param {function,Number} tau Tension parameter
1854  * @param {String} [type='uniform'] Type of the cardinal spline, may be 'uniform' (default) or 'centripetal'
1855  * @see JXG.Curve
1856  * @example
1857  * //Create a cardinal spline out of an array of JXG points with adjustable tension
1858  *
1859  * //Create array of points
1860  * var p = [];
1861  * p.push(board.create('point',[0,0]));
1862  * p.push(board.create('point',[1,4]));
1863  * p.push(board.create('point',[4,5]));
1864  * p.push(board.create('point',[2,3]));
1865  * p.push(board.create('point',[3,0]));
1866  *
1867  * // tension
1868  * var tau = board.create('slider', [[-4,-5],[2,-5],[0.001,0.5,1]], {name:'tau'});
1869  * var c = board.create('cardinalspline', [p, function(){ return tau.Value();}], {strokeWidth:3});
1870  *
1871  * </pre><div id="JXG1537cb69-4d45-43aa-8fc3-c6d4f98b4cdd" class="jxgbox" style="width: 300px; height: 300px;"></div>
1872  * <script type="text/javascript">
1873  *     (function() {
1874  *         var board = JXG.JSXGraph.initBoard('JXG1537cb69-4d45-43aa-8fc3-c6d4f98b4cdd',
1875  *             {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false});
1876  *     //Create a cardinal spline out of an array of JXG points with adjustable tension
1877  *
1878  *     //Create array of points
1879  *     var p = [];
1880  *     p.push(board.create('point',[0,0]));
1881  *     p.push(board.create('point',[1,4]));
1882  *     p.push(board.create('point',[4,5]));
1883  *     p.push(board.create('point',[2,3]));
1884  *     p.push(board.create('point',[3,0]));
1885  *
1886  *     // tension
1887  *     var tau = board.create('slider', [[-4,-5],[2,-5],[0.001,0.5,1]], {name:'tau'});
1888  *     var c = board.create('cardinalspline', [p, function(){ return tau.Value();}], {strokeWidth:3});
1889  *
1890  *     })();
1891  *
1892  * </script><pre>
1893  *
1894  */
1895 JXG.createCardinalSpline = function (board, parents, attributes) {
1896     var el,
1897         getPointLike,
1898         points,
1899         tau,
1900         type,
1901         p,
1902         q,
1903         i,
1904         le,
1905         splineArr,
1906         errStr = "\nPossible parent types: [points:array, tau:number|function, type:string]";
1907 
1908     if (!Type.exists(parents[0]) || !Type.isArray(parents[0])) {
1909         throw new Error(
1910             "JSXGraph: JXG.createCardinalSpline: argument 1 'points' has to be array of points or coordinate pairs" +
1911             errStr
1912         );
1913     }
1914     if (
1915         !Type.exists(parents[1]) ||
1916         (!Type.isNumber(parents[1]) && !Type.isFunction(parents[1]))
1917     ) {
1918         throw new Error(
1919             "JSXGraph: JXG.createCardinalSpline: argument 2 'tau' has to be number between [0,1] or function'" +
1920             errStr
1921         );
1922     }
1923     if (!Type.exists(parents[2]) || !Type.isString(parents[2])) {
1924         type = 'uniform';
1925         // throw new Error(
1926         //     "JSXGraph: JXG.createCardinalSpline: argument 3 'type' has to be string 'uniform' or 'centripetal'" +
1927         //     errStr
1928         // );
1929     } else {
1930         type = parents[2];
1931     }
1932 
1933     attributes = Type.copyAttributes(attributes, board.options, "curve");
1934     attributes = Type.copyAttributes(attributes, board.options, "cardinalspline");
1935     attributes.curvetype = "parameter";
1936 
1937     p = parents[0];
1938     q = [];
1939 
1940     // Given as [x[], y[]]
1941     if (
1942         !attributes.isarrayofcoordinates &&
1943         p.length === 2 &&
1944         Type.isArray(p[0]) &&
1945         Type.isArray(p[1]) &&
1946         p[0].length === p[1].length
1947     ) {
1948         for (i = 0; i < p[0].length; i++) {
1949             q[i] = [];
1950             if (Type.isFunction(p[0][i])) {
1951                 q[i].push(p[0][i]());
1952             } else {
1953                 q[i].push(p[0][i]);
1954             }
1955 
1956             if (Type.isFunction(p[1][i])) {
1957                 q[i].push(p[1][i]());
1958             } else {
1959                 q[i].push(p[1][i]);
1960             }
1961         }
1962     } else {
1963         // given as [[x0, y0], [x1, y1], point, ...]
1964         for (i = 0; i < p.length; i++) {
1965             if (Type.isString(p[i])) {
1966                 q.push(board.select(p[i]));
1967             } else if (Type.isPoint(p[i])) {
1968                 q.push(p[i]);
1969                 // given as [[x0,y0], [x1, y2], ...]
1970             } else if (Type.isArray(p[i]) && p[i].length === 2) {
1971                 q[i] = [];
1972                 if (Type.isFunction(p[i][0])) {
1973                     q[i].push(p[i][0]());
1974                 } else {
1975                     q[i].push(p[i][0]);
1976                 }
1977 
1978                 if (Type.isFunction(p[i][1])) {
1979                     q[i].push(p[i][1]());
1980                 } else {
1981                     q[i].push(p[i][1]);
1982                 }
1983             } else if (Type.isFunction(p[i]) && p[i]().length === 2) {
1984                 q.push(parents[i]());
1985             }
1986         }
1987     }
1988 
1989     if (attributes.createpoints === true) {
1990         points = Type.providePoints(board, q, attributes, "cardinalspline", ["points"]);
1991     } else {
1992         points = [];
1993 
1994         /**
1995          * @ignore
1996          */
1997         getPointLike = function (ii) {
1998             return {
1999                 X: function () {
2000                     return q[ii][0];
2001                 },
2002                 Y: function () {
2003                     return q[ii][1];
2004                 },
2005                 Dist: function (p) {
2006                     var dx = this.X() - p.X(),
2007                         dy = this.Y() - p.Y();
2008 
2009                     return Mat.hypot(dx, dy);
2010                 }
2011             };
2012         };
2013 
2014         for (i = 0; i < q.length; i++) {
2015             if (Type.isPoint(q[i])) {
2016                 points.push(q[i]);
2017             } else {
2018                 points.push(getPointLike(i));
2019             }
2020         }
2021     }
2022 
2023     tau = parents[1];
2024     // type = parents[2];
2025 
2026     splineArr = ["x"].concat(Numerics.CardinalSpline(points, tau, type));
2027 
2028     el = new JXG.Curve(board, splineArr, attributes);
2029     le = points.length;
2030     el.setParents(points);
2031     for (i = 0; i < le; i++) {
2032         p = points[i];
2033         if (Type.isPoint(p)) {
2034             if (Type.exists(p._is_new)) {
2035                 el.addChild(p);
2036                 delete p._is_new;
2037             } else {
2038                 p.addChild(el);
2039             }
2040         }
2041     }
2042     el.elType = "cardinalspline";
2043 
2044     return el;
2045 };
2046 
2047 /**
2048  * Register the element type cardinalspline at JSXGraph
2049  * @private
2050  */
2051 JXG.registerElement("cardinalspline", JXG.createCardinalSpline);
2052 
2053 /**
2054  * @class Interpolate data points by the spline curve from Metapost (by Donald Knuth and John Hobby).
2055  * Create a dynamic metapost spline interpolated curve given by sample points p_1 to p_n.
2056  * @pseudo
2057  * @name Metapostspline
2058  * @augments JXG.Curve
2059  * @constructor
2060  * @type JXG.Curve
2061  * @param {JXG.Board} board Reference to the board the metapost spline is drawn on.
2062  * @param {Array} parents Array with two entries.
2063  * <p>
2064  *   First entry: Array of points the spline interpolates. This can be
2065  *   <ul>
2066  *   <li> an array of JSXGraph points</li>
2067  *   <li> an object of coordinate pairs</li>
2068  *   <li> an array of functions returning coordinate pairs</li>
2069  *   <li> an array consisting of an array with x-coordinates and an array of y-coordinates</li>
2070  *   </ul>
2071  *   All individual entries of coordinates arrays may be numbers or functions returning numbers.
2072  *   <p>
2073  *   Second entry: JavaScript object containing the control values like tension, direction, curl.
2074  * @param {Object} attributes Define color, width, ... of the metapost spline
2075  * @returns {JXG.Curve} Returns reference to an object of type JXG.Curve.
2076  * @see JXG.Curve
2077  * @example
2078  *     var po = [],
2079  *         attr = {
2080  *             size: 5,
2081  *             color: 'red'
2082  *         },
2083  *         controls;
2084  *
2085  *     var tension = board.create('slider', [[-3, 6], [3, 6], [0, 1, 20]], {name: 'tension'});
2086  *     var curl = board.create('slider', [[-3, 5], [3, 5], [0, 1, 30]], {name: 'curl A, D'});
2087  *     var dir = board.create('slider', [[-3, 4], [3, 4], [-180, 0, 180]], {name: 'direction B'});
2088  *
2089  *     po.push(board.create('point', [-3, -3]));
2090  *     po.push(board.create('point', [0, -3]));
2091  *     po.push(board.create('point', [4, -5]));
2092  *     po.push(board.create('point', [6, -2]));
2093  *
2094  *     var controls = {
2095  *         tension: function() {return tension.Value(); },
2096  *         direction: { 1: function() {return dir.Value(); } },
2097  *         curl: { 0: function() {return curl.Value(); },
2098  *                 3: function() {return curl.Value(); }
2099  *             },
2100  *         isClosed: false
2101  *     };
2102  *
2103  *     // Plot a metapost curve
2104  *     var cu = board.create('metapostspline', [po, controls], {strokeColor: 'blue', strokeWidth: 2});
2105  *
2106  *
2107  * </pre><div id="JXGb8c6ffed-7419-41a3-9e55-3754b2327ae9" class="jxgbox" style="width: 300px; height: 300px;"></div>
2108  * <script type="text/javascript">
2109  *     (function() {
2110  *         var board = JXG.JSXGraph.initBoard('JXGb8c6ffed-7419-41a3-9e55-3754b2327ae9',
2111  *             {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false});
2112  *         var po = [],
2113  *             attr = {
2114  *                 size: 5,
2115  *                 color: 'red'
2116  *             },
2117  *             controls;
2118  *
2119  *         var tension = board.create('slider', [[-3, 6], [3, 6], [0, 1, 20]], {name: 'tension'});
2120  *         var curl = board.create('slider', [[-3, 5], [3, 5], [0, 1, 30]], {name: 'curl A, D'});
2121  *         var dir = board.create('slider', [[-3, 4], [3, 4], [-180, 0, 180]], {name: 'direction B'});
2122  *
2123  *         po.push(board.create('point', [-3, -3]));
2124  *         po.push(board.create('point', [0, -3]));
2125  *         po.push(board.create('point', [4, -5]));
2126  *         po.push(board.create('point', [6, -2]));
2127  *
2128  *         var controls = {
2129  *             tension: function() {return tension.Value(); },
2130  *             direction: { 1: function() {return dir.Value(); } },
2131  *             curl: { 0: function() {return curl.Value(); },
2132  *                     3: function() {return curl.Value(); }
2133  *                 },
2134  *             isClosed: false
2135  *         };
2136  *
2137  *         // Plot a metapost curve
2138  *         var cu = board.create('metapostspline', [po, controls], {strokeColor: 'blue', strokeWidth: 2});
2139  *
2140  *
2141  *     })();
2142  *
2143  * </script><pre>
2144  *
2145  */
2146 JXG.createMetapostSpline = function (board, parents, attributes) {
2147     var el,
2148         getPointLike,
2149         points,
2150         controls,
2151         p,
2152         q,
2153         i,
2154         le,
2155         errStr = "\nPossible parent types: [points:array, controls:object";
2156 
2157     if (!Type.exists(parents[0]) || !Type.isArray(parents[0])) {
2158         throw new Error(
2159             "JSXGraph: JXG.createMetapostSpline: argument 1 'points' has to be array of points or coordinate pairs" +
2160             errStr
2161         );
2162     }
2163     if (!Type.exists(parents[1]) || !Type.isObject(parents[1])) {
2164         throw new Error(
2165             "JSXGraph: JXG.createMetapostSpline: argument 2 'controls' has to be a JavaScript object'" +
2166             errStr
2167         );
2168     }
2169 
2170     attributes = Type.copyAttributes(attributes, board.options, "curve");
2171     attributes = Type.copyAttributes(attributes, board.options, "metapostspline");
2172     attributes.curvetype = "parameter";
2173 
2174     p = parents[0];
2175     q = [];
2176 
2177     // given as [x[], y[]]
2178     if (
2179         !attributes.isarrayofcoordinates &&
2180         p.length === 2 &&
2181         Type.isArray(p[0]) &&
2182         Type.isArray(p[1]) &&
2183         p[0].length === p[1].length
2184     ) {
2185         for (i = 0; i < p[0].length; i++) {
2186             q[i] = [];
2187             if (Type.isFunction(p[0][i])) {
2188                 q[i].push(p[0][i]());
2189             } else {
2190                 q[i].push(p[0][i]);
2191             }
2192 
2193             if (Type.isFunction(p[1][i])) {
2194                 q[i].push(p[1][i]());
2195             } else {
2196                 q[i].push(p[1][i]);
2197             }
2198         }
2199     } else {
2200         // given as [[x0, y0], [x1, y1], point, ...]
2201         for (i = 0; i < p.length; i++) {
2202             if (Type.isString(p[i])) {
2203                 q.push(board.select(p[i]));
2204             } else if (Type.isPoint(p[i])) {
2205                 q.push(p[i]);
2206                 // given as [[x0,y0], [x1, y2], ...]
2207             } else if (Type.isArray(p[i]) && p[i].length === 2) {
2208                 q[i] = [];
2209                 if (Type.isFunction(p[i][0])) {
2210                     q[i].push(p[i][0]());
2211                 } else {
2212                     q[i].push(p[i][0]);
2213                 }
2214 
2215                 if (Type.isFunction(p[i][1])) {
2216                     q[i].push(p[i][1]());
2217                 } else {
2218                     q[i].push(p[i][1]);
2219                 }
2220             } else if (Type.isFunction(p[i]) && p[i]().length === 2) {
2221                 q.push(parents[i]());
2222             }
2223         }
2224     }
2225 
2226     if (attributes.createpoints === true) {
2227         points = Type.providePoints(board, q, attributes, 'metapostspline', ['points']);
2228     } else {
2229         points = [];
2230 
2231         /**
2232          * @ignore
2233          */
2234         getPointLike = function (ii) {
2235             return {
2236                 X: function () {
2237                     return q[ii][0];
2238                 },
2239                 Y: function () {
2240                     return q[ii][1];
2241                 }
2242             };
2243         };
2244 
2245         for (i = 0; i < q.length; i++) {
2246             if (Type.isPoint(q[i])) {
2247                 points.push(q[i]);
2248             } else {
2249                 points.push(getPointLike);
2250             }
2251         }
2252     }
2253 
2254     controls = parents[1];
2255 
2256     el = new JXG.Curve(board, ["t", [], [], 0, p.length - 1], attributes);
2257     /**
2258      * @class
2259      * @ignore
2260      */
2261     el.updateDataArray = function () {
2262         var res,
2263             i,
2264             len = points.length,
2265             p = [];
2266 
2267         for (i = 0; i < len; i++) {
2268             p.push([points[i].X(), points[i].Y()]);
2269         }
2270 
2271         res = Metapost.curve(p, controls);
2272         this.dataX = res[0];
2273         this.dataY = res[1];
2274     };
2275     el.bezierDegree = 3;
2276 
2277     le = points.length;
2278     el.setParents(points);
2279     for (i = 0; i < le; i++) {
2280         if (Type.isPoint(points[i])) {
2281             points[i].addChild(el);
2282         }
2283     }
2284     el.elType = "metapostspline";
2285 
2286     return el;
2287 };
2288 
2289 JXG.registerElement("metapostspline", JXG.createMetapostSpline);
2290 
2291 /**
2292  * @class Visualize the Riemann sum which is an approximation of an integral by a finite sum.
2293  * It is realized as a special curve.
2294  * The returned element has the method Value() which returns the sum of the areas of the bars.
2295  * <p>
2296  * In case of type "simpson" and "trapezoidal", the horizontal line approximating the function value
2297  * is replaced by a parabola or a secant. IN case of "simpson",
2298  * the parabola is approximated visually by a polygonal chain of fixed step width.
2299  *
2300  * @pseudo
2301  * @name Riemannsum
2302  * @augments JXG.Curve
2303  * @constructor
2304  * @type Curve
2305  * @param {function,array_number,function_string,function_function,number_function,number} f,n,type_,a_,b_ Parent elements of Riemannsum are a
2306  *         Either a function term f(x) describing the function graph which is filled by the Riemann bars, or
2307  *         an array consisting of two functions and the area between is filled by the Riemann bars.
2308  *         <p>
2309  *         n determines the number of bars, it is either a fixed number or a function.
2310  *         <p>
2311  *         type is a string or function returning one of the values:  'left', 'right', 'middle', 'lower', 'upper', 'random', 'simpson', or 'trapezoidal'.
2312  *         Default value is 'left'. "simpson" is Simpson's 1/3 rule.
2313  *         <p>
2314  *         Further parameters are an optional number or function for the left interval border a,
2315  *         and an optional number or function for the right interval border b.
2316  *         <p>
2317  *         Default values are a=-10 and b=10.
2318  * @see JXG.Curve
2319  * @example
2320  * // Create Riemann sums for f(x) = 0.5*x*x-2*x.
2321  *   var s = board.create('slider',[[0,4],[3,4],[0,4,10]],{snapWidth:1});
2322  *   var f = function(x) { return 0.5*x*x-2*x; };
2323  *   var r = board.create('riemannsum',
2324  *               [f, function(){return s.Value();}, 'upper', -2, 5],
2325  *               {fillOpacity:0.4}
2326  *               );
2327  *   var g = board.create('functiongraph',[f, -2, 5]);
2328  *   var t = board.create('text',[-2,-2, function(){ return 'Sum=' + JXG.toFixed(r.Value(), 4); }]);
2329  * </pre><div class="jxgbox" id="JXG940f40cc-2015-420d-9191-c5d83de988cf" style="width: 300px; height: 300px;"></div>
2330  * <script type="text/javascript">
2331  * (function(){
2332  *   var board = JXG.JSXGraph.initBoard('JXG940f40cc-2015-420d-9191-c5d83de988cf', {boundingbox: [-3, 7, 5, -3], axis: true, showcopyright: false, shownavigation: false});
2333  *   var f = function(x) { return 0.5*x*x-2*x; };
2334  *   var s = board.create('slider',[[0,4],[3,4],[0,4,10]],{snapWidth:1});
2335  *   var r = board.create('riemannsum', [f, function(){return s.Value();}, 'upper', -2, 5], {fillOpacity:0.4});
2336  *   var g = board.create('functiongraph', [f, -2, 5]);
2337  *   var t = board.create('text',[-2,-2, function(){ return 'Sum=' + JXG.toFixed(r.Value(), 4); }]);
2338  * })();
2339  * </script><pre>
2340  *
2341  * @example
2342  *   // Riemann sum between two functions
2343  *   var s = board.create('slider',[[0,4],[3,4],[0,4,10]],{snapWidth:1});
2344  *   var g = function(x) { return 0.5*x*x-2*x; };
2345  *   var f = function(x) { return -x*(x-4); };
2346  *   var r = board.create('riemannsum',
2347  *               [[g,f], function(){return s.Value();}, 'lower', 0, 4],
2348  *               {fillOpacity:0.4}
2349  *               );
2350  *   var f = board.create('functiongraph',[f, -2, 5]);
2351  *   var g = board.create('functiongraph',[g, -2, 5]);
2352  *   var t = board.create('text',[-2,-2, function(){ return 'Sum=' + JXG.toFixed(r.Value(), 4); }]);
2353  * </pre><div class="jxgbox" id="JXGf9a7ba38-b50f-4a32-a873-2f3bf9caee79" style="width: 300px; height: 300px;"></div>
2354  * <script type="text/javascript">
2355  * (function(){
2356  *   var board = JXG.JSXGraph.initBoard('JXGf9a7ba38-b50f-4a32-a873-2f3bf9caee79', {boundingbox: [-3, 7, 5, -3], axis: true, showcopyright: false, shownavigation: false});
2357  *   var s = board.create('slider',[[0,4],[3,4],[0,4,10]],{snapWidth:1});
2358  *   var g = function(x) { return 0.5*x*x-2*x; };
2359  *   var f = function(x) { return -x*(x-4); };
2360  *   var r = board.create('riemannsum',
2361  *               [[g,f], function(){return s.Value();}, 'lower', 0, 4],
2362  *               {fillOpacity:0.4}
2363  *               );
2364  *   var f = board.create('functiongraph',[f, -2, 5]);
2365  *   var g = board.create('functiongraph',[g, -2, 5]);
2366  *   var t = board.create('text',[-2,-2, function(){ return 'Sum=' + JXG.toFixed(r.Value(), 4); }]);
2367  * })();
2368  * </script><pre>
2369  */
2370 JXG.createRiemannsum = function (board, parents, attributes) {
2371     var n, type, f, par, c, attr;
2372 
2373     attr = Type.copyAttributes(attributes, board.options, "riemannsum");
2374     attr.curvetype = "plot";
2375 
2376     f = parents[0];
2377     n = Type.createFunction(parents[1], board, "");
2378 
2379     if (!Type.exists(n)) {
2380         throw new Error(
2381             "JSXGraph: JXG.createRiemannsum: argument '2' n has to be number or function." +
2382             "\nPossible parent types: [function,n:number|function,type,start:number|function,end:number|function]"
2383         );
2384     }
2385 
2386     if (typeof parents[2] === 'string') {
2387         parents[2] = '\'' + parents[2] + '\'';
2388     }
2389 
2390     type = Type.createFunction(parents[2], board, "");
2391     if (!Type.exists(type)) {
2392         throw new Error(
2393             "JSXGraph: JXG.createRiemannsum: argument 3 'type' has to be string or function." +
2394             "\nPossible parent types: [function,n:number|function,type,start:number|function,end:number|function]"
2395         );
2396     }
2397 
2398     par = [[0], [0]].concat(parents.slice(3));
2399 
2400     c = board.create("curve", par, attr);
2401 
2402     c.sum = 0.0;
2403     /**
2404      * Returns the value of the Riemann sum, i.e. the sum of the (signed) areas of the rectangles.
2405      * @name Value
2406      * @memberOf Riemannsum.prototype
2407      * @function
2408      * @returns {Number} value of Riemann sum.
2409      */
2410     c.Value = function () {
2411         return this.sum;
2412     };
2413 
2414     /**
2415      * @class
2416      * @ignore
2417      */
2418     c.updateDataArray = function () {
2419         var u = Numerics.riemann(f, n(), type(), this.minX(), this.maxX());
2420         this.dataX = u[0];
2421         this.dataY = u[1];
2422 
2423         // Update "Riemann sum"
2424         this.sum = u[2];
2425     };
2426 
2427     c.addParentsFromJCFunctions([n, type]);
2428 
2429     return c;
2430 };
2431 
2432 JXG.registerElement("riemannsum", JXG.createRiemannsum);
2433 
2434 /**
2435  * @class A trace curve is simple locus curve showing the orbit of a point that depends on a glider point.
2436  * @pseudo
2437  * @name Tracecurve
2438  * @augments JXG.Curve
2439  * @constructor
2440  * @type Object
2441  * @descript JXG.Curve
2442  * @param {Point} Parent elements of Tracecurve are a
2443  *         glider point and a point whose locus is traced.
2444  * @param {point}
2445  * @see JXG.Curve
2446  * @example
2447  * // Create trace curve.
2448  * var c1 = board.create('circle',[[0, 0], [2, 0]]),
2449  * p1 = board.create('point',[-3, 1]),
2450  * g1 = board.create('glider',[2, 1, c1]),
2451  * s1 = board.create('segment',[g1, p1]),
2452  * p2 = board.create('midpoint',[s1]),
2453  * curve = board.create('tracecurve', [g1, p2]);
2454  *
2455  * </pre><div class="jxgbox" id="JXG5749fb7d-04fc-44d2-973e-45c1951e29ad" style="width: 300px; height: 300px;"></div>
2456  * <script type="text/javascript">
2457  *   var tc1_board = JXG.JSXGraph.initBoard('JXG5749fb7d-04fc-44d2-973e-45c1951e29ad', {boundingbox: [-4, 4, 4, -4], axis: false, showcopyright: false, shownavigation: false});
2458  *   var c1 = tc1_board.create('circle',[[0, 0], [2, 0]]),
2459  *       p1 = tc1_board.create('point',[-3, 1]),
2460  *       g1 = tc1_board.create('glider',[2, 1, c1]),
2461  *       s1 = tc1_board.create('segment',[g1, p1]),
2462  *       p2 = tc1_board.create('midpoint',[s1]),
2463  *       curve = tc1_board.create('tracecurve', [g1, p2]);
2464  * </script><pre>
2465  */
2466 JXG.createTracecurve = function (board, parents, attributes) {
2467     var c, glider, tracepoint, attr;
2468 
2469     if (parents.length !== 2) {
2470         throw new Error(
2471             "JSXGraph: Can't create trace curve with given parent'" +
2472             "\nPossible parent types: [glider, point]"
2473         );
2474     }
2475 
2476     glider = board.select(parents[0]);
2477     tracepoint = board.select(parents[1]);
2478 
2479     if (glider.type !== Const.OBJECT_TYPE_GLIDER || !Type.isPoint(tracepoint)) {
2480         throw new Error(
2481             "JSXGraph: Can't create trace curve with parent types '" +
2482             typeof parents[0] +
2483             "' and '" +
2484             typeof parents[1] +
2485             "'." +
2486             "\nPossible parent types: [glider, point]"
2487         );
2488     }
2489 
2490     attr = Type.copyAttributes(attributes, board.options, "tracecurve");
2491     attr.curvetype = "plot";
2492     c = board.create("curve", [[0], [0]], attr);
2493 
2494     /**
2495      * @class
2496      * @ignore
2497      */
2498     c.updateDataArray = function () {
2499         var i, step, t, el, pEl, x, y, from,
2500             savetrace,
2501             le = this.visProp.numberpoints,
2502             savePos = glider.position,
2503             slideObj = glider.slideObject,
2504             mi = slideObj.minX(),
2505             ma = slideObj.maxX();
2506 
2507         // set step width
2508         step = (ma - mi) / le;
2509         this.dataX = [];
2510         this.dataY = [];
2511 
2512         /*
2513          * For gliders on circles and lines a closed curve is computed.
2514          * For gliders on curves the curve is not closed.
2515          */
2516         if (slideObj.elementClass !== Const.OBJECT_CLASS_CURVE) {
2517             le++;
2518         }
2519 
2520         // Loop over all steps
2521         for (i = 0; i < le; i++) {
2522             t = mi + i * step;
2523             x = slideObj.X(t) / slideObj.Z(t);
2524             y = slideObj.Y(t) / slideObj.Z(t);
2525 
2526             // Position the glider
2527             glider.setPositionDirectly(Const.COORDS_BY_USER, [x, y]);
2528             from = false;
2529 
2530             // Update all elements from the glider up to the trace element
2531             for (el in this.board.objects) {
2532                 if (this.board.objects.hasOwnProperty(el)) {
2533                     pEl = this.board.objects[el];
2534 
2535                     if (pEl === glider) {
2536                         from = true;
2537                     }
2538 
2539                     if (from && pEl.needsRegularUpdate) {
2540                         // Save the trace mode of the element
2541                         savetrace = pEl.visProp.trace;
2542                         pEl.visProp.trace = false;
2543                         pEl.needsUpdate = true;
2544                         pEl.update(true);
2545 
2546                         // Restore the trace mode
2547                         pEl.visProp.trace = savetrace;
2548                         if (pEl === tracepoint) {
2549                             break;
2550                         }
2551                     }
2552                 }
2553             }
2554 
2555             // Store the position of the trace point
2556             this.dataX[i] = tracepoint.X();
2557             this.dataY[i] = tracepoint.Y();
2558         }
2559 
2560         // Restore the original position of the glider
2561         glider.position = savePos;
2562         from = false;
2563 
2564         // Update all elements from the glider to the trace point
2565         for (el in this.board.objects) {
2566             if (this.board.objects.hasOwnProperty(el)) {
2567                 pEl = this.board.objects[el];
2568                 if (pEl === glider) {
2569                     from = true;
2570                 }
2571 
2572                 if (from && pEl.needsRegularUpdate) {
2573                     savetrace = pEl.visProp.trace;
2574                     pEl.visProp.trace = false;
2575                     pEl.needsUpdate = true;
2576                     pEl.update(true);
2577                     pEl.visProp.trace = savetrace;
2578 
2579                     if (pEl === tracepoint) {
2580                         break;
2581                     }
2582                 }
2583             }
2584         }
2585     };
2586 
2587     return c;
2588 };
2589 
2590 JXG.registerElement("tracecurve", JXG.createTracecurve);
2591 
2592 /**
2593      * @class A step function is a function graph that is piecewise constant.
2594      *
2595      * In case the data points should be updated after creation time,
2596      * they can be accessed by curve.xterm and curve.yterm.
2597      * @pseudo
2598      * @name Stepfunction
2599      * @augments JXG.Curve
2600      * @constructor
2601      * @type Curve
2602      * @description JXG.Curve
2603      * @param {Array|Function} Parent1 elements of Stepfunction are two arrays containing the coordinates.
2604      * @param {Array|Function} Parent2
2605      * @see JXG.Curve
2606      * @example
2607      * // Create step function.
2608      var curve = board.create('stepfunction', [[0,1,2,3,4,5], [1,3,0,2,2,1]]);
2609 
2610      * </pre><div class="jxgbox" id="JXG32342ec9-ad17-4339-8a97-ff23dc34f51a" style="width: 300px; height: 300px;"></div>
2611      * <script type="text/javascript">
2612      *   var sf1_board = JXG.JSXGraph.initBoard('JXG32342ec9-ad17-4339-8a97-ff23dc34f51a', {boundingbox: [-1, 5, 6, -2], axis: true, showcopyright: false, shownavigation: false});
2613      *   var curve = sf1_board.create('stepfunction', [[0,1,2,3,4,5], [1,3,0,2,2,1]]);
2614      * </script><pre>
2615      */
2616 JXG.createStepfunction = function (board, parents, attributes) {
2617     var c, attr;
2618     if (parents.length !== 2) {
2619         throw new Error(
2620             "JSXGraph: Can't create step function with given parent'" +
2621             "\nPossible parent types: [array, array|function]"
2622         );
2623     }
2624 
2625     attr = Type.copyAttributes(attributes, board.options, "stepfunction");
2626     c = board.create("curve", parents, attr);
2627     /**
2628      * @class
2629      * @ignore
2630      */
2631     c.updateDataArray = function () {
2632         var i,
2633             j = 0,
2634             len = this.xterm.length;
2635 
2636         this.dataX = [];
2637         this.dataY = [];
2638 
2639         if (len === 0) {
2640             return;
2641         }
2642 
2643         this.dataX[j] = this.xterm[0];
2644         this.dataY[j] = this.yterm[0];
2645         ++j;
2646 
2647         for (i = 1; i < len; ++i) {
2648             this.dataX[j] = this.xterm[i];
2649             this.dataY[j] = this.dataY[j - 1];
2650             ++j;
2651             this.dataX[j] = this.xterm[i];
2652             this.dataY[j] = this.yterm[i];
2653             ++j;
2654         }
2655     };
2656 
2657     return c;
2658 };
2659 
2660 JXG.registerElement("stepfunction", JXG.createStepfunction);
2661 
2662 /**
2663  * @class A curve visualizing the function graph of the (numerical) derivative of a given curve.
2664  *
2665  * @pseudo
2666  * @name Derivative
2667  * @augments JXG.Curve
2668  * @constructor
2669  * @type JXG.Curve
2670  * @param {JXG.Curve} Parent Curve for which the derivative is generated.
2671  * @see JXG.Curve
2672  * @example
2673  * var cu = board.create('cardinalspline', [[[-3,0], [-1,2], [0,1], [2,0], [3,1]], 0.5, 'centripetal'], {createPoints: false});
2674  * var d = board.create('derivative', [cu], {dash: 2});
2675  *
2676  * </pre><div id="JXGb9600738-1656-11e8-8184-901b0e1b8723" class="jxgbox" style="width: 300px; height: 300px;"></div>
2677  * <script type="text/javascript">
2678  *     (function() {
2679  *         var board = JXG.JSXGraph.initBoard('JXGb9600738-1656-11e8-8184-901b0e1b8723',
2680  *             {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false});
2681  *     var cu = board.create('cardinalspline', [[[-3,0], [-1,2], [0,1], [2,0], [3,1]], 0.5, 'centripetal'], {createPoints: false});
2682  *     var d = board.create('derivative', [cu], {dash: 2});
2683  *
2684  *     })();
2685  *
2686  * </script><pre>
2687  *
2688  */
2689 JXG.createDerivative = function (board, parents, attributes) {
2690     var c, curve, dx, dy, attr;
2691 
2692     if (parents.length !== 1 && parents[0].class !== Const.OBJECT_CLASS_CURVE) {
2693         throw new Error(
2694             "JSXGraph: Can't create derivative curve with given parent'" +
2695             "\nPossible parent types: [curve]"
2696         );
2697     }
2698 
2699     attr = Type.copyAttributes(attributes, board.options, "curve");
2700 
2701     curve = parents[0];
2702     dx = Numerics.D(curve.X);
2703     dy = Numerics.D(curve.Y);
2704 
2705     c = board.create(
2706         "curve",
2707         [
2708             function (t) {
2709                 return curve.X(t);
2710             },
2711             function (t) {
2712                 return dy(t) / dx(t);
2713             },
2714             curve.minX(),
2715             curve.maxX()
2716         ],
2717         attr
2718     );
2719 
2720     c.setParents(curve);
2721 
2722     return c;
2723 };
2724 
2725 JXG.registerElement("derivative", JXG.createDerivative);
2726 
2727 /**
2728  * @class The path forming the intersection of two closed path elements.
2729  * The elements may be of type curve, circle, polygon, inequality.
2730  * If one element is a curve, it has to be closed.
2731  * The resulting element is of type curve.
2732  * @pseudo
2733  * @name CurveIntersection
2734  * @param {JXG.Curve|JXG.Polygon|JXG.Circle} curve1 First element which is intersected
2735  * @param {JXG.Curve|JXG.Polygon|JXG.Circle} curve2 Second element which is intersected
2736  * @augments JXG.Curve
2737  * @constructor
2738  * @type JXG.Curve
2739  *
2740  * @example
2741  * var f = board.create('functiongraph', ['cos(x)']);
2742  * var ineq = board.create('inequality', [f], {inverse: true, fillOpacity: 0.1});
2743  * var circ = board.create('circle', [[0,0], 4]);
2744  * var clip = board.create('curveintersection', [ineq, circ], {fillColor: 'yellow', fillOpacity: 0.6});
2745  *
2746  * </pre><div id="JXGe2948257-8835-4276-9164-8acccb48e8d4" class="jxgbox" style="width: 300px; height: 300px;"></div>
2747  * <script type="text/javascript">
2748  *     (function() {
2749  *         var board = JXG.JSXGraph.initBoard('JXGe2948257-8835-4276-9164-8acccb48e8d4',
2750  *             {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false});
2751  *     var f = board.create('functiongraph', ['cos(x)']);
2752  *     var ineq = board.create('inequality', [f], {inverse: true, fillOpacity: 0.1});
2753  *     var circ = board.create('circle', [[0,0], 4]);
2754  *     var clip = board.create('curveintersection', [ineq, circ], {fillColor: 'yellow', fillOpacity: 0.6});
2755  *
2756  *     })();
2757  *
2758  * </script><pre>
2759  *
2760  */
2761 JXG.createCurveIntersection = function (board, parents, attributes) {
2762     var c;
2763 
2764     if (parents.length !== 2) {
2765         throw new Error(
2766             "JSXGraph: Can't create curve intersection with given parent'" +
2767             "\nPossible parent types: [array, array|function]"
2768         );
2769     }
2770 
2771     c = board.create("curve", [[], []], attributes);
2772     /**
2773      * @class
2774      * @ignore
2775      */
2776     c.updateDataArray = function () {
2777         var a = Clip.intersection(parents[0], parents[1], this.board);
2778         this.dataX = a[0];
2779         this.dataY = a[1];
2780     };
2781     return c;
2782 };
2783 
2784 /**
2785  * @class The path forming the union of two closed path elements.
2786  * The elements may be of type curve, circle, polygon, inequality.
2787  * If one element is a curve, it has to be closed.
2788  * The resulting element is of type curve.
2789  * @pseudo
2790  * @name CurveUnion
2791  * @param {JXG.Curve|JXG.Polygon|JXG.Circle} curve1 First element defining the union
2792  * @param {JXG.Curve|JXG.Polygon|JXG.Circle} curve2 Second element defining the union
2793  * @augments JXG.Curve
2794  * @constructor
2795  * @type JXG.Curve
2796  *
2797  * @example
2798  * var f = board.create('functiongraph', ['cos(x)']);
2799  * var ineq = board.create('inequality', [f], {inverse: true, fillOpacity: 0.1});
2800  * var circ = board.create('circle', [[0,0], 4]);
2801  * var clip = board.create('curveunion', [ineq, circ], {fillColor: 'yellow', fillOpacity: 0.6});
2802  *
2803  * </pre><div id="JXGe2948257-8835-4276-9164-8acccb48e8d4" class="jxgbox" style="width: 300px; height: 300px;"></div>
2804  * <script type="text/javascript">
2805  *     (function() {
2806  *         var board = JXG.JSXGraph.initBoard('JXGe2948257-8835-4276-9164-8acccb48e8d4',
2807  *             {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false});
2808  *     var f = board.create('functiongraph', ['cos(x)']);
2809  *     var ineq = board.create('inequality', [f], {inverse: true, fillOpacity: 0.1});
2810  *     var circ = board.create('circle', [[0,0], 4]);
2811  *     var clip = board.create('curveunion', [ineq, circ], {fillColor: 'yellow', fillOpacity: 0.6});
2812  *
2813  *     })();
2814  *
2815  * </script><pre>
2816  *
2817  */
2818 JXG.createCurveUnion = function (board, parents, attributes) {
2819     var c;
2820 
2821     if (parents.length !== 2) {
2822         throw new Error(
2823             "JSXGraph: Can't create curve union with given parent'" +
2824             "\nPossible parent types: [array, array|function]"
2825         );
2826     }
2827 
2828     c = board.create("curve", [[], []], attributes);
2829     /**
2830      * @class
2831      * @ignore
2832      */
2833     c.updateDataArray = function () {
2834         var a = Clip.union(parents[0], parents[1], this.board);
2835         this.dataX = a[0];
2836         this.dataY = a[1];
2837     };
2838     return c;
2839 };
2840 
2841 /**
2842  * @class The path forming the difference of two closed path elements.
2843  * The elements may be of type curve, circle, polygon, inequality.
2844  * If one element is a curve, it has to be closed.
2845  * The resulting element is of type curve.
2846  * @pseudo
2847  * @name CurveDifference
2848  * @param {JXG.Curve|JXG.Polygon|JXG.Circle} curve1 First element from which the second element is "subtracted"
2849  * @param {JXG.Curve|JXG.Polygon|JXG.Circle} curve2 Second element which is subtracted from the first element
2850  * @augments JXG.Curve
2851  * @constructor
2852  * @type JXG.Curve
2853  *
2854  * @example
2855  * var f = board.create('functiongraph', ['cos(x)']);
2856  * var ineq = board.create('inequality', [f], {inverse: true, fillOpacity: 0.1});
2857  * var circ = board.create('circle', [[0,0], 4]);
2858  * var clip = board.create('curvedifference', [ineq, circ], {fillColor: 'yellow', fillOpacity: 0.6});
2859  *
2860  * </pre><div id="JXGe2948257-8835-4276-9164-8acccb48e8d4" class="jxgbox" style="width: 300px; height: 300px;"></div>
2861  * <script type="text/javascript">
2862  *     (function() {
2863  *         var board = JXG.JSXGraph.initBoard('JXGe2948257-8835-4276-9164-8acccb48e8d4',
2864  *             {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false});
2865  *     var f = board.create('functiongraph', ['cos(x)']);
2866  *     var ineq = board.create('inequality', [f], {inverse: true, fillOpacity: 0.1});
2867  *     var circ = board.create('circle', [[0,0], 4]);
2868  *     var clip = board.create('curvedifference', [ineq, circ], {fillColor: 'yellow', fillOpacity: 0.6});
2869  *
2870  *     })();
2871  *
2872  * </script><pre>
2873  *
2874  */
2875 JXG.createCurveDifference = function (board, parents, attributes) {
2876     var c;
2877 
2878     if (parents.length !== 2) {
2879         throw new Error(
2880             "JSXGraph: Can't create curve difference with given parent'" +
2881             "\nPossible parent types: [array, array|function]"
2882         );
2883     }
2884 
2885     c = board.create("curve", [[], []], attributes);
2886     /**
2887      * @class
2888      * @ignore
2889      */
2890     c.updateDataArray = function () {
2891         var a = Clip.difference(parents[0], parents[1], this.board);
2892         this.dataX = a[0];
2893         this.dataY = a[1];
2894     };
2895     return c;
2896 };
2897 
2898 JXG.registerElement("curvedifference", JXG.createCurveDifference);
2899 JXG.registerElement("curveintersection", JXG.createCurveIntersection);
2900 JXG.registerElement("curveunion", JXG.createCurveUnion);
2901 
2902 // /**
2903 //  * @class Concat of two path elements, in general neither is a closed path. The parent elements have to be curves, too.
2904 //  * The resulting element is of type curve. The curve points are simply concatenated.
2905 //  * @pseudo
2906 //  * @name CurveConcat
2907 //  * @param {JXG.Curve} curve1 First curve element.
2908 //  * @param {JXG.Curve} curve2 Second curve element.
2909 //  * @augments JXG.Curve
2910 //  * @constructor
2911 //  * @type JXG.Curve
2912 //  */
2913 // JXG.createCurveConcat = function (board, parents, attributes) {
2914 //     var c;
2915 
2916 //     if (parents.length !== 2) {
2917 //         throw new Error(
2918 //             "JSXGraph: Can't create curve difference with given parent'" +
2919 //                 "\nPossible parent types: [array, array|function]"
2920 //         );
2921 //     }
2922 
2923 //     c = board.create("curve", [[], []], attributes);
2924 //     /**
2925 //      * @class
2926 //      * @ignore
2927 //      */
2928 //     c.updateCurve = function () {
2929 //         this.points = parents[0].points.concat(
2930 //                 [new JXG.Coords(Const.COORDS_BY_USER, [NaN, NaN], this.board)]
2931 //             ).concat(parents[1].points);
2932 //         this.numberPoints = this.points.length;
2933 //         return this;
2934 //     };
2935 
2936 //     return c;
2937 // };
2938 
2939 // JXG.registerElement("curveconcat", JXG.createCurveConcat);
2940 
2941 /**
2942  * @class Vertical or horizontal box plot curve to present numerical data through their quartiles.
2943  * The direction of the box plot is controlled by the attribute "dir".
2944  * @pseudo
2945  * @name Boxplot
2946  * @param {Array} quantiles Array containing at least five quantiles. The elements can be of type number, function or string.
2947  * @param {Number|Function} axis Axis position of the box plot
2948  * @param {Number|Function} width Width of the rectangle part of the box plot. The width of the first and 4th quantile
2949  * is relative to this width and can be controlled by the attribute "smallWidth".
2950  * @augments JXG.Curve
2951  * @constructor
2952  * @type JXG.Curve
2953  *
2954  * @example
2955  * var Q = [ -1, 2, 3, 3.5, 5 ];
2956  *
2957  * var b = board.create('boxplot', [Q, 2, 4], {strokeWidth: 3});
2958  *
2959  * </pre><div id="JXG13eb23a1-a641-41a2-be11-8e03e400a947" class="jxgbox" style="width: 300px; height: 300px;"></div>
2960  * <script type="text/javascript">
2961  *     (function() {
2962  *         var board = JXG.JSXGraph.initBoard('JXG13eb23a1-a641-41a2-be11-8e03e400a947',
2963  *             {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false});
2964  *     var Q = [ -1, 2, 3, 3.5, 5 ];
2965  *     var b = board.create('boxplot', [Q, 2, 4], {strokeWidth: 3});
2966  *
2967  *     })();
2968  *
2969  * </script><pre>
2970  *
2971  * @example
2972  * var Q = [ -1, 2, 3, 3.5, 5 ];
2973  * var b = board.create('boxplot', [Q, 3, 4], {dir: 'horizontal', smallWidth: 0.25, color:'red'});
2974  *
2975  * </pre><div id="JXG0deb9cb2-84bc-470d-a6db-8be9a5694813" class="jxgbox" style="width: 300px; height: 300px;"></div>
2976  * <script type="text/javascript">
2977  *     (function() {
2978  *         var board = JXG.JSXGraph.initBoard('JXG0deb9cb2-84bc-470d-a6db-8be9a5694813',
2979  *             {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false});
2980  *     var Q = [ -1, 2, 3, 3.5, 5 ];
2981  *     var b = board.create('boxplot', [Q, 3, 4], {dir: 'horizontal', smallWidth: 0.25, color:'red'});
2982  *
2983  *     })();
2984  *
2985  * </script><pre>
2986  *
2987  * @example
2988  * var data = [57, 57, 57, 58, 63, 66, 66, 67, 67, 68, 69, 70, 70, 70, 70, 72, 73, 75, 75, 76, 76, 78, 79, 81];
2989  * var Q = [];
2990  *
2991  * Q[0] = JXG.Math.Statistics.min(data);
2992  * Q = Q.concat(JXG.Math.Statistics.percentile(data, [25, 50, 75]));
2993  * Q[4] = JXG.Math.Statistics.max(data);
2994  *
2995  * var b = board.create('boxplot', [Q, 0, 3]);
2996  *
2997  * </pre><div id="JXGef079e76-ae99-41e4-af29-1d07d83bf85a" class="jxgbox" style="width: 300px; height: 300px;"></div>
2998  * <script type="text/javascript">
2999  *     (function() {
3000  *         var board = JXG.JSXGraph.initBoard('JXGef079e76-ae99-41e4-af29-1d07d83bf85a',
3001  *             {boundingbox: [-5,90,5,30], axis: true, showcopyright: false, shownavigation: false});
3002  *     var data = [57, 57, 57, 58, 63, 66, 66, 67, 67, 68, 69, 70, 70, 70, 70, 72, 73, 75, 75, 76, 76, 78, 79, 81];
3003  *     var Q = [];
3004  *
3005  *     Q[0] = JXG.Math.Statistics.min(data);
3006  *     Q = Q.concat(JXG.Math.Statistics.percentile(data, [25, 50, 75]));
3007  *     Q[4] = JXG.Math.Statistics.max(data);
3008  *
3009  *     var b = board.create('boxplot', [Q, 0, 3]);
3010  *
3011  *     })();
3012  *
3013  * </script><pre>
3014  *
3015  * @example
3016  * var mi = board.create('glider', [0, -1, board.defaultAxes.y]);
3017  * var ma = board.create('glider', [0, 5, board.defaultAxes.y]);
3018  * var Q = [function() { return mi.Y(); }, 2, 3, 3.5, function() { return ma.Y(); }];
3019  *
3020  * var b = board.create('boxplot', [Q, 0, 2]);
3021  *
3022  * </pre><div id="JXG3b3225da-52f0-42fe-8396-be9016bf289b" class="jxgbox" style="width: 300px; height: 300px;"></div>
3023  * <script type="text/javascript">
3024  *     (function() {
3025  *         var board = JXG.JSXGraph.initBoard('JXG3b3225da-52f0-42fe-8396-be9016bf289b',
3026  *             {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false});
3027  *     var mi = board.create('glider', [0, -1, board.defaultAxes.y]);
3028  *     var ma = board.create('glider', [0, 5, board.defaultAxes.y]);
3029  *     var Q = [function() { return mi.Y(); }, 2, 3, 3.5, function() { return ma.Y(); }];
3030  *
3031  *     var b = board.create('boxplot', [Q, 0, 2]);
3032  *
3033  *     })();
3034  *
3035  * </script><pre>
3036  *
3037  */
3038 JXG.createBoxPlot = function (board, parents, attributes) {
3039     var box, i, len,
3040         attr = Type.copyAttributes(attributes, board.options, "boxplot");
3041 
3042     if (parents.length !== 3) {
3043         throw new Error(
3044             "JSXGraph: Can't create box plot with given parent'" +
3045             "\nPossible parent types: [array, number|function, number|function] containing quantiles, axis, width"
3046         );
3047     }
3048     if (parents[0].length < 5) {
3049         throw new Error(
3050             "JSXGraph: Can't create box plot with given parent[0]'" +
3051             "\nparent[0] has to contain at least 5 quantiles."
3052         );
3053     }
3054     box = board.create("curve", [[], []], attr);
3055 
3056     len = parents[0].length; // Quantiles
3057     box.Q = [];
3058     for (i = 0; i < len; i++) {
3059         box.Q[i] = Type.createFunction(parents[0][i], board);
3060     }
3061     box.x = Type.createFunction(parents[1], board);
3062     box.w = Type.createFunction(parents[2], board);
3063 
3064     /**
3065      * @class
3066      * @ignore
3067      */
3068     box.updateDataArray = function () {
3069         var v1, v2, l1, l2, r1, r2, w2, dir, x;
3070 
3071         w2 = this.evalVisProp('smallwidth');
3072         dir = this.evalVisProp('dir');
3073         x = this.x();
3074         l1 = x - this.w() * 0.5;
3075         l2 = x - this.w() * 0.5 * w2;
3076         r1 = x + this.w() * 0.5;
3077         r2 = x + this.w() * 0.5 * w2;
3078         v1 = [x, l2, r2, x, x, l1, l1, r1, r1, x, NaN, l1, r1, NaN, x, x, l2, r2, x];
3079         v2 = [
3080             this.Q[0](),
3081             this.Q[0](),
3082             this.Q[0](),
3083             this.Q[0](),
3084             this.Q[1](),
3085             this.Q[1](),
3086             this.Q[3](),
3087             this.Q[3](),
3088             this.Q[1](),
3089             this.Q[1](),
3090             NaN,
3091             this.Q[2](),
3092             this.Q[2](),
3093             NaN,
3094             this.Q[3](),
3095             this.Q[4](),
3096             this.Q[4](),
3097             this.Q[4](),
3098             this.Q[4]()
3099         ];
3100         if (dir === "vertical") {
3101             this.dataX = v1;
3102             this.dataY = v2;
3103         } else {
3104             this.dataX = v2;
3105             this.dataY = v1;
3106         }
3107     };
3108 
3109     box.addParentsFromJCFunctions([box.Q, box.x, box.w]);
3110 
3111     return box;
3112 };
3113 
3114 JXG.registerElement("boxplot", JXG.createBoxPlot);
3115 
3116 /**
3117  * @class An implicit curve is a plane curve defined by an implicit equation
3118  * relating two coordinate variables, commonly <i>x</i> and <i>y</i>.
3119  * For example, the unit circle is defined by the implicit equation
3120  * x<sup>2</sup> + y<sup>2</sup> = 1.
3121  * In general, every implicit curve is defined by an equation of the form
3122  * <i>f(x, y) = 0</i>
3123  * for some function <i>f</i> of two variables. (<a href="https://en.wikipedia.org/wiki/Implicit_curve">Wikipedia</a>)
3124  * <p>
3125  * The partial derivatives for <i>f</i> are optional. If not given, numerical
3126  * derivatives are used instead. This is good enough for most practical use cases.
3127  * But if supplied, both partial derivatives must be supplied.
3128  * <p>
3129  * The most effective attributes to tinker with if the implicit curve algorithm fails are
3130  * {@link ImplicitCurve#resolution_outer},
3131  * {@link ImplicitCurve#resolution_inner},
3132  * {@link ImplicitCurve#alpha_0},
3133  * {@link ImplicitCurve#h_initial},
3134  * {@link ImplicitCurve#h_max}, and
3135  * {@link ImplicitCurve#qdt_box}.
3136  *
3137  * @pseudo
3138  * @name ImplicitCurve
3139  * @param {Function|String} f Function of two variables for the left side of the equation <i>f(x,y)=0</i>.
3140  * If f is supplied as string, it has to use the variables 'x' and 'y'.
3141  * @param {Function|String} [dfx=null] Optional partial derivative in respect to the first variable
3142  * If dfx is supplied as string, it has to use the variables 'x' and 'y'.
3143  * @param {Function|String} [dfy=null] Optional partial derivative in respect to the second variable
3144  * If dfy is supplied as string, it has to use the variables 'x' and 'y'.
3145  * @param {Array|Function} [rangex=boundingbox] Optional array of length 2
3146  * of the form [x_min, x_max] setting the domain of the x coordinate of the implicit curve.
3147  * If not supplied, the board's boundingbox (+ the attribute "margin") is taken.
3148  * For algorithmic reasons, the plotted curve mighty slightly overflow the given domain.
3149  * @param {Array|Function} [rangey=boundingbox] Optional array of length 2
3150  * of the form [y_min, y_max] setting the domain of the y coordinate of the implicit curve.
3151  * If not supplied, the board's boundingbox (+ the attribute "margin") is taken.
3152  * For algorithmic reasons, the plotted curve mighty slightly overflow the given domain.
3153  * @augments JXG.Curve
3154  * @constructor
3155  * @type JXG.Curve
3156  *
3157  * @example
3158  *   var f, c;
3159  *   f = (x, y) => 1 / 16 * x ** 2 + y ** 2 - 1;
3160  *   c = board.create('implicitcurve', [f], {
3161  *       strokeWidth: 3,
3162  *       strokeColor: JXG.palette.red,
3163  *       strokeOpacity: 0.8
3164  *   });
3165  *
3166  * </pre><div id="JXGa6e86701-1a82-48d0-b007-3a3d32075076" class="jxgbox" style="width: 300px; height: 300px;"></div>
3167  * <script type="text/javascript">
3168  *     (function() {
3169  *         var board = JXG.JSXGraph.initBoard('JXGa6e86701-1a82-48d0-b007-3a3d32075076',
3170  *             {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false});
3171  *             var f, c;
3172  *             f = (x, y) => 1 / 16 * x ** 2 + y ** 2 - 1;
3173  *             c = board.create('implicitcurve', [f], {
3174  *                 strokeWidth: 3,
3175  *                 strokeColor: JXG.palette.red,
3176  *                 strokeOpacity: 0.8
3177  *             });
3178  *
3179  *     })();
3180  *
3181  * </script><pre>
3182  *
3183  * @example
3184  *  var a, c, f;
3185  *  a = board.create('slider', [[-3, 6], [3, 6], [-3, 1, 3]], {
3186  *      name: 'a', stepWidth: 0.1
3187  *  });
3188  *  f = (x, y) => x ** 2 - 2 * x * y - 2 * x + (a.Value() + 1) * y ** 2 + (4 * a.Value() + 2) * y + 4 * a.Value() - 3;
3189  *  c = board.create('implicitcurve', [f], {
3190  *      strokeWidth: 3,
3191  *      strokeColor: JXG.palette.red,
3192  *      strokeOpacity: 0.8,
3193  *      resolution_outer: 20,
3194  *      resolution_inner: 20
3195  *  });
3196  *
3197  * </pre><div id="JXG0b133a54-9509-4a65-9722-9c5145e23b40" class="jxgbox" style="width: 300px; height: 300px;"></div>
3198  * <script type="text/javascript">
3199  *     (function() {
3200  *         var board = JXG.JSXGraph.initBoard('JXG0b133a54-9509-4a65-9722-9c5145e23b40',
3201  *             {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false});
3202  *             var a, c, f;
3203  *             a = board.create('slider', [[-3, 6], [3, 6], [-3, 1, 3]], {
3204  *                 name: 'a', stepWidth: 0.1
3205  *             });
3206  *             f = (x, y) => x ** 2 - 2 * x * y - 2 * x + (a.Value() + 1) * y ** 2 + (4 * a.Value() + 2) * y + 4 * a.Value() - 3;
3207  *             c = board.create('implicitcurve', [f], {
3208  *                 strokeWidth: 3,
3209  *                 strokeColor: JXG.palette.red,
3210  *                 strokeOpacity: 0.8,
3211  *                 resolution_outer: 20,
3212  *                 resolution_inner: 20
3213  *             });
3214  *
3215  *     })();
3216  *
3217  * </script><pre>
3218  *
3219  * @example
3220  *  var c = board.create('implicitcurve', ['abs(x * y) - 3'], {
3221  *      strokeWidth: 3,
3222  *      strokeColor: JXG.palette.red,
3223  *      strokeOpacity: 0.8
3224  *  });
3225  *
3226  * </pre><div id="JXG02802981-0abb-446b-86ea-ee588f02ed1a" class="jxgbox" style="width: 300px; height: 300px;"></div>
3227  * <script type="text/javascript">
3228  *     (function() {
3229  *         var board = JXG.JSXGraph.initBoard('JXG02802981-0abb-446b-86ea-ee588f02ed1a',
3230  *             {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false});
3231  *             var c = board.create('implicitcurve', ['abs(x * y) - 3'], {
3232  *                 strokeWidth: 3,
3233  *                 strokeColor: JXG.palette.red,
3234  *                 strokeOpacity: 0.8
3235  *             });
3236  *
3237  *     })();
3238  *
3239  * </script><pre>
3240  *
3241  * @example
3242  * var niveauline = [];
3243  * niveauline = [0.5, 1, 1.5, 2];
3244  * for (let i = 0; i < niveauline.length; i++) {
3245  *     board.create("implicitcurve", [
3246  *         (x, y) => x ** .5 * y ** .5 - niveauline[i],
3247            [0.25, 3], [0.5, 4] // Domain
3248  *     ], {
3249  *         strokeWidth: 2,
3250  *         strokeColor: JXG.palette.red,
3251  *         strokeOpacity: (1 + i) / niveauline.length,
3252  *         needsRegularUpdate: false
3253  *     });
3254  * }
3255  *
3256  * </pre><div id="JXGccee9aab-6dd9-4a79-827d-3164f70cc6a1" class="jxgbox" style="width: 300px; height: 300px;"></div>
3257  * <script type="text/javascript">
3258  *     (function() {
3259  *         var board = JXG.JSXGraph.initBoard('JXGccee9aab-6dd9-4a79-827d-3164f70cc6a1',
3260  *             {boundingbox: [-1, 5, 5,-1], axis: true, showcopyright: false, shownavigation: false});
3261  *         var niveauline = [];
3262  *         niveauline = [0.5, 1, 1.5, 2];
3263  *         for (let i = 0; i < niveauline.length; i++) {
3264  *             board.create("implicitcurve", [
3265  *                 (x, y) => x ** .5 * y ** .5 - niveauline[i],
3266  *                 [0.25, 3], [0.5, 4]
3267  *             ], {
3268  *                 strokeWidth: 2,
3269  *                 strokeColor: JXG.palette.red,
3270  *                 strokeOpacity: (1 + i) / niveauline.length,
3271  *                 needsRegularUpdate: false
3272  *             });
3273  *         }
3274  *
3275  *     })();
3276  *
3277  * </script><pre>
3278  *
3279  */
3280 JXG.createImplicitCurve = function (board, parents, attributes) {
3281     var c, attr;
3282 
3283     if ([1, 3, 5].indexOf(parents.length) < 0) {
3284         throw new Error(
3285             "JSXGraph: Can't create curve implicitCurve with given parent'" +
3286             "\nPossible parent types: [f], [f, rangex, rangey], [f, dfx, dfy] or [f, dfx, dfy, rangex, rangey]" +
3287             "\nwith functions f, dfx, dfy and arrays of length 2 rangex, rangey."
3288         );
3289     }
3290 
3291     // if (parents.length === 3) {
3292     //     if (!Type.isArray(parents[1]) && !Type.isArray(parents[2])) {
3293     //         throw new Error(
3294     //             "JSXGraph: Can't create curve implicitCurve with given parent'" +
3295     //             "\nPossible parent types: [f], [f, rangex, rangey], [f, dfx, dfy] or [f, dfx, dfy, rangex, rangey]" +
3296     //             "\nwith functions f, dfx, dfy and arrays of length 2 rangex, rangey."
3297     //         );
3298     //     }
3299     // }
3300     // if (parents.length === 5) {
3301     //     if (!Type.isArray(parents[3]) && !Type.isArray(parents[4])) {
3302     //         throw new Error(
3303     //             "JSXGraph: Can't create curve implicitCurve with given parent'" +
3304     //             "\nPossible parent types: [f], [f, rangex, rangey], [f, dfx, dfy] or [f, dfx, dfy, rangex, rangey]" +
3305     //             "\nwith functions f, dfx, dfy and arrays of length 2 rangex, rangey."
3306     //         );
3307     //     }
3308     // }
3309 
3310     attr = Type.copyAttributes(attributes, board.options, "implicitcurve");
3311     c = board.create("curve", [[], []], attr);
3312 
3313     /**
3314      * Function of two variables for the left side of the equation <i>f(x,y)=0</i>.
3315      *
3316      * @name f
3317      * @memberOf ImplicitCurve.prototype
3318      * @function
3319      * @returns {Number}
3320      */
3321     c.f = Type.createFunction(parents[0], board, 'x, y');
3322 
3323     /**
3324      * Partial derivative in the first variable of
3325      * the left side of the equation <i>f(x,y)=0</i>.
3326      * If null, then numerical derivative is used.
3327      *
3328      * @name dfx
3329      * @memberOf ImplicitCurve.prototype
3330      * @function
3331      * @returns {Number}
3332      */
3333     c.dfx = Type.createFunction(parents[1], board, 'x, y');
3334 
3335     /**
3336      * Partial derivative in the second variable of
3337      * the left side of the equation <i>f(x,y)=0</i>.
3338      * If null, then numerical derivative is used.
3339      *
3340      * @name dfy
3341      * @memberOf ImplicitCurve.prototype
3342      * @function
3343      * @returns {Number}
3344      */
3345     c.dfy = Type.createFunction(parents[2], board, 'x, y');
3346 
3347     /**
3348      * Defines a domain for searching f(x,y)=0. Default is null, meaning
3349      * the bounding box of the board is used.
3350      * Using domain, visProp.margin is ignored.
3351      * @name domain
3352      * @memberOf ImplicitCurve.prototype
3353      * @param {Array} of length 4 defining the domain used to compute the implict curve.
3354      * Syntax: [x_min, y_max, x_max, y_min]
3355      */
3356     // c.domain = board.getBoundingBox();
3357     c.domain = null;
3358     if (parents.length === 5) {
3359         c.domain = [parents[3], parents[4]];
3360         // c.visProp.margin = 0;
3361     } else if (parents.length === 3) {
3362         c.domain = [parents[1], parents[2]];
3363         // c.visProp.margin = 0;
3364     }
3365 
3366     /**
3367      * @class
3368      * @ignore
3369      */
3370     c.updateDataArray = function () {
3371         var bbox, rx, ry,
3372             ip, cfg,
3373             ret = [],
3374             mgn;
3375 
3376         if (this.domain === null) {
3377             mgn = this.evalVisProp('margin');
3378             bbox = this.board.getBoundingBox();
3379             bbox[0] -= mgn;
3380             bbox[1] += mgn;
3381             bbox[2] += mgn;
3382             bbox[3] -= mgn;
3383         } else {
3384             rx = Type.evaluate(this.domain[0]);
3385             ry = Type.evaluate(this.domain[1]);
3386             bbox = [rx[0], ry[1], rx[1], ry[0]];
3387         }
3388 
3389         cfg = {
3390             resolution_out: Math.max(0.01, this.evalVisProp('resolution_outer')),
3391             resolution_in: Math.max(0.01, this.evalVisProp('resolution_inner')),
3392             max_steps: this.evalVisProp('max_steps'),
3393             alpha_0: this.evalVisProp('alpha_0'),
3394             tol_u0: this.evalVisProp('tol_u0'),
3395             tol_newton: this.evalVisProp('tol_newton'),
3396             tol_cusp: this.evalVisProp('tol_cusp'),
3397             tol_progress: this.evalVisProp('tol_progress'),
3398             qdt_box: this.evalVisProp('qdt_box'),
3399             kappa_0: this.evalVisProp('kappa_0'),
3400             delta_0: this.evalVisProp('delta_0'),
3401             h_initial: this.evalVisProp('h_initial'),
3402             h_critical: this.evalVisProp('h_critical'),
3403             h_max: this.evalVisProp('h_max'),
3404             loop_dist: this.evalVisProp('loop_dist'),
3405             loop_dir: this.evalVisProp('loop_dir'),
3406             loop_detection: this.evalVisProp('loop_detection'),
3407             unitX: this.board.unitX,
3408             unitY: this.board.unitY
3409         };
3410         this.dataX = [];
3411         this.dataY = [];
3412 
3413         // console.time("implicit plot");
3414         ip = new ImplicitPlot(bbox, cfg, this.f, this.dfx, this.dfy);
3415         this.qdt = ip.qdt;
3416 
3417         ret = ip.plot();
3418         // console.timeEnd("implicit plot");
3419 
3420         this.dataX = ret[0];
3421         this.dataY = ret[1];
3422     };
3423 
3424     c.elType = 'implicitcurve';
3425 
3426     return c;
3427 };
3428 
3429 JXG.registerElement("implicitcurve", JXG.createImplicitCurve);
3430 
3431 
3432 export default JXG.Curve;
3433 
3434 // export default {
3435 //     Curve: JXG.Curve,
3436 //     createCardinalSpline: JXG.createCardinalSpline,
3437 //     createCurve: JXG.createCurve,
3438 //     createCurveDifference: JXG.createCurveDifference,
3439 //     createCurveIntersection: JXG.createCurveIntersection,
3440 //     createCurveUnion: JXG.createCurveUnion,
3441 //     createDerivative: JXG.createDerivative,
3442 //     createFunctiongraph: JXG.createFunctiongraph,
3443 //     createMetapostSpline: JXG.createMetapostSpline,
3444 //     createPlot: JXG.createFunctiongraph,
3445 //     createSpline: JXG.createSpline,
3446 //     createRiemannsum: JXG.createRiemannsum,
3447 //     createStepfunction: JXG.createStepfunction,
3448 //     createTracecurve: JXG.createTracecurve
3449 // };
3450 
3451 // const Curve = JXG.Curve;
3452 // export { Curve as default, Curve};
3453