cr fixes and some more style/ESLINT/structure

This commit is contained in:
Thijs Wenker 2017-04-17 13:16:10 +02:00
parent d101bdb952
commit 12ef157316
9 changed files with 287 additions and 331 deletions

View file

@ -47,6 +47,4 @@ PUBLISHING
============= =============
- As a script: just add createGameTable.js to the marketplace. - 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.

View file

@ -8,16 +8,15 @@
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // 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');
var TABLE_MODEL_URL = Script.resolvePath('assets/table/gameTable.fbx') + CLEARCACHE; var MODEL_URL = Script.resolvePath('assets/table/finalFrame.fbx');
var MODEL_URL = Script.resolvePath('assets/table/finalFrame.fbx') + CLEARCACHE; var TABLE_SCRIPT_URL = Script.resolvePath('table.js');
var TABLE_SCRIPT_URL = Script.resolvePath('table.js') + CLEARCACHE; var ENTITY_SPAWNER_SCRIPT_URL = Script.resolvePath('entitySpawner.js');
var ENTITY_SPAWNER_SCRIPT_URL = Script.resolvePath('entitySpawner.js') + CLEARCACHE; var NEXT_GAME_BUTTON_SCRIPT_URL = Script.resolvePath('nextGameButton.js');
var NEXT_GAME_BUTTON_SCRIPT_URL = Script.resolvePath('nextGameButton.js') + CLEARCACHE; var RESET_BUTTON_SCRIPT_URL = Script.resolvePath('resetGameButton.js');
var RESET_BUTTON_SCRIPT_URL = Script.resolvePath('resetGameButton.js') + CLEARCACHE; var TABLE_PICTURE_URL = Script.resolvePath('assets/mats/Table-default.jpg');
var TABLE_PICTURE_URL = Script.resolvePath('assets/mats/Table-default.jpg') + CLEARCACHE; var NEXT_BUTTON_MODEL_URL = Script.resolvePath('assets/buttons/button-next.fbx');
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');
var RESET_BUTTON_MODEL_URL = Script.resolvePath('assets/buttons/button-reset.fbx') + CLEARCACHE;
// FIXME: CHANGE TO Quat.getForward when supported // FIXME: CHANGE TO Quat.getForward when supported
var front = Quat.getFront(MyAvatar.orientation); var front = Quat.getFront(MyAvatar.orientation);
@ -52,11 +51,11 @@ var resetGameButtonOffset = {
}; };
function getOffsetFromTable(forward, vertical, right) { function getOffsetFromTable(forward, vertical, right) {
var props = Entities.getEntityProperties(table); var properties = Entities.getEntityProperties(table, ['position', 'rotation']);
var position = props.position; var position = properties.position;
var frontVector = Quat.getFront(props.rotation); var frontVector = Quat.getFront(properties.rotation);
var upVector = Quat.getUp(props.rotation); var upVector = Quat.getUp(properties.rotation);
var rightVector = Quat.getRight(props.rotation); var rightVector = Quat.getRight(properties.rotation);
if (forward !== undefined) { if (forward !== undefined) {
position = Vec3.sum(position, Vec3.multiply(frontVector, forward)); position = Vec3.sum(position, Vec3.multiply(frontVector, forward));
} }
@ -71,7 +70,7 @@ function getOffsetFromTable(forward, vertical, right) {
} }
function createTable() { function createTable() {
var props = { table = Entities.addEntity({
type: 'Model', type: 'Model',
name: 'GameTable Table 1', name: 'GameTable Table 1',
description: 'hifi:gameTable:table', description: 'hifi:gameTable:table',
@ -105,13 +104,11 @@ function createTable() {
grabbable: true grabbable: true
} }
}) })
}; });
table = Entities.addEntity(props);
} }
function createEntitySpawner() { function createEntitySpawner() {
var props = { entitySpawner = Entities.addEntity({
type: 'Zone', type: 'Zone',
visible: false, visible: false,
name: 'GameTable Entity Spawner', name: 'GameTable Entity Spawner',
@ -130,14 +127,11 @@ function createEntitySpawner() {
script: ENTITY_SPAWNER_SCRIPT_URL, script: ENTITY_SPAWNER_SCRIPT_URL,
parentID: table, parentID: table,
position: getOffsetFromTable(entitySpawnerOffset.forward, entitySpawnerOffset.vertical, entitySpawnerOffset.right) position: getOffsetFromTable(entitySpawnerOffset.forward, entitySpawnerOffset.vertical, entitySpawnerOffset.right)
}; });
entitySpawner = Entities.addEntity(props);
} }
function createMat() { function createMat() {
var props = { return Entities.addEntity({
type: 'Model', type: 'Model',
modelURL: MODEL_URL, modelURL: MODEL_URL,
name: 'GameTable Mat', name: 'GameTable Mat',
@ -166,13 +160,11 @@ function createMat() {
grabbable: false grabbable: false
} }
}) })
}; });
return Entities.addEntity(props);
} }
function createNextGameButton() { function createNextGameButton() {
var props = { nextGameButton = Entities.addEntity({
type: 'Model', type: 'Model',
modelURL: NEXT_BUTTON_MODEL_URL, modelURL: NEXT_BUTTON_MODEL_URL,
name: 'GameTable Next Button', name: 'GameTable Next Button',
@ -195,19 +187,18 @@ function createNextGameButton() {
}), }),
parentID: table, parentID: table,
script: NEXT_GAME_BUTTON_SCRIPT_URL, 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({ userData: JSON.stringify({
grabbableKey: { grabbableKey: {
wantsTrigger: true wantsTrigger: true
} }
}) })
}; });
nextGameButton = Entities.addEntity(props);
} }
function createResetGameButton() { function createResetGameButton() {
var props = { resetGameButton = Entities.addEntity({
type: 'Model', type: 'Model',
modelURL: RESET_BUTTON_MODEL_URL, modelURL: RESET_BUTTON_MODEL_URL,
name: 'GameTable Reset Button', name: 'GameTable Reset Button',
@ -230,15 +221,14 @@ function createResetGameButton() {
}), }),
parentID: table, parentID: table,
script: RESET_BUTTON_SCRIPT_URL, script: RESET_BUTTON_SCRIPT_URL,
position: getOffsetFromTable(resetGameButtonOffset.forward, resetGameButtonOffset.vertical, resetGameButtonOffset.right), position: getOffsetFromTable(resetGameButtonOffset.forward, resetGameButtonOffset.vertical,
resetGameButtonOffset.right),
userData: JSON.stringify({ userData: JSON.stringify({
grabbableKey: { grabbableKey: {
wantsTrigger: true wantsTrigger: true
} }
}) })
}; });
resetGameButton = Entities.addEntity(props);
} }
function makeTable() { function makeTable() {

View file

@ -9,10 +9,10 @@
(function() { (function() {
var _this; var _this;
var pasted_cache = {}; var entityJSONCache = {};
const SANITIZE_PROPERTIES = ['childEntities', 'parentID', 'id']; var SANITIZE_PROPERTIES = ['childEntities', 'parentID', 'id'];
const ZERO_UUID = '{00000000-0000-0000-0000-000000000000}'; var ZERO_UUID = '{00000000-0000-0000-0000-000000000000}';
function entityListToTree(entitiesList) { function entityListToTree(entitiesList) {
function entityListToTreeRecursive(properties) { function entityListToTreeRecursive(properties) {
@ -33,7 +33,6 @@
return entityTree; return entityTree;
} }
// TODO: ATP support (currently the JS API for ATP does not support file links, only hashes)
function importEntitiesJSON(importLink, parentProperties, overrideProperties) { function importEntitiesJSON(importLink, parentProperties, overrideProperties) {
if (parentProperties === undefined) { if (parentProperties === undefined) {
parentProperties = {}; parentProperties = {};
@ -41,12 +40,23 @@
if (overrideProperties !== undefined) { if (overrideProperties !== undefined) {
parentProperties.overrideProperties = overrideProperties; parentProperties.overrideProperties = overrideProperties;
} }
var request = new XMLHttpRequest(); // FIXME: HACK: remove when Script.require is in release client (Beta Release 37)
request.open('GET', importLink, false); if (Script.require === undefined) {
request.send(); 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 { try {
var response = JSON.parse(request.responseText); var entityJSONImport = Script.require(importLink).Entities;
parentProperties.childEntities = entityListToTree(response.Entities); parentProperties.childEntities = entityListToTree(entityJSONImport.Entities);
return parentProperties; return parentProperties;
} catch (e) { } catch (e) {
print('Failed importing entities JSON because: ' + JSON.stringify(e)); print('Failed importing entities JSON because: ' + JSON.stringify(e));
@ -61,7 +71,7 @@
return link; 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) { var createEntity = function(entityProperties, parent, overrideProperties) {
// JSON.stringify -> JSON.parse trick to create a fresh copy of JSON data // JSON.stringify -> JSON.parse trick to create a fresh copy of JSON data
var newEntityProperties = JSON.parse(JSON.stringify(entityProperties)); var newEntityProperties = JSON.parse(JSON.stringify(entityProperties));
@ -80,7 +90,7 @@
if (parent.position !== undefined) { if (parent.position !== undefined) {
var localPosition = (parent.rotation !== undefined) ? var localPosition = (parent.rotation !== undefined) ?
Vec3.multiplyQbyV(parent.rotation, newEntityProperties.position) : newEntityProperties.position; 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) { if (parent.id !== undefined) {
newEntityProperties.parentID = parent.id; newEntityProperties.parentID = parent.id;
@ -127,46 +137,44 @@
return createdTree; return createdTree;
}; };
//listens for a release message from entities with the snap to grid script // 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 // checks for the nearest snap point and sends a message back to the entity
function PastedItem(url, spawnLocation, spawnRotation) { function ImportGamePiece(url, spawnLocation, spawnRotation) {
var fullURL = Script.resolvePath(url); var fullURL = Script.resolvePath(url);
print('CREATE PastedItem FROM SPAWNER: ' + fullURL); print('CREATE PastedItem FROM SPAWNER: ' + fullURL);
var created = []; var _created = [];
function create() { function create() {
var entitiesTree; var entitiesTree;
if (pasted_cache[fullURL]) { if (entityJSONCache[fullURL]) {
entitiesTree = pasted_cache[fullURL]; entitiesTree = entityJSONCache[fullURL];
//print('used cache');
} else { } else {
entitiesTree = importEntitiesJSON(fullURL); entitiesTree = importEntitiesJSON(fullURL);
pasted_cache[fullURL] = entitiesTree; entityJSONCache[fullURL] = entitiesTree;
//print('moved to cache');
} }
entitiesTree.position = spawnLocation; entitiesTree.position = spawnLocation;
entitiesTree.rotation = spawnRotation; entitiesTree.rotation = spawnRotation;
//print('entityTree: ' + JSON.stringify(entitiesTree)); // print('entityTree: ' + JSON.stringify(entitiesTree));
//var entities = importEntitiesJSON(fullURL); // var entities = importEntitiesJSON(fullURL);
//var success = Clipboard.importEntities(fullURL); // var success = Clipboard.importEntities(fullURL);
//var dimensions = Clipboard.getContentsDimensions(); // 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, // 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); // spawnLocation.y += (0.5 * dimensions.y);
//if (success === true) { // if (success === true) {
//created = Clipboard.pasteEntities(spawnLocation); // created = Clipboard.pasteEntities(spawnLocation);
// this.created = created; // this.created = created;
// print('created ' + created); // print('created ' + created);
//} // }
this.created = createEntitiesFromTree([entitiesTree]); _created = createEntitiesFromTree([entitiesTree]);
} }
function cleanup() { function cleanup() {
created.forEach(function(obj) { _created.forEach(function(obj) {
print('removing: ' + JSON.stringify(obj)); print('removing: ' + JSON.stringify(obj));
Entities.deleteEntity(obj.id); Entities.deleteEntity(obj.id);
}) });
} }
create(); create();
@ -177,7 +185,6 @@
function Tile(rowIndex, columnIndex) { function Tile(rowIndex, columnIndex) {
var side = _this.tableSideSize / _this.game.startingArrangement.length; var side = _this.tableSideSize / _this.game.startingArrangement.length;
var rightAmount = rowIndex * side; var rightAmount = rowIndex * side;
rightAmount += (0.5 * side); rightAmount += (0.5 * side);
var forwardAmount = columnIndex * side; var forwardAmount = columnIndex * side;
@ -196,14 +203,13 @@
this.url = Script.resolvePath(_this.game.pieces[0][splitURL[1]]); this.url = Script.resolvePath(_this.game.pieces[0][splitURL[1]]);
} }
if (splitURL[0] === '2') { 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') { if (splitURL[0] === 'empty') {
this.url = 'empty'; this.url = 'empty';
} }
} }
function EntitySpawner() { function EntitySpawner() {
_this = this; _this = this;
} }
@ -223,7 +229,7 @@
if (url === 'empty') { if (url === 'empty') {
return null; return null;
} }
var item = new PastedItem(url, spawnLocation, spawnRotation); var item = new ImportGamePiece(url, spawnLocation, spawnRotation);
_this.items.push(item); _this.items.push(item);
return item; return item;
}, },
@ -234,38 +240,40 @@
textures: JSON.stringify({ textures: JSON.stringify({
Picture: fullURL Picture: fullURL
}) })
}) });
}, },
spawnEntities: function(id, params) { spawnEntities: function(id, params) {
this.items = []; 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.game = JSON.parse(params[0]);
_this.matDimensions = dimensions; _this.matDimensions = matProperties.dimensions;
_this.matCenter = Entities.getEntityProperties(params[1]).position; _this.matCenter = matProperties.position;
_this.matCorner = { _this.matCorner = {
x: _this.matCenter.x - (dimensions.x * 0.5), x: _this.matCenter.x - (dimensions.x * 0.5),
y: _this.matCenter.y, y: _this.matCenter.y,
z: _this.matCenter.z + (dimensions.y * 0.5) z: _this.matCenter.z + (dimensions.y * 0.5)
}; };
_this.matRotation = Entities.getEntityProperties(params[1]).rotation; _this.matRotation = matProperties.rotation;
var parentID = Entities.getEntityProperties(params[1]).parentID; var tableID = matProperties.parentID;
_this.tableRotation = Entities.getEntityProperties(parentID).rotation; _this.tableRotation = Entities.getEntityProperties(tableID, 'rotation').rotation;
_this.tableSideSize = dimensions.x; _this.tableSideSize = dimensions.x;
_this.changeMatPicture(params[1]); _this.changeMatPicture(matEntity);
if (this.game.spawnStyle === "pile") { if (_this.game.spawnStyle === 'pile') {
_this.spawnByPile(); _this.spawnByPile();
} else if (this.game.spawnStyle === "arranged") { } else if (_this.game.spawnStyle === 'arranged') {
_this.spawnByArranged(); _this.spawnByArranged();
} }
}, },
spawnByPile: function() { 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++) { for (var i = 0; i < _this.game.howMany; i++) {
var spawnLocation = { var spawnLocation = {
x: props.position.x, x: position.x,
y: props.position.y - 0.25, y: position.y - 0.25,
z: props.position.z z: position.z
}; };
var url; var url;
if (_this.game.identicalPieces === false) { if (_this.game.identicalPieces === false) {
@ -273,22 +281,19 @@
} else { } else {
url = Script.resolvePath(_this.game.pieces[0]); url = Script.resolvePath(_this.game.pieces[0]);
} }
_this.createSingleEntity(url, spawnLocation, _this.tableRotation); _this.createSingleEntity(url, spawnLocation, _this.tableRotation);
} }
}, },
spawnByArranged: function() { spawnByArranged: function() {
// make sure to set userData.gameTable.attachedTo appropriately // make sure to set userData.gameTable.attachedTo appropriately
_this.setupGrid(); _this.setupGrid();
}, },
createDebugEntity: function(position) { createDebugEntity: function(position) {
return Entities.addEntity({ return Entities.addEntity({
type: 'Sphere', type: 'Sphere',
position: { position: {
x: position.x, x: position.x,
y: position.y += 0.1, y: position.y + 0.1,
z: position.z z: position.z
}, },
color: { color: {
@ -302,9 +307,8 @@
z: 0.1 z: 0.1
}, },
collisionless: true collisionless: true
}) });
}, },
setupGrid: function() { setupGrid: function() {
_this.tiles = []; _this.tiles = [];
@ -330,12 +334,10 @@
} }
} }
}, },
findMidpoint: function(start, end) { findMidpoint: function(start, end) {
var xy = Vec3.sum(start, end); var xy = Vec3.sum(start, end);
return Vec3.multiply(0.5, xy); return Vec3.multiply(0.5, xy);
}, },
createAnchorEntityAtPoint: function(position) { createAnchorEntityAtPoint: function(position) {
var properties = { var properties = {
type: 'Zone', type: 'Zone',
@ -348,39 +350,37 @@
y: 0.075, y: 0.075,
z: 0.075 z: 0.075
}, },
parentID: Entities.getEntityProperties(_this.entityID).id, parentID: _this.entityID,
position: position, position: position,
userData: 'available' userData: 'available'
}; };
return Entities.addEntity(properties); return Entities.addEntity(properties);
}, },
setCurrentUserData: function(data) { setCurrentUserData: function(data) {
var userData = getCurrentUserData(); var userData = _this.getCurrentUserData();
userData.gameTableData = data; userData.gameTableData = data;
Entities.editEntity(_this.entityID, { Entities.editEntity(_this.entityID, {
userData: userData userData: userData
}); });
}, },
getCurrentUserData: function() { getCurrentUserData: function() {
var props = Entities.getEntityProperties(_this.entityID); var userData = Entities.getEntityProperties(_this.entityID).userData;
var json = null;
try { try {
json = JSON.parse(props.userData); return JSON.parse(userData);
} catch (e) { } catch (e) {
return; // e
} }
return json; return null;
}, },
cleanupEntitiesList: function() { cleanupEntitiesList: function() {
_this.items.forEach(function(item) { _this.items.forEach(function(item) {
item.cleanup(); item.cleanup();
}) });
}, },
unload: function() { unload: function() {
_this.toCleanup.forEach(function(item) { _this.toCleanup.forEach(function(item) {
Entities.deleteEntity(item); Entities.deleteEntity(item);
}) });
} }
}; };
return new EntitySpawner(); return new EntitySpawner();

View file

@ -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() { (function() {
var _this; var _this;
var MAPPING_NAME = "hifi-gametable-cards-dev-" + Math.random(); var MAPPING_NAME = "hifi-gametable-cards-dev-" + Math.random();
@ -23,7 +34,6 @@
blue: 0 blue: 0
}; };
var SETUP_DELAY = 2000;
var NEARBY_CARDS_RANGE = 5; var NEARBY_CARDS_RANGE = 5;
function DeckOfCards() { function DeckOfCards() {
@ -44,15 +54,15 @@
createMapping: function() { createMapping: function() {
var mapping = Controller.newMapping(MAPPING_NAME); var mapping = Controller.newMapping(MAPPING_NAME);
mapping.from([Controller.Standard.RTClick]).peek().to(function(val) { 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) { mapping.from([Controller.Standard.LTClick]).peek().to(function(val) {
_this.handleTrigger(val, 'left') _this.handleTrigger(val, 'left');
}); });
Controller.enableMapping(MAPPING_NAME); Controller.enableMapping(MAPPING_NAME);
}, },
destroyMapping: function() { destroyMapping: function() {
Controller.disableMapping(MAPPING_NAME) Controller.disableMapping(MAPPING_NAME);
}, },
handleTrigger: function(val, hand) { handleTrigger: function(val, hand) {
if (val !== 1) { if (val !== 1) {
@ -61,7 +71,7 @@
print('jbp trigger pulled at val:' + val + ":" + hand); print('jbp trigger pulled at val:' + val + ":" + hand);
print('jbp at time hand was:' + _this.currentHand); print('jbp at time hand was:' + _this.currentHand);
if (_this.currentHand === hand) { if (_this.currentHand === hand) {
print('jbp should ignore its the same hand') print('jbp should ignore its the same hand');
} else { } else {
print('jbp should make a new thing its the off hand'); print('jbp should make a new thing its the off hand');
_this.createPlayingCard(); _this.createPlayingCard();
@ -72,35 +82,36 @@
var cards = _this.getCardsFromUserData(); var cards = _this.getCardsFromUserData();
if (cards === false) { if (cards === false) {
print('jbp should make new deck'); print('jbp should make new deck');
// should make a deck the first time
_this.makeNewDeck(); _this.makeNewDeck();
//should make a deck the first time
return;
} else { } else {
print('jbp already has deck' + cards); 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.makeNewDeck();
_this.currentStack._import(cards) _this.currentStack._import(cards);
} }
}, },
resetDeck: function() { resetDeck: function() {
print('jbp resetting deck') print('jbp resetting deck');
//finds and delete any nearby cards // finds and delete any nearby cards
var myProps = Entities.getEntityProperties(_this.entityID); var position = Entities.getEntityProperties(_this.entityID, 'position');
var results = Entities.findEntities(myProps.position, NEARBY_CARDS_RANGE); var results = Entities.findEntities(position, NEARBY_CARDS_RANGE);
results.forEach(function(item) { results.forEach(function(item) {
var itemProps = Entities.getEntityProperties(item); var itemProps = Entities.getEntityProperties(item, 'userData');
if (itemProps.userData.hasOwnProperty('playingCards') && itemProps.userData.playingCards.hasOwnProperty('card')) { if (itemProps.userData.hasOwnProperty('playingCards') &&
Entities.deleteEntity(item); itemProps.userData.playingCards.hasOwnProperty('card')) {
}
}); Entities.deleteEntity(item);
//resets this deck to a new deck }
});
// resets this deck to a new deck
_this.makeNewDeck(); _this.makeNewDeck();
}, },
makeNewDeck: function() { makeNewDeck: function() {
print('jbp make new deck'); print('jbp make new deck');
//make a stack and shuffle it up. // make a stack and shuffle it up.
var stack = new Stack(); var stack = new Stack();
stack.makeDeck(1); stack.makeDeck(1);
stack.shuffle(100); stack.shuffle(100);
@ -108,20 +119,20 @@
}, },
collisionWithEntity: function(me, other, collision) { 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) { if (collision.type !== 0) {
//its not the start, so exit early. // its not the start, so exit early.
return; return;
} }
var otherProps = Entities.getEntityProperties(other); var otherProps = Entities.getEntityProperties(other, 'userData');
var userData = {}; var userData = {};
try { try {
JSON.parse(otherProps.userData) userData = JSON.parse(otherProps.userData);
} catch (e) { } catch (e) {
return return;
} }
if (userData.hasOwnProperty('playingCards') && userData.playingCards.hasOwnProperty('card')) { 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); _this.currentStack.addCard(userData.playingCards.card);
@ -171,26 +182,26 @@
exitDealerMode: function() { exitDealerMode: function() {
_this.destroyMapping(); _this.destroyMapping();
//turn grab on // turn grab on
//save the cards // save the cards
//delete the overlay beam // delete the overlay beam
if (_this.updateConnected === true) { if (_this.updateConnected === true) {
Script.update.disconnect(_this.updateRays); Script.update.disconnect(_this.updateRays);
} }
Messages.sendLocalMessage('Hifi-Hand-Disabler', 'none'); Messages.sendLocalMessage('Hifi-Hand-Disabler', 'none');
_this.deleteCardTargetOverlay() _this.deleteCardTargetOverlay();
_this.turnOffOverlayBeams(); _this.turnOffOverlayBeams();
_this.storeCards(); _this.storeCards();
}, },
storeCards: function() { storeCards: function() {
var cards = _this.currentStack._export(); var cards = _this.currentStack._export();
print('deckof cards:' + cards) print('deck of cards: ' + cards);
Entities.editEntity(_this.entityID, { Entities.editEntity(_this.entityID, {
userData: JSON.stringify({ userData: JSON.stringify({
cards: cards cards: cards
}) })
}) });
}, },
restoreCards: function() { restoreCards: function() {
@ -199,28 +210,28 @@
}, },
getCardsFromUserData: function() { getCardsFromUserData: function() {
var props = Entities.getEntityProperties(_this.entityID); var props = Entities.getEntityProperties(_this.entityID, 'userData');
var data; var data;
try { try {
data = JSON.parse(props.userData); data = JSON.parse(props.userData);
print('jbp has cards in userdata' + props.userData) print('jbp has cards in userdata' + props.userData);
} catch (e) { } catch (e) {
print('jbp error parsing userdata') print('jbp error parsing userdata');
return false; return false;
} }
if (data.hasOwnProperty('cards')) { if (data.hasOwnProperty('cards')) {
print('jbp returning data.cards') print('jbp returning data.cards');
return data.cards; return data.cards;
} else {
return false
} }
return false;
}, },
rightRay: function() { rightRay: function() {
var pose = Controller.getPoseValue(Controller.Standard.RightHand); 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) : var rightRotation = pose.valid ? Quat.multiply(MyAvatar.orientation, pose.rotation) :
Quat.multiply(MyAvatar.headOrientation, Quat.angleAxis(-90, { Quat.multiply(MyAvatar.headOrientation, Quat.angleAxis(-90, {
x: 1, x: 1,
@ -230,7 +241,7 @@
var rightPickRay = { var rightPickRay = {
origin: rightPosition, origin: rightPosition,
direction: Quat.getUp(rightRotation), direction: Quat.getUp(rightRotation)
}; };
this.rightPickRay = rightPickRay; this.rightPickRay = rightPickRay;
@ -250,9 +261,7 @@
} else { } else {
this.rightLineOn(rightPickRay.origin, location, COLORS_CANNOT_PLACE); this.rightLineOn(rightPickRay.origin, location, COLORS_CANNOT_PLACE);
} }
}, },
leftRay: function() { leftRay: function() {
var pose = Controller.getPoseValue(Controller.Standard.LeftHand); var pose = Controller.getPoseValue(Controller.Standard.LeftHand);
var leftPosition = pose.valid ? Vec3.sum(Vec3.multiplyQbyV(MyAvatar.orientation, pose.translation), MyAvatar.position) : MyAvatar.getHeadPosition(); var leftPosition = pose.valid ? Vec3.sum(Vec3.multiplyQbyV(MyAvatar.orientation, pose.translation), MyAvatar.position) : MyAvatar.getHeadPosition();
@ -265,7 +274,7 @@
var leftPickRay = { var leftPickRay = {
origin: leftPosition, origin: leftPosition,
direction: Quat.getUp(leftRotation), direction: Quat.getUp(leftRotation)
}; };
this.leftPickRay = leftPickRay; this.leftPickRay = leftPickRay;
@ -285,10 +294,7 @@
} else { } else {
this.leftLineOn(leftPickRay.origin, location, COLORS_CANNOT_PLACE); this.leftLineOn(leftPickRay.origin, location, COLORS_CANNOT_PLACE);
} }
}, },
rightLineOn: function(closePoint, farPoint, color) { rightLineOn: function(closePoint, farPoint, color) {
if (this.rightOverlayLine === null) { if (this.rightOverlayLine === null) {
var lineProperties = { var lineProperties = {
@ -306,14 +312,13 @@
this.rightOverlayLine = Overlays.addOverlay("line3d", lineProperties); this.rightOverlayLine = Overlays.addOverlay("line3d", lineProperties);
} else { } else {
var success = Overlays.editOverlay(this.rightOverlayLine, { Overlays.editOverlay(this.rightOverlayLine, {
start: closePoint, start: closePoint,
end: farPoint, end: farPoint,
color: color color: color
}); });
} }
}, },
leftLineOn: function(closePoint, farPoint, color) { leftLineOn: function(closePoint, farPoint, color) {
if (this.leftOverlayLine === null) { if (this.leftOverlayLine === null) {
var lineProperties = { var lineProperties = {
@ -331,54 +336,33 @@
this.leftOverlayLine = Overlays.addOverlay("line3d", lineProperties); this.leftOverlayLine = Overlays.addOverlay("line3d", lineProperties);
} else { } else {
var success = Overlays.editOverlay(this.leftOverlayLine, { Overlays.editOverlay(this.leftOverlayLine, {
start: closePoint, start: closePoint,
end: farPoint, end: farPoint,
color: color color: color
}); });
} }
}, },
rightOverlayOff: function() { rightOverlayOff: function() {
if (this.rightOverlayLine !== null) { if (this.rightOverlayLine !== null) {
print('jbp inside right off') print('jbp inside right off');
Overlays.deleteOverlay(this.rightOverlayLine); Overlays.deleteOverlay(this.rightOverlayLine);
this.rightOverlayLine = null; this.rightOverlayLine = null;
} }
}, },
leftOverlayOff: function() { leftOverlayOff: function() {
if (this.leftOverlayLine !== null) { if (this.leftOverlayLine !== null) {
print('jbp inside left off') print('jbp inside left off');
Overlays.deleteOverlay(this.leftOverlayLine); Overlays.deleteOverlay(this.leftOverlayLine);
this.leftOverlayLine = null; this.leftOverlayLine = null;
} }
}, },
turnOffOverlayBeams: function() { turnOffOverlayBeams: function() {
this.rightOverlayOff(); this.rightOverlayOff();
this.leftOverlayOff(); 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() { createTargetOverlay: function() {
print('jbp should create target overlay');
print('jbp should create target overlay')
if (_this.targetOverlay !== null) { if (_this.targetOverlay !== null) {
return; return;
} }
@ -392,7 +376,7 @@
_this.targetOverlay = Overlays.addOverlay("model", targetOverlayProps); _this.targetOverlay = Overlays.addOverlay("model", targetOverlayProps);
print('jbp created target overlay: ' + _this.targetOverlay) print('jbp created target overlay: ' + _this.targetOverlay);
}, },
updateTargetOverlay: function(intersection) { updateTargetOverlay: function(intersection) {
@ -423,11 +407,11 @@
_this.targetOverlay = null; _this.targetOverlay = null;
}, },
handleEndOfDeck: function() { handleEndOfDeck: function() {
print('jbp at the end of the deck, no more.') print('jbp at the end of the deck, no more.');
}, },
createPlayingCard: function() { createPlayingCard: function() {
print('jbp should create playing card') print('jbp should create playing card');
if (_this.currentStack.cards.length > 0) { if (_this.currentStack.cards.length > 0) {
var card = _this.currentStack.draw(1); var card = _this.currentStack.draw(1);
} else { } else {
@ -435,7 +419,7 @@
return; return;
} }
print('jbp drew card: ' + card) print('jbp drew card: ' + card);
var properties = { var properties = {
type: 'Model', type: 'Model',
description: 'hifi:gameTable:game:playingCards', description: 'hifi:gameTable:game:playingCards',
@ -452,7 +436,7 @@
}, },
textures: JSON.stringify({ textures: JSON.stringify({
file1: PLAYING_CARD_BACK_IMAGE_URL, file1: PLAYING_CARD_BACK_IMAGE_URL,
file2: PLAYING_CARD_BACK_IMAGE_URL, file2: PLAYING_CARD_BACK_IMAGE_URL
}), }),
userData: JSON.stringify({ userData: JSON.stringify({
grabbableKey: { grabbableKey: {
@ -462,11 +446,11 @@
card: card card: card
} }
}) })
} };
Entities.addEntity(properties); Entities.addEntity(properties);
} }
} };
function Card(rank, suit) { function Card(rank, suit) {
this.rank = rank; this.rank = rank;
@ -474,14 +458,14 @@
} }
function stackImportCards(exportedCards) { function stackImportCards(exportedCards) {
print('jbp importing ' + exportedCards) print('jbp importing ' + exportedCards);
var cards = JSON.parse(exportedCards); var cards = JSON.parse(exportedCards);
this.cards = []; this.cards = [];
var cardArray = this.cards; var cardArray = this.cards;
cards.forEach(function(card) { cards.forEach(function(card) {
var newCard = new Card(card.substr(1, card.length), card[0]); var newCard = new Card(card.substr(1, card.length), card[0]);
cardArray.push(newCard) cardArray.push(newCard);
}) });
} }
function stackExportCards() { function stackExportCards() {
@ -499,9 +483,8 @@
function stackMakeDeck(n) { function stackMakeDeck(n) {
var ranks = new Array("A", "2", "3", "4", "5", "6", "7", "8", "9", var ranks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
"10", "J", "Q", "K"); var suits = ["C", "D", "H", "S"];
var suits = new Array("C", "D", "H", "S");
var i, j, k; var i, j, k;
var m; var m;
@ -509,15 +492,17 @@
// Set array of cards. // Set array of cards.
this.cards = new Array(); this.cards = [];
// Fill the array with 'n' packs of cards. // Fill the array with 'n' packs of cards.
for (i = 0; i < n; i++) for (i = 0; i < n; i++) {
for (j = 0; j < suits.length; j++) for (j = 0; j < suits.length; j++) {
for (k = 0; k < ranks.length; k++) for (k = 0; k < ranks.length; k++) {
this.cards[i * m + j * ranks.length + k] = this.cards[i * m + j * ranks.length + k] = new Card(ranks[k], suits[j]);
new Card(ranks[k], suits[j]); }
}
}
} }
function stackShuffle(n) { function stackShuffle(n) {
@ -527,21 +512,21 @@
// Shuffle the stack 'n' times. // 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++) { for (j = 0; j < this.cards.length; j++) {
k = Math.floor(Math.random() * this.cards.length); k = Math.floor(Math.random() * this.cards.length);
temp = this.cards[j]; temp = this.cards[j];
this.cards[j] = this.cards[k]; this.cards[j] = this.cards[k];
this.cards[k] = temp; this.cards[k] = temp;
} }
}
} }
function stackDeal() { function stackDeal() {
if (this.cards.length > 0) {
if (this.cards.length > 0)
return this.cards.shift(); return this.cards.shift();
else }
return null; return null;
} }
function stackDraw(n) { function stackDraw(n) {
@ -551,8 +536,9 @@
if (n >= 0 && n < this.cards.length) { if (n >= 0 && n < this.cards.length) {
card = this.cards[n]; card = this.cards[n];
this.cards.splice(n, 1); this.cards.splice(n, 1);
} else } else {
card = null; card = null;
}
return card; return card;
} }
@ -565,14 +551,14 @@
function stackCombine(stack) { function stackCombine(stack) {
this.cards = this.cards.concat(stack.cards); this.cards = this.cards.concat(stack.cards);
stack.cards = new Array(); stack.cards = [];
} }
function Stack() { function Stack() {
// Create an empty array of cards. // Create an empty array of cards.
this.cards = new Array(); this.cards = [];
this.makeDeck = stackMakeDeck; this.makeDeck = stackMakeDeck;
this.shuffle = stackShuffle; this.shuffle = stackShuffle;

View file

@ -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() { (function() {
var _this; var _this;
@ -14,8 +25,8 @@
preload: function(id) { preload: function(id) {
_this.entityID = id; _this.entityID = id;
}, },
startDistanceGrab:function(){ startDistanceGrab:function() {
_this.attachCardOverlay(); _this.attachCardOverlay();
}, },
startNearGrab: function() { startNearGrab: function() {
_this.attachCardOverlay(); _this.attachCardOverlay();
@ -24,8 +35,8 @@
_this.detachCardOverlay(); _this.detachCardOverlay();
}, },
attachCardOverlay: function() { attachCardOverlay: function() {
print('jbp should attach card overlay') print('jbp should attach card overlay');
var myProps = Entities.getEntityProperties(_this.entityID); var myProps = Entities.getEntityProperties(_this.entityID, ['position', 'rotation', 'dimensions']);
var cardFront = CARD_IMAGE_BASE_URL + _this.getCard().suit + this.getCard().rank + ".jpg"; var cardFront = CARD_IMAGE_BASE_URL + _this.getCard().suit + this.getCard().rank + ".jpg";
print('card front is:' + cardFront); print('card front is:' + cardFront);
var frontVec = Quat.getUp(myProps.rotation); var frontVec = Quat.getUp(myProps.rotation);
@ -37,24 +48,22 @@
dimensions: myProps.dimensions, dimensions: myProps.dimensions,
visible: true, visible: true,
drawInFront: 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() { Script.setTimeout(function() {
var success = Overlays.editOverlay(_this.cardOverlay, { var success = Overlays.editOverlay(_this.cardOverlay, {
textures: { textures: {
"file1": cardFront, "file1": cardFront,
"file2": CARD_BACK_IMAGE_URL, "file2": CARD_BACK_IMAGE_URL
}, }
}) });
print('jbp success on edit? ' + success) print('jbp success on edit? ' + success);
}, 1) }, 1);
}, },
detachCardOverlay: function() { detachCardOverlay: function() {
print('jbp should detach card overlay') print('jbp should detach card overlay');
Overlays.deleteOverlay(_this.cardOverlay); Overlays.deleteOverlay(_this.cardOverlay);
}, },
@ -62,23 +71,22 @@
return _this.getCurrentUserData().playingCards.card; return _this.getCurrentUserData().playingCards.card;
}, },
setCurrentUserData: function(data) { setCurrentUserData: function(data) {
var userData = getCurrentUserData(); var userData = _this.getCurrentUserData();
userData.playingCards = data; userData.playingCards = data;
Entities.editEntity(_this.entityID, { Entities.editEntity(_this.entityID, {
userData: userData userData: userData
}); });
}, },
getCurrentUserData: function() { getCurrentUserData: function() {
var props = Entities.getEntityProperties(_this.entityID); var userData = Entities.getEntityProperties(_this.entityID, 'userData').userData;
var json = null;
try { try {
json = JSON.parse(props.userData); return JSON.parse(userData);
} catch (e) { } catch (e) {
return; // e
} }
return json; return null;
}, }
} };
return new PlayingCard(); return new PlayingCard();
}) });

View file

@ -12,7 +12,6 @@
var _this; var _this;
var CLICK_SOUND_URL = Script.resolvePath('assets/sfx/woodenTapClick.wav'); var CLICK_SOUND_URL = Script.resolvePath('assets/sfx/woodenTapClick.wav');
var clickSound; var clickSound;
var myLocation;
function NextGameButton() { function NextGameButton() {
_this = this; _this = this;
@ -22,20 +21,6 @@
preload: function(id) { preload: function(id) {
_this.entityID = id; _this.entityID = id;
clickSound = SoundCache.getSound(CLICK_SOUND_URL); 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() { clickDownOnEntity: function() {
_this.nextGame(); _this.nextGame();
@ -43,12 +28,14 @@
startNearTrigger: function() { startNearTrigger: function() {
_this.nextGame(); _this.nextGame();
}, },
startFarTrigger: function() {},
nextGame: function() { nextGame: function() {
Audio.playSound(CLICK_SOUND_URL, { loop: false, position: myLocation, volume: 0.4 }); var buttonProperties = Entities.getEntityProperties(_this.entityID, ['position', 'parentID']);
var table = _this.getEntityFromGroup('gameTable', 'table'); Entities.callEntityMethod(buttonProperties.parentID, 'nextGame');
var tableString = table.substr(1, table.length - 2); Audio.playSound(clickSound, {
Entities.callEntityMethod(tableString, 'nextGame'); loop: false,
position: buttonProperties.position,
volume: 0.4
});
} }
}; };
return new NextGameButton(); return new NextGameButton();

View file

@ -7,20 +7,7 @@
ResetGameButton.prototype = { ResetGameButton.prototype = {
preload: function(id) { preload: function(id) {
_this.entityID = 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;
}, },
clickDownOnEntity: function() { clickDownOnEntity: function() {
_this.resetGame(); _this.resetGame();
@ -31,8 +18,7 @@
startFarTrigger: function() {}, startFarTrigger: function() {},
resetGame: function() { resetGame: function() {
print('reset game button calling resetGame'); print('reset game button calling resetGame');
var table = _this.getEntityFromGroup('gameTable', 'table'); Entities.callEntityMethod(Entities.getEntityProperties(_this.entityID, ['parentID']).parentID, 'resetGame');
Entities.callEntityMethod(table, 'resetGame');
} }
}; };
return new ResetGameButton(); return new ResetGameButton();

View file

@ -8,7 +8,7 @@
(function() { (function() {
var _this; var _this;
var DONT_SNAP_WHEN_FARTHER_THAN_THIS = 0.25; var DO_NOT_SNAP_WHEN_FARTHER_THAN_THIS = 0.25;
function SnapToGrid() { function SnapToGrid() {
_this = this; _this = this;
@ -32,21 +32,21 @@
}, },
getAnchorPoints: function() { getAnchorPoints: function() {
var availableAnchors = []; var availableAnchors = [];
var results = _this.getEntityFromGroup('gameTable', 'anchor'); var results = _this.getEntitiesFromGroup('gameTable', 'anchor');
results.forEach(function(item) { results.forEach(function(item) {
var props = Entities.getEntityProperties(item); var properties = Entities.getEntityProperties(item, ['position', 'userData']);
if (props.userData === 'occupied') { if (properties.userData === 'occupied') {
//don't put it on the stack // don't put it on the stack
} else if (props.userData === 'available') { } else if (properties.userData === 'available') {
availableAnchors.push(props.position); availableAnchors.push(properties.position);
} }
}); });
return availableAnchors; return availableAnchors;
}, },
attachToNearestAnchor: function() { attachToNearestAnchor: function() {
var myProps = Entities.getEntityProperties(_this.entityID); var myProps = Entities.getEntityProperties(_this.entityID, ['position', 'dimensions']);
var anchors = _this.getAnchorPoints(); var anchors = _this.getAnchorPoints();
var shortestDistance = DONT_SNAP_WHEN_FARTHER_THAN_THIS; var shortestDistance = DO_NOT_SNAP_WHEN_FARTHER_THAN_THIS;
var nearestAnchor = null; var nearestAnchor = null;
anchors.forEach(function(anchor) { anchors.forEach(function(anchor) {
var howFar = Vec3.distance(myProps.position, 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({ _this.setCurrentUserData({
attachedTo: null attachedTo: null
}); });
@ -70,7 +70,7 @@
userData: 'occupied' userData: 'occupied'
}); });
} else { } else {
//there is no nearest anchor. perhaps they are all occupied. // there is no nearest anchor. perhaps they are all occupied.
_this.setCurrentUserData({ _this.setCurrentUserData({
attachedTo: null attachedTo: null
}); });
@ -78,17 +78,18 @@
} }
}, },
getEntityFromGroup: function(groupName, entityName) { getEntitiesFromGroup: function(groupName, entityName) {
var props = Entities.getEntityProperties(_this.entityID); var position = Entities.getEntityProperties(_this.entityID, 'position').position;
var results = Entities.findEntities(props.position, 7.5); var nearbyEntities = Entities.findEntities(position, 7.5);
var found; var foundItems = [];
results.forEach(function(item) { nearbyEntities.forEach(function(entityID) {
var itemProps = Entities.getEntityProperties(item); var description = Entities.getEntityProperties(entityID, 'description').description;
var descriptionSplit = itemProps.description.split(":"); var descriptionSplit = description.split(":");
if (descriptionSplit[1] === groupName && descriptionSplit[2] === entityName) { if (descriptionSplit[1] === groupName && descriptionSplit[2] === entityName) {
return item; foundItems.push(entityID);
} }
}); });
return foundItems;
}, },
positionOnAnchor: function(anchor, myProps) { positionOnAnchor: function(anchor, myProps) {
Entities.editEntity(_this.entityID, { Entities.editEntity(_this.entityID, {
@ -97,24 +98,23 @@
y: anchor.y + (0.5 * myProps.dimensions.y), y: anchor.y + (0.5 * myProps.dimensions.y),
z: anchor.z z: anchor.z
} }
}) });
}, },
setCurrentUserData: function(data) { setCurrentUserData: function(data) {
var userData = getCurrentUserData(); var userData = _this.getCurrentUserData();
userData.gameTable = data; userData.gameTable = data;
Entities.editEntity(_this.entityID, { Entities.editEntity(_this.entityID, {
userData: userData userData: userData
}); });
}, },
getCurrentUserData: function() { getCurrentUserData: function() {
var props = Entities.getEntityProperties(_this.entityID); var userData = Entities.getEntityProperties(_this.entityID, 'userData').userData;
var json = null;
try { try {
json = JSON.parse(props.userData); return JSON.parse(userData);
} catch (e) { } catch (e) {
return; // e;
} }
return json; return null;
} }
} };
}); });

View file

@ -9,12 +9,22 @@
// //
(function() { (function() {
var CLEARCACHE = "?"+Math.random().toString(36).substring(7); var GAMES_LIST_ENDPOINT = Script.resolvePath('games/gamesDirectory.svo.json');
var GAMES_LIST_ENDPOINT = Script.resolvePath('games/gamesDirectory.svo.json') + CLEARCACHE;
var _this; var _this;
var INITIAL_DELAY = 1000; 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() { function GameTable() {
_this = this; _this = this;
} }
@ -29,17 +39,17 @@
}, INITIAL_DELAY); }, INITIAL_DELAY);
}, },
collisionWithEntity: function(me, other, collision) { collisionWithEntity: function(me, other, collision) {
//stick the table to the ground // stick the table to the ground
if (collision.type !== 1) { if (collision.type !== 1) {
return; return;
} }
var myProps = Entities.getEntityProperties(_this.entityID, ["rotation", "position"]); var myProps = Entities.getEntityProperties(_this.entityID, ['rotation', 'position']);
var eulerRotation = Quat.safeEulerAngles(myProps.rotation); var eulerRotation = Quat.safeEulerAngles(myProps.rotation);
eulerRotation.x = 0; eulerRotation.x = 0;
eulerRotation.z = 0; eulerRotation.z = 0;
var newRotation = Quat.fromVec3Degrees(eulerRotation); 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, { Entities.editEntity(_this.entityID, {
rotation: newRotation, rotation: newRotation,
dynamic: true, dynamic: true,
@ -88,15 +98,15 @@
_this.cleanupGameEntities(); _this.cleanupGameEntities();
}, },
cleanupGameEntities: function() { cleanupGameEntities: function() {
var props = Entities.getEntityProperties(_this.entityID); var position = Entities.getEntityProperties(_this.entityID, 'position').position;
var results = Entities.findEntities(props.position, 5); var results = Entities.findEntities(position, 5.0);
var found = []; var found = [];
results.forEach(function(item) { results.forEach(function(item) {
var itemProps = Entities.getEntityProperties(item); var description = Entities.getEntityProperties(item, 'description').description;
if (itemProps.description.indexOf('hifi:gameTable:piece:') === 0) { if (description.indexOf('hifi:gameTable:piece:') === 0) {
found.push(item); found.push(item);
} }
if (itemProps.description.indexOf('hifi:gameTable:anchor') > -1) { if (description.indexOf('hifi:gameTable:anchor') > -1) {
found.push(item); found.push(item);
} }
}); });
@ -113,7 +123,6 @@
}, },
setCurrentGame: function() { setCurrentGame: function() {
print('index in set current game: ' + _this.currentGameIndex); 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]); print('game at index' + _this.gamesList[_this.currentGameIndex]);
_this.currentGame = _this.gamesList[_this.currentGameIndex].gameName; _this.currentGame = _this.gamesList[_this.currentGameIndex].gameName;
_this.currentGameFull = _this.gamesList[_this.currentGameIndex]; _this.currentGameFull = _this.gamesList[_this.currentGameIndex];
@ -124,52 +133,44 @@
setCurrentUserData: function(data) { setCurrentUserData: function(data) {
var userData = _this.getCurrentUserData(); var userData = _this.getCurrentUserData();
userData['gameTableData'] = data; userData['gameTableData'] = data;
var success = Entities.editEntity(_this.entityID, { Entities.editEntity(_this.entityID, {
userData: JSON.stringify(userData) userData: JSON.stringify(userData)
}); });
}, },
getCurrentUserData: function() { getCurrentUserData: function() {
var props = Entities.getEntityProperties(_this.entityID); var userData = Entities.getEntityProperties(_this.entityID, ['userData']).userData;
var hasUserData = props.hasOwnProperty('userData');
var json = {};
try { try {
json = JSON.parse(props.userData); return JSON.parse(userData);
} catch (e) { } catch (e) {
print('user data is not json' + props.userData) print('user data is not json' + userData);
} }
return json; return {};
}, },
getEntityFromGroup: function(groupName, entityName) { getEntityFromGroup: function(groupName, entityName) {
print('getting entity from group: ' + groupName); print('getting entity from group: ' + groupName);
var props = Entities.getEntityProperties(_this.entityID); var position = Entities.getEntityProperties(_this.entityID, ['position']).position;
var results = Entities.findEntities(props.position, 7.5); var results = Entities.findEntities(position, 7.5);
var found;
var result = null; var result = null;
results.forEach(function(item) { results.forEach(function(item) {
var itemProps = Entities.getEntityProperties(item); var description = Entities.getEntityProperties(item, 'description').description;
var descriptionSplit = description.split(":");
var descriptionSplit = itemProps.description.split(":");
if (descriptionSplit[1] === groupName && descriptionSplit[2] === entityName) { if (descriptionSplit[1] === groupName && descriptionSplit[2] === entityName) {
result = item; result = item;
} }
}); });
return result return result;
}, },
spawnEntitiesForGame: function() { spawnEntitiesForGame: function() {
var entitySpawner = _this.getEntityFromGroup('gameTable', 'entitySpawner'); var entitySpawner = _this.getEntityFromGroup('gameTable', 'entitySpawner');
var mat = _this.getEntityFromGroup('gameTable', 'mat'); var mat = _this.getEntityFromGroup('gameTable', 'mat');
Entities.callEntityMethod(entitySpawner, 'spawnEntities', [JSON.stringify(_this.currentGameFull),mat, Entities.callEntityMethod(entitySpawner, 'spawnEntities', [
_this.entityID]); 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(); return new GameTable();
}); });