3
0
Fork 0
mirror of https://github.com/lubosz/overte.git synced 2025-04-26 16:35:28 +02:00

merge upstream/master into andrew/thermonuclear

This commit is contained in:
Andrew Meadows 2015-02-09 12:44:52 -08:00
commit e6a6946027
231 changed files with 7802 additions and 2392 deletions
.gitignoreBUILD.mdBUILD_ANDROID.mdBUILD_OSX.mdBUILD_WIN.mdCMakeLists.txt
assignment-client/src
cmake
domain-server
examples
gvr-interface
interface

9
.gitignore vendored
View file

@ -38,3 +38,12 @@ interface/resources/visage/*
# Ignore interfaceCache for Linux users
interface/interfaceCache/
# ignore audio-client externals
libraries/audio-client/external/*/*
!libraries/audio-client/external/*/readme.txt
gvr-interface/assets/oculussig*
gvr-interface/libs/*
TAGS

View file

@ -1,18 +1,20 @@
###Dependencies
* [cmake](http://www.cmake.org/cmake/resources/software.html) ~> 2.8.12.2
* [Qt](http://qt-project.org/downloads) ~> 5.3.0
* [Qt](http://qt-project.org/downloads) ~> 5.3.2
* [glm](http://glm.g-truc.net/0.9.5/index.html) ~> 0.9.5.4
* [OpenSSL](https://www.openssl.org/related/binaries.html) ~> 1.0.1g
* IMPORTANT: OpenSSL 1.0.1g is critical to avoid a security vulnerability.
* [Intel Threading Building Blocks](https://www.threadingbuildingblocks.org/) ~> 4.3
* [Soxr](http://sourceforge.net/projects/soxr/) ~> 0.1.1
* [Bullet Physics Engine](https://code.google.com/p/bullet/downloads/list) ~> 2.82
* [Gverb](https://github.com/highfidelity/gverb/archive/master.zip) (direct download to latest version)
### OS Specific Build Guides
* [BUILD_WIN.md](BUILD_WIN.md) - additional instructions for Windows.
* [BUILD_OSX.md](BUILD_OSX.md) - additional instructions for OS X.
* [BUILD_LINUX.md](BUILD_LINUX.md) - additional instructions for Linux.
* [BUILD_WIN.md](BUILD_WIN.md) - additional instructions for Windows.
* [BUILD_ANDROID.md](BUILD_ANDROID.md) - additional instructions for Android
###CMake
Hifi uses CMake to generate build files and project files for your platform.

148
BUILD_ANDROID.md Normal file
View file

@ -0,0 +1,148 @@
Please read the [general build guide](BUILD.md) for information on dependencies required for all platforms. Only Android specific instructions are found in this file.
###Android Dependencies
You will need the following tools to build our Android targets.
* [cmake](http://www.cmake.org/download/) ~> 3.1.0
* Note that this is a newer version required than the minimum for hifi desktop targets.
* [Qt](http://www.qt.io/download-open-source/#) ~> 5.4.0
* Note that this is a newer version required than the minimum for hifi desktop targets.
* [ant](http://ant.apache.org/bindownload.cgi) ~> 1.9.4
* [Android NDK](https://developer.android.com/tools/sdk/ndk/index.html) = r10c
* [Android SDK](http://developer.android.com/sdk/installing/index.html) ~> 24.0.2
* Install the latest Platform-tools
* Install the latest Build-tools
* Install the SDK Platform for API Level 19
* Install Sources for Android SDK for API Level 19
* Install the ARM EABI v7a System Image if you want to run an emulator.
You will also need to cross-compile the dependencies required for all platforms for Android, and help CMake find these compiled libraries on your machine.
####Optional Components
* [Oculus Mobile SDK](https://developer.oculus.com/downloads/#sdk=mobile) ~> 0.4.2
####ANDROID_LIB_DIR
Since you won't be installing Android dependencies to system paths on your development machine, CMake will need a little help tracking down your Android dependencies.
This is most easily accomplished by installing all Android dependencies in the same folder. You can place this folder wherever you like on your machine. In this build guide and across our CMakeLists files this folder is referred to as `ANDROID_LIB_DIR`. You can set `ANDROID_LIB_DIR` in your environment or by passing when you run CMake.
####Qt
Install Qt 5.4 for Android for your host environment from the [Qt downloads page](http://www.qt.io/download/). Install Qt to ``$ANDROID_LIB_DIR/Qt``. This is required so that our root CMakeLists file can help CMake find your Android Qt installation.
The component required for the Android build is the `Android armv7` component.
If you would like to install Qt to a different location, or attempt to build with a different Qt version, you can pass `ANDROID_QT_CMAKE_PREFIX_PATH` to CMake. Point to the `cmake` folder inside `$VERSION_NUMBER/android_armv7/lib`. Otherwise, our root CMakeLists will set it to `$ANDROID_LIB_DIR/Qt/5.3/android_armv7/lib/cmake`.
####OpenSSL
Cross-compilation of OpenSSL has been tested from an OS X machine running 10.10 compiling OpenSSL 1.0.2. It is likely that the steps below will work for other OpenSSL versions than 1.0.2.
The original instructions to compile OpenSSL for Android from your host environment can be found [here](http://wiki.openssl.org/index.php/Android). We required some tweaks to get OpenSSL to successfully compile, those tweaks are explained below.
Download the [OpenSSL source](https://www.openssl.org/source/) and extract the tarball inside your `ANDROID_LIB_DIR`. Rename the extracted folder to `openssl`.
You will need the [setenv-android.sh script](http://wiki.openssl.org/index.php/File:Setenv-android.sh) from the OpenSSL wiki.
You must change three values at the top of the `setenv-android.sh` script - `_ANDROID_NDK`, `_ANDROID_EABI` and `_ANDROID_API`.
`_ANDROID_NDK` should be `android-ndk-r10`, `_ANDROID_EABI` should be `arm-linux-androidebi-4.9` and `_ANDROID_API` should be `19`.
First, make sure `ANDROID_NDK_ROOT` is set in your env. This should be the path to the root of your Android NDK install. `setenv-android.sh` needs `ANDROID_NDK_ROOT` to set the environment variables required for building OpenSSL.
Source the `setenv-android.sh` script so it can set environment variables that OpenSSL will use while compiling. If you use zsh as your shell you may need to modify the `setenv-android.sh` for it to set the correct variables in your env.
```
export ANDROID_NDK_ROOT=YOUR_NDK_ROOT
source setenv-android.sh
```
Then, from the OpenSSL directory, run the following commands.
```
perl -pi -e 's/install: all install_docs install_sw/install: install_docs install_sw/g' Makefile.org
./config shared -no-ssl2 -no-ssl3 -no-comp -no-hw -no-engine --openssldir=/usr/local/ssl/$ANDROID_API
make depend
make all
```
This should generate libcrypto and libssl in the root of the OpenSSL directory. YOU MUST remove the `libssl.so` and `libcrypto.so` files that are generated. They are symlinks to `libssl.so.VER` and `libcrypto.so.VER` which Android does not know how to handle. By removing `libssl.so` and `libcrypto.so` the FindOpenSSL module will find the static libs and use those instead.
If you have been building other components it is possible that the OpenSSL compile will fail based on the values other cross-compilations (tbb, bullet) have set. Ensure that you are in a new terminal window to avoid compilation errors from previously set environment variables.
####Intel Threading Building Blocks
Download the [Intel Threading Building Blocks source](https://www.threadingbuildingblocks.org/download) and extract the tarball inside your `ANDROID_LIB_DIR`. Rename the extracted folder to `tbb`.
NOTE: BEFORE YOU ATTEMPT TO CROSS-COMPILE TBB, DISCONNECT ANY DEVICES ADB WOULD DETECT. The tbb build process asks adb for a couple of strings, and if a device is plugged in extra characters get added that will cause ndk-build to fail with an error.
From the tbb directory, execute the following commands. First, we build TBB using `ndk-build`. Then, the compiled libs are copied to a lib folder in the root of tbb directory.
```
cd jni
ndk-build target=android tbb tbbmalloc arch=arm
cd ../
mkdir lib
cp `find . -name "*.so"` lib/
```
####Soxr
Download the [Soxr source](http://sourceforge.net/projects/soxr/) and extract the tarball inside your `ANDROID_LIB_DIR`. Rename the extracted folder to `soxr`.
From the soxr directory, use cmake, along with the `android.toolchain.cmake` file (included in this repository under cmake/android) to cross-compile soxr for Android. Note that you will need ANDROID_NDK set in your environment before using the toolchain file.
The full set of commands to build soxr for Android is shown below. It is a long command, make sure you copy the entire command (up to `-DBUILD_TESTS=0`).
```
cmake -DCMAKE_TOOLCHAIN_FILE=$FULL_PATH_TO_TOOLCHAIN -DCMAKE_INSTALL_PREFIX=. -DHAVE_WORDS_BIGENDIAN_EXITCODE=1 -DBUILD_TESTS=0
make
make install
```
This will create the `lib` and `include` folders inside `ANDROID_LIB_DIR/soxr` that FindSoxr will look for.
####Oculus Mobile SDK
The Oculus Mobile SDK is optional, for Gear VR support. It is not required to compile gvr-interface.
Download the [Oculus Mobile SDK](https://developer.oculus.com/downloads/#sdk=mobile) and extract the archive inside your `ANDROID_LIB_DIR` folder. Rename the extracted folder to `libovr`.
From the VRLib directory, use ndk-build to build VrLib.
```
cd VRLib
ndk-build
```
This will create the liboculus.a archive that our FindLibOVR module will look for when cmake is run.
#####Hybrid testing
Currently the 'vr_dual' mode that would allow us to run a hybrid app has limited support in the Oculus Mobile SDK. The best way to have an application we can launch without having to connect to the GearVR is to put the Gear VR Service into developer mode. This stops Oculus Home from taking over the device when it is plugged into the Gear VR headset, and allows the application to be launched from the Applications page.
To put the Gear VR Service into developer mode you need an application with an Oculus Signature File on your device. Generate an Oculus Signature File for your device on the [Oculus osig tool page](https://developer.oculus.com/tools/osig/). Place this file in the gvr-interface/assets directory. Cmake will automatically copy it into your apk in the right place when you execute `make gvr-interface-apk`.
Once the application is on your device, go to `Settings->Application Manager->Gear VR Service->Manage Storage`. Tap on `VR Service Version` six times. It will scan your device to verify that you have an osig file in an application on your device, and then it will let you enable Developer mode.
####GLM
GLM is a header only library and technically the same GLM used for desktop builds of hifi could be used for the Android build. However, to avoid conflicts with system installations of Android dependencies, CMake will only look for Android headers and libraries in `ANDROID_LIB_DIR` or in your android-ndk install.
Download the [glm headers](http://sourceforge.net/projects/ogl-math/files/) from their sourceforge page. The version you download should match the requirement shown in the [general build guide](BUILD.md). Extract the archive into your `ANDROID_LIB_DIR` and rename the extracted folder to `glm`.
###CMake
We use CMake to generate the makefiles that compile and deploy the Android APKs to your device. In order to create Makefiles for the Android targets, CMake requires that some environment variables are set, and that other variables are passed to it when it is run.
The following must be set in your environment:
* ANDROID_NDK - the root of your Android NDK install
* ANDROID_HOME - the root of your Android SDK install
* ANDROID_LIB_DIR - the directory containing cross-compiled versions of dependencies
The following must be passed to CMake when it is run:
* USE_ANDROID_TOOLCHAIN - set to true to build for Android

View file

@ -4,7 +4,7 @@ Please read the [general build guide](BUILD.md) for information on dependencies
[Homebrew](http://brew.sh/) is an excellent package manager for OS X. It makes install of all hifi dependencies very simple.
brew tap highfidelity/homebrew-formulas
brew install cmake glm openssl tbb
brew install cmake glm openssl tbb libsoxr
brew install highfidelity/formulas/qt5
brew link qt5 --force

View file

@ -167,7 +167,7 @@ cmake .. -G "Visual Studio 12"
msbuild BULLET_PHYSICS.sln /p:Configuration=Debug
```
This will create Debug libraries in cmakebuild\lib\Debug you can replace Debug with Release in the msbuild command and that will generate Release libraries in cmakebuild\lib\Release.
This will create Debug libraries in cmakebuild\lib\Debug. You can replace Debug with Release in the msbuild command and that will generate Release libraries in cmakebuild\lib\Release.
You now have Bullet libraries compiled, now you need to put them in the right place for hifi to find them:
@ -178,6 +178,20 @@ You now have Bullet libraries compiled, now you need to put them in the right pl
_Note that the INSTALL target should handle the copying of files into an install directory automatically, however, without modifications to Cmake, the install target didn't work right for me, please update this instructions if you get that working right - Leo <leo@highfidelity.io>_
###Soxr
Download the zip from the [soxr sourceforge page](http://sourceforge.net/projects/soxr/).
We recommend you install it to %HIFI_LIB_DIR%\soxr. This will help our FindSoxr cmake module find what it needs. You can place it wherever you like on your machine if you specify SOXR_ROOT_DIR as an environment variable or a variable passed when cmake is run.
Extract the soxr archive wherever you like. Then, inside the extracted folder, create a directory called `build`. From that build directory, the following commands will build and then install soxr to `%HIFI_LIB_DIR%`.
```
cmake .. -G "NMake Makefiles" -DCMAKE_INSTALL_PREFIX=%HIFI_LIB_DIR%/soxr
nmake
nmake install
```
###Build High Fidelity using Visual Studio
Follow the same build steps from the CMake section of [BUILD.md](BUILD.md), but pass a different generator to CMake.

View file

@ -1,5 +1,10 @@
cmake_minimum_required(VERSION 2.8.12.2)
if (USE_ANDROID_TOOLCHAIN)
set(CMAKE_TOOLCHAIN_FILE "${CMAKE_CURRENT_SOURCE_DIR}/cmake/android/android.toolchain.cmake")
set(ANDROID_NATIVE_API_LEVEL 19)
endif ()
if (WIN32)
cmake_policy(SET CMP0020 NEW)
endif (WIN32)
@ -58,8 +63,27 @@ if (APPLE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --stdlib=libc++")
endif ()
if (NOT QT_CMAKE_PREFIX_PATH)
set(QT_CMAKE_PREFIX_PATH $ENV{QT_CMAKE_PREFIX_PATH})
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.4/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 ()
endif ()
set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} ${QT_CMAKE_PREFIX_PATH})
@ -71,6 +95,8 @@ set(CMAKE_OSX_DEPLOYMENT_TARGET 10.8)
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")
@ -84,10 +110,21 @@ foreach(CUSTOM_MACRO ${HIFI_CUSTOM_MACROS})
include(${CUSTOM_MACRO})
endforeach()
# targets on all platforms
add_subdirectory(assignment-client)
add_subdirectory(domain-server)
add_subdirectory(ice-server)
add_subdirectory(interface)
add_subdirectory(tests)
add_subdirectory(tools)
if (ANDROID)
file(GLOB ANDROID_CUSTOM_MACROS "cmake/android/*.cmake")
foreach(CUSTOM_MACRO ${ANDROID_CUSTOM_MACROS})
include(${CUSTOM_MACRO})
endforeach()
endif ()
# add subdirectories for all targets
if (NOT ANDROID)
add_subdirectory(assignment-client)
add_subdirectory(domain-server)
add_subdirectory(ice-server)
add_subdirectory(interface)
add_subdirectory(tests)
add_subdirectory(tools)
else ()
add_subdirectory(gvr-interface)
endif ()

View file

@ -17,7 +17,7 @@
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <AvatarData.h>
#include <AvatarHashMap.h>
#include <NetworkAccessManager.h>
#include <NodeList.h>
#include <PacketHeaders.h>
@ -39,13 +39,14 @@ Agent::Agent(const QByteArray& packet) :
_receivedAudioStream(AudioConstants::NETWORK_FRAME_SAMPLES_STEREO, RECEIVED_AUDIO_STREAM_CAPACITY_FRAMES,
InboundAudioStream::Settings(0, false, RECEIVED_AUDIO_STREAM_CAPACITY_FRAMES, false,
DEFAULT_WINDOW_STARVE_THRESHOLD, DEFAULT_WINDOW_SECONDS_FOR_DESIRED_CALC_ON_TOO_MANY_STARVES,
DEFAULT_WINDOW_SECONDS_FOR_DESIRED_REDUCTION, false)),
_avatarHashMap()
DEFAULT_WINDOW_SECONDS_FOR_DESIRED_REDUCTION, false))
{
// be the parent of the script engine so it gets moved when we do
_scriptEngine.setParent(this);
_scriptEngine.getEntityScriptingInterface()->setPacketSender(&_entityEditSender);
DependencyManager::set<ResouceCacheSharedItems>();
}
void Agent::readPendingDatagrams() {
@ -133,7 +134,7 @@ void Agent::readPendingDatagrams() {
|| datagramPacketType == PacketTypeAvatarBillboard
|| datagramPacketType == PacketTypeKillAvatar) {
// let the avatar hash map process it
_avatarHashMap.processAvatarMixerDatagram(receivedPacket, nodeList->sendingNodeForPacket(receivedPacket));
DependencyManager::get<AvatarHashMap>()->processAvatarMixerDatagram(receivedPacket, nodeList->sendingNodeForPacket(receivedPacket));
// let this continue through to the NodeList so it updates last heard timestamp
// for the sending avatar-mixer
@ -200,7 +201,7 @@ void Agent::run() {
// give this AvatarData object to the script engine
_scriptEngine.setAvatarData(&scriptedAvatar, "Avatar");
_scriptEngine.setAvatarHashMap(&_avatarHashMap, "AvatarList");
_scriptEngine.setAvatarHashMap(DependencyManager::get<AvatarHashMap>().data(), "AvatarList");
// register ourselves to the script engine
_scriptEngine.registerGlobalObject("Agent", this);

View file

@ -18,7 +18,6 @@
#include <QtCore/QObject>
#include <QtCore/QUrl>
#include <AvatarHashMap.h>
#include <EntityEditPacketSender.h>
#include <EntityTree.h>
#include <EntityTreeHeadlessViewer.h>
@ -63,8 +62,6 @@ private:
MixedAudioStream _receivedAudioStream;
float _lastReceivedAudioLoudness;
AvatarHashMap _avatarHashMap;
};
#endif // hifi_Agent_h

View file

@ -18,6 +18,7 @@
#include <AccountManager.h>
#include <AddressManager.h>
#include <Assignment.h>
#include <AvatarHashMap.h>
#include <HifiConfigVariantMap.h>
#include <LogHandler.h>
#include <LogUtils.h>
@ -55,6 +56,7 @@ AssignmentClient::AssignmentClient(int &argc, char **argv) :
DependencyManager::registerInheritance<LimitedNodeList, NodeList>();
auto addressManager = DependencyManager::set<AddressManager>();
auto nodeList = DependencyManager::set<NodeList>(NodeType::Unassigned);
auto avatarHashMap = DependencyManager::set<AvatarHashMap>();
// setup a shutdown event listener to handle SIGTERM or WM_CLOSE for us
#ifdef _WIN32

View file

@ -648,6 +648,7 @@ void AudioMixer::run() {
// setup a QThread with us as parent that will house the AudioMixerDatagramProcessor
_datagramProcessingThread = new QThread(this);
_datagramProcessingThread->setObjectName("Datagram Processor Thread");
// create an AudioMixerDatagramProcessor and move it to that thread
AudioMixerDatagramProcessor* datagramProcessor = new AudioMixerDatagramProcessor(nodeList->getNodeSocket(), thread());

View file

@ -879,6 +879,7 @@ void OctreeServer::setupDatagramProcessingThread() {
// setup a QThread with us as parent that will house the OctreeServerDatagramProcessor
_datagramProcessingThread = new QThread(this);
_datagramProcessingThread->setObjectName("Octree Datagram Processor");
// create an OctreeServerDatagramProcessor and move it to that thread
OctreeServerDatagramProcessor* datagramProcessor = new OctreeServerDatagramProcessor(nodeList->getNodeSocket(), thread());

View file

@ -0,0 +1,82 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- IMPORTANT: Do not manually manipulate this automatically generated file, changes will be gone after the next build! -->
<manifest package="${ANDROID_APK_PACKAGE}" xmlns:android="http://schemas.android.com/apk/res/android" android:versionName="${ANDROID_APK_VERSION_NAME}" android:versionCode="${ANDROID_APK_VERSION_CODE}" android:installLocation="auto">
<application
android:hardwareAccelerated="true"
android:name="org.qtproject.qt5.android.bindings.QtApplication"
android:label="@string/AppDisplayName"
android:icon="@drawable/icon"
android:debuggable="${ANDROID_APK_DEBUGGABLE}">
<!-- VR MODE -->
<meta-data android:name="com.samsung.android.vr.application.mode" android:value="vr_only"/>
<activity
android:configChanges="orientation|uiMode|screenLayout|screenSize|smallestScreenSize|locale|fontScale|keyboard|keyboardHidden|navigation"
android:name="${ANDROID_ACTIVITY_NAME}"
android:label="@string/AppDisplayName"
android:screenOrientation="landscape"
android:launchMode="singleTop"
${ANDROID_APK_THEME}>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<meta-data android:name="android.app.lib_name" android:value="-- %%INSERT_APP_LIB_NAME%% --"/>
<meta-data android:name="android.app.qt_sources_resource_id" android:resource="@array/qt_sources"/>
<meta-data android:name="android.app.repository" android:value="default"/>
<meta-data android:name="android.app.qt_libs_resource_id" android:resource="@array/qt_libs"/>
<meta-data android:name="android.app.bundled_libs_resource_id" android:resource="@array/bundled_libs"/>
<!-- Deploy Qt libs as part of package -->
<meta-data android:name="android.app.bundle_local_qt_libs" android:value="-- %%BUNDLE_LOCAL_QT_LIBS%% --"/>
<meta-data android:name="android.app.bundled_in_lib_resource_id" android:resource="@array/bundled_in_lib"/>
<meta-data android:name="android.app.bundled_in_assets_resource_id" android:resource="@array/bundled_in_assets"/>
<!-- Run with local libs -->
<meta-data android:name="android.app.use_local_qt_libs" android:value="-- %%USE_LOCAL_QT_LIBS%% --"/>
<meta-data android:name="android.app.libs_prefix" android:value="/data/local/tmp/qt/"/>
<meta-data android:name="android.app.load_local_libs" android:value="-- %%INSERT_LOCAL_LIBS%% --"/>
<meta-data android:name="android.app.load_local_jars" android:value="-- %%INSERT_LOCAL_JARS%% --"/>
<meta-data android:name="android.app.static_init_classes" android:value="-- %%INSERT_INIT_CLASSES%% --"/>
<!-- Messages maps -->
<meta-data android:value="@string/ministro_not_found_msg" android:name="android.app.ministro_not_found_msg"/>
<meta-data android:value="@string/ministro_needed_msg" android:name="android.app.ministro_needed_msg"/>
<meta-data android:value="@string/fatal_error_msg" android:name="android.app.fatal_error_msg"/>
<!-- Messages maps -->
<!-- Splash screen -->
<!-- <meta-data android:name="android.app.splash_screen_drawable" android:resource="@drawable/logo"/> -->
${ANDROID_EXTRA_ACTIVITY_XML}
</activity>
<activity
android:name="com.oculusvr.vrlib.PlatformActivity"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"
android:launchMode="singleTask"
android:screenOrientation="landscape"
android:configChanges="screenSize|orientation|keyboardHidden|keyboard">
</activity>
${ANDROID_EXTRA_APPLICATION_XML}
</application>
<uses-sdk android:minSdkVersion="${ANDROID_API_LEVEL}" android:targetSdkVersion="${ANDROID_API_LEVEL}"/>
<!-- The following comment will be replaced upon deployment with default permissions based on the dependencies of the application.
Remove the comment if you do not require these default permissions. -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- camera permission required for GEAR VR passthrough camera -->
<uses-permission android:name="android.permission.CAMERA" />
<!-- The following comment will be replaced upon deployment with default features based on the dependencies of the application.
Remove the comment if you do not require these default features. -->
<!-- Tell the system this app requires OpenGL ES 3.0. -->
<uses-feature android:glEsVersion="0x00030000" android:required="true" />
</manifest>

View file

@ -0,0 +1,162 @@
#
# QtCreateAPK.cmake
#
# Created by Stephen Birarda on 11/18/14.
# 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
#
#
# OPTIONS
# These options will modify how QtCreateAPK behaves. May be useful if somebody wants to fork.
# For High Fidelity purposes these should not need to be changed.
#
set(ANDROID_THIS_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}) # Directory this CMake file is in
if (POLICY CMP0026)
cmake_policy(SET CMP0026 OLD)
endif ()
macro(qt_create_apk)
if(ANDROID_APK_FULLSCREEN)
set(ANDROID_APK_THEME "android:theme=\"@android:style/Theme.NoTitleBar.Fullscreen\"")
else()
set(ANDROID_APK_THEME "")
endif()
if (CMAKE_BUILD_TYPE MATCHES RELEASE)
set(ANDROID_APK_DEBUGGABLE "false")
set(ANDROID_APK_RELEASE_LOCAL ${ANDROID_APK_RELEASE})
else ()
set(ANDROID_APK_DEBUGGABLE "true")
set(ANDROID_APK_RELEASE_LOCAL "0")
endif ()
# Create "AndroidManifest.xml"
configure_file("${ANDROID_THIS_DIRECTORY}/AndroidManifest.xml.in" "${ANDROID_APK_BUILD_DIR}/AndroidManifest.xml")
# create "strings.xml"
configure_file("${ANDROID_THIS_DIRECTORY}/strings.xml.in" "${ANDROID_APK_BUILD_DIR}/res/values/strings.xml")
# figure out where the qt dir is
get_filename_component(QT_DIR "${QT_CMAKE_PREFIX_PATH}/../../" ABSOLUTE)
# find androiddeployqt
find_program(ANDROID_DEPLOY_QT androiddeployqt HINTS "${QT_DIR}/bin")
# set the path to our app shared library
set(EXECUTABLE_DESTINATION_PATH "${ANDROID_APK_OUTPUT_DIR}/libs/${ANDROID_ABI}/lib${TARGET_NAME}.so")
# add our dependencies to the deployment file
get_property(_DEPENDENCIES TARGET ${TARGET_NAME} PROPERTY INTERFACE_LINK_LIBRARIES)
foreach(_IGNORE_COPY IN LISTS IGNORE_COPY_LIBS)
list(REMOVE_ITEM _DEPENDENCIES ${_IGNORE_COPY})
endforeach()
foreach(_DEP IN LISTS _DEPENDENCIES)
if (NOT TARGET ${_DEP})
list(APPEND _DEPS_LIST ${_DEP})
else ()
if(NOT _DEP MATCHES "Qt5::.*")
get_property(_DEP_LOCATION TARGET ${_DEP} PROPERTY "LOCATION_${CMAKE_BUILD_TYPE}")
# recurisvely add libraries which are dependencies of this target
get_property(_DEP_DEPENDENCIES TARGET ${_DEP} PROPERTY INTERFACE_LINK_LIBRARIES)
foreach(_SUB_DEP IN LISTS _DEP_DEPENDENCIES)
if (NOT TARGET ${_SUB_DEP} AND NOT _SUB_DEP MATCHES "Qt5::.*")
list(APPEND _DEPS_LIST ${_SUB_DEP})
endif()
endforeach()
list(APPEND _DEPS_LIST ${_DEP_LOCATION})
endif()
endif ()
endforeach()
list(REMOVE_DUPLICATES _DEPS_LIST)
# just copy static libs to apk libs folder - don't add to deps list
foreach(_LOCATED_DEP IN LISTS _DEPS_LIST)
if (_LOCATED_DEP MATCHES "\\.a$")
add_custom_command(
TARGET ${TARGET_NAME}
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy ${_LOCATED_DEP} "${ANDROID_APK_OUTPUT_DIR}/libs/${ANDROID_ABI}"
)
list(REMOVE_ITEM _DEPS_LIST ${_LOCATED_DEP})
endif ()
endforeach()
string(REPLACE ";" "," _DEPS "${_DEPS_LIST}")
configure_file("${ANDROID_THIS_DIRECTORY}/deployment-file.json.in" "${TARGET_NAME}-deployment.json")
# copy the res folder from the target to the apk build dir
add_custom_target(
${TARGET_NAME}-copy-res
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_SOURCE_DIR}/res" "${ANDROID_APK_BUILD_DIR}/res"
)
# copy the assets folder from the target to the apk build dir
add_custom_target(
${TARGET_NAME}-copy-assets
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_SOURCE_DIR}/assets" "${ANDROID_APK_BUILD_DIR}/assets"
)
# copy the java folder from src to the apk build dir
add_custom_target(
${TARGET_NAME}-copy-java
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_SOURCE_DIR}/src/java" "${ANDROID_APK_BUILD_DIR}/src"
)
# copy the libs folder from src to the apk build dir
add_custom_target(
${TARGET_NAME}-copy-libs
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_SOURCE_DIR}/libs" "${ANDROID_APK_BUILD_DIR}/libs"
)
# handle setup for ndk-gdb
add_custom_target(${TARGET_NAME}-gdb DEPENDS ${TARGET_NAME})
if (ANDROID_APK_DEBUGGABLE)
get_property(TARGET_LOCATION TARGET ${TARGET_NAME} PROPERTY LOCATION)
set(GDB_SOLIB_PATH ${ANDROID_APK_BUILD_DIR}/obj/local/${ANDROID_NDK_ABI_NAME}/)
# generate essential Android Makefiles
file(WRITE ${ANDROID_APK_BUILD_DIR}/jni/Android.mk "APP_ABI := ${ANDROID_NDK_ABI_NAME}\n")
file(WRITE ${ANDROID_APK_BUILD_DIR}/jni/Application.mk "APP_ABI := ${ANDROID_NDK_ABI_NAME}\n")
# create gdb.setup
get_directory_property(PROJECT_INCLUDES DIRECTORY ${PROJECT_SOURCE_DIR} INCLUDE_DIRECTORIES)
string(REGEX REPLACE ";" " " PROJECT_INCLUDES "${PROJECT_INCLUDES}")
file(WRITE ${ANDROID_APK_BUILD_DIR}/libs/${ANDROID_NDK_ABI_NAME}/gdb.setup "set solib-search-path ${GDB_SOLIB_PATH}\n")
file(APPEND ${ANDROID_APK_BUILD_DIR}/libs/${ANDROID_NDK_ABI_NAME}/gdb.setup "directory ${PROJECT_INCLUDES}\n")
# copy lib to obj
add_custom_command(TARGET ${TARGET_NAME}-gdb PRE_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory ${GDB_SOLIB_PATH})
add_custom_command(TARGET ${TARGET_NAME}-gdb PRE_BUILD COMMAND cp ${TARGET_LOCATION} ${GDB_SOLIB_PATH})
# strip symbols
add_custom_command(TARGET ${TARGET_NAME}-gdb PRE_BUILD COMMAND ${CMAKE_STRIP} ${TARGET_LOCATION})
endif ()
# use androiddeployqt to create the apk
add_custom_target(${TARGET_NAME}-apk
COMMAND ${ANDROID_DEPLOY_QT} --input "${TARGET_NAME}-deployment.json" --output "${ANDROID_APK_OUTPUT_DIR}" --android-platform android-${ANDROID_API_LEVEL} ${ANDROID_DEPLOY_QT_INSTALL} --verbose --deployment bundled "\\$(ARGS)"
DEPENDS ${TARGET_NAME} ${TARGET_NAME}-copy-res ${TARGET_NAME}-copy-assets ${TARGET_NAME}-copy-java ${TARGET_NAME}-copy-libs ${TARGET_NAME}-gdb
)
# rename the APK if the caller asked us to
if (ANDROID_APK_CUSTOM_NAME)
add_custom_command(
TARGET ${TARGET_NAME}-apk
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E rename "${ANDROID_APK_OUTPUT_DIR}/bin/QtApp-debug.apk" "${ANDROID_APK_OUTPUT_DIR}/bin/${ANDROID_APK_CUSTOM_NAME}"
)
endif ()
endmacro()

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,13 @@
{
"qt": "@QT_DIR@",
"sdk": "@ANDROID_SDK_ROOT@",
"ndk": "@ANDROID_NDK@",
"toolchain-prefix": "@ANDROID_TOOLCHAIN_MACHINE_NAME@",
"tool-prefix": "@ANDROID_TOOLCHAIN_MACHINE_NAME@",
"toolchain-version": "@ANDROID_COMPILER_VERSION@",
"ndk-host": "@ANDROID_NDK_HOST_SYSTEM_NAME@",
"target-architecture": "@ANDROID_ABI@",
"application-binary": "@EXECUTABLE_DESTINATION_PATH@",
"android-extra-libs": "@_DEPS@",
"android-package-source-directory": "@ANDROID_APK_BUILD_DIR@"
}

View file

@ -0,0 +1,11 @@
<?xml version='1.0' encoding='utf-8'?>
<!-- IMPORTANT: Do not manually manipulate this automatically generated file, changes will be gone after the next build! -->
<resources>
<string name="AppDisplayName">${ANDROID_APP_DISPLAY_NAME}</string>
<string name="ministro_not_found_msg">Can\'t find Ministro service.\nThe application can\'t start.</string>
<string name="ministro_needed_msg">This application requires Ministro service. Would you like to install it?</string>
<string name="fatal_error_msg">Your application encountered a fatal error and cannot continue.</string>
</resources>

View file

@ -13,5 +13,11 @@ macro(AUTO_MTC)
file(GLOB INCLUDE_FILES src/*.h)
add_custom_command(OUTPUT ${AUTOMTC_SRC} COMMAND mtc -o ${AUTOMTC_SRC} ${INCLUDE_FILES} DEPENDS mtc ${INCLUDE_FILES})
if (NOT ANDROID)
set(MTC_EXECUTABLE mtc)
else ()
set(MTC_EXECUTABLE $ENV{MTC_PATH}/mtc)
endif ()
add_custom_command(OUTPUT ${AUTOMTC_SRC} COMMAND ${MTC_EXECUTABLE} -o ${AUTOMTC_SRC} ${INCLUDE_FILES} DEPENDS ${MTC_EXECUTABLE} ${INCLUDE_FILES})
endmacro()

View file

@ -16,6 +16,10 @@ macro(HIFI_LIBRARY_SEARCH_HINTS LIBRARY_FOLDER)
set(${LIBRARY_PREFIX}_SEARCH_DIRS "${${LIBRARY_PREFIX}_ROOT_DIR}")
endif ()
if (ANDROID)
set(${LIBRARY_PREFIX}_SEARCH_DIRS "${${LIBRARY_PREFIX}_SEARCH_DIRS}" "/${LIBRARY_FOLDER}")
endif ()
if (DEFINED ENV{${LIBRARY_PREFIX}_ROOT_DIR})
set(${LIBRARY_PREFIX}_SEARCH_DIRS "${${LIBRARY_PREFIX}_SEARCH_DIRS}" "$ENV{${LIBRARY_PREFIX}_ROOT_DIR}")
endif ()

View file

@ -8,12 +8,6 @@
#
macro(INCLUDE_GLM)
find_package(GLM REQUIRED)
include_directories("${GLM_INCLUDE_DIRS}")
if (APPLE OR UNIX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -isystem ${GLM_INCLUDE_DIRS}")
endif ()
include_directories(SYSTEM "${GLM_INCLUDE_DIRS}")
endmacro(INCLUDE_GLM)

View file

@ -32,5 +32,4 @@ macro(LINK_HIFI_LIBRARIES)
list(APPEND ${TARGET_NAME}_DEPENDENCY_INCLUDES ${LINKED_TARGET_DEPENDENCY_INCLUDES})
endif()
endforeach()
endmacro(LINK_HIFI_LIBRARIES)

View file

@ -9,14 +9,18 @@
macro(SETUP_HIFI_LIBRARY)
project(${TARGET_NAME})
project(${TARGET_NAME})
# grab the implemenation and header files
file(GLOB_RECURSE LIB_SRCS "src/*.h" "src/*.cpp")
set(LIB_SRCS ${LIB_SRCS})
list(APPEND ${TARGET_NAME}_SRCS ${LIB_SRCS})
# create a library and set the property so it can be referenced later
add_library(${TARGET_NAME} ${LIB_SRCS} ${AUTOMTC_SRC} ${AUTOSCRIBE_SHADER_LIB_SRC})
if (${${TARGET_NAME}_SHARED})
add_library(${TARGET_NAME} SHARED ${LIB_SRCS} ${AUTOMTC_SRC} ${AUTOSCRIBE_SHADER_LIB_SRC} ${QT_RESOURCES_FILE})
else ()
add_library(${TARGET_NAME} ${LIB_SRCS} ${AUTOMTC_SRC} ${AUTOSCRIBE_SHADER_LIB_SRC} ${QT_RESOURCES_FILE})
endif ()
set(${TARGET_NAME}_DEPENDENCY_QT_MODULES ${ARGN})
list(APPEND ${TARGET_NAME}_DEPENDENCY_QT_MODULES Core)

View file

@ -35,27 +35,34 @@ include("${MACRO_DIR}/HifiLibrarySearchHints.cmake")
hifi_library_search_hints("bullet")
macro(_FIND_BULLET_LIBRARY _var)
find_library(${_var}
NAMES
${ARGN}
set(_${_var}_NAMES ${ARGN})
find_library(${_var}_LIBRARY_RELEASE
NAMES ${_${_var}_NAMES}
HINTS
${BULLET_SEARCH_DIRS}
$ENV{BULLET_ROOT_DIR}
${BULLET_ROOT}
${BULLET_ROOT}/out/release8/libs
${BULLET_ROOT}/out/debug8/libs
PATH_SUFFIXES lib lib/Release lib/Debug
PATH_SUFFIXES lib lib/Release out/release8/libs
)
mark_as_advanced(${_var})
endmacro()
macro(_BULLET_APPEND_LIBRARIES _list _release)
set(_debug ${_release}_DEBUG)
if(${_debug})
set(${_list} ${${_list}} optimized ${${_release}} debug ${${_debug}})
else()
set(${_list} ${${_list}} ${${_release}})
endif()
foreach(_NAME IN LISTS _${_var}_NAMES)
list(APPEND _${_var}_DEBUG_NAMES "${_NAME}_Debug")
list(APPEND _${_var}_DEBUG_NAMES "${_NAME}_d")
endforeach()
find_library(${_var}_LIBRARY_DEBUG
NAMES ${_${_var}_DEBUG_NAMES}
HINTS
${BULLET_SEARCH_DIRS}
$ENV{BULLET_ROOT_DIR}
${BULLET_ROOT}
PATH_SUFFIXES lib lib/Debug out/debug8/libs
)
select_library_configurations(${_var})
mark_as_advanced(${_var}_LIBRARY)
mark_as_advanced(${_var}_LIBRARY)
endmacro()
find_path(BULLET_INCLUDE_DIR NAMES btBulletCollisionCommon.h
@ -69,25 +76,18 @@ find_path(BULLET_INCLUDE_DIR NAMES btBulletCollisionCommon.h
# Find the libraries
_FIND_BULLET_LIBRARY(BULLET_DYNAMICS_LIBRARY BulletDynamics)
_FIND_BULLET_LIBRARY(BULLET_DYNAMICS_LIBRARY_DEBUG BulletDynamics_Debug BulletDynamics_d)
_FIND_BULLET_LIBRARY(BULLET_COLLISION_LIBRARY BulletCollision)
_FIND_BULLET_LIBRARY(BULLET_COLLISION_LIBRARY_DEBUG BulletCollision_Debug BulletCollision_d)
_FIND_BULLET_LIBRARY(BULLET_MATH_LIBRARY BulletMath LinearMath)
_FIND_BULLET_LIBRARY(BULLET_MATH_LIBRARY_DEBUG BulletMath_Debug BulletMath_d LinearMath_Debug LinearMath_d)
_FIND_BULLET_LIBRARY(BULLET_SOFTBODY_LIBRARY BulletSoftBody)
_FIND_BULLET_LIBRARY(BULLET_SOFTBODY_LIBRARY_DEBUG BulletSoftBody_Debug BulletSoftBody_d)
_FIND_BULLET_LIBRARY(BULLET_DYNAMICS BulletDynamics)
_FIND_BULLET_LIBRARY(BULLET_COLLISION BulletCollision)
_FIND_BULLET_LIBRARY(BULLET_MATH BulletMath LinearMath)
_FIND_BULLET_LIBRARY(BULLET_SOFTBODY BulletSoftBody)
set(BULLET_INCLUDE_DIRS ${BULLET_INCLUDE_DIR})
set(BULLET_LIBRARIES ${BULLET_DYNAMICS_LIBRARY} ${BULLET_COLLISION_LIBRARY} ${BULLET_MATH_LIBRARY} ${BULLET_SOFTBODY_LIBRARY})
find_package_handle_standard_args(Bullet "Could NOT find Bullet, try to set the path to Bullet root folder in the system variable BULLET_ROOT_DIR"
BULLET_DYNAMICS_LIBRARY BULLET_COLLISION_LIBRARY BULLET_MATH_LIBRARY
BULLET_INCLUDE_DIR
BULLET_INCLUDE_DIRS
BULLET_LIBRARIES
)
set(BULLET_INCLUDE_DIRS ${BULLET_INCLUDE_DIR})
if(BULLET_FOUND)
_BULLET_APPEND_LIBRARIES(BULLET_LIBRARIES BULLET_DYNAMICS_LIBRARY)
_BULLET_APPEND_LIBRARIES(BULLET_LIBRARIES BULLET_COLLISION_LIBRARY)
_BULLET_APPEND_LIBRARIES(BULLET_LIBRARIES BULLET_MATH_LIBRARY)
_BULLET_APPEND_LIBRARIES(BULLET_LIBRARIES BULLET_SOFTBODY_LIBRARY)
endif()

View file

@ -19,6 +19,7 @@ hifi_library_search_hints("glm")
# locate header
find_path(GLM_INCLUDE_DIR "glm/glm.hpp" HINTS ${GLM_SEARCH_DIRS})
set(GLM_INCLUDE_DIRS "${GLM_INCLUDE_DIR}")
include(FindPackageHandleStandardArgs)

View file

@ -23,8 +23,8 @@ else (GVERB_INCLUDE_DIRS)
include("${MACRO_DIR}/HifiLibrarySearchHints.cmake")
hifi_library_search_hints("gverb")
find_path(GVERB_INCLUDE_DIRS gverb.h PATH_SUFFIXES include HINTS ${GVERB_SEARCH_DIRS})
find_path(GVERB_SRC_DIRS gverb.c PATH_SUFFIXES src HINTS ${GVERB_SEARCH_DIRS})
find_path(GVERB_INCLUDE_DIRS gverb.h PATH_SUFFIXES include HINTS ${GVERB_SEARCH_DIRS} NO_CMAKE_FIND_ROOT_PATH)
find_path(GVERB_SRC_DIRS gverb.c PATH_SUFFIXES src HINTS ${GVERB_SEARCH_DIRS} NO_CMAKE_FIND_ROOT_PATH)
if (GVERB_INCLUDE_DIRS)
set(GVERB_FOUND TRUE)
@ -33,7 +33,7 @@ else (GVERB_INCLUDE_DIRS)
if (GVERB_FOUND)
message(STATUS "Found Gverb: ${GVERB_INCLUDE_DIRS}")
else (GVERB_FOUND)
message(FATAL_ERROR "Could NOT find Gverb. Read ./interface/externals/gverb/readme.txt")
message(FATAL_ERROR "Could NOT find Gverb. Read ./libraries/audio-client/externals/gverb/readme.txt")
endif (GVERB_FOUND)
endif(GVERB_INCLUDE_DIRS)

View file

@ -21,42 +21,60 @@
include("${MACRO_DIR}/HifiLibrarySearchHints.cmake")
hifi_library_search_hints("libovr")
find_path(LIBOVR_INCLUDE_DIRS OVR.h PATH_SUFFIXES Include HINTS ${LIBOVR_SEARCH_DIRS})
find_path(LIBOVR_SRC_DIR Util_Render_Stereo.h PATH_SUFFIXES Src/Util HINTS ${LIBOVR_SEARCH_DIRS})
include(SelectLibraryConfigurations)
if (APPLE)
find_library(LIBOVR_LIBRARY_DEBUG NAMES ovr PATH_SUFFIXES Lib/Mac/Debug HINTS ${LIBOVR_SEARCH_DIRS})
find_library(LIBOVR_LIBRARY_RELEASE NAMES ovr PATH_SUFFIXES Lib/Mac/Release HINTS ${LIBOVR_SEARCH_DIRS})
find_library(ApplicationServices ApplicationServices)
find_library(IOKit IOKit)
elseif (UNIX)
find_library(UDEV_LIBRARY_RELEASE udev /usr/lib/x86_64-linux-gnu/)
find_library(XINERAMA_LIBRARY_RELEASE Xinerama /usr/lib/x86_64-linux-gnu/)
if (NOT ANDROID)
find_path(LIBOVR_INCLUDE_DIRS OVR.h PATH_SUFFIXES Include HINTS ${LIBOVR_SEARCH_DIRS})
find_path(LIBOVR_SRC_DIR Util_Render_Stereo.h PATH_SUFFIXES Src/Util HINTS ${LIBOVR_SEARCH_DIRS})
if (CMAKE_CL_64)
set(LINUX_ARCH_DIR "i386")
else()
set(LINUX_ARCH_DIR "x86_64")
endif()
if (APPLE)
find_library(LIBOVR_LIBRARY_DEBUG NAMES ovr PATH_SUFFIXES Lib/Mac/Debug HINTS ${LIBOVR_SEARCH_DIRS})
find_library(LIBOVR_LIBRARY_RELEASE NAMES ovr PATH_SUFFIXES Lib/Mac/Release HINTS ${LIBOVR_SEARCH_DIRS})
find_library(ApplicationServices ApplicationServices)
find_library(IOKit IOKit)
elseif (UNIX)
find_library(UDEV_LIBRARY_RELEASE udev /usr/lib/x86_64-linux-gnu/)
find_library(XINERAMA_LIBRARY_RELEASE Xinerama /usr/lib/x86_64-linux-gnu/)
find_library(LIBOVR_LIBRARY_DEBUG NAMES ovr PATH_SUFFIXES Lib/Linux/Debug/${LINUX_ARCH_DIR} HINTS ${LIBOVR_SEARCH_DIRS})
find_library(LIBOVR_LIBRARY_RELEASE NAMES ovr PATH_SUFFIXES Lib/Linux/Release/${LINUX_ARCH_DIR} HINTS ${LIBOVR_SEARCH_DIRS})
if (CMAKE_CL_64)
set(LINUX_ARCH_DIR "i386")
else()
set(LINUX_ARCH_DIR "x86_64")
endif()
select_library_configurations(UDEV)
select_library_configurations(XINERAMA)
find_library(LIBOVR_LIBRARY_DEBUG NAMES ovr PATH_SUFFIXES Lib/Linux/Debug/${LINUX_ARCH_DIR} HINTS ${LIBOVR_SEARCH_DIRS})
find_library(LIBOVR_LIBRARY_RELEASE NAMES ovr PATH_SUFFIXES Lib/Linux/Release/${LINUX_ARCH_DIR} HINTS ${LIBOVR_SEARCH_DIRS})
elseif (WIN32)
if (MSVC10)
find_library(LIBOVR_LIBRARY_DEBUG NAMES libovrd PATH_SUFFIXES Lib/Win32/VS2010 HINTS ${LIBOVR_SEARCH_DIRS})
find_library(LIBOVR_LIBRARY_RELEASE NAMES libovr PATH_SUFFIXES Lib/Win32/VS2010 HINTS ${LIBOVR_SEARCH_DIRS})
elseif (MSVC12)
find_library(LIBOVR_LIBRARY_DEBUG NAMES libovrd PATH_SUFFIXES Lib/Win32/VS2013 HINTS ${LIBOVR_SEARCH_DIRS})
find_library(LIBOVR_LIBRARY_RELEASE NAMES libovr PATH_SUFFIXES Lib/Win32/VS2013 HINTS ${LIBOVR_SEARCH_DIRS})
select_library_configurations(UDEV)
select_library_configurations(XINERAMA)
elseif (WIN32)
if (MSVC10)
find_library(LIBOVR_LIBRARY_DEBUG NAMES libovrd PATH_SUFFIXES Lib/Win32/VS2010 HINTS ${LIBOVR_SEARCH_DIRS})
find_library(LIBOVR_LIBRARY_RELEASE NAMES libovr PATH_SUFFIXES Lib/Win32/VS2010 HINTS ${LIBOVR_SEARCH_DIRS})
elseif (MSVC12)
find_library(LIBOVR_LIBRARY_DEBUG NAMES libovrd PATH_SUFFIXES Lib/Win32/VS2013 HINTS ${LIBOVR_SEARCH_DIRS})
find_library(LIBOVR_LIBRARY_RELEASE NAMES libovr PATH_SUFFIXES Lib/Win32/VS2013 HINTS ${LIBOVR_SEARCH_DIRS})
endif ()
find_package(ATL)
endif ()
find_package(ATL)
endif ()
else (NOT ANDROID)
set(_VRLIB_JNI_DIR "VRLib/jni")
set(_VRLIB_LIBS_DIR "VRLib/obj/local/armeabi-v7a")
find_path(LIBOVR_VRLIB_DIR VRLib.vcxproj PATH_SUFFIXES VRLib HINTS ${LIBOVR_SEARCH_DIRS})
find_path(LIBOVR_INCLUDE_DIRS OVR.h PATH_SUFFIXES ${_VRLIB_JNI_DIR}/LibOVR/Include HINTS ${LIBOVR_SEARCH_DIRS})
find_path(LIBOVR_SRC_DIR OVR_CAPI.h PATH_SUFFIXES ${_VRLIB_JNI_DIR}/LibOVR/Src HINTS ${LIBOVR_SEARCH_DIRS})
find_path(MINIZIP_DIR minizip.c PATH_SUFFIXES ${_VRLIB_JNI_DIR}/3rdParty/minizip HINTS ${LIBOVR_SEARCH_DIRS})
find_path(JNI_DIR VrCommon.h PATH_SUFFIXES ${_VRLIB_JNI_DIR} HINTS ${LIBOVR_SEARCH_DIRS})
find_library(LIBOVR_LIBRARY_RELEASE NAMES oculus PATH_SUFFIXES ${_VRLIB_LIBS_DIR} HINTS ${LIBOVR_SEARCH_DIRS})
find_library(TURBOJPEG_LIBRARY NAMES jpeg PATH_SUFFIXES 3rdParty/turbojpeg HINTS ${LIBOVR_SEARCH_DIRS})
endif (NOT ANDROID)
select_library_configurations(LIBOVR)
set(LIBOVR_LIBRARIES ${LIBOVR_LIBRARY})
@ -66,6 +84,10 @@ list(APPEND LIBOVR_ARGS_LIST LIBOVR_INCLUDE_DIRS LIBOVR_SRC_DIR LIBOVR_LIBRARY)
if (APPLE)
list(APPEND LIBOVR_LIBRARIES ${IOKit} ${ApplicationServices})
list(APPEND LIBOVR_ARGS_LIST IOKit ApplicationServices)
elseif (ANDROID)
list(APPEND LIBOVR_ANDROID_LIBRARIES "-lGLESv3" "-lEGL" "-landroid" "-lOpenMAXAL" "-llog" "-lz" "-lOpenSLES")
list(APPEND LIBOVR_ARGS_LIST LIBOVR_ANDROID_LIBRARIES LIBOVR_VRLIB_DIR MINIZIP_DIR JNI_DIR TURBOJPEG_LIBRARY)
elseif (UNIX)
list(APPEND LIBOVR_LIBRARIES "${UDEV_LIBRARY}" "${XINERAMA_LIBRARY}")
list(APPEND LIBOVR_ARGS_LIST UDEV_LIBRARY XINERAMA_LIBRARY)
@ -75,7 +97,10 @@ elseif (WIN32)
endif ()
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(LibOVR DEFAULT_MSG ${LIBOVR_ARGS_LIST})
if (ANDROID)
list(APPEND LIBOVR_INCLUDE_DIRS ${LIBOVR_SRC_DIR} ${MINIZIP_DIR} ${JNI_DIR})
endif ()
mark_as_advanced(LIBOVR_INCLUDE_DIRS LIBOVR_LIBRARIES LIBOVR_SEARCH_DIRS)

View file

@ -52,7 +52,9 @@ else ()
set(_OPENSSL_ROOT_HINTS_AND_PATHS ${OPENSSL_SEARCH_DIRS})
endif ()
find_path(OPENSSL_INCLUDE_DIR NAMES openssl/ssl.h HINTS ${_OPENSSL_ROOT_HINTS_AND_PATHS} ${_OPENSSL_INCLUDEDIR} PATH_SUFFIXES include)
find_path(OPENSSL_INCLUDE_DIR NAMES openssl/ssl.h HINTS ${_OPENSSL_ROOT_HINTS_AND_PATHS} ${_OPENSSL_INCLUDEDIR}
PATH_SUFFIXES include
)
if (WIN32 AND NOT CYGWIN)
if (MSVC)
@ -133,7 +135,9 @@ else()
PATH_SUFFIXES lib
)
find_library(OPENSSL_CRYPTO_LIBRARY NAMES crypto HINTS ${_OPENSSL_ROOT_HINTS_AND_PATHS} ${_OPENSSL_LIBDIR} PATH_SUFFIXES lib)
find_library(OPENSSL_CRYPTO_LIBRARY NAMES crypto HINTS ${_OPENSSL_ROOT_HINTS_AND_PATHS} ${_OPENSSL_LIBDIR}
PATH_SUFFIXES lib
)
mark_as_advanced(OPENSSL_CRYPTO_LIBRARY OPENSSL_SSL_LIBRARY)
@ -179,8 +183,8 @@ endfunction()
if (OPENSSL_INCLUDE_DIR)
if(OPENSSL_INCLUDE_DIR AND EXISTS "${OPENSSL_INCLUDE_DIR}/openssl/opensslv.h")
file(STRINGS "${OPENSSL_INCLUDE_DIR}/openssl/opensslv.h" openssl_version_str
REGEX "^#define[\t ]+OPENSSL_VERSION_NUMBER[\t ]+0x([0-9a-fA-F])+.*")
REGEX "^#[ ]?define[\t ]+OPENSSL_VERSION_NUMBER[\t ]+0x([0-9a-fA-F])+.*")
# The version number is encoded as 0xMNNFFPPS: major minor fix patch status
# The status gives if this is a developer or prerelease and is ignored here.
# Major, minor, and fix directly translate into the version numbers shown in

View file

@ -1,5 +1,5 @@
#
# FindRtMidd.cmake
# FindRtMidi.cmake
#
# Try to find the RtMidi library
#

View file

@ -0,0 +1,30 @@
#
# FindSoxr.cmake
#
# Try to find the libsoxr resampling library
#
# You can provide a LIBSOXR_ROOT_DIR which contains lib and include directories
#
# Once done this will define
#
# SOXR_FOUND - system found libsoxr
# SOXR_INCLUDE_DIRS - the libsoxr include directory
# SOXR_LIBRARIES - link to this to use libsoxr
#
# Created on 1/22/2015 by Stephen Birarda
# Copyright 2015 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("${MACRO_DIR}/HifiLibrarySearchHints.cmake")
hifi_library_search_hints("soxr")
find_path(SOXR_INCLUDE_DIRS soxr.h PATH_SUFFIXES include HINTS ${SOXR_SEARCH_DIRS})
find_library(SOXR_LIBRARIES NAMES soxr PATH_SUFFIXES lib HINTS ${SOXR_SEARCH_DIRS})
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(SOXR DEFAULT_MSG SOXR_INCLUDE_DIRS SOXR_LIBRARIES)
mark_as_advanced(SOXR_INCLUDE_DIRS SOXR_LIBRARIES SOXR_SEARCH_DIRS)

View file

@ -28,7 +28,7 @@ set(_TBB_LIB_MALLOC_NAME "${_TBB_LIB_NAME}malloc")
if (APPLE)
set(_TBB_LIB_DIR "lib/libc++")
elseif (UNIX)
elseif (UNIX AND NOT ANDROID)
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
set(_TBB_ARCH_DIR "intel64")
else()
@ -56,6 +56,13 @@ elseif (WIN32)
endif()
set(_TBB_LIB_DIR "lib/${_TBB_ARCH_DIR}/vc12")
elseif (ANDROID)
set(_TBB_DEFAULT_INSTALL_DIR "/tbb")
set(_TBB_LIB_NAME "tbb")
set(_TBB_LIB_DIR "lib")
set(_TBB_LIB_MALLOC_NAME "${_TBB_LIB_NAME}malloc")
set(_TBB_LIB_DEBUG_NAME "${_TBB_LIB_NAME}_debug")
set(_TBB_LIB_MALLOC_DEBUG_NAME "${_TBB_LIB_MALLOC_NAME}_debug")
endif ()
find_library(TBB_LIBRARY_DEBUG NAMES ${_TBB_LIB_NAME}_debug PATH_SUFFIXES ${_TBB_LIB_DIR} HINTS ${TBB_SEARCH_DIRS})

View file

@ -73,6 +73,20 @@
"can_set": true
}
]
},
{
"name": "allowed_editors",
"type": "table",
"label": "Allowed Editors",
"help": "List the High Fidelity names for people you want to be able lock or unlock entities in this domain.<br/>An empty list means everyone.",
"numbered": false,
"columns": [
{
"name": "username",
"label": "Username",
"can_set": true
}
]
}
]
},
@ -433,4 +447,4 @@
}
]
}
]
]

View file

@ -28,7 +28,7 @@
#include <HTTPConnection.h>
#include <LogUtils.h>
#include <PacketHeaders.h>
#include <Settings.h>
#include <SettingHandle.h>
#include <SharedUtil.h>
#include <ShutdownEventListener.h>
#include <UUID.h>
@ -41,6 +41,11 @@ int const DomainServer::EXIT_CODE_REBOOT = 234923;
const QString ICE_SERVER_DEFAULT_HOSTNAME = "ice.highfidelity.io";
const QString ALLOWED_USERS_SETTINGS_KEYPATH = "security.allowed_users";
const QString ALLOWED_EDITORS_SETTINGS_KEYPATH = "security.allowed_editors";
DomainServer::DomainServer(int argc, char* argv[]) :
QCoreApplication(argc, argv),
_httpManager(DOMAIN_SERVER_HTTP_PORT, QString("%1/resources/web/").arg(QCoreApplication::applicationDirPath()), this),
@ -638,10 +643,16 @@ void DomainServer::handleConnectRequest(const QByteArray& packet, const HifiSock
// we got a packetUUID we didn't recognize, just add the node
nodeUUID = QUuid::createUuid();
}
SharedNodePointer newNode = DependencyManager::get<LimitedNodeList>()->addOrUpdateNode(nodeUUID, nodeType,
publicSockAddr, localSockAddr);
// if this user is in the editors list (or if the editors list is empty) set the user's node's canAdjustLocks to true
const QVariant* allowedEditorsVariant =
valueForKeyPath(_settingsManager.getSettingsMap(), ALLOWED_EDITORS_SETTINGS_KEYPATH);
QStringList allowedEditors = allowedEditorsVariant ? allowedEditorsVariant->toStringList() : QStringList();
bool canAdjustLocks = allowedEditors.isEmpty() || allowedEditors.contains(username);
SharedNodePointer newNode =
DependencyManager::get<LimitedNodeList>()->addOrUpdateNode(nodeUUID, nodeType,
publicSockAddr, localSockAddr, canAdjustLocks);
// when the newNode is created the linked data is also created
// if this was a static assignment set the UUID, set the sendingSockAddr
DomainServerNodeData* nodeData = reinterpret_cast<DomainServerNodeData*>(newNode->getLinkedData());
@ -663,7 +674,6 @@ void DomainServer::handleConnectRequest(const QByteArray& packet, const HifiSock
}
}
const QString ALLOWED_USERS_SETTINGS_KEYPATH = "security.allowed_users";
bool DomainServer::shouldAllowConnectionFromNode(const QString& username,
const QByteArray& usernameSignature,
@ -842,6 +852,7 @@ void DomainServer::sendDomainListToNode(const SharedNodePointer& node, const Hif
// always send the node their own UUID back
QDataStream broadcastDataStream(&broadcastPacket, QIODevice::Append);
broadcastDataStream << node->getUUID();
broadcastDataStream << node->getCanAdjustLocks();
int numBroadcastPacketLeadBytes = broadcastDataStream.device()->pos();
@ -906,10 +917,10 @@ void DomainServer::sendDomainListToNode(const SharedNodePointer& node, const Hif
}
});
}
// always write the last broadcastPacket
nodeList->writeDatagram(broadcastPacket, node, senderSockAddr);
}
// always write the last broadcastPacket
nodeList->writeDatagram(broadcastPacket, node, senderSockAddr);
}
void DomainServer::readAvailableDatagrams() {
@ -1925,7 +1936,7 @@ Headers DomainServer::setupCookieHeadersFromProfileReply(QNetworkReply* profileR
// persist the cookie to settings file so we can get it back on DS relaunch
QStringList path = QStringList() << DS_SETTINGS_SESSIONS_GROUP << cookieUUID.toString();
SettingHandles::SettingHandle<QVariant>(path).set(QVariant::fromValue(sessionData));
Setting::Handle<QVariant>(path).set(QVariant::fromValue(sessionData));
// setup expiry for cookie to 1 month from today
QDateTime cookieExpiry = QDateTime::currentDateTimeUtc().addMonths(1);

View file

@ -8,6 +8,7 @@
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
Script.load("progress.js");
Script.load("lookWithTouch.js");
Script.load("editEntities.js");
Script.load("selectAudioDevice.js");
@ -16,3 +17,4 @@ Script.load("headMove.js");
Script.load("inspect.js");
Script.load("lobby.js");
Script.load("notifications.js");
Script.load("lookWithMouse.js")

109
examples/dice.js Normal file
View file

@ -0,0 +1,109 @@
//
// dice.js
// examples
//
// Created by Philip Rosedale on February 2, 2015
// Copyright 2015 High Fidelity, Inc.
//
// Press the dice button to throw some dice from the center of the screen.
// Change NUMBER_OF_DICE to change the number thrown (Yahtzee, anyone?)
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
var isDice = false;
var NUMBER_OF_DICE = 2;
var dice = [];
var DIE_SIZE = 0.20;
var madeSound = true; // Set false at start of throw to look for collision
HIFI_PUBLIC_BUCKET = "http://s3.amazonaws.com/hifi-public/";
var rollSound = SoundCache.getSound(HIFI_PUBLIC_BUCKET + "sounds/dice/diceRoll.wav");
var screenSize = Controller.getViewportDimensions();
var offButton = Overlays.addOverlay("image", {
x: screenSize.x - 48,
y: 96,
width: 32,
height: 32,
imageURL: HIFI_PUBLIC_BUCKET + "images/close.png",
color: { red: 255, green: 255, blue: 255},
alpha: 1
});
var diceButton = Overlays.addOverlay("image", {
x: screenSize.x - 48,
y: 130,
width: 32,
height: 32,
imageURL: HIFI_PUBLIC_BUCKET + "images/die.png",
color: { red: 255, green: 255, blue: 255},
alpha: 1
});
var GRAVITY = -3.5;
var LIFETIME = 300;
function shootDice(position, velocity) {
for (var i = 0; i < NUMBER_OF_DICE; i++) {
dice.push(Entities.addEntity(
{ type: "Model",
modelURL: HIFI_PUBLIC_BUCKET + "models/props/Dice/goldDie.fbx",
position: position,
velocity: velocity,
rotation: Quat.fromPitchYawRollDegrees(Math.random() * 360, Math.random() * 360, Math.random() * 360),
lifetime: LIFETIME,
gravity: { x: 0, y: GRAVITY, z: 0 },
collisionsWillMove: true
}));
position = Vec3.sum(position, Vec3.multiply(DIE_SIZE, Vec3.normalize(Quat.getRight(Camera.getOrientation()))));
}
}
function deleteDice() {
while(dice.length > 0) {
Entities.deleteEntity(dice.pop());
}
}
function entityCollisionWithEntity(entity1, entity2, collision) {
if (!madeSound) {
// Is it one of our dice?
for (var i = 0; i < dice.length; i++) {
if (!dice[i].isKnownID) {
dice[i] = Entities.identifyEntity(dice[i]);
}
if ((entity1.id == dice[i].id) || (entity2.id == dice[i].id)) {
madeSound = true;
Audio.playSound(rollSound, { position: collision.contactPoint });
}
}
}
}
function mousePressEvent(event) {
var clickedText = false;
var clickedOverlay = Overlays.getOverlayAtPoint({x: event.x, y: event.y});
if (clickedOverlay == offButton) {
deleteDice();
} else if (clickedOverlay == diceButton) {
var HOW_HARD = 2.0;
var position = Vec3.sum(Camera.getPosition(), Quat.getFront(Camera.getOrientation()));
var velocity = Vec3.multiply(HOW_HARD, Quat.getFront(Camera.getOrientation()));
shootDice(position, velocity);
madeSound = false;
}
}
function scriptEnding() {
deleteDice();
Overlays.deleteOverlay(offButton);
Overlays.deleteOverlay(diceButton);
}
Entities.entityCollisionWithEntity.connect(entityCollisionWithEntity);
Controller.mousePressEvent.connect(mousePressEvent);
Script.scriptEnding.connect(scriptEnding);

View file

@ -46,27 +46,8 @@ gridTool.setVisible(false);
var entityListTool = EntityListTool();
var hasShownPropertiesTool = false;
var entityListVisible = false;
selectionManager.addEventListener(function() {
selectionDisplay.updateHandles();
if (selectionManager.hasSelection() && !hasShownPropertiesTool) {
// Open properties and model list, but force selection of model list tab
propertiesTool.setVisible(false);
entityListTool.setVisible(false);
gridTool.setVisible(false);
propertiesTool.setVisible(true);
entityListTool.setVisible(true);
gridTool.setVisible(true);
hasShownPropertiesTool = true;
}
if (!selectionManager.hasSelection()) {
toolBar.setActive(false);
} else {
toolBar.setActive(true);
}
});
var windowDimensions = Controller.getViewportDimensions();
@ -93,9 +74,11 @@ var DEFAULT_DIMENSIONS = {
};
var MENU_INSPECT_TOOL_ENABLED = "Inspect Tool";
var MENU_AUTO_FOCUS_ON_SELECT = "Auto Focus on Select";
var MENU_EASE_ON_FOCUS = "Ease Orientation on Focus";
var SETTING_INSPECT_TOOL_ENABLED = "inspectToolEnabled";
var SETTING_AUTO_FOCUS_ON_SELECT = "autoFocusOnSelect";
var SETTING_EASE_ON_FOCUS = "cameraEaseOnFocus";
var modelURLs = [
@ -111,6 +94,7 @@ var modelURLs = [
var mode = 0;
var isActive = false;
var placingEntityID = null;
var toolBar = (function () {
var that = {},
@ -137,10 +121,9 @@ var toolBar = (function () {
// Hide active button for now - this may come back, so not deleting yet.
activeButton = toolBar.addTool({
imageURL: toolIconUrl + "models-tool.svg",
// subImage: { x: 0, y: Tool.IMAGE_WIDTH, width: Tool.IMAGE_WIDTH, height: Tool.IMAGE_HEIGHT },
subImage: { x: 0, y: Tool.IMAGE_WIDTH, width: 0, height: 0 },
width: 0,//toolWidth,
height: 0,//toolHeight,
subImage: { x: 0, y: Tool.IMAGE_WIDTH, width: Tool.IMAGE_WIDTH, height: Tool.IMAGE_HEIGHT },
width: toolWidth,
height: toolHeight,
alpha: 0.9,
visible: true
}, true, false);
@ -252,7 +235,10 @@ var toolBar = (function () {
} else {
hasShownPropertiesTool = false;
cameraManager.enable();
grid.setEnabled(true);
entityListTool.setVisible(true);
gridTool.setVisible(true);
propertiesTool.setVisible(true);
Window.setFocus();
}
}
toolBar.selectTool(activeButton, active);
@ -378,7 +364,7 @@ var toolBar = (function () {
var position = Vec3.sum(MyAvatar.position, Vec3.multiply(Quat.getFront(MyAvatar.orientation), SPAWN_DISTANCE));
if (position.x > 0 && position.y > 0 && position.z > 0) {
Entities.addEntity({
placingEntityID = Entities.addEntity({
type: "Box",
position: grid.snapToSurface(grid.snapToGrid(position, false, DEFAULT_DIMENSIONS), DEFAULT_DIMENSIONS),
dimensions: DEFAULT_DIMENSIONS,
@ -395,7 +381,7 @@ var toolBar = (function () {
var position = Vec3.sum(MyAvatar.position, Vec3.multiply(Quat.getFront(MyAvatar.orientation), SPAWN_DISTANCE));
if (position.x > 0 && position.y > 0 && position.z > 0) {
Entities.addEntity({
placingEntityID = Entities.addEntity({
type: "Sphere",
position: grid.snapToSurface(grid.snapToGrid(position, false, DEFAULT_DIMENSIONS), DEFAULT_DIMENSIONS),
dimensions: DEFAULT_DIMENSIONS,
@ -411,7 +397,7 @@ var toolBar = (function () {
var position = Vec3.sum(MyAvatar.position, Vec3.multiply(Quat.getFront(MyAvatar.orientation), SPAWN_DISTANCE));
if (position.x > 0 && position.y > 0 && position.z > 0) {
Entities.addEntity({
placingEntityID = Entities.addEntity({
type: "Light",
position: grid.snapToSurface(grid.snapToGrid(position, false, DEFAULT_DIMENSIONS), DEFAULT_DIMENSIONS),
dimensions: DEFAULT_DIMENSIONS,
@ -436,14 +422,14 @@ var toolBar = (function () {
var position = Vec3.sum(MyAvatar.position, Vec3.multiply(Quat.getFront(MyAvatar.orientation), SPAWN_DISTANCE));
if (position.x > 0 && position.y > 0 && position.z > 0) {
Entities.addEntity({
placingEntityID = Entities.addEntity({
type: "Text",
position: grid.snapToSurface(grid.snapToGrid(position, false, DEFAULT_DIMENSIONS), DEFAULT_DIMENSIONS),
dimensions: DEFAULT_DIMENSIONS,
backgroundColor: { red: 0, green: 0, blue: 0 },
dimensions: { x: 0.5, y: 0.3, z: 0.01 },
backgroundColor: { red: 64, green: 64, blue: 64 },
textColor: { red: 255, green: 255, blue: 255 },
text: "some text",
lineHight: "0.1"
lineHeight: 0.06
});
} else {
print("Can't create box: Text would be out of bounds.");
@ -548,8 +534,25 @@ var mouseCapturedByTool = false;
var lastMousePosition = null;
var idleMouseTimerId = null;
var IDLE_MOUSE_TIMEOUT = 200;
var DEFAULT_ENTITY_DRAG_DROP_DISTANCE = 2.0;
function mouseMoveEvent(event) {
if (placingEntityID) {
if (!placingEntityID.isKnownID) {
placingEntityID = Entities.identifyEntity(placingEntityID);
}
var pickRay = Camera.computePickRay(event.x, event.y);
var distance = cameraManager.enabled ? cameraManager.zoomDistance : DEFAULT_ENTITY_DRAG_DROP_DISTANCE;
var offset = Vec3.multiply(distance, pickRay.direction);
var position = Vec3.sum(Camera.position, offset);
Entities.editEntity(placingEntityID, {
position: position,
});
return;
}
if (!isActive) {
return;
}
if (idleMouseTimerId) {
Script.clearTimeout(idleMouseTimerId);
}
@ -602,6 +605,10 @@ function highlightEntityUnderCursor(position, accurateRay) {
function mouseReleaseEvent(event) {
if (placingEntityID) {
selectionManager.setSelections([placingEntityID]);
placingEntityID = null;
}
if (isActive && selectionManager.hasSelection()) {
tooltip.show(false);
}
@ -617,7 +624,7 @@ function mouseReleaseEvent(event) {
}
function mouseClickEvent(event) {
if (!event.isRightButton) {
if (!event.isLeftButton || !isActive) {
return;
}
@ -670,19 +677,21 @@ function mouseClickEvent(event) {
orientation = MyAvatar.orientation;
intersection = rayPlaneIntersection(pickRay, P, Quat.getFront(orientation));
if (!event.isShifted) {
selectionManager.clearSelections();
}
var toggle = event.isShifted;
selectionManager.addEntity(foundEntity, toggle);
if (!event.isShifted) {
selectionManager.setSelections([foundEntity]);
} else {
selectionManager.addEntity(foundEntity, true);
}
print("Model selected: " + foundEntity.id);
selectionDisplay.select(selectedEntityID, event);
cameraManager.focus(selectionManager.worldPosition,
selectionManager.worldDimensions,
Menu.isOptionChecked(MENU_EASE_ON_FOCUS));
if (Menu.isOptionChecked(MENU_AUTO_FOCUS_ON_SELECT)) {
cameraManager.focus(selectionManager.worldPosition,
selectionManager.worldDimensions,
Menu.isOptionChecked(MENU_EASE_ON_FOCUS));
}
}
}
}
@ -724,7 +733,9 @@ function setupModelMenus() {
Menu.addMenuItem({ menuName: "File", menuItemName: "Import Models", shortcutKey: "CTRL+META+I", afterItem: "Export Models" });
Menu.addMenuItem({ menuName: "View", menuItemName: MENU_EASE_ON_FOCUS, afterItem: MENU_INSPECT_TOOL_ENABLED,
Menu.addMenuItem({ menuName: "View", menuItemName: MENU_AUTO_FOCUS_ON_SELECT, afterItem: MENU_INSPECT_TOOL_ENABLED,
isCheckable: true, isChecked: Settings.getValue(SETTING_AUTO_FOCUS_ON_SELECT) == "true" });
Menu.addMenuItem({ menuName: "View", menuItemName: MENU_EASE_ON_FOCUS, afterItem: MENU_AUTO_FOCUS_ON_SELECT,
isCheckable: true, isChecked: Settings.getValue(SETTING_EASE_ON_FOCUS) == "true" });
Entities.setLightsArePickable(false);
@ -750,11 +761,12 @@ function cleanupModelMenus() {
Menu.removeMenuItem("File", "Import Models");
Menu.removeMenuItem("View", MENU_INSPECT_TOOL_ENABLED);
Menu.removeMenuItem("View", MENU_AUTO_FOCUS_ON_SELECT);
Menu.removeMenuItem("View", MENU_EASE_ON_FOCUS);
}
Script.scriptEnding.connect(function() {
Settings.setValue(SETTING_INSPECT_TOOL_ENABLED, Menu.isOptionChecked(MENU_INSPECT_TOOL_ENABLED));
Settings.setValue(SETTING_AUTO_FOCUS_ON_SELECT, Menu.isOptionChecked(MENU_AUTO_FOCUS_ON_SELECT));
Settings.setValue(SETTING_EASE_ON_FOCUS, Menu.isOptionChecked(MENU_EASE_ON_FOCUS));
progressDialog.cleanup();
@ -820,9 +832,7 @@ function handeMenuEvent(menuItem) {
} else if (menuItem == "Import Models") {
modelImporter.doImport();
} else if (menuItem == "Entity List...") {
if (isActive) {
entityListTool.toggleVisible();
}
entityListTool.toggleVisible();
}
tooltip.show(false);
}

View file

@ -0,0 +1,41 @@
(function(){
var teleport;
var portalDestination;
function playSound() {
Audio.playSound(teleport, { volume: 0.40, localOnly: true });
};
this.preload = function(entityID) {
teleport = SoundCache.getSound("http://s3.amazonaws.com/hifi-public/birarda/teleport.raw");
var properties = Entities.getEntityProperties(entityID);
portalDestination = properties.userData;
print("The portal destination is " + portalDestination);
}
this.enterEntity = function(entityID) {
if (portalDestination.length > 0) {
print("Teleporting to hifi://" + portalDestination);
Window.location = "hifi://" + portalDestination;
}
};
this.leaveEntity = function(entityID) {
Entities.editEntity(entityID, {
animationURL: "http://hifi-public.s3.amazonaws.com/models/content/phonebooth.fbx",
animationSettings: '{ "frameIndex": 1, "running": false }'
});
playSound();
};
this.hoverEnterEntity = function(entityID) {
Entities.editEntity(entityID, {
animationURL: "http://hifi-public.s3.amazonaws.com/models/content/phonebooth.fbx",
animationSettings: '{ "fps": 24, "firstFrame": 1, "lastFrame": 25, "frameIndex": 1, "running": true, "hold": true }'
});
};
})

View file

@ -119,6 +119,7 @@
var elCollisionsWillMove = document.getElementById("property-collisions-will-move");
var elLifetime = document.getElementById("property-lifetime");
var elScriptURL = document.getElementById("property-script-url");
var elUserData = document.getElementById("property-user-data");
var elBoxSections = document.querySelectorAll(".box-section");
var elBoxColorRed = document.getElementById("property-box-red");
@ -224,6 +225,7 @@
elCollisionsWillMove.checked = properties.collisionsWillMove;
elLifetime.value = properties.lifetime;
elScriptURL.value = properties.script;
elUserData.value = properties.userData;
if (properties.type != "Box") {
for (var i = 0; i < elBoxSections.length; i++) {
@ -361,6 +363,7 @@
elCollisionsWillMove.addEventListener('change', createEmitCheckedPropertyUpdateFunction('collisionsWillMove'));
elLifetime.addEventListener('change', createEmitNumberPropertyUpdateFunction('lifetime'));
elScriptURL.addEventListener('change', createEmitTextPropertyUpdateFunction('script'));
elUserData.addEventListener('change', createEmitTextPropertyUpdateFunction('userData'));
var boxColorChangeFunction = createEmitColorPropertyUpdateFunction(
'color', elBoxColorRed, elBoxColorGreen, elBoxColorBlue);
@ -559,13 +562,6 @@
</div>
<div class="property">
<div class="label">Mass</div>
<div class="value">
<input type='number' id="property-mass"></input>
</div>
</div>
<div>
<div class="label">Density</div>
<div>
<input type='number' id="property-density"></input>
@ -600,6 +596,13 @@
</div>
</div>
<div class="property">
<div class="label">User Data</div>
<div class="value">
<textarea id="property-user-data"></textarea>
</div>
</div>
<div class="box-section property">
<div class="label">Color</div>
@ -645,7 +648,7 @@
<div class="model-section property">
<div class="label">Animation Settings</div>
<div class="value">
<textarea id="property-model-animation-settings" value='asdfasdf'></textarea>
<textarea id="property-model-animation-settings"></textarea>
</div>
</div>
<div class="model-section property">

View file

@ -15,11 +15,11 @@ var MOUSE_SENSITIVITY = 0.9;
var SCROLL_SENSITIVITY = 0.05;
var PAN_ZOOM_SCALE_RATIO = 0.4;
var KEY_ORBIT_SENSITIVITY = 40;
var KEY_ZOOM_SENSITIVITY = 10;
var KEY_ORBIT_SENSITIVITY = 90;
var KEY_ZOOM_SENSITIVITY = 3;
// Scaling applied based on the size of the object being focused
var FOCUS_ZOOM_SCALE = 1.3;
// Scaling applied based on the size of the object being focused (Larger values focus further away)
var FOCUS_ZOOM_SCALE = 2.3;
// Minimum zoom level when focusing on an object
var FOCUS_MIN_ZOOM = 0.5;
@ -433,8 +433,13 @@ CameraManager = function() {
that.targetYaw += (actions.orbitRight - actions.orbitLeft) * dt * KEY_ORBIT_SENSITIVITY;
that.targetPitch += (actions.orbitUp - actions.orbitDown) * dt * KEY_ORBIT_SENSITIVITY;
that.targetPitch = clamp(that.targetPitch, -90, 90);
that.targetZoomDistance += (actions.orbitBackward - actions.orbitForward) * dt * KEY_ZOOM_SENSITIVITY;
that.targetZoomDistance = clamp(that.targetZoomDistance, MIN_ZOOM_DISTANCE, MAX_ZOOM_DISTANCE);
var dZoom = actions.orbitBackward - actions.orbitForward;
if (dZoom) {
dZoom *= that.targetZoomDistance * dt * KEY_ZOOM_SENSITIVITY;
that.targetZoomDistance += dZoom;
that.targetZoomDistance = clamp(that.targetZoomDistance, MIN_ZOOM_DISTANCE, MAX_ZOOM_DISTANCE);
}
if (easing) {

View file

@ -1221,7 +1221,7 @@ SelectionDisplay = (function () {
x: selectionManager.worldDimensions.x,
y: selectionManager.worldDimensions.z
},
rotation: Quat.fromPitchYawRollDegrees(0, 0, 0),
rotation: Quat.fromPitchYawRollDegrees(90, 0, 0),
});

View file

@ -80,14 +80,6 @@ Controller.mousePressEvent.connect(mousePressEvent);
Controller.mouseMoveEvent.connect(mouseMoveEvent);
Controller.mouseReleaseEvent.connect(mouseReleaseEvent);
// disable the standard application for mouse events
Controller.captureMouseEvents();
function scriptEnding() {
// re-enabled the standard application for mouse events
Controller.releaseMouseEvents();
}
MyAvatar.bodyYaw = 0;
MyAvatar.bodyPitch = 0;
MyAvatar.bodyRoll = 0;

121
examples/planets.js Normal file
View file

@ -0,0 +1,121 @@
//
// planets.js
//
// Created by Philip Rosedale on January 26, 2015
// Copyright 2015 High Fidelity, Inc.
//
// Some planets are created in front of you. A physical object shot or thrown between them will move
// correctly.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
var MAX_RANGE = 75.0;
var MAX_TRANSLATION = MAX_RANGE / 20.0;
var LIFETIME = 600;
var DAMPING = 0.0;
var G = 3.0;
// In this section, setup where you want your 'Planets' that will exert gravity on the
// smaller test particles. Use the first one for the simplest 'planets around sun' simulation.
// Add additional planets to make things a lot more complicated!
var planetTypes = [];
planetTypes.push({ radius: 15, red: 0, green: 0, blue: 255, x: 0.0, y:0, z: 0.0 });
//planetTypes.push({ radius: 10, red: 0, green: 255, blue: 0, x: 0.60, y:0, z: 0.60 });
//planetTypes.push({ radius: 10, red: 0, green: 0, blue: 255, x: 0.75, y:0, z: 0.75 });
//planetTypes.push({ radius: 5, red: 255, green: 0, blue: 0, x: 0.25, y:0, z: 0.25 });
//planetTypes.push({ radius: 5, red: 0, green: 255, blue: 255, x: 0, y:0, z: 0 });
var center = Vec3.sum(MyAvatar.position, Vec3.multiply(MAX_RANGE, Quat.getFront(Camera.getOrientation())));
var NUM_INITIAL_PARTICLES = 200;
var PARTICLE_MIN_SIZE = 0.50;
var PARTICLE_MAX_SIZE = 1.50;
var INITIAL_VELOCITY = 5.0;
var planets = [];
var particles = [];
// Create planets that will extert gravity on test particles
for (var i = 0; i < planetTypes.length; i++) {
var rotationalVelocity = 10 + Math.random() * 60;
var position = { x: planetTypes[i].x, y: planetTypes[i].y, z: planetTypes[i].z };
position = Vec3.multiply(MAX_RANGE / 2, position);
position = Vec3.sum(center, position);
planets.push(Entities.addEntity(
{ type: "Sphere",
position: position,
dimensions: { x: planetTypes[i].radius, y: planetTypes[i].radius, z: planetTypes[i].radius },
color: { red: planetTypes[i].red, green: planetTypes[i].green, blue: planetTypes[i].blue },
gravity: { x: 0, y: 0, z: 0 },
angularVelocity: { x: 0, y: rotationalVelocity, z: 0 },
angularDamping: 0.0,
ignoreCollisions: false,
lifetime: LIFETIME,
collisionsWillMove: false }));
}
Script.setTimeout(createParticles, 1000);
function createParticles() {
// Create initial test particles that will move according to gravity from the planets
for (var i = 0; i < NUM_INITIAL_PARTICLES; i++) {
var radius = PARTICLE_MIN_SIZE + Math.random() * PARTICLE_MAX_SIZE;
var gray = Math.random() * 155;
var whichPlanet = Math.floor(Math.random() * planets.length);
var position = { x: (Math.random() - 0.5) * MAX_RANGE, y: (Math.random() - 0.5) * MAX_TRANSLATION, z: (Math.random() - 0.5) * MAX_RANGE };
var separation = Vec3.length(position);
particles.push(Entities.addEntity(
{ type: "Sphere",
position: Vec3.sum(center, position),
dimensions: { x: radius, y: radius, z: radius },
color: { red: 100 + gray, green: 100 + gray, blue: 100 + gray },
gravity: { x: 0, y: 0, z: 0 },
angularVelocity: { x: 0, y: 0, z: 0 },
velocity: Vec3.multiply(INITIAL_VELOCITY * Math.sqrt(separation), Vec3.normalize(Vec3.cross(position, { x: 0, y: 1, z: 0 }))),
ignoreCollisions: false,
damping: DAMPING,
lifetime: LIFETIME,
collisionsWillMove: true }));
}
Script.update.connect(update);
}
function scriptEnding() {
for (var i = 0; i < planetTypes.length; i++) {
Entities.deleteEntity(planets[i]);
}
for (var i = 0; i < particles.length; i++) {
Entities.deleteEntity(particles[i]);
}
}
function update(deltaTime) {
// Apply gravitational force from planets
for (var t = 0; t < particles.length; t++) {
var properties1 = Entities.getEntityProperties(particles[t]);
var velocity = properties1.velocity;
var vColor = Vec3.length(velocity) / 50 * 255;
var dV = { x:0, y:0, z:0 };
var mass1 = Math.pow(properties1.dimensions.x / 2.0, 3.0);
for (var p = 0; p < planets.length; p++) {
var properties2 = Entities.getEntityProperties(planets[p]);
var mass2 = Math.pow(properties2.dimensions.x / 2.0, 3.0);
var between = Vec3.subtract(properties1.position, properties2.position);
var separation = Vec3.length(between);
dV = Vec3.sum(dV, Vec3.multiply(-G * mass1 * mass2 / separation, Vec3.normalize(between)));
}
if (Math.random() < 0.1) {
Entities.editEntity(particles[t], { color: { red: vColor, green: 100, blue: (255 - vColor) }, velocity: Vec3.sum(velocity, Vec3.multiply(deltaTime, dV))});
} else {
Entities.editEntity(particles[t], { velocity: Vec3.sum(velocity, Vec3.multiply(deltaTime, dV))});
}
}
}
Script.scriptEnding.connect(scriptEnding);

265
examples/progress.js Normal file
View file

@ -0,0 +1,265 @@
//
// progress.js
// examples
//
// Created by David Rowe on 29 Jan 2015.
// Copyright 2015 High Fidelity, Inc.
//
// This script displays a progress download indicator when downloads are in progress.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
(function () {
var progress = 100, // %
alpha = 0.0,
alphaDelta = 0.0, // > 0 if fading in; < 0 if fading out/
ALPHA_DELTA_IN = 0.15,
ALPHA_DELTA_OUT = -0.02,
fadeTimer = null,
FADE_INTERVAL = 30, // ms between changes in alpha.
fadeWaitTimer = null,
FADE_OUT_WAIT = 1000, // Wait before starting to fade out after progress 100%.
visible = false,
BAR_WIDTH = 320, // Nominal dimension of SVG in pixels of visible portion (half) of the bar.
BAR_HEIGHT = 20,
BAR_URL = "http://hifi-public.s3.amazonaws.com/images/progress-bar.svg",
BACKGROUND_WIDTH = 360,
BACKGROUND_HEIGHT = 60,
BACKGROUND_URL = "http://hifi-public.s3.amazonaws.com/images/progress-bar-background.svg",
isOnHMD = false,
windowWidth = 0,
windowHeight = 0,
background2D = {},
bar2D = {},
SCALE_2D = 0.55, // Scale the SVGs for 2D display.
background3D = {},
bar3D = {},
ENABLE_VR_MODE_MENU_ITEM = "Enable VR Mode",
PROGRESS_3D_DIRECTION = 0.0, // Degrees from avatar orientation.
PROGRESS_3D_DISTANCE = 0.602, // Horizontal distance from avatar position.
PROGRESS_3D_ELEVATION = -0.8, // Height of top middle of top notification relative to avatar eyes.
PROGRESS_3D_YAW = 0.0, // Degrees relative to notifications direction.
PROGRESS_3D_PITCH = -60.0, // Degrees from vertical.
SCALE_3D = 0.0017, // Scale the bar SVG for 3D display.
BACKGROUND_3D_SIZE = { x: 0.76, y: 0.08 }, // Match up with the 3D background with those of notifications.js notices.
BACKGROUND_3D_COLOR = { red: 2, green: 2, blue: 2 },
BACKGROUND_3D_ALPHA = 0.7;
function fade() {
alpha = alpha + alphaDelta;
if (alpha < 0) {
alpha = 0;
}
if (alpha > 1) {
alpha = 1;
}
if (alpha === 0 || alpha === 1) { // Finished fading in or out
alphaDelta = 0;
Script.clearInterval(fadeTimer);
}
if (alpha === 0) { // Finished fading out
visible = false;
}
if (isOnHMD) {
Overlays.editOverlay(background3D.overlay, {
backgroundAlpha: alpha * BACKGROUND_3D_ALPHA,
visible: visible
});
} else {
Overlays.editOverlay(background2D.overlay, {
alpha: alpha,
visible: visible
});
}
Overlays.editOverlay(isOnHMD ? bar3D.overlay : bar2D.overlay, {
alpha: alpha,
visible: visible
});
}
function onDownloadInfoChanged(info) {
var i;
// Calculate progress
if (info.downloading.length + info.pending === 0) {
progress = 100;
} else {
progress = 0;
for (i = 0; i < info.downloading.length; i += 1) {
progress += info.downloading[i];
}
progress = progress / (info.downloading.length + info.pending);
}
// Update state
if (!visible) { // Not visible because no recent downloads
if (progress < 100) { // Have started downloading so fade in
visible = true;
alphaDelta = ALPHA_DELTA_IN;
fadeTimer = Script.setInterval(fade, FADE_INTERVAL);
}
} else if (alphaDelta !== 0.0) { // Fading in or out
if (alphaDelta > 0) {
if (progress === 100) { // Was donloading but now have finished so fade out
alphaDelta = ALPHA_DELTA_OUT;
}
} else {
if (progress < 100) { // Was finished downloading but have resumed so fade in
alphaDelta = ALPHA_DELTA_IN;
}
}
} else { // Fully visible because downloading or recently so
if (fadeWaitTimer === null) {
if (progress === 100) { // Was downloading but have finished so fade out soon
fadeWaitTimer = Script.setTimeout(function () {
alphaDelta = ALPHA_DELTA_OUT;
fadeTimer = Script.setInterval(fade, FADE_INTERVAL);
fadeWaitTimer = null;
}, FADE_OUT_WAIT);
}
} else {
if (progress < 100) { // Was finished and waiting to fade out but have resumed downloading so don't fade out
Script.clearInterval(fadeWaitTimer);
fadeWaitTimer = null;
}
}
}
// Update progress bar
if (visible) {
Overlays.editOverlay(isOnHMD ? bar3D.overlay : bar2D.overlay, {
subImage: { x: BAR_WIDTH * (1 - progress / 100), y: 0, width: BAR_WIDTH, height: BAR_HEIGHT }
});
}
}
function createOverlays() {
if (isOnHMD) {
background3D.overlay = Overlays.addOverlay("rectangle3d", {
size: BACKGROUND_3D_SIZE,
color: BACKGROUND_3D_COLOR,
alpha: BACKGROUND_3D_ALPHA,
solid: true,
isFacingAvatar: false,
visible: false,
ignoreRayIntersection: true
});
bar3D.overlay = Overlays.addOverlay("billboard", {
url: BAR_URL,
subImage: { x: BAR_WIDTH, y: 0, width: BAR_WIDTH, height: BAR_HEIGHT },
scale: SCALE_3D * BAR_WIDTH,
isFacingAvatar: false,
visible: false,
alpha: 0.0,
ignoreRayIntersection: true
});
} else {
background2D.overlay = Overlays.addOverlay("image", {
imageURL: BACKGROUND_URL,
width: background2D.width,
height: background2D.height,
visible: false,
alpha: 0.0
});
bar2D.overlay = Overlays.addOverlay("image", {
imageURL: BAR_URL,
subImage: { x: BAR_WIDTH, y: 0, width: BAR_WIDTH, height: BAR_HEIGHT },
width: bar2D.width,
height: bar2D.height,
visible: false,
alpha: 0.0
});
}
}
function deleteOverlays() {
Overlays.deleteOverlay(isOnHMD ? background3D.overlay : background2D.overlay);
Overlays.deleteOverlay(isOnHMD ? bar3D.overlay : bar2D.overlay);
}
function update() {
var viewport,
eyePosition,
avatarOrientation;
if (isOnHMD !== Menu.isOptionChecked(ENABLE_VR_MODE_MENU_ITEM)) {
deleteOverlays();
isOnHMD = !isOnHMD;
createOverlays();
}
if (visible) {
if (isOnHMD) {
// Update 3D overlays to maintain positions relative to avatar
eyePosition = MyAvatar.getDefaultEyePosition();
avatarOrientation = MyAvatar.orientation;
Overlays.editOverlay(background3D.overlay, {
position: Vec3.sum(eyePosition, Vec3.multiplyQbyV(avatarOrientation, background3D.offset)),
rotation: Quat.multiply(avatarOrientation, background3D.orientation)
});
Overlays.editOverlay(bar3D.overlay, {
position: Vec3.sum(eyePosition, Vec3.multiplyQbyV(avatarOrientation, bar3D.offset)),
rotation: Quat.multiply(avatarOrientation, bar3D.orientation)
});
} else {
// Update 2D overlays to maintain positions at bottom middle of window
viewport = Controller.getViewportDimensions();
if (viewport.x !== windowWidth || viewport.y !== windowHeight) {
windowWidth = viewport.x;
windowHeight = viewport.y;
Overlays.editOverlay(background2D.overlay, {
x: windowWidth / 2 - background2D.width / 2,
y: windowHeight - background2D.height - bar2D.height
});
Overlays.editOverlay(bar2D.overlay, {
x: windowWidth / 2 - bar2D.width / 2,
y: windowHeight - background2D.height - bar2D.height + (background2D.height - bar2D.height) / 2
});
}
}
}
}
function setUp() {
background2D.width = SCALE_2D * BACKGROUND_WIDTH;
background2D.height = SCALE_2D * BACKGROUND_HEIGHT;
bar2D.width = SCALE_2D * BAR_WIDTH;
bar2D.height = SCALE_2D * BAR_HEIGHT;
background3D.offset = Vec3.multiplyQbyV(Quat.fromPitchYawRollDegrees(0, PROGRESS_3D_DIRECTION, 0),
{ x: 0, y: 0, z: -PROGRESS_3D_DISTANCE });
background3D.offset.y += PROGRESS_3D_ELEVATION;
background3D.orientation = Quat.fromPitchYawRollDegrees(PROGRESS_3D_PITCH, PROGRESS_3D_DIRECTION + PROGRESS_3D_YAW, 0);
bar3D.offset = Vec3.sum(background3D.offset, { x: 0, y: 0, z: 0.001 }); // Just in front of background
bar3D.orientation = background3D.orientation;
createOverlays();
}
function tearDown() {
deleteOverlays();
}
setUp();
GlobalServices.downloadInfoChanged.connect(onDownloadInfoChanged);
GlobalServices.updateDownloadInfo();
Script.update.connect(update);
Script.scriptEnding.connect(tearDown);
}());

View file

@ -0,0 +1,88 @@
set(TARGET_NAME gvr-interface)
if (ANDROID)
set(ANDROID_APK_BUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/apk-build")
set(ANDROID_APK_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/apk")
set(ANDROID_SDK_ROOT $ENV{ANDROID_HOME})
set(ANDROID_APP_DISPLAY_NAME Interface)
set(ANDROID_API_LEVEL 19)
set(ANDROID_APK_PACKAGE io.highfidelity.gvrinterface)
set(ANDROID_ACTIVITY_NAME io.highfidelity.gvrinterface.InterfaceActivity)
set(ANDROID_APK_VERSION_NAME "0.1")
set(ANDROID_APK_VERSION_CODE 1)
set(ANDROID_APK_FULLSCREEN TRUE)
set(ANDROID_DEPLOY_QT_INSTALL "--install")
set(BUILD_SHARED_LIBS ON)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${ANDROID_APK_OUTPUT_DIR}/libs/${ANDROID_ABI}")
setup_hifi_library(Gui Widgets AndroidExtras)
else ()
setup_hifi_project(Gui Widgets)
endif ()
include_directories(${Qt5Gui_PRIVATE_INCLUDE_DIRS})
include_glm()
link_hifi_libraries(shared networking audio-client avatars)
include_dependency_includes()
if (ANDROID)
find_package(LibOVR)
if (LIBOVR_FOUND)
add_definitions(-DHAVE_LIBOVR)
target_link_libraries(${TARGET_NAME} ${LIBOVR_LIBRARIES} ${LIBOVR_ANDROID_LIBRARIES} ${TURBOJPEG_LIBRARY})
include_directories(SYSTEM ${LIBOVR_INCLUDE_DIRS})
# we need VRLib, so add a project.properties to our apk build folder that says that
file(RELATIVE_PATH RELATIVE_VRLIB_PATH ${ANDROID_APK_OUTPUT_DIR} "${LIBOVR_VRLIB_DIR}")
file(WRITE "${ANDROID_APK_BUILD_DIR}/project.properties" "android.library.reference.1=${RELATIVE_VRLIB_PATH}")
list(APPEND IGNORE_COPY_LIBS ${LIBOVR_ANDROID_LIBRARIES})
endif ()
endif ()
# the presence of a HOCKEY_APP_ID means we are making a beta build
if (ANDROID AND HOCKEY_APP_ID)
set(HOCKEY_APP_ENABLED true)
set(HOCKEY_APP_ACTIVITY "<activity android:name='net.hockeyapp.android.UpdateActivity' />\n")
set(ANDROID_ACTIVITY_NAME io.highfidelity.gvrinterface.InterfaceBetaActivity)
set(ANDROID_DEPLOY_QT_INSTALL "")
set(ANDROID_APK_CUSTOM_NAME "Interface-beta.apk")
# set the ANDROID_APK_VERSION_CODE to the number of git commits
execute_process(
COMMAND git rev-list --first-parent --count HEAD
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE GIT_COMMIT_COUNT
OUTPUT_STRIP_TRAILING_WHITESPACE
)
set(ANDROID_APK_VERSION_CODE ${GIT_COMMIT_COUNT})
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/templates/InterfaceBetaActivity.java.in" "${ANDROID_APK_BUILD_DIR}/src/io/highfidelity/gvrinterface/InterfaceBetaActivity.java")
elseif (ANDROID)
set(HOCKEY_APP_ENABLED false)
endif ()
if (ANDROID)
set(HIFI_URL_INTENT "<intent-filter>\
\n <action android:name='android.intent.action.VIEW' />\
\n <category android:name='android.intent.category.DEFAULT' />\
\n <category android:name='android.intent.category.BROWSABLE' />\
\n <data android:scheme='hifi' />\
\n </intent-filter>"
)
set(ANDROID_EXTRA_APPLICATION_XML "${HOCKEY_APP_ACTIVITY}")
set(ANDROID_EXTRA_ACTIVITY_XML "${HIFI_URL_INTENT}")
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/templates/hockeyapp.xml.in" "${ANDROID_APK_BUILD_DIR}/res/values/hockeyapp.xml")
qt_create_apk()
endif (ANDROID)

Binary file not shown.

After

(image error) Size: 9.7 KiB

View file

@ -0,0 +1,75 @@
//
// Client.cpp
// gvr-interface/src
//
// Created by Stephen Birarda on 1/20/15.
// 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 <QtCore/QThread>
#include <AccountManager.h>
#include <AddressManager.h>
#include <HifiSockAddr.h>
#include <NodeList.h>
#include <PacketHeaders.h>
#include "Client.h"
Client::Client(QObject* parent) :
QObject(parent)
{
// we need to make sure that required dependencies are created
DependencyManager::set<AddressManager>();
setupNetworking();
}
void Client::setupNetworking() {
// once Application order of instantiation is fixed this should be done from AccountManager
AccountManager::getInstance().setAuthURL(DEFAULT_NODE_AUTH_URL);
// setup the NodeList for this client
DependencyManager::registerInheritance<LimitedNodeList, NodeList>();
auto nodeList = DependencyManager::set<NodeList>(NodeType::Agent, 0);
// while datagram processing remains simple for targets using Client, we'll handle datagrams
connect(&nodeList->getNodeSocket(), &QUdpSocket::readyRead, this, &Client::processDatagrams);
// every second, ask the NodeList to check in with the domain server
QTimer* domainCheckInTimer = new QTimer(this);
domainCheckInTimer->setInterval(DOMAIN_SERVER_CHECK_IN_MSECS);
connect(domainCheckInTimer, &QTimer::timeout, nodeList.data(), &NodeList::sendDomainServerCheckIn);
// TODO: once the Client knows its Address on start-up we should be able to immediately send a check in here
domainCheckInTimer->start();
// handle the case where the domain stops talking to us
// TODO: can we just have the nodelist do this when it sets up? Is there a user of the NodeList that wouldn't want this?
connect(nodeList.data(), &NodeList::limitOfSilentDomainCheckInsReached, nodeList.data(), &NodeList::reset);
}
void Client::processVerifiedPacket(const HifiSockAddr& senderSockAddr, const QByteArray& incomingPacket) {
DependencyManager::get<NodeList>()->processNodeData(senderSockAddr, incomingPacket);
}
void Client::processDatagrams() {
HifiSockAddr senderSockAddr;
static QByteArray incomingPacket;
auto nodeList = DependencyManager::get<NodeList>();
while (DependencyManager::get<NodeList>()->getNodeSocket().hasPendingDatagrams()) {
incomingPacket.resize(nodeList->getNodeSocket().pendingDatagramSize());
nodeList->getNodeSocket().readDatagram(incomingPacket.data(), incomingPacket.size(),
senderSockAddr.getAddressPointer(), senderSockAddr.getPortPointer());
if (nodeList->packetVersionAndHashMatch(incomingPacket)) {
processVerifiedPacket(senderSockAddr, incomingPacket);
}
}
}

View file

@ -0,0 +1,32 @@
//
// Client.h
// gvr-interface/src
//
// Created by Stephen Birarda on 1/20/15.
// 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
//
#ifndef hifi_Client_h
#define hifi_Client_h
#include <QtCore/QObject>
#include <HifiSockAddr.h>
class QThread;
class Client : public QObject {
Q_OBJECT
public:
Client(QObject* parent = 0);
protected:
void setupNetworking();
virtual void processVerifiedPacket(const HifiSockAddr& senderSockAddr, const QByteArray& incomingPacket);
private slots:
void processDatagrams();
};
#endif // hifi_Client_h

View file

@ -0,0 +1,184 @@
//
// GVRInterface.cpp
// gvr-interface/src
//
// Created by Stephen Birarda on 11/18/14.
// 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
//
#ifdef ANDROID
#include <jni.h>
#include <qpa/qplatformnativeinterface.h>
#include <QtAndroidExtras/QAndroidJniEnvironment>
#include <QtAndroidExtras/QAndroidJniObject>
#ifdef HAVE_LIBOVR
#include <KeyState.h>
#include <VrApi/VrApi.h>
#endif
#endif
#include <QtCore/QTimer>
#include <QtGui/QKeyEvent>
#include <QtWidgets/QMenuBar>
#include "GVRMainWindow.h"
#include "RenderingClient.h"
#include "GVRInterface.h"
static QString launchURLString = QString();
#ifdef ANDROID
extern "C" {
JNIEXPORT void Java_io_highfidelity_gvrinterface_InterfaceActivity_handleHifiURL(JNIEnv *jni, jclass clazz, jstring hifiURLString) {
launchURLString = QAndroidJniObject(hifiURLString).toString();
}
}
#endif
GVRInterface::GVRInterface(int argc, char* argv[]) :
QApplication(argc, argv),
_mainWindow(NULL),
_inVRMode(false)
{
setApplicationName("gvr-interface");
setOrganizationName("highfidelity");
setOrganizationDomain("io");
if (!launchURLString.isEmpty()) {
// did we get launched with a lookup URL? If so it is time to give that to the AddressManager
qDebug() << "We were opened via a hifi URL -" << launchURLString;
}
_client = new RenderingClient(this, launchURLString);
launchURLString = QString();
connect(this, &QGuiApplication::applicationStateChanged, this, &GVRInterface::handleApplicationStateChange);
#if defined(ANDROID) && defined(HAVE_LIBOVR)
QAndroidJniEnvironment jniEnv;
QPlatformNativeInterface* interface = QApplication::platformNativeInterface();
jobject activity = (jobject) interface->nativeResourceForIntegration("QtActivity");
ovr_RegisterHmtReceivers(&*jniEnv, activity);
// PLATFORMACTIVITY_REMOVAL: Temp workaround for PlatformActivity being
// stripped from UnityPlugin. Alternate is to use LOCAL_WHOLE_STATIC_LIBRARIES
// but that increases the size of the plugin by ~1MiB
OVR::linkerPlatformActivity++;
#endif
// call our idle function whenever we can
QTimer* idleTimer = new QTimer(this);
connect(idleTimer, &QTimer::timeout, this, &GVRInterface::idle);
idleTimer->start(0);
}
void GVRInterface::idle() {
#if defined(ANDROID) && defined(HAVE_LIBOVR)
if (!_inVRMode && ovr_IsHeadsetDocked()) {
qDebug() << "The headset just got docked - enter VR mode.";
enterVRMode();
} else if (_inVRMode) {
if (ovr_IsHeadsetDocked()) {
static int counter = 0;
// Get the latest head tracking state, predicted ahead to the midpoint of the time
// it will be displayed. It will always be corrected to the real values by
// time warp, but the closer we get, the less black will be pulled in at the edges.
const double now = ovr_GetTimeInSeconds();
static double prev;
const double rawDelta = now - prev;
prev = now;
const double clampedPrediction = std::min( 0.1, rawDelta * 2);
ovrSensorState sensor = ovrHmd_GetSensorState(OvrHmd, now + clampedPrediction, true );
auto ovrOrientation = sensor.Predicted.Pose.Orientation;
glm::quat newOrientation(ovrOrientation.w, ovrOrientation.x, ovrOrientation.y, ovrOrientation.z);
_client->setOrientation(newOrientation);
if (counter++ % 100000 == 0) {
qDebug() << "GetSensorState in frame" << counter << "-"
<< ovrOrientation.x << ovrOrientation.y << ovrOrientation.z << ovrOrientation.w;
}
} else {
qDebug() << "The headset was undocked - leaving VR mode.";
leaveVRMode();
}
}
OVR::KeyState& backKeyState = _mainWindow->getBackKeyState();
auto backEvent = backKeyState.Update(ovr_GetTimeInSeconds());
if (backEvent == OVR::KeyState::KEY_EVENT_LONG_PRESS) {
qDebug() << "Attemping to start the Platform UI Activity.";
ovr_StartPackageActivity(_ovr, PUI_CLASS_NAME, PUI_GLOBAL_MENU);
} else if (backEvent == OVR::KeyState::KEY_EVENT_DOUBLE_TAP || backEvent == OVR::KeyState::KEY_EVENT_SHORT_PRESS) {
qDebug() << "Got an event we should cancel for!";
} else if (backEvent == OVR::KeyState::KEY_EVENT_DOUBLE_TAP) {
qDebug() << "The button is down!";
}
#endif
}
void GVRInterface::handleApplicationStateChange(Qt::ApplicationState state) {
switch(state) {
case Qt::ApplicationActive:
qDebug() << "The application is active.";
break;
case Qt::ApplicationSuspended:
qDebug() << "The application is being suspended.";
break;
default:
break;
}
}
void GVRInterface::enterVRMode() {
#if defined(ANDROID) && defined(HAVE_LIBOVR)
// Default vrModeParms
ovrModeParms vrModeParms;
vrModeParms.AsynchronousTimeWarp = true;
vrModeParms.AllowPowerSave = true;
vrModeParms.DistortionFileName = NULL;
vrModeParms.EnableImageServer = false;
vrModeParms.CpuLevel = 2;
vrModeParms.GpuLevel = 2;
vrModeParms.GameThreadTid = 0;
QAndroidJniEnvironment jniEnv;
QPlatformNativeInterface* interface = QApplication::platformNativeInterface();
jobject activity = (jobject) interface->nativeResourceForIntegration("QtActivity");
vrModeParms.ActivityObject = activity;
ovrHmdInfo hmdInfo;
_ovr = ovr_EnterVrMode(vrModeParms, &hmdInfo);
_inVRMode = true;
#endif
}
void GVRInterface::leaveVRMode() {
#if defined(ANDROID) && defined(HAVE_LIBOVR)
ovr_LeaveVrMode(_ovr);
_inVRMode = false;
#endif
}

View file

@ -0,0 +1,71 @@
//
// GVRInterface.h
// gvr-interface/src
//
// Created by Stephen Birarda on 11/18/14.
// 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
//
#ifndef hifi_GVRInterface_h
#define hifi_GVRInterface_h
#include <QtWidgets/QApplication>
#if defined(ANDROID) && defined(HAVE_LIBOVR)
class ovrMobile;
class ovrHmdInfo;
// This is set by JNI_OnLoad() when the .so is initially loaded.
// Must use to attach each thread that will use JNI:
namespace OVR {
// PLATFORMACTIVITY_REMOVAL: Temp workaround for PlatformActivity being
// stripped from UnityPlugin. Alternate is to use LOCAL_WHOLE_STATIC_LIBRARIES
// but that increases the size of the plugin by ~1MiB
extern int linkerPlatformActivity;
}
#endif
class GVRMainWindow;
class RenderingClient;
class QKeyEvent;
#if defined(qApp)
#undef qApp
#endif
#define qApp (static_cast<GVRInterface*>(QApplication::instance()))
class GVRInterface : public QApplication {
Q_OBJECT
public:
GVRInterface(int argc, char* argv[]);
RenderingClient* getClient() { return _client; }
void setMainWindow(GVRMainWindow* mainWindow) { _mainWindow = mainWindow; }
protected:
void keyPressEvent(QKeyEvent* event);
private slots:
void handleApplicationStateChange(Qt::ApplicationState state);
void idle();
private:
void enterVRMode();
void leaveVRMode();
#if defined(ANDROID) && defined(HAVE_LIBOVR)
ovrMobile* _ovr;
ovrHmdInfo* _hmdInfo;
#endif
GVRMainWindow* _mainWindow;
RenderingClient* _client;
bool _inVRMode;
};
#endif // hifi_GVRInterface_h

View file

@ -0,0 +1,176 @@
//
// GVRMainWindow.cpp
// gvr-interface/src
//
// Created by Stephen Birarda on 1/20/14.
// 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 <QtGui/QKeyEvent>
#include <QtWidgets/QApplication>
#include <QtWidgets/QInputDialog>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QVBoxLayout>
#ifndef ANDROID
#include <QtWidgets/QDesktopWidget>
#elif defined(HAVE_LIBOVR)
#include <OVR_CAPI.h>
const float LIBOVR_DOUBLE_TAP_DURATION = 0.25f;
const float LIBOVR_LONG_PRESS_DURATION = 0.75f;
#endif
#include <AddressManager.h>
#include "InterfaceView.h"
#include "LoginDialog.h"
#include "RenderingClient.h"
#include "GVRMainWindow.h"
GVRMainWindow::GVRMainWindow(QWidget* parent) :
QMainWindow(parent),
#if defined(ANDROID) && defined(HAVE_LIBOVR)
_backKeyState(LIBOVR_DOUBLE_TAP_DURATION, LIBOVR_LONG_PRESS_DURATION),
_wasBackKeyDown(false),
#endif
_mainLayout(NULL),
_menuBar(NULL),
_loginAction(NULL)
{
#ifndef ANDROID
const int NOTE_4_WIDTH = 2560;
const int NOTE_4_HEIGHT = 1440;
setFixedSize(NOTE_4_WIDTH / 2, NOTE_4_HEIGHT / 2);
#endif
setupMenuBar();
QWidget* baseWidget = new QWidget(this);
// setup a layout so we can vertically align to top
_mainLayout = new QVBoxLayout(baseWidget);
_mainLayout->setAlignment(Qt::AlignTop);
// set the layout on the base widget
baseWidget->setLayout(_mainLayout);
setCentralWidget(baseWidget);
// add the interface view
new InterfaceView(baseWidget);
}
GVRMainWindow::~GVRMainWindow() {
delete _menuBar;
}
void GVRMainWindow::keyPressEvent(QKeyEvent* event) {
#ifdef ANDROID
if (event->key() == Qt::Key_Back) {
// got the Android back key, hand off to OVR KeyState
_backKeyState.HandleEvent(ovr_GetTimeInSeconds(), true, (_wasBackKeyDown ? 1 : 0));
_wasBackKeyDown = true;
return;
}
#endif
QWidget::keyPressEvent(event);
}
void GVRMainWindow::keyReleaseEvent(QKeyEvent* event) {
#ifdef ANDROID
if (event->key() == Qt::Key_Back) {
// release on the Android back key, hand off to OVR KeyState
_backKeyState.HandleEvent(ovr_GetTimeInSeconds(), false, 0);
_wasBackKeyDown = false;
}
#endif
QWidget::keyReleaseEvent(event);
}
void GVRMainWindow::setupMenuBar() {
QMenu* fileMenu = new QMenu("File");
QMenu* helpMenu = new QMenu("Help");
_menuBar = new QMenuBar(0);
_menuBar->addMenu(fileMenu);
_menuBar->addMenu(helpMenu);
QAction* goToAddress = new QAction("Go to Address", fileMenu);
connect(goToAddress, &QAction::triggered, this, &GVRMainWindow::showAddressBar);
fileMenu->addAction(goToAddress);
_loginAction = new QAction("Login", fileMenu);
fileMenu->addAction(_loginAction);
// change the login action depending on our logged in/out state
AccountManager& accountManager = AccountManager::getInstance();
connect(&accountManager, &AccountManager::loginComplete, this, &GVRMainWindow::refreshLoginAction);
connect(&accountManager, &AccountManager::logoutComplete, this, &GVRMainWindow::refreshLoginAction);
// refresh the state now
refreshLoginAction();
QAction* aboutQt = new QAction("About Qt", helpMenu);
connect(aboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
helpMenu->addAction(aboutQt);
setMenuBar(_menuBar);
}
void GVRMainWindow::showAddressBar() {
// setup the address QInputDialog
QInputDialog* addressDialog = new QInputDialog(this);
addressDialog->setLabelText("Address");
// add the address dialog to the main layout
_mainLayout->addWidget(addressDialog);
connect(addressDialog, &QInputDialog::textValueSelected,
DependencyManager::get<AddressManager>().data(), &AddressManager::handleLookupString);
}
void GVRMainWindow::showLoginDialog() {
LoginDialog* loginDialog = new LoginDialog(this);
// have the acccount manager handle credentials from LoginDialog
AccountManager& accountManager = AccountManager::getInstance();
connect(loginDialog, &LoginDialog::credentialsEntered, &accountManager, &AccountManager::requestAccessToken);
connect(&accountManager, &AccountManager::loginFailed, this, &GVRMainWindow::showLoginFailure);
_mainLayout->addWidget(loginDialog);
}
void GVRMainWindow::showLoginFailure() {
QMessageBox::warning(this, "Login Failed",
"Could not log in with that username and password. Please try again!");
}
void GVRMainWindow::refreshLoginAction() {
AccountManager& accountManager = AccountManager::getInstance();
disconnect(_loginAction, &QAction::triggered, &accountManager, 0);
if (accountManager.isLoggedIn()) {
_loginAction->setText("Logout");
connect(_loginAction, &QAction::triggered, &accountManager, &AccountManager::logout);
} else {
_loginAction->setText("Login");
connect(_loginAction, &QAction::triggered, this, &GVRMainWindow::showLoginDialog);
}
}

View file

@ -0,0 +1,58 @@
//
// GVRMainWindow.h
// gvr-interface/src
//
// Created by Stephen Birarda on 1/20/14.
// 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
//
#ifndef hifi_GVRMainWindow_h
#define hifi_GVRMainWindow_h
#include <QtWidgets/QMainWindow>
#if defined(ANDROID) && defined(HAVE_LIBOVR)
#include <KeyState.h>
#endif
class QKeyEvent;
class QMenuBar;
class QVBoxLayout;
class GVRMainWindow : public QMainWindow {
Q_OBJECT
public:
GVRMainWindow(QWidget* parent = 0);
~GVRMainWindow();
public slots:
void showAddressBar();
void showLoginDialog();
void showLoginFailure();
#if defined(ANDROID) && defined(HAVE_LIBOVR)
OVR::KeyState& getBackKeyState() { return _backKeyState; }
#endif
protected:
void keyPressEvent(QKeyEvent* event);
void keyReleaseEvent(QKeyEvent* event);
private slots:
void refreshLoginAction();
private:
void setupMenuBar();
#if defined(ANDROID) && defined(HAVE_LIBOVR)
OVR::KeyState _backKeyState;
bool _wasBackKeyDown;
#endif
QVBoxLayout* _mainLayout;
QMenuBar* _menuBar;
QAction* _loginAction;
};
#endif // hifi_GVRMainWindow_h

View file

@ -0,0 +1,18 @@
//
// InterfaceView.cpp
// gvr-interface/src
//
// Created by Stephen Birarda on 1/28/14.
// 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 "InterfaceView.h"
InterfaceView::InterfaceView(QWidget* parent, Qt::WindowFlags flags) :
QOpenGLWidget(parent, flags)
{
}

View file

@ -0,0 +1,23 @@
//
// InterfaceView.h
// gvr-interface/src
//
// Created by Stephen Birarda on 1/28/14.
// 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
//
#ifndef hifi_InterfaceView_h
#define hifi_InterfaceView_h
#include <QtWidgets/QOpenGLWidget>
class InterfaceView : public QOpenGLWidget {
Q_OBJECT
public:
InterfaceView(QWidget* parent = 0, Qt::WindowFlags flags = 0);
};
#endif // hifi_InterfaceView_h

View file

@ -0,0 +1,69 @@
//
// LoginDialog.cpp
// gvr-interface/src
//
// Created by Stephen Birarda on 2015-02-03.
// Copyright 2015 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 <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include "LoginDialog.h"
LoginDialog::LoginDialog(QWidget* parent) :
QDialog(parent)
{
setupGUI();
setWindowTitle("Login");
setModal(true);
}
void LoginDialog::setupGUI() {
// setup a grid layout
QGridLayout* formGridLayout = new QGridLayout(this);
_usernameLineEdit = new QLineEdit(this);
QLabel* usernameLabel = new QLabel(this);
usernameLabel->setText("Username");
usernameLabel->setBuddy(_usernameLineEdit);
formGridLayout->addWidget(usernameLabel, 0, 0);
formGridLayout->addWidget(_usernameLineEdit, 1, 0);
_passwordLineEdit = new QLineEdit(this);
_passwordLineEdit->setEchoMode(QLineEdit::Password);
QLabel* passwordLabel = new QLabel(this);
passwordLabel->setText("Password");
passwordLabel->setBuddy(_passwordLineEdit);
formGridLayout->addWidget(passwordLabel, 2, 0);
formGridLayout->addWidget(_passwordLineEdit, 3, 0);
QDialogButtonBox* buttons = new QDialogButtonBox(this);
QPushButton* okButton = buttons->addButton(QDialogButtonBox::Ok);
QPushButton* cancelButton = buttons->addButton(QDialogButtonBox::Cancel);
okButton->setText("Login");
connect(cancelButton, &QPushButton::clicked, this, &QDialog::close);
connect(okButton, &QPushButton::clicked, this, &LoginDialog::loginButtonClicked);
formGridLayout->addWidget(buttons, 4, 0, 1, 2);
setLayout(formGridLayout);
}
void LoginDialog::loginButtonClicked() {
emit credentialsEntered(_usernameLineEdit->text(), _passwordLineEdit->text());
close();
}

View file

@ -0,0 +1,34 @@
//
// LoginDialog.h
// gvr-interface/src
//
// Created by Stephen Birarda on 2015-02-03.
// Copyright 2015 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
//
#ifndef hifi_LoginDialog_h
#define hifi_LoginDialog_h
#include <QtWidgets/QDialog>
class QLineEdit;
class LoginDialog : public QDialog {
Q_OBJECT
public:
LoginDialog(QWidget* parent = 0);
signals:
void credentialsEntered(const QString& username, const QString& password);
private slots:
void loginButtonClicked();
private:
void setupGUI();
QLineEdit* _usernameLineEdit;
QLineEdit* _passwordLineEdit;
};
#endif // hifi_LoginDialog_h

View file

@ -0,0 +1,167 @@
//
// RenderingClient.cpp
// gvr-interface/src
//
// Created by Stephen Birarda on 1/20/15.
// 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 <QtCore/QThread>
#include <QtWidgets/QInputDialog>
#include <AddressManager.h>
#include <AudioClient.h>
#include <AvatarHashMap.h>
#include <NodeList.h>
#include "RenderingClient.h"
RenderingClient* RenderingClient::_instance = NULL;
RenderingClient::RenderingClient(QObject *parent, const QString& launchURLString) :
Client(parent)
{
_instance = this;
// connect to AddressManager and pass it the launch URL, if we have one
auto addressManager = DependencyManager::get<AddressManager>();
connect(addressManager.data(), &AddressManager::locationChangeRequired, this, &RenderingClient::goToLocation);
addressManager->loadSettings(launchURLString);
// tell the NodeList which node types all rendering clients will want to know about
DependencyManager::get<NodeList>()->addSetOfNodeTypesToNodeInterestSet(NodeSet() << NodeType::AudioMixer << NodeType::AvatarMixer);
DependencyManager::set<AvatarHashMap>();
// get our audio client setup on its own thread
QThread* audioThread = new QThread(this);
auto audioClient = DependencyManager::set<AudioClient>();
audioClient->setPositionGetter(getPositionForAudio);
audioClient->setOrientationGetter(getOrientationForAudio);
audioClient->moveToThread(audioThread);
connect(audioThread, &QThread::started, audioClient.data(), &AudioClient::start);
audioThread->start();
connect(&_avatarTimer, &QTimer::timeout, this, &RenderingClient::sendAvatarPacket);
_avatarTimer.setInterval(16); // 60 FPS
_avatarTimer.start();
_fakeAvatar.setDisplayName("GearVR");
_fakeAvatar.setFaceModelURL(QUrl(DEFAULT_HEAD_MODEL_URL));
_fakeAvatar.setSkeletonModelURL(QUrl(DEFAULT_BODY_MODEL_URL));
_fakeAvatar.toByteArray(); // Creates HeadData
}
void RenderingClient::sendAvatarPacket() {
_fakeAvatar.setPosition(_position);
_fakeAvatar.setHeadOrientation(_orientation);
QByteArray packet = byteArrayWithPopulatedHeader(PacketTypeAvatarData);
packet.append(_fakeAvatar.toByteArray());
DependencyManager::get<NodeList>()->broadcastToNodes(packet, NodeSet() << NodeType::AvatarMixer);
_fakeAvatar.sendIdentityPacket();
}
RenderingClient::~RenderingClient() {
auto audioClient = DependencyManager::get<AudioClient>();
// stop the audio client
QMetaObject::invokeMethod(audioClient.data(), "stop", Qt::BlockingQueuedConnection);
// ask the audio thread to quit and wait until it is done
audioClient->thread()->quit();
audioClient->thread()->wait();
}
void RenderingClient::processVerifiedPacket(const HifiSockAddr& senderSockAddr, const QByteArray& incomingPacket) {
auto nodeList = DependencyManager::get<NodeList>();
PacketType incomingType = packetTypeForPacket(incomingPacket);
switch (incomingType) {
case PacketTypeAudioEnvironment:
case PacketTypeAudioStreamStats:
case PacketTypeMixedAudio:
case PacketTypeSilentAudioFrame: {
if (incomingType == PacketTypeAudioStreamStats) {
QMetaObject::invokeMethod(DependencyManager::get<AudioClient>().data(), "parseAudioStreamStatsPacket",
Qt::QueuedConnection,
Q_ARG(QByteArray, incomingPacket));
} else if (incomingType == PacketTypeAudioEnvironment) {
QMetaObject::invokeMethod(DependencyManager::get<AudioClient>().data(), "parseAudioEnvironmentData",
Qt::QueuedConnection,
Q_ARG(QByteArray, incomingPacket));
} else {
QMetaObject::invokeMethod(DependencyManager::get<AudioClient>().data(), "addReceivedAudioToStream",
Qt::QueuedConnection,
Q_ARG(QByteArray, incomingPacket));
}
// update having heard from the audio-mixer and record the bytes received
SharedNodePointer audioMixer = nodeList->sendingNodeForPacket(incomingPacket);
if (audioMixer) {
audioMixer->setLastHeardMicrostamp(usecTimestampNow());
}
break;
}
case PacketTypeBulkAvatarData:
case PacketTypeKillAvatar:
case PacketTypeAvatarIdentity:
case PacketTypeAvatarBillboard: {
// update having heard from the avatar-mixer and record the bytes received
SharedNodePointer avatarMixer = nodeList->sendingNodeForPacket(incomingPacket);
if (avatarMixer) {
avatarMixer->setLastHeardMicrostamp(usecTimestampNow());
QMetaObject::invokeMethod(DependencyManager::get<AvatarHashMap>().data(),
"processAvatarMixerDatagram",
Q_ARG(const QByteArray&, incomingPacket),
Q_ARG(const QWeakPointer<Node>&, avatarMixer));
}
break;
}
default:
Client::processVerifiedPacket(senderSockAddr, incomingPacket);
break;
}
}
void RenderingClient::goToLocation(const glm::vec3& newPosition,
bool hasOrientationChange, const glm::quat& newOrientation,
bool shouldFaceLocation) {
qDebug().nospace() << "RenderingClient goToLocation - moving to " << newPosition.x << ", "
<< newPosition.y << ", " << newPosition.z;
glm::vec3 shiftedPosition = newPosition;
if (hasOrientationChange) {
qDebug().nospace() << "RenderingClient goToLocation - new orientation is "
<< newOrientation.x << ", " << newOrientation.y << ", " << newOrientation.z << ", " << newOrientation.w;
// orient the user to face the target
glm::quat quatOrientation = newOrientation;
if (shouldFaceLocation) {
quatOrientation = newOrientation * glm::angleAxis(PI, glm::vec3(0.0f, 1.0f, 0.0f));
// move the user a couple units away
const float DISTANCE_TO_USER = 2.0f;
shiftedPosition = newPosition - quatOrientation * glm::vec3( 0.0f, 0.0f,-1.0f) * DISTANCE_TO_USER;
}
_orientation = quatOrientation;
}
_position = shiftedPosition;
}

View file

@ -0,0 +1,56 @@
//
// RenderingClient.h
// gvr-interface/src
//
// Created by Stephen Birarda on 1/20/15.
// 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
//
#ifndef hifi_RenderingClient_h
#define hifi_RenderingClient_h
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <QTimer>
#include <AvatarData.h>
#include "Client.h"
class RenderingClient : public Client {
Q_OBJECT
public:
RenderingClient(QObject* parent = 0, const QString& launchURLString = QString());
~RenderingClient();
const glm::vec3& getPosition() const { return _position; }
const glm::quat& getOrientation() const { return _orientation; }
void setOrientation(const glm::quat& orientation) { _orientation = orientation; }
static glm::vec3 getPositionForAudio() { return _instance->getPosition(); }
static glm::quat getOrientationForAudio() { return _instance->getOrientation(); }
private slots:
void goToLocation(const glm::vec3& newPosition,
bool hasOrientationChange, const glm::quat& newOrientation,
bool shouldFaceLocation);
void sendAvatarPacket();
private:
virtual void processVerifiedPacket(const HifiSockAddr& senderSockAddr, const QByteArray& incomingPacket);
static RenderingClient* _instance;
glm::vec3 _position;
glm::quat _orientation;
QTimer _avatarTimer;
AvatarData _fakeAvatar;
};
#endif // hifi_RenderingClient_h

View file

@ -0,0 +1,41 @@
//
// InterfaceActivity.java
// gvr-interface/java
//
// Created by Stephen Birarda on 1/26/15.
// Copyright 2015 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
//
package io.highfidelity.gvrinterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.WindowManager;
import android.util.Log;
import org.qtproject.qt5.android.bindings.QtActivity;
public class InterfaceActivity extends QtActivity {
public static native void handleHifiURL(String hifiURLString);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// Get the intent that started this activity in case we have a hifi:// URL to parse
Intent intent = getIntent();
if (intent.getAction() == Intent.ACTION_VIEW) {
Uri data = intent.getData();
if (data.getScheme().equals("hifi")) {
handleHifiURL(data.toString());
}
}
}
}

View file

@ -0,0 +1,28 @@
//
// main.cpp
// gvr-interface/src
//
// Created by Stephen Birarda on 11/17/14.
// Copyright 2014 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 "GVRMainWindow.h"
#include "GVRInterface.h"
int main(int argc, char* argv[]) {
GVRInterface app(argc, argv);
GVRMainWindow mainWindow;
#ifdef ANDROID
mainWindow.showFullScreen();
#else
mainWindow.showMaximized();
#endif
app.setMainWindow(&mainWindow);
return app.exec();
}

View file

@ -0,0 +1,51 @@
//
// InterfaceBetaActivity.java
// gvr-interface/java
//
// Created by Stephen Birarda on 1/27/15.
// Copyright 2015 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
//
package io.highfidelity.gvrinterface;
import android.os.Bundle;
import net.hockeyapp.android.CrashManager;
import net.hockeyapp.android.UpdateManager;
public class InterfaceBetaActivity extends InterfaceActivity {
public String _hockeyAppID;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_hockeyAppID = getString(R.string.HockeyAppID);
checkForUpdates();
}
@Override
protected void onPause() {
super.onPause();
UpdateManager.unregister();
}
@Override
protected void onResume() {
super.onResume();
checkForCrashes();
}
private void checkForCrashes() {
CrashManager.register(this, _hockeyAppID);
}
private void checkForUpdates() {
// Remove this for store / production builds!
UpdateManager.register(this, _hockeyAppID);
}
}

View file

@ -0,0 +1,5 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="HockeyAppID">${HOCKEY_APP_ID}</string>
<bool name="HockeyAppEnabled">${HOCKEY_APP_ENABLED}</bool>
</resources>

View file

@ -2,7 +2,7 @@ set(TARGET_NAME interface)
project(${TARGET_NAME})
# set a default root dir for each of our optional externals if it was not passed
set(OPTIONAL_EXTERNALS "Faceshift" "LibOVR" "PrioVR" "Sixense" "LeapMotion" "RtMidi" "Qxmpp" "SDL2" "Gverb" "RSSDK")
set(OPTIONAL_EXTERNALS "Faceshift" "LibOVR" "PrioVR" "Sixense" "LeapMotion" "RtMidi" "Qxmpp" "SDL2" "RSSDK")
foreach(EXTERNAL ${OPTIONAL_EXTERNALS})
string(TOUPPER ${EXTERNAL} ${EXTERNAL}_UPPERCASE)
if (NOT ${${EXTERNAL}_UPPERCASE}_ROOT_DIR)
@ -14,10 +14,6 @@ endforeach()
find_package(Qt5LinguistTools REQUIRED)
find_package(Qt5LinguistToolsMacros)
# As Gverb is currently the only reverb library, it's required.
find_package(Gverb REQUIRED)
if (DEFINED ENV{JOB_ID})
set(BUILD_SEQ $ENV{JOB_ID})
else ()
@ -114,7 +110,8 @@ endif()
add_executable(${TARGET_NAME} MACOSX_BUNDLE ${INTERFACE_SRCS} ${QM})
# link required hifi libraries
link_hifi_libraries(shared octree environment gpu model fbx metavoxels networking entities avatars audio animation script-engine physics
link_hifi_libraries(shared octree environment gpu model fbx metavoxels networking entities avatars
audio audio-client animation script-engine physics
render-utils entities-renderer)
# find any optional and required libraries
@ -179,13 +176,6 @@ if (QXMPP_FOUND AND NOT DISABLE_QXMPP AND WIN32)
add_definitions(-DQXMPP_STATIC)
endif ()
if (GVERB_FOUND)
file(GLOB GVERB_SRCS ${GVERB_SRC_DIRS}/*.c)
include_directories(${GVERB_INCLUDE_DIRS})
add_library(gverb STATIC ${GVERB_SRCS})
target_link_libraries(${TARGET_NAME} gverb)
endif (GVERB_FOUND)
# include headers for interface and InterfaceConfig.
include_directories("${PROJECT_SOURCE_DIR}/src" "${PROJECT_BINARY_DIR}/includes")
@ -199,12 +189,10 @@ add_definitions(-DQT_NO_BEARERMANAGEMENT)
if (APPLE)
# link in required OS X frameworks and include the right GL headers
find_library(CoreAudio CoreAudio)
find_library(CoreFoundation CoreFoundation)
find_library(OpenGL OpenGL)
find_library(AppKit AppKit)
target_link_libraries(${TARGET_NAME} ${CoreAudio} ${CoreFoundation} ${OpenGL} ${AppKit})
target_link_libraries(${TARGET_NAME} ${OpenGL} ${AppKit})
# install command for OS X bundle
INSTALL(TARGETS ${TARGET_NAME}

View file

@ -23,6 +23,7 @@
// include this before QGLWidget, which includes an earlier version of OpenGL
#include "InterfaceConfig.h"
#include <QAbstractNativeEventFilter>
#include <QActionGroup>
#include <QColorDialog>
#include <QDesktopWidget>
@ -73,20 +74,23 @@
#include <PhysicsEngine.h>
#include <ProgramObject.h>
#include <ResourceCache.h>
#include <Settings.h>
#include <ScriptCache.h>
#include <SettingHandle.h>
#include <SoundCache.h>
#include <TextRenderer.h>
#include <UserActivityLogger.h>
#include <UUID.h>
#include "Application.h"
#include "Audio.h"
#include "AudioClient.h"
#include "InterfaceVersion.h"
#include "LODManager.h"
#include "Menu.h"
#include "ModelUploader.h"
#include "Util.h"
#include "avatar/AvatarManager.h"
#include "audio/AudioToolBox.h"
#include "audio/AudioIOStatsRenderer.h"
#include "audio/AudioScope.h"
@ -126,17 +130,12 @@
#include "ui/StandAloneJSConsole.h"
#include "ui/Stats.h"
using namespace std;
// Starfield information
static unsigned STARFIELD_NUM_STARS = 50000;
static unsigned STARFIELD_SEED = 1;
static const int BANDWIDTH_METER_CLICK_MAX_DRAG_LENGTH = 6; // farther dragged clicks are ignored
const qint64 MAXIMUM_CACHE_SIZE = 10737418240; // 10GB
static QTimer* idleTimer = NULL;
@ -146,11 +145,36 @@ const QString SKIP_FILENAME = QStandardPaths::writableLocation(QStandardPaths::D
const QString DEFAULT_SCRIPTS_JS_URL = "http://s3.amazonaws.com/hifi-public/scripts/defaultScripts.js";
namespace SettingHandles {
const SettingHandle<bool> firstRun("firstRun", true);
const SettingHandle<QString> lastScriptLocation("LastScriptLocation");
const SettingHandle<QString> scriptsLocation("scriptsLocation");
}
#ifdef Q_OS_WIN
class MyNativeEventFilter : public QAbstractNativeEventFilter {
public:
static MyNativeEventFilter& getInstance() {
static MyNativeEventFilter staticInstance;
return staticInstance;
}
bool nativeEventFilter(const QByteArray &eventType, void* msg, long* result) Q_DECL_OVERRIDE {
if (eventType == "windows_generic_MSG") {
MSG* message = (MSG*)msg;
if (message->message == UWM_IDENTIFY_INSTANCES) {
*result = UWM_IDENTIFY_INSTANCES;
return true;
}
if (message->message == WM_SHOWWINDOW) {
Application::getInstance()->getWindow()->showNormal();
}
if (message->message == WM_COPYDATA) {
COPYDATASTRUCT* pcds = (COPYDATASTRUCT*)(message->lParam);
QUrl url = QUrl((const char*)(pcds->lpData));
if (url.isValid() && url.scheme() == HIFI_URL_SCHEME) {
DependencyManager::get<AddressManager>()->handleLookupString(url.toString());
}
}
}
return false;
}
};
#endif
void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message) {
QString logMessage = LogHandler::getInstance().printMessage((LogMsgType) type, context, message);
@ -167,18 +191,11 @@ bool setupEssentials(int& argc, char** argv) {
if (portStr) {
listenPort = atoi(portStr);
}
// read the ApplicationInfo.ini file for Name/Version/Domain information
QSettings::setDefaultFormat(QSettings::IniFormat);
QSettings applicationInfo(PathUtils::resourcesPath() + "info/ApplicationInfo.ini", QSettings::IniFormat);
// set the associated application properties
applicationInfo.beginGroup("INFO");
QApplication::setApplicationName(applicationInfo.value("name").toString());
QApplication::setApplicationVersion(BUILD_VERSION);
QApplication::setOrganizationName(applicationInfo.value("organizationName").toString());
QApplication::setOrganizationDomain(applicationInfo.value("organizationDomain").toString());
// Set build version
QCoreApplication::setApplicationVersion(BUILD_VERSION);
DependencyManager::registerInheritance<LimitedNodeList, NodeList>();
DependencyManager::registerInheritance<AvatarHashMap, AvatarManager>();
// Set dependencies
auto glCanvas = DependencyManager::set<GLCanvas>();
@ -187,7 +204,7 @@ bool setupEssentials(int& argc, char** argv) {
auto geometryCache = DependencyManager::set<GeometryCache>();
auto glowEffect = DependencyManager::set<GlowEffect>();
auto faceshift = DependencyManager::set<Faceshift>();
auto audio = DependencyManager::set<Audio>();
auto audio = DependencyManager::set<AudioClient>();
auto audioScope = DependencyManager::set<AudioScope>();
auto audioIOStatsRenderer = DependencyManager::set<AudioIOStatsRenderer>();
auto deferredLightingEffect = DependencyManager::set<DeferredLightingEffect>();
@ -198,9 +215,12 @@ bool setupEssentials(int& argc, char** argv) {
auto ddeFaceTracker = DependencyManager::set<DdeFaceTracker>();
auto modelBlender = DependencyManager::set<ModelBlender>();
auto audioToolBox = DependencyManager::set<AudioToolBox>();
auto avatarManager = DependencyManager::set<AvatarManager>();
auto lodManager = DependencyManager::set<LODManager>();
auto jsConsole = DependencyManager::set<StandAloneJSConsole>();
auto dialogsManager = DependencyManager::set<DialogsManager>();
auto bandwidthRecorder = DependencyManager::set<BandwidthRecorder>();
auto resouceCacheSharedItems = DependencyManager::set<ResouceCacheSharedItems>();
#if defined(Q_OS_MAC) || defined(Q_OS_WIN)
auto speechRecognizer = DependencyManager::set<SpeechRecognizer>();
#endif
@ -208,7 +228,6 @@ bool setupEssentials(int& argc, char** argv) {
return true;
}
Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) :
QApplication(argc, argv),
_dependencyManagerIsSetup(setupEssentials(argc, argv)),
@ -229,10 +248,15 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) :
_lastQueriedViewFrustum(),
_lastQueriedTime(usecTimestampNow()),
_mirrorViewRect(QRect(MIRROR_VIEW_LEFT_PADDING, MIRROR_VIEW_TOP_PADDING, MIRROR_VIEW_WIDTH, MIRROR_VIEW_HEIGHT)),
_firstRun("firstRun", true),
_previousScriptLocation("LastScriptLocation"),
_scriptsLocationHandle("scriptsLocation"),
_fieldOfView("fieldOfView", DEFAULT_FIELD_OF_VIEW_DEGREES),
_viewTransform(),
_scaleMirror(1.0f),
_rotateMirror(0.0f),
_raiseMirror(0.0f),
_cursorVisible(true),
_lastMouseMove(usecTimestampNow()),
_lastMouseMoveWasSimulated(false),
_touchAvgX(0.0f),
@ -241,12 +265,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) :
_mousePressed(false),
_enableProcessOctreeThread(true),
_octreeProcessor(),
_inPacketsPerSecond(0),
_outPacketsPerSecond(0),
_inBytesPerSecond(0),
_outBytesPerSecond(0),
_nodeBoundsDisplay(this),
_previousScriptLocation(),
_applicationOverlay(),
_runningScriptsWidget(NULL),
_runningScriptsWidgetWasVisible(false),
@ -254,11 +273,16 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) :
_lastNackTime(usecTimestampNow()),
_lastSendDownstreamAudioStats(usecTimestampNow()),
_isVSyncOn(true),
_aboutToQuit(false)
_aboutToQuit(false),
_notifiedPacketVersionMismatchThisDomain(false)
{
#ifdef Q_OS_WIN
installNativeEventFilter(&MyNativeEventFilter::getInstance());
#endif
_logger = new FileLogger(this); // After setting organization name in order to get correct directory
qInstallMessageHandler(messageHandler);
QFontDatabase::addApplicationFont(PathUtils::resourcesPath() + "styles/Inconsolata.otf");
_window->setWindowTitle("Interface");
@ -267,7 +291,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) :
auto glCanvas = DependencyManager::get<GLCanvas>();
auto nodeList = DependencyManager::get<NodeList>();
_myAvatar = _avatarManager.getMyAvatar();
_myAvatar = DependencyManager::get<AvatarManager>()->getMyAvatar();
_applicationStartupTime = startup_time;
@ -281,6 +305,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) :
_runningScriptsWidget = new RunningScriptsWidget(_window);
// start the nodeThread so its event loop is running
_nodeThread->setObjectName("Datagram Processor Thread");
_nodeThread->start();
// make sure the node thread is given highest priority
@ -295,10 +320,15 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) :
// put the audio processing on a separate thread
QThread* audioThread = new QThread(this);
audioThread->setObjectName("Audio Thread");
auto audioIO = DependencyManager::get<AudioClient>();
audioIO->setPositionGetter(getPositionForAudio);
audioIO->setOrientationGetter(getOrientationForAudio);
auto audioIO = DependencyManager::get<Audio>();
audioIO->moveToThread(audioThread);
connect(audioThread, &QThread::started, audioIO.data(), &Audio::start);
connect(audioThread, &QThread::started, audioIO.data(), &AudioClient::start);
connect(audioIO.data(), SIGNAL(muteToggled()), this, SLOT(audioMuteToggled()));
audioThread->start();
@ -326,6 +356,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) :
connect(nodeList.data(), SIGNAL(nodeKilled(SharedNodePointer)), SLOT(nodeKilled(SharedNodePointer)));
connect(nodeList.data(), &NodeList::uuidChanged, _myAvatar, &MyAvatar::setSessionUUID);
connect(nodeList.data(), &NodeList::limitOfSilentDomainCheckInsReached, nodeList.data(), &NodeList::reset);
connect(nodeList.data(), &NodeList::packetVersionMismatch, this, &Application::notifyPacketVersionMismatch);
// connect to appropriate slots on AccountManager
AccountManager& accountManager = AccountManager::getInstance();
@ -341,9 +372,6 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) :
auto dialogsManager = DependencyManager::get<DialogsManager>();
connect(&accountManager, &AccountManager::authRequired, dialogsManager.data(), &DialogsManager::showLoginDialog);
connect(&accountManager, &AccountManager::usernameChanged, this, &Application::updateWindowTitle);
// once we have a profile in account manager make sure we generate a new keypair
connect(&accountManager, &AccountManager::profileChanged, &accountManager, &AccountManager::generateNewKeypair);
// set the account manager's root URL and trigger a login request if we don't have the access token
accountManager.setAuthURL(DEFAULT_NODE_AUTH_URL);
@ -433,27 +461,31 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) :
connect(this, SIGNAL(aboutToQuit()), this, SLOT(saveScripts()));
connect(this, SIGNAL(aboutToQuit()), this, SLOT(aboutToQuit()));
// hook up bandwidth estimator
QSharedPointer<BandwidthRecorder> bandwidthRecorder = DependencyManager::get<BandwidthRecorder>();
connect(nodeList.data(), SIGNAL(dataSent(const quint8, const int)),
bandwidthRecorder.data(), SLOT(updateOutboundData(const quint8, const int)));
connect(nodeList.data(), SIGNAL(dataReceived(const quint8, const int)),
bandwidthRecorder.data(), SLOT(updateInboundData(const quint8, const int)));
// check first run...
bool firstRun = SettingHandles::firstRun.get();
if (firstRun) {
if (_firstRun.get()) {
qDebug() << "This is a first run...";
// clear the scripts, and set out script to our default scripts
clearScriptsBeforeRunning();
loadScript(DEFAULT_SCRIPTS_JS_URL);
SettingHandles::firstRun.set(false);
_firstRun.set(false);
} else {
// do this as late as possible so that all required subsystems are initialized
loadScripts();
_previousScriptLocation = SettingHandles::lastScriptLocation.get();
}
loadSettings();
int SAVE_SETTINGS_INTERVAL = 10 * MSECS_PER_SECOND; // Let's save every seconds for now
connect(&_settingsTimer, &QTimer::timeout, this, &Application::saveSettings);
connect(&_settingsThread, SIGNAL(started), &_settingsTimer, SLOT(start));
connect(&_settingsThread, &QThread::finished, &_settingsTimer, &QTimer::deleteLater);
connect(&_settingsThread, SIGNAL(started()), &_settingsTimer, SLOT(start()));
connect(&_settingsThread, SIGNAL(finished()), &_settingsTimer, SLOT(stop()));
_settingsTimer.moveToThread(&_settingsThread);
_settingsTimer.setSingleShot(false);
_settingsTimer.setInterval(SAVE_SETTINGS_INTERVAL);
@ -479,6 +511,8 @@ void Application::aboutToQuit() {
}
Application::~Application() {
QMetaObject::invokeMethod(&_settingsTimer, "stop", Qt::BlockingQueuedConnection);
_settingsThread.quit();
saveSettings();
_entities.getTree()->setSimulation(NULL);
@ -502,7 +536,7 @@ Application::~Application() {
// kill any audio injectors that are still around
AudioScriptingInterface::getInstance().stopAllInjectors();
auto audioIO = DependencyManager::get<Audio>();
auto audioIO = DependencyManager::get<AudioClient>();
// stop the audio process
QMetaObject::invokeMethod(audioIO.data(), "stop", Qt::BlockingQueuedConnection);
@ -519,6 +553,11 @@ Application::~Application() {
_myAvatar = NULL;
DependencyManager::destroy<GLCanvas>();
DependencyManager::destroy<AnimationCache>();
DependencyManager::destroy<TextureCache>();
DependencyManager::destroy<GeometryCache>();
DependencyManager::destroy<ScriptCache>();
DependencyManager::destroy<SoundCache>();
}
void Application::initializeGL() {
@ -564,6 +603,7 @@ void Application::initializeGL() {
// create thread for parsing of octee data independent of the main network and rendering threads
_octreeProcessor.initialize(_enableProcessOctreeThread);
connect(&_octreeProcessor, &OctreePacketProcessor::packetVersionMismatch, this, &Application::notifyPacketVersionMismatch);
_entityEditSender.initialize(_enableProcessOctreeThread);
// call our timer function every second
@ -705,7 +745,7 @@ void Application::runTests() {
void Application::audioMuteToggled() {
QAction* muteAction = Menu::getInstance()->getActionForOption(MenuOption::MuteAudio);
Q_CHECK_PTR(muteAction);
muteAction->setChecked(DependencyManager::get<Audio>()->isMuted());
muteAction->setChecked(DependencyManager::get<AudioClient>()->isMuted());
}
void Application::aboutApp() {
@ -723,7 +763,7 @@ void Application::resetCamerasOnResizeGL(Camera& camera, int width, int height)
TV3DManager::configureCamera(camera, width, height);
} else {
camera.setAspectRatio((float)width / height);
camera.setFieldOfView(_viewFrustum.getFieldOfView());
camera.setFieldOfView(_fieldOfView.get());
}
}
@ -771,25 +811,8 @@ void Application::updateProjectionMatrix(Camera& camera, bool updateViewFrustum)
void Application::controlledBroadcastToNodes(const QByteArray& packet, const NodeSet& destinationNodeTypes) {
foreach(NodeType_t type, destinationNodeTypes) {
// Perform the broadcast for one type
int nReceivingNodes = DependencyManager::get<NodeList>()->broadcastToNodes(packet, NodeSet() << type);
// Feed number of bytes to corresponding channel of the bandwidth meter, if any (done otherwise)
double bandwidth_amount = nReceivingNodes * packet.size();
switch (type) {
case NodeType::Agent:
case NodeType::AvatarMixer:
_bandwidthRecorder.avatarsChannel->output.updateValue(bandwidth_amount);
_bandwidthRecorder.totalChannel->input.updateValue(bandwidth_amount);
break;
case NodeType::EntityServer:
_bandwidthRecorder.octreeChannel->output.updateValue(bandwidth_amount);
_bandwidthRecorder.totalChannel->output.updateValue(bandwidth_amount);
break;
default:
continue;
}
DependencyManager::get<NodeList>()->broadcastToNodes(packet, NodeSet() << type);
}
}
@ -1390,15 +1413,8 @@ void Application::timer() {
float diffTime = (float)_timerStart.nsecsElapsed() / 1000000000.0f;
_fps = (float)_frameCount / diffTime;
_inPacketsPerSecond = (float) _datagramProcessor.getInPacketCount() / diffTime;
_outPacketsPerSecond = (float) _datagramProcessor.getOutPacketCount() / diffTime;
_inBytesPerSecond = (float) _datagramProcessor.getInByteCount() / diffTime;
_outBytesPerSecond = (float) _datagramProcessor.getOutByteCount() / diffTime;
_frameCount = 0;
_datagramProcessor.resetCounters();
_timerStart.start();
// ask the node list to check in with the domain server
@ -1501,6 +1517,8 @@ void Application::setEnableVRMode(bool enableVRMode) {
auto glCanvas = DependencyManager::get<GLCanvas>();
resizeGL(glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight());
updateCursorVisibility();
}
void Application::setLowVelocityFilter(bool lowVelocityFilter) {
@ -1587,15 +1605,16 @@ bool Application::exportEntities(const QString& filename, float x, float y, floa
}
void Application::loadSettings() {
DependencyManager::get<Audio>()->loadSettings();
DependencyManager::get<LODManager>()->loadSettings();
DependencyManager::get<AudioClient>()->loadSettings();
Menu::getInstance()->loadSettings();
_myAvatar->loadData();
}
void Application::saveSettings() {
DependencyManager::get<Audio>()->saveSettings();
DependencyManager::get<LODManager>()->saveSettings();
DependencyManager::get<AudioClient>()->saveSettings();
Menu::getInstance()->saveSettings();
_myAvatar->saveData();
}
@ -1629,7 +1648,7 @@ void Application::init() {
DependencyManager::get<AmbientOcclusionEffect>()->init(this);
// TODO: move _myAvatar out of Application. Move relevant code to MyAvataar or AvatarManager
_avatarManager.init();
DependencyManager::get<AvatarManager>()->init();
_myCamera.setMode(CAMERA_MODE_FIRST_PERSON);
_mirrorCamera.setMode(CAMERA_MODE_MIRROR);
@ -1970,35 +1989,22 @@ void Application::updateCursor(float deltaTime) {
static QPoint lastMousePos = QPoint();
_lastMouseMove = (lastMousePos == QCursor::pos()) ? _lastMouseMove : usecTimestampNow();
bool hideMouse = false;
bool underMouse = QGuiApplication::topLevelAt(QCursor::pos()) ==
Application::getInstance()->getWindow()->windowHandle();
static const int HIDE_CURSOR_TIMEOUT = 3 * USECS_PER_SECOND; // 3 second
int elapsed = usecTimestampNow() - _lastMouseMove;
if ((elapsed > HIDE_CURSOR_TIMEOUT) ||
(OculusManager::isConnected() && Menu::getInstance()->isOptionChecked(MenuOption::EnableVRMode))) {
hideMouse = underMouse;
}
setCursorVisible(!hideMouse);
lastMousePos = QCursor::pos();
}
void Application::setCursorVisible(bool visible) {
if (visible) {
if (overrideCursor() != NULL) {
restoreOverrideCursor();
}
void Application::updateCursorVisibility() {
if (!_cursorVisible || Menu::getInstance()->isOptionChecked(MenuOption::EnableVRMode)) {
DependencyManager::get<GLCanvas>()->setCursor(Qt::BlankCursor);
} else {
if (overrideCursor() != NULL) {
changeOverrideCursor(Qt::BlankCursor);
} else {
setOverrideCursor(Qt::BlankCursor);
}
DependencyManager::get<GLCanvas>()->unsetCursor();
}
}
void Application::setCursorVisible(bool visible) {
_cursorVisible = visible;
updateCursorVisibility();
}
void Application::update(float deltaTime) {
bool showWarnings = Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings);
PerformanceWarning warn(showWarnings, "Application::update()");
@ -2021,7 +2027,7 @@ void Application::update(float deltaTime) {
updateThreads(deltaTime); // If running non-threaded, then give the threads some time to process...
_avatarManager.updateOtherAvatars(deltaTime); //loop through all the other avatars and simulate them...
DependencyManager::get<AvatarManager>()->updateOtherAvatars(deltaTime); //loop through all the other avatars and simulate them...
updateMetavoxels(deltaTime); // update metavoxels
updateCamera(deltaTime); // handle various camera tweaks like off axis projection
@ -2048,7 +2054,7 @@ void Application::update(float deltaTime) {
{
PerformanceTimer perfTimer("myAvatar");
updateMyAvatarLookAtPosition();
updateMyAvatar(deltaTime); // Sample hardware, update view frustum if needed, and send avatar data to mixer/nodes
DependencyManager::get<AvatarManager>()->updateMyAvatar(deltaTime); // Sample hardware, update view frustum if needed, and send avatar data to mixer/nodes
}
{
@ -2105,31 +2111,11 @@ void Application::update(float deltaTime) {
if (sinceLastNack > TOO_LONG_SINCE_LAST_SEND_DOWNSTREAM_AUDIO_STATS) {
_lastSendDownstreamAudioStats = now;
QMetaObject::invokeMethod(DependencyManager::get<Audio>().data(), "sendDownstreamAudioStatsPacket", Qt::QueuedConnection);
QMetaObject::invokeMethod(DependencyManager::get<AudioClient>().data(), "sendDownstreamAudioStatsPacket", Qt::QueuedConnection);
}
}
}
void Application::updateMyAvatar(float deltaTime) {
bool showWarnings = Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings);
PerformanceWarning warn(showWarnings, "Application::updateMyAvatar()");
_myAvatar->update(deltaTime);
quint64 now = usecTimestampNow();
quint64 dt = now - _lastSendAvatarDataTime;
if (dt > MIN_TIME_BETWEEN_MY_AVATAR_DATA_SENDS) {
// send head/hand data to the avatar mixer and voxel server
PerformanceTimer perfTimer("send");
QByteArray packet = byteArrayWithPopulatedHeader(PacketTypeAvatarData);
packet.append(_myAvatar->toByteArray());
controlledBroadcastToNodes(packet, NodeSet() << NodeType::AvatarMixer);
_lastSendAvatarDataTime = now;
}
}
int Application::sendNackPackets() {
if (Menu::getInstance()->isOptionChecked(MenuOption::DisableNackPackets)) {
@ -2383,10 +2369,6 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType, Node
// make sure we still have an active socket
nodeList->writeUnverifiedDatagram(reinterpret_cast<const char*>(queryPacket), packetLength, node);
// Feed number of bytes to corresponding channel of the bandwidth meter
_bandwidthRecorder.octreeChannel->output.updateValue(packetLength);
_bandwidthRecorder.totalChannel->output.updateValue(packetLength);
}
});
}
@ -2573,7 +2555,7 @@ void Application::updateShadowMap() {
{
PerformanceTimer perfTimer("avatarManager");
_avatarManager.renderAvatars(Avatar::SHADOW_RENDER_MODE);
DependencyManager::get<AvatarManager>()->renderAvatars(Avatar::SHADOW_RENDER_MODE);
}
{
@ -2825,7 +2807,7 @@ void Application::displaySide(Camera& theCamera, bool selfAvatarOnly, RenderArgs
bool mirrorMode = (theCamera.getMode() == CAMERA_MODE_MIRROR);
{
PerformanceTimer perfTimer("avatars");
_avatarManager.renderAvatars(mirrorMode ? Avatar::MIRROR_RENDER_MODE : Avatar::NORMAL_RENDER_MODE,
DependencyManager::get<AvatarManager>()->renderAvatars(mirrorMode ? Avatar::MIRROR_RENDER_MODE : Avatar::NORMAL_RENDER_MODE,
false, selfAvatarOnly);
}
@ -2840,7 +2822,7 @@ void Application::displaySide(Camera& theCamera, bool selfAvatarOnly, RenderArgs
{
PerformanceTimer perfTimer("avatarsPostLighting");
_avatarManager.renderAvatars(mirrorMode ? Avatar::MIRROR_RENDER_MODE : Avatar::NORMAL_RENDER_MODE,
DependencyManager::get<AvatarManager>()->renderAvatars(mirrorMode ? Avatar::MIRROR_RENDER_MODE : Avatar::NORMAL_RENDER_MODE,
true, selfAvatarOnly);
}
@ -2980,7 +2962,7 @@ void Application::renderRearViewMirror(const QRect& region, bool billboard) {
_mirrorCamera.setPosition(_myAvatar->getPosition() +
_myAvatar->getOrientation() * glm::vec3(0.0f, 0.0f, -1.0f) * BILLBOARD_DISTANCE * _myAvatar->getScale());
} else if (SettingHandles::rearViewZoomLevel.get() == BODY) {
} else if (RearMirrorTools::rearViewZoomLevel.get() == BODY) {
_mirrorCamera.setFieldOfView(MIRROR_FIELD_OF_VIEW); // degrees
_mirrorCamera.setPosition(_myAvatar->getChestPosition() +
_myAvatar->getOrientation() * glm::vec3(0.0f, 0.0f, -1.0f) * MIRROR_REARVIEW_BODY_DISTANCE * _myAvatar->getScale());
@ -3104,7 +3086,7 @@ void Application::resetSensors() {
_myAvatar->reset();
QMetaObject::invokeMethod(DependencyManager::get<Audio>().data(), "reset", Qt::QueuedConnection);
QMetaObject::invokeMethod(DependencyManager::get<AudioClient>().data(), "reset", Qt::QueuedConnection);
}
static void setShortcutsEnabled(QWidget* widget, bool enabled) {
@ -3218,11 +3200,11 @@ void Application::connectedToDomain(const QString& hostname) {
if (accountManager.isLoggedIn() && !domainID.isNull()) {
// update our data-server with the domain-server we're logged in with
QString domainPutJsonString = "{\"location\":{\"domain_id\":\"" + uuidStringWithoutCurlyBraces(domainID) + "\"}}";
accountManager.authenticatedRequest("/api/v1/user/location", QNetworkAccessManager::PutOperation,
JSONCallbackParameters(), domainPutJsonString.toUtf8());
_notifiedPacketVersionMismatchThisDomain = false;
}
}
@ -3244,7 +3226,7 @@ void Application::nodeKilled(SharedNodePointer node) {
_entityEditSender.nodeKilled(node);
if (node->getType() == NodeType::AudioMixer) {
QMetaObject::invokeMethod(DependencyManager::get<Audio>().data(), "audioMixerKilled");
QMetaObject::invokeMethod(DependencyManager::get<AudioClient>().data(), "audioMixerKilled");
}
if (node->getType() == NodeType::EntityServer) {
@ -3287,7 +3269,7 @@ void Application::nodeKilled(SharedNodePointer node) {
} else if (node->getType() == NodeType::AvatarMixer) {
// our avatar mixer has gone away - clear the hash of avatars
_avatarManager.clearOtherAvatars();
DependencyManager::get<AvatarManager>()->clearOtherAvatars();
}
}
@ -3374,8 +3356,6 @@ int Application::parseOctreeStats(const QByteArray& packet, const SharedNodePoin
}
void Application::packetSent(quint64 length) {
_bandwidthRecorder.octreeChannel->output.updateValue(length);
_bandwidthRecorder.totalChannel->output.updateValue(length);
}
const QString SETTINGS_KEY = "Settings";
@ -3438,7 +3418,7 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEngine* scri
// hook our avatar and avatar hash map object into this script engine
scriptEngine->setAvatarData(_myAvatar, "MyAvatar"); // leave it as a MyAvatar class to expose thrust features
scriptEngine->setAvatarHashMap(&_avatarManager, "AvatarList");
scriptEngine->setAvatarHashMap(DependencyManager::get<AvatarManager>().data(), "AvatarList");
scriptEngine->registerGlobalObject("Camera", &_myCamera);
@ -3479,7 +3459,7 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEngine* scri
scriptEngine->registerGlobalObject("GlobalServices", GlobalServicesScriptingInterface::getInstance());
qScriptRegisterMetaType(scriptEngine, DownloadInfoResultToScriptValue, DownloadInfoResultFromScriptValue);
scriptEngine->registerGlobalObject("AvatarManager", &_avatarManager);
scriptEngine->registerGlobalObject("AvatarManager", DependencyManager::get<AvatarManager>().data());
scriptEngine->registerGlobalObject("Joysticks", &JoystickScriptingInterface::getInstance());
qScriptRegisterMetaType(scriptEngine, joystickToScriptValue, joystickFromScriptValue);
@ -3491,6 +3471,7 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEngine* scri
#endif
QThread* workerThread = new QThread(this);
workerThread->setObjectName("Script Engine Thread");
// when the worker thread is started, call our engine's run..
connect(workerThread, &QThread::started, scriptEngine, &ScriptEngine::run);
@ -3709,21 +3690,20 @@ void Application::domainSettingsReceived(const QJsonObject& domainSettingsObject
QString Application::getPreviousScriptLocation() {
QString suggestedName;
if (_previousScriptLocation.isEmpty()) {
if (_previousScriptLocation.get().isEmpty()) {
QString desktopLocation = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
// Temporary fix to Qt bug: http://stackoverflow.com/questions/16194475
#ifdef __APPLE__
suggestedName = desktopLocation.append("/script.js");
#endif
} else {
suggestedName = _previousScriptLocation;
suggestedName = _previousScriptLocation.get();
}
return suggestedName;
}
void Application::setPreviousScriptLocation(const QString& previousScriptLocation) {
_previousScriptLocation = previousScriptLocation;
SettingHandles::lastScriptLocation.set(_previousScriptLocation);
_previousScriptLocation.set(previousScriptLocation);
}
void Application::loadDialog() {
@ -3758,12 +3738,12 @@ void Application::loadScriptURLDialog() {
}
}
QString Application::getScriptsLocation() const {
return SettingHandles::scriptsLocation.get();
QString Application::getScriptsLocation() {
return _scriptsLocationHandle.get();
}
void Application::setScriptsLocation(const QString& scriptsLocation) {
SettingHandles::scriptsLocation.set(scriptsLocation);
_scriptsLocationHandle.set(scriptsLocation);
emit scriptLocationChanged(scriptsLocation);
}
@ -3779,10 +3759,6 @@ void Application::toggleLogDialog() {
}
}
void Application::initAvatarAndViewFrustum() {
updateMyAvatar(0.0f);
}
void Application::checkVersion() {
QNetworkRequest latestVersionRequest((QUrl(CHECK_VERSION_URL)));
latestVersionRequest.setHeader(QNetworkRequest::UserAgentHeader, HIGH_FIDELITY_USER_AGENT);
@ -3990,3 +3966,18 @@ int Application::getRenderAmbientLight() const {
return -1;
}
}
void Application::notifyPacketVersionMismatch() {
if (!_notifiedPacketVersionMismatchThisDomain) {
_notifiedPacketVersionMismatchThisDomain = true;
QString message = "The location you are visiting is running an incompatible server version.\n";
message += "Content may not display properly.";
QMessageBox msgBox;
msgBox.setText(message);
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setIcon(QMessageBox::Warning);
msgBox.exec();
}
}

View file

@ -37,6 +37,7 @@
#include <TextureCache.h>
#include <ViewFrustum.h>
#include "AudioClient.h"
#include "Bookmarks.h"
#include "Camera.h"
#include "DatagramProcessor.h"
@ -49,7 +50,6 @@
#include "Physics.h"
#include "Stars.h"
#include "avatar/Avatar.h"
#include "avatar/AvatarManager.h"
#include "avatar/MyAvatar.h"
#include "devices/PrioVR.h"
#include "devices/SixenseManager.h"
@ -109,15 +109,16 @@ static const float MIRROR_REARVIEW_DISTANCE = 0.722f;
static const float MIRROR_REARVIEW_BODY_DISTANCE = 2.56f;
static const float MIRROR_FIELD_OF_VIEW = 30.0f;
// 70 times per second - target is 60hz, but this helps account for any small deviations
// in the update loop
static const quint64 MIN_TIME_BETWEEN_MY_AVATAR_DATA_SENDS = (1000 * 1000) / 70;
static const quint64 TOO_LONG_SINCE_LAST_SEND_DOWNSTREAM_AUDIO_STATS = 1 * USECS_PER_SECOND;
static const QString INFO_HELP_PATH = "html/interface-welcome-allsvg.html";
static const QString INFO_EDIT_ENTITIES_PATH = "html/edit-entities-commands.html";
#ifdef Q_OS_WIN
static const UINT UWM_IDENTIFY_INSTANCES =
RegisterWindowMessage("UWM_IDENTIFY_INSTANCES_{8AB82783-B74A-4258-955B-8188C22AA0D6}");
#endif
class Application;
#if defined(qApp)
#undef qApp
@ -134,6 +135,8 @@ public:
static Application* getInstance() { return qApp; } // TODO: replace fully by qApp
static const glm::vec3& getPositionForPath() { return getInstance()->_myAvatar->getPosition(); }
static glm::quat getOrientationForPath() { return getInstance()->_myAvatar->getOrientation(); }
static glm::vec3 getPositionForAudio() { return getInstance()->_myAvatar->getHead()->getPosition(); }
static glm::quat getOrientationForAudio() { return getInstance()->_myAvatar->getHead()->getFinalOrientationInWorldFrame(); }
Application(int& argc, char** argv, QElapsedTimer &startup_time);
~Application();
@ -168,8 +171,6 @@ public:
bool isThrottleRendering() const { return DependencyManager::get<GLCanvas>()->isThrottleRendering(); }
MyAvatar* getAvatar() { return _myAvatar; }
const MyAvatar* getAvatar() const { return _myAvatar; }
Camera* getCamera() { return &_myCamera; }
ViewFrustum* getViewFrustum() { return &_viewFrustum; }
ViewFrustum* getDisplayViewFrustum() { return &_displayViewFrustum; }
@ -186,8 +187,7 @@ public:
EntityTreeRenderer* getEntityClipboardRenderer() { return &_entityClipboardRenderer; }
bool isMousePressed() const { return _mousePressed; }
bool isMouseHidden() const { return DependencyManager::get<GLCanvas>()->cursor().shape() == Qt::BlankCursor; }
void setCursorVisible(bool visible);
bool isMouseHidden() const { return !_cursorVisible; }
const glm::vec3& getMouseRayOrigin() const { return _mouseRayOrigin; }
const glm::vec3& getMouseRayDirection() const { return _mouseRayDirection; }
bool mouseOnScreen() const;
@ -202,21 +202,19 @@ public:
bool getLastMouseMoveWasSimulated() const { return _lastMouseMoveWasSimulated; }
FaceTracker* getActiveFaceTracker();
BandwidthRecorder* getBandwidthRecorder() { return &_bandwidthRecorder; }
QSystemTrayIcon* getTrayIcon() { return _trayIcon; }
ApplicationOverlay& getApplicationOverlay() { return _applicationOverlay; }
Overlays& getOverlays() { return _overlays; }
float getFps() const { return _fps; }
float getInPacketsPerSecond() const { return _inPacketsPerSecond; }
float getOutPacketsPerSecond() const { return _outPacketsPerSecond; }
float getInBytesPerSecond() const { return _inBytesPerSecond; }
float getOutBytesPerSecond() const { return _outBytesPerSecond; }
const glm::vec3& getViewMatrixTranslation() const { return _viewMatrixTranslation; }
void setViewMatrixTranslation(const glm::vec3& translation) { _viewMatrixTranslation = translation; }
virtual const Transform& getViewTransform() const { return _viewTransform; }
void setViewTransform(const Transform& view);
float getFieldOfView() { return _fieldOfView.get(); }
void setFieldOfView(float fov) { _fieldOfView.set(fov); }
NodeToOctreeSceneStats* getOcteeSceneStats() { return &_octreeServerSceneStats; }
void lockOctreeSceneStats() { _octreeSceneStatsLock.lockForRead(); }
@ -227,8 +225,6 @@ public:
virtual AbstractControllerScriptingInterface* getControllerScriptingInterface() { return &_controllerScriptingInterface; }
virtual void registerScriptEngineWithApplicationServices(ScriptEngine* scriptEngine);
AvatarManager& getAvatarManager() { return _avatarManager; }
void resetProfile(const QString& username);
void controlledBroadcastToNodes(const QByteArray& packet, const NodeSet& destinationNodeTypes);
@ -266,7 +262,7 @@ public:
virtual float getSizeScale() const;
virtual int getBoundaryLevelAdjust() const;
virtual PickRay computePickRay(float x, float y);
virtual const glm::vec3& getAvatarPosition() const { return getAvatar()->getPosition(); }
virtual const glm::vec3& getAvatarPosition() const { return _myAvatar->getPosition(); }
NodeBounds& getNodeBoundsDisplay() { return _nodeBoundsDisplay; }
@ -301,7 +297,7 @@ public:
Bookmarks* getBookmarks() const { return _bookmarks; }
QString getScriptsLocation() const;
QString getScriptsLocation();
void setScriptsLocation(const QString& scriptsLocation);
signals:
@ -336,7 +332,6 @@ public slots:
void loadDialog();
void loadScriptURLDialog();
void toggleLogDialog();
void initAvatarAndViewFrustum();
ScriptEngine* loadScript(const QString& scriptFilename = QString(), bool isUserLoaded = true,
bool loadScriptFromEditor = false, bool activateMainWindow = false);
void scriptFinished(const QString& scriptName);
@ -367,6 +362,8 @@ public slots:
void loadSettings();
void saveSettings();
void notifyPacketVersionMismatch();
private slots:
void clearDomainOctreeDetails();
void timer();
@ -398,11 +395,15 @@ private slots:
void audioMuteToggled();
void setCursorVisible(bool visible);
private:
void resetCamerasOnResizeGL(Camera& camera, int width, int height);
void updateProjectionMatrix();
void updateProjectionMatrix(Camera& camera, bool updateViewFrustum = true);
void updateCursorVisibility();
void sendPingPackets();
void initDisplay();
@ -427,7 +428,6 @@ private:
void renderLookatIndicator(glm::vec3 pointOfInterest);
void updateMyAvatar(float deltaTime);
void queryOctree(NodeType_t serverType, PacketType packetType, NodeToJurisdictionMap& jurisdictions);
void loadViewFrustum(Camera& camera, ViewFrustum& viewFrustum);
@ -484,10 +484,6 @@ private:
OctreeQuery _octreeQuery; // NodeData derived class for querying octee cells from octree servers
BandwidthRecorder _bandwidthRecorder;
AvatarManager _avatarManager;
MyAvatar* _myAvatar; // TODO: move this and relevant code to AvatarManager (or MyAvatar as the case may be)
PrioVR _prioVR;
@ -496,6 +492,11 @@ private:
Camera _mirrorCamera; // Cammera for mirror view
QRect _mirrorViewRect;
RearMirrorTools* _rearMirrorTools;
Setting::Handle<bool> _firstRun;
Setting::Handle<QString> _previousScriptLocation;
Setting::Handle<QString> _scriptsLocationHandle;
Setting::Handle<float> _fieldOfView;
Transform _viewTransform;
glm::mat4 _untranslatedViewMatrix;
@ -512,6 +513,7 @@ private:
Environment _environment;
bool _cursorVisible;
int _mouseDragStartedX;
int _mouseDragStartedY;
quint64 _lastMouseMove;
@ -535,11 +537,6 @@ private:
OctreePacketProcessor _octreeProcessor;
EntityEditPacketSender _entityEditSender;
int _inPacketsPerSecond;
int _outPacketsPerSecond;
int _inBytesPerSecond;
int _outBytesPerSecond;
StDev _idleLoopStdev;
float _idleLoopMeasuredJitter;
@ -558,8 +555,6 @@ private:
QPointer<LogDialog> _logDialog;
QPointer<SnapshotShareDialog> _snapshotShareDialog;
QString _previousScriptLocation;
FileLogger* _logger;
void checkVersion();
@ -582,13 +577,13 @@ private:
quint64 _lastNackTime;
quint64 _lastSendDownstreamAudioStats;
quint64 _lastSendAvatarDataTime;
bool _isVSyncOn;
bool _aboutToQuit;
Bookmarks* _bookmarks;
bool _notifiedPacketVersionMismatchThisDomain;
QThread _settingsThread;
QTimer _settingsTimer;

View file

@ -1,64 +0,0 @@
//
// BandwidthMeter.cpp
// interface/src/ui
//
// Created by Seth Alves on 2015-1-30
// Copyright 2015 High Fidelity, Inc.
//
// Based on code by Tobias Schwinger
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include <GeometryCache.h>
#include "BandwidthRecorder.h"
BandwidthRecorder::Channel::Channel(char const* const caption,
char const* unitCaption,
double unitScale,
unsigned colorRGBA) :
caption(caption),
unitCaption(unitCaption),
unitScale(unitScale),
colorRGBA(colorRGBA)
{
}
BandwidthRecorder::BandwidthRecorder() {
}
BandwidthRecorder::~BandwidthRecorder() {
delete audioChannel;
delete avatarsChannel;
delete octreeChannel;
delete metavoxelsChannel;
delete totalChannel;
}
BandwidthRecorder::Stream::Stream(float msToAverage) : _value(0.0f), _msToAverage(msToAverage) {
_prevTime.start();
}
void BandwidthRecorder::Stream::updateValue(double amount) {
// Determine elapsed time
double dt = (double)_prevTime.nsecsElapsed() / 1000000.0; // ns to ms
// Ignore this value when timer imprecision yields dt = 0
if (dt == 0.0) {
return;
}
_prevTime.start();
// Compute approximate average
_value = glm::mix(_value, amount / dt,
glm::clamp(dt / _msToAverage, 0.0, 1.0));
}

View file

@ -1,56 +0,0 @@
//
// BandwidthRecorder.h
//
// Created by Seth Alves on 2015-1-30
// Copyright 2015 High Fidelity, Inc.
//
// Based on code by Tobias Schwinger
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#ifndef hifi_BandwidthRecorder_h
#define hifi_BandwidthRecorder_h
#include <QElapsedTimer>
class BandwidthRecorder {
public:
BandwidthRecorder();
~BandwidthRecorder();
// keep track of data rate in one direction
class Stream {
public:
Stream(float msToAverage = 3000.0f);
void updateValue(double amount);
double getValue() const { return _value; }
private:
double _value; // Current value.
double _msToAverage; // Milliseconds to average.
QElapsedTimer _prevTime; // Time of last feed.
};
// keep track of data rate in two directions as well as units and style to use during display
class Channel {
public:
Channel(char const* const caption, char const* unitCaption, double unitScale, unsigned colorRGBA);
Stream input;
Stream output;
char const* const caption;
char const* unitCaption;
double unitScale;
unsigned colorRGBA;
};
// create the channels we keep track of
Channel* audioChannel = new Channel("Audio", "Kbps", 8000.0 / 1024.0, 0x33cc99ff);
Channel* avatarsChannel = new Channel("Avatars", "Kbps", 8000.0 / 1024.0, 0xffef40c0);
Channel* octreeChannel = new Channel("Octree", "Kbps", 8000.0 / 1024.0, 0xd0d0d0a0);
Channel* metavoxelsChannel = new Channel("Metavoxels", "Kbps", 8000.0 / 1024.0, 0xd0d0d0a0);
Channel* totalChannel = new Channel("Total", "Kbps", 8000.0 / 1024.0, 0xd0d0d0a0);
};
#endif

View file

@ -15,7 +15,8 @@
#include <PerfStat.h>
#include "Application.h"
#include "Audio.h"
#include "avatar/AvatarManager.h"
#include "AudioClient.h"
#include "Menu.h"
#include "DatagramProcessor.h"
@ -39,8 +40,7 @@ void DatagramProcessor::processDatagrams() {
while (DependencyManager::get<NodeList>()->getNodeSocket().hasPendingDatagrams()) {
incomingPacket.resize(nodeList->getNodeSocket().pendingDatagramSize());
nodeList->getNodeSocket().readDatagram(incomingPacket.data(), incomingPacket.size(),
senderSockAddr.getAddressPointer(), senderSockAddr.getPortPointer());
nodeList->readDatagram(incomingPacket, senderSockAddr.getAddressPointer(), senderSockAddr.getPortPointer());
_inPacketCount++;
_inByteCount += incomingPacket.size();
@ -55,15 +55,15 @@ void DatagramProcessor::processDatagrams() {
case PacketTypeMixedAudio:
case PacketTypeSilentAudioFrame: {
if (incomingType == PacketTypeAudioStreamStats) {
QMetaObject::invokeMethod(DependencyManager::get<Audio>().data(), "parseAudioStreamStatsPacket",
QMetaObject::invokeMethod(DependencyManager::get<AudioClient>().data(), "parseAudioStreamStatsPacket",
Qt::QueuedConnection,
Q_ARG(QByteArray, incomingPacket));
} else if (incomingType == PacketTypeAudioEnvironment) {
QMetaObject::invokeMethod(DependencyManager::get<Audio>().data(), "parseAudioEnvironmentData",
QMetaObject::invokeMethod(DependencyManager::get<AudioClient>().data(), "parseAudioEnvironmentData",
Qt::QueuedConnection,
Q_ARG(QByteArray, incomingPacket));
} else {
QMetaObject::invokeMethod(DependencyManager::get<Audio>().data(), "addReceivedAudioToStream",
QMetaObject::invokeMethod(DependencyManager::get<AudioClient>().data(), "addReceivedAudioToStream",
Qt::QueuedConnection,
Q_ARG(QByteArray, incomingPacket));
}
@ -73,7 +73,6 @@ void DatagramProcessor::processDatagrams() {
if (audioMixer) {
audioMixer->setLastHeardMicrostamp(usecTimestampNow());
audioMixer->recordBytesReceived(incomingPacket.size());
}
break;
@ -82,8 +81,6 @@ void DatagramProcessor::processDatagrams() {
// this will keep creatorTokenIDs to IDs mapped correctly
EntityItemID::handleAddEntityResponse(incomingPacket);
application->getEntities()->getTree()->handleAddEntityResponse(incomingPacket);
application->_bandwidthRecorder.octreeChannel->input.updateValue(incomingPacket.size());
application->_bandwidthRecorder.totalChannel->input.updateValue(incomingPacket.size());
break;
case PacketTypeEntityData:
case PacketTypeEntityErase:
@ -97,8 +94,6 @@ void DatagramProcessor::processDatagrams() {
// add this packet to our list of octree packets and process them on the octree data processing
application->_octreeProcessor.queueReceivedPacket(matchedNode, incomingPacket);
}
application->_bandwidthRecorder.octreeChannel->input.updateValue(incomingPacket.size());
application->_bandwidthRecorder.totalChannel->input.updateValue(incomingPacket.size());
break;
}
case PacketTypeMetavoxelData:
@ -113,15 +108,11 @@ void DatagramProcessor::processDatagrams() {
if (avatarMixer) {
avatarMixer->setLastHeardMicrostamp(usecTimestampNow());
avatarMixer->recordBytesReceived(incomingPacket.size());
QMetaObject::invokeMethod(&application->getAvatarManager(), "processAvatarMixerDatagram",
QMetaObject::invokeMethod(DependencyManager::get<AvatarManager>().data(), "processAvatarMixerDatagram",
Q_ARG(const QByteArray&, incomingPacket),
Q_ARG(const QWeakPointer<Node>&, avatarMixer));
}
application->_bandwidthRecorder.avatarsChannel->input.updateValue(incomingPacket.size());
application->_bandwidthRecorder.totalChannel->input.updateValue(incomingPacket.size());
break;
}
case PacketTypeDomainConnectionDenied: {
@ -134,7 +125,7 @@ void DatagramProcessor::processDatagrams() {
}
case PacketTypeNoisyMute:
case PacketTypeMuteEnvironment: {
bool mute = !DependencyManager::get<Audio>()->isMuted();
bool mute = !DependencyManager::get<AudioClient>()->isMuted();
if (incomingType == PacketTypeMuteEnvironment) {
glm::vec3 position;
@ -143,13 +134,14 @@ void DatagramProcessor::processDatagrams() {
int headerSize = numBytesForPacketHeaderGivenPacketType(PacketTypeMuteEnvironment);
memcpy(&position, incomingPacket.constData() + headerSize, sizeof(glm::vec3));
memcpy(&radius, incomingPacket.constData() + headerSize + sizeof(glm::vec3), sizeof(float));
distance = glm::distance(Application::getInstance()->getAvatar()->getPosition(), position);
distance = glm::distance(DependencyManager::get<AvatarManager>()->getMyAvatar()->getPosition(),
position);
mute = mute && (distance < radius);
}
if (mute) {
DependencyManager::get<Audio>()->toggleMute();
DependencyManager::get<AudioClient>()->toggleMute();
if (incomingType == PacketTypeMuteEnvironment) {
AudioScriptingInterface::getInstance().environmentMuted();
} else {

View file

@ -1,6 +1,6 @@
//
// FileUtils.cpp
// libraries/shared/src
// interface/src
//
// Created by Stojce Slavkovski on 12/23/13.
// Copyright 2013 High Fidelity, Inc.
@ -9,9 +9,14 @@
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include <qdir.h>
#include <qfileinfo.h>
#include <qdesktopservices.h>
#include <qprocess.h>
#include <qurl.h>
#include "FileUtils.h"
#include <QtCore>
#include <QDesktopServices>
void FileUtils::locateFile(QString filePath) {

View file

@ -1,6 +1,6 @@
//
// FileUtils.h
// libraries/shared/src
// interface/src
//
// Created by Stojce Slavkovski on 12/23/13.
// Copyright 2013 High Fidelity, Inc.

View file

@ -9,6 +9,7 @@
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include <SettingHandle.h>
#include <Util.h>
#include "Application.h"
@ -16,15 +17,14 @@
#include "LODManager.h"
namespace SettingHandles {
const SettingHandle<bool> automaticAvatarLOD("automaticAvatarLOD", true);
const SettingHandle<float> avatarLODDecreaseFPS("avatarLODDecreaseFPS", DEFAULT_ADJUST_AVATAR_LOD_DOWN_FPS);
const SettingHandle<float> avatarLODIncreaseFPS("avatarLODIncreaseFPS", ADJUST_LOD_UP_FPS);
const SettingHandle<float> avatarLODDistanceMultiplier("avatarLODDistanceMultiplier",
Setting::Handle<bool> automaticAvatarLOD("automaticAvatarLOD", true);
Setting::Handle<float> avatarLODDecreaseFPS("avatarLODDecreaseFPS", DEFAULT_ADJUST_AVATAR_LOD_DOWN_FPS);
Setting::Handle<float> avatarLODIncreaseFPS("avatarLODIncreaseFPS", ADJUST_LOD_UP_FPS);
Setting::Handle<float> avatarLODDistanceMultiplier("avatarLODDistanceMultiplier",
DEFAULT_AVATAR_LOD_DISTANCE_MULTIPLIER);
const SettingHandle<int> boundaryLevelAdjust("boundaryLevelAdjust", 0);
const SettingHandle<float> octreeSizeScale("octreeSizeScale", DEFAULT_OCTREE_SIZE_SCALE);
}
Setting::Handle<int> boundaryLevelAdjust("boundaryLevelAdjust", 0);
Setting::Handle<float> octreeSizeScale("octreeSizeScale", DEFAULT_OCTREE_SIZE_SCALE);
void LODManager::autoAdjustLOD(float currentFPS) {
// NOTE: our first ~100 samples at app startup are completely all over the place, and we don't
@ -190,21 +190,21 @@ void LODManager::setBoundaryLevelAdjust(int boundaryLevelAdjust) {
void LODManager::loadSettings() {
setAutomaticAvatarLOD(SettingHandles::automaticAvatarLOD.get());
setAvatarLODDecreaseFPS(SettingHandles::avatarLODDecreaseFPS.get());
setAvatarLODIncreaseFPS(SettingHandles::avatarLODIncreaseFPS.get());
setAvatarLODDistanceMultiplier(SettingHandles::avatarLODDistanceMultiplier.get());
setBoundaryLevelAdjust(SettingHandles::boundaryLevelAdjust.get());
setOctreeSizeScale(SettingHandles::octreeSizeScale.get());
setAutomaticAvatarLOD(automaticAvatarLOD.get());
setAvatarLODDecreaseFPS(avatarLODDecreaseFPS.get());
setAvatarLODIncreaseFPS(avatarLODIncreaseFPS.get());
setAvatarLODDistanceMultiplier(avatarLODDistanceMultiplier.get());
setBoundaryLevelAdjust(boundaryLevelAdjust.get());
setOctreeSizeScale(octreeSizeScale.get());
}
void LODManager::saveSettings() {
SettingHandles::automaticAvatarLOD.set(getAutomaticAvatarLOD());
SettingHandles::avatarLODDecreaseFPS.set(getAvatarLODDecreaseFPS());
SettingHandles::avatarLODIncreaseFPS.set(getAvatarLODIncreaseFPS());
SettingHandles::avatarLODDistanceMultiplier.set(getAvatarLODDistanceMultiplier());
SettingHandles::boundaryLevelAdjust.set(getBoundaryLevelAdjust());
SettingHandles::octreeSizeScale.set(getOctreeSizeScale());
automaticAvatarLOD.set(getAutomaticAvatarLOD());
avatarLODDecreaseFPS.set(getAvatarLODDecreaseFPS());
avatarLODIncreaseFPS.set(getAvatarLODIncreaseFPS());
avatarLODDistanceMultiplier.set(getAvatarLODDistanceMultiplier());
boundaryLevelAdjust.set(getBoundaryLevelAdjust());
octreeSizeScale.set(getOctreeSizeScale());
}

View file

@ -14,7 +14,6 @@
#include <DependencyManager.h>
#include <OctreeConstants.h>
#include <Settings.h>
#include <SharedUtil.h>
#include <SimpleMovingAverage.h>

View file

@ -18,24 +18,20 @@
#include <QHideEvent>
#include <QWindowStateChangeEvent>
#include <Settings.h>
#include "MainWindow.h"
#include "Menu.h"
#include "Util.h"
namespace SettingHandles {
const SettingHandle<QRect> windowGeometry("WindowGeometry");
}
MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
MainWindow::MainWindow(QWidget* parent) :
QMainWindow(parent),
_windowGeometry("WindowGeometry")
{
}
void MainWindow::restoreGeometry() {
// Did not use setGeometry() on purpose,
// see http://doc.qt.io/qt-5/qsettings.html#restoring-the-state-of-a-gui-application
QRect geometry = SettingHandles::windowGeometry.get(qApp->desktop()->availableGeometry());
QRect geometry = _windowGeometry.get(qApp->desktop()->availableGeometry());
move(geometry.topLeft());
resize(geometry.size());
}
@ -44,7 +40,7 @@ void MainWindow::saveGeometry() {
// Did not use geometry() on purpose,
// see http://doc.qt.io/qt-5/qsettings.html#restoring-the-state-of-a-gui-application
QRect geometry(pos(), size());
SettingHandles::windowGeometry.set(geometry);
_windowGeometry.set(geometry);
}
void MainWindow::moveEvent(QMoveEvent* event) {

View file

@ -14,6 +14,8 @@
#include <QMainWindow>
#include <SettingHandle.h>
class MainWindow : public QMainWindow {
Q_OBJECT
public:
@ -33,6 +35,9 @@ protected:
virtual void showEvent(QShowEvent* event);
virtual void hideEvent(QHideEvent* event);
virtual void changeEvent(QEvent* event);
private:
Setting::Handle<QRect> _windowGeometry;
};
#endif /* defined(__hifi__MainWindow__) */

View file

@ -14,18 +14,19 @@
#include <QShortcut>
#include <AddressManager.h>
#include <AudioClient.h>
#include <DependencyManager.h>
#include <GlowEffect.h>
#include <PathUtils.h>
#include <Settings.h>
#include <SettingHandle.h>
#include <UserActivityLogger.h>
#include <XmppClient.h>
#include "Application.h"
#include "AccountManager.h"
#include "Audio.h"
#include "audio/AudioIOStatsRenderer.h"
#include "audio/AudioScope.h"
#include "avatar/AvatarManager.h"
#include "devices/Faceshift.h"
#include "devices/RealSense.h"
#include "devices/SixenseManager.h"
@ -186,26 +187,26 @@ Menu::Menu() {
SLOT(resetSensors()));
QMenu* avatarMenu = addMenu("Avatar");
QObject* avatar = DependencyManager::get<AvatarManager>()->getMyAvatar();
QMenu* avatarSizeMenu = avatarMenu->addMenu("Size");
addActionToQMenuAndActionHash(avatarSizeMenu,
MenuOption::IncreaseAvatarSize,
Qt::Key_Plus,
qApp->getAvatar(),
avatar,
SLOT(increaseSize()));
addActionToQMenuAndActionHash(avatarSizeMenu,
MenuOption::DecreaseAvatarSize,
Qt::Key_Minus,
qApp->getAvatar(),
avatar,
SLOT(decreaseSize()));
addActionToQMenuAndActionHash(avatarSizeMenu,
MenuOption::ResetAvatarSize,
Qt::Key_Equal,
qApp->getAvatar(),
avatar,
SLOT(resetSize()));
QObject* avatar = qApp->getAvatar();
addCheckableActionToQMenuAndActionHash(avatarMenu, MenuOption::KeyboardMotorControl,
addCheckableActionToQMenuAndActionHash(avatarMenu, MenuOption::KeyboardMotorControl,
Qt::CTRL | Qt::SHIFT | Qt::Key_K, true, avatar, SLOT(updateMotionBehavior()));
addCheckableActionToQMenuAndActionHash(avatarMenu, MenuOption::ScriptedMotorControl, 0, true,
avatar, SLOT(updateMotionBehavior()));
@ -333,7 +334,7 @@ Menu::Menu() {
#if defined(Q_OS_MAC)
#else
addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::RenderTargetFramerateVSyncOn, 0, true,
qApp, SLOT(changeVSync()));
qApp, SLOT(setVSyncEnabled()));
#endif
}
@ -447,7 +448,7 @@ Menu::Menu() {
addCheckableActionToQMenuAndActionHash(timingMenu, MenuOption::PipelineWarnings);
addCheckableActionToQMenuAndActionHash(timingMenu, MenuOption::SuppressShortTimings);
auto audioIO = DependencyManager::get<Audio>();
auto audioIO = DependencyManager::get<AudioClient>();
QMenu* audioDebugMenu = developerMenu->addMenu("Audio");
addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioNoiseReduction,
0,

View file

@ -239,8 +239,6 @@ namespace MenuOption {
const QString RunTimingTests = "Run Timing Tests";
const QString ScriptEditor = "Script Editor...";
const QString ScriptedMotorControl = "Enable Scripted Motor Control";
const QString SettingsExport = "Export Settings";
const QString SettingsImport = "Import Settings";
const QString ShowBordersEntityNodes = "Show Entity Nodes";
const QString ShowBordersVoxelNodes = "Show Voxel Nodes";
const QString ShowIKConstraints = "Show IK Constraints";

View file

@ -899,8 +899,6 @@ int MetavoxelSystemClient::parseData(const QByteArray& packet) {
} else {
QMetaObject::invokeMethod(&_sequencer, "receivedDatagram", Q_ARG(const QByteArray&, packet));
}
Application::getInstance()->getBandwidthRecorder()->metavoxelsChannel->input.updateValue(packet.size());
Application::getInstance()->getBandwidthRecorder()->totalChannel->input.updateValue(packet.size());
}
return packet.size();
}
@ -1016,8 +1014,6 @@ void MetavoxelSystemClient::sendDatagram(const QByteArray& data) {
} else {
DependencyManager::get<NodeList>()->writeDatagram(data, _node);
}
Application::getInstance()->getBandwidthRecorder()->metavoxelsChannel->output.updateValue(data.size());
Application::getInstance()->getBandwidthRecorder()->totalChannel->output.updateValue(data.size());
}
}

View file

@ -38,7 +38,6 @@
#include <GeometryCache.h>
#include <GLMHelpers.h>
#include <ResourceCache.h>
#include <Settings.h>
#include <TextureCache.h>
#include "ModelUploader.h"
@ -68,14 +67,13 @@ static const int MAX_CHECK = 30;
static const int QCOMPRESS_HEADER_POSITION = 0;
static const int QCOMPRESS_HEADER_SIZE = 4;
namespace SettingHandles {
const SettingHandle<QString> lastModelUploadLocation("LastModelUploadLocation",
QStandardPaths::writableLocation(QStandardPaths::DownloadLocation));
}
Setting::Handle<QString> ModelUploader::_lastModelUploadLocation("LastModelUploadLocation",
QStandardPaths::writableLocation(QStandardPaths::DownloadLocation));
void ModelUploader::uploadModel(ModelType modelType) {
ModelUploader* uploader = new ModelUploader(modelType);
QThread* thread = new QThread();
thread->setObjectName("Model Uploader");
thread->connect(uploader, SIGNAL(destroyed()), SLOT(quit()));
thread->connect(thread, SIGNAL(finished()), SLOT(deleteLater()));
uploader->connect(thread, SIGNAL(started()), SLOT(send()));
@ -117,7 +115,7 @@ ModelUploader::~ModelUploader() {
bool ModelUploader::zip() {
// File Dialog
QString lastLocation = SettingHandles::lastModelUploadLocation.get();
QString lastLocation = _lastModelUploadLocation.get();
if (lastLocation.isEmpty()) {
lastLocation = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
@ -134,7 +132,7 @@ bool ModelUploader::zip() {
// If the user canceled we return.
return false;
}
SettingHandles::lastModelUploadLocation.set(filename);
_lastModelUploadLocation.set(filename);
// First we check the FST file (if any)
QFile* fst;
@ -265,7 +263,7 @@ bool ModelUploader::zip() {
return true;
}
void ModelUploader::populateBasicMapping(QVariantHash& mapping, QString filename, FBXGeometry geometry) {
void ModelUploader::populateBasicMapping(QVariantHash& mapping, QString filename, const FBXGeometry& geometry) {
if (!mapping.contains(NAME_FIELD)) {
mapping.insert(NAME_FIELD, QFileInfo(filename).baseName());
}

View file

@ -16,6 +16,7 @@
#include <QTimer>
#include <FBXReader.h>
#include <SettingHandle.h>
#include "ui/ModelsBrowser.h"
@ -53,7 +54,7 @@ private:
ModelUploader(ModelType type);
~ModelUploader();
void populateBasicMapping(QVariantHash& mapping, QString filename, FBXGeometry geometry);
void populateBasicMapping(QVariantHash& mapping, QString filename, const FBXGeometry& geometry);
bool zip();
bool addTextures(const QString& texdir, const FBXGeometry& geometry);
bool addPart(const QString& path, const QString& name, bool isTexture = false);
@ -68,13 +69,15 @@ private:
ModelType _modelType;
bool _readyToSend;
QHttpMultiPart* _dataMultiPart;
QHttpMultiPart* _dataMultiPart = nullptr;
int _numberOfChecks;
QTimer _timer;
QDialog* _progressDialog;
QProgressBar* _progressBar;
QDialog* _progressDialog = nullptr;
QProgressBar* _progressBar = nullptr;
static Setting::Handle<QString> _lastModelUploadLocation;
};
/// A dialog that allows customization of various model properties.
@ -101,23 +104,23 @@ private:
QVariantHash _originalMapping;
QString _basePath;
FBXGeometry _geometry;
QLineEdit* _name;
QPushButton* _textureDirectory;
QDoubleSpinBox* _scale;
QDoubleSpinBox* _translationX;
QDoubleSpinBox* _translationY;
QDoubleSpinBox* _translationZ;
QCheckBox* _pivotAboutCenter;
QComboBox* _pivotJoint;
QComboBox* _leftEyeJoint;
QComboBox* _rightEyeJoint;
QComboBox* _neckJoint;
QComboBox* _rootJoint;
QComboBox* _leanJoint;
QComboBox* _headJoint;
QComboBox* _leftHandJoint;
QComboBox* _rightHandJoint;
QVBoxLayout* _freeJoints;
QLineEdit* _name = nullptr;
QPushButton* _textureDirectory = nullptr;
QDoubleSpinBox* _scale = nullptr;
QDoubleSpinBox* _translationX = nullptr;
QDoubleSpinBox* _translationY = nullptr;
QDoubleSpinBox* _translationZ = nullptr;
QCheckBox* _pivotAboutCenter = nullptr;
QComboBox* _pivotJoint = nullptr;
QComboBox* _leftEyeJoint = nullptr;
QComboBox* _rightEyeJoint = nullptr;
QComboBox* _neckJoint = nullptr;
QComboBox* _rootJoint = nullptr;
QComboBox* _leanJoint = nullptr;
QComboBox* _headJoint = nullptr;
QComboBox* _leftHandJoint = nullptr;
QComboBox* _rightHandJoint = nullptr;
QVBoxLayout* _freeJoints = nullptr;
};
#endif // hifi_ModelUploader_h

View file

@ -1,6 +1,6 @@
//
// UIUtil.cpp
// library/shared/src
// interface/src
//
// Created by Ryan Huffman on 09/02/2014.
// Copyright 2014 High Fidelity, Inc.

View file

@ -1,6 +1,6 @@
//
// UIUtil.h
// library/shared/src
// interface/src
//
// Created by Ryan Huffman on 09/02/2014.
// Copyright 2014 High Fidelity, Inc.

View file

@ -96,7 +96,7 @@ static TextRenderer* textRenderer(int mono) {
}
int widthText(float scale, int mono, char const* string) {
return textRenderer(mono)->computeWidth(string) * (scale / 0.10);
return textRenderer(mono)->computeExtent(string).x; // computeWidth(string) * (scale / 0.10);
}
void drawText(int x, int y, float scale, float radians, int mono,

View file

@ -11,15 +11,14 @@
#include "InterfaceConfig.h"
#include <AudioClient.h>
#include <AudioConstants.h>
#include <AudioIOStats.h>
#include <DependencyManager.h>
#include <GeometryCache.h>
#include <NodeList.h>
#include <Util.h>
#include "Audio.h"
#include "AudioIOStats.h"
#include "AudioIOStatsRenderer.h"
AudioIOStatsRenderer::AudioIOStatsRenderer() :
@ -28,7 +27,7 @@ AudioIOStatsRenderer::AudioIOStatsRenderer() :
_shouldShowInjectedStreams(false)
{
// grab the stats object from the audio I/O singleton
_stats = &DependencyManager::get<Audio>()->getStats();
_stats = &DependencyManager::get<AudioClient>()->getStats();
}
#ifdef _WIN32

View file

@ -13,11 +13,10 @@
#include <limits>
#include <AudioClient.h>
#include <AudioConstants.h>
#include <GeometryCache.h>
#include "Audio.h"
#include "AudioScope.h"
static const unsigned int DEFAULT_FRAMES_PER_SCOPE = 5;
@ -41,14 +40,14 @@ AudioScope::AudioScope() :
_outputLeftID(DependencyManager::get<GeometryCache>()->allocateID()),
_outputRightD(DependencyManager::get<GeometryCache>()->allocateID())
{
auto audioIO = DependencyManager::get<Audio>();
auto audioIO = DependencyManager::get<AudioClient>();
connect(&audioIO->getReceivedAudioStream(), &MixedProcessedAudioStream::addedSilence,
this, &AudioScope::addStereoSilenceToScope);
connect(&audioIO->getReceivedAudioStream(), &MixedProcessedAudioStream::addedLastFrameRepeatedWithFade,
this, &AudioScope::addLastFrameRepeatedWithFadeToScope);
connect(&audioIO->getReceivedAudioStream(), &MixedProcessedAudioStream::addedStereoSamples,
this, &AudioScope::addStereoSamplesToScope);
connect(audioIO.data(), &Audio::inputReceived, this, &AudioScope::addInputToScope);
connect(audioIO.data(), &AudioClient::inputReceived, this, &AudioScope::addInputToScope);
}
void AudioScope::toggle() {

View file

@ -11,12 +11,11 @@
#include "InterfaceConfig.h"
#include <AudioClient.h>
#include <GLCanvas.h>
#include <PathUtils.h>
#include <GeometryCache.h>
#include "Audio.h"
#include "AudioToolBox.h"
// Mute icon configration
@ -29,7 +28,7 @@ AudioToolBox::AudioToolBox() :
bool AudioToolBox::mousePressEvent(int x, int y) {
if (_iconBounds.contains(x, y)) {
DependencyManager::get<Audio>()->toggleMute();
DependencyManager::get<AudioClient>()->toggleMute();
return true;
}
return false;
@ -49,7 +48,7 @@ void AudioToolBox::render(int x, int y, bool boxed) {
_boxTextureId = glCanvas->bindTexture(QImage(PathUtils::resourcesPath() + "images/audio-box.svg"));
}
auto audioIO = DependencyManager::get<Audio>();
auto audioIO = DependencyManager::get<AudioClient>();
if (boxed) {
bool isClipping = ((audioIO->getTimeSinceLastClip() > 0.0f) && (audioIO->getTimeSinceLastClip() < 1.0f));

View file

@ -36,6 +36,7 @@
#include "Application.h"
#include "Avatar.h"
#include "AvatarManager.h"
#include "Hand.h"
#include "Head.h"
#include "Menu.h"
@ -272,7 +273,8 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode, bool
_referential->update();
}
if (postLighting && glm::distance(Application::getInstance()->getAvatar()->getPosition(), _position) < 10.0f) {
if (postLighting &&
glm::distance(DependencyManager::get<AvatarManager>()->getMyAvatar()->getPosition(), _position) < 10.0f) {
auto geometryCache = DependencyManager::get<GeometryCache>();
// render pointing lasers
@ -351,7 +353,7 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode, bool
const float GLOW_MAX_LOUDNESS = 2500.0f;
const float MAX_GLOW = 0.5f;
float GLOW_FROM_AVERAGE_LOUDNESS = ((this == Application::getInstance()->getAvatar())
float GLOW_FROM_AVERAGE_LOUDNESS = ((this == DependencyManager::get<AvatarManager>()->getMyAvatar())
? 0.0f
: MAX_GLOW * getHeadData()->getAudioLoudness() / GLOW_MAX_LOUDNESS);
if (!Menu::getInstance()->isOptionChecked(MenuOption::GlowWhenSpeaking)) {
@ -375,7 +377,7 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode, bool
float distance = BASE_LIGHT_DISTANCE * _scale;
glm::vec3 position = glm::mix(_skeletonModel.getTranslation(), getHead()->getFaceModel().getTranslation(), 0.9f);
glm::quat orientation = getOrientation();
foreach (const AvatarManager::LocalLight& light, Application::getInstance()->getAvatarManager().getLocalLights()) {
foreach (const AvatarManager::LocalLight& light, DependencyManager::get<AvatarManager>()->getLocalLights()) {
glm::vec3 direction = orientation * light.direction;
DependencyManager::get<DeferredLightingEffect>()->addSpotLight(position - direction * distance,
distance * 2.0f, glm::vec3(), light.color, light.color, 1.0f, 0.5f, 0.0f, direction,
@ -678,9 +680,7 @@ void Avatar::renderDisplayName() {
glRotatef(glm::degrees(angle), 0.0f, 1.0f, 0.0f);
float scaleFactor = calculateDisplayNameScaleFactor(textPosition, inHMD);
glScalef(scaleFactor, scaleFactor, 1.0);
glScalef(1.0f, -1.0f, 1.0f); // TextRenderer::draw paints the text upside down in y axis
glScalef(scaleFactor, -scaleFactor, scaleFactor); // TextRenderer::draw paints the text upside down in y axis
int text_x = -_displayNameBoundingRect.width() / 2;
int text_y = -_displayNameBoundingRect.height() / 2;
@ -913,7 +913,9 @@ void Avatar::setAttachmentData(const QVector<AttachmentData>& attachmentData) {
void Avatar::setDisplayName(const QString& displayName) {
AvatarData::setDisplayName(displayName);
_displayNameBoundingRect = textRenderer(DISPLAYNAME)->metrics().tightBoundingRect(displayName);
// FIXME is this a sufficient replacement for tightBoundingRect?
glm::vec2 extent = textRenderer(DISPLAYNAME)->computeExtent(displayName);
_displayNameBoundingRect = QRect(QPoint(0, 0), QPoint((int)extent.x, (int)extent.y));
}
void Avatar::setBillboard(const QByteArray& billboard) {
@ -1048,7 +1050,7 @@ void Avatar::setShowDisplayName(bool showDisplayName) {
}
// For myAvatar, the alpha update is not done (called in simulate for other avatars)
if (Application::getInstance()->getAvatar() == this) {
if (DependencyManager::get<AvatarManager>()->getMyAvatar() == this) {
if (showDisplayName) {
_displayNameAlpha = DISPLAYNAME_ALPHA;
} else {

View file

@ -55,10 +55,6 @@ enum ScreenTintLayer {
NUM_SCREEN_TINT_LAYERS
};
// Where one's own Avatar begins in the world (will be overwritten if avatar data file is found).
// This is the start location in the Sandbox (xyz: 6270, 211, 6000).
const glm::vec3 START_LOCATION(0.38269043f * TREE_SCALE, 0.01287842f * TREE_SCALE, 0.36621094f * TREE_SCALE);
class Texture;
class Avatar : public AvatarData {

View file

@ -26,6 +26,9 @@
#include "Menu.h"
#include "MyAvatar.h"
// 70 times per second - target is 60hz, but this helps account for any small deviations
// in the update loop
static const quint64 MIN_TIME_BETWEEN_MY_AVATAR_DATA_SENDS = (1000 * 1000) / 70;
// We add _myAvatar into the hash with all the other AvatarData, and we use the default NULL QUid as the key.
const QUuid MY_AVATAR_KEY; // NULL key
@ -56,11 +59,26 @@ AvatarManager::AvatarManager(QObject* parent) :
void AvatarManager::init() {
_myAvatar->init();
_myAvatar->setPosition(START_LOCATION);
_myAvatar->setDisplayingLookatVectors(false);
_avatarHash.insert(MY_AVATAR_KEY, _myAvatar);
}
void AvatarManager::updateMyAvatar(float deltaTime) {
bool showWarnings = Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings);
PerformanceWarning warn(showWarnings, "AvatarManager::updateMyAvatar()");
_myAvatar->update(deltaTime);
quint64 now = usecTimestampNow();
quint64 dt = now - _lastSendAvatarDataTime;
if (dt > MIN_TIME_BETWEEN_MY_AVATAR_DATA_SENDS) {
// send head/hand data to the avatar mixer and voxel server
PerformanceTimer perfTimer("send");
_myAvatar->sendAvatarDataPacket();
_lastSendAvatarDataTime = now;
}
}
void AvatarManager::updateOtherAvatars(float deltaTime) {
if (_avatarHash.size() < 2 && _avatarFades.isEmpty()) {
return;

View file

@ -24,18 +24,18 @@ class MyAvatar;
class AvatarManager : public AvatarHashMap {
Q_OBJECT
SINGLETON_DEPENDENCY
public:
/// Registers the script types associated with the avatar manager.
static void registerMetaTypes(QScriptEngine* engine);
AvatarManager(QObject* parent = 0);
void init();
MyAvatar* getMyAvatar() { return _myAvatar.data(); }
void updateMyAvatar(float deltaTime);
void updateOtherAvatars(float deltaTime);
void renderAvatars(Avatar::RenderMode renderMode, bool postLighting = false, bool selfAvatarOnly = false);
@ -51,6 +51,7 @@ public:
Q_INVOKABLE QVector<AvatarManager::LocalLight> getLocalLights() const;
private:
AvatarManager(QObject* parent = 0);
AvatarManager(const AvatarManager& other);
void simulateAvatarFades(float deltaTime);
@ -63,6 +64,7 @@ private:
QVector<AvatarSharedPointer> _avatarFades;
QSharedPointer<MyAvatar> _myAvatar;
quint64 _lastSendAvatarDataTime = 0; // Controls MyAvatar send data rate.
QVector<AvatarManager::LocalLight> _localLights;
};

View file

@ -12,15 +12,14 @@
#include <QImage>
#include <NodeList.h>
#include <GeometryUtil.h>
#include <NodeList.h>
#include <ProgramObject.h>
#include "Application.h"
#include "Avatar.h"
#include "AvatarManager.h"
#include "Hand.h"
#include "Menu.h"
#include "MyAvatar.h"
#include "Util.h"
using namespace std;
@ -131,7 +130,7 @@ void Hand::render(bool isMine, Model::RenderMode renderMode) {
void Hand::renderHandTargets(bool isMine) {
glPushMatrix();
const float avatarScale = Application::getInstance()->getAvatar()->getScale();
const float avatarScale = DependencyManager::get<AvatarManager>()->getMyAvatar()->getScale();
const float alpha = 1.0f;
const glm::vec3 handColor(1.0, 0.0, 0.0); // Color the hand targets red to be different than skin

View file

@ -18,8 +18,6 @@
#include <HeadData.h>
#include <OctreeConstants.h> // for IDENTITY_*
#include "FaceModel.h"
#include "InterfaceConfig.h"
#include "world.h"

View file

@ -23,18 +23,18 @@
#include <AccountManager.h>
#include <AddressManager.h>
#include <AnimationHandle.h>
#include <AudioClient.h>
#include <DependencyManager.h>
#include <GeometryUtil.h>
#include <NodeList.h>
#include <PacketHeaders.h>
#include <PerfStat.h>
#include <Settings.h>
#include <ShapeCollider.h>
#include <SharedUtil.h>
#include <TextRenderer.h>
#include "Application.h"
#include "Audio.h"
#include "AvatarManager.h"
#include "Environment.h"
#include "Menu.h"
#include "ModelReferential.h"
@ -52,6 +52,7 @@ const float YAW_SPEED = 500.0f; // degrees/sec
const float PITCH_SPEED = 100.0f; // degrees/sec
const float COLLISION_RADIUS_SCALAR = 1.2f; // pertains to avatar-to-avatar collisions
const float COLLISION_RADIUS_SCALE = 0.125f;
const float DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES = 30.0f;
const float MAX_WALKING_SPEED = 2.5f; // human walking speed
const float MAX_BOOST_SPEED = 0.5f * MAX_WALKING_SPEED; // keyboard motor gets additive boost below this speed
@ -90,7 +91,9 @@ MyAvatar::MyAvatar() :
_billboardValid(false),
_physicsSimulation(),
_feetTouchFloor(true),
_isLookingAtLeftEye(true)
_isLookingAtLeftEye(true),
_realWorldFieldOfView("realWorldFieldOfView",
DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES)
{
ShapeCollider::initDispatchTable();
for (int i = 0; i < MAX_DRIVE_KEYS; i++) {
@ -147,7 +150,7 @@ void MyAvatar::update(float deltaTime) {
head->relaxLean(deltaTime);
updateFromTrackers(deltaTime);
// Get audio loudness data from audio input device
auto audio = DependencyManager::get<Audio>();
auto audio = DependencyManager::get<AudioClient>();
head->setAudioLoudness(audio->getLastInputLoudness());
head->setAudioAverageLoudness(audio->getAudioAverageInputLoudness());
@ -339,8 +342,8 @@ void MyAvatar::updateFromTrackers(float deltaTime) {
head->setDeltaPitch(estimatedRotation.x);
head->setDeltaYaw(estimatedRotation.y);
} else {
float magnifyFieldOfView = qApp->getViewFrustum()->getFieldOfView() /
qApp->getViewFrustum()->getRealWorldFieldOfView();
float magnifyFieldOfView = qApp->getFieldOfView() /
_realWorldFieldOfView.get();
head->setDeltaPitch(estimatedRotation.x * magnifyFieldOfView);
head->setDeltaYaw(estimatedRotation.y * magnifyFieldOfView);
}
@ -490,9 +493,12 @@ void MyAvatar::startRecording() {
if (!_recorder) {
_recorder = RecorderPointer(new Recorder(this));
}
DependencyManager::get<Audio>()->setRecorder(_recorder);
_recorder->startRecording();
// connect to AudioClient's signal so we get input audio
auto audioClient = DependencyManager::get<AudioClient>();
connect(audioClient.data(), &AudioClient::inputReceived, _recorder.data(),
&Recorder::recordAudio, Qt::BlockingQueuedConnection);
_recorder->startRecording();
}
void MyAvatar::stopRecording() {
@ -504,6 +510,10 @@ void MyAvatar::stopRecording() {
return;
}
if (_recorder) {
// stop grabbing audio from the AudioClient
auto audioClient = DependencyManager::get<AudioClient>();
disconnect(audioClient.data(), 0, _recorder.data(), 0);
_recorder->stopRecording();
}
}
@ -896,7 +906,7 @@ void MyAvatar::updateLookAtTargetAvatar() {
const float GREATEST_LOOKING_AT_DISTANCE = 10.0f;
int howManyLookingAtMe = 0;
foreach (const AvatarSharedPointer& avatarPointer, Application::getInstance()->getAvatarManager().getAvatarHash()) {
foreach (const AvatarSharedPointer& avatarPointer, DependencyManager::get<AvatarManager>()->getAvatarHash()) {
Avatar* avatar = static_cast<Avatar*>(avatarPointer.data());
bool isCurrentTarget = avatar->getIsLookAtTarget();
float distanceTo = glm::length(avatar->getHead()->getEyePosition() - cameraPosition);
@ -1613,7 +1623,7 @@ bool findAvatarAvatarPenetration(const glm::vec3 positionA, float radiusA, float
void MyAvatar::updateCollisionWithAvatars(float deltaTime) {
// Reset detector for nearest avatar
_distanceToNearestAvatar = std::numeric_limits<float>::max();
const AvatarHash& avatars = Application::getInstance()->getAvatarManager().getAvatarHash();
const AvatarHash& avatars = DependencyManager::get<AvatarManager>()->getAvatarHash();
if (avatars.size() <= 1) {
// no need to compute a bunch of stuff if we have one or fewer avatars
return;
@ -1688,7 +1698,7 @@ void MyAvatar::updateChatCircle(float deltaTime) {
// find all circle-enabled members and sort by distance
QVector<SortedAvatar> sortedAvatars;
foreach (const AvatarSharedPointer& avatarPointer, Application::getInstance()->getAvatarManager().getAvatarHash()) {
foreach (const AvatarSharedPointer& avatarPointer, DependencyManager::get<AvatarManager>()->getAvatarHash()) {
Avatar* avatar = static_cast<Avatar*>(avatarPointer.data());
if ( ! avatar->isChatCirclingEnabled() ||
avatar == static_cast<Avatar*>(this)) {

View file

@ -12,9 +12,8 @@
#ifndef hifi_MyAvatar_h
#define hifi_MyAvatar_h
#include <QSettings>
#include <PhysicsSimulation.h>
#include <SettingHandle.h>
#include "Avatar.h"
@ -47,12 +46,14 @@ public:
void setLeanScale(float scale) { _leanScale = scale; }
void setLocalGravity(glm::vec3 gravity);
void setShouldRenderLocally(bool shouldRender) { _shouldRender = shouldRender; }
void setRealWorldFieldOfView(float realWorldFov) { _realWorldFieldOfView.set(realWorldFov); }
// getters
float getLeanScale() const { return _leanScale; }
glm::vec3 getGravity() const { return _gravity; }
Q_INVOKABLE glm::vec3 getDefaultEyePosition() const;
bool getShouldRenderLocally() const { return _shouldRender; }
float getRealWorldFieldOfView() { return _realWorldFieldOfView.get(); }
const QList<AnimationHandlePointer>& getAnimationHandles() const { return _animationHandles; }
AnimationHandlePointer addAnimationHandle();
@ -225,6 +226,8 @@ private:
glm::vec3 _trackedHeadPosition;
Setting::Handle<float> _realWorldFieldOfView;
// private methods
void updateOrientation(float deltaTime);
glm::vec3 applyKeyboardMotor(float deltaTime, const glm::vec3& velocity, bool walkingOnFloor);

View file

@ -13,7 +13,6 @@
#include <GLMHelpers.h>
#include <PerfStat.h>
#include <Settings.h>
#include <SharedUtil.h>
#include "Faceshift.h"
@ -29,11 +28,6 @@ using namespace std;
const quint16 FACESHIFT_PORT = 33433;
float STARTING_FACESHIFT_FRAME_TIME = 0.033f;
namespace SettingHandles {
const SettingHandle<float> faceshiftEyeDeflection("faceshiftEyeDeflection", DEFAULT_FACESHIFT_EYE_DEFLECTION);
const SettingHandle<QString> faceshiftHostname("faceshiftHostname", DEFAULT_FACESHIFT_HOSTNAME);
}
Faceshift::Faceshift() :
_tcpEnabled(true),
_tcpRetryCount(0),
@ -61,7 +55,9 @@ Faceshift::Faceshift() :
_jawOpenIndex(21),
_longTermAverageEyePitch(0.0f),
_longTermAverageEyeYaw(0.0f),
_longTermAverageInitialized(false)
_longTermAverageInitialized(false),
_eyeDeflection("faceshiftEyeDeflection", DEFAULT_FACESHIFT_EYE_DEFLECTION),
_hostname("faceshiftHostname", DEFAULT_FACESHIFT_HOSTNAME)
{
#ifdef HAVE_FACESHIFT
connect(&_tcpSocket, SIGNAL(connected()), SLOT(noteConnected()));
@ -73,9 +69,6 @@ Faceshift::Faceshift() :
_udpSocket.bind(FACESHIFT_PORT);
#endif
_eyeDeflection = SettingHandles::faceshiftEyeDeflection.get();
_hostname = SettingHandles::faceshiftHostname.get();
}
void Faceshift::init() {
@ -169,7 +162,7 @@ void Faceshift::connectSocket() {
qDebug("Faceshift: Connecting...");
}
_tcpSocket.connectToHost(_hostname, FACESHIFT_PORT);
_tcpSocket.connectToHost(_hostname.get(), FACESHIFT_PORT);
_tracking = false;
}
}
@ -321,11 +314,9 @@ void Faceshift::receive(const QByteArray& buffer) {
}
void Faceshift::setEyeDeflection(float faceshiftEyeDeflection) {
_eyeDeflection = faceshiftEyeDeflection;
SettingHandles::faceshiftEyeDeflection.set(_eyeDeflection);
_eyeDeflection.set(faceshiftEyeDeflection);
}
void Faceshift::setHostname(const QString& hostname) {
_hostname = hostname;
SettingHandles::faceshiftHostname.set(_hostname);
_hostname.set(hostname);
}

View file

@ -20,6 +20,7 @@
#endif
#include <DependencyManager.h>
#include <SettingHandle.h>
#include "FaceTracker.h"
@ -62,10 +63,10 @@ public:
float getMouthSmileLeft() const { return getBlendshapeCoefficient(_mouthSmileLeftIndex); }
float getMouthSmileRight() const { return getBlendshapeCoefficient(_mouthSmileRightIndex); }
float getEyeDeflection() const { return _eyeDeflection; }
float getEyeDeflection() { return _eyeDeflection.get(); }
void setEyeDeflection(float faceshiftEyeDeflection);
const QString& getHostname() const { return _hostname; }
QString getHostname() { return _hostname.get(); }
void setHostname(const QString& hostname);
void update();
@ -151,8 +152,8 @@ private:
float _longTermAverageEyeYaw;
bool _longTermAverageInitialized;
float _eyeDeflection = DEFAULT_FACESHIFT_EYE_DEFLECTION;
QString _hostname = DEFAULT_FACESHIFT_HOSTNAME;
Setting::Handle<float> _eyeDeflection;
Setting::Handle<QString> _hostname;
};

View file

@ -83,8 +83,10 @@ MotionTracker::Index MotionTracker::addJoint(const Semantic& semantic, Index par
// Check that the semantic is not already in use
Index foundIndex = findJointIndex(semantic);
if (foundIndex >= 0)
if (foundIndex >= 0) {
return INVALID_SEMANTIC;
}
// All good then allocate the joint
Index newIndex = _jointsArray.size();
@ -97,8 +99,10 @@ MotionTracker::Index MotionTracker::addJoint(const Semantic& semantic, Index par
MotionTracker::Index MotionTracker::findJointIndex(const Semantic& semantic) const {
// TODO C++11 auto jointIt = _jointsMap.find(semantic);
JointTracker::Map::const_iterator jointIt = _jointsMap.find(semantic);
if (jointIt != _jointsMap.end())
if (jointIt != _jointsMap.end()) {
return (*jointIt).second;
}
return INVALID_SEMANTIC;
}

View file

@ -37,7 +37,7 @@ public:
// Semantic and Index types to retreive the JointTrackers of this MotionTracker
typedef std::string Semantic;
typedef int Index;
typedef int32_t Index;
static const Index INVALID_SEMANTIC = -1;
static const Index INVALID_PARENT = -2;

View file

@ -22,6 +22,8 @@
#include <glm/glm.hpp>
#include <avatar/AvatarManager.h>
#include <avatar/MyAvatar.h>
#include <GlowEffect.h>
#include <PathUtils.h>
#include <SharedUtil.h>
@ -198,11 +200,12 @@ void OculusManager::disconnect() {
#ifdef HAVE_LIBOVR
void OculusManager::positionCalibrationBillboard(Text3DOverlay* billboard) {
glm::quat headOrientation = Application::getInstance()->getAvatar()->getHeadOrientation();
MyAvatar* myAvatar = DependencyManager::get<AvatarManager>()->getMyAvatar();
glm::quat headOrientation = myAvatar->getHeadOrientation();
headOrientation.x = 0;
headOrientation.z = 0;
glm::normalize(headOrientation);
billboard->setPosition(Application::getInstance()->getAvatar()->getHeadPosition()
billboard->setPosition(myAvatar->getHeadPosition()
+ headOrientation * glm::vec3(0.0f, 0.0f, -CALIBRATION_MESSAGE_DISTANCE));
billboard->setRotation(headOrientation);
}

View file

@ -12,6 +12,7 @@
#include <QTimer>
#include <QtDebug>
#include <avatar/AvatarManager.h>
#include <FBXReader.h>
#include <PerfStat.h>
#include <TextRenderer.h>
@ -42,7 +43,7 @@ static int indexOfHumanIKJoint(const char* jointName) {
}
static void setPalm(float deltaTime, int index) {
MyAvatar* avatar = Application::getInstance()->getAvatar();
MyAvatar* avatar = DependencyManager::get<AvatarManager>()->getMyAvatar();
Hand* hand = avatar->getHand();
PalmData* palm;
bool foundHand = false;
@ -86,9 +87,9 @@ static void setPalm(float deltaTime, int index) {
// TODO: transfom this to stay in the model-frame.
glm::vec3 position;
glm::quat rotation;
SkeletonModel* skeletonModel = &Application::getInstance()->getAvatar()->getSkeletonModel();
SkeletonModel* skeletonModel = &DependencyManager::get<AvatarManager>()->getMyAvatar()->getSkeletonModel();
int jointIndex;
glm::quat inverseRotation = glm::inverse(Application::getInstance()->getAvatar()->getOrientation());
glm::quat inverseRotation = glm::inverse(DependencyManager::get<AvatarManager>()->getMyAvatar()->getOrientation());
if (index == LEFT_HAND_INDEX) {
jointIndex = skeletonModel->getLeftHandJointIndex();
skeletonModel->getJointRotationInWorldFrame(jointIndex, rotation);
@ -216,7 +217,7 @@ void PrioVR::renderCalibrationCountdown() {
false, TextRenderer::OUTLINE_EFFECT, 2);
QByteArray text = "Assume T-Pose in " + QByteArray::number(secondsRemaining) + "...";
auto glCanvas = DependencyManager::get<GLCanvas>();
textRenderer->draw((glCanvas->width() - textRenderer->computeWidth(text.constData())) / 2,
textRenderer->draw((glCanvas->width() - textRenderer->computeExtent(text.constData()).x) / 2,
glCanvas->height() / 2,
text, glm::vec4(1,1,1,1));
#endif

View file

@ -15,8 +15,10 @@
#include "Menu.h"
#include "SharedUtil.h"
const int PALMROOT_NUM_JOINTS = 2;
#ifdef HAVE_RSSDK
const int PALMROOT_NUM_JOINTS = 3;
const int FINGER_NUM_JOINTS = 4;
#endif // HAVE_RSSDK
const DeviceTracker::Name RealSense::NAME = "RealSense";

View file

@ -11,6 +11,7 @@
#include <vector>
#include <avatar/AvatarManager.h>
#include <PerfStat.h>
#include "Application.h"
@ -144,7 +145,7 @@ void SixenseManager::setFilter(bool filter) {
void SixenseManager::update(float deltaTime) {
#ifdef HAVE_SIXENSE
Hand* hand = Application::getInstance()->getAvatar()->getHand();
Hand* hand = DependencyManager::get<AvatarManager>()->getMyAvatar()->getHand();
if (_isInitialized && _isEnabled) {
#ifdef __APPLE__
SixenseBaseFunction sixenseGetNumActiveControllers =
@ -458,8 +459,7 @@ void SixenseManager::updateCalibration(const sixenseControllerData* controllers)
//Injecting mouse movements and clicks
void SixenseManager::emulateMouse(PalmData* palm, int index) {
Application* application = Application::getInstance();
MyAvatar* avatar = application->getAvatar();
MyAvatar* avatar = DependencyManager::get<AvatarManager>()->getMyAvatar();
auto glCanvas = DependencyManager::get<GLCanvas>();
QPoint pos;
@ -478,7 +478,7 @@ void SixenseManager::emulateMouse(PalmData* palm, int index) {
if (Menu::getInstance()->isOptionChecked(MenuOption::SixenseLasers)
|| Menu::getInstance()->isOptionChecked(MenuOption::EnableVRMode)) {
pos = application->getApplicationOverlay().getPalmClickLocation(palm);
pos = qApp->getApplicationOverlay().getPalmClickLocation(palm);
} else {
// Get directon relative to avatar orientation
glm::vec3 direction = glm::inverse(avatar->getOrientation()) * palm->getFingerDirection();
@ -501,14 +501,14 @@ void SixenseManager::emulateMouse(PalmData* palm, int index) {
if (_bumperPressed[index]) {
QMouseEvent mouseEvent(QEvent::MouseButtonRelease, pos, bumperButton, bumperButton, 0);
application->mouseReleaseEvent(&mouseEvent, deviceID);
qApp->mouseReleaseEvent(&mouseEvent, deviceID);
_bumperPressed[index] = false;
}
if (_triggerPressed[index]) {
QMouseEvent mouseEvent(QEvent::MouseButtonRelease, pos, triggerButton, triggerButton, 0);
application->mouseReleaseEvent(&mouseEvent, deviceID);
qApp->mouseReleaseEvent(&mouseEvent, deviceID);
_triggerPressed[index] = false;
}
@ -522,11 +522,11 @@ void SixenseManager::emulateMouse(PalmData* palm, int index) {
//Only send the mouse event if the opposite left button isnt held down.
if (triggerButton == Qt::LeftButton) {
if (!_triggerPressed[(int)(!index)]) {
application->mouseMoveEvent(&mouseEvent, deviceID);
qApp->mouseMoveEvent(&mouseEvent, deviceID);
}
} else {
if (!_bumperPressed[(int)(!index)]) {
application->mouseMoveEvent(&mouseEvent, deviceID);
qApp->mouseMoveEvent(&mouseEvent, deviceID);
}
}
}
@ -549,12 +549,12 @@ void SixenseManager::emulateMouse(PalmData* palm, int index) {
QMouseEvent mouseEvent(QEvent::MouseButtonPress, pos, bumperButton, bumperButton, 0);
application->mousePressEvent(&mouseEvent, deviceID);
qApp->mousePressEvent(&mouseEvent, deviceID);
}
} else if (_bumperPressed[index]) {
QMouseEvent mouseEvent(QEvent::MouseButtonRelease, pos, bumperButton, bumperButton, 0);
application->mouseReleaseEvent(&mouseEvent, deviceID);
qApp->mouseReleaseEvent(&mouseEvent, deviceID);
_bumperPressed[index] = false;
}
@ -566,12 +566,12 @@ void SixenseManager::emulateMouse(PalmData* palm, int index) {
QMouseEvent mouseEvent(QEvent::MouseButtonPress, pos, triggerButton, triggerButton, 0);
application->mousePressEvent(&mouseEvent, deviceID);
qApp->mousePressEvent(&mouseEvent, deviceID);
}
} else if (_triggerPressed[index]) {
QMouseEvent mouseEvent(QEvent::MouseButtonRelease, pos, triggerButton, triggerButton, 0);
application->mouseReleaseEvent(&mouseEvent, deviceID);
qApp->mouseReleaseEvent(&mouseEvent, deviceID);
_triggerPressed[index] = false;
}

View file

@ -15,9 +15,52 @@
#include <SharedUtil.h>
#include "AddressManager.h"
#include "Application.h"
#ifdef Q_OS_WIN
static BOOL CALLBACK enumWindowsCallback(HWND hWnd, LPARAM lParam) {
const UINT TIMEOUT = 200; // ms
DWORD response;
LRESULT result = SendMessageTimeout(hWnd, UWM_IDENTIFY_INSTANCES, 0, 0, SMTO_BLOCK | SMTO_ABORTIFHUNG, TIMEOUT, &response);
if (result == 0) { // Timeout; continue search.
return TRUE;
}
if (response == UWM_IDENTIFY_INSTANCES) {
HWND* target = (HWND*)lParam;
*target = hWnd;
return FALSE; // Found; terminate search.
}
return TRUE; // Not found; continue search.
}
#endif
int main(int argc, const char * argv[]) {
#ifdef Q_OS_WIN
// Run only one instance of Interface at a time.
HANDLE mutex = CreateMutex(NULL, FALSE, "High Fidelity Interface");
DWORD result = GetLastError();
if (result == ERROR_ALREADY_EXISTS || result == ERROR_ACCESS_DENIED) {
// Interface is already running.
HWND otherInstance = NULL;
EnumWindows(enumWindowsCallback, (LPARAM)&otherInstance);
if (otherInstance) {
ShowWindow(otherInstance, SW_RESTORE);
SetForegroundWindow(otherInstance);
QUrl url = QUrl(argv[1]);
if (url.isValid() && url.scheme() == HIFI_URL_SCHEME) {
COPYDATASTRUCT cds;
cds.cbData = strlen(argv[1]) + 1;
cds.lpData = (PVOID)argv[1];
SendMessage(otherInstance, WM_COPYDATA, 0, (LPARAM)&cds);
}
}
return 0;
}
#endif
QElapsedTimer startupTime;
startupTime.start();
@ -44,6 +87,11 @@ int main(int argc, const char * argv[]) {
qDebug( "Created QT Application.");
exitCode = app.exec();
}
#ifdef Q_OS_WIN
ReleaseMutex(mutex);
#endif
qDebug("Normal exit.");
return exitCode;
}

View file

@ -68,11 +68,12 @@ void OctreePacketProcessor::processPacket(const SharedNodePointer& sendingNode,
<< senderUUID << "sent" << (int)packetVersion << "but"
<< (int)expectedVersion << "expected.";
emit packetVersionMismatch();
versionDebugSuppressMap.insert(senderUUID, voxelPacketType);
}
return; // bail since piggyback version doesn't match
}
app->trackIncomingOctreePacket(mutablePacket, sendingNode, wasStatsPacket);

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