//// EntityTreeRenderer.cpp// interface/src//// Created by Brad Hefta-Gaub on 12/6/13.// Copyright 2013 High Fidelity, Inc.//// Distributed under the Apache License, Version 2.0.// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html// #include <gpu/GPUConfig.h>#include <gpu/GLBackend.h> #include <glm/gtx/quaternion.hpp> #include <QEventLoop>#include <QScriptSyntaxCheckResult> #include <AbstractScriptingServicesInterface.h>#include <AbstractViewStateInterface.h>#include <DeferredLightingEffect.h>#include <GlowEffect.h>#include <Model.h>#include <NetworkAccessManager.h>#include <PerfStat.h>#include <SceneScriptingInterface.h>#include <ScriptEngine.h>#include <TextureCache.h> #include "EntityTreeRenderer.h" #include "RenderableEntityItem.h" #include "RenderableBoxEntityItem.h"#include "RenderableLightEntityItem.h"#include "RenderableModelEntityItem.h"#include "RenderableParticleEffectEntityItem.h"#include "RenderableSphereEntityItem.h"#include "RenderableTextEntityItem.h"#include "RenderableWebEntityItem.h"#include "RenderableZoneEntityItem.h"#include "RenderableLineEntityItem.h"#include "RenderablePolyVoxEntityItem.h"#include "EntitiesRendererLogging.h" EntityTreeRenderer::EntityTreeRenderer(bool wantScripts, AbstractViewStateInterface* viewState, AbstractScriptingServicesInterface* scriptingServices) : OctreeRenderer(), _wantScripts(wantScripts), _entitiesScriptEngine(NULL), _sandboxScriptEngine(NULL), _lastMouseEventValid(false), _viewState(viewState), _scriptingServices(scriptingServices), _displayElementChildProxies(false), _displayModelBounds(false), _displayModelElementProxy(false), _dontDoPrecisionPicking(false){ REGISTER_ENTITY_TYPE_WITH_FACTORY(Model, RenderableModelEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(Box, RenderableBoxEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(Sphere, RenderableSphereEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(Light, RenderableLightEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(Text, RenderableTextEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(Web, RenderableWebEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(ParticleEffect, RenderableParticleEffectEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(Zone, RenderableZoneEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(Line, RenderableLineEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(PolyVox, RenderablePolyVoxEntityItem::factory) _currentHoverOverEntityID = UNKNOWN_ENTITY_ID; _currentClickingOnEntityID = UNKNOWN_ENTITY_ID;} EntityTreeRenderer::~EntityTreeRenderer() { // NOTE: we don't need to delete _entitiesScriptEngine because it is registered with the application and has a // signal tied to call it's deleteLater on doneRunning if (_sandboxScriptEngine) { // TODO: consider reworking how _sandboxScriptEngine is managed. It's treated differently than _entitiesScriptEngine // because we don't call registerScriptEngineWithApplicationServices() for it. This implementation is confusing and // potentially error prone because it's not a full fledged ScriptEngine that has been fully connected to the // application. We did this so that scripts that were ill-formed could be evaluated but not execute against the // application services. But this means it's shutdown behavior is different from other ScriptEngines delete _sandboxScriptEngine; _sandboxScriptEngine = NULL; }} void EntityTreeRenderer::clear() { leaveAllEntities(); foreach (const EntityItemID& entityID, _entityScripts.keys()) { checkAndCallUnload(entityID); } OctreeRenderer::clear(); _entityScripts.clear(); auto scene = _viewState->getMain3DScene(); render::PendingChanges pendingChanges; foreach(auto entity, _entitiesInScene) { entity->removeFromScene(entity, scene, pendingChanges); } scene->enqueuePendingChanges(pendingChanges); _entitiesInScene.clear();} void EntityTreeRenderer::init() { OctreeRenderer::init(); EntityTree* entityTree = static_cast<EntityTree*>(_tree); entityTree->setFBXService(this); if (_wantScripts) { _entitiesScriptEngine = new ScriptEngine(NO_SCRIPT, "Entities", _scriptingServices->getControllerScriptingInterface()); _scriptingServices->registerScriptEngineWithApplicationServices(_entitiesScriptEngine); _sandboxScriptEngine = new ScriptEngine(NO_SCRIPT, "Entities Sandbox", NULL); } // make sure our "last avatar position" is something other than our current position, so that on our // first chance, we'll check for enter/leave entity events. _lastAvatarPosition = _viewState->getAvatarPosition() + glm::vec3((float)TREE_SCALE); connect(entityTree, &EntityTree::deletingEntity, this, &EntityTreeRenderer::deletingEntity); connect(entityTree, &EntityTree::addingEntity, this, &EntityTreeRenderer::addingEntity); connect(entityTree, &EntityTree::entityScriptChanging, this, &EntityTreeRenderer::entitySciptChanging);} void EntityTreeRenderer::shutdown() { _entitiesScriptEngine->disconnect(); // disconnect all slots/signals from the script engine _shuttingDown = true;} void EntityTreeRenderer::scriptContentsAvailable(const QUrl& url, const QString& scriptContents) { if (_waitingOnPreload.contains(url)) { QList<EntityItemID> entityIDs = _waitingOnPreload.values(url); _waitingOnPreload.remove(url); foreach(EntityItemID entityID, entityIDs) { checkAndCallPreload(entityID); } }} void EntityTreeRenderer::errorInLoadingScript(const QUrl& url) { if (_waitingOnPreload.contains(url)) { _waitingOnPreload.remove(url); }} QScriptValue EntityTreeRenderer::loadEntityScript(const EntityItemID& entityItemID, bool isPreload) { EntityItemPointer entity = static_cast<EntityTree*>(_tree)->findEntityByEntityItemID(entityItemID); return loadEntityScript(entity, isPreload);} QString EntityTreeRenderer::loadScriptContents(const QString& scriptMaybeURLorText, bool& isURL, bool& isPending, QUrl& urlOut) { isPending = false; QUrl url(scriptMaybeURLorText); // If the url is not valid, this must be script text... // We document "direct injection" scripts as starting with "(function...", and that would never be a valid url. // But QUrl thinks it is. if (!url.isValid() || scriptMaybeURLorText.startsWith("(")) { isURL = false; return scriptMaybeURLorText; } isURL = true; urlOut = url; QString scriptContents; // assume empty // if the scheme length is one or lower, maybe they typed in a file, let's try const int WINDOWS_DRIVE_LETTER_SIZE = 1; if (url.scheme().size() <= WINDOWS_DRIVE_LETTER_SIZE) { url = QUrl::fromLocalFile(scriptMaybeURLorText); } // ok, let's see if it's valid... and if so, load it if (url.isValid()) { if (url.scheme() == "file") { QString fileName = url.toLocalFile(); QFile scriptFile(fileName); if (scriptFile.open(QFile::ReadOnly | QFile::Text)) { qCDebug(entitiesrenderer) << "Loading file:" << fileName; QTextStream in(&scriptFile); scriptContents = in.readAll(); } else { qCDebug(entitiesrenderer) << "ERROR Loading file:" << fileName; } } else { auto scriptCache = DependencyManager::get<ScriptCache>(); if (!scriptCache->isInBadScriptList(url)) { scriptContents = scriptCache->getScript(url, this, isPending); } } } return scriptContents;} QScriptValue EntityTreeRenderer::loadEntityScript(EntityItemPointer entity, bool isPreload) { if (_shuttingDown) { return QScriptValue(); // since we're shutting down, we don't load any more scripts } if (!entity) { return QScriptValue(); // no entity... } // NOTE: we keep local variables for the entityID and the script because // below in loadScriptContents() it's possible for us to execute the // application event loop, which may cause our entity to be deleted on // us. We don't really need access the entity after this point, can // can accomplish all we need to here with just the script "text" and the ID. EntityItemID entityID = entity->getEntityItemID(); QString entityScript = entity->getScript(); if (_entityScripts.contains(entityID)) { EntityScriptDetails details = _entityScripts[entityID]; // check to make sure our script text hasn't changed on us since we last loaded it if (details.scriptText == entityScript) { return details.scriptObject; // previously loaded } // if we got here, then we previously loaded a script, but the entity's script value // has changed and so we need to reload it. _entityScripts.remove(entityID); } if (entityScript.isEmpty()) { return QScriptValue(); // no script } bool isURL = false; // loadScriptContents() will tell us if this is a URL or just text. bool isPending = false; QUrl url; QString scriptContents = loadScriptContents(entityScript, isURL, isPending, url); if (isPending && isPreload && isURL) { _waitingOnPreload.insert(url, entityID); } auto scriptCache = DependencyManager::get<ScriptCache>(); if (isURL && scriptCache->isInBadScriptList(url)) { return QScriptValue(); // no script contents... } if (scriptContents.isEmpty()) { return QScriptValue(); // no script contents... } QScriptSyntaxCheckResult syntaxCheck = QScriptEngine::checkSyntax(scriptContents); if (syntaxCheck.state() != QScriptSyntaxCheckResult::Valid) { qCDebug(entitiesrenderer) << "EntityTreeRenderer::loadEntityScript() entity:" << entityID; qCDebug(entitiesrenderer) << " " << syntaxCheck.errorMessage() << ":" << syntaxCheck.errorLineNumber() << syntaxCheck.errorColumnNumber(); qCDebug(entitiesrenderer) << " SCRIPT:" << entityScript; scriptCache->addScriptToBadScriptList(url); return QScriptValue(); // invalid script } if (isURL) { _entitiesScriptEngine->setParentURL(entity->getScript()); } QScriptValue entityScriptConstructor = _sandboxScriptEngine->evaluate(scriptContents); if (!entityScriptConstructor.isFunction()) { qCDebug(entitiesrenderer) << "EntityTreeRenderer::loadEntityScript() entity:" << entityID; qCDebug(entitiesrenderer) << " NOT CONSTRUCTOR"; qCDebug(entitiesrenderer) << " SCRIPT:" << entityScript; scriptCache->addScriptToBadScriptList(url); return QScriptValue(); // invalid script } else { entityScriptConstructor = _entitiesScriptEngine->evaluate(scriptContents); } QScriptValue entityScriptObject = entityScriptConstructor.construct(); EntityScriptDetails newDetails = { entityScript, entityScriptObject }; _entityScripts[entityID] = newDetails; if (isURL) { _entitiesScriptEngine->setParentURL(""); } return entityScriptObject; // newly constructed} QScriptValue EntityTreeRenderer::getPreviouslyLoadedEntityScript(const EntityItemID& entityID) { if (_entityScripts.contains(entityID)) { EntityScriptDetails details = _entityScripts[entityID]; return details.scriptObject; // previously loaded } return QScriptValue(); // no script} void EntityTreeRenderer::setTree(Octree* newTree) { OctreeRenderer::setTree(newTree); static_cast<EntityTree*>(_tree)->setFBXService(this);} void EntityTreeRenderer::update() { if (_tree && !_shuttingDown) { EntityTree* tree = static_cast<EntityTree*>(_tree); tree->update(); // check to see if the avatar has moved and if we need to handle enter/leave entity logic checkEnterLeaveEntities(); // Even if we're not moving the mouse, if we started clicking on an entity and we have // not yet released the hold then this is still considered a holdingClickOnEntity event // and we want to simulate this message here as well as in mouse move if (_lastMouseEventValid && !_currentClickingOnEntityID.isInvalidID()) { emit holdingClickOnEntity(_currentClickingOnEntityID, _lastMouseEvent); QScriptValueList currentClickingEntityArgs = createMouseEventArgs(_currentClickingOnEntityID, _lastMouseEvent); QScriptValue currentClickingEntity = loadEntityScript(_currentClickingOnEntityID); if (currentClickingEntity.property("holdingClickOnEntity").isValid()) { currentClickingEntity.property("holdingClickOnEntity").call(currentClickingEntity, currentClickingEntityArgs); } } }} void EntityTreeRenderer::checkEnterLeaveEntities() { if (_tree && !_shuttingDown) { glm::vec3 avatarPosition = _viewState->getAvatarPosition(); if (avatarPosition != _lastAvatarPosition) { float radius = 1.0f; // for now, assume 1 meter radius QVector<EntityItemPointer> foundEntities; QVector<EntityItemID> entitiesContainingAvatar; // find the entities near us _tree->lockForRead(); // don't let someone else change our tree while we search static_cast<EntityTree*>(_tree)->findEntities(avatarPosition, radius, foundEntities); // create a list of entities that actually contain the avatar's position foreach(EntityItemPointer entity, foundEntities) { if (entity->contains(avatarPosition)) { entitiesContainingAvatar << entity->getEntityItemID(); } } _tree->unlock(); // Note: at this point we don't need to worry about the tree being locked, because we only deal with // EntityItemIDs from here. The loadEntityScript() method is robust against attempting to load scripts // for entity IDs that no longer exist. // for all of our previous containing entities, if they are no longer containing then send them a leave event foreach(const EntityItemID& entityID, _currentEntitiesInside) { if (!entitiesContainingAvatar.contains(entityID)) { emit leaveEntity(entityID); QScriptValueList entityArgs = createEntityArgs(entityID); QScriptValue entityScript = loadEntityScript(entityID); if (entityScript.property("leaveEntity").isValid()) { entityScript.property("leaveEntity").call(entityScript, entityArgs); } } } // for all of our new containing entities, if they weren't previously containing then send them an enter event foreach(const EntityItemID& entityID, entitiesContainingAvatar) { if (!_currentEntitiesInside.contains(entityID)) { emit enterEntity(entityID); QScriptValueList entityArgs = createEntityArgs(entityID); QScriptValue entityScript = loadEntityScript(entityID); if (entityScript.property("enterEntity").isValid()) { entityScript.property("enterEntity").call(entityScript, entityArgs); } } } _currentEntitiesInside = entitiesContainingAvatar; _lastAvatarPosition = avatarPosition; } }} void EntityTreeRenderer::leaveAllEntities() { if (_tree && !_shuttingDown) { // for all of our previous containing entities, if they are no longer containing then send them a leave event foreach(const EntityItemID& entityID, _currentEntitiesInside) { emit leaveEntity(entityID); QScriptValueList entityArgs = createEntityArgs(entityID); QScriptValue entityScript = loadEntityScript(entityID); if (entityScript.property("leaveEntity").isValid()) { entityScript.property("leaveEntity").call(entityScript, entityArgs); } } _currentEntitiesInside.clear(); // make sure our "last avatar position" is something other than our current position, so that on our // first chance, we'll check for enter/leave entity events. _lastAvatarPosition = _viewState->getAvatarPosition() + glm::vec3((float)TREE_SCALE); }} void EntityTreeRenderer::applyZonePropertiesToScene(std::shared_ptr<ZoneEntityItem> zone) { QSharedPointer<SceneScriptingInterface> scene = DependencyManager::get<SceneScriptingInterface>(); if (zone) { if (!_hasPreviousZone) { _previousKeyLightColor = scene->getKeyLightColor(); _previousKeyLightIntensity = scene->getKeyLightIntensity(); _previousKeyLightAmbientIntensity = scene->getKeyLightAmbientIntensity(); _previousKeyLightDirection = scene->getKeyLightDirection(); _previousStageSunModelEnabled = scene->isStageSunModelEnabled(); _previousStageLongitude = scene->getStageLocationLongitude(); _previousStageLatitude = scene->getStageLocationLatitude(); _previousStageAltitude = scene->getStageLocationAltitude(); _previousStageHour = scene->getStageDayTime(); _previousStageDay = scene->getStageYearTime(); _hasPreviousZone = true; } scene->setKeyLightColor(zone->getKeyLightColorVec3()); scene->setKeyLightIntensity(zone->getKeyLightIntensity()); scene->setKeyLightAmbientIntensity(zone->getKeyLightAmbientIntensity()); scene->setKeyLightDirection(zone->getKeyLightDirection()); scene->setStageSunModelEnable(zone->getStageProperties().getSunModelEnabled()); scene->setStageLocation(zone->getStageProperties().getLongitude(), zone->getStageProperties().getLatitude(), zone->getStageProperties().getAltitude()); scene->setStageDayTime(zone->getStageProperties().calculateHour()); scene->setStageYearTime(zone->getStageProperties().calculateDay()); if (zone->getBackgroundMode() == BACKGROUND_MODE_ATMOSPHERE) { EnvironmentData data = zone->getEnvironmentData(); glm::vec3 keyLightDirection = scene->getKeyLightDirection(); glm::vec3 inverseKeyLightDirection = keyLightDirection * -1.0f; // NOTE: is this right? It seems like the "sun" should be based on the center of the // atmosphere, not where the camera is. glm::vec3 keyLightLocation = _viewState->getAvatarPosition() + (inverseKeyLightDirection * data.getAtmosphereOuterRadius()); data.setSunLocation(keyLightLocation); const float KEY_LIGHT_INTENSITY_TO_SUN_BRIGHTNESS_RATIO = 20.0f; float sunBrightness = scene->getKeyLightIntensity() * KEY_LIGHT_INTENSITY_TO_SUN_BRIGHTNESS_RATIO; data.setSunBrightness(sunBrightness); _viewState->overrideEnvironmentData(data); scene->getSkyStage()->setBackgroundMode(model::SunSkyStage::SKY_DOME); } else { _viewState->endOverrideEnvironmentData(); auto stage = scene->getSkyStage(); if (zone->getBackgroundMode() == BACKGROUND_MODE_SKYBOX) { stage->getSkybox()->setColor(zone->getSkyboxProperties().getColorVec3()); if (zone->getSkyboxProperties().getURL().isEmpty()) { stage->getSkybox()->setCubemap(gpu::TexturePointer()); } else { // Update the Texture of the Skybox with the one pointed by this zone auto cubeMap = DependencyManager::get<TextureCache>()->getTexture(zone->getSkyboxProperties().getURL(), CUBE_TEXTURE); stage->getSkybox()->setCubemap(cubeMap->getGPUTexture()); } stage->setBackgroundMode(model::SunSkyStage::SKY_BOX); } else { stage->setBackgroundMode(model::SunSkyStage::SKY_DOME); // let the application atmosphere through } } } else { if (_hasPreviousZone) { scene->setKeyLightColor(_previousKeyLightColor); scene->setKeyLightIntensity(_previousKeyLightIntensity); scene->setKeyLightAmbientIntensity(_previousKeyLightAmbientIntensity); scene->setKeyLightDirection(_previousKeyLightDirection); scene->setStageSunModelEnable(_previousStageSunModelEnabled); scene->setStageLocation(_previousStageLongitude, _previousStageLatitude, _previousStageAltitude); scene->setStageDayTime(_previousStageHour); scene->setStageYearTime(_previousStageDay); _hasPreviousZone = false; } _viewState->endOverrideEnvironmentData(); scene->getSkyStage()->setBackgroundMode(model::SunSkyStage::SKY_DOME); // let the application atmosphere through }} void EntityTreeRenderer::render(RenderArgs* renderArgs) { if (_tree && !_shuttingDown) { renderArgs->_renderer = this; _tree->lockForRead(); // Whenever you're in an intersection between zones, we will always choose the smallest zone. _bestZone = NULL; // NOTE: Is this what we want? _bestZoneVolume = std::numeric_limits<float>::max(); // FIX ME: right now the renderOperation does the following: // 1) determining the best zone (not really rendering) // 2) render the debug cell details // we should clean this upLines 1–500 of 1144. Load more
// // EntityTreeRenderer.cpp // interface/src // // Created by Brad Hefta-Gaub on 12/6/13. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include <gpu/GPUConfig.h> #include <gpu/GLBackend.h> #include <glm/gtx/quaternion.hpp> #include <QEventLoop> #include <QScriptSyntaxCheckResult> #include <AbstractScriptingServicesInterface.h> #include <AbstractViewStateInterface.h> #include <DeferredLightingEffect.h> #include <GlowEffect.h> #include <Model.h> #include <NetworkAccessManager.h> #include <PerfStat.h> #include <SceneScriptingInterface.h> #include <ScriptEngine.h> #include <TextureCache.h> #include "EntityTreeRenderer.h" #include "RenderableEntityItem.h" #include "RenderableBoxEntityItem.h" #include "RenderableLightEntityItem.h" #include "RenderableModelEntityItem.h" #include "RenderableParticleEffectEntityItem.h" #include "RenderableSphereEntityItem.h" #include "RenderableTextEntityItem.h" #include "RenderableWebEntityItem.h" #include "RenderableZoneEntityItem.h" #include "RenderableLineEntityItem.h" #include "RenderablePolyVoxEntityItem.h" #include "EntitiesRendererLogging.h" EntityTreeRenderer::EntityTreeRenderer(bool wantScripts, AbstractViewStateInterface* viewState, AbstractScriptingServicesInterface* scriptingServices) : OctreeRenderer(), _wantScripts(wantScripts), _entitiesScriptEngine(NULL), _sandboxScriptEngine(NULL), _lastMouseEventValid(false), _viewState(viewState), _scriptingServices(scriptingServices), _displayElementChildProxies(false), _displayModelBounds(false), _displayModelElementProxy(false), _dontDoPrecisionPicking(false) { REGISTER_ENTITY_TYPE_WITH_FACTORY(Model, RenderableModelEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(Box, RenderableBoxEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(Sphere, RenderableSphereEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(Light, RenderableLightEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(Text, RenderableTextEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(Web, RenderableWebEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(ParticleEffect, RenderableParticleEffectEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(Zone, RenderableZoneEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(Line, RenderableLineEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(PolyVox, RenderablePolyVoxEntityItem::factory) _currentHoverOverEntityID = UNKNOWN_ENTITY_ID; _currentClickingOnEntityID = UNKNOWN_ENTITY_ID; } EntityTreeRenderer::~EntityTreeRenderer() { // NOTE: we don't need to delete _entitiesScriptEngine because it is registered with the application and has a // signal tied to call it's deleteLater on doneRunning if (_sandboxScriptEngine) { // TODO: consider reworking how _sandboxScriptEngine is managed. It's treated differently than _entitiesScriptEngine // because we don't call registerScriptEngineWithApplicationServices() for it. This implementation is confusing and // potentially error prone because it's not a full fledged ScriptEngine that has been fully connected to the // application. We did this so that scripts that were ill-formed could be evaluated but not execute against the // application services. But this means it's shutdown behavior is different from other ScriptEngines delete _sandboxScriptEngine; _sandboxScriptEngine = NULL; } } void EntityTreeRenderer::clear() { leaveAllEntities(); foreach (const EntityItemID& entityID, _entityScripts.keys()) { checkAndCallUnload(entityID); } OctreeRenderer::clear(); _entityScripts.clear(); auto scene = _viewState->getMain3DScene(); render::PendingChanges pendingChanges; foreach(auto entity, _entitiesInScene) { entity->removeFromScene(entity, scene, pendingChanges); } scene->enqueuePendingChanges(pendingChanges); _entitiesInScene.clear(); } void EntityTreeRenderer::init() { OctreeRenderer::init(); EntityTree* entityTree = static_cast<EntityTree*>(_tree); entityTree->setFBXService(this); if (_wantScripts) { _entitiesScriptEngine = new ScriptEngine(NO_SCRIPT, "Entities", _scriptingServices->getControllerScriptingInterface()); _scriptingServices->registerScriptEngineWithApplicationServices(_entitiesScriptEngine); _sandboxScriptEngine = new ScriptEngine(NO_SCRIPT, "Entities Sandbox", NULL); } // make sure our "last avatar position" is something other than our current position, so that on our // first chance, we'll check for enter/leave entity events. _lastAvatarPosition = _viewState->getAvatarPosition() + glm::vec3((float)TREE_SCALE); connect(entityTree, &EntityTree::deletingEntity, this, &EntityTreeRenderer::deletingEntity); connect(entityTree, &EntityTree::addingEntity, this, &EntityTreeRenderer::addingEntity); connect(entityTree, &EntityTree::entityScriptChanging, this, &EntityTreeRenderer::entitySciptChanging); } void EntityTreeRenderer::shutdown() { _entitiesScriptEngine->disconnect(); // disconnect all slots/signals from the script engine _shuttingDown = true; } void EntityTreeRenderer::scriptContentsAvailable(const QUrl& url, const QString& scriptContents) { if (_waitingOnPreload.contains(url)) { QList<EntityItemID> entityIDs = _waitingOnPreload.values(url); _waitingOnPreload.remove(url); foreach(EntityItemID entityID, entityIDs) { checkAndCallPreload(entityID); } } } void EntityTreeRenderer::errorInLoadingScript(const QUrl& url) { if (_waitingOnPreload.contains(url)) { _waitingOnPreload.remove(url); } } QScriptValue EntityTreeRenderer::loadEntityScript(const EntityItemID& entityItemID, bool isPreload) { EntityItemPointer entity = static_cast<EntityTree*>(_tree)->findEntityByEntityItemID(entityItemID); return loadEntityScript(entity, isPreload); } QString EntityTreeRenderer::loadScriptContents(const QString& scriptMaybeURLorText, bool& isURL, bool& isPending, QUrl& urlOut) { isPending = false; QUrl url(scriptMaybeURLorText); // If the url is not valid, this must be script text... // We document "direct injection" scripts as starting with "(function...", and that would never be a valid url. // But QUrl thinks it is. if (!url.isValid() || scriptMaybeURLorText.startsWith("(")) { isURL = false; return scriptMaybeURLorText; } isURL = true; urlOut = url; QString scriptContents; // assume empty // if the scheme length is one or lower, maybe they typed in a file, let's try const int WINDOWS_DRIVE_LETTER_SIZE = 1; if (url.scheme().size() <= WINDOWS_DRIVE_LETTER_SIZE) { url = QUrl::fromLocalFile(scriptMaybeURLorText); } // ok, let's see if it's valid... and if so, load it if (url.isValid()) { if (url.scheme() == "file") { QString fileName = url.toLocalFile(); QFile scriptFile(fileName); if (scriptFile.open(QFile::ReadOnly | QFile::Text)) { qCDebug(entitiesrenderer) << "Loading file:" << fileName; QTextStream in(&scriptFile); scriptContents = in.readAll(); } else { qCDebug(entitiesrenderer) << "ERROR Loading file:" << fileName; } } else { auto scriptCache = DependencyManager::get<ScriptCache>(); if (!scriptCache->isInBadScriptList(url)) { scriptContents = scriptCache->getScript(url, this, isPending); } } } return scriptContents; } QScriptValue EntityTreeRenderer::loadEntityScript(EntityItemPointer entity, bool isPreload) { if (_shuttingDown) { return QScriptValue(); // since we're shutting down, we don't load any more scripts } if (!entity) { return QScriptValue(); // no entity... } // NOTE: we keep local variables for the entityID and the script because // below in loadScriptContents() it's possible for us to execute the // application event loop, which may cause our entity to be deleted on // us. We don't really need access the entity after this point, can // can accomplish all we need to here with just the script "text" and the ID. EntityItemID entityID = entity->getEntityItemID(); QString entityScript = entity->getScript(); if (_entityScripts.contains(entityID)) { EntityScriptDetails details = _entityScripts[entityID]; // check to make sure our script text hasn't changed on us since we last loaded it if (details.scriptText == entityScript) { return details.scriptObject; // previously loaded } // if we got here, then we previously loaded a script, but the entity's script value // has changed and so we need to reload it. _entityScripts.remove(entityID); } if (entityScript.isEmpty()) { return QScriptValue(); // no script } bool isURL = false; // loadScriptContents() will tell us if this is a URL or just text. bool isPending = false; QUrl url; QString scriptContents = loadScriptContents(entityScript, isURL, isPending, url); if (isPending && isPreload && isURL) { _waitingOnPreload.insert(url, entityID); } auto scriptCache = DependencyManager::get<ScriptCache>(); if (isURL && scriptCache->isInBadScriptList(url)) { return QScriptValue(); // no script contents... } if (scriptContents.isEmpty()) { return QScriptValue(); // no script contents... } QScriptSyntaxCheckResult syntaxCheck = QScriptEngine::checkSyntax(scriptContents); if (syntaxCheck.state() != QScriptSyntaxCheckResult::Valid) { qCDebug(entitiesrenderer) << "EntityTreeRenderer::loadEntityScript() entity:" << entityID; qCDebug(entitiesrenderer) << " " << syntaxCheck.errorMessage() << ":" << syntaxCheck.errorLineNumber() << syntaxCheck.errorColumnNumber(); qCDebug(entitiesrenderer) << " SCRIPT:" << entityScript; scriptCache->addScriptToBadScriptList(url); return QScriptValue(); // invalid script } if (isURL) { _entitiesScriptEngine->setParentURL(entity->getScript()); } QScriptValue entityScriptConstructor = _sandboxScriptEngine->evaluate(scriptContents); if (!entityScriptConstructor.isFunction()) { qCDebug(entitiesrenderer) << "EntityTreeRenderer::loadEntityScript() entity:" << entityID; qCDebug(entitiesrenderer) << " NOT CONSTRUCTOR"; qCDebug(entitiesrenderer) << " SCRIPT:" << entityScript; scriptCache->addScriptToBadScriptList(url); return QScriptValue(); // invalid script } else { entityScriptConstructor = _entitiesScriptEngine->evaluate(scriptContents); } QScriptValue entityScriptObject = entityScriptConstructor.construct(); EntityScriptDetails newDetails = { entityScript, entityScriptObject }; _entityScripts[entityID] = newDetails; if (isURL) { _entitiesScriptEngine->setParentURL(""); } return entityScriptObject; // newly constructed } QScriptValue EntityTreeRenderer::getPreviouslyLoadedEntityScript(const EntityItemID& entityID) { if (_entityScripts.contains(entityID)) { EntityScriptDetails details = _entityScripts[entityID]; return details.scriptObject; // previously loaded } return QScriptValue(); // no script } void EntityTreeRenderer::setTree(Octree* newTree) { OctreeRenderer::setTree(newTree); static_cast<EntityTree*>(_tree)->setFBXService(this); } void EntityTreeRenderer::update() { if (_tree && !_shuttingDown) { EntityTree* tree = static_cast<EntityTree*>(_tree); tree->update(); // check to see if the avatar has moved and if we need to handle enter/leave entity logic checkEnterLeaveEntities(); // Even if we're not moving the mouse, if we started clicking on an entity and we have // not yet released the hold then this is still considered a holdingClickOnEntity event // and we want to simulate this message here as well as in mouse move if (_lastMouseEventValid && !_currentClickingOnEntityID.isInvalidID()) { emit holdingClickOnEntity(_currentClickingOnEntityID, _lastMouseEvent); QScriptValueList currentClickingEntityArgs = createMouseEventArgs(_currentClickingOnEntityID, _lastMouseEvent); QScriptValue currentClickingEntity = loadEntityScript(_currentClickingOnEntityID); if (currentClickingEntity.property("holdingClickOnEntity").isValid()) { currentClickingEntity.property("holdingClickOnEntity").call(currentClickingEntity, currentClickingEntityArgs); } } } } void EntityTreeRenderer::checkEnterLeaveEntities() { if (_tree && !_shuttingDown) { glm::vec3 avatarPosition = _viewState->getAvatarPosition(); if (avatarPosition != _lastAvatarPosition) { float radius = 1.0f; // for now, assume 1 meter radius QVector<EntityItemPointer> foundEntities; QVector<EntityItemID> entitiesContainingAvatar; // find the entities near us _tree->lockForRead(); // don't let someone else change our tree while we search static_cast<EntityTree*>(_tree)->findEntities(avatarPosition, radius, foundEntities); // create a list of entities that actually contain the avatar's position foreach(EntityItemPointer entity, foundEntities) { if (entity->contains(avatarPosition)) { entitiesContainingAvatar << entity->getEntityItemID(); } } _tree->unlock(); // Note: at this point we don't need to worry about the tree being locked, because we only deal with // EntityItemIDs from here. The loadEntityScript() method is robust against attempting to load scripts // for entity IDs that no longer exist. // for all of our previous containing entities, if they are no longer containing then send them a leave event foreach(const EntityItemID& entityID, _currentEntitiesInside) { if (!entitiesContainingAvatar.contains(entityID)) { emit leaveEntity(entityID); QScriptValueList entityArgs = createEntityArgs(entityID); QScriptValue entityScript = loadEntityScript(entityID); if (entityScript.property("leaveEntity").isValid()) { entityScript.property("leaveEntity").call(entityScript, entityArgs); } } } // for all of our new containing entities, if they weren't previously containing then send them an enter event foreach(const EntityItemID& entityID, entitiesContainingAvatar) { if (!_currentEntitiesInside.contains(entityID)) { emit enterEntity(entityID); QScriptValueList entityArgs = createEntityArgs(entityID); QScriptValue entityScript = loadEntityScript(entityID); if (entityScript.property("enterEntity").isValid()) { entityScript.property("enterEntity").call(entityScript, entityArgs); } } } _currentEntitiesInside = entitiesContainingAvatar; _lastAvatarPosition = avatarPosition; } } } void EntityTreeRenderer::leaveAllEntities() { if (_tree && !_shuttingDown) { // for all of our previous containing entities, if they are no longer containing then send them a leave event foreach(const EntityItemID& entityID, _currentEntitiesInside) { emit leaveEntity(entityID); QScriptValueList entityArgs = createEntityArgs(entityID); QScriptValue entityScript = loadEntityScript(entityID); if (entityScript.property("leaveEntity").isValid()) { entityScript.property("leaveEntity").call(entityScript, entityArgs); } } _currentEntitiesInside.clear(); // make sure our "last avatar position" is something other than our current position, so that on our // first chance, we'll check for enter/leave entity events. _lastAvatarPosition = _viewState->getAvatarPosition() + glm::vec3((float)TREE_SCALE); } } void EntityTreeRenderer::applyZonePropertiesToScene(std::shared_ptr<ZoneEntityItem> zone) { QSharedPointer<SceneScriptingInterface> scene = DependencyManager::get<SceneScriptingInterface>(); if (zone) { if (!_hasPreviousZone) { _previousKeyLightColor = scene->getKeyLightColor(); _previousKeyLightIntensity = scene->getKeyLightIntensity(); _previousKeyLightAmbientIntensity = scene->getKeyLightAmbientIntensity(); _previousKeyLightDirection = scene->getKeyLightDirection(); _previousStageSunModelEnabled = scene->isStageSunModelEnabled(); _previousStageLongitude = scene->getStageLocationLongitude(); _previousStageLatitude = scene->getStageLocationLatitude(); _previousStageAltitude = scene->getStageLocationAltitude(); _previousStageHour = scene->getStageDayTime(); _previousStageDay = scene->getStageYearTime(); _hasPreviousZone = true; } scene->setKeyLightColor(zone->getKeyLightColorVec3()); scene->setKeyLightIntensity(zone->getKeyLightIntensity()); scene->setKeyLightAmbientIntensity(zone->getKeyLightAmbientIntensity()); scene->setKeyLightDirection(zone->getKeyLightDirection()); scene->setStageSunModelEnable(zone->getStageProperties().getSunModelEnabled()); scene->setStageLocation(zone->getStageProperties().getLongitude(), zone->getStageProperties().getLatitude(), zone->getStageProperties().getAltitude()); scene->setStageDayTime(zone->getStageProperties().calculateHour()); scene->setStageYearTime(zone->getStageProperties().calculateDay()); if (zone->getBackgroundMode() == BACKGROUND_MODE_ATMOSPHERE) { EnvironmentData data = zone->getEnvironmentData(); glm::vec3 keyLightDirection = scene->getKeyLightDirection(); glm::vec3 inverseKeyLightDirection = keyLightDirection * -1.0f; // NOTE: is this right? It seems like the "sun" should be based on the center of the // atmosphere, not where the camera is. glm::vec3 keyLightLocation = _viewState->getAvatarPosition() + (inverseKeyLightDirection * data.getAtmosphereOuterRadius()); data.setSunLocation(keyLightLocation); const float KEY_LIGHT_INTENSITY_TO_SUN_BRIGHTNESS_RATIO = 20.0f; float sunBrightness = scene->getKeyLightIntensity() * KEY_LIGHT_INTENSITY_TO_SUN_BRIGHTNESS_RATIO; data.setSunBrightness(sunBrightness); _viewState->overrideEnvironmentData(data); scene->getSkyStage()->setBackgroundMode(model::SunSkyStage::SKY_DOME); } else { _viewState->endOverrideEnvironmentData(); auto stage = scene->getSkyStage(); if (zone->getBackgroundMode() == BACKGROUND_MODE_SKYBOX) { stage->getSkybox()->setColor(zone->getSkyboxProperties().getColorVec3()); if (zone->getSkyboxProperties().getURL().isEmpty()) { stage->getSkybox()->setCubemap(gpu::TexturePointer()); } else { // Update the Texture of the Skybox with the one pointed by this zone auto cubeMap = DependencyManager::get<TextureCache>()->getTexture(zone->getSkyboxProperties().getURL(), CUBE_TEXTURE); stage->getSkybox()->setCubemap(cubeMap->getGPUTexture()); } stage->setBackgroundMode(model::SunSkyStage::SKY_BOX); } else { stage->setBackgroundMode(model::SunSkyStage::SKY_DOME); // let the application atmosphere through } } } else { if (_hasPreviousZone) { scene->setKeyLightColor(_previousKeyLightColor); scene->setKeyLightIntensity(_previousKeyLightIntensity); scene->setKeyLightAmbientIntensity(_previousKeyLightAmbientIntensity); scene->setKeyLightDirection(_previousKeyLightDirection); scene->setStageSunModelEnable(_previousStageSunModelEnabled); scene->setStageLocation(_previousStageLongitude, _previousStageLatitude, _previousStageAltitude); scene->setStageDayTime(_previousStageHour); scene->setStageYearTime(_previousStageDay); _hasPreviousZone = false; } _viewState->endOverrideEnvironmentData(); scene->getSkyStage()->setBackgroundMode(model::SunSkyStage::SKY_DOME); // let the application atmosphere through } } void EntityTreeRenderer::render(RenderArgs* renderArgs) { if (_tree && !_shuttingDown) { renderArgs->_renderer = this; _tree->lockForRead(); // Whenever you're in an intersection between zones, we will always choose the smallest zone. _bestZone = NULL; // NOTE: Is this what we want? _bestZoneVolume = std::numeric_limits<float>::max(); // FIX ME: right now the renderOperation does the following: // 1) determining the best zone (not really rendering) // 2) render the debug cell details // we should clean this up