classname,id,original_code,num_file,num_line,Programming Language ckmeans,./ProjectTest/JavaScript/ckmeans.js,"// ckmeans/numeric_sort.js /** * Sort an array of numbers by their numeric value, ensuring that the * array is not changed in place. * * This is necessary because the default behavior of .sort * in JavaScript is to sort arrays as string values * * [1, 10, 12, 102, 20].sort() * // output * [1, 10, 102, 12, 20] * * @param {Array} x input array * @return {Array} sorted array * @private * @example * numericSort([3, 2, 1]) // => [1, 2, 3] */ function numericSort(x) { return ( x // ensure the array is not changed in-place .slice() // comparator function that treats input as numeric .sort(function (a, b) { return a - b; }) ); } export default numericSort; // ckmeans/ckmeans.js import makeMatrix from ""./make_matrix.js""; import numericSort from ""./numeric_sort.js""; import uniqueCountSorted from ""./unique_count_sorted.js""; /** * Generates incrementally computed values based on the sums and sums of * squares for the data array * * @private * @param {number} j * @param {number} i * @param {Array} sums * @param {Array} sumsOfSquares * @return {number} * @example * ssq(0, 1, [-1, 0, 2], [1, 1, 5]); */ function ssq(j, i, sums, sumsOfSquares) { let sji; // s(j, i) if (j > 0) { const muji = (sums[i] - sums[j - 1]) / (i - j + 1); // mu(j, i) sji = sumsOfSquares[i] - sumsOfSquares[j - 1] - (i - j + 1) * muji * muji; } else { sji = sumsOfSquares[i] - (sums[i] * sums[i]) / (i + 1); } if (sji < 0) { return 0; } return sji; } /** * Function that recursively divides and conquers computations * for cluster j * * @private * @param {number} iMin Minimum index in cluster to be computed * @param {number} iMax Maximum index in cluster to be computed * @param {number} cluster Index of the cluster currently being computed * @param {Array>} matrix * @param {Array>} backtrackMatrix * @param {Array} sums * @param {Array} sumsOfSquares */ function fillMatrixColumn( iMin, iMax, cluster, matrix, backtrackMatrix, sums, sumsOfSquares ) { if (iMin > iMax) { return; } // Start at midpoint between iMin and iMax const i = Math.floor((iMin + iMax) / 2); matrix[cluster][i] = matrix[cluster - 1][i - 1]; backtrackMatrix[cluster][i] = i; let jlow = cluster; // the lower end for j if (iMin > cluster) { jlow = Math.max(jlow, backtrackMatrix[cluster][iMin - 1] || 0); } jlow = Math.max(jlow, backtrackMatrix[cluster - 1][i] || 0); let jhigh = i - 1; // the upper end for j if (iMax < matrix[0].length - 1) { /* c8 ignore start */ jhigh = Math.min(jhigh, backtrackMatrix[cluster][iMax + 1] || 0); /* c8 ignore end */ } let sji; let sjlowi; let ssqjlow; let ssqj; for (let j = jhigh; j >= jlow; --j) { sji = ssq(j, i, sums, sumsOfSquares); if (sji + matrix[cluster - 1][jlow - 1] >= matrix[cluster][i]) { break; } // Examine the lower bound of the cluster border sjlowi = ssq(jlow, i, sums, sumsOfSquares); ssqjlow = sjlowi + matrix[cluster - 1][jlow - 1]; if (ssqjlow < matrix[cluster][i]) { // Shrink the lower bound matrix[cluster][i] = ssqjlow; backtrackMatrix[cluster][i] = jlow; } jlow++; ssqj = sji + matrix[cluster - 1][j - 1]; if (ssqj < matrix[cluster][i]) { matrix[cluster][i] = ssqj; backtrackMatrix[cluster][i] = j; } } fillMatrixColumn( iMin, i - 1, cluster, matrix, backtrackMatrix, sums, sumsOfSquares ); fillMatrixColumn( i + 1, iMax, cluster, matrix, backtrackMatrix, sums, sumsOfSquares ); } /** * Initializes the main matrices used in Ckmeans and kicks * off the divide and conquer cluster computation strategy * * @private * @param {Array} data sorted array of values * @param {Array>} matrix * @param {Array>} backtrackMatrix */ function fillMatrices(data, matrix, backtrackMatrix) { const nValues = matrix[0].length; // Shift values by the median to improve numeric stability const shift = data[Math.floor(nValues / 2)]; // Cumulative sum and cumulative sum of squares for all values in data array const sums = []; const sumsOfSquares = []; // Initialize first column in matrix & backtrackMatrix for (let i = 0, shiftedValue; i < nValues; ++i) { shiftedValue = data[i] - shift; if (i === 0) { sums.push(shiftedValue); sumsOfSquares.push(shiftedValue * shiftedValue); } else { sums.push(sums[i - 1] + shiftedValue); sumsOfSquares.push( sumsOfSquares[i - 1] + shiftedValue * shiftedValue ); } // Initialize for cluster = 0 matrix[0][i] = ssq(0, i, sums, sumsOfSquares); backtrackMatrix[0][i] = 0; } // Initialize the rest of the columns let iMin; for (let cluster = 1; cluster < matrix.length; ++cluster) { if (cluster < matrix.length - 1) { iMin = cluster; } else { // No need to compute matrix[K-1][0] ... matrix[K-1][N-2] iMin = nValues - 1; } fillMatrixColumn( iMin, nValues - 1, cluster, matrix, backtrackMatrix, sums, sumsOfSquares ); } } /** * Ckmeans clustering is an improvement on heuristic-based clustering * approaches like Jenks. The algorithm was developed in * [Haizhou Wang and Mingzhou Song](http://journal.r-project.org/archive/2011-2/RJournal_2011-2_Wang+Song.pdf) * as a [dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming) approach * to the problem of clustering numeric data into groups with the least * within-group sum-of-squared-deviations. * * Minimizing the difference within groups - what Wang & Song refer to as * `withinss`, or within sum-of-squares, means that groups are optimally * homogenous within and the data is split into representative groups. * This is very useful for visualization, where you may want to represent * a continuous variable in discrete color or style groups. This function * can provide groups that emphasize differences between data. * * Being a dynamic approach, this algorithm is based on two matrices that * store incrementally-computed values for squared deviations and backtracking * indexes. * * This implementation is based on Ckmeans 3.4.6, which introduced a new divide * and conquer approach that improved runtime from O(kn^2) to O(kn log(n)). * * Unlike the [original implementation](https://cran.r-project.org/web/packages/Ckmeans.1d.dp/index.html), * this implementation does not include any code to automatically determine * the optimal number of clusters: this information needs to be explicitly * provided. * * ### References * _Ckmeans.1d.dp: Optimal k-means Clustering in One Dimension by Dynamic * Programming_ Haizhou Wang and Mingzhou Song ISSN 2073-4859 * * from The R Journal Vol. 3/2, December 2011 * @param {Array} x input data, as an array of number values * @param {number} nClusters number of desired classes. This cannot be * greater than the number of values in the data array. * @returns {Array>} clustered input * @throws {Error} if the number of requested clusters is higher than the size of the data * @example * ckmeans([-1, 2, -1, 2, 4, 5, 6, -1, 2, -1], 3); * // The input, clustered into groups of similar numbers. * //= [[-1, -1, -1, -1], [2, 2, 2], [4, 5, 6]]); */ function ckmeans(x, nClusters) { if (nClusters > x.length) { throw new Error( ""cannot generate more classes than there are data values"" ); } const sorted = numericSort(x); // we'll use this as the maximum number of clusters const uniqueCount = uniqueCountSorted(sorted); // if all of the input values are identical, there's one cluster // with all of the input in it. if (uniqueCount === 1) { return [sorted]; } // named 'S' originally const matrix = makeMatrix(nClusters, sorted.length); // named 'J' originally const backtrackMatrix = makeMatrix(nClusters, sorted.length); // This is a dynamic programming way to solve the problem of minimizing // within-cluster sum of squares. It's similar to linear regression // in this way, and this calculation incrementally computes the // sum of squares that are later read. fillMatrices(sorted, matrix, backtrackMatrix); // The real work of Ckmeans clustering happens in the matrix generation: // the generated matrices encode all possible clustering combinations, and // once they're generated we can solve for the best clustering groups // very quickly. const clusters = []; let clusterRight = backtrackMatrix[0].length - 1; // Backtrack the clusters from the dynamic programming matrix. This // starts at the bottom-right corner of the matrix (if the top-left is 0, 0), // and moves the cluster target with the loop. for (let cluster = backtrackMatrix.length - 1; cluster >= 0; cluster--) { const clusterLeft = backtrackMatrix[cluster][clusterRight]; // fill the cluster from the sorted input by taking a slice of the // array. the backtrack matrix makes this easy - it stores the // indexes where the cluster should start and end. clusters[cluster] = sorted.slice(clusterLeft, clusterRight + 1); if (cluster > 0) { clusterRight = clusterLeft - 1; } } return clusters; } export default ckmeans; // ckmeans/unique_count_sorted.js /** * For a sorted input, counting the number of unique values * is possible in constant time and constant memory. This is * a simple implementation of the algorithm. * * Values are compared with `===`, so objects and non-primitive objects * are not handled in any special way. * * @param {Array<*>} x an array of any kind of value * @returns {number} count of unique values * @example * uniqueCountSorted([1, 2, 3]); // => 3 * uniqueCountSorted([1, 1, 1]); // => 1 */ function uniqueCountSorted(x) { let uniqueValueCount = 0; let lastSeenValue; for (let i = 0; i < x.length; i++) { if (i === 0 || x[i] !== lastSeenValue) { lastSeenValue = x[i]; uniqueValueCount++; } } return uniqueValueCount; } export default uniqueCountSorted; // ckmeans/make_matrix.js /** * Create a new column x row matrix. * * @private * @param {number} columns * @param {number} rows * @return {Array>} matrix * @example * makeMatrix(10, 10); */ function makeMatrix(columns, rows) { const matrix = []; for (let i = 0; i < columns; i++) { const column = []; for (let j = 0; j < rows; j++) { column.push(0); } matrix.push(column); } return matrix; } export default makeMatrix; ",4,364,JavaScript validate,./ProjectTest/JavaScript/validate.js,"// validate/map.js // We use a global `WeakMap` to store class-specific information (such as // options) instead of storing it as a symbol property on each error class to // ensure: // - This is not exposed to users or plugin authors // - This does not change how the error class is printed // We use a `WeakMap` instead of an object since the key should be the error // class, not its `name`, because classes might have duplicate names. export const classesData = new WeakMap() // The same but for error instances export const instancesData = new WeakMap() // validate/validate.js import { classesData } from './map.js' // We forbid subclasses that are not known, i.e. not passed to // `ErrorClass.subclass()` // - They would not be validated at load time // - The class would not be normalized until its first instantiation // - E.g. its `prototype.name` might be missing // - The list of `ErrorClasses` would be potentially incomplete // - E.g. `ErrorClass.parse()` would not be able to parse an error class // until its first instantiation // This usually happens if a class was: // - Not passed to the `custom` option of `*Error.subclass()` // - But was extended from a known class export const validateSubclass = (ErrorClass) => { if (classesData.has(ErrorClass)) { return } const { name } = ErrorClass const { name: parentName } = Object.getPrototypeOf(ErrorClass) throw new Error( `""new ${name}()"" must not be directly called. This error class should be created like this instead: export const ${name} = ${parentName}.subclass('${name}')`, ) } ",2,37,JavaScript convex,./ProjectTest/JavaScript/convex.js,"// convex/Convex.js var Shape = require('./Shape') , vec2 = require('./math/vec2') , dot = vec2.dot , polyk = require('./math/polyk') , shallowClone = require('./Utils').shallowClone; module.exports = Convex; /** * Convex shape class. * @class Convex * @constructor * @extends Shape * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink ""Shape""}}{{/crossLink}} constructor.) * @param {Array} [options.vertices] An array of vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction. * @example * var body = new Body({ mass: 1 }); * var vertices = [[-1,-1], [1,-1], [1,1], [-1,1]]; * var convexShape = new Convex({ * vertices: vertices * }); * body.addShape(convexShape); */ function Convex(options){ options = options ? shallowClone(options) : {}; /** * Vertices defined in the local frame. * @property vertices * @type {Array} */ this.vertices = []; // Copy the verts var vertices = options.vertices !== undefined ? options.vertices : []; for(var i=0; i < vertices.length; i++){ this.vertices.push(vec2.clone(vertices[i])); } /** * Edge normals defined in the local frame, pointing out of the shape. * @property normals * @type {Array} */ var normals = this.normals = []; for(var i=0; i < vertices.length; i++){ normals.push(vec2.create()); } this.updateNormals(); /** * The center of mass of the Convex * @property centerOfMass * @type {Array} */ this.centerOfMass = vec2.create(); /** * Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices. * @property triangles * @type {Array} */ this.triangles = []; if(this.vertices.length){ this.updateTriangles(); this.updateCenterOfMass(); } /** * The bounding radius of the convex * @property boundingRadius * @type {Number} */ this.boundingRadius = 0; options.type = options.type || Shape.CONVEX; Shape.call(this, options); this.updateBoundingRadius(); this.updateArea(); if(this.area < 0){ throw new Error(""Convex vertices must be given in counter-clockwise winding.""); } } Convex.prototype = new Shape(); Convex.prototype.constructor = Convex; var tmpVec1 = vec2.create(); var tmpVec2 = vec2.create(); Convex.prototype.updateNormals = function(){ var vertices = this.vertices; var normals = this.normals; for(var i = 0; i < vertices.length; i++){ var worldPoint0 = vertices[i]; var worldPoint1 = vertices[(i+1) % vertices.length]; var normal = normals[i]; vec2.subtract(normal, worldPoint1, worldPoint0); // Get normal - just rotate 90 degrees since vertices are given in CCW vec2.rotate90cw(normal, normal); vec2.normalize(normal, normal); } }; /** * Project a Convex onto a world-oriented axis * @method projectOntoAxis * @static * @param {Array} offset * @param {Array} localAxis * @param {Array} result */ Convex.prototype.projectOntoLocalAxis = function(localAxis, result){ var max=null, min=null, v, value, localAxis = tmpVec1; // Get projected position of all vertices for(var i=0; i max){ max = value; } if(min === null || value < min){ min = value; } } if(min > max){ var t = min; min = max; max = t; } vec2.set(result, min, max); }; Convex.prototype.projectOntoWorldAxis = function(localAxis, shapeOffset, shapeAngle, result){ var worldAxis = tmpVec2; this.projectOntoLocalAxis(localAxis, result); // Project the position of the body onto the axis - need to add this to the result if(shapeAngle !== 0){ vec2.rotate(worldAxis, localAxis, shapeAngle); } else { worldAxis = localAxis; } var offset = dot(shapeOffset, worldAxis); vec2.set(result, result[0] + offset, result[1] + offset); }; /** * Update the .triangles property * @method updateTriangles */ Convex.prototype.updateTriangles = function(){ this.triangles.length = 0; // Rewrite on polyk notation, array of numbers var polykVerts = []; for(var i=0; i r2){ r2 = l2; } } this.boundingRadius = Math.sqrt(r2); }; /** * Get the area of the triangle spanned by the three points a, b, c. The area is positive if the points are given in counter-clockwise order, otherwise negative. * @static * @method triangleArea * @param {Array} a * @param {Array} b * @param {Array} c * @return {Number} * @deprecated */ Convex.triangleArea = triangleArea; function triangleArea(a,b,c){ return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))) * 0.5; } /** * Update the .area * @method updateArea */ Convex.prototype.updateArea = function(){ this.updateTriangles(); this.area = 0; var triangles = this.triangles, verts = this.vertices; for(var i=0; i!==triangles.length; i++){ var t = triangles[i], a = verts[t[0]], b = verts[t[1]], c = verts[t[2]]; // Get mass for the triangle (density=1 in this case) var m = triangleArea(a,b,c); this.area += m; } }; /** * @method computeAABB * @param {AABB} out * @param {Array} position * @param {Number} angle * @todo: approximate with a local AABB? */ Convex.prototype.computeAABB = function(out, position, angle){ out.setFromPoints(this.vertices, position, angle, 0); }; var intersectConvex_rayStart = vec2.create(); var intersectConvex_rayEnd = vec2.create(); var intersectConvex_normal = vec2.create(); /** * @method raycast * @param {RaycastResult} result * @param {Ray} ray * @param {array} position * @param {number} angle */ Convex.prototype.raycast = function(result, ray, position, angle){ var rayStart = intersectConvex_rayStart; var rayEnd = intersectConvex_rayEnd; var normal = intersectConvex_normal; var vertices = this.vertices; // Transform to local shape space vec2.toLocalFrame(rayStart, ray.from, position, angle); vec2.toLocalFrame(rayEnd, ray.to, position, angle); var n = vertices.length; for (var i = 0; i < n && !result.shouldStop(ray); i++) { var q1 = vertices[i]; var q2 = vertices[(i+1) % n]; var delta = vec2.getLineSegmentsIntersectionFraction(rayStart, rayEnd, q1, q2); if(delta >= 0){ vec2.subtract(normal, q2, q1); vec2.rotate(normal, normal, -Math.PI / 2 + angle); vec2.normalize(normal, normal); ray.reportIntersection(result, delta, normal, i); } } }; var pic_r0 = vec2.create(); var pic_r1 = vec2.create(); Convex.prototype.pointTest = function(localPoint){ var r0 = pic_r0, r1 = pic_r1, verts = this.vertices, lastCross = null, numVerts = verts.length; for(var i=0; i < numVerts + 1; i++){ var v0 = verts[i % numVerts], v1 = verts[(i + 1) % numVerts]; vec2.subtract(r0, v0, localPoint); vec2.subtract(r1, v1, localPoint); var cross = vec2.crossLength(r0,r1); if(lastCross === null){ lastCross = cross; } // If we got a different sign of the distance vector, the point is out of the polygon if(cross * lastCross < 0){ return false; } lastCross = cross; } return true; }; // convex/math/vec2.js /* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net. * @class vec2 */ var vec2 = module.exports = {}; var Utils = require('../Utils'); /** * Make a cross product and only return the z component * @method crossLength * @static * @param {Array} a * @param {Array} b * @return {Number} */ vec2.crossLength = function(a,b){ return a[0] * b[1] - a[1] * b[0]; }; /** * Cross product between a vector and the Z component of a vector * @method crossVZ * @static * @param {Array} out * @param {Array} vec * @param {Number} zcomp * @return {Array} */ vec2.crossVZ = function(out, vec, zcomp){ vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule vec2.scale(out,out,zcomp); // Scale with z return out; }; /** * Cross product between a vector and the Z component of a vector * @method crossZV * @static * @param {Array} out * @param {Number} zcomp * @param {Array} vec * @return {Array} */ vec2.crossZV = function(out, zcomp, vec){ vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule vec2.scale(out,out,zcomp); // Scale with z return out; }; /** * Rotate a vector by an angle * @method rotate * @static * @param {Array} out * @param {Array} a * @param {Number} angle * @return {Array} */ vec2.rotate = function(out,a,angle){ if(angle !== 0){ var c = Math.cos(angle), s = Math.sin(angle), x = a[0], y = a[1]; out[0] = c*x -s*y; out[1] = s*x +c*y; } else { out[0] = a[0]; out[1] = a[1]; } return out; }; /** * Rotate a vector 90 degrees clockwise * @method rotate90cw * @static * @param {Array} out * @param {Array} a * @param {Number} angle * @return {Array} */ vec2.rotate90cw = function(out, a) { var x = a[0]; var y = a[1]; out[0] = y; out[1] = -x; return out; }; /** * Transform a point position to local frame. * @method toLocalFrame * @param {Array} out * @param {Array} worldPoint * @param {Array} framePosition * @param {Number} frameAngle * @return {Array} */ vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){ var c = Math.cos(-frameAngle), s = Math.sin(-frameAngle), x = worldPoint[0] - framePosition[0], y = worldPoint[1] - framePosition[1]; out[0] = c * x - s * y; out[1] = s * x + c * y; return out; }; /** * Transform a point position to global frame. * @method toGlobalFrame * @param {Array} out * @param {Array} localPoint * @param {Array} framePosition * @param {Number} frameAngle */ vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){ var c = Math.cos(frameAngle), s = Math.sin(frameAngle), x = localPoint[0], y = localPoint[1], addX = framePosition[0], addY = framePosition[1]; out[0] = c * x - s * y + addX; out[1] = s * x + c * y + addY; }; /** * Transform a vector to local frame. * @method vectorToLocalFrame * @param {Array} out * @param {Array} worldVector * @param {Number} frameAngle * @return {Array} */ vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){ var c = Math.cos(-frameAngle), s = Math.sin(-frameAngle), x = worldVector[0], y = worldVector[1]; out[0] = c*x -s*y; out[1] = s*x +c*y; return out; }; /** * Transform a vector to global frame. * @method vectorToGlobalFrame * @param {Array} out * @param {Array} localVector * @param {Number} frameAngle */ vec2.vectorToGlobalFrame = vec2.rotate; /** * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php * @method centroid * @static * @param {Array} out * @param {Array} a * @param {Array} b * @param {Array} c * @return {Array} The ""out"" vector. */ vec2.centroid = function(out, a, b, c){ vec2.add(out, a, b); vec2.add(out, out, c); vec2.scale(out, out, 1/3); return out; }; /** * Creates a new, empty vec2 * @static * @method create * @return {Array} a new 2D vector */ vec2.create = function() { var out = new Utils.ARRAY_TYPE(2); out[0] = 0; out[1] = 0; return out; }; /** * Creates a new vec2 initialized with values from an existing vector * @static * @method clone * @param {Array} a vector to clone * @return {Array} a new 2D vector */ vec2.clone = function(a) { var out = new Utils.ARRAY_TYPE(2); out[0] = a[0]; out[1] = a[1]; return out; }; /** * Creates a new vec2 initialized with the given values * @static * @method fromValues * @param {Number} x X component * @param {Number} y Y component * @return {Array} a new 2D vector */ vec2.fromValues = function(x, y) { var out = new Utils.ARRAY_TYPE(2); out[0] = x; out[1] = y; return out; }; /** * Copy the values from one vec2 to another * @static * @method copy * @param {Array} out the receiving vector * @param {Array} a the source vector * @return {Array} out */ vec2.copy = function(out, a) { out[0] = a[0]; out[1] = a[1]; return out; }; /** * Set the components of a vec2 to the given values * @static * @method set * @param {Array} out the receiving vector * @param {Number} x X component * @param {Number} y Y component * @return {Array} out */ vec2.set = function(out, x, y) { out[0] = x; out[1] = y; return out; }; /** * Adds two vec2's * @static * @method add * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.add = function(out, a, b) { out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; return out; }; /** * Subtracts two vec2's * @static * @method subtract * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.subtract = function(out, a, b) { out[0] = a[0] - b[0]; out[1] = a[1] - b[1]; return out; }; /** * Multiplies two vec2's * @static * @method multiply * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.multiply = function(out, a, b) { out[0] = a[0] * b[0]; out[1] = a[1] * b[1]; return out; }; /** * Divides two vec2's * @static * @method divide * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.divide = function(out, a, b) { out[0] = a[0] / b[0]; out[1] = a[1] / b[1]; return out; }; /** * Scales a vec2 by a scalar number * @static * @method scale * @param {Array} out the receiving vector * @param {Array} a the vector to scale * @param {Number} b amount to scale the vector by * @return {Array} out */ vec2.scale = function(out, a, b) { out[0] = a[0] * b; out[1] = a[1] * b; return out; }; /** * Calculates the euclidian distance between two vec2's * @static * @method distance * @param {Array} a the first operand * @param {Array} b the second operand * @return {Number} distance between a and b */ vec2.distance = function(a, b) { var x = b[0] - a[0], y = b[1] - a[1]; return Math.sqrt(x*x + y*y); }; /** * Calculates the squared euclidian distance between two vec2's * @static * @method squaredDistance * @param {Array} a the first operand * @param {Array} b the second operand * @return {Number} squared distance between a and b */ vec2.squaredDistance = function(a, b) { var x = b[0] - a[0], y = b[1] - a[1]; return x*x + y*y; }; /** * Calculates the length of a vec2 * @static * @method length * @param {Array} a vector to calculate length of * @return {Number} length of a */ vec2.length = function (a) { var x = a[0], y = a[1]; return Math.sqrt(x*x + y*y); }; /** * Calculates the squared length of a vec2 * @static * @method squaredLength * @param {Array} a vector to calculate squared length of * @return {Number} squared length of a */ vec2.squaredLength = function (a) { var x = a[0], y = a[1]; return x*x + y*y; }; /** * Negates the components of a vec2 * @static * @method negate * @param {Array} out the receiving vector * @param {Array} a vector to negate * @return {Array} out */ vec2.negate = function(out, a) { out[0] = -a[0]; out[1] = -a[1]; return out; }; /** * Normalize a vec2 * @static * @method normalize * @param {Array} out the receiving vector * @param {Array} a vector to normalize * @return {Array} out */ vec2.normalize = function(out, a) { var x = a[0], y = a[1]; var len = x*x + y*y; if (len > 0) { //TODO: evaluate use of glm_invsqrt here? len = 1 / Math.sqrt(len); out[0] = a[0] * len; out[1] = a[1] * len; } return out; }; /** * Calculates the dot product of two vec2's * @static * @method dot * @param {Array} a the first operand * @param {Array} b the second operand * @return {Number} dot product of a and b */ vec2.dot = function (a, b) { return a[0] * b[0] + a[1] * b[1]; }; /** * Returns a string representation of a vector * @static * @method str * @param {Array} vec vector to represent as a string * @return {String} string representation of the vector */ vec2.str = function (a) { return 'vec2(' + a[0] + ', ' + a[1] + ')'; }; /** * Linearly interpolate/mix two vectors. * @static * @method lerp * @param {Array} out * @param {Array} a First vector * @param {Array} b Second vector * @param {number} t Lerp factor */ vec2.lerp = function (out, a, b, t) { var ax = a[0], ay = a[1]; out[0] = ax + t * (b[0] - ax); out[1] = ay + t * (b[1] - ay); return out; }; /** * Reflect a vector along a normal. * @static * @method reflect * @param {Array} out * @param {Array} vector * @param {Array} normal */ vec2.reflect = function(out, vector, normal){ var dot = vector[0] * normal[0] + vector[1] * normal[1]; out[0] = vector[0] - 2 * normal[0] * dot; out[1] = vector[1] - 2 * normal[1] * dot; }; /** * Get the intersection point between two line segments. * @static * @method getLineSegmentsIntersection * @param {Array} out * @param {Array} p0 * @param {Array} p1 * @param {Array} p2 * @param {Array} p3 * @return {boolean} True if there was an intersection, otherwise false. */ vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) { var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3); if(t < 0){ return false; } else { out[0] = p0[0] + (t * (p1[0] - p0[0])); out[1] = p0[1] + (t * (p1[1] - p0[1])); return true; } }; /** * Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0) * @static * @method getLineSegmentsIntersectionFraction * @param {Array} p0 * @param {Array} p1 * @param {Array} p2 * @param {Array} p3 * @return {number} A number between 0 and 1 if there was an intersection, otherwise -1. */ vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) { var s1_x = p1[0] - p0[0]; var s1_y = p1[1] - p0[1]; var s2_x = p3[0] - p2[0]; var s2_y = p3[1] - p2[1]; var s, t; s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y); t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y); if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected return t; } return -1; // No collision }; // convex/math/polyk.js /* PolyK library url: http://polyk.ivank.net Released under MIT licence. Copyright (c) 2012 Ivan Kuckir Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var PolyK = {}; /* Is Polygon self-intersecting? O(n^2) */ /* PolyK.IsSimple = function(p) { var n = p.length>>1; if(n<4) return true; var a1 = new PolyK._P(), a2 = new PolyK._P(); var b1 = new PolyK._P(), b2 = new PolyK._P(); var c = new PolyK._P(); for(var i=0; i>1; if(n<3) return []; var tgs = []; var avl = []; for(var i=0; i 3) { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; var ax = p[2*i0], ay = p[2*i0+1]; var bx = p[2*i1], by = p[2*i1+1]; var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; if(PolyK._convex(ax, ay, bx, by, cx, cy)) { earFound = true; for(var j=0; j 3*al) break; // no convex angles :( } tgs.push(avl[0], avl[1], avl[2]); return tgs; } /* PolyK.ContainsPoint = function(p, px, py) { var n = p.length>>1; var ax, ay, bx = p[2*n-2]-px, by = p[2*n-1]-py; var depth = 0; for(var i=0; i=0 && by>=0) continue; // both ""up"" or both ""donw"" if(ax< 0 && bx< 0) continue; var lx = ax + (bx-ax)*(-ay)/(by-ay); if(lx>0) depth++; } return (depth & 1) == 1; } PolyK.Slice = function(p, ax, ay, bx, by) { if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)]; var a = new PolyK._P(ax, ay); var b = new PolyK._P(bx, by); var iscs = []; // intersections var ps = []; // points for(var i=0; i 0) { var n = ps.length; var i0 = iscs[0]; var i1 = iscs[1]; var ind0 = ps.indexOf(i0); var ind1 = ps.indexOf(i1); var solved = false; if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; else { i0 = iscs[1]; i1 = iscs[0]; ind0 = ps.indexOf(i0); ind1 = ps.indexOf(i1); if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; } if(solved) { dir--; var pgn = PolyK._getPoints(ps, ind0, ind1); pgs.push(pgn); ps = PolyK._getPoints(ps, ind1, ind0); i0.flag = i1.flag = false; iscs.splice(0,2); if(iscs.length == 0) pgs.push(ps); } else { dir++; iscs.reverse(); } if(dir>1) break; } var result = []; for(var i=0; i>1, isc); } b1.x = b2.x; b1.y = b2.y; b2.x = p[0]; b2.y = p[1]; PolyK._pointLineDist(a1, b1, b2, l>>1, isc); var idst = 1/isc.dist; isc.norm.x = (x-isc.point.x)*idst; isc.norm.y = (y-isc.point.y)*idst; return isc; } PolyK._pointLineDist = function(p, a, b, edge, isc) { var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y; var A = x - x1; var B = y - y1; var C = x2 - x1; var D = y2 - y1; var dot = A * C + B * D; var len_sq = C * C + D * D; var param = dot / len_sq; var xx, yy; if (param < 0 || (x1 == x2 && y1 == y2)) { xx = x1; yy = y1; } else if (param > 1) { xx = x2; yy = y2; } else { xx = x1 + param * C; yy = y1 + param * D; } var dx = x - xx; var dy = y - yy; var dst = Math.sqrt(dx * dx + dy * dy); if(dst= 0) && (v >= 0) && (u + v < 1); } /* PolyK._RayLineIntersection = function(a1, a2, b1, b2, c) { var dax = (a1.x-a2.x), dbx = (b1.x-b2.x); var day = (a1.y-a2.y), dby = (b1.y-b2.y); var Den = dax*dby - day*dbx; if (Den == 0) return null; // parallel var A = (a1.x * a2.y - a1.y * a2.x); var B = (b1.x * b2.y - b1.y * b2.x); var I = c; var iDen = 1/Den; I.x = ( A*dbx - dax*B ) * iDen; I.y = ( A*dby - day*B ) * iDen; if(!PolyK._InRect(I, b1, b2)) return null; if((day>0 && I.y>a1.y) || (day<0 && I.y0 && I.x>a1.x) || (dax<0 && I.x=Math.min(b.y, c.y) && a.y<=Math.max(b.y, c.y)); if (b.y == c.y) return (a.x>=Math.min(b.x, c.x) && a.x<=Math.max(b.x, c.x)); if(a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x) && a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y)) return true; return false; } */ PolyK._convex = function(ax, ay, bx, by, cx, cy) { return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0; } /* PolyK._P = function(x,y) { this.x = x; this.y = y; this.flag = false; } PolyK._P.prototype.toString = function() { return ""Point [""+this.x+"", ""+this.y+""]""; } PolyK._P.dist = function(a,b) { var dx = b.x-a.x; var dy = b.y-a.y; return Math.sqrt(dx*dx + dy*dy); } PolyK._tp = []; for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0)); */ module.exports = PolyK; // convex/Line.js var Shape = require('./Shape') , shallowClone = require('./Utils').shallowClone , vec2 = require('./math/vec2'); module.exports = Line; /** * Line shape class. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. * @class Line * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink ""Shape""}}{{/crossLink}} constructor.) * @param {Number} [options.length=1] The total length of the line * @extends Shape * @constructor * @example * var body = new Body(); * var lineShape = new Line({ * length: 1 * }); * body.addShape(lineShape); */ function Line(options){ options = options ? shallowClone(options) : {}; /** * Length of this line * @property {Number} length * @default 1 */ this.length = options.length !== undefined ? options.length : 1; options.type = Shape.LINE; Shape.call(this, options); } Line.prototype = new Shape(); Line.prototype.constructor = Line; Line.prototype.computeMomentOfInertia = function(){ return Math.pow(this.length,2) / 12; }; Line.prototype.updateBoundingRadius = function(){ this.boundingRadius = this.length/2; }; var points = [vec2.create(),vec2.create()]; /** * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Line.prototype.computeAABB = function(out, position, angle){ var l2 = this.length / 2; vec2.set(points[0], -l2, 0); vec2.set(points[1], l2, 0); out.setFromPoints(points,position,angle,0); }; var raycast_normal = vec2.create(); var raycast_l0 = vec2.create(); var raycast_l1 = vec2.create(); var raycast_unit_y = vec2.fromValues(0,1); /** * @method raycast * @param {RaycastResult} result * @param {Ray} ray * @param {number} angle * @param {array} position */ Line.prototype.raycast = function(result, ray, position, angle){ var from = ray.from; var to = ray.to; var l0 = raycast_l0; var l1 = raycast_l1; // get start and end of the line var halfLen = this.length / 2; vec2.set(l0, -halfLen, 0); vec2.set(l1, halfLen, 0); vec2.toGlobalFrame(l0, l0, position, angle); vec2.toGlobalFrame(l1, l1, position, angle); var fraction = vec2.getLineSegmentsIntersectionFraction(l0, l1, from, to); if(fraction >= 0){ var normal = raycast_normal; vec2.rotate(normal, raycast_unit_y, angle); // todo: this should depend on which side the ray comes from ray.reportIntersection(result, fraction, normal, -1); } }; // convex/Utils.js /* global P2_ARRAY_TYPE */ module.exports = Utils; /** * Misc utility functions * @class Utils * @constructor */ function Utils(){} /** * Append the values in array b to the array a. See this for an explanation. * @method appendArray * @static * @param {Array} a * @param {Array} b */ Utils.appendArray = function(a,b){ if (b.length < 150000) { a.push.apply(a, b); } else { for (var i = 0, len = b.length; i !== len; ++i) { a.push(b[i]); } } }; /** * Garbage free Array.splice(). Does not allocate a new array. * @method splice * @static * @param {Array} array * @param {Number} index * @param {Number} howmany */ Utils.splice = function(array,index,howmany){ howmany = howmany || 1; for (var i=index, len=array.length-howmany; i < len; i++){ array[i] = array[i + howmany]; } array.length = len; }; /** * Remove an element from an array, if the array contains the element. * @method arrayRemove * @static * @param {Array} array * @param {Number} element */ Utils.arrayRemove = function(array, element){ var idx = array.indexOf(element); if(idx!==-1){ Utils.splice(array, idx, 1); } }; /** * The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below. * @static * @property {function} ARRAY_TYPE * @example * * */ if(typeof P2_ARRAY_TYPE !== 'undefined') { Utils.ARRAY_TYPE = P2_ARRAY_TYPE; } else if (typeof Float32Array !== 'undefined'){ Utils.ARRAY_TYPE = Float32Array; } else { Utils.ARRAY_TYPE = Array; } /** * Extend an object with the properties of another * @static * @method extend * @param {object} a * @param {object} b */ Utils.extend = function(a,b){ for(var key in b){ a[key] = b[key]; } }; /** * Shallow clone an object. Returns a new object instance with the same properties as the input instance. * @static * @method shallowClone * @param {object} obj */ Utils.shallowClone = function(obj){ var newObj = {}; Utils.extend(newObj, obj); return newObj; }; /** * Extend an options object with default values. * @deprecated Not used internally, will be removed. * @static * @method defaults * @param {object} options The options object. May be falsy: in this case, a new object is created and returned. * @param {object} defaults An object containing default values. * @return {object} The modified options object. */ Utils.defaults = function(options, defaults){ console.warn('Utils.defaults is deprecated.'); options = options || {}; for(var key in defaults){ if(!(key in options)){ options[key] = defaults[key]; } } return options; }; // convex/Shape.js module.exports = Shape; var vec2 = require('./math/vec2'); /** * Base class for shapes. Not to be used directly. * @class Shape * @constructor * @param {object} [options] * @param {number} [options.angle=0] * @param {number} [options.collisionGroup=1] * @param {number} [options.collisionMask=1] * @param {boolean} [options.collisionResponse=true] * @param {Material} [options.material=null] * @param {array} [options.position] * @param {boolean} [options.sensor=false] * @param {object} [options.type=0] */ function Shape(options){ options = options || {}; /** * The body this shape is attached to. A shape can only be attached to a single body. * @property {Body} body */ this.body = null; /** * Body-local position of the shape. * @property {Array} position */ this.position = vec2.create(); if(options.position){ vec2.copy(this.position, options.position); } /** * Body-local angle of the shape. * @property {number} angle */ this.angle = options.angle || 0; /** * The type of the shape. One of: * * * * @property {number} type */ this.type = options.type || 0; /** * Shape object identifier. Read only. * @readonly * @type {Number} * @property id */ this.id = Shape.idCounter++; /** * Bounding circle radius of this shape * @readonly * @property boundingRadius * @type {Number} */ this.boundingRadius = 0; /** * Collision group that this shape belongs to (bit mask). See this tutorial. * @property collisionGroup * @type {Number} * @example * // Setup bits for each available group * var PLAYER = Math.pow(2,0), * ENEMY = Math.pow(2,1), * GROUND = Math.pow(2,2) * * // Put shapes into their groups * player1Shape.collisionGroup = PLAYER; * player2Shape.collisionGroup = PLAYER; * enemyShape .collisionGroup = ENEMY; * groundShape .collisionGroup = GROUND; * * // Assign groups that each shape collide with. * // Note that the players can collide with ground and enemies, but not with other players. * player1Shape.collisionMask = ENEMY | GROUND; * player2Shape.collisionMask = ENEMY | GROUND; * enemyShape .collisionMask = PLAYER | GROUND; * groundShape .collisionMask = PLAYER | ENEMY; * * @example * // How collision check is done * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){ * // The shapes will collide * } */ this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1; /** * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc. * @property {Boolean} collisionResponse */ this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true; /** * Collision mask of this shape. See .collisionGroup. * @property collisionMask * @type {Number} */ this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1; /** * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead. * @property material * @type {Material} */ this.material = options.material || null; /** * Area of this shape. * @property area * @type {Number} */ this.area = 0; /** * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts. * @property {Boolean} sensor */ this.sensor = options.sensor !== undefined ? options.sensor : false; if(this.type){ this.updateBoundingRadius(); } this.updateArea(); } Shape.idCounter = 0; /** * @static * @property {Number} CIRCLE */ Shape.CIRCLE = 1; /** * @static * @property {Number} PARTICLE */ Shape.PARTICLE = 2; /** * @static * @property {Number} PLANE */ Shape.PLANE = 4; /** * @static * @property {Number} CONVEX */ Shape.CONVEX = 8; /** * @static * @property {Number} LINE */ Shape.LINE = 16; /** * @static * @property {Number} BOX */ Shape.BOX = 32; /** * @static * @property {Number} CAPSULE */ Shape.CAPSULE = 64; /** * @static * @property {Number} HEIGHTFIELD */ Shape.HEIGHTFIELD = 128; Shape.prototype = { /** * Should return the moment of inertia around the Z axis of the body. See Wikipedia's list of moments of inertia. * @method computeMomentOfInertia * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0. */ computeMomentOfInertia: function(){}, /** * Returns the bounding circle radius of this shape. * @method updateBoundingRadius * @return {Number} */ updateBoundingRadius: function(){}, /** * Update the .area property of the shape. * @method updateArea */ updateArea: function(){}, /** * Compute the world axis-aligned bounding box (AABB) of this shape. * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position World position of the shape. * @param {Number} angle World angle of the shape. */ computeAABB: function(/*out, position, angle*/){ // To be implemented in each subclass }, /** * Perform raycasting on this shape. * @method raycast * @param {RayResult} result Where to store the resulting data. * @param {Ray} ray The Ray that you want to use for raycasting. * @param {array} position World position of the shape (the .position property will be ignored). * @param {number} angle World angle of the shape (the .angle property will be ignored). */ raycast: function(/*result, ray, position, angle*/){ // To be implemented in each subclass }, /** * Test if a point is inside this shape. * @method pointTest * @param {array} localPoint * @return {boolean} */ pointTest: function(/*localPoint*/){ return false; }, /** * Transform a world point to local shape space (assumed the shape is transformed by both itself and the body). * @method worldPointToLocal * @param {array} out * @param {array} worldPoint */ worldPointToLocal: (function () { var shapeWorldPosition = vec2.create(); return function (out, worldPoint) { var body = this.body; vec2.rotate(shapeWorldPosition, this.position, body.angle); vec2.add(shapeWorldPosition, shapeWorldPosition, body.position); vec2.toLocalFrame(out, worldPoint, shapeWorldPosition, this.body.angle + this.angle); }; })() }; ",6,1878,JavaScript spherical,./ProjectTest/JavaScript/spherical.js,"// spherical/MathUtils.js const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ]; let _seed = 1234567; const DEG2RAD = Math.PI / 180; const RAD2DEG = 180 / Math.PI; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136 function generateUUID() { const d0 = Math.random() * 0xffffffff | 0; const d1 = Math.random() * 0xffffffff | 0; const d2 = Math.random() * 0xffffffff | 0; const d3 = Math.random() * 0xffffffff | 0; const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' + _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' + _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] + _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ]; // .toLowerCase() here flattens concatenated strings to save heap memory space. return uuid.toLowerCase(); } function clamp( value, min, max ) { return Math.max( min, Math.min( max, value ) ); } // compute euclidean modulo of m % n // https://en.wikipedia.org/wiki/Modulo_operation function euclideanModulo( n, m ) { return ( ( n % m ) + m ) % m; } // Linear mapping from range to range function mapLinear( x, a1, a2, b1, b2 ) { return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); } // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/ function inverseLerp( x, y, value ) { if ( x !== y ) { return ( value - x ) / ( y - x ); } else { return 0; } } // https://en.wikipedia.org/wiki/Linear_interpolation function lerp( x, y, t ) { return ( 1 - t ) * x + t * y; } // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/ function damp( x, y, lambda, dt ) { return lerp( x, y, 1 - Math.exp( - lambda * dt ) ); } // https://www.desmos.com/calculator/vcsjnyz7x4 function pingpong( x, length = 1 ) { return length - Math.abs( euclideanModulo( x, length * 2 ) - length ); } // http://en.wikipedia.org/wiki/Smoothstep function smoothstep( x, min, max ) { if ( x <= min ) return 0; if ( x >= max ) return 1; x = ( x - min ) / ( max - min ); return x * x * ( 3 - 2 * x ); } function smootherstep( x, min, max ) { if ( x <= min ) return 0; if ( x >= max ) return 1; x = ( x - min ) / ( max - min ); return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); } // Random integer from interval function randInt( low, high ) { return low + Math.floor( Math.random() * ( high - low + 1 ) ); } // Random float from interval function randFloat( low, high ) { return low + Math.random() * ( high - low ); } // Random float from <-range/2, range/2> interval function randFloatSpread( range ) { return range * ( 0.5 - Math.random() ); } // Deterministic pseudo-random float in the interval [ 0, 1 ] function seededRandom( s ) { if ( s !== undefined ) _seed = s; // Mulberry32 generator let t = _seed += 0x6D2B79F5; t = Math.imul( t ^ t >>> 15, t | 1 ); t ^= t + Math.imul( t ^ t >>> 7, t | 61 ); return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296; } function degToRad( degrees ) { return degrees * DEG2RAD; } function radToDeg( radians ) { return radians * RAD2DEG; } function isPowerOfTwo( value ) { return ( value & ( value - 1 ) ) === 0 && value !== 0; } function ceilPowerOfTwo( value ) { return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) ); } function floorPowerOfTwo( value ) { return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) ); } function setQuaternionFromProperEuler( q, a, b, c, order ) { // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles // rotations are applied to the axes in the order specified by 'order' // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c' // angles are in radians const cos = Math.cos; const sin = Math.sin; const c2 = cos( b / 2 ); const s2 = sin( b / 2 ); const c13 = cos( ( a + c ) / 2 ); const s13 = sin( ( a + c ) / 2 ); const c1_3 = cos( ( a - c ) / 2 ); const s1_3 = sin( ( a - c ) / 2 ); const c3_1 = cos( ( c - a ) / 2 ); const s3_1 = sin( ( c - a ) / 2 ); switch ( order ) { case 'XYX': q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 ); break; case 'YZY': q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 ); break; case 'ZXZ': q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 ); break; case 'XZX': q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 ); break; case 'YXY': q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 ); break; case 'ZYZ': q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 ); break; default: console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order ); } } function denormalize( value, array ) { switch ( array.constructor ) { case Float32Array: return value; case Uint32Array: return value / 4294967295.0; case Uint16Array: return value / 65535.0; case Uint8Array: return value / 255.0; case Int32Array: return Math.max( value / 2147483647.0, - 1.0 ); case Int16Array: return Math.max( value / 32767.0, - 1.0 ); case Int8Array: return Math.max( value / 127.0, - 1.0 ); default: throw new Error( 'Invalid component type.' ); } } function normalize( value, array ) { switch ( array.constructor ) { case Float32Array: return value; case Uint32Array: return Math.round( value * 4294967295.0 ); case Uint16Array: return Math.round( value * 65535.0 ); case Uint8Array: return Math.round( value * 255.0 ); case Int32Array: return Math.round( value * 2147483647.0 ); case Int16Array: return Math.round( value * 32767.0 ); case Int8Array: return Math.round( value * 127.0 ); default: throw new Error( 'Invalid component type.' ); } } const MathUtils = { DEG2RAD: DEG2RAD, RAD2DEG: RAD2DEG, generateUUID: generateUUID, clamp: clamp, euclideanModulo: euclideanModulo, mapLinear: mapLinear, inverseLerp: inverseLerp, lerp: lerp, damp: damp, pingpong: pingpong, smoothstep: smoothstep, smootherstep: smootherstep, randInt: randInt, randFloat: randFloat, randFloatSpread: randFloatSpread, seededRandom: seededRandom, degToRad: degToRad, radToDeg: radToDeg, isPowerOfTwo: isPowerOfTwo, ceilPowerOfTwo: ceilPowerOfTwo, floorPowerOfTwo: floorPowerOfTwo, setQuaternionFromProperEuler: setQuaternionFromProperEuler, normalize: normalize, denormalize: denormalize }; export { DEG2RAD, RAD2DEG, generateUUID, clamp, euclideanModulo, mapLinear, inverseLerp, lerp, damp, pingpong, smoothstep, smootherstep, randInt, randFloat, randFloatSpread, seededRandom, degToRad, radToDeg, isPowerOfTwo, ceilPowerOfTwo, floorPowerOfTwo, setQuaternionFromProperEuler, normalize, denormalize, MathUtils }; // spherical/Spherical.js import { clamp } from './MathUtils.js'; /** * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system * * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up. * theta (the azimuthal angle) is measured from the positive z-axis. */ class Spherical { constructor( radius = 1, phi = 0, theta = 0 ) { this.radius = radius; this.phi = phi; // polar angle this.theta = theta; // azimuthal angle return this; } set( radius, phi, theta ) { this.radius = radius; this.phi = phi; this.theta = theta; return this; } copy( other ) { this.radius = other.radius; this.phi = other.phi; this.theta = other.theta; return this; } // restrict phi to be between EPS and PI-EPS makeSafe() { const EPS = 0.000001; this.phi = clamp( this.phi, EPS, Math.PI - EPS ); return this; } setFromVector3( v ) { return this.setFromCartesianCoords( v.x, v.y, v.z ); } setFromCartesianCoords( x, y, z ) { this.radius = Math.sqrt( x * x + y * y + z * z ); if ( this.radius === 0 ) { this.theta = 0; this.phi = 0; } else { this.theta = Math.atan2( x, z ); this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) ); } return this; } clone() { return new this.constructor().copy( this ); } } export { Spherical }; ",2,448,JavaScript circle,./ProjectTest/JavaScript/circle.js,"// circle/vec2.js /* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net. * @class vec2 */ var vec2 = module.exports = {}; var Utils = require('./Utils'); /** * Make a cross product and only return the z component * @method crossLength * @static * @param {Array} a * @param {Array} b * @return {Number} */ vec2.crossLength = function(a,b){ return a[0] * b[1] - a[1] * b[0]; }; /** * Cross product between a vector and the Z component of a vector * @method crossVZ * @static * @param {Array} out * @param {Array} vec * @param {Number} zcomp * @return {Array} */ vec2.crossVZ = function(out, vec, zcomp){ vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule vec2.scale(out,out,zcomp); // Scale with z return out; }; /** * Cross product between a vector and the Z component of a vector * @method crossZV * @static * @param {Array} out * @param {Number} zcomp * @param {Array} vec * @return {Array} */ vec2.crossZV = function(out, zcomp, vec){ vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule vec2.scale(out,out,zcomp); // Scale with z return out; }; /** * Rotate a vector by an angle * @method rotate * @static * @param {Array} out * @param {Array} a * @param {Number} angle * @return {Array} */ vec2.rotate = function(out,a,angle){ if(angle !== 0){ var c = Math.cos(angle), s = Math.sin(angle), x = a[0], y = a[1]; out[0] = c*x -s*y; out[1] = s*x +c*y; } else { out[0] = a[0]; out[1] = a[1]; } return out; }; /** * Rotate a vector 90 degrees clockwise * @method rotate90cw * @static * @param {Array} out * @param {Array} a * @param {Number} angle * @return {Array} */ vec2.rotate90cw = function(out, a) { var x = a[0]; var y = a[1]; out[0] = y; out[1] = -x; return out; }; /** * Transform a point position to local frame. * @method toLocalFrame * @param {Array} out * @param {Array} worldPoint * @param {Array} framePosition * @param {Number} frameAngle * @return {Array} */ vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){ var c = Math.cos(-frameAngle), s = Math.sin(-frameAngle), x = worldPoint[0] - framePosition[0], y = worldPoint[1] - framePosition[1]; out[0] = c * x - s * y; out[1] = s * x + c * y; return out; }; /** * Transform a point position to global frame. * @method toGlobalFrame * @param {Array} out * @param {Array} localPoint * @param {Array} framePosition * @param {Number} frameAngle */ vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){ var c = Math.cos(frameAngle), s = Math.sin(frameAngle), x = localPoint[0], y = localPoint[1], addX = framePosition[0], addY = framePosition[1]; out[0] = c * x - s * y + addX; out[1] = s * x + c * y + addY; }; /** * Transform a vector to local frame. * @method vectorToLocalFrame * @param {Array} out * @param {Array} worldVector * @param {Number} frameAngle * @return {Array} */ vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){ var c = Math.cos(-frameAngle), s = Math.sin(-frameAngle), x = worldVector[0], y = worldVector[1]; out[0] = c*x -s*y; out[1] = s*x +c*y; return out; }; /** * Transform a vector to global frame. * @method vectorToGlobalFrame * @param {Array} out * @param {Array} localVector * @param {Number} frameAngle */ vec2.vectorToGlobalFrame = vec2.rotate; /** * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php * @method centroid * @static * @param {Array} out * @param {Array} a * @param {Array} b * @param {Array} c * @return {Array} The ""out"" vector. */ vec2.centroid = function(out, a, b, c){ vec2.add(out, a, b); vec2.add(out, out, c); vec2.scale(out, out, 1/3); return out; }; /** * Creates a new, empty vec2 * @static * @method create * @return {Array} a new 2D vector */ vec2.create = function() { var out = new Utils.ARRAY_TYPE(2); out[0] = 0; out[1] = 0; return out; }; /** * Creates a new vec2 initialized with values from an existing vector * @static * @method clone * @param {Array} a vector to clone * @return {Array} a new 2D vector */ vec2.clone = function(a) { var out = new Utils.ARRAY_TYPE(2); out[0] = a[0]; out[1] = a[1]; return out; }; /** * Creates a new vec2 initialized with the given values * @static * @method fromValues * @param {Number} x X component * @param {Number} y Y component * @return {Array} a new 2D vector */ vec2.fromValues = function(x, y) { var out = new Utils.ARRAY_TYPE(2); out[0] = x; out[1] = y; return out; }; /** * Copy the values from one vec2 to another * @static * @method copy * @param {Array} out the receiving vector * @param {Array} a the source vector * @return {Array} out */ vec2.copy = function(out, a) { out[0] = a[0]; out[1] = a[1]; return out; }; /** * Set the components of a vec2 to the given values * @static * @method set * @param {Array} out the receiving vector * @param {Number} x X component * @param {Number} y Y component * @return {Array} out */ vec2.set = function(out, x, y) { out[0] = x; out[1] = y; return out; }; /** * Adds two vec2's * @static * @method add * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.add = function(out, a, b) { out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; return out; }; /** * Subtracts two vec2's * @static * @method subtract * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.subtract = function(out, a, b) { out[0] = a[0] - b[0]; out[1] = a[1] - b[1]; return out; }; /** * Multiplies two vec2's * @static * @method multiply * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.multiply = function(out, a, b) { out[0] = a[0] * b[0]; out[1] = a[1] * b[1]; return out; }; /** * Divides two vec2's * @static * @method divide * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.divide = function(out, a, b) { out[0] = a[0] / b[0]; out[1] = a[1] / b[1]; return out; }; /** * Scales a vec2 by a scalar number * @static * @method scale * @param {Array} out the receiving vector * @param {Array} a the vector to scale * @param {Number} b amount to scale the vector by * @return {Array} out */ vec2.scale = function(out, a, b) { out[0] = a[0] * b; out[1] = a[1] * b; return out; }; /** * Calculates the euclidian distance between two vec2's * @static * @method distance * @param {Array} a the first operand * @param {Array} b the second operand * @return {Number} distance between a and b */ vec2.distance = function(a, b) { var x = b[0] - a[0], y = b[1] - a[1]; return Math.sqrt(x*x + y*y); }; /** * Calculates the squared euclidian distance between two vec2's * @static * @method squaredDistance * @param {Array} a the first operand * @param {Array} b the second operand * @return {Number} squared distance between a and b */ vec2.squaredDistance = function(a, b) { var x = b[0] - a[0], y = b[1] - a[1]; return x*x + y*y; }; /** * Calculates the length of a vec2 * @static * @method length * @param {Array} a vector to calculate length of * @return {Number} length of a */ vec2.length = function (a) { var x = a[0], y = a[1]; return Math.sqrt(x*x + y*y); }; /** * Calculates the squared length of a vec2 * @static * @method squaredLength * @param {Array} a vector to calculate squared length of * @return {Number} squared length of a */ vec2.squaredLength = function (a) { var x = a[0], y = a[1]; return x*x + y*y; }; /** * Negates the components of a vec2 * @static * @method negate * @param {Array} out the receiving vector * @param {Array} a vector to negate * @return {Array} out */ vec2.negate = function(out, a) { out[0] = -a[0]; out[1] = -a[1]; return out; }; /** * Normalize a vec2 * @static * @method normalize * @param {Array} out the receiving vector * @param {Array} a vector to normalize * @return {Array} out */ vec2.normalize = function(out, a) { var x = a[0], y = a[1]; var len = x*x + y*y; if (len > 0) { //TODO: evaluate use of glm_invsqrt here? len = 1 / Math.sqrt(len); out[0] = a[0] * len; out[1] = a[1] * len; } return out; }; /** * Calculates the dot product of two vec2's * @static * @method dot * @param {Array} a the first operand * @param {Array} b the second operand * @return {Number} dot product of a and b */ vec2.dot = function (a, b) { return a[0] * b[0] + a[1] * b[1]; }; /** * Returns a string representation of a vector * @static * @method str * @param {Array} vec vector to represent as a string * @return {String} string representation of the vector */ vec2.str = function (a) { return 'vec2(' + a[0] + ', ' + a[1] + ')'; }; /** * Linearly interpolate/mix two vectors. * @static * @method lerp * @param {Array} out * @param {Array} a First vector * @param {Array} b Second vector * @param {number} t Lerp factor */ vec2.lerp = function (out, a, b, t) { var ax = a[0], ay = a[1]; out[0] = ax + t * (b[0] - ax); out[1] = ay + t * (b[1] - ay); return out; }; /** * Reflect a vector along a normal. * @static * @method reflect * @param {Array} out * @param {Array} vector * @param {Array} normal */ vec2.reflect = function(out, vector, normal){ var dot = vector[0] * normal[0] + vector[1] * normal[1]; out[0] = vector[0] - 2 * normal[0] * dot; out[1] = vector[1] - 2 * normal[1] * dot; }; /** * Get the intersection point between two line segments. * @static * @method getLineSegmentsIntersection * @param {Array} out * @param {Array} p0 * @param {Array} p1 * @param {Array} p2 * @param {Array} p3 * @return {boolean} True if there was an intersection, otherwise false. */ vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) { var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3); if(t < 0){ return false; } else { out[0] = p0[0] + (t * (p1[0] - p0[0])); out[1] = p0[1] + (t * (p1[1] - p0[1])); return true; } }; /** * Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0) * @static * @method getLineSegmentsIntersectionFraction * @param {Array} p0 * @param {Array} p1 * @param {Array} p2 * @param {Array} p3 * @return {number} A number between 0 and 1 if there was an intersection, otherwise -1. */ vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) { var s1_x = p1[0] - p0[0]; var s1_y = p1[1] - p0[1]; var s2_x = p3[0] - p2[0]; var s2_y = p3[1] - p2[1]; var s, t; s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y); t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y); if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected return t; } return -1; // No collision }; // circle/Circle.js var Shape = require('./Shape') , vec2 = require('./vec2') , shallowClone = require('./Utils').shallowClone; module.exports = Circle; /** * Circle shape class. * @class Circle * @extends Shape * @constructor * @param {options} [options] (Note that this options object will be passed on to the {{#crossLink ""Shape""}}{{/crossLink}} constructor.) * @param {number} [options.radius=1] The radius of this circle * * @example * var body = new Body({ mass: 1 }); * var circleShape = new Circle({ * radius: 1 * }); * body.addShape(circleShape); */ function Circle(options){ options = options ? shallowClone(options) : {}; /** * The radius of the circle. * @property radius * @type {number} */ this.radius = options.radius !== undefined ? options.radius : 1; options.type = Shape.CIRCLE; Shape.call(this, options); } Circle.prototype = new Shape(); Circle.prototype.constructor = Circle; /** * @method computeMomentOfInertia * @return {Number} */ Circle.prototype.computeMomentOfInertia = function(){ var r = this.radius; return r * r / 2; }; /** * @method updateBoundingRadius * @return {Number} */ Circle.prototype.updateBoundingRadius = function(){ this.boundingRadius = this.radius; }; /** * @method updateArea * @return {Number} */ Circle.prototype.updateArea = function(){ this.area = Math.PI * this.radius * this.radius; }; /** * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Circle.prototype.computeAABB = function(out, position/*, angle*/){ var r = this.radius; vec2.set(out.upperBound, r, r); vec2.set(out.lowerBound, -r, -r); if(position){ vec2.add(out.lowerBound, out.lowerBound, position); vec2.add(out.upperBound, out.upperBound, position); } }; var Ray_intersectSphere_intersectionPoint = vec2.create(); var Ray_intersectSphere_normal = vec2.create(); /** * @method raycast * @param {RaycastResult} result * @param {Ray} ray * @param {array} position * @param {number} angle */ Circle.prototype.raycast = function(result, ray, position/*, angle*/){ var from = ray.from, to = ray.to, r = this.radius; var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2); var b = 2 * ((to[0] - from[0]) * (from[0] - position[0]) + (to[1] - from[1]) * (from[1] - position[1])); var c = Math.pow(from[0] - position[0], 2) + Math.pow(from[1] - position[1], 2) - Math.pow(r, 2); var delta = Math.pow(b, 2) - 4 * a * c; var intersectionPoint = Ray_intersectSphere_intersectionPoint; var normal = Ray_intersectSphere_normal; if(delta < 0){ // No intersection return; } else if(delta === 0){ // single intersection point vec2.lerp(intersectionPoint, from, to, delta); vec2.subtract(normal, intersectionPoint, position); vec2.normalize(normal,normal); ray.reportIntersection(result, delta, normal, -1); } else { var sqrtDelta = Math.sqrt(delta); var inv2a = 1 / (2 * a); var d1 = (- b - sqrtDelta) * inv2a; var d2 = (- b + sqrtDelta) * inv2a; if(d1 >= 0 && d1 <= 1){ vec2.lerp(intersectionPoint, from, to, d1); vec2.subtract(normal, intersectionPoint, position); vec2.normalize(normal,normal); ray.reportIntersection(result, d1, normal, -1); if(result.shouldStop(ray)){ return; } } if(d2 >= 0 && d2 <= 1){ vec2.lerp(intersectionPoint, from, to, d2); vec2.subtract(normal, intersectionPoint, position); vec2.normalize(normal,normal); ray.reportIntersection(result, d2, normal, -1); } } }; Circle.prototype.pointTest = function(localPoint){ var radius = this.radius; return vec2.squaredLength(localPoint) <= radius * radius; }; // circle/Utils.js /* global P2_ARRAY_TYPE */ module.exports = Utils; /** * Misc utility functions * @class Utils * @constructor */ function Utils(){} /** * Append the values in array b to the array a. See this for an explanation. * @method appendArray * @static * @param {Array} a * @param {Array} b */ Utils.appendArray = function(a,b){ if (b.length < 150000) { a.push.apply(a, b); } else { for (var i = 0, len = b.length; i !== len; ++i) { a.push(b[i]); } } }; /** * Garbage free Array.splice(). Does not allocate a new array. * @method splice * @static * @param {Array} array * @param {Number} index * @param {Number} howmany */ Utils.splice = function(array,index,howmany){ howmany = howmany || 1; for (var i=index, len=array.length-howmany; i < len; i++){ array[i] = array[i + howmany]; } array.length = len; }; /** * Remove an element from an array, if the array contains the element. * @method arrayRemove * @static * @param {Array} array * @param {Number} element */ Utils.arrayRemove = function(array, element){ var idx = array.indexOf(element); if(idx!==-1){ Utils.splice(array, idx, 1); } }; /** * The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below. * @static * @property {function} ARRAY_TYPE * @example * * */ if(typeof P2_ARRAY_TYPE !== 'undefined') { Utils.ARRAY_TYPE = P2_ARRAY_TYPE; } else if (typeof Float32Array !== 'undefined'){ Utils.ARRAY_TYPE = Float32Array; } else { Utils.ARRAY_TYPE = Array; } /** * Extend an object with the properties of another * @static * @method extend * @param {object} a * @param {object} b */ Utils.extend = function(a,b){ for(var key in b){ a[key] = b[key]; } }; /** * Shallow clone an object. Returns a new object instance with the same properties as the input instance. * @static * @method shallowClone * @param {object} obj */ Utils.shallowClone = function(obj){ var newObj = {}; Utils.extend(newObj, obj); return newObj; }; /** * Extend an options object with default values. * @deprecated Not used internally, will be removed. * @static * @method defaults * @param {object} options The options object. May be falsy: in this case, a new object is created and returned. * @param {object} defaults An object containing default values. * @return {object} The modified options object. */ Utils.defaults = function(options, defaults){ console.warn('Utils.defaults is deprecated.'); options = options || {}; for(var key in defaults){ if(!(key in options)){ options[key] = defaults[key]; } } return options; }; // circle/Shape.js module.exports = Shape; var vec2 = require('./vec2'); /** * Base class for shapes. Not to be used directly. * @class Shape * @constructor * @param {object} [options] * @param {number} [options.angle=0] * @param {number} [options.collisionGroup=1] * @param {number} [options.collisionMask=1] * @param {boolean} [options.collisionResponse=true] * @param {Material} [options.material=null] * @param {array} [options.position] * @param {boolean} [options.sensor=false] * @param {object} [options.type=0] */ function Shape(options){ options = options || {}; /** * The body this shape is attached to. A shape can only be attached to a single body. * @property {Body} body */ this.body = null; /** * Body-local position of the shape. * @property {Array} position */ this.position = vec2.create(); if(options.position){ vec2.copy(this.position, options.position); } /** * Body-local angle of the shape. * @property {number} angle */ this.angle = options.angle || 0; /** * The type of the shape. One of: * * * * @property {number} type */ this.type = options.type || 0; /** * Shape object identifier. Read only. * @readonly * @type {Number} * @property id */ this.id = Shape.idCounter++; /** * Bounding circle radius of this shape * @readonly * @property boundingRadius * @type {Number} */ this.boundingRadius = 0; /** * Collision group that this shape belongs to (bit mask). See this tutorial. * @property collisionGroup * @type {Number} * @example * // Setup bits for each available group * var PLAYER = Math.pow(2,0), * ENEMY = Math.pow(2,1), * GROUND = Math.pow(2,2) * * // Put shapes into their groups * player1Shape.collisionGroup = PLAYER; * player2Shape.collisionGroup = PLAYER; * enemyShape .collisionGroup = ENEMY; * groundShape .collisionGroup = GROUND; * * // Assign groups that each shape collide with. * // Note that the players can collide with ground and enemies, but not with other players. * player1Shape.collisionMask = ENEMY | GROUND; * player2Shape.collisionMask = ENEMY | GROUND; * enemyShape .collisionMask = PLAYER | GROUND; * groundShape .collisionMask = PLAYER | ENEMY; * * @example * // How collision check is done * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){ * // The shapes will collide * } */ this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1; /** * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc. * @property {Boolean} collisionResponse */ this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true; /** * Collision mask of this shape. See .collisionGroup. * @property collisionMask * @type {Number} */ this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1; /** * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead. * @property material * @type {Material} */ this.material = options.material || null; /** * Area of this shape. * @property area * @type {Number} */ this.area = 0; /** * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts. * @property {Boolean} sensor */ this.sensor = options.sensor !== undefined ? options.sensor : false; if(this.type){ this.updateBoundingRadius(); } this.updateArea(); } Shape.idCounter = 0; /** * @static * @property {Number} CIRCLE */ Shape.CIRCLE = 1; /** * @static * @property {Number} PARTICLE */ Shape.PARTICLE = 2; /** * @static * @property {Number} PLANE */ Shape.PLANE = 4; /** * @static * @property {Number} CONVEX */ Shape.CONVEX = 8; /** * @static * @property {Number} LINE */ Shape.LINE = 16; /** * @static * @property {Number} BOX */ Shape.BOX = 32; /** * @static * @property {Number} CAPSULE */ Shape.CAPSULE = 64; /** * @static * @property {Number} HEIGHTFIELD */ Shape.HEIGHTFIELD = 128; Shape.prototype = { /** * Should return the moment of inertia around the Z axis of the body. See Wikipedia's list of moments of inertia. * @method computeMomentOfInertia * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0. */ computeMomentOfInertia: function(){}, /** * Returns the bounding circle radius of this shape. * @method updateBoundingRadius * @return {Number} */ updateBoundingRadius: function(){}, /** * Update the .area property of the shape. * @method updateArea */ updateArea: function(){}, /** * Compute the world axis-aligned bounding box (AABB) of this shape. * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position World position of the shape. * @param {Number} angle World angle of the shape. */ computeAABB: function(/*out, position, angle*/){ // To be implemented in each subclass }, /** * Perform raycasting on this shape. * @method raycast * @param {RayResult} result Where to store the resulting data. * @param {Ray} ray The Ray that you want to use for raycasting. * @param {array} position World position of the shape (the .position property will be ignored). * @param {number} angle World angle of the shape (the .angle property will be ignored). */ raycast: function(/*result, ray, position, angle*/){ // To be implemented in each subclass }, /** * Test if a point is inside this shape. * @method pointTest * @param {array} localPoint * @return {boolean} */ pointTest: function(/*localPoint*/){ return false; }, /** * Transform a world point to local shape space (assumed the shape is transformed by both itself and the body). * @method worldPointToLocal * @param {array} out * @param {array} worldPoint */ worldPointToLocal: (function () { var shapeWorldPosition = vec2.create(); return function (out, worldPoint) { var body = this.body; vec2.rotate(shapeWorldPosition, this.position, body.angle); vec2.add(shapeWorldPosition, shapeWorldPosition, body.position); vec2.toLocalFrame(out, worldPoint, shapeWorldPosition, this.body.angle + this.angle); }; })() }; ",4,1068,JavaScript pixelrender,./ProjectTest/JavaScript/pixelrender.js,"// pixelrender/DomUtil.js export default { /** * Creates and returns a new canvas. The opacity is by default set to 0 * * @memberof Proton#Proton.DomUtil * @method createCanvas * * @param {String} $id the canvas' id * @param {Number} $width the canvas' width * @param {Number} $height the canvas' height * @param {String} [$position=absolute] the canvas' position, default is 'absolute' * * @return {Object} */ createCanvas(id, width, height, position = ""absolute"") { const dom = document.createElement(""canvas""); dom.id = id; dom.width = width; dom.height = height; dom.style.opacity = 0; dom.style.position = position; this.transform(dom, -500, -500, 0, 0); return dom; }, createDiv(id, width, height) { const dom = document.createElement(""div""); dom.id = id; dom.style.position = ""absolute""; this.resize(dom, width, height); return dom; }, resize(dom, width, height) { dom.style.width = width + ""px""; dom.style.height = height + ""px""; dom.style.marginLeft = -width / 2 + ""px""; dom.style.marginTop = -height / 2 + ""px""; }, /** * Adds a transform: translate(), scale(), rotate() to a given div dom for all browsers * * @memberof Proton#Proton.DomUtil * @method transform * * @param {HTMLDivElement} div * @param {Number} $x * @param {Number} $y * @param {Number} $scale * @param {Number} $rotate */ transform(div, x, y, scale, rotate) { div.style.willChange = ""transform""; const transform = `translate(${x}px, ${y}px) scale(${scale}) rotate(${rotate}deg)`; this.css3(div, ""transform"", transform); }, transform3d(div, x, y, scale, rotate) { div.style.willChange = ""transform""; const transform = `translate3d(${x}px, ${y}px, 0) scale(${scale}) rotate(${rotate}deg)`; this.css3(div, ""backfaceVisibility"", ""hidden""); this.css3(div, ""transform"", transform); }, css3(div, key, val) { const bkey = key.charAt(0).toUpperCase() + key.substr(1); div.style[`Webkit${bkey}`] = val; div.style[`Moz${bkey}`] = val; div.style[`O${bkey}`] = val; div.style[`ms${bkey}`] = val; div.style[`${key}`] = val; } }; // pixelrender/Pool.js /** * Pool is the cache pool of the proton engine, it is very important. * * get(target, params, uid) * Class * uid = Puid.getId -> Puid save target cache * target.__puid = uid * * body * uid = Puid.getId -> Puid save target cache * * * expire(target) * cache[target.__puid] push target * */ import Util from ""./Util""; import Puid from ""./Puid""; export default class Pool { /** * @memberof! Proton# * @constructor * @alias Proton.Pool * * @todo add description * @todo add description of properties * * @property {Number} total * @property {Object} cache */ constructor(num) { this.total = 0; this.cache = {}; } /** * @todo add description * * @method get * @memberof Proton#Proton.Pool * * @param {Object|Function} target * @param {Object} [params] just add if `target` is a function * * @return {Object} */ get(target, params, uid) { let p; uid = uid || target.__puid || Puid.getId(target); if (this.cache[uid] && this.cache[uid].length > 0) { p = this.cache[uid].pop(); } else { p = this.createOrClone(target, params); } p.__puid = target.__puid || uid; return p; } /** * @todo add description * * @method set * @memberof Proton#Proton.Pool * * @param {Object} target * * @return {Object} */ expire(target) { return this.getCache(target.__puid).push(target); } /** * Creates a new class instance * * @todo add more documentation * * @method create * @memberof Proton#Proton.Pool * * @param {Object|Function} target any Object or Function * @param {Object} [params] just add if `target` is a function * * @return {Object} */ createOrClone(target, params) { this.total++; if (this.create) { return this.create(target, params); } else if (typeof target === ""function"") { return Util.classApply(target, params); } else { return target.clone(); } } /** * @todo add description - what is in the cache? * * @method getCount * @memberof Proton#Proton.Pool * * @return {Number} */ getCount() { let count = 0; for (let id in this.cache) count += this.cache[id].length; return count++; } /** * Destroyes all items from Pool.cache * * @method destroy * @memberof Proton#Proton.Pool */ destroy() { for (let id in this.cache) { this.cache[id].length = 0; delete this.cache[id]; } } /** * Returns Pool.cache * * @method getCache * @memberof Proton#Proton.Pool * @private * * @param {Number} uid the unique id * * @return {Object} */ getCache(uid = ""default"") { if (!this.cache[uid]) this.cache[uid] = []; return this.cache[uid]; } } // pixelrender/ImgUtil.js import WebGLUtil from ""./WebGLUtil""; import DomUtil from ""./DomUtil""; const imgsCache = {}; const canvasCache = {}; let canvasId = 0; export default { /** * This will get the image data. It could be necessary to create a Proton.Zone. * * @memberof Proton#Proton.Util * @method getImageData * * @param {HTMLCanvasElement} context any canvas, must be a 2dContext 'canvas.getContext('2d')' * @param {Object} image could be any dom image, e.g. document.getElementById('thisIsAnImgTag'); * @param {Proton.Rectangle} rect */ getImageData(context, image, rect) { context.drawImage(image, rect.x, rect.y); const imagedata = context.getImageData(rect.x, rect.y, rect.width, rect.height); context.clearRect(rect.x, rect.y, rect.width, rect.height); return imagedata; }, /** * @memberof Proton#Proton.Util * @method getImgFromCache * * @todo add description * @todo describe func * * @param {Mixed} img * @param {Proton.Particle} particle * @param {Boolean} drawCanvas set to true if a canvas should be saved into particle.data.canvas * @param {Boolean} func */ getImgFromCache(img, callback, param) { const src = typeof img === ""string"" ? img : img.src; if (imgsCache[src]) { callback(imgsCache[src], param); } else { const image = new Image(); image.onload = e => { imgsCache[src] = e.target; callback(imgsCache[src], param); }; image.src = src; } }, getCanvasFromCache(img, callback, param) { const src = img.src; if (!canvasCache[src]) { const width = WebGLUtil.nhpot(img.width); const height = WebGLUtil.nhpot(img.height); const canvas = DomUtil.createCanvas(`proton_canvas_cache_${++canvasId}`, width, height); const context = canvas.getContext(""2d""); context.drawImage(img, 0, 0, img.width, img.height); canvasCache[src] = canvas; } callback && callback(canvasCache[src], param); return canvasCache[src]; } }; // pixelrender/Util.js import ImgUtil from ""./ImgUtil""; export default { /** * Returns the default if the value is null or undefined * * @memberof Proton#Proton.Util * @method initValue * * @param {Mixed} value a specific value, could be everything but null or undefined * @param {Mixed} defaults the default if the value is null or undefined */ initValue(value, defaults) { value = value !== null && value !== undefined ? value : defaults; return value; }, /** * Checks if the value is a valid array * * @memberof Proton#Proton.Util * @method isArray * * @param {Array} value Any array * * @returns {Boolean} */ isArray(value) { return Object.prototype.toString.call(value) === ""[object Array]""; }, /** * Destroyes the given array * * @memberof Proton#Proton.Util * @method emptyArray * * @param {Array} array Any array */ emptyArray(arr) { if (arr) arr.length = 0; }, toArray(arr) { return this.isArray(arr) ? arr : [arr]; }, sliceArray(arr1, index, arr2) { this.emptyArray(arr2); for (let i = index; i < arr1.length; i++) { arr2.push(arr1[i]); } }, getRandFromArray(arr) { if (!arr) return null; return arr[Math.floor(arr.length * Math.random())]; }, /** * Destroyes the given object * * @memberof Proton#Proton.Util * @method emptyObject * * @param {Object} obj Any object */ emptyObject(obj, ignore = null) { for (let key in obj) { if (ignore && ignore.indexOf(key) > -1) continue; delete obj[key]; } }, /** * Makes an instance of a class and binds the given array * * @memberof Proton#Proton.Util * @method classApply * * @param {Function} constructor A class to make an instance from * @param {Array} [args] Any array to bind it to the constructor * * @return {Object} The instance of constructor, optionally bind with args */ classApply(constructor, args = null) { if (!args) { return new constructor(); } else { const FactoryFunc = constructor.bind.apply(constructor, [null].concat(args)); return new FactoryFunc(); } }, /** * This will get the image data. It could be necessary to create a Proton.Zone. * * @memberof Proton#Proton.Util * @method getImageData * * @param {HTMLCanvasElement} context any canvas, must be a 2dContext 'canvas.getContext('2d')' * @param {Object} image could be any dom image, e.g. document.getElementById('thisIsAnImgTag'); * @param {Proton.Rectangle} rect */ getImageData(context, image, rect) { return ImgUtil.getImageData(context, image, rect); }, destroyAll(arr, param = null) { let i = arr.length; while (i--) { try { arr[i].destroy(param); } catch (e) {} delete arr[i]; } arr.length = 0; }, assign(target, source) { if (typeof Object.assign !== ""function"") { for (let key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } return target; } else { return Object.assign(target, source); } } }; // pixelrender/Rectangle.js export default class Rectangle { constructor(x, y, w, h) { this.x = x; this.y = y; this.width = w; this.height = h; this.bottom = this.y + this.height; this.right = this.x + this.width; } contains(x, y) { if (x <= this.right && x >= this.x && y <= this.bottom && y >= this.y) return true; else return false; } } // pixelrender/WebGLUtil.js export default { /** * @memberof Proton#Proton.WebGLUtil * @method ipot * * @todo add description * @todo add length description * * @param {Number} length * * @return {Boolean} */ ipot(length) { return (length & (length - 1)) === 0; }, /** * @memberof Proton#Proton.WebGLUtil * @method nhpot * * @todo add description * @todo add length description * * @param {Number} length * * @return {Number} */ nhpot(length) { --length; for (let i = 1; i < 32; i <<= 1) { length = length | (length >> i); } return length + 1; }, /** * @memberof Proton#Proton.WebGLUtil * @method makeTranslation * * @todo add description * @todo add tx, ty description * @todo add return description * * @param {Number} tx either 0 or 1 * @param {Number} ty either 0 or 1 * * @return {Object} */ makeTranslation(tx, ty) { return [1, 0, 0, 0, 1, 0, tx, ty, 1]; }, /** * @memberof Proton#Proton.WebGLUtil * @method makeRotation * * @todo add description * @todo add return description * * @param {Number} angleInRadians * * @return {Object} */ makeRotation(angleInRadians) { let c = Math.cos(angleInRadians); let s = Math.sin(angleInRadians); return [c, -s, 0, s, c, 0, 0, 0, 1]; }, /** * @memberof Proton#Proton.WebGLUtil * @method makeScale * * @todo add description * @todo add tx, ty description * @todo add return description * * @param {Number} sx either 0 or 1 * @param {Number} sy either 0 or 1 * * @return {Object} */ makeScale(sx, sy) { return [sx, 0, 0, 0, sy, 0, 0, 0, 1]; }, /** * @memberof Proton#Proton.WebGLUtil * @method matrixMultiply * * @todo add description * @todo add a, b description * @todo add return description * * @param {Object} a * @param {Object} b * * @return {Object} */ matrixMultiply(a, b) { let a00 = a[0 * 3 + 0]; let a01 = a[0 * 3 + 1]; let a02 = a[0 * 3 + 2]; let a10 = a[1 * 3 + 0]; let a11 = a[1 * 3 + 1]; let a12 = a[1 * 3 + 2]; let a20 = a[2 * 3 + 0]; let a21 = a[2 * 3 + 1]; let a22 = a[2 * 3 + 2]; let b00 = b[0 * 3 + 0]; let b01 = b[0 * 3 + 1]; let b02 = b[0 * 3 + 2]; let b10 = b[1 * 3 + 0]; let b11 = b[1 * 3 + 1]; let b12 = b[1 * 3 + 2]; let b20 = b[2 * 3 + 0]; let b21 = b[2 * 3 + 1]; let b22 = b[2 * 3 + 2]; return [ a00 * b00 + a01 * b10 + a02 * b20, a00 * b01 + a01 * b11 + a02 * b21, a00 * b02 + a01 * b12 + a02 * b22, a10 * b00 + a11 * b10 + a12 * b20, a10 * b01 + a11 * b11 + a12 * b21, a10 * b02 + a11 * b12 + a12 * b22, a20 * b00 + a21 * b10 + a22 * b20, a20 * b01 + a21 * b11 + a22 * b21, a20 * b02 + a21 * b12 + a22 * b22 ]; } }; // pixelrender/Puid.js const idsMap = {}; const Puid = { _index: 0, _cache: {}, id(type) { if (idsMap[type] === undefined || idsMap[type] === null) idsMap[type] = 0; return `${type}_${idsMap[type]++}`; }, getId(target) { let uid = this.getIdFromCache(target); if (uid) return uid; uid = `PUID_${this._index++}`; this._cache[uid] = target; return uid; }, getIdFromCache(target) { let obj, id; for (id in this._cache) { obj = this._cache[id]; if (obj === target) return id; if (this.isBody(obj, target) && obj.src === target.src) return id; } return null; }, isBody(obj, target) { return typeof obj === ""object"" && typeof target === ""object"" && obj.isInner && target.isInner; }, getTarget(uid) { return this._cache[uid]; } }; export default Puid; // pixelrender/PixelRenderer.js import Rectangle from ""./Rectangle""; import BaseRenderer from ""./BaseRenderer""; export default class PixelRenderer extends BaseRenderer { constructor(element, rectangle) { super(element); this.context = this.element.getContext(""2d""); this.imageData = null; this.rectangle = rectangle; this.createImageData(rectangle); this.name = ""PixelRenderer""; } resize(width, height) { this.element.width = width; this.element.height = height; } createImageData(rectangle) { this.rectangle = rectangle ? rectangle : new Rectangle(0, 0, this.element.width, this.element.height); this.imageData = this.context.createImageData(this.rectangle.width, this.rectangle.height); this.context.putImageData(this.imageData, this.rectangle.x, this.rectangle.y); } onProtonUpdate() { this.context.clearRect(this.rectangle.x, this.rectangle.y, this.rectangle.width, this.rectangle.height); this.imageData = this.context.getImageData( this.rectangle.x, this.rectangle.y, this.rectangle.width, this.rectangle.height ); } onProtonUpdateAfter() { this.context.putImageData(this.imageData, this.rectangle.x, this.rectangle.y); } onParticleCreated(particle) {} onParticleUpdate(particle) { if (this.imageData) { this.setPixel( this.imageData, (particle.p.x - this.rectangle.x) >> 0, (particle.p.y - this.rectangle.y) >> 0, particle ); } } setPixel(imagedata, x, y, particle) { const rgb = particle.rgb; if (x < 0 || x > this.element.width || y < 0 || y > this.element.height) return; const i = ((y >> 0) * imagedata.width + (x >> 0)) * 4; imagedata.data[i] = rgb.r; imagedata.data[i + 1] = rgb.g; imagedata.data[i + 2] = rgb.b; imagedata.data[i + 3] = particle.alpha * 255; } onParticleDead(particle) {} destroy() { super.destroy(); this.stroke = null; this.context = null; this.imageData = null; this.rectangle = null; } } // pixelrender/BaseRenderer.js import Pool from ""./Pool""; export default class BaseRenderer { constructor(element, stroke) { this.pool = new Pool(); this.element = element; this.stroke = stroke; this.circleConf = { isCircle: true }; this.initEventHandler(); this.name = ""BaseRenderer""; } setStroke(color = ""#000000"", thinkness = 1) { this.stroke = { color, thinkness }; } initEventHandler() { this._protonUpdateHandler = () => { this.onProtonUpdate.call(this); }; this._protonUpdateAfterHandler = () => { this.onProtonUpdateAfter.call(this); }; this._emitterAddedHandler = emitter => { this.onEmitterAdded.call(this, emitter); }; this._emitterRemovedHandler = emitter => { this.onEmitterRemoved.call(this, emitter); }; this._particleCreatedHandler = particle => { this.onParticleCreated.call(this, particle); }; this._particleUpdateHandler = particle => { this.onParticleUpdate.call(this, particle); }; this._particleDeadHandler = particle => { this.onParticleDead.call(this, particle); }; } init(proton) { this.parent = proton; proton.addEventListener(""PROTON_UPDATE"", this._protonUpdateHandler); proton.addEventListener(""PROTON_UPDATE_AFTER"", this._protonUpdateAfterHandler); proton.addEventListener(""EMITTER_ADDED"", this._emitterAddedHandler); proton.addEventListener(""EMITTER_REMOVED"", this._emitterRemovedHandler); proton.addEventListener(""PARTICLE_CREATED"", this._particleCreatedHandler); proton.addEventListener(""PARTICLE_UPDATE"", this._particleUpdateHandler); proton.addEventListener(""PARTICLE_DEAD"", this._particleDeadHandler); } resize(width, height) {} destroy() { this.remove(); this.pool.destroy(); this.pool = null; this.element = null; this.stroke = null; } remove(proton) { this.parent.removeEventListener(""PROTON_UPDATE"", this._protonUpdateHandler); this.parent.removeEventListener(""PROTON_UPDATE_AFTER"", this._protonUpdateAfterHandler); this.parent.removeEventListener(""EMITTER_ADDED"", this._emitterAddedHandler); this.parent.removeEventListener(""EMITTER_REMOVED"", this._emitterRemovedHandler); this.parent.removeEventListener(""PARTICLE_CREATED"", this._particleCreatedHandler); this.parent.removeEventListener(""PARTICLE_UPDATE"", this._particleUpdateHandler); this.parent.removeEventListener(""PARTICLE_DEAD"", this._particleDeadHandler); this.parent = null; } onProtonUpdate() {} onProtonUpdateAfter() {} onEmitterAdded(emitter) {} onEmitterRemoved(emitter) {} onParticleCreated(particle) {} onParticleUpdate(particle) {} onParticleDead(particle) {} } ",9,794,JavaScript solver,./ProjectTest/JavaScript/solver.js,"// solver/EventEmitter.js module.exports = EventEmitter; /** * Base class for objects that dispatches events. * @class EventEmitter * @constructor * @example * var emitter = new EventEmitter(); * emitter.on('myEvent', function(evt){ * console.log(evt.message); * }); * emitter.emit({ * type: 'myEvent', * message: 'Hello world!' * }); */ function EventEmitter() { this.tmpArray = []; } EventEmitter.prototype = { constructor: EventEmitter, /** * Add an event listener * @method on * @param {String} type * @param {Function} listener * @return {EventEmitter} The self object, for chainability. * @example * emitter.on('myEvent', function(evt){ * console.log('myEvt was triggered!'); * }); */ on: function ( type, listener, context ) { listener.context = context || this; if ( this._listeners === undefined ){ this._listeners = {}; } var listeners = this._listeners; if ( listeners[ type ] === undefined ) { listeners[ type ] = []; } if ( listeners[ type ].indexOf( listener ) === - 1 ) { listeners[ type ].push( listener ); } return this; }, /** * Remove an event listener * @method off * @param {String} type * @param {Function} listener * @return {EventEmitter} The self object, for chainability. * @example * emitter.on('myEvent', handler); // Add handler * emitter.off('myEvent', handler); // Remove handler */ off: function ( type, listener ) { var listeners = this._listeners; if(!listeners || !listeners[type]){ return this; } var index = listeners[ type ].indexOf( listener ); if ( index !== - 1 ) { listeners[ type ].splice( index, 1 ); } return this; }, /** * Check if an event listener is added * @method has * @param {String} type * @param {Function} listener * @return {Boolean} */ has: function ( type, listener ) { if ( this._listeners === undefined ){ return false; } var listeners = this._listeners; if(listener){ if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { return true; } } else { if ( listeners[ type ] !== undefined ) { return true; } } return false; }, /** * Emit an event. * @method emit * @param {Object} event * @param {String} event.type * @return {EventEmitter} The self object, for chainability. * @example * emitter.emit({ * type: 'myEvent', * customData: 123 * }); */ emit: function ( event ) { if ( this._listeners === undefined ){ return this; } var listeners = this._listeners; var listenerArray = listeners[ event.type ]; if ( listenerArray !== undefined ) { event.target = this; // Need to copy the listener array, in case some listener was added/removed inside a listener var tmpArray = this.tmpArray; for (var i = 0, l = listenerArray.length; i < l; i++) { tmpArray[i] = listenerArray[i]; } for (var i = 0, l = tmpArray.length; i < l; i++) { var listener = tmpArray[ i ]; listener.call( listener.context, event ); } tmpArray.length = 0; } return this; } }; // solver/Solver.js var EventEmitter = require('./EventEmitter'); module.exports = Solver; /** * Base class for constraint solvers. * @class Solver * @constructor * @extends EventEmitter */ function Solver(options,type){ options = options || {}; EventEmitter.call(this); this.type = type; /** * Current equations in the solver. * * @property equations * @type {Array} */ this.equations = []; /** * Function that is used to sort all equations before each solve. * @property equationSortFunction * @type {function|boolean} */ this.equationSortFunction = options.equationSortFunction || false; } Solver.prototype = new EventEmitter(); Solver.prototype.constructor = Solver; /** * Method to be implemented in each subclass * @method solve * @param {Number} dt * @param {World} world */ Solver.prototype.solve = function(/*dt,world*/){ throw new Error(""Solver.solve should be implemented by subclasses!""); }; /** * Sort all equations using the .equationSortFunction. Should be called by subclasses before solving. * @method sortEquations */ Solver.prototype.sortEquations = function(){ if(this.equationSortFunction){ this.equations.sort(this.equationSortFunction); } }; /** * Add an equation to be solved. * * @method addEquation * @param {Equation} eq */ Solver.prototype.addEquation = function(eq){ if(eq.enabled){ this.equations.push(eq); } }; /** * Add equations. Same as .addEquation, but this time the argument is an array of Equations * * @method addEquations * @param {Array} eqs */ Solver.prototype.addEquations = function(eqs){ for(var i=0, N=eqs.length; i!==N; i++){ var eq = eqs[i]; if(eq.enabled){ this.equations.push(eq); } } }; /** * Remove an equation. * * @method removeEquation * @param {Equation} eq */ Solver.prototype.removeEquation = function(eq){ var i = this.equations.indexOf(eq); if(i !== -1){ this.equations.splice(i,1); } }; /** * Remove all currently added equations. * * @method removeAllEquations */ Solver.prototype.removeAllEquations = function(){ this.equations.length=0; }; /** * Gauss-Seidel solver. * @property GS * @type {Number} * @static */ Solver.GS = 1; ",2,242,JavaScript aggregate,./ProjectTest/JavaScript/aggregate.js,"// aggregate/aggregate.js import { setNonEnumProp } from './descriptors.js' // Array of `errors` can be set using an option. // This is like `AggregateError` except: // - This is available in any class, removing the need to create separate // classes for it // - Any class can opt-in to it or not // - This uses a named parameter instead of a positional one: // - This is more monomorphic // - This parallels the `cause` option // Child `errors` are always kept, only appended to. export const setAggregateErrors = (error, errors) => { if (errors === undefined) { return } if (!Array.isArray(errors)) { throw new TypeError(`""errors"" option must be an array: ${errors}`) } setNonEnumProp(error, 'errors', errors) } // aggregate/descriptors.js // Most error core properties are not enumerable export const setNonEnumProp = (object, propName, value) => { // eslint-disable-next-line fp/no-mutating-methods Object.defineProperty(object, propName, { value, enumerable: false, writable: true, configurable: true, }) } ",2,32,JavaScript overlapkeeper,./ProjectTest/JavaScript/overlapkeeper.js,"// overlapkeeper/Pool.js module.exports = Pool; /** * Object pooling utility. * @class Pool * @constructor */ function Pool(options) { options = options || {}; /** * @property {Array} objects * @type {Array} */ this.objects = []; if(options.size !== undefined){ this.resize(options.size); } } /** * @method resize * @param {number} size * @return {Pool} Self, for chaining */ Pool.prototype.resize = function (size) { var objects = this.objects; while (objects.length > size) { objects.pop(); } while (objects.length < size) { objects.push(this.create()); } return this; }; /** * Get an object from the pool or create a new instance. * @method get * @return {Object} */ Pool.prototype.get = function () { var objects = this.objects; return objects.length ? objects.pop() : this.create(); }; /** * Clean up and put the object back into the pool for later use. * @method release * @param {Object} object * @return {Pool} Self for chaining */ Pool.prototype.release = function (object) { this.destroy(object); this.objects.push(object); return this; }; // overlapkeeper/OverlapKeeperRecord.js module.exports = OverlapKeeperRecord; /** * Overlap data container for the OverlapKeeper * @class OverlapKeeperRecord * @constructor * @param {Body} bodyA * @param {Shape} shapeA * @param {Body} bodyB * @param {Shape} shapeB */ function OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB){ /** * @property {Shape} shapeA */ this.shapeA = shapeA; /** * @property {Shape} shapeB */ this.shapeB = shapeB; /** * @property {Body} bodyA */ this.bodyA = bodyA; /** * @property {Body} bodyB */ this.bodyB = bodyB; } /** * Set the data for the record * @method set * @param {Body} bodyA * @param {Shape} shapeA * @param {Body} bodyB * @param {Shape} shapeB */ OverlapKeeperRecord.prototype.set = function(bodyA, shapeA, bodyB, shapeB){ OverlapKeeperRecord.call(this, bodyA, shapeA, bodyB, shapeB); }; // overlapkeeper/TupleDictionary.js var Utils = require('./Utils'); module.exports = TupleDictionary; /** * @class TupleDictionary * @constructor */ function TupleDictionary() { /** * The data storage * @property data * @type {Object} */ this.data = {}; /** * Keys that are currently used. * @property {Array} keys */ this.keys = []; } /** * Generate a key given two integers * @method getKey * @param {number} i * @param {number} j * @return {string} */ TupleDictionary.prototype.getKey = function(id1, id2) { id1 = id1|0; id2 = id2|0; if ( (id1|0) === (id2|0) ){ return -1; } // valid for values < 2^16 return ((id1|0) > (id2|0) ? (id1 << 16) | (id2 & 0xFFFF) : (id2 << 16) | (id1 & 0xFFFF))|0 ; }; /** * @method getByKey * @param {Number} key * @return {Object} */ TupleDictionary.prototype.getByKey = function(key) { key = key|0; return this.data[key]; }; /** * @method get * @param {Number} i * @param {Number} j * @return {Number} */ TupleDictionary.prototype.get = function(i, j) { return this.data[this.getKey(i, j)]; }; /** * Set a value. * @method set * @param {Number} i * @param {Number} j * @param {Number} value */ TupleDictionary.prototype.set = function(i, j, value) { if(!value){ throw new Error(""No data!""); } var key = this.getKey(i, j); // Check if key already exists if(!this.data[key]){ this.keys.push(key); } this.data[key] = value; return key; }; /** * Remove all data. * @method reset */ TupleDictionary.prototype.reset = function() { var data = this.data, keys = this.keys; var l = keys.length; while(l--) { delete data[keys[l]]; } keys.length = 0; }; /** * Copy another TupleDictionary. Note that all data in this dictionary will be removed. * @method copy * @param {TupleDictionary} dict The TupleDictionary to copy into this one. */ TupleDictionary.prototype.copy = function(dict) { this.reset(); Utils.appendArray(this.keys, dict.keys); var l = dict.keys.length; while(l--){ var key = dict.keys[l]; this.data[key] = dict.data[key]; } }; // overlapkeeper/OverlapKeeperRecordPool.js var OverlapKeeperRecord = require('./OverlapKeeperRecord'); var Pool = require('./Pool'); module.exports = OverlapKeeperRecordPool; /** * @class */ function OverlapKeeperRecordPool() { Pool.apply(this, arguments); } OverlapKeeperRecordPool.prototype = new Pool(); OverlapKeeperRecordPool.prototype.constructor = OverlapKeeperRecordPool; /** * @method create * @return {OverlapKeeperRecord} */ OverlapKeeperRecordPool.prototype.create = function () { return new OverlapKeeperRecord(); }; /** * @method destroy * @param {OverlapKeeperRecord} record * @return {OverlapKeeperRecordPool} */ OverlapKeeperRecordPool.prototype.destroy = function (record) { record.bodyA = record.bodyB = record.shapeA = record.shapeB = null; return this; }; // overlapkeeper/OverlapKeeper.js var TupleDictionary = require('./TupleDictionary'); var OverlapKeeperRecordPool = require('./OverlapKeeperRecordPool'); module.exports = OverlapKeeper; /** * Keeps track of overlaps in the current state and the last step state. * @class OverlapKeeper * @constructor */ function OverlapKeeper() { this.overlappingShapesLastState = new TupleDictionary(); this.overlappingShapesCurrentState = new TupleDictionary(); this.recordPool = new OverlapKeeperRecordPool({ size: 16 }); this.tmpDict = new TupleDictionary(); this.tmpArray1 = []; } /** * Ticks one step forward in time. This will move the current overlap state to the ""old"" overlap state, and create a new one as current. * @method tick */ OverlapKeeper.prototype.tick = function() { var last = this.overlappingShapesLastState; var current = this.overlappingShapesCurrentState; // Save old objects into pool var l = last.keys.length; while(l--){ var key = last.keys[l]; var lastObject = last.getByKey(key); if(lastObject){ // The record is only used in the ""last"" dict, and will be removed. We might as well pool it. this.recordPool.release(lastObject); } } // Clear last object last.reset(); // Transfer from new object to old last.copy(current); // Clear current object current.reset(); }; /** * @method setOverlapping * @param {Body} bodyA * @param {Body} shapeA * @param {Body} bodyB * @param {Body} shapeB */ OverlapKeeper.prototype.setOverlapping = function(bodyA, shapeA, bodyB, shapeB) { var current = this.overlappingShapesCurrentState; // Store current contact state if(!current.get(shapeA.id, shapeB.id)){ var data = this.recordPool.get(); data.set(bodyA, shapeA, bodyB, shapeB); current.set(shapeA.id, shapeB.id, data); } }; OverlapKeeper.prototype.getNewOverlaps = function(result){ return this.getDiff(this.overlappingShapesLastState, this.overlappingShapesCurrentState, result); }; OverlapKeeper.prototype.getEndOverlaps = function(result){ return this.getDiff(this.overlappingShapesCurrentState, this.overlappingShapesLastState, result); }; /** * Checks if two bodies are currently overlapping. * @method bodiesAreOverlapping * @param {Body} bodyA * @param {Body} bodyB * @return {boolean} */ OverlapKeeper.prototype.bodiesAreOverlapping = function(bodyA, bodyB){ var current = this.overlappingShapesCurrentState; var l = current.keys.length; while(l--){ var key = current.keys[l]; var data = current.data[key]; if((data.bodyA === bodyA && data.bodyB === bodyB) || data.bodyA === bodyB && data.bodyB === bodyA){ return true; } } return false; }; OverlapKeeper.prototype.getDiff = function(dictA, dictB, result){ var result = result || []; var last = dictA; var current = dictB; result.length = 0; var l = current.keys.length; while(l--){ var key = current.keys[l]; var data = current.data[key]; if(!data){ throw new Error('Key '+key+' had no data!'); } var lastData = last.data[key]; if(!lastData){ // Not overlapping in last state, but in current. result.push(data); } } return result; }; OverlapKeeper.prototype.isNewOverlap = function(shapeA, shapeB){ var idA = shapeA.id|0, idB = shapeB.id|0; var last = this.overlappingShapesLastState; var current = this.overlappingShapesCurrentState; // Not in last but in new return !!!last.get(idA, idB) && !!current.get(idA, idB); }; OverlapKeeper.prototype.getNewBodyOverlaps = function(result){ this.tmpArray1.length = 0; var overlaps = this.getNewOverlaps(this.tmpArray1); return this.getBodyDiff(overlaps, result); }; OverlapKeeper.prototype.getEndBodyOverlaps = function(result){ this.tmpArray1.length = 0; var overlaps = this.getEndOverlaps(this.tmpArray1); return this.getBodyDiff(overlaps, result); }; OverlapKeeper.prototype.getBodyDiff = function(overlaps, result){ result = result || []; var accumulator = this.tmpDict; var l = overlaps.length; while(l--){ var data = overlaps[l]; // Since we use body id's for the accumulator, these will be a subset of the original one accumulator.set(data.bodyA.id|0, data.bodyB.id|0, data); } l = accumulator.keys.length; while(l--){ var data = accumulator.getByKey(accumulator.keys[l]); if(data){ result.push(data.bodyA, data.bodyB); } } accumulator.reset(); return result; }; // overlapkeeper/Utils.js /* global P2_ARRAY_TYPE */ module.exports = Utils; /** * Misc utility functions * @class Utils * @constructor */ function Utils(){} /** * Append the values in array b to the array a. See this for an explanation. * @method appendArray * @static * @param {Array} a * @param {Array} b */ Utils.appendArray = function(a,b){ if (b.length < 150000) { a.push.apply(a, b); } else { for (var i = 0, len = b.length; i !== len; ++i) { a.push(b[i]); } } }; /** * Garbage free Array.splice(). Does not allocate a new array. * @method splice * @static * @param {Array} array * @param {Number} index * @param {Number} howmany */ Utils.splice = function(array,index,howmany){ howmany = howmany || 1; for (var i=index, len=array.length-howmany; i < len; i++){ array[i] = array[i + howmany]; } array.length = len; }; /** * Remove an element from an array, if the array contains the element. * @method arrayRemove * @static * @param {Array} array * @param {Number} element */ Utils.arrayRemove = function(array, element){ var idx = array.indexOf(element); if(idx!==-1){ Utils.splice(array, idx, 1); } }; /** * The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below. * @static * @property {function} ARRAY_TYPE * @example * * */ if(typeof P2_ARRAY_TYPE !== 'undefined') { Utils.ARRAY_TYPE = P2_ARRAY_TYPE; } else if (typeof Float32Array !== 'undefined'){ Utils.ARRAY_TYPE = Float32Array; } else { Utils.ARRAY_TYPE = Array; } /** * Extend an object with the properties of another * @static * @method extend * @param {object} a * @param {object} b */ Utils.extend = function(a,b){ for(var key in b){ a[key] = b[key]; } }; /** * Shallow clone an object. Returns a new object instance with the same properties as the input instance. * @static * @method shallowClone * @param {object} obj */ Utils.shallowClone = function(obj){ var newObj = {}; Utils.extend(newObj, obj); return newObj; }; /** * Extend an options object with default values. * @deprecated Not used internally, will be removed. * @static * @method defaults * @param {object} options The options object. May be falsy: in this case, a new object is created and returned. * @param {object} defaults An object containing default values. * @return {object} The modified options object. */ Utils.defaults = function(options, defaults){ console.warn('Utils.defaults is deprecated.'); options = options || {}; for(var key in defaults){ if(!(key in options)){ options[key] = defaults[key]; } } return options; }; ",6,539,JavaScript synergy,./ProjectTest/JavaScript/synergy.js,"// synergy/attribute.js import { isPrimitive, typeOf } from ""./helpers.js"" const pascalToKebab = (string) => string.replace(/[\w]([A-Z])/g, function (m) { return m[0] + ""-"" + m[1].toLowerCase() }) const kebabToPascal = (string) => string.replace(/[\w]-([\w])/g, function (m) { return m[0] + m[2].toUpperCase() }) const parseStyles = (value) => { let type = typeof value if (type === ""string"") return value.split("";"").reduce((o, value) => { const [k, v] = value.split("":"").map((v) => v.trim()) if (k) o[k] = v return o }, {}) if (type === ""object"") return value return {} } const joinStyles = (value) => Object.entries(value) .map(([k, v]) => `${k}: ${v};`) .join("" "") const convertStyles = (o) => Object.keys(o).reduce((a, k) => { a[pascalToKebab(k)] = o[k] return a }, {}) export const applyAttribute = (node, name, value) => { if (name === ""style"") { value = joinStyles( convertStyles({ ...parseStyles(node.getAttribute(""style"")), ...parseStyles(value), }) ) } else if (name === ""class"") { switch (typeOf(value)) { case ""Array"": value = value.join("" "") break case ""Object"": value = Object.keys(value) .reduce((a, k) => { if (value[k]) a.push(k) return a }, []) .join("" "") break } } else if (!isPrimitive(value)) { return (node[kebabToPascal(name)] = value) } name = pascalToKebab(name) if (typeof value === ""boolean"") { if (name.startsWith(""aria-"")) { value = """" + value } else if (value) { value = """" } } let current = node.getAttribute(name) if (value === current) return if (typeof value === ""string"" || typeof value === ""number"") { node.setAttribute(name, value) } else { node.removeAttribute(name) } } // synergy/css.js function nextWord(css, count) { return css.slice(count - 1).split(/[\s+|\n+|,]/)[0] } function nextOpenBrace(css, count) { let index = css.slice(count - 1).indexOf(""{"") if (index > -1) { return count + index } } export function prefixSelectors(prefix, css) { let insideBlock = false let look = true let output = """" let count = 0 let skip = false for (let char of css) { if (char === ""@"" && nextWord(css, count + 1) === ""@media"") { skip = nextOpenBrace(css, count) } if (skip) { if (skip === count) skip = false } if (!skip) { if (char === ""}"") { insideBlock = false look = true } else if (char === "","") { look = true } else if (char === ""{"") { insideBlock = true } else if (look && !insideBlock && !char.match(/\s/)) { let w = nextWord(css, count + 1) // console.log({ w }) if ( w !== prefix && w.charAt(0) !== ""@"" && w.charAt(0) !== "":"" && w.charAt(0) !== ""*"" && w !== ""html"" && w !== ""body"" ) { output += prefix + "" "" } look = false } } output += char count += 1 } return output } export function appendStyles(name, css) { if (document.querySelector(`style#${name}`)) return const el = document.createElement(""style"") el.id = name el.innerHTML = prefixSelectors(name, css) document.head.appendChild(el) } // synergy/helpers.js export const wrapToken = (v) => { v = v.trim() if (v.startsWith(""{{"")) return v return `{{${v}}}` } export const last = (v = []) => v[v.length - 1] export const isWhitespace = (node) => { return node.nodeType === node.TEXT_NODE && node.nodeValue.trim() === """" } export const walk = (node, callback, deep = true) => { if (!node) return // if (node.matches?.(`script[type=""application/synergy""]`)) // return walk(node.nextSibling, callback, deep) if (!isWhitespace(node)) { let v = callback(node) if (v === false) return if (v?.nodeName) return walk(v, callback, deep) } if (deep) walk(node.firstChild, callback, deep) walk(node.nextSibling, callback, deep) } const transformBrackets = (str = """") => { let parts = str.split(/(\[[^\]]+\])/).filter((v) => v) return parts.reduce((a, part) => { let v = part.charAt(0) === ""["" ? ""."" + part.replace(/\./g, "":"") : part return a + v }, """") } const getTarget = (path, target) => { let parts = transformBrackets(path) .split(""."") .map((k) => { if (k.charAt(0) === ""["") { let p = k.slice(1, -1).replace(/:/g, ""."") return getValueAtPath(p, target) } else { return k } }) let t = parts.slice(0, -1).reduce((o, k) => { return o && o[k] }, target) || target return [t, last(parts)] } export const getValueAtPath = (path, target) => { let [a, b] = getTarget(path, target) let v = a?.[b] if (typeof v === ""function"") return v.bind(a) return v } export const setValueAtPath = (path, value, target) => { let [a, b] = getTarget(path, target) return (a[b] = value) } export const fragmentFromTemplate = (v) => { if (typeof v === ""string"") { if (v.charAt(0) === ""#"") { v = document.querySelector(v) } else { let tpl = document.createElement(""template"") tpl.innerHTML = v.trim() return tpl.content.cloneNode(true) } } if (v.nodeName === ""TEMPLATE"") return v.cloneNode(true).content if (v.nodeName === ""defs"") return v.firstElementChild.cloneNode(true) } export const debounce = (fn) => { let wait = false let invoke = false return () => { if (wait) { invoke = true } else { wait = true fn() requestAnimationFrame(() => { if (invoke) fn() wait = false }) } } } export const isPrimitive = (v) => v === null || typeof v !== ""object"" export const typeOf = (v) => Object.prototype.toString.call(v).match(/\s(.+[^\]])/)[1] export const pascalToKebab = (string) => string.replace(/[\w]([A-Z])/g, function (m) { return m[0] + ""-"" + m[1].toLowerCase() }) export const kebabToPascal = (string) => string.replace(/[\w]-([\w])/g, function (m) { return m[0] + m[2].toUpperCase() }) export const applyAttribute = (node, name, value) => { name = pascalToKebab(name) if (typeof value === ""boolean"") { if (name.startsWith(""aria-"")) { value = """" + value } else if (value) { value = """" } } if (typeof value === ""string"" || typeof value === ""number"") { node.setAttribute(name, value) } else { node.removeAttribute(name) } } export const attributeToProp = (k, v) => { let name = kebabToPascal(k) if (v === """") v = true if (k.startsWith(""aria-"")) { if (v === ""true"") v = true if (v === ""false"") v = false } return { name, value: v, } } export function getDataScript(node) { return node.querySelector( `script[type=""application/synergy""][id=""${node.nodeName}""]` ) } export function createDataScript(node) { let ds = document.createElement(""script"") ds.setAttribute(""type"", ""application/synergy"") ds.setAttribute(""id"", node.nodeName) node.append(ds) return ds } // synergy/partial.js import { appendStyles } from ""./css.js"" export const partials = {} export const partial = (name, html, css) => { if (css) appendStyles(name, css) partials[name.toUpperCase()] = html } // synergy/context.js import { getValueAtPath, isPrimitive } from ""./helpers.js"" const handler = ({ path, identifier, key, index, i, k }) => ({ get(target, property) { let x = getValueAtPath(path, target) // x === the collection if (property === identifier) { for (let n in x) { let v = x[n] if (key) { if (v[key] === k) return v } else { if (n == i) return v } } } if (property === index) { for (let n in x) { let v = x[n] if (key) { if (v[key] === k) return n } else { if (n == i) return n } } } let t = key ? x.find((v) => v[key] === k) : x?.[i] if (t?.hasOwnProperty?.(property)) return t[property] return Reflect.get(...arguments) }, set(target, property, value) { let x = getValueAtPath(path, target) let t = key ? x.find((v) => v[key] === k) : x[i] if (t && !isPrimitive(t)) { t[property] = value return true } return Reflect.set(...arguments) }, }) export const createContext = (v = []) => { let context = v return { get: () => context, push: (v) => context.push(v), wrap: (state) => { return context.reduce( (target, ctx) => new Proxy(target, handler(ctx)), state ) }, } } ",5,374,JavaScript easing,./ProjectTest/JavaScript/easing.js,"// easing/BezierEasing.js /** * @author pschroen / https://ufo.ai/ * * Based on https://github.com/gre/bezier-easing */ // These values are established by empiricism with tests (tradeoff: performance VS precision) const NEWTON_ITERATIONS = 4; const NEWTON_MIN_SLOPE = 0.001; const SUBDIVISION_PRECISION = 0.0000001; const SUBDIVISION_MAX_ITERATIONS = 10; const kSplineTableSize = 11; const kSampleStepSize = 1 / (kSplineTableSize - 1); function A(aA1, aA2) { return 1 - 3 * aA2 + 3 * aA1; } function B(aA1, aA2) { return 3 * aA2 - 6 * aA1; } function C(aA1) { return 3 * aA1; } // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2 function calcBezier(aT, aA1, aA2) { return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT; } // Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2 function getSlope(aT, aA1, aA2) { return 3 * A(aA1, aA2) * aT * aT + 2 * B(aA1, aA2) * aT + C(aA1); } function binarySubdivide(aX, aA, aB, mX1, mX2) { let currentX; let currentT; let i = 0; do { currentT = aA + (aB - aA) / 2; currentX = calcBezier(currentT, mX1, mX2) - aX; if (currentX > 0) { aB = currentT; } else { aA = currentT; } } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS); return currentT; } function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) { for (let i = 0; i < NEWTON_ITERATIONS; i++) { const currentSlope = getSlope(aGuessT, mX1, mX2); if (currentSlope === 0) { return aGuessT; } const currentX = calcBezier(aGuessT, mX1, mX2) - aX; aGuessT -= currentX / currentSlope; } return aGuessT; } function LinearEasing(x) { return x; } export default function bezier(mX1, mY1, mX2, mY2) { if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) { throw new Error('Bezier x values must be in [0, 1] range'); } if (mX1 === mY1 && mX2 === mY2) { return LinearEasing; } // Precompute samples table const sampleValues = new Float32Array(kSplineTableSize); for (let i = 0; i < kSplineTableSize; i++) { sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2); } function getTForX(aX) { let intervalStart = 0; let currentSample = 1; const lastSample = kSplineTableSize - 1; for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; currentSample++) { intervalStart += kSampleStepSize; } currentSample--; // Interpolate to provide an initial guess for t const dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]); const guessForT = intervalStart + dist * kSampleStepSize; const initialSlope = getSlope(guessForT, mX1, mX2); if (initialSlope >= NEWTON_MIN_SLOPE) { return newtonRaphsonIterate(aX, guessForT, mX1, mX2); } else if (initialSlope === 0) { return guessForT; } else { return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2); } } return function BezierEasing(x) { // Because JavaScript numbers are imprecise, we should guarantee the extremes are right if (x === 0 || x === 1) { return x; } return calcBezier(getTForX(x), mY1, mY2); }; } // easing/Easing.js /** * @author pschroen / https://ufo.ai/ * * Based on https://github.com/danro/easing-js * Based on https://github.com/CreateJS/TweenJS * Based on https://github.com/tweenjs/tween.js * Based on https://easings.net/ */ import BezierEasing from './BezierEasing.js'; export class Easing { static linear(t) { return t; } static easeInQuad(t) { return t * t; } static easeOutQuad(t) { return t * (2 - t); } static easeInOutQuad(t) { if ((t *= 2) < 1) { return 0.5 * t * t; } return -0.5 * (--t * (t - 2) - 1); } static easeInCubic(t) { return t * t * t; } static easeOutCubic(t) { return --t * t * t + 1; } static easeInOutCubic(t) { if ((t *= 2) < 1) { return 0.5 * t * t * t; } return 0.5 * ((t -= 2) * t * t + 2); } static easeInQuart(t) { return t * t * t * t; } static easeOutQuart(t) { return 1 - --t * t * t * t; } static easeInOutQuart(t) { if ((t *= 2) < 1) { return 0.5 * t * t * t * t; } return -0.5 * ((t -= 2) * t * t * t - 2); } static easeInQuint(t) { return t * t * t * t * t; } static easeOutQuint(t) { return --t * t * t * t * t + 1; } static easeInOutQuint(t) { if ((t *= 2) < 1) { return 0.5 * t * t * t * t * t; } return 0.5 * ((t -= 2) * t * t * t * t + 2); } static easeInSine(t) { return 1 - Math.sin(((1 - t) * Math.PI) / 2); } static easeOutSine(t) { return Math.sin((t * Math.PI) / 2); } static easeInOutSine(t) { return 0.5 * (1 - Math.sin(Math.PI * (0.5 - t))); } static easeInExpo(t) { return t === 0 ? 0 : Math.pow(1024, t - 1); } static easeOutExpo(t) { return t === 1 ? 1 : 1 - Math.pow(2, -10 * t); } static easeInOutExpo(t) { if (t === 0 || t === 1) { return t; } if ((t *= 2) < 1) { return 0.5 * Math.pow(1024, t - 1); } return 0.5 * (-Math.pow(2, -10 * (t - 1)) + 2); } static easeInCirc(t) { return 1 - Math.sqrt(1 - t * t); } static easeOutCirc(t) { return Math.sqrt(1 - --t * t); } static easeInOutCirc(t) { if ((t *= 2) < 1) { return -0.5 * (Math.sqrt(1 - t * t) - 1); } return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1); } static easeInBack(t) { const s = 1.70158; return t === 1 ? 1 : t * t * ((s + 1) * t - s); } static easeOutBack(t) { const s = 1.70158; return t === 0 ? 0 : --t * t * ((s + 1) * t + s) + 1; } static easeInOutBack(t) { const s = 1.70158 * 1.525; if ((t *= 2) < 1) { return 0.5 * (t * t * ((s + 1) * t - s)); } return 0.5 * ((t -= 2) * t * ((s + 1) * t + s) + 2); } static easeInElastic(t, amplitude = 1, period = 0.3) { if (t === 0 || t === 1) { return t; } const pi2 = Math.PI * 2; const s = period / pi2 * Math.asin(1 / amplitude); return -(amplitude * Math.pow(2, 10 * --t) * Math.sin((t - s) * pi2 / period)); } static easeOutElastic(t, amplitude = 1, period = 0.3) { if (t === 0 || t === 1) { return t; } const pi2 = Math.PI * 2; const s = period / pi2 * Math.asin(1 / amplitude); return amplitude * Math.pow(2, -10 * t) * Math.sin((t - s) * pi2 / period) + 1; } static easeInOutElastic(t, amplitude = 1, period = 0.3 * 1.5) { if (t === 0 || t === 1) { return t; } const pi2 = Math.PI * 2; const s = period / pi2 * Math.asin(1 / amplitude); if ((t *= 2) < 1) { return -0.5 * (amplitude * Math.pow(2, 10 * --t) * Math.sin((t - s) * pi2 / period)); } return amplitude * Math.pow(2, -10 * --t) * Math.sin((t - s) * pi2 / period) * 0.5 + 1; } static easeInBounce(t) { return 1 - this.easeOutBounce(1 - t); } static easeOutBounce(t) { const n1 = 7.5625; const d1 = 2.75; if (t < 1 / d1) { return n1 * t * t; } else if (t < 2 / d1) { return n1 * (t -= 1.5 / d1) * t + 0.75; } else if (t < 2.5 / d1) { return n1 * (t -= 2.25 / d1) * t + 0.9375; } else { return n1 * (t -= 2.625 / d1) * t + 0.984375; } } static easeInOutBounce(t) { if (t < 0.5) { return this.easeInBounce(t * 2) * 0.5; } return this.easeOutBounce(t * 2 - 1) * 0.5 + 0.5; } static addBezier(name, mX1, mY1, mX2, mY2) { this[name] = BezierEasing(mX1, mY1, mX2, mY2); } } ",2,341,JavaScript check,./ProjectTest/JavaScript/check.js,"// check/check.js import { isSubclass } from './subclass.js' // Confirm `custom` option is valid export const checkCustom = (custom, ParentError) => { if (typeof custom !== 'function') { throw new TypeError( `The ""custom"" class of ""${ParentError.name}.subclass()"" must be a class: ${custom}`, ) } checkParent(custom, ParentError) checkPrototype(custom, ParentError) } // We do not allow passing `ParentError` without extending from it, since // `undefined` can be used for it instead. // We do not allow extending from `ParentError` indirectly: // - This promotes using subclassing through `ErrorClass.subclass()`, since it // reduces the risk of user instantiating unregistered class // - This promotes `ErrorClass.subclass()` as a pattern for subclassing, to // reduce the risk of directly extending a registered class without // registering the subclass const checkParent = (custom, ParentError) => { if (custom === ParentError) { throw new TypeError( `The ""custom"" class of ""${ParentError.name}.subclass()"" must extend from ${ParentError.name}, but not be ${ParentError.name} itself.`, ) } if (!isSubclass(custom, ParentError)) { throw new TypeError( `The ""custom"" class of ""${ParentError.name}.subclass()"" must extend from ${ParentError.name}.`, ) } if (Object.getPrototypeOf(custom) !== ParentError) { throw new TypeError( `The ""custom"" class of ""${ParentError.name}.subclass()"" must extend directly from ${ParentError.name}.`, ) } } const checkPrototype = (custom, ParentError) => { if (typeof custom.prototype !== 'object' || custom.prototype === null) { throw new TypeError( `The ""custom"" class's prototype of ""${ParentError.name}.subclass()"" is invalid: ${custom.prototype}`, ) } if (custom.prototype.constructor !== custom) { throw new TypeError( `The ""custom"" class of ""${ParentError.name}.subclass()"" has an invalid ""constructor"" property.`, ) } } // check/subclass.js // Check if `ErrorClass` is a subclass of `ParentClass`. // We encourage `instanceof` over `error.name` for checking since this: // - Prevents name collisions with other libraries // - Allows checking if any error came from a given library // - Includes error classes in the exported interface explicitly instead of // implicitly, so that users are mindful about breaking changes // - Bundles classes with TypeScript documentation, types and autocompletion // - Encourages documenting error types // Checking class with `error.name` is still supported, but not documented // - Since it is widely used and can be better in specific cases // This also provides with namespacing, i.e. prevents classes of the same name // but in different libraries to be considered equal. As opposed to the // following alternatives: // - Namespacing all error names with a common prefix since this: // - Leads to verbose error names // - Requires either an additional option, or guessing ambiguously whether // error names are meant to include a namespace prefix // - Using a separate `namespace` property: this adds too much complexity and // is less standard than `instanceof` export const isSubclass = (ErrorClass, ParentClass) => ParentClass === ErrorClass || isProtoOf.call(ParentClass, ErrorClass) const { isPrototypeOf: isProtoOf } = Object.prototype ",2,78,JavaScript animation,./ProjectTest/JavaScript/animation.js,"// animation/AnimationAction.js import { WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, LoopPingPong, LoopOnce, LoopRepeat, NormalAnimationBlendMode, AdditiveAnimationBlendMode } from './constants.js'; class AnimationAction { constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) { this._mixer = mixer; this._clip = clip; this._localRoot = localRoot; this.blendMode = blendMode; const tracks = clip.tracks, nTracks = tracks.length, interpolants = new Array( nTracks ); const interpolantSettings = { endingStart: ZeroCurvatureEnding, endingEnd: ZeroCurvatureEnding }; for ( let i = 0; i !== nTracks; ++ i ) { const interpolant = tracks[ i ].createInterpolant( null ); interpolants[ i ] = interpolant; interpolant.settings = interpolantSettings; } this._interpolantSettings = interpolantSettings; this._interpolants = interpolants; // bound by the mixer // inside: PropertyMixer (managed by the mixer) this._propertyBindings = new Array( nTracks ); this._cacheIndex = null; // for the memory manager this._byClipCacheIndex = null; // for the memory manager this._timeScaleInterpolant = null; this._weightInterpolant = null; this.loop = LoopRepeat; this._loopCount = - 1; // global mixer time when the action is to be started // it's set back to 'null' upon start of the action this._startTime = null; // scaled local time of the action // gets clamped or wrapped to 0..clip.duration according to loop this.time = 0; this.timeScale = 1; this._effectiveTimeScale = 1; this.weight = 1; this._effectiveWeight = 1; this.repetitions = Infinity; // no. of repetitions when looping this.paused = false; // true -> zero effective time scale this.enabled = true; // false -> zero effective weight this.clampWhenFinished = false;// keep feeding the last frame? this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate this.zeroSlopeAtEnd = true;// clips for start, loop and end } // State & Scheduling play() { this._mixer._activateAction( this ); return this; } stop() { this._mixer._deactivateAction( this ); return this.reset(); } reset() { this.paused = false; this.enabled = true; this.time = 0; // restart clip this._loopCount = - 1;// forget previous loops this._startTime = null;// forget scheduling return this.stopFading().stopWarping(); } isRunning() { return this.enabled && ! this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction( this ); } // return true when play has been called isScheduled() { return this._mixer._isActiveAction( this ); } startAt( time ) { this._startTime = time; return this; } setLoop( mode, repetitions ) { this.loop = mode; this.repetitions = repetitions; return this; } // Weight // set the weight stopping any scheduled fading // although .enabled = false yields an effective weight of zero, this // method does *not* change .enabled, because it would be confusing setEffectiveWeight( weight ) { this.weight = weight; // note: same logic as when updated at runtime this._effectiveWeight = this.enabled ? weight : 0; return this.stopFading(); } // return the weight considering fading and .enabled getEffectiveWeight() { return this._effectiveWeight; } fadeIn( duration ) { return this._scheduleFading( duration, 0, 1 ); } fadeOut( duration ) { return this._scheduleFading( duration, 1, 0 ); } crossFadeFrom( fadeOutAction, duration, warp ) { fadeOutAction.fadeOut( duration ); this.fadeIn( duration ); if ( warp ) { const fadeInDuration = this._clip.duration, fadeOutDuration = fadeOutAction._clip.duration, startEndRatio = fadeOutDuration / fadeInDuration, endStartRatio = fadeInDuration / fadeOutDuration; fadeOutAction.warp( 1.0, startEndRatio, duration ); this.warp( endStartRatio, 1.0, duration ); } return this; } crossFadeTo( fadeInAction, duration, warp ) { return fadeInAction.crossFadeFrom( this, duration, warp ); } stopFading() { const weightInterpolant = this._weightInterpolant; if ( weightInterpolant !== null ) { this._weightInterpolant = null; this._mixer._takeBackControlInterpolant( weightInterpolant ); } return this; } // Time Scale Control // set the time scale stopping any scheduled warping // although .paused = true yields an effective time scale of zero, this // method does *not* change .paused, because it would be confusing setEffectiveTimeScale( timeScale ) { this.timeScale = timeScale; this._effectiveTimeScale = this.paused ? 0 : timeScale; return this.stopWarping(); } // return the time scale considering warping and .paused getEffectiveTimeScale() { return this._effectiveTimeScale; } setDuration( duration ) { this.timeScale = this._clip.duration / duration; return this.stopWarping(); } syncWith( action ) { this.time = action.time; this.timeScale = action.timeScale; return this.stopWarping(); } halt( duration ) { return this.warp( this._effectiveTimeScale, 0, duration ); } warp( startTimeScale, endTimeScale, duration ) { const mixer = this._mixer, now = mixer.time, timeScale = this.timeScale; let interpolant = this._timeScaleInterpolant; if ( interpolant === null ) { interpolant = mixer._lendControlInterpolant(); this._timeScaleInterpolant = interpolant; } const times = interpolant.parameterPositions, values = interpolant.sampleValues; times[ 0 ] = now; times[ 1 ] = now + duration; values[ 0 ] = startTimeScale / timeScale; values[ 1 ] = endTimeScale / timeScale; return this; } stopWarping() { const timeScaleInterpolant = this._timeScaleInterpolant; if ( timeScaleInterpolant !== null ) { this._timeScaleInterpolant = null; this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); } return this; } // Object Accessors getMixer() { return this._mixer; } getClip() { return this._clip; } getRoot() { return this._localRoot || this._mixer._root; } // Interna _update( time, deltaTime, timeDirection, accuIndex ) { // called by the mixer if ( ! this.enabled ) { // call ._updateWeight() to update ._effectiveWeight this._updateWeight( time ); return; } const startTime = this._startTime; if ( startTime !== null ) { // check for scheduled start of action const timeRunning = ( time - startTime ) * timeDirection; if ( timeRunning < 0 || timeDirection === 0 ) { deltaTime = 0; } else { this._startTime = null; // unschedule deltaTime = timeDirection * timeRunning; } } // apply time scale and advance time deltaTime *= this._updateTimeScale( time ); const clipTime = this._updateTime( deltaTime ); // note: _updateTime may disable the action resulting in // an effective weight of 0 const weight = this._updateWeight( time ); if ( weight > 0 ) { const interpolants = this._interpolants; const propertyMixers = this._propertyBindings; switch ( this.blendMode ) { case AdditiveAnimationBlendMode: for ( let j = 0, m = interpolants.length; j !== m; ++ j ) { interpolants[ j ].evaluate( clipTime ); propertyMixers[ j ].accumulateAdditive( weight ); } break; case NormalAnimationBlendMode: default: for ( let j = 0, m = interpolants.length; j !== m; ++ j ) { interpolants[ j ].evaluate( clipTime ); propertyMixers[ j ].accumulate( accuIndex, weight ); } } } } _updateWeight( time ) { let weight = 0; if ( this.enabled ) { weight = this.weight; const interpolant = this._weightInterpolant; if ( interpolant !== null ) { const interpolantValue = interpolant.evaluate( time )[ 0 ]; weight *= interpolantValue; if ( time > interpolant.parameterPositions[ 1 ] ) { this.stopFading(); if ( interpolantValue === 0 ) { // faded out, disable this.enabled = false; } } } } this._effectiveWeight = weight; return weight; } _updateTimeScale( time ) { let timeScale = 0; if ( ! this.paused ) { timeScale = this.timeScale; const interpolant = this._timeScaleInterpolant; if ( interpolant !== null ) { const interpolantValue = interpolant.evaluate( time )[ 0 ]; timeScale *= interpolantValue; if ( time > interpolant.parameterPositions[ 1 ] ) { this.stopWarping(); if ( timeScale === 0 ) { // motion has halted, pause this.paused = true; } else { // warp done - apply final time scale this.timeScale = timeScale; } } } } this._effectiveTimeScale = timeScale; return timeScale; } _updateTime( deltaTime ) { const duration = this._clip.duration; const loop = this.loop; let time = this.time + deltaTime; let loopCount = this._loopCount; const pingPong = ( loop === LoopPingPong ); if ( deltaTime === 0 ) { if ( loopCount === - 1 ) return time; return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time; } if ( loop === LoopOnce ) { if ( loopCount === - 1 ) { // just started this._loopCount = 0; this._setEndings( true, true, false ); } handle_stop: { if ( time >= duration ) { time = duration; } else if ( time < 0 ) { time = 0; } else { this.time = time; break handle_stop; } if ( this.clampWhenFinished ) this.paused = true; else this.enabled = false; this.time = time; this._mixer.dispatchEvent( { type: 'finished', action: this, direction: deltaTime < 0 ? - 1 : 1 } ); } } else { // repetitive Repeat or PingPong if ( loopCount === - 1 ) { // just started if ( deltaTime >= 0 ) { loopCount = 0; this._setEndings( true, this.repetitions === 0, pingPong ); } else { // when looping in reverse direction, the initial // transition through zero counts as a repetition, // so leave loopCount at -1 this._setEndings( this.repetitions === 0, true, pingPong ); } } if ( time >= duration || time < 0 ) { // wrap around const loopDelta = Math.floor( time / duration ); // signed time -= duration * loopDelta; loopCount += Math.abs( loopDelta ); const pending = this.repetitions - loopCount; if ( pending <= 0 ) { // have to stop (switch state, clamp time, fire event) if ( this.clampWhenFinished ) this.paused = true; else this.enabled = false; time = deltaTime > 0 ? duration : 0; this.time = time; this._mixer.dispatchEvent( { type: 'finished', action: this, direction: deltaTime > 0 ? 1 : - 1 } ); } else { // keep running if ( pending === 1 ) { // entering the last round const atStart = deltaTime < 0; this._setEndings( atStart, ! atStart, pingPong ); } else { this._setEndings( false, false, pingPong ); } this._loopCount = loopCount; this.time = time; this._mixer.dispatchEvent( { type: 'loop', action: this, loopDelta: loopDelta } ); } } else { this.time = time; } if ( pingPong && ( loopCount & 1 ) === 1 ) { // invert time for the ""pong round"" return duration - time; } } return time; } _setEndings( atStart, atEnd, pingPong ) { const settings = this._interpolantSettings; if ( pingPong ) { settings.endingStart = ZeroSlopeEnding; settings.endingEnd = ZeroSlopeEnding; } else { // assuming for LoopOnce atStart == atEnd == true if ( atStart ) { settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; } else { settings.endingStart = WrapAroundEnding; } if ( atEnd ) { settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; } else { settings.endingEnd = WrapAroundEnding; } } } _scheduleFading( duration, weightNow, weightThen ) { const mixer = this._mixer, now = mixer.time; let interpolant = this._weightInterpolant; if ( interpolant === null ) { interpolant = mixer._lendControlInterpolant(); this._weightInterpolant = interpolant; } const times = interpolant.parameterPositions, values = interpolant.sampleValues; times[ 0 ] = now; values[ 0 ] = weightNow; times[ 1 ] = now + duration; values[ 1 ] = weightThen; return this; } } export { AnimationAction }; // animation/constants.js export const REVISION = '172dev'; export const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; export const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; export const CullFaceNone = 0; export const CullFaceBack = 1; export const CullFaceFront = 2; export const CullFaceFrontBack = 3; export const BasicShadowMap = 0; export const PCFShadowMap = 1; export const PCFSoftShadowMap = 2; export const VSMShadowMap = 3; export const FrontSide = 0; export const BackSide = 1; export const DoubleSide = 2; export const NoBlending = 0; export const NormalBlending = 1; export const AdditiveBlending = 2; export const SubtractiveBlending = 3; export const MultiplyBlending = 4; export const CustomBlending = 5; export const AddEquation = 100; export const SubtractEquation = 101; export const ReverseSubtractEquation = 102; export const MinEquation = 103; export const MaxEquation = 104; export const ZeroFactor = 200; export const OneFactor = 201; export const SrcColorFactor = 202; export const OneMinusSrcColorFactor = 203; export const SrcAlphaFactor = 204; export const OneMinusSrcAlphaFactor = 205; export const DstAlphaFactor = 206; export const OneMinusDstAlphaFactor = 207; export const DstColorFactor = 208; export const OneMinusDstColorFactor = 209; export const SrcAlphaSaturateFactor = 210; export const ConstantColorFactor = 211; export const OneMinusConstantColorFactor = 212; export const ConstantAlphaFactor = 213; export const OneMinusConstantAlphaFactor = 214; export const NeverDepth = 0; export const AlwaysDepth = 1; export const LessDepth = 2; export const LessEqualDepth = 3; export const EqualDepth = 4; export const GreaterEqualDepth = 5; export const GreaterDepth = 6; export const NotEqualDepth = 7; export const MultiplyOperation = 0; export const MixOperation = 1; export const AddOperation = 2; export const NoToneMapping = 0; export const LinearToneMapping = 1; export const ReinhardToneMapping = 2; export const CineonToneMapping = 3; export const ACESFilmicToneMapping = 4; export const CustomToneMapping = 5; export const AgXToneMapping = 6; export const NeutralToneMapping = 7; export const AttachedBindMode = 'attached'; export const DetachedBindMode = 'detached'; export const UVMapping = 300; export const CubeReflectionMapping = 301; export const CubeRefractionMapping = 302; export const EquirectangularReflectionMapping = 303; export const EquirectangularRefractionMapping = 304; export const CubeUVReflectionMapping = 306; export const RepeatWrapping = 1000; export const ClampToEdgeWrapping = 1001; export const MirroredRepeatWrapping = 1002; export const NearestFilter = 1003; export const NearestMipmapNearestFilter = 1004; export const NearestMipMapNearestFilter = 1004; export const NearestMipmapLinearFilter = 1005; export const NearestMipMapLinearFilter = 1005; export const LinearFilter = 1006; export const LinearMipmapNearestFilter = 1007; export const LinearMipMapNearestFilter = 1007; export const LinearMipmapLinearFilter = 1008; export const LinearMipMapLinearFilter = 1008; export const UnsignedByteType = 1009; export const ByteType = 1010; export const ShortType = 1011; export const UnsignedShortType = 1012; export const IntType = 1013; export const UnsignedIntType = 1014; export const FloatType = 1015; export const HalfFloatType = 1016; export const UnsignedShort4444Type = 1017; export const UnsignedShort5551Type = 1018; export const UnsignedInt248Type = 1020; export const UnsignedInt5999Type = 35902; export const AlphaFormat = 1021; export const RGBFormat = 1022; export const RGBAFormat = 1023; export const LuminanceFormat = 1024; export const LuminanceAlphaFormat = 1025; export const DepthFormat = 1026; export const DepthStencilFormat = 1027; export const RedFormat = 1028; export const RedIntegerFormat = 1029; export const RGFormat = 1030; export const RGIntegerFormat = 1031; export const RGBIntegerFormat = 1032; export const RGBAIntegerFormat = 1033; export const RGB_S3TC_DXT1_Format = 33776; export const RGBA_S3TC_DXT1_Format = 33777; export const RGBA_S3TC_DXT3_Format = 33778; export const RGBA_S3TC_DXT5_Format = 33779; export const RGB_PVRTC_4BPPV1_Format = 35840; export const RGB_PVRTC_2BPPV1_Format = 35841; export const RGBA_PVRTC_4BPPV1_Format = 35842; export const RGBA_PVRTC_2BPPV1_Format = 35843; export const RGB_ETC1_Format = 36196; export const RGB_ETC2_Format = 37492; export const RGBA_ETC2_EAC_Format = 37496; export const RGBA_ASTC_4x4_Format = 37808; export const RGBA_ASTC_5x4_Format = 37809; export const RGBA_ASTC_5x5_Format = 37810; export const RGBA_ASTC_6x5_Format = 37811; export const RGBA_ASTC_6x6_Format = 37812; export const RGBA_ASTC_8x5_Format = 37813; export const RGBA_ASTC_8x6_Format = 37814; export const RGBA_ASTC_8x8_Format = 37815; export const RGBA_ASTC_10x5_Format = 37816; export const RGBA_ASTC_10x6_Format = 37817; export const RGBA_ASTC_10x8_Format = 37818; export const RGBA_ASTC_10x10_Format = 37819; export const RGBA_ASTC_12x10_Format = 37820; export const RGBA_ASTC_12x12_Format = 37821; export const RGBA_BPTC_Format = 36492; export const RGB_BPTC_SIGNED_Format = 36494; export const RGB_BPTC_UNSIGNED_Format = 36495; export const RED_RGTC1_Format = 36283; export const SIGNED_RED_RGTC1_Format = 36284; export const RED_GREEN_RGTC2_Format = 36285; export const SIGNED_RED_GREEN_RGTC2_Format = 36286; export const LoopOnce = 2200; export const LoopRepeat = 2201; export const LoopPingPong = 2202; export const InterpolateDiscrete = 2300; export const InterpolateLinear = 2301; export const InterpolateSmooth = 2302; export const ZeroCurvatureEnding = 2400; export const ZeroSlopeEnding = 2401; export const WrapAroundEnding = 2402; export const NormalAnimationBlendMode = 2500; export const AdditiveAnimationBlendMode = 2501; export const TrianglesDrawMode = 0; export const TriangleStripDrawMode = 1; export const TriangleFanDrawMode = 2; export const BasicDepthPacking = 3200; export const RGBADepthPacking = 3201; export const RGBDepthPacking = 3202; export const RGDepthPacking = 3203; export const TangentSpaceNormalMap = 0; export const ObjectSpaceNormalMap = 1; // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available. export const NoColorSpace = ''; export const SRGBColorSpace = 'srgb'; export const LinearSRGBColorSpace = 'srgb-linear'; export const LinearTransfer = 'linear'; export const SRGBTransfer = 'srgb'; export const ZeroStencilOp = 0; export const KeepStencilOp = 7680; export const ReplaceStencilOp = 7681; export const IncrementStencilOp = 7682; export const DecrementStencilOp = 7683; export const IncrementWrapStencilOp = 34055; export const DecrementWrapStencilOp = 34056; export const InvertStencilOp = 5386; export const NeverStencilFunc = 512; export const LessStencilFunc = 513; export const EqualStencilFunc = 514; export const LessEqualStencilFunc = 515; export const GreaterStencilFunc = 516; export const NotEqualStencilFunc = 517; export const GreaterEqualStencilFunc = 518; export const AlwaysStencilFunc = 519; export const NeverCompare = 512; export const LessCompare = 513; export const EqualCompare = 514; export const LessEqualCompare = 515; export const GreaterCompare = 516; export const NotEqualCompare = 517; export const GreaterEqualCompare = 518; export const AlwaysCompare = 519; export const StaticDrawUsage = 35044; export const DynamicDrawUsage = 35048; export const StreamDrawUsage = 35040; export const StaticReadUsage = 35045; export const DynamicReadUsage = 35049; export const StreamReadUsage = 35041; export const StaticCopyUsage = 35046; export const DynamicCopyUsage = 35050; export const StreamCopyUsage = 35042; export const GLSL1 = '100'; export const GLSL3 = '300 es'; export const WebGLCoordinateSystem = 2000; export const WebGPUCoordinateSystem = 2001; ",2,911,JavaScript controls,./ProjectTest/JavaScript/controls.js,"// controls/Controls.js import { EventDispatcher } from './EventDispatcher.js'; class Controls extends EventDispatcher { constructor( object, domElement = null ) { super(); this.object = object; this.domElement = domElement; this.enabled = true; this.state = - 1; this.keys = {}; this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null }; this.touches = { ONE: null, TWO: null }; } connect() {} disconnect() {} dispose() {} update( /* delta */ ) {} } export { Controls }; // controls/EventDispatcher.js /** * https://github.com/mrdoob/eventdispatcher.js/ */ class EventDispatcher { addEventListener( type, listener ) { if ( this._listeners === undefined ) this._listeners = {}; const listeners = this._listeners; if ( listeners[ type ] === undefined ) { listeners[ type ] = []; } if ( listeners[ type ].indexOf( listener ) === - 1 ) { listeners[ type ].push( listener ); } } hasEventListener( type, listener ) { if ( this._listeners === undefined ) return false; const listeners = this._listeners; return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1; } removeEventListener( type, listener ) { if ( this._listeners === undefined ) return; const listeners = this._listeners; const listenerArray = listeners[ type ]; if ( listenerArray !== undefined ) { const index = listenerArray.indexOf( listener ); if ( index !== - 1 ) { listenerArray.splice( index, 1 ); } } } dispatchEvent( event ) { if ( this._listeners === undefined ) return; const listeners = this._listeners; const listenerArray = listeners[ event.type ]; if ( listenerArray !== undefined ) { event.target = this; // Make a copy, in case listeners are removed while iterating. const array = listenerArray.slice( 0 ); for ( let i = 0, l = array.length; i < l; i ++ ) { array[ i ].call( this, event ); } event.target = null; } } } export { EventDispatcher }; ",2,119,JavaScript particle,./ProjectTest/JavaScript/particle.js,"// particle/Particle.js var Shape = require('./Shape') , shallowClone = require('./Utils').shallowClone , copy = require('./vec2').copy; module.exports = Particle; /** * Particle shape class. * @class Particle * @constructor * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink ""Shape""}}{{/crossLink}} constructor.) * @extends Shape * @example * var body = new Body(); * var shape = new Particle(); * body.addShape(shape); */ function Particle(options){ options = options ? shallowClone(options) : {}; options.type = Shape.PARTICLE; Shape.call(this, options); } Particle.prototype = new Shape(); Particle.prototype.constructor = Particle; Particle.prototype.computeMomentOfInertia = function(){ return 0; // Can't rotate a particle }; Particle.prototype.updateBoundingRadius = function(){ this.boundingRadius = 0; }; /** * @method computeAABB * @param {AABB} out * @param {Array} position * @param {Number} angle */ Particle.prototype.computeAABB = function(out, position/*, angle*/){ copy(out.lowerBound, position); copy(out.upperBound, position); }; // particle/vec2.js /* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net. * @class vec2 */ var vec2 = module.exports = {}; var Utils = require('./Utils'); /** * Make a cross product and only return the z component * @method crossLength * @static * @param {Array} a * @param {Array} b * @return {Number} */ vec2.crossLength = function(a,b){ return a[0] * b[1] - a[1] * b[0]; }; /** * Cross product between a vector and the Z component of a vector * @method crossVZ * @static * @param {Array} out * @param {Array} vec * @param {Number} zcomp * @return {Array} */ vec2.crossVZ = function(out, vec, zcomp){ vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule vec2.scale(out,out,zcomp); // Scale with z return out; }; /** * Cross product between a vector and the Z component of a vector * @method crossZV * @static * @param {Array} out * @param {Number} zcomp * @param {Array} vec * @return {Array} */ vec2.crossZV = function(out, zcomp, vec){ vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule vec2.scale(out,out,zcomp); // Scale with z return out; }; /** * Rotate a vector by an angle * @method rotate * @static * @param {Array} out * @param {Array} a * @param {Number} angle * @return {Array} */ vec2.rotate = function(out,a,angle){ if(angle !== 0){ var c = Math.cos(angle), s = Math.sin(angle), x = a[0], y = a[1]; out[0] = c*x -s*y; out[1] = s*x +c*y; } else { out[0] = a[0]; out[1] = a[1]; } return out; }; /** * Rotate a vector 90 degrees clockwise * @method rotate90cw * @static * @param {Array} out * @param {Array} a * @param {Number} angle * @return {Array} */ vec2.rotate90cw = function(out, a) { var x = a[0]; var y = a[1]; out[0] = y; out[1] = -x; return out; }; /** * Transform a point position to local frame. * @method toLocalFrame * @param {Array} out * @param {Array} worldPoint * @param {Array} framePosition * @param {Number} frameAngle * @return {Array} */ vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){ var c = Math.cos(-frameAngle), s = Math.sin(-frameAngle), x = worldPoint[0] - framePosition[0], y = worldPoint[1] - framePosition[1]; out[0] = c * x - s * y; out[1] = s * x + c * y; return out; }; /** * Transform a point position to global frame. * @method toGlobalFrame * @param {Array} out * @param {Array} localPoint * @param {Array} framePosition * @param {Number} frameAngle */ vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){ var c = Math.cos(frameAngle), s = Math.sin(frameAngle), x = localPoint[0], y = localPoint[1], addX = framePosition[0], addY = framePosition[1]; out[0] = c * x - s * y + addX; out[1] = s * x + c * y + addY; }; /** * Transform a vector to local frame. * @method vectorToLocalFrame * @param {Array} out * @param {Array} worldVector * @param {Number} frameAngle * @return {Array} */ vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){ var c = Math.cos(-frameAngle), s = Math.sin(-frameAngle), x = worldVector[0], y = worldVector[1]; out[0] = c*x -s*y; out[1] = s*x +c*y; return out; }; /** * Transform a vector to global frame. * @method vectorToGlobalFrame * @param {Array} out * @param {Array} localVector * @param {Number} frameAngle */ vec2.vectorToGlobalFrame = vec2.rotate; /** * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php * @method centroid * @static * @param {Array} out * @param {Array} a * @param {Array} b * @param {Array} c * @return {Array} The ""out"" vector. */ vec2.centroid = function(out, a, b, c){ vec2.add(out, a, b); vec2.add(out, out, c); vec2.scale(out, out, 1/3); return out; }; /** * Creates a new, empty vec2 * @static * @method create * @return {Array} a new 2D vector */ vec2.create = function() { var out = new Utils.ARRAY_TYPE(2); out[0] = 0; out[1] = 0; return out; }; /** * Creates a new vec2 initialized with values from an existing vector * @static * @method clone * @param {Array} a vector to clone * @return {Array} a new 2D vector */ vec2.clone = function(a) { var out = new Utils.ARRAY_TYPE(2); out[0] = a[0]; out[1] = a[1]; return out; }; /** * Creates a new vec2 initialized with the given values * @static * @method fromValues * @param {Number} x X component * @param {Number} y Y component * @return {Array} a new 2D vector */ vec2.fromValues = function(x, y) { var out = new Utils.ARRAY_TYPE(2); out[0] = x; out[1] = y; return out; }; /** * Copy the values from one vec2 to another * @static * @method copy * @param {Array} out the receiving vector * @param {Array} a the source vector * @return {Array} out */ vec2.copy = function(out, a) { out[0] = a[0]; out[1] = a[1]; return out; }; /** * Set the components of a vec2 to the given values * @static * @method set * @param {Array} out the receiving vector * @param {Number} x X component * @param {Number} y Y component * @return {Array} out */ vec2.set = function(out, x, y) { out[0] = x; out[1] = y; return out; }; /** * Adds two vec2's * @static * @method add * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.add = function(out, a, b) { out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; return out; }; /** * Subtracts two vec2's * @static * @method subtract * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.subtract = function(out, a, b) { out[0] = a[0] - b[0]; out[1] = a[1] - b[1]; return out; }; /** * Multiplies two vec2's * @static * @method multiply * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.multiply = function(out, a, b) { out[0] = a[0] * b[0]; out[1] = a[1] * b[1]; return out; }; /** * Divides two vec2's * @static * @method divide * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.divide = function(out, a, b) { out[0] = a[0] / b[0]; out[1] = a[1] / b[1]; return out; }; /** * Scales a vec2 by a scalar number * @static * @method scale * @param {Array} out the receiving vector * @param {Array} a the vector to scale * @param {Number} b amount to scale the vector by * @return {Array} out */ vec2.scale = function(out, a, b) { out[0] = a[0] * b; out[1] = a[1] * b; return out; }; /** * Calculates the euclidian distance between two vec2's * @static * @method distance * @param {Array} a the first operand * @param {Array} b the second operand * @return {Number} distance between a and b */ vec2.distance = function(a, b) { var x = b[0] - a[0], y = b[1] - a[1]; return Math.sqrt(x*x + y*y); }; /** * Calculates the squared euclidian distance between two vec2's * @static * @method squaredDistance * @param {Array} a the first operand * @param {Array} b the second operand * @return {Number} squared distance between a and b */ vec2.squaredDistance = function(a, b) { var x = b[0] - a[0], y = b[1] - a[1]; return x*x + y*y; }; /** * Calculates the length of a vec2 * @static * @method length * @param {Array} a vector to calculate length of * @return {Number} length of a */ vec2.length = function (a) { var x = a[0], y = a[1]; return Math.sqrt(x*x + y*y); }; /** * Calculates the squared length of a vec2 * @static * @method squaredLength * @param {Array} a vector to calculate squared length of * @return {Number} squared length of a */ vec2.squaredLength = function (a) { var x = a[0], y = a[1]; return x*x + y*y; }; /** * Negates the components of a vec2 * @static * @method negate * @param {Array} out the receiving vector * @param {Array} a vector to negate * @return {Array} out */ vec2.negate = function(out, a) { out[0] = -a[0]; out[1] = -a[1]; return out; }; /** * Normalize a vec2 * @static * @method normalize * @param {Array} out the receiving vector * @param {Array} a vector to normalize * @return {Array} out */ vec2.normalize = function(out, a) { var x = a[0], y = a[1]; var len = x*x + y*y; if (len > 0) { //TODO: evaluate use of glm_invsqrt here? len = 1 / Math.sqrt(len); out[0] = a[0] * len; out[1] = a[1] * len; } return out; }; /** * Calculates the dot product of two vec2's * @static * @method dot * @param {Array} a the first operand * @param {Array} b the second operand * @return {Number} dot product of a and b */ vec2.dot = function (a, b) { return a[0] * b[0] + a[1] * b[1]; }; /** * Returns a string representation of a vector * @static * @method str * @param {Array} vec vector to represent as a string * @return {String} string representation of the vector */ vec2.str = function (a) { return 'vec2(' + a[0] + ', ' + a[1] + ')'; }; /** * Linearly interpolate/mix two vectors. * @static * @method lerp * @param {Array} out * @param {Array} a First vector * @param {Array} b Second vector * @param {number} t Lerp factor */ vec2.lerp = function (out, a, b, t) { var ax = a[0], ay = a[1]; out[0] = ax + t * (b[0] - ax); out[1] = ay + t * (b[1] - ay); return out; }; /** * Reflect a vector along a normal. * @static * @method reflect * @param {Array} out * @param {Array} vector * @param {Array} normal */ vec2.reflect = function(out, vector, normal){ var dot = vector[0] * normal[0] + vector[1] * normal[1]; out[0] = vector[0] - 2 * normal[0] * dot; out[1] = vector[1] - 2 * normal[1] * dot; }; /** * Get the intersection point between two line segments. * @static * @method getLineSegmentsIntersection * @param {Array} out * @param {Array} p0 * @param {Array} p1 * @param {Array} p2 * @param {Array} p3 * @return {boolean} True if there was an intersection, otherwise false. */ vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) { var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3); if(t < 0){ return false; } else { out[0] = p0[0] + (t * (p1[0] - p0[0])); out[1] = p0[1] + (t * (p1[1] - p0[1])); return true; } }; /** * Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0) * @static * @method getLineSegmentsIntersectionFraction * @param {Array} p0 * @param {Array} p1 * @param {Array} p2 * @param {Array} p3 * @return {number} A number between 0 and 1 if there was an intersection, otherwise -1. */ vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) { var s1_x = p1[0] - p0[0]; var s1_y = p1[1] - p0[1]; var s2_x = p3[0] - p2[0]; var s2_y = p3[1] - p2[1]; var s, t; s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y); t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y); if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected return t; } return -1; // No collision }; // particle/Utils.js /* global P2_ARRAY_TYPE */ module.exports = Utils; /** * Misc utility functions * @class Utils * @constructor */ function Utils(){} /** * Append the values in array b to the array a. See this for an explanation. * @method appendArray * @static * @param {Array} a * @param {Array} b */ Utils.appendArray = function(a,b){ if (b.length < 150000) { a.push.apply(a, b); } else { for (var i = 0, len = b.length; i !== len; ++i) { a.push(b[i]); } } }; /** * Garbage free Array.splice(). Does not allocate a new array. * @method splice * @static * @param {Array} array * @param {Number} index * @param {Number} howmany */ Utils.splice = function(array,index,howmany){ howmany = howmany || 1; for (var i=index, len=array.length-howmany; i < len; i++){ array[i] = array[i + howmany]; } array.length = len; }; /** * Remove an element from an array, if the array contains the element. * @method arrayRemove * @static * @param {Array} array * @param {Number} element */ Utils.arrayRemove = function(array, element){ var idx = array.indexOf(element); if(idx!==-1){ Utils.splice(array, idx, 1); } }; /** * The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below. * @static * @property {function} ARRAY_TYPE * @example * * */ if(typeof P2_ARRAY_TYPE !== 'undefined') { Utils.ARRAY_TYPE = P2_ARRAY_TYPE; } else if (typeof Float32Array !== 'undefined'){ Utils.ARRAY_TYPE = Float32Array; } else { Utils.ARRAY_TYPE = Array; } /** * Extend an object with the properties of another * @static * @method extend * @param {object} a * @param {object} b */ Utils.extend = function(a,b){ for(var key in b){ a[key] = b[key]; } }; /** * Shallow clone an object. Returns a new object instance with the same properties as the input instance. * @static * @method shallowClone * @param {object} obj */ Utils.shallowClone = function(obj){ var newObj = {}; Utils.extend(newObj, obj); return newObj; }; /** * Extend an options object with default values. * @deprecated Not used internally, will be removed. * @static * @method defaults * @param {object} options The options object. May be falsy: in this case, a new object is created and returned. * @param {object} defaults An object containing default values. * @return {object} The modified options object. */ Utils.defaults = function(options, defaults){ console.warn('Utils.defaults is deprecated.'); options = options || {}; for(var key in defaults){ if(!(key in options)){ options[key] = defaults[key]; } } return options; }; // particle/Shape.js module.exports = Shape; var vec2 = require('./vec2'); /** * Base class for shapes. Not to be used directly. * @class Shape * @constructor * @param {object} [options] * @param {number} [options.angle=0] * @param {number} [options.collisionGroup=1] * @param {number} [options.collisionMask=1] * @param {boolean} [options.collisionResponse=true] * @param {Material} [options.material=null] * @param {array} [options.position] * @param {boolean} [options.sensor=false] * @param {object} [options.type=0] */ function Shape(options){ options = options || {}; /** * The body this shape is attached to. A shape can only be attached to a single body. * @property {Body} body */ this.body = null; /** * Body-local position of the shape. * @property {Array} position */ this.position = vec2.create(); if(options.position){ vec2.copy(this.position, options.position); } /** * Body-local angle of the shape. * @property {number} angle */ this.angle = options.angle || 0; /** * The type of the shape. One of: * * * * @property {number} type */ this.type = options.type || 0; /** * Shape object identifier. Read only. * @readonly * @type {Number} * @property id */ this.id = Shape.idCounter++; /** * Bounding circle radius of this shape * @readonly * @property boundingRadius * @type {Number} */ this.boundingRadius = 0; /** * Collision group that this shape belongs to (bit mask). See this tutorial. * @property collisionGroup * @type {Number} * @example * // Setup bits for each available group * var PLAYER = Math.pow(2,0), * ENEMY = Math.pow(2,1), * GROUND = Math.pow(2,2) * * // Put shapes into their groups * player1Shape.collisionGroup = PLAYER; * player2Shape.collisionGroup = PLAYER; * enemyShape .collisionGroup = ENEMY; * groundShape .collisionGroup = GROUND; * * // Assign groups that each shape collide with. * // Note that the players can collide with ground and enemies, but not with other players. * player1Shape.collisionMask = ENEMY | GROUND; * player2Shape.collisionMask = ENEMY | GROUND; * enemyShape .collisionMask = PLAYER | GROUND; * groundShape .collisionMask = PLAYER | ENEMY; * * @example * // How collision check is done * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){ * // The shapes will collide * } */ this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1; /** * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc. * @property {Boolean} collisionResponse */ this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true; /** * Collision mask of this shape. See .collisionGroup. * @property collisionMask * @type {Number} */ this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1; /** * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead. * @property material * @type {Material} */ this.material = options.material || null; /** * Area of this shape. * @property area * @type {Number} */ this.area = 0; /** * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts. * @property {Boolean} sensor */ this.sensor = options.sensor !== undefined ? options.sensor : false; if(this.type){ this.updateBoundingRadius(); } this.updateArea(); } Shape.idCounter = 0; /** * @static * @property {Number} CIRCLE */ Shape.CIRCLE = 1; /** * @static * @property {Number} PARTICLE */ Shape.PARTICLE = 2; /** * @static * @property {Number} PLANE */ Shape.PLANE = 4; /** * @static * @property {Number} CONVEX */ Shape.CONVEX = 8; /** * @static * @property {Number} LINE */ Shape.LINE = 16; /** * @static * @property {Number} BOX */ Shape.BOX = 32; /** * @static * @property {Number} CAPSULE */ Shape.CAPSULE = 64; /** * @static * @property {Number} HEIGHTFIELD */ Shape.HEIGHTFIELD = 128; Shape.prototype = { /** * Should return the moment of inertia around the Z axis of the body. See Wikipedia's list of moments of inertia. * @method computeMomentOfInertia * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0. */ computeMomentOfInertia: function(){}, /** * Returns the bounding circle radius of this shape. * @method updateBoundingRadius * @return {Number} */ updateBoundingRadius: function(){}, /** * Update the .area property of the shape. * @method updateArea */ updateArea: function(){}, /** * Compute the world axis-aligned bounding box (AABB) of this shape. * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position World position of the shape. * @param {Number} angle World angle of the shape. */ computeAABB: function(/*out, position, angle*/){ // To be implemented in each subclass }, /** * Perform raycasting on this shape. * @method raycast * @param {RayResult} result Where to store the resulting data. * @param {Ray} ray The Ray that you want to use for raycasting. * @param {array} position World position of the shape (the .position property will be ignored). * @param {number} angle World angle of the shape (the .angle property will be ignored). */ raycast: function(/*result, ray, position, angle*/){ // To be implemented in each subclass }, /** * Test if a point is inside this shape. * @method pointTest * @param {array} localPoint * @return {boolean} */ pointTest: function(/*localPoint*/){ return false; }, /** * Transform a world point to local shape space (assumed the shape is transformed by both itself and the body). * @method worldPointToLocal * @param {array} out * @param {array} worldPoint */ worldPointToLocal: (function () { var shapeWorldPosition = vec2.create(); return function (out, worldPoint) { var body = this.body; vec2.rotate(shapeWorldPosition, this.position, body.angle); vec2.add(shapeWorldPosition, shapeWorldPosition, body.position); vec2.toLocalFrame(out, worldPoint, shapeWorldPosition, this.body.angle + this.angle); }; })() }; ",4,963,JavaScript zone,./ProjectTest/JavaScript/zone.js,"// zone/MathUtil.js const PI = 3.1415926; const INFINITY = Infinity; const MathUtil = { PI: PI, PIx2: PI * 2, PI_2: PI / 2, PI_180: PI / 180, N180_PI: 180 / PI, Infinity: -999, isInfinity(num) { return num === this.Infinity || num === INFINITY; }, randomAToB(a, b, isInt = false) { if (!isInt) return a + Math.random() * (b - a); else return ((Math.random() * (b - a)) >> 0) + a; }, randomFloating(center, f, isInt) { return this.randomAToB(center - f, center + f, isInt); }, randomColor() { return ""#"" + (""00000"" + ((Math.random() * 0x1000000) << 0).toString(16)).slice(-6); }, randomZone(display) {}, floor(num, k = 4) { const digits = Math.pow(10, k); return Math.floor(num * digits) / digits; }, degreeTransform(a) { return (a * PI) / 180; }, toColor16(num) { return `#${num.toString(16)}`; } }; export default MathUtil; // zone/Vector2D.js import MathUtil from ""./MathUtil""; export default class Vector2D { constructor(x, y) { this.x = x || 0; this.y = y || 0; } set(x, y) { this.x = x; this.y = y; return this; } setX(x) { this.x = x; return this; } setY(y) { this.y = y; return this; } getGradient() { if (this.x !== 0) return Math.atan2(this.y, this.x); else if (this.y > 0) return MathUtil.PI_2; else if (this.y < 0) return -MathUtil.PI_2; } copy(v) { this.x = v.x; this.y = v.y; return this; } add(v, w) { if (w !== undefined) { return this.addVectors(v, w); } this.x += v.x; this.y += v.y; return this; } addXY(a, b) { this.x += a; this.y += b; return this; } addVectors(a, b) { this.x = a.x + b.x; this.y = a.y + b.y; return this; } sub(v, w) { if (w !== undefined) { return this.subVectors(v, w); } this.x -= v.x; this.y -= v.y; return this; } subVectors(a, b) { this.x = a.x - b.x; this.y = a.y - b.y; return this; } divideScalar(s) { if (s !== 0) { this.x /= s; this.y /= s; } else { this.set(0, 0); } return this; } multiplyScalar(s) { this.x *= s; this.y *= s; return this; } negate() { return this.multiplyScalar(-1); } dot(v) { return this.x * v.x + this.y * v.y; } lengthSq() { return this.x * this.x + this.y * this.y; } length() { return Math.sqrt(this.x * this.x + this.y * this.y); } normalize() { return this.divideScalar(this.length()); } distanceTo(v) { return Math.sqrt(this.distanceToSquared(v)); } rotate(tha) { const x = this.x; const y = this.y; this.x = x * Math.cos(tha) + y * Math.sin(tha); this.y = -x * Math.sin(tha) + y * Math.cos(tha); return this; } distanceToSquared(v) { const dx = this.x - v.x; const dy = this.y - v.y; return dx * dx + dy * dy; } lerp(v, alpha) { this.x += (v.x - this.x) * alpha; this.y += (v.y - this.y) * alpha; return this; } equals(v) { return v.x === this.x && v.y === this.y; } clear() { this.x = 0.0; this.y = 0.0; return this; } clone() { return new Vector2D(this.x, this.y); } } // zone/Zone.js import Vector2D from ""./Vector2D""; export default class Zone { constructor() { this.vector = new Vector2D(0, 0); this.random = 0; this.crossType = ""dead""; this.alert = true; } getPosition() {} crossing(particle) {} destroy() { this.vector = null; } } ",3,223,JavaScript magnetic,./ProjectTest/JavaScript/magnetic.js,"// magnetic/BezierEasing.js /** * @author pschroen / https://ufo.ai/ * * Based on https://github.com/gre/bezier-easing */ // These values are established by empiricism with tests (tradeoff: performance VS precision) const NEWTON_ITERATIONS = 4; const NEWTON_MIN_SLOPE = 0.001; const SUBDIVISION_PRECISION = 0.0000001; const SUBDIVISION_MAX_ITERATIONS = 10; const kSplineTableSize = 11; const kSampleStepSize = 1 / (kSplineTableSize - 1); function A(aA1, aA2) { return 1 - 3 * aA2 + 3 * aA1; } function B(aA1, aA2) { return 3 * aA2 - 6 * aA1; } function C(aA1) { return 3 * aA1; } // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2 function calcBezier(aT, aA1, aA2) { return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT; } // Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2 function getSlope(aT, aA1, aA2) { return 3 * A(aA1, aA2) * aT * aT + 2 * B(aA1, aA2) * aT + C(aA1); } function binarySubdivide(aX, aA, aB, mX1, mX2) { let currentX; let currentT; let i = 0; do { currentT = aA + (aB - aA) / 2; currentX = calcBezier(currentT, mX1, mX2) - aX; if (currentX > 0) { aB = currentT; } else { aA = currentT; } } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS); return currentT; } function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) { for (let i = 0; i < NEWTON_ITERATIONS; i++) { const currentSlope = getSlope(aGuessT, mX1, mX2); if (currentSlope === 0) { return aGuessT; } const currentX = calcBezier(aGuessT, mX1, mX2) - aX; aGuessT -= currentX / currentSlope; } return aGuessT; } function LinearEasing(x) { return x; } export default function bezier(mX1, mY1, mX2, mY2) { if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) { throw new Error('Bezier x values must be in [0, 1] range'); } if (mX1 === mY1 && mX2 === mY2) { return LinearEasing; } // Precompute samples table const sampleValues = new Float32Array(kSplineTableSize); for (let i = 0; i < kSplineTableSize; i++) { sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2); } function getTForX(aX) { let intervalStart = 0; let currentSample = 1; const lastSample = kSplineTableSize - 1; for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; currentSample++) { intervalStart += kSampleStepSize; } currentSample--; // Interpolate to provide an initial guess for t const dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]); const guessForT = intervalStart + dist * kSampleStepSize; const initialSlope = getSlope(guessForT, mX1, mX2); if (initialSlope >= NEWTON_MIN_SLOPE) { return newtonRaphsonIterate(aX, guessForT, mX1, mX2); } else if (initialSlope === 0) { return guessForT; } else { return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2); } } return function BezierEasing(x) { // Because JavaScript numbers are imprecise, we should guarantee the extremes are right if (x === 0 || x === 1) { return x; } return calcBezier(getTForX(x), mY1, mY2); }; } // magnetic/EventEmitter.js /** * @author pschroen / https://ufo.ai/ * * Based on https://developer.mozilla.org/en-US/docs/Web/API/EventTarget#simple_implementation_of_eventtarget */ /** * A simple implementation of EventTarget with event parameter spread. */ export class EventEmitter { constructor() { this.callbacks = {}; } on(type, callback) { if (!this.callbacks[type]) { this.callbacks[type] = []; } this.callbacks[type].push(callback); } off(type, callback) { if (!this.callbacks[type]) { return; } if (callback) { const index = this.callbacks[type].indexOf(callback); if (~index) { this.callbacks[type].splice(index, 1); } } else { delete this.callbacks[type]; } } emit(type, ...event) { if (!this.callbacks[type]) { return; } const stack = this.callbacks[type].slice(); for (let i = 0, l = stack.length; i < l; i++) { stack[i].call(this, ...event); } } destroy() { for (const prop in this) { this[prop] = null; } return null; } } // magnetic/Tween.js /** * @author pschroen / https://ufo.ai/ */ import { Easing } from './Easing.js'; import { ticker } from './Ticker.js'; const Tweens = []; /** * Tween animation engine. * @see {@link https://github.com/alienkitty/alien.js/wiki/Tween | Documentation} * @see {@link https://easings.net/ | Easing Functions Cheat Sheet} * @example * ticker.start(); * * const data = { * radius: 0 * }; * * tween(data, { radius: 24, spring: 1.2, damping: 0.4 }, 1000, 'easeOutElastic', null, () => { * console.log(data.radius); * }); */ export class Tween { constructor(object, props, duration, ease, delay = 0, complete, update) { if (typeof delay !== 'number') { update = complete; complete = delay; delay = 0; } this.object = object; this.duration = duration; this.elapsed = 0; this.ease = typeof ease === 'function' ? ease : Easing[ease] || Easing['easeOutCubic']; this.delay = delay; this.complete = complete; this.update = update; this.isAnimating = false; this.from = {}; this.to = Object.assign({}, props); this.spring = this.to.spring; this.damping = this.to.damping; delete this.to.spring; delete this.to.damping; for (const prop in this.to) { if (typeof this.to[prop] === 'number' && typeof object[prop] === 'number') { this.from[prop] = object[prop]; } } this.start(); } // Event handlers onUpdate = (time, delta) => { this.elapsed += delta; const progress = Math.max(0, Math.min(1, (this.elapsed - this.delay) / this.duration)); const alpha = this.ease(progress, this.spring, this.damping); for (const prop in this.from) { this.object[prop] = this.from[prop] + (this.to[prop] - this.from[prop]) * alpha; } if (this.update) { this.update(); } if (progress === 1) { clearTween(this); if (this.complete) { this.complete(); } } }; // Public methods start() { if (this.isAnimating) { return; } this.isAnimating = true; ticker.add(this.onUpdate); } stop() { if (!this.isAnimating) { return; } this.isAnimating = false; ticker.remove(this.onUpdate); } } /** * Defers a function by the given duration. * @param {number} duration Time to wait in milliseconds. * @param {function} complete Callback function. * @returns {Tween} * @example * delayedCall(500, animateIn); * @example * delayedCall(500, () => animateIn(delay)); * @example * timeout = delayedCall(500, () => animateIn(delay)); */ export function delayedCall(duration, complete) { const tween = new Tween(complete, null, duration, 'linear', 0, complete); Tweens.push(tween); return tween; } /** * Defers by the given duration. * @param {number} [duration=0] Time to wait in milliseconds. * @returns {Promise} * @example * await wait(250); */ export function wait(duration = 0) { return new Promise(resolve => delayedCall(duration, resolve)); } /** * Defers to the next tick. * @param {function} [complete] Callback function. * @returns {Promise} * @example * defer(resize); * @example * defer(() => resize()); * @example * await defer(); */ export function defer(complete) { const promise = new Promise(resolve => delayedCall(0, resolve)); if (complete) { promise.then(complete); } return promise; } /** * Tween that animates to the given destination properties. * @see {@link https://easings.net/ | Easing Functions Cheat Sheet} * @param {object} object Target object. * @param {object} props Tween properties. * @param {number} duration Time in milliseconds. * @param {string|function} ease Ease string or function. * @param {number} [delay=0] Time to wait in milliseconds. * @param {function} [complete] Callback function when the animation has completed. * @param {function} [update] Callback function every time the animation updates. * @returns {Promise} * @example * tween(data, { value: 0.3 }, 1000, 'linear'); */ export function tween(object, props, duration, ease, delay = 0, complete, update) { if (typeof delay !== 'number') { update = complete; complete = delay; delay = 0; } const promise = new Promise(resolve => { const tween = new Tween(object, props, duration, ease, delay, resolve, update); Tweens.push(tween); }); if (complete) { promise.then(complete); } return promise; } /** * Immediately clears all delayedCalls and tweens of a given object. * @param {object} object Target object. * @returns {void} * @example * delayedCall(500, animateIn); * clearTween(animateIn); * @example * clearTween(timeout); * timeout = delayedCall(500, () => animateIn()); * @example * tween(data, { value: 0.3 }, 1000, 'linear'); * clearTween(data); */ export function clearTween(object) { if (object instanceof Tween) { object.stop(); const index = Tweens.indexOf(object); if (~index) { Tweens.splice(index, 1); } } else { for (let i = Tweens.length - 1; i >= 0; i--) { if (Tweens[i].object === object) { clearTween(Tweens[i]); } } } } // magnetic/Component.js /** * @author pschroen / https://ufo.ai/ */ import { EventEmitter } from './EventEmitter.js'; import { ticker } from './Ticker.js'; import { clearTween, tween } from './Tween.js'; /** * A base class for components with tween and destroy methods. */ export class Component { constructor() { this.events = new EventEmitter(); this.children = []; } add(child) { if (!this.children) { return; } this.children.push(child); child.parent = this; return child; } remove(child) { if (!this.children) { return; } const index = this.children.indexOf(child); if (~index) { this.children.splice(index, 1); } } tween(props, duration, ease, delay, complete, update) { if (!ticker.isAnimating) { ticker.start(); } return tween(this, props, duration, ease, delay, complete, update); } clearTween() { clearTween(this); return this; } destroy() { if (!this.children) { return; } if (this.parent && this.parent.remove) { this.parent.remove(this); } this.clearTween(); this.events.destroy(); for (let i = this.children.length - 1; i >= 0; i--) { if (this.children[i] && this.children[i].destroy) { this.children[i].destroy(); } } for (const prop in this) { this[prop] = null; } return null; } } // magnetic/Ticker.js /** * @author pschroen / https://ufo.ai/ */ var RequestFrame; var CancelFrame; if (typeof window !== 'undefined') { RequestFrame = window.requestAnimationFrame; CancelFrame = window.cancelAnimationFrame; } else { const startTime = performance.now(); const timestep = 1000 / 60; RequestFrame = callback => { return setTimeout(() => { callback(performance.now() - startTime); }, timestep); }; CancelFrame = clearTimeout; } /** * A minimal requestAnimationFrame render loop with worker support. * @example * ticker.add(onUpdate); * ticker.start(); * * function onUpdate(time, delta, frame) { * console.log(time, delta, frame); * } * * setTimeout(() => { * ticker.remove(onUpdate); * }, 1000); */ export class Ticker { constructor() { this.callbacks = []; this.last = performance.now(); this.time = 0; this.delta = 0; this.frame = 0; this.isAnimating = false; } // Event handlers onTick = time => { if (this.isAnimating) { this.requestId = RequestFrame(this.onTick); } this.delta = time - this.last; this.last = time; this.time = time * 0.001; // seconds this.frame++; for (let i = this.callbacks.length - 1; i >= 0; i--) { const callback = this.callbacks[i]; if (!callback) { continue; } if (callback.fps) { const delta = time - callback.last; if (delta < 1000 / callback.fps) { continue; } callback.last = time; callback.frame++; callback(this.time, delta, callback.frame); continue; } callback(this.time, this.delta, this.frame); } }; // Public methods add(callback, fps) { if (fps) { callback.fps = fps; callback.last = performance.now(); callback.frame = 0; } this.callbacks.unshift(callback); } remove(callback) { const index = this.callbacks.indexOf(callback); if (~index) { this.callbacks.splice(index, 1); } } start() { if (this.isAnimating) { return; } this.isAnimating = true; this.requestId = RequestFrame(this.onTick); } stop() { if (!this.isAnimating) { return; } this.isAnimating = false; CancelFrame(this.requestId); } setRequestFrame(request) { RequestFrame = request; } setCancelFrame(cancel) { CancelFrame = cancel; } } export const ticker = new Ticker(); // magnetic/Magnetic.js /** * @author pschroen / https://ufo.ai/ * * Based on https://gist.github.com/jesperlandberg/66484c7bb456661662f57361851bfc31 */ import { Component } from './Component.js'; export class Magnetic extends Component { constructor(object, { threshold = 50 } = {}) { super(); this.object = object; this.threshold = threshold; this.hoveredIn = false; this.init(); this.enable(); } init() { this.object.css({ willChange: 'transform' }); } addListeners() { window.addEventListener('pointerdown', this.onPointerDown); window.addEventListener('pointermove', this.onPointerMove); window.addEventListener('pointerup', this.onPointerUp); } removeListeners() { window.removeEventListener('pointerdown', this.onPointerDown); window.removeEventListener('pointermove', this.onPointerMove); window.removeEventListener('pointerup', this.onPointerUp); } // Event handlers onPointerDown = e => { this.onPointerMove(e); }; onPointerMove = ({ clientX, clientY }) => { const { left, top, width, height } = this.object.element.getBoundingClientRect(); const x = clientX - (left + width / 2); const y = clientY - (top + height / 2); const distance = Math.sqrt(x * x + y * y); if (distance < (width + height) / 2 + this.threshold) { this.onHover({ type: 'over', x, y }); } else if (this.hoveredIn) { this.onHover({ type: 'out' }); } }; onPointerUp = () => { this.onHover({ type: 'out' }); }; onHover = ({ type, x, y }) => { this.object.clearTween(); if (type === 'over') { this.object.tween({ x: x * 0.8, y: y * 0.8, skewX: x * 0.125, skewY: 0, rotation: x * 0.05, scale: 1.1 }, 500, 'easeOutCubic'); this.hoveredIn = true; } else { this.object.tween({ x: 0, y: 0, skewX: 0, skewY: 0, rotation: 0, scale: 1, spring: 1.2, damping: 0.4 }, 1000, 'easeOutElastic'); this.hoveredIn = false; } }; // Public methods enable() { this.addListeners(); } disable() { this.removeListeners(); } destroy() { this.disable(); return super.destroy(); } } // magnetic/Easing.js /** * @author pschroen / https://ufo.ai/ * * Based on https://github.com/danro/easing-js * Based on https://github.com/CreateJS/TweenJS * Based on https://github.com/tweenjs/tween.js * Based on https://easings.net/ */ import BezierEasing from './BezierEasing.js'; export class Easing { static linear(t) { return t; } static easeInQuad(t) { return t * t; } static easeOutQuad(t) { return t * (2 - t); } static easeInOutQuad(t) { if ((t *= 2) < 1) { return 0.5 * t * t; } return -0.5 * (--t * (t - 2) - 1); } static easeInCubic(t) { return t * t * t; } static easeOutCubic(t) { return --t * t * t + 1; } static easeInOutCubic(t) { if ((t *= 2) < 1) { return 0.5 * t * t * t; } return 0.5 * ((t -= 2) * t * t + 2); } static easeInQuart(t) { return t * t * t * t; } static easeOutQuart(t) { return 1 - --t * t * t * t; } static easeInOutQuart(t) { if ((t *= 2) < 1) { return 0.5 * t * t * t * t; } return -0.5 * ((t -= 2) * t * t * t - 2); } static easeInQuint(t) { return t * t * t * t * t; } static easeOutQuint(t) { return --t * t * t * t * t + 1; } static easeInOutQuint(t) { if ((t *= 2) < 1) { return 0.5 * t * t * t * t * t; } return 0.5 * ((t -= 2) * t * t * t * t + 2); } static easeInSine(t) { return 1 - Math.sin(((1 - t) * Math.PI) / 2); } static easeOutSine(t) { return Math.sin((t * Math.PI) / 2); } static easeInOutSine(t) { return 0.5 * (1 - Math.sin(Math.PI * (0.5 - t))); } static easeInExpo(t) { return t === 0 ? 0 : Math.pow(1024, t - 1); } static easeOutExpo(t) { return t === 1 ? 1 : 1 - Math.pow(2, -10 * t); } static easeInOutExpo(t) { if (t === 0 || t === 1) { return t; } if ((t *= 2) < 1) { return 0.5 * Math.pow(1024, t - 1); } return 0.5 * (-Math.pow(2, -10 * (t - 1)) + 2); } static easeInCirc(t) { return 1 - Math.sqrt(1 - t * t); } static easeOutCirc(t) { return Math.sqrt(1 - --t * t); } static easeInOutCirc(t) { if ((t *= 2) < 1) { return -0.5 * (Math.sqrt(1 - t * t) - 1); } return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1); } static easeInBack(t) { const s = 1.70158; return t === 1 ? 1 : t * t * ((s + 1) * t - s); } static easeOutBack(t) { const s = 1.70158; return t === 0 ? 0 : --t * t * ((s + 1) * t + s) + 1; } static easeInOutBack(t) { const s = 1.70158 * 1.525; if ((t *= 2) < 1) { return 0.5 * (t * t * ((s + 1) * t - s)); } return 0.5 * ((t -= 2) * t * ((s + 1) * t + s) + 2); } static easeInElastic(t, amplitude = 1, period = 0.3) { if (t === 0 || t === 1) { return t; } const pi2 = Math.PI * 2; const s = period / pi2 * Math.asin(1 / amplitude); return -(amplitude * Math.pow(2, 10 * --t) * Math.sin((t - s) * pi2 / period)); } static easeOutElastic(t, amplitude = 1, period = 0.3) { if (t === 0 || t === 1) { return t; } const pi2 = Math.PI * 2; const s = period / pi2 * Math.asin(1 / amplitude); return amplitude * Math.pow(2, -10 * t) * Math.sin((t - s) * pi2 / period) + 1; } static easeInOutElastic(t, amplitude = 1, period = 0.3 * 1.5) { if (t === 0 || t === 1) { return t; } const pi2 = Math.PI * 2; const s = period / pi2 * Math.asin(1 / amplitude); if ((t *= 2) < 1) { return -0.5 * (amplitude * Math.pow(2, 10 * --t) * Math.sin((t - s) * pi2 / period)); } return amplitude * Math.pow(2, -10 * --t) * Math.sin((t - s) * pi2 / period) * 0.5 + 1; } static easeInBounce(t) { return 1 - this.easeOutBounce(1 - t); } static easeOutBounce(t) { const n1 = 7.5625; const d1 = 2.75; if (t < 1 / d1) { return n1 * t * t; } else if (t < 2 / d1) { return n1 * (t -= 1.5 / d1) * t + 0.75; } else if (t < 2.5 / d1) { return n1 * (t -= 2.25 / d1) * t + 0.9375; } else { return n1 * (t -= 2.625 / d1) * t + 0.984375; } } static easeInOutBounce(t) { if (t < 0.5) { return this.easeInBounce(t * 2) * 0.5; } return this.easeOutBounce(t * 2 - 1) * 0.5 + 0.5; } static addBezier(name, mX1, mY1, mX2, mY2) { this[name] = BezierEasing(mX1, mY1, mX2, mY2); } } ",7,949,JavaScript plane,./ProjectTest/JavaScript/plane.js,"// plane/vec2.js /* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net. * @class vec2 */ var vec2 = module.exports = {}; var Utils = require('./Utils'); /** * Make a cross product and only return the z component * @method crossLength * @static * @param {Array} a * @param {Array} b * @return {Number} */ vec2.crossLength = function(a,b){ return a[0] * b[1] - a[1] * b[0]; }; /** * Cross product between a vector and the Z component of a vector * @method crossVZ * @static * @param {Array} out * @param {Array} vec * @param {Number} zcomp * @return {Array} */ vec2.crossVZ = function(out, vec, zcomp){ vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule vec2.scale(out,out,zcomp); // Scale with z return out; }; /** * Cross product between a vector and the Z component of a vector * @method crossZV * @static * @param {Array} out * @param {Number} zcomp * @param {Array} vec * @return {Array} */ vec2.crossZV = function(out, zcomp, vec){ vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule vec2.scale(out,out,zcomp); // Scale with z return out; }; /** * Rotate a vector by an angle * @method rotate * @static * @param {Array} out * @param {Array} a * @param {Number} angle * @return {Array} */ vec2.rotate = function(out,a,angle){ if(angle !== 0){ var c = Math.cos(angle), s = Math.sin(angle), x = a[0], y = a[1]; out[0] = c*x -s*y; out[1] = s*x +c*y; } else { out[0] = a[0]; out[1] = a[1]; } return out; }; /** * Rotate a vector 90 degrees clockwise * @method rotate90cw * @static * @param {Array} out * @param {Array} a * @param {Number} angle * @return {Array} */ vec2.rotate90cw = function(out, a) { var x = a[0]; var y = a[1]; out[0] = y; out[1] = -x; return out; }; /** * Transform a point position to local frame. * @method toLocalFrame * @param {Array} out * @param {Array} worldPoint * @param {Array} framePosition * @param {Number} frameAngle * @return {Array} */ vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){ var c = Math.cos(-frameAngle), s = Math.sin(-frameAngle), x = worldPoint[0] - framePosition[0], y = worldPoint[1] - framePosition[1]; out[0] = c * x - s * y; out[1] = s * x + c * y; return out; }; /** * Transform a point position to global frame. * @method toGlobalFrame * @param {Array} out * @param {Array} localPoint * @param {Array} framePosition * @param {Number} frameAngle */ vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){ var c = Math.cos(frameAngle), s = Math.sin(frameAngle), x = localPoint[0], y = localPoint[1], addX = framePosition[0], addY = framePosition[1]; out[0] = c * x - s * y + addX; out[1] = s * x + c * y + addY; }; /** * Transform a vector to local frame. * @method vectorToLocalFrame * @param {Array} out * @param {Array} worldVector * @param {Number} frameAngle * @return {Array} */ vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){ var c = Math.cos(-frameAngle), s = Math.sin(-frameAngle), x = worldVector[0], y = worldVector[1]; out[0] = c*x -s*y; out[1] = s*x +c*y; return out; }; /** * Transform a vector to global frame. * @method vectorToGlobalFrame * @param {Array} out * @param {Array} localVector * @param {Number} frameAngle */ vec2.vectorToGlobalFrame = vec2.rotate; /** * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php * @method centroid * @static * @param {Array} out * @param {Array} a * @param {Array} b * @param {Array} c * @return {Array} The ""out"" vector. */ vec2.centroid = function(out, a, b, c){ vec2.add(out, a, b); vec2.add(out, out, c); vec2.scale(out, out, 1/3); return out; }; /** * Creates a new, empty vec2 * @static * @method create * @return {Array} a new 2D vector */ vec2.create = function() { var out = new Utils.ARRAY_TYPE(2); out[0] = 0; out[1] = 0; return out; }; /** * Creates a new vec2 initialized with values from an existing vector * @static * @method clone * @param {Array} a vector to clone * @return {Array} a new 2D vector */ vec2.clone = function(a) { var out = new Utils.ARRAY_TYPE(2); out[0] = a[0]; out[1] = a[1]; return out; }; /** * Creates a new vec2 initialized with the given values * @static * @method fromValues * @param {Number} x X component * @param {Number} y Y component * @return {Array} a new 2D vector */ vec2.fromValues = function(x, y) { var out = new Utils.ARRAY_TYPE(2); out[0] = x; out[1] = y; return out; }; /** * Copy the values from one vec2 to another * @static * @method copy * @param {Array} out the receiving vector * @param {Array} a the source vector * @return {Array} out */ vec2.copy = function(out, a) { out[0] = a[0]; out[1] = a[1]; return out; }; /** * Set the components of a vec2 to the given values * @static * @method set * @param {Array} out the receiving vector * @param {Number} x X component * @param {Number} y Y component * @return {Array} out */ vec2.set = function(out, x, y) { out[0] = x; out[1] = y; return out; }; /** * Adds two vec2's * @static * @method add * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.add = function(out, a, b) { out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; return out; }; /** * Subtracts two vec2's * @static * @method subtract * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.subtract = function(out, a, b) { out[0] = a[0] - b[0]; out[1] = a[1] - b[1]; return out; }; /** * Multiplies two vec2's * @static * @method multiply * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.multiply = function(out, a, b) { out[0] = a[0] * b[0]; out[1] = a[1] * b[1]; return out; }; /** * Divides two vec2's * @static * @method divide * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.divide = function(out, a, b) { out[0] = a[0] / b[0]; out[1] = a[1] / b[1]; return out; }; /** * Scales a vec2 by a scalar number * @static * @method scale * @param {Array} out the receiving vector * @param {Array} a the vector to scale * @param {Number} b amount to scale the vector by * @return {Array} out */ vec2.scale = function(out, a, b) { out[0] = a[0] * b; out[1] = a[1] * b; return out; }; /** * Calculates the euclidian distance between two vec2's * @static * @method distance * @param {Array} a the first operand * @param {Array} b the second operand * @return {Number} distance between a and b */ vec2.distance = function(a, b) { var x = b[0] - a[0], y = b[1] - a[1]; return Math.sqrt(x*x + y*y); }; /** * Calculates the squared euclidian distance between two vec2's * @static * @method squaredDistance * @param {Array} a the first operand * @param {Array} b the second operand * @return {Number} squared distance between a and b */ vec2.squaredDistance = function(a, b) { var x = b[0] - a[0], y = b[1] - a[1]; return x*x + y*y; }; /** * Calculates the length of a vec2 * @static * @method length * @param {Array} a vector to calculate length of * @return {Number} length of a */ vec2.length = function (a) { var x = a[0], y = a[1]; return Math.sqrt(x*x + y*y); }; /** * Calculates the squared length of a vec2 * @static * @method squaredLength * @param {Array} a vector to calculate squared length of * @return {Number} squared length of a */ vec2.squaredLength = function (a) { var x = a[0], y = a[1]; return x*x + y*y; }; /** * Negates the components of a vec2 * @static * @method negate * @param {Array} out the receiving vector * @param {Array} a vector to negate * @return {Array} out */ vec2.negate = function(out, a) { out[0] = -a[0]; out[1] = -a[1]; return out; }; /** * Normalize a vec2 * @static * @method normalize * @param {Array} out the receiving vector * @param {Array} a vector to normalize * @return {Array} out */ vec2.normalize = function(out, a) { var x = a[0], y = a[1]; var len = x*x + y*y; if (len > 0) { //TODO: evaluate use of glm_invsqrt here? len = 1 / Math.sqrt(len); out[0] = a[0] * len; out[1] = a[1] * len; } return out; }; /** * Calculates the dot product of two vec2's * @static * @method dot * @param {Array} a the first operand * @param {Array} b the second operand * @return {Number} dot product of a and b */ vec2.dot = function (a, b) { return a[0] * b[0] + a[1] * b[1]; }; /** * Returns a string representation of a vector * @static * @method str * @param {Array} vec vector to represent as a string * @return {String} string representation of the vector */ vec2.str = function (a) { return 'vec2(' + a[0] + ', ' + a[1] + ')'; }; /** * Linearly interpolate/mix two vectors. * @static * @method lerp * @param {Array} out * @param {Array} a First vector * @param {Array} b Second vector * @param {number} t Lerp factor */ vec2.lerp = function (out, a, b, t) { var ax = a[0], ay = a[1]; out[0] = ax + t * (b[0] - ax); out[1] = ay + t * (b[1] - ay); return out; }; /** * Reflect a vector along a normal. * @static * @method reflect * @param {Array} out * @param {Array} vector * @param {Array} normal */ vec2.reflect = function(out, vector, normal){ var dot = vector[0] * normal[0] + vector[1] * normal[1]; out[0] = vector[0] - 2 * normal[0] * dot; out[1] = vector[1] - 2 * normal[1] * dot; }; /** * Get the intersection point between two line segments. * @static * @method getLineSegmentsIntersection * @param {Array} out * @param {Array} p0 * @param {Array} p1 * @param {Array} p2 * @param {Array} p3 * @return {boolean} True if there was an intersection, otherwise false. */ vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) { var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3); if(t < 0){ return false; } else { out[0] = p0[0] + (t * (p1[0] - p0[0])); out[1] = p0[1] + (t * (p1[1] - p0[1])); return true; } }; /** * Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0) * @static * @method getLineSegmentsIntersectionFraction * @param {Array} p0 * @param {Array} p1 * @param {Array} p2 * @param {Array} p3 * @return {number} A number between 0 and 1 if there was an intersection, otherwise -1. */ vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) { var s1_x = p1[0] - p0[0]; var s1_y = p1[1] - p0[1]; var s2_x = p3[0] - p2[0]; var s2_y = p3[1] - p2[1]; var s, t; s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y); t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y); if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected return t; } return -1; // No collision }; // plane/Plane.js var Shape = require('./Shape') , vec2 = require('./vec2') , Utils = require('./Utils'); module.exports = Plane; /** * Plane shape class. The plane is facing in the Y direction. * @class Plane * @extends Shape * @constructor * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink ""Shape""}}{{/crossLink}} constructor.) * @example * var body = new Body(); * var shape = new Plane(); * body.addShape(shape); */ function Plane(options){ options = options ? Utils.shallowClone(options) : {}; options.type = Shape.PLANE; Shape.call(this, options); } Plane.prototype = new Shape(); Plane.prototype.constructor = Plane; /** * Compute moment of inertia * @method computeMomentOfInertia */ Plane.prototype.computeMomentOfInertia = function(){ return 0; // Plane is infinite. The inertia should therefore be infinty but by convention we set 0 here }; /** * Update the bounding radius * @method updateBoundingRadius */ Plane.prototype.updateBoundingRadius = function(){ this.boundingRadius = Number.MAX_VALUE; }; /** * @method computeAABB * @param {AABB} out * @param {Array} position * @param {Number} angle */ Plane.prototype.computeAABB = function(out, position, angle){ var a = angle % (2 * Math.PI); var set = vec2.set; var max = 1e7; var lowerBound = out.lowerBound; var upperBound = out.upperBound; // Set max bounds set(lowerBound, -max, -max); set(upperBound, max, max); if(a === 0){ // y goes from -inf to 0 upperBound[1] = position[1]; } else if(a === Math.PI / 2){ // x goes from 0 to inf lowerBound[0] = position[0]; } else if(a === Math.PI){ // y goes from 0 to inf lowerBound[1] = position[1]; } else if(a === 3*Math.PI/2){ // x goes from -inf to 0 upperBound[0] = position[0]; } }; Plane.prototype.updateArea = function(){ this.area = Number.MAX_VALUE; }; var intersectPlane_planePointToFrom = vec2.create(); var intersectPlane_normal = vec2.create(); var intersectPlane_len = vec2.create(); /** * @method raycast * @param {RayResult} result * @param {Ray} ray * @param {array} position * @param {number} angle */ Plane.prototype.raycast = function(result, ray, position, angle){ var from = ray.from; var to = ray.to; var direction = ray.direction; var planePointToFrom = intersectPlane_planePointToFrom; var normal = intersectPlane_normal; var len = intersectPlane_len; // Get plane normal vec2.set(normal, 0, 1); vec2.rotate(normal, normal, angle); vec2.subtract(len, from, position); var planeToFrom = vec2.dot(len, normal); vec2.subtract(len, to, position); var planeToTo = vec2.dot(len, normal); if(planeToFrom * planeToTo > 0){ // ""from"" and ""to"" are on the same side of the plane... bail out return; } if(vec2.squaredDistance(from, to) < planeToFrom * planeToFrom){ return; } var n_dot_dir = vec2.dot(normal, direction); vec2.subtract(planePointToFrom, from, position); var t = -vec2.dot(normal, planePointToFrom) / n_dot_dir / ray.length; ray.reportIntersection(result, t, normal, -1); }; Plane.prototype.pointTest = function(localPoint){ return localPoint[1] <= 0; }; // plane/Utils.js /* global P2_ARRAY_TYPE */ module.exports = Utils; /** * Misc utility functions * @class Utils * @constructor */ function Utils(){} /** * Append the values in array b to the array a. See this for an explanation. * @method appendArray * @static * @param {Array} a * @param {Array} b */ Utils.appendArray = function(a,b){ if (b.length < 150000) { a.push.apply(a, b); } else { for (var i = 0, len = b.length; i !== len; ++i) { a.push(b[i]); } } }; /** * Garbage free Array.splice(). Does not allocate a new array. * @method splice * @static * @param {Array} array * @param {Number} index * @param {Number} howmany */ Utils.splice = function(array,index,howmany){ howmany = howmany || 1; for (var i=index, len=array.length-howmany; i < len; i++){ array[i] = array[i + howmany]; } array.length = len; }; /** * Remove an element from an array, if the array contains the element. * @method arrayRemove * @static * @param {Array} array * @param {Number} element */ Utils.arrayRemove = function(array, element){ var idx = array.indexOf(element); if(idx!==-1){ Utils.splice(array, idx, 1); } }; /** * The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below. * @static * @property {function} ARRAY_TYPE * @example * * */ if(typeof P2_ARRAY_TYPE !== 'undefined') { Utils.ARRAY_TYPE = P2_ARRAY_TYPE; } else if (typeof Float32Array !== 'undefined'){ Utils.ARRAY_TYPE = Float32Array; } else { Utils.ARRAY_TYPE = Array; } /** * Extend an object with the properties of another * @static * @method extend * @param {object} a * @param {object} b */ Utils.extend = function(a,b){ for(var key in b){ a[key] = b[key]; } }; /** * Shallow clone an object. Returns a new object instance with the same properties as the input instance. * @static * @method shallowClone * @param {object} obj */ Utils.shallowClone = function(obj){ var newObj = {}; Utils.extend(newObj, obj); return newObj; }; /** * Extend an options object with default values. * @deprecated Not used internally, will be removed. * @static * @method defaults * @param {object} options The options object. May be falsy: in this case, a new object is created and returned. * @param {object} defaults An object containing default values. * @return {object} The modified options object. */ Utils.defaults = function(options, defaults){ console.warn('Utils.defaults is deprecated.'); options = options || {}; for(var key in defaults){ if(!(key in options)){ options[key] = defaults[key]; } } return options; }; // plane/Shape.js module.exports = Shape; var vec2 = require('./vec2'); /** * Base class for shapes. Not to be used directly. * @class Shape * @constructor * @param {object} [options] * @param {number} [options.angle=0] * @param {number} [options.collisionGroup=1] * @param {number} [options.collisionMask=1] * @param {boolean} [options.collisionResponse=true] * @param {Material} [options.material=null] * @param {array} [options.position] * @param {boolean} [options.sensor=false] * @param {object} [options.type=0] */ function Shape(options){ options = options || {}; /** * The body this shape is attached to. A shape can only be attached to a single body. * @property {Body} body */ this.body = null; /** * Body-local position of the shape. * @property {Array} position */ this.position = vec2.create(); if(options.position){ vec2.copy(this.position, options.position); } /** * Body-local angle of the shape. * @property {number} angle */ this.angle = options.angle || 0; /** * The type of the shape. One of: * * * * @property {number} type */ this.type = options.type || 0; /** * Shape object identifier. Read only. * @readonly * @type {Number} * @property id */ this.id = Shape.idCounter++; /** * Bounding circle radius of this shape * @readonly * @property boundingRadius * @type {Number} */ this.boundingRadius = 0; /** * Collision group that this shape belongs to (bit mask). See this tutorial. * @property collisionGroup * @type {Number} * @example * // Setup bits for each available group * var PLAYER = Math.pow(2,0), * ENEMY = Math.pow(2,1), * GROUND = Math.pow(2,2) * * // Put shapes into their groups * player1Shape.collisionGroup = PLAYER; * player2Shape.collisionGroup = PLAYER; * enemyShape .collisionGroup = ENEMY; * groundShape .collisionGroup = GROUND; * * // Assign groups that each shape collide with. * // Note that the players can collide with ground and enemies, but not with other players. * player1Shape.collisionMask = ENEMY | GROUND; * player2Shape.collisionMask = ENEMY | GROUND; * enemyShape .collisionMask = PLAYER | GROUND; * groundShape .collisionMask = PLAYER | ENEMY; * * @example * // How collision check is done * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){ * // The shapes will collide * } */ this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1; /** * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc. * @property {Boolean} collisionResponse */ this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true; /** * Collision mask of this shape. See .collisionGroup. * @property collisionMask * @type {Number} */ this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1; /** * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead. * @property material * @type {Material} */ this.material = options.material || null; /** * Area of this shape. * @property area * @type {Number} */ this.area = 0; /** * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts. * @property {Boolean} sensor */ this.sensor = options.sensor !== undefined ? options.sensor : false; if(this.type){ this.updateBoundingRadius(); } this.updateArea(); } Shape.idCounter = 0; /** * @static * @property {Number} CIRCLE */ Shape.CIRCLE = 1; /** * @static * @property {Number} PARTICLE */ Shape.PARTICLE = 2; /** * @static * @property {Number} PLANE */ Shape.PLANE = 4; /** * @static * @property {Number} CONVEX */ Shape.CONVEX = 8; /** * @static * @property {Number} LINE */ Shape.LINE = 16; /** * @static * @property {Number} BOX */ Shape.BOX = 32; /** * @static * @property {Number} CAPSULE */ Shape.CAPSULE = 64; /** * @static * @property {Number} HEIGHTFIELD */ Shape.HEIGHTFIELD = 128; Shape.prototype = { /** * Should return the moment of inertia around the Z axis of the body. See Wikipedia's list of moments of inertia. * @method computeMomentOfInertia * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0. */ computeMomentOfInertia: function(){}, /** * Returns the bounding circle radius of this shape. * @method updateBoundingRadius * @return {Number} */ updateBoundingRadius: function(){}, /** * Update the .area property of the shape. * @method updateArea */ updateArea: function(){}, /** * Compute the world axis-aligned bounding box (AABB) of this shape. * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position World position of the shape. * @param {Number} angle World angle of the shape. */ computeAABB: function(/*out, position, angle*/){ // To be implemented in each subclass }, /** * Perform raycasting on this shape. * @method raycast * @param {RayResult} result Where to store the resulting data. * @param {Ray} ray The Ray that you want to use for raycasting. * @param {array} position World position of the shape (the .position property will be ignored). * @param {number} angle World angle of the shape (the .angle property will be ignored). */ raycast: function(/*result, ray, position, angle*/){ // To be implemented in each subclass }, /** * Test if a point is inside this shape. * @method pointTest * @param {array} localPoint * @return {boolean} */ pointTest: function(/*localPoint*/){ return false; }, /** * Transform a world point to local shape space (assumed the shape is transformed by both itself and the body). * @method worldPointToLocal * @param {array} out * @param {array} worldPoint */ worldPointToLocal: (function () { var shapeWorldPosition = vec2.create(); return function (out, worldPoint) { var body = this.body; vec2.rotate(shapeWorldPosition, this.position, body.angle); vec2.add(shapeWorldPosition, shapeWorldPosition, body.position); vec2.toLocalFrame(out, worldPoint, shapeWorldPosition, this.body.angle + this.angle); }; })() }; ",4,1052,JavaScript span,./ProjectTest/JavaScript/span.js,"// span/Span.js import Util from ""./Util""; import MathUtil from ""./MathUtil""; export default class Span { constructor(a, b, center) { if (Util.isArray(a)) { this.isArray = true; this.a = a; } else { this.isArray = false; this.a = Util.initValue(a, 1); this.b = Util.initValue(b, this.a); this.center = Util.initValue(center, false); } } getValue(isInt = false) { if (this.isArray) { return Util.getRandFromArray(this.a); } else { if (!this.center) { return MathUtil.randomAToB(this.a, this.b, isInt); } else { return MathUtil.randomFloating(this.a, this.b, isInt); } } } /** * Returns a new Span object * * @memberof Proton#Proton.Util * @method setSpanValue * * @todo a, b and c should be 'Mixed' or 'Number'? * * @param {Mixed | Span} a * @param {Mixed} b * @param {Mixed} c * * @return {Span} */ static setSpanValue(a, b, c) { if (a instanceof Span) { return a; } else { if (b === undefined) { return new Span(a); } else { if (c === undefined) return new Span(a, b); else return new Span(a, b, c); } } } /** * Returns the value from a Span, if the param is not a Span it will return the given parameter * * @memberof Proton#Proton.Util * @method getValue * * @param {Mixed | Span} pan * * @return {Mixed} the value of Span OR the parameter if it is not a Span */ static getSpanValue(pan) { return pan instanceof Span ? pan.getValue() : pan; } } // span/DomUtil.js export default { /** * Creates and returns a new canvas. The opacity is by default set to 0 * * @memberof Proton#Proton.DomUtil * @method createCanvas * * @param {String} $id the canvas' id * @param {Number} $width the canvas' width * @param {Number} $height the canvas' height * @param {String} [$position=absolute] the canvas' position, default is 'absolute' * * @return {Object} */ createCanvas(id, width, height, position = ""absolute"") { const dom = document.createElement(""canvas""); dom.id = id; dom.width = width; dom.height = height; dom.style.opacity = 0; dom.style.position = position; this.transform(dom, -500, -500, 0, 0); return dom; }, createDiv(id, width, height) { const dom = document.createElement(""div""); dom.id = id; dom.style.position = ""absolute""; this.resize(dom, width, height); return dom; }, resize(dom, width, height) { dom.style.width = width + ""px""; dom.style.height = height + ""px""; dom.style.marginLeft = -width / 2 + ""px""; dom.style.marginTop = -height / 2 + ""px""; }, /** * Adds a transform: translate(), scale(), rotate() to a given div dom for all browsers * * @memberof Proton#Proton.DomUtil * @method transform * * @param {HTMLDivElement} div * @param {Number} $x * @param {Number} $y * @param {Number} $scale * @param {Number} $rotate */ transform(div, x, y, scale, rotate) { div.style.willChange = ""transform""; const transform = `translate(${x}px, ${y}px) scale(${scale}) rotate(${rotate}deg)`; this.css3(div, ""transform"", transform); }, transform3d(div, x, y, scale, rotate) { div.style.willChange = ""transform""; const transform = `translate3d(${x}px, ${y}px, 0) scale(${scale}) rotate(${rotate}deg)`; this.css3(div, ""backfaceVisibility"", ""hidden""); this.css3(div, ""transform"", transform); }, css3(div, key, val) { const bkey = key.charAt(0).toUpperCase() + key.substr(1); div.style[`Webkit${bkey}`] = val; div.style[`Moz${bkey}`] = val; div.style[`O${bkey}`] = val; div.style[`ms${bkey}`] = val; div.style[`${key}`] = val; } }; // span/ImgUtil.js import WebGLUtil from ""./WebGLUtil""; import DomUtil from ""./DomUtil""; const imgsCache = {}; const canvasCache = {}; let canvasId = 0; export default { /** * This will get the image data. It could be necessary to create a Proton.Zone. * * @memberof Proton#Proton.Util * @method getImageData * * @param {HTMLCanvasElement} context any canvas, must be a 2dContext 'canvas.getContext('2d')' * @param {Object} image could be any dom image, e.g. document.getElementById('thisIsAnImgTag'); * @param {Proton.Rectangle} rect */ getImageData(context, image, rect) { context.drawImage(image, rect.x, rect.y); const imagedata = context.getImageData(rect.x, rect.y, rect.width, rect.height); context.clearRect(rect.x, rect.y, rect.width, rect.height); return imagedata; }, /** * @memberof Proton#Proton.Util * @method getImgFromCache * * @todo add description * @todo describe func * * @param {Mixed} img * @param {Proton.Particle} particle * @param {Boolean} drawCanvas set to true if a canvas should be saved into particle.data.canvas * @param {Boolean} func */ getImgFromCache(img, callback, param) { const src = typeof img === ""string"" ? img : img.src; if (imgsCache[src]) { callback(imgsCache[src], param); } else { const image = new Image(); image.onload = e => { imgsCache[src] = e.target; callback(imgsCache[src], param); }; image.src = src; } }, getCanvasFromCache(img, callback, param) { const src = img.src; if (!canvasCache[src]) { const width = WebGLUtil.nhpot(img.width); const height = WebGLUtil.nhpot(img.height); const canvas = DomUtil.createCanvas(`proton_canvas_cache_${++canvasId}`, width, height); const context = canvas.getContext(""2d""); context.drawImage(img, 0, 0, img.width, img.height); canvasCache[src] = canvas; } callback && callback(canvasCache[src], param); return canvasCache[src]; } }; // span/Util.js import ImgUtil from ""./ImgUtil""; export default { /** * Returns the default if the value is null or undefined * * @memberof Proton#Proton.Util * @method initValue * * @param {Mixed} value a specific value, could be everything but null or undefined * @param {Mixed} defaults the default if the value is null or undefined */ initValue(value, defaults) { value = value !== null && value !== undefined ? value : defaults; return value; }, /** * Checks if the value is a valid array * * @memberof Proton#Proton.Util * @method isArray * * @param {Array} value Any array * * @returns {Boolean} */ isArray(value) { return Object.prototype.toString.call(value) === ""[object Array]""; }, /** * Destroyes the given array * * @memberof Proton#Proton.Util * @method emptyArray * * @param {Array} array Any array */ emptyArray(arr) { if (arr) arr.length = 0; }, toArray(arr) { return this.isArray(arr) ? arr : [arr]; }, sliceArray(arr1, index, arr2) { this.emptyArray(arr2); for (let i = index; i < arr1.length; i++) { arr2.push(arr1[i]); } }, getRandFromArray(arr) { if (!arr) return null; return arr[Math.floor(arr.length * Math.random())]; }, /** * Destroyes the given object * * @memberof Proton#Proton.Util * @method emptyObject * * @param {Object} obj Any object */ emptyObject(obj, ignore = null) { for (let key in obj) { if (ignore && ignore.indexOf(key) > -1) continue; delete obj[key]; } }, /** * Makes an instance of a class and binds the given array * * @memberof Proton#Proton.Util * @method classApply * * @param {Function} constructor A class to make an instance from * @param {Array} [args] Any array to bind it to the constructor * * @return {Object} The instance of constructor, optionally bind with args */ classApply(constructor, args = null) { if (!args) { return new constructor(); } else { const FactoryFunc = constructor.bind.apply(constructor, [null].concat(args)); return new FactoryFunc(); } }, /** * This will get the image data. It could be necessary to create a Proton.Zone. * * @memberof Proton#Proton.Util * @method getImageData * * @param {HTMLCanvasElement} context any canvas, must be a 2dContext 'canvas.getContext('2d')' * @param {Object} image could be any dom image, e.g. document.getElementById('thisIsAnImgTag'); * @param {Proton.Rectangle} rect */ getImageData(context, image, rect) { return ImgUtil.getImageData(context, image, rect); }, destroyAll(arr, param = null) { let i = arr.length; while (i--) { try { arr[i].destroy(param); } catch (e) {} delete arr[i]; } arr.length = 0; }, assign(target, source) { if (typeof Object.assign !== ""function"") { for (let key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } return target; } else { return Object.assign(target, source); } } }; // span/WebGLUtil.js export default { /** * @memberof Proton#Proton.WebGLUtil * @method ipot * * @todo add description * @todo add length description * * @param {Number} length * * @return {Boolean} */ ipot(length) { return (length & (length - 1)) === 0; }, /** * @memberof Proton#Proton.WebGLUtil * @method nhpot * * @todo add description * @todo add length description * * @param {Number} length * * @return {Number} */ nhpot(length) { --length; for (let i = 1; i < 32; i <<= 1) { length = length | (length >> i); } return length + 1; }, /** * @memberof Proton#Proton.WebGLUtil * @method makeTranslation * * @todo add description * @todo add tx, ty description * @todo add return description * * @param {Number} tx either 0 or 1 * @param {Number} ty either 0 or 1 * * @return {Object} */ makeTranslation(tx, ty) { return [1, 0, 0, 0, 1, 0, tx, ty, 1]; }, /** * @memberof Proton#Proton.WebGLUtil * @method makeRotation * * @todo add description * @todo add return description * * @param {Number} angleInRadians * * @return {Object} */ makeRotation(angleInRadians) { let c = Math.cos(angleInRadians); let s = Math.sin(angleInRadians); return [c, -s, 0, s, c, 0, 0, 0, 1]; }, /** * @memberof Proton#Proton.WebGLUtil * @method makeScale * * @todo add description * @todo add tx, ty description * @todo add return description * * @param {Number} sx either 0 or 1 * @param {Number} sy either 0 or 1 * * @return {Object} */ makeScale(sx, sy) { return [sx, 0, 0, 0, sy, 0, 0, 0, 1]; }, /** * @memberof Proton#Proton.WebGLUtil * @method matrixMultiply * * @todo add description * @todo add a, b description * @todo add return description * * @param {Object} a * @param {Object} b * * @return {Object} */ matrixMultiply(a, b) { let a00 = a[0 * 3 + 0]; let a01 = a[0 * 3 + 1]; let a02 = a[0 * 3 + 2]; let a10 = a[1 * 3 + 0]; let a11 = a[1 * 3 + 1]; let a12 = a[1 * 3 + 2]; let a20 = a[2 * 3 + 0]; let a21 = a[2 * 3 + 1]; let a22 = a[2 * 3 + 2]; let b00 = b[0 * 3 + 0]; let b01 = b[0 * 3 + 1]; let b02 = b[0 * 3 + 2]; let b10 = b[1 * 3 + 0]; let b11 = b[1 * 3 + 1]; let b12 = b[1 * 3 + 2]; let b20 = b[2 * 3 + 0]; let b21 = b[2 * 3 + 1]; let b22 = b[2 * 3 + 2]; return [ a00 * b00 + a01 * b10 + a02 * b20, a00 * b01 + a01 * b11 + a02 * b21, a00 * b02 + a01 * b12 + a02 * b22, a10 * b00 + a11 * b10 + a12 * b20, a10 * b01 + a11 * b11 + a12 * b21, a10 * b02 + a11 * b12 + a12 * b22, a20 * b00 + a21 * b10 + a22 * b20, a20 * b01 + a21 * b11 + a22 * b21, a20 * b02 + a21 * b12 + a22 * b22 ]; } }; // span/MathUtil.js const PI = 3.1415926; const INFINITY = Infinity; const MathUtil = { PI: PI, PIx2: PI * 2, PI_2: PI / 2, PI_180: PI / 180, N180_PI: 180 / PI, Infinity: -999, isInfinity(num) { return num === this.Infinity || num === INFINITY; }, randomAToB(a, b, isInt = false) { if (!isInt) return a + Math.random() * (b - a); else return ((Math.random() * (b - a)) >> 0) + a; }, randomFloating(center, f, isInt) { return this.randomAToB(center - f, center + f, isInt); }, randomColor() { return ""#"" + (""00000"" + ((Math.random() * 0x1000000) << 0).toString(16)).slice(-6); }, randomZone(display) {}, floor(num, k = 4) { const digits = Math.pow(10, k); return Math.floor(num * digits) / digits; }, degreeTransform(a) { return (a * PI) / 180; }, toColor16(num) { return `#${num.toString(16)}`; } }; export default MathUtil; ",6,536,JavaScript t_test,./ProjectTest/JavaScript/t_test.js,"// t_test/t_test.js import mean from ""./mean.js""; import standardDeviation from ""./standard_deviation.js""; /** * This is to compute [a one-sample t-test](https://en.wikipedia.org/wiki/Student%27s_t-test#One-sample_t-test), comparing the mean * of a sample to a known value, x. * * in this case, we're trying to determine whether the * population mean is equal to the value that we know, which is `x` * here. Usually the results here are used to look up a * [p-value](http://en.wikipedia.org/wiki/P-value), which, for * a certain level of significance, will let you determine that the * null hypothesis can or cannot be rejected. * * @param {Array} x sample of one or more numbers * @param {number} expectedValue expected value of the population mean * @returns {number} value * @example * tTest([1, 2, 3, 4, 5, 6], 3.385).toFixed(2); // => '0.16' */ function tTest(x, expectedValue) { // The mean of the sample const sampleMean = mean(x); // The standard deviation of the sample const sd = standardDeviation(x); // Square root the length of the sample const rootN = Math.sqrt(x.length); // returning the t value return (sampleMean - expectedValue) / (sd / rootN); } export default tTest; // t_test/sum_nth_power_deviations.js import mean from ""./mean.js""; /** * The sum of deviations to the Nth power. * When n=2 it's the sum of squared deviations. * When n=3 it's the sum of cubed deviations. * * @param {Array} x * @param {number} n power * @returns {number} sum of nth power deviations * * @example * var input = [1, 2, 3]; * // since the variance of a set is the mean squared * // deviations, we can calculate that with sumNthPowerDeviations: * sumNthPowerDeviations(input, 2) / input.length; */ function sumNthPowerDeviations(x, n) { const meanValue = mean(x); let sum = 0; let tempValue; let i; // This is an optimization: when n is 2 (we're computing a number squared), // multiplying the number by itself is significantly faster than using // the Math.pow method. if (n === 2) { for (i = 0; i < x.length; i++) { tempValue = x[i] - meanValue; sum += tempValue * tempValue; } } else { for (i = 0; i < x.length; i++) { sum += Math.pow(x[i] - meanValue, n); } } return sum; } export default sumNthPowerDeviations; // t_test/sum.js /** * Our default sum is the [Kahan-Babuska algorithm](https://pdfs.semanticscholar.org/1760/7d467cda1d0277ad272deb2113533131dc09.pdf). * This method is an improvement over the classical * [Kahan summation algorithm](https://en.wikipedia.org/wiki/Kahan_summation_algorithm). * It aims at computing the sum of a list of numbers while correcting for * floating-point errors. Traditionally, sums are calculated as many * successive additions, each one with its own floating-point roundoff. These * losses in precision add up as the number of numbers increases. This alternative * algorithm is more accurate than the simple way of calculating sums by simple * addition. * * This runs in `O(n)`, linear time, with respect to the length of the array. * * @param {Array} x input * @return {number} sum of all input numbers * @example * sum([1, 2, 3]); // => 6 */ function sum(x) { // If the array is empty, we needn't bother computing its sum if (x.length === 0) { return 0; } // Initializing the sum as the first number in the array let sum = x[0]; // Keeping track of the floating-point error correction let correction = 0; let transition; if (typeof sum !== ""number"") { return Number.NaN; } for (let i = 1; i < x.length; i++) { if (typeof x[i] !== ""number"") { return Number.NaN; } transition = sum + x[i]; // Here we need to update the correction in a different fashion // if the new absolute value is greater than the absolute sum if (Math.abs(sum) >= Math.abs(x[i])) { correction += sum - transition + x[i]; } else { correction += x[i] - transition + sum; } sum = transition; } // Returning the corrected sum return sum + correction; } export default sum; // t_test/mean.js import sum from ""./sum.js""; /** * The mean, _also known as average_, * is the sum of all values over the number of values. * This is a [measure of central tendency](https://en.wikipedia.org/wiki/Central_tendency): * a method of finding a typical or central value of a set of numbers. * * This runs in `O(n)`, linear time, with respect to the length of the array. * * @param {Array} x sample of one or more data points * @throws {Error} if the length of x is less than one * @returns {number} mean * @example * mean([0, 10]); // => 5 */ function mean(x) { if (x.length === 0) { throw new Error(""mean requires at least one data point""); } return sum(x) / x.length; } export default mean; // t_test/variance.js import sumNthPowerDeviations from ""./sum_nth_power_deviations.js""; /** * The [variance](http://en.wikipedia.org/wiki/Variance) * is the sum of squared deviations from the mean. * * This is an implementation of variance, not sample variance: * see the `sampleVariance` method if you want a sample measure. * * @param {Array} x a population of one or more data points * @returns {number} variance: a value greater than or equal to zero. * zero indicates that all values are identical. * @throws {Error} if x's length is 0 * @example * variance([1, 2, 3, 4, 5, 6]); // => 2.9166666666666665 */ function variance(x) { if (x.length === 0) { throw new Error(""variance requires at least one data point""); } // Find the mean of squared deviations between the // mean value and each value. return sumNthPowerDeviations(x, 2) / x.length; } export default variance; // t_test/standard_deviation.js import variance from ""./variance.js""; /** * The [standard deviation](http://en.wikipedia.org/wiki/Standard_deviation) * is the square root of the variance. This is also known as the population * standard deviation. It's useful for measuring the amount * of variation or dispersion in a set of values. * * Standard deviation is only appropriate for full-population knowledge: for * samples of a population, {@link sampleStandardDeviation} is * more appropriate. * * @param {Array} x input * @returns {number} standard deviation * @example * variance([2, 4, 4, 4, 5, 5, 7, 9]); // => 4 * standardDeviation([2, 4, 4, 4, 5, 5, 7, 9]); // => 2 */ function standardDeviation(x) { if (x.length === 1) { return 0; } const v = variance(x); return Math.sqrt(v); } export default standardDeviation; ",6,213,JavaScript