Merge branch 'master' into audio_devices_split

This commit is contained in:
vladest 2017-09-19 17:43:03 +02:00
commit 6c32783a09
229 changed files with 11693 additions and 6717 deletions

View file

@ -54,7 +54,11 @@ module.exports = {
"Window": false,
"XMLHttpRequest": false,
"location": false,
"print": false
"print": false,
"RayPick": false,
"LaserPointers": false,
"ContextOverlay": false,
"module": false
},
"rules": {
"brace-style": ["error", "1tbs", { "allowSingleLine": false }],

View file

@ -27,11 +27,20 @@ Go to `Control Panel > System > Advanced System Settings > Environment Variables
* Set "Variable name": `QT_CMAKE_PREFIX_PATH`
* Set "Variable value": `C:\Qt\5.9.1\msvc2017_64\lib\cmake`
### Step 5. Installing OpenSSL
### Step 5. Installing [vcpkg](https://github.com/Microsoft/vcpkg)
Download and install the Win64 OpenSSL v1.0.2 Installer[https://slproweb.com/products/Win32OpenSSL.html].
* Clone the VCPKG [repository](https://github.com/Microsoft/vcpkg)
* Follow the instructions in the [readme](https://github.com/Microsoft/vcpkg/blob/master/README.md) to bootstrap vcpkg
* Note, you may need to do these in a _Developer Command Prompt_
* Set an environment variable VCPKG_ROOT to the location of the cloned repository
* Close and re-open any command prompts after setting the environment variable so that they will pick up the change
### Step 6. Running CMake to Generate Build Files
### Step 6. Installing OpenSSL via vcpkg
* In the vcpkg directory, install the 64 bit OpenSSL package with the command `vcpkg install openssl:x64-windows`
* Once the build completes you should have a file `ssl.h` in `${VCPKG_ROOT}/installed/x64-windows/include/openssl`
### Step 7. Running CMake to Generate Build Files
Run Command Prompt from Start and run the following commands:
```
@ -43,7 +52,7 @@ cmake .. -G "Visual Studio 15 Win64"
Where `%HIFI_DIR%` is the directory for the highfidelity repository.
### Step 7. Making a Build
### Step 8. Making a Build
Open `%HIFI_DIR%\build\hifi.sln` using Visual Studio.
@ -51,7 +60,7 @@ Change the Solution Configuration (next to the green play button) from "Debug" t
Run `Build > Build Solution`.
### Step 8. Testing Interface
### Step 9. Testing Interface
Create another environment variable (see Step #4)
* Set "Variable name": `_NO_DEBUG_HEAP`
@ -65,16 +74,20 @@ Note: You can also run Interface by launching it from command line or File Explo
## Troubleshooting
For any problems after Step #6, first try this:
For any problems after Step #7, first try this:
* Delete your locally cloned copy of the highfidelity repository
* Restart your computer
* Redownload the [repository](https://github.com/highfidelity/hifi)
* Restart directions from Step #6
* Restart directions from Step #7
#### CMake gives you the same error message repeatedly after the build fails
Remove `CMakeCache.txt` found in the `%HIFI_DIR%\build` directory.
#### CMake can't find OpenSSL
Remove `CMakeCache.txt` found in the `%HIFI_DIR%\build` directory. Verify that your VCPKG_ROOT environment variable is set and pointing to the correct location. Verify that the file `${VCPKG_ROOT}/installed/x64-windows/include/openssl/ssl.h` exists.
#### Qt is throwing an error
Make sure you have the correct version (5.9.1) installed and `QT_CMAKE_PREFIX_PATH` environment variable is set correctly.

View file

@ -4,254 +4,81 @@ else()
cmake_minimum_required(VERSION 3.2)
endif()
if (USE_ANDROID_TOOLCHAIN)
set(CMAKE_TOOLCHAIN_FILE "${CMAKE_CURRENT_SOURCE_DIR}/cmake/android/android.toolchain.cmake")
set(ANDROID_NATIVE_API_LEVEL 19)
set(ANDROID_TOOLCHAIN_NAME arm-linux-androideabi-clang3.5)
set(ANDROID_STL c++_shared)
endif ()
if (WIN32)
cmake_policy(SET CMP0020 NEW)
endif (WIN32)
if (POLICY CMP0043)
cmake_policy(SET CMP0043 OLD)
endif ()
if (POLICY CMP0042)
cmake_policy(SET CMP0042 OLD)
endif ()
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
set_property(GLOBAL PROPERTY PREDEFINED_TARGETS_FOLDER "CMakeTargets")
include("cmake/init.cmake")
project(hifi)
add_definitions(-DGLM_FORCE_RADIANS)
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")
find_package( Threads )
include("cmake/compiler.cmake")
if (WIN32)
if (NOT "${CMAKE_SIZEOF_VOID_P}" EQUAL "8")
message( FATAL_ERROR "Only 64 bit builds supported." )
endif()
add_definitions(-DNOMINMAX -D_CRT_SECURE_NO_WARNINGS)
if (NOT WINDOW_SDK_PATH)
set(DEBUG_DISCOVERED_SDK_PATH TRUE)
endif()
# sets path for Microsoft SDKs
# if you get build error about missing 'glu32' this path is likely wrong
if (MSVC_VERSION GREATER_EQUAL 1910) # VS 2017
set(WINDOW_SDK_PATH "C:/Program Files (x86)/Windows Kits/10/Lib/${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}/x64" CACHE PATH "Windows SDK PATH")
elseif (MSVC_VERSION GREATER_EQUAL 1800) # VS 2013
set(WINDOW_SDK_PATH "C:\\Program Files (x86)\\Windows Kits\\8.1\\Lib\\winv6.3\\um\\${WINDOW_SDK_FOLDER}" CACHE PATH "Windows SDK PATH")
else()
message( FATAL_ERROR "Visual Studio 2013 or higher required." )
endif()
if (DEBUG_DISCOVERED_SDK_PATH)
message(STATUS "The discovered Windows SDK path is ${WINDOW_SDK_PATH}")
endif ()
set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} ${WINDOW_SDK_PATH})
# /wd4351 disables warning C4351: new behavior: elements of array will be default initialized
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP /wd4351")
# /LARGEADDRESSAWARE enables 32-bit apps to use more than 2GB of memory.
# Caveats: http://stackoverflow.com/questions/2288728/drawbacks-of-using-largeaddressaware-for-32-bit-windows-executables
# TODO: Remove when building 64-bit.
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /LARGEADDRESSAWARE")
# always produce symbols as PDB files
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /Zi")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /DEBUG /OPT:REF /OPT:ICF")
else ()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -fno-strict-aliasing -Wno-unused-parameter")
if (CMAKE_CXX_COMPILER_ID MATCHES "GNU")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ggdb -Woverloaded-virtual -Wdouble-promotion")
if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER "5.1") # gcc 5.1 and on have suggest-override
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wsuggest-override")
endif ()
endif ()
endif(WIN32)
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS "5.3")
# GLM 0.9.8 on Ubuntu 14 (gcc 4.4) has issues with the simd declarations
add_definitions(-DGLM_FORCE_PURE)
endif()
if (NOT DEFINED SERVER_ONLY)
set(SERVER_ONLY 0)
endif()
if (NOT ANDROID)
if ((NOT MSVC12) AND (NOT MSVC14))
include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if (COMPILER_SUPPORTS_CXX11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(COMPILER_SUPPORTS_CXX0X)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()
endif ()
else ()
# assume that the toolchain selected for android has C++11 support
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
endif ()
if (APPLE)
set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LANGUAGE_STANDARD "c++11")
set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LIBRARY "libc++")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --stdlib=libc++")
endif ()
if (NOT ANDROID_LIB_DIR)
set(ANDROID_LIB_DIR $ENV{ANDROID_LIB_DIR})
endif ()
if (ANDROID)
if (NOT ANDROID_QT_CMAKE_PREFIX_PATH)
set(QT_CMAKE_PREFIX_PATH ${ANDROID_LIB_DIR}/Qt/5.5/android_armv7/lib/cmake)
else ()
set(QT_CMAKE_PREFIX_PATH ${ANDROID_QT_CMAKE_PREFIX_PATH})
endif ()
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/lib)
if (ANDROID_LIB_DIR)
list(APPEND CMAKE_FIND_ROOT_PATH ${ANDROID_LIB_DIR})
endif ()
else ()
if (NOT QT_CMAKE_PREFIX_PATH)
set(QT_CMAKE_PREFIX_PATH $ENV{QT_CMAKE_PREFIX_PATH})
endif ()
if (NOT QT_CMAKE_PREFIX_PATH)
get_filename_component(QT_CMAKE_PREFIX_PATH "${Qt5_DIR}/.." REALPATH)
endif ()
endif ()
set(QT_DIR $ENV{QT_DIR})
if (WIN32)
if (NOT EXISTS ${QT_CMAKE_PREFIX_PATH})
message(FATAL_ERROR "Could not determine QT_CMAKE_PREFIX_PATH.")
endif ()
if (ANDROID OR UWP)
set(MOBILE 1)
else()
set(MOBILE 0)
endif()
# figure out where the qt dir is
get_filename_component(QT_DIR "${QT_CMAKE_PREFIX_PATH}/../../" ABSOLUTE)
if (ANDROID OR UWP)
option(BUILD_SERVER "Build server components" OFF)
option(BUILD_TOOLS "Build tools" OFF)
else()
option(BUILD_SERVER "Build server components" ON)
option(BUILD_TOOLS "Build tools" ON)
endif()
set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} ${QT_CMAKE_PREFIX_PATH})
if (SERVER_ONLY)
option(BUILD_CLIENT "Build client components" OFF)
option(BUILD_TESTS "Build tests" OFF)
else()
option(BUILD_CLIENT "Build client components" ON)
option(BUILD_TESTS "Build tests" ON)
endif()
if (APPLE)
option(BUILD_INSTALLER "Build installer" ON)
exec_program(sw_vers ARGS -productVersion OUTPUT_VARIABLE OSX_VERSION)
string(REGEX MATCH "^[0-9]+\\.[0-9]+" OSX_VERSION ${OSX_VERSION})
message(STATUS "Detected OS X version = ${OSX_VERSION}")
MESSAGE(STATUS "Build server: " ${BUILD_SERVER})
MESSAGE(STATUS "Build client: " ${BUILD_CLIENT})
MESSAGE(STATUS "Build tests: " ${BUILD_TESTS})
MESSAGE(STATUS "Build tools: " ${BUILD_TOOLS})
MESSAGE(STATUS "Build installer: " ${BUILD_INSTALLER})
set(OSX_SDK "${OSX_VERSION}" CACHE String "OS X SDK version to look for inside Xcode bundle or at OSX_SDK_PATH")
if (UNIX AND DEFINED ENV{HIFI_MEMORY_DEBUGGING})
MESSAGE(STATUS "Memory debugging is enabled")
endif()
# set our OS X deployment target
set(CMAKE_OSX_DEPLOYMENT_TARGET 10.8)
# find the SDK path for the desired SDK
find_path(
_OSX_DESIRED_SDK_PATH
NAME MacOSX${OSX_SDK}.sdk
HINTS ${OSX_SDK_PATH}
PATHS /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/
/Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/
)
if (NOT _OSX_DESIRED_SDK_PATH)
message(STATUS "Could not find OS X ${OSX_SDK} SDK. Will fall back to default. If you want a specific SDK, please pass OSX_SDK and optionally OSX_SDK_PATH to CMake.")
else ()
message(STATUS "Found OS X ${OSX_SDK} SDK at ${_OSX_DESIRED_SDK_PATH}/MacOSX${OSX_SDK}.sdk")
# set that as the SDK to use
set(CMAKE_OSX_SYSROOT ${_OSX_DESIRED_SDK_PATH}/MacOSX${OSX_SDK}.sdk)
endif ()
endif ()
# Hide automoc folders (for IDEs)
set(AUTOGEN_TARGETS_FOLDER "hidden/generated")
# Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# Instruct CMake to run moc automatically when needed.
set(CMAKE_AUTOMOC ON)
# Instruct CMake to run rcc automatically when needed
set(CMAKE_AUTORCC ON)
set(HIFI_LIBRARY_DIR "${CMAKE_CURRENT_SOURCE_DIR}/libraries")
# setup for find modules
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules/")
if (CMAKE_BUILD_TYPE)
string(TOUPPER ${CMAKE_BUILD_TYPE} UPPER_CMAKE_BUILD_TYPE)
else ()
set(UPPER_CMAKE_BUILD_TYPE DEBUG)
endif ()
set(HF_CMAKE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
set(MACRO_DIR "${HF_CMAKE_DIR}/macros")
set(EXTERNAL_PROJECT_DIR "${HF_CMAKE_DIR}/externals")
file(GLOB HIFI_CUSTOM_MACROS "cmake/macros/*.cmake")
foreach(CUSTOM_MACRO ${HIFI_CUSTOM_MACROS})
include(${CUSTOM_MACRO})
endforeach()
#
# Helper projects
#
file(GLOB_RECURSE CMAKE_SRC cmake/*.cmake cmake/CMakeLists.txt)
add_custom_target(cmake SOURCES ${CMAKE_SRC})
GroupSources("cmake")
file(GLOB_RECURSE JS_SRC scripts/*.js unpublishedScripts/*.js)
add_custom_target(js SOURCES ${JS_SRC})
GroupSources("scripts")
GroupSources("unpublishedScripts")
if (UNIX)
install(
DIRECTORY "${CMAKE_SOURCE_DIR}/scripts"
DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/interface
COMPONENT ${CLIENT_COMPONENT}
)
endif()
# Locate the required Qt build on the filesystem
setup_qt()
list(APPEND CMAKE_PREFIX_PATH "${QT_CMAKE_PREFIX_PATH}")
if (ANDROID)
file(GLOB ANDROID_CUSTOM_MACROS "cmake/android/*.cmake")
foreach(CUSTOM_MACRO ${ANDROID_CUSTOM_MACROS})
include(${CUSTOM_MACRO})
endforeach()
endif ()
find_package( Threads )
add_definitions(-DGLM_FORCE_RADIANS)
set(HIFI_LIBRARY_DIR "${CMAKE_CURRENT_SOURCE_DIR}/libraries")
set(EXTERNAL_PROJECT_PREFIX "project")
set_property(DIRECTORY PROPERTY EP_PREFIX ${EXTERNAL_PROJECT_PREFIX})
setup_externals_binary_dir()
option(USE_NSIGHT "Attempt to find the nSight libraries" 1)
option(GET_QUAZIP "Get QuaZip library automatically as external project" 1)
if (WIN32)
add_paths_to_fixup_libs("${QT_DIR}/bin")
endif ()
if (NOT DEFINED SERVER_ONLY)
set(SERVER_ONLY 0)
endif()
set_packaging_parameters()
option(BUILD_TESTS "Build tests" ON)
MESSAGE(STATUS "Build tests: " ${BUILD_TESTS})
# add subdirectories for all targets
if (NOT ANDROID)
if (BUILD_SERVER)
add_subdirectory(assignment-client)
set_target_properties(assignment-client PROPERTIES FOLDER "Apps")
add_subdirectory(domain-server)
@ -259,30 +86,36 @@ if (NOT ANDROID)
add_subdirectory(ice-server)
set_target_properties(ice-server PROPERTIES FOLDER "Apps")
add_subdirectory(server-console)
if (NOT SERVER_ONLY)
endif()
if (BUILD_CLIENT)
add_subdirectory(interface)
set_target_properties(interface PROPERTIES FOLDER "Apps")
if (BUILD_TESTS)
add_subdirectory(tests)
if (ANDROID)
add_subdirectory(gvr-interface)
set_target_properties(gvr-interface PROPERTIES FOLDER "Apps")
endif()
endif()
add_subdirectory(plugins)
endif()
if (BUILD_CLIENT OR BUILD_SERVER)
add_subdirectory(plugins)
endif()
if (BUILD_TOOLS)
add_subdirectory(tools)
endif()
if (ANDROID OR DESKTOP_GVR)
add_subdirectory(interface)
add_subdirectory(gvr-interface)
add_subdirectory(plugins)
endif ()
if (BUILD_TESTS)
add_subdirectory(tests)
endif()
if (DEFINED ENV{HIFI_MEMORY_DEBUGGING})
SET( HIFI_MEMORY_DEBUGGING true )
endif ()
if (HIFI_MEMORY_DEBUGGING)
if (UNIX)
MESSAGE("-- Memory debugging is enabled")
endif (UNIX)
endif ()
generate_installers()
if (BUILD_INSTALLER)
if (UNIX)
install(
DIRECTORY "${CMAKE_SOURCE_DIR}/scripts"
DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/interface
COMPONENT ${CLIENT_COMPONENT}
)
endif()
generate_installers()
endif()

Binary file not shown.

View file

@ -354,15 +354,16 @@ void Agent::scriptRequestFinished() {
void Agent::executeScript() {
_scriptEngine = std::unique_ptr<ScriptEngine>(new ScriptEngine(ScriptEngine::AGENT_SCRIPT, _scriptContents, _payload));
_scriptEngine = scriptEngineFactory(ScriptEngine::AGENT_SCRIPT, _scriptContents, _payload);
_scriptEngine->setParent(this); // be the parent of the script engine so it gets moved when we do
DependencyManager::get<RecordingScriptingInterface>()->setScriptEngine(_scriptEngine.get());
DependencyManager::get<RecordingScriptingInterface>()->setScriptEngine(_scriptEngine);
// setup an Avatar for the script to use
auto scriptedAvatar = DependencyManager::get<ScriptableAvatar>();
connect(_scriptEngine.get(), SIGNAL(update(float)), scriptedAvatar.data(), SLOT(update(float)), Qt::ConnectionType::QueuedConnection);
connect(_scriptEngine.data(), SIGNAL(update(float)),
scriptedAvatar.data(), SLOT(update(float)), Qt::ConnectionType::QueuedConnection);
scriptedAvatar->setForceFaceTrackerConnected(true);
// call model URL setters with empty URLs so our avatar, if user, will have the default models

View file

@ -88,7 +88,7 @@ private:
void encodeFrameOfZeros(QByteArray& encodedZeros);
void computeLoudness(const QByteArray* decodedBuffer, QSharedPointer<ScriptableAvatar>);
std::unique_ptr<ScriptEngine> _scriptEngine;
ScriptEnginePointer _scriptEngine;
EntityEditPacketSender _entityEditSender;
EntityTreeHeadlessViewer _entityViewer;

View file

@ -558,7 +558,7 @@ float computeAzimuth(const AvatarAudioStream& listeningNodeStream, const Positio
// produce an oriented angle about the y-axis
glm::vec3 direction = rotatedSourcePosition * (1.0f / fastSqrtf(rotatedSourcePositionLength2));
float angle = fastAcosf(glm::clamp(-direction.z, -1.0f, 1.0f)); // UNIT_NEG_Z is "forward"
float angle = fastAcosf(glm::clamp(-direction.z, -1.0f, 1.0f)); // UNIT_NEG_Z is "forward"
return (direction.x < 0.0f) ? -angle : angle;
} else {

View file

@ -170,9 +170,9 @@ void AvatarMixerSlave::broadcastAvatarDataToAgent(const SharedNodePointer& node)
auto avatarPacketList = NLPacketList::create(PacketType::BulkAvatarData);
// Define the minimum bubble size
static const glm::vec3 minBubbleSize = glm::vec3(0.3f, 1.3f, 0.3f);
static const glm::vec3 minBubbleSize = avatar.getSensorToWorldScale() * glm::vec3(0.3f, 1.3f, 0.3f);
// Define the scale of the box for the current node
glm::vec3 nodeBoxScale = (nodeData->getPosition() - nodeData->getGlobalBoundingBoxCorner()) * 2.0f;
glm::vec3 nodeBoxScale = (nodeData->getPosition() - nodeData->getGlobalBoundingBoxCorner()) * 2.0f * avatar.getSensorToWorldScale();
// Set up the bounding box for the current node
AABox nodeBox(nodeData->getGlobalBoundingBoxCorner(), nodeBoxScale);
// Clamp the size of the bounding box to a minimum scale
@ -209,7 +209,7 @@ void AvatarMixerSlave::broadcastAvatarDataToAgent(const SharedNodePointer& node)
assert(avatarNode); // we can't have gotten here without the avatarData being a valid key in the map
return nodeData->getLastBroadcastTime(avatarNode->getUUID());
}, [&](AvatarSharedPointer avatar)->float{
glm::vec3 nodeBoxHalfScale = (avatar->getPosition() - avatar->getGlobalBoundingBoxCorner());
glm::vec3 nodeBoxHalfScale = (avatar->getPosition() - avatar->getGlobalBoundingBoxCorner() * avatar->getSensorToWorldScale());
return glm::max(nodeBoxHalfScale.x, glm::max(nodeBoxHalfScale.y, nodeBoxHalfScale.z));
}, [&](AvatarSharedPointer avatar)->bool {
if (avatar == thisAvatar) {
@ -244,9 +244,9 @@ void AvatarMixerSlave::broadcastAvatarDataToAgent(const SharedNodePointer& node)
// Check to see if the space bubble is enabled
// Don't bother with these checks if the other avatar has their bubble enabled and we're gettingAnyIgnored
if (node->isIgnoreRadiusEnabled() || (avatarNode->isIgnoreRadiusEnabled() && !getsAnyIgnored)) {
float sensorToWorldScale = avatarNodeData->getAvatarSharedPointer()->getSensorToWorldScale();
// Define the scale of the box for the current other node
glm::vec3 otherNodeBoxScale = (avatarNodeData->getPosition() - avatarNodeData->getGlobalBoundingBoxCorner()) * 2.0f;
glm::vec3 otherNodeBoxScale = (avatarNodeData->getPosition() - avatarNodeData->getGlobalBoundingBoxCorner()) * 2.0f * sensorToWorldScale;
// Set up the bounding box for the current other node
AABox otherNodeBox(avatarNodeData->getGlobalBoundingBoxCorner(), otherNodeBoxScale);
// Clamp the size of the bounding box to a minimum scale
@ -334,8 +334,9 @@ void AvatarMixerSlave::broadcastAvatarDataToAgent(const SharedNodePointer& node)
glm::vec3 otherPosition = otherAvatar->getClientGlobalPosition();
// determine if avatar is in view, to determine how much data to include...
glm::vec3 otherNodeBoxScale = (otherPosition - otherNodeData->getGlobalBoundingBoxCorner()) * 2.0f;
glm::vec3 otherNodeBoxScale = (otherPosition - otherNodeData->getGlobalBoundingBoxCorner()) * 2.0f * otherAvatar->getSensorToWorldScale();
AABox otherNodeBox(otherNodeData->getGlobalBoundingBoxCorner(), otherNodeBoxScale);
bool isInView = nodeData->otherAvatarInView(otherNodeBox);

View file

@ -458,84 +458,80 @@ int OctreeSendThread::packetDistributor(SharedNodePointer node, OctreeQueryNode*
return _truePacketsSent;
}
bool OctreeSendThread::traverseTreeAndBuildNextPacketPayload(EncodeBitstreamParams& params) {
bool somethingToSend = false;
OctreeQueryNode* nodeData = static_cast<OctreeQueryNode*>(params.nodeData);
if (!nodeData->elementBag.isEmpty()) {
quint64 encodeStart = usecTimestampNow();
quint64 lockWaitStart = encodeStart;
_myServer->getOctree()->withReadLock([&]{
OctreeServer::trackTreeWaitTime((float)(usecTimestampNow() - lockWaitStart));
OctreeElementPointer subTree = nodeData->elementBag.extract();
if (subTree) {
// NOTE: this is where the tree "contents" are actually packed
nodeData->stats.encodeStarted();
_myServer->getOctree()->encodeTreeBitstream(subTree, &_packetData, nodeData->elementBag, params);
nodeData->stats.encodeStopped();
somethingToSend = true;
}
});
OctreeServer::trackEncodeTime((float)(usecTimestampNow() - encodeStart));
} else {
OctreeServer::trackTreeWaitTime(OctreeServer::SKIP_TIME);
OctreeServer::trackEncodeTime(OctreeServer::SKIP_TIME);
}
return somethingToSend;
}
void OctreeSendThread::traverseTreeAndSendContents(SharedNodePointer node, OctreeQueryNode* nodeData, bool viewFrustumChanged, bool isFullScene) {
// calculate max number of packets that can be sent during this interval
int clientMaxPacketsPerInterval = std::max(1, (nodeData->getMaxQueryPacketsPerSecond() / INTERVALS_PER_SECOND));
int maxPacketsPerInterval = std::min(clientMaxPacketsPerInterval, _myServer->getPacketsPerClientPerInterval());
int extraPackingAttempts = 0;
bool completedScene = false;
// init params once outside the while loop
int boundaryLevelAdjustClient = nodeData->getBoundaryLevelAdjust();
int boundaryLevelAdjust = boundaryLevelAdjustClient +
(viewFrustumChanged ? LOW_RES_MOVING_ADJUST : NO_BOUNDARY_ADJUST);
float octreeSizeScale = nodeData->getOctreeSizeScale();
EncodeBitstreamParams params(INT_MAX, WANT_EXISTS_BITS, DONT_CHOP,
viewFrustumChanged, boundaryLevelAdjust, octreeSizeScale,
isFullScene, _myServer->getJurisdiction(), nodeData);
// Our trackSend() function is implemented by the server subclass, and will be called back
// during the encodeTreeBitstream() as new entities/data elements are sent
params.trackSend = [this](const QUuid& dataID, quint64 dataEdited) {
_myServer->trackSend(dataID, dataEdited, _nodeUuid);
};
nodeData->copyCurrentViewFrustum(params.viewFrustum);
if (viewFrustumChanged) {
nodeData->copyLastKnownViewFrustum(params.lastViewFrustum);
}
bool somethingToSend = true; // assume we have something
bool bagHadSomething = !nodeData->elementBag.isEmpty();
while (somethingToSend && _packetsSentThisInterval < maxPacketsPerInterval && !nodeData->isShuttingDown()) {
float lockWaitElapsedUsec = OctreeServer::SKIP_TIME;
float encodeElapsedUsec = OctreeServer::SKIP_TIME;
float compressAndWriteElapsedUsec = OctreeServer::SKIP_TIME;
float packetSendingElapsedUsec = OctreeServer::SKIP_TIME;
quint64 startInside = usecTimestampNow();
bool lastNodeDidntFit = false; // assume each node fits
if (!nodeData->elementBag.isEmpty()) {
params.stopReason = EncodeBitstreamParams::UNKNOWN; // reset params.stopReason before traversal
quint64 lockWaitStart = usecTimestampNow();
_myServer->getOctree()->withReadLock([&]{
quint64 lockWaitEnd = usecTimestampNow();
lockWaitElapsedUsec = (float)(lockWaitEnd - lockWaitStart);
quint64 encodeStart = usecTimestampNow();
somethingToSend = traverseTreeAndBuildNextPacketPayload(params);
OctreeElementPointer subTree = nodeData->elementBag.extract();
if (!subTree) {
return;
}
float octreeSizeScale = nodeData->getOctreeSizeScale();
int boundaryLevelAdjustClient = nodeData->getBoundaryLevelAdjust();
int boundaryLevelAdjust = boundaryLevelAdjustClient +
(viewFrustumChanged ? LOW_RES_MOVING_ADJUST : NO_BOUNDARY_ADJUST);
EncodeBitstreamParams params(INT_MAX, WANT_EXISTS_BITS, DONT_CHOP,
viewFrustumChanged, boundaryLevelAdjust, octreeSizeScale,
isFullScene, _myServer->getJurisdiction(), nodeData);
nodeData->copyCurrentViewFrustum(params.viewFrustum);
if (viewFrustumChanged) {
nodeData->copyLastKnownViewFrustum(params.lastViewFrustum);
}
// Our trackSend() function is implemented by the server subclass, and will be called back
// during the encodeTreeBitstream() as new entities/data elements are sent
params.trackSend = [this](const QUuid& dataID, quint64 dataEdited) {
_myServer->trackSend(dataID, dataEdited, _nodeUuid);
};
// TODO: should this include the lock time or not? This stat is sent down to the client,
// it seems like it may be a good idea to include the lock time as part of the encode time
// are reported to client. Since you can encode without the lock
nodeData->stats.encodeStarted();
// NOTE: this is where the tree "contents" are actaully packed
_myServer->getOctree()->encodeTreeBitstream(subTree, &_packetData, nodeData->elementBag, params);
quint64 encodeEnd = usecTimestampNow();
encodeElapsedUsec = (float)(encodeEnd - encodeStart);
// If after calling encodeTreeBitstream() there are no nodes left to send, then we know we've
// sent the entire scene. We want to know this below so we'll actually write this content into
// the packet and send it
completedScene = nodeData->elementBag.isEmpty();
if (params.stopReason == EncodeBitstreamParams::DIDNT_FIT) {
lastNodeDidntFit = true;
extraPackingAttempts++;
}
nodeData->stats.encodeStopped();
});
} else {
somethingToSend = false; // this will cause us to drop out of the loop...
if (params.stopReason == EncodeBitstreamParams::DIDNT_FIT) {
lastNodeDidntFit = true;
extraPackingAttempts++;
}
// If the bag had contents but is now empty then we know we've sent the entire scene.
bool completedScene = bagHadSomething && nodeData->elementBag.isEmpty();
if (completedScene || lastNodeDidntFit) {
// we probably want to flush what has accumulated in nodeData but:
// do we have more data to send? and is there room?
@ -562,8 +558,7 @@ void OctreeSendThread::traverseTreeAndSendContents(SharedNodePointer node, Octre
if (sendNow) {
quint64 packetSendingStart = usecTimestampNow();
_packetsSentThisInterval += handlePacketSend(node, nodeData);
quint64 packetSendingEnd = usecTimestampNow();
packetSendingElapsedUsec = (float)(packetSendingEnd - packetSendingStart);
packetSendingElapsedUsec = (float)(usecTimestampNow() - packetSendingStart);
targetSize = nodeData->getAvailable() - sizeof(OCTREE_PACKET_INTERNAL_SECTION_SIZE);
extraPackingAttempts = 0;
@ -576,14 +571,9 @@ void OctreeSendThread::traverseTreeAndSendContents(SharedNodePointer node, Octre
}
_packetData.changeSettings(true, targetSize); // will do reset - NOTE: Always compressed
}
OctreeServer::trackTreeWaitTime(lockWaitElapsedUsec);
OctreeServer::trackEncodeTime(encodeElapsedUsec);
OctreeServer::trackCompressAndWriteTime(compressAndWriteElapsedUsec);
OctreeServer::trackPacketSendingTime(packetSendingElapsedUsec);
quint64 endInside = usecTimestampNow();
quint64 elapsedInsideUsecs = endInside - startInside;
OctreeServer::trackInsideTime((float)elapsedInsideUsecs);
OctreeServer::trackInsideTime((float)(usecTimestampNow() - startInside));
}
if (somethingToSend && _myServer->wantsVerboseDebug()) {

View file

@ -53,7 +53,9 @@ protected:
/// Called before a packetDistributor pass to allow for pre-distribution processing
virtual void preDistributionProcessing() {};
virtual void traverseTreeAndSendContents(SharedNodePointer node, OctreeQueryNode* nodeData, bool viewFrustumChanged, bool isFullScene);
virtual void traverseTreeAndSendContents(SharedNodePointer node, OctreeQueryNode* nodeData,
bool viewFrustumChanged, bool isFullScene);
virtual bool traverseTreeAndBuildNextPacketPayload(EncodeBitstreamParams& params);
OctreeServer* _myServer { nullptr };
QWeakPointer<Node> _node;

View file

@ -35,7 +35,7 @@
#include <QtCore/QDir>
int OctreeServer::_clientCount = 0;
const int MOVING_AVERAGE_SAMPLE_COUNTS = 1000000;
const int MOVING_AVERAGE_SAMPLE_COUNTS = 1000;
float OctreeServer::SKIP_TIME = -1.0f; // use this for trackXXXTime() calls for non-times
@ -136,18 +136,19 @@ void OctreeServer::trackEncodeTime(float time) {
if (time == SKIP_TIME) {
_noEncode++;
time = 0.0f;
} else if (time <= MAX_SHORT_TIME) {
_shortEncode++;
_averageShortEncodeTime.updateAverage(time);
} else if (time <= MAX_LONG_TIME) {
_longEncode++;
_averageLongEncodeTime.updateAverage(time);
} else {
_extraLongEncode++;
_averageExtraLongEncodeTime.updateAverage(time);
if (time <= MAX_SHORT_TIME) {
_shortEncode++;
_averageShortEncodeTime.updateAverage(time);
} else if (time <= MAX_LONG_TIME) {
_longEncode++;
_averageLongEncodeTime.updateAverage(time);
} else {
_extraLongEncode++;
_averageExtraLongEncodeTime.updateAverage(time);
}
_averageEncodeTime.updateAverage(time);
}
_averageEncodeTime.updateAverage(time);
}
void OctreeServer::trackTreeWaitTime(float time) {
@ -155,18 +156,19 @@ void OctreeServer::trackTreeWaitTime(float time) {
const float MAX_LONG_TIME = 100.0f;
if (time == SKIP_TIME) {
_noTreeWait++;
time = 0.0f;
} else if (time <= MAX_SHORT_TIME) {
_shortTreeWait++;
_averageTreeShortWaitTime.updateAverage(time);
} else if (time <= MAX_LONG_TIME) {
_longTreeWait++;
_averageTreeLongWaitTime.updateAverage(time);
} else {
_extraLongTreeWait++;
_averageTreeExtraLongWaitTime.updateAverage(time);
if (time <= MAX_SHORT_TIME) {
_shortTreeWait++;
_averageTreeShortWaitTime.updateAverage(time);
} else if (time <= MAX_LONG_TIME) {
_longTreeWait++;
_averageTreeLongWaitTime.updateAverage(time);
} else {
_extraLongTreeWait++;
_averageTreeExtraLongWaitTime.updateAverage(time);
}
_averageTreeWaitTime.updateAverage(time);
}
_averageTreeWaitTime.updateAverage(time);
}
void OctreeServer::trackCompressAndWriteTime(float time) {
@ -174,26 +176,27 @@ void OctreeServer::trackCompressAndWriteTime(float time) {
const float MAX_LONG_TIME = 100.0f;
if (time == SKIP_TIME) {
_noCompress++;
time = 0.0f;
} else if (time <= MAX_SHORT_TIME) {
_shortCompress++;
_averageShortCompressTime.updateAverage(time);
} else if (time <= MAX_LONG_TIME) {
_longCompress++;
_averageLongCompressTime.updateAverage(time);
} else {
_extraLongCompress++;
_averageExtraLongCompressTime.updateAverage(time);
if (time <= MAX_SHORT_TIME) {
_shortCompress++;
_averageShortCompressTime.updateAverage(time);
} else if (time <= MAX_LONG_TIME) {
_longCompress++;
_averageLongCompressTime.updateAverage(time);
} else {
_extraLongCompress++;
_averageExtraLongCompressTime.updateAverage(time);
}
_averageCompressAndWriteTime.updateAverage(time);
}
_averageCompressAndWriteTime.updateAverage(time);
}
void OctreeServer::trackPacketSendingTime(float time) {
if (time == SKIP_TIME) {
_noSend++;
time = 0.0f;
} else {
_averagePacketSendingTime.updateAverage(time);
}
_averagePacketSendingTime.updateAverage(time);
}
@ -202,18 +205,19 @@ void OctreeServer::trackProcessWaitTime(float time) {
const float MAX_LONG_TIME = 100.0f;
if (time == SKIP_TIME) {
_noProcessWait++;
time = 0.0f;
} else if (time <= MAX_SHORT_TIME) {
_shortProcessWait++;
_averageProcessShortWaitTime.updateAverage(time);
} else if (time <= MAX_LONG_TIME) {
_longProcessWait++;
_averageProcessLongWaitTime.updateAverage(time);
} else {
_extraLongProcessWait++;
_averageProcessExtraLongWaitTime.updateAverage(time);
if (time <= MAX_SHORT_TIME) {
_shortProcessWait++;
_averageProcessShortWaitTime.updateAverage(time);
} else if (time <= MAX_LONG_TIME) {
_longProcessWait++;
_averageProcessLongWaitTime.updateAverage(time);
} else {
_extraLongProcessWait++;
_averageProcessExtraLongWaitTime.updateAverage(time);
}
_averageProcessWaitTime.updateAverage(time);
}
_averageProcessWaitTime.updateAverage(time);
}
OctreeServer::OctreeServer(ReceivedMessage& message) :

View file

@ -415,8 +415,7 @@ void EntityScriptServer::selectAudioFormat(const QString& selectedCodecName) {
void EntityScriptServer::resetEntitiesScriptEngine() {
auto engineName = QString("about:Entities %1").arg(++_entitiesScriptEngineCount);
auto newEngine = QSharedPointer<ScriptEngine>(new ScriptEngine(ScriptEngine::ENTITY_SERVER_SCRIPT, NO_SCRIPT, engineName),
&ScriptEngine::deleteLater);
auto newEngine = scriptEngineFactory(ScriptEngine::ENTITY_SERVER_SCRIPT, NO_SCRIPT, engineName);
auto webSocketServerConstructorValue = newEngine->newFunction(WebSocketServerClass::constructor);
newEngine->globalObject().setProperty("WebSocketServer", webSocketServerConstructorValue);
@ -437,11 +436,14 @@ void EntityScriptServer::resetEntitiesScriptEngine() {
newEngine->runInThread();
DependencyManager::get<EntityScriptingInterface>()->setEntitiesScriptEngine(newEngine.data());
auto newEngineSP = qSharedPointerCast<EntitiesScriptEngineProvider>(newEngine);
DependencyManager::get<EntityScriptingInterface>()->setEntitiesScriptEngine(newEngineSP);
disconnect(_entitiesScriptEngine.data(), &ScriptEngine::entityScriptDetailsUpdated, this, &EntityScriptServer::updateEntityPPS);
disconnect(_entitiesScriptEngine.data(), &ScriptEngine::entityScriptDetailsUpdated,
this, &EntityScriptServer::updateEntityPPS);
_entitiesScriptEngine.swap(newEngine);
connect(_entitiesScriptEngine.data(), &ScriptEngine::entityScriptDetailsUpdated, this, &EntityScriptServer::updateEntityPPS);
connect(_entitiesScriptEngine.data(), &ScriptEngine::entityScriptDetailsUpdated,
this, &EntityScriptServer::updateEntityPPS);
}

View file

@ -72,7 +72,7 @@ private:
bool _shuttingDown { false };
static int _entitiesScriptEngineCount;
QSharedPointer<ScriptEngine> _entitiesScriptEngine;
ScriptEnginePointer _entitiesScriptEngine;
EntityEditPacketSender _entityEditSender;
EntityTreeHeadlessViewer _entityViewer;

106
cmake/compiler.cmake Normal file
View file

@ -0,0 +1,106 @@
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")
if (WIN32)
if (NOT "${CMAKE_SIZEOF_VOID_P}" EQUAL "8")
message( FATAL_ERROR "Only 64 bit builds supported." )
endif()
add_definitions(-DNOMINMAX -D_CRT_SECURE_NO_WARNINGS)
if (NOT WINDOW_SDK_PATH)
set(DEBUG_DISCOVERED_SDK_PATH TRUE)
endif()
# sets path for Microsoft SDKs
# if you get build error about missing 'glu32' this path is likely wrong
if (MSVC_VERSION GREATER_EQUAL 1910) # VS 2017
set(WINDOW_SDK_PATH "C:/Program Files (x86)/Windows Kits/10/Lib/${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}/x64" CACHE PATH "Windows SDK PATH")
elseif (MSVC_VERSION GREATER_EQUAL 1800) # VS 2013
set(WINDOW_SDK_PATH "C:\\Program Files (x86)\\Windows Kits\\8.1\\Lib\\winv6.3\\um\\${WINDOW_SDK_FOLDER}" CACHE PATH "Windows SDK PATH")
else()
message( FATAL_ERROR "Visual Studio 2013 or higher required." )
endif()
if (DEBUG_DISCOVERED_SDK_PATH)
message(STATUS "The discovered Windows SDK path is ${WINDOW_SDK_PATH}")
endif ()
list(APPEND CMAKE_PREFIX_PATH "${WINDOW_SDK_PATH}")
# /wd4351 disables warning C4351: new behavior: elements of array will be default initialized
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP /wd4351")
# /LARGEADDRESSAWARE enables 32-bit apps to use more than 2GB of memory.
# Caveats: http://stackoverflow.com/questions/2288728/drawbacks-of-using-largeaddressaware-for-32-bit-windows-executables
# TODO: Remove when building 64-bit.
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /LARGEADDRESSAWARE")
# always produce symbols as PDB files
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /Zi")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /DEBUG /OPT:REF /OPT:ICF")
else ()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -fno-strict-aliasing -Wno-unused-parameter")
if (CMAKE_CXX_COMPILER_ID MATCHES "GNU")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ggdb -Woverloaded-virtual -Wdouble-promotion")
if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER "5.1") # gcc 5.1 and on have suggest-override
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wsuggest-override")
endif ()
if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS "5.3")
# GLM 0.9.8 on Ubuntu 14 (gcc 4.4) has issues with the simd declarations
add_definitions(-DGLM_FORCE_PURE)
endif()
endif ()
endif()
if (ANDROID)
# assume that the toolchain selected for android has C++11 support
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif ((NOT MSVC12) AND (NOT MSVC14))
include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if (COMPILER_SUPPORTS_CXX11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(COMPILER_SUPPORTS_CXX0X)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
message(FATAL_ERROR "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()
endif ()
if (APPLE)
set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LANGUAGE_STANDARD "c++11")
set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LIBRARY "libc++")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --stdlib=libc++")
endif ()
if (NOT ANDROID_LIB_DIR)
set(ANDROID_LIB_DIR $ENV{ANDROID_LIB_DIR})
endif ()
if (APPLE)
exec_program(sw_vers ARGS -productVersion OUTPUT_VARIABLE OSX_VERSION)
string(REGEX MATCH "^[0-9]+\\.[0-9]+" OSX_VERSION ${OSX_VERSION})
message(STATUS "Detected OS X version = ${OSX_VERSION}")
set(OSX_SDK "${OSX_VERSION}" CACHE String "OS X SDK version to look for inside Xcode bundle or at OSX_SDK_PATH")
# set our OS X deployment target
set(CMAKE_OSX_DEPLOYMENT_TARGET 10.8)
# find the SDK path for the desired SDK
find_path(
_OSX_DESIRED_SDK_PATH
NAME MacOSX${OSX_SDK}.sdk
HINTS ${OSX_SDK_PATH}
PATHS /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/
/Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/
)
if (NOT _OSX_DESIRED_SDK_PATH)
message(STATUS "Could not find OS X ${OSX_SDK} SDK. Will fall back to default. If you want a specific SDK, please pass OSX_SDK and optionally OSX_SDK_PATH to CMake.")
else ()
message(STATUS "Found OS X ${OSX_SDK} SDK at ${_OSX_DESIRED_SDK_PATH}/MacOSX${OSX_SDK}.sdk")
# set that as the SDK to use
set(CMAKE_OSX_SYSROOT ${_OSX_DESIRED_SDK_PATH}/MacOSX${OSX_SDK}.sdk)
endif ()
endif ()

View file

@ -33,7 +33,6 @@ if (WIN32)
include(SelectLibraryConfigurations)
select_library_configurations(LIBOVR)
set(${EXTERNAL_NAME_UPPER}_LIBRARIES ${${EXTERNAL_NAME_UPPER}_LIBRARIES} CACHE TYPE INTERNAL)
message("Libs ${EXTERNAL_NAME_UPPER}_LIBRARIES ${${EXTERNAL_NAME_UPPER}_LIBRARIES}")
elseif(APPLE)

View file

@ -4,14 +4,6 @@ cmake_policy(SET CMP0046 OLD)
include(ExternalProject)
if (WIN32)
# windows shell does not like backslashes expanded on the command line,
# so convert all backslashes in the QT path to forward slashes
string(REPLACE \\ / QT_CMAKE_PREFIX_PATH $ENV{QT_CMAKE_PREFIX_PATH})
elseif ($ENV{QT_CMAKE_PREFIX_PATH})
set(QT_CMAKE_PREFIX_PATH $ENV{QT_CMAKE_PREFIX_PATH})
endif ()
set(QUAZIP_CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR> -DCMAKE_PREFIX_PATH=${QT_CMAKE_PREFIX_PATH} -DCMAKE_INSTALL_NAME_DIR:PATH=<INSTALL_DIR>/lib -DZLIB_ROOT=${ZLIB_ROOT} -DCMAKE_POSITION_INDEPENDENT_CODE=ON)
if (APPLE)
@ -34,9 +26,9 @@ add_dependencies(quazip zlib)
# Hide this external target (for ide users)
set_target_properties(${EXTERNAL_NAME} PROPERTIES
FOLDER "hidden/externals"
INSTALL_NAME_DIR ${INSTALL_DIR}/lib
BUILD_WITH_INSTALL_RPATH True)
FOLDER "hidden/externals"
INSTALL_NAME_DIR ${INSTALL_DIR}/lib
BUILD_WITH_INSTALL_RPATH True)
ExternalProject_Get_Property(${EXTERNAL_NAME} INSTALL_DIR)
set(${EXTERNAL_NAME_UPPER}_INCLUDE_DIR ${INSTALL_DIR}/include CACHE PATH "List of QuaZip include directories")

43
cmake/init.cmake Normal file
View file

@ -0,0 +1,43 @@
if (WIN32)
cmake_policy(SET CMP0020 NEW)
endif (WIN32)
if (POLICY CMP0043)
cmake_policy(SET CMP0043 OLD)
endif ()
if (POLICY CMP0042)
cmake_policy(SET CMP0042 OLD)
endif ()
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
set_property(GLOBAL PROPERTY PREDEFINED_TARGETS_FOLDER "CMakeTargets")
# Hide automoc folders (for IDEs)
set(AUTOGEN_TARGETS_FOLDER "hidden/generated")
# Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)
if (CMAKE_BUILD_TYPE)
string(TOUPPER ${CMAKE_BUILD_TYPE} UPPER_CMAKE_BUILD_TYPE)
else ()
set(UPPER_CMAKE_BUILD_TYPE DEBUG)
endif ()
# CMAKE_CURRENT_SOURCE_DIR is the parent folder here
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules/")
set(HF_CMAKE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
set(MACRO_DIR "${HF_CMAKE_DIR}/macros")
set(EXTERNAL_PROJECT_DIR "${HF_CMAKE_DIR}/externals")
file(GLOB HIFI_CUSTOM_MACROS "cmake/macros/*.cmake")
foreach(CUSTOM_MACRO ${HIFI_CUSTOM_MACROS})
include(${CUSTOM_MACRO})
endforeach()
if (ANDROID)
file(GLOB ANDROID_CUSTOM_MACROS "cmake/android/*.cmake")
foreach(CUSTOM_MACRO ${ANDROID_CUSTOM_MACROS})
include(${CUSTOM_MACRO})
endforeach()
endif ()

View file

@ -133,7 +133,7 @@ macro(SET_PACKAGING_PARAMETERS)
else()
message( FATAL_ERROR "Visual Studio 2013 or higher required." )
endif()
if (NOT SIGNTOOL_EXECUTABLE)
message(FATAL_ERROR "Code signing of executables was requested but signtool.exe could not be found.")
endif ()
@ -147,6 +147,7 @@ macro(SET_PACKAGING_PARAMETERS)
set(CONSOLE_STARTUP_REG_KEY "ConsoleStartupShortcut")
set(CLIENT_LAUNCH_NOW_REG_KEY "ClientLaunchAfterInstall")
set(SERVER_LAUNCH_NOW_REG_KEY "ServerLaunchAfterInstall")
set(CUSTOM_INSTALL_REG_KEY "CustomInstall")
endif ()
# setup component categories for installer

View file

@ -9,11 +9,13 @@ macro(SETUP_HIFI_CLIENT_SERVER_PLUGIN)
set(${TARGET_NAME}_SHARED 1)
setup_hifi_library(${ARGV})
if (NOT DEFINED SERVER_ONLY)
if (BUILD_CLIENT)
add_dependencies(interface ${TARGET_NAME})
endif()
add_dependencies(assignment-client ${TARGET_NAME})
if (BUILD_SERVER)
add_dependencies(assignment-client ${TARGET_NAME})
endif()
set_target_properties(${TARGET_NAME} PROPERTIES FOLDER "Plugins")

View file

@ -8,7 +8,9 @@
macro(SETUP_HIFI_PLUGIN)
set(${TARGET_NAME}_SHARED 1)
setup_hifi_library(${ARGV})
add_dependencies(interface ${TARGET_NAME})
if (BUILD_CLIENT)
add_dependencies(interface ${TARGET_NAME})
endif()
target_link_libraries(${TARGET_NAME} ${CMAKE_THREAD_LIBS_INIT})
set_target_properties(${TARGET_NAME} PROPERTIES FOLDER "Plugins")

View file

@ -0,0 +1,84 @@
#
# Copyright 2015 High Fidelity, Inc.
# Created by Bradley Austin Davis on 2015/10/10
#
# Distributed under the Apache License, Version 2.0.
# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
#
function(set_from_env _RESULT_NAME _ENV_VAR_NAME _DEFAULT_VALUE)
if ("$ENV{${_ENV_VAR_NAME}}" STREQUAL "")
set (${_RESULT_NAME} ${_DEFAULT_VALUE} PARENT_SCOPE)
else()
set (${_RESULT_NAME} $ENV{${_ENV_VAR_NAME}} PARENT_SCOPE)
endif()
endfunction()
# Construct a default QT location from a root path, a version and an architecture
function(calculate_default_qt_dir _RESULT_NAME)
if (ANDROID)
set(QT_DEFAULT_ARCH "android_armv7")
elseif(UWP)
set(QT_DEFAULT_ARCH "winrt_x64_msvc2017")
elseif(APPLE)
set(QT_DEFAULT_ARCH "clang_64")
elseif(WIN32)
set(QT_DEFAULT_ARCH "msvc2017_64")
else()
set(QT_DEFAULT_ARCH "gcc_64")
endif()
if (WIN32)
set(QT_DEFAULT_ROOT "c:/Qt")
else()
set(QT_DEFAULT_ROOT "$ENV{HOME}/Qt")
endif()
set_from_env(QT_ROOT QT_ROOT ${QT_DEFAULT_ROOT})
set_from_env(QT_VERSION QT_VERSION "5.9.1")
set_from_env(QT_ARCH QT_ARCH ${QT_DEFAULT_ARCH})
set(${_RESULT_NAME} "${QT_ROOT}/${QT_VERSION}/${QT_ARCH}" PARENT_SCOPE)
endfunction()
# Sets the QT_CMAKE_PREFIX_PATH and QT_DIR variables
# Also enables CMAKE_AUTOMOC and CMAKE_AUTORCC
macro(setup_qt)
set(QT_CMAKE_PREFIX_PATH "$ENV{QT_CMAKE_PREFIX_PATH}")
if (("QT_CMAKE_PREFIX_PATH" STREQUAL "") OR (NOT EXISTS "${QT_CMAKE_PREFIX_PATH}"))
calculate_default_qt_dir(QT_DIR)
set(QT_CMAKE_PREFIX_PATH "${QT_DIR}/lib/cmake")
else()
# figure out where the qt dir is
get_filename_component(QT_DIR "${QT_CMAKE_PREFIX_PATH}/../../" ABSOLUTE)
endif()
if (WIN32)
# windows shell does not like backslashes expanded on the command line,
# so convert all backslashes in the QT path to forward slashes
string(REPLACE \\ / QT_CMAKE_PREFIX_PATH ${QT_CMAKE_PREFIX_PATH})
string(REPLACE \\ / QT_DIR ${QT_DIR})
endif()
# This check doesn't work on Mac
#if (NOT EXISTS "${QT_DIR}/include/QtCore/QtGlobal")
# message(FATAL_ERROR "Unable to locate Qt includes in ${QT_DIR}")
#endif()
if (NOT EXISTS "${QT_CMAKE_PREFIX_PATH}/Qt5Core/Qt5CoreConfig.cmake")
message(FATAL_ERROR "Unable to locate Qt cmake config in ${QT_CMAKE_PREFIX_PATH}")
endif()
message(STATUS "The Qt build in use is: \"${QT_DIR}\"")
# Instruct CMake to run moc automatically when needed.
set(CMAKE_AUTOMOC ON)
# Instruct CMake to run rcc automatically when needed
set(CMAKE_AUTORCC ON)
if (WIN32)
add_paths_to_fixup_libs("${QT_DIR}/bin")
endif ()
endmacro()

View file

@ -34,26 +34,11 @@ if (UNIX)
endif ()
if (WIN32)
file(TO_CMAKE_PATH "$ENV{PROGRAMFILES}" _programfiles)
if ("${CMAKE_SIZEOF_VOID_P}" EQUAL "8")
# http://www.slproweb.com/products/Win32OpenSSL.html
set(_OPENSSL_ROOT_HINTS ${OPENSSL_ROOT_DIR} $ENV{OPENSSL_ROOT_DIR} $ENV{HIFI_LIB_DIR}/openssl
"[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OpenSSL (64-bit)_is1;Inno Setup: App Path]"
)
set(_OPENSSL_ROOT_PATHS "${_programfiles}/OpenSSL" "${_programfiles}/OpenSSL-Win64" "C:/OpenSSL/" "C:/OpenSSL-Win64/")
if (("${CMAKE_SIZEOF_VOID_P}" EQUAL "8"))
set(_OPENSSL_ROOT_HINTS_AND_PATHS $ENV{VCPKG_ROOT}/installed/x64-windows)
else()
# http://www.slproweb.com/products/Win32OpenSSL.html
set(_OPENSSL_ROOT_HINTS ${OPENSSL_ROOT_DIR} $ENV{OPENSSL_ROOT_DIR} $ENV{HIFI_LIB_DIR}/openssl
"[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OpenSSL (32-bit)_is1;Inno Setup: App Path]"
)
set(_OPENSSL_ROOT_PATHS "${_programfiles}/OpenSSL" "${_programfiles}/OpenSSL-Win32" "C:/OpenSSL/" "C:/OpenSSL-Win32/")
set(_OPENSSL_ROOT_HINTS_AND_PATHS $ENV{VCPKG_ROOT}/installed/x86-windows)
endif()
unset(_programfiles)
set(_OPENSSL_ROOT_HINTS_AND_PATHS HINTS ${_OPENSSL_ROOT_HINTS} PATHS ${_OPENSSL_ROOT_PATHS})
else ()
include("${MACRO_DIR}/HifiLibrarySearchHints.cmake")
hifi_library_search_hints("openssl")
@ -67,47 +52,14 @@ find_path(OPENSSL_INCLUDE_DIR NAMES openssl/ssl.h HINTS ${_OPENSSL_ROOT_HINTS_AN
if (WIN32 AND NOT CYGWIN)
if (MSVC)
# In Visual C++ naming convention each of these four kinds of Windows libraries has it's standard suffix:
# * MD for dynamic-release
# * MDd for dynamic-debug
# * MT for static-release
# * MTd for static-debug
# Implementation details:
# We are using the libraries located in the VC subdir instead of the parent directory eventhough :
# libeay32MD.lib is identical to ../libeay32.lib, and
# ssleay32MD.lib is identical to ../ssleay32.lib
# The Kitware FindOpenSSL module has been modified here by High Fidelity to look specifically for static libraries
find_library(LIB_EAY_DEBUG NAMES libeay32MTd
${_OPENSSL_ROOT_HINTS_AND_PATHS} PATH_SUFFIXES "lib/VC/static"
)
find_library(LIB_EAY_RELEASE NAMES libeay32MT
${_OPENSSL_ROOT_HINTS_AND_PATHS} PATH_SUFFIXES "lib/VC/static"
)
find_library(SSL_EAY_DEBUG NAMES ssleay32MTd
${_OPENSSL_ROOT_HINTS_AND_PATHS} PATH_SUFFIXES "lib/VC/static"
)
find_library(SSL_EAY_RELEASE NAMES ssleay32MT
${_OPENSSL_ROOT_HINTS_AND_PATHS} PATH_SUFFIXES "lib/VC/static"
)
set(LIB_EAY_LIBRARY_DEBUG "${LIB_EAY_DEBUG}")
set(LIB_EAY_LIBRARY_RELEASE "${LIB_EAY_RELEASE}")
set(SSL_EAY_LIBRARY_DEBUG "${SSL_EAY_DEBUG}")
set(SSL_EAY_LIBRARY_RELEASE "${SSL_EAY_RELEASE}")
# Using vcpkg builds of openssl
find_library(LIB_EAY_LIBRARY_RELEASE NAMES libeay32 HINTS ${_OPENSSL_ROOT_HINTS_AND_PATHS} PATH_SUFFIXES "lib")
find_library(SSL_EAY_LIBRARY_RELEASE NAMES ssleay32 HINTS ${_OPENSSL_ROOT_HINTS_AND_PATHS} PATH_SUFFIXES "lib")
include(SelectLibraryConfigurations)
select_library_configurations(LIB_EAY)
select_library_configurations(SSL_EAY)
set(OPENSSL_LIBRARIES ${SSL_EAY_LIBRARY} ${LIB_EAY_LIBRARY})
find_path(OPENSSL_DLL_PATH NAMES ssleay32.dll PATH_SUFFIXES "bin" ${_OPENSSL_ROOT_HINTS_AND_PATHS})
endif()
else()

View file

@ -40,6 +40,7 @@ set(CONSOLE_DESKTOP_SHORTCUT_REG_KEY "@CONSOLE_DESKTOP_SHORTCUT_REG_KEY@")
set(CONSOLE_STARTUP_REG_KEY "@CONSOLE_STARTUP_REG_KEY@")
set(SERVER_LAUNCH_NOW_REG_KEY "@SERVER_LAUNCH_NOW_REG_KEY@")
set(CLIENT_LAUNCH_NOW_REG_KEY "@CLIENT_LAUNCH_NOW_REG_KEY@")
set(CUSTOM_INSTALL_REG_KEY "@CUSTOM_INSTALL_REG_KEY@")
set(INSTALLER_HEADER_IMAGE "@INSTALLER_HEADER_IMAGE@")
set(UNINSTALLER_HEADER_IMAGE "@UNINSTALLER_HEADER_IMAGE@")
set(ADD_REMOVE_ICON_PATH "@ADD_REMOVE_ICON_PATH@")

View file

@ -49,7 +49,7 @@
Var STR_CONTAINS_VAR_3
Var STR_CONTAINS_VAR_4
Var STR_RETURN_VAR
Function StrContains
Exch $STR_NEEDLE
Exch 1
@ -343,29 +343,29 @@ SectionEnd
;--------------------------------
;Pages
!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_LICENSE "@CPACK_RESOURCE_FILE_LICENSE@"
Page custom InstallTypesPage ReadInstallTypes
!define MUI_PAGE_CUSTOMFUNCTION_PRE AbortFunction
!insertmacro MUI_PAGE_DIRECTORY
;Start Menu Folder Page Configuration
!define MUI_STARTMENUPAGE_REGISTRY_ROOT "HKLM"
!define MUI_STARTMENUPAGE_REGISTRY_KEY "Software\@CPACK_PACKAGE_VENDOR@\@CPACK_PACKAGE_INSTALL_REGISTRY_KEY@"
!define MUI_STARTMENUPAGE_REGISTRY_VALUENAME "Start Menu Folder"
!define MUI_PAGE_CUSTOMFUNCTION_PRE AbortFunction
!insertmacro MUI_PAGE_STARTMENU Application $STARTMENU_FOLDER
!define MUI_PAGE_CUSTOMFUNCTION_PRE AbortFunction
@CPACK_NSIS_PAGE_COMPONENTS@
Page custom PostInstallOptionsPage ReadPostInstallOptions
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES
@ -453,9 +453,10 @@ Var ExpressInstallRadioButton
Var CustomInstallRadioButton
Var InstallTypeDialog
Var Express
Var CustomInstallTemporaryState
!macro SetPostInstallOption Checkbox OptionName Default
; reads the value for the given post install option to the registry
!macro SetInstallOption Checkbox OptionName Default
; reads the value for the given install option to the registry
ReadRegStr $0 HKLM "@REGISTRY_HKLM_INSTALL_ROOT@\@CPACK_PACKAGE_INSTALL_REGISTRY_KEY@\@POST_INSTALL_OPTIONS_REG_GROUP@" "${OptionName}"
${If} $0 == "NO"
@ -472,31 +473,39 @@ Var Express
Function InstallTypesPage
!insertmacro MUI_HEADER_TEXT "Choose Installation Type" "Express or Custom Install"
nsDialogs::Create 1018
Pop $InstallTypeDialog
${If} $InstallTypeDialog == error
Abort
${EndIf}
StrCpy $CurrentOffset 0
StrCpy $OffsetUnits u
StrCpy $Express "0"
StrCpy $Express "0"
${NSD_CreateRadioButton} 30% $CurrentOffset$OffsetUnits 100% 10u "Express Install (Recommended)"; $\nInstalls High Fidelity Interface and High Fidelity Sandbox"
pop $ExpressInstallRadioButton
${NSD_OnClick} $ExpressInstallRadioButton ChangeExpressLabel
IntOp $CurrentOffset $CurrentOffset + 15
${NSD_CreateRadiobutton} 30% $CurrentOffset$OffsetUnits 100% 10u "Custom Install (Advanced)"
pop $CustomInstallRadioButton
${NSD_OnClick} $CustomInstallRadioButton ChangeCustomLabel
; Express Install selected by default
${NSD_Check} $ExpressInstallRadioButton
${NSD_OnClick} $CustomInstallRadioButton ChangeCustomLabel
; check install type from the registry, express install by default
!insertmacro SetInstallOption $CustomInstallRadioButton @CUSTOM_INSTALL_REG_KEY@ ${BST_UNCHECKED}
; set the express install value based on the custom install value from registry
${NSD_GetState} $CustomInstallRadioButton $CustomInstallTemporaryState
${If} $CustomInstallTemporaryState == ${BST_UNCHECKED}
${NSD_Check} $ExpressInstallRadioButton
${EndIf}
Call ChangeExpressLabel
nsDialogs::Show
FunctionEnd
@ -519,18 +528,18 @@ Function AbortFunction
StrCmp $Express "1" 0 end
Abort
end:
FunctionEnd
FunctionEnd
Function PostInstallOptionsPage
!insertmacro MUI_HEADER_TEXT "Setup Options" ""
nsDialogs::Create 1018
Pop $PostInstallDialog
${If} $PostInstallDialog == error
Abort
${EndIf}
; Check if Express is set, if so, abort the post install options page
StrCmp $Express "1" 0 end
Abort
@ -543,18 +552,18 @@ Function PostInstallOptionsPage
${NSD_CreateCheckbox} 0 $CurrentOffset$OffsetUnits 100% 10u "&Create a desktop shortcut for @INTERFACE_HF_SHORTCUT_NAME@"
Pop $DesktopClientCheckbox
IntOp $CurrentOffset $CurrentOffset + 15
; set the checkbox state depending on what is present in the registry
!insertmacro SetPostInstallOption $DesktopClientCheckbox @CLIENT_DESKTOP_SHORTCUT_REG_KEY@ ${BST_CHECKED}
!insertmacro SetInstallOption $DesktopClientCheckbox @CLIENT_DESKTOP_SHORTCUT_REG_KEY@ ${BST_CHECKED}
${EndIf}
${If} ${SectionIsSelected} ${@SERVER_COMPONENT_NAME@}
${NSD_CreateCheckbox} 0 $CurrentOffset$OffsetUnits 100% 10u "&Create a desktop shortcut for @CONSOLE_HF_SHORTCUT_NAME@"
Pop $DesktopServerCheckbox
IntOp $CurrentOffset $CurrentOffset + 15
; set the checkbox state depending on what is present in the registry
!insertmacro SetPostInstallOption $DesktopServerCheckbox @CONSOLE_DESKTOP_SHORTCUT_REG_KEY@ ${BST_UNCHECKED}
!insertmacro SetInstallOption $DesktopServerCheckbox @CONSOLE_DESKTOP_SHORTCUT_REG_KEY@ ${BST_UNCHECKED}
${EndIf}
${If} ${SectionIsSelected} ${@SERVER_COMPONENT_NAME@}
@ -562,7 +571,7 @@ Function PostInstallOptionsPage
Pop $LaunchServerNowCheckbox
; set the checkbox state depending on what is present in the registry
!insertmacro SetPostInstallOption $LaunchServerNowCheckbox @SERVER_LAUNCH_NOW_REG_KEY@ ${BST_CHECKED}
!insertmacro SetInstallOption $LaunchServerNowCheckbox @SERVER_LAUNCH_NOW_REG_KEY@ ${BST_CHECKED}
${StrContains} $substringResult "/forceNoLaunchServer" $CMDLINE
${IfNot} $substringResult == ""
${NSD_SetState} $LaunchServerNowCheckbox ${BST_UNCHECKED}
@ -570,29 +579,29 @@ Function PostInstallOptionsPage
IntOp $CurrentOffset $CurrentOffset + 15
${EndIf}
${If} ${SectionIsSelected} ${@CLIENT_COMPONENT_NAME@}
${NSD_CreateCheckbox} 0 $CurrentOffset$OffsetUnits 100% 10u "&Launch @INTERFACE_HF_SHORTCUT_NAME@ after install"
Pop $LaunchClientNowCheckbox
IntOp $CurrentOffset $CurrentOffset + 30
; set the checkbox state depending on what is present in the registry
!insertmacro SetPostInstallOption $LaunchClientNowCheckbox @CLIENT_LAUNCH_NOW_REG_KEY@ ${BST_CHECKED}
!insertmacro SetInstallOption $LaunchClientNowCheckbox @CLIENT_LAUNCH_NOW_REG_KEY@ ${BST_CHECKED}
${StrContains} $substringResult "/forceNoLaunchClient" $CMDLINE
${IfNot} $substringResult == ""
${NSD_SetState} $LaunchClientNowCheckbox ${BST_UNCHECKED}
${EndIf}
${EndIf}
${If} ${SectionIsSelected} ${@SERVER_COMPONENT_NAME@}
${NSD_CreateCheckbox} 0 $CurrentOffset$OffsetUnits 100% 10u "&Launch @CONSOLE_HF_SHORTCUT_NAME@ on startup"
Pop $ServerStartupCheckbox
IntOp $CurrentOffset $CurrentOffset + 15
; set the checkbox state depending on what is present in the registry
!insertmacro SetPostInstallOption $ServerStartupCheckbox @CONSOLE_STARTUP_REG_KEY@ ${BST_CHECKED}
!insertmacro SetInstallOption $ServerStartupCheckbox @CONSOLE_STARTUP_REG_KEY@ ${BST_CHECKED}
${EndIf}
${If} ${SectionIsSelected} ${@CLIENT_COMPONENT_NAME@}
${NSD_CreateCheckbox} 0 $CurrentOffset$OffsetUnits 100% 10u "&Perform a clean install (Delete older settings and content)"
Pop $CleanInstallCheckbox
@ -618,12 +627,12 @@ Function PostInstallOptionsPage
${NSD_SetState} $CopyFromProductionCheckbox ${BST_UNCHECKED}
${EndIf}
nsDialogs::Show
FunctionEnd
!macro WritePostInstallOption OptionName Option
; writes the value for the given post install option to the registry
!macro WriteInstallOption OptionName Option
; writes the value for the given install option to the registry
WriteRegStr HKLM "@REGISTRY_HKLM_INSTALL_ROOT@\@CPACK_PACKAGE_INSTALL_REGISTRY_KEY@\@POST_INSTALL_OPTIONS_REG_GROUP@" "${OptionName}" ${Option}
!macroend
@ -641,12 +650,12 @@ Function ReadInstallTypes
; check if the user asked for express/custom install
${NSD_GetState} $ExpressInstallRadioButton $ExpressInstallState
${NSD_GetState} $CustomInstallRadioButton $CustomInstallState
${If} $ExpressInstallState == ${BST_CHECKED}
StrCpy $Express "1"
StrCpy $DesktopClientState ${BST_CHECKED}
StrCpy $ServerStartupState ${BST_CHECKED}
StrCpy $DesktopClientState ${BST_CHECKED}
StrCpy $ServerStartupState ${BST_CHECKED}
StrCpy $LaunchServerNowState ${BST_CHECKED}
StrCpy $LaunchClientNowState ${BST_CHECKED}
StrCpy $CleanInstallState ${BST_UNCHECKED}
@ -655,9 +664,12 @@ Function ReadInstallTypes
${If} @PR_BUILD@ == 1
StrCpy $CopyFromProductionState ${BST_UNCHECKED}
${EndIf}
!insertmacro WriteInstallOption "@CUSTOM_INSTALL_REG_KEY@" NO
${Else}
!insertmacro WriteInstallOption "@CUSTOM_INSTALL_REG_KEY@" YES
${EndIf}
FunctionEnd
Function ReadPostInstallOptions
@ -683,12 +695,12 @@ Function ReadPostInstallOptions
; check if we need to launch the server post-install
${NSD_GetState} $LaunchServerNowCheckbox $LaunchServerNowState
${EndIf}
${If} ${SectionIsSelected} ${@CLIENT_COMPONENT_NAME@}
; check if we need to launch the client post-install
${NSD_GetState} $LaunchClientNowCheckbox $LaunchClientNowState
${EndIf}
${If} ${SectionIsSelected} ${@CLIENT_COMPONENT_NAME@}
; check if the user asked for a clean install
${NSD_GetState} $CleanInstallCheckbox $CleanInstallState
@ -700,9 +712,9 @@ Function HandlePostInstallOptions
; check if the user asked for a desktop shortcut to High Fidelity
${If} $DesktopClientState == ${BST_CHECKED}
CreateShortCut "$DESKTOP\@INTERFACE_HF_SHORTCUT_NAME@.lnk" "$INSTDIR\@INTERFACE_WIN_EXEC_NAME@"
!insertmacro WritePostInstallOption "@CLIENT_DESKTOP_SHORTCUT_REG_KEY@" YES
!insertmacro WriteInstallOption "@CLIENT_DESKTOP_SHORTCUT_REG_KEY@" YES
${Else}
!insertmacro WritePostInstallOption @CLIENT_DESKTOP_SHORTCUT_REG_KEY@ NO
!insertmacro WriteInstallOption @CLIENT_DESKTOP_SHORTCUT_REG_KEY@ NO
${EndIf}
${EndIf}
@ -711,12 +723,12 @@ Function HandlePostInstallOptions
; check if the user asked for a desktop shortcut to Sandbox
${If} $DesktopServerState == ${BST_CHECKED}
CreateShortCut "$DESKTOP\@CONSOLE_HF_SHORTCUT_NAME@.lnk" "$INSTDIR\@CONSOLE_INSTALL_SUBDIR@\@CONSOLE_WIN_EXEC_NAME@"
!insertmacro WritePostInstallOption @CONSOLE_DESKTOP_SHORTCUT_REG_KEY@ YES
!insertmacro WriteInstallOption @CONSOLE_DESKTOP_SHORTCUT_REG_KEY@ YES
${Else}
!insertmacro WritePostInstallOption @CONSOLE_DESKTOP_SHORTCUT_REG_KEY@ NO
!insertmacro WriteInstallOption @CONSOLE_DESKTOP_SHORTCUT_REG_KEY@ NO
${EndIf}
; check if the user asked to have Sandbox launched every startup
${If} $ServerStartupState == ${BST_CHECKED}
; in case we added a shortcut in the global context, pull that now
@ -730,12 +742,12 @@ Function HandlePostInstallOptions
; reset the shell var context back
SetShellVarContext all
!insertmacro WritePostInstallOption @CONSOLE_STARTUP_REG_KEY@ YES
!insertmacro WriteInstallOption @CONSOLE_STARTUP_REG_KEY@ YES
${Else}
!insertmacro WritePostInstallOption @CONSOLE_STARTUP_REG_KEY@ NO
!insertmacro WriteInstallOption @CONSOLE_STARTUP_REG_KEY@ NO
${EndIf}
${EndIf}
${If} ${SectionIsSelected} ${@CLIENT_COMPONENT_NAME@}
; check if the user asked for a clean install
${If} $CleanInstallState == ${BST_CHECKED}
@ -774,28 +786,28 @@ Function HandlePostInstallOptions
${EndIf}
${If} $LaunchServerNowState == ${BST_CHECKED}
!insertmacro WritePostInstallOption @SERVER_LAUNCH_NOW_REG_KEY@ YES
!insertmacro WriteInstallOption @SERVER_LAUNCH_NOW_REG_KEY@ YES
; both launches use the explorer trick in case the user has elevated permissions for the installer
${If} $LaunchClientNowState == ${BST_CHECKED}
!insertmacro WritePostInstallOption @CLIENT_LAUNCH_NOW_REG_KEY@ YES
!insertmacro WriteInstallOption @CLIENT_LAUNCH_NOW_REG_KEY@ YES
; create shortcut with ARGUMENTS
CreateShortCut "$TEMP\SandboxShortcut.lnk" "$INSTDIR\@CONSOLE_INSTALL_SUBDIR@\@CONSOLE_WIN_EXEC_NAME@" "-- --launchInterface"
Exec '"$WINDIR\explorer.exe" "$TEMP\SandboxShortcut.lnk"'
${Else}
!insertmacro WritePostInstallOption @CLIENT_LAUNCH_NOW_REG_KEY@ NO
!insertmacro WriteInstallOption @CLIENT_LAUNCH_NOW_REG_KEY@ NO
Exec '"$WINDIR\explorer.exe" "$INSTDIR\@CONSOLE_INSTALL_SUBDIR@\@CONSOLE_WIN_EXEC_NAME@"'
${EndIf}
${Else}
!insertmacro WritePostInstallOption @SERVER_LAUNCH_NOW_REG_KEY@ NO
!insertmacro WriteInstallOption @SERVER_LAUNCH_NOW_REG_KEY@ NO
; launch uses the explorer trick in case the user has elevated permissions for the installer
${If} $LaunchClientNowState == ${BST_CHECKED}
!insertmacro WritePostInstallOption @CLIENT_LAUNCH_NOW_REG_KEY@ YES
!insertmacro WriteInstallOption @CLIENT_LAUNCH_NOW_REG_KEY@ YES
Exec '"$WINDIR\explorer.exe" "$INSTDIR\@INTERFACE_WIN_EXEC_NAME@"'
${Else}
!insertmacro WritePostInstallOption @CLIENT_LAUNCH_NOW_REG_KEY@ NO
!insertmacro WriteInstallOption @CLIENT_LAUNCH_NOW_REG_KEY@ NO
${EndIf}
${EndIf}
@ -843,7 +855,7 @@ Section "-Core installation"
Rename "$INSTDIR\resources\qml\styles-uit\RalewaySemibold.qml" "$INSTDIR\resources\qml\styles-uit\RalewaySemiBold.qml"
ExecWait "$INSTDIR\vcredist_x64.exe /install /q /norestart"
; Remove the Old Interface directory and vcredist_x64.exe (from installs prior to Server Console)
RMDir /r "$INSTDIR\Interface"
Delete "$INSTDIR\vcredist_x64.exe"
@ -943,9 +955,9 @@ Section "-Core installation"
Call ConditionalAddToRegisty
!insertmacro MUI_STARTMENU_WRITE_END
@CPACK_NSIS_EXTRA_INSTALL_COMMANDS@
; Handle whichever post install options were set
Call HandlePostInstallOptions
@ -963,9 +975,18 @@ SectionEnd
${If} $R0 == 0
; the process is running, ask the user to close it
${If} "${displayName}" == "@CONSOLE_DISPLAY_NAME@"
MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION \
"${displayName} cannot be ${action} while ${displayName} is running.$\r$\nPlease close it and click Retry to continue." \
"${displayName} cannot be ${action} while ${displayName} is running.$\r$\nPlease close it in the system tray and click Retry to continue." \
/SD IDCANCEL IDRETRY Prompt_${UniqueID} IDCANCEL 0
${EndIf}
${If} "${displayName}" == "@INTERFACE_DISPLAY_NAME@"
MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION \
"${displayName} cannot be ${action} while ${displayName} is running.$\r$\nPlease close it in the task bar and click Retry to continue." \
/SD IDCANCEL IDRETRY Prompt_${UniqueID} IDCANCEL 0
${EndIf}
; If the user decided to cancel, stop the current installer/uninstaller
Abort

View file

@ -752,8 +752,28 @@ void DomainServer::setupICEHeartbeatForFullNetworking() {
}
void DomainServer::updateICEServerAddresses() {
if (_iceAddressLookupID == -1) {
if (_iceAddressLookupID == INVALID_ICE_LOOKUP_ID) {
_iceAddressLookupID = QHostInfo::lookupHost(_iceServerAddr, this, SLOT(handleICEHostInfo(QHostInfo)));
// there seems to be a 5.9 bug where lookupHost never calls our slot
// so we add a single shot manual "timeout" to fire it off again if it hasn't called back yet
static const int ICE_ADDRESS_LOOKUP_TIMEOUT_MS = 5000;
QTimer::singleShot(ICE_ADDRESS_LOOKUP_TIMEOUT_MS, this, &DomainServer::timeoutICEAddressLookup);
}
}
void DomainServer::timeoutICEAddressLookup() {
if (_iceAddressLookupID != INVALID_ICE_LOOKUP_ID) {
// we waited 5s and didn't hear back for our ICE DNS lookup
// so time that one out and kick off another
qDebug() << "IP address lookup timed out for" << _iceServerAddr << "- retrying";
QHostInfo::abortHostLookup(_iceAddressLookupID);
_iceAddressLookupID = INVALID_ICE_LOOKUP_ID;
updateICEServerAddresses();
}
}

View file

@ -39,6 +39,8 @@ typedef QMultiHash<QUuid, WalletTransaction*> TransactionHash;
using Subnet = QPair<QHostAddress, int>;
using SubnetList = std::vector<Subnet>;
const int INVALID_ICE_LOOKUP_ID = -1;
enum ReplicationServerDirection {
Upstream,
Downstream
@ -114,6 +116,8 @@ private slots:
void tokenGrantFinished();
void profileRequestFinished();
void timeoutICEAddressLookup();
signals:
void iceServerChanged();
void userConnected();
@ -223,7 +227,7 @@ private:
QList<QHostAddress> _iceServerAddresses;
QSet<QHostAddress> _failedIceServerAddresses;
int _iceAddressLookupID { -1 };
int _iceAddressLookupID { INVALID_ICE_LOOKUP_ID };
int _noReplyICEHeartbeats { 0 };
int _numHeartbeatDenials { 0 };
bool _connectedToICEServer { false };

View file

@ -0,0 +1,112 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="225pt"
height="225pt"
viewBox="0 0 79.374998 79.374998"
version="1.1"
id="svg8"
inkscape:version="0.92.2 (5c3e80d, 2017-08-06)"
sodipodi:docname="clap-a.svg">
<defs
id="defs2" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="2.8"
inkscape:cx="240.0566"
inkscape:cy="147.59313"
inkscape:document-units="mm"
inkscape:current-layer="g3790"
showgrid="false"
inkscape:window-width="2560"
inkscape:window-height="1377"
inkscape:window-x="1912"
inkscape:window-y="-8"
inkscape:window-maximized="1"
inkscape:pagecheckerboard="true"
units="pt" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-217.62501)">
<g
id="g3790"
transform="translate(-276.67857,-1.5119048)"
style="fill:#000000">
<path
sodipodi:nodetypes="ccscccsccscssscscsscsccc"
inkscape:connector-curvature="0"
id="path3764"
d="m 287.04656,288.04665 23.71378,9.0592 c 0,0 0.39967,-4.79605 4.5296,-6.92762 4.12992,-2.13158 7.40168,-15.99614 7.40168,-15.99614 l 2.5266,-9.92668 4.1934,-9.24819 c 0,0 -1.13082,-3.82467 -4.67519,-0.19524 -8.8408,9.05294 -3.51813,14.25651 -8.14833,14.16202 -3.77977,-0.75596 -0.13245,-10.86933 0.26722,-16.16497 0.26644,-3.06413 0.69941,-12.98928 0.29974,-18.85112 -0.39966,-5.86184 -0.93256,-6.66118 -2.66446,-6.52795 -1.73191,0.13322 -2.93093,0.93257 -4.39638,9.05919 -1.46546,8.12664 -3.33058,15.72038 -3.06414,18.91774 0.26644,3.19737 -4.36307,0.64443 -2.89762,-5.48385 1.46546,-6.12827 4.82299,-19.49577 4.95621,-21.36089 0.13322,-1.86512 -0.52548,-5.99423 -3.45641,-1.46464 -2.93091,4.52961 -8.39307,31.77464 -8.39307,31.77464 0,0 -4.61911,1.35544 4.75249,-29.62183 0.37058,-1.22492 -1.2231,-1.82036 -2.02245,-0.35491 -0.79933,1.46547 -2.93556,6.41177 -3.60169,9.47592 -0.66612,3.06413 -4.12526,18.76747 -5.99039,20.76582 -1.86514,1.99836 -0.77914,-1.64516 2.43172,-19.62594 -3.46015,-8.7099 -7.6029,16.6051 -8.29355,25.75422 -1.73191,11.05755 2.66446,14.65459 2.53124,22.78122 z"
style="fill:#000000;stroke:#000000;stroke-width:0.09325644px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
<path
sodipodi:nodetypes="ccscsssccccccssc"
inkscape:connector-curvature="0"
id="path3766"
d="m 326.28601,276.79194 4.85752,2.59518 c 0,0 5.99506,0.26645 7.86018,1.19902 1.86513,0.93256 14.52136,-19.31742 14.52136,-19.31742 0,0 -1.59867,-0.39967 -3.19735,-5.32893 -1.59868,-4.92926 -7.59374,-19.98353 -9.45888,-23.44734 -1.86513,-3.46381 -2.53124,-4.66283 -3.4638,-7.46051 -0.93257,-2.7977 -2.13159,-5.0625 -3.73027,-0.13323 -1.59868,4.92927 -1.66343,10.45537 -0.46441,13.91919 1.38613,5.18454 3.8952,15.07683 1.97631,17.7369 -3.13067,-0.0635 -4.1718,-8.94257 -4.84078,-11.98701 l -10.45574,-8.48036 -1.15458,18.13553 c 0,0 3.30736,-4.0697 9.65298,-5.19422 4.51067,-0.79933 2.81751,6.4678 1.21188,14.09965 -1.34794,6.40707 -3.31442,13.66355 -3.31442,13.66355 z"
style="fill:#000000;stroke:#000000;stroke-width:0.09325644px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
<path
sodipodi:nodetypes="cccc"
inkscape:connector-curvature="0"
id="path3768"
d="m 291.74698,236.36722 c 0,0 -1.36535,-0.56172 -0.0701,-3.22296 1.29528,-2.66125 3.72103,-1.62503 4.12138,-1.41306 -1.04349,0.50764 -3.37926,4.82292 -4.05132,4.63602 z"
style="fill:#000000;stroke:#000000;stroke-width:0.09325644px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
<path
inkscape:connector-curvature="0"
id="path3770"
d="m 278.60514,277.01718 c 0,0 -0.98806,-8.05217 1.36702,-17.09567 5.11868,-12.29479 -7.76345,3.61446 -1.36702,17.09567 z"
style="fill:#000000;stroke:#000000;stroke-width:0.09325644px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
sodipodi:nodetypes="ccc" />
<path
inkscape:connector-curvature="0"
id="path3772"
d="m 283.64252,261.72126 c 0,-0.0431 -1.44898,3.96362 -0.80247,9.53246 0.42679,3.67631 0.64575,8.36037 1.90705,11.72782 3.10143,7.14376 -8.41694,-7.43352 -1.10458,-21.26028 z"
style="fill:#000000;stroke:#000000;stroke-width:0.11350404px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
sodipodi:nodetypes="cscc" />
<path
inkscape:connector-curvature="0"
id="path3774"
d="m 318.12446,294.21149 c 0,0 6.68844,-4.71017 9.13772,-13.37686 -5.91279,4.63412 -6.77642,9.57974 -9.13772,13.37686 z"
style="fill:#000000;stroke:#000000;stroke-width:0.09325644px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
sodipodi:nodetypes="ccc" />
<path
inkscape:connector-curvature="0"
id="path3778"
d="m 344.21877,231.00112 c 0,0 1.60041,9.36884 7.07841,21.7522 5.35526,12.10587 4.05178,-4.80879 -7.07841,-21.7522 z"
style="fill:#000000;stroke:#000000;stroke-width:0.09325644px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
sodipodi:nodetypes="csc" />
<path
inkscape:connector-curvature="0"
id="path3780"
d="m 349.44951,230.90023 c -0.11119,-0.0477 0.96041,8.99393 4.75948,15.37263 1.48524,4.17497 3.73499,-6.08181 -4.75948,-15.37263 z"
style="fill:#000000;stroke:#000000;stroke-width:0.09325644px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
sodipodi:nodetypes="ccc" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 6.3 KiB

View file

@ -0,0 +1,112 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="225pt"
height="225pt"
viewBox="0 0 79.374998 79.374998"
version="1.1"
id="svg8"
inkscape:version="0.92.2 (5c3e80d, 2017-08-06)"
sodipodi:docname="clap-i.svg">
<defs
id="defs2" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="2.8"
inkscape:cx="240.0566"
inkscape:cy="147.59313"
inkscape:document-units="mm"
inkscape:current-layer="g3790"
showgrid="false"
inkscape:window-width="2560"
inkscape:window-height="1377"
inkscape:window-x="1912"
inkscape:window-y="-8"
inkscape:window-maximized="1"
inkscape:pagecheckerboard="true"
units="pt" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-217.62501)">
<g
id="g3790"
transform="translate(-276.67857,-1.5119048)"
style="fill:#000000">
<path
sodipodi:nodetypes="ccscccsccscssscscsscsccc"
inkscape:connector-curvature="0"
id="path3764"
d="m 287.04656,288.04665 23.71378,9.0592 c 0,0 0.39967,-4.79605 4.5296,-6.92762 4.12992,-2.13158 7.40168,-15.99614 7.40168,-15.99614 l 2.5266,-9.92668 4.1934,-9.24819 c 0,0 -1.13082,-3.82467 -4.67519,-0.19524 -8.8408,9.05294 -3.51813,14.25651 -8.14833,14.16202 -3.77977,-0.75596 -0.13245,-10.86933 0.26722,-16.16497 0.26644,-3.06413 0.69941,-12.98928 0.29974,-18.85112 -0.39966,-5.86184 -0.93256,-6.66118 -2.66446,-6.52795 -1.73191,0.13322 -2.93093,0.93257 -4.39638,9.05919 -1.46546,8.12664 -3.33058,15.72038 -3.06414,18.91774 0.26644,3.19737 -4.36307,0.64443 -2.89762,-5.48385 1.46546,-6.12827 4.82299,-19.49577 4.95621,-21.36089 0.13322,-1.86512 -0.52548,-5.99423 -3.45641,-1.46464 -2.93091,4.52961 -8.39307,31.77464 -8.39307,31.77464 0,0 -4.61911,1.35544 4.75249,-29.62183 0.37058,-1.22492 -1.2231,-1.82036 -2.02245,-0.35491 -0.79933,1.46547 -2.93556,6.41177 -3.60169,9.47592 -0.66612,3.06413 -4.12526,18.76747 -5.99039,20.76582 -1.86514,1.99836 -0.77914,-1.64516 2.43172,-19.62594 -3.46015,-8.7099 -7.6029,16.6051 -8.29355,25.75422 -1.73191,11.05755 2.66446,14.65459 2.53124,22.78122 z"
style="fill:#ffffff;stroke:#000000;stroke-width:0.09325644px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
<path
sodipodi:nodetypes="ccscsssccccccssc"
inkscape:connector-curvature="0"
id="path3766"
d="m 326.28601,276.79194 4.85752,2.59518 c 0,0 5.99506,0.26645 7.86018,1.19902 1.86513,0.93256 14.52136,-19.31742 14.52136,-19.31742 0,0 -1.59867,-0.39967 -3.19735,-5.32893 -1.59868,-4.92926 -7.59374,-19.98353 -9.45888,-23.44734 -1.86513,-3.46381 -2.53124,-4.66283 -3.4638,-7.46051 -0.93257,-2.7977 -2.13159,-5.0625 -3.73027,-0.13323 -1.59868,4.92927 -1.66343,10.45537 -0.46441,13.91919 1.38613,5.18454 3.8952,15.07683 1.97631,17.7369 -3.13067,-0.0635 -4.1718,-8.94257 -4.84078,-11.98701 l -10.45574,-8.48036 -1.15458,18.13553 c 0,0 3.30736,-4.0697 9.65298,-5.19422 4.51067,-0.79933 2.81751,6.4678 1.21188,14.09965 -1.34794,6.40707 -3.31442,13.66355 -3.31442,13.66355 z"
style="fill:#ffffff;stroke:#000000;stroke-width:0.09325644px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
<path
sodipodi:nodetypes="cccc"
inkscape:connector-curvature="0"
id="path3768"
d="m 291.74698,236.36722 c 0,0 -1.36535,-0.56172 -0.0701,-3.22296 1.29528,-2.66125 3.72103,-1.62503 4.12138,-1.41306 -1.04349,0.50764 -3.37926,4.82292 -4.05132,4.63602 z"
style="fill:#ffffff;stroke:#000000;stroke-width:0.09325644px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
<path
inkscape:connector-curvature="0"
id="path3770"
d="m 278.60514,277.01718 c 0,0 -0.98806,-8.05217 1.36702,-17.09567 5.11868,-12.29479 -7.76345,3.61446 -1.36702,17.09567 z"
style="fill:#ffffff;stroke:#000000;stroke-width:0.09325644px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
sodipodi:nodetypes="ccc" />
<path
inkscape:connector-curvature="0"
id="path3772"
d="m 283.64252,261.72126 c 0,-0.0431 -1.44898,3.96362 -0.80247,9.53246 0.42679,3.67631 0.64575,8.36037 1.90705,11.72782 3.10143,7.14376 -8.41694,-7.43352 -1.10458,-21.26028 z"
style="fill:#ffffff;stroke:#000000;stroke-width:0.11350404px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
sodipodi:nodetypes="cscc" />
<path
inkscape:connector-curvature="0"
id="path3774"
d="m 318.12446,294.21149 c 0,0 6.68844,-4.71017 9.13772,-13.37686 -5.91279,4.63412 -6.77642,9.57974 -9.13772,13.37686 z"
style="fill:#ffffff;stroke:#000000;stroke-width:0.09325644px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
sodipodi:nodetypes="ccc" />
<path
inkscape:connector-curvature="0"
id="path3778"
d="m 344.21877,231.00112 c 0,0 1.60041,9.36884 7.07841,21.7522 5.35526,12.10587 4.05178,-4.80879 -7.07841,-21.7522 z"
style="fill:#ffffff;stroke:#000000;stroke-width:0.09325644px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
sodipodi:nodetypes="csc" />
<path
inkscape:connector-curvature="0"
id="path3780"
d="m 349.44951,230.90023 c -0.11119,-0.0477 0.96041,8.99393 4.75948,15.37263 1.48524,4.17497 3.73499,-6.08181 -4.75948,-15.37263 z"
style="fill:#ffffff;stroke:#000000;stroke-width:0.09325644px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
sodipodi:nodetypes="ccc" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 6.3 KiB

View file

@ -6,13 +6,14 @@ import QtQuick.Controls 2.2
import "../styles-uit" as StylesUIt
Flickable {
Item {
id: flick
property alias url: _webview.url
property alias canGoBack: _webview.canGoBack
property alias webViewCore: _webview
property alias webViewCoreProfile: _webview.profile
property alias url: webViewCore.url
property alias canGoBack: webViewCore.canGoBack
property alias webViewCore: webViewCore
property alias webViewCoreProfile: webViewCore.profile
property string webViewCoreUserAgent
property string userScriptUrl: ""
property string urlTag: "noDownload=false";
@ -20,42 +21,21 @@ Flickable {
signal newViewRequestedCallback(var request)
signal loadingChangedCallback(var loadRequest)
boundsBehavior: Flickable.StopAtBounds
property bool interactive: false
StylesUIt.HifiConstants {
id: hifi
}
onHeightChanged: {
if (height > 0) {
//reload page since window dimentions changed,
//so web engine should recalculate page render dimentions
reloadTimer.start()
}
}
ScrollBar.vertical: ScrollBar {
id: scrollBar
visible: flick.contentHeight > flick.height
contentItem: Rectangle {
opacity: 0.75
implicitWidth: hifi.dimensions.scrollbarHandleWidth
radius: height / 2
color: hifi.colors.tableScrollHandleDark
}
}
function onLoadingChanged(loadRequest) {
if (WebEngineView.LoadStartedStatus === loadRequest.status) {
flick.contentWidth = flick.width
flick.contentHeight = flick.height
// Required to support clicking on "hifi://" links
var url = loadRequest.url.toString();
url = (url.indexOf("?") >= 0) ? url + urlTag : url + "?" + urlTag;
if (urlHandler.canHandleUrl(url)) {
if (urlHandler.handleUrl(url)) {
_webview.stop();
webViewCore.stop();
}
}
}
@ -66,34 +46,18 @@ Flickable {
if (WebEngineView.LoadSucceededStatus === loadRequest.status) {
//disable Chromium's scroll bars
_webview.runJavaScript("document.body.style.overflow = 'hidden';");
//calculate page height
_webview.runJavaScript("document.body.scrollHeight;", function (i_actualPageHeight) {
if (i_actualPageHeight !== undefined) {
flick.contentHeight = i_actualPageHeight
} else {
flick.contentHeight = flick.height;
}
})
flick.contentWidth = flick.width
}
}
Timer {
id: reloadTimer
interval: 100
repeat: false
onTriggered: {
_webview.reload()
}
}
WebEngineView {
id: _webview
id: webViewCore
height: parent.height
anchors.fill: parent
profile: HFWebEngineProfile;
settings.pluginsEnabled: true
settings.touchIconsEnabled: true
settings.allowRunningInsecureContent: true
// creates a global EventBridge object.
WebEngineScript {
@ -124,25 +88,23 @@ Flickable {
property string newUrl: ""
Component.onCompleted: {
width = Qt.binding(function() { return flick.width; });
webChannel.registerObject("eventBridge", eventBridge);
webChannel.registerObject("eventBridgeWrapper", eventBridgeWrapper);
// Ensure the JS from the web-engine makes it to our logging
_webview.javaScriptConsoleMessage.connect(function(level, message, lineNumber, sourceID) {
webViewCore.javaScriptConsoleMessage.connect(function(level, message, lineNumber, sourceID) {
console.log("Web Entity JS message: " + sourceID + " " + lineNumber + " " + message);
});
_webview.profile.httpUserAgent = "Mozilla/5.0 Chrome (HighFidelityInterface)";
if (webViewCoreUserAgent !== undefined) {
webViewCore.profile.httpUserAgent = webViewCoreUserAgent
} else {
webViewCore.profile.httpUserAgent += " (HighFidelityInterface)";
}
}
onFeaturePermissionRequested: {
grantFeaturePermission(securityOrigin, feature, true);
}
onContentsSizeChanged: {
flick.contentHeight = Math.max(contentsSize.height, flick.height);
flick.contentWidth = flick.width
}
//disable popup
onContextMenuRequested: {
request.accepted = true;
@ -163,7 +125,7 @@ Flickable {
x: flick.width/2 - width/2
y: flick.height/2 - height/2
source: "../../icons/loader-snake-64-w.gif"
visible: _webview.loading && /^(http.*|)$/i.test(_webview.url.toString())
visible: webViewCore.loading && /^(http.*|)$/i.test(webViewCore.url.toString())
playing: visible
z: 10000
}

View file

@ -486,9 +486,9 @@ ModalWindow {
model: filesModel
function updateSort() {
model.sortOrder = sortIndicatorOrder;
model.sortColumn = sortIndicatorColumn;
model.update();
fileTableModel.sortOrder = sortIndicatorOrder;
fileTableModel.sortColumn = sortIndicatorColumn;
fileTableModel.update();
}
onSortIndicatorColumnChanged: { updateSort(); }

View file

@ -484,9 +484,9 @@ TabletModalWindow {
model: filesModel
function updateSort() {
model.sortOrder = sortIndicatorOrder;
model.sortColumn = sortIndicatorColumn;
model.update();
fileTableModel.sortOrder = sortIndicatorOrder;
fileTableModel.sortColumn = sortIndicatorColumn;
fileTableModel.update();
}
onSortIndicatorColumnChanged: { updateSort(); }

View file

@ -137,48 +137,11 @@ Item {
}
}
}
// Left gray MouseArea
MouseArea {
anchors.left: parent.left;
anchors.right: textContainer.left;
anchors.top: textContainer.top;
anchors.bottom: textContainer.bottom;
anchors.fill: parent
acceptedButtons: Qt.LeftButton
onClicked: {
letterbox.visible = false
}
}
// Right gray MouseArea
MouseArea {
anchors.left: textContainer.left;
anchors.right: parent.left;
anchors.top: textContainer.top;
anchors.bottom: textContainer.bottom;
acceptedButtons: Qt.LeftButton
onClicked: {
letterbox.visible = false
}
}
// Top gray MouseArea
MouseArea {
anchors.left: parent.left;
anchors.right: parent.right;
anchors.top: parent.top;
anchors.bottom: textContainer.top;
acceptedButtons: Qt.LeftButton
onClicked: {
letterbox.visible = false
}
}
// Bottom gray MouseArea
MouseArea {
anchors.left: parent.left;
anchors.right: parent.right;
anchors.top: textContainer.bottom;
anchors.bottom: parent.bottom;
acceptedButtons: Qt.LeftButton
onClicked: {
letterbox.visible = false
letterbox.visible = false;
}
}
}

View file

@ -36,6 +36,7 @@ Rectangle {
return (root.parent !== null) && root.parent.objectName == "loader";
}
property bool isVR: Audio.context === "VR"
property real rightMostInputLevelPos: 0
//placeholder for control sizes and paddings
@ -68,6 +69,24 @@ Rectangle {
}
}
property bool showPeaks: true;
function enablePeakValues() {
Audio.devices.input.peakValuesEnabled = true;
Audio.devices.input.peakValuesEnabledChanged.connect(function(enabled) {
if (!enabled && root.showPeaks) {
Audio.devices.input.peakValuesEnabled = true;
}
});
}
function disablePeakValues() {
root.showPeaks = false;
Audio.devices.input.peakValuesEnabled = false;
}
Component.onCompleted: enablePeakValues();
Component.onDestruction: disablePeakValues();
onVisibleChanged: visible ? enablePeakValues() : disablePeakValues();
Column {
spacing: 12;
anchors.top: bar.bottom
@ -144,11 +163,7 @@ Rectangle {
anchors.verticalCenter: parent.verticalCenter;
size: 30;
}
RalewayRegular {
width: margins.sizeText + margins.sizeLevel
anchors.left: parent.left
anchors.leftMargin: margins.sizeCheckBox
anchors.verticalCenter: parent.verticalCenter;
size: 16;
color: hifi.colors.lightGrayText;

View file

@ -1,5 +1,5 @@
//
// InputLevel.qml
// InputPeak.qml
// qml/hifi/audio
//
// Created by Zach Pomerantz on 6/20/2017
@ -15,7 +15,7 @@ import QtQuick.Layouts 1.3
import QtGraphicalEffects 1.0
Rectangle {
readonly property var level: Audio.inputLevel;
property var peak;
width: 70;
height: 8;
@ -65,7 +65,7 @@ Rectangle {
Rectangle { // mask
id: mask;
width: parent.width * level;
width: parent.width * peak;
radius: 5;
anchors {
bottom: parent.bottom;

View file

@ -40,12 +40,20 @@ Rectangle {
Hifi.QmlCommerce {
id: commerce;
onAccountResult: {
if (result.status === "success") {
commerce.getKeyFilePathIfExists();
} else {
// unsure how to handle a failure here. We definitely cannot proceed.
}
}
onLoginStatusResult: {
if (!isLoggedIn && root.activeView !== "needsLogIn") {
root.activeView = "needsLogIn";
} else if (isLoggedIn) {
root.activeView = "initialize";
commerce.getKeyFilePathIfExists();
commerce.account();
}
}
@ -203,7 +211,7 @@ Rectangle {
commerce.getLoginStatus();
}
}
HifiWallet.NeedsLogIn {
id: needsLogIn;
visible: root.activeView === "needsLogIn";
@ -239,7 +247,7 @@ Rectangle {
}
}
}
//
// "WALLET NOT SET UP" START
//
@ -250,7 +258,7 @@ Rectangle {
anchors.bottom: parent.bottom;
anchors.left: parent.left;
anchors.right: parent.right;
RalewayRegular {
id: notSetUpText;
text: "<b>Your wallet isn't set up.</b><br><br>Set up your Wallet (no credit card necessary) to claim your <b>free HFC</b> " +
@ -281,7 +289,7 @@ Rectangle {
anchors.left: parent.left;
anchors.bottom: parent.bottom;
anchors.bottomMargin: 24;
// "Cancel" button
HifiControlsUit.Button {
id: cancelButton;

View file

@ -35,12 +35,20 @@ Rectangle {
Hifi.QmlCommerce {
id: commerce;
onAccountResult: {
if (result.status === "success") {
commerce.getKeyFilePathIfExists();
} else {
// unsure how to handle a failure here. We definitely cannot proceed.
}
}
onLoginStatusResult: {
if (!isLoggedIn && root.activeView !== "needsLogIn") {
root.activeView = "needsLogIn";
} else if (isLoggedIn) {
root.activeView = "initialize";
commerce.getKeyFilePathIfExists();
commerce.account();
}
}
@ -174,7 +182,7 @@ Rectangle {
commerce.getLoginStatus();
}
}
HifiWallet.NeedsLogIn {
id: needsLogIn;
visible: root.activeView === "needsLogIn";
@ -210,7 +218,7 @@ Rectangle {
}
}
}
//
// "WALLET NOT SET UP" START
//
@ -221,7 +229,7 @@ Rectangle {
anchors.bottom: parent.bottom;
anchors.left: parent.left;
anchors.right: parent.right;
RalewayRegular {
id: notSetUpText;
text: "<b>Your wallet isn't set up.</b><br><br>Set up your Wallet (no credit card necessary) to claim your <b>free HFC</b> " +
@ -252,7 +260,7 @@ Rectangle {
anchors.left: parent.left;
anchors.bottom: parent.bottom;
anchors.bottomMargin: 24;
// "Cancel" button
HifiControlsUit.Button {
id: cancelButton;
@ -309,7 +317,7 @@ Rectangle {
anchors.topMargin: 8;
anchors.bottom: actionButtonsContainer.top;
anchors.bottomMargin: 8;
//
// FILTER BAR START
//
@ -383,7 +391,7 @@ Rectangle {
itemHref: root_file_url;
anchors.topMargin: 12;
anchors.bottomMargin: 12;
Connections {
onSendToPurchases: {
if (msg.method === 'purchases_itemInfoClicked') {
@ -402,7 +410,7 @@ Rectangle {
anchors.left: parent.left;
anchors.bottom: parent.bottom;
width: parent.width;
// Explanitory text
RalewayRegular {
id: haventPurchasedYet;

View file

@ -55,6 +55,7 @@ Item {
text: "DEBUG: Clear Cached Passphrase";
onClicked: {
commerce.setPassphrase("");
sendSignalToWallet({method: 'passphraseReset'});
}
}
HifiControlsUit.Button {

View file

@ -33,12 +33,19 @@ Rectangle {
Hifi.QmlCommerce {
id: commerce;
onAccountResult: {
if (result.status === "success") {
commerce.getKeyFilePathIfExists();
} else {
// unsure how to handle a failure here. We definitely cannot proceed.
}
}
onLoginStatusResult: {
if (!isLoggedIn && root.activeView !== "needsLogIn") {
root.activeView = "needsLogIn";
} else if (isLoggedIn) {
root.activeView = "initialize";
commerce.getKeyFilePathIfExists();
commerce.account();
}
}
@ -318,7 +325,7 @@ Rectangle {
Connections {
onSendSignalToWallet: {
if (msg.method === 'walletReset') {
if (msg.method === 'walletReset' || msg.method === 'passphraseReset') {
sendToScript(msg);
}
}

View file

@ -325,7 +325,7 @@ Rectangle {
onClicked: {
if (passphraseSelection.validateAndSubmitPassphrase()) {
root.lastPage = "choosePassphrase";
commerce.balance(); // Do this here so that keys are generated. Order might change as backend changes?
commerce.generateKeyPair();
choosePassphraseContainer.visible = false;
privateKeysReadyContainer.visible = true;
}

View file

@ -387,9 +387,9 @@ ScrollingWindow {
readOnly: true
Connections {
target: treeView
target: treeView.selection
onCurrentIndexChanged: {
var path = scriptsModel.data(treeView.currentIndex, 0x100)
var path = scriptsModel.data(treeView.selection.currentIndex, 0x100)
if (path) {
selectedScript.text = path
} else {

View file

@ -416,9 +416,9 @@ Rectangle {
readOnly: true
Connections {
target: treeView
target: treeView.selection
onCurrentIndexChanged: {
var path = scriptsModel.data(treeView.currentIndex, 0x100)
var path = scriptsModel.data(treeView.selection.currentIndex, 0x100)
if (path) {
selectedScript.text = path
} else {

View file

@ -3,6 +3,8 @@ import QtGraphicalEffects 1.0
Item {
id: tabletButton
property string captionColorOverride: ""
property var uuid;
property string icon: "icons/tablet-icons/edit-i.svg"
property string hoverIcon: tabletButton.icon
@ -102,7 +104,7 @@ Item {
Text {
id: text
color: "#ffffff"
color: captionColorOverride !== "" ? captionColorOverride: "#ffffff"
text: tabletButton.text
font.bold: true
font.pixelSize: 18

View file

@ -14,6 +14,8 @@ import "../../windows" as Windows
import QtQuick 2.0
import Hifi 1.0
import Qt.labs.settings 1.0
Windows.ScrollingWindow {
id: tabletRoot
objectName: "tabletRoot"
@ -25,8 +27,32 @@ Windows.ScrollingWindow {
shown: false
resizable: false
Settings {
id: settings
category: "WindowRoot.Windows"
property real width: 480
property real height: 706
}
onResizableChanged: {
if (!resizable) {
// restore default size
settings.width = tabletRoot.width
settings.height = tabletRoot.height
tabletRoot.width = 480
tabletRoot.height = 706
} else {
tabletRoot.width = settings.width
tabletRoot.height = settings.height
}
}
signal showDesktop();
function setResizable(value) {
tabletRoot.resizable = value;
}
function setMenuProperties(rootMenu, subMenu) {
tabletRoot.rootMenu = rootMenu;
tabletRoot.subMenu = subMenu;

View file

@ -963,7 +963,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo
DependencyManager::get<AddressManager>().data(), &AddressManager::storeCurrentAddress);
auto scriptEngines = DependencyManager::get<ScriptEngines>().data();
scriptEngines->registerScriptInitializer([this](ScriptEngine* engine){
scriptEngines->registerScriptInitializer([this](ScriptEnginePointer engine){
registerScriptEngineWithApplicationServices(engine);
});
@ -2414,10 +2414,18 @@ void Application::paintGL() {
auto lodManager = DependencyManager::get<LODManager>();
RenderArgs renderArgs;
float sensorToWorldScale = getMyAvatar()->getSensorToWorldScale();
{
PROFILE_RANGE(render, "/buildFrustrumAndArgs");
{
QMutexLocker viewLocker(&_viewMutex);
// adjust near clip plane to account for sensor scaling.
auto adjustedProjection = glm::perspective(_viewFrustum.getFieldOfView(),
_viewFrustum.getAspectRatio(),
DEFAULT_NEAR_CLIP * sensorToWorldScale,
_viewFrustum.getFarClip());
_viewFrustum.setProjection(adjustedProjection);
_viewFrustum.calculate();
}
renderArgs = RenderArgs(_gpuContext, lodManager->getOctreeSizeScale(),
@ -2465,7 +2473,7 @@ void Application::paintGL() {
PerformanceTimer perfTimer("CameraUpdates");
auto myAvatar = getMyAvatar();
boomOffset = myAvatar->getScale() * myAvatar->getBoomLength() * -IDENTITY_FORWARD;
boomOffset = myAvatar->getModelScale() * myAvatar->getBoomLength() * -IDENTITY_FORWARD;
// The render mode is default or mirror if the camera is in mirror mode, assigned further below
renderArgs._renderMode = RenderArgs::DEFAULT_RENDER_MODE;
@ -2477,7 +2485,7 @@ void Application::paintGL() {
if (isHMDMode()) {
mat4 camMat = myAvatar->getSensorToWorldMatrix() * myAvatar->getHMDSensorMatrix();
_myCamera.setPosition(extractTranslation(camMat));
_myCamera.setOrientation(glm::quat_cast(camMat));
_myCamera.setOrientation(glmExtractRotation(camMat));
} else {
_myCamera.setPosition(myAvatar->getDefaultEyePosition());
_myCamera.setOrientation(myAvatar->getMyHead()->getHeadOrientation());
@ -2485,7 +2493,7 @@ void Application::paintGL() {
} else if (_myCamera.getMode() == CAMERA_MODE_THIRD_PERSON) {
if (isHMDMode()) {
auto hmdWorldMat = myAvatar->getSensorToWorldMatrix() * myAvatar->getHMDSensorMatrix();
_myCamera.setOrientation(glm::normalize(glm::quat_cast(hmdWorldMat)));
_myCamera.setOrientation(glm::normalize(glmExtractRotation(hmdWorldMat)));
_myCamera.setPosition(extractTranslation(hmdWorldMat) +
myAvatar->getOrientation() * boomOffset);
} else {
@ -2518,14 +2526,14 @@ void Application::paintGL() {
hmdOffset.x = -hmdOffset.x;
_myCamera.setPosition(myAvatar->getDefaultEyePosition()
+ glm::vec3(0, _raiseMirror * myAvatar->getUniformScale(), 0)
+ glm::vec3(0, _raiseMirror * myAvatar->getModelScale(), 0)
+ mirrorBodyOrientation * glm::vec3(0.0f, 0.0f, 1.0f) * MIRROR_FULLSCREEN_DISTANCE * _scaleMirror
+ mirrorBodyOrientation * hmdOffset);
} else {
_myCamera.setOrientation(myAvatar->getOrientation()
* glm::quat(glm::vec3(0.0f, PI + _rotateMirror, 0.0f)));
_myCamera.setPosition(myAvatar->getDefaultEyePosition()
+ glm::vec3(0, _raiseMirror * myAvatar->getUniformScale(), 0)
+ glm::vec3(0, _raiseMirror * myAvatar->getModelScale(), 0)
+ (myAvatar->getOrientation() * glm::quat(glm::vec3(0.0f, _rotateMirror, 0.0f))) *
glm::vec3(0.0f, 0.0f, -1.0f) * MIRROR_FULLSCREEN_DISTANCE * _scaleMirror);
}
@ -2553,7 +2561,7 @@ void Application::paintGL() {
{
PROFILE_RANGE(render, "/updateCompositor");
getApplicationCompositor().setFrameInfo(_frameCount, _myCamera.getTransform());
getApplicationCompositor().setFrameInfo(_frameCount, _myCamera.getTransform(), getMyAvatar()->getSensorToWorldMatrix());
}
gpu::FramebufferPointer finalFramebuffer;
@ -2567,6 +2575,12 @@ void Application::paintGL() {
finalFramebuffer = framebufferCache->getFramebuffer();
}
auto hmdInterface = DependencyManager::get<HMDScriptingInterface>();
float ipdScale = hmdInterface->getIPDScale();
// scale IPD by sensorToWorldScale, to make the world seem larger or smaller accordingly.
ipdScale *= sensorToWorldScale;
mat4 eyeProjections[2];
{
PROFILE_RANGE(render, "/mainRender");
@ -2576,6 +2590,7 @@ void Application::paintGL() {
// in the overlay render?
// Viewport is assigned to the size of the framebuffer
renderArgs._viewport = ivec4(0, 0, finalFramebufferSize.width(), finalFramebufferSize.height());
auto baseProjection = renderArgs.getViewFrustum().getProjection();
if (displayPlugin->isStereo()) {
// Stereo modes will typically have a larger projection matrix overall,
// so we ask for the 'mono' projection matrix, which for stereo and HMD
@ -2586,12 +2601,10 @@ void Application::paintGL() {
// just relying on the left FOV in each case and hoping that the
// overall culling margin of error doesn't cause popping in the
// right eye. There are FIXMEs in the relevant plugins
_myCamera.setProjection(displayPlugin->getCullingProjection(_myCamera.getProjection()));
_myCamera.setProjection(displayPlugin->getCullingProjection(baseProjection));
renderArgs._context->enableStereo(true);
mat4 eyeOffsets[2];
auto baseProjection = renderArgs.getViewFrustum().getProjection();
auto hmdInterface = DependencyManager::get<HMDScriptingInterface>();
float IPDScale = hmdInterface->getIPDScale();
mat4 eyeProjections[2];
// FIXME we probably don't need to set the projection matrix every frame,
// only when the display plugin changes (or in non-HMD modes when the user
@ -2605,7 +2618,7 @@ void Application::paintGL() {
// Grab the translation
vec3 eyeOffset = glm::vec3(eyeToHead[3]);
// Apply IPD scaling
mat4 eyeOffsetTransform = glm::translate(mat4(), eyeOffset * -1.0f * IPDScale);
mat4 eyeOffsetTransform = glm::translate(mat4(), eyeOffset * -1.0f * ipdScale);
eyeOffsets[eye] = eyeOffsetTransform;
eyeProjections[eye] = displayPlugin->getEyeProjection(eye, baseProjection);
});
@ -2625,8 +2638,14 @@ void Application::paintGL() {
PerformanceTimer perfTimer("postComposite");
renderArgs._batch = &postCompositeBatch;
renderArgs._batch->setViewportTransform(ivec4(0, 0, finalFramebufferSize.width(), finalFramebufferSize.height()));
renderArgs._batch->setViewTransform(renderArgs.getViewFrustum().getView());
for_each_eye([&](Eye eye) {
// apply eye offset and IPD scale to the view matrix
mat4 eyeToHead = displayPlugin->getEyeToHeadTransform(eye);
vec3 eyeOffset = glm::vec3(eyeToHead[3]);
mat4 eyeOffsetTransform = glm::translate(mat4(), eyeOffset * -1.0f * ipdScale);
renderArgs._batch->setViewTransform(renderArgs.getViewFrustum().getView() * eyeOffsetTransform);
renderArgs._batch->setProjectionTransform(eyeProjections[eye]);
_overlays.render3DHUDOverlays(&renderArgs);
});
@ -2804,35 +2823,18 @@ void Application::handleSandboxStatus(QNetworkReply* reply) {
// Get controller availability
bool hasHandControllers = false;
HandControllerType handControllerType = Vive;
if (PluginUtils::isViveControllerAvailable()) {
if (PluginUtils::isViveControllerAvailable() || PluginUtils::isOculusTouchControllerAvailable()) {
hasHandControllers = true;
handControllerType = Vive;
} else if (PluginUtils::isOculusTouchControllerAvailable()) {
hasHandControllers = true;
handControllerType = Oculus;
}
// Check tutorial content versioning
bool hasTutorialContent = contentVersion >= MIN_CONTENT_VERSION.at(handControllerType);
// Check HMD use (may be technically available without being in use)
bool hasHMD = PluginUtils::isHMDAvailable();
bool isUsingHMD = _displayPlugin->isHmd();
bool isUsingHMDAndHandControllers = hasHMD && hasHandControllers && isUsingHMD;
Setting::Handle<bool> tutorialComplete{ "tutorialComplete", false };
Setting::Handle<bool> firstRun{ Settings::firstRun, true };
const QString HIFI_SKIP_TUTORIAL_COMMAND_LINE_KEY = "--skipTutorial";
// Skips tutorial/help behavior, and does NOT clear firstRun setting.
bool skipTutorial = arguments().contains(HIFI_SKIP_TUTORIAL_COMMAND_LINE_KEY);
bool isTutorialComplete = tutorialComplete.get();
bool shouldGoToTutorial = isUsingHMDAndHandControllers && hasTutorialContent && !isTutorialComplete && !skipTutorial;
qCDebug(interfaceapp) << "HMD:" << hasHMD << ", Hand Controllers: " << hasHandControllers << ", Using HMD: " << isUsingHMDAndHandControllers;
qCDebug(interfaceapp) << "Tutorial version:" << contentVersion << ", sufficient:" << hasTutorialContent <<
", complete:" << isTutorialComplete << ", should go:" << shouldGoToTutorial;
// when --url in command line, teleport to location
const QString HIFI_URL_COMMAND_LINE_KEY = "--url";
@ -2842,58 +2844,31 @@ void Application::handleSandboxStatus(QNetworkReply* reply) {
addressLookupString = arguments().value(urlIndex + 1);
}
const QString TUTORIAL_PATH = "/tutorial_begin";
static const QString SENT_TO_TUTORIAL = "tutorial";
static const QString SENT_TO_PREVIOUS_LOCATION = "previous_location";
static const QString SENT_TO_ENTRY = "entry";
static const QString SENT_TO_SANDBOX = "sandbox";
QString sentTo;
if (shouldGoToTutorial) {
if (sandboxIsRunning) {
qCDebug(interfaceapp) << "Home sandbox appears to be running, going to Home.";
DependencyManager::get<AddressManager>()->goToLocalSandbox(TUTORIAL_PATH);
sentTo = SENT_TO_TUTORIAL;
} else {
qCDebug(interfaceapp) << "Home sandbox does not appear to be running, going to Entry.";
if (firstRun.get()) {
showHelp();
}
if (addressLookupString.isEmpty()) {
DependencyManager::get<AddressManager>()->goToEntry();
sentTo = SENT_TO_ENTRY;
} else {
DependencyManager::get<AddressManager>()->loadSettings(addressLookupString);
sentTo = SENT_TO_PREVIOUS_LOCATION;
}
}
} else {
// If this is a first run we short-circuit the address passed in
if (firstRun.get() && !skipTutorial) {
if (firstRun.get()) {
showHelp();
if (isUsingHMDAndHandControllers) {
if (sandboxIsRunning) {
qCDebug(interfaceapp) << "Home sandbox appears to be running, going to Home.";
DependencyManager::get<AddressManager>()->goToLocalSandbox();
sentTo = SENT_TO_SANDBOX;
} else {
qCDebug(interfaceapp) << "Home sandbox does not appear to be running, going to Entry.";
DependencyManager::get<AddressManager>()->goToEntry();
sentTo = SENT_TO_ENTRY;
}
if (sandboxIsRunning) {
qCDebug(interfaceapp) << "Home sandbox appears to be running, going to Home.";
DependencyManager::get<AddressManager>()->goToLocalSandbox();
sentTo = SENT_TO_SANDBOX;
} else {
qCDebug(interfaceapp) << "Home sandbox does not appear to be running, going to Entry.";
DependencyManager::get<AddressManager>()->goToEntry();
sentTo = SENT_TO_ENTRY;
}
firstRun.set(false);
} else {
qCDebug(interfaceapp) << "Not first run... going to" << qPrintable(addressLookupString.isEmpty() ? QString("previous location") : addressLookupString);
DependencyManager::get<AddressManager>()->loadSettings(addressLookupString);
sentTo = SENT_TO_PREVIOUS_LOCATION;
}
}
UserActivityLogger::getInstance().logAction("startup_sent_to", {
{ "sent_to", sentTo },
@ -2902,18 +2877,10 @@ void Application::handleSandboxStatus(QNetworkReply* reply) {
{ "has_hand_controllers", hasHandControllers },
{ "is_using_hmd", isUsingHMD },
{ "is_using_hmd_and_hand_controllers", isUsingHMDAndHandControllers },
{ "content_version", contentVersion },
{ "is_tutorial_complete", isTutorialComplete },
{ "has_tutorial_content", hasTutorialContent },
{ "should_go_to_tutorial", shouldGoToTutorial }
{ "content_version", contentVersion }
});
_connectionMonitor.init();
// After all of the constructor is completed, then set firstRun to false.
if (!skipTutorial) {
firstRun.set(false);
}
}
bool Application::importJSONFromURL(const QString& urlString) {
@ -5262,7 +5229,7 @@ void Application::update(float deltaTime) {
}
}
avatarManager->postUpdate(deltaTime);
avatarManager->postUpdate(deltaTime, getMain3DScene());
{
PROFILE_RANGE_EX(app, "PreRenderLambdas", 0xffff0000, (uint64_t)0);
@ -5983,7 +5950,7 @@ int Application::processOctreeStats(ReceivedMessage& message, SharedNodePointer
void Application::packetSent(quint64 length) {
}
void Application::registerScriptEngineWithApplicationServices(ScriptEngine* scriptEngine) {
void Application::registerScriptEngineWithApplicationServices(ScriptEnginePointer scriptEngine) {
scriptEngine->setEmitScriptUpdatesFunction([this]() {
SharedNodePointer entityServerNode = DependencyManager::get<NodeList>()->soloNodeOfType(NodeType::EntityServer);
@ -6018,29 +5985,31 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEngine* scri
ClipboardScriptingInterface* clipboardScriptable = new ClipboardScriptingInterface();
scriptEngine->registerGlobalObject("Clipboard", clipboardScriptable);
connect(scriptEngine, &ScriptEngine::finished, clipboardScriptable, &ClipboardScriptingInterface::deleteLater);
connect(scriptEngine.data(), &ScriptEngine::finished, clipboardScriptable, &ClipboardScriptingInterface::deleteLater);
scriptEngine->registerGlobalObject("Overlays", &_overlays);
qScriptRegisterMetaType(scriptEngine, OverlayPropertyResultToScriptValue, OverlayPropertyResultFromScriptValue);
qScriptRegisterMetaType(scriptEngine, RayToOverlayIntersectionResultToScriptValue,
qScriptRegisterMetaType(scriptEngine.data(), OverlayPropertyResultToScriptValue, OverlayPropertyResultFromScriptValue);
qScriptRegisterMetaType(scriptEngine.data(), RayToOverlayIntersectionResultToScriptValue,
RayToOverlayIntersectionResultFromScriptValue);
scriptEngine->registerGlobalObject("OffscreenFlags", DependencyManager::get<OffscreenUi>()->getFlags());
scriptEngine->registerGlobalObject("Desktop", DependencyManager::get<DesktopScriptingInterface>().data());
qScriptRegisterMetaType(scriptEngine, wrapperToScriptValue<ToolbarProxy>, wrapperFromScriptValue<ToolbarProxy>);
qScriptRegisterMetaType(scriptEngine, wrapperToScriptValue<ToolbarButtonProxy>, wrapperFromScriptValue<ToolbarButtonProxy>);
qScriptRegisterMetaType(scriptEngine.data(), wrapperToScriptValue<ToolbarProxy>, wrapperFromScriptValue<ToolbarProxy>);
qScriptRegisterMetaType(scriptEngine.data(),
wrapperToScriptValue<ToolbarButtonProxy>, wrapperFromScriptValue<ToolbarButtonProxy>);
scriptEngine->registerGlobalObject("Toolbars", DependencyManager::get<ToolbarScriptingInterface>().data());
qScriptRegisterMetaType(scriptEngine, wrapperToScriptValue<TabletProxy>, wrapperFromScriptValue<TabletProxy>);
qScriptRegisterMetaType(scriptEngine, wrapperToScriptValue<TabletButtonProxy>, wrapperFromScriptValue<TabletButtonProxy>);
qScriptRegisterMetaType(scriptEngine.data(), wrapperToScriptValue<TabletProxy>, wrapperFromScriptValue<TabletProxy>);
qScriptRegisterMetaType(scriptEngine.data(),
wrapperToScriptValue<TabletButtonProxy>, wrapperFromScriptValue<TabletButtonProxy>);
scriptEngine->registerGlobalObject("Tablet", DependencyManager::get<TabletScriptingInterface>().data());
DependencyManager::get<TabletScriptingInterface>().data()->setToolbarScriptingInterface(DependencyManager::get<ToolbarScriptingInterface>().data());
auto toolbarScriptingInterface = DependencyManager::get<ToolbarScriptingInterface>().data();
DependencyManager::get<TabletScriptingInterface>().data()->setToolbarScriptingInterface(toolbarScriptingInterface);
scriptEngine->registerGlobalObject("Window", DependencyManager::get<WindowScriptingInterface>().data());
qScriptRegisterMetaType(scriptEngine, CustomPromptResultToScriptValue, CustomPromptResultFromScriptValue);
qScriptRegisterMetaType(scriptEngine.data(), CustomPromptResultToScriptValue, CustomPromptResultFromScriptValue);
scriptEngine->registerGetterSetter("location", LocationScriptingInterface::locationGetter,
LocationScriptingInterface::locationSetter, "Window");
// register `location` on the global object.
@ -6072,7 +6041,7 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEngine* scri
scriptEngine->registerGlobalObject("DialogsManager", _dialogsManagerScriptingInterface);
scriptEngine->registerGlobalObject("GlobalServices", GlobalServicesScriptingInterface::getInstance());
qScriptRegisterMetaType(scriptEngine, DownloadInfoResultToScriptValue, DownloadInfoResultFromScriptValue);
qScriptRegisterMetaType(scriptEngine.data(), DownloadInfoResultToScriptValue, DownloadInfoResultFromScriptValue);
scriptEngine->registerGlobalObject("FaceTracker", DependencyManager::get<DdeFaceTracker>().data());
@ -6100,11 +6069,11 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEngine* scri
scriptEngine->registerGlobalObject("LimitlessSpeechRecognition", DependencyManager::get<LimitlessVoiceRecognitionScriptingInterface>().data());
if (auto steamClient = PluginManager::getInstance()->getSteamClientPlugin()) {
scriptEngine->registerGlobalObject("Steam", new SteamScriptingInterface(scriptEngine, steamClient.get()));
scriptEngine->registerGlobalObject("Steam", new SteamScriptingInterface(scriptEngine.data(), steamClient.get()));
}
auto scriptingInterface = DependencyManager::get<controller::ScriptingInterface>();
scriptEngine->registerGlobalObject("Controller", scriptingInterface.data());
UserInputMapper::registerControllerTypes(scriptEngine);
UserInputMapper::registerControllerTypes(scriptEngine.data());
auto recordingInterface = DependencyManager::get<RecordingScriptingInterface>();
scriptEngine->registerGlobalObject("Recording", recordingInterface.data());
@ -6115,14 +6084,19 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEngine* scri
scriptEngine->registerGlobalObject("Selection", DependencyManager::get<SelectionScriptingInterface>().data());
scriptEngine->registerGlobalObject("ContextOverlay", DependencyManager::get<ContextOverlayInterface>().data());
qScriptRegisterMetaType(scriptEngine, OverlayIDtoScriptValue, OverlayIDfromScriptValue);
qScriptRegisterMetaType(scriptEngine.data(), OverlayIDtoScriptValue, OverlayIDfromScriptValue);
// connect this script engines printedMessage signal to the global ScriptEngines these various messages
connect(scriptEngine, &ScriptEngine::printedMessage, DependencyManager::get<ScriptEngines>().data(), &ScriptEngines::onPrintedMessage);
connect(scriptEngine, &ScriptEngine::errorMessage, DependencyManager::get<ScriptEngines>().data(), &ScriptEngines::onErrorMessage);
connect(scriptEngine, &ScriptEngine::warningMessage, DependencyManager::get<ScriptEngines>().data(), &ScriptEngines::onWarningMessage);
connect(scriptEngine, &ScriptEngine::infoMessage, DependencyManager::get<ScriptEngines>().data(), &ScriptEngines::onInfoMessage);
connect(scriptEngine, &ScriptEngine::clearDebugWindow, DependencyManager::get<ScriptEngines>().data(), &ScriptEngines::onClearDebugWindow);
connect(scriptEngine.data(), &ScriptEngine::printedMessage,
DependencyManager::get<ScriptEngines>().data(), &ScriptEngines::onPrintedMessage);
connect(scriptEngine.data(), &ScriptEngine::errorMessage,
DependencyManager::get<ScriptEngines>().data(), &ScriptEngines::onErrorMessage);
connect(scriptEngine.data(), &ScriptEngine::warningMessage,
DependencyManager::get<ScriptEngines>().data(), &ScriptEngines::onWarningMessage);
connect(scriptEngine.data(), &ScriptEngine::infoMessage,
DependencyManager::get<ScriptEngines>().data(), &ScriptEngines::onInfoMessage);
connect(scriptEngine.data(), &ScriptEngine::clearDebugWindow,
DependencyManager::get<ScriptEngines>().data(), &ScriptEngines::onClearDebugWindow);
}
@ -6457,7 +6431,12 @@ void Application::addAssetToWorldFromURL(QString url) {
}
if (url.contains("vr.google.com/downloads")) {
filename = url.section('/', -1);
filename.remove(".zip");
if (url.contains("noDownload")) {
filename.remove(".zip?noDownload=false");
} else {
filename.remove(".zip");
}
}
if (!DependencyManager::get<NodeList>()->getThisNodeCanWriteAssets()) {
@ -6487,7 +6466,11 @@ void Application::addAssetToWorldFromURLRequestFinished() {
}
if (url.contains("vr.google.com/downloads")) {
filename = url.section('/', -1);
filename.remove(".zip");
if (url.contains("noDownload")) {
filename.remove(".zip?noDownload=false");
} else {
filename.remove(".zip");
}
isBlocks = true;
}
@ -6654,7 +6637,9 @@ void Application::addAssetToWorldAddEntity(QString filePath, QString mapping) {
properties.setShapeType(SHAPE_TYPE_SIMPLE_COMPOUND);
properties.setCollisionless(true); // Temporarily set so that doesn't collide with avatar.
properties.setVisible(false); // Temporarily set so that don't see at large unresized dimensions.
properties.setPosition(getMyAvatar()->getPosition() + getMyAvatar()->getOrientation() * glm::vec3(0.0f, 0.0f, -2.0f));
glm::vec3 positionOffset = getMyAvatar()->getOrientation() * (getMyAvatar()->getSensorToWorldScale() * glm::vec3(0.0f, 0.0f, -2.0f));
properties.setPosition(getMyAvatar()->getPosition() + positionOffset);
properties.setRotation(getMyAvatar()->getOrientation());
properties.setGravity(glm::vec3(0.0f, 0.0f, 0.0f));
auto entityID = DependencyManager::get<EntityScriptingInterface>()->addEntity(properties);
@ -6701,7 +6686,7 @@ void Application::addAssetToWorldCheckModelSize() {
if (dimensions != DEFAULT_DIMENSIONS) {
// Scale model so that its maximum is exactly specific size.
const float MAXIMUM_DIMENSION = 1.0f;
const float MAXIMUM_DIMENSION = 1.0f * getMyAvatar()->getSensorToWorldScale();
auto previousDimensions = dimensions;
auto scale = std::min(MAXIMUM_DIMENSION / dimensions.x, std::min(MAXIMUM_DIMENSION / dimensions.y,
MAXIMUM_DIMENSION / dimensions.z));
@ -7442,7 +7427,10 @@ void Application::updateDisplayMode() {
getApplicationCompositor().setDisplayPlugin(newDisplayPlugin);
_displayPlugin = newDisplayPlugin;
connect(_displayPlugin.get(), &DisplayPlugin::presented, this, &Application::onPresent);
offscreenUi->getDesktop()->setProperty("repositionLocked", wasRepositionLocked);
auto desktop = offscreenUi->getDesktop();
if (desktop) {
desktop->setProperty("repositionLocked", wasRepositionLocked);
}
}
bool isHmd = _displayPlugin->isHmd();

View file

@ -218,7 +218,7 @@ public:
NodeToOctreeSceneStats* getOcteeSceneStats() { return &_octreeServerSceneStats; }
virtual controller::ScriptingInterface* getControllerScriptingInterface() { return _controllerScriptingInterface; }
virtual void registerScriptEngineWithApplicationServices(ScriptEngine* scriptEngine) override;
virtual void registerScriptEngineWithApplicationServices(ScriptEnginePointer scriptEngine) override;
virtual void copyCurrentViewFrustum(ViewFrustum& viewOut) const override { copyDisplayViewFrustum(viewOut); }
virtual QThread* getMainThread() override { return thread(); }

View file

@ -165,7 +165,7 @@ bool AvatarActionHold::getTarget(float deltaTimeStep, glm::quat& rotation, glm::
Transform avatarTransform;
avatarTransform = myAvatar->getTransform();
palmPosition = avatarTransform.transform(camRelPos / myAvatar->getDomainLimitedScale());
palmPosition = avatarTransform.transform(camRelPos);
palmRotation = avatarTransform.getRotation() * camRelRot;
} else {
glm::vec3 avatarRigidBodyPosition;

View file

@ -259,12 +259,12 @@ void AvatarManager::updateOtherAvatars(float deltaTime) {
simulateAvatarFades(deltaTime);
}
void AvatarManager::postUpdate(float deltaTime) {
void AvatarManager::postUpdate(float deltaTime, const render::ScenePointer& scene) {
auto hashCopy = getHashCopy();
AvatarHash::iterator avatarIterator = hashCopy.begin();
for (avatarIterator = hashCopy.begin(); avatarIterator != hashCopy.end(); avatarIterator++) {
auto avatar = std::static_pointer_cast<Avatar>(avatarIterator.value());
avatar->postUpdate(deltaTime);
avatar->postUpdate(deltaTime, scene);
}
}

View file

@ -55,7 +55,7 @@ public:
void updateMyAvatar(float deltaTime);
void updateOtherAvatars(float deltaTime);
void postUpdate(float deltaTime);
void postUpdate(float deltaTime, const render::ScenePointer& scene);
void clearOtherAvatars();
void deleteAllAvatars();

View file

@ -64,18 +64,13 @@ using namespace std;
const float DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES = 30.0f;
const float MAX_WALKING_SPEED = 2.6f; // human walking speed
const float MAX_BOOST_SPEED = 0.5f * MAX_WALKING_SPEED; // action motor gets additive boost below this speed
const float MIN_AVATAR_SPEED = 0.05f;
const float MIN_AVATAR_SPEED_SQUARED = MIN_AVATAR_SPEED * MIN_AVATAR_SPEED; // speed is set to zero below this
const float YAW_SPEED_DEFAULT = 100.0f; // degrees/sec
const float PITCH_SPEED_DEFAULT = 75.0f; // degrees/sec
// TODO: normalize avatar speed for standard avatar size, then scale all motion logic
// to properly follow avatar size.
float MAX_AVATAR_SPEED = 30.0f;
float MAX_ACTION_MOTOR_SPEED = MAX_AVATAR_SPEED;
const float MAX_BOOST_SPEED = 0.5f * DEFAULT_AVATAR_MAX_WALKING_SPEED; // action motor gets additive boost below this speed
const float MIN_AVATAR_SPEED = 0.05f;
const float MIN_AVATAR_SPEED_SQUARED = MIN_AVATAR_SPEED * MIN_AVATAR_SPEED; // speed is set to zero below this
float MIN_SCRIPTED_MOTOR_TIMESCALE = 0.005f;
float DEFAULT_SCRIPTED_MOTOR_TIMESCALE = 1.0e6f;
const int SCRIPTED_MOTOR_CAMERA_FRAME = 0;
@ -87,29 +82,6 @@ const float MyAvatar::ZOOM_MIN = 0.5f;
const float MyAvatar::ZOOM_MAX = 25.0f;
const float MyAvatar::ZOOM_DEFAULT = 1.5f;
// default values, used when avatar is missing joints... (avatar space)
static const glm::quat DEFAULT_AVATAR_MIDDLE_EYE_ROT { Quaternions::Y_180 };
static const glm::vec3 DEFAULT_AVATAR_MIDDLE_EYE_POS { 0.0f, 0.6f, 0.0f };
static const glm::vec3 DEFAULT_AVATAR_HEAD_POS { 0.0f, 0.53f, 0.0f };
static const glm::quat DEFAULT_AVATAR_HEAD_ROT { Quaternions::Y_180 };
static const glm::vec3 DEFAULT_AVATAR_RIGHTARM_POS { -0.134824f, 0.396348f, -0.0515777f };
static const glm::quat DEFAULT_AVATAR_RIGHTARM_ROT { -0.536241f, 0.536241f, -0.460918f, -0.460918f };
static const glm::vec3 DEFAULT_AVATAR_LEFTARM_POS { 0.134795f, 0.396349f, -0.0515881f };
static const glm::quat DEFAULT_AVATAR_LEFTARM_ROT { 0.536257f, 0.536258f, -0.460899f, 0.4609f };
static const glm::vec3 DEFAULT_AVATAR_RIGHTHAND_POS { -0.72768f, 0.396349f, -0.0515779f };
static const glm::quat DEFAULT_AVATAR_RIGHTHAND_ROT { 0.479184f, -0.520013f, 0.522537f, 0.476365f};
static const glm::vec3 DEFAULT_AVATAR_LEFTHAND_POS { 0.727588f, 0.39635f, -0.0515878f };
static const glm::quat DEFAULT_AVATAR_LEFTHAND_ROT { -0.479181f, -0.52001f, 0.52254f, -0.476369f };
static const glm::vec3 DEFAULT_AVATAR_NECK_POS { 0.0f, 0.445f, 0.025f };
static const glm::vec3 DEFAULT_AVATAR_SPINE2_POS { 0.0f, 0.32f, 0.02f };
static const glm::quat DEFAULT_AVATAR_SPINE2_ROT { Quaternions::Y_180 };
static const glm::vec3 DEFAULT_AVATAR_HIPS_POS { 0.0f, 0.0f, 0.0f };
static const glm::quat DEFAULT_AVATAR_HIPS_ROT { Quaternions::Y_180 };
static const glm::vec3 DEFAULT_AVATAR_LEFTFOOT_POS { -0.08f, -0.96f, 0.029f};
static const glm::quat DEFAULT_AVATAR_LEFTFOOT_ROT { -0.40167322754859924f, 0.9154590368270874f, -0.005437685176730156f, -0.023744143545627594f };
static const glm::vec3 DEFAULT_AVATAR_RIGHTFOOT_POS { 0.08f, -0.96f, 0.029f };
static const glm::quat DEFAULT_AVATAR_RIGHTFOOT_ROT { -0.4016716778278351f, 0.9154615998268127f, 0.0053307069465518f, 0.023696165531873703f };
MyAvatar::MyAvatar(QThread* thread) :
Avatar(thread),
_yawSpeed(YAW_SPEED_DEFAULT),
@ -262,7 +234,7 @@ void MyAvatar::setDominantHand(const QString& hand) {
}
}
void MyAvatar::registerMetaTypes(QScriptEngine* engine) {
void MyAvatar::registerMetaTypes(ScriptEnginePointer engine) {
QScriptValue value = engine->newQObject(this, QScriptEngine::QtOwnership, QScriptEngine::ExcludeDeleteLater | QScriptEngine::ExcludeChildObjects);
engine->globalObject().setProperty("MyAvatar", value);
@ -273,8 +245,8 @@ void MyAvatar::registerMetaTypes(QScriptEngine* engine) {
}
engine->globalObject().setProperty("DriveKeys", driveKeys);
qScriptRegisterMetaType(engine, audioListenModeToScriptValue, audioListenModeFromScriptValue);
qScriptRegisterMetaType(engine, driveKeysToScriptValue, driveKeysFromScriptValue);
qScriptRegisterMetaType(engine.data(), audioListenModeToScriptValue, audioListenModeFromScriptValue);
qScriptRegisterMetaType(engine.data(), driveKeysToScriptValue, driveKeysFromScriptValue);
}
void MyAvatar::setOrientationVar(const QVariant& newOrientationVar) {
@ -344,7 +316,7 @@ void MyAvatar::centerBody() {
// transform this body into world space
auto worldBodyMatrix = _sensorToWorldMatrix * newBodySensorMatrix;
auto worldBodyPos = extractTranslation(worldBodyMatrix);
auto worldBodyRot = glm::normalize(glm::quat_cast(worldBodyMatrix));
auto worldBodyRot = glmExtractRotation(worldBodyMatrix);
if (_characterController.getState() == CharacterController::State::Ground) {
// the avatar's physical aspect thinks it is standing on something
@ -397,7 +369,7 @@ void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) {
// transform this body into world space
auto worldBodyMatrix = _sensorToWorldMatrix * newBodySensorMatrix;
auto worldBodyPos = extractTranslation(worldBodyMatrix);
auto worldBodyRot = glm::normalize(glm::quat_cast(worldBodyMatrix));
auto worldBodyRot = glmExtractRotation(worldBodyMatrix);
// this will become our new position.
setPosition(worldBodyPos);
@ -586,7 +558,7 @@ void MyAvatar::simulate(float deltaTime) {
headPosition = getPosition();
}
head->setPosition(headPosition);
head->setScale(getUniformScale());
head->setScale(getModelScale());
head->simulate(deltaTime);
}
@ -664,7 +636,7 @@ void MyAvatar::updateFromHMDSensorMatrix(const glm::mat4& hmdSensorMatrix) {
}
_hmdSensorPosition = newHmdSensorPosition;
_hmdSensorOrientation = glm::quat_cast(hmdSensorMatrix);
_hmdSensorOrientation = glmExtractRotation(hmdSensorMatrix);
auto headPose = getControllerPoseInSensorFrame(controller::Action::HEAD);
if (headPose.isValid()) {
_headControllerFacing = getFacingDir2D(headPose.rotation);
@ -688,9 +660,11 @@ void MyAvatar::updateJointFromController(controller::Action poseKey, ThreadSafeV
// update sensor to world matrix from current body position and hmd sensor.
// This is so the correct camera can be used for rendering.
void MyAvatar::updateSensorToWorldMatrix() {
// update the sensor mat so that the body position will end up in the desired
// position when driven from the head.
glm::mat4 desiredMat = createMatFromQuatAndPos(getOrientation(), getPosition());
float sensorToWorldScale = getEyeHeight() / getUserEyeHeight();
glm::mat4 desiredMat = createMatFromScaleQuatAndPos(glm::vec3(sensorToWorldScale), getOrientation(), getPosition());
_sensorToWorldMatrix = desiredMat * glm::inverse(_bodySensorMatrix);
lateUpdatePalms();
@ -1002,6 +976,7 @@ void MyAvatar::saveData() {
settings.setValue("collisionSoundURL", _collisionSoundURL);
settings.setValue("useSnapTurn", _useSnapTurn);
settings.setValue("clearOverlayWhenMoving", _clearOverlayWhenMoving);
settings.setValue("userHeight", getUserHeight());
settings.endGroup();
}
@ -1142,6 +1117,7 @@ void MyAvatar::loadData() {
setSnapTurn(settings.value("useSnapTurn", _useSnapTurn).toBool());
setClearOverlayWhenMoving(settings.value("clearOverlayWhenMoving", _clearOverlayWhenMoving).toBool());
setDominantHand(settings.value("dominantHand", _dominantHand).toString().toLower());
setUserHeight(settings.value("userHeight", DEFAULT_AVATAR_HEIGHT).toDouble());
settings.endGroup();
setEnableMeshVisible(Menu::getInstance()->isOptionChecked(MenuOption::MeshVisible));
@ -1247,7 +1223,7 @@ void MyAvatar::updateLookAtTargetAvatar() {
float distanceTo = glm::length(avatar->getHead()->getEyePosition() - cameraPosition);
avatar->setIsLookAtTarget(false);
if (!avatar->isMyAvatar() && avatar->isInitialized() &&
(distanceTo < GREATEST_LOOKING_AT_DISTANCE * getUniformScale())) {
(distanceTo < GREATEST_LOOKING_AT_DISTANCE * getModelScale())) {
float radius = glm::length(avatar->getHead()->getEyePosition() - avatar->getHead()->getRightEyePosition());
float angleTo = coneSphereAngle(getHead()->getEyePosition(), lookForward, avatar->getHead()->getEyePosition(), radius);
if (angleTo < (smallestAngleTo * (isCurrentTarget ? KEEP_LOOKING_AT_CURRENT_ANGLE_FACTOR : 1.0f))) {
@ -1489,7 +1465,7 @@ glm::vec3 MyAvatar::getSkeletonPosition() const {
void MyAvatar::rebuildCollisionShape() {
// compute localAABox
float scale = getUniformScale();
float scale = getModelScale();
float radius = scale * _skeletonModel->getBoundingCapsuleRadius();
float height = scale * _skeletonModel->getBoundingCapsuleHeight() + 2.0f * radius;
glm::vec3 corner(-radius, -0.5f * height, -radius);
@ -1595,6 +1571,7 @@ void MyAvatar::prepareForPhysicsSimulation() {
}
_characterController.handleChangedCollisionGroup();
_characterController.setParentVelocity(parentVelocity);
_characterController.setScaleFactor(getSensorToWorldScale());
_characterController.setPositionAndOrientation(getPosition(), getOrientation());
auto headPose = getControllerPoseInAvatarFrame(controller::Action::HEAD);
@ -1814,11 +1791,11 @@ void MyAvatar::destroyAnimGraph() {
_skeletonModel->getRig().destroyAnimGraph();
}
void MyAvatar::postUpdate(float deltaTime) {
void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) {
Avatar::postUpdate(deltaTime);
Avatar::postUpdate(deltaTime, scene);
if (DependencyManager::get<SceneScriptingInterface>()->shouldRenderAvatars() && _skeletonModel->initWhenReady(qApp->getMain3DScene())) {
if (_skeletonModel->isLoaded() && !_skeletonModel->getRig().getAnimNode()) {
initHeadBones();
_skeletonModel->setCauterizeBoneSet(_headBoneSet);
_fstAnimGraphOverrideUrl = _skeletonModel->getGeometry()->getAnimGraphOverrideUrl();
@ -1930,7 +1907,7 @@ void MyAvatar::preDisplaySide(RenderArgs* renderArgs) {
const float RENDER_HEAD_CUTOFF_DISTANCE = 0.3f;
bool MyAvatar::cameraInsideHead(const glm::vec3& cameraPosition) const {
return glm::length(cameraPosition - getHeadPosition()) < (RENDER_HEAD_CUTOFF_DISTANCE * getUniformScale());
return glm::length(cameraPosition - getHeadPosition()) < (RENDER_HEAD_CUTOFF_DISTANCE * getModelScale());
}
bool MyAvatar::shouldRenderHead(const RenderArgs* renderArgs) const {
@ -1978,38 +1955,8 @@ void MyAvatar::updateOrientation(float deltaTime) {
snapTurn = true;
}
// use head/HMD orientation to turn while flying
if (getCharacterController()->getState() == CharacterController::State::Hover) {
// This is the direction the user desires to fly in.
glm::vec3 desiredFacing = getMyHead()->getHeadOrientation() * Vectors::UNIT_Z;
desiredFacing.y = 0.0f;
// This is our reference frame, it is captured when the user begins to move.
glm::vec3 referenceFacing = transformVectorFast(_sensorToWorldMatrix, _hoverReferenceCameraFacing);
referenceFacing.y = 0.0f;
referenceFacing = glm::normalize(referenceFacing);
glm::vec3 referenceRight(referenceFacing.z, 0.0f, -referenceFacing.x);
const float HOVER_FLY_ROTATION_PERIOD = 0.5f;
float tau = glm::clamp(deltaTime / HOVER_FLY_ROTATION_PERIOD, 0.0f, 1.0f);
// new facing is a linear interpolation between the desired and reference vectors.
glm::vec3 newFacing = glm::normalize((1.0f - tau) * referenceFacing + tau * desiredFacing);
// calcualte the signed delta yaw angle to apply so that we match our newFacing.
float sign = copysignf(1.0f, glm::dot(desiredFacing, referenceRight));
float deltaAngle = sign * acosf(glm::clamp(glm::dot(referenceFacing, newFacing), -1.0f, 1.0f));
// speedFactor is 0 when we are at rest adn 1.0 when we are at max flying speed.
const float MAX_FLYING_SPEED = 30.0f;
float speedFactor = glm::min(glm::length(getVelocity()) / MAX_FLYING_SPEED, 1.0f);
// apply our delta, but scale it by the speed factor, so we turn faster when we are flying faster.
totalBodyYaw += (speedFactor * deltaAngle * (180.0f / PI));
}
// Use head/HMD roll to turn while walking or flying, but not when standing still
if (qApp->isHMDMode() && _hmdRollControlEnabled && hasDriveInput()) {
// Use head/HMD roll to turn while flying, but not when standing still.
if (qApp->isHMDMode() && getCharacterController()->getState() == CharacterController::State::Hover && _hmdRollControlEnabled && hasDriveInput()) {
// Turn with head roll.
const float MIN_CONTROL_SPEED = 0.01f;
float speed = glm::length(getVelocity());
@ -2103,17 +2050,17 @@ void MyAvatar::updateActionMotor(float deltaTime) {
if (state == CharacterController::State::Hover) {
// we're flying --> complex acceleration curve that builds on top of current motor speed and caps at some max speed
float motorSpeed = glm::length(_actionMotorVelocity);
float finalMaxMotorSpeed = getUniformScale() * MAX_ACTION_MOTOR_SPEED;
float finalMaxMotorSpeed = getSensorToWorldScale() * DEFAULT_AVATAR_MAX_FLYING_SPEED;
float speedGrowthTimescale = 2.0f;
float speedIncreaseFactor = 1.8f;
motorSpeed *= 1.0f + glm::clamp(deltaTime / speedGrowthTimescale, 0.0f, 1.0f) * speedIncreaseFactor;
const float maxBoostSpeed = getUniformScale() * MAX_BOOST_SPEED;
const float maxBoostSpeed = getSensorToWorldScale() * MAX_BOOST_SPEED;
if (_isPushing) {
if (motorSpeed < maxBoostSpeed) {
// an active action motor should never be slower than this
float boostCoefficient = (maxBoostSpeed - motorSpeed) / maxBoostSpeed;
motorSpeed += MIN_AVATAR_SPEED * boostCoefficient;
motorSpeed += getSensorToWorldScale() * MIN_AVATAR_SPEED * boostCoefficient;
} else if (motorSpeed > finalMaxMotorSpeed) {
motorSpeed = finalMaxMotorSpeed;
}
@ -2121,7 +2068,7 @@ void MyAvatar::updateActionMotor(float deltaTime) {
_actionMotorVelocity = motorSpeed * direction;
} else {
// we're interacting with a floor --> simple horizontal speed and exponential decay
_actionMotorVelocity = MAX_WALKING_SPEED * direction;
_actionMotorVelocity = getSensorToWorldScale() * DEFAULT_AVATAR_MAX_WALKING_SPEED * direction;
}
float boomChange = getDriveKey(ZOOM);
@ -2135,22 +2082,24 @@ void MyAvatar::updatePosition(float deltaTime) {
}
vec3 velocity = getVelocity();
float sensorToWorldScale = getSensorToWorldScale();
float sensorToWorldScale2 = sensorToWorldScale * sensorToWorldScale;
const float MOVING_SPEED_THRESHOLD_SQUARED = 0.0001f; // 0.01 m/s
if (!_characterController.isEnabledAndReady()) {
// _characterController is not in physics simulation but it can still compute its target velocity
updateMotors();
_characterController.computeNewVelocity(deltaTime, velocity);
float speed2 = glm::length2(velocity);
if (speed2 > MIN_AVATAR_SPEED_SQUARED) {
float speed2 = glm::length(velocity);
if (speed2 > sensorToWorldScale2 * MIN_AVATAR_SPEED_SQUARED) {
// update position ourselves
applyPositionDelta(deltaTime * velocity);
}
measureMotionDerivatives(deltaTime);
_moving = speed2 > MOVING_SPEED_THRESHOLD_SQUARED;
_moving = speed2 > sensorToWorldScale2 * MOVING_SPEED_THRESHOLD_SQUARED;
} else {
float speed2 = glm::length2(velocity);
_moving = speed2 > MOVING_SPEED_THRESHOLD_SQUARED;
_moving = speed2 > sensorToWorldScale2 * MOVING_SPEED_THRESHOLD_SQUARED;
if (_moving) {
// scan for walkability
@ -2161,18 +2110,6 @@ void MyAvatar::updatePosition(float deltaTime) {
_characterController.setStepUpEnabled(result.walkable);
}
}
// capture the head rotation, in sensor space, when the user first indicates they would like to move/fly.
if (!_hoverReferenceCameraFacingIsCaptured &&
(fabs(getDriveKey(TRANSLATE_Z)) > 0.1f || fabs(getDriveKey(TRANSLATE_X)) > 0.1f)) {
_hoverReferenceCameraFacingIsCaptured = true;
// transform the camera facing vector into sensor space.
_hoverReferenceCameraFacing = transformVectorFast(glm::inverse(_sensorToWorldMatrix),
getMyHead()->getHeadOrientation() * Vectors::UNIT_Z);
} else if (_hoverReferenceCameraFacingIsCaptured &&
(fabs(getDriveKey(TRANSLATE_Z)) <= 0.1f && fabs(getDriveKey(TRANSLATE_X)) <= 0.1f)) {
_hoverReferenceCameraFacingIsCaptured = false;
}
}
void MyAvatar::updateCollisionSound(const glm::vec3 &penetration, float deltaTime, float frequency) {
@ -2325,7 +2262,8 @@ void MyAvatar::restrictScaleFromDomainSettings(const QJsonObject& domainSettings
_targetScale = clampedScale;
}
setScale(glm::vec3(_targetScale));
setModelScale(_targetScale);
rebuildCollisionShape();
settings.endGroup();
}
@ -2711,11 +2649,30 @@ glm::mat4 MyAvatar::deriveBodyFromHMDSensor() const {
// Y_180 is necessary because rig is z forward and hmdOrientation is -z forward
glm::vec3 headToNeck = headOrientation * Quaternions::Y_180 * (localNeck - localHead);
glm::vec3 neckToRoot = headOrientationYawOnly * Quaternions::Y_180 * -localNeck;
glm::vec3 bodyPos = headPosition + headToNeck + neckToRoot;
float invSensorToWorldScale = getUserEyeHeight() / getEyeHeight();
glm::vec3 bodyPos = headPosition + invSensorToWorldScale * (headToNeck + neckToRoot);
return createMatFromQuatAndPos(headOrientationYawOnly, bodyPos);
}
float MyAvatar::getUserHeight() const {
return _userHeight.get();
}
void MyAvatar::setUserHeight(float value) {
_userHeight.set(value);
float sensorToWorldScale = getEyeHeight() / getUserEyeHeight();
emit sensorToWorldScaleChanged(sensorToWorldScale);
}
float MyAvatar::getUserEyeHeight() const {
float ratio = DEFAULT_AVATAR_EYE_TO_TOP_OF_HEAD / DEFAULT_AVATAR_HEIGHT;
float userHeight = _userHeight.get();
return userHeight - userHeight * ratio;
}
glm::vec3 MyAvatar::getPositionForAudio() {
switch (_audioListenerMode) {
case AudioListenerMode::FROM_HEAD:
@ -2834,7 +2791,6 @@ bool MyAvatar::FollowHelper::shouldActivateRotation(const MyAvatar& myAvatar, co
}
bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const {
// -z axis of currentBodyMatrix in world space.
glm::vec3 forward = glm::normalize(glm::vec3(-currentBodyMatrix[0][2], -currentBodyMatrix[1][2], -currentBodyMatrix[2][2]));
// x axis of currentBodyMatrix in world space.
@ -2858,7 +2814,6 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar,
}
bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const {
const float CYLINDER_TOP = 0.1f;
const float CYLINDER_BOTTOM = -1.5f;
@ -2886,6 +2841,10 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, const glm::mat
glm::mat4 currentWorldMatrix = myAvatar.getSensorToWorldMatrix() * currentBodyMatrix;
AnimPose followWorldPose(currentWorldMatrix);
// remove scale present from sensorToWorldMatrix
followWorldPose.scale() = glm::vec3(1.0f);
if (isActive(Rotation)) {
followWorldPose.rot() = glmExtractRotation(desiredWorldMatrix);
}
@ -2910,16 +2869,16 @@ glm::mat4 MyAvatar::FollowHelper::postPhysicsUpdate(const MyAvatar& myAvatar, co
// apply follow displacement to the body matrix.
glm::vec3 worldLinearDisplacement = myAvatar.getCharacterController()->getFollowLinearDisplacement();
glm::quat worldAngularDisplacement = myAvatar.getCharacterController()->getFollowAngularDisplacement();
glm::quat sensorToWorld = glmExtractRotation(myAvatar.getSensorToWorldMatrix());
glm::quat worldToSensor = glm::inverse(sensorToWorld);
glm::vec3 sensorLinearDisplacement = worldToSensor * worldLinearDisplacement;
glm::quat sensorAngularDisplacement = worldToSensor * worldAngularDisplacement * sensorToWorld;
glm::mat4 sensorToWorldMatrix = myAvatar.getSensorToWorldMatrix();
glm::mat4 worldToSensorMatrix = glm::inverse(sensorToWorldMatrix);
glm::vec3 sensorLinearDisplacement = transformVectorFast(worldToSensorMatrix, worldLinearDisplacement);
glm::quat sensorAngularDisplacement = glmExtractRotation(worldToSensorMatrix) * worldAngularDisplacement * glmExtractRotation(sensorToWorldMatrix);
glm::mat4 newBodyMat = createMatFromQuatAndPos(sensorAngularDisplacement * glmExtractRotation(currentBodyMatrix),
sensorLinearDisplacement + extractTranslation(currentBodyMatrix));
return newBodyMat;
} else {
return currentBodyMatrix;
}
@ -2977,15 +2936,20 @@ glm::mat4 MyAvatar::computeCameraRelativeHandControllerMatrix(const glm::mat4& c
cameraWorldMatrix *= createMatFromScaleQuatAndPos(vec3(-1.0f, 1.0f, 1.0f), glm::quat(), glm::vec3());
}
// compute a NEW sensorToWorldMatrix for the camera.
// The equation is cameraWorldMatrix = cameraSensorToWorldMatrix * _hmdSensorMatrix.
// here we solve for the unknown cameraSensorToWorldMatrix.
glm::mat4 cameraSensorToWorldMatrix = cameraWorldMatrix * glm::inverse(getHMDSensorMatrix());
// move the camera into sensor space.
glm::mat4 cameraSensorMatrix = glm::inverse(getSensorToWorldMatrix()) * cameraWorldMatrix;
// Using the new cameraSensorToWorldMatrix, compute where the controller is in world space.
glm::mat4 controllerWorldMatrix = cameraSensorToWorldMatrix * controllerSensorMatrix;
// cancel out scale
glm::vec3 scale = extractScale(cameraSensorMatrix);
cameraSensorMatrix = glm::scale(cameraSensorMatrix, 1.0f / scale);
// move it into avatar space
// measure the offset from the hmd and the camera, in sensor space
glm::mat4 delta = cameraSensorMatrix * glm::inverse(getHMDSensorMatrix());
// apply the delta offset to the controller, in sensor space, then transform it into world space.
glm::mat4 controllerWorldMatrix = getSensorToWorldMatrix() * delta * controllerSensorMatrix;
// transform controller into avatar space
glm::mat4 avatarMatrix = createMatFromQuatAndPos(getOrientation(), getPosition());
return glm::inverse(avatarMatrix) * controllerWorldMatrix;
}
@ -3257,3 +3221,12 @@ void MyAvatar::updateHoldActions(const AnimPose& prePhysicsPose, const AnimPose&
const MyHead* MyAvatar::getMyHead() const {
return static_cast<const MyHead*>(getHead());
}
void MyAvatar::setModelScale(float scale) {
bool changed = (scale != getModelScale());
Avatar::setModelScale(scale);
if (changed) {
float sensorToWorldScale = getEyeHeight() / getUserEyeHeight();
emit sensorToWorldScaleChanged(sensorToWorldScale);
}
}

View file

@ -19,9 +19,11 @@
#include <SettingHandle.h>
#include <Rig.h>
#include <Sound.h>
#include <ScriptEngine.h>
#include <controllers/Pose.h>
#include <controllers/Actions.h>
#include <AvatarConstants.h>
#include <avatars-renderer/Avatar.h>
#include <avatars-renderer/ScriptAvatar.h>
@ -102,6 +104,8 @@ class MyAvatar : public Avatar {
* @property collisionsEnabled {bool} This can be used to disable collisions between the avatar and the world.
* @property useAdvancedMovementControls {bool} Stores the user preference only, does not change user mappings, this is done in the defaultScript
* "scripts/system/controllers/toggleAdvancedMovementForHandControllers.js".
* @property userHeight {number} The height of the user in sensor space. (meters).
* @property userEyeHeight {number} Estimated height of the users eyes in sensor space. (meters)
*/
// FIXME: `glm::vec3 position` is not accessible from QML, so this exposes position in a QML-native type
@ -146,6 +150,9 @@ class MyAvatar : public Avatar {
Q_PROPERTY(float hmdRollControlDeadZone READ getHMDRollControlDeadZone WRITE setHMDRollControlDeadZone)
Q_PROPERTY(float hmdRollControlRate READ getHMDRollControlRate WRITE setHMDRollControlRate)
Q_PROPERTY(float userHeight READ getUserHeight WRITE setUserHeight)
Q_PROPERTY(float userEyeHeight READ getUserEyeHeight)
const QString DOMINANT_LEFT_HAND = "left";
const QString DOMINANT_RIGHT_HAND = "right";
@ -169,7 +176,7 @@ public:
~MyAvatar();
void instantiableAvatar() override {};
void registerMetaTypes(QScriptEngine* engine);
void registerMetaTypes(ScriptEnginePointer engine);
virtual void simulateAttachments(float deltaTime) override;
@ -196,7 +203,7 @@ public:
Q_INVOKABLE void clearIKJointLimitHistory(); // thread-safe
void update(float deltaTime);
virtual void postUpdate(float deltaTime) override;
virtual void postUpdate(float deltaTime, const render::ScenePointer& scene) override;
void preDisplaySide(RenderArgs* renderArgs);
const glm::mat4& getHMDSensorMatrix() const { return _hmdSensorMatrix; }
@ -533,6 +540,10 @@ public:
Q_INVOKABLE bool isUp(const glm::vec3& direction) { return glm::dot(direction, _worldUpDirection) > 0.0f; }; // true iff direction points up wrt avatar's definition of up.
Q_INVOKABLE bool isDown(const glm::vec3& direction) { return glm::dot(direction, _worldUpDirection) < 0.0f; };
void setUserHeight(float value);
float getUserHeight() const;
float getUserEyeHeight() const;
public slots:
void increaseSize();
void decreaseSize();
@ -580,6 +591,8 @@ public slots:
glm::vec3 getPositionForAudio();
glm::quat getOrientationForAudio();
virtual void setModelScale(float scale) override;
signals:
void audioListenerModeChanged();
void transformChanged();
@ -592,6 +605,7 @@ signals:
void wentActive();
void skeletonChanged();
void dominantHandChanged(const QString& hand);
void sensorToWorldScaleChanged(float sensorToWorldScale);
private:
@ -712,7 +726,7 @@ private:
float _hmdRollControlRate { ROLL_CONTROL_RATE_DEFAULT };
float _lastDrivenSpeed { 0.0f };
// working copies -- see AvatarData for thread-safe _sensorToWorldMatrixCache, used for outward facing access
// working copy -- see AvatarData for thread-safe _sensorToWorldMatrixCache, used for outward facing access
glm::mat4 _sensorToWorldMatrix { glm::mat4() };
// cache of the current HMD sensor position and orientation in sensor space.
@ -778,8 +792,6 @@ private:
AtRestDetector _hmdAtRestDetector;
bool _lastIsMoving { false };
bool _hoverReferenceCameraFacingIsCaptured { false };
glm::vec3 _hoverReferenceCameraFacing { 0.0f, 0.0f, -1.0f }; // hmd sensor space
// all poses are in sensor-frame
std::map<controller::Action, controller::Pose> _controllerPoseMap;
@ -806,6 +818,9 @@ private:
void setAway(bool value);
std::vector<int> _pinnedJoints;
// height of user in sensor space, when standing erect.
ThreadSafeValueCache<float> _userHeight { DEFAULT_AVATAR_HEIGHT };
};
QScriptValue audioListenModeToScriptValue(QScriptEngine* engine, const AudioListenerMode& audioListenerMode);

View file

@ -148,7 +148,7 @@ void MySkeletonModel::updateRig(float deltaTime, glm::mat4 parentTransform) {
Rig::CharacterControllerState ccState = convertCharacterControllerState(myAvatar->getCharacterController()->getState());
auto velocity = myAvatar->getLocalVelocity();
auto velocity = myAvatar->getLocalVelocity() / myAvatar->getSensorToWorldScale();
auto position = myAvatar->getLocalPosition();
auto orientation = myAvatar->getLocalOrientation();
_rig.computeMotionAnimationState(deltaTime, position, velocity, orientation, ccState);

View file

@ -176,3 +176,28 @@ void Ledger::resetFailure(QNetworkReply& reply) { failResponse("reset", reply);
void Ledger::reset() {
send("reset_user_hfc_account", "resetSuccess", "resetFailure", QNetworkAccessManager::PutOperation, QJsonObject());
}
void Ledger::accountSuccess(QNetworkReply& reply) {
// lets set the appropriate stuff in the wallet now
auto wallet = DependencyManager::get<Wallet>();
QByteArray response = reply.readAll();
QJsonObject data = QJsonDocument::fromJson(response).object()["data"].toObject();
auto salt = QByteArray::fromBase64(data["salt"].toString().toUtf8());
auto iv = QByteArray::fromBase64(data["iv"].toString().toUtf8());
auto ckey = QByteArray::fromBase64(data["ckey"].toString().toUtf8());
wallet->setSalt(salt);
wallet->setIv(iv);
wallet->setCKey(ckey);
// none of the hfc account info should be emitted
emit accountResult(QJsonObject{ {"status", "success"} });
}
void Ledger::accountFailure(QNetworkReply& reply) {
failResponse("account", reply);
}
void Ledger::account() {
send("hfc_account", "accountSuccess", "accountFailure", QNetworkAccessManager::PutOperation, QJsonObject());
}

View file

@ -29,6 +29,7 @@ public:
void balance(const QStringList& keys);
void inventory(const QStringList& keys);
void history(const QStringList& keys);
void account();
void reset();
signals:
@ -37,6 +38,7 @@ signals:
void balanceResult(QJsonObject result);
void inventoryResult(QJsonObject result);
void historyResult(QJsonObject result);
void accountResult(QJsonObject result);
public slots:
void buySuccess(QNetworkReply& reply);
@ -51,6 +53,8 @@ public slots:
void historyFailure(QNetworkReply& reply);
void resetSuccess(QNetworkReply& reply);
void resetFailure(QNetworkReply& reply);
void accountSuccess(QNetworkReply& reply);
void accountFailure(QNetworkReply& reply);
private:
QJsonObject apiResponse(const QString& label, QNetworkReply& reply);

View file

@ -27,6 +27,7 @@ QmlCommerce::QmlCommerce(QQuickItem* parent) : OffscreenQmlDialog(parent) {
connect(wallet.data(), &Wallet::securityImageResult, this, &QmlCommerce::securityImageResult);
connect(ledger.data(), &Ledger::historyResult, this, &QmlCommerce::historyResult);
connect(wallet.data(), &Wallet::keyFilePathIfExistsResult, this, &QmlCommerce::keyFilePathIfExistsResult);
connect(ledger.data(), &Ledger::accountResult, this, &QmlCommerce::accountResult);
}
void QmlCommerce::getLoginStatus() {
@ -86,7 +87,7 @@ void QmlCommerce::history() {
void QmlCommerce::setPassphrase(const QString& passphrase) {
auto wallet = DependencyManager::get<Wallet>();
if (wallet->getPassphrase() && !wallet->getPassphrase()->isEmpty()) {
if(wallet->getPassphrase() && !wallet->getPassphrase()->isEmpty() && !passphrase.isEmpty()) {
wallet->changePassphrase(passphrase);
} else {
wallet->setPassphrase(passphrase);
@ -94,9 +95,20 @@ void QmlCommerce::setPassphrase(const QString& passphrase) {
getWalletAuthenticatedStatus();
}
void QmlCommerce::generateKeyPair() {
auto wallet = DependencyManager::get<Wallet>();
wallet->generateKeyPair();
getWalletAuthenticatedStatus();
}
void QmlCommerce::reset() {
auto ledger = DependencyManager::get<Ledger>();
auto wallet = DependencyManager::get<Wallet>();
ledger->reset();
wallet->reset();
}
void QmlCommerce::account() {
auto ledger = DependencyManager::get<Ledger>();
ledger->account();
}

View file

@ -39,6 +39,7 @@ signals:
void balanceResult(QJsonObject result);
void inventoryResult(QJsonObject result);
void historyResult(QJsonObject result);
void accountResult(QJsonObject result);
protected:
Q_INVOKABLE void getLoginStatus();
@ -53,8 +54,9 @@ protected:
Q_INVOKABLE void balance();
Q_INVOKABLE void inventory();
Q_INVOKABLE void history();
Q_INVOKABLE void generateKeyPair();
Q_INVOKABLE void reset();
Q_INVOKABLE void account();
};
#endif // hifi_QmlCommerce_h

View file

@ -18,10 +18,12 @@
#include <PathUtils.h>
#include <OffscreenUi.h>
#include <AccountManager.h>
#include <QFile>
#include <QCryptographicHash>
#include <QQmlContext>
#include <QBuffer>
#include <openssl/ssl.h>
#include <openssl/err.h>
@ -31,8 +33,16 @@
#include <openssl/evp.h>
#include <openssl/aes.h>
// I know, right? But per https://www.openssl.org/docs/faq.html
// this avoids OPENSSL_Uplink(00007FF847238000,08): no OPENSSL_Applink
// at runtime.
#ifdef Q_OS_WIN
#include <openssl/applink.c>
#endif
static const char* KEY_FILE = "hifikey";
static const char* IMAGE_FILE = "hifi_image"; // eventually this will live in keyfile
static const char* IMAGE_HEADER = "-----BEGIN SECURITY IMAGE-----\n";
static const char* IMAGE_FOOTER = "-----END SECURITY IMAGE-----\n";
void initialize() {
static bool initialized = false;
@ -45,19 +55,19 @@ void initialize() {
}
QString keyFilePath() {
return PathUtils::getAppDataFilePath(KEY_FILE);
}
QString imageFilePath() {
return PathUtils::getAppDataFilePath(IMAGE_FILE);
auto accountManager = DependencyManager::get<AccountManager>();
return PathUtils::getAppDataFilePath(QString("%1.%2").arg(accountManager->getAccountInfo().getUsername(), KEY_FILE));
}
// use the cached _passphrase if it exists, otherwise we need to prompt
int passwordCallback(char* password, int maxPasswordSize, int rwFlag, void* u) {
// just return a hardcoded pwd for now
auto passphrase = DependencyManager::get<Wallet>()->getPassphrase();
auto wallet = DependencyManager::get<Wallet>();
auto passphrase = wallet->getPassphrase();
if (passphrase && !passphrase->isEmpty()) {
strcpy(password, passphrase->toLocal8Bit().constData());
QString saltedPassphrase(*passphrase);
saltedPassphrase.append(wallet->getSalt());
strcpy(password, saltedPassphrase.toUtf8().constData());
return static_cast<int>(passphrase->size());
} else {
// this shouldn't happen - so lets log it to tell us we have
@ -121,13 +131,12 @@ bool writeKeys(const char* filename, RSA* keys) {
return retval;
}
// BEGIN copied code - this will be removed/changed at some point soon
// copied (without emits for various signals) from libraries/networking/src/RSAKeypairGenerator.cpp.
// We will have a different implementation in practice, but this gives us a start for now
//
// NOTE: we don't really use the private keys returned - we can see how this evolves, but probably
// TODO: we don't really use the private keys returned - we can see how this evolves, but probably
// we should just return a list of public keys?
// or perhaps return the RSA* instead?
QPair<QByteArray*, QByteArray*> generateRSAKeypair() {
RSA* keyPair = RSA_new();
@ -245,6 +254,8 @@ RSA* readPrivateKey(const char* filename) {
} else {
qCDebug(commerce) << "couldn't parse" << filename;
// if the passphrase is wrong, then let's not cache it
DependencyManager::get<Wallet>()->setPassphrase("");
}
fclose(fp);
} else {
@ -252,13 +263,21 @@ RSA* readPrivateKey(const char* filename) {
}
return key;
}
static const unsigned char IVEC[16] = "IAmAnIVecYay123";
// QT's QByteArray will convert to Base64 without any embedded newlines. This just
// writes it with embedded newlines, which is more readable.
void outputBase64WithNewlines(QFile& file, const QByteArray& b64Array) {
for (int i = 0; i < b64Array.size(); i += 64) {
file.write(b64Array.mid(i, 64));
file.write("\n");
}
}
void initializeAESKeys(unsigned char* ivec, unsigned char* ckey, const QByteArray& salt) {
// first ivec
memcpy(ivec, IVEC, 16);
auto hash = QCryptographicHash::hash(salt, QCryptographicHash::Sha256);
memcpy(ckey, hash.data(), 32);
// use the ones in the wallet
auto wallet = DependencyManager::get<Wallet>();
memcpy(ivec, wallet->getIv(), 16);
memcpy(ckey, wallet->getCKey(), 32);
}
Wallet::~Wallet() {
@ -273,13 +292,10 @@ void Wallet::setPassphrase(const QString& passphrase) {
}
_passphrase = new QString(passphrase);
// no matter what, we now need to clear the keys as they
// need to be read using this passphrase
_publicKeys.clear();
}
// encrypt some stuff
bool Wallet::encryptFile(const QString& inputFilePath, const QString& outputFilePath) {
bool Wallet::writeSecurityImage(const QPixmap* pixmap, const QString& outputFilePath) {
// aes requires a couple 128-bit keys (ckey and ivec). For now, I'll just
// use the md5 of the salt as the ckey (md5 is 128-bit), and ivec will be
// a constant. We can review this later - there are ways to generate keys
@ -290,16 +306,12 @@ bool Wallet::encryptFile(const QString& inputFilePath, const QString& outputFile
initializeAESKeys(ivec, ckey, _salt);
int tempSize, outSize;
QByteArray inputFileBuffer;
QBuffer buffer(&inputFileBuffer);
buffer.open(QIODevice::WriteOnly);
// read entire unencrypted file into memory
QFile inputFile(inputFilePath);
if (!inputFile.exists()) {
qCDebug(commerce) << "cannot encrypt" << inputFilePath << "file doesn't exist";
return false;
}
inputFile.open(QIODevice::ReadOnly);
QByteArray inputFileBuffer = inputFile.readAll();
inputFile.close();
// another spot where we are assuming only jpgs
pixmap->save(&buffer, "jpg");
// reserve enough capacity for encrypted bytes
unsigned char* outputFileBuffer = new unsigned char[inputFileBuffer.size() + AES_BLOCK_SIZE];
@ -328,16 +340,21 @@ bool Wallet::encryptFile(const QString& inputFilePath, const QString& outputFile
EVP_CIPHER_CTX_free(ctx);
qCDebug(commerce) << "encrypted buffer size" << outSize;
QByteArray output((const char*)outputFileBuffer, outSize);
// now APPEND to the file,
QByteArray b64output = output.toBase64();
QFile outputFile(outputFilePath);
outputFile.open(QIODevice::WriteOnly);
outputFile.write(output);
outputFile.open(QIODevice::Append);
outputFile.write(IMAGE_HEADER);
outputBase64WithNewlines(outputFile, b64output);
outputFile.write(IMAGE_FOOTER);
outputFile.close();
delete[] outputFileBuffer;
return true;
}
bool Wallet::decryptFile(const QString& inputFilePath, unsigned char** outputBufferPtr, int* outputBufferSize) {
bool Wallet::readSecurityImage(const QString& inputFilePath, unsigned char** outputBufferPtr, int* outputBufferSize) {
unsigned char ivec[16];
unsigned char ckey[32];
initializeAESKeys(ivec, ckey, _salt);
@ -348,9 +365,31 @@ bool Wallet::decryptFile(const QString& inputFilePath, unsigned char** outputBuf
qCDebug(commerce) << "cannot decrypt file" << inputFilePath << "it doesn't exist";
return false;
}
inputFile.open(QIODevice::ReadOnly);
QByteArray encryptedBuffer = inputFile.readAll();
inputFile.open(QIODevice::ReadOnly | QIODevice::Text);
bool foundHeader = false;
bool foundFooter = false;
QByteArray base64EncryptedBuffer;
while (!inputFile.atEnd()) {
QString line(inputFile.readLine());
if (!foundHeader) {
foundHeader = (line == IMAGE_HEADER);
} else {
foundFooter = (line == IMAGE_FOOTER);
if (!foundFooter) {
base64EncryptedBuffer.append(line);
}
}
}
inputFile.close();
if (! (foundHeader && foundFooter)) {
qCDebug(commerce) << "couldn't parse" << inputFilePath << foundHeader << foundFooter;
return false;
}
// convert to bytes
auto encryptedBuffer = QByteArray::fromBase64(base64EncryptedBuffer);
// setup decrypted buffer
unsigned char* outputBuffer = new unsigned char[encryptedBuffer.size()];
@ -413,30 +452,15 @@ bool Wallet::walletIsAuthenticatedWithPassphrase() {
return false;
}
bool Wallet::createIfNeeded() {
if (_publicKeys.count() > 0) return false;
bool Wallet::generateKeyPair() {
// FIXME: initialize OpenSSL elsewhere soon
initialize();
// try to read existing keys if they exist...
auto publicKey = readPublicKey(keyFilePath().toStdString().c_str());
if (publicKey.size() > 0) {
if (auto key = readPrivateKey(keyFilePath().toStdString().c_str()) ) {
qCDebug(commerce) << "read private key";
RSA_free(key);
// K -- add the public key since we have a legit private key associated with it
_publicKeys.push_back(publicKey.toBase64());
return false;
}
}
qCInfo(commerce) << "Creating wallet.";
return generateKeyPair();
}
bool Wallet::generateKeyPair() {
qCInfo(commerce) << "Generating keypair.";
auto keyPair = generateRSAKeypair();
// TODO: redo this soon -- need error checking and so on
writeSecurityImage(_securityImage, keyFilePath());
sendKeyFilePathIfExists();
QString oldKey = _publicKeys.count() == 0 ? "" : _publicKeys.last();
QString key = keyPair.first->toBase64();
@ -453,7 +477,6 @@ bool Wallet::generateKeyPair() {
QStringList Wallet::listPublicKeys() {
qCInfo(commerce) << "Enumerating public keys.";
createIfNeeded();
return _publicKeys;
}
@ -503,27 +526,30 @@ void Wallet::chooseSecurityImage(const QString& filename) {
if (_securityImage) {
delete _securityImage;
}
// temporary...
QString path = qApp->applicationDirPath();
path.append("/resources/qml/hifi/commerce/wallet/");
path.append(filename);
// now create a new security image pixmap
_securityImage = new QPixmap();
qCDebug(commerce) << "loading data for pixmap from" << path;
_securityImage->load(path);
// encrypt it and save.
if (encryptFile(path, imageFilePath())) {
qCDebug(commerce) << "emitting pixmap";
updateImageProvider();
// update the image now
updateImageProvider();
// we could be choosing the _inital_ security image. If so, there
// will be no hifikey file yet. If that is the case, we are done. If
// there _is_ a keyfile, we need to update it (similar to changing the
// passphrase, we need to do so into a temp file and move it).
if (!QFile(keyFilePath()).exists()) {
emit securityImageResult(true);
} else {
qCDebug(commerce) << "failed to encrypt security image";
emit securityImageResult(false);
return;
}
bool success = writeWallet();
emit securityImageResult(success);
}
void Wallet::getSecurityImage() {
@ -536,10 +562,11 @@ void Wallet::getSecurityImage() {
return;
}
// decrypt and return
QString filePath(imageFilePath());
QFileInfo fileInfo(filePath);
if (fileInfo.exists() && decryptFile(filePath, &data, &dataLen)) {
bool success = false;
// decrypt and return. Don't bother if we have no file to decrypt, or
// no salt set yet.
QFileInfo fileInfo(keyFilePath());
if (fileInfo.exists() && _salt.size() > 0 && readSecurityImage(keyFilePath(), &data, &dataLen)) {
// create the pixmap
_securityImage = new QPixmap();
_securityImage->loadFromData(data, dataLen, "jpg");
@ -548,11 +575,9 @@ void Wallet::getSecurityImage() {
updateImageProvider();
delete[] data;
emit securityImageResult(true);
} else {
qCDebug(commerce) << "failed to decrypt security image (maybe none saved yet?)";
emit securityImageResult(false);
success = true;
}
emit securityImageResult(success);
}
void Wallet::sendKeyFilePathIfExists() {
QString filePath(keyFilePath());
@ -572,42 +597,51 @@ void Wallet::reset() {
// tell the provider we got nothing
updateImageProvider();
delete _passphrase;
_passphrase->clear();
// for now we need to maintain the hard-coded passphrase.
// FIXME: remove this line as part of wiring up the passphrase
// and probably set it to nullptr
_passphrase = new QString("pwd");
QFile keyFile(keyFilePath());
QFile imageFile(imageFilePath());
keyFile.remove();
imageFile.remove();
}
bool Wallet::writeWallet(const QString& newPassphrase) {
RSA* keys = readKeys(keyFilePath().toStdString().c_str());
if (keys) {
// we read successfully, so now write to a new temp file
QString tempFileName = QString("%1.%2").arg(keyFilePath(), QString("temp"));
QString oldPassphrase = *_passphrase;
if (!newPassphrase.isEmpty()) {
setPassphrase(newPassphrase);
}
if (writeKeys(tempFileName.toStdString().c_str(), keys)) {
if (writeSecurityImage(_securityImage, tempFileName)) {
// ok, now move the temp file to the correct spot
QFile(QString(keyFilePath())).remove();
QFile(tempFileName).rename(QString(keyFilePath()));
qCDebug(commerce) << "wallet written successfully";
return true;
} else {
qCDebug(commerce) << "couldn't write security image to temp wallet";
}
} else {
qCDebug(commerce) << "couldn't write keys to temp wallet";
}
// if we are here, we failed, so cleanup
QFile(tempFileName).remove();
if (!newPassphrase.isEmpty()) {
setPassphrase(oldPassphrase);
}
} else {
qCDebug(commerce) << "couldn't read wallet - bad passphrase?";
// TODO: review this, but it seems best to reset the passphrase
// since we couldn't decrypt the existing wallet (or is doesn't
// exist perhaps).
setPassphrase("");
}
return false;
}
bool Wallet::changePassphrase(const QString& newPassphrase) {
qCDebug(commerce) << "changing passphrase";
RSA* keys = readKeys(keyFilePath().toStdString().c_str());
if (keys) {
// we read successfully, so now write to a new temp file
// save old passphrase just in case
// TODO: force re-enter?
QString oldPassphrase = *_passphrase;
setPassphrase(newPassphrase);
QString tempFileName = QString("%1.%2").arg(keyFilePath(), QString("temp"));
if (writeKeys(tempFileName.toStdString().c_str(), keys)) {
// ok, now move the temp file to the correct spot
QFile(QString(keyFilePath())).remove();
QFile(tempFileName).rename(QString(keyFilePath()));
qCDebug(commerce) << "passphrase changed successfully";
return true;
} else {
qCDebug(commerce) << "couldn't write keys";
QFile(tempFileName).remove();
setPassphrase(oldPassphrase);
return false;
}
}
qCDebug(commerce) << "couldn't read keys";
return false;
return writeWallet(newPassphrase);
}

View file

@ -26,7 +26,6 @@ public:
~Wallet();
// These are currently blocking calls, although they might take a moment.
bool createIfNeeded();
bool generateKeyPair();
QStringList listPublicKeys();
QString signWithKey(const QByteArray& text, const QString& key);
@ -36,6 +35,10 @@ public:
void setSalt(const QByteArray& salt) { _salt = salt; }
QByteArray getSalt() { return _salt; }
void setIv(const QByteArray& iv) { _iv = iv; }
QByteArray getIv() { return _iv; }
void setCKey(const QByteArray& ckey) { _ckey = ckey; }
QByteArray getCKey() { return _ckey; }
void setPassphrase(const QString& passphrase);
QString* getPassphrase() { return _passphrase; }
@ -52,12 +55,15 @@ signals:
private:
QStringList _publicKeys{};
QPixmap* _securityImage { nullptr };
QByteArray _salt {"iamsalt!"};
QByteArray _salt;
QByteArray _iv;
QByteArray _ckey;
QString* _passphrase { new QString("") };
bool writeWallet(const QString& newPassphrase = QString(""));
void updateImageProvider();
bool encryptFile(const QString& inputFilePath, const QString& outputFilePath);
bool decryptFile(const QString& inputFilePath, unsigned char** outputBufferPtr, int* outputBufferLen);
bool writeSecurityImage(const QPixmap* pixmap, const QString& outputFilePath);
bool readSecurityImage(const QString& inputFilePath, unsigned char** outputBufferPtr, int* outputBufferLen);
};
#endif // hifi_Wallet_h

View file

@ -144,25 +144,33 @@ int main(int argc, const char* argv[]) {
#endif
}
// FIXME this method of checking the OpenGL version screws up the `QOpenGLContext::globalShareContext()` value, which in turn
// leads to crashes when creating the real OpenGL instance. Disabling for now until we come up with a better way of checking
// the GL version on the system without resorting to creating a full Qt application
#if 0
// Check OpenGL version.
// This is done separately from the main Application so that start-up and shut-down logic within the main Application is
// not made more complicated than it already is.
bool override = false;
bool overrideGLCheck = false;
QJsonObject glData;
{
OpenGLVersionChecker openGLVersionChecker(argc, const_cast<char**>(argv));
bool valid = true;
glData = openGLVersionChecker.checkVersion(valid, override);
glData = openGLVersionChecker.checkVersion(valid, overrideGLCheck);
if (!valid) {
if (override) {
if (overrideGLCheck) {
auto glVersion = glData["version"].toString();
qCDebug(interfaceapp, "Running on insufficient OpenGL version: %s.", glVersion.toStdString().c_str());
qCWarning(interfaceapp, "Running on insufficient OpenGL version: %s.", glVersion.toStdString().c_str());
} else {
qCDebug(interfaceapp, "Early exit due to OpenGL version.");
qCWarning(interfaceapp, "Early exit due to OpenGL version.");
return 0;
}
}
}
#endif
// Debug option to demonstrate that the client's local time does not
// need to be in sync with any other network node. This forces clock
@ -223,8 +231,9 @@ int main(int argc, const char* argv[]) {
Application app(argcExtended, const_cast<char**>(argvExtended.data()), startupTime, runningMarkerExisted);
#if 0
// If we failed the OpenGLVersion check, log it.
if (override) {
if (overrideGLcheck) {
auto accountManager = DependencyManager::get<AccountManager>();
if (accountManager->isLoggedIn()) {
UserActivityLogger::getInstance().insufficientGLVersion(glData);
@ -238,6 +247,8 @@ int main(int argc, const char* argv[]) {
});
}
}
#endif
// Setup local server
QLocalServer server { &app };

View file

@ -36,7 +36,7 @@ const PickRay JointRayPick::getPickRay(bool& valid) const {
glm::quat rot = useAvatarHead ? jointRot * glm::angleAxis(-PI / 2.0f, Vectors::RIGHT) : avatarRot * jointRot;
// Apply offset
pos = pos + (rot * _posOffset);
pos = pos + (rot * (myAvatar->getSensorToWorldScale() * _posOffset));
glm::vec3 dir = rot * glm::normalize(_dirOffset);
valid = true;

View file

@ -143,15 +143,16 @@ void LaserPointer::updateRenderState(const RenderState& renderState, const Inter
}
if (!renderState.getEndID().isNull()) {
QVariantMap endProps;
glm::quat faceAvatarRotation = DependencyManager::get<AvatarManager>()->getMyAvatar()->getOrientation() * glm::quat(glm::radians(glm::vec3(0.0f, 180.0f, 0.0f)));
if (_centerEndY) {
endProps.insert("position", end);
} else {
glm::vec3 dim = vec3FromVariant(qApp->getOverlays().getProperty(renderState.getEndID(), "dimensions").value);
endProps.insert("position", vec3toVariant(endVec + glm::vec3(0, 0.5f * dim.y, 0)));
glm::vec3 currentUpVector = faceAvatarRotation * Vectors::UP;
endProps.insert("position", vec3toVariant(endVec + glm::vec3(currentUpVector.x * 0.5f * dim.y, currentUpVector.y * 0.5f * dim.y, currentUpVector.z * 0.5f * dim.y)));
}
if (_faceAvatar) {
glm::quat rotation = glm::inverse(glm::quat_cast(glm::lookAt(endVec, DependencyManager::get<AvatarManager>()->getMyAvatar()->getPosition(), Vectors::UP)));
endProps.insert("rotation", quatToVariant(glm::quat(glm::radians(glm::vec3(0, glm::degrees(safeEulerAngles(rotation)).y, 0)))));
endProps.insert("rotation", quatToVariant(faceAvatarRotation));
}
endProps.insert("visible", true);
endProps.insert("ignoreRayIntersection", renderState.doesEndIgnoreRays());

View file

@ -108,4 +108,4 @@ void RayPickScriptingInterface::setIgnoreAvatars(QUuid uid, const QScriptValue&
void RayPickScriptingInterface::setIncludeAvatars(QUuid uid, const QScriptValue& includeAvatars) {
qApp->getRayPickManager().setIncludeAvatars(uid, includeAvatars);
}
}

View file

@ -37,6 +37,22 @@ Setting::Handle<QString>& getSetting(bool contextIsHMD, QAudio::Mode mode) {
}
}
enum AudioDeviceRole {
DeviceNameRole = Qt::UserRole,
SelectedDesktopRole,
SelectedHMDRole,
PeakRole,
InfoRole
};
QHash<int, QByteArray> AudioDeviceList::_roles {
{ DeviceNameRole, "devicename" },
{ SelectedDesktopRole, "selectedDesktop" },
{ SelectedHMDRole, "selectedHMD" },
{ PeakRole, "peak" },
{ InfoRole, "info" }
};
static QString getTargetDevice(bool hmd, QAudio::Mode mode) {
QString deviceName;
auto& setting = getSetting(hmd, mode);
@ -52,13 +68,6 @@ static QString getTargetDevice(bool hmd, QAudio::Mode mode) {
return deviceName;
}
QHash<int, QByteArray> AudioDeviceList::_roles {
{ AudioDeviceList::DeviceNameRole, "devicename" },
{ AudioDeviceList::SelectedDesktopRole, "selectedDesktop" },
{ AudioDeviceList::SelectedHMDRole, "selectedHMD" },
{ AudioDeviceList::DeviceInfoRole, "info" }
};
Qt::ItemFlags AudioDeviceList::_flags { Qt::ItemIsSelectable | Qt::ItemIsEnabled };
AudioDeviceList::AudioDeviceList(QAudio::Mode mode) : _mode(mode) {
@ -109,7 +118,7 @@ AudioDeviceList::~AudioDeviceList() {
}
QVariant AudioDeviceList::data(const QModelIndex& index, int role) const {
if (!index.isValid() || index.row() >= _devices.size()) {
if (!index.isValid() || index.row() >= rowCount()) {
return QVariant();
}
@ -208,11 +217,41 @@ void AudioDeviceList::onDevicesChanged(const QList<QAudioDeviceInfo>& devices, b
endResetModel();
}
bool AudioInputDeviceList::peakValuesAvailable() {
std::call_once(_peakFlag, [&] {
_peakValuesAvailable = DependencyManager::get<AudioClient>()->peakValuesAvailable();
});
return _peakValuesAvailable;
}
void AudioInputDeviceList::setPeakValuesEnabled(bool enable) {
if (peakValuesAvailable() && (enable != _peakValuesEnabled)) {
DependencyManager::get<AudioClient>()->enablePeakValues(enable);
_peakValuesEnabled = enable;
emit peakValuesEnabledChanged(_peakValuesEnabled);
}
}
void AudioInputDeviceList::onPeakValueListChanged(const QList<float>& peakValueList) {
assert(_mode == QAudio::AudioInput);
if (peakValueList.length() != rowCount()) {
qWarning() << "AudioDeviceList" << __FUNCTION__ << "length mismatch";
}
for (auto i = 0; i < rowCount(); ++i) {
std::static_pointer_cast<AudioInputDevice>(_devices[i])->peak = peakValueList[i];
}
emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, 0), { PeakRole });
}
AudioDevices::AudioDevices(bool& contextIsHMD) : _contextIsHMD(contextIsHMD) {
auto client = DependencyManager::get<AudioClient>();
connect(client.data(), &AudioClient::deviceChanged, this, &AudioDevices::onDeviceChanged, Qt::QueuedConnection);
connect(client.data(), &AudioClient::devicesChanged, this, &AudioDevices::onDevicesChanged, Qt::QueuedConnection);
connect(client.data(), &AudioClient::peakValueListChanged, &_inputs, &AudioInputDeviceList::onPeakValueListChanged, Qt::QueuedConnection);
_inputs.onDeviceChanged(client->getActiveAudioDevice(QAudio::AudioInput), contextIsHMD);
_outputs.onDeviceChanged(client->getActiveAudioDevice(QAudio::AudioOutput), contextIsHMD);

View file

@ -12,6 +12,9 @@
#ifndef hifi_scripting_AudioDevices_h
#define hifi_scripting_AudioDevices_h
#include <memory>
#include <mutex>
#include <QObject>
#include <QAbstractListModel>
#include <QAudioDeviceInfo>
@ -29,16 +32,12 @@ public:
class AudioDeviceList : public QAbstractListModel {
Q_OBJECT
enum AudioDeviceRoles {
DeviceNameRole = Qt::UserRole + 1,
SelectedDesktopRole,
SelectedHMDRole,
DeviceInfoRole
};
public:
AudioDeviceList(QAudio::Mode mode);
virtual ~AudioDeviceList();
AudioDeviceList(QAudio::Mode mode = QAudio::AudioOutput) : _mode(mode) {}
~AudioDeviceList() = default;
virtual std::shared_ptr<AudioDevice> newDevice(const AudioDevice& device)
{ return std::make_shared<AudioDevice>(device); }
int rowCount(const QModelIndex& parent = QModelIndex()) const override { Q_UNUSED(parent); return _devices.size(); }
QHash<int, QByteArray> roleNames() const override { return _roles; }
@ -53,11 +52,11 @@ public:
signals:
void deviceChanged(const QAudioDeviceInfo& device);
private slots:
protected slots:
void onDeviceChanged(const QAudioDeviceInfo& device, bool isHMD);
void onDevicesChanged(const QList<QAudioDeviceInfo>& devices, bool isHMD);
private:
protected:
friend class AudioDevices;
static QHash<int, QByteArray> _roles;
@ -65,16 +64,53 @@ private:
const QAudio::Mode _mode;
QAudioDeviceInfo _selectedDesktopDevice;
QAudioDeviceInfo _selectedHMDDevice;
QList<AudioDevice> _devices;
QList<std::shared_ptr<AudioDevice>> _devices;
QString _hmdSavedDeviceName;
QString _desktopSavedDeviceName;
};
class AudioInputDevice : public AudioDevice {
public:
AudioInputDevice(const AudioDevice& device) : AudioDevice(device) {}
float peak { 0.0f };
};
class AudioInputDeviceList : public AudioDeviceList {
Q_OBJECT
Q_PROPERTY(bool peakValuesAvailable READ peakValuesAvailable)
Q_PROPERTY(bool peakValuesEnabled READ peakValuesEnabled WRITE setPeakValuesEnabled NOTIFY peakValuesEnabledChanged)
public:
AudioInputDeviceList() : AudioDeviceList(QAudio::AudioInput) {}
virtual ~AudioInputDeviceList() = default;
virtual std::shared_ptr<AudioDevice> newDevice(const AudioDevice& device) override
{ return std::make_shared<AudioInputDevice>(device); }
QVariant data(const QModelIndex& index, int role) const override;
signals:
void peakValuesEnabledChanged(bool enabled);
protected slots:
void onPeakValueListChanged(const QList<float>& peakValueList);
protected:
friend class AudioDevices;
bool peakValuesAvailable();
std::once_flag _peakFlag;
bool _peakValuesAvailable;
bool peakValuesEnabled() const { return _peakValuesEnabled; }
void setPeakValuesEnabled(bool enable);
bool _peakValuesEnabled { false };
};
class Audio;
class AudioDevices : public QObject {
Q_OBJECT
Q_PROPERTY(AudioDeviceList* input READ getInputList NOTIFY nop)
Q_PROPERTY(AudioInputDeviceList* input READ getInputList NOTIFY nop)
Q_PROPERTY(AudioDeviceList* output READ getOutputList NOTIFY nop)
public:
@ -97,10 +133,10 @@ private slots:
private:
friend class Audio;
AudioDeviceList* getInputList() { return &_inputs; }
AudioInputDeviceList* getInputList() { return &_inputs; }
AudioDeviceList* getOutputList() { return &_outputs; }
AudioDeviceList _inputs { QAudio::AudioInput };
AudioInputDeviceList _inputs;
AudioDeviceList _outputs { QAudio::AudioOutput };
QAudioDeviceInfo _requestedOutputDevice;
QAudioDeviceInfo _requestedInputDevice;

View file

@ -151,7 +151,7 @@ glm::vec3 HMDScriptingInterface::getPosition() const {
glm::quat HMDScriptingInterface::getOrientation() const {
if (qApp->getActiveDisplayPlugin()->isHmd()) {
return glm::normalize(glm::quat_cast(getWorldHMDMatrix()));
return glmExtractRotation(getWorldHMDMatrix());
}
return glm::quat();
}

View file

@ -61,7 +61,7 @@ void _writeLines(const QString& filename, const QList<QString>& lines) {
QTextStream(&file) << json;
}
JSConsole::JSConsole(QWidget* parent, const QSharedPointer<ScriptEngine>& scriptEngine) :
JSConsole::JSConsole(QWidget* parent, const ScriptEnginePointer& scriptEngine) :
QWidget(parent),
_ui(new Ui::Console),
_currentCommandInHistory(NO_CURRENT_HISTORY_COMMAND),
@ -97,7 +97,7 @@ JSConsole::~JSConsole() {
delete _ui;
}
void JSConsole::setScriptEngine(const QSharedPointer<ScriptEngine>& scriptEngine) {
void JSConsole::setScriptEngine(const ScriptEnginePointer& scriptEngine) {
if (_scriptEngine == scriptEngine && scriptEngine != NULL) {
return;
}
@ -111,7 +111,7 @@ void JSConsole::setScriptEngine(const QSharedPointer<ScriptEngine>& scriptEngin
// if scriptEngine is NULL then create one and keep track of it using _ownScriptEngine
if (scriptEngine.isNull()) {
_scriptEngine = QSharedPointer<ScriptEngine>(DependencyManager::get<ScriptEngines>()->loadScript(_consoleFileName, false), &QObject::deleteLater);
_scriptEngine = DependencyManager::get<ScriptEngines>()->loadScript(_consoleFileName, false);
} else {
_scriptEngine = scriptEngine;
}

View file

@ -30,10 +30,10 @@ const int CONSOLE_HEIGHT = 200;
class JSConsole : public QWidget {
Q_OBJECT
public:
JSConsole(QWidget* parent, const QSharedPointer<ScriptEngine>& scriptEngine = QSharedPointer<ScriptEngine>());
JSConsole(QWidget* parent, const ScriptEnginePointer& scriptEngine = ScriptEnginePointer());
~JSConsole();
void setScriptEngine(const QSharedPointer<ScriptEngine>& scriptEngine = QSharedPointer<ScriptEngine>());
void setScriptEngine(const ScriptEnginePointer& scriptEngine = ScriptEnginePointer());
void clear();
public slots:
@ -66,7 +66,7 @@ private:
QString _savedHistoryFilename;
QList<QString> _commandHistory;
QString _rootCommand;
QSharedPointer<ScriptEngine> _scriptEngine;
ScriptEnginePointer _scriptEngine;
static const QString _consoleFileName;
};

View file

@ -169,12 +169,14 @@ void LoginDialog::openUrl(const QString& url) const {
auto offscreenUi = DependencyManager::get<OffscreenUi>();
if (tablet->getToolbarMode()) {
auto browser = offscreenUi->load("Browser.qml");
browser->setProperty("url", url);
offscreenUi->load("Browser.qml", [=](QQmlContext* context, QObject* newObject) {
newObject->setProperty("url", url);
});
} else {
if (!hmd->getShouldShowTablet() && !qApp->isHMDMode()) {
auto browser = offscreenUi->load("Browser.qml");
browser->setProperty("url", url);
offscreenUi->load("Browser.qml", [=](QQmlContext* context, QObject* newObject) {
newObject->setProperty("url", url);
});
} else {
tablet->gotoWebScreen(url);
}

View file

@ -193,7 +193,7 @@ void setupPreferences() {
preferences->addPreference(new PrimaryHandPreference(AVATAR_TUNING, "Dominant Hand", getter, setter));
}
{
auto getter = [=]()->float { return myAvatar->getUniformScale(); };
auto getter = [=]()->float { return myAvatar->getTargetScale(); };
auto setter = [=](float value) { myAvatar->setTargetScale(value); };
auto preference = new SpinnerSliderPreference(AVATAR_TUNING, "Avatar Scale", getter, setter);
preference->setStep(0.05f);
@ -205,6 +205,16 @@ void setupPreferences() {
// which can't be changed across domain switches. Having these values loaded up when you load the Dialog each time
// is a way around this, therefore they're not specified here but in the QML.
}
{
auto getter = [=]()->float { return myAvatar->getUserHeight(); };
auto setter = [=](float value) { myAvatar->setUserHeight(value); };
auto preference = new SpinnerPreference(AVATAR_TUNING, "User height (meters)", getter, setter);
preference->setMin(1.0f);
preference->setMax(2.2f);
preference->setDecimals(3);
preference->setStep(0.001f);
preferences->addPreference(preference);
}
{
auto getter = []()->float { return DependencyManager::get<DdeFaceTracker>()->getEyeClosingThreshold(); };
auto setter = [](float value) { DependencyManager::get<DdeFaceTracker>()->setEyeClosingThreshold(value); };

View file

@ -24,7 +24,7 @@ TestingDialog::TestingDialog(QWidget* parent) :
_console->setFixedHeight(TESTING_CONSOLE_HEIGHT);
auto _engines = DependencyManager::get<ScriptEngines>();
_engine.reset(_engines->loadScript(qApp->applicationDirPath() + testRunnerRelativePath));
_engine = _engines->loadScript(qApp->applicationDirPath() + testRunnerRelativePath);
_console->setScriptEngine(_engine);
connect(_engine.data(), &ScriptEngine::finished, this, &TestingDialog::onTestingFinished);
}

View file

@ -29,7 +29,7 @@ public:
private:
std::unique_ptr<JSConsole> _console;
QSharedPointer<ScriptEngine> _engine;
ScriptEnginePointer _engine;
};
#endif

View file

@ -256,15 +256,46 @@ bool Base3DOverlay::findRayIntersection(const glm::vec3& origin, const glm::vec3
void Base3DOverlay::locationChanged(bool tellPhysics) {
SpatiallyNestable::locationChanged(tellPhysics);
auto itemID = getRenderItemID();
if (render::Item::isValidID(itemID)) {
render::ScenePointer scene = qApp->getMain3DScene();
render::Transaction transaction;
transaction.updateItem(itemID);
scene->enqueueTransaction(transaction);
}
// Force the actual update of the render transform through the notify call
notifyRenderTransformChange();
}
void Base3DOverlay::parentDeleted() {
qApp->getOverlays().deleteOverlay(getOverlayID());
}
void Base3DOverlay::update(float duration) {
// In Base3DOverlay, if its location or bound changed, the renderTrasnformDirty flag is true.
// then the correct transform used for rendering is computed in the update transaction and assigned.
// TODO: Fix the value to be computed in main thread now and passed by value to the render item.
// This is the simplest fix for the web overlay of the tablet for now
if (_renderTransformDirty) {
_renderTransformDirty = false;
auto itemID = getRenderItemID();
if (render::Item::isValidID(itemID)) {
render::ScenePointer scene = qApp->getMain3DScene();
render::Transaction transaction;
transaction.updateItem<Overlay>(itemID, [](Overlay& data) {
auto overlay3D = dynamic_cast<Base3DOverlay*>(&data);
if (overlay3D) {
auto latestTransform = overlay3D->evalRenderTransform();
overlay3D->setRenderTransform(latestTransform);
}
});
scene->enqueueTransaction(transaction);
}
}
}
void Base3DOverlay::notifyRenderTransformChange() const {
_renderTransformDirty = true;
}
Transform Base3DOverlay::evalRenderTransform() const {
return getTransform();
}
void Base3DOverlay::setRenderTransform(const Transform& transform) {
_renderTransform = transform;
}

View file

@ -52,6 +52,10 @@ public:
virtual AABox getBounds() const override = 0;
void update(float deltatime) override;
void notifyRenderTransformChange() const;
void setProperties(const QVariantMap& properties) override;
QVariant getProperty(const QString& property) override;
@ -67,12 +71,18 @@ protected:
virtual void locationChanged(bool tellPhysics = true) override;
virtual void parentDeleted() override;
mutable Transform _renderTransform;
virtual Transform evalRenderTransform() const;
virtual void setRenderTransform(const Transform& transform);
const Transform& getRenderTransform() const { return _renderTransform; }
float _lineWidth;
bool _isSolid;
bool _isDashedLine;
bool _ignoreRayIntersection;
bool _drawInFront;
bool _isGrabbable { false };
mutable bool _renderTransformDirty{ true };
QString _name;
};

View file

@ -85,6 +85,7 @@ void Circle3DOverlay::render(RenderArgs* args) {
}
// FIXME: THe line width of _lineWidth is not supported anymore, we ll need a workaround
// FIXME Start using the _renderTransform instead of calling for Transform from here, do the custom things needed in evalRenderTransform()
auto transform = getTransform();
transform.postScale(glm::vec3(getDimensions(), 1.0f));

View file

@ -54,6 +54,7 @@ void Cube3DOverlay::render(RenderArgs* args) {
glm::vec4 cubeColor(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha);
// TODO: handle registration point??
// FIXME Start using the _renderTransform instead of calling for Transform from here, do the custom things needed in evalRenderTransform()
glm::vec3 position = getPosition();
glm::vec3 dimensions = getDimensions();
glm::quat rotation = getRotation();

View file

@ -79,6 +79,7 @@ void Grid3DOverlay::render(RenderArgs* args) {
position += glm::vec3(cameraPosition.x, 0.0f, cameraPosition.z);
}
// FIXME Start using the _renderTransform instead of calling for Transform from here, do the custom things needed in evalRenderTransform()
Transform transform;
transform.setRotation(getRotation());
transform.setScale(glm::vec3(getDimensions(), 1.0f));

View file

@ -117,6 +117,7 @@ void Image3DOverlay::render(RenderArgs* args) {
xColor color = getColor();
float alpha = getAlpha();
// FIXME Start using the _renderTransform instead of calling for Transform from here, do the custom things needed in evalRenderTransform()
Transform transform = getTransform();
bool transformChanged = applyTransformTo(transform, true);
// If the transform is not modified, setting the transform to

View file

@ -132,6 +132,7 @@ void Line3DOverlay::render(RenderArgs* args) {
glm::vec4 colorv4(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha);
auto batch = args->_batch;
if (batch) {
// FIXME Start using the _renderTransform instead of calling for Transform and start and end from here, do the custom things needed in evalRenderTransform()
batch->setModelTransform(Transform());
glm::vec3 start = getStart();
glm::vec3 end = getEnd();

View file

@ -46,13 +46,17 @@ void ModelOverlay::update(float deltatime) {
if (_updateModel) {
_updateModel = false;
_model->setSnapModelToCenter(true);
Transform transform = getTransform();
#ifndef USE_SN_SCALE
transform.setScale(1.0f); // disable inherited scale
#endif
if (_scaleToFit) {
_model->setScaleToFit(true, getScale() * getDimensions());
_model->setScaleToFit(true, transform.getScale() * getDimensions());
} else {
_model->setScale(getScale());
_model->setScale(transform.getScale());
}
_model->setRotation(getRotation());
_model->setTranslation(getPosition());
_model->setRotation(transform.getRotation());
_model->setTranslation(transform.getTranslation());
_model->setURL(_url);
_model->simulate(deltatime, true);
} else {
@ -93,13 +97,13 @@ void ModelOverlay::setProperties(const QVariantMap& properties) {
auto origPosition = getPosition();
auto origRotation = getRotation();
auto origDimensions = getDimensions();
auto origScale = getScale();
auto origScale = getSNScale();
Base3DOverlay::setProperties(properties);
auto scale = properties["scale"];
if (scale.isValid()) {
setScale(vec3FromVariant(scale));
setSNScale(vec3FromVariant(scale));
}
auto dimensions = properties["dimensions"];
@ -112,7 +116,7 @@ void ModelOverlay::setProperties(const QVariantMap& properties) {
_scaleToFit = false;
}
if (origPosition != getPosition() || origRotation != getRotation() || origDimensions != getDimensions() || origScale != getScale()) {
if (origPosition != getPosition() || origRotation != getRotation() || origDimensions != getDimensions() || origScale != getSNScale()) {
_updateModel = true;
}
@ -194,7 +198,7 @@ QVariant ModelOverlay::getProperty(const QString& property) {
return vec3toVariant(getDimensions());
}
if (property == "scale") {
return vec3toVariant(getScale());
return vec3toVariant(getSNScale());
}
if (property == "textures") {
if (_modelTextures.size() > 0) {
@ -281,6 +285,7 @@ ModelOverlay* ModelOverlay::createClone() const {
void ModelOverlay::locationChanged(bool tellPhysics) {
Base3DOverlay::locationChanged(tellPhysics);
// FIXME Start using the _renderTransform instead of calling for Transform and Dimensions from here, do the custom things needed in evalRenderTransform()
if (_model && _model->isActive()) {
_model->setRotation(getRotation());
_model->setTranslation(getPosition());

View file

@ -1045,6 +1045,7 @@ QVector<QUuid> Overlays::findOverlays(const glm::vec3& center, float radius) {
AABox overlayFrameBox(low, dimensions);
Transform overlayToWorldMatrix = overlay->getTransform();
overlayToWorldMatrix.setScale(1.0f); // ignore inherited scale factor from parents
glm::mat4 worldToOverlayMatrix = glm::inverse(overlayToWorldMatrix.getMatrix());
glm::vec3 overlayFrameSearchPosition = glm::vec3(worldToOverlayMatrix * glm::vec4(center, 1.0f));
glm::vec3 penetration;

View file

@ -74,7 +74,7 @@ namespace render {
glm::vec3 myAvatarPosition = avatar->getPosition();
float angle = glm::degrees(glm::angle(myAvatarRotation));
glm::vec3 axis = glm::axis(myAvatarRotation);
float myAvatarScale = avatar->getUniformScale();
float myAvatarScale = avatar->getModelScale();
Transform transform = Transform();
transform.setTranslation(myAvatarPosition);
transform.setRotation(glm::angleAxis(angle, axis));

View file

@ -66,3 +66,12 @@ bool Planar3DOverlay::findRayIntersection(const glm::vec3& origin, const glm::ve
// FIXME - face and surfaceNormal not being returned
return findRayRectangleIntersection(origin, direction, getRotation(), getPosition(), getDimensions(), distance);
}
Transform Planar3DOverlay::evalRenderTransform() const {
auto transform = getTransform();
transform.setScale(1.0f); // ignore inherited scale factor from parents
if (glm::length2(getDimensions()) != 1.0f) {
transform.postScale(vec3(getDimensions(), 1.0f));
}
return transform;
}

View file

@ -32,7 +32,9 @@ public:
virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance,
BoxFace& face, glm::vec3& surfaceNormal) override;
Transform evalRenderTransform() const override;
protected:
glm::vec2 _dimensions;
};

View file

@ -66,6 +66,7 @@ void Rectangle3DOverlay::render(RenderArgs* args) {
auto batch = args->_batch;
if (batch) {
// FIXME Start using the _renderTransform instead of calling for Transform and Dimensions from here, do the custom things needed in evalRenderTransform()
Transform transform;
transform.setTranslation(position);
transform.setRotation(rotation);

View file

@ -33,6 +33,7 @@ void Shape3DOverlay::render(RenderArgs* args) {
const float MAX_COLOR = 255.0f;
glm::vec4 cubeColor(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha);
// FIXME Start using the _renderTransform instead of calling for Transform and Dimensions from here, do the custom things needed in evalRenderTransform()
// TODO: handle registration point??
glm::vec3 position = getPosition();
glm::vec3 dimensions = getDimensions();

View file

@ -39,7 +39,11 @@ void Sphere3DOverlay::render(RenderArgs* args) {
auto batch = args->_batch;
if (batch) {
// FIXME Start using the _renderTransform instead of calling for Transform and Dimensions from here, do the custom things needed in evalRenderTransform()
Transform transform = getTransform();
#ifndef USE_SN_SCALE
transform.setScale(1.0f); // ignore inherited scale from SpatiallyNestable
#endif
transform.postScale(getDimensions() * SPHERE_OVERLAY_SCALE);
batch->setModelTransform(transform);

View file

@ -96,6 +96,7 @@ void Text3DOverlay::render(RenderArgs* args) {
Q_ASSERT(args->_batch);
auto& batch = *args->_batch;
// FIXME Start using the _renderTransform instead of calling for Transform and Dimensions from here, do the custom things needed in evalRenderTransform()
Transform transform = getTransform();
applyTransformTo(transform, true);
setTransform(transform);

View file

@ -56,7 +56,11 @@ bool Volume3DOverlay::findRayIntersection(const glm::vec3& origin, const glm::ve
float& distance, BoxFace& face, glm::vec3& surfaceNormal) {
// extents is the entity relative, scaled, centered extents of the entity
glm::mat4 worldToEntityMatrix;
getTransform().getInverseMatrix(worldToEntityMatrix);
Transform transform = getTransform();
#ifndef USE_SN_SCALE
transform.setScale(1.0f); // ignore any inherited scale from SpatiallyNestable
#endif
transform.getInverseMatrix(worldToEntityMatrix);
glm::vec3 overlayFrameOrigin = glm::vec3(worldToEntityMatrix * glm::vec4(origin, 1.0f));
glm::vec3 overlayFrameDirection = glm::vec3(worldToEntityMatrix * glm::vec4(direction, 0.0f));

View file

@ -184,6 +184,7 @@ void Web3DOverlay::update(float deltatime) {
// update globalPosition
_webSurface->getSurfaceContext()->setContextProperty("globalPosition", vec3toVariant(getPosition()));
}
Parent::update(deltatime);
}
QString Web3DOverlay::pickURL() {
@ -199,7 +200,6 @@ QString Web3DOverlay::pickURL() {
}
}
void Web3DOverlay::loadSourceURL() {
if (!_webSurface) {
return;
@ -302,23 +302,9 @@ void Web3DOverlay::render(RenderArgs* args) {
emit resizeWebSurface();
}
vec2 halfSize = getSize() / 2.0f;
vec4 color(toGlm(getColor()), getAlpha());
Transform transform = getTransform();
// FIXME: applyTransformTo causes tablet overlay to detach from tablet entity.
// Perhaps rather than deleting the following code it should be run only if isFacingAvatar() is true?
/*
applyTransformTo(transform, true);
setTransform(transform);
*/
if (glm::length2(getDimensions()) != 1.0f) {
transform.postScale(vec3(getDimensions(), 1.0f));
}
if (!_texture) {
_texture = gpu::Texture::createExternal(OffscreenQmlSurface::getDiscardLambda());
_texture->setSource(__FUNCTION__);
@ -332,7 +318,9 @@ void Web3DOverlay::render(RenderArgs* args) {
Q_ASSERT(args->_batch);
gpu::Batch& batch = *args->_batch;
batch.setResourceTexture(0, _texture);
batch.setModelTransform(transform);
auto renderTransform = getRenderTransform();
batch.setModelTransform(getRenderTransform());
auto geometryCache = DependencyManager::get<GeometryCache>();
if (color.a < OPAQUE_ALPHA_THRESHOLD) {
geometryCache->bindWebBrowserProgram(batch, true);

View file

@ -19,8 +19,10 @@ class OffscreenQmlSurface;
class Web3DOverlay : public Billboard3DOverlay {
Q_OBJECT
using Parent = Billboard3DOverlay;
public:
static const QString QML;
static QString const TYPE;
virtual QString getType() const override { return TYPE; }

View file

@ -1164,7 +1164,6 @@ static bool findPointKDopDisplacement(const glm::vec3& point, const AnimPose& sh
glm::vec3 localPoint = shapePose.inverse().xformPoint(point);
// Only works for 14-dop shape infos.
assert(shapeInfo.dots.size() == DOP14_COUNT);
if (shapeInfo.dots.size() != DOP14_COUNT) {
return false;
}

View file

@ -78,7 +78,7 @@ Setting::Handle<int> staticJitterBufferFrames("staticJitterBufferFrames",
// protect the Qt internal device list
using Mutex = std::mutex;
using Lock = std::unique_lock<Mutex>;
static Mutex _deviceMutex;
Mutex _deviceMutex;
// thread-safe
QList<QAudioDeviceInfo> getAvailableDevices(QAudio::Mode mode) {
@ -227,13 +227,18 @@ AudioClient::AudioClient() :
// start a thread to detect any device changes
_checkDevicesTimer = new QTimer(this);
connect(_checkDevicesTimer, &QTimer::timeout, [this] {
QtConcurrent::run(QThreadPool::globalInstance(), [this] {
checkDevices();
});
QtConcurrent::run(QThreadPool::globalInstance(), [this] { checkDevices(); });
});
const unsigned long DEVICE_CHECK_INTERVAL_MSECS = 2 * 1000;
_checkDevicesTimer->start(DEVICE_CHECK_INTERVAL_MSECS);
// start a thread to detect peak value changes
_checkPeakValuesTimer = new QTimer(this);
connect(_checkPeakValuesTimer, &QTimer::timeout, [this] {
QtConcurrent::run(QThreadPool::globalInstance(), [this] { checkPeakValues(); });
});
const unsigned long PEAK_VALUES_CHECK_INTERVAL_MSECS = 50;
_checkPeakValuesTimer->start(PEAK_VALUES_CHECK_INTERVAL_MSECS);
configureReverb();
@ -275,6 +280,7 @@ void AudioClient::cleanupBeforeQuit() {
stop();
_checkDevicesTimer->stop();
_checkPeakValuesTimer->stop();
guard.trigger();
}
@ -316,8 +322,6 @@ QString getWinDeviceName(IMMDevice* pEndpoint) {
QString deviceName;
IPropertyStore* pPropertyStore;
pEndpoint->OpenPropertyStore(STGM_READ, &pPropertyStore);
pEndpoint->Release();
pEndpoint = nullptr;
PROPVARIANT pv;
PropVariantInit(&pv);
HRESULT hr = pPropertyStore->GetValue(PKEY_Device_FriendlyName, &pv);
@ -346,6 +350,8 @@ QString AudioClient::getWinDeviceName(wchar_t* guid) {
deviceName = QString("NONE");
} else {
deviceName = ::getWinDeviceName(pEndpoint);
pEndpoint->Release();
pEndpoint = nullptr;
}
pMMDeviceEnumerator->Release();
pMMDeviceEnumerator = nullptr;
@ -429,6 +435,8 @@ QAudioDeviceInfo defaultAudioDeviceForMode(QAudio::Mode mode) {
deviceName = QString("NONE");
} else {
deviceName = getWinDeviceName(pEndpoint);
pEndpoint->Release();
pEndpoint = nullptr;
}
pMMDeviceEnumerator->Release();
pMMDeviceEnumerator = NULL;

View file

@ -148,6 +148,9 @@ public:
QAudioDeviceInfo getActiveAudioDevice(QAudio::Mode mode) const;
QList<QAudioDeviceInfo> getAudioDevices(QAudio::Mode mode) const;
void enablePeakValues(bool enable) { _enablePeakValues = enable; }
bool peakValuesAvailable() const;
static const float CALLBACK_ACCELERATOR_RATIO;
bool getNamedAudioDeviceForModeExists(QAudio::Mode mode, const QString& deviceName);
@ -224,6 +227,7 @@ signals:
void deviceChanged(QAudio::Mode mode, const QAudioDeviceInfo& device);
void devicesChanged(QAudio::Mode mode, const QList<QAudioDeviceInfo>& devices);
void peakValueListChanged(const QList<float> peakValueList);
void receivedFirstPacket();
void disconnected();
@ -242,9 +246,12 @@ private:
friend class CheckDevicesThread;
friend class LocalInjectorsThread;
// background tasks
void checkDevices();
void checkPeakValues();
void outputFormatChanged();
void handleAudioInput(QByteArray& audioBuffer);
void checkDevices();
void prepareLocalAudioInjectors(std::unique_ptr<Lock> localAudioLock = nullptr);
bool mixLocalAudioInjectors(float* mixBuffer);
float azimuthForSource(const glm::vec3& relativePosition);
@ -298,6 +305,7 @@ private:
std::atomic<bool> _localInjectorsAvailable { false };
MixedProcessedAudioStream _receivedAudioStream;
bool _isStereoInput;
std::atomic<bool> _enablePeakValues { false };
quint64 _outputStarveDetectionStartTimeMsec;
int _outputStarveDetectionCount;
@ -396,6 +404,7 @@ private:
RateCounter<> _audioInbound;
QTimer* _checkDevicesTimer { nullptr };
QTimer* _checkPeakValuesTimer { nullptr };
};

View file

@ -0,0 +1,176 @@
//
// AudioPeakValues.cpp
// interface/src
//
// Created by Zach Pomerantz on 6/26/2017
// 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 "AudioClient.h"
#ifdef Q_OS_WIN
#include <windows.h>
#include <mmdeviceapi.h>
#include <endpointvolume.h>
#include <audioclient.h>
#include <QString>
#define RETURN_ON_FAIL(result) if (FAILED(result)) { return; }
#define CONTINUE_ON_FAIL(result) if (FAILED(result)) { continue; }
extern QString getWinDeviceName(IMMDevice* pEndpoint);
extern std::mutex _deviceMutex;
std::map<std::wstring, std::shared_ptr<IAudioClient>> activeClients;
template <class T>
void release(T* t) {
t->Release();
}
template <>
void release(IAudioClient* audioClient) {
audioClient->Stop();
audioClient->Release();
}
void AudioClient::checkPeakValues() {
// prepare the windows environment
CoInitialize(NULL);
// if disabled, clean up active clients
if (!_enablePeakValues) {
activeClients.clear();
return;
}
// lock the devices so the _inputDevices list is static
std::unique_lock<std::mutex> lock(_deviceMutex);
HRESULT result;
// initialize the payload
QList<float> peakValueList;
for (int i = 0; i < _inputDevices.size(); ++i) {
peakValueList.push_back(0.0f);
}
std::shared_ptr<IMMDeviceEnumerator> enumerator;
{
IMMDeviceEnumerator* pEnumerator;
result = CoCreateInstance(
__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER,
__uuidof(IMMDeviceEnumerator), (void**)&pEnumerator);
RETURN_ON_FAIL(result);
enumerator = std::shared_ptr<IMMDeviceEnumerator>(pEnumerator, &release<IMMDeviceEnumerator>);
}
std::shared_ptr<IMMDeviceCollection> endpoints;
{
IMMDeviceCollection* pEndpoints;
result = enumerator->EnumAudioEndpoints(eCapture, DEVICE_STATE_ACTIVE, &pEndpoints);
RETURN_ON_FAIL(result);
endpoints = std::shared_ptr<IMMDeviceCollection>(pEndpoints, &release<IMMDeviceCollection>);
}
UINT count;
{
result = endpoints->GetCount(&count);
RETURN_ON_FAIL(result);
}
IMMDevice* pDevice;
std::shared_ptr<IMMDevice> device;
IAudioMeterInformation* pMeterInfo;
std::shared_ptr<IAudioMeterInformation> meterInfo;
IAudioClient* pAudioClient;
std::shared_ptr<IAudioClient> audioClient;
DWORD hardwareSupport;
LPWSTR pDeviceId = NULL;
LPWAVEFORMATEX format;
float peakValue;
QString deviceName;
int deviceIndex;
for (UINT i = 0; i < count; ++i) {
result = endpoints->Item(i, &pDevice);
CONTINUE_ON_FAIL(result);
device = std::shared_ptr<IMMDevice>(pDevice, &release<IMMDevice>);
// if the device isn't listed through Qt, skip it
deviceName = ::getWinDeviceName(pDevice);
deviceIndex = 0;
for (; deviceIndex < _inputDevices.size(); ++deviceIndex) {
if (deviceName == _inputDevices[deviceIndex].deviceName()) {
break;
}
}
if (deviceIndex >= _inputDevices.size()) {
continue;
}
//continue;
result = device->Activate(__uuidof(IAudioMeterInformation), CLSCTX_ALL, NULL, (void**)&pMeterInfo);
CONTINUE_ON_FAIL(result);
meterInfo = std::shared_ptr<IAudioMeterInformation>(pMeterInfo, &release<IAudioMeterInformation>);
//continue;
hardwareSupport;
result = meterInfo->QueryHardwareSupport(&hardwareSupport);
CONTINUE_ON_FAIL(result);
//continue;
// if the device has no hardware support (USB)...
if (!(hardwareSupport & ENDPOINT_HARDWARE_SUPPORT_METER)) {
result = device->GetId(&pDeviceId);
CONTINUE_ON_FAIL(result);
std::wstring deviceId(pDeviceId);
CoTaskMemFree(pDeviceId);
//continue;
// ...and no active client...
if (activeClients.find(deviceId) == activeClients.end()) {
result = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, (void**)&pAudioClient);
CONTINUE_ON_FAIL(result);
audioClient = std::shared_ptr<IAudioClient>(pAudioClient, &release<IAudioClient>);
//continue;
// ...activate a client
audioClient->GetMixFormat(&format);
audioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, 0, 0, format, NULL);
audioClient->Start();
//continue;
activeClients[deviceId] = audioClient;
}
}
// get the peak value and put it in the payload
meterInfo->GetPeakValue(&peakValue);
peakValueList[deviceIndex] = peakValue;
}
emit peakValueListChanged(peakValueList);
}
bool AudioClient::peakValuesAvailable() const {
return true;
}
#else
void AudioClient::checkPeakValues() {
}
bool AudioClient::peakValuesAvailable() const {
return false;
}
#endif

View file

@ -15,6 +15,7 @@
#include <glm/gtx/transform.hpp>
#include <glm/gtx/vector_query.hpp>
#include <AvatarConstants.h>
#include <shared/QtHelpers.h>
#include <DeferredLightingEffect.h>
#include <EntityTreeRenderer.h>
@ -106,7 +107,7 @@ Avatar::Avatar(QThread* thread) :
// we may have been created in the network thread, but we live in the main thread
moveToThread(thread);
setScale(glm::vec3(1.0f)); // avatar scale is uniform
setModelScale(1.0f); // avatar scale is uniform
auto geometryCache = DependencyManager::get<GeometryCache>();
_nameRectGeometryID = geometryCache->allocateID();
@ -155,14 +156,14 @@ glm::vec3 Avatar::getNeckPosition() const {
AABox Avatar::getBounds() const {
if (!_skeletonModel->isRenderable() || _skeletonModel->needsFixupInScene()) {
// approximately 2m tall, scaled to user request.
return AABox(getPosition() - glm::vec3(getUniformScale()), getUniformScale() * 2.0f);
return AABox(getPosition() - glm::vec3(getModelScale()), getModelScale() * 2.0f);
}
return _skeletonModel->getRenderableMeshBound();
}
void Avatar::animateScaleChanges(float deltaTime) {
if (_isAnimatingScale) {
float currentScale = getUniformScale();
float currentScale = getModelScale();
float desiredScale = getDomainLimitedScale();
// use exponential decay toward the domain limit clamped scale
@ -177,7 +178,7 @@ void Avatar::animateScaleChanges(float deltaTime) {
animatedScale = desiredScale;
_isAnimatingScale = false;
}
setScale(glm::vec3(animatedScale)); // avatar scale is uniform
setModelScale(animatedScale); // avatar scale is uniform
// flag the joints as having changed for force update to RenderItem
_hasNewJointData = true;
@ -364,7 +365,7 @@ void Avatar::simulate(float deltaTime, bool inView) {
}
head->setPosition(headPosition);
}
head->setScale(getUniformScale());
head->setScale(getModelScale());
head->simulate(deltaTime);
} else {
// a non-full update is still required so that the position, rotation, scale and bounds of the skeletonModel are updated.
@ -422,7 +423,7 @@ bool Avatar::isLookingAtMe(AvatarSharedPointer avatar) const {
glm::vec3 theirLookAt = dynamic_pointer_cast<Avatar>(avatar)->getHead()->getLookAtPosition();
glm::vec3 myEyePosition = getHead()->getEyePosition();
return glm::distance(theirLookAt, myEyePosition) <= (HEAD_SPHERE_RADIUS * getUniformScale());
return glm::distance(theirLookAt, myEyePosition) <= (HEAD_SPHERE_RADIUS * getModelScale());
}
void Avatar::slamPosition(const glm::vec3& newPosition) {
@ -553,7 +554,7 @@ void Avatar::updateRenderItem(render::Transaction& transaction) {
}
}
void Avatar::postUpdate(float deltaTime) {
void Avatar::postUpdate(float deltaTime, const render::ScenePointer& scene) {
if (isMyAvatar() ? showMyLookAtVectors : showOtherLookAtVectors) {
const float EYE_RAY_LENGTH = 10.0;
@ -577,6 +578,8 @@ void Avatar::postUpdate(float deltaTime) {
DebugDraw::getInstance().drawRay(rightEyePosition, rightEyePosition + rightEyeRotation * Vectors::UNIT_Z * EYE_RAY_LENGTH, RED);
}
}
fixupModelsInScene(scene);
}
void Avatar::render(RenderArgs* renderArgs) {
@ -648,12 +651,10 @@ void Avatar::render(RenderArgs* renderArgs) {
return;
}
fixupModelsInScene(renderArgs->_scene);
if (showCollisionShapes && shouldRenderHead(renderArgs) && _skeletonModel->isRenderable()) {
PROFILE_RANGE_BATCH(batch, __FUNCTION__":skeletonBoundingCollisionShapes");
const float BOUNDING_SHAPE_ALPHA = 0.7f;
_skeletonModel->renderBoundingCollisionShapes(renderArgs, *renderArgs->_batch, getUniformScale(), BOUNDING_SHAPE_ALPHA);
_skeletonModel->renderBoundingCollisionShapes(renderArgs, *renderArgs->_batch, getModelScale(), BOUNDING_SHAPE_ALPHA);
}
if (showReceiveStats || showNamesAboveHeads) {
@ -726,9 +727,9 @@ void Avatar::simulateAttachments(float deltaTime) {
} else {
if (_skeletonModel->getJointPositionInWorldFrame(jointIndex, jointPosition) &&
_skeletonModel->getJointRotationInWorldFrame(jointIndex, jointRotation)) {
model->setTranslation(jointPosition + jointRotation * attachment.translation * getUniformScale());
model->setTranslation(jointPosition + jointRotation * attachment.translation * getModelScale());
model->setRotation(jointRotation * attachment.rotation);
float scale = getUniformScale() * attachment.scale;
float scale = getModelScale() * attachment.scale;
model->setScaleToFit(true, model->getNaturalDimensions() * scale, true); // hack to force rescale
model->setSnapModelToCenter(false); // hack to force resnap
model->setSnapModelToCenter(true);
@ -888,7 +889,7 @@ void Avatar::renderDisplayName(gpu::Batch& batch, const ViewFrustum& view, const
}
void Avatar::setSkeletonOffset(const glm::vec3& offset) {
const float MAX_OFFSET_LENGTH = getUniformScale() * 0.5f;
const float MAX_OFFSET_LENGTH = getModelScale() * 0.5f;
float offsetLength = glm::length(offset);
if (offsetLength > MAX_OFFSET_LENGTH) {
_skeletonOffset = (MAX_OFFSET_LENGTH / offsetLength) * offset;
@ -986,14 +987,12 @@ glm::quat Avatar::getAbsoluteJointRotationInObjectFrame(int index) const {
index += numeric_limits<unsigned short>::max() + 1; // 65536
}
switch(index) {
switch (index) {
case SENSOR_TO_WORLD_MATRIX_INDEX: {
glm::mat4 sensorToWorldMatrix = getSensorToWorldMatrix();
bool success;
Transform avatarTransform;
Transform::mult(avatarTransform, getParentTransform(success), getLocalTransform());
glm::mat4 invAvatarMat = avatarTransform.getInverseMatrix();
return glmExtractRotation(invAvatarMat * sensorToWorldMatrix);
glm::mat4 avatarMatrix = getLocalTransform().getMatrix();
glm::mat4 finalMat = glm::inverse(avatarMatrix) * sensorToWorldMatrix;
return glmExtractRotation(finalMat);
}
case CONTROLLER_LEFTHAND_INDEX: {
Transform controllerLeftHandTransform = Transform(getControllerLeftHandMatrix());
@ -1026,14 +1025,12 @@ glm::vec3 Avatar::getAbsoluteJointTranslationInObjectFrame(int index) const {
index += numeric_limits<unsigned short>::max() + 1; // 65536
}
switch(index) {
switch (index) {
case SENSOR_TO_WORLD_MATRIX_INDEX: {
glm::mat4 sensorToWorldMatrix = getSensorToWorldMatrix();
bool success;
Transform avatarTransform;
Transform::mult(avatarTransform, getParentTransform(success), getLocalTransform());
glm::mat4 invAvatarMat = avatarTransform.getInverseMatrix();
return extractTranslation(invAvatarMat * sensorToWorldMatrix);
glm::mat4 avatarMatrix = getLocalTransform().getMatrix();
glm::mat4 finalMat = glm::inverse(avatarMatrix) * sensorToWorldMatrix;
return extractTranslation(finalMat);
}
case CONTROLLER_LEFTHAND_INDEX: {
Transform controllerLeftHandTransform = Transform(getControllerLeftHandMatrix());
@ -1061,6 +1058,22 @@ glm::vec3 Avatar::getAbsoluteJointTranslationInObjectFrame(int index) const {
}
}
glm::vec3 Avatar::getAbsoluteJointScaleInObjectFrame(int index) const {
if (index < 0) {
index += numeric_limits<unsigned short>::max() + 1; // 65536
}
// only sensor to world matrix has non identity scale.
switch (index) {
case SENSOR_TO_WORLD_MATRIX_INDEX: {
glm::mat4 sensorToWorldMatrix = getSensorToWorldMatrix();
return extractScale(sensorToWorldMatrix);
}
default:
return AvatarData::getAbsoluteJointScaleInObjectFrame(index);
}
}
void Avatar::invalidateJointIndicesCache() const {
QWriteLocker writeLock(&_modelJointIndicesCacheLock);
_modelJointsCached = false;
@ -1149,7 +1162,7 @@ glm::vec3 Avatar::getJointPosition(const QString& name) const {
void Avatar::scaleVectorRelativeToPosition(glm::vec3 &positionToScale) const {
//Scale a world space vector as if it was relative to the position
positionToScale = getPosition() + getUniformScale() * (positionToScale - getPosition());
positionToScale = getPosition() + getModelScale() * (positionToScale - getPosition());
}
void Avatar::setSkeletonModelURL(const QUrl& skeletonModelURL) {
@ -1351,7 +1364,7 @@ void Avatar::updateDisplayNameAlpha(bool showDisplayName) {
// virtual
void Avatar::computeShapeInfo(ShapeInfo& shapeInfo) {
float uniformScale = getUniformScale();
float uniformScale = getModelScale();
shapeInfo.setCapsuleY(uniformScale * _skeletonModel->getBoundingCapsuleRadius(),
0.5f * uniformScale * _skeletonModel->getBoundingCapsuleHeight());
shapeInfo.setOffset(uniformScale * _skeletonModel->getBoundingCapsuleOffset());
@ -1548,3 +1561,54 @@ void Avatar::ensureInScene(AvatarSharedPointer self, const render::ScenePointer&
addToScene(self, scene);
}
}
float Avatar::getEyeHeight() const {
if (QThread::currentThread() != thread()) {
float result = DEFAULT_AVATAR_EYE_HEIGHT;
BLOCKING_INVOKE_METHOD(const_cast<Avatar*>(this), "getHeight", Q_RETURN_ARG(float, result));
return result;
}
// TODO: if performance becomes a concern we can cache this value rather then computing it everytime.
// Makes assumption that the y = 0 plane in geometry is the ground plane.
// We also make that assumption in Rig::computeAvatarBoundingCapsule()
float avatarScale = getModelScale();
if (_skeletonModel) {
auto& rig = _skeletonModel->getRig();
int headTopJoint = rig.indexOfJoint("HeadTop_End");
int headJoint = rig.indexOfJoint("Head");
int eyeJoint = rig.indexOfJoint("LeftEye") != -1 ? rig.indexOfJoint("LeftEye") : rig.indexOfJoint("RightEye");
int toeJoint = rig.indexOfJoint("LeftToeBase") != -1 ? rig.indexOfJoint("LeftToeBase") : rig.indexOfJoint("RightToeBase");
if (eyeJoint >= 0 && toeJoint >= 0) {
// measure from eyes to toes.
float eyeHeight = rig.getAbsoluteDefaultPose(eyeJoint).trans().y - rig.getAbsoluteDefaultPose(toeJoint).trans().y;
return eyeHeight;
} else if (eyeJoint >= 0) {
// measure eyes to y = 0 plane.
float groundHeight = transformPoint(rig.getGeometryToRigTransform(), glm::vec3(0.0f)).y;
float eyeHeight = rig.getAbsoluteDefaultPose(eyeJoint).trans().y - groundHeight;
return eyeHeight;
} else if (headTopJoint >= 0 && toeJoint >= 0) {
// measure toe to top of head. Note: default poses already include avatar scale factor
const float ratio = DEFAULT_AVATAR_EYE_TO_TOP_OF_HEAD / DEFAULT_AVATAR_HEIGHT;
float height = rig.getAbsoluteDefaultPose(headTopJoint).trans().y - rig.getAbsoluteDefaultPose(toeJoint).trans().y;
return height - height * ratio;
} else if (headTopJoint >= 0) {
const float ratio = DEFAULT_AVATAR_EYE_TO_TOP_OF_HEAD / DEFAULT_AVATAR_HEIGHT;
float groundHeight = transformPoint(rig.getGeometryToRigTransform(), glm::vec3(0.0f)).y;
float headHeight = rig.getAbsoluteDefaultPose(headTopJoint).trans().y - groundHeight;
return headHeight - headHeight * ratio;
} else if (headJoint >= 0) {
float groundHeight = transformPoint(rig.getGeometryToRigTransform(), glm::vec3(0.0f)).y;
const float DEFAULT_AVATAR_NECK_TO_EYE = DEFAULT_AVATAR_NECK_TO_TOP_OF_HEAD - DEFAULT_AVATAR_EYE_TO_TOP_OF_HEAD;
const float ratio = DEFAULT_AVATAR_NECK_TO_EYE / DEFAULT_AVATAR_NECK_HEIGHT;
float neckHeight = rig.getAbsoluteDefaultPose(headJoint).trans().y - groundHeight;
return neckHeight + neckHeight * ratio;
} else {
return avatarScale * DEFAULT_AVATAR_EYE_HEIGHT;
}
} else {
return avatarScale * DEFAULT_AVATAR_EYE_HEIGHT;
}
}

View file

@ -98,7 +98,7 @@ public:
void updateRenderItem(render::Transaction& transaction);
virtual void postUpdate(float deltaTime);
virtual void postUpdate(float deltaTime, const render::ScenePointer& scene);
//setters
void setIsLookAtTarget(const bool isLookAtTarget) { _isLookAtTarget = isLookAtTarget; }
@ -108,7 +108,6 @@ public:
SkeletonModelPointer getSkeletonModel() { return _skeletonModel; }
const SkeletonModelPointer getSkeletonModel() const { return _skeletonModel; }
glm::vec3 getChestPosition() const;
float getUniformScale() const { return getScale().y; }
const Head* getHead() const { return static_cast<const Head*>(_headData); }
Head* getHead() { return static_cast<Head*>(_headData); }
@ -151,6 +150,7 @@ public:
*/
Q_INVOKABLE virtual glm::vec3 getAbsoluteDefaultJointTranslationInObjectFrame(int index) const;
virtual glm::vec3 getAbsoluteJointScaleInObjectFrame(int index) const override;
virtual glm::quat getAbsoluteJointRotationInObjectFrame(int index) const override;
virtual glm::vec3 getAbsoluteJointTranslationInObjectFrame(int index) const override;
virtual bool setAbsoluteJointRotationInObjectFrame(int index, const glm::quat& rotation) override { return false; }
@ -232,6 +232,7 @@ public:
void animateScaleChanges(float deltaTime);
void setTargetScale(float targetScale) override;
float getTargetScale() const { return _targetScale; }
Q_INVOKABLE float getSimulationRate(const QString& rateName = QString("")) const;
@ -254,6 +255,16 @@ public:
bool isFading() const { return _isFading; }
void updateFadingStatus(render::ScenePointer scene);
/**jsdoc
* Provides read only access to the current eye height of the avatar.
* @function Avatar.getEyeHeight
* @returns {number} eye height of avatar in meters
*/
Q_INVOKABLE float getEyeHeight() const;
virtual float getModelScale() const { return _modelScale; }
virtual void setModelScale(float scale) { _modelScale = scale; }
public slots:
// FIXME - these should be migrated to use Pose data instead
@ -356,6 +367,7 @@ private:
bool _isAnimatingScale { false };
bool _mustFadeIn { false };
bool _isFading { false };
float _modelScale { 1.0f };
static int _jointConesID;
@ -365,7 +377,6 @@ private:
float _displayNameTargetAlpha { 1.0f };
float _displayNameAlpha { 1.0f };
};
#endif // hifi_Avatar_h

View file

@ -121,7 +121,7 @@ void SkeletonModel::updateRig(float deltaTime, glm::mat4 parentTransform) {
void SkeletonModel::updateAttitude(const glm::quat& orientation) {
setTranslation(_owningAvatar->getSkeletonPosition());
setRotation(orientation * Quaternions::Y_180);
setScale(glm::vec3(1.0f, 1.0f, 1.0f) * _owningAvatar->getScale());
setScale(glm::vec3(1.0f, 1.0f, 1.0f) * _owningAvatar->getModelScale());
}
// Called by Avatar::simulate after it has set the joint states (fullUpdate true if changed),
@ -294,7 +294,7 @@ bool SkeletonModel::getEyePositions(glm::vec3& firstEyePosition, glm::vec3& seco
}
glm::vec3 SkeletonModel::getDefaultEyeModelPosition() const {
return _owningAvatar->getScale() * _defaultEyeModelPosition;
return _owningAvatar->getModelScale() * _defaultEyeModelPosition;
}
float DENSITY_OF_WATER = 1000.0f; // kg/m^3
@ -316,7 +316,7 @@ void SkeletonModel::computeBoundingShape() {
float radius, height;
glm::vec3 offset;
_rig.computeAvatarBoundingCapsule(geometry, radius, height, offset);
float invScale = 1.0f / _owningAvatar->getUniformScale();
float invScale = 1.0f / _owningAvatar->getModelScale();
_boundingCapsuleRadius = invScale * radius;
_boundingCapsuleHeight = invScale * height;
_boundingCapsuleLocalOffset = invScale * offset;

View file

@ -2345,6 +2345,11 @@ glm::mat4 AvatarData::getSensorToWorldMatrix() const {
return _sensorToWorldMatrixCache.get();
}
// thread-safe
float AvatarData::getSensorToWorldScale() const {
return extractUniformScale(_sensorToWorldMatrixCache.get());
}
// thread-safe
glm::mat4 AvatarData::getControllerLeftHandMatrix() const {
return _controllerLeftHandMatrixCache.get();

View file

@ -387,6 +387,8 @@ class AvatarData : public QObject, public SpatiallyNestable {
Q_PROPERTY(glm::mat4 controllerLeftHandMatrix READ getControllerLeftHandMatrix)
Q_PROPERTY(glm::mat4 controllerRightHandMatrix READ getControllerRightHandMatrix)
Q_PROPERTY(float sensorToWorldScale READ getSensorToWorldScale)
public:
virtual QString getName() const override { return QString("Avatar:") + _displayName; }
@ -621,6 +623,7 @@ public:
// thread safe
Q_INVOKABLE glm::mat4 getSensorToWorldMatrix() const;
Q_INVOKABLE float getSensorToWorldScale() const;
Q_INVOKABLE glm::mat4 getControllerLeftHandMatrix() const;
Q_INVOKABLE glm::mat4 getControllerRightHandMatrix() const;

View file

@ -20,6 +20,7 @@
#include <QtGui/QWindow>
#include <QQuickWindow>
#include <DebugDraw.h>
#include <shared/QtHelpers.h>
#include <ui/Menu.h>
#include <NumericalConstants.h>
@ -339,23 +340,29 @@ void CompositorHelper::computeHmdPickRay(const glm::vec2& cursorPos, glm::vec3&
glm::mat4 CompositorHelper::getUiTransform() const {
glm::mat4 modelMat;
_modelTransform.getMatrix(modelMat);
return _currentCamera * glm::inverse(_currentDisplayPlugin->getHeadPose()) * modelMat;
return _sensorToWorldMatrix * modelMat;
}
//Finds the collision point of a world space ray
bool CompositorHelper::calculateRayUICollisionPoint(const glm::vec3& position, const glm::vec3& direction, glm::vec3& result) const {
auto UITransform = getUiTransform();
auto relativePosition4 = glm::inverse(UITransform) * vec4(position, 1);
auto relativePosition = vec3(relativePosition4) / relativePosition4.w;
auto relativeDirection = glm::inverse(glm::quat_cast(UITransform)) * direction;
glm::mat4 uiToWorld = getUiTransform();
glm::mat4 worldToUi = glm::inverse(uiToWorld);
glm::vec3 localPosition = transformPoint(worldToUi, position);
glm::vec3 localDirection = glm::normalize(transformVectorFast(worldToUi, direction));
const float UI_RADIUS = 1.0f; // * myAvatar->getUniformScale(); // FIXME - how do we want to handle avatar scale
const float UI_RADIUS = 1.0f;
float instersectionDistance;
if (raySphereIntersect(relativeDirection, relativePosition, UI_RADIUS, &instersectionDistance)){
result = position + glm::normalize(direction) * instersectionDistance;
if (raySphereIntersect(localDirection, localPosition, UI_RADIUS, &instersectionDistance)) {
result = transformPoint(uiToWorld, localPosition + localDirection * instersectionDistance);
#ifdef WANT_DEBUG
DebugDraw::getInstance().drawRay(position, result, glm::vec4(0.0f, 1.0f, 0.0f, 1.0f));
#endif
return true;
} else {
#ifdef WANT_DEBUG
DebugDraw::getInstance().drawRay(position, position + (direction * 1000.0f), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
#endif
}
return false;
}

View file

@ -109,7 +109,10 @@ public:
void setReticleOverDesktop(bool value) { _isOverDesktop = value; }
void setDisplayPlugin(const DisplayPluginPointer& displayPlugin) { _currentDisplayPlugin = displayPlugin; }
void setFrameInfo(uint32_t frame, const glm::mat4& camera) { _currentCamera = camera; }
void setFrameInfo(uint32_t frame, const glm::mat4& camera, const glm::mat4& sensorToWorldMatrix) {
_currentCamera = camera;
_sensorToWorldMatrix = sensorToWorldMatrix;
}
signals:
void allowMouseCaptureChanged();
@ -124,6 +127,7 @@ private:
DisplayPluginPointer _currentDisplayPlugin;
glm::mat4 _currentCamera;
glm::mat4 _sensorToWorldMatrix;
QWidget* _renderingWidget{ nullptr };
//// Support for hovering and tooltips

Some files were not shown because too many files have changed in this diff Show more