code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
async function retryAsyncFunction(retries, delay, func, ...args) { let attempt = 0; while (attempt < retries) { try { const result = await func(...args); return result; } catch (error) { attempt++; if (attempt < retries) { await new Promise(resolve => setTimeout(resolve, delay)); } else { throw error; } } } }
* Generic function for retrying an async function @param {number} retries @param {number} delay @param {Function} func @param {any[]} args
retryAsyncFunction ( retries , delay , func , ... args )
javascript
hashicorp/vault-action
src/auth.js
https://github.com/hashicorp/vault-action/blob/master/src/auth.js
MIT
async function getSecrets(secretRequests, client, ignoreNotFound) { const responseCache = new Map(); let results = []; let upperCaseEnv = false; for (const secretRequest of secretRequests) { let { path, selector } = secretRequest; const requestPath = `v1/${path}`; let body; let cachedResponse = false; if (responseCache.has(requestPath)) { body = responseCache.get(requestPath); cachedResponse = true; } else { try { const result = await client.get(requestPath); body = result.body; responseCache.set(requestPath, body); } catch (error) { const {response} = error; if (response?.statusCode === 404) { notFoundMsg = `Unable to retrieve result for "${path}" because it was not found: ${response.body.trim()}`; const ignoreNotFound = (core.getInput('ignoreNotFound', { required: false }) || 'false').toLowerCase() != 'false'; if (ignoreNotFound) { core.error(`✘ ${notFoundMsg}`); continue; } else { throw Error(notFoundMsg) } } throw error } } body = JSON.parse(body); if (selector === WILDCARD || selector === WILDCARD_UPPERCASE) { upperCaseEnv = selector === WILDCARD_UPPERCASE; let keys = body.data; if (body.data["data"] != undefined) { keys = keys.data; } for (let key in keys) { let newRequest = Object.assign({},secretRequest); newRequest.selector = key; if (secretRequest.selector === secretRequest.outputVarName) { newRequest.outputVarName = key; newRequest.envVarName = key; } else { newRequest.outputVarName = secretRequest.outputVarName+key; newRequest.envVarName = secretRequest.envVarName+key; } newRequest.outputVarName = normalizeOutputKey(newRequest.outputVarName); newRequest.envVarName = normalizeOutputKey(newRequest.envVarName, upperCaseEnv); // JSONata field references containing reserved tokens should // be enclosed in backticks // https://docs.jsonata.org/simple#examples if (key.includes(".")) { const backtick = '`'; key = backtick.concat(key, backtick); } selector = key; results = await selectAndAppendResults( selector, body, cachedResponse, newRequest, results ); } } else { results = await selectAndAppendResults( selector, body, cachedResponse, secretRequest, results ); } } return results; }
@template TRequest @param {Array<TRequest>} secretRequests @param {import('got').Got} client @return {Promise<SecretResponse<TRequest>[]>}
getSecrets ( secretRequests , client , ignoreNotFound )
javascript
hashicorp/vault-action
src/secrets.js
https://github.com/hashicorp/vault-action/blob/master/src/secrets.js
MIT
async function selectData(data, selector) { const ata = jsonata(selector); let result = JSON.stringify(await ata.evaluate(data)); // Compat for custom engines if (!result && ((ata.ast().type === "path" && ata.ast()['steps'].length === 1) || ata.ast().type === "string") && selector !== 'data' && 'data' in data) { result = JSON.stringify(await jsonata(`data.${selector}`).evaluate(data)); } else if (!result) { throw Error(`Unable to retrieve result for ${selector}. No match data was found. Double check your Key or Selector.`); } if (result.startsWith(`"`)) { result = JSON.parse(result); } return result; }
Uses a Jsonata selector retrieve a bit of data from the result @param {object} data @param {string} selector
selectData ( data , selector )
javascript
hashicorp/vault-action
src/secrets.js
https://github.com/hashicorp/vault-action/blob/master/src/secrets.js
MIT
function mockGithubOIDCResponse(aud= "https://github.com/hashicorp/vault-action") { const alg = 'RS256'; const header = { alg: alg, typ: 'JWT' }; const now = rsasign.KJUR.jws.IntDate.getNow(); const payload = { jti: "unique-id", sub: "repo:hashicorp/vault-action:ref:refs/heads/main", aud, ref: "refs/heads/main", sha: "commit-sha", repository: "hashicorp/vault-action", repository_owner: "hashicorp", run_id: "1", run_number: "1", run_attempt: "1", actor: "github-username", workflow: "Workflow Name", head_ref: "", base_ref: "", event_name: "push", ref_type: "branch", job_workflow_ref: "hashicorp/vault-action/.github/workflows/workflow.yml@refs/heads/main", iss: 'vault-action', iat: now, nbf: now, exp: now + 3600, }; const decryptedKey = rsasign.KEYUTIL.getKey(privateRsaKey); return rsasign.KJUR.jws.JWS.sign(alg, JSON.stringify(header), JSON.stringify(payload), decryptedKey); }
Returns Github OIDC response mock @param {string} aud Audience claim @returns {string}
mockGithubOIDCResponse ( aud = "https://github.com/hashicorp/vault-action" )
javascript
hashicorp/vault-action
integrationTests/basic/jwt_auth.test.js
https://github.com/hashicorp/vault-action/blob/master/integrationTests/basic/jwt_auth.test.js
MIT
Mesh.prototype.setDrawOptions = function setOptions (options) { this._changeQueue.push(Commands.GL_SET_DRAW_OPTIONS); this._changeQueue.push(options); this.value.drawOptions = options; return this; };
Pass custom options to Mesh, such as a 3 element map which displaces the position of each vertex in world space. @method @param {Object} options Draw options @return {Mesh} Current mesh
setOptions ( options )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.getDrawOptions = function getDrawOptions () { return this.value.drawOptions; };
Get the mesh's custom options. @method @returns {Object} Options
getDrawOptions ( )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.setGeometry = function setGeometry (geometry, options) { if (typeof geometry === 'string') { if (!Geometry[geometry]) throw 'Invalid geometry: "' + geometry + '".'; else geometry = new Geometry[geometry](options); } if (this.value.geometry !== geometry || this._inDraw) { if (this._initialized) { this._changeQueue.push(Commands.GL_SET_GEOMETRY); this._changeQueue.push(geometry.spec.id); this._changeQueue.push(geometry.spec.type); this._changeQueue.push(geometry.spec.dynamic); } this._requestUpdate(); this.value.geometry = geometry; } if (this._initialized) { if (this._node) { var i = this.value.geometry.spec.invalidations.length; if (i) this._requestUpdate(); while (i--) { this.value.geometry.spec.invalidations.pop(); this._changeQueue.push(Commands.GL_BUFFER_DATA); this._changeQueue.push(this.value.geometry.spec.id); this._changeQueue.push(this.value.geometry.spec.bufferNames[i]); this._changeQueue.push(this.value.geometry.spec.bufferValues[i]); this._changeQueue.push(this.value.geometry.spec.bufferSpacings[i]); this._changeQueue.push(this.value.geometry.spec.dynamic); } } } return this; };
Assigns a geometry to be used for this mesh. Sets the geometry from either a 'Geometry' or a valid primitive (string) name. Queues the set command for this geometry and looks for buffers to send to the renderer to update geometry. @method @param {Geometry|String} geometry Geometry to be associated with the mesh. @param {Object} options Various configurations for geometries. @return {Mesh} Mesh
setGeometry ( geometry , options )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.getGeometry = function getGeometry () { return this.value.geometry; };
Gets the geometry of a mesh. @method @returns {Geometry} Geometry
getGeometry ( )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.setBaseColor = function setBaseColor (color) { var uniformValue; var isMaterial = color.__isAMaterial__; var isColor = !!color.getNormalizedRGBA; if (isMaterial) { addMeshToMaterial(this, color, 'baseColor'); this.value.color = null; this.value.expressions.baseColor = color; uniformValue = color; } else if (isColor) { this.value.expressions.baseColor = null; this.value.color = color; uniformValue = color.getNormalizedRGBA(); } if (this._initialized) { // If a material expression if (color.__isAMaterial__) { this._changeQueue.push(Commands.MATERIAL_INPUT); } // If a color component else if (color.getNormalizedRGB) { this._changeQueue.push(Commands.GL_UNIFORMS); } this._changeQueue.push('u_baseColor'); this._changeQueue.push(uniformValue); } this._requestUpdate(); return this; };
Changes the color of Mesh, passing either a material expression or color using the 'Color' utility component. @method @param {Object|Color} color Material, image, vec3, or Color instance @return {Mesh} Mesh
setBaseColor ( color )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.getBaseColor = function getBaseColor () { return this.value.expressions.baseColor || this.value.color; };
Returns either the material expression or the color instance of Mesh. @method @returns {MaterialExpress|Color} MaterialExpress or Color instance
getBaseColor ( )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.getFlatShading = function getFlatShading () { return this.value.flatShading; };
Returns a boolean for whether Mesh is affected by light. @method @returns {Boolean} Boolean
getFlatShading ( )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.getNormals = function getNormals (materialExpression) { return this.value.expressions.normals; };
Returns the Normals expression of Mesh @method @param {materialExpression} materialExpression Normals Material Expression @returns {Array} The normals expression for Mesh
getNormals ( materialExpression )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.getGlossiness = function getGlossiness() { return this.value.expressions.glossiness || this.value.glossiness; };
Returns material expression or scalar value for glossiness. @method @returns {MaterialExpress|Number} MaterialExpress or Number
getGlossiness ( )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.getPositionOffset = function getPositionOffset () { return this.value.expressions.positionOffset || this.value.positionOffset; };
Returns position offset. @method @returns {MaterialExpress|Number} MaterialExpress or Number
getPositionOffset ( )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.getMaterialExpressions = function getMaterialExpressions () { return this.value.expressions; };
Get the mesh's expressions @method @returns {Object} Object
getMaterialExpressions ( )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.getValue = function getValue () { return this.value; };
Get the mesh's value @method @returns {Number} Value
getValue ( )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype._pushInvalidations = function _pushInvalidations (expressionName) { var uniformKey; var expression = this.value.expressions[expressionName]; var sender = this._node; if (expression) { expression.traverse(function (node) { var i = node.invalidations.length; while (i--) { uniformKey = node.invalidations.pop(); sender.sendDrawCommand(Commands.GL_UNIFORMS); sender.sendDrawCommand(uniformKey); sender.sendDrawCommand(node.uniforms[uniformKey]); } }); } return this; };
Queues the invalidations for Mesh @param {String} expressionName Expression Name @return {Mesh} Mesh
_pushInvalidations ( expressionName )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.onUpdate = function onUpdate() { var node = this._node; var queue = this._changeQueue; if (node && node.isMounted()) { node.sendDrawCommand(Commands.WITH); node.sendDrawCommand(node.getLocation()); // If any invalidations exist, push them into the queue if (this.value.color && this.value.color.isActive()) { this._node.sendDrawCommand(Commands.GL_UNIFORMS); this._node.sendDrawCommand('u_baseColor'); this._node.sendDrawCommand(this.value.color.getNormalizedRGBA()); this._node.requestUpdateOnNextTick(this._id); } if (this.value.glossiness && this.value.glossiness[0] && this.value.glossiness[0].isActive()) { this._node.sendDrawCommand(Commands.GL_UNIFORMS); this._node.sendDrawCommand('u_glossiness'); var glossiness = this.value.glossiness[0].getNormalizedRGB(); glossiness.push(this.value.glossiness[1]); this._node.sendDrawCommand(glossiness); this._node.requestUpdateOnNextTick(this._id); } else { this._requestingUpdate = false; } // If any invalidations exist, push them into the queue this._pushInvalidations('baseColor'); this._pushInvalidations('positionOffset'); this._pushInvalidations('normals'); this._pushInvalidations('glossiness'); for (var i = 0; i < queue.length; i++) { node.sendDrawCommand(queue[i]); } queue.length = 0; } };
Sends draw commands to the renderer @private @method @return {undefined} undefined
onUpdate ( )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.onMount = function onMount (node, id) { this._node = node; this._id = id; TransformSystem.makeCalculateWorldMatrixAt(node.getLocation()); this.draw(); };
Save reference to node, set its ID and call draw on Mesh. @method @param {Node} node Node @param {Number} id Identifier for Mesh @return {undefined} undefined
onMount ( node , id )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.onDismount = function onDismount () { this._initialized = false; this._inDraw = false; this._node.sendDrawCommand(Commands.WITH); this._node.sendDrawCommand(this._node.getLocation()); this._node.sendDrawCommand(Commands.GL_REMOVE_MESH); this._node = null; this._id = null; };
Queues the command for dismounting Mesh @method @return {undefined} undefined
onDismount ( )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.onShow = function onShow () { this._changeQueue.push(Commands.GL_MESH_VISIBILITY, true); this._requestUpdate(); };
Makes Mesh visible @method @return {undefined} undefined
onShow ( )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.onHide = function onHide () { this._changeQueue.push(Commands.GL_MESH_VISIBILITY, false); this._requestUpdate(); };
Makes Mesh hidden @method @return {undefined} undefined
onHide ( )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.onTransformChange = function onTransformChange (transform) { if (this._initialized) { this._changeQueue.push(Commands.GL_UNIFORMS); this._changeQueue.push('u_transform'); this._changeQueue.push(transform.getWorldTransform()); } this._requestUpdate(); };
Receives transform change updates from the scene graph. @method @private @param {Array} transform Transform matric @return {undefined} undefined
onTransformChange ( transform )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.onSizeChange = function onSizeChange (x, y, z) { if (this._initialized) { this._changeQueue.push(Commands.GL_UNIFORMS); this._changeQueue.push('u_size'); this._changeQueue.push([x, y, z]); } this._requestUpdate(); };
Receives size change updates from the scene graph. @method @private @param {Number} x width of the Node the Mesh is attached to @param {Number} y height of the Node the Mesh is attached to @param {Number} z depth of the Node the Mesh is attached to @return {undefined} undefined
onSizeChange ( x , y , z )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.onOpacityChange = function onOpacityChange (opacity) { if (this._initialized) { this._changeQueue.push(Commands.GL_UNIFORMS); this._changeQueue.push('u_opacity'); this._changeQueue.push(opacity); } this._requestUpdate(); };
Receives opacity change updates from the scene graph. @method @private @param {Number} opacity Opacity @return {undefined} undefined
onOpacityChange ( opacity )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.onAddUIEvent = function onAddUIEvent (UIEvent) { //TODO };
Adds functionality for UI events (TODO) @method @param {String} UIEvent UI Event @return {undefined} undefined
onAddUIEvent ( UIEvent )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype._requestUpdate = function _requestUpdate () { if (!this._requestingUpdate && this._node) { this._node.requestUpdate(this._id); this._requestingUpdate = true; } };
Queues instance to be updated. @method @return {undefined} undefined
_requestUpdate ( )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.init = function init () { this._initialized = true; this.onTransformChange(TransformSystem.get(this._node.getLocation())); var size = this._node.getSize(); this.onSizeChange(size[0], size[1], size[2]); this.onOpacityChange(this._node.getOpacity()); this._requestUpdate(); };
Initializes the mesh with appropriate listeners. @method @return {undefined} undefined
init ( )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.draw = function draw () { this._inDraw = true; this.init(); var value = this.getValue(); if (value.geometry != null) this.setGeometry(value.geometry); if (value.color != null) this.setBaseColor(value.color); if (value.glossiness != null) this.setGlossiness.apply(this, value.glossiness); if (value.drawOptions != null) this.setDrawOptions(value.drawOptions); if (value.flatShading != null) this.setFlatShading(value.flatShading); if (value.expressions.normals != null) this.setNormals(value.expressions.normals); if (value.expressions.baseColor != null) this.setBaseColor(value.expressions.baseColor); if (value.expressions.glossiness != null) this.setGlossiness(value.expressions.glossiness); if (value.expressions.positionOffset != null) this.setPositionOffset(value.expressions.positionOffset); this._inDraw = false; };
Draws given Mesh's current state. @method @return {undefined} undefined
draw ( )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
Mesh.prototype.setPositionOffset = function positionOffset(materialExpression) { var uniformValue; var isMaterial = materialExpression.__isAMaterial__; if (isMaterial) { addMeshToMaterial(this, materialExpression, 'positionOffset'); this.value.expressions.positionOffset = materialExpression; uniformValue = materialExpression; } else { this.value.expressions.positionOffset = null; this.value.positionOffset = materialExpression; uniformValue = this.value.positionOffset; } if (this._initialized) { this._changeQueue.push(materialExpression.__isAMaterial__ ? Commands.MATERIAL_INPUT : Commands.GL_UNIFORMS); this._changeQueue.push('u_positionOffset'); this._changeQueue.push(uniformValue); } this._requestUpdate(); return this; }; /** * Returns position offset. * * @method * * @returns {MaterialExpress|Number} MaterialExpress or Number */ Mesh.prototype.getPositionOffset = function getPositionOffset () { return this.value.expressions.positionOffset || this.value.positionOffset; }; /** * Get the mesh's expressions * * @method * * @returns {Object} Object */ Mesh.prototype.getMaterialExpressions = function getMaterialExpressions () { return this.value.expressions; }; /** * Get the mesh's value * * @method * * @returns {Number} Value */ Mesh.prototype.getValue = function getValue () { return this.value; }; /** * Queues the invalidations for Mesh * * @param {String} expressionName Expression Name * * @return {Mesh} Mesh */ Mesh.prototype._pushInvalidations = function _pushInvalidations (expressionName) { var uniformKey; var expression = this.value.expressions[expressionName]; var sender = this._node; if (expression) { expression.traverse(function (node) { var i = node.invalidations.length; while (i--) { uniformKey = node.invalidations.pop(); sender.sendDrawCommand(Commands.GL_UNIFORMS); sender.sendDrawCommand(uniformKey); sender.sendDrawCommand(node.uniforms[uniformKey]); } }); } return this; }; /** * Sends draw commands to the renderer * * @private * @method * * @return {undefined} undefined */ Mesh.prototype.onUpdate = function onUpdate() { var node = this._node; var queue = this._changeQueue; if (node && node.isMounted()) { node.sendDrawCommand(Commands.WITH); node.sendDrawCommand(node.getLocation()); // If any invalidations exist, push them into the queue if (this.value.color && this.value.color.isActive()) { this._node.sendDrawCommand(Commands.GL_UNIFORMS); this._node.sendDrawCommand('u_baseColor'); this._node.sendDrawCommand(this.value.color.getNormalizedRGBA()); this._node.requestUpdateOnNextTick(this._id); } if (this.value.glossiness && this.value.glossiness[0] && this.value.glossiness[0].isActive()) { this._node.sendDrawCommand(Commands.GL_UNIFORMS); this._node.sendDrawCommand('u_glossiness'); var glossiness = this.value.glossiness[0].getNormalizedRGB(); glossiness.push(this.value.glossiness[1]); this._node.sendDrawCommand(glossiness); this._node.requestUpdateOnNextTick(this._id); } else { this._requestingUpdate = false; } // If any invalidations exist, push them into the queue this._pushInvalidations('baseColor'); this._pushInvalidations('positionOffset'); this._pushInvalidations('normals'); this._pushInvalidations('glossiness'); for (var i = 0; i < queue.length; i++) { node.sendDrawCommand(queue[i]); } queue.length = 0; } }; /** * Save reference to node, set its ID and call draw on Mesh. * * @method * * @param {Node} node Node * @param {Number} id Identifier for Mesh * * @return {undefined} undefined */ Mesh.prototype.onMount = function onMount (node, id) { this._node = node; this._id = id; TransformSystem.makeCalculateWorldMatrixAt(node.getLocation()); this.draw(); }; /** * Queues the command for dismounting Mesh * * @method * * @return {undefined} undefined */ Mesh.prototype.onDismount = function onDismount () { this._initialized = false; this._inDraw = false; this._node.sendDrawCommand(Commands.WITH); this._node.sendDrawCommand(this._node.getLocation()); this._node.sendDrawCommand(Commands.GL_REMOVE_MESH); this._node = null; this._id = null; }; /** * Makes Mesh visible * * @method * * @return {undefined} undefined */ Mesh.prototype.onShow = function onShow () { this._changeQueue.push(Commands.GL_MESH_VISIBILITY, true); this._requestUpdate(); }; /** * Makes Mesh hidden * * @method * * @return {undefined} undefined */ Mesh.prototype.onHide = function onHide () { this._changeQueue.push(Commands.GL_MESH_VISIBILITY, false); this._requestUpdate(); }; /** * Receives transform change updates from the scene graph. * * @method * @private * * @param {Array} transform Transform matric * * @return {undefined} undefined */ Mesh.prototype.onTransformChange = function onTransformChange (transform) { if (this._initialized) { this._changeQueue.push(Commands.GL_UNIFORMS); this._changeQueue.push('u_transform'); this._changeQueue.push(transform.getWorldTransform()); } this._requestUpdate(); }; /** * Receives size change updates from the scene graph. * * @method * @private * * @param {Number} x width of the Node the Mesh is attached to * @param {Number} y height of the Node the Mesh is attached to * @param {Number} z depth of the Node the Mesh is attached to * * @return {undefined} undefined */ Mesh.prototype.onSizeChange = function onSizeChange (x, y, z) { if (this._initialized) { this._changeQueue.push(Commands.GL_UNIFORMS); this._changeQueue.push('u_size'); this._changeQueue.push([x, y, z]); } this._requestUpdate(); }; /** * Receives opacity change updates from the scene graph. * * @method * @private * * @param {Number} opacity Opacity * * @return {undefined} undefined */ Mesh.prototype.onOpacityChange = function onOpacityChange (opacity) { if (this._initialized) { this._changeQueue.push(Commands.GL_UNIFORMS); this._changeQueue.push('u_opacity'); this._changeQueue.push(opacity); } this._requestUpdate(); }; /** * Adds functionality for UI events (TODO) * * @method * * @param {String} UIEvent UI Event * * @return {undefined} undefined */ Mesh.prototype.onAddUIEvent = function onAddUIEvent (UIEvent) { //TODO }; /** * Queues instance to be updated. * * @method * * @return {undefined} undefined */ Mesh.prototype._requestUpdate = function _requestUpdate () { if (!this._requestingUpdate && this._node) { this._node.requestUpdate(this._id); this._requestingUpdate = true; } }; /** * Initializes the mesh with appropriate listeners. * * @method * * @return {undefined} undefined */ Mesh.prototype.init = function init () { this._initialized = true; this.onTransformChange(TransformSystem.get(this._node.getLocation())); var size = this._node.getSize(); this.onSizeChange(size[0], size[1], size[2]); this.onOpacityChange(this._node.getOpacity()); this._requestUpdate(); }; /** * Draws given Mesh's current state. * * @method * * @return {undefined} undefined */ Mesh.prototype.draw = function draw () { this._inDraw = true; this.init(); var value = this.getValue(); if (value.geometry != null) this.setGeometry(value.geometry); if (value.color != null) this.setBaseColor(value.color); if (value.glossiness != null) this.setGlossiness.apply(this, value.glossiness); if (value.drawOptions != null) this.setDrawOptions(value.drawOptions); if (value.flatShading != null) this.setFlatShading(value.flatShading); if (value.expressions.normals != null) this.setNormals(value.expressions.normals); if (value.expressions.baseColor != null) this.setBaseColor(value.expressions.baseColor); if (value.expressions.glossiness != null) this.setGlossiness(value.expressions.glossiness); if (value.expressions.positionOffset != null) this.setPositionOffset(value.expressions.positionOffset); this._inDraw = false; }; function addMeshToMaterial(mesh, material, name) { var expressions = mesh.value.expressions; var previous = expressions[name]; var shouldRemove = true; var len = material.inputs; while(len--) addMeshToMaterial(mesh, material.inputs[len], name); len = INPUTS.length; while (len--) shouldRemove |= (name !== INPUTS[len] && previous !== expressions[INPUTS[len]]); if (shouldRemove) material.meshes.splice(material.meshes.indexOf(previous), 1); if (material.meshes.indexOf(mesh) === -1) material.meshes.push(mesh); } module.exports = Mesh;
Defines 3 element map which displaces the position of each vertex in world space. @method @param {MaterialExpression|Array} materialExpression Position offset expression @return {Mesh} Mesh
positionOffset ( materialExpression )
javascript
Famous/engine
webgl-renderables/Mesh.js
https://github.com/Famous/engine/blob/master/webgl-renderables/Mesh.js
MIT
function Light(node) { this._node = node; this._requestingUpdate = false; this._color = null; this.queue = []; this.commands = { color: Commands.GL_LIGHT_COLOR, position: Commands.GL_LIGHT_POSITION }; this._id = node.addComponent(this); }
The blueprint for all light components. @class Light @constructor @abstract @param {Node} node The controlling node from the corresponding Render Node @return {undefined} undefined
Light ( node )
javascript
Famous/engine
webgl-renderables/lights/Light.js
https://github.com/Famous/engine/blob/master/webgl-renderables/lights/Light.js
MIT
Light.prototype.setColor = function setColor(color) { if (!color.getNormalizedRGB) return false; if (!this._requestingUpdate) { this._node.requestUpdate(this._id); this._requestingUpdate = true; } this._color = color; this.queue.push(this.commands.color); var rgb = this._color.getNormalizedRGB(); this.queue.push(rgb[0]); this.queue.push(rgb[1]); this.queue.push(rgb[2]); return this; };
Changes the color of the light, using the 'Color' utility component. @method @param {Color} color Color instance @return {Light} Light
setColor ( color )
javascript
Famous/engine
webgl-renderables/lights/Light.js
https://github.com/Famous/engine/blob/master/webgl-renderables/lights/Light.js
MIT
function PointLight(node) { Light.call(this, node); }
PointLight extends the functionality of Light. PointLight is a light source that emits light in all directions from a point in space. @class PointLight @constructor @augments Light @param {Node} node LocalDispatch to be retrieved from the corresponding Render Node @return {undefined} undefined
PointLight ( node )
javascript
Famous/engine
webgl-renderables/lights/PointLight.js
https://github.com/Famous/engine/blob/master/webgl-renderables/lights/PointLight.js
MIT
PointLight.prototype.onMount = function onMount(node, id) { this._id = id; TransformSystem.makeBreakPointAt(this._node.getLocation()); this.onTransformChange(TransformSystem.get(this._node.getLocation())); };
Receive the notice that the node you are on has been mounted. @param {Node} node Node that the component has been associated with @param {Number} id ID associated with the node @return {undefined} undefined
onMount ( node , id )
javascript
Famous/engine
webgl-renderables/lights/PointLight.js
https://github.com/Famous/engine/blob/master/webgl-renderables/lights/PointLight.js
MIT
PointLight.prototype.onTransformChange = function onTransformChange (transform) { if (!this._requestingUpdate) { this._node.requestUpdate(this._id); this._requestingUpdate = true; } transform = transform.getWorldTransform(); this.queue.push(this.commands.position); this.queue.push(transform[12]); this.queue.push(transform[13]); this.queue.push(transform[14]); };
Receives transform change updates from the scene graph. @private @param {Array} transform Transform matrix @return {undefined} undefined
onTransformChange ( transform )
javascript
Famous/engine
webgl-renderables/lights/PointLight.js
https://github.com/Famous/engine/blob/master/webgl-renderables/lights/PointLight.js
MIT
function AmbientLight(node) { Light.call(this, node); this.commands.color = Commands.GL_AMBIENT_LIGHT; }
AmbientLight extends the functionality of Light. It sets the ambience in the scene. Ambience is a light source that emits light in the entire scene, evenly. @class AmbientLight @constructor @augments Light @param {Node} node LocalDispatch to be retrieved from the corresponding Render Node @return {undefined} undefined
AmbientLight ( node )
javascript
Famous/engine
webgl-renderables/lights/AmbientLight.js
https://github.com/Famous/engine/blob/master/webgl-renderables/lights/AmbientLight.js
MIT
function Transitionable(initialState) { this._queue = []; this._from = null; this._state = null; this._startedAt = null; this._pausedAt = null; if (initialState != null) this.from(initialState); }
A state maintainer for a smooth transition between numerically-specified states. Example numeric states include floats and arrays of floats objects. An initial state is set with the constructor or using {@link Transitionable#from}. Subsequent transitions consist of an intermediate state, easing curve, duration and callback. The final state of each transition is the initial state of the subsequent one. Calls to {@link Transitionable#get} provide the interpolated state along the way. Note that there is no event loop here - calls to {@link Transitionable#get} are the only way to find state projected to the current (or provided) time and are the only way to trigger callbacks and mutate the internal transition queue. @example var t = new Transitionable([0, 0]); t .to([100, 0], 'linear', 1000) .delay(1000) .to([200, 0], 'outBounce', 1000); var div = document.createElement('div'); div.style.background = 'blue'; div.style.width = '100px'; div.style.height = '100px'; document.body.appendChild(div); div.addEventListener('click', function() { t.isPaused() ? t.resume() : t.pause(); }); requestAnimationFrame(function loop() { div.style.transform = 'translateX(' + t.get()[0] + 'px)' + ' translateY(' + t.get()[1] + 'px)'; requestAnimationFrame(loop); }); @class Transitionable @constructor @param {Number|Array.Number} initialState initial state to transition from - equivalent to a pursuant invocation of {@link Transitionable#from}
Transitionable ( initialState )
javascript
Famous/engine
transitions/Transitionable.js
https://github.com/Famous/engine/blob/master/transitions/Transitionable.js
MIT
Transitionable.prototype.from = function from(initialState) { this._state = initialState; this._from = this._sync(null, this._state); this._queue.length = 0; this._startedAt = this.constructor.Clock.now(); this._pausedAt = null; return this; };
Resets the transition queue to a stable initial state. @method from @chainable @param {Number|Array.Number} initialState initial state to transition from @return {Transitionable} this
from ( initialState )
javascript
Famous/engine
transitions/Transitionable.js
https://github.com/Famous/engine/blob/master/transitions/Transitionable.js
MIT
Transitionable.prototype.delay = function delay(duration, callback) { var endState = this._queue.length > 0 ? this._queue[this._queue.length - 5] : this._state; return this.to(endState, Curves.flat, duration, callback); };
Delays the execution of the subsequent transition for a certain period of time. @method delay @chainable @param {Number} duration delay time in ms @param {Function} [callback] Zero-argument function to call on observed completion (t=1) @return {Transitionable} this
delay ( duration , callback )
javascript
Famous/engine
transitions/Transitionable.js
https://github.com/Famous/engine/blob/master/transitions/Transitionable.js
MIT
Transitionable.prototype.override = function override(finalState, curve, duration, callback, method) { if (this._queue.length > 0) { if (finalState != null) this._queue[0] = finalState; if (curve != null) this._queue[1] = curve.constructor === String ? Curves[curve] : curve; if (duration != null) this._queue[2] = duration; if (callback != null) this._queue[3] = callback; if (method != null) this._queue[4] = method; } return this; };
Overrides current transition. @method override @chainable @param {Number|Array.Number} [finalState] final state to transiton to @param {String|Function} [curve] easing function used for interpolating [0, 1] @param {Number} [duration] duration of transition @param {Function} [callback] callback function to be called after the transition is complete @param {String} [method] optional method used for interpolating between the values. Set to `slerp` for spherical linear interpolation. @return {Transitionable} this
override ( finalState , curve , duration , callback , method )
javascript
Famous/engine
transitions/Transitionable.js
https://github.com/Famous/engine/blob/master/transitions/Transitionable.js
MIT
Transitionable.prototype._interpolate = function _interpolate(output, from, to, progress, method) { if (to instanceof Object) { if (method === 'slerp') { var x, y, z, w; var qx, qy, qz, qw; var omega, cosomega, sinomega, scaleFrom, scaleTo; x = from[0]; y = from[1]; z = from[2]; w = from[3]; qx = to[0]; qy = to[1]; qz = to[2]; qw = to[3]; if (progress === 1) { output[0] = qx; output[1] = qy; output[2] = qz; output[3] = qw; return output; } cosomega = w * qw + x * qx + y * qy + z * qz; if ((1.0 - cosomega) > 1e-5) { omega = Math.acos(cosomega); sinomega = Math.sin(omega); scaleFrom = Math.sin((1.0 - progress) * omega) / sinomega; scaleTo = Math.sin(progress * omega) / sinomega; } else { scaleFrom = 1.0 - progress; scaleTo = progress; } output[0] = x * scaleFrom + qx * scaleTo; output[1] = y * scaleFrom + qy * scaleTo; output[2] = z * scaleFrom + qz * scaleTo; output[3] = w * scaleFrom + qw * scaleTo; } else if (to instanceof Array) { for (var i = 0, len = to.length; i < len; i++) { output[i] = this._interpolate(output[i], from[i], to[i], progress, method); } } else { for (var key in to) { output[key] = this._interpolate(output[key], from[key], to[key], progress, method); } } } else { output = from + progress * (to - from); } return output; };
Used for interpolating between the start and end state of the currently running transition @method _interpolate @private @param {Object|Array|Number} output Where to write to (in order to avoid object allocation and therefore GC). @param {Object|Array|Number} from Start state of current transition. @param {Object|Array|Number} to End state of current transition. @param {Number} progress Progress of the current transition, in [0, 1] @param {String} method Method used for interpolation (e.g. slerp) @return {Object|Array|Number} output
_interpolate ( output , from , to , progress , method )
javascript
Famous/engine
transitions/Transitionable.js
https://github.com/Famous/engine/blob/master/transitions/Transitionable.js
MIT
Transitionable.prototype._sync = function _sync(output, input) { if (typeof input === 'number') output = input; else if (input instanceof Array) { if (output == null) output = []; for (var i = 0, len = input.length; i < len; i++) { output[i] = _sync(output[i], input[i]); } } else if (input instanceof Object) { if (output == null) output = {}; for (var key in input) { output[key] = _sync(output[key], input[key]); } } return output; };
Internal helper method used for synchronizing the current, absolute state of a transition to a given output array, object literal or number. Supports nested state objects by through recursion. @method _sync @private @param {Number|Array|Object} output Where to write to (in order to avoid object allocation and therefore GC). @param {Number|Array|Object} input Input state to proxy onto the output. @return {Number|Array|Object} output Passed in output object.
_sync ( output , input )
javascript
Famous/engine
transitions/Transitionable.js
https://github.com/Famous/engine/blob/master/transitions/Transitionable.js
MIT
Transitionable.prototype.isActive = function isActive() { return this._queue.length > 0; };
Is there at least one transition pending completion? @method isActive @return {Boolean} Boolean indicating whether there is at least one pending transition. Paused transitions are still being considered active.
isActive ( )
javascript
Famous/engine
transitions/Transitionable.js
https://github.com/Famous/engine/blob/master/transitions/Transitionable.js
MIT
Transitionable.prototype.halt = function halt() { return this.from(this.get()); };
Halt transition at current state and erase all pending actions. @method halt @chainable @return {Transitionable} this
halt ( )
javascript
Famous/engine
transitions/Transitionable.js
https://github.com/Famous/engine/blob/master/transitions/Transitionable.js
MIT
Transitionable.prototype.pause = function pause() { this._pausedAt = this.constructor.Clock.now(); return this; };
Pause transition. This will not erase any actions. @method pause @chainable @return {Transitionable} this
pause ( )
javascript
Famous/engine
transitions/Transitionable.js
https://github.com/Famous/engine/blob/master/transitions/Transitionable.js
MIT
Transitionable.prototype.isPaused = function isPaused() { return !!this._pausedAt; };
Has the current action been paused? @method isPaused @chainable @return {Boolean} if the current action has been paused
isPaused ( )
javascript
Famous/engine
transitions/Transitionable.js
https://github.com/Famous/engine/blob/master/transitions/Transitionable.js
MIT
Transitionable.prototype.resume = function resume() { var diff = this._pausedAt - this._startedAt; this._startedAt = this.constructor.Clock.now() - diff; this._pausedAt = null; return this; };
Resume a previously paused transition. @method resume @chainable @return {Transitionable} this
resume ( )
javascript
Famous/engine
transitions/Transitionable.js
https://github.com/Famous/engine/blob/master/transitions/Transitionable.js
MIT
Transitionable.prototype.reset = function(start) { return this.from(start); };
Cancel all transitions and reset to a stable state @method reset @chainable @deprecated Use `.from` instead! @param {Number|Array.Number|Object.<number, number>} start stable state to set to @return {Transitionable} this
Transitionable.prototype.reset ( start )
javascript
Famous/engine
transitions/Transitionable.js
https://github.com/Famous/engine/blob/master/transitions/Transitionable.js
MIT
Transitionable.prototype.set = function(state, transition, callback) { if (transition == null) { this.from(state); if (callback) callback(); } else { this.to(state, transition.curve, transition.duration, callback, transition.method); } return this; };
Add transition to end state to the queue of pending transitions. Special Use: calling without a transition resets the object to that state with no pending actions @method set @chainable @deprecated Use `.to` instead! @param {Number|FamousEngineMatrix|Array.Number|Object.<number, number>} state end state to which we interpolate @param {transition=} transition object of type {duration: number, curve: f[0,1] -> [0,1] or name}. If transition is omitted, change will be instantaneous. @param {function()=} callback Zero-argument function to call on observed completion (t=1) @return {Transitionable} this
Transitionable.prototype.set ( state , transition , callback )
javascript
Famous/engine
transitions/Transitionable.js
https://github.com/Famous/engine/blob/master/transitions/Transitionable.js
MIT
Transitionable.prototype.get = function get(t) { if (this._queue.length === 0) return this._state; t = this._pausedAt ? this._pausedAt : t; t = t ? t : this.constructor.Clock.now(); var progress = (t - this._startedAt) / this._queue[2]; this._state = this._interpolate( this._state, this._from, this._queue[0], this._queue[1](progress > 1 ? 1 : progress), this._queue[4] ); var state = this._state; if (progress >= 1) { this._startedAt = this._startedAt + this._queue[2]; this._from = this._sync(this._from, this._state); this._queue.shift(); this._queue.shift(); this._queue.shift(); var callback = this._queue.shift(); this._queue.shift(); if (callback) callback(); } return progress > 1 ? this.get() : state; }; /** * Is there at least one transition pending completion? * * @method isActive * * @return {Boolean} Boolean indicating whether there is at least one pending * transition. Paused transitions are still being * considered active. */ Transitionable.prototype.isActive = function isActive() { return this._queue.length > 0; }; /** * Halt transition at current state and erase all pending actions. * * @method halt * @chainable * * @return {Transitionable} this */ Transitionable.prototype.halt = function halt() { return this.from(this.get()); }; /** * Pause transition. This will not erase any actions. * * @method pause * @chainable * * @return {Transitionable} this */ Transitionable.prototype.pause = function pause() { this._pausedAt = this.constructor.Clock.now(); return this; }; /** * Has the current action been paused? * * @method isPaused * @chainable * * @return {Boolean} if the current action has been paused */ Transitionable.prototype.isPaused = function isPaused() { return !!this._pausedAt; }; /** * Resume a previously paused transition. * * @method resume * @chainable * * @return {Transitionable} this */ Transitionable.prototype.resume = function resume() { var diff = this._pausedAt - this._startedAt; this._startedAt = this.constructor.Clock.now() - diff; this._pausedAt = null; return this; }; /** * Cancel all transitions and reset to a stable state * * @method reset * @chainable * @deprecated Use `.from` instead! * * @param {Number|Array.Number|Object.<number, number>} start * stable state to set to * @return {Transitionable} this */ Transitionable.prototype.reset = function(start) { return this.from(start); }; /** * Add transition to end state to the queue of pending transitions. Special * Use: calling without a transition resets the object to that state with * no pending actions * * @method set * @chainable * @deprecated Use `.to` instead! * * @param {Number|FamousEngineMatrix|Array.Number|Object.<number, number>} state * end state to which we interpolate * @param {transition=} transition object of type {duration: number, curve: * f[0,1] -> [0,1] or name}. If transition is omitted, change will be * instantaneous. * @param {function()=} callback Zero-argument function to call on observed * completion (t=1) * @return {Transitionable} this */ Transitionable.prototype.set = function(state, transition, callback) { if (transition == null) { this.from(state); if (callback) callback(); } else { this.to(state, transition.curve, transition.duration, callback, transition.method); } return this; }; module.exports = Transitionable;
Get interpolated state of current action at provided time. If the last action has completed, invoke its callback. @method get @param {Number=} t Evaluate the curve at a normalized version of this time. If omitted, use current time (Unix epoch time retrieved from Clock). @return {Number|Array.Number} Beginning state interpolated to this point in time.
get ( t )
javascript
Famous/engine
transitions/Transitionable.js
https://github.com/Famous/engine/blob/master/transitions/Transitionable.js
MIT
function PhysicsEngine(options) { this.events = new CallbackStore(); options = options || {}; /** @prop bodies The bodies currently active in the engine. */ this.bodies = []; /** @prop forces The forces currently active in the engine. */ this.forces = []; /** @prop constraints The constraints currently active in the engine. */ this.constraints = []; /** @prop step The time between frames in the engine. */ this.step = options.step || 1000/60; /** @prop iterations The number of times each constraint is solved per frame. */ this.iterations = options.iterations || 10; /** @prop _indexPool Pools of indicies to track holes in the arrays. */ this._indexPools = { bodies: [], forces: [], constraints: [] }; this._entityMaps = { bodies: {}, forces: {}, constraints: {} }; this.speed = options.speed || 1.0; this.time = 0; this.delta = 0; this.origin = options.origin || new Vec3(); this.orientation = options.orientation ? options.orientation.normalize() : new Quaternion(); this.frameDependent = options.frameDependent || false; this.transformBuffers = { position: [0, 0, 0], rotation: [0, 0, 0, 1] }; }
Singleton PhysicsEngine object. Manages bodies, forces, constraints. @class PhysicsEngine @param {Object} options A hash of configurable options.
PhysicsEngine ( options )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
PhysicsEngine.prototype.on = function on(key, callback) { this.events.on(key, callback); return this; };
Listen for a specific event. @method @param {String} key Name of the event. @param {Function} callback Callback to register for the event. @return {PhysicsEngine} this
on ( key , callback )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
PhysicsEngine.prototype.off = function off(key, callback) { this.events.off(key, callback); return this; };
Stop listening for a specific event. @method @param {String} key Name of the event. @param {Function} callback Callback to deregister for the event. @return {PhysicsEngine} this
off ( key , callback )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
PhysicsEngine.prototype.trigger = function trigger(key, payload) { this.events.trigger(key, payload); return this; };
Trigger an event. @method @param {String} key Name of the event. @param {Object} payload Payload to pass to the event listeners. @return {PhysicsEngine} this
trigger ( key , payload )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
PhysicsEngine.prototype.setOrigin = function setOrigin(x, y, z) { this.origin.set(x, y, z); return this; };
Set the origin of the world. @method @chainable @param {Number} x The x component. @param {Number} y The y component. @param {Number} z The z component. @return {PhysicsEngine} this
setOrigin ( x , y , z )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
PhysicsEngine.prototype.setOrientation = function setOrientation(w, x, y, z) { this.orientation.set(w, x, y, z).normalize(); return this; };
Set the orientation of the world. @method @chainable @param {Number} w The w component. @param {Number} x The x component. @param {Number} y The y component. @param {Number} z The z component. @return {PhysicsEngine} this
setOrientation ( w , x , y , z )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
function _addElement(context, element, key) { var map = context._entityMaps[key]; if (map[element._ID] == null) { var library = context[key]; var indexPool = context._indexPools[key]; if (indexPool.length) map[element._ID] = indexPool.pop(); else map[element._ID] = library.length; library[map[element._ID]] = element; } }
Private helper method to store an element in a library array. @method @private @param {Object} context Object in possesion of the element arrays. @param {Object} element The body, force, or constraint to add. @param {String} key Where to store the element. @return {undefined} undefined
_addElement ( context , element , key )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
function _removeElement(context, element, key) { var map = context._entityMaps[key]; var index = map[element._ID]; if (index != null) { context._indexPools[key].push(index); context[key][index] = null; map[element._ID] = null; } }
Private helper method to remove an element from a library array. @method @private @param {Object} context Object in possesion of the element arrays. @param {Object} element The body, force, or constraint to remove. @param {String} key Where to store the element. @return {undefined} undefined
_removeElement ( context , element , key )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
PhysicsEngine.prototype.add = function add() { for (var j = 0, lenj = arguments.length; j < lenj; j++) { var entity = arguments[j]; if (entity instanceof Array) { for (var i = 0, len = entity.length; i < len; i++) { var e = entity[i]; this.add(e); } } else { if (entity instanceof Particle) this.addBody(entity); else if (entity instanceof Constraint) this.addConstraint(entity); else if (entity instanceof Force) this.addForce(entity); } } return this; };
Add a group of bodies, force, or constraints to the engine. @method @return {PhysicsEngine} this
add ( )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
PhysicsEngine.prototype.remove = function remove() { for (var j = 0, lenj = arguments.length; j < lenj; j++) { var entity = arguments[j]; if (entity instanceof Array) { for (var i = 0, len = entity.length; i < len; i++) { var e = entity[i]; this.add(e); } } else { if (entity instanceof Particle) this.removeBody(entity); else if (entity instanceof Constraint) this.removeConstraint(entity); else if (entity instanceof Force) this.removeForce(entity); } } return this; };
Remove a group of bodies, force, or constraints from the engine. @method @return {PhysicsEngine} this
remove ( )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
PhysicsEngine.prototype.addBody = function addBody(body) { _addElement(this, body, 'bodies'); };
Begin tracking a body. @method @param {Particle} body The body to track. @return {undefined} undefined
addBody ( body )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
PhysicsEngine.prototype.addForce = function addForce(force) { _addElement(this, force, 'forces'); };
Begin tracking a force. @method @param {Force} force The force to track. @return {undefined} undefined
addForce ( force )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
PhysicsEngine.prototype.addConstraint = function addConstraint(constraint) { _addElement(this, constraint, 'constraints'); };
Begin tracking a constraint. @method @param {Constraint} constraint The constraint to track. @return {undefined} undefined
addConstraint ( constraint )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
PhysicsEngine.prototype.removeBody = function removeBody(body) { _removeElement(this, body, 'bodies'); };
Stop tracking a body. @method @param {Particle} body The body to stop tracking. @return {undefined} undefined
removeBody ( body )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
PhysicsEngine.prototype.removeForce = function removeForce(force) { _removeElement(this, force, 'forces'); };
Stop tracking a force. @method @param {Force} force The force to stop tracking. @return {undefined} undefined
removeForce ( force )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
PhysicsEngine.prototype.removeConstraint = function removeConstraint(constraint) { _removeElement(this, constraint, 'constraints'); };
Stop tracking a constraint. @method @param {Constraint} constraint The constraint to stop tracking. @return {undefined} undefined
removeConstraint ( constraint )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
PhysicsEngine.prototype.update = function update(time) { if (this.time === 0) this.time = time; var bodies = this.bodies; var forces = this.forces; var constraints = this.constraints; var frameDependent = this.frameDependent; var step = this.step; var dt = step * 0.001; var speed = this.speed; var delta = this.delta; delta += (time - this.time) * speed; this.time = time; var i, len; var force, body, constraint; while(delta > step) { this.events.trigger('prestep', time); // Update Forces on particles for (i = 0, len = forces.length; i < len; i++) { force = forces[i]; if (force === null) continue; force.update(time, dt); } // Tentatively update velocities for (i = 0, len = bodies.length; i < len; i++) { body = bodies[i]; if (body === null) continue; _integrateVelocity(body, dt); } // Prep constraints for solver for (i = 0, len = constraints.length; i < len; i++) { constraint = constraints[i]; if (constraint === null) continue; constraint.update(time, dt); } // Iteratively resolve constraints for (var j = 0, numIterations = this.iterations; j < numIterations; j++) { for (i = 0, len = constraints.length; i < len; i++) { constraint = constraints[i]; if (constraint === null) continue; constraint.resolve(time, dt); } } // Increment positions and orientations for (i = 0, len = bodies.length; i < len; i++) { body = bodies[i]; if (body === null) continue; _integratePose(body, dt); } this.events.trigger('poststep', time); if (frameDependent) delta = 0; else delta -= step; } this.delta = delta; };
Update the physics system to reflect the changes since the last frame. Steps forward in increments of PhysicsEngine.step. @method @param {Number} time The time to which to update. @return {undefined} undefined
update ( time )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
PhysicsEngine.prototype.getTransform = function getTransform(body) { var o = this.origin; var oq = this.orientation; var transform = this.transformBuffers; var p = body.position; var q = body.orientation; var rot = q; var loc = p; if (oq.w !== 1) { rot = Quaternion.multiply(q, oq, QUAT_REGISTER); loc = oq.rotateVector(p, VEC_REGISTER); } transform.position[0] = o.x+loc.x; transform.position[1] = o.y+loc.y; transform.position[2] = o.z+loc.z; transform.rotation[0] = rot.x; transform.rotation[1] = rot.y; transform.rotation[2] = rot.z; transform.rotation[3] = rot.w; return transform; };
Transform the body position and rotation to world coordinates. @method @param {Particle} body The body to retrieve the transform of. @return {Object} Position and rotation of the body, taking into account the origin and orientation of the world.
getTransform ( body )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
function _integrateVelocity(body, dt) { body.momentum.add(Vec3.scale(body.force, dt, DELTA_REGISTER)); body.angularMomentum.add(Vec3.scale(body.torque, dt, DELTA_REGISTER)); Vec3.scale(body.momentum, body.inverseMass, body.velocity); body.inverseInertia.vectorMultiply(body.angularMomentum, body.angularVelocity); body.force.clear(); body.torque.clear(); }
Update the Particle momenta based off of current incident force and torque. @method @private @param {Particle} body The body to update. @param {Number} dt Delta time. @return {undefined} undefined
_integrateVelocity ( body , dt )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
function _integratePose(body, dt) { if (body.restrictions !== 0) { var restrictions = body.restrictions; var x = null; var y = null; var z = null; var ax = null; var ay = null; var az = null; if (restrictions & 32) x = 0; if (restrictions & 16) y = 0; if (restrictions & 8) z = 0; if (restrictions & 4) ax = 0; if (restrictions & 2) ay = 0; if (restrictions & 1) az = 0; if (x !== null || y !== null || z !== null) body.setVelocity(x,y,z); if (ax !== null || ay !== null || az !== null) body.setAngularVelocity(ax, ay, az); } body.position.add(Vec3.scale(body.velocity, dt, DELTA_REGISTER)); var w = body.angularVelocity; var q = body.orientation; var wx = w.x; var wy = w.y; var wz = w.z; var qw = q.w; var qx = q.x; var qy = q.y; var qz = q.z; var hdt = dt * 0.5; q.w += (-wx * qx - wy * qy - wz * qz) * hdt; q.x += (wx * qw + wy * qz - wz * qy) * hdt; q.y += (wy * qw + wz * qx - wx * qz) * hdt; q.z += (wz * qw + wx * qy - wy * qx) * hdt; q.normalize(); body.updateInertia(); }
Update the Particle position and orientation based off current translational and angular velocities. @method @private @param {Particle} body The body to update. @param {Number} dt Delta time. @return {undefined} undefined
_integratePose ( body , dt )
javascript
Famous/engine
physics/PhysicsEngine.js
https://github.com/Famous/engine/blob/master/physics/PhysicsEngine.js
MIT
function tripleProduct(v1, v2, v3) { var v = TRIPLE_REGISTER; Vec3.cross(v1, v2, v); Vec3.cross(v, v3, v); return v; }
The so called triple product. Used to find a vector perpendicular to (v2 - v1) in the direction of v3. (v1 x v2) x v3. @method @private @param {Vec3} v1 The first Vec3. @param {Vec3} v2 The second Vec3. @param {Vec3} v3 The third Vec3. @return {Vec3} The result of the triple product.
tripleProduct ( v1 , v2 , v3 )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
function _hullSupport(vertices, direction) { var furthest; var max = -Infinity; var dot; var vertex; var index; for (var i = 0; i < vertices.length; i++) { vertex = vertices[i]; dot = Vec3.dot(vertex, direction); if (dot > max) { furthest = vertex; max = dot; index = i; } } return { vertex: furthest, index: index }; }
Of a set of vertices, retrieves the vertex furthest in the given direction. @method @private @param {Vec3[]} vertices The reference set of Vec3's. @param {Vec3} direction The direction to compare against. @return {Object} The vertex and its index in the vertex array.
_hullSupport ( vertices , direction )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
function DynamicGeometryFeature(distance, normal, vertexIndices) { this.distance = distance; this.normal = normal; this.vertexIndices = vertexIndices; }
Used internally to represent polyhedral facet information. @class DynamicGeometryFeature @param {Number} distance The distance of the feature from the origin. @param {Vec3} normal The Vec3 orthogonal to the feature, pointing out of the geometry. @param {Number[]} vertexIndices The indices of the vertices which compose the feature.
DynamicGeometryFeature ( distance , normal , vertexIndices )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
DynamicGeometryFeature.prototype.reset = function(distance, normal, vertexIndices) { this.distance = distance; this.normal = normal; this.vertexIndices = vertexIndices; return this; };
Used by ObjectManager to reset objects. @method @param {Number} distance Distance from the origin. @param {Vec3} normal Vec3 normal to the feature. @param {Number[]} vertexIndices Indices of the vertices which compose the feature. @return {DynamicGeometryFeature} this
DynamicGeometryFeature.prototype.reset ( distance , normal , vertexIndices )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
function DynamicGeometry() { this.vertices = []; this.numVertices = 0; this.features = []; this.numFeatures = 0; this.lastVertexIndex = 0; this._IDPool = { vertices: [], features: [] }; }
Abstract object representing a growing polyhedron. Used in ConvexHull and in GJK+EPA collision detection. @class DynamicGeometry
DynamicGeometry ( )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
DynamicGeometry.prototype.reset = function reset() { this.vertices = []; this.numVertices = 0; this.features = []; this.numFeatures = 0; this.lastVertexIndex = 0; this._IDPool = { vertices: [], features: [] }; return this; };
Used by ObjectManager to reset objects. @method @return {DynamicGeometry} this
reset ( )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
DynamicGeometry.prototype.addVertex = function(vertexObj) { var index = this._IDPool.vertices.length ? this._IDPool.vertices.pop() : this.vertices.length; this.vertices[index] = vertexObj; this.lastVertexIndex = index; this.numVertices++; };
Add a vertex to the polyhedron. @method @param {Object} vertexObj Object returned by the support function. @return {undefined} undefined
DynamicGeometry.prototype.addVertex ( vertexObj )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
DynamicGeometry.prototype.removeVertex = function(index) { var vertex = this.vertices[index]; this.vertices[index] = null; this._IDPool.vertices.push(index); this.numVertices--; return vertex; };
Remove a vertex and push its location in the vertex array to the IDPool for later use. @method @param {Number} index Index of the vertex to remove. @return {Object} vertex The vertex object.
DynamicGeometry.prototype.removeVertex ( index )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
DynamicGeometry.prototype.addFeature = function(distance, normal, vertexIndices) { var index = this._IDPool.features.length ? this._IDPool.features.pop() : this.features.length; this.features[index] = oMRequestDynamicGeometryFeature().reset(distance, normal, vertexIndices); this.numFeatures++; };
Add a feature (facet) to the polyhedron. Used internally in the reshaping process. @method @param {Number} distance The distance of the feature from the origin. @param {Vec3} normal The facet normal. @param {Number[]} vertexIndices The indices of the vertices which compose the feature. @return {undefined} undefined
DynamicGeometry.prototype.addFeature ( distance , normal , vertexIndices )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
DynamicGeometry.prototype.removeFeature = function(index) { var feature = this.features[index]; this.features[index] = null; this._IDPool.features.push(index); this.numFeatures--; oMFreeDynamicGeometryFeature(feature); };
Remove a feature and push its location in the feature array to the IDPool for later use. @method @param {Number} index Index of the feature to remove. @return {undefined} undefined
DynamicGeometry.prototype.removeFeature ( index )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
DynamicGeometry.prototype.getLastVertex = function() { return this.vertices[this.lastVertexIndex]; };
Retrieve the last vertex object added to the geometry. @method @return {Object} The last vertex added.
DynamicGeometry.prototype.getLastVertex ( )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
DynamicGeometry.prototype.getFeatureClosestToOrigin = function() { var min = Infinity; var closest = null; var features = this.features; for (var i = 0, len = features.length; i < len; i++) { var feature = features[i]; if (!feature) continue; if (feature.distance < min) { min = feature.distance; closest = feature; } } return closest; };
Return the feature closest to the origin. @method @return {DynamicGeometryFeature} The closest feature.
DynamicGeometry.prototype.getFeatureClosestToOrigin ( )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
function _validateEdge(vertices, frontier, start, end) { var e0 = vertices[start].vertex; var e1 = vertices[end].vertex; for (var i = 0, len = frontier.length; i < len; i++) { var edge = frontier[i]; if (!edge) continue; var v0 = vertices[edge[0]].vertex; var v1 = vertices[edge[1]].vertex; if ((e0 === v0 && (e1 === v1)) || (e0 === v1 && (e1 === v0))) { frontier[i] = null; return; } } frontier.push([start, end]); }
Adds edge if not already on the frontier, removes if the edge or its reverse are on the frontier. Used when reshaping DynamicGeometry's. @method @private @param {Object[]} vertices Vec3 reference array. @param {Array.<Number[]>} frontier Current edges potentially separating the features to remove from the persistant shape. @param {Number} start The index of the starting Vec3 on the edge. @param {Number} end The index of the culminating Vec3. @return {undefined} undefined
_validateEdge ( vertices , frontier , start , end )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
DynamicGeometry.prototype.reshape = function(referencePoint) { var vertices = this.vertices; var point = this.getLastVertex().vertex; var features = this.features; var vertexOnFeature; var featureVertices; var i, j, len; // The removal of features creates a hole in the polyhedron -- frontierEdges maintains the edges // of this hole, each of which will form one edge of a new feature to be created var frontierEdges = []; for (i = 0, len = features.length; i < len; i++) { if (!features[i]) continue; featureVertices = features[i].vertexIndices; vertexOnFeature = vertices[featureVertices[0]].vertex; // If point is 'above' the feature, remove that feature, and check to add its edges to the frontier. if (Vec3.dot(features[i].normal, Vec3.subtract(point, vertexOnFeature, POINTCHECK_REGISTER)) > -0.001) { _validateEdge(vertices, frontierEdges, featureVertices[0], featureVertices[1]); _validateEdge(vertices, frontierEdges, featureVertices[1], featureVertices[2]); _validateEdge(vertices, frontierEdges, featureVertices[2], featureVertices[0]); this.removeFeature(i); } } var A = point; var a = this.lastVertexIndex; for (j = 0, len = frontierEdges.length; j < len; j++) { if (!frontierEdges[j]) continue; var b = frontierEdges[j][0]; var c = frontierEdges[j][1]; var B = vertices[b].vertex; var C = vertices[c].vertex; var AB = Vec3.subtract(B, A, AB_REGISTER); var AC = Vec3.subtract(C, A, AC_REGISTER); var ABC = Vec3.cross(AB, AC, new Vec3()); ABC.normalize(); if (!referencePoint) { var distance = Vec3.dot(ABC, A); if (distance < 0) { ABC.invert(); distance *= -1; } this.addFeature(distance, ABC, [a, b, c]); } else { var reference = Vec3.subtract(referencePoint, A, VEC_REGISTER); if (Vec3.dot(ABC, reference) > -0.001) ABC.invert(); this.addFeature(null, ABC, [a, b, c]); } } };
Based on the last (exterior) point added to the polyhedron, removes features as necessary and redetermines its (convex) shape to include the new point by adding triangle features. Uses referencePoint, a point on the shape's interior, to ensure feature normals point outward, else takes referencePoint to be the origin. @method @param {Vec3} referencePoint Point known to be in the interior, used to orient feature normals. @return {undefined} undefined
DynamicGeometry.prototype.reshape ( referencePoint )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
DynamicGeometry.prototype.simplexContainsOrigin = function(direction, callback) { var numVertices = this.vertices.length; var a = this.lastVertexIndex; var b = a - 1; var c = a - 2; var d = a - 3; b = b < 0 ? b + numVertices : b; c = c < 0 ? c + numVertices : c; d = d < 0 ? d + numVertices : d; var A = this.vertices[a].vertex; var B = this.vertices[b].vertex; var C = this.vertices[c].vertex; var D = this.vertices[d].vertex; var AO = Vec3.scale(A, -1, AO_REGISTER); var AB = Vec3.subtract(B, A, AB_REGISTER); var AC, AD, BC, BD; var ABC, ACD, ABD, BCD; var distanceABC, distanceACD, distanceABD, distanceBCD; var vertexToRemove; if (numVertices === 4) { // Tetrahedron AC = Vec3.subtract(C, A, AC_REGISTER); AD = Vec3.subtract(D, A, AD_REGISTER); ABC = Vec3.cross(AB, AC, new Vec3()); ACD = Vec3.cross(AC, AD, new Vec3()); ABD = Vec3.cross(AB, AD, new Vec3()); ABC.normalize(); ACD.normalize(); ABD.normalize(); if (Vec3.dot(ABC, AD) > 0) ABC.invert(); if (Vec3.dot(ACD, AB) > 0) ACD.invert(); if (Vec3.dot(ABD, AC) > 0) ABD.invert(); // Don't need to check BCD because we would have just checked that in the previous iteration // -- we added A to the BCD triangle because A was in the direction of the origin. distanceABC = Vec3.dot(ABC, AO); distanceACD = Vec3.dot(ACD, AO); distanceABD = Vec3.dot(ABD, AO); // Norms point away from origin -> origin is inside tetrahedron if (distanceABC < 0.001 && distanceABD < 0.001 && distanceACD < 0.001) { BC = Vec3.subtract(C, B, BC_REGISTER); BD = Vec3.subtract(D, B, BD_REGISTER); BCD = Vec3.cross(BC, BD, new Vec3()); BCD.normalize(); if (Vec3.dot(BCD, AB) <= 0) BCD.invert(); distanceBCD = -1 * Vec3.dot(BCD,B); // Prep features for EPA this.addFeature(-distanceABC, ABC, [a,b,c]); this.addFeature(-distanceACD, ACD, [a,c,d]); this.addFeature(-distanceABD, ABD, [a,d,b]); this.addFeature(-distanceBCD, BCD, [b,c,d]); return true; } else if (distanceABC >= 0.001) { vertexToRemove = this.removeVertex(d); direction.copy(ABC); } else if (distanceACD >= 0.001) { vertexToRemove = this.removeVertex(b); direction.copy(ACD); } else { vertexToRemove = this.removeVertex(c); direction.copy(ABD); } } else if (numVertices === 3) { // Triangle AC = Vec3.subtract(C, A, AC_REGISTER); Vec3.cross(AB, AC, direction); if (Vec3.dot(direction, AO) <= 0) direction.invert(); } else { // Line direction.copy(tripleProduct(AB, AO, AB)); } if (vertexToRemove && callback) callback(vertexToRemove); return false; };
Checks if the Simplex instance contains the origin, returns true or false. If false, removes a point and, as a side effect, changes input direction to be both orthogonal to the current working simplex and point toward the origin. Calls callback on the removed point. @method @param {Vec3} direction Vector used to store the new search direction. @param {Function} callback Function invoked with the removed vertex, used e.g. to free the vertex object in the object manager. @return {Boolean} The result of the containment check.
DynamicGeometry.prototype.simplexContainsOrigin ( direction , callback )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
function ConvexHull(vertices, iterations) { iterations = iterations || 1e3; var hull = _computeConvexHull(vertices, iterations); var i, len; var indices = []; for (i = 0, len = hull.features.length; i < len; i++) { var f = hull.features[i]; if (f) indices.push(f.vertexIndices); } var polyhedralProperties = _computePolyhedralProperties(hull.vertices, indices); var centroid = polyhedralProperties.centroid; var worldVertices = []; for (i = 0, len = hull.vertices.length; i < len; i++) { worldVertices.push(Vec3.subtract(hull.vertices[i].vertex, centroid, new Vec3())); } var normals = []; for (i = 0, len = worldVertices.length; i < len; i++) { normals.push(Vec3.normalize(worldVertices[i], new Vec3())); } var graph = {}; var _neighborMatrix = {}; for (i = 0; i < indices.length; i++) { var a = indices[i][0]; var b = indices[i][1]; var c = indices[i][2]; _neighborMatrix[a] = _neighborMatrix[a] || {}; _neighborMatrix[b] = _neighborMatrix[b] || {}; _neighborMatrix[c] = _neighborMatrix[c] || {}; graph[a] = graph[a] || []; graph[b] = graph[b] || []; graph[c] = graph[c] || []; if (!_neighborMatrix[a][b]) { _neighborMatrix[a][b] = 1; graph[a].push(b); } if (!_neighborMatrix[a][c]) { _neighborMatrix[a][c] = 1; graph[a].push(c); } if (!_neighborMatrix[b][a]) { _neighborMatrix[b][a] = 1; graph[b].push(a); } if (!_neighborMatrix[b][c]) { _neighborMatrix[b][c] = 1; graph[b].push(c); } if (!_neighborMatrix[c][a]) { _neighborMatrix[c][a] = 1; graph[c].push(a); } if (!_neighborMatrix[c][b]) { _neighborMatrix[c][b] = 1; graph[c].push(b); } } this.indices = indices; this.vertices = worldVertices; this.normals = normals; this.polyhedralProperties = polyhedralProperties; this.graph = graph; }
Given an array of Vec3's, computes the convex hull. Used in constructing bodies in the physics system and to create custom GL meshes. @class ConvexHull @param {Vec3[]} vertices Cloud of vertices of which the enclosing convex hull is desired. @param {Number} iterations Maximum number of vertices to compose the convex hull.
ConvexHull ( vertices , iterations )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
function _computeConvexHull(vertices, maxIterations) { var hull = new DynamicGeometry(); hull.addVertex(_hullSupport(vertices, new Vec3(1, 0, 0))); hull.addVertex(_hullSupport(vertices, new Vec3(-1, 0, 0))); var A = hull.vertices[0].vertex; var B = hull.vertices[1].vertex; var AB = Vec3.subtract(B, A, AB_REGISTER); var dot; var vertex; var furthest; var index; var i, len; var max = -Infinity; for (i = 0; i < vertices.length; i++) { vertex = vertices[i]; if (vertex === A || vertex === B) continue; var AV = Vec3.subtract(vertex, A, VEC_REGISTER); dot = Vec3.dot(AV, tripleProduct(AB, AV, AB)); dot = dot < 0 ? dot * -1 : dot; if (dot > max) { max = dot; furthest = vertex; index = i; } } hull.addVertex({ vertex: furthest, index: index }); var C = furthest; var AC = Vec3.subtract(C, A, AC_REGISTER); var ABC = Vec3.cross(AB, AC, new Vec3()); ABC.normalize(); max = -Infinity; for (i = 0; i < vertices.length; i++) { vertex = vertices[i]; if (vertex === A || vertex === B || vertex === C) continue; dot = Vec3.dot(Vec3.subtract(vertex, A, VEC_REGISTER), ABC); dot = dot < 0 ? dot * -1 : dot; if (dot > max) { max = dot; furthest = vertex; index = i; } } hull.addVertex({ vertex: furthest, index: index }); var D = furthest; var AD = Vec3.subtract(D, A, AD_REGISTER); var BC = Vec3.subtract(C, B, BC_REGISTER); var BD = Vec3.subtract(D, B, BD_REGISTER); var ACD = Vec3.cross(AC, AD, new Vec3()); var ABD = Vec3.cross(AB, AD, new Vec3()); var BCD = Vec3.cross(BC, BD, new Vec3()); ACD.normalize(); ABD.normalize(); BCD.normalize(); if (Vec3.dot(ABC, AD) > 0) ABC.invert(); if (Vec3.dot(ACD, AB) > 0) ACD.invert(); if (Vec3.dot(ABD, AC) > 0) ABD.invert(); if (Vec3.dot(BCD, AB) < 0) BCD.invert(); var a = 0; var b = 1; var c = 2; var d = 3; hull.addFeature(null, ABC, [a, b, c]); hull.addFeature(null, ACD, [a, c, d]); hull.addFeature(null, ABD, [a, b, d]); hull.addFeature(null, BCD, [b, c, d]); var assigned = {}; for (i = 0, len = hull.vertices.length; i < len; i++) { assigned[hull.vertices[i].index] = true; } var cx = A.x + B.x + C.x + D.x; var cy = A.y + B.y + C.y + D.y; var cz = A.z + B.z + C.z + D.z; var referencePoint = new Vec3(cx, cy, cz); referencePoint.scale(0.25); var features = hull.features; var iteration = 0; while (iteration++ < maxIterations) { var currentFeature = null; for (i = 0, len = features.length; i < len; i++) { if (!features[i] || features[i].done) continue; currentFeature = features[i]; furthest = null; index = null; A = hull.vertices[currentFeature.vertexIndices[0]].vertex; var s = _hullSupport(vertices, currentFeature.normal); furthest = s.vertex; index = s.index; var dist = Vec3.dot(Vec3.subtract(furthest, A, VEC_REGISTER), currentFeature.normal); if (dist < 0.001 || assigned[index]) { currentFeature.done = true; continue; } assigned[index] = true; hull.addVertex(s); hull.reshape(referencePoint); } // No feature has points 'above' it -> finished if (currentFeature === null) break; } return hull; }
Performs the actual computation of the convex hull. @method @private @param {Vec3[]} vertices Cloud of vertices of which the enclosing convex hull is desired. @param {Number} maxIterations Maximum number of vertices to compose the convex hull. @return {DynamicGeometry} The computed hull.
_computeConvexHull ( vertices , maxIterations )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
function _subexpressions(w0, w1, w2, f, g) { var t0 = w0 + w1; f[0] = t0 + w2; var t1 = w0 * w0; var t2 = t1 + w1 * t0; f[1] = t2 + w2 * f[0]; f[2] = w0 * t1 + w1 * t2 + w2 * f[1]; g[0] = f[1] + w0 * (f[0] + w0); g[1] = f[1] + w1 * (f[0] + w1); g[2] = f[1] + w2 * (f[0] + w2); }
Helper function used in _computePolyhedralProperties. Sets f0 - f2 and g0 - g2 depending on w0 - w2. @method @private @param {Number} w0 Reference x coordinate. @param {Number} w1 Reference y coordinate. @param {Number} w2 Reference z coordinate. @param {Number[]} f One of two output registers to contain the result of the calculation. @param {Number[]} g One of two output registers to contain the result of the calculation. @return {undefined} undefined
_subexpressions ( w0 , w1 , w2 , f , g )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
function _computePolyhedralProperties(vertices, indices) { // Order: 1, x, y, z, x^2, y^2, z^2, xy, yz, zx var integrals = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; var fx = []; var fy = []; var fz = []; var gx = []; var gy = []; var gz = []; var i, len; for (i = 0, len = indices.length; i < len; i++) { var A = vertices[indices[i][0]].vertex; var B = vertices[indices[i][1]].vertex; var C = vertices[indices[i][2]].vertex; var AB = Vec3.subtract(B, A, AB_REGISTER); var AC = Vec3.subtract(C, A, AC_REGISTER); var ABC = AB.cross(AC); if (Vec3.dot(A, ABC) < 0) ABC.invert(); var d0 = ABC.x; var d1 = ABC.y; var d2 = ABC.z; var x0 = A.x; var y0 = A.y; var z0 = A.z; var x1 = B.x; var y1 = B.y; var z1 = B.z; var x2 = C.x; var y2 = C.y; var z2 = C.z; _subexpressions(x0, x1, x2, fx, gx); _subexpressions(y0, y1, y2, fy, gy); _subexpressions(z0, z1, z2, fz, gz); integrals[0] += d0 * fx[0]; integrals[1] += d0 * fx[1]; integrals[2] += d1 * fy[1]; integrals[3] += d2 * fz[1]; integrals[4] += d0 * fx[2]; integrals[5] += d1 * fy[2]; integrals[6] += d2 * fz[2]; integrals[7] += d0 * (y0 * gx[0] + y1 * gx[1] + y2 * gx[2]); integrals[8] += d1 * (z0 * gy[0] + z1 * gy[1] + z2 * gy[2]); integrals[9] += d2 * (x0 * gz[0] + x1 * gz[1] + x2 * gz[2]); } integrals[0] /= 6; integrals[1] /= 24; integrals[2] /= 24; integrals[3] /= 24; integrals[4] /= 60; integrals[5] /= 60; integrals[6] /= 60; integrals[7] /= 120; integrals[8] /= 120; integrals[9] /= 120; var minX = Infinity, maxX = -Infinity; var minY = Infinity, maxY = -Infinity; var minZ = Infinity, maxZ = -Infinity; for (i = 0, len = vertices.length; i < len; i++) { var vertex = vertices[i].vertex; if (vertex.x < minX) minX = vertex.x; if (vertex.x > maxX) maxX = vertex.x; if (vertex.y < minY) minY = vertex.y; if (vertex.y > maxY) maxY = vertex.y; if (vertex.z < minZ) minZ = vertex.z; if (vertex.z > maxZ) maxZ = vertex.z; } var size = [maxX - minX, maxY - minY, maxZ - minZ]; var volume = integrals[0]; var centroid = new Vec3(integrals[1], integrals[2], integrals[3]); centroid.scale(1 / volume); var eulerTensor = new Mat33([ integrals[4], integrals[7], integrals[9], integrals[7], integrals[5], integrals[8], integrals[9], integrals[8], integrals[6] ]); return { size: size, volume: volume, centroid: centroid, eulerTensor: eulerTensor }; }
Determines various properties of the volume. @method @private @param {Vec3[]} vertices The vertices of the polyhedron. @param {Array.<Number[]>} indices Array of arrays of indices of vertices composing the triangular features of the polyhedron, one array for each feature. @return {Object} Object holding the calculated span, volume, center, and euler tensor.
_computePolyhedralProperties ( vertices , indices )
javascript
Famous/engine
physics/Geometry.js
https://github.com/Famous/engine/blob/master/physics/Geometry.js
MIT
function Sphere(options) { Particle.call(this, options); var r = options.radius || 1; this.radius = r; this.size = [2*r, 2*r, 2*r]; this.updateLocalInertia(); this.inverseInertia.copy(this.localInverseInertia); var w = options.angularVelocity; if (w) this.setAngularVelocity(w.x, w.y, w.z); this.type = 1 << 2; }
Spherical Rigid body @class Sphere @extends Particle @param {Object} options The initial state of the body.
Sphere ( options )
javascript
Famous/engine
physics/bodies/Sphere.js
https://github.com/Famous/engine/blob/master/physics/bodies/Sphere.js
MIT
Sphere.prototype.getRadius = function getRadius() { return this.radius; };
Getter for radius. @method @return {Number} radius
getRadius ( )
javascript
Famous/engine
physics/bodies/Sphere.js
https://github.com/Famous/engine/blob/master/physics/bodies/Sphere.js
MIT
Sphere.prototype.setRadius = function setRadius(radius) { this.radius = radius; this.size = [2*this.radius, 2*this.radius, 2*this.radius]; return this; };
Setter for radius. @method @param {Number} radius The intended radius of the sphere. @return {Sphere} this
setRadius ( radius )
javascript
Famous/engine
physics/bodies/Sphere.js
https://github.com/Famous/engine/blob/master/physics/bodies/Sphere.js
MIT
Sphere.prototype.updateLocalInertia = function updateInertia() { var m = this.mass; var r = this.radius; var mrr = m * r * r; this.localInertia.set([ 0.4 * mrr, 0, 0, 0, 0.4 * mrr, 0, 0, 0, 0.4 * mrr ]); this.localInverseInertia.set([ 2.5 / mrr, 0, 0, 0, 2.5 / mrr, 0, 0, 0, 2.5 / mrr ]); };
Infers the inertia tensor. @override @method @return {undefined} undefined
updateInertia ( )
javascript
Famous/engine
physics/bodies/Sphere.js
https://github.com/Famous/engine/blob/master/physics/bodies/Sphere.js
MIT
Sphere.prototype.support = function support(direction) { return Vec3.scale(direction, this.radius, SUPPORT_REGISTER); };
Returns the point on the sphere furthest in a given direction. @method @param {Vec3} direction The direction in which to search. @return {Vec3} The support point.
support ( direction )
javascript
Famous/engine
physics/bodies/Sphere.js
https://github.com/Famous/engine/blob/master/physics/bodies/Sphere.js
MIT
function Wall(options) { Particle.call(this, options); var n = this.normal = new Vec3(); var d = this.direction = options.direction; switch (d) { case Wall.DOWN: n.set(0, 1, 0); break; case Wall.UP: n.set(0, -1, 0); break; case Wall.LEFT: n.set(-1, 0, 0); break; case Wall.RIGHT: n.set(1, 0, 0); break; case Wall.FORWARD: n.set(0, 0, -1); break; case Wall.BACKWARD: n.set(0, 0, 1); break; default: break; } this.invNormal = Vec3.clone(n, new Vec3()).invert(); this.mass = Infinity; this.inverseMass = 0; this.type = 1 << 3; }
An axis-aligned boundary. Will not respond to forces or impulses. @class Wall @extends Particle @param {Object} options The initial state of the body.
Wall ( options )
javascript
Famous/engine
physics/bodies/Wall.js
https://github.com/Famous/engine/blob/master/physics/bodies/Wall.js
MIT
function Particle(options) { this.events = new CallbackStore(); options = options || {}; this.position = options.position || new Vec3(); this.orientation = options.orientation || new Quaternion(); this.velocity = new Vec3(); this.momentum = new Vec3(); this.angularVelocity = new Vec3(); this.angularMomentum = new Vec3(); this.mass = options.mass || 1; this.inverseMass = 1 / this.mass; this.force = new Vec3(); this.torque = new Vec3(); this.restitution = options.restitution != null ? options.restitution : 0.4; this.friction = options.friction != null ? options.friction : 0.2; this.inverseInertia = new Mat33([0,0,0,0,0,0,0,0,0]); this.localInertia = new Mat33([0,0,0,0,0,0,0,0,0]); this.localInverseInertia = new Mat33([0,0,0,0,0,0,0,0,0]); this.size = options.size || [0, 0, 0]; var v = options.velocity; if (v) this.setVelocity(v.x, v.y, v.z); this.restrictions = 0; this.setRestrictions.apply(this, options.restrictions || []); this.collisionMask = options.collisionMask || 1; this.collisionGroup = options.collisionGroup || 1; this.type = 1 << 0; this._ID = _ID++; }
Fundamental physical body. Maintains translational and angular momentum, position and orientation, and other properties such as size and coefficients of restitution and friction used in collision response. @class Particle @param {Object} options Initial state of the body.
Particle ( options )
javascript
Famous/engine
physics/bodies/Particle.js
https://github.com/Famous/engine/blob/master/physics/bodies/Particle.js
MIT
Particle.prototype.on = function on(key, callback) { this.events.on(key, callback); return this; };
Listen for a specific event. @method @param {String} key Name of the event. @param {Function} callback Callback to register for the event. @return {Particle} this
on ( key , callback )
javascript
Famous/engine
physics/bodies/Particle.js
https://github.com/Famous/engine/blob/master/physics/bodies/Particle.js
MIT
Particle.prototype.off = function off(key, callback) { this.events.off(key, callback); return this; };
Stop listening for a specific event. @method @param {String} key Name of the event. @param {Function} callback Callback to deregister for the event. @return {Particle} this
off ( key , callback )
javascript
Famous/engine
physics/bodies/Particle.js
https://github.com/Famous/engine/blob/master/physics/bodies/Particle.js
MIT
Particle.prototype.trigger = function trigger(key, payload) { this.events.trigger(key, payload); return this; };
Trigger an event. @method @param {String} key Name of the event. @param {Object} payload Payload to pass to the event listeners. @return {Particle} this
trigger ( key , payload )
javascript
Famous/engine
physics/bodies/Particle.js
https://github.com/Famous/engine/blob/master/physics/bodies/Particle.js
MIT
Particle.prototype.getRestrictions = function getRestrictions() { var linear = ''; var angular = ''; var restrictions = this.restrictions; if (restrictions & 32) linear += 'x'; if (restrictions & 16) linear += 'y'; if (restrictions & 8) linear += 'z'; if (restrictions & 4) angular += 'x'; if (restrictions & 2) angular += 'y'; if (restrictions & 1) angular += 'z'; return [linear, angular]; };
Getter for the restriction bitmask. Converts the restrictions to their string representation. @method @return {String[]} restrictions
getRestrictions ( )
javascript
Famous/engine
physics/bodies/Particle.js
https://github.com/Famous/engine/blob/master/physics/bodies/Particle.js
MIT