From f6142686671fc14ff3e29c3a150dfa02ee81cf7a Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Sat, 6 Jun 2015 23:51:37 -0700 Subject: [PATCH 01/90] Moving windows to SDK 0.6 Working on SDK 0.6 for windows Working on SDK 0.6 for windows --- cmake/externals/LibOVR/CMakeLists.txt | 4 +- cmake/externals/oglplus/CMakeLists.txt | 10 +- cmake/macros/SetupHifiOpenGL.cmake | 43 ++ interface/src/Application.cpp | 14 +- interface/src/devices/OculusManager.cpp | 613 +++++++++++------------- interface/src/devices/OculusManager.h | 66 +-- libraries/render-utils/src/Model.cpp | 2 +- libraries/shared/CMakeLists.txt | 14 +- libraries/shared/src/OglplusHelpers.cpp | 322 +++++++++++++ libraries/shared/src/OglplusHelpers.h | 166 +++++++ 10 files changed, 851 insertions(+), 403 deletions(-) create mode 100644 cmake/macros/SetupHifiOpenGL.cmake create mode 100644 libraries/shared/src/OglplusHelpers.cpp create mode 100644 libraries/shared/src/OglplusHelpers.h diff --git a/cmake/externals/LibOVR/CMakeLists.txt b/cmake/externals/LibOVR/CMakeLists.txt index 2198ed378a..d491434b5f 100644 --- a/cmake/externals/LibOVR/CMakeLists.txt +++ b/cmake/externals/LibOVR/CMakeLists.txt @@ -9,8 +9,8 @@ if (WIN32) ExternalProject_Add( ${EXTERNAL_NAME} - URL http://static.oculus.com/sdk-downloads/ovr_sdk_win_0.5.0.1.zip - URL_MD5 d3fc4c02db9be5ff08af4ef4c97b32f9 + URL http://static.oculus.com/sdk-downloads/0.6.0.0/1431634088/ovr_sdk_win_0.6.0.0.zip + URL_MD5 a3dfdab037a854fdcf7e6033fa8d7028 CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND "" diff --git a/cmake/externals/oglplus/CMakeLists.txt b/cmake/externals/oglplus/CMakeLists.txt index 1413edce34..13709c1fde 100644 --- a/cmake/externals/oglplus/CMakeLists.txt +++ b/cmake/externals/oglplus/CMakeLists.txt @@ -4,11 +4,11 @@ string(TOUPPER ${EXTERNAL_NAME} EXTERNAL_NAME_UPPER) include(ExternalProject) ExternalProject_Add( ${EXTERNAL_NAME} - URL http://softlayer-dal.dl.sourceforge.net/project/oglplus/oglplus-0.61.x/oglplus-0.61.0.zip - URL_MD5 bb55038c36c660d2b6c7be380414fa60 - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - INSTALL_COMMAND "" + GIT_REPOSITORY https://github.com/matus-chochlik/oglplus.git + GIT_TAG 9660aaaf65c5a3f47e6c54827ae28ae1ec5c5deb + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND "" LOG_DOWNLOAD 1 ) diff --git a/cmake/macros/SetupHifiOpenGL.cmake b/cmake/macros/SetupHifiOpenGL.cmake new file mode 100644 index 0000000000..c62e43c27e --- /dev/null +++ b/cmake/macros/SetupHifiOpenGL.cmake @@ -0,0 +1,43 @@ + + +macro(SETUP_HIFI_OPENGL) + + if (APPLE) + + # link in required OS X frameworks and include the right GL headers + find_library(OpenGL OpenGL) + target_link_libraries(${TARGET_NAME} ${OpenGL}) + + elseif (WIN32) + + add_dependency_external_projects(glew) + find_package(GLEW REQUIRED) + target_include_directories(${TARGET_NAME} PUBLIC ${GLEW_INCLUDE_DIRS}) + target_link_libraries(${TARGET_NAME} ${GLEW_LIBRARIES} opengl32.lib) + + if (USE_NSIGHT) + # try to find the Nsight package and add it to the build if we find it + find_package(NSIGHT) + if (NSIGHT_FOUND) + include_directories(${NSIGHT_INCLUDE_DIRS}) + add_definitions(-DNSIGHT_FOUND) + target_link_libraries(${TARGET_NAME} "${NSIGHT_LIBRARIES}") + endif() + endif() + + elseif(ANDROID) + + target_link_libraries(${TARGET_NAME} "-lGLESv3" "-lEGL") + + else() + + find_package(OpenGL REQUIRED) + if (${OPENGL_INCLUDE_DIR}) + include_directories(SYSTEM "${OPENGL_INCLUDE_DIR}") + endif() + target_link_libraries(${TARGET_NAME} "${OPENGL_LIBRARY}") + target_include_directories(${TARGET_NAME} PUBLIC ${OPENGL_INCLUDE_DIR}) + + endif() + +endmacro() diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index dbdcaa122a..93f6217cb9 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1860,11 +1860,13 @@ void Application::setEnableVRMode(bool enableVRMode) { // attempt to reconnect the Oculus manager - it's possible this was a workaround // for the sixense crash OculusManager::disconnect(); + _glWidget->makeCurrent(); OculusManager::connect(); } OculusManager::recalibrate(); } else { OculusManager::abandonCalibration(); + OculusManager::disconnect(); _mirrorCamera.setHmdPosition(glm::vec3()); _mirrorCamera.setHmdRotation(glm::quat()); @@ -2102,12 +2104,12 @@ void Application::init() { _mirrorCamera.setMode(CAMERA_MODE_MIRROR); - OculusManager::connect(); - if (OculusManager::isConnected()) { - QMetaObject::invokeMethod(Menu::getInstance()->getActionForOption(MenuOption::Fullscreen), - "trigger", - Qt::QueuedConnection); - } + //OculusManager::connect(); + //if (OculusManager::isConnected()) { + // QMetaObject::invokeMethod(Menu::getInstance()->getActionForOption(MenuOption::Fullscreen), + // "trigger", + // Qt::QueuedConnection); + //} TV3DManager::connect(); if (TV3DManager::isConnected()) { diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index 3ceb2fd079..12b8abeb66 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -25,6 +25,8 @@ #include #include #include +#include +#include #include #include #include @@ -34,7 +36,6 @@ #include "InterfaceLogging.h" #include "Application.h" -#include template void for_each_eye(Function function) { @@ -53,27 +54,132 @@ void for_each_eye(const ovrHmd & hmd, Function function) { } } -#ifdef OVR_CLIENT_DISTORTION -ProgramObject OculusManager::_program; -int OculusManager::_textureLocation; -int OculusManager::_eyeToSourceUVScaleLocation; -int OculusManager::_eyeToSourceUVOffsetLocation; -int OculusManager::_eyeRotationStartLocation; -int OculusManager::_eyeRotationEndLocation; -int OculusManager::_positionAttributeLocation; -int OculusManager::_colorAttributeLocation; -int OculusManager::_texCoord0AttributeLocation; -int OculusManager::_texCoord1AttributeLocation; -int OculusManager::_texCoord2AttributeLocation; -ovrVector2f OculusManager::_UVScaleOffset[ovrEye_Count][2]; -GLuint OculusManager::_vertices[ovrEye_Count] = { 0, 0 }; -GLuint OculusManager::_indices[ovrEye_Count] = { 0, 0 }; -GLsizei OculusManager::_meshSize[ovrEye_Count] = { 0, 0 }; -ovrFrameTiming OculusManager::_hmdFrameTiming; -bool OculusManager::_programInitialized = false; -#endif + +#ifdef Q_OS_WIN + +// A base class for FBO wrappers that need to use the Oculus C +// API to manage textures via ovrHmd_CreateSwapTextureSetGL, +// ovrHmd_CreateMirrorTextureGL, etc +template +struct RiftFramebufferWrapper : public FramebufferWrapper { + ovrHmd hmd; + RiftFramebufferWrapper(const ovrHmd & hmd) : hmd(hmd) { + color = 0; + depth = 0; + }; + + void Resize(const uvec2 & size) { + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, oglplus::GetName(fbo)); + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + this->size = size; + initColor(); + initDone(); + } + +protected: + virtual void initDepth() override final { + } +}; + +// A wrapper for constructing and using a swap texture set, +// where each frame you draw to a texture via the FBO, +// then submit it and increment to the next texture. +// The Oculus SDK manages the creation and destruction of +// the textures +struct SwapFramebufferWrapper : public RiftFramebufferWrapper { + SwapFramebufferWrapper(const ovrHmd & hmd) + : RiftFramebufferWrapper(hmd) { + } + + ~SwapFramebufferWrapper() { + if (color) { + ovrHmd_DestroySwapTextureSet(hmd, color); + color = nullptr; + } + } + + void Increment() { + ++color->CurrentIndex; + color->CurrentIndex %= color->TextureCount; + } + +protected: + virtual void initColor() override { + if (color) { + ovrHmd_DestroySwapTextureSet(hmd, color); + color = nullptr; + } + + ovrResult result = ovrHmd_CreateSwapTextureSetGL(hmd, GL_RGBA, size.x, size.y, &color); + Q_ASSERT(OVR_SUCCESS(result)); + + for (int i = 0; i < color->TextureCount; ++i) { + ovrGLTexture& ovrTex = (ovrGLTexture&)color->Textures[i]; + glBindTexture(GL_TEXTURE_2D, ovrTex.OGL.TexId); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } + glBindTexture(GL_TEXTURE_2D, 0); + } + + virtual void initDone() override { + } + + virtual void onBind(oglplus::Framebuffer::Target target) override { + ovrGLTexture& tex = (ovrGLTexture&)(color->Textures[color->CurrentIndex]); + glFramebufferTexture2D(toEnum(target), GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex.OGL.TexId, 0); + } + + virtual void onUnbind(oglplus::Framebuffer::Target target) override { + glFramebufferTexture2D(toEnum(target), GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); + } +}; + + +// We use a FBO to wrap the mirror texture because it makes it easier to +// render to the screen via glBlitFramebuffer +struct MirrorFramebufferWrapper : public RiftFramebufferWrapper { + MirrorFramebufferWrapper(const ovrHmd & hmd) + : RiftFramebufferWrapper(hmd) { + } + + virtual ~MirrorFramebufferWrapper() { + if (color) { + ovrHmd_DestroyMirrorTexture(hmd, (ovrTexture*)color); + color = nullptr; + } + } + +private: + void initColor() override { + if (color) { + ovrHmd_DestroyMirrorTexture(hmd, (ovrTexture*)color); + color = nullptr; + } + ovrResult result = ovrHmd_CreateMirrorTextureGL(hmd, GL_RGBA, size.x, size.y, (ovrTexture**)&color); + Q_ASSERT(OVR_SUCCESS(result)); + } + + void initDone() override { + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, oglplus::GetName(fbo)); + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color->OGL.TexId, 0); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + } +}; + +SwapFramebufferWrapper* OculusManager::_swapFbo{ nullptr }; +MirrorFramebufferWrapper* OculusManager::_mirrorFbo{ nullptr }; +ovrLayerEyeFov OculusManager::_sceneLayer; + +#else ovrTexture OculusManager::_eyeTextures[ovrEye_Count]; + +#endif + bool OculusManager::_isConnected = false; ovrHmd OculusManager::_ovrHmd; ovrFovPort OculusManager::_eyeFov[ovrEye_Count]; @@ -104,39 +210,41 @@ bool OculusManager::_eyePerFrameMode = false; ovrEyeType OculusManager::_lastEyeRendered = ovrEye_Count; ovrSizei OculusManager::_recommendedTexSize = { 0, 0 }; float OculusManager::_offscreenRenderScale = 1.0; - - -void OculusManager::initSdk() { - ovr_Initialize(); - _ovrHmd = ovrHmd_Create(0); - if (!_ovrHmd) { - _ovrHmd = ovrHmd_CreateDebug(ovrHmd_DK2); - } -} - -void OculusManager::shutdownSdk() { - if (_ovrHmd) { - ovrHmd_Destroy(_ovrHmd); - _ovrHmd = nullptr; - ovr_Shutdown(); - } -} +ovrRecti OculusManager::_eyeViewports[ovrEye_Count]; void OculusManager::init() { -#ifdef OVR_DIRECT_MODE - initSdk(); -#endif } void OculusManager::deinit() { -#ifdef OVR_DIRECT_MODE - shutdownSdk(); -#endif } void OculusManager::connect() { -#ifndef OVR_DIRECT_MODE - initSdk(); + + ovrInitParams initParams; memset(&initParams, 0, sizeof(initParams)); +#ifdef DEBUG + //initParams.Flags |= ovrInit_Debug; +#endif + ovr_Initialize(&initParams); + +#ifdef Q_OS_WIN + + ovrResult res = ovrHmd_Create(0, &_ovrHmd); +#ifdef DEBUG + if (!OVR_SUCCESS(res)) { + res = ovrHmd_CreateDebug(ovrHmd_DK2, &_ovrHmd); + Q_ASSERT(OVR_SUCCESS(res)); + } +#endif + +#else + + _ovrHmd = ovrHmd_Create(0); +#ifdef DEBUG + if (!_ovrHmd) { + _ovrHmd = ovrHmd_CreateDebug(ovrHmd_DK2); + } +#endif + #endif _calibrationState = UNCALIBRATED; qCDebug(interfaceapp) << "Oculus SDK" << OVR_VERSION_STRING; @@ -150,6 +258,28 @@ void OculusManager::connect() { _eyeFov[eye] = _ovrHmd->DefaultEyeFov[eye]; }); + _recommendedTexSize = ovrHmd_GetFovTextureSize(_ovrHmd, ovrEye_Left, _eyeFov[ovrEye_Left], 1.0f); + _renderTargetSize = { _recommendedTexSize.w * 2, _recommendedTexSize.h }; + +#ifdef Q_OS_WIN + + _mirrorFbo = new MirrorFramebufferWrapper(_ovrHmd); + _swapFbo = new SwapFramebufferWrapper(_ovrHmd); + _swapFbo->Init(toGlm(_renderTargetSize)); + _sceneLayer.ColorTexture[0] = _swapFbo->color; + _sceneLayer.ColorTexture[1] = nullptr; + _sceneLayer.Viewport[0].Pos = { 0, 0 }; + _sceneLayer.Viewport[0].Size = { _swapFbo->size.x / 2, _swapFbo->size.y }; + _sceneLayer.Viewport[1].Pos = { _swapFbo->size.x / 2, 0 }; + _sceneLayer.Viewport[1].Size = { _swapFbo->size.x / 2, _swapFbo->size.y }; + _sceneLayer.Header.Type = ovrLayerType_EyeFov; + _sceneLayer.Header.Flags = ovrLayerFlag_TextureOriginAtBottomLeft; + for_each_eye([&](ovrEyeType eye) { + _eyeViewports[eye] = _sceneLayer.Viewport[eye]; + _sceneLayer.Fov[eye] = _eyeFov[eye]; + }); + +#else ovrGLConfig cfg; memset(&cfg, 0, sizeof(cfg)); cfg.OGL.Header.API = ovrRenderAPI_OpenGL; @@ -166,15 +296,19 @@ void OculusManager::connect() { assert(configResult); - _recommendedTexSize = ovrHmd_GetFovTextureSize(_ovrHmd, ovrEye_Left, _eyeFov[ovrEye_Left], 1.0f); - _renderTargetSize = { _recommendedTexSize.w * 2, _recommendedTexSize.h }; for_each_eye([&](ovrEyeType eye) { //Get texture size _eyeTextures[eye].Header.API = ovrRenderAPI_OpenGL; _eyeTextures[eye].Header.TextureSize = _renderTargetSize; _eyeTextures[eye].Header.RenderViewport.Pos = { 0, 0 }; + _eyeTextures[eye].Header.RenderViewport.Size = _renderTargetSize; + _eyeTextures[eye].Header.RenderViewport.Size.w /= 2; }); _eyeTextures[ovrEye_Right].Header.RenderViewport.Pos.x = _recommendedTexSize.w; + for_each_eye([&](ovrEyeType eye) { + _eyeViewports[eye] = _eyeTextures[eye].Header.RenderViewport; + }); +#endif ovrHmd_SetEnabledCaps(_ovrHmd, ovrHmdCap_LowPersistence | ovrHmdCap_DynamicPrediction); @@ -186,32 +320,6 @@ void OculusManager::connect() { _camera = new Camera; configureCamera(*_camera); // no need to use screen dimensions; they're ignored } -#ifdef OVR_CLIENT_DISTORTION - if (!_programInitialized) { - // Shader program - _programInitialized = true; - _program.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/oculus.vert"); - _program.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/oculus.frag"); - _program.link(); - - // Uniforms - _textureLocation = _program.uniformLocation("texture"); - _eyeToSourceUVScaleLocation = _program.uniformLocation("EyeToSourceUVScale"); - _eyeToSourceUVOffsetLocation = _program.uniformLocation("EyeToSourceUVOffset"); - _eyeRotationStartLocation = _program.uniformLocation("EyeRotationStart"); - _eyeRotationEndLocation = _program.uniformLocation("EyeRotationEnd"); - - // Attributes - _positionAttributeLocation = _program.attributeLocation("position"); - _colorAttributeLocation = _program.attributeLocation("color"); - _texCoord0AttributeLocation = _program.attributeLocation("texCoord0"); - _texCoord1AttributeLocation = _program.attributeLocation("texCoord1"); - _texCoord2AttributeLocation = _program.attributeLocation("texCoord2"); - } - - //Generate the distortion VBOs - generateDistortionMesh(); -#endif } else { _isConnected = false; @@ -223,27 +331,29 @@ void OculusManager::connect() { //Disconnects and deallocates the OR void OculusManager::disconnect() { if (_isConnected) { + +#ifdef Q_OS_WIN + if (_swapFbo) { + delete _swapFbo; + _swapFbo = nullptr; + } + + if (_mirrorFbo) { + delete _mirrorFbo; + _mirrorFbo = nullptr; + } +#endif + + if (_ovrHmd) { + ovrHmd_Destroy(_ovrHmd); + _ovrHmd = nullptr; + } + ovr_Shutdown(); + _isConnected = false; // Prepare to potentially have to dismiss the HSW again // if the user re-enables VR _hswDismissed = false; -#ifndef OVR_DIRECT_MODE - shutdownSdk(); -#endif - -#ifdef OVR_CLIENT_DISTORTION - //Free the distortion mesh data - for (int i = 0; i < ovrEye_Count; i++) { - if (_vertices[i] != 0) { - glDeleteBuffers(1, &(_vertices[i])); - _vertices[i] = 0; - } - if (_indices[i] != 0) { - glDeleteBuffers(1, &(_indices[i])); - _indices[i] = 0; - } - } -#endif } } @@ -363,64 +473,8 @@ void OculusManager::abandonCalibration() { } } -#ifdef OVR_CLIENT_DISTORTION -void OculusManager::generateDistortionMesh() { - - //Check if we already have the distortion mesh - if (_vertices[0] != 0) { - printf("WARNING: Tried to generate Oculus distortion mesh twice without freeing the VBOs."); - return; - } - - for (int eyeNum = 0; eyeNum < ovrEye_Count; eyeNum++) { - // Allocate and generate distortion mesh vertices - ovrDistortionMesh meshData; - ovrHmd_CreateDistortionMesh(_ovrHmd, _eyeRenderDesc[eyeNum].Eye, _eyeRenderDesc[eyeNum].Fov, _ovrHmd->DistortionCaps, &meshData); - - // Parse the vertex data and create a render ready vertex buffer - DistortionVertex* pVBVerts = new DistortionVertex[meshData.VertexCount]; - _meshSize[eyeNum] = meshData.IndexCount; - - // Convert the oculus vertex data to the DistortionVertex format. - DistortionVertex* v = pVBVerts; - ovrDistortionVertex* ov = meshData.pVertexData; - for (unsigned int vertNum = 0; vertNum < meshData.VertexCount; vertNum++) { - v->pos.x = ov->ScreenPosNDC.x; - v->pos.y = ov->ScreenPosNDC.y; - v->texR.x = ov->TanEyeAnglesR.x; - v->texR.y = ov->TanEyeAnglesR.y; - v->texG.x = ov->TanEyeAnglesG.x; - v->texG.y = ov->TanEyeAnglesG.y; - v->texB.x = ov->TanEyeAnglesB.x; - v->texB.y = ov->TanEyeAnglesB.y; - v->color.r = v->color.g = v->color.b = (GLubyte)(ov->VignetteFactor * 255.99f); - v->color.a = (GLubyte)(ov->TimeWarpFactor * 255.99f); - v++; - ov++; - } - - //vertices - glGenBuffers(1, &(_vertices[eyeNum])); - glBindBuffer(GL_ARRAY_BUFFER, _vertices[eyeNum]); - glBufferData(GL_ARRAY_BUFFER, sizeof(DistortionVertex) * meshData.VertexCount, pVBVerts, GL_STATIC_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, 0); - - //indices - glGenBuffers(1, &(_indices[eyeNum])); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indices[eyeNum]); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned short) * meshData.IndexCount, meshData.pIndexData, GL_STATIC_DRAW); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - - //Now that we have the VBOs we can get rid of the mesh data - delete [] pVBVerts; - ovrHmd_DestroyDistortionMesh(&meshData); - } - -} -#endif - bool OculusManager::isConnected() { - return _isConnected && Menu::getInstance()->isOptionChecked(MenuOption::EnableVRMode); + return _isConnected; } //Begins the frame timing for oculus prediction purposes @@ -428,10 +482,6 @@ void OculusManager::beginFrameTiming() { if (_frameTimingActive) { printf("WARNING: Called OculusManager::beginFrameTiming() twice in a row, need to call OculusManager::endFrameTiming()."); } - -#ifdef OVR_CLIENT_DISTORTION - _hmdFrameTiming = ovrHmd_BeginFrameTiming(_ovrHmd, _frameIndex); -#endif _frameTimingActive = true; } @@ -441,9 +491,6 @@ bool OculusManager::allowSwap() { //Ends frame timing void OculusManager::endFrameTiming() { -#ifdef OVR_CLIENT_DISTORTION - ovrHmd_EndFrameTiming(_ovrHmd); -#endif _frameIndex++; _frameTimingActive = false; } @@ -494,19 +541,20 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati timerActive = false; } #endif - -#ifdef OVR_DIRECT_MODE - static bool attached = false; - if (!attached) { - attached = true; - void * nativeWindowHandle = (void*)(size_t)glCanvas->effectiveWinId(); - if (nullptr != nativeWindowHandle) { - ovrHmd_AttachToWindow(_ovrHmd, nativeWindowHandle, nullptr, nullptr); - } + + ovrTrackingState ts = ovrHmd_GetTrackingState(_ovrHmd, ovr_GetTimeInSeconds()); + glm::vec3 trackerPosition = toGlm(ts.HeadPose.ThePose.Position); + + if (_calibrationState != CALIBRATED) { + calibrate(trackerPosition, toGlm(ts.HeadPose.ThePose.Orientation)); } -#endif + + trackerPosition = bodyOrientation * trackerPosition; + static ovrVector3f eyeOffsets[2] = { { 0, 0, 0 }, { 0, 0, 0 } }; + ovrPosef eyePoses[ovrEye_Count]; + ovrHmd_GetEyePoses(_ovrHmd, _frameIndex, eyeOffsets, eyePoses, nullptr); -#ifndef OVR_CLIENT_DISTORTION +#ifndef Q_OS_WIN // FIXME: we need a better way of responding to the HSW. In particular // we need to ensure that it's only displayed once per session, rather than // every time the user toggles VR mode, and we need to hook it up to actual @@ -522,7 +570,6 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati } } #endif - //beginFrameTiming must be called before display if (!_frameTimingActive) { @@ -545,27 +592,12 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati glMatrixMode(GL_MODELVIEW); glPushMatrix(); - - glm::quat orientation; - glm::vec3 trackerPosition; auto deviceSize = qApp->getDeviceSize(); - ovrTrackingState ts = ovrHmd_GetTrackingState(_ovrHmd, ovr_GetTimeInSeconds()); - ovrVector3f ovrHeadPosition = ts.HeadPose.ThePose.Position; - - trackerPosition = glm::vec3(ovrHeadPosition.x, ovrHeadPosition.y, ovrHeadPosition.z); - - if (_calibrationState != CALIBRATED) { - ovrQuatf ovrHeadOrientation = ts.HeadPose.ThePose.Orientation; - orientation = glm::quat(ovrHeadOrientation.w, ovrHeadOrientation.x, ovrHeadOrientation.y, ovrHeadOrientation.z); - calibrate(trackerPosition, orientation); - } - - trackerPosition = bodyOrientation * trackerPosition; - static ovrVector3f eyeOffsets[2] = { { 0, 0, 0 }, { 0, 0, 0 } }; - ovrPosef eyePoses[ovrEye_Count]; - ovrHmd_GetEyePoses(_ovrHmd, _frameIndex, eyeOffsets, eyePoses, nullptr); +#ifndef Q_OS_WIN ovrHmd_BeginFrame(_ovrHmd, _frameIndex); +#endif + static ovrPosef eyeRenderPose[ovrEye_Count]; //Render each eye into an fbo for_each_eye(_ovrHmd, [&](ovrEyeType eye){ @@ -578,11 +610,7 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati _lastEyeRendered = _activeEye = eye; eyeRenderPose[eye] = eyePoses[eye]; // Set the camera rotation for this eye - orientation.x = eyeRenderPose[eye].Orientation.x; - orientation.y = eyeRenderPose[eye].Orientation.y; - orientation.z = eyeRenderPose[eye].Orientation.z; - orientation.w = eyeRenderPose[eye].Orientation.w; - + glm::quat orientation = toGlm(eyeRenderPose[eye].Orientation); // Update the application camera with the latest HMD position whichCamera.setHmdPosition(trackerPosition); whichCamera.setHmdRotation(orientation); @@ -607,19 +635,14 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati glMatrixMode(GL_MODELVIEW); glLoadIdentity(); - ovrRecti & vp = _eyeTextures[eye].Header.RenderViewport; - vp.Size.h = _recommendedTexSize.h * _offscreenRenderScale; - vp.Size.w = _recommendedTexSize.w * _offscreenRenderScale; - + const ovrRecti& vp = _eyeViewports[eye]; glViewport(vp.Pos.x, vp.Pos.y, vp.Size.w, vp.Size.h); qApp->displaySide(*_camera, false, RenderArgs::MONO); - qApp->getApplicationOverlay().displayOverlayTextureHmd(*_camera); + //qApp->getApplicationOverlay().displayOverlayTextureHmd(*_camera); }); _activeEye = ovrEye_Count; - glPopMatrix(); - gpu::FramebufferPointer finalFbo; //Bind the output texture from the glow shader. If glow effect is disabled, we just grab the texture if (Menu::getInstance()->isOptionChecked(MenuOption::EnableGlowEffect)) { @@ -633,146 +656,70 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati glMatrixMode(GL_PROJECTION); glPopMatrix(); + glMatrixMode(GL_MODELVIEW); + glPopMatrix(); + + +#ifdef Q_OS_WIN + auto srcFboSize = finalFbo->getSize(); + + glBindFramebuffer(GL_READ_FRAMEBUFFER, gpu::GLBackend::getFramebufferID(finalFbo)); + _swapFbo->Bound(oglplus::Framebuffer::Target::Draw, [&] { + glBlitFramebuffer( + 0, 0, srcFboSize.x, srcFboSize.y, + 0, 0, _swapFbo->size.x, _swapFbo->size.y, + GL_COLOR_BUFFER_BIT, GL_NEAREST); + }); + auto destWindowSize = qApp->getDeviceSize(); + glBlitFramebuffer( + 0, 0, srcFboSize.x, srcFboSize.y, + 0, 0, destWindowSize.width(), destWindowSize.height(), + GL_COLOR_BUFFER_BIT, GL_NEAREST); + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + + ovrLayerEyeFov sceneLayer; + sceneLayer.ColorTexture[0] = _swapFbo->color; + sceneLayer.ColorTexture[1] = nullptr; + + sceneLayer.Viewport[0].Pos = { 0, 0 }; + sceneLayer.Viewport[0].Size = { _swapFbo->size.x / 2, _swapFbo->size.y }; + sceneLayer.Viewport[1].Pos = { _swapFbo->size.x / 2, 0 }; + sceneLayer.Viewport[1].Size = { _swapFbo->size.x / 2, _swapFbo->size.y }; + sceneLayer.Header.Type = ovrLayerType_EyeFov; + sceneLayer.Header.Flags = ovrLayerFlag_TextureOriginAtBottomLeft; + for_each_eye([&](ovrEyeType eye) { + sceneLayer.Fov[eye] = _eyeFov[eye]; + sceneLayer.RenderPose[eye] = eyeRenderPose[eye]; + }); + auto header = &sceneLayer.Header; + ovrResult res = ovrHmd_SubmitFrame(_ovrHmd, _frameIndex, nullptr, &header, 1); + Q_ASSERT(OVR_SUCCESS(res)); + _swapFbo->Increment(); +#else + GLuint textureId = gpu::GLBackend::getTextureID(finalFbo->getRenderBuffer(0)); + for_each_eye([&](ovrEyeType eye) { + ovrGLTexture & glEyeTexture = reinterpret_cast(_eyeTextures[eye]); + glEyeTexture.OGL.TexId = textureId; + }); + + //ovrHmd_EndFrame(_ovrHmd, eyeRenderPose, _eyeTextures); + glClearColor(0, 0, 0, 1); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + auto srcFboSize = finalFbo->getSize(); + glBindFramebuffer(GL_READ_FRAMEBUFFER, gpu::GLBackend::getFramebufferID(finalFbo)); + auto destWindowSize = qApp->getDeviceSize(); + glBlitFramebuffer( + 0, 0, srcFboSize.x, srcFboSize.y, + 0, 0, destWindowSize.width(), destWindowSize.height(), + GL_COLOR_BUFFER_BIT, GL_NEAREST); + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + glCanvas->swapBuffers(); +#endif // restore our normal viewport glViewport(0, 0, deviceSize.width(), deviceSize.height()); - -#if 0 - if (debugFrame && !timerActive) { - timerQuery.begin(); - } -#endif - -#ifdef OVR_CLIENT_DISTORTION - - //Wait till time-warp to reduce latency - ovr_WaitTillTime(_hmdFrameTiming.TimewarpPointSeconds); - -#ifdef DEBUG_RENDER_WITHOUT_DISTORTION - auto fboSize = finalFbo->getSize(); - glBindFramebuffer(GL_READ_FRAMEBUFFER, gpu::GLBackend::getFramebufferID(finalFbo)); - glBlitFramebuffer( - 0, 0, fboSize.x, fboSize.y, - 0, 0, deviceSize.width(), deviceSize.height(), - GL_COLOR_BUFFER_BIT, GL_NEAREST); -#else - //Clear the color buffer to ensure that there isnt any residual color - //Left over from when OR was not connected. - glClear(GL_COLOR_BUFFER_BIT); - glBindTexture(GL_TEXTURE_2D, gpu::GLBackend::getTextureID(finalFbo->getRenderBuffer(0))); - //Renders the distorted mesh onto the screen - renderDistortionMesh(eyeRenderPose); - glBindTexture(GL_TEXTURE_2D, 0); -#endif - glCanvas->swapBuffers(); - -#else - - for_each_eye([&](ovrEyeType eye) { - ovrGLTexture & glEyeTexture = reinterpret_cast(_eyeTextures[eye]); - glEyeTexture.OGL.TexId = finalFbo->texture(); - - }); - - ovrHmd_EndFrame(_ovrHmd, eyeRenderPose, _eyeTextures); - -#endif - -#if 0 - if (debugFrame && !timerActive) { - timerQuery.end(); - timerActive = true; - } -#endif - - // No DK2, no message. - { - float latencies[5] = {}; - if (debugFrame && ovrHmd_GetFloatArray(_ovrHmd, "DK2Latency", latencies, 5) == 5) - { - bool nonZero = false; - for (int i = 0; i < 5; ++i) - { - nonZero |= (latencies[i] != 0.f); - } - - if (nonZero) - { - qCDebug(interfaceapp) << QString().sprintf("M2P Latency: Ren: %4.2fms TWrp: %4.2fms PostPresent: %4.2fms Err: %4.2fms %4.2fms", - latencies[0], latencies[1], latencies[2], latencies[3], latencies[4]); - } - } - } - } -#ifdef OVR_CLIENT_DISTORTION -void OculusManager::renderDistortionMesh(ovrPosef eyeRenderPose[ovrEye_Count]) { - - glLoadIdentity(); - auto deviceSize = qApp->getDeviceSize(); - glOrtho(0, deviceSize.width(), 0, deviceSize.height(), -1.0, 1.0); - - glDisable(GL_DEPTH_TEST); - - glDisable(GL_BLEND); - _program.bind(); - _program.setUniformValue(_textureLocation, 0); - - _program.enableAttributeArray(_positionAttributeLocation); - _program.enableAttributeArray(_colorAttributeLocation); - _program.enableAttributeArray(_texCoord0AttributeLocation); - _program.enableAttributeArray(_texCoord1AttributeLocation); - _program.enableAttributeArray(_texCoord2AttributeLocation); - - //Render the distortion meshes for each eye - for (int eyeNum = 0; eyeNum < ovrEye_Count; eyeNum++) { - - ovrHmd_GetRenderScaleAndOffset(_eyeRenderDesc[eyeNum].Fov, _renderTargetSize, _eyeTextures[eyeNum].Header.RenderViewport, - _UVScaleOffset[eyeNum]); - - GLfloat uvScale[2] = { _UVScaleOffset[eyeNum][0].x, _UVScaleOffset[eyeNum][0].y }; - _program.setUniformValueArray(_eyeToSourceUVScaleLocation, uvScale, 1, 2); - GLfloat uvOffset[2] = { _UVScaleOffset[eyeNum][1].x, 1.0f - _UVScaleOffset[eyeNum][1].y }; - _program.setUniformValueArray(_eyeToSourceUVOffsetLocation, uvOffset, 1, 2); - - ovrMatrix4f timeWarpMatrices[2]; - glm::mat4 transposeMatrices[2]; - //Grabs the timewarp matrices to be used in the shader - ovrHmd_GetEyeTimewarpMatrices(_ovrHmd, (ovrEyeType)eyeNum, eyeRenderPose[eyeNum], timeWarpMatrices); - //Have to transpose the matrices before using them - transposeMatrices[0] = glm::transpose(toGlm(timeWarpMatrices[0])); - transposeMatrices[1] = glm::transpose(toGlm(timeWarpMatrices[1])); - - glUniformMatrix4fv(_eyeRotationStartLocation, 1, GL_FALSE, (GLfloat *)&transposeMatrices[0][0][0]); - glUniformMatrix4fv(_eyeRotationEndLocation, 1, GL_FALSE, (GLfloat *)&transposeMatrices[1][0][0]); - - glBindBuffer(GL_ARRAY_BUFFER, _vertices[eyeNum]); - - //Set vertex attribute pointers - glVertexAttribPointer(_positionAttributeLocation, 2, GL_FLOAT, GL_FALSE, sizeof(DistortionVertex), (void *)0); - glVertexAttribPointer(_texCoord0AttributeLocation, 2, GL_FLOAT, GL_FALSE, sizeof(DistortionVertex), (void *)8); - glVertexAttribPointer(_texCoord1AttributeLocation, 2, GL_FLOAT, GL_FALSE, sizeof(DistortionVertex), (void *)16); - glVertexAttribPointer(_texCoord2AttributeLocation, 2, GL_FLOAT, GL_FALSE, sizeof(DistortionVertex), (void *)24); - glVertexAttribPointer(_colorAttributeLocation, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(DistortionVertex), (void *)32); - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indices[eyeNum]); - glDrawElements(GL_TRIANGLES, _meshSize[eyeNum], GL_UNSIGNED_SHORT, 0); - } - - _program.disableAttributeArray(_positionAttributeLocation); - _program.disableAttributeArray(_colorAttributeLocation); - _program.disableAttributeArray(_texCoord0AttributeLocation); - _program.disableAttributeArray(_texCoord1AttributeLocation); - _program.disableAttributeArray(_texCoord2AttributeLocation); - - glEnable(GL_BLEND); - glEnable(GL_DEPTH_TEST); - _program.release(); - glBindBuffer(GL_ARRAY_BUFFER, 0); -} -#endif - //Tries to reconnect to the sensors void OculusManager::reset() { if (_isConnected) { @@ -825,6 +772,9 @@ void OculusManager::overrideOffAxisFrustum(float& left, float& right, float& bot } int OculusManager::getHMDScreen() { +#ifdef Q_OS_WIN + return -1; +#else int hmdScreenIndex = -1; // unknown // TODO: it might be smarter to handle multiple HMDs connected in this case. but for now, // we will simply assume the initialization code that set up _ovrHmd picked the best hmd @@ -875,5 +825,6 @@ int OculusManager::getHMDScreen() { } } return hmdScreenIndex; +#endif } diff --git a/interface/src/devices/OculusManager.h b/interface/src/devices/OculusManager.h index a6c3bbf4d5..d07a22fbd1 100644 --- a/interface/src/devices/OculusManager.h +++ b/interface/src/devices/OculusManager.h @@ -24,26 +24,9 @@ class Camera; class PalmData; class Text3DOverlay; -// Uncomment this to enable client side distortion. NOT recommended since -// the Oculus SDK will ideally provide the best practices for distortion in -// in terms of performance and quality, and by using it we will get updated -// best practices for free with new runtime releases. -#define OVR_CLIENT_DISTORTION 1 - - -// Direct HMD mode is currently only supported on windows and some linux systems will -// misbehave if we try to enable the Oculus SDK at all, so isolate support for Direct -// mode only to windows for now #ifdef Q_OS_WIN -// On Win32 platforms, enabling Direct HMD requires that the SDK be -// initialized before the GL context is set up, but this breaks v-sync -// for any application that has a Direct mode enable Rift connected -// but is not rendering to it. For the time being I'm setting this as -// a macro enabled mechanism which changes where the SDK is initialized. -// To enable Direct HMD mode, you can un-comment this, but with the -// caveat that it will break v-sync in NON-VR mode if you have an Oculus -// Rift connect and in Direct mode -#define OVR_DIRECT_MODE 1 +struct SwapFramebufferWrapper; +struct MirrorFramebufferWrapper; #endif @@ -83,44 +66,7 @@ public: private: static void initSdk(); static void shutdownSdk(); -#ifdef OVR_CLIENT_DISTORTION - static void generateDistortionMesh(); - static void renderDistortionMesh(ovrPosef eyeRenderPose[ovrEye_Count]); - struct DistortionVertex { - glm::vec2 pos; - glm::vec2 texR; - glm::vec2 texG; - glm::vec2 texB; - struct { - GLubyte r; - GLubyte g; - GLubyte b; - GLubyte a; - } color; - }; - static ProgramObject _program; - //Uniforms - static int _textureLocation; - static int _eyeToSourceUVScaleLocation; - static int _eyeToSourceUVOffsetLocation; - static int _eyeRotationStartLocation; - static int _eyeRotationEndLocation; - //Attributes - static int _positionAttributeLocation; - static int _colorAttributeLocation; - static int _texCoord0AttributeLocation; - static int _texCoord1AttributeLocation; - static int _texCoord2AttributeLocation; - static ovrVector2f _UVScaleOffset[ovrEye_Count][2]; - static GLuint _vertices[ovrEye_Count]; - static GLuint _indices[ovrEye_Count]; - static GLsizei _meshSize[ovrEye_Count]; - static ovrFrameTiming _hmdFrameTiming; - static bool _programInitialized; -#endif - - static ovrTexture _eyeTextures[ovrEye_Count]; static bool _isConnected; static glm::vec3 _eyePositions[ovrEye_Count]; static ovrHmd _ovrHmd; @@ -128,6 +74,7 @@ private: static ovrVector3f _eyeOffset[ovrEye_Count]; static glm::mat4 _eyeProjection[ovrEye_Count]; static ovrEyeRenderDesc _eyeRenderDesc[ovrEye_Count]; + static ovrRecti _eyeViewports[ovrEye_Count]; static ovrSizei _renderTargetSize; static unsigned int _frameIndex; static bool _frameTimingActive; @@ -160,6 +107,13 @@ private: static float _offscreenRenderScale; static bool _eyePerFrameMode; static ovrEyeType _lastEyeRendered; +#ifdef Q_OS_WIN + static SwapFramebufferWrapper* _swapFbo; + static MirrorFramebufferWrapper* _mirrorFbo; + static ovrLayerEyeFov _sceneLayer; +#else + static ovrTexture _eyeTextures[ovrEye_Count]; +#endif }; diff --git a/libraries/render-utils/src/Model.cpp b/libraries/render-utils/src/Model.cpp index 483ea6177e..feddf61405 100644 --- a/libraries/render-utils/src/Model.cpp +++ b/libraries/render-utils/src/Model.cpp @@ -1412,7 +1412,7 @@ void Model::simulate(float deltaTime, bool fullUpdate) { if (_snapModelToRegistrationPoint && !_snappedToRegistrationPoint) { snapToRegistrationPoint(); } - simulateInternal(deltaTime); + //simulateInternal(deltaTime); } } diff --git a/libraries/shared/CMakeLists.txt b/libraries/shared/CMakeLists.txt index 9785994a29..6f7efd1b40 100644 --- a/libraries/shared/CMakeLists.txt +++ b/libraries/shared/CMakeLists.txt @@ -2,8 +2,18 @@ set(TARGET_NAME shared) # use setup_hifi_library macro to setup our project and link appropriate Qt modules # TODO: there isn't really a good reason to have Script linked here - let's get what is requiring it out (RegisteredMetaTypes.cpp) -setup_hifi_library(Gui Network Script Widgets) +setup_hifi_library(Gui Network OpenGL Script Widgets) + +setup_hifi_opengl() add_dependency_external_projects(glm) find_package(GLM REQUIRED) -target_include_directories(${TARGET_NAME} PUBLIC ${GLM_INCLUDE_DIRS}) \ No newline at end of file +target_include_directories(${TARGET_NAME} PUBLIC ${GLM_INCLUDE_DIRS}) + +add_dependency_external_projects(boostconfig) +find_package(BOOSTCONFIG REQUIRED) +target_include_directories(${TARGET_NAME} PUBLIC ${BOOSTCONFIG_INCLUDE_DIRS}) + +add_dependency_external_projects(oglplus) +find_package(OGLPLUS REQUIRED) +target_include_directories(${TARGET_NAME} PUBLIC ${OGLPLUS_INCLUDE_DIRS}) diff --git a/libraries/shared/src/OglplusHelpers.cpp b/libraries/shared/src/OglplusHelpers.cpp new file mode 100644 index 0000000000..47e0773b5e --- /dev/null +++ b/libraries/shared/src/OglplusHelpers.cpp @@ -0,0 +1,322 @@ +// +// Created by Bradley Austin Davis on 2015/05/29 +// 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 "OglplusHelpers.h" + +using namespace oglplus; +using namespace oglplus::shapes; + +static const char * SIMPLE_TEXTURED_VS = R"VS(#version 410 core +#pragma line __LINE__ + +uniform mat4 Projection = mat4(1); +uniform mat4 ModelView = mat4(1); + +layout(location = 0) in vec3 Position; +layout(location = 1) in vec2 TexCoord; + +out vec2 vTexCoord; + +void main() { + gl_Position = Projection * ModelView * vec4(Position, 1); + vTexCoord = TexCoord; +} + +)VS"; + +static const char * SIMPLE_TEXTURED_FS = R"FS(#version 410 core +#pragma line __LINE__ + +uniform sampler2D sampler; +uniform float Alpha = 1.0; + +in vec2 vTexCoord; +out vec4 vFragColor; + +void main() { + vec4 c = texture(sampler, vTexCoord); + c.a = min(Alpha, c.a); + vFragColor = c; +} + +)FS"; + + +ProgramPtr loadDefaultShader() { + ProgramPtr result; + compileProgram(result, SIMPLE_TEXTURED_VS, SIMPLE_TEXTURED_FS); + return result; +} + +void compileProgram(ProgramPtr & result, const std::string& vs, const std::string& fs) { + using namespace oglplus; + try { + result = ProgramPtr(new Program()); + // attach the shaders to the program + result->AttachShader( + VertexShader() + .Source(GLSLSource(vs)) + .Compile() + ); + result->AttachShader( + FragmentShader() + .Source(GLSLSource(fs)) + .Compile() + ); + result->Link(); + } catch (ProgramBuildError & err) { + Q_UNUSED(err); + Q_ASSERT_X(false, "compileProgram", "Failed to build shader program"); + qFatal((const char*)err.Message); + result.reset(); + } +} + + +ShapeWrapperPtr loadPlane(ProgramPtr program, float aspect) { + using namespace oglplus; + Vec3f a(1, 0, 0); + Vec3f b(0, 1, 0); + if (aspect > 1) { + b[1] /= aspect; + } else { + a[0] *= aspect; + } + return ShapeWrapperPtr( + new shapes::ShapeWrapper({ "Position", "TexCoord" }, shapes::Plane(a, b), *program) + ); +} + +// Return a point's cartesian coordinates on a sphere from pitch and yaw +static glm::vec3 getPoint(float yaw, float pitch) { + return glm::vec3(glm::cos(-pitch) * (-glm::sin(yaw)), + glm::sin(-pitch), + glm::cos(-pitch) * (-glm::cos(yaw))); +} + + +class SphereSection : public DrawingInstructionWriter, public DrawMode { +public: + using IndexArray = std::vector; + using PosArray = std::vector; + using TexArray = std::vector; + /// The type of the index container returned by Indices() + // vertex positions + PosArray _pos_data; + // vertex tex coords + TexArray _tex_data; + IndexArray _idx_data; + unsigned int _prim_count{ 0 }; + +public: + SphereSection( + const float fov, + const float aspectRatio, + const int slices_, + const int stacks_) { + //UV mapping source: http://www.mvps.org/directx/articles/spheremap.htm + if (fov >= PI) { + qDebug() << "TexturedHemisphere::buildVBO(): FOV greater or equal than Pi will create issues"; + } + + int gridSize = std::max(slices_, stacks_); + int gridSizeLog2 = 1; + while (1 << gridSizeLog2 < gridSize) { + ++gridSizeLog2; + } + gridSize = (1 << gridSizeLog2) + 1; + // Compute number of vertices needed + int vertices = gridSize * gridSize; + _pos_data.resize(vertices * 3); + _tex_data.resize(vertices * 2); + + // Compute vertices positions and texture UV coordinate + for (int y = 0; y <= gridSize; ++y) { + for (int x = 0; x <= gridSize; ++x) { + + } + } + for (int i = 0; i < gridSize; i++) { + float stacksRatio = (float)i / (float)(gridSize - 1); // First stack is 0.0f, last stack is 1.0f + // abs(theta) <= fov / 2.0f + float pitch = -fov * (stacksRatio - 0.5f); + for (int j = 0; j < gridSize; j++) { + float slicesRatio = (float)j / (float)(gridSize - 1); // First slice is 0.0f, last slice is 1.0f + // abs(phi) <= fov * aspectRatio / 2.0f + float yaw = -fov * aspectRatio * (slicesRatio - 0.5f); + int vertex = i * gridSize + j; + int posOffset = vertex * 3; + int texOffset = vertex * 2; + vec3 pos = getPoint(yaw, pitch); + _pos_data[posOffset] = pos.x; + _pos_data[posOffset + 1] = pos.y; + _pos_data[posOffset + 2] = pos.z; + _tex_data[texOffset] = slicesRatio; + _tex_data[texOffset + 1] = stacksRatio; + } + } // done with vertices + + int rowLen = gridSize; + + // gridsize now refers to the triangles, not the vertices, so reduce by one + // or die by fencepost error http://en.wikipedia.org/wiki/Off-by-one_error + --gridSize; + int quads = gridSize * gridSize; + for (int t = 0; t < quads; ++t) { + int x = + ((t & 0x0001) >> 0) | + ((t & 0x0004) >> 1) | + ((t & 0x0010) >> 2) | + ((t & 0x0040) >> 3) | + ((t & 0x0100) >> 4) | + ((t & 0x0400) >> 5) | + ((t & 0x1000) >> 6) | + ((t & 0x4000) >> 7); + int y = + ((t & 0x0002) >> 1) | + ((t & 0x0008) >> 2) | + ((t & 0x0020) >> 3) | + ((t & 0x0080) >> 4) | + ((t & 0x0200) >> 5) | + ((t & 0x0800) >> 6) | + ((t & 0x2000) >> 7) | + ((t & 0x8000) >> 8); + int i = x * (rowLen) + y; + + _idx_data.push_back(i); + _idx_data.push_back(i + 1); + _idx_data.push_back(i + rowLen + 1); + + _idx_data.push_back(i + rowLen + 1); + _idx_data.push_back(i + rowLen); + _idx_data.push_back(i); + } + _prim_count = quads * 2; + } + + /// Returns the winding direction of faces + FaceOrientation FaceWinding(void) const { + return FaceOrientation::CCW; + } + + typedef GLuint(SphereSection::*VertexAttribFunc)(std::vector&) const; + + /// Makes the vertex positions and returns the number of values per vertex + template + GLuint Positions(std::vector& dest) const { + dest.clear(); + dest.insert(dest.begin(), _pos_data.begin(), _pos_data.end()); + return 3; + } + + /// Makes the vertex normals and returns the number of values per vertex + template + GLuint Normals(std::vector& dest) const { + dest.clear(); + return 3; + } + + /// Makes the vertex tangents and returns the number of values per vertex + template + GLuint Tangents(std::vector& dest) const { + dest.clear(); + return 3; + } + + /// Makes the vertex bi-tangents and returns the number of values per vertex + template + GLuint Bitangents(std::vector& dest) const { + dest.clear(); + return 3; + } + + /// Makes the texture coordinates returns the number of values per vertex + template + GLuint TexCoordinates(std::vector& dest) const { + dest.clear(); + dest.insert(dest.begin(), _tex_data.begin(), _tex_data.end()); + return 2; + } + + typedef VertexAttribsInfo< + SphereSection, + std::tuple< + VertexPositionsTag, + VertexNormalsTag, + VertexTangentsTag, + VertexBitangentsTag, + VertexTexCoordinatesTag + > + > VertexAttribs; + + Spheref MakeBoundingSphere(void) const { + GLfloat min_x = _pos_data[3], max_x = _pos_data[3]; + GLfloat min_y = _pos_data[4], max_y = _pos_data[4]; + GLfloat min_z = _pos_data[5], max_z = _pos_data[5]; + for (std::size_t v = 0, vn = _pos_data.size() / 3; v != vn; ++v) { + GLfloat x = _pos_data[v * 3 + 0]; + GLfloat y = _pos_data[v * 3 + 1]; + GLfloat z = _pos_data[v * 3 + 2]; + + if (min_x > x) min_x = x; + if (min_y > y) min_y = y; + if (min_z > z) min_z = z; + if (max_x < x) max_x = x; + if (max_y < y) max_y = y; + if (max_z < z) max_z = z; + } + + Vec3f c( + (min_x + max_x) * 0.5f, + (min_y + max_y) * 0.5f, + (min_z + max_z) * 0.5f + ); + + return Spheref( + c.x(), c.y(), c.z(), + Distance(c, Vec3f(min_x, min_y, min_z)) + ); + } + + /// Queries the bounding sphere coordinates and dimensions + template + void BoundingSphere(oglplus::Sphere& bounding_sphere) const { + bounding_sphere = oglplus::Sphere(MakeBoundingSphere()); + } + + + /// Returns element indices that are used with the drawing instructions + const IndexArray & Indices(Default = Default()) const { + return _idx_data; + } + + /// Returns the instructions for rendering of faces + DrawingInstructions Instructions(PrimitiveType primitive) const { + DrawingInstructions instr = this->MakeInstructions(); + DrawOperation operation; + operation.method = DrawOperation::Method::DrawElements; + operation.mode = primitive; + operation.first = 0; + operation.count = _prim_count * 3; + operation.restart_index = DrawOperation::NoRestartIndex(); + operation.phase = 0; + this->AddInstruction(instr, operation); + return std::move(instr); + } + + /// Returns the instructions for rendering of faces + DrawingInstructions Instructions(Default = Default()) const { + return Instructions(PrimitiveType::Triangles); + } +}; + +ShapeWrapperPtr loadSphereSection(ProgramPtr program, float fov, float aspect, int slices, int stacks) { + using namespace oglplus; + return ShapeWrapperPtr( + new shapes::ShapeWrapper({ "Position", "TexCoord" }, SphereSection(fov, aspect, slices, stacks), *program) + ); +} diff --git a/libraries/shared/src/OglplusHelpers.h b/libraries/shared/src/OglplusHelpers.h new file mode 100644 index 0000000000..1a00c021f9 --- /dev/null +++ b/libraries/shared/src/OglplusHelpers.h @@ -0,0 +1,166 @@ +// +// Created by Bradley Austin Davis on 2015/05/26 +// 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 +// +#pragma once + +#include "GLMHelpers.h" + +#define OGLPLUS_USE_GLCOREARB_H 0 + +#if defined(__APPLE__) + +#define OGLPLUS_USE_GL3_H 1 + +#elif defined(WIN32) + +#define OGLPLUS_USE_GLEW 1 +#pragma warning(disable : 4068) + +#elif defined(ANDROID) + +#else + +#define OGLPLUS_USE_GLCOREARB_H 1 + +#endif + + + +#define OGLPLUS_USE_BOOST_CONFIG 1 +#define OGLPLUS_NO_SITE_CONFIG 1 +#define OGLPLUS_LOW_PROFILE 1 +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "NumericalConstants.h" + +using FramebufferPtr = std::shared_ptr; +using ShapeWrapperPtr = std::shared_ptr; +using BufferPtr = std::shared_ptr; +using VertexArrayPtr = std::shared_ptr; +using ProgramPtr = std::shared_ptr; +using Mat4Uniform = oglplus::Uniform; + +ProgramPtr loadDefaultShader(); +void compileProgram(ProgramPtr & result, const std::string& vs, const std::string& fs); +ShapeWrapperPtr loadPlane(ProgramPtr program, float aspect = 1.0f); +ShapeWrapperPtr loadSphereSection(ProgramPtr program, float fov = PI / 3.0f * 2.0f, float aspect = 16.0f / 9.0f, int slices = 32, int stacks = 32); + + +// A basic wrapper for constructing a framebuffer with a renderbuffer +// for the depth attachment and an undefined type for the color attachement +// This allows us to reuse the basic framebuffer code for both the Mirror +// FBO as well as the Oculus swap textures we will use to render the scene +// Though we don't really need depth at all for the mirror FBO, or even an +// FBO, but using one means I can just use a glBlitFramebuffer to get it onto +// the screen. +template < + typename C, + typename D +> +struct FramebufferWrapper { + uvec2 size; + oglplus::Framebuffer fbo; + C color; + D depth; + + FramebufferWrapper() {} + + virtual ~FramebufferWrapper() { + } + + virtual void Init(const uvec2 & size) { + this->size = size; + initColor(); + initDepth(); + initDone(); + } + + template + void Bound(F f) { + Bound(oglplus::Framebuffer::Target::Draw, f); + } + + template + void Bound(oglplus::Framebuffer::Target target , F f) { + fbo.Bind(target); + onBind(target); + f(); + onUnbind(target); + oglplus::DefaultFramebuffer().Bind(target); + } + + void Viewport() { + oglplus::Context::Viewport(size.x, size.y); + } + +protected: + virtual void onBind(oglplus::Framebuffer::Target target) {} + virtual void onUnbind(oglplus::Framebuffer::Target target) {} + + static GLenum toEnum(oglplus::Framebuffer::Target target) { + switch (target) { + case oglplus::Framebuffer::Target::Draw: + return GL_DRAW_FRAMEBUFFER; + case oglplus::Framebuffer::Target::Read: + return GL_READ_FRAMEBUFFER; + default: + Q_ASSERT(false); + return GL_FRAMEBUFFER; + } + } + + virtual void initDepth() {} + + virtual void initColor() {} + + virtual void initDone() = 0; +}; + +struct BasicFramebufferWrapper : public FramebufferWrapper { +protected: + virtual void initDepth() override { + using namespace oglplus; + Context::Bound(Renderbuffer::Target::Renderbuffer, depth) + .Storage( + PixelDataInternalFormat::DepthComponent, + size.x, size.y); + } + + virtual void initColor() override { + using namespace oglplus; + Context::Bound(oglplus::Texture::Target::_2D, color) + .MinFilter(TextureMinFilter::Linear) + .MagFilter(TextureMagFilter::Linear) + .WrapS(TextureWrap::ClampToEdge) + .WrapT(TextureWrap::ClampToEdge) + .Image2D( + 0, PixelDataInternalFormat::RGBA8, + size.x, size.y, + 0, PixelDataFormat::RGB, PixelDataType::UnsignedByte, nullptr + ); + } + + virtual void initDone() override { + using namespace oglplus; + static const Framebuffer::Target target = Framebuffer::Target::Draw; + Bound(target, [&] { + fbo.AttachTexture(target, FramebufferAttachment::Color, color, 0); + fbo.AttachRenderbuffer(target, FramebufferAttachment::Depth, depth); + fbo.Complete(target); + }); + } +}; + +using BasicFramebufferWrapperPtr = std::shared_ptr; \ No newline at end of file From b56fbd474456ef9959b638fbd4fdfbb2ecad243f Mon Sep 17 00:00:00 2001 From: Bradley Austin Davis Date: Sun, 7 Jun 2015 13:56:06 -0700 Subject: [PATCH 02/90] Working on SDK 0.6 --- interface/src/devices/OculusManager.cpp | 56 ++++++++++++++++--------- libraries/shared/src/OglplusHelpers.cpp | 3 ++ libraries/shared/src/OglplusHelpers.h | 4 +- 3 files changed, 42 insertions(+), 21 deletions(-) diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index 12b8abeb66..d6151200f8 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -269,9 +269,9 @@ void OculusManager::connect() { _sceneLayer.ColorTexture[0] = _swapFbo->color; _sceneLayer.ColorTexture[1] = nullptr; _sceneLayer.Viewport[0].Pos = { 0, 0 }; - _sceneLayer.Viewport[0].Size = { _swapFbo->size.x / 2, _swapFbo->size.y }; - _sceneLayer.Viewport[1].Pos = { _swapFbo->size.x / 2, 0 }; - _sceneLayer.Viewport[1].Size = { _swapFbo->size.x / 2, _swapFbo->size.y }; + _sceneLayer.Viewport[0].Size = _recommendedTexSize; + _sceneLayer.Viewport[1].Pos = { _recommendedTexSize.x, 0 }; + _sceneLayer.Viewport[1].Size = _recommendedTexSize; _sceneLayer.Header.Type = ovrLayerType_EyeFov; _sceneLayer.Header.Flags = ovrLayerFlag_TextureOriginAtBottomLeft; for_each_eye([&](ovrEyeType eye) { @@ -541,18 +541,6 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati timerActive = false; } #endif - - ovrTrackingState ts = ovrHmd_GetTrackingState(_ovrHmd, ovr_GetTimeInSeconds()); - glm::vec3 trackerPosition = toGlm(ts.HeadPose.ThePose.Position); - - if (_calibrationState != CALIBRATED) { - calibrate(trackerPosition, toGlm(ts.HeadPose.ThePose.Orientation)); - } - - trackerPosition = bodyOrientation * trackerPosition; - static ovrVector3f eyeOffsets[2] = { { 0, 0, 0 }, { 0, 0, 0 } }; - ovrPosef eyePoses[ovrEye_Count]; - ovrHmd_GetEyePoses(_ovrHmd, _frameIndex, eyeOffsets, eyePoses, nullptr); #ifndef Q_OS_WIN // FIXME: we need a better way of responding to the HSW. In particular @@ -570,6 +558,7 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati } } #endif + //beginFrameTiming must be called before display if (!_frameTimingActive) { @@ -592,12 +581,30 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati glMatrixMode(GL_MODELVIEW); glPushMatrix(); + + glm::quat orientation; + glm::vec3 trackerPosition; auto deviceSize = qApp->getDeviceSize(); #ifndef Q_OS_WIN ovrHmd_BeginFrame(_ovrHmd, _frameIndex); #endif + ovrTrackingState ts = ovrHmd_GetTrackingState(_ovrHmd, ovr_GetTimeInSeconds()); + ovrVector3f ovrHeadPosition = ts.HeadPose.ThePose.Position; + + trackerPosition = glm::vec3(ovrHeadPosition.x, ovrHeadPosition.y, ovrHeadPosition.z); + if (_calibrationState != CALIBRATED) { + ovrQuatf ovrHeadOrientation = ts.HeadPose.ThePose.Orientation; + orientation = glm::quat(ovrHeadOrientation.w, ovrHeadOrientation.x, ovrHeadOrientation.y, ovrHeadOrientation.z); + calibrate(trackerPosition, orientation); + } + + trackerPosition = bodyOrientation * trackerPosition; + static ovrVector3f eyeOffsets[2] = { { 0, 0, 0 }, { 0, 0, 0 } }; + ovrPosef eyePoses[ovrEye_Count]; + ovrHmd_GetEyePoses(_ovrHmd, _frameIndex, eyeOffsets, eyePoses, nullptr); + ovrHmd_BeginFrame(_ovrHmd, _frameIndex); static ovrPosef eyeRenderPose[ovrEye_Count]; //Render each eye into an fbo for_each_eye(_ovrHmd, [&](ovrEyeType eye){ @@ -610,7 +617,11 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati _lastEyeRendered = _activeEye = eye; eyeRenderPose[eye] = eyePoses[eye]; // Set the camera rotation for this eye - glm::quat orientation = toGlm(eyeRenderPose[eye].Orientation); + orientation.x = eyeRenderPose[eye].Orientation.x; + orientation.y = eyeRenderPose[eye].Orientation.y; + orientation.z = eyeRenderPose[eye].Orientation.z; + orientation.w = eyeRenderPose[eye].Orientation.w; + // Update the application camera with the latest HMD position whichCamera.setHmdPosition(trackerPosition); whichCamera.setHmdRotation(orientation); @@ -635,14 +646,18 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati glMatrixMode(GL_MODELVIEW); glLoadIdentity(); - const ovrRecti& vp = _eyeViewports[eye]; + ovrRecti & vp = _eyeViewports[eye]; + vp.Size.h = _recommendedTexSize.h * _offscreenRenderScale; + vp.Size.w = _recommendedTexSize.w * _offscreenRenderScale; glViewport(vp.Pos.x, vp.Pos.y, vp.Size.w, vp.Size.h); qApp->displaySide(*_camera, false, RenderArgs::MONO); - //qApp->getApplicationOverlay().displayOverlayTextureHmd(*_camera); + qApp->getApplicationOverlay().displayOve rlayTextureHmd(*_camera); }); _activeEye = ovrEye_Count; + glPopMatrix(); + gpu::FramebufferPointer finalFbo; //Bind the output texture from the glow shader. If glow effect is disabled, we just grab the texture if (Menu::getInstance()->isOptionChecked(MenuOption::EnableGlowEffect)) { @@ -656,9 +671,9 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati glMatrixMode(GL_PROJECTION); glPopMatrix(); - glMatrixMode(GL_MODELVIEW); - glPopMatrix(); + // restore our normal viewport + glViewport(0, 0, deviceSize.width(), deviceSize.height()); #ifdef Q_OS_WIN auto srcFboSize = finalFbo->getSize(); @@ -715,6 +730,7 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); glCanvas->swapBuffers(); #endif + // restore our normal viewport glViewport(0, 0, deviceSize.width(), deviceSize.height()); diff --git a/libraries/shared/src/OglplusHelpers.cpp b/libraries/shared/src/OglplusHelpers.cpp index 47e0773b5e..47f9778cac 100644 --- a/libraries/shared/src/OglplusHelpers.cpp +++ b/libraries/shared/src/OglplusHelpers.cpp @@ -1,3 +1,5 @@ +#ifdef Q_OS_WIN + // // Created by Bradley Austin Davis on 2015/05/29 // Copyright 2015 High Fidelity, Inc. @@ -320,3 +322,4 @@ ShapeWrapperPtr loadSphereSection(ProgramPtr program, float fov, float aspect, i new shapes::ShapeWrapper({ "Position", "TexCoord" }, SphereSection(fov, aspect, slices, stacks), *program) ); } +#endif \ No newline at end of file diff --git a/libraries/shared/src/OglplusHelpers.h b/libraries/shared/src/OglplusHelpers.h index 1a00c021f9..73d32c4079 100644 --- a/libraries/shared/src/OglplusHelpers.h +++ b/libraries/shared/src/OglplusHelpers.h @@ -5,6 +5,7 @@ // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#ifdef Q_OS_WIN #pragma once #include "GLMHelpers.h" @@ -163,4 +164,5 @@ protected: } }; -using BasicFramebufferWrapperPtr = std::shared_ptr; \ No newline at end of file +using BasicFramebufferWrapperPtr = std::shared_ptr; +#endif \ No newline at end of file From 4d8bc27ece9ad434c7a0d383a4c34efb69e8a7c1 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Wed, 3 Jun 2015 11:11:31 -0700 Subject: [PATCH 03/90] Rename Dialog.qml to DialogOld.qml --- interface/resources/qml/Browser.qml | 2 +- interface/resources/qml/InfoView.qml | 2 +- interface/resources/qml/LoginDialog.qml | 2 +- interface/resources/qml/MarketplaceDialog.qml | 2 +- interface/resources/qml/MessageDialog.qml | 2 +- interface/resources/qml/TestDialog.qml | 2 +- interface/resources/qml/controls/{Dialog.qml => DialogOld.qml} | 0 7 files changed, 6 insertions(+), 6 deletions(-) rename interface/resources/qml/controls/{Dialog.qml => DialogOld.qml} (100%) diff --git a/interface/resources/qml/Browser.qml b/interface/resources/qml/Browser.qml index 55a0a6a461..3de616e05b 100644 --- a/interface/resources/qml/Browser.qml +++ b/interface/resources/qml/Browser.qml @@ -4,7 +4,7 @@ import QtWebKit 3.0 import "controls" import "styles" -Dialog { +DialogOld { id: root HifiConstants { id: hifi } title: "Browser" diff --git a/interface/resources/qml/InfoView.qml b/interface/resources/qml/InfoView.qml index 6b49e6f0c7..e97ebdeaf3 100644 --- a/interface/resources/qml/InfoView.qml +++ b/interface/resources/qml/InfoView.qml @@ -5,7 +5,7 @@ import QtQuick.Controls.Styles 1.3 import QtWebKit 3.0 import "controls" -Dialog { +DialogOld { id: root width: 800 height: 800 diff --git a/interface/resources/qml/LoginDialog.qml b/interface/resources/qml/LoginDialog.qml index 5653dfc7a1..0c02c0af64 100644 --- a/interface/resources/qml/LoginDialog.qml +++ b/interface/resources/qml/LoginDialog.qml @@ -4,7 +4,7 @@ import QtQuick.Controls.Styles 1.3 import "controls" import "styles" -Dialog { +DialogOld { HifiConstants { id: hifi } title: "Login" objectName: "LoginDialog" diff --git a/interface/resources/qml/MarketplaceDialog.qml b/interface/resources/qml/MarketplaceDialog.qml index 58bb3e6183..4ad3c6515f 100644 --- a/interface/resources/qml/MarketplaceDialog.qml +++ b/interface/resources/qml/MarketplaceDialog.qml @@ -5,7 +5,7 @@ import QtQuick.Controls.Styles 1.3 import QtWebKit 3.0 import "controls" -Dialog { +DialogOld { title: "Test Dlg" id: testDialog objectName: "Browser" diff --git a/interface/resources/qml/MessageDialog.qml b/interface/resources/qml/MessageDialog.qml index dd410b8070..5c699e1f1f 100644 --- a/interface/resources/qml/MessageDialog.qml +++ b/interface/resources/qml/MessageDialog.qml @@ -5,7 +5,7 @@ import QtQuick.Dialogs 1.2 import "controls" import "styles" -Dialog { +DialogOld { id: root HifiConstants { id: hifi } property real spacing: hifi.layout.spacing diff --git a/interface/resources/qml/TestDialog.qml b/interface/resources/qml/TestDialog.qml index 15bd790c22..3ae61fa054 100644 --- a/interface/resources/qml/TestDialog.qml +++ b/interface/resources/qml/TestDialog.qml @@ -3,7 +3,7 @@ import QtQuick.Controls 1.2 import QtQuick.Controls.Styles 1.3 import "controls" -Dialog { +DialogOld { title: "Test Dialog" id: testDialog objectName: "TestDialog" diff --git a/interface/resources/qml/controls/Dialog.qml b/interface/resources/qml/controls/DialogOld.qml similarity index 100% rename from interface/resources/qml/controls/Dialog.qml rename to interface/resources/qml/controls/DialogOld.qml From 811c2507630ef3e8ade00bbf7e4cf7e4bd5ca577 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Wed, 3 Jun 2015 13:01:47 -0700 Subject: [PATCH 04/90] Refactor common new dialog functionality into new Dialog.qml --- interface/resources/qml/AddressBarDialog.qml | 62 ++++--------------- interface/resources/qml/ErrorDialog.qml | 50 ++------------- interface/resources/qml/controls/Dialog.qml | 65 ++++++++++++++++++++ 3 files changed, 82 insertions(+), 95 deletions(-) create mode 100644 interface/resources/qml/controls/Dialog.qml diff --git a/interface/resources/qml/AddressBarDialog.qml b/interface/resources/qml/AddressBarDialog.qml index 91e05d020d..b4f1b2b247 100644 --- a/interface/resources/qml/AddressBarDialog.qml +++ b/interface/resources/qml/AddressBarDialog.qml @@ -9,18 +9,16 @@ // import Hifi 1.0 -import QtQuick 2.3 -import QtQuick.Controls 1.2 +import QtQuick 2.4 import "controls" import "styles" -Item { +Dialog { id: root HifiConstants { id: hifi } objectName: "AddressBarDialog" - property int animationDuration: hifi.effects.fadeInDuration property bool destroyOnInvisible: false property real scale: 1.25 // Make this dialog a little larger than normal @@ -101,47 +99,16 @@ Item { } } - // The UI enables an object, rather than manipulating its visibility, so that we can do animations in both directions. - // Because visibility and enabled are booleans, they cannot be animated. So when enabled is changed, we modify a property - // that can be animated, like scale or opacity, and then when the target animation value is reached, we can modify the - // visibility. - enabled: false - opacity: 0.0 - onEnabledChanged: { - opacity = enabled ? 1.0 : 0.0 if (enabled) { addressLine.forceActiveFocus(); } } - Behavior on opacity { - // Animate opacity. - NumberAnimation { - duration: animationDuration - easing.type: Easing.OutCubic - } - } - - onOpacityChanged: { - // Once we're transparent, disable the dialog's visibility. - visible = (opacity != 0.0) - } - onVisibleChanged: { if (!visible) { - reset() - - // Some dialogs should be destroyed when they become invisible. - if (destroyOnInvisible) { - destroy() - } + addressLine.text = "" } - - } - - function reset() { - addressLine.text = "" } function toggleOrGo() { @@ -152,21 +119,18 @@ Item { } } - Keys.onEscapePressed: { - enabled = false - } - Keys.onPressed: { - switch(event.key) { - case Qt.Key_W: - if (event.modifiers == Qt.ControlModifier) { - event.accepted = true - enabled = false - } + switch (event.key) { + case Qt.Key_Escape: + case Qt.Key_Back: + enabled = false; + event.accepted = true + break + case Qt.Key_Enter: + case Qt.Key_Return: + toggleOrGo() + event.accepted = true break } } - - Keys.onReturnPressed: toggleOrGo() - Keys.onEnterPressed: toggleOrGo() } diff --git a/interface/resources/qml/ErrorDialog.qml b/interface/resources/qml/ErrorDialog.qml index c0f8132f14..c3639f5f3c 100644 --- a/interface/resources/qml/ErrorDialog.qml +++ b/interface/resources/qml/ErrorDialog.qml @@ -9,17 +9,14 @@ // import Hifi 1.0 as Hifi -import QtQuick 2.3 -import QtQuick.Controls 1.2 -import QtQuick.Dialogs 1.2 +import QtQuick 2.4 import "controls" import "styles" -Item { +Dialog { id: root HifiConstants { id: hifi } - property int animationDuration: hifi.effects.fadeInDuration property bool destroyOnInvisible: true Component.onCompleted: { @@ -69,7 +66,7 @@ Item { Text { id: messageText - font.pointSize: 10 + font.pixelSize: hifi.fonts.pixelSize * 0.6 font.weight: Font.Bold anchors { @@ -99,47 +96,8 @@ Item { } } - // The UI enables an object, rather than manipulating its visibility, so that we can do animations in both directions. - // Because visibility and enabled are booleans, they cannot be animated. So when enabled is changed, we modify a property - // that can be animated, like scale or opacity, and then when the target animation value is reached, we can modify the - // visibility. - enabled: false - opacity: 0.0 - - onEnabledChanged: { - opacity = enabled ? 1.0 : 0.0 - } - - Behavior on opacity { - // Animate opacity. - NumberAnimation { - duration: animationDuration - easing.type: Easing.OutCubic - } - } - - onOpacityChanged: { - // Once we're transparent, disable the dialog's visibility. - visible = (opacity != 0.0) - } - - onVisibleChanged: { - if (!visible) { - // Some dialogs should be destroyed when they become invisible. - if (destroyOnInvisible) { - destroy() - } - } - } - Keys.onPressed: { - if (event.modifiers === Qt.ControlModifier) - switch (event.key) { - case Qt.Key_W: - event.accepted = true - content.accept() - break - } else switch (event.key) { + switch (event.key) { case Qt.Key_Escape: case Qt.Key_Back: case Qt.Key_Enter: diff --git a/interface/resources/qml/controls/Dialog.qml b/interface/resources/qml/controls/Dialog.qml new file mode 100644 index 0000000000..63430bdae0 --- /dev/null +++ b/interface/resources/qml/controls/Dialog.qml @@ -0,0 +1,65 @@ +// +// Dialog.qml +// +// Created by David Rowe on 3 Jun 2015 +// 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 +// + +import Hifi 1.0 +import QtQuick 2.4 +import "../styles" + +Item { + id: root + + property int animationDuration: hifi.effects.fadeInDuration + + + // The UI enables an object, rather than manipulating its visibility, so that we can do animations in both directions. + // Because visibility and enabled are booleans, they cannot be animated. So when enabled is changed, we modify a property + // that can be animated, like scale or opacity, and then when the target animation value is reached, we can modify the + // visibility. + enabled: false + opacity: 0.0 + + onEnabledChanged: { + opacity = enabled ? 1.0 : 0.0 + } + + Behavior on opacity { + // Animate opacity. + NumberAnimation { + duration: animationDuration + easing.type: Easing.OutCubic + } + } + + onOpacityChanged: { + // Once we're transparent, disable the dialog's visibility. + visible = (opacity != 0.0) + } + + onVisibleChanged: { + if (!visible) { + // Some dialogs should be destroyed when they become invisible. + if (destroyOnInvisible) { + destroy() + } + } + } + + + Keys.onPressed: { + switch(event.key) { + case Qt.Key_W: + if (event.modifiers == Qt.ControlModifier) { + enabled = false + event.accepted = true + } + break + } + } +} From 511832c273172f36476fa7d806a3a1d82376bad1 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Thu, 4 Jun 2015 13:20:48 -0700 Subject: [PATCH 05/90] New login dialog background with circular and rectangular variations Developer menu item toggles between the two. --- interface/resources/images/login-circle.svg | 3 + interface/resources/images/login-close.svg | 55 ++++ .../resources/images/login-rectangle.svg | 3 + interface/resources/qml/ErrorDialog.qml | 5 +- interface/resources/qml/LoginDialog.qml | 253 ++++++------------ interface/src/Menu.cpp | 15 ++ interface/src/Menu.h | 2 + interface/src/ui/DialogsManager.cpp | 4 + interface/src/ui/DialogsManager.h | 4 + interface/src/ui/LoginDialog.cpp | 37 ++- interface/src/ui/LoginDialog.h | 11 + 11 files changed, 219 insertions(+), 173 deletions(-) create mode 100644 interface/resources/images/login-circle.svg create mode 100644 interface/resources/images/login-close.svg create mode 100644 interface/resources/images/login-rectangle.svg diff --git a/interface/resources/images/login-circle.svg b/interface/resources/images/login-circle.svg new file mode 100644 index 0000000000..8a98902e6b --- /dev/null +++ b/interface/resources/images/login-circle.svg @@ -0,0 +1,3 @@ + + +2015-06-02 19:43ZCanvas 1Login Circle diff --git a/interface/resources/images/login-close.svg b/interface/resources/images/login-close.svg new file mode 100644 index 0000000000..88ca90b96f --- /dev/null +++ b/interface/resources/images/login-close.svg @@ -0,0 +1,55 @@ + +image/svg+xml \ No newline at end of file diff --git a/interface/resources/images/login-rectangle.svg b/interface/resources/images/login-rectangle.svg new file mode 100644 index 0000000000..774baf8193 --- /dev/null +++ b/interface/resources/images/login-rectangle.svg @@ -0,0 +1,3 @@ + + +2015-06-02 19:42ZCanvas 1Login2 diff --git a/interface/resources/qml/ErrorDialog.qml b/interface/resources/qml/ErrorDialog.qml index c3639f5f3c..51befb12a7 100644 --- a/interface/resources/qml/ErrorDialog.qml +++ b/interface/resources/qml/ErrorDialog.qml @@ -8,7 +8,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -import Hifi 1.0 as Hifi +import Hifi 1.0 import QtQuick 2.4 import "controls" import "styles" @@ -35,7 +35,7 @@ Dialog { x: parent ? parent.width / 2 - width / 2 : 0 y: parent ? parent.height / 2 - height / 2 : 0 - Hifi.ErrorDialog { + ErrorDialog { id: content implicitWidth: box.width @@ -88,6 +88,7 @@ Dialog { } MouseArea { anchors.fill: parent + cursorShape: "PointingHandCursor" onClicked: { content.accept(); } diff --git a/interface/resources/qml/LoginDialog.qml b/interface/resources/qml/LoginDialog.qml index 0c02c0af64..6db56d21bf 100644 --- a/interface/resources/qml/LoginDialog.qml +++ b/interface/resources/qml/LoginDialog.qml @@ -1,198 +1,119 @@ +// +// LoginDialog.qml +// +// Created by David Rowe on 3 Jun 2015 +// 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 +// + import Hifi 1.0 -import QtQuick 2.3 -import QtQuick.Controls.Styles 1.3 +import QtQuick 2.4 +import QtQuick.Controls 1.3 // TODO: Needed? import "controls" import "styles" -DialogOld { +Dialog { + id: root HifiConstants { id: hifi } - title: "Login" + objectName: "LoginDialog" - height: 512 - width: 384 - onVisibleChanged: { - if (!visible) { - reset() - } - } + property bool destroyOnInvisible: false - onEnabledChanged: { - if (enabled) { - username.forceActiveFocus(); - } - } + implicitWidth: loginDialog.implicitWidth + implicitHeight: loginDialog.implicitHeight - function reset() { - username.text = "" - password.text = "" - loginDialog.statusText = "" + x: parent ? parent.width / 2 - width / 2 : 0 + y: parent ? parent.height / 2 - height / 2 : 0 + property int maximumX: parent ? parent.width - width : 0 + property int maximumY: parent ? parent.height - height : 0 + + function isCircular() { + return loginDialog.dialogFormat == "circular" } LoginDialog { id: loginDialog - anchors.fill: parent - anchors.margins: parent.margins - anchors.topMargin: parent.topMargin - Column { - anchors.topMargin: 8 - anchors.right: parent.right - anchors.rightMargin: 0 - anchors.left: parent.left - anchors.top: parent.top - spacing: 8 - Image { - height: 64 - anchors.horizontalCenter: parent.horizontalCenter - width: 64 - source: "../images/hifi-logo.svg" + implicitWidth: isCircular() ? circularBackground.width : rectangularBackground.width + implicitHeight: isCircular() ? circularBackground.height : rectangularBackground.height + + Image { + id: circularBackground + visible: isCircular() + + source: "../images/login-circle.svg" + width: 500 + height: 500 + } + + Image { + id: rectangularBackground + visible: !isCircular() + + source: "../images/login-rectangle.svg" + width: 400 + height: 400 + } + + Text { + id: closeText + visible: isCircular() + + text: "Close" + font.pixelSize: hifi.fonts.pixelSize * 0.8 + font.weight: Font.Bold + color: "#175d74" + + anchors { + horizontalCenter: circularBackground.horizontalCenter + bottom: circularBackground.bottom + bottomMargin: hifi.layout.spacing * 4 } - Border { - width: 304 - height: 64 - anchors.horizontalCenter: parent.horizontalCenter - TextInput { - id: username - anchors.fill: parent - helperText: "Username or Email" - anchors.margins: 8 - KeyNavigation.tab: password - KeyNavigation.backtab: password + MouseArea { + anchors.fill: parent + cursorShape: "PointingHandCursor" + onClicked: { + root.enabled = false } } - - Border { - width: 304 - height: 64 - anchors.horizontalCenter: parent.horizontalCenter - TextInput { - id: password - anchors.fill: parent - echoMode: TextInput.Password - helperText: "Password" - anchors.margins: 8 - KeyNavigation.tab: username - KeyNavigation.backtab: username - onFocusChanged: { - if (password.focus) { - password.selectAll() - } - } - } - } - - Text { - anchors.horizontalCenter: parent.horizontalCenter - textFormat: Text.StyledText - width: parent.width - height: 96 - wrapMode: Text.WordWrap - verticalAlignment: Text.AlignVCenter - horizontalAlignment: Text.AlignHCenter - text: loginDialog.statusText - } } - Column { - anchors.bottomMargin: 5 - anchors.right: parent.right - anchors.rightMargin: 0 - anchors.left: parent.left - anchors.bottom: parent.bottom + Image { + id: closeIcon + visible: !isCircular() - Rectangle { - width: 192 - height: 64 - anchors.horizontalCenter: parent.horizontalCenter - color: hifi.colors.hifiBlue - border.width: 0 - radius: 10 - - MouseArea { - anchors.bottom: parent.bottom - anchors.bottomMargin: 0 - anchors.top: parent.top - anchors.right: parent.right - anchors.left: parent.left - onClicked: { - loginDialog.login(username.text, password.text) - } - } - - Row { - anchors.centerIn: parent - anchors.verticalCenter: parent.verticalCenter - spacing: 8 - Image { - id: loginIcon - height: 32 - width: 32 - source: "../images/login.svg" - } - Text { - text: "Login" - color: "white" - width: 64 - height: parent.height - } - } + source: "../images/login-close.svg" + width: 20 + height: 20 + anchors { + top: rectangularBackground.top + right: rectangularBackground.right + topMargin: hifi.layout.spacing * 2 + rightMargin: hifi.layout.spacing * 2 } - Text { - width: parent.width - height: 24 - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - text:"Create Account" - font.pointSize: 12 - font.bold: true - color: hifi.colors.hifiBlue - - MouseArea { - anchors.fill: parent - onClicked: { - loginDialog.openUrl(loginDialog.rootUrl + "/signup") - } - } - } - - Text { - width: parent.width - height: 24 - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - font.pointSize: 12 - text: "Recover Password" - color: hifi.colors.hifiBlue - - MouseArea { - anchors.fill: parent - onClicked: { - loginDialog.openUrl(loginDialog.rootUrl + "/users/password/new") - } + MouseArea { + anchors.fill: parent + cursorShape: "PointingHandCursor" + onClicked: { + root.enabled = false } } } } + Keys.onPressed: { - switch(event.key) { - case Qt.Key_Enter: - case Qt.Key_Return: - if (username.activeFocus) { - event.accepted = true - password.forceActiveFocus() - } else if (password.activeFocus) { - event.accepted = true - if (username.text == "") { - username.forceActiveFocus() - } else { - loginDialog.login(username.text, password.text) - } - } - break; + switch (event.key) { + case Qt.Key_Escape: + case Qt.Key_Back: + enabled = false; + event.accepted = true + break } } } diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 6242318170..b2b9553ea5 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -571,6 +571,21 @@ Menu::Menu() { addCheckableActionToQMenuAndActionHash(physicsOptionsMenu, MenuOption::PhysicsShowOwned); addCheckableActionToQMenuAndActionHash(physicsOptionsMenu, MenuOption::PhysicsShowHulls); + MenuWrapper* loginDialogFormatMenu = developerMenu->addMenu("Login Dialog"); + { + QActionGroup* dialogMenuFormatGroup = new QActionGroup(loginDialogFormatMenu); + + QAction* circularLoginDialog = addCheckableActionToQMenuAndActionHash(loginDialogFormatMenu, + MenuOption::LoginDialogCircular, 0, false, + dialogsManager.data(), SLOT(updateLoginDialogFormat())); + dialogMenuFormatGroup->addAction(circularLoginDialog); + + QAction* rectangularLoginDialog = addCheckableActionToQMenuAndActionHash(loginDialogFormatMenu, + MenuOption::LoginDialogRectangular, 0, true, + dialogsManager.data(), SLOT(updateLoginDialogFormat())); + dialogMenuFormatGroup->addAction(rectangularLoginDialog); + } + MenuWrapper* helpMenu = addMenu("Help"); addActionToQMenuAndActionHash(helpMenu, MenuOption::EditEntitiesHelp, 0, qApp, SLOT(showEditEntitiesHelp())); diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 6107744abc..eb1bd94637 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -209,6 +209,8 @@ namespace MenuOption { const QString LoadRSSDKFile = "Load .rssdk file"; const QString LodTools = "LOD Tools"; const QString Login = "Login"; + const QString LoginDialogCircular = "Circular"; + const QString LoginDialogRectangular = "Rectangular"; const QString Log = "Log"; const QString LowVelocityFilter = "Low Velocity Filter"; const QString Mirror = "Mirror"; diff --git a/interface/src/ui/DialogsManager.cpp b/interface/src/ui/DialogsManager.cpp index 1170e3c3a6..705f55586c 100644 --- a/interface/src/ui/DialogsManager.cpp +++ b/interface/src/ui/DialogsManager.cpp @@ -50,6 +50,10 @@ void DialogsManager::showLoginDialog() { LoginDialog::show(); } +void DialogsManager::updateLoginDialogFormat() { + emit loginDialogFormatChanged(); +} + void DialogsManager::octreeStatsDetails() { if (!_octreeStatsDialog) { _octreeStatsDialog = new OctreeStatsDialog(qApp->getWindow(), qApp->getOcteeSceneStats()); diff --git a/interface/src/ui/DialogsManager.h b/interface/src/ui/DialogsManager.h index fc2dad072b..f7301f5444 100644 --- a/interface/src/ui/DialogsManager.h +++ b/interface/src/ui/DialogsManager.h @@ -47,11 +47,15 @@ public: QPointer getOctreeStatsDialog() const { return _octreeStatsDialog; } QPointer getPreferencesDialog() const { return _preferencesDialog; } +signals: + void loginDialogFormatChanged(); + public slots: void toggleAddressBar(); void toggleDiskCacheEditor(); void toggleLoginDialog(); void showLoginDialog(); + void updateLoginDialogFormat(); void octreeStatsDetails(); void cachesSizeDialog(); void editPreferences(); diff --git a/interface/src/ui/LoginDialog.cpp b/interface/src/ui/LoginDialog.cpp index b452f153f0..4ed338c7db 100644 --- a/interface/src/ui/LoginDialog.cpp +++ b/interface/src/ui/LoginDialog.cpp @@ -1,6 +1,6 @@ // -// // LoginDialog.cpp +// interface/src/ui // // Created by Bradley Austin Davis on 2015/04/14 // Copyright 2015 High Fidelity, Inc. @@ -8,20 +8,28 @@ // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // + #include "LoginDialog.h" -#include "DependencyManager.h" -#include "AccountManager.h" -#include "Menu.h" #include +#include "AccountManager.h" +#include "DependencyManager.h" +#include "Menu.h" + HIFI_QML_DEF(LoginDialog) -LoginDialog::LoginDialog(QQuickItem *parent) : OffscreenQmlDialog(parent), _rootUrl(NetworkingConstants::METAVERSE_SERVER_URL.toString()) { +LoginDialog::LoginDialog(QQuickItem *parent) : OffscreenQmlDialog(parent), + _dialogFormat("rectangular"), + _rootUrl(NetworkingConstants::METAVERSE_SERVER_URL.toString()) +{ connect(&AccountManager::getInstance(), &AccountManager::loginComplete, this, &LoginDialog::handleLoginCompleted); connect(&AccountManager::getInstance(), &AccountManager::loginFailed, this, &LoginDialog::handleLoginFailed); + + connect(DependencyManager::get().data(), &DialogsManager::loginDialogFormatChanged, + this, &LoginDialog::updateDialogFormat); } void LoginDialog::toggleAction() { @@ -51,6 +59,25 @@ void LoginDialog::handleLoginFailed() { setStatusText("Invalid username or password.< / font>"); } +void LoginDialog::setDialogFormat(const QString& dialogFormat) { + if (dialogFormat != _dialogFormat) { + _dialogFormat = dialogFormat; + emit dialogFormatChanged(); + } +} + +QString LoginDialog::dialogFormat() const { + return _dialogFormat; +} + +void LoginDialog::updateDialogFormat() { + if (Menu::getInstance()->isOptionChecked(MenuOption::LoginDialogCircular)) { + setDialogFormat("circular"); + } else { + setDialogFormat("rectangular"); + } +} + void LoginDialog::setStatusText(const QString& statusText) { if (statusText != _statusText) { _statusText = statusText; diff --git a/interface/src/ui/LoginDialog.h b/interface/src/ui/LoginDialog.h index e9ae0a1c16..5761914642 100644 --- a/interface/src/ui/LoginDialog.h +++ b/interface/src/ui/LoginDialog.h @@ -1,5 +1,6 @@ // // LoginDialog.h +// interface/src/ui // // Created by Bradley Austin Davis on 2015/04/14 // Copyright 2015 High Fidelity, Inc. @@ -9,9 +10,12 @@ // #pragma once + #ifndef hifi_LoginDialog_h #define hifi_LoginDialog_h +#include "DialogsManager.h" // Need before OffscreenQmlDialog.h in order to get gl.h and glew.h includes in correct order. + #include class LoginDialog : public OffscreenQmlDialog @@ -19,6 +23,7 @@ class LoginDialog : public OffscreenQmlDialog Q_OBJECT HIFI_QML_DECL + Q_PROPERTY(QString dialogFormat READ dialogFormat WRITE setDialogFormat NOTIFY dialogFormatChanged) Q_PROPERTY(QString statusText READ statusText WRITE setStatusText NOTIFY statusTextChanged) Q_PROPERTY(QString rootUrl READ rootUrl) @@ -27,12 +32,17 @@ public: LoginDialog(QQuickItem* parent = nullptr); + void setDialogFormat(const QString& dialogFormat); + QString dialogFormat() const; + void updateDialogFormat(); // protected? + void setStatusText(const QString& statusText); QString statusText() const; QString rootUrl() const; signals: + void dialogFormatChanged(); void statusTextChanged(); protected: @@ -42,6 +52,7 @@ protected: Q_INVOKABLE void login(const QString& username, const QString& password); Q_INVOKABLE void openUrl(const QString& url); private: + QString _dialogFormat; QString _statusText; const QString _rootUrl; }; From a2f262f6595bec5ebd342e8355355237a67654a1 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Thu, 4 Jun 2015 18:48:21 -0700 Subject: [PATCH 06/90] Add basic username, password, login, and error functionality and styling --- interface/resources/qml/LoginDialog.qml | 180 +++++++++++++++++++----- interface/src/ui/LoginDialog.cpp | 4 +- 2 files changed, 148 insertions(+), 36 deletions(-) diff --git a/interface/resources/qml/LoginDialog.qml b/interface/resources/qml/LoginDialog.qml index 6db56d21bf..75adc30a1c 100644 --- a/interface/resources/qml/LoginDialog.qml +++ b/interface/resources/qml/LoginDialog.qml @@ -10,7 +10,6 @@ import Hifi 1.0 import QtQuick 2.4 -import QtQuick.Controls 1.3 // TODO: Needed? import "controls" import "styles" @@ -40,39 +39,148 @@ Dialog { implicitWidth: isCircular() ? circularBackground.width : rectangularBackground.width implicitHeight: isCircular() ? circularBackground.height : rectangularBackground.height + property int inputWidth: 500 + property int inputHeight: 60 + property int inputSpacing: isCircular() ? 24 : 16 + property int borderWidth: 30 + property int closeMargin: 16 + Image { id: circularBackground visible: isCircular() - source: "../images/login-circle.svg" - width: 500 - height: 500 + width: loginDialog.inputWidth * 1.2 + height: width } Image { id: rectangularBackground visible: !isCircular() - source: "../images/login-rectangle.svg" - width: 400 - height: 400 + width: loginDialog.inputWidth + loginDialog.borderWidth * 2 + height: loginDialog.inputHeight * 6 + } + + Image { + id: closeIcon + visible: !isCircular() + source: "../images/login-close.svg" + width: 20 + height: 20 + anchors { + top: rectangularBackground.top + right: rectangularBackground.right + topMargin: loginDialog.closeMargin + rightMargin: loginDialog.closeMargin + } + + MouseArea { + anchors.fill: parent + cursorShape: "PointingHandCursor" + onClicked: { + root.enabled = false + } + } + } + + Column { + id: mainContent + width: loginDialog.inputWidth + spacing: loginDialog.inputSpacing + anchors { + horizontalCenter: parent.horizontalCenter + verticalCenter: parent.verticalCenter + } + + Rectangle { + width: loginDialog.inputWidth + height: loginDialog.inputHeight + radius: height / 2 + color: "#ebebeb" + + TextInput { + id: username + anchors.fill: parent + anchors.leftMargin: loginDialog.inputHeight / 2 + + helperText: "username or email" + + KeyNavigation.tab: password + KeyNavigation.backtab: password + } + } + + Rectangle { + width: loginDialog.inputWidth + height: loginDialog.inputHeight + radius: height / 2 + color: "#ebebeb" + + TextInput { + id: password + anchors.fill: parent + anchors.leftMargin: loginDialog.inputHeight / 2 + + helperText: "password" + echoMode: TextInput.Password + + KeyNavigation.tab: username + KeyNavigation.backtab: username + onFocusChanged: { + if (password.focus) { + password.selectAll() + } + } + } + } + + Text { + id: messageText + width: loginDialog.inputWidth + height: loginDialog.inputHeight / 2 + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + + text: loginDialog.statusText + } + + Rectangle { + width: loginDialog.inputWidth + height: loginDialog.inputHeight + radius: height / 2 + color: "#353535" + + TextInput { + anchors.fill: parent + text: "Login" + color: "white" + horizontalAlignment: Text.AlignHCenter + } + + MouseArea { + anchors.fill: parent + cursorShape: "PointingHandCursor" + onClicked: { + loginDialog.login(username.text, password.text) + } + } + } } Text { id: closeText visible: isCircular() + anchors { + horizontalCenter: parent.horizontalCenter + top: mainContent.bottom + topMargin: loginDialog.inputSpacing + } text: "Close" font.pixelSize: hifi.fonts.pixelSize * 0.8 font.weight: Font.Bold color: "#175d74" - anchors { - horizontalCenter: circularBackground.horizontalCenter - bottom: circularBackground.bottom - bottomMargin: hifi.layout.spacing * 4 - } - MouseArea { anchors.fill: parent cursorShape: "PointingHandCursor" @@ -81,29 +189,19 @@ Dialog { } } } + } - Image { - id: closeIcon - visible: !isCircular() + onEnabledChanged: { + if (enabled) { + username.forceActiveFocus(); + } + } - source: "../images/login-close.svg" - - width: 20 - height: 20 - anchors { - top: rectangularBackground.top - right: rectangularBackground.right - topMargin: hifi.layout.spacing * 2 - rightMargin: hifi.layout.spacing * 2 - } - - MouseArea { - anchors.fill: parent - cursorShape: "PointingHandCursor" - onClicked: { - root.enabled = false - } - } + onVisibleChanged: { + if (!visible) { + username.text = "" + password.text = "" + loginDialog.statusText = "" } } @@ -114,6 +212,20 @@ Dialog { enabled = false; event.accepted = true break + case Qt.Key_Enter: + case Qt.Key_Return: + if (username.activeFocus) { + event.accepted = true + password.forceActiveFocus() + } else if (password.activeFocus) { + event.accepted = true + if (username.text == "") { + username.forceActiveFocus() + } else { + loginDialog.login(username.text, password.text) + } + } + break; } } } diff --git a/interface/src/ui/LoginDialog.cpp b/interface/src/ui/LoginDialog.cpp index 4ed338c7db..a326d6a6d1 100644 --- a/interface/src/ui/LoginDialog.cpp +++ b/interface/src/ui/LoginDialog.cpp @@ -56,7 +56,7 @@ void LoginDialog::handleLoginCompleted(const QUrl&) { } void LoginDialog::handleLoginFailed() { - setStatusText("Invalid username or password.< / font>"); + setStatusText("Invalid username or password"); } void LoginDialog::setDialogFormat(const QString& dialogFormat) { @@ -95,7 +95,7 @@ QString LoginDialog::rootUrl() const { void LoginDialog::login(const QString& username, const QString& password) { qDebug() << "Attempting to login " << username; - setStatusText("Authenticating..."); + setStatusText("Logging in..."); AccountManager::getInstance().requestAccessToken(username, password); } From 2a40bbb02b502a39d0fa2bac5d425698b1193386 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Thu, 4 Jun 2015 22:27:23 -0700 Subject: [PATCH 07/90] Add remainder of dialog content and polish look --- .../resources/images/hifi-logo-blackish.svg | 123 ++++++++++++++++++ interface/resources/images/login-close.svg | 4 +- interface/resources/images/login-password.svg | 58 +++++++++ interface/resources/images/login-username.svg | 51 ++++++++ interface/resources/qml/LoginDialog.qml | 104 ++++++++++++++- .../resources/qml/styles/HifiConstants.qml | 3 +- 6 files changed, 333 insertions(+), 10 deletions(-) create mode 100644 interface/resources/images/hifi-logo-blackish.svg create mode 100644 interface/resources/images/login-password.svg create mode 100644 interface/resources/images/login-username.svg diff --git a/interface/resources/images/hifi-logo-blackish.svg b/interface/resources/images/hifi-logo-blackish.svg new file mode 100644 index 0000000000..60bfb3d418 --- /dev/null +++ b/interface/resources/images/hifi-logo-blackish.svg @@ -0,0 +1,123 @@ + + + +image/svg+xml \ No newline at end of file diff --git a/interface/resources/images/login-close.svg b/interface/resources/images/login-close.svg index 88ca90b96f..2fb10c241b 100644 --- a/interface/resources/images/login-close.svg +++ b/interface/resources/images/login-close.svg @@ -35,7 +35,7 @@ id="namedview4139" showgrid="false" inkscape:zoom="4.8487496" - inkscape:cx="-11.452085" + inkscape:cx="-41.872299" inkscape:cy="37.53545" inkscape:window-x="77" inkscape:window-y="-8" @@ -48,7 +48,7 @@ d="M 38.400102,87.62655 C 28.705316,86.39839 21.084707,83.18102 13.982682,77.31765 5.5185024,70.329714 -0.09877759,60.244376 -1.7904936,48.998291 -2.1921426,46.328239 -2.2434696,39.677941 -1.8825126,37.07572 0.23131941,21.836625 9.4778634,8.9272213 23.005945,2.3281243 c 9.805646,-4.783264 20.444414,-5.902737 30.964952,-3.25830896 7.357662,1.849413 14.403738,5.75570696 19.976698,11.07495366 7.36697,7.031569 12.03213,16.084669 13.58981,26.37208 0.45133,2.980701 0.44981,9.518147 -0.003,12.481442 -0.72914,4.772737 -2.08456,9.199896 -4.04575,13.214497 -2.40852,4.930297 -4.94684,8.502038 -8.75077,12.313422 -6.78153,6.79482 -14.822805,10.95587 -24.504932,12.68035 -1.787127,0.3183 -3.134188,0.40875 -6.708441,0.45045 -2.459762,0.0287 -4.765789,0.0149 -5.124505,-0.0304 z m -3.02899,-27.869116 7.314939,-7.311007 7.360877,7.35692 7.360872,7.356917 4.983865,-4.982378 4.98386,-4.982378 -7.359111,-7.358686 -7.359105,-7.358687 7.359105,-7.358687 7.359111,-7.358686 -4.98387,-4.982383 -4.983864,-4.982384 -7.407456,7.393329 -7.407456,7.393328 -7.360652,-7.342464 -7.36065,-7.342467 -4.922357,4.916384 -4.922356,4.916381 7.300528,7.417269 7.300528,7.417267 -7.362706,7.362244 -7.362709,7.362244 4.890918,4.889465 c 2.690008,2.689205 4.974582,4.889463 5.076835,4.889463 0.102254,0 3.477639,-3.289951 7.500854,-7.311004 z" id="path4145" inkscape:connector-curvature="0" /> +image/svg+xml \ No newline at end of file diff --git a/interface/resources/images/login-username.svg b/interface/resources/images/login-username.svg new file mode 100644 index 0000000000..a40dd91cf7 --- /dev/null +++ b/interface/resources/images/login-username.svg @@ -0,0 +1,51 @@ + +image/svg+xml \ No newline at end of file diff --git a/interface/resources/qml/LoginDialog.qml b/interface/resources/qml/LoginDialog.qml index 75adc30a1c..f39eb7f5f2 100644 --- a/interface/resources/qml/LoginDialog.qml +++ b/interface/resources/qml/LoginDialog.qml @@ -58,7 +58,7 @@ Dialog { visible: !isCircular() source: "../images/login-rectangle.svg" width: loginDialog.inputWidth + loginDialog.borderWidth * 2 - height: loginDialog.inputHeight * 6 + height: loginDialog.inputHeight * 6 + loginDialog.closeMargin * 2 } Image { @@ -92,18 +92,39 @@ Dialog { verticalCenter: parent.verticalCenter } + Item { + // Offset content down a little + width: loginDialog.inputWidth + height: isCircular() ? loginDialog.inputHeight : loginDialog.closeMargin + } + Rectangle { width: loginDialog.inputWidth height: loginDialog.inputHeight radius: height / 2 color: "#ebebeb" + Image { + source: "../images/login-username.svg" + width: loginDialog.inputHeight * 0.65 + height: width + anchors { + verticalCenter: parent.verticalCenter + left: parent.left + leftMargin: loginDialog.inputHeight / 4 + } + } + TextInput { id: username - anchors.fill: parent - anchors.leftMargin: loginDialog.inputHeight / 2 + anchors { + fill: parent + leftMargin: loginDialog.inputHeight + rightMargin: loginDialog.inputHeight / 2 + } helperText: "username or email" + color: hifi.colors.text KeyNavigation.tab: password KeyNavigation.backtab: password @@ -116,13 +137,28 @@ Dialog { radius: height / 2 color: "#ebebeb" + Image { + source: "../images/login-password.svg" + width: loginDialog.inputHeight * 0.65 + height: width + anchors { + verticalCenter: parent.verticalCenter + left: parent.left + leftMargin: loginDialog.inputHeight / 4 + } + } + TextInput { id: password - anchors.fill: parent - anchors.leftMargin: loginDialog.inputHeight / 2 + anchors { + fill: parent + leftMargin: loginDialog.inputHeight + rightMargin: loginDialog.inputHeight / 2 + } helperText: "password" echoMode: TextInput.Password + color: hifi.colors.text KeyNavigation.tab: username KeyNavigation.backtab: username @@ -142,6 +178,7 @@ Dialog { verticalAlignment: Text.AlignVCenter text: loginDialog.statusText + color: "black" } Rectangle { @@ -165,6 +202,62 @@ Dialog { } } } + + Row { + anchors.horizontalCenter: parent.horizontalCenter + + Text { + text: "Forgot Password?" + font.pixelSize: hifi.fonts.pixelSize * 0.8 + font.underline: true + color: "#e0e0e0" + width: loginDialog.inputHeight * 4 + horizontalAlignment: Text.AlignRight + anchors.verticalCenter: parent.verticalCenter + + MouseArea { + anchors.fill: parent + cursorShape: "PointingHandCursor" + onClicked: { + loginDialog.openUrl(loginDialog.rootUrl + "/users/password/new") + } + } + } + + Item { + width: loginDialog.inputHeight + loginDialog.inputSpacing * 2 + height: loginDialog.inputHeight + + Image { + id: hifiIcon + source: "../images/hifi-logo-blackish.svg" + width: loginDialog.inputHeight + height: width + anchors { + horizontalCenter: parent.horizontalCenter + verticalCenter: parent.verticalCenter + } + } + } + + Text { + text: "Register" + font.pixelSize: hifi.fonts.pixelSize * 0.8 + font.underline: true + color: "#e0e0e0" + width: loginDialog.inputHeight * 4 + horizontalAlignment: Text.AlignLeft + anchors.verticalCenter: parent.verticalCenter + + MouseArea { + anchors.fill: parent + cursorShape: "PointingHandCursor" + onClicked: { + loginDialog.openUrl(loginDialog.rootUrl + "/signup") + } + } + } + } } Text { @@ -178,7 +271,6 @@ Dialog { text: "Close" font.pixelSize: hifi.fonts.pixelSize * 0.8 - font.weight: Font.Bold color: "#175d74" MouseArea { diff --git a/interface/resources/qml/styles/HifiConstants.qml b/interface/resources/qml/styles/HifiConstants.qml index fa556f2083..c232b993d1 100644 --- a/interface/resources/qml/styles/HifiConstants.qml +++ b/interface/resources/qml/styles/HifiConstants.qml @@ -13,10 +13,9 @@ Item { readonly property color hifiBlue: "#0e7077" readonly property color window: sysPalette.window readonly property color dialogBackground: sysPalette.window - //readonly property color dialogBackground: "#00000000" readonly property color inputBackground: "white" readonly property color background: sysPalette.dark - readonly property color text: sysPalette.text + readonly property color text: "#202020" readonly property color disabledText: "gray" readonly property color hintText: "gray" // A bit darker than sysPalette.dark so that it is visible on the DK2 readonly property color light: sysPalette.light From ed60e409ab527310e4b5ba83d2f915e825971e0f Mon Sep 17 00:00:00 2001 From: David Rowe Date: Fri, 5 Jun 2015 08:22:36 -0700 Subject: [PATCH 08/90] Make login dialog able to be dragged --- interface/resources/qml/LoginDialog.qml | 82 +++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/interface/resources/qml/LoginDialog.qml b/interface/resources/qml/LoginDialog.qml index f39eb7f5f2..55859cb83d 100644 --- a/interface/resources/qml/LoginDialog.qml +++ b/interface/resources/qml/LoginDialog.qml @@ -44,6 +44,9 @@ Dialog { property int inputSpacing: isCircular() ? 24 : 16 property int borderWidth: 30 property int closeMargin: 16 + property int maximumX: parent ? parent.width - width : 0 + property int maximumY: parent ? parent.height - height : 0 + property real tan30: 0.577 // tan(30°) Image { id: circularBackground @@ -51,6 +54,69 @@ Dialog { source: "../images/login-circle.svg" width: loginDialog.inputWidth * 1.2 height: width + + Item { + // Approximage circle with 3 rectangles that together contain the circle in a hexagon. + anchors.fill: parent + + MouseArea { + width: parent.width + height: parent.width * loginDialog.tan30 + anchors { + horizontalCenter: parent.horizontalCenter + verticalCenter: parent.verticalCenter + } + drag { + target: root + minimumX: -loginDialog.borderWidth + minimumY: -loginDialog.borderWidth + maximumX: root.parent ? root.maximumX + loginDialog.borderWidth : 0 + maximumY: root.parent ? root.maximumY + loginDialog.borderWidth : 0 + } + } + + MouseArea { + width: parent.width + height: parent.width * loginDialog.tan30 + anchors { + horizontalCenter: parent.horizontalCenter + verticalCenter: parent.verticalCenter + } + transform: Rotation { + origin.x: width / 2 + origin.y: width * loginDialog.tan30 / 2 + angle: -60 + } + drag { + target: root + minimumX: -loginDialog.borderWidth + minimumY: -loginDialog.borderWidth + maximumX: root.parent ? root.maximumX + loginDialog.borderWidth : 0 + maximumY: root.parent ? root.maximumY + loginDialog.borderWidth : 0 + } + } + + MouseArea { + width: parent.width + height: parent.width * loginDialog.tan30 + anchors { + horizontalCenter: parent.horizontalCenter + verticalCenter: parent.verticalCenter + } + transform: Rotation { + origin.x: width / 2 + origin.y: width * loginDialog.tan30 / 2 + angle: 60 + } + drag { + target: root + minimumX: -loginDialog.borderWidth + minimumY: -loginDialog.borderWidth + maximumX: root.parent ? root.maximumX + loginDialog.borderWidth : 0 + maximumY: root.parent ? root.maximumY + loginDialog.borderWidth : 0 + } + } + } } Image { @@ -59,6 +125,22 @@ Dialog { source: "../images/login-rectangle.svg" width: loginDialog.inputWidth + loginDialog.borderWidth * 2 height: loginDialog.inputHeight * 6 + loginDialog.closeMargin * 2 + + MouseArea { + width: parent.width + height: parent.height + anchors { + horizontalCenter: parent.horizontalCenter + verticalCenter: parent.verticalCenter + } + drag { + target: root + minimumX: 0 + minimumY: 0 + maximumX: root.parent ? root.maximumX : 0 + maximumY: root.parent ? root.maximumY : 0 + } + } } Image { From 162395e7fe8e62566f27408eb280ed2be2cb4df6 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Fri, 5 Jun 2015 08:42:33 -0700 Subject: [PATCH 09/90] Make login password and register links work --- interface/src/ui/LoginDialog.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/interface/src/ui/LoginDialog.cpp b/interface/src/ui/LoginDialog.cpp index a326d6a6d1..3de8b5adf1 100644 --- a/interface/src/ui/LoginDialog.cpp +++ b/interface/src/ui/LoginDialog.cpp @@ -101,4 +101,5 @@ void LoginDialog::login(const QString& username, const QString& password) { void LoginDialog::openUrl(const QString& url) { qDebug() << url; + Application::getInstance()->openUrl(url); } From 7819b5b5c3c1f425647651f0d74010cc86d598bd Mon Sep 17 00:00:00 2001 From: David Rowe Date: Fri, 5 Jun 2015 09:02:35 -0700 Subject: [PATCH 10/90] Fix setting focus at start-up when not logged in --- interface/resources/qml/LoginDialog.qml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/interface/resources/qml/LoginDialog.qml b/interface/resources/qml/LoginDialog.qml index 55859cb83d..55a4fec34c 100644 --- a/interface/resources/qml/LoginDialog.qml +++ b/interface/resources/qml/LoginDialog.qml @@ -365,9 +365,10 @@ Dialog { } } - onEnabledChanged: { - if (enabled) { - username.forceActiveFocus(); + onOpacityChanged: { + // Set focus once animation is completed so that focus is set at start-up when not logged in + if (opacity == 1.0) { + username.forceActiveFocus() } } From 263f3053497a7b8126296338a890de3540bf0895 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Fri, 5 Jun 2015 09:03:46 -0700 Subject: [PATCH 11/90] White error text instead of black --- interface/resources/qml/LoginDialog.qml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/resources/qml/LoginDialog.qml b/interface/resources/qml/LoginDialog.qml index 55a4fec34c..b1d488e0cf 100644 --- a/interface/resources/qml/LoginDialog.qml +++ b/interface/resources/qml/LoginDialog.qml @@ -260,7 +260,7 @@ Dialog { verticalAlignment: Text.AlignVCenter text: loginDialog.statusText - color: "black" + color: "white" } Rectangle { From 34209fa671fa823e0f7bf837085e1f2198a22d83 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Fri, 5 Jun 2015 09:07:07 -0700 Subject: [PATCH 12/90] Remove unnecessary semicolons --- interface/resources/qml/AddressBarDialog.qml | 4 ++-- interface/resources/qml/ErrorDialog.qml | 4 ++-- interface/resources/qml/LoginDialog.qml | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/interface/resources/qml/AddressBarDialog.qml b/interface/resources/qml/AddressBarDialog.qml index b4f1b2b247..7fa6bb3481 100644 --- a/interface/resources/qml/AddressBarDialog.qml +++ b/interface/resources/qml/AddressBarDialog.qml @@ -101,7 +101,7 @@ Dialog { onEnabledChanged: { if (enabled) { - addressLine.forceActiveFocus(); + addressLine.forceActiveFocus() } } @@ -123,7 +123,7 @@ Dialog { switch (event.key) { case Qt.Key_Escape: case Qt.Key_Back: - enabled = false; + enabled = false event.accepted = true break case Qt.Key_Enter: diff --git a/interface/resources/qml/ErrorDialog.qml b/interface/resources/qml/ErrorDialog.qml index 51befb12a7..1757aee376 100644 --- a/interface/resources/qml/ErrorDialog.qml +++ b/interface/resources/qml/ErrorDialog.qml @@ -25,7 +25,7 @@ Dialog { onParentChanged: { if (visible && enabled) { - forceActiveFocus(); + forceActiveFocus() } } @@ -90,7 +90,7 @@ Dialog { anchors.fill: parent cursorShape: "PointingHandCursor" onClicked: { - content.accept(); + content.accept() } } } diff --git a/interface/resources/qml/LoginDialog.qml b/interface/resources/qml/LoginDialog.qml index b1d488e0cf..ba8c24f3a7 100644 --- a/interface/resources/qml/LoginDialog.qml +++ b/interface/resources/qml/LoginDialog.qml @@ -384,7 +384,7 @@ Dialog { switch (event.key) { case Qt.Key_Escape: case Qt.Key_Back: - enabled = false; + enabled = false event.accepted = true break case Qt.Key_Enter: @@ -400,7 +400,7 @@ Dialog { loginDialog.login(username.text, password.text) } } - break; + break } } } From 8682cfc14a88e3b13f4c048955e8ba8702a80103 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Fri, 5 Jun 2015 09:47:34 -0700 Subject: [PATCH 13/90] Change login password recovery link text --- interface/resources/qml/LoginDialog.qml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/resources/qml/LoginDialog.qml b/interface/resources/qml/LoginDialog.qml index ba8c24f3a7..d75f692827 100644 --- a/interface/resources/qml/LoginDialog.qml +++ b/interface/resources/qml/LoginDialog.qml @@ -289,7 +289,7 @@ Dialog { anchors.horizontalCenter: parent.horizontalCenter Text { - text: "Forgot Password?" + text: "Password?" font.pixelSize: hifi.fonts.pixelSize * 0.8 font.underline: true color: "#e0e0e0" From 84ab8277dfa9001fae5c7bbb0adcdbb591c19b0c Mon Sep 17 00:00:00 2001 From: David Rowe Date: Fri, 5 Jun 2015 12:57:40 -0700 Subject: [PATCH 14/90] Add spinner in place of "Logging in..." --- interface/resources/qml/LoginDialog.qml | 69 ++++++++++++++++++++++--- 1 file changed, 63 insertions(+), 6 deletions(-) diff --git a/interface/resources/qml/LoginDialog.qml b/interface/resources/qml/LoginDialog.qml index d75f692827..0fa6ff43cc 100644 --- a/interface/resources/qml/LoginDialog.qml +++ b/interface/resources/qml/LoginDialog.qml @@ -252,15 +252,72 @@ Dialog { } } - Text { - id: messageText + Item { width: loginDialog.inputWidth height: loginDialog.inputHeight / 2 - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - text: loginDialog.statusText - color: "white" + Text { + id: messageText + + visible: loginDialog.statusText != "" && loginDialog.statusText != "Logging in..." + + width: loginDialog.inputWidth + height: loginDialog.inputHeight / 2 + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + + text: loginDialog.statusText + color: "white" + } + + Row { + id: messageSpinner + + visible: loginDialog.statusText == "Logging in..." + onVisibleChanged: visible ? messageSpinnerAnimation.restart() : messageSpinnerAnimation.stop() + + spacing: 24 + anchors { + verticalCenter: parent.verticalCenter + horizontalCenter: parent.horizontalCenter + } + + Rectangle { + id: spinner1 + width: 10 + height: 10 + color: "#ebebeb" + opacity: 0.05 + } + + Rectangle { + id: spinner2 + width: 10 + height: 10 + color: "#ebebeb" + opacity: 0.05 + } + + Rectangle { + id: spinner3 + width: 10 + height: 10 + color: "#ebebeb" + opacity: 0.05 + } + + SequentialAnimation { + id: messageSpinnerAnimation + running: messageSpinner.visible + loops: Animation.Infinite + NumberAnimation { target: spinner1; property: "opacity"; to: 1.0; duration: 1000 } + NumberAnimation { target: spinner2; property: "opacity"; to: 1.0; duration: 1000 } + NumberAnimation { target: spinner3; property: "opacity"; to: 1.0; duration: 1000 } + NumberAnimation { target: spinner1; property: "opacity"; to: 0.05; duration: 0 } + NumberAnimation { target: spinner2; property: "opacity"; to: 0.05; duration: 0 } + NumberAnimation { target: spinner3; property: "opacity"; to: 0.05; duration: 0 } + } + } } Rectangle { From dbe57696d827318b2029be4d32b3dfef56050f83 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Fri, 5 Jun 2015 13:15:18 -0700 Subject: [PATCH 15/90] Replace login background SVGs with QML rectangles --- interface/resources/images/login-circle.svg | 3 --- interface/resources/images/login-rectangle.svg | 3 --- interface/resources/qml/LoginDialog.qml | 14 ++++++++++---- 3 files changed, 10 insertions(+), 10 deletions(-) delete mode 100644 interface/resources/images/login-circle.svg delete mode 100644 interface/resources/images/login-rectangle.svg diff --git a/interface/resources/images/login-circle.svg b/interface/resources/images/login-circle.svg deleted file mode 100644 index 8a98902e6b..0000000000 --- a/interface/resources/images/login-circle.svg +++ /dev/null @@ -1,3 +0,0 @@ - - -2015-06-02 19:43ZCanvas 1Login Circle diff --git a/interface/resources/images/login-rectangle.svg b/interface/resources/images/login-rectangle.svg deleted file mode 100644 index 774baf8193..0000000000 --- a/interface/resources/images/login-rectangle.svg +++ /dev/null @@ -1,3 +0,0 @@ - - -2015-06-02 19:42ZCanvas 1Login2 diff --git a/interface/resources/qml/LoginDialog.qml b/interface/resources/qml/LoginDialog.qml index 0fa6ff43cc..aa6cbb162d 100644 --- a/interface/resources/qml/LoginDialog.qml +++ b/interface/resources/qml/LoginDialog.qml @@ -48,12 +48,15 @@ Dialog { property int maximumY: parent ? parent.height - height : 0 property real tan30: 0.577 // tan(30°) - Image { + Rectangle { id: circularBackground visible: isCircular() - source: "../images/login-circle.svg" width: loginDialog.inputWidth * 1.2 height: width + radius: width / 2 + + color: "#2c86b1" + opacity: 0.85 Item { // Approximage circle with 3 rectangles that together contain the circle in a hexagon. @@ -119,12 +122,15 @@ Dialog { } } - Image { + Rectangle { id: rectangularBackground visible: !isCircular() - source: "../images/login-rectangle.svg" width: loginDialog.inputWidth + loginDialog.borderWidth * 2 height: loginDialog.inputHeight * 6 + loginDialog.closeMargin * 2 + radius: loginDialog.closeMargin * 2 + + color: "#2c86b1" + opacity: 0.85 MouseArea { width: parent.width From b1f2ffd00869521bb881b4fcc75c32616768cbfa Mon Sep 17 00:00:00 2001 From: David Rowe Date: Fri, 5 Jun 2015 13:23:06 -0700 Subject: [PATCH 16/90] Code review and tidying --- interface/resources/qml/ErrorDialog.qml | 2 -- interface/resources/qml/LoginDialog.qml | 10 +++++----- interface/resources/qml/controls/Dialog.qml | 4 ++-- 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/interface/resources/qml/ErrorDialog.qml b/interface/resources/qml/ErrorDialog.qml index 1757aee376..26b18f4ffd 100644 --- a/interface/resources/qml/ErrorDialog.qml +++ b/interface/resources/qml/ErrorDialog.qml @@ -17,8 +17,6 @@ Dialog { id: root HifiConstants { id: hifi } - property bool destroyOnInvisible: true - Component.onCompleted: { enabled = true } diff --git a/interface/resources/qml/LoginDialog.qml b/interface/resources/qml/LoginDialog.qml index aa6cbb162d..3291fed0d0 100644 --- a/interface/resources/qml/LoginDialog.qml +++ b/interface/resources/qml/LoginDialog.qml @@ -39,14 +39,14 @@ Dialog { implicitWidth: isCircular() ? circularBackground.width : rectangularBackground.width implicitHeight: isCircular() ? circularBackground.height : rectangularBackground.height - property int inputWidth: 500 - property int inputHeight: 60 + readonly property int inputWidth: 500 + readonly property int inputHeight: 60 + readonly property int borderWidth: 30 + readonly property int closeMargin: 16 + readonly property real tan30: 0.577 // tan(30°) property int inputSpacing: isCircular() ? 24 : 16 - property int borderWidth: 30 - property int closeMargin: 16 property int maximumX: parent ? parent.width - width : 0 property int maximumY: parent ? parent.height - height : 0 - property real tan30: 0.577 // tan(30°) Rectangle { id: circularBackground diff --git a/interface/resources/qml/controls/Dialog.qml b/interface/resources/qml/controls/Dialog.qml index 63430bdae0..3cada90c3e 100644 --- a/interface/resources/qml/controls/Dialog.qml +++ b/interface/resources/qml/controls/Dialog.qml @@ -15,7 +15,7 @@ import "../styles" Item { id: root - property int animationDuration: hifi.effects.fadeInDuration + property bool destroyOnInvisible: true // The UI enables an object, rather than manipulating its visibility, so that we can do animations in both directions. @@ -32,7 +32,7 @@ Item { Behavior on opacity { // Animate opacity. NumberAnimation { - duration: animationDuration + duration: hifi.effects.fadeInDuration easing.type: Easing.OutCubic } } From 36312e7bb44d8945bac539031f55741049c06c54 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Fri, 5 Jun 2015 15:37:25 -0700 Subject: [PATCH 17/90] Remove circular login dialog variation --- interface/resources/qml/LoginDialog.qml | 116 ++---------------------- interface/src/Menu.cpp | 15 --- interface/src/Menu.h | 2 - interface/src/ui/DialogsManager.cpp | 4 - interface/src/ui/DialogsManager.h | 4 - interface/src/ui/LoginDialog.cpp | 26 +----- interface/src/ui/LoginDialog.h | 9 -- 7 files changed, 9 insertions(+), 167 deletions(-) diff --git a/interface/resources/qml/LoginDialog.qml b/interface/resources/qml/LoginDialog.qml index 3291fed0d0..e552532cbd 100644 --- a/interface/resources/qml/LoginDialog.qml +++ b/interface/resources/qml/LoginDialog.qml @@ -29,102 +29,23 @@ Dialog { property int maximumX: parent ? parent.width - width : 0 property int maximumY: parent ? parent.height - height : 0 - function isCircular() { - return loginDialog.dialogFormat == "circular" - } - LoginDialog { id: loginDialog - implicitWidth: isCircular() ? circularBackground.width : rectangularBackground.width - implicitHeight: isCircular() ? circularBackground.height : rectangularBackground.height + implicitWidth: backgroundRectangle.width + implicitHeight: backgroundRectangle.height readonly property int inputWidth: 500 readonly property int inputHeight: 60 readonly property int borderWidth: 30 readonly property int closeMargin: 16 readonly property real tan30: 0.577 // tan(30°) - property int inputSpacing: isCircular() ? 24 : 16 + readonly property int inputSpacing: 16 property int maximumX: parent ? parent.width - width : 0 property int maximumY: parent ? parent.height - height : 0 Rectangle { - id: circularBackground - visible: isCircular() - width: loginDialog.inputWidth * 1.2 - height: width - radius: width / 2 - - color: "#2c86b1" - opacity: 0.85 - - Item { - // Approximage circle with 3 rectangles that together contain the circle in a hexagon. - anchors.fill: parent - - MouseArea { - width: parent.width - height: parent.width * loginDialog.tan30 - anchors { - horizontalCenter: parent.horizontalCenter - verticalCenter: parent.verticalCenter - } - drag { - target: root - minimumX: -loginDialog.borderWidth - minimumY: -loginDialog.borderWidth - maximumX: root.parent ? root.maximumX + loginDialog.borderWidth : 0 - maximumY: root.parent ? root.maximumY + loginDialog.borderWidth : 0 - } - } - - MouseArea { - width: parent.width - height: parent.width * loginDialog.tan30 - anchors { - horizontalCenter: parent.horizontalCenter - verticalCenter: parent.verticalCenter - } - transform: Rotation { - origin.x: width / 2 - origin.y: width * loginDialog.tan30 / 2 - angle: -60 - } - drag { - target: root - minimumX: -loginDialog.borderWidth - minimumY: -loginDialog.borderWidth - maximumX: root.parent ? root.maximumX + loginDialog.borderWidth : 0 - maximumY: root.parent ? root.maximumY + loginDialog.borderWidth : 0 - } - } - - MouseArea { - width: parent.width - height: parent.width * loginDialog.tan30 - anchors { - horizontalCenter: parent.horizontalCenter - verticalCenter: parent.verticalCenter - } - transform: Rotation { - origin.x: width / 2 - origin.y: width * loginDialog.tan30 / 2 - angle: 60 - } - drag { - target: root - minimumX: -loginDialog.borderWidth - minimumY: -loginDialog.borderWidth - maximumX: root.parent ? root.maximumX + loginDialog.borderWidth : 0 - maximumY: root.parent ? root.maximumY + loginDialog.borderWidth : 0 - } - } - } - } - - Rectangle { - id: rectangularBackground - visible: !isCircular() + id: backgroundRectangle width: loginDialog.inputWidth + loginDialog.borderWidth * 2 height: loginDialog.inputHeight * 6 + loginDialog.closeMargin * 2 radius: loginDialog.closeMargin * 2 @@ -151,13 +72,12 @@ Dialog { Image { id: closeIcon - visible: !isCircular() source: "../images/login-close.svg" width: 20 height: 20 anchors { - top: rectangularBackground.top - right: rectangularBackground.right + top: backgroundRectangle.top + right: backgroundRectangle.right topMargin: loginDialog.closeMargin rightMargin: loginDialog.closeMargin } @@ -183,7 +103,7 @@ Dialog { Item { // Offset content down a little width: loginDialog.inputWidth - height: isCircular() ? loginDialog.inputHeight : loginDialog.closeMargin + height: loginDialog.closeMargin } Rectangle { @@ -404,28 +324,6 @@ Dialog { } } } - - Text { - id: closeText - visible: isCircular() - anchors { - horizontalCenter: parent.horizontalCenter - top: mainContent.bottom - topMargin: loginDialog.inputSpacing - } - - text: "Close" - font.pixelSize: hifi.fonts.pixelSize * 0.8 - color: "#175d74" - - MouseArea { - anchors.fill: parent - cursorShape: "PointingHandCursor" - onClicked: { - root.enabled = false - } - } - } } onOpacityChanged: { diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index b2b9553ea5..6242318170 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -571,21 +571,6 @@ Menu::Menu() { addCheckableActionToQMenuAndActionHash(physicsOptionsMenu, MenuOption::PhysicsShowOwned); addCheckableActionToQMenuAndActionHash(physicsOptionsMenu, MenuOption::PhysicsShowHulls); - MenuWrapper* loginDialogFormatMenu = developerMenu->addMenu("Login Dialog"); - { - QActionGroup* dialogMenuFormatGroup = new QActionGroup(loginDialogFormatMenu); - - QAction* circularLoginDialog = addCheckableActionToQMenuAndActionHash(loginDialogFormatMenu, - MenuOption::LoginDialogCircular, 0, false, - dialogsManager.data(), SLOT(updateLoginDialogFormat())); - dialogMenuFormatGroup->addAction(circularLoginDialog); - - QAction* rectangularLoginDialog = addCheckableActionToQMenuAndActionHash(loginDialogFormatMenu, - MenuOption::LoginDialogRectangular, 0, true, - dialogsManager.data(), SLOT(updateLoginDialogFormat())); - dialogMenuFormatGroup->addAction(rectangularLoginDialog); - } - MenuWrapper* helpMenu = addMenu("Help"); addActionToQMenuAndActionHash(helpMenu, MenuOption::EditEntitiesHelp, 0, qApp, SLOT(showEditEntitiesHelp())); diff --git a/interface/src/Menu.h b/interface/src/Menu.h index eb1bd94637..6107744abc 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -209,8 +209,6 @@ namespace MenuOption { const QString LoadRSSDKFile = "Load .rssdk file"; const QString LodTools = "LOD Tools"; const QString Login = "Login"; - const QString LoginDialogCircular = "Circular"; - const QString LoginDialogRectangular = "Rectangular"; const QString Log = "Log"; const QString LowVelocityFilter = "Low Velocity Filter"; const QString Mirror = "Mirror"; diff --git a/interface/src/ui/DialogsManager.cpp b/interface/src/ui/DialogsManager.cpp index 705f55586c..1170e3c3a6 100644 --- a/interface/src/ui/DialogsManager.cpp +++ b/interface/src/ui/DialogsManager.cpp @@ -50,10 +50,6 @@ void DialogsManager::showLoginDialog() { LoginDialog::show(); } -void DialogsManager::updateLoginDialogFormat() { - emit loginDialogFormatChanged(); -} - void DialogsManager::octreeStatsDetails() { if (!_octreeStatsDialog) { _octreeStatsDialog = new OctreeStatsDialog(qApp->getWindow(), qApp->getOcteeSceneStats()); diff --git a/interface/src/ui/DialogsManager.h b/interface/src/ui/DialogsManager.h index f7301f5444..fc2dad072b 100644 --- a/interface/src/ui/DialogsManager.h +++ b/interface/src/ui/DialogsManager.h @@ -47,15 +47,11 @@ public: QPointer getOctreeStatsDialog() const { return _octreeStatsDialog; } QPointer getPreferencesDialog() const { return _preferencesDialog; } -signals: - void loginDialogFormatChanged(); - public slots: void toggleAddressBar(); void toggleDiskCacheEditor(); void toggleLoginDialog(); void showLoginDialog(); - void updateLoginDialogFormat(); void octreeStatsDetails(); void cachesSizeDialog(); void editPreferences(); diff --git a/interface/src/ui/LoginDialog.cpp b/interface/src/ui/LoginDialog.cpp index 3de8b5adf1..eb6f3c0607 100644 --- a/interface/src/ui/LoginDialog.cpp +++ b/interface/src/ui/LoginDialog.cpp @@ -12,6 +12,7 @@ #include "LoginDialog.h" #include +#include #include "AccountManager.h" #include "DependencyManager.h" @@ -20,16 +21,12 @@ HIFI_QML_DEF(LoginDialog) LoginDialog::LoginDialog(QQuickItem *parent) : OffscreenQmlDialog(parent), - _dialogFormat("rectangular"), _rootUrl(NetworkingConstants::METAVERSE_SERVER_URL.toString()) { connect(&AccountManager::getInstance(), &AccountManager::loginComplete, this, &LoginDialog::handleLoginCompleted); connect(&AccountManager::getInstance(), &AccountManager::loginFailed, this, &LoginDialog::handleLoginFailed); - - connect(DependencyManager::get().data(), &DialogsManager::loginDialogFormatChanged, - this, &LoginDialog::updateDialogFormat); } void LoginDialog::toggleAction() { @@ -59,25 +56,6 @@ void LoginDialog::handleLoginFailed() { setStatusText("Invalid username or password"); } -void LoginDialog::setDialogFormat(const QString& dialogFormat) { - if (dialogFormat != _dialogFormat) { - _dialogFormat = dialogFormat; - emit dialogFormatChanged(); - } -} - -QString LoginDialog::dialogFormat() const { - return _dialogFormat; -} - -void LoginDialog::updateDialogFormat() { - if (Menu::getInstance()->isOptionChecked(MenuOption::LoginDialogCircular)) { - setDialogFormat("circular"); - } else { - setDialogFormat("rectangular"); - } -} - void LoginDialog::setStatusText(const QString& statusText) { if (statusText != _statusText) { _statusText = statusText; @@ -101,5 +79,5 @@ void LoginDialog::login(const QString& username, const QString& password) { void LoginDialog::openUrl(const QString& url) { qDebug() << url; - Application::getInstance()->openUrl(url); + QDesktopServices::openUrl(url); } diff --git a/interface/src/ui/LoginDialog.h b/interface/src/ui/LoginDialog.h index 5761914642..50c820aa07 100644 --- a/interface/src/ui/LoginDialog.h +++ b/interface/src/ui/LoginDialog.h @@ -14,8 +14,6 @@ #ifndef hifi_LoginDialog_h #define hifi_LoginDialog_h -#include "DialogsManager.h" // Need before OffscreenQmlDialog.h in order to get gl.h and glew.h includes in correct order. - #include class LoginDialog : public OffscreenQmlDialog @@ -23,7 +21,6 @@ class LoginDialog : public OffscreenQmlDialog Q_OBJECT HIFI_QML_DECL - Q_PROPERTY(QString dialogFormat READ dialogFormat WRITE setDialogFormat NOTIFY dialogFormatChanged) Q_PROPERTY(QString statusText READ statusText WRITE setStatusText NOTIFY statusTextChanged) Q_PROPERTY(QString rootUrl READ rootUrl) @@ -32,17 +29,12 @@ public: LoginDialog(QQuickItem* parent = nullptr); - void setDialogFormat(const QString& dialogFormat); - QString dialogFormat() const; - void updateDialogFormat(); // protected? - void setStatusText(const QString& statusText); QString statusText() const; QString rootUrl() const; signals: - void dialogFormatChanged(); void statusTextChanged(); protected: @@ -52,7 +44,6 @@ protected: Q_INVOKABLE void login(const QString& username, const QString& password); Q_INVOKABLE void openUrl(const QString& url); private: - QString _dialogFormat; QString _statusText; const QString _rootUrl; }; From 8c1ece88657035c4f94599a8b4ce53810fcfe11f Mon Sep 17 00:00:00 2001 From: David Rowe Date: Fri, 5 Jun 2015 15:57:09 -0700 Subject: [PATCH 18/90] Fix #include for Unix --- interface/src/ui/LoginDialog.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/interface/src/ui/LoginDialog.cpp b/interface/src/ui/LoginDialog.cpp index eb6f3c0607..196ba5d29e 100644 --- a/interface/src/ui/LoginDialog.cpp +++ b/interface/src/ui/LoginDialog.cpp @@ -11,8 +11,9 @@ #include "LoginDialog.h" +#include + #include -#include #include "AccountManager.h" #include "DependencyManager.h" From 6f7c52d2cca4c50c52d00a9ca5168537e70e92e8 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Sat, 6 Jun 2015 10:42:49 -0700 Subject: [PATCH 19/90] Rename new Dialog to DialogContainer --- interface/resources/qml/AddressBarDialog.qml | 2 +- interface/resources/qml/ErrorDialog.qml | 2 +- interface/resources/qml/LoginDialog.qml | 2 +- .../resources/qml/controls/{Dialog.qml => DialogContainer.qml} | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) rename interface/resources/qml/controls/{Dialog.qml => DialogContainer.qml} (98%) diff --git a/interface/resources/qml/AddressBarDialog.qml b/interface/resources/qml/AddressBarDialog.qml index 7fa6bb3481..3377b20d87 100644 --- a/interface/resources/qml/AddressBarDialog.qml +++ b/interface/resources/qml/AddressBarDialog.qml @@ -13,7 +13,7 @@ import QtQuick 2.4 import "controls" import "styles" -Dialog { +DialogContainer { id: root HifiConstants { id: hifi } diff --git a/interface/resources/qml/ErrorDialog.qml b/interface/resources/qml/ErrorDialog.qml index 26b18f4ffd..76d9111d97 100644 --- a/interface/resources/qml/ErrorDialog.qml +++ b/interface/resources/qml/ErrorDialog.qml @@ -13,7 +13,7 @@ import QtQuick 2.4 import "controls" import "styles" -Dialog { +DialogContainer { id: root HifiConstants { id: hifi } diff --git a/interface/resources/qml/LoginDialog.qml b/interface/resources/qml/LoginDialog.qml index e552532cbd..8d5267f7f8 100644 --- a/interface/resources/qml/LoginDialog.qml +++ b/interface/resources/qml/LoginDialog.qml @@ -13,7 +13,7 @@ import QtQuick 2.4 import "controls" import "styles" -Dialog { +DialogContainer { id: root HifiConstants { id: hifi } diff --git a/interface/resources/qml/controls/Dialog.qml b/interface/resources/qml/controls/DialogContainer.qml similarity index 98% rename from interface/resources/qml/controls/Dialog.qml rename to interface/resources/qml/controls/DialogContainer.qml index 3cada90c3e..4aa4e45d67 100644 --- a/interface/resources/qml/controls/Dialog.qml +++ b/interface/resources/qml/controls/DialogContainer.qml @@ -1,5 +1,5 @@ // -// Dialog.qml +// DialogCommon.qml // // Created by David Rowe on 3 Jun 2015 // Copyright 2015 High Fidelity, Inc. From 77f2943877fc1ac6b9389887cf9c2fa38f945619 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Sat, 6 Jun 2015 10:48:07 -0700 Subject: [PATCH 20/90] Rename previous Dialog to VrDialog --- interface/resources/qml/Browser.qml | 2 +- interface/resources/qml/InfoView.qml | 2 +- interface/resources/qml/MarketplaceDialog.qml | 2 +- interface/resources/qml/MessageDialog.qml | 2 +- interface/resources/qml/TestDialog.qml | 2 +- .../resources/qml/controls/{DialogOld.qml => VrDialog.qml} | 0 6 files changed, 5 insertions(+), 5 deletions(-) rename interface/resources/qml/controls/{DialogOld.qml => VrDialog.qml} (100%) diff --git a/interface/resources/qml/Browser.qml b/interface/resources/qml/Browser.qml index 3de616e05b..947bf739fc 100644 --- a/interface/resources/qml/Browser.qml +++ b/interface/resources/qml/Browser.qml @@ -4,7 +4,7 @@ import QtWebKit 3.0 import "controls" import "styles" -DialogOld { +VrDialog { id: root HifiConstants { id: hifi } title: "Browser" diff --git a/interface/resources/qml/InfoView.qml b/interface/resources/qml/InfoView.qml index e97ebdeaf3..012f04f1fd 100644 --- a/interface/resources/qml/InfoView.qml +++ b/interface/resources/qml/InfoView.qml @@ -5,7 +5,7 @@ import QtQuick.Controls.Styles 1.3 import QtWebKit 3.0 import "controls" -DialogOld { +VrDialog { id: root width: 800 height: 800 diff --git a/interface/resources/qml/MarketplaceDialog.qml b/interface/resources/qml/MarketplaceDialog.qml index 4ad3c6515f..946f32e84a 100644 --- a/interface/resources/qml/MarketplaceDialog.qml +++ b/interface/resources/qml/MarketplaceDialog.qml @@ -5,7 +5,7 @@ import QtQuick.Controls.Styles 1.3 import QtWebKit 3.0 import "controls" -DialogOld { +VrDialog { title: "Test Dlg" id: testDialog objectName: "Browser" diff --git a/interface/resources/qml/MessageDialog.qml b/interface/resources/qml/MessageDialog.qml index 5c699e1f1f..e8b01df9d0 100644 --- a/interface/resources/qml/MessageDialog.qml +++ b/interface/resources/qml/MessageDialog.qml @@ -5,7 +5,7 @@ import QtQuick.Dialogs 1.2 import "controls" import "styles" -DialogOld { +VrDialog { id: root HifiConstants { id: hifi } property real spacing: hifi.layout.spacing diff --git a/interface/resources/qml/TestDialog.qml b/interface/resources/qml/TestDialog.qml index 3ae61fa054..e6675b7282 100644 --- a/interface/resources/qml/TestDialog.qml +++ b/interface/resources/qml/TestDialog.qml @@ -3,7 +3,7 @@ import QtQuick.Controls 1.2 import QtQuick.Controls.Styles 1.3 import "controls" -DialogOld { +VrDialog { title: "Test Dialog" id: testDialog objectName: "TestDialog" diff --git a/interface/resources/qml/controls/DialogOld.qml b/interface/resources/qml/controls/VrDialog.qml similarity index 100% rename from interface/resources/qml/controls/DialogOld.qml rename to interface/resources/qml/controls/VrDialog.qml From 119f37a1784f3a7e89120ae092dea1bf8a96c099 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Sun, 7 Jun 2015 14:34:40 -0700 Subject: [PATCH 21/90] Working on SDK 0.6 --- cmake/externals/oglplus/CMakeLists.txt | 8 +++---- interface/src/devices/OculusManager.cpp | 28 +++++++------------------ libraries/render-utils/src/Model.cpp | 2 +- 3 files changed, 13 insertions(+), 25 deletions(-) diff --git a/cmake/externals/oglplus/CMakeLists.txt b/cmake/externals/oglplus/CMakeLists.txt index 13709c1fde..1ef67b5e9f 100644 --- a/cmake/externals/oglplus/CMakeLists.txt +++ b/cmake/externals/oglplus/CMakeLists.txt @@ -3,13 +3,13 @@ string(TOUPPER ${EXTERNAL_NAME} EXTERNAL_NAME_UPPER) include(ExternalProject) ExternalProject_Add( - ${EXTERNAL_NAME} - GIT_REPOSITORY https://github.com/matus-chochlik/oglplus.git - GIT_TAG 9660aaaf65c5a3f47e6c54827ae28ae1ec5c5deb + ${EXTERNAL_NAME} + URL http://softlayer-dal.dl.sourceforge.net/project/oglplus/oglplus-0.61.x/oglplus-0.61.0.zip + URL_MD5 bb55038c36c660d2b6c7be380414fa60 CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND "" - LOG_DOWNLOAD 1 + LOG_DOWNLOAD 1 ) ExternalProject_Get_Property(${EXTERNAL_NAME} SOURCE_DIR) diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index d6151200f8..24b378f4a4 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -270,7 +270,7 @@ void OculusManager::connect() { _sceneLayer.ColorTexture[1] = nullptr; _sceneLayer.Viewport[0].Pos = { 0, 0 }; _sceneLayer.Viewport[0].Size = _recommendedTexSize; - _sceneLayer.Viewport[1].Pos = { _recommendedTexSize.x, 0 }; + _sceneLayer.Viewport[1].Pos = { _recommendedTexSize.w, 0 }; _sceneLayer.Viewport[1].Size = _recommendedTexSize; _sceneLayer.Header.Type = ovrLayerType_EyeFov; _sceneLayer.Header.Flags = ovrLayerFlag_TextureOriginAtBottomLeft; @@ -344,10 +344,10 @@ void OculusManager::disconnect() { } #endif - if (_ovrHmd) { + if (_ovrHmd) { ovrHmd_Destroy(_ovrHmd); _ovrHmd = nullptr; - } + } ovr_Shutdown(); _isConnected = false; @@ -586,9 +586,6 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati glm::vec3 trackerPosition; auto deviceSize = qApp->getDeviceSize(); -#ifndef Q_OS_WIN - ovrHmd_BeginFrame(_ovrHmd, _frameIndex); -#endif ovrTrackingState ts = ovrHmd_GetTrackingState(_ovrHmd, ovr_GetTimeInSeconds()); ovrVector3f ovrHeadPosition = ts.HeadPose.ThePose.Position; @@ -604,7 +601,9 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati static ovrVector3f eyeOffsets[2] = { { 0, 0, 0 }, { 0, 0, 0 } }; ovrPosef eyePoses[ovrEye_Count]; ovrHmd_GetEyePoses(_ovrHmd, _frameIndex, eyeOffsets, eyePoses, nullptr); +#ifndef Q_OS_WIN ovrHmd_BeginFrame(_ovrHmd, _frameIndex); +#endif static ovrPosef eyeRenderPose[ovrEye_Count]; //Render each eye into an fbo for_each_eye(_ovrHmd, [&](ovrEyeType eye){ @@ -652,7 +651,7 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati glViewport(vp.Pos.x, vp.Pos.y, vp.Size.w, vp.Size.h); qApp->displaySide(*_camera, false, RenderArgs::MONO); - qApp->getApplicationOverlay().displayOve rlayTextureHmd(*_camera); + qApp->getApplicationOverlay().displayOverlayTextureHmd(*_camera); }); _activeEye = ovrEye_Count; @@ -692,21 +691,10 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati GL_COLOR_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); - ovrLayerEyeFov sceneLayer; - sceneLayer.ColorTexture[0] = _swapFbo->color; - sceneLayer.ColorTexture[1] = nullptr; - - sceneLayer.Viewport[0].Pos = { 0, 0 }; - sceneLayer.Viewport[0].Size = { _swapFbo->size.x / 2, _swapFbo->size.y }; - sceneLayer.Viewport[1].Pos = { _swapFbo->size.x / 2, 0 }; - sceneLayer.Viewport[1].Size = { _swapFbo->size.x / 2, _swapFbo->size.y }; - sceneLayer.Header.Type = ovrLayerType_EyeFov; - sceneLayer.Header.Flags = ovrLayerFlag_TextureOriginAtBottomLeft; for_each_eye([&](ovrEyeType eye) { - sceneLayer.Fov[eye] = _eyeFov[eye]; - sceneLayer.RenderPose[eye] = eyeRenderPose[eye]; + _sceneLayer.RenderPose[eye] = eyeRenderPose[eye]; }); - auto header = &sceneLayer.Header; + auto header = &_sceneLayer.Header; ovrResult res = ovrHmd_SubmitFrame(_ovrHmd, _frameIndex, nullptr, &header, 1); Q_ASSERT(OVR_SUCCESS(res)); _swapFbo->Increment(); diff --git a/libraries/render-utils/src/Model.cpp b/libraries/render-utils/src/Model.cpp index feddf61405..483ea6177e 100644 --- a/libraries/render-utils/src/Model.cpp +++ b/libraries/render-utils/src/Model.cpp @@ -1412,7 +1412,7 @@ void Model::simulate(float deltaTime, bool fullUpdate) { if (_snapModelToRegistrationPoint && !_snappedToRegistrationPoint) { snapToRegistrationPoint(); } - //simulateInternal(deltaTime); + simulateInternal(deltaTime); } } From 6a60da2a6c5de3fdeda6aeb0087a013a133572bc Mon Sep 17 00:00:00 2001 From: Bradley Austin Davis Date: Sun, 7 Jun 2015 17:58:33 -0700 Subject: [PATCH 22/90] Working on SDK 0.6 --- interface/src/devices/OculusManager.cpp | 39 +++++++++++++++---------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index 24b378f4a4..f177aa3097 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -219,6 +219,7 @@ void OculusManager::deinit() { } void OculusManager::connect() { + qCDebug(interfaceapp) << "Oculus SDK" << OVR_VERSION_STRING; ovrInitParams initParams; memset(&initParams, 0, sizeof(initParams)); #ifdef DEBUG @@ -245,10 +246,13 @@ void OculusManager::connect() { } #endif + _isConnected = false; + + // we're definitely not in "VR mode" so tell the menu that + Menu::getInstance()->getActionForOption(MenuOption::EnableVRMode)->setChecked(false); + #endif _calibrationState = UNCALIBRATED; - qCDebug(interfaceapp) << "Oculus SDK" << OVR_VERSION_STRING; - if (_ovrHmd) { if (!_isConnected) { UserActivityLogger::getInstance().connectedDevice("hmd", "oculus"); } @@ -677,6 +681,7 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati #ifdef Q_OS_WIN auto srcFboSize = finalFbo->getSize(); + // Blit to the oculus provided texture glBindFramebuffer(GL_READ_FRAMEBUFFER, gpu::GLBackend::getFramebufferID(finalFbo)); _swapFbo->Bound(oglplus::Framebuffer::Target::Draw, [&] { glBlitFramebuffer( @@ -684,6 +689,8 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati 0, 0, _swapFbo->size.x, _swapFbo->size.y, GL_COLOR_BUFFER_BIT, GL_NEAREST); }); + + // Blit to the onscreen window auto destWindowSize = qApp->getDeviceSize(); glBlitFramebuffer( 0, 0, srcFboSize.x, srcFboSize.y, @@ -691,6 +698,7 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati GL_COLOR_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + // Submit the frame to the Oculus SDK for timewarp and distortion for_each_eye([&](ovrEyeType eye) { _sceneLayer.RenderPose[eye] = eyeRenderPose[eye]; }); @@ -705,23 +713,22 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati glEyeTexture.OGL.TexId = textureId; }); - //ovrHmd_EndFrame(_ovrHmd, eyeRenderPose, _eyeTextures); - glClearColor(0, 0, 0, 1); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - auto srcFboSize = finalFbo->getSize(); - glBindFramebuffer(GL_READ_FRAMEBUFFER, gpu::GLBackend::getFramebufferID(finalFbo)); - auto destWindowSize = qApp->getDeviceSize(); - glBlitFramebuffer( - 0, 0, srcFboSize.x, srcFboSize.y, - 0, 0, destWindowSize.width(), destWindowSize.height(), - GL_COLOR_BUFFER_BIT, GL_NEAREST); - glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); - glCanvas->swapBuffers(); + // restore our normal viewport + glViewport(0, 0, deviceSize.width(), deviceSize.height()); + ovrHmd_EndFrame(_ovrHmd, eyeRenderPose, _eyeTextures); + +// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); +// auto srcFboSize = finalFbo->getSize(); +// glBindFramebuffer(GL_READ_FRAMEBUFFER, gpu::GLBackend::getFramebufferID(finalFbo)); +// glBlitFramebuffer( +// 0, 0, srcFboSize.x, srcFboSize.y, +// 0, 0, deviceSize.width(), deviceSize.height(), +// GL_COLOR_BUFFER_BIT, GL_NEAREST); +// glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); +// glCanvas->swapBuffers(); #endif - // restore our normal viewport - glViewport(0, 0, deviceSize.width(), deviceSize.height()); } //Tries to reconnect to the sensors From de268c47b3e73ff3dbaadb7af040defaeab1c20a Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Sun, 7 Jun 2015 18:25:16 -0700 Subject: [PATCH 23/90] Working on 0.6 --- interface/src/Application.cpp | 3 +- interface/src/devices/OculusManager.cpp | 174 +++++++++++++----------- interface/src/devices/OculusManager.h | 5 +- 3 files changed, 98 insertions(+), 84 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 93f6217cb9..84aaa2297f 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1860,8 +1860,7 @@ void Application::setEnableVRMode(bool enableVRMode) { // attempt to reconnect the Oculus manager - it's possible this was a workaround // for the sixense crash OculusManager::disconnect(); - _glWidget->makeCurrent(); - OculusManager::connect(); + OculusManager::connect(_glWidget->context()->contextHandle()); } OculusManager::recalibrate(); } else { diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index f177aa3097..8e5866a1ef 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -177,6 +178,7 @@ ovrLayerEyeFov OculusManager::_sceneLayer; #else ovrTexture OculusManager::_eyeTextures[ovrEye_Count]; +GlWindow* OculusManager::_outputWindow{ nullptr }; #endif @@ -197,12 +199,12 @@ float OculusManager::CALIBRATION_DELTA_MINIMUM_LENGTH = 0.02f; float OculusManager::CALIBRATION_DELTA_MINIMUM_ANGLE = 5.0f * RADIANS_PER_DEGREE; float OculusManager::CALIBRATION_ZERO_MAXIMUM_LENGTH = 0.01f; float OculusManager::CALIBRATION_ZERO_MAXIMUM_ANGLE = 2.0f * RADIANS_PER_DEGREE; -quint64 OculusManager::CALIBRATION_ZERO_HOLD_TIME = 3000000; // usec +uint64_t OculusManager::CALIBRATION_ZERO_HOLD_TIME = 3000000; // usec float OculusManager::CALIBRATION_MESSAGE_DISTANCE = 2.5f; OculusManager::CalibrationState OculusManager::_calibrationState; glm::vec3 OculusManager::_calibrationPosition; glm::quat OculusManager::_calibrationOrientation; -quint64 OculusManager::_calibrationStartTime; +uint64_t OculusManager::_calibrationStartTime; int OculusManager::_calibrationMessage = 0; glm::vec3 OculusManager::_eyePositions[ovrEye_Count]; // TODO expose this as a developer toggle @@ -218,13 +220,15 @@ void OculusManager::init() { void OculusManager::deinit() { } -void OculusManager::connect() { +void OculusManager::connect(QOpenGLContext* shareContext) { qCDebug(interfaceapp) << "Oculus SDK" << OVR_VERSION_STRING; ovrInitParams initParams; memset(&initParams, 0, sizeof(initParams)); + #ifdef DEBUG - //initParams.Flags |= ovrInit_Debug; + initParams.Flags |= ovrInit_Debug; #endif + ovr_Initialize(&initParams); #ifdef Q_OS_WIN @@ -246,89 +250,97 @@ void OculusManager::connect() { } #endif - _isConnected = false; - - // we're definitely not in "VR mode" so tell the menu that - Menu::getInstance()->getActionForOption(MenuOption::EnableVRMode)->setChecked(false); - #endif + + if (!_ovrHmd) { + _isConnected = false; + // we're definitely not in "VR mode" so tell the menu that + Menu::getInstance()->getActionForOption(MenuOption::EnableVRMode)->setChecked(false); + ovr_Shutdown(); + return; + } + _calibrationState = UNCALIBRATED; - if (!_isConnected) { - UserActivityLogger::getInstance().connectedDevice("hmd", "oculus"); - } - _isConnected = true; + if (!_isConnected) { + UserActivityLogger::getInstance().connectedDevice("hmd", "oculus"); + } + _isConnected = true; - for_each_eye([&](ovrEyeType eye) { - _eyeFov[eye] = _ovrHmd->DefaultEyeFov[eye]; - }); + for_each_eye([&](ovrEyeType eye) { + _eyeFov[eye] = _ovrHmd->DefaultEyeFov[eye]; + }); - _recommendedTexSize = ovrHmd_GetFovTextureSize(_ovrHmd, ovrEye_Left, _eyeFov[ovrEye_Left], 1.0f); - _renderTargetSize = { _recommendedTexSize.w * 2, _recommendedTexSize.h }; + _recommendedTexSize = ovrHmd_GetFovTextureSize(_ovrHmd, ovrEye_Left, _eyeFov[ovrEye_Left], 1.0f); + _renderTargetSize = { _recommendedTexSize.w * 2, _recommendedTexSize.h }; #ifdef Q_OS_WIN - _mirrorFbo = new MirrorFramebufferWrapper(_ovrHmd); - _swapFbo = new SwapFramebufferWrapper(_ovrHmd); - _swapFbo->Init(toGlm(_renderTargetSize)); - _sceneLayer.ColorTexture[0] = _swapFbo->color; - _sceneLayer.ColorTexture[1] = nullptr; - _sceneLayer.Viewport[0].Pos = { 0, 0 }; - _sceneLayer.Viewport[0].Size = _recommendedTexSize; - _sceneLayer.Viewport[1].Pos = { _recommendedTexSize.w, 0 }; - _sceneLayer.Viewport[1].Size = _recommendedTexSize; - _sceneLayer.Header.Type = ovrLayerType_EyeFov; - _sceneLayer.Header.Flags = ovrLayerFlag_TextureOriginAtBottomLeft; - for_each_eye([&](ovrEyeType eye) { - _eyeViewports[eye] = _sceneLayer.Viewport[eye]; - _sceneLayer.Fov[eye] = _eyeFov[eye]; - }); + _mirrorFbo = new MirrorFramebufferWrapper(_ovrHmd); + _swapFbo = new SwapFramebufferWrapper(_ovrHmd); + _swapFbo->Init(toGlm(_renderTargetSize)); + _sceneLayer.ColorTexture[0] = _swapFbo->color; + _sceneLayer.ColorTexture[1] = nullptr; + _sceneLayer.Viewport[0].Pos = { 0, 0 }; + _sceneLayer.Viewport[0].Size = _recommendedTexSize; + _sceneLayer.Viewport[1].Pos = { _recommendedTexSize.w, 0 }; + _sceneLayer.Viewport[1].Size = _recommendedTexSize; + _sceneLayer.Header.Type = ovrLayerType_EyeFov; + _sceneLayer.Header.Flags = ovrLayerFlag_TextureOriginAtBottomLeft; + for_each_eye([&](ovrEyeType eye) { + _eyeViewports[eye] = _sceneLayer.Viewport[eye]; + _sceneLayer.Fov[eye] = _eyeFov[eye]; + }); + + #else - ovrGLConfig cfg; - memset(&cfg, 0, sizeof(cfg)); - cfg.OGL.Header.API = ovrRenderAPI_OpenGL; - cfg.OGL.Header.BackBufferSize = _ovrHmd->Resolution; - cfg.OGL.Header.Multisample = 1; + _outputWindow = new GlWindow(shareContext); + _outputWindow->show(); + _outputWindow->setFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); + _outputWindow->resize(_ovrHmd->Resolution.w, _ovrHmd->Resolution.h); + // _outputWindow->setPosition(_ovrHmd->Position.x, _ovrHmd->Position.y); + _outputWindow->makeCurrent(); - int distortionCaps = 0 - | ovrDistortionCap_Vignette - | ovrDistortionCap_Overdrive - | ovrDistortionCap_TimeWarp; + ovrGLConfig cfg; + memset(&cfg, 0, sizeof(cfg)); + cfg.OGL.Header.API = ovrRenderAPI_OpenGL; + cfg.OGL.Header.BackBufferSize = _ovrHmd->Resolution; + cfg.OGL.Header.Multisample = 0; - int configResult = ovrHmd_ConfigureRendering(_ovrHmd, &cfg.Config, - distortionCaps, _eyeFov, _eyeRenderDesc); - assert(configResult); + int distortionCaps = 0 + | ovrDistortionCap_Vignette + | ovrDistortionCap_Overdrive + | ovrDistortionCap_TimeWarp; + + int configResult = ovrHmd_ConfigureRendering(_ovrHmd, &cfg.Config, + distortionCaps, _eyeFov, _eyeRenderDesc); + assert(configResult); - for_each_eye([&](ovrEyeType eye) { - //Get texture size - _eyeTextures[eye].Header.API = ovrRenderAPI_OpenGL; - _eyeTextures[eye].Header.TextureSize = _renderTargetSize; - _eyeTextures[eye].Header.RenderViewport.Pos = { 0, 0 }; - _eyeTextures[eye].Header.RenderViewport.Size = _renderTargetSize; - _eyeTextures[eye].Header.RenderViewport.Size.w /= 2; - }); - _eyeTextures[ovrEye_Right].Header.RenderViewport.Pos.x = _recommendedTexSize.w; - for_each_eye([&](ovrEyeType eye) { - _eyeViewports[eye] = _eyeTextures[eye].Header.RenderViewport; - }); + for_each_eye([&](ovrEyeType eye) { + //Get texture size + _eyeTextures[eye].Header.API = ovrRenderAPI_OpenGL; + _eyeTextures[eye].Header.TextureSize = _renderTargetSize; + _eyeTextures[eye].Header.RenderViewport.Pos = { 0, 0 }; + _eyeTextures[eye].Header.RenderViewport.Size = _renderTargetSize; + _eyeTextures[eye].Header.RenderViewport.Size.w /= 2; + }); + _eyeTextures[ovrEye_Right].Header.RenderViewport.Pos.x = _recommendedTexSize.w; + for_each_eye([&](ovrEyeType eye) { + _eyeViewports[eye] = _eyeTextures[eye].Header.RenderViewport; + }); #endif - ovrHmd_SetEnabledCaps(_ovrHmd, ovrHmdCap_LowPersistence | ovrHmdCap_DynamicPrediction); + ovrHmd_SetEnabledCaps(_ovrHmd, + ovrHmdCap_LowPersistence | ovrHmdCap_DynamicPrediction); - ovrHmd_ConfigureTracking(_ovrHmd, ovrTrackingCap_Orientation | ovrTrackingCap_Position | - ovrTrackingCap_MagYawCorrection, - ovrTrackingCap_Orientation); + ovrHmd_ConfigureTracking(_ovrHmd, + ovrTrackingCap_Orientation | ovrTrackingCap_Position | ovrTrackingCap_MagYawCorrection, + ovrTrackingCap_Orientation); - if (!_camera) { - _camera = new Camera; - configureCamera(*_camera); // no need to use screen dimensions; they're ignored - } - } else { - _isConnected = false; - - // we're definitely not in "VR mode" so tell the menu that - Menu::getInstance()->getActionForOption(MenuOption::EnableVRMode)->setChecked(false); + if (!_camera) { + _camera = new Camera; + configureCamera(*_camera); // no need to use screen dimensions; they're ignored } } @@ -460,7 +472,6 @@ void OculusManager::calibrate(glm::vec3 position, glm::quat orientation) { break; default: break; - } } @@ -713,19 +724,20 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati glEyeTexture.OGL.TexId = textureId; }); + _outputWindow->makeCurrent(); // restore our normal viewport - glViewport(0, 0, deviceSize.width(), deviceSize.height()); ovrHmd_EndFrame(_ovrHmd, eyeRenderPose, _eyeTextures); -// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); -// auto srcFboSize = finalFbo->getSize(); -// glBindFramebuffer(GL_READ_FRAMEBUFFER, gpu::GLBackend::getFramebufferID(finalFbo)); -// glBlitFramebuffer( -// 0, 0, srcFboSize.x, srcFboSize.y, -// 0, 0, deviceSize.width(), deviceSize.height(), -// GL_COLOR_BUFFER_BIT, GL_NEAREST); -// glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); -// glCanvas->swapBuffers(); + //auto outputSize = _outputWindow->size(); + //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + //auto srcFboSize = finalFbo->getSize(); + //glBindFramebuffer(GL_READ_FRAMEBUFFER, gpu::GLBackend::getFramebufferID(finalFbo)); + //glBlitFramebuffer( + // 0, 0, srcFboSize.x, srcFboSize.y, + // 0, 0, outputSize.width(), outputSize.height(), + // GL_COLOR_BUFFER_BIT, GL_NEAREST); + //glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + //glCanvas->swapBuffers(); #endif diff --git a/interface/src/devices/OculusManager.h b/interface/src/devices/OculusManager.h index d07a22fbd1..81377870eb 100644 --- a/interface/src/devices/OculusManager.h +++ b/interface/src/devices/OculusManager.h @@ -20,7 +20,9 @@ #include #include +class QOpenGLContext; class Camera; +class GlWindow; class PalmData; class Text3DOverlay; @@ -35,7 +37,7 @@ class OculusManager { public: static void init(); static void deinit(); - static void connect(); + static void connect(QOpenGLContext* shareContext); static void disconnect(); static bool isConnected(); static void recalibrate(); @@ -113,6 +115,7 @@ private: static ovrLayerEyeFov _sceneLayer; #else static ovrTexture _eyeTextures[ovrEye_Count]; + static GlWindow* _outputWindow; #endif }; From 5a52a389bebf5a2f89bb71136dfd62efbb9ef457 Mon Sep 17 00:00:00 2001 From: Bradley Austin Davis Date: Sun, 7 Jun 2015 23:23:21 -0700 Subject: [PATCH 24/90] Working on SDK 0.6 --- interface/src/Application.cpp | 3 ++ interface/src/avatar/SkeletonModel.cpp | 4 ++ interface/src/devices/OculusManager.cpp | 66 +++++++++++-------------- interface/src/devices/OculusManager.h | 4 ++ interface/src/ui/ApplicationOverlay.cpp | 2 +- interface/src/ui/HMDToolsDialog.cpp | 2 +- libraries/shared/src/OglplusHelpers.h | 4 +- 7 files changed, 42 insertions(+), 43 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 84aaa2297f..4f314eeb2c 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1861,6 +1861,9 @@ void Application::setEnableVRMode(bool enableVRMode) { // for the sixense crash OculusManager::disconnect(); OculusManager::connect(_glWidget->context()->contextHandle()); + _glWidget->setFocus(); + _glWidget->makeCurrent(); + glClear(GL_COLOR_BUFFER_BIT); } OculusManager::recalibrate(); } else { diff --git a/interface/src/avatar/SkeletonModel.cpp b/interface/src/avatar/SkeletonModel.cpp index e2f4ca51a0..5ccda4d288 100644 --- a/interface/src/avatar/SkeletonModel.cpp +++ b/interface/src/avatar/SkeletonModel.cpp @@ -258,6 +258,10 @@ void SkeletonModel::updateJointState(int index) { JointState& state = _jointStates[index]; const FBXJoint& joint = state.getFBXJoint(); if (joint.parentIndex != -1) { + if (joint.parentIndex < 0 || joint.parentIndex >= _jointStates.size()) { + qDebug() << "Bad parent index"; + return; + } const JointState& parentState = _jointStates.at(joint.parentIndex); const FBXGeometry& geometry = _geometry->getFBXGeometry(); if (index == geometry.leanJointIndex) { diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index 8e5866a1ef..5353d1cd55 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -177,6 +177,7 @@ ovrLayerEyeFov OculusManager::_sceneLayer; #else +BasicFramebufferWrapper* _transferFbo; ovrTexture OculusManager::_eyeTextures[ovrEye_Count]; GlWindow* OculusManager::_outputWindow{ nullptr }; @@ -296,11 +297,24 @@ void OculusManager::connect(QOpenGLContext* shareContext) { #else _outputWindow = new GlWindow(shareContext); _outputWindow->show(); - _outputWindow->setFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); - _outputWindow->resize(_ovrHmd->Resolution.w, _ovrHmd->Resolution.h); - // _outputWindow->setPosition(_ovrHmd->Position.x, _ovrHmd->Position.y); +// _outputWindow->setFlags(Qt::FramelessWindowHint ); +// _outputWindow->resize(_ovrHmd->Resolution.w, _ovrHmd->Resolution.h); +// _outputWindow->setPosition(_ovrHmd->WindowsPos.x, _ovrHmd->WindowsPos.y); + ivec2 desiredPosition = toGlm(_ovrHmd->WindowsPos); + foreach(QScreen* screen, qGuiApp->screens()) { + ivec2 screenPosition = toGlm(screen->geometry().topLeft()); + if (screenPosition == desiredPosition) { + _outputWindow->setScreen(screen); + break; + } + } + _outputWindow->showFullScreen(); _outputWindow->makeCurrent(); - + _transferFbo = new BasicFramebufferWrapper(); + _transferFbo->Init(toGlm(_renderTargetSize)); + + + ovrGLConfig cfg; memset(&cfg, 0, sizeof(cfg)); cfg.OGL.Header.API = ovrRenderAPI_OpenGL; @@ -315,7 +329,7 @@ void OculusManager::connect(QOpenGLContext* shareContext) { int configResult = ovrHmd_ConfigureRendering(_ovrHmd, &cfg.Config, distortionCaps, _eyeFov, _eyeRenderDesc); assert(configResult); - + _outputWindow->doneCurrent(); for_each_eye([&](ovrEyeType eye) { //Get texture size @@ -358,6 +372,10 @@ void OculusManager::disconnect() { delete _mirrorFbo; _mirrorFbo = nullptr; } +#else + _outputWindow->showNormal(); + _outputWindow->deleteLater(); + _outputWindow = nullptr; #endif if (_ovrHmd) { @@ -535,28 +553,11 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati assert(oldFrameIndex == -1 || (unsigned int)oldFrameIndex == _frameIndex - 1); oldFrameIndex = _frameIndex; #endif - - // Every so often do some additional timing calculations and debug output - bool debugFrame = 0 == _frameIndex % 400; -#if 0 - // Try to measure the amount of time taken to do the distortion - // (does not seem to work on OSX with SDK based distortion) - // FIXME can't use a static object here, because it will cause a crash when the - // query attempts deconstruct after the GL context is gone. - static bool timerActive = false; - static QOpenGLTimerQuery timerQuery; - if (!timerQuery.isCreated()) { - timerQuery.create(); + if (_outputWindow->visibility() != QWindow::FullScreen) { + // _outputWindow->showFullScreen(); } - if (timerActive && timerQuery.isResultAvailable()) { - auto result = timerQuery.waitForResult(); - if (result) { qCDebug(interfaceapp) << "Distortion took " << result << "ns"; }; - timerActive = false; - } -#endif - #ifndef Q_OS_WIN // FIXME: we need a better way of responding to the HSW. In particular // we need to ensure that it's only displayed once per session, rather than @@ -573,7 +574,6 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati } } #endif - //beginFrameTiming must be called before display if (!_frameTimingActive) { @@ -718,26 +718,16 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati Q_ASSERT(OVR_SUCCESS(res)); _swapFbo->Increment(); #else + glFinish(); GLuint textureId = gpu::GLBackend::getTextureID(finalFbo->getRenderBuffer(0)); + _outputWindow->makeCurrent(); for_each_eye([&](ovrEyeType eye) { ovrGLTexture & glEyeTexture = reinterpret_cast(_eyeTextures[eye]); glEyeTexture.OGL.TexId = textureId; }); - - _outputWindow->makeCurrent(); // restore our normal viewport ovrHmd_EndFrame(_ovrHmd, eyeRenderPose, _eyeTextures); - - //auto outputSize = _outputWindow->size(); - //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - //auto srcFboSize = finalFbo->getSize(); - //glBindFramebuffer(GL_READ_FRAMEBUFFER, gpu::GLBackend::getFramebufferID(finalFbo)); - //glBlitFramebuffer( - // 0, 0, srcFboSize.x, srcFboSize.y, - // 0, 0, outputSize.width(), outputSize.height(), - // GL_COLOR_BUFFER_BIT, GL_NEAREST); - //glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); - //glCanvas->swapBuffers(); + glCanvas->makeCurrent(); #endif diff --git a/interface/src/devices/OculusManager.h b/interface/src/devices/OculusManager.h index 81377870eb..03e754c40a 100644 --- a/interface/src/devices/OculusManager.h +++ b/interface/src/devices/OculusManager.h @@ -136,6 +136,10 @@ inline glm::vec2 toGlm(const ovrVector2f & ov) { return glm::make_vec2(&ov.x); } +inline glm::ivec2 toGlm(const ovrVector2i & ov) { + return glm::ivec2(ov.x, ov.y); +} + inline glm::uvec2 toGlm(const ovrSizei & ov) { return glm::uvec2(ov.w, ov.h); } diff --git a/interface/src/ui/ApplicationOverlay.cpp b/interface/src/ui/ApplicationOverlay.cpp index d9d2a1d971..7213635065 100644 --- a/interface/src/ui/ApplicationOverlay.cpp +++ b/interface/src/ui/ApplicationOverlay.cpp @@ -349,7 +349,7 @@ void ApplicationOverlay::displayOverlayTextureHmd(Camera& whichCamera) { textureAspectRatio = _textureAspectRatio; _overlays.buildVBO(_textureFov, _textureAspectRatio, 80, 80); - } + } with_each_texture(_overlays.getTexture(), _newUiTexture, [&] { _overlays.render(); diff --git a/interface/src/ui/HMDToolsDialog.cpp b/interface/src/ui/HMDToolsDialog.cpp index 0dfbb202da..7db0867d1c 100644 --- a/interface/src/ui/HMDToolsDialog.cpp +++ b/interface/src/ui/HMDToolsDialog.cpp @@ -250,7 +250,7 @@ void HMDToolsDialog::aboutToQuit() { void HMDToolsDialog::screenCountChanged(int newCount) { if (!OculusManager::isConnected()) { - OculusManager::connect(); + //OculusManager::connect(); } int hmdScreenNumber = OculusManager::getHMDScreen(); diff --git a/libraries/shared/src/OglplusHelpers.h b/libraries/shared/src/OglplusHelpers.h index 73d32c4079..1a00c021f9 100644 --- a/libraries/shared/src/OglplusHelpers.h +++ b/libraries/shared/src/OglplusHelpers.h @@ -5,7 +5,6 @@ // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifdef Q_OS_WIN #pragma once #include "GLMHelpers.h" @@ -164,5 +163,4 @@ protected: } }; -using BasicFramebufferWrapperPtr = std::shared_ptr; -#endif \ No newline at end of file +using BasicFramebufferWrapperPtr = std::shared_ptr; \ No newline at end of file From 5faa53d7e9c1309599310cd11a042dd2b232e329 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Mon, 8 Jun 2015 10:17:34 -0700 Subject: [PATCH 25/90] Working on OVR SDK 0.6 --- interface/src/Application.cpp | 7 --- interface/src/devices/OculusManager.cpp | 4 -- interface/src/ui/HMDToolsDialog.cpp | 61 ++----------------------- interface/src/ui/HMDToolsDialog.h | 4 -- 4 files changed, 3 insertions(+), 73 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 4f314eeb2c..5f8403e3f1 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2106,13 +2106,6 @@ void Application::init() { _mirrorCamera.setMode(CAMERA_MODE_MIRROR); - //OculusManager::connect(); - //if (OculusManager::isConnected()) { - // QMetaObject::invokeMethod(Menu::getInstance()->getActionForOption(MenuOption::Fullscreen), - // "trigger", - // Qt::QueuedConnection); - //} - TV3DManager::connect(); if (TV3DManager::isConnected()) { QMetaObject::invokeMethod(Menu::getInstance()->getActionForOption(MenuOption::Fullscreen), diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index 5353d1cd55..1fef48a8c9 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -554,10 +554,6 @@ void OculusManager::display(QGLWidget * glCanvas, const glm::quat &bodyOrientati oldFrameIndex = _frameIndex; #endif - if (_outputWindow->visibility() != QWindow::FullScreen) { - // _outputWindow->showFullScreen(); - } - #ifndef Q_OS_WIN // FIXME: we need a better way of responding to the HSW. In particular // we need to ensure that it's only displayed once per session, rather than diff --git a/interface/src/ui/HMDToolsDialog.cpp b/interface/src/ui/HMDToolsDialog.cpp index 7db0867d1c..9afd0f51c7 100644 --- a/interface/src/ui/HMDToolsDialog.cpp +++ b/interface/src/ui/HMDToolsDialog.cpp @@ -56,8 +56,6 @@ HMDToolsDialog::HMDToolsDialog(QWidget* parent) : this->QDialog::setLayout(form); - _wasMoved = false; - _previousRect = Application::getInstance()->getWindow()->rect(); Application::getInstance()->getWindow()->activateWindow(); // watch for our application window moving screens. If it does we want to update our screen details @@ -136,24 +134,6 @@ void HMDToolsDialog::enterHDMMode() { if (!_inHDMMode) { _switchModeButton->setText("Leave HMD Mode"); _debugDetails->setText(getDebugDetails()); - - _hmdScreenNumber = OculusManager::getHMDScreen(); - - if (_hmdScreenNumber >= 0) { - QWindow* mainWindow = Application::getInstance()->getWindow()->windowHandle(); - _hmdScreen = QGuiApplication::screens()[_hmdScreenNumber]; - - _previousRect = Application::getInstance()->getWindow()->rect(); - _previousRect = QRect(mainWindow->mapToGlobal(_previousRect.topLeft()), - mainWindow->mapToGlobal(_previousRect.bottomRight())); - _previousScreen = mainWindow->screen(); - QRect rect = QApplication::desktop()->screenGeometry(_hmdScreenNumber); - mainWindow->setScreen(_hmdScreen); - mainWindow->setGeometry(rect); - - _wasMoved = true; - } - // if we're on a single screen setup, then hide our tools window when entering HMD mode if (QApplication::desktop()->screenCount() == 1) { @@ -161,58 +141,21 @@ void HMDToolsDialog::enterHDMMode() { } Application::getInstance()->setEnableVRMode(true); - - const int SLIGHT_DELAY = 500; - // If we go to fullscreen immediately, it ends up on the primary monitor, - // even though we've already moved the window. By adding this delay, the - // fullscreen target screen ends up correct. - QTimer::singleShot(SLIGHT_DELAY, this, [&]{ - Application::getInstance()->setFullscreen(true); - activateWindowAfterEnterMode(); - }); - + _inHDMMode = true; } } -void HMDToolsDialog::activateWindowAfterEnterMode() { - Application::getInstance()->getWindow()->activateWindow(); - - // center the cursor on the main application window - centerCursorOnWidget(Application::getInstance()->getWindow()); -} - void HMDToolsDialog::leaveHDMMode() { if (_inHDMMode) { _switchModeButton->setText("Enter HMD Mode"); _debugDetails->setText(getDebugDetails()); - Application::getInstance()->setEnableVRMode(false); - Application::getInstance()->setFullscreen(false); Application::getInstance()->getWindow()->activateWindow(); - - if (_wasMoved) { - QWindow* mainWindow = Application::getInstance()->getWindow()->windowHandle(); - mainWindow->setScreen(_previousScreen); - mainWindow->setGeometry(_previousRect); - - const int SLIGHT_DELAY = 1500; - QTimer::singleShot(SLIGHT_DELAY, this, SLOT(moveWindowAfterLeaveMode())); - } - _wasMoved = false; _inHDMMode = false; } } -void HMDToolsDialog::moveWindowAfterLeaveMode() { - QWindow* mainWindow = Application::getInstance()->getWindow()->windowHandle(); - mainWindow->setScreen(_previousScreen); - mainWindow->setGeometry(_previousRect); - Application::getInstance()->getWindow()->activateWindow(); - Application::getInstance()->resetSensors(); -} - - void HMDToolsDialog::reject() { // Just regularly close upon ESC close(); @@ -244,6 +187,8 @@ void HMDToolsDialog::hideEvent(QHideEvent* event) { void HMDToolsDialog::aboutToQuit() { if (_inHDMMode) { + // FIXME this is ineffective because it doesn't trigger the menu to + // save the fact that VR Mode is not checked. leaveHDMMode(); } } diff --git a/interface/src/ui/HMDToolsDialog.h b/interface/src/ui/HMDToolsDialog.h index 10dc1c5c80..c16957f2d7 100644 --- a/interface/src/ui/HMDToolsDialog.h +++ b/interface/src/ui/HMDToolsDialog.h @@ -35,8 +35,6 @@ signals: public slots: void reject(); void switchModeClicked(bool checked); - void activateWindowAfterEnterMode(); - void moveWindowAfterLeaveMode(); void applicationWindowScreenChanged(QScreen* screen); void aboutToQuit(); void screenCountChanged(int newCount); @@ -51,8 +49,6 @@ private: void enterHDMMode(); void leaveHDMMode(); - bool _wasMoved; - QRect _previousRect; QScreen* _previousScreen; QScreen* _hmdScreen; int _hmdScreenNumber; From 11bc838be9580528dd29be643d0cc5c83aecff4e Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Tue, 9 Jun 2015 00:48:42 -0700 Subject: [PATCH 26/90] Switching to Git for oglplus --- cmake/externals/oglplus/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmake/externals/oglplus/CMakeLists.txt b/cmake/externals/oglplus/CMakeLists.txt index 1ef67b5e9f..fd3dcee687 100644 --- a/cmake/externals/oglplus/CMakeLists.txt +++ b/cmake/externals/oglplus/CMakeLists.txt @@ -4,8 +4,8 @@ string(TOUPPER ${EXTERNAL_NAME} EXTERNAL_NAME_UPPER) include(ExternalProject) ExternalProject_Add( ${EXTERNAL_NAME} - URL http://softlayer-dal.dl.sourceforge.net/project/oglplus/oglplus-0.61.x/oglplus-0.61.0.zip - URL_MD5 bb55038c36c660d2b6c7be380414fa60 + GIT_REPOSITORY https://github.com/matus-chochlik/oglplus.git + GIT_TAG 1aab48f45b40b4ea06a15975fa033b66b237078f CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND "" From 5a1b7131603ae451ba15189cad093a96fba1a97e Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Tue, 9 Jun 2015 00:59:17 -0700 Subject: [PATCH 27/90] Fixing texture include error in oglplus --- cmake/externals/oglplus/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmake/externals/oglplus/CMakeLists.txt b/cmake/externals/oglplus/CMakeLists.txt index fd3dcee687..bfe6f2a20a 100644 --- a/cmake/externals/oglplus/CMakeLists.txt +++ b/cmake/externals/oglplus/CMakeLists.txt @@ -4,8 +4,8 @@ string(TOUPPER ${EXTERNAL_NAME} EXTERNAL_NAME_UPPER) include(ExternalProject) ExternalProject_Add( ${EXTERNAL_NAME} - GIT_REPOSITORY https://github.com/matus-chochlik/oglplus.git - GIT_TAG 1aab48f45b40b4ea06a15975fa033b66b237078f + GIT_REPOSITORY https://github.com/jherico/oglplus.git + GIT_TAG e67b24a6e3397c2dc16523bcd5d4c229abd20b81 CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND "" From 43bddf23b4424c5d425945fc6bc66f1a68f188c1 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Tue, 9 Jun 2015 01:03:14 -0700 Subject: [PATCH 28/90] Grabbing correct oglplus commit --- cmake/externals/oglplus/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/externals/oglplus/CMakeLists.txt b/cmake/externals/oglplus/CMakeLists.txt index bfe6f2a20a..23ba0d515e 100644 --- a/cmake/externals/oglplus/CMakeLists.txt +++ b/cmake/externals/oglplus/CMakeLists.txt @@ -5,7 +5,7 @@ include(ExternalProject) ExternalProject_Add( ${EXTERNAL_NAME} GIT_REPOSITORY https://github.com/jherico/oglplus.git - GIT_TAG e67b24a6e3397c2dc16523bcd5d4c229abd20b81 + GIT_TAG 470d8e56fd6bf3913ceec03d82f42d3bafab2cbe CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND "" From e9587d90c4c6902e92c335ff6d1980bd6098515f Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Tue, 9 Jun 2015 01:50:32 -0700 Subject: [PATCH 29/90] Trying to fix linux build --- cmake/externals/boostconfig/CMakeLists.txt | 14 +++++++------- libraries/shared/CMakeLists.txt | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/cmake/externals/boostconfig/CMakeLists.txt b/cmake/externals/boostconfig/CMakeLists.txt index 8785e0d7c7..8494bb0114 100644 --- a/cmake/externals/boostconfig/CMakeLists.txt +++ b/cmake/externals/boostconfig/CMakeLists.txt @@ -3,13 +3,13 @@ string(TOUPPER ${EXTERNAL_NAME} EXTERNAL_NAME_UPPER) include(ExternalProject) ExternalProject_Add( - ${EXTERNAL_NAME} - URL https://github.com/boostorg/config/archive/boost-1.58.0.zip - URL_MD5 42fa673bae2b7645a22736445e80eb8d - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - INSTALL_COMMAND "" - LOG_DOWNLOAD 1 + ${EXTERNAL_NAME} + URL https://github.com/boostorg/config/archive/boost-1.58.0.zip + URL_MD5 42fa673bae2b7645a22736445e80eb8d + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND "" + LOG_DOWNLOAD 1 ) ExternalProject_Get_Property(${EXTERNAL_NAME} SOURCE_DIR) diff --git a/libraries/shared/CMakeLists.txt b/libraries/shared/CMakeLists.txt index 6f7efd1b40..cac8de2ced 100644 --- a/libraries/shared/CMakeLists.txt +++ b/libraries/shared/CMakeLists.txt @@ -11,7 +11,7 @@ find_package(GLM REQUIRED) target_include_directories(${TARGET_NAME} PUBLIC ${GLM_INCLUDE_DIRS}) add_dependency_external_projects(boostconfig) -find_package(BOOSTCONFIG REQUIRED) +find_package(BoostConfig REQUIRED) target_include_directories(${TARGET_NAME} PUBLIC ${BOOSTCONFIG_INCLUDE_DIRS}) add_dependency_external_projects(oglplus) From 5680d58a191c0a3e4a9455e4160133a931f9e543 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Tue, 9 Jun 2015 03:09:10 -0700 Subject: [PATCH 30/90] Removing oglplus requirement for linux and mac --- interface/src/devices/OculusManager.cpp | 5 ----- libraries/shared/src/OglplusHelpers.h | 9 ++++++++- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index 64f12969a0..1fd84bb921 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -177,7 +177,6 @@ ovrLayerEyeFov OculusManager::_sceneLayer; #else -BasicFramebufferWrapper* _transferFbo; ovrTexture OculusManager::_eyeTextures[ovrEye_Count]; GlWindow* OculusManager::_outputWindow{ nullptr }; @@ -310,10 +309,6 @@ void OculusManager::connect(QOpenGLContext* shareContext) { } _outputWindow->showFullScreen(); _outputWindow->makeCurrent(); - _transferFbo = new BasicFramebufferWrapper(); - _transferFbo->Init(toGlm(_renderTargetSize)); - - ovrGLConfig cfg; memset(&cfg, 0, sizeof(cfg)); diff --git a/libraries/shared/src/OglplusHelpers.h b/libraries/shared/src/OglplusHelpers.h index 1a00c021f9..47e7331ce0 100644 --- a/libraries/shared/src/OglplusHelpers.h +++ b/libraries/shared/src/OglplusHelpers.h @@ -7,6 +7,12 @@ // #pragma once +// FIXME support oglplus on all platforms +// For now it's a convenient helper for Windows + +#include + +#ifdef Q_OS_WIN #include "GLMHelpers.h" #define OGLPLUS_USE_GLCOREARB_H 0 @@ -163,4 +169,5 @@ protected: } }; -using BasicFramebufferWrapperPtr = std::shared_ptr; \ No newline at end of file +using BasicFramebufferWrapperPtr = std::shared_ptr; +#endif From 64bb120712ed8f4691e4337281ae8054202566b5 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Tue, 9 Jun 2015 10:25:05 -0700 Subject: [PATCH 31/90] Be a little less heavy handed with the GPU sync --- interface/src/devices/OculusManager.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index 1fd84bb921..6c3a3d84a0 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -710,13 +710,21 @@ void OculusManager::display(QGLWidget * glCanvas, RenderArgs* renderArgs, const Q_ASSERT(OVR_SUCCESS(res)); _swapFbo->Increment(); #else - glFinish(); - GLuint textureId = gpu::GLBackend::getTextureID(finalFbo->getRenderBuffer(0)); + GLsync syncObject = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); + glFlush(); + _outputWindow->makeCurrent(); + // force the compositing context to wait for the texture + // rendering to complete before it starts the distortion rendering, + // but without triggering a CPU/GPU synchronization + glWaitSync(syncObject, 0, GL_TIMEOUT_IGNORED); + + GLuint textureId = gpu::GLBackend::getTextureID(finalFbo->getRenderBuffer(0)); for_each_eye([&](ovrEyeType eye) { ovrGLTexture & glEyeTexture = reinterpret_cast(_eyeTextures[eye]); glEyeTexture.OGL.TexId = textureId; }); + // restore our normal viewport ovrHmd_EndFrame(_ovrHmd, eyeRenderPose, _eyeTextures); glCanvas->makeCurrent(); From 78c3ba0e2cf6005f2a7a5a455c292f6e40774954 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Tue, 9 Jun 2015 10:25:21 -0700 Subject: [PATCH 32/90] Removing dead code --- interface/src/devices/OculusManager.cpp | 15 --------------- interface/src/devices/OculusManager.h | 4 ---- interface/src/ui/ApplicationOverlay.cpp | 1 - 3 files changed, 20 deletions(-) diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index 6c3a3d84a0..ef3a906878 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -740,21 +740,6 @@ void OculusManager::reset() { } } -//Gets the current predicted angles from the oculus sensors -void OculusManager::getEulerAngles(float& yaw, float& pitch, float& roll) { - ovrTrackingState ts = ovrHmd_GetTrackingState(_ovrHmd, ovr_GetTimeInSeconds()); - if (ts.StatusFlags & (ovrStatus_OrientationTracked | ovrStatus_PositionTracked)) { - glm::vec3 euler = glm::eulerAngles(toGlm(ts.HeadPose.ThePose.Orientation)); - yaw = euler.y; - pitch = euler.x; - roll = euler.z; - } else { - yaw = 0.0f; - pitch = 0.0f; - roll = 0.0f; - } -} - glm::vec3 OculusManager::getRelativePosition() { ovrTrackingState trackingState = ovrHmd_GetTrackingState(_ovrHmd, ovr_GetTimeInSeconds()); return toGlm(trackingState.HeadPose.ThePose.Position); diff --git a/interface/src/devices/OculusManager.h b/interface/src/devices/OculusManager.h index f5265f3a74..b82379a7b3 100644 --- a/interface/src/devices/OculusManager.h +++ b/interface/src/devices/OculusManager.h @@ -52,10 +52,6 @@ public: static void display(QGLWidget * glCanvas, RenderArgs* renderArgs, const glm::quat &bodyOrientation, const glm::vec3 &position, Camera& whichCamera); static void reset(); - /// param \yaw[out] yaw in radians - /// param \pitch[out] pitch in radians - /// param \roll[out] roll in radians - static void getEulerAngles(float& yaw, float& pitch, float& roll); static glm::vec3 getRelativePosition(); static glm::quat getOrientation(); static QSize getRenderTargetSize(); diff --git a/interface/src/ui/ApplicationOverlay.cpp b/interface/src/ui/ApplicationOverlay.cpp index 7768b32eed..59ae786008 100644 --- a/interface/src/ui/ApplicationOverlay.cpp +++ b/interface/src/ui/ApplicationOverlay.cpp @@ -573,7 +573,6 @@ void ApplicationOverlay::renderPointers() { _lastMouseMove = usecTimestampNow(); } else if (usecTimestampNow() - _lastMouseMove > MAX_IDLE_TIME * USECS_PER_SECOND) { //float pitch = 0.0f, yaw = 0.0f, roll = 0.0f; // radians - //OculusManager::getEulerAngles(yaw, pitch, roll); glm::quat orientation = qApp->getHeadOrientation(); // (glm::vec3(pitch, yaw, roll)); glm::vec3 result; From 7b355fe69fdf5dc9a5659a2cbb27fe8e86a79a87 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Tue, 9 Jun 2015 10:29:10 -0700 Subject: [PATCH 33/90] Removing build of oglplus and boostconfig on non-Windows --- libraries/shared/CMakeLists.txt | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/libraries/shared/CMakeLists.txt b/libraries/shared/CMakeLists.txt index cac8de2ced..c4159b1190 100644 --- a/libraries/shared/CMakeLists.txt +++ b/libraries/shared/CMakeLists.txt @@ -10,10 +10,12 @@ add_dependency_external_projects(glm) find_package(GLM REQUIRED) target_include_directories(${TARGET_NAME} PUBLIC ${GLM_INCLUDE_DIRS}) -add_dependency_external_projects(boostconfig) -find_package(BoostConfig REQUIRED) -target_include_directories(${TARGET_NAME} PUBLIC ${BOOSTCONFIG_INCLUDE_DIRS}) +if (WIN32) + add_dependency_external_projects(boostconfig) + find_package(BoostConfig REQUIRED) + target_include_directories(${TARGET_NAME} PUBLIC ${BOOSTCONFIG_INCLUDE_DIRS}) -add_dependency_external_projects(oglplus) -find_package(OGLPLUS REQUIRED) -target_include_directories(${TARGET_NAME} PUBLIC ${OGLPLUS_INCLUDE_DIRS}) + add_dependency_external_projects(oglplus) + find_package(OGLPLUS REQUIRED) + target_include_directories(${TARGET_NAME} PUBLIC ${OGLPLUS_INCLUDE_DIRS}) +endif() \ No newline at end of file From e5a9fa8cdcabe8dc99cee9f9bf82988dfcf55fba Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Tue, 9 Jun 2015 11:20:13 -0700 Subject: [PATCH 34/90] Fixing broken declarations --- interface/src/devices/OculusManager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index ef3a906878..271d77bcde 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -199,12 +199,12 @@ float OculusManager::CALIBRATION_DELTA_MINIMUM_LENGTH = 0.02f; float OculusManager::CALIBRATION_DELTA_MINIMUM_ANGLE = 5.0f * RADIANS_PER_DEGREE; float OculusManager::CALIBRATION_ZERO_MAXIMUM_LENGTH = 0.01f; float OculusManager::CALIBRATION_ZERO_MAXIMUM_ANGLE = 2.0f * RADIANS_PER_DEGREE; -uint64_t OculusManager::CALIBRATION_ZERO_HOLD_TIME = 3000000; // usec +quint64 OculusManager::CALIBRATION_ZERO_HOLD_TIME = 3000000; // usec float OculusManager::CALIBRATION_MESSAGE_DISTANCE = 2.5f; OculusManager::CalibrationState OculusManager::_calibrationState; glm::vec3 OculusManager::_calibrationPosition; glm::quat OculusManager::_calibrationOrientation; -uint64_t OculusManager::_calibrationStartTime; +quint64 OculusManager::_calibrationStartTime; int OculusManager::_calibrationMessage = 0; glm::vec3 OculusManager::_eyePositions[ovrEye_Count]; // TODO expose this as a developer toggle From b8b61e7c62a8ad6dd891111064cdedc9cb432502 Mon Sep 17 00:00:00 2001 From: Sam Gondelman Date: Thu, 11 Jun 2015 15:51:21 -0700 Subject: [PATCH 35/90] integrated joysticks with userinputmapper, enabling plug-in-and-play controllers and input mapping with js --- interface/src/Application.cpp | 6 +- interface/src/devices/Joystick.cpp | 177 ++++++++++++++++-- interface/src/devices/Joystick.h | 51 +++-- .../SDL2Manager.cpp} | 101 +++++----- .../SDL2Manager.h} | 82 +++----- interface/src/ui/UserInputMapper.cpp | 5 + interface/src/ui/UserInputMapper.h | 1 + 7 files changed, 278 insertions(+), 145 deletions(-) rename interface/src/{scripting/JoystickScriptingInterface.cpp => devices/SDL2Manager.cpp} (62%) rename interface/src/{scripting/JoystickScriptingInterface.h => devices/SDL2Manager.h} (53%) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 750955dc6a..e126882004 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -113,6 +113,7 @@ #include "devices/Faceshift.h" #include "devices/Leapmotion.h" #include "devices/RealSense.h" +#include "devices/SDL2Manager.h" #include "devices/MIDIManager.h" #include "devices/OculusManager.h" #include "devices/TV3DManager.h" @@ -127,7 +128,6 @@ #include "scripting/AudioDeviceScriptingInterface.h" #include "scripting/ClipboardScriptingInterface.h" #include "scripting/HMDScriptingInterface.h" -#include "scripting/JoystickScriptingInterface.h" #include "scripting/GlobalServicesScriptingInterface.h" #include "scripting/LocationScriptingInterface.h" #include "scripting/MenuScriptingInterface.h" @@ -1455,6 +1455,7 @@ void Application::keyReleaseEvent(QKeyEvent* event) { void Application::focusOutEvent(QFocusEvent* event) { _keyboardMouseDevice.focusOutEvent(event); + SDL2Manager::getInstance()->focusOutEvent(); // synthesize events for keys currently pressed, since we may not get their release events foreach (int key, _keysPressed) { @@ -2450,7 +2451,7 @@ void Application::update(float deltaTime) { } SixenseManager::getInstance().update(deltaTime); - JoystickScriptingInterface::getInstance().update(); + SDL2Manager::getInstance()->update(); } _userInputMapper.update(deltaTime); @@ -4045,7 +4046,6 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEngine* scri scriptEngine->registerGlobalObject("AvatarManager", DependencyManager::get().data()); - scriptEngine->registerGlobalObject("Joysticks", &JoystickScriptingInterface::getInstance()); qScriptRegisterMetaType(scriptEngine, joystickToScriptValue, joystickFromScriptValue); scriptEngine->registerGlobalObject("UndoStack", &_undoStackScriptingInterface); diff --git a/interface/src/devices/Joystick.cpp b/interface/src/devices/Joystick.cpp index 8b225437c2..659e5fa175 100644 --- a/interface/src/devices/Joystick.cpp +++ b/interface/src/devices/Joystick.cpp @@ -13,8 +13,11 @@ #include +#include "Application.h" + #include "Joystick.h" +const float CONTROLLER_THRESHOLD = .25f; #ifdef HAVE_SDL2 const float MAX_AXIS = 32768.0f; @@ -22,10 +25,7 @@ const float MAX_AXIS = 32768.0f; Joystick::Joystick(SDL_JoystickID instanceId, const QString& name, SDL_GameController* sdlGameController) : _sdlGameController(sdlGameController), _sdlJoystick(SDL_GameControllerGetJoystick(_sdlGameController)), - _instanceId(instanceId), - _name(name), - _axes(QVector(SDL_JoystickNumAxes(_sdlJoystick))), - _buttons(QVector(SDL_JoystickNumButtons(_sdlJoystick))) + _instanceId(instanceId) { } @@ -42,24 +42,171 @@ void Joystick::closeJoystick() { #endif } +void Joystick::update() { + for (auto axisState : _axisStateMap) { + if (axisState.second < CONTROLLER_THRESHOLD && axisState.second > -CONTROLLER_THRESHOLD) { + _axisStateMap[axisState.first] = 0; + } + } +} + +void Joystick::focusOutEvent() { + _axisStateMap.clear(); + _buttonPressedMap.clear(); +}; #ifdef HAVE_SDL2 void Joystick::handleAxisEvent(const SDL_ControllerAxisEvent& event) { - if (_axes.size() <= event.axis) { - _axes.resize(event.axis + 1); + SDL_GameControllerAxis axis = (SDL_GameControllerAxis) event.axis; + + if (axis == SDL_CONTROLLER_AXIS_LEFTX) { + _axisStateMap[makeInput(LEFT_AXIS_X_POS).getChannel()] = (event.value > 0) ? event.value / MAX_AXIS : 0.0f; + _axisStateMap[makeInput(LEFT_AXIS_X_NEG).getChannel()] = (event.value < 0) ? -event.value / MAX_AXIS : 0.0f; + } else if (axis == SDL_CONTROLLER_AXIS_LEFTY) { + _axisStateMap[makeInput(LEFT_AXIS_Y_POS).getChannel()] = (event.value > 0) ? event.value / MAX_AXIS : 0.0f; + _axisStateMap[makeInput(LEFT_AXIS_Y_NEG).getChannel()] = (event.value < 0) ? -event.value / MAX_AXIS : 0.0f; + } else if (axis == SDL_CONTROLLER_AXIS_RIGHTX) { + _axisStateMap[makeInput(RIGHT_AXIS_X_POS).getChannel()] = (event.value > 0) ? event.value / MAX_AXIS : 0.0f; + _axisStateMap[makeInput(RIGHT_AXIS_X_NEG).getChannel()] = (event.value < 0) ? -event.value / MAX_AXIS : 0.0f; + } else if (axis == SDL_CONTROLLER_AXIS_RIGHTY) { + _axisStateMap[makeInput(RIGHT_AXIS_Y_POS).getChannel()] = (event.value > 0) ? event.value / MAX_AXIS : 0.0f; + _axisStateMap[makeInput(RIGHT_AXIS_Y_NEG).getChannel()] = (event.value < 0) ? -event.value / MAX_AXIS : 0.0f; } - - float oldValue = _axes[event.axis]; - float newValue = event.value / MAX_AXIS; - _axes[event.axis] = newValue; - - emit axisValueChanged(event.axis, newValue, oldValue); + } void Joystick::handleButtonEvent(const SDL_ControllerButtonEvent& event) { - bool oldValue = _buttons[event.button]; + auto input = makeInput((SDL_GameControllerButton) event.button); bool newValue = event.state == SDL_PRESSED; - _buttons[event.button] = newValue; - emit buttonStateChanged(event.button, newValue, oldValue); + if (newValue) { + _buttonPressedMap.insert(input.getChannel()); + } else { + _buttonPressedMap.erase(input.getChannel()); + } } #endif + + +void Joystick::registerToUserInputMapper(UserInputMapper& mapper) { + // Grab the current free device ID + _deviceID = mapper.getFreeDeviceID(); + + auto proxy = UserInputMapper::DeviceProxy::Pointer(new UserInputMapper::DeviceProxy(_name)); + proxy->getButton = [this] (const UserInputMapper::Input& input, int timestamp) -> bool { return this->getButton(input._channel); }; + proxy->getAxis = [this] (const UserInputMapper::Input& input, int timestamp) -> float { return this->getAxis(input._channel); }; + proxy->getAvailabeInputs = [this] () -> QVector { + QVector availableInputs; +#ifdef HAVE_SDL2 + availableInputs.append(UserInputMapper::InputPair(makeInput(SDL_CONTROLLER_BUTTON_A), "Bottom Button")); + availableInputs.append(UserInputMapper::InputPair(makeInput(SDL_CONTROLLER_BUTTON_B), "Right Button")); + availableInputs.append(UserInputMapper::InputPair(makeInput(SDL_CONTROLLER_BUTTON_X), "Left Button")); + availableInputs.append(UserInputMapper::InputPair(makeInput(SDL_CONTROLLER_BUTTON_Y), "Top Button")); + + availableInputs.append(UserInputMapper::InputPair(makeInput(SDL_CONTROLLER_BUTTON_DPAD_UP), "DPad Up")); + availableInputs.append(UserInputMapper::InputPair(makeInput(SDL_CONTROLLER_BUTTON_DPAD_DOWN), "DPad Down")); + availableInputs.append(UserInputMapper::InputPair(makeInput(SDL_CONTROLLER_BUTTON_DPAD_LEFT), "DPad Left")); + availableInputs.append(UserInputMapper::InputPair(makeInput(SDL_CONTROLLER_BUTTON_DPAD_RIGHT), "DPad Right")); + + availableInputs.append(UserInputMapper::InputPair(makeInput(SDL_CONTROLLER_BUTTON_LEFTSHOULDER), "L1")); + availableInputs.append(UserInputMapper::InputPair(makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), "R1")); +#endif + return availableInputs; + }; + proxy->resetDeviceBindings = [this, &mapper] () -> bool { + mapper.removeAllInputChannelsForDevice(_deviceID); + this->assignDefaultInputMapping(mapper); + return true; + }; + mapper.registerDevice(_deviceID, proxy); +} + +void Joystick::assignDefaultInputMapping(UserInputMapper& mapper) { +#ifdef HAVE_SDL2 + const float JOYSTICK_MOVE_SPEED = 1.0f; + const float DPAD_MOVE_SPEED = .5f; + const float JOYSTICK_YAW_SPEED = 0.5f; + const float JOYSTICK_PITCH_SPEED = 0.25f; + + // Y axes are flipped (up is negative) + // Left Joystick: Movement, strafing + mapper.addInputChannel(UserInputMapper::LONGITUDINAL_FORWARD, makeInput(LEFT_AXIS_Y_NEG), JOYSTICK_MOVE_SPEED); + mapper.addInputChannel(UserInputMapper::LONGITUDINAL_BACKWARD, makeInput(LEFT_AXIS_Y_POS), JOYSTICK_MOVE_SPEED); + mapper.addInputChannel(UserInputMapper::LATERAL_RIGHT, makeInput(LEFT_AXIS_X_POS), JOYSTICK_MOVE_SPEED); + mapper.addInputChannel(UserInputMapper::LATERAL_LEFT, makeInput(LEFT_AXIS_X_NEG), JOYSTICK_MOVE_SPEED); + + // Right Joystick: Camera orientation + mapper.addInputChannel(UserInputMapper::YAW_RIGHT, makeInput(RIGHT_AXIS_X_POS), JOYSTICK_YAW_SPEED); + mapper.addInputChannel(UserInputMapper::YAW_LEFT, makeInput(RIGHT_AXIS_X_NEG), JOYSTICK_YAW_SPEED); + mapper.addInputChannel(UserInputMapper::PITCH_UP, makeInput(RIGHT_AXIS_Y_NEG), JOYSTICK_PITCH_SPEED); + mapper.addInputChannel(UserInputMapper::PITCH_DOWN, makeInput(RIGHT_AXIS_Y_POS), JOYSTICK_PITCH_SPEED); + + // Dpad movement + mapper.addInputChannel(UserInputMapper::LONGITUDINAL_FORWARD, makeInput(SDL_CONTROLLER_BUTTON_DPAD_UP), DPAD_MOVE_SPEED); + mapper.addInputChannel(UserInputMapper::LONGITUDINAL_BACKWARD, makeInput(SDL_CONTROLLER_BUTTON_DPAD_DOWN), DPAD_MOVE_SPEED); + mapper.addInputChannel(UserInputMapper::LATERAL_RIGHT, makeInput(SDL_CONTROLLER_BUTTON_DPAD_RIGHT), DPAD_MOVE_SPEED); + mapper.addInputChannel(UserInputMapper::LATERAL_LEFT, makeInput(SDL_CONTROLLER_BUTTON_DPAD_LEFT), DPAD_MOVE_SPEED); + + // Button controls + mapper.addInputChannel(UserInputMapper::VERTICAL_UP, makeInput(SDL_CONTROLLER_BUTTON_Y), DPAD_MOVE_SPEED); + mapper.addInputChannel(UserInputMapper::VERTICAL_DOWN, makeInput(SDL_CONTROLLER_BUTTON_A), DPAD_MOVE_SPEED); + mapper.addInputChannel(UserInputMapper::YAW_LEFT, makeInput(SDL_CONTROLLER_BUTTON_X), JOYSTICK_YAW_SPEED); + mapper.addInputChannel(UserInputMapper::YAW_RIGHT, makeInput(SDL_CONTROLLER_BUTTON_B), JOYSTICK_YAW_SPEED); + + + // Hold front right shoulder button for precision controls + // Left Joystick: Movement, strafing + mapper.addInputChannel(UserInputMapper::LONGITUDINAL_FORWARD, makeInput(LEFT_AXIS_Y_NEG), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_MOVE_SPEED/2.); + mapper.addInputChannel(UserInputMapper::LONGITUDINAL_BACKWARD, makeInput(LEFT_AXIS_Y_POS), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_MOVE_SPEED/2.); + mapper.addInputChannel(UserInputMapper::LATERAL_RIGHT, makeInput(LEFT_AXIS_X_POS), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_MOVE_SPEED/2.); + mapper.addInputChannel(UserInputMapper::LATERAL_LEFT, makeInput(LEFT_AXIS_X_NEG), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_MOVE_SPEED/2.); + + // Right Joystick: Camera orientation + mapper.addInputChannel(UserInputMapper::YAW_RIGHT, makeInput(RIGHT_AXIS_X_POS), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_YAW_SPEED/2.); + mapper.addInputChannel(UserInputMapper::YAW_LEFT, makeInput(RIGHT_AXIS_X_NEG), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_YAW_SPEED/2.); + mapper.addInputChannel(UserInputMapper::PITCH_UP, makeInput(RIGHT_AXIS_Y_NEG), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_PITCH_SPEED/2.); + mapper.addInputChannel(UserInputMapper::PITCH_DOWN, makeInput(RIGHT_AXIS_Y_POS), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_PITCH_SPEED/2.); + + // Dpad movement + mapper.addInputChannel(UserInputMapper::LONGITUDINAL_FORWARD, makeInput(SDL_CONTROLLER_BUTTON_DPAD_UP), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.); + mapper.addInputChannel(UserInputMapper::LONGITUDINAL_BACKWARD, makeInput(SDL_CONTROLLER_BUTTON_DPAD_DOWN), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.); + mapper.addInputChannel(UserInputMapper::LATERAL_RIGHT, makeInput(SDL_CONTROLLER_BUTTON_DPAD_RIGHT), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.); + mapper.addInputChannel(UserInputMapper::LATERAL_LEFT, makeInput(SDL_CONTROLLER_BUTTON_DPAD_LEFT), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.); + + // Button controls + mapper.addInputChannel(UserInputMapper::VERTICAL_UP, makeInput(SDL_CONTROLLER_BUTTON_Y), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.); + mapper.addInputChannel(UserInputMapper::VERTICAL_DOWN, makeInput(SDL_CONTROLLER_BUTTON_A), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.); + mapper.addInputChannel(UserInputMapper::YAW_LEFT, makeInput(SDL_CONTROLLER_BUTTON_X), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_YAW_SPEED/2.); + mapper.addInputChannel(UserInputMapper::YAW_RIGHT, makeInput(SDL_CONTROLLER_BUTTON_B), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_YAW_SPEED/2.); +#endif +} + +float Joystick::getButton(int channel) const { + if (!_buttonPressedMap.empty()) { + if (_buttonPressedMap.find(channel) != _buttonPressedMap.end()) { + return 1.0f; + } else { + return 0.0f; + } + } + return 0.0f; +} + +float Joystick::getAxis(int channel) const { + auto axis = _axisStateMap.find(channel); + if (axis != _axisStateMap.end()) { + return (*axis).second; + } else { + return 0.0f; + } +} + +#ifdef HAVE_SDL2 +UserInputMapper::Input Joystick::makeInput(SDL_GameControllerButton button) { + return UserInputMapper::Input(_deviceID, button, UserInputMapper::ChannelType::BUTTON); +} +#endif + +UserInputMapper::Input Joystick::makeInput(Joystick::JoystickAxisChannel axis) { + return UserInputMapper::Input(_deviceID, axis, UserInputMapper::ChannelType::AXIS); +} + diff --git a/interface/src/devices/Joystick.h b/interface/src/devices/Joystick.h index eeeeb03759..c5ca7a6f7f 100644 --- a/interface/src/devices/Joystick.h +++ b/interface/src/devices/Joystick.h @@ -20,6 +20,8 @@ #undef main #endif +#include "ui/UserInputMapper.h" + class Joystick : public QObject { Q_OBJECT @@ -29,12 +31,38 @@ class Joystick : public QObject { Q_PROPERTY(int instanceId READ getInstanceId) #endif - Q_PROPERTY(int numAxes READ getNumAxes) - Q_PROPERTY(int numButtons READ getNumButtons) public: + enum JoystickAxisChannel { + LEFT_AXIS_X_POS = 0, + LEFT_AXIS_X_NEG, + LEFT_AXIS_Y_POS, + LEFT_AXIS_Y_NEG, + RIGHT_AXIS_X_POS, + RIGHT_AXIS_X_NEG, + RIGHT_AXIS_Y_POS, + RIGHT_AXIS_Y_NEG, + }; + Joystick(); ~Joystick(); + typedef std::unordered_set ButtonPressedMap; + typedef std::map AxisStateMap; + + float getButton(int channel) const; + float getAxis(int channel) const; + +#ifdef HAVE_SDL2 + UserInputMapper::Input makeInput(SDL_GameControllerButton button); +#endif + UserInputMapper::Input makeInput(Joystick::JoystickAxisChannel axis); + + void registerToUserInputMapper(UserInputMapper& mapper); + void assignDefaultInputMapping(UserInputMapper& mapper); + + void update(); + void focusOutEvent(); + #ifdef HAVE_SDL2 Joystick(SDL_JoystickID instanceId, const QString& name, SDL_GameController* sdlGameController); #endif @@ -51,15 +79,8 @@ public: int getInstanceId() const { return _instanceId; } #endif - const QVector& getAxes() const { return _axes; } - const QVector& getButtons() const { return _buttons; } + int getDeviceID() { return _deviceID; } - int getNumAxes() const { return _axes.size(); } - int getNumButtons() const { return _buttons.size(); } - -signals: - void axisValueChanged(int axis, float newValue, float oldValue); - void buttonStateChanged(int button, float newValue, float oldValue); private: #ifdef HAVE_SDL2 SDL_GameController* _sdlGameController; @@ -68,8 +89,12 @@ private: #endif QString _name; - QVector _axes; - QVector _buttons; + +protected: + int _deviceID = 0; + + ButtonPressedMap _buttonPressedMap; + AxisStateMap _axisStateMap; }; -#endif // hifi_JoystickTracker_h +#endif // hifi_Joystick_h diff --git a/interface/src/scripting/JoystickScriptingInterface.cpp b/interface/src/devices/SDL2Manager.cpp similarity index 62% rename from interface/src/scripting/JoystickScriptingInterface.cpp rename to interface/src/devices/SDL2Manager.cpp index 0490b1f704..32408fce18 100644 --- a/interface/src/scripting/JoystickScriptingInterface.cpp +++ b/interface/src/devices/SDL2Manager.cpp @@ -1,73 +1,66 @@ // -// JoystickScriptingInterface.cpp +// SDL2Manager.cpp // interface/src/devices // -// Created by Andrzej Kapolka on 5/15/14. -// Copyright 2014 High Fidelity, Inc. +// Created by Sam Gondelman on 6/5/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 // #include -#include -#include - -#ifdef HAVE_SDL2 -#include -#undef main -#endif #include #include #include -#include "Application.h" +#include "Application.h" -#include "JoystickScriptingInterface.h" +#include "SDL2Manager.h" #ifdef HAVE_SDL2 -SDL_JoystickID getInstanceId(SDL_GameController* controller) { +SDL_JoystickID SDL2Manager::getInstanceId(SDL_GameController* controller) { SDL_Joystick* joystick = SDL_GameControllerGetJoystick(controller); return SDL_JoystickInstanceID(joystick); } #endif -JoystickScriptingInterface& JoystickScriptingInterface::getInstance() { - static JoystickScriptingInterface sharedInstance; - return sharedInstance; -} - -JoystickScriptingInterface::JoystickScriptingInterface() : +SDL2Manager::SDL2Manager() : #ifdef HAVE_SDL2 - _openJoysticks(), +_openJoysticks(), #endif - _isInitialized(false) +_isInitialized(false) { #ifdef HAVE_SDL2 bool initSuccess = (SDL_Init(SDL_INIT_GAMECONTROLLER) == 0); if (initSuccess) { int joystickCount = SDL_NumJoysticks(); - + for (int i = 0; i < joystickCount; i++) { SDL_GameController* controller = SDL_GameControllerOpen(i); if (controller) { SDL_JoystickID id = getInstanceId(controller); - Joystick* joystick = new Joystick(id, SDL_GameControllerName(controller), controller); - _openJoysticks[id] = joystick; + if (!_openJoysticks.contains(id)) { + Joystick* joystick = new Joystick(id, SDL_GameControllerName(controller), controller); + _openJoysticks[id] = joystick; + joystick->registerToUserInputMapper(*Application::getUserInputMapper()); + joystick->assignDefaultInputMapping(*Application::getUserInputMapper()); + emit joystickAdded(joystick); + } } } - + _isInitialized = true; } else { - qDebug() << "Error initializing SDL"; + qDebug() << "Error initializing SDL2 Manager"; } #endif } -JoystickScriptingInterface::~JoystickScriptingInterface() { +SDL2Manager::~SDL2Manager() { #ifdef HAVE_SDL2 qDeleteAll(_openJoysticks); @@ -75,34 +68,25 @@ JoystickScriptingInterface::~JoystickScriptingInterface() { #endif } -const QObjectList JoystickScriptingInterface::getAllJoysticks() const { - QObjectList objectList; -#ifdef HAVE_SDL2 - const QList joystickList = _openJoysticks.values(); - for (int i = 0; i < joystickList.length(); i++) { - objectList << joystickList[i]; - } -#endif - return objectList; +SDL2Manager* SDL2Manager::getInstance() { + static SDL2Manager sharedInstance; + return &sharedInstance; } -Joystick* JoystickScriptingInterface::joystickWithName(const QString& name) { -#ifdef HAVE_SDL2 - QMap::iterator iter = _openJoysticks.begin(); - while (iter != _openJoysticks.end()) { - if (iter.value()->getName() == name) { - return iter.value(); - } - iter++; +void SDL2Manager::focusOutEvent() { + for (auto joystick : _openJoysticks) { + joystick->focusOutEvent(); } -#endif - return NULL; } -void JoystickScriptingInterface::update() { +void SDL2Manager::update() { #ifdef HAVE_SDL2 if (_isInitialized) { - PerformanceTimer perfTimer("JoystickScriptingInterface::update"); + for (auto joystick : _openJoysticks) { + joystick->update(); + } + + PerformanceTimer perfTimer("SDL2Manager::update"); SDL_GameControllerUpdate(); SDL_Event event; while (SDL_PollEvent(&event)) { @@ -120,16 +104,16 @@ void JoystickScriptingInterface::update() { if (event.cbutton.button == SDL_CONTROLLER_BUTTON_BACK) { // this will either start or stop a global back event QEvent::Type backType = (event.type == SDL_CONTROLLERBUTTONDOWN) - ? HFBackEvent::startType() - : HFBackEvent::endType(); + ? HFBackEvent::startType() + : HFBackEvent::endType(); HFBackEvent backEvent(backType); qApp->sendEvent(qApp, &backEvent); } else if (event.cbutton.button == SDL_CONTROLLER_BUTTON_A) { // this will either start or stop a global action event QEvent::Type actionType = (event.type == SDL_CONTROLLERBUTTONDOWN) - ? HFActionEvent::startType() - : HFActionEvent::endType(); + ? HFActionEvent::startType() + : HFActionEvent::endType(); // global action events fire in the center of the screen Application* app = Application::getInstance(); @@ -141,14 +125,19 @@ void JoystickScriptingInterface::update() { } else if (event.type == SDL_CONTROLLERDEVICEADDED) { SDL_GameController* controller = SDL_GameControllerOpen(event.cdevice.which); - + SDL_JoystickID id = getInstanceId(controller); - Joystick* joystick = new Joystick(id, SDL_GameControllerName(controller), controller); - _openJoysticks[id] = joystick; - emit joystickAdded(joystick); + if (!_openJoysticks.contains(id)) { + Joystick* joystick = new Joystick(id, SDL_GameControllerName(controller), controller); + _openJoysticks[id] = joystick; + joystick->registerToUserInputMapper(*Application::getUserInputMapper()); + joystick->assignDefaultInputMapping(*Application::getUserInputMapper()); + emit joystickAdded(joystick); + } } else if (event.type == SDL_CONTROLLERDEVICEREMOVED) { Joystick* joystick = _openJoysticks[event.cdevice.which]; _openJoysticks.remove(event.cdevice.which); + Application::getUserInputMapper()->removeDevice(joystick->getDeviceID()); emit joystickRemoved(joystick); } } diff --git a/interface/src/scripting/JoystickScriptingInterface.h b/interface/src/devices/SDL2Manager.h similarity index 53% rename from interface/src/scripting/JoystickScriptingInterface.h rename to interface/src/devices/SDL2Manager.h index c9a68d24b1..0a32570ee2 100644 --- a/interface/src/scripting/JoystickScriptingInterface.h +++ b/interface/src/devices/SDL2Manager.h @@ -1,77 +1,46 @@ // -// JoystickScriptingInterface.h +// SDL2Manager.h // interface/src/devices // -// Created by Andrzej Kapolka on 5/15/14. -// Copyright 2014 High Fidelity, Inc. +// Created by Sam Gondelman on 6/5/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 // -#ifndef hifi_JoystickScriptingInterface_h -#define hifi_JoystickScriptingInterface_h - -#include -#include +#ifndef hifi__SDL2Manager_h +#define hifi__SDL2Manager_h #ifdef HAVE_SDL2 #include #endif +#include "ui/UserInputMapper.h" + #include "devices/Joystick.h" -/// Handles joystick input through SDL. -class JoystickScriptingInterface : public QObject { +class SDL2Manager : public QObject { Q_OBJECT - -#ifdef HAVE_SDL2 - Q_PROPERTY(int AXIS_INVALID READ axisInvalid) - Q_PROPERTY(int AXIS_LEFT_X READ axisLeftX) - Q_PROPERTY(int AXIS_LEFT_Y READ axisLeftY) - Q_PROPERTY(int AXIS_RIGHT_X READ axisRightX) - Q_PROPERTY(int AXIS_RIGHT_Y READ axisRightY) - Q_PROPERTY(int AXIS_TRIGGER_LEFT READ axisTriggerLeft) - Q_PROPERTY(int AXIS_TRIGGER_RIGHT READ axisTriggerRight) - Q_PROPERTY(int AXIS_MAX READ axisMax) - - Q_PROPERTY(int BUTTON_INVALID READ buttonInvalid) - Q_PROPERTY(int BUTTON_FACE_BOTTOM READ buttonFaceBottom) - Q_PROPERTY(int BUTTON_FACE_RIGHT READ buttonFaceRight) - Q_PROPERTY(int BUTTON_FACE_LEFT READ buttonFaceLeft) - Q_PROPERTY(int BUTTON_FACE_TOP READ buttonFaceTop) - Q_PROPERTY(int BUTTON_BACK READ buttonBack) - Q_PROPERTY(int BUTTON_GUIDE READ buttonGuide) - Q_PROPERTY(int BUTTON_START READ buttonStart) - Q_PROPERTY(int BUTTON_LEFT_STICK READ buttonLeftStick) - Q_PROPERTY(int BUTTON_RIGHT_STICK READ buttonRightStick) - Q_PROPERTY(int BUTTON_LEFT_SHOULDER READ buttonLeftShoulder) - Q_PROPERTY(int BUTTON_RIGHT_SHOULDER READ buttonRightShoulder) - Q_PROPERTY(int BUTTON_DPAD_UP READ buttonDpadUp) - Q_PROPERTY(int BUTTON_DPAD_DOWN READ buttonDpadDown) - Q_PROPERTY(int BUTTON_DPAD_LEFT READ buttonDpadLeft) - Q_PROPERTY(int BUTTON_DPAD_RIGHT READ buttonDpadRight) - Q_PROPERTY(int BUTTON_MAX READ buttonMax) - - Q_PROPERTY(int BUTTON_PRESSED READ buttonPressed) - Q_PROPERTY(int BUTTON_RELEASED READ buttonRelease) -#endif - + public: - static JoystickScriptingInterface& getInstance(); - + SDL2Manager(); + ~SDL2Manager(); + + void focusOutEvent(); + void update(); - -public slots: - Joystick* joystickWithName(const QString& name); - const QObjectList getAllJoysticks() const; - + + static SDL2Manager* getInstance(); + signals: void joystickAdded(Joystick* joystick); void joystickRemoved(Joystick* joystick); - + private: #ifdef HAVE_SDL2 + SDL_JoystickID getInstanceId(SDL_GameController* controller); + int axisInvalid() const { return SDL_CONTROLLER_AXIS_INVALID; } int axisLeftX() const { return SDL_CONTROLLER_AXIS_LEFTX; } int axisLeftY() const { return SDL_CONTROLLER_AXIS_LEFTY; } @@ -80,7 +49,7 @@ private: int axisTriggerLeft() const { return SDL_CONTROLLER_AXIS_TRIGGERLEFT; } int axisTriggerRight() const { return SDL_CONTROLLER_AXIS_TRIGGERRIGHT; } int axisMax() const { return SDL_CONTROLLER_AXIS_MAX; } - + int buttonInvalid() const { return SDL_CONTROLLER_BUTTON_INVALID; } int buttonFaceBottom() const { return SDL_CONTROLLER_BUTTON_A; } int buttonFaceRight() const { return SDL_CONTROLLER_BUTTON_B; } @@ -98,18 +67,15 @@ private: int buttonDpadLeft() const { return SDL_CONTROLLER_BUTTON_DPAD_LEFT; } int buttonDpadRight() const { return SDL_CONTROLLER_BUTTON_DPAD_RIGHT; } int buttonMax() const { return SDL_CONTROLLER_BUTTON_MAX; } - + int buttonPressed() const { return SDL_PRESSED; } int buttonRelease() const { return SDL_RELEASED; } #endif - - JoystickScriptingInterface(); - ~JoystickScriptingInterface(); - + #ifdef HAVE_SDL2 QMap _openJoysticks; #endif bool _isInitialized; }; -#endif // hifi_JoystickScriptingInterface_h +#endif // hifi__SDL2Manager_h diff --git a/interface/src/ui/UserInputMapper.cpp b/interface/src/ui/UserInputMapper.cpp index e994b3cf30..2c28b79c75 100755 --- a/interface/src/ui/UserInputMapper.cpp +++ b/interface/src/ui/UserInputMapper.cpp @@ -106,6 +106,11 @@ void UserInputMapper::removeAllInputChannelsForDevice(uint16 device) { } } +void UserInputMapper::removeDevice(int device) { + removeAllInputChannelsForDevice((uint16) device); + _registeredDevices.erase(device); +} + int UserInputMapper::getInputChannels(InputChannels& channels) const { for (auto& channel : _actionToInputsMap) { channels.push_back(channel.second); diff --git a/interface/src/ui/UserInputMapper.h b/interface/src/ui/UserInputMapper.h index 0a08e277db..84ca192e3e 100755 --- a/interface/src/ui/UserInputMapper.h +++ b/interface/src/ui/UserInputMapper.h @@ -189,6 +189,7 @@ public: bool removeInputChannel(InputChannel channel); void removeAllInputChannels(); void removeAllInputChannelsForDevice(uint16 device); + void removeDevice(int device); //Grab all the input channels currently in use, return the number int getInputChannels(InputChannels& channels) const; QVector getAllInputsForDevice(uint16 device); From 2bdef6205e5d99f4b7fad1f9fed3dd51ad4b35dd Mon Sep 17 00:00:00 2001 From: Sam Gondelman Date: Thu, 11 Jun 2015 16:20:46 -0700 Subject: [PATCH 36/90] added more available inputs to joystick and keyboardmousedevice --- interface/src/devices/Joystick.cpp | 10 +++++++ interface/src/devices/KeyboardMouseDevice.cpp | 26 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/interface/src/devices/Joystick.cpp b/interface/src/devices/Joystick.cpp index 659e5fa175..43dc50b252 100644 --- a/interface/src/devices/Joystick.cpp +++ b/interface/src/devices/Joystick.cpp @@ -109,6 +109,16 @@ void Joystick::registerToUserInputMapper(UserInputMapper& mapper) { availableInputs.append(UserInputMapper::InputPair(makeInput(SDL_CONTROLLER_BUTTON_LEFTSHOULDER), "L1")); availableInputs.append(UserInputMapper::InputPair(makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), "R1")); + + availableInputs.append(UserInputMapper::InputPair(makeInput(LEFT_AXIS_Y_NEG), "Left Stick Up")); + availableInputs.append(UserInputMapper::InputPair(makeInput(LEFT_AXIS_Y_POS), "Left Stick Down")); + availableInputs.append(UserInputMapper::InputPair(makeInput(LEFT_AXIS_X_POS), "Left Stick Right")); + availableInputs.append(UserInputMapper::InputPair(makeInput(LEFT_AXIS_X_NEG), "Left Stick Left")); + availableInputs.append(UserInputMapper::InputPair(makeInput(RIGHT_AXIS_Y_NEG), "Right Stick Up")); + availableInputs.append(UserInputMapper::InputPair(makeInput(RIGHT_AXIS_Y_POS), "Right Stick Down")); + availableInputs.append(UserInputMapper::InputPair(makeInput(RIGHT_AXIS_X_POS), "Right Stick Right")); + availableInputs.append(UserInputMapper::InputPair(makeInput(RIGHT_AXIS_X_NEG), "Right Stick Left")); + #endif return availableInputs; }; diff --git a/interface/src/devices/KeyboardMouseDevice.cpp b/interface/src/devices/KeyboardMouseDevice.cpp index 8a336064e5..5f18c02c7e 100755 --- a/interface/src/devices/KeyboardMouseDevice.cpp +++ b/interface/src/devices/KeyboardMouseDevice.cpp @@ -170,7 +170,33 @@ void KeyboardMouseDevice::registerToUserInputMapper(UserInputMapper& mapper) { for (int i = (int) Qt::Key_A; i <= (int) Qt::Key_Z; i++) { availableInputs.append(UserInputMapper::InputPair(makeInput(Qt::Key(i)), QKeySequence(Qt::Key(i)).toString())); } + for (int i = (int) Qt::Key_Left; i <= (int) Qt::Key_Down; i++) { + availableInputs.append(UserInputMapper::InputPair(makeInput(Qt::Key(i)), QKeySequence(Qt::Key(i)).toString())); + } availableInputs.append(UserInputMapper::InputPair(makeInput(Qt::Key_Space), QKeySequence(Qt::Key_Space).toString())); + availableInputs.append(UserInputMapper::InputPair(makeInput(Qt::Key_Shift), "Shift")); + availableInputs.append(UserInputMapper::InputPair(makeInput(Qt::Key_PageUp), QKeySequence(Qt::Key_PageUp).toString())); + availableInputs.append(UserInputMapper::InputPair(makeInput(Qt::Key_PageDown), QKeySequence(Qt::Key_PageDown).toString())); + + availableInputs.append(UserInputMapper::InputPair(makeInput(Qt::LeftButton), "Left Mouse Click")); + availableInputs.append(UserInputMapper::InputPair(makeInput(Qt::MiddleButton), "Middle Mouse Click")); + availableInputs.append(UserInputMapper::InputPair(makeInput(Qt::RightButton), "Right Mouse Click")); + + availableInputs.append(UserInputMapper::InputPair(makeInput(MOUSE_AXIS_X_POS), "Mouse Move Right")); + availableInputs.append(UserInputMapper::InputPair(makeInput(MOUSE_AXIS_X_NEG), "Mouse Move Left")); + availableInputs.append(UserInputMapper::InputPair(makeInput(MOUSE_AXIS_Y_POS), "Mouse Move Up")); + availableInputs.append(UserInputMapper::InputPair(makeInput(MOUSE_AXIS_Y_NEG), "Mouse Move Down")); + + availableInputs.append(UserInputMapper::InputPair(makeInput(MOUSE_AXIS_WHEEL_Y_POS), "Mouse Wheel Right")); + availableInputs.append(UserInputMapper::InputPair(makeInput(MOUSE_AXIS_WHEEL_Y_NEG), "Mouse Wheel Left")); + availableInputs.append(UserInputMapper::InputPair(makeInput(MOUSE_AXIS_WHEEL_X_POS), "Mouse Wheel Up")); + availableInputs.append(UserInputMapper::InputPair(makeInput(MOUSE_AXIS_WHEEL_X_NEG), "Mouse Wheel Down")); + + availableInputs.append(UserInputMapper::InputPair(makeInput(TOUCH_AXIS_X_POS), "Touchpad Right")); + availableInputs.append(UserInputMapper::InputPair(makeInput(TOUCH_AXIS_X_NEG), "Touchpad Left")); + availableInputs.append(UserInputMapper::InputPair(makeInput(TOUCH_AXIS_Y_POS), "Touchpad Up")); + availableInputs.append(UserInputMapper::InputPair(makeInput(TOUCH_AXIS_Y_NEG), "Touchpad Down")); + return availableInputs; }; proxy->resetDeviceBindings = [this, &mapper] () -> bool { From 366be3c0c0775860f70fe817c0cbc2c9dc4eeb2d Mon Sep 17 00:00:00 2001 From: Niraj Venkat Date: Thu, 11 Jun 2015 16:27:50 -0700 Subject: [PATCH 37/90] Check if entity looked at has valid hyperlink href attached --- libraries/entities-renderer/src/EntityTreeRenderer.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/libraries/entities-renderer/src/EntityTreeRenderer.cpp b/libraries/entities-renderer/src/EntityTreeRenderer.cpp index 98cbc1f845..cd70eb93af 100644 --- a/libraries/entities-renderer/src/EntityTreeRenderer.cpp +++ b/libraries/entities-renderer/src/EntityTreeRenderer.cpp @@ -919,7 +919,14 @@ void EntityTreeRenderer::mouseMoveEvent(QMouseEvent* event, unsigned int deviceI entityScript.property("mouseMoveEvent").call(entityScript, entityScriptArgs); } - //qCDebug(entitiesrenderer) << "mouseMoveEvent over entity:" << rayPickResult.entityID; + QString urlString = rayPickResult.properties.getHref(); + QUrl url = QUrl(urlString, QUrl::StrictMode); + if (url.isValid() && !url.isEmpty()){ + qCDebug(entitiesrenderer) << "mouseMoveEvent over entity:" << urlString; + } else { + qCDebug(entitiesrenderer) << "mouseMoveEvent over entity:" << "Not valid href"; + } + emit mouseMoveOnEntity(rayPickResult, event, deviceID); if (entityScript.property("mouseMoveOnEntity").isValid()) { entityScript.property("mouseMoveOnEntity").call(entityScript, entityScriptArgs); From 72cc070f0a7df6f1d5d6e5f020dc60fbc482c919 Mon Sep 17 00:00:00 2001 From: Sam Gondelman Date: Thu, 11 Jun 2015 18:24:32 -0700 Subject: [PATCH 38/90] enabled remappable zooming (with keyboard: shift + w, shift + s, and others), switches to first person if you zoom in a lot --- interface/src/Application.cpp | 15 +++++++++++---- interface/src/avatar/Avatar.h | 2 ++ interface/src/avatar/MyAvatar.cpp | 8 ++++++++ interface/src/avatar/MyAvatar.h | 9 +++++++++ interface/src/devices/KeyboardMouseDevice.cpp | 14 +++++++------- 5 files changed, 37 insertions(+), 11 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index e126882004..f66980ab71 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -193,7 +193,6 @@ const QString SKIP_FILENAME = QStandardPaths::writableLocation(QStandardPaths::D const QString DEFAULT_SCRIPTS_JS_URL = "http://s3.amazonaws.com/hifi-public/scripts/defaultScripts.js"; Setting::Handle maxOctreePacketsPerSecond("maxOctreePPS", DEFAULT_MAX_OCTREE_PPS); - #ifdef Q_OS_WIN class MyNativeEventFilter : public QAbstractNativeEventFilter { public: @@ -881,6 +880,10 @@ void Application::paintGL() { } glEnable(GL_LINE_SMOOTH); + + const float CAMERA_PERSON_THRESHOLD = MyAvatar::ZOOM_MIN * _myAvatar->getScale(); + Menu::getInstance()->setIsOptionChecked("First Person", _myAvatar->getBoomLength() * _myAvatar->getScale() <= CAMERA_PERSON_THRESHOLD); + Application::getInstance()->cameraMenuChanged(); if (_myCamera.getMode() == CAMERA_MODE_FIRST_PERSON) { // Always use the default eye position, not the actual head eye position. @@ -899,9 +902,8 @@ void Application::paintGL() { } } else if (_myCamera.getMode() == CAMERA_MODE_THIRD_PERSON) { - static const float THIRD_PERSON_CAMERA_DISTANCE = 1.5f; _myCamera.setPosition(_myAvatar->getDefaultEyePosition() + - _myAvatar->getOrientation() * glm::vec3(0.0f, 0.0f, 1.0f) * THIRD_PERSON_CAMERA_DISTANCE * _myAvatar->getScale()); + _myAvatar->getOrientation() * glm::vec3(0.0f, 0.0f, 1.0f) * _myAvatar->getBoomLength() * _myAvatar->getScale()); if (OculusManager::isConnected()) { _myCamera.setRotation(_myAvatar->getWorldAlignedOrientation()); } else { @@ -2370,10 +2372,14 @@ void Application::cameraMenuChanged() { } else if (Menu::getInstance()->isOptionChecked(MenuOption::FirstPerson)) { if (_myCamera.getMode() != CAMERA_MODE_FIRST_PERSON) { _myCamera.setMode(CAMERA_MODE_FIRST_PERSON); + _myAvatar->setBoomLength(MyAvatar::ZOOM_MIN); } } else { if (_myCamera.getMode() != CAMERA_MODE_THIRD_PERSON) { _myCamera.setMode(CAMERA_MODE_THIRD_PERSON); + if (_myAvatar->getBoomLength() == MyAvatar::ZOOM_MIN) { + _myAvatar->setBoomLength(MyAvatar::ZOOM_DEFAULT); + } } } } @@ -2472,7 +2478,8 @@ void Application::update(float deltaTime) { _myAvatar->setDriveKeys(ROT_DOWN, _userInputMapper.getActionState(UserInputMapper::PITCH_DOWN)); _myAvatar->setDriveKeys(ROT_LEFT, _userInputMapper.getActionState(UserInputMapper::YAW_LEFT)); _myAvatar->setDriveKeys(ROT_RIGHT, _userInputMapper.getActionState(UserInputMapper::YAW_RIGHT)); - + _myAvatar->setDriveKeys(BOOM_IN, _userInputMapper.getActionState(UserInputMapper::BOOM_IN)); + _myAvatar->setDriveKeys(BOOM_OUT, _userInputMapper.getActionState(UserInputMapper::BOOM_OUT)); updateThreads(deltaTime); // If running non-threaded, then give the threads some time to process... diff --git a/interface/src/avatar/Avatar.h b/interface/src/avatar/Avatar.h index b198d12a6e..2590808347 100644 --- a/interface/src/avatar/Avatar.h +++ b/interface/src/avatar/Avatar.h @@ -52,6 +52,8 @@ enum DriveKeys { ROT_RIGHT, ROT_UP, ROT_DOWN, + BOOM_IN, + BOOM_OUT, MAX_DRIVE_KEYS }; diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index c4e08b5dba..6fe99b89e4 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -70,6 +70,10 @@ const int SCRIPTED_MOTOR_CAMERA_FRAME = 0; const int SCRIPTED_MOTOR_AVATAR_FRAME = 1; const int SCRIPTED_MOTOR_WORLD_FRAME = 2; +const float MyAvatar::ZOOM_MIN = .5f; +const float MyAvatar::ZOOM_MAX = 10.0f; +const float MyAvatar::ZOOM_DEFAULT = 1.5f; + MyAvatar::MyAvatar() : Avatar(), _turningKeyPressTime(0.0f), @@ -77,6 +81,7 @@ MyAvatar::MyAvatar() : _wasPushing(false), _isPushing(false), _isBraking(false), + _boomLength(ZOOM_DEFAULT), _trapDuration(0.0f), _thrust(0.0f), _keyboardMotorVelocity(0.0f), @@ -1347,6 +1352,9 @@ glm::vec3 MyAvatar::applyKeyboardMotor(float deltaTime, const glm::vec3& localVe } } } + + _boomLength += _driveKeys[BOOM_OUT] - _driveKeys[BOOM_IN]; + _boomLength = glm::clamp(_boomLength, ZOOM_MIN, ZOOM_MAX); return newLocalVelocity; } diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index a3dc34e6e0..7adaf908f4 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -162,6 +162,13 @@ public: const RecorderPointer getRecorder() const { return _recorder; } const PlayerPointer getPlayer() const { return _player; } + float getBoomLength() const { return _boomLength; } + void setBoomLength(float boomLength) { _boomLength = boomLength; } + + static const float ZOOM_MIN; + static const float ZOOM_MAX; + static const float ZOOM_DEFAULT; + public slots: void increaseSize(); void decreaseSize(); @@ -210,6 +217,8 @@ private: bool _wasPushing; bool _isPushing; bool _isBraking; + + float _boomLength; float _trapDuration; // seconds that avatar has been trapped by collisions glm::vec3 _thrust; // impulse accumulator for outside sources diff --git a/interface/src/devices/KeyboardMouseDevice.cpp b/interface/src/devices/KeyboardMouseDevice.cpp index 5f18c02c7e..aeeb2480e7 100755 --- a/interface/src/devices/KeyboardMouseDevice.cpp +++ b/interface/src/devices/KeyboardMouseDevice.cpp @@ -215,7 +215,7 @@ void KeyboardMouseDevice::assignDefaultInputMapping(UserInputMapper& mapper) { const float MOUSE_PITCH_SPEED = 0.25f; const float TOUCH_YAW_SPEED = 0.5f; const float TOUCH_PITCH_SPEED = 0.25f; - //const float BUTTON_BOOM_SPEED = 0.1f; + const float BUTTON_BOOM_SPEED = 0.1f; // AWSD keys mapping mapper.addInputChannel(UserInputMapper::LONGITUDINAL_BACKWARD, makeInput(Qt::Key_S), BUTTON_MOVE_SPEED); @@ -225,8 +225,8 @@ void KeyboardMouseDevice::assignDefaultInputMapping(UserInputMapper& mapper) { mapper.addInputChannel(UserInputMapper::VERTICAL_DOWN, makeInput(Qt::Key_C), BUTTON_MOVE_SPEED); mapper.addInputChannel(UserInputMapper::VERTICAL_UP, makeInput(Qt::Key_E), BUTTON_MOVE_SPEED); - // mapper.addInputChannel(UserInputMapper::BOOM_IN, makeInput(Qt::Key_W), makeInput(Qt::Key_Shift), BUTTON_BOOM_SPEED); - // mapper.addInputChannel(UserInputMapper::BOOM_OUT, makeInput(Qt::Key_S), makeInput(Qt::Key_Shift), BUTTON_BOOM_SPEED); + mapper.addInputChannel(UserInputMapper::BOOM_IN, makeInput(Qt::Key_W), makeInput(Qt::Key_Shift), BUTTON_BOOM_SPEED); + mapper.addInputChannel(UserInputMapper::BOOM_OUT, makeInput(Qt::Key_S), makeInput(Qt::Key_Shift), BUTTON_BOOM_SPEED); mapper.addInputChannel(UserInputMapper::LATERAL_LEFT, makeInput(Qt::Key_A), makeInput(Qt::RightButton), BUTTON_YAW_SPEED); mapper.addInputChannel(UserInputMapper::LATERAL_RIGHT, makeInput(Qt::Key_D), makeInput(Qt::RightButton), BUTTON_YAW_SPEED); mapper.addInputChannel(UserInputMapper::LATERAL_LEFT, makeInput(Qt::Key_A), makeInput(Qt::Key_Shift), BUTTON_YAW_SPEED); @@ -242,8 +242,8 @@ void KeyboardMouseDevice::assignDefaultInputMapping(UserInputMapper& mapper) { mapper.addInputChannel(UserInputMapper::VERTICAL_DOWN, makeInput(Qt::Key_PageDown), BUTTON_MOVE_SPEED); mapper.addInputChannel(UserInputMapper::VERTICAL_UP, makeInput(Qt::Key_PageUp), BUTTON_MOVE_SPEED); - // mapper.addInputChannel(UserInputMapper::BOOM_IN, makeInput(Qt::Key_Up), makeInput(Qt::Key_Shift), BUTTON_BOOM_SPEED); - // mapper.addInputChannel(UserInputMapper::BOOM_OUT, makeInput(Qt::Key_Down), makeInput(Qt::Key_Shift), BUTTON_BOOM_SPEED); + mapper.addInputChannel(UserInputMapper::BOOM_IN, makeInput(Qt::Key_Up), makeInput(Qt::Key_Shift), BUTTON_BOOM_SPEED); + mapper.addInputChannel(UserInputMapper::BOOM_OUT, makeInput(Qt::Key_Down), makeInput(Qt::Key_Shift), BUTTON_BOOM_SPEED); mapper.addInputChannel(UserInputMapper::LATERAL_LEFT, makeInput(Qt::Key_Left), makeInput(Qt::RightButton), BUTTON_YAW_SPEED); mapper.addInputChannel(UserInputMapper::LATERAL_RIGHT, makeInput(Qt::Key_Right), makeInput(Qt::RightButton), BUTTON_YAW_SPEED); mapper.addInputChannel(UserInputMapper::LATERAL_LEFT, makeInput(Qt::Key_Left), makeInput(Qt::Key_Shift), BUTTON_YAW_SPEED); @@ -272,8 +272,8 @@ void KeyboardMouseDevice::assignDefaultInputMapping(UserInputMapper& mapper) { mapper.addInputChannel(UserInputMapper::YAW_RIGHT, makeInput(TOUCH_AXIS_X_POS), TOUCH_YAW_SPEED); // Wheel move - //mapper.addInputChannel(UserInputMapper::BOOM_IN, makeInput(MOUSE_AXIS_WHEEL_Y_NEG), BUTTON_BOOM_SPEED); - //mapper.addInputChannel(UserInputMapper::BOOM_OUT, makeInput(MOUSE_AXIS_WHEEL_Y_POS), BUTTON_BOOM_SPEED); + mapper.addInputChannel(UserInputMapper::BOOM_IN, makeInput(MOUSE_AXIS_WHEEL_Y_NEG), BUTTON_BOOM_SPEED); + mapper.addInputChannel(UserInputMapper::BOOM_OUT, makeInput(MOUSE_AXIS_WHEEL_Y_POS), BUTTON_BOOM_SPEED); mapper.addInputChannel(UserInputMapper::LATERAL_LEFT, makeInput(MOUSE_AXIS_WHEEL_X_NEG), BUTTON_YAW_SPEED); mapper.addInputChannel(UserInputMapper::LATERAL_RIGHT, makeInput(MOUSE_AXIS_WHEEL_X_POS), BUTTON_YAW_SPEED); From b4e108cd3bcf288f9a09e731dd92639d7c8a1772 Mon Sep 17 00:00:00 2001 From: Sam Gondelman Date: Fri, 12 Jun 2015 10:16:00 -0700 Subject: [PATCH 39/90] added zooming to default joystick controls --- interface/src/Application.cpp | 3 +- interface/src/devices/Joystick.cpp | 47 +++++++++++++++++++++--------- interface/src/devices/Joystick.h | 2 ++ 3 files changed, 37 insertions(+), 15 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index f66980ab71..a3b226dafc 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -881,8 +881,7 @@ void Application::paintGL() { glEnable(GL_LINE_SMOOTH); - const float CAMERA_PERSON_THRESHOLD = MyAvatar::ZOOM_MIN * _myAvatar->getScale(); - Menu::getInstance()->setIsOptionChecked("First Person", _myAvatar->getBoomLength() * _myAvatar->getScale() <= CAMERA_PERSON_THRESHOLD); + Menu::getInstance()->setIsOptionChecked("First Person", _myAvatar->getBoomLength() <= MyAvatar::ZOOM_MIN); Application::getInstance()->cameraMenuChanged(); if (_myCamera.getMode() == CAMERA_MODE_FIRST_PERSON) { diff --git a/interface/src/devices/Joystick.cpp b/interface/src/devices/Joystick.cpp index 43dc50b252..cf1e6bce47 100644 --- a/interface/src/devices/Joystick.cpp +++ b/interface/src/devices/Joystick.cpp @@ -59,20 +59,30 @@ void Joystick::focusOutEvent() { void Joystick::handleAxisEvent(const SDL_ControllerAxisEvent& event) { SDL_GameControllerAxis axis = (SDL_GameControllerAxis) event.axis; - if (axis == SDL_CONTROLLER_AXIS_LEFTX) { - _axisStateMap[makeInput(LEFT_AXIS_X_POS).getChannel()] = (event.value > 0) ? event.value / MAX_AXIS : 0.0f; - _axisStateMap[makeInput(LEFT_AXIS_X_NEG).getChannel()] = (event.value < 0) ? -event.value / MAX_AXIS : 0.0f; - } else if (axis == SDL_CONTROLLER_AXIS_LEFTY) { - _axisStateMap[makeInput(LEFT_AXIS_Y_POS).getChannel()] = (event.value > 0) ? event.value / MAX_AXIS : 0.0f; - _axisStateMap[makeInput(LEFT_AXIS_Y_NEG).getChannel()] = (event.value < 0) ? -event.value / MAX_AXIS : 0.0f; - } else if (axis == SDL_CONTROLLER_AXIS_RIGHTX) { - _axisStateMap[makeInput(RIGHT_AXIS_X_POS).getChannel()] = (event.value > 0) ? event.value / MAX_AXIS : 0.0f; - _axisStateMap[makeInput(RIGHT_AXIS_X_NEG).getChannel()] = (event.value < 0) ? -event.value / MAX_AXIS : 0.0f; - } else if (axis == SDL_CONTROLLER_AXIS_RIGHTY) { - _axisStateMap[makeInput(RIGHT_AXIS_Y_POS).getChannel()] = (event.value > 0) ? event.value / MAX_AXIS : 0.0f; - _axisStateMap[makeInput(RIGHT_AXIS_Y_NEG).getChannel()] = (event.value < 0) ? -event.value / MAX_AXIS : 0.0f; + switch (axis) { + case SDL_CONTROLLER_AXIS_LEFTX: + _axisStateMap[makeInput(LEFT_AXIS_X_POS).getChannel()] = (event.value > 0) ? event.value / MAX_AXIS : 0.0f; + _axisStateMap[makeInput(LEFT_AXIS_X_NEG).getChannel()] = (event.value < 0) ? -event.value / MAX_AXIS : 0.0f; + break; + case SDL_CONTROLLER_AXIS_LEFTY: + _axisStateMap[makeInput(LEFT_AXIS_Y_POS).getChannel()] = (event.value > 0) ? event.value / MAX_AXIS : 0.0f; + _axisStateMap[makeInput(LEFT_AXIS_Y_NEG).getChannel()] = (event.value < 0) ? -event.value / MAX_AXIS : 0.0f; + break; + case SDL_CONTROLLER_AXIS_RIGHTX: + _axisStateMap[makeInput(RIGHT_AXIS_X_POS).getChannel()] = (event.value > 0) ? event.value / MAX_AXIS : 0.0f; + _axisStateMap[makeInput(RIGHT_AXIS_X_NEG).getChannel()] = (event.value < 0) ? -event.value / MAX_AXIS : 0.0f; + break; + case SDL_CONTROLLER_AXIS_RIGHTY: + _axisStateMap[makeInput(RIGHT_AXIS_Y_POS).getChannel()] = (event.value > 0) ? event.value / MAX_AXIS : 0.0f; + _axisStateMap[makeInput(RIGHT_AXIS_Y_NEG).getChannel()] = (event.value < 0) ? -event.value / MAX_AXIS : 0.0f; + break; + case SDL_CONTROLLER_AXIS_TRIGGERRIGHT: + _axisStateMap[makeInput(RIGHT_SHOULDER).getChannel()] = event.value / MAX_AXIS; + break; + case SDL_CONTROLLER_AXIS_TRIGGERLEFT: + _axisStateMap[makeInput(LEFT_SHOULDER).getChannel()] = event.value / MAX_AXIS; + break; } - } void Joystick::handleButtonEvent(const SDL_ControllerButtonEvent& event) { @@ -109,6 +119,8 @@ void Joystick::registerToUserInputMapper(UserInputMapper& mapper) { availableInputs.append(UserInputMapper::InputPair(makeInput(SDL_CONTROLLER_BUTTON_LEFTSHOULDER), "L1")); availableInputs.append(UserInputMapper::InputPair(makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), "R1")); + availableInputs.append(UserInputMapper::InputPair(makeInput(RIGHT_SHOULDER), "L2")); + availableInputs.append(UserInputMapper::InputPair(makeInput(LEFT_SHOULDER), "R2")); availableInputs.append(UserInputMapper::InputPair(makeInput(LEFT_AXIS_Y_NEG), "Left Stick Up")); availableInputs.append(UserInputMapper::InputPair(makeInput(LEFT_AXIS_Y_POS), "Left Stick Down")); @@ -136,6 +148,7 @@ void Joystick::assignDefaultInputMapping(UserInputMapper& mapper) { const float DPAD_MOVE_SPEED = .5f; const float JOYSTICK_YAW_SPEED = 0.5f; const float JOYSTICK_PITCH_SPEED = 0.25f; + const float BOOM_SPEED = 0.1f; // Y axes are flipped (up is negative) // Left Joystick: Movement, strafing @@ -162,6 +175,10 @@ void Joystick::assignDefaultInputMapping(UserInputMapper& mapper) { mapper.addInputChannel(UserInputMapper::YAW_LEFT, makeInput(SDL_CONTROLLER_BUTTON_X), JOYSTICK_YAW_SPEED); mapper.addInputChannel(UserInputMapper::YAW_RIGHT, makeInput(SDL_CONTROLLER_BUTTON_B), JOYSTICK_YAW_SPEED); + // Zoom + mapper.addInputChannel(UserInputMapper::BOOM_IN, makeInput(RIGHT_SHOULDER), BOOM_SPEED); + mapper.addInputChannel(UserInputMapper::BOOM_OUT, makeInput(LEFT_SHOULDER), BOOM_SPEED); + // Hold front right shoulder button for precision controls // Left Joystick: Movement, strafing @@ -187,6 +204,10 @@ void Joystick::assignDefaultInputMapping(UserInputMapper& mapper) { mapper.addInputChannel(UserInputMapper::VERTICAL_DOWN, makeInput(SDL_CONTROLLER_BUTTON_A), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.); mapper.addInputChannel(UserInputMapper::YAW_LEFT, makeInput(SDL_CONTROLLER_BUTTON_X), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_YAW_SPEED/2.); mapper.addInputChannel(UserInputMapper::YAW_RIGHT, makeInput(SDL_CONTROLLER_BUTTON_B), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_YAW_SPEED/2.); + + // Zoom + mapper.addInputChannel(UserInputMapper::BOOM_IN, makeInput(RIGHT_SHOULDER), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), BOOM_SPEED/2.); + mapper.addInputChannel(UserInputMapper::BOOM_OUT, makeInput(LEFT_SHOULDER), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), BOOM_SPEED/2.); #endif } diff --git a/interface/src/devices/Joystick.h b/interface/src/devices/Joystick.h index c5ca7a6f7f..c546a82aaa 100644 --- a/interface/src/devices/Joystick.h +++ b/interface/src/devices/Joystick.h @@ -41,6 +41,8 @@ public: RIGHT_AXIS_X_NEG, RIGHT_AXIS_Y_POS, RIGHT_AXIS_Y_NEG, + RIGHT_SHOULDER, + LEFT_SHOULDER, }; Joystick(); From b9b8cfd60d8f12f2c9b9c02e28bb959e91b4de47 Mon Sep 17 00:00:00 2001 From: Niraj Venkat Date: Fri, 12 Jun 2015 14:08:06 -0700 Subject: [PATCH 40/90] Starting the new address bar layout --- interface/resources/images/arrowcontainer.svg | 3 ++ interface/resources/images/darkgreyarrow.svg | 3 ++ interface/resources/images/lightgreyarrow.svg | 3 ++ interface/resources/images/sepline.svg | 3 ++ interface/resources/qml/AddressBarDialog.qml | 32 +++++++++++++++++-- .../src/EntityTreeRenderer.cpp | 5 ++- 6 files changed, 46 insertions(+), 3 deletions(-) create mode 100644 interface/resources/images/arrowcontainer.svg create mode 100644 interface/resources/images/darkgreyarrow.svg create mode 100644 interface/resources/images/lightgreyarrow.svg create mode 100644 interface/resources/images/sepline.svg diff --git a/interface/resources/images/arrowcontainer.svg b/interface/resources/images/arrowcontainer.svg new file mode 100644 index 0000000000..7f8bd28944 --- /dev/null +++ b/interface/resources/images/arrowcontainer.svg @@ -0,0 +1,3 @@ + + +2015-06-12 18:23ZCanvas 1 Navi Bar diff --git a/interface/resources/images/darkgreyarrow.svg b/interface/resources/images/darkgreyarrow.svg new file mode 100644 index 0000000000..6feb2be586 --- /dev/null +++ b/interface/resources/images/darkgreyarrow.svg @@ -0,0 +1,3 @@ + + +2015-06-12 18:23ZCanvas 1 Navi Bar diff --git a/interface/resources/images/lightgreyarrow.svg b/interface/resources/images/lightgreyarrow.svg new file mode 100644 index 0000000000..defaf8d798 --- /dev/null +++ b/interface/resources/images/lightgreyarrow.svg @@ -0,0 +1,3 @@ + + +2015-06-12 18:23ZCanvas 1 Navi Bar diff --git a/interface/resources/images/sepline.svg b/interface/resources/images/sepline.svg new file mode 100644 index 0000000000..32afaf7148 --- /dev/null +++ b/interface/resources/images/sepline.svg @@ -0,0 +1,3 @@ + + +2015-06-12 18:23ZCanvas 1 Navi Bar diff --git a/interface/resources/qml/AddressBarDialog.qml b/interface/resources/qml/AddressBarDialog.qml index 3377b20d87..5cac0da223 100644 --- a/interface/resources/qml/AddressBarDialog.qml +++ b/interface/resources/qml/AddressBarDialog.qml @@ -45,19 +45,47 @@ DialogContainer { property int inputAreaHeight: 56.0 * root.scale // Height of the background's input area property int inputAreaStep: (height - inputAreaHeight) / 2 + Image { + id: arrowContainer + + source: "../images/arrowcontainer.svg" + + anchors { + fill: parent + leftMargin: parent.height + hifi.layout.spacing * 2 + rightMargin: parent.height + hifi.layout.spacing * 50 + topMargin: parent.inputAreaStep + hifi.layout.spacing + bottomMargin: parent.inputAreaStep + hifi.layout.spacing + } + } + + //Image { + // id: darkGreyArrowBack + + // source: "../images/darkgreyarrow.svg" + + //anchors { + // fill: parent + // leftMargin: parent.height + hifi.layout.spacing * 4 + // rightMargin: parent.height + hifi.layout.spacing * 55 + // topMargin: parent.inputAreaStep + parent.inputAreaStep + hifi.layout.spacing + // bottomMargin: parent.inputAreaStep + parent.inputAreaStep + hifi.layout.spacing + //} + //} + TextInput { id: addressLine anchors { fill: parent - leftMargin: parent.height + hifi.layout.spacing * 2 + leftMargin: parent.height + parent.height + hifi.layout.spacing * 5 rightMargin: hifi.layout.spacing * 2 topMargin: parent.inputAreaStep + hifi.layout.spacing bottomMargin: parent.inputAreaStep + hifi.layout.spacing } - font.pixelSize: hifi.fonts.pixelSize * root.scale + font.pixelSize: hifi.fonts.pixelSize * root.scale * 0.75 helperText: "Go to: place, @user, /path, network address" diff --git a/libraries/entities-renderer/src/EntityTreeRenderer.cpp b/libraries/entities-renderer/src/EntityTreeRenderer.cpp index 9ef32b411e..57bc0ec60e 100644 --- a/libraries/entities-renderer/src/EntityTreeRenderer.cpp +++ b/libraries/entities-renderer/src/EntityTreeRenderer.cpp @@ -48,6 +48,9 @@ #include "RenderablePolyVoxEntityItem.h" #include "EntitiesRendererLogging.h" +#include "DependencyManager.h" +#include "AddressManager.h" + EntityTreeRenderer::EntityTreeRenderer(bool wantScripts, AbstractViewStateInterface* viewState, AbstractScriptingServicesInterface* scriptingServices) : OctreeRenderer(), @@ -921,7 +924,7 @@ void EntityTreeRenderer::mouseMoveEvent(QMouseEvent* event, unsigned int deviceI QString urlString = rayPickResult.properties.getHref(); QUrl url = QUrl(urlString, QUrl::StrictMode); - if (url.isValid() && !url.isEmpty()){ + if (url.isValid() && !url.isEmpty()) { qCDebug(entitiesrenderer) << "mouseMoveEvent over entity:" << urlString; } else { qCDebug(entitiesrenderer) << "mouseMoveEvent over entity:" << "Not valid href"; From 7142be07b69a802d225adf735e0165b0ea887212 Mon Sep 17 00:00:00 2001 From: Niraj Venkat Date: Fri, 12 Jun 2015 17:45:18 -0700 Subject: [PATCH 41/90] New address bar layout with back and forward buttons --- .../resources/images/address-bar.001.svg | 81 ++++++++++++++++++ interface/resources/images/darkgreyarrow.png | Bin 0 -> 369 bytes interface/resources/images/lightgreyarrow.png | Bin 0 -> 369 bytes interface/resources/images/lightgreyarrow.svg | 14 ++- interface/resources/images/sepline.png | Bin 0 -> 127 bytes interface/resources/qml/AddressBarDialog.qml | 54 +++++++++--- 6 files changed, 134 insertions(+), 15 deletions(-) create mode 100644 interface/resources/images/address-bar.001.svg create mode 100644 interface/resources/images/darkgreyarrow.png create mode 100644 interface/resources/images/lightgreyarrow.png create mode 100644 interface/resources/images/sepline.png diff --git a/interface/resources/images/address-bar.001.svg b/interface/resources/images/address-bar.001.svg new file mode 100644 index 0000000000..7734b95be5 --- /dev/null +++ b/interface/resources/images/address-bar.001.svg @@ -0,0 +1,81 @@ + + + + + + image/svg+xml + + + + + + + + + + + + diff --git a/interface/resources/images/darkgreyarrow.png b/interface/resources/images/darkgreyarrow.png new file mode 100644 index 0000000000000000000000000000000000000000..4c9a8a2bbf69185a4a64bce1da6460ba0996b57a GIT binary patch literal 369 zcmV-%0gnEOP)#J37rGx zfCU5K0F*EXn*jn2z`>A!gh|+IazDrdr7hPcmkYG{a=qSbFG(VdizKWliWIIVL7;~F zz%mj7mJGa_ZzTYH!IkTO>IBS0)x-4v90dY1-mc!7rvP9LH^S1rHOjMGO#bqtwd7GQ zqYKap3SiDa?Yb*E0JeO>sZZXOO>RaVA=N=PxrNp++2j^Flud5IP|ly%>AG%ziE>G^ z{94IKldkKYaCg{O49egM?gpEqyisSWVOOSzx`L}jp$vX=Iu7qIf$Mn|gRb&yz(bT?YD?ay+nz0Xi}X@b^0xL?KLG{+pmtFIQSBgb P00000NkvXXu0mjfAz_+$ literal 0 HcmV?d00001 diff --git a/interface/resources/images/lightgreyarrow.png b/interface/resources/images/lightgreyarrow.png new file mode 100644 index 0000000000000000000000000000000000000000..1e221f3c73af148b0cde671a1d14ffdf9d43d75f GIT binary patch literal 369 zcmV-%0gnEOP)%^Hu`8V`qj`n;EIrpw7JNlQCp83a5T3eZtj_~t zrD7I4wj)DAr`U0xZ>a76s-r1fv6B%QU#+){ERVC^5>WL;y<XA9r8U7y*M$)1X#ML@Un$<^*$3PU?JUszyK(FG zOM=x~pRP9e$8qUVKYYf - -2015-06-12 18:23ZCanvas 1 Navi Bar + + + + + + + + + diff --git a/interface/resources/images/sepline.png b/interface/resources/images/sepline.png new file mode 100644 index 0000000000000000000000000000000000000000..959fcee72f740ca4de861595bf835dacad79b9fe GIT binary patch literal 127 zcmeAS@N?(olHy`uVBq!ia0y~yU|?ooU@+uhV_;yApCv5Gz`!6`;u=vBoS#-wo>-L1 z;Fyx1l&avFo0y&&l$w}QS$HzlhJk@W(bL5-q~cc6ojsMG>)13B7?ao~+B+FJdy3pF fuRLd9kzml|VXm>1eSCv~fq}u()z4*}Q$iB}btNK7 literal 0 HcmV?d00001 diff --git a/interface/resources/qml/AddressBarDialog.qml b/interface/resources/qml/AddressBarDialog.qml index 5cac0da223..1ddce9b04d 100644 --- a/interface/resources/qml/AddressBarDialog.qml +++ b/interface/resources/qml/AddressBarDialog.qml @@ -39,12 +39,13 @@ DialogContainer { Image { id: backgroundImage - source: "../images/address-bar.svg" + source: "../images/address-bar.001.svg" width: 576 * root.scale height: 80 * root.scale property int inputAreaHeight: 56.0 * root.scale // Height of the background's input area property int inputAreaStep: (height - inputAreaHeight) / 2 + /* Image { id: arrowContainer @@ -57,21 +58,50 @@ DialogContainer { topMargin: parent.inputAreaStep + hifi.layout.spacing bottomMargin: parent.inputAreaStep + hifi.layout.spacing } + }*/ + + Image { + id: darkGreyArrowBack + + source: "../images/darkgreyarrow.png" + + anchors { + fill: parent + leftMargin: parent.height + hifi.layout.spacing * 2 + rightMargin: parent.height + hifi.layout.spacing * 60 + topMargin: parent.inputAreaStep + parent.inputAreaStep + hifi.layout.spacing + bottomMargin: parent.inputAreaStep + parent.inputAreaStep + hifi.layout.spacing + } } - //Image { - // id: darkGreyArrowBack + Image { + id: seperator - // source: "../images/darkgreyarrow.svg" + source: "../images/sepline.png" - //anchors { - // fill: parent - // leftMargin: parent.height + hifi.layout.spacing * 4 - // rightMargin: parent.height + hifi.layout.spacing * 55 - // topMargin: parent.inputAreaStep + parent.inputAreaStep + hifi.layout.spacing - // bottomMargin: parent.inputAreaStep + parent.inputAreaStep + hifi.layout.spacing - //} - //} + anchors { + fill: parent + leftMargin: parent.height + hifi.layout.spacing * 7 + rightMargin: parent.height + hifi.layout.spacing * 57 + topMargin: parent.inputAreaStep + hifi.layout.spacing + bottomMargin: parent.inputAreaStep + hifi.layout.spacing + } + } + + + Image { + id: lightGreyArrowForward + + source: "../images/lightgreyarrow.png" + + anchors { + fill: parent + leftMargin: parent.height + hifi.layout.spacing * 10 + rightMargin: parent.height + hifi.layout.spacing * 52 + topMargin: parent.inputAreaStep + parent.inputAreaStep + hifi.layout.spacing + bottomMargin: parent.inputAreaStep + parent.inputAreaStep + hifi.layout.spacing + } + } TextInput { id: addressLine From 428b80a50d11fda3b3c33e90e53f14c793759bcf Mon Sep 17 00:00:00 2001 From: Niraj Venkat Date: Fri, 12 Jun 2015 17:49:07 -0700 Subject: [PATCH 42/90] Removing old debug print code --- .../entities-renderer/src/EntityTreeRenderer.cpp | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/libraries/entities-renderer/src/EntityTreeRenderer.cpp b/libraries/entities-renderer/src/EntityTreeRenderer.cpp index 57bc0ec60e..e1bd01547e 100644 --- a/libraries/entities-renderer/src/EntityTreeRenderer.cpp +++ b/libraries/entities-renderer/src/EntityTreeRenderer.cpp @@ -914,22 +914,13 @@ void EntityTreeRenderer::mouseMoveEvent(QMouseEvent* event, unsigned int deviceI bool precisionPicking = false; // for mouse moves we do not do precision picking RayToEntityIntersectionResult rayPickResult = findRayIntersectionWorker(ray, Octree::TryLock, precisionPicking); if (rayPickResult.intersects) { + //qCDebug(entitiesrenderer) << "mouseReleaseEvent over entity:" << rayPickResult.entityID; QScriptValueList entityScriptArgs = createMouseEventArgs(rayPickResult.entityID, event, deviceID); - // load the entity script if needed... QScriptValue entityScript = loadEntityScript(rayPickResult.entity); if (entityScript.property("mouseMoveEvent").isValid()) { entityScript.property("mouseMoveEvent").call(entityScript, entityScriptArgs); } - - QString urlString = rayPickResult.properties.getHref(); - QUrl url = QUrl(urlString, QUrl::StrictMode); - if (url.isValid() && !url.isEmpty()) { - qCDebug(entitiesrenderer) << "mouseMoveEvent over entity:" << urlString; - } else { - qCDebug(entitiesrenderer) << "mouseMoveEvent over entity:" << "Not valid href"; - } - emit mouseMoveOnEntity(rayPickResult, event, deviceID); if (entityScript.property("mouseMoveOnEntity").isValid()) { entityScript.property("mouseMoveOnEntity").call(entityScript, entityScriptArgs); From 1a8df6509fcffe9015573d55051871701682cbdd Mon Sep 17 00:00:00 2001 From: Sam Gondelman Date: Fri, 12 Jun 2015 18:22:56 -0700 Subject: [PATCH 43/90] userinputmapper supports hydra, but some hydra events still register as mouse events --- interface/src/Application.cpp | 1 + interface/src/devices/Joystick.cpp | 6 +- interface/src/devices/KeyboardMouseDevice.cpp | 4 +- interface/src/devices/SixenseManager.cpp | 149 +++++++++++++++++- interface/src/devices/SixenseManager.h | 34 ++++ 5 files changed, 189 insertions(+), 5 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index a3b226dafc..a1ab6d35ae 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1456,6 +1456,7 @@ void Application::keyReleaseEvent(QKeyEvent* event) { void Application::focusOutEvent(QFocusEvent* event) { _keyboardMouseDevice.focusOutEvent(event); + SixenseManager::getInstance().focusOutEvent(); SDL2Manager::getInstance()->focusOutEvent(); // synthesize events for keys currently pressed, since we may not get their release events diff --git a/interface/src/devices/Joystick.cpp b/interface/src/devices/Joystick.cpp index cf1e6bce47..5d7e51b103 100644 --- a/interface/src/devices/Joystick.cpp +++ b/interface/src/devices/Joystick.cpp @@ -82,6 +82,8 @@ void Joystick::handleAxisEvent(const SDL_ControllerAxisEvent& event) { case SDL_CONTROLLER_AXIS_TRIGGERLEFT: _axisStateMap[makeInput(LEFT_SHOULDER).getChannel()] = event.value / MAX_AXIS; break; + default: + break; } } @@ -102,8 +104,8 @@ void Joystick::registerToUserInputMapper(UserInputMapper& mapper) { _deviceID = mapper.getFreeDeviceID(); auto proxy = UserInputMapper::DeviceProxy::Pointer(new UserInputMapper::DeviceProxy(_name)); - proxy->getButton = [this] (const UserInputMapper::Input& input, int timestamp) -> bool { return this->getButton(input._channel); }; - proxy->getAxis = [this] (const UserInputMapper::Input& input, int timestamp) -> float { return this->getAxis(input._channel); }; + proxy->getButton = [this] (const UserInputMapper::Input& input, int timestamp) -> bool { return this->getButton(input.getChannel()); }; + proxy->getAxis = [this] (const UserInputMapper::Input& input, int timestamp) -> float { return this->getAxis(input.getChannel()); }; proxy->getAvailabeInputs = [this] () -> QVector { QVector availableInputs; #ifdef HAVE_SDL2 diff --git a/interface/src/devices/KeyboardMouseDevice.cpp b/interface/src/devices/KeyboardMouseDevice.cpp index aeeb2480e7..fcb60cca26 100755 --- a/interface/src/devices/KeyboardMouseDevice.cpp +++ b/interface/src/devices/KeyboardMouseDevice.cpp @@ -160,8 +160,8 @@ void KeyboardMouseDevice::registerToUserInputMapper(UserInputMapper& mapper) { _deviceID = mapper.getFreeDeviceID(); auto proxy = UserInputMapper::DeviceProxy::Pointer(new UserInputMapper::DeviceProxy("Keyboard")); - proxy->getButton = [this] (const UserInputMapper::Input& input, int timestamp) -> bool { return this->getButton(input._channel); }; - proxy->getAxis = [this] (const UserInputMapper::Input& input, int timestamp) -> float { return this->getAxis(input._channel); }; + proxy->getButton = [this] (const UserInputMapper::Input& input, int timestamp) -> bool { return this->getButton(input.getChannel()); }; + proxy->getAxis = [this] (const UserInputMapper::Input& input, int timestamp) -> float { return this->getAxis(input.getChannel()); }; proxy->getAvailabeInputs = [this] () -> QVector { QVector availableInputs; for (int i = (int) Qt::Key_0; i <= (int) Qt::Key_9; i++) { diff --git a/interface/src/devices/SixenseManager.cpp b/interface/src/devices/SixenseManager.cpp index f1a762e64f..54cf202838 100644 --- a/interface/src/devices/SixenseManager.cpp +++ b/interface/src/devices/SixenseManager.cpp @@ -38,6 +38,10 @@ typedef int (*SixenseTakeIntFunction)(int); typedef int (*SixenseTakeIntAndSixenseControllerData)(int, sixenseControllerData*); #endif +// These bits aren't used for buttons, so they can be used as masks: +const unsigned int LEFT_MASK = 0; +const unsigned int RIGHT_MASK = 1U << 1; + #endif SixenseManager& SixenseManager::getInstance() { @@ -147,6 +151,7 @@ void SixenseManager::update(float deltaTime) { #ifdef HAVE_SIXENSE Hand* hand = DependencyManager::get()->getMyAvatar()->getHand(); if (_isInitialized && _isEnabled) { + _buttonPressedMap.clear(); #ifdef __APPLE__ SixenseBaseFunction sixenseGetNumActiveControllers = (SixenseBaseFunction) _sixenseLibrary->resolve("sixenseGetNumActiveControllers"); @@ -154,12 +159,18 @@ void SixenseManager::update(float deltaTime) { if (sixenseGetNumActiveControllers() == 0) { _hydrasConnected = false; + if (_deviceID) { + Application::getUserInputMapper()->removeDevice(_deviceID); + _deviceID = 0; + } return; } PerformanceTimer perfTimer("sixense"); if (!_hydrasConnected) { _hydrasConnected = true; + registerToUserInputMapper(*Application::getUserInputMapper()); + getInstance().assignDefaultInputMapping(*Application::getUserInputMapper()); UserActivityLogger::getInstance().connectedDevice("spatial_controller", "hydra"); } @@ -216,12 +227,14 @@ void SixenseManager::update(float deltaTime) { palm->setActive(false); // if this isn't a Sixsense ID palm, always make it inactive } - // Read controller buttons and joystick into the hand palm->setControllerButtons(data->buttons); palm->setTrigger(data->trigger); palm->setJoystick(data->joystick_x, data->joystick_y); + handleButtonEvent(data->buttons, numActiveControllers - 1); + handleAxisEvent(data->joystick_x, data->joystick_y, data->trigger, numActiveControllers - 1); + // Emulate the mouse so we can use scripts if (Menu::getInstance()->isOptionChecked(MenuOption::SixenseMouseInput) && !_controllersAtBase) { emulateMouse(palm, numActiveControllers - 1); @@ -590,3 +603,137 @@ void SixenseManager::emulateMouse(PalmData* palm, int index) { #endif // HAVE_SIXENSE +void SixenseManager::focusOutEvent() { + _axisStateMap.clear(); + _buttonPressedMap.clear(); +}; + +void SixenseManager::handleAxisEvent(float stickX, float stickY, float trigger, int index) { + _axisStateMap[makeInput(AXIS_Y_POS, index).getChannel()] = (stickY > 0) ? stickY : 0.0f; + _axisStateMap[makeInput(AXIS_Y_NEG, index).getChannel()] = (stickY < 0) ? -stickY : 0.0f; + _axisStateMap[makeInput(AXIS_X_POS, index).getChannel()] = (stickX > 0) ? stickX : 0.0f; + _axisStateMap[makeInput(AXIS_X_NEG, index).getChannel()] = (stickX < 0) ? -stickX : 0.0f; + _axisStateMap[makeInput(BACK_TRIGGER, index).getChannel()] = trigger; +} + +void SixenseManager::handleButtonEvent(unsigned int buttons, int index) { + if (buttons & BUTTON_0) { + _buttonPressedMap.insert(makeInput(BUTTON_0, index).getChannel()); + } + if (buttons & BUTTON_1) { + _buttonPressedMap.insert(makeInput(BUTTON_1, index).getChannel()); + } + if (buttons & BUTTON_2) { + _buttonPressedMap.insert(makeInput(BUTTON_2, index).getChannel()); + } + if (buttons & BUTTON_3) { + _buttonPressedMap.insert(makeInput(BUTTON_3, index).getChannel()); + } + if (buttons & BUTTON_4) { + _buttonPressedMap.insert(makeInput(BUTTON_4, index).getChannel()); + } + if (buttons & BUTTON_FWD) { + _buttonPressedMap.insert(makeInput(BUTTON_FWD, index).getChannel()); + } +} + +void SixenseManager::registerToUserInputMapper(UserInputMapper& mapper) { + // Grab the current free device ID + _deviceID = mapper.getFreeDeviceID(); + + auto proxy = UserInputMapper::DeviceProxy::Pointer(new UserInputMapper::DeviceProxy("Hydra")); + proxy->getButton = [this] (const UserInputMapper::Input& input, int timestamp) -> bool { return this->getButton(input.getChannel()); }; + proxy->getAxis = [this] (const UserInputMapper::Input& input, int timestamp) -> float { return this->getAxis(input.getChannel()); }; + proxy->getAvailabeInputs = [this] () -> QVector { + QVector availableInputs; + availableInputs.append(UserInputMapper::InputPair(makeInput(BUTTON_0, 0), "Left Start")); + availableInputs.append(UserInputMapper::InputPair(makeInput(BUTTON_1, 0), "Left Button 1")); + availableInputs.append(UserInputMapper::InputPair(makeInput(BUTTON_2, 0), "Left Button 2")); + availableInputs.append(UserInputMapper::InputPair(makeInput(BUTTON_3, 0), "Left Button 3")); + availableInputs.append(UserInputMapper::InputPair(makeInput(BUTTON_4, 0), "Left Button 4")); + + availableInputs.append(UserInputMapper::InputPair(makeInput(BUTTON_FWD, 0), "L1")); + availableInputs.append(UserInputMapper::InputPair(makeInput(BACK_TRIGGER, 0), "L2")); + + availableInputs.append(UserInputMapper::InputPair(makeInput(AXIS_Y_POS, 0), "Left Stick Up")); + availableInputs.append(UserInputMapper::InputPair(makeInput(AXIS_Y_NEG, 0), "Left Stick Down")); + availableInputs.append(UserInputMapper::InputPair(makeInput(AXIS_X_POS, 0), "Left Stick Right")); + availableInputs.append(UserInputMapper::InputPair(makeInput(AXIS_X_NEG, 0), "Left Stick Left")); + + availableInputs.append(UserInputMapper::InputPair(makeInput(BUTTON_0, 1), "Right Start")); + availableInputs.append(UserInputMapper::InputPair(makeInput(BUTTON_1, 1), "Right Button 1")); + availableInputs.append(UserInputMapper::InputPair(makeInput(BUTTON_2, 1), "Right Button 2")); + availableInputs.append(UserInputMapper::InputPair(makeInput(BUTTON_3, 1), "Right Button 3")); + availableInputs.append(UserInputMapper::InputPair(makeInput(BUTTON_4, 1), "Right Button 4")); + + availableInputs.append(UserInputMapper::InputPair(makeInput(BUTTON_FWD, 1), "R1")); + availableInputs.append(UserInputMapper::InputPair(makeInput(BACK_TRIGGER, 1), "R2")); + + availableInputs.append(UserInputMapper::InputPair(makeInput(AXIS_Y_POS, 1), "Right Stick Up")); + availableInputs.append(UserInputMapper::InputPair(makeInput(AXIS_Y_NEG, 1), "Right Stick Down")); + availableInputs.append(UserInputMapper::InputPair(makeInput(AXIS_X_POS, 1), "Right Stick Right")); + availableInputs.append(UserInputMapper::InputPair(makeInput(AXIS_X_NEG, 1), "Right Stick Left")); + return availableInputs; + }; + proxy->resetDeviceBindings = [this, &mapper] () -> bool { + mapper.removeAllInputChannelsForDevice(_deviceID); + this->assignDefaultInputMapping(mapper); + return true; + }; + mapper.registerDevice(_deviceID, proxy); +} + +void SixenseManager::assignDefaultInputMapping(UserInputMapper& mapper) { + const float JOYSTICK_MOVE_SPEED = 1.0f; + const float JOYSTICK_YAW_SPEED = 0.5f; + const float JOYSTICK_PITCH_SPEED = 0.25f; + const float BUTTON_MOVE_SPEED = 1.0f; + const float BOOM_SPEED = .1f; + + // Left Joystick: Movement, strafing + mapper.addInputChannel(UserInputMapper::LONGITUDINAL_FORWARD, makeInput(AXIS_Y_POS, 0), JOYSTICK_MOVE_SPEED); + mapper.addInputChannel(UserInputMapper::LONGITUDINAL_BACKWARD, makeInput(AXIS_Y_NEG, 0), JOYSTICK_MOVE_SPEED); + mapper.addInputChannel(UserInputMapper::LATERAL_RIGHT, makeInput(AXIS_X_POS, 0), JOYSTICK_MOVE_SPEED); + mapper.addInputChannel(UserInputMapper::LATERAL_LEFT, makeInput(AXIS_X_NEG, 0), JOYSTICK_MOVE_SPEED); + + // Right Joystick: Camera orientation + mapper.addInputChannel(UserInputMapper::YAW_RIGHT, makeInput(AXIS_X_POS, 1), JOYSTICK_YAW_SPEED); + mapper.addInputChannel(UserInputMapper::YAW_LEFT, makeInput(AXIS_X_NEG, 1), JOYSTICK_YAW_SPEED); + mapper.addInputChannel(UserInputMapper::PITCH_UP, makeInput(AXIS_Y_POS, 1), JOYSTICK_PITCH_SPEED); + mapper.addInputChannel(UserInputMapper::PITCH_DOWN, makeInput(AXIS_Y_NEG, 1), JOYSTICK_PITCH_SPEED); + + // Buttons + mapper.addInputChannel(UserInputMapper::BOOM_IN, makeInput(BUTTON_3, 0), BOOM_SPEED); + mapper.addInputChannel(UserInputMapper::BOOM_OUT, makeInput(BUTTON_1, 0), BOOM_SPEED); + + mapper.addInputChannel(UserInputMapper::VERTICAL_UP, makeInput(BUTTON_3, 1), BUTTON_MOVE_SPEED); + mapper.addInputChannel(UserInputMapper::VERTICAL_DOWN, makeInput(BUTTON_1, 1), BUTTON_MOVE_SPEED); +} + +float SixenseManager::getButton(int channel) const { + if (!_buttonPressedMap.empty()) { + if (_buttonPressedMap.find(channel) != _buttonPressedMap.end()) { + return 1.0f; + } else { + return 0.0f; + } + } + return 0.0f; +} + +float SixenseManager::getAxis(int channel) const { + auto axis = _axisStateMap.find(channel); + if (axis != _axisStateMap.end()) { + return (*axis).second; + } else { + return 0.0f; + } +} + +UserInputMapper::Input SixenseManager::makeInput(unsigned int button, int index) { + return UserInputMapper::Input(_deviceID, button | (index == 0 ? LEFT_MASK : RIGHT_MASK), UserInputMapper::ChannelType::BUTTON); +} + +UserInputMapper::Input SixenseManager::makeInput(SixenseManager::JoystickAxisChannel axis, int index) { + return UserInputMapper::Input(_deviceID, axis | (index == 0 ? LEFT_MASK : RIGHT_MASK), UserInputMapper::ChannelType::AXIS); +} diff --git a/interface/src/devices/SixenseManager.h b/interface/src/devices/SixenseManager.h index 6f47f2fac9..2ca6b0fb5b 100644 --- a/interface/src/devices/SixenseManager.h +++ b/interface/src/devices/SixenseManager.h @@ -13,6 +13,7 @@ #define hifi_SixenseManager_h #include +#include #ifdef HAVE_SIXENSE #include @@ -25,6 +26,8 @@ #endif +#include "ui/UserInputMapper.h" + class PalmData; const unsigned int BUTTON_0 = 1U << 0; // the skinny button between 1 and 2 @@ -45,6 +48,14 @@ const bool DEFAULT_INVERT_SIXENSE_MOUSE_BUTTONS = false; class SixenseManager : public QObject { Q_OBJECT public: + enum JoystickAxisChannel { + AXIS_Y_POS = 1U << 0, + AXIS_Y_NEG = 1U << 3, + AXIS_X_POS = 1U << 4, + AXIS_X_NEG = 1U << 5, + BACK_TRIGGER = 1U << 6, + }; + static SixenseManager& getInstance(); void initialize(); @@ -60,6 +71,21 @@ public: bool getInvertButtons() const { return _invertButtons; } void setInvertButtons(bool invertSixenseButtons) { _invertButtons = invertSixenseButtons; } + typedef std::unordered_set ButtonPressedMap; + typedef std::map AxisStateMap; + + float getButton(int channel) const; + float getAxis(int channel) const; + + UserInputMapper::Input makeInput(unsigned int button, int index); + UserInputMapper::Input makeInput(JoystickAxisChannel axis, int index); + + void registerToUserInputMapper(UserInputMapper& mapper); + void assignDefaultInputMapping(UserInputMapper& mapper); + + void update(); + void focusOutEvent(); + public slots: void toggleSixense(bool shouldEnable); void setFilter(bool filter); @@ -70,6 +96,8 @@ private: ~SixenseManager(); #ifdef HAVE_SIXENSE + void handleButtonEvent(unsigned int buttons, int index); + void handleAxisEvent(float x, float y, float trigger, int index); void updateCalibration(const sixenseControllerData* controllers); void emulateMouse(PalmData* palm, int index); @@ -110,6 +138,12 @@ private: float _reticleMoveSpeed = DEFAULT_SIXENSE_RETICLE_MOVE_SPEED; bool _invertButtons = DEFAULT_INVERT_SIXENSE_MOUSE_BUTTONS; + +protected: + int _deviceID = 0; + + ButtonPressedMap _buttonPressedMap; + AxisStateMap _axisStateMap; }; #endif // hifi_SixenseManager_h From fe576c6bafe98cdcd0432d0d13ca009f77a6e0bc Mon Sep 17 00:00:00 2001 From: Sam Gondelman Date: Mon, 15 Jun 2015 10:23:24 -0700 Subject: [PATCH 44/90] hands reset when hydras disconnect --- interface/src/devices/SixenseManager.cpp | 10 ++++++++++ interface/src/devices/SixenseManager.h | 1 + 2 files changed, 11 insertions(+) diff --git a/interface/src/devices/SixenseManager.cpp b/interface/src/devices/SixenseManager.cpp index 54cf202838..3927850a44 100644 --- a/interface/src/devices/SixenseManager.cpp +++ b/interface/src/devices/SixenseManager.cpp @@ -65,6 +65,8 @@ SixenseManager::SixenseManager() : _bumperPressed[1] = false; _oldX[1] = -1; _oldY[1] = -1; + _prevPalms[0] = nullptr; + _prevPalms[1] = nullptr; } SixenseManager::~SixenseManager() { @@ -162,6 +164,12 @@ void SixenseManager::update(float deltaTime) { if (_deviceID) { Application::getUserInputMapper()->removeDevice(_deviceID); _deviceID = 0; + if (_prevPalms[0]) { + _prevPalms[0]->setActive(false); + } + if (_prevPalms[1]) { + _prevPalms[1]->setActive(false); + } } return; } @@ -209,6 +217,7 @@ void SixenseManager::update(float deltaTime) { for (size_t j = 0; j < hand->getNumPalms(); j++) { if (hand->getPalms()[j].getSixenseID() == data->controller_index) { palm = &(hand->getPalms()[j]); + _prevPalms[numActiveControllers - 1] = palm; foundHand = true; } } @@ -217,6 +226,7 @@ void SixenseManager::update(float deltaTime) { hand->getPalms().push_back(newPalm); palm = &(hand->getPalms()[hand->getNumPalms() - 1]); palm->setSixenseID(data->controller_index); + _prevPalms[numActiveControllers - 1] = palm; qCDebug(interfaceapp, "Found new Sixense controller, ID %i", data->controller_index); } diff --git a/interface/src/devices/SixenseManager.h b/interface/src/devices/SixenseManager.h index 2ca6b0fb5b..63aa8846ec 100644 --- a/interface/src/devices/SixenseManager.h +++ b/interface/src/devices/SixenseManager.h @@ -132,6 +132,7 @@ private: bool _bumperPressed[2]; int _oldX[2]; int _oldY[2]; + PalmData* _prevPalms[2]; bool _lowVelocityFilter; bool _controllersAtBase; From 40bd747080979be5c69f32a8636c601918cce010 Mon Sep 17 00:00:00 2001 From: Sam Gondelman Date: Mon, 15 Jun 2015 11:13:07 -0700 Subject: [PATCH 45/90] added trigger buttons to hydra, removed hydraMove.js from default scripts --- examples/defaultScripts.js | 1 - interface/src/devices/SixenseManager.cpp | 6 ++++++ interface/src/devices/SixenseManager.h | 1 + 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/examples/defaultScripts.js b/examples/defaultScripts.js index 61bed8d9b1..b5e3e3f551 100644 --- a/examples/defaultScripts.js +++ b/examples/defaultScripts.js @@ -11,7 +11,6 @@ Script.load("progress.js"); Script.load("edit.js"); Script.load("selectAudioDevice.js"); -Script.load("controllers/hydra/hydraMove.js"); Script.load("inspect.js"); Script.load("lobby.js"); Script.load("notifications.js"); diff --git a/interface/src/devices/SixenseManager.cpp b/interface/src/devices/SixenseManager.cpp index 3927850a44..18c7365ef8 100644 --- a/interface/src/devices/SixenseManager.cpp +++ b/interface/src/devices/SixenseManager.cpp @@ -645,6 +645,9 @@ void SixenseManager::handleButtonEvent(unsigned int buttons, int index) { if (buttons & BUTTON_FWD) { _buttonPressedMap.insert(makeInput(BUTTON_FWD, index).getChannel()); } + if (buttons & BUTTON_TRIGGER) { + _buttonPressedMap.insert(makeInput(BUTTON_TRIGGER, index).getChannel()); + } } void SixenseManager::registerToUserInputMapper(UserInputMapper& mapper) { @@ -669,6 +672,7 @@ void SixenseManager::registerToUserInputMapper(UserInputMapper& mapper) { availableInputs.append(UserInputMapper::InputPair(makeInput(AXIS_Y_NEG, 0), "Left Stick Down")); availableInputs.append(UserInputMapper::InputPair(makeInput(AXIS_X_POS, 0), "Left Stick Right")); availableInputs.append(UserInputMapper::InputPair(makeInput(AXIS_X_NEG, 0), "Left Stick Left")); + availableInputs.append(UserInputMapper::InputPair(makeInput(BUTTON_TRIGGER, 0), "Left Trigger Press")); availableInputs.append(UserInputMapper::InputPair(makeInput(BUTTON_0, 1), "Right Start")); availableInputs.append(UserInputMapper::InputPair(makeInput(BUTTON_1, 1), "Right Button 1")); @@ -683,6 +687,8 @@ void SixenseManager::registerToUserInputMapper(UserInputMapper& mapper) { availableInputs.append(UserInputMapper::InputPair(makeInput(AXIS_Y_NEG, 1), "Right Stick Down")); availableInputs.append(UserInputMapper::InputPair(makeInput(AXIS_X_POS, 1), "Right Stick Right")); availableInputs.append(UserInputMapper::InputPair(makeInput(AXIS_X_NEG, 1), "Right Stick Left")); + availableInputs.append(UserInputMapper::InputPair(makeInput(BUTTON_TRIGGER, 1), "Right Trigger Press")); + return availableInputs; }; proxy->resetDeviceBindings = [this, &mapper] () -> bool { diff --git a/interface/src/devices/SixenseManager.h b/interface/src/devices/SixenseManager.h index 63aa8846ec..92cc0742d6 100644 --- a/interface/src/devices/SixenseManager.h +++ b/interface/src/devices/SixenseManager.h @@ -36,6 +36,7 @@ const unsigned int BUTTON_2 = 1U << 6; const unsigned int BUTTON_3 = 1U << 3; const unsigned int BUTTON_4 = 1U << 4; const unsigned int BUTTON_FWD = 1U << 7; +const unsigned int BUTTON_TRIGGER = 1U << 8; // Event type that represents using the controller const unsigned int CONTROLLER_0_EVENT = 1500U; From 4090fd6aa1013fb7043e7054d7e7122c0b243eb4 Mon Sep 17 00:00:00 2001 From: Sam Gondelman Date: Mon, 15 Jun 2015 12:53:14 -0700 Subject: [PATCH 46/90] attempt to fix build errors --- interface/src/devices/SixenseManager.cpp | 8 ++++---- interface/src/devices/SixenseManager.h | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/interface/src/devices/SixenseManager.cpp b/interface/src/devices/SixenseManager.cpp index 18c7365ef8..95a622e7ad 100644 --- a/interface/src/devices/SixenseManager.cpp +++ b/interface/src/devices/SixenseManager.cpp @@ -19,6 +19,10 @@ #include "UserActivityLogger.h" #include "InterfaceLogging.h" +// These bits aren't used for buttons, so they can be used as masks: +const unsigned int LEFT_MASK = 0; +const unsigned int RIGHT_MASK = 1U << 1; + #ifdef HAVE_SIXENSE const int CALIBRATION_STATE_IDLE = 0; @@ -38,10 +42,6 @@ typedef int (*SixenseTakeIntFunction)(int); typedef int (*SixenseTakeIntAndSixenseControllerData)(int, sixenseControllerData*); #endif -// These bits aren't used for buttons, so they can be used as masks: -const unsigned int LEFT_MASK = 0; -const unsigned int RIGHT_MASK = 1U << 1; - #endif SixenseManager& SixenseManager::getInstance() { diff --git a/interface/src/devices/SixenseManager.h b/interface/src/devices/SixenseManager.h index 92cc0742d6..c27b3ca0e2 100644 --- a/interface/src/devices/SixenseManager.h +++ b/interface/src/devices/SixenseManager.h @@ -96,9 +96,9 @@ private: SixenseManager(); ~SixenseManager(); -#ifdef HAVE_SIXENSE void handleButtonEvent(unsigned int buttons, int index); void handleAxisEvent(float x, float y, float trigger, int index); +#ifdef HAVE_SIXENSE void updateCalibration(const sixenseControllerData* controllers); void emulateMouse(PalmData* palm, int index); From 4a00bd3e7f2e30268c3ed4ee46a7f0bfef59d958 Mon Sep 17 00:00:00 2001 From: Seth Alves Date: Mon, 15 Jun 2015 16:06:20 -0700 Subject: [PATCH 47/90] quiet compiler --- libraries/entities/src/EntityItem.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries/entities/src/EntityItem.cpp b/libraries/entities/src/EntityItem.cpp index f64dad0ef4..d2881e5f3a 100644 --- a/libraries/entities/src/EntityItem.cpp +++ b/libraries/entities/src/EntityItem.cpp @@ -67,12 +67,12 @@ EntityItem::EntityItem(const EntityItemID& entityItemID) : _simulatorIDChangedTime(0), _marketplaceID(ENTITY_ITEM_DEFAULT_MARKETPLACE_ID), _name(ENTITY_ITEM_DEFAULT_NAME), + _href(""), + _description(""), _dirtyFlags(0), _element(nullptr), _physicsInfo(nullptr), - _simulated(false), - _href(""), - _description("") + _simulated(false) { quint64 now = usecTimestampNow(); _lastSimulated = now; From 445381bb6bf1dcfc8cf5574b63aa33eea49f49d7 Mon Sep 17 00:00:00 2001 From: Seth Alves Date: Mon, 15 Jun 2015 16:07:28 -0700 Subject: [PATCH 48/90] fix DEFAULT_VOXEL_DATA, recompress voxel data when a script calls setVoxel. Use provided transform when rendering. --- .../src/RenderablePolyVoxEntityItem.cpp | 30 ++++++++++++------- .../src/RenderablePolyVoxEntityItem.h | 3 +- libraries/entities/src/PolyVoxEntityItem.cpp | 21 ++++++++++++- libraries/entities/src/PolyVoxEntityItem.h | 22 +++++++------- 4 files changed, 54 insertions(+), 22 deletions(-) diff --git a/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp b/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp index bb5932d70c..d8e7ca0a18 100644 --- a/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp @@ -121,7 +121,7 @@ void RenderablePolyVoxEntityItem::setVoxelVolumeSize(glm::vec3 voxelVolumeSize) _volData->setBorderValue(255); #ifdef WANT_DEBUG - qDebug() << " new size is" << _volData->getWidth() << _volData->getHeight() << _volData->getDepth(); + qDebug() << " new voxel-space size is" << _volData->getWidth() << _volData->getHeight() << _volData->getDepth(); #endif // I'm not sure this is needed... the docs say that each element is initialized with its default @@ -220,12 +220,15 @@ uint8_t RenderablePolyVoxEntityItem::getVoxel(int x, int y, int z) { return _volData->getVoxelAt(x, y, z); } -void RenderablePolyVoxEntityItem::setVoxel(int x, int y, int z, uint8_t toValue) { +void RenderablePolyVoxEntityItem::setVoxelInternal(int x, int y, int z, uint8_t toValue) { + // set a voxel without recompressing the voxel data assert(_volData); if (!inUserBounds(_volData, _voxelSurfaceStyle, x, y, z)) { return; } + updateOnCount(x, y, z, toValue); + if (_voxelSurfaceStyle == SURFACE_EDGED_CUBIC) { _volData->setVoxelAt(x + 1, y + 1, z + 1, toValue); } else { @@ -234,6 +237,11 @@ void RenderablePolyVoxEntityItem::setVoxel(int x, int y, int z, uint8_t toValue) } +void RenderablePolyVoxEntityItem::setVoxel(int x, int y, int z, uint8_t toValue) { + setVoxelInternal(x, y, z, toValue); + compressVolumeData(); +} + void RenderablePolyVoxEntityItem::updateOnCount(int x, int y, int z, uint8_t toValue) { // keep _onCount up to date if (!inUserBounds(_volData, _voxelSurfaceStyle, x, y, z)) { @@ -259,7 +267,7 @@ void RenderablePolyVoxEntityItem::setAll(uint8_t toValue) { for (int y = 0; y < _voxelVolumeSize.y; y++) { for (int x = 0; x < _voxelVolumeSize.x; x++) { updateOnCount(x, y, z, toValue); - setVoxel(x, y, z, toValue); + setVoxelInternal(x, y, z, toValue); } } } @@ -267,7 +275,7 @@ void RenderablePolyVoxEntityItem::setAll(uint8_t toValue) { } void RenderablePolyVoxEntityItem::setVoxelInVolume(glm::vec3 position, uint8_t toValue) { - updateOnCount(position.x, position.y, position.z, toValue); + // same as setVoxel but takes a vector rather than 3 floats. setVoxel(position.x, position.y, position.z, toValue); } @@ -283,7 +291,7 @@ void RenderablePolyVoxEntityItem::setSphereInVolume(glm::vec3 center, float radi // If the current voxel is less than 'radius' units from the center then we make it solid. if (fDistToCenter <= radius) { updateOnCount(x, y, z, toValue); - setVoxel(x, y, z, toValue); + setVoxelInternal(x, y, z, toValue); } } } @@ -380,10 +388,7 @@ void RenderablePolyVoxEntityItem::render(RenderArgs* args) { getModel(); } - Transform transform; - transform.setTranslation(getPosition() - getRegistrationPoint() * getDimensions()); - transform.setRotation(getRotation()); - transform.setScale(getDimensions() / _voxelVolumeSize); + Transform transform(voxelToWorldMatrix()); auto mesh = _modelGeometry.getMesh(); Q_ASSERT(args->_batch); @@ -514,6 +519,11 @@ void RenderablePolyVoxEntityItem::compressVolumeData() { QByteArray newVoxelData; QDataStream writer(&newVoxelData, QIODevice::WriteOnly | QIODevice::Truncate); + + #ifdef WANT_DEBUG + qDebug() << "compressing voxel data of size:" << voxelXSize << voxelYSize << voxelZSize; + #endif + writer << voxelXSize << voxelYSize << voxelZSize; QByteArray compressedData = qCompress(uncompressedData, 9); @@ -573,7 +583,7 @@ void RenderablePolyVoxEntityItem::decompressVolumeData() { for (int x = 0; x < voxelXSize; x++) { int uncompressedIndex = (z * voxelYSize * voxelXSize) + (y * voxelZSize) + x; updateOnCount(x, y, z, uncompressedData[uncompressedIndex]); - setVoxel(x, y, z, uncompressedData[uncompressedIndex]); + setVoxelInternal(x, y, z, uncompressedData[uncompressedIndex]); } } } diff --git a/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.h b/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.h index 77aeb24f2a..814f3deb07 100644 --- a/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.h +++ b/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.h @@ -73,11 +73,12 @@ public: virtual void setVoxelInVolume(glm::vec3 position, uint8_t toValue); SIMPLE_RENDERABLE(); - + private: // The PolyVoxEntityItem class has _voxelData which contains dimensions and compressed voxel data. The dimensions // may not match _voxelVolumeSize. + void setVoxelInternal(int x, int y, int z, uint8_t toValue); void compressVolumeData(); void decompressVolumeData(); diff --git a/libraries/entities/src/PolyVoxEntityItem.cpp b/libraries/entities/src/PolyVoxEntityItem.cpp index 95ab7d1035..84fbf11311 100644 --- a/libraries/entities/src/PolyVoxEntityItem.cpp +++ b/libraries/entities/src/PolyVoxEntityItem.cpp @@ -23,7 +23,7 @@ const glm::vec3 PolyVoxEntityItem::DEFAULT_VOXEL_VOLUME_SIZE = glm::vec3(32, 32, 32); const float PolyVoxEntityItem::MAX_VOXEL_DIMENSION = 32.0f; -const QByteArray PolyVoxEntityItem::DEFAULT_VOXEL_DATA(qCompress(QByteArray(0), 9)); // XXX +const QByteArray PolyVoxEntityItem::DEFAULT_VOXEL_DATA(PolyVoxEntityItem::makeEmptyVoxelData()); const PolyVoxEntityItem::PolyVoxSurfaceStyle PolyVoxEntityItem::DEFAULT_VOXEL_SURFACE_STYLE = PolyVoxEntityItem::SURFACE_MARCHING_CUBES; @@ -31,6 +31,25 @@ EntityItemPointer PolyVoxEntityItem::factory(const EntityItemID& entityID, const return EntityItemPointer(new PolyVoxEntityItem(entityID, properties)); } + + + +QByteArray PolyVoxEntityItem::makeEmptyVoxelData(quint16 voxelXSize, quint16 voxelYSize, quint16 voxelZSize) { + int rawSize = voxelXSize * voxelYSize * voxelZSize; + + QByteArray uncompressedData = QByteArray(rawSize, '\0'); + QByteArray newVoxelData; + QDataStream writer(&newVoxelData, QIODevice::WriteOnly | QIODevice::Truncate); + writer << voxelXSize << voxelYSize << voxelZSize; + + QByteArray compressedData = qCompress(uncompressedData, 9); + writer << compressedData; + + return newVoxelData; +} + + + PolyVoxEntityItem::PolyVoxEntityItem(const EntityItemID& entityItemID, const EntityItemProperties& properties) : EntityItem(entityItemID), _voxelVolumeSize(PolyVoxEntityItem::DEFAULT_VOXEL_VOLUME_SIZE), diff --git a/libraries/entities/src/PolyVoxEntityItem.h b/libraries/entities/src/PolyVoxEntityItem.h index bf8214675b..33e127e9b2 100644 --- a/libraries/entities/src/PolyVoxEntityItem.h +++ b/libraries/entities/src/PolyVoxEntityItem.h @@ -12,14 +12,14 @@ #ifndef hifi_PolyVoxEntityItem_h #define hifi_PolyVoxEntityItem_h -#include "EntityItem.h" +#include "EntityItem.h" class PolyVoxEntityItem : public EntityItem { public: static EntityItemPointer factory(const EntityItemID& entityID, const EntityItemProperties& properties); PolyVoxEntityItem(const EntityItemID& entityItemID, const EntityItemProperties& properties); - + ALLOW_INSTANTIATION // This class can be instantiated // methods for getting/setting all properties of an entity @@ -29,22 +29,22 @@ class PolyVoxEntityItem : public EntityItem { // TODO: eventually only include properties changed since the params.lastViewFrustumSent time virtual EntityPropertyFlags getEntityProperties(EncodeBitstreamParams& params) const; - virtual void appendSubclassData(OctreePacketData* packetData, EncodeBitstreamParams& params, + virtual void appendSubclassData(OctreePacketData* packetData, EncodeBitstreamParams& params, EntityTreeElementExtraEncodeData* modelTreeElementExtraEncodeData, EntityPropertyFlags& requestedProperties, EntityPropertyFlags& propertyFlags, EntityPropertyFlags& propertiesDidntFit, - int& propertyCount, + int& propertyCount, OctreeElement::AppendState& appendState) const; - virtual int readEntitySubclassDataFromBuffer(const unsigned char* data, int bytesLeftToRead, + virtual int readEntitySubclassDataFromBuffer(const unsigned char* data, int bytesLeftToRead, ReadBitstreamToTreeParams& args, EntityPropertyFlags& propertyFlags, bool overwriteLocalData); - + // never have a ray intersection pick a PolyVoxEntityItem. virtual bool supportsDetailedRayIntersection() const { return true; } virtual bool findDetailedRayIntersection(const glm::vec3& origin, const glm::vec3& direction, - bool& keepSearching, OctreeElement*& element, float& distance, BoxFace& face, + bool& keepSearching, OctreeElement*& element, float& distance, BoxFace& face, void** intersectedObject, bool precisionPicking) const { return false; } virtual void debugDump() const; @@ -58,12 +58,12 @@ class PolyVoxEntityItem : public EntityItem { enum PolyVoxSurfaceStyle { SURFACE_MARCHING_CUBES, SURFACE_CUBIC, - SURFACE_EDGED_CUBIC + SURFACE_EDGED_CUBIC }; virtual void setVoxelSurfaceStyle(PolyVoxSurfaceStyle voxelSurfaceStyle) { _voxelSurfaceStyle = voxelSurfaceStyle; } virtual void setVoxelSurfaceStyle(uint16_t voxelSurfaceStyle) { - setVoxelSurfaceStyle((PolyVoxSurfaceStyle) voxelSurfaceStyle); + setVoxelSurfaceStyle((PolyVoxSurfaceStyle) voxelSurfaceStyle); } virtual PolyVoxSurfaceStyle getVoxelSurfaceStyle() const { return _voxelSurfaceStyle; } @@ -82,15 +82,17 @@ class PolyVoxEntityItem : public EntityItem { virtual void setAll(uint8_t toValue) {} virtual void setVoxelInVolume(glm::vec3 position, uint8_t toValue) {} - + virtual uint8_t getVoxel(int x, int y, int z) { return 0; } virtual void setVoxel(int x, int y, int z, uint8_t toValue) {} + static QByteArray makeEmptyVoxelData(quint16 voxelXSize = 16, quint16 voxelYSize = 16, quint16 voxelZSize = 16); protected: glm::vec3 _voxelVolumeSize; // this is always 3 bytes QByteArray _voxelData; PolyVoxSurfaceStyle _voxelSurfaceStyle; + }; #endif // hifi_PolyVoxEntityItem_h From 6def25de92a2409b025f09ba17c2c90a4ea3a607 Mon Sep 17 00:00:00 2001 From: Seth Alves Date: Mon, 15 Jun 2015 16:22:06 -0700 Subject: [PATCH 49/90] formatting --- libraries/entities/src/PolyVoxEntityItem.h | 1 - 1 file changed, 1 deletion(-) diff --git a/libraries/entities/src/PolyVoxEntityItem.h b/libraries/entities/src/PolyVoxEntityItem.h index 33e127e9b2..e5d511c087 100644 --- a/libraries/entities/src/PolyVoxEntityItem.h +++ b/libraries/entities/src/PolyVoxEntityItem.h @@ -92,7 +92,6 @@ class PolyVoxEntityItem : public EntityItem { glm::vec3 _voxelVolumeSize; // this is always 3 bytes QByteArray _voxelData; PolyVoxSurfaceStyle _voxelSurfaceStyle; - }; #endif // hifi_PolyVoxEntityItem_h From a24e0f7b1423953baf4237be7f5f3935471742e0 Mon Sep 17 00:00:00 2001 From: Niraj Venkat Date: Tue, 16 Jun 2015 09:50:03 -0700 Subject: [PATCH 50/90] Finishing up new address bar layout --- .../resources/images/address-bar.001.svg | 81 ------------------- interface/resources/images/address-bar.svg | 26 ++++-- interface/resources/images/arrowcontainer.svg | 3 - interface/resources/images/darkgreyarrow.svg | 14 +++- interface/resources/images/left-arrow.svg | 50 ++++++++++++ interface/resources/qml/AddressBarDialog.qml | 50 +++--------- 6 files changed, 94 insertions(+), 130 deletions(-) delete mode 100644 interface/resources/images/address-bar.001.svg delete mode 100644 interface/resources/images/arrowcontainer.svg create mode 100644 interface/resources/images/left-arrow.svg diff --git a/interface/resources/images/address-bar.001.svg b/interface/resources/images/address-bar.001.svg deleted file mode 100644 index 7734b95be5..0000000000 --- a/interface/resources/images/address-bar.001.svg +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/interface/resources/images/address-bar.svg b/interface/resources/images/address-bar.svg index 0a472cbe4e..dd907aa6c9 100644 --- a/interface/resources/images/address-bar.svg +++ b/interface/resources/images/address-bar.svg @@ -15,7 +15,7 @@ viewBox="0 0 1440 200" id="svg4136" inkscape:version="0.91 r13725" - sodipodi:docname="address-bar.svg"> + sodipodi:docname="address-bar.002.svg"> @@ -39,14 +39,14 @@ guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" - inkscape:window-width="1840" + inkscape:window-width="1835" inkscape:window-height="1057" id="namedview4140" showgrid="false" - inkscape:zoom="0.8671875" - inkscape:cx="707.02439" + inkscape:zoom="0.61319416" + inkscape:cx="132.58366" inkscape:cy="52.468468" - inkscape:window-x="72" + inkscape:window-x="77" inkscape:window-y="-8" inkscape:window-maximized="1" inkscape:current-layer="svg4136" /> @@ -59,6 +59,15 @@ y="30" rx="16.025024" ry="17.019567" /> + + diff --git a/interface/resources/images/arrowcontainer.svg b/interface/resources/images/arrowcontainer.svg deleted file mode 100644 index 7f8bd28944..0000000000 --- a/interface/resources/images/arrowcontainer.svg +++ /dev/null @@ -1,3 +0,0 @@ - - -2015-06-12 18:23ZCanvas 1 Navi Bar diff --git a/interface/resources/images/darkgreyarrow.svg b/interface/resources/images/darkgreyarrow.svg index 6feb2be586..2d049d90d7 100644 --- a/interface/resources/images/darkgreyarrow.svg +++ b/interface/resources/images/darkgreyarrow.svg @@ -1,3 +1,11 @@ - - -2015-06-12 18:23ZCanvas 1 Navi Bar + + + + + + + + + diff --git a/interface/resources/images/left-arrow.svg b/interface/resources/images/left-arrow.svg new file mode 100644 index 0000000000..cede9fa959 --- /dev/null +++ b/interface/resources/images/left-arrow.svg @@ -0,0 +1,50 @@ + + + +image/svg+xml \ No newline at end of file diff --git a/interface/resources/qml/AddressBarDialog.qml b/interface/resources/qml/AddressBarDialog.qml index 1ddce9b04d..e80c5f2aa5 100644 --- a/interface/resources/qml/AddressBarDialog.qml +++ b/interface/resources/qml/AddressBarDialog.qml @@ -39,68 +39,42 @@ DialogContainer { Image { id: backgroundImage - source: "../images/address-bar.001.svg" + source: "../images/address-bar.svg" width: 576 * root.scale height: 80 * root.scale property int inputAreaHeight: 56.0 * root.scale // Height of the background's input area property int inputAreaStep: (height - inputAreaHeight) / 2 - /* Image { - id: arrowContainer + id: backArrow - source: "../images/arrowcontainer.svg" + source: "../images/left-arrow.svg" + scale: 0.9 anchors { fill: parent - leftMargin: parent.height + hifi.layout.spacing * 2 - rightMargin: parent.height + hifi.layout.spacing * 50 - topMargin: parent.inputAreaStep + hifi.layout.spacing - bottomMargin: parent.inputAreaStep + hifi.layout.spacing - } - }*/ - - Image { - id: darkGreyArrowBack - - source: "../images/darkgreyarrow.png" - - anchors { - fill: parent - leftMargin: parent.height + hifi.layout.spacing * 2 + leftMargin: parent.height + hifi.layout.spacing + 6 rightMargin: parent.height + hifi.layout.spacing * 60 topMargin: parent.inputAreaStep + parent.inputAreaStep + hifi.layout.spacing bottomMargin: parent.inputAreaStep + parent.inputAreaStep + hifi.layout.spacing } } - - Image { - id: seperator - - source: "../images/sepline.png" - - anchors { - fill: parent - leftMargin: parent.height + hifi.layout.spacing * 7 - rightMargin: parent.height + hifi.layout.spacing * 57 - topMargin: parent.inputAreaStep + hifi.layout.spacing - bottomMargin: parent.inputAreaStep + hifi.layout.spacing - } - } - Image { - id: lightGreyArrowForward + id: forwardArrow - source: "../images/lightgreyarrow.png" + source: "../images/darkgreyarrow.svg" anchors { fill: parent - leftMargin: parent.height + hifi.layout.spacing * 10 - rightMargin: parent.height + hifi.layout.spacing * 52 + leftMargin: parent.height + hifi.layout.spacing * 9 + rightMargin: parent.height + hifi.layout.spacing * 53 topMargin: parent.inputAreaStep + parent.inputAreaStep + hifi.layout.spacing bottomMargin: parent.inputAreaStep + parent.inputAreaStep + hifi.layout.spacing } + + width: parent.width * 0.5 + height: parent.height * 0.5 } TextInput { From 8241a2170baa0e7d95e757e1e32b54fc78f8532f Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Tue, 16 Jun 2015 09:50:42 -0700 Subject: [PATCH 51/90] Update cube, line, and sphere overlays to use batches --- interface/src/ui/overlays/Cube3DOverlay.cpp | 228 +++++++++++------- interface/src/ui/overlays/Line3DOverlay.cpp | 66 +++-- interface/src/ui/overlays/Sphere3DOverlay.cpp | 58 +++-- 3 files changed, 222 insertions(+), 130 deletions(-) diff --git a/interface/src/ui/overlays/Cube3DOverlay.cpp b/interface/src/ui/overlays/Cube3DOverlay.cpp index 6fc9fe6e27..73406c07a0 100644 --- a/interface/src/ui/overlays/Cube3DOverlay.cpp +++ b/interface/src/ui/overlays/Cube3DOverlay.cpp @@ -35,13 +35,6 @@ void Cube3DOverlay::render(RenderArgs* args) { return; // do nothing if we're not visible } - - float glowLevel = getGlowLevel(); - Glower* glower = NULL; - if (glowLevel > 0.0f) { - glower = new Glower(glowLevel); - } - float alpha = getAlpha(); xColor color = getColor(); const float MAX_COLOR = 255.0f; @@ -49,91 +42,162 @@ void Cube3DOverlay::render(RenderArgs* args) { //glDisable(GL_LIGHTING); - // TODO: handle registration point?? + // TODO: handle registration point?? glm::vec3 position = getPosition(); glm::vec3 center = getCenter(); glm::vec3 dimensions = getDimensions(); glm::quat rotation = getRotation(); - - glPushMatrix(); - glTranslatef(position.x, position.y, position.z); - glm::vec3 axis = glm::axis(rotation); - glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); - glPushMatrix(); - glm::vec3 positionToCenter = center - position; - glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); - if (_isSolid) { - if (_borderSize > 0) { - // Draw a cube at a larger size behind the main cube, creating - // a border effect. - // Disable writing to the depth mask so that the "border" cube will not - // occlude the main cube. This means the border could be covered by - // overlays that are further back and drawn later, but this is good - // enough for the use-case. - glDepthMask(GL_FALSE); - glPushMatrix(); - glScalef(dimensions.x * _borderSize, dimensions.y * _borderSize, dimensions.z * _borderSize); - if (_drawOnHUD) { - DependencyManager::get()->renderSolidCube(1.0f, glm::vec4(1.0f, 1.0f, 1.0f, alpha)); - } else { - DependencyManager::get()->renderSolidCube(1.0f, glm::vec4(1.0f, 1.0f, 1.0f, alpha)); - } + auto batch = args->_batch; - glPopMatrix(); - glDepthMask(GL_TRUE); - } + if (batch) { + Transform transform; + transform.setTranslation(position); + transform.setRotation(rotation); + if (_isSolid) { + // if (_borderSize > 0) { + // // Draw a cube at a larger size behind the main cube, creating + // // a border effect. + // // Disable writing to the depth mask so that the "border" cube will not + // // occlude the main cube. This means the border could be covered by + // // overlays that are further back and drawn later, but this is good + // // enough for the use-case. + // transform.setScale(dimensions * _borderSize); + // batch->setModelTransform(transform); + // DependencyManager::get()->renderSolidCube(*batch, 1.0f, glm::vec4(1.0f, 1.0f, 1.0f, alpha)); + // } + + transform.setScale(dimensions); + batch->setModelTransform(transform); + + DependencyManager::get()->renderSolidCube(*batch, 1.0f, cubeColor); + } else { + + if (getIsDashedLine()) { + transform.setScale(1.0f); + batch->setModelTransform(transform); + + glm::vec3 halfDimensions = dimensions / 2.0f; + glm::vec3 bottomLeftNear(-halfDimensions.x, -halfDimensions.y, -halfDimensions.z); + glm::vec3 bottomRightNear(halfDimensions.x, -halfDimensions.y, -halfDimensions.z); + glm::vec3 topLeftNear(-halfDimensions.x, halfDimensions.y, -halfDimensions.z); + glm::vec3 topRightNear(halfDimensions.x, halfDimensions.y, -halfDimensions.z); + + glm::vec3 bottomLeftFar(-halfDimensions.x, -halfDimensions.y, halfDimensions.z); + glm::vec3 bottomRightFar(halfDimensions.x, -halfDimensions.y, halfDimensions.z); + glm::vec3 topLeftFar(-halfDimensions.x, halfDimensions.y, halfDimensions.z); + glm::vec3 topRightFar(halfDimensions.x, halfDimensions.y, halfDimensions.z); + + auto geometryCache = DependencyManager::get(); + + geometryCache->renderDashedLine(*batch, bottomLeftNear, bottomRightNear, cubeColor); + geometryCache->renderDashedLine(*batch, bottomRightNear, bottomRightFar, cubeColor); + geometryCache->renderDashedLine(*batch, bottomRightFar, bottomLeftFar, cubeColor); + geometryCache->renderDashedLine(*batch, bottomLeftFar, bottomLeftNear, cubeColor); + + geometryCache->renderDashedLine(*batch, topLeftNear, topRightNear, cubeColor); + geometryCache->renderDashedLine(*batch, topRightNear, topRightFar, cubeColor); + geometryCache->renderDashedLine(*batch, topRightFar, topLeftFar, cubeColor); + geometryCache->renderDashedLine(*batch, topLeftFar, topLeftNear, cubeColor); + + geometryCache->renderDashedLine(*batch, bottomLeftNear, topLeftNear, cubeColor); + geometryCache->renderDashedLine(*batch, bottomRightNear, topRightNear, cubeColor); + geometryCache->renderDashedLine(*batch, bottomLeftFar, topLeftFar, cubeColor); + geometryCache->renderDashedLine(*batch, bottomRightFar, topRightFar, cubeColor); - glPushMatrix(); - glScalef(dimensions.x, dimensions.y, dimensions.z); - if (_drawOnHUD) { - DependencyManager::get()->renderSolidCube(1.0f, cubeColor); - } else { - DependencyManager::get()->renderSolidCube(1.0f, cubeColor); - } - glPopMatrix(); } else { - glLineWidth(_lineWidth); - - if (getIsDashedLine()) { - glm::vec3 halfDimensions = dimensions / 2.0f; - glm::vec3 bottomLeftNear(-halfDimensions.x, -halfDimensions.y, -halfDimensions.z); - glm::vec3 bottomRightNear(halfDimensions.x, -halfDimensions.y, -halfDimensions.z); - glm::vec3 topLeftNear(-halfDimensions.x, halfDimensions.y, -halfDimensions.z); - glm::vec3 topRightNear(halfDimensions.x, halfDimensions.y, -halfDimensions.z); - - glm::vec3 bottomLeftFar(-halfDimensions.x, -halfDimensions.y, halfDimensions.z); - glm::vec3 bottomRightFar(halfDimensions.x, -halfDimensions.y, halfDimensions.z); - glm::vec3 topLeftFar(-halfDimensions.x, halfDimensions.y, halfDimensions.z); - glm::vec3 topRightFar(halfDimensions.x, halfDimensions.y, halfDimensions.z); - - auto geometryCache = DependencyManager::get(); - - geometryCache->renderDashedLine(bottomLeftNear, bottomRightNear, cubeColor); - geometryCache->renderDashedLine(bottomRightNear, bottomRightFar, cubeColor); - geometryCache->renderDashedLine(bottomRightFar, bottomLeftFar, cubeColor); - geometryCache->renderDashedLine(bottomLeftFar, bottomLeftNear, cubeColor); - - geometryCache->renderDashedLine(topLeftNear, topRightNear, cubeColor); - geometryCache->renderDashedLine(topRightNear, topRightFar, cubeColor); - geometryCache->renderDashedLine(topRightFar, topLeftFar, cubeColor); - geometryCache->renderDashedLine(topLeftFar, topLeftNear, cubeColor); - - geometryCache->renderDashedLine(bottomLeftNear, topLeftNear, cubeColor); - geometryCache->renderDashedLine(bottomRightNear, topRightNear, cubeColor); - geometryCache->renderDashedLine(bottomLeftFar, topLeftFar, cubeColor); - geometryCache->renderDashedLine(bottomRightFar, topRightFar, cubeColor); - - } else { - glScalef(dimensions.x, dimensions.y, dimensions.z); - DependencyManager::get()->renderWireCube(1.0f, cubeColor); - } + transform.setScale(dimensions); + batch->setModelTransform(transform); + DependencyManager::get()->renderWireCube(*batch, 1.0f, cubeColor); } - glPopMatrix(); - glPopMatrix(); + } + } else { + float glowLevel = getGlowLevel(); + Glower* glower = NULL; + if (glowLevel > 0.0f) { + glower = new Glower(glowLevel); + } - if (glower) { - delete glower; + glPushMatrix(); + glTranslatef(position.x, position.y, position.z); + glm::vec3 axis = glm::axis(rotation); + glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); + glPushMatrix(); + glm::vec3 positionToCenter = center - position; + glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); + if (_isSolid) { + if (_borderSize > 0) { + // Draw a cube at a larger size behind the main cube, creating + // a border effect. + // Disable writing to the depth mask so that the "border" cube will not + // occlude the main cube. This means the border could be covered by + // overlays that are further back and drawn later, but this is good + // enough for the use-case. + glDepthMask(GL_FALSE); + glPushMatrix(); + glScalef(dimensions.x * _borderSize, dimensions.y * _borderSize, dimensions.z * _borderSize); + + if (_drawOnHUD) { + DependencyManager::get()->renderSolidCube(1.0f, glm::vec4(1.0f, 1.0f, 1.0f, alpha)); + } else { + DependencyManager::get()->renderSolidCube(1.0f, glm::vec4(1.0f, 1.0f, 1.0f, alpha)); + } + + glPopMatrix(); + glDepthMask(GL_TRUE); + } + + glPushMatrix(); + glScalef(dimensions.x, dimensions.y, dimensions.z); + if (_drawOnHUD) { + DependencyManager::get()->renderSolidCube(1.0f, cubeColor); + } else { + DependencyManager::get()->renderSolidCube(1.0f, cubeColor); + } + glPopMatrix(); + } else { + glLineWidth(_lineWidth); + + if (getIsDashedLine()) { + glm::vec3 halfDimensions = dimensions / 2.0f; + glm::vec3 bottomLeftNear(-halfDimensions.x, -halfDimensions.y, -halfDimensions.z); + glm::vec3 bottomRightNear(halfDimensions.x, -halfDimensions.y, -halfDimensions.z); + glm::vec3 topLeftNear(-halfDimensions.x, halfDimensions.y, -halfDimensions.z); + glm::vec3 topRightNear(halfDimensions.x, halfDimensions.y, -halfDimensions.z); + + glm::vec3 bottomLeftFar(-halfDimensions.x, -halfDimensions.y, halfDimensions.z); + glm::vec3 bottomRightFar(halfDimensions.x, -halfDimensions.y, halfDimensions.z); + glm::vec3 topLeftFar(-halfDimensions.x, halfDimensions.y, halfDimensions.z); + glm::vec3 topRightFar(halfDimensions.x, halfDimensions.y, halfDimensions.z); + + auto geometryCache = DependencyManager::get(); + + geometryCache->renderDashedLine(bottomLeftNear, bottomRightNear, cubeColor); + geometryCache->renderDashedLine(bottomRightNear, bottomRightFar, cubeColor); + geometryCache->renderDashedLine(bottomRightFar, bottomLeftFar, cubeColor); + geometryCache->renderDashedLine(bottomLeftFar, bottomLeftNear, cubeColor); + + geometryCache->renderDashedLine(topLeftNear, topRightNear, cubeColor); + geometryCache->renderDashedLine(topRightNear, topRightFar, cubeColor); + geometryCache->renderDashedLine(topRightFar, topLeftFar, cubeColor); + geometryCache->renderDashedLine(topLeftFar, topLeftNear, cubeColor); + + geometryCache->renderDashedLine(bottomLeftNear, topLeftNear, cubeColor); + geometryCache->renderDashedLine(bottomRightNear, topRightNear, cubeColor); + geometryCache->renderDashedLine(bottomLeftFar, topLeftFar, cubeColor); + geometryCache->renderDashedLine(bottomRightFar, topRightFar, cubeColor); + + } else { + glScalef(dimensions.x, dimensions.y, dimensions.z); + DependencyManager::get()->renderWireCube(1.0f, cubeColor); + } + } + glPopMatrix(); + glPopMatrix(); + + if (glower) { + delete glower; + } } } diff --git a/interface/src/ui/overlays/Line3DOverlay.cpp b/interface/src/ui/overlays/Line3DOverlay.cpp index 6672a88e45..34c983d7b2 100644 --- a/interface/src/ui/overlays/Line3DOverlay.cpp +++ b/interface/src/ui/overlays/Line3DOverlay.cpp @@ -37,41 +37,57 @@ void Line3DOverlay::render(RenderArgs* args) { return; // do nothing if we're not visible } - float glowLevel = getGlowLevel(); - Glower* glower = NULL; - if (glowLevel > 0.0f) { - glower = new Glower(glowLevel); - } - - glPushMatrix(); - - glDisable(GL_LIGHTING); - glLineWidth(_lineWidth); - float alpha = getAlpha(); xColor color = getColor(); const float MAX_COLOR = 255.0f; glm::vec4 colorv4(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha); - glm::vec3 position = getPosition(); - glm::quat rotation = getRotation(); + auto batch = args->_batch; - glTranslatef(position.x, position.y, position.z); - glm::vec3 axis = glm::axis(rotation); - glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); + if (batch) { + Transform transform; + transform.setTranslation(_position); + transform.setRotation(_rotation); + batch->setModelTransform(transform); - if (getIsDashedLine()) { - // TODO: add support for color to renderDashedLine() - DependencyManager::get()->renderDashedLine(_position, _end, colorv4, _geometryCacheID); + if (getIsDashedLine()) { + // TODO: add support for color to renderDashedLine() + DependencyManager::get()->renderDashedLine(*batch, _position, _end, colorv4, _geometryCacheID); + } else { + DependencyManager::get()->renderLine(*batch, _start, _end, colorv4, _geometryCacheID); + } } else { - DependencyManager::get()->renderLine(_start, _end, colorv4, _geometryCacheID); - } - glEnable(GL_LIGHTING); + float glowLevel = getGlowLevel(); + Glower* glower = NULL; + if (glowLevel > 0.0f) { + glower = new Glower(glowLevel); + } - glPopMatrix(); + glPushMatrix(); - if (glower) { - delete glower; + glDisable(GL_LIGHTING); + glLineWidth(_lineWidth); + + glm::vec3 position = getPosition(); + glm::quat rotation = getRotation(); + + glTranslatef(position.x, position.y, position.z); + glm::vec3 axis = glm::axis(rotation); + glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); + + if (getIsDashedLine()) { + // TODO: add support for color to renderDashedLine() + DependencyManager::get()->renderDashedLine(_position, _end, colorv4, _geometryCacheID); + } else { + DependencyManager::get()->renderLine(_start, _end, colorv4, _geometryCacheID); + } + glEnable(GL_LIGHTING); + + glPopMatrix(); + + if (glower) { + delete glower; + } } } diff --git a/interface/src/ui/overlays/Sphere3DOverlay.cpp b/interface/src/ui/overlays/Sphere3DOverlay.cpp index a0e8d06b41..f5fba0ed05 100644 --- a/interface/src/ui/overlays/Sphere3DOverlay.cpp +++ b/interface/src/ui/overlays/Sphere3DOverlay.cpp @@ -39,33 +39,45 @@ void Sphere3DOverlay::render(RenderArgs* args) { const float MAX_COLOR = 255.0f; glm::vec4 sphereColor(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha); - glDisable(GL_LIGHTING); - - glm::vec3 position = getPosition(); - glm::vec3 center = getCenter(); - glm::vec3 dimensions = getDimensions(); - glm::quat rotation = getRotation(); + auto batch = args->_batch; - float glowLevel = getGlowLevel(); - Glower* glower = NULL; - if (glowLevel > 0.0f) { - glower = new Glower(glowLevel); - } + if (batch) { + Transform transform; + transform.setTranslation(_position); + transform.setRotation(_rotation); + transform.setScale(_dimensions); + + batch->setModelTransform(transform); + DependencyManager::get()->renderSphere(*batch, 1.0f, SLICES, SLICES, sphereColor, _isSolid); + } else { + glDisable(GL_LIGHTING); + + glm::vec3 position = getPosition(); + glm::vec3 center = getCenter(); + glm::vec3 dimensions = getDimensions(); + glm::quat rotation = getRotation(); + + float glowLevel = getGlowLevel(); + Glower* glower = NULL; + if (glowLevel > 0.0f) { + glower = new Glower(glowLevel); + } - glPushMatrix(); - glTranslatef(position.x, position.y, position.z); - glm::vec3 axis = glm::axis(rotation); - glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); glPushMatrix(); - glm::vec3 positionToCenter = center - position; - glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); - glScalef(dimensions.x, dimensions.y, dimensions.z); - DependencyManager::get()->renderSphere(1.0f, SLICES, SLICES, sphereColor, _isSolid); + glTranslatef(position.x, position.y, position.z); + glm::vec3 axis = glm::axis(rotation); + glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); + glPushMatrix(); + glm::vec3 positionToCenter = center - position; + glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); + glScalef(dimensions.x, dimensions.y, dimensions.z); + DependencyManager::get()->renderSphere(1.0f, SLICES, SLICES, sphereColor, _isSolid); + glPopMatrix(); glPopMatrix(); - glPopMatrix(); - - if (glower) { - delete glower; + + if (glower) { + delete glower; + } } } From a5f7ba51b67618845eecbca526b3029887884423 Mon Sep 17 00:00:00 2001 From: Seth Alves Date: Tue, 16 Jun 2015 10:13:47 -0700 Subject: [PATCH 52/90] only show polyvox property widgets if we are editing a polyvox. --- examples/html/entityProperties.html | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/examples/html/entityProperties.html b/examples/html/entityProperties.html index f029088b1a..27a2929d1c 100644 --- a/examples/html/entityProperties.html +++ b/examples/html/entityProperties.html @@ -354,7 +354,8 @@ var elZoneAtmosphereScatteringWavelengthsZ = document.getElementById("property-zone-atmosphere-scattering-wavelengths-z"); var elZoneAtmosphereHasStars = document.getElementById("property-zone-atmosphere-has-stars"); - var elPolyVoxSelections = document.querySelectorAll(".poly-vox-section"); + var elPolyVoxSections = document.querySelectorAll(".poly-vox-section"); + allSections.push(elPolyVoxSections); var elVoxelVolumeSizeX = document.getElementById("property-voxel-volume-size-x"); var elVoxelVolumeSizeY = document.getElementById("property-voxel-volume-size-y"); var elVoxelVolumeSizeZ = document.getElementById("property-voxel-volume-size-z"); @@ -602,6 +603,10 @@ elParticleLocalGravity.value = properties.localGravity.toFixed(2); elParticleRadius.value = properties.particleRadius.toFixed(3); } else if (properties.type == "PolyVox") { + for (var i = 0; i < elPolyVoxSections.length; i++) { + elPolyVoxSections[i].style.display = 'block'; + } + elVoxelVolumeSizeX.value = properties.voxelVolumeSize.x.toFixed(2); elVoxelVolumeSizeY.value = properties.voxelVolumeSize.y.toFixed(2); elVoxelVolumeSizeZ.value = properties.voxelVolumeSize.z.toFixed(2); @@ -1014,9 +1019,9 @@
Voxel Volume Size
-
X
-
Y
-
Z
+
X
+
Y
+
Z
Surface Extractor
From d7eddc398b5b87b73e14dab2f716d71b64877087 Mon Sep 17 00:00:00 2001 From: Seth Alves Date: Tue, 16 Jun 2015 10:14:01 -0700 Subject: [PATCH 53/90] don't make changes if the polyvox is locked --- .../src/RenderablePolyVoxEntityItem.cpp | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp b/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp index d8e7ca0a18..71c3537a0c 100644 --- a/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp @@ -238,6 +238,9 @@ void RenderablePolyVoxEntityItem::setVoxelInternal(int x, int y, int z, uint8_t void RenderablePolyVoxEntityItem::setVoxel(int x, int y, int z, uint8_t toValue) { + if (_locked) { + return; + } setVoxelInternal(x, y, z, toValue); compressVolumeData(); } @@ -263,6 +266,10 @@ void RenderablePolyVoxEntityItem::updateOnCount(int x, int y, int z, uint8_t toV } void RenderablePolyVoxEntityItem::setAll(uint8_t toValue) { + if (_locked) { + return; + } + for (int z = 0; z < _voxelVolumeSize.z; z++) { for (int y = 0; y < _voxelVolumeSize.y; y++) { for (int x = 0; x < _voxelVolumeSize.x; x++) { @@ -275,11 +282,19 @@ void RenderablePolyVoxEntityItem::setAll(uint8_t toValue) { } void RenderablePolyVoxEntityItem::setVoxelInVolume(glm::vec3 position, uint8_t toValue) { + if (_locked) { + return; + } + // same as setVoxel but takes a vector rather than 3 floats. - setVoxel(position.x, position.y, position.z, toValue); + setVoxel((int)position.x, (int)position.y, (int)position.z, toValue); } void RenderablePolyVoxEntityItem::setSphereInVolume(glm::vec3 center, float radius, uint8_t toValue) { + if (_locked) { + return; + } + // This three-level for loop iterates over every voxel in the volume for (int z = 0; z < _voxelVolumeSize.z; z++) { for (int y = 0; y < _voxelVolumeSize.y; y++) { From 68a08d969df0df898258450a71025b9b7bc3adea Mon Sep 17 00:00:00 2001 From: Sam Gondelman Date: Tue, 16 Jun 2015 10:19:40 -0700 Subject: [PATCH 54/90] code review fixes --- interface/src/devices/Joystick.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/devices/Joystick.cpp b/interface/src/devices/Joystick.cpp index 5d7e51b103..7525d66d74 100644 --- a/interface/src/devices/Joystick.cpp +++ b/interface/src/devices/Joystick.cpp @@ -44,8 +44,8 @@ void Joystick::closeJoystick() { void Joystick::update() { for (auto axisState : _axisStateMap) { - if (axisState.second < CONTROLLER_THRESHOLD && axisState.second > -CONTROLLER_THRESHOLD) { - _axisStateMap[axisState.first] = 0; + if (fabsf(axisState.second) < CONTROLLER_THRESHOLD) { + _axisStateMap[axisState.first] = 0.0f; } } } From 1ecc954656aa8acf41c611bd2884da9557b366ac Mon Sep 17 00:00:00 2001 From: Sam Gondelman Date: Tue, 16 Jun 2015 10:25:30 -0700 Subject: [PATCH 55/90] coding standard fixes --- interface/src/devices/Joystick.cpp | 4 ++-- interface/src/devices/SixenseManager.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/interface/src/devices/Joystick.cpp b/interface/src/devices/Joystick.cpp index 7525d66d74..a302becb77 100644 --- a/interface/src/devices/Joystick.cpp +++ b/interface/src/devices/Joystick.cpp @@ -17,7 +17,7 @@ #include "Joystick.h" -const float CONTROLLER_THRESHOLD = .25f; +const float CONTROLLER_THRESHOLD = 0.25f; #ifdef HAVE_SDL2 const float MAX_AXIS = 32768.0f; @@ -147,7 +147,7 @@ void Joystick::registerToUserInputMapper(UserInputMapper& mapper) { void Joystick::assignDefaultInputMapping(UserInputMapper& mapper) { #ifdef HAVE_SDL2 const float JOYSTICK_MOVE_SPEED = 1.0f; - const float DPAD_MOVE_SPEED = .5f; + const float DPAD_MOVE_SPEED = 0.5f; const float JOYSTICK_YAW_SPEED = 0.5f; const float JOYSTICK_PITCH_SPEED = 0.25f; const float BOOM_SPEED = 0.1f; diff --git a/interface/src/devices/SixenseManager.cpp b/interface/src/devices/SixenseManager.cpp index 95a622e7ad..959a1e147f 100644 --- a/interface/src/devices/SixenseManager.cpp +++ b/interface/src/devices/SixenseManager.cpp @@ -161,7 +161,7 @@ void SixenseManager::update(float deltaTime) { if (sixenseGetNumActiveControllers() == 0) { _hydrasConnected = false; - if (_deviceID) { + if (_deviceID != 0) { Application::getUserInputMapper()->removeDevice(_deviceID); _deviceID = 0; if (_prevPalms[0]) { @@ -704,7 +704,7 @@ void SixenseManager::assignDefaultInputMapping(UserInputMapper& mapper) { const float JOYSTICK_YAW_SPEED = 0.5f; const float JOYSTICK_PITCH_SPEED = 0.25f; const float BUTTON_MOVE_SPEED = 1.0f; - const float BOOM_SPEED = .1f; + const float BOOM_SPEED = 0.1f; // Left Joystick: Movement, strafing mapper.addInputChannel(UserInputMapper::LONGITUDINAL_FORWARD, makeInput(AXIS_Y_POS, 0), JOYSTICK_MOVE_SPEED); From 6d99d50f722e7bcd662e3e749e0f47d2a0b9453f Mon Sep 17 00:00:00 2001 From: Howard Stearns Date: Tue, 16 Jun 2015 10:51:42 -0700 Subject: [PATCH 56/90] Don't clip local audio sounds (https://app.asana.com/0/32622044445063/37633564937422) and quiet some warnings (of https://app.asana.com/0/32622044445063/37620738098871). --- libraries/audio/src/AudioInjector.cpp | 3 +-- libraries/audio/src/AudioInjectorLocalBuffer.cpp | 12 +++++++++--- libraries/audio/src/AudioInjectorLocalBuffer.h | 1 + 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/libraries/audio/src/AudioInjector.cpp b/libraries/audio/src/AudioInjector.cpp index 912351e21a..333a944e1b 100644 --- a/libraries/audio/src/AudioInjector.cpp +++ b/libraries/audio/src/AudioInjector.cpp @@ -51,7 +51,7 @@ void AudioInjector::setIsFinished(bool isFinished) { emit finished(); if (_localBuffer) { - _localBuffer->stop(); + // delete will stop (and nosily if we do so ourselves here first). _localBuffer->deleteLater(); _localBuffer = NULL; } @@ -60,7 +60,6 @@ void AudioInjector::setIsFinished(bool isFinished) { if (_shouldDeleteAfterFinish) { // we've been asked to delete after finishing, trigger a queued deleteLater here - qCDebug(audio) << "AudioInjector triggering delete from setIsFinished"; QMetaObject::invokeMethod(this, "deleteLater", Qt::QueuedConnection); } } diff --git a/libraries/audio/src/AudioInjectorLocalBuffer.cpp b/libraries/audio/src/AudioInjectorLocalBuffer.cpp index f40e613437..457abeb89e 100644 --- a/libraries/audio/src/AudioInjectorLocalBuffer.cpp +++ b/libraries/audio/src/AudioInjectorLocalBuffer.cpp @@ -17,7 +17,8 @@ AudioInjectorLocalBuffer::AudioInjectorLocalBuffer(const QByteArray& rawAudioArr _shouldLoop(false), _isStopped(false), _currentOffset(0), - _volume(1.0f) + _volume(1.0f), + _isFinished(false) { } @@ -51,6 +52,11 @@ void copy(char* to, char* from, int size, qreal factor) { qint64 AudioInjectorLocalBuffer::readData(char* data, qint64 maxSize) { if (!_isStopped) { + if (_isFinished) { + emit bufferEmpty(); + return -1; // qt docs say -1 is appropriate when subsequent calls will not write data + } + // first copy to the end of the raw audio int bytesToEnd = _rawAudioArray.size() - _currentOffset; @@ -70,8 +76,8 @@ qint64 AudioInjectorLocalBuffer::readData(char* data, qint64 maxSize) { } if (!_shouldLoop && bytesRead == bytesToEnd) { - // we hit the end of the buffer, emit a signal - emit bufferEmpty(); + // If we emit bufferEmpty now, we'll clip the end of the sound. Wait until the next call. + _isFinished = true; } else if (_shouldLoop && _currentOffset == _rawAudioArray.size()) { _currentOffset = 0; } diff --git a/libraries/audio/src/AudioInjectorLocalBuffer.h b/libraries/audio/src/AudioInjectorLocalBuffer.h index 9753cbbd83..270e730590 100644 --- a/libraries/audio/src/AudioInjectorLocalBuffer.h +++ b/libraries/audio/src/AudioInjectorLocalBuffer.h @@ -44,6 +44,7 @@ private: int _currentOffset; float _volume; + bool _isFinished; }; #endif // hifi_AudioInjectorLocalBuffer_h \ No newline at end of file From 814e22364ad6fb46c22ebf6f58bc93796e7f4cd0 Mon Sep 17 00:00:00 2001 From: Sam Gondelman Date: Tue, 16 Jun 2015 11:30:28 -0700 Subject: [PATCH 57/90] coding standard fixes --- interface/src/devices/Joystick.cpp | 52 ++++++++++++------------ interface/src/devices/SixenseManager.cpp | 8 ++-- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/interface/src/devices/Joystick.cpp b/interface/src/devices/Joystick.cpp index a302becb77..07f3c4873c 100644 --- a/interface/src/devices/Joystick.cpp +++ b/interface/src/devices/Joystick.cpp @@ -61,20 +61,20 @@ void Joystick::handleAxisEvent(const SDL_ControllerAxisEvent& event) { switch (axis) { case SDL_CONTROLLER_AXIS_LEFTX: - _axisStateMap[makeInput(LEFT_AXIS_X_POS).getChannel()] = (event.value > 0) ? event.value / MAX_AXIS : 0.0f; - _axisStateMap[makeInput(LEFT_AXIS_X_NEG).getChannel()] = (event.value < 0) ? -event.value / MAX_AXIS : 0.0f; + _axisStateMap[makeInput(LEFT_AXIS_X_POS).getChannel()] = (event.value > 0.0f) ? event.value / MAX_AXIS : 0.0f; + _axisStateMap[makeInput(LEFT_AXIS_X_NEG).getChannel()] = (event.value < 0.0f) ? -event.value / MAX_AXIS : 0.0f; break; case SDL_CONTROLLER_AXIS_LEFTY: - _axisStateMap[makeInput(LEFT_AXIS_Y_POS).getChannel()] = (event.value > 0) ? event.value / MAX_AXIS : 0.0f; - _axisStateMap[makeInput(LEFT_AXIS_Y_NEG).getChannel()] = (event.value < 0) ? -event.value / MAX_AXIS : 0.0f; + _axisStateMap[makeInput(LEFT_AXIS_Y_POS).getChannel()] = (event.value > 0.0f) ? event.value / MAX_AXIS : 0.0f; + _axisStateMap[makeInput(LEFT_AXIS_Y_NEG).getChannel()] = (event.value < 0.0f) ? -event.value / MAX_AXIS : 0.0f; break; case SDL_CONTROLLER_AXIS_RIGHTX: - _axisStateMap[makeInput(RIGHT_AXIS_X_POS).getChannel()] = (event.value > 0) ? event.value / MAX_AXIS : 0.0f; - _axisStateMap[makeInput(RIGHT_AXIS_X_NEG).getChannel()] = (event.value < 0) ? -event.value / MAX_AXIS : 0.0f; + _axisStateMap[makeInput(RIGHT_AXIS_X_POS).getChannel()] = (event.value > 0.0f) ? event.value / MAX_AXIS : 0.0f; + _axisStateMap[makeInput(RIGHT_AXIS_X_NEG).getChannel()] = (event.value < 0.0f) ? -event.value / MAX_AXIS : 0.0f; break; case SDL_CONTROLLER_AXIS_RIGHTY: - _axisStateMap[makeInput(RIGHT_AXIS_Y_POS).getChannel()] = (event.value > 0) ? event.value / MAX_AXIS : 0.0f; - _axisStateMap[makeInput(RIGHT_AXIS_Y_NEG).getChannel()] = (event.value < 0) ? -event.value / MAX_AXIS : 0.0f; + _axisStateMap[makeInput(RIGHT_AXIS_Y_POS).getChannel()] = (event.value > 0.0f) ? event.value / MAX_AXIS : 0.0f; + _axisStateMap[makeInput(RIGHT_AXIS_Y_NEG).getChannel()] = (event.value < 0.0f) ? -event.value / MAX_AXIS : 0.0f; break; case SDL_CONTROLLER_AXIS_TRIGGERRIGHT: _axisStateMap[makeInput(RIGHT_SHOULDER).getChannel()] = event.value / MAX_AXIS; @@ -184,32 +184,32 @@ void Joystick::assignDefaultInputMapping(UserInputMapper& mapper) { // Hold front right shoulder button for precision controls // Left Joystick: Movement, strafing - mapper.addInputChannel(UserInputMapper::LONGITUDINAL_FORWARD, makeInput(LEFT_AXIS_Y_NEG), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_MOVE_SPEED/2.); - mapper.addInputChannel(UserInputMapper::LONGITUDINAL_BACKWARD, makeInput(LEFT_AXIS_Y_POS), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_MOVE_SPEED/2.); - mapper.addInputChannel(UserInputMapper::LATERAL_RIGHT, makeInput(LEFT_AXIS_X_POS), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_MOVE_SPEED/2.); - mapper.addInputChannel(UserInputMapper::LATERAL_LEFT, makeInput(LEFT_AXIS_X_NEG), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_MOVE_SPEED/2.); + mapper.addInputChannel(UserInputMapper::LONGITUDINAL_FORWARD, makeInput(LEFT_AXIS_Y_NEG), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_MOVE_SPEED/2.0f); + mapper.addInputChannel(UserInputMapper::LONGITUDINAL_BACKWARD, makeInput(LEFT_AXIS_Y_POS), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_MOVE_SPEED/2.0f); + mapper.addInputChannel(UserInputMapper::LATERAL_RIGHT, makeInput(LEFT_AXIS_X_POS), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_MOVE_SPEED/2.0f); + mapper.addInputChannel(UserInputMapper::LATERAL_LEFT, makeInput(LEFT_AXIS_X_NEG), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_MOVE_SPEED/2.0f); // Right Joystick: Camera orientation - mapper.addInputChannel(UserInputMapper::YAW_RIGHT, makeInput(RIGHT_AXIS_X_POS), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_YAW_SPEED/2.); - mapper.addInputChannel(UserInputMapper::YAW_LEFT, makeInput(RIGHT_AXIS_X_NEG), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_YAW_SPEED/2.); - mapper.addInputChannel(UserInputMapper::PITCH_UP, makeInput(RIGHT_AXIS_Y_NEG), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_PITCH_SPEED/2.); - mapper.addInputChannel(UserInputMapper::PITCH_DOWN, makeInput(RIGHT_AXIS_Y_POS), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_PITCH_SPEED/2.); + mapper.addInputChannel(UserInputMapper::YAW_RIGHT, makeInput(RIGHT_AXIS_X_POS), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_YAW_SPEED/2.0f); + mapper.addInputChannel(UserInputMapper::YAW_LEFT, makeInput(RIGHT_AXIS_X_NEG), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_YAW_SPEED/2.0f); + mapper.addInputChannel(UserInputMapper::PITCH_UP, makeInput(RIGHT_AXIS_Y_NEG), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_PITCH_SPEED/2.0f); + mapper.addInputChannel(UserInputMapper::PITCH_DOWN, makeInput(RIGHT_AXIS_Y_POS), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_PITCH_SPEED/2.0f); // Dpad movement - mapper.addInputChannel(UserInputMapper::LONGITUDINAL_FORWARD, makeInput(SDL_CONTROLLER_BUTTON_DPAD_UP), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.); - mapper.addInputChannel(UserInputMapper::LONGITUDINAL_BACKWARD, makeInput(SDL_CONTROLLER_BUTTON_DPAD_DOWN), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.); - mapper.addInputChannel(UserInputMapper::LATERAL_RIGHT, makeInput(SDL_CONTROLLER_BUTTON_DPAD_RIGHT), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.); - mapper.addInputChannel(UserInputMapper::LATERAL_LEFT, makeInput(SDL_CONTROLLER_BUTTON_DPAD_LEFT), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.); + mapper.addInputChannel(UserInputMapper::LONGITUDINAL_FORWARD, makeInput(SDL_CONTROLLER_BUTTON_DPAD_UP), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.0f); + mapper.addInputChannel(UserInputMapper::LONGITUDINAL_BACKWARD, makeInput(SDL_CONTROLLER_BUTTON_DPAD_DOWN), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.0f); + mapper.addInputChannel(UserInputMapper::LATERAL_RIGHT, makeInput(SDL_CONTROLLER_BUTTON_DPAD_RIGHT), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.0f); + mapper.addInputChannel(UserInputMapper::LATERAL_LEFT, makeInput(SDL_CONTROLLER_BUTTON_DPAD_LEFT), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.0f); // Button controls - mapper.addInputChannel(UserInputMapper::VERTICAL_UP, makeInput(SDL_CONTROLLER_BUTTON_Y), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.); - mapper.addInputChannel(UserInputMapper::VERTICAL_DOWN, makeInput(SDL_CONTROLLER_BUTTON_A), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.); - mapper.addInputChannel(UserInputMapper::YAW_LEFT, makeInput(SDL_CONTROLLER_BUTTON_X), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_YAW_SPEED/2.); - mapper.addInputChannel(UserInputMapper::YAW_RIGHT, makeInput(SDL_CONTROLLER_BUTTON_B), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_YAW_SPEED/2.); + mapper.addInputChannel(UserInputMapper::VERTICAL_UP, makeInput(SDL_CONTROLLER_BUTTON_Y), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.0f); + mapper.addInputChannel(UserInputMapper::VERTICAL_DOWN, makeInput(SDL_CONTROLLER_BUTTON_A), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), DPAD_MOVE_SPEED/2.0f); + mapper.addInputChannel(UserInputMapper::YAW_LEFT, makeInput(SDL_CONTROLLER_BUTTON_X), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_YAW_SPEED/2.0f); + mapper.addInputChannel(UserInputMapper::YAW_RIGHT, makeInput(SDL_CONTROLLER_BUTTON_B), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), JOYSTICK_YAW_SPEED/2.0f); // Zoom - mapper.addInputChannel(UserInputMapper::BOOM_IN, makeInput(RIGHT_SHOULDER), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), BOOM_SPEED/2.); - mapper.addInputChannel(UserInputMapper::BOOM_OUT, makeInput(LEFT_SHOULDER), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), BOOM_SPEED/2.); + mapper.addInputChannel(UserInputMapper::BOOM_IN, makeInput(RIGHT_SHOULDER), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), BOOM_SPEED/2.0f); + mapper.addInputChannel(UserInputMapper::BOOM_OUT, makeInput(LEFT_SHOULDER), makeInput(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER), BOOM_SPEED/2.0f); #endif } diff --git a/interface/src/devices/SixenseManager.cpp b/interface/src/devices/SixenseManager.cpp index 959a1e147f..c2a53508e3 100644 --- a/interface/src/devices/SixenseManager.cpp +++ b/interface/src/devices/SixenseManager.cpp @@ -619,10 +619,10 @@ void SixenseManager::focusOutEvent() { }; void SixenseManager::handleAxisEvent(float stickX, float stickY, float trigger, int index) { - _axisStateMap[makeInput(AXIS_Y_POS, index).getChannel()] = (stickY > 0) ? stickY : 0.0f; - _axisStateMap[makeInput(AXIS_Y_NEG, index).getChannel()] = (stickY < 0) ? -stickY : 0.0f; - _axisStateMap[makeInput(AXIS_X_POS, index).getChannel()] = (stickX > 0) ? stickX : 0.0f; - _axisStateMap[makeInput(AXIS_X_NEG, index).getChannel()] = (stickX < 0) ? -stickX : 0.0f; + _axisStateMap[makeInput(AXIS_Y_POS, index).getChannel()] = (stickY > 0.0f) ? stickY : 0.0f; + _axisStateMap[makeInput(AXIS_Y_NEG, index).getChannel()] = (stickY < 0.0f) ? -stickY : 0.0f; + _axisStateMap[makeInput(AXIS_X_POS, index).getChannel()] = (stickX > 0.0f) ? stickX : 0.0f; + _axisStateMap[makeInput(AXIS_X_NEG, index).getChannel()] = (stickX < 0.0f) ? -stickX : 0.0f; _axisStateMap[makeInput(BACK_TRIGGER, index).getChannel()] = trigger; } From 156adb1a9870bf4ad0021b973f745984c7368dc8 Mon Sep 17 00:00:00 2001 From: Sam Gondelman Date: Tue, 16 Jun 2015 11:34:59 -0700 Subject: [PATCH 58/90] one more coding standard fix --- interface/src/avatar/MyAvatar.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 6fe99b89e4..586e7a1f56 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -70,7 +70,7 @@ const int SCRIPTED_MOTOR_CAMERA_FRAME = 0; const int SCRIPTED_MOTOR_AVATAR_FRAME = 1; const int SCRIPTED_MOTOR_WORLD_FRAME = 2; -const float MyAvatar::ZOOM_MIN = .5f; +const float MyAvatar::ZOOM_MIN = 0.5f; const float MyAvatar::ZOOM_MAX = 10.0f; const float MyAvatar::ZOOM_DEFAULT = 1.5f; From 167e7d13777693ce748ffdc3e145cd7244c8e4c0 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Jun 2015 14:05:14 -0700 Subject: [PATCH 59/90] first cut at atmospheres in batch (doesn't work) --- interface/src/Application.cpp | 10 +- interface/src/Environment.cpp | 150 +++++++++++++++--- interface/src/Environment.h | 17 +- libraries/gpu/src/gpu/Batch.h | 2 + libraries/gpu/src/gpu/GLBackend.cpp | 28 ++++ .../model/src/model/SkyFromAtmosphere.slf | 6 +- .../model/src/model/SkyFromAtmosphere.slv | 21 +-- libraries/model/src/model/SkyFromSpace.slf | 4 +- libraries/model/src/model/SkyFromSpace.slv | 25 ++- 9 files changed, 217 insertions(+), 46 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 22cbad6775..4c84e39b64 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3255,6 +3255,9 @@ namespace render { template <> const Item::Bound payloadGetBound(const BackgroundRenderData::Pointer& stuff) { return Item::Bound(); } template <> void payloadRender(const BackgroundRenderData::Pointer& background, RenderArgs* args) { + Q_ASSERT(args->_batch); + gpu::Batch& batch = *args->_batch; + // Background rendering decision auto skyStage = DependencyManager::get()->getSkyStage(); auto skybox = model::SkyboxPointer(); @@ -3322,7 +3325,11 @@ namespace render { PerformanceTimer perfTimer("atmosphere"); PerformanceWarning warn(Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings), "Application::displaySide() ... atmosphere..."); - background->_environment->renderAtmospheres(*(args->_viewFrustum)); + //gpu::Batch batch; + background->_environment->renderAtmospheres(batch, *(args->_viewFrustum)); + //gpu::GLBackend::renderBatch(batch, true); + //glUseProgram(0); + } } @@ -3333,7 +3340,6 @@ namespace render { if (skybox) { gpu::Batch batch; model::Skybox::render(batch, *(Application::getInstance()->getDisplayViewFrustum()), *skybox); - gpu::GLBackend::renderBatch(batch, true); glUseProgram(0); } diff --git a/interface/src/Environment.cpp b/interface/src/Environment.cpp index 9f197920d9..1e9c571a57 100644 --- a/interface/src/Environment.cpp +++ b/interface/src/Environment.cpp @@ -28,6 +28,11 @@ #include "Environment.h" +#include "../../build/libraries/model/SkyFromSpace_vert.h" +#include "../../build/libraries/model/SkyFromSpace_frag.h" +#include "../../build/libraries/model/SkyFromAtmosphere_vert.h" +#include "../../build/libraries/model/SkyFromAtmosphere_frag.h" + uint qHash(const HifiSockAddr& sockAddr) { if (sockAddr.getAddress().isNull()) { return 0; // shouldn't happen, but if it does, zero is a perfectly valid hash @@ -56,6 +61,15 @@ void Environment::init() { _skyFromAtmosphereProgram = createSkyProgram("Atmosphere", _skyFromAtmosphereUniformLocations); _skyFromSpaceProgram = createSkyProgram("Space", _skyFromSpaceUniformLocations); + + + + qDebug() << "line:" << __LINE__; + setupAtmosphereProgram(SkyFromSpace_vert, SkyFromSpace_frag, _newSkyFromSpaceProgram, _newSkyFromSpaceUniformLocations); + qDebug() << "line:" << __LINE__; + setupAtmosphereProgram(SkyFromAtmosphere_vert, SkyFromAtmosphere_frag, _newSkyFromAtmosphereProgram, _newSkyFromAtmosphereUniformLocations); + qDebug() << "line:" << __LINE__; + // start off with a default-constructed environment data _data[HifiSockAddr()][0]; @@ -63,22 +77,84 @@ void Environment::init() { _initialized = true; } +void Environment::setupAtmosphereProgram(const char* vertSource, const char* fragSource, gpu::PipelinePointer& pipelineProgram, int* locations) { + + auto VS = gpu::ShaderPointer(gpu::Shader::createVertex(std::string(vertSource))); + auto PS = gpu::ShaderPointer(gpu::Shader::createPixel(std::string(fragSource))); + + gpu::ShaderPointer program = gpu::ShaderPointer(gpu::Shader::createProgram(VS, PS)); + + gpu::Shader::BindingSet slotBindings; + gpu::Shader::makeProgram(*program, slotBindings); + + gpu::StatePointer state = gpu::StatePointer(new gpu::State()); + state->setCullMode(gpu::State::CULL_NONE); + state->setDepthTest(false); + state->setBlendFunction(true,gpu::State::SRC_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::INV_SRC_ALPHA); + pipelineProgram = gpu::PipelinePointer(gpu::Pipeline::create(program, state)); + + locations[CAMERA_POS_LOCATION] = program->getUniforms().findLocation("v3CameraPos"); + locations[LIGHT_POS_LOCATION] = program->getUniforms().findLocation("v3LightPos"); + locations[INV_WAVELENGTH_LOCATION] = program->getUniforms().findLocation("v3InvWavelength"); + locations[CAMERA_HEIGHT2_LOCATION] = program->getUniforms().findLocation("fCameraHeight2"); + locations[OUTER_RADIUS_LOCATION] = program->getUniforms().findLocation("fOuterRadius"); + locations[OUTER_RADIUS2_LOCATION] = program->getUniforms().findLocation("fOuterRadius2"); + locations[INNER_RADIUS_LOCATION] = program->getUniforms().findLocation("fInnerRadius"); + locations[KR_ESUN_LOCATION] = program->getUniforms().findLocation("fKrESun"); + locations[KM_ESUN_LOCATION] = program->getUniforms().findLocation("fKmESun"); + locations[KR_4PI_LOCATION] = program->getUniforms().findLocation("fKr4PI"); + locations[KM_4PI_LOCATION] = program->getUniforms().findLocation("fKm4PI"); + locations[SCALE_LOCATION] = program->getUniforms().findLocation("fScale"); + locations[SCALE_DEPTH_LOCATION] = program->getUniforms().findLocation("fScaleDepth"); + locations[SCALE_OVER_SCALE_DEPTH_LOCATION] = program->getUniforms().findLocation("fScaleOverScaleDepth"); + locations[G_LOCATION] = program->getUniforms().findLocation("g"); + locations[G2_LOCATION] = program->getUniforms().findLocation("g2"); + + /* + + program.addShaderFromSourceCode(QGLShader::Vertex, vertSource); + program.addShaderFromSourceCode(QGLShader::Fragment, fragSource); + program.link(); + + program.bind(); + + locations[CAMERA_POS_LOCATION] = program.uniformLocation("v3CameraPos"); + locations[LIGHT_POS_LOCATION] = program.uniformLocation("v3LightPos"); + locations[INV_WAVELENGTH_LOCATION] = program.uniformLocation("v3InvWavelength"); + locations[CAMERA_HEIGHT2_LOCATION] = program.uniformLocation("fCameraHeight2"); + locations[OUTER_RADIUS_LOCATION] = program.uniformLocation("fOuterRadius"); + locations[OUTER_RADIUS2_LOCATION] = program.uniformLocation("fOuterRadius2"); + locations[INNER_RADIUS_LOCATION] = program.uniformLocation("fInnerRadius"); + locations[KR_ESUN_LOCATION] = program.uniformLocation("fKrESun"); + locations[KM_ESUN_LOCATION] = program.uniformLocation("fKmESun"); + locations[KR_4PI_LOCATION] = program.uniformLocation("fKr4PI"); + locations[KM_4PI_LOCATION] = program.uniformLocation("fKm4PI"); + locations[SCALE_LOCATION] = program.uniformLocation("fScale"); + locations[SCALE_DEPTH_LOCATION] = program.uniformLocation("fScaleDepth"); + locations[SCALE_OVER_SCALE_DEPTH_LOCATION] = program.uniformLocation("fScaleOverScaleDepth"); + locations[G_LOCATION] = program.uniformLocation("g"); + locations[G2_LOCATION] = program.uniformLocation("g2"); + + program.release(); + */ +} + void Environment::resetToDefault() { _data.clear(); _data[HifiSockAddr()][0]; } -void Environment::renderAtmospheres(ViewFrustum& camera) { +void Environment::renderAtmospheres(gpu::Batch& batch, ViewFrustum& camera) { // get the lock for the duration of the call QMutexLocker locker(&_mutex); if (_environmentIsOverridden) { - renderAtmosphere(camera, _overrideData); + renderAtmosphere(batch, camera, _overrideData); } else { foreach (const ServerData& serverData, _data) { // TODO: do something about EnvironmentData foreach (const EnvironmentData& environmentData, serverData) { - renderAtmosphere(camera, environmentData); + renderAtmosphere(batch, camera, environmentData); } } } @@ -228,30 +304,39 @@ ProgramObject* Environment::createSkyProgram(const char* from, int* locations) { return program; } -void Environment::renderAtmosphere(ViewFrustum& camera, const EnvironmentData& data) { +void Environment::renderAtmosphere(gpu::Batch& batch, ViewFrustum& camera, const EnvironmentData& data) { glm::vec3 center = data.getAtmosphereCenter(); - glPushMatrix(); - glTranslatef(center.x, center.y, center.z); + //glPushMatrix(); + //glTranslatef(center.x, center.y, center.z); + + Transform transform; + transform.setTranslation(center); + transform.setScale(1.0f); + batch.setModelTransform(transform); glm::vec3 relativeCameraPos = camera.getPosition() - center; float height = glm::length(relativeCameraPos); // use the appropriate shader depending on whether we're inside or outside - ProgramObject* program; + //ProgramObject* program; int* locations; if (height < data.getAtmosphereOuterRadius()) { - program = _skyFromAtmosphereProgram; - locations = _skyFromAtmosphereUniformLocations; + //program = &_newSkyFromAtmosphereProgram; + batch.setPipeline(_newSkyFromAtmosphereProgram); + locations = _newSkyFromAtmosphereUniformLocations; } else { - program = _skyFromSpaceProgram; - locations = _skyFromSpaceUniformLocations; + //program = &_newSkyFromSpaceProgram; + batch.setPipeline(_newSkyFromSpaceProgram); + locations = _newSkyFromSpaceUniformLocations; } // the constants here are from Sean O'Neil's GPU Gems entry // (http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter16.html), GameEngine.cpp - program->bind(); + + //program->bind(); + /* program->setUniform(locations[CAMERA_POS_LOCATION], relativeCameraPos); glm::vec3 lightDirection = glm::normalize(data.getSunLocation()); program->setUniform(locations[LIGHT_POS_LOCATION], lightDirection); @@ -273,15 +358,40 @@ void Environment::renderAtmosphere(ViewFrustum& camera, const EnvironmentData& d (1.0f / (data.getAtmosphereOuterRadius() - data.getAtmosphereInnerRadius())) / 0.25f); program->setUniformValue(locations[G_LOCATION], -0.990f); program->setUniformValue(locations[G2_LOCATION], -0.990f * -0.990f); + */ - glDepthMask(GL_FALSE); - glDisable(GL_DEPTH_TEST); - glDisable(GL_CULL_FACE); - glEnable(GL_BLEND); - DependencyManager::get()->renderSphere(1.0f, 100, 50, glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)); //Draw a unit sphere - glDepthMask(GL_TRUE); + + batch._glUniform3fv(locations[CAMERA_POS_LOCATION], relativeCameraPos); + glm::vec3 lightDirection = glm::normalize(data.getSunLocation()); + batch._glUniform3fv(locations[LIGHT_POS_LOCATION], lightDirection); + batch._glUniform3f(locations[INV_WAVELENGTH_LOCATION], + 1 / powf(data.getScatteringWavelengths().r, 4.0f), + 1 / powf(data.getScatteringWavelengths().g, 4.0f), + 1 / powf(data.getScatteringWavelengths().b, 4.0f)); + batch._glUniform1f(locations[CAMERA_HEIGHT2_LOCATION], height * height); + batch._glUniform1f(locations[OUTER_RADIUS_LOCATION], data.getAtmosphereOuterRadius()); + batch._glUniform1f(locations[OUTER_RADIUS2_LOCATION], data.getAtmosphereOuterRadius() * data.getAtmosphereOuterRadius()); + batch._glUniform1f(locations[INNER_RADIUS_LOCATION], data.getAtmosphereInnerRadius()); + batch._glUniform1f(locations[KR_ESUN_LOCATION], data.getRayleighScattering() * data.getSunBrightness()); + batch._glUniform1f(locations[KM_ESUN_LOCATION], data.getMieScattering() * data.getSunBrightness()); + batch._glUniform1f(locations[KR_4PI_LOCATION], data.getRayleighScattering() * 4.0f * PI); + batch._glUniform1f(locations[KM_4PI_LOCATION], data.getMieScattering() * 4.0f * PI); + batch._glUniform1f(locations[SCALE_LOCATION], 1.0f / (data.getAtmosphereOuterRadius() - data.getAtmosphereInnerRadius())); + batch._glUniform1f(locations[SCALE_DEPTH_LOCATION], 0.25f); + batch._glUniform1f(locations[SCALE_OVER_SCALE_DEPTH_LOCATION], + (1.0f / (data.getAtmosphereOuterRadius() - data.getAtmosphereInnerRadius())) / 0.25f); + batch._glUniform1f(locations[G_LOCATION], -0.990f); + batch._glUniform1f(locations[G2_LOCATION], -0.990f * -0.990f); + + + //glDepthMask(GL_FALSE); + //glDisable(GL_DEPTH_TEST); + //glDisable(GL_CULL_FACE); + //glEnable(GL_BLEND); + DependencyManager::get()->renderSphere(batch,1.0f, 100, 50, glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)); //Draw a unit sphere + //glDepthMask(GL_TRUE); - program->release(); + //program->release(); - glPopMatrix(); + //glPopMatrix(); } diff --git a/interface/src/Environment.h b/interface/src/Environment.h index c1b4171947..9048678230 100644 --- a/interface/src/Environment.h +++ b/interface/src/Environment.h @@ -16,6 +16,9 @@ #include #include +#include + +#include #include "EnvironmentData.h" @@ -29,7 +32,7 @@ public: void init(); void resetToDefault(); - void renderAtmospheres(ViewFrustum& camera); + void renderAtmospheres(gpu::Batch& batch, ViewFrustum& camera); void override(const EnvironmentData& overrideData) { _overrideData = overrideData; _environmentIsOverridden = true; } void endOverride() { _environmentIsOverridden = false; } @@ -46,12 +49,12 @@ private: ProgramObject* createSkyProgram(const char* from, int* locations); - void renderAtmosphere(ViewFrustum& camera, const EnvironmentData& data); + void renderAtmosphere(gpu::Batch& batch, ViewFrustum& camera, const EnvironmentData& data); bool _initialized; ProgramObject* _skyFromAtmosphereProgram; ProgramObject* _skyFromSpaceProgram; - + enum { CAMERA_POS_LOCATION, LIGHT_POS_LOCATION, @@ -74,6 +77,14 @@ private: int _skyFromAtmosphereUniformLocations[LOCATION_COUNT]; int _skyFromSpaceUniformLocations[LOCATION_COUNT]; + + void setupAtmosphereProgram(const char* vertSource, const char* fragSource, gpu::PipelinePointer& pipelineProgram, int* locations); + + + gpu::PipelinePointer _newSkyFromAtmosphereProgram; + gpu::PipelinePointer _newSkyFromSpaceProgram; + int _newSkyFromAtmosphereUniformLocations[LOCATION_COUNT]; + int _newSkyFromSpaceUniformLocations[LOCATION_COUNT]; typedef QHash ServerData; diff --git a/libraries/gpu/src/gpu/Batch.h b/libraries/gpu/src/gpu/Batch.h index 405ea9459d..77c9308af5 100644 --- a/libraries/gpu/src/gpu/Batch.h +++ b/libraries/gpu/src/gpu/Batch.h @@ -150,6 +150,7 @@ public: void _glUseProgram(GLuint program); void _glUniform1f(GLint location, GLfloat v0); void _glUniform2f(GLint location, GLfloat v0, GLfloat v1); + void _glUniform3f(GLint location, GLfloat v0, GLfloat v1); void _glUniform4fv(GLint location, GLsizei count, const GLfloat* value); void _glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); @@ -210,6 +211,7 @@ public: COMMAND_glUseProgram, COMMAND_glUniform1f, COMMAND_glUniform2f, + COMMAND_glUniform3f, COMMAND_glUniform4fv, COMMAND_glUniformMatrix4fv, diff --git a/libraries/gpu/src/gpu/GLBackend.cpp b/libraries/gpu/src/gpu/GLBackend.cpp index da6979fb27..7ba344dfbd 100644 --- a/libraries/gpu/src/gpu/GLBackend.cpp +++ b/libraries/gpu/src/gpu/GLBackend.cpp @@ -61,6 +61,7 @@ GLBackend::CommandCall GLBackend::_commandCalls[Batch::NUM_COMMANDS] = (&::gpu::GLBackend::do_glUseProgram), (&::gpu::GLBackend::do_glUniform1f), (&::gpu::GLBackend::do_glUniform2f), + (&::gpu::GLBackend::do_glUniform3f), (&::gpu::GLBackend::do_glUniform4fv), (&::gpu::GLBackend::do_glUniformMatrix4fv), @@ -462,6 +463,7 @@ void Batch::_glUniform2f(GLint location, GLfloat v0, GLfloat v1) { DO_IT_NOW(_glUniform2f, 1); } + void GLBackend::do_glUniform2f(Batch& batch, uint32 paramOffset) { if (_pipeline._program == 0) { // We should call updatePipeline() to bind the program but we are not doing that @@ -475,6 +477,32 @@ void GLBackend::do_glUniform2f(Batch& batch, uint32 paramOffset) { (void) CHECK_GL_ERROR(); } +void Batch::_glUniform3f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2) { + ADD_COMMAND_GL(glUniform3f); + + _params.push_back(v2); + _params.push_back(v1); + _params.push_back(v0); + _params.push_back(location); + + DO_IT_NOW(_glUniform3f, 1); +} + +void GLBackend::do_glUniform3f(Batch& batch, uint32 paramOffset) { + if (_pipeline._program == 0) { + // We should call updatePipeline() to bind the program but we are not doing that + // because these uniform setters are deprecated and we don;t want to create side effect + return; + } + glUniform3f( + batch._params[paramOffset + 3]._int, + batch._params[paramOffset + 2]._float, + batch._params[paramOffset + 1]._float, + batch._params[paramOffset + 0]._float); + (void) CHECK_GL_ERROR(); +} + + void Batch::_glUniform4fv(GLint location, GLsizei count, const GLfloat* value) { ADD_COMMAND_GL(glUniform4fv); diff --git a/libraries/model/src/model/SkyFromAtmosphere.slf b/libraries/model/src/model/SkyFromAtmosphere.slf index 02036d0d7c..b82cddc282 100755 --- a/libraries/model/src/model/SkyFromAtmosphere.slf +++ b/libraries/model/src/model/SkyFromAtmosphere.slf @@ -51,7 +51,8 @@ uniform vec3 v3LightPos; uniform float g; uniform float g2; -varying vec3 position; +varying vec3 myPosition; + float scale(float fCos) { @@ -59,10 +60,11 @@ float scale(float fCos) return fScaleDepth * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.80 + x*5.25)))); } + void main (void) { // Get the ray from the camera to the vertex, and its length (which is the far point of the ray passing through the atmosphere) - vec3 v3Pos = position; + vec3 v3Pos = myPosition; vec3 v3Ray = v3Pos - v3CameraPos; float fFar = length(v3Ray); v3Ray /= fFar; diff --git a/libraries/model/src/model/SkyFromAtmosphere.slv b/libraries/model/src/model/SkyFromAtmosphere.slv index 785f89bb48..c19cb34c6a 100755 --- a/libraries/model/src/model/SkyFromAtmosphere.slv +++ b/libraries/model/src/model/SkyFromAtmosphere.slv @@ -33,6 +33,9 @@ // Copyright (c) 2004 Sean O'Neil // +<@include gpu/Transform.slh@> +<$declareStandardTransform()$> + uniform vec3 v3CameraPos; // The camera's current position uniform vec3 v3LightPos; // The direction vector to the light source uniform vec3 v3InvWavelength; // 1 / pow(wavelength, 4) for the red, green, and blue channels @@ -50,19 +53,19 @@ uniform float fScaleOverScaleDepth; // fScale / fScaleDepth const int nSamples = 2; const float fSamples = 2.0; -varying vec3 position; +varying vec3 myPosition; -float scale(float fCos) -{ - float x = 1.0 - fCos; - return fScaleDepth * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.80 + x*5.25)))); -} - void main(void) { // Get the ray from the camera to the vertex, and its length (which is the far point of the ray passing through the atmosphere) - position = gl_Vertex.xyz * fOuterRadius; + myPosition = gl_Vertex.xyz * fOuterRadius; - gl_Position = gl_ModelViewProjectionMatrix * vec4(position, 1.0); + //gl_Position = gl_ModelViewProjectionMatrix * vec4(position, 1.0); + + // standard transform + TransformCamera cam = getTransformCamera(); + TransformObject obj = getTransformObject(); + vec4 v4pos = vec4(myPosition, 1.0); + <$transformModelToClipPos(cam, obj, v4pos, gl_Position)$> } diff --git a/libraries/model/src/model/SkyFromSpace.slf b/libraries/model/src/model/SkyFromSpace.slf index 5f6ce80efa..4e13438ccb 100755 --- a/libraries/model/src/model/SkyFromSpace.slf +++ b/libraries/model/src/model/SkyFromSpace.slf @@ -53,7 +53,7 @@ uniform float g2; const int nSamples = 2; const float fSamples = 2.0; -varying vec3 position; +varying vec3 myPosition; float scale(float fCos) { @@ -65,7 +65,7 @@ float scale(float fCos) void main (void) { // Get the ray from the camera to the vertex and its length (which is the far point of the ray passing through the atmosphere) - vec3 v3Pos = position; + vec3 v3Pos = myPosition; vec3 v3Ray = v3Pos - v3CameraPos; float fFar = length(v3Ray); v3Ray /= fFar; diff --git a/libraries/model/src/model/SkyFromSpace.slv b/libraries/model/src/model/SkyFromSpace.slv index 6740d1909e..9090d76da2 100755 --- a/libraries/model/src/model/SkyFromSpace.slv +++ b/libraries/model/src/model/SkyFromSpace.slv @@ -1,5 +1,6 @@ -#version 120 - +<@include gpu/Config.slh@> +<$VERSION_HEADER$> +// Generated on <$_SCRIBE_DATE$> // // For licensing information, see http://http.developer.nvidia.com/GPUGems/gpugems_app01.html: // @@ -32,12 +33,20 @@ // Copyright (c) 2004 Sean O'Neil // +<@include gpu/Transform.slh@> +<$declareStandardTransform()$> + uniform float fOuterRadius; // The outer (atmosphere) radius -varying vec3 position; +varying vec3 myPosition; -void main(void) -{ - position = gl_Vertex.xyz * fOuterRadius; - gl_Position = gl_ModelViewProjectionMatrix * vec4(position, 1.0); -} + +void main(void) { + myPosition = gl_Vertex.xyz * fOuterRadius; + + // standard transform + TransformCamera cam = getTransformCamera(); + TransformObject obj = getTransformObject(); + vec4 v4pos = vec4(myPosition, 1.0); + <$transformModelToClipPos(cam, obj, v4pos, gl_Position)$> +} \ No newline at end of file From d47f5a2abb87c47109f62322bab410083e630f1b Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Tue, 16 Jun 2015 16:44:33 -0700 Subject: [PATCH 60/90] Update Rectangle, Grid, and Billboard overlays to use batches --- .../src/ui/overlays/BillboardOverlay.cpp | 122 +++++++----- interface/src/ui/overlays/Grid3DOverlay.cpp | 181 +++++++++++------- .../src/ui/overlays/Rectangle3DOverlay.cpp | 146 +++++++++----- 3 files changed, 274 insertions(+), 175 deletions(-) diff --git a/interface/src/ui/overlays/BillboardOverlay.cpp b/interface/src/ui/overlays/BillboardOverlay.cpp index 3e3e823737..ed0ddd8dc7 100644 --- a/interface/src/ui/overlays/BillboardOverlay.cpp +++ b/interface/src/ui/overlays/BillboardOverlay.cpp @@ -43,72 +43,88 @@ void BillboardOverlay::render(RenderArgs* args) { return; } - glEnable(GL_ALPHA_TEST); - glAlphaFunc(GL_GREATER, 0.5f); + glm::quat rotation; + if (_isFacingAvatar) { + // rotate about vertical to face the camera + rotation = Application::getInstance()->getCamera()->getRotation(); + rotation *= glm::angleAxis(glm::pi(), glm::vec3(0.0f, 1.0f, 0.0f)); + rotation *= getRotation(); + } else { + rotation = getRotation(); + } - glEnable(GL_TEXTURE_2D); - glDisable(GL_LIGHTING); + float imageWidth = _texture->getWidth(); + float imageHeight = _texture->getHeight(); - glBindTexture(GL_TEXTURE_2D, _texture->getID()); + QRect fromImage; + if (_fromImage.isNull()) { + fromImage.setX(0); + fromImage.setY(0); + fromImage.setWidth(imageWidth); + fromImage.setHeight(imageHeight); + } else { + float scaleX = imageWidth / _texture->getOriginalWidth(); + float scaleY = imageHeight / _texture->getOriginalHeight(); - glPushMatrix(); { - glTranslatef(_position.x, _position.y, _position.z); - glm::quat rotation; - if (_isFacingAvatar) { - // rotate about vertical to face the camera - rotation = Application::getInstance()->getCamera()->getRotation(); - rotation *= glm::angleAxis(glm::pi(), glm::vec3(0.0f, 1.0f, 0.0f)); - rotation *= getRotation(); - } else { - rotation = getRotation(); - } - glm::vec3 axis = glm::axis(rotation); - glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); - glScalef(_scale, _scale, _scale); + fromImage.setX(scaleX * _fromImage.x()); + fromImage.setY(scaleY * _fromImage.y()); + fromImage.setWidth(scaleX * _fromImage.width()); + fromImage.setHeight(scaleY * _fromImage.height()); + } - const float MAX_COLOR = 255.0f; - xColor color = getColor(); - float alpha = getAlpha(); + float maxSize = glm::max(fromImage.width(), fromImage.height()); + float x = fromImage.width() / (2.0f * maxSize); + float y = -fromImage.height() / (2.0f * maxSize); - float imageWidth = _texture->getWidth(); - float imageHeight = _texture->getHeight(); + glm::vec2 topLeft(-x, -y); + glm::vec2 bottomRight(x, y); + glm::vec2 texCoordTopLeft(fromImage.x() / imageWidth, fromImage.y() / imageHeight); + glm::vec2 texCoordBottomRight((fromImage.x() + fromImage.width()) / imageWidth, + (fromImage.y() + fromImage.height()) / imageHeight); - QRect fromImage; - if (_fromImage.isNull()) { - fromImage.setX(0); - fromImage.setY(0); - fromImage.setWidth(imageWidth); - fromImage.setHeight(imageHeight); - } else { - float scaleX = imageWidth / _texture->getOriginalWidth(); - float scaleY = imageHeight / _texture->getOriginalHeight(); + const float MAX_COLOR = 255.0f; + xColor color = getColor(); + float alpha = getAlpha(); - fromImage.setX(scaleX * _fromImage.x()); - fromImage.setY(scaleY * _fromImage.y()); - fromImage.setWidth(scaleX * _fromImage.width()); - fromImage.setHeight(scaleY * _fromImage.height()); - } + auto batch = args->_batch; - float maxSize = glm::max(fromImage.width(), fromImage.height()); - float x = fromImage.width() / (2.0f * maxSize); - float y = -fromImage.height() / (2.0f * maxSize); + if (batch) { + Transform transform; + transform.setTranslation(_position); + transform.setRotation(rotation); + transform.setScale(_scale); - glm::vec2 topLeft(-x, -y); - glm::vec2 bottomRight(x, y); - glm::vec2 texCoordTopLeft(fromImage.x() / imageWidth, fromImage.y() / imageHeight); - glm::vec2 texCoordBottomRight((fromImage.x() + fromImage.width()) / imageWidth, - (fromImage.y() + fromImage.height()) / imageHeight); - - DependencyManager::get()->renderQuad(topLeft, bottomRight, texCoordTopLeft, texCoordBottomRight, + batch->setModelTransform(transform); + batch->setUniformTexture(0, _texture->getGPUTexture()); + + DependencyManager::get()->renderQuad(*batch, topLeft, bottomRight, texCoordTopLeft, texCoordBottomRight, glm::vec4(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha)); + } else { + glEnable(GL_ALPHA_TEST); + glAlphaFunc(GL_GREATER, 0.5f); - } glPopMatrix(); + glEnable(GL_TEXTURE_2D); + glDisable(GL_LIGHTING); - glDisable(GL_TEXTURE_2D); - glEnable(GL_LIGHTING); - glDisable(GL_ALPHA_TEST); + glBindTexture(GL_TEXTURE_2D, _texture->getID()); - glBindTexture(GL_TEXTURE_2D, 0); + glPushMatrix(); { + glTranslatef(_position.x, _position.y, _position.z); + glm::vec3 axis = glm::axis(rotation); + glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); + glScalef(_scale, _scale, _scale); + + DependencyManager::get()->renderQuad(topLeft, bottomRight, texCoordTopLeft, texCoordBottomRight, + glm::vec4(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha)); + + } glPopMatrix(); + + glDisable(GL_TEXTURE_2D); + glEnable(GL_LIGHTING); + glDisable(GL_ALPHA_TEST); + + glBindTexture(GL_TEXTURE_2D, 0); + } } void BillboardOverlay::setProperties(const QScriptValue &properties) { diff --git a/interface/src/ui/overlays/Grid3DOverlay.cpp b/interface/src/ui/overlays/Grid3DOverlay.cpp index b39b2c3274..e68e5b47f2 100644 --- a/interface/src/ui/overlays/Grid3DOverlay.cpp +++ b/interface/src/ui/overlays/Grid3DOverlay.cpp @@ -36,87 +36,128 @@ void Grid3DOverlay::render(RenderArgs* args) { return; // do nothing if we're not visible } - if (!_gridProgram.isLinked()) { - if (!_gridProgram.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/grid.vert")) { - qDebug() << "Failed to compile: " + _gridProgram.log(); - return; - } - if (!_gridProgram.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/grid.frag")) { - qDebug() << "Failed to compile: " + _gridProgram.log(); - return; - } - if (!_gridProgram.link()) { - qDebug() << "Failed to link: " + _gridProgram.log(); - return; - } - } - - // Render code largely taken from MetavoxelEditor::render() - glDisable(GL_LIGHTING); - - glDepthMask(GL_FALSE); - - glPushMatrix(); - - glm::quat rotation = getRotation(); - - glm::vec3 axis = glm::axis(rotation); - - glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); - - glLineWidth(1.5f); - - // center the grid around the camera position on the plane - glm::vec3 rotated = glm::inverse(rotation) * Application::getInstance()->getCamera()->getPosition(); - float spacing = _minorGridWidth; - - float alpha = getAlpha(); - xColor color = getColor(); - glm::vec3 position = getPosition(); - const int MINOR_GRID_DIVISIONS = 200; const int MAJOR_GRID_DIVISIONS = 100; const float MAX_COLOR = 255.0f; + // center the grid around the camera position on the plane + glm::vec3 rotated = glm::inverse(_rotation) * Application::getInstance()->getCamera()->getPosition(); + float spacing = _minorGridWidth; + + float alpha = getAlpha(); + xColor color = getColor(); glm::vec4 gridColor(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha); - _gridProgram.bind(); + auto batch = args->_batch; - // Minor grid - glPushMatrix(); - { - glTranslatef(_minorGridWidth * (floorf(rotated.x / spacing) - MINOR_GRID_DIVISIONS / 2), - spacing * (floorf(rotated.y / spacing) - MINOR_GRID_DIVISIONS / 2), position.z); + if (batch) { + Transform transform; + transform.setRotation(_rotation); - float scale = MINOR_GRID_DIVISIONS * spacing; - glScalef(scale, scale, scale); - DependencyManager::get()->renderGrid(MINOR_GRID_DIVISIONS, MINOR_GRID_DIVISIONS, gridColor); + // Minor grid + { + batch->_glLineWidth(1.0f); + auto position = glm::vec3(_minorGridWidth * (floorf(rotated.x / spacing) - MINOR_GRID_DIVISIONS / 2), + spacing * (floorf(rotated.y / spacing) - MINOR_GRID_DIVISIONS / 2), + _position.z); + float scale = MINOR_GRID_DIVISIONS * spacing; + + transform.setTranslation(position); + transform.setScale(scale); + + batch->setModelTransform(transform); + + DependencyManager::get()->renderGrid(*batch, MINOR_GRID_DIVISIONS, MINOR_GRID_DIVISIONS, gridColor); + } + + // Major grid + { + batch->_glLineWidth(4.0f); + spacing *= _majorGridEvery; + auto position = glm::vec3(spacing * (floorf(rotated.x / spacing) - MAJOR_GRID_DIVISIONS / 2), + spacing * (floorf(rotated.y / spacing) - MAJOR_GRID_DIVISIONS / 2), + _position.z); + float scale = MAJOR_GRID_DIVISIONS * spacing; + + transform.setTranslation(position); + transform.setScale(scale); + + batch->setModelTransform(transform); + + DependencyManager::get()->renderGrid(*batch, MAJOR_GRID_DIVISIONS, MAJOR_GRID_DIVISIONS, gridColor); + } + } else { + if (!_gridProgram.isLinked()) { + if (!_gridProgram.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/grid.vert")) { + qDebug() << "Failed to compile: " + _gridProgram.log(); + return; + } + if (!_gridProgram.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/grid.frag")) { + qDebug() << "Failed to compile: " + _gridProgram.log(); + return; + } + if (!_gridProgram.link()) { + qDebug() << "Failed to link: " + _gridProgram.log(); + return; + } + } + + // Render code largely taken from MetavoxelEditor::render() + glDisable(GL_LIGHTING); + + glDepthMask(GL_FALSE); + + glPushMatrix(); + + glm::quat rotation = getRotation(); + + glm::vec3 axis = glm::axis(rotation); + + glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); + + glLineWidth(1.5f); + + glm::vec3 position = getPosition(); + + _gridProgram.bind(); + + // Minor grid + glPushMatrix(); + { + glTranslatef(_minorGridWidth * (floorf(rotated.x / spacing) - MINOR_GRID_DIVISIONS / 2), + spacing * (floorf(rotated.y / spacing) - MINOR_GRID_DIVISIONS / 2), position.z); + + float scale = MINOR_GRID_DIVISIONS * spacing; + glScalef(scale, scale, scale); + + DependencyManager::get()->renderGrid(MINOR_GRID_DIVISIONS, MINOR_GRID_DIVISIONS, gridColor); + } + glPopMatrix(); + + // Major grid + glPushMatrix(); + { + glLineWidth(4.0f); + spacing *= _majorGridEvery; + glTranslatef(spacing * (floorf(rotated.x / spacing) - MAJOR_GRID_DIVISIONS / 2), + spacing * (floorf(rotated.y / spacing) - MAJOR_GRID_DIVISIONS / 2), position.z); + + float scale = MAJOR_GRID_DIVISIONS * spacing; + glScalef(scale, scale, scale); + + DependencyManager::get()->renderGrid(MAJOR_GRID_DIVISIONS, MAJOR_GRID_DIVISIONS, gridColor); + } + glPopMatrix(); + + _gridProgram.release(); + + glPopMatrix(); + + glEnable(GL_LIGHTING); + glDepthMask(GL_TRUE); } - glPopMatrix(); - - // Major grid - glPushMatrix(); - { - glLineWidth(4.0f); - spacing *= _majorGridEvery; - glTranslatef(spacing * (floorf(rotated.x / spacing) - MAJOR_GRID_DIVISIONS / 2), - spacing * (floorf(rotated.y / spacing) - MAJOR_GRID_DIVISIONS / 2), position.z); - - float scale = MAJOR_GRID_DIVISIONS * spacing; - glScalef(scale, scale, scale); - - DependencyManager::get()->renderGrid(MAJOR_GRID_DIVISIONS, MAJOR_GRID_DIVISIONS, gridColor); - } - glPopMatrix(); - - _gridProgram.release(); - - glPopMatrix(); - - glEnable(GL_LIGHTING); - glDepthMask(GL_TRUE); } void Grid3DOverlay::setProperties(const QScriptValue& properties) { diff --git a/interface/src/ui/overlays/Rectangle3DOverlay.cpp b/interface/src/ui/overlays/Rectangle3DOverlay.cpp index 8662030e23..dc5fdeabb2 100644 --- a/interface/src/ui/overlays/Rectangle3DOverlay.cpp +++ b/interface/src/ui/overlays/Rectangle3DOverlay.cpp @@ -41,74 +41,116 @@ void Rectangle3DOverlay::render(RenderArgs* args) { const float MAX_COLOR = 255.0f; glm::vec4 rectangleColor(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha); - glDisable(GL_LIGHTING); - glm::vec3 position = getPosition(); glm::vec3 center = getCenter(); glm::vec2 dimensions = getDimensions(); glm::vec2 halfDimensions = dimensions * 0.5f; glm::quat rotation = getRotation(); - float glowLevel = getGlowLevel(); - Glower* glower = NULL; - if (glowLevel > 0.0f) { - glower = new Glower(glowLevel); - } + auto batch = args->_batch; - glPushMatrix(); - glTranslatef(position.x, position.y, position.z); - glm::vec3 axis = glm::axis(rotation); - glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); - glPushMatrix(); - glm::vec3 positionToCenter = center - position; - glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); - //glScalef(dimensions.x, dimensions.y, 1.0f); + if (batch) { + Transform transform; + transform.setTranslation(position); + transform.setRotation(rotation); - glLineWidth(_lineWidth); + batch->setModelTransform(transform); + if (getIsSolid()) { + glm::vec3 topLeft(-halfDimensions.x, -halfDimensions.y, 0.0f); + glm::vec3 bottomRight(halfDimensions.x, halfDimensions.y, 0.0f); + DependencyManager::get()->renderQuad(*batch, topLeft, bottomRight, rectangleColor); + } else { auto geometryCache = DependencyManager::get(); + if (getIsDashedLine()) { + glm::vec3 point1(-halfDimensions.x, -halfDimensions.y, 0.0f); + glm::vec3 point2(halfDimensions.x, -halfDimensions.y, 0.0f); + glm::vec3 point3(halfDimensions.x, halfDimensions.y, 0.0f); + glm::vec3 point4(-halfDimensions.x, halfDimensions.y, 0.0f); - // for our overlay, is solid means we draw a solid "filled" rectangle otherwise we just draw a border line... - if (getIsSolid()) { - glm::vec3 topLeft(-halfDimensions.x, -halfDimensions.y, 0.0f); - glm::vec3 bottomRight(halfDimensions.x, halfDimensions.y, 0.0f); - DependencyManager::get()->renderQuad(topLeft, bottomRight, rectangleColor); + geometryCache->renderDashedLine(*batch, point1, point2, rectangleColor); + geometryCache->renderDashedLine(*batch, point2, point3, rectangleColor); + geometryCache->renderDashedLine(*batch, point3, point4, rectangleColor); + geometryCache->renderDashedLine(*batch, point4, point1, rectangleColor); } else { - if (getIsDashedLine()) { + if (halfDimensions != _previousHalfDimensions) { + QVector border; + border << glm::vec3(-halfDimensions.x, -halfDimensions.y, 0.0f); + border << glm::vec3(halfDimensions.x, -halfDimensions.y, 0.0f); + border << glm::vec3(halfDimensions.x, halfDimensions.y, 0.0f); + border << glm::vec3(-halfDimensions.x, halfDimensions.y, 0.0f); + border << glm::vec3(-halfDimensions.x, -halfDimensions.y, 0.0f); + geometryCache->updateVertices(_geometryCacheID, border, rectangleColor); - glm::vec3 point1(-halfDimensions.x, -halfDimensions.y, 0.0f); - glm::vec3 point2(halfDimensions.x, -halfDimensions.y, 0.0f); - glm::vec3 point3(halfDimensions.x, halfDimensions.y, 0.0f); - glm::vec3 point4(-halfDimensions.x, halfDimensions.y, 0.0f); - - geometryCache->renderDashedLine(point1, point2, rectangleColor); - geometryCache->renderDashedLine(point2, point3, rectangleColor); - geometryCache->renderDashedLine(point3, point4, rectangleColor); - geometryCache->renderDashedLine(point4, point1, rectangleColor); - - } else { - - if (halfDimensions != _previousHalfDimensions) { - QVector border; - border << glm::vec3(-halfDimensions.x, -halfDimensions.y, 0.0f); - border << glm::vec3(halfDimensions.x, -halfDimensions.y, 0.0f); - border << glm::vec3(halfDimensions.x, halfDimensions.y, 0.0f); - border << glm::vec3(-halfDimensions.x, halfDimensions.y, 0.0f); - border << glm::vec3(-halfDimensions.x, -halfDimensions.y, 0.0f); - geometryCache->updateVertices(_geometryCacheID, border, rectangleColor); - - _previousHalfDimensions = halfDimensions; - - } - geometryCache->renderVertices(gpu::LINE_STRIP, _geometryCacheID); + _previousHalfDimensions = halfDimensions; } + geometryCache->renderVertices(*batch, gpu::LINE_STRIP, _geometryCacheID); } - + } + } else { + glDisable(GL_LIGHTING); + + float glowLevel = getGlowLevel(); + Glower* glower = NULL; + if (glowLevel > 0.0f) { + glower = new Glower(glowLevel); + } + + glPushMatrix(); + glTranslatef(position.x, position.y, position.z); + glm::vec3 axis = glm::axis(rotation); + glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); + glPushMatrix(); + glm::vec3 positionToCenter = center - position; + glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); + //glScalef(dimensions.x, dimensions.y, 1.0f); + + glLineWidth(_lineWidth); + + auto geometryCache = DependencyManager::get(); + + // for our overlay, is solid means we draw a solid "filled" rectangle otherwise we just draw a border line... + if (getIsSolid()) { + glm::vec3 topLeft(-halfDimensions.x, -halfDimensions.y, 0.0f); + glm::vec3 bottomRight(halfDimensions.x, halfDimensions.y, 0.0f); + DependencyManager::get()->renderQuad(topLeft, bottomRight, rectangleColor); + } else { + if (getIsDashedLine()) { + + glm::vec3 point1(-halfDimensions.x, -halfDimensions.y, 0.0f); + glm::vec3 point2(halfDimensions.x, -halfDimensions.y, 0.0f); + glm::vec3 point3(halfDimensions.x, halfDimensions.y, 0.0f); + glm::vec3 point4(-halfDimensions.x, halfDimensions.y, 0.0f); + + geometryCache->renderDashedLine(point1, point2, rectangleColor); + geometryCache->renderDashedLine(point2, point3, rectangleColor); + geometryCache->renderDashedLine(point3, point4, rectangleColor); + geometryCache->renderDashedLine(point4, point1, rectangleColor); + + } else { + + if (halfDimensions != _previousHalfDimensions) { + QVector border; + border << glm::vec3(-halfDimensions.x, -halfDimensions.y, 0.0f); + border << glm::vec3(halfDimensions.x, -halfDimensions.y, 0.0f); + border << glm::vec3(halfDimensions.x, halfDimensions.y, 0.0f); + border << glm::vec3(-halfDimensions.x, halfDimensions.y, 0.0f); + border << glm::vec3(-halfDimensions.x, -halfDimensions.y, 0.0f); + geometryCache->updateVertices(_geometryCacheID, border, rectangleColor); + + _previousHalfDimensions = halfDimensions; + + } + geometryCache->renderVertices(gpu::LINE_STRIP, _geometryCacheID); + } + } + + glPopMatrix(); glPopMatrix(); - glPopMatrix(); - - if (glower) { - delete glower; + + if (glower) { + delete glower; + } } } From 569971582d3d7f9bffa18803858c8b29a4ef4739 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Jun 2015 18:39:35 -0700 Subject: [PATCH 61/90] more hacking on trying to port atmospheres to the new pipeline --- interface/src/Environment.cpp | 96 +++---------------- libraries/gpu/src/gpu/Batch.h | 4 +- libraries/gpu/src/gpu/GLBackend.cpp | 25 +++++ libraries/gpu/src/gpu/GLBackend.h | 2 + .../model/src/model/SkyFromAtmosphere.slf | 8 +- .../model/src/model/SkyFromAtmosphere.slv | 1 - 6 files changed, 50 insertions(+), 86 deletions(-) diff --git a/interface/src/Environment.cpp b/interface/src/Environment.cpp index 1e9c571a57..66b463949a 100644 --- a/interface/src/Environment.cpp +++ b/interface/src/Environment.cpp @@ -15,6 +15,7 @@ #include #include +#include #include #include #include @@ -32,6 +33,8 @@ #include "../../build/libraries/model/SkyFromSpace_frag.h" #include "../../build/libraries/model/SkyFromAtmosphere_vert.h" #include "../../build/libraries/model/SkyFromAtmosphere_frag.h" +#include "../../build/libraries/render-utils/simple_vert.h" +#include "../../build/libraries/render-utils/simple_frag.h" uint qHash(const HifiSockAddr& sockAddr) { if (sockAddr.getAddress().isNull()) { @@ -64,11 +67,11 @@ void Environment::init() { - qDebug() << "line:" << __LINE__; + qDebug() << "here:" << __LINE__; setupAtmosphereProgram(SkyFromSpace_vert, SkyFromSpace_frag, _newSkyFromSpaceProgram, _newSkyFromSpaceUniformLocations); - qDebug() << "line:" << __LINE__; + qDebug() << "here:" << __LINE__; setupAtmosphereProgram(SkyFromAtmosphere_vert, SkyFromAtmosphere_frag, _newSkyFromAtmosphereProgram, _newSkyFromAtmosphereUniformLocations); - qDebug() << "line:" << __LINE__; + qDebug() << "here:" << __LINE__; // start off with a default-constructed environment data @@ -77,7 +80,7 @@ void Environment::init() { _initialized = true; } -void Environment::setupAtmosphereProgram(const char* vertSource, const char* fragSource, gpu::PipelinePointer& pipelineProgram, int* locations) { +void Environment::setupAtmosphereProgram(const char* vertSource, const char* fragSource, gpu::PipelinePointer& pipeline, int* locations) { auto VS = gpu::ShaderPointer(gpu::Shader::createVertex(std::string(vertSource))); auto PS = gpu::ShaderPointer(gpu::Shader::createPixel(std::string(fragSource))); @@ -91,7 +94,7 @@ void Environment::setupAtmosphereProgram(const char* vertSource, const char* fra state->setCullMode(gpu::State::CULL_NONE); state->setDepthTest(false); state->setBlendFunction(true,gpu::State::SRC_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::INV_SRC_ALPHA); - pipelineProgram = gpu::PipelinePointer(gpu::Pipeline::create(program, state)); + pipeline = gpu::PipelinePointer(gpu::Pipeline::create(program, state)); locations[CAMERA_POS_LOCATION] = program->getUniforms().findLocation("v3CameraPos"); locations[LIGHT_POS_LOCATION] = program->getUniforms().findLocation("v3LightPos"); @@ -109,34 +112,6 @@ void Environment::setupAtmosphereProgram(const char* vertSource, const char* fra locations[SCALE_OVER_SCALE_DEPTH_LOCATION] = program->getUniforms().findLocation("fScaleOverScaleDepth"); locations[G_LOCATION] = program->getUniforms().findLocation("g"); locations[G2_LOCATION] = program->getUniforms().findLocation("g2"); - - /* - - program.addShaderFromSourceCode(QGLShader::Vertex, vertSource); - program.addShaderFromSourceCode(QGLShader::Fragment, fragSource); - program.link(); - - program.bind(); - - locations[CAMERA_POS_LOCATION] = program.uniformLocation("v3CameraPos"); - locations[LIGHT_POS_LOCATION] = program.uniformLocation("v3LightPos"); - locations[INV_WAVELENGTH_LOCATION] = program.uniformLocation("v3InvWavelength"); - locations[CAMERA_HEIGHT2_LOCATION] = program.uniformLocation("fCameraHeight2"); - locations[OUTER_RADIUS_LOCATION] = program.uniformLocation("fOuterRadius"); - locations[OUTER_RADIUS2_LOCATION] = program.uniformLocation("fOuterRadius2"); - locations[INNER_RADIUS_LOCATION] = program.uniformLocation("fInnerRadius"); - locations[KR_ESUN_LOCATION] = program.uniformLocation("fKrESun"); - locations[KM_ESUN_LOCATION] = program.uniformLocation("fKmESun"); - locations[KR_4PI_LOCATION] = program.uniformLocation("fKr4PI"); - locations[KM_4PI_LOCATION] = program.uniformLocation("fKm4PI"); - locations[SCALE_LOCATION] = program.uniformLocation("fScale"); - locations[SCALE_DEPTH_LOCATION] = program.uniformLocation("fScaleDepth"); - locations[SCALE_OVER_SCALE_DEPTH_LOCATION] = program.uniformLocation("fScaleOverScaleDepth"); - locations[G_LOCATION] = program.uniformLocation("g"); - locations[G2_LOCATION] = program.uniformLocation("g2"); - - program.release(); - */ } void Environment::resetToDefault() { @@ -305,29 +280,24 @@ ProgramObject* Environment::createSkyProgram(const char* from, int* locations) { } void Environment::renderAtmosphere(gpu::Batch& batch, ViewFrustum& camera, const EnvironmentData& data) { + glm::vec3 center = data.getAtmosphereCenter(); - //glPushMatrix(); - //glTranslatef(center.x, center.y, center.z); - Transform transform; transform.setTranslation(center); - transform.setScale(1.0f); + //transform.setScale(2.0f); batch.setModelTransform(transform); glm::vec3 relativeCameraPos = camera.getPosition() - center; float height = glm::length(relativeCameraPos); // use the appropriate shader depending on whether we're inside or outside - //ProgramObject* program; int* locations; if (height < data.getAtmosphereOuterRadius()) { - //program = &_newSkyFromAtmosphereProgram; batch.setPipeline(_newSkyFromAtmosphereProgram); locations = _newSkyFromAtmosphereUniformLocations; } else { - //program = &_newSkyFromSpaceProgram; batch.setPipeline(_newSkyFromSpaceProgram); locations = _newSkyFromSpaceUniformLocations; } @@ -335,39 +305,13 @@ void Environment::renderAtmosphere(gpu::Batch& batch, ViewFrustum& camera, const // the constants here are from Sean O'Neil's GPU Gems entry // (http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter16.html), GameEngine.cpp - //program->bind(); - /* - program->setUniform(locations[CAMERA_POS_LOCATION], relativeCameraPos); + batch._glUniform3f(locations[CAMERA_POS_LOCATION], relativeCameraPos.x, relativeCameraPos.y, relativeCameraPos.z); glm::vec3 lightDirection = glm::normalize(data.getSunLocation()); - program->setUniform(locations[LIGHT_POS_LOCATION], lightDirection); - program->setUniformValue(locations[INV_WAVELENGTH_LOCATION], - 1 / powf(data.getScatteringWavelengths().r, 4.0f), - 1 / powf(data.getScatteringWavelengths().g, 4.0f), - 1 / powf(data.getScatteringWavelengths().b, 4.0f)); - program->setUniformValue(locations[CAMERA_HEIGHT2_LOCATION], height * height); - program->setUniformValue(locations[OUTER_RADIUS_LOCATION], data.getAtmosphereOuterRadius()); - program->setUniformValue(locations[OUTER_RADIUS2_LOCATION], data.getAtmosphereOuterRadius() * data.getAtmosphereOuterRadius()); - program->setUniformValue(locations[INNER_RADIUS_LOCATION], data.getAtmosphereInnerRadius()); - program->setUniformValue(locations[KR_ESUN_LOCATION], data.getRayleighScattering() * data.getSunBrightness()); - program->setUniformValue(locations[KM_ESUN_LOCATION], data.getMieScattering() * data.getSunBrightness()); - program->setUniformValue(locations[KR_4PI_LOCATION], data.getRayleighScattering() * 4.0f * PI); - program->setUniformValue(locations[KM_4PI_LOCATION], data.getMieScattering() * 4.0f * PI); - program->setUniformValue(locations[SCALE_LOCATION], 1.0f / (data.getAtmosphereOuterRadius() - data.getAtmosphereInnerRadius())); - program->setUniformValue(locations[SCALE_DEPTH_LOCATION], 0.25f); - program->setUniformValue(locations[SCALE_OVER_SCALE_DEPTH_LOCATION], - (1.0f / (data.getAtmosphereOuterRadius() - data.getAtmosphereInnerRadius())) / 0.25f); - program->setUniformValue(locations[G_LOCATION], -0.990f); - program->setUniformValue(locations[G2_LOCATION], -0.990f * -0.990f); - */ - - - batch._glUniform3fv(locations[CAMERA_POS_LOCATION], relativeCameraPos); - glm::vec3 lightDirection = glm::normalize(data.getSunLocation()); - batch._glUniform3fv(locations[LIGHT_POS_LOCATION], lightDirection); + batch._glUniform3f(locations[LIGHT_POS_LOCATION], lightDirection.x, lightDirection.y, lightDirection.z); batch._glUniform3f(locations[INV_WAVELENGTH_LOCATION], - 1 / powf(data.getScatteringWavelengths().r, 4.0f), - 1 / powf(data.getScatteringWavelengths().g, 4.0f), - 1 / powf(data.getScatteringWavelengths().b, 4.0f)); + 1 / powf(data.getScatteringWavelengths().r, 4.0f), + 1 / powf(data.getScatteringWavelengths().g, 4.0f), + 1 / powf(data.getScatteringWavelengths().b, 4.0f)); batch._glUniform1f(locations[CAMERA_HEIGHT2_LOCATION], height * height); batch._glUniform1f(locations[OUTER_RADIUS_LOCATION], data.getAtmosphereOuterRadius()); batch._glUniform1f(locations[OUTER_RADIUS2_LOCATION], data.getAtmosphereOuterRadius() * data.getAtmosphereOuterRadius()); @@ -383,15 +327,5 @@ void Environment::renderAtmosphere(gpu::Batch& batch, ViewFrustum& camera, const batch._glUniform1f(locations[G_LOCATION], -0.990f); batch._glUniform1f(locations[G2_LOCATION], -0.990f * -0.990f); - - //glDepthMask(GL_FALSE); - //glDisable(GL_DEPTH_TEST); - //glDisable(GL_CULL_FACE); - //glEnable(GL_BLEND); DependencyManager::get()->renderSphere(batch,1.0f, 100, 50, glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)); //Draw a unit sphere - //glDepthMask(GL_TRUE); - - //program->release(); - - //glPopMatrix(); } diff --git a/libraries/gpu/src/gpu/Batch.h b/libraries/gpu/src/gpu/Batch.h index 77c9308af5..bbd2121c54 100644 --- a/libraries/gpu/src/gpu/Batch.h +++ b/libraries/gpu/src/gpu/Batch.h @@ -150,7 +150,8 @@ public: void _glUseProgram(GLuint program); void _glUniform1f(GLint location, GLfloat v0); void _glUniform2f(GLint location, GLfloat v0, GLfloat v1); - void _glUniform3f(GLint location, GLfloat v0, GLfloat v1); + void _glUniform3f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2); + void _glUniform3fv(GLint location, GLsizei count, const GLfloat* value); void _glUniform4fv(GLint location, GLsizei count, const GLfloat* value); void _glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); @@ -212,6 +213,7 @@ public: COMMAND_glUniform1f, COMMAND_glUniform2f, COMMAND_glUniform3f, + COMMAND_glUniform3fv, COMMAND_glUniform4fv, COMMAND_glUniformMatrix4fv, diff --git a/libraries/gpu/src/gpu/GLBackend.cpp b/libraries/gpu/src/gpu/GLBackend.cpp index 7ba344dfbd..20a6b60901 100644 --- a/libraries/gpu/src/gpu/GLBackend.cpp +++ b/libraries/gpu/src/gpu/GLBackend.cpp @@ -62,6 +62,7 @@ GLBackend::CommandCall GLBackend::_commandCalls[Batch::NUM_COMMANDS] = (&::gpu::GLBackend::do_glUniform1f), (&::gpu::GLBackend::do_glUniform2f), (&::gpu::GLBackend::do_glUniform3f), + (&::gpu::GLBackend::do_glUniform3fv), (&::gpu::GLBackend::do_glUniform4fv), (&::gpu::GLBackend::do_glUniformMatrix4fv), @@ -502,6 +503,30 @@ void GLBackend::do_glUniform3f(Batch& batch, uint32 paramOffset) { (void) CHECK_GL_ERROR(); } +void Batch::_glUniform3fv(GLint location, GLsizei count, const GLfloat* value) { + ADD_COMMAND_GL(glUniform3fv); + + const int VEC3_SIZE = 3 * sizeof(float); + _params.push_back(cacheData(count * VEC3_SIZE, value)); + _params.push_back(count); + _params.push_back(location); + + DO_IT_NOW(_glUniform3fv, 3); +} +void GLBackend::do_glUniform3fv(Batch& batch, uint32 paramOffset) { + if (_pipeline._program == 0) { + // We should call updatePipeline() to bind the program but we are not doing that + // because these uniform setters are deprecated and we don;t want to create side effect + return; + } + glUniform3fv( + batch._params[paramOffset + 2]._int, + batch._params[paramOffset + 1]._uint, + (const GLfloat*)batch.editData(batch._params[paramOffset + 0]._uint)); + + (void) CHECK_GL_ERROR(); +} + void Batch::_glUniform4fv(GLint location, GLsizei count, const GLfloat* value) { ADD_COMMAND_GL(glUniform4fv); diff --git a/libraries/gpu/src/gpu/GLBackend.h b/libraries/gpu/src/gpu/GLBackend.h index e7a5e62df8..c87394869c 100644 --- a/libraries/gpu/src/gpu/GLBackend.h +++ b/libraries/gpu/src/gpu/GLBackend.h @@ -379,6 +379,8 @@ protected: void do_glUseProgram(Batch& batch, uint32 paramOffset); void do_glUniform1f(Batch& batch, uint32 paramOffset); void do_glUniform2f(Batch& batch, uint32 paramOffset); + void do_glUniform3f(Batch& batch, uint32 paramOffset); + void do_glUniform3fv(Batch& batch, uint32 paramOffset); void do_glUniform4fv(Batch& batch, uint32 paramOffset); void do_glUniformMatrix4fv(Batch& batch, uint32 paramOffset); diff --git a/libraries/model/src/model/SkyFromAtmosphere.slf b/libraries/model/src/model/SkyFromAtmosphere.slf index b82cddc282..a9e2bc6156 100755 --- a/libraries/model/src/model/SkyFromAtmosphere.slf +++ b/libraries/model/src/model/SkyFromAtmosphere.slf @@ -104,7 +104,9 @@ void main (void) float fCos = dot(v3LightPos, v3Direction) / length(v3Direction); float fMiePhase = 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + fCos*fCos) / pow(1.0 + g2 - 2.0*g*fCos, 1.5); - gl_FragColor.rgb = frontColor.rgb + fMiePhase * secondaryFrontColor.rgb; - gl_FragColor.a = gl_FragColor.b; - gl_FragColor.rgb = pow(gl_FragColor.rgb, vec3(1.0/2.2)); + + vec3 finalColor = frontColor.rgb + fMiePhase * secondaryFrontColor.rgb; + gl_FragData[0].rgb = finalColor; + gl_FragData[0].a = finalColor.b; + gl_FragData[0].rgb = pow(finalColor.rgb, vec3(1.0/2.2)); } diff --git a/libraries/model/src/model/SkyFromAtmosphere.slv b/libraries/model/src/model/SkyFromAtmosphere.slv index c19cb34c6a..99c782adf1 100755 --- a/libraries/model/src/model/SkyFromAtmosphere.slv +++ b/libraries/model/src/model/SkyFromAtmosphere.slv @@ -55,7 +55,6 @@ const float fSamples = 2.0; varying vec3 myPosition; - void main(void) { // Get the ray from the camera to the vertex, and its length (which is the far point of the ray passing through the atmosphere) From 006899d73ff5afec4ca538a87bed39ff084997ce Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Jun 2015 22:23:14 -0700 Subject: [PATCH 62/90] more hacking almost working --- interface/src/Application.cpp | 9 +++++---- interface/src/Environment.cpp | 23 ++++++++++++++++++++--- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 5726dcacd5..efe7df4240 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3330,10 +3330,11 @@ namespace render { PerformanceTimer perfTimer("atmosphere"); PerformanceWarning warn(Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings), "Application::displaySide() ... atmosphere..."); - //gpu::Batch batch; - background->_environment->renderAtmospheres(batch, *(args->_viewFrustum)); - //gpu::GLBackend::renderBatch(batch, true); - //glUseProgram(0); + gpu::Batch batch; + //DependencyManager::get()->renderSolidSphere(batch,0.5f, 100, 50, glm::vec4(1.0f, 0.0f, 0.0f, 1.0f)); //Draw a unit sphere + background->_environment->renderAtmospheres(batch, *(args->_viewFrustum)); + gpu::GLBackend::renderBatch(batch, true); + glUseProgram(0); } diff --git a/interface/src/Environment.cpp b/interface/src/Environment.cpp index 66b463949a..b80e4795d4 100644 --- a/interface/src/Environment.cpp +++ b/interface/src/Environment.cpp @@ -36,6 +36,9 @@ #include "../../build/libraries/render-utils/simple_vert.h" #include "../../build/libraries/render-utils/simple_frag.h" +#include "../../build/libraries/render-utils/other_simple_vert.h" +#include "../../build/libraries/render-utils/other_simple_frag.h" + uint qHash(const HifiSockAddr& sockAddr) { if (sockAddr.getAddress().isNull()) { return 0; // shouldn't happen, but if it does, zero is a perfectly valid hash @@ -69,8 +72,10 @@ void Environment::init() { qDebug() << "here:" << __LINE__; setupAtmosphereProgram(SkyFromSpace_vert, SkyFromSpace_frag, _newSkyFromSpaceProgram, _newSkyFromSpaceUniformLocations); + //setupAtmosphereProgram(other_simple_vert, other_simple_frag, _newSkyFromSpaceProgram, _newSkyFromSpaceUniformLocations); qDebug() << "here:" << __LINE__; setupAtmosphereProgram(SkyFromAtmosphere_vert, SkyFromAtmosphere_frag, _newSkyFromAtmosphereProgram, _newSkyFromAtmosphereUniformLocations); + //setupAtmosphereProgram(other_simple_vert, other_simple_frag, _newSkyFromAtmosphereProgram, _newSkyFromAtmosphereUniformLocations); qDebug() << "here:" << __LINE__; @@ -91,9 +96,19 @@ void Environment::setupAtmosphereProgram(const char* vertSource, const char* fra gpu::Shader::makeProgram(*program, slotBindings); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); + + /* state->setCullMode(gpu::State::CULL_NONE); state->setDepthTest(false); state->setBlendFunction(true,gpu::State::SRC_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::INV_SRC_ALPHA); + */ + + state->setCullMode(gpu::State::CULL_NONE); + state->setDepthTest(false); + state->setBlendFunction(false, + gpu::State::SRC_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::INV_SRC_ALPHA, + gpu::State::FACTOR_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::ONE); + pipeline = gpu::PipelinePointer(gpu::Pipeline::create(program, state)); locations[CAMERA_POS_LOCATION] = program->getUniforms().findLocation("v3CameraPos"); @@ -280,12 +295,13 @@ ProgramObject* Environment::createSkyProgram(const char* from, int* locations) { } void Environment::renderAtmosphere(gpu::Batch& batch, ViewFrustum& camera, const EnvironmentData& data) { - + glm::vec3 center = data.getAtmosphereCenter(); Transform transform; transform.setTranslation(center); //transform.setScale(2.0f); + //transform.setTranslation(glm::vec3(0,0,0)); batch.setModelTransform(transform); glm::vec3 relativeCameraPos = camera.getPosition() - center; @@ -304,7 +320,8 @@ void Environment::renderAtmosphere(gpu::Batch& batch, ViewFrustum& camera, const // the constants here are from Sean O'Neil's GPU Gems entry // (http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter16.html), GameEngine.cpp - + + batch._glUniform3f(locations[CAMERA_POS_LOCATION], relativeCameraPos.x, relativeCameraPos.y, relativeCameraPos.z); glm::vec3 lightDirection = glm::normalize(data.getSunLocation()); batch._glUniform3f(locations[LIGHT_POS_LOCATION], lightDirection.x, lightDirection.y, lightDirection.z); @@ -327,5 +344,5 @@ void Environment::renderAtmosphere(gpu::Batch& batch, ViewFrustum& camera, const batch._glUniform1f(locations[G_LOCATION], -0.990f); batch._glUniform1f(locations[G2_LOCATION], -0.990f * -0.990f); - DependencyManager::get()->renderSphere(batch,1.0f, 100, 50, glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)); //Draw a unit sphere + DependencyManager::get()->renderSphere(batch,1.0f, 100, 50, glm::vec4(1.0f, 0.0f, 0.0f, 0.5f)); //Draw a unit sphere } From 5c547037f26ab6d51c2c55c9c484fddfd6a85a7e Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Wed, 17 Jun 2015 15:54:20 +0200 Subject: [PATCH 63/90] Migrating the overaly 3d rendering in their own job and their own shader --- .../src/ui/overlays/BillboardOverlay.cpp | 2 + interface/src/ui/overlays/Cube3DOverlay.cpp | 3 +- .../render-utils/src/RenderDeferredTask.cpp | 73 ++++++++++++++++++- .../render-utils/src/RenderDeferredTask.h | 11 +++ libraries/render-utils/src/overlay3D.slf | 28 +++++++ libraries/render-utils/src/overlay3D.slv | 40 ++++++++++ libraries/shared/src/RenderArgs.h | 5 ++ 7 files changed, 159 insertions(+), 3 deletions(-) create mode 100644 libraries/render-utils/src/overlay3D.slf create mode 100644 libraries/render-utils/src/overlay3D.slv diff --git a/interface/src/ui/overlays/BillboardOverlay.cpp b/interface/src/ui/overlays/BillboardOverlay.cpp index ed0ddd8dc7..e7b043f44f 100644 --- a/interface/src/ui/overlays/BillboardOverlay.cpp +++ b/interface/src/ui/overlays/BillboardOverlay.cpp @@ -99,6 +99,8 @@ void BillboardOverlay::render(RenderArgs* args) { DependencyManager::get()->renderQuad(*batch, topLeft, bottomRight, texCoordTopLeft, texCoordBottomRight, glm::vec4(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha)); + + batch->setUniformTexture(0, args->_whiteTexture); // restore default white color after me } else { glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.5f); diff --git a/interface/src/ui/overlays/Cube3DOverlay.cpp b/interface/src/ui/overlays/Cube3DOverlay.cpp index 73406c07a0..d048b1a05a 100644 --- a/interface/src/ui/overlays/Cube3DOverlay.cpp +++ b/interface/src/ui/overlays/Cube3DOverlay.cpp @@ -69,8 +69,9 @@ void Cube3DOverlay::render(RenderArgs* args) { transform.setScale(dimensions); batch->setModelTransform(transform); + DependencyManager::get()->renderSolidCube(*batch, 1.0f, cubeColor); - DependencyManager::get()->renderSolidCube(*batch, 1.0f, cubeColor); + //DependencyManager::get()->renderSolidCube(*batch, 1.0f, cubeColor); } else { if (getIsDashedLine()) { diff --git a/libraries/render-utils/src/RenderDeferredTask.cpp b/libraries/render-utils/src/RenderDeferredTask.cpp index d9dda279e0..ce3c6769ca 100755 --- a/libraries/render-utils/src/RenderDeferredTask.cpp +++ b/libraries/render-utils/src/RenderDeferredTask.cpp @@ -15,9 +15,12 @@ #include "DeferredLightingEffect.h" #include "ViewFrustum.h" #include "RenderArgs.h" +#include "TextureCache.h" #include +#include "overlay3D_vert.h" +#include "overlay3D_frag.h" using namespace render; @@ -50,7 +53,7 @@ RenderDeferredTask::RenderDeferredTask() : Task() { _jobs.push_back(Job(RenderDeferred())); _jobs.push_back(Job(ResolveDeferred())); _jobs.push_back(Job(DrawTransparentDeferred())); - _jobs.push_back(Job(DrawPostLayered())); + _jobs.push_back(Job(DrawOverlay3D())); _jobs.push_back(Job(ResetGLState())); } @@ -225,10 +228,76 @@ template <> void render::jobRun(const DrawTransparentDeferred& job, const SceneC renderItems(sceneContext, renderContext, renderedItems, renderContext->_maxDrawnTransparentItems); + // Before rendering the batch make sure we re in sync with gl state + args->_context->syncCache(); args->_context->render((*args->_batch)); args->_batch = nullptr; // reset blend function to standard... - glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_CONSTANT_ALPHA, GL_ONE); + // glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_CONSTANT_ALPHA, GL_ONE); } } + +const gpu::PipelinePointer& DrawOverlay3D::getOpaquePipeline() const { + if (!_opaquePipeline) { + auto vs = gpu::ShaderPointer(gpu::Shader::createVertex(std::string(overlay3D_vert))); + auto ps = gpu::ShaderPointer(gpu::Shader::createPixel(std::string(overlay3D_frag))); + + auto program = gpu::ShaderPointer(gpu::Shader::createProgram(vs, ps)); + + auto state = gpu::StatePointer(new gpu::State()); + state->setDepthTest(true, true, gpu::LESS_EQUAL); + + _opaquePipeline.reset(gpu::Pipeline::create(program, state)); + } + return _opaquePipeline; +} + +template <> void render::jobRun(const DrawOverlay3D& job, const SceneContextPointer& sceneContext, const RenderContextPointer& renderContext) { + PerformanceTimer perfTimer("DrawOverlay3D"); + assert(renderContext->args); + assert(renderContext->args->_viewFrustum); + + // render backgrounds + auto& scene = sceneContext->_scene; + auto& items = scene->getMasterBucket().at(ItemFilter::Builder::opaqueShape().withLayered()); + + + ItemIDsBounds inItems; + inItems.reserve(items.size()); + for (auto id : items) { + auto& item = scene->getItem(id); + if (item.getKey().isVisible() && (item.getLayer() == 1)) { + inItems.emplace_back(id); + } + } + + RenderArgs* args = renderContext->args; + gpu::Batch batch; + args->_batch = &batch; + args->_whiteTexture = DependencyManager::get()->getWhiteTexture(); + + + glm::mat4 projMat; + Transform viewMat; + args->_viewFrustum->evalProjectionMatrix(projMat); + args->_viewFrustum->evalViewTransform(viewMat); + if (args->_renderMode == RenderArgs::MIRROR_RENDER_MODE) { + viewMat.postScale(glm::vec3(-1.0f, 1.0f, 1.0f)); + } + batch.setProjectionTransform(projMat); + batch.setViewTransform(viewMat); + batch.setPipeline(job.getOpaquePipeline()); + batch.setUniformTexture(0, args->_whiteTexture); + + if (!inItems.empty()) { + batch.clearFramebuffer(gpu::Framebuffer::BUFFER_DEPTH, glm::vec4(), 1.f, 0); + renderItems(sceneContext, renderContext, inItems); + } + + // Before rendering the batch make sure we re in sync with gl state + args->_context->syncCache(); + args->_context->render((*args->_batch)); + args->_batch = nullptr; + args->_whiteTexture.reset(); +} diff --git a/libraries/render-utils/src/RenderDeferredTask.h b/libraries/render-utils/src/RenderDeferredTask.h index e2cac53c0d..3b0ffdfc9b 100755 --- a/libraries/render-utils/src/RenderDeferredTask.h +++ b/libraries/render-utils/src/RenderDeferredTask.h @@ -14,6 +14,8 @@ #include "render/DrawTask.h" +#include "gpu/Pipeline.h" + class PrepareDeferred { public: }; @@ -50,6 +52,15 @@ namespace render { template <> void jobRun(const DrawTransparentDeferred& job, const SceneContextPointer& sceneContext, const RenderContextPointer& renderContext); } +class DrawOverlay3D { + mutable gpu::PipelinePointer _opaquePipeline; //lazy evaluation hence mutable +public: + const gpu::PipelinePointer& getOpaquePipeline() const; +}; +namespace render { +template <> void jobRun(const DrawOverlay3D& job, const SceneContextPointer& sceneContext, const RenderContextPointer& renderContext); +} + class RenderDeferredTask : public render::Task { public: diff --git a/libraries/render-utils/src/overlay3D.slf b/libraries/render-utils/src/overlay3D.slf new file mode 100644 index 0000000000..8686066dd8 --- /dev/null +++ b/libraries/render-utils/src/overlay3D.slf @@ -0,0 +1,28 @@ +<@include gpu/Config.slh@> +<$VERSION_HEADER$> +// Generated on <$_SCRIBE_DATE$> +// model.frag +// fragment shader +// +// Created by Sam Gateau on 6/16/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 +// + +uniform sampler2D diffuseMap; + +varying vec2 varTexcoord; + +varying vec3 varEyeNormal; + +varying vec4 varColor; + + +void main(void) { + vec4 diffuse = texture2D(diffuseMap, varTexcoord.st); + + + gl_FragColor = vec4(varColor * diffuse); +} diff --git a/libraries/render-utils/src/overlay3D.slv b/libraries/render-utils/src/overlay3D.slv new file mode 100644 index 0000000000..b272b2bfd0 --- /dev/null +++ b/libraries/render-utils/src/overlay3D.slv @@ -0,0 +1,40 @@ +<@include gpu/Config.slh@> +<$VERSION_HEADER$> +// Generated on <$_SCRIBE_DATE$> +// overlay3D.slv +// +// Created by Sam Gateau on 6/16/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 +// + +<@include gpu/Transform.slh@> + +<$declareStandardTransform()$> + +attribute vec2 attribTexcoord; + +varying vec2 varTexcoord; + +// interpolated eye position +varying vec4 varEyePosition; + +// the interpolated normal +varying vec3 varEyeNormal; + +varying vec4 varColor; + +void main(void) { + varTexcoord = attribTexcoord; + + // pass along the color + varColor = gl_Color; + + // standard transform + TransformCamera cam = getTransformCamera(); + TransformObject obj = getTransformObject(); + <$transformModelToEyeAndClipPos(cam, obj, gl_Vertex, varEyePosition, gl_Position)$> + <$transformModelToEyeDir(cam, obj, gl_Normal, varEyeNormal.xyz)$> +} diff --git a/libraries/shared/src/RenderArgs.h b/libraries/shared/src/RenderArgs.h index 84b3a202b4..9673623b13 100644 --- a/libraries/shared/src/RenderArgs.h +++ b/libraries/shared/src/RenderArgs.h @@ -13,6 +13,8 @@ #define hifi_RenderArgs_h #include +#include + class AABox; class OctreeRenderer; @@ -20,6 +22,7 @@ class ViewFrustum; namespace gpu { class Batch; class Context; +class Texture; } class RenderDetails { @@ -109,6 +112,8 @@ public: gpu::Batch* _batch = nullptr; ShoudRenderFunctor _shouldRender; + std::shared_ptr _whiteTexture; + RenderDetails _details; float _alphaThreshold = 0.5f; From d703748ec3ad34ad87062bcbe7a8f1bb5792f0ef Mon Sep 17 00:00:00 2001 From: samcake Date: Wed, 17 Jun 2015 16:44:02 +0200 Subject: [PATCH 64/90] trying to solve the rendering of overlay3d --- interface/src/ui/overlays/OverlaysPayload.cpp | 8 +++++--- libraries/render-utils/src/overlay3D.slf | 6 ++++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/interface/src/ui/overlays/OverlaysPayload.cpp b/interface/src/ui/overlays/OverlaysPayload.cpp index d5e4b34f6b..bcfba67313 100644 --- a/interface/src/ui/overlays/OverlaysPayload.cpp +++ b/interface/src/ui/overlays/OverlaysPayload.cpp @@ -66,8 +66,8 @@ namespace render { } template <> void payloadRender(const Overlay::Pointer& overlay, RenderArgs* args) { if (args) { - glPushMatrix(); if (overlay->getAnchor() == Overlay::MY_AVATAR) { + glPushMatrix(); MyAvatar* avatar = DependencyManager::get()->getMyAvatar(); glm::quat myAvatarRotation = avatar->getOrientation(); glm::vec3 myAvatarPosition = avatar->getPosition(); @@ -78,9 +78,11 @@ namespace render { glTranslatef(myAvatarPosition.x, myAvatarPosition.y, myAvatarPosition.z); glRotatef(angle, axis.x, axis.y, axis.z); glScalef(myAvatarScale, myAvatarScale, myAvatarScale); + overlay->render(args); + glPopMatrix(); + } else { + overlay->render(args); } - overlay->render(args); - glPopMatrix(); } } } diff --git a/libraries/render-utils/src/overlay3D.slf b/libraries/render-utils/src/overlay3D.slf index 8686066dd8..e38086ebb5 100644 --- a/libraries/render-utils/src/overlay3D.slf +++ b/libraries/render-utils/src/overlay3D.slf @@ -22,7 +22,9 @@ varying vec4 varColor; void main(void) { vec4 diffuse = texture2D(diffuseMap, varTexcoord.st); - + if (diffuse.a < 0.5) { + discard; + } - gl_FragColor = vec4(varColor * diffuse); + gl_FragColor = vec4(varColor.rgb * (1 - diffuse.a) + diffuse.a * diffuse.rgb, 1.0); } From febc3333cd45839381d37733298e58c9aaa5b07b Mon Sep 17 00:00:00 2001 From: samcake Date: Wed, 17 Jun 2015 16:50:35 +0200 Subject: [PATCH 65/90] Solving the rendering of textured overlay3d --- libraries/gpu/src/gpu/GLBackendShader.cpp | 6 +++++- libraries/render-utils/src/overlay3D.slv | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/libraries/gpu/src/gpu/GLBackendShader.cpp b/libraries/gpu/src/gpu/GLBackendShader.cpp index e0ea2f2d98..45adbcdb3c 100755 --- a/libraries/gpu/src/gpu/GLBackendShader.cpp +++ b/libraries/gpu/src/gpu/GLBackendShader.cpp @@ -61,7 +61,11 @@ void makeBindings(GLBackend::GLShader* shader) { if (loc >= 0) { glBindAttribLocation(glprogram, gpu::Stream::TEXCOORD, "texcoord"); } - + loc = glGetAttribLocation(glprogram, "attribTexcoord"); + if (loc >= 0) { + glBindAttribLocation(glprogram, gpu::Stream::TEXCOORD, "attribTexcoord"); + } + loc = glGetAttribLocation(glprogram, "tangent"); if (loc >= 0) { glBindAttribLocation(glprogram, gpu::Stream::TANGENT, "tangent"); diff --git a/libraries/render-utils/src/overlay3D.slv b/libraries/render-utils/src/overlay3D.slv index b272b2bfd0..cdb11c1d08 100644 --- a/libraries/render-utils/src/overlay3D.slv +++ b/libraries/render-utils/src/overlay3D.slv @@ -14,7 +14,7 @@ <$declareStandardTransform()$> -attribute vec2 attribTexcoord; +//attribute vec2 texcoord; varying vec2 varTexcoord; @@ -27,7 +27,7 @@ varying vec3 varEyeNormal; varying vec4 varColor; void main(void) { - varTexcoord = attribTexcoord; + varTexcoord = gl_MultiTexCoord0.xy; // pass along the color varColor = gl_Color; From 3176c8e93c1e82aae16b22ae986e16bf6588a9ed Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Wed, 17 Jun 2015 17:09:33 +0200 Subject: [PATCH 66/90] polish before PR --- interface/src/ui/overlays/Cube3DOverlay.cpp | 2 -- libraries/render-utils/src/overlay3D.slf | 3 +-- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/interface/src/ui/overlays/Cube3DOverlay.cpp b/interface/src/ui/overlays/Cube3DOverlay.cpp index d048b1a05a..37b30a5bcb 100644 --- a/interface/src/ui/overlays/Cube3DOverlay.cpp +++ b/interface/src/ui/overlays/Cube3DOverlay.cpp @@ -70,8 +70,6 @@ void Cube3DOverlay::render(RenderArgs* args) { transform.setScale(dimensions); batch->setModelTransform(transform); DependencyManager::get()->renderSolidCube(*batch, 1.0f, cubeColor); - - //DependencyManager::get()->renderSolidCube(*batch, 1.0f, cubeColor); } else { if (getIsDashedLine()) { diff --git a/libraries/render-utils/src/overlay3D.slf b/libraries/render-utils/src/overlay3D.slf index e38086ebb5..69ea8c0e76 100644 --- a/libraries/render-utils/src/overlay3D.slf +++ b/libraries/render-utils/src/overlay3D.slf @@ -25,6 +25,5 @@ void main(void) { if (diffuse.a < 0.5) { discard; } - - gl_FragColor = vec4(varColor.rgb * (1 - diffuse.a) + diffuse.a * diffuse.rgb, 1.0); + gl_FragColor = vec4(varColor * diffuse); } From 2356a071dd4298216d1b16e49b83e36054d44ac0 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Jun 2015 08:48:04 -0700 Subject: [PATCH 67/90] some cleanup --- interface/src/Environment.cpp | 71 ++++------------------------------- interface/src/Environment.h | 15 ++------ 2 files changed, 11 insertions(+), 75 deletions(-) diff --git a/interface/src/Environment.cpp b/interface/src/Environment.cpp index b80e4795d4..b333d648ef 100644 --- a/interface/src/Environment.cpp +++ b/interface/src/Environment.cpp @@ -33,11 +33,6 @@ #include "../../build/libraries/model/SkyFromSpace_frag.h" #include "../../build/libraries/model/SkyFromAtmosphere_vert.h" #include "../../build/libraries/model/SkyFromAtmosphere_frag.h" -#include "../../build/libraries/render-utils/simple_vert.h" -#include "../../build/libraries/render-utils/simple_frag.h" - -#include "../../build/libraries/render-utils/other_simple_vert.h" -#include "../../build/libraries/render-utils/other_simple_frag.h" uint qHash(const HifiSockAddr& sockAddr) { if (sockAddr.getAddress().isNull()) { @@ -53,10 +48,6 @@ Environment::Environment() } Environment::~Environment() { - if (_initialized) { - delete _skyFromAtmosphereProgram; - delete _skyFromSpaceProgram; - } } void Environment::init() { @@ -65,19 +56,8 @@ void Environment::init() { return; } - _skyFromAtmosphereProgram = createSkyProgram("Atmosphere", _skyFromAtmosphereUniformLocations); - _skyFromSpaceProgram = createSkyProgram("Space", _skyFromSpaceUniformLocations); - - - - qDebug() << "here:" << __LINE__; - setupAtmosphereProgram(SkyFromSpace_vert, SkyFromSpace_frag, _newSkyFromSpaceProgram, _newSkyFromSpaceUniformLocations); - //setupAtmosphereProgram(other_simple_vert, other_simple_frag, _newSkyFromSpaceProgram, _newSkyFromSpaceUniformLocations); - qDebug() << "here:" << __LINE__; - setupAtmosphereProgram(SkyFromAtmosphere_vert, SkyFromAtmosphere_frag, _newSkyFromAtmosphereProgram, _newSkyFromAtmosphereUniformLocations); - //setupAtmosphereProgram(other_simple_vert, other_simple_frag, _newSkyFromAtmosphereProgram, _newSkyFromAtmosphereUniformLocations); - qDebug() << "here:" << __LINE__; - + setupAtmosphereProgram(SkyFromSpace_vert, SkyFromSpace_frag, _skyFromSpaceProgram, _skyFromSpaceUniformLocations); + setupAtmosphereProgram(SkyFromAtmosphere_vert, SkyFromAtmosphere_frag, _skyFromAtmosphereProgram, _skyFromAtmosphereUniformLocations); // start off with a default-constructed environment data _data[HifiSockAddr()][0]; @@ -97,15 +77,9 @@ void Environment::setupAtmosphereProgram(const char* vertSource, const char* fra gpu::StatePointer state = gpu::StatePointer(new gpu::State()); - /* state->setCullMode(gpu::State::CULL_NONE); state->setDepthTest(false); - state->setBlendFunction(true,gpu::State::SRC_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::INV_SRC_ALPHA); - */ - - state->setCullMode(gpu::State::CULL_NONE); - state->setDepthTest(false); - state->setBlendFunction(false, + state->setBlendFunction(true, gpu::State::SRC_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::INV_SRC_ALPHA, gpu::State::FACTOR_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::ONE); @@ -267,41 +241,12 @@ int Environment::parseData(const HifiSockAddr& senderAddress, const QByteArray& return bytesRead; } -ProgramObject* Environment::createSkyProgram(const char* from, int* locations) { - ProgramObject* program = new ProgramObject(); - QByteArray prefix = QString(PathUtils::resourcesPath() + "/shaders/SkyFrom" + from).toUtf8(); - program->addShaderFromSourceFile(QGLShader::Vertex, prefix + ".vert"); - program->addShaderFromSourceFile(QGLShader::Fragment, prefix + ".frag"); - program->link(); - - locations[CAMERA_POS_LOCATION] = program->uniformLocation("v3CameraPos"); - locations[LIGHT_POS_LOCATION] = program->uniformLocation("v3LightPos"); - locations[INV_WAVELENGTH_LOCATION] = program->uniformLocation("v3InvWavelength"); - locations[CAMERA_HEIGHT2_LOCATION] = program->uniformLocation("fCameraHeight2"); - locations[OUTER_RADIUS_LOCATION] = program->uniformLocation("fOuterRadius"); - locations[OUTER_RADIUS2_LOCATION] = program->uniformLocation("fOuterRadius2"); - locations[INNER_RADIUS_LOCATION] = program->uniformLocation("fInnerRadius"); - locations[KR_ESUN_LOCATION] = program->uniformLocation("fKrESun"); - locations[KM_ESUN_LOCATION] = program->uniformLocation("fKmESun"); - locations[KR_4PI_LOCATION] = program->uniformLocation("fKr4PI"); - locations[KM_4PI_LOCATION] = program->uniformLocation("fKm4PI"); - locations[SCALE_LOCATION] = program->uniformLocation("fScale"); - locations[SCALE_DEPTH_LOCATION] = program->uniformLocation("fScaleDepth"); - locations[SCALE_OVER_SCALE_DEPTH_LOCATION] = program->uniformLocation("fScaleOverScaleDepth"); - locations[G_LOCATION] = program->uniformLocation("g"); - locations[G2_LOCATION] = program->uniformLocation("g2"); - - return program; -} - void Environment::renderAtmosphere(gpu::Batch& batch, ViewFrustum& camera, const EnvironmentData& data) { glm::vec3 center = data.getAtmosphereCenter(); Transform transform; transform.setTranslation(center); - //transform.setScale(2.0f); - //transform.setTranslation(glm::vec3(0,0,0)); batch.setModelTransform(transform); glm::vec3 relativeCameraPos = camera.getPosition() - center; @@ -310,18 +255,16 @@ void Environment::renderAtmosphere(gpu::Batch& batch, ViewFrustum& camera, const // use the appropriate shader depending on whether we're inside or outside int* locations; if (height < data.getAtmosphereOuterRadius()) { - batch.setPipeline(_newSkyFromAtmosphereProgram); - locations = _newSkyFromAtmosphereUniformLocations; + batch.setPipeline(_skyFromAtmosphereProgram); + locations = _skyFromAtmosphereUniformLocations; } else { - batch.setPipeline(_newSkyFromSpaceProgram); - locations = _newSkyFromSpaceUniformLocations; + batch.setPipeline(_skyFromSpaceProgram); + locations = _skyFromSpaceUniformLocations; } // the constants here are from Sean O'Neil's GPU Gems entry // (http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter16.html), GameEngine.cpp - - batch._glUniform3f(locations[CAMERA_POS_LOCATION], relativeCameraPos.x, relativeCameraPos.y, relativeCameraPos.z); glm::vec3 lightDirection = glm::normalize(data.getSunLocation()); batch._glUniform3f(locations[LIGHT_POS_LOCATION], lightDirection.x, lightDirection.y, lightDirection.z); diff --git a/interface/src/Environment.h b/interface/src/Environment.h index 9048678230..547f46c9fe 100644 --- a/interface/src/Environment.h +++ b/interface/src/Environment.h @@ -47,13 +47,9 @@ private: bool findCapsulePenetration(const glm::vec3& start, const glm::vec3& end, float radius, glm::vec3& penetration); // NOTE: Deprecated - ProgramObject* createSkyProgram(const char* from, int* locations); - void renderAtmosphere(gpu::Batch& batch, ViewFrustum& camera, const EnvironmentData& data); bool _initialized; - ProgramObject* _skyFromAtmosphereProgram; - ProgramObject* _skyFromSpaceProgram; enum { CAMERA_POS_LOCATION, @@ -75,16 +71,13 @@ private: LOCATION_COUNT }; - int _skyFromAtmosphereUniformLocations[LOCATION_COUNT]; - int _skyFromSpaceUniformLocations[LOCATION_COUNT]; - void setupAtmosphereProgram(const char* vertSource, const char* fragSource, gpu::PipelinePointer& pipelineProgram, int* locations); - gpu::PipelinePointer _newSkyFromAtmosphereProgram; - gpu::PipelinePointer _newSkyFromSpaceProgram; - int _newSkyFromAtmosphereUniformLocations[LOCATION_COUNT]; - int _newSkyFromSpaceUniformLocations[LOCATION_COUNT]; + gpu::PipelinePointer _skyFromAtmosphereProgram; + gpu::PipelinePointer _skyFromSpaceProgram; + int _skyFromAtmosphereUniformLocations[LOCATION_COUNT]; + int _skyFromSpaceUniformLocations[LOCATION_COUNT]; typedef QHash ServerData; From b5731135ddeb2c4feae495d00f4f4aff399f8f3c Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Jun 2015 09:08:41 -0700 Subject: [PATCH 68/90] cleanup --- interface/src/Application.cpp | 8 +++++--- interface/src/Environment.cpp | 10 +++------- interface/src/Environment.h | 2 +- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index efe7df4240..1ead8fe4f8 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3330,11 +3330,13 @@ namespace render { PerformanceTimer perfTimer("atmosphere"); PerformanceWarning warn(Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings), "Application::displaySide() ... atmosphere..."); - gpu::Batch batch; - //DependencyManager::get()->renderSolidSphere(batch,0.5f, 100, 50, glm::vec4(1.0f, 0.0f, 0.0f, 1.0f)); //Draw a unit sphere + background->_environment->renderAtmospheres(batch, *(args->_viewFrustum)); + + // FIX ME - If I don't call this renderBatch() here, then the atmosphere doesn't render, but it + // seems like these payloadRender() methods shouldn't be doing this. We need to investigate why + // the engine isn't rendering our batch gpu::GLBackend::renderBatch(batch, true); - glUseProgram(0); } diff --git a/interface/src/Environment.cpp b/interface/src/Environment.cpp index b333d648ef..09dd8f792e 100644 --- a/interface/src/Environment.cpp +++ b/interface/src/Environment.cpp @@ -15,18 +15,15 @@ #include #include -#include +#include #include +#include +#include #include #include #include #include -#include "Application.h" -#include "Camera.h" -#include "world.h" -#include "InterfaceLogging.h" - #include "Environment.h" #include "../../build/libraries/model/SkyFromSpace_vert.h" @@ -52,7 +49,6 @@ Environment::~Environment() { void Environment::init() { if (_initialized) { - qCDebug(interfaceapp, "[ERROR] Environment is already initialized."); return; } diff --git a/interface/src/Environment.h b/interface/src/Environment.h index 547f46c9fe..fe0c564493 100644 --- a/interface/src/Environment.h +++ b/interface/src/Environment.h @@ -18,7 +18,7 @@ #include #include -#include +//#include #include "EnvironmentData.h" From ea98581d22c20cbba734941fc69b0477afed39e8 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Jun 2015 09:18:00 -0700 Subject: [PATCH 69/90] reorganize files to cleanup headers --- libraries/model/CMakeLists.txt | 3 ++- .../render-utils}/src/Environment.cpp | 13 +++++-------- .../render-utils}/src/Environment.h | 0 .../src}/SkyFromAtmosphere.slf | 0 .../src}/SkyFromAtmosphere.slv | 0 .../src/model => render-utils/src}/SkyFromSpace.slf | 0 .../src/model => render-utils/src}/SkyFromSpace.slv | 0 7 files changed, 7 insertions(+), 9 deletions(-) rename {interface => libraries/render-utils}/src/Environment.cpp (97%) rename {interface => libraries/render-utils}/src/Environment.h (100%) rename libraries/{model/src/model => render-utils/src}/SkyFromAtmosphere.slf (100%) rename libraries/{model/src/model => render-utils/src}/SkyFromAtmosphere.slv (100%) rename libraries/{model/src/model => render-utils/src}/SkyFromSpace.slf (100%) rename libraries/{model/src/model => render-utils/src}/SkyFromSpace.slv (100%) diff --git a/libraries/model/CMakeLists.txt b/libraries/model/CMakeLists.txt index 278c40c435..7456716946 100755 --- a/libraries/model/CMakeLists.txt +++ b/libraries/model/CMakeLists.txt @@ -1,5 +1,6 @@ set(TARGET_NAME model) - + + AUTOSCRIBE_SHADER_LIB(gpu) # use setup_hifi_library macro to setup our project and link appropriate Qt modules diff --git a/interface/src/Environment.cpp b/libraries/render-utils/src/Environment.cpp similarity index 97% rename from interface/src/Environment.cpp rename to libraries/render-utils/src/Environment.cpp index 09dd8f792e..411beca0ae 100644 --- a/interface/src/Environment.cpp +++ b/libraries/render-utils/src/Environment.cpp @@ -9,27 +9,24 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#include "InterfaceConfig.h" - #include #include #include -#include +#include "GeometryCache.h" #include #include #include #include #include -#include #include #include "Environment.h" -#include "../../build/libraries/model/SkyFromSpace_vert.h" -#include "../../build/libraries/model/SkyFromSpace_frag.h" -#include "../../build/libraries/model/SkyFromAtmosphere_vert.h" -#include "../../build/libraries/model/SkyFromAtmosphere_frag.h" +#include "SkyFromSpace_vert.h" +#include "SkyFromSpace_frag.h" +#include "SkyFromAtmosphere_vert.h" +#include "SkyFromAtmosphere_frag.h" uint qHash(const HifiSockAddr& sockAddr) { if (sockAddr.getAddress().isNull()) { diff --git a/interface/src/Environment.h b/libraries/render-utils/src/Environment.h similarity index 100% rename from interface/src/Environment.h rename to libraries/render-utils/src/Environment.h diff --git a/libraries/model/src/model/SkyFromAtmosphere.slf b/libraries/render-utils/src/SkyFromAtmosphere.slf similarity index 100% rename from libraries/model/src/model/SkyFromAtmosphere.slf rename to libraries/render-utils/src/SkyFromAtmosphere.slf diff --git a/libraries/model/src/model/SkyFromAtmosphere.slv b/libraries/render-utils/src/SkyFromAtmosphere.slv similarity index 100% rename from libraries/model/src/model/SkyFromAtmosphere.slv rename to libraries/render-utils/src/SkyFromAtmosphere.slv diff --git a/libraries/model/src/model/SkyFromSpace.slf b/libraries/render-utils/src/SkyFromSpace.slf similarity index 100% rename from libraries/model/src/model/SkyFromSpace.slf rename to libraries/render-utils/src/SkyFromSpace.slf diff --git a/libraries/model/src/model/SkyFromSpace.slv b/libraries/render-utils/src/SkyFromSpace.slv similarity index 100% rename from libraries/model/src/model/SkyFromSpace.slv rename to libraries/render-utils/src/SkyFromSpace.slv From 0e18c75b0bacd7f6f67e8200690de81cc24e507d Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Jun 2015 09:23:12 -0700 Subject: [PATCH 70/90] cleanup --- libraries/render-utils/src/SkyFromAtmosphere.slf | 4 ++-- libraries/render-utils/src/SkyFromAtmosphere.slv | 8 +++----- libraries/render-utils/src/SkyFromSpace.slf | 4 ++-- libraries/render-utils/src/SkyFromSpace.slv | 8 ++++---- 4 files changed, 11 insertions(+), 13 deletions(-) diff --git a/libraries/render-utils/src/SkyFromAtmosphere.slf b/libraries/render-utils/src/SkyFromAtmosphere.slf index a9e2bc6156..53d0573737 100755 --- a/libraries/render-utils/src/SkyFromAtmosphere.slf +++ b/libraries/render-utils/src/SkyFromAtmosphere.slf @@ -51,7 +51,7 @@ uniform vec3 v3LightPos; uniform float g; uniform float g2; -varying vec3 myPosition; +varying vec3 position; float scale(float fCos) @@ -64,7 +64,7 @@ float scale(float fCos) void main (void) { // Get the ray from the camera to the vertex, and its length (which is the far point of the ray passing through the atmosphere) - vec3 v3Pos = myPosition; + vec3 v3Pos = position; vec3 v3Ray = v3Pos - v3CameraPos; float fFar = length(v3Ray); v3Ray /= fFar; diff --git a/libraries/render-utils/src/SkyFromAtmosphere.slv b/libraries/render-utils/src/SkyFromAtmosphere.slv index 99c782adf1..29c907b94c 100755 --- a/libraries/render-utils/src/SkyFromAtmosphere.slv +++ b/libraries/render-utils/src/SkyFromAtmosphere.slv @@ -53,18 +53,16 @@ uniform float fScaleOverScaleDepth; // fScale / fScaleDepth const int nSamples = 2; const float fSamples = 2.0; -varying vec3 myPosition; +varying vec3 position; void main(void) { // Get the ray from the camera to the vertex, and its length (which is the far point of the ray passing through the atmosphere) - myPosition = gl_Vertex.xyz * fOuterRadius; + position = gl_Vertex.xyz * fOuterRadius; - //gl_Position = gl_ModelViewProjectionMatrix * vec4(position, 1.0); - // standard transform TransformCamera cam = getTransformCamera(); TransformObject obj = getTransformObject(); - vec4 v4pos = vec4(myPosition, 1.0); + vec4 v4pos = vec4(position, 1.0); <$transformModelToClipPos(cam, obj, v4pos, gl_Position)$> } diff --git a/libraries/render-utils/src/SkyFromSpace.slf b/libraries/render-utils/src/SkyFromSpace.slf index 4e13438ccb..5f6ce80efa 100755 --- a/libraries/render-utils/src/SkyFromSpace.slf +++ b/libraries/render-utils/src/SkyFromSpace.slf @@ -53,7 +53,7 @@ uniform float g2; const int nSamples = 2; const float fSamples = 2.0; -varying vec3 myPosition; +varying vec3 position; float scale(float fCos) { @@ -65,7 +65,7 @@ float scale(float fCos) void main (void) { // Get the ray from the camera to the vertex and its length (which is the far point of the ray passing through the atmosphere) - vec3 v3Pos = myPosition; + vec3 v3Pos = position; vec3 v3Ray = v3Pos - v3CameraPos; float fFar = length(v3Ray); v3Ray /= fFar; diff --git a/libraries/render-utils/src/SkyFromSpace.slv b/libraries/render-utils/src/SkyFromSpace.slv index 9090d76da2..6427af6715 100755 --- a/libraries/render-utils/src/SkyFromSpace.slv +++ b/libraries/render-utils/src/SkyFromSpace.slv @@ -38,15 +38,15 @@ uniform float fOuterRadius; // The outer (atmosphere) radius -varying vec3 myPosition; +varying vec3 position; void main(void) { - myPosition = gl_Vertex.xyz * fOuterRadius; + position = gl_Vertex.xyz * fOuterRadius; // standard transform TransformCamera cam = getTransformCamera(); TransformObject obj = getTransformObject(); - vec4 v4pos = vec4(myPosition, 1.0); + vec4 v4pos = vec4(position, 1.0); <$transformModelToClipPos(cam, obj, v4pos, gl_Position)$> -} \ No newline at end of file +} From 268bb370ccafc9d395cb40e600005410e8bb092c Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Jun 2015 09:24:42 -0700 Subject: [PATCH 71/90] cleanup --- libraries/model/CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/libraries/model/CMakeLists.txt b/libraries/model/CMakeLists.txt index 7456716946..1520378f1a 100755 --- a/libraries/model/CMakeLists.txt +++ b/libraries/model/CMakeLists.txt @@ -1,6 +1,5 @@ set(TARGET_NAME model) - AUTOSCRIBE_SHADER_LIB(gpu) # use setup_hifi_library macro to setup our project and link appropriate Qt modules From 8162c37013131d4b4011057dcc01e4e5a9bcf6c3 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Jun 2015 09:33:15 -0700 Subject: [PATCH 72/90] cleanup --- libraries/model/CMakeLists.txt | 2 +- libraries/render-utils/src/Environment.h | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/libraries/model/CMakeLists.txt b/libraries/model/CMakeLists.txt index 1520378f1a..278c40c435 100755 --- a/libraries/model/CMakeLists.txt +++ b/libraries/model/CMakeLists.txt @@ -1,5 +1,5 @@ set(TARGET_NAME model) - + AUTOSCRIBE_SHADER_LIB(gpu) # use setup_hifi_library macro to setup our project and link appropriate Qt modules diff --git a/libraries/render-utils/src/Environment.h b/libraries/render-utils/src/Environment.h index fe0c564493..65e0df4b36 100644 --- a/libraries/render-utils/src/Environment.h +++ b/libraries/render-utils/src/Environment.h @@ -18,9 +18,7 @@ #include #include -//#include - -#include "EnvironmentData.h" +#include class ViewFrustum; class ProgramObject; From 467609f2b69e0b6c9382071a99523f978735b5b2 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Jun 2015 09:44:26 -0700 Subject: [PATCH 73/90] standardize skybox and atmosphere batch --- interface/src/Application.cpp | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 1ead8fe4f8..8d5f8810fd 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3332,12 +3332,6 @@ namespace render { "Application::displaySide() ... atmosphere..."); background->_environment->renderAtmospheres(batch, *(args->_viewFrustum)); - - // FIX ME - If I don't call this renderBatch() here, then the atmosphere doesn't render, but it - // seems like these payloadRender() methods shouldn't be doing this. We need to investigate why - // the engine isn't rendering our batch - gpu::GLBackend::renderBatch(batch, true); - } } @@ -3346,12 +3340,13 @@ namespace render { skybox = skyStage->getSkybox(); if (skybox) { - gpu::Batch batch; model::Skybox::render(batch, *(Application::getInstance()->getDisplayViewFrustum()), *skybox); - gpu::GLBackend::renderBatch(batch, true); - glUseProgram(0); } } + // FIX ME - If I don't call this renderBatch() here, then the atmosphere and skybox don't render, but it + // seems like these payloadRender() methods shouldn't be doing this. We need to investigate why the engine + // isn't rendering our batch + gpu::GLBackend::renderBatch(batch, true); } } From 689e10cc27185c0d17973e28fdbe01eba06e3f75 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Jun 2015 09:53:50 -0700 Subject: [PATCH 74/90] build buster fix --- libraries/model/src/model/Stage.cpp | 15 --------------- libraries/model/src/model/Stage.h | 2 -- 2 files changed, 17 deletions(-) diff --git a/libraries/model/src/model/Stage.cpp b/libraries/model/src/model/Stage.cpp index a255a1f7c9..a3a8b9f3fd 100644 --- a/libraries/model/src/model/Stage.cpp +++ b/libraries/model/src/model/Stage.cpp @@ -14,9 +14,6 @@ #include #include -#include "SkyFromAtmosphere_vert.h" -#include "SkyFromAtmosphere_frag.h" - using namespace model; @@ -207,17 +204,6 @@ SunSkyStage::SunSkyStage() : // Begining of march setYearTime(60.0f); - auto skyFromAtmosphereVertex = gpu::ShaderPointer(gpu::Shader::createVertex(std::string(SkyFromAtmosphere_vert))); - auto skyFromAtmosphereFragment = gpu::ShaderPointer(gpu::Shader::createPixel(std::string(SkyFromAtmosphere_frag))); - auto skyShader = gpu::ShaderPointer(gpu::Shader::createProgram(skyFromAtmosphereVertex, skyFromAtmosphereFragment)); - - auto skyState = gpu::StatePointer(new gpu::State()); - // skyState->setStencilEnable(false); - // skyState->setBlendEnable(false); - - _skyPipeline = gpu::PipelinePointer(gpu::Pipeline::create(skyShader, skyState)); - - _skybox.reset(new Skybox()); _skybox->setColor(Color(1.0f, 0.0f, 0.0f)); @@ -310,7 +296,6 @@ void SunSkyStage::updateGraphicsObject() const { static int firstTime = 0; if (firstTime == 0) { firstTime++; - gpu::Shader::makeProgram(*(_skyPipeline->getProgram())); } } diff --git a/libraries/model/src/model/Stage.h b/libraries/model/src/model/Stage.h index fc90b0c903..b4df45e024 100644 --- a/libraries/model/src/model/Stage.h +++ b/libraries/model/src/model/Stage.h @@ -229,8 +229,6 @@ protected: AtmospherePointer _atmosphere; mutable SkyboxPointer _skybox; - gpu::PipelinePointer _skyPipeline; - float _dayTime = 12.0f; int _yearTime = 0; mutable EarthSunModel _earthSunModel; From e9bf553254c2edf9e80caf691c94a5e79db554a0 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Jun 2015 09:59:38 -0700 Subject: [PATCH 75/90] CR feedback --- libraries/render-utils/src/SkyFromAtmosphere.slf | 5 ++--- libraries/render-utils/src/SkyFromSpace.slf | 7 ++++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/libraries/render-utils/src/SkyFromAtmosphere.slf b/libraries/render-utils/src/SkyFromAtmosphere.slf index 53d0573737..1e1718677c 100755 --- a/libraries/render-utils/src/SkyFromAtmosphere.slf +++ b/libraries/render-utils/src/SkyFromAtmosphere.slf @@ -106,7 +106,6 @@ void main (void) float fMiePhase = 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + fCos*fCos) / pow(1.0 + g2 - 2.0*g*fCos, 1.5); vec3 finalColor = frontColor.rgb + fMiePhase * secondaryFrontColor.rgb; - gl_FragData[0].rgb = finalColor; - gl_FragData[0].a = finalColor.b; - gl_FragData[0].rgb = pow(finalColor.rgb, vec3(1.0/2.2)); + gl_FragColor.a = finalColor.b; + gl_FragColor.rgb = pow(finalColor.rgb, vec3(1.0/2.2)); } diff --git a/libraries/render-utils/src/SkyFromSpace.slf b/libraries/render-utils/src/SkyFromSpace.slf index 5f6ce80efa..2373511932 100755 --- a/libraries/render-utils/src/SkyFromSpace.slf +++ b/libraries/render-utils/src/SkyFromSpace.slf @@ -108,7 +108,8 @@ void main (void) float fMiePhase = 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + fCos*fCos) / pow(1.0 + g2 - 2.0*g*fCos, 1.5); vec3 color = v3FrontColor * (v3InvWavelength * fKrESun); vec3 secondaryColor = v3FrontColor * fKmESun; - gl_FragColor.rgb = color + fMiePhase * secondaryColor; - gl_FragColor.a = gl_FragColor.b; - gl_FragColor.rgb = pow(gl_FragColor.rgb, vec3(1.0/2.2)); + + vec3 finalColor = color + fMiePhase * secondaryColor; + gl_FragColor.a = finalColor.b; + gl_FragColor.rgb = pow(finalColor.rgb, vec3(1.0/2.2)); } From fb59939cf4b2781e045b07837fda4a1f06c1db30 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Jun 2015 10:02:02 -0700 Subject: [PATCH 76/90] CR feedback --- libraries/model/src/model/Stage.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/libraries/model/src/model/Stage.cpp b/libraries/model/src/model/Stage.cpp index a3a8b9f3fd..220ee31c65 100644 --- a/libraries/model/src/model/Stage.cpp +++ b/libraries/model/src/model/Stage.cpp @@ -292,11 +292,6 @@ void SunSkyStage::updateGraphicsObject() const { case NUM_BACKGROUND_MODES: Q_UNREACHABLE(); }; - - static int firstTime = 0; - if (firstTime == 0) { - firstTime++; - } } void SunSkyStage::setBackgroundMode(BackgroundMode mode) { From dc4ae082f87e70db6005b3a47d321e1fde86bdb7 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 17 Jun 2015 10:13:49 -0700 Subject: [PATCH 77/90] make goToUser public again --- libraries/networking/src/AddressManager.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libraries/networking/src/AddressManager.h b/libraries/networking/src/AddressManager.h index a0fc7eb0be..b4c34176a4 100644 --- a/libraries/networking/src/AddressManager.h +++ b/libraries/networking/src/AddressManager.h @@ -72,6 +72,8 @@ public slots: void goBack(); void goForward(); + void goToUser(const QString& username); + void storeCurrentAddress(); void copyAddress(); @@ -100,7 +102,6 @@ private slots: void handleAPIResponse(QNetworkReply& requestReply); void handleAPIError(QNetworkReply& errorReply); - void goToUser(const QString& username); void goToAddressFromObject(const QVariantMap& addressMap, const QNetworkReply& reply); private: void setHost(const QString& host, LookupTrigger trigger); From bc20ea6ed284dacc5a324246e56824c94b02b491 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 17 Jun 2015 11:18:43 -0700 Subject: [PATCH 78/90] fix for path handling on return of place info --- libraries/networking/src/AddressManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/networking/src/AddressManager.cpp b/libraries/networking/src/AddressManager.cpp index 6941d7335d..a8ed54fdd1 100644 --- a/libraries/networking/src/AddressManager.cpp +++ b/libraries/networking/src/AddressManager.cpp @@ -305,7 +305,7 @@ void AddressManager::goToAddressFromObject(const QVariantMap& dataObject, const << returnedPath; } } else { - handlePath(overridePath, trigger); + handlePath(returnedPath, trigger); } } else { // we didn't override the path or get one back - ask the DS for the viewpoint of its index path From 45a5f1364a21abb89771654baf97b498bafe2b89 Mon Sep 17 00:00:00 2001 From: Sam Gondelman Date: Wed, 17 Jun 2015 11:56:44 -0700 Subject: [PATCH 79/90] fix compile issue if you don't have sdl2 --- interface/src/devices/SDL2Manager.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/interface/src/devices/SDL2Manager.cpp b/interface/src/devices/SDL2Manager.cpp index 32408fce18..e039a80b0d 100644 --- a/interface/src/devices/SDL2Manager.cpp +++ b/interface/src/devices/SDL2Manager.cpp @@ -74,9 +74,11 @@ SDL2Manager* SDL2Manager::getInstance() { } void SDL2Manager::focusOutEvent() { +#ifdef HAVE_SDL2 for (auto joystick : _openJoysticks) { joystick->focusOutEvent(); } +#endif } void SDL2Manager::update() { From b4dfaba55ec57bf18830723e0691fc2a73ffed1d Mon Sep 17 00:00:00 2001 From: Howard Stearns Date: Wed, 17 Jun 2015 11:59:15 -0700 Subject: [PATCH 80/90] Incorporate ctrlaltdavid's changes. --- libraries/audio-client/src/AudioClient.cpp | 11 ++++++++++- libraries/audio-client/src/AudioClient.h | 5 +++++ libraries/audio/src/AudioInjector.cpp | 5 +---- libraries/audio/src/AudioInjectorLocalBuffer.cpp | 13 ++----------- libraries/audio/src/AudioInjectorLocalBuffer.h | 4 ---- 5 files changed, 18 insertions(+), 20 deletions(-) diff --git a/libraries/audio-client/src/AudioClient.cpp b/libraries/audio-client/src/AudioClient.cpp index 6450f25208..84022d0fb9 100644 --- a/libraries/audio-client/src/AudioClient.cpp +++ b/libraries/audio-client/src/AudioClient.cpp @@ -1011,7 +1011,10 @@ bool AudioClient::outputLocalInjector(bool isStereo, AudioInjector* injector) { localOutput->moveToThread(injector->getLocalBuffer()->thread()); // have it be stopped when that local buffer is about to close - connect(injector->getLocalBuffer(), &AudioInjectorLocalBuffer::bufferEmpty, localOutput, &QAudioOutput::stop); + connect(localOutput, &QAudioOutput::stateChanged, this, &AudioClient::audioStateChanged); + connect(this, &AudioClient::audioFinished, localOutput, &QAudioOutput::stop); + connect(this, &AudioClient::audioFinished, injector, &AudioInjector::stop); + connect(injector->getLocalBuffer(), &QIODevice::aboutToClose, localOutput, &QAudioOutput::stop); qCDebug(audioclient) << "Starting QAudioOutput for local injector" << localOutput; @@ -1329,3 +1332,9 @@ void AudioClient::saveSettings() { windowSecondsForDesiredReduction.set(_receivedAudioStream.getWindowSecondsForDesiredReduction()); repetitionWithFade.set(_receivedAudioStream.getRepetitionWithFade()); } + +void AudioClient::audioStateChanged(QAudio::State state) { + if (state == QAudio::IdleState) { + emit audioFinished(); + } +} diff --git a/libraries/audio-client/src/AudioClient.h b/libraries/audio-client/src/AudioClient.h index 642edde84a..d2492e1064 100644 --- a/libraries/audio-client/src/AudioClient.h +++ b/libraries/audio-client/src/AudioClient.h @@ -188,6 +188,8 @@ signals: void receivedFirstPacket(); void disconnected(); + void audioFinished(); + protected: AudioClient(); ~AudioClient(); @@ -196,6 +198,9 @@ protected: deleteLater(); } +private slots: + void audioStateChanged(QAudio::State state); + private: void outputFormatChanged(); diff --git a/libraries/audio/src/AudioInjector.cpp b/libraries/audio/src/AudioInjector.cpp index 333a944e1b..675a3b8b28 100644 --- a/libraries/audio/src/AudioInjector.cpp +++ b/libraries/audio/src/AudioInjector.cpp @@ -51,7 +51,7 @@ void AudioInjector::setIsFinished(bool isFinished) { emit finished(); if (_localBuffer) { - // delete will stop (and nosily if we do so ourselves here first). + _localBuffer->stop(); _localBuffer->deleteLater(); _localBuffer = NULL; } @@ -121,9 +121,6 @@ void AudioInjector::injectLocally() { success = _localAudioInterface->outputLocalInjector(_options.stereo, this); - // if we're not looping and the buffer tells us it is empty then emit finished - connect(_localBuffer, &AudioInjectorLocalBuffer::bufferEmpty, this, &AudioInjector::stop); - if (!success) { qCDebug(audio) << "AudioInjector::injectLocally could not output locally via _localAudioInterface"; } diff --git a/libraries/audio/src/AudioInjectorLocalBuffer.cpp b/libraries/audio/src/AudioInjectorLocalBuffer.cpp index 457abeb89e..27e93a678e 100644 --- a/libraries/audio/src/AudioInjectorLocalBuffer.cpp +++ b/libraries/audio/src/AudioInjectorLocalBuffer.cpp @@ -17,8 +17,7 @@ AudioInjectorLocalBuffer::AudioInjectorLocalBuffer(const QByteArray& rawAudioArr _shouldLoop(false), _isStopped(false), _currentOffset(0), - _volume(1.0f), - _isFinished(false) + _volume(1.0f) { } @@ -52,11 +51,6 @@ void copy(char* to, char* from, int size, qreal factor) { qint64 AudioInjectorLocalBuffer::readData(char* data, qint64 maxSize) { if (!_isStopped) { - if (_isFinished) { - emit bufferEmpty(); - return -1; // qt docs say -1 is appropriate when subsequent calls will not write data - } - // first copy to the end of the raw audio int bytesToEnd = _rawAudioArray.size() - _currentOffset; @@ -75,10 +69,7 @@ qint64 AudioInjectorLocalBuffer::readData(char* data, qint64 maxSize) { _currentOffset += bytesRead; } - if (!_shouldLoop && bytesRead == bytesToEnd) { - // If we emit bufferEmpty now, we'll clip the end of the sound. Wait until the next call. - _isFinished = true; - } else if (_shouldLoop && _currentOffset == _rawAudioArray.size()) { + if (_shouldLoop && _currentOffset == _rawAudioArray.size()) { _currentOffset = 0; } diff --git a/libraries/audio/src/AudioInjectorLocalBuffer.h b/libraries/audio/src/AudioInjectorLocalBuffer.h index 270e730590..32a1221b78 100644 --- a/libraries/audio/src/AudioInjectorLocalBuffer.h +++ b/libraries/audio/src/AudioInjectorLocalBuffer.h @@ -32,9 +32,6 @@ public: void setCurrentOffset(int currentOffset) { _currentOffset = currentOffset; } void setVolume(float volume) { _volume = glm::clamp(volume, 0.0f, 1.0f); } -signals: - void bufferEmpty(); - private: qint64 recursiveReadFromFront(char* data, qint64 maxSize); @@ -44,7 +41,6 @@ private: int _currentOffset; float _volume; - bool _isFinished; }; #endif // hifi_AudioInjectorLocalBuffer_h \ No newline at end of file From 1328ea619971967dee5362b43fd45251e7aca35a Mon Sep 17 00:00:00 2001 From: Niraj Venkat Date: Wed, 17 Jun 2015 13:41:41 -0700 Subject: [PATCH 81/90] Calling AddressManager back and forward functions --- interface/resources/qml/AddressBarDialog.qml | 19 +++++++++++++++++-- interface/src/ui/AddressBarDialog.cpp | 12 +++++++++++- interface/src/ui/AddressBarDialog.h | 2 ++ 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/interface/resources/qml/AddressBarDialog.qml b/interface/resources/qml/AddressBarDialog.qml index e80c5f2aa5..b8543c132d 100644 --- a/interface/resources/qml/AddressBarDialog.qml +++ b/interface/resources/qml/AddressBarDialog.qml @@ -58,6 +58,15 @@ DialogContainer { topMargin: parent.inputAreaStep + parent.inputAreaStep + hifi.layout.spacing bottomMargin: parent.inputAreaStep + parent.inputAreaStep + hifi.layout.spacing } + + MouseArea { + anchors.fill: parent + acceptedButtons: Qt.LeftButton + onClicked: { + event.accepted = true + addressBarDialog.loadBack() + } + } } Image { @@ -73,8 +82,14 @@ DialogContainer { bottomMargin: parent.inputAreaStep + parent.inputAreaStep + hifi.layout.spacing } - width: parent.width * 0.5 - height: parent.height * 0.5 + MouseArea { + anchors.fill: parent + acceptedButtons: Qt.LeftButton + onClicked: { + event.accepted = true + addressBarDialog.loadForward() + } + } } TextInput { diff --git a/interface/src/ui/AddressBarDialog.cpp b/interface/src/ui/AddressBarDialog.cpp index 3c3a843586..50fbf979a0 100644 --- a/interface/src/ui/AddressBarDialog.cpp +++ b/interface/src/ui/AddressBarDialog.cpp @@ -31,10 +31,20 @@ void AddressBarDialog::hide() { void AddressBarDialog::loadAddress(const QString& address) { qDebug() << "Called LoadAddress with address " << address; if (!address.isEmpty()) { - DependencyManager::get()->handleLookupString(address); + DependencyManager::get()->handleLookupString(address);; } } +void AddressBarDialog::loadBack() { + qDebug() << "Called LoadBack"; + DependencyManager::get()->goBack(); +} + +void AddressBarDialog::loadForward() { + qDebug() << "Called LoadForward"; + DependencyManager::get()->goForward(); +} + void AddressBarDialog::displayAddressOfflineMessage() { OffscreenUi::error("That user or place is currently offline"); } diff --git a/interface/src/ui/AddressBarDialog.h b/interface/src/ui/AddressBarDialog.h index 395cf3c725..da54e29929 100644 --- a/interface/src/ui/AddressBarDialog.h +++ b/interface/src/ui/AddressBarDialog.h @@ -28,6 +28,8 @@ protected: void hide(); Q_INVOKABLE void loadAddress(const QString& address); + Q_INVOKABLE void loadBack(); + Q_INVOKABLE void loadForward(); }; #endif From 58ee5217e3c1c515118e9ce1e65a2ed50505ad4b Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Jun 2015 14:08:02 -0700 Subject: [PATCH 82/90] fix some warnings --- interface/src/devices/OculusManager.cpp | 1 + libraries/entities/src/DeleteEntityOperator.cpp | 1 + libraries/render-utils/src/TextRenderer3D.cpp | 1 - libraries/render-utils/src/TextRenderer3D.h | 2 -- libraries/shared/src/MatrixStack.h | 2 ++ libraries/shared/src/PhysicsCollisionGroups.h | 2 +- libraries/ui/src/VrMenu.cpp | 4 ++-- tools/vhacd-util/src/VHACDUtilApp.cpp | 1 + 8 files changed, 8 insertions(+), 6 deletions(-) diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index a7383ae4bb..96926406d9 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -164,6 +164,7 @@ void OculusManager::connect() { int configResult = ovrHmd_ConfigureRendering(_ovrHmd, &cfg.Config, distortionCaps, _eyeFov, _eyeRenderDesc); assert(configResult); + (void)configResult; // quiet warning _recommendedTexSize = ovrHmd_GetFovTextureSize(_ovrHmd, ovrEye_Left, _eyeFov[ovrEye_Left], 1.0f); diff --git a/libraries/entities/src/DeleteEntityOperator.cpp b/libraries/entities/src/DeleteEntityOperator.cpp index 051accc732..bb96b9698d 100644 --- a/libraries/entities/src/DeleteEntityOperator.cpp +++ b/libraries/entities/src/DeleteEntityOperator.cpp @@ -95,6 +95,7 @@ bool DeleteEntityOperator::preRecursion(OctreeElement* element) { EntityItemPointer theEntity = details.entity; bool entityDeleted = entityTreeElement->removeEntityItem(theEntity); // remove it from the element assert(entityDeleted); + (void)entityDeleted; // quite warning _tree->setContainingElement(details.entity->getEntityItemID(), NULL); // update or id to element lookup _foundCount++; } diff --git a/libraries/render-utils/src/TextRenderer3D.cpp b/libraries/render-utils/src/TextRenderer3D.cpp index 0eb560bf72..2f898542b9 100644 --- a/libraries/render-utils/src/TextRenderer3D.cpp +++ b/libraries/render-utils/src/TextRenderer3D.cpp @@ -451,7 +451,6 @@ TextRenderer3D::TextRenderer3D(const char* family, float pointSize, int weight, EffectType effect, int effectThickness, const QColor& color) : _effectType(effect), _effectThickness(effectThickness), - _pointSize(pointSize), _color(toGlm(color)), _font(loadFont3D(family)) { if (!_font) { diff --git a/libraries/render-utils/src/TextRenderer3D.h b/libraries/render-utils/src/TextRenderer3D.h index e61203b06f..9f6a16d743 100644 --- a/libraries/render-utils/src/TextRenderer3D.h +++ b/libraries/render-utils/src/TextRenderer3D.h @@ -65,8 +65,6 @@ private: // the thickness of the effect const int _effectThickness; - const float _pointSize; - // text color const glm::vec4 _color; diff --git a/libraries/shared/src/MatrixStack.h b/libraries/shared/src/MatrixStack.h index a02e284725..5a0b56ff9b 100644 --- a/libraries/shared/src/MatrixStack.h +++ b/libraries/shared/src/MatrixStack.h @@ -118,7 +118,9 @@ public: template void withPush(Function f) { + #ifdef DEBUG size_t startingDepth = size(); + #endif push(); f(); pop(); diff --git a/libraries/shared/src/PhysicsCollisionGroups.h b/libraries/shared/src/PhysicsCollisionGroups.h index cce9637cd4..08d83a29ca 100644 --- a/libraries/shared/src/PhysicsCollisionGroups.h +++ b/libraries/shared/src/PhysicsCollisionGroups.h @@ -55,7 +55,7 @@ const int16_t COLLISION_GROUP_COLLISIONLESS = 1 << 15; const int16_t COLLISION_MASK_DEFAULT = ~ COLLISION_GROUP_COLLISIONLESS; // STATIC also doesn't collide with other STATIC -const int16_t COLLISION_MASK_STATIC = ~ (COLLISION_GROUP_COLLISIONLESS | COLLISION_MASK_STATIC); +const int16_t COLLISION_MASK_STATIC = ~ (COLLISION_GROUP_COLLISIONLESS | COLLISION_GROUP_STATIC); const int16_t COLLISION_MASK_KINEMATIC = COLLISION_MASK_DEFAULT; diff --git a/libraries/ui/src/VrMenu.cpp b/libraries/ui/src/VrMenu.cpp index b6cb0b136b..1b402ff2a3 100644 --- a/libraries/ui/src/VrMenu.cpp +++ b/libraries/ui/src/VrMenu.cpp @@ -135,8 +135,8 @@ void VrMenu::setRootMenu(QObject* rootMenu) { void VrMenu::addMenu(QMenu* menu) { Q_ASSERT(!MenuUserData::forObject(menu)); - QObject * parent = menu->parent(); - QObject * qmlParent; + QObject* parent = menu->parent(); + QObject* qmlParent = nullptr; if (dynamic_cast(parent)) { MenuUserData* userData = MenuUserData::forObject(parent); qmlParent = findMenuObject(userData->uuid.toString()); diff --git a/tools/vhacd-util/src/VHACDUtilApp.cpp b/tools/vhacd-util/src/VHACDUtilApp.cpp index ed4dab020f..2af6bca337 100644 --- a/tools/vhacd-util/src/VHACDUtilApp.cpp +++ b/tools/vhacd-util/src/VHACDUtilApp.cpp @@ -322,6 +322,7 @@ VHACDUtilApp::VHACDUtilApp(int argc, char* argv[]) : QString outputFileName = baseFileName + "-" + QString::number(count) + ".obj"; writeOBJ(outputFileName, fbx, outputCentimeters, count); count++; + (void)meshPart; // quiet warning } } } From f2ba91383c294b36344040901460f9addb0180df Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Jun 2015 14:26:36 -0700 Subject: [PATCH 83/90] fix some warnings --- libraries/physics/src/MeshMassProperties.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libraries/physics/src/MeshMassProperties.cpp b/libraries/physics/src/MeshMassProperties.cpp index ee2945422d..4e471f7870 100644 --- a/libraries/physics/src/MeshMassProperties.cpp +++ b/libraries/physics/src/MeshMassProperties.cpp @@ -270,7 +270,9 @@ void MeshMassProperties::computeMassProperties(const VectorOfPoints& points, con } // create some variables to hold temporary results + #ifdef DEBUG uint32_t numPoints = points.size(); + #endif const btVector3 p0(0.0f, 0.0f, 0.0f); btMatrix3x3 tetraInertia; btMatrix3x3 doubleDebugInertia; From 225e2ebfdc8003be22124f221f26bdce927c6738 Mon Sep 17 00:00:00 2001 From: Niraj Venkat Date: Wed, 17 Jun 2015 14:27:16 -0700 Subject: [PATCH 84/90] Fixing build issues and finishing up address bar --- interface/resources/qml/AddressBarDialog.qml | 11 +++++------ interface/src/ui/AddressBarDialog.cpp | 2 +- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/interface/resources/qml/AddressBarDialog.qml b/interface/resources/qml/AddressBarDialog.qml index b8543c132d..70cb22dc4d 100644 --- a/interface/resources/qml/AddressBarDialog.qml +++ b/interface/resources/qml/AddressBarDialog.qml @@ -62,8 +62,7 @@ DialogContainer { MouseArea { anchors.fill: parent acceptedButtons: Qt.LeftButton - onClicked: { - event.accepted = true + onClicked: { addressBarDialog.loadBack() } } @@ -85,8 +84,7 @@ DialogContainer { MouseArea { anchors.fill: parent acceptedButtons: Qt.LeftButton - onClicked: { - event.accepted = true + onClicked: { addressBarDialog.loadForward() } } @@ -113,7 +111,7 @@ DialogContainer { addressBarDialog.loadAddress(addressLine.text) } } - + MouseArea { // Drag the icon width: parent.height @@ -129,6 +127,7 @@ DialogContainer { } } + /* MouseArea { // Drag the input rectangle width: parent.width - parent.height @@ -142,7 +141,7 @@ DialogContainer { maximumX: root.parent ? root.maximumX : 0 maximumY: root.parent ? root.maximumY + parent.inputAreaStep : 0 } - } + }*/ } } diff --git a/interface/src/ui/AddressBarDialog.cpp b/interface/src/ui/AddressBarDialog.cpp index 50fbf979a0..80f51ff906 100644 --- a/interface/src/ui/AddressBarDialog.cpp +++ b/interface/src/ui/AddressBarDialog.cpp @@ -31,7 +31,7 @@ void AddressBarDialog::hide() { void AddressBarDialog::loadAddress(const QString& address) { qDebug() << "Called LoadAddress with address " << address; if (!address.isEmpty()) { - DependencyManager::get()->handleLookupString(address);; + DependencyManager::get()->handleLookupString(address); } } From 9a51a4c5b18aac06d5a5c97851914e36680b217a Mon Sep 17 00:00:00 2001 From: Seth Alves Date: Wed, 17 Jun 2015 14:48:37 -0700 Subject: [PATCH 85/90] fix debug build --- libraries/shared/src/MatrixStack.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libraries/shared/src/MatrixStack.h b/libraries/shared/src/MatrixStack.h index 5a0b56ff9b..bcb4bb31a9 100644 --- a/libraries/shared/src/MatrixStack.h +++ b/libraries/shared/src/MatrixStack.h @@ -124,7 +124,9 @@ public: push(); f(); pop(); + #ifdef DEBUG assert(startingDepth = size()); + #endif } template From 44bb2201307b9e058669eb529fef4e7abc26509e Mon Sep 17 00:00:00 2001 From: Seth Alves Date: Wed, 17 Jun 2015 14:54:13 -0700 Subject: [PATCH 86/90] fix debug build --- libraries/physics/src/MeshMassProperties.cpp | 2 ++ libraries/shared/src/MatrixStack.h | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/libraries/physics/src/MeshMassProperties.cpp b/libraries/physics/src/MeshMassProperties.cpp index 4e471f7870..21ad8a0e1c 100644 --- a/libraries/physics/src/MeshMassProperties.cpp +++ b/libraries/physics/src/MeshMassProperties.cpp @@ -283,9 +283,11 @@ void MeshMassProperties::computeMassProperties(const VectorOfPoints& points, con uint32_t numTriangles = triangleIndices.size() / 3; for (uint32_t i = 0; i < numTriangles; ++i) { uint32_t t = 3 * i; + #ifdef DEBUG assert(triangleIndices[t] < numPoints); assert(triangleIndices[t + 1] < numPoints); assert(triangleIndices[t + 2] < numPoints); + #endif // extract raw vertices tetraPoints[0] = p0; diff --git a/libraries/shared/src/MatrixStack.h b/libraries/shared/src/MatrixStack.h index bcb4bb31a9..0eea14a18a 100644 --- a/libraries/shared/src/MatrixStack.h +++ b/libraries/shared/src/MatrixStack.h @@ -125,7 +125,7 @@ public: f(); pop(); #ifdef DEBUG - assert(startingDepth = size()); + assert(startingDepth == size()); #endif } From a27e06713b9136c664deae0affb73b08709fb728 Mon Sep 17 00:00:00 2001 From: Bradley Austin Davis Date: Wed, 17 Jun 2015 14:57:14 -0700 Subject: [PATCH 87/90] Preserve the GL matrix stack when running batch commands --- libraries/gpu/src/gpu/GLBackendTransform.cpp | 29 +++++++++----------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/libraries/gpu/src/gpu/GLBackendTransform.cpp b/libraries/gpu/src/gpu/GLBackendTransform.cpp index 3f760e4cc8..2e3c2dca70 100755 --- a/libraries/gpu/src/gpu/GLBackendTransform.cpp +++ b/libraries/gpu/src/gpu/GLBackendTransform.cpp @@ -75,6 +75,8 @@ void GLBackend::syncTransformStateCache() { } void GLBackend::updateTransform() { + GLint originalMatrixMode; + glGetIntegerv(GL_MATRIX_MODE, &originalMatrixMode); // Check all the dirty flags and update the state accordingly if (_transform._invalidProj) { _transform._transformCamera._projection = _transform._projection; @@ -132,12 +134,13 @@ void GLBackend::updateTransform() { (void) CHECK_GL_ERROR(); } + if (_transform._invalidModel || _transform._invalidView) { + if (_transform._lastMode != GL_MODELVIEW) { + glMatrixMode(GL_MODELVIEW); + _transform._lastMode = GL_MODELVIEW; + } if (!_transform._model.isIdentity()) { - if (_transform._lastMode != GL_MODELVIEW) { - glMatrixMode(GL_MODELVIEW); - _transform._lastMode = GL_MODELVIEW; - } Transform::Mat4 modelView; if (!_transform._view.isIdentity()) { Transform mvx; @@ -147,19 +150,12 @@ void GLBackend::updateTransform() { _transform._model.getMatrix(modelView); } glLoadMatrixf(reinterpret_cast< const GLfloat* >(&modelView)); + } else if (!_transform._view.isIdentity()) { + Transform::Mat4 modelView; + _transform._view.getInverseMatrix(modelView); + glLoadMatrixf(reinterpret_cast< const GLfloat* >(&modelView)); } else { - if (!_transform._view.isIdentity()) { - if (_transform._lastMode != GL_MODELVIEW) { - glMatrixMode(GL_MODELVIEW); - _transform._lastMode = GL_MODELVIEW; - } - Transform::Mat4 modelView; - _transform._view.getInverseMatrix(modelView); - glLoadMatrixf(reinterpret_cast< const GLfloat* >(&modelView)); - } else { - // TODO: eventually do something about the matrix when neither view nor model is specified? - // glLoadIdentity(); - } + glLoadIdentity(); } (void) CHECK_GL_ERROR(); } @@ -167,6 +163,7 @@ void GLBackend::updateTransform() { // Flags are clean _transform._invalidView = _transform._invalidProj = _transform._invalidModel = false; + glMatrixMode(originalMatrixMode); } From 68df6b662de3c38a36b9483c7e3bd7f65f09aefc Mon Sep 17 00:00:00 2001 From: Seth Alves Date: Wed, 17 Jun 2015 15:03:09 -0700 Subject: [PATCH 88/90] fix ifdefs around asserts --- libraries/physics/src/MeshMassProperties.cpp | 4 ++-- libraries/shared/src/MatrixStack.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/libraries/physics/src/MeshMassProperties.cpp b/libraries/physics/src/MeshMassProperties.cpp index 21ad8a0e1c..d18c068d26 100644 --- a/libraries/physics/src/MeshMassProperties.cpp +++ b/libraries/physics/src/MeshMassProperties.cpp @@ -270,7 +270,7 @@ void MeshMassProperties::computeMassProperties(const VectorOfPoints& points, con } // create some variables to hold temporary results - #ifdef DEBUG + #ifndef NDEBUG uint32_t numPoints = points.size(); #endif const btVector3 p0(0.0f, 0.0f, 0.0f); @@ -283,7 +283,7 @@ void MeshMassProperties::computeMassProperties(const VectorOfPoints& points, con uint32_t numTriangles = triangleIndices.size() / 3; for (uint32_t i = 0; i < numTriangles; ++i) { uint32_t t = 3 * i; - #ifdef DEBUG + #ifndef NDEBUG assert(triangleIndices[t] < numPoints); assert(triangleIndices[t + 1] < numPoints); assert(triangleIndices[t + 2] < numPoints); diff --git a/libraries/shared/src/MatrixStack.h b/libraries/shared/src/MatrixStack.h index 0eea14a18a..fdfea2b3cb 100644 --- a/libraries/shared/src/MatrixStack.h +++ b/libraries/shared/src/MatrixStack.h @@ -118,13 +118,13 @@ public: template void withPush(Function f) { - #ifdef DEBUG + #ifndef NDEBUG size_t startingDepth = size(); #endif push(); f(); pop(); - #ifdef DEBUG + #ifndef NDEBUG assert(startingDepth == size()); #endif } From 8735fa1eac13af0cf3ba6820117bb81d7df31589 Mon Sep 17 00:00:00 2001 From: Seth Alves Date: Wed, 17 Jun 2015 18:33:43 -0700 Subject: [PATCH 89/90] have variantMapToScriptValue handle lists. --- .../shared/src/VariantMapToScriptValue.cpp | 72 +++++++++++++------ .../shared/src/VariantMapToScriptValue.h | 2 + 2 files changed, 51 insertions(+), 23 deletions(-) diff --git a/libraries/shared/src/VariantMapToScriptValue.cpp b/libraries/shared/src/VariantMapToScriptValue.cpp index 6c21557325..c0d21e9995 100644 --- a/libraries/shared/src/VariantMapToScriptValue.cpp +++ b/libraries/shared/src/VariantMapToScriptValue.cpp @@ -13,35 +13,61 @@ #include "SharedLogging.h" #include "VariantMapToScriptValue.h" + +QScriptValue variantToScriptValue(QVariant& qValue, QScriptEngine& scriptEngine) { + switch(qValue.type()) { + case QVariant::Bool: + return qValue.toBool(); + break; + case QVariant::Int: + return qValue.toInt(); + break; + case QVariant::Double: + return qValue.toDouble(); + break; + case QVariant::String: { + return scriptEngine.newVariant(qValue); + break; + } + case QVariant::Map: { + QVariantMap childMap = qValue.toMap(); + return variantMapToScriptValue(childMap, scriptEngine); + break; + } + case QVariant::List: { + QVariantList childList = qValue.toList(); + return variantListToScriptValue(childList, scriptEngine); + break; + } + default: + qCDebug(shared) << "unhandled QScript type" << qValue.type(); + break; + } + + return QScriptValue(); +} + + QScriptValue variantMapToScriptValue(QVariantMap& variantMap, QScriptEngine& scriptEngine) { QScriptValue scriptValue = scriptEngine.newObject(); for (QVariantMap::const_iterator iter = variantMap.begin(); iter != variantMap.end(); ++iter) { QString key = iter.key(); QVariant qValue = iter.value(); - - switch(qValue.type()) { - case QVariant::Bool: - scriptValue.setProperty(key, qValue.toBool()); - break; - case QVariant::Int: - scriptValue.setProperty(key, qValue.toInt()); - break; - case QVariant::Double: - scriptValue.setProperty(key, qValue.toDouble()); - break; - case QVariant::String: { - scriptValue.setProperty(key, scriptEngine.newVariant(qValue)); - break; - } - case QVariant::Map: { - QVariantMap childMap = qValue.toMap(); - scriptValue.setProperty(key, variantMapToScriptValue(childMap, scriptEngine)); - break; - } - default: - qCDebug(shared) << "unhandled QScript type" << qValue.type(); - } + scriptValue.setProperty(key, variantToScriptValue(qValue, scriptEngine)); + } + + return scriptValue; +} + + +QScriptValue variantListToScriptValue(QVariantList& variantList, QScriptEngine& scriptEngine) { + QScriptValue scriptValue = scriptEngine.newObject(); + + scriptValue.setProperty("length", variantList.size()); + int i = 0; + foreach (QVariant v, variantList) { + scriptValue.setProperty(i++, variantToScriptValue(v, scriptEngine)); } return scriptValue; diff --git a/libraries/shared/src/VariantMapToScriptValue.h b/libraries/shared/src/VariantMapToScriptValue.h index 503f8c6490..ea65cccb3d 100644 --- a/libraries/shared/src/VariantMapToScriptValue.h +++ b/libraries/shared/src/VariantMapToScriptValue.h @@ -13,4 +13,6 @@ #include #include +QScriptValue variantToScriptValue(QVariant& qValue, QScriptEngine& scriptEngine); QScriptValue variantMapToScriptValue(QVariantMap& variantMap, QScriptEngine& scriptEngine); +QScriptValue variantListToScriptValue(QVariantList& variantList, QScriptEngine& scriptEngine); From 610bfc63e8b266e511df3e00ecd9967e6265b544 Mon Sep 17 00:00:00 2001 From: Seth Alves Date: Wed, 17 Jun 2015 18:34:46 -0700 Subject: [PATCH 90/90] check success in OctreePacketData::appendValue for qvectors of vec3s before proceeding with further data appends --- libraries/octree/src/OctreePacketData.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/libraries/octree/src/OctreePacketData.cpp b/libraries/octree/src/OctreePacketData.cpp index 7c977210fc..db2e2953c0 100644 --- a/libraries/octree/src/OctreePacketData.cpp +++ b/libraries/octree/src/OctreePacketData.cpp @@ -384,10 +384,12 @@ bool OctreePacketData::appendValue(const glm::vec3& value) { bool OctreePacketData::appendValue(const QVector& value) { uint16_t qVecSize = value.size(); bool success = appendValue(qVecSize); - success = append((const unsigned char*)value.constData(), qVecSize * sizeof(glm::vec3)); if (success) { - _bytesOfValues += qVecSize * sizeof(glm::vec3); - _totalBytesOfValues += qVecSize * sizeof(glm::vec3); + success = append((const unsigned char*)value.constData(), qVecSize * sizeof(glm::vec3)); + if (success) { + _bytesOfValues += qVecSize * sizeof(glm::vec3); + _totalBytesOfValues += qVecSize * sizeof(glm::vec3); + } } return success; }