From c9fd650e70939bfe62fea6323f16d986519d999c Mon Sep 17 00:00:00 2001 From: humbletim Date: Mon, 16 Jan 2017 19:37:31 -0500 Subject: [PATCH 1/9] update to support click/far-click toggling and userData.disabled setting --- .../tutorials/entity_scripts/ambientSound.js | 330 +++++++++++++++--- 1 file changed, 282 insertions(+), 48 deletions(-) diff --git a/scripts/tutorials/entity_scripts/ambientSound.js b/scripts/tutorials/entity_scripts/ambientSound.js index 620b371400..64adcf379a 100644 --- a/scripts/tutorials/entity_scripts/ambientSound.js +++ b/scripts/tutorials/entity_scripts/ambientSound.js @@ -1,55 +1,70 @@ // ambientSound.js // // This entity script will allow you to create an ambient sound that loops when a person is within a given -// range of this entity. Great way to add one or more ambisonic soundfields to your environment. +// range of this entity. Great way to add one or more ambisonic soundfields to your environment. // -// In the userData section for the entity, add/edit three values: -// userData.soundURL should be a string giving the URL to the sound file. Defaults to 100 meters if not set. +// In the userData section for the entity, add/edit three values: +// userData.soundURL should be a string giving the URL to the sound file. Defaults to 100 meters if not set. // userData.range should be an integer for the max distance away from the entity where the sound will be audible. -// userData.volume is the max volume at which the clip should play. Defaults to 1.0 full volume) +// userData.maxVolume is the max volume at which the clip should play. Defaults to 1.0 full volume. +// userData.disabled is an optionanl boolean flag which can be used to disable the ambient sound. Defaults to false. +// +// The rotation of the entity is copied to the ambisonic field, so by rotating the entity you will rotate the +// direction in-which a certain sound comes from. // -// The rotation of the entity is copied to the ambisonic field, so by rotating the entity you will rotate the -// direction in-which a certain sound comes from. -// // Remember that the entity has to be visible to the user for the sound to play at all, so make sure the entity is -// large enough to be loaded at the range you set, particularly for large ranges. -// +// large enough to be loaded at the range you set, particularly for large ranges. +// // Copyright 2016 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -(function(){ +(function(){ + var VERSION = "0.0.1"; // This sample clip and range will be used if you don't add userData to the entity (see above) var DEFAULT_RANGE = 100; var DEFAULT_URL = "http://hifi-content.s3.amazonaws.com/ken/samples/forest_ambiX.wav"; var DEFAULT_VOLUME = 1.0; var soundURL = ""; + var soundName = ""; + var startTime; + var soundOptions = { + loop: true, + localOnly: true, + //ignorePenumbra: true, + }; var range = DEFAULT_RANGE; var maxVolume = DEFAULT_VOLUME; + var disabled = false; var UPDATE_INTERVAL_MSECS = 100; var rotation; var entity; var ambientSound; var center; - var soundPlaying = false; + var soundPlaying; var checkTimer = false; var _this; - var WANT_COLOR_CHANGE = false; var COLOR_OFF = { red: 128, green: 128, blue: 128 }; var COLOR_ON = { red: 255, green: 0, blue: 0 }; - var WANT_DEBUG = false; + var WANT_DEBUG = true; function debugPrint(string) { if (WANT_DEBUG) { - print(string); + print("ambientSound | " + string); } } + var WANT_DEBUG_BROADCASTS = "ambientSound.js"; + var WANT_DEBUG_OVERLAY = false; + var LINEHEIGHT = 0.1; + // Optionally enable debug overlays using a Settings value + WANT_DEBUG_OVERLAY = WANT_DEBUG_OVERLAY || /ambientSound/.test(Settings.getValue("WANT_DEBUG_OVERLAY")); + this.updateSettings = function() { // Check user data on the entity for any changes var oldSoundURL = soundURL; @@ -58,81 +73,300 @@ var data = JSON.parse(props.userData); if (data.soundURL && !(soundURL === data.soundURL)) { soundURL = data.soundURL; - debugPrint("Read ambient sound URL: " + soundURL); - } else if (!data.soundURL) { - soundURL = DEFAULT_URL; + soundName = (soundURL||"").split("/").pop(); // just filename part + debugPrint("Read ambient sound URL: " + soundURL); } if (data.range && !(range === data.range)) { range = data.range; debugPrint("Read ambient sound range: " + range); } - if (data.volume && !(maxVolume === data.volume)) { - maxVolume = data.volume; + // Check known aliases for the "volume" setting (which allows for inplace upgrade of existing marketplace entities) + data.maxVolume = data.maxVolume || data.soundVolume || data.volume; + if (data.maxVolume && !(maxVolume === data.maxVolume)) { + maxVolume = data.maxVolume; debugPrint("Read ambient sound volume: " + maxVolume); } + if ("disabled" in data && !(disabled === data.disabled)) { + disabled = data.disabled; + debugPrint("Read ambient disabled state: " + disabled); + if (disabled) { + this.cleanup(); + debugState("disabled"); + return; + } + } + /*if ("loop" in data && !(soundOptions.loop === data.loop)) { + soundOptions.loop = data.loop; + debugPrint("Read ambient loop state: " + soundOptions.loop); + }*/ } if (!(soundURL === oldSoundURL) || (soundURL === "")) { - debugPrint("Loading ambient sound into cache"); - ambientSound = SoundCache.getSound(soundURL); + if (soundURL) { + debugState("downloading", "Loading ambient sound into cache"); + // Use prefetch to detect URL loading errors + var resource = SoundCache.prefetch(soundURL); + function onStateChanged() { + if (resource.state === Resource.State.FINISHED) { + resource.stateChanged.disconnect(onStateChanged); + ambientSound = SoundCache.getSound(soundURL); + debugState("idle"); + } else if (resource.state === Resource.State.FAILED) { + resource.stateChanged.disconnect(onStateChanged); + debugPrint("Failed to download ambient sound: " + soundURL); + debugState("error"); + } + debugPrint("onStateChanged: " + JSON.stringify({ + sound: soundName, + state: resource.state, + stateName: Object.keys(Resource.State).filter(function(key) { + return Resource.State[key] === resource.state; + }) + })); + } + resource.stateChanged.connect(onStateChanged); + onStateChanged(resource.state); + } if (soundPlaying && soundPlaying.playing) { + debugPrint("URL changed, stopping current ambient sound"); soundPlaying.stop(); soundPlaying = false; - if (WANT_COLOR_CHANGE) { - Entities.editEntity(entity, { color: COLOR_OFF }); - } - debugPrint("Restarting ambient sound"); } - } + } } - this.preload = function(entityID) { + this.clickDownOnEntity = function(entityID, mouseEvent) { + print("click"); + if (mouseEvent.isPrimaryButton) { + this._toggle("primary click"); + } + }; + + this.startFarTrigger = function() { + this._toggle("far click"); + }; + + this._toggle = function(hint) { + // Toggle between ON/OFF state, but only if not in edit mode + if (Settings.getValue("io.highfidelity.isEditting")) { + return; + } + var props = Entities.getEntityProperties(entity, [ "userData", "age", "scriptTimestamp" ]); + var data = JSON.parse(props.userData); + data.disabled = !data.disabled; + + debugPrint(hint + " -- triggering ambient sound " + (data.disabled ? "OFF" : "ON") + " (" + soundName + ")"); + var oldState = _debugState; + + if (WANT_DEBUG_BROADCASTS) { + Messages.sendMessage(WANT_DEBUG_BROADCASTS /*entity*/, JSON.stringify({ palName: MyAvatar.sessionDisplayName, soundName: soundName, hint: hint, scriptTimestamp: props.scriptTimestamp, oldState: oldState, newState: _debugState, age: props.age })); + } + + this.cleanup(); + + // Save the userData and bump scriptTimestamp, which causes all nearby listeners to apply the state change + Entities.editEntity(entity, { + userData: JSON.stringify(data), + scriptTimestamp: Math.round(props.age * 1000) + }); + //this._updateColor(data.disabled); + }; + + this._updateColor = function(disabled) { + // Update Shape or Text Entity color based on ON/OFF status + var props = Entities.getEntityProperties(entity, [ "color", "textColor" ]); + var targetColor = disabled ? COLOR_OFF : COLOR_ON; + var currentColor = props.textColor || props.color; + var newProps = props.textColor ? { textColor: targetColor } : { color: targetColor }; + + if (currentColor.red !== targetColor.red || + currentColor.green !== targetColor.green || + currentColor.blue !== targetColor.blue) { + Entities.editEntity(entity, newProps); + } + }; + + this.preload = function(entityID) { // Load the sound and range from the entity userData fields, and note the position of the entity. - debugPrint("Ambient sound preload"); + debugPrint("Ambient sound preload " + VERSION); entity = entityID; _this = this; - checkTimer = Script.setInterval(this.maybeUpdate, UPDATE_INTERVAL_MSECS); - }; + + if (WANT_DEBUG_OVERLAY) { + _createDebugOverlays(); + } + + var props = Entities.getEntityProperties(entity, [ "userData" ]); + if (props.userData) { + var data = JSON.parse(props.userData); + this._updateColor(data.disabled); + if (data.disabled) { + _this.maybeUpdate(); + return; + } + } + + checkTimer = Script.setInterval(_this.maybeUpdate, UPDATE_INTERVAL_MSECS); + }; this.maybeUpdate = function() { // Every UPDATE_INTERVAL_MSECS, update the volume of the ambient sound based on distance from my avatar _this.updateSettings(); var HYSTERESIS_FRACTION = 0.1; var props = Entities.getEntityProperties(entity, [ "position", "rotation" ]); + if (!props.position) { + // FIXME: this mysterious state has been happening while testing + // and might indicate a bug where an Entity can become unreachable without `unload` having been called.. + print("FIXME: ambientSound.js -- expected Entity unavailable!") + if (WANT_DEBUG_BROADCASTS) { + Messages.sendMessage(WANT_DEBUG_BROADCASTS /*entity*/, JSON.stringify({ palName: MyAvatar.sessionDisplayName, soundName: soundName, hint: "FIXME: maybeUpdate", oldState: _debugState })); + } + return _this.cleanup(); + } center = props.position; rotation = props.rotation; var distance = Vec3.length(Vec3.subtract(MyAvatar.position, center)); if (distance <= range) { var volume = (1.0 - distance / range) * maxVolume; - if (!soundPlaying && ambientSound.downloaded) { - soundPlaying = Audio.playSound(ambientSound, { loop: true, - localOnly: true, - orientation: rotation, - volume: volume }); - debugPrint("Starting ambient sound, volume: " + volume); - if (WANT_COLOR_CHANGE) { - Entities.editEntity(entity, { color: COLOR_ON }); - } - + soundOptions.orientation = Quat.rotation; + soundOptions.volume = volume; + if (!soundPlaying && ambientSound && ambientSound.downloaded) { + debugState("playing", "Starting ambient sound: " + soundName + " (duration: " + ambientSound.duration + ")"); + soundPlaying = Audio.playSound(ambientSound, soundOptions); } else if (soundPlaying && soundPlaying.playing) { - soundPlaying.setOptions( { volume: volume, orientation: rotation } ); + soundPlaying.setOptions(soundOptions); } - } else if (soundPlaying && soundPlaying.playing && (distance > range * HYSTERESIS_FRACTION)) { soundPlaying.stop(); soundPlaying = false; - Entities.editEntity(entity, { color: { red: 128, green: 128, blue: 128 }}); - debugPrint("Out of range, stopping ambient sound"); + debugState("idle", "Out of range, stopping ambient sound: " + soundName); + } + if (WANT_DEBUG_OVERLAY) { + updateDebugOverlay(distance); } } - this.unload = function(entityID) { - debugPrint("Ambient sound unload"); + this.unload = function(entityID) { + debugPrint("Ambient sound unload "); + if (WANT_DEBUG_BROADCASTS) { + var offset = ambientSound && (new Date - startTime)/1000 % ambientSound.duration; + Messages.sendMessage(WANT_DEBUG_BROADCASTS /*entity*/, JSON.stringify({ palName: MyAvatar.sessionDisplayName, soundName: soundName, hint: "unload", oldState: _debugState, offset: offset })); + } + if (WANT_DEBUG_OVERLAY) { + _removeDebugOverlays(); + } + this.cleanup(); + }; + + this.cleanup = function() { if (checkTimer) { Script.clearInterval(checkTimer); + checkTimer = false; } if (soundPlaying && soundPlaying.playing) { soundPlaying.stop(); + soundPlaying = false; } - }; + }; -}) + // Visual debugging overlay (to see set WANT_DEBUG_OVERLAY = true) + + var DEBUG_COLORS = { + //preload: { red: 0, green: 80, blue: 80 }, + disabled: { red: 0, green: 0, blue: 0, alpha: 0.0 }, + downloading: { red: 255, green: 255, blue: 0 }, + error: { red: 255, green: 0, blue: 0 }, + playing: { red: 0, green: 200, blue: 0 }, + idle: { red: 0, green: 100, blue: 0 } + }; + var _debugOverlay; + var _debugState = ""; + function debugState(state, message) { + if (state === "playing") { + startTime = new Date; + } + _debugState = state; + if (message) { + debugPrint(message); + } + updateDebugOverlay(); + if (WANT_DEBUG_BROADCASTS) { + // Broadcast state changes to an implicit entity channel, making multi-user scenarios easier to verify from a single console + Messages.sendMessage(WANT_DEBUG_BROADCASTS /*entity*/, JSON.stringify({ palName: MyAvatar.sessionDisplayName, soundName: soundName, state: state })); + } + } + + function updateDebugOverlay(distance) { + var props = Entities.getEntityProperties(entity, [ "name", "dimensions" ]); + if (!props.dimensions) { + return print("ambientSound.js: updateDebugOverlay -- entity no longer available " + entity); + } + var options = soundPlaying && soundPlaying.options; + if (options) { + var offset = soundPlaying.playing && ambientSound && (new Date - startTime)/1000 % ambientSound.duration; + var deg = Quat.safeEulerAngles(options.orientation); + var orientation = [ deg.x, deg.y, deg.z].map(Math.round).join(", "); + var volume = options.volume; + } + var info = { + //loudness: soundPlaying.loudness && soundPlaying.loudness.toFixed(4) || undefined, + offset: offset && ("00"+offset.toFixed(1)).substr(-4)+"s" || undefined, + orientation: orientation, + injector: soundPlaying && soundPlaying.playing && "playing", + resource: ambientSound && ambientSound.downloaded && "ready (" + ambientSound.duration.toFixed(1) + "s)", + name: props.name || undefined, + uuid: entity.split(/\W/)[1], // extracts just the first part of the UUID + sound: soundName, + volume: Math.max(0,volume||0).toFixed(2) + " / " + maxVolume.toFixed(2), + distance: (distance||0).toFixed(1) + "m / " + range.toFixed(1) + "m", + state: _debugState.toUpperCase(), + }; + + // Pretty print key/value pairs, excluding any undefined values + var outputText = Object.keys(info).filter(function(key) { + return info[key] !== undefined; + }).map(function(key) { + return key + ": " + info[key]; + }).join("\n"); + + // Calculate a local position for displaying info just above the Entity + var textSize = Overlays.textSize(_debugOverlay, outputText); + var size = { + x: textSize.width + LINEHEIGHT, + y: textSize.height + LINEHEIGHT + }; + var pos = { x: 0, y: props.dimensions.y + size.y/2, z: 0 }; + + var backgroundColor = DEBUG_COLORS[_debugState]; + var backgroundAlpha = backgroundColor ? backgroundColor.alpha : 0.6; + Overlays.editOverlay(_debugOverlay, { + visible: true, + backgroundColor: backgroundColor, + backgroundAlpha: backgroundAlpha, + text: outputText, + localPosition: pos, + size: size, + }); + } + + function _removeDebugOverlays() { + if (_debugOverlay) { + Overlays.deleteOverlay(_debugOverlay); + _debugOverlay = 0; + } + } + + function _createDebugOverlays() { + _debugOverlay = Overlays.addOverlay("text3d", { + visible: true, + lineHeight: LINEHEIGHT, + leftMargin: LINEHEIGHT/2, + topMargin: LINEHEIGHT/2, + localPosition: Vec3.ZERO, + parentID: entity, + ignoreRayIntersection: true, + isFacingAvatar: true, + textAlpha: 0.6, + //drawInFront: true, + }); + } +}) From 827aa68d3f609146a59fd7edf20c6d4a906e6e6f Mon Sep 17 00:00:00 2001 From: humbletim Date: Mon, 16 Jan 2017 19:50:25 -0500 Subject: [PATCH 2/9] cleanup pass --- .../tutorials/entity_scripts/ambientSound.js | 23 ++++++++----------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/scripts/tutorials/entity_scripts/ambientSound.js b/scripts/tutorials/entity_scripts/ambientSound.js index 64adcf379a..3b75ed6720 100644 --- a/scripts/tutorials/entity_scripts/ambientSound.js +++ b/scripts/tutorials/entity_scripts/ambientSound.js @@ -45,25 +45,25 @@ var entity; var ambientSound; var center; - var soundPlaying; + var soundPlaying = false; var checkTimer = false; var _this; var COLOR_OFF = { red: 128, green: 128, blue: 128 }; var COLOR_ON = { red: 255, green: 0, blue: 0 }; - var WANT_DEBUG = true; + var WANT_DEBUG = false; function debugPrint(string) { if (WANT_DEBUG) { print("ambientSound | " + string); } } - var WANT_DEBUG_BROADCASTS = "ambientSound.js"; var WANT_DEBUG_OVERLAY = false; var LINEHEIGHT = 0.1; // Optionally enable debug overlays using a Settings value WANT_DEBUG_OVERLAY = WANT_DEBUG_OVERLAY || /ambientSound/.test(Settings.getValue("WANT_DEBUG_OVERLAY")); + var WANT_DEBUG_BROADCASTS = WANT_DEBUG_OVERLAY && "ambientSound.js"; this.updateSettings = function() { // Check user data on the entity for any changes @@ -95,10 +95,6 @@ return; } } - /*if ("loop" in data && !(soundOptions.loop === data.loop)) { - soundOptions.loop = data.loop; - debugPrint("Read ambient loop state: " + soundOptions.loop); - }*/ } if (!(soundURL === oldSoundURL) || (soundURL === "")) { if (soundURL) { @@ -135,7 +131,6 @@ } this.clickDownOnEntity = function(entityID, mouseEvent) { - print("click"); if (mouseEvent.isPrimaryButton) { this._toggle("primary click"); } @@ -158,7 +153,7 @@ var oldState = _debugState; if (WANT_DEBUG_BROADCASTS) { - Messages.sendMessage(WANT_DEBUG_BROADCASTS /*entity*/, JSON.stringify({ palName: MyAvatar.sessionDisplayName, soundName: soundName, hint: hint, scriptTimestamp: props.scriptTimestamp, oldState: oldState, newState: _debugState, age: props.age })); + Messages.sendMessage(WANT_DEBUG_BROADCASTS, JSON.stringify({ palName: MyAvatar.sessionDisplayName, soundName: soundName, hint: hint, scriptTimestamp: props.scriptTimestamp, oldState: oldState, newState: _debugState, age: props.age })); } this.cleanup(); @@ -218,7 +213,7 @@ // and might indicate a bug where an Entity can become unreachable without `unload` having been called.. print("FIXME: ambientSound.js -- expected Entity unavailable!") if (WANT_DEBUG_BROADCASTS) { - Messages.sendMessage(WANT_DEBUG_BROADCASTS /*entity*/, JSON.stringify({ palName: MyAvatar.sessionDisplayName, soundName: soundName, hint: "FIXME: maybeUpdate", oldState: _debugState })); + Messages.sendMessage(WANT_DEBUG_BROADCASTS, JSON.stringify({ palName: MyAvatar.sessionDisplayName, soundName: soundName, hint: "FIXME: maybeUpdate", oldState: _debugState })); } return _this.cleanup(); } @@ -227,7 +222,7 @@ var distance = Vec3.length(Vec3.subtract(MyAvatar.position, center)); if (distance <= range) { var volume = (1.0 - distance / range) * maxVolume; - soundOptions.orientation = Quat.rotation; + soundOptions.orientation = rotation; soundOptions.volume = volume; if (!soundPlaying && ambientSound && ambientSound.downloaded) { debugState("playing", "Starting ambient sound: " + soundName + " (duration: " + ambientSound.duration + ")"); @@ -249,7 +244,7 @@ debugPrint("Ambient sound unload "); if (WANT_DEBUG_BROADCASTS) { var offset = ambientSound && (new Date - startTime)/1000 % ambientSound.duration; - Messages.sendMessage(WANT_DEBUG_BROADCASTS /*entity*/, JSON.stringify({ palName: MyAvatar.sessionDisplayName, soundName: soundName, hint: "unload", oldState: _debugState, offset: offset })); + Messages.sendMessage(WANT_DEBUG_BROADCASTS, JSON.stringify({ palName: MyAvatar.sessionDisplayName, soundName: soundName, hint: "unload", oldState: _debugState, offset: offset })); } if (WANT_DEBUG_OVERLAY) { _removeDebugOverlays(); @@ -290,8 +285,8 @@ } updateDebugOverlay(); if (WANT_DEBUG_BROADCASTS) { - // Broadcast state changes to an implicit entity channel, making multi-user scenarios easier to verify from a single console - Messages.sendMessage(WANT_DEBUG_BROADCASTS /*entity*/, JSON.stringify({ palName: MyAvatar.sessionDisplayName, soundName: soundName, state: state })); + // Broadcast state changes to make multi-user scenarios easier to verify from a single console + Messages.sendMessage(WANT_DEBUG_BROADCASTS, JSON.stringify({ palName: MyAvatar.sessionDisplayName, soundName: soundName, state: state })); } } From c7a561aff9cbcee7a01fb5ef81aa401f6920a31b Mon Sep 17 00:00:00 2001 From: humbletim Date: Tue, 17 Jan 2017 01:23:03 -0500 Subject: [PATCH 3/9] trim extra debugging code --- .../tutorials/entity_scripts/ambientSound.js | 150 +----------------- 1 file changed, 4 insertions(+), 146 deletions(-) diff --git a/scripts/tutorials/entity_scripts/ambientSound.js b/scripts/tutorials/entity_scripts/ambientSound.js index 3b75ed6720..700db4753c 100644 --- a/scripts/tutorials/entity_scripts/ambientSound.js +++ b/scripts/tutorials/entity_scripts/ambientSound.js @@ -22,19 +22,15 @@ // (function(){ - var VERSION = "0.0.1"; // This sample clip and range will be used if you don't add userData to the entity (see above) var DEFAULT_RANGE = 100; var DEFAULT_URL = "http://hifi-content.s3.amazonaws.com/ken/samples/forest_ambiX.wav"; var DEFAULT_VOLUME = 1.0; var soundURL = ""; - var soundName = ""; - var startTime; var soundOptions = { loop: true, localOnly: true, - //ignorePenumbra: true, }; var range = DEFAULT_RANGE; var maxVolume = DEFAULT_VOLUME; @@ -59,12 +55,6 @@ } } - var WANT_DEBUG_OVERLAY = false; - var LINEHEIGHT = 0.1; - // Optionally enable debug overlays using a Settings value - WANT_DEBUG_OVERLAY = WANT_DEBUG_OVERLAY || /ambientSound/.test(Settings.getValue("WANT_DEBUG_OVERLAY")); - var WANT_DEBUG_BROADCASTS = WANT_DEBUG_OVERLAY && "ambientSound.js"; - this.updateSettings = function() { // Check user data on the entity for any changes var oldSoundURL = soundURL; @@ -73,7 +63,6 @@ var data = JSON.parse(props.userData); if (data.soundURL && !(soundURL === data.soundURL)) { soundURL = data.soundURL; - soundName = (soundURL||"").split("/").pop(); // just filename part debugPrint("Read ambient sound URL: " + soundURL); } if (data.range && !(range === data.range)) { @@ -111,13 +100,6 @@ debugPrint("Failed to download ambient sound: " + soundURL); debugState("error"); } - debugPrint("onStateChanged: " + JSON.stringify({ - sound: soundName, - state: resource.state, - stateName: Object.keys(Resource.State).filter(function(key) { - return Resource.State[key] === resource.state; - }) - })); } resource.stateChanged.connect(onStateChanged); onStateChanged(resource.state); @@ -149,13 +131,9 @@ var data = JSON.parse(props.userData); data.disabled = !data.disabled; - debugPrint(hint + " -- triggering ambient sound " + (data.disabled ? "OFF" : "ON") + " (" + soundName + ")"); + debugPrint(hint + " -- triggering ambient sound " + (data.disabled ? "OFF" : "ON") + " (" + soundURL + ")"); var oldState = _debugState; - if (WANT_DEBUG_BROADCASTS) { - Messages.sendMessage(WANT_DEBUG_BROADCASTS, JSON.stringify({ palName: MyAvatar.sessionDisplayName, soundName: soundName, hint: hint, scriptTimestamp: props.scriptTimestamp, oldState: oldState, newState: _debugState, age: props.age })); - } - this.cleanup(); // Save the userData and bump scriptTimestamp, which causes all nearby listeners to apply the state change @@ -182,14 +160,10 @@ this.preload = function(entityID) { // Load the sound and range from the entity userData fields, and note the position of the entity. - debugPrint("Ambient sound preload " + VERSION); + debugPrint("Ambient sound preload"); entity = entityID; _this = this; - if (WANT_DEBUG_OVERLAY) { - _createDebugOverlays(); - } - var props = Entities.getEntityProperties(entity, [ "userData" ]); if (props.userData) { var data = JSON.parse(props.userData); @@ -209,12 +183,7 @@ var HYSTERESIS_FRACTION = 0.1; var props = Entities.getEntityProperties(entity, [ "position", "rotation" ]); if (!props.position) { - // FIXME: this mysterious state has been happening while testing - // and might indicate a bug where an Entity can become unreachable without `unload` having been called.. print("FIXME: ambientSound.js -- expected Entity unavailable!") - if (WANT_DEBUG_BROADCASTS) { - Messages.sendMessage(WANT_DEBUG_BROADCASTS, JSON.stringify({ palName: MyAvatar.sessionDisplayName, soundName: soundName, hint: "FIXME: maybeUpdate", oldState: _debugState })); - } return _this.cleanup(); } center = props.position; @@ -225,7 +194,7 @@ soundOptions.orientation = rotation; soundOptions.volume = volume; if (!soundPlaying && ambientSound && ambientSound.downloaded) { - debugState("playing", "Starting ambient sound: " + soundName + " (duration: " + ambientSound.duration + ")"); + debugState("playing", "Starting ambient sound: " + soundURL + " (duration: " + ambientSound.duration + ")"); soundPlaying = Audio.playSound(ambientSound, soundOptions); } else if (soundPlaying && soundPlaying.playing) { soundPlaying.setOptions(soundOptions); @@ -233,22 +202,12 @@ } else if (soundPlaying && soundPlaying.playing && (distance > range * HYSTERESIS_FRACTION)) { soundPlaying.stop(); soundPlaying = false; - debugState("idle", "Out of range, stopping ambient sound: " + soundName); - } - if (WANT_DEBUG_OVERLAY) { - updateDebugOverlay(distance); + debugState("idle", "Out of range, stopping ambient sound: " + soundURL); } } this.unload = function(entityID) { debugPrint("Ambient sound unload "); - if (WANT_DEBUG_BROADCASTS) { - var offset = ambientSound && (new Date - startTime)/1000 % ambientSound.duration; - Messages.sendMessage(WANT_DEBUG_BROADCASTS, JSON.stringify({ palName: MyAvatar.sessionDisplayName, soundName: soundName, hint: "unload", oldState: _debugState, offset: offset })); - } - if (WANT_DEBUG_OVERLAY) { - _removeDebugOverlays(); - } this.cleanup(); }; @@ -263,105 +222,4 @@ } }; - // Visual debugging overlay (to see set WANT_DEBUG_OVERLAY = true) - - var DEBUG_COLORS = { - //preload: { red: 0, green: 80, blue: 80 }, - disabled: { red: 0, green: 0, blue: 0, alpha: 0.0 }, - downloading: { red: 255, green: 255, blue: 0 }, - error: { red: 255, green: 0, blue: 0 }, - playing: { red: 0, green: 200, blue: 0 }, - idle: { red: 0, green: 100, blue: 0 } - }; - var _debugOverlay; - var _debugState = ""; - function debugState(state, message) { - if (state === "playing") { - startTime = new Date; - } - _debugState = state; - if (message) { - debugPrint(message); - } - updateDebugOverlay(); - if (WANT_DEBUG_BROADCASTS) { - // Broadcast state changes to make multi-user scenarios easier to verify from a single console - Messages.sendMessage(WANT_DEBUG_BROADCASTS, JSON.stringify({ palName: MyAvatar.sessionDisplayName, soundName: soundName, state: state })); - } - } - - function updateDebugOverlay(distance) { - var props = Entities.getEntityProperties(entity, [ "name", "dimensions" ]); - if (!props.dimensions) { - return print("ambientSound.js: updateDebugOverlay -- entity no longer available " + entity); - } - var options = soundPlaying && soundPlaying.options; - if (options) { - var offset = soundPlaying.playing && ambientSound && (new Date - startTime)/1000 % ambientSound.duration; - var deg = Quat.safeEulerAngles(options.orientation); - var orientation = [ deg.x, deg.y, deg.z].map(Math.round).join(", "); - var volume = options.volume; - } - var info = { - //loudness: soundPlaying.loudness && soundPlaying.loudness.toFixed(4) || undefined, - offset: offset && ("00"+offset.toFixed(1)).substr(-4)+"s" || undefined, - orientation: orientation, - injector: soundPlaying && soundPlaying.playing && "playing", - resource: ambientSound && ambientSound.downloaded && "ready (" + ambientSound.duration.toFixed(1) + "s)", - name: props.name || undefined, - uuid: entity.split(/\W/)[1], // extracts just the first part of the UUID - sound: soundName, - volume: Math.max(0,volume||0).toFixed(2) + " / " + maxVolume.toFixed(2), - distance: (distance||0).toFixed(1) + "m / " + range.toFixed(1) + "m", - state: _debugState.toUpperCase(), - }; - - // Pretty print key/value pairs, excluding any undefined values - var outputText = Object.keys(info).filter(function(key) { - return info[key] !== undefined; - }).map(function(key) { - return key + ": " + info[key]; - }).join("\n"); - - // Calculate a local position for displaying info just above the Entity - var textSize = Overlays.textSize(_debugOverlay, outputText); - var size = { - x: textSize.width + LINEHEIGHT, - y: textSize.height + LINEHEIGHT - }; - var pos = { x: 0, y: props.dimensions.y + size.y/2, z: 0 }; - - var backgroundColor = DEBUG_COLORS[_debugState]; - var backgroundAlpha = backgroundColor ? backgroundColor.alpha : 0.6; - Overlays.editOverlay(_debugOverlay, { - visible: true, - backgroundColor: backgroundColor, - backgroundAlpha: backgroundAlpha, - text: outputText, - localPosition: pos, - size: size, - }); - } - - function _removeDebugOverlays() { - if (_debugOverlay) { - Overlays.deleteOverlay(_debugOverlay); - _debugOverlay = 0; - } - } - - function _createDebugOverlays() { - _debugOverlay = Overlays.addOverlay("text3d", { - visible: true, - lineHeight: LINEHEIGHT, - leftMargin: LINEHEIGHT/2, - topMargin: LINEHEIGHT/2, - localPosition: Vec3.ZERO, - parentID: entity, - ignoreRayIntersection: true, - isFacingAvatar: true, - textAlpha: 0.6, - //drawInFront: true, - }); - } }) From 27a23676345b744465d31195c210a1e2cc8ea886 Mon Sep 17 00:00:00 2001 From: humbletim Date: Tue, 17 Jan 2017 01:27:48 -0500 Subject: [PATCH 4/9] update debugPrints --- scripts/tutorials/entity_scripts/ambientSound.js | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/scripts/tutorials/entity_scripts/ambientSound.js b/scripts/tutorials/entity_scripts/ambientSound.js index 700db4753c..523b96c076 100644 --- a/scripts/tutorials/entity_scripts/ambientSound.js +++ b/scripts/tutorials/entity_scripts/ambientSound.js @@ -80,25 +80,22 @@ debugPrint("Read ambient disabled state: " + disabled); if (disabled) { this.cleanup(); - debugState("disabled"); return; } } } if (!(soundURL === oldSoundURL) || (soundURL === "")) { if (soundURL) { - debugState("downloading", "Loading ambient sound into cache"); + debugPrint("Loading ambient sound into cache"); // Use prefetch to detect URL loading errors var resource = SoundCache.prefetch(soundURL); function onStateChanged() { if (resource.state === Resource.State.FINISHED) { resource.stateChanged.disconnect(onStateChanged); ambientSound = SoundCache.getSound(soundURL); - debugState("idle"); } else if (resource.state === Resource.State.FAILED) { resource.stateChanged.disconnect(onStateChanged); debugPrint("Failed to download ambient sound: " + soundURL); - debugState("error"); } } resource.stateChanged.connect(onStateChanged); @@ -132,7 +129,6 @@ data.disabled = !data.disabled; debugPrint(hint + " -- triggering ambient sound " + (data.disabled ? "OFF" : "ON") + " (" + soundURL + ")"); - var oldState = _debugState; this.cleanup(); @@ -141,7 +137,6 @@ userData: JSON.stringify(data), scriptTimestamp: Math.round(props.age * 1000) }); - //this._updateColor(data.disabled); }; this._updateColor = function(disabled) { @@ -194,7 +189,7 @@ soundOptions.orientation = rotation; soundOptions.volume = volume; if (!soundPlaying && ambientSound && ambientSound.downloaded) { - debugState("playing", "Starting ambient sound: " + soundURL + " (duration: " + ambientSound.duration + ")"); + debugPrint("Starting ambient sound: " + soundURL + " (duration: " + ambientSound.duration + ")"); soundPlaying = Audio.playSound(ambientSound, soundOptions); } else if (soundPlaying && soundPlaying.playing) { soundPlaying.setOptions(soundOptions); @@ -202,7 +197,7 @@ } else if (soundPlaying && soundPlaying.playing && (distance > range * HYSTERESIS_FRACTION)) { soundPlaying.stop(); soundPlaying = false; - debugState("idle", "Out of range, stopping ambient sound: " + soundURL); + debugPrint("Out of range, stopping ambient sound: " + soundURL); } } From 88b7f9ec9d6edbda0659b48aef1594680627f6f3 Mon Sep 17 00:00:00 2001 From: humbletim Date: Tue, 17 Jan 2017 01:44:03 -0500 Subject: [PATCH 5/9] add ambient sound test --- scripts/developer/tests/ambientSoundTest.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 scripts/developer/tests/ambientSoundTest.js diff --git a/scripts/developer/tests/ambientSoundTest.js b/scripts/developer/tests/ambientSoundTest.js new file mode 100644 index 0000000000..2d5fd832c6 --- /dev/null +++ b/scripts/developer/tests/ambientSoundTest.js @@ -0,0 +1,18 @@ +var WAVE = 'http://cdn.rawgit.com/ambisonictoolkit/atk-sounds/aa31005c/stereo/Aurora_Surgit-Lux_Aeterna.wav'; +var uuid = Entities.addEntity({ + type: "Shape", + shape: "Icosahedron", + dimensions: Vec3.HALF, + script: Script.resolvePath('../../tutorials/entity_scripts/ambientSound.js'), + position: Vec3.sum(Vec3.multiply(5, Quat.getFront(MyAvatar.orientation)), MyAvatar.position), + userData: JSON.stringify({ + soundURL: WAVE, + maxVolume: 0.1, + range: 25, + disabled: true, + }), + lifetime: 600, +}); +Script.scriptEnding.connect(function() { + Entities.deleteEntity(uuid); +}); From 7025ed59090ac719412606975b56000e3edb40a9 Mon Sep 17 00:00:00 2001 From: humbletim Date: Tue, 17 Jan 2017 03:18:56 -0500 Subject: [PATCH 6/9] update test script to create a triggerable entity --- scripts/developer/tests/ambientSoundTest.js | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/developer/tests/ambientSoundTest.js b/scripts/developer/tests/ambientSoundTest.js index 2d5fd832c6..5b373715c0 100644 --- a/scripts/developer/tests/ambientSoundTest.js +++ b/scripts/developer/tests/ambientSoundTest.js @@ -10,6 +10,7 @@ var uuid = Entities.addEntity({ maxVolume: 0.1, range: 25, disabled: true, + grabbableKey: { wantsTrigger: true }, }), lifetime: 600, }); From 1048c2a3bf2c099d8912b55096eb48f41bc6c5ce Mon Sep 17 00:00:00 2001 From: humbletim Date: Wed, 18 Jan 2017 01:39:55 -0500 Subject: [PATCH 7/9] apply default userData values; add error checking; throttle toggle clicks --- .../tutorials/entity_scripts/ambientSound.js | 67 ++++++++++++++----- 1 file changed, 52 insertions(+), 15 deletions(-) diff --git a/scripts/tutorials/entity_scripts/ambientSound.js b/scripts/tutorials/entity_scripts/ambientSound.js index 523b96c076..35c9753221 100644 --- a/scripts/tutorials/entity_scripts/ambientSound.js +++ b/scripts/tutorials/entity_scripts/ambientSound.js @@ -27,6 +27,14 @@ var DEFAULT_URL = "http://hifi-content.s3.amazonaws.com/ken/samples/forest_ambiX.wav"; var DEFAULT_VOLUME = 1.0; + var DEFAULT_USERDATA = { + soundURL: DEFAULT_URL, + range: DEFAULT_RANGE, + maxVolume: DEFAULT_VOLUME, + disabled: true, + grabbableKey: { wantsTrigger: true }, + }; + var soundURL = ""; var soundOptions = { loop: true, @@ -60,7 +68,13 @@ var oldSoundURL = soundURL; var props = Entities.getEntityProperties(entity, [ "userData" ]); if (props.userData) { - var data = JSON.parse(props.userData); + try { + var data = JSON.parse(props.userData); + } catch(e) { + debugPrint("unable to parse userData JSON string: " + props.userData); + this.cleanup(); + return; + } if (data.soundURL && !(soundURL === data.soundURL)) { soundURL = data.soundURL; debugPrint("Read ambient sound URL: " + soundURL); @@ -125,18 +139,27 @@ return; } var props = Entities.getEntityProperties(entity, [ "userData", "age", "scriptTimestamp" ]); + if (!props.userData) { + debugPrint("userData is empty; ignoring " + hint); + this.cleanup(); + return; + } var data = JSON.parse(props.userData); data.disabled = !data.disabled; debugPrint(hint + " -- triggering ambient sound " + (data.disabled ? "OFF" : "ON") + " (" + soundURL + ")"); this.cleanup(); + // Prevent rapid-fire toggling (which seems to sometimes lead to sound injectors becoming unstoppable) + this._toggle = this.clickDownOnEntity = function(hint) { debugPrint("ignoring additonal clicks" + hint); }; - // Save the userData and bump scriptTimestamp, which causes all nearby listeners to apply the state change - Entities.editEntity(entity, { - userData: JSON.stringify(data), - scriptTimestamp: Math.round(props.age * 1000) - }); + Script.setTimeout(function() { + // Save the userData and bump scriptTimestamp, which causes all nearby listeners to apply the state change + Entities.editEntity(entity, { + userData: JSON.stringify(data), + scriptTimestamp: props.scriptTimestamp + 1 + }); + }, 250); }; this._updateColor = function(disabled) { @@ -155,21 +178,35 @@ this.preload = function(entityID) { // Load the sound and range from the entity userData fields, and note the position of the entity. - debugPrint("Ambient sound preload"); + debugPrint("Ambient sound preload " + entityID); entity = entityID; _this = this; - var props = Entities.getEntityProperties(entity, [ "userData" ]); + var props = Entities.getEntityProperties(entity, [ "name", "userData" ]); + var data = {}; if (props.userData) { - var data = JSON.parse(props.userData); - this._updateColor(data.disabled); - if (data.disabled) { - _this.maybeUpdate(); - return; + data = JSON.parse(props.userData); + } + var changed = false; + for(var p in DEFAULT_USERDATA) { + if (!(p in data)) { + data[p] = DEFAULT_USERDATA[p]; + changed = true; } } - - checkTimer = Script.setInterval(_this.maybeUpdate, UPDATE_INTERVAL_MSECS); + if (!data.grabbableKey.wantsTrigger) { + data.grabbableKey.wantsTrigger = true; + changed = true; + } + if (changed) { + debugPrint("applying default values to userData"); + Entities.editEntity(entity, { userData: JSON.stringify(data) }); + } + this._updateColor(data.disabled); + this.updateSettings(); + if (!data.disabled) { + checkTimer = Script.setInterval(_this.maybeUpdate, UPDATE_INTERVAL_MSECS); + } }; this.maybeUpdate = function() { From f88b39918f8281dd314a188fc41560016727f53f Mon Sep 17 00:00:00 2001 From: humbletim Date: Wed, 18 Jan 2017 02:54:42 -0500 Subject: [PATCH 8/9] switch to messaging for toggle notifications; cleanup --- .../tutorials/entity_scripts/ambientSound.js | 57 +++++++++++-------- 1 file changed, 34 insertions(+), 23 deletions(-) diff --git a/scripts/tutorials/entity_scripts/ambientSound.js b/scripts/tutorials/entity_scripts/ambientSound.js index 35c9753221..810c9769b8 100644 --- a/scripts/tutorials/entity_scripts/ambientSound.js +++ b/scripts/tutorials/entity_scripts/ambientSound.js @@ -92,12 +92,16 @@ if ("disabled" in data && !(disabled === data.disabled)) { disabled = data.disabled; debugPrint("Read ambient disabled state: " + disabled); - if (disabled) { - this.cleanup(); - return; - } + this._updateColor(disabled); } } + if (disabled) { + this.cleanup(); + soundURL = ""; + return; + } else if (!checkTimer) { + checkTimer = Script.setInterval(_this.maybeUpdate, UPDATE_INTERVAL_MSECS); + } if (!(soundURL === oldSoundURL) || (soundURL === "")) { if (soundURL) { debugPrint("Loading ambient sound into cache"); @@ -138,7 +142,7 @@ if (Settings.getValue("io.highfidelity.isEditting")) { return; } - var props = Entities.getEntityProperties(entity, [ "userData", "age", "scriptTimestamp" ]); + var props = Entities.getEntityProperties(entity, [ "userData" ]); if (!props.userData) { debugPrint("userData is empty; ignoring " + hint); this.cleanup(); @@ -147,19 +151,15 @@ var data = JSON.parse(props.userData); data.disabled = !data.disabled; - debugPrint(hint + " -- triggering ambient sound " + (data.disabled ? "OFF" : "ON") + " (" + soundURL + ")"); + debugPrint(hint + " -- triggering ambient sound " + (data.disabled ? "OFF" : "ON") + " (" + data.soundURL + ")"); this.cleanup(); - // Prevent rapid-fire toggling (which seems to sometimes lead to sound injectors becoming unstoppable) - this._toggle = this.clickDownOnEntity = function(hint) { debugPrint("ignoring additonal clicks" + hint); }; - Script.setTimeout(function() { - // Save the userData and bump scriptTimestamp, which causes all nearby listeners to apply the state change - Entities.editEntity(entity, { - userData: JSON.stringify(data), - scriptTimestamp: props.scriptTimestamp + 1 - }); - }, 250); + // Save the userData and notify nearby listeners of the change + Entities.editEntity(entity, { + userData: JSON.stringify(data) + }); + Messages.sendMessage(entity, "toggled"); }; this._updateColor = function(disabled) { @@ -182,7 +182,7 @@ entity = entityID; _this = this; - var props = Entities.getEntityProperties(entity, [ "name", "userData" ]); + var props = Entities.getEntityProperties(entity, [ "userData" ]); var data = {}; if (props.userData) { data = JSON.parse(props.userData); @@ -204,8 +204,17 @@ } this._updateColor(data.disabled); this.updateSettings(); - if (!data.disabled) { - checkTimer = Script.setInterval(_this.maybeUpdate, UPDATE_INTERVAL_MSECS); + + // Subscribe to toggle notifications using entity ID as a channel name + Messages.subscribe(entity); + Messages.messageReceived.connect(this, "_onMessageReceived"); + }; + + this._onMessageReceived = function(channel, message, sender, local) { + // Handle incoming toggle notifications + if (channel === entity && message === "toggled"/*&& sender !== MyAvatar.sessionUUID*/) { + debugPrint("received " + message + " from " + sender); + this.updateSettings(); } }; @@ -214,9 +223,9 @@ _this.updateSettings(); var HYSTERESIS_FRACTION = 0.1; var props = Entities.getEntityProperties(entity, [ "position", "rotation" ]); - if (!props.position) { - print("FIXME: ambientSound.js -- expected Entity unavailable!") - return _this.cleanup(); + if (disabled || !props.position) { + _this.cleanup(); + return; } center = props.position; rotation = props.rotation; @@ -236,11 +245,13 @@ soundPlaying = false; debugPrint("Out of range, stopping ambient sound: " + soundURL); } - } + }; this.unload = function(entityID) { - debugPrint("Ambient sound unload "); + debugPrint("Ambient sound unload"); this.cleanup(); + Messages.unsubscribe(entity); + Messages.messageReceived.disconnect(this, "_onMessageReceived"); }; this.cleanup = function() { From 6320d872b40a8f6332e82097fbddccae98c62bec Mon Sep 17 00:00:00 2001 From: humbletim Date: Wed, 18 Jan 2017 02:57:13 -0500 Subject: [PATCH 9/9] remove commented code --- scripts/tutorials/entity_scripts/ambientSound.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/tutorials/entity_scripts/ambientSound.js b/scripts/tutorials/entity_scripts/ambientSound.js index 810c9769b8..e0a7d0a3cf 100644 --- a/scripts/tutorials/entity_scripts/ambientSound.js +++ b/scripts/tutorials/entity_scripts/ambientSound.js @@ -212,7 +212,7 @@ this._onMessageReceived = function(channel, message, sender, local) { // Handle incoming toggle notifications - if (channel === entity && message === "toggled"/*&& sender !== MyAvatar.sessionUUID*/) { + if (channel === entity && message === "toggled") { debugPrint("received " + message + " from " + sender); this.updateSettings(); }