1 /*
  2     Copyright 2008-2023
  3         Matthias Ehmann,
  4         Carsten Miller,
  5         Andreas Walter,
  6         Alfred Wassermann
  7 
  8     This file is part of JSXGraph.
  9 
 10     JSXGraph is free software dual licensed under the GNU LGPL or MIT License.
 11 
 12     You can redistribute it and/or modify it under the terms of the
 13 
 14       * GNU Lesser General Public License as published by
 15         the Free Software Foundation, either version 3 of the License, or
 16         (at your option) any later version
 17       OR
 18       * MIT License: https://github.com/jsxgraph/jsxgraph/blob/master/LICENSE.MIT
 19 
 20     JSXGraph is distributed in the hope that it will be useful,
 21     but WITHOUT ANY WARRANTY; without even the implied warranty of
 22     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 23     GNU Lesser General Public License for more details.
 24 
 25     You should have received a copy of the GNU Lesser General Public License and
 26     the MIT License along with JSXGraph. If not, see <https://www.gnu.org/licenses/>
 27     and <https://opensource.org/licenses/MIT/>.
 28  */
 29 /*global JXG:true, define: true*/
 30 
 31 import JXG from "../jxg";
 32 import Const from "../base/constants";
 33 import Mat from "../math/math";
 34 import Geometry from "../math/geometry";
 35 import Type from "../utils/type";
 36 //, GeometryElement3D) {
 37 
 38 /**
 39  * A 3D point is the basic geometric element.
 40  * @class Creates a new 3D point object. Do not use this constructor to create a 3D point. Use {@link JXG.View3D#create} with
 41  * type {@link Point3D} instead.
 42  * @augments JXG.GeometryElement3D
 43  * @augments JXG.GeometryElement
 44  * @param {JXG.View3D} view The 3D view the point is drawn on.
 45  * @param {Function|Array} F Array of numbers, array of functions or function returning an array with defines the user coordinates of the point.
 46  * @parame {JXG.GeometryElement3D} slide Object the 3D point should be bound to. If null, the point is a free point.
 47  * @param {Object} attributes An object containing visual properties like in {@link JXG.Options#point3d} and
 48  * {@link JXG.Options#elements}, and optional a name and an id.
 49  * @see JXG.Board#generateName
 50  */
 51 JXG.Point3D = function (view, F, slide, attributes) {
 52     this.constructor(view.board, attributes, Const.OBJECT_TYPE_POINT3D, Const.OBJECT_CLASS_3D);
 53     this.constructor3D(view, "point3d");
 54 
 55     this.board.finalizeAdding(this);
 56 
 57     /**
 58      * Homogeneous coordinates of a Point3D, i.e. array of length 4: [w, x, y, z]. Usually, w=1 for finite points and w=0 for points
 59      * which are infinitely far.
 60      *
 61      * @example
 62      *   p.coords;
 63      *
 64      * @name Point3D#coords
 65      * @type Array
 66      * @private
 67      */
 68     this.coords = [0, 0, 0, 0];
 69 
 70     /**
 71      * Function or array of functions or array of numbers defining the coordinates of the point, used in {@link updateCoords}.
 72      *
 73      * @name Point3D#F
 74      * @function
 75      * @private
 76      *
 77      * @see updateCoords
 78      */
 79     this.F = F;
 80 
 81     /**
 82      * Optional slide element, i.e. element the Point3D lives on.
 83      *
 84      * @example
 85      *   p.slide;
 86      *
 87      * @name Point3D#slide
 88      * @type JXG.GeometryElement3D
 89      * @default null
 90      * @private
 91      *
 92      */
 93     this.slide = slide;
 94 
 95     /**
 96      * Get x-coordinate of a 3D point.
 97      *
 98      * @name X
 99      * @memberOf Point3D
100      * @function
101      * @returns {Number}
102      *
103      * @example
104      *   p.X();
105      */
106     this.X = function () {
107         return this.coords[1];
108     };
109 
110     /**
111      * Get y-coordinate of a 3D point.
112      *
113      * @name Y
114      * @memberOf Point3D
115      * @function
116      * @returns Number
117      *
118      * @example
119      *   p.Y();
120      */
121     this.Y = function () {
122         return this.coords[2];
123     };
124 
125     /**
126      * Get z-coordinate of a 3D point.
127      *
128      * @name Z
129      * @memberOf Point3D
130      * @function
131      * @returns Number
132      *
133      * @example
134      *   p.Z();
135      */
136     this.Z = function () {
137         return this.coords[3];
138     };
139 
140     /**
141      * Store the last position of the 2D point for the optimizer.
142      *
143      * @type Array
144      * @private
145      */
146     this._params = null;
147 
148     this._c2d = null;
149 
150     this.methodMap = Type.deepCopy(this.methodMap, {
151         // TODO
152     });
153 };
154 JXG.Point3D.prototype = new JXG.GeometryElement();
155 Type.copyPrototypeMethods(JXG.Point3D, JXG.GeometryElement3D, "constructor3D");
156 
157 JXG.extend(
158     JXG.Point3D.prototype,
159     /** @lends JXG.Point3D.prototype */ {
160         /**
161          * Update the homogeneous coords array.
162          *
163          * @name updateCoords
164          * @memberOf Point3D
165          * @function
166          * @returns {Object} Reference to the Point3D object
167          * @private
168          * @example
169          *    p.updateCoords();
170          */
171         updateCoords: function () {
172             var i;
173 
174             if (Type.isFunction(this.F)) {
175                 this.coords = [1].concat(Type.evaluate(this.F));
176             } else {
177                 this.coords[0] = 1;
178                 for (i = 0; i < 3; i++) {
179                     // Attention: if F is array of numbers, coords are not updated.
180                     // Otherwise, dragging will not work anymore.
181                     if (Type.isFunction(this.F[i])) {
182                         this.coords[i + 1] = Type.evaluate(this.F[i]);
183                     }
184                 }
185             }
186             return this;
187         },
188 
189         /**
190          * Initialize the coords array.
191          *
192          * @private
193          * @returns {Object} Reference to the Point3D object
194          */
195         initCoords: function () {
196             var i;
197 
198             if (Type.isFunction(this.F)) {
199                 this.coords = [1].concat(Type.evaluate(this.F));
200             } else {
201                 this.coords[0] = 1;
202                 for (i = 0; i < 3; i++) {
203                     this.coords[i + 1] = Type.evaluate(this.F[i]);
204                 }
205             }
206             return this;
207         },
208 
209         /**
210          * Normalize homogeneous coordinates such the the first coordinate (the w-coordinate is equal to 1 or 0)-
211          *
212          * @name normalizeCoords
213          * @memberOf Point3D
214          * @function
215          * @returns {Object} Reference to the Point3D object
216          * @private
217          * @example
218          *    p.normalizeCoords();
219          */
220         normalizeCoords: function () {
221             if (Math.abs(this.coords[0]) > Mat.eps) {
222                 this.coords[1] /= this.coords[0];
223                 this.coords[2] /= this.coords[0];
224                 this.coords[3] /= this.coords[0];
225                 this.coords[0] = 1.0;
226             }
227             return this;
228         },
229 
230         /**
231          * Set the position of a 3D point.
232          *
233          * @name setPosition
234          * @memberOf Point3D
235          * @function
236          * @param {Array} coords 3D coordinates. Either of the form [x,y,z] (Euclidean) or [w,x,y,z] (homogeneous).
237          * @param {Boolean} [noevent] If true, no events are triggered.
238          * @returns {Object} Reference to the Point3D object
239          *
240          * @example
241          *    p.setPosition([1, 3, 4]);
242          */
243         setPosition: function (coords, noevent) {
244             var c = this.coords,
245                 oc = this.coords.slice(); // Copy of original values
246 
247             if (coords.length === 3) {
248                 // Euclidean coordinates
249                 c[0] = 1.0;
250                 c[1] = coords[0];
251                 c[2] = coords[1];
252                 c[3] = coords[2];
253             } else {
254                 // Homogeneous coordinates (normalized)
255                 c[0] = coords[0];
256                 c[1] = coords[1];
257                 c[2] = coords[2];
258                 c[3] = coords[2];
259                 this.normalizeCoords();
260             }
261 
262             // console.log(el.emitter, !noevent, oc[0] !== c[0] || oc[1] !== c[1] || oc[2] !== c[2] || oc[3] !== c[3]);
263             // Not yet working
264             // if (el.emitter && !noevent &&
265             //     (oc[0] !== c[0] || oc[1] !== c[1] || oc[2] !== c[2] || oc[3] !== c[3])) {
266             //     this.triggerEventHandlers(['update3D'], [oc]);
267             // }
268             return this;
269         },
270 
271         update: function (drag) {
272             var c3d, foot;
273 
274             // Update is called from two methods:
275             // Once in setToPosition and
276             // once in the subsequent board.update
277             if (
278                 this.element2D.draggable() &&
279                 Geometry.distance(this._c2d, this.element2D.coords.usrCoords) !== 0
280             ) {
281                 if (this.slide) {
282                     this.projectCoords2Surface();
283                 } else {
284                     if (this.view.isVerticalDrag()) {
285                         // Drag the point in its vertical to the xy plane
286                         c3d = this.view.project2DTo3DVertical(this.element2D, this.coords);
287                     } else {
288                         // Drag the point in its xy plane
289                         foot = [1, 0, 0, this.coords[3]];
290                         c3d = this.view.project2DTo3DPlane(this.element2D, [1, 0, 0, 1], foot);
291                     }
292                     if (c3d[0] !== 0) {
293                         this.coords = this.view.project3DToCube(c3d);
294                     }
295                 }
296             } else {
297                 this.updateCoords();
298                 // Update 2D point from its 3D view
299                 this.element2D.coords.setCoordinates(
300                     Const.COORDS_BY_USER,
301                     this.view.project3DTo2D([1, this.X(), this.Y(), this.Z()])
302                 );
303             }
304             this._c2d = this.element2D.coords.usrCoords.slice();
305 
306             return this;
307         },
308 
309         updateRenderer: function () {
310             this.needsUpdate = false;
311             return this;
312         },
313 
314         projectCoords2Surface: function () {
315             var n = 2, // # of variables
316                 m = 2, // number of constraints
317                 x = [0, 0],
318                 // Various Cobyla constants, see Cobyla docs in Cobyja.js
319                 rhobeg = 5.0,
320                 rhoend = 1.0e-6,
321                 iprint = 0,
322                 maxfun = 200,
323                 surface = this.slide,
324                 that = this,
325                 r,
326                 c3d,
327                 c2d,
328                 _minFunc;
329 
330             if (surface === null) {
331                 return;
332             }
333 
334             _minFunc = function (n, m, x, con) {
335                 var c3d = [
336                         1,
337                         surface.X(x[0], x[1]),
338                         surface.Y(x[0], x[1]),
339                         surface.Z(x[0], x[1])
340                     ],
341                     c2d = that.view.project3DTo2D(c3d);
342 
343                 con[0] = that.element2D.X() - c2d[1];
344                 con[1] = that.element2D.Y() - c2d[2];
345 
346                 return con[0] * con[0] + con[1] * con[1];
347             };
348             if (Type.exists(this._params)) {
349                 x = this._params.slice();
350             }
351             r = Mat.Nlp.FindMinimum(_minFunc, n, m, x, rhobeg, rhoend, iprint, maxfun);
352 
353             c3d = [1, surface.X(x[0], x[1]), surface.Y(x[0], x[1]), surface.Z(x[0], x[1])];
354             c2d = this.view.project3DTo2D(c3d);
355             this._params = x;
356             this.coords = c3d;
357             this.element2D.coords.setCoordinates(Const.COORDS_BY_USER, c2d);
358             this._c2d = c2d;
359         },
360 
361         // Not yet working
362         __evt__update3D: function (oc) {}
363     }
364 );
365 
366 /**
367  * @class This element is used to provide a constructor for a 3D Point.
368  * @pseudo
369  * @description A Point3D object is defined by 3 coordinates [x,y,z].
370  * <p>
371  * All numbers can also be provided as functions returning a number.
372  *
373  * @name Point3D
374  * @augments JXG.Point3D
375  * @constructor
376  * @throws {Exception} If the element cannot be constructed with the given parent
377  * objects an exception is thrown.
378  * @param {number,function_number,function_number,function} x,y,z The coordinates are given as x, y, z consisting of numbers of functions.
379  * @param {array,function} F Alternatively, the coordinates can be supplied as
380  *  <ul>
381  *   <li>array arr=[x,y,z] of length 3 consisting of numbers or
382  *   <li>function returning an array [x,y,z] of length 3 of numbers.
383  * </ul>
384  *
385  * @example
386  *    var bound = [-5, 5];
387  *    var view = board.create('view3d',
388  *        [[-6, -3], [8, 8],
389  *        [bound, bound, bound]],
390  *        {});
391  *    var p = view.create('point3d', [1, 2, 2], { name:'A', size: 5 });
392  *    var q = view.create('point3d', function() { return [p.X(), p.Y(), p.Z() - 3]; }, { name:'B', size: 5, fixed: true });
393  *
394  * </pre><div id="JXGb9ee8f9f-3d2b-4f73-8221-4f82c09933f1" class="jxgbox" style="width: 300px; height: 300px;"></div>
395  * <script type="text/javascript">
396  *     (function() {
397  *         var board = JXG.JSXGraph.initBoard('JXGb9ee8f9f-3d2b-4f73-8221-4f82c09933f1',
398  *             {boundingbox: [-8, 8, 8,-8], axis: false, showcopyright: false, shownavigation: false});
399  *         var bound = [-5, 5];
400  *         var view = board.create('view3d',
401  *             [[-6, -3], [8, 8],
402  *             [bound, bound, bound]],
403  *             {});
404  *         var p = view.create('point3d', [1, 2, 2], { name:'A', size: 5 });
405  *         var q = view.create('point3d', function() { return [p.X(), p.Y(), p.Z() - 3]; }, { name:'B', size: 5 });
406  *     })();
407  *
408  * </script><pre>
409  *
410  */
411 JXG.createPoint3D = function (board, parents, attributes) {
412     //   parents[0]: view
413     // followed by
414     //   parents[1]: function or array
415     // or
416     //   parents[1..3]: coordinates
417 
418     var view = parents[0],
419         attr, F, slide, c2d, el;
420 
421     // If the last element of parents is a 3D object,
422     // the point is a glider on that element.
423     if (parents.length > 2 && Type.exists(parents[parents.length - 1].is3D)) {
424         slide = parents.pop();
425     } else {
426         slide = null;
427     }
428 
429     if (parents.length === 2) {
430         // [view, array|fun] (Array [x, y, z] | function) returning [x, y, z]
431         F = parents[1];
432     } else if (parents.length === 4) {
433         // [view, x, y, z], (3 numbers | functions)
434         F = parents.slice(1);
435     } else {
436         throw new Error(
437             "JSXGraph: Can't create point3d with parent types '" +
438                 typeof parents[0] +
439                 "' and '" +
440                 typeof parents[1] +
441                 "'." +
442                 "\nPossible parent types: [[x,y,z]], [x,y,z]"
443         );
444         //  "\nPossible parent types: [[x,y,z]], [x,y,z], [element,transformation]"); // TODO
445     }
446 
447     attr = Type.copyAttributes(attributes, board.options, 'point3d');
448     el = new JXG.Point3D(view, F, slide, attr);
449     el.initCoords();
450 
451     c2d = view.project3DTo2D(el.coords);
452 
453     attr = el.setAttr2D(attr);
454     el.element2D = view.create('point', c2d, attr);
455     el.addChild(el.element2D);
456     el.inherits.push(el.element2D);
457     el.element2D.setParents(el);
458 
459     el._c2d = el.element2D.coords.usrCoords.slice(); // Store a copy of the coordinates to detect dragging
460 
461     return el;
462 };
463 
464 JXG.registerElement("point3d", JXG.createPoint3D);
465