From 21903b746cb3e9f02214bbc9028b341cd8063884 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Wed, 21 Oct 2015 10:06:51 -0700 Subject: [PATCH] CP --- examples/baseballEntityScript.js | 0 examples/libraries/walkApi.js | 1884 ++++++++++++------------ examples/map.js~ | 323 ++++ examples/pitching.js | 6 +- examples/toys/flashlight/flashlight.js | 536 +++---- examples/walk.js | 906 ++++++------ 6 files changed, 1990 insertions(+), 1665 deletions(-) create mode 100644 examples/baseballEntityScript.js create mode 100644 examples/map.js~ diff --git a/examples/baseballEntityScript.js b/examples/baseballEntityScript.js new file mode 100644 index 0000000000..e69de29bb2 diff --git a/examples/libraries/walkApi.js b/examples/libraries/walkApi.js index d1192deee7..7f5070f5d0 100644 --- a/examples/libraries/walkApi.js +++ b/examples/libraries/walkApi.js @@ -1,943 +1,943 @@ -// -// walkApi.js -// version 1.3 -// -// Created by David Wooldridge, June 2015 -// Copyright © 2014 - 2015 High Fidelity, Inc. -// -// Exposes API for use by walk.js version 1.2+. -// -// Editing tools for animation data files available here: https://github.com/DaveDubUK/walkTools -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -// included here to ensure walkApi.js can be used as an API, separate from walk.js -Script.include("./libraries/walkConstants.js"); - -Avatar = function() { - // if Hydras are connected, the only way to enable use is to never set any arm joint rotation - this.hydraCheck = function() { - // function courtesy of Thijs Wenker (frisbee.js) - var numberOfButtons = Controller.getNumberOfButtons(); - var numberOfTriggers = Controller.getNumberOfTriggers(); - var numberOfSpatialControls = Controller.getNumberOfSpatialControls(); - const HYDRA_BUTTONS = 12; - const HYDRA_TRIGGERS = 2; - const HYDRA_CONTROLLERS_PER_TRIGGER = 2; - var controllersPerTrigger = numberOfSpatialControls / numberOfTriggers; - if (numberOfButtons == HYDRA_BUTTONS && - numberOfTriggers == HYDRA_TRIGGERS && - controllersPerTrigger == HYDRA_CONTROLLERS_PER_TRIGGER) { - print('walk.js info: Razer Hydra detected. Setting arms free (not controlled by script)'); - return true; - } else { - print('walk.js info: Razer Hydra not detected. Arms will be controlled by script.'); - return false; - } - } - // settings - this.headFree = true; - this.armsFree = this.hydraCheck(); // automatically sets true to enable Hydra support - temporary fix - this.makesFootStepSounds = false; - this.blenderPreRotations = false; // temporary fix - this.animationSet = undefined; // currently just one animation set - this.setAnimationSet = function(animationSet) { - this.animationSet = animationSet; - switch (animationSet) { - case 'standardMale': - this.selectedIdle = walkAssets.getAnimationDataFile("MaleIdle"); - this.selectedWalk = walkAssets.getAnimationDataFile("MaleWalk"); - this.selectedWalkBackwards = walkAssets.getAnimationDataFile("MaleWalkBackwards"); - this.selectedSideStepLeft = walkAssets.getAnimationDataFile("MaleSideStepLeft"); - this.selectedSideStepRight = walkAssets.getAnimationDataFile("MaleSideStepRight"); - this.selectedWalkBlend = walkAssets.getAnimationDataFile("WalkBlend"); - this.selectedHover = walkAssets.getAnimationDataFile("MaleHover"); - this.selectedFly = walkAssets.getAnimationDataFile("MaleFly"); - this.selectedFlyBackwards = walkAssets.getAnimationDataFile("MaleFlyBackwards"); - this.selectedFlyDown = walkAssets.getAnimationDataFile("MaleFlyDown"); - this.selectedFlyUp = walkAssets.getAnimationDataFile("MaleFlyUp"); - this.selectedFlyBlend = walkAssets.getAnimationDataFile("FlyBlend"); - this.currentAnimation = this.selectedIdle; - return; - } - } - this.setAnimationSet('standardMale'); - - // calibration - this.calibration = { - hipsToFeet: 1, - strideLength: this.selectedWalk.calibration.strideLength - } - this.distanceFromSurface = 0; - this.calibrate = function() { - // Triple check: measurements are taken three times to ensure accuracy - the first result is often too large - const MAX_ATTEMPTS = 3; - var attempts = MAX_ATTEMPTS; - var extraAttempts = 0; - do { - for (joint in walkAssets.animationReference.joints) { - var IKChain = walkAssets.animationReference.joints[joint].IKChain; - - // only need to zero right leg IK chain and hips - if (IKChain === "RightLeg" || joint === "Hips" ) { - MyAvatar.setJointRotation(joint, Quat.fromPitchYawRollDegrees(0, 0, 0)); - } - } - this.calibration.hipsToFeet = MyAvatar.getJointPosition("Hips").y - MyAvatar.getJointPosition("RightToeBase").y; - - // maybe measuring before Blender pre-rotations have been applied? - if (this.calibration.hipsToFeet < 0 && this.blenderPreRotations) { - this.calibration.hipsToFeet *= -1; - } - - if (this.calibration.hipsToFeet === 0 && extraAttempts < 100) { - attempts++; - extraAttempts++;// Interface can sometimes report zero for hips to feet. if so, we try again. - } - } while (attempts-- > 1) - - // just in case - if (this.calibration.hipsToFeet <= 0 || isNaN(this.calibration.hipsToFeet)) { - this.calibration.hipsToFeet = 1; - print('walk.js error: Unable to get a non-zero measurement for the avatar hips to feet measure. Hips to feet set to default value ('+ - this.calibration.hipsToFeet.toFixed(3)+'m). This will cause some foot sliding. If your avatar has only just appeared, it is recommended that you re-load the walk script.'); - } else { - print('walk.js info: Hips to feet calibrated to '+this.calibration.hipsToFeet.toFixed(3)+'m'); - } - } - - // pose the fingers - this.poseFingers = function() { - for (knuckle in walkAssets.animationReference.leftHand) { - if (walkAssets.animationReference.leftHand[knuckle].IKChain === "LeftHandThumb") { - MyAvatar.setJointRotation(knuckle, Quat.fromPitchYawRollDegrees(0, 0, -4)); - } else { - MyAvatar.setJointRotation(knuckle, Quat.fromPitchYawRollDegrees(16, 0, 5)); - } - } - for (knuckle in walkAssets.animationReference.rightHand) { - if (walkAssets.animationReference.rightHand[knuckle].IKChain === "RightHandThumb") { - MyAvatar.setJointRotation(knuckle, Quat.fromPitchYawRollDegrees(0, 0, 4)); - } else { - MyAvatar.setJointRotation(knuckle, Quat.fromPitchYawRollDegrees(16, 0, -5)); - } - } - }; - this.calibrate(); - this.poseFingers(); - - // footsteps - this.nextStep = RIGHT; // the first step is right, because the waveforms say so - this.leftAudioInjector = null; - this.rightAudioInjector = null; - this.makeFootStepSound = function() { - // correlate footstep volume with avatar speed. place the audio source at the feet, not the hips - const SPEED_THRESHOLD = 0.4; - const VOLUME_ATTENUATION = 0.8; - const MIN_VOLUME = 0.5; - var volume = Vec3.length(motion.velocity) > SPEED_THRESHOLD ? - VOLUME_ATTENUATION * Vec3.length(motion.velocity) / MAX_WALK_SPEED : MIN_VOLUME; - volume = volume > 1 ? 1 : volume; // occurs when landing at speed - can walk faster than max walking speed - var options = { - position: Vec3.sum(MyAvatar.position, {x:0, y: -this.calibration.hipsToFeet, z:0}), - volume: volume - }; - if (this.nextStep === RIGHT) { - if (this.rightAudioInjector === null) { - this.rightAudioInjector = Audio.playSound(walkAssets.footsteps[0], options); - } else { - this.rightAudioInjector.setOptions(options); - this.rightAudioInjector.restart(); - } - this.nextStep = LEFT; - } else if (this.nextStep === LEFT) { - if (this.leftAudioInjector === null) { - this.leftAudioInjector = Audio.playSound(walkAssets.footsteps[1], options); - } else { - this.leftAudioInjector.setOptions(options); - this.leftAudioInjector.restart(); - } - this.nextStep = RIGHT; - } - } -}; - -// constructor for the Motion object -Motion = function() { - this.isLive = true; - // locomotion status - this.state = STATIC; - this.nextState = STATIC; - this.isMoving = false; - this.isWalkingSpeed = false; - this.isFlyingSpeed = false; - this.isAccelerating = false; - this.isDecelerating = false; - this.isDeceleratingFast = false; - this.isComingToHalt = false; - this.directedAcceleration = 0; - - // used to make sure at least one step has been taken when transitioning from a walk cycle - this.elapsedFTDegrees = 0; - - // the current transition (any layered transitions are nested within this transition) - this.currentTransition = null; - - // orientation, locomotion and timing - this.velocity = {x:0, y:0, z:0}; - this.acceleration = {x:0, y:0, z:0}; - this.yaw = Quat.safeEulerAngles(MyAvatar.orientation).y; - this.yawDelta = 0; - this.yawDeltaAcceleration = 0; - this.direction = FORWARDS; - this.deltaTime = 0; - - // historical orientation, locomotion and timing - this.lastDirection = FORWARDS; - this.lastVelocity = {x:0, y:0, z:0}; - this.lastYaw = Quat.safeEulerAngles(MyAvatar.orientation).y; - this.lastYawDelta = 0; - this.lastYawDeltaAcceleration = 0; - - // Quat.safeEulerAngles(MyAvatar.orientation).y tends to repeat values between frames, so values are filtered - var YAW_SMOOTHING = 22; - this.yawFilter = filter.createAveragingFilter(YAW_SMOOTHING); - this.deltaTimeFilter = filter.createAveragingFilter(YAW_SMOOTHING); - this.yawDeltaAccelerationFilter = filter.createAveragingFilter(YAW_SMOOTHING); - - // assess locomotion state - this.assess = function(deltaTime) { - // calculate avatar frame speed, velocity and acceleration - this.deltaTime = deltaTime; - this.velocity = Vec3.multiplyQbyV(Quat.inverse(MyAvatar.orientation), MyAvatar.getVelocity()); - var lateralVelocity = Math.sqrt(Math.pow(this.velocity.x, 2) + Math.pow(this.velocity.z, 2)); - - // MyAvatar.getAcceleration() currently not working. bug report submitted: https://worklist.net/20527 - var acceleration = {x:0, y:0, z:0}; - this.acceleration.x = (this.velocity.x - this.lastVelocity.x) / deltaTime; - this.acceleration.y = (this.velocity.y - this.lastVelocity.y) / deltaTime; - this.acceleration.z = (this.velocity.z - this.lastVelocity.z) / deltaTime; - - // MyAvatar.getAngularVelocity and MyAvatar.getAngularAcceleration currently not working. bug report submitted - this.yaw = Quat.safeEulerAngles(MyAvatar.orientation).y; - if (this.lastYaw < 0 && this.yaw > 0 || this.lastYaw > 0 && this.yaw < 0) { - this.lastYaw *= -1; - } - var timeDelta = this.deltaTimeFilter.process(deltaTime); - this.yawDelta = filter.degToRad(this.yawFilter.process(this.lastYaw - this.yaw)) / timeDelta; - this.yawDeltaAcceleration = this.yawDeltaAccelerationFilter.process(this.lastYawDelta - this.yawDelta) / timeDelta; - - // how far above the surface is the avatar? (for testing / validation purposes) - var pickRay = {origin: MyAvatar.position, direction: {x:0, y:-1, z:0}}; - var distanceFromSurface = Entities.findRayIntersectionBlocking(pickRay).distance; - avatar.distanceFromSurface = distanceFromSurface - avatar.calibration.hipsToFeet; - - // determine principle direction of locomotion - var FWD_BACK_BIAS = 100; // helps prevent false sidestep condition detection when banking hard - if (Math.abs(this.velocity.x) > Math.abs(this.velocity.y) && - Math.abs(this.velocity.x) > FWD_BACK_BIAS * Math.abs(this.velocity.z)) { - if (this.velocity.x < 0) { - this.directedAcceleration = -this.acceleration.x; - this.direction = LEFT; - } else if (this.velocity.x > 0){ - this.directedAcceleration = this.acceleration.x; - this.direction = RIGHT; - } - } else if (Math.abs(this.velocity.y) > Math.abs(this.velocity.x) && - Math.abs(this.velocity.y) > Math.abs(this.velocity.z)) { - if (this.velocity.y > 0) { - this.directedAcceleration = this.acceleration.y; - this.direction = UP; - } else if (this.velocity.y < 0) { - this.directedAcceleration = -this.acceleration.y; - this.direction = DOWN; - } - } else if (FWD_BACK_BIAS * Math.abs(this.velocity.z) > Math.abs(this.velocity.x) && - Math.abs(this.velocity.z) > Math.abs(this.velocity.y)) { - if (this.velocity.z < 0) { - this.direction = FORWARDS; - this.directedAcceleration = -this.acceleration.z; - } else if (this.velocity.z > 0) { - this.directedAcceleration = this.acceleration.z; - this.direction = BACKWARDS; - } - } else { - this.direction = NONE; - this.directedAcceleration = 0; - } - - // set speed flags - if (Vec3.length(this.velocity) < MOVE_THRESHOLD) { - this.isMoving = false; - this.isWalkingSpeed = false; - this.isFlyingSpeed = false; - this.isComingToHalt = false; - } else if (Vec3.length(this.velocity) < MAX_WALK_SPEED) { - this.isMoving = true; - this.isWalkingSpeed = true; - this.isFlyingSpeed = false; - } else { - this.isMoving = true; - this.isWalkingSpeed = false; - this.isFlyingSpeed = true; - } - - // set acceleration flags - if (this.directedAcceleration > ACCELERATION_THRESHOLD) { - this.isAccelerating = true; - this.isDecelerating = false; - this.isDeceleratingFast = false; - this.isComingToHalt = false; - } else if (this.directedAcceleration < DECELERATION_THRESHOLD) { - this.isAccelerating = false; - this.isDecelerating = true; - this.isDeceleratingFast = (this.directedAcceleration < FAST_DECELERATION_THRESHOLD); - } else { - this.isAccelerating = false; - this.isDecelerating = false; - this.isDeceleratingFast = false; - } - - // use the gathered information to build up some spatial awareness - var isOnSurface = (avatar.distanceFromSurface < ON_SURFACE_THRESHOLD); - var isUnderGravity = (avatar.distanceFromSurface < GRAVITY_THRESHOLD); - var isTakingOff = (isUnderGravity && this.velocity.y > OVERCOME_GRAVITY_SPEED); - var isComingInToLand = (isUnderGravity && this.velocity.y < -OVERCOME_GRAVITY_SPEED); - var aboutToLand = isComingInToLand && avatar.distanceFromSurface < LANDING_THRESHOLD; - var surfaceMotion = isOnSurface && this.isMoving; - var acceleratingAndAirborne = this.isAccelerating && !isOnSurface; - var goingTooFastToWalk = !this.isDecelerating && this.isFlyingSpeed; - var movingDirectlyUpOrDown = (this.direction === UP || this.direction === DOWN) - var maybeBouncing = Math.abs(this.acceleration.y > BOUNCE_ACCELERATION_THRESHOLD) ? true : false; - - // we now have enough information to set the appropriate locomotion mode - switch (this.state) { - case STATIC: - var staticToAirMotion = this.isMoving && (acceleratingAndAirborne || goingTooFastToWalk || - (movingDirectlyUpOrDown && !isOnSurface)); - var staticToSurfaceMotion = surfaceMotion && !motion.isComingToHalt && !movingDirectlyUpOrDown && - !this.isDecelerating && lateralVelocity > MOVE_THRESHOLD; - - if (staticToAirMotion) { - this.nextState = AIR_MOTION; - } else if (staticToSurfaceMotion) { - this.nextState = SURFACE_MOTION; - } else { - this.nextState = STATIC; - } - break; - - case SURFACE_MOTION: - var surfaceMotionToStatic = !this.isMoving || - (this.isDecelerating && motion.lastDirection !== DOWN && surfaceMotion && - !maybeBouncing && Vec3.length(this.velocity) < MAX_WALK_SPEED); - var surfaceMotionToAirMotion = (acceleratingAndAirborne || goingTooFastToWalk || movingDirectlyUpOrDown) && - (!surfaceMotion && isTakingOff) || - (!surfaceMotion && this.isMoving && !isComingInToLand); - - if (surfaceMotionToStatic) { - // working on the assumption that stopping is now inevitable - if (!motion.isComingToHalt && isOnSurface) { - motion.isComingToHalt = true; - } - this.nextState = STATIC; - } else if (surfaceMotionToAirMotion) { - this.nextState = AIR_MOTION; - } else { - this.nextState = SURFACE_MOTION; - } - break; - - case AIR_MOTION: - var airMotionToSurfaceMotion = (surfaceMotion || aboutToLand) && !movingDirectlyUpOrDown; - var airMotionToStatic = !this.isMoving && this.direction === this.lastDirection; - - if (airMotionToSurfaceMotion){ - this.nextState = SURFACE_MOTION; - } else if (airMotionToStatic) { - this.nextState = STATIC; - } else { - this.nextState = AIR_MOTION; - } - break; - } - } - - // frequency time wheel (foot / ground speed matching) - const DEFAULT_HIPS_TO_FEET = 1; - this.frequencyTimeWheelPos = 0; - this.frequencyTimeWheelRadius = DEFAULT_HIPS_TO_FEET / 2; - this.recentFrequencyTimeIncrements = []; - const FT_WHEEL_HISTORY_LENGTH = 8; - for (var i = 0; i < FT_WHEEL_HISTORY_LENGTH; i++) { - this.recentFrequencyTimeIncrements.push(0); - } - this.averageFrequencyTimeIncrement = 0; - - this.advanceFrequencyTimeWheel = function(angle){ - this.elapsedFTDegrees += angle; - // keep a running average of increments for use in transitions (used during transitioning) - this.recentFrequencyTimeIncrements.push(angle); - this.recentFrequencyTimeIncrements.shift(); - for (increment in this.recentFrequencyTimeIncrements) { - this.averageFrequencyTimeIncrement += this.recentFrequencyTimeIncrements[increment]; - } - this.averageFrequencyTimeIncrement /= this.recentFrequencyTimeIncrements.length; - this.frequencyTimeWheelPos += angle; - const FULL_CIRCLE = 360; - if (this.frequencyTimeWheelPos >= FULL_CIRCLE) { - this.frequencyTimeWheelPos = this.frequencyTimeWheelPos % FULL_CIRCLE; - } - } - - this.saveHistory = function() { - this.lastDirection = this.direction; - this.lastVelocity = this.velocity; - this.lastYaw = this.yaw; - this.lastYawDelta = this.yawDelta; - this.lastYawDeltaAcceleration = this.yawDeltaAcceleration; - } -}; // end Motion constructor - -// animation manipulation object -animationOperations = (function() { - - return { - - // helper function for renderMotion(). calculate joint translations based on animation file settings and frequency * time - calculateTranslations: function(animation, ft, direction) { - var jointName = "Hips"; - var joint = animation.joints[jointName]; - var jointTranslations = {x:0, y:0, z:0}; - - // gather modifiers and multipliers - modifiers = new FrequencyMultipliers(joint, direction); - - // calculate translations. Use synthesis filters where specified by the animation data file. - - // sway (oscillation on the x-axis) - if (animation.filters.hasOwnProperty(jointName) && 'swayFilter' in animation.filters[jointName]) { - jointTranslations.x = joint.sway * animation.filters[jointName].swayFilter.calculate - (filter.degToRad(modifiers.swayFrequencyMultiplier * ft + joint.swayPhase)) + joint.swayOffset; - } else { - jointTranslations.x = joint.sway * Math.sin - (filter.degToRad(modifiers.swayFrequencyMultiplier * ft + joint.swayPhase)) + joint.swayOffset; - } - // bob (oscillation on the y-axis) - if (animation.filters.hasOwnProperty(jointName) && 'bobFilter' in animation.filters[jointName]) { - jointTranslations.y = joint.bob * animation.filters[jointName].bobFilter.calculate - (filter.degToRad(modifiers.bobFrequencyMultiplier * ft + joint.bobPhase)) + joint.bobOffset; - } else { - jointTranslations.y = joint.bob * Math.sin - (filter.degToRad(modifiers.bobFrequencyMultiplier * ft + joint.bobPhase)) + joint.bobOffset; - - if (animation.filters.hasOwnProperty(jointName) && 'bobLPFilter' in animation.filters[jointName]) { - jointTranslations.y = filter.clipTrough(jointTranslations.y, joint, 2); - jointTranslations.y = animation.filters[jointName].bobLPFilter.process(jointTranslations.y); - } - } - // thrust (oscillation on the z-axis) - if (animation.filters.hasOwnProperty(jointName) && 'thrustFilter' in animation.filters[jointName]) { - jointTranslations.z = joint.thrust * animation.filters[jointName].thrustFilter.calculate - (filter.degToRad(modifiers.thrustFrequencyMultiplier * ft + joint.thrustPhase)) + joint.thrustOffset; - } else { - jointTranslations.z = joint.thrust * Math.sin - (filter.degToRad(modifiers.thrustFrequencyMultiplier * ft + joint.thrustPhase)) + joint.thrustOffset; - } - return jointTranslations; - }, - - // helper function for renderMotion(). calculate joint rotations based on animation file settings and frequency * time - calculateRotations: function(jointName, animation, ft, direction) { - var joint = animation.joints[jointName]; - var jointRotations = {x:0, y:0, z:0}; - - if (avatar.blenderPreRotations) { - jointRotations = Vec3.sum(jointRotations, walkAssets.blenderPreRotations.joints[jointName]); - } - - // gather frequency multipliers for this joint - modifiers = new FrequencyMultipliers(joint, direction); - - // calculate rotations. Use synthesis filters where specified by the animation data file. - - // calculate pitch - if (animation.filters.hasOwnProperty(jointName) && - 'pitchFilter' in animation.filters[jointName]) { - jointRotations.x += joint.pitch * animation.filters[jointName].pitchFilter.calculate - (filter.degToRad(ft * modifiers.pitchFrequencyMultiplier + joint.pitchPhase)) + joint.pitchOffset; - } else { - jointRotations.x += joint.pitch * Math.sin - (filter.degToRad(ft * modifiers.pitchFrequencyMultiplier + joint.pitchPhase)) + joint.pitchOffset; - } - // calculate yaw - if (animation.filters.hasOwnProperty(jointName) && - 'yawFilter' in animation.filters[jointName]) { - jointRotations.y += joint.yaw * animation.filters[jointName].yawFilter.calculate - (filter.degToRad(ft * modifiers.yawFrequencyMultiplier + joint.yawPhase)) + joint.yawOffset; - } else { - jointRotations.y += joint.yaw * Math.sin - (filter.degToRad(ft * modifiers.yawFrequencyMultiplier + joint.yawPhase)) + joint.yawOffset; - } - // calculate roll - if (animation.filters.hasOwnProperty(jointName) && - 'rollFilter' in animation.filters[jointName]) { - jointRotations.z += joint.roll * animation.filters[jointName].rollFilter.calculate - (filter.degToRad(ft * modifiers.rollFrequencyMultiplier + joint.rollPhase)) + joint.rollOffset; - } else { - jointRotations.z += joint.roll * Math.sin - (filter.degToRad(ft * modifiers.rollFrequencyMultiplier + joint.rollPhase)) + joint.rollOffset; - } - return jointRotations; - }, - - zeroAnimation: function(animation) { - for (i in animation.joints) { - for (j in animation.joints[i]) { - animation.joints[i][j] = 0; - } - } - }, - - blendAnimation: function(sourceAnimation, targetAnimation, percent) { - for (i in targetAnimation.joints) { - targetAnimation.joints[i].pitch += percent * sourceAnimation.joints[i].pitch; - targetAnimation.joints[i].yaw += percent * sourceAnimation.joints[i].yaw; - targetAnimation.joints[i].roll += percent * sourceAnimation.joints[i].roll; - targetAnimation.joints[i].pitchPhase += percent * sourceAnimation.joints[i].pitchPhase; - targetAnimation.joints[i].yawPhase += percent * sourceAnimation.joints[i].yawPhase; - targetAnimation.joints[i].rollPhase += percent * sourceAnimation.joints[i].rollPhase; - targetAnimation.joints[i].pitchOffset += percent * sourceAnimation.joints[i].pitchOffset; - targetAnimation.joints[i].yawOffset += percent * sourceAnimation.joints[i].yawOffset; - targetAnimation.joints[i].rollOffset += percent * sourceAnimation.joints[i].rollOffset; - if (i === "Hips") { - // Hips only - targetAnimation.joints[i].thrust += percent * sourceAnimation.joints[i].thrust; - targetAnimation.joints[i].sway += percent * sourceAnimation.joints[i].sway; - targetAnimation.joints[i].bob += percent * sourceAnimation.joints[i].bob; - targetAnimation.joints[i].thrustPhase += percent * sourceAnimation.joints[i].thrustPhase; - targetAnimation.joints[i].swayPhase += percent * sourceAnimation.joints[i].swayPhase; - targetAnimation.joints[i].bobPhase += percent * sourceAnimation.joints[i].bobPhase; - targetAnimation.joints[i].thrustOffset += percent * sourceAnimation.joints[i].thrustOffset; - targetAnimation.joints[i].swayOffset += percent * sourceAnimation.joints[i].swayOffset; - targetAnimation.joints[i].bobOffset += percent * sourceAnimation.joints[i].bobOffset; - } - } - }, - - deepCopy: function(sourceAnimation, targetAnimation) { - // calibration - targetAnimation.calibration = JSON.parse(JSON.stringify(sourceAnimation.calibration)); - - // harmonics - targetAnimation.harmonics = {}; - if (sourceAnimation.harmonics) { - targetAnimation.harmonics = JSON.parse(JSON.stringify(sourceAnimation.harmonics)); - } - - // filters - targetAnimation.filters = {}; - for (i in sourceAnimation.filters) { - // are any filters specified for this joint? - if (sourceAnimation.filters[i]) { - targetAnimation.filters[i] = sourceAnimation.filters[i]; - // wave shapers - if (sourceAnimation.filters[i].pitchFilter) { - targetAnimation.filters[i].pitchFilter = sourceAnimation.filters[i].pitchFilter; - } - if (sourceAnimation.filters[i].yawFilter) { - targetAnimation.filters[i].yawFilter = sourceAnimation.filters[i].yawFilter; - } - if (sourceAnimation.filters[i].rollFilter) { - targetAnimation.filters[i].rollFilter = sourceAnimation.filters[i].rollFilter; - } - // LP filters - if (sourceAnimation.filters[i].swayLPFilter) { - targetAnimation.filters[i].swayLPFilter = sourceAnimation.filters[i].swayLPFilter; - } - if (sourceAnimation.filters[i].bobLPFilter) { - targetAnimation.filters[i].bobLPFilter = sourceAnimation.filters[i].bobLPFilter; - } - if (sourceAnimation.filters[i].thrustLPFilter) { - targetAnimation.filters[i].thrustLPFilter = sourceAnimation.filters[i].thrustLPFilter; - } - } - } - // joints - targetAnimation.joints = JSON.parse(JSON.stringify(sourceAnimation.joints)); - } - } - -})(); // end animation object literal - -// ReachPose datafile wrapper object -ReachPose = function(reachPoseName) { - this.name = reachPoseName; - this.reachPoseParameters = walkAssets.getReachPoseParameters(reachPoseName); - this.reachPoseDataFile = walkAssets.getReachPoseDataFile(reachPoseName); - this.progress = 0; - this.smoothingFilter = filter.createAveragingFilter(this.reachPoseParameters.smoothing); - this.currentStrength = function() { - // apply optionally smoothed (D)ASDR envelope to reach pose's strength / influence whilst active - var segmentProgress = undefined; // progress through chosen segment - var segmentTimeDelta = undefined; // total change in time over chosen segment - var segmentStrengthDelta = undefined; // total change in strength over chosen segment - var lastStrength = undefined; // the last value the previous segment held - var currentStrength = undefined; // return value - - // select parameters based on segment (a segment being one of (D),A,S,D or R) - if (this.progress >= this.reachPoseParameters.sustain.timing) { - // release segment - segmentProgress = this.progress - this.reachPoseParameters.sustain.timing; - segmentTimeDelta = this.reachPoseParameters.release.timing - this.reachPoseParameters.sustain.timing; - segmentStrengthDelta = this.reachPoseParameters.release.strength - this.reachPoseParameters.sustain.strength; - lastStrength = this.reachPoseParameters.sustain.strength; - } else if (this.progress >= this.reachPoseParameters.decay.timing) { - // sustain phase - segmentProgress = this.progress - this.reachPoseParameters.decay.timing; - segmentTimeDelta = this.reachPoseParameters.sustain.timing - this.reachPoseParameters.decay.timing; - segmentStrengthDelta = this.reachPoseParameters.sustain.strength - this.reachPoseParameters.decay.strength; - lastStrength = this.reachPoseParameters.decay.strength; - } else if (this.progress >= this.reachPoseParameters.attack.timing) { - // decay phase - segmentProgress = this.progress - this.reachPoseParameters.attack.timing; - segmentTimeDelta = this.reachPoseParameters.decay.timing - this.reachPoseParameters.attack.timing; - segmentStrengthDelta = this.reachPoseParameters.decay.strength - this.reachPoseParameters.attack.strength; - lastStrength = this.reachPoseParameters.attack.strength; - } else if (this.progress >= this.reachPoseParameters.delay.timing) { - // attack phase - segmentProgress = this.progress - this.reachPoseParameters.delay.timing; - segmentTimeDelta = this.reachPoseParameters.attack.timing - this.reachPoseParameters.delay.timing; - segmentStrengthDelta = this.reachPoseParameters.attack.strength - this.reachPoseParameters.delay.strength; - lastStrength = 0; //this.delay.strength; - } else { - // delay phase - segmentProgress = this.progress; - segmentTimeDelta = this.reachPoseParameters.delay.timing; - segmentStrengthDelta = this.reachPoseParameters.delay.strength; - lastStrength = 0; - } - currentStrength = segmentTimeDelta > 0 ? lastStrength + segmentStrengthDelta * segmentProgress / segmentTimeDelta - : lastStrength; - // smooth off the response curve - currentStrength = this.smoothingFilter.process(currentStrength); - return currentStrength; - } -}; - -// constructor with default parameters -TransitionParameters = function() { - this.duration = 0.5; - this.easingLower = {x:0.25, y:0.75}; - this.easingUpper = {x:0.75, y:0.25}; - this.reachPoses = []; -} - -const QUARTER_CYCLE = 90; -const HALF_CYCLE = 180; -const THREE_QUARTER_CYCLE = 270; -const FULL_CYCLE = 360; - -// constructor for animation Transition -Transition = function(nextAnimation, lastAnimation, lastTransition, playTransitionReachPoses) { - - if (playTransitionReachPoses === undefined) { - playTransitionReachPoses = true; - } - - // record the current state of animation - this.nextAnimation = nextAnimation; - this.lastAnimation = lastAnimation; - this.lastTransition = lastTransition; - - // collect information about the currently playing animation - this.direction = motion.direction; - this.lastDirection = motion.lastDirection; - this.lastFrequencyTimeWheelPos = motion.frequencyTimeWheelPos; - this.lastFrequencyTimeIncrement = motion.averageFrequencyTimeIncrement; - this.lastFrequencyTimeWheelRadius = motion.frequencyTimeWheelRadius; - this.degreesToTurn = 0; // total degrees to turn the ft wheel before the avatar stops (walk only) - this.degreesRemaining = 0; // remaining degrees to turn the ft wheel before the avatar stops (walk only) - this.lastElapsedFTDegrees = motion.elapsedFTDegrees; // degrees elapsed since last transition start - motion.elapsedFTDegrees = 0; // reset ready for the next transition - motion.frequencyTimeWheelPos = 0; // start the next animation's frequency time wheel from zero - - // set parameters for the transition - this.parameters = new TransitionParameters(); - this.liveReachPoses = []; - if (walkAssets && lastAnimation && nextAnimation) { - // overwrite this.parameters with any transition parameters specified for this particular transition - walkAssets.getTransitionParameters(lastAnimation, nextAnimation, this.parameters); - // fire up any reach poses for this transition - if (playTransitionReachPoses) { - for (poseName in this.parameters.reachPoses) { - this.liveReachPoses.push(new ReachPose(this.parameters.reachPoses[poseName])); - } - } - } - this.startTime = new Date().getTime(); // Starting timestamp (seconds) - this.progress = 0; // how far are we through the transition? - this.filteredProgress = 0; - - // coming to a halt whilst walking? if so, will need a clean stopping point defined - if (motion.isComingToHalt) { - - const FULL_CYCLE_THRESHOLD = 320; - const HALF_CYCLE_THRESHOLD = 140; - const CYCLE_COMMIT_THRESHOLD = 5; - - // how many degrees do we need to turn the walk wheel to finish walking with both feet on the ground? - if (this.lastElapsedFTDegrees < CYCLE_COMMIT_THRESHOLD) { - // just stop the walk cycle right here and blend to idle - this.degreesToTurn = 0; - } else if (this.lastElapsedFTDegrees < HALF_CYCLE) { - // we have not taken a complete step yet, so we advance to the second stop angle - this.degreesToTurn = HALF_CYCLE - this.lastFrequencyTimeWheelPos; - } else if (this.lastFrequencyTimeWheelPos > 0 && this.lastFrequencyTimeWheelPos <= HALF_CYCLE_THRESHOLD) { - // complete the step and stop at 180 - this.degreesToTurn = HALF_CYCLE - this.lastFrequencyTimeWheelPos; - } else if (this.lastFrequencyTimeWheelPos > HALF_CYCLE_THRESHOLD && this.lastFrequencyTimeWheelPos <= HALF_CYCLE) { - // complete the step and next then stop at 0 - this.degreesToTurn = HALF_CYCLE - this.lastFrequencyTimeWheelPos + HALF_CYCLE; - } else if (this.lastFrequencyTimeWheelPos > HALF_CYCLE && this.lastFrequencyTimeWheelPos <= FULL_CYCLE_THRESHOLD) { - // complete the step and stop at 0 - this.degreesToTurn = FULL_CYCLE - this.lastFrequencyTimeWheelPos; - } else { - // complete the step and the next then stop at 180 - this.degreesToTurn = FULL_CYCLE - this.lastFrequencyTimeWheelPos + HALF_CYCLE; - } - - // transition length in this case should be directly proportional to the remaining degrees to turn - var MIN_FT_INCREMENT = 5.0; // degrees per frame - var MIN_TRANSITION_DURATION = 0.4; - const TWO_THIRDS = 0.6667; - this.lastFrequencyTimeIncrement *= TWO_THIRDS; // help ease the transition - var lastFrequencyTimeIncrement = this.lastFrequencyTimeIncrement > MIN_FT_INCREMENT ? - this.lastFrequencyTimeIncrement : MIN_FT_INCREMENT; - var timeToFinish = Math.max(motion.deltaTime * this.degreesToTurn / lastFrequencyTimeIncrement, - MIN_TRANSITION_DURATION); - this.parameters.duration = timeToFinish; - this.degreesRemaining = this.degreesToTurn; - } - - // deal with transition recursion (overlapping transitions) - this.recursionDepth = 0; - this.incrementRecursion = function() { - this.recursionDepth += 1; - - // cancel any continued motion - this.degreesToTurn = 0; - - // limit the number of layered / nested transitions - if (this.lastTransition !== nullTransition) { - this.lastTransition.incrementRecursion(); - if (this.lastTransition.recursionDepth > MAX_TRANSITION_RECURSION) { - this.lastTransition = nullTransition; - } - } - }; - if (this.lastTransition !== nullTransition) { - this.lastTransition.incrementRecursion(); - } - - // end of transition initialisation. begin Transition public methods - - // keep up the pace for the frequency time wheel for the last animation - this.advancePreviousFrequencyTimeWheel = function(deltaTime) { - var wheelAdvance = undefined; - - if (this.lastAnimation === avatar.selectedWalkBlend && - this.nextAnimation === avatar.selectedIdle) { - if (this.degreesRemaining <= 0) { - // stop continued motion - wheelAdvance = 0; - if (motion.isComingToHalt) { - if (this.lastFrequencyTimeWheelPos < QUARTER_CYCLE) { - this.lastFrequencyTimeWheelPos = 0; - } else { - this.lastFrequencyTimeWheelPos = HALF_CYCLE; - } - } - } else { - wheelAdvance = this.lastFrequencyTimeIncrement; - var distanceToTravel = avatar.calibration.strideLength * wheelAdvance / HALF_CYCLE; - if (this.degreesRemaining <= 0) { - distanceToTravel = 0; - this.degreesRemaining = 0; - } else { - this.degreesRemaining -= wheelAdvance; - } - } - } else { - wheelAdvance = this.lastFrequencyTimeIncrement; - } - - // advance the ft wheel - this.lastFrequencyTimeWheelPos += wheelAdvance; - if (this.lastFrequencyTimeWheelPos >= FULL_CYCLE) { - this.lastFrequencyTimeWheelPos = this.lastFrequencyTimeWheelPos % FULL_CYCLE; - } - - // advance ft wheel for the nested (previous) Transition - if (this.lastTransition !== nullTransition) { - this.lastTransition.advancePreviousFrequencyTimeWheel(deltaTime); - } - // update the lastElapsedFTDegrees for short stepping - this.lastElapsedFTDegrees += wheelAdvance; - this.degreesTurned += wheelAdvance; - }; - - this.updateProgress = function() { - const MILLISECONDS_CONVERT = 1000; - const ACCURACY_INCREASER = 1000; - var elapasedTime = (new Date().getTime() - this.startTime) / MILLISECONDS_CONVERT; - this.progress = elapasedTime / this.parameters.duration; - this.progress = Math.round(this.progress * ACCURACY_INCREASER) / ACCURACY_INCREASER; - - // updated nested transition/s - if (this.lastTransition !== nullTransition) { - if (this.lastTransition.updateProgress() === TRANSITION_COMPLETE) { - // the previous transition is now complete - this.lastTransition = nullTransition; - } - } - - // update any reachPoses - for (pose in this.liveReachPoses) { - // use independent timing for reachPoses - this.liveReachPoses[pose].progress += (motion.deltaTime / this.liveReachPoses[pose].reachPoseParameters.duration); - if (this.liveReachPoses[pose].progress >= 1) { - // time to kill off this reach pose - this.liveReachPoses.splice(pose, 1); - } - } - - // update transition progress - this.filteredProgress = filter.bezier(this.progress, this.parameters.easingLower, this.parameters.easingUpper); - return this.progress >= 1 ? TRANSITION_COMPLETE : false; - }; - - this.blendTranslations = function(frequencyTimeWheelPos, direction) { - var lastTranslations = {x:0, y:0, z:0}; - var nextTranslations = animationOperations.calculateTranslations(this.nextAnimation, - frequencyTimeWheelPos, - direction); - // are we blending with a previous, still live transition? - if (this.lastTransition !== nullTransition) { - lastTranslations = this.lastTransition.blendTranslations(this.lastFrequencyTimeWheelPos, - this.lastDirection); - } else { - lastTranslations = animationOperations.calculateTranslations(this.lastAnimation, - this.lastFrequencyTimeWheelPos, - this.lastDirection); - } - - // blend last / next translations - nextTranslations = Vec3.multiply(this.filteredProgress, nextTranslations); - lastTranslations = Vec3.multiply((1 - this.filteredProgress), lastTranslations); - nextTranslations = Vec3.sum(nextTranslations, lastTranslations); - - if (this.liveReachPoses.length > 0) { - for (pose in this.liveReachPoses) { - var reachPoseStrength = this.liveReachPoses[pose].currentStrength(); - var poseTranslations = animationOperations.calculateTranslations( - this.liveReachPoses[pose].reachPoseDataFile, - frequencyTimeWheelPos, - direction); - - // can't use Vec3 operations here, as if x,y or z is zero, the reachPose should have no influence at all - if (Math.abs(poseTranslations.x) > 0) { - nextTranslations.x = reachPoseStrength * poseTranslations.x + (1 - reachPoseStrength) * nextTranslations.x; - } - if (Math.abs(poseTranslations.y) > 0) { - nextTranslations.y = reachPoseStrength * poseTranslations.y + (1 - reachPoseStrength) * nextTranslations.y; - } - if (Math.abs(poseTranslations.z) > 0) { - nextTranslations.z = reachPoseStrength * poseTranslations.z + (1 - reachPoseStrength) * nextTranslations.z; - } - } - } - return nextTranslations; - }; - - this.blendRotations = function(jointName, frequencyTimeWheelPos, direction) { - var lastRotations = {x:0, y:0, z:0}; - var nextRotations = animationOperations.calculateRotations(jointName, - this.nextAnimation, - frequencyTimeWheelPos, - direction); - - // are we blending with a previous, still live transition? - if (this.lastTransition !== nullTransition) { - lastRotations = this.lastTransition.blendRotations(jointName, - this.lastFrequencyTimeWheelPos, - this.lastDirection); - } else { - lastRotations = animationOperations.calculateRotations(jointName, - this.lastAnimation, - this.lastFrequencyTimeWheelPos, - this.lastDirection); - } - // blend last / next translations - nextRotations = Vec3.multiply(this.filteredProgress, nextRotations); - lastRotations = Vec3.multiply((1 - this.filteredProgress), lastRotations); - nextRotations = Vec3.sum(nextRotations, lastRotations); - - // are there reachPoses defined for this transition? - if (this.liveReachPoses.length > 0) { - for (pose in this.liveReachPoses) { - var reachPoseStrength = this.liveReachPoses[pose].currentStrength(); - var poseRotations = animationOperations.calculateRotations(jointName, - this.liveReachPoses[pose].reachPoseDataFile, - frequencyTimeWheelPos, - direction); - - // don't use Vec3 operations here, as if x,y or z is zero, the reach pose should have no influence at all - if (Math.abs(poseRotations.x) > 0) { - nextRotations.x = reachPoseStrength * poseRotations.x + (1 - reachPoseStrength) * nextRotations.x; - } - if (Math.abs(poseRotations.y) > 0) { - nextRotations.y = reachPoseStrength * poseRotations.y + (1 - reachPoseStrength) * nextRotations.y; - } - if (Math.abs(poseRotations.z) > 0) { - nextRotations.z = reachPoseStrength * poseRotations.z + (1 - reachPoseStrength) * nextRotations.z; - } - } - } - return nextRotations; - }; -}; // end Transition constructor - -// individual joint modifiers -FrequencyMultipliers = function(joint, direction) { - // gather multipliers - this.pitchFrequencyMultiplier = 1; - this.yawFrequencyMultiplier = 1; - this.rollFrequencyMultiplier = 1; - this.swayFrequencyMultiplier = 1; - this.bobFrequencyMultiplier = 1; - this.thrustFrequencyMultiplier = 1; - - if (joint) { - if (joint.pitchFrequencyMultiplier) { - this.pitchFrequencyMultiplier = joint.pitchFrequencyMultiplier; - } - if (joint.yawFrequencyMultiplier) { - this.yawFrequencyMultiplier = joint.yawFrequencyMultiplier; - } - if (joint.rollFrequencyMultiplier) { - this.rollFrequencyMultiplier = joint.rollFrequencyMultiplier; - } - if (joint.swayFrequencyMultiplier) { - this.swayFrequencyMultiplier = joint.swayFrequencyMultiplier; - } - if (joint.bobFrequencyMultiplier) { - this.bobFrequencyMultiplier = joint.bobFrequencyMultiplier; - } - if (joint.thrustFrequencyMultiplier) { - this.thrustFrequencyMultiplier = joint.thrustFrequencyMultiplier; - } - } +// +// walkApi.js +// version 1.3 +// +// Created by David Wooldridge, June 2015 +// Copyright © 2014 - 2015 High Fidelity, Inc. +// +// Exposes API for use by walk.js version 1.2+. +// +// Editing tools for animation data files available here: https://github.com/DaveDubUK/walkTools +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +// included here to ensure walkApi.js can be used as an API, separate from walk.js +Script.include("./libraries/walkConstants.js"); + +Avatar = function() { + // if Hydras are connected, the only way to enable use is to never set any arm joint rotation + this.hydraCheck = function() { + // function courtesy of Thijs Wenker (frisbee.js) + var numberOfButtons = Controller.getNumberOfButtons(); + var numberOfTriggers = Controller.getNumberOfTriggers(); + var numberOfSpatialControls = Controller.getNumberOfSpatialControls(); + const HYDRA_BUTTONS = 12; + const HYDRA_TRIGGERS = 2; + const HYDRA_CONTROLLERS_PER_TRIGGER = 2; + var controllersPerTrigger = numberOfSpatialControls / numberOfTriggers; + if (numberOfButtons == HYDRA_BUTTONS && + numberOfTriggers == HYDRA_TRIGGERS && + controllersPerTrigger == HYDRA_CONTROLLERS_PER_TRIGGER) { + print('walk.js info: Razer Hydra detected. Setting arms free (not controlled by script)'); + return true; + } else { + print('walk.js info: Razer Hydra not detected. Arms will be controlled by script.'); + return false; + } + } + // settings + this.headFree = true; + this.armsFree = this.hydraCheck(); // automatically sets true to enable Hydra support - temporary fix + this.makesFootStepSounds = false; + this.blenderPreRotations = false; // temporary fix + this.animationSet = undefined; // currently just one animation set + this.setAnimationSet = function(animationSet) { + this.animationSet = animationSet; + switch (animationSet) { + case 'standardMale': + this.selectedIdle = walkAssets.getAnimationDataFile("MaleIdle"); + this.selectedWalk = walkAssets.getAnimationDataFile("MaleWalk"); + this.selectedWalkBackwards = walkAssets.getAnimationDataFile("MaleWalkBackwards"); + this.selectedSideStepLeft = walkAssets.getAnimationDataFile("MaleSideStepLeft"); + this.selectedSideStepRight = walkAssets.getAnimationDataFile("MaleSideStepRight"); + this.selectedWalkBlend = walkAssets.getAnimationDataFile("WalkBlend"); + this.selectedHover = walkAssets.getAnimationDataFile("MaleHover"); + this.selectedFly = walkAssets.getAnimationDataFile("MaleFly"); + this.selectedFlyBackwards = walkAssets.getAnimationDataFile("MaleFlyBackwards"); + this.selectedFlyDown = walkAssets.getAnimationDataFile("MaleFlyDown"); + this.selectedFlyUp = walkAssets.getAnimationDataFile("MaleFlyUp"); + this.selectedFlyBlend = walkAssets.getAnimationDataFile("FlyBlend"); + this.currentAnimation = this.selectedIdle; + return; + } + } + this.setAnimationSet('standardMale'); + + // calibration + this.calibration = { + hipsToFeet: 1, + strideLength: this.selectedWalk.calibration.strideLength + } + this.distanceFromSurface = 0; + this.calibrate = function() { + // Triple check: measurements are taken three times to ensure accuracy - the first result is often too large + const MAX_ATTEMPTS = 3; + var attempts = MAX_ATTEMPTS; + var extraAttempts = 0; + do { + for (joint in walkAssets.animationReference.joints) { + var IKChain = walkAssets.animationReference.joints[joint].IKChain; + + // only need to zero right leg IK chain and hips + if (IKChain === "RightLeg" || joint === "Hips" ) { + MyAvatar.setJointRotation(joint, Quat.fromPitchYawRollDegrees(0, 0, 0)); + } + } + this.calibration.hipsToFeet = MyAvatar.getJointPosition("Hips").y - MyAvatar.getJointPosition("RightToeBase").y; + + // maybe measuring before Blender pre-rotations have been applied? + if (this.calibration.hipsToFeet < 0 && this.blenderPreRotations) { + this.calibration.hipsToFeet *= -1; + } + + if (this.calibration.hipsToFeet === 0 && extraAttempts < 100) { + attempts++; + extraAttempts++;// Interface can sometimes report zero for hips to feet. if so, we try again. + } + } while (attempts-- > 1) + + // just in case + if (this.calibration.hipsToFeet <= 0 || isNaN(this.calibration.hipsToFeet)) { + this.calibration.hipsToFeet = 1; + print('walk.js error: Unable to get a non-zero measurement for the avatar hips to feet measure. Hips to feet set to default value ('+ + this.calibration.hipsToFeet.toFixed(3)+'m). This will cause some foot sliding. If your avatar has only just appeared, it is recommended that you re-load the walk script.'); + } else { + print('walk.js info: Hips to feet calibrated to '+this.calibration.hipsToFeet.toFixed(3)+'m'); + } + } + + // pose the fingers + this.poseFingers = function() { + for (knuckle in walkAssets.animationReference.leftHand) { + if (walkAssets.animationReference.leftHand[knuckle].IKChain === "LeftHandThumb") { + MyAvatar.setJointRotation(knuckle, Quat.fromPitchYawRollDegrees(0, 0, -4)); + } else { + MyAvatar.setJointRotation(knuckle, Quat.fromPitchYawRollDegrees(16, 0, 5)); + } + } + for (knuckle in walkAssets.animationReference.rightHand) { + if (walkAssets.animationReference.rightHand[knuckle].IKChain === "RightHandThumb") { + MyAvatar.setJointRotation(knuckle, Quat.fromPitchYawRollDegrees(0, 0, 4)); + } else { + MyAvatar.setJointRotation(knuckle, Quat.fromPitchYawRollDegrees(16, 0, -5)); + } + } + }; + this.calibrate(); + this.poseFingers(); + + // footsteps + this.nextStep = RIGHT; // the first step is right, because the waveforms say so + this.leftAudioInjector = null; + this.rightAudioInjector = null; + this.makeFootStepSound = function() { + // correlate footstep volume with avatar speed. place the audio source at the feet, not the hips + const SPEED_THRESHOLD = 0.4; + const VOLUME_ATTENUATION = 0.8; + const MIN_VOLUME = 0.5; + var volume = Vec3.length(motion.velocity) > SPEED_THRESHOLD ? + VOLUME_ATTENUATION * Vec3.length(motion.velocity) / MAX_WALK_SPEED : MIN_VOLUME; + volume = volume > 1 ? 1 : volume; // occurs when landing at speed - can walk faster than max walking speed + var options = { + position: Vec3.sum(MyAvatar.position, {x:0, y: -this.calibration.hipsToFeet, z:0}), + volume: volume + }; + if (this.nextStep === RIGHT) { + if (this.rightAudioInjector === null) { + this.rightAudioInjector = Audio.playSound(walkAssets.footsteps[0], options); + } else { + this.rightAudioInjector.setOptions(options); + this.rightAudioInjector.restart(); + } + this.nextStep = LEFT; + } else if (this.nextStep === LEFT) { + if (this.leftAudioInjector === null) { + this.leftAudioInjector = Audio.playSound(walkAssets.footsteps[1], options); + } else { + this.leftAudioInjector.setOptions(options); + this.leftAudioInjector.restart(); + } + this.nextStep = RIGHT; + } + } +}; + +// constructor for the Motion object +Motion = function() { + this.isLive = true; + // locomotion status + this.state = STATIC; + this.nextState = STATIC; + this.isMoving = false; + this.isWalkingSpeed = false; + this.isFlyingSpeed = false; + this.isAccelerating = false; + this.isDecelerating = false; + this.isDeceleratingFast = false; + this.isComingToHalt = false; + this.directedAcceleration = 0; + + // used to make sure at least one step has been taken when transitioning from a walk cycle + this.elapsedFTDegrees = 0; + + // the current transition (any layered transitions are nested within this transition) + this.currentTransition = null; + + // orientation, locomotion and timing + this.velocity = {x:0, y:0, z:0}; + this.acceleration = {x:0, y:0, z:0}; + this.yaw = Quat.safeEulerAngles(MyAvatar.orientation).y; + this.yawDelta = 0; + this.yawDeltaAcceleration = 0; + this.direction = FORWARDS; + this.deltaTime = 0; + + // historical orientation, locomotion and timing + this.lastDirection = FORWARDS; + this.lastVelocity = {x:0, y:0, z:0}; + this.lastYaw = Quat.safeEulerAngles(MyAvatar.orientation).y; + this.lastYawDelta = 0; + this.lastYawDeltaAcceleration = 0; + + // Quat.safeEulerAngles(MyAvatar.orientation).y tends to repeat values between frames, so values are filtered + var YAW_SMOOTHING = 22; + this.yawFilter = filter.createAveragingFilter(YAW_SMOOTHING); + this.deltaTimeFilter = filter.createAveragingFilter(YAW_SMOOTHING); + this.yawDeltaAccelerationFilter = filter.createAveragingFilter(YAW_SMOOTHING); + + // assess locomotion state + this.assess = function(deltaTime) { + // calculate avatar frame speed, velocity and acceleration + this.deltaTime = deltaTime; + this.velocity = Vec3.multiplyQbyV(Quat.inverse(MyAvatar.orientation), MyAvatar.getVelocity()); + var lateralVelocity = Math.sqrt(Math.pow(this.velocity.x, 2) + Math.pow(this.velocity.z, 2)); + + // MyAvatar.getAcceleration() currently not working. bug report submitted: https://worklist.net/20527 + var acceleration = {x:0, y:0, z:0}; + this.acceleration.x = (this.velocity.x - this.lastVelocity.x) / deltaTime; + this.acceleration.y = (this.velocity.y - this.lastVelocity.y) / deltaTime; + this.acceleration.z = (this.velocity.z - this.lastVelocity.z) / deltaTime; + + // MyAvatar.getAngularVelocity and MyAvatar.getAngularAcceleration currently not working. bug report submitted + this.yaw = Quat.safeEulerAngles(MyAvatar.orientation).y; + if (this.lastYaw < 0 && this.yaw > 0 || this.lastYaw > 0 && this.yaw < 0) { + this.lastYaw *= -1; + } + var timeDelta = this.deltaTimeFilter.process(deltaTime); + this.yawDelta = filter.degToRad(this.yawFilter.process(this.lastYaw - this.yaw)) / timeDelta; + this.yawDeltaAcceleration = this.yawDeltaAccelerationFilter.process(this.lastYawDelta - this.yawDelta) / timeDelta; + + // how far above the surface is the avatar? (for testing / validation purposes) + var pickRay = {origin: MyAvatar.position, direction: {x:0, y:-1, z:0}}; + var distanceFromSurface = Entities.findRayIntersectionBlocking(pickRay).distance; + avatar.distanceFromSurface = distanceFromSurface - avatar.calibration.hipsToFeet; + + // determine principle direction of locomotion + var FWD_BACK_BIAS = 100; // helps prevent false sidestep condition detection when banking hard + if (Math.abs(this.velocity.x) > Math.abs(this.velocity.y) && + Math.abs(this.velocity.x) > FWD_BACK_BIAS * Math.abs(this.velocity.z)) { + if (this.velocity.x < 0) { + this.directedAcceleration = -this.acceleration.x; + this.direction = LEFT; + } else if (this.velocity.x > 0){ + this.directedAcceleration = this.acceleration.x; + this.direction = RIGHT; + } + } else if (Math.abs(this.velocity.y) > Math.abs(this.velocity.x) && + Math.abs(this.velocity.y) > Math.abs(this.velocity.z)) { + if (this.velocity.y > 0) { + this.directedAcceleration = this.acceleration.y; + this.direction = UP; + } else if (this.velocity.y < 0) { + this.directedAcceleration = -this.acceleration.y; + this.direction = DOWN; + } + } else if (FWD_BACK_BIAS * Math.abs(this.velocity.z) > Math.abs(this.velocity.x) && + Math.abs(this.velocity.z) > Math.abs(this.velocity.y)) { + if (this.velocity.z < 0) { + this.direction = FORWARDS; + this.directedAcceleration = -this.acceleration.z; + } else if (this.velocity.z > 0) { + this.directedAcceleration = this.acceleration.z; + this.direction = BACKWARDS; + } + } else { + this.direction = NONE; + this.directedAcceleration = 0; + } + + // set speed flags + if (Vec3.length(this.velocity) < MOVE_THRESHOLD) { + this.isMoving = false; + this.isWalkingSpeed = false; + this.isFlyingSpeed = false; + this.isComingToHalt = false; + } else if (Vec3.length(this.velocity) < MAX_WALK_SPEED) { + this.isMoving = true; + this.isWalkingSpeed = true; + this.isFlyingSpeed = false; + } else { + this.isMoving = true; + this.isWalkingSpeed = false; + this.isFlyingSpeed = true; + } + + // set acceleration flags + if (this.directedAcceleration > ACCELERATION_THRESHOLD) { + this.isAccelerating = true; + this.isDecelerating = false; + this.isDeceleratingFast = false; + this.isComingToHalt = false; + } else if (this.directedAcceleration < DECELERATION_THRESHOLD) { + this.isAccelerating = false; + this.isDecelerating = true; + this.isDeceleratingFast = (this.directedAcceleration < FAST_DECELERATION_THRESHOLD); + } else { + this.isAccelerating = false; + this.isDecelerating = false; + this.isDeceleratingFast = false; + } + + // use the gathered information to build up some spatial awareness + var isOnSurface = (avatar.distanceFromSurface < ON_SURFACE_THRESHOLD); + var isUnderGravity = (avatar.distanceFromSurface < GRAVITY_THRESHOLD); + var isTakingOff = (isUnderGravity && this.velocity.y > OVERCOME_GRAVITY_SPEED); + var isComingInToLand = (isUnderGravity && this.velocity.y < -OVERCOME_GRAVITY_SPEED); + var aboutToLand = isComingInToLand && avatar.distanceFromSurface < LANDING_THRESHOLD; + var surfaceMotion = isOnSurface && this.isMoving; + var acceleratingAndAirborne = this.isAccelerating && !isOnSurface; + var goingTooFastToWalk = !this.isDecelerating && this.isFlyingSpeed; + var movingDirectlyUpOrDown = (this.direction === UP || this.direction === DOWN) + var maybeBouncing = Math.abs(this.acceleration.y > BOUNCE_ACCELERATION_THRESHOLD) ? true : false; + + // we now have enough information to set the appropriate locomotion mode + switch (this.state) { + case STATIC: + var staticToAirMotion = this.isMoving && (acceleratingAndAirborne || goingTooFastToWalk || + (movingDirectlyUpOrDown && !isOnSurface)); + var staticToSurfaceMotion = surfaceMotion && !motion.isComingToHalt && !movingDirectlyUpOrDown && + !this.isDecelerating && lateralVelocity > MOVE_THRESHOLD; + + if (staticToAirMotion) { + this.nextState = AIR_MOTION; + } else if (staticToSurfaceMotion) { + this.nextState = SURFACE_MOTION; + } else { + this.nextState = STATIC; + } + break; + + case SURFACE_MOTION: + var surfaceMotionToStatic = !this.isMoving || + (this.isDecelerating && motion.lastDirection !== DOWN && surfaceMotion && + !maybeBouncing && Vec3.length(this.velocity) < MAX_WALK_SPEED); + var surfaceMotionToAirMotion = (acceleratingAndAirborne || goingTooFastToWalk || movingDirectlyUpOrDown) && + (!surfaceMotion && isTakingOff) || + (!surfaceMotion && this.isMoving && !isComingInToLand); + + if (surfaceMotionToStatic) { + // working on the assumption that stopping is now inevitable + if (!motion.isComingToHalt && isOnSurface) { + motion.isComingToHalt = true; + } + this.nextState = STATIC; + } else if (surfaceMotionToAirMotion) { + this.nextState = AIR_MOTION; + } else { + this.nextState = SURFACE_MOTION; + } + break; + + case AIR_MOTION: + var airMotionToSurfaceMotion = (surfaceMotion || aboutToLand) && !movingDirectlyUpOrDown; + var airMotionToStatic = !this.isMoving && this.direction === this.lastDirection; + + if (airMotionToSurfaceMotion){ + this.nextState = SURFACE_MOTION; + } else if (airMotionToStatic) { + this.nextState = STATIC; + } else { + this.nextState = AIR_MOTION; + } + break; + } + } + + // frequency time wheel (foot / ground speed matching) + const DEFAULT_HIPS_TO_FEET = 1; + this.frequencyTimeWheelPos = 0; + this.frequencyTimeWheelRadius = DEFAULT_HIPS_TO_FEET / 2; + this.recentFrequencyTimeIncrements = []; + const FT_WHEEL_HISTORY_LENGTH = 8; + for (var i = 0; i < FT_WHEEL_HISTORY_LENGTH; i++) { + this.recentFrequencyTimeIncrements.push(0); + } + this.averageFrequencyTimeIncrement = 0; + + this.advanceFrequencyTimeWheel = function(angle){ + this.elapsedFTDegrees += angle; + // keep a running average of increments for use in transitions (used during transitioning) + this.recentFrequencyTimeIncrements.push(angle); + this.recentFrequencyTimeIncrements.shift(); + for (increment in this.recentFrequencyTimeIncrements) { + this.averageFrequencyTimeIncrement += this.recentFrequencyTimeIncrements[increment]; + } + this.averageFrequencyTimeIncrement /= this.recentFrequencyTimeIncrements.length; + this.frequencyTimeWheelPos += angle; + const FULL_CIRCLE = 360; + if (this.frequencyTimeWheelPos >= FULL_CIRCLE) { + this.frequencyTimeWheelPos = this.frequencyTimeWheelPos % FULL_CIRCLE; + } + } + + this.saveHistory = function() { + this.lastDirection = this.direction; + this.lastVelocity = this.velocity; + this.lastYaw = this.yaw; + this.lastYawDelta = this.yawDelta; + this.lastYawDeltaAcceleration = this.yawDeltaAcceleration; + } +}; // end Motion constructor + +// animation manipulation object +animationOperations = (function() { + + return { + + // helper function for renderMotion(). calculate joint translations based on animation file settings and frequency * time + calculateTranslations: function(animation, ft, direction) { + var jointName = "Hips"; + var joint = animation.joints[jointName]; + var jointTranslations = {x:0, y:0, z:0}; + + // gather modifiers and multipliers + modifiers = new FrequencyMultipliers(joint, direction); + + // calculate translations. Use synthesis filters where specified by the animation data file. + + // sway (oscillation on the x-axis) + if (animation.filters.hasOwnProperty(jointName) && 'swayFilter' in animation.filters[jointName]) { + jointTranslations.x = joint.sway * animation.filters[jointName].swayFilter.calculate + (filter.degToRad(modifiers.swayFrequencyMultiplier * ft + joint.swayPhase)) + joint.swayOffset; + } else { + jointTranslations.x = joint.sway * Math.sin + (filter.degToRad(modifiers.swayFrequencyMultiplier * ft + joint.swayPhase)) + joint.swayOffset; + } + // bob (oscillation on the y-axis) + if (animation.filters.hasOwnProperty(jointName) && 'bobFilter' in animation.filters[jointName]) { + jointTranslations.y = joint.bob * animation.filters[jointName].bobFilter.calculate + (filter.degToRad(modifiers.bobFrequencyMultiplier * ft + joint.bobPhase)) + joint.bobOffset; + } else { + jointTranslations.y = joint.bob * Math.sin + (filter.degToRad(modifiers.bobFrequencyMultiplier * ft + joint.bobPhase)) + joint.bobOffset; + + if (animation.filters.hasOwnProperty(jointName) && 'bobLPFilter' in animation.filters[jointName]) { + jointTranslations.y = filter.clipTrough(jointTranslations.y, joint, 2); + jointTranslations.y = animation.filters[jointName].bobLPFilter.process(jointTranslations.y); + } + } + // thrust (oscillation on the z-axis) + if (animation.filters.hasOwnProperty(jointName) && 'thrustFilter' in animation.filters[jointName]) { + jointTranslations.z = joint.thrust * animation.filters[jointName].thrustFilter.calculate + (filter.degToRad(modifiers.thrustFrequencyMultiplier * ft + joint.thrustPhase)) + joint.thrustOffset; + } else { + jointTranslations.z = joint.thrust * Math.sin + (filter.degToRad(modifiers.thrustFrequencyMultiplier * ft + joint.thrustPhase)) + joint.thrustOffset; + } + return jointTranslations; + }, + + // helper function for renderMotion(). calculate joint rotations based on animation file settings and frequency * time + calculateRotations: function(jointName, animation, ft, direction) { + var joint = animation.joints[jointName]; + var jointRotations = {x:0, y:0, z:0}; + + if (avatar.blenderPreRotations) { + jointRotations = Vec3.sum(jointRotations, walkAssets.blenderPreRotations.joints[jointName]); + } + + // gather frequency multipliers for this joint + modifiers = new FrequencyMultipliers(joint, direction); + + // calculate rotations. Use synthesis filters where specified by the animation data file. + + // calculate pitch + if (animation.filters.hasOwnProperty(jointName) && + 'pitchFilter' in animation.filters[jointName]) { + jointRotations.x += joint.pitch * animation.filters[jointName].pitchFilter.calculate + (filter.degToRad(ft * modifiers.pitchFrequencyMultiplier + joint.pitchPhase)) + joint.pitchOffset; + } else { + jointRotations.x += joint.pitch * Math.sin + (filter.degToRad(ft * modifiers.pitchFrequencyMultiplier + joint.pitchPhase)) + joint.pitchOffset; + } + // calculate yaw + if (animation.filters.hasOwnProperty(jointName) && + 'yawFilter' in animation.filters[jointName]) { + jointRotations.y += joint.yaw * animation.filters[jointName].yawFilter.calculate + (filter.degToRad(ft * modifiers.yawFrequencyMultiplier + joint.yawPhase)) + joint.yawOffset; + } else { + jointRotations.y += joint.yaw * Math.sin + (filter.degToRad(ft * modifiers.yawFrequencyMultiplier + joint.yawPhase)) + joint.yawOffset; + } + // calculate roll + if (animation.filters.hasOwnProperty(jointName) && + 'rollFilter' in animation.filters[jointName]) { + jointRotations.z += joint.roll * animation.filters[jointName].rollFilter.calculate + (filter.degToRad(ft * modifiers.rollFrequencyMultiplier + joint.rollPhase)) + joint.rollOffset; + } else { + jointRotations.z += joint.roll * Math.sin + (filter.degToRad(ft * modifiers.rollFrequencyMultiplier + joint.rollPhase)) + joint.rollOffset; + } + return jointRotations; + }, + + zeroAnimation: function(animation) { + for (i in animation.joints) { + for (j in animation.joints[i]) { + animation.joints[i][j] = 0; + } + } + }, + + blendAnimation: function(sourceAnimation, targetAnimation, percent) { + for (i in targetAnimation.joints) { + targetAnimation.joints[i].pitch += percent * sourceAnimation.joints[i].pitch; + targetAnimation.joints[i].yaw += percent * sourceAnimation.joints[i].yaw; + targetAnimation.joints[i].roll += percent * sourceAnimation.joints[i].roll; + targetAnimation.joints[i].pitchPhase += percent * sourceAnimation.joints[i].pitchPhase; + targetAnimation.joints[i].yawPhase += percent * sourceAnimation.joints[i].yawPhase; + targetAnimation.joints[i].rollPhase += percent * sourceAnimation.joints[i].rollPhase; + targetAnimation.joints[i].pitchOffset += percent * sourceAnimation.joints[i].pitchOffset; + targetAnimation.joints[i].yawOffset += percent * sourceAnimation.joints[i].yawOffset; + targetAnimation.joints[i].rollOffset += percent * sourceAnimation.joints[i].rollOffset; + if (i === "Hips") { + // Hips only + targetAnimation.joints[i].thrust += percent * sourceAnimation.joints[i].thrust; + targetAnimation.joints[i].sway += percent * sourceAnimation.joints[i].sway; + targetAnimation.joints[i].bob += percent * sourceAnimation.joints[i].bob; + targetAnimation.joints[i].thrustPhase += percent * sourceAnimation.joints[i].thrustPhase; + targetAnimation.joints[i].swayPhase += percent * sourceAnimation.joints[i].swayPhase; + targetAnimation.joints[i].bobPhase += percent * sourceAnimation.joints[i].bobPhase; + targetAnimation.joints[i].thrustOffset += percent * sourceAnimation.joints[i].thrustOffset; + targetAnimation.joints[i].swayOffset += percent * sourceAnimation.joints[i].swayOffset; + targetAnimation.joints[i].bobOffset += percent * sourceAnimation.joints[i].bobOffset; + } + } + }, + + deepCopy: function(sourceAnimation, targetAnimation) { + // calibration + targetAnimation.calibration = JSON.parse(JSON.stringify(sourceAnimation.calibration)); + + // harmonics + targetAnimation.harmonics = {}; + if (sourceAnimation.harmonics) { + targetAnimation.harmonics = JSON.parse(JSON.stringify(sourceAnimation.harmonics)); + } + + // filters + targetAnimation.filters = {}; + for (i in sourceAnimation.filters) { + // are any filters specified for this joint? + if (sourceAnimation.filters[i]) { + targetAnimation.filters[i] = sourceAnimation.filters[i]; + // wave shapers + if (sourceAnimation.filters[i].pitchFilter) { + targetAnimation.filters[i].pitchFilter = sourceAnimation.filters[i].pitchFilter; + } + if (sourceAnimation.filters[i].yawFilter) { + targetAnimation.filters[i].yawFilter = sourceAnimation.filters[i].yawFilter; + } + if (sourceAnimation.filters[i].rollFilter) { + targetAnimation.filters[i].rollFilter = sourceAnimation.filters[i].rollFilter; + } + // LP filters + if (sourceAnimation.filters[i].swayLPFilter) { + targetAnimation.filters[i].swayLPFilter = sourceAnimation.filters[i].swayLPFilter; + } + if (sourceAnimation.filters[i].bobLPFilter) { + targetAnimation.filters[i].bobLPFilter = sourceAnimation.filters[i].bobLPFilter; + } + if (sourceAnimation.filters[i].thrustLPFilter) { + targetAnimation.filters[i].thrustLPFilter = sourceAnimation.filters[i].thrustLPFilter; + } + } + } + // joints + targetAnimation.joints = JSON.parse(JSON.stringify(sourceAnimation.joints)); + } + } + +})(); // end animation object literal + +// ReachPose datafile wrapper object +ReachPose = function(reachPoseName) { + this.name = reachPoseName; + this.reachPoseParameters = walkAssets.getReachPoseParameters(reachPoseName); + this.reachPoseDataFile = walkAssets.getReachPoseDataFile(reachPoseName); + this.progress = 0; + this.smoothingFilter = filter.createAveragingFilter(this.reachPoseParameters.smoothing); + this.currentStrength = function() { + // apply optionally smoothed (D)ASDR envelope to reach pose's strength / influence whilst active + var segmentProgress = undefined; // progress through chosen segment + var segmentTimeDelta = undefined; // total change in time over chosen segment + var segmentStrengthDelta = undefined; // total change in strength over chosen segment + var lastStrength = undefined; // the last value the previous segment held + var currentStrength = undefined; // return value + + // select parameters based on segment (a segment being one of (D),A,S,D or R) + if (this.progress >= this.reachPoseParameters.sustain.timing) { + // release segment + segmentProgress = this.progress - this.reachPoseParameters.sustain.timing; + segmentTimeDelta = this.reachPoseParameters.release.timing - this.reachPoseParameters.sustain.timing; + segmentStrengthDelta = this.reachPoseParameters.release.strength - this.reachPoseParameters.sustain.strength; + lastStrength = this.reachPoseParameters.sustain.strength; + } else if (this.progress >= this.reachPoseParameters.decay.timing) { + // sustain phase + segmentProgress = this.progress - this.reachPoseParameters.decay.timing; + segmentTimeDelta = this.reachPoseParameters.sustain.timing - this.reachPoseParameters.decay.timing; + segmentStrengthDelta = this.reachPoseParameters.sustain.strength - this.reachPoseParameters.decay.strength; + lastStrength = this.reachPoseParameters.decay.strength; + } else if (this.progress >= this.reachPoseParameters.attack.timing) { + // decay phase + segmentProgress = this.progress - this.reachPoseParameters.attack.timing; + segmentTimeDelta = this.reachPoseParameters.decay.timing - this.reachPoseParameters.attack.timing; + segmentStrengthDelta = this.reachPoseParameters.decay.strength - this.reachPoseParameters.attack.strength; + lastStrength = this.reachPoseParameters.attack.strength; + } else if (this.progress >= this.reachPoseParameters.delay.timing) { + // attack phase + segmentProgress = this.progress - this.reachPoseParameters.delay.timing; + segmentTimeDelta = this.reachPoseParameters.attack.timing - this.reachPoseParameters.delay.timing; + segmentStrengthDelta = this.reachPoseParameters.attack.strength - this.reachPoseParameters.delay.strength; + lastStrength = 0; //this.delay.strength; + } else { + // delay phase + segmentProgress = this.progress; + segmentTimeDelta = this.reachPoseParameters.delay.timing; + segmentStrengthDelta = this.reachPoseParameters.delay.strength; + lastStrength = 0; + } + currentStrength = segmentTimeDelta > 0 ? lastStrength + segmentStrengthDelta * segmentProgress / segmentTimeDelta + : lastStrength; + // smooth off the response curve + currentStrength = this.smoothingFilter.process(currentStrength); + return currentStrength; + } +}; + +// constructor with default parameters +TransitionParameters = function() { + this.duration = 0.5; + this.easingLower = {x:0.25, y:0.75}; + this.easingUpper = {x:0.75, y:0.25}; + this.reachPoses = []; +} + +const QUARTER_CYCLE = 90; +const HALF_CYCLE = 180; +const THREE_QUARTER_CYCLE = 270; +const FULL_CYCLE = 360; + +// constructor for animation Transition +Transition = function(nextAnimation, lastAnimation, lastTransition, playTransitionReachPoses) { + + if (playTransitionReachPoses === undefined) { + playTransitionReachPoses = true; + } + + // record the current state of animation + this.nextAnimation = nextAnimation; + this.lastAnimation = lastAnimation; + this.lastTransition = lastTransition; + + // collect information about the currently playing animation + this.direction = motion.direction; + this.lastDirection = motion.lastDirection; + this.lastFrequencyTimeWheelPos = motion.frequencyTimeWheelPos; + this.lastFrequencyTimeIncrement = motion.averageFrequencyTimeIncrement; + this.lastFrequencyTimeWheelRadius = motion.frequencyTimeWheelRadius; + this.degreesToTurn = 0; // total degrees to turn the ft wheel before the avatar stops (walk only) + this.degreesRemaining = 0; // remaining degrees to turn the ft wheel before the avatar stops (walk only) + this.lastElapsedFTDegrees = motion.elapsedFTDegrees; // degrees elapsed since last transition start + motion.elapsedFTDegrees = 0; // reset ready for the next transition + motion.frequencyTimeWheelPos = 0; // start the next animation's frequency time wheel from zero + + // set parameters for the transition + this.parameters = new TransitionParameters(); + this.liveReachPoses = []; + if (walkAssets && lastAnimation && nextAnimation) { + // overwrite this.parameters with any transition parameters specified for this particular transition + walkAssets.getTransitionParameters(lastAnimation, nextAnimation, this.parameters); + // fire up any reach poses for this transition + if (playTransitionReachPoses) { + for (poseName in this.parameters.reachPoses) { + this.liveReachPoses.push(new ReachPose(this.parameters.reachPoses[poseName])); + } + } + } + this.startTime = new Date().getTime(); // Starting timestamp (seconds) + this.progress = 0; // how far are we through the transition? + this.filteredProgress = 0; + + // coming to a halt whilst walking? if so, will need a clean stopping point defined + if (motion.isComingToHalt) { + + const FULL_CYCLE_THRESHOLD = 320; + const HALF_CYCLE_THRESHOLD = 140; + const CYCLE_COMMIT_THRESHOLD = 5; + + // how many degrees do we need to turn the walk wheel to finish walking with both feet on the ground? + if (this.lastElapsedFTDegrees < CYCLE_COMMIT_THRESHOLD) { + // just stop the walk cycle right here and blend to idle + this.degreesToTurn = 0; + } else if (this.lastElapsedFTDegrees < HALF_CYCLE) { + // we have not taken a complete step yet, so we advance to the second stop angle + this.degreesToTurn = HALF_CYCLE - this.lastFrequencyTimeWheelPos; + } else if (this.lastFrequencyTimeWheelPos > 0 && this.lastFrequencyTimeWheelPos <= HALF_CYCLE_THRESHOLD) { + // complete the step and stop at 180 + this.degreesToTurn = HALF_CYCLE - this.lastFrequencyTimeWheelPos; + } else if (this.lastFrequencyTimeWheelPos > HALF_CYCLE_THRESHOLD && this.lastFrequencyTimeWheelPos <= HALF_CYCLE) { + // complete the step and next then stop at 0 + this.degreesToTurn = HALF_CYCLE - this.lastFrequencyTimeWheelPos + HALF_CYCLE; + } else if (this.lastFrequencyTimeWheelPos > HALF_CYCLE && this.lastFrequencyTimeWheelPos <= FULL_CYCLE_THRESHOLD) { + // complete the step and stop at 0 + this.degreesToTurn = FULL_CYCLE - this.lastFrequencyTimeWheelPos; + } else { + // complete the step and the next then stop at 180 + this.degreesToTurn = FULL_CYCLE - this.lastFrequencyTimeWheelPos + HALF_CYCLE; + } + + // transition length in this case should be directly proportional to the remaining degrees to turn + var MIN_FT_INCREMENT = 5.0; // degrees per frame + var MIN_TRANSITION_DURATION = 0.4; + const TWO_THIRDS = 0.6667; + this.lastFrequencyTimeIncrement *= TWO_THIRDS; // help ease the transition + var lastFrequencyTimeIncrement = this.lastFrequencyTimeIncrement > MIN_FT_INCREMENT ? + this.lastFrequencyTimeIncrement : MIN_FT_INCREMENT; + var timeToFinish = Math.max(motion.deltaTime * this.degreesToTurn / lastFrequencyTimeIncrement, + MIN_TRANSITION_DURATION); + this.parameters.duration = timeToFinish; + this.degreesRemaining = this.degreesToTurn; + } + + // deal with transition recursion (overlapping transitions) + this.recursionDepth = 0; + this.incrementRecursion = function() { + this.recursionDepth += 1; + + // cancel any continued motion + this.degreesToTurn = 0; + + // limit the number of layered / nested transitions + if (this.lastTransition !== nullTransition) { + this.lastTransition.incrementRecursion(); + if (this.lastTransition.recursionDepth > MAX_TRANSITION_RECURSION) { + this.lastTransition = nullTransition; + } + } + }; + if (this.lastTransition !== nullTransition) { + this.lastTransition.incrementRecursion(); + } + + // end of transition initialisation. begin Transition public methods + + // keep up the pace for the frequency time wheel for the last animation + this.advancePreviousFrequencyTimeWheel = function(deltaTime) { + var wheelAdvance = undefined; + + if (this.lastAnimation === avatar.selectedWalkBlend && + this.nextAnimation === avatar.selectedIdle) { + if (this.degreesRemaining <= 0) { + // stop continued motion + wheelAdvance = 0; + if (motion.isComingToHalt) { + if (this.lastFrequencyTimeWheelPos < QUARTER_CYCLE) { + this.lastFrequencyTimeWheelPos = 0; + } else { + this.lastFrequencyTimeWheelPos = HALF_CYCLE; + } + } + } else { + wheelAdvance = this.lastFrequencyTimeIncrement; + var distanceToTravel = avatar.calibration.strideLength * wheelAdvance / HALF_CYCLE; + if (this.degreesRemaining <= 0) { + distanceToTravel = 0; + this.degreesRemaining = 0; + } else { + this.degreesRemaining -= wheelAdvance; + } + } + } else { + wheelAdvance = this.lastFrequencyTimeIncrement; + } + + // advance the ft wheel + this.lastFrequencyTimeWheelPos += wheelAdvance; + if (this.lastFrequencyTimeWheelPos >= FULL_CYCLE) { + this.lastFrequencyTimeWheelPos = this.lastFrequencyTimeWheelPos % FULL_CYCLE; + } + + // advance ft wheel for the nested (previous) Transition + if (this.lastTransition !== nullTransition) { + this.lastTransition.advancePreviousFrequencyTimeWheel(deltaTime); + } + // update the lastElapsedFTDegrees for short stepping + this.lastElapsedFTDegrees += wheelAdvance; + this.degreesTurned += wheelAdvance; + }; + + this.updateProgress = function() { + const MILLISECONDS_CONVERT = 1000; + const ACCURACY_INCREASER = 1000; + var elapasedTime = (new Date().getTime() - this.startTime) / MILLISECONDS_CONVERT; + this.progress = elapasedTime / this.parameters.duration; + this.progress = Math.round(this.progress * ACCURACY_INCREASER) / ACCURACY_INCREASER; + + // updated nested transition/s + if (this.lastTransition !== nullTransition) { + if (this.lastTransition.updateProgress() === TRANSITION_COMPLETE) { + // the previous transition is now complete + this.lastTransition = nullTransition; + } + } + + // update any reachPoses + for (pose in this.liveReachPoses) { + // use independent timing for reachPoses + this.liveReachPoses[pose].progress += (motion.deltaTime / this.liveReachPoses[pose].reachPoseParameters.duration); + if (this.liveReachPoses[pose].progress >= 1) { + // time to kill off this reach pose + this.liveReachPoses.splice(pose, 1); + } + } + + // update transition progress + this.filteredProgress = filter.bezier(this.progress, this.parameters.easingLower, this.parameters.easingUpper); + return this.progress >= 1 ? TRANSITION_COMPLETE : false; + }; + + this.blendTranslations = function(frequencyTimeWheelPos, direction) { + var lastTranslations = {x:0, y:0, z:0}; + var nextTranslations = animationOperations.calculateTranslations(this.nextAnimation, + frequencyTimeWheelPos, + direction); + // are we blending with a previous, still live transition? + if (this.lastTransition !== nullTransition) { + lastTranslations = this.lastTransition.blendTranslations(this.lastFrequencyTimeWheelPos, + this.lastDirection); + } else { + lastTranslations = animationOperations.calculateTranslations(this.lastAnimation, + this.lastFrequencyTimeWheelPos, + this.lastDirection); + } + + // blend last / next translations + nextTranslations = Vec3.multiply(this.filteredProgress, nextTranslations); + lastTranslations = Vec3.multiply((1 - this.filteredProgress), lastTranslations); + nextTranslations = Vec3.sum(nextTranslations, lastTranslations); + + if (this.liveReachPoses.length > 0) { + for (pose in this.liveReachPoses) { + var reachPoseStrength = this.liveReachPoses[pose].currentStrength(); + var poseTranslations = animationOperations.calculateTranslations( + this.liveReachPoses[pose].reachPoseDataFile, + frequencyTimeWheelPos, + direction); + + // can't use Vec3 operations here, as if x,y or z is zero, the reachPose should have no influence at all + if (Math.abs(poseTranslations.x) > 0) { + nextTranslations.x = reachPoseStrength * poseTranslations.x + (1 - reachPoseStrength) * nextTranslations.x; + } + if (Math.abs(poseTranslations.y) > 0) { + nextTranslations.y = reachPoseStrength * poseTranslations.y + (1 - reachPoseStrength) * nextTranslations.y; + } + if (Math.abs(poseTranslations.z) > 0) { + nextTranslations.z = reachPoseStrength * poseTranslations.z + (1 - reachPoseStrength) * nextTranslations.z; + } + } + } + return nextTranslations; + }; + + this.blendRotations = function(jointName, frequencyTimeWheelPos, direction) { + var lastRotations = {x:0, y:0, z:0}; + var nextRotations = animationOperations.calculateRotations(jointName, + this.nextAnimation, + frequencyTimeWheelPos, + direction); + + // are we blending with a previous, still live transition? + if (this.lastTransition !== nullTransition) { + lastRotations = this.lastTransition.blendRotations(jointName, + this.lastFrequencyTimeWheelPos, + this.lastDirection); + } else { + lastRotations = animationOperations.calculateRotations(jointName, + this.lastAnimation, + this.lastFrequencyTimeWheelPos, + this.lastDirection); + } + // blend last / next translations + nextRotations = Vec3.multiply(this.filteredProgress, nextRotations); + lastRotations = Vec3.multiply((1 - this.filteredProgress), lastRotations); + nextRotations = Vec3.sum(nextRotations, lastRotations); + + // are there reachPoses defined for this transition? + if (this.liveReachPoses.length > 0) { + for (pose in this.liveReachPoses) { + var reachPoseStrength = this.liveReachPoses[pose].currentStrength(); + var poseRotations = animationOperations.calculateRotations(jointName, + this.liveReachPoses[pose].reachPoseDataFile, + frequencyTimeWheelPos, + direction); + + // don't use Vec3 operations here, as if x,y or z is zero, the reach pose should have no influence at all + if (Math.abs(poseRotations.x) > 0) { + nextRotations.x = reachPoseStrength * poseRotations.x + (1 - reachPoseStrength) * nextRotations.x; + } + if (Math.abs(poseRotations.y) > 0) { + nextRotations.y = reachPoseStrength * poseRotations.y + (1 - reachPoseStrength) * nextRotations.y; + } + if (Math.abs(poseRotations.z) > 0) { + nextRotations.z = reachPoseStrength * poseRotations.z + (1 - reachPoseStrength) * nextRotations.z; + } + } + } + return nextRotations; + }; +}; // end Transition constructor + +// individual joint modifiers +FrequencyMultipliers = function(joint, direction) { + // gather multipliers + this.pitchFrequencyMultiplier = 1; + this.yawFrequencyMultiplier = 1; + this.rollFrequencyMultiplier = 1; + this.swayFrequencyMultiplier = 1; + this.bobFrequencyMultiplier = 1; + this.thrustFrequencyMultiplier = 1; + + if (joint) { + if (joint.pitchFrequencyMultiplier) { + this.pitchFrequencyMultiplier = joint.pitchFrequencyMultiplier; + } + if (joint.yawFrequencyMultiplier) { + this.yawFrequencyMultiplier = joint.yawFrequencyMultiplier; + } + if (joint.rollFrequencyMultiplier) { + this.rollFrequencyMultiplier = joint.rollFrequencyMultiplier; + } + if (joint.swayFrequencyMultiplier) { + this.swayFrequencyMultiplier = joint.swayFrequencyMultiplier; + } + if (joint.bobFrequencyMultiplier) { + this.bobFrequencyMultiplier = joint.bobFrequencyMultiplier; + } + if (joint.thrustFrequencyMultiplier) { + this.thrustFrequencyMultiplier = joint.thrustFrequencyMultiplier; + } + } }; \ No newline at end of file diff --git a/examples/map.js~ b/examples/map.js~ new file mode 100644 index 0000000000..5a4e0f0f8c --- /dev/null +++ b/examples/map.js~ @@ -0,0 +1,323 @@ +Script.include("entityManager.js"); +Script.include("overlayManager.js"); + + +// Poll for nearby map data + +var entityManager = new EntityManager(); + +// From http://evanw.github.io/lightgl.js/docs/raytracer.html +function raySphereIntersection(origin, ray, center, radius) { + var offset = Vec3.subtract(origin, center); + var a = Vec3.dot(ray, ray); + // var a = ray.dot(ray); + var b = 2 * Vec3.dot(ray, offset); + // var b = 2 * ray.dot(offset); + var c = Vec3.dot(offset, offset) - radius * radius; + // var c = offset.dot(offset) - radius * radius; + var discriminant = b * b - 4 * a * c; + + if (discriminant > 0) { + return true; + } + + return null; +}; + + +Map = function(data) { + var visible = false; + + var ROOT_OFFSET = Vec3.multiply(0.3, Quat.getFront(MyAvatar.orientation)); + var ROOT_POSITION = Vec3.sum(MyAvatar.position, ROOT_OFFSET); + + var ROOT_SCALE = 0.0005; + + // Create object in objectManager + var rootObject = entityManager.addBare(); + var position = ROOT_POSITION; + rootObject.position = ROOT_POSITION; + rootObject.scale = ROOT_SCALE + Vec3.print("Position:", position); + + // Search for all nearby objects that have the userData "mapped" + // TODO Update to use the zone's bounds + var entities = Entities.findEntities(MyAvatar.position, 32000); + var mappedEntities = []; + var minCorner = { + x: 4294967295, + y: 4294967295, + z: 4294967295, + }; + var maxCorner = { + x: -4294967295, + y: -4294967295, + z: -4294967295, + }; + + for (var i = 0; i < entities.length; ++i) { + var entityID = entities[i]; + var properties = Entities.getEntityProperties(entityID); + if (properties.userData == "mapped" || properties.userData == "tracked") { + + print("Found: ", properties.name); + + minCorner.x = Math.min(minCorner.x, properties.position.x - (properties.dimensions.x / 2)); + minCorner.y = Math.min(minCorner.y, properties.position.y - (properties.dimensions.y / 2)); + minCorner.z = Math.min(minCorner.z, properties.position.z - (properties.dimensions.z / 2)); + + maxCorner.x = Math.max(maxCorner.x, properties.position.x - (properties.dimensions.x / 2)); + maxCorner.y = Math.max(maxCorner.y, properties.position.y - (properties.dimensions.y / 2)); + maxCorner.z = Math.max(maxCorner.z, properties.position.z - (properties.dimensions.z / 2)); + + } + // if (properties.userData == "mapped") { + // properties.visible = false; + // var entity = entityManager.add(properties.type, properties); + // mappedEntities.push(entity); + // } else if (properties.userData == "tracked") { + // // TODO implement tracking of objects + // } + } + + var dimensions = { + x: maxCorner.x - minCorner.x, + y: maxCorner.y - minCorner.y, + z: maxCorner.z - minCorner.z, + }; + Vec3.print("dims", dimensions); + + var center = { + x: minCorner.x + (dimensions.x / 2), + y: minCorner.y + (dimensions.y / 2), + z: minCorner.z + (dimensions.z / 2), + }; + Vec3.print("center", center); + + var trackedEntities = []; + var waypointEntities = []; + for (var i = 0; i < entities.length; ++i) { + var entityID = entities[i]; + var properties = Entities.getEntityProperties(entityID); + var mapData = null; + try { + var data = JSON.parse(properties.userData.replace(/(\r\n|\n|\r)/gm,"")); + mapData = data.mapData; + } catch (e) { + print("Caught: ", properties.name); + } + + if (mapData) { + print("Creating copy of", properties.name); + properties.name += " (COPY)"; + properties.userData = ""; + properties.visible = true; + var position = properties.position; + properties.position = Vec3.subtract(properties.position, center); + properties.position = Vec3.multiply(properties.position, ROOT_SCALE); + var extra = { }; + + if (mapData.track) { + extra.trackingEntityID= entityID; + trackedEntities.push(entity); + rootObject.addChild(entity); + } + if (mapData.waypoint) { + print("Waypoint: ", mapData.waypoint.name); + // properties.type = "Model"; + // properties.modelURL = "atp:ca49a13938376b3eb68d7b2b9189afb3f580c07b6950ea9e65b5260787204145.fbx"; + extra.waypoint = mapData.waypoint; + extra.waypoint.position = position; + } + + var entity = entityManager.add(properties.type, properties); + entity.__extra__ = extra; + if (mapData.waypoint) { + waypointEntities.push(entity); + } + mappedEntities.push(entity); + + rootObject.addChild(entity); + + } else { + // print("Not creating copy of", properties.name); + } + } + + var avatarArrowEntity = entityManager.add("Model", { + name: "You Are Here", + modelURL: "atp:ce4f0c4e491e40b73d28f2646da4f676fe9ea364cf5f1bf5615522ef6acfd80e.fbx", + position: Vec3.multiply(Vec3.subtract(MyAvatar.position, center), ROOT_SCALE), + dimensions: { x: 30, y: 100, z: 100 }, + }); + rootObject.addChild(avatarArrowEntity); + + this.isVisible = function() { + return visible; + } + + Controller.mousePressEvent.connect(mousePressEvent); + function mousePressEvent(event) { + // Entities.setZonesArePickable(false); + + var pickRay = Camera.computePickRay(event.x, event.y); + for (var i = 0; i < waypointEntities.length; ++i) { + var entity = waypointEntities[i]; + print("Checkit for hit", entity.__extra__.waypoint.name); + var result = raySphereIntersection(pickRay.origin, pickRay.direction, entity.worldPosition, 0.1);//entity.worldScale); + if (result) { + print("Pressed entity: ", entity.id); + print("Pressed waypoint: ", entity.__extra__.waypoint.name); + print("Teleporting..."); + MyAvatar.position = entity.__extra__.waypoint.position; + break; + } + } + // var result = Entities.findRayIntersection(pickRay, false); + // if (result.intersects) { + // var entity = entityManager.get(result.entityID); + // if (entity) { + // print("Pressed entity: ", entity.id); + // } + // if (entity && entity.__extra__.waypoint) { + // print("Pressed waypoint: ", entity.__extra__.waypoint.name); + // print("Teleporting..."); + // MyAvatar.position = entity.__extra__.waypoint.position; + // } + // } + + // Entities.setZonesArePickable(true); + }; + + var time = 0; + Script.update.connect(function(dt) { + time += dt; + // Update tracked entities + for (var i = 0; i < trackedEntities.length; ++i) { + entity = trackedEntities[i]; + var entityID = entity.__extra__.trackingEntityID; + var properties = Entities.getEntityProperties(entityID); + properties.position = Vec3.subtract(properties.position, center); + properties.position = Vec3.multiply(properties.position, ROOT_SCALE); + entity.position = properties.position; + } + + + var position = Vec3.subtract(MyAvatar.position, center) + position.y += 60 + (Math.sin(time) * 10); + position = Vec3.multiply(position, ROOT_SCALE); + avatarArrowEntity.position = position; + // Vec3.print("Position:", avatarArrowEntity.position); + + // rootObject.position = Vec3.sum(position, { x: 0, y: Math.sin(time) / 30, z: 0 }); + //var ROOT_OFFSET = Vec3.multiply(0.3, Quat.getFront(MyAvatar.orientation)); + //var ROOT_POSITION = Vec3.sum(MyAvatar.position, ROOT_OFFSET); + // position = ROOT_POSITION; + rootObject.position = ROOT_POSITION; + entityManager.update(); + + // Update waypoint highlights + var pickRay = Camera.computePickRay(event.x, event.y); + for (var i = 0; i < waypointEntities.length; ++i) { + var entity = waypointEntities[i]; + print("Checkit for hit", entity.__extra__.waypoint.name); + var result = raySphereIntersection(pickRay.origin, pickRay.direction, entity.worldPosition, 0.1);//entity.worldScale); + if (result) { + print("Pressed entity: ", entity.id); + print("Pressed waypoint: ", entity.__extra__.waypoint.name); + print("Teleporting..."); + MyAvatar.position = entity.__extra__.waypoint.position; + break; + } + } + }); + + function setVisible(newValue) { + if (visible != newValue) { + visible = newValue; + + if (visible) { + } else { + } + } + } + + this.show = function() { + setVisible(true); + } + + this.hide = function() { + setVisible(false); + } +}; + +var map = null; +map = Map(mapData); + +// On press key +Controller.keyPressEvent.connect(function(event) { + if (event.text == "m") { + if (!map) { + map = Map(mapData); + } + + map.show(); + print("MAP!"); + } +}); + + + + + +var mapData = { + config: { + // World dimensions that the minimap maps to + worldDimensions: { + x: 10.0, + y: 10.0, + z: 10.0, + }, + // The center of the map should map to this location in the center of the area + worldCenter: { + x: 5.0, + y: 5.0, + z: 5.0, + }, + // Map dimensions + mapDimensions: { + x: 10.0, + y: 10.0, + z: 10.0, + }, + + // Can this be automated? Tag entities that should be included? Store in UserData? + objects: [ + { + type: "Model", + modelURL: "https://hifi-public.s3.amazonaws.com/ozan/sets/huffman_set/huffman_set.fbx", + }, + ], + }, + waypoints: [ + { + name: "Forest's Edge", + position: { + }, + }, + ], +}; + + +// entityManager = new OverlayManager(); +// entityManager = new EntityManager(); +// +// var rootEntity = entityManager.addBare(); +// +// var time = 0; +// +// +// rootEntity.scale = 0.1; +// Script.include("sfData.js"); +// rootEntity.addChild(entity); +entityManager.update(); diff --git a/examples/pitching.js b/examples/pitching.js index 046113cbc3..b419e8935c 100644 --- a/examples/pitching.js +++ b/examples/pitching.js @@ -142,6 +142,7 @@ function createBaseball(position, velocity, ballScale) { var buildBaseballHitCallback = function(entityID) { var f = function(entityA, entityB, collision) { + print("Got baseball hit callback"); var properties = Entities.getEntityProperties(entityID, ['position', 'velocity']); var line = new InfiniteLine(properties.position, { red: 255, green: 128, blue: 89 }); var lastPosition = properties.position; @@ -154,11 +155,12 @@ var buildBaseballHitCallback = function(entityID) { lastPosition = properties.position; } }, 50); + var speed = Vec3.length(properties.velocity); Entities.editEntity(entityID, { - velocity: Vec3.multiply(3, properties.velocity), + velocity: Vec3.multiply(2, properties.velocity), gravity: { x: 0, - y: -2.8, + y: -9.8, z: 0 } }); diff --git a/examples/toys/flashlight/flashlight.js b/examples/toys/flashlight/flashlight.js index a775f185e3..912d542d6c 100644 --- a/examples/toys/flashlight/flashlight.js +++ b/examples/toys/flashlight/flashlight.js @@ -1,269 +1,269 @@ -// -// flashlight.js -// -// Script Type: Entity -// -// Created by Sam Gateau on 9/9/15. -// Additions by James B. Pollack @imgntn on 9/21/2015 -// Copyright 2015 High Fidelity, Inc. -// -// This is a toy script that can be added to the Flashlight model entity: -// "https://hifi-public.s3.amazonaws.com/models/props/flashlight.fbx" -// that creates a spotlight attached with the flashlight model while the entity is grabbed -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// -/*global MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, Audio, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt */ -(function() { - - Script.include("../../libraries/utils.js"); - - var ON_SOUND_URL = 'http://hifi-public.s3.amazonaws.com/sounds/Switches%20and%20sliders/flashlight_on.wav'; - var OFF_SOUND_URL = 'http://hifi-public.s3.amazonaws.com/sounds/Switches%20and%20sliders/flashlight_off.wav'; - - //we are creating lights that we don't want to get stranded so lets make sure that we can get rid of them - var startTime = Date.now(); - //if you're going to be using this in a dungeon or something and holding it for a long time, increase this lifetime value. - var LIFETIME = 25; - var MSEC_PER_SEC = 1000.0; - - // this is the "constructor" for the entity as a JS object we don't do much here, but we do want to remember - // our this object, so we can access it in cases where we're called without a this (like in the case of various global signals) - function Flashlight() { - return; - } - - //if the trigger value goes below this while held, the flashlight will turn off. if it goes above, it will - var DISABLE_LIGHT_THRESHOLD = 0.7; - - // These constants define the Spotlight position and orientation relative to the model - var MODEL_LIGHT_POSITION = { - x: 0, - y: -0.3, - z: 0 - }; - var MODEL_LIGHT_ROTATION = Quat.angleAxis(-90, { - x: 1, - y: 0, - z: 0 - }); - - var GLOW_LIGHT_POSITION = { - x: 0, - y: -0.1, - z: 0 - }; - - // Evaluate the world light entity positions and orientations from the model ones - function evalLightWorldTransform(modelPos, modelRot) { - - return { - p: Vec3.sum(modelPos, Vec3.multiplyQbyV(modelRot, MODEL_LIGHT_POSITION)), - q: Quat.multiply(modelRot, MODEL_LIGHT_ROTATION) - }; - } - - function glowLightWorldTransform(modelPos, modelRot) { - return { - p: Vec3.sum(modelPos, Vec3.multiplyQbyV(modelRot, GLOW_LIGHT_POSITION)), - q: Quat.multiply(modelRot, MODEL_LIGHT_ROTATION) - }; - } - - Flashlight.prototype = { - lightOn: false, - hand: null, - whichHand: null, - hasSpotlight: false, - spotlight: null, - setRightHand: function() { - this.hand = 'RIGHT'; - }, - - setLeftHand: function() { - this.hand = 'LEFT'; - }, - - startNearGrab: function() { - if (!this.hasSpotlight) { - - //this light casts the beam - this.spotlight = Entities.addEntity({ - type: "Light", - isSpotlight: true, - dimensions: { - x: 2, - y: 2, - z: 20 - }, - color: { - red: 255, - green: 255, - blue: 255 - }, - intensity: 2, - exponent: 0.3, - cutoff: 20, - lifetime: LIFETIME - }); - - //this light creates the effect of a bulb at the end of the flashlight - this.glowLight = Entities.addEntity({ - type: "Light", - dimensions: { - x: 0.25, - y: 0.25, - z: 0.25 - }, - isSpotlight: false, - color: { - red: 255, - green: 255, - blue: 255 - }, - exponent: 0, - cutoff: 90, // in degrees - lifetime: LIFETIME - }); - - this.hasSpotlight = true; - - } - - }, - - setWhichHand: function() { - this.whichHand = this.hand; - }, - - continueNearGrab: function() { - if (this.whichHand === null) { - //only set the active hand once -- if we always read the current hand, our 'holding' hand will get overwritten - this.setWhichHand(); - } else { - this.updateLightPositions(); - this.changeLightWithTriggerPressure(this.whichHand); - } - }, - - releaseGrab: function() { - //delete the lights and reset state - if (this.hasSpotlight) { - Entities.deleteEntity(this.spotlight); - Entities.deleteEntity(this.glowLight); - this.hasSpotlight = false; - this.glowLight = null; - this.spotlight = null; - this.whichHand = null; - this.lightOn = false; - } - }, - - updateLightPositions: function() { - var modelProperties = Entities.getEntityProperties(this.entityID, ['position', 'rotation']); - - //move the two lights along the vectors we set above - var lightTransform = evalLightWorldTransform(modelProperties.position, modelProperties.rotation); - var glowLightTransform = glowLightWorldTransform(modelProperties.position, modelProperties.rotation); - - //move them with the entity model - Entities.editEntity(this.spotlight, { - position: lightTransform.p, - rotation: lightTransform.q, - lifetime: (Date.now() - startTime) / MSEC_PER_SEC + LIFETIME - }); - - Entities.editEntity(this.glowLight, { - position: glowLightTransform.p, - rotation: glowLightTransform.q, - lifetime: (Date.now() - startTime) / MSEC_PER_SEC + LIFETIME - }); - - }, - - changeLightWithTriggerPressure: function(flashLightHand) { - var handClickString = flashLightHand + "_HAND_CLICK"; - - var handClick = Controller.findAction(handClickString); - - this.triggerValue = Controller.getActionValue(handClick); - - if (this.triggerValue < DISABLE_LIGHT_THRESHOLD && this.lightOn === true) { - this.turnLightOff(); - } else if (this.triggerValue >= DISABLE_LIGHT_THRESHOLD && this.lightOn === false) { - this.turnLightOn(); - } - return; - }, - - turnLightOff: function() { - this.playSoundAtCurrentPosition(false); - Entities.editEntity(this.spotlight, { - intensity: 0 - }); - Entities.editEntity(this.glowLight, { - intensity: 0 - }); - this.lightOn = false; - }, - - turnLightOn: function() { - this.playSoundAtCurrentPosition(true); - - Entities.editEntity(this.glowLight, { - intensity: 2 - }); - Entities.editEntity(this.spotlight, { - intensity: 2 - }); - this.lightOn = true; - }, - - playSoundAtCurrentPosition: function(playOnSound) { - var position = Entities.getEntityProperties(this.entityID, "position").position; - - var audioProperties = { - volume: 0.25, - position: position - }; - - if (playOnSound) { - Audio.playSound(this.ON_SOUND, audioProperties); - } else { - Audio.playSound(this.OFF_SOUND, audioProperties); - } - }, - - preload: function(entityID) { - - // preload() will be called when the entity has become visible (or known) to the interface - // it gives us a chance to set our local JavaScript object up. In this case it means: - // * remembering our entityID, so we can access it in cases where we're called without an entityID - // * preloading sounds - this.entityID = entityID; - this.ON_SOUND = SoundCache.getSound(ON_SOUND_URL); - this.OFF_SOUND = SoundCache.getSound(OFF_SOUND_URL); - - }, - - unload: function() { - // unload() will be called when our entity is no longer available. It may be because we were deleted, - // or because we've left the domain or quit the application. - if (this.hasSpotlight) { - Entities.deleteEntity(this.spotlight); - Entities.deleteEntity(this.glowLight); - this.hasSpotlight = false; - this.glowLight = null; - this.spotlight = null; - this.whichHand = null; - this.lightOn = false; - } - - }, - - }; - - // entity scripts always need to return a newly constructed object of our type - return new Flashlight(); +// +// flashlight.js +// +// Script Type: Entity +// +// Created by Sam Gateau on 9/9/15. +// Additions by James B. Pollack @imgntn on 9/21/2015 +// Copyright 2015 High Fidelity, Inc. +// +// This is a toy script that can be added to the Flashlight model entity: +// "https://hifi-public.s3.amazonaws.com/models/props/flashlight.fbx" +// that creates a spotlight attached with the flashlight model while the entity is grabbed +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// +/*global MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, Audio, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt */ +(function() { + + Script.include("../../libraries/utils.js"); + + var ON_SOUND_URL = 'http://hifi-public.s3.amazonaws.com/sounds/Switches%20and%20sliders/flashlight_on.wav'; + var OFF_SOUND_URL = 'http://hifi-public.s3.amazonaws.com/sounds/Switches%20and%20sliders/flashlight_off.wav'; + + //we are creating lights that we don't want to get stranded so lets make sure that we can get rid of them + var startTime = Date.now(); + //if you're going to be using this in a dungeon or something and holding it for a long time, increase this lifetime value. + var LIFETIME = 25; + var MSEC_PER_SEC = 1000.0; + + // this is the "constructor" for the entity as a JS object we don't do much here, but we do want to remember + // our this object, so we can access it in cases where we're called without a this (like in the case of various global signals) + function Flashlight() { + return; + } + + //if the trigger value goes below this while held, the flashlight will turn off. if it goes above, it will + var DISABLE_LIGHT_THRESHOLD = 0.7; + + // These constants define the Spotlight position and orientation relative to the model + var MODEL_LIGHT_POSITION = { + x: 0, + y: -0.3, + z: 0 + }; + var MODEL_LIGHT_ROTATION = Quat.angleAxis(-90, { + x: 1, + y: 0, + z: 0 + }); + + var GLOW_LIGHT_POSITION = { + x: 0, + y: -0.1, + z: 0 + }; + + // Evaluate the world light entity positions and orientations from the model ones + function evalLightWorldTransform(modelPos, modelRot) { + + return { + p: Vec3.sum(modelPos, Vec3.multiplyQbyV(modelRot, MODEL_LIGHT_POSITION)), + q: Quat.multiply(modelRot, MODEL_LIGHT_ROTATION) + }; + } + + function glowLightWorldTransform(modelPos, modelRot) { + return { + p: Vec3.sum(modelPos, Vec3.multiplyQbyV(modelRot, GLOW_LIGHT_POSITION)), + q: Quat.multiply(modelRot, MODEL_LIGHT_ROTATION) + }; + } + + Flashlight.prototype = { + lightOn: false, + hand: null, + whichHand: null, + hasSpotlight: false, + spotlight: null, + setRightHand: function() { + this.hand = 'RIGHT'; + }, + + setLeftHand: function() { + this.hand = 'LEFT'; + }, + + startNearGrab: function() { + if (!this.hasSpotlight) { + + //this light casts the beam + this.spotlight = Entities.addEntity({ + type: "Light", + isSpotlight: true, + dimensions: { + x: 2, + y: 2, + z: 20 + }, + color: { + red: 255, + green: 255, + blue: 255 + }, + intensity: 2, + exponent: 0.3, + cutoff: 20, + lifetime: LIFETIME + }); + + //this light creates the effect of a bulb at the end of the flashlight + this.glowLight = Entities.addEntity({ + type: "Light", + dimensions: { + x: 0.25, + y: 0.25, + z: 0.25 + }, + isSpotlight: false, + color: { + red: 255, + green: 255, + blue: 255 + }, + exponent: 0, + cutoff: 90, // in degrees + lifetime: LIFETIME + }); + + this.hasSpotlight = true; + + } + + }, + + setWhichHand: function() { + this.whichHand = this.hand; + }, + + continueNearGrab: function() { + if (this.whichHand === null) { + //only set the active hand once -- if we always read the current hand, our 'holding' hand will get overwritten + this.setWhichHand(); + } else { + this.updateLightPositions(); + this.changeLightWithTriggerPressure(this.whichHand); + } + }, + + releaseGrab: function() { + //delete the lights and reset state + if (this.hasSpotlight) { + Entities.deleteEntity(this.spotlight); + Entities.deleteEntity(this.glowLight); + this.hasSpotlight = false; + this.glowLight = null; + this.spotlight = null; + this.whichHand = null; + this.lightOn = false; + } + }, + + updateLightPositions: function() { + var modelProperties = Entities.getEntityProperties(this.entityID, ['position', 'rotation']); + + //move the two lights along the vectors we set above + var lightTransform = evalLightWorldTransform(modelProperties.position, modelProperties.rotation); + var glowLightTransform = glowLightWorldTransform(modelProperties.position, modelProperties.rotation); + + //move them with the entity model + Entities.editEntity(this.spotlight, { + position: lightTransform.p, + rotation: lightTransform.q, + lifetime: (Date.now() - startTime) / MSEC_PER_SEC + LIFETIME + }); + + Entities.editEntity(this.glowLight, { + position: glowLightTransform.p, + rotation: glowLightTransform.q, + lifetime: (Date.now() - startTime) / MSEC_PER_SEC + LIFETIME + }); + + }, + + changeLightWithTriggerPressure: function(flashLightHand) { + var handClickString = flashLightHand + "_HAND_CLICK"; + + var handClick = Controller.findAction(handClickString); + + this.triggerValue = Controller.getActionValue(handClick); + + if (this.triggerValue < DISABLE_LIGHT_THRESHOLD && this.lightOn === true) { + this.turnLightOff(); + } else if (this.triggerValue >= DISABLE_LIGHT_THRESHOLD && this.lightOn === false) { + this.turnLightOn(); + } + return; + }, + + turnLightOff: function() { + this.playSoundAtCurrentPosition(false); + Entities.editEntity(this.spotlight, { + intensity: 0 + }); + Entities.editEntity(this.glowLight, { + intensity: 0 + }); + this.lightOn = false; + }, + + turnLightOn: function() { + this.playSoundAtCurrentPosition(true); + + Entities.editEntity(this.glowLight, { + intensity: 2 + }); + Entities.editEntity(this.spotlight, { + intensity: 2 + }); + this.lightOn = true; + }, + + playSoundAtCurrentPosition: function(playOnSound) { + var position = Entities.getEntityProperties(this.entityID, "position").position; + + var audioProperties = { + volume: 0.25, + position: position + }; + + if (playOnSound) { + Audio.playSound(this.ON_SOUND, audioProperties); + } else { + Audio.playSound(this.OFF_SOUND, audioProperties); + } + }, + + preload: function(entityID) { + + // preload() will be called when the entity has become visible (or known) to the interface + // it gives us a chance to set our local JavaScript object up. In this case it means: + // * remembering our entityID, so we can access it in cases where we're called without an entityID + // * preloading sounds + this.entityID = entityID; + this.ON_SOUND = SoundCache.getSound(ON_SOUND_URL); + this.OFF_SOUND = SoundCache.getSound(OFF_SOUND_URL); + + }, + + unload: function() { + // unload() will be called when our entity is no longer available. It may be because we were deleted, + // or because we've left the domain or quit the application. + if (this.hasSpotlight) { + Entities.deleteEntity(this.spotlight); + Entities.deleteEntity(this.glowLight); + this.hasSpotlight = false; + this.glowLight = null; + this.spotlight = null; + this.whichHand = null; + this.lightOn = false; + } + + }, + + }; + + // entity scripts always need to return a newly constructed object of our type + return new Flashlight(); }); \ No newline at end of file diff --git a/examples/walk.js b/examples/walk.js index 0b5bcab65a..63b5599cc2 100644 --- a/examples/walk.js +++ b/examples/walk.js @@ -1,454 +1,454 @@ -// -// walk.js -// version 1.25 -// -// Created by David Wooldridge, June 2015 -// Copyright © 2014 - 2015 High Fidelity, Inc. -// -// Animates an avatar using procedural animation techniques. -// -// Editing tools for animation data files available here: https://github.com/DaveDubUK/walkTools -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -// animations, reach poses, reach pose parameters, transitions, transition parameters, sounds, image/s and reference files -const HIFI_PUBLIC_BUCKET = "https://hifi-public.s3.amazonaws.com/"; -var pathToAssets = HIFI_PUBLIC_BUCKET + "procedural-animator/assets/"; - -Script.include([ - "./libraries/walkConstants.js", - "./libraries/walkFilters.js", - "./libraries/walkApi.js", - pathToAssets + "walkAssets.js" -]); - -// construct Avatar, Motion and (null) Transition -var avatar = new Avatar(); -var motion = new Motion(); -var nullTransition = new Transition(); -motion.currentTransition = nullTransition; - -// create settings (gets initial values from avatar) -Script.include("./libraries/walkSettings.js"); - -// Main loop -Script.update.connect(function(deltaTime) { - - if (motion.isLive) { - - // assess current locomotion state - motion.assess(deltaTime); - - // decide which animation should be playing - selectAnimation(); - - // advance the animation cycle/s by the correct amount/s - advanceAnimations(); - - // update the progress of any live transitions - updateTransitions(); - - // apply translation and rotations - renderMotion(); - - // save this frame's parameters - motion.saveHistory(); - } -}); - -// helper function for selectAnimation() -function setTransition(nextAnimation, playTransitionReachPoses) { - var lastTransition = motion.currentTransition; - var lastAnimation = avatar.currentAnimation; - - // if already transitioning from a blended walk need to maintain the previous walk's direction - if (lastAnimation.lastDirection) { - switch(lastAnimation.lastDirection) { - - case FORWARDS: - lastAnimation = avatar.selectedWalk; - break; - - case BACKWARDS: - lastAnimation = avatar.selectedWalkBackwards; - break; - - case LEFT: - lastAnimation = avatar.selectedSideStepLeft; - break; - - case RIGHT: - lastAnimation = avatar.selectedSideStepRight; - break; - } - } - - motion.currentTransition = new Transition(nextAnimation, lastAnimation, lastTransition, playTransitionReachPoses); - avatar.currentAnimation = nextAnimation; - - // reset default first footstep - if (nextAnimation === avatar.selectedWalkBlend && lastTransition === nullTransition) { - avatar.nextStep = RIGHT; - } -} - -// fly animation blending: smoothing / damping filters -const FLY_BLEND_DAMPING = 50; -var flyUpFilter = filter.createAveragingFilter(FLY_BLEND_DAMPING); -var flyDownFilter = filter.createAveragingFilter(FLY_BLEND_DAMPING); -var flyForwardFilter = filter.createAveragingFilter(FLY_BLEND_DAMPING); -var flyBackwardFilter = filter.createAveragingFilter(FLY_BLEND_DAMPING); - -// select / blend the appropriate animation for the current state of motion -function selectAnimation() { - var playTransitionReachPoses = true; - - // select appropriate animation. create transitions where appropriate - switch (motion.nextState) { - case STATIC: { - if (avatar.distanceFromSurface < ON_SURFACE_THRESHOLD && - avatar.currentAnimation !== avatar.selectedIdle) { - setTransition(avatar.selectedIdle, playTransitionReachPoses); - } else if (!(avatar.distanceFromSurface < ON_SURFACE_THRESHOLD) && - avatar.currentAnimation !== avatar.selectedHover) { - setTransition(avatar.selectedHover, playTransitionReachPoses); - } - motion.state = STATIC; - avatar.selectedWalkBlend.lastDirection = NONE; - break; - } - - case SURFACE_MOTION: { - // walk transition reach poses are currently only specified for starting to walk forwards - playTransitionReachPoses = (motion.direction === FORWARDS); - var isAlreadyWalking = (avatar.currentAnimation === avatar.selectedWalkBlend); - - switch (motion.direction) { - case FORWARDS: - if (avatar.selectedWalkBlend.lastDirection !== FORWARDS) { - animationOperations.deepCopy(avatar.selectedWalk, avatar.selectedWalkBlend); - avatar.calibration.strideLength = avatar.selectedWalk.calibration.strideLength; - } - avatar.selectedWalkBlend.lastDirection = FORWARDS; - break; - - case BACKWARDS: - if (avatar.selectedWalkBlend.lastDirection !== BACKWARDS) { - animationOperations.deepCopy(avatar.selectedWalkBackwards, avatar.selectedWalkBlend); - avatar.calibration.strideLength = avatar.selectedWalkBackwards.calibration.strideLength; - } - avatar.selectedWalkBlend.lastDirection = BACKWARDS; - break; - - case LEFT: - animationOperations.deepCopy(avatar.selectedSideStepLeft, avatar.selectedWalkBlend); - avatar.selectedWalkBlend.lastDirection = LEFT; - avatar.calibration.strideLength = avatar.selectedSideStepLeft.calibration.strideLength; - break - - case RIGHT: - animationOperations.deepCopy(avatar.selectedSideStepRight, avatar.selectedWalkBlend); - avatar.selectedWalkBlend.lastDirection = RIGHT; - avatar.calibration.strideLength = avatar.selectedSideStepRight.calibration.strideLength; - break; - - default: - // condition occurs when the avi goes through the floor due to collision hull errors - animationOperations.deepCopy(avatar.selectedWalk, avatar.selectedWalkBlend); - avatar.selectedWalkBlend.lastDirection = FORWARDS; - avatar.calibration.strideLength = avatar.selectedWalk.calibration.strideLength; - break; - } - - if (!isAlreadyWalking && !motion.isComingToHalt) { - setTransition(avatar.selectedWalkBlend, playTransitionReachPoses); - } - motion.state = SURFACE_MOTION; - break; - } - - case AIR_MOTION: { - // blend the up, down, forward and backward flying animations relative to motion speed and direction - animationOperations.zeroAnimation(avatar.selectedFlyBlend); - - // calculate influences based on velocity and direction - var velocityMagnitude = Vec3.length(motion.velocity); - var verticalProportion = motion.velocity.y / velocityMagnitude; - var thrustProportion = motion.velocity.z / velocityMagnitude / 2; - - // directional components - var upComponent = motion.velocity.y > 0 ? verticalProportion : 0; - var downComponent = motion.velocity.y < 0 ? -verticalProportion : 0; - var forwardComponent = motion.velocity.z < 0 ? -thrustProportion : 0; - var backwardComponent = motion.velocity.z > 0 ? thrustProportion : 0; - - // smooth / damp directional components to add visual 'weight' - upComponent = flyUpFilter.process(upComponent); - downComponent = flyDownFilter.process(downComponent); - forwardComponent = flyForwardFilter.process(forwardComponent); - backwardComponent = flyBackwardFilter.process(backwardComponent); - - // normalise directional components - var normaliser = upComponent + downComponent + forwardComponent + backwardComponent; - upComponent = upComponent / normaliser; - downComponent = downComponent / normaliser; - forwardComponent = forwardComponent / normaliser; - backwardComponent = backwardComponent / normaliser; - - // blend animations proportionally - if (upComponent > 0) { - animationOperations.blendAnimation(avatar.selectedFlyUp, - avatar.selectedFlyBlend, - upComponent); - } - if (downComponent > 0) { - animationOperations.blendAnimation(avatar.selectedFlyDown, - avatar.selectedFlyBlend, - downComponent); - } - if (forwardComponent > 0) { - animationOperations.blendAnimation(avatar.selectedFly, - avatar.selectedFlyBlend, - Math.abs(forwardComponent)); - } - if (backwardComponent > 0) { - animationOperations.blendAnimation(avatar.selectedFlyBackwards, - avatar.selectedFlyBlend, - Math.abs(backwardComponent)); - } - - if (avatar.currentAnimation !== avatar.selectedFlyBlend) { - setTransition(avatar.selectedFlyBlend, playTransitionReachPoses); - } - motion.state = AIR_MOTION; - avatar.selectedWalkBlend.lastDirection = NONE; - break; - } - } // end switch next state of motion -} - -// determine the length of stride. advance the frequency time wheels. advance frequency time wheels for any live transitions -function advanceAnimations() { - var wheelAdvance = 0; - - // turn the frequency time wheel - if (avatar.currentAnimation === avatar.selectedWalkBlend) { - // Using technique described here: http://www.gdcvault.com/play/1020583/Animation-Bootcamp-An-Indie-Approach - // wrap the stride length around a 'surveyor's wheel' twice and calculate the angular speed at the given (linear) speed - // omega = v / r , where r = circumference / 2 PI and circumference = 2 * stride length - var speed = Vec3.length(motion.velocity); - motion.frequencyTimeWheelRadius = avatar.calibration.strideLength / Math.PI; - var ftWheelAngularVelocity = speed / motion.frequencyTimeWheelRadius; - // calculate the degrees turned (at this angular speed) since last frame - wheelAdvance = filter.radToDeg(motion.deltaTime * ftWheelAngularVelocity); - } else { - // turn the frequency time wheel by the amount specified for this animation - wheelAdvance = filter.radToDeg(avatar.currentAnimation.calibration.frequency * motion.deltaTime); - } - - if (motion.currentTransition !== nullTransition) { - // the last animation is still playing so we turn it's frequency time wheel to maintain the animation - if (motion.currentTransition.lastAnimation === motion.selectedWalkBlend) { - // if at a stop angle (i.e. feet now under the avi) hold the wheel position for remainder of transition - var tolerance = motion.currentTransition.lastFrequencyTimeIncrement + 0.1; - if ((motion.currentTransition.lastFrequencyTimeWheelPos > - (motion.currentTransition.stopAngle - tolerance)) && - (motion.currentTransition.lastFrequencyTimeWheelPos < - (motion.currentTransition.stopAngle + tolerance))) { - motion.currentTransition.lastFrequencyTimeIncrement = 0; - } - } - motion.currentTransition.advancePreviousFrequencyTimeWheel(motion.deltaTime); - } - - // avoid unnaturally fast walking when landing at speed - simulates skimming / skidding - if (Math.abs(wheelAdvance) > MAX_FT_WHEEL_INCREMENT) { - wheelAdvance = 0; - } - - // advance the walk wheel the appropriate amount - motion.advanceFrequencyTimeWheel(wheelAdvance); - - // walking? then see if it's a good time to measure the stride length (needs to be at least 97% of max walking speed) - const ALMOST_ONE = 0.97; - if (avatar.currentAnimation === avatar.selectedWalkBlend && - (Vec3.length(motion.velocity) / MAX_WALK_SPEED > ALMOST_ONE)) { - - var strideMaxAt = avatar.currentAnimation.calibration.strideMaxAt; - const TOLERANCE = 1.0; - - if (motion.frequencyTimeWheelPos < (strideMaxAt + TOLERANCE) && - motion.frequencyTimeWheelPos > (strideMaxAt - TOLERANCE) && - motion.currentTransition === nullTransition) { - // measure and save stride length - var footRPos = MyAvatar.getJointPosition("RightFoot"); - var footLPos = MyAvatar.getJointPosition("LeftFoot"); - avatar.calibration.strideLength = Vec3.distance(footRPos, footLPos); - avatar.currentAnimation.calibration.strideLength = avatar.calibration.strideLength; - } else { - // use the previously saved value for stride length - avatar.calibration.strideLength = avatar.currentAnimation.calibration.strideLength; - } - } // end get walk stride length -} - -// initialise a new transition. update progress of a live transition -function updateTransitions() { - - if (motion.currentTransition !== nullTransition) { - // is this a new transition? - if (motion.currentTransition.progress === 0) { - // do we have overlapping transitions? - if (motion.currentTransition.lastTransition !== nullTransition) { - // is the last animation for the nested transition the same as the new animation? - if (motion.currentTransition.lastTransition.lastAnimation === avatar.currentAnimation) { - // then sync the nested transition's frequency time wheel for a smooth animation blend - motion.frequencyTimeWheelPos = motion.currentTransition.lastTransition.lastFrequencyTimeWheelPos; - } - } - } - if (motion.currentTransition.updateProgress() === TRANSITION_COMPLETE) { - motion.currentTransition = nullTransition; - } - } -} - -// helper function for renderMotion(). calculate the amount to lean forwards (or backwards) based on the avi's velocity -var leanPitchSmoothingFilter = filter.createButterworthFilter(); -function getLeanPitch() { - var leanProgress = 0; - - if (motion.direction === DOWN || - motion.direction === FORWARDS || - motion.direction === BACKWARDS) { - leanProgress = -motion.velocity.z / TOP_SPEED; - } - // use filters to shape the walking acceleration response - leanProgress = leanPitchSmoothingFilter.process(leanProgress); - return PITCH_MAX * leanProgress; -} - -// helper function for renderMotion(). calculate the angle at which to bank into corners whilst turning -var leanRollSmoothingFilter = filter.createButterworthFilter(); -function getLeanRoll() { - var leanRollProgress = 0; - var linearContribution = 0; - const LOG_SCALER = 8; - - if (Vec3.length(motion.velocity) > 0) { - linearContribution = (Math.log(Vec3.length(motion.velocity) / TOP_SPEED) + LOG_SCALER) / LOG_SCALER; - } - var angularContribution = Math.abs(motion.yawDelta) / DELTA_YAW_MAX; - leanRollProgress = linearContribution; - leanRollProgress *= angularContribution; - // shape the response curve - leanRollProgress = filter.bezier(leanRollProgress, {x: 1, y: 0}, {x: 1, y: 0}); - // which way to lean? - var turnSign = (motion.yawDelta >= 0) ? 1 : -1; - - if (motion.direction === BACKWARDS || - motion.direction === LEFT) { - turnSign *= -1; - } - // filter progress - leanRollProgress = leanRollSmoothingFilter.process(turnSign * leanRollProgress); - return ROLL_MAX * leanRollProgress; -} - -// animate the avatar using sine waves, geometric waveforms and harmonic generators -function renderMotion() { - // leaning in response to speed and acceleration - var leanPitch = motion.state === STATIC ? 0 : getLeanPitch(); - var leanRoll = motion.state === STATIC ? 0 : getLeanRoll(); - var lastDirection = motion.lastDirection; - // hips translations from currently playing animations - var hipsTranslations = {x:0, y:0, z:0}; - - if (motion.currentTransition !== nullTransition) { - // maintain previous direction when transitioning from a walk - if (motion.currentTransition.lastAnimation === avatar.selectedWalkBlend) { - motion.lastDirection = motion.currentTransition.lastDirection; - } - hipsTranslations = motion.currentTransition.blendTranslations(motion.frequencyTimeWheelPos, - motion.lastDirection); - } else { - hipsTranslations = animationOperations.calculateTranslations(avatar.currentAnimation, - motion.frequencyTimeWheelPos, - motion.direction); - } - // factor any leaning into the hips offset - hipsTranslations.z += avatar.calibration.hipsToFeet * Math.sin(filter.degToRad(leanPitch)); - hipsTranslations.x += avatar.calibration.hipsToFeet * Math.sin(filter.degToRad(leanRoll)); - - // ensure skeleton offsets are within the 1m limit - hipsTranslations.x = hipsTranslations.x > 1 ? 1 : hipsTranslations.x; - hipsTranslations.x = hipsTranslations.x < -1 ? -1 : hipsTranslations.x; - hipsTranslations.y = hipsTranslations.y > 1 ? 1 : hipsTranslations.y; - hipsTranslations.y = hipsTranslations.y < -1 ? -1 : hipsTranslations.y; - hipsTranslations.z = hipsTranslations.z > 1 ? 1 : hipsTranslations.z; - hipsTranslations.z = hipsTranslations.z < -1 ? -1 : hipsTranslations.z; - // apply translations - MyAvatar.setSkeletonOffset(hipsTranslations); - - // play footfall sound? - var producingFootstepSounds = (avatar.currentAnimation === avatar.selectedWalkBlend) && avatar.makesFootStepSounds; - - if (motion.currentTransition !== nullTransition && avatar.makesFootStepSounds) { - if (motion.currentTransition.nextAnimation === avatar.selectedWalkBlend || - motion.currentTransition.lastAnimation === avatar.selectedWalkBlend) { - producingFootstepSounds = true; - } - } - if (producingFootstepSounds) { - const QUARTER_CYCLE = 90; - const THREE_QUARTER_CYCLE = 270; - var ftWheelPosition = motion.frequencyTimeWheelPos; - - if (motion.currentTransition !== nullTransition && - motion.currentTransition.lastAnimation === avatar.selectedWalkBlend) { - ftWheelPosition = motion.currentTransition.lastFrequencyTimeWheelPos; - } - if (avatar.nextStep === LEFT && ftWheelPosition > THREE_QUARTER_CYCLE) { - avatar.makeFootStepSound(); - } else if (avatar.nextStep === RIGHT && (ftWheelPosition < THREE_QUARTER_CYCLE && ftWheelPosition > QUARTER_CYCLE)) { - avatar.makeFootStepSound(); - } - } - - // apply joint rotations - for (jointName in avatar.currentAnimation.joints) { - var joint = walkAssets.animationReference.joints[jointName]; - var jointRotations = undefined; - - // ignore arms / head rotations if options are selected in the settings - if (avatar.armsFree && (joint.IKChain === "LeftArm" || joint.IKChain === "RightArm")) { - continue; - } - if (avatar.headFree && joint.IKChain === "Head") { - continue; - } - - // if there's a live transition, blend the rotations with the last animation's rotations - if (motion.currentTransition !== nullTransition) { - jointRotations = motion.currentTransition.blendRotations(jointName, - motion.frequencyTimeWheelPos, - motion.lastDirection); - } else { - jointRotations = animationOperations.calculateRotations(jointName, - avatar.currentAnimation, - motion.frequencyTimeWheelPos, - motion.direction); - } - - // apply angular velocity and speed induced leaning - if (jointName === "Hips") { - jointRotations.x += leanPitch; - jointRotations.z += leanRoll; - } - - // apply rotations - MyAvatar.setJointRotation(jointName, Quat.fromVec3Degrees(jointRotations)); - } +// +// walk.js +// version 1.25 +// +// Created by David Wooldridge, June 2015 +// Copyright © 2014 - 2015 High Fidelity, Inc. +// +// Animates an avatar using procedural animation techniques. +// +// Editing tools for animation data files available here: https://github.com/DaveDubUK/walkTools +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +// animations, reach poses, reach pose parameters, transitions, transition parameters, sounds, image/s and reference files +const HIFI_PUBLIC_BUCKET = "https://hifi-public.s3.amazonaws.com/"; +var pathToAssets = HIFI_PUBLIC_BUCKET + "procedural-animator/assets/"; + +Script.include([ + "./libraries/walkConstants.js", + "./libraries/walkFilters.js", + "./libraries/walkApi.js", + pathToAssets + "walkAssets.js" +]); + +// construct Avatar, Motion and (null) Transition +var avatar = new Avatar(); +var motion = new Motion(); +var nullTransition = new Transition(); +motion.currentTransition = nullTransition; + +// create settings (gets initial values from avatar) +Script.include("./libraries/walkSettings.js"); + +// Main loop +Script.update.connect(function(deltaTime) { + + if (motion.isLive) { + + // assess current locomotion state + motion.assess(deltaTime); + + // decide which animation should be playing + selectAnimation(); + + // advance the animation cycle/s by the correct amount/s + advanceAnimations(); + + // update the progress of any live transitions + updateTransitions(); + + // apply translation and rotations + renderMotion(); + + // save this frame's parameters + motion.saveHistory(); + } +}); + +// helper function for selectAnimation() +function setTransition(nextAnimation, playTransitionReachPoses) { + var lastTransition = motion.currentTransition; + var lastAnimation = avatar.currentAnimation; + + // if already transitioning from a blended walk need to maintain the previous walk's direction + if (lastAnimation.lastDirection) { + switch(lastAnimation.lastDirection) { + + case FORWARDS: + lastAnimation = avatar.selectedWalk; + break; + + case BACKWARDS: + lastAnimation = avatar.selectedWalkBackwards; + break; + + case LEFT: + lastAnimation = avatar.selectedSideStepLeft; + break; + + case RIGHT: + lastAnimation = avatar.selectedSideStepRight; + break; + } + } + + motion.currentTransition = new Transition(nextAnimation, lastAnimation, lastTransition, playTransitionReachPoses); + avatar.currentAnimation = nextAnimation; + + // reset default first footstep + if (nextAnimation === avatar.selectedWalkBlend && lastTransition === nullTransition) { + avatar.nextStep = RIGHT; + } +} + +// fly animation blending: smoothing / damping filters +const FLY_BLEND_DAMPING = 50; +var flyUpFilter = filter.createAveragingFilter(FLY_BLEND_DAMPING); +var flyDownFilter = filter.createAveragingFilter(FLY_BLEND_DAMPING); +var flyForwardFilter = filter.createAveragingFilter(FLY_BLEND_DAMPING); +var flyBackwardFilter = filter.createAveragingFilter(FLY_BLEND_DAMPING); + +// select / blend the appropriate animation for the current state of motion +function selectAnimation() { + var playTransitionReachPoses = true; + + // select appropriate animation. create transitions where appropriate + switch (motion.nextState) { + case STATIC: { + if (avatar.distanceFromSurface < ON_SURFACE_THRESHOLD && + avatar.currentAnimation !== avatar.selectedIdle) { + setTransition(avatar.selectedIdle, playTransitionReachPoses); + } else if (!(avatar.distanceFromSurface < ON_SURFACE_THRESHOLD) && + avatar.currentAnimation !== avatar.selectedHover) { + setTransition(avatar.selectedHover, playTransitionReachPoses); + } + motion.state = STATIC; + avatar.selectedWalkBlend.lastDirection = NONE; + break; + } + + case SURFACE_MOTION: { + // walk transition reach poses are currently only specified for starting to walk forwards + playTransitionReachPoses = (motion.direction === FORWARDS); + var isAlreadyWalking = (avatar.currentAnimation === avatar.selectedWalkBlend); + + switch (motion.direction) { + case FORWARDS: + if (avatar.selectedWalkBlend.lastDirection !== FORWARDS) { + animationOperations.deepCopy(avatar.selectedWalk, avatar.selectedWalkBlend); + avatar.calibration.strideLength = avatar.selectedWalk.calibration.strideLength; + } + avatar.selectedWalkBlend.lastDirection = FORWARDS; + break; + + case BACKWARDS: + if (avatar.selectedWalkBlend.lastDirection !== BACKWARDS) { + animationOperations.deepCopy(avatar.selectedWalkBackwards, avatar.selectedWalkBlend); + avatar.calibration.strideLength = avatar.selectedWalkBackwards.calibration.strideLength; + } + avatar.selectedWalkBlend.lastDirection = BACKWARDS; + break; + + case LEFT: + animationOperations.deepCopy(avatar.selectedSideStepLeft, avatar.selectedWalkBlend); + avatar.selectedWalkBlend.lastDirection = LEFT; + avatar.calibration.strideLength = avatar.selectedSideStepLeft.calibration.strideLength; + break + + case RIGHT: + animationOperations.deepCopy(avatar.selectedSideStepRight, avatar.selectedWalkBlend); + avatar.selectedWalkBlend.lastDirection = RIGHT; + avatar.calibration.strideLength = avatar.selectedSideStepRight.calibration.strideLength; + break; + + default: + // condition occurs when the avi goes through the floor due to collision hull errors + animationOperations.deepCopy(avatar.selectedWalk, avatar.selectedWalkBlend); + avatar.selectedWalkBlend.lastDirection = FORWARDS; + avatar.calibration.strideLength = avatar.selectedWalk.calibration.strideLength; + break; + } + + if (!isAlreadyWalking && !motion.isComingToHalt) { + setTransition(avatar.selectedWalkBlend, playTransitionReachPoses); + } + motion.state = SURFACE_MOTION; + break; + } + + case AIR_MOTION: { + // blend the up, down, forward and backward flying animations relative to motion speed and direction + animationOperations.zeroAnimation(avatar.selectedFlyBlend); + + // calculate influences based on velocity and direction + var velocityMagnitude = Vec3.length(motion.velocity); + var verticalProportion = motion.velocity.y / velocityMagnitude; + var thrustProportion = motion.velocity.z / velocityMagnitude / 2; + + // directional components + var upComponent = motion.velocity.y > 0 ? verticalProportion : 0; + var downComponent = motion.velocity.y < 0 ? -verticalProportion : 0; + var forwardComponent = motion.velocity.z < 0 ? -thrustProportion : 0; + var backwardComponent = motion.velocity.z > 0 ? thrustProportion : 0; + + // smooth / damp directional components to add visual 'weight' + upComponent = flyUpFilter.process(upComponent); + downComponent = flyDownFilter.process(downComponent); + forwardComponent = flyForwardFilter.process(forwardComponent); + backwardComponent = flyBackwardFilter.process(backwardComponent); + + // normalise directional components + var normaliser = upComponent + downComponent + forwardComponent + backwardComponent; + upComponent = upComponent / normaliser; + downComponent = downComponent / normaliser; + forwardComponent = forwardComponent / normaliser; + backwardComponent = backwardComponent / normaliser; + + // blend animations proportionally + if (upComponent > 0) { + animationOperations.blendAnimation(avatar.selectedFlyUp, + avatar.selectedFlyBlend, + upComponent); + } + if (downComponent > 0) { + animationOperations.blendAnimation(avatar.selectedFlyDown, + avatar.selectedFlyBlend, + downComponent); + } + if (forwardComponent > 0) { + animationOperations.blendAnimation(avatar.selectedFly, + avatar.selectedFlyBlend, + Math.abs(forwardComponent)); + } + if (backwardComponent > 0) { + animationOperations.blendAnimation(avatar.selectedFlyBackwards, + avatar.selectedFlyBlend, + Math.abs(backwardComponent)); + } + + if (avatar.currentAnimation !== avatar.selectedFlyBlend) { + setTransition(avatar.selectedFlyBlend, playTransitionReachPoses); + } + motion.state = AIR_MOTION; + avatar.selectedWalkBlend.lastDirection = NONE; + break; + } + } // end switch next state of motion +} + +// determine the length of stride. advance the frequency time wheels. advance frequency time wheels for any live transitions +function advanceAnimations() { + var wheelAdvance = 0; + + // turn the frequency time wheel + if (avatar.currentAnimation === avatar.selectedWalkBlend) { + // Using technique described here: http://www.gdcvault.com/play/1020583/Animation-Bootcamp-An-Indie-Approach + // wrap the stride length around a 'surveyor's wheel' twice and calculate the angular speed at the given (linear) speed + // omega = v / r , where r = circumference / 2 PI and circumference = 2 * stride length + var speed = Vec3.length(motion.velocity); + motion.frequencyTimeWheelRadius = avatar.calibration.strideLength / Math.PI; + var ftWheelAngularVelocity = speed / motion.frequencyTimeWheelRadius; + // calculate the degrees turned (at this angular speed) since last frame + wheelAdvance = filter.radToDeg(motion.deltaTime * ftWheelAngularVelocity); + } else { + // turn the frequency time wheel by the amount specified for this animation + wheelAdvance = filter.radToDeg(avatar.currentAnimation.calibration.frequency * motion.deltaTime); + } + + if (motion.currentTransition !== nullTransition) { + // the last animation is still playing so we turn it's frequency time wheel to maintain the animation + if (motion.currentTransition.lastAnimation === motion.selectedWalkBlend) { + // if at a stop angle (i.e. feet now under the avi) hold the wheel position for remainder of transition + var tolerance = motion.currentTransition.lastFrequencyTimeIncrement + 0.1; + if ((motion.currentTransition.lastFrequencyTimeWheelPos > + (motion.currentTransition.stopAngle - tolerance)) && + (motion.currentTransition.lastFrequencyTimeWheelPos < + (motion.currentTransition.stopAngle + tolerance))) { + motion.currentTransition.lastFrequencyTimeIncrement = 0; + } + } + motion.currentTransition.advancePreviousFrequencyTimeWheel(motion.deltaTime); + } + + // avoid unnaturally fast walking when landing at speed - simulates skimming / skidding + if (Math.abs(wheelAdvance) > MAX_FT_WHEEL_INCREMENT) { + wheelAdvance = 0; + } + + // advance the walk wheel the appropriate amount + motion.advanceFrequencyTimeWheel(wheelAdvance); + + // walking? then see if it's a good time to measure the stride length (needs to be at least 97% of max walking speed) + const ALMOST_ONE = 0.97; + if (avatar.currentAnimation === avatar.selectedWalkBlend && + (Vec3.length(motion.velocity) / MAX_WALK_SPEED > ALMOST_ONE)) { + + var strideMaxAt = avatar.currentAnimation.calibration.strideMaxAt; + const TOLERANCE = 1.0; + + if (motion.frequencyTimeWheelPos < (strideMaxAt + TOLERANCE) && + motion.frequencyTimeWheelPos > (strideMaxAt - TOLERANCE) && + motion.currentTransition === nullTransition) { + // measure and save stride length + var footRPos = MyAvatar.getJointPosition("RightFoot"); + var footLPos = MyAvatar.getJointPosition("LeftFoot"); + avatar.calibration.strideLength = Vec3.distance(footRPos, footLPos); + avatar.currentAnimation.calibration.strideLength = avatar.calibration.strideLength; + } else { + // use the previously saved value for stride length + avatar.calibration.strideLength = avatar.currentAnimation.calibration.strideLength; + } + } // end get walk stride length +} + +// initialise a new transition. update progress of a live transition +function updateTransitions() { + + if (motion.currentTransition !== nullTransition) { + // is this a new transition? + if (motion.currentTransition.progress === 0) { + // do we have overlapping transitions? + if (motion.currentTransition.lastTransition !== nullTransition) { + // is the last animation for the nested transition the same as the new animation? + if (motion.currentTransition.lastTransition.lastAnimation === avatar.currentAnimation) { + // then sync the nested transition's frequency time wheel for a smooth animation blend + motion.frequencyTimeWheelPos = motion.currentTransition.lastTransition.lastFrequencyTimeWheelPos; + } + } + } + if (motion.currentTransition.updateProgress() === TRANSITION_COMPLETE) { + motion.currentTransition = nullTransition; + } + } +} + +// helper function for renderMotion(). calculate the amount to lean forwards (or backwards) based on the avi's velocity +var leanPitchSmoothingFilter = filter.createButterworthFilter(); +function getLeanPitch() { + var leanProgress = 0; + + if (motion.direction === DOWN || + motion.direction === FORWARDS || + motion.direction === BACKWARDS) { + leanProgress = -motion.velocity.z / TOP_SPEED; + } + // use filters to shape the walking acceleration response + leanProgress = leanPitchSmoothingFilter.process(leanProgress); + return PITCH_MAX * leanProgress; +} + +// helper function for renderMotion(). calculate the angle at which to bank into corners whilst turning +var leanRollSmoothingFilter = filter.createButterworthFilter(); +function getLeanRoll() { + var leanRollProgress = 0; + var linearContribution = 0; + const LOG_SCALER = 8; + + if (Vec3.length(motion.velocity) > 0) { + linearContribution = (Math.log(Vec3.length(motion.velocity) / TOP_SPEED) + LOG_SCALER) / LOG_SCALER; + } + var angularContribution = Math.abs(motion.yawDelta) / DELTA_YAW_MAX; + leanRollProgress = linearContribution; + leanRollProgress *= angularContribution; + // shape the response curve + leanRollProgress = filter.bezier(leanRollProgress, {x: 1, y: 0}, {x: 1, y: 0}); + // which way to lean? + var turnSign = (motion.yawDelta >= 0) ? 1 : -1; + + if (motion.direction === BACKWARDS || + motion.direction === LEFT) { + turnSign *= -1; + } + // filter progress + leanRollProgress = leanRollSmoothingFilter.process(turnSign * leanRollProgress); + return ROLL_MAX * leanRollProgress; +} + +// animate the avatar using sine waves, geometric waveforms and harmonic generators +function renderMotion() { + // leaning in response to speed and acceleration + var leanPitch = motion.state === STATIC ? 0 : getLeanPitch(); + var leanRoll = motion.state === STATIC ? 0 : getLeanRoll(); + var lastDirection = motion.lastDirection; + // hips translations from currently playing animations + var hipsTranslations = {x:0, y:0, z:0}; + + if (motion.currentTransition !== nullTransition) { + // maintain previous direction when transitioning from a walk + if (motion.currentTransition.lastAnimation === avatar.selectedWalkBlend) { + motion.lastDirection = motion.currentTransition.lastDirection; + } + hipsTranslations = motion.currentTransition.blendTranslations(motion.frequencyTimeWheelPos, + motion.lastDirection); + } else { + hipsTranslations = animationOperations.calculateTranslations(avatar.currentAnimation, + motion.frequencyTimeWheelPos, + motion.direction); + } + // factor any leaning into the hips offset + hipsTranslations.z += avatar.calibration.hipsToFeet * Math.sin(filter.degToRad(leanPitch)); + hipsTranslations.x += avatar.calibration.hipsToFeet * Math.sin(filter.degToRad(leanRoll)); + + // ensure skeleton offsets are within the 1m limit + hipsTranslations.x = hipsTranslations.x > 1 ? 1 : hipsTranslations.x; + hipsTranslations.x = hipsTranslations.x < -1 ? -1 : hipsTranslations.x; + hipsTranslations.y = hipsTranslations.y > 1 ? 1 : hipsTranslations.y; + hipsTranslations.y = hipsTranslations.y < -1 ? -1 : hipsTranslations.y; + hipsTranslations.z = hipsTranslations.z > 1 ? 1 : hipsTranslations.z; + hipsTranslations.z = hipsTranslations.z < -1 ? -1 : hipsTranslations.z; + // apply translations + MyAvatar.setSkeletonOffset(hipsTranslations); + + // play footfall sound? + var producingFootstepSounds = (avatar.currentAnimation === avatar.selectedWalkBlend) && avatar.makesFootStepSounds; + + if (motion.currentTransition !== nullTransition && avatar.makesFootStepSounds) { + if (motion.currentTransition.nextAnimation === avatar.selectedWalkBlend || + motion.currentTransition.lastAnimation === avatar.selectedWalkBlend) { + producingFootstepSounds = true; + } + } + if (producingFootstepSounds) { + const QUARTER_CYCLE = 90; + const THREE_QUARTER_CYCLE = 270; + var ftWheelPosition = motion.frequencyTimeWheelPos; + + if (motion.currentTransition !== nullTransition && + motion.currentTransition.lastAnimation === avatar.selectedWalkBlend) { + ftWheelPosition = motion.currentTransition.lastFrequencyTimeWheelPos; + } + if (avatar.nextStep === LEFT && ftWheelPosition > THREE_QUARTER_CYCLE) { + avatar.makeFootStepSound(); + } else if (avatar.nextStep === RIGHT && (ftWheelPosition < THREE_QUARTER_CYCLE && ftWheelPosition > QUARTER_CYCLE)) { + avatar.makeFootStepSound(); + } + } + + // apply joint rotations + for (jointName in avatar.currentAnimation.joints) { + var joint = walkAssets.animationReference.joints[jointName]; + var jointRotations = undefined; + + // ignore arms / head rotations if options are selected in the settings + if (avatar.armsFree && (joint.IKChain === "LeftArm" || joint.IKChain === "RightArm")) { + continue; + } + if (avatar.headFree && joint.IKChain === "Head") { + continue; + } + + // if there's a live transition, blend the rotations with the last animation's rotations + if (motion.currentTransition !== nullTransition) { + jointRotations = motion.currentTransition.blendRotations(jointName, + motion.frequencyTimeWheelPos, + motion.lastDirection); + } else { + jointRotations = animationOperations.calculateRotations(jointName, + avatar.currentAnimation, + motion.frequencyTimeWheelPos, + motion.direction); + } + + // apply angular velocity and speed induced leaning + if (jointName === "Hips") { + jointRotations.x += leanPitch; + jointRotations.z += leanRoll; + } + + // apply rotations + MyAvatar.setJointRotation(jointName, Quat.fromVec3Degrees(jointRotations)); + } } \ No newline at end of file