diff --git a/assignment-client/src/AssignmentAction.cpp b/assignment-client/src/AssignmentAction.cpp index 388f4123f6..8d296cd6ab 100644 --- a/assignment-client/src/AssignmentAction.cpp +++ b/assignment-client/src/AssignmentAction.cpp @@ -23,7 +23,7 @@ AssignmentAction::AssignmentAction(EntityActionType type, const QUuid& id, Entit AssignmentAction::~AssignmentAction() { } -void AssignmentAction::removeFromSimulation(EntitySimulation* simulation) const { +void AssignmentAction::removeFromSimulation(EntitySimulationPointer simulation) const { withReadLock([&]{ simulation->removeAction(_id); simulation->applyActionChanges(); diff --git a/assignment-client/src/AssignmentAction.h b/assignment-client/src/AssignmentAction.h index 6b901c9766..6b55b280bb 100644 --- a/assignment-client/src/AssignmentAction.h +++ b/assignment-client/src/AssignmentAction.h @@ -24,7 +24,7 @@ public: AssignmentAction(EntityActionType type, const QUuid& id, EntityItemPointer ownerEntity); virtual ~AssignmentAction(); - virtual void removeFromSimulation(EntitySimulation* simulation) const; + virtual void removeFromSimulation(EntitySimulationPointer simulation) const; virtual EntityItemWeakPointer getOwnerEntity() const { return _ownerEntity; } virtual void setOwnerEntity(const EntityItemPointer ownerEntity) { _ownerEntity = ownerEntity; } virtual bool updateArguments(QVariantMap arguments); diff --git a/assignment-client/src/entities/EntityServer.cpp b/assignment-client/src/entities/EntityServer.cpp index 867412f6c0..0555f95c65 100644 --- a/assignment-client/src/entities/EntityServer.cpp +++ b/assignment-client/src/entities/EntityServer.cpp @@ -56,7 +56,7 @@ OctreePointer EntityServer::createTree() { tree->createRootElement(); tree->addNewlyCreatedHook(this); if (!_entitySimulation) { - SimpleEntitySimulation* simpleSimulation = new SimpleEntitySimulation(); + SimpleEntitySimulationPointer simpleSimulation { new SimpleEntitySimulation() }; simpleSimulation->setEntityTree(tree); tree->setSimulation(simpleSimulation); _entitySimulation = simpleSimulation; diff --git a/assignment-client/src/entities/EntityServer.h b/assignment-client/src/entities/EntityServer.h index ec58cda6cd..1685f08e01 100644 --- a/assignment-client/src/entities/EntityServer.h +++ b/assignment-client/src/entities/EntityServer.h @@ -28,6 +28,8 @@ struct ViewerSendingStats { }; class SimpleEntitySimulation; +using SimpleEntitySimulationPointer = std::shared_ptr; + class EntityServer : public OctreeServer, public NewlyCreatedEntityHook { Q_OBJECT @@ -69,7 +71,7 @@ private slots: void handleEntityPacket(QSharedPointer message, SharedNodePointer senderNode); private: - SimpleEntitySimulation* _entitySimulation; + SimpleEntitySimulationPointer _entitySimulation; QTimer* _pruneDeletedEntitiesTimer = nullptr; QReadWriteLock _viewerSendingStatsLock; diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index 800cadf72f..84aa0328b0 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -44,7 +44,7 @@ else () endif () find_package(Qt5 COMPONENTS - Gui Multimedia Network OpenGL Qml Quick Script Svg + Gui Multimedia Network OpenGL Qml Quick Script ScriptTools Svg WebChannel WebEngine WebEngineWidgets WebKitWidgets WebSockets) # grab the ui files in resources/ui @@ -201,7 +201,7 @@ include_directories("${PROJECT_SOURCE_DIR}/src") target_link_libraries( ${TARGET_NAME} Qt5::Gui Qt5::Network Qt5::Multimedia Qt5::OpenGL - Qt5::Qml Qt5::Quick Qt5::Script Qt5::Svg + Qt5::Qml Qt5::Quick Qt5::Script Qt5::ScriptTools Qt5::Svg Qt5::WebChannel Qt5::WebEngine Qt5::WebEngineWidgets Qt5::WebKitWidgets ) diff --git a/interface/resources/avatar/animations/fly.fbx b/interface/resources/avatar/animations/fly.fbx index a05a1e9a37..4a855032f9 100644 Binary files a/interface/resources/avatar/animations/fly.fbx and b/interface/resources/avatar/animations/fly.fbx differ diff --git a/interface/resources/avatar/animations/idle.fbx b/interface/resources/avatar/animations/idle.fbx index 6e4b3f4155..67e2be8735 100644 Binary files a/interface/resources/avatar/animations/idle.fbx and b/interface/resources/avatar/animations/idle.fbx differ diff --git a/interface/resources/avatar/animations/idle_to_walk.fbx b/interface/resources/avatar/animations/idle_to_walk.fbx index 9c2b03a4d6..858f35596f 100644 Binary files a/interface/resources/avatar/animations/idle_to_walk.fbx and b/interface/resources/avatar/animations/idle_to_walk.fbx differ diff --git a/interface/resources/avatar/animations/talk.fbx b/interface/resources/avatar/animations/talk.fbx index 4c27deadd8..3fd470befd 100644 Binary files a/interface/resources/avatar/animations/talk.fbx and b/interface/resources/avatar/animations/talk.fbx differ diff --git a/interface/resources/avatar/animations/turn_left.fbx b/interface/resources/avatar/animations/turn_left.fbx index 8856d159b9..de6d68b6c0 100644 Binary files a/interface/resources/avatar/animations/turn_left.fbx and b/interface/resources/avatar/animations/turn_left.fbx differ diff --git a/interface/resources/avatar/animations/turn_right.fbx b/interface/resources/avatar/animations/turn_right.fbx deleted file mode 100644 index 8af7213d22..0000000000 Binary files a/interface/resources/avatar/animations/turn_right.fbx and /dev/null differ diff --git a/interface/resources/avatar/avatar-animation.json b/interface/resources/avatar/avatar-animation.json index 9bdbbec3da..834a3fc277 100644 --- a/interface/resources/avatar/avatar-animation.json +++ b/interface/resources/avatar/avatar-animation.json @@ -274,7 +274,7 @@ }, { "id": "walkFwd", - "interpTarget": 15, + "interpTarget": 16, "interpDuration": 6, "transitions": [ { "var": "isNotMoving", "state": "idle" }, @@ -497,7 +497,7 @@ "data": { "url": "animations/idle.fbx", "startFrame": 0.0, - "endFrame": 90.0, + "endFrame": 300.0, "timeScale": 1.0, "loopFlag": true }, @@ -509,7 +509,7 @@ "data": { "url": "animations/talk.fbx", "startFrame": 0.0, - "endFrame": 801.0, + "endFrame": 800.0, "timeScale": 1.0, "loopFlag": true }, @@ -572,7 +572,7 @@ "data": { "url": "animations/idle_to_walk.fbx", "startFrame": 1.0, - "endFrame": 19.0, + "endFrame": 13.0, "timeScale": 1.0, "loopFlag": false }, @@ -631,11 +631,12 @@ "id": "turnRight", "type": "clip", "data": { - "url": "animations/turn_right.fbx", + "url": "animations/turn_left.fbx", "startFrame": 0.0, "endFrame": 30.0, "timeScale": 1.0, - "loopFlag": true + "loopFlag": true, + "mirrorFlag": true }, "children": [] }, diff --git a/interface/resources/controllers/vive.json b/interface/resources/controllers/vive.json index 1f71658946..37f5b45b1e 100644 --- a/interface/resources/controllers/vive.json +++ b/interface/resources/controllers/vive.json @@ -1,15 +1,15 @@ { "name": "Vive to Standard", "channels": [ - { "from": "Vive.LY", "when": "Vive.LS", "filters": "invert", "to": "Standard.LY" }, - { "from": "Vive.LX", "when": "Vive.LS", "to": "Standard.LX" }, + { "from": "Vive.LY", "when": "Vive.LS", "filters": ["invert" ,{ "type": "deadZone", "min": 0.6 }], "to": "Standard.LY" }, + { "from": "Vive.LX", "when": "Vive.LS", "filters": [{ "type": "deadZone", "min": 0.6 }], "to": "Standard.LX" }, { "from": "Vive.LT", "to": "Standard.LT" }, { "from": "Vive.LB", "to": "Standard.LB" }, { "from": "Vive.LS", "to": "Standard.LS" }, - { "from": "Vive.RY", "when": "Vive.RS", "filters": "invert", "to": "Standard.RY" }, - { "from": "Vive.RX", "when": "Vive.RS", "to": "Standard.RX" }, + { "from": "Vive.RY", "when": "Vive.RS", "filters": ["invert", { "type": "deadZone", "min": 0.6 }], "to": "Standard.RY" }, + { "from": "Vive.RX", "when": "Vive.RS", "filters": [{ "type": "deadZone", "min": 0.6 }], "to": "Standard.RX" }, { "from": "Vive.RT", "to": "Standard.RT" }, { "from": "Vive.RB", "to": "Standard.RB" }, diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 3977e85bc2..aa98724a7d 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -485,6 +485,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer) : _sessionRunTimer(startupTimer), _previousSessionCrashed(setupEssentials(argc, argv)), _undoStackScriptingInterface(&_undoStack), + _entitySimulation(new PhysicalEntitySimulation()), _physicsEngine(new PhysicsEngine(Vectors::ZERO)), _entityClipboardRenderer(false, this, this), _entityClipboard(new EntityTree()), @@ -560,12 +561,6 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer) : // put the NodeList and datagram processing on the node thread nodeList->moveToThread(nodeThread); - // Model background downloads need to happen on the Datagram Processor Thread. The idle loop will - // emit checkBackgroundDownloads to cause the ModelCache to check it's queue for requested background - // downloads. - auto modelCache = DependencyManager::get(); - connect(this, &Application::checkBackgroundDownloads, modelCache.data(), &ModelCache::checkAsynchronousGets); - // put the audio processing on a separate thread QThread* audioThread = new QThread(); audioThread->setObjectName("Audio Thread"); @@ -2734,9 +2729,6 @@ void Application::idle(uint64_t now) { } _overlayConductor.update(secondsSinceLastUpdate); - - // check for any requested background downloads. - emit checkBackgroundDownloads(); } void Application::setLowVelocityFilter(bool lowVelocityFilter) { @@ -2986,13 +2978,13 @@ void Application::init() { _physicsEngine->init(); EntityTreePointer tree = getEntities()->getTree(); - _entitySimulation.init(tree, _physicsEngine, &_entityEditSender); - tree->setSimulation(&_entitySimulation); + _entitySimulation->init(tree, _physicsEngine, &_entityEditSender); + tree->setSimulation(_entitySimulation); auto entityScriptingInterface = DependencyManager::get(); // connect the _entityCollisionSystem to our EntityTreeRenderer since that's what handles running entity scripts - connect(&_entitySimulation, &EntitySimulation::entityCollisionWithEntity, + connect(_entitySimulation.get(), &EntitySimulation::entityCollisionWithEntity, getEntities(), &EntityTreeRenderer::entityCollisionWithEntity); // connect the _entities (EntityTreeRenderer) to our script engine's EntityScriptingInterface for firing @@ -3412,22 +3404,22 @@ void Application::update(float deltaTime) { PerformanceTimer perfTimer("updateStates)"); static VectorOfMotionStates motionStates; - _entitySimulation.getObjectsToRemoveFromPhysics(motionStates); + _entitySimulation->getObjectsToRemoveFromPhysics(motionStates); _physicsEngine->removeObjects(motionStates); - _entitySimulation.deleteObjectsRemovedFromPhysics(); + _entitySimulation->deleteObjectsRemovedFromPhysics(); getEntities()->getTree()->withReadLock([&] { - _entitySimulation.getObjectsToAddToPhysics(motionStates); + _entitySimulation->getObjectsToAddToPhysics(motionStates); _physicsEngine->addObjects(motionStates); }); getEntities()->getTree()->withReadLock([&] { - _entitySimulation.getObjectsToChange(motionStates); + _entitySimulation->getObjectsToChange(motionStates); VectorOfMotionStates stillNeedChange = _physicsEngine->changeObjects(motionStates); - _entitySimulation.setObjectsToChange(stillNeedChange); + _entitySimulation->setObjectsToChange(stillNeedChange); }); - _entitySimulation.applyActionChanges(); + _entitySimulation->applyActionChanges(); avatarManager->getObjectsToRemoveFromPhysics(motionStates); _physicsEngine->removeObjects(motionStates); @@ -3455,7 +3447,7 @@ void Application::update(float deltaTime) { getEntities()->getTree()->withWriteLock([&] { PerformanceTimer perfTimer("handleOutgoingChanges"); const VectorOfMotionStates& outgoingChanges = _physicsEngine->getOutgoingChanges(); - _entitySimulation.handleOutgoingChanges(outgoingChanges); + _entitySimulation->handleOutgoingChanges(outgoingChanges); avatarManager->handleOutgoingChanges(outgoingChanges); }); @@ -3468,7 +3460,7 @@ void Application::update(float deltaTime) { PerformanceTimer perfTimer("entities"); // Collision events (and their scripts) must not be handled when we're locked, above. (That would risk // deadlock.) - _entitySimulation.handleCollisionEvents(collisionEvents); + _entitySimulation->handleCollisionEvents(collisionEvents); // NOTE: the getEntities()->update() call below will wait for lock // and will simulate entity motion (the EntityTree has been given an EntitySimulation). diff --git a/interface/src/Application.h b/interface/src/Application.h index 9af04d19d0..f52dfc8c07 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -222,8 +222,6 @@ public: signals: void svoImportRequested(const QString& url); - void checkBackgroundDownloads(); - void fullAvatarURLChanged(const QString& newValue, const QString& modelName); void beforeAboutToQuit(); @@ -405,7 +403,7 @@ private: QElapsedTimer _lastTimeUpdated; ShapeManager _shapeManager; - PhysicalEntitySimulation _entitySimulation; + PhysicalEntitySimulationPointer _entitySimulation; PhysicsEnginePointer _physicsEngine; EntityTreeRenderer _entityClipboardRenderer; diff --git a/interface/src/scripting/MenuScriptingInterface.cpp b/interface/src/scripting/MenuScriptingInterface.cpp index da55a8829f..7eb80b5946 100644 --- a/interface/src/scripting/MenuScriptingInterface.cpp +++ b/interface/src/scripting/MenuScriptingInterface.cpp @@ -11,8 +11,11 @@ #include "MenuScriptingInterface.h" -#include "Menu.h" +#include +#include + #include +#include "Menu.h" MenuScriptingInterface* MenuScriptingInterface::getInstance() { static MenuScriptingInterface sharedInstance; @@ -36,6 +39,9 @@ void MenuScriptingInterface::removeMenu(const QString& menu) { } bool MenuScriptingInterface::menuExists(const QString& menu) { + if (QThread::currentThread() == qApp->thread()) { + return Menu::getInstance()->menuExists(menu); + } bool result; QMetaObject::invokeMethod(Menu::getInstance(), "menuExists", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, result), @@ -76,11 +82,14 @@ void MenuScriptingInterface::removeMenuItem(const QString& menu, const QString& }; bool MenuScriptingInterface::menuItemExists(const QString& menu, const QString& menuitem) { + if (QThread::currentThread() == qApp->thread()) { + return Menu::getInstance()->menuItemExists(menu, menuitem); + } bool result; QMetaObject::invokeMethod(Menu::getInstance(), "menuItemExists", Qt::BlockingQueuedConnection, - Q_RETURN_ARG(bool, result), - Q_ARG(const QString&, menu), - Q_ARG(const QString&, menuitem)); + Q_RETURN_ARG(bool, result), + Q_ARG(const QString&, menu), + Q_ARG(const QString&, menuitem)); return result; } @@ -101,6 +110,9 @@ void MenuScriptingInterface::removeActionGroup(const QString& groupName) { } bool MenuScriptingInterface::isOptionChecked(const QString& menuOption) { + if (QThread::currentThread() == qApp->thread()) { + return Menu::getInstance()->isOptionChecked(menuOption); + } bool result; QMetaObject::invokeMethod(Menu::getInstance(), "isOptionChecked", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, result), @@ -109,7 +121,7 @@ bool MenuScriptingInterface::isOptionChecked(const QString& menuOption) { } void MenuScriptingInterface::setIsOptionChecked(const QString& menuOption, bool isChecked) { - QMetaObject::invokeMethod(Menu::getInstance(), "setIsOptionChecked", Qt::BlockingQueuedConnection, + QMetaObject::invokeMethod(Menu::getInstance(), "setIsOptionChecked", Q_ARG(const QString&, menuOption), Q_ARG(bool, isChecked)); } diff --git a/libraries/animation/src/AnimationCache.cpp b/libraries/animation/src/AnimationCache.cpp index 9364045857..482c4211cb 100644 --- a/libraries/animation/src/AnimationCache.cpp +++ b/libraries/animation/src/AnimationCache.cpp @@ -36,7 +36,7 @@ AnimationPointer AnimationCache::getAnimation(const QUrl& url) { } QSharedPointer AnimationCache::createResource(const QUrl& url, const QSharedPointer& fallback, - bool delayLoad, const void* extra) { + const void* extra) { return QSharedPointer(new Animation(url), &Resource::deleter); } diff --git a/libraries/animation/src/AnimationCache.h b/libraries/animation/src/AnimationCache.h index 59a4ad0498..9da649e66e 100644 --- a/libraries/animation/src/AnimationCache.h +++ b/libraries/animation/src/AnimationCache.h @@ -35,8 +35,8 @@ public: protected: - virtual QSharedPointer createResource(const QUrl& url, - const QSharedPointer& fallback, bool delayLoad, const void* extra); + virtual QSharedPointer createResource(const QUrl& url, const QSharedPointer& fallback, + const void* extra); private: explicit AnimationCache(QObject* parent = NULL); virtual ~AnimationCache() { } diff --git a/libraries/audio/src/SoundCache.cpp b/libraries/audio/src/SoundCache.cpp index 2752c6669f..96a2cee204 100644 --- a/libraries/audio/src/SoundCache.cpp +++ b/libraries/audio/src/SoundCache.cpp @@ -35,7 +35,7 @@ SharedSoundPointer SoundCache::getSound(const QUrl& url) { } QSharedPointer SoundCache::createResource(const QUrl& url, const QSharedPointer& fallback, - bool delayLoad, const void* extra) { + const void* extra) { qCDebug(audio) << "Requesting sound at" << url.toString(); return QSharedPointer(new Sound(url), &Resource::deleter); } diff --git a/libraries/audio/src/SoundCache.h b/libraries/audio/src/SoundCache.h index 7942e16010..59a25dd847 100644 --- a/libraries/audio/src/SoundCache.h +++ b/libraries/audio/src/SoundCache.h @@ -25,8 +25,8 @@ public: Q_INVOKABLE SharedSoundPointer getSound(const QUrl& url); protected: - virtual QSharedPointer createResource(const QUrl& url, - const QSharedPointer& fallback, bool delayLoad, const void* extra); + virtual QSharedPointer createResource(const QUrl& url, const QSharedPointer& fallback, + const void* extra); private: SoundCache(QObject* parent = NULL); }; diff --git a/libraries/controllers/src/controllers/impl/filters/DeadZoneFilter.cpp b/libraries/controllers/src/controllers/impl/filters/DeadZoneFilter.cpp index 809308eeab..f07ef25976 100644 --- a/libraries/controllers/src/controllers/impl/filters/DeadZoneFilter.cpp +++ b/libraries/controllers/src/controllers/impl/filters/DeadZoneFilter.cpp @@ -13,11 +13,12 @@ using namespace controller; float DeadZoneFilter::apply(float value) const { - float scale = 1.0f / (1.0f - _min); - if (std::abs(value) < _min) { + float scale = ((value < 0.0f) ? -1.0f : 1.0f) / (1.0f - _min); + float magnitude = std::abs(value); + if (magnitude < _min) { return 0.0f; } - return (value - _min) * scale; + return (magnitude - _min) * scale; } bool DeadZoneFilter::parseParameters(const QJsonValue& parameters) { diff --git a/libraries/display-plugins/src/display-plugins/CompositorHelper.cpp b/libraries/display-plugins/src/display-plugins/CompositorHelper.cpp index 4648fc8957..f9d527de8f 100644 --- a/libraries/display-plugins/src/display-plugins/CompositorHelper.cpp +++ b/libraries/display-plugins/src/display-plugins/CompositorHelper.cpp @@ -16,6 +16,8 @@ #include #include #include +#include +#include #include #include @@ -256,7 +258,7 @@ glm::vec2 CompositorHelper::getReticlePosition() const { QMutexLocker locker(&_reticleLock); return _reticlePositionInHMD; } - return toGlm(QCursor::pos()); + return toGlm(_renderingWidget->mapFromGlobal(QCursor::pos())); } bool CompositorHelper::getReticleOverDesktop() const { @@ -322,17 +324,8 @@ void CompositorHelper::setReticlePosition(const glm::vec2& position, bool sendFa sendFakeMouseEvent(); } } else { - // NOTE: This is some debugging code we will leave in while debugging various reticle movement strategies, - // remove it after we're done - const float REASONABLE_CHANGE = 50.0f; - glm::vec2 oldPos = toGlm(QCursor::pos()); - auto distance = glm::distance(oldPos, position); - if (distance > REASONABLE_CHANGE) { - qDebug() << "Contrller::ScriptingInterface ---- UNREASONABLE CHANGE! distance:" << - distance << " oldPos:" << oldPos.x << "," << oldPos.y << " newPos:" << position.x << "," << position.y; - } - - QCursor::setPos(position.x, position.y); + const QPoint point(position.x, position.y); + QCursor::setPos(_renderingWidget->mapToGlobal(point)); } } diff --git a/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp b/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp index 6c4e3994c6..1d5570b8b7 100644 --- a/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp @@ -977,8 +977,8 @@ void RenderablePolyVoxEntityItem::compressVolumeDataAndSendEditPacket() { properties.setVoxelDataDirty(); properties.setLastEdited(now); - EntitySimulation* simulation = tree ? tree->getSimulation() : nullptr; - PhysicalEntitySimulation* peSimulation = static_cast(simulation); + EntitySimulationPointer simulation = tree ? tree->getSimulation() : nullptr; + PhysicalEntitySimulationPointer peSimulation = std::static_pointer_cast(simulation); EntityEditPacketSender* packetSender = peSimulation ? peSimulation->getPacketSender() : nullptr; if (packetSender) { packetSender->queueEditEntityMessage(PacketType::EntityEdit, entity->getID(), properties); diff --git a/libraries/entities/src/EntityActionInterface.h b/libraries/entities/src/EntityActionInterface.h index 34de87cca4..9a881cf94c 100644 --- a/libraries/entities/src/EntityActionInterface.h +++ b/libraries/entities/src/EntityActionInterface.h @@ -20,6 +20,8 @@ class EntityItem; class EntitySimulation; using EntityItemPointer = std::shared_ptr; using EntityItemWeakPointer = std::weak_ptr; +class EntitySimulation; +using EntitySimulationPointer = std::shared_ptr; enum EntityActionType { // keep these synchronized with actionTypeFromString and actionTypeToString @@ -39,7 +41,7 @@ public: bool isActive() { return _active; } - virtual void removeFromSimulation(EntitySimulation* simulation) const = 0; + virtual void removeFromSimulation(EntitySimulationPointer simulation) const = 0; virtual EntityItemWeakPointer getOwnerEntity() const = 0; virtual void setOwnerEntity(const EntityItemPointer ownerEntity) = 0; virtual bool updateArguments(QVariantMap arguments) = 0; diff --git a/libraries/entities/src/EntityItem.cpp b/libraries/entities/src/EntityItem.cpp index 5ef068c551..187c4f51be 100644 --- a/libraries/entities/src/EntityItem.cpp +++ b/libraries/entities/src/EntityItem.cpp @@ -89,7 +89,7 @@ EntityItem::EntityItem(const EntityItemID& entityItemID) : EntityItem::~EntityItem() { // clear out any left-over actions EntityTreePointer entityTree = _element ? _element->getTree() : nullptr; - EntitySimulation* simulation = entityTree ? entityTree->getSimulation() : nullptr; + EntitySimulationPointer simulation = entityTree ? entityTree->getSimulation() : nullptr; if (simulation) { clearActions(simulation); } @@ -1736,7 +1736,7 @@ QString EntityItem::actionsToDebugString() { return result; } -bool EntityItem::addAction(EntitySimulation* simulation, EntityActionPointer action) { +bool EntityItem::addAction(EntitySimulationPointer simulation, EntityActionPointer action) { bool result; withWriteLock([&] { checkWaitingToRemove(simulation); @@ -1753,7 +1753,7 @@ bool EntityItem::addAction(EntitySimulation* simulation, EntityActionPointer act return result; } -bool EntityItem::addActionInternal(EntitySimulation* simulation, EntityActionPointer action) { +bool EntityItem::addActionInternal(EntitySimulationPointer simulation, EntityActionPointer action) { assert(action); assert(simulation); auto actionOwnerEntity = action->getOwnerEntity().lock(); @@ -1777,7 +1777,7 @@ bool EntityItem::addActionInternal(EntitySimulation* simulation, EntityActionPoi return success; } -bool EntityItem::updateAction(EntitySimulation* simulation, const QUuid& actionID, const QVariantMap& arguments) { +bool EntityItem::updateAction(EntitySimulationPointer simulation, const QUuid& actionID, const QVariantMap& arguments) { bool success = false; withWriteLock([&] { checkWaitingToRemove(simulation); @@ -1800,7 +1800,7 @@ bool EntityItem::updateAction(EntitySimulation* simulation, const QUuid& actionI return success; } -bool EntityItem::removeAction(EntitySimulation* simulation, const QUuid& actionID) { +bool EntityItem::removeAction(EntitySimulationPointer simulation, const QUuid& actionID) { bool success = false; withWriteLock([&] { checkWaitingToRemove(simulation); @@ -1809,7 +1809,7 @@ bool EntityItem::removeAction(EntitySimulation* simulation, const QUuid& actionI return success; } -bool EntityItem::removeActionInternal(const QUuid& actionID, EntitySimulation* simulation) { +bool EntityItem::removeActionInternal(const QUuid& actionID, EntitySimulationPointer simulation) { _previouslyDeletedActions.insert(actionID, usecTimestampNow()); if (_objectActions.contains(actionID)) { if (!simulation) { @@ -1836,7 +1836,7 @@ bool EntityItem::removeActionInternal(const QUuid& actionID, EntitySimulation* s return false; } -bool EntityItem::clearActions(EntitySimulation* simulation) { +bool EntityItem::clearActions(EntitySimulationPointer simulation) { withWriteLock([&] { QHash::iterator i = _objectActions.begin(); while (i != _objectActions.end()) { @@ -1872,7 +1872,7 @@ void EntityItem::deserializeActionsInternal() { EntityTreePointer entityTree = getTree(); assert(entityTree); - EntitySimulation* simulation = entityTree ? entityTree->getSimulation() : nullptr; + EntitySimulationPointer simulation = entityTree ? entityTree->getSimulation() : nullptr; assert(simulation); QVector serializedActions; @@ -1952,7 +1952,7 @@ void EntityItem::deserializeActionsInternal() { return; } -void EntityItem::checkWaitingToRemove(EntitySimulation* simulation) { +void EntityItem::checkWaitingToRemove(EntitySimulationPointer simulation) { foreach(QUuid actionID, _actionsToRemove) { removeActionInternal(actionID, simulation); } diff --git a/libraries/entities/src/EntityItem.h b/libraries/entities/src/EntityItem.h index a602e09c4d..8868830c8a 100644 --- a/libraries/entities/src/EntityItem.h +++ b/libraries/entities/src/EntityItem.h @@ -383,10 +383,10 @@ public: void flagForMotionStateChange() { _dirtyFlags |= Simulation::DIRTY_MOTION_TYPE; } QString actionsToDebugString(); - bool addAction(EntitySimulation* simulation, EntityActionPointer action); - bool updateAction(EntitySimulation* simulation, const QUuid& actionID, const QVariantMap& arguments); - bool removeAction(EntitySimulation* simulation, const QUuid& actionID); - bool clearActions(EntitySimulation* simulation); + bool addAction(EntitySimulationPointer simulation, EntityActionPointer action); + bool updateAction(EntitySimulationPointer simulation, const QUuid& actionID, const QVariantMap& arguments); + bool removeAction(EntitySimulationPointer simulation, const QUuid& actionID); + bool clearActions(EntitySimulationPointer simulation); void setActionData(QByteArray actionData); const QByteArray getActionData() const; bool hasActions() const { return !_objectActions.empty(); } @@ -522,8 +522,8 @@ protected: void* _physicsInfo = nullptr; // set by EntitySimulation bool _simulated; // set by EntitySimulation - bool addActionInternal(EntitySimulation* simulation, EntityActionPointer action); - bool removeActionInternal(const QUuid& actionID, EntitySimulation* simulation = nullptr); + bool addActionInternal(EntitySimulationPointer simulation, EntityActionPointer action); + bool removeActionInternal(const QUuid& actionID, EntitySimulationPointer simulation = nullptr); void deserializeActionsInternal(); void serializeActions(bool& success, QByteArray& result) const; QHash _objectActions; @@ -534,7 +534,7 @@ protected: // when an entity-server starts up, EntityItem::setActionData is called before the entity-tree is // ready. This means we can't find our EntityItemPointer or add the action to the simulation. These // are used to keep track of and work around this situation. - void checkWaitingToRemove(EntitySimulation* simulation = nullptr); + void checkWaitingToRemove(EntitySimulationPointer simulation = nullptr); mutable QSet _actionsToRemove; mutable bool _actionDataDirty = false; mutable bool _actionDataNeedsTransmit = false; diff --git a/libraries/entities/src/EntityScriptingInterface.cpp b/libraries/entities/src/EntityScriptingInterface.cpp index 093fa73ace..01f444491d 100644 --- a/libraries/entities/src/EntityScriptingInterface.cpp +++ b/libraries/entities/src/EntityScriptingInterface.cpp @@ -766,7 +766,7 @@ bool EntityScriptingInterface::appendPoint(QUuid entityID, const glm::vec3& poin bool EntityScriptingInterface::actionWorker(const QUuid& entityID, - std::function actor) { + std::function actor) { if (!_entityTree) { return false; } @@ -774,7 +774,7 @@ bool EntityScriptingInterface::actionWorker(const QUuid& entityID, EntityItemPointer entity; bool doTransmit = false; _entityTree->withWriteLock([&] { - EntitySimulation* simulation = _entityTree->getSimulation(); + EntitySimulationPointer simulation = _entityTree->getSimulation(); entity = _entityTree->findEntityByEntityItemID(entityID); if (!entity) { qDebug() << "actionWorker -- unknown entity" << entityID; @@ -815,7 +815,7 @@ QUuid EntityScriptingInterface::addAction(const QString& actionTypeString, QUuid actionID = QUuid::createUuid(); auto actionFactory = DependencyManager::get(); bool success = false; - actionWorker(entityID, [&](EntitySimulation* simulation, EntityItemPointer entity) { + actionWorker(entityID, [&](EntitySimulationPointer simulation, EntityItemPointer entity) { // create this action even if the entity doesn't have physics info. it will often be the // case that a script adds an action immediately after an object is created, and the physicsInfo // is computed asynchronously. @@ -843,7 +843,7 @@ QUuid EntityScriptingInterface::addAction(const QString& actionTypeString, bool EntityScriptingInterface::updateAction(const QUuid& entityID, const QUuid& actionID, const QVariantMap& arguments) { - return actionWorker(entityID, [&](EntitySimulation* simulation, EntityItemPointer entity) { + return actionWorker(entityID, [&](EntitySimulationPointer simulation, EntityItemPointer entity) { bool success = entity->updateAction(simulation, actionID, arguments); if (success) { entity->grabSimulationOwnership(); @@ -854,7 +854,7 @@ bool EntityScriptingInterface::updateAction(const QUuid& entityID, const QUuid& bool EntityScriptingInterface::deleteAction(const QUuid& entityID, const QUuid& actionID) { bool success = false; - actionWorker(entityID, [&](EntitySimulation* simulation, EntityItemPointer entity) { + actionWorker(entityID, [&](EntitySimulationPointer simulation, EntityItemPointer entity) { success = entity->removeAction(simulation, actionID); if (success) { // reduce from grab to poke @@ -867,7 +867,7 @@ bool EntityScriptingInterface::deleteAction(const QUuid& entityID, const QUuid& QVector EntityScriptingInterface::getActionIDs(const QUuid& entityID) { QVector result; - actionWorker(entityID, [&](EntitySimulation* simulation, EntityItemPointer entity) { + actionWorker(entityID, [&](EntitySimulationPointer simulation, EntityItemPointer entity) { QList actionIDs = entity->getActionIDs(); result = QVector::fromList(actionIDs); return false; // don't send an edit packet @@ -877,7 +877,7 @@ QVector EntityScriptingInterface::getActionIDs(const QUuid& entityID) { QVariantMap EntityScriptingInterface::getActionArguments(const QUuid& entityID, const QUuid& actionID) { QVariantMap result; - actionWorker(entityID, [&](EntitySimulation* simulation, EntityItemPointer entity) { + actionWorker(entityID, [&](EntitySimulationPointer simulation, EntityItemPointer entity) { result = entity->getActionArguments(actionID); return false; // don't send an edit packet }); diff --git a/libraries/entities/src/EntityScriptingInterface.h b/libraries/entities/src/EntityScriptingInterface.h index e5f913dbf8..5f80b7abb2 100644 --- a/libraries/entities/src/EntityScriptingInterface.h +++ b/libraries/entities/src/EntityScriptingInterface.h @@ -200,11 +200,11 @@ signals: void debitEnergySource(float value); private: - bool actionWorker(const QUuid& entityID, std::function actor); + bool actionWorker(const QUuid& entityID, std::function actor); bool setVoxels(QUuid entityID, std::function actor); bool setPoints(QUuid entityID, std::function actor); void queueEntityMessage(PacketType packetType, EntityItemID entityID, const EntityItemProperties& properties); - + EntityItemPointer checkForTreeEntityAndTypeMatch(const QUuid& entityID, EntityTypes::EntityType entityType = EntityTypes::Unknown); diff --git a/libraries/entities/src/EntitySimulation.cpp b/libraries/entities/src/EntitySimulation.cpp index 524f52e815..893ae83cc5 100644 --- a/libraries/entities/src/EntitySimulation.cpp +++ b/libraries/entities/src/EntitySimulation.cpp @@ -64,7 +64,7 @@ void EntitySimulation::prepareEntityForDelete(EntityItemPointer entity) { assert(entity->isDead()); if (entity->isSimulated()) { QMutexLocker lock(&_mutex); - entity->clearActions(this); + entity->clearActions(getThisPointer()); removeEntityInternal(entity); _entitiesToDelete.insert(entity); } diff --git a/libraries/entities/src/EntitySimulation.h b/libraries/entities/src/EntitySimulation.h index cbedbbd868..f8f506ac70 100644 --- a/libraries/entities/src/EntitySimulation.h +++ b/libraries/entities/src/EntitySimulation.h @@ -22,8 +22,9 @@ #include "EntityItem.h" #include "EntityTree.h" -typedef QSet SetOfEntities; -typedef QVector VectorOfEntities; +using EntitySimulationPointer = std::shared_ptr; +using SetOfEntities = QSet; +using VectorOfEntities = QVector; // the EntitySimulation needs to know when these things change on an entity, // so it can sort EntityItem or relay its state to the PhysicsEngine. @@ -41,12 +42,16 @@ const int DIRTY_SIMULATION_FLAGS = Simulation::DIRTY_MATERIAL | Simulation::DIRTY_SIMULATOR_ID; -class EntitySimulation : public QObject { +class EntitySimulation : public QObject, public std::enable_shared_from_this { Q_OBJECT public: EntitySimulation() : _mutex(QMutex::Recursive), _entityTree(NULL), _nextExpiry(quint64(-1)) { } virtual ~EntitySimulation() { setEntityTree(NULL); } + inline EntitySimulationPointer getThisPointer() const { + return std::const_pointer_cast(shared_from_this()); + } + /// \param tree pointer to EntityTree which is stored internally void setEntityTree(EntityTreePointer tree); diff --git a/libraries/entities/src/EntityTree.cpp b/libraries/entities/src/EntityTree.cpp index 8a24b77036..30c37d46b1 100644 --- a/libraries/entities/src/EntityTree.cpp +++ b/libraries/entities/src/EntityTree.cpp @@ -365,7 +365,7 @@ void EntityTree::notifyNewCollisionSoundURL(const QString& newURL, const EntityI emit newCollisionSoundURL(QUrl(newURL), entityID); } -void EntityTree::setSimulation(EntitySimulation* simulation) { +void EntityTree::setSimulation(EntitySimulationPointer simulation) { this->withWriteLock([&] { if (simulation) { // assert that the simulation's backpointer has already been properly connected diff --git a/libraries/entities/src/EntityTree.h b/libraries/entities/src/EntityTree.h index 83bc31aa92..03b8a9b55a 100644 --- a/libraries/entities/src/EntityTree.h +++ b/libraries/entities/src/EntityTree.h @@ -194,8 +194,8 @@ public: void emitEntityScriptChanging(const EntityItemID& entityItemID, const bool reload); - void setSimulation(EntitySimulation* simulation); - EntitySimulation* getSimulation() const { return _simulation; } + void setSimulation(EntitySimulationPointer simulation); + EntitySimulationPointer getSimulation() const { return _simulation; } bool wantEditLogging() const { return _wantEditLogging; } void setWantEditLogging(bool value) { _wantEditLogging = value; } @@ -299,7 +299,7 @@ protected: mutable QReadWriteLock _entityToElementLock; QHash _entityToElementMap; - EntitySimulation* _simulation; + EntitySimulationPointer _simulation; bool _wantEditLogging = false; bool _wantTerseEditLogging = false; diff --git a/libraries/entities/src/EntityTreeHeadlessViewer.cpp b/libraries/entities/src/EntityTreeHeadlessViewer.cpp index 149f92adad..81c42cda1e 100644 --- a/libraries/entities/src/EntityTreeHeadlessViewer.cpp +++ b/libraries/entities/src/EntityTreeHeadlessViewer.cpp @@ -22,7 +22,7 @@ EntityTreeHeadlessViewer::~EntityTreeHeadlessViewer() { void EntityTreeHeadlessViewer::init() { OctreeHeadlessViewer::init(); if (!_simulation) { - SimpleEntitySimulation* simpleSimulation = new SimpleEntitySimulation(); + SimpleEntitySimulationPointer simpleSimulation { new SimpleEntitySimulation() }; EntityTreePointer entityTree = std::static_pointer_cast(_tree); simpleSimulation->setEntityTree(entityTree); entityTree->setSimulation(simpleSimulation); diff --git a/libraries/entities/src/EntityTreeHeadlessViewer.h b/libraries/entities/src/EntityTreeHeadlessViewer.h index 40e428b655..0e0d4f9726 100644 --- a/libraries/entities/src/EntityTreeHeadlessViewer.h +++ b/libraries/entities/src/EntityTreeHeadlessViewer.h @@ -49,7 +49,7 @@ protected: return newTree; } - EntitySimulation* _simulation; + EntitySimulationPointer _simulation; }; #endif // hifi_EntityTreeHeadlessViewer_h diff --git a/libraries/entities/src/SimpleEntitySimulation.h b/libraries/entities/src/SimpleEntitySimulation.h index 12ded8a30d..9c7c9a374e 100644 --- a/libraries/entities/src/SimpleEntitySimulation.h +++ b/libraries/entities/src/SimpleEntitySimulation.h @@ -14,6 +14,10 @@ #include "EntitySimulation.h" +class SimpleEntitySimulation; +using SimpleEntitySimulationPointer = std::shared_ptr; + + /// provides simple velocity + gravity extrapolation of EntityItem's class SimpleEntitySimulation : public EntitySimulation { diff --git a/libraries/model-networking/src/model-networking/ModelCache.cpp b/libraries/model-networking/src/model-networking/ModelCache.cpp index 24834967d6..8cd6d9b65e 100644 --- a/libraries/model-networking/src/model-networking/ModelCache.cpp +++ b/libraries/model-networking/src/model-networking/ModelCache.cpp @@ -71,7 +71,7 @@ void GeometryMappingResource::downloadFinished(const QByteArray& data) { GeometryExtra extra{ mapping, _textureBaseUrl }; // Get the raw GeometryResource, not the wrapped NetworkGeometry - _geometryResource = modelCache->getResource(url, QUrl(), false, &extra).staticCast(); + _geometryResource = modelCache->getResource(url, QUrl(), &extra).staticCast(); // Avoid caching nested resources - their references will be held by the parent _geometryResource->_isCacheable = false; @@ -236,7 +236,7 @@ ModelCache::ModelCache() { } QSharedPointer ModelCache::createResource(const QUrl& url, const QSharedPointer& fallback, - bool delayLoad, const void* extra) { + const void* extra) { Resource* resource = nullptr; if (url.path().toLower().endsWith(".fst")) { resource = new GeometryMappingResource(url); @@ -252,7 +252,7 @@ QSharedPointer ModelCache::createResource(const QUrl& url, const QShar std::shared_ptr ModelCache::getGeometry(const QUrl& url, const QVariantHash& mapping, const QUrl& textureBaseUrl) { GeometryExtra geometryExtra = { mapping, textureBaseUrl }; - GeometryResource::Pointer resource = getResource(url, QUrl(), true, &geometryExtra).staticCast(); + GeometryResource::Pointer resource = getResource(url, QUrl(), &geometryExtra).staticCast(); if (resource) { if (resource->isLoaded() && resource->shouldSetTextures()) { resource->setTextures(); diff --git a/libraries/model-networking/src/model-networking/ModelCache.h b/libraries/model-networking/src/model-networking/ModelCache.h index bf47f293e8..f15e1106e2 100644 --- a/libraries/model-networking/src/model-networking/ModelCache.h +++ b/libraries/model-networking/src/model-networking/ModelCache.h @@ -44,8 +44,8 @@ public: protected: friend class GeometryMappingResource; - virtual QSharedPointer createResource(const QUrl& url, - const QSharedPointer& fallback, bool delayLoad, const void* extra); + virtual QSharedPointer createResource(const QUrl& url, const QSharedPointer& fallback, + const void* extra); private: ModelCache(); diff --git a/libraries/model-networking/src/model-networking/ShaderCache.cpp b/libraries/model-networking/src/model-networking/ShaderCache.cpp index 3e14a99f87..bf7ade07f7 100644 --- a/libraries/model-networking/src/model-networking/ShaderCache.cpp +++ b/libraries/model-networking/src/model-networking/ShaderCache.cpp @@ -7,11 +7,8 @@ // #include "ShaderCache.h" -NetworkShader::NetworkShader(const QUrl& url, bool delayLoad) - : Resource(url, delayLoad) -{ - -} +NetworkShader::NetworkShader(const QUrl& url) : + Resource(url) {} void NetworkShader::downloadFinished(const QByteArray& data) { _source = QString::fromUtf8(data); @@ -24,10 +21,11 @@ ShaderCache& ShaderCache::instance() { } NetworkShaderPointer ShaderCache::getShader(const QUrl& url) { - return ResourceCache::getResource(url, QUrl(), false, nullptr).staticCast(); + return ResourceCache::getResource(url, QUrl(), nullptr).staticCast(); } -QSharedPointer ShaderCache::createResource(const QUrl& url, const QSharedPointer& fallback, bool delayLoad, const void* extra) { - return QSharedPointer(new NetworkShader(url, delayLoad), &Resource::deleter); +QSharedPointer ShaderCache::createResource(const QUrl& url, const QSharedPointer& fallback, + const void* extra) { + return QSharedPointer(new NetworkShader(url), &Resource::deleter); } diff --git a/libraries/model-networking/src/model-networking/ShaderCache.h b/libraries/model-networking/src/model-networking/ShaderCache.h index ffe8d437ce..4af12fdbfa 100644 --- a/libraries/model-networking/src/model-networking/ShaderCache.h +++ b/libraries/model-networking/src/model-networking/ShaderCache.h @@ -13,7 +13,7 @@ class NetworkShader : public Resource { public: - NetworkShader(const QUrl& url, bool delayLoad); + NetworkShader(const QUrl& url); virtual void downloadFinished(const QByteArray& data) override; QString _source; @@ -28,7 +28,8 @@ public: NetworkShaderPointer getShader(const QUrl& url); protected: - virtual QSharedPointer createResource(const QUrl& url, const QSharedPointer& fallback, bool delayLoad, const void* extra) override; + virtual QSharedPointer createResource(const QUrl& url, const QSharedPointer& fallback, + const void* extra) override; }; #endif diff --git a/libraries/model-networking/src/model-networking/TextureCache.cpp b/libraries/model-networking/src/model-networking/TextureCache.cpp index 2aaddace88..000ca67989 100644 --- a/libraries/model-networking/src/model-networking/TextureCache.cpp +++ b/libraries/model-networking/src/model-networking/TextureCache.cpp @@ -167,7 +167,7 @@ ScriptableResource* TextureCache::prefetch(const QUrl& url, int type) { NetworkTexturePointer TextureCache::getTexture(const QUrl& url, Type type, const QByteArray& content) { TextureExtra extra = { type, content }; - return ResourceCache::getResource(url, QUrl(), content.isEmpty(), &extra).staticCast(); + return ResourceCache::getResource(url, QUrl(), &extra).staticCast(); } @@ -231,8 +231,8 @@ gpu::TexturePointer TextureCache::getImageTexture(const QString& path, Type type return gpu::TexturePointer(loader(image, QUrl::fromLocalFile(path).fileName().toStdString())); } -QSharedPointer TextureCache::createResource(const QUrl& url, - const QSharedPointer& fallback, bool delayLoad, const void* extra) { +QSharedPointer TextureCache::createResource(const QUrl& url, const QSharedPointer& fallback, + const void* extra) { const TextureExtra* textureExtra = static_cast(extra); auto type = textureExtra ? textureExtra->type : Type::DEFAULT_TEXTURE; auto content = textureExtra ? textureExtra->content : QByteArray(); @@ -241,7 +241,7 @@ QSharedPointer TextureCache::createResource(const QUrl& url, } NetworkTexture::NetworkTexture(const QUrl& url, Type type, const QByteArray& content) : - Resource(url, !content.isEmpty()), + Resource(url), _type(type) { _textureSource = std::make_shared(); diff --git a/libraries/model-networking/src/model-networking/TextureCache.h b/libraries/model-networking/src/model-networking/TextureCache.h index 8fd0b12369..f3c6a86b49 100644 --- a/libraries/model-networking/src/model-networking/TextureCache.h +++ b/libraries/model-networking/src/model-networking/TextureCache.h @@ -131,8 +131,8 @@ protected: // Overload ResourceCache::prefetch to allow specifying texture type for loads Q_INVOKABLE ScriptableResource* prefetch(const QUrl& url, int type); - virtual QSharedPointer createResource(const QUrl& url, - const QSharedPointer& fallback, bool delayLoad, const void* extra); + virtual QSharedPointer createResource(const QUrl& url, const QSharedPointer& fallback, + const void* extra); private: TextureCache(); diff --git a/libraries/networking/src/ResourceCache.cpp b/libraries/networking/src/ResourceCache.cpp index d6a2fa7dba..36828b3992 100644 --- a/libraries/networking/src/ResourceCache.cpp +++ b/libraries/networking/src/ResourceCache.cpp @@ -179,7 +179,7 @@ ScriptableResource* ResourceCache::prefetch(const QUrl& url, void* extra) { result = new ScriptableResource(url); - auto resource = getResource(url, QUrl(), false, extra); + auto resource = getResource(url, QUrl(), extra); result->_resource = resource; result->setObjectName(url.toString()); @@ -316,25 +316,7 @@ void ResourceCache::setRequestLimit(int limit) { } } -void ResourceCache::getResourceAsynchronously(const QUrl& url) { - qCDebug(networking) << "ResourceCache::getResourceAsynchronously" << url.toString(); - QWriteLocker locker(&_resourcesToBeGottenLock); - _resourcesToBeGotten.enqueue(QUrl(url)); -} - -void ResourceCache::checkAsynchronousGets() { - assert(QThread::currentThread() == thread()); - QWriteLocker locker(&_resourcesToBeGottenLock); - if (!_resourcesToBeGotten.isEmpty()) { - QUrl url = _resourcesToBeGotten.dequeue(); - - locker.unlock(); - getResource(url); - } -} - -QSharedPointer ResourceCache::getResource(const QUrl& url, const QUrl& fallback, - bool delayLoad, void* extra) { +QSharedPointer ResourceCache::getResource(const QUrl& url, const QUrl& fallback, void* extra) { QSharedPointer resource; { QReadLocker locker(&_resourcesLock); @@ -346,17 +328,21 @@ QSharedPointer ResourceCache::getResource(const QUrl& url, const QUrl& } if (QThread::currentThread() != thread()) { - assert(delayLoad); - getResourceAsynchronously(url); + qCDebug(networking) << "Fetching asynchronously:" << url; + QMetaObject::invokeMethod(this, "getResource", + Q_ARG(QUrl, url), Q_ARG(QUrl, fallback)); + // Cannot use extra parameter as it might be freed before the invocation return QSharedPointer(); } if (!url.isValid() && !url.isEmpty() && fallback.isValid()) { - return getResource(fallback, QUrl(), delayLoad); + return getResource(fallback, QUrl()); } - resource = createResource(url, fallback.isValid() ? - getResource(fallback, QUrl(), true) : QSharedPointer(), delayLoad, extra); + resource = createResource( + url, + fallback.isValid() ? getResource(fallback, QUrl()) : QSharedPointer(), + extra); resource->setSelf(resource); resource->setCache(this); connect(resource.data(), &Resource::updateSize, this, &ResourceCache::updateTotalSize); @@ -508,7 +494,7 @@ const int DEFAULT_REQUEST_LIMIT = 10; int ResourceCache::_requestLimit = DEFAULT_REQUEST_LIMIT; int ResourceCache::_requestsActive = 0; -Resource::Resource(const QUrl& url, bool delayLoad) : +Resource::Resource(const QUrl& url) : _url(url), _activeUrl(url), _request(nullptr) { diff --git a/libraries/networking/src/ResourceCache.h b/libraries/networking/src/ResourceCache.h index 64e3f4dc34..11b80ca349 100644 --- a/libraries/networking/src/ResourceCache.h +++ b/libraries/networking/src/ResourceCache.h @@ -179,9 +179,6 @@ public: signals: void dirty(); -public slots: - void checkAsynchronousGets(); - protected slots: void updateTotalSize(const qint64& deltaSize); @@ -190,6 +187,14 @@ protected slots: // and delegate to it (see TextureCache::prefetch(const QUrl&, int). ScriptableResource* prefetch(const QUrl& url, void* extra); + /// Loads a resource from the specified URL and returns it. + /// If the caller is on a different thread than the ResourceCache, + /// returns an empty smart pointer and loads its asynchronously. + /// \param fallback a fallback URL to load if the desired one is unavailable + /// \param extra extra data to pass to the creator, if appropriate + QSharedPointer getResource(const QUrl& url, const QUrl& fallback = QUrl(), + void* extra = NULL); + private slots: void clearATPAssets(); @@ -200,16 +205,9 @@ protected: // the QScriptEngine will delete the pointer when it is garbage collected. Q_INVOKABLE ScriptableResource* prefetch(const QUrl& url) { return prefetch(url, nullptr); } - /// Loads a resource from the specified URL. - /// \param fallback a fallback URL to load if the desired one is unavailable - /// \param delayLoad if true, don't load the resource immediately; wait until load is first requested - /// \param extra extra data to pass to the creator, if appropriate - QSharedPointer getResource(const QUrl& url, const QUrl& fallback = QUrl(), - bool delayLoad = false, void* extra = NULL); - /// Creates a new resource. - virtual QSharedPointer createResource(const QUrl& url, - const QSharedPointer& fallback, bool delayLoad, const void* extra) = 0; + virtual QSharedPointer createResource(const QUrl& url, const QSharedPointer& fallback, + const void* extra) = 0; void addUnusedResource(const QSharedPointer& resource); void removeUnusedResource(const QSharedPointer& resource); @@ -260,7 +258,7 @@ class Resource : public QObject { public: - Resource(const QUrl& url, bool delayLoad = false); + Resource(const QUrl& url); ~Resource(); /// Returns the key last used to identify this resource in the unused map. diff --git a/libraries/physics/src/ObjectAction.cpp b/libraries/physics/src/ObjectAction.cpp index 8d33c69d1c..ca64cabe5f 100644 --- a/libraries/physics/src/ObjectAction.cpp +++ b/libraries/physics/src/ObjectAction.cpp @@ -138,7 +138,7 @@ QVariantMap ObjectAction::getArguments() { void ObjectAction::debugDraw(btIDebugDraw* debugDrawer) { } -void ObjectAction::removeFromSimulation(EntitySimulation* simulation) const { +void ObjectAction::removeFromSimulation(EntitySimulationPointer simulation) const { QUuid myID; withReadLock([&]{ myID = _id; diff --git a/libraries/physics/src/ObjectAction.h b/libraries/physics/src/ObjectAction.h index efc5808f14..43330269ac 100644 --- a/libraries/physics/src/ObjectAction.h +++ b/libraries/physics/src/ObjectAction.h @@ -29,7 +29,7 @@ public: ObjectAction(EntityActionType type, const QUuid& id, EntityItemPointer ownerEntity); virtual ~ObjectAction(); - virtual void removeFromSimulation(EntitySimulation* simulation) const override; + virtual void removeFromSimulation(EntitySimulationPointer simulation) const override; virtual EntityItemWeakPointer getOwnerEntity() const override { return _ownerEntity; } virtual void setOwnerEntity(const EntityItemPointer ownerEntity) override { _ownerEntity = ownerEntity; } diff --git a/libraries/physics/src/PhysicalEntitySimulation.cpp b/libraries/physics/src/PhysicalEntitySimulation.cpp index 70ca512646..3fbf8ffaf5 100644 --- a/libraries/physics/src/PhysicalEntitySimulation.cpp +++ b/libraries/physics/src/PhysicalEntitySimulation.cpp @@ -156,7 +156,7 @@ void PhysicalEntitySimulation::clearEntitiesInternal() { void PhysicalEntitySimulation::prepareEntityForDelete(EntityItemPointer entity) { assert(entity); assert(entity->isDead()); - entity->clearActions(this); + entity->clearActions(getThisPointer()); removeEntityInternal(entity); } // end EntitySimulation overrides diff --git a/libraries/physics/src/PhysicalEntitySimulation.h b/libraries/physics/src/PhysicalEntitySimulation.h index 935ee57115..24b9ba95f0 100644 --- a/libraries/physics/src/PhysicalEntitySimulation.h +++ b/libraries/physics/src/PhysicalEntitySimulation.h @@ -23,7 +23,9 @@ #include "PhysicsEngine.h" #include "EntityMotionState.h" -typedef QSet SetOfEntityMotionStates; +class PhysicalEntitySimulation; +using PhysicalEntitySimulationPointer = std::shared_ptr; +using SetOfEntityMotionStates = QSet; class PhysicalEntitySimulation :public EntitySimulation { public: diff --git a/libraries/recording/src/recording/ClipCache.cpp b/libraries/recording/src/recording/ClipCache.cpp index 145ecfc7b9..66d5fb0d88 100644 --- a/libraries/recording/src/recording/ClipCache.cpp +++ b/libraries/recording/src/recording/ClipCache.cpp @@ -9,12 +9,9 @@ #include "impl/PointerClip.h" using namespace recording; -NetworkClipLoader::NetworkClipLoader(const QUrl& url, bool delayLoad) - : Resource(url, delayLoad), _clip(std::make_shared(url)) -{ - -} - +NetworkClipLoader::NetworkClipLoader(const QUrl& url) : + Resource(url), + _clip(std::make_shared(url)) {} void NetworkClip::init(const QByteArray& clipData) { _clipData = clipData; @@ -32,10 +29,10 @@ ClipCache& ClipCache::instance() { } NetworkClipLoaderPointer ClipCache::getClipLoader(const QUrl& url) { - return ResourceCache::getResource(url, QUrl(), false, nullptr).staticCast(); + return ResourceCache::getResource(url, QUrl(), nullptr).staticCast(); } -QSharedPointer ClipCache::createResource(const QUrl& url, const QSharedPointer& fallback, bool delayLoad, const void* extra) { - return QSharedPointer(new NetworkClipLoader(url, delayLoad), &Resource::deleter); +QSharedPointer ClipCache::createResource(const QUrl& url, const QSharedPointer& fallback, const void* extra) { + return QSharedPointer(new NetworkClipLoader(url), &Resource::deleter); } diff --git a/libraries/recording/src/recording/ClipCache.h b/libraries/recording/src/recording/ClipCache.h index c72d45648d..7df83efdbf 100644 --- a/libraries/recording/src/recording/ClipCache.h +++ b/libraries/recording/src/recording/ClipCache.h @@ -31,7 +31,7 @@ private: class NetworkClipLoader : public Resource { public: - NetworkClipLoader(const QUrl& url, bool delayLoad); + NetworkClipLoader(const QUrl& url); virtual void downloadFinished(const QByteArray& data) override; ClipPointer getClip() { return _clip; } bool completed() { return _failedToLoad || isLoaded(); } @@ -49,7 +49,7 @@ public: NetworkClipLoaderPointer getClipLoader(const QUrl& url); protected: - virtual QSharedPointer createResource(const QUrl& url, const QSharedPointer& fallback, bool delayLoad, const void* extra) override; + virtual QSharedPointer createResource(const QUrl& url, const QSharedPointer& fallback, const void* extra) override; }; } diff --git a/libraries/script-engine/CMakeLists.txt b/libraries/script-engine/CMakeLists.txt index 8ff13aba70..48fda99b9d 100644 --- a/libraries/script-engine/CMakeLists.txt +++ b/libraries/script-engine/CMakeLists.txt @@ -1,3 +1,3 @@ set(TARGET_NAME script-engine) -setup_hifi_library(Gui Network Script WebSockets Widgets) +setup_hifi_library(Gui Network Script ScriptTools WebSockets Widgets) link_hifi_libraries(shared networking octree gpu ui procedural model model-networking recording avatars fbx entities controllers animation audio physics) diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index d1eaffd2c5..f7ac7894ff 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -17,12 +17,18 @@ #include #include #include +#include + +#include +#include + #include #include -#include + #include #include -#include + +#include #include #include @@ -34,6 +40,7 @@ #include #include #include +#include #include #include @@ -169,6 +176,93 @@ void ScriptEngine::disconnectNonEssentialSignals() { } } +void ScriptEngine::runDebuggable() { + static QMenuBar* menuBar { nullptr }; + static QMenu* scriptDebugMenu { nullptr }; + static size_t scriptMenuCount { 0 }; + if (!scriptDebugMenu) { + for (auto window : qApp->topLevelWidgets()) { + auto mainWindow = qobject_cast(window); + if (mainWindow) { + menuBar = mainWindow->menuBar(); + break; + } + } + if (menuBar) { + scriptDebugMenu = menuBar->addMenu("Script Debug"); + } + } + + init(); + _isRunning = true; + _debuggable = true; + _debugger = new QScriptEngineDebugger(this); + _debugger->attachTo(this); + + QMenu* parentMenu = scriptDebugMenu; + QMenu* scriptMenu { nullptr }; + if (parentMenu) { + ++scriptMenuCount; + scriptMenu = parentMenu->addMenu(_fileNameString); + scriptMenu->addMenu(_debugger->createStandardMenu(qApp->activeWindow())); + } else { + qWarning() << "Unable to add script debug menu"; + } + + QScriptValue result = evaluate(_scriptContents, _fileNameString); + + _lastUpdate = usecTimestampNow(); + QTimer* timer = new QTimer(this); + connect(this, &ScriptEngine::finished, [this, timer, parentMenu, scriptMenu] { + if (scriptMenu) { + parentMenu->removeAction(scriptMenu->menuAction()); + --scriptMenuCount; + if (0 == scriptMenuCount) { + menuBar->removeAction(scriptDebugMenu->menuAction()); + scriptDebugMenu = nullptr; + } + } + disconnect(timer); + }); + + connect(timer, &QTimer::timeout, [this, timer] { + if (_isFinished) { + if (!_isRunning) { + return; + } + stopAllTimers(); // make sure all our timers are stopped if the script is ending + if (_wantSignals) { + emit scriptEnding(); + emit finished(_fileNameString, this); + } + _isRunning = false; + if (_wantSignals) { + emit runningStateChanged(); + emit doneRunning(); + } + timer->deleteLater(); + return; + } + + qint64 now = usecTimestampNow(); + // we check for 'now' in the past in case people set their clock back + if (_lastUpdate < now) { + float deltaTime = (float)(now - _lastUpdate) / (float)USECS_PER_SECOND; + if (!_isFinished) { + if (_wantSignals) { + emit update(deltaTime); + } + } + } + _lastUpdate = now; + // Debug and clear exceptions + hadUncaughtExceptions(*this, _fileNameString); + }); + + timer->start(10); +} + + void ScriptEngine::runInThread() { Q_ASSERT_X(!_isThreaded, "ScriptEngine::runInThread()", "runInThread should not be called more than once"); @@ -260,6 +354,10 @@ void ScriptEngine::loadURL(const QUrl& scriptURL, bool reload) { // FIXME - switch this to the new model of ScriptCache callbacks void ScriptEngine::scriptContentsAvailable(const QUrl& url, const QString& scriptContents) { _scriptContents = scriptContents; + static const QString DEBUG_FLAG("#debug"); + if (QRegularExpression(DEBUG_FLAG).match(scriptContents).hasMatch()) { + _debuggable = true; + } if (_wantSignals) { emit scriptLoaded(url.toString()); } @@ -723,7 +821,7 @@ void ScriptEngine::run() { auto nodeList = DependencyManager::get(); auto entityScriptingInterface = DependencyManager::get(); - qint64 lastUpdate = usecTimestampNow(); + _lastUpdate = usecTimestampNow(); // TODO: Integrate this with signals/slots instead of reimplementing throttling for ScriptEngine while (!_isFinished) { @@ -771,15 +869,15 @@ void ScriptEngine::run() { qint64 now = usecTimestampNow(); // we check for 'now' in the past in case people set their clock back - if (lastUpdate < now) { - float deltaTime = (float) (now - lastUpdate) / (float) USECS_PER_SECOND; + if (_lastUpdate < now) { + float deltaTime = (float) (now - _lastUpdate) / (float) USECS_PER_SECOND; if (!_isFinished) { if (_wantSignals) { emit update(deltaTime); } } } - lastUpdate = now; + _lastUpdate = now; // Debug and clear exceptions hadUncaughtExceptions(*this, _fileNameString); diff --git a/libraries/script-engine/src/ScriptEngine.h b/libraries/script-engine/src/ScriptEngine.h index f050997235..d37e3eb177 100644 --- a/libraries/script-engine/src/ScriptEngine.h +++ b/libraries/script-engine/src/ScriptEngine.h @@ -18,9 +18,10 @@ #include #include #include -#include #include +#include + #include #include #include @@ -39,6 +40,8 @@ #include "ScriptUUID.h" #include "Vec3.h" +class QScriptEngineDebugger; + static const QString NO_SCRIPT(""); static const int SCRIPT_FPS = 60; @@ -75,6 +78,8 @@ public: /// services before calling this. void runInThread(); + void runDebuggable(); + /// run the script in the callers thread, exit when stop() is called. void run(); @@ -140,6 +145,8 @@ public: bool isFinished() const { return _isFinished; } // used by Application and ScriptWidget bool isRunning() const { return _isRunning; } // used by ScriptWidget + bool isDebuggable() const { return _debuggable; } + void disconnectNonEssentialSignals(); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -187,6 +194,9 @@ protected: bool _wantSignals { true }; QHash _entityScripts; bool _isThreaded { false }; + QScriptEngineDebugger* _debugger { nullptr }; + bool _debuggable { false }; + qint64 _lastUpdate; void init(); QString getFilename() const; diff --git a/libraries/script-engine/src/ScriptEngines.cpp b/libraries/script-engine/src/ScriptEngines.cpp index c6070e0598..cf82d9db4f 100644 --- a/libraries/script-engine/src/ScriptEngines.cpp +++ b/libraries/script-engine/src/ScriptEngines.cpp @@ -9,7 +9,8 @@ #include "ScriptEngines.h" #include -#include + +#include #include #include @@ -490,7 +491,12 @@ void ScriptEngines::launchScriptEngine(ScriptEngine* scriptEngine) { for (auto initializer : _scriptInitializers) { initializer(scriptEngine); } - scriptEngine->runInThread(); + + if (scriptEngine->isDebuggable() || (qApp->queryKeyboardModifiers() & Qt::ShiftModifier)) { + scriptEngine->runDebuggable(); + } else { + scriptEngine->runInThread(); + } } diff --git a/scripts/defaultScripts.js b/scripts/defaultScripts.js index 9b11fa73cc..2a050d183e 100644 --- a/scripts/defaultScripts.js +++ b/scripts/defaultScripts.js @@ -17,7 +17,7 @@ Script.load("system/edit.js"); Script.load("system/selectAudioDevice.js"); Script.load("system/notifications.js"); Script.load("system/controllers/handControllerGrab.js"); +Script.load("system/controllers/handControllerPointer.js"); Script.load("system/controllers/squeezeHands.js"); Script.load("system/controllers/grab.js"); Script.load("system/dialTone.js"); -Script.load("system/depthReticle.js"); \ No newline at end of file diff --git a/scripts/system/controllers/handControllerPointer.js b/scripts/system/controllers/handControllerPointer.js new file mode 100644 index 0000000000..6e9fe17077 --- /dev/null +++ b/scripts/system/controllers/handControllerPointer.js @@ -0,0 +1,456 @@ +"use strict"; +/*jslint vars: true, plusplus: true*/ +/*globals Script, Overlays, Controller, Reticle, HMD, Camera, Entities, MyAvatar, Settings, Menu, ScriptDiscoveryService, Window, Vec3, Quat, print */ + +// +// handControllerPointer.js +// examples/controllers +// +// Created by Howard Stearns on 2016/04/22 +// Copyright 2016 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +// Control the "mouse" using hand controller. (HMD and desktop.) +// For now: +// Hydra thumb button 3 is left-mouse, button 4 is right-mouse. +// A click in the center of the vive thumb pad is left mouse. Vive menu button is context menu (right mouse). +// First-person only. +// Starts right handed, but switches to whichever is free: Whichever hand was NOT most recently squeezed. +// (For now, the thumb buttons on both controllers are always on.) +// When over a HUD element, the reticle is shown where the active hand controller beam intersects the HUD. +// Otherwise, the active hand controller shows a red ball where a click will act. +// +// Bugs: +// On Windows, the upper left corner of Interface must be in the upper left corner of the screen, and the title bar must be 50px high. (System bug.) +// While hardware mouse move switches to mouse move, hardware mouse click (without amove) does not. + + +// UTILITIES ------------- +// + +// Utility to make it easier to setup and disconnect cleanly. +function setupHandler(event, handler) { + event.connect(handler); + Script.scriptEnding.connect(function () { + event.disconnect(handler); + }); +} +// If some capability is not available until expiration milliseconds after the last update. +function TimeLock(expiration) { + var last = 0; + this.update = function (optionalNow) { + last = optionalNow || Date.now(); + }; + this.expired = function (optionalNow) { + return ((optionalNow || Date.now()) - last) > expiration; + }; +} +var handControllerLockOut = new TimeLock(2000); + +// Calls onFunction() or offFunction() when swtich(on), but only if it is to a new value. +function LatchedToggle(onFunction, offFunction, state) { + this.getState = function () { + return state; + }; + this.setState = function (on) { + if (state === on) { + return; + } + state = on; + if (on) { + onFunction(); + } else { + offFunction(); + } + }; +} + +// VERTICAL FIELD OF VIEW --------- +// +// Cache the verticalFieldOfView setting and update it every so often. +var verticalFieldOfView, DEFAULT_VERTICAL_FIELD_OF_VIEW = 45; // degrees +function updateFieldOfView() { + verticalFieldOfView = Settings.getValue('fieldOfView') || DEFAULT_VERTICAL_FIELD_OF_VIEW; +} + +// SHIMS ---------- +// +var weMovedReticle = false; +function ignoreMouseActivity() { + // If we're paused, or if change in cursor position is from this script, not the hardware mouse. + if (!Reticle.allowMouseCapture) { + return true; + } + // Only we know if we moved it, which is why this script has to replace depthReticle.js + if (!weMovedReticle) { + return false; + } + weMovedReticle = false; + return true; +} +var setReticlePosition = function (point2d) { + weMovedReticle = true; + Reticle.setPosition(point2d); +}; + +// Generalizations of utilities that work with system and overlay elements. +function findRayIntersection(pickRay) { + // Check 3D overlays and entities. Argument is an object with origin and direction. + var result = Overlays.findRayIntersection(pickRay); + if (!result.intersects) { + result = Entities.findRayIntersection(pickRay, true); + } + return result; +} +function isPointingAtOverlay(optionalHudPosition2d) { + return Reticle.pointingAtSystemOverlay || Overlays.getOverlayAtPoint(optionalHudPosition2d || Reticle.position); +} + +// Generalized HUD utilities, with or without HMD: +// These two "vars" are for documentation. Do not change their values! +var SPHERICAL_HUD_DISTANCE = 1; // meters. +var PLANAR_PERPENDICULAR_HUD_DISTANCE = SPHERICAL_HUD_DISTANCE; +function calculateRayUICollisionPoint(position, direction) { + // Answer the 3D intersection of the HUD by the given ray, or falsey if no intersection. + if (HMD.active) { + return HMD.calculateRayUICollisionPoint(position, direction); + } + // interect HUD plane, 1m in front of camera, using formula: + // scale = hudNormal dot (hudPoint - position) / hudNormal dot direction + // intersection = postion + scale*direction + var hudNormal = Quat.getFront(Camera.getOrientation()); + var hudPoint = Vec3.sum(Camera.getPosition(), hudNormal); // must also scale if PLANAR_PERPENDICULAR_HUD_DISTANCE!=1 + var denominator = Vec3.dot(hudNormal, direction); + if (denominator === 0) { + return null; + } // parallel to plane + var numerator = Vec3.dot(hudNormal, Vec3.subtract(hudPoint, position)); + var scale = numerator / denominator; + return Vec3.sum(position, Vec3.multiply(scale, direction)); +} +var DEGREES_TO_HALF_RADIANS = Math.PI / 360; +function overlayFromWorldPoint(point) { + // Answer the 2d pixel-space location in the HUD that covers the given 3D point. + // REQUIRES: that the 3d point be on the hud surface! + // Note that this is based on the Camera, and doesn't know anything about any + // ray that may or may not have been used to compute the point. E.g., the + // overlay point is NOT the intersection of some non-camera ray with the HUD. + if (HMD.active) { + return HMD.overlayFromWorldPoint(point); + } + var cameraToPoint = Vec3.subtract(point, Camera.getPosition()); + var cameraX = Vec3.dot(cameraToPoint, Quat.getRight(Camera.getOrientation())); + var cameraY = Vec3.dot(cameraToPoint, Quat.getUp(Camera.getOrientation())); + var size = Controller.getViewportDimensions(); + var hudHeight = 2 * Math.tan(verticalFieldOfView * DEGREES_TO_HALF_RADIANS); // must adjust if PLANAR_PERPENDICULAR_HUD_DISTANCE!=1 + var hudWidth = hudHeight * size.x / size.y; + var horizontalFraction = (cameraX / hudWidth + 0.5); + var verticalFraction = 1 - (cameraY / hudHeight + 0.5); + var horizontalPixels = size.x * horizontalFraction; + var verticalPixels = size.y * verticalFraction; + return { x: horizontalPixels, y: verticalPixels }; +} + +// MOUSE ACTIVITY -------- +// +var isSeeking = false; +var averageMouseVelocity = 0, lastIntegration = 0, lastMouse; +var WEIGHTING = 1 / 20; // simple moving average over last 20 samples +var ONE_MINUS_WEIGHTING = 1 - WEIGHTING; +var AVERAGE_MOUSE_VELOCITY_FOR_SEEK_TO = 20; +function isShakingMouse() { // True if the person is waving the mouse around trying to find it. + var now = Date.now(), mouse = Reticle.position, isShaking = false; + if (lastIntegration && (lastIntegration !== now)) { + var velocity = Vec3.length(Vec3.subtract(mouse, lastMouse)) / (now - lastIntegration); + averageMouseVelocity = (ONE_MINUS_WEIGHTING * averageMouseVelocity) + (WEIGHTING * velocity); + if (averageMouseVelocity > AVERAGE_MOUSE_VELOCITY_FOR_SEEK_TO) { + isShaking = true; + } + } + lastIntegration = now; + lastMouse = mouse; + return isShaking; +} +var NON_LINEAR_DIVISOR = 2; +var MINIMUM_SEEK_DISTANCE = 0.01; +function updateSeeking() { + if (!Reticle.visible || isShakingMouse()) { + isSeeking = true; + } // e.g., if we're about to turn it on with first movement. + if (!isSeeking) { + return; + } + averageMouseVelocity = lastIntegration = 0; + var lookAt2D = HMD.getHUDLookAtPosition2D(); + if (!lookAt2D) { + print('Cannot seek without lookAt position'); + return; + } // E.g., if parallel to location in HUD + var copy = Reticle.position; + function updateDimension(axis) { + var distanceBetween = lookAt2D[axis] - Reticle.position[axis]; + var move = distanceBetween / NON_LINEAR_DIVISOR; + if (Math.abs(move) < MINIMUM_SEEK_DISTANCE) { + return false; + } + copy[axis] += move; + return true; + } + var okX = !updateDimension('x'), okY = !updateDimension('y'); // Evaluate both. Don't short-circuit. + if (okX && okY) { + isSeeking = false; + } else { + Reticle.setPosition(copy); // Not setReticlePosition + } +} + +var mouseCursorActivity = new TimeLock(5000); +var APPARENT_MAXIMUM_DEPTH = 100.0; // this is a depth at which things all seem sufficiently distant +function updateMouseActivity(isClick) { + if (ignoreMouseActivity()) { + return; + } + var now = Date.now(); + mouseCursorActivity.update(now); + if (isClick) { + return; + } // Bug: mouse clicks should keep going. Just not hand controller clicks + handControllerLockOut.update(now); + Reticle.visible = true; +} +function expireMouseCursor(now) { + if (!isPointingAtOverlay() && mouseCursorActivity.expired(now)) { + Reticle.visible = false; + } +} +function onMouseMove() { + // Display cursor at correct depth (as in depthReticle.js), and updateMouseActivity. + if (ignoreMouseActivity()) { + return; + } + + if (HMD.active) { // set depth + updateSeeking(); + if (isPointingAtOverlay()) { + Reticle.setDepth(SPHERICAL_HUD_DISTANCE); // NOT CORRECT IF WE SWITCH TO OFFSET SPHERE! + } else { + var result = findRayIntersection(Camera.computePickRay(Reticle.position.x, Reticle.position.y)); + var depth = result.intersects ? result.distance : APPARENT_MAXIMUM_DEPTH; + Reticle.setDepth(depth); + } + } + updateMouseActivity(); // After the above, just in case the depth movement is awkward when becoming visible. +} +function onMouseClick() { + updateMouseActivity(true); +} +setupHandler(Controller.mouseMoveEvent, onMouseMove); +setupHandler(Controller.mousePressEvent, onMouseClick); +setupHandler(Controller.mouseDoublePressEvent, onMouseClick); + +// CONTROLLER MAPPING --------- +// + +var activeHand = Controller.Standard.RightHand; +function toggleHand() { + if (activeHand === Controller.Standard.RightHand) { + activeHand = Controller.Standard.LeftHand; + } else { + activeHand = Controller.Standard.RightHand; + } +} + +// Create clickMappings as needed, on demand. +var clickMappings = {}, clickMapping, clickMapToggle; +var hardware; // undefined +function checkHardware() { + var newHardware = Controller.Hardware.Hydra ? 'Hydra' : (Controller.Hardware.Vive ? 'Vive' : null); // not undefined + if (hardware === newHardware) { + return; + } + print('Setting mapping for new controller hardware:', newHardware); + if (clickMapToggle) { + clickMapToggle.setState(false); + } + hardware = newHardware; + if (clickMappings[hardware]) { + clickMapping = clickMappings[hardware]; + } else { + clickMapping = Controller.newMapping(Script.resolvePath('') + '-click-' + hardware); + Script.scriptEnding.connect(clickMapping.disable); + function mapToAction(button, action) { + clickMapping.from(Controller.Hardware[hardware][button]).peek().to(Controller.Actions[action]); + } + function makeHandToggle(button, hand, optionalWhen) { + var whenThunk = optionalWhen || function () { + return true; + }; + function maybeToggle() { + if (activeHand !== Controller.Standard[hand]) { + toggleHand(); + } + + } + clickMapping.from(Controller.Hardware[hardware][button]).peek().when(whenThunk).to(maybeToggle); + } + function makeViveWhen(click, x, y) { + var viveClick = Controller.Hardware.Vive[click], + viveX = Controller.Standard[x], // Standard after filtering by mapping + viveY = Controller.Standard[y]; + return function () { + var clickValue = Controller.getValue(viveClick); + var xValue = Controller.getValue(viveX); + var yValue = Controller.getValue(viveY); + return clickValue && !xValue && !yValue; + }; + } + switch (hardware) { + case 'Hydra': + makeHandToggle('R3', 'RightHand'); + makeHandToggle('L3', 'LeftHand'); + + mapToAction('R3', 'ReticleClick'); + mapToAction('L3', 'ReticleClick'); + mapToAction('R4', 'ContextMenu'); + mapToAction('L4', 'ContextMenu'); + break; + case 'Vive': + // When touchpad click is NOT treated as movement, treat as left click + makeHandToggle('RS', 'RightHand', makeViveWhen('RS', 'RX', 'RY')); + makeHandToggle('LS', 'LeftHand', makeViveWhen('LS', 'LX', 'LY')); + clickMapping.from(Controller.Hardware.Vive.RS).when(makeViveWhen('RS', 'RX', 'RY')).to(Controller.Actions.ReticleClick); + clickMapping.from(Controller.Hardware.Vive.LS).when(makeViveWhen('LS', 'LX', 'LY')).to(Controller.Actions.ReticleClick); + mapToAction('RightApplicationMenu', 'ContextMenu'); + mapToAction('LeftApplicationMenu', 'ContextMenu'); + break; + } + clickMappings[hardware] = clickMapping; + } + clickMapToggle = new LatchedToggle(clickMapping.enable, clickMapping.disable); + clickMapToggle.setState(true); +} +checkHardware(); + +// VISUAL AID ----------- +// Same properties as handControllerGrab search sphere +var BALL_SIZE = 0.011; +var BALL_ALPHA = 0.5; +var fakeProjectionBall = Overlays.addOverlay("sphere", { + size: 5 * BALL_SIZE, + color: {red: 255, green: 10, blue: 10}, + ignoreRayIntersection: true, + alpha: BALL_ALPHA, + visible: false, + solid: true, + drawInFront: true // Even when burried inside of something, show it. +}); +var overlays = [fakeProjectionBall]; // If we want to try showing multiple balls and lasers. +Script.scriptEnding.connect(function () { + overlays.forEach(Overlays.deleteOverlay); +}); +var visualizationIsShowing = false; // Not whether it desired, but simply whether it is. Just an optimziation. +function turnOffVisualization(optionalEnableClicks) { // because we're showing cursor on HUD + if (!optionalEnableClicks) { + expireMouseCursor(); + } + if (!visualizationIsShowing) { + return; + } + visualizationIsShowing = false; + overlays.forEach(function (overlay) { + Overlays.editOverlay(overlay, {visible: false}); + }); +} +var MAX_RAY_SCALE = 32000; // Anything large. It's a scale, not a distance. +function updateVisualization(controllerPosition, controllerDirection, hudPosition3d, hudPosition2d) { + // Show an indication of where the cursor will appear when crossing a HUD element, + // and where in-world clicking will occur. + // + // There are a number of ways we could do this, but for now, it's a blue sphere that rolls along + // the HUD surface, and a red sphere that rolls along the 3d objects that will receive the click. + // We'll leave it to other scripts (like handControllerGrab) to show a search beam when desired. + + function intersection3d(position, direction) { + // Answer in-world intersection (entity or 3d overlay), or way-out point + var pickRay = {origin: position, direction: direction}; + var result = findRayIntersection(pickRay); + return result.intersects ? result.intersection : Vec3.sum(position, Vec3.multiply(MAX_RAY_SCALE, direction)); + } + + visualizationIsShowing = true; + // We'd rather in-world interactions be done at the termination of the hand beam + // -- intersection3d(controllerPosition, controllerDirection). Maybe have handControllerGrab + // direclty manipulate both entity and 3d overlay objects. + // For now, though, we present a false projection of the cursor onto whatever is below it. This is + // different from the hand beam termination because the false projection is from the camera, while + // the hand beam termination is from the hand. + var eye = Camera.getPosition(); + var falseProjection = intersection3d(eye, Vec3.subtract(hudPosition3d, eye)); + Overlays.editOverlay(fakeProjectionBall, {visible: true, position: falseProjection}); + Reticle.visible = false; + + return visualizationIsShowing; // In case we change caller to act conditionally. +} + +// MAIN OPERATIONS ----------- +// +function update() { + var now = Date.now(); + if (!handControllerLockOut.expired(now)) { + return turnOffVisualization(); + } // Let them use mouse it in peace. + if (!Menu.isOptionChecked("First Person")) { + return turnOffVisualization(); + } // What to do? menus can be behind hand! + var controllerPose = Controller.getPoseValue(activeHand); + // Vive is effectively invalid when not in HMD + if (!controllerPose.valid || ((hardware === 'Vive') && !HMD.active)) { + return turnOffVisualization(); + } // Controller is cradled. + var controllerPosition = Vec3.sum(Vec3.multiplyQbyV(MyAvatar.orientation, controllerPose.translation), + MyAvatar.position); + // This gets point direction right, but if you want general quaternion it would be more complicated: + var controllerDirection = Quat.getUp(Quat.multiply(MyAvatar.orientation, controllerPose.rotation)); + + var hudPoint3d = calculateRayUICollisionPoint(controllerPosition, controllerDirection); + if (!hudPoint3d) { + print('Controller is parallel to HUD'); + return turnOffVisualization(); + } + var hudPoint2d = overlayFromWorldPoint(hudPoint3d); + + // We don't know yet if we'll want to make the cursor visble, but we need to move it to see if + // it's pointing at a QML tool (aka system overlay). + setReticlePosition(hudPoint2d); + // If there's a HUD element at the (newly moved) reticle, just make it visible and bail. + if (isPointingAtOverlay(hudPoint2d)) { + if (HMD.active) { // Doesn't hurt anything without the guard, but consider it documentation. + Reticle.depth = SPHERICAL_HUD_DISTANCE; // NOT CORRECT IF WE SWITCH TO OFFSET SPHERE! + } + Reticle.visible = true; + return turnOffVisualization(true); + } + // We are not pointing at a HUD element (but it could be a 3d overlay). + updateVisualization(controllerPosition, controllerDirection, hudPoint3d, hudPoint2d); +} + +var UPDATE_INTERVAL = 20; // milliseconds. Script.update is too frequent. +var updater = Script.setInterval(update, UPDATE_INTERVAL); +Script.scriptEnding.connect(function () { + Script.clearInterval(updater); +}); + +// Check periodically for changes to setup. +var SETTINGS_CHANGE_RECHECK_INTERVAL = 10 * 1000; // milliseconds +function checkSettings() { + updateFieldOfView(); + checkHardware(); +} +checkSettings(); +var settingsChecker = Script.setInterval(checkSettings, SETTINGS_CHANGE_RECHECK_INTERVAL); +Script.scriptEnding.connect(function () { + Script.clearInterval(settingsChecker); +}); diff --git a/scripts/system/depthReticle.js b/scripts/system/depthReticle.js deleted file mode 100644 index 10d604f707..0000000000 --- a/scripts/system/depthReticle.js +++ /dev/null @@ -1,185 +0,0 @@ -// depthReticle.js -// examples -// -// Created by Brad Hefta-Gaub on 2/23/16. -// Copyright 2016 High Fidelity, Inc. -// -// When used in HMD, this script will make the reticle depth track to any clickable item in view. -// This script also handles auto-hiding the reticle after inactivity, as well as having the reticle -// seek the look at position upon waking up. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -var APPARENT_2D_OVERLAY_DEPTH = 1.0; -var APPARENT_MAXIMUM_DEPTH = 100.0; // this is a depth at which things all seem sufficiently distant -var lastDepthCheckTime = Date.now(); -var desiredDepth = APPARENT_2D_OVERLAY_DEPTH; -var TIME_BETWEEN_DEPTH_CHECKS = 100; -var MINIMUM_DEPTH_ADJUST = 0.01; -var NON_LINEAR_DIVISOR = 2; -var MINIMUM_SEEK_DISTANCE = 0.01; - -var lastMouseMoveOrClick = Date.now(); -var lastMouseX = Reticle.position.x; -var lastMouseY = Reticle.position.y; -var HIDE_STATIC_MOUSE_AFTER = 3000; // 3 seconds -var shouldSeekToLookAt = false; -var fastMouseMoves = 0; -var averageMouseVelocity = 0; -var WEIGHTING = 1/20; // simple moving average over last 20 samples -var ONE_MINUS_WEIGHTING = 1 - WEIGHTING; -var AVERAGE_MOUSE_VELOCITY_FOR_SEEK_TO = 50; - -function showReticleOnMouseClick() { - Reticle.visible = true; - lastMouseMoveOrClick = Date.now(); // move or click -} - -Controller.mousePressEvent.connect(showReticleOnMouseClick); -Controller.mouseDoublePressEvent.connect(showReticleOnMouseClick); - -Controller.mouseMoveEvent.connect(function(mouseEvent) { - var now = Date.now(); - - // if the reticle is hidden, and we're not in away mode... - if (!Reticle.visible && Reticle.allowMouseCapture) { - Reticle.visible = true; - if (HMD.active) { - shouldSeekToLookAt = true; - } - } else { - // even if the reticle is visible, if we're in HMD mode, and the person is moving their mouse quickly (shaking it) - // then they are probably looking for it, and we should move into seekToLookAt mode - if (HMD.active && !shouldSeekToLookAt && Reticle.allowMouseCapture) { - var dx = Reticle.position.x - lastMouseX; - var dy = Reticle.position.y - lastMouseY; - var dt = Math.max(1, (now - lastMouseMoveOrClick)); // mSecs since last mouse move - var mouseMoveDistance = Math.sqrt((dx*dx) + (dy*dy)); - var mouseVelocity = mouseMoveDistance / dt; - averageMouseVelocity = (ONE_MINUS_WEIGHTING * averageMouseVelocity) + (WEIGHTING * mouseVelocity); - if (averageMouseVelocity > AVERAGE_MOUSE_VELOCITY_FOR_SEEK_TO) { - shouldSeekToLookAt = true; - } - } - } - lastMouseMoveOrClick = now; - lastMouseX = mouseEvent.x; - lastMouseY = mouseEvent.y; -}); - -function seekToLookAt() { - // if we're currently seeking the lookAt move the mouse toward the lookat - if (shouldSeekToLookAt) { - averageMouseVelocity = 0; // reset this, these never count for movement... - var lookAt2D = HMD.getHUDLookAtPosition2D(); - var currentReticlePosition = Reticle.position; - var distanceBetweenX = lookAt2D.x - Reticle.position.x; - var distanceBetweenY = lookAt2D.y - Reticle.position.y; - var moveX = distanceBetweenX / NON_LINEAR_DIVISOR; - var moveY = distanceBetweenY / NON_LINEAR_DIVISOR; - var newPosition = { x: Reticle.position.x + moveX, y: Reticle.position.y + moveY }; - var closeEnoughX = false; - var closeEnoughY = false; - if (moveX < MINIMUM_SEEK_DISTANCE) { - newPosition.x = lookAt2D.x; - closeEnoughX = true; - } - if (moveY < MINIMUM_SEEK_DISTANCE) { - newPosition.y = lookAt2D.y; - closeEnoughY = true; - } - Reticle.position = newPosition; - if (closeEnoughX && closeEnoughY) { - shouldSeekToLookAt = false; - } - } -} - -function autoHideReticle() { - var now = Date.now(); - - // sometimes we don't actually get mouse move messages (for example, if the focus has been set - // to an overlay or web page 'overlay') in but the mouse can still be moving, and we don't want - // to autohide in these cases, so we will take this opportunity to also check if the reticle - // position has changed. - if (lastMouseX != Reticle.position.x || lastMouseY != Reticle.position.y) { - lastMouseMoveOrClick = now; - lastMouseX = Reticle.position.x; - lastMouseY = Reticle.position.y; - } - - // if we haven't moved in a long period of time, and we're not pointing at some - // system overlay (like a window), then hide the reticle - if (Reticle.visible && !Reticle.pointingAtSystemOverlay) { - var timeSinceLastMouseMove = now - lastMouseMoveOrClick; - if (timeSinceLastMouseMove > HIDE_STATIC_MOUSE_AFTER) { - Reticle.visible = false; - } - } -} - -function checkReticleDepth() { - var now = Date.now(); - var timeSinceLastDepthCheck = now - lastDepthCheckTime; - if (timeSinceLastDepthCheck > TIME_BETWEEN_DEPTH_CHECKS && Reticle.visible) { - var newDesiredDepth = desiredDepth; - lastDepthCheckTime = now; - var reticlePosition = Reticle.position; - - // first check the 2D Overlays - if (Reticle.pointingAtSystemOverlay || Overlays.getOverlayAtPoint(reticlePosition)) { - newDesiredDepth = APPARENT_2D_OVERLAY_DEPTH; - } else { - var pickRay = Camera.computePickRay(reticlePosition.x, reticlePosition.y); - - // Then check the 3D overlays - var result = Overlays.findRayIntersection(pickRay); - - if (!result.intersects) { - // finally check the entities - result = Entities.findRayIntersection(pickRay, true); - } - - // If either the overlays or entities intersect, then set the reticle depth to - // the distance of intersection - if (result.intersects) { - newDesiredDepth = result.distance; - } else { - // if nothing intersects... set the depth to some sufficiently large depth - newDesiredDepth = APPARENT_MAXIMUM_DEPTH; - } - } - - // If the desired depth has changed, reset our fade start time - if (desiredDepth != newDesiredDepth) { - desiredDepth = newDesiredDepth; - } - } - -} - -function moveToDesiredDepth() { - // move the reticle toward the desired depth - if (desiredDepth != Reticle.depth) { - - // cut distance between desiredDepth and current depth in half until we're close enough - var distanceToAdjustThisCycle = (desiredDepth - Reticle.depth) / NON_LINEAR_DIVISOR; - if (Math.abs(distanceToAdjustThisCycle) < MINIMUM_DEPTH_ADJUST) { - newDepth = desiredDepth; - } else { - newDepth = Reticle.depth + distanceToAdjustThisCycle; - } - Reticle.setDepth(newDepth); - } -} - -Script.update.connect(function(deltaTime) { - autoHideReticle(); // auto hide reticle for desktop or HMD mode - if (HMD.active) { - seekToLookAt(); // handle moving the reticle toward the look at - checkReticleDepth(); // make sure reticle is at correct depth - moveToDesiredDepth(); // move the fade the reticle to the desired depth - } -});