diff --git a/unpublishedScripts/marketplace/gameTable/README.md b/unpublishedScripts/marketplace/gameTable/README.md index 86764b8b7e..f089f97562 100644 --- a/unpublishedScripts/marketplace/gameTable/README.md +++ b/unpublishedScripts/marketplace/gameTable/README.md @@ -47,6 +47,4 @@ PUBLISHING ============= - As a script: just add createGameTable.js to the marketplace. -- As an item: runcreateGameTable.js and select everything, export it to json. Go through the usual marketplace uploading and prep sequence. - - +- As an item: run createGameTable.js and select everything, export it to json. Go through the usual marketplace uploading and prep sequence. diff --git a/unpublishedScripts/marketplace/gameTable/createGameTable.js b/unpublishedScripts/marketplace/gameTable/createGameTable.js index 7ce084f413..d30bd4608b 100644 --- a/unpublishedScripts/marketplace/gameTable/createGameTable.js +++ b/unpublishedScripts/marketplace/gameTable/createGameTable.js @@ -8,16 +8,15 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -var CLEARCACHE = "?"+Math.random().toString(36).substring(7); -var TABLE_MODEL_URL = Script.resolvePath('assets/table/gameTable.fbx') + CLEARCACHE; -var MODEL_URL = Script.resolvePath('assets/table/finalFrame.fbx') + CLEARCACHE; -var TABLE_SCRIPT_URL = Script.resolvePath('table.js') + CLEARCACHE; -var ENTITY_SPAWNER_SCRIPT_URL = Script.resolvePath('entitySpawner.js') + CLEARCACHE; -var NEXT_GAME_BUTTON_SCRIPT_URL = Script.resolvePath('nextGameButton.js') + CLEARCACHE; -var RESET_BUTTON_SCRIPT_URL = Script.resolvePath('resetGameButton.js') + CLEARCACHE; -var TABLE_PICTURE_URL = Script.resolvePath('assets/mats/Table-default.jpg') + CLEARCACHE; -var NEXT_BUTTON_MODEL_URL = Script.resolvePath('assets/buttons/button-next.fbx') + CLEARCACHE; -var RESET_BUTTON_MODEL_URL = Script.resolvePath('assets/buttons/button-reset.fbx') + CLEARCACHE; +var TABLE_MODEL_URL = Script.resolvePath('assets/table/gameTable.fbx'); +var MODEL_URL = Script.resolvePath('assets/table/finalFrame.fbx'); +var TABLE_SCRIPT_URL = Script.resolvePath('table.js'); +var ENTITY_SPAWNER_SCRIPT_URL = Script.resolvePath('entitySpawner.js'); +var NEXT_GAME_BUTTON_SCRIPT_URL = Script.resolvePath('nextGameButton.js'); +var RESET_BUTTON_SCRIPT_URL = Script.resolvePath('resetGameButton.js'); +var TABLE_PICTURE_URL = Script.resolvePath('assets/mats/Table-default.jpg'); +var NEXT_BUTTON_MODEL_URL = Script.resolvePath('assets/buttons/button-next.fbx'); +var RESET_BUTTON_MODEL_URL = Script.resolvePath('assets/buttons/button-reset.fbx'); // FIXME: CHANGE TO Quat.getForward when supported var front = Quat.getFront(MyAvatar.orientation); @@ -52,11 +51,11 @@ var resetGameButtonOffset = { }; function getOffsetFromTable(forward, vertical, right) { - var props = Entities.getEntityProperties(table); - var position = props.position; - var frontVector = Quat.getFront(props.rotation); - var upVector = Quat.getUp(props.rotation); - var rightVector = Quat.getRight(props.rotation); + var properties = Entities.getEntityProperties(table, ['position', 'rotation']); + var position = properties.position; + var frontVector = Quat.getFront(properties.rotation); + var upVector = Quat.getUp(properties.rotation); + var rightVector = Quat.getRight(properties.rotation); if (forward !== undefined) { position = Vec3.sum(position, Vec3.multiply(frontVector, forward)); } @@ -71,7 +70,7 @@ function getOffsetFromTable(forward, vertical, right) { } function createTable() { - var props = { + table = Entities.addEntity({ type: 'Model', name: 'GameTable Table 1', description: 'hifi:gameTable:table', @@ -105,13 +104,11 @@ function createTable() { grabbable: true } }) - }; - - table = Entities.addEntity(props); + }); } function createEntitySpawner() { - var props = { + entitySpawner = Entities.addEntity({ type: 'Zone', visible: false, name: 'GameTable Entity Spawner', @@ -130,14 +127,11 @@ function createEntitySpawner() { script: ENTITY_SPAWNER_SCRIPT_URL, parentID: table, position: getOffsetFromTable(entitySpawnerOffset.forward, entitySpawnerOffset.vertical, entitySpawnerOffset.right) - }; - - entitySpawner = Entities.addEntity(props); + }); } - function createMat() { - var props = { + return Entities.addEntity({ type: 'Model', modelURL: MODEL_URL, name: 'GameTable Mat', @@ -166,13 +160,11 @@ function createMat() { grabbable: false } }) - }; - - return Entities.addEntity(props); + }); } function createNextGameButton() { - var props = { + nextGameButton = Entities.addEntity({ type: 'Model', modelURL: NEXT_BUTTON_MODEL_URL, name: 'GameTable Next Button', @@ -195,19 +187,18 @@ function createNextGameButton() { }), parentID: table, script: NEXT_GAME_BUTTON_SCRIPT_URL, - position: getOffsetFromTable(nextGameButtonOffset.forward, nextGameButtonOffset.vertical, nextGameButtonOffset.right), + position: getOffsetFromTable(nextGameButtonOffset.forward, nextGameButtonOffset.vertical, + nextGameButtonOffset.right), userData: JSON.stringify({ grabbableKey: { wantsTrigger: true } }) - }; - - nextGameButton = Entities.addEntity(props); + }); } function createResetGameButton() { - var props = { + resetGameButton = Entities.addEntity({ type: 'Model', modelURL: RESET_BUTTON_MODEL_URL, name: 'GameTable Reset Button', @@ -230,15 +221,14 @@ function createResetGameButton() { }), parentID: table, script: RESET_BUTTON_SCRIPT_URL, - position: getOffsetFromTable(resetGameButtonOffset.forward, resetGameButtonOffset.vertical, resetGameButtonOffset.right), + position: getOffsetFromTable(resetGameButtonOffset.forward, resetGameButtonOffset.vertical, + resetGameButtonOffset.right), userData: JSON.stringify({ grabbableKey: { wantsTrigger: true } }) - }; - - resetGameButton = Entities.addEntity(props); + }); } function makeTable() { diff --git a/unpublishedScripts/marketplace/gameTable/entitySpawner.js b/unpublishedScripts/marketplace/gameTable/entitySpawner.js index dcee2f0652..f07b7c764e 100644 --- a/unpublishedScripts/marketplace/gameTable/entitySpawner.js +++ b/unpublishedScripts/marketplace/gameTable/entitySpawner.js @@ -9,10 +9,10 @@ (function() { var _this; - var pasted_cache = {}; + var entityJSONCache = {}; - const SANITIZE_PROPERTIES = ['childEntities', 'parentID', 'id']; - const ZERO_UUID = '{00000000-0000-0000-0000-000000000000}'; + var SANITIZE_PROPERTIES = ['childEntities', 'parentID', 'id']; + var ZERO_UUID = '{00000000-0000-0000-0000-000000000000}'; function entityListToTree(entitiesList) { function entityListToTreeRecursive(properties) { @@ -33,7 +33,6 @@ return entityTree; } - // TODO: ATP support (currently the JS API for ATP does not support file links, only hashes) function importEntitiesJSON(importLink, parentProperties, overrideProperties) { if (parentProperties === undefined) { parentProperties = {}; @@ -41,12 +40,23 @@ if (overrideProperties !== undefined) { parentProperties.overrideProperties = overrideProperties; } - var request = new XMLHttpRequest(); - request.open('GET', importLink, false); - request.send(); + // FIXME: HACK: remove when Script.require is in release client (Beta Release 37) + if (Script.require === undefined) { + var request = new XMLHttpRequest(); + request.open('GET', importLink, false); + request.send(); + try { + var response = JSON.parse(request.responseText); + parentProperties.childEntities = entityListToTree(response.Entities); + return parentProperties; + } catch (e) { + print('Failed importing entities JSON because: ' + JSON.stringify(e)); + } + return null; + } try { - var response = JSON.parse(request.responseText); - parentProperties.childEntities = entityListToTree(response.Entities); + var entityJSONImport = Script.require(importLink).Entities; + parentProperties.childEntities = entityListToTree(entityJSONImport.Entities); return parentProperties; } catch (e) { print('Failed importing entities JSON because: ' + JSON.stringify(e)); @@ -61,7 +71,7 @@ return link; } - //Creates an entity and returns a mixed object of the creation properties and the assigned entityID + // Creates an entity and returns a mixed object of the creation properties and the assigned entityID var createEntity = function(entityProperties, parent, overrideProperties) { // JSON.stringify -> JSON.parse trick to create a fresh copy of JSON data var newEntityProperties = JSON.parse(JSON.stringify(entityProperties)); @@ -80,7 +90,7 @@ if (parent.position !== undefined) { var localPosition = (parent.rotation !== undefined) ? Vec3.multiplyQbyV(parent.rotation, newEntityProperties.position) : newEntityProperties.position; - newEntityProperties.position = Vec3.sum(localPosition, parent.position) + newEntityProperties.position = Vec3.sum(localPosition, parent.position); } if (parent.id !== undefined) { newEntityProperties.parentID = parent.id; @@ -127,46 +137,44 @@ return createdTree; }; - //listens for a release message from entities with the snap to grid script - //checks for the nearest snap point and sends a message back to the entity - function PastedItem(url, spawnLocation, spawnRotation) { + // listens for a release message from entities with the snap to grid script + // checks for the nearest snap point and sends a message back to the entity + function ImportGamePiece(url, spawnLocation, spawnRotation) { var fullURL = Script.resolvePath(url); print('CREATE PastedItem FROM SPAWNER: ' + fullURL); - var created = []; + var _created = []; function create() { var entitiesTree; - if (pasted_cache[fullURL]) { - entitiesTree = pasted_cache[fullURL]; - //print('used cache'); + if (entityJSONCache[fullURL]) { + entitiesTree = entityJSONCache[fullURL]; } else { entitiesTree = importEntitiesJSON(fullURL); - pasted_cache[fullURL] = entitiesTree; - //print('moved to cache'); + entityJSONCache[fullURL] = entitiesTree; } entitiesTree.position = spawnLocation; entitiesTree.rotation = spawnRotation; - //print('entityTree: ' + JSON.stringify(entitiesTree)); + // print('entityTree: ' + JSON.stringify(entitiesTree)); - //var entities = importEntitiesJSON(fullURL); - //var success = Clipboard.importEntities(fullURL); - //var dimensions = Clipboard.getContentsDimensions(); - //we want the bottom of any piece to actually be on the board, so we add half of the height of the piece to the location when we paste it, - //spawnLocation.y += (0.5 * dimensions.y); - //if (success === true) { - //created = Clipboard.pasteEntities(spawnLocation); + // var entities = importEntitiesJSON(fullURL); + // var success = Clipboard.importEntities(fullURL); + // var dimensions = Clipboard.getContentsDimensions(); + // we want the bottom of any piece to actually be on the board, so we add half of the height of the piece to the location when we paste it, + // spawnLocation.y += (0.5 * dimensions.y); + // if (success === true) { + // created = Clipboard.pasteEntities(spawnLocation); // this.created = created; // print('created ' + created); - //} - this.created = createEntitiesFromTree([entitiesTree]); + // } + _created = createEntitiesFromTree([entitiesTree]); } function cleanup() { - created.forEach(function(obj) { + _created.forEach(function(obj) { print('removing: ' + JSON.stringify(obj)); Entities.deleteEntity(obj.id); - }) + }); } create(); @@ -177,7 +185,6 @@ function Tile(rowIndex, columnIndex) { var side = _this.tableSideSize / _this.game.startingArrangement.length; - var rightAmount = rowIndex * side; rightAmount += (0.5 * side); var forwardAmount = columnIndex * side; @@ -196,14 +203,13 @@ this.url = Script.resolvePath(_this.game.pieces[0][splitURL[1]]); } if (splitURL[0] === '2') { - this.url = Script.resolvePath(_this.game.pieces[1][splitURL[1]]) + this.url = Script.resolvePath(_this.game.pieces[1][splitURL[1]]); } if (splitURL[0] === 'empty') { this.url = 'empty'; } } - function EntitySpawner() { _this = this; } @@ -223,7 +229,7 @@ if (url === 'empty') { return null; } - var item = new PastedItem(url, spawnLocation, spawnRotation); + var item = new ImportGamePiece(url, spawnLocation, spawnRotation); _this.items.push(item); return item; }, @@ -234,38 +240,40 @@ textures: JSON.stringify({ Picture: fullURL }) - }) + }); }, spawnEntities: function(id, params) { this.items = []; - var dimensions = Entities.getEntityProperties(params[1]).dimensions; + var matEntity = params[1]; + var matProperties = Entities.getEntityProperties(matEntity, ['dimensions', 'position', 'rotation', + 'parentID']); + var dimensions = Entities.getEntityProperties(matEntity, 'dimensions').dimensions; _this.game = JSON.parse(params[0]); - _this.matDimensions = dimensions; - _this.matCenter = Entities.getEntityProperties(params[1]).position; + _this.matDimensions = matProperties.dimensions; + _this.matCenter = matProperties.position; _this.matCorner = { x: _this.matCenter.x - (dimensions.x * 0.5), y: _this.matCenter.y, z: _this.matCenter.z + (dimensions.y * 0.5) }; - _this.matRotation = Entities.getEntityProperties(params[1]).rotation; - var parentID = Entities.getEntityProperties(params[1]).parentID; - _this.tableRotation = Entities.getEntityProperties(parentID).rotation; + _this.matRotation = matProperties.rotation; + var tableID = matProperties.parentID; + _this.tableRotation = Entities.getEntityProperties(tableID, 'rotation').rotation; _this.tableSideSize = dimensions.x; - _this.changeMatPicture(params[1]); - if (this.game.spawnStyle === "pile") { + _this.changeMatPicture(matEntity); + if (_this.game.spawnStyle === 'pile') { _this.spawnByPile(); - } else if (this.game.spawnStyle === "arranged") { + } else if (_this.game.spawnStyle === 'arranged') { _this.spawnByArranged(); } - }, spawnByPile: function() { - var props = Entities.getEntityProperties(_this.entityID); + var position = Entities.getEntityProperties(_this.entityID, 'position').position; for (var i = 0; i < _this.game.howMany; i++) { var spawnLocation = { - x: props.position.x, - y: props.position.y - 0.25, - z: props.position.z + x: position.x, + y: position.y - 0.25, + z: position.z }; var url; if (_this.game.identicalPieces === false) { @@ -273,22 +281,19 @@ } else { url = Script.resolvePath(_this.game.pieces[0]); } - _this.createSingleEntity(url, spawnLocation, _this.tableRotation); } }, spawnByArranged: function() { // make sure to set userData.gameTable.attachedTo appropriately _this.setupGrid(); - }, - createDebugEntity: function(position) { return Entities.addEntity({ type: 'Sphere', position: { x: position.x, - y: position.y += 0.1, + y: position.y + 0.1, z: position.z }, color: { @@ -302,9 +307,8 @@ z: 0.1 }, collisionless: true - }) + }); }, - setupGrid: function() { _this.tiles = []; @@ -330,12 +334,10 @@ } } }, - findMidpoint: function(start, end) { var xy = Vec3.sum(start, end); return Vec3.multiply(0.5, xy); }, - createAnchorEntityAtPoint: function(position) { var properties = { type: 'Zone', @@ -348,39 +350,37 @@ y: 0.075, z: 0.075 }, - parentID: Entities.getEntityProperties(_this.entityID).id, + parentID: _this.entityID, position: position, userData: 'available' }; return Entities.addEntity(properties); }, - setCurrentUserData: function(data) { - var userData = getCurrentUserData(); + var userData = _this.getCurrentUserData(); userData.gameTableData = data; Entities.editEntity(_this.entityID, { userData: userData }); }, getCurrentUserData: function() { - var props = Entities.getEntityProperties(_this.entityID); - var json = null; + var userData = Entities.getEntityProperties(_this.entityID).userData; try { - json = JSON.parse(props.userData); + return JSON.parse(userData); } catch (e) { - return; + // e } - return json; + return null; }, cleanupEntitiesList: function() { _this.items.forEach(function(item) { item.cleanup(); - }) + }); }, unload: function() { _this.toCleanup.forEach(function(item) { Entities.deleteEntity(item); - }) + }); } }; return new EntitySpawner(); diff --git a/unpublishedScripts/marketplace/gameTable/games/deckOfCards/deckOfCards.js b/unpublishedScripts/marketplace/gameTable/games/deckOfCards/deckOfCards.js index 390882c016..4fd47fcb0e 100644 --- a/unpublishedScripts/marketplace/gameTable/games/deckOfCards/deckOfCards.js +++ b/unpublishedScripts/marketplace/gameTable/games/deckOfCards/deckOfCards.js @@ -1,3 +1,14 @@ +// +// Created by Thijs Wenker on 3/31/2017 +// Copyright 2017 High Fidelity, Inc. +// +// Revision of James B. Pollack's work on GamesTable in 2016 +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +// TODO: This game needs some work to get running (function() { var _this; var MAPPING_NAME = "hifi-gametable-cards-dev-" + Math.random(); @@ -23,7 +34,6 @@ blue: 0 }; - var SETUP_DELAY = 2000; var NEARBY_CARDS_RANGE = 5; function DeckOfCards() { @@ -44,15 +54,15 @@ createMapping: function() { var mapping = Controller.newMapping(MAPPING_NAME); mapping.from([Controller.Standard.RTClick]).peek().to(function(val) { - _this.handleTrigger(val, 'right') + _this.handleTrigger(val, 'right'); }); mapping.from([Controller.Standard.LTClick]).peek().to(function(val) { - _this.handleTrigger(val, 'left') + _this.handleTrigger(val, 'left'); }); Controller.enableMapping(MAPPING_NAME); }, destroyMapping: function() { - Controller.disableMapping(MAPPING_NAME) + Controller.disableMapping(MAPPING_NAME); }, handleTrigger: function(val, hand) { if (val !== 1) { @@ -61,7 +71,7 @@ print('jbp trigger pulled at val:' + val + ":" + hand); print('jbp at time hand was:' + _this.currentHand); if (_this.currentHand === hand) { - print('jbp should ignore its the same hand') + print('jbp should ignore its the same hand'); } else { print('jbp should make a new thing its the off hand'); _this.createPlayingCard(); @@ -72,35 +82,36 @@ var cards = _this.getCardsFromUserData(); if (cards === false) { print('jbp should make new deck'); + // should make a deck the first time _this.makeNewDeck(); - //should make a deck the first time - return; } else { print('jbp already has deck' + cards); - //someone already started a game with this deck + // someone already started a game with this deck _this.makeNewDeck(); - _this.currentStack._import(cards) + _this.currentStack._import(cards); } }, resetDeck: function() { - print('jbp resetting deck') - //finds and delete any nearby cards - var myProps = Entities.getEntityProperties(_this.entityID); - var results = Entities.findEntities(myProps.position, NEARBY_CARDS_RANGE); + print('jbp resetting deck'); + // finds and delete any nearby cards + var position = Entities.getEntityProperties(_this.entityID, 'position'); + var results = Entities.findEntities(position, NEARBY_CARDS_RANGE); results.forEach(function(item) { - var itemProps = Entities.getEntityProperties(item); - if (itemProps.userData.hasOwnProperty('playingCards') && itemProps.userData.playingCards.hasOwnProperty('card')) { - Entities.deleteEntity(item); - } - }); - //resets this deck to a new deck + var itemProps = Entities.getEntityProperties(item, 'userData'); + if (itemProps.userData.hasOwnProperty('playingCards') && + itemProps.userData.playingCards.hasOwnProperty('card')) { + + Entities.deleteEntity(item); + } + }); + // resets this deck to a new deck _this.makeNewDeck(); }, makeNewDeck: function() { print('jbp make new deck'); - //make a stack and shuffle it up. + // make a stack and shuffle it up. var stack = new Stack(); stack.makeDeck(1); stack.shuffle(100); @@ -108,20 +119,20 @@ }, collisionWithEntity: function(me, other, collision) { - //on the start of a collision with the deck, if its a card, add it back to the deck + // on the start of a collision with the deck, if its a card, add it back to the deck if (collision.type !== 0) { - //its not the start, so exit early. + // its not the start, so exit early. return; } - var otherProps = Entities.getEntityProperties(other); + var otherProps = Entities.getEntityProperties(other, 'userData'); var userData = {}; try { - JSON.parse(otherProps.userData) + userData = JSON.parse(otherProps.userData); } catch (e) { - return + return; } if (userData.hasOwnProperty('playingCards') && userData.playingCards.hasOwnProperty('card')) { - print('collided with a playing card!!!') + print('collided with a playing card!!!'); _this.currentStack.addCard(userData.playingCards.card); @@ -171,26 +182,26 @@ exitDealerMode: function() { _this.destroyMapping(); - //turn grab on - //save the cards - //delete the overlay beam + // turn grab on + // save the cards + // delete the overlay beam if (_this.updateConnected === true) { Script.update.disconnect(_this.updateRays); } Messages.sendLocalMessage('Hifi-Hand-Disabler', 'none'); - _this.deleteCardTargetOverlay() + _this.deleteCardTargetOverlay(); _this.turnOffOverlayBeams(); _this.storeCards(); }, storeCards: function() { var cards = _this.currentStack._export(); - print('deckof cards:' + cards) + print('deck of cards: ' + cards); Entities.editEntity(_this.entityID, { userData: JSON.stringify({ cards: cards }) - }) + }); }, restoreCards: function() { @@ -199,28 +210,28 @@ }, getCardsFromUserData: function() { - var props = Entities.getEntityProperties(_this.entityID); + var props = Entities.getEntityProperties(_this.entityID, 'userData'); var data; try { data = JSON.parse(props.userData); - print('jbp has cards in userdata' + props.userData) + print('jbp has cards in userdata' + props.userData); } catch (e) { - print('jbp error parsing userdata') + print('jbp error parsing userdata'); return false; } if (data.hasOwnProperty('cards')) { - print('jbp returning data.cards') + print('jbp returning data.cards'); return data.cards; - } else { - return false } - + return false; }, rightRay: function() { var pose = Controller.getPoseValue(Controller.Standard.RightHand); - var rightPosition = pose.valid ? Vec3.sum(Vec3.multiplyQbyV(MyAvatar.orientation, pose.translation), MyAvatar.position) : MyAvatar.getHeadPosition(); + var rightPosition = pose.valid ? + Vec3.sum(Vec3.multiplyQbyV(MyAvatar.orientation, pose.translation), MyAvatar.position) : + MyAvatar.getHeadPosition(); var rightRotation = pose.valid ? Quat.multiply(MyAvatar.orientation, pose.rotation) : Quat.multiply(MyAvatar.headOrientation, Quat.angleAxis(-90, { x: 1, @@ -230,7 +241,7 @@ var rightPickRay = { origin: rightPosition, - direction: Quat.getUp(rightRotation), + direction: Quat.getUp(rightRotation) }; this.rightPickRay = rightPickRay; @@ -250,9 +261,7 @@ } else { this.rightLineOn(rightPickRay.origin, location, COLORS_CANNOT_PLACE); } - }, - leftRay: function() { var pose = Controller.getPoseValue(Controller.Standard.LeftHand); var leftPosition = pose.valid ? Vec3.sum(Vec3.multiplyQbyV(MyAvatar.orientation, pose.translation), MyAvatar.position) : MyAvatar.getHeadPosition(); @@ -265,7 +274,7 @@ var leftPickRay = { origin: leftPosition, - direction: Quat.getUp(leftRotation), + direction: Quat.getUp(leftRotation) }; this.leftPickRay = leftPickRay; @@ -285,10 +294,7 @@ } else { this.leftLineOn(leftPickRay.origin, location, COLORS_CANNOT_PLACE); } - - }, - rightLineOn: function(closePoint, farPoint, color) { if (this.rightOverlayLine === null) { var lineProperties = { @@ -306,14 +312,13 @@ this.rightOverlayLine = Overlays.addOverlay("line3d", lineProperties); } else { - var success = Overlays.editOverlay(this.rightOverlayLine, { + Overlays.editOverlay(this.rightOverlayLine, { start: closePoint, end: farPoint, color: color }); } }, - leftLineOn: function(closePoint, farPoint, color) { if (this.leftOverlayLine === null) { var lineProperties = { @@ -331,54 +336,33 @@ this.leftOverlayLine = Overlays.addOverlay("line3d", lineProperties); } else { - var success = Overlays.editOverlay(this.leftOverlayLine, { + Overlays.editOverlay(this.leftOverlayLine, { start: closePoint, end: farPoint, color: color }); } }, - rightOverlayOff: function() { if (this.rightOverlayLine !== null) { - print('jbp inside right off') + print('jbp inside right off'); Overlays.deleteOverlay(this.rightOverlayLine); this.rightOverlayLine = null; } }, - leftOverlayOff: function() { if (this.leftOverlayLine !== null) { - print('jbp inside left off') + print('jbp inside left off'); Overlays.deleteOverlay(this.leftOverlayLine); this.leftOverlayLine = null; } }, - turnOffOverlayBeams: function() { this.rightOverlayOff(); this.leftOverlayOff(); }, - - rightOverlayOff: function() { - print('jbp right overlay off') - if (this.rightOverlayLine !== null) { - Overlays.deleteOverlay(this.rightOverlayLine); - this.rightOverlayLine = null; - } - }, - - leftOverlayOff: function() { - print('jbp left overlay off') - if (this.leftOverlayLine !== null) { - Overlays.deleteOverlay(this.leftOverlayLine); - this.leftOverlayLine = null; - } - }, - createTargetOverlay: function() { - - print('jbp should create target overlay') + print('jbp should create target overlay'); if (_this.targetOverlay !== null) { return; } @@ -392,7 +376,7 @@ _this.targetOverlay = Overlays.addOverlay("model", targetOverlayProps); - print('jbp created target overlay: ' + _this.targetOverlay) + print('jbp created target overlay: ' + _this.targetOverlay); }, updateTargetOverlay: function(intersection) { @@ -423,11 +407,11 @@ _this.targetOverlay = null; }, handleEndOfDeck: function() { - print('jbp at the end of the deck, no more.') + print('jbp at the end of the deck, no more.'); }, createPlayingCard: function() { - print('jbp should create playing card') + print('jbp should create playing card'); if (_this.currentStack.cards.length > 0) { var card = _this.currentStack.draw(1); } else { @@ -435,7 +419,7 @@ return; } - print('jbp drew card: ' + card) + print('jbp drew card: ' + card); var properties = { type: 'Model', description: 'hifi:gameTable:game:playingCards', @@ -452,7 +436,7 @@ }, textures: JSON.stringify({ file1: PLAYING_CARD_BACK_IMAGE_URL, - file2: PLAYING_CARD_BACK_IMAGE_URL, + file2: PLAYING_CARD_BACK_IMAGE_URL }), userData: JSON.stringify({ grabbableKey: { @@ -462,11 +446,11 @@ card: card } }) - } + }; Entities.addEntity(properties); } - } + }; function Card(rank, suit) { this.rank = rank; @@ -474,14 +458,14 @@ } function stackImportCards(exportedCards) { - print('jbp importing ' + exportedCards) + print('jbp importing ' + exportedCards); var cards = JSON.parse(exportedCards); this.cards = []; var cardArray = this.cards; cards.forEach(function(card) { var newCard = new Card(card.substr(1, card.length), card[0]); - cardArray.push(newCard) - }) + cardArray.push(newCard); + }); } function stackExportCards() { @@ -499,9 +483,8 @@ function stackMakeDeck(n) { - var ranks = new Array("A", "2", "3", "4", "5", "6", "7", "8", "9", - "10", "J", "Q", "K"); - var suits = new Array("C", "D", "H", "S"); + var ranks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]; + var suits = ["C", "D", "H", "S"]; var i, j, k; var m; @@ -509,15 +492,17 @@ // Set array of cards. - this.cards = new Array(); + this.cards = []; // Fill the array with 'n' packs of cards. - for (i = 0; i < n; i++) - for (j = 0; j < suits.length; j++) - for (k = 0; k < ranks.length; k++) - this.cards[i * m + j * ranks.length + k] = - new Card(ranks[k], suits[j]); + for (i = 0; i < n; i++) { + for (j = 0; j < suits.length; j++) { + for (k = 0; k < ranks.length; k++) { + this.cards[i * m + j * ranks.length + k] = new Card(ranks[k], suits[j]); + } + } + } } function stackShuffle(n) { @@ -527,21 +512,21 @@ // Shuffle the stack 'n' times. - for (i = 0; i < n; i++) + for (i = 0; i < n; i++) { for (j = 0; j < this.cards.length; j++) { k = Math.floor(Math.random() * this.cards.length); temp = this.cards[j]; this.cards[j] = this.cards[k]; this.cards[k] = temp; } + } } function stackDeal() { - - if (this.cards.length > 0) + if (this.cards.length > 0) { return this.cards.shift(); - else - return null; + } + return null; } function stackDraw(n) { @@ -551,8 +536,9 @@ if (n >= 0 && n < this.cards.length) { card = this.cards[n]; this.cards.splice(n, 1); - } else + } else { card = null; + } return card; } @@ -565,14 +551,14 @@ function stackCombine(stack) { this.cards = this.cards.concat(stack.cards); - stack.cards = new Array(); + stack.cards = []; } function Stack() { // Create an empty array of cards. - this.cards = new Array(); + this.cards = []; this.makeDeck = stackMakeDeck; this.shuffle = stackShuffle; diff --git a/unpublishedScripts/marketplace/gameTable/games/deckOfCards/playingCard.js b/unpublishedScripts/marketplace/gameTable/games/deckOfCards/playingCard.js index ed5910117f..4a28fc09fd 100644 --- a/unpublishedScripts/marketplace/gameTable/games/deckOfCards/playingCard.js +++ b/unpublishedScripts/marketplace/gameTable/games/deckOfCards/playingCard.js @@ -1,3 +1,14 @@ +// +// Created by Thijs Wenker on 3/31/2017 +// Copyright 2017 High Fidelity, Inc. +// +// Revision of James B. Pollack's work on GamesTable in 2016 +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +// TODO: This game needs some work to get running (function() { var _this; @@ -14,8 +25,8 @@ preload: function(id) { _this.entityID = id; }, - startDistanceGrab:function(){ - _this.attachCardOverlay(); + startDistanceGrab:function() { + _this.attachCardOverlay(); }, startNearGrab: function() { _this.attachCardOverlay(); @@ -24,8 +35,8 @@ _this.detachCardOverlay(); }, attachCardOverlay: function() { - print('jbp should attach card overlay') - var myProps = Entities.getEntityProperties(_this.entityID); + print('jbp should attach card overlay'); + var myProps = Entities.getEntityProperties(_this.entityID, ['position', 'rotation', 'dimensions']); var cardFront = CARD_IMAGE_BASE_URL + _this.getCard().suit + this.getCard().rank + ".jpg"; print('card front is:' + cardFront); var frontVec = Quat.getUp(myProps.rotation); @@ -37,24 +48,22 @@ dimensions: myProps.dimensions, visible: true, drawInFront: true, - parentID: myProps.id + parentID: _this.entityID }); - print('jbp did attach card overlay:' + _this.cardOverlay) + print('jbp did attach card overlay:' + _this.cardOverlay); Script.setTimeout(function() { var success = Overlays.editOverlay(_this.cardOverlay, { textures: { "file1": cardFront, - "file2": CARD_BACK_IMAGE_URL, - }, - }) - print('jbp success on edit? ' + success) - }, 1) - - + "file2": CARD_BACK_IMAGE_URL + } + }); + print('jbp success on edit? ' + success); + }, 1); }, detachCardOverlay: function() { - print('jbp should detach card overlay') + print('jbp should detach card overlay'); Overlays.deleteOverlay(_this.cardOverlay); }, @@ -62,23 +71,22 @@ return _this.getCurrentUserData().playingCards.card; }, setCurrentUserData: function(data) { - var userData = getCurrentUserData(); + var userData = _this.getCurrentUserData(); userData.playingCards = data; Entities.editEntity(_this.entityID, { userData: userData }); }, getCurrentUserData: function() { - var props = Entities.getEntityProperties(_this.entityID); - var json = null; + var userData = Entities.getEntityProperties(_this.entityID, 'userData').userData; try { - json = JSON.parse(props.userData); + return JSON.parse(userData); } catch (e) { - return; + // e } - return json; - }, - } + return null; + } + }; return new PlayingCard(); -}) \ No newline at end of file +}); diff --git a/unpublishedScripts/marketplace/gameTable/nextGameButton.js b/unpublishedScripts/marketplace/gameTable/nextGameButton.js index 473e3c196c..36a92d4247 100644 --- a/unpublishedScripts/marketplace/gameTable/nextGameButton.js +++ b/unpublishedScripts/marketplace/gameTable/nextGameButton.js @@ -12,7 +12,6 @@ var _this; var CLICK_SOUND_URL = Script.resolvePath('assets/sfx/woodenTapClick.wav'); var clickSound; - var myLocation; function NextGameButton() { _this = this; @@ -22,20 +21,6 @@ preload: function(id) { _this.entityID = id; clickSound = SoundCache.getSound(CLICK_SOUND_URL); - myLocation = Entities.getEntityProperties(_this.entityID).position; - }, - getEntityFromGroup: function(groupName, entityName) { - var props = Entities.getEntityProperties(_this.entityID); - var results = Entities.findEntities(props.position, 7.5); - var found = false; - results.forEach(function(item) { - var itemProps = Entities.getEntityProperties(item); - var descriptionSplit = itemProps.description.split(":"); - if (descriptionSplit[1] === groupName && descriptionSplit[2] === entityName) { - found = item - } - }); - return found; }, clickDownOnEntity: function() { _this.nextGame(); @@ -43,12 +28,14 @@ startNearTrigger: function() { _this.nextGame(); }, - startFarTrigger: function() {}, nextGame: function() { - Audio.playSound(CLICK_SOUND_URL, { loop: false, position: myLocation, volume: 0.4 }); - var table = _this.getEntityFromGroup('gameTable', 'table'); - var tableString = table.substr(1, table.length - 2); - Entities.callEntityMethod(tableString, 'nextGame'); + var buttonProperties = Entities.getEntityProperties(_this.entityID, ['position', 'parentID']); + Entities.callEntityMethod(buttonProperties.parentID, 'nextGame'); + Audio.playSound(clickSound, { + loop: false, + position: buttonProperties.position, + volume: 0.4 + }); } }; return new NextGameButton(); diff --git a/unpublishedScripts/marketplace/gameTable/resetGameButton.js b/unpublishedScripts/marketplace/gameTable/resetGameButton.js index 19114cf4d5..703b136898 100644 --- a/unpublishedScripts/marketplace/gameTable/resetGameButton.js +++ b/unpublishedScripts/marketplace/gameTable/resetGameButton.js @@ -7,20 +7,7 @@ ResetGameButton.prototype = { preload: function(id) { - _this.entityID = id - }, - getEntityFromGroup: function(groupName, entityName) { - var props = Entities.getEntityProperties(_this.entityID); - var results = Entities.findEntities(props.position, 7.5); - var found; - results.forEach(function(item) { - var itemProps = Entities.getEntityProperties(item); - var descriptionSplit = itemProps.description.split(":"); - if (descriptionSplit[1] === groupName && descriptionSplit[2] === entityName) { - found = item - } - }); - return found; + _this.entityID = id; }, clickDownOnEntity: function() { _this.resetGame(); @@ -31,8 +18,7 @@ startFarTrigger: function() {}, resetGame: function() { print('reset game button calling resetGame'); - var table = _this.getEntityFromGroup('gameTable', 'table'); - Entities.callEntityMethod(table, 'resetGame'); + Entities.callEntityMethod(Entities.getEntityProperties(_this.entityID, ['parentID']).parentID, 'resetGame'); } }; return new ResetGameButton(); diff --git a/unpublishedScripts/marketplace/gameTable/snapToGrid.js b/unpublishedScripts/marketplace/gameTable/snapToGrid.js index a0405a9206..e3c764b529 100644 --- a/unpublishedScripts/marketplace/gameTable/snapToGrid.js +++ b/unpublishedScripts/marketplace/gameTable/snapToGrid.js @@ -8,7 +8,7 @@ (function() { var _this; - var DONT_SNAP_WHEN_FARTHER_THAN_THIS = 0.25; + var DO_NOT_SNAP_WHEN_FARTHER_THAN_THIS = 0.25; function SnapToGrid() { _this = this; @@ -32,21 +32,21 @@ }, getAnchorPoints: function() { var availableAnchors = []; - var results = _this.getEntityFromGroup('gameTable', 'anchor'); + var results = _this.getEntitiesFromGroup('gameTable', 'anchor'); results.forEach(function(item) { - var props = Entities.getEntityProperties(item); - if (props.userData === 'occupied') { - //don't put it on the stack - } else if (props.userData === 'available') { - availableAnchors.push(props.position); + var properties = Entities.getEntityProperties(item, ['position', 'userData']); + if (properties.userData === 'occupied') { + // don't put it on the stack + } else if (properties.userData === 'available') { + availableAnchors.push(properties.position); } }); return availableAnchors; }, attachToNearestAnchor: function() { - var myProps = Entities.getEntityProperties(_this.entityID); + var myProps = Entities.getEntityProperties(_this.entityID, ['position', 'dimensions']); var anchors = _this.getAnchorPoints(); - var shortestDistance = DONT_SNAP_WHEN_FARTHER_THAN_THIS; + var shortestDistance = DO_NOT_SNAP_WHEN_FARTHER_THAN_THIS; var nearestAnchor = null; anchors.forEach(function(anchor) { var howFar = Vec3.distance(myProps.position, anchor); @@ -56,7 +56,7 @@ } }); - if (shortestDistance > DONT_SNAP_WHEN_FARTHER_THAN_THIS) { + if (shortestDistance > DO_NOT_SNAP_WHEN_FARTHER_THAN_THIS) { _this.setCurrentUserData({ attachedTo: null }); @@ -70,7 +70,7 @@ userData: 'occupied' }); } else { - //there is no nearest anchor. perhaps they are all occupied. + // there is no nearest anchor. perhaps they are all occupied. _this.setCurrentUserData({ attachedTo: null }); @@ -78,17 +78,18 @@ } }, - getEntityFromGroup: function(groupName, entityName) { - var props = Entities.getEntityProperties(_this.entityID); - var results = Entities.findEntities(props.position, 7.5); - var found; - results.forEach(function(item) { - var itemProps = Entities.getEntityProperties(item); - var descriptionSplit = itemProps.description.split(":"); + getEntitiesFromGroup: function(groupName, entityName) { + var position = Entities.getEntityProperties(_this.entityID, 'position').position; + var nearbyEntities = Entities.findEntities(position, 7.5); + var foundItems = []; + nearbyEntities.forEach(function(entityID) { + var description = Entities.getEntityProperties(entityID, 'description').description; + var descriptionSplit = description.split(":"); if (descriptionSplit[1] === groupName && descriptionSplit[2] === entityName) { - return item; + foundItems.push(entityID); } }); + return foundItems; }, positionOnAnchor: function(anchor, myProps) { Entities.editEntity(_this.entityID, { @@ -97,24 +98,23 @@ y: anchor.y + (0.5 * myProps.dimensions.y), z: anchor.z } - }) + }); }, setCurrentUserData: function(data) { - var userData = getCurrentUserData(); + var userData = _this.getCurrentUserData(); userData.gameTable = data; Entities.editEntity(_this.entityID, { userData: userData }); }, getCurrentUserData: function() { - var props = Entities.getEntityProperties(_this.entityID); - var json = null; + var userData = Entities.getEntityProperties(_this.entityID, 'userData').userData; try { - json = JSON.parse(props.userData); + return JSON.parse(userData); } catch (e) { - return; + // e; } - return json; + return null; } - } + }; }); diff --git a/unpublishedScripts/marketplace/gameTable/table.js b/unpublishedScripts/marketplace/gameTable/table.js index f618fe4f88..1c59d7ace0 100644 --- a/unpublishedScripts/marketplace/gameTable/table.js +++ b/unpublishedScripts/marketplace/gameTable/table.js @@ -9,12 +9,22 @@ // (function() { - var CLEARCACHE = "?"+Math.random().toString(36).substring(7); - var GAMES_LIST_ENDPOINT = Script.resolvePath('games/gamesDirectory.svo.json') + CLEARCACHE; + var GAMES_LIST_ENDPOINT = Script.resolvePath('games/gamesDirectory.svo.json'); var _this; var INITIAL_DELAY = 1000; + function getGamesList() { + // FIXME: HACK: remove when Script.require is in release client (Beta Release 37) + if (Script.require === undefined) { + var request = new XMLHttpRequest(); + request.open('GET', GAMES_LIST_ENDPOINT, false); + request.send(); + return JSON.parse(request.responseText); + } + return Script.require(GAMES_LIST_ENDPOINT); + } + function GameTable() { _this = this; } @@ -29,17 +39,17 @@ }, INITIAL_DELAY); }, collisionWithEntity: function(me, other, collision) { - //stick the table to the ground + // stick the table to the ground if (collision.type !== 1) { return; } - var myProps = Entities.getEntityProperties(_this.entityID, ["rotation", "position"]); + var myProps = Entities.getEntityProperties(_this.entityID, ['rotation', 'position']); var eulerRotation = Quat.safeEulerAngles(myProps.rotation); eulerRotation.x = 0; eulerRotation.z = 0; var newRotation = Quat.fromVec3Degrees(eulerRotation); - //we zero out the velocity and angular velocity so the table doesn't change position or spin + // we zero out the velocity and angular velocity so the table doesn't change position or spin Entities.editEntity(_this.entityID, { rotation: newRotation, dynamic: true, @@ -88,15 +98,15 @@ _this.cleanupGameEntities(); }, cleanupGameEntities: function() { - var props = Entities.getEntityProperties(_this.entityID); - var results = Entities.findEntities(props.position, 5); + var position = Entities.getEntityProperties(_this.entityID, 'position').position; + var results = Entities.findEntities(position, 5.0); var found = []; results.forEach(function(item) { - var itemProps = Entities.getEntityProperties(item); - if (itemProps.description.indexOf('hifi:gameTable:piece:') === 0) { + var description = Entities.getEntityProperties(item, 'description').description; + if (description.indexOf('hifi:gameTable:piece:') === 0) { found.push(item); } - if (itemProps.description.indexOf('hifi:gameTable:anchor') > -1) { + if (description.indexOf('hifi:gameTable:anchor') > -1) { found.push(item); } }); @@ -113,7 +123,6 @@ }, setCurrentGame: function() { print('index in set current game: ' + _this.currentGameIndex); - // print('games list in set current game' + JSON.stringify(_this.gamesList)); print('game at index' + _this.gamesList[_this.currentGameIndex]); _this.currentGame = _this.gamesList[_this.currentGameIndex].gameName; _this.currentGameFull = _this.gamesList[_this.currentGameIndex]; @@ -124,52 +133,44 @@ setCurrentUserData: function(data) { var userData = _this.getCurrentUserData(); userData['gameTableData'] = data; - var success = Entities.editEntity(_this.entityID, { + Entities.editEntity(_this.entityID, { userData: JSON.stringify(userData) }); }, getCurrentUserData: function() { - var props = Entities.getEntityProperties(_this.entityID); - var hasUserData = props.hasOwnProperty('userData'); - var json = {}; + var userData = Entities.getEntityProperties(_this.entityID, ['userData']).userData; try { - json = JSON.parse(props.userData); + return JSON.parse(userData); } catch (e) { - print('user data is not json' + props.userData) + print('user data is not json' + userData); } - return json; + return {}; }, getEntityFromGroup: function(groupName, entityName) { print('getting entity from group: ' + groupName); - var props = Entities.getEntityProperties(_this.entityID); - var results = Entities.findEntities(props.position, 7.5); - var found; + var position = Entities.getEntityProperties(_this.entityID, ['position']).position; + var results = Entities.findEntities(position, 7.5); var result = null; results.forEach(function(item) { - var itemProps = Entities.getEntityProperties(item); - - var descriptionSplit = itemProps.description.split(":"); + var description = Entities.getEntityProperties(item, 'description').description; + var descriptionSplit = description.split(":"); if (descriptionSplit[1] === groupName && descriptionSplit[2] === entityName) { result = item; } }); - return result + return result; }, spawnEntitiesForGame: function() { var entitySpawner = _this.getEntityFromGroup('gameTable', 'entitySpawner'); var mat = _this.getEntityFromGroup('gameTable', 'mat'); - Entities.callEntityMethod(entitySpawner, 'spawnEntities', [JSON.stringify(_this.currentGameFull),mat, - _this.entityID]); + Entities.callEntityMethod(entitySpawner, 'spawnEntities', [ + JSON.stringify(_this.currentGameFull), + mat, + _this.entityID + ]); } }; - function getGamesList() { - var request = new XMLHttpRequest(); - request.open("GET", GAMES_LIST_ENDPOINT, false); - request.send(); - return JSON.parse(request.responseText); - } - return new GameTable(); });