From 0c992ef43dab1d3c12fbd397925b6ea319901e2c Mon Sep 17 00:00:00 2001 From: Jeroen Baert Date: Thu, 30 Jan 2014 13:20:37 +0100 Subject: [PATCH 001/595] Updated Ubuntu package requirements --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bc32998113..92fe83c4e1 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ distributions. A Windows build is planned for the future, but not currently in development. On a fresh Ubuntu 13.10 install, these are all the packages you need to grab and build the hifi project: -
sudo apt-get install build-essential cmake git libcurl4-openssl-dev libqt5scripttools5 libqt5svg5-dev libqt5webkit5-dev libqt5location5 qtlocation5-dev qtdeclarative5-dev qtscript5-dev qtsensors5-dev qtmultimedia5-dev qtquick1-5-dev libasound2 libxmu-dev libxi-dev freeglut3-dev libasound2-dev libjack-dev
+
sudo apt-get install build-essential cmake git qttools5-dev libcurl4-openssl-dev libqt5scripttools5 libqt5svg5-dev libqt5webkit5-dev libqt5location5 qtlocation5-dev qtdeclarative5-dev qtscript5-dev qtsensors5-dev qtmultimedia5-dev qtquick1-5-dev libasound2 libxmu-dev libxi-dev freeglut3-dev libasound2-dev libjack-dev
Running Interface ----- From ec73edb8d88f80195d6b9708d6b6847db00c4cf4 Mon Sep 17 00:00:00 2001 From: stojce Date: Sun, 23 Feb 2014 13:54:22 +0100 Subject: [PATCH 002/595] restyled preferences dialog - Frameless dialog super class --- interface/resources/styles/global.qss | 35 ++ interface/src/Menu.cpp | 139 +----- interface/src/Menu.h | 2 + interface/src/ui/FramelessDialog.cpp | 23 + interface/src/ui/FramelessDialog.h | 27 ++ interface/src/ui/PreferencesDialog.cpp | 96 ++++ interface/src/ui/PreferencesDialog.h | 37 ++ interface/ui/preferencesDialog.ui | 646 +++++++++++++++++++++++++ 8 files changed, 871 insertions(+), 134 deletions(-) create mode 100644 interface/resources/styles/global.qss create mode 100644 interface/src/ui/FramelessDialog.cpp create mode 100644 interface/src/ui/FramelessDialog.h create mode 100644 interface/src/ui/PreferencesDialog.cpp create mode 100644 interface/src/ui/PreferencesDialog.h create mode 100644 interface/ui/preferencesDialog.ui diff --git a/interface/resources/styles/global.qss b/interface/resources/styles/global.qss new file mode 100644 index 0000000000..3ecb96fa8c --- /dev/null +++ b/interface/resources/styles/global.qss @@ -0,0 +1,35 @@ +* { + padding: 0; + margin: 0; +} + +FramelessDialog { + background-color: rgb(255, 255, 255); + font-family: Helvetica, Arial, sans-serif; + font-size: 16px; +} + +QLineEdit { + background-color: rgba(255, 255, 255, 1); + border-style: solid; + border-width: 1px; + border-color: #ccc; + padding: 7px; + opacity: 1; +} + +QLabel p { + color: #0e7077; + font-size: 23px; +} + +QPushButton { + border-width: 0; + border-radius: 9px; + border-radius: 9px; + font-family: Arial; + font-size: 18px; + font-weight: 100; + color: #ffffff; + padding: 10px 15px; +} diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 327f905194..e3fd698ecf 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -71,7 +71,8 @@ Menu::Menu() : _voxelSizeScale(DEFAULT_OCTREE_SIZE_SCALE), _boundaryLevelAdjust(0), _maxVoxelPacketsPerSecond(DEFAULT_MAX_VOXEL_PPS), - _lastAdjust(usecTimestampNow()) + _lastAdjust(usecTimestampNow()), + _preferencesDialog() { Application *appInstance = Application::getInstance(); @@ -763,140 +764,10 @@ void Menu::login() { } void Menu::editPreferences() { - Application* applicationInstance = Application::getInstance(); - - QDialog dialog(applicationInstance->getWindow()); - dialog.setWindowTitle("Interface Preferences"); - QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom); - dialog.setLayout(layout); - - QFormLayout* form = new QFormLayout(); - layout->addLayout(form, 1); - - QString faceURLString = applicationInstance->getAvatar()->getHead()->getFaceModel().getURL().toString(); - QLineEdit* faceURLEdit = new QLineEdit(faceURLString); - faceURLEdit->setMinimumWidth(QLINE_MINIMUM_WIDTH); - faceURLEdit->setPlaceholderText(DEFAULT_HEAD_MODEL_URL.toString()); - form->addRow("Face URL:", faceURLEdit); - - QString skeletonURLString = applicationInstance->getAvatar()->getSkeletonModel().getURL().toString(); - QLineEdit* skeletonURLEdit = new QLineEdit(skeletonURLString); - skeletonURLEdit->setMinimumWidth(QLINE_MINIMUM_WIDTH); - skeletonURLEdit->setPlaceholderText(DEFAULT_BODY_MODEL_URL.toString()); - form->addRow("Skeleton URL:", skeletonURLEdit); - - QString displayNameString = applicationInstance->getAvatar()->getDisplayName(); - QLineEdit* displayNameEdit = new QLineEdit(displayNameString); - displayNameEdit->setMinimumWidth(QLINE_MINIMUM_WIDTH); - form->addRow("Display name:", displayNameEdit); - - QSlider* pupilDilation = new QSlider(Qt::Horizontal); - pupilDilation->setValue(applicationInstance->getAvatar()->getHead()->getPupilDilation() * pupilDilation->maximum()); - form->addRow("Pupil Dilation:", pupilDilation); - - QSlider* faceshiftEyeDeflection = new QSlider(Qt::Horizontal); - faceshiftEyeDeflection->setValue(_faceshiftEyeDeflection * faceshiftEyeDeflection->maximum()); - form->addRow("Faceshift Eye Deflection:", faceshiftEyeDeflection); - - QSpinBox* fieldOfView = new QSpinBox(); - fieldOfView->setMaximum(180); - fieldOfView->setMinimum(1); - fieldOfView->setValue(_fieldOfView); - form->addRow("Vertical Field of View (Degrees):", fieldOfView); - - QDoubleSpinBox* leanScale = new QDoubleSpinBox(); - leanScale->setValue(applicationInstance->getAvatar()->getLeanScale()); - form->addRow("Lean Scale:", leanScale); - - QDoubleSpinBox* avatarScale = new QDoubleSpinBox(); - avatarScale->setValue(applicationInstance->getAvatar()->getScale()); - form->addRow("Avatar Scale:", avatarScale); - - QSpinBox* audioJitterBufferSamples = new QSpinBox(); - audioJitterBufferSamples->setMaximum(10000); - audioJitterBufferSamples->setMinimum(-10000); - audioJitterBufferSamples->setValue(_audioJitterBufferSamples); - form->addRow("Audio Jitter Buffer Samples (0 for automatic):", audioJitterBufferSamples); - - QSpinBox* maxVoxels = new QSpinBox(); - const int MAX_MAX_VOXELS = 5000000; - const int MIN_MAX_VOXELS = 0; - const int STEP_MAX_VOXELS = 50000; - maxVoxels->setMaximum(MAX_MAX_VOXELS); - maxVoxels->setMinimum(MIN_MAX_VOXELS); - maxVoxels->setSingleStep(STEP_MAX_VOXELS); - maxVoxels->setValue(_maxVoxels); - form->addRow("Maximum Voxels:", maxVoxels); - - QSpinBox* maxVoxelsPPS = new QSpinBox(); - const int MAX_MAX_VOXELS_PPS = 6000; - const int MIN_MAX_VOXELS_PPS = 60; - const int STEP_MAX_VOXELS_PPS = 10; - maxVoxelsPPS->setMaximum(MAX_MAX_VOXELS_PPS); - maxVoxelsPPS->setMinimum(MIN_MAX_VOXELS_PPS); - maxVoxelsPPS->setSingleStep(STEP_MAX_VOXELS_PPS); - maxVoxelsPPS->setValue(_maxVoxelPacketsPerSecond); - form->addRow("Maximum Voxels Packets Per Second:", maxVoxelsPPS); - - QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - dialog.connect(buttons, SIGNAL(accepted()), SLOT(accept())); - dialog.connect(buttons, SIGNAL(rejected()), SLOT(reject())); - layout->addWidget(buttons); - - int ret = dialog.exec(); - if (ret == QDialog::Accepted) { - QUrl faceModelURL(faceURLEdit->text()); - - bool shouldDispatchIdentityPacket = false; - - if (faceModelURL.toString() != faceURLString) { - // change the faceModelURL in the profile, it will also update this user's BlendFace - applicationInstance->getAvatar()->setFaceModelURL(faceModelURL); - shouldDispatchIdentityPacket = true; - } - - QUrl skeletonModelURL(skeletonURLEdit->text()); - - if (skeletonModelURL.toString() != skeletonURLString) { - // change the skeletonModelURL in the profile, it will also update this user's Body - applicationInstance->getAvatar()->setSkeletonModelURL(skeletonModelURL); - shouldDispatchIdentityPacket = true; - } - - QString displayNameStr(displayNameEdit->text()); - - if (displayNameStr != displayNameString) { - applicationInstance->getAvatar()->setDisplayName(displayNameStr); - shouldDispatchIdentityPacket = true; - } - - if (shouldDispatchIdentityPacket) { - applicationInstance->getAvatar()->sendIdentityPacket(); - } - - applicationInstance->getAvatar()->getHead()->setPupilDilation(pupilDilation->value() / (float)pupilDilation->maximum()); - - _maxVoxels = maxVoxels->value(); - applicationInstance->getVoxels()->setMaxVoxels(_maxVoxels); - - _maxVoxelPacketsPerSecond = maxVoxelsPPS->value(); - - applicationInstance->getAvatar()->setLeanScale(leanScale->value()); - applicationInstance->getAvatar()->setClampedTargetScale(avatarScale->value()); - - _audioJitterBufferSamples = audioJitterBufferSamples->value(); - - if (_audioJitterBufferSamples != 0) { - applicationInstance->getAudio()->setJitterBufferSamples(_audioJitterBufferSamples); - } - - _fieldOfView = fieldOfView->value(); - applicationInstance->resizeGL(applicationInstance->getGLWidget()->width(), applicationInstance->getGLWidget()->height()); - - _faceshiftEyeDeflection = faceshiftEyeDeflection->value() / (float)faceshiftEyeDeflection->maximum(); + if (! _preferencesDialog) { + _preferencesDialog = new PreferencesDialog(Application::getInstance()->getGLWidget()); } - - sendFakeEnterEvent(); + _preferencesDialog->show(); } void Menu::goToDomain(const QString newDomain) { diff --git a/interface/src/Menu.h b/interface/src/Menu.h index bd9cdc523e..4e75bc6fb9 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -15,6 +15,7 @@ #include #include +#include "ui/PreferencesDialog.h" const float ADJUST_LOD_DOWN_FPS = 40.0; const float ADJUST_LOD_UP_FPS = 55.0; @@ -173,6 +174,7 @@ private: QMenu* _activeScriptsMenu; QString replaceLastOccurrence(QChar search, QChar replace, QString string); quint64 _lastAdjust; + QPointer _preferencesDialog; }; namespace MenuOption { diff --git a/interface/src/ui/FramelessDialog.cpp b/interface/src/ui/FramelessDialog.cpp new file mode 100644 index 0000000000..ddd056fd32 --- /dev/null +++ b/interface/src/ui/FramelessDialog.cpp @@ -0,0 +1,23 @@ +// +// FramelessDialog.cpp +// hifi +// +// Created by Stojce Slavkovski on 2/20/14. +// +// + +#include "FramelessDialog.h" +#include +#include + +FramelessDialog::FramelessDialog(QWidget *parent, Qt::WindowFlags flags) : QDialog(parent, flags | Qt::FramelessWindowHint) { + QFile styleSheet("resources/styles/global.qss"); + if (styleSheet.open(QIODevice::ReadOnly)) { + setStyleSheet(styleSheet.readAll()); + } + setWindowOpacity(0.95); +} + +FramelessDialog::~FramelessDialog() { + +} diff --git a/interface/src/ui/FramelessDialog.h b/interface/src/ui/FramelessDialog.h new file mode 100644 index 0000000000..ca11c3eb2f --- /dev/null +++ b/interface/src/ui/FramelessDialog.h @@ -0,0 +1,27 @@ +// +// FramelessDialog.h +// hifi +// +// Created by Stojce Slavkovski on 2/20/14. +// +// + +#ifndef __hifi__FramelessDialog__ +#define __hifi__FramelessDialog__ + +#include +#include +#include +#include +#include + +class FramelessDialog : public QDialog { + Q_OBJECT + +public: + FramelessDialog(QWidget* parent = 0, Qt::WindowFlags flags = 0); + ~FramelessDialog(); + +}; + +#endif /* defined(__hifi__FramelessDialog__) */ diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp new file mode 100644 index 0000000000..df3e94f31f --- /dev/null +++ b/interface/src/ui/PreferencesDialog.cpp @@ -0,0 +1,96 @@ +// +// PreferencesDialog.cpp +// hifi +// +// Created by Stojce Slavkovski on 2/22/14. +// +// + +#include "PreferencesDialog.h" +#include "Application.h" +#include "Menu.h" + +PreferencesDialog::PreferencesDialog(QWidget* parent, Qt::WindowFlags flags) : FramelessDialog(parent, flags) { + ui.setupUi(this); + setAttribute(Qt::WA_DeleteOnClose); + loadPreferences(); +} + +void PreferencesDialog::accept() { + savePreferences(); + close(); +} + +void PreferencesDialog::loadPreferences() { + + MyAvatar* myAvatar = Application::getInstance()->getAvatar(); + Menu* menuInstance = Menu::getInstance(); + + _displayNameString = myAvatar->getDisplayName(); + ui.displayNameEdit->setText(_displayNameString); + + _faceURLString = myAvatar->getHead()->getFaceModel().getURL().toString(); + ui.faceURLEdit->setText(_faceURLString); + + _skeletonURLString = myAvatar->getSkeletonModel().getURL().toString(); + ui.skeletonURLEdit->setText(_skeletonURLString); + + float pupilDilation = myAvatar->getHead()->getPupilDilation(); + ui.pupilDilationSlider->setValue(pupilDilation * ui.pupilDilationSlider->maximum()); + + ui.faceshiftEyeDeflectionSider->setValue(menuInstance->getFaceshiftEyeDeflection() * + ui.faceshiftEyeDeflectionSider->maximum()); + + ui.fieldOfViewSpin->setValue(menuInstance->getFieldOfView() * ui.fieldOfViewSpin->maximum()); + + ui.leanScaleSpin->setValue(myAvatar->getLeanScale()); + + ui.avatarScaleSpin->setValue(myAvatar->getScale()); + + ui.maxVoxelsSpin->setValue(menuInstance->getMaxVoxels()); + + ui.maxVoxelsPPSSpin->setValue(menuInstance->getMaxVoxelPacketsPerSecond()); +} + +void PreferencesDialog::savePreferences() { + + MyAvatar* myAvatar = Application::getInstance()->getAvatar(); + bool shouldDispatchIdentityPacket = false; + + QString displayNameStr(ui.displayNameEdit->text()); + if (displayNameStr != _displayNameString) { + myAvatar->setDisplayName(displayNameStr); + shouldDispatchIdentityPacket = true; + } + + QUrl faceModelURL(ui.faceURLEdit->text()); + if (faceModelURL.toString() != _faceURLString) { + // change the faceModelURL in the profile, it will also update this user's BlendFace + myAvatar->setFaceModelURL(faceModelURL); + shouldDispatchIdentityPacket = true; + } + + QUrl skeletonModelURL(ui.skeletonURLEdit->text()); + if (skeletonModelURL.toString() != _skeletonURLString) { + // change the skeletonModelURL in the profile, it will also update this user's Body + myAvatar->setSkeletonModelURL(skeletonModelURL); + shouldDispatchIdentityPacket = true; + } + + if (shouldDispatchIdentityPacket) { + myAvatar->sendIdentityPacket(); + } + + myAvatar->getHead()->setPupilDilation(ui.pupilDilationSlider->value() / (float)ui.pupilDilationSlider->maximum()); + Application::getInstance()->getVoxels()->setMaxVoxels(ui.maxVoxelsSpin->value()); + + + myAvatar->setLeanScale(ui.leanScaleSpin->value()); + myAvatar->setClampedTargetScale(ui.avatarScaleSpin->value()); + + Application::getInstance()->resizeGL(Application::getInstance()->getGLWidget()->width(), + Application::getInstance()->getGLWidget()->height()); + + // _maxVoxelPacketsPerSecond = maxVoxelsPPS->value(); + // _faceshiftEyeDeflection = faceshiftEyeDeflection->value() / (float)faceshiftEyeDeflection->maximum(); +} diff --git a/interface/src/ui/PreferencesDialog.h b/interface/src/ui/PreferencesDialog.h new file mode 100644 index 0000000000..d5cb41c7df --- /dev/null +++ b/interface/src/ui/PreferencesDialog.h @@ -0,0 +1,37 @@ +// +// PreferencesDialog.h +// hifi +// +// Created by Stojce Slavkovski on 2/22/14. +// +// + +#ifndef __hifi__PreferencesDialog__ +#define __hifi__PreferencesDialog__ + +#include "FramelessDialog.h" +#include "ui_preferencesDialog.h" + +#include + +class PreferencesDialog : public FramelessDialog { + Q_OBJECT + +public: + PreferencesDialog(QWidget* parent = 0, Qt::WindowFlags flags = 0); + +private: + Ui_PreferencesDialog ui; + void loadPreferences(); + void savePreferences(); + + QString _faceURLString; + QString _skeletonURLString; + QString _displayNameString; + +private slots: + void accept(); + +}; + +#endif /* defined(__hifi__PreferencesDialog__) */ diff --git a/interface/ui/preferencesDialog.ui b/interface/ui/preferencesDialog.ui new file mode 100644 index 0000000000..7c89eb15c9 --- /dev/null +++ b/interface/ui/preferencesDialog.ui @@ -0,0 +1,646 @@ + + + PreferencesDialog + + + + 0 + 0 + 611 + 745 + + + + + + 30 + 30 + 555 + 596 + + + + + + + + 23 + + + + color: #0e7077 + + + Avatar + + + faceURLEdit + + + + + + + + 0 + 0 + + + + color: #0e7077 + + + <html><head/><body><p>Avatar display name <span style=" color:#909090;">(optional)</span></p></body></html> + + + displayNameEdit + + + + + + + + 0 + 0 + + + + + 280 + 0 + + + + Qt::LeftToRight + + + + + + Not showing a name + + + + + + + color: #0e7077 + + + Head + + + faceURLEdit + + + + + + + + + + color: #0e7077 + + + Body + + + faceURLEdit + + + + + + + + + + + 23 + + + + color: #0e7077 + + + Advanced Tuning + + + + + + + It's not recomended that you play with these settings unless you've looked into exactly what they do. + + + false + + + true + + + + + + + + 20 + 50 + false + + + + color: #0e7077 + + + <p>Avatar</p> + + + + + + + + 0 + 0 + + + + background-color: #fff + + + + + 7 + 0 + 531 + 26 + + + + + + + Lean scale (applies to Faceshift users) + + + leanScaleSpin + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + + + Vertical field of view + + + fieldOfViewSpin + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 1 + + + 180 + + + + + + + + + + 0 + 0 + + + + background-color: #fff + + + + + 7 + 0 + 531 + 26 + + + + + + + Avatar scale (default is 1.0) + + + avatarScaleSpin + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + + + Pupil dillation + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + Qt::Horizontal + + + + + + + + + + 0 + 0 + + + + background-color: #fff + + + + + 7 + 0 + 531 + 26 + + + + + + + Faceshift eye detection + + + avatarScaleSpin + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + Qt::Horizontal + + + + + + + + + + + + 20 + 50 + false + + + + color: #0e7077 + + + <html><head/><body><p>Voxels</p></body></html> + + + + + + + + 0 + 0 + + + + background-color: #fff + + + + + 7 + 0 + 531 + 26 + + + + + + + Maximum voxels + + + leanScaleSpin + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 5000000 + + + 50000 + + + + + + + + + + + + 0 + 0 + + + + background-color: #fff + + + + + 7 + 0 + 531 + 26 + + + + + + + Max voxels sent each second + + + leanScaleSpin + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 60 + + + 6000 + + + 10 + + + + + + + + + + + + + 0 + 665 + 616 + 80 + + + + background-color: #0e7077 + + + + + 0 + 20 + 591 + 41 + + + + + + + Qt::Horizontal + + + + 0 + 0 + + + + + + + + Cancel + + + + + + + background-color: #fff; +color: #0e7077 + + + Save all changes + + + true + + + + + + + + + + FramelessDialog + 1 + + + + displayNameEdit + faceURLEdit + leanScaleSpin + fieldOfViewSpin + avatarScaleSpin + pupilDilationSlider + + + + + cancelButton + clicked() + PreferencesDialog + close() + + + 372 + 700 + + + 528 + -9 + + + + + defaultButton + clicked() + PreferencesDialog + accept() + + + 20 + 20 + + + 20 + 20 + + + + + From 1e2cd0c1a2c93b3d3b4ff8301e5e1af15e5a0a26 Mon Sep 17 00:00:00 2001 From: stojce Date: Tue, 25 Feb 2014 20:36:14 +0100 Subject: [PATCH 003/595] UI changes --- interface/resources/styles/avatar.svg | 27 + interface/resources/styles/close.svg | 14 + interface/resources/styles/down.svg | 9 + interface/resources/styles/slider-bg.svg | 10 + interface/resources/styles/slider-handle.svg | 10 + interface/resources/styles/up.svg | 9 + interface/resources/styles/wrench.svg | 9 + interface/src/Menu.h | 5 +- interface/src/ui/PreferencesDialog.cpp | 20 +- interface/ui/preferencesDialog.ui | 493 ++++++++----------- 10 files changed, 320 insertions(+), 286 deletions(-) create mode 100644 interface/resources/styles/avatar.svg create mode 100644 interface/resources/styles/close.svg create mode 100644 interface/resources/styles/down.svg create mode 100644 interface/resources/styles/slider-bg.svg create mode 100644 interface/resources/styles/slider-handle.svg create mode 100644 interface/resources/styles/up.svg create mode 100644 interface/resources/styles/wrench.svg diff --git a/interface/resources/styles/avatar.svg b/interface/resources/styles/avatar.svg new file mode 100644 index 0000000000..f9382edee4 --- /dev/null +++ b/interface/resources/styles/avatar.svg @@ -0,0 +1,27 @@ + + + + + + + + diff --git a/interface/resources/styles/close.svg b/interface/resources/styles/close.svg new file mode 100644 index 0000000000..8fe4bf4bdb --- /dev/null +++ b/interface/resources/styles/close.svg @@ -0,0 +1,14 @@ + + + + + + + + + + diff --git a/interface/resources/styles/down.svg b/interface/resources/styles/down.svg new file mode 100644 index 0000000000..983ccd9597 --- /dev/null +++ b/interface/resources/styles/down.svg @@ -0,0 +1,9 @@ + + + + + + diff --git a/interface/resources/styles/slider-bg.svg b/interface/resources/styles/slider-bg.svg new file mode 100644 index 0000000000..36c6478026 --- /dev/null +++ b/interface/resources/styles/slider-bg.svg @@ -0,0 +1,10 @@ + + + + + + + + diff --git a/interface/resources/styles/slider-handle.svg b/interface/resources/styles/slider-handle.svg new file mode 100644 index 0000000000..5d87e8599c --- /dev/null +++ b/interface/resources/styles/slider-handle.svg @@ -0,0 +1,10 @@ + + + + + + + + + diff --git a/interface/resources/styles/up.svg b/interface/resources/styles/up.svg new file mode 100644 index 0000000000..d122c4801e --- /dev/null +++ b/interface/resources/styles/up.svg @@ -0,0 +1,9 @@ + + + + + + diff --git a/interface/resources/styles/wrench.svg b/interface/resources/styles/wrench.svg new file mode 100644 index 0000000000..5019f92b18 --- /dev/null +++ b/interface/resources/styles/wrench.svg @@ -0,0 +1,9 @@ + + + + + + diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 5c1e26933d..81089473d3 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -65,10 +65,12 @@ public: void triggerOption(const QString& menuOption); QAction* getActionForOption(const QString& menuOption); bool isVoxelModeActionChecked(); - + float getAudioJitterBufferSamples() const { return _audioJitterBufferSamples; } + void setAudioJitterBufferSamples(int audioJitterBufferSamples) { _audioJitterBufferSamples = audioJitterBufferSamples; } float getFieldOfView() const { return _fieldOfView; } float getFaceshiftEyeDeflection() const { return _faceshiftEyeDeflection; } + void setFaceshiftEyeDeflection(float faceshiftEyeDeflection) { _faceshiftEyeDeflection = faceshiftEyeDeflection; } BandwidthDialog* getBandwidthDialog() const { return _bandwidthDialog; } FrustumDrawMode getFrustumDrawMode() const { return _frustumDrawMode; } ViewFrustumOffset getViewFrustumOffset() const { return _viewFrustumOffset; } @@ -89,6 +91,7 @@ public: // User Tweakable PPS from Voxel Server int getMaxVoxelPacketsPerSecond() const { return _maxVoxelPacketsPerSecond; } + void setMaxVoxelPacketsPerSecond(int maxVoxelPacketsPerSecond) { _maxVoxelPacketsPerSecond = maxVoxelPacketsPerSecond; } virtual QMenu* getActiveScriptsMenu() { return _activeScriptsMenu;} virtual QAction* addActionToQMenuAndActionHash(QMenu* destinationMenu, diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index df3e94f31f..de585d0a2a 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -35,13 +35,15 @@ void PreferencesDialog::loadPreferences() { _skeletonURLString = myAvatar->getSkeletonModel().getURL().toString(); ui.skeletonURLEdit->setText(_skeletonURLString); - float pupilDilation = myAvatar->getHead()->getPupilDilation(); - ui.pupilDilationSlider->setValue(pupilDilation * ui.pupilDilationSlider->maximum()); + ui.pupilDilationSlider->setValue(myAvatar->getHead()->getPupilDilation() * + ui.pupilDilationSlider->maximum()); ui.faceshiftEyeDeflectionSider->setValue(menuInstance->getFaceshiftEyeDeflection() * ui.faceshiftEyeDeflectionSider->maximum()); - ui.fieldOfViewSpin->setValue(menuInstance->getFieldOfView() * ui.fieldOfViewSpin->maximum()); + ui.audioJitterSpin->setValue(menuInstance->getAudioJitterBufferSamples()); + + ui.fieldOfViewSpin->setValue(menuInstance->getFieldOfView()); ui.leanScaleSpin->setValue(myAvatar->getLeanScale()); @@ -82,15 +84,17 @@ void PreferencesDialog::savePreferences() { } myAvatar->getHead()->setPupilDilation(ui.pupilDilationSlider->value() / (float)ui.pupilDilationSlider->maximum()); - Application::getInstance()->getVoxels()->setMaxVoxels(ui.maxVoxelsSpin->value()); - - myAvatar->setLeanScale(ui.leanScaleSpin->value()); myAvatar->setClampedTargetScale(ui.avatarScaleSpin->value()); + Application::getInstance()->getVoxels()->setMaxVoxels(ui.maxVoxelsSpin->value()); Application::getInstance()->resizeGL(Application::getInstance()->getGLWidget()->width(), Application::getInstance()->getGLWidget()->height()); + + Menu::getInstance()->setFaceshiftEyeDeflection(ui.faceshiftEyeDeflectionSider->value() / + (float)ui.faceshiftEyeDeflectionSider->maximum()); + Menu::getInstance()->setMaxVoxelPacketsPerSecond(ui.maxVoxelsPPSSpin->value()); + + Menu::getInstance()->setAudioJitterBufferSamples(ui.audioJitterSpin->value()); - // _maxVoxelPacketsPerSecond = maxVoxelsPPS->value(); - // _faceshiftEyeDeflection = faceshiftEyeDeflection->value() / (float)faceshiftEyeDeflection->maximum(); } diff --git a/interface/ui/preferencesDialog.ui b/interface/ui/preferencesDialog.ui index 7c89eb15c9..8fed57c06b 100644 --- a/interface/ui/preferencesDialog.ui +++ b/interface/ui/preferencesDialog.ui @@ -7,16 +7,16 @@ 0 0 611 - 745 + 805 30 - 30 + 0 555 - 596 + 701 @@ -96,7 +96,14 @@ - + + + + 0 + 0 + + + @@ -160,55 +167,34 @@ - - - - 0 - 0 - - - - background-color: #fff - - - - - 7 - 0 - 531 - 26 - - - - - - - Lean scale (applies to Faceshift users) - - - leanScaleSpin - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - + + + + + Lean scale (applies to Faceshift users) + + + leanScaleSpin + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + @@ -248,55 +234,34 @@ - - - - 0 - 0 - - - - background-color: #fff - - - - - 7 - 0 - 531 - 26 - - - - - - - Avatar scale (default is 1.0) - - - avatarScaleSpin - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - + + + + + Avatar scale (default is 1.0) + + + avatarScaleSpin + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + @@ -336,65 +301,81 @@ - - - - 0 - 0 - - - - background-color: #fff - - - - - 7 - 0 - 531 - 26 - - - - - - - Faceshift eye detection - - - avatarScaleSpin - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - Qt::Horizontal - - - - - - + + + + + Audio Jitter Buffer Samples (0 for automatic) + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + -10000 + + + 10000 + + + 1 + + + + + + + + + + + Faceshift eye detection + + + avatarScaleSpin + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + Qt::Horizontal + + + + @@ -414,123 +395,81 @@ - - - - 0 - 0 - - - - background-color: #fff - - - - - 7 - 0 - 531 - 26 - - - - - - - Maximum voxels - - - leanScaleSpin - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - 5000000 - - - 50000 - - - - - - + + + + + Maximum voxels + + + leanScaleSpin + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 5000000 + + + 50000 + + + + - - - - 0 - 0 - - - - background-color: #fff - - - - - 7 - 0 - 531 - 26 - - - - - - - Max voxels sent each second - - - leanScaleSpin - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - 60 - - - 6000 - - - 10 - - - - - - + + + + + Max voxels sent each second + + + leanScaleSpin + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 60 + + + 6000 + + + 10 + + + + @@ -538,7 +477,7 @@ 0 - 665 + 725 616 80 From 303fddd93b6ba503557236b4f35e3701561fc2ec Mon Sep 17 00:00:00 2001 From: stojce Date: Tue, 25 Feb 2014 21:19:43 +0100 Subject: [PATCH 004/595] Bad merge fix --- interface/src/Menu.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 5f8cc5c4dc..662f91548f 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -71,8 +71,6 @@ Menu::Menu() : _boundaryLevelAdjust(0), _maxVoxelPacketsPerSecond(DEFAULT_MAX_VOXEL_PPS), _lastAdjust(usecTimestampNow()), - _loginAction(NULL) - _lastAdjust(usecTimestampNow()), _preferencesDialog() { Application *appInstance = Application::getInstance(); From 6383457e4e11f777c109e1fbec832569904026e8 Mon Sep 17 00:00:00 2001 From: stojce Date: Wed, 26 Feb 2014 22:15:12 +0100 Subject: [PATCH 005/595] styling bad merge fix --- interface/resources/styles/global.qss | 32 +++++- interface/src/Menu.cpp | 135 +------------------------ interface/src/ui/FramelessDialog.cpp | 1 + interface/src/ui/PreferencesDialog.cpp | 1 - 4 files changed, 35 insertions(+), 134 deletions(-) diff --git a/interface/resources/styles/global.qss b/interface/resources/styles/global.qss index 3ecb96fa8c..e3548fb52e 100644 --- a/interface/resources/styles/global.qss +++ b/interface/resources/styles/global.qss @@ -26,10 +26,40 @@ QLabel p { QPushButton { border-width: 0; border-radius: 9px; - border-radius: 9px; font-family: Arial; font-size: 18px; font-weight: 100; color: #ffffff; padding: 10px 15px; } + + +QSpinBox { + padding: 5px; + border-width: 1; + +} + +QSpinBox::up-button { + + width: 25px; + height: 18px; + background-image: url(resources/styles/up.svg); + background-repeat: no-repeat; + border: 1px #ccc solid; + + border-top-left-radius: 2px; + border-top-right-radius: 2px; +} + +QSpinBox::down-button { + + width: 25px; + height: 18px; + background-image: url(resources/styles/down.svg); + background-repeat: no-repeat; + border: 1px #ccc solid; + + border-top-left-radius: 2px; + border-top-right-radius: 2px; +} diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 662f91548f..d3a0d7f8c1 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -792,139 +792,10 @@ void Menu::loginForCurrentDomain() { } void Menu::editPreferences() { - Application* applicationInstance = Application::getInstance(); - - QDialog dialog(applicationInstance->getWindow()); - dialog.setWindowTitle("Interface Preferences"); - - QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom); - dialog.setLayout(layout); - - QFormLayout* form = new QFormLayout(); - layout->addLayout(form, 1); - - QString faceURLString = applicationInstance->getAvatar()->getHead()->getFaceModel().getURL().toString(); - QLineEdit* faceURLEdit = new QLineEdit(faceURLString); - faceURLEdit->setMinimumWidth(QLINE_MINIMUM_WIDTH); - faceURLEdit->setPlaceholderText(DEFAULT_HEAD_MODEL_URL.toString()); - form->addRow("Face URL:", faceURLEdit); - - QString skeletonURLString = applicationInstance->getAvatar()->getSkeletonModel().getURL().toString(); - QLineEdit* skeletonURLEdit = new QLineEdit(skeletonURLString); - skeletonURLEdit->setMinimumWidth(QLINE_MINIMUM_WIDTH); - skeletonURLEdit->setPlaceholderText(DEFAULT_BODY_MODEL_URL.toString()); - form->addRow("Skeleton URL:", skeletonURLEdit); - - QString displayNameString = applicationInstance->getAvatar()->getDisplayName(); - QLineEdit* displayNameEdit = new QLineEdit(displayNameString); - displayNameEdit->setMinimumWidth(QLINE_MINIMUM_WIDTH); - form->addRow("Display name:", displayNameEdit); - - QSlider* pupilDilation = new QSlider(Qt::Horizontal); - pupilDilation->setValue(applicationInstance->getAvatar()->getHead()->getPupilDilation() * pupilDilation->maximum()); - form->addRow("Pupil Dilation:", pupilDilation); - - QSlider* faceshiftEyeDeflection = new QSlider(Qt::Horizontal); - faceshiftEyeDeflection->setValue(_faceshiftEyeDeflection * faceshiftEyeDeflection->maximum()); - form->addRow("Faceshift Eye Deflection:", faceshiftEyeDeflection); - - QSpinBox* fieldOfView = new QSpinBox(); - fieldOfView->setMaximum(180); - fieldOfView->setMinimum(1); - fieldOfView->setValue(_fieldOfView); - form->addRow("Vertical Field of View (Degrees):", fieldOfView); - - QDoubleSpinBox* leanScale = new QDoubleSpinBox(); - leanScale->setValue(applicationInstance->getAvatar()->getLeanScale()); - form->addRow("Lean Scale:", leanScale); - - QDoubleSpinBox* avatarScale = new QDoubleSpinBox(); - avatarScale->setValue(applicationInstance->getAvatar()->getScale()); - form->addRow("Avatar Scale:", avatarScale); - - QSpinBox* audioJitterBufferSamples = new QSpinBox(); - audioJitterBufferSamples->setMaximum(10000); - audioJitterBufferSamples->setMinimum(-10000); - audioJitterBufferSamples->setValue(_audioJitterBufferSamples); - form->addRow("Audio Jitter Buffer Samples (0 for automatic):", audioJitterBufferSamples); - - QSpinBox* maxVoxels = new QSpinBox(); - const int MAX_MAX_VOXELS = 5000000; - const int MIN_MAX_VOXELS = 0; - const int STEP_MAX_VOXELS = 50000; - maxVoxels->setMaximum(MAX_MAX_VOXELS); - maxVoxels->setMinimum(MIN_MAX_VOXELS); - maxVoxels->setSingleStep(STEP_MAX_VOXELS); - maxVoxels->setValue(_maxVoxels); - form->addRow("Maximum Voxels:", maxVoxels); - - QSpinBox* maxVoxelsPPS = new QSpinBox(); - const int MAX_MAX_VOXELS_PPS = 6000; - const int MIN_MAX_VOXELS_PPS = 60; - const int STEP_MAX_VOXELS_PPS = 10; - maxVoxelsPPS->setMaximum(MAX_MAX_VOXELS_PPS); - maxVoxelsPPS->setMinimum(MIN_MAX_VOXELS_PPS); - maxVoxelsPPS->setSingleStep(STEP_MAX_VOXELS_PPS); - maxVoxelsPPS->setValue(_maxVoxelPacketsPerSecond); - form->addRow("Maximum Voxels Packets Per Second:", maxVoxelsPPS); - - QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - dialog.connect(buttons, SIGNAL(accepted()), SLOT(accept())); - dialog.connect(buttons, SIGNAL(rejected()), SLOT(reject())); - layout->addWidget(buttons); - - int ret = dialog.exec(); - if (ret == QDialog::Accepted) { - QUrl faceModelURL(faceURLEdit->text()); - - bool shouldDispatchIdentityPacket = false; - - if (faceModelURL.toString() != faceURLString) { - // change the faceModelURL in the profile, it will also update this user's BlendFace - applicationInstance->getAvatar()->setFaceModelURL(faceModelURL); - shouldDispatchIdentityPacket = true; - } - - QUrl skeletonModelURL(skeletonURLEdit->text()); - - if (skeletonModelURL.toString() != skeletonURLString) { - // change the skeletonModelURL in the profile, it will also update this user's Body - applicationInstance->getAvatar()->setSkeletonModelURL(skeletonModelURL); - shouldDispatchIdentityPacket = true; - } - - QString displayNameStr(displayNameEdit->text()); - - if (displayNameStr != displayNameString) { - applicationInstance->getAvatar()->setDisplayName(displayNameStr); - shouldDispatchIdentityPacket = true; - } - - if (shouldDispatchIdentityPacket) { - applicationInstance->getAvatar()->sendIdentityPacket(); - } - - applicationInstance->getAvatar()->getHead()->setPupilDilation(pupilDilation->value() / (float)pupilDilation->maximum()); - - _maxVoxels = maxVoxels->value(); - applicationInstance->getVoxels()->setMaxVoxels(_maxVoxels); - - _maxVoxelPacketsPerSecond = maxVoxelsPPS->value(); - - applicationInstance->getAvatar()->setLeanScale(leanScale->value()); - applicationInstance->getAvatar()->setClampedTargetScale(avatarScale->value()); - - _audioJitterBufferSamples = audioJitterBufferSamples->value(); - - if (_audioJitterBufferSamples != 0) { - applicationInstance->getAudio()->setJitterBufferSamples(_audioJitterBufferSamples); - } - - _fieldOfView = fieldOfView->value(); - applicationInstance->resizeGL(applicationInstance->getGLWidget()->width(), applicationInstance->getGLWidget()->height()); - - _faceshiftEyeDeflection = faceshiftEyeDeflection->value() / (float)faceshiftEyeDeflection->maximum(); + if(! _preferencesDialog) { + _preferencesDialog = new PreferencesDialog(Application::getInstance()->getGLWidget()); } + _preferencesDialog->show(); } diff --git a/interface/src/ui/FramelessDialog.cpp b/interface/src/ui/FramelessDialog.cpp index ddd056fd32..4ca765b352 100644 --- a/interface/src/ui/FramelessDialog.cpp +++ b/interface/src/ui/FramelessDialog.cpp @@ -16,6 +16,7 @@ FramelessDialog::FramelessDialog(QWidget *parent, Qt::WindowFlags flags) : QDial setStyleSheet(styleSheet.readAll()); } setWindowOpacity(0.95); + setAttribute(Qt::WA_DeleteOnClose); } FramelessDialog::~FramelessDialog() { diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index de585d0a2a..b82bcd7e68 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -12,7 +12,6 @@ PreferencesDialog::PreferencesDialog(QWidget* parent, Qt::WindowFlags flags) : FramelessDialog(parent, flags) { ui.setupUi(this); - setAttribute(Qt::WA_DeleteOnClose); loadPreferences(); } From b8bb8013f3862f0e0ff687da25192cbb26163c6c Mon Sep 17 00:00:00 2001 From: stojce Date: Thu, 27 Feb 2014 23:15:57 +0100 Subject: [PATCH 006/595] Bad merge fixes --- interface/src/Menu.h | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 041f1fcd50..f7beca0f39 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -18,6 +18,8 @@ #include #include +#include "ui/PreferencesDialog.h" + const float ADJUST_LOD_DOWN_FPS = 40.0; const float ADJUST_LOD_UP_FPS = 55.0; @@ -66,10 +68,12 @@ public: void setIsOptionChecked(const QString& menuOption, bool isChecked); void triggerOption(const QString& menuOption); QAction* getActionForOption(const QString& menuOption); - + float getAudioJitterBufferSamples() const { return _audioJitterBufferSamples; } + void setAudioJitterBufferSamples(float audioJitterBufferSamples) { _audioJitterBufferSamples = audioJitterBufferSamples; } float getFieldOfView() const { return _fieldOfView; } float getFaceshiftEyeDeflection() const { return _faceshiftEyeDeflection; } + void setFaceshiftEyeDeflection(float faceshiftEyeDeflection) { _faceshiftEyeDeflection = faceshiftEyeDeflection; } BandwidthDialog* getBandwidthDialog() const { return _bandwidthDialog; } FrustumDrawMode getFrustumDrawMode() const { return _frustumDrawMode; } ViewFrustumOffset getViewFrustumOffset() const { return _viewFrustumOffset; } @@ -89,6 +93,7 @@ public: // User Tweakable PPS from Voxel Server int getMaxVoxelPacketsPerSecond() const { return _maxVoxelPacketsPerSecond; } + void setMaxVoxelPacketsPerSecond(int maxVoxelPacketsPerSecond) { _maxVoxelPacketsPerSecond = maxVoxelPacketsPerSecond; } QMenu* getActiveScriptsMenu() { return _activeScriptsMenu;} @@ -194,6 +199,7 @@ private: QString replaceLastOccurrence(QChar search, QChar replace, QString string); quint64 _lastAdjust; QAction* _loginAction; + QPointer _preferencesDialog; }; namespace MenuOption { From 251e38cc16d408ecdff36e0f9fde81392bf8f599 Mon Sep 17 00:00:00 2001 From: matsukaze Date: Sun, 2 Mar 2014 14:28:44 -0500 Subject: [PATCH 007/595] Removed TODO --- interface/src/VoxelSystem.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/interface/src/VoxelSystem.cpp b/interface/src/VoxelSystem.cpp index 99f6171b7a..7513774a07 100644 --- a/interface/src/VoxelSystem.cpp +++ b/interface/src/VoxelSystem.cpp @@ -1751,11 +1751,12 @@ bool VoxelSystem::inspectForExteriorOcclusionsOperation(OctreeElement* element, //qDebug("Completely occupied voxel at %f %f %f size: %f", v.x, v.y, v.z, s); - // TODO: All of the exterior faces of this voxel element are - // occluders, which means that this element is completely - // occupied. Hence, the subtree from this node could be - // pruned and replaced by a leaf voxel, if the visible - // properties of the children are the same + // All of the exterior faces of this voxel element are + // occluders, which means that this element is completely + // occupied. Hence, the subtree from this node could be + // pruned and replaced by a leaf voxel, if the visible + // properties of the children are the same + } else if (exteriorOcclusions != OctreeElement::HalfSpace::None) { //const glm::vec3& v = voxel->getCorner(); //float s = voxel->getScale(); From ddb7fb9271ed9536cb68a5a98f334a81c605c5e4 Mon Sep 17 00:00:00 2001 From: matsukaze Date: Sun, 2 Mar 2014 14:29:25 -0500 Subject: [PATCH 008/595] Additional documentation --- interface/src/PrimitiveRenderer.h | 112 +++++++++++++++++------------- 1 file changed, 62 insertions(+), 50 deletions(-) diff --git a/interface/src/PrimitiveRenderer.h b/interface/src/PrimitiveRenderer.h index 51d96e0840..55f24cdf7a 100644 --- a/interface/src/PrimitiveRenderer.h +++ b/interface/src/PrimitiveRenderer.h @@ -103,7 +103,7 @@ private: /// Copy constructor prohibited. /// Primitive( - const Primitive& prim + const Primitive& copy ); // SPI methods are defined here @@ -150,14 +150,14 @@ public: /// Configuration dependency injection constructor. /// Cube( - float x, - float y, - float z, - float s, - unsigned char r, - unsigned char g, - unsigned char b, - unsigned char faces + float x, ///< Cube location on X-axis + float y, ///< Cube location on Y-axis + float z, ///< Cube location on Z-axis + float s, ///< Cube size + unsigned char r, ///< Cube red color component + unsigned char g, ///< Cube green color component + unsigned char b, ///< Cube blue color component + unsigned char faces ///< Bitmask of faces of cube excluded from construction ); ~Cube(); @@ -169,36 +169,48 @@ private: const Cube& cube ); + /// Cube initialization + /// void init( - float x, - float y, - float z, - float s, - unsigned char r, - unsigned char g, - unsigned char b, - unsigned char faceExclusions + float x, ///< Cube location on X-axis + float y, ///< Cube location on Y-axis + float z, ///< Cube location on Z-axis + float s, ///< Cube size + unsigned char r, ///< Cube red color component + unsigned char g, ///< Cube green color component + unsigned char b, ///< Cube blue color component + unsigned char faceExclusions ///< Bitmask of faces of cube excluded from construction ); + /// Cube termination + /// void terminate(); + /// Initialize cube's vertex list + /// void initializeVertices( - float x, - float y, - float z, - float s, - unsigned char r, - unsigned char g, - unsigned char b, - unsigned char faceExclusions + float x, ///< Cube location on X-axis + float y, ///< Cube location on Y-axis + float z, ///< Cube location on Z-axis + float s, ///< Cube size + unsigned char r, ///< Cube red color component + unsigned char g, ///< Cube green color component + unsigned char b, ///< Cube blue color component + unsigned char faceExclusions ///< Bitmask of faces of cube excluded from construction ); + /// Terminate cube's vertex list + /// void terminateVertices(); + /// Initialize cube's triangle list + /// void initializeTris( unsigned char faceExclusions ); + /// Terminate cube's triangle list + /// void terminateTris(); // SPI virtual override methods go here @@ -216,11 +228,11 @@ private: unsigned long _cpuMemoryUsage; ///< Memory allocation of object - static const int _sNumFacesPerCube = 6; - static const int _sNumVerticesPerCube = 24; - static unsigned char _sFaceIndexToHalfSpaceMask[6]; - static float _sVertexIndexToConstructionVector[24][3]; - static float _sVertexIndexToNormalVector[6][3]; + static const int _sNumFacesPerCube = 6; ///< Number of faces per cube + static const int _sNumVerticesPerCube = 24; ///< Number of vertices per cube + static unsigned char _sFaceIndexToHalfSpaceMask[6]; ///< index to bitmask map + static float _sVertexIndexToConstructionVector[24][3]; ///< Vertex index to construction vector map + static float _sVertexIndexToNormalVector[6][3]; ///< Vertex index to normal vector map }; @@ -239,13 +251,13 @@ public: /// Add primitive to renderer database. /// int add( - Primitive* primitive ///< Pointer to primitive + Primitive* primitive ///< Primitive instance to be added ); /// Remove primitive from renderer database. /// void remove( - int id ///< Primitive id + int id ///< Primitive id to be removed ); /// Clear all primitives from renderer database @@ -275,7 +287,7 @@ private: /// Copy constructor prohibited. /// Renderer( - const Renderer& primitive + const Renderer& copy ); // SPI methods are defined here @@ -283,10 +295,10 @@ private: /// Add primitive to renderer database. /// Service implementer to provide private override for this method /// in derived class - /// @return primitive id + /// @return Primitive id /// virtual int vAdd( - Primitive* primitive ///< Pointer to primitive + Primitive* primitive ///< Primitive instance to be added ) = 0; /// Remove primitive from renderer database. @@ -294,7 +306,7 @@ private: /// in derived class /// virtual void vRemove( - int id ///< Primitive id + int id ///< Primitive id ) = 0; /// Clear all primitives from renderer database @@ -329,7 +341,7 @@ public: /// Configuration dependency injection constructor. /// PrimitiveRenderer( - int maxCount + int maxCount ///< Max count ); ~PrimitiveRenderer(); @@ -362,39 +374,39 @@ private: /// Construct the elements of the faces of the primitive. /// void constructElements( - Primitive* primitive + Primitive* primitive ///< Primitive instance ); /// Deconstruct the elements of the faces of the primitive. /// void deconstructElements( - Primitive* primitive + Primitive* primitive ///< Primitive instance ); /// Deconstruct the triangle element from the GL buffer. /// void deconstructTriElement( - int idx + int idx ///< Triangle element index ); /// Deconstruct the vertex element from the GL buffer. /// void deconstructVertexElement( - int idx + int idx ///< Vertex element index ); /// Transfer the vertex element to the GL buffer. /// void transferVertexElement( - int idx, - VertexElement *vertex + int idx, ///< Vertex element index + VertexElement *vertex ///< Vertex element instance ); /// Transfer the triangle element to the GL buffer. /// void transferTriElement( - int idx, - int tri[3] + int idx, ///< Triangle element index + int tri[3] ///< Triangle element data ); /// Get available primitive index. @@ -421,13 +433,13 @@ private: /// Add primitive to renderer database. /// int vAdd( - Primitive* primitive + Primitive* primitive ///< Primitive instance to be added ); /// Remove primitive from renderer database. /// void vRemove( - int id + int id ///< Primitive id to be removed ); /// Clear all primitives from renderer database @@ -448,7 +460,7 @@ private: private: - int _maxCount; + int _maxCount; ///< Maximum count of tris // GL related parameters @@ -476,8 +488,8 @@ private: // Statistics parameters, not necessary for proper operation - unsigned long _gpuMemoryUsage; - unsigned long _cpuMemoryUsage; + unsigned long _gpuMemoryUsage; ///< GPU memory used by this instance + unsigned long _cpuMemoryUsage; ///< CPU memory used by this instance static const int _sIndicesPerTri = 3; From a29025a7396f7400fe2ac9f4f69d344dd90998ce Mon Sep 17 00:00:00 2001 From: stojce Date: Fri, 14 Mar 2014 01:51:22 +0100 Subject: [PATCH 009/595] New layout --- interface/interface_en.ts | 133 +++++++++++++++++++++++++++++++++++--- interface/src/Menu.cpp | 12 +++- 2 files changed, 135 insertions(+), 10 deletions(-) diff --git a/interface/interface_en.ts b/interface/interface_en.ts index 1d962393d7..a0d1378d44 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -4,22 +4,22 @@ Application - + Export Voxels - + Sparse Voxel Octree Files (*.svo) - + Open Script - + JavaScript Files (*.js) @@ -113,22 +113,139 @@ Menu - + Open .ini config file - - + + Text files (*.ini) - + Save .ini config file + + PreferencesDialog + + + + Avatar + + + + + + <html><head/><body><p>Avatar display name <span style=" color:#909090;">(optional)</span></p></body></html> + + + + + + Not showing a name + + + + + + Head + + + + + + Body + + + + + + Advanced Tuning + + + + + + It's not recomended that you play with these settings unless you've looked into exactly what they do. + + + + + + <p>Avatar</p> + + + + + + Lean scale (applies to Faceshift users) + + + + + + Vertical field of view + + + + + + Avatar scale (default is 1.0) + + + + + + Pupil dillation + + + + + + Audio Jitter Buffer Samples (0 for automatic) + + + + + + Faceshift eye detection + + + + + + <html><head/><body><p>Voxels</p></body></html> + + + + + + Maximum voxels + + + + + + Max voxels sent each second + + + + + + Cancel + + + + + + Save all changes + + + QObject diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index bf94c3ad4b..b20b468acf 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -76,7 +76,7 @@ Menu::Menu() : _lastAdjust(usecTimestampNow()), _fpsAverage(FIVE_SECONDS_OF_FRAMES), _loginAction(NULL), - _preferencesDialog() + _preferencesDialog(NULL) { Application *appInstance = Application::getInstance(); @@ -678,6 +678,14 @@ void Menu::loginForCurrentDomain() { } void Menu::editPreferences() { + if (! _preferencesDialog) { + _preferencesDialog = new PreferencesDialog(Application::getInstance()->getGLWidget()); + _preferencesDialog->show(); + } + _preferencesDialog->raise(); + + /* + Application* applicationInstance = Application::getInstance(); QDialog dialog(applicationInstance->getWindow()); @@ -812,7 +820,7 @@ void Menu::editPreferences() { _faceshiftEyeDeflection = faceshiftEyeDeflection->value() / (float)faceshiftEyeDeflection->maximum(); } QMetaObject::invokeMethod(applicationInstance->getAudio(), "reset", Qt::QueuedConnection); - +*/ sendFakeEnterEvent(); } From 4e2d3c95495a2ae1beb9156ec74bf299cddf604b Mon Sep 17 00:00:00 2001 From: stojce Date: Fri, 14 Mar 2014 23:24:32 +0100 Subject: [PATCH 010/595] styling QSlider --- interface/interface_en.ts | 125 ++++++++++++++++++++++- interface/resources/styles/global.qss | 30 ++++-- interface/src/Menu.cpp | 142 +------------------------- interface/src/ui/FramelessDialog.cpp | 10 +- interface/src/ui/FramelessDialog.h | 2 +- 5 files changed, 154 insertions(+), 155 deletions(-) diff --git a/interface/interface_en.ts b/interface/interface_en.ts index c52ec91671..18ae5f446c 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -113,22 +113,139 @@ Menu - + Open .ini config file - - + + Text files (*.ini) - + Save .ini config file + + PreferencesDialog + + + + Avatar + + + + + + <html><head/><body><p>Avatar display name <span style=" color:#909090;">(optional)</span></p></body></html> + + + + + + Not showing a name + + + + + + Head + + + + + + Body + + + + + + Advanced Tuning + + + + + + It's not recomended that you play with these settings unless you've looked into exactly what they do. + + + + + + <p>Avatar</p> + + + + + + Lean scale (applies to Faceshift users) + + + + + + Vertical field of view + + + + + + Avatar scale (default is 1.0) + + + + + + Pupil dillation + + + + + + Audio Jitter Buffer Samples (0 for automatic) + + + + + + Faceshift eye detection + + + + + + <html><head/><body><p>Voxels</p></body></html> + + + + + + Maximum voxels + + + + + + Max voxels sent each second + + + + + + Cancel + + + + + + Save all changes + + + QObject diff --git a/interface/resources/styles/global.qss b/interface/resources/styles/global.qss index e3548fb52e..87e142eb00 100644 --- a/interface/resources/styles/global.qss +++ b/interface/resources/styles/global.qss @@ -33,18 +33,18 @@ QPushButton { padding: 10px 15px; } - QSpinBox { padding: 5px; border-width: 1; } +QDoubleSpinBox::up-button, QSpinBox::up-button { width: 25px; height: 18px; - background-image: url(resources/styles/up.svg); + background-image: url(styles/up.svg); background-repeat: no-repeat; border: 1px #ccc solid; @@ -52,14 +52,32 @@ QSpinBox::up-button { border-top-right-radius: 2px; } +QDoubleSpinBox::down-button, QSpinBox::down-button { width: 25px; height: 18px; - background-image: url(resources/styles/down.svg); + background-image: url(styles/down.svg); background-repeat: no-repeat; border: 1px #ccc solid; - - border-top-left-radius: 2px; - border-top-right-radius: 2px; +} + +QSlider { + width: 125px; + height: 18px; +} + +QSlider::groove:horizontal { + border: none; + background-image: url(styles/slider-bg.svg); + background-repeat: no-repeat; + background-position: center center; +} + +QSlider::handle:horizontal { + width: 18px; + height: 18px; + background-image: url(styles/slider-handle.svg); + background-repeat: no-repeat; + background-position: center center; } diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 1d3b6753ff..df9e1d40dc 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -687,148 +687,8 @@ void Menu::loginForCurrentDomain() { void Menu::editPreferences() { if (! _preferencesDialog) { _preferencesDialog = new PreferencesDialog(Application::getInstance()->getGLWidget()); - _preferencesDialog->show(); } - _preferencesDialog->raise(); - - /* - - Application* applicationInstance = Application::getInstance(); - - QDialog dialog(applicationInstance->getWindow()); - dialog.setWindowTitle("Interface Preferences"); - - QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom); - dialog.setLayout(layout); - - QFormLayout* form = new QFormLayout(); - layout->addLayout(form, 1); - - QString faceURLString = applicationInstance->getAvatar()->getHead()->getFaceModel().getURL().toString(); - QLineEdit* faceURLEdit = new QLineEdit(faceURLString); - faceURLEdit->setMinimumWidth(QLINE_MINIMUM_WIDTH); - faceURLEdit->setPlaceholderText(DEFAULT_HEAD_MODEL_URL.toString()); - form->addRow("Face URL:", faceURLEdit); - - QString skeletonURLString = applicationInstance->getAvatar()->getSkeletonModel().getURL().toString(); - QLineEdit* skeletonURLEdit = new QLineEdit(skeletonURLString); - skeletonURLEdit->setMinimumWidth(QLINE_MINIMUM_WIDTH); - skeletonURLEdit->setPlaceholderText(DEFAULT_BODY_MODEL_URL.toString()); - form->addRow("Skeleton URL:", skeletonURLEdit); - - QString displayNameString = applicationInstance->getAvatar()->getDisplayName(); - QLineEdit* displayNameEdit = new QLineEdit(displayNameString); - displayNameEdit->setMinimumWidth(QLINE_MINIMUM_WIDTH); - form->addRow("Display name:", displayNameEdit); - - QSlider* pupilDilation = new QSlider(Qt::Horizontal); - pupilDilation->setValue(applicationInstance->getAvatar()->getHead()->getPupilDilation() * pupilDilation->maximum()); - form->addRow("Pupil Dilation:", pupilDilation); - - QSlider* faceshiftEyeDeflection = new QSlider(Qt::Horizontal); - faceshiftEyeDeflection->setValue(_faceshiftEyeDeflection * faceshiftEyeDeflection->maximum()); - form->addRow("Faceshift Eye Deflection:", faceshiftEyeDeflection); - - QSpinBox* fieldOfView = new QSpinBox(); - fieldOfView->setMaximum(180.f); - fieldOfView->setMinimum(1.f); - fieldOfView->setValue(_fieldOfView); - form->addRow("Vertical Field of View (Degrees):", fieldOfView); - - QDoubleSpinBox* leanScale = new QDoubleSpinBox(); - leanScale->setValue(applicationInstance->getAvatar()->getLeanScale()); - form->addRow("Lean Scale:", leanScale); - - QDoubleSpinBox* avatarScale = new QDoubleSpinBox(); - avatarScale->setValue(applicationInstance->getAvatar()->getScale()); - form->addRow("Avatar Scale:", avatarScale); - - QSpinBox* audioJitterBufferSamples = new QSpinBox(); - audioJitterBufferSamples->setMaximum(10000); - audioJitterBufferSamples->setMinimum(-10000); - audioJitterBufferSamples->setValue(_audioJitterBufferSamples); - form->addRow("Audio Jitter Buffer Samples (0 for automatic):", audioJitterBufferSamples); - - QSpinBox* maxVoxels = new QSpinBox(); - const int MAX_MAX_VOXELS = 5000000; - const int MIN_MAX_VOXELS = 0; - const int STEP_MAX_VOXELS = 50000; - maxVoxels->setMaximum(MAX_MAX_VOXELS); - maxVoxels->setMinimum(MIN_MAX_VOXELS); - maxVoxels->setSingleStep(STEP_MAX_VOXELS); - maxVoxels->setValue(_maxVoxels); - form->addRow("Maximum Voxels:", maxVoxels); - - QSpinBox* maxVoxelsPPS = new QSpinBox(); - const int MAX_MAX_VOXELS_PPS = 6000; - const int MIN_MAX_VOXELS_PPS = 60; - const int STEP_MAX_VOXELS_PPS = 10; - maxVoxelsPPS->setMaximum(MAX_MAX_VOXELS_PPS); - maxVoxelsPPS->setMinimum(MIN_MAX_VOXELS_PPS); - maxVoxelsPPS->setSingleStep(STEP_MAX_VOXELS_PPS); - maxVoxelsPPS->setValue(_maxVoxelPacketsPerSecond); - form->addRow("Maximum Voxels Packets Per Second:", maxVoxelsPPS); - - QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - dialog.connect(buttons, SIGNAL(accepted()), SLOT(accept())); - dialog.connect(buttons, SIGNAL(rejected()), SLOT(reject())); - layout->addWidget(buttons); - - int ret = dialog.exec(); - if (ret == QDialog::Accepted) { - QUrl faceModelURL(faceURLEdit->text()); - - bool shouldDispatchIdentityPacket = false; - - if (faceModelURL.toString() != faceURLString) { - // change the faceModelURL in the profile, it will also update this user's BlendFace - applicationInstance->getAvatar()->setFaceModelURL(faceModelURL); - shouldDispatchIdentityPacket = true; - } - - QUrl skeletonModelURL(skeletonURLEdit->text()); - - if (skeletonModelURL.toString() != skeletonURLString) { - // change the skeletonModelURL in the profile, it will also update this user's Body - applicationInstance->getAvatar()->setSkeletonModelURL(skeletonModelURL); - shouldDispatchIdentityPacket = true; - } - - QString displayNameStr(displayNameEdit->text()); - - if (displayNameStr != displayNameString) { - applicationInstance->getAvatar()->setDisplayName(displayNameStr); - shouldDispatchIdentityPacket = true; - } - - if (shouldDispatchIdentityPacket) { - applicationInstance->getAvatar()->sendIdentityPacket(); - } - - applicationInstance->getAvatar()->getHead()->setPupilDilation(pupilDilation->value() / (float)pupilDilation->maximum()); - - _maxVoxels = maxVoxels->value(); - applicationInstance->getVoxels()->setMaxVoxels(_maxVoxels); - - _maxVoxelPacketsPerSecond = maxVoxelsPPS->value(); - - applicationInstance->getAvatar()->setLeanScale(leanScale->value()); - applicationInstance->getAvatar()->setClampedTargetScale(avatarScale->value()); - - _audioJitterBufferSamples = audioJitterBufferSamples->value(); - - if (_audioJitterBufferSamples != 0) { - applicationInstance->getAudio()->setJitterBufferSamples(_audioJitterBufferSamples); - } - - _fieldOfView = fieldOfView->value(); - applicationInstance->resizeGL(applicationInstance->getGLWidget()->width(), applicationInstance->getGLWidget()->height()); - - _faceshiftEyeDeflection = faceshiftEyeDeflection->value() / (float)faceshiftEyeDeflection->maximum(); - } - QMetaObject::invokeMethod(applicationInstance->getAudio(), "reset", Qt::QueuedConnection); -*/ - sendFakeEnterEvent(); + _preferencesDialog->show(); } void Menu::goToDomain(const QString newDomain) { diff --git a/interface/src/ui/FramelessDialog.cpp b/interface/src/ui/FramelessDialog.cpp index 4ca765b352..94bb218171 100644 --- a/interface/src/ui/FramelessDialog.cpp +++ b/interface/src/ui/FramelessDialog.cpp @@ -6,13 +6,17 @@ // // -#include "FramelessDialog.h" -#include #include +#include + +#include "Application.h" +#include "FramelessDialog.h" FramelessDialog::FramelessDialog(QWidget *parent, Qt::WindowFlags flags) : QDialog(parent, flags | Qt::FramelessWindowHint) { - QFile styleSheet("resources/styles/global.qss"); + + QFile styleSheet(Application::resourcesPath() + "styles/global.qss"); if (styleSheet.open(QIODevice::ReadOnly)) { + QDir::setCurrent(Application::resourcesPath()); setStyleSheet(styleSheet.readAll()); } setWindowOpacity(0.95); diff --git a/interface/src/ui/FramelessDialog.h b/interface/src/ui/FramelessDialog.h index ca11c3eb2f..fd2121ddad 100644 --- a/interface/src/ui/FramelessDialog.h +++ b/interface/src/ui/FramelessDialog.h @@ -20,7 +20,7 @@ class FramelessDialog : public QDialog { public: FramelessDialog(QWidget* parent = 0, Qt::WindowFlags flags = 0); - ~FramelessDialog(); + virtual ~FramelessDialog(); }; From ebd7dff4b97a2a9dd221fb114ff40785f3b08e24 Mon Sep 17 00:00:00 2001 From: stojce Date: Sat, 15 Mar 2014 22:07:29 +0100 Subject: [PATCH 011/595] QSpinBox, QDoubleSpinBox styling --- interface/resources/styles/global.qss | 49 +++++++++++++++++---------- interface/src/ui/FramelessDialog.cpp | 1 + 2 files changed, 33 insertions(+), 17 deletions(-) diff --git a/interface/resources/styles/global.qss b/interface/resources/styles/global.qss index 87e142eb00..14929d39af 100644 --- a/interface/resources/styles/global.qss +++ b/interface/resources/styles/global.qss @@ -33,33 +33,48 @@ QPushButton { padding: 10px 15px; } -QSpinBox { +QSpinBox, QDoubleSpinBox { padding: 5px; border-width: 1; - +} + +QDoubleSpinBox::up-arrow, +QSpinBox::up-arrow { + background-image: url(styles/up.svg); + background-repeat: no-repeat; + background-position: center center; +} + +QDoubleSpinBox::down-arrow, +QSpinBox::down-arrow { + background-image: url(styles/down.svg); + background-repeat: no-repeat; + background-position: center center; +} + +QDoubleSpinBox::up-button, +QSpinBox::up-button, +QDoubleSpinBox::down-button, +QSpinBox::down-button { + width: 26px; + height: 13px; + + background-color: #f2f2f2; + border-color: #ccc; + border-style: solid; + border-width: 1px; } QDoubleSpinBox::up-button, QSpinBox::up-button { - - width: 25px; - height: 18px; - background-image: url(styles/up.svg); - background-repeat: no-repeat; - border: 1px #ccc solid; - - border-top-left-radius: 2px; - border-top-right-radius: 2px; + border-top-left-radius: 4px; + border-top-right-radius: 4px; } QDoubleSpinBox::down-button, QSpinBox::down-button { - - width: 25px; - height: 18px; - background-image: url(styles/down.svg); - background-repeat: no-repeat; - border: 1px #ccc solid; + border-bottom-left-radius: 4px; + border-bottom-right-radius: 4px; } QSlider { diff --git a/interface/src/ui/FramelessDialog.cpp b/interface/src/ui/FramelessDialog.cpp index 94bb218171..2216e61b91 100644 --- a/interface/src/ui/FramelessDialog.cpp +++ b/interface/src/ui/FramelessDialog.cpp @@ -19,6 +19,7 @@ FramelessDialog::FramelessDialog(QWidget *parent, Qt::WindowFlags flags) : QDial QDir::setCurrent(Application::resourcesPath()); setStyleSheet(styleSheet.readAll()); } + setWindowOpacity(0.95); setAttribute(Qt::WA_DeleteOnClose); } From 913783c0f121cd6763a2a76f3e4771a30d35eb2a Mon Sep 17 00:00:00 2001 From: stojce Date: Sun, 16 Mar 2014 22:47:03 +0100 Subject: [PATCH 012/595] resizing - fixed layout --- interface/interface_en.ts | 131 +- interface/resources/styles/global.qss | 4 +- interface/resources/styles/preferences.qss | 11 + interface/src/Menu.cpp | 3 +- interface/src/ui/FramelessDialog.cpp | 42 +- interface/src/ui/FramelessDialog.h | 13 +- interface/src/ui/PreferencesDialog.cpp | 1 + interface/ui/preferencesDialog.ui | 1615 ++++++++++++++------ 8 files changed, 1296 insertions(+), 524 deletions(-) create mode 100644 interface/resources/styles/preferences.qss diff --git a/interface/interface_en.ts b/interface/interface_en.ts index 75ada1910c..3c61d5f17a 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -113,22 +113,145 @@ Menu - + Open .ini config file - - + + Text files (*.ini) - + Save .ini config file + + PreferencesDialog + + + + Avatar + + + + + + <html><head/><body><p>Avatar display name <span style=" color:#909090;">(optional)</span></p></body></html> + + + + + + Not showing a name + + + + + + Head + + + + + + Body + + + + + + Advanced Tuning + + + + + + It's not recomended that you play with these settings unless you've looked into exactly what they do. + + + + + + <p>Avatar</p> + + + + + + Lean scale (applies to Faceshift users) + + + + + + Vertical field of view + + + + + + Avatar scale (default is 1.0) + + + + + + Pupil dillation + + + + + + Audio Jitter Buffer Samples (0 for automatic) + + + + + + Faceshift eye detection + + + + + + <html><head/><body><p>Voxels</p></body></html> + + + + + + Maximum voxels + + + + + + Max voxels sent each second + + + + + + PushButton + + + + + + Cancel + + + + + + Save all changes + + + QObject diff --git a/interface/resources/styles/global.qss b/interface/resources/styles/global.qss index 14929d39af..d302555463 100644 --- a/interface/resources/styles/global.qss +++ b/interface/resources/styles/global.qss @@ -4,7 +4,6 @@ } FramelessDialog { - background-color: rgb(255, 255, 255); font-family: Helvetica, Arial, sans-serif; font-size: 16px; } @@ -67,12 +66,15 @@ QSpinBox::down-button { QDoubleSpinBox::up-button, QSpinBox::up-button { + + margin-top:2px; border-top-left-radius: 4px; border-top-right-radius: 4px; } QDoubleSpinBox::down-button, QSpinBox::down-button { + margin-bottom:3px; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; } diff --git a/interface/resources/styles/preferences.qss b/interface/resources/styles/preferences.qss new file mode 100644 index 0000000000..ee587b70da --- /dev/null +++ b/interface/resources/styles/preferences.qss @@ -0,0 +1,11 @@ +QLabel#avatarLabel { + background-image: url(styles/avatar.svg); + background-repeat: no-repeat; + background-position: left center; +} + +QLabel#advancedTuningLabel { + background-image: url(styles/wrench.svg); + background-repeat: no-repeat; + background-position: left center; +} diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index dd43e511bd..99e984c8cb 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -695,8 +695,9 @@ void Menu::loginForCurrentDomain() { void Menu::editPreferences() { if (! _preferencesDialog) { _preferencesDialog = new PreferencesDialog(Application::getInstance()->getGLWidget()); + _preferencesDialog->show(); } - _preferencesDialog->show(); + _preferencesDialog->raise(); } void Menu::goToDomain(const QString newDomain) { diff --git a/interface/src/ui/FramelessDialog.cpp b/interface/src/ui/FramelessDialog.cpp index 2216e61b91..9239deed90 100644 --- a/interface/src/ui/FramelessDialog.cpp +++ b/interface/src/ui/FramelessDialog.cpp @@ -8,20 +8,46 @@ #include #include +#include #include "Application.h" #include "FramelessDialog.h" FramelessDialog::FramelessDialog(QWidget *parent, Qt::WindowFlags flags) : QDialog(parent, flags | Qt::FramelessWindowHint) { - - QFile styleSheet(Application::resourcesPath() + "styles/global.qss"); - if (styleSheet.open(QIODevice::ReadOnly)) { - QDir::setCurrent(Application::resourcesPath()); - setStyleSheet(styleSheet.readAll()); - } - - setWindowOpacity(0.95); + setWindowOpacity(0.9); setAttribute(Qt::WA_DeleteOnClose); + isResizing = false; +} + +void FramelessDialog::setStyleSheet(const QString& fileName) { + QFile globalStyleSheet(Application::resourcesPath() + "styles/global.qss"); + QFile styleSheet(Application::resourcesPath() + fileName); + if (styleSheet.open(QIODevice::ReadOnly) && globalStyleSheet.open(QIODevice::ReadOnly) ) { + QDir::setCurrent(Application::resourcesPath()); + QDialog::setStyleSheet(globalStyleSheet.readAll() + styleSheet.readAll()); + } +} +void FramelessDialog::mousePressEvent(QMouseEvent* mouseEvent) { + if (abs(mouseEvent->pos().x() - size().width()) < 2 && mouseEvent->button() == Qt::LeftButton) { + isResizing = true; + QApplication::setOverrideCursor(Qt::SizeHorCursor); + } + // propagate the event + QDialog::mousePressEvent(mouseEvent); +} + +void FramelessDialog::mouseReleaseEvent(QMouseEvent* mouseEvent) { + QApplication::restoreOverrideCursor(); + isResizing = false; + // propagate the event + QDialog::mouseReleaseEvent(mouseEvent); +} + +void FramelessDialog::mouseMoveEvent(QMouseEvent* mouseEvent) { + if (isResizing) { + resize(mouseEvent->pos().x(), size().height()); + } + QDialog::mouseMoveEvent(mouseEvent); } FramelessDialog::~FramelessDialog() { diff --git a/interface/src/ui/FramelessDialog.h b/interface/src/ui/FramelessDialog.h index fd2121ddad..4e18aff161 100644 --- a/interface/src/ui/FramelessDialog.h +++ b/interface/src/ui/FramelessDialog.h @@ -10,10 +10,10 @@ #define __hifi__FramelessDialog__ #include +#include +#include #include #include -#include -#include class FramelessDialog : public QDialog { Q_OBJECT @@ -21,6 +21,15 @@ class FramelessDialog : public QDialog { public: FramelessDialog(QWidget* parent = 0, Qt::WindowFlags flags = 0); virtual ~FramelessDialog(); + void setStyleSheet(const QString& fileName); + +protected: + void mouseMoveEvent(QMouseEvent* mouseEvent); + void mousePressEvent(QMouseEvent* mouseEvent); + void mouseReleaseEvent(QMouseEvent* mouseEvent); + +private: + bool isResizing; }; diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index b82bcd7e68..318db54f2c 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -12,6 +12,7 @@ PreferencesDialog::PreferencesDialog(QWidget* parent, Qt::WindowFlags flags) : FramelessDialog(parent, flags) { ui.setupUi(this); + setStyleSheet("styles/preferences.qss"); loadPreferences(); } diff --git a/interface/ui/preferencesDialog.ui b/interface/ui/preferencesDialog.ui index 8fed57c06b..0099838177 100644 --- a/interface/ui/preferencesDialog.ui +++ b/interface/ui/preferencesDialog.ui @@ -2,486 +2,43 @@ PreferencesDialog + + Qt::ApplicationModal + 0 0 - 611 - 805 + 640 + 752 - - - - 30 - 0 - 555 - 701 - - - - - - - - 23 - - - - color: #0e7077 - - - Avatar - - - faceURLEdit - - - - - - - - 0 - 0 - - - - color: #0e7077 - - - <html><head/><body><p>Avatar display name <span style=" color:#909090;">(optional)</span></p></body></html> - - - displayNameEdit - - - - - - - - 0 - 0 - - - - - 280 - 0 - - - - Qt::LeftToRight - - - - - - Not showing a name - - - - - - - color: #0e7077 - - - Head - - - faceURLEdit - - - - - - - - 0 - 0 - - - - - - - - color: #0e7077 - - - Body - - - faceURLEdit - - - - - - - - - - - 23 - - - - color: #0e7077 - - - Advanced Tuning - - - - - - - It's not recomended that you play with these settings unless you've looked into exactly what they do. - - - false - - - true - - - - - - - - 20 - 50 - false - - - - color: #0e7077 - - - <p>Avatar</p> - - - - - - - - - Lean scale (applies to Faceshift users) - - - leanScaleSpin - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - - - Vertical field of view - - - fieldOfViewSpin - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - 1 - - - 180 - - - - - - - - - - - Avatar scale (default is 1.0) - - - avatarScaleSpin - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - - - Pupil dillation - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - Qt::Horizontal - - - - - - - - - - - Audio Jitter Buffer Samples (0 for automatic) - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - -10000 - - - 10000 - - - 1 - - - - - - - - - - - Faceshift eye detection - - - avatarScaleSpin - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - Qt::Horizontal - - - - - - - - - - 20 - 50 - false - - - - color: #0e7077 - - - <html><head/><body><p>Voxels</p></body></html> - - - - - - - - - Maximum voxels - - - leanScaleSpin - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - 5000000 - - - 50000 - - - - - - - - - - - Max voxels sent each second - - - leanScaleSpin - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - 60 - - - 6000 - - - 10 - - - - - - - + + + 0 + 0 + + + + + 610 + 0 + + 0 - 725 + 720 616 80 + + + Arial + + background-color: #0e7077 @@ -494,9 +51,22 @@ 41 + + + Arial + + + + 0 + + + + Arial + + Qt::Horizontal @@ -510,6 +80,11 @@ + + + Arial + + Cancel @@ -517,6 +92,11 @@ + + + Arial + + background-color: #fff; color: #0e7077 @@ -532,6 +112,1066 @@ color: #0e7077 + + + + 0 + 0 + 621 + 1000 + + + + + 0 + 0 + + + + true + + + + + 0 + 0 + 619 + 998 + + + + + + 0 + 50 + 621 + 783 + + + + + Arial + + + + + 0 + + + 30 + + + 0 + + + 30 + + + + + + 0 + 0 + + + + + Arial + 24 + + + + color: #0e7077 + + + Avatar + + + 25 + + + + + + + + + + + 0 + 0 + + + + + 0 + 30 + + + + + Arial + 16 + + + + color: #0e7077 + + + <html><head/><body><p>Avatar display name <span style=" color:#909090;">(optional)</span></p></body></html> + + + Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft + + + displayNameEdit + + + + + + + + 0 + 0 + + + + + 280 + 0 + + + + + Arial + + + + Qt::LeftToRight + + + + + + Not showing a name + + + + + + + + 0 + 0 + + + + + 0 + 30 + + + + + Arial + 16 + + + + color: #0e7077 + + + Head + + + Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft + + + 0 + + + faceURLEdit + + + + + + + + 0 + 0 + + + + + Arial + + + + + + + + + 0 + 0 + + + + + 0 + 30 + + + + + Arial + 16 + + + + color: #0e7077 + + + Body + + + Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft + + + skeletonURLEdit + + + + + + + + 0 + 0 + + + + + Arial + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + Arial + 24 + + + + color: #0e7077 + + + Advanced Tuning + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + 25 + + + + + + + + 0 + 0 + + + + + Arial + + + + color: rgb(51, 51, 51) + + + It's not recomended that you play with these settings unless you've looked into exactly what they do. + + + false + + + true + + + + + + + + 0 + 0 + + + + + 0 + 40 + + + + + Arial + 20 + 50 + false + + + + color: #0e7077 + + + <p>Avatar</p> + + + Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft + + + + + + + 0 + + + 10 + + + 10 + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 25 + + + + + Arial + + + + color: rgb(51, 51, 51) + + + Lean scale (applies to Faceshift users) + + + leanScaleSpin + + + + + + + + Arial + + + + Qt::Horizontal + + + QSizePolicy::Expanding + + + + 40 + 10 + + + + + + + + + 0 + 0 + + + + + 95 + 36 + + + + + 70 + 16777215 + + + + + Arial + + + + + + + + + + 0 + + + 10 + + + 0 + + + 10 + + + + + + Arial + + + + color: rgb(51, 51, 51) + + + Vertical field of view + + + fieldOfViewSpin + + + + + + + + Arial + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 95 + 36 + + + + + 70 + 16777215 + + + + + Arial + + + + 1 + + + 180 + + + + + + + + + 0 + + + 10 + + + 0 + + + 10 + + + + + + Arial + + + + color: rgb(51, 51, 51) + + + Avatar scale (default is 1.0) + + + avatarScaleSpin + + + + + + + + Arial + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 95 + 36 + + + + + 70 + 16777215 + + + + + Arial + + + + + + + + + + 0 + + + 10 + + + 0 + + + 10 + + + + + + Arial + + + + color: rgb(51, 51, 51) + + + Pupil dillation + + + + + + + + Arial + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 125 + 0 + + + + + Arial + + + + Qt::Horizontal + + + + + + + + + 0 + + + 10 + + + 0 + + + 10 + + + + + + Arial + + + + color: rgb(51, 51, 51) + + + Audio Jitter Buffer Samples (0 for automatic) + + + + + + + + Arial + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 95 + 36 + + + + + 70 + 16777215 + + + + + Arial + + + + -10000 + + + 10000 + + + 1 + + + + + + + + + 0 + + + 10 + + + 0 + + + 10 + + + + + + Arial + + + + color: rgb(51, 51, 51) + + + Faceshift eye detection + + + avatarScaleSpin + + + + + + + + Arial + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 125 + 0 + + + + + Arial + + + + Qt::Horizontal + + + + + + + + + + 0 + 0 + + + + + 0 + 40 + + + + + Arial + 20 + 50 + false + + + + color: #0e7077 + + + <html><head/><body><p>Voxels</p></body></html> + + + + + + + 0 + + + 10 + + + 0 + + + 10 + + + + + + Arial + + + + color: rgb(51, 51, 51) + + + Maximum voxels + + + leanScaleSpin + + + + + + + + Arial + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 125 + 36 + + + + + Arial + + + + 5000000 + + + 50000 + + + + + + + + + 0 + + + 10 + + + 0 + + + 10 + + + + + + Arial + + + + Max voxels sent each second + + + leanScaleSpin + + + + + + + + Arial + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 95 + 36 + + + + + 70 + 16777215 + + + + + Arial + + + + 60 + + + 6000 + + + 10 + + + + + + + + + + + 540 + 40 + 114 + 32 + + + + PushButton + + + + @@ -539,47 +1179,6 @@ color: #0e7077 1 - - displayNameEdit - faceURLEdit - leanScaleSpin - fieldOfViewSpin - avatarScaleSpin - pupilDilationSlider - - - - cancelButton - clicked() - PreferencesDialog - close() - - - 372 - 700 - - - 528 - -9 - - - - - defaultButton - clicked() - PreferencesDialog - accept() - - - 20 - 20 - - - 20 - 20 - - - - + From 5fe59acb87996447bafba976488cc7511f5fa3d0 Mon Sep 17 00:00:00 2001 From: Lucas Crisman Date: Fri, 21 Mar 2014 14:10:00 -0300 Subject: [PATCH 013/595] Stats variable width for panels --- interface/src/Application.cpp | 424 ++---------------------------- interface/src/Application.h | 8 - interface/src/ui/Stats.cpp | 468 ++++++++++++++++++++++++++++++++++ interface/src/ui/Stats.h | 40 +++ 4 files changed, 525 insertions(+), 415 deletions(-) create mode 100644 interface/src/ui/Stats.cpp create mode 100644 interface/src/ui/Stats.h diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 030e3bc6fd..01e68e92d9 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -76,6 +76,7 @@ #include "ui/TextRenderer.h" #include "InfoView.h" #include "ui/Snapshot.h" +#include "ui/Stats.h" using namespace std; @@ -105,8 +106,6 @@ const float MIRROR_FIELD_OF_VIEW = 30.0f; const QString CHECK_VERSION_URL = "http://highfidelity.io/latestVersion.xml"; const QString SKIP_FILENAME = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/hifi.skipversion"; -const int STATS_PELS_PER_LINE = 20; - const QString CUSTOM_URL_SCHEME = "hifi:"; void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message) { @@ -132,7 +131,6 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : QApplication(argc, argv), _window(new QMainWindow(desktop())), _glWidget(new GLCanvas()), - _statsExpanded(false), _nodeThread(new QThread(this)), _datagramProcessor(), _frameCount(0), @@ -162,8 +160,6 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : _voxelHideShowThread(&_voxels), _packetsPerSecond(0), _bytesPerSecond(0), - _recentMaxPackets(0), - _resetRecentMaxPacketsSoon(true), _logger(new FileLogger(this)) { // read the ApplicationInfo.ini file for Name/Version/Domain information @@ -594,6 +590,8 @@ void Application::resizeGL(int width, int height) { updateProjectionMatrix(); glLoadIdentity(); + + Stats::getInstance()->resetWidthOnResizeGL(width); } void Application::updateProjectionMatrix() { @@ -1053,8 +1051,12 @@ void Application::mouseReleaseEvent(QMouseEvent* event) { _mousePressed = false; checkBandwidthMeterClick(); if (Menu::getInstance()->isOptionChecked(MenuOption::Stats)) { - checkStatsClick(); - } + int horizontalOffset = 0; + if (Menu::getInstance()->isOptionChecked(MenuOption::Mirror)) { + horizontalOffset = MIRROR_VIEW_WIDTH; + } + Stats::getInstance()->checkClick(_mouseX, _mouseY, _mouseDragStartedX, _mouseDragStartedY, horizontalOffset); + } } } } @@ -2486,11 +2488,17 @@ void Application::displayOverlay() { glPointSize(1.0f); if (Menu::getInstance()->isOptionChecked(MenuOption::Stats)) { + int horizontalOffset = 0; + if (Menu::getInstance()->isOptionChecked(MenuOption::Mirror)) { + // mirror is enabled, let's set horizontal offset to give stats some margin + horizontalOffset += MIRROR_VIEW_WIDTH + MIRROR_VIEW_LEFT_PADDING * 2; + } + int voxelPacketsToProcess = _voxelProcessor.packetsToProcessCount(); // Onscreen text about position, servers, etc - displayStats(); + Stats::getInstance()->display(WHITE_TEXT, horizontalOffset, _fps, _packetsPerSecond, _bytesPerSecond, voxelPacketsToProcess); // Bandwidth meter if (Menu::getInstance()->isOptionChecked(MenuOption::Bandwidth)) { - displayStatsBackground(0x33333399, _glWidget->width() - 296, _glWidget->height() - 68, 296, 68); + Stats::drawBackground(0x33333399, _glWidget->width() - 296, _glWidget->height() - 68, 296, 68); _bandwidthMeter.render(_glWidget->width(), _glWidget->height()); } } @@ -2512,404 +2520,6 @@ void Application::displayOverlay() { glPopMatrix(); } -// translucent background box that makes stats more readable -void Application::displayStatsBackground(unsigned int rgba, int x, int y, int width, int height) { - glBegin(GL_QUADS); - glColor4f(((rgba >> 24) & 0xff) / 255.0f, - ((rgba >> 16) & 0xff) / 255.0f, - ((rgba >> 8) & 0xff) / 255.0f, - (rgba & 0xff) / 255.0f); - glVertex3f(x, y, 0); - glVertex3f(x + width, y, 0); - glVertex3f(x + width, y + height, 0); - glVertex3f(x , y + height, 0); - glEnd(); - glColor4f(1, 1, 1, 1); -} - -// display expanded or contracted stats - -void Application::displayStats() { - unsigned int backgroundColor = 0x33333399; - int verticalOffset = 0, horizontalOffset = 0, lines = 0; - bool mirrorEnabled = Menu::getInstance()->isOptionChecked(MenuOption::Mirror); - - QLocale locale(QLocale::English); - std::stringstream voxelStats; - - glPointSize(1.0f); - - // we need to take one avatar out so we don't include ourselves - int totalAvatars = _avatarManager.size() - 1; - int totalServers = NodeList::getInstance()->size(); - - if (mirrorEnabled) { - horizontalOffset += MIRROR_VIEW_WIDTH + MIRROR_VIEW_LEFT_PADDING * 2; - } - - lines = _statsExpanded ? 5 : 3; - displayStatsBackground(backgroundColor, horizontalOffset, 0, 165, lines * STATS_PELS_PER_LINE + 10); - horizontalOffset += 5; - - char serverNodes[30]; - sprintf(serverNodes, "Servers: %d", totalServers); - char avatarNodes[30]; - sprintf(avatarNodes, "Avatars: %d", totalAvatars); - char framesPerSecond[30]; - sprintf(framesPerSecond, "Framerate: %3.0f FPS", _fps); - - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, serverNodes, WHITE_TEXT); - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarNodes, WHITE_TEXT); - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, framesPerSecond, WHITE_TEXT); - - if (_statsExpanded) { - char packetsPerSecond[30]; - sprintf(packetsPerSecond, "Pkts/sec: %d", _packetsPerSecond); - char averageMegabitsPerSecond[30]; - sprintf(averageMegabitsPerSecond, "Mbps: %3.2f", (float)_bytesPerSecond * 8.f / 1000000.f); - - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, packetsPerSecond, WHITE_TEXT); - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, averageMegabitsPerSecond, WHITE_TEXT); - } - - verticalOffset = 0; - horizontalOffset += 161; - - if (Menu::getInstance()->isOptionChecked(MenuOption::TestPing)) { - int pingAudio = 0, pingAvatar = 0, pingVoxel = 0, pingVoxelMax = 0; - - NodeList* nodeList = NodeList::getInstance(); - SharedNodePointer audioMixerNode = nodeList->soloNodeOfType(NodeType::AudioMixer); - SharedNodePointer avatarMixerNode = nodeList->soloNodeOfType(NodeType::AvatarMixer); - - pingAudio = audioMixerNode ? audioMixerNode->getPingMs() : 0; - pingAvatar = avatarMixerNode ? avatarMixerNode->getPingMs() : 0; - - // Now handle voxel servers, since there could be more than one, we average their ping times - unsigned long totalPingVoxel = 0; - int voxelServerCount = 0; - - foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { - if (node->getType() == NodeType::VoxelServer) { - totalPingVoxel += node->getPingMs(); - voxelServerCount++; - if (pingVoxelMax < node->getPingMs()) { - pingVoxelMax = node->getPingMs(); - } - } - } - - if (voxelServerCount) { - pingVoxel = totalPingVoxel/voxelServerCount; - } - - lines = _statsExpanded ? 4 : 3; - displayStatsBackground(backgroundColor, horizontalOffset, 0, 175, lines * STATS_PELS_PER_LINE + 10); - horizontalOffset += 5; - - char audioJitter[30]; - sprintf(audioJitter, - "Buffer msecs %.1f", - (float) (_audio.getNetworkBufferLengthSamplesPerChannel() + (float) _audio.getJitterBufferSamples()) / - (float)_audio.getNetworkSampleRate() * 1000.f); - drawText(30, _glWidget->height() - 22, 0.10f, 0.f, 2.f, audioJitter, WHITE_TEXT); - - - char audioPing[30]; - sprintf(audioPing, "Audio ping: %d", pingAudio); - - - char avatarPing[30]; - sprintf(avatarPing, "Avatar ping: %d", pingAvatar); - char voxelAvgPing[30]; - sprintf(voxelAvgPing, "Voxel avg ping: %d", pingVoxel); - - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, audioPing, WHITE_TEXT); - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarPing, WHITE_TEXT); - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, voxelAvgPing, WHITE_TEXT); - - if (_statsExpanded) { - char voxelMaxPing[30]; - sprintf(voxelMaxPing, "Voxel max ping: %d", pingVoxelMax); - - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, voxelMaxPing, WHITE_TEXT); - } - - verticalOffset = 0; - horizontalOffset += 171; - } - - glm::vec3 avatarPos = _myAvatar->getPosition(); - - lines = _statsExpanded ? 4 : 3; - displayStatsBackground(backgroundColor, horizontalOffset, 0, _glWidget->width() - (mirrorEnabled ? 301 : 411) - horizontalOffset, lines * STATS_PELS_PER_LINE + 10); - horizontalOffset += 5; - - char avatarPosition[200]; - if (mirrorEnabled) { - // shorthand formatting - sprintf(avatarPosition, "Pos: %.0f,%.0f,%.0f", avatarPos.x, avatarPos.y, avatarPos.z); - } else { - // longhand way - sprintf(avatarPosition, "Position: %.1f, %.1f, %.1f", avatarPos.x, avatarPos.y, avatarPos.z); - } - char avatarVelocity[30]; - sprintf(avatarVelocity, "Velocity: %.1f", glm::length(_myAvatar->getVelocity())); - char avatarBodyYaw[30]; - sprintf(avatarBodyYaw, "Yaw: %.1f", _myAvatar->getBodyYaw()); - char avatarMixerStats[200]; - - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarPosition, WHITE_TEXT); - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarVelocity, WHITE_TEXT); - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarBodyYaw, WHITE_TEXT); - - if (_statsExpanded) { - SharedNodePointer avatarMixer = NodeList::getInstance()->soloNodeOfType(NodeType::AvatarMixer); - if (avatarMixer) { - sprintf(avatarMixerStats, "Avatar Mixer: %.f kbps, %.f pps", - roundf(avatarMixer->getAverageKilobitsPerSecond()), - roundf(avatarMixer->getAveragePacketsPerSecond())); - } else { - sprintf(avatarMixerStats, "No Avatar Mixer"); - } - - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarMixerStats, WHITE_TEXT); - } - - verticalOffset = 0; - horizontalOffset = _glWidget->width() - (mirrorEnabled ? 300 : 410); - - lines = _statsExpanded ? 11 : 3; - displayStatsBackground(backgroundColor, horizontalOffset, 0, _glWidget->width() - horizontalOffset, lines * STATS_PELS_PER_LINE + 10); - horizontalOffset += 5; - - if (_statsExpanded) { - // Local Voxel Memory Usage - voxelStats.str(""); - voxelStats << "Voxels Memory Nodes: " << VoxelTreeElement::getTotalMemoryUsage() / 1000000.f << "MB"; - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), WHITE_TEXT); - - voxelStats.str(""); - voxelStats << - "Geometry RAM: " << _voxels.getVoxelMemoryUsageRAM() / 1000000.f << "MB / " << - "VBO: " << _voxels.getVoxelMemoryUsageVBO() / 1000000.f << "MB"; - if (_voxels.hasVoxelMemoryUsageGPU()) { - voxelStats << " / GPU: " << _voxels.getVoxelMemoryUsageGPU() / 1000000.f << "MB"; - } - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), WHITE_TEXT); - - // Voxel Rendering - voxelStats.str(""); - voxelStats.precision(4); - voxelStats << "Voxel Rendering Slots Max: " << _voxels.getMaxVoxels() / 1000.f << "K"; - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), WHITE_TEXT); - } - - voxelStats.str(""); - voxelStats.precision(4); - voxelStats << "Drawn: " << _voxels.getVoxelsWritten() / 1000.f << "K " << - "Abandoned: " << _voxels.getAbandonedVoxels() / 1000.f << "K "; - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), WHITE_TEXT); - - // iterate all the current voxel stats, and list their sending modes, and total voxel counts - std::stringstream sendingMode(""); - sendingMode << "Octree Sending Mode: ["; - int serverCount = 0; - int movingServerCount = 0; - unsigned long totalNodes = 0; - unsigned long totalInternal = 0; - unsigned long totalLeaves = 0; - for(NodeToOctreeSceneStatsIterator i = _octreeServerSceneStats.begin(); i != _octreeServerSceneStats.end(); i++) { - //const QUuid& uuid = i->first; - OctreeSceneStats& stats = i->second; - serverCount++; - if (_statsExpanded) { - if (serverCount > 1) { - sendingMode << ","; - } - if (stats.isMoving()) { - sendingMode << "M"; - movingServerCount++; - } else { - sendingMode << "S"; - } - } - - // calculate server node totals - totalNodes += stats.getTotalElements(); - if (_statsExpanded) { - totalInternal += stats.getTotalInternal(); - totalLeaves += stats.getTotalLeaves(); - } - } - if (_statsExpanded) { - if (serverCount == 0) { - sendingMode << "---"; - } - sendingMode << "] " << serverCount << " servers"; - if (movingServerCount > 0) { - sendingMode << " "; - } else { - sendingMode << " "; - } - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)sendingMode.str().c_str(), WHITE_TEXT); - } - - // Incoming packets - int voxelPacketsToProcess = _voxelProcessor.packetsToProcessCount(); - if (_statsExpanded) { - voxelStats.str(""); - QString packetsString = locale.toString((int)voxelPacketsToProcess); - QString maxString = locale.toString((int)_recentMaxPackets); - voxelStats << "Voxel Packets to Process: " << qPrintable(packetsString) - << " [Recent Max: " << qPrintable(maxString) << "]"; - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), WHITE_TEXT); - } - - if (_resetRecentMaxPacketsSoon && voxelPacketsToProcess > 0) { - _recentMaxPackets = 0; - _resetRecentMaxPacketsSoon = false; - } - if (voxelPacketsToProcess == 0) { - _resetRecentMaxPacketsSoon = true; - } else { - if (voxelPacketsToProcess > _recentMaxPackets) { - _recentMaxPackets = voxelPacketsToProcess; - } - } - - verticalOffset += (_statsExpanded ? STATS_PELS_PER_LINE : 0); - - QString serversTotalString = locale.toString((uint)totalNodes); // consider adding: .rightJustified(10, ' '); - - // Server Voxels - voxelStats.str(""); - voxelStats << "Server voxels: " << qPrintable(serversTotalString); - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), WHITE_TEXT); - - if (_statsExpanded) { - QString serversInternalString = locale.toString((uint)totalInternal); - QString serversLeavesString = locale.toString((uint)totalLeaves); - - voxelStats.str(""); - voxelStats << - "Internal: " << qPrintable(serversInternalString) << " " << - "Leaves: " << qPrintable(serversLeavesString) << ""; - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), WHITE_TEXT); - } - - unsigned long localTotal = VoxelTreeElement::getNodeCount(); - QString localTotalString = locale.toString((uint)localTotal); // consider adding: .rightJustified(10, ' '); - - // Local Voxels - voxelStats.str(""); - voxelStats << "Local voxels: " << qPrintable(localTotalString); - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), WHITE_TEXT); - - if (_statsExpanded) { - unsigned long localInternal = VoxelTreeElement::getInternalNodeCount(); - unsigned long localLeaves = VoxelTreeElement::getLeafNodeCount(); - QString localInternalString = locale.toString((uint)localInternal); - QString localLeavesString = locale.toString((uint)localLeaves); - - voxelStats.str(""); - voxelStats << - "Internal: " << qPrintable(localInternalString) << " " << - "Leaves: " << qPrintable(localLeavesString) << ""; - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0, 2, (char*)voxelStats.str().c_str(), WHITE_TEXT); - } - - // LOD Details - if (_statsExpanded) { - voxelStats.str(""); - QString displayLODDetails = Menu::getInstance()->getLODFeedbackText(); - voxelStats << "LOD: You can see " << qPrintable(displayLODDetails.trimmed()); - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), WHITE_TEXT); - } -} - -// called on mouse click release -// check for clicks over stats in order to expand or contract them -void Application::checkStatsClick() { - if (0 != glm::compMax(glm::abs(glm::ivec2(_mouseX - _mouseDragStartedX, _mouseY - _mouseDragStartedY)))) { - // not worried about dragging on stats - return; - } - - int statsHeight = 0, statsWidth = 0, statsX = 0, statsY = 0, lines = 0; - - if (Menu::getInstance()->isOptionChecked(MenuOption::Mirror)) { - statsX += MIRROR_VIEW_WIDTH; - } - - // top-left stats click - lines = _statsExpanded ? 5 : 3; - statsHeight = lines * STATS_PELS_PER_LINE + 10; - statsWidth = 165; - if (_mouseX > statsX && _mouseX < statsX + statsWidth && _mouseY > statsY && _mouseY < statsY + statsHeight) { - toggleStatsExpanded(); - return; - } - - // ping stats click - lines = _statsExpanded ? 4 : 3; - statsX += statsWidth; - statsHeight = lines * STATS_PELS_PER_LINE + 10; - statsWidth = 175; - if (_mouseX > statsX && _mouseX < statsX + statsWidth && _mouseY > statsY && _mouseY < statsY + statsHeight) { - toggleStatsExpanded(); - return; - } - - // top-center stats panel click - lines = _statsExpanded ? 4 : 3; - statsX += statsWidth; - statsHeight = lines * STATS_PELS_PER_LINE + 10; - statsWidth = _glWidget->width() - 411 - statsX; - if (_mouseX > statsX && _mouseX < statsX + statsWidth && _mouseY > statsY && _mouseY < statsY + statsHeight) { - toggleStatsExpanded(); - return; - } - - // top-right stats click - lines = _statsExpanded ? 11 : 3; - statsX = _glWidget->width() - 410; - statsHeight = lines * STATS_PELS_PER_LINE + 10; - statsWidth = _glWidget->width() - statsX; - if (_mouseX > statsX && _mouseX < statsX + statsWidth && _mouseY > statsY && _mouseY < statsY + statsHeight) { - toggleStatsExpanded(); - return; - } -} - -void Application::toggleStatsExpanded() { - _statsExpanded = !_statsExpanded; -} - glm::vec2 Application::getScaledScreenPoint(glm::vec2 projectedPoint) { float horizontalScale = _glWidget->width() / 2.0f; float verticalScale = _glWidget->height() / 2.0f; diff --git a/interface/src/Application.h b/interface/src/Application.h index 28060113a9..8e65a660b8 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -321,10 +321,6 @@ private: void updateShadowMap(); void displayOverlay(); - void displayStatsBackground(unsigned int rgba, int x, int y, int width, int height); - void displayStats(); - void checkStatsClick(); - void toggleStatsExpanded(); void renderRearViewMirror(const QRect& region, bool billboard = false); void renderViewFrustum(ViewFrustum& viewFrustum); @@ -345,7 +341,6 @@ private: QMainWindow* _window; GLCanvas* _glWidget; // our GLCanvas has a couple extra features - bool _statsExpanded; BandwidthMeter _bandwidthMeter; QThread* _nodeThread; @@ -456,9 +451,6 @@ private: int _packetsPerSecond; int _bytesPerSecond; - int _recentMaxPackets; // recent max incoming voxel packets to process - bool _resetRecentMaxPacketsSoon; - StDev _idleLoopStdev; float _idleLoopMeasuredJitter; diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp new file mode 100644 index 0000000000..9f87371c4c --- /dev/null +++ b/interface/src/ui/Stats.cpp @@ -0,0 +1,468 @@ +// +// Stats.cpp +// interface +// +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved +// + +#include + +#include + +#include +#include +#include +#include + +#include "Stats.h" +#include "InterfaceConfig.h" +#include "Menu.h" +#include "Util.h" + +const int STATS_PELS_PER_LINE = 20; + +const int STATS_GENERAL_MIN_WIDTH = 165; +const int STATS_PING_MIN_WIDTH = 190; +const int STATS_GEO_MIN_WIDTH = 240; +const int STATS_VOXEL_MIN_WIDTH = 410; + +Stats* Stats::getInstance() { + static Stats stats; + return &stats; +} + +Stats::Stats(): + _expanded(false), + _recentMaxPackets(0), + _resetRecentMaxPacketsSoon(true), + _generalStatsWidth(STATS_GENERAL_MIN_WIDTH), + _pingStatsWidth(STATS_PING_MIN_WIDTH), + _geoStatsWidth(STATS_GEO_MIN_WIDTH), + _voxelStatsWidth(STATS_VOXEL_MIN_WIDTH) +{ + // no constructor behavior yet, only members initialization +} + +void Stats::toggleExpanded() { + _expanded = !_expanded; +} + +// called on mouse click release +// check for clicks over stats in order to expand or contract them +void Stats::checkClick(int mouseX, int mouseY, int mouseDragStartedX, int mouseDragStartedY, int horizontalOffset) { + QGLWidget* glWidget = Application::getInstance()->getGLWidget(); + + if (0 != glm::compMax(glm::abs(glm::ivec2(mouseX - mouseDragStartedX, mouseY - mouseDragStartedY)))) { + // not worried about dragging on stats + return; + } + + int statsHeight = 0, + statsWidth = 0, + statsX = 0, + statsY = 0, + lines = 0; + + statsX = horizontalOffset; + + // top-left stats click + lines = _expanded ? 5 : 3; + statsHeight = lines * STATS_PELS_PER_LINE + 10; + if (mouseX > statsX && mouseX < statsX + _generalStatsWidth && mouseY > statsY && mouseY < statsY + statsHeight) { + toggleExpanded(); + return; + } + statsX += _generalStatsWidth; + + // ping stats click + lines = _expanded ? 4 : 3; + statsHeight = lines * STATS_PELS_PER_LINE + 10; + if (mouseX > statsX && mouseX < statsX + _pingStatsWidth && mouseY > statsY && mouseY < statsY + statsHeight) { + toggleExpanded(); + return; + } + statsX += _pingStatsWidth; + + // top-center stats panel click + lines = _expanded ? 4 : 3; + statsHeight = lines * STATS_PELS_PER_LINE + 10; + if (mouseX > statsX && mouseX < statsX + _geoStatsWidth && mouseY > statsY && mouseY < statsY + statsHeight) { + toggleExpanded(); + return; + } + statsX += _geoStatsWidth; + + // top-right stats click + lines = _expanded ? 11 : 3; + statsHeight = lines * STATS_PELS_PER_LINE + 10; + statsWidth = glWidget->width() - statsX; + if (mouseX > statsX && mouseX < statsX + statsWidth && mouseY > statsY && mouseY < statsY + statsHeight) { + toggleExpanded(); + return; + } +} + +void Stats::resetWidthOnResizeGL(int width) { + QGLWidget* glWidget = Application::getInstance()->getGLWidget(); + int extraSpace = glWidget->width() + - STATS_GENERAL_MIN_WIDTH + - STATS_PING_MIN_WIDTH + - STATS_GEO_MIN_WIDTH + - STATS_VOXEL_MIN_WIDTH + - 3; + + _generalStatsWidth = STATS_GENERAL_MIN_WIDTH; + _pingStatsWidth = STATS_PING_MIN_WIDTH; + _geoStatsWidth = STATS_GEO_MIN_WIDTH; + _voxelStatsWidth = STATS_VOXEL_MIN_WIDTH; + + if (extraSpace > 4) { + _generalStatsWidth += (int) extraSpace / 4; + _pingStatsWidth += (int) extraSpace / 4; + _geoStatsWidth += (int) extraSpace / 4; + _voxelStatsWidth += glWidget->width() - (_generalStatsWidth + _pingStatsWidth + _geoStatsWidth + 3); + } +} + + +// translucent background box that makes stats more readable +void Stats::drawBackground(unsigned int rgba, int x, int y, int width, int height) { + glBegin(GL_QUADS); + glColor4f(((rgba >> 24) & 0xff) / 255.0f, + ((rgba >> 16) & 0xff) / 255.0f, + ((rgba >> 8) & 0xff) / 255.0f, + (rgba & 0xff) / 255.0f); + glVertex3f(x, y, 0); + glVertex3f(x + width, y, 0); + glVertex3f(x + width, y + height, 0); + glVertex3f(x , y + height, 0); + glEnd(); + glColor4f(1, 1, 1, 1); +} + +// display expanded or contracted stats +void Stats::display( + const float* color, + int horizontalOffset, + float fps, + int packetsPerSecond, + int bytesPerSecond, + int voxelPacketsToProcess) +{ + QGLWidget* glWidget = Application::getInstance()->getGLWidget(); + + unsigned int backgroundColor = 0x33333399; + int verticalOffset = 0, lines = 0; + + QLocale locale(QLocale::English); + std::stringstream voxelStats; + + glPointSize(1.0f); + + // we need to take one avatar out so we don't include ourselves + int totalAvatars = Application::getInstance()->getAvatarManager().size() - 1; + int totalServers = NodeList::getInstance()->size(); + + lines = _expanded ? 5 : 3; + drawBackground(backgroundColor, horizontalOffset, 0, _generalStatsWidth, lines * STATS_PELS_PER_LINE + 10); + horizontalOffset += 5; + + char serverNodes[30]; + sprintf(serverNodes, "Servers: %d", totalServers); + char avatarNodes[30]; + sprintf(avatarNodes, "Avatars: %d", totalAvatars); + char framesPerSecond[30]; + sprintf(framesPerSecond, "Framerate: %3.0f FPS", fps); + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, serverNodes, color); + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarNodes, color); + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, framesPerSecond, color); + + if (_expanded) { + char packetsPerSecondString[30]; + sprintf(packetsPerSecondString, "Pkts/sec: %d", packetsPerSecond); + char averageMegabitsPerSecond[30]; + sprintf(averageMegabitsPerSecond, "Mbps: %3.2f", (float)bytesPerSecond * 8.f / 1000000.f); + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, packetsPerSecondString, color); + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, averageMegabitsPerSecond, color); + } + + verticalOffset = 0; + horizontalOffset = _generalStatsWidth +1; + + if (Menu::getInstance()->isOptionChecked(MenuOption::TestPing)) { + int pingAudio = 0, pingAvatar = 0, pingVoxel = 0, pingVoxelMax = 0; + + NodeList* nodeList = NodeList::getInstance(); + SharedNodePointer audioMixerNode = nodeList->soloNodeOfType(NodeType::AudioMixer); + SharedNodePointer avatarMixerNode = nodeList->soloNodeOfType(NodeType::AvatarMixer); + + pingAudio = audioMixerNode ? audioMixerNode->getPingMs() : 0; + pingAvatar = avatarMixerNode ? avatarMixerNode->getPingMs() : 0; + + // Now handle voxel servers, since there could be more than one, we average their ping times + unsigned long totalPingVoxel = 0; + int voxelServerCount = 0; + + foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { + if (node->getType() == NodeType::VoxelServer) { + totalPingVoxel += node->getPingMs(); + voxelServerCount++; + if (pingVoxelMax < node->getPingMs()) { + pingVoxelMax = node->getPingMs(); + } + } + } + + if (voxelServerCount) { + pingVoxel = totalPingVoxel/voxelServerCount; + } + + lines = _expanded ? 4 : 3; + drawBackground(backgroundColor, horizontalOffset, 0, _pingStatsWidth, lines * STATS_PELS_PER_LINE + 10); + horizontalOffset += 5; + + Audio* audio = Application::getInstance()->getAudio(); + + char audioJitter[30]; + sprintf(audioJitter, + "Buffer msecs %.1f", + (float) (audio->getNetworkBufferLengthSamplesPerChannel() + (float) audio->getJitterBufferSamples()) / + (float) audio->getNetworkSampleRate() * 1000.f); + drawText(30, glWidget->height() - 22, 0.10f, 0.f, 2.f, audioJitter, color); + + + char audioPing[30]; + sprintf(audioPing, "Audio ping: %d", pingAudio); + + + char avatarPing[30]; + sprintf(avatarPing, "Avatar ping: %d", pingAvatar); + char voxelAvgPing[30]; + sprintf(voxelAvgPing, "Voxel avg ping: %d", pingVoxel); + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, audioPing, color); + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarPing, color); + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, voxelAvgPing, color); + + if (_expanded) { + char voxelMaxPing[30]; + sprintf(voxelMaxPing, "Voxel max ping: %d", pingVoxelMax); + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, voxelMaxPing, color); + } + + verticalOffset = 0; + horizontalOffset = _generalStatsWidth + _pingStatsWidth + 2; + } + + MyAvatar* myAvatar = Application::getInstance()->getAvatar(); + glm::vec3 avatarPos = myAvatar->getPosition(); + + lines = _expanded ? 4 : 3; + drawBackground(backgroundColor, horizontalOffset, 0, _geoStatsWidth, lines * STATS_PELS_PER_LINE + 10); + horizontalOffset += 5; + + char avatarPosition[200]; + sprintf(avatarPosition, "Position: %.1f, %.1f, %.1f", avatarPos.x, avatarPos.y, avatarPos.z); + char avatarVelocity[30]; + sprintf(avatarVelocity, "Velocity: %.1f", glm::length(myAvatar->getVelocity())); + char avatarBodyYaw[30]; + sprintf(avatarBodyYaw, "Yaw: %.1f", myAvatar->getBodyYaw()); + char avatarMixerStats[200]; + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarPosition, color); + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarVelocity, color); + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarBodyYaw, color); + + if (_expanded) { + SharedNodePointer avatarMixer = NodeList::getInstance()->soloNodeOfType(NodeType::AvatarMixer); + if (avatarMixer) { + sprintf(avatarMixerStats, "Avatar Mixer: %.f kbps, %.f pps", + roundf(avatarMixer->getAverageKilobitsPerSecond()), + roundf(avatarMixer->getAveragePacketsPerSecond())); + } else { + sprintf(avatarMixerStats, "No Avatar Mixer"); + } + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarMixerStats, color); + } + + verticalOffset = 0; + horizontalOffset = _generalStatsWidth + _pingStatsWidth + _geoStatsWidth + 3; + + VoxelSystem* voxels = Application::getInstance()->getVoxels(); + + lines = _expanded ? 11 : 3; + drawBackground(backgroundColor, horizontalOffset, 0, glWidget->width() - horizontalOffset, lines * STATS_PELS_PER_LINE + 10); + horizontalOffset += 5; + + if (_expanded) { + // Local Voxel Memory Usage + voxelStats.str(""); + voxelStats << "Voxels Memory Nodes: " << VoxelTreeElement::getTotalMemoryUsage() / 1000000.f << "MB"; + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + + voxelStats.str(""); + voxelStats << + "Geometry RAM: " << voxels->getVoxelMemoryUsageRAM() / 1000000.f << "MB / " << + "VBO: " << voxels->getVoxelMemoryUsageVBO() / 1000000.f << "MB"; + if (voxels->hasVoxelMemoryUsageGPU()) { + voxelStats << " / GPU: " << voxels->getVoxelMemoryUsageGPU() / 1000000.f << "MB"; + } + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + + // Voxel Rendering + voxelStats.str(""); + voxelStats.precision(4); + voxelStats << "Voxel Rendering Slots Max: " << voxels->getMaxVoxels() / 1000.f << "K"; + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + } + + voxelStats.str(""); + voxelStats.precision(4); + voxelStats << "Drawn: " << voxels->getVoxelsWritten() / 1000.f << "K " << + "Abandoned: " << voxels->getAbandonedVoxels() / 1000.f << "K "; + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + + // iterate all the current voxel stats, and list their sending modes, and total voxel counts + std::stringstream sendingMode(""); + sendingMode << "Octree Sending Mode: ["; + int serverCount = 0; + int movingServerCount = 0; + unsigned long totalNodes = 0; + unsigned long totalInternal = 0; + unsigned long totalLeaves = 0; + NodeToOctreeSceneStats* octreeServerSceneStats = Application::getInstance()->getOcteeSceneStats(); + for(NodeToOctreeSceneStatsIterator i = octreeServerSceneStats->begin(); i != octreeServerSceneStats->end(); i++) { + //const QUuid& uuid = i->first; + OctreeSceneStats& stats = i->second; + serverCount++; + if (_expanded) { + if (serverCount > 1) { + sendingMode << ","; + } + if (stats.isMoving()) { + sendingMode << "M"; + movingServerCount++; + } else { + sendingMode << "S"; + } + } + + // calculate server node totals + totalNodes += stats.getTotalElements(); + if (_expanded) { + totalInternal += stats.getTotalInternal(); + totalLeaves += stats.getTotalLeaves(); + } + } + if (_expanded) { + if (serverCount == 0) { + sendingMode << "---"; + } + sendingMode << "] " << serverCount << " servers"; + if (movingServerCount > 0) { + sendingMode << " "; + } else { + sendingMode << " "; + } + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)sendingMode.str().c_str(), color); + } + + // Incoming packets + if (_expanded) { + voxelStats.str(""); + QString packetsString = locale.toString((int)voxelPacketsToProcess); + QString maxString = locale.toString((int)_recentMaxPackets); + voxelStats << "Voxel Packets to Process: " << qPrintable(packetsString) + << " [Recent Max: " << qPrintable(maxString) << "]"; + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + } + + if (_resetRecentMaxPacketsSoon && voxelPacketsToProcess > 0) { + _recentMaxPackets = 0; + _resetRecentMaxPacketsSoon = false; + } + if (voxelPacketsToProcess == 0) { + _resetRecentMaxPacketsSoon = true; + } else { + if (voxelPacketsToProcess > _recentMaxPackets) { + _recentMaxPackets = voxelPacketsToProcess; + } + } + + verticalOffset += (_expanded ? STATS_PELS_PER_LINE : 0); + + QString serversTotalString = locale.toString((uint)totalNodes); // consider adding: .rightJustified(10, ' '); + + // Server Voxels + voxelStats.str(""); + voxelStats << "Server voxels: " << qPrintable(serversTotalString); + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + + if (_expanded) { + QString serversInternalString = locale.toString((uint)totalInternal); + QString serversLeavesString = locale.toString((uint)totalLeaves); + + voxelStats.str(""); + voxelStats << + "Internal: " << qPrintable(serversInternalString) << " " << + "Leaves: " << qPrintable(serversLeavesString) << ""; + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + } + + unsigned long localTotal = VoxelTreeElement::getNodeCount(); + QString localTotalString = locale.toString((uint)localTotal); // consider adding: .rightJustified(10, ' '); + + // Local Voxels + voxelStats.str(""); + voxelStats << "Local voxels: " << qPrintable(localTotalString); + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + + if (_expanded) { + unsigned long localInternal = VoxelTreeElement::getInternalNodeCount(); + unsigned long localLeaves = VoxelTreeElement::getLeafNodeCount(); + QString localInternalString = locale.toString((uint)localInternal); + QString localLeavesString = locale.toString((uint)localLeaves); + + voxelStats.str(""); + voxelStats << + "Internal: " << qPrintable(localInternalString) << " " << + "Leaves: " << qPrintable(localLeavesString) << ""; + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0, 2, (char*)voxelStats.str().c_str(), color); + } + + // LOD Details + if (_expanded) { + voxelStats.str(""); + QString displayLODDetails = Menu::getInstance()->getLODFeedbackText(); + voxelStats << "LOD: You can see " << qPrintable(displayLODDetails.trimmed()); + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + } +} diff --git a/interface/src/ui/Stats.h b/interface/src/ui/Stats.h new file mode 100644 index 0000000000..aeb981a0c6 --- /dev/null +++ b/interface/src/ui/Stats.h @@ -0,0 +1,40 @@ +// +// Stats.h +// interface +// +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// + +#include + +#include + +//#include "Menu.h" + +class Stats: public QObject { + Q_OBJECT + +public: + static Stats* getInstance(); + + Stats(); + + static void drawBackground(unsigned int rgba, int x, int y, int width, int height); + + void toggleExpanded(); + void checkClick(int mouseX, int mouseY, int mouseDragStartedX, int mouseDragStartedY, int horizontalOffset); + void resetWidthOnResizeGL(int width); + void display(const float* color, int horizontalOffset, float fps, int packetsPerSecond, int bytesPerSecond, int voxelPacketsToProcess); +private: + static Stats* _sharedInstance; + + bool _expanded; + + int _recentMaxPackets; // recent max incoming voxel packets to process + bool _resetRecentMaxPacketsSoon; + + int _generalStatsWidth; + int _pingStatsWidth; + int _geoStatsWidth; + int _voxelStatsWidth; +}; \ No newline at end of file From 9077a05f9d76881ea5c5776f4404d4f48337ad6d Mon Sep 17 00:00:00 2001 From: stojce Date: Fri, 21 Mar 2014 22:34:10 +0100 Subject: [PATCH 014/595] - Layout fix - Model browsers - merge --- assignment-client/src/audio/AudioMixer.cpp | 64 +- assignment-client/src/audio/AudioMixer.h | 9 +- .../src/audio/AudioMixerClientData.cpp | 22 +- .../src/audio/AudioMixerClientData.h | 5 +- .../src/octree/OctreeQueryNode.cpp | 66 +- .../src/octree/OctreeQueryNode.h | 5 + .../src/octree/OctreeSendThread.cpp | 25 +- assignment-client/src/octree/OctreeServer.cpp | 16 +- examples/editVoxels.js | 250 +- examples/inspect.js | 240 ++ interface/interface_en.ts | 98 +- interface/resources/resources.qrc | 7 +- interface/resources/styles/global.qss | 21 +- interface/src/Application.cpp | 100 +- interface/src/Application.h | 5 + interface/src/Environment.cpp | 16 +- interface/src/GLCanvas.cpp | 4 + interface/src/GLCanvas.h | 2 + interface/src/Menu.cpp | 11 +- interface/src/Menu.h | 3 +- interface/src/ModelBrowser.cpp | 150 ++ interface/src/ModelBrowser.h | 62 + interface/src/avatar/MyAvatar.cpp | 5 +- interface/src/avatar/MyAvatar.h | 2 + interface/src/renderer/TextureCache.cpp | 2 +- interface/src/ui/FramelessDialog.cpp | 40 +- interface/src/ui/FramelessDialog.h | 11 +- interface/src/ui/PreferencesDialog.cpp | 50 +- interface/src/ui/PreferencesDialog.h | 12 +- interface/ui/preferencesDialog.ui | 2366 +++++++++-------- libraries/audio/src/AudioRingBuffer.cpp | 19 +- libraries/audio/src/AudioRingBuffer.h | 5 +- .../audio/src/PositionalAudioRingBuffer.cpp | 1 + libraries/avatars/src/AvatarData.cpp | 26 + libraries/shared/src/FileDownloader.cpp | 65 + libraries/shared/src/FileDownloader.h | 44 + libraries/shared/src/FstReader.cpp | 23 +- libraries/shared/src/FstReader.h | 1 + libraries/shared/src/PacketHeaders.cpp | 4 +- libraries/voxels/src/EnvironmentData.cpp | 15 + libraries/voxels/src/EnvironmentData.h | 8 + 41 files changed, 2347 insertions(+), 1533 deletions(-) create mode 100644 examples/inspect.js create mode 100644 interface/src/ModelBrowser.cpp create mode 100644 interface/src/ModelBrowser.h create mode 100644 libraries/shared/src/FileDownloader.cpp create mode 100644 libraries/shared/src/FileDownloader.h diff --git a/assignment-client/src/audio/AudioMixer.cpp b/assignment-client/src/audio/AudioMixer.cpp index 988bcc1da7..e86ecda36e 100644 --- a/assignment-client/src/audio/AudioMixer.cpp +++ b/assignment-client/src/audio/AudioMixer.cpp @@ -62,7 +62,12 @@ void attachNewBufferToNode(Node *newNode) { } AudioMixer::AudioMixer(const QByteArray& packet) : - ThreadedAssignment(packet) + ThreadedAssignment(packet), + _trailingSleepRatio(1.0f), + _minSourceLoudnessInFrame(1.0f), + _maxSourceLoudnessInFrame(0.0f), + _loudnessCutoffRatio(0.0f), + _minRequiredLoudness(0.0f) { } @@ -301,7 +306,7 @@ void AudioMixer::prepareMixForListeningNode(Node* node) { if ((*otherNode != *node || otherNodeBuffer->shouldLoopbackForNode()) && otherNodeBuffer->willBeAddedToMix() - && otherNodeClientData->getNextOutputLoudness() > 0) { + && otherNodeBuffer->getAverageLoudness() > _minRequiredLoudness) { addBufferToMixForListeningNodeWithBuffer(otherNodeBuffer, nodeRingBuffer); } } @@ -350,14 +355,65 @@ void AudioMixer::run() { char* clientMixBuffer = new char[NETWORK_BUFFER_LENGTH_BYTES_STEREO + numBytesForPacketHeaderGivenPacketType(PacketTypeMixedAudio)]; + + int usecToSleep = BUFFER_SEND_INTERVAL_USECS; while (!_isFinished) { + _minSourceLoudnessInFrame = 1.0f; + _maxSourceLoudnessInFrame = 0.0f; + foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { if (node->getLinkedData()) { - ((AudioMixerClientData*) node->getLinkedData())->checkBuffersBeforeFrameSend(JITTER_BUFFER_SAMPLES); + ((AudioMixerClientData*) node->getLinkedData())->checkBuffersBeforeFrameSend(JITTER_BUFFER_SAMPLES, + _minSourceLoudnessInFrame, + _maxSourceLoudnessInFrame); } } + + const float STRUGGLE_TRIGGER_SLEEP_PERCENTAGE_THRESHOLD = 0.10; + const float BACK_OFF_TRIGGER_SLEEP_PERCENTAGE_THRESHOLD = 0.30; + const float CUTOFF_EPSILON = 0.0001; + + const int TRAILING_AVERAGE_FRAMES = 100; + const float CURRENT_FRAME_RATIO = 1.0f / TRAILING_AVERAGE_FRAMES; + const float PREVIOUS_FRAMES_RATIO = 1 - CURRENT_FRAME_RATIO; + + if (usecToSleep < 0) { + usecToSleep = 0; + } + + _trailingSleepRatio = (PREVIOUS_FRAMES_RATIO * _trailingSleepRatio) + + (usecToSleep * CURRENT_FRAME_RATIO / (float) BUFFER_SEND_INTERVAL_USECS); + + float lastCutoffRatio = _loudnessCutoffRatio; + bool hasRatioChanged = false; + + if (_trailingSleepRatio <= STRUGGLE_TRIGGER_SLEEP_PERCENTAGE_THRESHOLD) { + // we're struggling - change our min required loudness to reduce some load + _loudnessCutoffRatio += (1 - _loudnessCutoffRatio) / 2; + + qDebug() << "Mixer is struggling, sleeping" << _trailingSleepRatio * 100 << "% of frame time. Old cutoff was" + << lastCutoffRatio << "and is now" << _loudnessCutoffRatio; + hasRatioChanged = true; + } else if (_trailingSleepRatio >= BACK_OFF_TRIGGER_SLEEP_PERCENTAGE_THRESHOLD && _loudnessCutoffRatio != 0) { + // we've recovered and can back off the required loudness + _loudnessCutoffRatio -= _loudnessCutoffRatio / 2; + + if (_loudnessCutoffRatio < CUTOFF_EPSILON) { + _loudnessCutoffRatio = 0; + } + + qDebug() << "Mixer is recovering, sleeping" << _trailingSleepRatio * 100 << "% of frame time. Old cutoff was" + << lastCutoffRatio << "and is now" << _loudnessCutoffRatio; + hasRatioChanged = true; + } + + if (hasRatioChanged) { + // set out min required loudness from the new ratio + _minRequiredLoudness = _loudnessCutoffRatio * (_maxSourceLoudnessInFrame - _minSourceLoudnessInFrame); + qDebug() << "Minimum loudness required to be mixed is now" << _minRequiredLoudness; + } foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { if (node->getType() == NodeType::Agent && node->getActiveSocket() && node->getLinkedData() @@ -384,7 +440,7 @@ void AudioMixer::run() { break; } - int usecToSleep = usecTimestamp(&startTime) + (++nextFrame * BUFFER_SEND_INTERVAL_USECS) - usecTimestampNow(); + usecToSleep = usecTimestamp(&startTime) + (++nextFrame * BUFFER_SEND_INTERVAL_USECS) - usecTimestampNow(); if (usecToSleep > 0) { usleep(usecToSleep); diff --git a/assignment-client/src/audio/AudioMixer.h b/assignment-client/src/audio/AudioMixer.h index 5a68b0023f..4ba8cdebd3 100644 --- a/assignment-client/src/audio/AudioMixer.h +++ b/assignment-client/src/audio/AudioMixer.h @@ -37,7 +37,14 @@ private: void prepareMixForListeningNode(Node* node); // client samples capacity is larger than what will be sent to optimize mixing - int16_t _clientSamples[NETWORK_BUFFER_LENGTH_SAMPLES_STEREO + SAMPLE_PHASE_DELAY_AT_90]; + // we are MMX adding 4 samples at a time so we need client samples to have an extra 4 + int16_t _clientSamples[NETWORK_BUFFER_LENGTH_SAMPLES_STEREO + (SAMPLE_PHASE_DELAY_AT_90 * 2)]; + + float _trailingSleepRatio; + float _minSourceLoudnessInFrame; + float _maxSourceLoudnessInFrame; + float _loudnessCutoffRatio; + float _minRequiredLoudness; }; #endif /* defined(__hifi__AudioMixer__) */ diff --git a/assignment-client/src/audio/AudioMixerClientData.cpp b/assignment-client/src/audio/AudioMixerClientData.cpp index b2da0a0aaa..41fd72e54e 100644 --- a/assignment-client/src/audio/AudioMixerClientData.cpp +++ b/assignment-client/src/audio/AudioMixerClientData.cpp @@ -6,6 +6,8 @@ // Copyright (c) 2013 HighFidelity, Inc. All rights reserved. // +#include + #include #include @@ -14,8 +16,7 @@ #include "AudioMixerClientData.h" AudioMixerClientData::AudioMixerClientData() : - _ringBuffers(), - _nextOutputLoudness(0) + _ringBuffers() { } @@ -82,16 +83,29 @@ int AudioMixerClientData::parseData(const QByteArray& packet) { return 0; } -void AudioMixerClientData::checkBuffersBeforeFrameSend(int jitterBufferLengthSamples) { +void AudioMixerClientData::checkBuffersBeforeFrameSend(int jitterBufferLengthSamples, + float& currentMinLoudness, + float& currentMaxLoudness) { for (unsigned int i = 0; i < _ringBuffers.size(); i++) { if (_ringBuffers[i]->shouldBeAddedToMix(jitterBufferLengthSamples)) { // this is a ring buffer that is ready to go // set its flag so we know to push its buffer when all is said and done _ringBuffers[i]->setWillBeAddedToMix(true); + // calculate the average loudness for the next NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL // that would be mixed in - _nextOutputLoudness = _ringBuffers[i]->averageLoudnessForBoundarySamples(NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL); + _ringBuffers[i]->updateAverageLoudnessForBoundarySamples(NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL); + + float ringBufferLoudness = _ringBuffers[i]->getAverageLoudness(); + + if (ringBufferLoudness != 0 && ringBufferLoudness < currentMinLoudness) { + currentMinLoudness = ringBufferLoudness; + } + + if (ringBufferLoudness > currentMaxLoudness) { + currentMaxLoudness = ringBufferLoudness; + } } } } diff --git a/assignment-client/src/audio/AudioMixerClientData.h b/assignment-client/src/audio/AudioMixerClientData.h index bb10098e23..d41563bbca 100644 --- a/assignment-client/src/audio/AudioMixerClientData.h +++ b/assignment-client/src/audio/AudioMixerClientData.h @@ -24,14 +24,11 @@ public: const std::vector getRingBuffers() const { return _ringBuffers; } AvatarAudioRingBuffer* getAvatarAudioRingBuffer() const; - float getNextOutputLoudness() const { return _nextOutputLoudness; } - int parseData(const QByteArray& packet); - void checkBuffersBeforeFrameSend(int jitterBufferLengthSamples); + void checkBuffersBeforeFrameSend(int jitterBufferLengthSamples, float& currentMinLoudness, float& currentMaxLoudness); void pushBuffersAfterFrameSend(); private: std::vector _ringBuffers; - float _nextOutputLoudness; }; #endif /* defined(__hifi__AudioMixerClientData__) */ diff --git a/assignment-client/src/octree/OctreeQueryNode.cpp b/assignment-client/src/octree/OctreeQueryNode.cpp index a1922f980d..2ceb9e1040 100644 --- a/assignment-client/src/octree/OctreeQueryNode.cpp +++ b/assignment-client/src/octree/OctreeQueryNode.cpp @@ -36,18 +36,34 @@ OctreeQueryNode::OctreeQueryNode() : _lodChanged(false), _lodInitialized(false), _sequenceNumber(0), - _lastRootTimestamp(0) + _lastRootTimestamp(0), + _myPacketType(PacketTypeUnknown), + _isShuttingDown(false) { } OctreeQueryNode::~OctreeQueryNode() { + _isShuttingDown = true; + const bool extraDebugging = false; + if (extraDebugging) { + qDebug() << "OctreeQueryNode::~OctreeQueryNode()"; + } if (_octreeSendThread) { + if (extraDebugging) { + qDebug() << "OctreeQueryNode::~OctreeQueryNode()... calling _octreeSendThread->terminate()"; + } _octreeSendThread->terminate(); + if (extraDebugging) { + qDebug() << "OctreeQueryNode::~OctreeQueryNode()... calling delete _octreeSendThread"; + } delete _octreeSendThread; } delete[] _octreePacket; delete[] _lastOctreePacket; + if (extraDebugging) { + qDebug() << "OctreeQueryNode::~OctreeQueryNode()... DONE..."; + } } @@ -59,9 +75,13 @@ void OctreeQueryNode::initializeOctreeSendThread(OctreeServer* octreeServer, con } bool OctreeQueryNode::packetIsDuplicate() const { + // if shutting down, return immediately + if (_isShuttingDown) { + return false; + } // since our packets now include header information, like sequence number, and createTime, we can't just do a memcmp // of the entire packet, we need to compare only the packet content... - int numBytesPacketHeader = numBytesForPacketHeaderGivenPacketType(getMyPacketType()); + int numBytesPacketHeader = numBytesForPacketHeaderGivenPacketType(_myPacketType); if (_lastOctreePacketLength == getPacketLength()) { if (memcmp(_lastOctreePacket + (numBytesPacketHeader + OCTREE_PACKET_EXTRA_HEADERS_SIZE), @@ -74,6 +94,11 @@ bool OctreeQueryNode::packetIsDuplicate() const { } bool OctreeQueryNode::shouldSuppressDuplicatePacket() { + // if shutting down, return immediately + if (_isShuttingDown) { + return true; + } + bool shouldSuppress = false; // assume we won't suppress // only consider duplicate packets @@ -107,7 +132,17 @@ bool OctreeQueryNode::shouldSuppressDuplicatePacket() { return shouldSuppress; } +void OctreeQueryNode::init() { + _myPacketType = getMyPacketType(); + resetOctreePacket(true); // don't bump sequence +} + void OctreeQueryNode::resetOctreePacket(bool lastWasSurpressed) { + // if shutting down, return immediately + if (_isShuttingDown) { + return; + } + // Whenever we call this, we will keep a copy of the last packet, so we can determine if the last packet has // changed since we last reset it. Since we know that no two packets can ever be identical without being the same // scene information, (e.g. the root node packet of a static scene), we can use this as a strategy for reducing @@ -128,7 +163,7 @@ void OctreeQueryNode::resetOctreePacket(bool lastWasSurpressed) { } _octreePacketAvailableBytes = MAX_PACKET_SIZE; - int numBytesPacketHeader = populatePacketHeader(reinterpret_cast(_octreePacket), getMyPacketType()); + int numBytesPacketHeader = populatePacketHeader(reinterpret_cast(_octreePacket), _myPacketType); _octreePacketAt = _octreePacket + numBytesPacketHeader; _octreePacketAvailableBytes -= numBytesPacketHeader; @@ -158,6 +193,11 @@ void OctreeQueryNode::resetOctreePacket(bool lastWasSurpressed) { } void OctreeQueryNode::writeToPacket(const unsigned char* buffer, unsigned int bytes) { + // if shutting down, return immediately + if (_isShuttingDown) { + return; + } + // compressed packets include lead bytes which contain compressed size, this allows packing of // multiple compressed portions together if (_currentPacketIsCompressed) { @@ -174,6 +214,11 @@ void OctreeQueryNode::writeToPacket(const unsigned char* buffer, unsigned int by } bool OctreeQueryNode::updateCurrentViewFrustum() { + // if shutting down, return immediately + if (_isShuttingDown) { + return false; + } + bool currentViewFrustumChanged = false; ViewFrustum newestViewFrustum; // get position and orientation details from the camera @@ -233,6 +278,11 @@ void OctreeQueryNode::setViewSent(bool viewSent) { } void OctreeQueryNode::updateLastKnownViewFrustum() { + // if shutting down, return immediately + if (_isShuttingDown) { + return; + } + bool frustumChanges = !_lastKnownViewFrustum.isVerySimilar(_currentViewFrustum); if (frustumChanges) { @@ -247,6 +297,11 @@ void OctreeQueryNode::updateLastKnownViewFrustum() { bool OctreeQueryNode::moveShouldDump() const { + // if shutting down, return immediately + if (_isShuttingDown) { + return false; + } + glm::vec3 oldPosition = _lastKnownViewFrustum.getPosition(); glm::vec3 newPosition = _currentViewFrustum.getPosition(); @@ -259,6 +314,11 @@ bool OctreeQueryNode::moveShouldDump() const { } void OctreeQueryNode::dumpOutOfView() { + // if shutting down, return immediately + if (_isShuttingDown) { + return; + } + int stillInView = 0; int outOfView = 0; OctreeElementBag tempBag; diff --git a/assignment-client/src/octree/OctreeQueryNode.h b/assignment-client/src/octree/OctreeQueryNode.h index 20fa2c5858..eab8cb5d0a 100644 --- a/assignment-client/src/octree/OctreeQueryNode.h +++ b/assignment-client/src/octree/OctreeQueryNode.h @@ -28,6 +28,7 @@ public: OctreeQueryNode(); virtual ~OctreeQueryNode(); + void init(); // called after creation to set up some virtual items virtual PacketType getMyPacketType() const = 0; void resetOctreePacket(bool lastWasSurpressed = false); // resets octree packet to after "V" header @@ -91,6 +92,7 @@ public: unsigned int getlastOctreePacketLength() const { return _lastOctreePacketLength; } int getDuplicatePacketCount() const { return _duplicatePacketCount; } + bool isShuttingDown() const { return _isShuttingDown; } private: OctreeQueryNode(const OctreeQueryNode &); @@ -127,6 +129,9 @@ private: OCTREE_PACKET_SEQUENCE _sequenceNumber; quint64 _lastRootTimestamp; + + PacketType _myPacketType; + bool _isShuttingDown; }; #endif /* defined(__hifi__OctreeQueryNode__) */ diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index caa729e340..9c04c4a1ad 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -65,7 +65,7 @@ bool OctreeSendThread::process() { nodeData = (OctreeQueryNode*) node->getLinkedData(); // Sometimes the node data has not yet been linked, in which case we can't really do anything - if (nodeData) { + if (nodeData && !nodeData->isShuttingDown()) { bool viewFrustumChanged = nodeData->updateCurrentViewFrustum(); packetDistributor(node, nodeData, viewFrustumChanged); } @@ -99,7 +99,14 @@ quint64 OctreeSendThread::_totalBytes = 0; quint64 OctreeSendThread::_totalWastedBytes = 0; quint64 OctreeSendThread::_totalPackets = 0; -int OctreeSendThread::handlePacketSend(const SharedNodePointer& node, OctreeQueryNode* nodeData, int& trueBytesSent, int& truePacketsSent) { +int OctreeSendThread::handlePacketSend(const SharedNodePointer& node, + OctreeQueryNode* nodeData, int& trueBytesSent, int& truePacketsSent) { + + // if we're shutting down, then exit early + if (nodeData->isShuttingDown()) { + return 0; + } + bool debug = _myServer->wantsDebugSending(); quint64 now = usecTimestampNow(); @@ -136,7 +143,7 @@ int OctreeSendThread::handlePacketSend(const SharedNodePointer& node, OctreeQuer // If we've got a stats message ready to send, then see if we can piggyback them together - if (nodeData->stats.isReadyToSend()) { + if (nodeData->stats.isReadyToSend() && !nodeData->isShuttingDown()) { // Send the stats message to the client unsigned char* statsMessage = nodeData->stats.getStatsMessage(); int statsMessageLength = nodeData->stats.getStatsMessageLength(); @@ -203,7 +210,7 @@ int OctreeSendThread::handlePacketSend(const SharedNodePointer& node, OctreeQuer nodeData->stats.markAsSent(); } else { // If there's actually a packet waiting, then send it. - if (nodeData->isPacketWaiting()) { + if (nodeData->isPacketWaiting() && !nodeData->isShuttingDown()) { // just send the voxel packet NodeList::getInstance()->writeDatagram((char*) nodeData->getPacket(), nodeData->getPacketLength(), SharedNodePointer(node)); @@ -234,6 +241,12 @@ int OctreeSendThread::handlePacketSend(const SharedNodePointer& node, OctreeQuer /// Version of voxel distributor that sends the deepest LOD level at once int OctreeSendThread::packetDistributor(const SharedNodePointer& node, OctreeQueryNode* nodeData, bool viewFrustumChanged) { + + // if shutting down, exit early + if (nodeData->isShuttingDown()) { + return 0; + } + int truePacketsSent = 0; int trueBytesSent = 0; int packetsSentThisInterval = 0; @@ -336,7 +349,7 @@ int OctreeSendThread::packetDistributor(const SharedNodePointer& node, OctreeQue int extraPackingAttempts = 0; bool completedScene = false; - while (somethingToSend && packetsSentThisInterval < maxPacketsPerInterval) { + while (somethingToSend && packetsSentThisInterval < maxPacketsPerInterval && !nodeData->isShuttingDown()) { float lockWaitElapsedUsec = OctreeServer::SKIP_TIME; float encodeElapsedUsec = OctreeServer::SKIP_TIME; float compressAndWriteElapsedUsec = OctreeServer::SKIP_TIME; @@ -503,7 +516,7 @@ int OctreeSendThread::packetDistributor(const SharedNodePointer& node, OctreeQue // Here's where we can/should allow the server to send other data... // send the environment packet // TODO: should we turn this into a while loop to better handle sending multiple special packets - if (_myServer->hasSpecialPacketToSend(node)) { + if (_myServer->hasSpecialPacketToSend(node) && !nodeData->isShuttingDown()) { trueBytesSent += _myServer->sendSpecialPacket(node); truePacketsSent++; packetsSentThisInterval++; diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 7e6ffe52da..496f9af1a0 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -168,7 +168,7 @@ void OctreeServer::trackPacketSendingTime(float time) { void OctreeServer::attachQueryNodeToNode(Node* newNode) { if (!newNode->getLinkedData()) { OctreeQueryNode* newQueryNodeData = _instance->createOctreeQueryNode(); - newQueryNodeData->resetOctreePacket(true); // don't bump sequence + newQueryNodeData->init(); newNode->setLinkedData(newQueryNodeData); } } @@ -784,16 +784,26 @@ void OctreeServer::readPendingDatagrams() { if (packetType == getMyQueryMessageType()) { bool debug = false; if (debug) { - qDebug() << "Got PacketTypeVoxelQuery at" << usecTimestampNow(); + if (matchingNode) { + qDebug() << "Got PacketTypeVoxelQuery at" << usecTimestampNow() << "node:" << *matchingNode; + } else { + qDebug() << "Got PacketTypeVoxelQuery at" << usecTimestampNow() << "node: ??????"; + } } // If we got a PacketType_VOXEL_QUERY, then we're talking to an NodeType_t_AVATAR, and we // need to make sure we have it in our nodeList. if (matchingNode) { + if (debug) { + qDebug() << "calling updateNodeWithDataFromPacket()... node:" << *matchingNode; + } nodeList->updateNodeWithDataFromPacket(matchingNode, receivedPacket); OctreeQueryNode* nodeData = (OctreeQueryNode*) matchingNode->getLinkedData(); if (nodeData && !nodeData->isOctreeSendThreadInitalized()) { + if (debug) { + qDebug() << "calling initializeOctreeSendThread()... node:" << *matchingNode; + } nodeData->initializeOctreeSendThread(this, matchingNode->getUUID()); } } @@ -999,6 +1009,8 @@ void OctreeServer::nodeKilled(SharedNodePointer node) { node->setLinkedData(NULL); // set this first in case another thread comes through and tryes to acces this qDebug() << qPrintable(_safeServerName) << "server deleting Linked Data for node:" << *node; nodeData->deleteLater(); + } else { + qDebug() << qPrintable(_safeServerName) << "server node missing linked data node:" << *node; } } diff --git a/examples/editVoxels.js b/examples/editVoxels.js index 31d483d798..43bc485274 100644 --- a/examples/editVoxels.js +++ b/examples/editVoxels.js @@ -20,8 +20,6 @@ var windowDimensions = Controller.getViewportDimensions(); var NEW_VOXEL_SIZE = 1.0; var NEW_VOXEL_DISTANCE_FROM_CAMERA = 3.0; -var ORBIT_RATE_ALTITUDE = 200.0; -var ORBIT_RATE_AZIMUTH = 90.0; var PIXELS_PER_EXTRUDE_VOXEL = 16; var WHEEL_PIXELS_PER_SCALE_CHANGE = 100; var MAX_VOXEL_SCALE = 1.0; @@ -37,19 +35,7 @@ var previewLineWidth = 1.5; var oldMode = Camera.getMode(); var isAdding = false; -var isExtruding = false; -var isOrbiting = false; -var isOrbitingFromTouch = false; -var isPanning = false; -var isPanningFromTouch = false; -var touchPointsToOrbit = 2; // you can change these, but be mindful that on some track pads 2 touch points = right click+drag -var touchPointsToPan = 3; -var orbitAzimuth = 0.0; -var orbitAltitude = 0.0; -var orbitCenter = { x: 0, y: 0, z: 0 }; -var orbitPosition = { x: 0, y: 0, z: 0 }; -var torsoToEyeVector = { x: 0, y: 0, z: 0 }; -var orbitRadius = 0.0; +var isExtruding = false; var extrudeDirection = { x: 0, y: 0, z: 0 }; var extrudeScale = 0.0; var lastVoxelPosition = { x: 0, y: 0, z: 0 }; @@ -444,24 +430,11 @@ function getNewVoxelPosition() { return newPosition; } -function fixEulerAngles(eulers) { - var rVal = { x: 0, y: 0, z: eulers.z }; - if (eulers.x >= 90.0) { - rVal.x = 180.0 - eulers.x; - rVal.y = eulers.y - 180.0; - } else if (eulers.x <= -90.0) { - rVal.x = 180.0 - eulers.x; - rVal.y = eulers.y - 180.0; - } - return rVal; -} - var trackLastMouseX = 0; var trackLastMouseY = 0; var trackAsDelete = false; var trackAsRecolor = false; var trackAsEyedropper = false; -var trackAsOrbitOrPan = false; var voxelToolSelected = true; var recolorToolSelected = false; @@ -761,10 +734,6 @@ function trackKeyPressEvent(event) { trackAsEyedropper = true; moveTools(); } - if (event.text == "ALT") { - trackAsOrbitOrPan = true; - moveTools(); - } showPreviewGuides(); } @@ -802,10 +771,6 @@ function trackKeyReleaseEvent(event) { trackAsEyedropper = false; moveTools(); } - if (event.text == "ALT") { - trackAsOrbitOrPan = false; - moveTools(); - } // on F1 toggle the preview mode between cubes and lines if (event.text == "F1") { @@ -816,74 +781,6 @@ function trackKeyReleaseEvent(event) { } } -function startOrbitMode(event) { - mouseX = event.x; - mouseY = event.y; - var pickRay = Camera.computePickRay(event.x, event.y); - var intersection = Voxels.findRayIntersection(pickRay); - - // start orbit camera! - var cameraPosition = Camera.getPosition(); - torsoToEyeVector = Vec3.subtract(cameraPosition, MyAvatar.position); - torsoToEyeVector.x = 0.0; - torsoToEyeVector.z = 0.0; - oldMode = Camera.getMode(); - Camera.setMode("independent"); - Camera.keepLookingAt(intersection.intersection); - // get position for initial azimuth, elevation - orbitCenter = intersection.intersection; - var orbitVector = Vec3.subtract(cameraPosition, orbitCenter); - orbitRadius = Vec3.length(orbitVector); - orbitAzimuth = Math.atan2(orbitVector.z, orbitVector.x); - orbitAltitude = Math.asin(orbitVector.y / Vec3.length(orbitVector)); - - //print("startOrbitMode..."); -} - -function handleOrbitingMove(event) { - var cameraOrientation = Camera.getOrientation(); - var origEulers = Quat.safeEulerAngles(cameraOrientation); - var newEulers = fixEulerAngles(Quat.safeEulerAngles(cameraOrientation)); - var dx = event.x - mouseX; - var dy = event.y - mouseY; - orbitAzimuth += dx / ORBIT_RATE_AZIMUTH; - orbitAltitude += dy / ORBIT_RATE_ALTITUDE; - var orbitVector = { x:(Math.cos(orbitAltitude) * Math.cos(orbitAzimuth)) * orbitRadius, - y:Math.sin(orbitAltitude) * orbitRadius, - z:(Math.cos(orbitAltitude) * Math.sin(orbitAzimuth)) * orbitRadius }; - orbitPosition = Vec3.sum(orbitCenter, orbitVector); - Camera.setPosition(orbitPosition); - - mouseX = event.x; - mouseY = event.y; - //print("handleOrbitingMove..."); -} - -function endOrbitMode(event) { - var cameraOrientation = Camera.getOrientation(); - MyAvatar.position = Vec3.subtract(Camera.getPosition(), torsoToEyeVector); - MyAvatar.headOrientation = cameraOrientation; - Camera.stopLooking(); - Camera.setMode(oldMode); - Camera.setOrientation(cameraOrientation); - //print("endOrbitMode..."); -} - -function startPanMode(event, intersection) { - // start pan camera! - print("handle PAN mode!!!"); -} - -function handlePanMove(event) { - print("PANNING mode!!! "); - //print("isPanning="+isPanning + " inPanningFromTouch="+isPanningFromTouch + " trackAsOrbitOrPan="+trackAsOrbitOrPan); -} - -function endPanMode(event) { - print("ending PAN mode!!!"); -} - - function mousePressEvent(event) { // if our tools are off, then don't do anything @@ -891,31 +788,6 @@ function mousePressEvent(event) { return; } - // Normally, if we're panning or orbiting from touch, ignore these... because our touch takes precedence. - // but In the case of a button="RIGHT" click, we may get some touch messages first, and we actually want to - // cancel any touch mode, and then let the right-click through - if (isOrbitingFromTouch || isPanningFromTouch) { - - // if the user is holding the ALT key AND they are clicking the RIGHT button (or on multi-touch doing a two - // finger touch, then we want to let the new panning behavior take over. - // if it's any other case we still want to bail - if (event.button == "RIGHT" && trackAsOrbitOrPan) { - // cancel our current multitouch operation... - if (isOrbitingFromTouch) { - endOrbitMode(event); - isOrbitingFromTouch = false; - } - if (isPanningFromTouch) { - //print("mousePressEvent... calling endPanMode()"); - endPanMode(event); - isPanningFromTouch = false; - } - // let things fall through - } else { - return; - } - } - // no clicking on overlays while in panning mode if (!trackAsOrbitOrPan) { var clickedOnSomething = false; @@ -1008,17 +880,7 @@ function mousePressEvent(event) { calcThumbFromScale(intersection.voxel.s); } - // Note: touch and mouse events can cross paths, so we want to ignore any mouse events that would - // start a pan or orbit if we're already doing a pan or orbit via touch... - if ((event.isAlt || trackAsOrbitOrPan) && !(isOrbitingFromTouch || isPanningFromTouch)) { - if (event.isLeftButton && !event.isRightButton) { - startOrbitMode(event); - isOrbiting = true; - } else if (event.isRightButton && !event.isLeftButton) { - startPanMode(event); - isPanning = true; - } - } else if (trackAsDelete || event.isRightButton && !trackAsEyedropper) { + if (trackAsDelete || event.isRightButton && !trackAsEyedropper) { // Delete voxel voxelDetails = calculateVoxelFromIntersection(intersection,"delete"); Voxels.eraseVoxel(voxelDetails.x, voxelDetails.y, voxelDetails.z, voxelDetails.s); @@ -1209,23 +1071,7 @@ function mouseMoveEvent(event) { return; } - // if we're panning or orbiting from touch, ignore these... because our touch takes precedence. - if (isOrbitingFromTouch || isPanningFromTouch) { - return; - } - // double check that we didn't accidentally miss a pan or orbit click request - if (trackAsOrbitOrPan && !isPanning && !isOrbiting) { - if (event.isLeftButton && !event.isRightButton) { - startOrbitMode(event); - isOrbiting = true; - } - if (!event.isLeftButton && event.isRightButton) { - startPanMode(event); - isPanning = true; - } - } - if (!trackAsOrbitOrPan && isMovingSlider) { thumbX = (event.x - thumbClickOffsetX) - sliderX; if (thumbX < minThumbX) { @@ -1236,10 +1082,6 @@ function mouseMoveEvent(event) { } calcScaleFromThumb(thumbX); - } else if (isOrbiting) { - handleOrbitingMove(event); - } else if (isPanning) { - handlePanMove(event); } else if (!trackAsOrbitOrPan && isAdding) { // Watch the drag direction to tell which way to 'extrude' this voxel if (!isExtruding) { @@ -1293,16 +1135,6 @@ function mouseReleaseEvent(event) { if (isMovingSlider) { isMovingSlider = false; } - - if (isOrbiting) { - endOrbitMode(event); - isOrbiting = false; - } - if (isPanning) { - print("mouseReleaseEvent... calling endPanMode()"); - endPanMode(event); - isPanning = false; - } isAdding = false; isExtruding = false; } @@ -1396,96 +1228,18 @@ function touchBeginEvent(event) { if (!editToolsOn) { return; } - - // if we're already in the middle of orbiting or panning, then ignore these multi-touch events... - if (isOrbiting || isPanning) { - return; - } - - if (event.isAlt || trackAsOrbitOrPan) { - if (event.touchPoints == touchPointsToOrbit) { - // we need to double check that we didn't start an orbit, because the touch events will sometimes - // come in as 2 then 3 touches... - if (isPanningFromTouch) { - print("touchBeginEvent... calling endPanMode()"); - endPanMode(event); - isPanningFromTouch = false; - } - startOrbitMode(event); - isOrbitingFromTouch = true; - } else if (event.touchPoints == touchPointsToPan) { - // we need to double check that we didn't start an orbit, because the touch events will sometimes - // come in as 2 then 3 touches... - if (isOrbitingFromTouch) { - endOrbitMode(event); - isOrbitingFromTouch = false; - } - startPanMode(event); - isPanningFromTouch = true; - } - } } function touchUpdateEvent(event) { if (!editToolsOn) { return; } - - // if we're already in the middle of orbiting or panning, then ignore these multi-touch events... - if (isOrbiting || isPanning) { - return; - } - - if (isOrbitingFromTouch) { - // we need to double check that we didn't start an orbit, because the touch events will sometimes - // come in as 2 then 3 touches... - if (event.touchPoints == touchPointsToPan) { - //print("we now have touchPointsToPan touches... switch to pan..."); - endOrbitMode(event); - isOrbitingFromTouch = false; - startPanMode(event); - isPanningFromTouch = true; - } else { - handleOrbitingMove(event); - } - } - if (isPanningFromTouch) { - //print("touchUpdateEvent... isPanningFromTouch... event.touchPoints=" + event.touchPoints); - // we need to double check that we didn't start an orbit, because the touch events will sometimes - // come in as 2 then 3 touches... - if (event.touchPoints == touchPointsToOrbit) { - //print("we now have touchPointsToOrbit touches... switch to orbit..."); - //print("touchUpdateEvent... calling endPanMode()"); - endPanMode(event); - isPanningFromTouch = false; - startOrbitMode(event); - isOrbitingFromTouch = true; - handleOrbitingMove(event); - } else { - handlePanMove(event); - } - } } function touchEndEvent(event) { if (!editToolsOn) { return; } - - // if we're already in the middle of orbiting or panning, then ignore these multi-touch events... - if (isOrbiting || isPanning) { - return; - } - - if (isOrbitingFromTouch) { - endOrbitMode(event); - isOrbitingFromTouch = false; - } - if (isPanningFromTouch) { - print("touchEndEvent... calling endPanMode()"); - endPanMode(event); - isPanningFromTouch = false; - } } var lastFingerAddVoxel = { x: -1, y: -1, z: -1}; // off of the build-able area diff --git a/examples/inspect.js b/examples/inspect.js new file mode 100644 index 0000000000..9292450784 --- /dev/null +++ b/examples/inspect.js @@ -0,0 +1,240 @@ +// +// inspect.js +// hifi +// +// Created by Clément Brisset on March 20, 2014 +// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// +// Allows you to inspect non moving objects (Voxels or Avatars) using Atl, Control (Command on Mac) and Shift +// +// radial mode = hold ALT +// orbit mode = hold ALT + CONTROL +// pan mode = hold ALT + CONTROL + SHIFT +// Once you are in a mode left click on the object to inspect and hold the click +// Dragging the mouse will move your camera according to the mode you are in. +// + +var AZIMUTH_RATE = 90.0; +var ALTITUDE_RATE = 200.0; +var RADIUS_RATE = 20.0; +var PAN_RATE = 50.0; + +var alt = false; +var shift = false; +var control = false; + +var isActive = false; + +var noMode = 0; +var orbitMode = 1; +var radialMode = 2; +var panningMode = 3; + +var mode = noMode; + +var mouseLastX = 0; +var mouseLastY = 0; + + +var center = { x: 0, y: 0, z: 0 }; +var position = { x: 0, y: 0, z: 0 }; +var vector = { x: 0, y: 0, z: 0 }; +var radius = 0.0; +var azimuth = 0.0; +var altitude = 0.0; + + +function handleRadialMode(dx, dy) { + azimuth += dx / AZIMUTH_RATE; + radius += radius * dy / RADIUS_RATE; + if (radius < 1) { + radius = 1; + } + + vector = { x: (Math.cos(altitude) * Math.cos(azimuth)) * radius, + y: Math.sin(altitude) * radius, + z: (Math.cos(altitude) * Math.sin(azimuth)) * radius }; + position = Vec3.sum(center, vector); + Camera.setPosition(position); +} + +function handleOrbitMode(dx, dy) { + azimuth += dx / AZIMUTH_RATE; + altitude += dy / ALTITUDE_RATE; + + vector = { x:(Math.cos(altitude) * Math.cos(azimuth)) * radius, + y:Math.sin(altitude) * radius, + z:(Math.cos(altitude) * Math.sin(azimuth)) * radius }; + position = Vec3.sum(center, vector); + Camera.setPosition(position); +} + + +function handlePanMode(dx, dy) { + var up = Quat.getUp(Camera.getOrientation()); + var right = Quat.getRight(Camera.getOrientation()); + var distance = Vec3.length(vector); + + var dv = Vec3.sum(Vec3.multiply(up, - distance * dy / PAN_RATE), Vec3.multiply(right, distance * dx / PAN_RATE)); + + center = Vec3.sum(center, dv); + position = Vec3.sum(position, dv); + + Camera.setPosition(position); + Camera.keepLookingAt(center); +} + +function saveCameraState() { + oldMode = Camera.getMode(); + var oldPosition = Camera.getPosition(); + Camera.setMode("independent"); + Camera.setPosition(oldPosition); +} + +function restoreCameraState() { + Camera.stopLooking(); + Camera.setMode(oldMode); +} + +function handleModes() { + var newMode = noMode; + if (alt) { + if (control) { + if (shift) { + newMode = panningMode; + } else { + newMode = orbitMode; + } + } else { + newMode = radialMode; + } + } + + // if leaving noMode + if (mode == noMode && newMode != noMode) { + saveCameraState(); + } + // if entering noMode + if (newMode == noMode && mode != noMode) { + restoreCameraState(); + } + + mode = newMode; +} + +function keyPressEvent(event) { + var changed = false; + + if (event.text == "ALT") { + alt = true; + changed = true; + } + if (event.text == "CONTROL") { + control = true; + changed = true; + } + if (event.text == "SHIFT") { + shift = true; + changed = true; + } + + if (changed) { + handleModes(); + } +} + +function keyReleaseEvent(event) { + var changed = false; + + if (event.text == "ALT") { + alt = false; + changed = true; + } + if (event.text == "CONTROL") { + control = false; + changed = true; + } + if (event.text == "SHIFT") { + shift = false; + changed = true; + } + + if (changed) { + handleModes(); + } +} + +function mousePressEvent(event) { + if (alt) { + isActive = true; + mouseLastX = event.x; + mouseLastY = event.y; + + // Compute trajectories related values + var pickRay = Camera.computePickRay(mouseLastX, mouseLastY); + var intersection = Voxels.findRayIntersection(pickRay); + + position = Camera.getPosition(); + + avatarTarget = MyAvatar.getTargetAvatarPosition(); + voxelTarget = intersection.intersection; + if (Vec3.length(Vec3.subtract(avatarTarget, position)) < Vec3.length(Vec3.subtract(voxelTarget, position))) { + if (avatarTarget.x != 0 || avatarTarget.y != 0 || avatarTarget.z != 0) { + center = avatarTarget; + } else { + center = voxelTarget; + } + } else { + if (voxelTarget.x != 0 || voxelTarget.y != 0 || voxelTarget.z != 0) { + center = voxelTarget; + } else { + center = avatarTarget; + } + } + + vector = Vec3.subtract(position, center); + radius = Vec3.length(vector); + azimuth = Math.atan2(vector.z, vector.x); + altitude = Math.asin(vector.y / Vec3.length(vector)); + + Camera.keepLookingAt(center); + } +} + +function mouseReleaseEvent(event) { + if (isActive) { + isActive = false; + } +} + +function mouseMoveEvent(event) { + if (isActive && mode != noMode) { + if (mode == radialMode) { + handleRadialMode(event.x - mouseLastX, event.y - mouseLastY); + } + if (mode == orbitMode) { + handleOrbitMode(event.x - mouseLastX, event.y - mouseLastY); + } + if (mode == panningMode) { + handlePanMode(event.x - mouseLastX, event.y - mouseLastY); + } + + mouseLastX = event.x; + mouseLastY = event.y; + } +} + +function scriptEnding() { + if (mode != noMode) { + restoreCameraState(); + } +} + +Controller.keyPressEvent.connect(keyPressEvent); +Controller.keyReleaseEvent.connect(keyReleaseEvent); + +Controller.mousePressEvent.connect(mousePressEvent); +Controller.mouseReleaseEvent.connect(mouseReleaseEvent); +Controller.mouseMoveEvent.connect(mouseMoveEvent); + +Script.scriptEnding.connect(scriptEnding); \ No newline at end of file diff --git a/interface/interface_en.ts b/interface/interface_en.ts index 3c61d5f17a..05998e6436 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -4,22 +4,22 @@ Application - + Export Voxels - + Sparse Voxel Octree Files (*.svo) - + Open Script - + JavaScript Files (*.js) @@ -113,18 +113,18 @@ Menu - + Open .ini config file - - + + Text files (*.ini) - + Save .ini config file @@ -132,122 +132,116 @@ PreferencesDialog - - + + Avatar - - + + <html><head/><body><p>Avatar display name <span style=" color:#909090;">(optional)</span></p></body></html> - - + + Not showing a name - - + + Head - - + + Body - - + + Advanced Tuning - - + + It's not recomended that you play with these settings unless you've looked into exactly what they do. - - + + <p>Avatar</p> - - + + Lean scale (applies to Faceshift users) - - + + Vertical field of view - - + + Avatar scale (default is 1.0) - - + + Pupil dillation - - + + Audio Jitter Buffer Samples (0 for automatic) - - + + Faceshift eye detection - - + + <html><head/><body><p>Voxels</p></body></html> - - + + Maximum voxels - - + + Max voxels sent each second - - - PushButton - - - - - + + Cancel - - + + Save all changes diff --git a/interface/resources/resources.qrc b/interface/resources/resources.qrc index 372fa8b1d4..300728392c 100644 --- a/interface/resources/resources.qrc +++ b/interface/resources/resources.qrc @@ -1,5 +1,6 @@ - - images/close.svg - + + images/close.svg + styles/search.svg + diff --git a/interface/resources/styles/global.qss b/interface/resources/styles/global.qss index d302555463..2554f3b2c9 100644 --- a/interface/resources/styles/global.qss +++ b/interface/resources/styles/global.qss @@ -13,8 +13,9 @@ QLineEdit { border-style: solid; border-width: 1px; border-color: #ccc; - padding: 7px; - opacity: 1; + padding: 8px; + font-size: 16px; + color: rgb(51, 51, 51); } QLabel p { @@ -27,14 +28,15 @@ QPushButton { border-radius: 9px; font-family: Arial; font-size: 18px; - font-weight: 100; color: #ffffff; - padding: 10px 15px; + padding: 10px 0px; } QSpinBox, QDoubleSpinBox { padding: 5px; border-width: 1; + font-size: 16px; + color: rgb(51, 51, 51); } QDoubleSpinBox::up-arrow, @@ -98,3 +100,14 @@ QSlider::handle:horizontal { background-repeat: no-repeat; background-position: center center; } + +QPushButton#closeButton { + border-color: #ccc; + border-style: solid; + border-width: 1px; + border-radius: 0; + background-color: #fff; + background-image: url(styles/close.svg); + background-repeat: no-repeat; + background-position: center center; +} diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 50dbf1b51a..030e3bc6fd 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -692,6 +692,8 @@ bool Application::event(QEvent* event) { void Application::keyPressEvent(QKeyEvent* event) { + _keysPressed.insert(event->key()); + _controllerScriptingInterface.emitKeyPressEvent(event); // send events to any registered scripts // if one of our scripts have asked to capture this event, then stop processing it @@ -914,6 +916,8 @@ void Application::keyPressEvent(QKeyEvent* event) { void Application::keyReleaseEvent(QKeyEvent* event) { + _keysPressed.remove(event->key()); + _controllerScriptingInterface.emitKeyReleaseEvent(event); // send events to any registered scripts // if one of our scripts have asked to capture this event, then stop processing it @@ -921,60 +925,66 @@ void Application::keyReleaseEvent(QKeyEvent* event) { return; } + switch (event->key()) { + case Qt::Key_E: + _myAvatar->setDriveKeys(UP, 0.f); + break; - if (activeWindow() == _window) { - switch (event->key()) { - case Qt::Key_E: - _myAvatar->setDriveKeys(UP, 0.f); - break; + case Qt::Key_C: + _myAvatar->setDriveKeys(DOWN, 0.f); + break; - case Qt::Key_C: - _myAvatar->setDriveKeys(DOWN, 0.f); - break; + case Qt::Key_W: + _myAvatar->setDriveKeys(FWD, 0.f); + break; - case Qt::Key_W: - _myAvatar->setDriveKeys(FWD, 0.f); - break; + case Qt::Key_S: + _myAvatar->setDriveKeys(BACK, 0.f); + break; - case Qt::Key_S: - _myAvatar->setDriveKeys(BACK, 0.f); - break; + case Qt::Key_A: + _myAvatar->setDriveKeys(ROT_LEFT, 0.f); + break; - case Qt::Key_A: - _myAvatar->setDriveKeys(ROT_LEFT, 0.f); - break; + case Qt::Key_D: + _myAvatar->setDriveKeys(ROT_RIGHT, 0.f); + break; - case Qt::Key_D: - _myAvatar->setDriveKeys(ROT_RIGHT, 0.f); - break; + case Qt::Key_Up: + _myAvatar->setDriveKeys(FWD, 0.f); + _myAvatar->setDriveKeys(UP, 0.f); + break; - case Qt::Key_Up: - _myAvatar->setDriveKeys(FWD, 0.f); - _myAvatar->setDriveKeys(UP, 0.f); - break; + case Qt::Key_Down: + _myAvatar->setDriveKeys(BACK, 0.f); + _myAvatar->setDriveKeys(DOWN, 0.f); + break; - case Qt::Key_Down: - _myAvatar->setDriveKeys(BACK, 0.f); - _myAvatar->setDriveKeys(DOWN, 0.f); - break; + case Qt::Key_Left: + _myAvatar->setDriveKeys(LEFT, 0.f); + _myAvatar->setDriveKeys(ROT_LEFT, 0.f); + break; - case Qt::Key_Left: - _myAvatar->setDriveKeys(LEFT, 0.f); - _myAvatar->setDriveKeys(ROT_LEFT, 0.f); - break; + case Qt::Key_Right: + _myAvatar->setDriveKeys(RIGHT, 0.f); + _myAvatar->setDriveKeys(ROT_RIGHT, 0.f); + break; - case Qt::Key_Right: - _myAvatar->setDriveKeys(RIGHT, 0.f); - _myAvatar->setDriveKeys(ROT_RIGHT, 0.f); - break; - - default: - event->ignore(); - break; - } + default: + event->ignore(); + break; } } +void Application::focusOutEvent(QFocusEvent* event) { + // synthesize events for keys currently pressed, since we may not get their release events + foreach (int key, _keysPressed) { + QKeyEvent event(QEvent::KeyRelease, key, Qt::NoModifier); + keyReleaseEvent(&event); + } + _keysPressed.clear(); +} + void Application::mouseMoveEvent(QMouseEvent* event) { _controllerScriptingInterface.emitMouseMoveEvent(event); // send events to any registered scripts @@ -1680,7 +1690,7 @@ void Application::updateMyAvatarLookAtPosition() { } else { // look in direction of the mouse ray, but use distance from intersection, if any float distance = TREE_SCALE; - if (_myAvatar->getLookAtTargetAvatar()) { + if (_myAvatar->getLookAtTargetAvatar() && _myAvatar != _myAvatar->getLookAtTargetAvatar()) { distance = glm::distance(_mouseRayOrigin, static_cast(_myAvatar->getLookAtTargetAvatar())->getHead()->calculateAverageEyePosition()); } @@ -2140,7 +2150,8 @@ void Application::loadViewFrustum(Camera& camera, ViewFrustum& viewFrustum) { } glm::vec3 Application::getSunDirection() { - return glm::normalize(_environment.getClosestData(_myCamera.getPosition()).getSunLocation() - _myCamera.getPosition()); + return glm::normalize(_environment.getClosestData(_myCamera.getPosition()).getSunLocation(_myCamera.getPosition()) - + _myCamera.getPosition()); } void Application::updateShadowMap() { @@ -2302,7 +2313,8 @@ void Application::displaySide(Camera& whichCamera, bool selfAvatarOnly) { float alpha = 1.0f; if (Menu::getInstance()->isOptionChecked(MenuOption::Atmosphere)) { const EnvironmentData& closestData = _environment.getClosestData(whichCamera.getPosition()); - float height = glm::distance(whichCamera.getPosition(), closestData.getAtmosphereCenter()); + float height = glm::distance(whichCamera.getPosition(), + closestData.getAtmosphereCenter(whichCamera.getPosition())); if (height < closestData.getAtmosphereInnerRadius()) { alpha = 0.0f; diff --git a/interface/src/Application.h b/interface/src/Application.h index cbfbf4166d..28060113a9 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -18,6 +18,7 @@ #include #include #include +#include #include #include @@ -122,6 +123,8 @@ public: void keyPressEvent(QKeyEvent* event); void keyReleaseEvent(QKeyEvent* event); + void focusOutEvent(QFocusEvent* event); + void mouseMoveEvent(QMouseEvent* event); void mousePressEvent(QMouseEvent* event); void mouseReleaseEvent(QMouseEvent* event); @@ -432,6 +435,8 @@ private: bool _mousePressed; // true if mouse has been pressed (clear when finished) + QSet _keysPressed; + GeometryCache _geometryCache; TextureCache _textureCache; diff --git a/interface/src/Environment.cpp b/interface/src/Environment.cpp index 1f9e23bee1..096b8770fb 100644 --- a/interface/src/Environment.cpp +++ b/interface/src/Environment.cpp @@ -92,7 +92,7 @@ glm::vec3 Environment::getGravity (const glm::vec3& position) { foreach (const ServerData& serverData, _data) { foreach (const EnvironmentData& environmentData, serverData) { - glm::vec3 vector = environmentData.getAtmosphereCenter() - position; + glm::vec3 vector = environmentData.getAtmosphereCenter(position) - position; float surfaceRadius = environmentData.getAtmosphereInnerRadius(); if (glm::length(vector) <= surfaceRadius) { // At or inside a planet, gravity is as set for the planet @@ -116,7 +116,7 @@ const EnvironmentData Environment::getClosestData(const glm::vec3& position) { float closestDistance = FLT_MAX; foreach (const ServerData& serverData, _data) { foreach (const EnvironmentData& environmentData, serverData) { - float distance = glm::distance(position, environmentData.getAtmosphereCenter()) - + float distance = glm::distance(position, environmentData.getAtmosphereCenter(position)) - environmentData.getAtmosphereOuterRadius(); if (distance < closestDistance) { closest = environmentData; @@ -132,6 +132,8 @@ bool Environment::findCapsulePenetration(const glm::vec3& start, const glm::vec3 // collide with the "floor" bool found = findCapsulePlanePenetration(start, end, radius, glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), penetration); + glm::vec3 middle = (start + end) * 0.5f; + // get the lock for the duration of the call QMutexLocker locker(&_mutex); @@ -141,7 +143,7 @@ bool Environment::findCapsulePenetration(const glm::vec3& start, const glm::vec3 continue; // don't bother colliding with gravity-less environments } glm::vec3 environmentPenetration; - if (findCapsuleSpherePenetration(start, end, radius, environmentData.getAtmosphereCenter(), + if (findCapsuleSpherePenetration(start, end, radius, environmentData.getAtmosphereCenter(middle), environmentData.getAtmosphereInnerRadius(), environmentPenetration)) { penetration = addPenetrations(penetration, environmentPenetration); found = true; @@ -203,10 +205,12 @@ ProgramObject* Environment::createSkyProgram(const char* from, int* locations) { } void Environment::renderAtmosphere(Camera& camera, const EnvironmentData& data) { + glm::vec3 center = data.getAtmosphereCenter(camera.getPosition()); + glPushMatrix(); - glTranslatef(data.getAtmosphereCenter().x, data.getAtmosphereCenter().y, data.getAtmosphereCenter().z); - - glm::vec3 relativeCameraPos = camera.getPosition() - data.getAtmosphereCenter(); + glTranslatef(center.x, center.y, center.z); + + glm::vec3 relativeCameraPos = camera.getPosition() - center; float height = glm::length(relativeCameraPos); // use the appropriate shader depending on whether we're inside or outside diff --git a/interface/src/GLCanvas.cpp b/interface/src/GLCanvas.cpp index a91452c06d..513dcfe40c 100644 --- a/interface/src/GLCanvas.cpp +++ b/interface/src/GLCanvas.cpp @@ -55,6 +55,10 @@ void GLCanvas::keyReleaseEvent(QKeyEvent* event) { Application::getInstance()->keyReleaseEvent(event); } +void GLCanvas::focusOutEvent(QFocusEvent* event) { + Application::getInstance()->focusOutEvent(event); +} + void GLCanvas::mouseMoveEvent(QMouseEvent* event) { Application::getInstance()->mouseMoveEvent(event); } diff --git a/interface/src/GLCanvas.h b/interface/src/GLCanvas.h index ad396a48ce..f7f7fb7c20 100644 --- a/interface/src/GLCanvas.h +++ b/interface/src/GLCanvas.h @@ -31,6 +31,8 @@ protected: virtual void keyPressEvent(QKeyEvent* event); virtual void keyReleaseEvent(QKeyEvent* event); + virtual void focusOutEvent(QFocusEvent* event); + virtual void mouseMoveEvent(QMouseEvent* event); virtual void mousePressEvent(QMouseEvent* event); virtual void mouseReleaseEvent(QMouseEvent* event); diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 54b6a5dac2..2b1003f2e4 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -24,11 +24,12 @@ #include #include #include -#include +#include #include #include #include +#include #include "Application.h" #include "Menu.h" @@ -36,6 +37,7 @@ #include "Util.h" #include "InfoView.h" #include "ui/MetavoxelEditor.h" +#include "ModelBrowser.h" Menu* Menu::_instance = NULL; @@ -138,9 +140,8 @@ Menu::Menu() : this, SLOT(goTo())); - addDisabledActionAndSeparator(fileMenu, "Upload/Browse"); - addActionToQMenuAndActionHash(fileMenu, MenuOption::UploaderAvatarHead, 0, Application::getInstance(), SLOT(uploadFST())); - addActionToQMenuAndActionHash(fileMenu, MenuOption::UploaderAvatarSkeleton, 0, Application::getInstance(), SLOT(uploadFST())); + addDisabledActionAndSeparator(fileMenu, "Upload Avatar Model"); + addActionToQMenuAndActionHash(fileMenu, MenuOption::UploadFST, 0, Application::getInstance(), SLOT(uploadFST())); addDisabledActionAndSeparator(fileMenu, "Settings"); addActionToQMenuAndActionHash(fileMenu, MenuOption::SettingsImport, 0, this, SLOT(importSettings())); @@ -693,7 +694,7 @@ void Menu::loginForCurrentDomain() { } void Menu::editPreferences() { - if (! _preferencesDialog) { + if (!_preferencesDialog) { _preferencesDialog = new PreferencesDialog(Application::getInstance()->getGLWidget()); _preferencesDialog->show(); } diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 15a4ee1811..96d5267b9c 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -300,8 +300,7 @@ namespace MenuOption { const QString StopAllScripts = "Stop All Scripts"; const QString TestPing = "Test Ping"; const QString TransmitterDrive = "Transmitter Drive"; - const QString UploaderAvatarHead = "Upload Avatar Head"; - const QString UploaderAvatarSkeleton = "Upload Avatar Skeleton"; + const QString UploadFST = "Upload FST file"; const QString Visage = "Visage"; const QString Quit = "Quit"; const QString Voxels = "Voxels"; diff --git a/interface/src/ModelBrowser.cpp b/interface/src/ModelBrowser.cpp new file mode 100644 index 0000000000..e03081273f --- /dev/null +++ b/interface/src/ModelBrowser.cpp @@ -0,0 +1,150 @@ +// +// ModelBrowser.cpp +// hifi +// +// Created by Clement on 3/17/14. +// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "ModelBrowser.h" + +static const QString PREFIX_PARAMETER_NAME = "prefix"; +static const QString MARKER_PARAMETER_NAME = "marker"; +static const QString IS_TRUNCATED_NAME = "IsTruncated"; +static const QString CONTAINER_NAME = "Contents"; +static const QString KEY_NAME = "Key"; + +ModelBrowser::ModelBrowser(ModelType modelType, QWidget* parent) : QWidget(parent), _type(modelType) { + QUrl url(S3_URL); + QUrlQuery query; + + if (_type == Head) { + query.addQueryItem(PREFIX_PARAMETER_NAME, HEAD_MODELS_LOCATION); + } else if (_type == Skeleton) { + query.addQueryItem(PREFIX_PARAMETER_NAME, SKELETON_MODELS_LOCATION); + } + url.setQuery(query); + + _downloader = new FileDownloader(url); + connect(_downloader, SIGNAL(done(QNetworkReply::NetworkError)), SLOT(downloadFinished())); +} + +ModelBrowser::~ModelBrowser() { + delete _downloader; +} + +void ModelBrowser::downloadFinished() { + parseXML(_downloader->getData()); +} + +void ModelBrowser::browse() { + QDialog dialog(this); + dialog.setWindowTitle("Browse models"); + + QGridLayout* layout = new QGridLayout(&dialog); + dialog.setLayout(layout); + + QLineEdit* searchBar = new QLineEdit(&dialog); + layout->addWidget(searchBar, 0, 0); + + ListView* listView = new ListView(&dialog); + listView->setEditTriggers(QAbstractItemView::NoEditTriggers); + layout->addWidget(listView, 1, 0); + listView->connect(searchBar, SIGNAL(textChanged(const QString&)), SLOT(keyboardSearch(const QString&))); + dialog.connect(listView, SIGNAL(doubleClicked(const QModelIndex&)), SLOT(accept())); + + QStringListModel* model = new QStringListModel(_models.keys(), listView); + model->sort(0); + listView->setModel(model); + + QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + layout->addWidget(buttons, 2, 0); + dialog.connect(buttons, SIGNAL(accepted()), SLOT(accept())); + dialog.connect(buttons, SIGNAL(rejected()), SLOT(reject())); + + if (dialog.exec() == QDialog::Rejected) { + return; + } + + QString selectedKey = model->data(listView->currentIndex(), Qt::DisplayRole).toString(); + + emit selected(_models[selectedKey]); +} + +bool ModelBrowser::parseXML(QByteArray xmlFile) { + QXmlStreamReader xml(xmlFile); + QRegExp rx(".*fst"); + bool truncated = false; + QString lastKey; + + // Read xml until the end or an error is detected + while(!xml.atEnd() && !xml.hasError()) { + if(xml.tokenType() == QXmlStreamReader::StartElement && xml.name() == IS_TRUNCATED_NAME) { + while(!(xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == IS_TRUNCATED_NAME)) { + // Let's check if there is more + xml.readNext(); + if (xml.text().toString() == "True") { + truncated = true; + } + } + } + + if(xml.tokenType() == QXmlStreamReader::StartElement && xml.name() == CONTAINER_NAME) { + while(!(xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == CONTAINER_NAME)) { + // If a file is find, process it + if(xml.tokenType() == QXmlStreamReader::StartElement && xml.name() == KEY_NAME) { + xml.readNext(); + lastKey = xml.text().toString(); + if (rx.exactMatch(xml.text().toString())) { + // Add the found file to the list + _models.insert(QFileInfo(xml.text().toString()).baseName(), + S3_URL + "/" + xml.text().toString()); + } + } + xml.readNext(); + } + } + xml.readNext(); + } + + // Error handling + if(xml.hasError()) { + _models.clear(); + QMessageBox::critical(this, + "ModelBrowser::ModelBrowser()", + xml.errorString(), + QMessageBox::Ok); + return false; + } + + // If we didn't all the files, download the next ones + if (truncated) { + QUrl url(S3_URL); + QUrlQuery query; + + if (_type == Head) { + query.addQueryItem(PREFIX_PARAMETER_NAME, HEAD_MODELS_LOCATION); + } else if (_type == Skeleton) { + query.addQueryItem(PREFIX_PARAMETER_NAME, SKELETON_MODELS_LOCATION); + } + query.addQueryItem(MARKER_PARAMETER_NAME, lastKey); + url.setQuery(query); + + delete _downloader; + _downloader = new FileDownloader(url); + connect(_downloader, SIGNAL(done(QNetworkReply::NetworkError)), SLOT(downloadFinished())); + } + + return true; +} \ No newline at end of file diff --git a/interface/src/ModelBrowser.h b/interface/src/ModelBrowser.h new file mode 100644 index 0000000000..4628642e89 --- /dev/null +++ b/interface/src/ModelBrowser.h @@ -0,0 +1,62 @@ +// +// ModelBrowser.h +// hifi +// +// Created by Clement on 3/17/14. +// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// + +#ifndef __hifi__ModelBrowser__ +#define __hifi__ModelBrowser__ + +#include + +#include +#include + +static const QString S3_URL = "http://highfidelity-public.s3-us-west-1.amazonaws.com"; +static const QString HEAD_MODELS_LOCATION = "models/heads/"; +static const QString SKELETON_MODELS_LOCATION = "models/skeletons/"; + +enum ModelType { + Head, + Skeleton +}; + +class ModelBrowser : public QWidget { + Q_OBJECT + +public: + ModelBrowser(ModelType modelType, QWidget* parent = NULL); + ~ModelBrowser(); + +signals: + void selected(QString filename); + +public slots: + void browse(); + +private slots: + void downloadFinished(); + +private: + ModelType _type; + FileDownloader* _downloader; + QHash _models; + + bool parseXML(QByteArray xmlFile); +}; + + + +class ListView : public QListView { + Q_OBJECT +public: + ListView(QWidget* parent) : QListView(parent) {} + public slots: + void keyboardSearch(const QString& text) { + QAbstractItemView::keyboardSearch(text); + } +}; + +#endif /* defined(__hifi__ModelBrowser__) */ diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index fb0d704c6a..13e2d3321a 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -582,16 +582,15 @@ void MyAvatar::updateLookAtTargetAvatar() { foreach (const AvatarSharedPointer& avatarPointer, Application::getInstance()->getAvatarManager().getAvatarHash()) { Avatar* avatar = static_cast(avatarPointer.data()); - if (avatar == static_cast(this)) { - continue; - } float distance; if (avatar->findRayIntersection(mouseOrigin, mouseDirection, distance)) { _lookAtTargetAvatar = avatarPointer; + _targetAvatarPosition = avatarPointer->getPosition(); return; } } _lookAtTargetAvatar.clear(); + _targetAvatarPosition = glm::vec3(0, 0, 0); } } diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index 3544fb1a61..d958103fa6 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -76,6 +76,7 @@ public: void orbit(const glm::vec3& position, int deltaX, int deltaY); + Q_INVOKABLE glm::vec3 getTargetAvatarPosition() const { return _targetAvatarPosition; } AvatarData* getLookAtTargetAvatar() const { return _lookAtTargetAvatar.data(); } void updateLookAtTargetAvatar(); void clearLookAtTargetAvatar(); @@ -116,6 +117,7 @@ private: glm::vec3 _moveTarget; int _moveTargetStepCounter; QWeakPointer _lookAtTargetAvatar; + glm::vec3 _targetAvatarPosition; bool _shouldRender; bool _billboardValid; diff --git a/interface/src/renderer/TextureCache.cpp b/interface/src/renderer/TextureCache.cpp index 2b43c89998..b3820abf25 100644 --- a/interface/src/renderer/TextureCache.cpp +++ b/interface/src/renderer/TextureCache.cpp @@ -313,7 +313,7 @@ void ImageReader::run() { int imageArea = image.width() * image.height(); if (opaquePixels == imageArea) { qDebug() << "Image with alpha channel is completely opaque:" << url; - image.convertToFormat(QImage::Format_RGB888); + image = image.convertToFormat(QImage::Format_RGB888); } QMetaObject::invokeMethod(texture.data(), "setImage", Q_ARG(const QImage&, image), Q_ARG(bool, translucentPixels >= imageArea / 2)); diff --git a/interface/src/ui/FramelessDialog.cpp b/interface/src/ui/FramelessDialog.cpp index 9239deed90..1f67e9f4d1 100644 --- a/interface/src/ui/FramelessDialog.cpp +++ b/interface/src/ui/FramelessDialog.cpp @@ -6,6 +6,7 @@ // // +#include #include #include #include @@ -13,13 +14,29 @@ #include "Application.h" #include "FramelessDialog.h" -FramelessDialog::FramelessDialog(QWidget *parent, Qt::WindowFlags flags) : QDialog(parent, flags | Qt::FramelessWindowHint) { - setWindowOpacity(0.9); +const int RESIZE_HANDLE_WIDTH = 7; + +FramelessDialog::FramelessDialog(QWidget *parent, Qt::WindowFlags flags) : + QDialog(parent, flags | Qt::FramelessWindowHint), + _isResizing(false) { + + setWindowOpacity(0.95); setAttribute(Qt::WA_DeleteOnClose); - isResizing = false; + + installEventFilter(this); } -void FramelessDialog::setStyleSheet(const QString& fileName) { +void FramelessDialog::showEvent(QShowEvent* event) { + QDesktopWidget desktop; + + // move to upper left + move(desktop.availableGeometry().x(), desktop.availableGeometry().y()); + + // keep full height + resize(size().width(), desktop.availableGeometry().height()); +} + +void FramelessDialog::setStyleSheetFile(const QString& fileName) { QFile globalStyleSheet(Application::resourcesPath() + "styles/global.qss"); QFile styleSheet(Application::resourcesPath() + fileName); if (styleSheet.open(QIODevice::ReadOnly) && globalStyleSheet.open(QIODevice::ReadOnly) ) { @@ -27,27 +44,24 @@ void FramelessDialog::setStyleSheet(const QString& fileName) { QDialog::setStyleSheet(globalStyleSheet.readAll() + styleSheet.readAll()); } } + void FramelessDialog::mousePressEvent(QMouseEvent* mouseEvent) { - if (abs(mouseEvent->pos().x() - size().width()) < 2 && mouseEvent->button() == Qt::LeftButton) { - isResizing = true; + + if (abs(mouseEvent->pos().x() - size().width()) < RESIZE_HANDLE_WIDTH && mouseEvent->button() == Qt::LeftButton) { + _isResizing = true; QApplication::setOverrideCursor(Qt::SizeHorCursor); } - // propagate the event - QDialog::mousePressEvent(mouseEvent); } void FramelessDialog::mouseReleaseEvent(QMouseEvent* mouseEvent) { QApplication::restoreOverrideCursor(); - isResizing = false; - // propagate the event - QDialog::mouseReleaseEvent(mouseEvent); + _isResizing = false; } void FramelessDialog::mouseMoveEvent(QMouseEvent* mouseEvent) { - if (isResizing) { + if (_isResizing) { resize(mouseEvent->pos().x(), size().height()); } - QDialog::mouseMoveEvent(mouseEvent); } FramelessDialog::~FramelessDialog() { diff --git a/interface/src/ui/FramelessDialog.h b/interface/src/ui/FramelessDialog.h index 4e18aff161..2bb8d6b85c 100644 --- a/interface/src/ui/FramelessDialog.h +++ b/interface/src/ui/FramelessDialog.h @@ -21,15 +21,16 @@ class FramelessDialog : public QDialog { public: FramelessDialog(QWidget* parent = 0, Qt::WindowFlags flags = 0); virtual ~FramelessDialog(); - void setStyleSheet(const QString& fileName); + void setStyleSheetFile(const QString& fileName); protected: - void mouseMoveEvent(QMouseEvent* mouseEvent); - void mousePressEvent(QMouseEvent* mouseEvent); - void mouseReleaseEvent(QMouseEvent* mouseEvent); + virtual void mouseMoveEvent(QMouseEvent* mouseEvent); + virtual void mousePressEvent(QMouseEvent* mouseEvent); + virtual void mouseReleaseEvent(QMouseEvent* mouseEvent); + virtual void showEvent(QShowEvent* event); private: - bool isResizing; + bool _isResizing; }; diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index 318db54f2c..56dbf8470c 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -6,14 +6,27 @@ // // -#include "PreferencesDialog.h" #include "Application.h" #include "Menu.h" +#include "ModelBrowser.h" +#include "PreferencesDialog.h" + +const int SCROLL_PANEL_BOTTOM_MARGIN = 30; +const int OK_BUTTON_RIGHT_MARGIN = 30; +const int BUTTONS_TOP_MARGIN = 24; PreferencesDialog::PreferencesDialog(QWidget* parent, Qt::WindowFlags flags) : FramelessDialog(parent, flags) { + ui.setupUi(this); - setStyleSheet("styles/preferences.qss"); + setStyleSheetFile("styles/preferences.qss"); loadPreferences(); + connect(ui.closeButton, &QPushButton::clicked, this, &QDialog::close); + connect(ui.buttonBrowseHead, &QPushButton::clicked, this, &PreferencesDialog::openHeadModelBrowser); + connect(ui.buttonBrowseBody, &QPushButton::clicked, this, &PreferencesDialog::openBodyModelBrowser); +} + +PreferencesDialog::~PreferencesDialog() { + deleteLater(); } void PreferencesDialog::accept() { @@ -21,6 +34,39 @@ void PreferencesDialog::accept() { close(); } +void PreferencesDialog::openHeadModelBrowser() { + ModelBrowser modelBrowser(Head); + modelBrowser.browse(); + connect(&modelBrowser, &ModelBrowser::selected, ui.faceURLEdit, &QLineEdit::setText); +} + +void PreferencesDialog::openBodyModelBrowser() { + ModelBrowser modelBrowser(Skeleton); + modelBrowser.browse(); + connect(&modelBrowser, &ModelBrowser::selected, ui.skeletonURLEdit, &QLineEdit::setText); +} + +void PreferencesDialog::resizeEvent(QResizeEvent *resizeEvent) { + + // keep buttons panel at the bottom + ui.buttonsPanel->setGeometry(0, size().height() - ui.buttonsPanel->height(), size().width(), ui.buttonsPanel->height()); + + // set width and height of srcollarea to match bottom panel and width + ui.scrollArea->setGeometry(ui.scrollArea->geometry().x(), ui.scrollArea->geometry().y(), + size().width(), + size().height() - ui.buttonsPanel->height() - + SCROLL_PANEL_BOTTOM_MARGIN - ui.scrollArea->geometry().y()); + + // move Save button to left position + ui.defaultButton->move(size().width() - OK_BUTTON_RIGHT_MARGIN - ui.defaultButton->size().width(), BUTTONS_TOP_MARGIN); + + // move Save button to left position + ui.cancelButton->move(ui.defaultButton->pos().x() - ui.cancelButton->size().width(), BUTTONS_TOP_MARGIN); + + // move close button + ui.closeButton->move(size().width() - OK_BUTTON_RIGHT_MARGIN - ui.closeButton->size().width(), ui.closeButton->pos().y()); +} + void PreferencesDialog::loadPreferences() { MyAvatar* myAvatar = Application::getInstance()->getAvatar(); diff --git a/interface/src/ui/PreferencesDialog.h b/interface/src/ui/PreferencesDialog.h index d5cb41c7df..f1f37c66cd 100644 --- a/interface/src/ui/PreferencesDialog.h +++ b/interface/src/ui/PreferencesDialog.h @@ -19,16 +19,22 @@ class PreferencesDialog : public FramelessDialog { public: PreferencesDialog(QWidget* parent = 0, Qt::WindowFlags flags = 0); + ~PreferencesDialog(); + +protected: + void resizeEvent(QResizeEvent* resizeEvent); private: - Ui_PreferencesDialog ui; void loadPreferences(); void savePreferences(); - + void openHeadModelBrowser(); + void openBodyModelBrowser(); + + Ui_PreferencesDialog ui; QString _faceURLString; QString _skeletonURLString; QString _displayNameString; - + private slots: void accept(); diff --git a/interface/ui/preferencesDialog.ui b/interface/ui/preferencesDialog.ui index 0099838177..0f33e2a0b0 100644 --- a/interface/ui/preferencesDialog.ui +++ b/interface/ui/preferencesDialog.ui @@ -3,14 +3,14 @@ PreferencesDialog - Qt::ApplicationModal + Qt::NonModal 0 0 - 640 - 752 + 610 + 499 @@ -25,15 +25,27 @@ 0 - + 0 - 720 - 616 - 80 + 400 + 611 + 97 + + + 0 + 0 + + + + + 0 + 97 + + Arial @@ -42,1136 +54,1245 @@ background-color: #0e7077 - + - 0 - 20 - 591 - 41 + 310 + 24 + 91 + 50 + + + 0 + 0 + + + + + 0 + 50 + + Arial + 18 + 50 + false - - - 0 - - - - - - Arial - - - - Qt::Horizontal - - - - 0 - 0 - - - - - - - - - Arial - - - - Cancel - - - - - - - - Arial - - - - background-color: #fff; + + + + + Cancel + + + + + + 400 + 24 + 188 + 50 + + + + + 0 + 0 + + + + + 188 + 49 + + + + + Arial + 18 + + + + background-color: #fff; color: #0e7077 - - - Save all changes - - - true - - - - + + + Save all changes + + + true + 0 - 0 - 621 - 1000 + 30 + 615 + 351 - - - 0 - 0 - + + QFrame::NoFrame + + + QFrame::Plain + + + 0 true - + 0 0 - 619 - 998 + 615 + 833 - - - - 0 - 50 - 621 - 783 - + + + 0 - - - Arial - + + 30 - - - 0 - - - 30 - - - 0 - - - 30 - - - - - - 0 - 0 - - - - - Arial - 24 - - - - color: #0e7077 - - - Avatar - - - 25 - - - - - - - - - - - 0 - 0 - - - - - 0 - 30 - - - - - Arial - 16 - - - - color: #0e7077 - - - <html><head/><body><p>Avatar display name <span style=" color:#909090;">(optional)</span></p></body></html> - - - Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft - - - displayNameEdit - - - - - - - - 0 - 0 - - - - - 280 - 0 - - - - - Arial - - - - Qt::LeftToRight - - - - - - Not showing a name - - - - - - - - 0 - 0 - - - - - 0 - 30 - - - - - Arial - 16 - - - - color: #0e7077 - - - Head - - - Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft - - - 0 - - - faceURLEdit - - - - - - - - 0 - 0 - - - - - Arial - - - - - - - - - 0 - 0 - - - - - 0 - 30 - - - - - Arial - 16 - - - - color: #0e7077 - - - Body - - - Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft - - - skeletonURLEdit - - - - - - - - 0 - 0 - - - - - Arial - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - Arial - 24 - - - - color: #0e7077 - - - Advanced Tuning - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - 25 - - - - - - - - 0 - 0 - - - - - Arial - - - - color: rgb(51, 51, 51) - - - It's not recomended that you play with these settings unless you've looked into exactly what they do. - - - false - - - true - - - - - - - - 0 - 0 - - - - - 0 - 40 - - - - - Arial - 20 - 50 - false - - - - color: #0e7077 - - - <p>Avatar</p> - - - Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft - - - - - - - 0 - - - 10 - - - 10 - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 25 - - - - - Arial - - - - color: rgb(51, 51, 51) - - - Lean scale (applies to Faceshift users) - - - leanScaleSpin - - - - - - - - Arial - - - - Qt::Horizontal - - - QSizePolicy::Expanding - - - - 40 - 10 - - - - - - - - - 0 - 0 - - - - - 95 - 36 - - - - - 70 - 16777215 - - - - - Arial - - - - - - - - - - 0 - - - 10 - - - 0 - - - 10 - - - - - - Arial - - - - color: rgb(51, 51, 51) - - - Vertical field of view - - - fieldOfViewSpin - - - - - - - - Arial - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 95 - 36 - - - - - 70 - 16777215 - - - - - Arial - - - - 1 - - - 180 - - - - - - - - - 0 - - - 10 - - - 0 - - - 10 - - - - - - Arial - - - - color: rgb(51, 51, 51) - - - Avatar scale (default is 1.0) - - - avatarScaleSpin - - - - - - - - Arial - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 95 - 36 - - - - - 70 - 16777215 - - - - - Arial - - - - - - - - - - 0 - - - 10 - - - 0 - - - 10 - - - - - - Arial - - - - color: rgb(51, 51, 51) - - - Pupil dillation - - - - - - - - Arial - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 125 - 0 - - - - - Arial - - - - Qt::Horizontal - - - - - - - - - 0 - - - 10 - - - 0 - - - 10 - - - - - - Arial - - - - color: rgb(51, 51, 51) - - - Audio Jitter Buffer Samples (0 for automatic) - - - - - - - - Arial - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 95 - 36 - - - - - 70 - 16777215 - - - - - Arial - - - - -10000 - - - 10000 - - - 1 - - - - - - - - - 0 - - - 10 - - - 0 - - - 10 - - - - - - Arial - - - - color: rgb(51, 51, 51) - - - Faceshift eye detection - - - avatarScaleSpin - - - - - - - - Arial - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 125 - 0 - - - - - Arial - - - - Qt::Horizontal - - - - - - - - - - 0 - 0 - - - - - 0 - 40 - - - - - Arial - 20 - 50 - false - - - - color: #0e7077 - - - <html><head/><body><p>Voxels</p></body></html> - - - - - - - 0 - - - 10 - - - 0 - - - 10 - - - - - - Arial - - - - color: rgb(51, 51, 51) - - - Maximum voxels - - - leanScaleSpin - - - - - - - - Arial - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 125 - 36 - - - - - Arial - - - - 5000000 - - - 50000 - - - - - - - - - 0 - - - 10 - - - 0 - - - 10 - - - - - - Arial - - - - Max voxels sent each second - - - leanScaleSpin - - - - - - - - Arial - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 95 - 36 - - - - - 70 - 16777215 - - - - - Arial - - - - 60 - - - 6000 - - - 10 - - - - - - - - - - - 540 - 40 - 114 - 32 - + + 0 - - PushButton + + 30 - + + 30 + + + + + + 0 + 0 + + + + + Arial + 24 + + + + color: #0e7077 + + + Avatar + + + 25 + + + + + + + + + + + 0 + 0 + + + + + 0 + 30 + + + + + Arial + 16 + + + + color: #0e7077 + + + <html><head/><body><p>Avatar display name <span style=" color:#909090;">(optional)</span></p></body></html> + + + Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft + + + displayNameEdit + + + + + + + + 0 + 0 + + + + + 280 + 20 + + + + + Arial + + + + Qt::LeftToRight + + + + + + Not showing a name + + + + + + + + 0 + 0 + + + + + 0 + 30 + + + + + Arial + 16 + + + + color: #0e7077 + + + Head + + + Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft + + + 0 + + + faceURLEdit + + + + + + + + + + 0 + 0 + + + + + Arial + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + + 0 + 0 + + + + + 30 + 30 + + + + background-color: #fff; +border-radius: 0; +padding: 0; + + + + + + + :/styles/search.svg + + + + + + + + + + + 0 + 0 + + + + + 0 + 30 + + + + + Arial + 16 + + + + color: #0e7077 + + + Body + + + Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft + + + skeletonURLEdit + + + + + + + + + + 0 + 0 + + + + + Arial + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + + 0 + 0 + + + + + 30 + 30 + + + + background-color: #fff; +border-radius: 0; +padding: 0; + + + + + + + :/styles/search.svg + + + + + + + + + + Qt::Vertical + + + + 0 + 35 + + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + Arial + 24 + + + + color: #0e7077 + + + Advanced Tuning + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + 25 + + + + + + + + 0 + 0 + + + + + Arial + 16 + + + + color: rgb(51, 51, 51) + + + It's not recomended that you play with these settings unless you've looked into exactly what they do. + + + false + + + true + + + + + + + + 0 + 0 + + + + + 0 + 40 + + + + + Arial + 20 + 50 + false + + + + color: #0e7077 + + + <p>Avatar</p> + + + Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft + + + + + + + 0 + + + 10 + + + 0 + + + 10 + + + + + + Arial + + + + color: rgb(51, 51, 51) + + + Vertical field of view + + + fieldOfViewSpin + + + + + + + + Arial + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 95 + 36 + + + + + 70 + 16777215 + + + + + Arial + + + + 1 + + + 180 + + + + + + + + + 0 + + + 10 + + + 10 + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 25 + + + + + Arial + + + + color: rgb(51, 51, 51) + + + Lean scale (applies to Faceshift users) + + + leanScaleSpin + + + + + + + + Arial + + + + Qt::Horizontal + + + QSizePolicy::Expanding + + + + 40 + 10 + + + + + + + + + 0 + 0 + + + + + 95 + 36 + + + + + 70 + 16777215 + + + + + Arial + + + + + + + + + + 0 + + + 10 + + + 0 + + + 10 + + + + + + Arial + + + + color: rgb(51, 51, 51) + + + Avatar scale (default is 1.0) + + + avatarScaleSpin + + + + + + + + Arial + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 95 + 36 + + + + + 70 + 16777215 + + + + + Arial + + + + + + + + + + 0 + + + 10 + + + 0 + + + 10 + + + + + + Arial + + + + color: rgb(51, 51, 51) + + + Pupil dillation + + + pupilDilationSlider + + + + + + + + Arial + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 125 + 0 + + + + + Arial + + + + Qt::Horizontal + + + + + + + + + 0 + + + 10 + + + 0 + + + 10 + + + + + + Arial + + + + color: rgb(51, 51, 51) + + + Audio Jitter Buffer Samples (0 for automatic) + + + audioJitterSpin + + + + + + + + Arial + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 95 + 36 + + + + + 70 + 16777215 + + + + + Arial + + + + -10000 + + + 10000 + + + 1 + + + + + + + + + 0 + + + 10 + + + 0 + + + 10 + + + + + + Arial + + + + color: rgb(51, 51, 51) + + + Faceshift eye detection + + + faceshiftEyeDeflectionSider + + + + + + + + Arial + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 125 + 0 + + + + + Arial + + + + Qt::Horizontal + + + + + + + + + + 0 + 0 + + + + + 0 + 40 + + + + + Arial + 20 + 50 + false + + + + color: #0e7077 + + + <html><head/><body><p>Voxels</p></body></html> + + + Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft + + + + + + + 0 + + + 10 + + + 0 + + + 10 + + + + + + Arial + + + + color: rgb(51, 51, 51) + + + Maximum voxels + + + maxVoxelsSpin + + + + + + + + Arial + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 125 + 36 + + + + + Arial + + + + 5000000 + + + 50000 + + + + + + + + + 0 + + + 10 + + + 0 + + + 10 + + + + + + Arial + + + + Max voxels sent each second + + + maxVoxelsPPSSpin + + + + + + + + Arial + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 95 + 36 + + + + + 70 + 16777215 + + + + + Arial + + + + 60 + + + 6000 + + + 10 + + + + + + + + + + 540 + 24 + 31 + 31 + + + + + PreferAntialias + + + + + + @@ -1179,6 +1300,41 @@ color: #0e7077 1 - - + + + + + + cancelButton + clicked() + PreferencesDialog + close() + + + 495 + 749 + + + 528 + 0 + + + + + defaultButton + clicked() + PreferencesDialog + accept() + + + 504 + 749 + + + 20 + 20 + + + + diff --git a/libraries/audio/src/AudioRingBuffer.cpp b/libraries/audio/src/AudioRingBuffer.cpp index 0e92ab4eb5..cf35b6a20f 100644 --- a/libraries/audio/src/AudioRingBuffer.cpp +++ b/libraries/audio/src/AudioRingBuffer.cpp @@ -19,7 +19,8 @@ AudioRingBuffer::AudioRingBuffer(int numFrameSamples) : NodeData(), _sampleCapacity(numFrameSamples * RING_BUFFER_LENGTH_FRAMES), _isStarved(true), - _hasStarted(false) + _hasStarted(false), + _averageLoudness(0) { if (numFrameSamples) { _buffer = new int16_t[_sampleCapacity]; @@ -55,18 +56,22 @@ int AudioRingBuffer::parseData(const QByteArray& packet) { return writeData(packet.data() + numBytesPacketHeader, packet.size() - numBytesPacketHeader); } -float AudioRingBuffer::averageLoudnessForBoundarySamples(int numSamples) { +void AudioRingBuffer::updateAverageLoudnessForBoundarySamples(int numSamples) { // ForBoundarySamples means that we expect the number of samples not to roll of the end of the ring buffer - float averageLoudness = 0; + float nextLoudness = 0; for (int i = 0; i < numSamples; ++i) { - averageLoudness += fabsf(_nextOutput[i]); + nextLoudness += fabsf(_nextOutput[i]); } - averageLoudness /= numSamples; - averageLoudness /= MAX_SAMPLE_VALUE; + nextLoudness /= numSamples; + nextLoudness /= MAX_SAMPLE_VALUE; + + const int TRAILING_AVERAGE_FRAMES = 100; + const float CURRENT_FRAME_RATIO = 1.0f / TRAILING_AVERAGE_FRAMES; + const float PREVIOUS_FRAMES_RATIO = 1 - CURRENT_FRAME_RATIO; - return averageLoudness; + _averageLoudness = (_averageLoudness * PREVIOUS_FRAMES_RATIO) + (CURRENT_FRAME_RATIO * nextLoudness); } qint64 AudioRingBuffer::readSamples(int16_t* destination, qint64 maxSamples) { diff --git a/libraries/audio/src/AudioRingBuffer.h b/libraries/audio/src/AudioRingBuffer.h index 0beb45ca18..efc85ac94b 100644 --- a/libraries/audio/src/AudioRingBuffer.h +++ b/libraries/audio/src/AudioRingBuffer.h @@ -50,7 +50,8 @@ public: const int16_t* getNextOutput() { return _nextOutput; } const int16_t* getBuffer() { return _buffer; } - float averageLoudnessForBoundarySamples(int numSamples); + void updateAverageLoudnessForBoundarySamples(int numSamples); + float getAverageLoudness() const { return _averageLoudness; } qint64 readSamples(int16_t* destination, qint64 maxSamples); qint64 writeSamples(const int16_t* source, qint64 maxSamples); @@ -85,6 +86,8 @@ protected: int16_t* _buffer; bool _isStarved; bool _hasStarted; + + float _averageLoudness; }; #endif /* defined(__interface__AudioRingBuffer__) */ diff --git a/libraries/audio/src/PositionalAudioRingBuffer.cpp b/libraries/audio/src/PositionalAudioRingBuffer.cpp index 66a27647d6..ccbe5d3f23 100644 --- a/libraries/audio/src/PositionalAudioRingBuffer.cpp +++ b/libraries/audio/src/PositionalAudioRingBuffer.cpp @@ -50,6 +50,7 @@ int PositionalAudioRingBuffer::parseData(const QByteArray& packet) { int16_t numSilentSamples; memcpy(&numSilentSamples, packet.data() + readBytes, sizeof(int16_t)); + readBytes += sizeof(int16_t); addSilentFrame(numSilentSamples); diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index e5e0e4b3d7..4e57e311eb 100644 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -88,6 +88,17 @@ QByteArray AvatarData::toByteArray() { // Body scale destinationBuffer += packFloatRatioToTwoByte(destinationBuffer, _targetScale); + // Head rotation (NOTE: This needs to become a quaternion to save two bytes) + destinationBuffer += packFloatAngleToTwoByte(destinationBuffer, _headData->getTweakedYaw()); + destinationBuffer += packFloatAngleToTwoByte(destinationBuffer, _headData->getTweakedPitch()); + destinationBuffer += packFloatAngleToTwoByte(destinationBuffer, _headData->getTweakedRoll()); + + // Head lean X,Z (head lateral and fwd/back motion relative to torso) + memcpy(destinationBuffer, &_headData->_leanSideways, sizeof(_headData->_leanSideways)); + destinationBuffer += sizeof(_headData->_leanSideways); + memcpy(destinationBuffer, &_headData->_leanForward, sizeof(_headData->_leanForward)); + destinationBuffer += sizeof(_headData->_leanForward); + // Lookat Position memcpy(destinationBuffer, &_headData->_lookAtPosition, sizeof(_headData->_lookAtPosition)); destinationBuffer += sizeof(_headData->_lookAtPosition); @@ -191,6 +202,21 @@ int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { // Body scale sourceBuffer += unpackFloatRatioFromTwoByte(sourceBuffer, _targetScale); + // Head rotation (NOTE: This needs to become a quaternion to save two bytes) + float headYaw, headPitch, headRoll; + sourceBuffer += unpackFloatAngleFromTwoByte((uint16_t*) sourceBuffer, &headYaw); + sourceBuffer += unpackFloatAngleFromTwoByte((uint16_t*) sourceBuffer, &headPitch); + sourceBuffer += unpackFloatAngleFromTwoByte((uint16_t*) sourceBuffer, &headRoll); + _headData->setYaw(headYaw); + _headData->setPitch(headPitch); + _headData->setRoll(headRoll); + + // Head position relative to pelvis + memcpy(&_headData->_leanSideways, sourceBuffer, sizeof(_headData->_leanSideways)); + sourceBuffer += sizeof(float); + memcpy(&_headData->_leanForward, sourceBuffer, sizeof(_headData->_leanForward)); + sourceBuffer += sizeof(_headData->_leanForward); + // Lookat Position memcpy(&_headData->_lookAtPosition, sourceBuffer, sizeof(_headData->_lookAtPosition)); sourceBuffer += sizeof(_headData->_lookAtPosition); diff --git a/libraries/shared/src/FileDownloader.cpp b/libraries/shared/src/FileDownloader.cpp new file mode 100644 index 0000000000..2b65bbd8df --- /dev/null +++ b/libraries/shared/src/FileDownloader.cpp @@ -0,0 +1,65 @@ +// +// FileDownloader.cpp +// hifi +// +// Created by Clement Brisset on 3/14/14. +// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// +// + +#include +#include +#include +#include + +#include "FileDownloader.h" + +FileDownloader::FileDownloader(const QUrl dataURL, QObject* parent) : + QObject(parent), + _done(false) +{ + connect(&_networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(processReply(QNetworkReply*))); + + QNetworkRequest request(dataURL); + _networkAccessManager.get(request); +} + +void FileDownloader::processReply(QNetworkReply *reply) { + if (reply->error() == QNetworkReply::NoError) { + _downloadedData = reply->readAll(); + } + + reply->deleteLater(); + _done = true; + emit done(reply->error()); +} + +void FileDownloader::waitForFile(int timeout) { + QTimer timer; + QEventLoop loop; + connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); + connect(this, SIGNAL(done(QNetworkReply::NetworkError)), &loop, SLOT(quit())); + + if (!_done) { + if (timeout > 0) { + timer.start(timeout); + } + loop.exec(); + } +} + +QByteArray FileDownloader::download(const QUrl dataURL, int timeout) { + QTimer timer; + QEventLoop loop; + connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit)); + + FileDownloader downloader(dataURL); + connect(&downloader, SIGNAL(done(QNetworkReply::NetworkError)), &loop, SLOT(quit())); + + if (timeout > 0) { + timer.start(timeout); + } + loop.exec(); + + return downloader.getData(); +} \ No newline at end of file diff --git a/libraries/shared/src/FileDownloader.h b/libraries/shared/src/FileDownloader.h new file mode 100644 index 0000000000..593b39b013 --- /dev/null +++ b/libraries/shared/src/FileDownloader.h @@ -0,0 +1,44 @@ +// +// FileDownloader.h +// hifi +// +// Created by Clement Brisset on 3/14/14. +// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// +// + +#ifndef __hifi__FileDownloader__ +#define __hifi__FileDownloader__ + +#include +#include +#include + +class FileDownloader : public QObject { + Q_OBJECT + +public: + FileDownloader(const QUrl dataURL, QObject* parent = NULL); + + void waitForFile(int timeout = 0); + + QByteArray getData() const { return _downloadedData; } + bool done() { return _done; } + + static QByteArray download(const QUrl dataURL, int timeout = 0); + +signals: + void done(QNetworkReply::NetworkError error); + +private slots: + void processReply(QNetworkReply* reply); + +private: + QNetworkAccessManager _networkAccessManager; + QByteArray _downloadedData; + + bool _done; +}; + + +#endif /* defined(__hifi__FileDownloader__) */ diff --git a/libraries/shared/src/FstReader.cpp b/libraries/shared/src/FstReader.cpp index d82ddf68a3..a803583598 100644 --- a/libraries/shared/src/FstReader.cpp +++ b/libraries/shared/src/FstReader.cpp @@ -24,6 +24,7 @@ static const QString NAME_FIELD = "name"; static const QString FILENAME_FIELD = "filename"; static const QString TEXDIR_FIELD = "texdir"; static const QString LOD_FIELD = "lod"; +static const QString HEAD_SPECIFIC_FIELD = "bs"; static const QString MODEL_URL = "/api/v1/models"; @@ -32,6 +33,7 @@ static const int MAX_SIZE = 10 * 1024 * 1024; // 10 MB FstReader::FstReader() : _lodCount(-1), _texturesCount(-1), + _isHead(false), _readyToSend(false), _dataMultiPart(new QHttpMultiPart(QHttpMultiPart::FormDataType)) { @@ -81,13 +83,15 @@ bool FstReader::zip() { } // according to what is read, we modify the command - if (line.first() == NAME_FIELD) { + if (line[1] == HEAD_SPECIFIC_FIELD) { + _isHead = true; + } else if (line[1] == NAME_FIELD) { QHttpPart textPart; textPart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data;" " name=\"model_name\""); textPart.setBody(line[1].toUtf8()); _dataMultiPart->append(textPart); - } else if (line.first() == FILENAME_FIELD) { + } else if (line[1] == FILENAME_FIELD) { QFileInfo fbx(QFileInfo(fst).path() + "/" + line[1]); if (!fbx.exists() || !fbx.isFile()) { // Check existence qDebug() << "[ERROR] FBX file " << fbx.absoluteFilePath() << " doesn't exist."; @@ -101,7 +105,7 @@ bool FstReader::zip() { if (!addPart(_zipDir.path() + "/" + line[1], "fbx")) { return false; } - } else if (line.first() == TEXDIR_FIELD) { // Check existence + } else if (line[1] == TEXDIR_FIELD) { // Check existence QFileInfo texdir(QFileInfo(fst).path() + "/" + line[1]); if (!texdir.exists() || !texdir.isDir()) { qDebug() << "[ERROR] Texture directory " << texdir.absolutePath() << " doesn't exist."; @@ -110,7 +114,7 @@ bool FstReader::zip() { if (!addTextures(texdir)) { // Recursive compress and copy return false; } - } else if (line.first() == LOD_FIELD) { + } else if (line[1] == LOD_FIELD) { QFileInfo lod(QFileInfo(fst).path() + "/" + line[1]); if (!lod.exists() || !lod.isFile()) { // Check existence qDebug() << "[ERROR] FBX file " << lod.absoluteFilePath() << " doesn't exist."; @@ -127,6 +131,17 @@ bool FstReader::zip() { } } + + QHttpPart textPart; + textPart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data;" + " name=\"model_category\""); + if (_isHead) { + textPart.setBody("head"); + } else { + textPart.setBody("skeleton"); + } + _dataMultiPart->append(textPart); + _readyToSend = true; return true; } diff --git a/libraries/shared/src/FstReader.h b/libraries/shared/src/FstReader.h index aab42bd967..1d9da71641 100644 --- a/libraries/shared/src/FstReader.h +++ b/libraries/shared/src/FstReader.h @@ -27,6 +27,7 @@ private: int _lodCount; int _texturesCount; int _totalSize; + bool _isHead; bool _readyToSend; QHttpMultiPart* _dataMultiPart; diff --git a/libraries/shared/src/PacketHeaders.cpp b/libraries/shared/src/PacketHeaders.cpp index 307453d8bf..c7518708ce 100644 --- a/libraries/shared/src/PacketHeaders.cpp +++ b/libraries/shared/src/PacketHeaders.cpp @@ -45,7 +45,9 @@ int packArithmeticallyCodedValue(int value, char* destination) { PacketVersion versionForPacketType(PacketType type) { switch (type) { case PacketTypeAvatarData: - return 2; + return 3; + case PacketTypeEnvironmentData: + return 1; case PacketTypeParticleData: return 1; case PacketTypeDomainList: diff --git a/libraries/voxels/src/EnvironmentData.cpp b/libraries/voxels/src/EnvironmentData.cpp index 5cee88e127..1c9af55abd 100644 --- a/libraries/voxels/src/EnvironmentData.cpp +++ b/libraries/voxels/src/EnvironmentData.cpp @@ -14,6 +14,7 @@ // GameEngine.cpp EnvironmentData::EnvironmentData(int id) : _id(id), + _flat(true), _gravity(0.0f), _atmosphereCenter(0, -1000, 0), _atmosphereInnerRadius(1000), @@ -25,12 +26,23 @@ EnvironmentData::EnvironmentData(int id) : _sunBrightness(20.0f) { } +glm::vec3 EnvironmentData::getAtmosphereCenter(const glm::vec3& cameraPosition) const { + return _atmosphereCenter + (_flat ? glm::vec3(cameraPosition.x, 0.0f, cameraPosition.z) : glm::vec3()); +} + +glm::vec3 EnvironmentData::getSunLocation(const glm::vec3& cameraPosition) const { + return _sunLocation + (_flat ? glm::vec3(cameraPosition.x, 0.0f, cameraPosition.z) : glm::vec3()); +} + int EnvironmentData::getBroadcastData(unsigned char* destinationBuffer) const { unsigned char* bufferStart = destinationBuffer; memcpy(destinationBuffer, &_id, sizeof(_id)); destinationBuffer += sizeof(_id); + memcpy(destinationBuffer, &_flat, sizeof(_flat)); + destinationBuffer += sizeof(_flat); + memcpy(destinationBuffer, &_gravity, sizeof(_gravity)); destinationBuffer += sizeof(_gravity); @@ -67,6 +79,9 @@ int EnvironmentData::parseData(const unsigned char* sourceBuffer, int numBytes) memcpy(&_id, sourceBuffer, sizeof(_id)); sourceBuffer += sizeof(_id); + memcpy(&_flat, sourceBuffer, sizeof(_flat)); + sourceBuffer += sizeof(_flat); + memcpy(&_gravity, sourceBuffer, sizeof(_gravity)); sourceBuffer += sizeof(_gravity); diff --git a/libraries/voxels/src/EnvironmentData.h b/libraries/voxels/src/EnvironmentData.h index 90cc0763fe..627a661e1c 100644 --- a/libraries/voxels/src/EnvironmentData.h +++ b/libraries/voxels/src/EnvironmentData.h @@ -19,6 +19,9 @@ public: void setID(int id) { _id = id; } int getID() const { return _id; } + void setFlat(bool flat) { _flat = flat; } + bool isFlat() const { return _flat; } + void setGravity(float gravity) { _gravity = gravity; } float getGravity() const { return _gravity; } @@ -42,6 +45,9 @@ public: const glm::vec3& getSunLocation() const { return _sunLocation; } float getSunBrightness() const { return _sunBrightness; } + glm::vec3 getAtmosphereCenter(const glm::vec3& cameraPosition) const; + glm::vec3 getSunLocation(const glm::vec3& cameraPosition) const; + int getBroadcastData(unsigned char* destinationBuffer) const; int parseData(const unsigned char* sourceBuffer, int numBytes); @@ -49,6 +55,8 @@ private: int _id; + bool _flat; + float _gravity; glm::vec3 _atmosphereCenter; From 3eb64f5b2933fd11e341ce986a4b7932cbd53d8b Mon Sep 17 00:00:00 2001 From: stojce Date: Fri, 21 Mar 2014 22:45:15 +0100 Subject: [PATCH 015/595] updated interface_en.ts file --- interface/interface_en.ts | 125 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 121 insertions(+), 4 deletions(-) diff --git a/interface/interface_en.ts b/interface/interface_en.ts index 34e3614716..12d9e48589 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -113,22 +113,139 @@ Menu - + Open .ini config file - - + + Text files (*.ini) - + Save .ini config file + + PreferencesDialog + + + + Cancel + + + + + + Save all changes + + + + + + Avatar + + + + + + <html><head/><body><p>Avatar display name <span style=" color:#909090;">(optional)</span></p></body></html> + + + + + + Not showing a name + + + + + + Head + + + + + + Body + + + + + + Advanced Tuning + + + + + + It's not recomended that you play with these settings unless you've looked into exactly what they do. + + + + + + <p>Avatar</p> + + + + + + Vertical field of view + + + + + + Lean scale (applies to Faceshift users) + + + + + + Avatar scale (default is 1.0) + + + + + + Pupil dillation + + + + + + Audio Jitter Buffer Samples (0 for automatic) + + + + + + Faceshift eye detection + + + + + + <html><head/><body><p>Voxels</p></body></html> + + + + + + Maximum voxels + + + + + + Max voxels sent each second + + + QObject From 7c36c4a2b73f1c8b33d440d146eef51d840b3555 Mon Sep 17 00:00:00 2001 From: stojce Date: Sun, 23 Mar 2014 13:20:24 +0100 Subject: [PATCH 016/595] Layout fixes --- interface/interface_en.ts | 82 ++++++++++++++-------------- interface/src/ui/FramelessDialog.cpp | 3 - interface/ui/preferencesDialog.ui | 44 ++++++++++++--- 3 files changed, 78 insertions(+), 51 deletions(-) diff --git a/interface/interface_en.ts b/interface/interface_en.ts index 12d9e48589..7dc5a4c41d 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -14,12 +14,12 @@ - + Open Script - + JavaScript Files (*.js) @@ -132,116 +132,116 @@ PreferencesDialog - - + + Cancel - - + + Save all changes - - + + Avatar - - + + <html><head/><body><p>Avatar display name <span style=" color:#909090;">(optional)</span></p></body></html> - - + + Not showing a name - - + + Head - - + + Body - - + + Advanced Tuning - - + + It's not recomended that you play with these settings unless you've looked into exactly what they do. - - + + <p>Avatar</p> - - + + Vertical field of view - - + + Lean scale (applies to Faceshift users) - - - Avatar scale (default is 1.0) + + + Avatar scale <span style=" color:#909090;">(default is 1.0)</span> - - + + Pupil dillation - - + + Audio Jitter Buffer Samples (0 for automatic) - - + + Faceshift eye detection - - + + <html><head/><body><p>Voxels</p></body></html> - - + + Maximum voxels - - + + Max voxels sent each second diff --git a/interface/src/ui/FramelessDialog.cpp b/interface/src/ui/FramelessDialog.cpp index 1f67e9f4d1..2b9dd42ed7 100644 --- a/interface/src/ui/FramelessDialog.cpp +++ b/interface/src/ui/FramelessDialog.cpp @@ -19,10 +19,7 @@ const int RESIZE_HANDLE_WIDTH = 7; FramelessDialog::FramelessDialog(QWidget *parent, Qt::WindowFlags flags) : QDialog(parent, flags | Qt::FramelessWindowHint), _isResizing(false) { - - setWindowOpacity(0.95); setAttribute(Qt::WA_DeleteOnClose); - installEventFilter(this); } diff --git a/interface/ui/preferencesDialog.ui b/interface/ui/preferencesDialog.ui index 0f33e2a0b0..7692da2943 100644 --- a/interface/ui/preferencesDialog.ui +++ b/interface/ui/preferencesDialog.ui @@ -9,8 +9,8 @@ 0 0 - 610 - 499 + 638 + 652 @@ -25,11 +25,14 @@ 0 + + 0.950000000000000 + 0 - 400 + 560 611 97 @@ -135,7 +138,7 @@ color: #0e7077 0 30 615 - 351 + 491 @@ -527,8 +530,11 @@ padding: 0; 16 + + true + - color: rgb(51, 51, 51) + color: rgb(51, 51, 51); It's not recomended that you play with these settings unless you've looked into exactly what they do. @@ -596,11 +602,14 @@ padding: 0; - color: rgb(51, 51, 51) + Vertical field of view + + 15 + fieldOfViewSpin @@ -701,6 +710,9 @@ padding: 0; Lean scale (applies to Faceshift users) + + 15 + leanScaleSpin @@ -781,7 +793,10 @@ padding: 0; color: rgb(51, 51, 51) - Avatar scale (default is 1.0) + Avatar scale <span style=" color:#909090;">(default is 1.0)</span> + + + 15 avatarScaleSpin @@ -862,6 +877,9 @@ padding: 0; Pupil dillation + + 15 + pupilDilationSlider @@ -938,6 +956,9 @@ padding: 0; Audio Jitter Buffer Samples (0 for automatic) + + 15 + audioJitterSpin @@ -1026,6 +1047,9 @@ padding: 0; Faceshift eye detection + + 15 + faceshiftEyeDeflectionSider @@ -1135,6 +1159,9 @@ padding: 0; Maximum voxels + + 15 + maxVoxelsSpin @@ -1211,6 +1238,9 @@ padding: 0; Max voxels sent each second + + 15 + maxVoxelsPPSSpin From 32502d7b0dbb0ca35981aae7ba574f40ec8ba39e Mon Sep 17 00:00:00 2001 From: stojce Date: Sun, 23 Mar 2014 16:20:29 +0100 Subject: [PATCH 017/595] layout improvements --- interface/interface_en.ts | 62 ++++++++++++-------------- interface/src/Menu.h | 1 + interface/src/ui/PreferencesDialog.cpp | 14 +++--- interface/ui/preferencesDialog.ui | 14 +++--- 4 files changed, 46 insertions(+), 45 deletions(-) diff --git a/interface/interface_en.ts b/interface/interface_en.ts index 7dc5a4c41d..b8534c1779 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -133,115 +133,111 @@ PreferencesDialog - + Cancel - + Save all changes - + + + Avatar - + <html><head/><body><p>Avatar display name <span style=" color:#909090;">(optional)</span></p></body></html> - + Not showing a name - + Head - + Body - + Advanced Tuning - + It's not recomended that you play with these settings unless you've looked into exactly what they do. - - - <p>Avatar</p> - - - - - + + Vertical field of view - - + + Lean scale (applies to Faceshift users) - - + + Avatar scale <span style=" color:#909090;">(default is 1.0)</span> - - + + Pupil dillation - - + + Audio Jitter Buffer Samples (0 for automatic) - - + + Faceshift eye detection - - + + <html><head/><body><p>Voxels</p></body></html> - - + + Maximum voxels - - + + Max voxels sent each second diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 96d5267b9c..2c459a488a 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -75,6 +75,7 @@ public: float getAudioJitterBufferSamples() const { return _audioJitterBufferSamples; } void setAudioJitterBufferSamples(float audioJitterBufferSamples) { _audioJitterBufferSamples = audioJitterBufferSamples; } float getFieldOfView() const { return _fieldOfView; } + void setFieldOfView(float fieldOfView) { _fieldOfView = fieldOfView; } float getFaceshiftEyeDeflection() const { return _faceshiftEyeDeflection; } void setFaceshiftEyeDeflection(float faceshiftEyeDeflection) { _faceshiftEyeDeflection = faceshiftEyeDeflection; } BandwidthDialog* getBandwidthDialog() const { return _bandwidthDialog; } diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index 56dbf8470c..c7f5f19099 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -71,16 +71,16 @@ void PreferencesDialog::loadPreferences() { MyAvatar* myAvatar = Application::getInstance()->getAvatar(); Menu* menuInstance = Menu::getInstance(); - + _displayNameString = myAvatar->getDisplayName(); ui.displayNameEdit->setText(_displayNameString); - + _faceURLString = myAvatar->getHead()->getFaceModel().getURL().toString(); ui.faceURLEdit->setText(_faceURLString); - + _skeletonURLString = myAvatar->getSkeletonModel().getURL().toString(); ui.skeletonURLEdit->setText(_skeletonURLString); - + ui.pupilDilationSlider->setValue(myAvatar->getHead()->getPupilDilation() * ui.pupilDilationSlider->maximum()); @@ -137,10 +137,14 @@ void PreferencesDialog::savePreferences() { Application::getInstance()->resizeGL(Application::getInstance()->getGLWidget()->width(), Application::getInstance()->getGLWidget()->height()); + Menu::getInstance()->setFieldOfView(ui.fieldOfViewSpin->value()); + Menu::getInstance()->setFaceshiftEyeDeflection(ui.faceshiftEyeDeflectionSider->value() / (float)ui.faceshiftEyeDeflectionSider->maximum()); Menu::getInstance()->setMaxVoxelPacketsPerSecond(ui.maxVoxelsPPSSpin->value()); Menu::getInstance()->setAudioJitterBufferSamples(ui.audioJitterSpin->value()); - + + Application::getInstance()->resizeGL(Application::getInstance()->getGLWidget()->width(), + Application::getInstance()->getGLWidget()->height()); } diff --git a/interface/ui/preferencesDialog.ui b/interface/ui/preferencesDialog.ui index 7692da2943..14db1b6d5e 100644 --- a/interface/ui/preferencesDialog.ui +++ b/interface/ui/preferencesDialog.ui @@ -573,7 +573,7 @@ padding: 0; color: #0e7077 - <p>Avatar</p> + Avatar Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft @@ -627,8 +627,8 @@ padding: 0; - 40 - 20 + 0 + 0 @@ -649,8 +649,8 @@ padding: 0; - 70 - 16777215 + 95 + 36 @@ -1100,7 +1100,7 @@ padding: 0; - + 0 @@ -1125,7 +1125,7 @@ padding: 0; color: #0e7077 - <html><head/><body><p>Voxels</p></body></html> + Voxels Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft From e545c2ac6565bcd754e3afd7c170f087ed3454cd Mon Sep 17 00:00:00 2001 From: Lucas Crisman Date: Mon, 24 Mar 2014 14:57:40 -0300 Subject: [PATCH 018/595] Stats tweaks: fonts adjustments --- interface/src/Application.cpp | 8 ++++- interface/src/ui/Stats.cpp | 58 +++++++++++++++++++++++------------ interface/src/ui/Stats.h | 7 +++-- 3 files changed, 49 insertions(+), 24 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 01e68e92d9..5fd6e7366a 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -591,7 +591,13 @@ void Application::resizeGL(int width, int height) { updateProjectionMatrix(); glLoadIdentity(); - Stats::getInstance()->resetWidthOnResizeGL(width); + // update Stats width + int horizontalOffset = 0; + if (Menu::getInstance()->isOptionChecked(MenuOption::Mirror)) { + // mirror is enabled, let's set horizontal offset to give stats some margin + horizontalOffset += MIRROR_VIEW_WIDTH + MIRROR_VIEW_LEFT_PADDING * 2; + } + Stats::getInstance()->resetWidth(width, horizontalOffset); } void Application::updateProjectionMatrix() { diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp index 9f87371c4c..305b5fad57 100644 --- a/interface/src/ui/Stats.cpp +++ b/interface/src/ui/Stats.cpp @@ -2,6 +2,7 @@ // Stats.cpp // interface // +// Created by Lucas Crisman on 22/03/14. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved // @@ -38,9 +39,11 @@ Stats::Stats(): _generalStatsWidth(STATS_GENERAL_MIN_WIDTH), _pingStatsWidth(STATS_PING_MIN_WIDTH), _geoStatsWidth(STATS_GEO_MIN_WIDTH), - _voxelStatsWidth(STATS_VOXEL_MIN_WIDTH) + _voxelStatsWidth(STATS_VOXEL_MIN_WIDTH), + _lastHorizontalOffset(0) { - // no constructor behavior yet, only members initialization + QGLWidget* glWidget = Application::getInstance()->getGLWidget(); + resetWidth(glWidget->width(), 0); } void Stats::toggleExpanded() { @@ -75,15 +78,17 @@ void Stats::checkClick(int mouseX, int mouseY, int mouseDragStartedX, int mouseD statsX += _generalStatsWidth; // ping stats click - lines = _expanded ? 4 : 3; - statsHeight = lines * STATS_PELS_PER_LINE + 10; - if (mouseX > statsX && mouseX < statsX + _pingStatsWidth && mouseY > statsY && mouseY < statsY + statsHeight) { - toggleExpanded(); - return; + if (Menu::getInstance()->isOptionChecked(MenuOption::TestPing)) { + lines = _expanded ? 4 : 3; + statsHeight = lines * STATS_PELS_PER_LINE + 10; + if (mouseX > statsX && mouseX < statsX + _pingStatsWidth && mouseY > statsY && mouseY < statsY + statsHeight) { + toggleExpanded(); + return; + } + statsX += _pingStatsWidth; } - statsX += _pingStatsWidth; - // top-center stats panel click + // geo stats panel click lines = _expanded ? 4 : 3; statsHeight = lines * STATS_PELS_PER_LINE + 10; if (mouseX > statsX && mouseX < statsX + _geoStatsWidth && mouseY > statsY && mouseY < statsY + statsHeight) { @@ -102,24 +107,32 @@ void Stats::checkClick(int mouseX, int mouseY, int mouseDragStartedX, int mouseD } } -void Stats::resetWidthOnResizeGL(int width) { +void Stats::resetWidth(int width, int horizontalOffset) { QGLWidget* glWidget = Application::getInstance()->getGLWidget(); - int extraSpace = glWidget->width() + int extraSpace = glWidget->width() - horizontalOffset -2 - STATS_GENERAL_MIN_WIDTH - - STATS_PING_MIN_WIDTH + - (Menu::getInstance()->isOptionChecked(MenuOption::TestPing) ? STATS_PING_MIN_WIDTH -1 : 0) - STATS_GEO_MIN_WIDTH - - STATS_VOXEL_MIN_WIDTH - - 3; + - STATS_VOXEL_MIN_WIDTH; + + int panels = 4; _generalStatsWidth = STATS_GENERAL_MIN_WIDTH; - _pingStatsWidth = STATS_PING_MIN_WIDTH; + if (Menu::getInstance()->isOptionChecked(MenuOption::TestPing)) { + _pingStatsWidth = STATS_PING_MIN_WIDTH; + } else { + _pingStatsWidth = 0; + panels = 3; + } _geoStatsWidth = STATS_GEO_MIN_WIDTH; _voxelStatsWidth = STATS_VOXEL_MIN_WIDTH; - if (extraSpace > 4) { - _generalStatsWidth += (int) extraSpace / 4; - _pingStatsWidth += (int) extraSpace / 4; - _geoStatsWidth += (int) extraSpace / 4; + if (extraSpace > panels) { + _generalStatsWidth += (int) extraSpace / panels; + if (Menu::getInstance()->isOptionChecked(MenuOption::TestPing)) { + _pingStatsWidth += (int) extraSpace / panels; + } + _geoStatsWidth += (int) extraSpace / panels; _voxelStatsWidth += glWidget->width() - (_generalStatsWidth + _pingStatsWidth + _geoStatsWidth + 3); } } @@ -157,6 +170,11 @@ void Stats::display( QLocale locale(QLocale::English); std::stringstream voxelStats; + if (_lastHorizontalOffset != horizontalOffset) { + resetWidth(glWidget->width(), horizontalOffset); + _lastHorizontalOffset = horizontalOffset; + } + glPointSize(1.0f); // we need to take one avatar out so we don't include ourselves @@ -307,7 +325,7 @@ void Stats::display( VoxelSystem* voxels = Application::getInstance()->getVoxels(); - lines = _expanded ? 11 : 3; + lines = _expanded ? 12 : 3; drawBackground(backgroundColor, horizontalOffset, 0, glWidget->width() - horizontalOffset, lines * STATS_PELS_PER_LINE + 10); horizontalOffset += 5; diff --git a/interface/src/ui/Stats.h b/interface/src/ui/Stats.h index aeb981a0c6..7920c35953 100644 --- a/interface/src/ui/Stats.h +++ b/interface/src/ui/Stats.h @@ -2,6 +2,7 @@ // Stats.h // interface // +// Created by Lucas Crisman on 22/03/14. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. // @@ -9,8 +10,6 @@ #include -//#include "Menu.h" - class Stats: public QObject { Q_OBJECT @@ -23,7 +22,7 @@ public: void toggleExpanded(); void checkClick(int mouseX, int mouseY, int mouseDragStartedX, int mouseDragStartedY, int horizontalOffset); - void resetWidthOnResizeGL(int width); + void resetWidth(int width, int horizontalOffset); void display(const float* color, int horizontalOffset, float fps, int packetsPerSecond, int bytesPerSecond, int voxelPacketsToProcess); private: static Stats* _sharedInstance; @@ -37,4 +36,6 @@ private: int _pingStatsWidth; int _geoStatsWidth; int _voxelStatsWidth; + + int _lastHorizontalOffset; }; \ No newline at end of file From 9af1ddb37a55802620237a0bdcf974dc62a988a5 Mon Sep 17 00:00:00 2001 From: Lucas Crisman Date: Mon, 24 Mar 2014 15:27:17 -0300 Subject: [PATCH 019/595] Stats: fix for stats panels positioning when mirror is enabled --- interface/src/ui/Stats.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp index 305b5fad57..1722732e76 100644 --- a/interface/src/ui/Stats.cpp +++ b/interface/src/ui/Stats.cpp @@ -212,7 +212,7 @@ void Stats::display( } verticalOffset = 0; - horizontalOffset = _generalStatsWidth +1; + horizontalOffset = _lastHorizontalOffset + _generalStatsWidth +1; if (Menu::getInstance()->isOptionChecked(MenuOption::TestPing)) { int pingAudio = 0, pingAvatar = 0, pingVoxel = 0, pingVoxelMax = 0; @@ -281,7 +281,7 @@ void Stats::display( } verticalOffset = 0; - horizontalOffset = _generalStatsWidth + _pingStatsWidth + 2; + horizontalOffset = _lastHorizontalOffset + _generalStatsWidth + _pingStatsWidth + 2; } MyAvatar* myAvatar = Application::getInstance()->getAvatar(); @@ -321,7 +321,7 @@ void Stats::display( } verticalOffset = 0; - horizontalOffset = _generalStatsWidth + _pingStatsWidth + _geoStatsWidth + 3; + horizontalOffset = _lastHorizontalOffset + _generalStatsWidth + _pingStatsWidth + _geoStatsWidth + 3; VoxelSystem* voxels = Application::getInstance()->getVoxels(); From 22a8693b896dfdfba3a2079682539f94f5488bf3 Mon Sep 17 00:00:00 2001 From: stojce Date: Wed, 26 Mar 2014 00:05:11 +0100 Subject: [PATCH 020/595] Overlay behaviour --- interface/interface_en.ts | 129 +++++++++++++++++++++++++-- interface/src/Menu.cpp | 2 +- interface/src/ui/FramelessDialog.cpp | 22 ++++- interface/src/ui/FramelessDialog.h | 3 + 4 files changed, 144 insertions(+), 12 deletions(-) diff --git a/interface/interface_en.ts b/interface/interface_en.ts index 689b45afcf..913ae2c50b 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -4,22 +4,22 @@ Application - + Export Voxels - + Sparse Voxel Octree Files (*.svo) - + Open Script - + JavaScript Files (*.js) @@ -113,22 +113,135 @@ Menu - + Open .ini config file - - + + Text files (*.ini) - + Save .ini config file + + PreferencesDialog + + + + Cancel + + + + + + Save all changes + + + + + + + + Avatar + + + + + + <html><head/><body><p>Avatar display name <span style=" color:#909090;">(optional)</span></p></body></html> + + + + + + Not showing a name + + + + + + Head + + + + + + Body + + + + + + Advanced Tuning + + + + + + It's not recomended that you play with these settings unless you've looked into exactly what they do. + + + + + + Vertical field of view + + + + + + Lean scale (applies to Faceshift users) + + + + + + Avatar scale <span style=" color:#909090;">(default is 1.0)</span> + + + + + + Pupil dillation + + + + + + Audio Jitter Buffer Samples (0 for automatic) + + + + + + Faceshift eye detection + + + + + + Voxels + + + + + + Maximum voxels + + + + + + Max voxels sent each second + + + QObject diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 38a1bc8aaa..7373bb8833 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -714,7 +714,7 @@ void Menu::loginForCurrentDomain() { void Menu::editPreferences() { if (!_preferencesDialog) { - _preferencesDialog = new PreferencesDialog(Application::getInstance()->getGLWidget()); + _preferencesDialog = new PreferencesDialog(Application::getInstance()->getWindow()); _preferencesDialog->show(); } _preferencesDialog->raise(); diff --git a/interface/src/ui/FramelessDialog.cpp b/interface/src/ui/FramelessDialog.cpp index 2b9dd42ed7..d11fd5ae6b 100644 --- a/interface/src/ui/FramelessDialog.cpp +++ b/interface/src/ui/FramelessDialog.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include "Application.h" #include "FramelessDialog.h" @@ -17,20 +18,35 @@ const int RESIZE_HANDLE_WIDTH = 7; FramelessDialog::FramelessDialog(QWidget *parent, Qt::WindowFlags flags) : - QDialog(parent, flags | Qt::FramelessWindowHint), + QDialog(parent, flags | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint), _isResizing(false) { setAttribute(Qt::WA_DeleteOnClose); installEventFilter(this); + + startTimer(20); +} + +void FramelessDialog::timerEvent(QTimerEvent *event) { + move(parentWidget()->pos().x(), parentWidget()->pos().y() + 22); + setFixedHeight(parentWidget()->size().height()); +} + +void FramelessDialog::paintEvent(QPaintEvent* event) { + //move(parentWidget()->pos()); + //resize(size().width(), parentWidget()->size().height()); } void FramelessDialog::showEvent(QShowEvent* event) { QDesktopWidget desktop; // move to upper left - move(desktop.availableGeometry().x(), desktop.availableGeometry().y()); +// move(desktop.availableGeometry().x(), desktop.availableGeometry().y()); + + move(parentWidget()->pos().x(), parentWidget()->pos().y() + 22); // keep full height - resize(size().width(), desktop.availableGeometry().height()); + setFixedHeight(parentWidget()->size().height()); +// resize(size().width(), desktop.availableGeometry().height()); } void FramelessDialog::setStyleSheetFile(const QString& fileName) { diff --git a/interface/src/ui/FramelessDialog.h b/interface/src/ui/FramelessDialog.h index 2bb8d6b85c..3cca9ec4fb 100644 --- a/interface/src/ui/FramelessDialog.h +++ b/interface/src/ui/FramelessDialog.h @@ -14,6 +14,7 @@ #include #include #include +#include class FramelessDialog : public QDialog { Q_OBJECT @@ -28,6 +29,8 @@ protected: virtual void mousePressEvent(QMouseEvent* mouseEvent); virtual void mouseReleaseEvent(QMouseEvent* mouseEvent); virtual void showEvent(QShowEvent* event); + void paintEvent(QPaintEvent* event); + void timerEvent(QTimerEvent *event); private: bool _isResizing; From 8b6db350da404b21a3e4effb6fee6c2126f9eaa6 Mon Sep 17 00:00:00 2001 From: stojce Date: Thu, 27 Mar 2014 21:50:41 +0100 Subject: [PATCH 021/595] Switched to QDockWidget --- interface/interface_en.ts | 76 ++++++++++++++-------------- interface/src/Menu.cpp | 7 +-- interface/src/ui/FramelessDialog.cpp | 58 +++------------------ interface/src/ui/FramelessDialog.h | 12 ++--- interface/ui/preferencesDialog.ui | 5 +- 5 files changed, 55 insertions(+), 103 deletions(-) diff --git a/interface/interface_en.ts b/interface/interface_en.ts index 913ae2c50b..6403e5fdd5 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -132,112 +132,112 @@ PreferencesDialog - - + + Cancel - - + + Save all changes - - - - + + + + Avatar - - + + <html><head/><body><p>Avatar display name <span style=" color:#909090;">(optional)</span></p></body></html> - - + + Not showing a name - - + + Head - - + + Body - - + + Advanced Tuning - - + + It's not recomended that you play with these settings unless you've looked into exactly what they do. - - + + Vertical field of view - - + + Lean scale (applies to Faceshift users) - - + + Avatar scale <span style=" color:#909090;">(default is 1.0)</span> - - + + Pupil dillation - - + + Audio Jitter Buffer Samples (0 for automatic) - - + + Faceshift eye detection - - + + Voxels - - + + Maximum voxels - - + + Max voxels sent each second diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 7373bb8833..5c0fd72eee 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -714,10 +714,11 @@ void Menu::loginForCurrentDomain() { void Menu::editPreferences() { if (!_preferencesDialog) { - _preferencesDialog = new PreferencesDialog(Application::getInstance()->getWindow()); - _preferencesDialog->show(); + Application::getInstance()->getWindow()->addDockWidget(Qt::LeftDockWidgetArea, _preferencesDialog = new PreferencesDialog()); + } else { + Application::getInstance()->getWindow()->removeDockWidget(_preferencesDialog); + _preferencesDialog->close(); } - _preferencesDialog->raise(); } void Menu::goToDomain(const QString newDomain) { diff --git a/interface/src/ui/FramelessDialog.cpp b/interface/src/ui/FramelessDialog.cpp index d11fd5ae6b..40388b2f5f 100644 --- a/interface/src/ui/FramelessDialog.cpp +++ b/interface/src/ui/FramelessDialog.cpp @@ -15,38 +15,17 @@ #include "Application.h" #include "FramelessDialog.h" -const int RESIZE_HANDLE_WIDTH = 7; - FramelessDialog::FramelessDialog(QWidget *parent, Qt::WindowFlags flags) : - QDialog(parent, flags | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint), - _isResizing(false) { + QDockWidget(parent, flags) { setAttribute(Qt::WA_DeleteOnClose); - installEventFilter(this); - startTimer(20); -} + // set as floating + setFeatures(QDockWidget::DockWidgetFloatable); -void FramelessDialog::timerEvent(QTimerEvent *event) { - move(parentWidget()->pos().x(), parentWidget()->pos().y() + 22); - setFixedHeight(parentWidget()->size().height()); -} + // remove titlebar + setTitleBarWidget(new QWidget()); -void FramelessDialog::paintEvent(QPaintEvent* event) { - //move(parentWidget()->pos()); - //resize(size().width(), parentWidget()->size().height()); -} - -void FramelessDialog::showEvent(QShowEvent* event) { - QDesktopWidget desktop; - - // move to upper left -// move(desktop.availableGeometry().x(), desktop.availableGeometry().y()); - - move(parentWidget()->pos().x(), parentWidget()->pos().y() + 22); - - // keep full height - setFixedHeight(parentWidget()->size().height()); -// resize(size().width(), desktop.availableGeometry().height()); + setAllowedAreas(Qt::LeftDockWidgetArea); } void FramelessDialog::setStyleSheetFile(const QString& fileName) { @@ -54,29 +33,6 @@ void FramelessDialog::setStyleSheetFile(const QString& fileName) { QFile styleSheet(Application::resourcesPath() + fileName); if (styleSheet.open(QIODevice::ReadOnly) && globalStyleSheet.open(QIODevice::ReadOnly) ) { QDir::setCurrent(Application::resourcesPath()); - QDialog::setStyleSheet(globalStyleSheet.readAll() + styleSheet.readAll()); + setStyleSheet(globalStyleSheet.readAll() + styleSheet.readAll()); } } - -void FramelessDialog::mousePressEvent(QMouseEvent* mouseEvent) { - - if (abs(mouseEvent->pos().x() - size().width()) < RESIZE_HANDLE_WIDTH && mouseEvent->button() == Qt::LeftButton) { - _isResizing = true; - QApplication::setOverrideCursor(Qt::SizeHorCursor); - } -} - -void FramelessDialog::mouseReleaseEvent(QMouseEvent* mouseEvent) { - QApplication::restoreOverrideCursor(); - _isResizing = false; -} - -void FramelessDialog::mouseMoveEvent(QMouseEvent* mouseEvent) { - if (_isResizing) { - resize(mouseEvent->pos().x(), size().height()); - } -} - -FramelessDialog::~FramelessDialog() { - -} diff --git a/interface/src/ui/FramelessDialog.h b/interface/src/ui/FramelessDialog.h index 3cca9ec4fb..5c55f3de25 100644 --- a/interface/src/ui/FramelessDialog.h +++ b/interface/src/ui/FramelessDialog.h @@ -9,29 +9,27 @@ #ifndef __hifi__FramelessDialog__ #define __hifi__FramelessDialog__ -#include +#include #include #include #include #include #include -class FramelessDialog : public QDialog { +class FramelessDialog : public QDockWidget { Q_OBJECT public: FramelessDialog(QWidget* parent = 0, Qt::WindowFlags flags = 0); - virtual ~FramelessDialog(); void setStyleSheetFile(const QString& fileName); protected: + /* virtual void mouseMoveEvent(QMouseEvent* mouseEvent); virtual void mousePressEvent(QMouseEvent* mouseEvent); virtual void mouseReleaseEvent(QMouseEvent* mouseEvent); - virtual void showEvent(QShowEvent* event); - void paintEvent(QPaintEvent* event); - void timerEvent(QTimerEvent *event); - + */ + private: bool _isResizing; diff --git a/interface/ui/preferencesDialog.ui b/interface/ui/preferencesDialog.ui index 14db1b6d5e..f28bcde60c 100644 --- a/interface/ui/preferencesDialog.ui +++ b/interface/ui/preferencesDialog.ui @@ -2,9 +2,6 @@ PreferencesDialog - - Qt::NonModal - 0 @@ -251,7 +248,7 @@ color: #0e7077 280 - 20 + 0 From 252326726980ec2bb3ce601ad86321a4944ced26 Mon Sep 17 00:00:00 2001 From: stojce Date: Thu, 27 Mar 2014 22:02:45 +0100 Subject: [PATCH 022/595] i18n file updates --- interface/interface_en.ts | 121 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 117 insertions(+), 4 deletions(-) diff --git a/interface/interface_en.ts b/interface/interface_en.ts index da8827d89d..48b395339e 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -113,22 +113,135 @@ Menu - + Open .ini config file - - + + Text files (*.ini) - + Save .ini config file + + PreferencesDialog + + + + Cancel + + + + + + Save all changes + + + + + + + + Avatar + + + + + + <html><head/><body><p>Avatar display name <span style=" color:#909090;">(optional)</span></p></body></html> + + + + + + Not showing a name + + + + + + Head + + + + + + Body + + + + + + Advanced Tuning + + + + + + It's not recomended that you play with these settings unless you've looked into exactly what they do. + + + + + + Vertical field of view + + + + + + Lean scale (applies to Faceshift users) + + + + + + Avatar scale <span style=" color:#909090;">(default is 1.0)</span> + + + + + + Pupil dillation + + + + + + Audio Jitter Buffer Samples (0 for automatic) + + + + + + Faceshift eye detection + + + + + + Voxels + + + + + + Maximum voxels + + + + + + Max voxels sent each second + + + QObject From 0cb9bec1aa372322bfb74d672bf1b5bfbe959bb5 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 27 Mar 2014 19:29:18 -0700 Subject: [PATCH 023/595] keep SharedNodePointer in the OctreeSendThread --- .../src/octree/OctreeSendThread.cpp | 22 +++++-------------- .../src/octree/OctreeSendThread.h | 1 + 2 files changed, 6 insertions(+), 17 deletions(-) diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index 4105b21eb8..6ee7904c55 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -21,6 +21,7 @@ quint64 endSceneSleepTime = 0; OctreeSendThread::OctreeSendThread(OctreeServer* myServer, SharedNodePointer node) : _myServer(myServer), + _node(node), _nodeUUID(node->getUUID()), _packetData(), _nodeMissingCount(0), @@ -45,6 +46,7 @@ OctreeSendThread::~OctreeSendThread() { qDebug() << qPrintable(safeServerName) << "server [" << _myServer << "]: client disconnected " "- ending sending thread [" << this << "]"; OctreeServer::clientDisconnected(); + _node.clear(); } void OctreeSendThread::setIsShuttingDown() { @@ -74,28 +76,14 @@ bool OctreeSendThread::process() { // don't do any send processing until the initial load of the octree is complete... if (_myServer->isInitialLoadComplete()) { - SharedNodePointer node = NodeList::getInstance()->nodeWithUUID(_nodeUUID, false); - if (node) { + if (!_node.isNull()) { _nodeMissingCount = 0; - OctreeQueryNode* nodeData = static_cast(node->getLinkedData()); + OctreeQueryNode* nodeData = static_cast(_node->getLinkedData()); // Sometimes the node data has not yet been linked, in which case we can't really do anything if (nodeData && !nodeData->isShuttingDown()) { bool viewFrustumChanged = nodeData->updateCurrentViewFrustum(); - packetDistributor(node, nodeData, viewFrustumChanged); - } - } else { - _nodeMissingCount++; - const int MANY_FAILED_LOCKS = 1; - if (_nodeMissingCount >= MANY_FAILED_LOCKS) { - - QString safeServerName("Octree"); - if (_myServer) { - safeServerName = _myServer->getMyServerName(); - } - - qDebug() << qPrintable(safeServerName) << "server: sending thread [" << this << "]" - << "failed to get nodeWithUUID() " << _nodeUUID <<". Failed:" << _nodeMissingCount << "times"; + packetDistributor(_node, nodeData, viewFrustumChanged); } } } diff --git a/assignment-client/src/octree/OctreeSendThread.h b/assignment-client/src/octree/OctreeSendThread.h index 4b1b6d8c92..ef968707f9 100644 --- a/assignment-client/src/octree/OctreeSendThread.h +++ b/assignment-client/src/octree/OctreeSendThread.h @@ -39,6 +39,7 @@ protected: private: OctreeServer* _myServer; + SharedNodePointer _node; QUuid _nodeUUID; int handlePacketSend(const SharedNodePointer& node, OctreeQueryNode* nodeData, int& trueBytesSent, int& truePacketsSent); From 8856a609a4436b55c449708d6031287e97669a7f Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 28 Mar 2014 09:46:23 -0700 Subject: [PATCH 024/595] first cut at migrating to SharedOctreeServerPointer for ref count management of OctreeServer --- .../src/octree/OctreeQueryNode.cpp | 2 +- .../src/octree/OctreeQueryNode.h | 3 +- .../src/octree/OctreeSendThread.cpp | 41 ++++++++++--------- .../src/octree/OctreeSendThread.h | 9 ++-- assignment-client/src/octree/OctreeServer.cpp | 13 ++++-- assignment-client/src/octree/OctreeServer.h | 6 ++- 6 files changed, 43 insertions(+), 31 deletions(-) diff --git a/assignment-client/src/octree/OctreeQueryNode.cpp b/assignment-client/src/octree/OctreeQueryNode.cpp index 984ce42631..ab7b2f65fd 100644 --- a/assignment-client/src/octree/OctreeQueryNode.cpp +++ b/assignment-client/src/octree/OctreeQueryNode.cpp @@ -76,7 +76,7 @@ void OctreeQueryNode::deleteLater() { } -void OctreeQueryNode::initializeOctreeSendThread(OctreeServer* octreeServer, SharedNodePointer node) { +void OctreeQueryNode::initializeOctreeSendThread(const SharedOctreeServerPointer& octreeServer, SharedNodePointer node) { // Create octree sending thread... _octreeSendThread = new OctreeSendThread(octreeServer, node); _octreeSendThread->initialize(true); diff --git a/assignment-client/src/octree/OctreeQueryNode.h b/assignment-client/src/octree/OctreeQueryNode.h index 17d6f6337c..ace1235908 100644 --- a/assignment-client/src/octree/OctreeQueryNode.h +++ b/assignment-client/src/octree/OctreeQueryNode.h @@ -21,6 +21,7 @@ class OctreeSendThread; class OctreeServer; +typedef QSharedPointer SharedOctreeServerPointer; class OctreeQueryNode : public OctreeQuery { Q_OBJECT @@ -83,7 +84,7 @@ public: OctreeSceneStats stats; - void initializeOctreeSendThread(OctreeServer* octreeServer, SharedNodePointer node); + void initializeOctreeSendThread(const SharedOctreeServerPointer& octreeServer, SharedNodePointer node); bool isOctreeSendThreadInitalized() { return _octreeSendThread; } void dumpOutOfView(); diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index 6ee7904c55..ef115167af 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -19,7 +19,7 @@ quint64 startSceneSleepTime = 0; quint64 endSceneSleepTime = 0; -OctreeSendThread::OctreeSendThread(OctreeServer* myServer, SharedNodePointer node) : +OctreeSendThread::OctreeSendThread(const SharedOctreeServerPointer& myServer, SharedNodePointer node) : _myServer(myServer), _node(node), _nodeUUID(node->getUUID()), @@ -29,7 +29,7 @@ OctreeSendThread::OctreeSendThread(OctreeServer* myServer, SharedNodePointer nod _isShuttingDown(false) { QString safeServerName("Octree"); - if (_myServer) { + if (!_myServer.isNull()) { safeServerName = _myServer->getMyServerName(); } qDebug() << qPrintable(safeServerName) << "server [" << _myServer << "]: client connected " @@ -40,7 +40,7 @@ OctreeSendThread::OctreeSendThread(OctreeServer* myServer, SharedNodePointer nod OctreeSendThread::~OctreeSendThread() { QString safeServerName("Octree"); - if (_myServer) { + if (!_myServer.isNull()) { safeServerName = _myServer->getMyServerName(); } qDebug() << qPrintable(safeServerName) << "server [" << _myServer << "]: client disconnected " @@ -63,6 +63,11 @@ bool OctreeSendThread::process() { return false; // exit early if we're shutting down } + // check that our WeakPointer to our server is still valid + if (_myServer.isNull()) { + return false; // exit early if it's not, it means the server is shutting down + } + OctreeServer::didProcess(this); float lockWaitElapsedUsec = OctreeServer::SKIP_TIME; @@ -83,7 +88,7 @@ bool OctreeSendThread::process() { // Sometimes the node data has not yet been linked, in which case we can't really do anything if (nodeData && !nodeData->isShuttingDown()) { bool viewFrustumChanged = nodeData->updateCurrentViewFrustum(); - packetDistributor(_node, nodeData, viewFrustumChanged); + packetDistributor(nodeData, viewFrustumChanged); } } } @@ -119,8 +124,7 @@ quint64 OctreeSendThread::_totalBytes = 0; quint64 OctreeSendThread::_totalWastedBytes = 0; quint64 OctreeSendThread::_totalPackets = 0; -int OctreeSendThread::handlePacketSend(const SharedNodePointer& node, - OctreeQueryNode* nodeData, int& trueBytesSent, int& truePacketsSent) { +int OctreeSendThread::handlePacketSend(OctreeQueryNode* nodeData, int& trueBytesSent, int& truePacketsSent) { OctreeServer::didHandlePacketSend(this); @@ -180,12 +184,12 @@ int OctreeSendThread::handlePacketSend(const SharedNodePointer& node, // actually send it OctreeServer::didCallWriteDatagram(this); - NodeList::getInstance()->writeDatagram((char*) statsMessage, statsMessageLength, SharedNodePointer(node)); + NodeList::getInstance()->writeDatagram((char*) statsMessage, statsMessageLength, _node); packetSent = true; } else { // not enough room in the packet, send two packets OctreeServer::didCallWriteDatagram(this); - NodeList::getInstance()->writeDatagram((char*) statsMessage, statsMessageLength, SharedNodePointer(node)); + NodeList::getInstance()->writeDatagram((char*) statsMessage, statsMessageLength, _node); // since a stats message is only included on end of scene, don't consider any of these bytes "wasted", since // there was nothing else to send. @@ -204,8 +208,7 @@ int OctreeSendThread::handlePacketSend(const SharedNodePointer& node, packetsSent++; OctreeServer::didCallWriteDatagram(this); - NodeList::getInstance()->writeDatagram((char*) nodeData->getPacket(), nodeData->getPacketLength(), - SharedNodePointer(node)); + NodeList::getInstance()->writeDatagram((char*) nodeData->getPacket(), nodeData->getPacketLength(), _node); packetSent = true; @@ -225,8 +228,7 @@ int OctreeSendThread::handlePacketSend(const SharedNodePointer& node, if (nodeData->isPacketWaiting() && !nodeData->isShuttingDown()) { // just send the voxel packet OctreeServer::didCallWriteDatagram(this); - NodeList::getInstance()->writeDatagram((char*) nodeData->getPacket(), nodeData->getPacketLength(), - SharedNodePointer(node)); + NodeList::getInstance()->writeDatagram((char*) nodeData->getPacket(), nodeData->getPacketLength(), _node); packetSent = true; int thisWastedBytes = MAX_PACKET_SIZE - nodeData->getPacketLength(); @@ -253,7 +255,8 @@ int OctreeSendThread::handlePacketSend(const SharedNodePointer& node, } /// Version of voxel distributor that sends the deepest LOD level at once -int OctreeSendThread::packetDistributor(const SharedNodePointer& node, OctreeQueryNode* nodeData, bool viewFrustumChanged) { +int OctreeSendThread::packetDistributor(OctreeQueryNode* nodeData, bool viewFrustumChanged) { + OctreeServer::didPacketDistributor(this); // if shutting down, exit early @@ -283,7 +286,7 @@ int OctreeSendThread::packetDistributor(const SharedNodePointer& node, OctreeQue // then let's just send that waiting packet. if (!nodeData->getCurrentPacketFormatMatches()) { if (nodeData->isPacketWaiting()) { - packetsSentThisInterval += handlePacketSend(node, nodeData, trueBytesSent, truePacketsSent); + packetsSentThisInterval += handlePacketSend(nodeData, trueBytesSent, truePacketsSent); } else { nodeData->resetOctreePacket(); } @@ -324,7 +327,7 @@ int OctreeSendThread::packetDistributor(const SharedNodePointer& node, OctreeQue //unsigned long encodeTime = nodeData->stats.getTotalEncodeTime(); //unsigned long elapsedTime = nodeData->stats.getElapsedTime(); - int packetsJustSent = handlePacketSend(node, nodeData, trueBytesSent, truePacketsSent); + int packetsJustSent = handlePacketSend(nodeData, trueBytesSent, truePacketsSent); packetsSentThisInterval += packetsJustSent; // If we're starting a full scene, then definitely we want to empty the nodeBag @@ -475,7 +478,7 @@ int OctreeSendThread::packetDistributor(const SharedNodePointer& node, OctreeQue if (writtenSize > nodeData->getAvailable()) { - packetsSentThisInterval += handlePacketSend(node, nodeData, trueBytesSent, truePacketsSent); + packetsSentThisInterval += handlePacketSend(nodeData, trueBytesSent, truePacketsSent); } nodeData->writeToPacket(_packetData.getFinalizedData(), _packetData.getFinalizedSize()); @@ -497,7 +500,7 @@ int OctreeSendThread::packetDistributor(const SharedNodePointer& node, OctreeQue int targetSize = MAX_OCTREE_PACKET_DATA_SIZE; if (sendNow) { quint64 packetSendingStart = usecTimestampNow(); - packetsSentThisInterval += handlePacketSend(node, nodeData, trueBytesSent, truePacketsSent); + packetsSentThisInterval += handlePacketSend(nodeData, trueBytesSent, truePacketsSent); quint64 packetSendingEnd = usecTimestampNow(); packetSendingElapsedUsec = (float)(packetSendingEnd - packetSendingStart); @@ -530,8 +533,8 @@ int OctreeSendThread::packetDistributor(const SharedNodePointer& node, OctreeQue // Here's where we can/should allow the server to send other data... // send the environment packet // TODO: should we turn this into a while loop to better handle sending multiple special packets - if (_myServer->hasSpecialPacketToSend(node) && !nodeData->isShuttingDown()) { - trueBytesSent += _myServer->sendSpecialPacket(node); + if (_myServer->hasSpecialPacketToSend(_node) && !nodeData->isShuttingDown()) { + trueBytesSent += _myServer->sendSpecialPacket(_node); truePacketsSent++; packetsSentThisInterval++; } diff --git a/assignment-client/src/octree/OctreeSendThread.h b/assignment-client/src/octree/OctreeSendThread.h index ef968707f9..bcaa9baf0e 100644 --- a/assignment-client/src/octree/OctreeSendThread.h +++ b/assignment-client/src/octree/OctreeSendThread.h @@ -16,12 +16,11 @@ #include "OctreeQueryNode.h" #include "OctreeServer.h" - /// Threaded processor for sending voxel packets to a single client class OctreeSendThread : public GenericThread { Q_OBJECT public: - OctreeSendThread(OctreeServer* myServer, SharedNodePointer node); + OctreeSendThread(const SharedOctreeServerPointer& myServer, SharedNodePointer node); virtual ~OctreeSendThread(); void setIsShuttingDown(); @@ -38,12 +37,12 @@ protected: virtual bool process(); private: - OctreeServer* _myServer; + SharedOctreeServerPointer _myServer; SharedNodePointer _node; QUuid _nodeUUID; - int handlePacketSend(const SharedNodePointer& node, OctreeQueryNode* nodeData, int& trueBytesSent, int& truePacketsSent); - int packetDistributor(const SharedNodePointer& node, OctreeQueryNode* nodeData, bool viewFrustumChanged); + int handlePacketSend(OctreeQueryNode* nodeData, int& trueBytesSent, int& truePacketsSent); + int packetDistributor(OctreeQueryNode* nodeData, bool viewFrustumChanged); OctreePacketData _packetData; diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index fd3f9e6cb7..d711215643 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -19,7 +19,7 @@ #include "OctreeServer.h" #include "OctreeServerConsts.h" -OctreeServer* OctreeServer::_instance = NULL; +SharedOctreeServerPointer OctreeServer::_instance; int OctreeServer::_clientCount = 0; const int MOVING_AVERAGE_SAMPLE_COUNTS = 1000000; @@ -203,7 +203,7 @@ void OctreeServer::trackProcessWaitTime(float time) { } void OctreeServer::attachQueryNodeToNode(Node* newNode) { - if (!newNode->getLinkedData()) { + if (!newNode->getLinkedData() && !_instance.isNull()) { OctreeQueryNode* newQueryNodeData = _instance->createOctreeQueryNode(); newQueryNodeData->init(); newNode->setLinkedData(newQueryNodeData); @@ -231,7 +231,8 @@ OctreeServer::OctreeServer(const QByteArray& packet) : _started(time(0)), _startedUSecs(usecTimestampNow()) { - _instance = this; + assert(_instance.isNull()); // you should only ever have one instance at a time! + _instance = SharedOctreeServerPointer(this); _averageLoopTime.updateAverage(0); qDebug() << "Octree server starting... [" << this << "]"; } @@ -835,7 +836,8 @@ void OctreeServer::readPendingDatagrams() { if (debug) { qDebug() << "calling initializeOctreeSendThread()... node:" << *matchingNode; } - nodeData->initializeOctreeSendThread(this, matchingNode); + SharedOctreeServerPointer myServer(this); + nodeData->initializeOctreeSendThread(myServer, matchingNode); } } } else if (packetType == PacketTypeJurisdictionRequest) { @@ -1058,6 +1060,9 @@ void OctreeServer::aboutToFinish() { nodeKilled(node); } qDebug() << qPrintable(_safeServerName) << "server ENDING about to finish..."; + + // release our reference to the instance, this will allow the shared pointers to properly unwind + _instance.clear(); } QString OctreeServer::getUptime() { diff --git a/assignment-client/src/octree/OctreeServer.h b/assignment-client/src/octree/OctreeServer.h index 63d43b6634..5cf5fda59f 100644 --- a/assignment-client/src/octree/OctreeServer.h +++ b/assignment-client/src/octree/OctreeServer.h @@ -13,6 +13,7 @@ #include #include #include +#include #include @@ -26,6 +27,9 @@ const int DEFAULT_PACKETS_PER_INTERVAL = 2000; // some 120,000 packets per second total +class OctreeServer; +typedef QSharedPointer SharedOctreeServerPointer; + /// Handles assignments of type OctreeServer - sending octrees to various clients. class OctreeServer : public ThreadedAssignment, public HTTPRequestHandler { Q_OBJECT @@ -154,7 +158,7 @@ protected: OctreeInboundPacketProcessor* _octreeInboundPacketProcessor; OctreePersistThread* _persistThread; - static OctreeServer* _instance; + static SharedOctreeServerPointer _instance; time_t _started; quint64 _startedUSecs; From 540649071970e5a2f3f25609af1768ecac7f6b3a Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Fri, 28 Mar 2014 11:00:30 -0700 Subject: [PATCH 025/595] rename _shapes -> _jointShapes also stubbed Model::createBoundingShape() --- interface/src/avatar/SkeletonModel.cpp | 8 +++--- interface/src/renderer/Model.cpp | 37 +++++++++++++++----------- interface/src/renderer/Model.h | 5 ++-- 3 files changed, 28 insertions(+), 22 deletions(-) diff --git a/interface/src/avatar/SkeletonModel.cpp b/interface/src/avatar/SkeletonModel.cpp index 3c5f5cae6a..9d67709fde 100644 --- a/interface/src/avatar/SkeletonModel.cpp +++ b/interface/src/avatar/SkeletonModel.cpp @@ -63,7 +63,7 @@ void SkeletonModel::simulate(float deltaTime, bool fullUpdate) { } void SkeletonModel::getHandShapes(int jointIndex, QVector& shapes) const { - if (jointIndex < 0 || jointIndex >= int(_shapes.size())) { + if (jointIndex < 0 || jointIndex >= int(_jointShapes.size())) { return; } if (jointIndex == getLeftHandJointIndex() @@ -75,16 +75,16 @@ void SkeletonModel::getHandShapes(int jointIndex, QVector& shapes) int parentIndex = joint.parentIndex; if (i == jointIndex) { // this shape is the hand - shapes.push_back(_shapes[i]); + shapes.push_back(_jointShapes[i]); if (parentIndex != -1) { // also add the forearm - shapes.push_back(_shapes[parentIndex]); + shapes.push_back(_jointShapes[parentIndex]); } } else { while (parentIndex != -1) { if (parentIndex == jointIndex) { // this shape is a child of the hand - shapes.push_back(_shapes[i]); + shapes.push_back(_jointShapes[i]); break; } parentIndex = geometry.joints[parentIndex].parentIndex; diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index df5560a4b1..ceddcd009a 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -136,13 +136,13 @@ void Model::reset() { } void Model::clearShapes() { - for (int i = 0; i < _shapes.size(); ++i) { - delete _shapes[i]; + for (int i = 0; i < _jointShapes.size(); ++i) { + delete _jointShapes[i]; } - _shapes.clear(); + _jointShapes.clear(); } -void Model::createCollisionShapes() { +void Model::createJointCollisionShapes() { clearShapes(); const FBXGeometry& geometry = _geometry->getFBXGeometry(); float uniformScale = extractUniformScale(_scale); @@ -156,16 +156,21 @@ void Model::createCollisionShapes() { float halfHeight = 0.5f * uniformScale * joint.distanceToParent; CapsuleShape* shape = new CapsuleShape(radius, halfHeight); shape->setPosition(position); - _shapes.push_back(shape); + _jointShapes.push_back(shape); } else { SphereShape* shape = new SphereShape(radius, position); - _shapes.push_back(shape); + _jointShapes.push_back(shape); } } } +void Model::createBoundingShape() { + //const FBXGeometry& geometry = _geometry->getFBXGeometry(); + //float uniformScale = extractUniformScale(_scale); +} + void Model::updateShapePositions() { - if (_shapesAreDirty && _shapes.size() == _jointStates.size()) { + if (_shapesAreDirty && _jointShapes.size() == _jointStates.size()) { _boundingRadius = 0.f; float uniformScale = extractUniformScale(_scale); const FBXGeometry& geometry = _geometry->getFBXGeometry(); @@ -174,8 +179,8 @@ void Model::updateShapePositions() { // shape position and rotation need to be in world-frame glm::vec3 jointToShapeOffset = uniformScale * (_jointStates[i].combinedRotation * joint.shapePosition); glm::vec3 worldPosition = extractTranslation(_jointStates[i].transform) + jointToShapeOffset + _translation; - _shapes[i]->setPosition(worldPosition); - _shapes[i]->setRotation(_jointStates[i].combinedRotation * joint.shapeRotation); + _jointShapes[i]->setPosition(worldPosition); + _jointShapes[i]->setRotation(_jointStates[i].combinedRotation * joint.shapeRotation); float distance2 = glm::distance2(worldPosition, _translation); if (distance2 > _boundingRadius) { _boundingRadius = distance2; @@ -401,8 +406,8 @@ bool Model::findCollisions(const QVector shapes, CollisionList& co bool collided = false; for (int i = 0; i < shapes.size(); ++i) { const Shape* theirShape = shapes[i]; - for (int j = 0; j < _shapes.size(); ++j) { - const Shape* ourShape = _shapes[j]; + for (int j = 0; j < _jointShapes.size(); ++j) { + const Shape* ourShape = _jointShapes[j]; if (ShapeCollider::shapeShape(theirShape, ourShape, collisions)) { collided = true; } @@ -417,7 +422,7 @@ bool Model::findSphereCollisions(const glm::vec3& sphereCenter, float sphereRadi updateShapePositions(); SphereShape sphere(sphereRadius, sphereCenter); const FBXGeometry& geometry = _geometry->getFBXGeometry(); - for (int i = 0; i < _shapes.size(); i++) { + for (int i = 0; i < _jointShapes.size(); i++) { const FBXJoint& joint = geometry.joints[i]; if (joint.parentIndex != -1) { if (skipIndex != -1) { @@ -431,7 +436,7 @@ bool Model::findSphereCollisions(const glm::vec3& sphereCenter, float sphereRadi } while (ancestorIndex != -1); } } - if (ShapeCollider::shapeShape(&sphere, _shapes[i], collisions)) { + if (ShapeCollider::shapeShape(&sphere, _jointShapes[i], collisions)) { CollisionInfo* collision = collisions.getLastCollision(); collision->_type = MODEL_COLLISION; collision->_data = (void*)(this); @@ -578,7 +583,7 @@ void Model::simulate(float deltaTime, bool fullUpdate, const QVector _attachments.append(model); } fullUpdate = true; - createCollisionShapes(); + createJointCollisionShapes(); } // exit early if we don't have to perform a full update @@ -825,10 +830,10 @@ void Model::renderCollisionProxies(float alpha) { Application::getInstance()->loadTranslatedViewMatrix(_translation); updateShapePositions(); const int BALL_SUBDIVISIONS = 10; - for (int i = 0; i < _shapes.size(); i++) { + for (int i = 0; i < _jointShapes.size(); i++) { glPushMatrix(); - Shape* shape = _shapes[i]; + Shape* shape = _jointShapes[i]; if (shape->getType() == Shape::SPHERE_SHAPE) { // shapes are stored in world-frame, so we have to transform into model frame diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index 3fdf1cd291..0b05fab2bf 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -55,7 +55,8 @@ public: void init(); void reset(); void clearShapes(); - void createCollisionShapes(); + void createJointCollisionShapes(); + void createBoundingShape(); void updateShapePositions(); void simulate(float deltaTime, bool fullUpdate = true); bool render(float alpha = 1.0f, bool forShadowMap = false); @@ -203,7 +204,7 @@ protected: bool _shapesAreDirty; QVector _jointStates; - QVector _shapes; + QVector _jointShapes; class MeshState { public: From ce6af9ecb84a5dd63580fd4f69718f04a48b5521 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 28 Mar 2014 11:04:27 -0700 Subject: [PATCH 026/595] added debug destructor to persist thread --- libraries/octree/src/OctreePersistThread.cpp | 4 ++++ libraries/octree/src/OctreePersistThread.h | 1 + 2 files changed, 5 insertions(+) diff --git a/libraries/octree/src/OctreePersistThread.cpp b/libraries/octree/src/OctreePersistThread.cpp index 29715f9d90..6c0c0d9bfe 100644 --- a/libraries/octree/src/OctreePersistThread.cpp +++ b/libraries/octree/src/OctreePersistThread.cpp @@ -23,6 +23,10 @@ OctreePersistThread::OctreePersistThread(Octree* tree, const QString& filename, { } +OctreePersistThread::~OctreePersistThread() { + qDebug() << "OctreePersistThread::~OctreePersistThread()..."; +} + bool OctreePersistThread::process() { if (!_initialLoadComplete) { diff --git a/libraries/octree/src/OctreePersistThread.h b/libraries/octree/src/OctreePersistThread.h index ce6190b0e6..8e70733192 100644 --- a/libraries/octree/src/OctreePersistThread.h +++ b/libraries/octree/src/OctreePersistThread.h @@ -22,6 +22,7 @@ public: static const int DEFAULT_PERSIST_INTERVAL = 1000 * 30; // every 30 seconds OctreePersistThread(Octree* tree, const QString& filename, int persistInterval = DEFAULT_PERSIST_INTERVAL); + ~OctreePersistThread(); bool isInitialLoadComplete() const { return _initialLoadComplete; } quint64 getLoadElapsedTime() const { return _loadTimeUSecs; } From 640dbaacab83bff79813d8f94981426f663a9c13 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 28 Mar 2014 11:05:54 -0700 Subject: [PATCH 027/595] migration to shared pointers --- .../src/octree/OctreeSendThread.cpp | 31 ++++++++++------- assignment-client/src/octree/OctreeServer.cpp | 33 ++++++++++++++----- assignment-client/src/octree/OctreeServer.h | 2 +- 3 files changed, 45 insertions(+), 21 deletions(-) diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index ef115167af..c760963310 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -28,25 +28,34 @@ OctreeSendThread::OctreeSendThread(const SharedOctreeServerPointer& myServer, Sh _processLock(), _isShuttingDown(false) { - QString safeServerName("Octree"); - if (!_myServer.isNull()) { - safeServerName = _myServer->getMyServerName(); - } - qDebug() << qPrintable(safeServerName) << "server [" << _myServer << "]: client connected " + qDebug() << qPrintable(_myServer->getMyServerName()) << "server [" << _myServer.data() << "]: client connected " "- starting sending thread [" << this << "]"; OctreeServer::clientConnected(); } -OctreeSendThread::~OctreeSendThread() { - QString safeServerName("Octree"); - if (!_myServer.isNull()) { - safeServerName = _myServer->getMyServerName(); - } - qDebug() << qPrintable(safeServerName) << "server [" << _myServer << "]: client disconnected " +OctreeSendThread::~OctreeSendThread() { + QString serverName(_myServer->getMyServerName()); + + qDebug() << qPrintable(serverName) << "server [" << _myServer.data() << "]: client disconnected " "- ending sending thread [" << this << "]"; OctreeServer::clientDisconnected(); + + qDebug() << qPrintable(serverName) << "server [" << _myServer.data() << "]: " + "- OctreeSendThread::~OctreeSendThread() this=[" << this << "]" + "line: " << __LINE__; + _node.clear(); + + qDebug() << qPrintable(serverName) << "server [" << _myServer.data() << "]: " + "- OctreeSendThread::~OctreeSendThread() this=[" << this << "]" + "line: " << __LINE__; + void* serverPtr = _myServer.data(); + _myServer.clear(); + + qDebug() << qPrintable(serverName) << "server [" << serverPtr << "]: " + "- OctreeSendThread::~OctreeSendThread() this=[" << this << "]" + "line: " << __LINE__; } void OctreeSendThread::setIsShuttingDown() { diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index d711215643..e5c8cd262c 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -19,7 +19,7 @@ #include "OctreeServer.h" #include "OctreeServerConsts.h" -SharedOctreeServerPointer OctreeServer::_instance; +OctreeServer* OctreeServer::_instance; int OctreeServer::_clientCount = 0; const int MOVING_AVERAGE_SAMPLE_COUNTS = 1000000; @@ -203,7 +203,7 @@ void OctreeServer::trackProcessWaitTime(float time) { } void OctreeServer::attachQueryNodeToNode(Node* newNode) { - if (!newNode->getLinkedData() && !_instance.isNull()) { + if (!newNode->getLinkedData() && _instance) { OctreeQueryNode* newQueryNodeData = _instance->createOctreeQueryNode(); newQueryNodeData->init(); newNode->setLinkedData(newQueryNodeData); @@ -231,8 +231,11 @@ OctreeServer::OctreeServer(const QByteArray& packet) : _started(time(0)), _startedUSecs(usecTimestampNow()) { - assert(_instance.isNull()); // you should only ever have one instance at a time! - _instance = SharedOctreeServerPointer(this); + assert(!_instance); // you should only ever have one instance at a time! + + qDebug() << "Octree Server starting... setting _instance to=[" << this << "]"; + _instance = this; + _averageLoopTime.updateAverage(0); qDebug() << "Octree server starting... [" << this << "]"; } @@ -245,25 +248,40 @@ OctreeServer::~OctreeServer() { } delete[] _parsedArgV; } + qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; if (_jurisdictionSender) { _jurisdictionSender->terminate(); _jurisdictionSender->deleteLater(); } + qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; + if (_octreeInboundPacketProcessor) { _octreeInboundPacketProcessor->terminate(); _octreeInboundPacketProcessor->deleteLater(); } + qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; + if (_persistThread) { + qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; _persistThread->terminate(); + qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; _persistThread->deleteLater(); + qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; } + qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; + delete _jurisdiction; _jurisdiction = NULL; qDebug() << qPrintable(_safeServerName) << "server DONE shutting down... [" << this << "]"; + + qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; + + _instance = NULL; // we are gone + qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; } void OctreeServer::initHTTPManager(int port) { @@ -836,8 +854,7 @@ void OctreeServer::readPendingDatagrams() { if (debug) { qDebug() << "calling initializeOctreeSendThread()... node:" << *matchingNode; } - SharedOctreeServerPointer myServer(this); - nodeData->initializeOctreeSendThread(myServer, matchingNode); + nodeData->initializeOctreeSendThread(SharedOctreeServerPointer(this), matchingNode); } } } else if (packetType == PacketTypeJurisdictionRequest) { @@ -1059,10 +1076,8 @@ void OctreeServer::aboutToFinish() { qDebug() << qPrintable(_safeServerName) << "server about to finish while node still connected node:" << *node; nodeKilled(node); } + qDebug() << qPrintable(_safeServerName) << "server ENDING about to finish..."; - - // release our reference to the instance, this will allow the shared pointers to properly unwind - _instance.clear(); } QString OctreeServer::getUptime() { diff --git a/assignment-client/src/octree/OctreeServer.h b/assignment-client/src/octree/OctreeServer.h index 5cf5fda59f..ff9452170d 100644 --- a/assignment-client/src/octree/OctreeServer.h +++ b/assignment-client/src/octree/OctreeServer.h @@ -158,7 +158,7 @@ protected: OctreeInboundPacketProcessor* _octreeInboundPacketProcessor; OctreePersistThread* _persistThread; - static SharedOctreeServerPointer _instance; + static OctreeServer* _instance; time_t _started; quint64 _startedUSecs; From 44860a5f5a5acb1951c3ced95224dbf36a053981 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 28 Mar 2014 12:01:37 -0700 Subject: [PATCH 028/595] put servers alphabetically first in node list --- domain-server/resources/web/js/tables.js | 25 +++++++++++++++++++++--- domain-server/src/DomainServer.cpp | 11 +++++++---- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/domain-server/resources/web/js/tables.js b/domain-server/resources/web/js/tables.js index 18e67ac6e7..3f7b2b7b28 100644 --- a/domain-server/resources/web/js/tables.js +++ b/domain-server/resources/web/js/tables.js @@ -2,16 +2,35 @@ $(document).ready(function(){ // setup a function to grab the assignments function getNodesAndAssignments() { $.getJSON("nodes.json", function(json){ + + json.nodes.sort(function(a, b){ + if (a.type === b.type) { + return 0; + } + + if (a.type === "agent" && b.type !== "agent") { + return 1; + } + + if (a.type > b.type) { + return 1; + } + + if (a.type < b.type) { + return -1; + } + }); + nodesTableBody = ""; - $.each(json.nodes, function (uuid, data) { + $.each(json.nodes, function(index, data) { nodesTableBody += ""; nodesTableBody += "" + data.type + ""; - nodesTableBody += "" + uuid + ""; + nodesTableBody += "" + data.uuid + ""; nodesTableBody += "" + (data.pool ? data.pool : "") + ""; nodesTableBody += "" + data.public.ip + ":" + data.public.port + ""; nodesTableBody += "" + data.local.ip + ":" + data.local.port + ""; - nodesTableBody += ""; + nodesTableBody += ""; nodesTableBody += ""; }); diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 035e6c9a20..d18f12ec7f 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -622,6 +622,7 @@ QJsonObject DomainServer::jsonForSocket(const HifiSockAddr& socket) { return socketJSON; } +const char JSON_KEY_UUID[] = "uuid"; const char JSON_KEY_TYPE[] = "type"; const char JSON_KEY_PUBLIC_SOCKET[] = "public"; const char JSON_KEY_LOCAL_SOCKET[] = "local"; @@ -635,6 +636,9 @@ QJsonObject DomainServer::jsonObjectForNode(const SharedNodePointer& node) { nodeTypeName = nodeTypeName.toLower(); nodeTypeName.replace(' ', '-'); + // add the node UUID + nodeJson[JSON_KEY_UUID] = uuidStringWithoutCurlyBraces(node->getUUID()); + // add the node type nodeJson[JSON_KEY_TYPE] = nodeTypeName; @@ -707,18 +711,17 @@ bool DomainServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url } else if (url.path() == QString("%1.json").arg(URI_NODES)) { // setup the JSON QJsonObject rootJSON; - QJsonObject nodesJSON; + QJsonArray nodesJSONArray; // enumerate the NodeList to find the assigned nodes NodeList* nodeList = NodeList::getInstance(); foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { // add the node using the UUID as the key - QString uuidString = uuidStringWithoutCurlyBraces(node->getUUID()); - nodesJSON[uuidString] = jsonObjectForNode(node); + nodesJSONArray.append(jsonObjectForNode(node)); } - rootJSON["nodes"] = nodesJSON; + rootJSON["nodes"] = nodesJSONArray; // print out the created JSON QJsonDocument nodesDocument(rootJSON); From 89aeb034d1057d1c0b0e52622917d4bc89062b73 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 28 Mar 2014 15:22:44 -0700 Subject: [PATCH 029/595] add find module for QCA and link to interface and DS --- cmake/modules/FindQCA.cmake | 38 ++++++++++++++++++++++++++++++++++++ domain-server/CMakeLists.txt | 7 ++++++- interface/CMakeLists.txt | 4 +++- 3 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 cmake/modules/FindQCA.cmake diff --git a/cmake/modules/FindQCA.cmake b/cmake/modules/FindQCA.cmake new file mode 100644 index 0000000000..1e679ff96b --- /dev/null +++ b/cmake/modules/FindQCA.cmake @@ -0,0 +1,38 @@ +# Try to find the QCA library +# +# You can provide a QCA_ROOT_DIR which contains lib and include directories +# +# Once done this will define +# +# QCA_FOUND - system found qca +# QCA_INCLUDE_DIRS - the qca include directory +# QCA_LIBRARIES - Link this to use qca +# +# Created on 3/28/2014 by Stephen Birarda +# Copyright (c) 2014 High Fidelity +# + +if (QCA_LIBRARIES AND QCA_INCLUDE_DIRS) + # in cache already + set(QCA_FOUND TRUE) +else () + + set(QCA_SEARCH_DIRS "${QCA_ROOT_DIR}" "$ENV{HIFI_LIB_DIR}/qca") + + find_path(QCA_INCLUDE_DIR qca.h PATH_SUFFIXES include/QtCrypto HINTS ${QCA_SEARCH_DIRS}) + + find_library(QCA_LIBRARY NAMES qca PATH_SUFFIXES lib HINTS ${QCA_SEARCH_DIRS}) + + include(FindPackageHandleStandardArgs) + find_package_handle_standard_args(QCA DEFAULT_MSG QCA_INCLUDE_DIR QCA_LIBRARY) + + if (QCA_FOUND) + if (NOT QCA_FIND_QUIETLY) + message(STATUS "Found qca: ${QCA_LIBRARY}") + endif () + else () + if (QCA_FIND_REQUIRED) + message(FATAL_ERROR "Could not find qca") + endif () + endif () +endif () \ No newline at end of file diff --git a/domain-server/CMakeLists.txt b/domain-server/CMakeLists.txt index 16bdb0df6b..57c9fa848c 100644 --- a/domain-server/CMakeLists.txt +++ b/domain-server/CMakeLists.txt @@ -17,6 +17,7 @@ include(${MACRO_DIR}/IncludeGLM.cmake) include_glm(${TARGET_NAME} "${ROOT_DIR}") find_package(Qt5Network REQUIRED) +find_package(QCA REQUIRED) include(${MACRO_DIR}/SetupHifiProject.cmake) @@ -36,8 +37,12 @@ include(${MACRO_DIR}/LinkHifiLibrary.cmake) link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(embedded-webserver ${TARGET_NAME} "${ROOT_DIR}") +# include the QCA dir +include_directories(QCA_INCLUDE_DIR) + IF (WIN32) target_link_libraries(${TARGET_NAME} Winmm Ws2_32) ENDIF(WIN32) -target_link_libraries(${TARGET_NAME} Qt5::Network) \ No newline at end of file +# link QtNetwork and QCA +target_link_libraries(${TARGET_NAME} Qt5::Network "${QCA_LIBRARY}") \ No newline at end of file diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index f991212a6e..b260f994a3 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -67,6 +67,7 @@ foreach(EXTERNAL_SOURCE_SUBDIR ${EXTERNAL_SOURCE_SUBDIRS}) endforeach(EXTERNAL_SOURCE_SUBDIR) find_package(Qt5 COMPONENTS Core Gui Multimedia Network OpenGL Script Svg WebKit WebKitWidgets Xml UiTools) +find_package(QCA REQUIRED) # grab the ui files in resources/ui file (GLOB_RECURSE QT_UI_FILES ui/*.ui) @@ -187,7 +188,7 @@ include_directories("${PROJECT_SOURCE_DIR}/src" "${PROJECT_BINARY_DIR}/includes" # include external library headers # use system flag so warnings are supressed -include_directories(SYSTEM "${FACESHIFT_INCLUDE_DIRS}") +include_directories(SYSTEM "${FACESHIFT_INCLUDE_DIRS}" "${QCA_INCLUDE_DIR}") target_link_libraries( ${TARGET_NAME} @@ -195,6 +196,7 @@ target_link_libraries( "${ZLIB_LIBRARIES}" Qt5::Core Qt5::Gui Qt5::Multimedia Qt5::Network Qt5::OpenGL Qt5::Script Qt5::Svg Qt5::WebKit Qt5::WebKitWidgets Qt5::Xml Qt5::UiTools + "${QCA_LIBRARY}" ) if (APPLE) From 9ae06913a02d443662d9a6547b9d46b8cccb88c4 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 31 Mar 2014 09:45:19 -0700 Subject: [PATCH 030/595] remove QCA which only supports DTLS v1 --- cmake/modules/FindQCA.cmake | 38 ------- domain-server/src/DomainServer.cpp | 176 +++++++++++------------------ domain-server/src/DomainServer.h | 18 +-- domain-server/src/main.cpp | 2 +- 4 files changed, 73 insertions(+), 161 deletions(-) delete mode 100644 cmake/modules/FindQCA.cmake diff --git a/cmake/modules/FindQCA.cmake b/cmake/modules/FindQCA.cmake deleted file mode 100644 index 1e679ff96b..0000000000 --- a/cmake/modules/FindQCA.cmake +++ /dev/null @@ -1,38 +0,0 @@ -# Try to find the QCA library -# -# You can provide a QCA_ROOT_DIR which contains lib and include directories -# -# Once done this will define -# -# QCA_FOUND - system found qca -# QCA_INCLUDE_DIRS - the qca include directory -# QCA_LIBRARIES - Link this to use qca -# -# Created on 3/28/2014 by Stephen Birarda -# Copyright (c) 2014 High Fidelity -# - -if (QCA_LIBRARIES AND QCA_INCLUDE_DIRS) - # in cache already - set(QCA_FOUND TRUE) -else () - - set(QCA_SEARCH_DIRS "${QCA_ROOT_DIR}" "$ENV{HIFI_LIB_DIR}/qca") - - find_path(QCA_INCLUDE_DIR qca.h PATH_SUFFIXES include/QtCrypto HINTS ${QCA_SEARCH_DIRS}) - - find_library(QCA_LIBRARY NAMES qca PATH_SUFFIXES lib HINTS ${QCA_SEARCH_DIRS}) - - include(FindPackageHandleStandardArgs) - find_package_handle_standard_args(QCA DEFAULT_MSG QCA_INCLUDE_DIR QCA_LIBRARY) - - if (QCA_FOUND) - if (NOT QCA_FIND_QUIETLY) - message(STATUS "Found qca: ${QCA_LIBRARY}") - endif () - else () - if (QCA_FIND_REQUIRED) - message(FATAL_ERROR "Could not find qca") - endif () - endif () -endif () \ No newline at end of file diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 035e6c9a20..1f1e3a4207 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -32,63 +32,80 @@ DomainServer::DomainServer(int argc, char* argv[]) : QCoreApplication(argc, argv), _HTTPManager(DOMAIN_SERVER_HTTP_PORT, QString("%1/resources/web/").arg(QCoreApplication::applicationDirPath()), this), _staticAssignmentHash(), - _assignmentQueue(), - _nodeAuthenticationURL(), - _redeemedTokenResponses() -{ + _assignmentQueue() +{ setOrganizationName("High Fidelity"); setOrganizationDomain("highfidelity.io"); setApplicationName("domain-server"); QSettings::setDefaultFormat(QSettings::IniFormat); _argumentList = arguments(); - int argumentIndex = 0; - // check if this domain server should use no authentication or a custom hostname for authentication - const QString DEFAULT_AUTH_OPTION = "--defaultAuth"; - const QString CUSTOM_AUTH_OPTION = "--customAuth"; - if ((argumentIndex = _argumentList.indexOf(DEFAULT_AUTH_OPTION) != -1)) { - _nodeAuthenticationURL = QUrl(DEFAULT_NODE_AUTH_URL); - } else if ((argumentIndex = _argumentList.indexOf(CUSTOM_AUTH_OPTION)) != -1) { - _nodeAuthenticationURL = QUrl(_argumentList.value(argumentIndex + 1)); - } - - if (!_nodeAuthenticationURL.isEmpty()) { - const QString DATA_SERVER_USERNAME_ENV = "HIFI_DS_USERNAME"; - const QString DATA_SERVER_PASSWORD_ENV = "HIFI_DS_PASSWORD"; - - // this node will be using an authentication server, let's make sure we have a username/password - QProcessEnvironment sysEnvironment = QProcessEnvironment::systemEnvironment(); - - QString username = sysEnvironment.value(DATA_SERVER_USERNAME_ENV); - QString password = sysEnvironment.value(DATA_SERVER_PASSWORD_ENV); - - AccountManager& accountManager = AccountManager::getInstance(); - accountManager.setAuthURL(_nodeAuthenticationURL); - - if (!username.isEmpty() && !password.isEmpty()) { - - connect(&accountManager, &AccountManager::loginComplete, this, &DomainServer::requestCreationFromDataServer); - - // ask the account manager to log us in from the env variables - accountManager.requestAccessToken(username, password); - } else { - qDebug() << "Authentication was requested against" << qPrintable(_nodeAuthenticationURL.toString()) - << "but both or one of" << qPrintable(DATA_SERVER_USERNAME_ENV) - << "/" << qPrintable(DATA_SERVER_PASSWORD_ENV) << "are not set. Qutting!"; - - // bail out - QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection); - - return; - } - - } else { - // auth is not requested for domain-server, setup NodeList and assignments now + if (readCertificateAndPrivateKey()) { + // we either read a certificate and private key or were not passed one, good to load assignments + // and set up the node list setupNodeListAndAssignments(); } } +bool DomainServer::readCertificateAndPrivateKey() { + const QString X509_CERTIFICATE_PATH_OPTION = "--cert"; + const QString PRIVATE_KEY_OPTION = "--key"; + const QString PRIVATE_KEY_PASSPHRASE_ENV = "DOMAIN_SERVER_KEY_PASSPHRASE"; + + int certificateIndex = _argumentList.indexOf(X509_CERTIFICATE_PATH_OPTION); + int keyIndex = _argumentList.indexOf(PRIVATE_KEY_OPTION); + + if (certificateIndex != -1 && keyIndex != -1) { + // the user wants to use DTLS to encrypt communication with nodes + // let's make sure we can load the certificate and private key + +// QCA::ConvertResult conversionResult = QCA::ErrorFile; +// +// QFile certificateFile(_argumentList.value(certificateIndex + 1)); +// qDebug() << "Attempting to read X.509 certificate from" << certificateFile.fileName(); +// +// if (certificateFile.exists()) { +// certificateFile.open(QIODevice::ReadOnly); +// QByteArray filearray = certificateFile.readAll(); +// qDebug() << filearray; +// _certificate = QCA::Certificate::fromPEM(filearray, &conversionResult); +// certificateFile.close(); +// } +// +// if (conversionResult != QCA::ConvertGood) { +// // couldn't read the certificate from file, bail +// qCritical() << "Error" << conversionResult << "reading certificate from file. domain-server will now quit." ; +// QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection); +// return false; +// } +// +// QByteArray keyPassphrase = QProcessEnvironment::systemEnvironment().value(PRIVATE_KEY_PASSPHRASE_ENV).toLocal8Bit(); +// QCA::SecureArray keySecureArray = QCA::SecureArray(keyPassphrase); +// +// QString keyFileString(_argumentList.value(keyIndex + 1)); +// qDebug() << "Attempting to read private key from" << keyFileString; +// _privateKey = QCA::PrivateKey::fromPEMFile(keyFileString, keySecureArray, &conversionResult); +// +// if (conversionResult != QCA::ConvertGood) { +// // couldn't read the private key from file, bail +// qCritical() << "Error" << conversionResult << "reading private key from file. domain-server will now quit."; +// QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection); +// return false; +// } + + qDebug() << "Successfully read certificate and private key. Using DTLS for node communication."; + } else if (certificateIndex != -1 || keyIndex != -1) { + // one of the certificate or private key was missing, can't use one without the other + // bail + qCritical("Missing certificate or private key. domain-server will now quit."); + QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection); + return false; + } + + return true; +} + void DomainServer::requestCreationFromDataServer() { // this slot is fired when we get a valid access token from the data-server // now let's ask it to set us up with a UUID @@ -109,17 +126,6 @@ void DomainServer::processCreateResponseFromDataServer(const QJsonObject& jsonOb } } -void DomainServer::processTokenRedeemResponse(const QJsonObject& jsonObject) { - // pull out the registration token this is associated with - QString registrationToken = jsonObject["data"].toObject()["registration_token"].toString(); - - // if we have a registration token add it to our hash of redeemed token responses - if (!registrationToken.isEmpty()) { - qDebug() << "Redeemed registration token" << registrationToken; - _redeemedTokenResponses.insert(registrationToken, jsonObject); - } -} - void DomainServer::setupNodeListAndAssignments(const QUuid& sessionUUID) { int argumentIndex = 0; @@ -299,21 +305,6 @@ void DomainServer::populateDefaultStaticAssignmentsExcludingTypes(const QSetgetNodeSocket().writeDatagram(authenticationRequestPacket, - senderSockAddr.getAddress(), senderSockAddr.getPort()); -} - const NodeSet STATICALLY_ASSIGNED_NODES = NodeSet() << NodeType::AudioMixer << NodeType::AvatarMixer << NodeType::VoxelServer << NodeType::ParticleServer << NodeType::MetavoxelServer; @@ -483,7 +474,6 @@ void DomainServer::sendDomainListToNode(const SharedNodePointer& node, const Hif void DomainServer::readAvailableDatagrams() { NodeList* nodeList = NodeList::getInstance(); - AccountManager& accountManager = AccountManager::getInstance(); HifiSockAddr senderSockAddr; @@ -507,43 +497,9 @@ void DomainServer::readAvailableDatagrams() { quint8 hasRegistrationToken; packetStream >> hasRegistrationToken; - if (requiresAuthentication() && !hasRegistrationToken) { - // we need authentication and this node did not give us a registration token - tell it to auth - requestAuthenticationFromPotentialNode(senderSockAddr); - } else if (requiresAuthentication()) { - QByteArray registrationToken; - packetStream >> registrationToken; - - QString registrationTokenString(registrationToken.toHex()); - QJsonObject jsonForRedeemedToken = _redeemedTokenResponses.value(registrationTokenString); - - // check if we have redeemed this token and are ready to check the node in - if (jsonForRedeemedToken.isEmpty()) { - // make a request against the data-server to get information required to connect to this node - JSONCallbackParameters tokenCallbackParams; - tokenCallbackParams.jsonCallbackReceiver = this; - tokenCallbackParams.jsonCallbackMethod = "processTokenRedeemResponse"; - - QString redeemURLString = QString("/api/v1/nodes/redeem/%1.json").arg(registrationTokenString); - accountManager.authenticatedRequest(redeemURLString, QNetworkAccessManager::GetOperation, - tokenCallbackParams); - } else if (jsonForRedeemedToken["status"].toString() != "success") { - // we redeemed the token, but it was invalid - get the node to get another - requestAuthenticationFromPotentialNode(senderSockAddr); - } else { - // we've redeemed the token for this node and are ready to start communicating with it - // add the node to our NodeList - addNodeToNodeListAndConfirmConnection(receivedPacket, senderSockAddr, jsonForRedeemedToken); - } - - // if it exists, remove this response from the in-memory hash - _redeemedTokenResponses.remove(registrationTokenString); - - } else { - // we don't require authentication - add this node to our NodeList - // and send back session UUID right away - addNodeToNodeListAndConfirmConnection(receivedPacket, senderSockAddr); - } + // we don't require authentication - add this node to our NodeList + // and send back session UUID right away + addNodeToNodeListAndConfirmConnection(receivedPacket, senderSockAddr); } else if (requestType == PacketTypeDomainListRequest) { QUuid nodeUUID = uuidFromPacketHeader(receivedPacket); diff --git a/domain-server/src/DomainServer.h b/domain-server/src/DomainServer.h index 597be7f50d..c6a9879555 100644 --- a/domain-server/src/DomainServer.h +++ b/domain-server/src/DomainServer.h @@ -28,8 +28,6 @@ class DomainServer : public QCoreApplication, public HTTPRequestHandler { public: DomainServer(int argc, char* argv[]); - bool requiresAuthentication() const { return !_nodeAuthenticationURL.isEmpty(); } - bool handleHTTPRequest(HTTPConnection* connection, const QUrl& url); void exit(int retCode = 0); @@ -40,8 +38,14 @@ public slots: /// Called by NodeList to inform us a node has been killed void nodeKilled(SharedNodePointer node); +private slots: + void requestCreationFromDataServer(); + void processCreateResponseFromDataServer(const QJsonObject& jsonObject); + + void readAvailableDatagrams(); private: void setupNodeListAndAssignments(const QUuid& sessionUUID = QUuid::createUuid()); + bool readCertificateAndPrivateKey(); void requestAuthenticationFromPotentialNode(const HifiSockAddr& senderSockAddr); void addNodeToNodeListAndConfirmConnection(const QByteArray& packet, const HifiSockAddr& senderSockAddr, @@ -73,17 +77,7 @@ private: QHash _staticAssignmentHash; QQueue _assignmentQueue; - QUrl _nodeAuthenticationURL; - QStringList _argumentList; - - QHash _redeemedTokenResponses; -private slots: - void requestCreationFromDataServer(); - void processCreateResponseFromDataServer(const QJsonObject& jsonObject); - void processTokenRedeemResponse(const QJsonObject& jsonObject); - - void readAvailableDatagrams(); }; #endif /* defined(__hifi__DomainServer__) */ diff --git a/domain-server/src/main.cpp b/domain-server/src/main.cpp index 970d1dad70..096431e0a4 100644 --- a/domain-server/src/main.cpp +++ b/domain-server/src/main.cpp @@ -23,7 +23,7 @@ int main(int argc, char* argv[]) { #ifndef WIN32 setvbuf(stdout, NULL, _IOLBF, 0); #endif - + qInstallMessageHandler(Logging::verboseMessageHandler); DomainServer domainServer(argc, argv); From dc38b27485d00fb1483a657ce0010c69673db264 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 31 Mar 2014 12:31:34 -0700 Subject: [PATCH 031/595] using GnuTLS read self-signed key and cert on DS load --- cmake/modules/FindGnuTLS.cmake | 28 +++++++++++ cmake/modules/FindQxmpp.cmake | 12 +---- domain-server/CMakeLists.txt | 6 +-- domain-server/src/DomainServer.cpp | 77 ++++++++++++------------------ domain-server/src/DomainServer.h | 4 ++ domain-server/src/main.cpp | 2 + interface/CMakeLists.txt | 4 +- 7 files changed, 69 insertions(+), 64 deletions(-) create mode 100644 cmake/modules/FindGnuTLS.cmake diff --git a/cmake/modules/FindGnuTLS.cmake b/cmake/modules/FindGnuTLS.cmake new file mode 100644 index 0000000000..d09ba38fb7 --- /dev/null +++ b/cmake/modules/FindGnuTLS.cmake @@ -0,0 +1,28 @@ +# Try to find the GnuTLS library +# +# You can provide a GNUTLS_ROOT_DIR which contains lib and include directories +# +# Once done this will define +# +# GNUTLS_FOUND - system found GnuTLS +# GNUTLS_INCLUDE_DIRS - the GnuTLS include directory +# GNUTLS_LIBRARY - Link this to use GnuTLS +# +# Created on 3/31/2014 by Stephen Birarda +# Copyright (c) 2014 High Fidelity +# + +if (GNUTLS_LIBRARY AND GNUTLS_INCLUDE_DIRS) + # in cache already + set(GNUTLS_FOUND TRUE) +else () + + set(GNUTLS_SEARCH_DIRS "${GNUTLS_ROOT_DIR}" "$ENV{HIFI_LIB_DIR}/gnutls") + + find_path(GNUTLS_INCLUDE_DIR gnutls.h PATH_SUFFIXES include gnutls HINTS ${GNUTLS_SEARCH_DIRS}) + + find_library(GNUTLS_LIBRARY NAMES gnutls PATH_SUFFIXES lib HINTS ${GNUTLS_SEARCH_DIRS}) + + include(FindPackageHandleStandardArgs) + find_package_handle_standard_args(GNUTLS DEFAULT_MSG GNUTLS_INCLUDE_DIR GNUTLS_LIBRARY) +endif () \ No newline at end of file diff --git a/cmake/modules/FindQxmpp.cmake b/cmake/modules/FindQxmpp.cmake index 415b184a65..2e883e02f2 100644 --- a/cmake/modules/FindQxmpp.cmake +++ b/cmake/modules/FindQxmpp.cmake @@ -6,7 +6,7 @@ # # QXMPP_FOUND - system found qxmpp # QXMPP_INCLUDE_DIRS - the qxmpp include directory -# QXMPP_LIBRARIES - Link this to use qxmpp +# QXMPP_LIBRARY - Link this to use qxmpp # # Created on 3/10/2014 by Stephen Birarda # Copyright (c) 2014 High Fidelity @@ -25,14 +25,4 @@ else () include(FindPackageHandleStandardArgs) find_package_handle_standard_args(QXMPP DEFAULT_MSG QXMPP_INCLUDE_DIR QXMPP_LIBRARY) - - if (QXMPP_FOUND) - if (NOT QXMPP_FIND_QUIETLY) - message(STATUS "Found qxmpp: ${QXMPP_LIBRARY}") - endif () - else () - if (QXMPP_FIND_REQUIRED) - message(FATAL_ERROR "Could not find qxmpp") - endif () - endif () endif () \ No newline at end of file diff --git a/domain-server/CMakeLists.txt b/domain-server/CMakeLists.txt index 57c9fa848c..4cbc29c62d 100644 --- a/domain-server/CMakeLists.txt +++ b/domain-server/CMakeLists.txt @@ -17,7 +17,7 @@ include(${MACRO_DIR}/IncludeGLM.cmake) include_glm(${TARGET_NAME} "${ROOT_DIR}") find_package(Qt5Network REQUIRED) -find_package(QCA REQUIRED) +find_package(GnuTLS REQUIRED) include(${MACRO_DIR}/SetupHifiProject.cmake) @@ -38,11 +38,11 @@ link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(embedded-webserver ${TARGET_NAME} "${ROOT_DIR}") # include the QCA dir -include_directories(QCA_INCLUDE_DIR) +include_directories(GNUTLS_INCLUDE_DIR) IF (WIN32) target_link_libraries(${TARGET_NAME} Winmm Ws2_32) ENDIF(WIN32) # link QtNetwork and QCA -target_link_libraries(${TARGET_NAME} Qt5::Network "${QCA_LIBRARY}") \ No newline at end of file +target_link_libraries(${TARGET_NAME} Qt5::Network "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 1f1e3a4207..80a86da8a0 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -16,6 +16,8 @@ #include #include +#include + #include #include #include @@ -32,7 +34,8 @@ DomainServer::DomainServer(int argc, char* argv[]) : QCoreApplication(argc, argv), _HTTPManager(DOMAIN_SERVER_HTTP_PORT, QString("%1/resources/web/").arg(QCoreApplication::applicationDirPath()), this), _staticAssignmentHash(), - _assignmentQueue() + _assignmentQueue(), + _x509Credentials() { setOrganizationName("High Fidelity"); setOrganizationDomain("highfidelity.io"); @@ -49,56 +52,36 @@ DomainServer::DomainServer(int argc, char* argv[]) : } bool DomainServer::readCertificateAndPrivateKey() { - const QString X509_CERTIFICATE_PATH_OPTION = "--cert"; - const QString PRIVATE_KEY_OPTION = "--key"; - const QString PRIVATE_KEY_PASSPHRASE_ENV = "DOMAIN_SERVER_KEY_PASSPHRASE"; + const QString X509_CERTIFICATE_OPTION = "--cert"; + const QString X509_PRIVATE_KEY_OPTION = "--key"; + const QString X509_KEY_PASSPHRASE_ENV = "DOMAIN_SERVER_KEY_PASSPHRASE"; + + int certIndex = _argumentList.indexOf(X509_CERTIFICATE_OPTION); + int keyIndex = _argumentList.indexOf(X509_PRIVATE_KEY_OPTION); - int certificateIndex = _argumentList.indexOf(X509_CERTIFICATE_PATH_OPTION); - int keyIndex = _argumentList.indexOf(PRIVATE_KEY_OPTION); - - if (certificateIndex != -1 && keyIndex != -1) { + if (certIndex != -1 && keyIndex != -1) { // the user wants to use DTLS to encrypt communication with nodes - // let's make sure we can load the certificate and private key - -// QCA::ConvertResult conversionResult = QCA::ErrorFile; -// -// QFile certificateFile(_argumentList.value(certificateIndex + 1)); -// qDebug() << "Attempting to read X.509 certificate from" << certificateFile.fileName(); -// -// if (certificateFile.exists()) { -// certificateFile.open(QIODevice::ReadOnly); -// QByteArray filearray = certificateFile.readAll(); -// qDebug() << filearray; -// _certificate = QCA::Certificate::fromPEM(filearray, &conversionResult); -// certificateFile.close(); -// } -// -// if (conversionResult != QCA::ConvertGood) { -// // couldn't read the certificate from file, bail -// qCritical() << "Error" << conversionResult << "reading certificate from file. domain-server will now quit." ; -// QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection); -// return false; -// } -// -// QByteArray keyPassphrase = QProcessEnvironment::systemEnvironment().value(PRIVATE_KEY_PASSPHRASE_ENV).toLocal8Bit(); -// QCA::SecureArray keySecureArray = QCA::SecureArray(keyPassphrase); -// -// QString keyFileString(_argumentList.value(keyIndex + 1)); -// qDebug() << "Attempting to read private key from" << keyFileString; -// _privateKey = QCA::PrivateKey::fromPEMFile(keyFileString, keySecureArray, &conversionResult); -// -// if (conversionResult != QCA::ConvertGood) { -// // couldn't read the private key from file, bail -// qCritical() << "Error" << conversionResult << "reading private key from file. domain-server will now quit."; -// QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection); -// return false; -// } + // let's make sure we can load the ey + gnutls_certificate_allocate_credentials(&_x509Credentials); + + QString keyPassphraseString = QProcessEnvironment::systemEnvironment().value(X509_KEY_PASSPHRASE_ENV); + + int gnutlsReturn = gnutls_certificate_set_x509_key_file2(_x509Credentials, + _argumentList[certIndex + 1].toLocal8Bit().constData(), + _argumentList[keyIndex + 1].toLocal8Bit().constData(), + GNUTLS_X509_FMT_PEM, + keyPassphraseString.toLocal8Bit().constData(), + 0); + + if (gnutlsReturn < 0) { + qDebug() << "Unable to load certificate or key file." << "Error" << gnutlsReturn << "- domain-server will now quit."; + QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection); + return false; + } qDebug() << "Successfully read certificate and private key. Using DTLS for node communication."; - } else if (certificateIndex != -1 || keyIndex != -1) { - // one of the certificate or private key was missing, can't use one without the other - // bail - qCritical("Missing certificate or private key. domain-server will now quit."); + } else if (certIndex != -1 || keyIndex != -1) { + qDebug() << "Missing certificate or private key. domain-server will now quit."; QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection); return false; } diff --git a/domain-server/src/DomainServer.h b/domain-server/src/DomainServer.h index c6a9879555..244621c7b1 100644 --- a/domain-server/src/DomainServer.h +++ b/domain-server/src/DomainServer.h @@ -17,6 +17,8 @@ #include #include +#include + #include #include #include @@ -78,6 +80,8 @@ private: QQueue _assignmentQueue; QStringList _argumentList; + + gnutls_certificate_credentials_t _x509Credentials; }; #endif /* defined(__hifi__DomainServer__) */ diff --git a/domain-server/src/main.cpp b/domain-server/src/main.cpp index 096431e0a4..4bfa35fac5 100644 --- a/domain-server/src/main.cpp +++ b/domain-server/src/main.cpp @@ -24,6 +24,8 @@ int main(int argc, char* argv[]) { setvbuf(stdout, NULL, _IOLBF, 0); #endif + gnutls_global_init(); + qInstallMessageHandler(Logging::verboseMessageHandler); DomainServer domainServer(argc, argv); diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index b260f994a3..f991212a6e 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -67,7 +67,6 @@ foreach(EXTERNAL_SOURCE_SUBDIR ${EXTERNAL_SOURCE_SUBDIRS}) endforeach(EXTERNAL_SOURCE_SUBDIR) find_package(Qt5 COMPONENTS Core Gui Multimedia Network OpenGL Script Svg WebKit WebKitWidgets Xml UiTools) -find_package(QCA REQUIRED) # grab the ui files in resources/ui file (GLOB_RECURSE QT_UI_FILES ui/*.ui) @@ -188,7 +187,7 @@ include_directories("${PROJECT_SOURCE_DIR}/src" "${PROJECT_BINARY_DIR}/includes" # include external library headers # use system flag so warnings are supressed -include_directories(SYSTEM "${FACESHIFT_INCLUDE_DIRS}" "${QCA_INCLUDE_DIR}") +include_directories(SYSTEM "${FACESHIFT_INCLUDE_DIRS}") target_link_libraries( ${TARGET_NAME} @@ -196,7 +195,6 @@ target_link_libraries( "${ZLIB_LIBRARIES}" Qt5::Core Qt5::Gui Qt5::Multimedia Qt5::Network Qt5::OpenGL Qt5::Script Qt5::Svg Qt5::WebKit Qt5::WebKitWidgets Qt5::Xml Qt5::UiTools - "${QCA_LIBRARY}" ) if (APPLE) From da30d21f6efeff8626aaafb2324435e8e66a2222 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 31 Mar 2014 14:02:11 -0700 Subject: [PATCH 032/595] complete inital DTLS setup in domain-server --- domain-server/src/DomainServer.cpp | 80 +++++++++++++++++++++++++++--- domain-server/src/DomainServer.h | 9 +++- libraries/shared/src/NodeList.cpp | 9 ++++ libraries/shared/src/NodeList.h | 2 + 4 files changed, 90 insertions(+), 10 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 80a86da8a0..df0935ba54 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -35,7 +35,10 @@ DomainServer::DomainServer(int argc, char* argv[]) : _HTTPManager(DOMAIN_SERVER_HTTP_PORT, QString("%1/resources/web/").arg(QCoreApplication::applicationDirPath()), this), _staticAssignmentHash(), _assignmentQueue(), - _x509Credentials() + _isUsingDTLS(false), + _x509Credentials(NULL), + _dhParams(NULL), + _priorityCache(NULL) { setOrganizationName("High Fidelity"); setOrganizationDomain("highfidelity.io"); @@ -44,29 +47,85 @@ DomainServer::DomainServer(int argc, char* argv[]) : _argumentList = arguments(); - if (readCertificateAndPrivateKey()) { + if (optionallySetupDTLS()) { // we either read a certificate and private key or were not passed one, good to load assignments // and set up the node list + qDebug() << "Setting up NodeList and assignments."; setupNodeListAndAssignments(); + + if (_isUsingDTLS) { + // we're using DTLS and our NodeList socket is good to go, so make the required DTLS changes + // DTLS requires that IP_DONTFRAG be set + // This is not accessible on some platforms (OS X) so we need to make sure DTLS still works without it + + NodeList* nodeList = NodeList::getInstance(); + +#if defined(IP_DONTFRAG) || defined(IP_MTU_DISCOVER) + qDebug() << "Making required DTLS changes to NodeList DTLS socket."; + + int socketHandle = NodeList::getInstance()->getDTLSSocket().socketDescriptor(); +#if defined(IP_DONTFRAG) + int optValue = 1;yea + setsockopt(socketHandle, IPPROTO_IP, IP_DONTFRAG, (const void*) optValue, sizeof(optValue)); +#elif defined(IP_MTU_DISCOVER) + int optValue = 1; + setsockopt(socketHandle, IPPROTO_IP, IP_MTU_DISCOVER, (const void*) optValue, sizeof(optValue)); +#endif +#endif + // connect our socket to read datagrams received on the DTLS socket + connect(&nodeList->getDTLSSocket(), &QUdpSocket::readyRead, this, &DomainServer::readAvailableDTLSDatagrams); + } } } -bool DomainServer::readCertificateAndPrivateKey() { +bool DomainServer::optionallySetupDTLS() { + if (readX509KeyAndCertificate()) { + qDebug() << "Generating Diffie-Hellman parameters."; + + // generate Diffie-Hellman parameters + // When short bit length is used, it might be wise to regenerate parameters often. + int dhBits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, GNUTLS_SEC_PARAM_LEGACY); + + _dhParams = new gnutls_dh_params_t; + gnutls_dh_params_init(_dhParams); + gnutls_dh_params_generate2(*_dhParams, dhBits); + + qDebug() << "Successfully generated Diffie-Hellman parameters."; + + // set the D-H paramters on the X509 credentials + gnutls_certificate_set_dh_params(*_x509Credentials, *_dhParams); + + _priorityCache = new gnutls_priority_t; + const char DTLS_PRIORITY_STRING[] = "PERFORMANCE:-VERS-TLS-ALL:+VERS-DTLS1.2:%SERVER_PRECEDENCE"; + gnutls_priority_init(_priorityCache, DTLS_PRIORITY_STRING, NULL); + + _isUsingDTLS = true; + + qDebug() << "Initial DTLS setup complete."; + + return true; + } else { + return false; + } +} + +bool DomainServer::readX509KeyAndCertificate() { const QString X509_CERTIFICATE_OPTION = "--cert"; const QString X509_PRIVATE_KEY_OPTION = "--key"; const QString X509_KEY_PASSPHRASE_ENV = "DOMAIN_SERVER_KEY_PASSPHRASE"; - + int certIndex = _argumentList.indexOf(X509_CERTIFICATE_OPTION); int keyIndex = _argumentList.indexOf(X509_PRIVATE_KEY_OPTION); if (certIndex != -1 && keyIndex != -1) { // the user wants to use DTLS to encrypt communication with nodes - // let's make sure we can load the ey - gnutls_certificate_allocate_credentials(&_x509Credentials); + // let's make sure we can load the key and certificate + _x509Credentials = new gnutls_certificate_credentials_t; + gnutls_certificate_allocate_credentials(_x509Credentials); QString keyPassphraseString = QProcessEnvironment::systemEnvironment().value(X509_KEY_PASSPHRASE_ENV); - int gnutlsReturn = gnutls_certificate_set_x509_key_file2(_x509Credentials, + int gnutlsReturn = gnutls_certificate_set_x509_key_file2(*_x509Credentials, _argumentList[certIndex + 1].toLocal8Bit().constData(), _argumentList[keyIndex + 1].toLocal8Bit().constData(), GNUTLS_X509_FMT_PEM, @@ -79,7 +138,8 @@ bool DomainServer::readCertificateAndPrivateKey() { return false; } - qDebug() << "Successfully read certificate and private key. Using DTLS for node communication."; + qDebug() << "Successfully read certificate and private key."; + } else if (certIndex != -1 || keyIndex != -1) { qDebug() << "Missing certificate or private key. domain-server will now quit."; QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection); @@ -552,6 +612,10 @@ void DomainServer::readAvailableDatagrams() { } } +void DomainServer::readAvailableDTLSDatagrams() { + +} + QJsonObject DomainServer::jsonForSocket(const HifiSockAddr& socket) { QJsonObject socketJSON; diff --git a/domain-server/src/DomainServer.h b/domain-server/src/DomainServer.h index 244621c7b1..ba2b47a2e7 100644 --- a/domain-server/src/DomainServer.h +++ b/domain-server/src/DomainServer.h @@ -45,9 +45,11 @@ private slots: void processCreateResponseFromDataServer(const QJsonObject& jsonObject); void readAvailableDatagrams(); + void readAvailableDTLSDatagrams(); private: void setupNodeListAndAssignments(const QUuid& sessionUUID = QUuid::createUuid()); - bool readCertificateAndPrivateKey(); + bool optionallySetupDTLS(); + bool readX509KeyAndCertificate(); void requestAuthenticationFromPotentialNode(const HifiSockAddr& senderSockAddr); void addNodeToNodeListAndConfirmConnection(const QByteArray& packet, const HifiSockAddr& senderSockAddr, @@ -81,7 +83,10 @@ private: QStringList _argumentList; - gnutls_certificate_credentials_t _x509Credentials; + bool _isUsingDTLS; + gnutls_certificate_credentials_t* _x509Credentials; + gnutls_dh_params_t* _dhParams; + gnutls_priority_t* _priorityCache; }; #endif /* defined(__hifi__DomainServer__) */ diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 761ea40d55..b053db356e 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -89,6 +89,15 @@ NodeList::NodeList(char newOwnerType, unsigned short int newSocketListenPort) : _packetStatTimer.start(); } +QUdpSocket& NodeList::getDTLSSocket() { + if (_dtlsSocket.state() == QAbstractSocket::UnconnectedState) { + _dtlsSocket.bind(QHostAddress::AnyIPv4); + qDebug() << "NodeList DTLS socket is listening on" << _dtlsSocket.localPort(); + } + + return _dtlsSocket; +} + void NodeList::changeSendSocketBufferSize(int numSendBytes) { // change the socket send buffer size to be 1MB int oldBufferSize = 0; diff --git a/libraries/shared/src/NodeList.h b/libraries/shared/src/NodeList.h index d05d6a2fbc..24281e3aa3 100644 --- a/libraries/shared/src/NodeList.h +++ b/libraries/shared/src/NodeList.h @@ -72,6 +72,7 @@ public: void setSessionUUID(const QUuid& sessionUUID); QUdpSocket& getNodeSocket() { return _nodeSocket; } + QUdpSocket& getDTLSSocket(); bool packetVersionAndHashMatch(const QByteArray& packet); @@ -165,6 +166,7 @@ private: NodeHash _nodeHash; QMutex _nodeHashMutex; QUdpSocket _nodeSocket; + QUdpSocket _dtlsSocket; NodeType_t _ownerType; NodeSet _nodeTypesOfInterest; DomainInfo _domainInfo; From faa062f8ab4793c520e5f50b752bfca9a76eb8c3 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 14:08:19 -0700 Subject: [PATCH 033/595] use single instance of SharedAssignmentPointer for assignment client so we actually get reference counting --- assignment-client/src/AssignmentClient.cpp | 5 +++-- assignment-client/src/AssignmentClient.h | 6 +++++- .../src/octree/OctreeQueryNode.cpp | 4 ++-- .../src/octree/OctreeQueryNode.h | 6 +++--- .../src/octree/OctreeSendThread.cpp | 20 +++++++++---------- .../src/octree/OctreeSendThread.h | 11 ++++++++-- assignment-client/src/octree/OctreeServer.cpp | 5 ++++- assignment-client/src/octree/OctreeServer.h | 8 ++++++-- libraries/shared/src/ThreadedAssignment.cpp | 1 - libraries/shared/src/ThreadedAssignment.h | 7 +++++-- 10 files changed, 47 insertions(+), 26 deletions(-) diff --git a/assignment-client/src/AssignmentClient.cpp b/assignment-client/src/AssignmentClient.cpp index aa20f2ff29..8795dc5bc4 100644 --- a/assignment-client/src/AssignmentClient.cpp +++ b/assignment-client/src/AssignmentClient.cpp @@ -25,11 +25,12 @@ const QString ASSIGNMENT_CLIENT_TARGET_NAME = "assignment-client"; const long long ASSIGNMENT_REQUEST_INTERVAL_MSECS = 1 * 1000; +SharedAssignmentPointer AssignmentClient::_currentAssignment; + int hifiSockAddrMeta = qRegisterMetaType("HifiSockAddr"); AssignmentClient::AssignmentClient(int &argc, char **argv) : - QCoreApplication(argc, argv), - _currentAssignment() + QCoreApplication(argc, argv) { setOrganizationName("High Fidelity"); setOrganizationDomain("highfidelity.io"); diff --git a/assignment-client/src/AssignmentClient.h b/assignment-client/src/AssignmentClient.h index c267c6238b..1b61fb3efe 100644 --- a/assignment-client/src/AssignmentClient.h +++ b/assignment-client/src/AssignmentClient.h @@ -17,14 +17,18 @@ class AssignmentClient : public QCoreApplication { Q_OBJECT public: AssignmentClient(int &argc, char **argv); + + static const SharedAssignmentPointer& getCurrentAssignment() { return _currentAssignment; } + private slots: void sendAssignmentRequest(); void readPendingDatagrams(); void assignmentCompleted(); void handleAuthenticationRequest(); + private: Assignment _requestAssignment; - SharedAssignmentPointer _currentAssignment; + static SharedAssignmentPointer _currentAssignment; }; #endif /* defined(__hifi__AssignmentClient__) */ diff --git a/assignment-client/src/octree/OctreeQueryNode.cpp b/assignment-client/src/octree/OctreeQueryNode.cpp index ab7b2f65fd..77d36f69fa 100644 --- a/assignment-client/src/octree/OctreeQueryNode.cpp +++ b/assignment-client/src/octree/OctreeQueryNode.cpp @@ -76,9 +76,9 @@ void OctreeQueryNode::deleteLater() { } -void OctreeQueryNode::initializeOctreeSendThread(const SharedOctreeServerPointer& octreeServer, SharedNodePointer node) { +void OctreeQueryNode::initializeOctreeSendThread(const SharedAssignmentPointer& myAssignment, SharedNodePointer node) { // Create octree sending thread... - _octreeSendThread = new OctreeSendThread(octreeServer, node); + _octreeSendThread = new OctreeSendThread(myAssignment, node); _octreeSendThread->initialize(true); } diff --git a/assignment-client/src/octree/OctreeQueryNode.h b/assignment-client/src/octree/OctreeQueryNode.h index ace1235908..66e4e5b0bb 100644 --- a/assignment-client/src/octree/OctreeQueryNode.h +++ b/assignment-client/src/octree/OctreeQueryNode.h @@ -19,9 +19,9 @@ #include #include +#include "OctreeServer.h" + class OctreeSendThread; -class OctreeServer; -typedef QSharedPointer SharedOctreeServerPointer; class OctreeQueryNode : public OctreeQuery { Q_OBJECT @@ -84,7 +84,7 @@ public: OctreeSceneStats stats; - void initializeOctreeSendThread(const SharedOctreeServerPointer& octreeServer, SharedNodePointer node); + void initializeOctreeSendThread(const SharedAssignmentPointer& myAssignment, SharedNodePointer node); bool isOctreeSendThreadInitalized() { return _octreeSendThread; } void dumpOutOfView(); diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index c760963310..8fe2fb6f30 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -19,8 +19,9 @@ quint64 startSceneSleepTime = 0; quint64 endSceneSleepTime = 0; -OctreeSendThread::OctreeSendThread(const SharedOctreeServerPointer& myServer, SharedNodePointer node) : - _myServer(myServer), +OctreeSendThread::OctreeSendThread(const SharedAssignmentPointer& myAssignment, SharedNodePointer node) : + _myAssignment(myAssignment), + _myServer(static_cast(myAssignment.data())), _node(node), _nodeUUID(node->getUUID()), _packetData(), @@ -28,7 +29,7 @@ OctreeSendThread::OctreeSendThread(const SharedOctreeServerPointer& myServer, Sh _processLock(), _isShuttingDown(false) { - qDebug() << qPrintable(_myServer->getMyServerName()) << "server [" << _myServer.data() << "]: client connected " + qDebug() << qPrintable(_myServer->getMyServerName()) << "server [" << _myServer << "]: client connected " "- starting sending thread [" << this << "]"; OctreeServer::clientConnected(); @@ -37,23 +38,22 @@ OctreeSendThread::OctreeSendThread(const SharedOctreeServerPointer& myServer, Sh OctreeSendThread::~OctreeSendThread() { QString serverName(_myServer->getMyServerName()); - qDebug() << qPrintable(serverName) << "server [" << _myServer.data() << "]: client disconnected " + qDebug() << qPrintable(serverName) << "server [" << _myServer << "]: client disconnected " "- ending sending thread [" << this << "]"; OctreeServer::clientDisconnected(); - qDebug() << qPrintable(serverName) << "server [" << _myServer.data() << "]: " + qDebug() << qPrintable(serverName) << "server [" << _myServer << "]: " "- OctreeSendThread::~OctreeSendThread() this=[" << this << "]" "line: " << __LINE__; _node.clear(); - qDebug() << qPrintable(serverName) << "server [" << _myServer.data() << "]: " + qDebug() << qPrintable(serverName) << "server [" << _myServer << "]: " "- OctreeSendThread::~OctreeSendThread() this=[" << this << "]" "line: " << __LINE__; - void* serverPtr = _myServer.data(); - _myServer.clear(); + _myAssignment.clear(); - qDebug() << qPrintable(serverName) << "server [" << serverPtr << "]: " + qDebug() << qPrintable(serverName) << "server [" << _myServer << "]: " "- OctreeSendThread::~OctreeSendThread() this=[" << this << "]" "line: " << __LINE__; } @@ -73,7 +73,7 @@ bool OctreeSendThread::process() { } // check that our WeakPointer to our server is still valid - if (_myServer.isNull()) { + if (!_myServer || _myAssignment.isNull()) { return false; // exit early if it's not, it means the server is shutting down } diff --git a/assignment-client/src/octree/OctreeSendThread.h b/assignment-client/src/octree/OctreeSendThread.h index bcaa9baf0e..a341a5be7d 100644 --- a/assignment-client/src/octree/OctreeSendThread.h +++ b/assignment-client/src/octree/OctreeSendThread.h @@ -13,6 +13,12 @@ #include #include #include + + +class OctreeServer; +class OctreeQueryNode; + + #include "OctreeQueryNode.h" #include "OctreeServer.h" @@ -20,7 +26,7 @@ class OctreeSendThread : public GenericThread { Q_OBJECT public: - OctreeSendThread(const SharedOctreeServerPointer& myServer, SharedNodePointer node); + OctreeSendThread(const SharedAssignmentPointer& myAssignment, SharedNodePointer node); virtual ~OctreeSendThread(); void setIsShuttingDown(); @@ -37,7 +43,8 @@ protected: virtual bool process(); private: - SharedOctreeServerPointer _myServer; + SharedAssignmentPointer _myAssignment; + OctreeServer* _myServer; SharedNodePointer _node; QUuid _nodeUUID; diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index e5c8cd262c..3134b577ae 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -16,6 +16,8 @@ #include #include +#include "../AssignmentClient.h" + #include "OctreeServer.h" #include "OctreeServerConsts.h" @@ -854,7 +856,8 @@ void OctreeServer::readPendingDatagrams() { if (debug) { qDebug() << "calling initializeOctreeSendThread()... node:" << *matchingNode; } - nodeData->initializeOctreeSendThread(SharedOctreeServerPointer(this), matchingNode); + SharedAssignmentPointer sharedAssignment = AssignmentClient::getCurrentAssignment(); + nodeData->initializeOctreeSendThread(sharedAssignment, matchingNode); } } } else if (packetType == PacketTypeJurisdictionRequest) { diff --git a/assignment-client/src/octree/OctreeServer.h b/assignment-client/src/octree/OctreeServer.h index ff9452170d..6405dc986e 100644 --- a/assignment-client/src/octree/OctreeServer.h +++ b/assignment-client/src/octree/OctreeServer.h @@ -20,6 +20,10 @@ #include #include +class OctreeServer; +class OctreeQueryNode; +class OctreeSendThread; + #include "OctreePersistThread.h" #include "OctreeSendThread.h" #include "OctreeServerConsts.h" @@ -27,8 +31,8 @@ const int DEFAULT_PACKETS_PER_INTERVAL = 2000; // some 120,000 packets per second total -class OctreeServer; -typedef QSharedPointer SharedOctreeServerPointer; +//class OctreeServer; +//typedef QSharedPointer SharedOctreeServerPointer; /// Handles assignments of type OctreeServer - sending octrees to various clients. class OctreeServer : public ThreadedAssignment, public HTTPRequestHandler { diff --git a/libraries/shared/src/ThreadedAssignment.cpp b/libraries/shared/src/ThreadedAssignment.cpp index fdf2d91c36..66c0ca750d 100644 --- a/libraries/shared/src/ThreadedAssignment.cpp +++ b/libraries/shared/src/ThreadedAssignment.cpp @@ -17,7 +17,6 @@ ThreadedAssignment::ThreadedAssignment(const QByteArray& packet) : Assignment(packet), _isFinished(false) { - } void ThreadedAssignment::setFinished(bool isFinished) { diff --git a/libraries/shared/src/ThreadedAssignment.h b/libraries/shared/src/ThreadedAssignment.h index f9652dd98d..32118997a9 100644 --- a/libraries/shared/src/ThreadedAssignment.h +++ b/libraries/shared/src/ThreadedAssignment.h @@ -13,6 +13,10 @@ #include "Assignment.h" + +class ThreadedAssignment; +typedef QSharedPointer SharedAssignmentPointer; + class ThreadedAssignment : public Assignment { Q_OBJECT public: @@ -35,8 +39,7 @@ private slots: void checkInWithDomainServerOrExit(); signals: void finished(); -}; + }; -typedef QSharedPointer SharedAssignmentPointer; #endif /* defined(__hifi__ThreadedAssignment__) */ From 0f9df4a8ee4fb9796e226ef95020423dd592a59b Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 14:11:47 -0700 Subject: [PATCH 034/595] clean up includes --- assignment-client/src/octree/OctreeQueryNode.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/assignment-client/src/octree/OctreeQueryNode.h b/assignment-client/src/octree/OctreeQueryNode.h index 66e4e5b0bb..f5b64627a7 100644 --- a/assignment-client/src/octree/OctreeQueryNode.h +++ b/assignment-client/src/octree/OctreeQueryNode.h @@ -10,16 +10,16 @@ #define __hifi__OctreeQueryNode__ #include -#include -#include -#include + #include +#include #include #include +#include +#include #include - -#include "OctreeServer.h" +#include // for SharedAssignmentPointer class OctreeSendThread; From 226274e98b8a4739ae9a179c106eb9a7671285fa Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 14:24:08 -0700 Subject: [PATCH 035/595] cleaning up SharedNodePointer usage --- assignment-client/src/octree/OctreeQueryNode.cpp | 2 +- assignment-client/src/octree/OctreeQueryNode.h | 2 +- assignment-client/src/octree/OctreeSendThread.cpp | 2 +- assignment-client/src/octree/OctreeSendThread.h | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/assignment-client/src/octree/OctreeQueryNode.cpp b/assignment-client/src/octree/OctreeQueryNode.cpp index 77d36f69fa..20a8d5ce4c 100644 --- a/assignment-client/src/octree/OctreeQueryNode.cpp +++ b/assignment-client/src/octree/OctreeQueryNode.cpp @@ -76,7 +76,7 @@ void OctreeQueryNode::deleteLater() { } -void OctreeQueryNode::initializeOctreeSendThread(const SharedAssignmentPointer& myAssignment, SharedNodePointer node) { +void OctreeQueryNode::initializeOctreeSendThread(const SharedAssignmentPointer& myAssignment, const SharedNodePointer& node) { // Create octree sending thread... _octreeSendThread = new OctreeSendThread(myAssignment, node); _octreeSendThread->initialize(true); diff --git a/assignment-client/src/octree/OctreeQueryNode.h b/assignment-client/src/octree/OctreeQueryNode.h index f5b64627a7..fd8d338663 100644 --- a/assignment-client/src/octree/OctreeQueryNode.h +++ b/assignment-client/src/octree/OctreeQueryNode.h @@ -84,7 +84,7 @@ public: OctreeSceneStats stats; - void initializeOctreeSendThread(const SharedAssignmentPointer& myAssignment, SharedNodePointer node); + void initializeOctreeSendThread(const SharedAssignmentPointer& myAssignment, const SharedNodePointer& node); bool isOctreeSendThreadInitalized() { return _octreeSendThread; } void dumpOutOfView(); diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index 8fe2fb6f30..14e7086f5c 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -19,7 +19,7 @@ quint64 startSceneSleepTime = 0; quint64 endSceneSleepTime = 0; -OctreeSendThread::OctreeSendThread(const SharedAssignmentPointer& myAssignment, SharedNodePointer node) : +OctreeSendThread::OctreeSendThread(const SharedAssignmentPointer& myAssignment, const SharedNodePointer& node) : _myAssignment(myAssignment), _myServer(static_cast(myAssignment.data())), _node(node), diff --git a/assignment-client/src/octree/OctreeSendThread.h b/assignment-client/src/octree/OctreeSendThread.h index a341a5be7d..a96a30d617 100644 --- a/assignment-client/src/octree/OctreeSendThread.h +++ b/assignment-client/src/octree/OctreeSendThread.h @@ -26,7 +26,7 @@ class OctreeQueryNode; class OctreeSendThread : public GenericThread { Q_OBJECT public: - OctreeSendThread(const SharedAssignmentPointer& myAssignment, SharedNodePointer node); + OctreeSendThread(const SharedAssignmentPointer& myAssignment, const SharedNodePointer& node); virtual ~OctreeSendThread(); void setIsShuttingDown(); From 6df3ff57c42503d8238148b9d4a58e3398c97df0 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 14:30:25 -0700 Subject: [PATCH 036/595] cleanup isNull() usage --- assignment-client/src/octree/OctreeSendThread.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index 14e7086f5c..b2e292fb12 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -73,7 +73,7 @@ bool OctreeSendThread::process() { } // check that our WeakPointer to our server is still valid - if (!_myServer || _myAssignment.isNull()) { + if (!_myServer || !_myAssignment) { return false; // exit early if it's not, it means the server is shutting down } @@ -90,7 +90,7 @@ bool OctreeSendThread::process() { // don't do any send processing until the initial load of the octree is complete... if (_myServer->isInitialLoadComplete()) { - if (!_node.isNull()) { + if (_node) { _nodeMissingCount = 0; OctreeQueryNode* nodeData = static_cast(_node->getLinkedData()); From 6601a0d4e96140cd6868294f5696560eb35d443d Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 14:54:39 -0700 Subject: [PATCH 037/595] cleaning up nodeKilled() --- .../src/octree/OctreeQueryNode.cpp | 21 ++++++++++++++++++- .../src/octree/OctreeQueryNode.h | 1 + assignment-client/src/octree/OctreeServer.cpp | 8 +++---- 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/assignment-client/src/octree/OctreeQueryNode.cpp b/assignment-client/src/octree/OctreeQueryNode.cpp index 20a8d5ce4c..57de87c45d 100644 --- a/assignment-client/src/octree/OctreeQueryNode.cpp +++ b/assignment-client/src/octree/OctreeQueryNode.cpp @@ -44,7 +44,7 @@ OctreeQueryNode::OctreeQueryNode() : OctreeQueryNode::~OctreeQueryNode() { _isShuttingDown = true; - const bool extraDebugging = false; + const bool extraDebugging = true; if (extraDebugging) { qDebug() << "OctreeQueryNode::~OctreeQueryNode()"; } @@ -75,6 +75,25 @@ void OctreeQueryNode::deleteLater() { OctreeQuery::deleteLater(); } +void OctreeQueryNode::nodeKilled() { + _isShuttingDown = true; + const bool extraDebugging = true; + if (extraDebugging) { + qDebug() << "OctreeQueryNode::nodeKilled()"; + } + if (_octreeSendThread) { + if (extraDebugging) { + qDebug() << "OctreeQueryNode::nodeKilled()... calling _octreeSendThread->terminate()"; + } + _octreeSendThread->terminate(); + if (extraDebugging) { + qDebug() << "OctreeQueryNode::nodeKilled()... calling delete _octreeSendThread"; + } + delete _octreeSendThread; + _octreeSendThread = NULL; + } +} + void OctreeQueryNode::initializeOctreeSendThread(const SharedAssignmentPointer& myAssignment, const SharedNodePointer& node) { // Create octree sending thread... diff --git a/assignment-client/src/octree/OctreeQueryNode.h b/assignment-client/src/octree/OctreeQueryNode.h index fd8d338663..c08bdcb2bf 100644 --- a/assignment-client/src/octree/OctreeQueryNode.h +++ b/assignment-client/src/octree/OctreeQueryNode.h @@ -94,6 +94,7 @@ public: unsigned int getlastOctreePacketLength() const { return _lastOctreePacketLength; } int getDuplicatePacketCount() const { return _duplicatePacketCount; } + void nodeKilled(); bool isShuttingDown() const { return _isShuttingDown; } private: diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 3134b577ae..6499a2f4a4 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -21,7 +21,7 @@ #include "OctreeServer.h" #include "OctreeServerConsts.h" -OctreeServer* OctreeServer::_instance; +OctreeServer* OctreeServer::_instance = NULL; int OctreeServer::_clientCount = 0; const int MOVING_AVERAGE_SAMPLE_COUNTS = 1000000; @@ -1064,10 +1064,8 @@ void OctreeServer::nodeKilled(SharedNodePointer node) { qDebug() << qPrintable(_safeServerName) << "server killed node:" << *node; OctreeQueryNode* nodeData = static_cast(node->getLinkedData()); if (nodeData) { - qDebug() << qPrintable(_safeServerName) << "server resetting Linked Data for node:" << *node; - node->setLinkedData(NULL); // set this first in case another thread comes through and tryes to acces this - qDebug() << qPrintable(_safeServerName) << "server deleting Linked Data for node:" << *node; - nodeData->deleteLater(); + qDebug() << qPrintable(_safeServerName) << "server calling nodeData->nodeKilled() for node:" << *node; + nodeData->nodeKilled(); // tell our node data and sending threads that we'd like to shut down } else { qDebug() << qPrintable(_safeServerName) << "server node missing linked data node:" << *node; } From a82a583030399c9651062e7db1cc0a21b1c488a0 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 14:59:28 -0700 Subject: [PATCH 038/595] cleanup --- assignment-client/src/octree/OctreeSendThread.cpp | 2 +- assignment-client/src/octree/OctreeServer.h | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index b2e292fb12..9c0ddbb779 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -72,7 +72,7 @@ bool OctreeSendThread::process() { return false; // exit early if we're shutting down } - // check that our WeakPointer to our server is still valid + // check that our server and assignment is still valid if (!_myServer || !_myAssignment) { return false; // exit early if it's not, it means the server is shutting down } diff --git a/assignment-client/src/octree/OctreeServer.h b/assignment-client/src/octree/OctreeServer.h index 6405dc986e..4ac0339001 100644 --- a/assignment-client/src/octree/OctreeServer.h +++ b/assignment-client/src/octree/OctreeServer.h @@ -13,7 +13,6 @@ #include #include #include -#include #include From d2cf898e220f1829f81d5a261cfa0235218983d0 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 15:06:17 -0700 Subject: [PATCH 039/595] revert tweaks --- libraries/shared/src/ThreadedAssignment.h | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/libraries/shared/src/ThreadedAssignment.h b/libraries/shared/src/ThreadedAssignment.h index 32118997a9..aa2994a2be 100644 --- a/libraries/shared/src/ThreadedAssignment.h +++ b/libraries/shared/src/ThreadedAssignment.h @@ -13,10 +13,6 @@ #include "Assignment.h" - -class ThreadedAssignment; -typedef QSharedPointer SharedAssignmentPointer; - class ThreadedAssignment : public Assignment { Q_OBJECT public: @@ -39,7 +35,9 @@ private slots: void checkInWithDomainServerOrExit(); signals: void finished(); - }; +}; + +typedef QSharedPointer SharedAssignmentPointer; #endif /* defined(__hifi__ThreadedAssignment__) */ From 6c08e2a4075082fb5aa3683a000a8da8d615eed6 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 31 Mar 2014 15:06:58 -0700 Subject: [PATCH 040/595] add option for domain-server to enforce DTLS --- cmake/modules/FindGnuTLS.cmake | 2 +- domain-server/src/DomainServer.cpp | 161 +++++++++++++---------- domain-server/src/DomainServer.h | 3 +- interface/CMakeLists.txt | 4 +- libraries/shared/CMakeLists.txt | 4 +- libraries/shared/src/DomainInfo.cpp | 44 +++---- libraries/shared/src/DomainInfo.h | 20 +-- libraries/shared/src/NodeList.cpp | 175 +++++++------------------ libraries/shared/src/NodeList.h | 6 +- libraries/shared/src/PacketHeaders.cpp | 2 +- libraries/shared/src/PacketHeaders.h | 6 +- 11 files changed, 180 insertions(+), 247 deletions(-) diff --git a/cmake/modules/FindGnuTLS.cmake b/cmake/modules/FindGnuTLS.cmake index d09ba38fb7..f56a0db7d2 100644 --- a/cmake/modules/FindGnuTLS.cmake +++ b/cmake/modules/FindGnuTLS.cmake @@ -5,7 +5,7 @@ # Once done this will define # # GNUTLS_FOUND - system found GnuTLS -# GNUTLS_INCLUDE_DIRS - the GnuTLS include directory +# GNUTLS_INCLUDE_DIR - the GnuTLS include directory # GNUTLS_LIBRARY - Link this to use GnuTLS # # Created on 3/31/2014 by Stephen Birarda diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index df0935ba54..7584b00c8d 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -180,6 +180,18 @@ void DomainServer::setupNodeListAndAssignments(const QUuid& sessionUUID) { domainServerPort = _argumentList.value(argumentIndex + 1).toUShort(); } + unsigned short domainServerDTLSPort = -1; + + if (_isUsingDTLS) { + domainServerDTLSPort = DEFAULT_DOMAIN_SERVER_DTLS_PORT; + + const QString CUSTOM_DTLS_PORT_OPTION = "--dtlsPort"; + + if ((argumentIndex = _argumentList.indexOf(CUSTOM_DTLS_PORT_OPTION)) != -1) { + domainServerDTLSPort = _argumentList.value(argumentIndex + 1).toUShort(); + } + } + QSet parsedTypes(QSet() << Assignment::AgentType); parseCommandLineTypeConfigs(_argumentList, parsedTypes); @@ -191,7 +203,7 @@ void DomainServer::setupNodeListAndAssignments(const QUuid& sessionUUID) { populateDefaultStaticAssignmentsExcludingTypes(parsedTypes); - NodeList* nodeList = NodeList::createInstance(NodeType::DomainServer, domainServerPort); + NodeList* nodeList = NodeList::createInstance(NodeType::DomainServer, domainServerPort, domainServerDTLSPort); // create a random UUID for this session for the domain-server nodeList->setSessionUUID(sessionUUID); @@ -519,10 +531,6 @@ void DomainServer::readAvailableDatagrams() { NodeList* nodeList = NodeList::getInstance(); HifiSockAddr senderSockAddr; - - static QByteArray assignmentPacket = byteArrayWithPopulatedHeader(PacketTypeCreateAssignment); - static int numAssignmentPacketHeaderBytes = assignmentPacket.size(); - QByteArray receivedPacket; while (nodeList->getNodeSocket().hasPendingDatagrams()) { @@ -530,22 +538,42 @@ void DomainServer::readAvailableDatagrams() { nodeList->getNodeSocket().readDatagram(receivedPacket.data(), receivedPacket.size(), senderSockAddr.getAddressPointer(), senderSockAddr.getPortPointer()); - if (nodeList->packetVersionAndHashMatch(receivedPacket)) { - PacketType requestType = packetTypeForPacket(receivedPacket); + if (!_isUsingDTLS) { + // not using DTLS, process datagram normally + processDatagram(receivedPacket, senderSockAddr); + } else { + // we're using DTLS, so tell the sender to get back to us using DTLS + static QByteArray dtlsRequiredPacket = byteArrayWithPopulatedHeader(PacketTypeDomainServerRequireDTLS); + static int numBytesDTLSHeader = numBytesForPacketHeaderGivenPacketType(PacketTypeDomainServerRequireDTLS); - if (requestType == PacketTypeDomainConnectRequest) { - QDataStream packetStream(receivedPacket); - packetStream.skipRawData(numBytesForPacketHeader(receivedPacket)); - - quint8 hasRegistrationToken; - packetStream >> hasRegistrationToken; - - // we don't require authentication - add this node to our NodeList - // and send back session UUID right away - addNodeToNodeListAndConfirmConnection(receivedPacket, senderSockAddr); - - } else if (requestType == PacketTypeDomainListRequest) { - QUuid nodeUUID = uuidFromPacketHeader(receivedPacket); + if (dtlsRequiredPacket.size() == numBytesDTLSHeader) { + // pack the port that we accept DTLS traffic on + unsigned short dtlsPort = nodeList->getDTLSSocket().localPort(); + dtlsRequiredPacket.replace(numBytesDTLSHeader, sizeof(dtlsPort), reinterpret_cast(&dtlsPort)); + } + + nodeList->getNodeSocket().writeDatagram(dtlsRequiredPacket, senderSockAddr.getAddress(), senderSockAddr.getPort()); + } + } +} + +void DomainServer::readAvailableDTLSDatagrams() { + +} + +void DomainServer::processDatagram(const QByteArray& receivedPacket, const HifiSockAddr& senderSockAddr) { + NodeList* nodeList = NodeList::getInstance(); + + static QByteArray assignmentPacket = byteArrayWithPopulatedHeader(PacketTypeCreateAssignment); + static int numAssignmentPacketHeaderBytes = assignmentPacket.size(); + + if (nodeList->packetVersionAndHashMatch(receivedPacket)) { + PacketType requestType = packetTypeForPacket(receivedPacket); + + if (requestType == PacketTypeDomainListRequest) { + QUuid nodeUUID = uuidFromPacketHeader(receivedPacket); + + if (!nodeUUID.isNull() && nodeList->nodeWithUUID(nodeUUID)) { NodeType_t throwawayNodeType; HifiSockAddr nodePublicAddress, nodeLocalAddress; @@ -553,69 +581,68 @@ void DomainServer::readAvailableDatagrams() { receivedPacket, senderSockAddr); SharedNodePointer checkInNode = nodeList->updateSocketsForNode(nodeUUID, nodePublicAddress, nodeLocalAddress); - + // update last receive to now quint64 timeNow = usecTimestampNow(); checkInNode->setLastHeardMicrostamp(timeNow); - - + sendDomainListToNode(checkInNode, senderSockAddr, nodeInterestListFromPacket(receivedPacket, numNodeInfoBytes)); + } else { + // new node - add this node to our NodeList + // and send back session UUID right away + addNodeToNodeListAndConfirmConnection(receivedPacket, senderSockAddr); + } + + } else if (requestType == PacketTypeRequestAssignment) { + + // construct the requested assignment from the packet data + Assignment requestAssignment(receivedPacket); + + // Suppress these for Assignment::AgentType to once per 5 seconds + static quint64 lastNoisyMessage = usecTimestampNow(); + quint64 timeNow = usecTimestampNow(); + const quint64 NOISY_TIME_ELAPSED = 5 * USECS_PER_SECOND; + bool noisyMessage = false; + if (requestAssignment.getType() != Assignment::AgentType || (timeNow - lastNoisyMessage) > NOISY_TIME_ELAPSED) { + qDebug() << "Received a request for assignment type" << requestAssignment.getType() + << "from" << senderSockAddr; + noisyMessage = true; + } + + SharedAssignmentPointer assignmentToDeploy = deployableAssignmentForRequest(requestAssignment); + + if (assignmentToDeploy) { + qDebug() << "Deploying assignment -" << *assignmentToDeploy.data() << "- to" << senderSockAddr; - } else if (requestType == PacketTypeRequestAssignment) { + // give this assignment out, either the type matches or the requestor said they will take any + assignmentPacket.resize(numAssignmentPacketHeaderBytes); - // construct the requested assignment from the packet data - Assignment requestAssignment(receivedPacket); + QDataStream assignmentStream(&assignmentPacket, QIODevice::Append); - // Suppress these for Assignment::AgentType to once per 5 seconds - static quint64 lastNoisyMessage = usecTimestampNow(); - quint64 timeNow = usecTimestampNow(); - const quint64 NOISY_TIME_ELAPSED = 5 * USECS_PER_SECOND; - bool noisyMessage = false; + assignmentStream << *assignmentToDeploy.data(); + + nodeList->getNodeSocket().writeDatagram(assignmentPacket, + senderSockAddr.getAddress(), senderSockAddr.getPort()); + } else { if (requestAssignment.getType() != Assignment::AgentType || (timeNow - lastNoisyMessage) > NOISY_TIME_ELAPSED) { - qDebug() << "Received a request for assignment type" << requestAssignment.getType() + qDebug() << "Unable to fulfill assignment request of type" << requestAssignment.getType() << "from" << senderSockAddr; noisyMessage = true; } - - SharedAssignmentPointer assignmentToDeploy = deployableAssignmentForRequest(requestAssignment); - - if (assignmentToDeploy) { - qDebug() << "Deploying assignment -" << *assignmentToDeploy.data() << "- to" << senderSockAddr; - - // give this assignment out, either the type matches or the requestor said they will take any - assignmentPacket.resize(numAssignmentPacketHeaderBytes); - - QDataStream assignmentStream(&assignmentPacket, QIODevice::Append); - - assignmentStream << *assignmentToDeploy.data(); - - nodeList->getNodeSocket().writeDatagram(assignmentPacket, - senderSockAddr.getAddress(), senderSockAddr.getPort()); - } else { - if (requestAssignment.getType() != Assignment::AgentType || (timeNow - lastNoisyMessage) > NOISY_TIME_ELAPSED) { - qDebug() << "Unable to fulfill assignment request of type" << requestAssignment.getType() - << "from" << senderSockAddr; - noisyMessage = true; - } - } - - if (noisyMessage) { - lastNoisyMessage = timeNow; - } - } else if (requestType == PacketTypeNodeJsonStats) { - SharedNodePointer matchingNode = nodeList->sendingNodeForPacket(receivedPacket); - if (matchingNode) { - reinterpret_cast(matchingNode->getLinkedData())->parseJSONStatsPacket(receivedPacket); - } + } + + if (noisyMessage) { + lastNoisyMessage = timeNow; + } + } else if (requestType == PacketTypeNodeJsonStats) { + SharedNodePointer matchingNode = nodeList->sendingNodeForPacket(receivedPacket); + if (matchingNode) { + reinterpret_cast(matchingNode->getLinkedData())->parseJSONStatsPacket(receivedPacket); } } } } -void DomainServer::readAvailableDTLSDatagrams() { - -} - QJsonObject DomainServer::jsonForSocket(const HifiSockAddr& socket) { QJsonObject socketJSON; diff --git a/domain-server/src/DomainServer.h b/domain-server/src/DomainServer.h index ba2b47a2e7..7ee6d7374e 100644 --- a/domain-server/src/DomainServer.h +++ b/domain-server/src/DomainServer.h @@ -51,7 +51,8 @@ private: bool optionallySetupDTLS(); bool readX509KeyAndCertificate(); - void requestAuthenticationFromPotentialNode(const HifiSockAddr& senderSockAddr); + void processDatagram(const QByteArray& receivedPacket, const HifiSockAddr& senderSockAddr); + void addNodeToNodeListAndConfirmConnection(const QByteArray& packet, const HifiSockAddr& senderSockAddr, const QJsonObject& authJsonObject = QJsonObject()); int parseNodeDataFromByteArray(NodeType_t& nodeType, HifiSockAddr& publicSockAddr, diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index f991212a6e..18210668f6 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -67,6 +67,7 @@ foreach(EXTERNAL_SOURCE_SUBDIR ${EXTERNAL_SOURCE_SUBDIRS}) endforeach(EXTERNAL_SOURCE_SUBDIR) find_package(Qt5 COMPONENTS Core Gui Multimedia Network OpenGL Script Svg WebKit WebKitWidgets Xml UiTools) +find_package(GnuTLS REQUIRED) # grab the ui files in resources/ui file (GLOB_RECURSE QT_UI_FILES ui/*.ui) @@ -187,7 +188,7 @@ include_directories("${PROJECT_SOURCE_DIR}/src" "${PROJECT_BINARY_DIR}/includes" # include external library headers # use system flag so warnings are supressed -include_directories(SYSTEM "${FACESHIFT_INCLUDE_DIRS}") +include_directories(SYSTEM "${FACESHIFT_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") target_link_libraries( ${TARGET_NAME} @@ -195,6 +196,7 @@ target_link_libraries( "${ZLIB_LIBRARIES}" Qt5::Core Qt5::Gui Qt5::Multimedia Qt5::Network Qt5::OpenGL Qt5::Script Qt5::Svg Qt5::WebKit Qt5::WebKitWidgets Qt5::Xml Qt5::UiTools + "${GNUTLS_LIBRARY}" ) if (APPLE) diff --git a/libraries/shared/CMakeLists.txt b/libraries/shared/CMakeLists.txt index 3af7272cc1..6b4dafd8d4 100644 --- a/libraries/shared/CMakeLists.txt +++ b/libraries/shared/CMakeLists.txt @@ -11,6 +11,7 @@ set(TARGET_NAME shared) project(${TARGET_NAME}) find_package(Qt5 COMPONENTS Network Widgets Xml) +find_package(GnuTLS REQUIRED) include(${MACRO_DIR}/SetupHifiLibrary.cmake) setup_hifi_library(${TARGET_NAME}) @@ -32,4 +33,5 @@ if (UNIX AND NOT APPLE) target_link_libraries(${TARGET_NAME} "${CMAKE_THREAD_LIBS_INIT}") endif (UNIX AND NOT APPLE) -target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets) +include_directories("${GNUTLS_INCLUDE_DIR}") +target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/shared/src/DomainInfo.cpp b/libraries/shared/src/DomainInfo.cpp index bed638bf59..648f658619 100644 --- a/libraries/shared/src/DomainInfo.cpp +++ b/libraries/shared/src/DomainInfo.cpp @@ -8,7 +8,7 @@ #include -#include "AccountManager.h" +#include "PacketHeaders.h" #include "DomainInfo.h" @@ -16,22 +16,14 @@ DomainInfo::DomainInfo() : _uuid(), _sockAddr(HifiSockAddr(QHostAddress::Null, DEFAULT_DOMAIN_SERVER_PORT)), _assignmentUUID(), - _connectionSecret(), - _registrationToken(), - _rootAuthenticationURL(), - _publicKey(), + _requiresDTLS(false), _isConnected(false) { - // clear appropriate variables after a domain-server logout - connect(&AccountManager::getInstance(), &AccountManager::logoutComplete, this, &DomainInfo::logout); + } void DomainInfo::clearConnectionInfo() { _uuid = QUuid(); - _connectionSecret = QUuid(); - _registrationToken = QByteArray(); - _rootAuthenticationURL = QUrl(); - _publicKey = QString(); _isConnected = false; } @@ -39,13 +31,7 @@ void DomainInfo::reset() { clearConnectionInfo(); _hostname = QString(); _sockAddr.setAddress(QHostAddress::Null); -} - -void DomainInfo::parseAuthInformationFromJsonObject(const QJsonObject& jsonObject) { - QJsonObject dataObject = jsonObject["data"].toObject(); - _connectionSecret = QUuid(dataObject["connection_secret"].toString()); - _registrationToken = QByteArray::fromHex(dataObject["registration_token"].toString().toUtf8()); - _publicKey = dataObject["public_key"].toString(); + _requiresDTLS = false; } void DomainInfo::setSockAddr(const HifiSockAddr& sockAddr) { @@ -114,13 +100,15 @@ void DomainInfo::setIsConnected(bool isConnected) { } } -void DomainInfo::logout() { - // clear any information related to auth for this domain, assuming it had requested auth - if (!_rootAuthenticationURL.isEmpty()) { - _rootAuthenticationURL = QUrl(); - _connectionSecret = QUuid(); - _registrationToken = QByteArray(); - _publicKey = QString(); - _isConnected = false; - } -} +void DomainInfo::parseDTLSRequirementPacket(const QByteArray& dtlsRequirementPacket) { + // figure out the port that the DS wants us to use for us to talk to them with DTLS + int numBytesPacketHeader = numBytesForPacketHeader(dtlsRequirementPacket); + + unsigned short dtlsPort = 0; + memcpy(&dtlsPort, dtlsRequirementPacket.data() + numBytesPacketHeader, sizeof(dtlsPort)); + + _sockAddr.setPort(dtlsPort); + _requiresDTLS = true; + + qDebug() << "domain-server DTLS port changed to" << dtlsPort << "- DTLS enabled."; +} \ No newline at end of file diff --git a/libraries/shared/src/DomainInfo.h b/libraries/shared/src/DomainInfo.h index da65525f9d..63c7dcbf6d 100644 --- a/libraries/shared/src/DomainInfo.h +++ b/libraries/shared/src/DomainInfo.h @@ -18,6 +18,7 @@ const QString DEFAULT_DOMAIN_HOSTNAME = "alpha.highfidelity.io"; const unsigned short DEFAULT_DOMAIN_SERVER_PORT = 40102; +const unsigned short DEFAULT_DOMAIN_SERVER_DTLS_PORT = 40103; class DomainInfo : public QObject { Q_OBJECT @@ -26,8 +27,6 @@ public: void clearConnectionInfo(); - void parseAuthInformationFromJsonObject(const QJsonObject& jsonObject); - const QUuid& getUUID() const { return _uuid; } void setUUID(const QUuid& uuid) { _uuid = uuid; } @@ -45,21 +44,13 @@ public: const QUuid& getAssignmentUUID() const { return _assignmentUUID; } void setAssignmentUUID(const QUuid& assignmentUUID) { _assignmentUUID = assignmentUUID; } - const QUuid& getConnectionSecret() const { return _connectionSecret; } - void setConnectionSecret(const QUuid& connectionSecret) { _connectionSecret = connectionSecret; } - - const QByteArray& getRegistrationToken() const { return _registrationToken; } - - const QUrl& getRootAuthenticationURL() const { return _rootAuthenticationURL; } - void setRootAuthenticationURL(const QUrl& rootAuthenticationURL) { _rootAuthenticationURL = rootAuthenticationURL; } - bool isConnected() const { return _isConnected; } void setIsConnected(bool isConnected); + void parseDTLSRequirementPacket(const QByteArray& dtlsRequirementPacket); + private slots: void completedHostnameLookup(const QHostInfo& hostInfo); - - void logout(); signals: void hostnameChanged(const QString& hostname); void connectedToDomain(const QString& hostname); @@ -70,10 +61,7 @@ private: QString _hostname; HifiSockAddr _sockAddr; QUuid _assignmentUUID; - QUuid _connectionSecret; - QByteArray _registrationToken; - QUrl _rootAuthenticationURL; - QString _publicKey; + bool _requiresDTLS; bool _isConnected; }; diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index b053db356e..bb4ff84865 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -34,11 +34,11 @@ const QUrl DEFAULT_NODE_AUTH_URL = QUrl("https://data-web.highfidelity.io"); NodeList* NodeList::_sharedInstance = NULL; -NodeList* NodeList::createInstance(char ownerType, unsigned short int socketListenPort) { +NodeList* NodeList::createInstance(char ownerType, unsigned short socketListenPort, unsigned short dtlsPort) { if (!_sharedInstance) { NodeType::init(); - _sharedInstance = new NodeList(ownerType, socketListenPort); + _sharedInstance = new NodeList(ownerType, socketListenPort, dtlsPort); // register the SharedNodePointer meta-type for signals/slots qRegisterMetaType(); @@ -58,7 +58,7 @@ NodeList* NodeList::getInstance() { } -NodeList::NodeList(char newOwnerType, unsigned short int newSocketListenPort) : +NodeList::NodeList(char newOwnerType, unsigned short socketListenPort, unsigned short dtlsListenPort) : _nodeHash(), _nodeHashMutex(QMutex::Recursive), _nodeSocket(this), @@ -74,9 +74,15 @@ NodeList::NodeList(char newOwnerType, unsigned short int newSocketListenPort) : _numCollectedBytes(0), _packetStatTimer() { - _nodeSocket.bind(QHostAddress::AnyIPv4, newSocketListenPort); + _nodeSocket.bind(QHostAddress::AnyIPv4, socketListenPort); qDebug() << "NodeList socket is listening on" << _nodeSocket.localPort(); + if (dtlsListenPort > 0) { + // we have a specfic DTLS port, bind that socket now + _dtlsSocket.bind(QHostAddress::AnyIPv4, dtlsListenPort); + qDebug() << "NodeList DTLS socket is listening on" << _dtlsSocket.localPort(); + } + // clear our NodeList when the domain changes connect(&_domainInfo, &DomainInfo::hostnameChanged, this, &NodeList::reset); @@ -141,7 +147,7 @@ bool NodeList::packetVersionAndHashMatch(const QByteArray& packet) { } const QSet NON_VERIFIED_PACKETS = QSet() - << PacketTypeDomainServerAuthRequest << PacketTypeDomainConnectRequest + << PacketTypeDomainServerRequireDTLS << PacketTypeDomainList << PacketTypeDomainListRequest << PacketTypeStunResponse << PacketTypeDataServerConfirm << PacketTypeDataServerGet << PacketTypeDataServerPut << PacketTypeDataServerSend << PacketTypeCreateAssignment << PacketTypeRequestAssignment; @@ -158,31 +164,6 @@ bool NodeList::packetVersionAndHashMatch(const QByteArray& packet) { << uuidFromPacketHeader(packet); } } else { - if (checkType == PacketTypeDomainList) { - - if (_domainInfo.getRootAuthenticationURL().isEmpty() && _domainInfo.getUUID().isNull()) { - // if this is a domain-server that doesn't require auth, - // pull the UUID from this packet and set it as our domain-server UUID - _domainInfo.setUUID(uuidFromPacketHeader(packet)); - - // we also know this domain-server requires no authentication - // so set the account manager root URL to the default one - AccountManager::getInstance().setAuthURL(DEFAULT_NODE_AUTH_URL); - } - - if (_domainInfo.getUUID() == uuidFromPacketHeader(packet)) { - if (hashForPacketAndConnectionUUID(packet, _domainInfo.getConnectionSecret()) == hashFromPacketHeader(packet)) { - // this is a packet from the domain-server (PacketTypeDomainServerListRequest) - // and the sender UUID matches the UUID we expect for the domain - return true; - } else { - // this is a packet from the domain-server but there is a hash mismatch - qDebug() << "Packet hash mismatch on" << checkType << "from domain-server at" << _domainInfo.getHostname(); - return false; - } - } - } - qDebug() << "Packet of type" << checkType << "received from unknown node with UUID" << uuidFromPacketHeader(packet); } @@ -246,7 +227,7 @@ qint64 NodeList::sendStatsToDomainServer(const QJsonObject& statsObject) { statsPacketStream << statsObject.toVariantMap(); - return writeDatagram(statsPacket, _domainInfo.getSockAddr(), _domainInfo.getConnectionSecret()); + return writeDatagram(statsPacket, _domainInfo.getSockAddr(), QUuid()); } void NodeList::timePingReply(const QByteArray& packet, const SharedNodePointer& sendingNode) { @@ -290,10 +271,8 @@ void NodeList::processNodeData(const HifiSockAddr& senderSockAddr, const QByteAr processDomainServerList(packet); break; } - case PacketTypeDomainServerAuthRequest: { - // the domain-server has asked us to auth via a data-server - processDomainServerAuthRequest(packet); - + case PacketTypeDomainServerRequireDTLS: { + _domainInfo.parseDTLSRequirementPacket(packet); break; } case PacketTypePing: { @@ -590,61 +569,44 @@ void NodeList::sendDomainServerCheckIn() { // send a STUN request to figure it out sendSTUNRequest(); } else if (!_domainInfo.getIP().isNull()) { - if (_domainInfo.getRootAuthenticationURL().isEmpty() - || !_sessionUUID.isNull() - || !_domainInfo.getRegistrationToken().isEmpty() ) { - // construct the DS check in packet - - PacketType domainPacketType = _sessionUUID.isNull() ? PacketTypeDomainConnectRequest : PacketTypeDomainListRequest; - - QUuid packetUUID = (domainPacketType == PacketTypeDomainListRequest) - ? _sessionUUID : _domainInfo.getAssignmentUUID(); - - QByteArray domainServerPacket = byteArrayWithPopulatedHeader(domainPacketType, packetUUID); - QDataStream packetStream(&domainServerPacket, QIODevice::Append); - - if (domainPacketType == PacketTypeDomainConnectRequest) { - // we may need a registration token to present to the domain-server - packetStream << (quint8) !_domainInfo.getRegistrationToken().isEmpty(); - - if (!_domainInfo.getRegistrationToken().isEmpty()) { - // if we have a registration token send that along in the request - packetStream << _domainInfo.getRegistrationToken(); - } - } - - // pack our data to send to the domain-server - packetStream << _ownerType << _publicSockAddr - << HifiSockAddr(QHostAddress(getHostOrderLocalAddress()), _nodeSocket.localPort()) - << (quint8) _nodeTypesOfInterest.size(); - - // copy over the bytes for node types of interest, if required - foreach (NodeType_t nodeTypeOfInterest, _nodeTypesOfInterest) { - packetStream << nodeTypeOfInterest; - } - - writeDatagram(domainServerPacket, _domainInfo.getSockAddr(), _domainInfo.getConnectionSecret()); - const int NUM_DOMAIN_SERVER_CHECKINS_PER_STUN_REQUEST = 5; - static unsigned int numDomainCheckins = 0; - - // send a STUN request every Nth domain server check in so we update our public socket, if required - if (numDomainCheckins++ % NUM_DOMAIN_SERVER_CHECKINS_PER_STUN_REQUEST == 0) { - sendSTUNRequest(); - } - - if (_numNoReplyDomainCheckIns >= MAX_SILENT_DOMAIN_SERVER_CHECK_INS) { - // we haven't heard back from DS in MAX_SILENT_DOMAIN_SERVER_CHECK_INS - // so emit our signal that indicates that - emit limitOfSilentDomainCheckInsReached(); - } - - // increment the count of un-replied check-ins - _numNoReplyDomainCheckIns++; - } else if (AccountManager::getInstance().hasValidAccessToken()) { - // we have an access token we can use for the authentication server the domain-server requested - // so ask that server to provide us with information to connect to the domain-server - requestAuthForDomainServer(); + // construct the DS check in packet + + PacketType domainPacketType = _sessionUUID.isNull() ? PacketTypeDomainConnectRequest : PacketTypeDomainListRequest; + + QUuid packetUUID = (domainPacketType == PacketTypeDomainListRequest) + ? _sessionUUID : _domainInfo.getAssignmentUUID(); + + QByteArray domainServerPacket = byteArrayWithPopulatedHeader(domainPacketType, packetUUID); + QDataStream packetStream(&domainServerPacket, QIODevice::Append); + + + // pack our data to send to the domain-server + packetStream << _ownerType << _publicSockAddr + << HifiSockAddr(QHostAddress(getHostOrderLocalAddress()), _nodeSocket.localPort()) + << (quint8) _nodeTypesOfInterest.size(); + + // copy over the bytes for node types of interest, if required + foreach (NodeType_t nodeTypeOfInterest, _nodeTypesOfInterest) { + packetStream << nodeTypeOfInterest; } + + writeDatagram(domainServerPacket, _domainInfo.getSockAddr(), QUuid()); + const int NUM_DOMAIN_SERVER_CHECKINS_PER_STUN_REQUEST = 5; + static unsigned int numDomainCheckins = 0; + + // send a STUN request every Nth domain server check in so we update our public socket, if required + if (numDomainCheckins++ % NUM_DOMAIN_SERVER_CHECKINS_PER_STUN_REQUEST == 0) { + sendSTUNRequest(); + } + + if (_numNoReplyDomainCheckIns >= MAX_SILENT_DOMAIN_SERVER_CHECK_INS) { + // we haven't heard back from DS in MAX_SILENT_DOMAIN_SERVER_CHECK_INS + // so emit our signal that indicates that + emit limitOfSilentDomainCheckInsReached(); + } + + // increment the count of un-replied check-ins + _numNoReplyDomainCheckIns++; } } @@ -707,41 +669,6 @@ int NodeList::processDomainServerList(const QByteArray& packet) { return readNodes; } -void NodeList::domainServerAuthReply(const QJsonObject& jsonObject) { - _domainInfo.parseAuthInformationFromJsonObject(jsonObject); -} - -void NodeList::requestAuthForDomainServer() { - JSONCallbackParameters callbackParams; - callbackParams.jsonCallbackReceiver = this; - callbackParams.jsonCallbackMethod = "domainServerAuthReply"; - - AccountManager::getInstance().authenticatedRequest("/api/v1/domains/" - + uuidStringWithoutCurlyBraces(_domainInfo.getUUID()) + "/auth.json", - QNetworkAccessManager::GetOperation, - callbackParams); -} - -void NodeList::processDomainServerAuthRequest(const QByteArray& packet) { - QDataStream authPacketStream(packet); - authPacketStream.skipRawData(numBytesForPacketHeader(packet)); - - _domainInfo.setUUID(uuidFromPacketHeader(packet)); - AccountManager& accountManager = AccountManager::getInstance(); - - // grab the hostname this domain-server wants us to authenticate with - QUrl authenticationRootURL; - authPacketStream >> authenticationRootURL; - - accountManager.setAuthURL(authenticationRootURL); - _domainInfo.setRootAuthenticationURL(authenticationRootURL); - - if (AccountManager::getInstance().checkAndSignalForAccessToken()) { - // request a domain-server auth - requestAuthForDomainServer(); - } -} - void NodeList::sendAssignment(Assignment& assignment) { PacketType assignmentPacketType = assignment.getCommand() == Assignment::CreateCommand diff --git a/libraries/shared/src/NodeList.h b/libraries/shared/src/NodeList.h index 24281e3aa3..4f9b839779 100644 --- a/libraries/shared/src/NodeList.h +++ b/libraries/shared/src/NodeList.h @@ -63,7 +63,7 @@ namespace PingType { class NodeList : public QObject { Q_OBJECT public: - static NodeList* createInstance(char ownerType, unsigned short int socketListenPort = 0); + static NodeList* createInstance(char ownerType, unsigned short socketListenPort = 0, unsigned short dtlsPort = 0); static NodeList* getInstance(); NodeType_t getOwnerType() const { return _ownerType; } void setOwnerType(NodeType_t ownerType) { _ownerType = ownerType; } @@ -140,12 +140,10 @@ signals: void nodeAdded(SharedNodePointer); void nodeKilled(SharedNodePointer); void limitOfSilentDomainCheckInsReached(); -private slots: - void domainServerAuthReply(const QJsonObject& jsonObject); private: static NodeList* _sharedInstance; - NodeList(char ownerType, unsigned short int socketListenPort); + NodeList(char ownerType, unsigned short socketListenPort, unsigned short dtlsListenPort); NodeList(NodeList const&); // Don't implement, needed to avoid copies of singleton void operator=(NodeList const&); // Don't implement, needed to avoid copies of singleton void sendSTUNRequest(); diff --git a/libraries/shared/src/PacketHeaders.cpp b/libraries/shared/src/PacketHeaders.cpp index c7518708ce..0035f053fb 100644 --- a/libraries/shared/src/PacketHeaders.cpp +++ b/libraries/shared/src/PacketHeaders.cpp @@ -52,7 +52,7 @@ PacketVersion versionForPacketType(PacketType type) { return 1; case PacketTypeDomainList: case PacketTypeDomainListRequest: - return 1; + return 2; case PacketTypeCreateAssignment: case PacketTypeRequestAssignment: return 1; diff --git a/libraries/shared/src/PacketHeaders.h b/libraries/shared/src/PacketHeaders.h index a9bc5d3763..483fdb8a4d 100644 --- a/libraries/shared/src/PacketHeaders.h +++ b/libraries/shared/src/PacketHeaders.h @@ -57,9 +57,9 @@ enum PacketType { PacketTypeMetavoxelData, PacketTypeAvatarIdentity, PacketTypeAvatarBillboard, - PacketTypeDomainConnectRequest, - PacketTypeDomainServerAuthRequest, - PacketTypeNodeJsonStats + PacketTypeDomainConnectRequest, // RE-USABLE + PacketTypeDomainServerRequireDTLS, + PacketTypeNodeJsonStats, }; typedef char PacketVersion; From 5ef437da39ee86794dfadb97cc5810fe1f86d3ca Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 15:07:13 -0700 Subject: [PATCH 041/595] revert tweaks --- libraries/shared/src/ThreadedAssignment.h | 1 - 1 file changed, 1 deletion(-) diff --git a/libraries/shared/src/ThreadedAssignment.h b/libraries/shared/src/ThreadedAssignment.h index aa2994a2be..f9652dd98d 100644 --- a/libraries/shared/src/ThreadedAssignment.h +++ b/libraries/shared/src/ThreadedAssignment.h @@ -39,5 +39,4 @@ signals: typedef QSharedPointer SharedAssignmentPointer; - #endif /* defined(__hifi__ThreadedAssignment__) */ From 6fd1a6f4e44f7bec3f5632cac242a6cc70a9f09f Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 15:07:34 -0700 Subject: [PATCH 042/595] revert tweaks --- libraries/shared/src/ThreadedAssignment.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries/shared/src/ThreadedAssignment.cpp b/libraries/shared/src/ThreadedAssignment.cpp index 66c0ca750d..09569dbe81 100644 --- a/libraries/shared/src/ThreadedAssignment.cpp +++ b/libraries/shared/src/ThreadedAssignment.cpp @@ -17,6 +17,7 @@ ThreadedAssignment::ThreadedAssignment(const QByteArray& packet) : Assignment(packet), _isFinished(false) { + } void ThreadedAssignment::setFinished(bool isFinished) { From 989e087701dc7e324b0e2293f5467052a01f7850 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 15:09:18 -0700 Subject: [PATCH 043/595] revert tweaks --- libraries/shared/src/ThreadedAssignment.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/shared/src/ThreadedAssignment.cpp b/libraries/shared/src/ThreadedAssignment.cpp index 09569dbe81..fdf2d91c36 100644 --- a/libraries/shared/src/ThreadedAssignment.cpp +++ b/libraries/shared/src/ThreadedAssignment.cpp @@ -17,7 +17,7 @@ ThreadedAssignment::ThreadedAssignment(const QByteArray& packet) : Assignment(packet), _isFinished(false) { - + } void ThreadedAssignment::setFinished(bool isFinished) { From 514f43c6cc0dad10b7eb17ee3765c609a7af2fa5 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 15:10:36 -0700 Subject: [PATCH 044/595] revert tweaks --- assignment-client/src/octree/OctreeServer.h | 7 ------- 1 file changed, 7 deletions(-) diff --git a/assignment-client/src/octree/OctreeServer.h b/assignment-client/src/octree/OctreeServer.h index 4ac0339001..63d43b6634 100644 --- a/assignment-client/src/octree/OctreeServer.h +++ b/assignment-client/src/octree/OctreeServer.h @@ -19,10 +19,6 @@ #include #include -class OctreeServer; -class OctreeQueryNode; -class OctreeSendThread; - #include "OctreePersistThread.h" #include "OctreeSendThread.h" #include "OctreeServerConsts.h" @@ -30,9 +26,6 @@ class OctreeSendThread; const int DEFAULT_PACKETS_PER_INTERVAL = 2000; // some 120,000 packets per second total -//class OctreeServer; -//typedef QSharedPointer SharedOctreeServerPointer; - /// Handles assignments of type OctreeServer - sending octrees to various clients. class OctreeServer : public ThreadedAssignment, public HTTPRequestHandler { Q_OBJECT From 27f42b5b863f35ba187e2f986fb25c98def3904b Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 15:15:54 -0700 Subject: [PATCH 045/595] clean up headers --- assignment-client/src/octree/OctreeSendThread.h | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/assignment-client/src/octree/OctreeSendThread.h b/assignment-client/src/octree/OctreeSendThread.h index a96a30d617..85c7c18b19 100644 --- a/assignment-client/src/octree/OctreeSendThread.h +++ b/assignment-client/src/octree/OctreeSendThread.h @@ -13,14 +13,11 @@ #include #include #include - - -class OctreeServer; -class OctreeQueryNode; - +#include #include "OctreeQueryNode.h" -#include "OctreeServer.h" + +class OctreeServer; /// Threaded processor for sending voxel packets to a single client class OctreeSendThread : public GenericThread { From a9d153054fde6b0def1240f16dbde6caa59e644c Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 15:28:13 -0700 Subject: [PATCH 046/595] remove _process mutex since it's no longer needed --- assignment-client/src/octree/OctreeSendThread.cpp | 13 ------------- assignment-client/src/octree/OctreeSendThread.h | 1 - 2 files changed, 14 deletions(-) diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index 9c0ddbb779..b2bb2a8c16 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -26,7 +26,6 @@ OctreeSendThread::OctreeSendThread(const SharedAssignmentPointer& myAssignment, _nodeUUID(node->getUUID()), _packetData(), _nodeMissingCount(0), - _processLock(), _isShuttingDown(false) { qDebug() << qPrintable(_myServer->getMyServerName()) << "server [" << _myServer << "]: client connected " @@ -61,9 +60,6 @@ OctreeSendThread::~OctreeSendThread() { void OctreeSendThread::setIsShuttingDown() { _isShuttingDown = true; OctreeServer::stopTrackingThread(this); - - // this will cause us to wait till the process loop is complete, we do this after we change _isShuttingDown - QMutexLocker locker(&_processLock); } @@ -79,13 +75,6 @@ bool OctreeSendThread::process() { OctreeServer::didProcess(this); - float lockWaitElapsedUsec = OctreeServer::SKIP_TIME; - quint64 lockWaitStart = usecTimestampNow(); - _processLock.lock(); - quint64 lockWaitEnd = usecTimestampNow(); - lockWaitElapsedUsec = (float)(lockWaitEnd - lockWaitStart); - OctreeServer::trackProcessWaitTime(lockWaitElapsedUsec); - quint64 start = usecTimestampNow(); // don't do any send processing until the initial load of the octree is complete... @@ -102,8 +91,6 @@ bool OctreeSendThread::process() { } } - _processLock.unlock(); - if (_isShuttingDown) { return false; // exit early if we're shutting down } diff --git a/assignment-client/src/octree/OctreeSendThread.h b/assignment-client/src/octree/OctreeSendThread.h index 85c7c18b19..971e27668c 100644 --- a/assignment-client/src/octree/OctreeSendThread.h +++ b/assignment-client/src/octree/OctreeSendThread.h @@ -51,7 +51,6 @@ private: OctreePacketData _packetData; int _nodeMissingCount; - QMutex _processLock; // don't allow us to have our nodeData, or our thread to be deleted while we're processing bool _isShuttingDown; }; From 62da4d622df716806d7a950676b05bfe12dc6448 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 31 Mar 2014 15:36:32 -0700 Subject: [PATCH 047/595] don't require an MD5 hash in non-verified packets --- domain-server/src/DomainServer.cpp | 4 ++-- libraries/shared/src/NodeList.cpp | 19 +++++++++-------- libraries/shared/src/NodeList.h | 1 + libraries/shared/src/PacketHeaders.cpp | 29 ++++++++++++++++---------- libraries/shared/src/PacketHeaders.h | 19 +++++++++++------ 5 files changed, 44 insertions(+), 28 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 7584b00c8d..a9bb6c4cfc 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -551,8 +551,8 @@ void DomainServer::readAvailableDatagrams() { unsigned short dtlsPort = nodeList->getDTLSSocket().localPort(); dtlsRequiredPacket.replace(numBytesDTLSHeader, sizeof(dtlsPort), reinterpret_cast(&dtlsPort)); } - - nodeList->getNodeSocket().writeDatagram(dtlsRequiredPacket, senderSockAddr.getAddress(), senderSockAddr.getPort()); + + nodeList->writeUnverifiedDatagram(dtlsRequiredPacket, senderSockAddr); } } } diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index bb4ff84865..167354542c 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -146,12 +146,6 @@ bool NodeList::packetVersionAndHashMatch(const QByteArray& packet) { return false; } - const QSet NON_VERIFIED_PACKETS = QSet() - << PacketTypeDomainServerRequireDTLS << PacketTypeDomainList << PacketTypeDomainListRequest - << PacketTypeStunResponse << PacketTypeDataServerConfirm - << PacketTypeDataServerGet << PacketTypeDataServerPut << PacketTypeDataServerSend - << PacketTypeCreateAssignment << PacketTypeRequestAssignment; - if (!NON_VERIFIED_PACKETS.contains(checkType)) { // figure out which node this is from SharedNodePointer sendingNode = sendingNodeForPacket(packet); @@ -178,14 +172,17 @@ qint64 NodeList::writeDatagram(const QByteArray& datagram, const HifiSockAddr& d const QUuid& connectionSecret) { QByteArray datagramCopy = datagram; - // setup the MD5 hash for source verification in the header - replaceHashInPacketGivenConnectionUUID(datagramCopy, connectionSecret); + if (!connectionSecret.isNull()) { + // setup the MD5 hash for source verification in the header + replaceHashInPacketGivenConnectionUUID(datagramCopy, connectionSecret); + } // stat collection for packets ++_numCollectedPackets; _numCollectedBytes += datagram.size(); - qint64 bytesWritten = _nodeSocket.writeDatagram(datagramCopy, destinationSockAddr.getAddress(), destinationSockAddr.getPort()); + qint64 bytesWritten = _nodeSocket.writeDatagram(datagramCopy, + destinationSockAddr.getAddress(), destinationSockAddr.getPort()); if (bytesWritten < 0) { qDebug() << "ERROR in writeDatagram:" << _nodeSocket.error() << "-" << _nodeSocket.errorString(); @@ -216,6 +213,10 @@ qint64 NodeList::writeDatagram(const QByteArray& datagram, const SharedNodePoint return 0; } +qint64 NodeList::writeUnverifiedDatagram(const QByteArray& datagram, const HifiSockAddr& destinationSockAddr) { + return writeDatagram(datagram, destinationSockAddr, QUuid()); +} + qint64 NodeList::writeDatagram(const char* data, qint64 size, const SharedNodePointer& destinationNode, const HifiSockAddr& overridenSockAddr) { return writeDatagram(QByteArray(data, size), destinationNode, overridenSockAddr); diff --git a/libraries/shared/src/NodeList.h b/libraries/shared/src/NodeList.h index 4f9b839779..613b431929 100644 --- a/libraries/shared/src/NodeList.h +++ b/libraries/shared/src/NodeList.h @@ -78,6 +78,7 @@ public: qint64 writeDatagram(const QByteArray& datagram, const SharedNodePointer& destinationNode, const HifiSockAddr& overridenSockAddr = HifiSockAddr()); + qint64 writeUnverifiedDatagram(const QByteArray& datagram, const HifiSockAddr& destinationSockAddr); qint64 writeDatagram(const char* data, qint64 size, const SharedNodePointer& destinationNode, const HifiSockAddr& overridenSockAddr = HifiSockAddr()); qint64 sendStatsToDomainServer(const QJsonObject& statsObject); diff --git a/libraries/shared/src/PacketHeaders.cpp b/libraries/shared/src/PacketHeaders.cpp index 0035f053fb..da8de0ddb0 100644 --- a/libraries/shared/src/PacketHeaders.cpp +++ b/libraries/shared/src/PacketHeaders.cpp @@ -56,11 +56,6 @@ PacketVersion versionForPacketType(PacketType type) { case PacketTypeCreateAssignment: case PacketTypeRequestAssignment: return 1; - case PacketTypeDataServerGet: - case PacketTypeDataServerPut: - case PacketTypeDataServerConfirm: - case PacketTypeDataServerSend: - return 1; case PacketTypeVoxelSet: case PacketTypeVoxelSetDestructive: return 1; @@ -95,9 +90,11 @@ int populatePacketHeader(char* packet, PacketType type, const QUuid& connectionU memcpy(position, rfcUUID.constData(), NUM_BYTES_RFC4122_UUID); position += NUM_BYTES_RFC4122_UUID; - // pack 16 bytes of zeros where the md5 hash will be placed one data is packed - memset(position, 0, NUM_BYTES_MD5_HASH); - position += NUM_BYTES_MD5_HASH; + if (!NON_VERIFIED_PACKETS.contains(type)) { + // pack 16 bytes of zeros where the md5 hash will be placed one data is packed + memset(position, 0, NUM_BYTES_MD5_HASH); + position += NUM_BYTES_MD5_HASH; + } // return the number of bytes written for pointer pushing return position - packet; @@ -105,16 +102,26 @@ int populatePacketHeader(char* packet, PacketType type, const QUuid& connectionU int numBytesForPacketHeader(const QByteArray& packet) { // returns the number of bytes used for the type, version, and UUID - return numBytesArithmeticCodingFromBuffer(packet.data()) + NUM_STATIC_HEADER_BYTES; + return numBytesArithmeticCodingFromBuffer(packet.data()) + + numHashBytesInPacketHeaderGivenPacketType(packetTypeForPacket(packet)) + + NUM_STATIC_HEADER_BYTES; } int numBytesForPacketHeader(const char* packet) { // returns the number of bytes used for the type, version, and UUID - return numBytesArithmeticCodingFromBuffer(packet) + NUM_STATIC_HEADER_BYTES; + return numBytesArithmeticCodingFromBuffer(packet) + + numHashBytesInPacketHeaderGivenPacketType(packetTypeForPacket(packet)) + + NUM_STATIC_HEADER_BYTES; } int numBytesForPacketHeaderGivenPacketType(PacketType type) { - return (int) ceilf((float)type / 255) + NUM_STATIC_HEADER_BYTES; + return (int) ceilf((float)type / 255) + + numHashBytesInPacketHeaderGivenPacketType(type) + + NUM_STATIC_HEADER_BYTES; +} + +int numHashBytesInPacketHeaderGivenPacketType(PacketType type) { + return (NON_VERIFIED_PACKETS.contains(type) ? 0 : NUM_BYTES_MD5_HASH); } QUuid uuidFromPacketHeader(const QByteArray& packet) { diff --git a/libraries/shared/src/PacketHeaders.h b/libraries/shared/src/PacketHeaders.h index 483fdb8a4d..0250fb038a 100644 --- a/libraries/shared/src/PacketHeaders.h +++ b/libraries/shared/src/PacketHeaders.h @@ -13,6 +13,7 @@ #define hifi_PacketHeaders_h #include +#include #include #include "UUID.h" @@ -37,9 +38,9 @@ enum PacketType { PacketTypeDomainListRequest, PacketTypeRequestAssignment, PacketTypeCreateAssignment, - PacketTypeDataServerPut, - PacketTypeDataServerGet, - PacketTypeDataServerSend, + PacketTypeDataServerPut, // reusable + PacketTypeDataServerGet, // reusable + PacketTypeDataServerSend, // reusable PacketTypeDataServerConfirm, PacketTypeVoxelQuery, PacketTypeVoxelData, @@ -57,16 +58,20 @@ enum PacketType { PacketTypeMetavoxelData, PacketTypeAvatarIdentity, PacketTypeAvatarBillboard, - PacketTypeDomainConnectRequest, // RE-USABLE + PacketTypeDomainConnectRequest, // reusable PacketTypeDomainServerRequireDTLS, PacketTypeNodeJsonStats, }; typedef char PacketVersion; +const QSet NON_VERIFIED_PACKETS = QSet() + << PacketTypeDomainServerRequireDTLS << PacketTypeDomainList << PacketTypeDomainListRequest + << PacketTypeCreateAssignment << PacketTypeRequestAssignment << PacketTypeStunResponse; + const int NUM_BYTES_MD5_HASH = 16; -const int NUM_STATIC_HEADER_BYTES = sizeof(PacketVersion) + NUM_BYTES_RFC4122_UUID + NUM_BYTES_MD5_HASH; -const int MAX_PACKET_HEADER_BYTES = sizeof(PacketType) + NUM_STATIC_HEADER_BYTES; +const int NUM_STATIC_HEADER_BYTES = sizeof(PacketVersion) + NUM_BYTES_RFC4122_UUID; +const int MAX_PACKET_HEADER_BYTES = sizeof(PacketType) + NUM_BYTES_MD5_HASH + NUM_STATIC_HEADER_BYTES; PacketVersion versionForPacketType(PacketType type); @@ -76,6 +81,8 @@ QByteArray byteArrayWithPopulatedHeader(PacketType type, const QUuid& connection int populatePacketHeader(QByteArray& packet, PacketType type, const QUuid& connectionUUID = nullUUID); int populatePacketHeader(char* packet, PacketType type, const QUuid& connectionUUID = nullUUID); +int numHashBytesInPacketHeaderGivenPacketType(PacketType type); + int numBytesForPacketHeader(const QByteArray& packet); int numBytesForPacketHeader(const char* packet); int numBytesForPacketHeaderGivenPacketType(PacketType type); From 1eb15b0d12c230ea9de3dbade8284ece9cc43845 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 15:37:53 -0700 Subject: [PATCH 048/595] cleanup --- assignment-client/src/octree/OctreeQueryNode.cpp | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/assignment-client/src/octree/OctreeQueryNode.cpp b/assignment-client/src/octree/OctreeQueryNode.cpp index 57de87c45d..56fdbb997b 100644 --- a/assignment-client/src/octree/OctreeQueryNode.cpp +++ b/assignment-client/src/octree/OctreeQueryNode.cpp @@ -44,7 +44,7 @@ OctreeQueryNode::OctreeQueryNode() : OctreeQueryNode::~OctreeQueryNode() { _isShuttingDown = true; - const bool extraDebugging = true; + const bool extraDebugging = false; if (extraDebugging) { qDebug() << "OctreeQueryNode::~OctreeQueryNode()"; } @@ -77,18 +77,8 @@ void OctreeQueryNode::deleteLater() { void OctreeQueryNode::nodeKilled() { _isShuttingDown = true; - const bool extraDebugging = true; - if (extraDebugging) { - qDebug() << "OctreeQueryNode::nodeKilled()"; - } if (_octreeSendThread) { - if (extraDebugging) { - qDebug() << "OctreeQueryNode::nodeKilled()... calling _octreeSendThread->terminate()"; - } _octreeSendThread->terminate(); - if (extraDebugging) { - qDebug() << "OctreeQueryNode::nodeKilled()... calling delete _octreeSendThread"; - } delete _octreeSendThread; _octreeSendThread = NULL; } From b3734d870b31803281c79be2570451d91e9549a5 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 15:39:12 -0700 Subject: [PATCH 049/595] cleanup --- assignment-client/src/octree/OctreeSendThread.cpp | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index b2bb2a8c16..8bf70c3853 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -40,21 +40,8 @@ OctreeSendThread::~OctreeSendThread() { qDebug() << qPrintable(serverName) << "server [" << _myServer << "]: client disconnected " "- ending sending thread [" << this << "]"; OctreeServer::clientDisconnected(); - - qDebug() << qPrintable(serverName) << "server [" << _myServer << "]: " - "- OctreeSendThread::~OctreeSendThread() this=[" << this << "]" - "line: " << __LINE__; - _node.clear(); - - qDebug() << qPrintable(serverName) << "server [" << _myServer << "]: " - "- OctreeSendThread::~OctreeSendThread() this=[" << this << "]" - "line: " << __LINE__; _myAssignment.clear(); - - qDebug() << qPrintable(serverName) << "server [" << _myServer << "]: " - "- OctreeSendThread::~OctreeSendThread() this=[" << this << "]" - "line: " << __LINE__; } void OctreeSendThread::setIsShuttingDown() { From 5c37a79378c2023c54d400711a6c95fa259d4a6d Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 15:42:16 -0700 Subject: [PATCH 050/595] cleanup of debuggin --- assignment-client/src/octree/OctreeServer.cpp | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 6499a2f4a4..a79bba44a4 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -250,40 +250,26 @@ OctreeServer::~OctreeServer() { } delete[] _parsedArgV; } - qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; if (_jurisdictionSender) { _jurisdictionSender->terminate(); _jurisdictionSender->deleteLater(); } - qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; - if (_octreeInboundPacketProcessor) { _octreeInboundPacketProcessor->terminate(); _octreeInboundPacketProcessor->deleteLater(); } - qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; - if (_persistThread) { - qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; _persistThread->terminate(); - qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; _persistThread->deleteLater(); - qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; } - qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; - delete _jurisdiction; _jurisdiction = NULL; - qDebug() << qPrintable(_safeServerName) << "server DONE shutting down... [" << this << "]"; - - qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; - _instance = NULL; // we are gone - qDebug() << qPrintable(_safeServerName) << "server shutting down... [" << this << "] OctreeServer::~OctreeServer() line:" << __LINE__; + qDebug() << qPrintable(_safeServerName) << "server DONE shutting down... [" << this << "]"; } void OctreeServer::initHTTPManager(int port) { From 81fc0bea4dc35da6adaf93b53dafd3019afb9f17 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 15:50:40 -0700 Subject: [PATCH 051/595] revert small tweaks --- libraries/octree/src/OctreePersistThread.cpp | 4 ---- libraries/octree/src/OctreePersistThread.h | 1 - 2 files changed, 5 deletions(-) diff --git a/libraries/octree/src/OctreePersistThread.cpp b/libraries/octree/src/OctreePersistThread.cpp index 6c0c0d9bfe..29715f9d90 100644 --- a/libraries/octree/src/OctreePersistThread.cpp +++ b/libraries/octree/src/OctreePersistThread.cpp @@ -23,10 +23,6 @@ OctreePersistThread::OctreePersistThread(Octree* tree, const QString& filename, { } -OctreePersistThread::~OctreePersistThread() { - qDebug() << "OctreePersistThread::~OctreePersistThread()..."; -} - bool OctreePersistThread::process() { if (!_initialLoadComplete) { diff --git a/libraries/octree/src/OctreePersistThread.h b/libraries/octree/src/OctreePersistThread.h index 8e70733192..ce6190b0e6 100644 --- a/libraries/octree/src/OctreePersistThread.h +++ b/libraries/octree/src/OctreePersistThread.h @@ -22,7 +22,6 @@ public: static const int DEFAULT_PERSIST_INTERVAL = 1000 * 30; // every 30 seconds OctreePersistThread(Octree* tree, const QString& filename, int persistInterval = DEFAULT_PERSIST_INTERVAL); - ~OctreePersistThread(); bool isInitialLoadComplete() const { return _initialLoadComplete; } quint64 getLoadElapsedTime() const { return _loadTimeUSecs; } From 7a683b177da5eb88a1725a9091f08536352c32ad Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 16:43:25 -0700 Subject: [PATCH 052/595] added some debugging, and reordered some shutdown logic --- .../src/octree/OctreeQueryNode.cpp | 17 +++++++++++++++-- .../src/octree/OctreeSendThread.cpp | 17 ++++++++++++++++- assignment-client/src/octree/OctreeServer.cpp | 1 + 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/assignment-client/src/octree/OctreeQueryNode.cpp b/assignment-client/src/octree/OctreeQueryNode.cpp index 56fdbb997b..3b73617845 100644 --- a/assignment-client/src/octree/OctreeQueryNode.cpp +++ b/assignment-client/src/octree/OctreeQueryNode.cpp @@ -44,7 +44,7 @@ OctreeQueryNode::OctreeQueryNode() : OctreeQueryNode::~OctreeQueryNode() { _isShuttingDown = true; - const bool extraDebugging = false; + const bool extraDebugging = true; if (extraDebugging) { qDebug() << "OctreeQueryNode::~OctreeQueryNode()"; } @@ -76,12 +76,25 @@ void OctreeQueryNode::deleteLater() { } void OctreeQueryNode::nodeKilled() { + qDebug() << "OctreeQueryNode::nodeKilled()... "; _isShuttingDown = true; if (_octreeSendThread) { + qDebug() << "OctreeQueryNode::nodeKilled()... calling _octreeSendThread->terminate()"; _octreeSendThread->terminate(); - delete _octreeSendThread; + qDebug() << "OctreeQueryNode::nodeKilled()... AFTER _octreeSendThread->terminate()"; + + OctreeSendThread* sendThread = _octreeSendThread; + + qDebug() << "OctreeQueryNode::nodeKilled()... calling _octreeSendThread = NULL"; _octreeSendThread = NULL; + qDebug() << "OctreeQueryNode::nodeKilled()... AFTER _octreeSendThread = NULL"; + + qDebug() << "OctreeQueryNode::nodeKilled()... calling delete sendThread"; + delete sendThread; + qDebug() << "OctreeQueryNode::nodeKilled()... AFTER delete sendThread"; + } + qDebug() << "OctreeQueryNode::nodeKilled()... DONE"; } diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index 8bf70c3853..b98d17c033 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -35,13 +35,28 @@ OctreeSendThread::OctreeSendThread(const SharedAssignmentPointer& myAssignment, } OctreeSendThread::~OctreeSendThread() { - QString serverName(_myServer->getMyServerName()); + qDebug() << "OctreeSendThread::~OctreeSendThread()... START"; + QString serverName("Octree"); + if (_myServer) { + serverName = _myServer->getMyServerName(); + } qDebug() << qPrintable(serverName) << "server [" << _myServer << "]: client disconnected " "- ending sending thread [" << this << "]"; + + qDebug() << "OctreeSendThread::~OctreeSendThread()... BEFORE OctreeServer::clientDisconnected();"; OctreeServer::clientDisconnected(); + qDebug() << "OctreeSendThread::~OctreeSendThread()... AFTER OctreeServer::clientDisconnected();"; + + qDebug() << "OctreeSendThread::~OctreeSendThread()... BEFORE _node.clear();"; _node.clear(); + qDebug() << "OctreeSendThread::~OctreeSendThread()... AFTER _node.clear();"; + + qDebug() << "OctreeSendThread::~OctreeSendThread()... BEFORE _myAssignment.clear();"; _myAssignment.clear(); + qDebug() << "OctreeSendThread::~OctreeSendThread()... BEFORE _myAssignment.clear();"; + + qDebug() << "OctreeSendThread::~OctreeSendThread()... DONE"; } void OctreeSendThread::setIsShuttingDown() { diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index a79bba44a4..977c0c25f3 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -1052,6 +1052,7 @@ void OctreeServer::nodeKilled(SharedNodePointer node) { if (nodeData) { qDebug() << qPrintable(_safeServerName) << "server calling nodeData->nodeKilled() for node:" << *node; nodeData->nodeKilled(); // tell our node data and sending threads that we'd like to shut down + qDebug() << qPrintable(_safeServerName) << "server AFTER nodeData->nodeKilled() for node:" << *node; } else { qDebug() << qPrintable(_safeServerName) << "server node missing linked data node:" << *node; } From dc302e7126cd6e33abc68e444b71144a802b1beb Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 16:51:00 -0700 Subject: [PATCH 053/595] tweak shutdown --- assignment-client/src/octree/OctreeQueryNode.cpp | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/assignment-client/src/octree/OctreeQueryNode.cpp b/assignment-client/src/octree/OctreeQueryNode.cpp index 3b73617845..d2c1cf281e 100644 --- a/assignment-client/src/octree/OctreeQueryNode.cpp +++ b/assignment-client/src/octree/OctreeQueryNode.cpp @@ -48,6 +48,8 @@ OctreeQueryNode::~OctreeQueryNode() { if (extraDebugging) { qDebug() << "OctreeQueryNode::~OctreeQueryNode()"; } + + /* if (_octreeSendThread) { if (extraDebugging) { qDebug() << "OctreeQueryNode::~OctreeQueryNode()... calling _octreeSendThread->terminate()"; @@ -58,6 +60,7 @@ OctreeQueryNode::~OctreeQueryNode() { } delete _octreeSendThread; } + */ delete[] _octreePacket; delete[] _lastOctreePacket; @@ -79,16 +82,20 @@ void OctreeQueryNode::nodeKilled() { qDebug() << "OctreeQueryNode::nodeKilled()... "; _isShuttingDown = true; if (_octreeSendThread) { - qDebug() << "OctreeQueryNode::nodeKilled()... calling _octreeSendThread->terminate()"; - _octreeSendThread->terminate(); - qDebug() << "OctreeQueryNode::nodeKilled()... AFTER _octreeSendThread->terminate()"; - OctreeSendThread* sendThread = _octreeSendThread; qDebug() << "OctreeQueryNode::nodeKilled()... calling _octreeSendThread = NULL"; _octreeSendThread = NULL; qDebug() << "OctreeQueryNode::nodeKilled()... AFTER _octreeSendThread = NULL"; + qDebug() << "OctreeQueryNode::nodeKilled()... calling _octreeSendThread->setIsShuttingDown()"; + sendThread->setIsShuttingDown(); + qDebug() << "OctreeQueryNode::nodeKilled()... AFTER _octreeSendThread->setIsShuttingDown()"; + + qDebug() << "OctreeQueryNode::nodeKilled()... calling _octreeSendThread->terminate()"; + sendThread->terminate(); + qDebug() << "OctreeQueryNode::nodeKilled()... AFTER _octreeSendThread->terminate()"; + qDebug() << "OctreeQueryNode::nodeKilled()... calling delete sendThread"; delete sendThread; qDebug() << "OctreeQueryNode::nodeKilled()... AFTER delete sendThread"; From ef68f164c9a7aa1bfd9fe66d6045df196c883dcc Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 17:05:31 -0700 Subject: [PATCH 054/595] tweak shutdown --- assignment-client/src/octree/OctreeQueryNode.cpp | 5 +++++ assignment-client/src/octree/OctreeSendThread.cpp | 11 ++++++++++- assignment-client/src/octree/OctreeServer.cpp | 4 ++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/assignment-client/src/octree/OctreeQueryNode.cpp b/assignment-client/src/octree/OctreeQueryNode.cpp index d2c1cf281e..fe2e271a09 100644 --- a/assignment-client/src/octree/OctreeQueryNode.cpp +++ b/assignment-client/src/octree/OctreeQueryNode.cpp @@ -107,8 +107,13 @@ void OctreeQueryNode::nodeKilled() { void OctreeQueryNode::initializeOctreeSendThread(const SharedAssignmentPointer& myAssignment, const SharedNodePointer& node) { // Create octree sending thread... + qDebug() << "OctreeQueryNode::initializeOctreeSendThread()... BEFORE new OctreeSendThread(myAssignment, node);"; _octreeSendThread = new OctreeSendThread(myAssignment, node); + qDebug() << "OctreeQueryNode::initializeOctreeSendThread()... AFTER new OctreeSendThread(myAssignment, node);"; + + qDebug() << "OctreeQueryNode::initializeOctreeSendThread()... BEFORE _octreeSendThread->initialize(true)"; _octreeSendThread->initialize(true); + qDebug() << "OctreeQueryNode::initializeOctreeSendThread()... AFTER _octreeSendThread->initialize(true)"; } bool OctreeQueryNode::packetIsDuplicate() const { diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index b98d17c033..20a7260737 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -28,10 +28,19 @@ OctreeSendThread::OctreeSendThread(const SharedAssignmentPointer& myAssignment, _nodeMissingCount(0), _isShuttingDown(false) { - qDebug() << qPrintable(_myServer->getMyServerName()) << "server [" << _myServer << "]: client connected " + qDebug() << "OctreeSendThread::OctreeSendThread()... START"; + + QString serverName("Octree"); + if (_myServer) { + serverName = _myServer->getMyServerName(); + } + qDebug() << qPrintable(serverName) << "server [" << _myServer << "]: client connected " "- starting sending thread [" << this << "]"; + qDebug() << "OctreeSendThread::OctreeSendThread()... before OctreeServer::clientConnected()"; OctreeServer::clientConnected(); + qDebug() << "OctreeSendThread::OctreeSendThread()... AFTER OctreeServer::clientConnected()"; + qDebug() << "OctreeSendThread::OctreeSendThread()... DONE"; } OctreeSendThread::~OctreeSendThread() { diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 977c0c25f3..e791b542fc 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -842,8 +842,12 @@ void OctreeServer::readPendingDatagrams() { if (debug) { qDebug() << "calling initializeOctreeSendThread()... node:" << *matchingNode; } + + + qDebug() << "OctreeServer::readPendingDatagrams()... BEFORE nodeData->initializeOctreeSendThread()"; SharedAssignmentPointer sharedAssignment = AssignmentClient::getCurrentAssignment(); nodeData->initializeOctreeSendThread(sharedAssignment, matchingNode); + qDebug() << "OctreeServer::readPendingDatagrams()... AFTER nodeData->initializeOctreeSendThread()"; } } } else if (packetType == PacketTypeJurisdictionRequest) { From 4bf7faba7b64f45cc65255796bee828ffd00c893 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 17:55:40 -0700 Subject: [PATCH 055/595] workaround for assert failures when bad view frustum input --- libraries/octree/src/ViewFrustum.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/libraries/octree/src/ViewFrustum.cpp b/libraries/octree/src/ViewFrustum.cpp index fa6873b093..dbb6f955f2 100644 --- a/libraries/octree/src/ViewFrustum.cpp +++ b/libraries/octree/src/ViewFrustum.cpp @@ -129,9 +129,11 @@ void ViewFrustum::calculate() { // Also calculate our projection matrix in case people want to project points... // Projection matrix : Field of View, ratio, display range : near to far - glm::mat4 projection = glm::perspective(_fieldOfView, _aspectRatio, _nearClip, _farClip); - glm::vec3 lookAt = _position + _direction; - glm::mat4 view = glm::lookAt(_position, lookAt, _up); + const float CLIP_NUDGE = 1.0f; + float farClip = (_farClip != _nearClip) ? _farClip : _nearClip + CLIP_NUDGE; // don't allow near and far to be equal + glm::mat4 projection = glm::perspective(_fieldOfView, _aspectRatio, _nearClip, farClip); + glm::vec3 lookAt = _position + _direction; + glm::mat4 view = glm::lookAt(_position, lookAt, _up); // Our ModelViewProjection : multiplication of our 3 matrices (note: model is identity, so we can drop it) _ourModelViewProjectionMatrix = projection * view; // Remember, matrix multiplication is the other way around From 9d60be97736f5c9e1b594bb6768cbe9cd74e242e Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 17:57:48 -0700 Subject: [PATCH 056/595] cleanup some debugging --- .../src/octree/OctreeQueryNode.cpp | 37 ++++++------------- .../src/octree/OctreeSendThread.cpp | 24 ++++++------ 2 files changed, 24 insertions(+), 37 deletions(-) diff --git a/assignment-client/src/octree/OctreeQueryNode.cpp b/assignment-client/src/octree/OctreeQueryNode.cpp index fe2e271a09..3291fb49ba 100644 --- a/assignment-client/src/octree/OctreeQueryNode.cpp +++ b/assignment-client/src/octree/OctreeQueryNode.cpp @@ -49,19 +49,6 @@ OctreeQueryNode::~OctreeQueryNode() { qDebug() << "OctreeQueryNode::~OctreeQueryNode()"; } - /* - if (_octreeSendThread) { - if (extraDebugging) { - qDebug() << "OctreeQueryNode::~OctreeQueryNode()... calling _octreeSendThread->terminate()"; - } - _octreeSendThread->terminate(); - if (extraDebugging) { - qDebug() << "OctreeQueryNode::~OctreeQueryNode()... calling delete _octreeSendThread"; - } - delete _octreeSendThread; - } - */ - delete[] _octreePacket; delete[] _lastOctreePacket; if (extraDebugging) { @@ -84,21 +71,21 @@ void OctreeQueryNode::nodeKilled() { if (_octreeSendThread) { OctreeSendThread* sendThread = _octreeSendThread; - qDebug() << "OctreeQueryNode::nodeKilled()... calling _octreeSendThread = NULL"; + //qDebug() << "OctreeQueryNode::nodeKilled()... calling _octreeSendThread = NULL"; _octreeSendThread = NULL; - qDebug() << "OctreeQueryNode::nodeKilled()... AFTER _octreeSendThread = NULL"; + //qDebug() << "OctreeQueryNode::nodeKilled()... AFTER _octreeSendThread = NULL"; - qDebug() << "OctreeQueryNode::nodeKilled()... calling _octreeSendThread->setIsShuttingDown()"; + //qDebug() << "OctreeQueryNode::nodeKilled()... calling _octreeSendThread->setIsShuttingDown()"; sendThread->setIsShuttingDown(); - qDebug() << "OctreeQueryNode::nodeKilled()... AFTER _octreeSendThread->setIsShuttingDown()"; + //qDebug() << "OctreeQueryNode::nodeKilled()... AFTER _octreeSendThread->setIsShuttingDown()"; - qDebug() << "OctreeQueryNode::nodeKilled()... calling _octreeSendThread->terminate()"; + //qDebug() << "OctreeQueryNode::nodeKilled()... calling _octreeSendThread->terminate()"; sendThread->terminate(); - qDebug() << "OctreeQueryNode::nodeKilled()... AFTER _octreeSendThread->terminate()"; + //qDebug() << "OctreeQueryNode::nodeKilled()... AFTER _octreeSendThread->terminate()"; - qDebug() << "OctreeQueryNode::nodeKilled()... calling delete sendThread"; + //qDebug() << "OctreeQueryNode::nodeKilled()... calling delete sendThread"; delete sendThread; - qDebug() << "OctreeQueryNode::nodeKilled()... AFTER delete sendThread"; + //qDebug() << "OctreeQueryNode::nodeKilled()... AFTER delete sendThread"; } qDebug() << "OctreeQueryNode::nodeKilled()... DONE"; @@ -107,13 +94,13 @@ void OctreeQueryNode::nodeKilled() { void OctreeQueryNode::initializeOctreeSendThread(const SharedAssignmentPointer& myAssignment, const SharedNodePointer& node) { // Create octree sending thread... - qDebug() << "OctreeQueryNode::initializeOctreeSendThread()... BEFORE new OctreeSendThread(myAssignment, node);"; + //qDebug() << "OctreeQueryNode::initializeOctreeSendThread()... BEFORE new OctreeSendThread(myAssignment, node);"; _octreeSendThread = new OctreeSendThread(myAssignment, node); - qDebug() << "OctreeQueryNode::initializeOctreeSendThread()... AFTER new OctreeSendThread(myAssignment, node);"; + //qDebug() << "OctreeQueryNode::initializeOctreeSendThread()... AFTER new OctreeSendThread(myAssignment, node);"; - qDebug() << "OctreeQueryNode::initializeOctreeSendThread()... BEFORE _octreeSendThread->initialize(true)"; + //qDebug() << "OctreeQueryNode::initializeOctreeSendThread()... BEFORE _octreeSendThread->initialize(true)"; _octreeSendThread->initialize(true); - qDebug() << "OctreeQueryNode::initializeOctreeSendThread()... AFTER _octreeSendThread->initialize(true)"; + //qDebug() << "OctreeQueryNode::initializeOctreeSendThread()... AFTER _octreeSendThread->initialize(true)"; } bool OctreeQueryNode::packetIsDuplicate() const { diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index 20a7260737..a748d766c3 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -28,7 +28,7 @@ OctreeSendThread::OctreeSendThread(const SharedAssignmentPointer& myAssignment, _nodeMissingCount(0), _isShuttingDown(false) { - qDebug() << "OctreeSendThread::OctreeSendThread()... START"; + //qDebug() << "OctreeSendThread::OctreeSendThread()... START"; QString serverName("Octree"); if (_myServer) { @@ -37,14 +37,14 @@ OctreeSendThread::OctreeSendThread(const SharedAssignmentPointer& myAssignment, qDebug() << qPrintable(serverName) << "server [" << _myServer << "]: client connected " "- starting sending thread [" << this << "]"; - qDebug() << "OctreeSendThread::OctreeSendThread()... before OctreeServer::clientConnected()"; + //qDebug() << "OctreeSendThread::OctreeSendThread()... before OctreeServer::clientConnected()"; OctreeServer::clientConnected(); - qDebug() << "OctreeSendThread::OctreeSendThread()... AFTER OctreeServer::clientConnected()"; - qDebug() << "OctreeSendThread::OctreeSendThread()... DONE"; + //qDebug() << "OctreeSendThread::OctreeSendThread()... AFTER OctreeServer::clientConnected()"; + //qDebug() << "OctreeSendThread::OctreeSendThread()... DONE"; } OctreeSendThread::~OctreeSendThread() { - qDebug() << "OctreeSendThread::~OctreeSendThread()... START"; + //qDebug() << "OctreeSendThread::~OctreeSendThread()... START"; QString serverName("Octree"); if (_myServer) { serverName = _myServer->getMyServerName(); @@ -53,19 +53,19 @@ OctreeSendThread::~OctreeSendThread() { qDebug() << qPrintable(serverName) << "server [" << _myServer << "]: client disconnected " "- ending sending thread [" << this << "]"; - qDebug() << "OctreeSendThread::~OctreeSendThread()... BEFORE OctreeServer::clientDisconnected();"; + //qDebug() << "OctreeSendThread::~OctreeSendThread()... BEFORE OctreeServer::clientDisconnected();"; OctreeServer::clientDisconnected(); - qDebug() << "OctreeSendThread::~OctreeSendThread()... AFTER OctreeServer::clientDisconnected();"; + //qDebug() << "OctreeSendThread::~OctreeSendThread()... AFTER OctreeServer::clientDisconnected();"; - qDebug() << "OctreeSendThread::~OctreeSendThread()... BEFORE _node.clear();"; + //qDebug() << "OctreeSendThread::~OctreeSendThread()... BEFORE _node.clear();"; _node.clear(); - qDebug() << "OctreeSendThread::~OctreeSendThread()... AFTER _node.clear();"; + //qDebug() << "OctreeSendThread::~OctreeSendThread()... AFTER _node.clear();"; - qDebug() << "OctreeSendThread::~OctreeSendThread()... BEFORE _myAssignment.clear();"; + //qDebug() << "OctreeSendThread::~OctreeSendThread()... BEFORE _myAssignment.clear();"; _myAssignment.clear(); - qDebug() << "OctreeSendThread::~OctreeSendThread()... BEFORE _myAssignment.clear();"; + //qDebug() << "OctreeSendThread::~OctreeSendThread()... BEFORE _myAssignment.clear();"; - qDebug() << "OctreeSendThread::~OctreeSendThread()... DONE"; + //qDebug() << "OctreeSendThread::~OctreeSendThread()... DONE"; } void OctreeSendThread::setIsShuttingDown() { From b5c538b05130dff271538c9107363ceba0c5ee24 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 18:22:06 -0700 Subject: [PATCH 057/595] added some debugging --- assignment-client/src/octree/OctreeServer.cpp | 6 ++++++ libraries/shared/src/ThreadedAssignment.cpp | 4 ++++ 2 files changed, 10 insertions(+) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index e791b542fc..11d0e0ca37 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -1051,6 +1051,8 @@ void OctreeServer::nodeAdded(SharedNodePointer node) { } void OctreeServer::nodeKilled(SharedNodePointer node) { + quint64 start = usecTimestampNow(); + qDebug() << qPrintable(_safeServerName) << "server killed node:" << *node; OctreeQueryNode* nodeData = static_cast(node->getLinkedData()); if (nodeData) { @@ -1060,6 +1062,10 @@ void OctreeServer::nodeKilled(SharedNodePointer node) { } else { qDebug() << qPrintable(_safeServerName) << "server node missing linked data node:" << *node; } + + quint64 end = usecTimestampNow(); + quint64 usecsElapsed = (end - start); + qDebug() << qPrintable(_safeServerName) << "server killed node:" << *node << " took: " << usecsElapsed << " usecs"; } void OctreeServer::aboutToFinish() { diff --git a/libraries/shared/src/ThreadedAssignment.cpp b/libraries/shared/src/ThreadedAssignment.cpp index fdf2d91c36..eed5aa46f6 100644 --- a/libraries/shared/src/ThreadedAssignment.cpp +++ b/libraries/shared/src/ThreadedAssignment.cpp @@ -74,6 +74,10 @@ void ThreadedAssignment::sendStatsPacket() { } void ThreadedAssignment::checkInWithDomainServerOrExit() { + qDebug() << "ThreadedAssignment::checkInWithDomainServerOrExit()... " + "Num No Reply Domain Check Ins=" << NodeList::getInstance()->getNumNoReplyDomainCheckIns() + << "MAX_SILENT_DOMAIN_SERVER_CHECK_INS=" << MAX_SILENT_DOMAIN_SERVER_CHECK_INS; + if (NodeList::getInstance()->getNumNoReplyDomainCheckIns() == MAX_SILENT_DOMAIN_SERVER_CHECK_INS) { setFinished(true); } else { From 19b8f101d8994bd0f9b4a86a45fd0144ed9bc6eb Mon Sep 17 00:00:00 2001 From: James Brotchie Date: Tue, 1 Apr 2014 11:31:43 +1000 Subject: [PATCH 058/595] Improved hifi:// style URL scheme handling. First steps towards implementing #1463. - Moved url parsing code from Application::event to Menu::goTo(QString). - Handle destination component of URL as either a @username, #place, or x-xx,y-yy,z-zz style coordinate. - Added support for entering hifi:// style URL into @ invoked goto menu option. --- interface/interface_en.ts | 8 +++---- interface/src/Application.cpp | 27 ++++------------------ interface/src/Application.h | 1 + interface/src/Menu.cpp | 43 +++++++++++++++++++++++++++++++++-- interface/src/Menu.h | 1 + 5 files changed, 51 insertions(+), 29 deletions(-) diff --git a/interface/interface_en.ts b/interface/interface_en.ts index 7c5d1ecbcf..49906379c4 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -4,22 +4,22 @@ Application - + Export Voxels - + Sparse Voxel Octree Files (*.svo) - + Open Script - + JavaScript Files (*.js) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index d91e686844..883da9b7bc 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -112,8 +112,6 @@ const QString SKIP_FILENAME = QStandardPaths::writableLocation(QStandardPaths::D const int STATS_PELS_PER_LINE = 20; -const QString CUSTOM_URL_SCHEME = "hifi:"; - void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message) { if (message.size() > 0) { QString dateString = QDateTime::currentDateTime().toTimeSpec(Qt::LocalTime).toString(Qt::ISODate); @@ -676,30 +674,13 @@ void Application::controlledBroadcastToNodes(const QByteArray& packet, const Nod } bool Application::event(QEvent* event) { - + // handle custom URL if (event->type() == QEvent::FileOpen) { QFileOpenEvent* fileEvent = static_cast(event); - if (!fileEvent->url().isEmpty() && fileEvent->url().toLocalFile().startsWith(CUSTOM_URL_SCHEME)) { - QString destination = fileEvent->url().toLocalFile().remove(CUSTOM_URL_SCHEME); - QStringList urlParts = destination.split('/', QString::SkipEmptyParts); - - if (urlParts.count() > 1) { - // if url has 2 or more parts, the first one is domain name - Menu::getInstance()->goToDomain(urlParts[0]); - - // location coordinates - Menu::getInstance()->goToDestination(urlParts[1]); - if (urlParts.count() > 2) { - - // location orientation - Menu::getInstance()->goToOrientation(urlParts[2]); - } - } else if (urlParts.count() == 1) { - - // location coordinates - Menu::getInstance()->goToDestination(urlParts[0]); - } + bool isHifiSchemeURL = !fileEvent->url().isEmpty() && fileEvent->url().toLocalFile().startsWith(CUSTOM_URL_SCHEME); + if (isHifiSchemeURL) { + Menu::getInstance()->goTo(fileEvent->url().toString()); } return false; diff --git a/interface/src/Application.h b/interface/src/Application.h index bab7578ca4..a0b81a740e 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -93,6 +93,7 @@ static const float NODE_KILLED_GREEN = 0.0f; static const float NODE_KILLED_BLUE = 0.0f; static const QString SNAPSHOT_EXTENSION = ".jpg"; +static const QString CUSTOM_URL_SCHEME = "hifi:"; static const float BILLBOARD_FIELD_OF_VIEW = 30.0f; // degrees static const float BILLBOARD_DISTANCE = 5.0f; // meters diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index ec20401fef..31471ce60b 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -912,19 +912,58 @@ bool Menu::goToDestination(QString destination) { return LocationManager::getInstance().goToDestination(destination); } +void Menu::goTo(QString destination) { + LocationManager::getInstance().goTo(destination); +} + void Menu::goTo() { QInputDialog gotoDialog(Application::getInstance()->getWindow()); gotoDialog.setWindowTitle("Go to"); - gotoDialog.setLabelText("Destination:"); + gotoDialog.setLabelText("Destination or URL:\n @user, #place, hifi://domain/location/orientation"); QString destination = QString(); + gotoDialog.setTextValue(destination); gotoDialog.setWindowFlags(Qt::Sheet); gotoDialog.resize(gotoDialog.parentWidget()->size().width() * DIALOG_RATIO_OF_WINDOW, gotoDialog.size().height()); int dialogReturn = gotoDialog.exec(); if (dialogReturn == QDialog::Accepted && !gotoDialog.textValue().isEmpty()) { - goToUser(gotoDialog.textValue()); + QString desiredDestination = gotoDialog.textValue(); + + if (desiredDestination.startsWith(CUSTOM_URL_SCHEME + "//")) { + QStringList urlParts = desiredDestination.remove(0, CUSTOM_URL_SCHEME.length() + 2).split('/', QString::SkipEmptyParts); + + if (urlParts.count() > 1) { + // if url has 2 or more parts, the first one is domain name + QString domain = urlParts[0]; + + // second part is either a destination coordinate or + // a place name + QString destination = urlParts[1]; + + // any third part is an avatar orientation. + QString orientation = urlParts.count() > 2 ? urlParts[2] : QString(); + + goToDomain(domain); + + // goto either @user, #place, or x-xx,y-yy,z-zz + // style co-ordinate. + goTo(destination); + + if (!orientation.isEmpty()) { + // location orientation + goToOrientation(orientation); + } + } else if (urlParts.count() == 1) { + // location coordinates or place name + QString destination = urlParts[0]; + goTo(destination); + } + + } else { + goToUser(gotoDialog.textValue()); + } } sendFakeEnterEvent(); } diff --git a/interface/src/Menu.h b/interface/src/Menu.h index c7c4c6ecea..f31803e65d 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -110,6 +110,7 @@ public: bool goToDestination(QString destination); void goToOrientation(QString orientation); void goToDomain(const QString newDomain); + void goTo(QString destination); public slots: From 7cd39d3ef044d77fd3615a27230cc0ae4cea3761 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 20:53:34 -0700 Subject: [PATCH 059/595] add forceNodeShutdown() to handle forced shutdown of nodes in case of server shutdown --- .../src/octree/OctreeQueryNode.cpp | 48 +++++++++---------- .../src/octree/OctreeQueryNode.h | 7 ++- .../src/octree/OctreeSendThread.cpp | 13 +---- assignment-client/src/octree/OctreeServer.cpp | 34 +++++++++++-- assignment-client/src/octree/OctreeServer.h | 1 + libraries/shared/src/ThreadedAssignment.cpp | 4 -- 6 files changed, 60 insertions(+), 47 deletions(-) diff --git a/assignment-client/src/octree/OctreeQueryNode.cpp b/assignment-client/src/octree/OctreeQueryNode.cpp index 3291fb49ba..642a34edd7 100644 --- a/assignment-client/src/octree/OctreeQueryNode.cpp +++ b/assignment-client/src/octree/OctreeQueryNode.cpp @@ -49,6 +49,10 @@ OctreeQueryNode::~OctreeQueryNode() { qDebug() << "OctreeQueryNode::~OctreeQueryNode()"; } + if (_octreeSendThread) { + forceNodeShutdown(); + } + delete[] _octreePacket; delete[] _lastOctreePacket; if (extraDebugging) { @@ -56,51 +60,45 @@ OctreeQueryNode::~OctreeQueryNode() { } } - -void OctreeQueryNode::deleteLater() { +void OctreeQueryNode::nodeKilled() { _isShuttingDown = true; if (_octreeSendThread) { + // just tell our thread we want to shutdown, this is asynchronous, and fast, we don't need or want it to block + // while the thread actually shuts down _octreeSendThread->setIsShuttingDown(); } - OctreeQuery::deleteLater(); } -void OctreeQueryNode::nodeKilled() { - qDebug() << "OctreeQueryNode::nodeKilled()... "; +void OctreeQueryNode::forceNodeShutdown() { _isShuttingDown = true; if (_octreeSendThread) { + // we really need to force our thread to shutdown, this is synchronous, we will block while the thread actually + // shuts down because we really need it to shutdown, and it's ok if we wait for it to complete OctreeSendThread* sendThread = _octreeSendThread; - - //qDebug() << "OctreeQueryNode::nodeKilled()... calling _octreeSendThread = NULL"; _octreeSendThread = NULL; - //qDebug() << "OctreeQueryNode::nodeKilled()... AFTER _octreeSendThread = NULL"; - - //qDebug() << "OctreeQueryNode::nodeKilled()... calling _octreeSendThread->setIsShuttingDown()"; sendThread->setIsShuttingDown(); - //qDebug() << "OctreeQueryNode::nodeKilled()... AFTER _octreeSendThread->setIsShuttingDown()"; - - //qDebug() << "OctreeQueryNode::nodeKilled()... calling _octreeSendThread->terminate()"; sendThread->terminate(); - //qDebug() << "OctreeQueryNode::nodeKilled()... AFTER _octreeSendThread->terminate()"; - - //qDebug() << "OctreeQueryNode::nodeKilled()... calling delete sendThread"; delete sendThread; - //qDebug() << "OctreeQueryNode::nodeKilled()... AFTER delete sendThread"; - } - qDebug() << "OctreeQueryNode::nodeKilled()... DONE"; } +void OctreeQueryNode::sendThreadFinished() { + // We've been notified by our thread that it is shutting down. So we can clean up our reference to it, and + // delete the actual thread object. Cleaning up our thread will correctly unroll all refereces to shared + // pointers to our node as well as the octree server assignment + if (_octreeSendThread) { + OctreeSendThread* sendThread = _octreeSendThread; + _octreeSendThread = NULL; + delete sendThread; + } +} void OctreeQueryNode::initializeOctreeSendThread(const SharedAssignmentPointer& myAssignment, const SharedNodePointer& node) { - // Create octree sending thread... - //qDebug() << "OctreeQueryNode::initializeOctreeSendThread()... BEFORE new OctreeSendThread(myAssignment, node);"; _octreeSendThread = new OctreeSendThread(myAssignment, node); - //qDebug() << "OctreeQueryNode::initializeOctreeSendThread()... AFTER new OctreeSendThread(myAssignment, node);"; - - //qDebug() << "OctreeQueryNode::initializeOctreeSendThread()... BEFORE _octreeSendThread->initialize(true)"; + + // we want to be notified when the thread finishes + connect(_octreeSendThread, &GenericThread::finished, this, &OctreeQueryNode::sendThreadFinished); _octreeSendThread->initialize(true); - //qDebug() << "OctreeQueryNode::initializeOctreeSendThread()... AFTER _octreeSendThread->initialize(true)"; } bool OctreeQueryNode::packetIsDuplicate() const { diff --git a/assignment-client/src/octree/OctreeQueryNode.h b/assignment-client/src/octree/OctreeQueryNode.h index c08bdcb2bf..a3f31ba98b 100644 --- a/assignment-client/src/octree/OctreeQueryNode.h +++ b/assignment-client/src/octree/OctreeQueryNode.h @@ -28,8 +28,7 @@ class OctreeQueryNode : public OctreeQuery { public: OctreeQueryNode(); virtual ~OctreeQueryNode(); - virtual void deleteLater(); - + void init(); // called after creation to set up some virtual items virtual PacketType getMyPacketType() const = 0; @@ -95,8 +94,12 @@ public: int getDuplicatePacketCount() const { return _duplicatePacketCount; } void nodeKilled(); + void forceNodeShutdown(); bool isShuttingDown() const { return _isShuttingDown; } +private slots: + void sendThreadFinished(); + private: OctreeQueryNode(const OctreeQueryNode &); OctreeQueryNode& operator= (const OctreeQueryNode&); diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index a748d766c3..e655acc400 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -44,28 +44,17 @@ OctreeSendThread::OctreeSendThread(const SharedAssignmentPointer& myAssignment, } OctreeSendThread::~OctreeSendThread() { - //qDebug() << "OctreeSendThread::~OctreeSendThread()... START"; QString serverName("Octree"); if (_myServer) { serverName = _myServer->getMyServerName(); } - + qDebug() << qPrintable(serverName) << "server [" << _myServer << "]: client disconnected " "- ending sending thread [" << this << "]"; - //qDebug() << "OctreeSendThread::~OctreeSendThread()... BEFORE OctreeServer::clientDisconnected();"; OctreeServer::clientDisconnected(); - //qDebug() << "OctreeSendThread::~OctreeSendThread()... AFTER OctreeServer::clientDisconnected();"; - - //qDebug() << "OctreeSendThread::~OctreeSendThread()... BEFORE _node.clear();"; _node.clear(); - //qDebug() << "OctreeSendThread::~OctreeSendThread()... AFTER _node.clear();"; - - //qDebug() << "OctreeSendThread::~OctreeSendThread()... BEFORE _myAssignment.clear();"; _myAssignment.clear(); - //qDebug() << "OctreeSendThread::~OctreeSendThread()... BEFORE _myAssignment.clear();"; - - //qDebug() << "OctreeSendThread::~OctreeSendThread()... DONE"; } void OctreeSendThread::setIsShuttingDown() { diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 11d0e0ca37..567e91157d 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -233,7 +233,10 @@ OctreeServer::OctreeServer(const QByteArray& packet) : _started(time(0)), _startedUSecs(usecTimestampNow()) { - assert(!_instance); // you should only ever have one instance at a time! + //assert(!_instance); // you should only ever have one instance at a time! + if (_instance) { + qDebug() << "Octree Server starting... while old instance still running _instance=["<<_instance<<"] this=[" << this << "]"; + } qDebug() << "Octree Server starting... setting _instance to=[" << this << "]"; _instance = this; @@ -268,7 +271,10 @@ OctreeServer::~OctreeServer() { delete _jurisdiction; _jurisdiction = NULL; - _instance = NULL; // we are gone + + if (_instance == this) { + _instance = NULL; // we are gone + } qDebug() << qPrintable(_safeServerName) << "server DONE shutting down... [" << this << "]"; } @@ -1065,14 +1071,34 @@ void OctreeServer::nodeKilled(SharedNodePointer node) { quint64 end = usecTimestampNow(); quint64 usecsElapsed = (end - start); - qDebug() << qPrintable(_safeServerName) << "server killed node:" << *node << " took: " << usecsElapsed << " usecs"; + qDebug() << qPrintable(_safeServerName) << "server killed took: " << usecsElapsed << " usecs for node:" << *node; } +void OctreeServer::forceNodeShutdown(SharedNodePointer node) { + quint64 start = usecTimestampNow(); + + qDebug() << qPrintable(_safeServerName) << "server killed node:" << *node; + OctreeQueryNode* nodeData = static_cast(node->getLinkedData()); + if (nodeData) { + qDebug() << qPrintable(_safeServerName) << "server calling nodeData->forceNodeShutdown() for node:" << *node; + nodeData->forceNodeShutdown(); // tell our node data and sending threads that we'd like to shut down + qDebug() << qPrintable(_safeServerName) << "server AFTER nodeData->forceNodeShutdown() for node:" << *node; + } else { + qDebug() << qPrintable(_safeServerName) << "server node missing linked data node:" << *node; + } + + quint64 end = usecTimestampNow(); + quint64 usecsElapsed = (end - start); + qDebug() << qPrintable(_safeServerName) << "server killed took: " << usecsElapsed << " usecs for node:" << *node; +} + + void OctreeServer::aboutToFinish() { qDebug() << qPrintable(_safeServerName) << "server STARTING about to finish..."; foreach (const SharedNodePointer& node, NodeList::getInstance()->getNodeHash()) { qDebug() << qPrintable(_safeServerName) << "server about to finish while node still connected node:" << *node; - nodeKilled(node); + + forceNodeShutdown(node); } qDebug() << qPrintable(_safeServerName) << "server ENDING about to finish..."; diff --git a/assignment-client/src/octree/OctreeServer.h b/assignment-client/src/octree/OctreeServer.h index 63d43b6634..63a3341f55 100644 --- a/assignment-client/src/octree/OctreeServer.h +++ b/assignment-client/src/octree/OctreeServer.h @@ -115,6 +115,7 @@ public: bool handleHTTPRequest(HTTPConnection* connection, const QUrl& url); virtual void aboutToFinish(); + void forceNodeShutdown(SharedNodePointer node); public slots: /// runs the voxel server assignment diff --git a/libraries/shared/src/ThreadedAssignment.cpp b/libraries/shared/src/ThreadedAssignment.cpp index eed5aa46f6..fdf2d91c36 100644 --- a/libraries/shared/src/ThreadedAssignment.cpp +++ b/libraries/shared/src/ThreadedAssignment.cpp @@ -74,10 +74,6 @@ void ThreadedAssignment::sendStatsPacket() { } void ThreadedAssignment::checkInWithDomainServerOrExit() { - qDebug() << "ThreadedAssignment::checkInWithDomainServerOrExit()... " - "Num No Reply Domain Check Ins=" << NodeList::getInstance()->getNumNoReplyDomainCheckIns() - << "MAX_SILENT_DOMAIN_SERVER_CHECK_INS=" << MAX_SILENT_DOMAIN_SERVER_CHECK_INS; - if (NodeList::getInstance()->getNumNoReplyDomainCheckIns() == MAX_SILENT_DOMAIN_SERVER_CHECK_INS) { setFinished(true); } else { From 9df315d8896e1f2685495f03b3a7aabb16b31c55 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 31 Mar 2014 20:54:58 -0700 Subject: [PATCH 060/595] removed dead debug code --- assignment-client/src/octree/OctreeSendThread.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index e655acc400..48d45bbb55 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -28,8 +28,6 @@ OctreeSendThread::OctreeSendThread(const SharedAssignmentPointer& myAssignment, _nodeMissingCount(0), _isShuttingDown(false) { - //qDebug() << "OctreeSendThread::OctreeSendThread()... START"; - QString serverName("Octree"); if (_myServer) { serverName = _myServer->getMyServerName(); @@ -37,10 +35,7 @@ OctreeSendThread::OctreeSendThread(const SharedAssignmentPointer& myAssignment, qDebug() << qPrintable(serverName) << "server [" << _myServer << "]: client connected " "- starting sending thread [" << this << "]"; - //qDebug() << "OctreeSendThread::OctreeSendThread()... before OctreeServer::clientConnected()"; OctreeServer::clientConnected(); - //qDebug() << "OctreeSendThread::OctreeSendThread()... AFTER OctreeServer::clientConnected()"; - //qDebug() << "OctreeSendThread::OctreeSendThread()... DONE"; } OctreeSendThread::~OctreeSendThread() { From 6ed9b968b08882fbebf0b2e6c8d5ced6642d6326 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 09:23:19 -0700 Subject: [PATCH 061/595] removed some extra debugging --- assignment-client/src/octree/OctreeQueryNode.cpp | 8 -------- 1 file changed, 8 deletions(-) diff --git a/assignment-client/src/octree/OctreeQueryNode.cpp b/assignment-client/src/octree/OctreeQueryNode.cpp index 642a34edd7..a20b3dad01 100644 --- a/assignment-client/src/octree/OctreeQueryNode.cpp +++ b/assignment-client/src/octree/OctreeQueryNode.cpp @@ -44,20 +44,12 @@ OctreeQueryNode::OctreeQueryNode() : OctreeQueryNode::~OctreeQueryNode() { _isShuttingDown = true; - const bool extraDebugging = true; - if (extraDebugging) { - qDebug() << "OctreeQueryNode::~OctreeQueryNode()"; - } - if (_octreeSendThread) { forceNodeShutdown(); } delete[] _octreePacket; delete[] _lastOctreePacket; - if (extraDebugging) { - qDebug() << "OctreeQueryNode::~OctreeQueryNode()... DONE..."; - } } void OctreeQueryNode::nodeKilled() { From 1bbdc9d78b771ceafd9679c3fc02dafddd66d485 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 1 Apr 2014 09:25:25 -0700 Subject: [PATCH 062/595] Adding bounding capsule shape for Model Also: Cleaned up the automatic geometry LOD loading Removed staticExtents data member from FBXGeometry Split debug rendering of bounding shapes from joint shapes --- interface/interface_en.ts | 8 +- interface/src/Menu.cpp | 5 +- interface/src/Menu.h | 5 +- interface/src/avatar/Avatar.cpp | 25 +- interface/src/avatar/Avatar.h | 1 - interface/src/avatar/FaceModel.cpp | 6 +- interface/src/avatar/Hand.cpp | 2 +- interface/src/avatar/MyAvatar.cpp | 47 +-- interface/src/avatar/SkeletonModel.cpp | 12 +- interface/src/avatar/SkeletonModel.h | 8 +- interface/src/renderer/FBXReader.cpp | 12 +- interface/src/renderer/FBXReader.h | 5 +- interface/src/renderer/Model.cpp | 389 +++++++++++++++---------- interface/src/renderer/Model.h | 33 ++- 14 files changed, 337 insertions(+), 221 deletions(-) diff --git a/interface/interface_en.ts b/interface/interface_en.ts index da8827d89d..ade5275c30 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -113,18 +113,18 @@ Menu - + Open .ini config file - - + + Text files (*.ini) - + Save .ini config file diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 79b0a23ce5..d77f236300 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -282,8 +282,9 @@ Menu::Menu() : QMenu* avatarOptionsMenu = developerMenu->addMenu("Avatar Options"); addCheckableActionToQMenuAndActionHash(avatarOptionsMenu, MenuOption::Avatars, 0, true); - addCheckableActionToQMenuAndActionHash(avatarOptionsMenu, MenuOption::RenderSkeletonCollisionProxies); - addCheckableActionToQMenuAndActionHash(avatarOptionsMenu, MenuOption::RenderHeadCollisionProxies); + addCheckableActionToQMenuAndActionHash(avatarOptionsMenu, MenuOption::RenderSkeletonCollisionShapes); + addCheckableActionToQMenuAndActionHash(avatarOptionsMenu, MenuOption::RenderHeadCollisionShapes); + addCheckableActionToQMenuAndActionHash(avatarOptionsMenu, MenuOption::RenderBoundingCollisionShapes); addCheckableActionToQMenuAndActionHash(avatarOptionsMenu, MenuOption::LookAtVectors, 0, false); addCheckableActionToQMenuAndActionHash(avatarOptionsMenu, diff --git a/interface/src/Menu.h b/interface/src/Menu.h index cab5645304..cc5bb2c186 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -285,8 +285,9 @@ namespace MenuOption { const QString PlaySlaps = "Play Slaps"; const QString Preferences = "Preferences..."; const QString ReloadAllScripts = "Reload All Scripts"; - const QString RenderSkeletonCollisionProxies = "Skeleton Collision Proxies"; - const QString RenderHeadCollisionProxies = "Head Collision Proxies"; + const QString RenderSkeletonCollisionShapes = "Skeleton Collision Shapes"; + const QString RenderHeadCollisionShapes = "Head Collision Shapes"; + const QString RenderBoundingCollisionShapes = "Bounding Collision Shapes"; const QString ResetAvatarSize = "Reset Avatar Size"; const QString RunTimingTests = "Run Timing Tests"; const QString SettingsImport = "Import Settings"; diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 75b0a4c66a..b36baf15b1 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -56,8 +56,7 @@ Avatar::Avatar() : _owningAvatarMixer(), _collisionFlags(0), _initialized(false), - _shouldRenderBillboard(true), - _modelsDirty(true) + _shouldRenderBillboard(true) { // we may have been created in the network thread, but we live in the main thread moveToThread(Application::getInstance()->thread()); @@ -125,8 +124,7 @@ void Avatar::simulate(float deltaTime) { } glm::vec3 headPosition = _position; if (!_shouldRenderBillboard && inViewFrustum) { - _skeletonModel.simulate(deltaTime, _modelsDirty); - _modelsDirty = false; + _skeletonModel.simulate(deltaTime); _skeletonModel.getHeadPosition(headPosition); } Head* head = getHead(); @@ -210,11 +208,19 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode) { if (Menu::getInstance()->isOptionChecked(MenuOption::Avatars)) { renderBody(renderMode); } - if (Menu::getInstance()->isOptionChecked(MenuOption::RenderSkeletonCollisionProxies)) { - _skeletonModel.renderCollisionProxies(0.7f); + if (Menu::getInstance()->isOptionChecked(MenuOption::RenderSkeletonCollisionShapes)) { + _skeletonModel.updateShapePositions(); + _skeletonModel.renderJointCollisionShapes(0.7f); } - if (Menu::getInstance()->isOptionChecked(MenuOption::RenderHeadCollisionProxies)) { - getHead()->getFaceModel().renderCollisionProxies(0.7f); + if (Menu::getInstance()->isOptionChecked(MenuOption::RenderHeadCollisionShapes)) { + getHead()->getFaceModel().updateShapePositions(); + getHead()->getFaceModel().renderJointCollisionShapes(0.7f); + } + if (Menu::getInstance()->isOptionChecked(MenuOption::RenderBoundingCollisionShapes)) { + _skeletonModel.updateShapePositions(); + _skeletonModel.renderBoundingCollisionShapes(0.7f); + getHead()->getFaceModel().updateShapePositions(); + getHead()->getFaceModel().renderBoundingCollisionShapes(0.7f); } // quick check before falling into the code below: @@ -650,9 +656,6 @@ int Avatar::parseDataAtOffset(const QByteArray& packet, int offset) { const float MOVE_DISTANCE_THRESHOLD = 0.001f; _moving = glm::distance(oldPosition, _position) > MOVE_DISTANCE_THRESHOLD; - // note that we need to update our models - _modelsDirty = true; - return bytesRead; } diff --git a/interface/src/avatar/Avatar.h b/interface/src/avatar/Avatar.h index f2ee400ba2..f6d5669859 100755 --- a/interface/src/avatar/Avatar.h +++ b/interface/src/avatar/Avatar.h @@ -192,7 +192,6 @@ private: bool _initialized; QScopedPointer _billboardTexture; bool _shouldRenderBillboard; - bool _modelsDirty; void renderBillboard(); diff --git a/interface/src/avatar/FaceModel.cpp b/interface/src/avatar/FaceModel.cpp index 19120d10be..c483642d15 100644 --- a/interface/src/avatar/FaceModel.cpp +++ b/interface/src/avatar/FaceModel.cpp @@ -19,8 +19,8 @@ FaceModel::FaceModel(Head* owningHead) : } void FaceModel::simulate(float deltaTime) { - QVector newJointStates = updateGeometry(); - if (!isActive()) { + bool geometryIsUpToDate = updateGeometry(); + if (!geometryIsUpToDate) { return; } Avatar* owningAvatar = static_cast(_owningHead->_owningAvatar); @@ -42,7 +42,7 @@ void FaceModel::simulate(float deltaTime) { setPupilDilation(_owningHead->getPupilDilation()); setBlendshapeCoefficients(_owningHead->getBlendshapeCoefficients()); - Model::simulate(deltaTime, true, newJointStates); + Model::simulateInternal(deltaTime); } void FaceModel::maybeUpdateNeckRotation(const JointState& parentState, const FBXJoint& joint, JointState& state) { diff --git a/interface/src/avatar/Hand.cpp b/interface/src/avatar/Hand.cpp index 750fae7b2a..4351a53ab4 100644 --- a/interface/src/avatar/Hand.cpp +++ b/interface/src/avatar/Hand.cpp @@ -253,7 +253,7 @@ void Hand::render(bool isMine) { _renderAlpha = 1.0; - if (Menu::getInstance()->isOptionChecked(MenuOption::RenderSkeletonCollisionProxies)) { + if (Menu::getInstance()->isOptionChecked(MenuOption::RenderSkeletonCollisionShapes)) { // draw a green sphere at hand joint location, which is actually near the wrist) for (size_t i = 0; i < getNumPalms(); i++) { PalmData& palm = getPalms()[i]; diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index e18735e3e5..6e01ad3292 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -20,6 +20,11 @@ #include #include +#ifdef ANDREW_HACKERY +#include +#include +#endif ANDREW_HACKERY + #include "Application.h" #include "Audio.h" #include "Environment.h" @@ -867,6 +872,8 @@ bool findAvatarAvatarPenetration(const glm::vec3 positionA, float radiusA, float return false; } +static CollisionList bodyCollisions(16); + void MyAvatar::updateCollisionWithAvatars(float deltaTime) { // Reset detector for nearest avatar _distanceToNearestAvatar = std::numeric_limits::max(); @@ -878,15 +885,6 @@ void MyAvatar::updateCollisionWithAvatars(float deltaTime) { updateShapePositions(); float myBoundingRadius = getBoundingRadius(); - /* TODO: Andrew to fix Avatar-Avatar body collisions - // HACK: body-body collision uses two coaxial capsules with axes parallel to y-axis - // TODO: make the collision work without assuming avatar orientation - Extents myStaticExtents = _skeletonModel.getStaticExtents(); - glm::vec3 staticScale = myStaticExtents.maximum - myStaticExtents.minimum; - float myCapsuleRadius = 0.25f * (staticScale.x + staticScale.z); - float myCapsuleHeight = staticScale.y; - */ - foreach (const AvatarSharedPointer& avatarPointer, avatars) { Avatar* avatar = static_cast(avatarPointer.data()); if (static_cast(this) == avatar) { @@ -900,19 +898,26 @@ void MyAvatar::updateCollisionWithAvatars(float deltaTime) { } float theirBoundingRadius = avatar->getBoundingRadius(); if (distance < myBoundingRadius + theirBoundingRadius) { - /* TODO: Andrew to fix Avatar-Avatar body collisions - Extents theirStaticExtents = _skeletonModel.getStaticExtents(); - glm::vec3 staticScale = theirStaticExtents.maximum - theirStaticExtents.minimum; - float theirCapsuleRadius = 0.25f * (staticScale.x + staticScale.z); - float theirCapsuleHeight = staticScale.y; - - glm::vec3 penetration(0.f); - if (findAvatarAvatarPenetration(_position, myCapsuleRadius, myCapsuleHeight, - avatar->getPosition(), theirCapsuleRadius, theirCapsuleHeight, penetration)) { - // move the avatar out by half the penetration - setPosition(_position - 0.5f * penetration); +#ifdef ANDREW_HACKERY + QVector myShapes; + _skeletonModel.getBodyShapes(myShapes); + QVector theirShapes; + avatar->getSkeletonModel().getBodyShapes(theirShapes); + bodyCollisions.clear(); + foreach (const Shape* myShape, myShapes) { + foreach (const Shape* theirShape, theirShapes) { + ShapeCollider::shapeShape(myShape, theirShape, bodyCollisions); + if (bodyCollisions.size() > 0) { + std::cout << "adebug myPos = " << myShape->getPosition() + << " myRadius = " << myShape->getBoundingRadius() + << " theirPos = " << theirShape->getPosition() + << " theirRadius = " << theirShape->getBoundingRadius() + << std::endl; // adebug + std::cout << "adebug collision count = " << bodyCollisions.size() << std::endl; // adebug + } + } } - */ +#endif // ANDREW_HACKERY // collide our hands against them // TODO: make this work when we can figure out when the other avatar won't yeild diff --git a/interface/src/avatar/SkeletonModel.cpp b/interface/src/avatar/SkeletonModel.cpp index 9d67709fde..0986021ac8 100644 --- a/interface/src/avatar/SkeletonModel.cpp +++ b/interface/src/avatar/SkeletonModel.cpp @@ -14,17 +14,17 @@ #include "Menu.h" #include "SkeletonModel.h" -SkeletonModel::SkeletonModel(Avatar* owningAvatar) : +SkeletonModel::SkeletonModel(Avatar* owningAvatar) : _owningAvatar(owningAvatar) { } -void SkeletonModel::simulate(float deltaTime, bool fullUpdate) { +void SkeletonModel::simulate(float deltaTime) { setTranslation(_owningAvatar->getPosition()); setRotation(_owningAvatar->getOrientation() * glm::angleAxis(PI, glm::vec3(0.0f, 1.0f, 0.0f))); const float MODEL_SCALE = 0.0006f; setScale(glm::vec3(1.0f, 1.0f, 1.0f) * _owningAvatar->getScale() * MODEL_SCALE); - Model::simulate(deltaTime, fullUpdate); + Model::simulate(deltaTime); if (!(isActive() && _owningAvatar->isMyAvatar())) { return; // only simulate for own avatar @@ -94,6 +94,12 @@ void SkeletonModel::getHandShapes(int jointIndex, QVector& shapes) } } +void SkeletonModel::getBodyShapes(QVector& shapes) const { + // for now we push a single bounding shape, + // but later we could push a subset of joint shapes + shapes.push_back(&_boundingShape); +} + class IndexValue { public: int index; diff --git a/interface/src/avatar/SkeletonModel.h b/interface/src/avatar/SkeletonModel.h index 213a53d9ed..60b12eb8f5 100644 --- a/interface/src/avatar/SkeletonModel.h +++ b/interface/src/avatar/SkeletonModel.h @@ -9,7 +9,6 @@ #ifndef __interface__SkeletonModel__ #define __interface__SkeletonModel__ - #include "renderer/Model.h" class Avatar; @@ -22,14 +21,17 @@ public: SkeletonModel(Avatar* owningAvatar); - void simulate(float deltaTime, bool fullUpdate = true); + void simulate(float deltaTime); /// \param jointIndex index of hand joint /// \param shapes[out] list in which is stored pointers to hand shapes void getHandShapes(int jointIndex, QVector& shapes) const; + /// \param shapes[out] list of shapes for body collisions + void getBodyShapes(QVector& shapes) const; + protected: - + void applyHandPosition(int jointIndex, const glm::vec3& position); void applyPalmData(int jointIndex, const QVector& fingerJointIndices, diff --git a/interface/src/renderer/FBXReader.cpp b/interface/src/renderer/FBXReader.cpp index 53f4e04b0b..87b7d43938 100644 --- a/interface/src/renderer/FBXReader.cpp +++ b/interface/src/renderer/FBXReader.cpp @@ -41,6 +41,11 @@ bool Extents::containsPoint(const glm::vec3& point) const { && point.z >= minimum.z && point.z <= maximum.z); } +void Extents::addExtents(const Extents& extents) { + minimum = glm::min(minimum, extents.minimum); + maximum = glm::max(maximum, extents.maximum); +} + void Extents::addPoint(const glm::vec3& point) { minimum = glm::min(minimum, point); maximum = glm::max(maximum, point); @@ -1337,7 +1342,6 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) } geometry.bindExtents.reset(); - geometry.staticExtents.reset(); geometry.meshExtents.reset(); for (QHash::iterator it = meshes.begin(); it != meshes.end(); it++) { @@ -1505,8 +1509,6 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) JointShapeInfo& jointShapeInfo = jointShapeInfos[jointIndex]; jointShapeInfo.boneBegin = rotateMeshToJoint * (radiusScale * (boneBegin - boneEnd)); - bool jointIsStatic = joint.freeLineage.isEmpty(); - glm::vec3 jointTranslation = extractTranslation(geometry.offset * joint.bindTransform); float totalWeight = 0.0f; for (int j = 0; j < cluster.indices.size(); j++) { int oldIndex = cluster.indices.at(j); @@ -1528,10 +1530,6 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) jointShapeInfo.extents.addPoint(vertexInJointFrame); jointShapeInfo.averageVertex += vertexInJointFrame; ++jointShapeInfo.numVertices; - if (jointIsStatic) { - // expand the extents of static (nonmovable) joints - geometry.staticExtents.addPoint(vertex + jointTranslation); - } } // look for an unused slot in the weights vector diff --git a/interface/src/renderer/FBXReader.h b/interface/src/renderer/FBXReader.h index 5f6a4f51ba..2847d2a971 100644 --- a/interface/src/renderer/FBXReader.h +++ b/interface/src/renderer/FBXReader.h @@ -30,6 +30,10 @@ public: /// set minimum and maximum to FLT_MAX and -FLT_MAX respectively void reset(); + /// \param extents another intance of extents + /// expand current limits to contain other extents + void addExtents(const Extents& extents); + /// \param point new point to compare against existing limits /// compare point to current limits and expand them if necessary to contain point void addPoint(const glm::vec3& point); @@ -174,7 +178,6 @@ public: glm::vec3 neckPivot; Extents bindExtents; - Extents staticExtents; Extents meshExtents; QVector attachments; diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index ceddcd009a..8251b67b1e 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -32,9 +32,11 @@ Model::Model(QObject* parent) : QObject(parent), _scale(1.0f, 1.0f, 1.0f), _shapesAreDirty(true), + _boundingRadius(0.f), + _boundingShape(), + _boundingShapeLocalOffset(0.f), _lodDistance(0.0f), - _pupilDilation(0.0f), - _boundingRadius(0.f) { + _pupilDilation(0.0f) { // we may have been created in the network thread, but we live in the main thread moveToThread(Application::getInstance()->thread()); } @@ -73,6 +75,44 @@ QVector Model::createJointStates(const FBXGeometry& geometry) state.rotation = joint.rotation; jointStates.append(state); } + + // compute transforms + // Unfortunately, the joints are not neccessarily in order from parents to children, + // so we must iterate over the list multiple times until all are set correctly. + QVector jointIsSet; + int numJoints = jointStates.size(); + jointIsSet.fill(false, numJoints); + int numJointsSet = 0; + int lastNumJointsSet = -1; + while (numJointsSet < numJoints && numJointsSet != lastNumJointsSet) { + lastNumJointsSet = numJointsSet; + for (int i = 0; i < numJoints; ++i) { + if (jointIsSet[i]) { + continue; + } + JointState& state = jointStates[i]; + const FBXJoint& joint = geometry.joints[i]; + int parentIndex = joint.parentIndex; + if (parentIndex == -1) { + glm::mat4 baseTransform = glm::mat4_cast(_rotation) * glm::scale(_scale) * glm::translate(_offset); + glm::quat combinedRotation = joint.preRotation * state.rotation * joint.postRotation; + state.transform = baseTransform * geometry.offset * glm::translate(state.translation) * joint.preTransform * + glm::mat4_cast(combinedRotation) * joint.postTransform; + state.combinedRotation = _rotation * combinedRotation; + ++numJointsSet; + jointIsSet[i] = true; + } else if (jointIsSet[parentIndex]) { + const JointState& parentState = jointStates.at(parentIndex); + glm::quat combinedRotation = joint.preRotation * state.rotation * joint.postRotation; + state.transform = parentState.transform * glm::translate(state.translation) * joint.preTransform * + glm::mat4_cast(combinedRotation) * joint.postTransform; + state.combinedRotation = parentState.combinedRotation * combinedRotation; + ++numJointsSet; + jointIsSet[i] = true; + } + } + } + return jointStates; } @@ -135,65 +175,87 @@ void Model::reset() { } } -void Model::clearShapes() { - for (int i = 0; i < _jointShapes.size(); ++i) { - delete _jointShapes[i]; - } - _jointShapes.clear(); -} +// return 'true' if geometry is up to date +bool Model::updateGeometry() { + bool needToRebuild = false; -void Model::createJointCollisionShapes() { - clearShapes(); - const FBXGeometry& geometry = _geometry->getFBXGeometry(); - float uniformScale = extractUniformScale(_scale); - for (int i = 0; i < _jointStates.size(); i++) { - const FBXJoint& joint = geometry.joints[i]; - glm::vec3 meshCenter = _jointStates[i].combinedRotation * joint.shapePosition; - glm::vec3 position = _rotation * (extractTranslation(_jointStates[i].transform) + uniformScale * meshCenter) + _translation; - - float radius = uniformScale * joint.boneRadius; - if (joint.shapeType == Shape::CAPSULE_SHAPE) { - float halfHeight = 0.5f * uniformScale * joint.distanceToParent; - CapsuleShape* shape = new CapsuleShape(radius, halfHeight); - shape->setPosition(position); - _jointShapes.push_back(shape); - } else { - SphereShape* shape = new SphereShape(radius, position); - _jointShapes.push_back(shape); + if (_nextGeometry) { + _nextGeometry = _nextGeometry->getLODOrFallback(_lodDistance, _nextLODHysteresis); + _nextGeometry->setLoadPriority(this, -_lodDistance); + _nextGeometry->ensureLoading(); + if (_nextGeometry->isLoaded()) { + applyNextGeometry(); + needToRebuild = true; } } -} + if (!_geometry) { + // geometry is not ready + return false; + } -void Model::createBoundingShape() { - //const FBXGeometry& geometry = _geometry->getFBXGeometry(); - //float uniformScale = extractUniformScale(_scale); -} + QSharedPointer geometry = _geometry->getLODOrFallback(_lodDistance, _lodHysteresis); + if (_geometry != geometry) { + // NOTE: it is theoretically impossible to reach here after passing through the applyNextGeometry() call above. + // Which means we don't need to worry about calling deleteGeometry() below immediately after creating new geometry. -void Model::updateShapePositions() { - if (_shapesAreDirty && _jointShapes.size() == _jointStates.size()) { - _boundingRadius = 0.f; - float uniformScale = extractUniformScale(_scale); - const FBXGeometry& geometry = _geometry->getFBXGeometry(); - for (int i = 0; i < _jointStates.size(); i++) { - const FBXJoint& joint = geometry.joints[i]; - // shape position and rotation need to be in world-frame - glm::vec3 jointToShapeOffset = uniformScale * (_jointStates[i].combinedRotation * joint.shapePosition); - glm::vec3 worldPosition = extractTranslation(_jointStates[i].transform) + jointToShapeOffset + _translation; - _jointShapes[i]->setPosition(worldPosition); - _jointShapes[i]->setRotation(_jointStates[i].combinedRotation * joint.shapeRotation); - float distance2 = glm::distance2(worldPosition, _translation); - if (distance2 > _boundingRadius) { - _boundingRadius = distance2; + const FBXGeometry& newGeometry = geometry->getFBXGeometry(); + QVector newJointStates = createJointStates(newGeometry); + if (! _jointStates.isEmpty()) { + // copy the existing joint states + const FBXGeometry& oldGeometry = _geometry->getFBXGeometry(); + for (QHash::const_iterator it = oldGeometry.jointIndices.constBegin(); + it != oldGeometry.jointIndices.constEnd(); it++) { + int oldIndex = it.value() - 1; + int newIndex = newGeometry.getJointIndex(it.key()); + if (newIndex != -1) { + newJointStates[newIndex] = _jointStates.at(oldIndex); + } } + } + deleteGeometry(); + _dilatedTextures.clear(); + _geometry = geometry; + _jointStates = newJointStates; + needToRebuild = true; + } else if (_jointStates.isEmpty()) { + const FBXGeometry& fbxGeometry = geometry->getFBXGeometry(); + if (fbxGeometry.joints.size() > 0) { + _jointStates = createJointStates(fbxGeometry); + needToRebuild = true; } - _boundingRadius = sqrtf(_boundingRadius); - _shapesAreDirty = false; } -} - -void Model::simulate(float deltaTime, bool fullUpdate) { - // update our LOD, then simulate - simulate(deltaTime, fullUpdate, updateGeometry()); + _geometry->setLoadPriority(this, -_lodDistance); + _geometry->ensureLoading(); + + if (needToRebuild) { + const FBXGeometry& fbxGeometry = geometry->getFBXGeometry(); + foreach (const FBXMesh& mesh, fbxGeometry.meshes) { + MeshState state; + state.clusterMatrices.resize(mesh.clusters.size()); + _meshStates.append(state); + + QOpenGLBuffer buffer; + if (!mesh.blendshapes.isEmpty()) { + buffer.setUsagePattern(QOpenGLBuffer::DynamicDraw); + buffer.create(); + buffer.bind(); + buffer.allocate((mesh.vertices.size() + mesh.normals.size()) * sizeof(glm::vec3)); + buffer.write(0, mesh.vertices.constData(), mesh.vertices.size() * sizeof(glm::vec3)); + buffer.write(mesh.vertices.size() * sizeof(glm::vec3), mesh.normals.constData(), + mesh.normals.size() * sizeof(glm::vec3)); + buffer.release(); + } + _blendedVertexBuffers.append(buffer); + } + foreach (const FBXAttachment& attachment, fbxGeometry.attachments) { + Model* model = new Model(this); + model->init(); + model->setURL(attachment.url); + _attachments.append(model); + } + createShapes(); + } + return true; } bool Model::render(float alpha, bool forShadowMap) { @@ -262,15 +324,6 @@ Extents Model::getBindExtents() const { return scaledExtents; } -Extents Model::getStaticExtents() const { - if (!isActive()) { - return Extents(); - } - const Extents& staticExtents = _geometry->getFBXGeometry().staticExtents; - Extents scaledExtents = { staticExtents.minimum * _scale, staticExtents.maximum * _scale }; - return scaledExtents; -} - bool Model::getJointState(int index, glm::quat& rotation) const { if (index == -1 || index >= _jointStates.size()) { return false; @@ -373,6 +426,90 @@ void Model::setURL(const QUrl& url, const QUrl& fallback, bool retainCurrent, bo } } +void Model::clearShapes() { + for (int i = 0; i < _jointShapes.size(); ++i) { + delete _jointShapes[i]; + } + _jointShapes.clear(); +} + +void Model::createShapes() { + clearShapes(); + const FBXGeometry& geometry = _geometry->getFBXGeometry(); + float uniformScale = extractUniformScale(_scale); + glm::quat inverseRotation = glm::inverse(_rotation); + + for (int i = 0; i < _jointStates.size(); i++) { + updateJointState(i); + } + + // joint shapes + Extents totalExtents; + for (int i = 0; i < _jointStates.size(); i++) { + const FBXJoint& joint = geometry.joints[i]; + + glm::vec3 jointToShapeOffset = uniformScale * (_jointStates[i].combinedRotation * joint.shapePosition); + glm::vec3 worldPosition = extractTranslation(_jointStates[i].transform) + jointToShapeOffset + _translation; + Extents shapeExtents; + + float radius = uniformScale * joint.boneRadius; + float halfHeight = 0.5f * uniformScale * joint.distanceToParent; + if (joint.shapeType == Shape::CAPSULE_SHAPE && halfHeight > EPSILON) { + CapsuleShape* capsule = new CapsuleShape(radius, halfHeight); + capsule->setPosition(worldPosition); + capsule->setRotation(_jointStates[i].combinedRotation * joint.shapeRotation); + _jointShapes.push_back(capsule); + + glm::vec3 endPoint; + capsule->getEndPoint(endPoint); + glm::vec3 startPoint; + capsule->getStartPoint(startPoint); + glm::vec3 axis = (halfHeight + radius) * glm::normalize(endPoint - startPoint); + shapeExtents.addPoint(inverseRotation * (worldPosition + axis - _translation)); + shapeExtents.addPoint(inverseRotation * (worldPosition - axis - _translation)); + } else { + SphereShape* sphere = new SphereShape(radius, worldPosition); + _jointShapes.push_back(sphere); + + glm::vec3 axis = glm::vec3(radius); + shapeExtents.addPoint(inverseRotation * (worldPosition + axis - _translation)); + shapeExtents.addPoint(inverseRotation * (worldPosition - axis - _translation)); + } + totalExtents.addExtents(shapeExtents); + } + + // bounding shape + // NOTE: we assume that the longest side of totalExtents is the yAxis + glm::vec3 diagonal = totalExtents.maximum - totalExtents.minimum; + float capsuleRadius = 0.25f * (diagonal.x + diagonal.z); // half the average of x and z + _boundingShape.setRadius(capsuleRadius); + _boundingShape.setHalfHeight(0.5f * diagonal.y - capsuleRadius); + _boundingShapeLocalOffset = 0.5f * (totalExtents.maximum + totalExtents.minimum); +} + +void Model::updateShapePositions() { + if (_shapesAreDirty && _jointShapes.size() == _jointStates.size()) { + _boundingRadius = 0.f; + float uniformScale = extractUniformScale(_scale); + const FBXGeometry& geometry = _geometry->getFBXGeometry(); + for (int i = 0; i < _jointStates.size(); i++) { + const FBXJoint& joint = geometry.joints[i]; + // shape position and rotation need to be in world-frame + glm::vec3 jointToShapeOffset = uniformScale * (_jointStates[i].combinedRotation * joint.shapePosition); + glm::vec3 worldPosition = extractTranslation(_jointStates[i].transform) + jointToShapeOffset + _translation; + _jointShapes[i]->setPosition(worldPosition); + _jointShapes[i]->setRotation(_jointStates[i].combinedRotation * joint.shapeRotation); + float distance2 = glm::distance2(worldPosition, _translation); + if (distance2 > _boundingRadius) { + _boundingRadius = distance2; + } + } + _boundingRadius = sqrtf(_boundingRadius); + _shapesAreDirty = false; + } + _boundingShape.setPosition(_translation + _rotation * _boundingShapeLocalOffset); +} + bool Model::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance) const { const glm::vec3 relativeOrigin = origin - _translation; const FBXGeometry& geometry = _geometry->getFBXGeometry(); @@ -419,7 +556,6 @@ bool Model::findCollisions(const QVector shapes, CollisionList& co bool Model::findSphereCollisions(const glm::vec3& sphereCenter, float sphereRadius, CollisionList& collisions, int skipIndex) { bool collided = false; - updateShapePositions(); SphereShape sphere(sphereRadius, sphereCenter); const FBXGeometry& geometry = _geometry->getFBXGeometry(); for (int i = 0; i < _jointShapes.size(); i++) { @@ -448,45 +584,6 @@ bool Model::findSphereCollisions(const glm::vec3& sphereCenter, float sphereRadi return collided; } -QVector Model::updateGeometry() { - QVector newJointStates; - if (_nextGeometry) { - _nextGeometry = _nextGeometry->getLODOrFallback(_lodDistance, _nextLODHysteresis); - _nextGeometry->setLoadPriority(this, -_lodDistance); - _nextGeometry->ensureLoading(); - if (_nextGeometry->isLoaded()) { - applyNextGeometry(); - return newJointStates; - } - } - if (!_geometry) { - return newJointStates; - } - QSharedPointer geometry = _geometry->getLODOrFallback(_lodDistance, _lodHysteresis); - if (_geometry != geometry) { - if (!_jointStates.isEmpty()) { - // copy the existing joint states - const FBXGeometry& oldGeometry = _geometry->getFBXGeometry(); - const FBXGeometry& newGeometry = geometry->getFBXGeometry(); - newJointStates = createJointStates(newGeometry); - for (QHash::const_iterator it = oldGeometry.jointIndices.constBegin(); - it != oldGeometry.jointIndices.constEnd(); it++) { - int oldIndex = it.value() - 1; - int newIndex = newGeometry.getJointIndex(it.key()); - if (newIndex != -1) { - newJointStates[newIndex] = _jointStates.at(oldIndex); - } - } - } - deleteGeometry(); - _dilatedTextures.clear(); - _geometry = geometry; - } - _geometry->setLoadPriority(this, -_lodDistance); - _geometry->ensureLoading(); - return newJointStates; -} - class Blender : public QRunnable { public: @@ -549,53 +646,23 @@ void Blender::run() { Q_ARG(const QVector&, vertices), Q_ARG(const QVector&, normals)); } -void Model::simulate(float deltaTime, bool fullUpdate, const QVector& newJointStates) { - if (!isActive()) { + +void Model::simulate(float deltaTime) { + bool geometryIsUpToDate = updateGeometry(); + if (!geometryIsUpToDate) { return; } - - // set up world vertices on first simulate after load - const FBXGeometry& geometry = _geometry->getFBXGeometry(); - if (_jointStates.isEmpty()) { - _jointStates = newJointStates.isEmpty() ? createJointStates(geometry) : newJointStates; - foreach (const FBXMesh& mesh, geometry.meshes) { - MeshState state; - state.clusterMatrices.resize(mesh.clusters.size()); - _meshStates.append(state); - - QOpenGLBuffer buffer; - if (!mesh.blendshapes.isEmpty()) { - buffer.setUsagePattern(QOpenGLBuffer::DynamicDraw); - buffer.create(); - buffer.bind(); - buffer.allocate((mesh.vertices.size() + mesh.normals.size()) * sizeof(glm::vec3)); - buffer.write(0, mesh.vertices.constData(), mesh.vertices.size() * sizeof(glm::vec3)); - buffer.write(mesh.vertices.size() * sizeof(glm::vec3), mesh.normals.constData(), - mesh.normals.size() * sizeof(glm::vec3)); - buffer.release(); - } - _blendedVertexBuffers.append(buffer); - } - foreach (const FBXAttachment& attachment, geometry.attachments) { - Model* model = new Model(this); - model->init(); - model->setURL(attachment.url); - _attachments.append(model); - } - fullUpdate = true; - createJointCollisionShapes(); - } - - // exit early if we don't have to perform a full update - if (!fullUpdate) { - return; - } - + simulateInternal(deltaTime); +} + +void Model::simulateInternal(float deltaTime) { // update the world space transforms for all joints for (int i = 0; i < _jointStates.size(); i++) { updateJointState(i); } + const FBXGeometry& geometry = _geometry->getFBXGeometry(); + // update the attachment transforms and simulate them for (int i = 0; i < _attachments.size(); i++) { const FBXAttachment& attachment = geometry.attachments.at(i); @@ -641,7 +708,7 @@ void Model::updateJointState(int index) { state.transform = baseTransform * geometry.offset * glm::translate(state.translation) * joint.preTransform * glm::mat4_cast(combinedRotation) * joint.postTransform; state.combinedRotation = _rotation * combinedRotation; - + } else { const JointState& parentState = _jointStates.at(joint.parentIndex); if (index == geometry.leanJointIndex) { @@ -825,11 +892,11 @@ void Model::applyRotationDelta(int jointIndex, const glm::quat& delta, bool cons state.rotation = newRotation; } -void Model::renderCollisionProxies(float alpha) { +const int BALL_SUBDIVISIONS = 10; + +void Model::renderJointCollisionShapes(float alpha) { glPushMatrix(); Application::getInstance()->loadTranslatedViewMatrix(_translation); - updateShapePositions(); - const int BALL_SUBDIVISIONS = 10; for (int i = 0; i < _jointShapes.size(); i++) { glPushMatrix(); @@ -876,6 +943,36 @@ void Model::renderCollisionProxies(float alpha) { glPopMatrix(); } +void Model::renderBoundingCollisionShapes(float alpha) { + glPushMatrix(); + + Application::getInstance()->loadTranslatedViewMatrix(_translation); + + // draw a blue sphere at the capsule endpoint + glm::vec3 endPoint; + _boundingShape.getEndPoint(endPoint); + endPoint = endPoint - _translation; + glTranslatef(endPoint.x, endPoint.y, endPoint.z); + glColor4f(0.6f, 0.6f, 0.8f, alpha); + glutSolidSphere(_boundingShape.getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + + // draw a yellow sphere at the capsule startpoint + glm::vec3 startPoint; + _boundingShape.getStartPoint(startPoint); + startPoint = startPoint - _translation; + glm::vec3 axis = endPoint - startPoint; + glTranslatef(-axis.x, -axis.y, -axis.z); + glColor4f(0.8f, 0.8f, 0.6f, alpha); + glutSolidSphere(_boundingShape.getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + + // draw a green cylinder between the two points + glm::vec3 origin(0.f); + glColor4f(0.6f, 0.8f, 0.6f, alpha); + Avatar::renderJointConnectingCone( origin, axis, _boundingShape.getRadius(), _boundingShape.getRadius()); + + glPopMatrix(); +} + bool Model::collisionHitsMoveableJoint(CollisionInfo& collision) const { if (collision._type == MODEL_COLLISION) { // the joint is pokable by a collision if it exists and is free to move diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index 0b05fab2bf..205687baa9 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -12,6 +12,8 @@ #include #include +#include + #include "GeometryCache.h" #include "InterfaceConfig.h" #include "ProgramObject.h" @@ -54,13 +56,9 @@ public: void init(); void reset(); - void clearShapes(); - void createJointCollisionShapes(); - void createBoundingShape(); - void updateShapePositions(); - void simulate(float deltaTime, bool fullUpdate = true); + void simulate(float deltaTime); bool render(float alpha = 1.0f, bool forShadowMap = false); - + /// Sets the URL of the model to render. /// \param fallback the URL of a fallback model to render if the requested model fails to load /// \param retainCurrent if true, keep rendering the current model until the new one is loaded @@ -76,9 +74,6 @@ public: /// Returns the extents of the model in its bind pose. Extents getBindExtents() const; - /// Returns the extents of the unmovable joints of the model. - Extents getStaticExtents() const; - /// Returns a reference to the shared geometry. const QSharedPointer& getGeometry() const { return _geometry; } @@ -160,6 +155,12 @@ public: /// Returns the extended length from the right hand to its first free ancestor. float getRightArmLength() const; + void clearShapes(); + void createShapes(); + void updateShapePositions(); + void renderJointCollisionShapes(float alpha); + void renderBoundingCollisionShapes(float alpha); + bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance) const; /// \param shapes list of pointers shapes to test against Model @@ -170,8 +171,6 @@ public: bool findSphereCollisions(const glm::vec3& penetratorCenter, float penetratorRadius, CollisionList& collisions, int skipIndex = -1); - void renderCollisionProxies(float alpha); - /// \param collision details about the collisions /// \return true if the collision is against a moveable joint bool collisionHitsMoveableJoint(CollisionInfo& collision) const; @@ -206,6 +205,10 @@ protected: QVector _jointStates; QVector _jointShapes; + float _boundingRadius; + CapsuleShape _boundingShape; + glm::vec3 _boundingShapeLocalOffset; + class MeshState { public: QVector clusterMatrices; @@ -213,8 +216,8 @@ protected: QVector _meshStates; - QVector updateGeometry(); - void simulate(float deltaTime, bool fullUpdate, const QVector& newJointStates); + bool updateGeometry(); + void simulateInternal(float deltaTime); /// Updates the state of the joint at the specified index. virtual void updateJointState(int index); @@ -249,6 +252,7 @@ private: void applyNextGeometry(); void deleteGeometry(); void renderMeshes(float alpha, bool forShadowMap, bool translucent); + QVector createJointStates(const FBXGeometry& geometry); QSharedPointer _baseGeometry; ///< reference required to prevent collection of base QSharedPointer _nextBaseGeometry; @@ -268,8 +272,6 @@ private: QVector _attachments; - float _boundingRadius; - static ProgramObject _program; static ProgramObject _normalMapProgram; static ProgramObject _shadowProgram; @@ -292,7 +294,6 @@ private: static SkinLocations _skinShadowLocations; static void initSkinProgram(ProgramObject& program, SkinLocations& locations); - static QVector createJointStates(const FBXGeometry& geometry); }; Q_DECLARE_METATYPE(QPointer) From 20d944a43b8ce7101db602589f8c15b0fdc0eee3 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 09:31:40 -0700 Subject: [PATCH 063/595] removed some debug --- assignment-client/src/octree/OctreeServer.cpp | 30 ++----------------- 1 file changed, 3 insertions(+), 27 deletions(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 567e91157d..06b3e6eeeb 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -826,34 +826,15 @@ void OctreeServer::readPendingDatagrams() { SharedNodePointer matchingNode = nodeList->sendingNodeForPacket(receivedPacket); if (packetType == getMyQueryMessageType()) { - bool debug = false; - if (debug) { - if (matchingNode) { - qDebug() << "Got PacketTypeVoxelQuery at" << usecTimestampNow() << "node:" << *matchingNode; - } else { - qDebug() << "Got PacketTypeVoxelQuery at" << usecTimestampNow() << "node: ??????"; - } - } - // If we got a PacketType_VOXEL_QUERY, then we're talking to an NodeType_t_AVATAR, and we // need to make sure we have it in our nodeList. if (matchingNode) { - if (debug) { - qDebug() << "calling updateNodeWithDataFromPacket()... node:" << *matchingNode; - } nodeList->updateNodeWithDataFromPacket(matchingNode, receivedPacket); OctreeQueryNode* nodeData = (OctreeQueryNode*) matchingNode->getLinkedData(); if (nodeData && !nodeData->isOctreeSendThreadInitalized()) { - if (debug) { - qDebug() << "calling initializeOctreeSendThread()... node:" << *matchingNode; - } - - - qDebug() << "OctreeServer::readPendingDatagrams()... BEFORE nodeData->initializeOctreeSendThread()"; SharedAssignmentPointer sharedAssignment = AssignmentClient::getCurrentAssignment(); nodeData->initializeOctreeSendThread(sharedAssignment, matchingNode); - qDebug() << "OctreeServer::readPendingDatagrams()... AFTER nodeData->initializeOctreeSendThread()"; } } } else if (packetType == PacketTypeJurisdictionRequest) { @@ -1062,16 +1043,14 @@ void OctreeServer::nodeKilled(SharedNodePointer node) { qDebug() << qPrintable(_safeServerName) << "server killed node:" << *node; OctreeQueryNode* nodeData = static_cast(node->getLinkedData()); if (nodeData) { - qDebug() << qPrintable(_safeServerName) << "server calling nodeData->nodeKilled() for node:" << *node; nodeData->nodeKilled(); // tell our node data and sending threads that we'd like to shut down - qDebug() << qPrintable(_safeServerName) << "server AFTER nodeData->nodeKilled() for node:" << *node; } else { qDebug() << qPrintable(_safeServerName) << "server node missing linked data node:" << *node; } quint64 end = usecTimestampNow(); quint64 usecsElapsed = (end - start); - qDebug() << qPrintable(_safeServerName) << "server killed took: " << usecsElapsed << " usecs for node:" << *node; + qDebug() << qPrintable(_safeServerName) << "server nodeKilled() took: " << usecsElapsed << " usecs for node:" << *node; } void OctreeServer::forceNodeShutdown(SharedNodePointer node) { @@ -1080,16 +1059,15 @@ void OctreeServer::forceNodeShutdown(SharedNodePointer node) { qDebug() << qPrintable(_safeServerName) << "server killed node:" << *node; OctreeQueryNode* nodeData = static_cast(node->getLinkedData()); if (nodeData) { - qDebug() << qPrintable(_safeServerName) << "server calling nodeData->forceNodeShutdown() for node:" << *node; nodeData->forceNodeShutdown(); // tell our node data and sending threads that we'd like to shut down - qDebug() << qPrintable(_safeServerName) << "server AFTER nodeData->forceNodeShutdown() for node:" << *node; } else { qDebug() << qPrintable(_safeServerName) << "server node missing linked data node:" << *node; } quint64 end = usecTimestampNow(); quint64 usecsElapsed = (end - start); - qDebug() << qPrintable(_safeServerName) << "server killed took: " << usecsElapsed << " usecs for node:" << *node; + qDebug() << qPrintable(_safeServerName) << "server forceNodeShutdown() took: " + << usecsElapsed << " usecs for node:" << *node; } @@ -1097,10 +1075,8 @@ void OctreeServer::aboutToFinish() { qDebug() << qPrintable(_safeServerName) << "server STARTING about to finish..."; foreach (const SharedNodePointer& node, NodeList::getInstance()->getNodeHash()) { qDebug() << qPrintable(_safeServerName) << "server about to finish while node still connected node:" << *node; - forceNodeShutdown(node); } - qDebug() << qPrintable(_safeServerName) << "server ENDING about to finish..."; } From 21e0bc119b414efd0e956e0ac478e37ecc28a171 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 09:50:10 -0700 Subject: [PATCH 064/595] moved OctreeServer::stopTrackingThread() to destructor instead of setIsShuttingDown() --- assignment-client/src/octree/OctreeSendThread.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index 48d45bbb55..70d6033e3e 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -48,13 +48,14 @@ OctreeSendThread::~OctreeSendThread() { "- ending sending thread [" << this << "]"; OctreeServer::clientDisconnected(); + OctreeServer::stopTrackingThread(this); + _node.clear(); _myAssignment.clear(); } void OctreeSendThread::setIsShuttingDown() { _isShuttingDown = true; - OctreeServer::stopTrackingThread(this); } From ff17c6a0717c6af6eca712efa965d69d7b1c88df Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 10:08:46 -0700 Subject: [PATCH 065/595] quiet some debugging --- assignment-client/src/octree/OctreeServer.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 06b3e6eeeb..bc823983e0 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -1040,17 +1040,20 @@ void OctreeServer::nodeAdded(SharedNodePointer node) { void OctreeServer::nodeKilled(SharedNodePointer node) { quint64 start = usecTimestampNow(); - qDebug() << qPrintable(_safeServerName) << "server killed node:" << *node; + //qDebug() << qPrintable(_safeServerName) << "server killed node:" << *node; OctreeQueryNode* nodeData = static_cast(node->getLinkedData()); if (nodeData) { nodeData->nodeKilled(); // tell our node data and sending threads that we'd like to shut down } else { - qDebug() << qPrintable(_safeServerName) << "server node missing linked data node:" << *node; + //qDebug() << qPrintable(_safeServerName) << "server node missing linked data node:" << *node; } quint64 end = usecTimestampNow(); quint64 usecsElapsed = (end - start); - qDebug() << qPrintable(_safeServerName) << "server nodeKilled() took: " << usecsElapsed << " usecs for node:" << *node; + if (usecsElapsed > 1000) { + qDebug() << qPrintable(_safeServerName) << "server nodeKilled() took: " << usecsElapsed << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"; + // << " usecs for node:" << *node; + } } void OctreeServer::forceNodeShutdown(SharedNodePointer node) { From 64c7a6a4400f142166076dbe901c84c5f403237e Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 10:25:32 -0700 Subject: [PATCH 066/595] testing, remove create sending thread and processing of query --- assignment-client/src/octree/OctreeServer.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index bc823983e0..2a1db54924 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -826,6 +826,8 @@ void OctreeServer::readPendingDatagrams() { SharedNodePointer matchingNode = nodeList->sendingNodeForPacket(receivedPacket); if (packetType == getMyQueryMessageType()) { + + /** // If we got a PacketType_VOXEL_QUERY, then we're talking to an NodeType_t_AVATAR, and we // need to make sure we have it in our nodeList. if (matchingNode) { @@ -837,6 +839,7 @@ void OctreeServer::readPendingDatagrams() { nodeData->initializeOctreeSendThread(sharedAssignment, matchingNode); } } + **/ } else if (packetType == PacketTypeJurisdictionRequest) { _jurisdictionSender->queueReceivedPacket(matchingNode, receivedPacket); } else if (_octreeInboundPacketProcessor && getOctree()->handlesEditPacketType(packetType)) { @@ -1034,7 +1037,7 @@ void OctreeServer::run() { void OctreeServer::nodeAdded(SharedNodePointer node) { // we might choose to use this notifier to track clients in a pending state - qDebug() << qPrintable(_safeServerName) << "server added node:" << *node; + //qDebug() << qPrintable(_safeServerName) << "server added node:" << *node; } void OctreeServer::nodeKilled(SharedNodePointer node) { From ce8a599b16cd43d041a152d10495a68e890b8ec4 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 10:38:21 -0700 Subject: [PATCH 067/595] tweak --- assignment-client/src/octree/OctreeServer.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 2a1db54924..2267f99201 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -827,7 +827,6 @@ void OctreeServer::readPendingDatagrams() { if (packetType == getMyQueryMessageType()) { - /** // If we got a PacketType_VOXEL_QUERY, then we're talking to an NodeType_t_AVATAR, and we // need to make sure we have it in our nodeList. if (matchingNode) { @@ -835,11 +834,12 @@ void OctreeServer::readPendingDatagrams() { OctreeQueryNode* nodeData = (OctreeQueryNode*) matchingNode->getLinkedData(); if (nodeData && !nodeData->isOctreeSendThreadInitalized()) { + /** SharedAssignmentPointer sharedAssignment = AssignmentClient::getCurrentAssignment(); nodeData->initializeOctreeSendThread(sharedAssignment, matchingNode); + **/ } } - **/ } else if (packetType == PacketTypeJurisdictionRequest) { _jurisdictionSender->queueReceivedPacket(matchingNode, receivedPacket); } else if (_octreeInboundPacketProcessor && getOctree()->handlesEditPacketType(packetType)) { From 03d04e194d2ceff66e79322c3cba0035c557c3e2 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 1 Apr 2014 10:39:58 -0700 Subject: [PATCH 068/595] Init bounding Extents for more correct shapes --- interface/src/renderer/Model.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 8251b67b1e..91b69d052c 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -445,12 +445,14 @@ void Model::createShapes() { // joint shapes Extents totalExtents; + totalExtents.reset(); for (int i = 0; i < _jointStates.size(); i++) { const FBXJoint& joint = geometry.joints[i]; glm::vec3 jointToShapeOffset = uniformScale * (_jointStates[i].combinedRotation * joint.shapePosition); glm::vec3 worldPosition = extractTranslation(_jointStates[i].transform) + jointToShapeOffset + _translation; Extents shapeExtents; + shapeExtents.reset(); float radius = uniformScale * joint.boneRadius; float halfHeight = 0.5f * uniformScale * joint.distanceToParent; From 9d757434ab9c7a719c22d120f726a870be956041 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 10:47:25 -0700 Subject: [PATCH 069/595] testing tweak --- assignment-client/src/octree/OctreeSendThread.cpp | 2 ++ assignment-client/src/octree/OctreeServer.cpp | 2 -- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index 70d6033e3e..ca7e835b8a 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -81,8 +81,10 @@ bool OctreeSendThread::process() { // Sometimes the node data has not yet been linked, in which case we can't really do anything if (nodeData && !nodeData->isShuttingDown()) { + /* bool viewFrustumChanged = nodeData->updateCurrentViewFrustum(); packetDistributor(nodeData, viewFrustumChanged); + */ } } } diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 2267f99201..b0a9a9b4de 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -834,10 +834,8 @@ void OctreeServer::readPendingDatagrams() { OctreeQueryNode* nodeData = (OctreeQueryNode*) matchingNode->getLinkedData(); if (nodeData && !nodeData->isOctreeSendThreadInitalized()) { - /** SharedAssignmentPointer sharedAssignment = AssignmentClient::getCurrentAssignment(); nodeData->initializeOctreeSendThread(sharedAssignment, matchingNode); - **/ } } } else if (packetType == PacketTypeJurisdictionRequest) { From 193e2372855b0baa2043ca8904d2b12c06ecf2ca Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 10:58:20 -0700 Subject: [PATCH 070/595] tweaks --- assignment-client/src/octree/OctreeSendThread.cpp | 2 -- assignment-client/src/octree/OctreeServer.cpp | 7 +++++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index ca7e835b8a..70d6033e3e 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -81,10 +81,8 @@ bool OctreeSendThread::process() { // Sometimes the node data has not yet been linked, in which case we can't really do anything if (nodeData && !nodeData->isShuttingDown()) { - /* bool viewFrustumChanged = nodeData->updateCurrentViewFrustum(); packetDistributor(nodeData, viewFrustumChanged); - */ } } } diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index b0a9a9b4de..03f40c5b7b 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -1184,6 +1184,11 @@ QString OctreeServer::getStatusLink() { } void OctreeServer::sendStatsPacket() { + + static QJsonObject statsObject1; + ThreadedAssignment::addPacketStatsAndSendStatsPacket(statsObject1); + + /** // TODO: we have too many stats to fit in a single MTU... so for now, we break it into multiple JSON objects and // send them separately. What we really should do is change the NodeList::sendStatsToDomainServer() to handle the // the following features: @@ -1257,6 +1262,8 @@ void OctreeServer::sendStatsPacket() { (double)_octreeInboundPacketProcessor->getAverageLockWaitTimePerElement(); NodeList::getInstance()->sendStatsToDomainServer(statsObject3); + + **/ } QMap OctreeServer::_threadsDidProcess; From 9e445098f1ab696daabea04e57413acbfb3aa623 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 11:22:44 -0700 Subject: [PATCH 071/595] more debugging --- assignment-client/src/octree/OctreeServer.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 03f40c5b7b..259d9be954 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -813,7 +813,13 @@ void OctreeServer::parsePayload() { } } +quint64 lastReadPendingDatagrams = usecTimestampNow(); +quint64 lastProcessNodeData = usecTimestampNow(); + void OctreeServer::readPendingDatagrams() { + quint64 now = usecTimestampNow(); + qDebug() << "OctreeServer::readPendingDatagrams(): since lastReadPendingDatagrams=" << (now - lastReadPendingDatagrams) << "usecs"; + QByteArray receivedPacket; HifiSockAddr senderSockAddr; @@ -843,6 +849,9 @@ void OctreeServer::readPendingDatagrams() { } else if (_octreeInboundPacketProcessor && getOctree()->handlesEditPacketType(packetType)) { _octreeInboundPacketProcessor->queueReceivedPacket(matchingNode, receivedPacket); } else { + quint64 now = usecTimestampNow(); + qDebug() << "OctreeServer::readPendingDatagrams(): since lastProcessNodeData=" << (now - lastProcessNodeData) << "usecs"; + // let processNodeData handle it. NodeList::getInstance()->processNodeData(senderSockAddr, receivedPacket); } From 1aa05c4de5526ba3d9efda890b17287b254d17e5 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 11:26:55 -0700 Subject: [PATCH 072/595] more debugging --- assignment-client/src/octree/OctreeServer.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 259d9be954..332ab28807 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -819,6 +819,7 @@ quint64 lastProcessNodeData = usecTimestampNow(); void OctreeServer::readPendingDatagrams() { quint64 now = usecTimestampNow(); qDebug() << "OctreeServer::readPendingDatagrams(): since lastReadPendingDatagrams=" << (now - lastReadPendingDatagrams) << "usecs"; + lastReadPendingDatagrams = now; QByteArray receivedPacket; HifiSockAddr senderSockAddr; @@ -851,6 +852,7 @@ void OctreeServer::readPendingDatagrams() { } else { quint64 now = usecTimestampNow(); qDebug() << "OctreeServer::readPendingDatagrams(): since lastProcessNodeData=" << (now - lastProcessNodeData) << "usecs"; + lastProcessNodeData = now; // let processNodeData handle it. NodeList::getInstance()->processNodeData(senderSockAddr, receivedPacket); From 30ff4a1d19833f01088c3a3e276d6ca6cffde834 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 11:32:35 -0700 Subject: [PATCH 073/595] more debugging --- assignment-client/src/octree/OctreeServer.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 332ab28807..e598310470 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -818,7 +818,9 @@ quint64 lastProcessNodeData = usecTimestampNow(); void OctreeServer::readPendingDatagrams() { quint64 now = usecTimestampNow(); - qDebug() << "OctreeServer::readPendingDatagrams(): since lastReadPendingDatagrams=" << (now - lastReadPendingDatagrams) << "usecs"; + if ((now - lastReadPendingDatagrams) > 100000) { + qDebug() << "OctreeServer::readPendingDatagrams(): since lastReadPendingDatagrams=" << (now - lastReadPendingDatagrams) << "usecs"; + } lastReadPendingDatagrams = now; QByteArray receivedPacket; From 9f9127b7165f0535fe63ad816bf94512a3f10cb9 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 1 Apr 2014 11:39:24 -0700 Subject: [PATCH 074/595] draw head bounding shape first --- interface/src/avatar/Avatar.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index b36baf15b1..490daf4cab 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -217,10 +217,10 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode) { getHead()->getFaceModel().renderJointCollisionShapes(0.7f); } if (Menu::getInstance()->isOptionChecked(MenuOption::RenderBoundingCollisionShapes)) { - _skeletonModel.updateShapePositions(); - _skeletonModel.renderBoundingCollisionShapes(0.7f); getHead()->getFaceModel().updateShapePositions(); getHead()->getFaceModel().renderBoundingCollisionShapes(0.7f); + _skeletonModel.updateShapePositions(); + _skeletonModel.renderBoundingCollisionShapes(0.7f); } // quick check before falling into the code below: From 3d43956c111998eab97abb3731e195e9aa7ea86d Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 1 Apr 2014 11:39:40 -0700 Subject: [PATCH 075/595] bounding shape relative to model's root Joint --- interface/src/renderer/Model.cpp | 33 +++++++++++++++++++++++--------- interface/src/renderer/Model.h | 2 +- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 91b69d052c..3a12d76626 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -435,13 +435,20 @@ void Model::clearShapes() { void Model::createShapes() { clearShapes(); - const FBXGeometry& geometry = _geometry->getFBXGeometry(); - float uniformScale = extractUniformScale(_scale); - glm::quat inverseRotation = glm::inverse(_rotation); + if (_jointStates.isEmpty()) { + return; + } + + // make sure all the joints are updated correctly before we try to create their shapes for (int i = 0; i < _jointStates.size(); i++) { updateJointState(i); } + + const FBXGeometry& geometry = _geometry->getFBXGeometry(); + float uniformScale = extractUniformScale(_scale); + glm::quat inverseRotation = glm::inverse(_rotation); + glm::vec3 rootPosition(0.f); // joint shapes Extents totalExtents; @@ -454,6 +461,10 @@ void Model::createShapes() { Extents shapeExtents; shapeExtents.reset(); + if (joint.parentIndex == -1) { + rootPosition = worldPosition; + } + float radius = uniformScale * joint.boneRadius; float halfHeight = 0.5f * uniformScale * joint.distanceToParent; if (joint.shapeType == Shape::CAPSULE_SHAPE && halfHeight > EPSILON) { @@ -467,15 +478,15 @@ void Model::createShapes() { glm::vec3 startPoint; capsule->getStartPoint(startPoint); glm::vec3 axis = (halfHeight + radius) * glm::normalize(endPoint - startPoint); - shapeExtents.addPoint(inverseRotation * (worldPosition + axis - _translation)); - shapeExtents.addPoint(inverseRotation * (worldPosition - axis - _translation)); + shapeExtents.addPoint(worldPosition + axis); + shapeExtents.addPoint(worldPosition - axis); } else { SphereShape* sphere = new SphereShape(radius, worldPosition); _jointShapes.push_back(sphere); glm::vec3 axis = glm::vec3(radius); - shapeExtents.addPoint(inverseRotation * (worldPosition + axis - _translation)); - shapeExtents.addPoint(inverseRotation * (worldPosition - axis - _translation)); + shapeExtents.addPoint(worldPosition + axis); + shapeExtents.addPoint(worldPosition - axis); } totalExtents.addExtents(shapeExtents); } @@ -486,11 +497,12 @@ void Model::createShapes() { float capsuleRadius = 0.25f * (diagonal.x + diagonal.z); // half the average of x and z _boundingShape.setRadius(capsuleRadius); _boundingShape.setHalfHeight(0.5f * diagonal.y - capsuleRadius); - _boundingShapeLocalOffset = 0.5f * (totalExtents.maximum + totalExtents.minimum); + _boundingShapeLocalOffset = inverseRotation * (0.5f * (totalExtents.maximum + totalExtents.minimum) - rootPosition); } void Model::updateShapePositions() { if (_shapesAreDirty && _jointShapes.size() == _jointStates.size()) { + glm::vec3 rootPosition(0.f); _boundingRadius = 0.f; float uniformScale = extractUniformScale(_scale); const FBXGeometry& geometry = _geometry->getFBXGeometry(); @@ -505,11 +517,14 @@ void Model::updateShapePositions() { if (distance2 > _boundingRadius) { _boundingRadius = distance2; } + if (joint.parentIndex == -1) { + rootPosition = worldPosition; + } } _boundingRadius = sqrtf(_boundingRadius); _shapesAreDirty = false; + _boundingShape.setPosition(rootPosition + _rotation * _boundingShapeLocalOffset); } - _boundingShape.setPosition(_translation + _rotation * _boundingShapeLocalOffset); } bool Model::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance) const { diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index 205687baa9..43eb7fda67 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -56,7 +56,7 @@ public: void init(); void reset(); - void simulate(float deltaTime); + virtual void simulate(float deltaTime); bool render(float alpha = 1.0f, bool forShadowMap = false); /// Sets the URL of the model to render. From 58a52cf5e18baeb431d969d8c92514ee4a98163a Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 11:45:29 -0700 Subject: [PATCH 076/595] more debugging --- assignment-client/src/octree/OctreeServer.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index e598310470..b46331e39d 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -832,14 +832,24 @@ void OctreeServer::readPendingDatagrams() { if (nodeList->packetVersionAndHashMatch(receivedPacket)) { PacketType packetType = packetTypeForPacket(receivedPacket); + quint64 startNodeLookup = usecTimestampNow(); SharedNodePointer matchingNode = nodeList->sendingNodeForPacket(receivedPacket); + quint64 endNodeLookup = usecTimestampNow(); + if ((endNodeLookup - startNodeLookup) > 100000) { + qDebug() << "OctreeServer::readPendingDatagrams(): sendingNodeForPacket() took" << (endNodeLookup - startNodeLookup) << "usecs"; + } if (packetType == getMyQueryMessageType()) { // If we got a PacketType_VOXEL_QUERY, then we're talking to an NodeType_t_AVATAR, and we // need to make sure we have it in our nodeList. if (matchingNode) { + quint64 startUpdateNode = usecTimestampNow(); nodeList->updateNodeWithDataFromPacket(matchingNode, receivedPacket); + quint64 endUpdateNode = usecTimestampNow(); + if ((endUpdateNode - startUpdateNode) > 100000) { + qDebug() << "OctreeServer::readPendingDatagrams(): updateNodeWithDataFromPacket() took" << (endUpdateNode - startUpdateNode) << "usecs"; + } OctreeQueryNode* nodeData = (OctreeQueryNode*) matchingNode->getLinkedData(); if (nodeData && !nodeData->isOctreeSendThreadInitalized()) { @@ -857,7 +867,12 @@ void OctreeServer::readPendingDatagrams() { lastProcessNodeData = now; // let processNodeData handle it. + quint64 startProcessNodeData = usecTimestampNow(); NodeList::getInstance()->processNodeData(senderSockAddr, receivedPacket); + quint64 endProcessNodeData = usecTimestampNow(); + if ((endProcessNodeData - startProcessNodeData) > 100000) { + qDebug() << "OctreeServer::readPendingDatagrams(): processNodeData() took" << (endProcessNodeData - startProcessNodeData) << "usecs"; + } } } } From f5045696555c64c538101ecff4503400e4da855e Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 11:49:49 -0700 Subject: [PATCH 077/595] more debugging --- assignment-client/src/octree/OctreeServer.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index b46331e39d..d38a654219 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -863,7 +863,9 @@ void OctreeServer::readPendingDatagrams() { _octreeInboundPacketProcessor->queueReceivedPacket(matchingNode, receivedPacket); } else { quint64 now = usecTimestampNow(); - qDebug() << "OctreeServer::readPendingDatagrams(): since lastProcessNodeData=" << (now - lastProcessNodeData) << "usecs"; + if ((now - lastProcessNodeData) > 500000) { + qDebug() << "OctreeServer::readPendingDatagrams(): since lastProcessNodeData=" << (now - lastProcessNodeData) << "usecs"; + } lastProcessNodeData = now; // let processNodeData handle it. From 03958f2fa07d0ab8346790630b51c30d257a4f5a Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 1 Apr 2014 12:02:47 -0700 Subject: [PATCH 078/595] work on metadata in the model browser + real time updates --- interface/src/Menu.cpp | 23 +- interface/src/ui/ModelBrowser.cpp | 150 ------------ interface/src/ui/ModelBrowser.h | 62 ----- interface/src/ui/ModelsBrowser.cpp | 305 ++++++++++++++++++++++++ interface/src/ui/ModelsBrowser.h | 79 ++++++ libraries/shared/src/FileDownloader.cpp | 54 ++--- libraries/shared/src/FileDownloader.h | 13 +- 7 files changed, 421 insertions(+), 265 deletions(-) delete mode 100644 interface/src/ui/ModelBrowser.cpp delete mode 100644 interface/src/ui/ModelBrowser.h create mode 100644 interface/src/ui/ModelsBrowser.cpp create mode 100644 interface/src/ui/ModelsBrowser.h diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 79b0a23ce5..3e097008c9 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -29,7 +29,6 @@ #include #include #include -#include #include "Application.h" #include "Menu.h" @@ -37,7 +36,7 @@ #include "Util.h" #include "ui/InfoView.h" #include "ui/MetavoxelEditor.h" -#include "ui/ModelBrowser.h" +#include "ui/ModelsBrowser.h" Menu* Menu::_instance = NULL; @@ -714,8 +713,8 @@ void Menu::loginForCurrentDomain() { void Menu::editPreferences() { Application* applicationInstance = Application::getInstance(); - ModelBrowser headBrowser(Head); - ModelBrowser skeletonBrowser(Skeleton); + ModelsBrowser headBrowser(Head); + ModelsBrowser skeletonBrowser(Skeleton); const QString BROWSE_BUTTON_TEXT = "Browse"; @@ -816,15 +815,23 @@ void Menu::editPreferences() { if (ret == QDialog::Accepted) { bool shouldDispatchIdentityPacket = false; - if (headURLEdit.text() != faceURLString && !headURLEdit.text().isEmpty()) { + if (headURLEdit.text() != faceURLString) { // change the faceModelURL in the profile, it will also update this user's BlendFace - applicationInstance->getAvatar()->setFaceModelURL(QUrl(headURLEdit.text())); + if (headURLEdit.text().isEmpty()) { + applicationInstance->getAvatar()->setFaceModelURL(QUrl(headURLEdit.placeholderText())); + } else { + applicationInstance->getAvatar()->setFaceModelURL(QUrl(headURLEdit.text())); + } shouldDispatchIdentityPacket = true; } - if (skeletonURLEdit.text() != skeletonURLString && !skeletonURLEdit.text().isEmpty()) { + if (skeletonURLEdit.text() != skeletonURLString) { // change the skeletonModelURL in the profile, it will also update this user's Body - applicationInstance->getAvatar()->setSkeletonModelURL(QUrl(skeletonURLEdit.text())); + if (skeletonURLEdit.text().isEmpty()) { + applicationInstance->getAvatar()->setSkeletonModelURL(QUrl(skeletonURLEdit.placeholderText())); + } else { + applicationInstance->getAvatar()->setSkeletonModelURL(QUrl(skeletonURLEdit.text())); + } shouldDispatchIdentityPacket = true; } diff --git a/interface/src/ui/ModelBrowser.cpp b/interface/src/ui/ModelBrowser.cpp deleted file mode 100644 index e03081273f..0000000000 --- a/interface/src/ui/ModelBrowser.cpp +++ /dev/null @@ -1,150 +0,0 @@ -// -// ModelBrowser.cpp -// hifi -// -// Created by Clement on 3/17/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. -// - -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "ModelBrowser.h" - -static const QString PREFIX_PARAMETER_NAME = "prefix"; -static const QString MARKER_PARAMETER_NAME = "marker"; -static const QString IS_TRUNCATED_NAME = "IsTruncated"; -static const QString CONTAINER_NAME = "Contents"; -static const QString KEY_NAME = "Key"; - -ModelBrowser::ModelBrowser(ModelType modelType, QWidget* parent) : QWidget(parent), _type(modelType) { - QUrl url(S3_URL); - QUrlQuery query; - - if (_type == Head) { - query.addQueryItem(PREFIX_PARAMETER_NAME, HEAD_MODELS_LOCATION); - } else if (_type == Skeleton) { - query.addQueryItem(PREFIX_PARAMETER_NAME, SKELETON_MODELS_LOCATION); - } - url.setQuery(query); - - _downloader = new FileDownloader(url); - connect(_downloader, SIGNAL(done(QNetworkReply::NetworkError)), SLOT(downloadFinished())); -} - -ModelBrowser::~ModelBrowser() { - delete _downloader; -} - -void ModelBrowser::downloadFinished() { - parseXML(_downloader->getData()); -} - -void ModelBrowser::browse() { - QDialog dialog(this); - dialog.setWindowTitle("Browse models"); - - QGridLayout* layout = new QGridLayout(&dialog); - dialog.setLayout(layout); - - QLineEdit* searchBar = new QLineEdit(&dialog); - layout->addWidget(searchBar, 0, 0); - - ListView* listView = new ListView(&dialog); - listView->setEditTriggers(QAbstractItemView::NoEditTriggers); - layout->addWidget(listView, 1, 0); - listView->connect(searchBar, SIGNAL(textChanged(const QString&)), SLOT(keyboardSearch(const QString&))); - dialog.connect(listView, SIGNAL(doubleClicked(const QModelIndex&)), SLOT(accept())); - - QStringListModel* model = new QStringListModel(_models.keys(), listView); - model->sort(0); - listView->setModel(model); - - QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - layout->addWidget(buttons, 2, 0); - dialog.connect(buttons, SIGNAL(accepted()), SLOT(accept())); - dialog.connect(buttons, SIGNAL(rejected()), SLOT(reject())); - - if (dialog.exec() == QDialog::Rejected) { - return; - } - - QString selectedKey = model->data(listView->currentIndex(), Qt::DisplayRole).toString(); - - emit selected(_models[selectedKey]); -} - -bool ModelBrowser::parseXML(QByteArray xmlFile) { - QXmlStreamReader xml(xmlFile); - QRegExp rx(".*fst"); - bool truncated = false; - QString lastKey; - - // Read xml until the end or an error is detected - while(!xml.atEnd() && !xml.hasError()) { - if(xml.tokenType() == QXmlStreamReader::StartElement && xml.name() == IS_TRUNCATED_NAME) { - while(!(xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == IS_TRUNCATED_NAME)) { - // Let's check if there is more - xml.readNext(); - if (xml.text().toString() == "True") { - truncated = true; - } - } - } - - if(xml.tokenType() == QXmlStreamReader::StartElement && xml.name() == CONTAINER_NAME) { - while(!(xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == CONTAINER_NAME)) { - // If a file is find, process it - if(xml.tokenType() == QXmlStreamReader::StartElement && xml.name() == KEY_NAME) { - xml.readNext(); - lastKey = xml.text().toString(); - if (rx.exactMatch(xml.text().toString())) { - // Add the found file to the list - _models.insert(QFileInfo(xml.text().toString()).baseName(), - S3_URL + "/" + xml.text().toString()); - } - } - xml.readNext(); - } - } - xml.readNext(); - } - - // Error handling - if(xml.hasError()) { - _models.clear(); - QMessageBox::critical(this, - "ModelBrowser::ModelBrowser()", - xml.errorString(), - QMessageBox::Ok); - return false; - } - - // If we didn't all the files, download the next ones - if (truncated) { - QUrl url(S3_URL); - QUrlQuery query; - - if (_type == Head) { - query.addQueryItem(PREFIX_PARAMETER_NAME, HEAD_MODELS_LOCATION); - } else if (_type == Skeleton) { - query.addQueryItem(PREFIX_PARAMETER_NAME, SKELETON_MODELS_LOCATION); - } - query.addQueryItem(MARKER_PARAMETER_NAME, lastKey); - url.setQuery(query); - - delete _downloader; - _downloader = new FileDownloader(url); - connect(_downloader, SIGNAL(done(QNetworkReply::NetworkError)), SLOT(downloadFinished())); - } - - return true; -} \ No newline at end of file diff --git a/interface/src/ui/ModelBrowser.h b/interface/src/ui/ModelBrowser.h deleted file mode 100644 index 4628642e89..0000000000 --- a/interface/src/ui/ModelBrowser.h +++ /dev/null @@ -1,62 +0,0 @@ -// -// ModelBrowser.h -// hifi -// -// Created by Clement on 3/17/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. -// - -#ifndef __hifi__ModelBrowser__ -#define __hifi__ModelBrowser__ - -#include - -#include -#include - -static const QString S3_URL = "http://highfidelity-public.s3-us-west-1.amazonaws.com"; -static const QString HEAD_MODELS_LOCATION = "models/heads/"; -static const QString SKELETON_MODELS_LOCATION = "models/skeletons/"; - -enum ModelType { - Head, - Skeleton -}; - -class ModelBrowser : public QWidget { - Q_OBJECT - -public: - ModelBrowser(ModelType modelType, QWidget* parent = NULL); - ~ModelBrowser(); - -signals: - void selected(QString filename); - -public slots: - void browse(); - -private slots: - void downloadFinished(); - -private: - ModelType _type; - FileDownloader* _downloader; - QHash _models; - - bool parseXML(QByteArray xmlFile); -}; - - - -class ListView : public QListView { - Q_OBJECT -public: - ListView(QWidget* parent) : QListView(parent) {} - public slots: - void keyboardSearch(const QString& text) { - QAbstractItemView::keyboardSearch(text); - } -}; - -#endif /* defined(__hifi__ModelBrowser__) */ diff --git a/interface/src/ui/ModelsBrowser.cpp b/interface/src/ui/ModelsBrowser.cpp new file mode 100644 index 0000000000..3bdc4ca9ed --- /dev/null +++ b/interface/src/ui/ModelsBrowser.cpp @@ -0,0 +1,305 @@ +// +// ModelsBrowser.cpp +// hifi +// +// Created by Clement on 3/17/14. +// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "ModelsBrowser.h" + +static const QString S3_URL = "http://highfidelity-public.s3-us-west-1.amazonaws.com"; +static const QString PUBLIC_URL = "http://public.highfidelity.io"; +static const QString HEAD_MODELS_LOCATION = "models/heads"; +static const QString SKELETON_MODELS_LOCATION = "models/skeletons/"; + +static const QString PREFIX_PARAMETER_NAME = "prefix"; +static const QString MARKER_PARAMETER_NAME = "marker"; +static const QString IS_TRUNCATED_NAME = "IsTruncated"; +static const QString CONTAINER_NAME = "Contents"; +static const QString KEY_NAME = "Key"; +static const QString LOADING_MSG = "Loading..."; + +enum ModelMetaData { + Name = 0, + Creator, + UploadeDate, + Type, + Gender, + + ModelMetaDataCount +}; +static const QString propertiesNames[ModelMetaDataCount] = { + "Name", + "Creator", + "Upload Date", + "Type", + "Gender" +}; + +ModelsBrowser::ModelsBrowser(ModelType modelsType, QWidget* parent) : + QWidget(parent), + _handler(new ModelHandler(modelsType)) +{ + // Connect handler + _handler->connect(this, SIGNAL(startDownloading()), SLOT(download())); + _handler->connect(this, SIGNAL(startUpdating()), SLOT(update())); + _handler->connect(this, SIGNAL(destroyed()), SLOT(exit())); + + // Setup and launch update thread + QThread* thread = new QThread(); + thread->connect(_handler, SIGNAL(destroyed()), SLOT(quit())); + thread->connect(thread, SIGNAL(finished()), SLOT(deleteLater())); + _handler->moveToThread(thread); + thread->start(); + emit startDownloading(); + + // Initialize the view + _view.setEditTriggers(QAbstractItemView::NoEditTriggers); + _view.setRootIsDecorated(false); + _view.setModel(_handler->getModel()); +} + +ModelsBrowser::~ModelsBrowser() { +} + +void ModelsBrowser::applyFilter(const QString &filter) { + QStringList filters = filter.split(" "); + + // Try and match every filter with each rows + for (int i = 0; i < _handler->getModel()->rowCount(); ++i) { + bool match = false; + for (int k = 0; k < filters.count(); ++k) { + match = false; + for (int j = 0; j < ModelMetaDataCount; ++j) { + if (_handler->getModel()->item(i, j)->text().contains(filters.at(k))) { + match = true; + break; + } + } + if (!match) { + break; + } + } + + // Hid the row if it doesn't match (Make sure it's not it it does) + if (match) { + _view.setRowHidden(i, QModelIndex(), false); + } else { + _view.setRowHidden(i, QModelIndex(), true); + } + } +} + +void ModelsBrowser::browse() { + QDialog dialog; + dialog.setWindowTitle("Browse models"); + + QGridLayout* layout = new QGridLayout(&dialog); + dialog.setLayout(layout); + + QLineEdit* searchBar = new QLineEdit(&dialog); + layout->addWidget(searchBar, 0, 0); + + layout->addWidget(&_view, 1, 0); + dialog.connect(&_view, SIGNAL(doubleClicked(const QModelIndex&)), SLOT(accept())); + connect(searchBar, SIGNAL(textChanged(const QString&)), SLOT(applyFilter(const QString&))); + + QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + layout->addWidget(buttons, 2, 0); + dialog.connect(buttons, SIGNAL(accepted()), SLOT(accept())); + dialog.connect(buttons, SIGNAL(rejected()), SLOT(reject())); + + if (dialog.exec() == QDialog::Accepted) { + QVariant selectedFile = _handler->getModel()->data(_view.currentIndex(), Qt::UserRole); + if (selectedFile.isValid()) { + emit selected(selectedFile.toString()); + } + } + + // So that we don't have to reconstruct the view + _view.setParent(NULL); +} + + +ModelHandler::ModelHandler(ModelType modelsType, QWidget* parent) : + QObject(parent), + _initiateExit(false), + _type(modelsType) +{ + connect(&_downloader, SIGNAL(done(QNetworkReply::NetworkError)), SLOT(downloadFinished())); + + // set headers data + QStringList headerData; + for (int i = 0; i < ModelMetaDataCount; ++i) { + headerData << propertiesNames[i]; + } + _model.setHorizontalHeaderLabels(headerData); +} + +void ModelHandler::download() { + // Query models list + queryNewFiles(); + + QMutexLocker lockerModel(&_modelMutex); + if (_initiateExit) { + return; + } + // Show loading message + QStandardItem* loadingItem = new QStandardItem(LOADING_MSG); + loadingItem->setEnabled(false); + _model.appendRow(loadingItem); +} + +void ModelHandler::update() { + // Will be implemented in my next PR +} + +void ModelHandler::exit() { + QMutexLocker lockerDownload(&_downloadMutex); + QMutexLocker lockerModel(&_modelMutex); + _initiateExit = true; + + // Disconnect everything + _downloader.disconnect(); + disconnect(); + thread()->disconnect(); + + // Make sure the thread will exit correctly + thread()->connect(this, SIGNAL(destroyed()), SLOT(quit())); + thread()->connect(thread(), SIGNAL(finished()), SLOT(deleteLater())); + deleteLater(); +} + +void ModelHandler::downloadFinished() { + QMutexLocker lockerDownload(&_downloadMutex); + if (_initiateExit) { + return; + } + parseXML(_downloader.getData()); +} + +void ModelHandler::queryNewFiles(QString marker) { + QMutexLocker lockerDownload(&_downloadMutex); + if (_initiateExit) { + return; + } + + // Build query + QUrl url(S3_URL); + QUrlQuery query; + if (_type == Head) { + query.addQueryItem(PREFIX_PARAMETER_NAME, HEAD_MODELS_LOCATION); + } else if (_type == Skeleton) { + query.addQueryItem(PREFIX_PARAMETER_NAME, SKELETON_MODELS_LOCATION); + } + + if (!marker.isEmpty()) { + query.addQueryItem(MARKER_PARAMETER_NAME, marker); + } + + // Download + url.setQuery(query); + _downloader.download(url); +} + +bool ModelHandler::parseXML(QByteArray xmlFile) { + QMutexLocker lockerModel(&_modelMutex); + if (_initiateExit) { + return false; + } + + QXmlStreamReader xml(xmlFile); + QRegExp rx(".*fst"); + bool truncated = false; + QString lastKey; + + // Remove loading indication + int oldLastRow = _model.rowCount() - 1; + delete _model.takeRow(oldLastRow).first(); + + // Read xml until the end or an error is detected + while(!xml.atEnd() && !xml.hasError()) { + if (_initiateExit) { + return false; + } + + if(xml.tokenType() == QXmlStreamReader::StartElement && xml.name() == IS_TRUNCATED_NAME) { + while(!(xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == IS_TRUNCATED_NAME)) { + // Let's check if there is more + xml.readNext(); + if (xml.text().toString() == "True") { + truncated = true; + } + } + } + + if(xml.tokenType() == QXmlStreamReader::StartElement && xml.name() == CONTAINER_NAME) { + while(!(xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == CONTAINER_NAME)) { + // If a file is find, process it + if(xml.tokenType() == QXmlStreamReader::StartElement && xml.name() == KEY_NAME) { + xml.readNext(); + lastKey = xml.text().toString(); + if (rx.exactMatch(xml.text().toString())) { + // Add the found file to the list + QList model; + model << new QStandardItem(QFileInfo(xml.text().toString()).baseName()); + model.first()->setData(PUBLIC_URL + "/" + xml.text().toString(), Qt::UserRole); + + // Rand properties for now (Will be taken out in the next PR) + static QString creator[] = {"Ryan", "Philip", "Andzrej"}; + static QString type[] = {"human", "beast", "pet", "elfe"}; + static QString gender[] = {"male", "female", "none"}; + model << new QStandardItem(creator[randIntInRange(0, 2)]); + model << new QStandardItem(QDate(randIntInRange(2013, 2014), + randIntInRange(1, 12), + randIntInRange(1, 30)).toString()); + model << new QStandardItem(type[randIntInRange(0, 3)]); + model << new QStandardItem(gender[randIntInRange(0, 2)]); + //////////////////////////////////////////////////////////// + + _model.appendRow(model); + } + } + xml.readNext(); + } + } + xml.readNext(); + } + + static const QString ERROR_MSG = "Error loading files"; + // Error handling + if(xml.hasError()) { + _model.clear(); + QStandardItem* errorItem = new QStandardItem(ERROR_MSG); + errorItem->setEnabled(false); + _model.appendRow(errorItem); + + return false; + } + + // If we didn't all the files, download the next ones + if (truncated) { + // Indicate more files are being loaded + QStandardItem* loadingItem = new QStandardItem(LOADING_MSG); + loadingItem->setEnabled(false); + _model.appendRow(loadingItem); + + // query those files + queryNewFiles(lastKey); + } + + return true; +} \ No newline at end of file diff --git a/interface/src/ui/ModelsBrowser.h b/interface/src/ui/ModelsBrowser.h new file mode 100644 index 0000000000..7343c0c14f --- /dev/null +++ b/interface/src/ui/ModelsBrowser.h @@ -0,0 +1,79 @@ +// +// ModelsBrowser.h +// hifi +// +// Created by Clement on 3/17/14. +// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// + +#ifndef __hifi__ModelsBrowser__ +#define __hifi__ModelsBrowser__ + +#include +#include +#include +#include + +#include + +typedef +enum { + Head, + Skeleton +} ModelType; + +class ModelHandler : public QObject { + Q_OBJECT +public: + ModelHandler(ModelType modelsType, QWidget* parent = NULL); + QStandardItemModel* getModel() { QMutexLocker locker(&_modelMutex); return &_model; } + +signals: + void doneDownloading(); + void doneUpdating(); + +public slots: + void download(); + void update(); + void exit(); + +private slots: + void downloadFinished(); + +private: + bool _initiateExit; + ModelType _type; + QMutex _downloadMutex; + FileDownloader _downloader; + QMutex _modelMutex; + QStandardItemModel _model; + + void queryNewFiles(QString marker = QString()); + bool parseXML(QByteArray xmlFile); +}; + + +class ModelsBrowser : public QWidget { + Q_OBJECT +public: + + ModelsBrowser(ModelType modelsType, QWidget* parent = NULL); + ~ModelsBrowser(); + +signals: + void startDownloading(); + void startUpdating(); + void selected(QString filename); + +public slots: + void browse(); + +private slots: + void applyFilter(const QString& filter); + +private: + ModelHandler* _handler; + QTreeView _view; +}; + +#endif /* defined(__hifi__ModelBrowser__) */ diff --git a/libraries/shared/src/FileDownloader.cpp b/libraries/shared/src/FileDownloader.cpp index 2b65bbd8df..69cf599fae 100644 --- a/libraries/shared/src/FileDownloader.cpp +++ b/libraries/shared/src/FileDownloader.cpp @@ -14,14 +14,25 @@ #include "FileDownloader.h" -FileDownloader::FileDownloader(const QUrl dataURL, QObject* parent) : - QObject(parent), - _done(false) -{ - connect(&_networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(processReply(QNetworkReply*))); +FileDownloader::FileDownloader(QObject* parent) : QObject(parent) { + connect(&_networkAccessManager, SIGNAL(finished(QNetworkReply*)), SLOT(processReply(QNetworkReply*))); +} +void FileDownloader::download(const QUrl dataURL, QNetworkAccessManager::Operation operation) { QNetworkRequest request(dataURL); - _networkAccessManager.get(request); + + _downloadedData.clear(); + switch (operation) { + case QNetworkAccessManager::GetOperation: + _networkAccessManager.get(request); + break; + case QNetworkAccessManager::HeadOperation: + _networkAccessManager.head(request); + break; + default: + emit done(QNetworkReply::ProtocolInvalidOperationError); + break; + } } void FileDownloader::processReply(QNetworkReply *reply) { @@ -30,36 +41,5 @@ void FileDownloader::processReply(QNetworkReply *reply) { } reply->deleteLater(); - _done = true; emit done(reply->error()); -} - -void FileDownloader::waitForFile(int timeout) { - QTimer timer; - QEventLoop loop; - connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); - connect(this, SIGNAL(done(QNetworkReply::NetworkError)), &loop, SLOT(quit())); - - if (!_done) { - if (timeout > 0) { - timer.start(timeout); - } - loop.exec(); - } -} - -QByteArray FileDownloader::download(const QUrl dataURL, int timeout) { - QTimer timer; - QEventLoop loop; - connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit)); - - FileDownloader downloader(dataURL); - connect(&downloader, SIGNAL(done(QNetworkReply::NetworkError)), &loop, SLOT(quit())); - - if (timeout > 0) { - timer.start(timeout); - } - loop.exec(); - - return downloader.getData(); } \ No newline at end of file diff --git a/libraries/shared/src/FileDownloader.h b/libraries/shared/src/FileDownloader.h index 593b39b013..7c5a416600 100644 --- a/libraries/shared/src/FileDownloader.h +++ b/libraries/shared/src/FileDownloader.h @@ -13,31 +13,28 @@ #include #include #include +#include class FileDownloader : public QObject { Q_OBJECT public: - FileDownloader(const QUrl dataURL, QObject* parent = NULL); - - void waitForFile(int timeout = 0); - + FileDownloader(QObject* parent = NULL); QByteArray getData() const { return _downloadedData; } - bool done() { return _done; } - static QByteArray download(const QUrl dataURL, int timeout = 0); signals: void done(QNetworkReply::NetworkError error); +public slots: + void download(const QUrl dataURL, QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation); + private slots: void processReply(QNetworkReply* reply); private: QNetworkAccessManager _networkAccessManager; QByteArray _downloadedData; - - bool _done; }; From f87c82450a48b409db0ac55e33a20db9504ef8d1 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 1 Apr 2014 12:20:08 -0700 Subject: [PATCH 079/595] Modified dialog default size --- interface/src/ui/ModelsBrowser.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/interface/src/ui/ModelsBrowser.cpp b/interface/src/ui/ModelsBrowser.cpp index 3bdc4ca9ed..c47ee1b5ba 100644 --- a/interface/src/ui/ModelsBrowser.cpp +++ b/interface/src/ui/ModelsBrowser.cpp @@ -106,6 +106,7 @@ void ModelsBrowser::applyFilter(const QString &filter) { void ModelsBrowser::browse() { QDialog dialog; dialog.setWindowTitle("Browse models"); + dialog.setMinimumSize(570, 500); QGridLayout* layout = new QGridLayout(&dialog); dialog.setLayout(layout); From 916a5d2da07fb2052a5f5beffa81f35d5f1fd826 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 12:24:03 -0700 Subject: [PATCH 080/595] more debugging --- assignment-client/src/octree/OctreeServer.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index d38a654219..15beafa0c0 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -828,6 +828,7 @@ void OctreeServer::readPendingDatagrams() { NodeList* nodeList = NodeList::getInstance(); + quint64 startReadAvailable = usecTimestampNow(); while (readAvailableDatagram(receivedPacket, senderSockAddr)) { if (nodeList->packetVersionAndHashMatch(receivedPacket)) { PacketType packetType = packetTypeForPacket(receivedPacket); @@ -878,6 +879,9 @@ void OctreeServer::readPendingDatagrams() { } } } + quint64 endReadAvailable = usecTimestampNow(); + qDebug() << "OctreeServer::readPendingDatagrams(): while(readAvailable) took" << (endReadAvailable - startReadAvailable) << "usecs"; + } void OctreeServer::run() { From 6cb44a4d0ca13c066fd7b5fea26fded32797697d Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 12:33:59 -0700 Subject: [PATCH 081/595] more debugging --- assignment-client/src/octree/OctreeServer.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 15beafa0c0..c3c6510982 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -880,7 +880,9 @@ void OctreeServer::readPendingDatagrams() { } } quint64 endReadAvailable = usecTimestampNow(); - qDebug() << "OctreeServer::readPendingDatagrams(): while(readAvailable) took" << (endReadAvailable - startReadAvailable) << "usecs"; + if (endReadAvailable - startReadAvailable > 1000) { + qDebug() << "OctreeServer::readPendingDatagrams(): while(readAvailable) took" << (endReadAvailable - startReadAvailable) << "usecs"; + } } From 59bba99c6f49f8344a0cd340a1283a9d8459596d Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 1 Apr 2014 12:48:17 -0700 Subject: [PATCH 082/595] Resolve body-body collisions with other avatars --- interface/src/avatar/MyAvatar.cpp | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 6e01ad3292..9710ad3b17 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -11,6 +11,7 @@ #include +#include #include #include @@ -20,10 +21,7 @@ #include #include -#ifdef ANDREW_HACKERY #include -#include -#endif ANDREW_HACKERY #include "Application.h" #include "Audio.h" @@ -873,6 +871,7 @@ bool findAvatarAvatarPenetration(const glm::vec3 positionA, float radiusA, float } static CollisionList bodyCollisions(16); +const float BODY_COLLISION_RESOLVE_TIMESCALE = 0.5f; // seconds void MyAvatar::updateCollisionWithAvatars(float deltaTime) { // Reset detector for nearest avatar @@ -885,6 +884,8 @@ void MyAvatar::updateCollisionWithAvatars(float deltaTime) { updateShapePositions(); float myBoundingRadius = getBoundingRadius(); + const float BODY_COLLISION_RESOLVE_FACTOR = deltaTime / BODY_COLLISION_RESOLVE_TIMESCALE; + foreach (const AvatarSharedPointer& avatarPointer, avatars) { Avatar* avatar = static_cast(avatarPointer.data()); if (static_cast(this) == avatar) { @@ -898,26 +899,27 @@ void MyAvatar::updateCollisionWithAvatars(float deltaTime) { } float theirBoundingRadius = avatar->getBoundingRadius(); if (distance < myBoundingRadius + theirBoundingRadius) { -#ifdef ANDREW_HACKERY + // collide our body against theirs QVector myShapes; _skeletonModel.getBodyShapes(myShapes); QVector theirShapes; avatar->getSkeletonModel().getBodyShapes(theirShapes); bodyCollisions.clear(); + // TODO: add method to ShapeCollider for colliding lists of shapes foreach (const Shape* myShape, myShapes) { foreach (const Shape* theirShape, theirShapes) { ShapeCollider::shapeShape(myShape, theirShape, bodyCollisions); - if (bodyCollisions.size() > 0) { - std::cout << "adebug myPos = " << myShape->getPosition() - << " myRadius = " << myShape->getBoundingRadius() - << " theirPos = " << theirShape->getPosition() - << " theirRadius = " << theirShape->getBoundingRadius() - << std::endl; // adebug - std::cout << "adebug collision count = " << bodyCollisions.size() << std::endl; // adebug - } } } -#endif // ANDREW_HACKERY + glm::vec3 totalPenetration(0.f); + for (int j = 0; j < bodyCollisions.size(); ++j) { + CollisionInfo* collision = bodyCollisions.getCollision(j); + totalPenetration = addPenetrations(totalPenetration, collision->_penetration); + } + + if (glm::length2(totalPenetration) > EPSILON) { + setPosition(getPosition() - BODY_COLLISION_RESOLVE_FACTOR * totalPenetration); + } // collide our hands against them // TODO: make this work when we can figure out when the other avatar won't yeild From 124619f8d90fa57ecd52b842522e400f60483f0b Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 12:51:34 -0700 Subject: [PATCH 083/595] more debugging --- assignment-client/src/octree/OctreeServer.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index c3c6510982..0958e2fa20 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -829,7 +829,9 @@ void OctreeServer::readPendingDatagrams() { NodeList* nodeList = NodeList::getInstance(); quint64 startReadAvailable = usecTimestampNow(); + int readDataGrams = 0; while (readAvailableDatagram(receivedPacket, senderSockAddr)) { + readDataGrams++; if (nodeList->packetVersionAndHashMatch(receivedPacket)) { PacketType packetType = packetTypeForPacket(receivedPacket); @@ -881,7 +883,8 @@ void OctreeServer::readPendingDatagrams() { } quint64 endReadAvailable = usecTimestampNow(); if (endReadAvailable - startReadAvailable > 1000) { - qDebug() << "OctreeServer::readPendingDatagrams(): while(readAvailable) took" << (endReadAvailable - startReadAvailable) << "usecs"; + qDebug() << "OctreeServer::readPendingDatagrams(): while(readAvailable) took" << (endReadAvailable - startReadAvailable) << "usecs" + << " readDataGrams=" << readDataGrams; } } From caf2473df82741db635097b8f03a2ec1e4f44976 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 1 Apr 2014 13:08:00 -0700 Subject: [PATCH 084/595] add a DTLSSession object to handle GnuTLS DTLS sessions --- assignment-client/src/AssignmentClient.cpp | 4 + domain-server/src/DomainServer.cpp | 168 +++++++++++---------- domain-server/src/main.cpp | 2 - libraries/shared/src/DTLSSession.cpp | 43 ++++++ libraries/shared/src/DTLSSession.h | 32 ++++ libraries/shared/src/DomainInfo.cpp | 21 ++- libraries/shared/src/DomainInfo.h | 7 +- libraries/shared/src/NodeList.cpp | 23 +-- libraries/shared/src/NodeList.h | 4 +- 9 files changed, 206 insertions(+), 98 deletions(-) create mode 100644 libraries/shared/src/DTLSSession.cpp create mode 100644 libraries/shared/src/DTLSSession.h diff --git a/assignment-client/src/AssignmentClient.cpp b/assignment-client/src/AssignmentClient.cpp index aa20f2ff29..7da87e4e5d 100644 --- a/assignment-client/src/AssignmentClient.cpp +++ b/assignment-client/src/AssignmentClient.cpp @@ -10,6 +10,8 @@ #include #include +#include + #include #include #include @@ -31,6 +33,8 @@ AssignmentClient::AssignmentClient(int &argc, char **argv) : QCoreApplication(argc, argv), _currentAssignment() { + gnutls_global_init(); + setOrganizationName("High Fidelity"); setOrganizationDomain("highfidelity.io"); setApplicationName("assignment-client"); diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index a9bb6c4cfc..d6fc91c8e7 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -39,7 +39,9 @@ DomainServer::DomainServer(int argc, char* argv[]) : _x509Credentials(NULL), _dhParams(NULL), _priorityCache(NULL) -{ +{ + gnutls_global_init(); + setOrganizationName("High Fidelity"); setOrganizationDomain("highfidelity.io"); setApplicationName("domain-server"); @@ -80,28 +82,30 @@ DomainServer::DomainServer(int argc, char* argv[]) : bool DomainServer::optionallySetupDTLS() { if (readX509KeyAndCertificate()) { - qDebug() << "Generating Diffie-Hellman parameters."; - - // generate Diffie-Hellman parameters - // When short bit length is used, it might be wise to regenerate parameters often. - int dhBits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, GNUTLS_SEC_PARAM_LEGACY); - - _dhParams = new gnutls_dh_params_t; - gnutls_dh_params_init(_dhParams); - gnutls_dh_params_generate2(*_dhParams, dhBits); - - qDebug() << "Successfully generated Diffie-Hellman parameters."; - - // set the D-H paramters on the X509 credentials - gnutls_certificate_set_dh_params(*_x509Credentials, *_dhParams); - - _priorityCache = new gnutls_priority_t; - const char DTLS_PRIORITY_STRING[] = "PERFORMANCE:-VERS-TLS-ALL:+VERS-DTLS1.2:%SERVER_PRECEDENCE"; - gnutls_priority_init(_priorityCache, DTLS_PRIORITY_STRING, NULL); - - _isUsingDTLS = true; - - qDebug() << "Initial DTLS setup complete."; + if (_x509Credentials) { + qDebug() << "Generating Diffie-Hellman parameters."; + + // generate Diffie-Hellman parameters + // When short bit length is used, it might be wise to regenerate parameters often. + int dhBits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, GNUTLS_SEC_PARAM_LEGACY); + + _dhParams = new gnutls_dh_params_t; + gnutls_dh_params_init(_dhParams); + gnutls_dh_params_generate2(*_dhParams, dhBits); + + qDebug() << "Successfully generated Diffie-Hellman parameters."; + + // set the D-H paramters on the X509 credentials + gnutls_certificate_set_dh_params(*_x509Credentials, *_dhParams); + + _priorityCache = new gnutls_priority_t; + const char DTLS_PRIORITY_STRING[] = "PERFORMANCE:-VERS-TLS-ALL:+VERS-DTLS1.2:%SERVER_PRECEDENCE"; + gnutls_priority_init(_priorityCache, DTLS_PRIORITY_STRING, NULL); + + _isUsingDTLS = true; + + qDebug() << "Initial DTLS setup complete."; + } return true; } else { @@ -180,7 +184,7 @@ void DomainServer::setupNodeListAndAssignments(const QUuid& sessionUUID) { domainServerPort = _argumentList.value(argumentIndex + 1).toUShort(); } - unsigned short domainServerDTLSPort = -1; + unsigned short domainServerDTLSPort = 0; if (_isUsingDTLS) { domainServerDTLSPort = DEFAULT_DOMAIN_SERVER_DTLS_PORT; @@ -532,69 +536,17 @@ void DomainServer::readAvailableDatagrams() { HifiSockAddr senderSockAddr; QByteArray receivedPacket; + + + static QByteArray assignmentPacket = byteArrayWithPopulatedHeader(PacketTypeCreateAssignment); + static int numAssignmentPacketHeaderBytes = assignmentPacket.size(); while (nodeList->getNodeSocket().hasPendingDatagrams()) { receivedPacket.resize(nodeList->getNodeSocket().pendingDatagramSize()); nodeList->getNodeSocket().readDatagram(receivedPacket.data(), receivedPacket.size(), senderSockAddr.getAddressPointer(), senderSockAddr.getPortPointer()); - - if (!_isUsingDTLS) { - // not using DTLS, process datagram normally - processDatagram(receivedPacket, senderSockAddr); - } else { - // we're using DTLS, so tell the sender to get back to us using DTLS - static QByteArray dtlsRequiredPacket = byteArrayWithPopulatedHeader(PacketTypeDomainServerRequireDTLS); - static int numBytesDTLSHeader = numBytesForPacketHeaderGivenPacketType(PacketTypeDomainServerRequireDTLS); - - if (dtlsRequiredPacket.size() == numBytesDTLSHeader) { - // pack the port that we accept DTLS traffic on - unsigned short dtlsPort = nodeList->getDTLSSocket().localPort(); - dtlsRequiredPacket.replace(numBytesDTLSHeader, sizeof(dtlsPort), reinterpret_cast(&dtlsPort)); - } + if (packetTypeForPacket(receivedPacket) && nodeList->packetVersionAndHashMatch(receivedPacket)) { - nodeList->writeUnverifiedDatagram(dtlsRequiredPacket, senderSockAddr); - } - } -} - -void DomainServer::readAvailableDTLSDatagrams() { - -} - -void DomainServer::processDatagram(const QByteArray& receivedPacket, const HifiSockAddr& senderSockAddr) { - NodeList* nodeList = NodeList::getInstance(); - - static QByteArray assignmentPacket = byteArrayWithPopulatedHeader(PacketTypeCreateAssignment); - static int numAssignmentPacketHeaderBytes = assignmentPacket.size(); - - if (nodeList->packetVersionAndHashMatch(receivedPacket)) { - PacketType requestType = packetTypeForPacket(receivedPacket); - - if (requestType == PacketTypeDomainListRequest) { - QUuid nodeUUID = uuidFromPacketHeader(receivedPacket); - - if (!nodeUUID.isNull() && nodeList->nodeWithUUID(nodeUUID)) { - NodeType_t throwawayNodeType; - HifiSockAddr nodePublicAddress, nodeLocalAddress; - - int numNodeInfoBytes = parseNodeDataFromByteArray(throwawayNodeType, nodePublicAddress, nodeLocalAddress, - receivedPacket, senderSockAddr); - - SharedNodePointer checkInNode = nodeList->updateSocketsForNode(nodeUUID, nodePublicAddress, nodeLocalAddress); - - // update last receive to now - quint64 timeNow = usecTimestampNow(); - checkInNode->setLastHeardMicrostamp(timeNow); - - sendDomainListToNode(checkInNode, senderSockAddr, nodeInterestListFromPacket(receivedPacket, numNodeInfoBytes)); - } else { - // new node - add this node to our NodeList - // and send back session UUID right away - addNodeToNodeListAndConfirmConnection(receivedPacket, senderSockAddr); - } - - } else if (requestType == PacketTypeRequestAssignment) { - // construct the requested assignment from the packet data Assignment requestAssignment(receivedPacket); @@ -626,7 +578,7 @@ void DomainServer::processDatagram(const QByteArray& receivedPacket, const HifiS } else { if (requestAssignment.getType() != Assignment::AgentType || (timeNow - lastNoisyMessage) > NOISY_TIME_ELAPSED) { qDebug() << "Unable to fulfill assignment request of type" << requestAssignment.getType() - << "from" << senderSockAddr; + << "from" << senderSockAddr; noisyMessage = true; } } @@ -634,6 +586,58 @@ void DomainServer::processDatagram(const QByteArray& receivedPacket, const HifiS if (noisyMessage) { lastNoisyMessage = timeNow; } + } else if (!_isUsingDTLS) { + // not using DTLS, process datagram normally + processDatagram(receivedPacket, senderSockAddr); + } else { + // we're using DTLS, so tell the sender to get back to us using DTLS + static QByteArray dtlsRequiredPacket = byteArrayWithPopulatedHeader(PacketTypeDomainServerRequireDTLS); + static int numBytesDTLSHeader = numBytesForPacketHeaderGivenPacketType(PacketTypeDomainServerRequireDTLS); + + if (dtlsRequiredPacket.size() == numBytesDTLSHeader) { + // pack the port that we accept DTLS traffic on + unsigned short dtlsPort = nodeList->getDTLSSocket().localPort(); + dtlsRequiredPacket.replace(numBytesDTLSHeader, sizeof(dtlsPort), reinterpret_cast(&dtlsPort)); + } + + nodeList->writeUnverifiedDatagram(dtlsRequiredPacket, senderSockAddr); + } + } +} + +void DomainServer::readAvailableDTLSDatagrams() { + +} + +void DomainServer::processDatagram(const QByteArray& receivedPacket, const HifiSockAddr& senderSockAddr) { + NodeList* nodeList = NodeList::getInstance(); + + if (nodeList->packetVersionAndHashMatch(receivedPacket)) { + PacketType requestType = packetTypeForPacket(receivedPacket); + + if (requestType == PacketTypeDomainListRequest) { + QUuid nodeUUID = uuidFromPacketHeader(receivedPacket); + + if (!nodeUUID.isNull() && nodeList->nodeWithUUID(nodeUUID)) { + NodeType_t throwawayNodeType; + HifiSockAddr nodePublicAddress, nodeLocalAddress; + + int numNodeInfoBytes = parseNodeDataFromByteArray(throwawayNodeType, nodePublicAddress, nodeLocalAddress, + receivedPacket, senderSockAddr); + + SharedNodePointer checkInNode = nodeList->updateSocketsForNode(nodeUUID, nodePublicAddress, nodeLocalAddress); + + // update last receive to now + quint64 timeNow = usecTimestampNow(); + checkInNode->setLastHeardMicrostamp(timeNow); + + sendDomainListToNode(checkInNode, senderSockAddr, nodeInterestListFromPacket(receivedPacket, numNodeInfoBytes)); + } else { + // new node - add this node to our NodeList + // and send back session UUID right away + addNodeToNodeListAndConfirmConnection(receivedPacket, senderSockAddr); + } + } else if (requestType == PacketTypeNodeJsonStats) { SharedNodePointer matchingNode = nodeList->sendingNodeForPacket(receivedPacket); if (matchingNode) { diff --git a/domain-server/src/main.cpp b/domain-server/src/main.cpp index 4bfa35fac5..096431e0a4 100644 --- a/domain-server/src/main.cpp +++ b/domain-server/src/main.cpp @@ -24,8 +24,6 @@ int main(int argc, char* argv[]) { setvbuf(stdout, NULL, _IOLBF, 0); #endif - gnutls_global_init(); - qInstallMessageHandler(Logging::verboseMessageHandler); DomainServer domainServer(argc, argv); diff --git a/libraries/shared/src/DTLSSession.cpp b/libraries/shared/src/DTLSSession.cpp new file mode 100644 index 0000000000..ce14d91f27 --- /dev/null +++ b/libraries/shared/src/DTLSSession.cpp @@ -0,0 +1,43 @@ +// +// DTLSSession.cpp +// hifi +// +// Created by Stephen Birarda on 2014-04-01. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// + +#include "DTLSSession.h" + +static int socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms) { + return 1; +} + +static ssize_t socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t size) { + DTLSSession* session = static_cast(ptr); + QUdpSocket& dtlsSocket = session->_dtlsSocket; + + if (dtlsSocket.hasPendingDatagrams()) { + return dtlsSocket.read(reinterpret_cast(buffer), size); + } else { + gnutls_transport_set_errno(session->_gnutlsSession, GNUTLS_E_AGAIN); + return 0; + } +} + +static ssize_t socketPush(gnutls_transport_ptr_t ptr, const void* buffer, size_t size) { + DTLSSession* session = static_cast(ptr); + QUdpSocket& dtlsSocket = session->_dtlsSocket; + + if (dtlsSocket.state() != QAbstractSocket::ConnectedState) { + gnutls_transport_set_errno(session->_gnutlsSession, GNUTLS_E_AGAIN); + return -1; + } + + return dtlsSocket.write(reinterpret_cast(buffer), size); +} + +DTLSSession::DTLSSession(QUdpSocket& dtlsSocket) : + _dtlsSocket(dtlsSocket) +{ + +} \ No newline at end of file diff --git a/libraries/shared/src/DTLSSession.h b/libraries/shared/src/DTLSSession.h new file mode 100644 index 0000000000..190373c155 --- /dev/null +++ b/libraries/shared/src/DTLSSession.h @@ -0,0 +1,32 @@ +// +// DTLSSession.h +// hifi +// +// Created by Stephen Birarda on 2014-04-01. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// + +#ifndef __hifi__DTLSSession__ +#define __hifi__DTLSSession__ + +#include + +#include + +static int socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms); +static ssize_t socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t size); +static ssize_t socketPush(gnutls_transport_ptr_t ptr, const void* buffer, size_t size); + +class DTLSSession { +public: + DTLSSession(QUdpSocket& dtlsSocket); + + friend int socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms); + friend ssize_t socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t size); + friend ssize_t socketPush(gnutls_transport_ptr_t ptr, const void* buffer, size_t size); +private: + QUdpSocket& _dtlsSocket; + gnutls_session_t _gnutlsSession; +}; + +#endif /* defined(__hifi__DTLSSession__) */ diff --git a/libraries/shared/src/DomainInfo.cpp b/libraries/shared/src/DomainInfo.cpp index 648f658619..1a360d1150 100644 --- a/libraries/shared/src/DomainInfo.cpp +++ b/libraries/shared/src/DomainInfo.cpp @@ -6,8 +6,9 @@ // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. // -#include +#include +#include "NodeList.h" #include "PacketHeaders.h" #include "DomainInfo.h" @@ -16,12 +17,17 @@ DomainInfo::DomainInfo() : _uuid(), _sockAddr(HifiSockAddr(QHostAddress::Null, DEFAULT_DOMAIN_SERVER_PORT)), _assignmentUUID(), + _isConnected(false), _requiresDTLS(false), - _isConnected(false) + _dtlsSession(NULL) { } +DomainInfo::~DomainInfo() { + delete _dtlsSession; +} + void DomainInfo::clearConnectionInfo() { _uuid = QUuid(); _isConnected = false; @@ -34,6 +40,12 @@ void DomainInfo::reset() { _requiresDTLS = false; } +void DomainInfo::initializeDTLSSession() { + if (!_dtlsSession) { + _dtlsSession = new DTLSSession(NodeList::getInstance()->getDTLSSocket()); + } +} + void DomainInfo::setSockAddr(const HifiSockAddr& sockAddr) { if (_sockAddr != sockAddr) { // we should reset on a sockAddr change @@ -107,8 +119,11 @@ void DomainInfo::parseDTLSRequirementPacket(const QByteArray& dtlsRequirementPac unsigned short dtlsPort = 0; memcpy(&dtlsPort, dtlsRequirementPacket.data() + numBytesPacketHeader, sizeof(dtlsPort)); + + qDebug() << "domain-server DTLS port changed to" << dtlsPort << "- Enabling DTLS."; + _sockAddr.setPort(dtlsPort); _requiresDTLS = true; - qDebug() << "domain-server DTLS port changed to" << dtlsPort << "- DTLS enabled."; + initializeDTLSSession(); } \ No newline at end of file diff --git a/libraries/shared/src/DomainInfo.h b/libraries/shared/src/DomainInfo.h index 63c7dcbf6d..71a0caabe0 100644 --- a/libraries/shared/src/DomainInfo.h +++ b/libraries/shared/src/DomainInfo.h @@ -14,6 +14,7 @@ #include #include +#include "DTLSSession.h" #include "HifiSockAddr.h" const QString DEFAULT_DOMAIN_HOSTNAME = "alpha.highfidelity.io"; @@ -24,6 +25,7 @@ class DomainInfo : public QObject { Q_OBJECT public: DomainInfo(); + ~DomainInfo(); void clearConnectionInfo(); @@ -54,15 +56,18 @@ private slots: signals: void hostnameChanged(const QString& hostname); void connectedToDomain(const QString& hostname); + void initializedDTLSSession(); private: void reset(); + void initializeDTLSSession(); QUuid _uuid; QString _hostname; HifiSockAddr _sockAddr; QUuid _assignmentUUID; - bool _requiresDTLS; bool _isConnected; + bool _requiresDTLS; + DTLSSession* _dtlsSession; }; #endif /* defined(__hifi__DomainInfo__) */ diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 167354542c..56986b4cc8 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -62,6 +62,7 @@ NodeList::NodeList(char newOwnerType, unsigned short socketListenPort, unsigned _nodeHash(), _nodeHashMutex(QMutex::Recursive), _nodeSocket(this), + _dtlsSocket(NULL), _ownerType(newOwnerType), _nodeTypesOfInterest(), _sessionUUID(), @@ -78,9 +79,11 @@ NodeList::NodeList(char newOwnerType, unsigned short socketListenPort, unsigned qDebug() << "NodeList socket is listening on" << _nodeSocket.localPort(); if (dtlsListenPort > 0) { - // we have a specfic DTLS port, bind that socket now - _dtlsSocket.bind(QHostAddress::AnyIPv4, dtlsListenPort); - qDebug() << "NodeList DTLS socket is listening on" << _dtlsSocket.localPort(); + // only create the DTLS socket during constructor if a custom port is passed + _dtlsSocket = new QUdpSocket(this); + + _dtlsSocket->bind(QHostAddress::AnyIPv4, dtlsListenPort); + qDebug() << "NodeList DTLS socket is listening on" << _dtlsSocket->localPort(); } // clear our NodeList when the domain changes @@ -96,12 +99,15 @@ NodeList::NodeList(char newOwnerType, unsigned short socketListenPort, unsigned } QUdpSocket& NodeList::getDTLSSocket() { - if (_dtlsSocket.state() == QAbstractSocket::UnconnectedState) { - _dtlsSocket.bind(QHostAddress::AnyIPv4); - qDebug() << "NodeList DTLS socket is listening on" << _dtlsSocket.localPort(); + if (!_dtlsSocket) { + // DTLS socket getter called but no DTLS socket exists, create it now + _dtlsSocket = new QUdpSocket(this); + + _dtlsSocket->bind(QHostAddress::AnyIPv4, 0, QAbstractSocket::DontShareAddress); + qDebug() << "NodeList DTLS socket is listening on" << _dtlsSocket->localPort(); } - return _dtlsSocket; + return *_dtlsSocket; } void NodeList::changeSendSocketBufferSize(int numSendBytes) { @@ -569,7 +575,7 @@ void NodeList::sendDomainServerCheckIn() { // we don't know our public socket and we need to send it to the domain server // send a STUN request to figure it out sendSTUNRequest(); - } else if (!_domainInfo.getIP().isNull()) { + } else if (!_domainInfo.getIP().isNull()) { // construct the DS check in packet PacketType domainPacketType = _sessionUUID.isNull() ? PacketTypeDomainConnectRequest : PacketTypeDomainListRequest; @@ -580,7 +586,6 @@ void NodeList::sendDomainServerCheckIn() { QByteArray domainServerPacket = byteArrayWithPopulatedHeader(domainPacketType, packetUUID); QDataStream packetStream(&domainServerPacket, QIODevice::Append); - // pack our data to send to the domain-server packetStream << _ownerType << _publicSockAddr << HifiSockAddr(QHostAddress(getHostOrderLocalAddress()), _nodeSocket.localPort()) diff --git a/libraries/shared/src/NodeList.h b/libraries/shared/src/NodeList.h index 613b431929..b12174296b 100644 --- a/libraries/shared/src/NodeList.h +++ b/libraries/shared/src/NodeList.h @@ -29,6 +29,8 @@ #include #include +#include + #include "DomainInfo.h" #include "Node.h" @@ -165,7 +167,7 @@ private: NodeHash _nodeHash; QMutex _nodeHashMutex; QUdpSocket _nodeSocket; - QUdpSocket _dtlsSocket; + QUdpSocket* _dtlsSocket; NodeType_t _ownerType; NodeSet _nodeTypesOfInterest; DomainInfo _domainInfo; From 62041d91a8682fd25dd14710b0b593f0b97177fe Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 1 Apr 2014 13:09:35 -0700 Subject: [PATCH 085/595] rename NodeList DomainInfo to DomainHandler --- animation-server/src/AnimationServer.cpp | 4 +-- assignment-client/src/Agent.cpp | 2 +- assignment-client/src/AssignmentClient.cpp | 6 ++--- interface/src/Application.cpp | 6 ++--- interface/src/Menu.cpp | 12 ++++----- interface/src/avatar/MyAvatar.cpp | 2 +- interface/src/ui/Snapshot.cpp | 2 +- .../src/{DomainInfo.cpp => DomainHandler.cpp} | 24 ++++++++--------- .../src/{DomainInfo.h => DomainHandler.h} | 14 +++++----- libraries/shared/src/NodeList.cpp | 26 +++++++++---------- libraries/shared/src/NodeList.h | 6 ++--- 11 files changed, 52 insertions(+), 52 deletions(-) rename libraries/shared/src/{DomainInfo.cpp => DomainHandler.cpp} (85%) rename libraries/shared/src/{DomainInfo.h => DomainHandler.h} (90%) diff --git a/animation-server/src/AnimationServer.cpp b/animation-server/src/AnimationServer.cpp index 1f0828ec17..e66ca35501 100644 --- a/animation-server/src/AnimationServer.cpp +++ b/animation-server/src/AnimationServer.cpp @@ -723,12 +723,12 @@ AnimationServer::AnimationServer(int &argc, char **argv) : ::wantLocalDomain = cmdOptionExists(argc, (const char**) argv,local); if (::wantLocalDomain) { printf("Local Domain MODE!\n"); - nodeList->getDomainInfo().setIPToLocalhost(); + nodeList->getDomainHandler().setIPToLocalhost(); } const char* domainHostname = getCmdOption(argc, (const char**) argv, "--domain"); if (domainHostname) { - NodeList::getInstance()->getDomainInfo().setHostname(domainHostname); + NodeList::getInstance()->getDomainHandler().setHostname(domainHostname); } const char* packetsPerSecondCommand = getCmdOption(argc, (const char**) argv, "--pps"); diff --git a/assignment-client/src/Agent.cpp b/assignment-client/src/Agent.cpp index b5199e87e8..4203ec02dc 100644 --- a/assignment-client/src/Agent.cpp +++ b/assignment-client/src/Agent.cpp @@ -146,7 +146,7 @@ void Agent::run() { // figure out the URL for the script for this agent assignment QString scriptURLString("http://%1:8080/assignment/%2"); - scriptURLString = scriptURLString.arg(NodeList::getInstance()->getDomainInfo().getIP().toString(), + scriptURLString = scriptURLString.arg(NodeList::getInstance()->getDomainHandler().getIP().toString(), uuidStringWithoutCurlyBraces(_uuid)); QNetworkAccessManager *networkManager = new QNetworkAccessManager(this); diff --git a/assignment-client/src/AssignmentClient.cpp b/assignment-client/src/AssignmentClient.cpp index 7da87e4e5d..046f362e1e 100644 --- a/assignment-client/src/AssignmentClient.cpp +++ b/assignment-client/src/AssignmentClient.cpp @@ -136,10 +136,10 @@ void AssignmentClient::readPendingDatagrams() { // switch our nodelist domain IP and port to whoever sent us the assignment - nodeList->getDomainInfo().setSockAddr(senderSockAddr); - nodeList->getDomainInfo().setAssignmentUUID(_currentAssignment->getUUID()); + nodeList->getDomainHandler().setSockAddr(senderSockAddr); + nodeList->getDomainHandler().setAssignmentUUID(_currentAssignment->getUUID()); - qDebug() << "Destination IP for assignment is" << nodeList->getDomainInfo().getIP().toString(); + qDebug() << "Destination IP for assignment is" << nodeList->getDomainHandler().getIP().toString(); // start the deployed assignment AssignmentThread* workerThread = new AssignmentThread(_currentAssignment, this); diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index c6fc522fca..4ffdf5b2b7 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -228,8 +228,8 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : audioThread->start(); - connect(&nodeList->getDomainInfo(), SIGNAL(hostnameChanged(const QString&)), SLOT(domainChanged(const QString&))); - connect(&nodeList->getDomainInfo(), SIGNAL(connectedToDomain(const QString&)), SLOT(connectedToDomain(const QString&))); + connect(&nodeList->getDomainHandler(), SIGNAL(hostnameChanged(const QString&)), SLOT(domainChanged(const QString&))); + connect(&nodeList->getDomainHandler(), SIGNAL(connectedToDomain(const QString&)), SLOT(connectedToDomain(const QString&))); connect(nodeList, &NodeList::nodeAdded, this, &Application::nodeAdded); connect(nodeList, &NodeList::nodeKilled, this, &Application::nodeKilled); @@ -3279,7 +3279,7 @@ void Application::updateWindowTitle(){ QString username = AccountManager::getInstance().getUsername(); QString title = QString() + (!username.isEmpty() ? username + " " : QString()) + nodeList->getSessionUUID().toString() - + " @ " + nodeList->getDomainInfo().getHostname() + buildVersion; + + " @ " + nodeList->getDomainHandler().getHostname() + buildVersion; qDebug("Application title set to: %s", title.toStdString().c_str()); _window->setWindowTitle(title); diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 7748c466c7..ebb817deb3 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -863,23 +863,23 @@ void Menu::editPreferences() { } void Menu::goToDomain(const QString newDomain) { - if (NodeList::getInstance()->getDomainInfo().getHostname() != newDomain) { + if (NodeList::getInstance()->getDomainHandler().getHostname() != newDomain) { // send a node kill request, indicating to other clients that they should play the "disappeared" effect Application::getInstance()->getAvatar()->sendKillAvatar(); // give our nodeList the new domain-server hostname - NodeList::getInstance()->getDomainInfo().setHostname(newDomain); + NodeList::getInstance()->getDomainHandler().setHostname(newDomain); } } void Menu::goToDomainDialog() { - QString currentDomainHostname = NodeList::getInstance()->getDomainInfo().getHostname(); + QString currentDomainHostname = NodeList::getInstance()->getDomainHandler().getHostname(); - if (NodeList::getInstance()->getDomainInfo().getPort() != DEFAULT_DOMAIN_SERVER_PORT) { + if (NodeList::getInstance()->getDomainHandler().getPort() != DEFAULT_DOMAIN_SERVER_PORT) { // add the port to the currentDomainHostname string if it is custom - currentDomainHostname.append(QString(":%1").arg(NodeList::getInstance()->getDomainInfo().getPort())); + currentDomainHostname.append(QString(":%1").arg(NodeList::getInstance()->getDomainHandler().getPort())); } QInputDialog domainDialog(Application::getInstance()->getWindow()); @@ -1034,7 +1034,7 @@ void Menu::nameLocation() { connect(manager, &LocationManager::creationCompleted, this, &Menu::namedLocationCreated); NamedLocation* location = new NamedLocation(locationName, myAvatar->getPosition(), myAvatar->getOrientation(), - NodeList::getInstance()->getDomainInfo().getHostname()); + NodeList::getInstance()->getDomainHandler().getHostname()); manager->createNamedLocation(location); } } diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 62ba24a384..4fadd98cdd 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -1129,7 +1129,7 @@ void MyAvatar::goToLocationFromResponse(const QJsonObject& jsonObject) { QStringList coordinateItems = positionString.split(','); QStringList orientationItems = orientationString.split(','); - NodeList::getInstance()->getDomainInfo().setHostname(domainHostnameString); + NodeList::getInstance()->getDomainHandler().setHostname(domainHostnameString); // orient the user to face the target glm::quat newOrientation = glm::quat(glm::radians(glm::vec3(orientationItems[0].toFloat(), diff --git a/interface/src/ui/Snapshot.cpp b/interface/src/ui/Snapshot.cpp index a29a96f009..dec69498ed 100644 --- a/interface/src/ui/Snapshot.cpp +++ b/interface/src/ui/Snapshot.cpp @@ -76,7 +76,7 @@ void Snapshot::saveSnapshot(QGLWidget* widget, Avatar* avatar) { shot.setText(ORIENTATION_Z, QString::number(orientation.z)); shot.setText(ORIENTATION_W, QString::number(orientation.w)); - shot.setText(DOMAIN_KEY, NodeList::getInstance()->getDomainInfo().getHostname()); + shot.setText(DOMAIN_KEY, NodeList::getInstance()->getDomainHandler().getHostname()); QString formattedLocation = QString("%1_%2_%3").arg(location.x).arg(location.y).arg(location.z); // replace decimal . with '-' diff --git a/libraries/shared/src/DomainInfo.cpp b/libraries/shared/src/DomainHandler.cpp similarity index 85% rename from libraries/shared/src/DomainInfo.cpp rename to libraries/shared/src/DomainHandler.cpp index 1a360d1150..52bfa04414 100644 --- a/libraries/shared/src/DomainInfo.cpp +++ b/libraries/shared/src/DomainHandler.cpp @@ -1,5 +1,5 @@ // -// DomainInfo.cpp +// DomainHandler.cpp // hifi // // Created by Stephen Birarda on 2/18/2014. @@ -11,9 +11,9 @@ #include "NodeList.h" #include "PacketHeaders.h" -#include "DomainInfo.h" +#include "DomainHandler.h" -DomainInfo::DomainInfo() : +DomainHandler::DomainHandler() : _uuid(), _sockAddr(HifiSockAddr(QHostAddress::Null, DEFAULT_DOMAIN_SERVER_PORT)), _assignmentUUID(), @@ -24,29 +24,29 @@ DomainInfo::DomainInfo() : } -DomainInfo::~DomainInfo() { +DomainHandler::~DomainHandler() { delete _dtlsSession; } -void DomainInfo::clearConnectionInfo() { +void DomainHandler::clearConnectionInfo() { _uuid = QUuid(); _isConnected = false; } -void DomainInfo::reset() { +void DomainHandler::reset() { clearConnectionInfo(); _hostname = QString(); _sockAddr.setAddress(QHostAddress::Null); _requiresDTLS = false; } -void DomainInfo::initializeDTLSSession() { +void DomainHandler::initializeDTLSSession() { if (!_dtlsSession) { _dtlsSession = new DTLSSession(NodeList::getInstance()->getDTLSSocket()); } } -void DomainInfo::setSockAddr(const HifiSockAddr& sockAddr) { +void DomainHandler::setSockAddr(const HifiSockAddr& sockAddr) { if (_sockAddr != sockAddr) { // we should reset on a sockAddr change reset(); @@ -55,7 +55,7 @@ void DomainInfo::setSockAddr(const HifiSockAddr& sockAddr) { } } -void DomainInfo::setHostname(const QString& hostname) { +void DomainHandler::setHostname(const QString& hostname) { if (hostname != _hostname) { // re-set the domain info so that auth information is reloaded @@ -88,7 +88,7 @@ void DomainInfo::setHostname(const QString& hostname) { } } -void DomainInfo::completedHostnameLookup(const QHostInfo& hostInfo) { +void DomainHandler::completedHostnameLookup(const QHostInfo& hostInfo) { for (int i = 0; i < hostInfo.addresses().size(); i++) { if (hostInfo.addresses()[i].protocol() == QAbstractSocket::IPv4Protocol) { _sockAddr.setAddress(hostInfo.addresses()[i]); @@ -102,7 +102,7 @@ void DomainInfo::completedHostnameLookup(const QHostInfo& hostInfo) { qDebug("Failed domain server lookup"); } -void DomainInfo::setIsConnected(bool isConnected) { +void DomainHandler::setIsConnected(bool isConnected) { if (_isConnected != isConnected) { _isConnected = isConnected; @@ -112,7 +112,7 @@ void DomainInfo::setIsConnected(bool isConnected) { } } -void DomainInfo::parseDTLSRequirementPacket(const QByteArray& dtlsRequirementPacket) { +void DomainHandler::parseDTLSRequirementPacket(const QByteArray& dtlsRequirementPacket) { // figure out the port that the DS wants us to use for us to talk to them with DTLS int numBytesPacketHeader = numBytesForPacketHeader(dtlsRequirementPacket); diff --git a/libraries/shared/src/DomainInfo.h b/libraries/shared/src/DomainHandler.h similarity index 90% rename from libraries/shared/src/DomainInfo.h rename to libraries/shared/src/DomainHandler.h index 71a0caabe0..4a9f166963 100644 --- a/libraries/shared/src/DomainInfo.h +++ b/libraries/shared/src/DomainHandler.h @@ -1,13 +1,13 @@ // -// DomainInfo.h +// DomainHandler.h // hifi // // Created by Stephen Birarda on 2/18/2014. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. // -#ifndef __hifi__DomainInfo__ -#define __hifi__DomainInfo__ +#ifndef __hifi__DomainHandler__ +#define __hifi__DomainHandler__ #include #include @@ -21,11 +21,11 @@ const QString DEFAULT_DOMAIN_HOSTNAME = "alpha.highfidelity.io"; const unsigned short DEFAULT_DOMAIN_SERVER_PORT = 40102; const unsigned short DEFAULT_DOMAIN_SERVER_DTLS_PORT = 40103; -class DomainInfo : public QObject { +class DomainHandler : public QObject { Q_OBJECT public: - DomainInfo(); - ~DomainInfo(); + DomainHandler(); + ~DomainHandler(); void clearConnectionInfo(); @@ -70,4 +70,4 @@ private: DTLSSession* _dtlsSession; }; -#endif /* defined(__hifi__DomainInfo__) */ +#endif /* defined(__hifi__DomainHandler__) */ diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 56986b4cc8..7cf58385fe 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -87,7 +87,7 @@ NodeList::NodeList(char newOwnerType, unsigned short socketListenPort, unsigned } // clear our NodeList when the domain changes - connect(&_domainInfo, &DomainInfo::hostnameChanged, this, &NodeList::reset); + connect(&_DomainHandler, &DomainHandler::hostnameChanged, this, &NodeList::reset); // clear our NodeList when logout is requested connect(&AccountManager::getInstance(), &AccountManager::logoutComplete , this, &NodeList::reset); @@ -234,7 +234,7 @@ qint64 NodeList::sendStatsToDomainServer(const QJsonObject& statsObject) { statsPacketStream << statsObject.toVariantMap(); - return writeDatagram(statsPacket, _domainInfo.getSockAddr(), QUuid()); + return writeDatagram(statsPacket, _DomainHandler.getSockAddr(), QUuid()); } void NodeList::timePingReply(const QByteArray& packet, const SharedNodePointer& sendingNode) { @@ -279,7 +279,7 @@ void NodeList::processNodeData(const HifiSockAddr& senderSockAddr, const QByteAr break; } case PacketTypeDomainServerRequireDTLS: { - _domainInfo.parseDTLSRequirementPacket(packet); + _DomainHandler.parseDTLSRequirementPacket(packet); break; } case PacketTypePing: { @@ -400,7 +400,7 @@ void NodeList::reset() { setSessionUUID(QUuid()); // clear the domain connection information - _domainInfo.clearConnectionInfo(); + _DomainHandler.clearConnectionInfo(); } void NodeList::addNodeTypeToInterestSet(NodeType_t nodeTypeToAdd) { @@ -575,13 +575,13 @@ void NodeList::sendDomainServerCheckIn() { // we don't know our public socket and we need to send it to the domain server // send a STUN request to figure it out sendSTUNRequest(); - } else if (!_domainInfo.getIP().isNull()) { + } else if (!_DomainHandler.getIP().isNull()) { // construct the DS check in packet PacketType domainPacketType = _sessionUUID.isNull() ? PacketTypeDomainConnectRequest : PacketTypeDomainListRequest; QUuid packetUUID = (domainPacketType == PacketTypeDomainListRequest) - ? _sessionUUID : _domainInfo.getAssignmentUUID(); + ? _sessionUUID : _DomainHandler.getAssignmentUUID(); QByteArray domainServerPacket = byteArrayWithPopulatedHeader(domainPacketType, packetUUID); QDataStream packetStream(&domainServerPacket, QIODevice::Append); @@ -596,7 +596,7 @@ void NodeList::sendDomainServerCheckIn() { packetStream << nodeTypeOfInterest; } - writeDatagram(domainServerPacket, _domainInfo.getSockAddr(), QUuid()); + writeDatagram(domainServerPacket, _DomainHandler.getSockAddr(), QUuid()); const int NUM_DOMAIN_SERVER_CHECKINS_PER_STUN_REQUEST = 5; static unsigned int numDomainCheckins = 0; @@ -632,7 +632,7 @@ int NodeList::processDomainServerList(const QByteArray& packet) { _numNoReplyDomainCheckIns = 0; // if this was the first domain-server list from this domain, we've now connected - _domainInfo.setIsConnected(true); + _DomainHandler.setIsConnected(true); int readNodes = 0; @@ -659,7 +659,7 @@ int NodeList::processDomainServerList(const QByteArray& packet) { // if the public socket address is 0 then it's reachable at the same IP // as the domain server if (nodePublicSocket.getAddress().isNull()) { - nodePublicSocket.setAddress(_domainInfo.getIP()); + nodePublicSocket.setAddress(_DomainHandler.getIP()); } SharedNodePointer node = addOrUpdateNode(nodeUUID, nodeType, nodePublicSocket, nodeLocalSocket); @@ -881,9 +881,9 @@ void NodeList::loadData(QSettings *settings) { QString domainServerHostname = settings->value(DOMAIN_SERVER_SETTING_KEY).toString(); if (domainServerHostname.size() > 0) { - _domainInfo.setHostname(domainServerHostname); + _DomainHandler.setHostname(domainServerHostname); } else { - _domainInfo.setHostname(DEFAULT_DOMAIN_HOSTNAME); + _DomainHandler.setHostname(DEFAULT_DOMAIN_HOSTNAME); } settings->endGroup(); @@ -892,9 +892,9 @@ void NodeList::loadData(QSettings *settings) { void NodeList::saveData(QSettings* settings) { settings->beginGroup(DOMAIN_SERVER_SETTING_KEY); - if (_domainInfo.getHostname() != DEFAULT_DOMAIN_HOSTNAME) { + if (_DomainHandler.getHostname() != DEFAULT_DOMAIN_HOSTNAME) { // the user is using a different hostname, store it - settings->setValue(DOMAIN_SERVER_SETTING_KEY, QVariant(_domainInfo.getHostname())); + settings->setValue(DOMAIN_SERVER_SETTING_KEY, QVariant(_DomainHandler.getHostname())); } else { // the user has switched back to default, remove the current setting settings->remove(DOMAIN_SERVER_SETTING_KEY); diff --git a/libraries/shared/src/NodeList.h b/libraries/shared/src/NodeList.h index b12174296b..9c19e33ed9 100644 --- a/libraries/shared/src/NodeList.h +++ b/libraries/shared/src/NodeList.h @@ -31,7 +31,7 @@ #include -#include "DomainInfo.h" +#include "DomainHandler.h" #include "Node.h" const quint64 NODE_SILENCE_THRESHOLD_USECS = 2 * 1000 * 1000; @@ -91,7 +91,7 @@ public: int size() const { return _nodeHash.size(); } int getNumNoReplyDomainCheckIns() const { return _numNoReplyDomainCheckIns; } - DomainInfo& getDomainInfo() { return _domainInfo; } + DomainHandler& getDomainHandler() { return _DomainHandler; } const NodeSet& getNodeInterestSet() const { return _nodeTypesOfInterest; } void addNodeTypeToInterestSet(NodeType_t nodeTypeToAdd); @@ -170,7 +170,7 @@ private: QUdpSocket* _dtlsSocket; NodeType_t _ownerType; NodeSet _nodeTypesOfInterest; - DomainInfo _domainInfo; + DomainHandler _DomainHandler; QUuid _sessionUUID; int _numNoReplyDomainCheckIns; HifiSockAddr _assignmentServerSocket; From 45c6ae44a665dfb2851de1add545b8045dbcbf22 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 1 Apr 2014 13:33:30 -0700 Subject: [PATCH 086/595] use a LimitedNodeList in domain-server --- domain-server/src/DomainServer.cpp | 37 +- libraries/shared/src/LimitedNodeList.cpp | 429 +++++++++++++++++++++++ libraries/shared/src/LimitedNodeList.h | 128 +++++++ libraries/shared/src/NodeList.cpp | 380 +------------------- libraries/shared/src/NodeList.h | 75 +--- 5 files changed, 582 insertions(+), 467 deletions(-) create mode 100644 libraries/shared/src/LimitedNodeList.cpp create mode 100644 libraries/shared/src/LimitedNodeList.h diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index d6fc91c8e7..a32ae76e79 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -60,12 +60,12 @@ DomainServer::DomainServer(int argc, char* argv[]) : // DTLS requires that IP_DONTFRAG be set // This is not accessible on some platforms (OS X) so we need to make sure DTLS still works without it - NodeList* nodeList = NodeList::getInstance(); + LimitedNodeList* nodeList = LimitedNodeList::getInstance(); #if defined(IP_DONTFRAG) || defined(IP_MTU_DISCOVER) qDebug() << "Making required DTLS changes to NodeList DTLS socket."; - int socketHandle = NodeList::getInstance()->getDTLSSocket().socketDescriptor(); + int socketHandle = LimitedNodeList::getInstance()->getDTLSSocket().socketDescriptor(); #if defined(IP_DONTFRAG) int optValue = 1;yea setsockopt(socketHandle, IPPROTO_IP, IP_DONTFRAG, (const void*) optValue, sizeof(optValue)); @@ -207,13 +207,10 @@ void DomainServer::setupNodeListAndAssignments(const QUuid& sessionUUID) { populateDefaultStaticAssignmentsExcludingTypes(parsedTypes); - NodeList* nodeList = NodeList::createInstance(NodeType::DomainServer, domainServerPort, domainServerDTLSPort); + LimitedNodeList* nodeList = LimitedNodeList::createInstance(domainServerPort, domainServerDTLSPort); - // create a random UUID for this session for the domain-server - nodeList->setSessionUUID(sessionUUID); - - connect(nodeList, &NodeList::nodeAdded, this, &DomainServer::nodeAdded); - connect(nodeList, &NodeList::nodeKilled, this, &DomainServer::nodeKilled); + connect(nodeList, &LimitedNodeList::nodeAdded, this, &DomainServer::nodeAdded); + connect(nodeList, &LimitedNodeList::nodeKilled, this, &DomainServer::nodeKilled); QTimer* silentNodeTimer = new QTimer(this); connect(silentNodeTimer, SIGNAL(timeout()), nodeList, SLOT(removeSilentNodes())); @@ -394,7 +391,7 @@ void DomainServer::addNodeToNodeListAndConfirmConnection(const QByteArray& packe // create a new session UUID for this node QUuid nodeUUID = QUuid::createUuid(); - SharedNodePointer newNode = NodeList::getInstance()->addOrUpdateNode(nodeUUID, nodeType, publicSockAddr, localSockAddr); + SharedNodePointer newNode = LimitedNodeList::getInstance()->addOrUpdateNode(nodeUUID, nodeType, publicSockAddr, localSockAddr); // when the newNode is created the linked data is also created, if this was a static assignment set the UUID reinterpret_cast(newNode->getLinkedData())->setStaticAssignmentUUID(assignmentUUID); @@ -477,7 +474,7 @@ void DomainServer::sendDomainListToNode(const SharedNodePointer& node, const Hif DomainServerNodeData* nodeData = reinterpret_cast(node->getLinkedData()); - NodeList* nodeList = NodeList::getInstance(); + LimitedNodeList* nodeList = LimitedNodeList::getInstance(); if (nodeInterestList.size() > 0) { @@ -532,7 +529,7 @@ void DomainServer::sendDomainListToNode(const SharedNodePointer& node, const Hif } void DomainServer::readAvailableDatagrams() { - NodeList* nodeList = NodeList::getInstance(); + LimitedNodeList* nodeList = LimitedNodeList::getInstance(); HifiSockAddr senderSockAddr; QByteArray receivedPacket; @@ -610,7 +607,7 @@ void DomainServer::readAvailableDTLSDatagrams() { } void DomainServer::processDatagram(const QByteArray& receivedPacket, const HifiSockAddr& senderSockAddr) { - NodeList* nodeList = NodeList::getInstance(); + LimitedNodeList* nodeList = LimitedNodeList::getInstance(); if (nodeList->packetVersionAndHashMatch(receivedPacket)) { PacketType requestType = packetTypeForPacket(receivedPacket); @@ -702,7 +699,7 @@ bool DomainServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url QJsonObject assignedNodesJSON; // enumerate the NodeList to find the assigned nodes - foreach (const SharedNodePointer& node, NodeList::getInstance()->getNodeHash()) { + foreach (const SharedNodePointer& node, LimitedNodeList::getInstance()->getNodeHash()) { if (_staticAssignmentHash.value(node->getUUID())) { // add the node using the UUID as the key QString uuidString = uuidStringWithoutCurlyBraces(node->getUUID()); @@ -744,7 +741,7 @@ bool DomainServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url QJsonObject nodesJSON; // enumerate the NodeList to find the assigned nodes - NodeList* nodeList = NodeList::getInstance(); + LimitedNodeList* nodeList = LimitedNodeList::getInstance(); foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { // add the node using the UUID as the key @@ -769,7 +766,7 @@ bool DomainServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url QUuid matchingUUID = QUuid(nodeShowRegex.cap(1)); // see if we have a node that matches this ID - SharedNodePointer matchingNode = NodeList::getInstance()->nodeWithUUID(matchingUUID); + SharedNodePointer matchingNode = LimitedNodeList::getInstance()->nodeWithUUID(matchingUUID); if (matchingNode) { // create a QJsonDocument with the stats QJsonObject QJsonObject statsObject = @@ -848,14 +845,14 @@ bool DomainServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url // pull the captured string, if it exists QUuid deleteUUID = QUuid(nodeDeleteRegex.cap(1)); - SharedNodePointer nodeToKill = NodeList::getInstance()->nodeWithUUID(deleteUUID); + SharedNodePointer nodeToKill = LimitedNodeList::getInstance()->nodeWithUUID(deleteUUID); if (nodeToKill) { // start with a 200 response connection->respond(HTTPConnection::StatusCode200); // we have a valid UUID and node - kill the node that has this assignment - QMetaObject::invokeMethod(NodeList::getInstance(), "killNodeWithUUID", Q_ARG(const QUuid&, deleteUUID)); + QMetaObject::invokeMethod(LimitedNodeList::getInstance(), "killNodeWithUUID", Q_ARG(const QUuid&, deleteUUID)); // successfully processed request return true; @@ -864,7 +861,7 @@ bool DomainServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url return true; } else if (allNodesDeleteRegex.indexIn(url.path()) != -1) { qDebug() << "Received request to kill all nodes."; - NodeList::getInstance()->eraseAllNodes(); + LimitedNodeList::getInstance()->eraseAllNodes(); return true; } @@ -911,7 +908,7 @@ void DomainServer::nodeKilled(SharedNodePointer node) { // cleanup the connection secrets that we set up for this node (on the other nodes) foreach (const QUuid& otherNodeSessionUUID, nodeData->getSessionSecretHash().keys()) { - SharedNodePointer otherNode = NodeList::getInstance()->nodeWithUUID(otherNodeSessionUUID); + SharedNodePointer otherNode = LimitedNodeList::getInstance()->nodeWithUUID(otherNodeSessionUUID); if (otherNode) { reinterpret_cast(otherNode->getLinkedData())->getSessionSecretHash().remove(node->getUUID()); } @@ -996,7 +993,7 @@ void DomainServer::addStaticAssignmentsToQueue() { bool foundMatchingAssignment = false; // enumerate the nodes and check if there is one with an attached assignment with matching UUID - foreach (const SharedNodePointer& node, NodeList::getInstance()->getNodeHash()) { + foreach (const SharedNodePointer& node, LimitedNodeList::getInstance()->getNodeHash()) { if (node->getUUID() == staticAssignment->data()->getUUID()) { foundMatchingAssignment = true; } diff --git a/libraries/shared/src/LimitedNodeList.cpp b/libraries/shared/src/LimitedNodeList.cpp new file mode 100644 index 0000000000..88fdf18574 --- /dev/null +++ b/libraries/shared/src/LimitedNodeList.cpp @@ -0,0 +1,429 @@ +// +// LimitedNodeList.cpp +// hifi +// +// Created by Stephen Birarda on 2/15/13. +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "AccountManager.h" +#include "Assignment.h" +#include "HifiSockAddr.h" +#include "Logging.h" +#include "LimitedNodeList.h" +#include "PacketHeaders.h" +#include "SharedUtil.h" +#include "UUID.h" + +const char SOLO_NODE_TYPES[2] = { + NodeType::AvatarMixer, + NodeType::AudioMixer +}; + +const QUrl DEFAULT_NODE_AUTH_URL = QUrl("https://data-web.highfidelity.io"); + +LimitedNodeList* LimitedNodeList::_sharedInstance = NULL; + +LimitedNodeList* LimitedNodeList::createInstance(unsigned short socketListenPort, unsigned short dtlsPort) { + if (!_sharedInstance) { + NodeType::init(); + + _sharedInstance = new LimitedNodeList(socketListenPort, dtlsPort); + + // register the SharedNodePointer meta-type for signals/slots + qRegisterMetaType(); + } else { + qDebug("NodeList createInstance called with existing instance."); + } + + return _sharedInstance; +} + +LimitedNodeList* LimitedNodeList::getInstance() { + if (!_sharedInstance) { + qDebug("NodeList getInstance called before call to createInstance. Returning NULL pointer."); + } + + return _sharedInstance; +} + + +LimitedNodeList::LimitedNodeList(unsigned short socketListenPort, unsigned short dtlsListenPort) : + _nodeHash(), + _nodeHashMutex(QMutex::Recursive), + _nodeSocket(this), + _dtlsSocket(NULL), + _numCollectedPackets(0), + _numCollectedBytes(0), + _packetStatTimer() +{ + _nodeSocket.bind(QHostAddress::AnyIPv4, socketListenPort); + qDebug() << "NodeList socket is listening on" << _nodeSocket.localPort(); + + if (dtlsListenPort > 0) { + // only create the DTLS socket during constructor if a custom port is passed + _dtlsSocket = new QUdpSocket(this); + + _dtlsSocket->bind(QHostAddress::AnyIPv4, dtlsListenPort); + qDebug() << "NodeList DTLS socket is listening on" << _dtlsSocket->localPort(); + } + + const int LARGER_SNDBUF_SIZE = 1048576; + changeSendSocketBufferSize(LARGER_SNDBUF_SIZE); + + _packetStatTimer.start(); +} + +QUdpSocket& LimitedNodeList::getDTLSSocket() { + if (!_dtlsSocket) { + // DTLS socket getter called but no DTLS socket exists, create it now + _dtlsSocket = new QUdpSocket(this); + + _dtlsSocket->bind(QHostAddress::AnyIPv4, 0, QAbstractSocket::DontShareAddress); + qDebug() << "NodeList DTLS socket is listening on" << _dtlsSocket->localPort(); + } + + return *_dtlsSocket; +} + +void LimitedNodeList::changeSendSocketBufferSize(int numSendBytes) { + // change the socket send buffer size to be 1MB + int oldBufferSize = 0; + +#ifdef Q_OS_WIN + int sizeOfInt = sizeof(oldBufferSize); +#else + unsigned int sizeOfInt = sizeof(oldBufferSize); +#endif + + getsockopt(_nodeSocket.socketDescriptor(), SOL_SOCKET, SO_SNDBUF, reinterpret_cast(&oldBufferSize), &sizeOfInt); + + setsockopt(_nodeSocket.socketDescriptor(), SOL_SOCKET, SO_SNDBUF, reinterpret_cast(&numSendBytes), + sizeof(numSendBytes)); + + int newBufferSize = 0; + getsockopt(_nodeSocket.socketDescriptor(), SOL_SOCKET, SO_SNDBUF, reinterpret_cast(&newBufferSize), &sizeOfInt); + + qDebug() << "Changed socket send buffer size from" << oldBufferSize << "to" << newBufferSize << "bytes"; +} + +bool LimitedNodeList::packetVersionAndHashMatch(const QByteArray& packet) { + PacketType checkType = packetTypeForPacket(packet); + if (packet[1] != versionForPacketType(checkType) + && checkType != PacketTypeStunResponse) { + PacketType mismatchType = packetTypeForPacket(packet); + int numPacketTypeBytes = numBytesArithmeticCodingFromBuffer(packet.data()); + + static QMultiMap versionDebugSuppressMap; + + QUuid senderUUID = uuidFromPacketHeader(packet); + if (!versionDebugSuppressMap.contains(senderUUID, checkType)) { + qDebug() << "Packet version mismatch on" << packetTypeForPacket(packet) << "- Sender" + << uuidFromPacketHeader(packet) << "sent" << qPrintable(QString::number(packet[numPacketTypeBytes])) << "but" + << qPrintable(QString::number(versionForPacketType(mismatchType))) << "expected."; + + versionDebugSuppressMap.insert(senderUUID, checkType); + } + + return false; + } + + if (!NON_VERIFIED_PACKETS.contains(checkType)) { + // figure out which node this is from + SharedNodePointer sendingNode = sendingNodeForPacket(packet); + if (sendingNode) { + // check if the md5 hash in the header matches the hash we would expect + if (hashFromPacketHeader(packet) == hashForPacketAndConnectionUUID(packet, sendingNode->getConnectionSecret())) { + return true; + } else { + qDebug() << "Packet hash mismatch on" << checkType << "- Sender" + << uuidFromPacketHeader(packet); + } + } else { + qDebug() << "Packet of type" << checkType << "received from unknown node with UUID" + << uuidFromPacketHeader(packet); + } + } else { + return true; + } + + return false; +} + +qint64 LimitedNodeList::writeDatagram(const QByteArray& datagram, const HifiSockAddr& destinationSockAddr, + const QUuid& connectionSecret) { + QByteArray datagramCopy = datagram; + + if (!connectionSecret.isNull()) { + // setup the MD5 hash for source verification in the header + replaceHashInPacketGivenConnectionUUID(datagramCopy, connectionSecret); + } + + // stat collection for packets + ++_numCollectedPackets; + _numCollectedBytes += datagram.size(); + + qint64 bytesWritten = _nodeSocket.writeDatagram(datagramCopy, + destinationSockAddr.getAddress(), destinationSockAddr.getPort()); + + if (bytesWritten < 0) { + qDebug() << "ERROR in writeDatagram:" << _nodeSocket.error() << "-" << _nodeSocket.errorString(); + } + + return bytesWritten; +} + +qint64 LimitedNodeList::writeDatagram(const QByteArray& datagram, const SharedNodePointer& destinationNode, + const HifiSockAddr& overridenSockAddr) { + if (destinationNode) { + // if we don't have an ovveriden address, assume they want to send to the node's active socket + const HifiSockAddr* destinationSockAddr = &overridenSockAddr; + if (overridenSockAddr.isNull()) { + if (destinationNode->getActiveSocket()) { + // use the node's active socket as the destination socket + destinationSockAddr = destinationNode->getActiveSocket(); + } else { + // we don't have a socket to send to, return 0 + return 0; + } + } + + writeDatagram(datagram, *destinationSockAddr, destinationNode->getConnectionSecret()); + } + + // didn't have a destinationNode to send to, return 0 + return 0; +} + +qint64 LimitedNodeList::writeUnverifiedDatagram(const QByteArray& datagram, const HifiSockAddr& destinationSockAddr) { + return writeDatagram(datagram, destinationSockAddr, QUuid()); +} + +qint64 LimitedNodeList::writeDatagram(const char* data, qint64 size, const SharedNodePointer& destinationNode, + const HifiSockAddr& overridenSockAddr) { + return writeDatagram(QByteArray(data, size), destinationNode, overridenSockAddr); +} + +void LimitedNodeList::processNodeData(const HifiSockAddr& senderSockAddr, const QByteArray& packet) { + // the node decided not to do anything with this packet + // if it comes from a known source we should keep that node alive + SharedNodePointer matchingNode = sendingNodeForPacket(packet); + if (matchingNode) { + matchingNode->setLastHeardMicrostamp(usecTimestampNow()); + } +} + +int LimitedNodeList::updateNodeWithDataFromPacket(const SharedNodePointer& matchingNode, const QByteArray &packet) { + QMutexLocker locker(&matchingNode->getMutex()); + + matchingNode->setLastHeardMicrostamp(usecTimestampNow()); + matchingNode->recordBytesReceived(packet.size()); + + if (!matchingNode->getLinkedData() && linkedDataCreateCallback) { + linkedDataCreateCallback(matchingNode.data()); + } + + QMutexLocker linkedDataLocker(&matchingNode->getLinkedData()->getMutex()); + + return matchingNode->getLinkedData()->parseData(packet); +} + +int LimitedNodeList::findNodeAndUpdateWithDataFromPacket(const QByteArray& packet) { + SharedNodePointer matchingNode = sendingNodeForPacket(packet); + + if (matchingNode) { + updateNodeWithDataFromPacket(matchingNode, packet); + } + + // we weren't able to match the sender address to the address we have for this node, unlock and don't parse + return 0; +} + +SharedNodePointer LimitedNodeList::nodeWithUUID(const QUuid& nodeUUID, bool blockingLock) { + const int WAIT_TIME = 10; // wait up to 10ms in the try lock case + SharedNodePointer node; + // if caller wants us to block and guarantee the correct answer, then honor that request + if (blockingLock) { + // this will block till we can get access + QMutexLocker locker(&_nodeHashMutex); + node = _nodeHash.value(nodeUUID); + } else if (_nodeHashMutex.tryLock(WAIT_TIME)) { // some callers are willing to get wrong answers but not block + node = _nodeHash.value(nodeUUID); + _nodeHashMutex.unlock(); + } + return node; + } + +SharedNodePointer LimitedNodeList::sendingNodeForPacket(const QByteArray& packet) { + QUuid nodeUUID = uuidFromPacketHeader(packet); + + // return the matching node, or NULL if there is no match + return nodeWithUUID(nodeUUID); +} + +NodeHash LimitedNodeList::getNodeHash() { + QMutexLocker locker(&_nodeHashMutex); + return NodeHash(_nodeHash); +} + +void LimitedNodeList::eraseAllNodes() { + qDebug() << "Clearing the NodeList. Deleting all nodes in list."; + + QMutexLocker locker(&_nodeHashMutex); + + NodeHash::iterator nodeItem = _nodeHash.begin(); + + // iterate the nodes in the list + while (nodeItem != _nodeHash.end()) { + nodeItem = killNodeAtHashIterator(nodeItem); + } +} + +void LimitedNodeList::reset() { + eraseAllNodes(); +} + +void LimitedNodeList::killNodeWithUUID(const QUuid& nodeUUID) { + QMutexLocker locker(&_nodeHashMutex); + + NodeHash::iterator nodeItemToKill = _nodeHash.find(nodeUUID); + if (nodeItemToKill != _nodeHash.end()) { + killNodeAtHashIterator(nodeItemToKill); + } +} + +NodeHash::iterator LimitedNodeList::killNodeAtHashIterator(NodeHash::iterator& nodeItemToKill) { + qDebug() << "Killed" << *nodeItemToKill.value(); + emit nodeKilled(nodeItemToKill.value()); + return _nodeHash.erase(nodeItemToKill); +} + +void LimitedNodeList::processKillNode(const QByteArray& dataByteArray) { + // read the node id + QUuid nodeUUID = QUuid::fromRfc4122(dataByteArray.mid(numBytesForPacketHeader(dataByteArray), NUM_BYTES_RFC4122_UUID)); + + // kill the node with this UUID, if it exists + killNodeWithUUID(nodeUUID); +} + +SharedNodePointer LimitedNodeList::addOrUpdateNode(const QUuid& uuid, char nodeType, + const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket) { + _nodeHashMutex.lock(); + + if (!_nodeHash.contains(uuid)) { + + // we didn't have this node, so add them + Node* newNode = new Node(uuid, nodeType, publicSocket, localSocket); + SharedNodePointer newNodeSharedPointer(newNode, &QObject::deleteLater); + + _nodeHash.insert(newNode->getUUID(), newNodeSharedPointer); + + _nodeHashMutex.unlock(); + + qDebug() << "Added" << *newNode; + + emit nodeAdded(newNodeSharedPointer); + + return newNodeSharedPointer; + } else { + _nodeHashMutex.unlock(); + + return updateSocketsForNode(uuid, publicSocket, localSocket); + } +} + +SharedNodePointer LimitedNodeList::updateSocketsForNode(const QUuid& uuid, + const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket) { + + SharedNodePointer matchingNode = nodeWithUUID(uuid); + + if (matchingNode) { + // perform appropriate updates to this node + QMutexLocker locker(&matchingNode->getMutex()); + + // check if we need to change this node's public or local sockets + if (publicSocket != matchingNode->getPublicSocket()) { + matchingNode->setPublicSocket(publicSocket); + qDebug() << "Public socket change for node" << *matchingNode; + } + + if (localSocket != matchingNode->getLocalSocket()) { + matchingNode->setLocalSocket(localSocket); + qDebug() << "Local socket change for node" << *matchingNode; + } + } + + return matchingNode; +} + +unsigned LimitedNodeList::broadcastToNodes(const QByteArray& packet, const NodeSet& destinationNodeTypes) { + unsigned n = 0; + + foreach (const SharedNodePointer& node, getNodeHash()) { + // only send to the NodeTypes we are asked to send to. + if (destinationNodeTypes.contains(node->getType())) { + writeDatagram(packet, node); + ++n; + } + } + + return n; +} + +SharedNodePointer LimitedNodeList::soloNodeOfType(char nodeType) { + + if (memchr(SOLO_NODE_TYPES, nodeType, sizeof(SOLO_NODE_TYPES))) { + foreach (const SharedNodePointer& node, getNodeHash()) { + if (node->getType() == nodeType) { + return node; + } + } + } + return SharedNodePointer(); +} + +void LimitedNodeList::getPacketStats(float& packetsPerSecond, float& bytesPerSecond) { + packetsPerSecond = (float) _numCollectedPackets / ((float) _packetStatTimer.elapsed() / 1000.0f); + bytesPerSecond = (float) _numCollectedBytes / ((float) _packetStatTimer.elapsed() / 1000.0f); +} + +void LimitedNodeList::resetPacketStats() { + _numCollectedPackets = 0; + _numCollectedBytes = 0; + _packetStatTimer.restart(); +} + +void LimitedNodeList::removeSilentNodes() { + + _nodeHashMutex.lock(); + + NodeHash::iterator nodeItem = _nodeHash.begin(); + + while (nodeItem != _nodeHash.end()) { + SharedNodePointer node = nodeItem.value(); + + node->getMutex().lock(); + + if ((usecTimestampNow() - node->getLastHeardMicrostamp()) > NODE_SILENCE_THRESHOLD_USECS) { + // call our private method to kill this node (removes it and emits the right signal) + nodeItem = killNodeAtHashIterator(nodeItem); + } else { + // we didn't kill this node, push the iterator forwards + ++nodeItem; + } + + node->getMutex().unlock(); + } + + _nodeHashMutex.unlock(); +} diff --git a/libraries/shared/src/LimitedNodeList.h b/libraries/shared/src/LimitedNodeList.h new file mode 100644 index 0000000000..1c4035be47 --- /dev/null +++ b/libraries/shared/src/LimitedNodeList.h @@ -0,0 +1,128 @@ +// +// LimitedNodeList.h +// hifi +// +// Created by Stephen Birarda on 2/15/13. +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// + +#ifndef __hifi__LimitedNodeList__ +#define __hifi__LimitedNodeList__ + +#ifdef _WIN32 +#include "Syssocket.h" +#else +#include +#endif +#include +#include + +#ifndef _WIN32 +#include // not on windows, not needed for mac or windows +#endif + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "DomainHandler.h" +#include "Node.h" + +const quint64 NODE_SILENCE_THRESHOLD_USECS = 2 * 1000 * 1000; + +extern const char SOLO_NODE_TYPES[2]; + +extern const QUrl DEFAULT_NODE_AUTH_URL; + +const char DEFAULT_ASSIGNMENT_SERVER_HOSTNAME[] = "localhost"; + +class HifiSockAddr; + +typedef QSet NodeSet; + +typedef QSharedPointer SharedNodePointer; +typedef QHash NodeHash; +Q_DECLARE_METATYPE(SharedNodePointer) + +class LimitedNodeList : public QObject { + Q_OBJECT +public: + static LimitedNodeList* createInstance(unsigned short socketListenPort = 0, unsigned short dtlsPort = 0); + static LimitedNodeList* getInstance(); + + QUdpSocket& getNodeSocket() { return _nodeSocket; } + QUdpSocket& getDTLSSocket(); + + bool packetVersionAndHashMatch(const QByteArray& packet); + + qint64 writeDatagram(const QByteArray& datagram, const SharedNodePointer& destinationNode, + const HifiSockAddr& overridenSockAddr = HifiSockAddr()); + qint64 writeUnverifiedDatagram(const QByteArray& datagram, const HifiSockAddr& destinationSockAddr); + qint64 writeDatagram(const char* data, qint64 size, const SharedNodePointer& destinationNode, + const HifiSockAddr& overridenSockAddr = HifiSockAddr()); + + void(*linkedDataCreateCallback)(Node *); + + NodeHash getNodeHash(); + int size() const { return _nodeHash.size(); } + + SharedNodePointer nodeWithUUID(const QUuid& nodeUUID, bool blockingLock = true); + SharedNodePointer sendingNodeForPacket(const QByteArray& packet); + + SharedNodePointer addOrUpdateNode(const QUuid& uuid, char nodeType, + const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket); + SharedNodePointer updateSocketsForNode(const QUuid& uuid, + const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket); + + void processNodeData(const HifiSockAddr& senderSockAddr, const QByteArray& packet); + void processKillNode(const QByteArray& datagram); + + int updateNodeWithDataFromPacket(const SharedNodePointer& matchingNode, const QByteArray& packet); + int findNodeAndUpdateWithDataFromPacket(const QByteArray& packet); + + unsigned broadcastToNodes(const QByteArray& packet, const NodeSet& destinationNodeTypes); + SharedNodePointer soloNodeOfType(char nodeType); + + void getPacketStats(float &packetsPerSecond, float &bytesPerSecond); + void resetPacketStats(); +public slots: + void reset(); + void eraseAllNodes(); + + void removeSilentNodes(); + + void killNodeWithUUID(const QUuid& nodeUUID); +signals: + void nodeAdded(SharedNodePointer); + void nodeKilled(SharedNodePointer); +protected: + static LimitedNodeList* _sharedInstance; + + LimitedNodeList(unsigned short socketListenPort, unsigned short dtlsListenPort); + LimitedNodeList(LimitedNodeList const&); // Don't implement, needed to avoid copies of singleton + void operator=(LimitedNodeList const&); // Don't implement, needed to avoid copies of singleton + + qint64 writeDatagram(const QByteArray& datagram, const HifiSockAddr& destinationSockAddr, + const QUuid& connectionSecret); + + NodeHash::iterator killNodeAtHashIterator(NodeHash::iterator& nodeItemToKill); + + + void changeSendSocketBufferSize(int numSendBytes); + + NodeHash _nodeHash; + QMutex _nodeHashMutex; + QUdpSocket _nodeSocket; + QUdpSocket* _dtlsSocket; + int _numCollectedPackets; + int _numCollectedBytes; + QElapsedTimer _packetStatTimer; +}; + +#endif /* defined(__hifi__LimitedNodeList__) */ diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 7cf58385fe..0b94e1b774 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -6,10 +6,6 @@ // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. // -#include -#include -#include - #include #include #include @@ -25,13 +21,6 @@ #include "SharedUtil.h" #include "UUID.h" -const char SOLO_NODE_TYPES[2] = { - NodeType::AvatarMixer, - NodeType::AudioMixer -}; - -const QUrl DEFAULT_NODE_AUTH_URL = QUrl("https://data-web.highfidelity.io"); - NodeList* NodeList::_sharedInstance = NULL; NodeList* NodeList::createInstance(char ownerType, unsigned short socketListenPort, unsigned short dtlsPort) { @@ -57,12 +46,8 @@ NodeList* NodeList::getInstance() { return _sharedInstance; } - NodeList::NodeList(char newOwnerType, unsigned short socketListenPort, unsigned short dtlsListenPort) : - _nodeHash(), - _nodeHashMutex(QMutex::Recursive), - _nodeSocket(this), - _dtlsSocket(NULL), + LimitedNodeList(socketListenPort, dtlsListenPort), _ownerType(newOwnerType), _nodeTypesOfInterest(), _sessionUUID(), @@ -70,162 +55,13 @@ NodeList::NodeList(char newOwnerType, unsigned short socketListenPort, unsigned _assignmentServerSocket(), _publicSockAddr(), _hasCompletedInitialSTUNFailure(false), - _stunRequestsSinceSuccess(0), - _numCollectedPackets(0), - _numCollectedBytes(0), - _packetStatTimer() + _stunRequestsSinceSuccess(0) { - _nodeSocket.bind(QHostAddress::AnyIPv4, socketListenPort); - qDebug() << "NodeList socket is listening on" << _nodeSocket.localPort(); - - if (dtlsListenPort > 0) { - // only create the DTLS socket during constructor if a custom port is passed - _dtlsSocket = new QUdpSocket(this); - - _dtlsSocket->bind(QHostAddress::AnyIPv4, dtlsListenPort); - qDebug() << "NodeList DTLS socket is listening on" << _dtlsSocket->localPort(); - } - // clear our NodeList when the domain changes connect(&_DomainHandler, &DomainHandler::hostnameChanged, this, &NodeList::reset); // clear our NodeList when logout is requested connect(&AccountManager::getInstance(), &AccountManager::logoutComplete , this, &NodeList::reset); - - const int LARGER_SNDBUF_SIZE = 1048576; - changeSendSocketBufferSize(LARGER_SNDBUF_SIZE); - - _packetStatTimer.start(); -} - -QUdpSocket& NodeList::getDTLSSocket() { - if (!_dtlsSocket) { - // DTLS socket getter called but no DTLS socket exists, create it now - _dtlsSocket = new QUdpSocket(this); - - _dtlsSocket->bind(QHostAddress::AnyIPv4, 0, QAbstractSocket::DontShareAddress); - qDebug() << "NodeList DTLS socket is listening on" << _dtlsSocket->localPort(); - } - - return *_dtlsSocket; -} - -void NodeList::changeSendSocketBufferSize(int numSendBytes) { - // change the socket send buffer size to be 1MB - int oldBufferSize = 0; - -#ifdef Q_OS_WIN - int sizeOfInt = sizeof(oldBufferSize); -#else - unsigned int sizeOfInt = sizeof(oldBufferSize); -#endif - - getsockopt(_nodeSocket.socketDescriptor(), SOL_SOCKET, SO_SNDBUF, reinterpret_cast(&oldBufferSize), &sizeOfInt); - - setsockopt(_nodeSocket.socketDescriptor(), SOL_SOCKET, SO_SNDBUF, reinterpret_cast(&numSendBytes), - sizeof(numSendBytes)); - - int newBufferSize = 0; - getsockopt(_nodeSocket.socketDescriptor(), SOL_SOCKET, SO_SNDBUF, reinterpret_cast(&newBufferSize), &sizeOfInt); - - qDebug() << "Changed socket send buffer size from" << oldBufferSize << "to" << newBufferSize << "bytes"; -} - -bool NodeList::packetVersionAndHashMatch(const QByteArray& packet) { - PacketType checkType = packetTypeForPacket(packet); - if (packet[1] != versionForPacketType(checkType) - && checkType != PacketTypeStunResponse) { - PacketType mismatchType = packetTypeForPacket(packet); - int numPacketTypeBytes = numBytesArithmeticCodingFromBuffer(packet.data()); - - static QMultiMap versionDebugSuppressMap; - - QUuid senderUUID = uuidFromPacketHeader(packet); - if (!versionDebugSuppressMap.contains(senderUUID, checkType)) { - qDebug() << "Packet version mismatch on" << packetTypeForPacket(packet) << "- Sender" - << uuidFromPacketHeader(packet) << "sent" << qPrintable(QString::number(packet[numPacketTypeBytes])) << "but" - << qPrintable(QString::number(versionForPacketType(mismatchType))) << "expected."; - - versionDebugSuppressMap.insert(senderUUID, checkType); - } - - return false; - } - - if (!NON_VERIFIED_PACKETS.contains(checkType)) { - // figure out which node this is from - SharedNodePointer sendingNode = sendingNodeForPacket(packet); - if (sendingNode) { - // check if the md5 hash in the header matches the hash we would expect - if (hashFromPacketHeader(packet) == hashForPacketAndConnectionUUID(packet, sendingNode->getConnectionSecret())) { - return true; - } else { - qDebug() << "Packet hash mismatch on" << checkType << "- Sender" - << uuidFromPacketHeader(packet); - } - } else { - qDebug() << "Packet of type" << checkType << "received from unknown node with UUID" - << uuidFromPacketHeader(packet); - } - } else { - return true; - } - - return false; -} - -qint64 NodeList::writeDatagram(const QByteArray& datagram, const HifiSockAddr& destinationSockAddr, - const QUuid& connectionSecret) { - QByteArray datagramCopy = datagram; - - if (!connectionSecret.isNull()) { - // setup the MD5 hash for source verification in the header - replaceHashInPacketGivenConnectionUUID(datagramCopy, connectionSecret); - } - - // stat collection for packets - ++_numCollectedPackets; - _numCollectedBytes += datagram.size(); - - qint64 bytesWritten = _nodeSocket.writeDatagram(datagramCopy, - destinationSockAddr.getAddress(), destinationSockAddr.getPort()); - - if (bytesWritten < 0) { - qDebug() << "ERROR in writeDatagram:" << _nodeSocket.error() << "-" << _nodeSocket.errorString(); - } - - return bytesWritten; -} - -qint64 NodeList::writeDatagram(const QByteArray& datagram, const SharedNodePointer& destinationNode, - const HifiSockAddr& overridenSockAddr) { - if (destinationNode) { - // if we don't have an ovveriden address, assume they want to send to the node's active socket - const HifiSockAddr* destinationSockAddr = &overridenSockAddr; - if (overridenSockAddr.isNull()) { - if (destinationNode->getActiveSocket()) { - // use the node's active socket as the destination socket - destinationSockAddr = destinationNode->getActiveSocket(); - } else { - // we don't have a socket to send to, return 0 - return 0; - } - } - - writeDatagram(datagram, *destinationSockAddr, destinationNode->getConnectionSecret()); - } - - // didn't have a destinationNode to send to, return 0 - return 0; -} - -qint64 NodeList::writeUnverifiedDatagram(const QByteArray& datagram, const HifiSockAddr& destinationSockAddr) { - return writeDatagram(datagram, destinationSockAddr, QUuid()); -} - -qint64 NodeList::writeDatagram(const char* data, qint64 size, const SharedNodePointer& destinationNode, - const HifiSockAddr& overridenSockAddr) { - return writeDatagram(QByteArray(data, size), destinationNode, overridenSockAddr); } qint64 NodeList::sendStatsToDomainServer(const QJsonObject& statsObject) { @@ -315,85 +151,14 @@ void NodeList::processNodeData(const HifiSockAddr& senderSockAddr, const QByteAr break; } default: - // the node decided not to do anything with this packet - // if it comes from a known source we should keep that node alive - SharedNodePointer matchingNode = sendingNodeForPacket(packet); - if (matchingNode) { - matchingNode->setLastHeardMicrostamp(usecTimestampNow()); - } - + LimitedNodeList::processNodeData(senderSockAddr, packet); break; } } -int NodeList::updateNodeWithDataFromPacket(const SharedNodePointer& matchingNode, const QByteArray &packet) { - QMutexLocker locker(&matchingNode->getMutex()); - - matchingNode->setLastHeardMicrostamp(usecTimestampNow()); - matchingNode->recordBytesReceived(packet.size()); - - if (!matchingNode->getLinkedData() && linkedDataCreateCallback) { - linkedDataCreateCallback(matchingNode.data()); - } - - QMutexLocker linkedDataLocker(&matchingNode->getLinkedData()->getMutex()); - - return matchingNode->getLinkedData()->parseData(packet); -} - -int NodeList::findNodeAndUpdateWithDataFromPacket(const QByteArray& packet) { - SharedNodePointer matchingNode = sendingNodeForPacket(packet); - - if (matchingNode) { - updateNodeWithDataFromPacket(matchingNode, packet); - } - - // we weren't able to match the sender address to the address we have for this node, unlock and don't parse - return 0; -} - -SharedNodePointer NodeList::nodeWithUUID(const QUuid& nodeUUID, bool blockingLock) { - const int WAIT_TIME = 10; // wait up to 10ms in the try lock case - SharedNodePointer node; - // if caller wants us to block and guarantee the correct answer, then honor that request - if (blockingLock) { - // this will block till we can get access - QMutexLocker locker(&_nodeHashMutex); - node = _nodeHash.value(nodeUUID); - } else if (_nodeHashMutex.tryLock(WAIT_TIME)) { // some callers are willing to get wrong answers but not block - node = _nodeHash.value(nodeUUID); - _nodeHashMutex.unlock(); - } - return node; - } - -SharedNodePointer NodeList::sendingNodeForPacket(const QByteArray& packet) { - QUuid nodeUUID = uuidFromPacketHeader(packet); - - // return the matching node, or NULL if there is no match - return nodeWithUUID(nodeUUID); -} - -NodeHash NodeList::getNodeHash() { - QMutexLocker locker(&_nodeHashMutex); - return NodeHash(_nodeHash); -} - -void NodeList::eraseAllNodes() { - qDebug() << "Clearing the NodeList. Deleting all nodes in list."; - - QMutexLocker locker(&_nodeHashMutex); - - NodeHash::iterator nodeItem = _nodeHash.begin(); - - // iterate the nodes in the list - while (nodeItem != _nodeHash.end()) { - nodeItem = killNodeAtHashIterator(nodeItem); - } -} - void NodeList::reset() { - eraseAllNodes(); + LimitedNodeList::reset(); + _numNoReplyDomainCheckIns = 0; // refresh the owner UUID to the NULL UUID @@ -547,29 +312,6 @@ void NodeList::processSTUNResponse(const QByteArray& packet) { } } -void NodeList::killNodeWithUUID(const QUuid& nodeUUID) { - QMutexLocker locker(&_nodeHashMutex); - - NodeHash::iterator nodeItemToKill = _nodeHash.find(nodeUUID); - if (nodeItemToKill != _nodeHash.end()) { - killNodeAtHashIterator(nodeItemToKill); - } -} - -NodeHash::iterator NodeList::killNodeAtHashIterator(NodeHash::iterator& nodeItemToKill) { - qDebug() << "Killed" << *nodeItemToKill.value(); - emit nodeKilled(nodeItemToKill.value()); - return _nodeHash.erase(nodeItemToKill); -} - -void NodeList::processKillNode(const QByteArray& dataByteArray) { - // read the node id - QUuid nodeUUID = QUuid::fromRfc4122(dataByteArray.mid(numBytesForPacketHeader(dataByteArray), NUM_BYTES_RFC4122_UUID)); - - // kill the node with this UUID, if it exists - killNodeWithUUID(nodeUUID); -} - void NodeList::sendDomainServerCheckIn() { if (_publicSockAddr.isNull() && !_hasCompletedInitialSTUNFailure) { // we don't know our public socket and we need to send it to the domain server @@ -734,70 +476,6 @@ void NodeList::pingPublicAndLocalSocketsForInactiveNode(const SharedNodePointer& writeDatagram(publicPingPacket, node, node->getPublicSocket()); } -SharedNodePointer NodeList::addOrUpdateNode(const QUuid& uuid, char nodeType, - const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket) { - _nodeHashMutex.lock(); - - if (!_nodeHash.contains(uuid)) { - - // we didn't have this node, so add them - Node* newNode = new Node(uuid, nodeType, publicSocket, localSocket); - SharedNodePointer newNodeSharedPointer(newNode, &QObject::deleteLater); - - _nodeHash.insert(newNode->getUUID(), newNodeSharedPointer); - - _nodeHashMutex.unlock(); - - qDebug() << "Added" << *newNode; - - emit nodeAdded(newNodeSharedPointer); - - return newNodeSharedPointer; - } else { - _nodeHashMutex.unlock(); - - return updateSocketsForNode(uuid, publicSocket, localSocket); - } -} - -SharedNodePointer NodeList::updateSocketsForNode(const QUuid& uuid, - const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket) { - - SharedNodePointer matchingNode = nodeWithUUID(uuid); - - if (matchingNode) { - // perform appropriate updates to this node - QMutexLocker locker(&matchingNode->getMutex()); - - // check if we need to change this node's public or local sockets - if (publicSocket != matchingNode->getPublicSocket()) { - matchingNode->setPublicSocket(publicSocket); - qDebug() << "Public socket change for node" << *matchingNode; - } - - if (localSocket != matchingNode->getLocalSocket()) { - matchingNode->setLocalSocket(localSocket); - qDebug() << "Local socket change for node" << *matchingNode; - } - } - - return matchingNode; -} - -unsigned NodeList::broadcastToNodes(const QByteArray& packet, const NodeSet& destinationNodeTypes) { - unsigned n = 0; - - foreach (const SharedNodePointer& node, getNodeHash()) { - // only send to the NodeTypes we are asked to send to. - if (destinationNodeTypes.contains(node->getType())) { - writeDatagram(packet, node); - ++n; - } - } - - return n; -} - void NodeList::pingInactiveNodes() { foreach (const SharedNodePointer& node, getNodeHash()) { if (!node->getActiveSocket()) { @@ -824,54 +502,6 @@ void NodeList::activateSocketFromNodeCommunication(const QByteArray& packet, con } } -SharedNodePointer NodeList::soloNodeOfType(char nodeType) { - - if (memchr(SOLO_NODE_TYPES, nodeType, sizeof(SOLO_NODE_TYPES))) { - foreach (const SharedNodePointer& node, getNodeHash()) { - if (node->getType() == nodeType) { - return node; - } - } - } - return SharedNodePointer(); -} - -void NodeList::getPacketStats(float& packetsPerSecond, float& bytesPerSecond) { - packetsPerSecond = (float) _numCollectedPackets / ((float) _packetStatTimer.elapsed() / 1000.0f); - bytesPerSecond = (float) _numCollectedBytes / ((float) _packetStatTimer.elapsed() / 1000.0f); -} - -void NodeList::resetPacketStats() { - _numCollectedPackets = 0; - _numCollectedBytes = 0; - _packetStatTimer.restart(); -} - -void NodeList::removeSilentNodes() { - - _nodeHashMutex.lock(); - - NodeHash::iterator nodeItem = _nodeHash.begin(); - - while (nodeItem != _nodeHash.end()) { - SharedNodePointer node = nodeItem.value(); - - node->getMutex().lock(); - - if ((usecTimestampNow() - node->getLastHeardMicrostamp()) > NODE_SILENCE_THRESHOLD_USECS) { - // call our private method to kill this node (removes it and emits the right signal) - nodeItem = killNodeAtHashIterator(nodeItem); - } else { - // we didn't kill this node, push the iterator forwards - ++nodeItem; - } - - node->getMutex().unlock(); - } - - _nodeHashMutex.unlock(); -} - const QString QSETTINGS_GROUP_NAME = "NodeList"; const QString DOMAIN_SERVER_SETTING_KEY = "domainServerHostname"; diff --git a/libraries/shared/src/NodeList.h b/libraries/shared/src/NodeList.h index 9c19e33ed9..bc22c97904 100644 --- a/libraries/shared/src/NodeList.h +++ b/libraries/shared/src/NodeList.h @@ -32,28 +32,14 @@ #include #include "DomainHandler.h" +#include "LimitedNodeList.h" #include "Node.h" -const quint64 NODE_SILENCE_THRESHOLD_USECS = 2 * 1000 * 1000; const quint64 DOMAIN_SERVER_CHECK_IN_USECS = 1 * 1000000; -const quint64 PING_INACTIVE_NODE_INTERVAL_USECS = 1 * 1000 * 1000; - -extern const char SOLO_NODE_TYPES[2]; - -extern const QUrl DEFAULT_NODE_AUTH_URL; - -const char DEFAULT_ASSIGNMENT_SERVER_HOSTNAME[] = "localhost"; const int MAX_SILENT_DOMAIN_SERVER_CHECK_INS = 5; class Assignment; -class HifiSockAddr; - -typedef QSet NodeSet; - -typedef QSharedPointer SharedNodePointer; -typedef QHash NodeHash; -Q_DECLARE_METATYPE(SharedNodePointer) typedef quint8 PingType_t; namespace PingType { @@ -62,7 +48,7 @@ namespace PingType { const PingType_t Public = 2; } -class NodeList : public QObject { +class NodeList : public LimitedNodeList { Q_OBJECT public: static NodeList* createInstance(char ownerType, unsigned short socketListenPort = 0, unsigned short dtlsPort = 0); @@ -73,23 +59,8 @@ public: const QUuid& getSessionUUID() const { return _sessionUUID; } void setSessionUUID(const QUuid& sessionUUID); - QUdpSocket& getNodeSocket() { return _nodeSocket; } - QUdpSocket& getDTLSSocket(); - - bool packetVersionAndHashMatch(const QByteArray& packet); - - qint64 writeDatagram(const QByteArray& datagram, const SharedNodePointer& destinationNode, - const HifiSockAddr& overridenSockAddr = HifiSockAddr()); - qint64 writeUnverifiedDatagram(const QByteArray& datagram, const HifiSockAddr& destinationSockAddr); - qint64 writeDatagram(const char* data, qint64 size, const SharedNodePointer& destinationNode, - const HifiSockAddr& overridenSockAddr = HifiSockAddr()); qint64 sendStatsToDomainServer(const QJsonObject& statsObject); - void(*linkedDataCreateCallback)(Node *); - - NodeHash getNodeHash(); - int size() const { return _nodeHash.size(); } - int getNumNoReplyDomainCheckIns() const { return _numNoReplyDomainCheckIns; } DomainHandler& getDomainHandler() { return _DomainHandler; } @@ -98,6 +69,7 @@ public: void addSetOfNodeTypesToNodeInterestSet(const NodeSet& setOfNodeTypes); void resetNodeInterestSet() { _nodeTypesOfInterest.clear(); } + void processNodeData(const HifiSockAddr& senderSockAddr, const QByteArray& packet); int processDomainServerList(const QByteArray& packet); void setAssignmentServerSocket(const HifiSockAddr& serverSocket) { _assignmentServerSocket = serverSocket; } @@ -106,42 +78,15 @@ public: QByteArray constructPingPacket(PingType_t pingType = PingType::Agnostic); QByteArray constructPingReplyPacket(const QByteArray& pingPacket); void pingPublicAndLocalSocketsForInactiveNode(const SharedNodePointer& node); - - SharedNodePointer nodeWithUUID(const QUuid& nodeUUID, bool blockingLock = true); - SharedNodePointer sendingNodeForPacket(const QByteArray& packet); - - SharedNodePointer addOrUpdateNode(const QUuid& uuid, char nodeType, - const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket); - SharedNodePointer updateSocketsForNode(const QUuid& uuid, - const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket); - - void processNodeData(const HifiSockAddr& senderSockAddr, const QByteArray& packet); - void processKillNode(const QByteArray& datagram); - - int updateNodeWithDataFromPacket(const SharedNodePointer& matchingNode, const QByteArray& packet); - int findNodeAndUpdateWithDataFromPacket(const QByteArray& packet); - - unsigned broadcastToNodes(const QByteArray& packet, const NodeSet& destinationNodeTypes); - SharedNodePointer soloNodeOfType(char nodeType); - - void getPacketStats(float &packetsPerSecond, float &bytesPerSecond); - void resetPacketStats(); void loadData(QSettings* settings); void saveData(QSettings* settings); public slots: void reset(); - void eraseAllNodes(); - void sendDomainServerCheckIn(); void pingInactiveNodes(); - void removeSilentNodes(); - - void killNodeWithUUID(const QUuid& nodeUUID); signals: void uuidChanged(const QUuid& ownerUUID); - void nodeAdded(SharedNodePointer); - void nodeKilled(SharedNodePointer); void limitOfSilentDomainCheckInsReached(); private: static NodeList* _sharedInstance; @@ -152,22 +97,11 @@ private: void sendSTUNRequest(); void processSTUNResponse(const QByteArray& packet); - qint64 writeDatagram(const QByteArray& datagram, const HifiSockAddr& destinationSockAddr, - const QUuid& connectionSecret); - - NodeHash::iterator killNodeAtHashIterator(NodeHash::iterator& nodeItemToKill); - void processDomainServerAuthRequest(const QByteArray& packet); void requestAuthForDomainServer(); void activateSocketFromNodeCommunication(const QByteArray& packet, const SharedNodePointer& sendingNode); void timePingReply(const QByteArray& packet, const SharedNodePointer& sendingNode); - void changeSendSocketBufferSize(int numSendBytes); - - NodeHash _nodeHash; - QMutex _nodeHashMutex; - QUdpSocket _nodeSocket; - QUdpSocket* _dtlsSocket; NodeType_t _ownerType; NodeSet _nodeTypesOfInterest; DomainHandler _DomainHandler; @@ -177,9 +111,6 @@ private: HifiSockAddr _publicSockAddr; bool _hasCompletedInitialSTUNFailure; unsigned int _stunRequestsSinceSuccess; - int _numCollectedPackets; - int _numCollectedBytes; - QElapsedTimer _packetStatTimer; }; #endif /* defined(__hifi__NodeList__) */ From b7695ba050b007e54b5240d3bc1617d0cd67c459 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 13:55:25 -0700 Subject: [PATCH 087/595] more debugging --- assignment-client/src/octree/OctreeServer.cpp | 42 ++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 0958e2fa20..bb0424c27e 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -830,6 +830,18 @@ void OctreeServer::readPendingDatagrams() { quint64 startReadAvailable = usecTimestampNow(); int readDataGrams = 0; + + int queryPackets = 0; + int jurisdictionRequests = 0; + int editPackets = 0; + int nodeListPackets = 0; + + quint64 queryElapsed = 0; + quint64 jurisdictionElapsed = 0; + quint64 editElapsed = 0; + quint64 nodeListElapsed = 0; + + while (readAvailableDatagram(receivedPacket, senderSockAddr)) { readDataGrams++; if (nodeList->packetVersionAndHashMatch(receivedPacket)) { @@ -843,6 +855,8 @@ void OctreeServer::readPendingDatagrams() { } if (packetType == getMyQueryMessageType()) { + quint64 queryStart = usecTimestampNow(); + queryPackets++; // If we got a PacketType_VOXEL_QUERY, then we're talking to an NodeType_t_AVATAR, and we // need to make sure we have it in our nodeList. @@ -860,11 +874,24 @@ void OctreeServer::readPendingDatagrams() { nodeData->initializeOctreeSendThread(sharedAssignment, matchingNode); } } + quint64 queryEnd = usecTimestampNow(); + queryElapsed += (queryEnd - queryStart); } else if (packetType == PacketTypeJurisdictionRequest) { + quint64 jurisdictionStart = usecTimestampNow(); + jurisdictionRequests++; _jurisdictionSender->queueReceivedPacket(matchingNode, receivedPacket); + quint64 jurisdictionEnd = usecTimestampNow(); + jurisdictionElapsed += (jurisdictionEnd - jurisdictionStart); } else if (_octreeInboundPacketProcessor && getOctree()->handlesEditPacketType(packetType)) { + quint64 editStart = usecTimestampNow(); + editPackets++; _octreeInboundPacketProcessor->queueReceivedPacket(matchingNode, receivedPacket); + quint64 editEnd = usecTimestampNow(); + editElapsed += (editEnd - editStart); } else { + quint64 nodeListStart = usecTimestampNow(); + + nodeListPackets++; quint64 now = usecTimestampNow(); if ((now - lastProcessNodeData) > 500000) { qDebug() << "OctreeServer::readPendingDatagrams(): since lastProcessNodeData=" << (now - lastProcessNodeData) << "usecs"; @@ -878,13 +905,26 @@ void OctreeServer::readPendingDatagrams() { if ((endProcessNodeData - startProcessNodeData) > 100000) { qDebug() << "OctreeServer::readPendingDatagrams(): processNodeData() took" << (endProcessNodeData - startProcessNodeData) << "usecs"; } + + quint64 nodeListEnd = usecTimestampNow(); + nodeListElapsed += (nodeListEnd - nodeListStart); } } } quint64 endReadAvailable = usecTimestampNow(); if (endReadAvailable - startReadAvailable > 1000) { qDebug() << "OctreeServer::readPendingDatagrams(): while(readAvailable) took" << (endReadAvailable - startReadAvailable) << "usecs" - << " readDataGrams=" << readDataGrams; + << " readDataGrams=" << readDataGrams + << " nodeListPackets=" << nodeListPackets + << " editPackets=" << editPackets + << " jurisdictionRequests=" << jurisdictionRequests + << " queryPackets=" << queryPackets; + + qDebug() << "OctreeServer::readPendingDatagrams(): while(readAvailable) took" << (endReadAvailable - startReadAvailable) << "usecs" + << " nodeListElapsed=" << nodeListElapsed + << " editElapsed=" << editElapsed + << " jurisdictionElapsed=" << jurisdictionElapsed + << " queryElapsed=" << queryElapsed; } } From 0be2eb57bfef11b35ddaebf0cea577ea038d8465 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 1 Apr 2014 13:56:33 -0700 Subject: [PATCH 088/595] repairs to NodeList and LimitedNodeList --- domain-server/src/DomainServer.cpp | 5 +-- libraries/shared/src/LimitedNodeList.cpp | 16 +++++++-- libraries/shared/src/LimitedNodeList.h | 5 +++ libraries/shared/src/NodeList.cpp | 45 ++++++++---------------- libraries/shared/src/NodeList.h | 9 ++--- libraries/shared/src/PacketHeaders.cpp | 2 +- libraries/shared/src/PacketHeaders.h | 3 +- 7 files changed, 42 insertions(+), 43 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index a32ae76e79..f83b6da97f 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -52,7 +52,7 @@ DomainServer::DomainServer(int argc, char* argv[]) : if (optionallySetupDTLS()) { // we either read a certificate and private key or were not passed one, good to load assignments // and set up the node list - qDebug() << "Setting up NodeList and assignments."; + qDebug() << "Setting up LimitedNodeList and assignments."; setupNodeListAndAssignments(); if (_isUsingDTLS) { @@ -542,7 +542,8 @@ void DomainServer::readAvailableDatagrams() { receivedPacket.resize(nodeList->getNodeSocket().pendingDatagramSize()); nodeList->getNodeSocket().readDatagram(receivedPacket.data(), receivedPacket.size(), senderSockAddr.getAddressPointer(), senderSockAddr.getPortPointer()); - if (packetTypeForPacket(receivedPacket) && nodeList->packetVersionAndHashMatch(receivedPacket)) { + if (packetTypeForPacket(receivedPacket) == PacketTypeRequestAssignment + && nodeList->packetVersionAndHashMatch(receivedPacket)) { // construct the requested assignment from the packet data Assignment requestAssignment(receivedPacket); diff --git a/libraries/shared/src/LimitedNodeList.cpp b/libraries/shared/src/LimitedNodeList.cpp index 88fdf18574..c71f3c13c9 100644 --- a/libraries/shared/src/LimitedNodeList.cpp +++ b/libraries/shared/src/LimitedNodeList.cpp @@ -43,7 +43,7 @@ LimitedNodeList* LimitedNodeList::createInstance(unsigned short socketListenPort // register the SharedNodePointer meta-type for signals/slots qRegisterMetaType(); } else { - qDebug("NodeList createInstance called with existing instance."); + qDebug("LimitedNodeList createInstance called with existing instance."); } return _sharedInstance; @@ -51,7 +51,7 @@ LimitedNodeList* LimitedNodeList::createInstance(unsigned short socketListenPort LimitedNodeList* LimitedNodeList::getInstance() { if (!_sharedInstance) { - qDebug("NodeList getInstance called before call to createInstance. Returning NULL pointer."); + qDebug("LimitedNodeList getInstance called before call to createInstance. Returning NULL pointer."); } return _sharedInstance; @@ -59,6 +59,7 @@ LimitedNodeList* LimitedNodeList::getInstance() { LimitedNodeList::LimitedNodeList(unsigned short socketListenPort, unsigned short dtlsListenPort) : + _sessionUUID(), _nodeHash(), _nodeHashMutex(QMutex::Recursive), _nodeSocket(this), @@ -84,6 +85,17 @@ LimitedNodeList::LimitedNodeList(unsigned short socketListenPort, unsigned short _packetStatTimer.start(); } +void LimitedNodeList::setSessionUUID(const QUuid& sessionUUID) { + QUuid oldUUID = _sessionUUID; + _sessionUUID = sessionUUID; + + if (sessionUUID != oldUUID) { + qDebug() << "NodeList UUID changed from" << uuidStringWithoutCurlyBraces(oldUUID) + << "to" << uuidStringWithoutCurlyBraces(_sessionUUID); + emit uuidChanged(sessionUUID); + } +} + QUdpSocket& LimitedNodeList::getDTLSSocket() { if (!_dtlsSocket) { // DTLS socket getter called but no DTLS socket exists, create it now diff --git a/libraries/shared/src/LimitedNodeList.h b/libraries/shared/src/LimitedNodeList.h index 1c4035be47..544207d1b5 100644 --- a/libraries/shared/src/LimitedNodeList.h +++ b/libraries/shared/src/LimitedNodeList.h @@ -56,6 +56,9 @@ public: static LimitedNodeList* createInstance(unsigned short socketListenPort = 0, unsigned short dtlsPort = 0); static LimitedNodeList* getInstance(); + const QUuid& getSessionUUID() const { return _sessionUUID; } + void setSessionUUID(const QUuid& sessionUUID); + QUdpSocket& getNodeSocket() { return _nodeSocket; } QUdpSocket& getDTLSSocket(); @@ -99,6 +102,7 @@ public slots: void killNodeWithUUID(const QUuid& nodeUUID); signals: + void uuidChanged(const QUuid& ownerUUID); void nodeAdded(SharedNodePointer); void nodeKilled(SharedNodePointer); protected: @@ -116,6 +120,7 @@ protected: void changeSendSocketBufferSize(int numSendBytes); + QUuid _sessionUUID; NodeHash _nodeHash; QMutex _nodeHashMutex; QUdpSocket _nodeSocket; diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 0b94e1b774..3202909447 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -28,6 +28,7 @@ NodeList* NodeList::createInstance(char ownerType, unsigned short socketListenPo NodeType::init(); _sharedInstance = new NodeList(ownerType, socketListenPort, dtlsPort); + LimitedNodeList::_sharedInstance = _sharedInstance; // register the SharedNodePointer meta-type for signals/slots qRegisterMetaType(); @@ -50,7 +51,6 @@ NodeList::NodeList(char newOwnerType, unsigned short socketListenPort, unsigned LimitedNodeList(socketListenPort, dtlsListenPort), _ownerType(newOwnerType), _nodeTypesOfInterest(), - _sessionUUID(), _numNoReplyDomainCheckIns(0), _assignmentServerSocket(), _publicSockAddr(), @@ -58,7 +58,7 @@ NodeList::NodeList(char newOwnerType, unsigned short socketListenPort, unsigned _stunRequestsSinceSuccess(0) { // clear our NodeList when the domain changes - connect(&_DomainHandler, &DomainHandler::hostnameChanged, this, &NodeList::reset); + connect(&_domainHandler, &DomainHandler::hostnameChanged, this, &NodeList::reset); // clear our NodeList when logout is requested connect(&AccountManager::getInstance(), &AccountManager::logoutComplete , this, &NodeList::reset); @@ -70,7 +70,7 @@ qint64 NodeList::sendStatsToDomainServer(const QJsonObject& statsObject) { statsPacketStream << statsObject.toVariantMap(); - return writeDatagram(statsPacket, _DomainHandler.getSockAddr(), QUuid()); + return writeDatagram(statsPacket, _domainHandler.getSockAddr(), QUuid()); } void NodeList::timePingReply(const QByteArray& packet, const SharedNodePointer& sendingNode) { @@ -115,7 +115,7 @@ void NodeList::processNodeData(const HifiSockAddr& senderSockAddr, const QByteAr break; } case PacketTypeDomainServerRequireDTLS: { - _DomainHandler.parseDTLSRequirementPacket(packet); + _domainHandler.parseDTLSRequirementPacket(packet); break; } case PacketTypePing: { @@ -165,7 +165,7 @@ void NodeList::reset() { setSessionUUID(QUuid()); // clear the domain connection information - _DomainHandler.clearConnectionInfo(); + _domainHandler.clearConnectionInfo(); } void NodeList::addNodeTypeToInterestSet(NodeType_t nodeTypeToAdd) { @@ -317,15 +317,11 @@ void NodeList::sendDomainServerCheckIn() { // we don't know our public socket and we need to send it to the domain server // send a STUN request to figure it out sendSTUNRequest(); - } else if (!_DomainHandler.getIP().isNull()) { + } else if (!_domainHandler.getIP().isNull()) { // construct the DS check in packet + QUuid packetUUID = (!_sessionUUID.isNull() ? _sessionUUID : _domainHandler.getAssignmentUUID()); - PacketType domainPacketType = _sessionUUID.isNull() ? PacketTypeDomainConnectRequest : PacketTypeDomainListRequest; - - QUuid packetUUID = (domainPacketType == PacketTypeDomainListRequest) - ? _sessionUUID : _DomainHandler.getAssignmentUUID(); - - QByteArray domainServerPacket = byteArrayWithPopulatedHeader(domainPacketType, packetUUID); + QByteArray domainServerPacket = byteArrayWithPopulatedHeader(PacketTypeDomainListRequest, packetUUID); QDataStream packetStream(&domainServerPacket, QIODevice::Append); // pack our data to send to the domain-server @@ -338,7 +334,7 @@ void NodeList::sendDomainServerCheckIn() { packetStream << nodeTypeOfInterest; } - writeDatagram(domainServerPacket, _DomainHandler.getSockAddr(), QUuid()); + writeDatagram(domainServerPacket, _domainHandler.getSockAddr(), QUuid()); const int NUM_DOMAIN_SERVER_CHECKINS_PER_STUN_REQUEST = 5; static unsigned int numDomainCheckins = 0; @@ -358,23 +354,12 @@ void NodeList::sendDomainServerCheckIn() { } } -void NodeList::setSessionUUID(const QUuid& sessionUUID) { - QUuid oldUUID = _sessionUUID; - _sessionUUID = sessionUUID; - - if (sessionUUID != oldUUID) { - qDebug() << "NodeList UUID changed from" << uuidStringWithoutCurlyBraces(oldUUID) - << "to" << uuidStringWithoutCurlyBraces(_sessionUUID); - emit uuidChanged(sessionUUID); - } -} - int NodeList::processDomainServerList(const QByteArray& packet) { // this is a packet from the domain server, reset the count of un-replied check-ins _numNoReplyDomainCheckIns = 0; // if this was the first domain-server list from this domain, we've now connected - _DomainHandler.setIsConnected(true); + _domainHandler.setIsConnected(true); int readNodes = 0; @@ -401,7 +386,7 @@ int NodeList::processDomainServerList(const QByteArray& packet) { // if the public socket address is 0 then it's reachable at the same IP // as the domain server if (nodePublicSocket.getAddress().isNull()) { - nodePublicSocket.setAddress(_DomainHandler.getIP()); + nodePublicSocket.setAddress(_domainHandler.getIP()); } SharedNodePointer node = addOrUpdateNode(nodeUUID, nodeType, nodePublicSocket, nodeLocalSocket); @@ -511,9 +496,9 @@ void NodeList::loadData(QSettings *settings) { QString domainServerHostname = settings->value(DOMAIN_SERVER_SETTING_KEY).toString(); if (domainServerHostname.size() > 0) { - _DomainHandler.setHostname(domainServerHostname); + _domainHandler.setHostname(domainServerHostname); } else { - _DomainHandler.setHostname(DEFAULT_DOMAIN_HOSTNAME); + _domainHandler.setHostname(DEFAULT_DOMAIN_HOSTNAME); } settings->endGroup(); @@ -522,9 +507,9 @@ void NodeList::loadData(QSettings *settings) { void NodeList::saveData(QSettings* settings) { settings->beginGroup(DOMAIN_SERVER_SETTING_KEY); - if (_DomainHandler.getHostname() != DEFAULT_DOMAIN_HOSTNAME) { + if (_domainHandler.getHostname() != DEFAULT_DOMAIN_HOSTNAME) { // the user is using a different hostname, store it - settings->setValue(DOMAIN_SERVER_SETTING_KEY, QVariant(_DomainHandler.getHostname())); + settings->setValue(DOMAIN_SERVER_SETTING_KEY, QVariant(_domainHandler.getHostname())); } else { // the user has switched back to default, remove the current setting settings->remove(DOMAIN_SERVER_SETTING_KEY); diff --git a/libraries/shared/src/NodeList.h b/libraries/shared/src/NodeList.h index bc22c97904..5ccfc80e35 100644 --- a/libraries/shared/src/NodeList.h +++ b/libraries/shared/src/NodeList.h @@ -56,13 +56,10 @@ public: NodeType_t getOwnerType() const { return _ownerType; } void setOwnerType(NodeType_t ownerType) { _ownerType = ownerType; } - const QUuid& getSessionUUID() const { return _sessionUUID; } - void setSessionUUID(const QUuid& sessionUUID); - qint64 sendStatsToDomainServer(const QJsonObject& statsObject); int getNumNoReplyDomainCheckIns() const { return _numNoReplyDomainCheckIns; } - DomainHandler& getDomainHandler() { return _DomainHandler; } + DomainHandler& getDomainHandler() { return _domainHandler; } const NodeSet& getNodeInterestSet() const { return _nodeTypesOfInterest; } void addNodeTypeToInterestSet(NodeType_t nodeTypeToAdd); @@ -86,7 +83,6 @@ public slots: void sendDomainServerCheckIn(); void pingInactiveNodes(); signals: - void uuidChanged(const QUuid& ownerUUID); void limitOfSilentDomainCheckInsReached(); private: static NodeList* _sharedInstance; @@ -104,8 +100,7 @@ private: NodeType_t _ownerType; NodeSet _nodeTypesOfInterest; - DomainHandler _DomainHandler; - QUuid _sessionUUID; + DomainHandler _domainHandler; int _numNoReplyDomainCheckIns; HifiSockAddr _assignmentServerSocket; HifiSockAddr _publicSockAddr; diff --git a/libraries/shared/src/PacketHeaders.cpp b/libraries/shared/src/PacketHeaders.cpp index da8de0ddb0..1c7439861c 100644 --- a/libraries/shared/src/PacketHeaders.cpp +++ b/libraries/shared/src/PacketHeaders.cpp @@ -84,7 +84,7 @@ int populatePacketHeader(char* packet, PacketType type, const QUuid& connectionU char* position = packet + numTypeBytes + sizeof(PacketVersion); - QUuid packUUID = connectionUUID.isNull() ? NodeList::getInstance()->getSessionUUID() : connectionUUID; + QUuid packUUID = connectionUUID.isNull() ? LimitedNodeList::getInstance()->getSessionUUID() : connectionUUID; QByteArray rfcUUID = packUUID.toRfc4122(); memcpy(position, rfcUUID.constData(), NUM_BYTES_RFC4122_UUID); diff --git a/libraries/shared/src/PacketHeaders.h b/libraries/shared/src/PacketHeaders.h index 0250fb038a..61176051bb 100644 --- a/libraries/shared/src/PacketHeaders.h +++ b/libraries/shared/src/PacketHeaders.h @@ -67,7 +67,8 @@ typedef char PacketVersion; const QSet NON_VERIFIED_PACKETS = QSet() << PacketTypeDomainServerRequireDTLS << PacketTypeDomainList << PacketTypeDomainListRequest - << PacketTypeCreateAssignment << PacketTypeRequestAssignment << PacketTypeStunResponse; + << PacketTypeCreateAssignment << PacketTypeRequestAssignment << PacketTypeStunResponse + << PacketTypeNodeJsonStats; const int NUM_BYTES_MD5_HASH = 16; const int NUM_STATIC_HEADER_BYTES = sizeof(PacketVersion) + NUM_BYTES_RFC4122_UUID; From 97b2e689881a591658048b6446b749514b3f5f33 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 14:05:05 -0700 Subject: [PATCH 089/595] more debugging --- assignment-client/src/octree/OctreeServer.cpp | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index bb0424c27e..4ead1705fa 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -840,16 +840,26 @@ void OctreeServer::readPendingDatagrams() { quint64 jurisdictionElapsed = 0; quint64 editElapsed = 0; quint64 nodeListElapsed = 0; + quint64 versionMatchElapsed = 0; + quint64 matchingElapsed = 0; while (readAvailableDatagram(receivedPacket, senderSockAddr)) { readDataGrams++; - if (nodeList->packetVersionAndHashMatch(receivedPacket)) { + + quint64 versionMatchStart = usecTimestampNow(); + bool matches = nodeList->packetVersionAndHashMatch(receivedPacket); + quint64 versionMatchEnd = usecTimestampNow(); + versionMatchElapsed += (versionMatchEnd - versionMatchStart); + + if (matches) { PacketType packetType = packetTypeForPacket(receivedPacket); quint64 startNodeLookup = usecTimestampNow(); SharedNodePointer matchingNode = nodeList->sendingNodeForPacket(receivedPacket); quint64 endNodeLookup = usecTimestampNow(); + matchingElapsed += (endNodeLookup - startNodeLookup); + if ((endNodeLookup - startNodeLookup) > 100000) { qDebug() << "OctreeServer::readPendingDatagrams(): sendingNodeForPacket() took" << (endNodeLookup - startNodeLookup) << "usecs"; } @@ -924,7 +934,9 @@ void OctreeServer::readPendingDatagrams() { << " nodeListElapsed=" << nodeListElapsed << " editElapsed=" << editElapsed << " jurisdictionElapsed=" << jurisdictionElapsed - << " queryElapsed=" << queryElapsed; + << " queryElapsed=" << queryElapsed + << " versionMatchElapsed=" << versionMatchElapsed + << " matchingElapsed=" << matchingElapsed; } } From 94b29782eb84ed6471f41399756b5f7a1aebfded Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 1 Apr 2014 14:19:07 -0700 Subject: [PATCH 090/595] re-scaffold some client side DTLS in DTLSSession --- libraries/shared/src/DTLSSession.cpp | 50 +++++++++++++++++++------- libraries/shared/src/DTLSSession.h | 15 ++++---- libraries/shared/src/DomainHandler.cpp | 3 +- 3 files changed, 46 insertions(+), 22 deletions(-) diff --git a/libraries/shared/src/DTLSSession.cpp b/libraries/shared/src/DTLSSession.cpp index ce14d91f27..9c86f8d7a2 100644 --- a/libraries/shared/src/DTLSSession.cpp +++ b/libraries/shared/src/DTLSSession.cpp @@ -6,13 +6,15 @@ // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. // +#include + #include "DTLSSession.h" -static int socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms) { +int DTLSSession::socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms) { return 1; } -static ssize_t socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t size) { +ssize_t DTLSSession::socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t size) { DTLSSession* session = static_cast(ptr); QUdpSocket& dtlsSocket = session->_dtlsSocket; @@ -24,20 +26,44 @@ static ssize_t socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t size) } } -static ssize_t socketPush(gnutls_transport_ptr_t ptr, const void* buffer, size_t size) { +ssize_t DTLSSession::socketPush(gnutls_transport_ptr_t ptr, const void* buffer, size_t size) { DTLSSession* session = static_cast(ptr); QUdpSocket& dtlsSocket = session->_dtlsSocket; - if (dtlsSocket.state() != QAbstractSocket::ConnectedState) { - gnutls_transport_set_errno(session->_gnutlsSession, GNUTLS_E_AGAIN); - return -1; - } - - return dtlsSocket.write(reinterpret_cast(buffer), size); + return dtlsSocket.writeDatagram(reinterpret_cast(buffer), size, + session->_destinationSocket.getAddress(), session->_destinationSocket.getPort()); } -DTLSSession::DTLSSession(QUdpSocket& dtlsSocket) : - _dtlsSocket(dtlsSocket) -{ +static gnutls_certificate_credentials_t* x509ClientCredentials() { + static gnutls_certificate_credentials_t x509Credentials; + static bool credentialsInitialized = false; + if (!credentialsInitialized) { + gnutls_certificate_allocate_credentials(&x509Credentials); + } + + return &x509Credentials; +} + +DTLSSession::DTLSSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket) : + _dtlsSocket(dtlsSocket), + _destinationSocket(destinationSocket) +{ + qDebug() << "Initializing DTLS Session."; + + gnutls_init(&_gnutlsSession, GNUTLS_CLIENT | GNUTLS_DATAGRAM); + gnutls_priority_set_direct(_gnutlsSession, "NORMAL", NULL); + + gnutls_credentials_set(_gnutlsSession, GNUTLS_CRD_CERTIFICATE, x509ClientCredentials()); + + // tell GnuTLS to call us for push or pull + gnutls_transport_set_ptr(_gnutlsSession, this); + gnutls_transport_set_push_function(_gnutlsSession, socketPush); + gnutls_transport_set_pull_function(_gnutlsSession, socketPull); + gnutls_transport_set_pull_timeout_function(_gnutlsSession, socketPullTimeout); + + // start the handshake process with domain-server now + int handshakeReturn = gnutls_handshake(_gnutlsSession); + gnutls_perror(handshakeReturn); + qDebug() << "HR" << handshakeReturn; } \ No newline at end of file diff --git a/libraries/shared/src/DTLSSession.h b/libraries/shared/src/DTLSSession.h index 190373c155..c0077a38b4 100644 --- a/libraries/shared/src/DTLSSession.h +++ b/libraries/shared/src/DTLSSession.h @@ -13,20 +13,19 @@ #include -static int socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms); -static ssize_t socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t size); -static ssize_t socketPush(gnutls_transport_ptr_t ptr, const void* buffer, size_t size); +#include "HifiSockAddr.h" class DTLSSession { public: - DTLSSession(QUdpSocket& dtlsSocket); - - friend int socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms); - friend ssize_t socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t size); - friend ssize_t socketPush(gnutls_transport_ptr_t ptr, const void* buffer, size_t size); + DTLSSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket); private: + static int socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms); + static ssize_t socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t size); + static ssize_t socketPush(gnutls_transport_ptr_t ptr, const void* buffer, size_t size); + QUdpSocket& _dtlsSocket; gnutls_session_t _gnutlsSession; + HifiSockAddr _destinationSocket; }; #endif /* defined(__hifi__DTLSSession__) */ diff --git a/libraries/shared/src/DomainHandler.cpp b/libraries/shared/src/DomainHandler.cpp index 52bfa04414..2881da64c5 100644 --- a/libraries/shared/src/DomainHandler.cpp +++ b/libraries/shared/src/DomainHandler.cpp @@ -42,7 +42,7 @@ void DomainHandler::reset() { void DomainHandler::initializeDTLSSession() { if (!_dtlsSession) { - _dtlsSession = new DTLSSession(NodeList::getInstance()->getDTLSSocket()); + _dtlsSession = new DTLSSession(NodeList::getInstance()->getDTLSSocket(), _sockAddr); } } @@ -119,7 +119,6 @@ void DomainHandler::parseDTLSRequirementPacket(const QByteArray& dtlsRequirement unsigned short dtlsPort = 0; memcpy(&dtlsPort, dtlsRequirementPacket.data() + numBytesPacketHeader, sizeof(dtlsPort)); - qDebug() << "domain-server DTLS port changed to" << dtlsPort << "- Enabling DTLS."; _sockAddr.setPort(dtlsPort); From 5325453c89669dbfff10d36bee7dcb80abb204dd Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 14:39:59 -0700 Subject: [PATCH 091/595] more debugging --- libraries/shared/src/NodeList.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 879377a2fd..ff835771cb 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -135,7 +135,8 @@ bool NodeList::packetVersionAndHashMatch(const QByteArray& packet) { << PacketTypeDomainServerAuthRequest << PacketTypeDomainConnectRequest << PacketTypeStunResponse << PacketTypeDataServerConfirm << PacketTypeDataServerGet << PacketTypeDataServerPut << PacketTypeDataServerSend - << PacketTypeCreateAssignment << PacketTypeRequestAssignment; + << PacketTypeCreateAssignment << PacketTypeRequestAssignment + << PacketTypeVoxelQuery << PacketTypeParticleQuery; if (!NON_VERIFIED_PACKETS.contains(checkType)) { // figure out which node this is from From ce6f84568187652e1f15ce832ec455dc38b06887 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 1 Apr 2014 14:47:30 -0700 Subject: [PATCH 092/595] remove some gnutls handshake debugging --- domain-server/src/DomainServer.cpp | 1 - libraries/shared/src/DTLSSession.cpp | 4 +--- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index f83b6da97f..60df41007d 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -476,7 +476,6 @@ void DomainServer::sendDomainListToNode(const SharedNodePointer& node, const Hif LimitedNodeList* nodeList = LimitedNodeList::getInstance(); - if (nodeInterestList.size() > 0) { // if the node has any interest types, send back those nodes as well foreach (const SharedNodePointer& otherNode, nodeList->getNodeHash()) { diff --git a/libraries/shared/src/DTLSSession.cpp b/libraries/shared/src/DTLSSession.cpp index 9c86f8d7a2..90558034a7 100644 --- a/libraries/shared/src/DTLSSession.cpp +++ b/libraries/shared/src/DTLSSession.cpp @@ -63,7 +63,5 @@ DTLSSession::DTLSSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket gnutls_transport_set_pull_timeout_function(_gnutlsSession, socketPullTimeout); // start the handshake process with domain-server now - int handshakeReturn = gnutls_handshake(_gnutlsSession); - gnutls_perror(handshakeReturn); - qDebug() << "HR" << handshakeReturn; + gnutls_handshake(_gnutlsSession); } \ No newline at end of file From bef5677e91705c3c5b8b28dcd981b7e715cc5ad2 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 14:51:19 -0700 Subject: [PATCH 093/595] more debugging --- libraries/shared/src/ThreadedAssignment.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/libraries/shared/src/ThreadedAssignment.cpp b/libraries/shared/src/ThreadedAssignment.cpp index fdf2d91c36..0269edd193 100644 --- a/libraries/shared/src/ThreadedAssignment.cpp +++ b/libraries/shared/src/ThreadedAssignment.cpp @@ -11,6 +11,7 @@ #include #include "Logging.h" +#include "SharedUtil.h" #include "ThreadedAssignment.h" ThreadedAssignment::ThreadedAssignment(const QByteArray& packet) : @@ -73,7 +74,14 @@ void ThreadedAssignment::sendStatsPacket() { addPacketStatsAndSendStatsPacket(statsObject); } +quint64 lastCheckIn = usecTimestampNow(); void ThreadedAssignment::checkInWithDomainServerOrExit() { + quint64 now = usecTimestampNow(); + if ((now - lastCheckIn) > 100000) { + qDebug() << "ThreadedAssignment::checkInWithDomainServerOrExit(): since lastCheckIn=" << (now - lastCheckIn) << "usecs"; + } + lastCheckIn = now; + if (NodeList::getInstance()->getNumNoReplyDomainCheckIns() == MAX_SILENT_DOMAIN_SERVER_CHECK_INS) { setFinished(true); } else { From 5b7ab1e49a20d81699377cdbdb9aff71a7cf07c1 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 14:59:52 -0700 Subject: [PATCH 094/595] more debugging --- libraries/shared/src/NodeList.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index ff835771cb..db625d416a 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -924,6 +924,7 @@ void NodeList::resetPacketStats() { } void NodeList::removeSilentNodes() { + quint64 removeSilentNodesStart = usecTimestampNow(); _nodeHashMutex.lock(); @@ -946,6 +947,12 @@ void NodeList::removeSilentNodes() { } _nodeHashMutex.unlock(); + + quint64 removeSilentNodesEnd = usecTimestampNow(); + quint64 removeSilentNodesElapsed = (removeSilentNodesEnd - removeSilentNodesStart); + if (removeSilentNodesElapsed > 100000) { + qDebug() << "removeSilentNodesElapsed="< Date: Tue, 1 Apr 2014 15:35:46 -0700 Subject: [PATCH 095/595] test other way of doing loudness --- interface/interface_en.ts | 12 ++++++------ interface/src/Application.cpp | 7 +++++++ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/interface/interface_en.ts b/interface/interface_en.ts index a1abb57b52..709cea840d 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -14,12 +14,12 @@ - + Open Script - + JavaScript Files (*.js) @@ -113,18 +113,18 @@ Menu - + Open .ini config file - - + + Text files (*.ini) - + Save .ini config file diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index a237e92e2b..e0c26f3f14 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2540,6 +2540,13 @@ void Application::displayOverlay() { audioLevel = log2loudness / MAX_LOG2_SAMPLE * AUDIO_METER_SCALE_WIDTH; + + if (log2loudness <= 11.f) { + audioLevel = log2loudness / 11.f * AUDIO_METER_SCALE_WIDTH / 5.f; + } else { + audioLevel = (log2loudness - 10.f) * AUDIO_METER_SCALE_WIDTH / 5.f; + } + bool isClipping = ((_audio.getTimeSinceLastClip() > 0.f) && (_audio.getTimeSinceLastClip() < CLIPPING_INDICATOR_TIME)); glBegin(GL_QUADS); From 0b792985d3489dfb24e49c65cc0725f3c86a18e9 Mon Sep 17 00:00:00 2001 From: Philip Rosedale Date: Tue, 1 Apr 2014 16:43:18 -0700 Subject: [PATCH 096/595] Tweaks to VU meter, tone injector, and fix to noise gate --- interface/interface_en.ts | 4 +- interface/src/Application.cpp | 17 +++++---- interface/src/Audio.cpp | 69 +++++++++++++++++------------------ 3 files changed, 45 insertions(+), 45 deletions(-) diff --git a/interface/interface_en.ts b/interface/interface_en.ts index 709cea840d..f2efa8e9cb 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -14,12 +14,12 @@ - + Open Script - + JavaScript Files (*.js) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index e0c26f3f14..a685dfbb48 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2531,20 +2531,21 @@ void Application::displayOverlay() { const float CLIPPING_INDICATOR_TIME = 1.0f; const float AUDIO_METER_AVERAGING = 0.5; const float LOG2 = log(2.f); - const float MAX_LOG2_SAMPLE = 15.f; + const float METER_LOUDNESS_SCALE = 2.8f / 5.f; + const float LOG2_LOUDNESS_FLOOR = 11.f; float audioLevel = 0.f; float loudness = _audio.getLastInputLoudness() + 1.f; + _trailingAudioLoudness = AUDIO_METER_AVERAGING * _trailingAudioLoudness + (1.f - AUDIO_METER_AVERAGING) * loudness; - float log2loudness = log(_trailingAudioLoudness) / LOG2; - audioLevel = log2loudness / MAX_LOG2_SAMPLE * AUDIO_METER_SCALE_WIDTH; - - - if (log2loudness <= 11.f) { - audioLevel = log2loudness / 11.f * AUDIO_METER_SCALE_WIDTH / 5.f; + if (log2loudness <= LOG2_LOUDNESS_FLOOR) { + audioLevel = (log2loudness / LOG2_LOUDNESS_FLOOR) * METER_LOUDNESS_SCALE * AUDIO_METER_SCALE_WIDTH; } else { - audioLevel = (log2loudness - 10.f) * AUDIO_METER_SCALE_WIDTH / 5.f; + audioLevel = (log2loudness - (LOG2_LOUDNESS_FLOOR - 1.f)) * METER_LOUDNESS_SCALE * AUDIO_METER_SCALE_WIDTH; + } + if (audioLevel > AUDIO_METER_SCALE_WIDTH) { + audioLevel = AUDIO_METER_SCALE_WIDTH; } bool isClipping = ((_audio.getTimeSinceLastClip() > 0.f) && (_audio.getTimeSinceLastClip() < CLIPPING_INDICATOR_TIME)); diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 9f993e653d..5f6b320a8b 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -436,12 +436,12 @@ void Audio::handleAudioInput() { measuredDcOffset += monoAudioSamples[i]; monoAudioSamples[i] -= (int16_t) _dcOffset; thisSample = fabsf(monoAudioSamples[i]); - if (thisSample > (32767.f * CLIPPING_THRESHOLD)) { + if (thisSample >= (32767.f * CLIPPING_THRESHOLD)) { _timeSinceLastClip = 0.0f; } loudness += thisSample; // Noise Reduction: Count peaks above the average loudness - if (thisSample > (_noiseGateMeasuredFloor * NOISE_GATE_HEIGHT)) { + if (_noiseGateEnabled && (thisSample > (_noiseGateMeasuredFloor * NOISE_GATE_HEIGHT))) { samplesOverNoiseGate++; } } @@ -454,32 +454,41 @@ void Audio::handleAudioInput() { _dcOffset = DC_OFFSET_AVERAGING * _dcOffset + (1.f - DC_OFFSET_AVERAGING) * measuredDcOffset; } - // - _lastInputLoudness = fabs(loudness / NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL); - - float averageOfAllSampleFrames = 0.f; - _noiseSampleFrames[_noiseGateSampleCounter++] = _lastInputLoudness; - if (_noiseGateSampleCounter == NUMBER_OF_NOISE_SAMPLE_FRAMES) { - float smallestSample = FLT_MAX; - for (int i = 0; i <= NUMBER_OF_NOISE_SAMPLE_FRAMES - NOISE_GATE_FRAMES_TO_AVERAGE; i+= NOISE_GATE_FRAMES_TO_AVERAGE) { - float thisAverage = 0.0f; - for (int j = i; j < i + NOISE_GATE_FRAMES_TO_AVERAGE; j++) { - thisAverage += _noiseSampleFrames[j]; - averageOfAllSampleFrames += _noiseSampleFrames[j]; - } - thisAverage /= NOISE_GATE_FRAMES_TO_AVERAGE; - - if (thisAverage < smallestSample) { - smallestSample = thisAverage; - } + // Add tone injection if enabled + const float TONE_FREQ = 220.f / SAMPLE_RATE * TWO_PI; + const float QUARTER_VOLUME = 8192.f; + if (_toneInjectionEnabled) { + loudness = 0.f; + for (int i = 0; i < NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL; i++) { + monoAudioSamples[i] = QUARTER_VOLUME * sinf(TONE_FREQ * (float)(i + _proceduralEffectSample)); + loudness += fabsf(monoAudioSamples[i]); } - averageOfAllSampleFrames /= NUMBER_OF_NOISE_SAMPLE_FRAMES; - _noiseGateMeasuredFloor = smallestSample; - _noiseGateSampleCounter = 0; - } + _lastInputLoudness = fabs(loudness / NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL); - if (_noiseGateEnabled) { + // If Noise Gate is enabled, check and turn the gate on and off + if (!_toneInjectionEnabled && _noiseGateEnabled) { + float averageOfAllSampleFrames = 0.f; + _noiseSampleFrames[_noiseGateSampleCounter++] = _lastInputLoudness; + if (_noiseGateSampleCounter == NUMBER_OF_NOISE_SAMPLE_FRAMES) { + float smallestSample = FLT_MAX; + for (int i = 0; i <= NUMBER_OF_NOISE_SAMPLE_FRAMES - NOISE_GATE_FRAMES_TO_AVERAGE; i+= NOISE_GATE_FRAMES_TO_AVERAGE) { + float thisAverage = 0.0f; + for (int j = i; j < i + NOISE_GATE_FRAMES_TO_AVERAGE; j++) { + thisAverage += _noiseSampleFrames[j]; + averageOfAllSampleFrames += _noiseSampleFrames[j]; + } + thisAverage /= NOISE_GATE_FRAMES_TO_AVERAGE; + + if (thisAverage < smallestSample) { + smallestSample = thisAverage; + } + } + averageOfAllSampleFrames /= NUMBER_OF_NOISE_SAMPLE_FRAMES; + _noiseGateMeasuredFloor = smallestSample; + _noiseGateSampleCounter = 0; + + } if (samplesOverNoiseGate > NOISE_GATE_WIDTH) { _noiseGateOpen = true; _noiseGateFramesToClose = NOISE_GATE_CLOSE_FRAME_DELAY; @@ -493,16 +502,6 @@ void Audio::handleAudioInput() { _lastInputLoudness = 0; } } - // - // Add tone injection if enabled - // - const float TONE_FREQ = 220.f / SAMPLE_RATE * TWO_PI; - const float QUARTER_VOLUME = 8192.f; - if (_toneInjectionEnabled) { - for (int i = 0; i < NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL; i++) { - monoAudioSamples[i] = QUARTER_VOLUME * sinf(TONE_FREQ * (float)(i + _proceduralEffectSample)); - } - } // add input data just written to the scope QMetaObject::invokeMethod(_scope, "addSamples", Qt::QueuedConnection, From b5b4edc999639c60bd3ca97cfc0d7f3354466c19 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 1 Apr 2014 16:47:45 -0700 Subject: [PATCH 097/595] add notion of server and client DTLSSessions --- domain-server/src/DTLSServerSession.cpp | 15 ++++++++++ domain-server/src/DTLSServerSession.h | 19 ++++++++++++ domain-server/src/DomainServer.cpp | 34 ++++++++++++++++++---- domain-server/src/DomainServer.h | 4 +++ domain-server/src/DomainServerNodeData.cpp | 3 +- domain-server/src/DomainServerNodeData.h | 5 ++++ libraries/shared/src/DTLSClientSession.cpp | 15 ++++++++++ libraries/shared/src/DTLSClientSession.h | 19 ++++++++++++ libraries/shared/src/DTLSSession.cpp | 20 ++----------- libraries/shared/src/DTLSSession.h | 9 ++++-- libraries/shared/src/DomainHandler.cpp | 2 +- libraries/shared/src/DomainHandler.h | 4 +-- libraries/shared/src/HifiSockAddr.cpp | 19 +++++++++++- libraries/shared/src/HifiSockAddr.h | 3 ++ 14 files changed, 141 insertions(+), 30 deletions(-) create mode 100644 domain-server/src/DTLSServerSession.cpp create mode 100644 domain-server/src/DTLSServerSession.h create mode 100644 libraries/shared/src/DTLSClientSession.cpp create mode 100644 libraries/shared/src/DTLSClientSession.h diff --git a/domain-server/src/DTLSServerSession.cpp b/domain-server/src/DTLSServerSession.cpp new file mode 100644 index 0000000000..994b196357 --- /dev/null +++ b/domain-server/src/DTLSServerSession.cpp @@ -0,0 +1,15 @@ +// +// DTLSServerSession.cpp +// hifi +// +// Created by Stephen Birarda on 2014-04-01. +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// + +#include "DTLSServerSession.h" + +DTLSServerSession::DTLSServerSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket) : + DTLSSession(GNUTLS_SERVER, dtlsSocket, destinationSocket) +{ + +} \ No newline at end of file diff --git a/domain-server/src/DTLSServerSession.h b/domain-server/src/DTLSServerSession.h new file mode 100644 index 0000000000..5bdb0f9e91 --- /dev/null +++ b/domain-server/src/DTLSServerSession.h @@ -0,0 +1,19 @@ +// +// DTLSServerSession.h +// hifi +// +// Created by Stephen Birarda on 2014-04-01. +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// + +#ifndef __hifi__DTLSServerSession__ +#define __hifi__DTLSServerSession__ + +#include + +class DTLSServerSession : public DTLSSession { +public: + DTLSServerSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket); +}; + +#endif /* defined(__hifi__DTLSServerSession__) */ diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 60df41007d..ba2f2791bd 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -6,8 +6,6 @@ // Copyright (c) 2013 HighFidelity, Inc. All rights reserved. // -#include - #include #include #include @@ -393,8 +391,12 @@ void DomainServer::addNodeToNodeListAndConfirmConnection(const QByteArray& packe SharedNodePointer newNode = LimitedNodeList::getInstance()->addOrUpdateNode(nodeUUID, nodeType, publicSockAddr, localSockAddr); - // when the newNode is created the linked data is also created, if this was a static assignment set the UUID - reinterpret_cast(newNode->getLinkedData())->setStaticAssignmentUUID(assignmentUUID); + // when the newNode is created the linked data is also created + // if this was a static assignment set the UUID, set the sendingSockAddr + DomainServerNodeData* nodeData = reinterpret_cast(newNode->getLinkedData()); + + nodeData->setStaticAssignmentUUID(assignmentUUID); + nodeData->setSendingSockAddr(senderSockAddr); if (!authJsonObject.isEmpty()) { // pull the connection secret from the authJsonObject and set it as the connection secret for this node @@ -533,7 +535,6 @@ void DomainServer::readAvailableDatagrams() { HifiSockAddr senderSockAddr; QByteArray receivedPacket; - static QByteArray assignmentPacket = byteArrayWithPopulatedHeader(PacketTypeCreateAssignment); static int numAssignmentPacketHeaderBytes = assignmentPacket.size(); @@ -603,7 +604,30 @@ void DomainServer::readAvailableDatagrams() { } void DomainServer::readAvailableDTLSDatagrams() { + LimitedNodeList* nodeList = LimitedNodeList::getInstance(); + QUdpSocket& dtlsSocket = nodeList->getDTLSSocket(); + + static sockaddr senderSockAddr; + static socklen_t sockAddrSize = sizeof(senderSockAddr); + + while (dtlsSocket.hasPendingDatagrams()) { + // check if we have an active DTLS session for this sender + QByteArray peekDatagram(dtlsSocket.pendingDatagramSize(), 0); + + recvfrom(dtlsSocket.socketDescriptor(), peekDatagram.data(), dtlsSocket.pendingDatagramSize(), + MSG_PEEK, &senderSockAddr, &sockAddrSize); + + DTLSSession* existingSession = _dtlsSessions.value(HifiSockAddr(&senderSockAddr)); + + qDebug() << "Checking for a session with" << HifiSockAddr(&senderSockAddr); + + if (existingSession) { + // use GnuTLS to receive the encrypted data + } else { + // no existing session - set up a new session now + } + } } void DomainServer::processDatagram(const QByteArray& receivedPacket, const HifiSockAddr& senderSockAddr) { diff --git a/domain-server/src/DomainServer.h b/domain-server/src/DomainServer.h index 7ee6d7374e..a69df5dec0 100644 --- a/domain-server/src/DomainServer.h +++ b/domain-server/src/DomainServer.h @@ -23,6 +23,8 @@ #include #include +#include "DTLSServerSession.h" + typedef QSharedPointer SharedAssignmentPointer; class DomainServer : public QCoreApplication, public HTTPRequestHandler { @@ -88,6 +90,8 @@ private: gnutls_certificate_credentials_t* _x509Credentials; gnutls_dh_params_t* _dhParams; gnutls_priority_t* _priorityCache; + + QHash _dtlsSessions; }; #endif /* defined(__hifi__DomainServer__) */ diff --git a/domain-server/src/DomainServerNodeData.cpp b/domain-server/src/DomainServerNodeData.cpp index f1e08e3bc4..6e94a8a330 100644 --- a/domain-server/src/DomainServerNodeData.cpp +++ b/domain-server/src/DomainServerNodeData.cpp @@ -17,7 +17,8 @@ DomainServerNodeData::DomainServerNodeData() : _sessionSecretHash(), _staticAssignmentUUID(), - _statsJSONObject() + _statsJSONObject(), + _sendingSockAddr() { } diff --git a/domain-server/src/DomainServerNodeData.h b/domain-server/src/DomainServerNodeData.h index 20531839f4..40516a70aa 100644 --- a/domain-server/src/DomainServerNodeData.h +++ b/domain-server/src/DomainServerNodeData.h @@ -12,6 +12,7 @@ #include #include +#include #include class DomainServerNodeData : public NodeData { @@ -26,6 +27,9 @@ public: void setStaticAssignmentUUID(const QUuid& staticAssignmentUUID) { _staticAssignmentUUID = staticAssignmentUUID; } const QUuid& getStaticAssignmentUUID() const { return _staticAssignmentUUID; } + void setSendingSockAddr(const HifiSockAddr& sendingSockAddr) { _sendingSockAddr = sendingSockAddr; } + const HifiSockAddr& getSendingSockAddr() { return _sendingSockAddr; } + QHash& getSessionSecretHash() { return _sessionSecretHash; } private: QJsonObject mergeJSONStatsFromNewObject(const QJsonObject& newObject, QJsonObject destinationObject); @@ -33,6 +37,7 @@ private: QHash _sessionSecretHash; QUuid _staticAssignmentUUID; QJsonObject _statsJSONObject; + HifiSockAddr _sendingSockAddr; }; #endif /* defined(__hifi__DomainServerNodeData__) */ diff --git a/libraries/shared/src/DTLSClientSession.cpp b/libraries/shared/src/DTLSClientSession.cpp new file mode 100644 index 0000000000..30ca536c9e --- /dev/null +++ b/libraries/shared/src/DTLSClientSession.cpp @@ -0,0 +1,15 @@ +// +// DTLSClientSession.cpp +// hifi +// +// Created by Stephen Birarda on 2014-04-01. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// + +#include "DTLSClientSession.h" + +DTLSClientSession::DTLSClientSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket) : + DTLSSession(GNUTLS_CLIENT, dtlsSocket, destinationSocket) +{ + +} \ No newline at end of file diff --git a/libraries/shared/src/DTLSClientSession.h b/libraries/shared/src/DTLSClientSession.h new file mode 100644 index 0000000000..93cd51cb9a --- /dev/null +++ b/libraries/shared/src/DTLSClientSession.h @@ -0,0 +1,19 @@ +// +// DTLSClientSession.h +// hifi +// +// Created by Stephen Birarda on 2014-04-01. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// + +#ifndef __hifi__DTLSClientSession__ +#define __hifi__DTLSClientSession__ + +#include "DTLSSession.h" + +class DTLSClientSession : public DTLSSession { +public: + DTLSClientSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket); +}; + +#endif /* defined(__hifi__DTLSClientSession__) */ diff --git a/libraries/shared/src/DTLSSession.cpp b/libraries/shared/src/DTLSSession.cpp index 90558034a7..6113019cf9 100644 --- a/libraries/shared/src/DTLSSession.cpp +++ b/libraries/shared/src/DTLSSession.cpp @@ -34,7 +34,7 @@ ssize_t DTLSSession::socketPush(gnutls_transport_ptr_t ptr, const void* buffer, session->_destinationSocket.getAddress(), session->_destinationSocket.getPort()); } -static gnutls_certificate_credentials_t* x509ClientCredentials() { +gnutls_certificate_credentials_t* x509CACredentials() { static gnutls_certificate_credentials_t x509Credentials; static bool credentialsInitialized = false; @@ -45,23 +45,9 @@ static gnutls_certificate_credentials_t* x509ClientCredentials() { return &x509Credentials; } -DTLSSession::DTLSSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket) : +DTLSSession::DTLSSession(int end, QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket) : _dtlsSocket(dtlsSocket), _destinationSocket(destinationSocket) { - qDebug() << "Initializing DTLS Session."; - - gnutls_init(&_gnutlsSession, GNUTLS_CLIENT | GNUTLS_DATAGRAM); - gnutls_priority_set_direct(_gnutlsSession, "NORMAL", NULL); - - gnutls_credentials_set(_gnutlsSession, GNUTLS_CRD_CERTIFICATE, x509ClientCredentials()); - - // tell GnuTLS to call us for push or pull - gnutls_transport_set_ptr(_gnutlsSession, this); - gnutls_transport_set_push_function(_gnutlsSession, socketPush); - gnutls_transport_set_pull_function(_gnutlsSession, socketPull); - gnutls_transport_set_pull_timeout_function(_gnutlsSession, socketPullTimeout); - - // start the handshake process with domain-server now - gnutls_handshake(_gnutlsSession); + gnutls_init(&_gnutlsSession, end | GNUTLS_DATAGRAM); } \ No newline at end of file diff --git a/libraries/shared/src/DTLSSession.h b/libraries/shared/src/DTLSSession.h index c0077a38b4..ce453c6d22 100644 --- a/libraries/shared/src/DTLSSession.h +++ b/libraries/shared/src/DTLSSession.h @@ -15,13 +15,16 @@ #include "HifiSockAddr.h" -class DTLSSession { +class DTLSSession : public QObject { + Q_OBJECT public: - DTLSSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket); -private: + DTLSSession(int end, QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket); + +protected: static int socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms); static ssize_t socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t size); static ssize_t socketPush(gnutls_transport_ptr_t ptr, const void* buffer, size_t size); + static gnutls_certificate_credentials_t* x509CACredentials(); QUdpSocket& _dtlsSocket; gnutls_session_t _gnutlsSession; diff --git a/libraries/shared/src/DomainHandler.cpp b/libraries/shared/src/DomainHandler.cpp index 2881da64c5..e6403dcbc1 100644 --- a/libraries/shared/src/DomainHandler.cpp +++ b/libraries/shared/src/DomainHandler.cpp @@ -42,7 +42,7 @@ void DomainHandler::reset() { void DomainHandler::initializeDTLSSession() { if (!_dtlsSession) { - _dtlsSession = new DTLSSession(NodeList::getInstance()->getDTLSSocket(), _sockAddr); + _dtlsSession = new DTLSClientSession(NodeList::getInstance()->getDTLSSocket(), _sockAddr); } } diff --git a/libraries/shared/src/DomainHandler.h b/libraries/shared/src/DomainHandler.h index 4a9f166963..5032138858 100644 --- a/libraries/shared/src/DomainHandler.h +++ b/libraries/shared/src/DomainHandler.h @@ -14,7 +14,7 @@ #include #include -#include "DTLSSession.h" +#include "DTLSClientSession.h" #include "HifiSockAddr.h" const QString DEFAULT_DOMAIN_HOSTNAME = "alpha.highfidelity.io"; @@ -67,7 +67,7 @@ private: QUuid _assignmentUUID; bool _isConnected; bool _requiresDTLS; - DTLSSession* _dtlsSession; + DTLSClientSession* _dtlsSession; }; #endif /* defined(__hifi__DomainHandler__) */ diff --git a/libraries/shared/src/HifiSockAddr.cpp b/libraries/shared/src/HifiSockAddr.cpp index cc031525d8..8010202424 100644 --- a/libraries/shared/src/HifiSockAddr.cpp +++ b/libraries/shared/src/HifiSockAddr.cpp @@ -6,12 +6,14 @@ // Copyright (c) 2013 HighFidelity, Inc. All rights reserved. // -#include "HifiSockAddr.h" +#include #include #include #include +#include "HifiSockAddr.h" + static int hifiSockAddrMetaTypeId = qMetaTypeId(); HifiSockAddr::HifiSockAddr() : @@ -44,6 +46,16 @@ HifiSockAddr::HifiSockAddr(const QString& hostname, quint16 hostOrderPort) { } } +HifiSockAddr::HifiSockAddr(const sockaddr* sockaddr) { + _address = QHostAddress(sockaddr); + + if (sockaddr->sa_family == AF_INET) { + _port = reinterpret_cast(sockaddr)->sin_port; + } else { + _port = reinterpret_cast(sockaddr)->sin6_port; + } +} + HifiSockAddr& HifiSockAddr::operator=(const HifiSockAddr& rhsSockAddr) { _address = rhsSockAddr._address; _port = rhsSockAddr._port; @@ -109,3 +121,8 @@ quint32 getHostOrderLocalAddress() { // return the looked up local address return localAddress; } + +uint qHash(const HifiSockAddr& key, uint seed) { + // use the existing QHostAddress and quint16 hash functions to get our hash + return qHash(key.getAddress(), seed) + qHash(key.getPort(), seed); +} diff --git a/libraries/shared/src/HifiSockAddr.h b/libraries/shared/src/HifiSockAddr.h index e8f928c36d..365067080b 100644 --- a/libraries/shared/src/HifiSockAddr.h +++ b/libraries/shared/src/HifiSockAddr.h @@ -17,6 +17,7 @@ public: HifiSockAddr(const QHostAddress& address, quint16 port); HifiSockAddr(const HifiSockAddr& otherSockAddr); HifiSockAddr(const QString& hostname, quint16 hostOrderPort); + HifiSockAddr(const sockaddr* sockaddr); bool isNull() const { return _address.isNull() && _port == 0; } @@ -45,6 +46,8 @@ private: quint16 _port; }; +uint qHash(const HifiSockAddr& key, uint seed); + quint32 getHostOrderLocalAddress(); Q_DECLARE_METATYPE(HifiSockAddr) From 632dc6b8e4f6811ac8427eeca4d15ae832d3e55d Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 1 Apr 2014 16:51:05 -0700 Subject: [PATCH 098/595] set GnuTLS credentials for DTLSClientSession --- libraries/shared/src/DTLSClientSession.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/shared/src/DTLSClientSession.cpp b/libraries/shared/src/DTLSClientSession.cpp index 30ca536c9e..7649b7f352 100644 --- a/libraries/shared/src/DTLSClientSession.cpp +++ b/libraries/shared/src/DTLSClientSession.cpp @@ -11,5 +11,5 @@ DTLSClientSession::DTLSClientSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket) : DTLSSession(GNUTLS_CLIENT, dtlsSocket, destinationSocket) { - + gnutls_credentials_set(_gnutlsSession, GNUTLS_CRD_CERTIFICATE, DTLSSession::x509CACredentials()); } \ No newline at end of file From fd1ed13de028ab692eed2f228600e2d3ef3231f7 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 1 Apr 2014 16:53:17 -0700 Subject: [PATCH 099/595] fix static x509CACredentials method --- libraries/shared/src/DTLSSession.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/shared/src/DTLSSession.cpp b/libraries/shared/src/DTLSSession.cpp index 6113019cf9..0ab5bdb2bc 100644 --- a/libraries/shared/src/DTLSSession.cpp +++ b/libraries/shared/src/DTLSSession.cpp @@ -34,7 +34,7 @@ ssize_t DTLSSession::socketPush(gnutls_transport_ptr_t ptr, const void* buffer, session->_destinationSocket.getAddress(), session->_destinationSocket.getPort()); } -gnutls_certificate_credentials_t* x509CACredentials() { +gnutls_certificate_credentials_t* DTLSSession::x509CACredentials() { static gnutls_certificate_credentials_t x509Credentials; static bool credentialsInitialized = false; From 515593e41cb1b0b45fc079817a5ee3c72fe0c546 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 1 Apr 2014 17:25:26 -0700 Subject: [PATCH 100/595] modify avatar thrust during collisions --- interface/src/avatar/MyAvatar.cpp | 35 +++++++++++++++++++++++++------ interface/src/avatar/MyAvatar.h | 1 + interface/src/renderer/Model.h | 1 + 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 249929d774..9dcfaa09ba 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -86,9 +86,9 @@ void MyAvatar::reset() { getHead()->reset(); getHand()->reset(); - setVelocity(glm::vec3(0,0,0)); - setThrust(glm::vec3(0,0,0)); - setOrientation(glm::quat(glm::vec3(0,0,0))); + setVelocity(glm::vec3(0.f)); + setThrust(glm::vec3(0.f)); + setOrientation(glm::quat(glm::vec3(0.f))); } void MyAvatar::setMoveTarget(const glm::vec3 moveTarget) { @@ -677,6 +677,28 @@ void MyAvatar::updateThrust(float deltaTime) { _thrust -= _driveKeys[LEFT] * _scale * THRUST_MAG_LATERAL * _thrustMultiplier * deltaTime * right; _thrust += _driveKeys[UP] * _scale * THRUST_MAG_UP * _thrustMultiplier * deltaTime * up; _thrust -= _driveKeys[DOWN] * _scale * THRUST_MAG_DOWN * _thrustMultiplier * deltaTime * up; + + // attenuate thrust when in penetration + if (glm::dot(_thrust, _lastBodyPenetration) > 0.f) { + const float MAX_BODY_PENETRATION_DEPTH = 0.6f * _skeletonModel.getBoundingShapeRadius(); + float penetrationFactor = glm::min(1.f, glm::length(_lastBodyPenetration) / MAX_BODY_PENETRATION_DEPTH); + glm::vec3 penetrationDirection = glm::normalize(_lastBodyPenetration); + // attenuate parallel component + glm::vec3 parallelThrust = glm::dot(_thrust, penetrationDirection) * penetrationDirection; + // attenuate perpendicular component (friction) + glm::vec3 perpendicularThrust = _thrust - parallelThrust; + // recombine to get the final thrust + _thrust = (1.f - penetrationFactor) * parallelThrust + (1.f - penetrationFactor * penetrationFactor) * perpendicularThrust; + + // attenuate the growth of _thrustMultiplier when in penetration + // otherwise the avatar will eventually be able to tunnel through the obstacle + _thrustMultiplier *= (1.f - penetrationFactor * penetrationFactor); + } else if (_thrustMultiplier < 1.f) { + // rapid healing of attenuated thrustMultiplier after penetration event + _thrustMultiplier = 1.f; + } + _lastBodyPenetration = glm::vec3(0.f); + _bodyYawDelta -= _driveKeys[ROT_RIGHT] * YAW_SPEED * deltaTime; _bodyYawDelta += _driveKeys[ROT_LEFT] * YAW_SPEED * deltaTime; getHead()->setBasePitch(getHead()->getBasePitch() + (_driveKeys[ROT_UP] - _driveKeys[ROT_DOWN]) * PITCH_SPEED * deltaTime); @@ -686,8 +708,9 @@ void MyAvatar::updateThrust(float deltaTime) { const float THRUST_INCREASE_RATE = 1.05f; const float MAX_THRUST_MULTIPLIER = 75.0f; //printf("m = %.3f\n", _thrustMultiplier); - if (_thrustMultiplier < MAX_THRUST_MULTIPLIER) { - _thrustMultiplier *= 1.f + deltaTime * THRUST_INCREASE_RATE; + _thrustMultiplier *= 1.f + deltaTime * THRUST_INCREASE_RATE; + if (_thrustMultiplier > MAX_THRUST_MULTIPLIER) { + _thrustMultiplier = MAX_THRUST_MULTIPLIER; } } else { _thrustMultiplier = 1.f; @@ -917,10 +940,10 @@ void MyAvatar::updateCollisionWithAvatars(float deltaTime) { CollisionInfo* collision = bodyCollisions.getCollision(j); totalPenetration = addPenetrations(totalPenetration, collision->_penetration); } - if (glm::length2(totalPenetration) > EPSILON) { setPosition(getPosition() - BODY_COLLISION_RESOLVE_FACTOR * totalPenetration); } + _lastBodyPenetration += totalPenetration; // collide our hands against them // TODO: make this work when we can figure out when the other avatar won't yeild diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index 38edc5356e..5c940f0f50 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -121,6 +121,7 @@ private: bool _isThrustOn; float _thrustMultiplier; glm::vec3 _moveTarget; + glm::vec3 _lastBodyPenetration; int _moveTargetStepCounter; QWeakPointer _lookAtTargetAvatar; glm::vec3 _targetAvatarPosition; diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index 43eb7fda67..e7c94deb43 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -180,6 +180,7 @@ public: void applyCollision(CollisionInfo& collision); float getBoundingRadius() const { return _boundingRadius; } + float getBoundingShapeRadius() const { return _boundingShape.getRadius(); } /// Sets blended vertices computed in a separate thread. void setBlendedVertices(const QVector& vertices, const QVector& normals); From dc7e2dbe1b7518a8445ef9b528e31c6d176a0159 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 1 Apr 2014 20:14:38 -0700 Subject: [PATCH 101/595] more debugging --- assignment-client/src/octree/OctreeServer.cpp | 26 ++++++++++++++++++- libraries/shared/src/NodeList.cpp | 3 +++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 4ead1705fa..0a23019bef 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -205,11 +205,16 @@ void OctreeServer::trackProcessWaitTime(float time) { } void OctreeServer::attachQueryNodeToNode(Node* newNode) { + quint64 start = usecTimestampNow(); if (!newNode->getLinkedData() && _instance) { OctreeQueryNode* newQueryNodeData = _instance->createOctreeQueryNode(); newQueryNodeData->init(); newNode->setLinkedData(newQueryNodeData); } + quint64 end = usecTimestampNow(); + if (end - start > 1000) { + qDebug() << "OctreeServer::attachQueryNodeToNode() took:" << (end - start); + } } OctreeServer::OctreeServer(const QByteArray& packet) : @@ -243,6 +248,21 @@ OctreeServer::OctreeServer(const QByteArray& packet) : _averageLoopTime.updateAverage(0); qDebug() << "Octree server starting... [" << this << "]"; + + + QTimer* timer = new QTimer(this); + connect(timer, SIGNAL(timeout()), SLOT(doNothing())); + timer->start(0); + +} + +quint64 lastNothing = usecTimestampNow(); +void OctreeServer::doNothing() { + quint64 now = usecTimestampNow(); + if (now - lastNothing > 100) { + qDebug() << "since last doNothing:" << (now - lastNothing); + } + lastNothing = now; } OctreeServer::~OctreeServer() { @@ -1275,9 +1295,13 @@ QString OctreeServer::getStatusLink() { } void OctreeServer::sendStatsPacket() { - + quint64 start = usecTimestampNow(); static QJsonObject statsObject1; ThreadedAssignment::addPacketStatsAndSendStatsPacket(statsObject1); + quint64 end = usecTimestampNow(); + if (end - start > 1000) { + qDebug() << "OctreeServer::sendStatsPacket() took:" << (end - start); + } /** // TODO: we have too many stats to fit in a single MTU... so for now, we break it into multiple JSON objects and diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index db625d416a..1e93ebf56e 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -923,8 +923,11 @@ void NodeList::resetPacketStats() { _packetStatTimer.restart(); } +quint64 lastSilentNodesStart = usecTimestampNow(); void NodeList::removeSilentNodes() { quint64 removeSilentNodesStart = usecTimestampNow(); + qDebug() << "since last removeSilentNodes()..." << (lastSilentNodesStart - removeSilentNodesStart); + lastSilentNodesStart = removeSilentNodesStart; _nodeHashMutex.lock(); From dc3a4d49574b2766101eacd847c3e53488da72cf Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 2 Apr 2014 09:07:34 -0700 Subject: [PATCH 102/595] remove some unneeded parenthesis --- libraries/shared/src/DTLSSession.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/shared/src/DTLSSession.h b/libraries/shared/src/DTLSSession.h index ce453c6d22..81c1a50916 100644 --- a/libraries/shared/src/DTLSSession.h +++ b/libraries/shared/src/DTLSSession.h @@ -20,11 +20,11 @@ class DTLSSession : public QObject { public: DTLSSession(int end, QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket); + static gnutls_certificate_credentials_t* x509CACredentials(); protected: static int socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms); static ssize_t socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t size); static ssize_t socketPush(gnutls_transport_ptr_t ptr, const void* buffer, size_t size); - static gnutls_certificate_credentials_t* x509CACredentials(); QUdpSocket& _dtlsSocket; gnutls_session_t _gnutlsSession; From 7f6dc7ac2fbc98562ae3f301deed701db5d4742a Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Wed, 2 Apr 2014 09:56:30 -0700 Subject: [PATCH 103/595] Updated translations. --- interface/interface_en.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/interface_en.ts b/interface/interface_en.ts index 3f859c2cd1..c990ef0f20 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -14,12 +14,12 @@ - + Open Script - + JavaScript Files (*.js) From e60e1929f3f4b647c4ce4f609d6c73ab06de8ef2 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 2 Apr 2014 11:36:52 -0700 Subject: [PATCH 104/595] Review comments --- interface/src/ui/ModelsBrowser.cpp | 82 +++++++++++++++++------------- interface/src/ui/ModelsBrowser.h | 19 +++---- 2 files changed, 58 insertions(+), 43 deletions(-) diff --git a/interface/src/ui/ModelsBrowser.cpp b/interface/src/ui/ModelsBrowser.cpp index c47ee1b5ba..15f1e9111e 100644 --- a/interface/src/ui/ModelsBrowser.cpp +++ b/interface/src/ui/ModelsBrowser.cpp @@ -6,17 +6,17 @@ // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. // +#include +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include -#include -#include -#include -#include -#include +#include "Application.h" #include "ModelsBrowser.h" @@ -31,17 +31,18 @@ static const QString IS_TRUNCATED_NAME = "IsTruncated"; static const QString CONTAINER_NAME = "Contents"; static const QString KEY_NAME = "Key"; static const QString LOADING_MSG = "Loading..."; +static const QString ERROR_MSG = "Error loading files"; enum ModelMetaData { - Name = 0, - Creator, - UploadeDate, - Type, - Gender, + NAME, + CREATOR, + UPLOAD_DATE, + TYPE, + GENDER, - ModelMetaDataCount + MODEL_METADATA_COUNT }; -static const QString propertiesNames[ModelMetaDataCount] = { +static const QString propertiesNames[MODEL_METADATA_COUNT] = { "Name", "Creator", "Upload Date", @@ -55,7 +56,7 @@ ModelsBrowser::ModelsBrowser(ModelType modelsType, QWidget* parent) : { // Connect handler _handler->connect(this, SIGNAL(startDownloading()), SLOT(download())); - _handler->connect(this, SIGNAL(startUpdating()), SLOT(update())); + _handler->connect(_handler, SIGNAL(doneDownloading()), SLOT(update())); _handler->connect(this, SIGNAL(destroyed()), SLOT(exit())); // Setup and launch update thread @@ -72,19 +73,20 @@ ModelsBrowser::ModelsBrowser(ModelType modelsType, QWidget* parent) : _view.setModel(_handler->getModel()); } -ModelsBrowser::~ModelsBrowser() { -} - void ModelsBrowser::applyFilter(const QString &filter) { QStringList filters = filter.split(" "); + _handler->lockModel(); + QStandardItemModel* model = _handler->getModel(); + int rows = model->rowCount(); + // Try and match every filter with each rows - for (int i = 0; i < _handler->getModel()->rowCount(); ++i) { + for (int i = 0; i < rows; ++i) { bool match = false; for (int k = 0; k < filters.count(); ++k) { match = false; - for (int j = 0; j < ModelMetaDataCount; ++j) { - if (_handler->getModel()->item(i, j)->text().contains(filters.at(k))) { + for (int j = 0; j < MODEL_METADATA_COUNT; ++j) { + if (model->item(i, j)->text().contains(filters.at(k))) { match = true; break; } @@ -101,6 +103,7 @@ void ModelsBrowser::applyFilter(const QString &filter) { _view.setRowHidden(i, QModelIndex(), true); } } + _handler->unlockModel(); } void ModelsBrowser::browse() { @@ -124,7 +127,9 @@ void ModelsBrowser::browse() { dialog.connect(buttons, SIGNAL(rejected()), SLOT(reject())); if (dialog.exec() == QDialog::Accepted) { + _handler->lockModel(); QVariant selectedFile = _handler->getModel()->data(_view.currentIndex(), Qt::UserRole); + _handler->unlockModel(); if (selectedFile.isValid()) { emit selected(selectedFile.toString()); } @@ -144,7 +149,7 @@ ModelHandler::ModelHandler(ModelType modelsType, QWidget* parent) : // set headers data QStringList headerData; - for (int i = 0; i < ModelMetaDataCount; ++i) { + for (int i = 0; i < MODEL_METADATA_COUNT; ++i) { headerData << propertiesNames[i]; } _model.setHorizontalHeaderLabels(headerData); @@ -154,14 +159,16 @@ void ModelHandler::download() { // Query models list queryNewFiles(); - QMutexLocker lockerModel(&_modelMutex); + _lock.lockForWrite(); if (_initiateExit) { + _lock.unlock(); return; } // Show loading message QStandardItem* loadingItem = new QStandardItem(LOADING_MSG); loadingItem->setEnabled(false); _model.appendRow(loadingItem); + _lock.unlock(); } void ModelHandler::update() { @@ -169,8 +176,7 @@ void ModelHandler::update() { } void ModelHandler::exit() { - QMutexLocker lockerDownload(&_downloadMutex); - QMutexLocker lockerModel(&_modelMutex); + _lock.lockForWrite(); _initiateExit = true; // Disconnect everything @@ -182,18 +188,18 @@ void ModelHandler::exit() { thread()->connect(this, SIGNAL(destroyed()), SLOT(quit())); thread()->connect(thread(), SIGNAL(finished()), SLOT(deleteLater())); deleteLater(); + _lock.unlock(); } void ModelHandler::downloadFinished() { - QMutexLocker lockerDownload(&_downloadMutex); - if (_initiateExit) { - return; + if (_downloader.getData().startsWith("setEnabled(false); _model.appendRow(errorItem); - + + _lock.unlock(); return false; } @@ -301,6 +309,12 @@ bool ModelHandler::parseXML(QByteArray xmlFile) { // query those files queryNewFiles(lastKey); } + _lock.unlock(); + + if (!truncated) { + qDebug() << "Emitting..."; + emit doneDownloading(); + } return true; } \ No newline at end of file diff --git a/interface/src/ui/ModelsBrowser.h b/interface/src/ui/ModelsBrowser.h index 7343c0c14f..9bc239ba18 100644 --- a/interface/src/ui/ModelsBrowser.h +++ b/interface/src/ui/ModelsBrowser.h @@ -11,22 +11,25 @@ #include #include -#include #include +#include +#include -#include +#include "FileDownloader.h" -typedef -enum { +enum ModelType { Head, Skeleton -} ModelType; +}; class ModelHandler : public QObject { Q_OBJECT public: ModelHandler(ModelType modelsType, QWidget* parent = NULL); - QStandardItemModel* getModel() { QMutexLocker locker(&_modelMutex); return &_model; } + + void lockModel() { _lock.lockForRead(); } + QStandardItemModel* getModel() { return &_model; } + void unlockModel() { _lock.unlock(); } signals: void doneDownloading(); @@ -43,9 +46,8 @@ private slots: private: bool _initiateExit; ModelType _type; - QMutex _downloadMutex; FileDownloader _downloader; - QMutex _modelMutex; + QReadWriteLock _lock; QStandardItemModel _model; void queryNewFiles(QString marker = QString()); @@ -58,7 +60,6 @@ class ModelsBrowser : public QWidget { public: ModelsBrowser(ModelType modelsType, QWidget* parent = NULL); - ~ModelsBrowser(); signals: void startDownloading(); From 97ba5250a5d920fc93770c50ee372a948c279954 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 2 Apr 2014 12:01:18 -0700 Subject: [PATCH 105/595] Only simulate() Avatar Models when necessary Also: rebuild collision shapes when Model scale changes --- interface/src/avatar/Avatar.cpp | 33 ++++++++++++++-------- interface/src/avatar/FaceModel.cpp | 5 ++-- interface/src/avatar/MyAvatar.cpp | 2 ++ interface/src/avatar/SkeletonModel.cpp | 3 ++ interface/src/renderer/Model.cpp | 38 ++++++++++++++++---------- interface/src/renderer/Model.h | 9 +++--- libraries/avatars/src/AvatarData.cpp | 2 ++ libraries/avatars/src/AvatarData.h | 2 ++ 8 files changed, 59 insertions(+), 35 deletions(-) diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 5e12282f53..ec8539954a 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -117,20 +117,29 @@ void Avatar::simulate(float deltaTime) { getHand()->simulate(deltaTime, false); _skeletonModel.setLODDistance(getLODDistance()); - // copy joint data to skeleton - for (int i = 0; i < _jointData.size(); i++) { - const JointData& data = _jointData.at(i); - _skeletonModel.setJointState(i, data.valid, data.rotation); - } - glm::vec3 headPosition = _position; if (!_shouldRenderBillboard && inViewFrustum) { - _skeletonModel.simulate(deltaTime); - _skeletonModel.getHeadPosition(headPosition); + glm::vec3 headPosition = _position; + + _skeletonModel.updateGeometry(); + if (_skeletonModel.isActive()) { + // copy joint data to skeleton + if (_hasNewJointRotations) { + for (int i = 0; i < _jointData.size(); i++) { + const JointData& data = _jointData.at(i); + _skeletonModel.setJointState(i, data.valid, data.rotation); + } + _skeletonModel.simulate(deltaTime); + _hasNewJointRotations = false; + } + _skeletonModel.getHeadPosition(headPosition); + } + + Head* head = getHead(); + head->setPosition(headPosition); + head->setScale(_scale); + head->getFaceModel().updateGeometry(); + head->simulate(deltaTime, false, _shouldRenderBillboard); } - Head* head = getHead(); - head->setPosition(headPosition); - head->setScale(_scale); - head->simulate(deltaTime, false, _shouldRenderBillboard); // use speed and angular velocity to determine walking vs. standing if (_speed + fabs(_bodyYawDelta) > 0.2) { diff --git a/interface/src/avatar/FaceModel.cpp b/interface/src/avatar/FaceModel.cpp index c483642d15..5d9b71f11d 100644 --- a/interface/src/avatar/FaceModel.cpp +++ b/interface/src/avatar/FaceModel.cpp @@ -19,8 +19,7 @@ FaceModel::FaceModel(Head* owningHead) : } void FaceModel::simulate(float deltaTime) { - bool geometryIsUpToDate = updateGeometry(); - if (!geometryIsUpToDate) { + if (!isActive()) { return; } Avatar* owningAvatar = static_cast(_owningHead->_owningAvatar); @@ -42,7 +41,7 @@ void FaceModel::simulate(float deltaTime) { setPupilDilation(_owningHead->getPupilDilation()); setBlendshapeCoefficients(_owningHead->getBlendshapeCoefficients()); - Model::simulateInternal(deltaTime); + Model::simulate(deltaTime); } void FaceModel::maybeUpdateNeckRotation(const JointState& parentState, const FBXJoint& joint, JointState& state) { diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 9dcfaa09ba..0b220a532c 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -289,6 +289,7 @@ void MyAvatar::simulate(float deltaTime) { getHand()->collideAgainstOurself(); getHand()->simulate(deltaTime, true); + _skeletonModel.updateGeometry(); _skeletonModel.simulate(deltaTime); // copy out the skeleton joints from the model @@ -305,6 +306,7 @@ void MyAvatar::simulate(float deltaTime) { } head->setPosition(headPosition); head->setScale(_scale); + head->getFaceModel().updateGeometry(); head->simulate(deltaTime, true); // Zero thrust out now that we've added it to velocity in this frame diff --git a/interface/src/avatar/SkeletonModel.cpp b/interface/src/avatar/SkeletonModel.cpp index e6318e2003..0ce97f4ef9 100644 --- a/interface/src/avatar/SkeletonModel.cpp +++ b/interface/src/avatar/SkeletonModel.cpp @@ -19,6 +19,9 @@ SkeletonModel::SkeletonModel(Avatar* owningAvatar) : } void SkeletonModel::simulate(float deltaTime) { + if (!isActive()) { + return; + } setTranslation(_owningAvatar->getPosition()); setRotation(_owningAvatar->getOrientation() * glm::angleAxis(PI, glm::vec3(0.0f, 1.0f, 0.0f))); const float MODEL_SCALE = 0.0006f; diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 1e609afe33..000a41b7d5 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -56,6 +56,14 @@ Model::SkinLocations Model::_skinLocations; Model::SkinLocations Model::_skinNormalMapLocations; Model::SkinLocations Model::_skinShadowLocations; +void Model::setScale(const glm::vec3& scale) { + glm::vec3 deltaScale = _scale - scale; + if (glm::length2(deltaScale) > EPSILON) { + _scale = scale; + rebuildShapes(); + } +} + void Model::initSkinProgram(ProgramObject& program, Model::SkinLocations& locations) { program.bind(); locations.clusterMatrices = program.uniformLocation("clusterMatrices"); @@ -182,10 +190,14 @@ void Model::reset() { } } -// return 'true' if geometry is up to date -bool Model::updateGeometry() { - bool needToRebuild = false; +void Model::updateGeometry() { + // NOTE: this is a recursive call that walks all attachments, and their attachments + for (int i = 0; i < _attachments.size(); i++) { + Model* model = _attachments.at(i); + model->updateGeometry(); + } + bool needToRebuild = false; if (_nextGeometry) { _nextGeometry = _nextGeometry->getLODOrFallback(_lodDistance, _nextLODHysteresis); _nextGeometry->setLoadPriority(this, -_lodDistance); @@ -197,7 +209,7 @@ bool Model::updateGeometry() { } if (!_geometry) { // geometry is not ready - return false; + return; } QSharedPointer geometry = _geometry->getLODOrFallback(_lodDistance, _lodHysteresis); @@ -260,9 +272,9 @@ bool Model::updateGeometry() { model->setURL(attachment.url); _attachments.append(model); } - createShapes(); + rebuildShapes(); } - return true; + return; } bool Model::render(float alpha, bool forShadowMap) { @@ -440,7 +452,7 @@ void Model::clearShapes() { _jointShapes.clear(); } -void Model::createShapes() { +void Model::rebuildShapes() { clearShapes(); if (_jointStates.isEmpty()) { @@ -670,20 +682,16 @@ void Blender::run() { Q_ARG(const QVector&, vertices), Q_ARG(const QVector&, normals)); } - void Model::simulate(float deltaTime) { - bool geometryIsUpToDate = updateGeometry(); - if (!geometryIsUpToDate) { + // NOTE: this is a recursive call that walks all attachments, and their attachments + if (!isActive()) { return; } - simulateInternal(deltaTime); -} - -void Model::simulateInternal(float deltaTime) { // update the world space transforms for all joints for (int i = 0; i < _jointStates.size(); i++) { updateJointState(i); } + _shapesAreDirty = true; const FBXGeometry& geometry = _geometry->getFBXGeometry(); @@ -720,7 +728,6 @@ void Model::simulateInternal(float deltaTime) { } void Model::updateJointState(int index) { - _shapesAreDirty = true; JointState& state = _jointStates[index]; const FBXGeometry& geometry = _geometry->getFBXGeometry(); const FBXJoint& joint = geometry.joints.at(index); @@ -838,6 +845,7 @@ bool Model::setJointPosition(int jointIndex, const glm::vec3& position, int last for (int j = freeLineage.size() - 1; j >= 0; j--) { updateJointState(freeLineage.at(j)); } + _shapesAreDirty = true; return true; } diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index e7c94deb43..0c05b18429 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -36,7 +36,7 @@ public: void setRotation(const glm::quat& rotation) { _rotation = rotation; } const glm::quat& getRotation() const { return _rotation; } - void setScale(const glm::vec3& scale) { _scale = scale; } + void setScale(const glm::vec3& scale); const glm::vec3& getScale() const { return _scale; } void setOffset(const glm::vec3& offset) { _offset = offset; } @@ -156,7 +156,7 @@ public: float getRightArmLength() const; void clearShapes(); - void createShapes(); + void rebuildShapes(); void updateShapePositions(); void renderJointCollisionShapes(float alpha); void renderBoundingCollisionShapes(float alpha); @@ -185,6 +185,8 @@ public: /// Sets blended vertices computed in a separate thread. void setBlendedVertices(const QVector& vertices, const QVector& normals); + void updateGeometry(); + protected: QSharedPointer _geometry; @@ -217,9 +219,6 @@ protected: QVector _meshStates; - bool updateGeometry(); - void simulateInternal(float deltaTime); - /// Updates the state of the joint at the specified index. virtual void updateJointState(int index); diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index 31639b6836..930e3f7350 100644 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -40,6 +40,7 @@ AvatarData::AvatarData() : _handState(0), _keyState(NO_KEY_DOWN), _isChatCirclingEnabled(false), + _hasNewJointRotations(true), _headData(NULL), _handData(NULL), _displayNameBoundingRect(), @@ -483,6 +484,7 @@ int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { } } } // numJoints * 8 bytes + _hasNewJointRotations = true; return sourceBuffer - startPosition; } diff --git a/libraries/avatars/src/AvatarData.h b/libraries/avatars/src/AvatarData.h index 2ea20c1041..221bbd0428 100755 --- a/libraries/avatars/src/AvatarData.h +++ b/libraries/avatars/src/AvatarData.h @@ -242,6 +242,8 @@ protected: bool _isChatCirclingEnabled; + bool _hasNewJointRotations; // set in AvatarData, cleared in Avatar + HeadData* _headData; HandData* _handData; From 40844d2000ede56d4ac04f6de713e2def80935d7 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Wed, 2 Apr 2014 12:40:01 -0700 Subject: [PATCH 106/595] Working on ability to set a region of the metavoxel data directly. --- .../src/metavoxels/MetavoxelServer.cpp | 2 + libraries/metavoxels/src/Bitstream.h | 7 ++ libraries/metavoxels/src/MetavoxelData.cpp | 92 ++++++++++++++++++- libraries/metavoxels/src/MetavoxelData.h | 18 +++- .../metavoxels/src/MetavoxelMessages.cpp | 9 ++ libraries/metavoxels/src/MetavoxelMessages.h | 17 ++++ 6 files changed, 139 insertions(+), 6 deletions(-) diff --git a/assignment-client/src/metavoxels/MetavoxelServer.cpp b/assignment-client/src/metavoxels/MetavoxelServer.cpp index 98c91d44e7..23c8f2189c 100644 --- a/assignment-client/src/metavoxels/MetavoxelServer.cpp +++ b/assignment-client/src/metavoxels/MetavoxelServer.cpp @@ -95,6 +95,8 @@ MetavoxelSession::MetavoxelSession(MetavoxelServer* server, const SharedNodePoin connect(&_sequencer, SIGNAL(readyToRead(Bitstream&)), SLOT(readPacket(Bitstream&))); connect(&_sequencer, SIGNAL(sendAcknowledged(int)), SLOT(clearSendRecordsBefore(int))); connect(&_sequencer, SIGNAL(receivedHighPriorityMessage(const QVariant&)), SLOT(handleMessage(const QVariant&))); + connect(_sequencer.getReliableInputChannel(), SIGNAL(receivedMessage(const QVariant&)), + SLOT(handleMessage(const QVariant&))); // insert the baseline send record SendRecord record = { 0 }; diff --git a/libraries/metavoxels/src/Bitstream.h b/libraries/metavoxels/src/Bitstream.h index 760154a928..8f36ce9a08 100644 --- a/libraries/metavoxels/src/Bitstream.h +++ b/libraries/metavoxels/src/Bitstream.h @@ -920,6 +920,13 @@ public: _Pragma(STRINGIFY(unused(_TypePtr##X))) #endif +/// Registers a simple type and its streamer. +template int registerSimpleMetaType() { + int type = qRegisterMetaType(); + Bitstream::registerTypeStreamer(type, new SimpleTypeStreamer()); + return type; +} + /// Registers a streamable type and its streamer. template int registerStreamableMetaType() { int type = qRegisterMetaType(); diff --git a/libraries/metavoxels/src/MetavoxelData.cpp b/libraries/metavoxels/src/MetavoxelData.cpp index e548de46c7..c89967b3a0 100644 --- a/libraries/metavoxels/src/MetavoxelData.cpp +++ b/libraries/metavoxels/src/MetavoxelData.cpp @@ -24,6 +24,8 @@ REGISTER_META_OBJECT(Spanner) REGISTER_META_OBJECT(Sphere) REGISTER_META_OBJECT(StaticModel) +static int metavoxelDataTypeId = registerSimpleMetaType(); + MetavoxelLOD::MetavoxelLOD(const glm::vec3& position, float threshold) : position(position), threshold(threshold) { @@ -327,6 +329,67 @@ const int Y_MAXIMUM_FLAG = 2; const int Z_MAXIMUM_FLAG = 4; const int MAXIMUM_FLAG_MASK = X_MAXIMUM_FLAG | Y_MAXIMUM_FLAG | Z_MAXIMUM_FLAG; +static glm::vec3 getNextMinimum(const glm::vec3& minimum, float nextSize, int index) { + return minimum + glm::vec3( + (index & X_MAXIMUM_FLAG) ? nextSize : 0.0f, + (index & Y_MAXIMUM_FLAG) ? nextSize : 0.0f, + (index & Z_MAXIMUM_FLAG) ? nextSize : 0.0f); +} + +static void setNode(const AttributePointer& attribute, MetavoxelNode*& node, MetavoxelNode* other) { + if (node) { + node->decrementReferenceCount(attribute); + } + (node = other)->incrementReferenceCount(); +} + +static void setNode(const AttributeValue& value, MetavoxelNode*& node, const glm::vec3& minimum, float size, + MetavoxelNode* other, const glm::vec3& otherMinimum, float otherSize) { + if (otherSize >= size) { + setNode(value.getAttribute(), node, other); + return; + } + if (!node) { + node = new MetavoxelNode(value); + } + int index = 0; + float otherHalfSize = otherSize * 0.5f; + float nextSize = size * 0.5f; + if (otherMinimum.x + otherHalfSize >= minimum.x + nextSize) { + index |= X_MAXIMUM_FLAG; + } + if (otherMinimum.y + otherHalfSize >= minimum.y + nextSize) { + index |= Y_MAXIMUM_FLAG; + } + if (otherMinimum.z + otherHalfSize >= minimum.z + nextSize) { + index |= Z_MAXIMUM_FLAG; + } + if (node->isLeaf()) { + for (int i = 1; i < MetavoxelNode::CHILD_COUNT; i++) { + node->setChild((index + i) % MetavoxelNode::CHILD_COUNT, new MetavoxelNode( + node->getAttributeValue(value.getAttribute()))); + } + } + MetavoxelNode* nextNode = node->getChild(index); + setNode(node->getAttributeValue(value.getAttribute()), nextNode, getNextMinimum(minimum, nextSize, index), + nextSize, other, otherMinimum, otherSize); + node->setChild(index, nextNode); +} + +void MetavoxelData::set(const glm::vec3& minimum, const MetavoxelData& data) { + // expand to fit the entire data + Box bounds = minimum + glm::vec3(data.getSize(), data.getSize(), data.getSize()); + while (!getBounds().contains(bounds)) { + expand(); + } + + // set each attribute separately + for (QHash::const_iterator it = data._roots.constBegin(); + it != data._roots.constEnd(); it++) { + setNode(it.key(), _roots[it.key()], getMinimum(), getSize(), it.value(), minimum, data.getSize()); + } +} + static int getOppositeIndex(int index) { return index ^ MAXIMUM_FLAG_MASK; } @@ -511,6 +574,14 @@ MetavoxelNode* MetavoxelData::createRoot(const AttributePointer& attribute) { return root = new MetavoxelNode(attribute); } +bool MetavoxelData::operator==(const MetavoxelData& other) const { + return _size == other._size && _roots == other._roots; +} + +bool MetavoxelData::operator!=(const MetavoxelData& other) const { + return _size != other._size || _roots != other._roots; +} + void MetavoxelData::incrementRootReferenceCounts() { for (QHash::const_iterator it = _roots.constBegin(); it != _roots.constEnd(); it++) { it.value()->incrementReferenceCount(); @@ -523,11 +594,22 @@ void MetavoxelData::decrementRootReferenceCounts() { } } -static glm::vec3 getNextMinimum(const glm::vec3& minimum, float nextSize, int index) { - return minimum + glm::vec3( - (index & X_MAXIMUM_FLAG) ? nextSize : 0.0f, - (index & Y_MAXIMUM_FLAG) ? nextSize : 0.0f, - (index & Z_MAXIMUM_FLAG) ? nextSize : 0.0f); +Bitstream& operator<<(Bitstream& out, const MetavoxelData& data) { + data.write(out); + return out; +} + +Bitstream& operator>>(Bitstream& in, MetavoxelData& data) { + data.read(in); + return in; +} + +template<> void Bitstream::writeDelta(const MetavoxelData& value, const MetavoxelData& reference) { + value.writeDelta(reference, MetavoxelLOD(), *this, MetavoxelLOD()); +} + +template<> void Bitstream::readDelta(MetavoxelData& value, const MetavoxelData& reference) { + value.readDelta(reference, MetavoxelLOD(), *this, MetavoxelLOD()); } bool MetavoxelStreamState::shouldSubdivide() const { diff --git a/libraries/metavoxels/src/MetavoxelData.h b/libraries/metavoxels/src/MetavoxelData.h index fa408aafb7..4db2e919b4 100644 --- a/libraries/metavoxels/src/MetavoxelData.h +++ b/libraries/metavoxels/src/MetavoxelData.h @@ -90,6 +90,9 @@ public: SharedObjectPointer findFirstRaySpannerIntersection(const glm::vec3& origin, const glm::vec3& direction, const AttributePointer& attribute, float& distance, const MetavoxelLOD& lod = MetavoxelLOD()); + /// Sets part of the data. + void set(const glm::vec3& minimum, const MetavoxelData& data); + /// Expands the tree, increasing its capacity in all dimensions. void expand(); @@ -103,6 +106,9 @@ public: MetavoxelNode* getRoot(const AttributePointer& attribute) const { return _roots.value(attribute); } MetavoxelNode* createRoot(const AttributePointer& attribute); + bool operator==(const MetavoxelData& other) const; + bool operator!=(const MetavoxelData& other) const; + private: friend class MetavoxelVisitation; @@ -114,6 +120,16 @@ private: QHash _roots; }; +Bitstream& operator<<(Bitstream& out, const MetavoxelData& data); + +Bitstream& operator>>(Bitstream& in, MetavoxelData& data); + +template<> void Bitstream::writeDelta(const MetavoxelData& value, const MetavoxelData& reference); + +template<> void Bitstream::readDelta(MetavoxelData& value, const MetavoxelData& reference); + +Q_DECLARE_METATYPE(MetavoxelData) + /// Holds the state used in streaming metavoxel data. class MetavoxelStreamState { public: @@ -592,7 +608,7 @@ public: const QUrl& getURL() const { return _url; } virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, - const glm::vec3& clipMinimum, float clipSize,float& distance) const; + const glm::vec3& clipMinimum, float clipSize, float& distance) const; signals: diff --git a/libraries/metavoxels/src/MetavoxelMessages.cpp b/libraries/metavoxels/src/MetavoxelMessages.cpp index ce0d01ccf2..7bf10467f6 100644 --- a/libraries/metavoxels/src/MetavoxelMessages.cpp +++ b/libraries/metavoxels/src/MetavoxelMessages.cpp @@ -305,3 +305,12 @@ void SetSpannerEdit::apply(MetavoxelData& data, const WeakSharedObjectHash& obje setIntersectingMasked(spanner->getBounds(), data); } + +SetDataEdit::SetDataEdit(const glm::vec3& minimum, const MetavoxelData& data) : + minimum(minimum), + data(data) { +} + +void SetDataEdit::apply(MetavoxelData& data, const WeakSharedObjectHash& objects) const { + data.set(minimum, this->data); +} diff --git a/libraries/metavoxels/src/MetavoxelMessages.h b/libraries/metavoxels/src/MetavoxelMessages.h index 25db8e5464..309439812d 100644 --- a/libraries/metavoxels/src/MetavoxelMessages.h +++ b/libraries/metavoxels/src/MetavoxelMessages.h @@ -176,4 +176,21 @@ public: DECLARE_STREAMABLE_METATYPE(SetSpannerEdit) +/// An edit that directly sets part of the metavoxel data. +class SetDataEdit : public MetavoxelEdit { + STREAMABLE + +public: + + STREAM glm::vec3 minimum; + + STREAM MetavoxelData data; + + SetDataEdit(const glm::vec3& minimum = glm::vec3(), const MetavoxelData& data = MetavoxelData()); + + virtual void apply(MetavoxelData& data, const WeakSharedObjectHash& objects) const; +}; + +DECLARE_STREAMABLE_METATYPE(SetDataEdit) + #endif /* defined(__interface__MetavoxelMessages__) */ From 3a44a846ed3daa6f8cd4c2d35044293b3721dd13 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Wed, 2 Apr 2014 15:48:53 -0700 Subject: [PATCH 107/595] More set/blend bits. --- .../metavoxels/src/AttributeRegistry.cpp | 28 ++++++++++ libraries/metavoxels/src/AttributeRegistry.h | 12 ++++ libraries/metavoxels/src/MetavoxelData.cpp | 56 +++++++++++++++---- libraries/metavoxels/src/MetavoxelData.h | 8 ++- .../metavoxels/src/MetavoxelMessages.cpp | 7 ++- libraries/metavoxels/src/MetavoxelMessages.h | 4 +- 6 files changed, 96 insertions(+), 19 deletions(-) diff --git a/libraries/metavoxels/src/AttributeRegistry.cpp b/libraries/metavoxels/src/AttributeRegistry.cpp index fc448613f9..8914a9e3c9 100644 --- a/libraries/metavoxels/src/AttributeRegistry.cpp +++ b/libraries/metavoxels/src/AttributeRegistry.cpp @@ -144,6 +144,14 @@ void OwnedAttributeValue::mix(const AttributeValue& first, const AttributeValue& _value = _attribute->mix(first.getValue(), second.getValue(), alpha); } +void OwnedAttributeValue::blend(const AttributeValue& source, const AttributeValue& dest) { + if (_attribute) { + _attribute->destroy(_value); + } + _attribute = source.getAttribute(); + _value = _attribute->blend(source.getValue(), dest.getValue()); +} + OwnedAttributeValue& OwnedAttributeValue::operator=(const AttributeValue& other) { if (_attribute) { _attribute->destroy(_value); @@ -243,6 +251,19 @@ void* QRgbAttribute::mix(void* first, void* second, float alpha) const { glm::mix((float)qAlpha(firstValue), (float)qAlpha(secondValue), alpha))); } +const float EIGHT_BIT_MAXIMUM = 255.0f; + +void* QRgbAttribute::blend(void* source, void* dest) const { + QRgb sourceValue = decodeInline(source); + QRgb destValue = decodeInline(dest); + float alpha = qAlpha(sourceValue) / EIGHT_BIT_MAXIMUM; + return encodeInline(qRgba( + glm::mix((float)qRed(destValue), (float)qRed(sourceValue), alpha), + glm::mix((float)qGreen(destValue), (float)qGreen(sourceValue), alpha), + glm::mix((float)qBlue(destValue), (float)qBlue(sourceValue), alpha), + glm::mix((float)qAlpha(destValue), (float)qAlpha(sourceValue), alpha))); +} + void* QRgbAttribute::createFromScript(const QScriptValue& value, QScriptEngine* engine) const { return encodeInline((QRgb)value.toUInt32()); } @@ -287,6 +308,13 @@ void* PackedNormalAttribute::mix(void* first, void* second, float alpha) const { return encodeInline(packNormal(glm::normalize(glm::mix(firstNormal, secondNormal, alpha)))); } +void* PackedNormalAttribute::blend(void* source, void* dest) const { + QRgb sourceValue = decodeInline(source); + QRgb destValue = decodeInline(dest); + float alpha = qAlpha(sourceValue) / EIGHT_BIT_MAXIMUM; + return encodeInline(packNormal(glm::normalize(glm::mix(unpackNormal(destValue), unpackNormal(sourceValue), alpha)))); +} + const float CHAR_SCALE = 127.0f; const float INVERSE_CHAR_SCALE = 1.0f / CHAR_SCALE; diff --git a/libraries/metavoxels/src/AttributeRegistry.h b/libraries/metavoxels/src/AttributeRegistry.h index f7d8d955a5..db13ea9f4e 100644 --- a/libraries/metavoxels/src/AttributeRegistry.h +++ b/libraries/metavoxels/src/AttributeRegistry.h @@ -158,6 +158,9 @@ public: /// Sets this attribute to a mix of the first and second provided. void mix(const AttributeValue& first, const AttributeValue& second, float alpha); + /// Sets this attribute to a blend of the source and destination. + void blend(const AttributeValue& source, const AttributeValue& dest); + /// Destroys the current value, if any, and copies the specified other value. OwnedAttributeValue& operator=(const AttributeValue& other); @@ -218,6 +221,9 @@ public: /// Mixes the first and the second, returning a new value with the result. virtual void* mix(void* first, void* second, float alpha) const = 0; + /// Blends the source with the destination, returning a new value with the result. + virtual void* blend(void* source, void* dest) const = 0; + virtual void* getDefaultValue() const = 0; virtual void* createFromScript(const QScriptValue& value, QScriptEngine* engine) const { return create(); } @@ -249,6 +255,8 @@ public: virtual void* mix(void* first, void* second, float alpha) const { return create(alpha < 0.5f ? first : second); } + virtual void* blend(void* source, void* dest) const { return create(source); } + virtual void* getDefaultValue() const { return encodeInline(_defaultValue); } protected: @@ -315,6 +323,8 @@ public: virtual void* mix(void* first, void* second, float alpha) const; + virtual void* blend(void* source, void* dest) const; + virtual void* createFromScript(const QScriptValue& value, QScriptEngine* engine) const; virtual void* createFromVariant(const QVariant& value) const; @@ -333,6 +343,8 @@ public: virtual bool merge(void*& parent, void* children[], bool postRead = false) const; virtual void* mix(void* first, void* second, float alpha) const; + + virtual void* blend(void* source, void* dest) const; }; /// Packs a normal into an RGB value. diff --git a/libraries/metavoxels/src/MetavoxelData.cpp b/libraries/metavoxels/src/MetavoxelData.cpp index c89967b3a0..efbc0b157d 100644 --- a/libraries/metavoxels/src/MetavoxelData.cpp +++ b/libraries/metavoxels/src/MetavoxelData.cpp @@ -336,17 +336,41 @@ static glm::vec3 getNextMinimum(const glm::vec3& minimum, float nextSize, int in (index & Z_MAXIMUM_FLAG) ? nextSize : 0.0f); } -static void setNode(const AttributePointer& attribute, MetavoxelNode*& node, MetavoxelNode* other) { - if (node) { - node->decrementReferenceCount(attribute); +static void setNode(const AttributeValue& value, MetavoxelNode*& node, MetavoxelNode* other, bool blend) { + if (!blend) { + // if we're not blending, we can just make a shallow copy + if (node) { + node->decrementReferenceCount(value.getAttribute()); + } + (node = other)->incrementReferenceCount(); + return; } - (node = other)->incrementReferenceCount(); + if (node) { + MetavoxelNode* oldNode = node; + node = new MetavoxelNode(value.getAttribute(), oldNode); + oldNode->decrementReferenceCount(value.getAttribute()); + + } else { + node = new MetavoxelNode(value); + } + OwnedAttributeValue oldValue = node->getAttributeValue(value.getAttribute()); + node->blendAttributeValues(other->getAttributeValue(value.getAttribute()), oldValue); + if (other->isLeaf()) { + node->clearChildren(value.getAttribute()); + return; + } + for (int i = 0; i < MetavoxelNode::CHILD_COUNT; i++) { + MetavoxelNode* child = node->getChild(i); + setNode(oldValue, child, other->getChild(i), true); + node->setChild(i, child); + } + node->mergeChildren(value.getAttribute()); } static void setNode(const AttributeValue& value, MetavoxelNode*& node, const glm::vec3& minimum, float size, - MetavoxelNode* other, const glm::vec3& otherMinimum, float otherSize) { + MetavoxelNode* other, const glm::vec3& otherMinimum, float otherSize, bool blend) { if (otherSize >= size) { - setNode(value.getAttribute(), node, other); + setNode(value, node, other, blend); return; } if (!node) { @@ -372,21 +396,27 @@ static void setNode(const AttributeValue& value, MetavoxelNode*& node, const glm } MetavoxelNode* nextNode = node->getChild(index); setNode(node->getAttributeValue(value.getAttribute()), nextNode, getNextMinimum(minimum, nextSize, index), - nextSize, other, otherMinimum, otherSize); + nextSize, other, otherMinimum, otherSize, blend); node->setChild(index, nextNode); + node->mergeChildren(value.getAttribute()); } -void MetavoxelData::set(const glm::vec3& minimum, const MetavoxelData& data) { +void MetavoxelData::set(const glm::vec3& minimum, const MetavoxelData& data, bool blend) { // expand to fit the entire data Box bounds = minimum + glm::vec3(data.getSize(), data.getSize(), data.getSize()); while (!getBounds().contains(bounds)) { expand(); } - // set each attribute separately + // set/mix each attribute separately for (QHash::const_iterator it = data._roots.constBegin(); it != data._roots.constEnd(); it++) { - setNode(it.key(), _roots[it.key()], getMinimum(), getSize(), it.value(), minimum, data.getSize()); + MetavoxelNode*& root = _roots[it.key()]; + setNode(it.key(), root, getMinimum(), getSize(), it.value(), minimum, data.getSize(), blend); + if (root->isLeaf() && root->getAttributeValue(it.key()).isDefault()) { + _roots.remove(it.key()); + root->decrementReferenceCount(it.key()); + } } } @@ -659,7 +689,11 @@ MetavoxelNode::MetavoxelNode(const AttributePointer& attribute, const MetavoxelN void MetavoxelNode::setAttributeValue(const AttributeValue& attributeValue) { attributeValue.getAttribute()->destroy(_attributeValue); _attributeValue = attributeValue.copy(); - clearChildren(attributeValue.getAttribute()); +} + +void MetavoxelNode::blendAttributeValues(const AttributeValue& source, const AttributeValue& dest) { + source.getAttribute()->destroy(_attributeValue); + _attributeValue = source.getAttribute()->blend(source.getValue(), dest.getValue()); } AttributeValue MetavoxelNode::getAttributeValue(const AttributePointer& attribute) const { diff --git a/libraries/metavoxels/src/MetavoxelData.h b/libraries/metavoxels/src/MetavoxelData.h index 4db2e919b4..ed8b1a224c 100644 --- a/libraries/metavoxels/src/MetavoxelData.h +++ b/libraries/metavoxels/src/MetavoxelData.h @@ -91,7 +91,7 @@ public: const AttributePointer& attribute, float& distance, const MetavoxelLOD& lod = MetavoxelLOD()); /// Sets part of the data. - void set(const glm::vec3& minimum, const MetavoxelData& data); + void set(const glm::vec3& minimum, const MetavoxelData& data, bool blend = false); /// Expands the tree, increasing its capacity in all dimensions. void expand(); @@ -158,6 +158,8 @@ public: void setAttributeValue(const AttributeValue& attributeValue); + void blendAttributeValues(const AttributeValue& source, const AttributeValue& dest); + AttributeValue getAttributeValue(const AttributePointer& attribute) const; void* getAttributeValue() const { return _attributeValue; } @@ -190,13 +192,13 @@ public: void destroy(const AttributePointer& attribute); + void clearChildren(const AttributePointer& attribute); + private: Q_DISABLE_COPY(MetavoxelNode) friend class MetavoxelVisitation; - void clearChildren(const AttributePointer& attribute); - int _referenceCount; void* _attributeValue; MetavoxelNode* _children[CHILD_COUNT]; diff --git a/libraries/metavoxels/src/MetavoxelMessages.cpp b/libraries/metavoxels/src/MetavoxelMessages.cpp index 7bf10467f6..c930688cbd 100644 --- a/libraries/metavoxels/src/MetavoxelMessages.cpp +++ b/libraries/metavoxels/src/MetavoxelMessages.cpp @@ -306,11 +306,12 @@ void SetSpannerEdit::apply(MetavoxelData& data, const WeakSharedObjectHash& obje setIntersectingMasked(spanner->getBounds(), data); } -SetDataEdit::SetDataEdit(const glm::vec3& minimum, const MetavoxelData& data) : +SetDataEdit::SetDataEdit(const glm::vec3& minimum, const MetavoxelData& data, bool blend) : minimum(minimum), - data(data) { + data(data), + blend(blend) { } void SetDataEdit::apply(MetavoxelData& data, const WeakSharedObjectHash& objects) const { - data.set(minimum, this->data); + data.set(minimum, this->data, blend); } diff --git a/libraries/metavoxels/src/MetavoxelMessages.h b/libraries/metavoxels/src/MetavoxelMessages.h index 309439812d..4f90a52e4c 100644 --- a/libraries/metavoxels/src/MetavoxelMessages.h +++ b/libraries/metavoxels/src/MetavoxelMessages.h @@ -183,10 +183,10 @@ class SetDataEdit : public MetavoxelEdit { public: STREAM glm::vec3 minimum; - STREAM MetavoxelData data; + STREAM bool blend; - SetDataEdit(const glm::vec3& minimum = glm::vec3(), const MetavoxelData& data = MetavoxelData()); + SetDataEdit(const glm::vec3& minimum = glm::vec3(), const MetavoxelData& data = MetavoxelData(), bool blend = false); virtual void apply(MetavoxelData& data, const WeakSharedObjectHash& objects) const; }; From 52df77b4b560005aece460c907058fc055ac054b Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 2 Apr 2014 16:25:35 -0700 Subject: [PATCH 108/595] Final work on models metadata support --- interface/src/ui/ModelsBrowser.cpp | 114 +++++++++++++++++------- interface/src/ui/ModelsBrowser.h | 14 ++- libraries/shared/src/FileDownloader.cpp | 45 ---------- libraries/shared/src/FileDownloader.h | 41 --------- 4 files changed, 87 insertions(+), 127 deletions(-) delete mode 100644 libraries/shared/src/FileDownloader.cpp delete mode 100644 libraries/shared/src/FileDownloader.h diff --git a/interface/src/ui/ModelsBrowser.cpp b/interface/src/ui/ModelsBrowser.cpp index 15f1e9111e..e128d047ef 100644 --- a/interface/src/ui/ModelsBrowser.cpp +++ b/interface/src/ui/ModelsBrowser.cpp @@ -8,11 +8,10 @@ #include #include -#include #include #include #include -#include +#include #include #include @@ -33,27 +32,39 @@ static const QString KEY_NAME = "Key"; static const QString LOADING_MSG = "Loading..."; static const QString ERROR_MSG = "Error loading files"; +static const QString DO_NOT_MODIFY_TAG = "DoNotModify"; + enum ModelMetaData { NAME, - CREATOR, - UPLOAD_DATE, TYPE, GENDER, + CREATOR, + UPLOAD_DATE, MODEL_METADATA_COUNT }; static const QString propertiesNames[MODEL_METADATA_COUNT] = { "Name", - "Creator", - "Upload Date", "Type", - "Gender" + "Gender", + "Creator", + "Last Modified" +}; +static const QString propertiesIds[MODEL_METADATA_COUNT] = { + DO_NOT_MODIFY_TAG, + "Type", + "Gender", + "x-amz-request-id", + "Last-Modified" }; ModelsBrowser::ModelsBrowser(ModelType modelsType, QWidget* parent) : QWidget(parent), _handler(new ModelHandler(modelsType)) { + connect(_handler, SIGNAL(doneDownloading()), SLOT(resizeView())); + connect(_handler, SIGNAL(updated()), SLOT(resizeView())); + // Connect handler _handler->connect(this, SIGNAL(startDownloading()), SLOT(download())); _handler->connect(_handler, SIGNAL(doneDownloading()), SLOT(update())); @@ -106,6 +117,12 @@ void ModelsBrowser::applyFilter(const QString &filter) { _handler->unlockModel(); } +void ModelsBrowser::resizeView() { + for (int i = 0; i < MODEL_METADATA_COUNT; ++i) { + _view.resizeColumnToContents(i); + } +} + void ModelsBrowser::browse() { QDialog dialog; dialog.setWindowTitle("Browse models"); @@ -145,8 +162,6 @@ ModelHandler::ModelHandler(ModelType modelsType, QWidget* parent) : _initiateExit(false), _type(modelsType) { - connect(&_downloader, SIGNAL(done(QNetworkReply::NetworkError)), SLOT(downloadFinished())); - // set headers data QStringList headerData; for (int i = 0; i < MODEL_METADATA_COUNT; ++i) { @@ -156,9 +171,6 @@ ModelHandler::ModelHandler(ModelType modelsType, QWidget* parent) : } void ModelHandler::download() { - // Query models list - queryNewFiles(); - _lock.lockForWrite(); if (_initiateExit) { _lock.unlock(); @@ -169,10 +181,25 @@ void ModelHandler::download() { loadingItem->setEnabled(false); _model.appendRow(loadingItem); _lock.unlock(); + + // Query models list + queryNewFiles(); } void ModelHandler::update() { - // Will be implemented in my next PR + _lock.lockForWrite(); + if (_initiateExit) { + _lock.unlock(); + return; + } + for (int i = 0; i < _model.rowCount(); ++i) { + QUrl url(_model.item(i,0)->data(Qt::UserRole).toString()); + QNetworkAccessManager* accessManager = new QNetworkAccessManager(this); + QNetworkRequest request(url); + accessManager->head(request); + connect(accessManager, SIGNAL(finished(QNetworkReply*)), SLOT(downloadFinished(QNetworkReply*))); + } + _lock.unlock(); } void ModelHandler::exit() { @@ -180,7 +207,6 @@ void ModelHandler::exit() { _initiateExit = true; // Disconnect everything - _downloader.disconnect(); disconnect(); thread()->disconnect(); @@ -191,12 +217,16 @@ void ModelHandler::exit() { _lock.unlock(); } -void ModelHandler::downloadFinished() { - if (_downloader.getData().startsWith("readAll(); + + if (!data.isEmpty()) { + parseXML(data); } else { - qDebug() << _downloader.getData(); + parseHeaders(reply); } + reply->deleteLater(); + sender()->deleteLater(); } void ModelHandler::queryNewFiles(QString marker) { @@ -219,7 +249,11 @@ void ModelHandler::queryNewFiles(QString marker) { // Download url.setQuery(query); - _downloader.download(url); + QNetworkAccessManager* accessManager = new QNetworkAccessManager(this); + QNetworkRequest request(url); + accessManager->get(request); + connect(accessManager, SIGNAL(finished(QNetworkReply*)), SLOT(downloadFinished(QNetworkReply*))); + } bool ModelHandler::parseXML(QByteArray xmlFile) { @@ -266,18 +300,9 @@ bool ModelHandler::parseXML(QByteArray xmlFile) { QList model; model << new QStandardItem(QFileInfo(xml.text().toString()).baseName()); model.first()->setData(PUBLIC_URL + "/" + xml.text().toString(), Qt::UserRole); - - // Rand properties for now (Will be taken out in the next PR) - static QString creator[] = {"Ryan", "Philip", "Andzrej"}; - static QString type[] = {"human", "beast", "pet", "elfe"}; - static QString gender[] = {"male", "female", "none"}; - model << new QStandardItem(creator[randIntInRange(0, 2)]); - model << new QStandardItem(QDate(randIntInRange(2013, 2014), - randIntInRange(1, 12), - randIntInRange(1, 30)).toString()); - model << new QStandardItem(type[randIntInRange(0, 3)]); - model << new QStandardItem(gender[randIntInRange(0, 2)]); - //////////////////////////////////////////////////////////// + for (int i = 1; i < MODEL_METADATA_COUNT; ++i) { + model << new QStandardItem(); + } _model.appendRow(model); } @@ -312,9 +337,32 @@ bool ModelHandler::parseXML(QByteArray xmlFile) { _lock.unlock(); if (!truncated) { - qDebug() << "Emitting..."; emit doneDownloading(); } return true; -} \ No newline at end of file +} + +bool ModelHandler::parseHeaders(QNetworkReply* reply) { + _lock.lockForWrite(); + + QList items = _model.findItems(QFileInfo(reply->url().toString()).baseName()); + if (items.isEmpty() || items.first()->text() == DO_NOT_MODIFY_TAG) { + return false; + } + + for (int i = 0; i < MODEL_METADATA_COUNT; ++i) { + for (int k = 1; k < reply->rawHeaderPairs().count(); ++k) { + QString key = reply->rawHeaderPairs().at(k).first.data(); + QString item = reply->rawHeaderPairs().at(k).second.data(); + if (key == propertiesIds[i]) { + _model.item(_model.indexFromItem(items.first()).row(), i)->setText(item); + } + } + } + _lock.unlock(); + + emit updated(); + return true; +} + diff --git a/interface/src/ui/ModelsBrowser.h b/interface/src/ui/ModelsBrowser.h index 9bc239ba18..30320de1c1 100644 --- a/interface/src/ui/ModelsBrowser.h +++ b/interface/src/ui/ModelsBrowser.h @@ -9,13 +9,10 @@ #ifndef __hifi__ModelsBrowser__ #define __hifi__ModelsBrowser__ -#include -#include -#include -#include #include +#include +#include -#include "FileDownloader.h" enum ModelType { Head, @@ -33,7 +30,7 @@ public: signals: void doneDownloading(); - void doneUpdating(); + void updated(); public slots: void download(); @@ -41,17 +38,17 @@ public slots: void exit(); private slots: - void downloadFinished(); + void downloadFinished(QNetworkReply* reply); private: bool _initiateExit; ModelType _type; - FileDownloader _downloader; QReadWriteLock _lock; QStandardItemModel _model; void queryNewFiles(QString marker = QString()); bool parseXML(QByteArray xmlFile); + bool parseHeaders(QNetworkReply* reply); }; @@ -71,6 +68,7 @@ public slots: private slots: void applyFilter(const QString& filter); + void resizeView(); private: ModelHandler* _handler; diff --git a/libraries/shared/src/FileDownloader.cpp b/libraries/shared/src/FileDownloader.cpp deleted file mode 100644 index 8b13b129fe..0000000000 --- a/libraries/shared/src/FileDownloader.cpp +++ /dev/null @@ -1,45 +0,0 @@ -// -// FileDownloader.cpp -// hifi -// -// Created by Clement Brisset on 3/14/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. -// -// - -#include -#include -#include -#include - -#include "FileDownloader.h" - -FileDownloader::FileDownloader(QObject* parent) : QObject(parent) { - connect(&_networkAccessManager, SIGNAL(finished(QNetworkReply*)), SLOT(processReply(QNetworkReply*))); -} - -void FileDownloader::download(const QUrl& dataURL, QNetworkAccessManager::Operation operation) { - QNetworkRequest request(dataURL); - - _downloadedData.clear(); - switch (operation) { - case QNetworkAccessManager::GetOperation: - _networkAccessManager.get(request); - break; - case QNetworkAccessManager::HeadOperation: - _networkAccessManager.head(request); - break; - default: - emit done(QNetworkReply::ProtocolInvalidOperationError); - break; - } -} - -void FileDownloader::processReply(QNetworkReply *reply) { - if (reply->error() == QNetworkReply::NoError) { - _downloadedData = reply->readAll(); - } - - reply->deleteLater(); - emit done(reply->error()); -} \ No newline at end of file diff --git a/libraries/shared/src/FileDownloader.h b/libraries/shared/src/FileDownloader.h deleted file mode 100644 index ad1351a575..0000000000 --- a/libraries/shared/src/FileDownloader.h +++ /dev/null @@ -1,41 +0,0 @@ -// -// FileDownloader.h -// hifi -// -// Created by Clement Brisset on 3/14/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. -// -// - -#ifndef __hifi__FileDownloader__ -#define __hifi__FileDownloader__ - -#include -#include -#include -#include - -class FileDownloader : public QObject { - Q_OBJECT - -public: - FileDownloader(QObject* parent = NULL); - QByteArray getData() const { return _downloadedData; } - - -signals: - void done(QNetworkReply::NetworkError error); - -public slots: - void download(const QUrl& dataURL, QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation); - -private slots: - void processReply(QNetworkReply* reply); - -private: - QNetworkAccessManager _networkAccessManager; - QByteArray _downloadedData; -}; - - -#endif /* defined(__hifi__FileDownloader__) */ From 933cade6b0391a8975e0a7367ba8da247ceba029 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 2 Apr 2014 16:34:33 -0700 Subject: [PATCH 109/595] Re-add fullUpdate hint to Model::simulate() --- interface/src/avatar/Avatar.cpp | 23 +++++++++------------ interface/src/avatar/FaceModel.cpp | 10 ++++----- interface/src/avatar/MyAvatar.cpp | 2 -- interface/src/avatar/SkeletonModel.cpp | 7 ++----- interface/src/avatar/SkeletonModel.h | 2 +- interface/src/renderer/Model.cpp | 28 +++++++++++++++++--------- interface/src/renderer/Model.h | 9 ++++++--- 7 files changed, 42 insertions(+), 39 deletions(-) diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index ec8539954a..899514d1c1 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -118,26 +118,21 @@ void Avatar::simulate(float deltaTime) { _skeletonModel.setLODDistance(getLODDistance()); if (!_shouldRenderBillboard && inViewFrustum) { - glm::vec3 headPosition = _position; - - _skeletonModel.updateGeometry(); - if (_skeletonModel.isActive()) { - // copy joint data to skeleton - if (_hasNewJointRotations) { - for (int i = 0; i < _jointData.size(); i++) { - const JointData& data = _jointData.at(i); - _skeletonModel.setJointState(i, data.valid, data.rotation); - } - _skeletonModel.simulate(deltaTime); - _hasNewJointRotations = false; + if (_hasNewJointRotations) { + for (int i = 0; i < _jointData.size(); i++) { + const JointData& data = _jointData.at(i); + _skeletonModel.setJointState(i, data.valid, data.rotation); } - _skeletonModel.getHeadPosition(headPosition); + _skeletonModel.simulate(deltaTime); } + _skeletonModel.simulate(deltaTime, _hasNewJointRotations); + _hasNewJointRotations = false; + glm::vec3 headPosition = _position; + _skeletonModel.getHeadPosition(headPosition); Head* head = getHead(); head->setPosition(headPosition); head->setScale(_scale); - head->getFaceModel().updateGeometry(); head->simulate(deltaTime, false, _shouldRenderBillboard); } diff --git a/interface/src/avatar/FaceModel.cpp b/interface/src/avatar/FaceModel.cpp index 5d9b71f11d..2934a022af 100644 --- a/interface/src/avatar/FaceModel.cpp +++ b/interface/src/avatar/FaceModel.cpp @@ -19,9 +19,7 @@ FaceModel::FaceModel(Head* owningHead) : } void FaceModel::simulate(float deltaTime) { - if (!isActive()) { - return; - } + updateGeometry(); Avatar* owningAvatar = static_cast(_owningHead->_owningAvatar); glm::vec3 neckPosition; if (!owningAvatar->getSkeletonModel().getNeckPosition(neckPosition)) { @@ -36,12 +34,14 @@ void FaceModel::simulate(float deltaTime) { const float MODEL_SCALE = 0.0006f; setScale(glm::vec3(1.0f, 1.0f, 1.0f) * _owningHead->getScale() * MODEL_SCALE); - setOffset(-_geometry->getFBXGeometry().neckPivot); + if (isActive()) { + setOffset(-_geometry->getFBXGeometry().neckPivot); + } setPupilDilation(_owningHead->getPupilDilation()); setBlendshapeCoefficients(_owningHead->getBlendshapeCoefficients()); - Model::simulate(deltaTime); + Model::simulateInternal(deltaTime); } void FaceModel::maybeUpdateNeckRotation(const JointState& parentState, const FBXJoint& joint, JointState& state) { diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 0b220a532c..9dcfaa09ba 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -289,7 +289,6 @@ void MyAvatar::simulate(float deltaTime) { getHand()->collideAgainstOurself(); getHand()->simulate(deltaTime, true); - _skeletonModel.updateGeometry(); _skeletonModel.simulate(deltaTime); // copy out the skeleton joints from the model @@ -306,7 +305,6 @@ void MyAvatar::simulate(float deltaTime) { } head->setPosition(headPosition); head->setScale(_scale); - head->getFaceModel().updateGeometry(); head->simulate(deltaTime, true); // Zero thrust out now that we've added it to velocity in this frame diff --git a/interface/src/avatar/SkeletonModel.cpp b/interface/src/avatar/SkeletonModel.cpp index 0ce97f4ef9..69229d9e8d 100644 --- a/interface/src/avatar/SkeletonModel.cpp +++ b/interface/src/avatar/SkeletonModel.cpp @@ -18,16 +18,13 @@ SkeletonModel::SkeletonModel(Avatar* owningAvatar) : _owningAvatar(owningAvatar) { } -void SkeletonModel::simulate(float deltaTime) { - if (!isActive()) { - return; - } +void SkeletonModel::simulate(float deltaTime, bool fullUpdate) { setTranslation(_owningAvatar->getPosition()); setRotation(_owningAvatar->getOrientation() * glm::angleAxis(PI, glm::vec3(0.0f, 1.0f, 0.0f))); const float MODEL_SCALE = 0.0006f; setScale(glm::vec3(1.0f, 1.0f, 1.0f) * _owningAvatar->getScale() * MODEL_SCALE); - Model::simulate(deltaTime); + Model::simulate(deltaTime, fullUpdate); if (!(isActive() && _owningAvatar->isMyAvatar())) { return; // only simulate for own avatar diff --git a/interface/src/avatar/SkeletonModel.h b/interface/src/avatar/SkeletonModel.h index 60b12eb8f5..31867dec5c 100644 --- a/interface/src/avatar/SkeletonModel.h +++ b/interface/src/avatar/SkeletonModel.h @@ -21,7 +21,7 @@ public: SkeletonModel(Avatar* owningAvatar); - void simulate(float deltaTime); + void simulate(float deltaTime, bool fullUpdate = true); /// \param jointIndex index of hand joint /// \param shapes[out] list in which is stored pointers to hand shapes diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 000a41b7d5..9d2a031a6e 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -190,11 +190,14 @@ void Model::reset() { } } -void Model::updateGeometry() { +bool Model::updateGeometry() { // NOTE: this is a recursive call that walks all attachments, and their attachments + bool needFullUpdate = false; for (int i = 0; i < _attachments.size(); i++) { Model* model = _attachments.at(i); - model->updateGeometry(); + if (model->updateGeometry()) { + needFullUpdate = true; + } } bool needToRebuild = false; @@ -209,7 +212,7 @@ void Model::updateGeometry() { } if (!_geometry) { // geometry is not ready - return; + return false; } QSharedPointer geometry = _geometry->getLODOrFallback(_lodDistance, _lodHysteresis); @@ -273,8 +276,9 @@ void Model::updateGeometry() { _attachments.append(model); } rebuildShapes(); + needFullUpdate = true; } - return; + return needFullUpdate; } bool Model::render(float alpha, bool forShadowMap) { @@ -682,11 +686,15 @@ void Blender::run() { Q_ARG(const QVector&, vertices), Q_ARG(const QVector&, normals)); } -void Model::simulate(float deltaTime) { - // NOTE: this is a recursive call that walks all attachments, and their attachments - if (!isActive()) { - return; +void Model::simulate(float deltaTime, bool fullUpdate) { + fullUpdate = updateGeometry() || fullUpdate; + if (isActive() && fullUpdate) { + simulateInternal(deltaTime); } +} + +void Model::simulateInternal(float deltaTime) { + // NOTE: this is a recursive call that walks all attachments, and their attachments // update the world space transforms for all joints for (int i = 0; i < _jointStates.size(); i++) { updateJointState(i); @@ -709,7 +717,9 @@ void Model::simulate(float deltaTime) { model->setRotation(jointRotation * attachment.rotation); model->setScale(_scale * attachment.scale); - model->simulate(deltaTime); + if (model->isActive()) { + model->simulateInternal(deltaTime); + } } for (int i = 0; i < _meshStates.size(); i++) { diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index 0c05b18429..11374a6369 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -56,7 +56,7 @@ public: void init(); void reset(); - virtual void simulate(float deltaTime); + virtual void simulate(float deltaTime, bool fullUpdate = true); bool render(float alpha = 1.0f, bool forShadowMap = false); /// Sets the URL of the model to render. @@ -185,8 +185,6 @@ public: /// Sets blended vertices computed in a separate thread. void setBlendedVertices(const QVector& vertices, const QVector& normals); - void updateGeometry(); - protected: QSharedPointer _geometry; @@ -219,6 +217,11 @@ protected: QVector _meshStates; + // returns 'true' if needs fullUpdate after geometry change + bool updateGeometry(); + + void simulateInternal(float deltaTime); + /// Updates the state of the joint at the specified index. virtual void updateJointState(int index); From cf20c448a3100ab1ca51bbee858b4f15d7d70d6f Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 2 Apr 2014 16:46:03 -0700 Subject: [PATCH 110/595] Few tweaks before PR --- interface/src/ui/ModelsBrowser.cpp | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/interface/src/ui/ModelsBrowser.cpp b/interface/src/ui/ModelsBrowser.cpp index e128d047ef..276fdd24c1 100644 --- a/interface/src/ui/ModelsBrowser.cpp +++ b/interface/src/ui/ModelsBrowser.cpp @@ -54,7 +54,7 @@ static const QString propertiesIds[MODEL_METADATA_COUNT] = { DO_NOT_MODIFY_TAG, "Type", "Gender", - "x-amz-request-id", + "Creator", "Last-Modified" }; @@ -97,7 +97,7 @@ void ModelsBrowser::applyFilter(const QString &filter) { for (int k = 0; k < filters.count(); ++k) { match = false; for (int j = 0; j < MODEL_METADATA_COUNT; ++j) { - if (model->item(i, j)->text().contains(filters.at(k))) { + if (model->item(i, j)->text().contains(filters.at(k), Qt::CaseInsensitive)) { match = true; break; } @@ -359,6 +359,22 @@ bool ModelHandler::parseHeaders(QNetworkReply* reply) { _model.item(_model.indexFromItem(items.first()).row(), i)->setText(item); } } + + // Rand properties for now (Will be taken out when we have real metadata on the server) + if (_model.item(_model.indexFromItem(items.first()).row(), i)->text().isEmpty()) { + if (i == CREATOR) { + static QString creator[] = {"Ryan", "Philip", "Andzrej", "Phteven", "Brad"}; + _model.item(_model.indexFromItem(items.first()).row(), i)->setText(creator[randIntInRange(0, 4)]); + } else if (i == TYPE) { + static QString type[] = {"human", "beast", "pet", "elfe"}; + _model.item(_model.indexFromItem(items.first()).row(), i)->setText(type[randIntInRange(0, 3)]); + } else if (i == GENDER) { + static QString gender[] = {"male", "female", "none"}; + _model.item(_model.indexFromItem(items.first()).row(), i)->setText(gender[randIntInRange(0, 2)]); + } + } + //////////////////////////////////////////////////////////// + } _lock.unlock(); From c2f0545d96c3af7fc1c1f047a3b42d66d0a58826 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 2 Apr 2014 17:12:11 -0700 Subject: [PATCH 111/595] Setup for actual metadata --- interface/src/ui/ModelsBrowser.cpp | 37 ++++++++++-------------------- 1 file changed, 12 insertions(+), 25 deletions(-) diff --git a/interface/src/ui/ModelsBrowser.cpp b/interface/src/ui/ModelsBrowser.cpp index 276fdd24c1..616aba3881 100644 --- a/interface/src/ui/ModelsBrowser.cpp +++ b/interface/src/ui/ModelsBrowser.cpp @@ -36,26 +36,29 @@ static const QString DO_NOT_MODIFY_TAG = "DoNotModify"; enum ModelMetaData { NAME, - TYPE, - GENDER, CREATOR, - UPLOAD_DATE, + DATE_ADDED, + TOTAL_SIZE, + POLY_NUM, + TAGS, MODEL_METADATA_COUNT }; static const QString propertiesNames[MODEL_METADATA_COUNT] = { "Name", - "Type", - "Gender", "Creator", - "Last Modified" + "Date Added", + "Total Size", + "Poly#", + "Tags" }; static const QString propertiesIds[MODEL_METADATA_COUNT] = { DO_NOT_MODIFY_TAG, - "Type", - "Gender", "Creator", - "Last-Modified" + "Date-Added", + "Total-Size", + "Poly-Num", + "Tags" }; ModelsBrowser::ModelsBrowser(ModelType modelsType, QWidget* parent) : @@ -359,22 +362,6 @@ bool ModelHandler::parseHeaders(QNetworkReply* reply) { _model.item(_model.indexFromItem(items.first()).row(), i)->setText(item); } } - - // Rand properties for now (Will be taken out when we have real metadata on the server) - if (_model.item(_model.indexFromItem(items.first()).row(), i)->text().isEmpty()) { - if (i == CREATOR) { - static QString creator[] = {"Ryan", "Philip", "Andzrej", "Phteven", "Brad"}; - _model.item(_model.indexFromItem(items.first()).row(), i)->setText(creator[randIntInRange(0, 4)]); - } else if (i == TYPE) { - static QString type[] = {"human", "beast", "pet", "elfe"}; - _model.item(_model.indexFromItem(items.first()).row(), i)->setText(type[randIntInRange(0, 3)]); - } else if (i == GENDER) { - static QString gender[] = {"male", "female", "none"}; - _model.item(_model.indexFromItem(items.first()).row(), i)->setText(gender[randIntInRange(0, 2)]); - } - } - //////////////////////////////////////////////////////////// - } _lock.unlock(); From e1cae6d295ba2c7384546b35eb552edfb814fafb Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 2 Apr 2014 17:29:14 -0700 Subject: [PATCH 112/595] initial handshaking for DTLS sessions between DS and clients --- animation-server/src/AnimationServer.cpp | 2 +- assignment-client/src/audio/AudioMixer.cpp | 2 +- domain-server/src/DTLSServerSession.h | 2 + domain-server/src/DomainServer.cpp | 51 ++++++++++-- domain-server/src/DomainServer.h | 1 + libraries/audio/src/Sound.cpp | 1 + .../metavoxels/src/DatagramSequencer.cpp | 2 +- libraries/shared/src/DTLSClientSession.cpp | 22 +++++- libraries/shared/src/DTLSClientSession.h | 2 + libraries/shared/src/DTLSSession.cpp | 78 +++++++++++++----- libraries/shared/src/DTLSSession.h | 5 +- libraries/shared/src/DomainHandler.cpp | 9 ++- libraries/shared/src/DomainHandler.h | 3 +- libraries/shared/src/HifiSockAddr.cpp | 4 +- libraries/shared/src/LimitedNodeList.h | 2 + libraries/shared/src/NodeList.cpp | 79 +++++++++++-------- libraries/shared/src/NodeList.h | 2 +- libraries/shared/src/SharedUtil.h | 3 - libraries/shared/src/ThreadedAssignment.cpp | 2 +- 19 files changed, 200 insertions(+), 72 deletions(-) diff --git a/animation-server/src/AnimationServer.cpp b/animation-server/src/AnimationServer.cpp index e66ca35501..e92169bcfa 100644 --- a/animation-server/src/AnimationServer.cpp +++ b/animation-server/src/AnimationServer.cpp @@ -797,7 +797,7 @@ AnimationServer::AnimationServer(int &argc, char **argv) : QTimer* domainServerTimer = new QTimer(this); connect(domainServerTimer, SIGNAL(timeout()), nodeList, SLOT(sendDomainServerCheckIn())); - domainServerTimer->start(DOMAIN_SERVER_CHECK_IN_USECS / 1000); + domainServerTimer->start(DOMAIN_SERVER_CHECK_IN_MSECS); QTimer* silentNodeTimer = new QTimer(this); connect(silentNodeTimer, SIGNAL(timeout()), nodeList, SLOT(removeSilentNodes())); diff --git a/assignment-client/src/audio/AudioMixer.cpp b/assignment-client/src/audio/AudioMixer.cpp index f183abade9..b8cee17df5 100644 --- a/assignment-client/src/audio/AudioMixer.cpp +++ b/assignment-client/src/audio/AudioMixer.cpp @@ -369,7 +369,7 @@ void AudioMixer::sendStatsPacket() { statsObject["average_mixes_per_listener"] = 0.0; } - ThreadedAssignment::addPacketStatsAndSendStatsPacket(statsObject); +// ThreadedAssignment::addPacketStatsAndSendStatsPacket(statsObject); _sumListeners = 0; _sumMixes = 0; diff --git a/domain-server/src/DTLSServerSession.h b/domain-server/src/DTLSServerSession.h index 5bdb0f9e91..86f642b104 100644 --- a/domain-server/src/DTLSServerSession.h +++ b/domain-server/src/DTLSServerSession.h @@ -9,6 +9,8 @@ #ifndef __hifi__DTLSServerSession__ #define __hifi__DTLSServerSession__ +#include + #include class DTLSServerSession : public DTLSSession { diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index ba2f2791bd..5550c2741d 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -96,8 +96,12 @@ bool DomainServer::optionallySetupDTLS() { // set the D-H paramters on the X509 credentials gnutls_certificate_set_dh_params(*_x509Credentials, *_dhParams); + // setup the key used for cookie verification + _cookieKey = new gnutls_datum_t; + gnutls_key_generate(_cookieKey, GNUTLS_COOKIE_KEY_SIZE); + _priorityCache = new gnutls_priority_t; - const char DTLS_PRIORITY_STRING[] = "PERFORMANCE:-VERS-TLS-ALL:+VERS-DTLS1.2:%SERVER_PRECEDENCE"; + const char DTLS_PRIORITY_STRING[] = "PERFORMANCE:-VERS-TLS-ALL:+VERS-DTLS1.0:%SERVER_PRECEDENCE"; gnutls_priority_init(_priorityCache, DTLS_PRIORITY_STRING, NULL); _isUsingDTLS = true; @@ -612,20 +616,55 @@ void DomainServer::readAvailableDTLSDatagrams() { static socklen_t sockAddrSize = sizeof(senderSockAddr); while (dtlsSocket.hasPendingDatagrams()) { + qDebug() << "Looking at a datagram"; + // check if we have an active DTLS session for this sender QByteArray peekDatagram(dtlsSocket.pendingDatagramSize(), 0); recvfrom(dtlsSocket.socketDescriptor(), peekDatagram.data(), dtlsSocket.pendingDatagramSize(), MSG_PEEK, &senderSockAddr, &sockAddrSize); - DTLSSession* existingSession = _dtlsSessions.value(HifiSockAddr(&senderSockAddr)); - - qDebug() << "Checking for a session with" << HifiSockAddr(&senderSockAddr); + HifiSockAddr senderHifiSockAddr(&senderSockAddr); + DTLSServerSession* existingSession = _dtlsSessions.value(senderHifiSockAddr); if (existingSession) { - // use GnuTLS to receive the encrypted data + // check if we have completed handshake with this user + int handshakeReturn = gnutls_handshake(*existingSession->getGnuTLSSession()); + qDebug() << "Handshake return for user is" << handshakeReturn; } else { - // no existing session - set up a new session now + // first we verify the cookie + // see http://gnutls.org/manual/html_node/DTLS-sessions.html for why this is required + gnutls_dtls_prestate_st prestate; + memset(&prestate, 0, sizeof(prestate)); + int cookieValid = gnutls_dtls_cookie_verify(_cookieKey, &senderSockAddr, sizeof(senderSockAddr), + peekDatagram.data(), peekDatagram.size(), &prestate); + + if (cookieValid < 0) { + // the cookie sent by the client was not valid + // send a valid one + DTLSServerSession tempServerSession(LimitedNodeList::getInstance()->getDTLSSocket(), senderHifiSockAddr); + gnutls_dtls_cookie_send(_cookieKey, &senderSockAddr, sizeof(senderSockAddr), &prestate, + &tempServerSession, DTLSSession::socketPush); + + // acutally pull the peeked data off the network stack so that it gets discarded + dtlsSocket.readDatagram(peekDatagram.data(), peekDatagram.size()); + } else { + // cookie valid but no existing session - set up a new session now + DTLSServerSession* newServerSession = new DTLSServerSession(LimitedNodeList::getInstance()->getDTLSSocket(), + senderHifiSockAddr); + gnutls_session_t* gnutlsSession = newServerSession->getGnuTLSSession(); + + gnutls_priority_set(*gnutlsSession, *_priorityCache); + gnutls_credentials_set(*gnutlsSession, GNUTLS_CRD_CERTIFICATE, *_x509Credentials); + gnutls_dtls_prestate_set(*gnutlsSession, &prestate); + + // handshake to begin the session + int handshakeReturn = gnutls_handshake(*gnutlsSession); + qDebug() << "initial handshake return" << handshakeReturn; + + qDebug() << "Beginning DTLS session with node at" << senderHifiSockAddr; + _dtlsSessions[senderHifiSockAddr] = newServerSession; + } } } } diff --git a/domain-server/src/DomainServer.h b/domain-server/src/DomainServer.h index a69df5dec0..6bca67df0d 100644 --- a/domain-server/src/DomainServer.h +++ b/domain-server/src/DomainServer.h @@ -89,6 +89,7 @@ private: bool _isUsingDTLS; gnutls_certificate_credentials_t* _x509Credentials; gnutls_dh_params_t* _dhParams; + gnutls_datum_t* _cookieKey; gnutls_priority_t* _priorityCache; QHash _dtlsSessions; diff --git a/libraries/audio/src/Sound.cpp b/libraries/audio/src/Sound.cpp index 91a47b7d2c..17babcdae3 100644 --- a/libraries/audio/src/Sound.cpp +++ b/libraries/audio/src/Sound.cpp @@ -18,6 +18,7 @@ #include #include +#include #include #include "AudioRingBuffer.h" diff --git a/libraries/metavoxels/src/DatagramSequencer.cpp b/libraries/metavoxels/src/DatagramSequencer.cpp index 052f480fcf..be39fb78b1 100644 --- a/libraries/metavoxels/src/DatagramSequencer.cpp +++ b/libraries/metavoxels/src/DatagramSequencer.cpp @@ -10,7 +10,7 @@ #include -#include +#include #include "DatagramSequencer.h" #include "MetavoxelMessages.h" diff --git a/libraries/shared/src/DTLSClientSession.cpp b/libraries/shared/src/DTLSClientSession.cpp index 7649b7f352..109172487f 100644 --- a/libraries/shared/src/DTLSClientSession.cpp +++ b/libraries/shared/src/DTLSClientSession.cpp @@ -8,8 +8,28 @@ #include "DTLSClientSession.h" +gnutls_certificate_credentials_t* DTLSClientSession::x509CACredentials() { + static gnutls_certificate_credentials_t x509Credentials; + static bool credentialsInitialized = false; + + if (!credentialsInitialized) { + gnutls_certificate_allocate_credentials(&x509Credentials); + qDebug() << "processed" << gnutls_certificate_set_x509_trust_file(x509Credentials, "/Users/birarda/code/hifi/certs/root-ca.crt", GNUTLS_X509_FMT_PEM); + } + + return &x509Credentials; +} + +int verifyX509Certificate(gnutls_session_t session) { + int certificateType = gnutls_certificate_type_get(session); + qDebug() << "Verifying a certificate of type" << certificateType; + + return 0; +} + DTLSClientSession::DTLSClientSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket) : DTLSSession(GNUTLS_CLIENT, dtlsSocket, destinationSocket) { - gnutls_credentials_set(_gnutlsSession, GNUTLS_CRD_CERTIFICATE, DTLSSession::x509CACredentials()); + gnutls_priority_set_direct(_gnutlsSession, "PERFORMANCE", NULL); + gnutls_credentials_set(_gnutlsSession, GNUTLS_CRD_CERTIFICATE, x509CACredentials()); } \ No newline at end of file diff --git a/libraries/shared/src/DTLSClientSession.h b/libraries/shared/src/DTLSClientSession.h index 93cd51cb9a..a81daf6d74 100644 --- a/libraries/shared/src/DTLSClientSession.h +++ b/libraries/shared/src/DTLSClientSession.h @@ -14,6 +14,8 @@ class DTLSClientSession : public DTLSSession { public: DTLSClientSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket); + + static gnutls_certificate_credentials_t* x509CACredentials(); }; #endif /* defined(__hifi__DTLSClientSession__) */ diff --git a/libraries/shared/src/DTLSSession.cpp b/libraries/shared/src/DTLSSession.cpp index 0ab5bdb2bc..52c55bec23 100644 --- a/libraries/shared/src/DTLSSession.cpp +++ b/libraries/shared/src/DTLSSession.cpp @@ -8,46 +8,88 @@ #include +#include "NodeList.h" #include "DTLSSession.h" int DTLSSession::socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms) { - return 1; + DTLSSession* session = static_cast(ptr); + QUdpSocket& dtlsSocket = session->_dtlsSocket; + + if (dtlsSocket.hasPendingDatagrams()) { + // peek the data on stack to see if it belongs to this session + static sockaddr senderSockAddr; + static socklen_t sockAddrSize = sizeof(senderSockAddr); + + QByteArray peekDatagram(dtlsSocket.pendingDatagramSize(), 0); + + recvfrom(dtlsSocket.socketDescriptor(), peekDatagram.data(), dtlsSocket.pendingDatagramSize(), + MSG_PEEK, &senderSockAddr, &sockAddrSize); + + if (HifiSockAddr(&senderSockAddr) == session->_destinationSocket) { + // there is data for this session ready to be read + return 1; + } else { + // the next data from the dtlsSocket is not for this session + return 0; + } + } else { + // no data available on the dtlsSocket + return 0; + } } ssize_t DTLSSession::socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t size) { DTLSSession* session = static_cast(ptr); QUdpSocket& dtlsSocket = session->_dtlsSocket; - if (dtlsSocket.hasPendingDatagrams()) { - return dtlsSocket.read(reinterpret_cast(buffer), size); - } else { - gnutls_transport_set_errno(session->_gnutlsSession, GNUTLS_E_AGAIN); - return 0; + HifiSockAddr pulledSockAddr; + qint64 bytesReceived = dtlsSocket.readDatagram(reinterpret_cast(buffer), size, + pulledSockAddr.getAddressPointer(), pulledSockAddr.getPortPointer()); + if (bytesReceived == -1) { + // no data to pull, return -1 + qDebug() << "Received no data on call to readDatagram"; + return bytesReceived; } + + if (pulledSockAddr == session->_destinationSocket) { + // bytes received from the correct sender, return number of bytes received + qDebug() << "Received" << bytesReceived << "on DTLS socket from" << pulledSockAddr; + return bytesReceived; + } else { + qDebug() << pulledSockAddr << "is not" << session->_destinationSocket; + } + + // we pulled a packet not matching this session, so output that + qDebug() << "Denied connection from" << pulledSockAddr; + + gnutls_transport_set_errno(session->_gnutlsSession, GNUTLS_E_AGAIN); + return -1; } ssize_t DTLSSession::socketPush(gnutls_transport_ptr_t ptr, const void* buffer, size_t size) { DTLSSession* session = static_cast(ptr); QUdpSocket& dtlsSocket = session->_dtlsSocket; + qDebug() << "Pushing a message of size" << size << "to" << session->_destinationSocket; return dtlsSocket.writeDatagram(reinterpret_cast(buffer), size, session->_destinationSocket.getAddress(), session->_destinationSocket.getPort()); } -gnutls_certificate_credentials_t* DTLSSession::x509CACredentials() { - static gnutls_certificate_credentials_t x509Credentials; - static bool credentialsInitialized = false; - - if (!credentialsInitialized) { - gnutls_certificate_allocate_credentials(&x509Credentials); - } - - return &x509Credentials; -} - DTLSSession::DTLSSession(int end, QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket) : _dtlsSocket(dtlsSocket), _destinationSocket(destinationSocket) { - gnutls_init(&_gnutlsSession, end | GNUTLS_DATAGRAM); + gnutls_init(&_gnutlsSession, end | GNUTLS_DATAGRAM | GNUTLS_NONBLOCK); + + // see http://gnutls.org/manual/html_node/Datagram-TLS-API.html#gnutls_005fdtls_005fset_005fmtu + const unsigned int DTLS_MAX_MTU = 1452; + gnutls_dtls_set_mtu(_gnutlsSession, DTLS_MAX_MTU); + + const unsigned int DTLS_TOTAL_CONNECTION_TIMEOUT = 10 * DOMAIN_SERVER_CHECK_IN_MSECS; + gnutls_dtls_set_timeouts(_gnutlsSession, 0, DTLS_TOTAL_CONNECTION_TIMEOUT); + + gnutls_transport_set_ptr(_gnutlsSession, this); + gnutls_transport_set_push_function(_gnutlsSession, socketPush); + gnutls_transport_set_pull_function(_gnutlsSession, socketPull); + gnutls_transport_set_pull_timeout_function(_gnutlsSession, socketPullTimeout); } \ No newline at end of file diff --git a/libraries/shared/src/DTLSSession.h b/libraries/shared/src/DTLSSession.h index 81c1a50916..ce190e11c0 100644 --- a/libraries/shared/src/DTLSSession.h +++ b/libraries/shared/src/DTLSSession.h @@ -20,12 +20,13 @@ class DTLSSession : public QObject { public: DTLSSession(int end, QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket); - static gnutls_certificate_credentials_t* x509CACredentials(); -protected: static int socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms); static ssize_t socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t size); static ssize_t socketPush(gnutls_transport_ptr_t ptr, const void* buffer, size_t size); + gnutls_session_t* getGnuTLSSession() { return &_gnutlsSession; } + +protected: QUdpSocket& _dtlsSocket; gnutls_session_t _gnutlsSession; HifiSockAddr _destinationSocket; diff --git a/libraries/shared/src/DomainHandler.cpp b/libraries/shared/src/DomainHandler.cpp index e6403dcbc1..6bc959be47 100644 --- a/libraries/shared/src/DomainHandler.cpp +++ b/libraries/shared/src/DomainHandler.cpp @@ -18,7 +18,6 @@ DomainHandler::DomainHandler() : _sockAddr(HifiSockAddr(QHostAddress::Null, DEFAULT_DOMAIN_SERVER_PORT)), _assignmentUUID(), _isConnected(false), - _requiresDTLS(false), _dtlsSession(NULL) { @@ -31,13 +30,18 @@ DomainHandler::~DomainHandler() { void DomainHandler::clearConnectionInfo() { _uuid = QUuid(); _isConnected = false; + + delete _dtlsSession; + _dtlsSession = NULL; } void DomainHandler::reset() { clearConnectionInfo(); _hostname = QString(); _sockAddr.setAddress(QHostAddress::Null); - _requiresDTLS = false; + + delete _dtlsSession; + _dtlsSession = NULL; } void DomainHandler::initializeDTLSSession() { @@ -122,7 +126,6 @@ void DomainHandler::parseDTLSRequirementPacket(const QByteArray& dtlsRequirement qDebug() << "domain-server DTLS port changed to" << dtlsPort << "- Enabling DTLS."; _sockAddr.setPort(dtlsPort); - _requiresDTLS = true; initializeDTLSSession(); } \ No newline at end of file diff --git a/libraries/shared/src/DomainHandler.h b/libraries/shared/src/DomainHandler.h index 5032138858..a867207190 100644 --- a/libraries/shared/src/DomainHandler.h +++ b/libraries/shared/src/DomainHandler.h @@ -49,6 +49,8 @@ public: bool isConnected() const { return _isConnected; } void setIsConnected(bool isConnected); + DTLSClientSession* getDTLSSession() { return _dtlsSession; } + void parseDTLSRequirementPacket(const QByteArray& dtlsRequirementPacket); private slots: @@ -66,7 +68,6 @@ private: HifiSockAddr _sockAddr; QUuid _assignmentUUID; bool _isConnected; - bool _requiresDTLS; DTLSClientSession* _dtlsSession; }; diff --git a/libraries/shared/src/HifiSockAddr.cpp b/libraries/shared/src/HifiSockAddr.cpp index 8010202424..07a7d25680 100644 --- a/libraries/shared/src/HifiSockAddr.cpp +++ b/libraries/shared/src/HifiSockAddr.cpp @@ -50,9 +50,9 @@ HifiSockAddr::HifiSockAddr(const sockaddr* sockaddr) { _address = QHostAddress(sockaddr); if (sockaddr->sa_family == AF_INET) { - _port = reinterpret_cast(sockaddr)->sin_port; + _port = ntohs(reinterpret_cast(sockaddr)->sin_port); } else { - _port = reinterpret_cast(sockaddr)->sin6_port; + _port = ntohs(reinterpret_cast(sockaddr)->sin6_port); } } diff --git a/libraries/shared/src/LimitedNodeList.h b/libraries/shared/src/LimitedNodeList.h index 544207d1b5..3688ddfdb4 100644 --- a/libraries/shared/src/LimitedNodeList.h +++ b/libraries/shared/src/LimitedNodeList.h @@ -34,6 +34,8 @@ #include "DomainHandler.h" #include "Node.h" +const int MAX_PACKET_SIZE = 1500; + const quint64 NODE_SILENCE_THRESHOLD_USECS = 2 * 1000 * 1000; extern const char SOLO_NODE_TYPES[2]; diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 3202909447..1740525ef1 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -12,6 +12,8 @@ #include #include +#include + #include "AccountManager.h" #include "Assignment.h" #include "HifiSockAddr.h" @@ -318,39 +320,54 @@ void NodeList::sendDomainServerCheckIn() { // send a STUN request to figure it out sendSTUNRequest(); } else if (!_domainHandler.getIP().isNull()) { - // construct the DS check in packet - QUuid packetUUID = (!_sessionUUID.isNull() ? _sessionUUID : _domainHandler.getAssignmentUUID()); - QByteArray domainServerPacket = byteArrayWithPopulatedHeader(PacketTypeDomainListRequest, packetUUID); - QDataStream packetStream(&domainServerPacket, QIODevice::Append); + DTLSClientSession* dtlsSession = _domainHandler.getDTLSSession(); - // pack our data to send to the domain-server - packetStream << _ownerType << _publicSockAddr - << HifiSockAddr(QHostAddress(getHostOrderLocalAddress()), _nodeSocket.localPort()) - << (quint8) _nodeTypesOfInterest.size(); - - // copy over the bytes for node types of interest, if required - foreach (NodeType_t nodeTypeOfInterest, _nodeTypesOfInterest) { - packetStream << nodeTypeOfInterest; - } - - writeDatagram(domainServerPacket, _domainHandler.getSockAddr(), QUuid()); - const int NUM_DOMAIN_SERVER_CHECKINS_PER_STUN_REQUEST = 5; - static unsigned int numDomainCheckins = 0; - - // send a STUN request every Nth domain server check in so we update our public socket, if required - if (numDomainCheckins++ % NUM_DOMAIN_SERVER_CHECKINS_PER_STUN_REQUEST == 0) { - sendSTUNRequest(); - } - - if (_numNoReplyDomainCheckIns >= MAX_SILENT_DOMAIN_SERVER_CHECK_INS) { - // we haven't heard back from DS in MAX_SILENT_DOMAIN_SERVER_CHECK_INS - // so emit our signal that indicates that - emit limitOfSilentDomainCheckInsReached(); - } - - // increment the count of un-replied check-ins - _numNoReplyDomainCheckIns++; + if (dtlsSession) { + int handshakeReturn = gnutls_handshake(*dtlsSession->getGnuTLSSession()); + + gnutls_handshake_description_t inType = gnutls_handshake_get_last_in(*dtlsSession->getGnuTLSSession()); + gnutls_handshake_description_t outType = gnutls_handshake_get_last_out(*dtlsSession->getGnuTLSSession()); + qDebug() << "in" << gnutls_handshake_description_get_name(inType); + qDebug() << "out" << gnutls_handshake_description_get_name(outType); + + // make sure DTLS handshake with the domain-server is complete + qDebug() << "GnuTLS handshake return is" << handshakeReturn; + } else { + // construct the DS check in packet + QUuid packetUUID = (!_sessionUUID.isNull() ? _sessionUUID : _domainHandler.getAssignmentUUID()); + + QByteArray domainServerPacket = byteArrayWithPopulatedHeader(PacketTypeDomainListRequest, packetUUID); + QDataStream packetStream(&domainServerPacket, QIODevice::Append); + + // pack our data to send to the domain-server + packetStream << _ownerType << _publicSockAddr + << HifiSockAddr(QHostAddress(getHostOrderLocalAddress()), _nodeSocket.localPort()) + << (quint8) _nodeTypesOfInterest.size(); + + // copy over the bytes for node types of interest, if required + foreach (NodeType_t nodeTypeOfInterest, _nodeTypesOfInterest) { + packetStream << nodeTypeOfInterest; + } + + writeDatagram(domainServerPacket, _domainHandler.getSockAddr(), QUuid()); + const int NUM_DOMAIN_SERVER_CHECKINS_PER_STUN_REQUEST = 5; + static unsigned int numDomainCheckins = 0; + + // send a STUN request every Nth domain server check in so we update our public socket, if required + if (numDomainCheckins++ % NUM_DOMAIN_SERVER_CHECKINS_PER_STUN_REQUEST == 0) { + sendSTUNRequest(); + } + + if (_numNoReplyDomainCheckIns >= MAX_SILENT_DOMAIN_SERVER_CHECK_INS) { + // we haven't heard back from DS in MAX_SILENT_DOMAIN_SERVER_CHECK_INS + // so emit our signal that indicates that + emit limitOfSilentDomainCheckInsReached(); + } + + // increment the count of un-replied check-ins + _numNoReplyDomainCheckIns++; + } } } diff --git a/libraries/shared/src/NodeList.h b/libraries/shared/src/NodeList.h index 5ccfc80e35..625d7098ce 100644 --- a/libraries/shared/src/NodeList.h +++ b/libraries/shared/src/NodeList.h @@ -35,7 +35,7 @@ #include "LimitedNodeList.h" #include "Node.h" -const quint64 DOMAIN_SERVER_CHECK_IN_USECS = 1 * 1000000; +const quint64 DOMAIN_SERVER_CHECK_IN_MSECS = 1 * 1000; const int MAX_SILENT_DOMAIN_SERVER_CHECK_INS = 5; diff --git a/libraries/shared/src/SharedUtil.h b/libraries/shared/src/SharedUtil.h index d8d686c63b..e7898f3e2b 100644 --- a/libraries/shared/src/SharedUtil.h +++ b/libraries/shared/src/SharedUtil.h @@ -42,7 +42,6 @@ struct xColor { unsigned char blue; }; - static const float ZERO = 0.0f; static const float ONE = 1.0f; static const float ONE_HALF = 0.5f; @@ -66,8 +65,6 @@ static const quint64 USECS_PER_SECOND = USECS_PER_MSEC * MSECS_PER_SECOND; const int BITS_IN_BYTE = 8; -const int MAX_PACKET_SIZE = 1500; - quint64 usecTimestamp(const timeval *time); quint64 usecTimestampNow(); void usecTimestampNowForceClockSkew(int clockSkew); diff --git a/libraries/shared/src/ThreadedAssignment.cpp b/libraries/shared/src/ThreadedAssignment.cpp index fdf2d91c36..b31d282f64 100644 --- a/libraries/shared/src/ThreadedAssignment.cpp +++ b/libraries/shared/src/ThreadedAssignment.cpp @@ -41,7 +41,7 @@ void ThreadedAssignment::commonInit(const QString& targetName, NodeType_t nodeTy QTimer* domainServerTimer = new QTimer(this); connect(domainServerTimer, SIGNAL(timeout()), this, SLOT(checkInWithDomainServerOrExit())); - domainServerTimer->start(DOMAIN_SERVER_CHECK_IN_USECS / 1000); + domainServerTimer->start(DOMAIN_SERVER_CHECK_IN_MSECS); QTimer* silentNodeRemovalTimer = new QTimer(this); connect(silentNodeRemovalTimer, SIGNAL(timeout()), nodeList, SLOT(removeSilentNodes())); From ec9884833be8c707c7ebff1c1d4db8c0f2cf09b8 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 2 Apr 2014 17:45:34 -0700 Subject: [PATCH 113/595] first cut at reflections --- interface/src/Application.cpp | 10 ++ interface/src/Application.h | 2 + interface/src/AudioReflector.cpp | 274 +++++++++++++++++++++++++++++++ interface/src/AudioReflector.h | 48 ++++++ interface/src/avatar/Head.h | 7 + 5 files changed, 341 insertions(+) create mode 100644 interface/src/AudioReflector.cpp create mode 100644 interface/src/AudioReflector.h diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index bdbe0194e6..fd566e345e 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1597,6 +1597,13 @@ void Application::init() { connect(_rearMirrorTools, SIGNAL(restoreView()), SLOT(restoreMirrorView())); connect(_rearMirrorTools, SIGNAL(shrinkView()), SLOT(shrinkMirrorView())); connect(_rearMirrorTools, SIGNAL(resetView()), SLOT(resetSensors())); + + + // set up our audio reflector + _audioReflector.setMyAvatar(getAvatar()); + _audioReflector.setVoxels(_voxels.getTree()); + _audioReflector.setAudio(getAudio()); + connect(getAudio(), &Audio::audioBufferWrittenToDevice, &_audioReflector, &AudioReflector::addSamples); } void Application::closeMirrorView() { @@ -2378,6 +2385,9 @@ void Application::displaySide(Camera& whichCamera, bool selfAvatarOnly) { // disable specular lighting for ground and voxels glMaterialfv(GL_FRONT, GL_SPECULAR, NO_SPECULAR_COLOR); + + // draw the audio reflector overlay + _audioReflector.render(); // Draw voxels if (Menu::getInstance()->isOptionChecked(MenuOption::Voxels)) { diff --git a/interface/src/Application.h b/interface/src/Application.h index e12d0b307f..50275d96d2 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -33,6 +33,7 @@ #include #include "Audio.h" +#include "AudioReflector.h" #include "BuckyBalls.h" #include "Camera.h" #include "DatagramProcessor.h" @@ -497,6 +498,7 @@ private: TouchEvent _lastTouchEvent; Overlays _overlays; + AudioReflector _audioReflector; }; #endif /* defined(__interface__Application__) */ diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp new file mode 100644 index 0000000000..f6d186d5c9 --- /dev/null +++ b/interface/src/AudioReflector.cpp @@ -0,0 +1,274 @@ +// +// AudioReflector.cpp +// interface +// +// Created by Brad Hefta-Gaub on 4/2/2014 +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// + +#include "AudioReflector.h" + +void AudioReflector::render() { + if (!_myAvatar) { + return; // exit early if not set up correctly + } + + + /* + glm::vec3 position = _myAvatar->getHead()->getPosition(); + const float radius = 0.25f; + glPushMatrix(); + glTranslatef(position.x, position.y, position.z); + glutWireSphere(radius, 15, 15); + glPopMatrix(); + */ + + drawRays(); +} + + +// delay = 1ms per foot +// = 3ms per meter +// attenuation = +// BOUNCE_ATTENUATION_FACTOR [0.5] * (1/(1+distance)) + +int getDelayFromDistance(float distance) { + const int DELAY_PER_METER = 3; + return DELAY_PER_METER * distance; +} + +const float BOUNCE_ATTENUATION_FACTOR = 0.5f; + +float getDistanceAttenuationCoefficient(float distance) { + const float DISTANCE_SCALE = 2.5f; + const float GEOMETRIC_AMPLITUDE_SCALAR = 0.3f; + const float DISTANCE_LOG_BASE = 2.5f; + const float DISTANCE_SCALE_LOG = logf(DISTANCE_SCALE) / logf(DISTANCE_LOG_BASE); + + float distanceSquareToSource = distance * distance; + + // calculate the distance coefficient using the distance to this node + float distanceCoefficient = powf(GEOMETRIC_AMPLITUDE_SCALAR, + DISTANCE_SCALE_LOG + + (0.5f * logf(distanceSquareToSource) / logf(DISTANCE_LOG_BASE)) - 1); + distanceCoefficient = std::min(1.0f, distanceCoefficient); + + return distanceCoefficient; +} + +glm::vec3 getFaceNormal(BoxFace face) { + if (face == MIN_X_FACE) { + return glm::vec3(-1, 0, 0); + } else if (face == MAX_X_FACE) { + return glm::vec3(1, 0, 0); + } else if (face == MIN_Y_FACE) { + return glm::vec3(0, -1, 0); + } else if (face == MAX_Y_FACE) { + return glm::vec3(0, 1, 0); + } else if (face == MIN_Z_FACE) { + return glm::vec3(0, 0, -1); + } else if (face == MAX_Z_FACE) { + return glm::vec3(0, 0, 1); + } + return glm::vec3(0, 0, 0); //error case +} + + +void AudioReflector::drawReflections(const glm::vec3& origin, const glm::vec3& originalDirection, + int bounces, const glm::vec3& originalColor) { + + glm::vec3 start = origin; + glm::vec3 direction = originalDirection; + glm::vec3 color = originalColor; + OctreeElement* elementHit; + float distance; + BoxFace face; + const float SLIGHTLY_SHORT = 0.999f; // slightly inside the distance so we're on the inside of the reflection point + const float COLOR_ADJUST_PER_BOUNCE = 0.75f; + + for (int i = 0; i < bounces; i++) { + if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { + glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); + drawVector(start, end, color); + + glm::vec3 faceNormal = getFaceNormal(face); + direction = glm::normalize(glm::reflect(direction,faceNormal)); + start = end; + color = color * COLOR_ADJUST_PER_BOUNCE; + } + } +} + +void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::vec3& originalDirection, + int bounces, const AudioRingBuffer& samplesRingBuffer) { + + int samplesTouched = 0; + + glm::vec3 rightEarPosition = _myAvatar->getHead()->getRightEarPosition(); + glm::vec3 leftEarPosition = _myAvatar->getHead()->getLeftEarPosition(); + glm::vec3 start = origin; + glm::vec3 direction = originalDirection; + OctreeElement* elementHit; + float distance; + BoxFace face; + const float SLIGHTLY_SHORT = 0.999f; // slightly inside the distance so we're on the inside of the reflection point + + // set up our buffers for our attenuated and delayed samples + AudioRingBuffer attenuatedLeftSamples(samplesRingBuffer.getSampleCapacity()); + AudioRingBuffer attenuatedRightSamples(samplesRingBuffer.getSampleCapacity()); + + const int NUMBER_OF_CHANNELS = 2; + int totalNumberOfSamples = samplesByteArray.size() / (sizeof(int16_t) * NUMBER_OF_CHANNELS); + + for (int bounceNumber = 1; bounceNumber <= bounces; bounceNumber++) { + if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { + glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); + + glm::vec3 faceNormal = getFaceNormal(face); + direction = glm::normalize(glm::reflect(direction,faceNormal)); + start = end; + + // calculate the distance to the ears + float rightEarDistance = glm::distance(end, rightEarPosition); + float leftEarDistance = glm::distance(end, leftEarPosition); + int rightEarDelay = getDelayFromDistance(rightEarDistance); + int leftEarDelay = getDelayFromDistance(leftEarDistance); + float rightEarAttenuation = getDistanceAttenuationCoefficient(rightEarDistance) * + (bounceNumber * BOUNCE_ATTENUATION_FACTOR); + float leftEarAttenuation = getDistanceAttenuationCoefficient(leftEarDistance) * + (bounceNumber * BOUNCE_ATTENUATION_FACTOR); + + // run through the samples, and attenuate them + for (int sample = 0; sample < totalNumberOfSamples; sample++) { + int16_t leftSample = samplesRingBuffer[sample * NUMBER_OF_CHANNELS]; + int16_t rightSample = samplesRingBuffer[(sample * NUMBER_OF_CHANNELS) + 1]; + + attenuatedLeftSamples[sample * NUMBER_OF_CHANNELS] = leftSample * leftEarAttenuation; + attenuatedLeftSamples[sample * NUMBER_OF_CHANNELS + 1] = 0; + + attenuatedRightSamples[sample * NUMBER_OF_CHANNELS] = 0; + attenuatedRightSamples[sample * NUMBER_OF_CHANNELS + 1] = rightSample * rightEarAttenuation; + + samplesTouched++; + } + + // now inject the attenuated array with the appropriate delay + _audio->addDelayedAudio(attenuatedLeftSamples, leftEarDelay); + _audio->addDelayedAudio(attenuatedRightSamples, rightEarDelay); + } + } +} + +void AudioReflector::addSamples(AudioRingBuffer samples) { + quint64 start = usecTimestampNow(); + + glm::vec3 origin = _myAvatar->getHead()->getPosition(); + + glm::quat orientation = _myAvatar->getOrientation(); // _myAvatar->getHead()->getOrientation(); + glm::vec3 right = glm::normalize(orientation * IDENTITY_RIGHT); + glm::vec3 up = glm::normalize(orientation * IDENTITY_UP); + glm::vec3 front = glm::normalize(orientation * IDENTITY_FRONT); + glm::vec3 left = -right; + glm::vec3 down = -up; + glm::vec3 back = -front; + glm::vec3 frontRightUp = glm::normalize(front + right + up); + glm::vec3 frontLeftUp = glm::normalize(front + left + up); + glm::vec3 backRightUp = glm::normalize(back + right + up); + glm::vec3 backLeftUp = glm::normalize(back + left + up); + glm::vec3 frontRightDown = glm::normalize(front + right + down); + glm::vec3 frontLeftDown = glm::normalize(front + left + down); + glm::vec3 backRightDown = glm::normalize(back + right + down); + glm::vec3 backLeftDown = glm::normalize(back + left + down); + + const int BOUNCE_COUNT = 5; + + calculateReflections(origin, frontRightUp, BOUNCE_COUNT, samples); + calculateReflections(origin, frontLeftUp, BOUNCE_COUNT, samples); + calculateReflections(origin, backRightUp, BOUNCE_COUNT, samples); + calculateReflections(origin, backLeftUp, BOUNCE_COUNT, samples); + calculateReflections(origin, frontRightDown, BOUNCE_COUNT, samples); + calculateReflections(origin, frontLeftDown, BOUNCE_COUNT, samples); + calculateReflections(origin, backRightDown, BOUNCE_COUNT, samples); + calculateReflections(origin, backLeftDown, BOUNCE_COUNT, samples); + + calculateReflections(origin, front, BOUNCE_COUNT, samples); + calculateReflections(origin, back, BOUNCE_COUNT, samples); + calculateReflections(origin, left, BOUNCE_COUNT, samples); + calculateReflections(origin, right, BOUNCE_COUNT, samples); + calculateReflections(origin, up, BOUNCE_COUNT, samples); + calculateReflections(origin, down, BOUNCE_COUNT, samples); + quint64 end = usecTimestampNow(); + + qDebug() << "AudioReflector::addSamples()... samples.size()=" << samples.size() << " elapsed=" << (end - start); + +} + +void AudioReflector::drawRays() { + glm::vec3 origin = _myAvatar->getHead()->getPosition(); + //glm::vec3 origin = _myAvatar->getHead()->getRightEarPosition(); + + glm::quat orientation = _myAvatar->getOrientation(); // _myAvatar->getHead()->getOrientation(); + glm::vec3 right = glm::normalize(orientation * IDENTITY_RIGHT); + glm::vec3 up = glm::normalize(orientation * IDENTITY_UP); + glm::vec3 front = glm::normalize(orientation * IDENTITY_FRONT); + glm::vec3 left = -right; + glm::vec3 down = -up; + glm::vec3 back = -front; + glm::vec3 frontRightUp = glm::normalize(front + right + up); + glm::vec3 frontLeftUp = glm::normalize(front + left + up); + glm::vec3 backRightUp = glm::normalize(back + right + up); + glm::vec3 backLeftUp = glm::normalize(back + left + up); + glm::vec3 frontRightDown = glm::normalize(front + right + down); + glm::vec3 frontLeftDown = glm::normalize(front + left + down); + glm::vec3 backRightDown = glm::normalize(back + right + down); + glm::vec3 backLeftDown = glm::normalize(back + left + down); + + + const glm::vec3 RED(1,0,0); + const glm::vec3 GREEN(0,1,0); + const glm::vec3 BLUE(0,0,1); + const glm::vec3 PURPLE(1,0,1); + const glm::vec3 YELLOW(1,1,0); + const glm::vec3 CYAN(0,1,1); + const glm::vec3 DARK_RED(0.8f,0.2f,0.2f); + const glm::vec3 DARK_GREEN(0.2f,0.8f,0.2f); + const glm::vec3 DARK_BLUE(0.2f,0.2f,0.8f); + const glm::vec3 DARK_PURPLE(0.8f,0.2f,0.8f); + const glm::vec3 DARK_YELLOW(0.8f,0.8f,0.2f); + const glm::vec3 DARK_CYAN(0.2f,0.8f,0.8f); + + const glm::vec3 WHITE(1,1,1); + const glm::vec3 GRAY(0.5f,0.5f,0.5f); + + const int BOUNCE_COUNT = 5; + + drawReflections(origin, frontRightUp, BOUNCE_COUNT, RED); + drawReflections(origin, frontLeftUp, BOUNCE_COUNT, GREEN); + drawReflections(origin, backRightUp, BOUNCE_COUNT, BLUE); + drawReflections(origin, backLeftUp, BOUNCE_COUNT, CYAN); + drawReflections(origin, frontRightDown, BOUNCE_COUNT, PURPLE); + drawReflections(origin, frontLeftDown, BOUNCE_COUNT, YELLOW); + drawReflections(origin, backRightDown, BOUNCE_COUNT, WHITE); + drawReflections(origin, backLeftDown, BOUNCE_COUNT, DARK_RED); + + drawReflections(origin, front, BOUNCE_COUNT, DARK_GREEN); + drawReflections(origin, back, BOUNCE_COUNT, DARK_BLUE); + drawReflections(origin, left, BOUNCE_COUNT, DARK_CYAN); + drawReflections(origin, right, BOUNCE_COUNT, DARK_PURPLE); + drawReflections(origin, up, BOUNCE_COUNT, DARK_YELLOW); + drawReflections(origin, down, BOUNCE_COUNT, GRAY); +} + +void AudioReflector::drawVector(const glm::vec3& start, const glm::vec3& end, const glm::vec3& color) { + glDisable(GL_LIGHTING); // ?? + glLineWidth(2.0); + + // Draw the vector itself + glBegin(GL_LINES); + glColor3f(color.x,color.y,color.z); + glVertex3f(start.x, start.y, start.z); + glVertex3f(end.x, end.y, end.z); + glEnd(); + + glEnable(GL_LIGHTING); // ?? +} diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h new file mode 100644 index 0000000000..a348fc67ea --- /dev/null +++ b/interface/src/AudioReflector.h @@ -0,0 +1,48 @@ +// +// AudioReflector.h +// interface +// +// Created by Brad Hefta-Gaub on 4/2/2014 +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// + +#ifndef __interface__AudioReflector__ +#define __interface__AudioReflector__ + +#include + +#include "Audio.h" +#include "avatar/MyAvatar.h" + +class AudioReflector : public QObject { + Q_OBJECT +public: + AudioReflector(QObject* parent = 0) : QObject(parent) { }; + + void setVoxels(VoxelTree* voxels) { _voxels = voxels; } + void setMyAvatar(MyAvatar* myAvatar) { _myAvatar = myAvatar; } + void setAudio(Audio* audio) { _audio = audio; } + + void render(); + +public slots: + void addSamples(AudioRingBuffer samples); + +signals: + +private: + VoxelTree* _voxels; // used to access voxel scene + MyAvatar* _myAvatar; // access to listener + Audio* _audio; // access to audio API + + void drawRays(); + void drawVector(const glm::vec3& start, const glm::vec3& end, const glm::vec3& color); + void drawReflections(const glm::vec3& origin, const glm::vec3& direction, int bounces, const glm::vec3& color); + + void calculateReflections(const glm::vec3& origin, const glm::vec3& originalDirection, + int bounces, const AudioRingBuffer& samplesRingBuffer); + +}; + + +#endif /* defined(__interface__AudioReflector__) */ diff --git a/interface/src/avatar/Head.h b/interface/src/avatar/Head.h index 8a03cfc7ad..0ec0b17a8c 100644 --- a/interface/src/avatar/Head.h +++ b/interface/src/avatar/Head.h @@ -27,6 +27,8 @@ enum eyeContactTargets { MOUTH }; +const float EYE_EAR_GAP = 0.08f; + class Avatar; class ProgramObject; @@ -70,6 +72,11 @@ public: glm::quat getEyeRotation(const glm::vec3& eyePosition) const; + const glm::vec3& getRightEyePosition() const { return _rightEyePosition; } + const glm::vec3& getLeftEyePosition() const { return _leftEyePosition; } + glm::vec3 getRightEarPosition() const { return _rightEyePosition + (getRightDirection() * EYE_EAR_GAP) + (getFrontDirection() * -EYE_EAR_GAP); } + glm::vec3 getLeftEarPosition() const { return _leftEyePosition + (getRightDirection() * -EYE_EAR_GAP) + (getFrontDirection() * -EYE_EAR_GAP); } + FaceModel& getFaceModel() { return _faceModel; } const FaceModel& getFaceModel() const { return _faceModel; } From f7d926931423d450fdb2beb0c18755e1cc47bbc2 Mon Sep 17 00:00:00 2001 From: matsukaze Date: Thu, 3 Apr 2014 17:36:03 -0700 Subject: [PATCH 114/595] Modifications to support spatial audio processing. --- interface/src/Audio.cpp | 122 +++++++++++++++++++++++++++++++++++----- interface/src/Audio.h | 13 ++++- interface/src/Menu.cpp | 5 ++ interface/src/Menu.h | 1 + 4 files changed, 125 insertions(+), 16 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 63c683dbb0..503ec5155b 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -76,7 +76,11 @@ Audio::Audio(Oscilloscope* scope, int16_t initialJitterBufferSamples, QObject* p _collisionSoundDuration(0.0f), _proceduralEffectSample(0), _numFramesDisplayStarve(0), - _muted(false) + _muted(false), + _processSpatialAudio(false), + _spatialAudioStart(0), + _spatialAudioFinish(0), + _spatialAudioRingBuffer(NETWORK_BUFFER_LENGTH_BYTES_PER_CHANNEL) { // clear the array of locally injected samples memset(_localProceduralSamples, 0, NETWORK_BUFFER_LENGTH_BYTES_PER_CHANNEL); @@ -584,7 +588,7 @@ void Audio::addReceivedAudioToBuffer(const QByteArray& audioByteArray) { _totalPacketsReceived++; double timeDiff = diffclock(&_lastReceiveTime, ¤tReceiveTime); - + // Discard first few received packets for computing jitter (often they pile up on start) if (_totalPacketsReceived > NUM_INITIAL_PACKETS_DISCARD) { _stdev.addValue(timeDiff); @@ -604,7 +608,8 @@ void Audio::addReceivedAudioToBuffer(const QByteArray& audioByteArray) { if (_audioOutput) { // Audio output must exist and be correctly set up if we're going to process received audio - processReceivedAudio(audioByteArray); + _ringBuffer.parseData(audioByteArray); + processReceivedAudio(_spatialAudioStart, _ringBuffer); } Application::getInstance()->getBandwidthMeter()->inputStream(BandwidthMeter::AUDIO).updateValue(audioByteArray.size()); @@ -612,6 +617,68 @@ void Audio::addReceivedAudioToBuffer(const QByteArray& audioByteArray) { _lastReceiveTime = currentReceiveTime; } +unsigned int Audio::timeValToSampleTick(const quint64 time, int sampleRate) { + unsigned int sample = (unsigned int)(time / 1000000 * sampleRate); + return sample; +} + +void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, AudioRingBuffer& spatialAudio) { + + // Calculate the number of remaining samples available + unsigned int remaining = _spatialAudioRingBuffer.getSampleCapacity() - _spatialAudioRingBuffer.samplesAvailable(); + if (sampleTime >= _spatialAudioFinish) { + if (_spatialAudioStart == _spatialAudioFinish) { + + // Nothing in the spatial audio ring buffer yet + // Just do a straight copy, clipping if necessary + unsigned int sampleCt = (remaining < spatialAudio.samplesAvailable()) ? remaining : spatialAudio.samplesAvailable(); + if (sampleCt) { + _spatialAudioRingBuffer.writeSamples(spatialAudio.getBuffer(), sampleCt); + } + _spatialAudioFinish = _spatialAudioStart + spatialAudio.samplesAvailable() / _desiredOutputFormat.channelCount(); + + } else { + + // Spatial audio ring buffer already has data, but there is no overlap with the new sample + // compute the appropriate time delay and pad with silence until the new start time + unsigned int delay = sampleTime - _spatialAudioFinish; + unsigned int ct = delay * _desiredOutputFormat.channelCount(); + unsigned int silentCt = (remaining < ct) ? remaining : ct; + if (silentCt) { + _spatialAudioRingBuffer.addSilentFrame(silentCt); + } + + // Recalculate the number of remaining samples + remaining -= silentCt; + unsigned int sampleCt = (remaining < spatialAudio.samplesAvailable()) ? remaining : spatialAudio.samplesAvailable(); + + // Copy the new spatial audio to the accumulation ring buffer + if (sampleCt) { + _spatialAudioRingBuffer.writeSamples(spatialAudio.getBuffer(), sampleCt); + } + _spatialAudioFinish += (sampleCt + silentCt) / _desiredOutputFormat.channelCount(); + } + } else { + + // There is overlap between the spatial audio buffer and the new sample, + // acumulate the overlap + unsigned int offset = (sampleTime - _spatialAudioStart) * _desiredOutputFormat.channelCount(); + unsigned int accumulationCt = (_spatialAudioFinish - sampleTime) * _desiredOutputFormat.channelCount(); + int j = 0; + for (int i = accumulationCt; --i >= 0; j++) { + _spatialAudioRingBuffer[j + offset] += spatialAudio[j]; + } + + // Copy the remaining unoverlapped spatial audio to the accumulation buffer + unsigned int sampleCt = (remaining < spatialAudio.samplesAvailable()) ? remaining : spatialAudio.samplesAvailable(); + if (sampleCt) { + _spatialAudioRingBuffer.writeSamples(spatialAudio.getBuffer() + accumulationCt, sampleCt); + } + _spatialAudioFinish += sampleCt / _desiredOutputFormat.channelCount(); + } + spatialAudio.reset(); +} + bool Audio::mousePressEvent(int x, int y) { if (_iconBounds.contains(x, y)) { toggleMute(); @@ -629,24 +696,23 @@ void Audio::toggleAudioNoiseReduction() { _noiseGateEnabled = !_noiseGateEnabled; } -void Audio::processReceivedAudio(const QByteArray& audioByteArray) { - _ringBuffer.parseData(audioByteArray); +void Audio::processReceivedAudio(unsigned int sampleTime, AudioRingBuffer& ringBuffer) { float networkOutputToOutputRatio = (_desiredOutputFormat.sampleRate() / (float) _outputFormat.sampleRate()) * (_desiredOutputFormat.channelCount() / (float) _outputFormat.channelCount()); - if (!_ringBuffer.isStarved() && _audioOutput && _audioOutput->bytesFree() == _audioOutput->bufferSize()) { + if (!ringBuffer.isStarved() && _audioOutput && _audioOutput->bytesFree() == _audioOutput->bufferSize()) { // we don't have any audio data left in the output buffer // we just starved //qDebug() << "Audio output just starved."; - _ringBuffer.setIsStarved(true); + ringBuffer.setIsStarved(true); _numFramesDisplayStarve = 10; } // if there is anything in the ring buffer, decide what to do - if (_ringBuffer.samplesAvailable() > 0) { + if (ringBuffer.samplesAvailable() > 0) { - int numNetworkOutputSamples = _ringBuffer.samplesAvailable(); + int numNetworkOutputSamples = ringBuffer.samplesAvailable(); int numDeviceOutputSamples = numNetworkOutputSamples / networkOutputToOutputRatio; QByteArray outputBuffer; @@ -654,19 +720,35 @@ void Audio::processReceivedAudio(const QByteArray& audioByteArray) { int numSamplesNeededToStartPlayback = NETWORK_BUFFER_LENGTH_SAMPLES_STEREO + (_jitterBufferSamples * 2); - if (!_ringBuffer.isNotStarvedOrHasMinimumSamples(numSamplesNeededToStartPlayback)) { + if (!ringBuffer.isNotStarvedOrHasMinimumSamples(numSamplesNeededToStartPlayback)) { // We are still waiting for enough samples to begin playback // qDebug() << numNetworkOutputSamples << " samples so far, waiting for " << numSamplesNeededToStartPlayback; } else { // We are either already playing back, or we have enough audio to start playing back. //qDebug() << "pushing " << numNetworkOutputSamples; - _ringBuffer.setIsStarved(false); + ringBuffer.setIsStarved(false); - // copy the samples we'll resample from the ring buffer - this also - // pushes the read pointer of the ring buffer forwards int16_t* ringBufferSamples= new int16_t[numNetworkOutputSamples]; - _ringBuffer.readSamples(ringBufferSamples, numNetworkOutputSamples); - + if (_processSpatialAudio) { + unsigned int sampleTime = _spatialAudioFinish; + // Accumulate direct transmission of audio from sender to receiver + addSpatialAudioToBuffer(sampleTime, ringBuffer); + + // Send audio off for spatial processing + emit processSpatialAudio(sampleTime, ringBuffer, _desiredOutputFormat); + + // copy the samples we'll resample from the spatial audio ring buffer - this also + // pushes the read pointer of the spatial audio ring buffer forwards + _spatialAudioRingBuffer.readSamples(ringBufferSamples, numNetworkOutputSamples); + _spatialAudioStart += ringBuffer.samplesAvailable() / _desiredOutputFormat.channelCount(); + + } else { + + // copy the samples we'll resample from the ring buffer - this also + // pushes the read pointer of the ring buffer forwards + ringBuffer.readSamples(ringBufferSamples, numNetworkOutputSamples); + } + // add the next numNetworkOutputSamples from each QByteArray // in our _localInjectionByteArrays QVector to the localInjectedSamples @@ -723,6 +805,10 @@ void Audio::toggleToneInjection() { _toneInjectionEnabled = !_toneInjectionEnabled; } +void Audio::toggleAudioSpatialProcessing() { + _processSpatialAudio = !_processSpatialAudio; +} + // Take a pointer to the acquired microphone input samples and add procedural sounds void Audio::addProceduralSounds(int16_t* monoInput, int numSamples) { float sample; @@ -943,6 +1029,12 @@ bool Audio::switchOutputToAudioDevice(const QAudioDeviceInfo& outputDeviceInfo) _proceduralAudioOutput = new QAudioOutput(outputDeviceInfo, _outputFormat, this); gettimeofday(&_lastReceiveTime, NULL); + + // setup spatial audio ringbuffer + int numFrameSamples = _outputFormat.sampleRate() * _desiredOutputFormat.channelCount(); + _spatialAudioRingBuffer.resizeForFrameSize(numFrameSamples); + _spatialAudioStart = _spatialAudioFinish = 0; + supportedFormat = true; } } diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 88488922f3..879eb27d42 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -78,11 +78,13 @@ public slots: void start(); void stop(); void addReceivedAudioToBuffer(const QByteArray& audioByteArray); + void addSpatialAudioToBuffer(unsigned int sampleTime, AudioRingBuffer& spatialAudio); void handleAudioInput(); void reset(); void toggleMute(); void toggleAudioNoiseReduction(); void toggleToneInjection(); + void toggleAudioSpatialProcessing(); virtual void handleAudioByteArray(const QByteArray& audioByteArray); @@ -98,6 +100,7 @@ public slots: signals: bool muteToggled(); + void processSpatialAudio(unsigned int sampleTime, const AudioRingBuffer& ringBuffer, const QAudioFormat& format); private: @@ -166,6 +169,14 @@ private: // Audio callback in class context. inline void performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* outputRight); + // Process received audio by spatial attenuation geometric response + bool _processSpatialAudio; + unsigned int _spatialAudioStart; ///< Start of spatial audio interval (in sample rate time base) + unsigned int _spatialAudioFinish; ///< End of spatial audio interval (in sample rate time base) + AudioRingBuffer _spatialAudioRingBuffer; ///< Spatially processed audio + + unsigned int timeValToSampleTick(const quint64 time, int sampleRate); + // Process procedural audio by // 1. Echo to the local procedural output device // 2. Mix with the audio input @@ -175,7 +186,7 @@ private: void addProceduralSounds(int16_t* monoInput, int numSamples); // Process received audio - void processReceivedAudio(const QByteArray& audioByteArray); + void processReceivedAudio(unsigned int sampleTime, AudioRingBuffer& ringBuffer); bool switchInputToAudioDevice(const QAudioDeviceInfo& inputDeviceInfo); bool switchOutputToAudioDevice(const QAudioDeviceInfo& outputDeviceInfo); diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 89de7a2d03..3dd4733c64 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -366,6 +366,11 @@ Menu::Menu() : false, appInstance->getAudio(), SLOT(toggleToneInjection())); + addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessing, + Qt::CTRL | Qt::SHIFT | Qt::Key_M, + false, + appInstance->getAudio(), + SLOT(toggleAudioSpatialProcessing())); addActionToQMenuAndActionHash(developerMenu, MenuOption::PasteToVoxel, diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 5aa0a13c9c..b6feb2e2f5 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -243,6 +243,7 @@ namespace MenuOption { const QString Enable3DTVMode = "Enable 3DTV Mode"; const QString AudioNoiseReduction = "Audio Noise Reduction"; const QString AudioToneInjection = "Inject Test Tone"; + const QString AudioSpatialProcessing = "Audio Spatial Processing"; const QString EchoServerAudio = "Echo Server Audio"; const QString EchoLocalAudio = "Echo Local Audio"; const QString MuteAudio = "Mute Microphone"; From 62de84315e5226b805d6ae238a15c6e1aeb55fe2 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 2 Apr 2014 17:56:04 -0700 Subject: [PATCH 115/595] detect handshake completion in DS and client --- domain-server/src/DomainServer.cpp | 22 +++++++++++++++++----- libraries/shared/src/DTLSClientSession.cpp | 10 +--------- libraries/shared/src/DTLSSession.cpp | 3 ++- libraries/shared/src/DTLSSession.h | 4 ++++ libraries/shared/src/NodeList.cpp | 22 ++++++++++++++-------- 5 files changed, 38 insertions(+), 23 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 5550c2741d..efecd5d322 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -628,9 +628,22 @@ void DomainServer::readAvailableDTLSDatagrams() { DTLSServerSession* existingSession = _dtlsSessions.value(senderHifiSockAddr); if (existingSession) { - // check if we have completed handshake with this user - int handshakeReturn = gnutls_handshake(*existingSession->getGnuTLSSession()); - qDebug() << "Handshake return for user is" << handshakeReturn; + if (!existingSession->completedHandshake()) { + // check if we have completed handshake with this user + int handshakeReturn = gnutls_handshake(*existingSession->getGnuTLSSession()); + + if (handshakeReturn == 0) { + existingSession->setCompletedHandshake(true); + } else if (gnutls_error_is_fatal(handshakeReturn)) { + // this was a fatal error handshaking, so remove this session + qDebug() << "Fatal error -" << gnutls_strerror(handshakeReturn) << "- during DTLS handshake with" + << senderHifiSockAddr; + _dtlsSessions.remove(senderHifiSockAddr); + } + } else { + // pull the data from this user off the stack and process it + dtlsSocket.readDatagram(peekDatagram.data(), peekDatagram.size()); + } } else { // first we verify the cookie // see http://gnutls.org/manual/html_node/DTLS-sessions.html for why this is required @@ -659,8 +672,7 @@ void DomainServer::readAvailableDTLSDatagrams() { gnutls_dtls_prestate_set(*gnutlsSession, &prestate); // handshake to begin the session - int handshakeReturn = gnutls_handshake(*gnutlsSession); - qDebug() << "initial handshake return" << handshakeReturn; + gnutls_handshake(*gnutlsSession); qDebug() << "Beginning DTLS session with node at" << senderHifiSockAddr; _dtlsSessions[senderHifiSockAddr] = newServerSession; diff --git a/libraries/shared/src/DTLSClientSession.cpp b/libraries/shared/src/DTLSClientSession.cpp index 109172487f..73daa4e03a 100644 --- a/libraries/shared/src/DTLSClientSession.cpp +++ b/libraries/shared/src/DTLSClientSession.cpp @@ -14,22 +14,14 @@ gnutls_certificate_credentials_t* DTLSClientSession::x509CACredentials() { if (!credentialsInitialized) { gnutls_certificate_allocate_credentials(&x509Credentials); - qDebug() << "processed" << gnutls_certificate_set_x509_trust_file(x509Credentials, "/Users/birarda/code/hifi/certs/root-ca.crt", GNUTLS_X509_FMT_PEM); } return &x509Credentials; } -int verifyX509Certificate(gnutls_session_t session) { - int certificateType = gnutls_certificate_type_get(session); - qDebug() << "Verifying a certificate of type" << certificateType; - - return 0; -} - DTLSClientSession::DTLSClientSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket) : DTLSSession(GNUTLS_CLIENT, dtlsSocket, destinationSocket) { gnutls_priority_set_direct(_gnutlsSession, "PERFORMANCE", NULL); - gnutls_credentials_set(_gnutlsSession, GNUTLS_CRD_CERTIFICATE, x509CACredentials()); + gnutls_credentials_set(_gnutlsSession, GNUTLS_CRD_CERTIFICATE, *x509CACredentials()); } \ No newline at end of file diff --git a/libraries/shared/src/DTLSSession.cpp b/libraries/shared/src/DTLSSession.cpp index 52c55bec23..9d30ab8148 100644 --- a/libraries/shared/src/DTLSSession.cpp +++ b/libraries/shared/src/DTLSSession.cpp @@ -77,7 +77,8 @@ ssize_t DTLSSession::socketPush(gnutls_transport_ptr_t ptr, const void* buffer, DTLSSession::DTLSSession(int end, QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket) : _dtlsSocket(dtlsSocket), - _destinationSocket(destinationSocket) + _destinationSocket(destinationSocket), + _completedHandshake(false) { gnutls_init(&_gnutlsSession, end | GNUTLS_DATAGRAM | GNUTLS_NONBLOCK); diff --git a/libraries/shared/src/DTLSSession.h b/libraries/shared/src/DTLSSession.h index ce190e11c0..01e0e187e8 100644 --- a/libraries/shared/src/DTLSSession.h +++ b/libraries/shared/src/DTLSSession.h @@ -26,10 +26,14 @@ public: gnutls_session_t* getGnuTLSSession() { return &_gnutlsSession; } + bool completedHandshake() const { return _completedHandshake; } + void setCompletedHandshake(bool completedHandshake) { _completedHandshake = completedHandshake; } + protected: QUdpSocket& _dtlsSocket; gnutls_session_t _gnutlsSession; HifiSockAddr _destinationSocket; + bool _completedHandshake; }; #endif /* defined(__hifi__DTLSSession__) */ diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 1740525ef1..792215ea68 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -324,15 +324,21 @@ void NodeList::sendDomainServerCheckIn() { DTLSClientSession* dtlsSession = _domainHandler.getDTLSSession(); if (dtlsSession) { - int handshakeReturn = gnutls_handshake(*dtlsSession->getGnuTLSSession()); + if (dtlsSession->completedHandshake()) { + qDebug() << "we can send a DTLS check in!"; + } else { + int handshakeReturn = gnutls_handshake(*dtlsSession->getGnuTLSSession()); + if (handshakeReturn == 0) { + dtlsSession->setCompletedHandshake(true); + } else if (gnutls_error_is_fatal(handshakeReturn)) { + // this was a fatal error handshaking, so remove this session + qDebug() << "Fatal error -" << gnutls_strerror(handshakeReturn) + << "- during DTLS handshake with DS at" << _domainHandler.getHostname(); + + _domainHandler.clearConnectionInfo(); + } + } - gnutls_handshake_description_t inType = gnutls_handshake_get_last_in(*dtlsSession->getGnuTLSSession()); - gnutls_handshake_description_t outType = gnutls_handshake_get_last_out(*dtlsSession->getGnuTLSSession()); - qDebug() << "in" << gnutls_handshake_description_get_name(inType); - qDebug() << "out" << gnutls_handshake_description_get_name(outType); - - // make sure DTLS handshake with the domain-server is complete - qDebug() << "GnuTLS handshake return is" << handshakeReturn; } else { // construct the DS check in packet QUuid packetUUID = (!_sessionUUID.isNull() ? _sessionUUID : _domainHandler.getAssignmentUUID()); From 5acc8313ba13223b6c5085bce923e9933b3ed823 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 2 Apr 2014 18:07:55 -0700 Subject: [PATCH 116/595] Manual merge --- interface/interface_en.ts | 71 +++- interface/resources/images/kill-script.svg | 7 + interface/resources/images/reload.svg | 24 ++ interface/resources/images/stop.svg | 7 + interface/resources/resources.qrc | 3 + interface/src/Application.cpp | 332 ++++++++++--------- interface/src/Application.h | 39 ++- interface/src/Menu.cpp | 119 ++++--- interface/src/Menu.h | 10 +- interface/src/ui/RunningScriptsWidget.cpp | 203 ++++++++++++ interface/src/ui/RunningScriptsWidget.h | 46 +++ interface/ui/runningScriptsWidget.ui | 248 ++++++++++++++ libraries/script-engine/src/ScriptEngine.cpp | 131 +++----- libraries/script-engine/src/ScriptEngine.h | 33 +- 14 files changed, 930 insertions(+), 343 deletions(-) create mode 100644 interface/resources/images/kill-script.svg create mode 100644 interface/resources/images/reload.svg create mode 100644 interface/resources/images/stop.svg create mode 100644 interface/src/ui/RunningScriptsWidget.cpp create mode 100644 interface/src/ui/RunningScriptsWidget.h create mode 100644 interface/ui/runningScriptsWidget.ui diff --git a/interface/interface_en.ts b/interface/interface_en.ts index 7628407039..4473672b01 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -4,22 +4,30 @@ Application - + Export Voxels - + Sparse Voxel Octree Files (*.svo) +<<<<<<< HEAD +======= + +>>>>>>> 0fa910c61fd4ffb4e4eb4b7c53f1e67da9ac0913 Open Script +<<<<<<< HEAD +======= + +>>>>>>> 0fa910c61fd4ffb4e4eb4b7c53f1e67da9ac0913 JavaScript Files (*.js) @@ -106,18 +114,18 @@ Menu - + Open .ini config file - - + + Text files (*.ini) - + Save .ini config file @@ -151,4 +159,55 @@ + + RunningScriptsWidget + + + + Form + + + + + + <html><head/><body><p><span style=" font-size:18pt;">Running Scripts</span></p></body></html> + + + + + + <html><head/><body><p><span style=" font-weight:600;">Currently running</span></p></body></html> + + + + + + Reload All + + + + + + Stop All + + + + + + <html><head/><body><p><span style=" font-weight:600;">Recently loaded</span></p></body></html> + + + + + + (click a script or use the 1-9 keys to load and run it) + + + + + + There are no scripts currently running. + + + diff --git a/interface/resources/images/kill-script.svg b/interface/resources/images/kill-script.svg new file mode 100644 index 0000000000..d98fc4555a --- /dev/null +++ b/interface/resources/images/kill-script.svg @@ -0,0 +1,7 @@ + + + + + + diff --git a/interface/resources/images/reload.svg b/interface/resources/images/reload.svg new file mode 100644 index 0000000000..a596f03301 --- /dev/null +++ b/interface/resources/images/reload.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + diff --git a/interface/resources/images/stop.svg b/interface/resources/images/stop.svg new file mode 100644 index 0000000000..ea22bb592a --- /dev/null +++ b/interface/resources/images/stop.svg @@ -0,0 +1,7 @@ + + + + + + diff --git a/interface/resources/resources.qrc b/interface/resources/resources.qrc index 372fa8b1d4..35c0e40270 100644 --- a/interface/resources/resources.qrc +++ b/interface/resources/resources.qrc @@ -1,5 +1,8 @@ images/close.svg + images/kill-script.svg + images/reload.svg + images/stop.svg diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index bdbe0194e6..d070256035 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -49,7 +49,7 @@ #include #include #include -#include +#include #include #include @@ -118,7 +118,7 @@ void messageHandler(QtMsgType type, const QMessageLogContext& context, const QSt if (message.size() > 0) { QString dateString = QDateTime::currentDateTime().toTimeSpec(Qt::LocalTime).toString(Qt::ISODate); QString formattedMessage = QString("[%1] %2\n").arg(dateString).arg(message); - + fprintf(stdout, "%s", qPrintable(formattedMessage)); Application::getInstance()->getLogger()->addMessage(qPrintable(formattedMessage)); } @@ -175,23 +175,23 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : { // read the ApplicationInfo.ini file for Name/Version/Domain information QSettings applicationInfo(Application::resourcesPath() + "info/ApplicationInfo.ini", QSettings::IniFormat); - + // set the associated application properties applicationInfo.beginGroup("INFO"); - + qDebug() << "[VERSION] Build sequence: " << qPrintable(applicationVersion()); - + setApplicationName(applicationInfo.value("name").toString()); setApplicationVersion(BUILD_VERSION); setOrganizationName(applicationInfo.value("organizationName").toString()); setOrganizationDomain(applicationInfo.value("organizationDomain").toString()); - + QSettings::setDefaultFormat(QSettings::IniFormat); - + _myAvatar = _avatarManager.getMyAvatar(); _applicationStartupTime = startup_time; - + QFontDatabase::addApplicationFont(Application::resourcesPath() + "styles/Inconsolata.otf"); _window->setWindowTitle("Interface"); @@ -206,19 +206,19 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : if (portStr) { listenPort = atoi(portStr); } - + // start the nodeThread so its event loop is running _nodeThread->start(); - + // make sure the node thread is given highest priority _nodeThread->setPriority(QThread::TimeCriticalPriority); - + // put the NodeList and datagram processing on the node thread NodeList* nodeList = NodeList::createInstance(NodeType::Agent, listenPort); - + nodeList->moveToThread(_nodeThread); _datagramProcessor.moveToThread(_nodeThread); - + // connect the DataProcessor processDatagrams slot to the QUDPSocket readyRead() signal connect(&nodeList->getNodeSocket(), SIGNAL(readyRead()), &_datagramProcessor, SLOT(processDatagrams())); @@ -240,20 +240,20 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : connect(nodeList, SIGNAL(nodeKilled(SharedNodePointer)), &_voxels, SLOT(nodeKilled(SharedNodePointer))); connect(nodeList, &NodeList::uuidChanged, this, &Application::updateWindowTitle); connect(nodeList, &NodeList::limitOfSilentDomainCheckInsReached, nodeList, &NodeList::reset); - + // connect to appropriate slots on AccountManager AccountManager& accountManager = AccountManager::getInstance(); connect(&accountManager, &AccountManager::authRequired, Menu::getInstance(), &Menu::loginForCurrentDomain); connect(&accountManager, &AccountManager::usernameChanged, this, &Application::updateWindowTitle); - + // set the account manager's root URL and trigger a login request if we don't have the access token accountManager.setAuthURL(DEFAULT_NODE_AUTH_URL); - + // once the event loop has started, check and signal for an access token QMetaObject::invokeMethod(&accountManager, "checkAndSignalForAccessToken", Qt::QueuedConnection); _settings = new QSettings(this); - + // Check to see if the user passed in a command line option for loading a local // Voxel File. _voxelsFilename = getCmdOption(argc, constArgv, "-i"); @@ -267,7 +267,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : nodeList->addSetOfNodeTypesToNodeInterestSet(NodeSet() << NodeType::AudioMixer << NodeType::AvatarMixer << NodeType::VoxelServer << NodeType::ParticleServer << NodeType::MetavoxelServer); - + // connect to the packet sent signal of the _voxelEditSender and the _particleEditSender connect(&_voxelEditSender, &VoxelEditPacketSender::packetSent, this, &Application::packetSent); connect(&_particleEditSender, &ParticleEditPacketSender::packetSent, this, &Application::packetSent); @@ -277,7 +277,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : connect(silentNodeTimer, SIGNAL(timeout()), nodeList, SLOT(removeSilentNodes())); silentNodeTimer->moveToThread(_nodeThread); silentNodeTimer->start(NODE_SILENCE_THRESHOLD_USECS / 1000); - + // send the identity packet for our avatar each second to our avatar mixer QTimer* identityPacketTimer = new QTimer(); connect(identityPacketTimer, &QTimer::timeout, _myAvatar, &MyAvatar::sendIdentityPacket); @@ -325,14 +325,18 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : // Set the sixense filtering _sixenseManager.setFilter(Menu::getInstance()->isOptionChecked(MenuOption::FilterSixense)); - + checkVersion(); - + _overlays.init(_glWidget); // do this before scripts load - + LocalVoxelsList::getInstance()->addPersistantTree(DOMAIN_TREE_NAME, _voxels.getTree()); LocalVoxelsList::getInstance()->addPersistantTree(CLIPBOARD_TREE_NAME, &_clipboard); + _window->addDockWidget(Qt::NoDockWidgetArea, _runningScriptsWidget = new RunningScriptsWidget()); + _runningScriptsWidget->setRunningScripts(getRunningScripts()); + connect(_runningScriptsWidget, &RunningScriptsWidget::stopScriptName, this, &Application::stopScript); + // check first run... QVariant firstRunValue = _settings->value("firstRun",QVariant(true)); if (firstRunValue.isValid() && firstRunValue.toBool()) { @@ -340,7 +344,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : // clear the scripts, and set out script to our default scripts clearScriptsBeforeRunning(); loadScript("http://public.highfidelity.io/scripts/defaultScripts.js"); - + _settings->setValue("firstRun",QVariant(false)); } else { // do this as late as possible so that all required subsystems are inialized @@ -351,34 +355,34 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : Application::~Application() { qInstallMessageHandler(NULL); - + // make sure we don't call the idle timer any more delete idleTimer; - + Menu::getInstance()->saveSettings(); _rearMirrorTools->saveSettings(_settings); - + _sharedVoxelSystem.changeTree(new VoxelTree); if (_voxelImporter) { _voxelImporter->saveSettings(_settings); delete _voxelImporter; } _settings->sync(); - + // let the avatar mixer know we're out MyAvatar::sendKillAvatar(); - + // ask the datagram processing thread to quit and wait until it is done _nodeThread->quit(); _nodeThread->wait(); - + // stop the audio process QMetaObject::invokeMethod(&_audio, "stop"); - + // ask the audio thread to quit and wait until it is done _audio.thread()->quit(); _audio.thread()->wait(); - + _voxelProcessor.terminate(); _voxelHideShowThread.terminate(); _voxelEditSender.terminate(); @@ -391,9 +395,9 @@ Application::~Application() { Menu::getInstance()->deleteLater(); _myAvatar = NULL; - + delete _glWidget; - + AccountManager::getInstance().destroy(); } @@ -585,7 +589,7 @@ void Application::paintGL() { if (Menu::getInstance()->isOptionChecked(MenuOption::Mirror)) { renderRearViewMirror(_mirrorViewRect); - + } else if (Menu::getInstance()->isOptionChecked(MenuOption::FullscreenMirror)) { _rearMirrorTools->render(true); } @@ -658,10 +662,10 @@ void Application::controlledBroadcastToNodes(const QByteArray& packet, const Nod if (type == NodeType::VoxelServer && !Menu::getInstance()->isOptionChecked(MenuOption::Voxels)) { continue; } - + // Perform the broadcast for one type int nReceivingNodes = NodeList::getInstance()->broadcastToNodes(packet, NodeSet() << type); - + // Feed number of bytes to corresponding channel of the bandwidth meter, if any (done otherwise) BandwidthMeter::ChannelIndex channel; switch (type) { @@ -680,7 +684,7 @@ void Application::controlledBroadcastToNodes(const QByteArray& packet, const Nod } bool Application::event(QEvent* event) { - + // handle custom URL if (event->type() == QEvent::FileOpen) { QFileOpenEvent* fileEvent = static_cast(event); @@ -691,11 +695,11 @@ bool Application::event(QEvent* event) { if (urlParts.count() > 1) { // if url has 2 or more parts, the first one is domain name Menu::getInstance()->goToDomain(urlParts[0]); - + // location coordinates Menu::getInstance()->goToDestination(urlParts[1]); if (urlParts.count() > 2) { - + // location orientation Menu::getInstance()->goToOrientation(urlParts[2]); } @@ -705,7 +709,7 @@ bool Application::event(QEvent* event) { Menu::getInstance()->goToDestination(urlParts[0]); } } - + return false; } return QApplication::event(event); @@ -716,7 +720,7 @@ void Application::keyPressEvent(QKeyEvent* event) { _keysPressed.insert(event->key()); _controllerScriptingInterface.emitKeyPressEvent(event); // send events to any registered scripts - + // if one of our scripts have asked to capture this event, then stop processing it if (_controllerScriptingInterface.isKeyCaptured(event)) { return; @@ -1075,7 +1079,7 @@ void Application::mouseReleaseEvent(QMouseEvent* event) { checkBandwidthMeterClick(); if (Menu::getInstance()->isOptionChecked(MenuOption::Stats)) { checkStatsClick(); - } + } } } } @@ -1124,7 +1128,7 @@ void Application::touchBeginEvent(QTouchEvent* event) { if (_controllerScriptingInterface.isTouchCaptured()) { return; } - + // put any application specific touch behavior below here.. _lastTouchAvgX = _touchAvgX; _lastTouchAvgY = _touchAvgY; @@ -1167,13 +1171,13 @@ void Application::dropEvent(QDropEvent *event) { break; } } - + SnapshotMetaData* snapshotData = Snapshot::parseSnapshotData(snapshotPath); if (snapshotData) { if (!snapshotData->getDomain().isEmpty()) { Menu::getInstance()->goToDomain(snapshotData->getDomain()); } - + _myAvatar->setPosition(snapshotData->getLocation()); _myAvatar->setOrientation(snapshotData->getOrientation()); } else { @@ -1201,19 +1205,19 @@ void Application::timer() { } _fps = (float)_frameCount / ((float)diffclock(&_timerStart, &_timerEnd) / 1000.f); - + _packetsPerSecond = (float) _datagramProcessor.getPacketCount() / ((float)diffclock(&_timerStart, &_timerEnd) / 1000.f); _bytesPerSecond = (float) _datagramProcessor.getByteCount() / ((float)diffclock(&_timerStart, &_timerEnd) / 1000.f); _frameCount = 0; - + _datagramProcessor.resetCounters(); gettimeofday(&_timerStart, NULL); // ask the node list to check in with the domain server NodeList::getInstance()->sendDomainServerCheckIn(); - - + + } void Application::idle() { @@ -1250,11 +1254,11 @@ void Application::idle() { _idleLoopMeasuredJitter = _idleLoopStdev.getStDev(); _idleLoopStdev.reset(); } - + if (Menu::getInstance()->isOptionChecked(MenuOption::BuckyBalls)) { _buckyBalls.simulate(timeSinceLastUpdate / 1000.f, Application::getInstance()->getAvatar()->getHandData()); } - + // After finishing all of the above work, restart the idle timer, allowing 2ms to process events. idleTimer->start(2); } @@ -1386,7 +1390,7 @@ void Application::exportVoxels(const VoxelDetail& sourceVoxel) { tr("Sparse Voxel Octree Files (*.svo)")); QByteArray fileNameAscii = fileNameString.toLocal8Bit(); const char* fileName = fileNameAscii.data(); - + VoxelTreeElement* selectedNode = _voxels.getTree()->getVoxelAt(sourceVoxel.x, sourceVoxel.y, sourceVoxel.z, sourceVoxel.s); if (selectedNode) { VoxelTree exportTree; @@ -1400,12 +1404,12 @@ void Application::exportVoxels(const VoxelDetail& sourceVoxel) { void Application::importVoxels() { _importSucceded = false; - + if (!_voxelImporter) { _voxelImporter = new VoxelImporter(_window); _voxelImporter->loadSettings(_settings); } - + if (!_voxelImporter->exec()) { qDebug() << "[DEBUG] Import succeeded." << endl; _importSucceded = true; @@ -1419,7 +1423,7 @@ void Application::importVoxels() { // restore the main window's active state _window->activateWindow(); - + emit importDone(); } @@ -1475,7 +1479,7 @@ void Application::pasteVoxels(const VoxelDetail& sourceVoxel) { } pasteVoxelsToOctalCode(octalCodeDestination); - + if (calculatedOctCode) { delete[] calculatedOctCode; } @@ -1512,9 +1516,9 @@ void Application::init() { // Cleanup of the original shared tree _sharedVoxelSystem.init(); - + _voxelImporter = new VoxelImporter(_window); - + _environment.init(); _glowEffect.init(); @@ -1556,11 +1560,11 @@ void Application::init() { _audio.setJitterBufferSamples(Menu::getInstance()->getAudioJitterBufferSamples()); } qDebug("Loaded settings"); - + // initialize Visage and Faceshift after loading the menu settings _faceshift.init(); _visage.init(); - + // fire off an immediate domain-server check in now that settings are loaded NodeList::getInstance()->sendDomainServerCheckIn(); @@ -1579,20 +1583,20 @@ void Application::init() { _particleCollisionSystem.init(&_particleEditSender, _particles.getTree(), _voxels.getTree(), &_audio, &_avatarManager); // connect the _particleCollisionSystem to our script engine's ParticleScriptingInterface - connect(&_particleCollisionSystem, + connect(&_particleCollisionSystem, SIGNAL(particleCollisionWithVoxel(const ParticleID&, const VoxelDetail&, const glm::vec3&)), - ScriptEngine::getParticlesScriptingInterface(), + ScriptEngine::getParticlesScriptingInterface(), SLOT(forwardParticleCollisionWithVoxel(const ParticleID&, const VoxelDetail&, const glm::vec3&))); - connect(&_particleCollisionSystem, + connect(&_particleCollisionSystem, SIGNAL(particleCollisionWithParticle(const ParticleID&, const ParticleID&, const glm::vec3&)), - ScriptEngine::getParticlesScriptingInterface(), + ScriptEngine::getParticlesScriptingInterface(), SLOT(forwardParticleCollisionWithParticle(const ParticleID&, const ParticleID&, const glm::vec3&))); - + _audio.init(_glWidget); _rearMirrorTools = new RearMirrorTools(_glWidget, _mirrorViewRect, _settings); - + connect(_rearMirrorTools, SIGNAL(closeView()), SLOT(closeMirrorView())); connect(_rearMirrorTools, SIGNAL(restoreView()), SLOT(restoreMirrorView())); connect(_rearMirrorTools, SIGNAL(shrinkView()), SLOT(shrinkMirrorView())); @@ -1715,7 +1719,7 @@ void Application::updateMyAvatarLookAtPosition() { float distance = TREE_SCALE; if (_myAvatar->getLookAtTargetAvatar() && _myAvatar != _myAvatar->getLookAtTargetAvatar()) { distance = glm::distance(_mouseRayOrigin, - static_cast(_myAvatar->getLookAtTargetAvatar())->getHead()->calculateAverageEyePosition()); + static_cast(_myAvatar->getLookAtTargetAvatar())->getHead()->calculateAverageEyePosition()); } const float FIXED_MIN_EYE_DISTANCE = 0.3f; float minEyeDistance = FIXED_MIN_EYE_DISTANCE + (_myCamera.getMode() == CAMERA_MODE_FIRST_PERSON ? 0.0f : @@ -1728,7 +1732,7 @@ void Application::updateMyAvatarLookAtPosition() { eyePitch = _faceshift.getEstimatedEyePitch(); eyeYaw = _faceshift.getEstimatedEyeYaw(); trackerActive = true; - + } else if (_visage.isActive()) { eyePitch = _visage.getEstimatedEyePitch(); eyeYaw = _visage.getEstimatedEyeYaw(); @@ -1901,9 +1905,9 @@ void Application::update(float deltaTime) { _particles.update(); // update the particles... _particleCollisionSystem.update(); // collide the particles... - + _overlays.update(deltaTime); - + // let external parties know we're updating emit simulating(deltaTime); } @@ -1927,7 +1931,7 @@ void Application::updateMyAvatar(float deltaTime) { // actually need to calculate the view frustum planes to send these details // to the server. loadViewFrustum(_myCamera, _viewFrustum); - + // Update my voxel servers with my current voxel query... quint64 now = usecTimestampNow(); quint64 sinceLastQuery = now - _lastQueriedTime; @@ -2203,7 +2207,7 @@ void Application::updateShadowMap() { } center = inverseRotation * center; glm::vec3 minima(center.x - radius, center.y - radius, center.z - radius); - glm::vec3 maxima(center.x + radius, center.y + radius, center.z + radius); + glm::vec3 maxima(center.x + radius, center.y + radius, center.z + radius); // stretch out our extents in z so that we get all of the avatars minima.z -= _viewFrustum.getFarClip() * 0.5f; @@ -2224,7 +2228,7 @@ void Application::updateShadowMap() { _shadowViewFrustum.setEyeOffsetPosition(glm::vec3()); _shadowViewFrustum.setEyeOffsetOrientation(glm::quat()); _shadowViewFrustum.calculate(); - + glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); @@ -2279,19 +2283,19 @@ void Application::setupWorldLight() { QImage Application::renderAvatarBillboard() { _textureCache.getPrimaryFramebufferObject()->bind(); - + glDisable(GL_BLEND); const int BILLBOARD_SIZE = 64; renderRearViewMirror(QRect(0, _glWidget->height() - BILLBOARD_SIZE, BILLBOARD_SIZE, BILLBOARD_SIZE), true); - + QImage image(BILLBOARD_SIZE, BILLBOARD_SIZE, QImage::Format_ARGB32); glReadPixels(0, 0, BILLBOARD_SIZE, BILLBOARD_SIZE, GL_BGRA, GL_UNSIGNED_BYTE, image.bits()); - + glEnable(GL_BLEND); - + _textureCache.getPrimaryFramebufferObject()->release(); - + return image; } @@ -2392,7 +2396,7 @@ void Application::displaySide(Camera& whichCamera, bool selfAvatarOnly) { "Application::displaySide() ... metavoxels..."); _metavoxels.render(); } - + if (Menu::getInstance()->isOptionChecked(MenuOption::BuckyBalls)) { PerformanceWarning warn(Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings), "Application::displaySide() ... bucky balls..."); @@ -2405,7 +2409,7 @@ void Application::displaySide(Camera& whichCamera, bool selfAvatarOnly) { "Application::displaySide() ... particles..."); _particles.render(); } - + // render the ambient occlusion effect if enabled if (Menu::getInstance()->isOptionChecked(MenuOption::AmbientOcclusion)) { PerformanceWarning warn(Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings), @@ -2449,7 +2453,7 @@ void Application::displaySide(Camera& whichCamera, bool selfAvatarOnly) { // give external parties a change to hook in emit renderingInWorldInterface(); - + // render JS/scriptable overlays _overlays.render3D(); } @@ -2498,7 +2502,7 @@ void Application::displayOverlay() { renderCollisionOverlay(_glWidget->width(), _glWidget->height(), _audio.getCollisionSoundMagnitude()); } } - + // Audio Scope const int AUDIO_SCOPE_Y_OFFSET = 135; if (Menu::getInstance()->isOptionChecked(MenuOption::Stats)) { @@ -2507,7 +2511,7 @@ void Application::displayOverlay() { _audioScope.render(MIRROR_VIEW_LEFT_PADDING, oscilloscopeTop); } } - + // Audio VU Meter and Mute Icon const int MUTE_ICON_SIZE = 24; const int AUDIO_METER_INSET = 2; @@ -2516,7 +2520,7 @@ void Application::displayOverlay() { const int AUDIO_METER_HEIGHT = 8; const int AUDIO_METER_Y_GAP = 8; const int AUDIO_METER_X = MIRROR_VIEW_LEFT_PADDING + MUTE_ICON_SIZE + AUDIO_METER_INSET; - + int audioMeterY; if (Menu::getInstance()->isOptionChecked(MenuOption::Mirror)) { audioMeterY = MIRROR_VIEW_HEIGHT + AUDIO_METER_Y_GAP; @@ -2524,8 +2528,8 @@ void Application::displayOverlay() { audioMeterY = AUDIO_METER_Y_GAP; } _audio.renderMuteIcon(MIRROR_VIEW_LEFT_PADDING, audioMeterY); - - + + const float AUDIO_METER_BLUE[] = {0.0, 0.0, 1.0}; const float AUDIO_METER_GREEN[] = {0.0, 1.0, 0.0}; const float AUDIO_METER_RED[] = {1.0, 0.0, 0.0}; @@ -2627,8 +2631,8 @@ void Application::displayOverlay() { char frameTimer[10]; quint64 mSecsNow = floor(usecTimestampNow() / 1000.0 + 0.5); sprintf(frameTimer, "%d\n", (int)(mSecsNow % 1000)); - int timerBottom = - (Menu::getInstance()->isOptionChecked(MenuOption::Stats) && + int timerBottom = + (Menu::getInstance()->isOptionChecked(MenuOption::Stats) && Menu::getInstance()->isOptionChecked(MenuOption::Bandwidth)) ? 80 : 20; drawText(_glWidget->width() - 100, _glWidget->height() - timerBottom, 0.30f, 1.0f, 0.f, frameTimer, WHITE_TEXT); @@ -2643,7 +2647,7 @@ void Application::displayOverlay() { void Application::displayStatsBackground(unsigned int rgba, int x, int y, int width, int height) { glBegin(GL_QUADS); glColor4f(((rgba >> 24) & 0xff) / 255.0f, - ((rgba >> 16) & 0xff) / 255.0f, + ((rgba >> 16) & 0xff) / 255.0f, ((rgba >> 8) & 0xff) / 255.0f, (rgba & 0xff) / 255.0f); glVertex3f(x, y, 0); @@ -2651,7 +2655,7 @@ void Application::displayStatsBackground(unsigned int rgba, int x, int y, int wi glVertex3f(x + width, y + height, 0); glVertex3f(x , y + height, 0); glEnd(); - glColor4f(1, 1, 1, 1); + glColor4f(1, 1, 1, 1); } // display expanded or contracted stats @@ -2745,12 +2749,12 @@ void Application::displayStats() { (float) (_audio.getNetworkBufferLengthSamplesPerChannel() + (float) _audio.getJitterBufferSamples()) / (float)_audio.getNetworkSampleRate() * 1000.f); drawText(30, _glWidget->height() - 22, 0.10f, 0.f, 2.f, audioJitter, WHITE_TEXT); - - + + char audioPing[30]; sprintf(audioPing, "Audio ping: %d", pingAudio); - - + + char avatarPing[30]; sprintf(avatarPing, "Avatar ping: %d", pingAvatar); char voxelAvgPing[30]; @@ -2788,7 +2792,7 @@ void Application::displayStats() { } else { // longhand way sprintf(avatarPosition, "Position: %.1f, %.1f, %.1f", avatarPos.x, avatarPos.y, avatarPos.z); - } + } char avatarVelocity[30]; sprintf(avatarVelocity, "Velocity: %.1f", glm::length(_myAvatar->getVelocity())); char avatarBodyYaw[30]; @@ -2814,7 +2818,7 @@ void Application::displayStats() { verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarMixerStats, WHITE_TEXT); - + stringstream downloadStats; downloadStats << "Downloads: "; foreach (Resource* resource, ResourceCache::getLoadingRequests()) { @@ -2822,7 +2826,7 @@ void Application::displayStats() { downloadStats << roundf(resource->getProgress() * MAXIMUM_PERCENTAGE) << "% "; } downloadStats << "(" << ResourceCache::getPendingRequestCount() << " pending)"; - + verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, downloadStats.str().c_str(), WHITE_TEXT); } @@ -2842,7 +2846,7 @@ void Application::displayStats() { drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), WHITE_TEXT); voxelStats.str(""); - voxelStats << + voxelStats << "Geometry RAM: " << _voxels.getVoxelMemoryUsageRAM() / 1000000.f << "MB / " << "VBO: " << _voxels.getVoxelMemoryUsageVBO() / 1000000.f << "MB"; if (_voxels.hasVoxelMemoryUsageGPU()) { @@ -2894,7 +2898,7 @@ void Application::displayStats() { totalNodes += stats.getTotalElements(); if (_statsExpanded) { totalInternal += stats.getTotalInternal(); - totalLeaves += stats.getTotalLeaves(); + totalLeaves += stats.getTotalLeaves(); } } if (_statsExpanded) { @@ -2918,7 +2922,7 @@ void Application::displayStats() { QString packetsString = locale.toString((int)voxelPacketsToProcess); QString maxString = locale.toString((int)_recentMaxPackets); voxelStats << "Voxel Packets to Process: " << qPrintable(packetsString) - << " [Recent Max: " << qPrintable(maxString) << "]"; + << " [Recent Max: " << qPrintable(maxString) << "]"; verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), WHITE_TEXT); } @@ -3080,12 +3084,12 @@ void Application::renderRearViewMirror(const QRect& region, bool billboard) { _mirrorCamera.setFieldOfView(BILLBOARD_FIELD_OF_VIEW); // degees _mirrorCamera.setDistance(BILLBOARD_DISTANCE * _myAvatar->getScale()); _mirrorCamera.setTargetPosition(_myAvatar->getPosition()); - + } else if (_rearMirrorTools->getZoomLevel() == BODY) { _mirrorCamera.setFieldOfView(MIRROR_FIELD_OF_VIEW); // degrees _mirrorCamera.setDistance(MIRROR_REARVIEW_BODY_DISTANCE * _myAvatar->getScale()); _mirrorCamera.setTargetPosition(_myAvatar->getChestPosition()); - + } else { // HEAD zoom level _mirrorCamera.setFieldOfView(MIRROR_FIELD_OF_VIEW); // degrees _mirrorCamera.setDistance(MIRROR_REARVIEW_DISTANCE * _myAvatar->getScale()); @@ -3100,7 +3104,7 @@ void Application::renderRearViewMirror(const QRect& region, bool billboard) { } } _mirrorCamera.setAspectRatio((float)region.width() / region.height()); - + _mirrorCamera.setTargetRotation(_myAvatar->getWorldAlignedOrientation() * glm::quat(glm::vec3(0.0f, PI, 0.0f))); _mirrorCamera.update(1.0f/_fps); @@ -3145,7 +3149,7 @@ void Application::renderRearViewMirror(const QRect& region, bool billboard) { if (!billboard) { _rearMirrorTools->render(false); } - + // reset Viewport and projection matrix glViewport(0, 0, _glWidget->width(), _glWidget->height()); glDisable(GL_SCISSOR_TEST); @@ -3365,14 +3369,14 @@ void Application::setMenuShortcutsEnabled(bool enabled) { } void Application::updateWindowTitle(){ - + QString buildVersion = " (build " + applicationVersion() + ")"; NodeList* nodeList = NodeList::getInstance(); - + QString username = AccountManager::getInstance().getUsername(); QString title = QString() + (!username.isEmpty() ? username + " " : QString()) + nodeList->getSessionUUID().toString() + " @ " + nodeList->getDomainInfo().getHostname() + buildVersion; - + qDebug("Application title set to: %s", title.toStdString().c_str()); _window->setWindowTitle(title); } @@ -3387,7 +3391,7 @@ void Application::domainChanged(const QString& domainHostname) { _voxelServerJurisdictions.clear(); _octreeServerSceneStats.clear(); _particleServerJurisdictions.clear(); - + // reset the particle renderer _particles.clear(); @@ -3397,12 +3401,12 @@ void Application::domainChanged(const QString& domainHostname) { void Application::connectedToDomain(const QString& hostname) { AccountManager& accountManager = AccountManager::getInstance(); - + if (accountManager.isLoggedIn()) { // update our domain-server with the data-server we're logged in with - + QString domainPutJsonString = "{\"address\":{\"domain\":\"" + hostname + "\"}}"; - + accountManager.authenticatedRequest("/api/v1/users/address", QNetworkAccessManager::PutOperation, JSONCallbackParameters(), domainPutJsonString.toUtf8()); } @@ -3567,13 +3571,13 @@ void Application::loadScripts() { // loads all saved scripts QSettings* settings = new QSettings(this); int size = settings->beginReadArray("Settings"); - + for (int i = 0; i < size; ++i){ settings->setArrayIndex(i); QString string = settings->value("script").toString(); loadScript(string); } - + settings->endArray(); } @@ -3588,42 +3592,72 @@ void Application::saveScripts() { // saves all current running scripts QSettings* settings = new QSettings(this); settings->beginWriteArray("Settings"); - for (int i = 0; i < _activeScripts.size(); ++i){ + for (int i = 0; i < getRunningScripts().size(); ++i){ settings->setArrayIndex(i); - settings->setValue("script", _activeScripts.at(i)); + settings->setValue("script", getRunningScripts().at(i)); } - + settings->endArray(); } void Application::stopAllScripts() { // stops all current running scripts - QList scriptActions = Menu::getInstance()->getActiveScriptsMenu()->actions(); - foreach (QAction* scriptAction, scriptActions) { - scriptAction->activate(QAction::Trigger); - qDebug() << "stopping script..." << scriptAction->text(); + for (int i = 0; i < _scriptEnginesHash.size(); ++i) { + _scriptEnginesHash.values().at(i)->stop(); + qDebug() << "stopping script..." << getRunningScripts().at(i); } - _activeScripts.clear(); + _scriptEnginesHash.clear(); + _runningScriptsWidget->setRunningScripts(getRunningScripts()); +} + +void Application::stopScript(const QString &scriptName) +{ + _scriptEnginesHash.value(scriptName)->stop(); + qDebug() << "stopping script..." << scriptName; + _scriptEnginesHash.remove(scriptName); + _runningScriptsWidget->setRunningScripts(getRunningScripts()); } void Application::reloadAllScripts() { // remember all the current scripts so we can reload them - QStringList reloadList = _activeScripts; + QStringList reloadList = getRunningScripts(); // reloads all current running scripts - QList scriptActions = Menu::getInstance()->getActiveScriptsMenu()->actions(); - foreach (QAction* scriptAction, scriptActions) { - scriptAction->activate(QAction::Trigger); - qDebug() << "stopping script..." << scriptAction->text(); - } + stopAllScripts(); - // NOTE: we don't need to clear the _activeScripts list because that is handled on script shutdown. - foreach (QString scriptName, reloadList){ qDebug() << "reloading script..." << scriptName; loadScript(scriptName); } } +void Application::toggleRunningScriptsWidget() +{ + if (!_runningScriptsWidget->toggleViewAction()->isChecked()) { + _runningScriptsWidget->move(_window->geometry().topLeft().x(), _window->geometry().topLeft().y()); + _runningScriptsWidget->resize(0, _window->height()); + _runningScriptsWidget->toggleViewAction()->trigger(); + _runningScriptsWidget->grabKeyboard(); + + QPropertyAnimation* slideAnimation = new QPropertyAnimation(_runningScriptsWidget, "geometry", _runningScriptsWidget); + slideAnimation->setStartValue(_runningScriptsWidget->geometry()); + slideAnimation->setEndValue(QRect(_window->geometry().topLeft().x(), _window->geometry().topLeft().y(), + 310, _runningScriptsWidget->height())); + slideAnimation->setDuration(250); + slideAnimation->start(QAbstractAnimation::DeleteWhenStopped); + } else { + _runningScriptsWidget->releaseKeyboard(); + + QPropertyAnimation* slideAnimation = new QPropertyAnimation(_runningScriptsWidget, "geometry", _runningScriptsWidget); + slideAnimation->setStartValue(_runningScriptsWidget->geometry()); + slideAnimation->setEndValue(QRect(_window->geometry().topLeft().x(), _window->geometry().topLeft().y(), + 0, _runningScriptsWidget->height())); + slideAnimation->setDuration(250); + slideAnimation->start(QAbstractAnimation::DeleteWhenStopped); + + QTimer::singleShot(260, _runningScriptsWidget->toggleViewAction(), SLOT(trigger())); + } +} + void Application::uploadFST(bool isHead) { FstReader reader(isHead); if (reader.zip()) { @@ -3639,29 +3673,17 @@ void Application::uploadSkeleton() { uploadFST(false); } -void Application::removeScriptName(const QString& fileNameString) { - _activeScripts.removeOne(fileNameString); -} - -void Application::cleanupScriptMenuItem(const QString& scriptMenuName) { - Menu::getInstance()->removeAction(Menu::getInstance()->getActiveScriptsMenu(), scriptMenuName); -} - void Application::loadScript(const QString& scriptName) { // start the script on a new thread... - bool wantMenuItems = true; // tells the ScriptEngine object to add menu items for itself - ScriptEngine* scriptEngine = new ScriptEngine(QUrl(scriptName), wantMenuItems, &_controllerScriptingInterface); + ScriptEngine* scriptEngine = new ScriptEngine(QUrl(scriptName), &_controllerScriptingInterface); + _scriptEnginesHash.insert(scriptName, scriptEngine); if (!scriptEngine->hasScript()) { qDebug() << "Application::loadScript(), script failed to load..."; return; } - _activeScripts.append(scriptName); - - // add a stop menu item - Menu::getInstance()->addActionToQMenuAndActionHash(Menu::getInstance()->getActiveScriptsMenu(), - scriptEngine->getScriptMenuName(), 0, scriptEngine, SLOT(stop())); + _runningScriptsWidget->setRunningScripts(getRunningScripts()); // setup the packet senders and jurisdiction listeners of the script engine's scripting interfaces so // we can use the same ones from the application. @@ -3669,7 +3691,7 @@ void Application::loadScript(const QString& scriptName) { scriptEngine->getVoxelsScriptingInterface()->setVoxelTree(_voxels.getTree()); scriptEngine->getParticlesScriptingInterface()->setPacketSender(&_particleEditSender); scriptEngine->getParticlesScriptingInterface()->setParticleTree(_particles.getTree()); - + // hook our avatar object into this script engine scriptEngine->setAvatarData(_myAvatar, "MyAvatar"); // leave it as a MyAvatar class to expose thrust features @@ -3694,8 +3716,6 @@ void Application::loadScript(const QString& scriptName) { // when the thread is terminated, add both scriptEngine and thread to the deleteLater queue connect(scriptEngine, SIGNAL(finished(const QString&)), scriptEngine, SLOT(deleteLater())); connect(workerThread, SIGNAL(finished()), workerThread, SLOT(deleteLater())); - connect(scriptEngine, SIGNAL(finished(const QString&)), this, SLOT(removeScriptName(const QString&))); - connect(scriptEngine, SIGNAL(cleanupMenuItem(const QString&)), this, SLOT(cleanupScriptMenuItem(const QString&))); // when the application is about to quit, stop our script engine so it unwinds properly connect(this, SIGNAL(aboutToQuit()), scriptEngine, SLOT(stop())); @@ -3719,12 +3739,12 @@ void Application::loadDialog() { suggestedName = _previousScriptLocation; } - QString fileNameString = QFileDialog::getOpenFileName(_glWidget, tr("Open Script"), suggestedName, + QString fileNameString = QFileDialog::getOpenFileName(_glWidget, tr("Open Script"), suggestedName, tr("JavaScript Files (*.js)")); if (!fileNameString.isEmpty()) { _previousScriptLocation = fileNameString; } - + loadScript(fileNameString); } @@ -3735,7 +3755,7 @@ void Application::loadScriptURLDialog() { scriptURLDialog.setLabelText("Script:"); scriptURLDialog.setWindowFlags(Qt::Sheet); const float DIALOG_RATIO_OF_WINDOW = 0.30f; - scriptURLDialog.resize(scriptURLDialog.parentWidget()->size().width() * DIALOG_RATIO_OF_WINDOW, + scriptURLDialog.resize(scriptURLDialog.parentWidget()->size().width() * DIALOG_RATIO_OF_WINDOW, scriptURLDialog.size().height()); int dialogReturn = scriptURLDialog.exec(); @@ -3773,29 +3793,29 @@ void Application::checkVersion() { } void Application::parseVersionXml() { - + #ifdef Q_OS_WIN32 QString operatingSystem("win"); #endif - + #ifdef Q_OS_MAC QString operatingSystem("mac"); #endif - + #ifdef Q_OS_LINUX QString operatingSystem("ubuntu"); #endif - + QString releaseDate; QString releaseNotes; QString latestVersion; QUrl downloadUrl; QObject* sender = QObject::sender(); - + QXmlStreamReader xml(qobject_cast(sender)); while (!xml.atEnd() && !xml.hasError()) { QXmlStreamReader::TokenType token = xml.readNext(); - + if (token == QXmlStreamReader::StartElement) { if (xml.name() == "ReleaseDate") { xml.readNext(); diff --git a/interface/src/Application.h b/interface/src/Application.h index e12d0b307f..221a81478e 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -21,6 +21,7 @@ #include #include #include +#include #include #include @@ -65,6 +66,7 @@ #include "ui/LogDialog.h" #include "ui/UpdateDialog.h" #include "ui/overlays/Overlays.h" +#include "ui/RunningScriptsWidget.h" #include "voxels/VoxelFade.h" #include "voxels/VoxelHideShowThread.h" #include "voxels/VoxelImporter.h" @@ -112,7 +114,7 @@ public: ~Application(); void restoreSizeAndPosition(); - void loadScript(const QString& fileNameString); + void loadScript(const QString& fileNameString); void loadScripts(); void storeSizeAndPosition(); void clearScriptsBeforeRunning(); @@ -136,9 +138,9 @@ public: void wheelEvent(QWheelEvent* event); void dropEvent(QDropEvent *event); - + bool event(QEvent* event); - + void makeVoxel(glm::vec3 position, float scale, unsigned char red, @@ -226,6 +228,8 @@ public: void skipVersion(QString latestVersion); + QStringList getRunningScripts() { return _scriptEnginesHash.keys(); } + signals: /// Fired when we're simulating; allows external parties to hook in. @@ -233,10 +237,10 @@ signals: /// Fired when we're rendering in-world interface elements; allows external parties to hook in. void renderingInWorldInterface(); - + /// Fired when the import window is closed void importDone(); - + public slots: void domainChanged(const QString& domainHostname); void updateWindowTitle(); @@ -259,8 +263,10 @@ public slots: void toggleLogDialog(); void initAvatarAndViewFrustum(); void stopAllScripts(); + void stopScript(const QString& scriptName); void reloadAllScripts(); - + void toggleRunningScriptsWidget(); + void uploadFST(bool isHead); void uploadHead(); void uploadSkeleton(); @@ -268,24 +274,21 @@ public slots: private slots: void timer(); void idle(); - + void connectedToDomain(const QString& hostname); void setFullscreen(bool fullscreen); void setEnable3DTVMode(bool enable3DTVMode); void cameraMenuChanged(); - + glm::vec2 getScaledScreenPoint(glm::vec2 projectedPoint); void closeMirrorView(); void restoreMirrorView(); void shrinkMirrorView(); void resetSensors(); - - void parseVersionXml(); - void removeScriptName(const QString& fileNameString); - void cleanupScriptMenuItem(const QString& scriptMenuName); + void parseVersionXml(); private: void resetCamerasOnResizeGL(Camera& camera, int width, int height); @@ -355,7 +358,7 @@ private: bool _statsExpanded; BandwidthMeter _bandwidthMeter; - + QThread* _nodeThread; DatagramProcessor _datagramProcessor; @@ -374,7 +377,7 @@ private: timeval _lastTimeUpdated; bool _justStarted; Stars _stars; - + BuckyBalls _buckyBalls; VoxelSystem _voxels; @@ -409,7 +412,6 @@ private: Visage _visage; SixenseManager _sixenseManager; - QStringList _activeScripts; Camera _myCamera; // My view onto the world Camera _viewFrustumOffsetCamera; // The camera we use to sometimes show the view frustum from an offset mode @@ -493,10 +495,13 @@ private: void displayUpdateDialog(); bool shouldSkipVersion(QString latestVersion); void takeSnapshot(); - + TouchEvent _lastTouchEvent; - + Overlays _overlays; + + RunningScriptsWidget* _runningScriptsWidget; + QHash _scriptEnginesHash; }; #endif /* defined(__interface__Application__) */ diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 092f9090b0..4e2680944a 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -86,7 +86,7 @@ Menu::Menu() : _loginAction(NULL) { Application *appInstance = Application::getInstance(); - + QMenu* fileMenu = addMenu("File"); #ifdef Q_OS_MAC @@ -99,23 +99,24 @@ Menu::Menu() : #endif AccountManager& accountManager = AccountManager::getInstance(); - + _loginAction = addActionToQMenuAndActionHash(fileMenu, MenuOption::Logout); - + // call our toggle login function now so the menu option is setup properly toggleLoginMenuItem(); - + // connect to the appropriate slots of the AccountManager so that we can change the Login/Logout menu item connect(&accountManager, &AccountManager::accessTokenChanged, this, &Menu::toggleLoginMenuItem); connect(&accountManager, &AccountManager::logoutComplete, this, &Menu::toggleLoginMenuItem); addDisabledActionAndSeparator(fileMenu, "Scripts"); addActionToQMenuAndActionHash(fileMenu, MenuOption::LoadScript, Qt::CTRL | Qt::Key_O, appInstance, SLOT(loadDialog())); - addActionToQMenuAndActionHash(fileMenu, MenuOption::LoadScriptURL, + addActionToQMenuAndActionHash(fileMenu, MenuOption::LoadScriptURL, Qt::CTRL | Qt::SHIFT | Qt::Key_O, appInstance, SLOT(loadScriptURLDialog())); addActionToQMenuAndActionHash(fileMenu, MenuOption::StopAllScripts, 0, appInstance, SLOT(stopAllScripts())); addActionToQMenuAndActionHash(fileMenu, MenuOption::ReloadAllScripts, 0, appInstance, SLOT(reloadAllScripts())); - _activeScriptsMenu = fileMenu->addMenu("Running Scripts"); + addActionToQMenuAndActionHash(fileMenu, MenuOption::RunningScripts, Qt::CTRL | Qt::Key_J, + appInstance, SLOT(toggleRunningScriptsWidget())); addDisabledActionAndSeparator(fileMenu, "Go"); addActionToQMenuAndActionHash(fileMenu, @@ -147,7 +148,6 @@ Menu::Menu() : addDisabledActionAndSeparator(fileMenu, "Upload Avatar Model"); addActionToQMenuAndActionHash(fileMenu, MenuOption::UploadHead, 0, Application::getInstance(), SLOT(uploadHead())); addActionToQMenuAndActionHash(fileMenu, MenuOption::UploadSkeleton, 0, Application::getInstance(), SLOT(uploadSkeleton())); - addDisabledActionAndSeparator(fileMenu, "Settings"); addActionToQMenuAndActionHash(fileMenu, MenuOption::SettingsImport, 0, this, SLOT(importSettings())); addActionToQMenuAndActionHash(fileMenu, MenuOption::SettingsExport, 0, this, SLOT(exportSettings())); @@ -172,8 +172,8 @@ Menu::Menu() : addDisabledActionAndSeparator(editMenu, "Physics"); addCheckableActionToQMenuAndActionHash(editMenu, MenuOption::Gravity, Qt::SHIFT | Qt::Key_G, false); - - + + addAvatarCollisionSubMenu(editMenu); @@ -207,7 +207,7 @@ Menu::Menu() : addCheckableActionToQMenuAndActionHash(viewMenu, MenuOption::Mirror, Qt::SHIFT | Qt::Key_H, true); addCheckableActionToQMenuAndActionHash(viewMenu, MenuOption::FullscreenMirror, Qt::Key_H, false, appInstance, SLOT(cameraMenuChanged())); - + addCheckableActionToQMenuAndActionHash(viewMenu, MenuOption::Enable3DTVMode, 0, false, appInstance, @@ -334,16 +334,16 @@ Menu::Menu() : addCheckableActionToQMenuAndActionHash(renderDebugMenu, MenuOption::PipelineWarnings, Qt::CTRL | Qt::SHIFT | Qt::Key_P); addCheckableActionToQMenuAndActionHash(renderDebugMenu, MenuOption::SuppressShortTimings, Qt::CTRL | Qt::SHIFT | Qt::Key_S); - addCheckableActionToQMenuAndActionHash(renderDebugMenu, - MenuOption::CullSharedFaces, - Qt::CTRL | Qt::SHIFT | Qt::Key_C, + addCheckableActionToQMenuAndActionHash(renderDebugMenu, + MenuOption::CullSharedFaces, + Qt::CTRL | Qt::SHIFT | Qt::Key_C, false, appInstance->getVoxels(), SLOT(cullSharedFaces())); - addCheckableActionToQMenuAndActionHash(renderDebugMenu, - MenuOption::ShowCulledSharedFaces, - Qt::CTRL | Qt::SHIFT | Qt::Key_X, + addCheckableActionToQMenuAndActionHash(renderDebugMenu, + MenuOption::ShowCulledSharedFaces, + Qt::CTRL | Qt::SHIFT | Qt::Key_X, false, appInstance->getVoxels(), SLOT(showCulledSharedFaces())); @@ -367,14 +367,13 @@ Menu::Menu() : appInstance->getAudio(), SLOT(toggleToneInjection())); - addActionToQMenuAndActionHash(developerMenu, MenuOption::PasteToVoxel, Qt::CTRL | Qt::SHIFT | Qt::Key_V, this, SLOT(pasteToVoxel())); connect(appInstance->getAudio(), SIGNAL(muteToggled()), this, SLOT(audioMuteToggled())); - + #ifndef Q_OS_MAC QMenu* helpMenu = addMenu("Help"); QAction* helpAction = helpMenu->addAction(MenuOption::AboutApp); @@ -578,7 +577,7 @@ void Menu::addDisabledActionAndSeparator(QMenu* destinationMenu, const QString& QAction* separatorText = new QAction(actionName,destinationMenu); separatorText->setEnabled(false); destinationMenu->insertAction(actionBefore, separatorText); - + } else { destinationMenu->addSeparator(); (destinationMenu->addAction(actionName))->setEnabled(false); @@ -630,7 +629,7 @@ QAction* Menu::addCheckableActionToQMenuAndActionHash(QMenu* destinationMenu, const char* member, int menuItemLocation) { - QAction* action = addActionToQMenuAndActionHash(destinationMenu, actionName, shortcut, receiver, member, + QAction* action = addActionToQMenuAndActionHash(destinationMenu, actionName, shortcut, receiver, member, QAction::NoRole, menuItemLocation); action->setCheckable(true); action->setChecked(checked); @@ -684,40 +683,40 @@ const float DIALOG_RATIO_OF_WINDOW = 0.30f; void Menu::loginForCurrentDomain() { QDialog loginDialog(Application::getInstance()->getWindow()); loginDialog.setWindowTitle("Login"); - + QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom); loginDialog.setLayout(layout); loginDialog.setWindowFlags(Qt::Sheet); - + QFormLayout* form = new QFormLayout(); layout->addLayout(form, 1); - + QLineEdit* loginLineEdit = new QLineEdit(); loginLineEdit->setMinimumWidth(QLINE_MINIMUM_WIDTH); form->addRow("Login:", loginLineEdit); - + QLineEdit* passwordLineEdit = new QLineEdit(); passwordLineEdit->setMinimumWidth(QLINE_MINIMUM_WIDTH); passwordLineEdit->setEchoMode(QLineEdit::Password); form->addRow("Password:", passwordLineEdit); - + QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); loginDialog.connect(buttons, SIGNAL(accepted()), SLOT(accept())); loginDialog.connect(buttons, SIGNAL(rejected()), SLOT(reject())); layout->addWidget(buttons); - + int dialogReturn = loginDialog.exec(); - + if (dialogReturn == QDialog::Accepted && !loginLineEdit->text().isEmpty() && !passwordLineEdit->text().isEmpty()) { // attempt to get an access token given this username and password AccountManager::getInstance().requestAccessToken(loginLineEdit->text(), passwordLineEdit->text()); } - + sendFakeEnterEvent(); } void Menu::editPreferences() { - Application* applicationInstance = Application::getInstance(); + Application* applicationInstance = Application::getInstance(); ModelsBrowser headBrowser(Head); ModelsBrowser skeletonBrowser(Skeleton); @@ -725,14 +724,14 @@ void Menu::editPreferences() { QDialog dialog(applicationInstance->getWindow()); dialog.setWindowTitle("Interface Preferences"); - + QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom); dialog.setLayout(layout); - + QFormLayout* form = new QFormLayout(); layout->addLayout(form, 1); - + QHBoxLayout headModelLayout; QString faceURLString = applicationInstance->getAvatar()->getHead()->getFaceModel().getURL().toString(); QLineEdit headURLEdit(faceURLString); @@ -744,7 +743,7 @@ void Menu::editPreferences() { headModelLayout.addWidget(&headURLEdit); headModelLayout.addWidget(&headBrowseButton); form->addRow("Head URL:", &headModelLayout); - + QHBoxLayout skeletonModelLayout; QString skeletonURLString = applicationInstance->getAvatar()->getSkeletonModel().getURL().toString(); QLineEdit skeletonURLEdit(skeletonURLString); @@ -756,7 +755,7 @@ void Menu::editPreferences() { skeletonModelLayout.addWidget(&skeletonURLEdit); skeletonModelLayout.addWidget(&SkeletonBrowseButton); form->addRow("Skeleton URL:", &skeletonModelLayout); - + QString displayNameString = applicationInstance->getAvatar()->getDisplayName(); QLineEdit* displayNameEdit = new QLineEdit(displayNameString); @@ -841,12 +840,12 @@ void Menu::editPreferences() { } QString displayNameStr(displayNameEdit->text()); - + if (displayNameStr != displayNameString) { applicationInstance->getAvatar()->setDisplayName(displayNameStr); shouldDispatchIdentityPacket = true; } - + if (shouldDispatchIdentityPacket) { applicationInstance->getAvatar()->sendIdentityPacket(); } @@ -879,10 +878,10 @@ void Menu::editPreferences() { void Menu::goToDomain(const QString newDomain) { if (NodeList::getInstance()->getDomainInfo().getHostname() != newDomain) { - + // send a node kill request, indicating to other clients that they should play the "disappeared" effect Application::getInstance()->getAvatar()->sendKillAvatar(); - + // give our nodeList the new domain-server hostname NodeList::getInstance()->getDomainInfo().setHostname(newDomain); } @@ -912,7 +911,7 @@ void Menu::goToDomainDialog() { // the user input a new hostname, use that newHostname = domainDialog.textValue(); } - + goToDomain(newHostname); } @@ -928,7 +927,7 @@ bool Menu::goToDestination(QString destination) { } void Menu::goTo() { - + QInputDialog gotoDialog(Application::getInstance()->getWindow()); gotoDialog.setWindowTitle("Go to"); gotoDialog.setLabelText("Destination:"); @@ -936,7 +935,7 @@ void Menu::goTo() { gotoDialog.setTextValue(destination); gotoDialog.setWindowFlags(Qt::Sheet); gotoDialog.resize(gotoDialog.parentWidget()->size().width() * DIALOG_RATIO_OF_WINDOW, gotoDialog.size().height()); - + int dialogReturn = gotoDialog.exec(); if (dialogReturn == QDialog::Accepted && !gotoDialog.textValue().isEmpty()) { goToUser(gotoDialog.textValue()); @@ -1085,7 +1084,7 @@ void Menu::toggleLoginMenuItem() { AccountManager& accountManager = AccountManager::getInstance(); disconnect(_loginAction, 0, 0, 0); - + if (accountManager.isLoggedIn()) { // change the menu item to logout _loginAction->setText("Logout " + accountManager.getUsername()); @@ -1093,7 +1092,7 @@ void Menu::toggleLoginMenuItem() { } else { // change the menu item to login _loginAction->setText("Login"); - + connect(_loginAction, &QAction::triggered, this, &Menu::loginForCurrentDomain); } } @@ -1200,7 +1199,7 @@ QString Menu::getLODFeedbackText() { } break; } - // distance feedback + // distance feedback float voxelSizeScale = getVoxelSizeScale(); float relativeToDefault = voxelSizeScale / DEFAULT_OCTREE_SIZE_SCALE; QString result; @@ -1215,7 +1214,7 @@ QString Menu::getLODFeedbackText() { } void Menu::autoAdjustLOD(float currentFPS) { - // NOTE: our first ~100 samples at app startup are completely all over the place, and we don't + // NOTE: our first ~100 samples at app startup are completely all over the place, and we don't // really want to count them in our average, so we will ignore the real frame rates and stuff // our moving average with simulated good data const int IGNORE_THESE_SAMPLES = 100; @@ -1227,7 +1226,7 @@ void Menu::autoAdjustLOD(float currentFPS) { _fastFPSAverage.updateAverage(currentFPS); quint64 now = usecTimestampNow(); - + const quint64 ADJUST_AVATAR_LOD_DOWN_DELAY = 1000 * 1000; if (_fastFPSAverage.getAverage() < ADJUST_LOD_DOWN_FPS) { if (now - _lastAvatarDetailDrop > ADJUST_AVATAR_LOD_DOWN_DELAY) { @@ -1246,11 +1245,11 @@ void Menu::autoAdjustLOD(float currentFPS) { _avatarLODDistanceMultiplier = qMax(MINIMUM_DISTANCE_MULTIPLIER, _avatarLODDistanceMultiplier - DISTANCE_DECREASE_RATE); } - + bool changed = false; quint64 elapsed = now - _lastAdjust; - if (elapsed > ADJUST_LOD_DOWN_DELAY && _fpsAverage.getAverage() < ADJUST_LOD_DOWN_FPS + if (elapsed > ADJUST_LOD_DOWN_DELAY && _fpsAverage.getAverage() < ADJUST_LOD_DOWN_FPS && _voxelSizeScale > ADJUST_LOD_MIN_SIZE_SCALE) { _voxelSizeScale *= ADJUST_LOD_DOWN_BY; @@ -1263,7 +1262,7 @@ void Menu::autoAdjustLOD(float currentFPS) { << "_voxelSizeScale=" << _voxelSizeScale; } - if (elapsed > ADJUST_LOD_UP_DELAY && _fpsAverage.getAverage() > ADJUST_LOD_UP_FPS + if (elapsed > ADJUST_LOD_UP_DELAY && _fpsAverage.getAverage() > ADJUST_LOD_UP_FPS && _voxelSizeScale < ADJUST_LOD_MAX_SIZE_SCALE) { _voxelSizeScale *= ADJUST_LOD_UP_BY; if (_voxelSizeScale > ADJUST_LOD_MAX_SIZE_SCALE) { @@ -1274,7 +1273,7 @@ void Menu::autoAdjustLOD(float currentFPS) { qDebug() << "adjusting LOD up... average fps for last approximately 5 seconds=" << _fpsAverage.getAverage() << "_voxelSizeScale=" << _voxelSizeScale; } - + if (changed) { if (_lodToolsDialog) { _lodToolsDialog->reloadSliders(); @@ -1352,13 +1351,13 @@ void Menu::addAvatarCollisionSubMenu(QMenu* overMenu) { Application* appInstance = Application::getInstance(); QObject* avatar = appInstance->getAvatar(); - addCheckableActionToQMenuAndActionHash(subMenu, MenuOption::CollideWithEnvironment, + addCheckableActionToQMenuAndActionHash(subMenu, MenuOption::CollideWithEnvironment, 0, false, avatar, SLOT(updateCollisionFlags())); - addCheckableActionToQMenuAndActionHash(subMenu, MenuOption::CollideWithAvatars, + addCheckableActionToQMenuAndActionHash(subMenu, MenuOption::CollideWithAvatars, 0, true, avatar, SLOT(updateCollisionFlags())); - addCheckableActionToQMenuAndActionHash(subMenu, MenuOption::CollideWithVoxels, + addCheckableActionToQMenuAndActionHash(subMenu, MenuOption::CollideWithVoxels, 0, false, avatar, SLOT(updateCollisionFlags())); - addCheckableActionToQMenuAndActionHash(subMenu, MenuOption::CollideWithParticles, + addCheckableActionToQMenuAndActionHash(subMenu, MenuOption::CollideWithParticles, 0, true, avatar, SLOT(updateCollisionFlags())); } @@ -1367,9 +1366,9 @@ QAction* Menu::getActionFromName(const QString& menuName, QMenu* menu) { if (menu) { menuActions = menu->actions(); } else { - menuActions = actions(); + menuActions = actions(); } - + foreach (QAction* menuAction, menuActions) { if (menuName == menuAction->text()) { return menuAction; @@ -1476,7 +1475,7 @@ QMenu* Menu::addMenu(const QString& menuName) { void Menu::removeMenu(const QString& menuName) { QAction* action = getMenuAction(menuName); - + // only proceed if the menu actually exists if (action) { QString finalMenuPart; @@ -1528,7 +1527,7 @@ void Menu::addMenuItem(const MenuItemProperties& properties) { if (!properties.shortcutKeySequence.isEmpty()) { shortcut = new QShortcut(properties.shortcutKeySequence, this); } - + // check for positioning requests int requestedPosition = properties.position; if (requestedPosition == UNSPECIFIED_POSITION && !properties.beforeItem.isEmpty()) { @@ -1542,13 +1541,13 @@ void Menu::addMenuItem(const MenuItemProperties& properties) { requestedPosition = afterPosition + 1; } } - + QAction* menuItemAction = NULL; if (properties.isSeparator) { addDisabledActionAndSeparator(menuObj, properties.menuItemName, requestedPosition); } else if (properties.isCheckable) { menuItemAction = addCheckableActionToQMenuAndActionHash(menuObj, properties.menuItemName, - properties.shortcutKeySequence, properties.isChecked, + properties.shortcutKeySequence, properties.isChecked, MenuScriptingInterface::getInstance(), SLOT(menuItemTriggered()), requestedPosition); } else { menuItemAction = addActionToQMenuAndActionHash(menuObj, properties.menuItemName, properties.shortcutKeySequence, diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 55eeff6498..b54266f915 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -95,8 +95,6 @@ public: // User Tweakable PPS from Voxel Server int getMaxVoxelPacketsPerSecond() const { return _maxVoxelPacketsPerSecond; } - QMenu* getActiveScriptsMenu() { return _activeScriptsMenu;} - QAction* addActionToQMenuAndActionHash(QMenu* destinationMenu, const QString& actionName, const QKeySequence& shortcut = 0, @@ -124,7 +122,7 @@ public slots: void goTo(); void goToUser(const QString& user); void pasteToVoxel(); - + void toggleLoginMenuItem(); QMenu* addMenu(const QString& menuName); @@ -166,7 +164,7 @@ private: void scanMenu(QMenu* menu, settingsAction modifySetting, QSettings* set); /// helper method to have separators with labels that are also compatible with OS X - void addDisabledActionAndSeparator(QMenu* destinationMenu, const QString& actionName, + void addDisabledActionAndSeparator(QMenu* destinationMenu, const QString& actionName, int menuItemLocation = UNSPECIFIED_POSITION); QAction* addCheckableActionToQMenuAndActionHash(QMenu* destinationMenu, @@ -189,7 +187,7 @@ private: int findPositionOfMenuItem(QMenu* menu, const QString& searchMenuItem); int positionBeforeSeparatorIfNeeded(QMenu* menu, int requestedPosition); QMenu* getMenu(const QString& menuName); - + QHash _actionHash; int _audioJitterBufferSamples; /// number of extra samples to wait before starting audio playback @@ -208,7 +206,6 @@ private: int _boundaryLevelAdjust; QAction* _useVoxelShader; int _maxVoxelPacketsPerSecond; - QMenu* _activeScriptsMenu; QString replaceLastOccurrence(QChar search, QChar replace, QString string); quint64 _lastAdjust; quint64 _lastAvatarDetailDrop; @@ -292,6 +289,7 @@ namespace MenuOption { const QString RenderHeadCollisionShapes = "Head Collision Shapes"; const QString RenderBoundingCollisionShapes = "Bounding Collision Shapes"; const QString ResetAvatarSize = "Reset Avatar Size"; + const QString RunningScripts = "Running Scripts"; const QString RunTimingTests = "Run Timing Tests"; const QString SettingsImport = "Import Settings"; const QString Shadows = "Shadows"; diff --git a/interface/src/ui/RunningScriptsWidget.cpp b/interface/src/ui/RunningScriptsWidget.cpp new file mode 100644 index 0000000000..2238cab2df --- /dev/null +++ b/interface/src/ui/RunningScriptsWidget.cpp @@ -0,0 +1,203 @@ +// +// RunningScripts.cpp +// interface +// +// Created by Mohammed Nafees on 03/28/2014. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. + +#include "ui_runningScriptsWidget.h" +#include "RunningScriptsWidget.h" + +#include +#include + +#include "Application.h" + +RunningScriptsWidget::RunningScriptsWidget(QDockWidget *parent) : + QDockWidget(parent), + ui(new Ui::RunningScriptsWidget) +{ + ui->setupUi(this); + + // remove the title bar (see the Qt docs on setTitleBarWidget) + setTitleBarWidget(new QWidget()); + + ui->runningScriptsTableWidget->setColumnCount(2); + ui->runningScriptsTableWidget->verticalHeader()->setVisible(false); + ui->runningScriptsTableWidget->horizontalHeader()->setVisible(false); + ui->runningScriptsTableWidget->setSelectionMode(QAbstractItemView::NoSelection); + ui->runningScriptsTableWidget->setShowGrid(false); + ui->runningScriptsTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); + ui->runningScriptsTableWidget->setColumnWidth(0, 235); + ui->runningScriptsTableWidget->setColumnWidth(1, 25); + connect(ui->runningScriptsTableWidget, &QTableWidget::cellClicked, this, &RunningScriptsWidget::stopScript); + + ui->recentlyLoadedScriptsTableWidget->setColumnCount(2); + ui->recentlyLoadedScriptsTableWidget->verticalHeader()->setVisible(false); + ui->recentlyLoadedScriptsTableWidget->horizontalHeader()->setVisible(false); + ui->recentlyLoadedScriptsTableWidget->setSelectionMode(QAbstractItemView::NoSelection); + ui->recentlyLoadedScriptsTableWidget->setShowGrid(false); + ui->recentlyLoadedScriptsTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); + ui->recentlyLoadedScriptsTableWidget->setColumnWidth(0, 25); + ui->recentlyLoadedScriptsTableWidget->setColumnWidth(1, 235); + connect(ui->recentlyLoadedScriptsTableWidget, &QTableWidget::cellClicked, + this, &RunningScriptsWidget::loadScript); + + connect(ui->hideWidgetButton, &QPushButton::clicked, + Application::getInstance(), &Application::toggleRunningScriptsWidget); + connect(ui->reloadAllButton, &QPushButton::clicked, + Application::getInstance(), &Application::reloadAllScripts); + connect(ui->stopAllButton, &QPushButton::clicked, + this, &RunningScriptsWidget::allScriptsStopped); +} + +RunningScriptsWidget::~RunningScriptsWidget() +{ + delete ui; +} + +void RunningScriptsWidget::setRunningScripts(const QStringList& list) +{ + ui->runningScriptsTableWidget->setRowCount(list.size()); + + ui->noRunningScriptsLabel->setVisible(list.isEmpty()); + ui->currentlyRunningLabel->setVisible(!list.isEmpty()); + ui->line1->setVisible(!list.isEmpty()); + ui->runningScriptsTableWidget->setVisible(!list.isEmpty()); + ui->reloadAllButton->setVisible(!list.isEmpty()); + ui->stopAllButton->setVisible(!list.isEmpty()); + + for (int i = 0; i < list.size(); ++i) { + QTableWidgetItem *scriptName = new QTableWidgetItem; + scriptName->setText(list.at(i)); + scriptName->setToolTip(list.at(i)); + scriptName->setTextAlignment(Qt::AlignCenter); + QTableWidgetItem *closeIcon = new QTableWidgetItem; + closeIcon->setIcon(QIcon(":/images/kill-script.svg")); + + ui->runningScriptsTableWidget->setItem(i, 0, scriptName); + ui->runningScriptsTableWidget->setItem(i, 1, closeIcon); + } + + createRecentlyLoadedScriptsTable(); +} + +void RunningScriptsWidget::keyPressEvent(QKeyEvent *e) +{ + switch(e->key()) { + case Qt::Key_Escape: + Application::getInstance()->toggleRunningScriptsWidget(); + break; + + case Qt::Key_1: + if (_recentlyLoadedScripts.size() > 0) { + Application::getInstance()->loadScript(_recentlyLoadedScripts.at(0)); + } + break; + + case Qt::Key_2: + if (_recentlyLoadedScripts.size() > 0 && _recentlyLoadedScripts.size() >= 2) { + Application::getInstance()->loadScript(_recentlyLoadedScripts.at(1)); + } + break; + + case Qt::Key_3: + if (_recentlyLoadedScripts.size() > 0 && _recentlyLoadedScripts.size() >= 3) { + Application::getInstance()->loadScript(_recentlyLoadedScripts.at(2)); + } + break; + + case Qt::Key_4: + if (_recentlyLoadedScripts.size() > 0 && _recentlyLoadedScripts.size() >= 4) { + Application::getInstance()->loadScript(_recentlyLoadedScripts.at(3)); + } + break; + case Qt::Key_5: + if (_recentlyLoadedScripts.size() > 0 && _recentlyLoadedScripts.size() >= 5) { + Application::getInstance()->loadScript(_recentlyLoadedScripts.at(4)); + } + break; + + case Qt::Key_6: + if (_recentlyLoadedScripts.size() > 0 && _recentlyLoadedScripts.size() >= 6) { + Application::getInstance()->loadScript(_recentlyLoadedScripts.at(5)); + } + break; + + case Qt::Key_7: + if (_recentlyLoadedScripts.size() > 0 && _recentlyLoadedScripts.size() >= 7) { + Application::getInstance()->loadScript(_recentlyLoadedScripts.at(6)); + } + break; + case Qt::Key_8: + if (_recentlyLoadedScripts.size() > 0 && _recentlyLoadedScripts.size() >= 8) { + Application::getInstance()->loadScript(_recentlyLoadedScripts.at(7)); + } + break; + + case Qt::Key_9: + if (_recentlyLoadedScripts.size() > 0 && _recentlyLoadedScripts.size() >= 9) { + Application::getInstance()->loadScript(_recentlyLoadedScripts.at(8)); + } + break; + + default: + break; + } +} + +void RunningScriptsWidget::stopScript(int row, int column) +{ + if (column == 1) { // make sure the user has clicked on the close icon + _lastStoppedScript = ui->runningScriptsTableWidget->item(row, 0)->text(); + emit stopScriptName(ui->runningScriptsTableWidget->item(row, 0)->text()); + } +} + +void RunningScriptsWidget::loadScript(int row, int column) +{ + Application::getInstance()->loadScript(ui->recentlyLoadedScriptsTableWidget->item(row, column)->text()); +} + +void RunningScriptsWidget::allScriptsStopped() +{ + QStringList list = Application::getInstance()->getRunningScripts(); + for (int i = 0; i < list.size(); ++i) { + _recentlyLoadedScripts.prepend(list.at(i)); + } + + Application::getInstance()->stopAllScripts(); +} + +void RunningScriptsWidget::createRecentlyLoadedScriptsTable() +{ + if (!_recentlyLoadedScripts.contains(_lastStoppedScript) && !_lastStoppedScript.isEmpty()) { + _recentlyLoadedScripts.prepend(_lastStoppedScript); + _lastStoppedScript = ""; + } + + for (int i = 0; i < _recentlyLoadedScripts.size(); ++i) { + if (Application::getInstance()->getRunningScripts().contains(_recentlyLoadedScripts.at(i))) { + _recentlyLoadedScripts.removeOne(_recentlyLoadedScripts.at(i)); + } + } + + ui->recentlyLoadedLabel->setVisible(!_recentlyLoadedScripts.isEmpty()); + ui->line2->setVisible(!_recentlyLoadedScripts.isEmpty()); + ui->recentlyLoadedScriptsTableWidget->setVisible(!_recentlyLoadedScripts.isEmpty()); + ui->recentlyLoadedInstruction->setVisible(!_recentlyLoadedScripts.isEmpty()); + + int limit = _recentlyLoadedScripts.size() > 9 ? 9 : _recentlyLoadedScripts.size(); + ui->recentlyLoadedScriptsTableWidget->setRowCount(limit); + for (int i = 0; i < limit; ++i) { + QTableWidgetItem *scriptName = new QTableWidgetItem; + scriptName->setText(_recentlyLoadedScripts.at(i)); + scriptName->setToolTip(_recentlyLoadedScripts.at(i)); + scriptName->setTextAlignment(Qt::AlignCenter); + QTableWidgetItem *number = new QTableWidgetItem; + number->setText(QString::number(i+1) + "."); + + ui->recentlyLoadedScriptsTableWidget->setItem(i, 0, number); + ui->recentlyLoadedScriptsTableWidget->setItem(i, 1, scriptName); + } +} diff --git a/interface/src/ui/RunningScriptsWidget.h b/interface/src/ui/RunningScriptsWidget.h new file mode 100644 index 0000000000..d92927347f --- /dev/null +++ b/interface/src/ui/RunningScriptsWidget.h @@ -0,0 +1,46 @@ +// +// RunningScripts.h +// interface +// +// Created by Mohammed Nafees on 03/28/2014. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. + +#ifndef __hifi__RunningScriptsWidget__ +#define __hifi__RunningScriptsWidget__ + +// Qt +#include + +namespace Ui { + class RunningScriptsWidget; +} + +class RunningScriptsWidget : public QDockWidget +{ + Q_OBJECT +public: + explicit RunningScriptsWidget(QDockWidget *parent = 0); + ~RunningScriptsWidget(); + + void setRunningScripts(const QStringList& list); + +signals: + void stopScriptName(const QString& name); + +protected: + void keyPressEvent(QKeyEvent *e); + +private slots: + void stopScript(int row, int column); + void loadScript(int row, int column); + void allScriptsStopped(); + +private: + Ui::RunningScriptsWidget *ui; + QStringList _recentlyLoadedScripts; + QString _lastStoppedScript; + + void createRecentlyLoadedScriptsTable(); +}; + +#endif /* defined(__hifi__RunningScriptsWidget__) */ diff --git a/interface/ui/runningScriptsWidget.ui b/interface/ui/runningScriptsWidget.ui new file mode 100644 index 0000000000..9494d4ed09 --- /dev/null +++ b/interface/ui/runningScriptsWidget.ui @@ -0,0 +1,248 @@ + + + RunningScriptsWidget + + + + 0 + 0 + 310 + 651 + + + + Form + + + background: #f7f7f7; +font-family: Helvetica, Arial, "DejaVu Sans"; + + + + + 20 + 10 + 221 + 31 + + + + color: #0e7077; + + + <html><head/><body><p><span style=" font-size:18pt;">Running Scripts</span></p></body></html> + + + + + + 20 + 40 + 301 + 20 + + + + color: #0e7077; + + + <html><head/><body><p><span style=" font-weight:600;">Currently running</span></p></body></html> + + + + + + 40 + 230 + 111 + 31 + + + + PointingHandCursor + + + background: #0e7077; +color: #fff; +border-radius: 6px; + + + Reload All + + + + :/images/reload.svg:/images/reload.svg + + + + + + 160 + 230 + 101 + 31 + + + + PointingHandCursor + + + background: #0e7077; +color: #fff; +border-radius: 6px; + + + Stop All + + + + :/images/stop.svg:/images/stop.svg + + + + + + 20 + 280 + 301 + 20 + + + + color: #0e7077; + + + <html><head/><body><p><span style=" font-weight:600;">Recently loaded</span></p></body></html> + + + + + + 20 + 300 + 271 + 8 + + + + + + + Qt::Horizontal + + + + + + 20 + 590 + 271 + 41 + + + + color: #95a5a6; + + + (click a script or use the 1-9 keys to load and run it) + + + true + + + + + + 270 + 10 + 31 + 31 + + + + PointingHandCursor + + + + + + + :/images/close.svg:/images/close.svg + + + + 20 + 20 + + + + true + + + + + + 20 + 70 + 271 + 141 + + + + background: transparent; + + + + + + 20 + 60 + 271 + 8 + + + + + + + Qt::Horizontal + + + + + + 20 + 310 + 271 + 281 + + + + background: transparent; + + + + + + 20 + 40 + 271 + 51 + + + + font: 14px; + + + There are no scripts currently running. + + + Qt::AlignCenter + + + + + + + + diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index 1f1eab6baf..7572638a30 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -29,7 +29,6 @@ #include "LocalVoxels.h" #include "ScriptEngine.h" -int ScriptEngine::_scriptNumber = 1; VoxelsScriptingInterface ScriptEngine::_voxelsScriptingInterface; ParticlesScriptingInterface ScriptEngine::_particlesScriptingInterface; @@ -41,7 +40,7 @@ static QScriptValue soundConstructor(QScriptContext* context, QScriptEngine* eng } -ScriptEngine::ScriptEngine(const QString& scriptContents, bool wantMenuItems, const QString& fileNameString, +ScriptEngine::ScriptEngine(const QString& scriptContents, const QString& fileNameString, AbstractControllerScriptingInterface* controllerScriptingInterface) : _scriptContents(scriptContents), @@ -58,26 +57,15 @@ ScriptEngine::ScriptEngine(const QString& scriptContents, bool wantMenuItems, co _numAvatarSoundSentBytes(0), _controllerScriptingInterface(controllerScriptingInterface), _avatarData(NULL), - _wantMenuItems(wantMenuItems), - _scriptMenuName(), + _scriptName(), _fileNameString(fileNameString), _quatLibrary(), _vec3Library() { - // some clients will use these menu features - if (!fileNameString.isEmpty()) { - _scriptMenuName = "Stop "; - _scriptMenuName.append(qPrintable(fileNameString)); - _scriptMenuName.append(QString(" [%1]").arg(_scriptNumber)); - } else { - _scriptMenuName = "Stop Script "; - _scriptMenuName.append(_scriptNumber); - } - _scriptNumber++; } -ScriptEngine::ScriptEngine(const QUrl& scriptURL, bool wantMenuItems, - AbstractControllerScriptingInterface* controllerScriptingInterface) : +ScriptEngine::ScriptEngine(const QUrl& scriptURL, + AbstractControllerScriptingInterface* controllerScriptingInterface) : _scriptContents(), _isFinished(false), _isRunning(false), @@ -92,32 +80,21 @@ ScriptEngine::ScriptEngine(const QUrl& scriptURL, bool wantMenuItems, _numAvatarSoundSentBytes(0), _controllerScriptingInterface(controllerScriptingInterface), _avatarData(NULL), - _wantMenuItems(wantMenuItems), - _scriptMenuName(), + _scriptName(), _fileNameString(), _quatLibrary(), _vec3Library() { QString scriptURLString = scriptURL.toString(); _fileNameString = scriptURLString; - // some clients will use these menu features - if (!scriptURLString.isEmpty()) { - _scriptMenuName = "Stop "; - _scriptMenuName.append(qPrintable(scriptURLString)); - _scriptMenuName.append(QString(" [%1]").arg(_scriptNumber)); - } else { - _scriptMenuName = "Stop Script "; - _scriptMenuName.append(_scriptNumber); - } - _scriptNumber++; - + QUrl url(scriptURL); - + // if the scheme is empty, maybe they typed in a file, let's try if (url.scheme().isEmpty()) { url = QUrl::fromLocalFile(scriptURLString); } - + // ok, let's see if it's valid... and if so, load it if (url.isValid()) { if (url.scheme() == "file") { @@ -144,16 +121,16 @@ ScriptEngine::ScriptEngine(const QUrl& scriptURL, bool wantMenuItems, void ScriptEngine::setIsAvatar(bool isAvatar) { _isAvatar = isAvatar; - + if (_isAvatar && !_avatarIdentityTimer) { // set up the avatar timers _avatarIdentityTimer = new QTimer(this); _avatarBillboardTimer = new QTimer(this); - + // connect our slot connect(_avatarIdentityTimer, &QTimer::timeout, this, &ScriptEngine::sendAvatarIdentityPacket); connect(_avatarBillboardTimer, &QTimer::timeout, this, &ScriptEngine::sendAvatarBillboardPacket); - + // start the timers _avatarIdentityTimer->start(AVATAR_IDENTITY_PACKET_SEND_INTERVAL_MSECS); _avatarBillboardTimer->start(AVATAR_BILLBOARD_PACKET_SEND_INTERVAL_MSECS); @@ -162,20 +139,14 @@ void ScriptEngine::setIsAvatar(bool isAvatar) { void ScriptEngine::setAvatarData(AvatarData* avatarData, const QString& objectName) { _avatarData = avatarData; - + // remove the old Avatar property, if it exists _engine.globalObject().setProperty(objectName, QScriptValue()); - + // give the script engine the new Avatar script property registerGlobalObject(objectName, _avatarData); } -void ScriptEngine::cleanupMenuItems() { - if (_wantMenuItems) { - emit cleanupMenuItem(_scriptMenuName); - } -} - bool ScriptEngine::setScriptContents(const QString& scriptContents, const QString& fileNameString) { if (_isRunning) { return false; @@ -203,7 +174,7 @@ void ScriptEngine::init() { registerVoxelMetaTypes(&_engine); registerEventTypes(&_engine); registerMenuItemProperties(&_engine); - + qScriptRegisterMetaType(&_engine, ParticlePropertiesToScriptValue, ParticlePropertiesFromScriptValue); qScriptRegisterMetaType(&_engine, ParticleIDtoScriptValue, ParticleIDfromScriptValue); qScriptRegisterSequenceMetaType >(&_engine); @@ -216,7 +187,7 @@ void ScriptEngine::init() { QScriptValue injectionOptionValue = _engine.scriptValueFromQMetaObject(); _engine.globalObject().setProperty("AudioInjectionOptions", injectionOptionValue); - + QScriptValue localVoxelsValue = _engine.scriptValueFromQMetaObject(); _engine.globalObject().setProperty("LocalVoxels", localVoxelsValue); @@ -285,9 +256,9 @@ void ScriptEngine::run() { gettimeofday(&startTime, NULL); int thisFrame = 0; - + NodeList* nodeList = NodeList::getInstance(); - + qint64 lastUpdate = usecTimestampNow(); while (!_isFinished) { @@ -325,36 +296,36 @@ void ScriptEngine::run() { _particlesScriptingInterface.getParticlePacketSender()->process(); } } - + if (_isAvatar && _avatarData) { - + const int SCRIPT_AUDIO_BUFFER_SAMPLES = floor(((SCRIPT_DATA_CALLBACK_USECS * SAMPLE_RATE) / (1000 * 1000)) + 0.5); const int SCRIPT_AUDIO_BUFFER_BYTES = SCRIPT_AUDIO_BUFFER_SAMPLES * sizeof(int16_t); - + QByteArray avatarPacket = byteArrayWithPopulatedHeader(PacketTypeAvatarData); avatarPacket.append(_avatarData->toByteArray()); - + nodeList->broadcastToNodes(avatarPacket, NodeSet() << NodeType::AvatarMixer); - + if (_isListeningToAudioStream || _avatarSound) { // if we have an avatar audio stream then send it out to our audio-mixer bool silentFrame = true; - + int16_t numAvailableSamples = SCRIPT_AUDIO_BUFFER_SAMPLES; const int16_t* nextSoundOutput = NULL; - + if (_avatarSound) { - + const QByteArray& soundByteArray = _avatarSound->getByteArray(); nextSoundOutput = reinterpret_cast(soundByteArray.data() + _numAvatarSoundSentBytes); - + int numAvailableBytes = (soundByteArray.size() - _numAvatarSoundSentBytes) > SCRIPT_AUDIO_BUFFER_BYTES ? SCRIPT_AUDIO_BUFFER_BYTES : soundByteArray.size() - _numAvatarSoundSentBytes; numAvailableSamples = numAvailableBytes / sizeof(int16_t); - - + + // check if the all of the _numAvatarAudioBufferSamples to be sent are silence for (int i = 0; i < numAvailableSamples; ++i) { if (nextSoundOutput[i] != 0) { @@ -362,7 +333,7 @@ void ScriptEngine::run() { break; } } - + _numAvatarSoundSentBytes += numAvailableBytes; if (_numAvatarSoundSentBytes == soundByteArray.size()) { // we're done with this sound object - so set our pointer back to NULL @@ -371,24 +342,24 @@ void ScriptEngine::run() { _numAvatarSoundSentBytes = 0; } } - + QByteArray audioPacket = byteArrayWithPopulatedHeader(silentFrame ? PacketTypeSilentAudioFrame : PacketTypeMicrophoneAudioNoEcho); - + QDataStream packetStream(&audioPacket, QIODevice::Append); - + // use the orientation and position of this avatar for the source of this audio packetStream.writeRawData(reinterpret_cast(&_avatarData->getPosition()), sizeof(glm::vec3)); glm::quat headOrientation = _avatarData->getHeadOrientation(); packetStream.writeRawData(reinterpret_cast(&headOrientation), sizeof(glm::quat)); - + if (silentFrame) { if (!_isListeningToAudioStream) { // if we have a silent frame and we're not listening then just send nothing and break out of here break; } - + // write the number of silent samples so the audio-mixer can uphold timing packetStream.writeRawData(reinterpret_cast(&SCRIPT_AUDIO_BUFFER_SAMPLES), sizeof(int16_t)); } else if (nextSoundOutput) { @@ -396,7 +367,7 @@ void ScriptEngine::run() { packetStream.writeRawData(reinterpret_cast(nextSoundOutput), numAvailableSamples * sizeof(int16_t)); } - + nodeList->broadcastToNodes(audioPacket, NodeSet() << NodeType::AudioMixer); } } @@ -412,10 +383,10 @@ void ScriptEngine::run() { } } emit scriptEnding(); - + // kill the avatar identity timer delete _avatarIdentityTimer; - + if (_voxelsScriptingInterface.getVoxelPacketSender()->serversExist()) { // release the queue of edit voxel messages. _voxelsScriptingInterface.getVoxelPacketSender()->releaseQueuedMessages(); @@ -435,8 +406,6 @@ void ScriptEngine::run() { _particlesScriptingInterface.getParticlePacketSender()->process(); } } - - cleanupMenuItems(); // If we were on a thread, then wait till it's done if (thread()) { @@ -444,7 +413,7 @@ void ScriptEngine::run() { } emit finished(_fileNameString); - + _isRunning = false; } @@ -454,13 +423,13 @@ void ScriptEngine::stop() { void ScriptEngine::timerFired() { QTimer* callingTimer = reinterpret_cast(sender()); - + // call the associated JS function, if it exists QScriptValue timerFunction = _timerFunctionMap.value(callingTimer); if (timerFunction.isValid()) { timerFunction.call(); } - + if (!callingTimer->isActive()) { // this timer is done, we can kill it delete callingTimer; @@ -471,14 +440,14 @@ QObject* ScriptEngine::setupTimerWithInterval(const QScriptValue& function, int // create the timer, add it to the map, and start it QTimer* newTimer = new QTimer(this); newTimer->setSingleShot(isSingleShot); - + connect(newTimer, &QTimer::timeout, this, &ScriptEngine::timerFired); - + // make sure the timer stops when the script does connect(this, &ScriptEngine::scriptEnding, newTimer, &QTimer::stop); - + _timerFunctionMap.insert(newTimer, function); - + newTimer->start(intervalMS); return newTimer; } @@ -505,17 +474,17 @@ QUrl ScriptEngine::resolveInclude(const QString& include) const { if (!url.scheme().isEmpty()) { return url; } - - // we apparently weren't a fully qualified url, so, let's assume we're relative + + // we apparently weren't a fully qualified url, so, let's assume we're relative // to the original URL of our script QUrl parentURL(_fileNameString); - + // if the parent URL's scheme is empty, then this is probably a local file... if (parentURL.scheme().isEmpty()) { parentURL = QUrl::fromLocalFile(_fileNameString); } - - // at this point we should have a legitimate fully qualified URL for our parent + + // at this point we should have a legitimate fully qualified URL for our parent url = parentURL.resolved(url); return url; } @@ -543,7 +512,7 @@ void ScriptEngine::include(const QString& includeFile) { loop.exec(); includeContents = reply->readAll(); } - + QScriptValue result = _engine.evaluate(includeContents); if (_engine.hasUncaughtException()) { int line = _engine.uncaughtExceptionLineNumber(); diff --git a/libraries/script-engine/src/ScriptEngine.h b/libraries/script-engine/src/ScriptEngine.h index 4fc90d2959..964f64a005 100644 --- a/libraries/script-engine/src/ScriptEngine.h +++ b/libraries/script-engine/src/ScriptEngine.h @@ -33,11 +33,11 @@ const unsigned int SCRIPT_DATA_CALLBACK_USECS = floor(((1.0 / 60.0f) * 1000 * 10 class ScriptEngine : public QObject { Q_OBJECT public: - ScriptEngine(const QUrl& scriptURL, bool wantMenuItems = false, + ScriptEngine(const QUrl& scriptURL, AbstractControllerScriptingInterface* controllerScriptingInterface = NULL); - ScriptEngine(const QString& scriptContents = NO_SCRIPT, bool wantMenuItems = false, - const QString& fileNameString = QString(""), + ScriptEngine(const QString& scriptContents = NO_SCRIPT, + const QString& fileNameString = QString(""), AbstractControllerScriptingInterface* controllerScriptingInterface = NULL); /// Access the VoxelsScriptingInterface in order to initialize it with a custom packet sender and jurisdiction listener @@ -49,39 +49,39 @@ public: /// sets the script contents, will return false if failed, will fail if script is already running bool setScriptContents(const QString& scriptContents, const QString& fileNameString = QString("")); - const QString& getScriptMenuName() const { return _scriptMenuName; } + const QString& getScriptName() const { return _scriptName; } void cleanupMenuItems(); void registerGlobalObject(const QString& name, QObject* object); /// registers a global object by name - + Q_INVOKABLE void setIsAvatar(bool isAvatar); bool isAvatar() const { return _isAvatar; } - + void setAvatarData(AvatarData* avatarData, const QString& objectName); - + bool isListeningToAudioStream() const { return _isListeningToAudioStream; } void setIsListeningToAudioStream(bool isListeningToAudioStream) { _isListeningToAudioStream = isListeningToAudioStream; } - + void setAvatarSound(Sound* avatarSound) { _avatarSound = avatarSound; } bool isPlayingAvatarSound() const { return _avatarSound != NULL; } - + void init(); void run(); /// runs continuously until Agent.stop() is called void evaluate(); /// initializes the engine, and evaluates the script, but then returns control to caller - + void timerFired(); bool hasScript() const { return !_scriptContents.isEmpty(); } public slots: void stop(); - + QObject* setInterval(const QScriptValue& function, int intervalMS); QObject* setTimeout(const QScriptValue& function, int timeoutMS); void clearInterval(QObject* timer) { stopTimer(reinterpret_cast(timer)); } void clearTimeout(QObject* timer) { stopTimer(reinterpret_cast(timer)); } void include(const QString& includeFile); - + signals: void update(float deltaTime); void scriptEnding(); @@ -106,19 +106,18 @@ private: QUrl resolveInclude(const QString& include) const; void sendAvatarIdentityPacket(); void sendAvatarBillboardPacket(); - + QObject* setupTimerWithInterval(const QScriptValue& function, int intervalMS, bool isSingleShot); void stopTimer(QTimer* timer); - + static VoxelsScriptingInterface _voxelsScriptingInterface; static ParticlesScriptingInterface _particlesScriptingInterface; static int _scriptNumber; - + AbstractControllerScriptingInterface* _controllerScriptingInterface; AudioScriptingInterface _audioScriptingInterface; AvatarData* _avatarData; - bool _wantMenuItems; - QString _scriptMenuName; + QString _scriptName; QString _fileNameString; Quat _quatLibrary; Vec3 _vec3Library; From 1c4d44ba4af3d3cf0fee3c4b8b71aa3dd67c1611 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 2 Apr 2014 18:08:44 -0700 Subject: [PATCH 117/595] attempt to complete handshake every 100ms instead of every 1s --- libraries/shared/src/DomainHandler.cpp | 46 ++++++++++++++++++++++++-- libraries/shared/src/DomainHandler.h | 5 ++- libraries/shared/src/NodeList.cpp | 19 ++--------- 3 files changed, 51 insertions(+), 19 deletions(-) diff --git a/libraries/shared/src/DomainHandler.cpp b/libraries/shared/src/DomainHandler.cpp index 6bc959be47..00278689a2 100644 --- a/libraries/shared/src/DomainHandler.cpp +++ b/libraries/shared/src/DomainHandler.cpp @@ -13,12 +13,14 @@ #include "DomainHandler.h" -DomainHandler::DomainHandler() : +DomainHandler::DomainHandler(QObject* parent) : + QObject(parent), _uuid(), _sockAddr(HifiSockAddr(QHostAddress::Null, DEFAULT_DOMAIN_SERVER_PORT)), _assignmentUUID(), _isConnected(false), - _dtlsSession(NULL) + _dtlsSession(NULL), + _handshakeTimer(NULL) { } @@ -33,6 +35,12 @@ void DomainHandler::clearConnectionInfo() { delete _dtlsSession; _dtlsSession = NULL; + + if (_handshakeTimer) { + _handshakeTimer->stop(); + delete _handshakeTimer; + _handshakeTimer = NULL; + } } void DomainHandler::reset() { @@ -44,9 +52,21 @@ void DomainHandler::reset() { _dtlsSession = NULL; } +const unsigned int DTLS_HANDSHAKE_INTERVAL_MSECS = 100; + void DomainHandler::initializeDTLSSession() { if (!_dtlsSession) { _dtlsSession = new DTLSClientSession(NodeList::getInstance()->getDTLSSocket(), _sockAddr); + + // start a timer to complete the handshake process + _handshakeTimer = new QTimer(this); + connect(_handshakeTimer, &QTimer::timeout, this, &DomainHandler::completeDTLSHandshake); + + // start the handshake right now + completeDTLSHandshake(); + + // start the timer to finish off the handshake + _handshakeTimer->start(DTLS_HANDSHAKE_INTERVAL_MSECS); } } @@ -92,6 +112,28 @@ void DomainHandler::setHostname(const QString& hostname) { } } +void DomainHandler::completeDTLSHandshake() { + int handshakeReturn = gnutls_handshake(*_dtlsSession->getGnuTLSSession()); + + qDebug() << "handshake return is" << handshakeReturn; + + if (handshakeReturn == 0) { + // we've shaken hands, so we're good to go now + _dtlsSession->setCompletedHandshake(true); + + _handshakeTimer->stop(); + delete _handshakeTimer; + _handshakeTimer = NULL; + + } else if (gnutls_error_is_fatal(handshakeReturn)) { + // this was a fatal error handshaking, so remove this session + qDebug() << "Fatal error -" << gnutls_strerror(handshakeReturn) + << "- during DTLS handshake with DS at" << getHostname(); + + clearConnectionInfo(); + } +} + void DomainHandler::completedHostnameLookup(const QHostInfo& hostInfo) { for (int i = 0; i < hostInfo.addresses().size(); i++) { if (hostInfo.addresses()[i].protocol() == QAbstractSocket::IPv4Protocol) { diff --git a/libraries/shared/src/DomainHandler.h b/libraries/shared/src/DomainHandler.h index a867207190..f53cbd5689 100644 --- a/libraries/shared/src/DomainHandler.h +++ b/libraries/shared/src/DomainHandler.h @@ -10,6 +10,7 @@ #define __hifi__DomainHandler__ #include +#include #include #include #include @@ -24,7 +25,7 @@ const unsigned short DEFAULT_DOMAIN_SERVER_DTLS_PORT = 40103; class DomainHandler : public QObject { Q_OBJECT public: - DomainHandler(); + DomainHandler(QObject* parent = 0); ~DomainHandler(); void clearConnectionInfo(); @@ -54,6 +55,7 @@ public: void parseDTLSRequirementPacket(const QByteArray& dtlsRequirementPacket); private slots: + void completeDTLSHandshake(); void completedHostnameLookup(const QHostInfo& hostInfo); signals: void hostnameChanged(const QString& hostname); @@ -69,6 +71,7 @@ private: QUuid _assignmentUUID; bool _isConnected; DTLSClientSession* _dtlsSession; + QTimer* _handshakeTimer; }; #endif /* defined(__hifi__DomainHandler__) */ diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 792215ea68..50339947ef 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -53,6 +53,7 @@ NodeList::NodeList(char newOwnerType, unsigned short socketListenPort, unsigned LimitedNodeList(socketListenPort, dtlsListenPort), _ownerType(newOwnerType), _nodeTypesOfInterest(), + _domainHandler(this), _numNoReplyDomainCheckIns(0), _assignmentServerSocket(), _publicSockAddr(), @@ -323,22 +324,8 @@ void NodeList::sendDomainServerCheckIn() { DTLSClientSession* dtlsSession = _domainHandler.getDTLSSession(); - if (dtlsSession) { - if (dtlsSession->completedHandshake()) { - qDebug() << "we can send a DTLS check in!"; - } else { - int handshakeReturn = gnutls_handshake(*dtlsSession->getGnuTLSSession()); - if (handshakeReturn == 0) { - dtlsSession->setCompletedHandshake(true); - } else if (gnutls_error_is_fatal(handshakeReturn)) { - // this was a fatal error handshaking, so remove this session - qDebug() << "Fatal error -" << gnutls_strerror(handshakeReturn) - << "- during DTLS handshake with DS at" << _domainHandler.getHostname(); - - _domainHandler.clearConnectionInfo(); - } - } - + if (dtlsSession && dtlsSession->completedHandshake()) { + qDebug() << "we can send a DTLS check in!"; } else { // construct the DS check in packet QUuid packetUUID = (!_sessionUUID.isNull() ? _sessionUUID : _domainHandler.getAssignmentUUID()); From 42efb0db6552581936ebd316b224e1c4bab957d1 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 2 Apr 2014 18:18:17 -0700 Subject: [PATCH 118/595] glue in processSpatialAudio() --- interface/src/Application.cpp | 2 +- interface/src/Audio.h | 2 +- interface/src/AudioReflector.cpp | 63 ++++++++++++++----------- interface/src/AudioReflector.h | 5 +- libraries/audio/src/AudioRingBuffer.cpp | 4 ++ libraries/audio/src/AudioRingBuffer.h | 1 + 6 files changed, 46 insertions(+), 31 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index fd566e345e..bf3166a928 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1603,7 +1603,7 @@ void Application::init() { _audioReflector.setMyAvatar(getAvatar()); _audioReflector.setVoxels(_voxels.getTree()); _audioReflector.setAudio(getAudio()); - connect(getAudio(), &Audio::audioBufferWrittenToDevice, &_audioReflector, &AudioReflector::addSamples); + connect(getAudio(), &Audio::processSpatialAudio, &_audioReflector, &AudioReflector::processSpatialAudio); } void Application::closeMirrorView() { diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 879eb27d42..2a5119a0f9 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -100,7 +100,7 @@ public slots: signals: bool muteToggled(); - void processSpatialAudio(unsigned int sampleTime, const AudioRingBuffer& ringBuffer, const QAudioFormat& format); + void processSpatialAudio(unsigned int sampleTime, AudioRingBuffer& ringBuffer, const QAudioFormat& format); private: diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index f6d186d5c9..077c370c63 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -33,8 +33,8 @@ void AudioReflector::render() { // BOUNCE_ATTENUATION_FACTOR [0.5] * (1/(1+distance)) int getDelayFromDistance(float distance) { - const int DELAY_PER_METER = 3; - return DELAY_PER_METER * distance; + const int MS_DELAY_PER_METER = 3; + return MS_DELAY_PER_METER * distance; } const float BOUNCE_ATTENUATION_FACTOR = 0.5f; @@ -99,8 +99,10 @@ void AudioReflector::drawReflections(const glm::vec3& origin, const glm::vec3& o } } + void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::vec3& originalDirection, - int bounces, const AudioRingBuffer& samplesRingBuffer) { + int bounces, const AudioRingBuffer& samplesRingBuffer, + unsigned int sampleTime, int sampleRate) { int samplesTouched = 0; @@ -114,11 +116,11 @@ void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::ve const float SLIGHTLY_SHORT = 0.999f; // slightly inside the distance so we're on the inside of the reflection point // set up our buffers for our attenuated and delayed samples - AudioRingBuffer attenuatedLeftSamples(samplesRingBuffer.getSampleCapacity()); - AudioRingBuffer attenuatedRightSamples(samplesRingBuffer.getSampleCapacity()); - const int NUMBER_OF_CHANNELS = 2; - int totalNumberOfSamples = samplesByteArray.size() / (sizeof(int16_t) * NUMBER_OF_CHANNELS); + AudioRingBuffer attenuatedLeftSamples(samplesRingBuffer.samplesAvailable()); + AudioRingBuffer attenuatedRightSamples(samplesRingBuffer.samplesAvailable()); + + int totalNumberOfSamples = samplesRingBuffer.samplesAvailable(); for (int bounceNumber = 1; bounceNumber <= bounces; bounceNumber++) { if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { @@ -131,8 +133,11 @@ void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::ve // calculate the distance to the ears float rightEarDistance = glm::distance(end, rightEarPosition); float leftEarDistance = glm::distance(end, leftEarPosition); - int rightEarDelay = getDelayFromDistance(rightEarDistance); - int leftEarDelay = getDelayFromDistance(leftEarDistance); + int rightEarDelayMsecs = getDelayFromDistance(rightEarDistance); + int leftEarDelayMsecs = getDelayFromDistance(leftEarDistance); + int rightEarDelay = rightEarDelayMsecs / MSECS_PER_SECOND * sampleRate; + int leftEarDelay = leftEarDelayMsecs / MSECS_PER_SECOND * sampleRate; + float rightEarAttenuation = getDistanceAttenuationCoefficient(rightEarDistance) * (bounceNumber * BOUNCE_ATTENUATION_FACTOR); float leftEarAttenuation = getDistanceAttenuationCoefficient(leftEarDistance) * @@ -153,13 +158,17 @@ void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::ve } // now inject the attenuated array with the appropriate delay - _audio->addDelayedAudio(attenuatedLeftSamples, leftEarDelay); - _audio->addDelayedAudio(attenuatedRightSamples, rightEarDelay); + + unsigned int sampleTimeLeft = sampleTime + leftEarDelay; + unsigned int sampleTimeRight = sampleTime + rightEarDelay; + + _audio->addSpatialAudioToBuffer(sampleTimeLeft, attenuatedLeftSamples); + _audio->addSpatialAudioToBuffer(sampleTimeRight, attenuatedRightSamples); } } } -void AudioReflector::addSamples(AudioRingBuffer samples) { +void AudioReflector::processSpatialAudio(unsigned int sampleTime, AudioRingBuffer& ringBuffer, const QAudioFormat& format) { quint64 start = usecTimestampNow(); glm::vec3 origin = _myAvatar->getHead()->getPosition(); @@ -182,24 +191,24 @@ void AudioReflector::addSamples(AudioRingBuffer samples) { const int BOUNCE_COUNT = 5; - calculateReflections(origin, frontRightUp, BOUNCE_COUNT, samples); - calculateReflections(origin, frontLeftUp, BOUNCE_COUNT, samples); - calculateReflections(origin, backRightUp, BOUNCE_COUNT, samples); - calculateReflections(origin, backLeftUp, BOUNCE_COUNT, samples); - calculateReflections(origin, frontRightDown, BOUNCE_COUNT, samples); - calculateReflections(origin, frontLeftDown, BOUNCE_COUNT, samples); - calculateReflections(origin, backRightDown, BOUNCE_COUNT, samples); - calculateReflections(origin, backLeftDown, BOUNCE_COUNT, samples); + calculateReflections(origin, frontRightUp, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); + calculateReflections(origin, frontLeftUp, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); + calculateReflections(origin, backRightUp, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); + calculateReflections(origin, backLeftUp, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); + calculateReflections(origin, frontRightDown, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); + calculateReflections(origin, frontLeftDown, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); + calculateReflections(origin, backRightDown, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); + calculateReflections(origin, backLeftDown, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); - calculateReflections(origin, front, BOUNCE_COUNT, samples); - calculateReflections(origin, back, BOUNCE_COUNT, samples); - calculateReflections(origin, left, BOUNCE_COUNT, samples); - calculateReflections(origin, right, BOUNCE_COUNT, samples); - calculateReflections(origin, up, BOUNCE_COUNT, samples); - calculateReflections(origin, down, BOUNCE_COUNT, samples); + calculateReflections(origin, front, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); + calculateReflections(origin, back, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); + calculateReflections(origin, left, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); + calculateReflections(origin, right, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); + calculateReflections(origin, up, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); + calculateReflections(origin, down, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); quint64 end = usecTimestampNow(); - qDebug() << "AudioReflector::addSamples()... samples.size()=" << samples.size() << " elapsed=" << (end - start); + //qDebug() << "AudioReflector::addSamples()... samples.size()=" << samples.size() << " elapsed=" << (end - start); } diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index a348fc67ea..7934b30ad2 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -26,7 +26,7 @@ public: void render(); public slots: - void addSamples(AudioRingBuffer samples); + void processSpatialAudio(unsigned int sampleTime, AudioRingBuffer& ringBuffer, const QAudioFormat& format); signals: @@ -40,7 +40,8 @@ private: void drawReflections(const glm::vec3& origin, const glm::vec3& direction, int bounces, const glm::vec3& color); void calculateReflections(const glm::vec3& origin, const glm::vec3& originalDirection, - int bounces, const AudioRingBuffer& samplesRingBuffer); + int bounces, const AudioRingBuffer& samplesRingBuffer, + unsigned int sampleTime, int sampleRate); }; diff --git a/libraries/audio/src/AudioRingBuffer.cpp b/libraries/audio/src/AudioRingBuffer.cpp index 376b60ffa1..5dac3e0456 100644 --- a/libraries/audio/src/AudioRingBuffer.cpp +++ b/libraries/audio/src/AudioRingBuffer.cpp @@ -125,6 +125,10 @@ int16_t& AudioRingBuffer::operator[](const int index) { return *shiftedPositionAccomodatingWrap(_nextOutput, index); } +const int16_t& AudioRingBuffer::operator[] (const int index) const { + return *shiftedPositionAccomodatingWrap(_nextOutput, index); +} + void AudioRingBuffer::shiftReadPosition(unsigned int numSamples) { _nextOutput = shiftedPositionAccomodatingWrap(_nextOutput, numSamples); } diff --git a/libraries/audio/src/AudioRingBuffer.h b/libraries/audio/src/AudioRingBuffer.h index e55eeda40e..e3c82a1509 100644 --- a/libraries/audio/src/AudioRingBuffer.h +++ b/libraries/audio/src/AudioRingBuffer.h @@ -57,6 +57,7 @@ public: qint64 writeData(const char* data, qint64 maxSize); int16_t& operator[](const int index); + const int16_t& operator[] (const int index) const; void shiftReadPosition(unsigned int numSamples); From 7717a09f916c3c2efd4dd9268ead85da6dfe4abd Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 2 Apr 2014 18:48:28 -0700 Subject: [PATCH 119/595] use QByteArray for processSpatialAudio() signal --- interface/src/Audio.cpp | 7 +++-- interface/src/Audio.h | 2 +- interface/src/AudioReflector.cpp | 51 +++++++++++++++++++------------- interface/src/AudioReflector.h | 4 +-- 4 files changed, 37 insertions(+), 27 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 503ec5155b..668c8f353b 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -734,14 +734,15 @@ void Audio::processReceivedAudio(unsigned int sampleTime, AudioRingBuffer& ringB // Accumulate direct transmission of audio from sender to receiver addSpatialAudioToBuffer(sampleTime, ringBuffer); - // Send audio off for spatial processing - emit processSpatialAudio(sampleTime, ringBuffer, _desiredOutputFormat); - // copy the samples we'll resample from the spatial audio ring buffer - this also // pushes the read pointer of the spatial audio ring buffer forwards _spatialAudioRingBuffer.readSamples(ringBufferSamples, numNetworkOutputSamples); _spatialAudioStart += ringBuffer.samplesAvailable() / _desiredOutputFormat.channelCount(); + // Send audio off for spatial processing + emit processSpatialAudio(sampleTime, QByteArray((char*)ringBufferSamples, numNetworkOutputSamples), _desiredOutputFormat); + + } else { // copy the samples we'll resample from the ring buffer - this also diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 2a5119a0f9..51a3aab8ae 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -100,7 +100,7 @@ public slots: signals: bool muteToggled(); - void processSpatialAudio(unsigned int sampleTime, AudioRingBuffer& ringBuffer, const QAudioFormat& format); + void processSpatialAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); private: diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 077c370c63..aea1583c68 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -101,7 +101,7 @@ void AudioReflector::drawReflections(const glm::vec3& origin, const glm::vec3& o void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::vec3& originalDirection, - int bounces, const AudioRingBuffer& samplesRingBuffer, + int bounces, const QByteArray& originalSamples, unsigned int sampleTime, int sampleRate) { int samplesTouched = 0; @@ -117,10 +117,13 @@ void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::ve // set up our buffers for our attenuated and delayed samples const int NUMBER_OF_CHANNELS = 2; - AudioRingBuffer attenuatedLeftSamples(samplesRingBuffer.samplesAvailable()); - AudioRingBuffer attenuatedRightSamples(samplesRingBuffer.samplesAvailable()); + + int totalNumberOfSamples = originalSamples.size() / (sizeof(int16_t) * NUMBER_OF_CHANNELS); + + const int16_t* originalSamplesData = (const int16_t*)originalSamples.constData(); + AudioRingBuffer attenuatedLeftSamples(totalNumberOfSamples); + AudioRingBuffer attenuatedRightSamples(totalNumberOfSamples); - int totalNumberOfSamples = samplesRingBuffer.samplesAvailable(); for (int bounceNumber = 1; bounceNumber <= bounces; bounceNumber++) { if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { @@ -145,14 +148,18 @@ void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::ve // run through the samples, and attenuate them for (int sample = 0; sample < totalNumberOfSamples; sample++) { - int16_t leftSample = samplesRingBuffer[sample * NUMBER_OF_CHANNELS]; - int16_t rightSample = samplesRingBuffer[(sample * NUMBER_OF_CHANNELS) + 1]; + int16_t leftSample = originalSamplesData[sample * NUMBER_OF_CHANNELS]; + int16_t rightSample = originalSamplesData[(sample * NUMBER_OF_CHANNELS) + 1]; + + //qDebug() << "leftSample=" << leftSample << "rightSample=" << rightSample; attenuatedLeftSamples[sample * NUMBER_OF_CHANNELS] = leftSample * leftEarAttenuation; attenuatedLeftSamples[sample * NUMBER_OF_CHANNELS + 1] = 0; attenuatedRightSamples[sample * NUMBER_OF_CHANNELS] = 0; attenuatedRightSamples[sample * NUMBER_OF_CHANNELS + 1] = rightSample * rightEarAttenuation; + + //qDebug() << "attenuated... leftSample=" << (leftSample * leftEarAttenuation) << "rightSample=" << (rightSample * rightEarAttenuation); samplesTouched++; } @@ -162,13 +169,15 @@ void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::ve unsigned int sampleTimeLeft = sampleTime + leftEarDelay; unsigned int sampleTimeRight = sampleTime + rightEarDelay; + qDebug() << "sampleTimeLeft=" << sampleTimeLeft << "sampleTimeRight=" << sampleTimeRight; + _audio->addSpatialAudioToBuffer(sampleTimeLeft, attenuatedLeftSamples); _audio->addSpatialAudioToBuffer(sampleTimeRight, attenuatedRightSamples); } } } -void AudioReflector::processSpatialAudio(unsigned int sampleTime, AudioRingBuffer& ringBuffer, const QAudioFormat& format) { +void AudioReflector::processSpatialAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { quint64 start = usecTimestampNow(); glm::vec3 origin = _myAvatar->getHead()->getPosition(); @@ -191,21 +200,21 @@ void AudioReflector::processSpatialAudio(unsigned int sampleTime, AudioRingBuffe const int BOUNCE_COUNT = 5; - calculateReflections(origin, frontRightUp, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); - calculateReflections(origin, frontLeftUp, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); - calculateReflections(origin, backRightUp, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); - calculateReflections(origin, backLeftUp, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); - calculateReflections(origin, frontRightDown, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); - calculateReflections(origin, frontLeftDown, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); - calculateReflections(origin, backRightDown, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); - calculateReflections(origin, backLeftDown, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); + calculateReflections(origin, frontRightUp, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + calculateReflections(origin, frontLeftUp, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + calculateReflections(origin, backRightUp, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + calculateReflections(origin, backLeftUp, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + calculateReflections(origin, frontRightDown, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + calculateReflections(origin, frontLeftDown, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + calculateReflections(origin, backRightDown, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + calculateReflections(origin, backLeftDown, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - calculateReflections(origin, front, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); - calculateReflections(origin, back, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); - calculateReflections(origin, left, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); - calculateReflections(origin, right, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); - calculateReflections(origin, up, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); - calculateReflections(origin, down, BOUNCE_COUNT, ringBuffer, sampleTime, format.sampleRate()); + calculateReflections(origin, front, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + calculateReflections(origin, back, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + calculateReflections(origin, left, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + calculateReflections(origin, right, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + calculateReflections(origin, up, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + calculateReflections(origin, down, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); quint64 end = usecTimestampNow(); //qDebug() << "AudioReflector::addSamples()... samples.size()=" << samples.size() << " elapsed=" << (end - start); diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 7934b30ad2..4767361c29 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -26,7 +26,7 @@ public: void render(); public slots: - void processSpatialAudio(unsigned int sampleTime, AudioRingBuffer& ringBuffer, const QAudioFormat& format); + void processSpatialAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); signals: @@ -40,7 +40,7 @@ private: void drawReflections(const glm::vec3& origin, const glm::vec3& direction, int bounces, const glm::vec3& color); void calculateReflections(const glm::vec3& origin, const glm::vec3& originalDirection, - int bounces, const AudioRingBuffer& samplesRingBuffer, + int bounces, const QByteArray& samples, unsigned int sampleTime, int sampleRate); }; From 4375fe85f1b504d0b9658bf448b16edd6e13cada Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Wed, 2 Apr 2014 18:56:18 -0700 Subject: [PATCH 120/595] Working on voxelizing spanners using a set of six rendered images. --- interface/src/ui/MetavoxelEditor.cpp | 121 +++++++++++++++++++++++++-- interface/src/ui/MetavoxelEditor.h | 6 +- 2 files changed, 115 insertions(+), 12 deletions(-) diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index 19f5902336..d0a2d40461 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -13,8 +13,12 @@ #include #include #include +#include +#include #include +#include #include +#include #include #include @@ -582,20 +586,18 @@ bool PlaceSpannerTool::eventFilter(QObject* watched, QEvent* event) { void PlaceSpannerTool::place() { AttributePointer attribute = AttributeRegistry::getInstance()->getAttribute(_editor->getSelectedAttribute()); - if (!attribute) { - return; + if (attribute) { + applyEdit(attribute, _editor->getValue().value()); } - SharedObjectPointer spanner = _editor->getValue().value(); - MetavoxelEditMessage message = { createEdit(attribute, spanner) }; - Application::getInstance()->getMetavoxels()->applyEdit(message); } InsertSpannerTool::InsertSpannerTool(MetavoxelEditor* editor) : PlaceSpannerTool(editor, "Insert Spanner", "Insert") { } -QVariant InsertSpannerTool::createEdit(const AttributePointer& attribute, const SharedObjectPointer& spanner) { - return QVariant::fromValue(InsertSpannerEdit(attribute, spanner)); +void InsertSpannerTool::applyEdit(const AttributePointer& attribute, const SharedObjectPointer& spanner) { + MetavoxelEditMessage message = { QVariant::fromValue(InsertSpannerEdit(attribute, spanner)) }; + Application::getInstance()->getMetavoxels()->applyEdit(message); } RemoveSpannerTool::RemoveSpannerTool(MetavoxelEditor* editor) : @@ -654,6 +656,107 @@ bool SetSpannerTool::appliesTo(const AttributePointer& attribute) const { return attribute == AttributeRegistry::getInstance()->getSpannersAttribute(); } -QVariant SetSpannerTool::createEdit(const AttributePointer& attribute, const SharedObjectPointer& spanner) { - return QVariant::fromValue(SetSpannerEdit(spanner)); +glm::vec3 DIRECTION_VECTORS[] = { glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f), + glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f), glm::vec3(0.0f, 0.0f, 1.0f) }; + +/// Represents a view from one direction of the spanner to be voxelized. +class DirectionImages { +public: + QImage color; + QVector depth; +}; + +class Voxelizer : public QRunnable { +public: + + Voxelizer(float size, const Box& bounds, const QVector& directionImages); + + virtual void run(); + +private: + + float _size; + Box _bounds; + QVector _directionImages; +}; + +Voxelizer::Voxelizer(float size, const Box& bounds, const QVector& directionImages) : + _size(size), + _bounds(bounds), + _directionImages(directionImages) { +} + +void Voxelizer::run() { + +} + +void SetSpannerTool::applyEdit(const AttributePointer& attribute, const SharedObjectPointer& spanner) { + Spanner* spannerData = static_cast(spanner.data()); + Box bounds = spannerData->getBounds(); + float longestSide(qMax(bounds.getLongestSide(), spannerData->getPlacementGranularity())); + float size = powf(2.0f, floorf(logf(longestSide) / logf(2.0f))); + Box cellBounds(glm::floor(bounds.minimum / size) * size, glm::ceil(bounds.maximum / size) * size); + + Application::getInstance()->getTextureCache()->getPrimaryFramebufferObject()->bind(); + + glEnable(GL_SCISSOR_TEST); + glEnable(GL_LIGHTING); + glEnable(GL_DEPTH_TEST); + glDisable(GL_BLEND); + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + + QVector directionImages; + + for (unsigned int i = 0; i < sizeof(DIRECTION_VECTORS) / sizeof(DIRECTION_VECTORS[0]); i++) { + glm::quat rotation = rotationBetween(DIRECTION_VECTORS[i], IDENTITY_FRONT); + glm::vec3 minima(FLT_MAX, FLT_MAX, FLT_MAX); + glm::vec3 maxima(-FLT_MAX, -FLT_MAX, -FLT_MAX); + for (int j = 0; j < Box::VERTEX_COUNT; j++) { + glm::vec3 rotated = rotation * cellBounds.getVertex(j); + minima = glm::min(minima, rotated); + maxima = glm::max(maxima, rotated); + } + int width = glm::round((maxima.x - minima.x) / spannerData->getVoxelizationGranularity()); + int height = glm::round((maxima.y - minima.y) / spannerData->getVoxelizationGranularity()); + + glViewport(0, 0, width, height); + glScissor(0, 0, width, height); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + glLoadIdentity(); + glOrtho(minima.x, maxima.x, minima.y, maxima.y, -minima.z, -maxima.z); + + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glm::vec3 axis = glm::axis(rotation); + glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); + + spannerData->getRenderer()->render(1.0f, glm::vec3(), 0.0f); + + DirectionImages images = { QImage(width, height, QImage::Format_ARGB32), QVector(width * height) }; + glReadPixels(0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, images.color.bits()); + glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, images.depth.data()); + directionImages.append(images); + + glMatrixMode(GL_PROJECTION); + } + glPopMatrix(); + + glMatrixMode(GL_MODELVIEW); + glPopMatrix(); + + glEnable(GL_BLEND); + glDisable(GL_SCISSOR_TEST); + + Application::getInstance()->getTextureCache()->getPrimaryFramebufferObject()->release(); + + glViewport(0, 0, Application::getInstance()->getGLWidget()->width(), Application::getInstance()->getGLWidget()->height()); + + // send the images off to the lab for processing + QThreadPool::globalInstance()->start(new Voxelizer(size, cellBounds, directionImages)); } diff --git a/interface/src/ui/MetavoxelEditor.h b/interface/src/ui/MetavoxelEditor.h index 76ef8baf6f..7f3521bd1a 100644 --- a/interface/src/ui/MetavoxelEditor.h +++ b/interface/src/ui/MetavoxelEditor.h @@ -157,7 +157,7 @@ public: protected: - virtual QVariant createEdit(const AttributePointer& attribute, const SharedObjectPointer& spanner) = 0; + virtual void applyEdit(const AttributePointer& attribute, const SharedObjectPointer& spanner) = 0; private slots: @@ -174,7 +174,7 @@ public: protected: - virtual QVariant createEdit(const AttributePointer& attribute, const SharedObjectPointer& spanner); + virtual void applyEdit(const AttributePointer& attribute, const SharedObjectPointer& spanner); }; /// Allows removing a spanner from the scene. @@ -217,7 +217,7 @@ public: protected: - virtual QVariant createEdit(const AttributePointer& attribute, const SharedObjectPointer& spanner); + virtual void applyEdit(const AttributePointer& attribute, const SharedObjectPointer& spanner); }; #endif /* defined(__interface__MetavoxelEditor__) */ From d2800ccd559e9c03ed4fbf9d83a00b70c3174333 Mon Sep 17 00:00:00 2001 From: Jeroen Baert Date: Thu, 3 Apr 2014 11:52:13 +0100 Subject: [PATCH 121/595] For some GLEW distributions, it's just lib --- cmake/modules/FindGLEW.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/modules/FindGLEW.cmake b/cmake/modules/FindGLEW.cmake index 684acca762..dbb366390a 100644 --- a/cmake/modules/FindGLEW.cmake +++ b/cmake/modules/FindGLEW.cmake @@ -20,7 +20,7 @@ else () find_path(GLEW_INCLUDE_DIRS GL/glew.h PATH_SUFFIXES include HINTS ${WIN_GLEW_SEARCH_DIRS}) - find_library(GLEW_LIBRARY glew32s PATH_SUFFIXES "lib/Release/Win32" HINTS ${WIN_GLEW_SEARCH_DIRS}) + find_library(GLEW_LIBRARY glew32s PATH_SUFFIXES "lib/Release/Win32" "lib" HINTS ${WIN_GLEW_SEARCH_DIRS}) endif () include(FindPackageHandleStandardArgs) From 09bcada2635a4b9d5a975ce25a21fd87dafb31b4 Mon Sep 17 00:00:00 2001 From: matsukaze Date: Thu, 3 Apr 2014 19:41:59 -0700 Subject: [PATCH 122/595] Fixes to audio spatial processing. --- interface/src/Audio.cpp | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 668c8f353b..074610e269 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -633,7 +633,7 @@ void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, AudioRingBuffer& sp // Just do a straight copy, clipping if necessary unsigned int sampleCt = (remaining < spatialAudio.samplesAvailable()) ? remaining : spatialAudio.samplesAvailable(); if (sampleCt) { - _spatialAudioRingBuffer.writeSamples(spatialAudio.getBuffer(), sampleCt); + _spatialAudioRingBuffer.writeSamples(spatialAudio.getNextOutput(), sampleCt); } _spatialAudioFinish = _spatialAudioStart + spatialAudio.samplesAvailable() / _desiredOutputFormat.channelCount(); @@ -654,7 +654,7 @@ void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, AudioRingBuffer& sp // Copy the new spatial audio to the accumulation ring buffer if (sampleCt) { - _spatialAudioRingBuffer.writeSamples(spatialAudio.getBuffer(), sampleCt); + _spatialAudioRingBuffer.writeSamples(spatialAudio.getNextOutput(), sampleCt); } _spatialAudioFinish += (sampleCt + silentCt) / _desiredOutputFormat.channelCount(); } @@ -664,19 +664,20 @@ void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, AudioRingBuffer& sp // acumulate the overlap unsigned int offset = (sampleTime - _spatialAudioStart) * _desiredOutputFormat.channelCount(); unsigned int accumulationCt = (_spatialAudioFinish - sampleTime) * _desiredOutputFormat.channelCount(); + accumulationCt = (accumulationCt < spatialAudio.samplesAvailable()) ? accumulationCt : spatialAudio.samplesAvailable(); int j = 0; for (int i = accumulationCt; --i >= 0; j++) { _spatialAudioRingBuffer[j + offset] += spatialAudio[j]; } // Copy the remaining unoverlapped spatial audio to the accumulation buffer - unsigned int sampleCt = (remaining < spatialAudio.samplesAvailable()) ? remaining : spatialAudio.samplesAvailable(); + unsigned int sampleCt = spatialAudio.samplesAvailable() - accumulationCt; + sampleCt = (remaining < sampleCt) ? remaining : sampleCt; if (sampleCt) { - _spatialAudioRingBuffer.writeSamples(spatialAudio.getBuffer() + accumulationCt, sampleCt); + _spatialAudioRingBuffer.writeSamples(spatialAudio.getNextOutput() + accumulationCt, sampleCt); } _spatialAudioFinish += sampleCt / _desiredOutputFormat.channelCount(); } - spatialAudio.reset(); } bool Audio::mousePressEvent(int x, int y) { @@ -730,18 +731,20 @@ void Audio::processReceivedAudio(unsigned int sampleTime, AudioRingBuffer& ringB int16_t* ringBufferSamples= new int16_t[numNetworkOutputSamples]; if (_processSpatialAudio) { - unsigned int sampleTime = _spatialAudioFinish; + unsigned int sampleTime = _spatialAudioStart; // Accumulate direct transmission of audio from sender to receiver addSpatialAudioToBuffer(sampleTime, ringBuffer); + addSpatialAudioToBuffer(sampleTime + 48000, ringBuffer); + + // Send audio off for spatial processing + emit processSpatialAudio(sampleTime, QByteArray((char*)ringBuffer.getBuffer(), numNetworkOutputSamples), _desiredOutputFormat); // copy the samples we'll resample from the spatial audio ring buffer - this also // pushes the read pointer of the spatial audio ring buffer forwards _spatialAudioRingBuffer.readSamples(ringBufferSamples, numNetworkOutputSamples); - _spatialAudioStart += ringBuffer.samplesAvailable() / _desiredOutputFormat.channelCount(); - - // Send audio off for spatial processing - emit processSpatialAudio(sampleTime, QByteArray((char*)ringBufferSamples, numNetworkOutputSamples), _desiredOutputFormat); - + int samples = ringBuffer.samplesAvailable(); + _spatialAudioStart += samples / _desiredOutputFormat.channelCount(); + ringBuffer.reset(); } else { From 3808cfa83ddcaf84608e343e9254c702b9bfb836 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 3 Apr 2014 08:55:48 -0700 Subject: [PATCH 123/595] latest work --- interface/interface_en.ts | 12 ++-- interface/src/Application.cpp | 2 +- interface/src/Audio.cpp | 10 +++- interface/src/Audio.h | 2 +- interface/src/AudioReflector.cpp | 82 ++++++++++++++++++++------- libraries/audio/src/AudioRingBuffer.h | 4 +- 6 files changed, 78 insertions(+), 34 deletions(-) diff --git a/interface/interface_en.ts b/interface/interface_en.ts index 3f859c2cd1..43ec129c99 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -14,12 +14,12 @@ - + Open Script - + JavaScript Files (*.js) @@ -113,18 +113,18 @@ Menu - + Open .ini config file - - + + Text files (*.ini) - + Save .ini config file diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index bf3166a928..863df28319 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1603,7 +1603,7 @@ void Application::init() { _audioReflector.setMyAvatar(getAvatar()); _audioReflector.setVoxels(_voxels.getTree()); _audioReflector.setAudio(getAudio()); - connect(getAudio(), &Audio::processSpatialAudio, &_audioReflector, &AudioReflector::processSpatialAudio); + connect(getAudio(), &Audio::processSpatialAudio, &_audioReflector, &AudioReflector::processSpatialAudio,Qt::DirectConnection); } void Application::closeMirrorView() { diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 074610e269..930a88e222 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -622,10 +622,11 @@ unsigned int Audio::timeValToSampleTick(const quint64 time, int sampleRate) { return sample; } -void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, AudioRingBuffer& spatialAudio) { +void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, const AudioRingBuffer& spatialAudio) { // Calculate the number of remaining samples available unsigned int remaining = _spatialAudioRingBuffer.getSampleCapacity() - _spatialAudioRingBuffer.samplesAvailable(); + if (sampleTime >= _spatialAudioFinish) { if (_spatialAudioStart == _spatialAudioFinish) { @@ -645,7 +646,7 @@ void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, AudioRingBuffer& sp unsigned int ct = delay * _desiredOutputFormat.channelCount(); unsigned int silentCt = (remaining < ct) ? remaining : ct; if (silentCt) { - _spatialAudioRingBuffer.addSilentFrame(silentCt); + _spatialAudioRingBuffer.addSilentFrame(silentCt); } // Recalculate the number of remaining samples @@ -660,11 +661,13 @@ void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, AudioRingBuffer& sp } } else { + // There is overlap between the spatial audio buffer and the new sample, // acumulate the overlap unsigned int offset = (sampleTime - _spatialAudioStart) * _desiredOutputFormat.channelCount(); unsigned int accumulationCt = (_spatialAudioFinish - sampleTime) * _desiredOutputFormat.channelCount(); accumulationCt = (accumulationCt < spatialAudio.samplesAvailable()) ? accumulationCt : spatialAudio.samplesAvailable(); + int j = 0; for (int i = accumulationCt; --i >= 0; j++) { _spatialAudioRingBuffer[j + offset] += spatialAudio[j]; @@ -734,7 +737,7 @@ void Audio::processReceivedAudio(unsigned int sampleTime, AudioRingBuffer& ringB unsigned int sampleTime = _spatialAudioStart; // Accumulate direct transmission of audio from sender to receiver addSpatialAudioToBuffer(sampleTime, ringBuffer); - addSpatialAudioToBuffer(sampleTime + 48000, ringBuffer); + //addSpatialAudioToBuffer(sampleTime + 48000, ringBuffer); // Send audio off for spatial processing emit processSpatialAudio(sampleTime, QByteArray((char*)ringBuffer.getBuffer(), numNetworkOutputSamples), _desiredOutputFormat); @@ -744,6 +747,7 @@ void Audio::processReceivedAudio(unsigned int sampleTime, AudioRingBuffer& ringB _spatialAudioRingBuffer.readSamples(ringBufferSamples, numNetworkOutputSamples); int samples = ringBuffer.samplesAvailable(); _spatialAudioStart += samples / _desiredOutputFormat.channelCount(); + ringBuffer.reset(); } else { diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 51a3aab8ae..052eb06bdd 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -78,7 +78,7 @@ public slots: void start(); void stop(); void addReceivedAudioToBuffer(const QByteArray& audioByteArray); - void addSpatialAudioToBuffer(unsigned int sampleTime, AudioRingBuffer& spatialAudio); + void addSpatialAudioToBuffer(unsigned int sampleTime, const AudioRingBuffer& spatialAudio); void handleAudioInput(); void reset(); void toggleMute(); diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index aea1583c68..e7d5c29e25 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -37,7 +37,7 @@ int getDelayFromDistance(float distance) { return MS_DELAY_PER_METER * distance; } -const float BOUNCE_ATTENUATION_FACTOR = 0.5f; +const float BOUNCE_ATTENUATION_FACTOR = 0.125f; float getDistanceAttenuationCoefficient(float distance) { const float DISTANCE_SCALE = 2.5f; @@ -99,6 +99,9 @@ void AudioReflector::drawReflections(const glm::vec3& origin, const glm::vec3& o } } +// set up our buffers for our attenuated and delayed samples +const int NUMBER_OF_CHANNELS = 2; + void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::vec3& originalDirection, int bounces, const QByteArray& originalSamples, @@ -115,14 +118,20 @@ void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::ve BoxFace face; const float SLIGHTLY_SHORT = 0.999f; // slightly inside the distance so we're on the inside of the reflection point - // set up our buffers for our attenuated and delayed samples - const int NUMBER_OF_CHANNELS = 2; - - int totalNumberOfSamples = originalSamples.size() / (sizeof(int16_t) * NUMBER_OF_CHANNELS); + int totalNumberOfSamples = originalSamples.size() / sizeof(int16_t); + int totalNumberOfStereoSamples = originalSamples.size() / (sizeof(int16_t) * NUMBER_OF_CHANNELS); const int16_t* originalSamplesData = (const int16_t*)originalSamples.constData(); - AudioRingBuffer attenuatedLeftSamples(totalNumberOfSamples); - AudioRingBuffer attenuatedRightSamples(totalNumberOfSamples); + QByteArray attenuatedLeftSamples; + QByteArray attenuatedRightSamples; + attenuatedLeftSamples.resize(originalSamples.size()); + attenuatedRightSamples.resize(originalSamples.size()); + + int16_t* attenuatedLeftSamplesData = (int16_t*)attenuatedLeftSamples.data(); + int16_t* attenuatedRightSamplesData = (int16_t*)attenuatedRightSamples.data(); + + AudioRingBuffer attenuatedLeftBuffer(totalNumberOfSamples); + AudioRingBuffer attenuatedRightBuffer(totalNumberOfSamples); for (int bounceNumber = 1; bounceNumber <= bounces; bounceNumber++) { @@ -138,26 +147,25 @@ void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::ve float leftEarDistance = glm::distance(end, leftEarPosition); int rightEarDelayMsecs = getDelayFromDistance(rightEarDistance); int leftEarDelayMsecs = getDelayFromDistance(leftEarDistance); - int rightEarDelay = rightEarDelayMsecs / MSECS_PER_SECOND * sampleRate; - int leftEarDelay = leftEarDelayMsecs / MSECS_PER_SECOND * sampleRate; + int rightEarDelay = rightEarDelayMsecs * sampleRate / MSECS_PER_SECOND; + int leftEarDelay = leftEarDelayMsecs * sampleRate / MSECS_PER_SECOND; - float rightEarAttenuation = getDistanceAttenuationCoefficient(rightEarDistance) * - (bounceNumber * BOUNCE_ATTENUATION_FACTOR); - float leftEarAttenuation = getDistanceAttenuationCoefficient(leftEarDistance) * - (bounceNumber * BOUNCE_ATTENUATION_FACTOR); + float rightEarAttenuation = getDistanceAttenuationCoefficient(rightEarDistance) * (bounceNumber * BOUNCE_ATTENUATION_FACTOR); + float leftEarAttenuation = getDistanceAttenuationCoefficient(leftEarDistance) * (bounceNumber * BOUNCE_ATTENUATION_FACTOR); + //qDebug() << "leftEarAttenuation=" << leftEarAttenuation << "rightEarAttenuation=" << rightEarAttenuation; // run through the samples, and attenuate them - for (int sample = 0; sample < totalNumberOfSamples; sample++) { + for (int sample = 0; sample < totalNumberOfStereoSamples; sample++) { int16_t leftSample = originalSamplesData[sample * NUMBER_OF_CHANNELS]; int16_t rightSample = originalSamplesData[(sample * NUMBER_OF_CHANNELS) + 1]; //qDebug() << "leftSample=" << leftSample << "rightSample=" << rightSample; - attenuatedLeftSamples[sample * NUMBER_OF_CHANNELS] = leftSample * leftEarAttenuation; - attenuatedLeftSamples[sample * NUMBER_OF_CHANNELS + 1] = 0; + attenuatedLeftSamplesData[sample * NUMBER_OF_CHANNELS] = leftSample * leftEarAttenuation; + attenuatedLeftSamplesData[sample * NUMBER_OF_CHANNELS + 1] = 0; - attenuatedRightSamples[sample * NUMBER_OF_CHANNELS] = 0; - attenuatedRightSamples[sample * NUMBER_OF_CHANNELS + 1] = rightSample * rightEarAttenuation; + attenuatedRightSamplesData[sample * NUMBER_OF_CHANNELS] = 0; + attenuatedRightSamplesData[sample * NUMBER_OF_CHANNELS + 1] = rightSample * rightEarAttenuation; //qDebug() << "attenuated... leftSample=" << (leftSample * leftEarAttenuation) << "rightSample=" << (rightSample * rightEarAttenuation); @@ -169,15 +177,47 @@ void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::ve unsigned int sampleTimeLeft = sampleTime + leftEarDelay; unsigned int sampleTimeRight = sampleTime + rightEarDelay; - qDebug() << "sampleTimeLeft=" << sampleTimeLeft << "sampleTimeRight=" << sampleTimeRight; + //qDebug() << "sampleTimeLeft=" << sampleTimeLeft << "sampleTimeRight=" << sampleTimeRight; + + attenuatedLeftBuffer.writeSamples(attenuatedLeftSamplesData, totalNumberOfSamples); + attenuatedRightBuffer.writeSamples(attenuatedRightSamplesData, totalNumberOfSamples); - _audio->addSpatialAudioToBuffer(sampleTimeLeft, attenuatedLeftSamples); - _audio->addSpatialAudioToBuffer(sampleTimeRight, attenuatedRightSamples); + _audio->addSpatialAudioToBuffer(sampleTimeLeft, attenuatedLeftBuffer); + _audio->addSpatialAudioToBuffer(sampleTimeRight, attenuatedRightBuffer); + attenuatedLeftBuffer.reset(); + attenuatedRightBuffer.reset(); } } } void AudioReflector::processSpatialAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { + + + //qDebug() << "AudioReflector::processSpatialAudio()...sampleTime=" << sampleTime << " threadID=" << QThread::currentThreadId(); + + /* + int totalNumberOfSamples = samples.size() / (sizeof(int16_t)); + int numFrameSamples = format.sampleRate() * format.channelCount(); + + qDebug() << " totalNumberOfSamples=" << totalNumberOfSamples; + qDebug() << " numFrameSamples=" << numFrameSamples; + qDebug() << " samples.size()=" << samples.size(); + qDebug() << " sizeof(int16_t)=" << sizeof(int16_t); + + + AudioRingBuffer samplesRingBuffer(totalNumberOfSamples); + qint64 bytesCopied = samplesRingBuffer.writeData(samples.constData(),samples.size()); + for(int i = 0; i < totalNumberOfSamples; i++) { + samplesRingBuffer[i] = samplesRingBuffer[i] * 0.25f; + } + + qDebug() << " bytesCopied=" << bytesCopied; + + _audio->addSpatialAudioToBuffer(sampleTime + 12000, samplesRingBuffer); + + return; + */ + quint64 start = usecTimestampNow(); glm::vec3 origin = _myAvatar->getHead()->getPosition(); diff --git a/libraries/audio/src/AudioRingBuffer.h b/libraries/audio/src/AudioRingBuffer.h index e3c82a1509..b0f6aab5ea 100644 --- a/libraries/audio/src/AudioRingBuffer.h +++ b/libraries/audio/src/AudioRingBuffer.h @@ -47,8 +47,8 @@ public: int parseData(const QByteArray& packet); // assume callers using this will never wrap around the end - const int16_t* getNextOutput() { return _nextOutput; } - const int16_t* getBuffer() { return _buffer; } + const int16_t* getNextOutput() const { return _nextOutput; } + const int16_t* getBuffer() const { return _buffer; } qint64 readSamples(int16_t* destination, qint64 maxSamples); qint64 writeSamples(const int16_t* source, qint64 maxSamples); From 7a602aedd1e07a36cff0c59b98c1d25eb117dc09 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Thu, 3 Apr 2014 09:06:49 -0700 Subject: [PATCH 124/595] Fix crash: don't simulate until geometry exists --- interface/src/avatar/FaceModel.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/interface/src/avatar/FaceModel.cpp b/interface/src/avatar/FaceModel.cpp index 2934a022af..b0ef947f65 100644 --- a/interface/src/avatar/FaceModel.cpp +++ b/interface/src/avatar/FaceModel.cpp @@ -34,14 +34,13 @@ void FaceModel::simulate(float deltaTime) { const float MODEL_SCALE = 0.0006f; setScale(glm::vec3(1.0f, 1.0f, 1.0f) * _owningHead->getScale() * MODEL_SCALE); - if (isActive()) { - setOffset(-_geometry->getFBXGeometry().neckPivot); - } - setPupilDilation(_owningHead->getPupilDilation()); setBlendshapeCoefficients(_owningHead->getBlendshapeCoefficients()); - Model::simulateInternal(deltaTime); + if (isActive()) { + setOffset(-_geometry->getFBXGeometry().neckPivot); + Model::simulateInternal(deltaTime); + } } void FaceModel::maybeUpdateNeckRotation(const JointState& parentState, const FBXJoint& joint, JointState& state) { From 1265e5b12d20f58b35cee087c1ba632e5a391c8c Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 3 Apr 2014 09:23:10 -0700 Subject: [PATCH 125/595] just echo --- interface/src/AudioReflector.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index e7d5c29e25..402b111c26 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -193,30 +193,29 @@ void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::ve void AudioReflector::processSpatialAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { - //qDebug() << "AudioReflector::processSpatialAudio()...sampleTime=" << sampleTime << " threadID=" << QThread::currentThreadId(); + qDebug() << "AudioReflector::processSpatialAudio()...sampleTime=" << sampleTime << " threadID=" << QThread::currentThreadId(); - /* int totalNumberOfSamples = samples.size() / (sizeof(int16_t)); - int numFrameSamples = format.sampleRate() * format.channelCount(); qDebug() << " totalNumberOfSamples=" << totalNumberOfSamples; - qDebug() << " numFrameSamples=" << numFrameSamples; qDebug() << " samples.size()=" << samples.size(); qDebug() << " sizeof(int16_t)=" << sizeof(int16_t); AudioRingBuffer samplesRingBuffer(totalNumberOfSamples); qint64 bytesCopied = samplesRingBuffer.writeData(samples.constData(),samples.size()); + + /* for(int i = 0; i < totalNumberOfSamples; i++) { samplesRingBuffer[i] = samplesRingBuffer[i] * 0.25f; } + */ qDebug() << " bytesCopied=" << bytesCopied; _audio->addSpatialAudioToBuffer(sampleTime + 12000, samplesRingBuffer); return; - */ quint64 start = usecTimestampNow(); From 716858e6f69c1487cf6dae3be793a9e8bb4d3412 Mon Sep 17 00:00:00 2001 From: Dimitar Dobrev Date: Thu, 3 Apr 2014 19:45:46 +0300 Subject: [PATCH 126/595] Informed users who want to chat they have to log in first. --- interface/interface_en.ts | 33 +++++++++++++++++++-------------- interface/src/Menu.cpp | 10 ++-------- interface/src/ui/ChatWindow.cpp | 4 ++++ 3 files changed, 25 insertions(+), 22 deletions(-) diff --git a/interface/interface_en.ts b/interface/interface_en.ts index afd77ecc07..192f5d4015 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -44,32 +44,37 @@ online now: + + + You must be logged in to chat with others. + + - + day - - + %n day + %n days - + hour - - + %n hour + %n hours - + minute - - + %n minute + %n minutes - + %1 online now: @@ -106,18 +111,18 @@ Menu - + Open .ini config file - - + + Text files (*.ini) - + Save .ini config file diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index c07dfb9222..5530c57281 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -180,18 +180,17 @@ Menu::Menu() : QMenu* toolsMenu = addMenu("Tools"); addActionToQMenuAndActionHash(toolsMenu, MenuOption::MetavoxelEditor, 0, this, SLOT(showMetavoxelEditor())); +#ifdef HAVE_QXMPP _chatAction = addActionToQMenuAndActionHash(toolsMenu, MenuOption::Chat, Qt::Key_Return, this, SLOT(showChat())); -#ifdef HAVE_QXMPP + const QXmppClient& xmppClient = XmppClient::getInstance().getXMPPClient(); toggleChat(); connect(&xmppClient, SIGNAL(connected()), this, SLOT(toggleChat())); connect(&xmppClient, SIGNAL(disconnected()), this, SLOT(toggleChat())); -#else - _chatAction->setEnabled(false); #endif QMenu* viewMenu = addMenu("View"); @@ -1155,11 +1154,6 @@ void Menu::showMetavoxelEditor() { } void Menu::showChat() { - if (!_chatAction->isEnabled()) { - // Don't do anything if chat is disabled (No - // QXMPP library or xmpp is disconnected). - return; - } QMainWindow* mainWindow = Application::getInstance()->getWindow(); if (!_chatWindow) { mainWindow->addDockWidget(Qt::NoDockWidgetArea, _chatWindow = new ChatWindow()); diff --git a/interface/src/ui/ChatWindow.cpp b/interface/src/ui/ChatWindow.cpp index 6963c208c5..a667afddae 100644 --- a/interface/src/ui/ChatWindow.cpp +++ b/interface/src/ui/ChatWindow.cpp @@ -42,6 +42,10 @@ ChatWindow::ChatWindow() : ui->messagesGridLayout->setColumnStretch(1, 3); ui->messagePlainTextEdit->installEventFilter(this); + + if (!AccountManager::getInstance().isLoggedIn()) { + ui->connectingToXMPPLabel->setText(tr("You must be logged in to chat with others.")); + } #ifdef HAVE_QXMPP const QXmppClient& xmppClient = XmppClient::getInstance().getXMPPClient(); From 407a6ecc700ac02838060385009c3d36553059be Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 3 Apr 2014 11:26:54 -0700 Subject: [PATCH 127/595] More work on voxelizing. --- interface/src/MetavoxelSystem.cpp | 19 ++++++++++++------- interface/src/MetavoxelSystem.h | 4 ++-- interface/src/ui/MetavoxelEditor.cpp | 15 ++++++++++++++- 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index 042c9329f2..11d6e8de2c 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -69,13 +69,13 @@ SharedObjectPointer MetavoxelSystem::findFirstRaySpannerIntersection( return closestSpanner; } -void MetavoxelSystem::applyEdit(const MetavoxelEditMessage& edit) { +void MetavoxelSystem::applyEdit(const MetavoxelEditMessage& edit, bool reliable) { foreach (const SharedNodePointer& node, NodeList::getInstance()->getNodeHash()) { if (node->getType() == NodeType::MetavoxelServer) { QMutexLocker locker(&node->getMutex()); MetavoxelClient* client = static_cast(node->getLinkedData()); if (client) { - client->applyEdit(edit); + client->applyEdit(edit, reliable); } } } @@ -267,12 +267,17 @@ void MetavoxelClient::guide(MetavoxelVisitor& visitor) { _data.guide(visitor); } -void MetavoxelClient::applyEdit(const MetavoxelEditMessage& edit) { - // apply immediately to local tree - edit.apply(_data, _sequencer.getWeakSharedObjectHash()); +void MetavoxelClient::applyEdit(const MetavoxelEditMessage& edit, bool reliable) { + if (reliable) { + _sequencer.getReliableOutputChannel()->sendMessage(QVariant::fromValue(edit)); + + } else { + // apply immediately to local tree + edit.apply(_data, _sequencer.getWeakSharedObjectHash()); - // start sending it out - _sequencer.sendHighPriorityMessage(QVariant::fromValue(edit)); + // start sending it out + _sequencer.sendHighPriorityMessage(QVariant::fromValue(edit)); + } } void MetavoxelClient::simulate(float deltaTime) { diff --git a/interface/src/MetavoxelSystem.h b/interface/src/MetavoxelSystem.h index 58f40dad37..ee6f91597e 100644 --- a/interface/src/MetavoxelSystem.h +++ b/interface/src/MetavoxelSystem.h @@ -38,7 +38,7 @@ public: SharedObjectPointer findFirstRaySpannerIntersection(const glm::vec3& origin, const glm::vec3& direction, const AttributePointer& attribute, float& distance); - void applyEdit(const MetavoxelEditMessage& edit); + Q_INVOKABLE void applyEdit(const MetavoxelEditMessage& edit, bool reliable = false); void simulate(float deltaTime); void render(); @@ -98,7 +98,7 @@ public: void guide(MetavoxelVisitor& visitor); - void applyEdit(const MetavoxelEditMessage& edit); + void applyEdit(const MetavoxelEditMessage& edit, bool reliable = false); void simulate(float deltaTime); diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index d0a2d40461..1c37ec9078 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -675,6 +675,8 @@ public: private: + void voxelize(const glm::vec3& minimum); + float _size; Box _bounds; QVector _directionImages; @@ -687,7 +689,18 @@ Voxelizer::Voxelizer(float size, const Box& bounds, const QVector Date: Thu, 3 Apr 2014 11:30:06 -0700 Subject: [PATCH 128/595] Remove translations for now, but use correct translation keys for the only translations we had (days/weeks/etc.) --- interface/CMakeLists.txt | 3 +- interface/interface_en.ts | 210 -------------------------------- interface/src/ui/ChatWindow.cpp | 2 +- 3 files changed, 3 insertions(+), 212 deletions(-) delete mode 100644 interface/interface_en.ts diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index f991212a6e..ed14e164ac 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -81,9 +81,10 @@ qt5_add_resources(QT_RESOURCES "${QT_RESOURCE_FILES}") # add them to the interface source files set(INTERFACE_SRCS ${INTERFACE_SRCS} "${QT_UI_HEADERS}" "${QT_RESOURCES}") +# translation disabled until we strip out the line numbers set(QM ${TARGET_NAME}_en.qm) set(TS ${TARGET_NAME}_en.ts) -qt5_create_translation_custom(${QM} ${INTERFACE_SRCS} ${QT_UI_FILES} ${TS}) +# qt5_create_translation_custom(${QM} ${INTERFACE_SRCS} ${QT_UI_FILES} ${TS}) if (APPLE) # configure CMake to use a custom Info.plist diff --git a/interface/interface_en.ts b/interface/interface_en.ts deleted file mode 100644 index 192f5d4015..0000000000 --- a/interface/interface_en.ts +++ /dev/null @@ -1,210 +0,0 @@ - - - - - Application - - - Export Voxels - - - - - Sparse Voxel Octree Files (*.svo) - - - - - Open Script - - - - - JavaScript Files (*.js) - - - - - ChatWindow - - - - Chat - - - - - - Connecting to XMPP... - - - - - - online now: - - - - - You must be logged in to chat with others. - - - - - day - - %n day - %n days - - - - - hour - - %n hour - %n hours - - - - - minute - - %n minute - %n minutes - - - - - %1 online now: - - - - - Dialog - - - - - - Update Required - - - - - - Download - - - - - - Skip Version - - - - - - Close - - - - - Menu - - - Open .ini config file - - - - - - Text files (*.ini) - - - - - Save .ini config file - - - - - QObject - - - - Import Voxels - - - - - Loading ... - - - - - Place voxels - - - - - <b>Import</b> %1 as voxels - - - - - Cancel - - - - - RunningScriptsWidget - - - - Form - - - - - - <html><head/><body><p><span style=" font-size:18pt;">Running Scripts</span></p></body></html> - - - - - - <html><head/><body><p><span style=" font-weight:600;">Currently running</span></p></body></html> - - - - - - Reload All - - - - - - Stop All - - - - - - <html><head/><body><p><span style=" font-weight:600;">Recently loaded</span></p></body></html> - - - - - - (click a script or use the 1-9 keys to load and run it) - - - - - - There are no scripts currently running. - - - - diff --git a/interface/src/ui/ChatWindow.cpp b/interface/src/ui/ChatWindow.cpp index a667afddae..b079b56584 100644 --- a/interface/src/ui/ChatWindow.cpp +++ b/interface/src/ui/ChatWindow.cpp @@ -136,7 +136,7 @@ QString ChatWindow::getParticipantName(const QString& participant) { void ChatWindow::addTimeStamp() { QTimeSpan timePassed = QDateTime::currentDateTime() - lastMessageStamp; int times[] = { timePassed.daysPart(), timePassed.hoursPart(), timePassed.minutesPart() }; - QString strings[] = { tr("day", 0, times[0]), tr("hour", 0, times[1]), tr("minute", 0, times[2]) }; + QString strings[] = { tr("%n day(s)", 0, times[0]), tr("%n hour(s)", 0, times[1]), tr("%n minute(s)", 0, times[2]) }; QString timeString = ""; for (int i = 0; i < 3; i++) { if (times[i] > 0) { From 840847cf543f9a819af5240c2707150bb3d7a67c Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 3 Apr 2014 11:42:43 -0700 Subject: [PATCH 129/595] Don't refer to the QM file. --- interface/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index ed14e164ac..55d0a86d87 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -82,8 +82,8 @@ qt5_add_resources(QT_RESOURCES "${QT_RESOURCE_FILES}") set(INTERFACE_SRCS ${INTERFACE_SRCS} "${QT_UI_HEADERS}" "${QT_RESOURCES}") # translation disabled until we strip out the line numbers -set(QM ${TARGET_NAME}_en.qm) -set(TS ${TARGET_NAME}_en.ts) +# set(QM ${TARGET_NAME}_en.qm) +# set(TS ${TARGET_NAME}_en.ts) # qt5_create_translation_custom(${QM} ${INTERFACE_SRCS} ${QT_UI_FILES} ${TS}) if (APPLE) From d15e12da771ea0f2728783d71e163302d1a0fc70 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Thu, 3 Apr 2014 12:25:50 -0700 Subject: [PATCH 130/595] Changed FstReader categories to place models in the right dirs --- libraries/shared/src/FstReader.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/shared/src/FstReader.cpp b/libraries/shared/src/FstReader.cpp index 14cff957b1..fa71679dd2 100644 --- a/libraries/shared/src/FstReader.cpp +++ b/libraries/shared/src/FstReader.cpp @@ -157,9 +157,9 @@ bool FstReader::zip() { textPart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data;" " name=\"model_category\""); if (_isHead) { - textPart.setBody("head"); + textPart.setBody("heads"); } else { - textPart.setBody("skeleton"); + textPart.setBody("skeletons"); } _dataMultiPart->append(textPart); From 06adaa009cc6c679a3df5d513a71f8b8b30c75f8 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 3 Apr 2014 12:40:35 -0700 Subject: [PATCH 131/595] add first cut at simple low pass filter --- interface/src/Audio.cpp | 43 ++++++++++++++++++++++++++++++++++++++++- interface/src/Audio.h | 2 +- interface/src/Menu.cpp | 3 +++ interface/src/Menu.h | 1 + 4 files changed, 47 insertions(+), 2 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 374976c691..62eaacc7c8 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -468,7 +468,8 @@ void Audio::handleAudioInput() { } // Add tone injection if enabled - const float TONE_FREQ = 220.f / SAMPLE_RATE * TWO_PI; + //const float TONE_FREQ = 220.f / SAMPLE_RATE * TWO_PI; + const float TONE_FREQ = 440.f / SAMPLE_RATE * TWO_PI; const float QUARTER_VOLUME = 8192.f; if (_toneInjectionEnabled) { loudness = 0.f; @@ -760,11 +761,20 @@ void Audio::processReceivedAudio(unsigned int sampleTime, AudioRingBuffer& ringB // copy the samples we'll resample from the ring buffer - this also // pushes the read pointer of the ring buffer forwards ringBuffer.readSamples(ringBufferSamples, numNetworkOutputSamples); + + } // add the next numNetworkOutputSamples from each QByteArray // in our _localInjectionByteArrays QVector to the localInjectedSamples + + if (Menu::getInstance()->isOptionChecked(MenuOption::LowPassFilter)) { + int channels = _desiredOutputFormat.channelCount(); + int filterSamples = numNetworkOutputSamples / channels; + lowPassFilter(ringBufferSamples, filterSamples, channels); + } + // copy the packet from the RB to the output linearResampling(ringBufferSamples, (int16_t*) outputBuffer.data(), @@ -894,6 +904,37 @@ void Audio::addProceduralSounds(int16_t* monoInput, int numSamples) { } } + +// simple 3 pole low pass filter +void Audio::lowPassFilter(int16_t* inputBuffer, int samples, int channels) { + + //qDebug() << "lowPassFilter() samples=" << samples << " channels=" << channels; + //const int POLE_COUNT = 3; + + for (int c = 0; c < channels; c++) { + const float C1 = 0.0f; // 0.25f; + const float C2 = 1.0f; // 0.5f; + const float C3 = 0.0f; // 0.25f; + int16_t S1,S2,S3; + S1 = inputBuffer[c]; // start with the Nth sample, based on the current channel, this is the fist sample for the channel + for (int i = 0; i < samples; i++) { + int sampleAt = (i * channels) + c; + int nextSampleAt = sampleAt + channels; + S2 = inputBuffer[sampleAt]; + if (i == samples - 1) { + S3 = inputBuffer[sampleAt]; + } else { + S3 = inputBuffer[nextSampleAt]; + } + // save our S1 for next time before we mod this + S1 = inputBuffer[sampleAt]; + inputBuffer[sampleAt] = (C1 * S1) + (C2 * S2) + (C3 * S3); + //qDebug() << "channel=" << c << " sampleAt=" << sampleAt; + } + } +} + + // Starts a collision sound. magnitude is 0-1, with 1 the loudest possible sound. void Audio::startCollisionSound(float magnitude, float frequency, float noise, float duration, bool flashScreen) { _collisionSoundMagnitude = magnitude; diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 052eb06bdd..fe3a6cbb7c 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -55,7 +55,7 @@ public: void setJitterBufferSamples(int samples) { _jitterBufferSamples = samples; } int getJitterBufferSamples() { return _jitterBufferSamples; } - void lowPassFilter(int16_t* inputBuffer); + void lowPassFilter(int16_t* inputBuffer, int samples, int channels); virtual void startCollisionSound(float magnitude, float frequency, float noise, float duration, bool flashScreen); virtual void startDrumSound(float volume, float frequency, float duration, float decay); diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 3dd4733c64..9bb63b4a34 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -371,6 +371,9 @@ Menu::Menu() : false, appInstance->getAudio(), SLOT(toggleAudioSpatialProcessing())); + addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::LowPassFilter, + Qt::CTRL | Qt::SHIFT | Qt::Key_F, + false); addActionToQMenuAndActionHash(developerMenu, MenuOption::PasteToVoxel, diff --git a/interface/src/Menu.h b/interface/src/Menu.h index b6feb2e2f5..99df84784a 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -270,6 +270,7 @@ namespace MenuOption { const QString Login = "Login"; const QString Logout = "Logout"; const QString LookAtVectors = "Look-at Vectors"; + const QString LowPassFilter = "Low Pass Filter"; const QString MetavoxelEditor = "Metavoxel Editor..."; const QString Chat = "Chat..."; const QString Metavoxels = "Metavoxels"; From 3bb6d9b3b33caa7fb28665fdce2992d7518daa74 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Thu, 3 Apr 2014 16:07:25 -0700 Subject: [PATCH 132/595] Added call back to model upload. --- libraries/shared/src/FstReader.cpp | 24 ++++++++++++++++++++++-- libraries/shared/src/FstReader.h | 7 +++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/libraries/shared/src/FstReader.cpp b/libraries/shared/src/FstReader.cpp index fa71679dd2..4a299fd757 100644 --- a/libraries/shared/src/FstReader.cpp +++ b/libraries/shared/src/FstReader.cpp @@ -172,14 +172,34 @@ bool FstReader::send() { return false; } - AccountManager::getInstance().authenticatedRequest(MODEL_URL, QNetworkAccessManager::PostOperation, JSONCallbackParameters(), QByteArray(), _dataMultiPart); + JSONCallbackParameters callbackParams; + callbackParams.jsonCallbackReceiver = this; + callbackParams.jsonCallbackMethod = "uploadSuccess"; + callbackParams.errorCallbackReceiver = this; + callbackParams.errorCallbackMethod = "uploadFailed"; + + AccountManager::getInstance().authenticatedRequest(MODEL_URL, QNetworkAccessManager::PostOperation, callbackParams, QByteArray(), _dataMultiPart); _zipDir = NULL; _dataMultiPart = NULL; - qDebug() << "Model sent."; return true; } +void FstReader::uploadSuccess(const QJsonObject& jsonResponse) { + qDebug() << "Model sent with success to the data server."; + qDebug() << "It might take a few minute for it to appear in your model browser."; + deleteLater(); +} + +void FstReader::uploadFailed(QNetworkReply::NetworkError errorCode, const QString& errorString) { + QMessageBox::warning(NULL, + QString("ModelUploader::uploadFailed()"), + QString("Model could not be sent to the data server."), + QMessageBox::Ok); + qDebug() << "Model upload failed (" << errorCode << "): " << errorString; + deleteLater(); +} + bool FstReader::addTextures(const QFileInfo& texdir) { QStringList filter; filter << "*.png" << "*.tif" << "*.jpg" << "*.jpeg"; diff --git a/libraries/shared/src/FstReader.h b/libraries/shared/src/FstReader.h index 6d1cac01c4..2ccf21a3b0 100644 --- a/libraries/shared/src/FstReader.h +++ b/libraries/shared/src/FstReader.h @@ -12,8 +12,11 @@ class TemporaryDir; class QHttpMultiPart; +class QFileInfo; class FstReader : public QObject { + Q_OBJECT + public: FstReader(bool isHead); ~FstReader(); @@ -21,6 +24,10 @@ public: bool zip(); bool send(); +private slots: + void uploadSuccess(const QJsonObject& jsonResponse); + void uploadFailed(QNetworkReply::NetworkError errorCode, const QString& errorString); + private: TemporaryDir* _zipDir; int _lodCount; From 9166dea02eadb04a2810d28c2b7771dd99f494e7 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Thu, 3 Apr 2014 16:16:58 -0700 Subject: [PATCH 133/595] Changed FstReader name to ModelUploader --- interface/src/Application.cpp | 8 +++---- .../src/{FstReader.cpp => ModelUploader.cpp} | 22 +++++++++---------- .../src/{FstReader.h => ModelUploader.h} | 14 ++++++------ 3 files changed, 22 insertions(+), 22 deletions(-) rename libraries/shared/src/{FstReader.cpp => ModelUploader.cpp} (94%) rename libraries/shared/src/{FstReader.h => ModelUploader.h} (78%) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 18a3a228d6..83eab37318 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -63,7 +63,7 @@ #include #include #include -#include +#include #include "Application.h" #include "InterfaceVersion.h" @@ -3244,9 +3244,9 @@ void Application::toggleRunningScriptsWidget() } void Application::uploadFST(bool isHead) { - FstReader reader(isHead); - if (reader.zip()) { - reader.send(); + ModelUploader* uploader = new ModelUploader(isHead); + if (uploader->zip()) { + uploader->send(); } } diff --git a/libraries/shared/src/FstReader.cpp b/libraries/shared/src/ModelUploader.cpp similarity index 94% rename from libraries/shared/src/FstReader.cpp rename to libraries/shared/src/ModelUploader.cpp index 4a299fd757..aeeb3f642e 100644 --- a/libraries/shared/src/FstReader.cpp +++ b/libraries/shared/src/ModelUploader.cpp @@ -1,5 +1,5 @@ // -// FstReader.cpp +// ModelUploader.cpp // hifi // // Created by Clément Brisset on 3/4/14. @@ -18,7 +18,7 @@ #include #include "AccountManager.h" -#include "FstReader.h" +#include "ModelUploader.h" static const QString NAME_FIELD = "name"; @@ -38,7 +38,7 @@ public: } }; -FstReader::FstReader(bool isHead) : +ModelUploader::ModelUploader(bool isHead) : _zipDir(new TemporaryDir()), _lodCount(-1), _texturesCount(-1), @@ -51,11 +51,11 @@ FstReader::FstReader(bool isHead) : } -FstReader::~FstReader() { +ModelUploader::~ModelUploader() { delete _dataMultiPart; } -bool FstReader::zip() { +bool ModelUploader::zip() { // File Dialog QString filename = QFileDialog::getOpenFileName(NULL, "Select your .fst file ...", @@ -167,7 +167,7 @@ bool FstReader::zip() { return true; } -bool FstReader::send() { +bool ModelUploader::send() { if (!_readyToSend) { return false; } @@ -185,13 +185,13 @@ bool FstReader::send() { return true; } -void FstReader::uploadSuccess(const QJsonObject& jsonResponse) { +void ModelUploader::uploadSuccess(const QJsonObject& jsonResponse) { qDebug() << "Model sent with success to the data server."; qDebug() << "It might take a few minute for it to appear in your model browser."; deleteLater(); } -void FstReader::uploadFailed(QNetworkReply::NetworkError errorCode, const QString& errorString) { +void ModelUploader::uploadFailed(QNetworkReply::NetworkError errorCode, const QString& errorString) { QMessageBox::warning(NULL, QString("ModelUploader::uploadFailed()"), QString("Model could not be sent to the data server."), @@ -200,7 +200,7 @@ void FstReader::uploadFailed(QNetworkReply::NetworkError errorCode, const QStrin deleteLater(); } -bool FstReader::addTextures(const QFileInfo& texdir) { +bool ModelUploader::addTextures(const QFileInfo& texdir) { QStringList filter; filter << "*.png" << "*.tif" << "*.jpg" << "*.jpeg"; @@ -229,7 +229,7 @@ bool FstReader::addTextures(const QFileInfo& texdir) { return true; } -bool FstReader::compressFile(const QString &inFileName, const QString &outFileName) { +bool ModelUploader::compressFile(const QString &inFileName, const QString &outFileName) { QFile inFile(inFileName); inFile.open(QIODevice::ReadOnly); QByteArray buffer = inFile.readAll(); @@ -253,7 +253,7 @@ bool FstReader::compressFile(const QString &inFileName, const QString &outFileNa } -bool FstReader::addPart(const QString &path, const QString& name) { +bool ModelUploader::addPart(const QString &path, const QString& name) { QFile* file = new QFile(path); if (!file->open(QIODevice::ReadOnly)) { QMessageBox::warning(NULL, diff --git a/libraries/shared/src/FstReader.h b/libraries/shared/src/ModelUploader.h similarity index 78% rename from libraries/shared/src/FstReader.h rename to libraries/shared/src/ModelUploader.h index 2ccf21a3b0..f127008f44 100644 --- a/libraries/shared/src/FstReader.h +++ b/libraries/shared/src/ModelUploader.h @@ -1,5 +1,5 @@ // -// FstReader.h +// ModelUploader.h // hifi // // Created by Clément Brisset on 3/4/14. @@ -7,19 +7,19 @@ // // -#ifndef __hifi__FstReader__ -#define __hifi__FstReader__ +#ifndef __hifi__ModelUploader__ +#define __hifi__ModelUploader__ class TemporaryDir; class QHttpMultiPart; class QFileInfo; -class FstReader : public QObject { +class ModelUploader : public QObject { Q_OBJECT public: - FstReader(bool isHead); - ~FstReader(); + ModelUploader(bool isHead); + ~ModelUploader(); bool zip(); bool send(); @@ -44,4 +44,4 @@ private: bool addPart(const QString& path, const QString& name); }; -#endif /* defined(__hifi__FstReader__) */ +#endif /* defined(__hifi__ModelUploader__) */ From ba4ccc22efa19e7d5e296e03b3ddce47b3bdf9c0 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Thu, 3 Apr 2014 16:16:58 -0700 Subject: [PATCH 134/595] Changed FstReader name to ModelUploader --- interface/src/Application.cpp | 8 +++---- .../src/{FstReader.cpp => ModelUploader.cpp} | 23 ++++++++++--------- .../src/{FstReader.h => ModelUploader.h} | 14 +++++------ 3 files changed, 23 insertions(+), 22 deletions(-) rename libraries/shared/src/{FstReader.cpp => ModelUploader.cpp} (94%) rename libraries/shared/src/{FstReader.h => ModelUploader.h} (78%) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 18a3a228d6..83eab37318 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -63,7 +63,7 @@ #include #include #include -#include +#include #include "Application.h" #include "InterfaceVersion.h" @@ -3244,9 +3244,9 @@ void Application::toggleRunningScriptsWidget() } void Application::uploadFST(bool isHead) { - FstReader reader(isHead); - if (reader.zip()) { - reader.send(); + ModelUploader* uploader = new ModelUploader(isHead); + if (uploader->zip()) { + uploader->send(); } } diff --git a/libraries/shared/src/FstReader.cpp b/libraries/shared/src/ModelUploader.cpp similarity index 94% rename from libraries/shared/src/FstReader.cpp rename to libraries/shared/src/ModelUploader.cpp index 4a299fd757..71514c8b0f 100644 --- a/libraries/shared/src/FstReader.cpp +++ b/libraries/shared/src/ModelUploader.cpp @@ -1,5 +1,5 @@ // -// FstReader.cpp +// ModelUploader.cpp // hifi // // Created by Clément Brisset on 3/4/14. @@ -18,7 +18,7 @@ #include #include "AccountManager.h" -#include "FstReader.h" +#include "ModelUploader.h" static const QString NAME_FIELD = "name"; @@ -38,7 +38,7 @@ public: } }; -FstReader::FstReader(bool isHead) : +ModelUploader::ModelUploader(bool isHead) : _zipDir(new TemporaryDir()), _lodCount(-1), _texturesCount(-1), @@ -51,11 +51,11 @@ FstReader::FstReader(bool isHead) : } -FstReader::~FstReader() { +ModelUploader::~ModelUploader() { delete _dataMultiPart; } -bool FstReader::zip() { +bool ModelUploader::zip() { // File Dialog QString filename = QFileDialog::getOpenFileName(NULL, "Select your .fst file ...", @@ -167,7 +167,7 @@ bool FstReader::zip() { return true; } -bool FstReader::send() { +bool ModelUploader::send() { if (!_readyToSend) { return false; } @@ -181,17 +181,18 @@ bool FstReader::send() { AccountManager::getInstance().authenticatedRequest(MODEL_URL, QNetworkAccessManager::PostOperation, callbackParams, QByteArray(), _dataMultiPart); _zipDir = NULL; _dataMultiPart = NULL; + qDebug() << "Sending model..."; return true; } -void FstReader::uploadSuccess(const QJsonObject& jsonResponse) { +void ModelUploader::uploadSuccess(const QJsonObject& jsonResponse) { qDebug() << "Model sent with success to the data server."; qDebug() << "It might take a few minute for it to appear in your model browser."; deleteLater(); } -void FstReader::uploadFailed(QNetworkReply::NetworkError errorCode, const QString& errorString) { +void ModelUploader::uploadFailed(QNetworkReply::NetworkError errorCode, const QString& errorString) { QMessageBox::warning(NULL, QString("ModelUploader::uploadFailed()"), QString("Model could not be sent to the data server."), @@ -200,7 +201,7 @@ void FstReader::uploadFailed(QNetworkReply::NetworkError errorCode, const QStrin deleteLater(); } -bool FstReader::addTextures(const QFileInfo& texdir) { +bool ModelUploader::addTextures(const QFileInfo& texdir) { QStringList filter; filter << "*.png" << "*.tif" << "*.jpg" << "*.jpeg"; @@ -229,7 +230,7 @@ bool FstReader::addTextures(const QFileInfo& texdir) { return true; } -bool FstReader::compressFile(const QString &inFileName, const QString &outFileName) { +bool ModelUploader::compressFile(const QString &inFileName, const QString &outFileName) { QFile inFile(inFileName); inFile.open(QIODevice::ReadOnly); QByteArray buffer = inFile.readAll(); @@ -253,7 +254,7 @@ bool FstReader::compressFile(const QString &inFileName, const QString &outFileNa } -bool FstReader::addPart(const QString &path, const QString& name) { +bool ModelUploader::addPart(const QString &path, const QString& name) { QFile* file = new QFile(path); if (!file->open(QIODevice::ReadOnly)) { QMessageBox::warning(NULL, diff --git a/libraries/shared/src/FstReader.h b/libraries/shared/src/ModelUploader.h similarity index 78% rename from libraries/shared/src/FstReader.h rename to libraries/shared/src/ModelUploader.h index 2ccf21a3b0..f127008f44 100644 --- a/libraries/shared/src/FstReader.h +++ b/libraries/shared/src/ModelUploader.h @@ -1,5 +1,5 @@ // -// FstReader.h +// ModelUploader.h // hifi // // Created by Clément Brisset on 3/4/14. @@ -7,19 +7,19 @@ // // -#ifndef __hifi__FstReader__ -#define __hifi__FstReader__ +#ifndef __hifi__ModelUploader__ +#define __hifi__ModelUploader__ class TemporaryDir; class QHttpMultiPart; class QFileInfo; -class FstReader : public QObject { +class ModelUploader : public QObject { Q_OBJECT public: - FstReader(bool isHead); - ~FstReader(); + ModelUploader(bool isHead); + ~ModelUploader(); bool zip(); bool send(); @@ -44,4 +44,4 @@ private: bool addPart(const QString& path, const QString& name); }; -#endif /* defined(__hifi__FstReader__) */ +#endif /* defined(__hifi__ModelUploader__) */ From 5872ec0569c19a6ce5f9d759588c3c25fb11f7e1 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 3 Apr 2014 16:19:33 -0700 Subject: [PATCH 135/595] checkpoint --- interface/src/Audio.cpp | 10 +- interface/src/AudioReflector.cpp | 288 ++++++++++++++++++++++--------- interface/src/AudioReflector.h | 5 +- 3 files changed, 216 insertions(+), 87 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 62eaacc7c8..39f8a7f567 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -468,8 +468,8 @@ void Audio::handleAudioInput() { } // Add tone injection if enabled - //const float TONE_FREQ = 220.f / SAMPLE_RATE * TWO_PI; - const float TONE_FREQ = 440.f / SAMPLE_RATE * TWO_PI; + const float TONE_FREQ = 220.f / SAMPLE_RATE * TWO_PI; + //const float TONE_FREQ = 5000.f / SAMPLE_RATE * TWO_PI; const float QUARTER_VOLUME = 8192.f; if (_toneInjectionEnabled) { loudness = 0.f; @@ -912,9 +912,9 @@ void Audio::lowPassFilter(int16_t* inputBuffer, int samples, int channels) { //const int POLE_COUNT = 3; for (int c = 0; c < channels; c++) { - const float C1 = 0.0f; // 0.25f; - const float C2 = 1.0f; // 0.5f; - const float C3 = 0.0f; // 0.25f; + const float C1 = 0.25f; // 0.0f; // + const float C2 = 0.5f; // 1.0f; // + const float C3 = 0.25f; // 0.0f; // int16_t S1,S2,S3; S1 = inputBuffer[c]; // start with the Nth sample, based on the current channel, this is the fist sample for the channel for (int i = 0; i < samples; i++) { diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 402b111c26..1db234c1ee 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -73,6 +73,42 @@ glm::vec3 getFaceNormal(BoxFace face) { return glm::vec3(0, 0, 0); //error case } +QVector AudioReflector::calculateReflections(const glm::vec3& origin, const glm::vec3& originalDirection, int maxBounces) { + QVector reflectionPoints; + glm::vec3 start = origin; + glm::vec3 direction = originalDirection; + OctreeElement* elementHit; + float distance; + BoxFace face; + const float SLIGHTLY_SHORT = 0.999f; // slightly inside the distance so we're on the inside of the reflection point + + for (int i = 0; i < maxBounces; i++) { + if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { + glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); + + reflectionPoints.push_back(end); + + glm::vec3 faceNormal = getFaceNormal(face); + direction = glm::normalize(glm::reflect(direction,faceNormal)); + start = end; + } + } + return reflectionPoints; +} + + +void AudioReflector::newDrawReflections(const glm::vec3& origin, const glm::vec3& originalColor, const QVector& reflections) { + + glm::vec3 start = origin; + glm::vec3 color = originalColor; + const float COLOR_ADJUST_PER_BOUNCE = 0.75f; + + foreach (glm::vec3 end, reflections) { + drawVector(start, end, color); + start = end; + color = color * COLOR_ADJUST_PER_BOUNCE; + } +} void AudioReflector::drawReflections(const glm::vec3& origin, const glm::vec3& originalDirection, int bounces, const glm::vec3& originalColor) { @@ -98,12 +134,9 @@ void AudioReflector::drawReflections(const glm::vec3& origin, const glm::vec3& o } } } - // set up our buffers for our attenuated and delayed samples const int NUMBER_OF_CHANNELS = 2; - - -void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::vec3& originalDirection, +void AudioReflector::echoReflections(const glm::vec3& origin, const glm::vec3& originalDirection, int bounces, const QByteArray& originalSamples, unsigned int sampleTime, int sampleRate) { @@ -191,73 +224,59 @@ void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::ve } void AudioReflector::processSpatialAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { + bool doNothing = true; + bool doSimpleEcho = false; - - qDebug() << "AudioReflector::processSpatialAudio()...sampleTime=" << sampleTime << " threadID=" << QThread::currentThreadId(); + if (doNothing) { + return; + } else if (doSimpleEcho) { + int totalNumberOfSamples = samples.size() / (sizeof(int16_t)); + AudioRingBuffer samplesRingBuffer(totalNumberOfSamples); + samplesRingBuffer.writeData(samples.constData(),samples.size()); + _audio->addSpatialAudioToBuffer(sampleTime + 12000, samplesRingBuffer); + return; + } else { + quint64 start = usecTimestampNow(); - int totalNumberOfSamples = samples.size() / (sizeof(int16_t)); + glm::vec3 origin = _myAvatar->getHead()->getPosition(); - qDebug() << " totalNumberOfSamples=" << totalNumberOfSamples; - qDebug() << " samples.size()=" << samples.size(); - qDebug() << " sizeof(int16_t)=" << sizeof(int16_t); - + glm::quat orientation = _myAvatar->getOrientation(); // _myAvatar->getHead()->getOrientation(); + glm::vec3 right = glm::normalize(orientation * IDENTITY_RIGHT); + glm::vec3 up = glm::normalize(orientation * IDENTITY_UP); + glm::vec3 front = glm::normalize(orientation * IDENTITY_FRONT); + glm::vec3 left = -right; + glm::vec3 down = -up; + glm::vec3 back = -front; + glm::vec3 frontRightUp = glm::normalize(front + right + up); + glm::vec3 frontLeftUp = glm::normalize(front + left + up); + glm::vec3 backRightUp = glm::normalize(back + right + up); + glm::vec3 backLeftUp = glm::normalize(back + left + up); + glm::vec3 frontRightDown = glm::normalize(front + right + down); + glm::vec3 frontLeftDown = glm::normalize(front + left + down); + glm::vec3 backRightDown = glm::normalize(back + right + down); + glm::vec3 backLeftDown = glm::normalize(back + left + down); - AudioRingBuffer samplesRingBuffer(totalNumberOfSamples); - qint64 bytesCopied = samplesRingBuffer.writeData(samples.constData(),samples.size()); - - /* - for(int i = 0; i < totalNumberOfSamples; i++) { - samplesRingBuffer[i] = samplesRingBuffer[i] * 0.25f; + const int BOUNCE_COUNT = 5; + + echoReflections(origin, frontRightUp, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + echoReflections(origin, frontLeftUp, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + echoReflections(origin, backRightUp, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + echoReflections(origin, backLeftUp, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + echoReflections(origin, frontRightDown, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + echoReflections(origin, frontLeftDown, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + echoReflections(origin, backRightDown, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + echoReflections(origin, backLeftDown, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + + echoReflections(origin, front, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + echoReflections(origin, back, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + echoReflections(origin, left, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + echoReflections(origin, right, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + echoReflections(origin, up, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + echoReflections(origin, down, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + quint64 end = usecTimestampNow(); + + qDebug() << "AudioReflector::addSamples()... elapsed=" << (end - start); } - */ - - qDebug() << " bytesCopied=" << bytesCopied; - - _audio->addSpatialAudioToBuffer(sampleTime + 12000, samplesRingBuffer); - - return; - - quint64 start = usecTimestampNow(); - - glm::vec3 origin = _myAvatar->getHead()->getPosition(); - - glm::quat orientation = _myAvatar->getOrientation(); // _myAvatar->getHead()->getOrientation(); - glm::vec3 right = glm::normalize(orientation * IDENTITY_RIGHT); - glm::vec3 up = glm::normalize(orientation * IDENTITY_UP); - glm::vec3 front = glm::normalize(orientation * IDENTITY_FRONT); - glm::vec3 left = -right; - glm::vec3 down = -up; - glm::vec3 back = -front; - glm::vec3 frontRightUp = glm::normalize(front + right + up); - glm::vec3 frontLeftUp = glm::normalize(front + left + up); - glm::vec3 backRightUp = glm::normalize(back + right + up); - glm::vec3 backLeftUp = glm::normalize(back + left + up); - glm::vec3 frontRightDown = glm::normalize(front + right + down); - glm::vec3 frontLeftDown = glm::normalize(front + left + down); - glm::vec3 backRightDown = glm::normalize(back + right + down); - glm::vec3 backLeftDown = glm::normalize(back + left + down); - - const int BOUNCE_COUNT = 5; - - calculateReflections(origin, frontRightUp, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - calculateReflections(origin, frontLeftUp, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - calculateReflections(origin, backRightUp, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - calculateReflections(origin, backLeftUp, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - calculateReflections(origin, frontRightDown, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - calculateReflections(origin, frontLeftDown, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - calculateReflections(origin, backRightDown, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - calculateReflections(origin, backLeftDown, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - - calculateReflections(origin, front, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - calculateReflections(origin, back, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - calculateReflections(origin, left, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - calculateReflections(origin, right, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - calculateReflections(origin, up, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - calculateReflections(origin, down, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - quint64 end = usecTimestampNow(); - - //qDebug() << "AudioReflector::addSamples()... samples.size()=" << samples.size() << " elapsed=" << (end - start); - } void AudioReflector::drawRays() { @@ -299,21 +318,130 @@ void AudioReflector::drawRays() { const int BOUNCE_COUNT = 5; - drawReflections(origin, frontRightUp, BOUNCE_COUNT, RED); - drawReflections(origin, frontLeftUp, BOUNCE_COUNT, GREEN); - drawReflections(origin, backRightUp, BOUNCE_COUNT, BLUE); - drawReflections(origin, backLeftUp, BOUNCE_COUNT, CYAN); - drawReflections(origin, frontRightDown, BOUNCE_COUNT, PURPLE); - drawReflections(origin, frontLeftDown, BOUNCE_COUNT, YELLOW); - drawReflections(origin, backRightDown, BOUNCE_COUNT, WHITE); - drawReflections(origin, backLeftDown, BOUNCE_COUNT, DARK_RED); + bool oldWay = false; + + if (oldWay) { + drawReflections(origin, frontRightUp, BOUNCE_COUNT, RED); + drawReflections(origin, frontLeftUp, BOUNCE_COUNT, GREEN); + drawReflections(origin, backRightUp, BOUNCE_COUNT, BLUE); + drawReflections(origin, backLeftUp, BOUNCE_COUNT, CYAN); + drawReflections(origin, frontRightDown, BOUNCE_COUNT, PURPLE); + drawReflections(origin, frontLeftDown, BOUNCE_COUNT, YELLOW); + drawReflections(origin, backRightDown, BOUNCE_COUNT, WHITE); + drawReflections(origin, backLeftDown, BOUNCE_COUNT, DARK_RED); - drawReflections(origin, front, BOUNCE_COUNT, DARK_GREEN); - drawReflections(origin, back, BOUNCE_COUNT, DARK_BLUE); - drawReflections(origin, left, BOUNCE_COUNT, DARK_CYAN); - drawReflections(origin, right, BOUNCE_COUNT, DARK_PURPLE); - drawReflections(origin, up, BOUNCE_COUNT, DARK_YELLOW); - drawReflections(origin, down, BOUNCE_COUNT, GRAY); + drawReflections(origin, front, BOUNCE_COUNT, DARK_GREEN); + drawReflections(origin, back, BOUNCE_COUNT, DARK_BLUE); + drawReflections(origin, left, BOUNCE_COUNT, DARK_CYAN); + drawReflections(origin, right, BOUNCE_COUNT, DARK_PURPLE); + drawReflections(origin, up, BOUNCE_COUNT, DARK_YELLOW); + drawReflections(origin, down, BOUNCE_COUNT, GRAY); + } else { + QVector frontRightUpReflections = calculateReflections(origin, frontRightUp, BOUNCE_COUNT); + QVector frontLeftUpReflections = calculateReflections(origin, frontLeftUp, BOUNCE_COUNT); + QVector backRightUpReflections = calculateReflections(origin, backRightUp, BOUNCE_COUNT); + QVector backLeftUpReflections = calculateReflections(origin, backLeftUp, BOUNCE_COUNT); + QVector frontRightDownReflections = calculateReflections(origin, frontRightDown, BOUNCE_COUNT); + QVector frontLeftDownReflections = calculateReflections(origin, frontLeftDown, BOUNCE_COUNT); + QVector backRightDownReflections = calculateReflections(origin, backRightDown, BOUNCE_COUNT); + QVector backLeftDownReflections = calculateReflections(origin, backLeftDown, BOUNCE_COUNT); + QVector frontReflections = calculateReflections(origin, front, BOUNCE_COUNT); + QVector backReflections = calculateReflections(origin, back, BOUNCE_COUNT); + QVector leftReflections = calculateReflections(origin, left, BOUNCE_COUNT); + QVector rightReflections = calculateReflections(origin, right, BOUNCE_COUNT); + QVector upReflections = calculateReflections(origin, up, BOUNCE_COUNT); + QVector downReflections = calculateReflections(origin, down, BOUNCE_COUNT); + + glm::vec3 frontRightUpColor = RED; + glm::vec3 frontLeftUpColor = GREEN; + glm::vec3 backRightUpColor = BLUE; + glm::vec3 backLeftUpColor = CYAN; + glm::vec3 frontRightDownColor = PURPLE; + glm::vec3 frontLeftDownColor = YELLOW; + glm::vec3 backRightDownColor = WHITE; + glm::vec3 backLeftDownColor = DARK_RED; + glm::vec3 frontColor = GRAY; + glm::vec3 backColor = DARK_GREEN; + glm::vec3 leftColor = DARK_BLUE; + glm::vec3 rightColor = DARK_CYAN; + glm::vec3 upColor = DARK_PURPLE; + glm::vec3 downColor = DARK_YELLOW; + + // attempt to determine insidness/outsideness based on number of directional rays that reflect + bool inside = false; + + bool blockedUp = (frontRightUpReflections.size() > 0) && + (frontLeftUpReflections.size() > 0) && + (backRightUpReflections.size() > 0) && + (backLeftUpReflections.size() > 0) && + (upReflections.size() > 0); + + bool blockedDown = (frontRightDownReflections.size() > 0) && + (frontLeftDownReflections.size() > 0) && + (backRightDownReflections.size() > 0) && + (backLeftDownReflections.size() > 0) && + (downReflections.size() > 0); + + bool blockedFront = (frontRightUpReflections.size() > 0) && + (frontLeftUpReflections.size() > 0) && + (frontRightDownReflections.size() > 0) && + (frontLeftDownReflections.size() > 0) && + (frontReflections.size() > 0); + + bool blockedBack = (backRightUpReflections.size() > 0) && + (backLeftUpReflections.size() > 0) && + (backRightDownReflections.size() > 0) && + (backLeftDownReflections.size() > 0) && + (backReflections.size() > 0); + + bool blockedLeft = (frontLeftUpReflections.size() > 0) && + (backLeftUpReflections.size() > 0) && + (frontLeftDownReflections.size() > 0) && + (backLeftDownReflections.size() > 0) && + (leftReflections.size() > 0); + + bool blockedRight = (frontRightUpReflections.size() > 0) && + (backRightUpReflections.size() > 0) && + (frontRightDownReflections.size() > 0) && + (backRightDownReflections.size() > 0) && + (rightReflections.size() > 0); + + inside = blockedUp && blockedDown && blockedFront && blockedBack && blockedLeft && blockedRight; + + if (inside) { + frontRightUpColor = RED; + frontLeftUpColor = RED; + backRightUpColor = RED; + backLeftUpColor = RED; + frontRightDownColor = RED; + frontLeftDownColor = RED; + backRightDownColor = RED; + backLeftDownColor = RED; + frontColor = RED; + backColor = RED; + leftColor = RED; + rightColor = RED; + upColor = RED; + downColor = RED; + } + + newDrawReflections(origin, frontRightUpColor, frontRightUpReflections); + newDrawReflections(origin, frontLeftUpColor, frontLeftUpReflections); + newDrawReflections(origin, backRightUpColor, backRightUpReflections); + newDrawReflections(origin, backLeftUpColor, backLeftUpReflections); + newDrawReflections(origin, frontRightDownColor, frontRightDownReflections); + newDrawReflections(origin, frontLeftDownColor, frontLeftDownReflections); + newDrawReflections(origin, backRightDownColor, backRightDownReflections); + newDrawReflections(origin, backLeftDownColor, backLeftDownReflections); + + newDrawReflections(origin, frontColor, frontReflections); + newDrawReflections(origin, backColor, backReflections); + newDrawReflections(origin, leftColor, leftReflections); + newDrawReflections(origin, rightColor, rightReflections); + newDrawReflections(origin, upColor, upReflections); + newDrawReflections(origin, downColor, downReflections); + + } } void AudioReflector::drawVector(const glm::vec3& start, const glm::vec3& end, const glm::vec3& color) { diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 4767361c29..ea379f2790 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -38,11 +38,12 @@ private: void drawRays(); void drawVector(const glm::vec3& start, const glm::vec3& end, const glm::vec3& color); void drawReflections(const glm::vec3& origin, const glm::vec3& direction, int bounces, const glm::vec3& color); - - void calculateReflections(const glm::vec3& origin, const glm::vec3& originalDirection, + void echoReflections(const glm::vec3& origin, const glm::vec3& originalDirection, int bounces, const QByteArray& samples, unsigned int sampleTime, int sampleRate); + QVector calculateReflections(const glm::vec3& origin, const glm::vec3& originalDirection, int maxBounces); + void newDrawReflections(const glm::vec3& origin, const glm::vec3& originalColor, const QVector& reflections); }; From 836fda2c051d866b0d5cde905689875ff2d15b5a Mon Sep 17 00:00:00 2001 From: matsukaze Date: Fri, 4 Apr 2014 09:07:27 -0700 Subject: [PATCH 136/595] Clamp the audio summation. --- interface/src/Audio.cpp | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 930a88e222..374976c691 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include "Application.h" #include "Audio.h" @@ -624,9 +625,11 @@ unsigned int Audio::timeValToSampleTick(const quint64 time, int sampleRate) { void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, const AudioRingBuffer& spatialAudio) { - // Calculate the number of remaining samples available + // Calculate the number of remaining samples available, the source spatial audio buffer will get + // clipped if there are insufficient samples available in the accumulation buffer. unsigned int remaining = _spatialAudioRingBuffer.getSampleCapacity() - _spatialAudioRingBuffer.samplesAvailable(); + // Locate where in the accumulation buffer the new samples need to go if (sampleTime >= _spatialAudioFinish) { if (_spatialAudioStart == _spatialAudioFinish) { @@ -636,12 +639,12 @@ void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, const AudioRingBuff if (sampleCt) { _spatialAudioRingBuffer.writeSamples(spatialAudio.getNextOutput(), sampleCt); } - _spatialAudioFinish = _spatialAudioStart + spatialAudio.samplesAvailable() / _desiredOutputFormat.channelCount(); + _spatialAudioFinish = _spatialAudioStart + sampleCt / _desiredOutputFormat.channelCount(); } else { - // Spatial audio ring buffer already has data, but there is no overlap with the new sample - // compute the appropriate time delay and pad with silence until the new start time + // Spatial audio ring buffer already has data, but there is no overlap with the new sample. + // Compute the appropriate time delay and pad with silence until the new start time. unsigned int delay = sampleTime - _spatialAudioFinish; unsigned int ct = delay * _desiredOutputFormat.channelCount(); unsigned int silentCt = (remaining < ct) ? remaining : ct; @@ -670,16 +673,18 @@ void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, const AudioRingBuff int j = 0; for (int i = accumulationCt; --i >= 0; j++) { - _spatialAudioRingBuffer[j + offset] += spatialAudio[j]; + int tmp = _spatialAudioRingBuffer[j + offset] + spatialAudio[j]; + _spatialAudioRingBuffer[j + offset] = + static_cast(glm::clamp(tmp, std::numeric_limits::min(), std::numeric_limits::max())); } - // Copy the remaining unoverlapped spatial audio to the accumulation buffer + // Copy the remaining unoverlapped spatial audio to the accumulation buffer, if any unsigned int sampleCt = spatialAudio.samplesAvailable() - accumulationCt; sampleCt = (remaining < sampleCt) ? remaining : sampleCt; if (sampleCt) { _spatialAudioRingBuffer.writeSamples(spatialAudio.getNextOutput() + accumulationCt, sampleCt); + _spatialAudioFinish += sampleCt / _desiredOutputFormat.channelCount(); } - _spatialAudioFinish += sampleCt / _desiredOutputFormat.channelCount(); } } From 33718684e6166f6a582351f1347b265ff3c728b0 Mon Sep 17 00:00:00 2001 From: matsukaze Date: Fri, 4 Apr 2014 16:09:25 -0700 Subject: [PATCH 137/595] More audio fixes. --- interface/src/Audio.cpp | 42 +++++++++++++++++++------------- interface/src/Audio.h | 2 +- interface/src/AudioReflector.cpp | 18 +++----------- 3 files changed, 30 insertions(+), 32 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 374976c691..4a501f74b7 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -623,9 +623,9 @@ unsigned int Audio::timeValToSampleTick(const quint64 time, int sampleRate) { return sample; } -void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, const AudioRingBuffer& spatialAudio) { +void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, QByteArray& spatialAudio, unsigned int numSamples) { - // Calculate the number of remaining samples available, the source spatial audio buffer will get + // Calculate the number of remaining samples available. The source spatial audio buffer will get // clipped if there are insufficient samples available in the accumulation buffer. unsigned int remaining = _spatialAudioRingBuffer.getSampleCapacity() - _spatialAudioRingBuffer.samplesAvailable(); @@ -635,9 +635,9 @@ void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, const AudioRingBuff // Nothing in the spatial audio ring buffer yet // Just do a straight copy, clipping if necessary - unsigned int sampleCt = (remaining < spatialAudio.samplesAvailable()) ? remaining : spatialAudio.samplesAvailable(); + unsigned int sampleCt = (remaining < numSamples) ? remaining : numSamples; if (sampleCt) { - _spatialAudioRingBuffer.writeSamples(spatialAudio.getNextOutput(), sampleCt); + _spatialAudioRingBuffer.writeSamples((int16_t*)spatialAudio.data(), sampleCt); } _spatialAudioFinish = _spatialAudioStart + sampleCt / _desiredOutputFormat.channelCount(); @@ -654,35 +654,37 @@ void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, const AudioRingBuff // Recalculate the number of remaining samples remaining -= silentCt; - unsigned int sampleCt = (remaining < spatialAudio.samplesAvailable()) ? remaining : spatialAudio.samplesAvailable(); + unsigned int sampleCt = (remaining < numSamples) ? remaining : numSamples; // Copy the new spatial audio to the accumulation ring buffer if (sampleCt) { - _spatialAudioRingBuffer.writeSamples(spatialAudio.getNextOutput(), sampleCt); + _spatialAudioRingBuffer.writeSamples((int16_t*)spatialAudio.data(), sampleCt); } _spatialAudioFinish += (sampleCt + silentCt) / _desiredOutputFormat.channelCount(); } } else { - // There is overlap between the spatial audio buffer and the new sample, // acumulate the overlap + + // Calculate the offset from the buffer's current read position, which should be located at _spatialAudioStart unsigned int offset = (sampleTime - _spatialAudioStart) * _desiredOutputFormat.channelCount(); unsigned int accumulationCt = (_spatialAudioFinish - sampleTime) * _desiredOutputFormat.channelCount(); - accumulationCt = (accumulationCt < spatialAudio.samplesAvailable()) ? accumulationCt : spatialAudio.samplesAvailable(); + accumulationCt = (accumulationCt < numSamples) ? accumulationCt : numSamples; + int16_t* spatial = reinterpret_cast(spatialAudio.data()); int j = 0; for (int i = accumulationCt; --i >= 0; j++) { - int tmp = _spatialAudioRingBuffer[j + offset] + spatialAudio[j]; + int tmp = _spatialAudioRingBuffer[j + offset] + spatial[j]; _spatialAudioRingBuffer[j + offset] = static_cast(glm::clamp(tmp, std::numeric_limits::min(), std::numeric_limits::max())); } // Copy the remaining unoverlapped spatial audio to the accumulation buffer, if any - unsigned int sampleCt = spatialAudio.samplesAvailable() - accumulationCt; + unsigned int sampleCt = numSamples - accumulationCt; sampleCt = (remaining < sampleCt) ? remaining : sampleCt; if (sampleCt) { - _spatialAudioRingBuffer.writeSamples(spatialAudio.getNextOutput() + accumulationCt, sampleCt); + _spatialAudioRingBuffer.writeSamples((int16_t*)spatialAudio.data() + accumulationCt, sampleCt); _spatialAudioFinish += sampleCt / _desiredOutputFormat.channelCount(); } } @@ -737,23 +739,29 @@ void Audio::processReceivedAudio(unsigned int sampleTime, AudioRingBuffer& ringB //qDebug() << "pushing " << numNetworkOutputSamples; ringBuffer.setIsStarved(false); - int16_t* ringBufferSamples= new int16_t[numNetworkOutputSamples]; + int16_t* ringBufferSamples = new int16_t[numNetworkOutputSamples]; if (_processSpatialAudio) { unsigned int sampleTime = _spatialAudioStart; + QByteArray buffer; + buffer.resize(numDeviceOutputSamples * sizeof(int16_t)); + + ringBuffer.readSamples((int16_t*)buffer.data(), numDeviceOutputSamples); // Accumulate direct transmission of audio from sender to receiver - addSpatialAudioToBuffer(sampleTime, ringBuffer); + addSpatialAudioToBuffer(sampleTime, buffer, numNetworkOutputSamples); //addSpatialAudioToBuffer(sampleTime + 48000, ringBuffer); // Send audio off for spatial processing - emit processSpatialAudio(sampleTime, QByteArray((char*)ringBuffer.getBuffer(), numNetworkOutputSamples), _desiredOutputFormat); + emit processSpatialAudio(sampleTime, buffer, _desiredOutputFormat); // copy the samples we'll resample from the spatial audio ring buffer - this also // pushes the read pointer of the spatial audio ring buffer forwards _spatialAudioRingBuffer.readSamples(ringBufferSamples, numNetworkOutputSamples); - int samples = ringBuffer.samplesAvailable(); - _spatialAudioStart += samples / _desiredOutputFormat.channelCount(); + + // Advance the start point for the next packet of audio to arrive + _spatialAudioStart += numNetworkOutputSamples; - ringBuffer.reset(); + // Advance the read position by the same amount + //ringBuffer.shiftReadPosition(numNetworkOutputSamples); } else { diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 052eb06bdd..80f2e93688 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -78,7 +78,7 @@ public slots: void start(); void stop(); void addReceivedAudioToBuffer(const QByteArray& audioByteArray); - void addSpatialAudioToBuffer(unsigned int sampleTime, const AudioRingBuffer& spatialAudio); + void addSpatialAudioToBuffer(unsigned int sampleTime, QByteArray& spatialAudio, unsigned int numSamples); void handleAudioInput(); void reset(); void toggleMute(); diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index e7d5c29e25..d9471ab796 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -130,10 +130,6 @@ void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::ve int16_t* attenuatedLeftSamplesData = (int16_t*)attenuatedLeftSamples.data(); int16_t* attenuatedRightSamplesData = (int16_t*)attenuatedRightSamples.data(); - AudioRingBuffer attenuatedLeftBuffer(totalNumberOfSamples); - AudioRingBuffer attenuatedRightBuffer(totalNumberOfSamples); - - for (int bounceNumber = 1; bounceNumber <= bounces; bounceNumber++) { if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); @@ -179,13 +175,8 @@ void AudioReflector::calculateReflections(const glm::vec3& origin, const glm::ve //qDebug() << "sampleTimeLeft=" << sampleTimeLeft << "sampleTimeRight=" << sampleTimeRight; - attenuatedLeftBuffer.writeSamples(attenuatedLeftSamplesData, totalNumberOfSamples); - attenuatedRightBuffer.writeSamples(attenuatedRightSamplesData, totalNumberOfSamples); - - _audio->addSpatialAudioToBuffer(sampleTimeLeft, attenuatedLeftBuffer); - _audio->addSpatialAudioToBuffer(sampleTimeRight, attenuatedRightBuffer); - attenuatedLeftBuffer.reset(); - attenuatedRightBuffer.reset(); + _audio->addSpatialAudioToBuffer(sampleTimeLeft, attenuatedLeftSamples, totalNumberOfSamples); + _audio->addSpatialAudioToBuffer(sampleTimeRight, attenuatedRightSamples, totalNumberOfSamples); } } } @@ -195,7 +186,6 @@ void AudioReflector::processSpatialAudio(unsigned int sampleTime, const QByteArr //qDebug() << "AudioReflector::processSpatialAudio()...sampleTime=" << sampleTime << " threadID=" << QThread::currentThreadId(); - /* int totalNumberOfSamples = samples.size() / (sizeof(int16_t)); int numFrameSamples = format.sampleRate() * format.channelCount(); @@ -205,6 +195,7 @@ void AudioReflector::processSpatialAudio(unsigned int sampleTime, const QByteArr qDebug() << " sizeof(int16_t)=" << sizeof(int16_t); + /* AudioRingBuffer samplesRingBuffer(totalNumberOfSamples); qint64 bytesCopied = samplesRingBuffer.writeData(samples.constData(),samples.size()); for(int i = 0; i < totalNumberOfSamples; i++) { @@ -212,8 +203,7 @@ void AudioReflector::processSpatialAudio(unsigned int sampleTime, const QByteArr } qDebug() << " bytesCopied=" << bytesCopied; - - _audio->addSpatialAudioToBuffer(sampleTime + 12000, samplesRingBuffer); + _audio->addSpatialAudioToBuffer(sampleTime + 12000, samples, totalNumberOfSamples); return; */ From 9e157ff1c5bdd48013ae6e5f8c808b875b0f3019 Mon Sep 17 00:00:00 2001 From: matsukaze Date: Fri, 4 Apr 2014 16:17:49 -0700 Subject: [PATCH 138/595] More audio fixes. --- interface/src/Audio.cpp | 22 +++++++++++++++------- interface/src/Audio.h | 2 +- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 33fc6ec4d2..5efb120793 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -624,7 +624,7 @@ unsigned int Audio::timeValToSampleTick(const quint64 time, int sampleRate) { return sample; } -void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, QByteArray& spatialAudio, unsigned int numSamples) { +void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, const QByteArray& spatialAudio, unsigned int numSamples) { // Calculate the number of remaining samples available. The source spatial audio buffer will get // clipped if there are insufficient samples available in the accumulation buffer. @@ -673,10 +673,12 @@ void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, QByteArray& spatial unsigned int accumulationCt = (_spatialAudioFinish - sampleTime) * _desiredOutputFormat.channelCount(); accumulationCt = (accumulationCt < numSamples) ? accumulationCt : numSamples; - int16_t* spatial = reinterpret_cast(spatialAudio.data()); + const int16_t* spatial = reinterpret_cast(spatialAudio.data()); int j = 0; for (int i = accumulationCt; --i >= 0; j++) { - int tmp = _spatialAudioRingBuffer[j + offset] + spatial[j]; + int t1 = _spatialAudioRingBuffer[j + offset]; + int t2 = spatial[j]; + int tmp = t1 + t2; _spatialAudioRingBuffer[j + offset] = static_cast(glm::clamp(tmp, std::numeric_limits::min(), std::numeric_limits::max())); } @@ -686,6 +688,7 @@ void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, QByteArray& spatial sampleCt = (remaining < sampleCt) ? remaining : sampleCt; if (sampleCt) { _spatialAudioRingBuffer.writeSamples((int16_t*)spatialAudio.data() + accumulationCt, sampleCt); + // Extend the finish time by the amount of unoverlapped samples _spatialAudioFinish += sampleCt / _desiredOutputFormat.channelCount(); } } @@ -744,12 +747,12 @@ void Audio::processReceivedAudio(unsigned int sampleTime, AudioRingBuffer& ringB if (_processSpatialAudio) { unsigned int sampleTime = _spatialAudioStart; QByteArray buffer; - buffer.resize(numDeviceOutputSamples * sizeof(int16_t)); + buffer.resize(numNetworkOutputSamples * sizeof(int16_t)); - ringBuffer.readSamples((int16_t*)buffer.data(), numDeviceOutputSamples); + ringBuffer.readSamples((int16_t*)buffer.data(), numNetworkOutputSamples); // Accumulate direct transmission of audio from sender to receiver addSpatialAudioToBuffer(sampleTime, buffer, numNetworkOutputSamples); - //addSpatialAudioToBuffer(sampleTime + 48000, ringBuffer); + //addSpatialAudioToBuffer(sampleTime + 48000, buffer, numNetworkOutputSamples); // Send audio off for spatial processing emit processSpatialAudio(sampleTime, buffer, _desiredOutputFormat); @@ -759,7 +762,7 @@ void Audio::processReceivedAudio(unsigned int sampleTime, AudioRingBuffer& ringB _spatialAudioRingBuffer.readSamples(ringBufferSamples, numNetworkOutputSamples); // Advance the start point for the next packet of audio to arrive - _spatialAudioStart += numNetworkOutputSamples; + _spatialAudioStart += numNetworkOutputSamples / _desiredOutputFormat.channelCount(); // Advance the read position by the same amount //ringBuffer.shiftReadPosition(numNetworkOutputSamples); @@ -838,6 +841,11 @@ void Audio::toggleToneInjection() { void Audio::toggleAudioSpatialProcessing() { _processSpatialAudio = !_processSpatialAudio; + if (_processSpatialAudio) { + _spatialAudioStart = 0; + _spatialAudioFinish = 0; + _spatialAudioRingBuffer.reset(); + } } // Take a pointer to the acquired microphone input samples and add procedural sounds diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 7520d97c0b..11ad235289 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -78,7 +78,7 @@ public slots: void start(); void stop(); void addReceivedAudioToBuffer(const QByteArray& audioByteArray); - void addSpatialAudioToBuffer(unsigned int sampleTime, QByteArray& spatialAudio, unsigned int numSamples); + void addSpatialAudioToBuffer(unsigned int sampleTime, const QByteArray& spatialAudio, unsigned int numSamples); void handleAudioInput(); void reset(); void toggleMute(); From 23e5452a8984ad1c734ddfdabf38a3df6310d418 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 3 Apr 2014 16:31:28 -0700 Subject: [PATCH 139/595] next cut --- interface/src/AudioReflector.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 8587aa1c90..bb07a586ed 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -215,7 +215,7 @@ void AudioReflector::echoReflections(const glm::vec3& origin, const glm::vec3& o } void AudioReflector::processSpatialAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { - bool doNothing = true; + bool doNothing = false; bool doSimpleEcho = false; if (doNothing) { @@ -264,7 +264,7 @@ void AudioReflector::processSpatialAudio(unsigned int sampleTime, const QByteArr echoReflections(origin, down, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); quint64 end = usecTimestampNow(); - qDebug() << "AudioReflector::addSamples()... elapsed=" << (end - start); + //qDebug() << "AudioReflector::addSamples()... elapsed=" << (end - start); } } From 42f47f5db205f1e4b4f127bdf05cc9bdb026b7f8 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Thu, 3 Apr 2014 16:48:56 -0700 Subject: [PATCH 140/595] Some alphabetical cleaning --- interface/src/Application.h | 14 +++++----- interface/src/Menu.h | 56 ++++++++++++++++++------------------- 2 files changed, 35 insertions(+), 35 deletions(-) diff --git a/interface/src/Application.h b/interface/src/Application.h index fd2d6f2dfa..284e475d2f 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -14,14 +14,14 @@ #include #include -#include -#include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include +#include #include #include diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 56d5e5fd6f..3726bcd9a1 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -219,65 +219,65 @@ private: namespace MenuOption { const QString AboutApp = "About Interface"; const QString AmbientOcclusion = "Ambient Occlusion"; - const QString Avatars = "Avatars"; const QString Atmosphere = "Atmosphere"; - const QString DisableAutoAdjustLOD = "Disable Automatically Adjusting LOD"; + const QString AudioNoiseReduction = "Audio Noise Reduction"; + const QString AudioToneInjection = "Inject Test Tone"; + const QString Avatars = "Avatars"; const QString Bandwidth = "Bandwidth Display"; const QString BandwidthDetails = "Bandwidth Details"; const QString BuckyBalls = "Bucky Balls"; + const QString Chat = "Chat..."; const QString ChatCircling = "Chat Circling"; - const QString Collisions = "Collisions"; const QString CollideWithAvatars = "Collide With Avatars"; + const QString CollideWithEnvironment = "Collide With World Boundaries"; const QString CollideWithParticles = "Collide With Particles"; const QString CollideWithVoxels = "Collide With Voxels"; - const QString CollideWithEnvironment = "Collide With World Boundaries"; + const QString Collisions = "Collisions"; const QString CullSharedFaces = "Cull Shared Voxel Faces"; const QString DecreaseAvatarSize = "Decrease Avatar Size"; const QString DecreaseVoxelSize = "Decrease Voxel Size"; + const QString DisableAutoAdjustLOD = "Disable Automatically Adjusting LOD"; const QString DisplayFrustum = "Display Frustum"; const QString DisplayHands = "Display Hands"; const QString DisplayHandTargets = "Display Hand Targets"; - const QString FilterSixense = "Smooth Sixense Movement"; - const QString Enable3DTVMode = "Enable 3DTV Mode"; - const QString AudioNoiseReduction = "Audio Noise Reduction"; - const QString AudioToneInjection = "Inject Test Tone"; - const QString EchoServerAudio = "Echo Server Audio"; - const QString EchoLocalAudio = "Echo Local Audio"; - const QString MuteAudio = "Mute Microphone"; const QString DontFadeOnVoxelServerChanges = "Don't Fade In/Out on Voxel Server Changes"; - const QString HeadMouse = "Head Mouse"; - const QString HandsCollideWithSelf = "Collide With Self"; + const QString EchoLocalAudio = "Echo Local Audio"; + const QString EchoServerAudio = "Echo Server Audio"; + const QString Enable3DTVMode = "Enable 3DTV Mode"; const QString Faceshift = "Faceshift"; + const QString FilterSixense = "Smooth Sixense Movement"; const QString FirstPerson = "First Person"; const QString FrameTimer = "Show Timer"; const QString FrustumRenderMode = "Render Mode"; const QString Fullscreen = "Fullscreen"; const QString FullscreenMirror = "Fullscreen Mirror"; const QString GlowMode = "Cycle Glow Mode"; + const QString GoHome = "Go Home"; + const QString GoTo = "Go To..."; const QString GoToDomain = "Go To Domain..."; const QString GoToLocation = "Go To Location..."; - const QString NameLocation = "Name this location"; - const QString GoTo = "Go To..."; + const QString Gravity = "Use Gravity"; + const QString HandsCollideWithSelf = "Collide With Self"; + const QString HeadMouse = "Head Mouse"; const QString IncreaseAvatarSize = "Increase Avatar Size"; const QString IncreaseVoxelSize = "Increase Voxel Size"; - const QString GoHome = "Go Home"; - const QString Gravity = "Use Gravity"; + const QString LoadScript = "Open and Run Script File..."; + const QString LoadScriptURL = "Open and Run Script from URL..."; const QString LodTools = "LOD Tools"; const QString Log = "Log"; const QString Login = "Login"; const QString Logout = "Logout"; const QString LookAtVectors = "Look-at Vectors"; const QString MetavoxelEditor = "Metavoxel Editor..."; - const QString Chat = "Chat..."; const QString Metavoxels = "Metavoxels"; const QString Mirror = "Mirror"; const QString MoveWithLean = "Move with Lean"; + const QString MuteAudio = "Mute Microphone"; + const QString NameLocation = "Name this location"; const QString NewVoxelCullingMode = "New Voxel Culling Mode"; + const QString OctreeStats = "Voxel and Particle Statistics"; const QString OffAxisProjection = "Off-Axis Projection"; const QString OldVoxelCullingMode = "Old Voxel Culling Mode"; - const QString TurnWithHead = "Turn using Head"; - const QString LoadScript = "Open and Run Script File..."; - const QString LoadScriptURL = "Open and Run Script from URL..."; const QString Oscilloscope = "Audio Oscilloscope"; const QString Pair = "Pair"; const QString Particles = "Particles"; @@ -285,30 +285,30 @@ namespace MenuOption { const QString PipelineWarnings = "Show Render Pipeline Warnings"; const QString PlaySlaps = "Play Slaps"; const QString Preferences = "Preferences..."; + const QString Quit = "Quit"; const QString ReloadAllScripts = "Reload All Scripts"; - const QString RenderSkeletonCollisionShapes = "Skeleton Collision Shapes"; - const QString RenderHeadCollisionShapes = "Head Collision Shapes"; const QString RenderBoundingCollisionShapes = "Bounding Collision Shapes"; + const QString RenderHeadCollisionShapes = "Head Collision Shapes"; + const QString RenderSkeletonCollisionShapes = "Skeleton Collision Shapes"; const QString ResetAvatarSize = "Reset Avatar Size"; const QString RunningScripts = "Running Scripts"; const QString RunTimingTests = "Run Timing Tests"; + const QString SettingsExport = "Export Settings"; const QString SettingsImport = "Import Settings"; const QString Shadows = "Shadows"; - const QString SettingsExport = "Export Settings"; const QString ShowCulledSharedFaces = "Show Culled Shared Voxel Faces"; - const QString SuppressShortTimings = "Suppress Timings Less than 10ms"; const QString Stars = "Stars"; const QString Stats = "Stats"; const QString StopAllScripts = "Stop All Scripts"; + const QString SuppressShortTimings = "Suppress Timings Less than 10ms"; const QString TestPing = "Test Ping"; const QString TransmitterDrive = "Transmitter Drive"; + const QString TurnWithHead = "Turn using Head"; const QString UploadHead = "Upload Head Model"; const QString UploadSkeleton = "Upload Skeleton Model"; const QString Visage = "Visage"; - const QString Quit = "Quit"; - const QString Voxels = "Voxels"; const QString VoxelMode = "Cycle Voxel Mode"; - const QString OctreeStats = "Voxel and Particle Statistics"; + const QString Voxels = "Voxels"; const QString VoxelTextures = "Voxel Textures"; } From d3ce2c7640c468b051c40c9d28a810bcfa0329a3 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Thu, 3 Apr 2014 16:51:08 -0700 Subject: [PATCH 141/595] Added undo/redo support to the client --- interface/src/Application.h | 4 ++++ interface/src/Menu.cpp | 43 +++++++++++++++++++++++++++++++++++++ interface/src/Menu.h | 8 ++++++- 3 files changed, 54 insertions(+), 1 deletion(-) diff --git a/interface/src/Application.h b/interface/src/Application.h index 284e475d2f..627d80d8dc 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -22,6 +22,7 @@ #include #include #include +#include #include #include @@ -176,6 +177,7 @@ public: Visage* getVisage() { return &_visage; } SixenseManager* getSixenseManager() { return &_sixenseManager; } BandwidthMeter* getBandwidthMeter() { return &_bandwidthMeter; } + QUndoStack* getUndoStack() { return &_undoStack; } /// if you need to access the application settings, use lockSettings()/unlockSettings() QSettings* lockSettings() { _settingsMutex.lock(); return _settings; } @@ -362,6 +364,8 @@ private: QMutex _settingsMutex; QSettings* _settings; + QUndoStack _undoStack; + glm::vec3 _gravity; // Frame Rate Measurement diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 5530c57281..89db728465 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -161,6 +161,14 @@ Menu::Menu() : QMenu* editMenu = addMenu("Edit"); + QUndoStack* undoStack = Application::getInstance()->getUndoStack(); + QAction* undoAction = undoStack->createUndoAction(editMenu); + QAction* redoAction = undoStack->createRedoAction(editMenu); + + addActionToQMenuAndActionHash(editMenu, + undoAction); + addActionToQMenuAndActionHash(editMenu, + redoAction); addActionToQMenuAndActionHash(editMenu, MenuOption::Preferences, @@ -620,6 +628,41 @@ QAction* Menu::addActionToQMenuAndActionHash(QMenu* destinationMenu, return action; } +QAction* Menu::addActionToQMenuAndActionHash(QMenu* destinationMenu, + QAction* action, + const QString& actionName, + const QKeySequence& shortcut, + QAction::MenuRole role, + int menuItemLocation) { + QAction* actionBefore = NULL; + + if (menuItemLocation >= 0 && destinationMenu->actions().size() > menuItemLocation) { + actionBefore = destinationMenu->actions()[menuItemLocation]; + } + + if (!actionName.isEmpty()) { + action->setText(actionName); + } + + if (shortcut != 0) { + action->setShortcut(shortcut); + } + + if (role != QAction::NoRole) { + action->setMenuRole(role); + } + + if (!actionBefore) { + destinationMenu->addAction(action); + } else { + destinationMenu->insertAction(actionBefore, action); + } + + _actionHash.insert(action->text(), action); + + return action; +} + QAction* Menu::addCheckableActionToQMenuAndActionHash(QMenu* destinationMenu, const QString& actionName, const QKeySequence& shortcut, diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 3726bcd9a1..7bb0b75675 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -102,7 +102,13 @@ public: const char* member = NULL, QAction::MenuRole role = QAction::NoRole, int menuItemLocation = UNSPECIFIED_POSITION); - + QAction* addActionToQMenuAndActionHash(QMenu* destinationMenu, + QAction* action, + const QString& actionName = QString(), + const QKeySequence& shortcut = 0, + QAction::MenuRole role = QAction::NoRole, + int menuItemLocation = UNSPECIFIED_POSITION); + void removeAction(QMenu* menu, const QString& actionName); bool goToDestination(QString destination); From 98f0fe8619d3ba8f3e37dfbaedbc15b97bc4f0d8 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 3 Apr 2014 18:57:08 -0700 Subject: [PATCH 142/595] latest pass, improved distance calulations, added menu item to remove original source --- interface/src/Audio.cpp | 9 +- interface/src/Audio.h | 4 +- interface/src/AudioReflector.cpp | 394 ++++++++++++++++++------------- interface/src/AudioReflector.h | 8 +- interface/src/Menu.cpp | 5 + interface/src/Menu.h | 1 + 6 files changed, 243 insertions(+), 178 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index e76adc4178..708bb72cc7 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -611,7 +611,7 @@ void Audio::addReceivedAudioToBuffer(const QByteArray& audioByteArray) { if (_audioOutput) { // Audio output must exist and be correctly set up if we're going to process received audio _ringBuffer.parseData(audioByteArray); - processReceivedAudio(_spatialAudioStart, _ringBuffer); + processReceivedAudio(_ringBuffer); } Application::getInstance()->getBandwidthMeter()->inputStream(BandwidthMeter::AUDIO).updateValue(audioByteArray.size()); @@ -711,7 +711,7 @@ void Audio::toggleAudioNoiseReduction() { _noiseGateEnabled = !_noiseGateEnabled; } -void Audio::processReceivedAudio(unsigned int sampleTime, AudioRingBuffer& ringBuffer) { +void Audio::processReceivedAudio(AudioRingBuffer& ringBuffer) { float networkOutputToOutputRatio = (_desiredOutputFormat.sampleRate() / (float) _outputFormat.sampleRate()) * (_desiredOutputFormat.channelCount() / (float) _outputFormat.channelCount()); @@ -751,8 +751,9 @@ void Audio::processReceivedAudio(unsigned int sampleTime, AudioRingBuffer& ringB ringBuffer.readSamples((int16_t*)buffer.data(), numNetworkOutputSamples); // Accumulate direct transmission of audio from sender to receiver - addSpatialAudioToBuffer(sampleTime, buffer, numNetworkOutputSamples); - //addSpatialAudioToBuffer(sampleTime + 48000, buffer, numNetworkOutputSamples); + if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingIncudeOriginal)) { + addSpatialAudioToBuffer(sampleTime, buffer, numNetworkOutputSamples); + } // Send audio off for spatial processing emit processSpatialAudio(sampleTime, buffer, _desiredOutputFormat); diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 11ad235289..c3417ae891 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -74,6 +74,8 @@ public: int getNetworkSampleRate() { return SAMPLE_RATE; } int getNetworkBufferLengthSamplesPerChannel() { return NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL; } + bool getProcessSpatialAudio() const { return _processSpatialAudio; } + public slots: void start(); void stop(); @@ -186,7 +188,7 @@ private: void addProceduralSounds(int16_t* monoInput, int numSamples); // Process received audio - void processReceivedAudio(unsigned int sampleTime, AudioRingBuffer& ringBuffer); + void processReceivedAudio(AudioRingBuffer& ringBuffer); bool switchInputToAudioDevice(const QAudioDeviceInfo& inputDeviceInfo); bool switchOutputToAudioDevice(const QAudioDeviceInfo& outputDeviceInfo); diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index bb07a586ed..177d0ecb93 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -13,17 +13,9 @@ void AudioReflector::render() { return; // exit early if not set up correctly } - - /* - glm::vec3 position = _myAvatar->getHead()->getPosition(); - const float radius = 0.25f; - glPushMatrix(); - glTranslatef(position.x, position.y, position.z); - glutWireSphere(radius, 15, 15); - glPopMatrix(); - */ - - drawRays(); + if (_audio->getProcessSpatialAudio()) { + drawRays(); + } } @@ -39,6 +31,13 @@ int getDelayFromDistance(float distance) { const float BOUNCE_ATTENUATION_FACTOR = 0.125f; +// each bounce we adjust our attenuation by this factor, the result is an asymptotically decreasing attenuation... +// 0.125, 0.25, 0.5, ... +const float PER_BOUNCE_ATTENUATION_ADJUSTMENT = 2.0f; + +// we don't grow larger than this, which means by the 4th bounce we don't get that much less quiet +const float MAX_BOUNCE_ATTENUATION = 0.9f; + float getDistanceAttenuationCoefficient(float distance) { const float DISTANCE_SCALE = 2.5f; const float GEOMETRIC_AMPLITUDE_SCALAR = 0.3f; @@ -97,7 +96,7 @@ QVector AudioReflector::calculateReflections(const glm::vec3& origin, } -void AudioReflector::newDrawReflections(const glm::vec3& origin, const glm::vec3& originalColor, const QVector& reflections) { +void AudioReflector::drawReflections(const glm::vec3& origin, const glm::vec3& originalColor, const QVector& reflections) { glm::vec3 start = origin; glm::vec3 color = originalColor; @@ -110,33 +109,94 @@ void AudioReflector::newDrawReflections(const glm::vec3& origin, const glm::vec3 } } -void AudioReflector::drawReflections(const glm::vec3& origin, const glm::vec3& originalDirection, - int bounces, const glm::vec3& originalColor) { - - glm::vec3 start = origin; - glm::vec3 direction = originalDirection; - glm::vec3 color = originalColor; - OctreeElement* elementHit; - float distance; - BoxFace face; - const float SLIGHTLY_SHORT = 0.999f; // slightly inside the distance so we're on the inside of the reflection point - const float COLOR_ADJUST_PER_BOUNCE = 0.75f; - - for (int i = 0; i < bounces; i++) { - if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { - glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); - drawVector(start, end, color); - - glm::vec3 faceNormal = getFaceNormal(face); - direction = glm::normalize(glm::reflect(direction,faceNormal)); - start = end; - color = color * COLOR_ADJUST_PER_BOUNCE; - } - } -} // set up our buffers for our attenuated and delayed samples const int NUMBER_OF_CHANNELS = 2; -void AudioReflector::echoReflections(const glm::vec3& origin, const glm::vec3& originalDirection, + + +void AudioReflector::echoReflections(const glm::vec3& origin, const QVector& reflections, const QByteArray& samples, + unsigned int sampleTime, int sampleRate) { + + glm::vec3 rightEarPosition = _myAvatar->getHead()->getRightEarPosition(); + glm::vec3 leftEarPosition = _myAvatar->getHead()->getLeftEarPosition(); + glm::vec3 start = origin; + + int totalNumberOfSamples = samples.size() / sizeof(int16_t); + int totalNumberOfStereoSamples = samples.size() / (sizeof(int16_t) * NUMBER_OF_CHANNELS); + + const int16_t* originalSamplesData = (const int16_t*)samples.constData(); + QByteArray attenuatedLeftSamples; + QByteArray attenuatedRightSamples; + attenuatedLeftSamples.resize(samples.size()); + attenuatedRightSamples.resize(samples.size()); + + int16_t* attenuatedLeftSamplesData = (int16_t*)attenuatedLeftSamples.data(); + int16_t* attenuatedRightSamplesData = (int16_t*)attenuatedRightSamples.data(); + + float rightDistance = 0; + float leftDistance = 0; + float bounceAttenuation = BOUNCE_ATTENUATION_FACTOR; + + foreach (glm::vec3 end, reflections) { + + rightDistance += glm::distance(start, end); + leftDistance += glm::distance(start, end); + + // calculate the distance to the ears + float rightEarDistance = glm::distance(end, rightEarPosition); + float leftEarDistance = glm::distance(end, leftEarPosition); + + float rightTotalDistance = rightEarDistance + rightDistance; + float leftTotalDistance = leftEarDistance + leftDistance; + + int rightEarDelayMsecs = getDelayFromDistance(rightTotalDistance); + int leftEarDelayMsecs = getDelayFromDistance(leftTotalDistance); + int rightEarDelay = rightEarDelayMsecs * sampleRate / MSECS_PER_SECOND; + int leftEarDelay = leftEarDelayMsecs * sampleRate / MSECS_PER_SECOND; + + //qDebug() << "leftTotalDistance=" << leftTotalDistance << "rightTotalDistance=" << rightTotalDistance; + //qDebug() << "leftEarDelay=" << leftEarDelay << "rightEarDelay=" << rightEarDelay; + + float rightEarAttenuation = getDistanceAttenuationCoefficient(rightTotalDistance) * bounceAttenuation; + float leftEarAttenuation = getDistanceAttenuationCoefficient(leftTotalDistance) * bounceAttenuation; + + //qDebug() << "leftEarAttenuation=" << leftEarAttenuation << "rightEarAttenuation=" << rightEarAttenuation; + + + bounceAttenuation = std::min(MAX_BOUNCE_ATTENUATION, bounceAttenuation * PER_BOUNCE_ATTENUATION_ADJUSTMENT); + + // run through the samples, and attenuate them + for (int sample = 0; sample < totalNumberOfStereoSamples; sample++) { + int16_t leftSample = originalSamplesData[sample * NUMBER_OF_CHANNELS]; + int16_t rightSample = originalSamplesData[(sample * NUMBER_OF_CHANNELS) + 1]; + + //qDebug() << "leftSample=" << leftSample << "rightSample=" << rightSample; + + attenuatedLeftSamplesData[sample * NUMBER_OF_CHANNELS] = leftSample * leftEarAttenuation; + attenuatedLeftSamplesData[sample * NUMBER_OF_CHANNELS + 1] = 0; + + attenuatedRightSamplesData[sample * NUMBER_OF_CHANNELS] = 0; + attenuatedRightSamplesData[sample * NUMBER_OF_CHANNELS + 1] = rightSample * rightEarAttenuation; + + //qDebug() << "attenuated... leftSample=" << (leftSample * leftEarAttenuation) << "rightSample=" << (rightSample * rightEarAttenuation); + } + + // now inject the attenuated array with the appropriate delay + + unsigned int sampleTimeLeft = sampleTime + leftEarDelay; + unsigned int sampleTimeRight = sampleTime + rightEarDelay; + + //qDebug() << "sampleTimeLeft=" << sampleTimeLeft << "sampleTimeRight=" << sampleTimeRight; + + _audio->addSpatialAudioToBuffer(sampleTimeLeft, attenuatedLeftSamples, totalNumberOfSamples); + _audio->addSpatialAudioToBuffer(sampleTimeRight, attenuatedRightSamples, totalNumberOfSamples); + + + start = end; + } +} + + +void AudioReflector::oldEchoReflections(const glm::vec3& origin, const glm::vec3& originalDirection, int bounces, const QByteArray& originalSamples, unsigned int sampleTime, int sampleRate) { @@ -225,7 +285,7 @@ void AudioReflector::processSpatialAudio(unsigned int sampleTime, const QByteArr _audio->addSpatialAudioToBuffer(sampleTime + 12000, samples, totalNumberOfSamples); return; } else { - quint64 start = usecTimestampNow(); + //quint64 start = usecTimestampNow(); glm::vec3 origin = _myAvatar->getHead()->getPosition(); @@ -247,22 +307,37 @@ void AudioReflector::processSpatialAudio(unsigned int sampleTime, const QByteArr const int BOUNCE_COUNT = 5; - echoReflections(origin, frontRightUp, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - echoReflections(origin, frontLeftUp, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - echoReflections(origin, backRightUp, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - echoReflections(origin, backLeftUp, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - echoReflections(origin, frontRightDown, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - echoReflections(origin, frontLeftDown, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - echoReflections(origin, backRightDown, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - echoReflections(origin, backLeftDown, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); + QVector frontRightUpReflections = calculateReflections(origin, frontRightUp, BOUNCE_COUNT); + QVector frontLeftUpReflections = calculateReflections(origin, frontLeftUp, BOUNCE_COUNT); + QVector backRightUpReflections = calculateReflections(origin, backRightUp, BOUNCE_COUNT); + QVector backLeftUpReflections = calculateReflections(origin, backLeftUp, BOUNCE_COUNT); + QVector frontRightDownReflections = calculateReflections(origin, frontRightDown, BOUNCE_COUNT); + QVector frontLeftDownReflections = calculateReflections(origin, frontLeftDown, BOUNCE_COUNT); + QVector backRightDownReflections = calculateReflections(origin, backRightDown, BOUNCE_COUNT); + QVector backLeftDownReflections = calculateReflections(origin, backLeftDown, BOUNCE_COUNT); + QVector frontReflections = calculateReflections(origin, front, BOUNCE_COUNT); + QVector backReflections = calculateReflections(origin, back, BOUNCE_COUNT); + QVector leftReflections = calculateReflections(origin, left, BOUNCE_COUNT); + QVector rightReflections = calculateReflections(origin, right, BOUNCE_COUNT); + QVector upReflections = calculateReflections(origin, up, BOUNCE_COUNT); + QVector downReflections = calculateReflections(origin, down, BOUNCE_COUNT); - echoReflections(origin, front, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - echoReflections(origin, back, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - echoReflections(origin, left, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - echoReflections(origin, right, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - echoReflections(origin, up, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - echoReflections(origin, down, BOUNCE_COUNT, samples, sampleTime, format.sampleRate()); - quint64 end = usecTimestampNow(); + echoReflections(origin, frontRightUpReflections, samples, sampleTime, format.sampleRate()); + echoReflections(origin, frontLeftUpReflections, samples, sampleTime, format.sampleRate()); + echoReflections(origin, backRightUpReflections, samples, sampleTime, format.sampleRate()); + echoReflections(origin, backLeftUpReflections, samples, sampleTime, format.sampleRate()); + echoReflections(origin, frontRightDownReflections, samples, sampleTime, format.sampleRate()); + echoReflections(origin, frontLeftDownReflections, samples, sampleTime, format.sampleRate()); + echoReflections(origin, backRightDownReflections, samples, sampleTime, format.sampleRate()); + echoReflections(origin, backLeftDownReflections, samples, sampleTime, format.sampleRate()); + + echoReflections(origin, frontReflections, samples, sampleTime, format.sampleRate()); + echoReflections(origin, backReflections, samples, sampleTime, format.sampleRate()); + echoReflections(origin, leftReflections, samples, sampleTime, format.sampleRate()); + echoReflections(origin, rightReflections, samples, sampleTime, format.sampleRate()); + echoReflections(origin, upReflections, samples, sampleTime, format.sampleRate()); + echoReflections(origin, downReflections, samples, sampleTime, format.sampleRate()); + //quint64 end = usecTimestampNow(); //qDebug() << "AudioReflector::addSamples()... elapsed=" << (end - start); } @@ -307,130 +382,109 @@ void AudioReflector::drawRays() { const int BOUNCE_COUNT = 5; - bool oldWay = false; + QVector frontRightUpReflections = calculateReflections(origin, frontRightUp, BOUNCE_COUNT); + QVector frontLeftUpReflections = calculateReflections(origin, frontLeftUp, BOUNCE_COUNT); + QVector backRightUpReflections = calculateReflections(origin, backRightUp, BOUNCE_COUNT); + QVector backLeftUpReflections = calculateReflections(origin, backLeftUp, BOUNCE_COUNT); + QVector frontRightDownReflections = calculateReflections(origin, frontRightDown, BOUNCE_COUNT); + QVector frontLeftDownReflections = calculateReflections(origin, frontLeftDown, BOUNCE_COUNT); + QVector backRightDownReflections = calculateReflections(origin, backRightDown, BOUNCE_COUNT); + QVector backLeftDownReflections = calculateReflections(origin, backLeftDown, BOUNCE_COUNT); + QVector frontReflections = calculateReflections(origin, front, BOUNCE_COUNT); + QVector backReflections = calculateReflections(origin, back, BOUNCE_COUNT); + QVector leftReflections = calculateReflections(origin, left, BOUNCE_COUNT); + QVector rightReflections = calculateReflections(origin, right, BOUNCE_COUNT); + QVector upReflections = calculateReflections(origin, up, BOUNCE_COUNT); + QVector downReflections = calculateReflections(origin, down, BOUNCE_COUNT); + + glm::vec3 frontRightUpColor = RED; + glm::vec3 frontLeftUpColor = GREEN; + glm::vec3 backRightUpColor = BLUE; + glm::vec3 backLeftUpColor = CYAN; + glm::vec3 frontRightDownColor = PURPLE; + glm::vec3 frontLeftDownColor = YELLOW; + glm::vec3 backRightDownColor = WHITE; + glm::vec3 backLeftDownColor = DARK_RED; + glm::vec3 frontColor = GRAY; + glm::vec3 backColor = DARK_GREEN; + glm::vec3 leftColor = DARK_BLUE; + glm::vec3 rightColor = DARK_CYAN; + glm::vec3 upColor = DARK_PURPLE; + glm::vec3 downColor = DARK_YELLOW; - if (oldWay) { - drawReflections(origin, frontRightUp, BOUNCE_COUNT, RED); - drawReflections(origin, frontLeftUp, BOUNCE_COUNT, GREEN); - drawReflections(origin, backRightUp, BOUNCE_COUNT, BLUE); - drawReflections(origin, backLeftUp, BOUNCE_COUNT, CYAN); - drawReflections(origin, frontRightDown, BOUNCE_COUNT, PURPLE); - drawReflections(origin, frontLeftDown, BOUNCE_COUNT, YELLOW); - drawReflections(origin, backRightDown, BOUNCE_COUNT, WHITE); - drawReflections(origin, backLeftDown, BOUNCE_COUNT, DARK_RED); + // attempt to determine insidness/outsideness based on number of directional rays that reflect + bool inside = false; + + bool blockedUp = (frontRightUpReflections.size() > 0) && + (frontLeftUpReflections.size() > 0) && + (backRightUpReflections.size() > 0) && + (backLeftUpReflections.size() > 0) && + (upReflections.size() > 0); - drawReflections(origin, front, BOUNCE_COUNT, DARK_GREEN); - drawReflections(origin, back, BOUNCE_COUNT, DARK_BLUE); - drawReflections(origin, left, BOUNCE_COUNT, DARK_CYAN); - drawReflections(origin, right, BOUNCE_COUNT, DARK_PURPLE); - drawReflections(origin, up, BOUNCE_COUNT, DARK_YELLOW); - drawReflections(origin, down, BOUNCE_COUNT, GRAY); - } else { - QVector frontRightUpReflections = calculateReflections(origin, frontRightUp, BOUNCE_COUNT); - QVector frontLeftUpReflections = calculateReflections(origin, frontLeftUp, BOUNCE_COUNT); - QVector backRightUpReflections = calculateReflections(origin, backRightUp, BOUNCE_COUNT); - QVector backLeftUpReflections = calculateReflections(origin, backLeftUp, BOUNCE_COUNT); - QVector frontRightDownReflections = calculateReflections(origin, frontRightDown, BOUNCE_COUNT); - QVector frontLeftDownReflections = calculateReflections(origin, frontLeftDown, BOUNCE_COUNT); - QVector backRightDownReflections = calculateReflections(origin, backRightDown, BOUNCE_COUNT); - QVector backLeftDownReflections = calculateReflections(origin, backLeftDown, BOUNCE_COUNT); - QVector frontReflections = calculateReflections(origin, front, BOUNCE_COUNT); - QVector backReflections = calculateReflections(origin, back, BOUNCE_COUNT); - QVector leftReflections = calculateReflections(origin, left, BOUNCE_COUNT); - QVector rightReflections = calculateReflections(origin, right, BOUNCE_COUNT); - QVector upReflections = calculateReflections(origin, up, BOUNCE_COUNT); - QVector downReflections = calculateReflections(origin, down, BOUNCE_COUNT); + bool blockedDown = (frontRightDownReflections.size() > 0) && + (frontLeftDownReflections.size() > 0) && + (backRightDownReflections.size() > 0) && + (backLeftDownReflections.size() > 0) && + (downReflections.size() > 0); - glm::vec3 frontRightUpColor = RED; - glm::vec3 frontLeftUpColor = GREEN; - glm::vec3 backRightUpColor = BLUE; - glm::vec3 backLeftUpColor = CYAN; - glm::vec3 frontRightDownColor = PURPLE; - glm::vec3 frontLeftDownColor = YELLOW; - glm::vec3 backRightDownColor = WHITE; - glm::vec3 backLeftDownColor = DARK_RED; - glm::vec3 frontColor = GRAY; - glm::vec3 backColor = DARK_GREEN; - glm::vec3 leftColor = DARK_BLUE; - glm::vec3 rightColor = DARK_CYAN; - glm::vec3 upColor = DARK_PURPLE; - glm::vec3 downColor = DARK_YELLOW; - - // attempt to determine insidness/outsideness based on number of directional rays that reflect - bool inside = false; - - bool blockedUp = (frontRightUpReflections.size() > 0) && - (frontLeftUpReflections.size() > 0) && - (backRightUpReflections.size() > 0) && - (backLeftUpReflections.size() > 0) && - (upReflections.size() > 0); + bool blockedFront = (frontRightUpReflections.size() > 0) && + (frontLeftUpReflections.size() > 0) && + (frontRightDownReflections.size() > 0) && + (frontLeftDownReflections.size() > 0) && + (frontReflections.size() > 0); - bool blockedDown = (frontRightDownReflections.size() > 0) && - (frontLeftDownReflections.size() > 0) && - (backRightDownReflections.size() > 0) && - (backLeftDownReflections.size() > 0) && - (downReflections.size() > 0); + bool blockedBack = (backRightUpReflections.size() > 0) && + (backLeftUpReflections.size() > 0) && + (backRightDownReflections.size() > 0) && + (backLeftDownReflections.size() > 0) && + (backReflections.size() > 0); + + bool blockedLeft = (frontLeftUpReflections.size() > 0) && + (backLeftUpReflections.size() > 0) && + (frontLeftDownReflections.size() > 0) && + (backLeftDownReflections.size() > 0) && + (leftReflections.size() > 0); - bool blockedFront = (frontRightUpReflections.size() > 0) && - (frontLeftUpReflections.size() > 0) && - (frontRightDownReflections.size() > 0) && - (frontLeftDownReflections.size() > 0) && - (frontReflections.size() > 0); - - bool blockedBack = (backRightUpReflections.size() > 0) && - (backLeftUpReflections.size() > 0) && - (backRightDownReflections.size() > 0) && - (backLeftDownReflections.size() > 0) && - (backReflections.size() > 0); - - bool blockedLeft = (frontLeftUpReflections.size() > 0) && - (backLeftUpReflections.size() > 0) && - (frontLeftDownReflections.size() > 0) && - (backLeftDownReflections.size() > 0) && - (leftReflections.size() > 0); - - bool blockedRight = (frontRightUpReflections.size() > 0) && - (backRightUpReflections.size() > 0) && - (frontRightDownReflections.size() > 0) && - (backRightDownReflections.size() > 0) && - (rightReflections.size() > 0); - - inside = blockedUp && blockedDown && blockedFront && blockedBack && blockedLeft && blockedRight; - - if (inside) { - frontRightUpColor = RED; - frontLeftUpColor = RED; - backRightUpColor = RED; - backLeftUpColor = RED; - frontRightDownColor = RED; - frontLeftDownColor = RED; - backRightDownColor = RED; - backLeftDownColor = RED; - frontColor = RED; - backColor = RED; - leftColor = RED; - rightColor = RED; - upColor = RED; - downColor = RED; - } - - newDrawReflections(origin, frontRightUpColor, frontRightUpReflections); - newDrawReflections(origin, frontLeftUpColor, frontLeftUpReflections); - newDrawReflections(origin, backRightUpColor, backRightUpReflections); - newDrawReflections(origin, backLeftUpColor, backLeftUpReflections); - newDrawReflections(origin, frontRightDownColor, frontRightDownReflections); - newDrawReflections(origin, frontLeftDownColor, frontLeftDownReflections); - newDrawReflections(origin, backRightDownColor, backRightDownReflections); - newDrawReflections(origin, backLeftDownColor, backLeftDownReflections); - - newDrawReflections(origin, frontColor, frontReflections); - newDrawReflections(origin, backColor, backReflections); - newDrawReflections(origin, leftColor, leftReflections); - newDrawReflections(origin, rightColor, rightReflections); - newDrawReflections(origin, upColor, upReflections); - newDrawReflections(origin, downColor, downReflections); + bool blockedRight = (frontRightUpReflections.size() > 0) && + (backRightUpReflections.size() > 0) && + (frontRightDownReflections.size() > 0) && + (backRightDownReflections.size() > 0) && + (rightReflections.size() > 0); + inside = blockedUp && blockedDown && blockedFront && blockedBack && blockedLeft && blockedRight; + + if (inside) { + frontRightUpColor = RED; + frontLeftUpColor = RED; + backRightUpColor = RED; + backLeftUpColor = RED; + frontRightDownColor = RED; + frontLeftDownColor = RED; + backRightDownColor = RED; + backLeftDownColor = RED; + frontColor = RED; + backColor = RED; + leftColor = RED; + rightColor = RED; + upColor = RED; + downColor = RED; } + + drawReflections(origin, frontRightUpColor, frontRightUpReflections); + drawReflections(origin, frontLeftUpColor, frontLeftUpReflections); + drawReflections(origin, backRightUpColor, backRightUpReflections); + drawReflections(origin, backLeftUpColor, backLeftUpReflections); + drawReflections(origin, frontRightDownColor, frontRightDownReflections); + drawReflections(origin, frontLeftDownColor, frontLeftDownReflections); + drawReflections(origin, backRightDownColor, backRightDownReflections); + drawReflections(origin, backLeftDownColor, backLeftDownReflections); + + drawReflections(origin, frontColor, frontReflections); + drawReflections(origin, backColor, backReflections); + drawReflections(origin, leftColor, leftReflections); + drawReflections(origin, rightColor, rightReflections); + drawReflections(origin, upColor, upReflections); + drawReflections(origin, downColor, downReflections); } void AudioReflector::drawVector(const glm::vec3& start, const glm::vec3& end, const glm::vec3& color) { diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index ea379f2790..d15927dddc 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -37,13 +37,15 @@ private: void drawRays(); void drawVector(const glm::vec3& start, const glm::vec3& end, const glm::vec3& color); - void drawReflections(const glm::vec3& origin, const glm::vec3& direction, int bounces, const glm::vec3& color); - void echoReflections(const glm::vec3& origin, const glm::vec3& originalDirection, + void oldEchoReflections(const glm::vec3& origin, const glm::vec3& originalDirection, int bounces, const QByteArray& samples, unsigned int sampleTime, int sampleRate); + void echoReflections(const glm::vec3& origin, const QVector& reflections, const QByteArray& samples, + unsigned int sampleTime, int sampleRate); + QVector calculateReflections(const glm::vec3& origin, const glm::vec3& originalDirection, int maxBounces); - void newDrawReflections(const glm::vec3& origin, const glm::vec3& originalColor, const QVector& reflections); + void drawReflections(const glm::vec3& origin, const glm::vec3& originalColor, const QVector& reflections); }; diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 9bb63b4a34..d000b9cd6a 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -371,6 +371,11 @@ Menu::Menu() : false, appInstance->getAudio(), SLOT(toggleAudioSpatialProcessing())); + + addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingIncudeOriginal, + Qt::CTRL | Qt::SHIFT | Qt::Key_O, + true); + addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::LowPassFilter, Qt::CTRL | Qt::SHIFT | Qt::Key_F, false); diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 99df84784a..3d3961edaa 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -244,6 +244,7 @@ namespace MenuOption { const QString AudioNoiseReduction = "Audio Noise Reduction"; const QString AudioToneInjection = "Inject Test Tone"; const QString AudioSpatialProcessing = "Audio Spatial Processing"; + const QString AudioSpatialProcessingIncudeOriginal = "Audio Spatial Processing includes Original"; const QString EchoServerAudio = "Echo Server Audio"; const QString EchoLocalAudio = "Echo Local Audio"; const QString MuteAudio = "Mute Microphone"; From f45f30234f1ab669055af35af458f3f29cd12bc1 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 3 Apr 2014 23:03:06 -0700 Subject: [PATCH 143/595] more tweaks to reflections --- interface/src/AudioReflector.cpp | 417 +++++++++++++++---------------- interface/src/AudioReflector.h | 51 +++- 2 files changed, 243 insertions(+), 225 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 177d0ecb93..1562055be7 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -6,8 +6,17 @@ // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. // +#include + #include "AudioReflector.h" +AudioReflector::AudioReflector(QObject* parent) : + QObject(parent) +{ + reset(); +} + + void AudioReflector::render() { if (!_myAvatar) { return; // exit early if not set up correctly @@ -36,7 +45,7 @@ const float BOUNCE_ATTENUATION_FACTOR = 0.125f; const float PER_BOUNCE_ATTENUATION_ADJUSTMENT = 2.0f; // we don't grow larger than this, which means by the 4th bounce we don't get that much less quiet -const float MAX_BOUNCE_ATTENUATION = 0.9f; +const float MAX_BOUNCE_ATTENUATION = 0.99f; float getDistanceAttenuationCoefficient(float distance) { const float DISTANCE_SCALE = 2.5f; @@ -72,6 +81,97 @@ glm::vec3 getFaceNormal(BoxFace face) { return glm::vec3(0, 0, 0); //error case } +void AudioReflector::reset() { + _reflections = 0; + _averageAttenuation = 0.0f; + _maxAttenuation = 0.0f; + _minAttenuation = 0.0f; + _averageDelay = 0; + _maxDelay = 0; + _minDelay = 0; + + _reflections = _frontRightUpReflections.size() + + _frontLeftUpReflections.size() + + _backRightUpReflections.size() + + _backLeftUpReflections.size() + + _frontRightDownReflections.size() + + _frontLeftDownReflections.size() + + _backRightDownReflections.size() + + _backLeftDownReflections.size() + + _frontReflections.size() + + _backReflections.size() + + _leftReflections.size() + + _rightReflections.size() + + _upReflections.size() + + _downReflections.size(); + +} + +void AudioReflector::calculateAllReflections() { + + // only recalculate when we've moved... + // TODO: what about case where new voxels are added in front of us??? + if (_myAvatar->getHead()->getPosition() != _origin) { + QMutexLocker locker(&_mutex); + + qDebug() << "origin has changed..."; + qDebug(" _myAvatar->getHead()->getPosition()=%f,%f,%f", + _myAvatar->getHead()->getPosition().x, + _myAvatar->getHead()->getPosition().y, + _myAvatar->getHead()->getPosition().z); + + qDebug(" _origin=%f,%f,%f", + _origin.x, + _origin.y, + _origin.z); + + + quint64 start = usecTimestampNow(); + + _origin = _myAvatar->getHead()->getPosition(); + + glm::quat orientation = _myAvatar->getOrientation(); // _myAvatar->getHead()->getOrientation(); + glm::vec3 right = glm::normalize(orientation * IDENTITY_RIGHT); + glm::vec3 up = glm::normalize(orientation * IDENTITY_UP); + glm::vec3 front = glm::normalize(orientation * IDENTITY_FRONT); + glm::vec3 left = -right; + glm::vec3 down = -up; + glm::vec3 back = -front; + glm::vec3 frontRightUp = glm::normalize(front + right + up); + glm::vec3 frontLeftUp = glm::normalize(front + left + up); + glm::vec3 backRightUp = glm::normalize(back + right + up); + glm::vec3 backLeftUp = glm::normalize(back + left + up); + glm::vec3 frontRightDown = glm::normalize(front + right + down); + glm::vec3 frontLeftDown = glm::normalize(front + left + down); + glm::vec3 backRightDown = glm::normalize(back + right + down); + glm::vec3 backLeftDown = glm::normalize(back + left + down); + + const int BOUNCE_COUNT = 5; + + _frontRightUpReflections = calculateReflections(_origin, frontRightUp, BOUNCE_COUNT); + _frontLeftUpReflections = calculateReflections(_origin, frontLeftUp, BOUNCE_COUNT); + _backRightUpReflections = calculateReflections(_origin, backRightUp, BOUNCE_COUNT); + _backLeftUpReflections = calculateReflections(_origin, backLeftUp, BOUNCE_COUNT); + _frontRightDownReflections = calculateReflections(_origin, frontRightDown, BOUNCE_COUNT); + _frontLeftDownReflections = calculateReflections(_origin, frontLeftDown, BOUNCE_COUNT); + _backRightDownReflections = calculateReflections(_origin, backRightDown, BOUNCE_COUNT); + _backLeftDownReflections = calculateReflections(_origin, backLeftDown, BOUNCE_COUNT); + _frontReflections = calculateReflections(_origin, front, BOUNCE_COUNT); + _backReflections = calculateReflections(_origin, back, BOUNCE_COUNT); + _leftReflections = calculateReflections(_origin, left, BOUNCE_COUNT); + _rightReflections = calculateReflections(_origin, right, BOUNCE_COUNT); + _upReflections = calculateReflections(_origin, up, BOUNCE_COUNT); + _downReflections = calculateReflections(_origin, down, BOUNCE_COUNT); + + quint64 end = usecTimestampNow(); + + reset(); + + qDebug() << "Reflections recalculated in " << (end - start) << "usecs"; + + } +} + QVector AudioReflector::calculateReflections(const glm::vec3& origin, const glm::vec3& originalDirection, int maxBounces) { QVector reflectionPoints; glm::vec3 start = origin; @@ -150,6 +250,14 @@ void AudioReflector::echoReflections(const glm::vec3& origin, const QVector + #include #include "Audio.h" @@ -17,7 +19,7 @@ class AudioReflector : public QObject { Q_OBJECT public: - AudioReflector(QObject* parent = 0) : QObject(parent) { }; + AudioReflector(QObject* parent = NULL); void setVoxels(VoxelTree* voxels) { _voxels = voxels; } void setMyAvatar(MyAvatar* myAvatar) { _myAvatar = myAvatar; } @@ -25,6 +27,14 @@ public: void render(); + int getReflections() const { return _reflections; } + int getAverageDelayMsecs() const { return _averageDelay; } + float getAverageAttenuation() const { return _averageAttenuation; } + int getMaxDelayMsecs() const { return _maxDelay; } + float getMaxAttenuation() const { return _maxAttenuation; } + int getMinDelayMsecs() const { return _minDelay; } + float getMinAttenuation() const { return _minAttenuation; } + public slots: void processSpatialAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); @@ -37,15 +47,48 @@ private: void drawRays(); void drawVector(const glm::vec3& start, const glm::vec3& end, const glm::vec3& color); - void oldEchoReflections(const glm::vec3& origin, const glm::vec3& originalDirection, - int bounces, const QByteArray& samples, - unsigned int sampleTime, int sampleRate); void echoReflections(const glm::vec3& origin, const QVector& reflections, const QByteArray& samples, unsigned int sampleTime, int sampleRate); QVector calculateReflections(const glm::vec3& origin, const glm::vec3& originalDirection, int maxBounces); void drawReflections(const glm::vec3& origin, const glm::vec3& originalColor, const QVector& reflections); + + void calculateAllReflections(); + void reset(); + + int _reflections; + + int _delayCount; + int _totalDelay; + int _averageDelay; + int _maxDelay; + int _minDelay; + + int _attenuationCount; + float _totalAttenuation; + float _averageAttenuation; + float _maxAttenuation; + float _minAttenuation; + + glm::vec3 _origin; + QVector _frontRightUpReflections; + QVector _frontLeftUpReflections; + QVector _backRightUpReflections; + QVector _backLeftUpReflections; + QVector _frontRightDownReflections; + QVector _frontLeftDownReflections; + QVector _backRightDownReflections; + QVector _backLeftDownReflections; + QVector _frontReflections; + QVector _backReflections; + QVector _leftReflections; + QVector _rightReflections; + QVector _upReflections; + QVector _downReflections; + + QMutex _mutex; + }; From d706e23012c6d067e161531a7232959cab2b12b7 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 3 Apr 2014 23:47:31 -0700 Subject: [PATCH 144/595] Basic voxelization. --- interface/src/ui/MetavoxelEditor.cpp | 139 ++++++++++++++++++--- libraries/metavoxels/src/MetavoxelData.cpp | 9 +- libraries/metavoxels/src/MetavoxelData.h | 1 + libraries/metavoxels/src/SharedObject.cpp | 7 +- libraries/metavoxels/src/SharedObject.h | 5 +- 5 files changed, 138 insertions(+), 23 deletions(-) diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index 1c37ec9078..6471dd21b2 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -656,35 +656,45 @@ bool SetSpannerTool::appliesTo(const AttributePointer& attribute) const { return attribute == AttributeRegistry::getInstance()->getSpannersAttribute(); } -glm::vec3 DIRECTION_VECTORS[] = { glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f), - glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f), glm::vec3(0.0f, 0.0f, 1.0f) }; +glm::quat DIRECTION_ROTATIONS[] = { + rotationBetween(glm::vec3(-1.0f, 0.0f, 0.0f), IDENTITY_FRONT), + rotationBetween(glm::vec3(1.0f, 0.0f, 0.0f), IDENTITY_FRONT), + rotationBetween(glm::vec3(0.0f, -1.0f, 0.0f), IDENTITY_FRONT), + rotationBetween(glm::vec3(0.0f, 1.0f, 0.0f), IDENTITY_FRONT), + rotationBetween(glm::vec3(0.0f, 0.0f, -1.0f), IDENTITY_FRONT), + rotationBetween(glm::vec3(0.0f, 0.0f, 1.0f), IDENTITY_FRONT) }; /// Represents a view from one direction of the spanner to be voxelized. class DirectionImages { public: QImage color; QVector depth; + glm::vec3 minima; + glm::vec3 maxima; + glm::vec3 scale; }; class Voxelizer : public QRunnable { public: - Voxelizer(float size, const Box& bounds, const QVector& directionImages); + Voxelizer(float size, const Box& bounds, float granularity, const QVector& directionImages); virtual void run(); private: - void voxelize(const glm::vec3& minimum); + void voxelize(const glm::vec3& center); float _size; Box _bounds; + float _granularity; QVector _directionImages; }; -Voxelizer::Voxelizer(float size, const Box& bounds, const QVector& directionImages) : +Voxelizer::Voxelizer(float size, const Box& bounds, float granularity, const QVector& directionImages) : _size(size), _bounds(bounds), + _granularity(granularity), _directionImages(directionImages) { } @@ -694,13 +704,108 @@ void Voxelizer::run() { for (float x = _bounds.minimum.x + halfSize; x < _bounds.maximum.x; x += _size) { for (float y = _bounds.minimum.y + halfSize; y < _bounds.maximum.y; y += _size) { for (float z = _bounds.minimum.z + halfSize; z < _bounds.maximum.z; z += _size) { - + voxelize(glm::vec3(x, y, z)); } } } } -void Voxelizer::voxelize(const glm::vec3& minimum) { +class VoxelizationVisitor : public MetavoxelVisitor { +public: + + VoxelizationVisitor(const QVector& directionImages, const glm::vec3& center, float granularity); + + virtual int visit(MetavoxelInfo& info); + +private: + + QVector _directionImages; + glm::vec3 _center; + float _granularity; +}; + +VoxelizationVisitor::VoxelizationVisitor(const QVector& directionImages, + const glm::vec3& center, float granularity) : + MetavoxelVisitor(QVector(), QVector() << + AttributeRegistry::getInstance()->getColorAttribute()), + _directionImages(directionImages), + _center(center), + _granularity(granularity) { +} + +bool checkDisjoint(const DirectionImages& images, const glm::vec3& minimum, const glm::vec3& maximum) { + for (int x = qMax(0, (int)minimum.x), xmax = qMin(images.color.width(), (int)maximum.x); x < xmax; x++) { + for (int y = qMax(0, (int)minimum.y), ymax = qMin(images.color.height(), (int)maximum.y); y < ymax; y++) { + float depth = 1.0f - images.depth.at(y * images.color.width() + x); + if (depth - minimum.z >= 0.0f) { + return false; + } + } + } + return true; +} + +int VoxelizationVisitor::visit(MetavoxelInfo& info) { + float halfSize = info.size * 0.5f; + glm::vec3 center = info.minimum + _center + glm::vec3(halfSize, halfSize, halfSize); + if (info.size > _granularity) { + for (unsigned int i = 0; i < sizeof(DIRECTION_ROTATIONS) / sizeof(DIRECTION_ROTATIONS[0]); i++) { + glm::vec3 rotated = DIRECTION_ROTATIONS[i] * center; + const DirectionImages& images = _directionImages.at(i); + glm::vec3 relative = (rotated - images.minima) * images.scale; + glm::vec3 extents = images.scale * halfSize; + glm::vec3 minimum = relative - extents; + glm::vec3 maximum = relative + extents; + if (checkDisjoint(images, minimum, maximum)) { + info.outputValues[0] = AttributeValue(_outputs.at(0)); + return STOP_RECURSION; + } + } + return DEFAULT_ORDER; + } + QRgb closestColor; + float closestDistance = FLT_MAX; + for (unsigned int i = 0; i < sizeof(DIRECTION_ROTATIONS) / sizeof(DIRECTION_ROTATIONS[0]); i++) { + glm::vec3 rotated = DIRECTION_ROTATIONS[i] * center; + const DirectionImages& images = _directionImages.at(i); + glm::vec3 relative = (rotated - images.minima) * images.scale; + int x = qMax(qMin((int)glm::round(relative.x), images.color.width() - 1), 0); + int y = qMax(qMin((int)glm::round(relative.y), images.color.height() - 1), 0); + float depth = 1.0f - images.depth.at(y * images.color.width() + x); + float distance = depth - relative.z; + if (distance < 0.0f) { + info.outputValues[0] = AttributeValue(_outputs.at(0)); + return STOP_RECURSION; + } + QRgb color = images.color.pixel(x, y); + if (distance < EPSILON) { + info.outputValues[0] = AttributeValue(_outputs.at(0), encodeInline(color)); + return STOP_RECURSION; + } + if (distance < closestDistance) { + closestColor = color; + closestDistance = distance; + } + } + info.outputValues[0] = AttributeValue(_outputs.at(0), encodeInline(closestColor)); + return STOP_RECURSION; +} + +void Voxelizer::voxelize(const glm::vec3& center) { + MetavoxelData data; + data.setSize(_size); + + qDebug() << "Started voxelizing " << center.x << center.y << center.z; + + VoxelizationVisitor visitor(_directionImages, center, _granularity); + data.guide(visitor); + + qDebug() << "Finished voxelizing " << center.x << center.y << center.z; + + MetavoxelEditMessage edit = { QVariant::fromValue(SetDataEdit( + center - glm::vec3(_size, _size, _size) * 0.5f, data, false)) }; + QMetaObject::invokeMethod(Application::getInstance()->getMetavoxels(), "applyEdit", + Q_ARG(const MetavoxelEditMessage&, edit), Q_ARG(bool, true)); } void SetSpannerTool::applyEdit(const AttributePointer& attribute, const SharedObjectPointer& spanner) { @@ -725,12 +830,11 @@ void SetSpannerTool::applyEdit(const AttributePointer& attribute, const SharedOb QVector directionImages; - for (unsigned int i = 0; i < sizeof(DIRECTION_VECTORS) / sizeof(DIRECTION_VECTORS[0]); i++) { - glm::quat rotation = rotationBetween(DIRECTION_VECTORS[i], IDENTITY_FRONT); + for (unsigned int i = 0; i < sizeof(DIRECTION_ROTATIONS) / sizeof(DIRECTION_ROTATIONS[0]); i++) { glm::vec3 minima(FLT_MAX, FLT_MAX, FLT_MAX); glm::vec3 maxima(-FLT_MAX, -FLT_MAX, -FLT_MAX); for (int j = 0; j < Box::VERTEX_COUNT; j++) { - glm::vec3 rotated = rotation * cellBounds.getVertex(j); + glm::vec3 rotated = DIRECTION_ROTATIONS[i] * cellBounds.getVertex(j); minima = glm::min(minima, rotated); maxima = glm::max(maxima, rotated); } @@ -742,16 +846,20 @@ void SetSpannerTool::applyEdit(const AttributePointer& attribute, const SharedOb glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); - glOrtho(minima.x, maxima.x, minima.y, maxima.y, -minima.z, -maxima.z); + glOrtho(minima.x, maxima.x, minima.y, maxima.y, -maxima.z, -minima.z); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); - glm::vec3 axis = glm::axis(rotation); - glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); + glm::vec3 axis = glm::axis(DIRECTION_ROTATIONS[i]); + glRotatef(glm::degrees(glm::angle(DIRECTION_ROTATIONS[i])), axis.x, axis.y, axis.z); + + Application::getInstance()->setupWorldLight(); spannerData->getRenderer()->render(1.0f, glm::vec3(), 0.0f); - DirectionImages images = { QImage(width, height, QImage::Format_ARGB32), QVector(width * height) }; + DirectionImages images = { QImage(width, height, QImage::Format_ARGB32), + QVector(width * height), minima, maxima, glm::vec3(width / (maxima.x - minima.x), + height / (maxima.y - minima.y), 1.0f / (maxima.z - minima.z)) }; glReadPixels(0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, images.color.bits()); glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, images.depth.data()); directionImages.append(images); @@ -771,5 +879,6 @@ void SetSpannerTool::applyEdit(const AttributePointer& attribute, const SharedOb glViewport(0, 0, Application::getInstance()->getGLWidget()->width(), Application::getInstance()->getGLWidget()->height()); // send the images off to the lab for processing - QThreadPool::globalInstance()->start(new Voxelizer(size, cellBounds, directionImages)); + QThreadPool::globalInstance()->start(new Voxelizer(size, cellBounds, + spannerData->getVoxelizationGranularity(), directionImages)); } diff --git a/libraries/metavoxels/src/MetavoxelData.cpp b/libraries/metavoxels/src/MetavoxelData.cpp index efbc0b157d..f86406a507 100644 --- a/libraries/metavoxels/src/MetavoxelData.cpp +++ b/libraries/metavoxels/src/MetavoxelData.cpp @@ -373,7 +373,12 @@ static void setNode(const AttributeValue& value, MetavoxelNode*& node, const glm setNode(value, node, other, blend); return; } - if (!node) { + if (node) { + MetavoxelNode* oldNode = node; + node = new MetavoxelNode(value.getAttribute(), oldNode); + oldNode->decrementReferenceCount(value.getAttribute()); + + } else { node = new MetavoxelNode(value); } int index = 0; @@ -403,7 +408,7 @@ static void setNode(const AttributeValue& value, MetavoxelNode*& node, const glm void MetavoxelData::set(const glm::vec3& minimum, const MetavoxelData& data, bool blend) { // expand to fit the entire data - Box bounds = minimum + glm::vec3(data.getSize(), data.getSize(), data.getSize()); + Box bounds(minimum, minimum + glm::vec3(data.getSize(), data.getSize(), data.getSize())); while (!getBounds().contains(bounds)) { expand(); } diff --git a/libraries/metavoxels/src/MetavoxelData.h b/libraries/metavoxels/src/MetavoxelData.h index ed8b1a224c..4254b3bbb2 100644 --- a/libraries/metavoxels/src/MetavoxelData.h +++ b/libraries/metavoxels/src/MetavoxelData.h @@ -61,6 +61,7 @@ public: MetavoxelData& operator=(const MetavoxelData& other); + void setSize(float size) { _size = size; } float getSize() const { return _size; } glm::vec3 getMinimum() const { return glm::vec3(_size, _size, _size) * -0.5f; } diff --git a/libraries/metavoxels/src/SharedObject.cpp b/libraries/metavoxels/src/SharedObject.cpp index 36257a740f..64ea48e016 100644 --- a/libraries/metavoxels/src/SharedObject.cpp +++ b/libraries/metavoxels/src/SharedObject.cpp @@ -20,18 +20,17 @@ REGISTER_META_OBJECT(SharedObject) SharedObject::SharedObject() : _id(++_lastID), - _remoteID(0), - _referenceCount(0) { + _remoteID(0) { _weakHash.insert(_id, this); } void SharedObject::incrementReferenceCount() { - _referenceCount++; + _referenceCount.ref(); } void SharedObject::decrementReferenceCount() { - if (--_referenceCount == 0) { + if (!_referenceCount.deref()) { _weakHash.remove(_id); delete this; } diff --git a/libraries/metavoxels/src/SharedObject.h b/libraries/metavoxels/src/SharedObject.h index 435127fffd..2751a66db3 100644 --- a/libraries/metavoxels/src/SharedObject.h +++ b/libraries/metavoxels/src/SharedObject.h @@ -9,6 +9,7 @@ #ifndef __interface__SharedObject__ #define __interface__SharedObject__ +#include #include #include #include @@ -42,7 +43,7 @@ public: void setRemoteID(int remoteID) { _remoteID = remoteID; } - int getReferenceCount() const { return _referenceCount; } + int getReferenceCount() const { return _referenceCount.load(); } void incrementReferenceCount(); void decrementReferenceCount(); @@ -62,7 +63,7 @@ private: int _id; int _remoteID; - int _referenceCount; + QAtomicInt _referenceCount; static int _lastID; static WeakSharedObjectHash _weakHash; From dfaa98cc34f5e1713d5f9b5ddd94d433d2026345 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 3 Apr 2014 23:51:49 -0700 Subject: [PATCH 145/595] Blend when setting. --- interface/src/ui/MetavoxelEditor.cpp | 2 +- libraries/metavoxels/src/MetavoxelData.cpp | 14 ++++++-------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index 6471dd21b2..a7d9026582 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -803,7 +803,7 @@ void Voxelizer::voxelize(const glm::vec3& center) { qDebug() << "Finished voxelizing " << center.x << center.y << center.z; MetavoxelEditMessage edit = { QVariant::fromValue(SetDataEdit( - center - glm::vec3(_size, _size, _size) * 0.5f, data, false)) }; + center - glm::vec3(_size, _size, _size) * 0.5f, data, true)) }; QMetaObject::invokeMethod(Application::getInstance()->getMetavoxels(), "applyEdit", Q_ARG(const MetavoxelEditMessage&, edit), Q_ARG(bool, true)); } diff --git a/libraries/metavoxels/src/MetavoxelData.cpp b/libraries/metavoxels/src/MetavoxelData.cpp index f86406a507..f4d2870ad4 100644 --- a/libraries/metavoxels/src/MetavoxelData.cpp +++ b/libraries/metavoxels/src/MetavoxelData.cpp @@ -355,14 +355,12 @@ static void setNode(const AttributeValue& value, MetavoxelNode*& node, Metavoxel } OwnedAttributeValue oldValue = node->getAttributeValue(value.getAttribute()); node->blendAttributeValues(other->getAttributeValue(value.getAttribute()), oldValue); - if (other->isLeaf()) { - node->clearChildren(value.getAttribute()); - return; - } - for (int i = 0; i < MetavoxelNode::CHILD_COUNT; i++) { - MetavoxelNode* child = node->getChild(i); - setNode(oldValue, child, other->getChild(i), true); - node->setChild(i, child); + if (!other->isLeaf()) { + for (int i = 0; i < MetavoxelNode::CHILD_COUNT; i++) { + MetavoxelNode* child = node->getChild(i); + setNode(oldValue, child, other->getChild(i), true); + node->setChild(i, child); + } } node->mergeChildren(value.getAttribute()); } From 38022d2440114ea7acaf9005101d400a3efc3f9d Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Fri, 4 Apr 2014 00:33:33 -0700 Subject: [PATCH 146/595] Fix for voxelizing models. --- interface/src/Application.cpp | 11 +++++++---- interface/src/Application.h | 4 ++++ interface/src/ui/MetavoxelEditor.cpp | 2 ++ 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 18a3a228d6..7d3d5e9c19 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2229,8 +2229,7 @@ void Application::updateShadowMap() { glRotatef(glm::degrees(glm::angle(inverseRotation)), axis.x, axis.y, axis.z); // store view matrix without translation, which we'll use for precision-sensitive objects - glGetFloatv(GL_MODELVIEW_MATRIX, (GLfloat*)&_untranslatedViewMatrix); - _viewMatrixTranslation = glm::vec3(); + updateUntranslatedViewMatrix(); _avatarManager.renderAvatars(Avatar::SHADOW_RENDER_MODE); _particles.render(); @@ -2315,8 +2314,7 @@ void Application::displaySide(Camera& whichCamera, bool selfAvatarOnly) { glRotatef(-glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); // store view matrix without translation, which we'll use for precision-sensitive objects - glGetFloatv(GL_MODELVIEW_MATRIX, (GLfloat*)&_untranslatedViewMatrix); - _viewMatrixTranslation = -whichCamera.getPosition(); + updateUntranslatedViewMatrix(-whichCamera.getPosition()); glTranslatef(_viewMatrixTranslation.x, _viewMatrixTranslation.y, _viewMatrixTranslation.z); @@ -2447,6 +2445,11 @@ void Application::displaySide(Camera& whichCamera, bool selfAvatarOnly) { } } +void Application::updateUntranslatedViewMatrix(const glm::vec3& viewMatrixTranslation) { + glGetFloatv(GL_MODELVIEW_MATRIX, (GLfloat*)&_untranslatedViewMatrix); + _viewMatrixTranslation = viewMatrixTranslation; +} + void Application::loadTranslatedViewMatrix(const glm::vec3& translation) { glLoadMatrixf((const GLfloat*)&_untranslatedViewMatrix); glTranslatef(translation.x + _viewMatrixTranslation.x, translation.y + _viewMatrixTranslation.y, diff --git a/interface/src/Application.h b/interface/src/Application.h index fd2d6f2dfa..625974d0bd 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -203,6 +203,10 @@ public: void displaySide(Camera& whichCamera, bool selfAvatarOnly = false); + /// Stores the current modelview matrix as the untranslated view matrix to use for transforms and the supplied vector as + /// the view matrix translation. + void updateUntranslatedViewMatrix(const glm::vec3& viewMatrixTranslation = glm::vec3()); + /// Loads a view matrix that incorporates the specified model translation without the precision issues that can /// result from matrix multiplication at high translation magnitudes. void loadTranslatedViewMatrix(const glm::vec3& translation); diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index a7d9026582..024dd0c5d1 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -855,6 +855,8 @@ void SetSpannerTool::applyEdit(const AttributePointer& attribute, const SharedOb Application::getInstance()->setupWorldLight(); + Application::getInstance()->updateUntranslatedViewMatrix(); + spannerData->getRenderer()->render(1.0f, glm::vec3(), 0.0f); DirectionImages images = { QImage(width, height, QImage::Format_ARGB32), From 4c0f83913bc08c5c481d26b04906ae3a682837e3 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 4 Apr 2014 07:04:02 -0700 Subject: [PATCH 147/595] tweaks to bounce --- interface/src/AudioReflector.cpp | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 1562055be7..f61f411abc 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -38,12 +38,14 @@ int getDelayFromDistance(float distance) { return MS_DELAY_PER_METER * distance; } -const float BOUNCE_ATTENUATION_FACTOR = 0.125f; +// **option 1**: this is what we're using +const float PER_BOUNCE_ATTENUATION_FACTOR = 0.5f; +// **option 2**: we're not using these +const float BOUNCE_ATTENUATION_FACTOR = 0.125f; // each bounce we adjust our attenuation by this factor, the result is an asymptotically decreasing attenuation... // 0.125, 0.25, 0.5, ... const float PER_BOUNCE_ATTENUATION_ADJUSTMENT = 2.0f; - // we don't grow larger than this, which means by the 4th bounce we don't get that much less quiet const float MAX_BOUNCE_ATTENUATION = 0.99f; @@ -234,9 +236,12 @@ void AudioReflector::echoReflections(const glm::vec3& origin, const QVector Date: Fri, 4 Apr 2014 09:20:40 -0700 Subject: [PATCH 149/595] add processing of DTLS datagrams to domain-server --- domain-server/src/DomainServer.cpp | 13 +++-- libraries/shared/src/DTLSSession.cpp | 6 +- libraries/shared/src/NodeList.cpp | 82 ++++++++++++++++------------ 3 files changed, 59 insertions(+), 42 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index efecd5d322..82f908fcf9 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -101,7 +101,7 @@ bool DomainServer::optionallySetupDTLS() { gnutls_key_generate(_cookieKey, GNUTLS_COOKIE_KEY_SIZE); _priorityCache = new gnutls_priority_t; - const char DTLS_PRIORITY_STRING[] = "PERFORMANCE:-VERS-TLS-ALL:+VERS-DTLS1.0:%SERVER_PRECEDENCE"; + const char DTLS_PRIORITY_STRING[] = "PERFORMANCE:-VERS-TLS-ALL:+VERS-DTLS1.2:%SERVER_PRECEDENCE"; gnutls_priority_init(_priorityCache, DTLS_PRIORITY_STRING, NULL); _isUsingDTLS = true; @@ -616,8 +616,6 @@ void DomainServer::readAvailableDTLSDatagrams() { static socklen_t sockAddrSize = sizeof(senderSockAddr); while (dtlsSocket.hasPendingDatagrams()) { - qDebug() << "Looking at a datagram"; - // check if we have an active DTLS session for this sender QByteArray peekDatagram(dtlsSocket.pendingDatagramSize(), 0); @@ -642,7 +640,14 @@ void DomainServer::readAvailableDTLSDatagrams() { } } else { // pull the data from this user off the stack and process it - dtlsSocket.readDatagram(peekDatagram.data(), peekDatagram.size()); + int receiveCode = gnutls_record_recv(*existingSession->getGnuTLSSession(), + peekDatagram.data(), peekDatagram.size()); + if (receiveCode > 0) { + processDatagram(peekDatagram, senderHifiSockAddr); + } else if (gnutls_error_is_fatal(receiveCode)) { + qDebug() << "Fatal error -" << gnutls_strerror(receiveCode) << "- during DTLS handshake with" + << senderHifiSockAddr; + } } } else { // first we verify the cookie diff --git a/libraries/shared/src/DTLSSession.cpp b/libraries/shared/src/DTLSSession.cpp index 9d30ab8148..07dadef54c 100644 --- a/libraries/shared/src/DTLSSession.cpp +++ b/libraries/shared/src/DTLSSession.cpp @@ -54,9 +54,8 @@ ssize_t DTLSSession::socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t if (pulledSockAddr == session->_destinationSocket) { // bytes received from the correct sender, return number of bytes received qDebug() << "Received" << bytesReceived << "on DTLS socket from" << pulledSockAddr; + qDebug() << QByteArray(reinterpret_cast(buffer), bytesReceived).toHex(); return bytesReceived; - } else { - qDebug() << pulledSockAddr << "is not" << session->_destinationSocket; } // we pulled a packet not matching this session, so output that @@ -71,6 +70,7 @@ ssize_t DTLSSession::socketPush(gnutls_transport_ptr_t ptr, const void* buffer, QUdpSocket& dtlsSocket = session->_dtlsSocket; qDebug() << "Pushing a message of size" << size << "to" << session->_destinationSocket; + qDebug() << QByteArray(reinterpret_cast(buffer), size).toHex(); return dtlsSocket.writeDatagram(reinterpret_cast(buffer), size, session->_destinationSocket.getAddress(), session->_destinationSocket.getPort()); } @@ -87,7 +87,7 @@ DTLSSession::DTLSSession(int end, QUdpSocket& dtlsSocket, HifiSockAddr& destinat gnutls_dtls_set_mtu(_gnutlsSession, DTLS_MAX_MTU); const unsigned int DTLS_TOTAL_CONNECTION_TIMEOUT = 10 * DOMAIN_SERVER_CHECK_IN_MSECS; - gnutls_dtls_set_timeouts(_gnutlsSession, 0, DTLS_TOTAL_CONNECTION_TIMEOUT); + gnutls_dtls_set_timeouts(_gnutlsSession, 1, DTLS_TOTAL_CONNECTION_TIMEOUT); gnutls_transport_set_ptr(_gnutlsSession, this); gnutls_transport_set_push_function(_gnutlsSession, socketPush); diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 50339947ef..705de5afec 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -323,44 +323,56 @@ void NodeList::sendDomainServerCheckIn() { } else if (!_domainHandler.getIP().isNull()) { DTLSClientSession* dtlsSession = _domainHandler.getDTLSSession(); + bool isUsingDTLS = false; - if (dtlsSession && dtlsSession->completedHandshake()) { - qDebug() << "we can send a DTLS check in!"; - } else { - // construct the DS check in packet - QUuid packetUUID = (!_sessionUUID.isNull() ? _sessionUUID : _domainHandler.getAssignmentUUID()); - - QByteArray domainServerPacket = byteArrayWithPopulatedHeader(PacketTypeDomainListRequest, packetUUID); - QDataStream packetStream(&domainServerPacket, QIODevice::Append); - - // pack our data to send to the domain-server - packetStream << _ownerType << _publicSockAddr - << HifiSockAddr(QHostAddress(getHostOrderLocalAddress()), _nodeSocket.localPort()) - << (quint8) _nodeTypesOfInterest.size(); - - // copy over the bytes for node types of interest, if required - foreach (NodeType_t nodeTypeOfInterest, _nodeTypesOfInterest) { - packetStream << nodeTypeOfInterest; + if (dtlsSession) { + if (!dtlsSession->completedHandshake()) { + // if the handshake process is not complete then we can't check in, so return + return; + } else { + isUsingDTLS = true; } - + } + + // construct the DS check in packet + QUuid packetUUID = (!_sessionUUID.isNull() ? _sessionUUID : _domainHandler.getAssignmentUUID()); + + QByteArray domainServerPacket = byteArrayWithPopulatedHeader(PacketTypeDomainListRequest, packetUUID); + QDataStream packetStream(&domainServerPacket, QIODevice::Append); + + // pack our data to send to the domain-server + packetStream << _ownerType << _publicSockAddr + << HifiSockAddr(QHostAddress(getHostOrderLocalAddress()), _nodeSocket.localPort()) + << (quint8) _nodeTypesOfInterest.size(); + + // copy over the bytes for node types of interest, if required + foreach (NodeType_t nodeTypeOfInterest, _nodeTypesOfInterest) { + packetStream << nodeTypeOfInterest; + } + + if (!isUsingDTLS) { writeDatagram(domainServerPacket, _domainHandler.getSockAddr(), QUuid()); - const int NUM_DOMAIN_SERVER_CHECKINS_PER_STUN_REQUEST = 5; - static unsigned int numDomainCheckins = 0; - - // send a STUN request every Nth domain server check in so we update our public socket, if required - if (numDomainCheckins++ % NUM_DOMAIN_SERVER_CHECKINS_PER_STUN_REQUEST == 0) { - sendSTUNRequest(); - } - - if (_numNoReplyDomainCheckIns >= MAX_SILENT_DOMAIN_SERVER_CHECK_INS) { - // we haven't heard back from DS in MAX_SILENT_DOMAIN_SERVER_CHECK_INS - // so emit our signal that indicates that - emit limitOfSilentDomainCheckInsReached(); - } - - // increment the count of un-replied check-ins - _numNoReplyDomainCheckIns++; - } + } else { + gnutls_record_send(*dtlsSession->getGnuTLSSession(), domainServerPacket.data(), domainServerPacket.size()); + } + + + const int NUM_DOMAIN_SERVER_CHECKINS_PER_STUN_REQUEST = 5; + static unsigned int numDomainCheckins = 0; + + // send a STUN request every Nth domain server check in so we update our public socket, if required + if (numDomainCheckins++ % NUM_DOMAIN_SERVER_CHECKINS_PER_STUN_REQUEST == 0) { + sendSTUNRequest(); + } + + if (_numNoReplyDomainCheckIns >= MAX_SILENT_DOMAIN_SERVER_CHECK_INS) { + // we haven't heard back from DS in MAX_SILENT_DOMAIN_SERVER_CHECK_INS + // so emit our signal that indicates that + emit limitOfSilentDomainCheckInsReached(); + } + + // increment the count of un-replied check-ins + _numNoReplyDomainCheckIns++; } } From efd176f93ceaee2cda497253f6273c49f0d56592 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 4 Apr 2014 09:56:57 -0700 Subject: [PATCH 150/595] complete check in and heartbeat via DTLS --- domain-server/src/DomainServer.cpp | 31 ++++++++++++++++-------- libraries/shared/src/DTLSSession.cpp | 18 ++++++++++++-- libraries/shared/src/DTLSSession.h | 2 ++ libraries/shared/src/DomainHandler.cpp | 5 ++-- libraries/shared/src/DomainHandler.h | 3 ++- libraries/shared/src/LimitedNodeList.cpp | 2 +- libraries/shared/src/NodeList.cpp | 31 +++++++++++++++++++++--- libraries/shared/src/NodeList.h | 3 +++ 8 files changed, 76 insertions(+), 19 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 82f908fcf9..205661aae2 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -483,6 +483,9 @@ void DomainServer::sendDomainListToNode(const SharedNodePointer& node, const Hif LimitedNodeList* nodeList = LimitedNodeList::getInstance(); if (nodeInterestList.size() > 0) { + + DTLSServerSession* dtlsSession = _isUsingDTLS ? _dtlsSessions[senderSockAddr] : NULL; + // if the node has any interest types, send back those nodes as well foreach (const SharedNodePointer& otherNode, nodeList->getNodeHash()) { @@ -516,7 +519,11 @@ void DomainServer::sendDomainListToNode(const SharedNodePointer& node, const Hif // we need to break here and start a new packet // so send the current one - nodeList->writeDatagram(broadcastPacket, node, senderSockAddr); + if (!dtlsSession) { + nodeList->writeDatagram(broadcastPacket, node, senderSockAddr); + } else { + dtlsSession->writeDatagram(broadcastPacket); + } // reset the broadcastPacket structure broadcastPacket.resize(numBroadcastPacketLeadBytes); @@ -527,10 +534,14 @@ void DomainServer::sendDomainListToNode(const SharedNodePointer& node, const Hif broadcastPacket.append(nodeByteArray); } } + + // always write the last broadcastPacket + if (!dtlsSession) { + nodeList->writeDatagram(broadcastPacket, node, senderSockAddr); + } else { + dtlsSession->writeDatagram(broadcastPacket); + } } - - // always write the last broadcastPacket - nodeList->writeDatagram(broadcastPacket, node, senderSockAddr); } void DomainServer::readAvailableDatagrams() { @@ -640,12 +651,12 @@ void DomainServer::readAvailableDTLSDatagrams() { } } else { // pull the data from this user off the stack and process it - int receiveCode = gnutls_record_recv(*existingSession->getGnuTLSSession(), - peekDatagram.data(), peekDatagram.size()); - if (receiveCode > 0) { - processDatagram(peekDatagram, senderHifiSockAddr); - } else if (gnutls_error_is_fatal(receiveCode)) { - qDebug() << "Fatal error -" << gnutls_strerror(receiveCode) << "- during DTLS handshake with" + int receivedBytes = gnutls_record_recv(*existingSession->getGnuTLSSession(), + peekDatagram.data(), peekDatagram.size()); + if (receivedBytes > 0) { + processDatagram(peekDatagram.left(receivedBytes), senderHifiSockAddr); + } else if (gnutls_error_is_fatal(receivedBytes)) { + qDebug() << "Fatal error -" << gnutls_strerror(receivedBytes) << "- during DTLS handshake with" << senderHifiSockAddr; } } diff --git a/libraries/shared/src/DTLSSession.cpp b/libraries/shared/src/DTLSSession.cpp index 07dadef54c..b8b3efddae 100644 --- a/libraries/shared/src/DTLSSession.cpp +++ b/libraries/shared/src/DTLSSession.cpp @@ -11,6 +11,8 @@ #include "NodeList.h" #include "DTLSSession.h" +#define DTLS_VERBOSE_DEBUG 0 + int DTLSSession::socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms) { DTLSSession* session = static_cast(ptr); QUdpSocket& dtlsSocket = session->_dtlsSocket; @@ -47,14 +49,19 @@ ssize_t DTLSSession::socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t pulledSockAddr.getAddressPointer(), pulledSockAddr.getPortPointer()); if (bytesReceived == -1) { // no data to pull, return -1 +#if DTLS_VERBOSE_DEBUG qDebug() << "Received no data on call to readDatagram"; +#endif return bytesReceived; } if (pulledSockAddr == session->_destinationSocket) { // bytes received from the correct sender, return number of bytes received + +#if DTLS_VERBOSE_DEBUG qDebug() << "Received" << bytesReceived << "on DTLS socket from" << pulledSockAddr; - qDebug() << QByteArray(reinterpret_cast(buffer), bytesReceived).toHex(); +#endif + return bytesReceived; } @@ -69,8 +76,10 @@ ssize_t DTLSSession::socketPush(gnutls_transport_ptr_t ptr, const void* buffer, DTLSSession* session = static_cast(ptr); QUdpSocket& dtlsSocket = session->_dtlsSocket; +#if DTLS_VERBOSE_DEBUG qDebug() << "Pushing a message of size" << size << "to" << session->_destinationSocket; - qDebug() << QByteArray(reinterpret_cast(buffer), size).toHex(); +#endif + return dtlsSocket.writeDatagram(reinterpret_cast(buffer), size, session->_destinationSocket.getAddress(), session->_destinationSocket.getPort()); } @@ -93,4 +102,9 @@ DTLSSession::DTLSSession(int end, QUdpSocket& dtlsSocket, HifiSockAddr& destinat gnutls_transport_set_push_function(_gnutlsSession, socketPush); gnutls_transport_set_pull_function(_gnutlsSession, socketPull); gnutls_transport_set_pull_timeout_function(_gnutlsSession, socketPullTimeout); +} + +qint64 DTLSSession::writeDatagram(const QByteArray& datagram) { + // we don't need to put a hash in this packet, so just send it off + return gnutls_record_send(_gnutlsSession, datagram.data(), datagram.size()); } \ No newline at end of file diff --git a/libraries/shared/src/DTLSSession.h b/libraries/shared/src/DTLSSession.h index 01e0e187e8..a06ddc00ad 100644 --- a/libraries/shared/src/DTLSSession.h +++ b/libraries/shared/src/DTLSSession.h @@ -24,6 +24,8 @@ public: static ssize_t socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t size); static ssize_t socketPush(gnutls_transport_ptr_t ptr, const void* buffer, size_t size); + qint64 writeDatagram(const QByteArray& datagram); + gnutls_session_t* getGnuTLSSession() { return &_gnutlsSession; } bool completedHandshake() const { return _completedHandshake; } diff --git a/libraries/shared/src/DomainHandler.cpp b/libraries/shared/src/DomainHandler.cpp index 00278689a2..59b7f73e0d 100644 --- a/libraries/shared/src/DomainHandler.cpp +++ b/libraries/shared/src/DomainHandler.cpp @@ -115,8 +115,6 @@ void DomainHandler::setHostname(const QString& hostname) { void DomainHandler::completeDTLSHandshake() { int handshakeReturn = gnutls_handshake(*_dtlsSession->getGnuTLSSession()); - qDebug() << "handshake return is" << handshakeReturn; - if (handshakeReturn == 0) { // we've shaken hands, so we're good to go now _dtlsSession->setCompletedHandshake(true); @@ -125,6 +123,9 @@ void DomainHandler::completeDTLSHandshake() { delete _handshakeTimer; _handshakeTimer = NULL; + // emit a signal so NodeList can handle incoming DTLS packets + emit completedDTLSHandshake(); + } else if (gnutls_error_is_fatal(handshakeReturn)) { // this was a fatal error handshaking, so remove this session qDebug() << "Fatal error -" << gnutls_strerror(handshakeReturn) diff --git a/libraries/shared/src/DomainHandler.h b/libraries/shared/src/DomainHandler.h index f53cbd5689..b8351653f6 100644 --- a/libraries/shared/src/DomainHandler.h +++ b/libraries/shared/src/DomainHandler.h @@ -60,7 +60,8 @@ private slots: signals: void hostnameChanged(const QString& hostname); void connectedToDomain(const QString& hostname); - void initializedDTLSSession(); + void completedDTLSHandshake(); + private: void reset(); void initializeDTLSSession(); diff --git a/libraries/shared/src/LimitedNodeList.cpp b/libraries/shared/src/LimitedNodeList.cpp index c71f3c13c9..ca377e553c 100644 --- a/libraries/shared/src/LimitedNodeList.cpp +++ b/libraries/shared/src/LimitedNodeList.cpp @@ -173,7 +173,7 @@ bool LimitedNodeList::packetVersionAndHashMatch(const QByteArray& packet) { } qint64 LimitedNodeList::writeDatagram(const QByteArray& datagram, const HifiSockAddr& destinationSockAddr, - const QUuid& connectionSecret) { + const QUuid& connectionSecret) { QByteArray datagramCopy = datagram; if (!connectionSecret.isNull()) { diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 705de5afec..50fa0269ef 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -65,6 +65,9 @@ NodeList::NodeList(char newOwnerType, unsigned short socketListenPort, unsigned // clear our NodeList when logout is requested connect(&AccountManager::getInstance(), &AccountManager::logoutComplete , this, &NodeList::reset); + + // perform a function when DTLS handshake is completed + connect(&_domainHandler, &DomainHandler::completedDTLSHandshake, this, &NodeList::completedDTLSHandshake); } qint64 NodeList::sendStatsToDomainServer(const QJsonObject& statsObject) { @@ -111,6 +114,28 @@ void NodeList::timePingReply(const QByteArray& packet, const SharedNodePointer& } } +void NodeList::completedDTLSHandshake() { + // at this point, we've got a DTLS socket + // make this NodeList the handler of DTLS packets + connect(_dtlsSocket, &QUdpSocket::readyRead, this, &NodeList::processAvailableDTLSDatagrams); +} + +void NodeList::processAvailableDTLSDatagrams() { + while (_dtlsSocket->hasPendingDatagrams()) { + QByteArray dtlsPacket(_dtlsSocket->pendingDatagramSize(), 0); + + // pull the data from this user off the stack and process it + int receivedBytes = gnutls_record_recv(*_domainHandler.getDTLSSession()->getGnuTLSSession(), + dtlsPacket.data(), dtlsPacket.size()); + if (receivedBytes > 0) { + // successful data receive, hand this off to processNodeData + processNodeData(_domainHandler.getSockAddr(), dtlsPacket.left(receivedBytes)); + } else if (gnutls_error_is_fatal(receivedBytes)) { + qDebug() << "Fatal error -" << gnutls_strerror(receivedBytes) << "- receiving DTLS packet from domain-server."; + } + } +} + void NodeList::processNodeData(const HifiSockAddr& senderSockAddr, const QByteArray& packet) { switch (packetTypeForPacket(packet)) { case PacketTypeDomainList: { @@ -342,8 +367,8 @@ void NodeList::sendDomainServerCheckIn() { // pack our data to send to the domain-server packetStream << _ownerType << _publicSockAddr - << HifiSockAddr(QHostAddress(getHostOrderLocalAddress()), _nodeSocket.localPort()) - << (quint8) _nodeTypesOfInterest.size(); + << HifiSockAddr(QHostAddress(getHostOrderLocalAddress()), _nodeSocket.localPort()) + << (quint8) _nodeTypesOfInterest.size(); // copy over the bytes for node types of interest, if required foreach (NodeType_t nodeTypeOfInterest, _nodeTypesOfInterest) { @@ -353,7 +378,7 @@ void NodeList::sendDomainServerCheckIn() { if (!isUsingDTLS) { writeDatagram(domainServerPacket, _domainHandler.getSockAddr(), QUuid()); } else { - gnutls_record_send(*dtlsSession->getGnuTLSSession(), domainServerPacket.data(), domainServerPacket.size()); + dtlsSession->writeDatagram(domainServerPacket); } diff --git a/libraries/shared/src/NodeList.h b/libraries/shared/src/NodeList.h index 625d7098ce..c7598eb7d0 100644 --- a/libraries/shared/src/NodeList.h +++ b/libraries/shared/src/NodeList.h @@ -67,6 +67,7 @@ public: void resetNodeInterestSet() { _nodeTypesOfInterest.clear(); } void processNodeData(const HifiSockAddr& senderSockAddr, const QByteArray& packet); + int processDomainServerList(const QByteArray& packet); void setAssignmentServerSocket(const HifiSockAddr& serverSocket) { _assignmentServerSocket = serverSocket; } @@ -82,6 +83,8 @@ public slots: void reset(); void sendDomainServerCheckIn(); void pingInactiveNodes(); + void completedDTLSHandshake(); + void processAvailableDTLSDatagrams(); signals: void limitOfSilentDomainCheckInsReached(); private: From f6c98a1cc23107f2fa0c416510c1b0afde4d6e78 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Fri, 4 Apr 2014 10:40:55 -0700 Subject: [PATCH 151/595] fix bug in gun.js: unplayed target delete sound --- examples/gun.js | 1 - 1 file changed, 1 deletion(-) diff --git a/examples/gun.js b/examples/gun.js index e358e6b391..3edb823bd1 100644 --- a/examples/gun.js +++ b/examples/gun.js @@ -176,7 +176,6 @@ function particleCollisionWithParticle(particle1, particle2) { print("hit, msecs = " + msecs); Particles.deleteParticle(particle1); Particles.deleteParticle(particle2); - audioOptions.position = newPosition; audioOptions.position = Vec3.sum(Camera.getPosition(), Quat.getFront(Camera.getOrientation())); Audio.playSound(targetHitSound, audioOptions); } From 5e2b8bb2c3296095278bd59c74443368ff350ae6 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Fri, 4 Apr 2014 10:43:06 -0700 Subject: [PATCH 152/595] connect SIGNAL to SIGNAL to avoid forwarding slot --- interface/src/Application.cpp | 4 ++-- libraries/particles/src/ParticlesScriptingInterface.h | 11 ----------- 2 files changed, 2 insertions(+), 13 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 21fefac6f1..7ba3e5c631 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1567,12 +1567,12 @@ void Application::init() { connect(&_particleCollisionSystem, SIGNAL(particleCollisionWithVoxel(const ParticleID&, const VoxelDetail&, const glm::vec3&)), ScriptEngine::getParticlesScriptingInterface(), - SLOT(forwardParticleCollisionWithVoxel(const ParticleID&, const VoxelDetail&, const glm::vec3&))); + SIGNAL(particleCollisionWithVoxels(const ParticleID&, const VoxelDetail&, const glm::vec3&))); connect(&_particleCollisionSystem, SIGNAL(particleCollisionWithParticle(const ParticleID&, const ParticleID&, const glm::vec3&)), ScriptEngine::getParticlesScriptingInterface(), - SLOT(forwardParticleCollisionWithParticle(const ParticleID&, const ParticleID&, const glm::vec3&))); + SIGNAL(particleCollisionWithParticle(const ParticleID&, const ParticleID&, const glm::vec3&))); _audio.init(_glWidget); diff --git a/libraries/particles/src/ParticlesScriptingInterface.h b/libraries/particles/src/ParticlesScriptingInterface.h index af5f76a6af..24bbad9e3e 100644 --- a/libraries/particles/src/ParticlesScriptingInterface.h +++ b/libraries/particles/src/ParticlesScriptingInterface.h @@ -27,17 +27,6 @@ public: void setParticleTree(ParticleTree* particleTree) { _particleTree = particleTree; } ParticleTree* getParticleTree(ParticleTree*) { return _particleTree; } -private slots: - /// inbound slots for external collision systems - void forwardParticleCollisionWithVoxel(const ParticleID& particleID, - const VoxelDetail& voxel, const glm::vec3& penetration) { - emit particleCollisionWithVoxel(particleID, voxel, penetration); - } - - void forwardParticleCollisionWithParticle(const ParticleID& idA, const ParticleID& idB, const glm::vec3& penetration) { - emit particleCollisionWithParticle(idA, idB, penetration); - } - public slots: /// adds a particle with the specific properties ParticleID addParticle(const ParticleProperties& properties); From c8409046429d3cd65dc347f064344fcfcfac7c5d Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 4 Apr 2014 10:44:15 -0700 Subject: [PATCH 153/595] output a message when handshake has completed with a client --- libraries/shared/src/DTLSSession.cpp | 5 +++++ libraries/shared/src/DTLSSession.h | 5 ++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/libraries/shared/src/DTLSSession.cpp b/libraries/shared/src/DTLSSession.cpp index b8b3efddae..8278ad93ed 100644 --- a/libraries/shared/src/DTLSSession.cpp +++ b/libraries/shared/src/DTLSSession.cpp @@ -104,6 +104,11 @@ DTLSSession::DTLSSession(int end, QUdpSocket& dtlsSocket, HifiSockAddr& destinat gnutls_transport_set_pull_timeout_function(_gnutlsSession, socketPullTimeout); } +void DTLSSession::setCompletedHandshake(bool completedHandshake) { + _completedHandshake = completedHandshake; + qDebug() << "Completed DTLS handshake with" << _destinationSocket; +} + qint64 DTLSSession::writeDatagram(const QByteArray& datagram) { // we don't need to put a hash in this packet, so just send it off return gnutls_record_send(_gnutlsSession, datagram.data(), datagram.size()); diff --git a/libraries/shared/src/DTLSSession.h b/libraries/shared/src/DTLSSession.h index a06ddc00ad..e9b5267592 100644 --- a/libraries/shared/src/DTLSSession.h +++ b/libraries/shared/src/DTLSSession.h @@ -29,12 +29,11 @@ public: gnutls_session_t* getGnuTLSSession() { return &_gnutlsSession; } bool completedHandshake() const { return _completedHandshake; } - void setCompletedHandshake(bool completedHandshake) { _completedHandshake = completedHandshake; } - + void setCompletedHandshake(bool completedHandshake); protected: QUdpSocket& _dtlsSocket; - gnutls_session_t _gnutlsSession; HifiSockAddr _destinationSocket; + gnutls_session_t _gnutlsSession; bool _completedHandshake; }; From e2224e0f0c8e715b0b49168712f8f2a8bfe1c9f9 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 4 Apr 2014 10:56:04 -0700 Subject: [PATCH 154/595] cleanup node silence timing and use for DTLS timeouts --- animation-server/src/AnimationServer.cpp | 2 +- domain-server/src/DomainServer.cpp | 2 +- interface/src/Application.cpp | 2 +- libraries/shared/src/DTLSSession.cpp | 5 +++-- libraries/shared/src/LimitedNodeList.cpp | 2 +- libraries/shared/src/LimitedNodeList.h | 2 +- libraries/shared/src/ThreadedAssignment.cpp | 2 +- 7 files changed, 9 insertions(+), 8 deletions(-) diff --git a/animation-server/src/AnimationServer.cpp b/animation-server/src/AnimationServer.cpp index e92169bcfa..61a3dc4aa9 100644 --- a/animation-server/src/AnimationServer.cpp +++ b/animation-server/src/AnimationServer.cpp @@ -801,7 +801,7 @@ AnimationServer::AnimationServer(int &argc, char **argv) : QTimer* silentNodeTimer = new QTimer(this); connect(silentNodeTimer, SIGNAL(timeout()), nodeList, SLOT(removeSilentNodes())); - silentNodeTimer->start(NODE_SILENCE_THRESHOLD_USECS / 1000); + silentNodeTimer->start(NODE_SILENCE_THRESHOLD_MSECS); connect(&nodeList->getNodeSocket(), SIGNAL(readyRead()), SLOT(readPendingDatagrams())); } diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 205661aae2..12df8a4ada 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -216,7 +216,7 @@ void DomainServer::setupNodeListAndAssignments(const QUuid& sessionUUID) { QTimer* silentNodeTimer = new QTimer(this); connect(silentNodeTimer, SIGNAL(timeout()), nodeList, SLOT(removeSilentNodes())); - silentNodeTimer->start(NODE_SILENCE_THRESHOLD_USECS / 1000); + silentNodeTimer->start(NODE_SILENCE_THRESHOLD_MSECS); connect(&nodeList->getNodeSocket(), SIGNAL(readyRead()), SLOT(readAvailableDatagrams())); diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 4ffdf5b2b7..548b5ac702 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -274,7 +274,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : QTimer* silentNodeTimer = new QTimer(); connect(silentNodeTimer, SIGNAL(timeout()), nodeList, SLOT(removeSilentNodes())); silentNodeTimer->moveToThread(_nodeThread); - silentNodeTimer->start(NODE_SILENCE_THRESHOLD_USECS / 1000); + silentNodeTimer->start(NODE_SILENCE_THRESHOLD_MSECS); // send the identity packet for our avatar each second to our avatar mixer QTimer* identityPacketTimer = new QTimer(); diff --git a/libraries/shared/src/DTLSSession.cpp b/libraries/shared/src/DTLSSession.cpp index 8278ad93ed..9b009730b4 100644 --- a/libraries/shared/src/DTLSSession.cpp +++ b/libraries/shared/src/DTLSSession.cpp @@ -95,8 +95,9 @@ DTLSSession::DTLSSession(int end, QUdpSocket& dtlsSocket, HifiSockAddr& destinat const unsigned int DTLS_MAX_MTU = 1452; gnutls_dtls_set_mtu(_gnutlsSession, DTLS_MAX_MTU); - const unsigned int DTLS_TOTAL_CONNECTION_TIMEOUT = 10 * DOMAIN_SERVER_CHECK_IN_MSECS; - gnutls_dtls_set_timeouts(_gnutlsSession, 1, DTLS_TOTAL_CONNECTION_TIMEOUT); + const unsigned int DTLS_HANDSHAKE_RETRANSMISSION_TIMEOUT = DOMAIN_SERVER_CHECK_IN_MSECS; + const unsigned int DTLS_TOTAL_CONNECTION_TIMEOUT = 2 * NODE_SILENCE_THRESHOLD_MSECS; + gnutls_dtls_set_timeouts(_gnutlsSession, DTLS_HANDSHAKE_RETRANSMISSION_TIMEOUT, DTLS_TOTAL_CONNECTION_TIMEOUT); gnutls_transport_set_ptr(_gnutlsSession, this); gnutls_transport_set_push_function(_gnutlsSession, socketPush); diff --git a/libraries/shared/src/LimitedNodeList.cpp b/libraries/shared/src/LimitedNodeList.cpp index ca377e553c..e9fdaa493c 100644 --- a/libraries/shared/src/LimitedNodeList.cpp +++ b/libraries/shared/src/LimitedNodeList.cpp @@ -426,7 +426,7 @@ void LimitedNodeList::removeSilentNodes() { node->getMutex().lock(); - if ((usecTimestampNow() - node->getLastHeardMicrostamp()) > NODE_SILENCE_THRESHOLD_USECS) { + if ((usecTimestampNow() - node->getLastHeardMicrostamp()) > (NODE_SILENCE_THRESHOLD_MSECS * 1000)) { // call our private method to kill this node (removes it and emits the right signal) nodeItem = killNodeAtHashIterator(nodeItem); } else { diff --git a/libraries/shared/src/LimitedNodeList.h b/libraries/shared/src/LimitedNodeList.h index 3688ddfdb4..adbc94e8d2 100644 --- a/libraries/shared/src/LimitedNodeList.h +++ b/libraries/shared/src/LimitedNodeList.h @@ -36,7 +36,7 @@ const int MAX_PACKET_SIZE = 1500; -const quint64 NODE_SILENCE_THRESHOLD_USECS = 2 * 1000 * 1000; +const quint64 NODE_SILENCE_THRESHOLD_MSECS = 2 * 1000; extern const char SOLO_NODE_TYPES[2]; diff --git a/libraries/shared/src/ThreadedAssignment.cpp b/libraries/shared/src/ThreadedAssignment.cpp index b31d282f64..82bea4e279 100644 --- a/libraries/shared/src/ThreadedAssignment.cpp +++ b/libraries/shared/src/ThreadedAssignment.cpp @@ -45,7 +45,7 @@ void ThreadedAssignment::commonInit(const QString& targetName, NodeType_t nodeTy QTimer* silentNodeRemovalTimer = new QTimer(this); connect(silentNodeRemovalTimer, SIGNAL(timeout()), nodeList, SLOT(removeSilentNodes())); - silentNodeRemovalTimer->start(NODE_SILENCE_THRESHOLD_USECS / 1000); + silentNodeRemovalTimer->start(NODE_SILENCE_THRESHOLD_MSECS); if (shouldSendStats) { // send a stats packet every 1 second From 85933545cd44fe6119dacd9d9b06702e8e90d404 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 4 Apr 2014 10:59:58 -0700 Subject: [PATCH 155/595] add GnuTLS init to Application --- interface/src/Application.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 548b5ac702..4c2d28376f 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -171,6 +171,9 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : _resetRecentMaxPacketsSoon(true), _logger(new FileLogger(this)) { + // init GnuTLS for DTLS with domain-servers + gnutls_global_init(); + // read the ApplicationInfo.ini file for Name/Version/Domain information QSettings applicationInfo(Application::resourcesPath() + "info/ApplicationInfo.ini", QSettings::IniFormat); From fd8e32190e772341c85a756b4b157bb14ea24c4e Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 4 Apr 2014 11:08:50 -0700 Subject: [PATCH 156/595] perform cleanup of GnuTLS structures across targets --- assignment-client/src/AssignmentClient.cpp | 4 ++++ assignment-client/src/AssignmentClient.h | 1 + domain-server/src/DomainServer.cpp | 14 +++++++++++++ domain-server/src/DomainServer.h | 1 + interface/src/Application.cpp | 2 ++ libraries/shared/src/DTLSClientSession.cpp | 23 ++++++++++------------ libraries/shared/src/DTLSClientSession.h | 5 +++-- 7 files changed, 35 insertions(+), 15 deletions(-) diff --git a/assignment-client/src/AssignmentClient.cpp b/assignment-client/src/AssignmentClient.cpp index 046f362e1e..c370c78132 100644 --- a/assignment-client/src/AssignmentClient.cpp +++ b/assignment-client/src/AssignmentClient.cpp @@ -109,6 +109,10 @@ AssignmentClient::AssignmentClient(int &argc, char **argv) : this, &AssignmentClient::handleAuthenticationRequest); } +AssignmentClient::~AssignmentClient() { + gnutls_global_deinit(); +} + void AssignmentClient::sendAssignmentRequest() { if (!_currentAssignment) { NodeList::getInstance()->sendAssignment(_requestAssignment); diff --git a/assignment-client/src/AssignmentClient.h b/assignment-client/src/AssignmentClient.h index c267c6238b..939d06b14f 100644 --- a/assignment-client/src/AssignmentClient.h +++ b/assignment-client/src/AssignmentClient.h @@ -17,6 +17,7 @@ class AssignmentClient : public QCoreApplication { Q_OBJECT public: AssignmentClient(int &argc, char **argv); + ~AssignmentClient(); private slots: void sendAssignmentRequest(); void readPendingDatagrams(); diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 12df8a4ada..a40bb2fa37 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -78,6 +78,20 @@ DomainServer::DomainServer(int argc, char* argv[]) : } } +DomainServer::~DomainServer() { + if (_x509Credentials) { + gnutls_certificate_free_credentials(*_x509Credentials); + gnutls_priority_deinit(*_priorityCache); + gnutls_dh_params_deinit(*_dhParams); + + delete _x509Credentials; + delete _priorityCache; + delete _dhParams; + delete _cookieKey; + } + gnutls_global_deinit(); +} + bool DomainServer::optionallySetupDTLS() { if (readX509KeyAndCertificate()) { if (_x509Credentials) { diff --git a/domain-server/src/DomainServer.h b/domain-server/src/DomainServer.h index 6bca67df0d..78e48f1468 100644 --- a/domain-server/src/DomainServer.h +++ b/domain-server/src/DomainServer.h @@ -31,6 +31,7 @@ class DomainServer : public QCoreApplication, public HTTPRequestHandler { Q_OBJECT public: DomainServer(int argc, char* argv[]); + ~DomainServer(); bool handleHTTPRequest(HTTPConnection* connection, const QUrl& url); diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 4c2d28376f..255712b5b6 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -393,6 +393,8 @@ Application::~Application() { delete _glWidget; AccountManager::getInstance().destroy(); + + gnutls_global_deinit(); } void Application::restoreSizeAndPosition() { diff --git a/libraries/shared/src/DTLSClientSession.cpp b/libraries/shared/src/DTLSClientSession.cpp index 73daa4e03a..58ca99f1a8 100644 --- a/libraries/shared/src/DTLSClientSession.cpp +++ b/libraries/shared/src/DTLSClientSession.cpp @@ -8,20 +8,17 @@ #include "DTLSClientSession.h" -gnutls_certificate_credentials_t* DTLSClientSession::x509CACredentials() { - static gnutls_certificate_credentials_t x509Credentials; - static bool credentialsInitialized = false; - - if (!credentialsInitialized) { - gnutls_certificate_allocate_credentials(&x509Credentials); - } - - return &x509Credentials; -} - DTLSClientSession::DTLSClientSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket) : DTLSSession(GNUTLS_CLIENT, dtlsSocket, destinationSocket) { + // _x509 as a member variable and not global/static assumes a single DTLSClientSession per client + gnutls_certificate_allocate_credentials(&_x509Credentials); + gnutls_priority_set_direct(_gnutlsSession, "PERFORMANCE", NULL); - gnutls_credentials_set(_gnutlsSession, GNUTLS_CRD_CERTIFICATE, *x509CACredentials()); -} \ No newline at end of file + gnutls_credentials_set(_gnutlsSession, GNUTLS_CRD_CERTIFICATE, _x509Credentials); +} + +DTLSClientSession::~DTLSClientSession() { + gnutls_certificate_free_credentials(_x509Credentials); +} + diff --git a/libraries/shared/src/DTLSClientSession.h b/libraries/shared/src/DTLSClientSession.h index a81daf6d74..325a162f61 100644 --- a/libraries/shared/src/DTLSClientSession.h +++ b/libraries/shared/src/DTLSClientSession.h @@ -14,8 +14,9 @@ class DTLSClientSession : public DTLSSession { public: DTLSClientSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket); - - static gnutls_certificate_credentials_t* x509CACredentials(); + ~DTLSClientSession(); +private: + gnutls_certificate_credentials_t _x509Credentials; }; #endif /* defined(__hifi__DTLSClientSession__) */ From b40dd6a31a49a53e6065f161aa61189a8b206206 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 4 Apr 2014 11:17:50 -0700 Subject: [PATCH 157/595] say bye and de-init DTLS session from DomainServer --- domain-server/src/DomainServer.cpp | 9 +++++++++ libraries/shared/src/DTLSSession.cpp | 5 +++++ libraries/shared/src/DTLSSession.h | 1 + 3 files changed, 15 insertions(+) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index a40bb2fa37..a66c46fc09 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -1001,6 +1001,7 @@ void DomainServer::nodeAdded(SharedNodePointer node) { void DomainServer::nodeKilled(SharedNodePointer node) { DomainServerNodeData* nodeData = reinterpret_cast(node->getLinkedData()); + if (nodeData) { // if this node's UUID matches a static assignment we need to throw it back in the assignment queue if (!nodeData->getStaticAssignmentUUID().isNull()) { @@ -1018,6 +1019,14 @@ void DomainServer::nodeKilled(SharedNodePointer node) { reinterpret_cast(otherNode->getLinkedData())->getSessionSecretHash().remove(node->getUUID()); } } + + if (_isUsingDTLS) { + // check if we need to remove a DTLS session from our in-memory hash + DTLSServerSession* existingSession = _dtlsSessions.take(nodeData->getSendingSockAddr()); + if (existingSession) { + delete existingSession; + } + } } } diff --git a/libraries/shared/src/DTLSSession.cpp b/libraries/shared/src/DTLSSession.cpp index 9b009730b4..44829c424e 100644 --- a/libraries/shared/src/DTLSSession.cpp +++ b/libraries/shared/src/DTLSSession.cpp @@ -105,6 +105,11 @@ DTLSSession::DTLSSession(int end, QUdpSocket& dtlsSocket, HifiSockAddr& destinat gnutls_transport_set_pull_timeout_function(_gnutlsSession, socketPullTimeout); } +DTLSSession::~DTLSSession() { + gnutls_bye(_gnutlsSession, GNUTLS_SHUT_WR); + gnutls_deinit(_gnutlsSession); +} + void DTLSSession::setCompletedHandshake(bool completedHandshake) { _completedHandshake = completedHandshake; qDebug() << "Completed DTLS handshake with" << _destinationSocket; diff --git a/libraries/shared/src/DTLSSession.h b/libraries/shared/src/DTLSSession.h index e9b5267592..395809c6c6 100644 --- a/libraries/shared/src/DTLSSession.h +++ b/libraries/shared/src/DTLSSession.h @@ -19,6 +19,7 @@ class DTLSSession : public QObject { Q_OBJECT public: DTLSSession(int end, QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket); + ~DTLSSession(); static int socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms); static ssize_t socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t size); From c35d6bdb0c55f872aa10bf8152b51f2371c8aa63 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 4 Apr 2014 11:25:43 -0700 Subject: [PATCH 158/595] add reflection stats to stats display, add pre-delay, add toggle for separate ears, add surface randomness --- interface/src/Application.cpp | 30 ++++++++++++++++++++ interface/src/AudioReflector.cpp | 48 ++++++++++++++++++++++---------- interface/src/AudioReflector.h | 15 +++++----- interface/src/Menu.cpp | 8 ++++++ interface/src/Menu.h | 2 ++ 5 files changed, 81 insertions(+), 22 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 863df28319..89f6a8e223 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2835,6 +2835,36 @@ void Application::displayStats() { verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, downloadStats.str().c_str(), WHITE_TEXT); + + if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessing)) { + // add some reflection stats + char reflectionsStatus[128]; + + sprintf(reflectionsStatus, "Reflections: %d, Pre-Delay: %f, Separate Ears:%s", + _audioReflector.getReflections(), + _audioReflector.getDelayFromDistance(0.0f), + debug::valueOf(Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingSeparateEars))); + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, WHITE_TEXT); + + sprintf(reflectionsStatus, "Delay: average %f, max %f, min %f", + _audioReflector.getAverageDelayMsecs(), + _audioReflector.getMaxDelayMsecs(), + _audioReflector.getMinDelayMsecs()); + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, WHITE_TEXT); + + sprintf(reflectionsStatus, "Attenuation: average %f, max %f, min %f", + _audioReflector.getAverageAttenuation(), + _audioReflector.getMaxAttenuation(), + _audioReflector.getMinAttenuation()); + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, WHITE_TEXT); + } + } verticalOffset = 0; diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index f61f411abc..b7ee81ff1c 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -9,6 +9,7 @@ #include #include "AudioReflector.h" +#include "Menu.h" AudioReflector::AudioReflector(QObject* parent) : QObject(parent) @@ -28,14 +29,23 @@ void AudioReflector::render() { } + // delay = 1ms per foot // = 3ms per meter // attenuation = // BOUNCE_ATTENUATION_FACTOR [0.5] * (1/(1+distance)) +const float PRE_DELAY = 20.0f; // this delay in msecs will always be added to all reflections -int getDelayFromDistance(float distance) { +float AudioReflector::getDelayFromDistance(float distance) { const int MS_DELAY_PER_METER = 3; - return MS_DELAY_PER_METER * distance; + float delay = (MS_DELAY_PER_METER * distance); + + if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingPreDelay)) { + delay += PRE_DELAY; + } + + + return delay; } // **option 1**: this is what we're using @@ -61,24 +71,29 @@ float getDistanceAttenuationCoefficient(float distance) { float distanceCoefficient = powf(GEOMETRIC_AMPLITUDE_SCALAR, DISTANCE_SCALE_LOG + (0.5f * logf(distanceSquareToSource) / logf(DISTANCE_LOG_BASE)) - 1); - distanceCoefficient = std::min(1.0f, distanceCoefficient); + + const float DISTANCE_SCALING_FACTOR = 2.0f; + + distanceCoefficient = std::min(1.0f, distanceCoefficient * DISTANCE_SCALING_FACTOR); return distanceCoefficient; } glm::vec3 getFaceNormal(BoxFace face) { + float surfaceRandomness = randFloatInRange(0.99,1.0); + float surfaceRemainder = (1.0f - surfaceRandomness)/2.0f; if (face == MIN_X_FACE) { - return glm::vec3(-1, 0, 0); + return glm::vec3(-surfaceRandomness, surfaceRemainder, surfaceRemainder); } else if (face == MAX_X_FACE) { - return glm::vec3(1, 0, 0); + return glm::vec3(surfaceRandomness, surfaceRemainder, surfaceRemainder); } else if (face == MIN_Y_FACE) { - return glm::vec3(0, -1, 0); + return glm::vec3(surfaceRemainder, -surfaceRandomness, surfaceRemainder); } else if (face == MAX_Y_FACE) { - return glm::vec3(0, 1, 0); + return glm::vec3(surfaceRemainder, surfaceRandomness, surfaceRemainder); } else if (face == MIN_Z_FACE) { - return glm::vec3(0, 0, -1); + return glm::vec3(surfaceRemainder, surfaceRemainder, -surfaceRandomness); } else if (face == MAX_Z_FACE) { - return glm::vec3(0, 0, 1); + return glm::vec3(surfaceRemainder, surfaceRemainder, surfaceRandomness); } return glm::vec3(0, 0, 0); //error case } @@ -113,7 +128,7 @@ void AudioReflector::calculateAllReflections() { // only recalculate when we've moved... // TODO: what about case where new voxels are added in front of us??? - if (_myAvatar->getHead()->getPosition() != _origin) { + if (_reflections == 0 || _myAvatar->getHead()->getPosition() != _origin) { QMutexLocker locker(&_mutex); qDebug() << "origin has changed..."; @@ -218,8 +233,11 @@ const int NUMBER_OF_CHANNELS = 2; void AudioReflector::echoReflections(const glm::vec3& origin, const QVector& reflections, const QByteArray& samples, unsigned int sampleTime, int sampleRate) { - glm::vec3 rightEarPosition = _myAvatar->getHead()->getRightEarPosition(); - glm::vec3 leftEarPosition = _myAvatar->getHead()->getLeftEarPosition(); + bool wantEarSeparation = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingSeparateEars); + glm::vec3 rightEarPosition = wantEarSeparation ? _myAvatar->getHead()->getRightEarPosition() : + _myAvatar->getHead()->getPosition(); + glm::vec3 leftEarPosition = wantEarSeparation ? _myAvatar->getHead()->getLeftEarPosition() : + _myAvatar->getHead()->getPosition(); glm::vec3 start = origin; int totalNumberOfSamples = samples.size() / sizeof(int16_t); @@ -253,8 +271,8 @@ void AudioReflector::echoReflections(const glm::vec3& origin, const QVector::max(); _minAttenuation = std::numeric_limits::max(); - _totalDelay = 0; + _totalDelay = 0.0f; _delayCount = 0; _totalAttenuation = 0.0f; _attenuationCount = 0; diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index f7e710d556..119a45f211 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -28,12 +28,13 @@ public: void render(); int getReflections() const { return _reflections; } - int getAverageDelayMsecs() const { return _averageDelay; } + float getAverageDelayMsecs() const { return _averageDelay; } float getAverageAttenuation() const { return _averageAttenuation; } - int getMaxDelayMsecs() const { return _maxDelay; } + float getMaxDelayMsecs() const { return _maxDelay; } float getMaxAttenuation() const { return _maxAttenuation; } - int getMinDelayMsecs() const { return _minDelay; } + float getMinDelayMsecs() const { return _minDelay; } float getMinAttenuation() const { return _minAttenuation; } + float getDelayFromDistance(float distance); public slots: void processSpatialAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); @@ -60,10 +61,10 @@ private: int _reflections; int _delayCount; - int _totalDelay; - int _averageDelay; - int _maxDelay; - int _minDelay; + float _totalDelay; + float _averageDelay; + float _maxDelay; + float _minDelay; int _attenuationCount; float _totalAttenuation; diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index d000b9cd6a..f0c7b27780 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -375,6 +375,14 @@ Menu::Menu() : addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingIncudeOriginal, Qt::CTRL | Qt::SHIFT | Qt::Key_O, true); + + addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingSeparateEars, + Qt::CTRL | Qt::SHIFT | Qt::Key_E, + true); + + addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingPreDelay, + Qt::CTRL | Qt::SHIFT | Qt::Key_D, + true); addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::LowPassFilter, Qt::CTRL | Qt::SHIFT | Qt::Key_F, diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 3d3961edaa..fbaf8b57a7 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -245,6 +245,8 @@ namespace MenuOption { const QString AudioToneInjection = "Inject Test Tone"; const QString AudioSpatialProcessing = "Audio Spatial Processing"; const QString AudioSpatialProcessingIncudeOriginal = "Audio Spatial Processing includes Original"; + const QString AudioSpatialProcessingSeparateEars = "Audio Spatial Processing separates ears"; + const QString AudioSpatialProcessingPreDelay = "Audio Spatial Processing add Pre-Delay"; const QString EchoServerAudio = "Echo Server Audio"; const QString EchoLocalAudio = "Echo Local Audio"; const QString MuteAudio = "Mute Microphone"; From c015fdd212eb49a3a9508450708694de155de388 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 4 Apr 2014 11:42:14 -0700 Subject: [PATCH 159/595] leverage a DummyDTLSSession to not require cleanup of DTLSSession for cookies --- domain-server/src/DomainServer.cpp | 5 +++- libraries/shared/src/DTLSClientSession.cpp | 23 +++++++++------- libraries/shared/src/DTLSClientSession.h | 5 ++-- libraries/shared/src/DTLSSession.cpp | 21 +++------------ libraries/shared/src/DTLSSession.h | 6 ++--- libraries/shared/src/DomainHandler.cpp | 6 ++--- libraries/shared/src/DummyDTLSSession.cpp | 28 +++++++++++++++++++ libraries/shared/src/DummyDTLSSession.h | 31 ++++++++++++++++++++++ libraries/shared/src/LimitedNodeList.cpp | 2 +- libraries/shared/src/NodeList.cpp | 2 ++ 10 files changed, 89 insertions(+), 40 deletions(-) create mode 100644 libraries/shared/src/DummyDTLSSession.cpp create mode 100644 libraries/shared/src/DummyDTLSSession.h diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index a66c46fc09..5d99a755c1 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -23,6 +23,7 @@ #include #include "DomainServerNodeData.h" +#include "DummyDTLSSession.h" #include "DomainServer.h" @@ -651,6 +652,7 @@ void DomainServer::readAvailableDTLSDatagrams() { DTLSServerSession* existingSession = _dtlsSessions.value(senderHifiSockAddr); if (existingSession) { + qDebug() << "There is an existing session for" << senderHifiSockAddr; if (!existingSession->completedHandshake()) { // check if we have completed handshake with this user int handshakeReturn = gnutls_handshake(*existingSession->getGnuTLSSession()); @@ -685,7 +687,8 @@ void DomainServer::readAvailableDTLSDatagrams() { if (cookieValid < 0) { // the cookie sent by the client was not valid // send a valid one - DTLSServerSession tempServerSession(LimitedNodeList::getInstance()->getDTLSSocket(), senderHifiSockAddr); + DummyDTLSSession tempServerSession(LimitedNodeList::getInstance()->getDTLSSocket(), senderHifiSockAddr); + qDebug() << "sending back a fresh cookie!"; gnutls_dtls_cookie_send(_cookieKey, &senderSockAddr, sizeof(senderSockAddr), &prestate, &tempServerSession, DTLSSession::socketPush); diff --git a/libraries/shared/src/DTLSClientSession.cpp b/libraries/shared/src/DTLSClientSession.cpp index 58ca99f1a8..73daa4e03a 100644 --- a/libraries/shared/src/DTLSClientSession.cpp +++ b/libraries/shared/src/DTLSClientSession.cpp @@ -8,17 +8,20 @@ #include "DTLSClientSession.h" +gnutls_certificate_credentials_t* DTLSClientSession::x509CACredentials() { + static gnutls_certificate_credentials_t x509Credentials; + static bool credentialsInitialized = false; + + if (!credentialsInitialized) { + gnutls_certificate_allocate_credentials(&x509Credentials); + } + + return &x509Credentials; +} + DTLSClientSession::DTLSClientSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket) : DTLSSession(GNUTLS_CLIENT, dtlsSocket, destinationSocket) { - // _x509 as a member variable and not global/static assumes a single DTLSClientSession per client - gnutls_certificate_allocate_credentials(&_x509Credentials); - gnutls_priority_set_direct(_gnutlsSession, "PERFORMANCE", NULL); - gnutls_credentials_set(_gnutlsSession, GNUTLS_CRD_CERTIFICATE, _x509Credentials); -} - -DTLSClientSession::~DTLSClientSession() { - gnutls_certificate_free_credentials(_x509Credentials); -} - + gnutls_credentials_set(_gnutlsSession, GNUTLS_CRD_CERTIFICATE, *x509CACredentials()); +} \ No newline at end of file diff --git a/libraries/shared/src/DTLSClientSession.h b/libraries/shared/src/DTLSClientSession.h index 325a162f61..a81daf6d74 100644 --- a/libraries/shared/src/DTLSClientSession.h +++ b/libraries/shared/src/DTLSClientSession.h @@ -14,9 +14,8 @@ class DTLSClientSession : public DTLSSession { public: DTLSClientSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket); - ~DTLSClientSession(); -private: - gnutls_certificate_credentials_t _x509Credentials; + + static gnutls_certificate_credentials_t* x509CACredentials(); }; #endif /* defined(__hifi__DTLSClientSession__) */ diff --git a/libraries/shared/src/DTLSSession.cpp b/libraries/shared/src/DTLSSession.cpp index 44829c424e..c5f4ade182 100644 --- a/libraries/shared/src/DTLSSession.cpp +++ b/libraries/shared/src/DTLSSession.cpp @@ -11,8 +11,6 @@ #include "NodeList.h" #include "DTLSSession.h" -#define DTLS_VERBOSE_DEBUG 0 - int DTLSSession::socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms) { DTLSSession* session = static_cast(ptr); QUdpSocket& dtlsSocket = session->_dtlsSocket; @@ -72,21 +70,8 @@ ssize_t DTLSSession::socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t return -1; } -ssize_t DTLSSession::socketPush(gnutls_transport_ptr_t ptr, const void* buffer, size_t size) { - DTLSSession* session = static_cast(ptr); - QUdpSocket& dtlsSocket = session->_dtlsSocket; - -#if DTLS_VERBOSE_DEBUG - qDebug() << "Pushing a message of size" << size << "to" << session->_destinationSocket; -#endif - - return dtlsSocket.writeDatagram(reinterpret_cast(buffer), size, - session->_destinationSocket.getAddress(), session->_destinationSocket.getPort()); -} - DTLSSession::DTLSSession(int end, QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket) : - _dtlsSocket(dtlsSocket), - _destinationSocket(destinationSocket), + DummyDTLSSession(dtlsSocket, destinationSocket), _completedHandshake(false) { gnutls_init(&_gnutlsSession, end | GNUTLS_DATAGRAM | GNUTLS_NONBLOCK); @@ -100,13 +85,13 @@ DTLSSession::DTLSSession(int end, QUdpSocket& dtlsSocket, HifiSockAddr& destinat gnutls_dtls_set_timeouts(_gnutlsSession, DTLS_HANDSHAKE_RETRANSMISSION_TIMEOUT, DTLS_TOTAL_CONNECTION_TIMEOUT); gnutls_transport_set_ptr(_gnutlsSession, this); - gnutls_transport_set_push_function(_gnutlsSession, socketPush); + gnutls_transport_set_push_function(_gnutlsSession, DummyDTLSSession::socketPush); gnutls_transport_set_pull_function(_gnutlsSession, socketPull); gnutls_transport_set_pull_timeout_function(_gnutlsSession, socketPullTimeout); } DTLSSession::~DTLSSession() { - gnutls_bye(_gnutlsSession, GNUTLS_SHUT_WR); + qDebug() << "cleaning up current session"; gnutls_deinit(_gnutlsSession); } diff --git a/libraries/shared/src/DTLSSession.h b/libraries/shared/src/DTLSSession.h index 395809c6c6..6b5f5df5e3 100644 --- a/libraries/shared/src/DTLSSession.h +++ b/libraries/shared/src/DTLSSession.h @@ -13,9 +13,10 @@ #include +#include "DummyDTLSSession.h" #include "HifiSockAddr.h" -class DTLSSession : public QObject { +class DTLSSession : public DummyDTLSSession { Q_OBJECT public: DTLSSession(int end, QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket); @@ -23,7 +24,6 @@ public: static int socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms); static ssize_t socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t size); - static ssize_t socketPush(gnutls_transport_ptr_t ptr, const void* buffer, size_t size); qint64 writeDatagram(const QByteArray& datagram); @@ -32,8 +32,6 @@ public: bool completedHandshake() const { return _completedHandshake; } void setCompletedHandshake(bool completedHandshake); protected: - QUdpSocket& _dtlsSocket; - HifiSockAddr _destinationSocket; gnutls_session_t _gnutlsSession; bool _completedHandshake; }; diff --git a/libraries/shared/src/DomainHandler.cpp b/libraries/shared/src/DomainHandler.cpp index 59b7f73e0d..e1aedc4d11 100644 --- a/libraries/shared/src/DomainHandler.cpp +++ b/libraries/shared/src/DomainHandler.cpp @@ -33,14 +33,14 @@ void DomainHandler::clearConnectionInfo() { _uuid = QUuid(); _isConnected = false; - delete _dtlsSession; - _dtlsSession = NULL; - if (_handshakeTimer) { _handshakeTimer->stop(); delete _handshakeTimer; _handshakeTimer = NULL; } + + delete _dtlsSession; + _dtlsSession = NULL; } void DomainHandler::reset() { diff --git a/libraries/shared/src/DummyDTLSSession.cpp b/libraries/shared/src/DummyDTLSSession.cpp new file mode 100644 index 0000000000..df7e82274c --- /dev/null +++ b/libraries/shared/src/DummyDTLSSession.cpp @@ -0,0 +1,28 @@ +// +// DummyDTLSSession.cpp +// hifi +// +// Created by Stephen Birarda on 2014-04-04. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// + +#include "DummyDTLSSession.h" + +ssize_t DummyDTLSSession::socketPush(gnutls_transport_ptr_t ptr, const void* buffer, size_t size) { + DummyDTLSSession* session = static_cast(ptr); + QUdpSocket& dtlsSocket = session->_dtlsSocket; + +#if DTLS_VERBOSE_DEBUG + qDebug() << "Pushing a message of size" << size << "to" << session->_destinationSocket; +#endif + + return dtlsSocket.writeDatagram(reinterpret_cast(buffer), size, + session->_destinationSocket.getAddress(), session->_destinationSocket.getPort()); +} + +DummyDTLSSession::DummyDTLSSession(QUdpSocket& dtlsSocket, const HifiSockAddr& destinationSocket) : + _dtlsSocket(dtlsSocket), + _destinationSocket(destinationSocket) +{ + +} \ No newline at end of file diff --git a/libraries/shared/src/DummyDTLSSession.h b/libraries/shared/src/DummyDTLSSession.h new file mode 100644 index 0000000000..6d4a54b4ca --- /dev/null +++ b/libraries/shared/src/DummyDTLSSession.h @@ -0,0 +1,31 @@ +// +// DummyDTLSSession.h +// hifi +// +// Created by Stephen Birarda on 2014-04-04. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// + +#ifndef __hifi__DummyDTLSSession__ +#define __hifi__DummyDTLSSession__ + +#include + +#include + +#include "HifiSockAddr.h" + +#define DTLS_VERBOSE_DEBUG 1 + +class DummyDTLSSession : public QObject { + Q_OBJECT +public: + DummyDTLSSession(QUdpSocket& dtlsSocket, const HifiSockAddr& destinationSocket); + + static ssize_t socketPush(gnutls_transport_ptr_t ptr, const void* buffer, size_t size); +protected: + QUdpSocket& _dtlsSocket; + HifiSockAddr _destinationSocket; +}; + +#endif /* defined(__hifi__DummyDTLSSession__) */ diff --git a/libraries/shared/src/LimitedNodeList.cpp b/libraries/shared/src/LimitedNodeList.cpp index e9fdaa493c..f6e6d282d9 100644 --- a/libraries/shared/src/LimitedNodeList.cpp +++ b/libraries/shared/src/LimitedNodeList.cpp @@ -426,7 +426,7 @@ void LimitedNodeList::removeSilentNodes() { node->getMutex().lock(); - if ((usecTimestampNow() - node->getLastHeardMicrostamp()) > (NODE_SILENCE_THRESHOLD_MSECS * 1000)) { + if ((usecTimestampNow() - node->getLastHeardMicrostamp()) > (NODE_SILENCE_THRESHOLD_MSECS * 1)) { // call our private method to kill this node (removes it and emits the right signal) nodeItem = killNodeAtHashIterator(nodeItem); } else { diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 50fa0269ef..92eb186c96 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -132,6 +132,8 @@ void NodeList::processAvailableDTLSDatagrams() { processNodeData(_domainHandler.getSockAddr(), dtlsPacket.left(receivedBytes)); } else if (gnutls_error_is_fatal(receivedBytes)) { qDebug() << "Fatal error -" << gnutls_strerror(receivedBytes) << "- receiving DTLS packet from domain-server."; + } else { + qDebug() << "non fatal receive" << receivedBytes; } } } From a0c7e4d3cc84c5eefadd15b9192a1149c29a2aeb Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Fri, 4 Apr 2014 11:45:03 -0700 Subject: [PATCH 160/595] Working on model rendering modes. --- interface/src/Menu.cpp | 2 +- interface/src/MetavoxelSystem.cpp | 18 +++++++++--------- interface/src/MetavoxelSystem.h | 10 +++++----- interface/src/avatar/Head.cpp | 4 ++-- interface/src/avatar/Head.h | 2 +- interface/src/renderer/Model.cpp | 20 ++++++++++---------- interface/src/renderer/Model.h | 7 +++++-- interface/src/ui/MetavoxelEditor.cpp | 12 ++++++++---- libraries/metavoxels/src/Bitstream.cpp | 6 +++++- libraries/metavoxels/src/MetavoxelData.cpp | 2 +- libraries/metavoxels/src/MetavoxelData.h | 4 +++- 11 files changed, 50 insertions(+), 37 deletions(-) diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 5530c57281..e324b5dd16 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -183,7 +183,7 @@ Menu::Menu() : #ifdef HAVE_QXMPP _chatAction = addActionToQMenuAndActionHash(toolsMenu, MenuOption::Chat, - Qt::Key_Return, + 0, this, SLOT(showChat())); diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index 11d6e8de2c..ce9c00ad17 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -228,7 +228,7 @@ MetavoxelSystem::RenderVisitor::RenderVisitor() : } bool MetavoxelSystem::RenderVisitor::visit(Spanner* spanner, const glm::vec3& clipMinimum, float clipSize) { - spanner->getRenderer()->render(1.0f, clipMinimum, clipSize); + spanner->getRenderer()->render(1.0f, SpannerRenderer::DEFAULT_MODE, clipMinimum, clipSize); return true; } @@ -345,9 +345,9 @@ static void enableClipPlane(GLenum plane, float x, float y, float z, float w) { glEnable(plane); } -void ClippedRenderer::render(float alpha, const glm::vec3& clipMinimum, float clipSize) { +void ClippedRenderer::render(float alpha, Mode mode, const glm::vec3& clipMinimum, float clipSize) { if (clipSize == 0.0f) { - renderUnclipped(alpha); + renderUnclipped(alpha, mode); return; } enableClipPlane(GL_CLIP_PLANE0, -1.0f, 0.0f, 0.0f, clipMinimum.x + clipSize); @@ -357,7 +357,7 @@ void ClippedRenderer::render(float alpha, const glm::vec3& clipMinimum, float cl enableClipPlane(GL_CLIP_PLANE4, 0.0f, 0.0f, -1.0f, clipMinimum.z + clipSize); enableClipPlane(GL_CLIP_PLANE5, 0.0f, 0.0f, 1.0f, -clipMinimum.z); - renderUnclipped(alpha); + renderUnclipped(alpha, mode); glDisable(GL_CLIP_PLANE0); glDisable(GL_CLIP_PLANE1); @@ -370,9 +370,9 @@ void ClippedRenderer::render(float alpha, const glm::vec3& clipMinimum, float cl SphereRenderer::SphereRenderer() { } -void SphereRenderer::render(float alpha, const glm::vec3& clipMinimum, float clipSize) { +void SphereRenderer::render(float alpha, Mode mode, const glm::vec3& clipMinimum, float clipSize) { if (clipSize == 0.0f) { - renderUnclipped(alpha); + renderUnclipped(alpha, mode); return; } // slight performance optimization: don't render if clip bounds are entirely within sphere @@ -381,13 +381,13 @@ void SphereRenderer::render(float alpha, const glm::vec3& clipMinimum, float cli for (int i = 0; i < Box::VERTEX_COUNT; i++) { const float CLIP_PROPORTION = 0.95f; if (glm::distance(sphere->getTranslation(), clipBox.getVertex(i)) >= sphere->getScale() * CLIP_PROPORTION) { - ClippedRenderer::render(alpha, clipMinimum, clipSize); + ClippedRenderer::render(alpha, mode, clipMinimum, clipSize); return; } } } -void SphereRenderer::renderUnclipped(float alpha) { +void SphereRenderer::renderUnclipped(float alpha, Mode mode) { Sphere* sphere = static_cast(parent()); const QColor& color = sphere->getColor(); glColor4f(color.redF(), color.greenF(), color.blueF(), color.alphaF() * alpha); @@ -435,7 +435,7 @@ void StaticModelRenderer::simulate(float deltaTime) { _model->simulate(deltaTime); } -void StaticModelRenderer::renderUnclipped(float alpha) { +void StaticModelRenderer::renderUnclipped(float alpha, Mode mode) { _model->render(alpha); } diff --git a/interface/src/MetavoxelSystem.h b/interface/src/MetavoxelSystem.h index ee6f91597e..7612437bb9 100644 --- a/interface/src/MetavoxelSystem.h +++ b/interface/src/MetavoxelSystem.h @@ -147,11 +147,11 @@ class ClippedRenderer : public SpannerRenderer { public: - virtual void render(float alpha, const glm::vec3& clipMinimum, float clipSize); + virtual void render(float alpha, Mode mode, const glm::vec3& clipMinimum, float clipSize); protected: - virtual void renderUnclipped(float alpha) = 0; + virtual void renderUnclipped(float alpha, Mode mode) = 0; }; /// Renders spheres. @@ -162,11 +162,11 @@ public: Q_INVOKABLE SphereRenderer(); - virtual void render(float alpha, const glm::vec3& clipMinimum, float clipSize); + virtual void render(float alpha, Mode mode, const glm::vec3& clipMinimum, float clipSize); protected: - virtual void renderUnclipped(float alpha); + virtual void renderUnclipped(float alpha, Mode mode); }; /// Renders static models. @@ -184,7 +184,7 @@ public: protected: - virtual void renderUnclipped(float alpha); + virtual void renderUnclipped(float alpha, Mode mode); private slots: diff --git a/interface/src/avatar/Head.cpp b/interface/src/avatar/Head.cpp index ffa0975ccb..396f93d821 100644 --- a/interface/src/avatar/Head.cpp +++ b/interface/src/avatar/Head.cpp @@ -179,8 +179,8 @@ void Head::relaxLean(float deltaTime) { _deltaLeanForward *= relaxationFactor; } -void Head::render(float alpha, bool forShadowMap) { - if (_faceModel.render(alpha, forShadowMap) && _renderLookatVectors) { +void Head::render(float alpha, Model::RenderMode mode) { + if (_faceModel.render(alpha, mode) && _renderLookatVectors) { renderLookatVectors(_leftEyePosition, _rightEyePosition, _lookAtPosition); } } diff --git a/interface/src/avatar/Head.h b/interface/src/avatar/Head.h index 8a03cfc7ad..36ab6a9229 100644 --- a/interface/src/avatar/Head.h +++ b/interface/src/avatar/Head.h @@ -37,7 +37,7 @@ public: void init(); void reset(); void simulate(float deltaTime, bool isMine, bool billboard = false); - void render(float alpha, bool forShadowMap); + void render(float alpha, Model::RenderMode mode); void setScale(float scale); void setPosition(glm::vec3 position) { _position = position; } void setGravity(glm::vec3 gravity) { _gravity = gravity; } diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 9d2a031a6e..e840de9fbb 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -281,7 +281,7 @@ bool Model::updateGeometry() { return needFullUpdate; } -bool Model::render(float alpha, bool forShadowMap) { +bool Model::render(float alpha, RenderMode mode) { // render the attachments foreach (Model* attachment, _attachments) { attachment->render(alpha); @@ -305,20 +305,20 @@ bool Model::render(float alpha, bool forShadowMap) { glDisable(GL_COLOR_MATERIAL); - glEnable(GL_CULL_FACE); + // glEnable(GL_CULL_FACE); // render opaque meshes with alpha testing glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.5f * alpha); - renderMeshes(alpha, forShadowMap, false); + renderMeshes(alpha, mode, false); glDisable(GL_ALPHA_TEST); // render translucent meshes afterwards, with back face culling - renderMeshes(alpha, forShadowMap, true); + renderMeshes(alpha, mode, true); glDisable(GL_CULL_FACE); @@ -1112,7 +1112,7 @@ void Model::deleteGeometry() { } } -void Model::renderMeshes(float alpha, bool forShadowMap, bool translucent) { +void Model::renderMeshes(float alpha, RenderMode mode, bool translucent) { const FBXGeometry& geometry = _geometry->getFBXGeometry(); const QVector& networkMeshes = _geometry->getMeshes(); @@ -1137,7 +1137,7 @@ void Model::renderMeshes(float alpha, bool forShadowMap, bool translucent) { ProgramObject* program = &_program; ProgramObject* skinProgram = &_skinProgram; SkinLocations* skinLocations = &_skinLocations; - if (forShadowMap) { + if (mode == SHADOW_MAP_MODE) { program = &_shadowProgram; skinProgram = &_skinShadowProgram; skinLocations = &_skinShadowLocations; @@ -1175,7 +1175,7 @@ void Model::renderMeshes(float alpha, bool forShadowMap, bool translucent) { } if (mesh.blendshapes.isEmpty()) { - if (!(mesh.tangents.isEmpty() || forShadowMap)) { + if (!(mesh.tangents.isEmpty() || mode == SHADOW_MAP_MODE)) { activeProgram->setAttributeBuffer(tangentLocation, GL_FLOAT, vertexCount * 2 * sizeof(glm::vec3), 3); activeProgram->enableAttributeArray(tangentLocation); } @@ -1185,7 +1185,7 @@ void Model::renderMeshes(float alpha, bool forShadowMap, bool translucent) { (mesh.tangents.size() + mesh.colors.size()) * sizeof(glm::vec3))); } else { - if (!(mesh.tangents.isEmpty() || forShadowMap)) { + if (!(mesh.tangents.isEmpty() || mode == SHADOW_MAP_MODE)) { activeProgram->setAttributeBuffer(tangentLocation, GL_FLOAT, 0, 3); activeProgram->enableAttributeArray(tangentLocation); } @@ -1214,7 +1214,7 @@ void Model::renderMeshes(float alpha, bool forShadowMap, bool translucent) { continue; } // apply material properties - if (forShadowMap) { + if (mode == SHADOW_MAP_MODE) { glBindTexture(GL_TEXTURE_2D, 0); } else { @@ -1255,7 +1255,7 @@ void Model::renderMeshes(float alpha, bool forShadowMap, bool translucent) { glDisableClientState(GL_TEXTURE_COORD_ARRAY); } - if (!(mesh.tangents.isEmpty() || forShadowMap)) { + if (!(mesh.tangents.isEmpty() || mode == SHADOW_MAP_MODE)) { glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE0); diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index 11374a6369..5671e104fc 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -57,7 +57,10 @@ public: void init(); void reset(); virtual void simulate(float deltaTime, bool fullUpdate = true); - bool render(float alpha = 1.0f, bool forShadowMap = false); + + enum RenderMode { DEFAULT_MODE, SHADOW_MAP_MODE, DIFFUSE_MODE, NORMAL_MODE }; + + bool render(float alpha = 1.0f, RenderMode mode = DEFAULT_MODE); /// Sets the URL of the model to render. /// \param fallback the URL of a fallback model to render if the requested model fails to load @@ -254,7 +257,7 @@ private: void applyNextGeometry(); void deleteGeometry(); - void renderMeshes(float alpha, bool forShadowMap, bool translucent); + void renderMeshes(float alpha, RenderMode mode, bool translucent); QVector createJointStates(const FBXGeometry& geometry); QSharedPointer _baseGeometry; ///< reference required to prevent collection of base diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index 024dd0c5d1..2bb2b3a7e5 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -569,7 +569,7 @@ void PlaceSpannerTool::render() { } Spanner* spanner = static_cast(_editor->getValue().value().data()); const float SPANNER_ALPHA = 0.25f; - spanner->getRenderer()->render(SPANNER_ALPHA, glm::vec3(), 0.0f); + spanner->getRenderer()->render(SPANNER_ALPHA, SpannerRenderer::DEFAULT_MODE, glm::vec3(), 0.0f); } bool PlaceSpannerTool::appliesTo(const AttributePointer& attribute) const { @@ -773,6 +773,7 @@ int VoxelizationVisitor::visit(MetavoxelInfo& info) { int y = qMax(qMin((int)glm::round(relative.y), images.color.height() - 1), 0); float depth = 1.0f - images.depth.at(y * images.color.width() + x); float distance = depth - relative.z; + float extent = images.scale.z * halfSize; if (distance < 0.0f) { info.outputValues[0] = AttributeValue(_outputs.at(0)); return STOP_RECURSION; @@ -838,8 +839,9 @@ void SetSpannerTool::applyEdit(const AttributePointer& attribute, const SharedOb minima = glm::min(minima, rotated); maxima = glm::max(maxima, rotated); } - int width = glm::round((maxima.x - minima.x) / spannerData->getVoxelizationGranularity()); - int height = glm::round((maxima.y - minima.y) / spannerData->getVoxelizationGranularity()); + float renderGranularity = spannerData->getVoxelizationGranularity() / 4.0f; + int width = glm::round((maxima.x - minima.x) / renderGranularity); + int height = glm::round((maxima.y - minima.y) / renderGranularity); glViewport(0, 0, width, height); glScissor(0, 0, width, height); @@ -857,7 +859,7 @@ void SetSpannerTool::applyEdit(const AttributePointer& attribute, const SharedOb Application::getInstance()->updateUntranslatedViewMatrix(); - spannerData->getRenderer()->render(1.0f, glm::vec3(), 0.0f); + spannerData->getRenderer()->render(1.0f, SpannerRenderer::DIFFUSE_MODE, glm::vec3(), 0.0f); DirectionImages images = { QImage(width, height, QImage::Format_ARGB32), QVector(width * height), minima, maxima, glm::vec3(width / (maxima.x - minima.x), @@ -866,6 +868,8 @@ void SetSpannerTool::applyEdit(const AttributePointer& attribute, const SharedOb glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, images.depth.data()); directionImages.append(images); + images.color.save(QString::number(i) + ".png"); + glMatrixMode(GL_PROJECTION); } glPopMatrix(); diff --git a/libraries/metavoxels/src/Bitstream.cpp b/libraries/metavoxels/src/Bitstream.cpp index 077e6c1c69..09e71700be 100644 --- a/libraries/metavoxels/src/Bitstream.cpp +++ b/libraries/metavoxels/src/Bitstream.cpp @@ -869,7 +869,11 @@ Bitstream& Bitstream::operator>(SharedObjectPointer& object) { *this >> rawObject; } pointer = static_cast(rawObject); - pointer->setRemoteID(id); + if (pointer) { + pointer->setRemoteID(id); + } else { + qDebug() << "Null object" << pointer << reference; + } } object = static_cast(pointer.data()); return *this; diff --git a/libraries/metavoxels/src/MetavoxelData.cpp b/libraries/metavoxels/src/MetavoxelData.cpp index f4d2870ad4..e4cce9c735 100644 --- a/libraries/metavoxels/src/MetavoxelData.cpp +++ b/libraries/metavoxels/src/MetavoxelData.cpp @@ -1527,7 +1527,7 @@ void SpannerRenderer::simulate(float deltaTime) { // nothing by default } -void SpannerRenderer::render(float alpha, const glm::vec3& clipMinimum, float clipSize) { +void SpannerRenderer::render(float alpha, Mode mode, const glm::vec3& clipMinimum, float clipSize) { // nothing by default } diff --git a/libraries/metavoxels/src/MetavoxelData.h b/libraries/metavoxels/src/MetavoxelData.h index 4254b3bbb2..41285af2f5 100644 --- a/libraries/metavoxels/src/MetavoxelData.h +++ b/libraries/metavoxels/src/MetavoxelData.h @@ -518,11 +518,13 @@ class SpannerRenderer : public QObject { public: + enum Mode { DEFAULT_MODE, DIFFUSE_MODE, NORMAL_MODE }; + Q_INVOKABLE SpannerRenderer(); virtual void init(Spanner* spanner); virtual void simulate(float deltaTime); - virtual void render(float alpha, const glm::vec3& clipMinimum, float clipSize); + virtual void render(float alpha, Mode mode, const glm::vec3& clipMinimum, float clipSize); virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, const glm::vec3& clipMinimum, float clipSize, float& distance) const; }; From a2b94aa43330c139ff073838b9c90e481014f6d9 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Fri, 4 Apr 2014 14:22:01 -0700 Subject: [PATCH 161/595] Working on render modes. --- interface/src/MetavoxelSystem.cpp | 13 +++++++++++++ interface/src/avatar/Avatar.cpp | 6 ++++-- interface/src/avatar/MyAvatar.cpp | 6 ++++-- interface/src/renderer/Model.cpp | 20 ++++++++++++-------- interface/src/renderer/Model.h | 4 ++-- interface/src/ui/MetavoxelEditor.cpp | 4 ++-- 6 files changed, 37 insertions(+), 16 deletions(-) diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index ce9c00ad17..8fe4b53922 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -436,6 +436,19 @@ void StaticModelRenderer::simulate(float deltaTime) { } void StaticModelRenderer::renderUnclipped(float alpha, Mode mode) { + switch (mode) { + case DIFFUSE_MODE: + _model->render(alpha, Model::DIFFUSE_RENDER_MODE); + break; + + case NORMAL_MODE: + _model->render(alpha, Model::NORMAL_RENDER_MODE); + break; + + default: + _model->render(alpha); + break; + } _model->render(alpha); } diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 899514d1c1..d2e6293f3b 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -326,8 +326,10 @@ void Avatar::renderBody(RenderMode renderMode) { renderBillboard(); return; } - _skeletonModel.render(1.0f, renderMode == SHADOW_RENDER_MODE); - getHead()->render(1.0f, renderMode == SHADOW_RENDER_MODE); + Model::RenderMode modelRenderMode = (renderMode == SHADOW_RENDER_MODE) ? + Model::SHADOW_RENDER_MODE : Model::DEFAULT_RENDER_MODE; + _skeletonModel.render(1.0f, modelRenderMode); + getHead()->render(1.0f, modelRenderMode); getHand()->render(false); } diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 9dcfaa09ba..b63da79c6f 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -642,14 +642,16 @@ void MyAvatar::renderBody(RenderMode renderMode) { } // Render the body's voxels and head - _skeletonModel.render(1.0f, renderMode == SHADOW_RENDER_MODE); + Model::RenderMode modelRenderMode = (renderMode == SHADOW_RENDER_MODE) ? + Model::SHADOW_RENDER_MODE : Model::DEFAULT_RENDER_MODE; + _skeletonModel.render(1.0f, modelRenderMode); // Render head so long as the camera isn't inside it const float RENDER_HEAD_CUTOFF_DISTANCE = 0.40f; Camera* myCamera = Application::getInstance()->getCamera(); if (renderMode != NORMAL_RENDER_MODE || (glm::length(myCamera->getPosition() - getHead()->calculateAverageEyePosition()) > RENDER_HEAD_CUTOFF_DISTANCE * _scale)) { - getHead()->render(1.0f, renderMode == SHADOW_RENDER_MODE); + getHead()->render(1.0f, modelRenderMode); } getHand()->render(true); } diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index e840de9fbb..6583b436b7 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -284,7 +284,7 @@ bool Model::updateGeometry() { bool Model::render(float alpha, RenderMode mode) { // render the attachments foreach (Model* attachment, _attachments) { - attachment->render(alpha); + attachment->render(alpha, mode); } if (_meshStates.isEmpty()) { return false; @@ -305,7 +305,11 @@ bool Model::render(float alpha, RenderMode mode) { glDisable(GL_COLOR_MATERIAL); - // glEnable(GL_CULL_FACE); + if (mode == DIFFUSE_RENDER_MODE || mode == NORMAL_RENDER_MODE) { + glDisable(GL_CULL_FACE); + } else { + glEnable(GL_CULL_FACE); + } // render opaque meshes with alpha testing @@ -316,7 +320,7 @@ bool Model::render(float alpha, RenderMode mode) { glDisable(GL_ALPHA_TEST); - // render translucent meshes afterwards, with back face culling + // render translucent meshes afterwards renderMeshes(alpha, mode, true); @@ -1137,7 +1141,7 @@ void Model::renderMeshes(float alpha, RenderMode mode, bool translucent) { ProgramObject* program = &_program; ProgramObject* skinProgram = &_skinProgram; SkinLocations* skinLocations = &_skinLocations; - if (mode == SHADOW_MAP_MODE) { + if (mode == SHADOW_RENDER_MODE) { program = &_shadowProgram; skinProgram = &_skinShadowProgram; skinLocations = &_skinShadowLocations; @@ -1175,7 +1179,7 @@ void Model::renderMeshes(float alpha, RenderMode mode, bool translucent) { } if (mesh.blendshapes.isEmpty()) { - if (!(mesh.tangents.isEmpty() || mode == SHADOW_MAP_MODE)) { + if (!(mesh.tangents.isEmpty() || mode == SHADOW_RENDER_MODE)) { activeProgram->setAttributeBuffer(tangentLocation, GL_FLOAT, vertexCount * 2 * sizeof(glm::vec3), 3); activeProgram->enableAttributeArray(tangentLocation); } @@ -1185,7 +1189,7 @@ void Model::renderMeshes(float alpha, RenderMode mode, bool translucent) { (mesh.tangents.size() + mesh.colors.size()) * sizeof(glm::vec3))); } else { - if (!(mesh.tangents.isEmpty() || mode == SHADOW_MAP_MODE)) { + if (!(mesh.tangents.isEmpty() || mode == SHADOW_RENDER_MODE)) { activeProgram->setAttributeBuffer(tangentLocation, GL_FLOAT, 0, 3); activeProgram->enableAttributeArray(tangentLocation); } @@ -1214,7 +1218,7 @@ void Model::renderMeshes(float alpha, RenderMode mode, bool translucent) { continue; } // apply material properties - if (mode == SHADOW_MAP_MODE) { + if (mode == SHADOW_RENDER_MODE) { glBindTexture(GL_TEXTURE_2D, 0); } else { @@ -1255,7 +1259,7 @@ void Model::renderMeshes(float alpha, RenderMode mode, bool translucent) { glDisableClientState(GL_TEXTURE_COORD_ARRAY); } - if (!(mesh.tangents.isEmpty() || mode == SHADOW_MAP_MODE)) { + if (!(mesh.tangents.isEmpty() || mode == SHADOW_RENDER_MODE)) { glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE0); diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index 5671e104fc..134a3e2172 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -58,9 +58,9 @@ public: void reset(); virtual void simulate(float deltaTime, bool fullUpdate = true); - enum RenderMode { DEFAULT_MODE, SHADOW_MAP_MODE, DIFFUSE_MODE, NORMAL_MODE }; + enum RenderMode { DEFAULT_RENDER_MODE, SHADOW_RENDER_MODE, DIFFUSE_RENDER_MODE, NORMAL_RENDER_MODE }; - bool render(float alpha = 1.0f, RenderMode mode = DEFAULT_MODE); + bool render(float alpha = 1.0f, RenderMode mode = DEFAULT_RENDER_MODE); /// Sets the URL of the model to render. /// \param fallback the URL of a fallback model to render if the requested model fails to load diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index 2bb2b3a7e5..e12bc334a5 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -774,12 +774,12 @@ int VoxelizationVisitor::visit(MetavoxelInfo& info) { float depth = 1.0f - images.depth.at(y * images.color.width() + x); float distance = depth - relative.z; float extent = images.scale.z * halfSize; - if (distance < 0.0f) { + if (distance < -extent - EPSILON) { info.outputValues[0] = AttributeValue(_outputs.at(0)); return STOP_RECURSION; } QRgb color = images.color.pixel(x, y); - if (distance < EPSILON) { + if (distance < extent + EPSILON) { info.outputValues[0] = AttributeValue(_outputs.at(0), encodeInline(color)); return STOP_RECURSION; } From 3a125db1f8241999e0457141a1fe14c728eb688d Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Fri, 4 Apr 2014 14:31:30 -0700 Subject: [PATCH 162/595] Increase the rate at which we increase detail and put a limit on the LOD multiplier so that it never takes more than about five seconds to return to default detail. Also, since there seems to be a weird issue where OS X throttles the frame rate to 30 fps (independent of our own throttling), use that as the lower adjustment range. --- interface/src/Menu.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 5530c57281..5deb9474cf 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -1260,20 +1260,22 @@ void Menu::autoAdjustLOD(float currentFPS) { quint64 now = usecTimestampNow(); + const float ADJUST_AVATAR_LOD_DOWN_FPS = 30.0f; const quint64 ADJUST_AVATAR_LOD_DOWN_DELAY = 1000 * 1000; - if (_fastFPSAverage.getAverage() < ADJUST_LOD_DOWN_FPS) { + if (_fastFPSAverage.getAverage() < ADJUST_AVATAR_LOD_DOWN_FPS) { if (now - _lastAvatarDetailDrop > ADJUST_AVATAR_LOD_DOWN_DELAY) { // attempt to lower the detail in proportion to the fps difference - float targetFps = (ADJUST_LOD_DOWN_FPS + ADJUST_LOD_UP_FPS) * 0.5f; + float targetFps = (ADJUST_AVATAR_LOD_DOWN_FPS + ADJUST_LOD_UP_FPS) * 0.5f; float averageFps = _fastFPSAverage.getAverage(); const float MAXIMUM_MULTIPLIER_SCALE = 2.0f; - _avatarLODDistanceMultiplier *= (averageFps < EPSILON) ? MAXIMUM_MULTIPLIER_SCALE : - qMin(MAXIMUM_MULTIPLIER_SCALE, targetFps / averageFps); + const float MAXIMUM_DISTANCE_MULTIPLIER = 15.0f; + _avatarLODDistanceMultiplier = qMin(MAXIMUM_DISTANCE_MULTIPLIER, _avatarLODDistanceMultiplier * + (averageFps < EPSILON ? MAXIMUM_MULTIPLIER_SCALE : qMin(MAXIMUM_MULTIPLIER_SCALE, targetFps / averageFps))); _lastAvatarDetailDrop = now; } } else if (_fastFPSAverage.getAverage() > ADJUST_LOD_UP_FPS) { // let the detail level creep slowly upwards - const float DISTANCE_DECREASE_RATE = 0.02f; + const float DISTANCE_DECREASE_RATE = 0.05f; const float MINIMUM_DISTANCE_MULTIPLIER = 0.1f; _avatarLODDistanceMultiplier = qMax(MINIMUM_DISTANCE_MULTIPLIER, _avatarLODDistanceMultiplier - DISTANCE_DECREASE_RATE); From 01c42c741c57ecd01c51238ab3996228a45d2e0c Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Fri, 4 Apr 2014 14:46:54 -0700 Subject: [PATCH 163/595] fix #2567 thrust + oculus doesn't change body rot --- interface/src/Application.cpp | 2 +- interface/src/avatar/Head.cpp | 4 ++++ interface/src/avatar/MyAvatar.cpp | 28 +--------------------------- 3 files changed, 6 insertions(+), 28 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 83eab37318..d54cceb245 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -510,7 +510,7 @@ void Application::paintGL() { _myCamera.setDistance(0.0f); _myCamera.setTightness(0.0f); // Camera is directly connected to head without smoothing _myCamera.setTargetPosition(_myAvatar->getHead()->calculateAverageEyePosition()); - _myCamera.setTargetRotation(_myAvatar->getHead()->getOrientation()); + _myCamera.setTargetRotation(_myAvatar->getHead()->getCameraOrientation()); } else if (_myCamera.getMode() == CAMERA_MODE_FIRST_PERSON) { _myCamera.setTightness(0.0f); // In first person, camera follows (untweaked) head exactly without delay diff --git a/interface/src/avatar/Head.cpp b/interface/src/avatar/Head.cpp index ffa0975ccb..8a25c14574 100644 --- a/interface/src/avatar/Head.cpp +++ b/interface/src/avatar/Head.cpp @@ -14,6 +14,7 @@ #include "Head.h" #include "Menu.h" #include "Util.h" +#include "devices/OculusManager.h" using namespace std; @@ -198,6 +199,9 @@ glm::quat Head::getFinalOrientation() const { } glm::quat Head::getCameraOrientation () const { + if (OculusManager::isConnected()) { + return getOrientation(); + } Avatar* owningAvatar = static_cast(_owningAvatar); return owningAvatar->getWorldAlignedOrientation() * glm::quat(glm::radians(glm::vec3(_basePitch, 0.f, 0.0f))); } diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 9dcfaa09ba..1ff93794c5 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -169,9 +169,6 @@ void MyAvatar::simulate(float deltaTime) { // Collect thrust forces from keyboard and devices updateThrust(deltaTime); - // copy velocity so we can use it later for acceleration - glm::vec3 oldVelocity = getVelocity(); - // calculate speed _speed = glm::length(_velocity); @@ -231,29 +228,6 @@ void MyAvatar::simulate(float deltaTime) { // update the euler angles setOrientation(orientation); - // Compute instantaneous acceleration - float forwardAcceleration = glm::length(glm::dot(getBodyFrontDirection(), getVelocity() - oldVelocity)) / deltaTime; - const float OCULUS_ACCELERATION_PULL_THRESHOLD = 1.0f; - const int OCULUS_YAW_OFFSET_THRESHOLD = 10; - - if (!Application::getInstance()->getFaceshift()->isActive() && OculusManager::isConnected() && - fabsf(forwardAcceleration) > OCULUS_ACCELERATION_PULL_THRESHOLD && - fabs(getHead()->getBaseYaw()) > OCULUS_YAW_OFFSET_THRESHOLD) { - - // if we're wearing the oculus - // and this acceleration is above the pull threshold - // and the head yaw if off the body by more than OCULUS_YAW_OFFSET_THRESHOLD - - // match the body yaw to the oculus yaw - _bodyYaw = getAbsoluteHeadYaw(); - - // set the head yaw to zero for this draw - getHead()->setBaseYaw(0); - - // correct the oculus yaw offset - OculusManager::updateYawOffset(); - } - const float WALKING_SPEED_THRESHOLD = 0.2f; // use speed and angular velocity to determine walking vs. standing if (_speed + fabs(_bodyYawDelta) > WALKING_SPEED_THRESHOLD) { @@ -308,7 +282,7 @@ void MyAvatar::simulate(float deltaTime) { head->simulate(deltaTime, true); // Zero thrust out now that we've added it to velocity in this frame - _thrust = glm::vec3(0, 0, 0); + _thrust = glm::vec3(0.f); // now that we're done stepping the avatar forward in time, compute new collisions if (_collisionFlags != 0) { From 403ad5e984a8365353fe3b1a3371846fdcf7d0fb Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Fri, 4 Apr 2014 15:18:12 -0700 Subject: [PATCH 164/595] removing a warning about hidden virtual override --- interface/src/avatar/FaceModel.cpp | 2 +- interface/src/avatar/FaceModel.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/avatar/FaceModel.cpp b/interface/src/avatar/FaceModel.cpp index b0ef947f65..e81e1da117 100644 --- a/interface/src/avatar/FaceModel.cpp +++ b/interface/src/avatar/FaceModel.cpp @@ -18,7 +18,7 @@ FaceModel::FaceModel(Head* owningHead) : { } -void FaceModel::simulate(float deltaTime) { +void FaceModel::simulate(float deltaTime, bool fullUpdate) { updateGeometry(); Avatar* owningAvatar = static_cast(_owningHead->_owningAvatar); glm::vec3 neckPosition; diff --git a/interface/src/avatar/FaceModel.h b/interface/src/avatar/FaceModel.h index acf2d2baf4..d675495e6b 100644 --- a/interface/src/avatar/FaceModel.h +++ b/interface/src/avatar/FaceModel.h @@ -21,7 +21,7 @@ public: FaceModel(Head* owningHead); - void simulate(float deltaTime); + virtual void simulate(float deltaTime, bool fullUpdate = true); protected: From 45d796e8f3dbf91dc94c6abc82a577038b62b950 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 4 Apr 2014 15:56:02 -0700 Subject: [PATCH 165/595] allow re-handshake in NodeList after domain refresh --- domain-server/src/DomainServer.cpp | 1 - libraries/shared/src/DomainHandler.h | 1 + libraries/shared/src/DummyDTLSSession.h | 2 +- libraries/shared/src/LimitedNodeList.cpp | 2 +- libraries/shared/src/NodeList.cpp | 3 +++ 5 files changed, 6 insertions(+), 3 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 5d99a755c1..60c5cf1d0e 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -652,7 +652,6 @@ void DomainServer::readAvailableDTLSDatagrams() { DTLSServerSession* existingSession = _dtlsSessions.value(senderHifiSockAddr); if (existingSession) { - qDebug() << "There is an existing session for" << senderHifiSockAddr; if (!existingSession->completedHandshake()) { // check if we have completed handshake with this user int handshakeReturn = gnutls_handshake(*existingSession->getGnuTLSSession()); diff --git a/libraries/shared/src/DomainHandler.h b/libraries/shared/src/DomainHandler.h index b8351653f6..c34321cf87 100644 --- a/libraries/shared/src/DomainHandler.h +++ b/libraries/shared/src/DomainHandler.h @@ -61,6 +61,7 @@ signals: void hostnameChanged(const QString& hostname); void connectedToDomain(const QString& hostname); void completedDTLSHandshake(); + void DTLSConnectionLost(); private: void reset(); diff --git a/libraries/shared/src/DummyDTLSSession.h b/libraries/shared/src/DummyDTLSSession.h index 6d4a54b4ca..394bb82ae5 100644 --- a/libraries/shared/src/DummyDTLSSession.h +++ b/libraries/shared/src/DummyDTLSSession.h @@ -15,7 +15,7 @@ #include "HifiSockAddr.h" -#define DTLS_VERBOSE_DEBUG 1 +#define DTLS_VERBOSE_DEBUG 0 class DummyDTLSSession : public QObject { Q_OBJECT diff --git a/libraries/shared/src/LimitedNodeList.cpp b/libraries/shared/src/LimitedNodeList.cpp index f6e6d282d9..e9fdaa493c 100644 --- a/libraries/shared/src/LimitedNodeList.cpp +++ b/libraries/shared/src/LimitedNodeList.cpp @@ -426,7 +426,7 @@ void LimitedNodeList::removeSilentNodes() { node->getMutex().lock(); - if ((usecTimestampNow() - node->getLastHeardMicrostamp()) > (NODE_SILENCE_THRESHOLD_MSECS * 1)) { + if ((usecTimestampNow() - node->getLastHeardMicrostamp()) > (NODE_SILENCE_THRESHOLD_MSECS * 1000)) { // call our private method to kill this node (removes it and emits the right signal) nodeItem = killNodeAtHashIterator(nodeItem); } else { diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index 92eb186c96..50fd3d1cbc 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -196,6 +196,9 @@ void NodeList::reset() { // clear the domain connection information _domainHandler.clearConnectionInfo(); + + // also disconnect from the DTLS socket readyRead() so it can handle handshaking + disconnect(_dtlsSocket, 0, this, 0); } void NodeList::addNodeTypeToInterestSet(NodeType_t nodeTypeToAdd) { From d2b0cc43dd1414710aafa23c82c0bde959fde561 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Fri, 4 Apr 2014 16:32:14 -0700 Subject: [PATCH 166/595] Extent tweaks. --- interface/src/ui/MetavoxelEditor.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index e12bc334a5..87b04e53d5 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -733,11 +733,11 @@ VoxelizationVisitor::VoxelizationVisitor(const QVector& directi _granularity(granularity) { } -bool checkDisjoint(const DirectionImages& images, const glm::vec3& minimum, const glm::vec3& maximum) { +bool checkDisjoint(const DirectionImages& images, const glm::vec3& minimum, const glm::vec3& maximum, float extent) { for (int x = qMax(0, (int)minimum.x), xmax = qMin(images.color.width(), (int)maximum.x); x < xmax; x++) { for (int y = qMax(0, (int)minimum.y), ymax = qMin(images.color.height(), (int)maximum.y); y < ymax; y++) { float depth = 1.0f - images.depth.at(y * images.color.width() + x); - if (depth - minimum.z >= 0.0f) { + if (depth - minimum.z >= -extent - EPSILON) { return false; } } @@ -748,6 +748,7 @@ bool checkDisjoint(const DirectionImages& images, const glm::vec3& minimum, cons int VoxelizationVisitor::visit(MetavoxelInfo& info) { float halfSize = info.size * 0.5f; glm::vec3 center = info.minimum + _center + glm::vec3(halfSize, halfSize, halfSize); + const float EXTENT_SCALE = 2.0f; if (info.size > _granularity) { for (unsigned int i = 0; i < sizeof(DIRECTION_ROTATIONS) / sizeof(DIRECTION_ROTATIONS[0]); i++) { glm::vec3 rotated = DIRECTION_ROTATIONS[i] * center; @@ -756,7 +757,7 @@ int VoxelizationVisitor::visit(MetavoxelInfo& info) { glm::vec3 extents = images.scale * halfSize; glm::vec3 minimum = relative - extents; glm::vec3 maximum = relative + extents; - if (checkDisjoint(images, minimum, maximum)) { + if (checkDisjoint(images, minimum, maximum, extents.z * EXTENT_SCALE)) { info.outputValues[0] = AttributeValue(_outputs.at(0)); return STOP_RECURSION; } @@ -773,7 +774,7 @@ int VoxelizationVisitor::visit(MetavoxelInfo& info) { int y = qMax(qMin((int)glm::round(relative.y), images.color.height() - 1), 0); float depth = 1.0f - images.depth.at(y * images.color.width() + x); float distance = depth - relative.z; - float extent = images.scale.z * halfSize; + float extent = images.scale.z * halfSize * EXTENT_SCALE; if (distance < -extent - EPSILON) { info.outputValues[0] = AttributeValue(_outputs.at(0)); return STOP_RECURSION; From 2d535f3b867dd38952d9b739ed47c70b454cffca Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Fri, 4 Apr 2014 16:36:58 -0700 Subject: [PATCH 167/595] Removed debugging code. --- interface/src/ui/MetavoxelEditor.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index 87b04e53d5..71539d3a27 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -797,13 +797,9 @@ void Voxelizer::voxelize(const glm::vec3& center) { MetavoxelData data; data.setSize(_size); - qDebug() << "Started voxelizing " << center.x << center.y << center.z; - VoxelizationVisitor visitor(_directionImages, center, _granularity); data.guide(visitor); - qDebug() << "Finished voxelizing " << center.x << center.y << center.z; - MetavoxelEditMessage edit = { QVariant::fromValue(SetDataEdit( center - glm::vec3(_size, _size, _size) * 0.5f, data, true)) }; QMetaObject::invokeMethod(Application::getInstance()->getMetavoxels(), "applyEdit", @@ -869,8 +865,6 @@ void SetSpannerTool::applyEdit(const AttributePointer& attribute, const SharedOb glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, images.depth.data()); directionImages.append(images); - images.color.save(QString::number(i) + ".png"); - glMatrixMode(GL_PROJECTION); } glPopMatrix(); From 593fc6c96309acdc4534d841a89d862e1e0cd153 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 4 Apr 2014 17:29:39 -0700 Subject: [PATCH 168/595] lots of knobs and dials --- interface/src/Application.cpp | 25 +++-- interface/src/AudioReflector.cpp | 169 +++++++++++++++++++------------ interface/src/AudioReflector.h | 22 +++- interface/src/Menu.cpp | 14 ++- interface/src/Menu.h | 2 + 5 files changed, 154 insertions(+), 78 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 89f6a8e223..ac5a374a1f 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2787,7 +2787,7 @@ void Application::displayStats() { glm::vec3 avatarPos = _myAvatar->getPosition(); - lines = _statsExpanded ? 5 : 3; + lines = _statsExpanded ? 8 : 3; displayStatsBackground(backgroundColor, horizontalOffset, 0, _glWidget->width() - (mirrorEnabled ? 301 : 411) - horizontalOffset, lines * STATS_PELS_PER_LINE + 10); horizontalOffset += 5; @@ -2840,26 +2840,34 @@ void Application::displayStats() { // add some reflection stats char reflectionsStatus[128]; - sprintf(reflectionsStatus, "Reflections: %d, Pre-Delay: %f, Separate Ears:%s", + sprintf(reflectionsStatus, "Reflections: %d, Original: %s, Ears: %s, Source: %s", _audioReflector.getReflections(), - _audioReflector.getDelayFromDistance(0.0f), - debug::valueOf(Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingSeparateEars))); + (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingIncudeOriginal) + ? "with" : "without"), + (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingSeparateEars) + ? "two" : "one"), + (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingStereoSource) + ? "stereo" : "mono") + ); verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, WHITE_TEXT); - sprintf(reflectionsStatus, "Delay: average %f, max %f, min %f", + sprintf(reflectionsStatus, "Delay: pre: %f, average %f, max %f, min %f, speed: %f", + _audioReflector.getDelayFromDistance(0.0f), _audioReflector.getAverageDelayMsecs(), _audioReflector.getMaxDelayMsecs(), - _audioReflector.getMinDelayMsecs()); + _audioReflector.getMinDelayMsecs(), + _audioReflector.getSoundMsPerMeter()); verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, WHITE_TEXT); - sprintf(reflectionsStatus, "Attenuation: average %f, max %f, min %f", + sprintf(reflectionsStatus, "Attenuation: average %f, max %f, min %f, distance scale: %f", _audioReflector.getAverageAttenuation(), _audioReflector.getMaxAttenuation(), - _audioReflector.getMinAttenuation()); + _audioReflector.getMinAttenuation(), + _audioReflector.getDistanceAttenuationScalingFactor()); verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, WHITE_TEXT); @@ -3725,6 +3733,7 @@ void Application::loadScript(const QString& scriptName) { scriptEngine->registerGlobalObject("Menu", MenuScriptingInterface::getInstance()); scriptEngine->registerGlobalObject("Settings", SettingsScriptingInterface::getInstance()); scriptEngine->registerGlobalObject("AudioDevice", AudioDeviceScriptingInterface::getInstance()); + scriptEngine->registerGlobalObject("AudioReflector", &_audioReflector); QThread* workerThread = new QThread(this); diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index b7ee81ff1c..9a4da87014 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -11,8 +11,18 @@ #include "AudioReflector.h" #include "Menu.h" + +const float DEFAULT_PRE_DELAY = 20.0f; // this delay in msecs will always be added to all reflections +const float DEFAULT_MS_DELAY_PER_METER = 3.0f; +const float MINIMUM_ATTENUATION_TO_REFLECT = 1.0f / 256.0f; +const float DEFAULT_DISTANCE_SCALING_FACTOR = 2.0f; + + AudioReflector::AudioReflector(QObject* parent) : - QObject(parent) + QObject(parent), + _preDelay(DEFAULT_PRE_DELAY), + _soundMsPerMeter(DEFAULT_MS_DELAY_PER_METER), + _distanceAttenuationScalingFactor(DEFAULT_DISTANCE_SCALING_FACTOR) { reset(); } @@ -34,14 +44,12 @@ void AudioReflector::render() { // = 3ms per meter // attenuation = // BOUNCE_ATTENUATION_FACTOR [0.5] * (1/(1+distance)) -const float PRE_DELAY = 20.0f; // this delay in msecs will always be added to all reflections float AudioReflector::getDelayFromDistance(float distance) { - const int MS_DELAY_PER_METER = 3; - float delay = (MS_DELAY_PER_METER * distance); + float delay = (_soundMsPerMeter * distance); if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingPreDelay)) { - delay += PRE_DELAY; + delay += _preDelay; } @@ -52,14 +60,14 @@ float AudioReflector::getDelayFromDistance(float distance) { const float PER_BOUNCE_ATTENUATION_FACTOR = 0.5f; // **option 2**: we're not using these -const float BOUNCE_ATTENUATION_FACTOR = 0.125f; +//const float BOUNCE_ATTENUATION_FACTOR = 0.125f; // each bounce we adjust our attenuation by this factor, the result is an asymptotically decreasing attenuation... // 0.125, 0.25, 0.5, ... -const float PER_BOUNCE_ATTENUATION_ADJUSTMENT = 2.0f; +//const float PER_BOUNCE_ATTENUATION_ADJUSTMENT = 2.0f; // we don't grow larger than this, which means by the 4th bounce we don't get that much less quiet -const float MAX_BOUNCE_ATTENUATION = 0.99f; +//const float MAX_BOUNCE_ATTENUATION = 0.99f; -float getDistanceAttenuationCoefficient(float distance) { +float AudioReflector::getDistanceAttenuationCoefficient(float distance) { const float DISTANCE_SCALE = 2.5f; const float GEOMETRIC_AMPLITUDE_SCALAR = 0.3f; const float DISTANCE_LOG_BASE = 2.5f; @@ -72,13 +80,15 @@ float getDistanceAttenuationCoefficient(float distance) { DISTANCE_SCALE_LOG + (0.5f * logf(distanceSquareToSource) / logf(DISTANCE_LOG_BASE)) - 1); - const float DISTANCE_SCALING_FACTOR = 2.0f; - - distanceCoefficient = std::min(1.0f, distanceCoefficient * DISTANCE_SCALING_FACTOR); + distanceCoefficient = std::min(1.0f, distanceCoefficient * getDistanceAttenuationScalingFactor()); return distanceCoefficient; } +float getBounceAttenuationCoefficient(int bounceCount) { + return PER_BOUNCE_ATTENUATION_FACTOR * bounceCount; +} + glm::vec3 getFaceNormal(BoxFace face) { float surfaceRandomness = randFloatInRange(0.99,1.0); float surfaceRemainder = (1.0f - surfaceRandomness)/2.0f; @@ -128,29 +138,52 @@ void AudioReflector::calculateAllReflections() { // only recalculate when we've moved... // TODO: what about case where new voxels are added in front of us??? - if (_reflections == 0 || _myAvatar->getHead()->getPosition() != _origin) { + bool wantHeadOrientation = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingHeadOriented); + glm::quat orientation = wantHeadOrientation ? _myAvatar->getHead()->getFinalOrientation() : _myAvatar->getOrientation(); + + bool shouldRecalc = _reflections == 0 || _myAvatar->getHead()->getPosition() != _origin || (orientation != _orientation); + + /* + qDebug() << "wantHeadOrientation=" << wantHeadOrientation; + + qDebug(" _myAvatar->getHead()->getPosition()=%f,%f,%f", + _myAvatar->getHead()->getPosition().x, + _myAvatar->getHead()->getPosition().y, + _myAvatar->getHead()->getPosition().z); + + qDebug(" _origin=%f,%f,%f", + _origin.x, + _origin.y, + _origin.z); + + qDebug(" orientation=%f,%f,%f,%f", + orientation.x, + orientation.y, + orientation.z, + orientation.w); + + qDebug(" _orientation=%f,%f,%f,%f", + _orientation.x, + _orientation.y, + _orientation.z, + _orientation.w); + */ + if (shouldRecalc) { + //qDebug() << "origin or orientation has changed..."; + QMutexLocker locker(&_mutex); - qDebug() << "origin has changed..."; - qDebug(" _myAvatar->getHead()->getPosition()=%f,%f,%f", - _myAvatar->getHead()->getPosition().x, - _myAvatar->getHead()->getPosition().y, - _myAvatar->getHead()->getPosition().z); - - qDebug(" _origin=%f,%f,%f", - _origin.x, - _origin.y, - _origin.z); quint64 start = usecTimestampNow(); _origin = _myAvatar->getHead()->getPosition(); + glm::vec3 averageEarPosition = _myAvatar->getHead()->getPosition(); - glm::quat orientation = _myAvatar->getOrientation(); // _myAvatar->getHead()->getOrientation(); - glm::vec3 right = glm::normalize(orientation * IDENTITY_RIGHT); - glm::vec3 up = glm::normalize(orientation * IDENTITY_UP); - glm::vec3 front = glm::normalize(orientation * IDENTITY_FRONT); + _orientation = orientation; + glm::vec3 right = glm::normalize(_orientation * IDENTITY_RIGHT); + glm::vec3 up = glm::normalize(_orientation * IDENTITY_UP); + glm::vec3 front = glm::normalize(_orientation * IDENTITY_FRONT); glm::vec3 left = -right; glm::vec3 down = -up; glm::vec3 back = -front; @@ -163,33 +196,31 @@ void AudioReflector::calculateAllReflections() { glm::vec3 backRightDown = glm::normalize(back + right + down); glm::vec3 backLeftDown = glm::normalize(back + left + down); - const int BOUNCE_COUNT = 5; - - _frontRightUpReflections = calculateReflections(_origin, frontRightUp, BOUNCE_COUNT); - _frontLeftUpReflections = calculateReflections(_origin, frontLeftUp, BOUNCE_COUNT); - _backRightUpReflections = calculateReflections(_origin, backRightUp, BOUNCE_COUNT); - _backLeftUpReflections = calculateReflections(_origin, backLeftUp, BOUNCE_COUNT); - _frontRightDownReflections = calculateReflections(_origin, frontRightDown, BOUNCE_COUNT); - _frontLeftDownReflections = calculateReflections(_origin, frontLeftDown, BOUNCE_COUNT); - _backRightDownReflections = calculateReflections(_origin, backRightDown, BOUNCE_COUNT); - _backLeftDownReflections = calculateReflections(_origin, backLeftDown, BOUNCE_COUNT); - _frontReflections = calculateReflections(_origin, front, BOUNCE_COUNT); - _backReflections = calculateReflections(_origin, back, BOUNCE_COUNT); - _leftReflections = calculateReflections(_origin, left, BOUNCE_COUNT); - _rightReflections = calculateReflections(_origin, right, BOUNCE_COUNT); - _upReflections = calculateReflections(_origin, up, BOUNCE_COUNT); - _downReflections = calculateReflections(_origin, down, BOUNCE_COUNT); + _frontRightUpReflections = calculateReflections(averageEarPosition, _origin, frontRightUp); + _frontLeftUpReflections = calculateReflections(averageEarPosition, _origin, frontLeftUp); + _backRightUpReflections = calculateReflections(averageEarPosition, _origin, backRightUp); + _backLeftUpReflections = calculateReflections(averageEarPosition, _origin, backLeftUp); + _frontRightDownReflections = calculateReflections(averageEarPosition, _origin, frontRightDown); + _frontLeftDownReflections = calculateReflections(averageEarPosition, _origin, frontLeftDown); + _backRightDownReflections = calculateReflections(averageEarPosition, _origin, backRightDown); + _backLeftDownReflections = calculateReflections(averageEarPosition, _origin, backLeftDown); + _frontReflections = calculateReflections(averageEarPosition, _origin, front); + _backReflections = calculateReflections(averageEarPosition, _origin, back); + _leftReflections = calculateReflections(averageEarPosition, _origin, left); + _rightReflections = calculateReflections(averageEarPosition, _origin, right); + _upReflections = calculateReflections(averageEarPosition, _origin, up); + _downReflections = calculateReflections(averageEarPosition, _origin, down); quint64 end = usecTimestampNow(); reset(); - qDebug() << "Reflections recalculated in " << (end - start) << "usecs"; + //qDebug() << "Reflections recalculated in " << (end - start) << "usecs"; } } -QVector AudioReflector::calculateReflections(const glm::vec3& origin, const glm::vec3& originalDirection, int maxBounces) { +QVector AudioReflector::calculateReflections(const glm::vec3& earPosition, const glm::vec3& origin, const glm::vec3& originalDirection) { QVector reflectionPoints; glm::vec3 start = origin; glm::vec3 direction = originalDirection; @@ -197,16 +228,28 @@ QVector AudioReflector::calculateReflections(const glm::vec3& origin, float distance; BoxFace face; const float SLIGHTLY_SHORT = 0.999f; // slightly inside the distance so we're on the inside of the reflection point + float currentAttenuation = 1.0f; + float totalDistance = 0.0f; + int bounceCount = 1; - for (int i = 0; i < maxBounces; i++) { + while (currentAttenuation > MINIMUM_ATTENUATION_TO_REFLECT) { if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); + + totalDistance += glm::distance(start, end); + float earDistance = glm::distance(end, earPosition); + float totalDistance = earDistance + distance; + currentAttenuation = getDistanceAttenuationCoefficient(totalDistance) * getBounceAttenuationCoefficient(bounceCount); - reflectionPoints.push_back(end); - - glm::vec3 faceNormal = getFaceNormal(face); - direction = glm::normalize(glm::reflect(direction,faceNormal)); - start = end; + if (currentAttenuation > MINIMUM_ATTENUATION_TO_REFLECT) { + reflectionPoints.push_back(end); + glm::vec3 faceNormal = getFaceNormal(face); + direction = glm::normalize(glm::reflect(direction,faceNormal)); + start = end; + bounceCount++; + } + } else { + currentAttenuation = 0.0f; } } return reflectionPoints; @@ -234,6 +277,7 @@ void AudioReflector::echoReflections(const glm::vec3& origin, const QVectorisOptionChecked(MenuOption::AudioSpatialProcessingSeparateEars); + bool wantStereo = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingStereoSource); glm::vec3 rightEarPosition = wantEarSeparation ? _myAvatar->getHead()->getRightEarPosition() : _myAvatar->getHead()->getPosition(); glm::vec3 leftEarPosition = wantEarSeparation ? _myAvatar->getHead()->getLeftEarPosition() : @@ -254,12 +298,10 @@ void AudioReflector::echoReflections(const glm::vec3& origin, const QVector& reflections, const QByteArray& samples, unsigned int sampleTime, int sampleRate); - QVector calculateReflections(const glm::vec3& origin, const glm::vec3& originalDirection, int maxBounces); + QVector calculateReflections(const glm::vec3& earPosition, const glm::vec3& origin, const glm::vec3& originalDirection); void drawReflections(const glm::vec3& origin, const glm::vec3& originalColor, const QVector& reflections); void calculateAllReflections(); void reset(); + float getDistanceAttenuationCoefficient(float distance); int _reflections; @@ -73,6 +84,7 @@ private: float _minAttenuation; glm::vec3 _origin; + glm::quat _orientation; QVector _frontRightUpReflections; QVector _frontLeftUpReflections; QVector _backRightUpReflections; @@ -89,6 +101,10 @@ private: QVector _downReflections; QMutex _mutex; + + float _preDelay; + float _soundMsPerMeter; + float _distanceAttenuationScalingFactor; }; diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index f0c7b27780..1a0adb5550 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -331,8 +331,8 @@ Menu::Menu() : QMenu* renderDebugMenu = developerMenu->addMenu("Render Debugging Tools"); - addCheckableActionToQMenuAndActionHash(renderDebugMenu, MenuOption::PipelineWarnings, Qt::CTRL | Qt::SHIFT | Qt::Key_P); - addCheckableActionToQMenuAndActionHash(renderDebugMenu, MenuOption::SuppressShortTimings, Qt::CTRL | Qt::SHIFT | Qt::Key_S); + addCheckableActionToQMenuAndActionHash(renderDebugMenu, MenuOption::PipelineWarnings); + addCheckableActionToQMenuAndActionHash(renderDebugMenu, MenuOption::SuppressShortTimings); addCheckableActionToQMenuAndActionHash(renderDebugMenu, MenuOption::CullSharedFaces, @@ -383,7 +383,15 @@ Menu::Menu() : addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingPreDelay, Qt::CTRL | Qt::SHIFT | Qt::Key_D, true); - + + addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingStereoSource, + Qt::CTRL | Qt::SHIFT | Qt::Key_S, + true); + + addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingHeadOriented, + Qt::CTRL | Qt::SHIFT | Qt::Key_H, + true); + addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::LowPassFilter, Qt::CTRL | Qt::SHIFT | Qt::Key_F, false); diff --git a/interface/src/Menu.h b/interface/src/Menu.h index fbaf8b57a7..fd7873fae9 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -247,6 +247,8 @@ namespace MenuOption { const QString AudioSpatialProcessingIncudeOriginal = "Audio Spatial Processing includes Original"; const QString AudioSpatialProcessingSeparateEars = "Audio Spatial Processing separates ears"; const QString AudioSpatialProcessingPreDelay = "Audio Spatial Processing add Pre-Delay"; + const QString AudioSpatialProcessingStereoSource = "Audio Spatial Processing Stereo Source"; + const QString AudioSpatialProcessingHeadOriented = "Audio Spatial Processing Head Oriented"; const QString EchoServerAudio = "Echo Server Audio"; const QString EchoLocalAudio = "Echo Local Audio"; const QString MuteAudio = "Mute Microphone"; From d198b04daf891655fb6fbff88eabbd3256882fc6 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 4 Apr 2014 17:29:50 -0700 Subject: [PATCH 169/595] lots of knobs and dials --- examples/audioReflectorTools.js | 208 ++++++++++++++++++++++++++++++++ 1 file changed, 208 insertions(+) create mode 100644 examples/audioReflectorTools.js diff --git a/examples/audioReflectorTools.js b/examples/audioReflectorTools.js new file mode 100644 index 0000000000..e19e757367 --- /dev/null +++ b/examples/audioReflectorTools.js @@ -0,0 +1,208 @@ +// +// overlaysExample.js +// hifi +// +// Created by Brad Hefta-Gaub on 2/14/14. +// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// +// This is an example script that demonstrates use of the Overlays class +// +// + + +var delayScale = 100.0; +var speedScale = 20; +var factorScale = 5.0; + +// This will create a couple of image overlays that make a "slider", we will demonstrate how to trap mouse messages to +// move the slider +var delayY = 300; +var delaySlider = Overlays.addOverlay("image", { + // alternate form of expressing bounds + bounds: { x: 100, y: delayY, width: 150, height: 35}, + subImage: { x: 46, y: 0, width: 200, height: 71 }, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/slider.png", + color: { red: 255, green: 255, blue: 255}, + alpha: 1 + }); + +// This is the thumb of our slider +var delayMinThumbX = 110; +var delayMaxThumbX = delayMinThumbX + 110; +var delayThumbX = (delayMinThumbX + delayMaxThumbX) / 2; +var delayThumb = Overlays.addOverlay("image", { + x: delayThumbX, + y: delayY + 9, + width: 18, + height: 17, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/thumb.png", + color: { red: 255, green: 255, blue: 255}, + alpha: 1 + }); + +// This will create a couple of image overlays that make a "slider", we will demonstrate how to trap mouse messages to +// move the slider +var speedY = 350; +var speedSlider = Overlays.addOverlay("image", { + // alternate form of expressing bounds + bounds: { x: 100, y: speedY, width: 150, height: 35}, + subImage: { x: 46, y: 0, width: 200, height: 71 }, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/slider.png", + color: { red: 255, green: 255, blue: 255}, + alpha: 1 + }); + +// This is the thumb of our slider +var speedMinThumbX = 110; +var speedMaxThumbX = speedMinThumbX + 110; +var speedThumbX = (speedMinThumbX + speedMaxThumbX) / 2; +var speedThumb = Overlays.addOverlay("image", { + x: speedThumbX, + y: speedY+9, + width: 18, + height: 17, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/thumb.png", + color: { red: 255, green: 255, blue: 255}, + alpha: 1 + }); + +// This will create a couple of image overlays that make a "slider", we will demonstrate how to trap mouse messages to +// move the slider +var factorY = 400; +var factorSlider = Overlays.addOverlay("image", { + // alternate form of expressing bounds + bounds: { x: 100, y: factorY, width: 150, height: 35}, + subImage: { x: 46, y: 0, width: 200, height: 71 }, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/slider.png", + color: { red: 255, green: 255, blue: 255}, + alpha: 1 + }); + +// This is the thumb of our slider +var factorMinThumbX = 110; +var factorMaxThumbX = factorMinThumbX + 110; +var factorThumbX = (factorMinThumbX + factorMaxThumbX) / 2; +var factorThumb = Overlays.addOverlay("image", { + x: factorThumbX, + y: factorY+9, + width: 18, + height: 17, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/thumb.png", + color: { red: 255, green: 255, blue: 255}, + alpha: 1 + }); + + +// When our script shuts down, we should clean up all of our overlays +function scriptEnding() { + Overlays.deleteOverlay(factorThumb); + Overlays.deleteOverlay(factorSlider); + Overlays.deleteOverlay(speedThumb); + Overlays.deleteOverlay(speedSlider); + Overlays.deleteOverlay(delayThumb); + Overlays.deleteOverlay(delaySlider); +} +Script.scriptEnding.connect(scriptEnding); + + +var count = 0; + +// Our update() function is called at approximately 60fps, and we will use it to animate our various overlays +function update(deltaTime) { + count++; +} +Script.update.connect(update); + + +// The slider is handled in the mouse event callbacks. +var movingSliderDelay = false; +var movingSliderSpeed = false; +var movingSliderFactor = false; +var thumbClickOffsetX = 0; +function mouseMoveEvent(event) { + if (movingSliderDelay) { + newThumbX = event.x - thumbClickOffsetX; + if (newThumbX < delayMinThumbX) { + newThumbX = delayMinThumbX; + } + if (newThumbX > delayMaxThumbX) { + newThumbX = delayMaxThumbX; + } + Overlays.editOverlay(delayThumb, { x: newThumbX } ); + var delay = ((newThumbX - delayMinThumbX) / (delayMaxThumbX - delayMinThumbX)) * delayScale; + AudioReflector.setPreDelay(delay); + } + if (movingSliderSpeed) { + newThumbX = event.x - thumbClickOffsetX; + if (newThumbX < speedMinThumbX) { + newThumbX = speedMminThumbX; + } + if (newThumbX > speedMaxThumbX) { + newThumbX = speedMaxThumbX; + } + Overlays.editOverlay(speedThumb, { x: newThumbX } ); + var speed = ((newThumbX - speedMinThumbX) / (speedMaxThumbX - speedMinThumbX)) * speedScale; + AudioReflector.setSoundMsPerMeter(speed); + } + if (movingSliderFactor) { + newThumbX = event.x - thumbClickOffsetX; + if (newThumbX < factorMinThumbX) { + newThumbX = factorMminThumbX; + } + if (newThumbX > factorMaxThumbX) { + newThumbX = factorMaxThumbX; + } + Overlays.editOverlay(factorThumb, { x: newThumbX } ); + var factor = ((newThumbX - factorMinThumbX) / (factorMaxThumbX - factorMinThumbX)) * factorScale; + AudioReflector.setDistanceAttenuationScalingFactor(factor); + } +} + +// we also handle click detection in our mousePressEvent() +function mousePressEvent(event) { + var clickedOverlay = Overlays.getOverlayAtPoint({x: event.x, y: event.y}); + + // If the user clicked on the thumb, handle the slider logic + if (clickedOverlay == delayThumb) { + movingSliderDelay = true; + thumbClickOffsetX = event.x - delayThumbX; + } + + // If the user clicked on the thumb, handle the slider logic + if (clickedOverlay == speedThumb) { + movingSliderSpeed = true; + thumbClickOffsetX = event.x - speedThumbX; + } + + // If the user clicked on the thumb, handle the slider logic + if (clickedOverlay == factorThumb) { +print("movingSliderFactor..."); + movingSliderFactor = true; + thumbClickOffsetX = event.x - factorThumbX; + } +} +function mouseReleaseEvent(event) { + if (movingSliderDelay) { + movingSliderDelay = false; + var delay = ((newThumbX - delayMinThumbX) / (delayMaxThumbX - delayMinThumbX)) * delayScale; + AudioReflector.setPreDelay(delay); + delayThumbX = newThumbX; + } + if (movingSliderSpeed) { + movingSliderSpeed = false; + var speed = ((newThumbX - speedMinThumbX) / (speedMaxThumbX - speedMinThumbX)) * speedScale; + AudioReflector.setSoundMsPerMeter(speed); + speedThumbX = newThumbX; + } + if (movingSliderFactor) { + movingSliderFactor = false; + var factor = ((newThumbX - factorMinThumbX) / (factorMaxThumbX - factorMinThumbX)) * factorScale; + AudioReflector.setDistanceAttenuationScalingFactor(factor); + factorThumbX = newThumbX; + } +} + +Controller.mouseMoveEvent.connect(mouseMoveEvent); +Controller.mousePressEvent.connect(mousePressEvent); +Controller.mouseReleaseEvent.connect(mouseReleaseEvent); + From ba5a092ad7287baf2033caeab9042b01fd6ced24 Mon Sep 17 00:00:00 2001 From: stojce Date: Sun, 6 Apr 2014 15:30:30 +0200 Subject: [PATCH 170/595] Frameless dialog position/size fixes Fixed frameless dialog size and position on main window resize and move --- interface/src/Menu.cpp | 4 +- interface/src/ui/FramelessDialog.cpp | 93 ++++++++++++++++++++++++---- interface/src/ui/FramelessDialog.h | 12 ++-- 3 files changed, 90 insertions(+), 19 deletions(-) diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 859b3250be..9615238b36 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -717,9 +717,9 @@ void Menu::loginForCurrentDomain() { void Menu::editPreferences() { if (!_preferencesDialog) { - Application::getInstance()->getWindow()->addDockWidget(Qt::LeftDockWidgetArea, _preferencesDialog = new PreferencesDialog()); + _preferencesDialog = new PreferencesDialog(Application::getInstance()->getWindow()); + _preferencesDialog->show(); } else { - Application::getInstance()->getWindow()->removeDockWidget(_preferencesDialog); _preferencesDialog->close(); } } diff --git a/interface/src/ui/FramelessDialog.cpp b/interface/src/ui/FramelessDialog.cpp index 40388b2f5f..14f7e57f3b 100644 --- a/interface/src/ui/FramelessDialog.cpp +++ b/interface/src/ui/FramelessDialog.cpp @@ -6,26 +6,65 @@ // // -#include -#include -#include -#include -#include - #include "Application.h" #include "FramelessDialog.h" +const int RESIZE_HANDLE_WIDTH = 7; + FramelessDialog::FramelessDialog(QWidget *parent, Qt::WindowFlags flags) : - QDockWidget(parent, flags) { +QDialog(parent, flags | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint) { setAttribute(Qt::WA_DeleteOnClose); - // set as floating - setFeatures(QDockWidget::DockWidgetFloatable); + // handle rezize and move events + parentWidget()->installEventFilter(this); - // remove titlebar - setTitleBarWidget(new QWidget()); + // handle minimize, restore and focus events + Application::getInstance()->installEventFilter(this); +} - setAllowedAreas(Qt::LeftDockWidgetArea); +bool FramelessDialog::eventFilter(QObject* sender, QEvent* event) { + switch (event->type()) { + case QEvent::Move: + + if (sender == parentWidget()) { + // move to upper left corner on app move + move(parentWidget()->geometry().topLeft()); + } + break; + + case QEvent::Resize: + if (sender == parentWidget()) { + // keep full app height on resizing the app + setFixedHeight(parentWidget()->size().height()); + } + break; + + case QEvent::WindowStateChange: + if (parentWidget()->isMinimized()) { + setHidden(true); + } else { + setHidden(false); + } + break; + + case QEvent::ApplicationDeactivate: + // hide on minimize and focus lost + setHidden(true); + break; + + case QEvent::ApplicationActivate: + setHidden(false); + break; + + default: + break; + } + + return false; +} + +FramelessDialog::~FramelessDialog() { + deleteLater(); } void FramelessDialog::setStyleSheetFile(const QString& fileName) { @@ -36,3 +75,33 @@ void FramelessDialog::setStyleSheetFile(const QString& fileName) { setStyleSheet(globalStyleSheet.readAll() + styleSheet.readAll()); } } + +void FramelessDialog::showEvent(QShowEvent* event) { + // move to upper left corner + move(parentWidget()->geometry().topLeft()); + + // keep full app height + setFixedHeight(parentWidget()->size().height()); + + // resize parrent if width is smaller than this dialog + if (parentWidget()->size().width() < size().width()) { + parentWidget()->resize(size().width(), parentWidget()->size().height()); + } +} +void FramelessDialog::mousePressEvent(QMouseEvent* mouseEvent) { + if (abs(mouseEvent->pos().x() - size().width()) < RESIZE_HANDLE_WIDTH && mouseEvent->button() == Qt::LeftButton) { + _isResizing = true; + QApplication::setOverrideCursor(Qt::SizeHorCursor); + } +} + +void FramelessDialog::mouseReleaseEvent(QMouseEvent* mouseEvent) { + QApplication::restoreOverrideCursor(); + _isResizing = false; +} + +void FramelessDialog::mouseMoveEvent(QMouseEvent* mouseEvent) { + if (_isResizing) { + resize(mouseEvent->pos().x(), size().height()); + } +} diff --git a/interface/src/ui/FramelessDialog.h b/interface/src/ui/FramelessDialog.h index 5c55f3de25..f13219a688 100644 --- a/interface/src/ui/FramelessDialog.h +++ b/interface/src/ui/FramelessDialog.h @@ -9,27 +9,29 @@ #ifndef __hifi__FramelessDialog__ #define __hifi__FramelessDialog__ -#include +#include #include #include #include #include #include -class FramelessDialog : public QDockWidget { +class FramelessDialog : public QDialog { Q_OBJECT public: FramelessDialog(QWidget* parent = 0, Qt::WindowFlags flags = 0); + ~FramelessDialog(); void setStyleSheetFile(const QString& fileName); protected: - /* virtual void mouseMoveEvent(QMouseEvent* mouseEvent); virtual void mousePressEvent(QMouseEvent* mouseEvent); virtual void mouseReleaseEvent(QMouseEvent* mouseEvent); - */ - + virtual void showEvent(QShowEvent* event); + + bool eventFilter(QObject* sender, QEvent* event); + private: bool _isResizing; From dd5a19874012c5c420aefa22217fcbb40ef36bfc Mon Sep 17 00:00:00 2001 From: stojce Date: Sun, 6 Apr 2014 16:13:15 +0200 Subject: [PATCH 171/595] Models browser fixes --- interface/src/ui/FramelessDialog.h | 5 ----- interface/src/ui/ModelsBrowser.cpp | 2 +- interface/src/ui/PreferencesDialog.cpp | 17 +++++++++++++++-- interface/src/ui/PreferencesDialog.h | 2 ++ 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/interface/src/ui/FramelessDialog.h b/interface/src/ui/FramelessDialog.h index f13219a688..aa83960b8b 100644 --- a/interface/src/ui/FramelessDialog.h +++ b/interface/src/ui/FramelessDialog.h @@ -10,11 +10,6 @@ #define __hifi__FramelessDialog__ #include -#include -#include -#include -#include -#include class FramelessDialog : public QDialog { Q_OBJECT diff --git a/interface/src/ui/ModelsBrowser.cpp b/interface/src/ui/ModelsBrowser.cpp index 616aba3881..52c10a51d7 100644 --- a/interface/src/ui/ModelsBrowser.cpp +++ b/interface/src/ui/ModelsBrowser.cpp @@ -62,7 +62,7 @@ static const QString propertiesIds[MODEL_METADATA_COUNT] = { }; ModelsBrowser::ModelsBrowser(ModelType modelsType, QWidget* parent) : - QWidget(parent), + QWidget(parent, Qt::WindowStaysOnTopHint), _handler(new ModelHandler(modelsType)) { connect(_handler, SIGNAL(doneDownloading()), SLOT(resizeView())); diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index 3aa439558a..96ffe662c7 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -21,6 +21,7 @@ PreferencesDialog::PreferencesDialog(QWidget* parent, Qt::WindowFlags flags) : F setStyleSheetFile("styles/preferences.qss"); loadPreferences(); connect(ui.closeButton, &QPushButton::clicked, this, &QDialog::close); + connect(ui.buttonBrowseHead, &QPushButton::clicked, this, &PreferencesDialog::openHeadModelBrowser); connect(ui.buttonBrowseBody, &QPushButton::clicked, this, &PreferencesDialog::openBodyModelBrowser); } @@ -34,16 +35,28 @@ void PreferencesDialog::accept() { close(); } +void PreferencesDialog::setHeadUrl(QString modelUrl) { + ui.faceURLEdit->setText(modelUrl); + setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint); +} + +void PreferencesDialog::setSkeletonUrl(QString modelUrl) { + ui.skeletonURLEdit->setText(modelUrl); + setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint); +} + void PreferencesDialog::openHeadModelBrowser() { + setWindowFlags(windowFlags() & ~Qt::WindowStaysOnTopHint); ModelsBrowser modelBrowser(Head); + connect(&modelBrowser, &ModelsBrowser::selected, this, &PreferencesDialog::setHeadUrl); modelBrowser.browse(); - connect(&modelBrowser, &ModelsBrowser::selected, ui.faceURLEdit, &QLineEdit::setText); } void PreferencesDialog::openBodyModelBrowser() { + setWindowFlags(windowFlags() & ~Qt::WindowStaysOnTopHint); ModelsBrowser modelBrowser(Skeleton); + connect(&modelBrowser, &ModelsBrowser::selected, this, &PreferencesDialog::setSkeletonUrl); modelBrowser.browse(); - connect(&modelBrowser, &ModelsBrowser::selected, ui.skeletonURLEdit, &QLineEdit::setText); } void PreferencesDialog::resizeEvent(QResizeEvent *resizeEvent) { diff --git a/interface/src/ui/PreferencesDialog.h b/interface/src/ui/PreferencesDialog.h index f1f37c66cd..c7f8f43616 100644 --- a/interface/src/ui/PreferencesDialog.h +++ b/interface/src/ui/PreferencesDialog.h @@ -37,6 +37,8 @@ private: private slots: void accept(); + void setHeadUrl(QString modelUrl); + void setSkeletonUrl(QString modelUrl); }; From dfd6411a4fd83d3636ca8e3d7758d1b04f37e3a4 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Sun, 6 Apr 2014 10:11:11 -0700 Subject: [PATCH 172/595] add hooks for local audio echo, first cut at diffusion --- interface/src/Application.cpp | 3 +- interface/src/Audio.cpp | 9 ++- interface/src/Audio.h | 3 +- interface/src/AudioReflector.cpp | 134 +++++++++++++++++++++++++++---- interface/src/AudioReflector.h | 15 +++- 5 files changed, 142 insertions(+), 22 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index ac5a374a1f..4a7da51887 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1603,7 +1603,8 @@ void Application::init() { _audioReflector.setMyAvatar(getAvatar()); _audioReflector.setVoxels(_voxels.getTree()); _audioReflector.setAudio(getAudio()); - connect(getAudio(), &Audio::processSpatialAudio, &_audioReflector, &AudioReflector::processSpatialAudio,Qt::DirectConnection); + connect(getAudio(), &Audio::processInboundAudio, &_audioReflector, &AudioReflector::processInboundAudio,Qt::DirectConnection); + connect(getAudio(), &Audio::processLocalAudio, &_audioReflector, &AudioReflector::processLocalAudio,Qt::DirectConnection); } void Application::closeMirrorView() { diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 708bb72cc7..f7bb3f78c9 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -360,6 +360,11 @@ void Audio::handleAudioInput() { QByteArray inputByteArray = _inputDevice->readAll(); + // send our local loopback to any interested parties + if (_processSpatialAudio && !_muted && _audioOutput) { + emit processLocalAudio(_spatialAudioStart, inputByteArray, _inputFormat); + } + if (Menu::getInstance()->isOptionChecked(MenuOption::EchoLocalAudio) && !_muted && _audioOutput) { // if this person wants local loopback add that to the locally injected audio @@ -367,7 +372,7 @@ void Audio::handleAudioInput() { // we didn't have the loopback output device going so set that up now _loopbackOutputDevice = _loopbackAudioOutput->start(); } - + if (_inputFormat == _outputFormat) { if (_loopbackOutputDevice) { _loopbackOutputDevice->write(inputByteArray); @@ -756,7 +761,7 @@ void Audio::processReceivedAudio(AudioRingBuffer& ringBuffer) { } // Send audio off for spatial processing - emit processSpatialAudio(sampleTime, buffer, _desiredOutputFormat); + emit processInboundAudio(sampleTime, buffer, _desiredOutputFormat); // copy the samples we'll resample from the spatial audio ring buffer - this also // pushes the read pointer of the spatial audio ring buffer forwards diff --git a/interface/src/Audio.h b/interface/src/Audio.h index c3417ae891..e449d8f6c7 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -102,7 +102,8 @@ public slots: signals: bool muteToggled(); - void processSpatialAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); + void processInboundAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); + void processLocalAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); private: diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 9a4da87014..6c4e78eae2 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -16,13 +16,16 @@ const float DEFAULT_PRE_DELAY = 20.0f; // this delay in msecs will always be add const float DEFAULT_MS_DELAY_PER_METER = 3.0f; const float MINIMUM_ATTENUATION_TO_REFLECT = 1.0f / 256.0f; const float DEFAULT_DISTANCE_SCALING_FACTOR = 2.0f; - +const float MAXIMUM_DELAY_MS = 1000.0 * 20.0f; // stop reflecting after path is this long +const int DEFAULT_DIFFUSION_FANOUT = 2; +const int ABSOLUTE_MAXIMUM_BOUNCE_COUNT = 10; AudioReflector::AudioReflector(QObject* parent) : QObject(parent), _preDelay(DEFAULT_PRE_DELAY), _soundMsPerMeter(DEFAULT_MS_DELAY_PER_METER), - _distanceAttenuationScalingFactor(DEFAULT_DISTANCE_SCALING_FACTOR) + _distanceAttenuationScalingFactor(DEFAULT_DISTANCE_SCALING_FACTOR), + _diffusionFanout(DEFAULT_DIFFUSION_FANOUT) { reset(); } @@ -90,22 +93,27 @@ float getBounceAttenuationCoefficient(int bounceCount) { } glm::vec3 getFaceNormal(BoxFace face) { - float surfaceRandomness = randFloatInRange(0.99,1.0); + glm::vec3 slightlyRandomFaceNormal; + + float surfaceRandomness = randFloatInRange(0.99f,1.0f); float surfaceRemainder = (1.0f - surfaceRandomness)/2.0f; + float altRemainderSignA = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; + float altRemainderSignB = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; + if (face == MIN_X_FACE) { - return glm::vec3(-surfaceRandomness, surfaceRemainder, surfaceRemainder); + slightlyRandomFaceNormal = glm::vec3(-surfaceRandomness, surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB); } else if (face == MAX_X_FACE) { - return glm::vec3(surfaceRandomness, surfaceRemainder, surfaceRemainder); + slightlyRandomFaceNormal = glm::vec3(surfaceRandomness, surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB); } else if (face == MIN_Y_FACE) { - return glm::vec3(surfaceRemainder, -surfaceRandomness, surfaceRemainder); + slightlyRandomFaceNormal = glm::vec3(surfaceRemainder * altRemainderSignA, -surfaceRandomness, surfaceRemainder * altRemainderSignB); } else if (face == MAX_Y_FACE) { - return glm::vec3(surfaceRemainder, surfaceRandomness, surfaceRemainder); + slightlyRandomFaceNormal = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRandomness, surfaceRemainder * altRemainderSignB); } else if (face == MIN_Z_FACE) { - return glm::vec3(surfaceRemainder, surfaceRemainder, -surfaceRandomness); + slightlyRandomFaceNormal = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB, -surfaceRandomness); } else if (face == MAX_Z_FACE) { - return glm::vec3(surfaceRemainder, surfaceRemainder, surfaceRandomness); + slightlyRandomFaceNormal = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB, surfaceRandomness); } - return glm::vec3(0, 0, 0); //error case + return slightlyRandomFaceNormal; } void AudioReflector::reset() { @@ -214,13 +222,96 @@ void AudioReflector::calculateAllReflections() { quint64 end = usecTimestampNow(); reset(); - + //qDebug() << "Reflections recalculated in " << (end - start) << "usecs"; } } -QVector AudioReflector::calculateReflections(const glm::vec3& earPosition, const glm::vec3& origin, const glm::vec3& originalDirection) { +// TODO: add diffusion ratio. percentage of echo energy that diffuses +// so say that 50% of the energy that hits the echo point diffuses in fanout directions +void AudioReflector::calculateDiffusions(const glm::vec3& earPosition, const glm::vec3& origin, + const glm::vec3& thisReflection, float thisDistance, float thisAttenuation, int thisBounceCount, + BoxFace thisReflectionFace, QVector reflectionPoints) { + + //return; // do nothing + + QVector diffusionDirections; + + // diffusions fan out from random places on the semisphere of the collision point + for(int i = 0; i < _diffusionFanout; i++) { + glm::vec3 randomDirection; + + float surfaceRandomness = randFloatInRange(0.5f,1.0f); + float surfaceRemainder = (1.0f - surfaceRandomness)/2.0f; + float altRemainderSignA = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; + float altRemainderSignB = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; + + if (thisReflectionFace == MIN_X_FACE) { + randomDirection = glm::vec3(-surfaceRandomness, surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB); + } else if (thisReflectionFace == MAX_X_FACE) { + randomDirection = glm::vec3(surfaceRandomness, surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB); + } else if (thisReflectionFace == MIN_Y_FACE) { + randomDirection = glm::vec3(surfaceRemainder * altRemainderSignA, -surfaceRandomness, surfaceRemainder * altRemainderSignB); + } else if (thisReflectionFace == MAX_Y_FACE) { + randomDirection = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRandomness, surfaceRemainder * altRemainderSignB); + } else if (thisReflectionFace == MIN_Z_FACE) { + randomDirection = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB, -surfaceRandomness); + } else if (thisReflectionFace == MAX_Z_FACE) { + randomDirection = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB, surfaceRandomness); + } + diffusionDirections.push_back(randomDirection); + } + + foreach(glm::vec3 direction, diffusionDirections) { + + glm::vec3 start = thisReflection; + OctreeElement* elementHit; + float distance; + BoxFace face; + const float SLIGHTLY_SHORT = 0.999f; // slightly inside the distance so we're on the inside of the reflection point + float currentAttenuation = thisAttenuation; + float totalDistance = thisDistance; + float totalDelay = getDelayFromDistance(totalDistance); + int bounceCount = thisBounceCount; + + while (currentAttenuation > MINIMUM_ATTENUATION_TO_REFLECT && totalDelay < MAXIMUM_DELAY_MS && bounceCount < ABSOLUTE_MAXIMUM_BOUNCE_COUNT) { + if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { + glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); + + totalDistance += glm::distance(start, end); + float earDistance = glm::distance(end, earPosition); + float totalDistanceToEar = earDistance + distance; + totalDelay = getDelayFromDistance(totalDistanceToEar); + currentAttenuation = getDistanceAttenuationCoefficient(totalDistanceToEar) * getBounceAttenuationCoefficient(bounceCount); + + if (currentAttenuation > MINIMUM_ATTENUATION_TO_REFLECT && totalDelay < MAXIMUM_DELAY_MS) { + reflectionPoints.push_back(end); + glm::vec3 faceNormal = getFaceNormal(face); + direction = glm::normalize(glm::reflect(direction,faceNormal)); + start = end; + bounceCount++; + + /* + // handle diffusion here + if (_diffusionFanout > 0 && bounceCount < ABSOLUTE_MAXIMUM_BOUNCE_COUNT) { + glm::vec3 thisReflection = end; + calculateDiffusions(earPosition, origin, end, totalDistance, + currentAttenuation, bounceCount, face, reflectionPoints); + } + */ + } + } else { + currentAttenuation = 0.0f; + } + } + } +} + + +QVector AudioReflector::calculateReflections(const glm::vec3& earPosition, + const glm::vec3& origin, const glm::vec3& originalDirection) { + QVector reflectionPoints; glm::vec3 start = origin; glm::vec3 direction = originalDirection; @@ -230,23 +321,32 @@ QVector AudioReflector::calculateReflections(const glm::vec3& earPosi const float SLIGHTLY_SHORT = 0.999f; // slightly inside the distance so we're on the inside of the reflection point float currentAttenuation = 1.0f; float totalDistance = 0.0f; + float totalDelay = 0.0f; int bounceCount = 1; - while (currentAttenuation > MINIMUM_ATTENUATION_TO_REFLECT) { + while (currentAttenuation > MINIMUM_ATTENUATION_TO_REFLECT && totalDelay < MAXIMUM_DELAY_MS && bounceCount < ABSOLUTE_MAXIMUM_BOUNCE_COUNT) { if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); totalDistance += glm::distance(start, end); float earDistance = glm::distance(end, earPosition); float totalDistance = earDistance + distance; + totalDelay = getDelayFromDistance(totalDistance); currentAttenuation = getDistanceAttenuationCoefficient(totalDistance) * getBounceAttenuationCoefficient(bounceCount); - if (currentAttenuation > MINIMUM_ATTENUATION_TO_REFLECT) { + if (currentAttenuation > MINIMUM_ATTENUATION_TO_REFLECT && totalDelay < MAXIMUM_DELAY_MS) { reflectionPoints.push_back(end); glm::vec3 faceNormal = getFaceNormal(face); direction = glm::normalize(glm::reflect(direction,faceNormal)); start = end; bounceCount++; + + // handle diffusion here + if (_diffusionFanout > 0) { + glm::vec3 thisReflection = end; + calculateDiffusions(earPosition, origin, end, totalDistance, + currentAttenuation, bounceCount, face, reflectionPoints); + } } } else { currentAttenuation = 0.0f; @@ -373,7 +473,11 @@ void AudioReflector::echoReflections(const glm::vec3& origin, const QVector calculateReflections(const glm::vec3& earPosition, const glm::vec3& origin, const glm::vec3& originalDirection); + void calculateDiffusions(const glm::vec3& earPosition, const glm::vec3& origin, + const glm::vec3& thisReflection, float thisDistance, float thisAttenuation, int thisBounceCount, + BoxFace thisReflectionFace, QVector reflectionPoints); + + void drawReflections(const glm::vec3& origin, const glm::vec3& originalColor, const QVector& reflections); void calculateAllReflections(); @@ -105,6 +112,8 @@ private: float _preDelay; float _soundMsPerMeter; float _distanceAttenuationScalingFactor; + + int _diffusionFanout; // number of points of diffusion from each reflection point }; From 4335ba7b5aa2d5b9b167b05fc9c2ad2b232585db Mon Sep 17 00:00:00 2001 From: Thijs Wenker Date: Mon, 7 Apr 2014 17:01:24 +0200 Subject: [PATCH 173/595] windows default device fix --- interface/src/Audio.cpp | 73 +++++++++++++++++++++++++++++++---------- 1 file changed, 55 insertions(+), 18 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 63c683dbb0..3f48c73867 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -15,6 +15,13 @@ #include #endif +#ifdef WIN32 +#include +#include +#include +#include +#endif + #include #include #include @@ -146,24 +153,54 @@ QAudioDeviceInfo defaultAudioDeviceForMode(QAudio::Mode mode) { } #endif #ifdef WIN32 - QString deviceName; - if (mode == QAudio::AudioInput) { - WAVEINCAPS wic; - // first use WAVE_MAPPER to get the default devices manufacturer ID - waveInGetDevCaps(WAVE_MAPPER, &wic, sizeof(wic)); - //Use the received manufacturer id to get the device's real name - waveInGetDevCaps(wic.wMid, &wic, sizeof(wic)); - qDebug() << "input device:" << wic.szPname; - deviceName = wic.szPname; - } else { - WAVEOUTCAPS woc; - // first use WAVE_MAPPER to get the default devices manufacturer ID - waveOutGetDevCaps(WAVE_MAPPER, &woc, sizeof(woc)); - //Use the received manufacturer id to get the device's real name - waveOutGetDevCaps(woc.wMid, &woc, sizeof(woc)); - qDebug() << "output device:" << woc.szPname; - deviceName = woc.szPname; - } + QString deviceName; + //Check for Windows Vista or higher, IMMDeviceEnumerator doesn't work below that. + OSVERSIONINFO osvi; + ZeroMemory(&osvi, sizeof(OSVERSIONINFO)); + osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + GetVersionEx(&osvi); + if (osvi.dwMajorVersion < 6) {// lower then vista + if (mode == QAudio::AudioInput) { + WAVEINCAPS wic; + // first use WAVE_MAPPER to get the default devices manufacturer ID + waveInGetDevCaps(WAVE_MAPPER, &wic, sizeof(wic)); + //Use the received manufacturer id to get the device's real name + waveInGetDevCaps(wic.wMid, &wic, sizeof(wic)); + qDebug() << "input device:" << wic.szPname; + deviceName = wic.szPname; + } else { + WAVEOUTCAPS woc; + // first use WAVE_MAPPER to get the default devices manufacturer ID + waveOutGetDevCaps(WAVE_MAPPER, &woc, sizeof(woc)); + //Use the received manufacturer id to get the device's real name + waveOutGetDevCaps(woc.wMid, &woc, sizeof(woc)); + qDebug() << "output device:" << woc.szPname; + deviceName = woc.szPname; + } + } else { + HRESULT hr = S_OK; + CoInitialize(NULL); + IMMDeviceEnumerator *pMMDeviceEnumerator = NULL; + CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&pMMDeviceEnumerator); + IMMDevice *pEndpoint; + pMMDeviceEnumerator->GetDefaultAudioEndpoint(mode == QAudio::AudioOutput ? eRender : eCapture, eMultimedia, &pEndpoint); + IPropertyStore *pPropertyStore; + pEndpoint->OpenPropertyStore(STGM_READ, &pPropertyStore); + pEndpoint->Release(); + pEndpoint = NULL; + PROPVARIANT pv; + PropVariantInit(&pv); + hr = pPropertyStore->GetValue(PKEY_Device_FriendlyName, &pv); + pPropertyStore->Release(); + pPropertyStore = NULL; + //QAudio devices seems to only take the 31 first characters of the Friendly Device Name. + deviceName = QString::fromWCharArray((wchar_t *)pv.pwszVal).left(31); + qDebug() << (mode == QAudio::AudioOutput ? "output" : "input") << " device:" << deviceName; + PropVariantClear(&pv); + pMMDeviceEnumerator->Release(); + pMMDeviceEnumerator = NULL; + CoUninitialize(); + } qDebug() << "DEBUG [" << deviceName << "] [" << getNamedAudioDeviceForMode(mode, deviceName).deviceName() << "]"; return getNamedAudioDeviceForMode(mode, deviceName); From 5adcf6875241fd7c58ec309f026e8b866fd87a8a Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 7 Apr 2014 09:08:51 -0700 Subject: [PATCH 174/595] sort nodes on DS page by their uptime --- domain-server/resources/web/index.shtml | 1 + domain-server/resources/web/js/tables.js | 16 ++++++++++++++-- domain-server/src/DomainServer.cpp | 4 ++++ libraries/shared/src/Node.cpp | 3 ++- libraries/shared/src/Node.h | 6 +++--- 5 files changed, 24 insertions(+), 6 deletions(-) diff --git a/domain-server/resources/web/index.shtml b/domain-server/resources/web/index.shtml index bba4dc4d22..afd0af1679 100644 --- a/domain-server/resources/web/index.shtml +++ b/domain-server/resources/web/index.shtml @@ -12,6 +12,7 @@ Pool Public Local + Uptime (s) Kill? diff --git a/domain-server/resources/web/js/tables.js b/domain-server/resources/web/js/tables.js index 3f7b2b7b28..a4884486c3 100644 --- a/domain-server/resources/web/js/tables.js +++ b/domain-server/resources/web/js/tables.js @@ -5,13 +5,21 @@ $(document).ready(function(){ json.nodes.sort(function(a, b){ if (a.type === b.type) { - return 0; + if (a.wake_timestamp < b.wake_timestamp) { + return 1; + } else if (a.wake_timestamp > b.wake_timestamp) { + return -1; + } else { + return 0; + } } if (a.type === "agent" && b.type !== "agent") { return 1; + } else if (b.type === "agent" && a.type !== "agent") { + return -1; } - + if (a.type > b.type) { return 1; } @@ -30,6 +38,10 @@ $(document).ready(function(){ nodesTableBody += "" + (data.pool ? data.pool : "") + ""; nodesTableBody += "" + data.public.ip + ":" + data.public.port + ""; nodesTableBody += "" + data.local.ip + ":" + data.local.port + ""; + + var uptimeSeconds = (Date.now() - data.wake_timestamp) / 1000; + nodesTableBody += "" + uptimeSeconds.toLocaleString() + ""; + nodesTableBody += ""; nodesTableBody += ""; }); diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index d18f12ec7f..8d1ee9d3dd 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -627,6 +627,7 @@ const char JSON_KEY_TYPE[] = "type"; const char JSON_KEY_PUBLIC_SOCKET[] = "public"; const char JSON_KEY_LOCAL_SOCKET[] = "local"; const char JSON_KEY_POOL[] = "pool"; +const char JSON_KEY_WAKE_TIMESTAMP[] = "wake_timestamp"; QJsonObject DomainServer::jsonObjectForNode(const SharedNodePointer& node) { QJsonObject nodeJson; @@ -646,6 +647,9 @@ QJsonObject DomainServer::jsonObjectForNode(const SharedNodePointer& node) { nodeJson[JSON_KEY_PUBLIC_SOCKET] = jsonForSocket(node->getPublicSocket()); nodeJson[JSON_KEY_LOCAL_SOCKET] = jsonForSocket(node->getLocalSocket()); + // add the node uptime in our list + nodeJson[JSON_KEY_WAKE_TIMESTAMP] = QString::number(node->getWakeTimestamp()); + // if the node has pool information, add it SharedAssignmentPointer matchingAssignment = _staticAssignmentHash.value(node->getUUID()); if (matchingAssignment) { diff --git a/libraries/shared/src/Node.cpp b/libraries/shared/src/Node.cpp index a4491fb707..1e78bc3feb 100644 --- a/libraries/shared/src/Node.cpp +++ b/libraries/shared/src/Node.cpp @@ -19,6 +19,7 @@ #include "SharedUtil.h" #include +#include #include const QString UNKNOWN_NodeType_t_NAME = "Unknown"; @@ -47,7 +48,7 @@ const QString& NodeType::getNodeTypeName(NodeType_t nodeType) { Node::Node(const QUuid& uuid, char type, const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket) : _type(type), _uuid(uuid), - _wakeMicrostamp(usecTimestampNow()), + _wakeTimestamp(QDateTime::currentMSecsSinceEpoch()), _lastHeardMicrostamp(usecTimestampNow()), _publicSocket(publicSocket), _localSocket(localSocket), diff --git a/libraries/shared/src/Node.h b/libraries/shared/src/Node.h index 79d75629a6..5d30d6f7b0 100644 --- a/libraries/shared/src/Node.h +++ b/libraries/shared/src/Node.h @@ -60,8 +60,8 @@ public: const QUuid& getUUID() const { return _uuid; } void setUUID(const QUuid& uuid) { _uuid = uuid; } - quint64 getWakeMicrostamp() const { return _wakeMicrostamp; } - void setWakeMicrostamp(quint64 wakeMicrostamp) { _wakeMicrostamp = wakeMicrostamp; } + quint64 getWakeTimestamp() const { return _wakeTimestamp; } + void setWakeTimestamp(quint64 wakeTimestamp) { _wakeTimestamp = wakeTimestamp; } quint64 getLastHeardMicrostamp() const { return _lastHeardMicrostamp; } void setLastHeardMicrostamp(quint64 lastHeardMicrostamp) { _lastHeardMicrostamp = lastHeardMicrostamp; } @@ -109,7 +109,7 @@ private: NodeType_t _type; QUuid _uuid; - quint64 _wakeMicrostamp; + quint64 _wakeTimestamp; quint64 _lastHeardMicrostamp; HifiSockAddr _publicSocket; HifiSockAddr _localSocket; From 69504b0a9df5ecef878db505ec84d25863cda46d Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 7 Apr 2014 09:47:51 -0700 Subject: [PATCH 175/595] proper cleanup of CA credentials on DTLSClientSession side --- assignment-client/src/AssignmentClient.cpp | 4 ++-- interface/src/Application.cpp | 4 ++-- libraries/shared/src/DTLSClientSession.cpp | 20 +++++++++++++------- libraries/shared/src/DTLSClientSession.h | 6 +++++- 4 files changed, 22 insertions(+), 12 deletions(-) diff --git a/assignment-client/src/AssignmentClient.cpp b/assignment-client/src/AssignmentClient.cpp index c370c78132..222cb0ce9a 100644 --- a/assignment-client/src/AssignmentClient.cpp +++ b/assignment-client/src/AssignmentClient.cpp @@ -33,7 +33,7 @@ AssignmentClient::AssignmentClient(int &argc, char **argv) : QCoreApplication(argc, argv), _currentAssignment() { - gnutls_global_init(); + DTLSClientSession::globalInit(); setOrganizationName("High Fidelity"); setOrganizationDomain("highfidelity.io"); @@ -110,7 +110,7 @@ AssignmentClient::AssignmentClient(int &argc, char **argv) : } AssignmentClient::~AssignmentClient() { - gnutls_global_deinit(); + DTLSClientSession::globalDeinit(); } void AssignmentClient::sendAssignmentRequest() { diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index b3bb085cdc..cfe920bf40 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -167,7 +167,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : _logger(new FileLogger(this)) { // init GnuTLS for DTLS with domain-servers - gnutls_global_init(); + DTLSClientSession::globalInit(); // read the ApplicationInfo.ini file for Name/Version/Domain information QSettings applicationInfo(Application::resourcesPath() + "info/ApplicationInfo.ini", QSettings::IniFormat); @@ -396,7 +396,7 @@ Application::~Application() { AccountManager::getInstance().destroy(); - gnutls_global_deinit(); + DTLSClientSession::globalDeinit(); } void Application::restoreSizeAndPosition() { diff --git a/libraries/shared/src/DTLSClientSession.cpp b/libraries/shared/src/DTLSClientSession.cpp index 73daa4e03a..5762038a20 100644 --- a/libraries/shared/src/DTLSClientSession.cpp +++ b/libraries/shared/src/DTLSClientSession.cpp @@ -8,20 +8,26 @@ #include "DTLSClientSession.h" -gnutls_certificate_credentials_t* DTLSClientSession::x509CACredentials() { - static gnutls_certificate_credentials_t x509Credentials; - static bool credentialsInitialized = false; +gnutls_certificate_credentials_t DTLSClientSession::_x509CACredentials; + +void DTLSClientSession::globalInit() { + static bool initialized = false; - if (!credentialsInitialized) { - gnutls_certificate_allocate_credentials(&x509Credentials); + if (!initialized) { + gnutls_global_init(); + gnutls_certificate_allocate_credentials(&_x509CACredentials); } +} + +void DTLSClientSession::globalDeinit() { + gnutls_certificate_free_credentials(_x509CACredentials); - return &x509Credentials; + gnutls_global_deinit(); } DTLSClientSession::DTLSClientSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket) : DTLSSession(GNUTLS_CLIENT, dtlsSocket, destinationSocket) { gnutls_priority_set_direct(_gnutlsSession, "PERFORMANCE", NULL); - gnutls_credentials_set(_gnutlsSession, GNUTLS_CRD_CERTIFICATE, *x509CACredentials()); + gnutls_credentials_set(_gnutlsSession, GNUTLS_CRD_CERTIFICATE, _x509CACredentials); } \ No newline at end of file diff --git a/libraries/shared/src/DTLSClientSession.h b/libraries/shared/src/DTLSClientSession.h index a81daf6d74..ad5b0cd55b 100644 --- a/libraries/shared/src/DTLSClientSession.h +++ b/libraries/shared/src/DTLSClientSession.h @@ -15,7 +15,11 @@ class DTLSClientSession : public DTLSSession { public: DTLSClientSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket); - static gnutls_certificate_credentials_t* x509CACredentials(); + static void globalInit(); + static void globalDeinit(); + + static gnutls_certificate_credentials_t _x509CACredentials; + static bool _wasGloballyInitialized; }; #endif /* defined(__hifi__DTLSClientSession__) */ From e9922b6db92337da655290ae9d9f0d98069fa7d7 Mon Sep 17 00:00:00 2001 From: Thijs Wenker Date: Mon, 7 Apr 2014 18:50:13 +0200 Subject: [PATCH 176/595] windows default device fix: - fixed tabs>spaces - doesn't require atlbase anymore, so works on visual studio express --- interface/src/Audio.cpp | 80 +++++++++++++++++++++-------------------- 1 file changed, 41 insertions(+), 39 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 3f48c73867..7e7dfd9df1 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -16,7 +16,9 @@ #endif #ifdef WIN32 -#include +#define WIN32_LEAN_AND_MEAN +#include +#include #include #include #include @@ -153,55 +155,55 @@ QAudioDeviceInfo defaultAudioDeviceForMode(QAudio::Mode mode) { } #endif #ifdef WIN32 - QString deviceName; - //Check for Windows Vista or higher, IMMDeviceEnumerator doesn't work below that. + QString deviceName; + //Check for Windows Vista or higher, IMMDeviceEnumerator doesn't work below that. OSVERSIONINFO osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFO)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&osvi); - if (osvi.dwMajorVersion < 6) {// lower then vista - if (mode == QAudio::AudioInput) { - WAVEINCAPS wic; - // first use WAVE_MAPPER to get the default devices manufacturer ID - waveInGetDevCaps(WAVE_MAPPER, &wic, sizeof(wic)); - //Use the received manufacturer id to get the device's real name - waveInGetDevCaps(wic.wMid, &wic, sizeof(wic)); - qDebug() << "input device:" << wic.szPname; - deviceName = wic.szPname; - } else { - WAVEOUTCAPS woc; - // first use WAVE_MAPPER to get the default devices manufacturer ID - waveOutGetDevCaps(WAVE_MAPPER, &woc, sizeof(woc)); - //Use the received manufacturer id to get the device's real name - waveOutGetDevCaps(woc.wMid, &woc, sizeof(woc)); - qDebug() << "output device:" << woc.szPname; - deviceName = woc.szPname; - } - } else { - HRESULT hr = S_OK; - CoInitialize(NULL); - IMMDeviceEnumerator *pMMDeviceEnumerator = NULL; - CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&pMMDeviceEnumerator); - IMMDevice *pEndpoint; - pMMDeviceEnumerator->GetDefaultAudioEndpoint(mode == QAudio::AudioOutput ? eRender : eCapture, eMultimedia, &pEndpoint); + if (osvi.dwMajorVersion < 6) {// lower then vista + if (mode == QAudio::AudioInput) { + WAVEINCAPS wic; + // first use WAVE_MAPPER to get the default devices manufacturer ID + waveInGetDevCaps(WAVE_MAPPER, &wic, sizeof(wic)); + //Use the received manufacturer id to get the device's real name + waveInGetDevCaps(wic.wMid, &wic, sizeof(wic)); + qDebug() << "input device:" << wic.szPname; + deviceName = wic.szPname; + } else { + WAVEOUTCAPS woc; + // first use WAVE_MAPPER to get the default devices manufacturer ID + waveOutGetDevCaps(WAVE_MAPPER, &woc, sizeof(woc)); + //Use the received manufacturer id to get the device's real name + waveOutGetDevCaps(woc.wMid, &woc, sizeof(woc)); + qDebug() << "output device:" << woc.szPname; + deviceName = woc.szPname; + } + } else { + HRESULT hr = S_OK; + CoInitialize(NULL); + IMMDeviceEnumerator *pMMDeviceEnumerator = NULL; + CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&pMMDeviceEnumerator); + IMMDevice *pEndpoint; + pMMDeviceEnumerator->GetDefaultAudioEndpoint(mode == QAudio::AudioOutput ? eRender : eCapture, eMultimedia, &pEndpoint); IPropertyStore *pPropertyStore; pEndpoint->OpenPropertyStore(STGM_READ, &pPropertyStore); pEndpoint->Release(); - pEndpoint = NULL; + pEndpoint = NULL; PROPVARIANT pv; - PropVariantInit(&pv); + PropVariantInit(&pv); hr = pPropertyStore->GetValue(PKEY_Device_FriendlyName, &pv); pPropertyStore->Release(); - pPropertyStore = NULL; - //QAudio devices seems to only take the 31 first characters of the Friendly Device Name. - deviceName = QString::fromWCharArray((wchar_t *)pv.pwszVal).left(31); + pPropertyStore = NULL; + //QAudio devices seems to only take the 31 first characters of the Friendly Device Name. + deviceName = QString::fromWCharArray((wchar_t *)pv.pwszVal).left(31); qDebug() << (mode == QAudio::AudioOutput ? "output" : "input") << " device:" << deviceName; - PropVariantClear(&pv); - pMMDeviceEnumerator->Release(); - pMMDeviceEnumerator = NULL; - CoUninitialize(); - } - qDebug() << "DEBUG [" << deviceName << "] [" << getNamedAudioDeviceForMode(mode, deviceName).deviceName() << "]"; + PropVariantClear(&pv); + pMMDeviceEnumerator->Release(); + pMMDeviceEnumerator = NULL; + CoUninitialize(); + } + qDebug() << "DEBUG [" << deviceName << "] [" << getNamedAudioDeviceForMode(mode, deviceName).deviceName() << "]"; return getNamedAudioDeviceForMode(mode, deviceName); #endif From d902580d6faff2d6ca460a93ff850df4e4f2e5d5 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Mon, 7 Apr 2014 10:03:10 -0700 Subject: [PATCH 177/595] Add Collision metatype to JS script system --- examples/collidingParticles.js | 10 +++-- examples/globalCollisionsExample.js | 10 +++-- examples/gun.js | 16 +++---- examples/paintGun.js | 5 ++- examples/spaceInvadersExample.js | 5 ++- interface/src/Application.cpp | 8 ++-- .../particles/src/ParticleCollisionSystem.cpp | 42 ++++++++++++------- .../particles/src/ParticleCollisionSystem.h | 8 ++-- .../src/ParticlesScriptingInterface.h | 6 ++- libraries/shared/src/RegisteredMetaTypes.cpp | 13 ++++++ libraries/shared/src/RegisteredMetaTypes.h | 5 +++ 11 files changed, 82 insertions(+), 46 deletions(-) diff --git a/examples/collidingParticles.js b/examples/collidingParticles.js index 2d2cf4fecc..95520df757 100644 --- a/examples/collidingParticles.js +++ b/examples/collidingParticles.js @@ -30,9 +30,10 @@ var gravity = { var damping = 0.1; var scriptA = " " + - " function collisionWithParticle(other, penetration) { " + + " function collisionWithParticle(other, collision) { " + " print('collisionWithParticle(other.getID()=' + other.getID() + ')...'); " + - " Vec3.print('penetration=', penetration); " + + " Vec3.print('penetration=', collision.penetration); " + + " Vec3.print('contactPoint=', collision.contactPoint); " + " print('myID=' + Particle.getID() + '\\n'); " + " var colorBlack = { red: 0, green: 0, blue: 0 };" + " var otherColor = other.getColor();" + @@ -46,9 +47,10 @@ var scriptA = " " + " "; var scriptB = " " + - " function collisionWithParticle(other, penetration) { " + + " function collisionWithParticle(other, collision) { " + " print('collisionWithParticle(other.getID()=' + other.getID() + ')...'); " + - " Vec3.print('penetration=', penetration); " + + " Vec3.print('penetration=', collision.penetration); " + + " Vec3.print('contactPoint=', collision.contactPoint); " + " print('myID=' + Particle.getID() + '\\n'); " + " Particle.setScript('Particle.setShouldDie(true);'); " + " } " + diff --git a/examples/globalCollisionsExample.js b/examples/globalCollisionsExample.js index 266823f564..7abf707cbf 100644 --- a/examples/globalCollisionsExample.js +++ b/examples/globalCollisionsExample.js @@ -12,18 +12,20 @@ print("hello..."); -function particleCollisionWithVoxel(particle, voxel, penetration) { +function particleCollisionWithVoxel(particle, voxel, collision) { print("particleCollisionWithVoxel().."); print(" particle.getID()=" + particle.id); print(" voxel color...=" + voxel.red + ", " + voxel.green + ", " + voxel.blue); - Vec3.print('penetration=', penetration); + Vec3.print('penetration=', collision.penetration); + Vec3.print('contactPoint=', collision.contactPoint); } -function particleCollisionWithParticle(particleA, particleB, penetration) { +function particleCollisionWithParticle(particleA, particleB, collision) { print("particleCollisionWithParticle().."); print(" particleA.getID()=" + particleA.id); print(" particleB.getID()=" + particleB.id); - Vec3.print('penetration=', penetration); + Vec3.print('penetration=', collision.penetration); + Vec3.print('contactPoint=', collision.contactPoint); } Particles.particleCollisionWithVoxel.connect(particleCollisionWithVoxel); diff --git a/examples/gun.js b/examples/gun.js index 3edb823bd1..7bdde19d94 100644 --- a/examples/gun.js +++ b/examples/gun.js @@ -145,24 +145,21 @@ function shootTarget() { -function particleCollisionWithVoxel(particle, voxel, penetration) { +function particleCollisionWithVoxel(particle, voxel, collision) { var HOLE_SIZE = 0.125; var particleProperties = Particles.getParticleProperties(particle); var position = particleProperties.position; Particles.deleteParticle(particle); // Make a hole in this voxel - Vec3.print("penetration", penetration); - Vec3.print("position", position); - var pointOfEntry = Vec3.subtract(position, penetration); - Vec3.print("pointOfEntry", pointOfEntry); - Voxels.eraseVoxel(pointOfEntry.x, pointOfEntry.y, pointOfEntry.z, HOLE_SIZE); + Vec3.print("penetration", collision.penetration); + Vec3.print("contactPoint", collision.contactPoint); + Voxels.eraseVoxel(contactPoint.x, contactPoint.y, contactPoint.z, HOLE_SIZE); Voxels.eraseVoxel(position.x, position.y, position.z, HOLE_SIZE); - //audioOptions.position = position; audioOptions.position = Vec3.sum(Camera.getPosition(), Quat.getFront(Camera.getOrientation())); Audio.playSound(impactSound, audioOptions); } -function particleCollisionWithParticle(particle1, particle2) { +function particleCollisionWithParticle(particle1, particle2, collision) { score++; if (showScore) { Overlays.editOverlay(text, { text: "Score: " + score } ); @@ -174,8 +171,11 @@ function particleCollisionWithParticle(particle1, particle2) { var endTime = new Date(); var msecs = endTime.valueOf() - shotTime.valueOf(); print("hit, msecs = " + msecs); + Vec3.print("penetration = ", collision.penetration); + Vec3.print("contactPoint = ", collision.contactPoint); Particles.deleteParticle(particle1); Particles.deleteParticle(particle2); + // play the sound near the camera so the shooter can hear it audioOptions.position = Vec3.sum(Camera.getPosition(), Quat.getFront(Camera.getOrientation())); Audio.playSound(targetHitSound, audioOptions); } diff --git a/examples/paintGun.js b/examples/paintGun.js index 6b6e78b43e..0b30d99fb5 100644 --- a/examples/paintGun.js +++ b/examples/paintGun.js @@ -62,9 +62,10 @@ function checkController(deltaTime) { // This is the script for the particles that this gun shoots. var script = - " function collisionWithVoxel(voxel, penetration) { " + + " function collisionWithVoxel(voxel, collision) { " + " print('collisionWithVoxel(voxel)... '); " + - " Vec3.print('penetration=', penetration); " + + " Vec3.print('penetration=', collision.penetration); " + + " Vec3.print('contactPoint=', collision.contactPoint); " + " print('myID=' + Particle.getID() + '\\n'); " + " var voxelColor = { red: voxel.red, green: voxel.green, blue: voxel.blue };" + " var voxelAt = { x: voxel.x, y: voxel.y, z: voxel.z };" + diff --git a/examples/spaceInvadersExample.js b/examples/spaceInvadersExample.js index 61ff93fc8f..df985e2e18 100644 --- a/examples/spaceInvadersExample.js +++ b/examples/spaceInvadersExample.js @@ -392,9 +392,10 @@ function deleteIfInvader(possibleInvaderParticle) { } } -function particleCollisionWithParticle(particleA, particleB, penetration) { +function particleCollisionWithParticle(particleA, particleB, collision) { print("particleCollisionWithParticle() a.id="+particleA.id + " b.id=" + particleB.id); - Vec3.print('particleCollisionWithParticle() penetration=', penetration); + Vec3.print('particleCollisionWithParticle() penetration=', collision.penetration); + Vec3.print('particleCollisionWithParticle() contactPoint=', collision.contactPoint); if (missileFired) { myMissile = Particles.identifyParticle(myMissile); if (myMissile.id == particleA.id) { diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 7ba3e5c631..48aab620a5 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1565,14 +1565,14 @@ void Application::init() { // connect the _particleCollisionSystem to our script engine's ParticleScriptingInterface connect(&_particleCollisionSystem, - SIGNAL(particleCollisionWithVoxel(const ParticleID&, const VoxelDetail&, const glm::vec3&)), + SIGNAL(particleCollisionWithVoxel(const ParticleID&, const VoxelDetail&, const CollisionInfo&)), ScriptEngine::getParticlesScriptingInterface(), - SIGNAL(particleCollisionWithVoxels(const ParticleID&, const VoxelDetail&, const glm::vec3&))); + SIGNAL(particleCollisionWithVoxels(const ParticleID&, const VoxelDetail&, const CollisionInfo&))); connect(&_particleCollisionSystem, - SIGNAL(particleCollisionWithParticle(const ParticleID&, const ParticleID&, const glm::vec3&)), + SIGNAL(particleCollisionWithParticle(const ParticleID&, const ParticleID&, const CollisionInfo&)), ScriptEngine::getParticlesScriptingInterface(), - SIGNAL(particleCollisionWithParticle(const ParticleID&, const ParticleID&, const glm::vec3&))); + SIGNAL(particleCollisionWithParticle(const ParticleID&, const ParticleID&, const CollisionInfo&))); _audio.init(_glWidget); diff --git a/libraries/particles/src/ParticleCollisionSystem.cpp b/libraries/particles/src/ParticleCollisionSystem.cpp index c827e28c78..028cf80df9 100644 --- a/libraries/particles/src/ParticleCollisionSystem.cpp +++ b/libraries/particles/src/ParticleCollisionSystem.cpp @@ -72,17 +72,17 @@ void ParticleCollisionSystem::checkParticle(Particle* particle) { } void ParticleCollisionSystem::emitGlobalParticleCollisionWithVoxel(Particle* particle, - VoxelDetail* voxelDetails, const glm::vec3& penetration) { + VoxelDetail* voxelDetails, const CollisionInfo& collision) { ParticleID particleID = particle->getParticleID(); - emit particleCollisionWithVoxel(particleID, *voxelDetails, penetration); + emit particleCollisionWithVoxel(particleID, *voxelDetails, collision); } void ParticleCollisionSystem::emitGlobalParticleCollisionWithParticle(Particle* particleA, - Particle* particleB, const glm::vec3& penetration) { + Particle* particleB, const CollisionInfo& collision) { ParticleID idA = particleA->getParticleID(); ParticleID idB = particleB->getParticleID(); - emit particleCollisionWithParticle(idA, idB, penetration); + emit particleCollisionWithParticle(idA, idB, collision); } void ParticleCollisionSystem::updateCollisionWithVoxels(Particle* particle) { @@ -100,11 +100,17 @@ void ParticleCollisionSystem::updateCollisionWithVoxels(Particle* particle) { // let the particles run their collision scripts if they have them particle->collisionWithVoxel(voxelDetails, collisionInfo._penetration); - // let the global script run their collision scripts for particles if they have them - emitGlobalParticleCollisionWithVoxel(particle, voxelDetails, collisionInfo._penetration); - + // findSpherePenetration() only computes the penetration but we also want some other collision info + // so we compute it ourselves here. Note that we must multiply scale by TREE_SCALE when feeding + // the results to systems outside of this octree reference frame. updateCollisionSound(particle, collisionInfo._penetration, COLLISION_FREQUENCY); + collisionInfo._contactPoint = (float)TREE_SCALE * (particle->getPosition() + particle->getRadius() * glm::normalize(collisionInfo._penetration)); + // let the global script run their collision scripts for particles if they have them + emitGlobalParticleCollisionWithVoxel(particle, voxelDetails, collisionInfo); + + // we must scale back down to the octree reference frame before updating the particle properties collisionInfo._penetration /= (float)(TREE_SCALE); + collisionInfo._contactPoint /= (float)(TREE_SCALE); particle->applyHardCollision(collisionInfo); queueParticlePropertiesUpdate(particle); @@ -121,8 +127,7 @@ void ParticleCollisionSystem::updateCollisionWithParticles(Particle* particleA) glm::vec3 penetration; Particle* particleB; if (_particles->findSpherePenetration(center, radius, penetration, (void**)&particleB, Octree::NoLock)) { - // NOTE: 'penetration' is the depth that 'particleA' overlaps 'particleB'. - // That is, it points from A into B. + // NOTE: 'penetration' is the depth that 'particleA' overlaps 'particleB'. It points from A into B. // Even if the particles overlap... when the particles are already moving appart // we don't want to count this as a collision. @@ -130,7 +135,12 @@ void ParticleCollisionSystem::updateCollisionWithParticles(Particle* particleA) if (glm::dot(relativeVelocity, penetration) > 0.0f) { particleA->collisionWithParticle(particleB, penetration); particleB->collisionWithParticle(particleA, penetration * -1.0f); // the penetration is reversed - emitGlobalParticleCollisionWithParticle(particleA, particleB, penetration); + + CollisionInfo collision; + collision._penetration = penetration; + // for now the contactPoint is the average between the the two paricle centers + collision._contactPoint = (0.5f * (float)TREE_SCALE) * (particleA->getPosition() + particleB->getPosition()); + emitGlobalParticleCollisionWithParticle(particleA, particleB, collision); glm::vec3 axis = glm::normalize(penetration); glm::vec3 axialVelocity = glm::dot(relativeVelocity, axis) * axis; @@ -142,25 +152,25 @@ void ParticleCollisionSystem::updateCollisionWithParticles(Particle* particleA) float massB = (particleB->getInHand()) ? MAX_MASS : particleB->getMass(); float totalMass = massA + massB; - // handle A particle + // handle particle A particleA->setVelocity(particleA->getVelocity() - axialVelocity * (2.0f * massB / totalMass)); particleA->setPosition(particleA->getPosition() - 0.5f * penetration); ParticleProperties propertiesA; - ParticleID particleAid(particleA->getID()); + ParticleID idA(particleA->getID()); propertiesA.copyFromParticle(*particleA); propertiesA.setVelocity(particleA->getVelocity() * (float)TREE_SCALE); propertiesA.setPosition(particleA->getPosition() * (float)TREE_SCALE); - _packetSender->queueParticleEditMessage(PacketTypeParticleAddOrEdit, particleAid, propertiesA); + _packetSender->queueParticleEditMessage(PacketTypeParticleAddOrEdit, idA, propertiesA); - // handle B particle + // handle particle B particleB->setVelocity(particleB->getVelocity() + axialVelocity * (2.0f * massA / totalMass)); particleA->setPosition(particleB->getPosition() + 0.5f * penetration); ParticleProperties propertiesB; - ParticleID particleBid(particleB->getID()); + ParticleID idB(particleB->getID()); propertiesB.copyFromParticle(*particleB); propertiesB.setVelocity(particleB->getVelocity() * (float)TREE_SCALE); propertiesB.setPosition(particleB->getPosition() * (float)TREE_SCALE); - _packetSender->queueParticleEditMessage(PacketTypeParticleAddOrEdit, particleBid, propertiesB); + _packetSender->queueParticleEditMessage(PacketTypeParticleAddOrEdit, idB, propertiesB); _packetSender->releaseQueuedMessages(); diff --git a/libraries/particles/src/ParticleCollisionSystem.h b/libraries/particles/src/ParticleCollisionSystem.h index 1b30fd31ac..c6ab97c02b 100644 --- a/libraries/particles/src/ParticleCollisionSystem.h +++ b/libraries/particles/src/ParticleCollisionSystem.h @@ -53,13 +53,13 @@ public: void updateCollisionSound(Particle* particle, const glm::vec3 &penetration, float frequency); signals: - void particleCollisionWithVoxel(const ParticleID& particleID, const VoxelDetail& voxel, const glm::vec3& penetration); - void particleCollisionWithParticle(const ParticleID& idA, const ParticleID& idB, const glm::vec3& penetration); + void particleCollisionWithVoxel(const ParticleID& particleID, const VoxelDetail& voxel, const CollisionInfo& penetration); + void particleCollisionWithParticle(const ParticleID& idA, const ParticleID& idB, const CollisionInfo& penetration); private: static bool updateOperation(OctreeElement* element, void* extraData); - void emitGlobalParticleCollisionWithVoxel(Particle* particle, VoxelDetail* voxelDetails, const glm::vec3& penetration); - void emitGlobalParticleCollisionWithParticle(Particle* particleA, Particle* particleB, const glm::vec3& penetration); + void emitGlobalParticleCollisionWithVoxel(Particle* particle, VoxelDetail* voxelDetails, const CollisionInfo& penetration); + void emitGlobalParticleCollisionWithParticle(Particle* particleA, Particle* particleB, const CollisionInfo& penetration); ParticleEditPacketSender* _packetSender; ParticleTree* _particles; diff --git a/libraries/particles/src/ParticlesScriptingInterface.h b/libraries/particles/src/ParticlesScriptingInterface.h index 24bbad9e3e..8de44e20bb 100644 --- a/libraries/particles/src/ParticlesScriptingInterface.h +++ b/libraries/particles/src/ParticlesScriptingInterface.h @@ -11,6 +11,8 @@ #include +#include + #include #include "ParticleEditPacketSender.h" @@ -55,8 +57,8 @@ public slots: QVector findParticles(const glm::vec3& center, float radius) const; signals: - void particleCollisionWithVoxel(const ParticleID& particleID, const VoxelDetail& voxel, const glm::vec3& penetration); - void particleCollisionWithParticle(const ParticleID& idA, const ParticleID& idB, const glm::vec3& penetration); + void particleCollisionWithVoxel(const ParticleID& particleID, const VoxelDetail& voxel, const CollisionInfo& collision); + void particleCollisionWithParticle(const ParticleID& idA, const ParticleID& idB, const CollisionInfo& collision); private: void queueParticleMessage(PacketType packetType, ParticleID particleID, const ParticleProperties& properties); diff --git a/libraries/shared/src/RegisteredMetaTypes.cpp b/libraries/shared/src/RegisteredMetaTypes.cpp index d106977ae0..af074c59bc 100644 --- a/libraries/shared/src/RegisteredMetaTypes.cpp +++ b/libraries/shared/src/RegisteredMetaTypes.cpp @@ -16,6 +16,7 @@ static int vec2MetaTypeId = qRegisterMetaType(); static int quatMetaTypeId = qRegisterMetaType(); static int xColorMetaTypeId = qRegisterMetaType(); static int pickRayMetaTypeId = qRegisterMetaType(); +static int collisionMetaTypeId = qRegisterMetaType(); void registerMetaTypes(QScriptEngine* engine) { qScriptRegisterMetaType(engine, vec4toScriptValue, vec4FromScriptValue); @@ -24,6 +25,7 @@ void registerMetaTypes(QScriptEngine* engine) { qScriptRegisterMetaType(engine, quatToScriptValue, quatFromScriptValue); qScriptRegisterMetaType(engine, xColorToScriptValue, xColorFromScriptValue); qScriptRegisterMetaType(engine, pickRayToScriptValue, pickRayFromScriptValue); + qScriptRegisterMetaType(engine, collisionToScriptValue, collisionFromScriptValue); } QScriptValue vec4toScriptValue(QScriptEngine* engine, const glm::vec4& vec4) { @@ -122,3 +124,14 @@ void pickRayFromScriptValue(const QScriptValue& object, PickRay& pickRay) { } } +QScriptValue collisionToScriptValue(QScriptEngine* engine, const CollisionInfo& collision) { + QScriptValue obj = engine->newObject(); + obj.setProperty("penetration", vec3toScriptValue(engine, collision._penetration)); + obj.setProperty("contactPoint", vec3toScriptValue(engine, collision._contactPoint)); + return obj; +} + +void collisionFromScriptValue(const QScriptValue &object, CollisionInfo& collision) { + // TODO: implement this when we know what it means to accept collision events from JS +} + diff --git a/libraries/shared/src/RegisteredMetaTypes.h b/libraries/shared/src/RegisteredMetaTypes.h index ea65e45c95..0e7732c057 100644 --- a/libraries/shared/src/RegisteredMetaTypes.h +++ b/libraries/shared/src/RegisteredMetaTypes.h @@ -15,6 +15,7 @@ #include +#include "CollisionInfo.h" #include "SharedUtil.h" Q_DECLARE_METATYPE(glm::vec4) @@ -50,4 +51,8 @@ Q_DECLARE_METATYPE(PickRay) QScriptValue pickRayToScriptValue(QScriptEngine* engine, const PickRay& pickRay); void pickRayFromScriptValue(const QScriptValue& object, PickRay& pickRay); +Q_DECLARE_METATYPE(CollisionInfo) +QScriptValue collisionToScriptValue(QScriptEngine* engine, const CollisionInfo& collision); +void collisionFromScriptValue(const QScriptValue &object, CollisionInfo& collision); + #endif From a6641aa95b5d1edfc2b5c862730e8d6cb347fb37 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 7 Apr 2014 10:48:58 -0700 Subject: [PATCH 178/595] respect the DTLS MTU for domain server list sending --- domain-server/src/DomainServer.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 60c5cf1d0e..2f4179e56b 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -37,7 +37,8 @@ DomainServer::DomainServer(int argc, char* argv[]) : _isUsingDTLS(false), _x509Credentials(NULL), _dhParams(NULL), - _priorityCache(NULL) + _priorityCache(NULL), + _dtlsSessions() { gnutls_global_init(); @@ -500,6 +501,7 @@ void DomainServer::sendDomainListToNode(const SharedNodePointer& node, const Hif if (nodeInterestList.size() > 0) { DTLSServerSession* dtlsSession = _isUsingDTLS ? _dtlsSessions[senderSockAddr] : NULL; + unsigned int dataMTU = dtlsSession ? gnutls_dtls_get_data_mtu(*dtlsSession->getGnuTLSSession()) : MAX_PACKET_SIZE; // if the node has any interest types, send back those nodes as well foreach (const SharedNodePointer& otherNode, nodeList->getNodeHash()) { @@ -530,7 +532,7 @@ void DomainServer::sendDomainListToNode(const SharedNodePointer& node, const Hif nodeDataStream << secretUUID; - if (broadcastPacket.size() + nodeByteArray.size() > MAX_PACKET_SIZE) { + if (broadcastPacket.size() + nodeByteArray.size() > dataMTU) { // we need to break here and start a new packet // so send the current one From 0f92e02da798f0ba482b6ebee839d4c73f7c3143 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 7 Apr 2014 11:19:06 -0700 Subject: [PATCH 179/595] add the hifi root CA trusted cert to source --- libraries/shared/src/DTLSClientSession.cpp | 2 ++ libraries/shared/src/DTLSSession.cpp | 37 ++++++++++++++++++++++ libraries/shared/src/DTLSSession.h | 2 ++ 3 files changed, 41 insertions(+) diff --git a/libraries/shared/src/DTLSClientSession.cpp b/libraries/shared/src/DTLSClientSession.cpp index 5762038a20..40b2b87b66 100644 --- a/libraries/shared/src/DTLSClientSession.cpp +++ b/libraries/shared/src/DTLSClientSession.cpp @@ -16,6 +16,8 @@ void DTLSClientSession::globalInit() { if (!initialized) { gnutls_global_init(); gnutls_certificate_allocate_credentials(&_x509CACredentials); + int certsProcessed = gnutls_certificate_set_x509_trust_mem(_x509CACredentials, DTLSSession::highFidelityCADatum(), GNUTLS_X509_FMT_PEM); + qDebug() << "There were" << certsProcessed; } } diff --git a/libraries/shared/src/DTLSSession.cpp b/libraries/shared/src/DTLSSession.cpp index c5f4ade182..f76119fd1f 100644 --- a/libraries/shared/src/DTLSSession.cpp +++ b/libraries/shared/src/DTLSSession.cpp @@ -70,6 +70,43 @@ ssize_t DTLSSession::socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t return -1; } +gnutls_datum_t* DTLSSession::highFidelityCADatum() { + static gnutls_datum_t hifiCADatum; + static bool datumInitialized = false; + + static unsigned char HIGHFIDELITY_ROOT_CA_CERT[] = + "-----BEGIN CERTIFICATE-----" + "MIID6TCCA1KgAwIBAgIJANlfRkRD9A8bMA0GCSqGSIb3DQEBBQUAMIGqMQswCQYD\n" + "VQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZyYW5j\n" + "aXNjbzEbMBkGA1UEChMSSGlnaCBGaWRlbGl0eSwgSW5jMRMwEQYDVQQLEwpPcGVy\n" + "YXRpb25zMRgwFgYDVQQDEw9oaWdoZmlkZWxpdHkuaW8xIjAgBgkqhkiG9w0BCQEW\n" + "E29wc0BoaWdoZmlkZWxpdHkuaW8wHhcNMTQwMzI4MjIzMzM1WhcNMjQwMzI1MjIz\n" + "MzM1WjCBqjELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNV\n" + "BAcTDVNhbiBGcmFuY2lzY28xGzAZBgNVBAoTEkhpZ2ggRmlkZWxpdHksIEluYzET\n" + "MBEGA1UECxMKT3BlcmF0aW9uczEYMBYGA1UEAxMPaGlnaGZpZGVsaXR5LmlvMSIw\n" + "IAYJKoZIhvcNAQkBFhNvcHNAaGlnaGZpZGVsaXR5LmlvMIGfMA0GCSqGSIb3DQEB\n" + "AQUAA4GNADCBiQKBgQDyo1euYiPPEdnvDZnIjWrrP230qUKMSj8SWoIkbTJF2hE8\n" + "2eP3YOgbgSGBzZ8EJBxIOuNmj9g9Eg6691hIKFqy5W0BXO38P04Gg+pVBvpHFGBi\n" + "wpqGbfsjaUDuYmBeJRcMO0XYkLCRQG+lAQNHoFDdItWAJfC3FwtP3OCDnz8cNwID\n" + "AQABo4IBEzCCAQ8wHQYDVR0OBBYEFCSv2kmiGg6VFMnxXzLDNP304cPAMIHfBgNV\n" + "HSMEgdcwgdSAFCSv2kmiGg6VFMnxXzLDNP304cPAoYGwpIGtMIGqMQswCQYDVQQG\n" + "EwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNj\n" + "bzEbMBkGA1UEChMSSGlnaCBGaWRlbGl0eSwgSW5jMRMwEQYDVQQLEwpPcGVyYXRp\n" + "b25zMRgwFgYDVQQDEw9oaWdoZmlkZWxpdHkuaW8xIjAgBgkqhkiG9w0BCQEWE29w\n" + "c0BoaWdoZmlkZWxpdHkuaW+CCQDZX0ZEQ/QPGzAMBgNVHRMEBTADAQH/MA0GCSqG\n" + "SIb3DQEBBQUAA4GBAEkQl3p+lH5vuoCNgyfa67nL0MsBEt+5RSBOgjwCjjASjzou\n" + "FTv5w0he2OypgMQb8i/BYtS1lJSFqjPJcSM1Salzrm3xDOK5pOXJ7h6SQLPDVEyf\n" + "Hy2/9d/to+99+SOUlvfzfgycgjOc+s/AV7Y+GBd7uzGxUdrN4egCZW1F6/mH\n" + "-----END CERTIFICATE-----"; + + if (!datumInitialized) { + hifiCADatum.data = HIGHFIDELITY_ROOT_CA_CERT; + hifiCADatum.size = sizeof(HIGHFIDELITY_ROOT_CA_CERT); + } + + return &hifiCADatum; +} + DTLSSession::DTLSSession(int end, QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket) : DummyDTLSSession(dtlsSocket, destinationSocket), _completedHandshake(false) diff --git a/libraries/shared/src/DTLSSession.h b/libraries/shared/src/DTLSSession.h index 6b5f5df5e3..2d5a7098f1 100644 --- a/libraries/shared/src/DTLSSession.h +++ b/libraries/shared/src/DTLSSession.h @@ -25,6 +25,8 @@ public: static int socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms); static ssize_t socketPull(gnutls_transport_ptr_t ptr, void* buffer, size_t size); + static gnutls_datum_t* highFidelityCADatum(); + qint64 writeDatagram(const QByteArray& datagram); gnutls_session_t* getGnuTLSSession() { return &_gnutlsSession; } From 86a0b715f3185eefba0163190037af041256b0ce Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 7 Apr 2014 11:36:32 -0700 Subject: [PATCH 180/595] verify DTLS certificate to ensure trust before handshaking --- domain-server/src/DomainServer.cpp | 2 +- libraries/shared/src/DTLSClientSession.cpp | 36 ++++++++++++++++++++-- libraries/shared/src/DTLSClientSession.h | 2 ++ libraries/shared/src/DTLSSession.cpp | 1 - libraries/shared/src/DomainHandler.cpp | 3 +- 5 files changed, 39 insertions(+), 5 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 2f4179e56b..d0ac369700 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -689,7 +689,7 @@ void DomainServer::readAvailableDTLSDatagrams() { // the cookie sent by the client was not valid // send a valid one DummyDTLSSession tempServerSession(LimitedNodeList::getInstance()->getDTLSSocket(), senderHifiSockAddr); - qDebug() << "sending back a fresh cookie!"; + gnutls_dtls_cookie_send(_cookieKey, &senderSockAddr, sizeof(senderSockAddr), &prestate, &tempServerSession, DTLSSession::socketPush); diff --git a/libraries/shared/src/DTLSClientSession.cpp b/libraries/shared/src/DTLSClientSession.cpp index 40b2b87b66..0ebb282f29 100644 --- a/libraries/shared/src/DTLSClientSession.cpp +++ b/libraries/shared/src/DTLSClientSession.cpp @@ -16,8 +16,9 @@ void DTLSClientSession::globalInit() { if (!initialized) { gnutls_global_init(); gnutls_certificate_allocate_credentials(&_x509CACredentials); - int certsProcessed = gnutls_certificate_set_x509_trust_mem(_x509CACredentials, DTLSSession::highFidelityCADatum(), GNUTLS_X509_FMT_PEM); - qDebug() << "There were" << certsProcessed; + + gnutls_certificate_set_x509_trust_mem(_x509CACredentials, DTLSSession::highFidelityCADatum(), GNUTLS_X509_FMT_PEM); + gnutls_certificate_set_verify_function(_x509CACredentials, DTLSClientSession::verifyServerCertificate); } } @@ -27,6 +28,37 @@ void DTLSClientSession::globalDeinit() { gnutls_global_deinit(); } +int DTLSClientSession::verifyServerCertificate(gnutls_session_t session) { + unsigned int verifyStatus = 0; + int certReturn = gnutls_certificate_verify_peers3(session, NULL, &verifyStatus); + + if (certReturn < 0) { + return GNUTLS_E_CERTIFICATE_ERROR; + } + + gnutls_certificate_type_t typeReturn = gnutls_certificate_type_get(session); + + gnutls_datum_t printOut; + + + certReturn = gnutls_certificate_verification_status_print(verifyStatus, typeReturn, &printOut, 0); + + if (certReturn < 0) { + return GNUTLS_E_CERTIFICATE_ERROR; + } + + qDebug() << "Gnutls certificate verification status:" << reinterpret_cast(printOut.data); + gnutls_free(printOut.data); + + if (verifyStatus != 0) { + qDebug() << "Server provided certificate for DTLS is not trusted. Can not complete handshake."; + return GNUTLS_E_CERTIFICATE_ERROR; + } else { + // certificate is valid, continue handshaking as normal + return 0; + } +} + DTLSClientSession::DTLSClientSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket) : DTLSSession(GNUTLS_CLIENT, dtlsSocket, destinationSocket) { diff --git a/libraries/shared/src/DTLSClientSession.h b/libraries/shared/src/DTLSClientSession.h index ad5b0cd55b..fe8dec49b9 100644 --- a/libraries/shared/src/DTLSClientSession.h +++ b/libraries/shared/src/DTLSClientSession.h @@ -18,6 +18,8 @@ public: static void globalInit(); static void globalDeinit(); + static int verifyServerCertificate(gnutls_session_t session); + static gnutls_certificate_credentials_t _x509CACredentials; static bool _wasGloballyInitialized; }; diff --git a/libraries/shared/src/DTLSSession.cpp b/libraries/shared/src/DTLSSession.cpp index f76119fd1f..4685a05970 100644 --- a/libraries/shared/src/DTLSSession.cpp +++ b/libraries/shared/src/DTLSSession.cpp @@ -128,7 +128,6 @@ DTLSSession::DTLSSession(int end, QUdpSocket& dtlsSocket, HifiSockAddr& destinat } DTLSSession::~DTLSSession() { - qDebug() << "cleaning up current session"; gnutls_deinit(_gnutlsSession); } diff --git a/libraries/shared/src/DomainHandler.cpp b/libraries/shared/src/DomainHandler.cpp index e1aedc4d11..380a9a4b7b 100644 --- a/libraries/shared/src/DomainHandler.cpp +++ b/libraries/shared/src/DomainHandler.cpp @@ -129,7 +129,8 @@ void DomainHandler::completeDTLSHandshake() { } else if (gnutls_error_is_fatal(handshakeReturn)) { // this was a fatal error handshaking, so remove this session qDebug() << "Fatal error -" << gnutls_strerror(handshakeReturn) - << "- during DTLS handshake with DS at" << getHostname(); + << "- during DTLS handshake with DS at" + << qPrintable((_hostname.isEmpty() ? _sockAddr.getAddress().toString() : _hostname)); clearConnectionInfo(); } From 02e2135a2ecda70ee2855c4210fc4405634de177 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 7 Apr 2014 12:52:26 -0700 Subject: [PATCH 181/595] allow setting of expected DTLS cert hostname from AC --- assignment-client/src/AssignmentClient.cpp | 58 ++++++++++------------ assignment-client/src/AssignmentClient.h | 1 + libraries/shared/src/DTLSClientSession.cpp | 11 +++- libraries/shared/src/DomainHandler.cpp | 7 ++- libraries/shared/src/DomainHandler.h | 2 +- 5 files changed, 43 insertions(+), 36 deletions(-) diff --git a/assignment-client/src/AssignmentClient.cpp b/assignment-client/src/AssignmentClient.cpp index 222cb0ce9a..d5d6beaead 100644 --- a/assignment-client/src/AssignmentClient.cpp +++ b/assignment-client/src/AssignmentClient.cpp @@ -31,7 +31,8 @@ int hifiSockAddrMeta = qRegisterMetaType("HifiSockAddr"); AssignmentClient::AssignmentClient(int &argc, char **argv) : QCoreApplication(argc, argv), - _currentAssignment() + _currentAssignment(), + _assignmentServerHostname(DEFAULT_ASSIGNMENT_SERVER_HOSTNAME) { DTLSClientSession::globalInit(); @@ -40,57 +41,48 @@ AssignmentClient::AssignmentClient(int &argc, char **argv) : setApplicationName("assignment-client"); QSettings::setDefaultFormat(QSettings::IniFormat); + QStringList argumentList = arguments(); + // register meta type is required for queued invoke method on Assignment subclasses // set the logging target to the the CHILD_TARGET_NAME Logging::setTargetName(ASSIGNMENT_CLIENT_TARGET_NAME); - const char ASSIGNMENT_TYPE_OVVERIDE_OPTION[] = "-t"; - const char* assignmentTypeString = getCmdOption(argc, (const char**)argv, ASSIGNMENT_TYPE_OVVERIDE_OPTION); + const QString ASSIGNMENT_TYPE_OVVERIDE_OPTION = "-t"; + int argumentIndex = argumentList.indexOf(ASSIGNMENT_TYPE_OVVERIDE_OPTION); Assignment::Type requestAssignmentType = Assignment::AllTypes; - if (assignmentTypeString) { - // the user is asking to only be assigned to a particular type of assignment - // so set that as the ::overridenAssignmentType to be used in requests - requestAssignmentType = (Assignment::Type) atoi(assignmentTypeString); + if (argumentIndex != -1) { + requestAssignmentType = (Assignment::Type) argumentList[argumentIndex + 1].toInt(); } - const char ASSIGNMENT_POOL_OPTION[] = "--pool"; - const char* requestAssignmentPool = getCmdOption(argc, (const char**) argv, ASSIGNMENT_POOL_OPTION); + const QString ASSIGNMENT_POOL_OPTION = "--pool"; + argumentIndex = argumentList.indexOf(ASSIGNMENT_POOL_OPTION); + QString assignmentPool; + + if (argumentIndex != -1) { + assignmentPool = argumentList[argumentIndex + 1]; + } // setup our _requestAssignment member variable from the passed arguments - _requestAssignment = Assignment(Assignment::RequestCommand, requestAssignmentType, requestAssignmentPool); + _requestAssignment = Assignment(Assignment::RequestCommand, requestAssignmentType, assignmentPool); // create a NodeList as an unassigned client NodeList* nodeList = NodeList::createInstance(NodeType::Unassigned); - const char CUSTOM_ASSIGNMENT_SERVER_HOSTNAME_OPTION[] = "-a"; - const char CUSTOM_ASSIGNMENT_SERVER_PORT_OPTION[] = "-p"; + // check for an overriden assignment server hostname + const QString CUSTOM_ASSIGNMENT_SERVER_HOSTNAME_OPTION = "-a"; - // grab the overriden assignment-server hostname from argv, if it exists - const char* customAssignmentServerHostname = getCmdOption(argc, (const char**)argv, CUSTOM_ASSIGNMENT_SERVER_HOSTNAME_OPTION); - const char* customAssignmentServerPortString = getCmdOption(argc,(const char**)argv, CUSTOM_ASSIGNMENT_SERVER_PORT_OPTION); + argumentIndex = argumentList.indexOf(CUSTOM_ASSIGNMENT_SERVER_HOSTNAME_OPTION); - HifiSockAddr customAssignmentSocket; - - if (customAssignmentServerHostname || customAssignmentServerPortString) { + if (argumentIndex != -1) { + _assignmentServerHostname = argumentList[argumentIndex + 1]; - // set the custom port or default if it wasn't passed - unsigned short assignmentServerPort = customAssignmentServerPortString - ? atoi(customAssignmentServerPortString) : DEFAULT_DOMAIN_SERVER_PORT; + // set the custom assignment socket on our NodeList + HifiSockAddr customAssignmentSocket = HifiSockAddr(_assignmentServerHostname, DEFAULT_DOMAIN_SERVER_PORT); - // set the custom hostname or default if it wasn't passed - if (!customAssignmentServerHostname) { - customAssignmentServerHostname = DEFAULT_ASSIGNMENT_SERVER_HOSTNAME; - } - - customAssignmentSocket = HifiSockAddr(customAssignmentServerHostname, assignmentServerPort); - } - - // set the custom assignment socket if we have it - if (!customAssignmentSocket.isNull()) { nodeList->setAssignmentServerSocket(customAssignmentSocket); } @@ -138,9 +130,9 @@ void AssignmentClient::readPendingDatagrams() { if (_currentAssignment) { qDebug() << "Received an assignment -" << *_currentAssignment; - // switch our nodelist domain IP and port to whoever sent us the assignment + // switch our DomainHandler hostname and port to whoever sent us the assignment - nodeList->getDomainHandler().setSockAddr(senderSockAddr); + nodeList->getDomainHandler().setSockAddr(senderSockAddr, _assignmentServerHostname); nodeList->getDomainHandler().setAssignmentUUID(_currentAssignment->getUUID()); qDebug() << "Destination IP for assignment is" << nodeList->getDomainHandler().getIP().toString(); diff --git a/assignment-client/src/AssignmentClient.h b/assignment-client/src/AssignmentClient.h index 939d06b14f..33b1dd70e9 100644 --- a/assignment-client/src/AssignmentClient.h +++ b/assignment-client/src/AssignmentClient.h @@ -26,6 +26,7 @@ private slots: private: Assignment _requestAssignment; SharedAssignmentPointer _currentAssignment; + QString _assignmentServerHostname; }; #endif /* defined(__hifi__AssignmentClient__) */ diff --git a/libraries/shared/src/DTLSClientSession.cpp b/libraries/shared/src/DTLSClientSession.cpp index 0ebb282f29..ec8e121013 100644 --- a/libraries/shared/src/DTLSClientSession.cpp +++ b/libraries/shared/src/DTLSClientSession.cpp @@ -6,6 +6,8 @@ // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. // +#include "DomainHandler.h" + #include "DTLSClientSession.h" gnutls_certificate_credentials_t DTLSClientSession::_x509CACredentials; @@ -30,7 +32,14 @@ void DTLSClientSession::globalDeinit() { int DTLSClientSession::verifyServerCertificate(gnutls_session_t session) { unsigned int verifyStatus = 0; - int certReturn = gnutls_certificate_verify_peers3(session, NULL, &verifyStatus); + + // grab the hostname from the domain handler that this session is associated with + DomainHandler* domainHandler = reinterpret_cast(gnutls_session_get_ptr(session)); + qDebug() << "Checking for" << domainHandler->getHostname() << "from cert."; + + int certReturn = gnutls_certificate_verify_peers3(session, + domainHandler->getHostname().toLocal8Bit().constData(), + &verifyStatus); if (certReturn < 0) { return GNUTLS_E_CERTIFICATE_ERROR; diff --git a/libraries/shared/src/DomainHandler.cpp b/libraries/shared/src/DomainHandler.cpp index 380a9a4b7b..4773a368a4 100644 --- a/libraries/shared/src/DomainHandler.cpp +++ b/libraries/shared/src/DomainHandler.cpp @@ -58,6 +58,8 @@ void DomainHandler::initializeDTLSSession() { if (!_dtlsSession) { _dtlsSession = new DTLSClientSession(NodeList::getInstance()->getDTLSSocket(), _sockAddr); + gnutls_session_set_ptr(*_dtlsSession->getGnuTLSSession(), this); + // start a timer to complete the handshake process _handshakeTimer = new QTimer(this); connect(_handshakeTimer, &QTimer::timeout, this, &DomainHandler::completeDTLSHandshake); @@ -70,13 +72,16 @@ void DomainHandler::initializeDTLSSession() { } } -void DomainHandler::setSockAddr(const HifiSockAddr& sockAddr) { +void DomainHandler::setSockAddr(const HifiSockAddr& sockAddr, const QString& hostname) { if (_sockAddr != sockAddr) { // we should reset on a sockAddr change reset(); // change the sockAddr _sockAddr = sockAddr; } + + // some callers may pass a hostname, this is not to be used for lookup but for DTLS certificate verification + _hostname = hostname; } void DomainHandler::setHostname(const QString& hostname) { diff --git a/libraries/shared/src/DomainHandler.h b/libraries/shared/src/DomainHandler.h index c34321cf87..106eff67f1 100644 --- a/libraries/shared/src/DomainHandler.h +++ b/libraries/shared/src/DomainHandler.h @@ -40,7 +40,7 @@ public: void setIPToLocalhost() { _sockAddr.setAddress(QHostAddress(QHostAddress::LocalHost)); } const HifiSockAddr& getSockAddr() { return _sockAddr; } - void setSockAddr(const HifiSockAddr& sockAddr); + void setSockAddr(const HifiSockAddr& sockAddr, const QString& hostname); unsigned short getPort() const { return _sockAddr.getPort(); } From cec99caa47ff1692dd95a85e716f751620f7bef8 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 7 Apr 2014 13:45:30 -0700 Subject: [PATCH 182/595] Added upload progress tracking to AccountManager via JSON --- libraries/shared/src/AccountManager.cpp | 12 +++++++++--- libraries/shared/src/AccountManager.h | 5 ++++- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/libraries/shared/src/AccountManager.cpp b/libraries/shared/src/AccountManager.cpp index 955ba779d1..841fd9dde0 100644 --- a/libraries/shared/src/AccountManager.cpp +++ b/libraries/shared/src/AccountManager.cpp @@ -170,12 +170,18 @@ void AccountManager::invokedRequest(const QString& path, QNetworkAccessManager:: if (!callbackParams.isEmpty()) { // if we have information for a callback, insert the callbackParams into our local map _pendingCallbackMap.insert(networkReply, callbackParams); + + if (callbackParams.updateReciever && !callbackParams.updateSlot.isEmpty()) { + callbackParams.updateReciever->connect(networkReply, SIGNAL(uploadProgress(qint64, qint64)), + callbackParams.updateSlot.toStdString().c_str()); + } } // if we ended up firing of a request, hook up to it now - connect(networkReply, SIGNAL(finished()), this, SLOT(passSuccessToCallback())); + connect(networkReply, SIGNAL(finished()), + SLOT(passSuccessToCallback())); connect(networkReply, SIGNAL(error(QNetworkReply::NetworkError)), - this, SLOT(passErrorToCallback(QNetworkReply::NetworkError))); + SLOT(passErrorToCallback(QNetworkReply::NetworkError))); } } } @@ -194,7 +200,7 @@ void AccountManager::passSuccessToCallback() { // remove the related reply-callback group from the map _pendingCallbackMap.remove(requestReply); - } else { + } else { if (VERBOSE_HTTP_REQUEST_DEBUGGING) { qDebug() << "Received JSON response from data-server that has no matching callback."; qDebug() << jsonResponse; diff --git a/libraries/shared/src/AccountManager.h b/libraries/shared/src/AccountManager.h index bfe84f392e..b410885705 100644 --- a/libraries/shared/src/AccountManager.h +++ b/libraries/shared/src/AccountManager.h @@ -21,7 +21,8 @@ class JSONCallbackParameters { public: JSONCallbackParameters() : jsonCallbackReceiver(NULL), jsonCallbackMethod(), - errorCallbackReceiver(NULL), errorCallbackMethod() {}; + errorCallbackReceiver(NULL), errorCallbackMethod(), + updateReciever(NULL), updateSlot() {}; bool isEmpty() const { return !jsonCallbackReceiver && !errorCallbackReceiver; } @@ -29,6 +30,8 @@ public: QString jsonCallbackMethod; QObject* errorCallbackReceiver; QString errorCallbackMethod; + QObject* updateReciever; + QString updateSlot; }; class AccountManager : public QObject { From b21fe02fa2ae017520d6e4a6e05a5e371286bcaf Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 7 Apr 2014 13:46:38 -0700 Subject: [PATCH 183/595] Put ModelUploder on a different thread, not to block the rendering of the main window --- interface/src/Application.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index d54cceb245..fb50f647e8 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3245,9 +3245,12 @@ void Application::toggleRunningScriptsWidget() void Application::uploadFST(bool isHead) { ModelUploader* uploader = new ModelUploader(isHead); - if (uploader->zip()) { - uploader->send(); - } + QThread* thread = new QThread(); + thread->connect(uploader, SIGNAL(destroyed()), SLOT(quit())); + thread->connect(thread, SIGNAL(finished()), SLOT(deleteLater())); + uploader->connect(thread, SIGNAL(started()), SLOT(send())); + + thread->start(); } void Application::uploadHead() { From e85703d25bf657f3a5d7297a38dfe73a5827be04 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 7 Apr 2014 13:48:28 -0700 Subject: [PATCH 184/595] Added feedback and a better success check --- libraries/shared/src/ModelUploader.cpp | 102 +++++++++++++++++++++---- libraries/shared/src/ModelUploader.h | 25 +++++- 2 files changed, 109 insertions(+), 18 deletions(-) diff --git a/libraries/shared/src/ModelUploader.cpp b/libraries/shared/src/ModelUploader.cpp index 71514c8b0f..2ec199750f 100644 --- a/libraries/shared/src/ModelUploader.cpp +++ b/libraries/shared/src/ModelUploader.cpp @@ -9,13 +9,15 @@ #include #include -#include #include -#include +#include #include -#include -#include #include +#include +#include +#include +#include +#include #include "AccountManager.h" #include "ModelUploader.h" @@ -26,9 +28,12 @@ static const QString FILENAME_FIELD = "filename"; static const QString TEXDIR_FIELD = "texdir"; static const QString LOD_FIELD = "lod"; +static const QString S3_URL = "http://highfidelity-public.s3-us-west-1.amazonaws.com"; static const QString MODEL_URL = "/api/v1/models"; static const int MAX_SIZE = 10 * 1024 * 1024; // 10 MB +static const int TIMEOUT = 1000; +static const int MAX_CHECK = 30; // Class providing the QObject parent system to QTemporaryDir class TemporaryDir : public QTemporaryDir, public QObject { @@ -45,10 +50,11 @@ ModelUploader::ModelUploader(bool isHead) : _totalSize(0), _isHead(isHead), _readyToSend(false), - _dataMultiPart(new QHttpMultiPart(QHttpMultiPart::FormDataType)) + _dataMultiPart(new QHttpMultiPart(QHttpMultiPart::FormDataType)), + _numberOfChecks(MAX_CHECK) { _zipDir->setParent(_dataMultiPart); - + connect(&_timer, SIGNAL(timeout()), SLOT(checkS3())); } ModelUploader::~ModelUploader() { @@ -59,8 +65,9 @@ bool ModelUploader::zip() { // File Dialog QString filename = QFileDialog::getOpenFileName(NULL, "Select your .fst file ...", - QStandardPaths::writableLocation(QStandardPaths::DownloadLocation), + QStandardPaths::writableLocation(QStandardPaths::HomeLocation), "*.fst"); + qDebug() << QStandardPaths::writableLocation(QStandardPaths::HomeLocation); if (filename == "") { // If the user canceled we return. return false; @@ -103,6 +110,7 @@ bool ModelUploader::zip() { " name=\"model_name\""); textPart.setBody(line[1].toUtf8()); _dataMultiPart->append(textPart); + _url = S3_URL + ((_isHead)? "/models/heads/" : "/models/skeletons/") + line[1].toUtf8() + ".fst"; } else if (line[0] == FILENAME_FIELD) { QFileInfo fbx(QFileInfo(fst).path() + "/" + line[1]); if (!fbx.exists() || !fbx.isFile()) { // Check existence @@ -167,9 +175,9 @@ bool ModelUploader::zip() { return true; } -bool ModelUploader::send() { - if (!_readyToSend) { - return false; +void ModelUploader::send() { + if (!zip()) { + return; } JSONCallbackParameters callbackParams; @@ -177,22 +185,52 @@ bool ModelUploader::send() { callbackParams.jsonCallbackMethod = "uploadSuccess"; callbackParams.errorCallbackReceiver = this; callbackParams.errorCallbackMethod = "uploadFailed"; + callbackParams.updateReciever = this; + callbackParams.updateSlot = SLOT(uploadUpdate(qint64, qint64)); AccountManager::getInstance().authenticatedRequest(MODEL_URL, QNetworkAccessManager::PostOperation, callbackParams, QByteArray(), _dataMultiPart); _zipDir = NULL; _dataMultiPart = NULL; qDebug() << "Sending model..."; + _progressDialog = new QDialog(); + _progressBar = new QProgressBar(_progressDialog); + _progressBar->setRange(0, 100); + _progressBar->setValue(0); - return true; + _progressDialog->setWindowTitle("Uploading model..."); + _progressDialog->setLayout(new QGridLayout(_progressDialog)); + _progressDialog->layout()->addWidget(_progressBar); + + _progressDialog->exec(); + + delete _progressDialog; + _progressDialog = NULL; + _progressBar = NULL; +} + +void ModelUploader::uploadUpdate(qint64 bytesSent, qint64 bytesTotal) { + if (_progressDialog) { + _progressBar->setRange(0, bytesTotal); + _progressBar->setValue(bytesSent); + } } void ModelUploader::uploadSuccess(const QJsonObject& jsonResponse) { - qDebug() << "Model sent with success to the data server."; - qDebug() << "It might take a few minute for it to appear in your model browser."; - deleteLater(); + if (_progressDialog) { + _progressDialog->accept(); + } + QMessageBox::information(NULL, + QString("ModelUploader::uploadSuccess()"), + QString("Your model is being processed by the system."), + QMessageBox::Ok); + qDebug() << "Model sent with success"; + checkS3(); } void ModelUploader::uploadFailed(QNetworkReply::NetworkError errorCode, const QString& errorString) { + if (_progressDialog) { + _progressDialog->reject(); + } QMessageBox::warning(NULL, QString("ModelUploader::uploadFailed()"), QString("Model could not be sent to the data server."), @@ -201,6 +239,42 @@ void ModelUploader::uploadFailed(QNetworkReply::NetworkError errorCode, const QS deleteLater(); } +void ModelUploader::checkS3() { + qDebug() << "Checking S3 for " << _url; + QNetworkRequest request(_url); + QNetworkReply* reply = _networkAccessManager.head(request); + connect(reply, SIGNAL(finished()), SLOT(processCheck())); +} + +void ModelUploader::processCheck() { + QNetworkReply* reply = static_cast(sender()); + _timer.stop(); + + switch (reply->error()) { + case QNetworkReply::NoError: + QMessageBox::information(NULL, + QString("ModelUploader::processCheck()"), + QString("Your model is now available in the browser."), + QMessageBox::Ok); + deleteLater(); + break; + case QNetworkReply::ContentNotFoundError: + if (--_numberOfChecks) { + _timer.start(TIMEOUT); + break; + } + default: + QMessageBox::warning(NULL, + QString("ModelUploader::processCheck()"), + QString("Could not verify that the model is present on the server."), + QMessageBox::Ok); + deleteLater(); + break; + } + + delete reply; +} + bool ModelUploader::addTextures(const QFileInfo& texdir) { QStringList filter; filter << "*.png" << "*.tif" << "*.jpg" << "*.jpeg"; diff --git a/libraries/shared/src/ModelUploader.h b/libraries/shared/src/ModelUploader.h index f127008f44..066a577e57 100644 --- a/libraries/shared/src/ModelUploader.h +++ b/libraries/shared/src/ModelUploader.h @@ -10,9 +10,14 @@ #ifndef __hifi__ModelUploader__ #define __hifi__ModelUploader__ -class TemporaryDir; -class QHttpMultiPart; +#include + +class QDialog; class QFileInfo; +class QHttpMultiPart; +class QProgressBar; + +class TemporaryDir; class ModelUploader : public QObject { Q_OBJECT @@ -21,14 +26,18 @@ public: ModelUploader(bool isHead); ~ModelUploader(); - bool zip(); - bool send(); +public slots: + void send(); private slots: + void uploadUpdate(qint64 bytesSent, qint64 bytesTotal); void uploadSuccess(const QJsonObject& jsonResponse); void uploadFailed(QNetworkReply::NetworkError errorCode, const QString& errorString); + void checkS3(); + void processCheck(); private: + QString _url; TemporaryDir* _zipDir; int _lodCount; int _texturesCount; @@ -37,8 +46,16 @@ private: bool _readyToSend; QHttpMultiPart* _dataMultiPart; + QNetworkAccessManager _networkAccessManager; + + int _numberOfChecks; + QTimer _timer; + + QDialog* _progressDialog; + QProgressBar* _progressBar; + bool zip(); bool addTextures(const QFileInfo& texdir); bool compressFile(const QString& inFileName, const QString& outFileName); bool addPart(const QString& path, const QString& name); From 23c6873d999bd7deed28126766e7ffe51b4872bc Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Mon, 7 Apr 2014 14:12:29 -0700 Subject: [PATCH 185/595] Add Uuid object to ScriptEngine --- libraries/script-engine/src/ScriptEngine.cpp | 7 ++-- libraries/script-engine/src/ScriptEngine.h | 2 ++ libraries/script-engine/src/ScriptUUID.cpp | 35 ++++++++++++++++++++ libraries/script-engine/src/ScriptUUID.h | 29 ++++++++++++++++ 4 files changed, 71 insertions(+), 2 deletions(-) create mode 100644 libraries/script-engine/src/ScriptUUID.cpp create mode 100644 libraries/script-engine/src/ScriptUUID.h diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index 7572638a30..7d3dd650ae 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -60,7 +60,8 @@ ScriptEngine::ScriptEngine(const QString& scriptContents, const QString& fileNam _scriptName(), _fileNameString(fileNameString), _quatLibrary(), - _vec3Library() + _vec3Library(), + _uuidLibrary() { } @@ -83,7 +84,8 @@ ScriptEngine::ScriptEngine(const QUrl& scriptURL, _scriptName(), _fileNameString(), _quatLibrary(), - _vec3Library() + _vec3Library(), + _uuidLibrary() { QString scriptURLString = scriptURL.toString(); _fileNameString = scriptURLString; @@ -197,6 +199,7 @@ void ScriptEngine::init() { registerGlobalObject("Particles", &_particlesScriptingInterface); registerGlobalObject("Quat", &_quatLibrary); registerGlobalObject("Vec3", &_vec3Library); + registerGlobalObject("Uuid", &_uuidLibrary); registerGlobalObject("Voxels", &_voxelsScriptingInterface); diff --git a/libraries/script-engine/src/ScriptEngine.h b/libraries/script-engine/src/ScriptEngine.h index 964f64a005..2b98549d66 100644 --- a/libraries/script-engine/src/ScriptEngine.h +++ b/libraries/script-engine/src/ScriptEngine.h @@ -22,6 +22,7 @@ #include "AbstractControllerScriptingInterface.h" #include "Quat.h" +#include "ScriptUUID.h" #include "Vec3.h" class ParticlesScriptingInterface; @@ -121,6 +122,7 @@ private: QString _fileNameString; Quat _quatLibrary; Vec3 _vec3Library; + ScriptUUID _uuidLibrary; }; #endif /* defined(__hifi__ScriptEngine__) */ diff --git a/libraries/script-engine/src/ScriptUUID.cpp b/libraries/script-engine/src/ScriptUUID.cpp new file mode 100644 index 0000000000..cea7247e90 --- /dev/null +++ b/libraries/script-engine/src/ScriptUUID.cpp @@ -0,0 +1,35 @@ +// +// ScriptUUID.h +// hifi +// +// Created by Andrew Meadows on 2014.04.07 +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// + +#include + +#include "ScriptUUID.h" + +QUuid ScriptUUID::fromString(const QString& s) { + return QUuid(s); +} + +QString ScriptUUID::toString(const QUuid& id) { + return id.toString(); +} + +QUuid ScriptUUID::generate() { + return QUuid::createUuid(); +} + +bool ScriptUUID::isEqual(const QUuid& idA, const QUuid& idB) { + return idA == idB; +} + +bool ScriptUUID::isNull(const QUuid& id) { + return id.isNull(); +} + +void ScriptUUID::print(const QString& lable, const QUuid& id) { + qDebug() << qPrintable(lable) << id.toString(); +} diff --git a/libraries/script-engine/src/ScriptUUID.h b/libraries/script-engine/src/ScriptUUID.h new file mode 100644 index 0000000000..43e885cf98 --- /dev/null +++ b/libraries/script-engine/src/ScriptUUID.h @@ -0,0 +1,29 @@ +// +// ScriptUUID.h +// hifi +// +// Created by Andrew Meadows on 2014.04.07 +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// + +#ifndef __hifi__ScriptUUID__ +#define __hifi__ScriptUUID__ + +#include + +/// Scriptable interface a UUID helper class object. Used exclusively in the JavaScript API +class ScriptUUID : public QObject { + Q_OBJECT + +public slots: + QUuid fromString(const QString& string); + QString toString(const QUuid& id); + QUuid generate(); + bool isEqual(const QUuid& idA, const QUuid& idB); + bool isNull(const QUuid& id); + void print(const QString& lable, const QUuid& id); +}; + + + +#endif /* defined(__hifi__Vec3__) */ From 0011276b0bc1e6aab7b8854d39acae874a19261d Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Mon, 7 Apr 2014 14:19:17 -0700 Subject: [PATCH 186/595] Added back the download stats, which got lost in a merge. --- interface/src/ui/Stats.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp index 1722732e76..dbcbb3d8bb 100644 --- a/interface/src/ui/Stats.cpp +++ b/interface/src/ui/Stats.cpp @@ -20,6 +20,8 @@ #include "Menu.h" #include "Util.h" +using namespace std; + const int STATS_PELS_PER_LINE = 20; const int STATS_GENERAL_MIN_WIDTH = 165; @@ -287,7 +289,7 @@ void Stats::display( MyAvatar* myAvatar = Application::getInstance()->getAvatar(); glm::vec3 avatarPos = myAvatar->getPosition(); - lines = _expanded ? 4 : 3; + lines = _expanded ? 5 : 3; drawBackground(backgroundColor, horizontalOffset, 0, _geoStatsWidth, lines * STATS_PELS_PER_LINE + 10); horizontalOffset += 5; @@ -318,6 +320,16 @@ void Stats::display( verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarMixerStats, color); + + stringstream downloads; + downloads << "Downloads: "; + foreach (Resource* resource, ResourceCache::getLoadingRequests()) { + downloads << (int)(resource->getProgress() * 100.0f) << "% "; + } + downloads << "(" << ResourceCache::getPendingRequestCount() << " pending)"; + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, downloads.str().c_str(), color); } verticalOffset = 0; From 262c6d320640a168894593764d612934e156a969 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 7 Apr 2014 14:35:13 -0700 Subject: [PATCH 187/595] Fixed double JSON callback when http error occurs --- libraries/shared/src/AccountManager.cpp | 25 +++++++++++++++---------- libraries/shared/src/AccountManager.h | 6 ++++-- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/libraries/shared/src/AccountManager.cpp b/libraries/shared/src/AccountManager.cpp index 841fd9dde0..fe361ba751 100644 --- a/libraries/shared/src/AccountManager.cpp +++ b/libraries/shared/src/AccountManager.cpp @@ -179,15 +179,23 @@ void AccountManager::invokedRequest(const QString& path, QNetworkAccessManager:: // if we ended up firing of a request, hook up to it now connect(networkReply, SIGNAL(finished()), - SLOT(passSuccessToCallback())); - connect(networkReply, SIGNAL(error(QNetworkReply::NetworkError)), - SLOT(passErrorToCallback(QNetworkReply::NetworkError))); + SLOT(processReply())); } } } -void AccountManager::passSuccessToCallback() { +void AccountManager::processReply() { QNetworkReply* requestReply = reinterpret_cast(sender()); + + if (requestReply->error() == QNetworkReply::NoError) { + passSuccessToCallback(requestReply); + } else { + passErrorToCallback(requestReply); + } + delete requestReply; +} + +void AccountManager::passSuccessToCallback(QNetworkReply* requestReply) { QJsonDocument jsonResponse = QJsonDocument::fromJson(requestReply->readAll()); JSONCallbackParameters callbackParams = _pendingCallbackMap.value(requestReply); @@ -206,17 +214,15 @@ void AccountManager::passSuccessToCallback() { qDebug() << jsonResponse; } } - delete requestReply; } -void AccountManager::passErrorToCallback(QNetworkReply::NetworkError errorCode) { - QNetworkReply* requestReply = reinterpret_cast(sender()); +void AccountManager::passErrorToCallback(QNetworkReply* requestReply) { JSONCallbackParameters callbackParams = _pendingCallbackMap.value(requestReply); if (callbackParams.errorCallbackReceiver) { // invoke the right method on the callback receiver QMetaObject::invokeMethod(callbackParams.errorCallbackReceiver, qPrintable(callbackParams.errorCallbackMethod), - Q_ARG(QNetworkReply::NetworkError, errorCode), + Q_ARG(QNetworkReply::NetworkError, requestReply->error()), Q_ARG(const QString&, requestReply->errorString())); // remove the related reply-callback group from the map @@ -224,10 +230,9 @@ void AccountManager::passErrorToCallback(QNetworkReply::NetworkError errorCode) } else { if (VERBOSE_HTTP_REQUEST_DEBUGGING) { qDebug() << "Received error response from data-server that has no matching callback."; - qDebug() << "Error" << errorCode << "-" << requestReply->errorString(); + qDebug() << "Error" << requestReply->error() << "-" << requestReply->errorString(); } } - delete requestReply; } bool AccountManager::hasValidAccessToken() { diff --git a/libraries/shared/src/AccountManager.h b/libraries/shared/src/AccountManager.h index b410885705..55a40438e0 100644 --- a/libraries/shared/src/AccountManager.h +++ b/libraries/shared/src/AccountManager.h @@ -73,13 +73,15 @@ signals: void loginComplete(const QUrl& authURL); void logoutComplete(); private slots: - void passSuccessToCallback(); - void passErrorToCallback(QNetworkReply::NetworkError errorCode); + void processReply(); private: AccountManager(); AccountManager(AccountManager const& other); // not implemented void operator=(AccountManager const& other); // not implemented + void passSuccessToCallback(QNetworkReply* reply); + void passErrorToCallback(QNetworkReply* reply); + Q_INVOKABLE void invokedRequest(const QString& path, QNetworkAccessManager::Operation operation, const JSONCallbackParameters& callbackParams, const QByteArray& dataByteArray, From 56b0583600bb21ff12c4180cc58c72d780283b22 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 7 Apr 2014 14:42:35 -0700 Subject: [PATCH 188/595] Fix for editVoxels/inspect conflict --- examples/editVoxels.js | 46 ++++++++++++++++++------------------------ 1 file changed, 20 insertions(+), 26 deletions(-) diff --git a/examples/editVoxels.js b/examples/editVoxels.js index 4922caf0d8..1dc8c189f3 100644 --- a/examples/editVoxels.js +++ b/examples/editVoxels.js @@ -32,6 +32,7 @@ var MIN_PASTE_VOXEL_SCALE = .256; var zFightingSizeAdjust = 0.002; // used to adjust preview voxels to prevent z fighting var previewLineWidth = 1.5; +var inspectJsIsRunning = false; var isAdding = false; var isExtruding = false; var extrudeDirection = { x: 0, y: 0, z: 0 }; @@ -62,9 +63,9 @@ var whichColor = -1; // Starting color is 'Copy' mode // Create sounds for adding, deleting, recoloring voxels var addSound1 = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Voxels/voxel+create+2.raw"); -var addSound2 = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Voxels/voxel+create+3.raw"); -var addSound3 = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Voxels/voxel+create+4.raw"); +var addSound2 = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Voxels/voxel+create+4.raw"); +var addSound3 = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Voxels/voxel+create+3.raw"); var deleteSound = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Voxels/voxel+delete+2.raw"); var changeColorSound = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Voxels/voxel+edit+2.raw"); var clickSound = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Switches+and+sliders/toggle+switch+-+medium.raw"); @@ -727,6 +728,9 @@ function trackKeyPressEvent(event) { trackAsEyedropper = true; moveTools(); } + if (event.text == "ALT") { + inspectJsIsRunning = true; + } showPreviewGuides(); } @@ -739,6 +743,10 @@ function trackKeyReleaseEvent(event) { showPreviewGuides(); Audio.playSound(clickSound, audioOptions); } + + if (event.text == "ALT") { + inspectJsIsRunning = false; + } if (editToolsOn) { if (event.text == "ESC") { @@ -777,11 +785,13 @@ function trackKeyReleaseEvent(event) { } function mousePressEvent(event) { - // if our tools are off, then don't do anything if (!editToolsOn) { return; } + if (inspectJsIsRunning) { + return; + } var clickedOnSomething = false; var clickedOverlay = Overlays.getOverlayAtPoint({x: event.x, y: event.y}); @@ -1061,7 +1071,9 @@ function mouseMoveEvent(event) { if (!editToolsOn) { return; } - + if (inspectJsIsRunning) { + return; + } if (isMovingSlider) { thumbX = (event.x - thumbClickOffsetX) - sliderX; @@ -1121,7 +1133,10 @@ function mouseReleaseEvent(event) { if (!editToolsOn) { return; } - + if (inspectJsIsRunning) { + return; + } + if (isMovingSlider) { isMovingSlider = false; } @@ -1214,24 +1229,6 @@ function moveTools() { } -function touchBeginEvent(event) { - if (!editToolsOn) { - return; - } -} - -function touchUpdateEvent(event) { - if (!editToolsOn) { - return; - } -} - -function touchEndEvent(event) { - if (!editToolsOn) { - return; - } -} - var lastFingerAddVoxel = { x: -1, y: -1, z: -1}; // off of the build-able area var lastFingerDeleteVoxel = { x: -1, y: -1, z: -1}; // off of the build-able area @@ -1332,9 +1329,6 @@ Controller.mouseReleaseEvent.connect(mouseReleaseEvent); Controller.mouseMoveEvent.connect(mouseMoveEvent); Controller.keyPressEvent.connect(keyPressEvent); Controller.keyReleaseEvent.connect(keyReleaseEvent); -Controller.touchBeginEvent.connect(touchBeginEvent); -Controller.touchUpdateEvent.connect(touchUpdateEvent); -Controller.touchEndEvent.connect(touchEndEvent); Controller.captureKeyEvents({ text: "+" }); Controller.captureKeyEvents({ text: "-" }); From 79670563d487058daa08df46f1a64c2b3230f512 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Mon, 7 Apr 2014 14:42:49 -0700 Subject: [PATCH 189/595] AvatarData stores its sessionID --- interface/src/avatar/AvatarManager.cpp | 26 ++++++++++++------------- libraries/avatars/src/AvatarData.h | 5 +++++ libraries/avatars/src/AvatarHashMap.cpp | 1 + 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/interface/src/avatar/AvatarManager.cpp b/interface/src/avatar/AvatarManager.cpp index c2ba28ac7b..5b98d933ff 100644 --- a/interface/src/avatar/AvatarManager.cpp +++ b/interface/src/avatar/AvatarManager.cpp @@ -123,8 +123,8 @@ void AvatarManager::renderAvatarFades(const glm::vec3& cameraPosition, Avatar::R } } -AvatarSharedPointer AvatarManager::matchingOrNewAvatar(const QUuid& nodeUUID, const QWeakPointer& mixerWeakPointer) { - AvatarSharedPointer matchingAvatar = _avatarHash.value(nodeUUID); +AvatarSharedPointer AvatarManager::matchingOrNewAvatar(const QUuid& sessionID, const QWeakPointer& mixerWeakPointer) { + AvatarSharedPointer matchingAvatar = _avatarHash.value(sessionID); if (!matchingAvatar) { // construct a new Avatar for this node @@ -133,9 +133,9 @@ AvatarSharedPointer AvatarManager::matchingOrNewAvatar(const QUuid& nodeUUID, co // insert the new avatar into our hash matchingAvatar = AvatarSharedPointer(avatar); - _avatarHash.insert(nodeUUID, matchingAvatar); + _avatarHash.insert(sessionID, matchingAvatar); - qDebug() << "Adding avatar with UUID" << nodeUUID << "to AvatarManager hash."; + qDebug() << "Adding avatar with sessionID " << sessionID << "to AvatarManager hash."; } return matchingAvatar; @@ -166,10 +166,10 @@ void AvatarManager::processAvatarDataPacket(const QByteArray &datagram, const QW // enumerate over all of the avatars in this packet // only add them if mixerWeakPointer points to something (meaning that mixer is still around) while (bytesRead < datagram.size() && mixerWeakPointer.data()) { - QUuid nodeUUID = QUuid::fromRfc4122(datagram.mid(bytesRead, NUM_BYTES_RFC4122_UUID)); + QUuid sessionID = QUuid::fromRfc4122(datagram.mid(bytesRead, NUM_BYTES_RFC4122_UUID)); bytesRead += NUM_BYTES_RFC4122_UUID; - AvatarSharedPointer matchingAvatarData = matchingOrNewAvatar(nodeUUID, mixerWeakPointer); + AvatarSharedPointer matchingAvatarData = matchingOrNewAvatar(sessionID, mixerWeakPointer); // have the matching (or new) avatar parse the data from the packet bytesRead += matchingAvatarData->parseDataAtOffset(datagram, bytesRead); @@ -188,16 +188,16 @@ void AvatarManager::processAvatarIdentityPacket(const QByteArray &packet, const QDataStream identityStream(packet); identityStream.skipRawData(numBytesForPacketHeader(packet)); - QUuid nodeUUID; + QUuid sessionID; while (!identityStream.atEnd()) { QUrl faceMeshURL, skeletonURL; QString displayName; - identityStream >> nodeUUID >> faceMeshURL >> skeletonURL >> displayName; + identityStream >> sessionID >> faceMeshURL >> skeletonURL >> displayName; // mesh URL for a UUID, find avatar in our list - AvatarSharedPointer matchingAvatar = matchingOrNewAvatar(nodeUUID, mixerWeakPointer); + AvatarSharedPointer matchingAvatar = matchingOrNewAvatar(sessionID, mixerWeakPointer); if (matchingAvatar) { Avatar* avatar = static_cast(matchingAvatar.data()); @@ -218,9 +218,9 @@ void AvatarManager::processAvatarIdentityPacket(const QByteArray &packet, const void AvatarManager::processAvatarBillboardPacket(const QByteArray& packet, const QWeakPointer& mixerWeakPointer) { int headerSize = numBytesForPacketHeader(packet); - QUuid nodeUUID = QUuid::fromRfc4122(QByteArray::fromRawData(packet.constData() + headerSize, NUM_BYTES_RFC4122_UUID)); + QUuid sessionID = QUuid::fromRfc4122(QByteArray::fromRawData(packet.constData() + headerSize, NUM_BYTES_RFC4122_UUID)); - AvatarSharedPointer matchingAvatar = matchingOrNewAvatar(nodeUUID, mixerWeakPointer); + AvatarSharedPointer matchingAvatar = matchingOrNewAvatar(sessionID, mixerWeakPointer); if (matchingAvatar) { Avatar* avatar = static_cast(matchingAvatar.data()); QByteArray billboard = packet.mid(headerSize + NUM_BYTES_RFC4122_UUID); @@ -232,10 +232,10 @@ void AvatarManager::processAvatarBillboardPacket(const QByteArray& packet, const void AvatarManager::processKillAvatar(const QByteArray& datagram) { // read the node id - QUuid nodeUUID = QUuid::fromRfc4122(datagram.mid(numBytesForPacketHeader(datagram), NUM_BYTES_RFC4122_UUID)); + QUuid sessionID = QUuid::fromRfc4122(datagram.mid(numBytesForPacketHeader(datagram), NUM_BYTES_RFC4122_UUID)); // remove the avatar with that UUID from our hash, if it exists - AvatarHash::iterator matchedAvatar = _avatarHash.find(nodeUUID); + AvatarHash::iterator matchedAvatar = _avatarHash.find(sessionID); if (matchedAvatar != _avatarHash.end()) { erase(matchedAvatar); } diff --git a/libraries/avatars/src/AvatarData.h b/libraries/avatars/src/AvatarData.h index 221bbd0428..2637b5a0c3 100755 --- a/libraries/avatars/src/AvatarData.h +++ b/libraries/avatars/src/AvatarData.h @@ -36,6 +36,7 @@ typedef unsigned long long quint64; #include #include #include +#include #include #include @@ -97,6 +98,9 @@ public: AvatarData(); virtual ~AvatarData(); + const QUuid& getSessionID() { return _sessionID; } + void setSessionID(const QUuid& id) { _sessionID = id; } + const glm::vec3& getPosition() const { return _position; } void setPosition(const glm::vec3 position) { _position = position; } @@ -218,6 +222,7 @@ public slots: void sendBillboardPacket(); void setBillboardFromNetworkReply(); protected: + QUuid _sessionID; glm::vec3 _position; glm::vec3 _handPosition; diff --git a/libraries/avatars/src/AvatarHashMap.cpp b/libraries/avatars/src/AvatarHashMap.cpp index 82485691c5..5a56e3d5dc 100644 --- a/libraries/avatars/src/AvatarHashMap.cpp +++ b/libraries/avatars/src/AvatarHashMap.cpp @@ -15,6 +15,7 @@ AvatarHashMap::AvatarHashMap() : void AvatarHashMap::insert(const QUuid& id, AvatarSharedPointer avatar) { _avatarHash.insert(id, avatar); + avatar->setSessionID(id); } AvatarHash::iterator AvatarHashMap::erase(const AvatarHash::iterator& iterator) { From 15e9d45dc3465503364adcaf83dc55738b55ff81 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Mon, 7 Apr 2014 15:41:42 -0700 Subject: [PATCH 190/595] Switched from storing Euler angles to using quaternions along with a quaternion editor. Also, use a default step of 0.01 for floats/doubles. --- interface/src/MetavoxelSystem.cpp | 8 +-- interface/src/MetavoxelSystem.h | 2 +- interface/src/renderer/Model.cpp | 5 +- libraries/metavoxels/src/Bitstream.cpp | 9 +++ libraries/metavoxels/src/Bitstream.h | 3 + libraries/metavoxels/src/MetavoxelData.cpp | 2 +- libraries/metavoxels/src/MetavoxelData.h | 10 ++-- libraries/metavoxels/src/MetavoxelUtil.cpp | 69 +++++++++++++++++----- libraries/metavoxels/src/MetavoxelUtil.h | 66 +++++++++++++++++---- 9 files changed, 136 insertions(+), 38 deletions(-) diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index 8fe4b53922..7eb046756b 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -395,7 +395,7 @@ void SphereRenderer::renderUnclipped(float alpha, Mode mode) { glPushMatrix(); const glm::vec3& translation = sphere->getTranslation(); glTranslatef(translation.x, translation.y, translation.z); - glm::quat rotation = glm::quat(glm::radians(sphere->getRotation())); + glm::quat rotation = sphere->getRotation(); glm::vec3 axis = glm::axis(rotation); glRotatef(glm::angle(rotation), axis.x, axis.y, axis.z); @@ -418,7 +418,7 @@ void StaticModelRenderer::init(Spanner* spanner) { applyURL(staticModel->getURL()); connect(spanner, SIGNAL(translationChanged(const glm::vec3&)), SLOT(applyTranslation(const glm::vec3&))); - connect(spanner, SIGNAL(rotationChanged(const glm::vec3&)), SLOT(applyRotation(const glm::vec3&))); + connect(spanner, SIGNAL(rotationChanged(const glm::quat&)), SLOT(applyRotation(const glm::quat&))); connect(spanner, SIGNAL(scaleChanged(float)), SLOT(applyScale(float))); connect(spanner, SIGNAL(urlChanged(const QUrl&)), SLOT(applyURL(const QUrl&))); } @@ -461,8 +461,8 @@ void StaticModelRenderer::applyTranslation(const glm::vec3& translation) { _model->setTranslation(translation); } -void StaticModelRenderer::applyRotation(const glm::vec3& rotation) { - _model->setRotation(glm::quat(glm::radians(rotation))); +void StaticModelRenderer::applyRotation(const glm::quat& rotation) { + _model->setRotation(rotation); } void StaticModelRenderer::applyScale(float scale) { diff --git a/interface/src/MetavoxelSystem.h b/interface/src/MetavoxelSystem.h index 7612437bb9..ecab30d535 100644 --- a/interface/src/MetavoxelSystem.h +++ b/interface/src/MetavoxelSystem.h @@ -189,7 +189,7 @@ protected: private slots: void applyTranslation(const glm::vec3& translation); - void applyRotation(const glm::vec3& eulerAngles); // eulerAngles are in degrees + void applyRotation(const glm::quat& rotation); void applyScale(float scale); void applyURL(const QUrl& url); diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 6583b436b7..36fbbe3833 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -58,7 +58,10 @@ Model::SkinLocations Model::_skinShadowLocations; void Model::setScale(const glm::vec3& scale) { glm::vec3 deltaScale = _scale - scale; - if (glm::length2(deltaScale) > EPSILON) { + + // decreased epsilon because this wasn't handling scale changes of 0.01 + const float SMALLER_EPSILON = EPSILON * 0.0001f; + if (glm::length2(deltaScale) > SMALLER_EPSILON) { _scale = scale; rebuildShapes(); } diff --git a/libraries/metavoxels/src/Bitstream.cpp b/libraries/metavoxels/src/Bitstream.cpp index 09e71700be..3f3d6e5423 100644 --- a/libraries/metavoxels/src/Bitstream.cpp +++ b/libraries/metavoxels/src/Bitstream.cpp @@ -35,6 +35,7 @@ REGISTER_SIMPLE_TYPE_STREAMER(SharedObjectPointer) // some types don't quite work with our macro static int vec3Streamer = Bitstream::registerTypeStreamer(qMetaTypeId(), new SimpleTypeStreamer()); +static int quatStreamer = Bitstream::registerTypeStreamer(qMetaTypeId(), new SimpleTypeStreamer()); static int metaObjectStreamer = Bitstream::registerTypeStreamer(qMetaTypeId(), new SimpleTypeStreamer()); @@ -352,6 +353,14 @@ Bitstream& Bitstream::operator>>(glm::vec3& value) { return *this >> value.x >> value.y >> value.z; } +Bitstream& Bitstream::operator<<(const glm::quat& value) { + return *this << value.w << value.x << value.y << value.z; +} + +Bitstream& Bitstream::operator>>(glm::quat& value) { + return *this >> value.w >> value.x >> value.y >> value.z; +} + Bitstream& Bitstream::operator<<(const QByteArray& string) { *this << string.size(); return write(string.constData(), string.size() * BITS_IN_BYTE); diff --git a/libraries/metavoxels/src/Bitstream.h b/libraries/metavoxels/src/Bitstream.h index 8f36ce9a08..d7b16fcc4a 100644 --- a/libraries/metavoxels/src/Bitstream.h +++ b/libraries/metavoxels/src/Bitstream.h @@ -312,6 +312,9 @@ public: Bitstream& operator<<(const glm::vec3& value); Bitstream& operator>>(glm::vec3& value); + Bitstream& operator<<(const glm::quat& value); + Bitstream& operator>>(glm::quat& value); + Bitstream& operator<<(const QByteArray& string); Bitstream& operator>>(QByteArray& string); diff --git a/libraries/metavoxels/src/MetavoxelData.cpp b/libraries/metavoxels/src/MetavoxelData.cpp index e4cce9c735..6ae847cea3 100644 --- a/libraries/metavoxels/src/MetavoxelData.cpp +++ b/libraries/metavoxels/src/MetavoxelData.cpp @@ -1545,7 +1545,7 @@ void Transformable::setTranslation(const glm::vec3& translation) { } } -void Transformable::setRotation(const glm::vec3& rotation) { +void Transformable::setRotation(const glm::quat& rotation) { if (_rotation != rotation) { emit rotationChanged(_rotation = rotation); } diff --git a/libraries/metavoxels/src/MetavoxelData.h b/libraries/metavoxels/src/MetavoxelData.h index 41285af2f5..7a53598042 100644 --- a/libraries/metavoxels/src/MetavoxelData.h +++ b/libraries/metavoxels/src/MetavoxelData.h @@ -533,7 +533,7 @@ public: class Transformable : public Spanner { Q_OBJECT Q_PROPERTY(glm::vec3 translation MEMBER _translation WRITE setTranslation NOTIFY translationChanged) - Q_PROPERTY(glm::vec3 rotation MEMBER _rotation WRITE setRotation NOTIFY rotationChanged) + Q_PROPERTY(glm::quat rotation MEMBER _rotation WRITE setRotation NOTIFY rotationChanged) Q_PROPERTY(float scale MEMBER _scale WRITE setScale NOTIFY scaleChanged) public: @@ -543,8 +543,8 @@ public: void setTranslation(const glm::vec3& translation); const glm::vec3& getTranslation() const { return _translation; } - void setRotation(const glm::vec3& rotation); - const glm::vec3& getRotation() const { return _rotation; } + void setRotation(const glm::quat& rotation); + const glm::quat& getRotation() const { return _rotation; } void setScale(float scale); float getScale() const { return _scale; } @@ -552,13 +552,13 @@ public: signals: void translationChanged(const glm::vec3& translation); - void rotationChanged(const glm::vec3& rotation); + void rotationChanged(const glm::quat& rotation); void scaleChanged(float scale); private: glm::vec3 _translation; - glm::vec3 _rotation; // Euler Angles in degrees + glm::quat _rotation; float _scale; }; diff --git a/libraries/metavoxels/src/MetavoxelUtil.cpp b/libraries/metavoxels/src/MetavoxelUtil.cpp index 7995809f1c..b259c1b513 100644 --- a/libraries/metavoxels/src/MetavoxelUtil.cpp +++ b/libraries/metavoxels/src/MetavoxelUtil.cpp @@ -52,6 +52,7 @@ public: DoubleEditor::DoubleEditor(QWidget* parent) : QDoubleSpinBox(parent) { setMinimum(-FLT_MAX); setMaximum(FLT_MAX); + setSingleStep(0.01); } DelegatingItemEditorFactory::DelegatingItemEditorFactory() : @@ -127,6 +128,12 @@ static QItemEditorCreatorBase* createVec3EditorCreator() { return creator; } +static QItemEditorCreatorBase* createQuatEditorCreator() { + QItemEditorCreatorBase* creator = new LazyItemEditorCreator(); + getItemEditorFactory()->registerEditor(qMetaTypeId(), creator); + return creator; +} + static QItemEditorCreatorBase* createParameterizedURLEditorCreator() { QItemEditorCreatorBase* creator = new LazyItemEditorCreator(); getItemEditorFactory()->registerEditor(qMetaTypeId(), creator); @@ -138,6 +145,7 @@ static QItemEditorCreatorBase* qMetaObjectEditorCreator = createQMetaObjectEdito static QItemEditorCreatorBase* qColorEditorCreator = createQColorEditorCreator(); static QItemEditorCreatorBase* qUrlEditorCreator = createQUrlEditorCreator(); static QItemEditorCreatorBase* vec3EditorCreator = createVec3EditorCreator(); +static QItemEditorCreatorBase* quatEditorCreator = createQuatEditorCreator(); static QItemEditorCreatorBase* parameterizedURLEditorCreator = createParameterizedURLEditorCreator(); QByteArray signal(const char* signature) { @@ -380,7 +388,7 @@ void QUrlEditor::updateSettings() { QSettings().setValue("editorURLs", urls); } -Vec3Editor::Vec3Editor(QWidget* parent) : QWidget(parent) { +BaseVec3Editor::BaseVec3Editor(QWidget* parent) : QWidget(parent) { QHBoxLayout* layout = new QHBoxLayout(); layout->setContentsMargins(QMargins()); setLayout(layout); @@ -390,26 +398,59 @@ Vec3Editor::Vec3Editor(QWidget* parent) : QWidget(parent) { layout->addWidget(_z = createComponentBox()); } -void Vec3Editor::setVector(const glm::vec3& vector) { - _vector = vector; - _x->setValue(vector.x); - _y->setValue(vector.y); - _z->setValue(vector.z); -} - -void Vec3Editor::updateVector() { - emit vectorChanged(_vector = glm::vec3(_x->value(), _y->value(), _z->value())); -} - -QDoubleSpinBox* Vec3Editor::createComponentBox() { +QDoubleSpinBox* BaseVec3Editor::createComponentBox() { QDoubleSpinBox* box = new QDoubleSpinBox(); box->setMinimum(-FLT_MAX); box->setMaximum(FLT_MAX); box->setMinimumWidth(50); - connect(box, SIGNAL(valueChanged(double)), SLOT(updateVector())); + connect(box, SIGNAL(valueChanged(double)), SLOT(updateValue())); return box; } +Vec3Editor::Vec3Editor(QWidget* parent) : BaseVec3Editor(parent) { + _x->setSingleStep(0.01); + _y->setSingleStep(0.01); + _z->setSingleStep(0.01); +} + +static void setComponentValue(QDoubleSpinBox* box, double value) { + box->blockSignals(true); + box->setValue(value); + box->blockSignals(false); +} + +void Vec3Editor::setValue(const glm::vec3& value) { + _value = value; + setComponentValue(_x, value.x); + setComponentValue(_y, value.y); + setComponentValue(_z, value.z); +} + +void Vec3Editor::updateValue() { + emit valueChanged(_value = glm::vec3(_x->value(), _y->value(), _z->value())); +} + +QuatEditor::QuatEditor(QWidget* parent) : BaseVec3Editor(parent) { + _x->setRange(-180.0, 180.0); + _y->setRange(-90.0, 90.0); + _z->setRange(-180.0, 180.0); + + _x->setWrapping(true); + _y->setWrapping(true); + _z->setWrapping(true); +} + +void QuatEditor::setValue(const glm::quat& value) { + glm::vec3 eulers = glm::degrees(safeEulerAngles(_value = value)); + setComponentValue(_x, eulers.x); + setComponentValue(_y, eulers.y); + setComponentValue(_z, eulers.z); +} + +void QuatEditor::updateValue() { + emit valueChanged(_value = glm::quat(glm::radians(glm::vec3(_x->value(), _y->value(), _z->value())))); +} + ParameterizedURL::ParameterizedURL(const QUrl& url, const ScriptHash& parameters) : _url(url), _parameters(parameters) { diff --git a/libraries/metavoxels/src/MetavoxelUtil.h b/libraries/metavoxels/src/MetavoxelUtil.h index 9972981bc7..cc6c540151 100644 --- a/libraries/metavoxels/src/MetavoxelUtil.h +++ b/libraries/metavoxels/src/MetavoxelUtil.h @@ -142,10 +142,31 @@ private: QUrl _url; }; -/// Editor for vector values. -class Vec3Editor : public QWidget { +/// Base class for Vec3Editor and QuatEditor. +class BaseVec3Editor : public QWidget { Q_OBJECT - Q_PROPERTY(glm::vec3 vector MEMBER _vector WRITE setVector NOTIFY vectorChanged USER true) + +public: + + BaseVec3Editor(QWidget* parent); + +protected slots: + + virtual void updateValue() = 0; + +protected: + + QDoubleSpinBox* createComponentBox(); + + QDoubleSpinBox* _x; + QDoubleSpinBox* _y; + QDoubleSpinBox* _z; +}; + +/// Editor for vector values. +class Vec3Editor : public BaseVec3Editor { + Q_OBJECT + Q_PROPERTY(glm::vec3 value MEMBER _value WRITE setValue NOTIFY valueChanged USER true) public: @@ -153,24 +174,45 @@ public: signals: - void vectorChanged(const glm::vec3& vector); + void valueChanged(const glm::vec3& vector); public slots: - void setVector(const glm::vec3& vector); + void setValue(const glm::vec3& vector); -private slots: +protected: - void updateVector(); + virtual void updateValue(); private: - QDoubleSpinBox* createComponentBox(); + glm::vec3 _value; +}; + +/// Editor for quaternion values. +class QuatEditor : public BaseVec3Editor { + Q_OBJECT + Q_PROPERTY(glm::quat value MEMBER _value WRITE setValue NOTIFY valueChanged USER true) + +public: - QDoubleSpinBox* _x; - QDoubleSpinBox* _y; - QDoubleSpinBox* _z; - glm::vec3 _vector; + QuatEditor(QWidget* parent); + +signals: + + void valueChanged(const glm::quat& value); + +public slots: + + void setValue(const glm::quat& value); + +protected: + + virtual void updateValue(); + +private: + + glm::quat _value; }; typedef QHash ScriptHash; From 2a58a863fd8271f7952f387f67e47b4dbfe2f128 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Mon, 7 Apr 2014 15:48:34 -0700 Subject: [PATCH 191/595] Fix for rotation placement. --- libraries/metavoxels/src/MetavoxelUtil.cpp | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/libraries/metavoxels/src/MetavoxelUtil.cpp b/libraries/metavoxels/src/MetavoxelUtil.cpp index b259c1b513..2ec1c3cb57 100644 --- a/libraries/metavoxels/src/MetavoxelUtil.cpp +++ b/libraries/metavoxels/src/MetavoxelUtil.cpp @@ -431,9 +431,9 @@ void Vec3Editor::updateValue() { } QuatEditor::QuatEditor(QWidget* parent) : BaseVec3Editor(parent) { - _x->setRange(-180.0, 180.0); - _y->setRange(-90.0, 90.0); - _z->setRange(-180.0, 180.0); + _x->setRange(-179.0, 180.0); + _y->setRange(-179.0, 180.0); + _z->setRange(-179.0, 180.0); _x->setWrapping(true); _y->setWrapping(true); @@ -441,14 +441,19 @@ QuatEditor::QuatEditor(QWidget* parent) : BaseVec3Editor(parent) { } void QuatEditor::setValue(const glm::quat& value) { - glm::vec3 eulers = glm::degrees(safeEulerAngles(_value = value)); - setComponentValue(_x, eulers.x); - setComponentValue(_y, eulers.y); - setComponentValue(_z, eulers.z); + if (_value != value) { + glm::vec3 eulers = glm::degrees(safeEulerAngles(_value = value)); + setComponentValue(_x, eulers.x); + setComponentValue(_y, eulers.y); + setComponentValue(_z, eulers.z); + } } void QuatEditor::updateValue() { - emit valueChanged(_value = glm::quat(glm::radians(glm::vec3(_x->value(), _y->value(), _z->value())))); + glm::quat value(glm::radians(glm::vec3(_x->value(), _y->value(), _z->value()))); + if (_value != value) { + emit valueChanged(_value = value); + } } ParameterizedURL::ParameterizedURL(const QUrl& url, const ScriptHash& parameters) : From 3be2319081ec99d0df4997cfb95e6eecbb2baa59 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 7 Apr 2014 16:18:23 -0700 Subject: [PATCH 192/595] Removed all the temporaryDir junk --- libraries/shared/src/ModelUploader.cpp | 77 +++++--------------------- libraries/shared/src/ModelUploader.h | 2 - 2 files changed, 14 insertions(+), 65 deletions(-) diff --git a/libraries/shared/src/ModelUploader.cpp b/libraries/shared/src/ModelUploader.cpp index 2ec199750f..cda57aeab9 100644 --- a/libraries/shared/src/ModelUploader.cpp +++ b/libraries/shared/src/ModelUploader.cpp @@ -15,7 +15,6 @@ #include #include #include -#include #include #include @@ -35,16 +34,8 @@ static const int MAX_SIZE = 10 * 1024 * 1024; // 10 MB static const int TIMEOUT = 1000; static const int MAX_CHECK = 30; -// Class providing the QObject parent system to QTemporaryDir -class TemporaryDir : public QTemporaryDir, public QObject { -public: - virtual ~TemporaryDir() { - // ensuring the entire object gets deleted by the QObject parent. - } -}; ModelUploader::ModelUploader(bool isHead) : - _zipDir(new TemporaryDir()), _lodCount(-1), _texturesCount(-1), _totalSize(0), @@ -53,7 +44,6 @@ ModelUploader::ModelUploader(bool isHead) : _dataMultiPart(new QHttpMultiPart(QHttpMultiPart::FormDataType)), _numberOfChecks(MAX_CHECK) { - _zipDir->setParent(_dataMultiPart); connect(&_timer, SIGNAL(timeout()), SLOT(checkS3())); } @@ -86,11 +76,7 @@ bool ModelUploader::zip() { qDebug() << "Reading FST file : " << QFileInfo(fst).filePath(); // Compress and copy the fst - if (!compressFile(QFileInfo(fst).filePath(), _zipDir->path() + "/" + QFileInfo(fst).fileName())) { - return false; - } - if (!addPart(_zipDir->path() + "/" + QFileInfo(fst).fileName(), - QString("fst"))) { + if (!addPart(QFileInfo(fst).filePath(), QString("fst"))) { return false; } @@ -122,10 +108,7 @@ bool ModelUploader::zip() { return false; } // Compress and copy - if (!compressFile(fbx.filePath(), _zipDir->path() + "/" + line[1])) { - return false; - } - if (!addPart(_zipDir->path() + "/" + line[1], "fbx")) { + if (!addPart(fbx.filePath(), "fbx")) { return false; } } else if (line[0] == TEXDIR_FIELD) { // Check existence @@ -152,10 +135,7 @@ bool ModelUploader::zip() { return false; } // Compress and copy - if (!compressFile(lod.filePath(), _zipDir->path() + "/" + line[1])) { - return false; - } - if (!addPart(_zipDir->path() + "/" + line[1], QString("lod%1").arg(++_lodCount))) { + if (!addPart(lod.filePath(), QString("lod%1").arg(++_lodCount))) { return false; } } @@ -189,7 +169,6 @@ void ModelUploader::send() { callbackParams.updateSlot = SLOT(uploadUpdate(qint64, qint64)); AccountManager::getInstance().authenticatedRequest(MODEL_URL, QNetworkAccessManager::PostOperation, callbackParams, QByteArray(), _dataMultiPart); - _zipDir = NULL; _dataMultiPart = NULL; qDebug() << "Sending model..."; _progressDialog = new QDialog(); @@ -287,11 +266,7 @@ bool ModelUploader::addTextures(const QFileInfo& texdir) { foreach (QFileInfo info, list) { if (info.isFile()) { // Compress and copy - if (!compressFile(info.filePath(), _zipDir->path() + "/" + info.fileName())) { - return false; - } - if (!addPart(_zipDir->path() + "/" + info.fileName(), - QString("texture%1").arg(++_texturesCount))) { + if (!addPart(info.filePath(), QString("texture%1").arg(++_texturesCount))) { return false; } } else if (info.isDir()) { @@ -304,54 +279,30 @@ bool ModelUploader::addTextures(const QFileInfo& texdir) { return true; } -bool ModelUploader::compressFile(const QString &inFileName, const QString &outFileName) { - QFile inFile(inFileName); - inFile.open(QIODevice::ReadOnly); - QByteArray buffer = inFile.readAll(); - - QFile outFile(outFileName); - if (!outFile.open(QIODevice::WriteOnly)) { - QDir(_zipDir->path()).mkpath(QFileInfo(outFileName).path()); - if (!outFile.open(QIODevice::WriteOnly)) { - QMessageBox::warning(NULL, - QString("ModelUploader::compressFile()"), - QString("Could not compress %1").arg(inFileName), - QMessageBox::Ok); - qDebug() << "[Warning] " << QString("Could not compress %1").arg(inFileName); - return false; - } - } - QDataStream out(&outFile); - out << qCompress(buffer); - - return true; -} - - bool ModelUploader::addPart(const QString &path, const QString& name) { - QFile* file = new QFile(path); - if (!file->open(QIODevice::ReadOnly)) { + QFile file(path); + if (!file.open(QIODevice::ReadOnly)) { QMessageBox::warning(NULL, QString("ModelUploader::addPart()"), QString("Could not open %1").arg(path), QMessageBox::Ok); qDebug() << "[Warning] " << QString("Could not open %1").arg(path); - delete file; return false; } + QByteArray buffer = qCompress(file.readAll()); + buffer.remove(0, 4); QHttpPart part; - part.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data;" + part.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data;" " name=\"" + name.toUtf8() + "\";" - " filename=\"" + QFileInfo(*file).fileName().toUtf8() + "\""); - part.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream"); - part.setBodyDevice(file); + " filename=\"" + QFileInfo(file).fileName().toUtf8() + "\"")); + part.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/octet-stream")); + part.setBody(buffer); _dataMultiPart->append(part); - file->setParent(_dataMultiPart); - qDebug() << "File " << QFileInfo(*file).fileName() << " added to model."; - _totalSize += file->size(); + qDebug() << "File " << QFileInfo(file).fileName() << " added to model."; + _totalSize += file.size(); if (_totalSize > MAX_SIZE) { QMessageBox::warning(NULL, QString("ModelUploader::zip()"), diff --git a/libraries/shared/src/ModelUploader.h b/libraries/shared/src/ModelUploader.h index 066a577e57..0e62ab8705 100644 --- a/libraries/shared/src/ModelUploader.h +++ b/libraries/shared/src/ModelUploader.h @@ -38,7 +38,6 @@ private slots: private: QString _url; - TemporaryDir* _zipDir; int _lodCount; int _texturesCount; int _totalSize; @@ -57,7 +56,6 @@ private: bool zip(); bool addTextures(const QFileInfo& texdir); - bool compressFile(const QString& inFileName, const QString& outFileName); bool addPart(const QString& path, const QString& name); }; From bf0eb69e2c9733b500ecff3d8d03a706e58b98e5 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Mon, 7 Apr 2014 16:28:55 -0700 Subject: [PATCH 193/595] fix for sometimes slow avatar --- interface/src/avatar/Avatar.cpp | 4 ++-- interface/src/avatar/Avatar.h | 1 - interface/src/avatar/MyAvatar.cpp | 18 ++++++++---------- interface/src/avatar/MyAvatar.h | 1 - 4 files changed, 10 insertions(+), 14 deletions(-) diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 899514d1c1..75b9db1581 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -46,7 +46,6 @@ Avatar::Avatar() : _mode(AVATAR_MODE_STANDING), _velocity(0.0f, 0.0f, 0.0f), _thrust(0.0f, 0.0f, 0.0f), - _speed(0.0f), _leanScale(0.5f), _scale(1.0f), _worldUpDirection(DEFAULT_UP_DIRECTION), @@ -137,7 +136,8 @@ void Avatar::simulate(float deltaTime) { } // use speed and angular velocity to determine walking vs. standing - if (_speed + fabs(_bodyYawDelta) > 0.2) { + float speed = glm::length(_velocity); + if (speed + fabs(_bodyYawDelta) > 0.2) { _mode = AVATAR_MODE_WALKING; } else { _mode = AVATAR_MODE_INTERACTING; diff --git a/interface/src/avatar/Avatar.h b/interface/src/avatar/Avatar.h index f6d5669859..a6cefedef8 100755 --- a/interface/src/avatar/Avatar.h +++ b/interface/src/avatar/Avatar.h @@ -160,7 +160,6 @@ protected: AvatarMode _mode; glm::vec3 _velocity; glm::vec3 _thrust; - float _speed; float _leanScale; float _scale; glm::vec3 _worldUpDirection; diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 1ff93794c5..05636166e2 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -169,9 +169,6 @@ void MyAvatar::simulate(float deltaTime) { // Collect thrust forces from keyboard and devices updateThrust(deltaTime); - // calculate speed - _speed = glm::length(_velocity); - // update the movement of the hand and process handshaking with other avatars... updateHandMovementAndTouching(deltaTime); @@ -203,9 +200,9 @@ void MyAvatar::simulate(float deltaTime) { if (fabs(_bodyRollDelta) < MINIMUM_ROTATION_RATE) { _bodyRollDelta = 0.f; } if (fabs(_bodyPitchDelta) < MINIMUM_ROTATION_RATE) { _bodyPitchDelta = 0.f; } - const float MAX_STATIC_FRICTION_VELOCITY = 0.5f; + const float MAX_STATIC_FRICTION_SPEED = 0.5f; const float STATIC_FRICTION_STRENGTH = _scale * 20.f; - applyStaticFriction(deltaTime, _velocity, MAX_STATIC_FRICTION_VELOCITY, STATIC_FRICTION_STRENGTH); + applyStaticFriction(deltaTime, _velocity, MAX_STATIC_FRICTION_SPEED, STATIC_FRICTION_STRENGTH); // Damp avatar velocity const float LINEAR_DAMPING_STRENGTH = 0.5f; @@ -230,7 +227,8 @@ void MyAvatar::simulate(float deltaTime) { const float WALKING_SPEED_THRESHOLD = 0.2f; // use speed and angular velocity to determine walking vs. standing - if (_speed + fabs(_bodyYawDelta) > WALKING_SPEED_THRESHOLD) { + float speed = glm::length(_velocity); + if (speed + fabs(_bodyYawDelta) > WALKING_SPEED_THRESHOLD) { _mode = AVATAR_MODE_WALKING; } else { _mode = AVATAR_MODE_INTERACTING; @@ -238,7 +236,7 @@ void MyAvatar::simulate(float deltaTime) { // update moving flag based on speed const float MOVING_SPEED_THRESHOLD = 0.01f; - _moving = _speed > MOVING_SPEED_THRESHOLD; + _moving = speed > MOVING_SPEED_THRESHOLD; // If a move target is set, update position explicitly const float MOVE_FINISHED_TOLERANCE = 0.1f; @@ -681,7 +679,6 @@ void MyAvatar::updateThrust(float deltaTime) { if (_driveKeys[FWD] || _driveKeys[BACK] || _driveKeys[RIGHT] || _driveKeys[LEFT] || _driveKeys[UP] || _driveKeys[DOWN]) { const float THRUST_INCREASE_RATE = 1.05f; const float MAX_THRUST_MULTIPLIER = 75.0f; - //printf("m = %.3f\n", _thrustMultiplier); _thrustMultiplier *= 1.f + deltaTime * THRUST_INCREASE_RATE; if (_thrustMultiplier > MAX_THRUST_MULTIPLIER) { _thrustMultiplier = MAX_THRUST_MULTIPLIER; @@ -703,11 +700,12 @@ void MyAvatar::updateThrust(float deltaTime) { if ((glm::length(_thrust) == 0.0f) && _isThrustOn && (glm::length(_velocity) > MIN_SPEED_BRAKE_VELOCITY)) { _speedBrakes = true; } + _isThrustOn = (glm::length(_thrust) > EPSILON); - if (_speedBrakes && (glm::length(_velocity) < MIN_SPEED_BRAKE_VELOCITY)) { + if (_isThrustOn || (_speedBrakes && (glm::length(_velocity) < MIN_SPEED_BRAKE_VELOCITY))) { _speedBrakes = false; } - _isThrustOn = (glm::length(_thrust) > EPSILON); + } void MyAvatar::updateHandMovementAndTouching(float deltaTime) { diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index 5c940f0f50..2125b126b3 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -50,7 +50,6 @@ public: void setShouldRenderLocally(bool shouldRender) { _shouldRender = shouldRender; } // getters - float getSpeed() const { return _speed; } AvatarMode getMode() const { return _mode; } float getLeanScale() const { return _leanScale; } float getElapsedTimeStopped() const { return _elapsedTimeStopped; } From d213cd784034285337e137b6575166088ef7a803 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 7 Apr 2014 17:10:15 -0700 Subject: [PATCH 194/595] More work on Undo/Redo --- examples/editVoxels.js | 1 - interface/src/Application.cpp | 1 + interface/src/Menu.cpp | 11 +-- libraries/voxels/src/VoxelTree.h | 7 +- libraries/voxels/src/VoxelTreeCommands.cpp | 64 +++++++++++++++ libraries/voxels/src/VoxelTreeCommands.h | 46 +++++++++++ .../voxels/src/VoxelsScriptingInterface.cpp | 77 +++++++++++++++---- .../voxels/src/VoxelsScriptingInterface.h | 4 +- 8 files changed, 190 insertions(+), 21 deletions(-) create mode 100644 libraries/voxels/src/VoxelTreeCommands.cpp create mode 100644 libraries/voxels/src/VoxelTreeCommands.h diff --git a/examples/editVoxels.js b/examples/editVoxels.js index 4922caf0d8..0f9ed25d2c 100644 --- a/examples/editVoxels.js +++ b/examples/editVoxels.js @@ -911,7 +911,6 @@ function mousePressEvent(event) { } voxelDetails = calculateVoxelFromIntersection(intersection,"add"); - Voxels.eraseVoxel(voxelDetails.x, voxelDetails.y, voxelDetails.z, voxelDetails.s); Voxels.setVoxel(voxelDetails.x, voxelDetails.y, voxelDetails.z, voxelDetails.s, newColor.red, newColor.green, newColor.blue); lastVoxelPosition = { x: voxelDetails.x, y: voxelDetails.y, z: voxelDetails.z }; diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index d54cceb245..68b2ae9a24 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3274,6 +3274,7 @@ void Application::loadScript(const QString& scriptName) { // we can use the same ones from the application. scriptEngine->getVoxelsScriptingInterface()->setPacketSender(&_voxelEditSender); scriptEngine->getVoxelsScriptingInterface()->setVoxelTree(_voxels.getTree()); + scriptEngine->getVoxelsScriptingInterface()->setUndoStack(&_undoStack); scriptEngine->getParticlesScriptingInterface()->setPacketSender(&_particleEditSender); scriptEngine->getParticlesScriptingInterface()->setParticleTree(_particles.getTree()); diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index e090f4d046..b9aa0ea91c 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -161,14 +161,15 @@ Menu::Menu() : QMenu* editMenu = addMenu("Edit"); + QUndoStack* undoStack = Application::getInstance()->getUndoStack(); QAction* undoAction = undoStack->createUndoAction(editMenu); + undoAction->setShortcut(Qt::CTRL | Qt::Key_Z); + addActionToQMenuAndActionHash(editMenu, undoAction); + QAction* redoAction = undoStack->createRedoAction(editMenu); - - addActionToQMenuAndActionHash(editMenu, - undoAction); - addActionToQMenuAndActionHash(editMenu, - redoAction); + redoAction->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_Z); + addActionToQMenuAndActionHash(editMenu, redoAction); addActionToQMenuAndActionHash(editMenu, MenuOption::Preferences, diff --git a/libraries/voxels/src/VoxelTree.h b/libraries/voxels/src/VoxelTree.h index 2079ab91b2..3d1b699a45 100644 --- a/libraries/voxels/src/VoxelTree.h +++ b/libraries/voxels/src/VoxelTree.h @@ -1,4 +1,4 @@ -// + // // VoxelTree.h // hifi // @@ -14,6 +14,7 @@ #include "VoxelTreeElement.h" #include "VoxelEditPacketSender.h" +class QUndoStack; class ReadCodeColorBufferToTreeArgs; class VoxelTree : public Octree { @@ -44,6 +45,8 @@ public: virtual bool handlesEditPacketType(PacketType packetType) const; virtual int processEditPacketData(PacketType packetType, const unsigned char* packetData, int packetLength, const unsigned char* editData, int maxLength, const SharedNodePointer& node); + + void setUndoStack(QUndoStack* undoStack) { _undoStack = undoStack; } private: // helper functions for nudgeSubTree @@ -52,6 +55,8 @@ private: void nudgeLeaf(VoxelTreeElement* element, void* extraData); void chunkifyLeaf(VoxelTreeElement* element); void readCodeColorBufferToTreeRecursion(VoxelTreeElement* node, ReadCodeColorBufferToTreeArgs& args); + + QUndoStack* _undoStack; }; #endif /* defined(__hifi__VoxelTree__) */ diff --git a/libraries/voxels/src/VoxelTreeCommands.cpp b/libraries/voxels/src/VoxelTreeCommands.cpp new file mode 100644 index 0000000000..a557137367 --- /dev/null +++ b/libraries/voxels/src/VoxelTreeCommands.cpp @@ -0,0 +1,64 @@ +// +// VoxelTreeCommands.cpp +// hifi +// +// Created by Clement on 4/4/14. +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// +// + +#include "VoxelTree.h" + +#include "VoxelTreeCommands.h" + +AddVoxelCommand::AddVoxelCommand(VoxelTree* tree, VoxelDetail& voxel, VoxelEditPacketSender* packetSender, QUndoCommand* parent) : +QUndoCommand("Add Voxel", parent), +_tree(tree), +_packetSender(packetSender), +_voxel(voxel) +{ +} + +void AddVoxelCommand::redo() { + if (_tree) { + _tree->createVoxel(_voxel.x, _voxel.y, _voxel.z, _voxel.s, _voxel.red, _voxel.green, _voxel.blue); + } + if (_packetSender) { + _packetSender->queueVoxelEditMessages(PacketTypeVoxelSet, 1, &_voxel); + } +} + +void AddVoxelCommand::undo() { + if (_tree) { + _tree->deleteVoxelAt(_voxel.x, _voxel.y, _voxel.z, _voxel.s); + } + if (_packetSender) { + _packetSender->queueVoxelEditMessages(PacketTypeVoxelErase, 1, &_voxel); + } +} + +DeleteVoxelCommand::DeleteVoxelCommand(VoxelTree* tree, VoxelDetail& voxel, VoxelEditPacketSender* packetSender, QUndoCommand* parent) : +QUndoCommand("Delete Voxel", parent), +_tree(tree), +_packetSender(packetSender), +_voxel(voxel) +{ +} + +void DeleteVoxelCommand::redo() { + if (_tree) { + _tree->deleteVoxelAt(_voxel.x, _voxel.y, _voxel.z, _voxel.s); + } + if (_packetSender) { + _packetSender->queueVoxelEditMessages(PacketTypeVoxelErase, 1, &_voxel); + } +} + +void DeleteVoxelCommand::undo() { + if (_tree) { + _tree->createVoxel(_voxel.x, _voxel.y, _voxel.z, _voxel.s, _voxel.red, _voxel.green, _voxel.blue); + } + if (_packetSender) { + _packetSender->queueVoxelEditMessages(PacketTypeVoxelSet, 1, &_voxel); + } +} \ No newline at end of file diff --git a/libraries/voxels/src/VoxelTreeCommands.h b/libraries/voxels/src/VoxelTreeCommands.h new file mode 100644 index 0000000000..ca7700417c --- /dev/null +++ b/libraries/voxels/src/VoxelTreeCommands.h @@ -0,0 +1,46 @@ +// +// VoxelTreeCommands.h +// hifi +// +// Created by Clement on 4/4/14. +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// + +#ifndef __hifi__VoxelTreeCommands__ +#define __hifi__VoxelTreeCommands__ + +#include +#include + +#include "VoxelDetail.h" +#include "VoxelEditPacketSender.h" + +class VoxelTree; + +class AddVoxelCommand : public QUndoCommand { +public: + AddVoxelCommand(VoxelTree* tree, VoxelDetail& voxel, VoxelEditPacketSender* packetSender = NULL, QUndoCommand* parent = NULL); + + virtual void redo(); + virtual void undo(); + +private: + VoxelTree* _tree; + VoxelEditPacketSender* _packetSender; + VoxelDetail _voxel; +}; + +class DeleteVoxelCommand : public QUndoCommand { +public: + DeleteVoxelCommand(VoxelTree* tree, VoxelDetail& voxel, VoxelEditPacketSender* packetSender = NULL, QUndoCommand* parent = NULL); + + virtual void redo(); + virtual void undo(); + +private: + VoxelTree* _tree; + VoxelEditPacketSender* _packetSender; + VoxelDetail _voxel; +}; + +#endif /* defined(__hifi__VoxelTreeCommands__) */ diff --git a/libraries/voxels/src/VoxelsScriptingInterface.cpp b/libraries/voxels/src/VoxelsScriptingInterface.cpp index 2aecb2d457..59e4662bed 100644 --- a/libraries/voxels/src/VoxelsScriptingInterface.cpp +++ b/libraries/voxels/src/VoxelsScriptingInterface.cpp @@ -6,6 +6,8 @@ // Copyright (c) 2013 HighFidelity, Inc. All rights reserved. // +#include "VoxelTreeCommands.h" + #include "VoxelsScriptingInterface.h" void VoxelsScriptingInterface::queueVoxelAdd(PacketType addPacketType, VoxelDetail& addVoxelDetails) { @@ -37,17 +39,24 @@ VoxelDetail VoxelsScriptingInterface::getVoxelAt(float x, float y, float z, floa } void VoxelsScriptingInterface::setVoxelNonDestructive(float x, float y, float z, float scale, - uchar red, uchar green, uchar blue) { + uchar red, uchar green, uchar blue) { // setup a VoxelDetail struct with the data - VoxelDetail addVoxelDetail = {x / (float)TREE_SCALE, y / (float)TREE_SCALE, z / (float)TREE_SCALE, + VoxelDetail addVoxelDetail = {x / (float)TREE_SCALE, y / (float)TREE_SCALE, z / (float)TREE_SCALE, scale / (float)TREE_SCALE, red, green, blue}; - // queue the add packet - queueVoxelAdd(PacketTypeVoxelSet, addVoxelDetail); // handle the local tree also... if (_tree) { - _tree->createVoxel(addVoxelDetail.x, addVoxelDetail.y, addVoxelDetail.z, addVoxelDetail.s, red, green, blue, false); + if (_undoStack) { + AddVoxelCommand* command = new AddVoxelCommand(_tree, + addVoxelDetail, + getVoxelPacketSender()); + _undoStack->push(command); + } else { + // queue the add packet + queueVoxelAdd(PacketTypeVoxelSet, addVoxelDetail); + _tree->createVoxel(addVoxelDetail.x, addVoxelDetail.y, addVoxelDetail.z, addVoxelDetail.s, red, green, blue, false); + } } } @@ -57,26 +66,68 @@ void VoxelsScriptingInterface::setVoxel(float x, float y, float z, float scale, VoxelDetail addVoxelDetail = {x / (float)TREE_SCALE, y / (float)TREE_SCALE, z / (float)TREE_SCALE, scale / (float)TREE_SCALE, red, green, blue}; - // queue the destructive add - queueVoxelAdd(PacketTypeVoxelSetDestructive, addVoxelDetail); // handle the local tree also... if (_tree) { - _tree->createVoxel(addVoxelDetail.x, addVoxelDetail.y, addVoxelDetail.z, addVoxelDetail.s, red, green, blue, true); + if (_undoStack) { + AddVoxelCommand* addCommand = new AddVoxelCommand(_tree, + addVoxelDetail, + getVoxelPacketSender()); + + VoxelTreeElement* deleteVoxelElement = _tree->getVoxelAt(addVoxelDetail.x, addVoxelDetail.y, addVoxelDetail.z, addVoxelDetail.s); + if (deleteVoxelElement) { + nodeColor color; + memcpy(&color, &deleteVoxelElement->getColor(), sizeof(nodeColor)); + VoxelDetail deleteVoxelDetail = {addVoxelDetail.x, + addVoxelDetail.y, + addVoxelDetail.z, + addVoxelDetail.s, + color[0], + color[1], + color[2]}; + DeleteVoxelCommand* delCommand = new DeleteVoxelCommand(_tree, + deleteVoxelDetail, + getVoxelPacketSender()); + _undoStack->beginMacro(addCommand->text()); + qDebug() << "Macro"; + _undoStack->push(delCommand); + _undoStack->push(addCommand); + _undoStack->endMacro(); + } else { + _undoStack->push(addCommand); + } + } else { + // queue the destructive add + queueVoxelAdd(PacketTypeVoxelSetDestructive, addVoxelDetail); + _tree->createVoxel(addVoxelDetail.x, addVoxelDetail.y, addVoxelDetail.z, addVoxelDetail.s, red, green, blue, true); + } } } void VoxelsScriptingInterface::eraseVoxel(float x, float y, float z, float scale) { - // setup a VoxelDetail struct with data - VoxelDetail deleteVoxelDetail = {x / (float)TREE_SCALE, y / (float)TREE_SCALE, z / (float)TREE_SCALE, - scale / (float)TREE_SCALE, 0, 0, 0}; + VoxelDetail deleteVoxelDetail = {x / (float)TREE_SCALE, y / (float)TREE_SCALE, z / (float)TREE_SCALE, + scale / (float)TREE_SCALE}; - getVoxelPacketSender()->queueVoxelEditMessages(PacketTypeVoxelErase, 1, &deleteVoxelDetail); // handle the local tree also... if (_tree) { - _tree->deleteVoxelAt(deleteVoxelDetail.x, deleteVoxelDetail.y, deleteVoxelDetail.z, deleteVoxelDetail.s); + VoxelTreeElement* deleteVoxelElement = _tree->getVoxelAt(deleteVoxelDetail.x, deleteVoxelDetail.y, deleteVoxelDetail.z, deleteVoxelDetail.s); + if (deleteVoxelElement) { + deleteVoxelDetail.red = deleteVoxelElement->getColor()[0]; + deleteVoxelDetail.green = deleteVoxelElement->getColor()[1]; + deleteVoxelDetail.blue = deleteVoxelElement->getColor()[2]; + } + + if (_undoStack) { + DeleteVoxelCommand* command = new DeleteVoxelCommand(_tree, + deleteVoxelDetail, + getVoxelPacketSender()); + _undoStack->push(command); + } else { + getVoxelPacketSender()->queueVoxelEditMessages(PacketTypeVoxelErase, 1, &deleteVoxelDetail); + _tree->deleteVoxelAt(deleteVoxelDetail.x, deleteVoxelDetail.y, deleteVoxelDetail.z, deleteVoxelDetail.s); + } } } diff --git a/libraries/voxels/src/VoxelsScriptingInterface.h b/libraries/voxels/src/VoxelsScriptingInterface.h index d07d2a785c..339e527ebc 100644 --- a/libraries/voxels/src/VoxelsScriptingInterface.h +++ b/libraries/voxels/src/VoxelsScriptingInterface.h @@ -22,12 +22,13 @@ class VoxelsScriptingInterface : public OctreeScriptingInterface { Q_OBJECT public: - VoxelsScriptingInterface() : _tree(NULL) {}; + VoxelsScriptingInterface() : _tree(NULL), _undoStack(NULL) {}; VoxelEditPacketSender* getVoxelPacketSender() { return (VoxelEditPacketSender*)getPacketSender(); } virtual NodeType_t getServerNodeType() const { return NodeType::VoxelServer; } virtual OctreeEditPacketSender* createPacketSender() { return new VoxelEditPacketSender(); } void setVoxelTree(VoxelTree* tree) { _tree = tree; } + void setUndoStack(QUndoStack* undoStack) { _undoStack = undoStack; } public slots: @@ -79,6 +80,7 @@ public slots: private: void queueVoxelAdd(PacketType addPacketType, VoxelDetail& addVoxelDetails); VoxelTree* _tree; + QUndoStack* _undoStack; }; #endif /* defined(__hifi__VoxelsScriptingInterface__) */ From 46f0e78039529fa6670a9d00fb0cbf7df1f4dfdf Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 7 Apr 2014 17:28:03 -0700 Subject: [PATCH 195/595] Erased deprecated code --- libraries/voxels/src/VoxelTree.h | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/libraries/voxels/src/VoxelTree.h b/libraries/voxels/src/VoxelTree.h index 3d1b699a45..2079ab91b2 100644 --- a/libraries/voxels/src/VoxelTree.h +++ b/libraries/voxels/src/VoxelTree.h @@ -1,4 +1,4 @@ - // +// // VoxelTree.h // hifi // @@ -14,7 +14,6 @@ #include "VoxelTreeElement.h" #include "VoxelEditPacketSender.h" -class QUndoStack; class ReadCodeColorBufferToTreeArgs; class VoxelTree : public Octree { @@ -45,8 +44,6 @@ public: virtual bool handlesEditPacketType(PacketType packetType) const; virtual int processEditPacketData(PacketType packetType, const unsigned char* packetData, int packetLength, const unsigned char* editData, int maxLength, const SharedNodePointer& node); - - void setUndoStack(QUndoStack* undoStack) { _undoStack = undoStack; } private: // helper functions for nudgeSubTree @@ -55,8 +52,6 @@ private: void nudgeLeaf(VoxelTreeElement* element, void* extraData); void chunkifyLeaf(VoxelTreeElement* element); void readCodeColorBufferToTreeRecursion(VoxelTreeElement* node, ReadCodeColorBufferToTreeArgs& args); - - QUndoStack* _undoStack; }; #endif /* defined(__hifi__VoxelTree__) */ From fa05a482707a049c53ac554aede2b7190579b87c Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Mon, 7 Apr 2014 17:55:36 -0700 Subject: [PATCH 196/595] Provide a means of supplying the joint mappings in the FST file so that agent scripts can address joints by name. Closes #2526. --- examples/crazylegs.js | 7 +++-- interface/src/avatar/Avatar.cpp | 4 +++ interface/src/avatar/Avatar.h | 2 ++ libraries/avatars/src/AvatarData.cpp | 46 ++++++++++++++++++++++++++++ libraries/avatars/src/AvatarData.h | 12 ++++++-- 5 files changed, 67 insertions(+), 4 deletions(-) diff --git a/examples/crazylegs.js b/examples/crazylegs.js index 099387e000..19a171dbdf 100644 --- a/examples/crazylegs.js +++ b/examples/crazylegs.js @@ -12,9 +12,12 @@ var AMPLITUDE = 45.0; var cumulativeTime = 0.0; -print("Joint List:"); +print("# Joint list start"); var jointList = MyAvatar.getJointNames(); -print(jointList); +for (var i = 0; i < jointList.length; i++) { + print("jointIndex = " + jointList[i] + " = " + i); +} +print("# Joint list end"); Script.update.connect(function(deltaTime) { cumulativeTime += deltaTime; diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 899514d1c1..7a55d4d534 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -331,6 +331,10 @@ void Avatar::renderBody(RenderMode renderMode) { getHand()->render(false); } +void Avatar::updateJointMappings() { + // no-op; joint mappings come from skeleton model +} + void Avatar::renderBillboard() { if (_billboard.isEmpty()) { return; diff --git a/interface/src/avatar/Avatar.h b/interface/src/avatar/Avatar.h index f6d5669859..e0d46c8624 100755 --- a/interface/src/avatar/Avatar.h +++ b/interface/src/avatar/Avatar.h @@ -187,6 +187,8 @@ protected: void renderDisplayName(); virtual void renderBody(RenderMode renderMode); + virtual void updateJointMappings(); + private: bool _initialized; diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index 930e3f7350..e84636b5a4 100644 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -639,6 +639,8 @@ void AvatarData::setSkeletonModelURL(const QUrl& skeletonModelURL) { _skeletonModelURL = skeletonModelURL.isEmpty() ? DEFAULT_BODY_MODEL_URL : skeletonModelURL; qDebug() << "Changing skeleton model for avatar to" << _skeletonModelURL.toString(); + + updateJointMappings(); } void AvatarData::setDisplayName(const QString& displayName) { @@ -673,6 +675,40 @@ void AvatarData::setBillboardFromURL(const QString &billboardURL) { void AvatarData::setBillboardFromNetworkReply() { QNetworkReply* networkReply = reinterpret_cast(sender()); setBillboard(networkReply->readAll()); + networkReply->deleteLater(); +} + +void AvatarData::setJointMappingsFromNetworkReply() { + QNetworkReply* networkReply = static_cast(sender()); + + QByteArray line; + while (!(line = networkReply->readLine()).isEmpty()) { + if (!(line = line.trimmed()).startsWith("jointIndex")) { + continue; + } + int jointNameIndex = line.indexOf('=') + 1; + if (jointNameIndex == 0) { + continue; + } + int secondSeparatorIndex = line.indexOf('=', jointNameIndex); + if (secondSeparatorIndex == -1) { + continue; + } + QString jointName = line.mid(jointNameIndex, secondSeparatorIndex - jointNameIndex).trimmed(); + bool ok; + int jointIndex = line.mid(secondSeparatorIndex + 1).trimmed().toInt(&ok); + if (ok) { + while (_jointNames.size() < jointIndex + 1) { + _jointNames.append(QString()); + } + _jointNames[jointIndex] = jointName; + } + } + for (int i = 0; i < _jointNames.size(); i++) { + _jointIndices.insert(_jointNames.at(i), i + 1); + } + + networkReply->deleteLater(); } void AvatarData::setClampedTargetScale(float targetScale) { @@ -705,3 +741,13 @@ void AvatarData::sendBillboardPacket() { NodeList::getInstance()->broadcastToNodes(billboardPacket, NodeSet() << NodeType::AvatarMixer); } } + +void AvatarData::updateJointMappings() { + _jointIndices.clear(); + _jointNames.clear(); + + if (networkAccessManager && _skeletonModelURL.fileName().toLower().endsWith(".fst")) { + QNetworkReply* networkReply = networkAccessManager->get(QNetworkRequest(_skeletonModelURL)); + connect(networkReply, SIGNAL(finished()), this, SLOT(setJointMappingsFromNetworkReply())); + } +} diff --git a/libraries/avatars/src/AvatarData.h b/libraries/avatars/src/AvatarData.h index 221bbd0428..cf645855e8 100755 --- a/libraries/avatars/src/AvatarData.h +++ b/libraries/avatars/src/AvatarData.h @@ -30,6 +30,7 @@ typedef unsigned long long quint64; #include #include +#include #include #include #include @@ -160,9 +161,9 @@ public: Q_INVOKABLE glm::quat getJointRotation(const QString& name) const; /// Returns the index of the joint with the specified name, or -1 if not found/unknown. - Q_INVOKABLE virtual int getJointIndex(const QString& name) const { return -1; } + Q_INVOKABLE virtual int getJointIndex(const QString& name) const { return _jointIndices.value(name) - 1; } - Q_INVOKABLE virtual QStringList getJointNames() const { return QStringList(); } + Q_INVOKABLE virtual QStringList getJointNames() const { return _jointNames; } // key state void setKeyState(KeyState s) { _keyState = s; } @@ -217,6 +218,7 @@ public slots: void sendIdentityPacket(); void sendBillboardPacket(); void setBillboardFromNetworkReply(); + void setJointMappingsFromNetworkReply(); protected: glm::vec3 _position; glm::vec3 _handPosition; @@ -258,10 +260,16 @@ protected: QByteArray _billboard; QString _billboardURL; + QHash _jointIndices; ///< 1-based, since zero is returned for missing keys + QStringList _jointNames; ///< in order of depth-first traversal + static QNetworkAccessManager* networkAccessManager; quint64 _errorLogExpiry; ///< time in future when to log an error + /// Loads the joint indices, names from the FST file (if any) + virtual void updateJointMappings(); + private: // privatize the copy constructor and assignment operator so they cannot be called AvatarData(const AvatarData&); From 5a610090998ced77554c7fbdd506a147f655889f Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Tue, 8 Apr 2014 10:19:39 -0700 Subject: [PATCH 197/595] Add metavoxel bandwidth to details. --- interface/src/MetavoxelSystem.cpp | 2 ++ interface/src/ui/BandwidthMeter.cpp | 3 ++- interface/src/ui/BandwidthMeter.h | 4 ++-- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index 7eb046756b..6b4d817f7f 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -295,11 +295,13 @@ void MetavoxelClient::simulate(float deltaTime) { int MetavoxelClient::parseData(const QByteArray& packet) { // process through sequencer QMetaObject::invokeMethod(&_sequencer, "receivedDatagram", Q_ARG(const QByteArray&, packet)); + Application::getInstance()->getBandwidthMeter()->inputStream(BandwidthMeter::METAVOXELS).updateValue(packet.size()); return packet.size(); } void MetavoxelClient::sendData(const QByteArray& data) { NodeList::getInstance()->writeDatagram(data, _node); + Application::getInstance()->getBandwidthMeter()->outputStream(BandwidthMeter::METAVOXELS).updateValue(data.size()); } void MetavoxelClient::readPacket(Bitstream& in) { diff --git a/interface/src/ui/BandwidthMeter.cpp b/interface/src/ui/BandwidthMeter.cpp index 64ff74b846..962e8a857b 100644 --- a/interface/src/ui/BandwidthMeter.cpp +++ b/interface/src/ui/BandwidthMeter.cpp @@ -42,7 +42,8 @@ namespace { // .cpp-local BandwidthMeter::ChannelInfo BandwidthMeter::_CHANNELS[] = { { "Audio" , "Kbps", 8000.0 / 1024.0, 0x33cc99ff }, { "Avatars" , "Kbps", 8000.0 / 1024.0, 0xffef40c0 }, - { "Voxels" , "Kbps", 8000.0 / 1024.0, 0xd0d0d0a0 } + { "Voxels" , "Kbps", 8000.0 / 1024.0, 0xd0d0d0a0 }, + { "Metavoxels", "Kbps", 8000.0 / 1024.0, 0xd0d0d0a0 } }; BandwidthMeter::BandwidthMeter() : diff --git a/interface/src/ui/BandwidthMeter.h b/interface/src/ui/BandwidthMeter.h index 5879b1546d..c1577da8e4 100644 --- a/interface/src/ui/BandwidthMeter.h +++ b/interface/src/ui/BandwidthMeter.h @@ -30,11 +30,11 @@ public: bool isWithinArea(int x, int y, int screenWidth, int screenHeight); // Number of channels / streams. - static size_t const N_CHANNELS = 3; + static size_t const N_CHANNELS = 4; static size_t const N_STREAMS = N_CHANNELS * 2; // Channel usage. - enum ChannelIndex { AUDIO, AVATARS, VOXELS }; + enum ChannelIndex { AUDIO, AVATARS, VOXELS, METAVOXELS }; // Meta information held for a communication channel (bidirectional). struct ChannelInfo { From ee5ebae89e037f27dcf8cda4d212769d9c3020cc Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 8 Apr 2014 10:22:50 -0700 Subject: [PATCH 198/595] Code review --- libraries/voxels/src/VoxelTreeCommands.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/libraries/voxels/src/VoxelTreeCommands.cpp b/libraries/voxels/src/VoxelTreeCommands.cpp index a557137367..d919f0e150 100644 --- a/libraries/voxels/src/VoxelTreeCommands.cpp +++ b/libraries/voxels/src/VoxelTreeCommands.cpp @@ -12,10 +12,10 @@ #include "VoxelTreeCommands.h" AddVoxelCommand::AddVoxelCommand(VoxelTree* tree, VoxelDetail& voxel, VoxelEditPacketSender* packetSender, QUndoCommand* parent) : -QUndoCommand("Add Voxel", parent), -_tree(tree), -_packetSender(packetSender), -_voxel(voxel) + QUndoCommand("Add Voxel", parent), + _tree(tree), + _packetSender(packetSender), + _voxel(voxel) { } @@ -38,10 +38,10 @@ void AddVoxelCommand::undo() { } DeleteVoxelCommand::DeleteVoxelCommand(VoxelTree* tree, VoxelDetail& voxel, VoxelEditPacketSender* packetSender, QUndoCommand* parent) : -QUndoCommand("Delete Voxel", parent), -_tree(tree), -_packetSender(packetSender), -_voxel(voxel) + QUndoCommand("Delete Voxel", parent), + _tree(tree), + _packetSender(packetSender), + _voxel(voxel) { } From e1a1ff39887152e21aea3f394eb64cc51f3d56c0 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 8 Apr 2014 10:32:49 -0700 Subject: [PATCH 199/595] Code review --- libraries/shared/src/AccountManager.cpp | 15 ++++++++++++--- libraries/shared/src/AccountManager.h | 5 +---- libraries/shared/src/ModelUploader.cpp | 7 ++++++- 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/libraries/shared/src/AccountManager.cpp b/libraries/shared/src/AccountManager.cpp index fe361ba751..d284640924 100644 --- a/libraries/shared/src/AccountManager.cpp +++ b/libraries/shared/src/AccountManager.cpp @@ -34,6 +34,16 @@ Q_DECLARE_METATYPE(JSONCallbackParameters) const QString ACCOUNTS_GROUP = "accounts"; +JSONCallbackParameters::JSONCallbackParameters() : + jsonCallbackReceiver(NULL), + jsonCallbackMethod(), + errorCallbackReceiver(NULL), + errorCallbackMethod(), + updateReciever(NULL), + updateSlot() +{ +} + AccountManager::AccountManager() : _authURL(), _networkAccessManager(NULL), @@ -178,8 +188,7 @@ void AccountManager::invokedRequest(const QString& path, QNetworkAccessManager:: } // if we ended up firing of a request, hook up to it now - connect(networkReply, SIGNAL(finished()), - SLOT(processReply())); + connect(networkReply, SIGNAL(finished()), SLOT(processReply())); } } } @@ -208,7 +217,7 @@ void AccountManager::passSuccessToCallback(QNetworkReply* requestReply) { // remove the related reply-callback group from the map _pendingCallbackMap.remove(requestReply); - } else { + } else { if (VERBOSE_HTTP_REQUEST_DEBUGGING) { qDebug() << "Received JSON response from data-server that has no matching callback."; qDebug() << jsonResponse; diff --git a/libraries/shared/src/AccountManager.h b/libraries/shared/src/AccountManager.h index 55a40438e0..05a2e6a08a 100644 --- a/libraries/shared/src/AccountManager.h +++ b/libraries/shared/src/AccountManager.h @@ -19,10 +19,7 @@ class JSONCallbackParameters { public: - JSONCallbackParameters() : - jsonCallbackReceiver(NULL), jsonCallbackMethod(), - errorCallbackReceiver(NULL), errorCallbackMethod(), - updateReciever(NULL), updateSlot() {}; + JSONCallbackParameters(); bool isEmpty() const { return !jsonCallbackReceiver && !errorCallbackReceiver; } diff --git a/libraries/shared/src/ModelUploader.cpp b/libraries/shared/src/ModelUploader.cpp index cda57aeab9..4386704559 100644 --- a/libraries/shared/src/ModelUploader.cpp +++ b/libraries/shared/src/ModelUploader.cpp @@ -34,6 +34,8 @@ static const int MAX_SIZE = 10 * 1024 * 1024; // 10 MB static const int TIMEOUT = 1000; static const int MAX_CHECK = 30; +static const int QCOMPRESS_HEADER_POSITION = 0; +static const int QCOMPRESS_HEADER_SIZE = 4; ModelUploader::ModelUploader(bool isHead) : _lodCount(-1), @@ -290,7 +292,10 @@ bool ModelUploader::addPart(const QString &path, const QString& name) { return false; } QByteArray buffer = qCompress(file.readAll()); - buffer.remove(0, 4); + + // Qt's qCompress() default compression level (-1) is the standard zLib compression. + // Here remove Qt's custom header that prevent the data server from uncompressing the files with zLib. + buffer.remove(QCOMPRESS_HEADER_POSITION, QCOMPRESS_HEADER_SIZE); QHttpPart part; part.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data;" From ccd7106527de27fc2597f321793ea00048f7ad58 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Tue, 8 Apr 2014 10:54:41 -0700 Subject: [PATCH 200/595] Include "InterfaceConfig" before QOpenGLFramebufferObject to fix Windows build. --- interface/src/ui/MetavoxelEditor.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index 71539d3a27..ee1b4b0460 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -5,6 +5,9 @@ // Created by Andrzej Kapolka on 1/21/14. // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL +#include "InterfaceConfig.h" + #include #include #include From 22cab29d251842c4e063739a788f9e0fb1a56acc Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 8 Apr 2014 11:06:48 -0700 Subject: [PATCH 201/595] Code review --- libraries/voxels/src/VoxelsScriptingInterface.cpp | 6 +++++- libraries/voxels/src/VoxelsScriptingInterface.h | 2 ++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/libraries/voxels/src/VoxelsScriptingInterface.cpp b/libraries/voxels/src/VoxelsScriptingInterface.cpp index 59e4662bed..61ee4b317d 100644 --- a/libraries/voxels/src/VoxelsScriptingInterface.cpp +++ b/libraries/voxels/src/VoxelsScriptingInterface.cpp @@ -51,6 +51,8 @@ void VoxelsScriptingInterface::setVoxelNonDestructive(float x, float y, float z, AddVoxelCommand* command = new AddVoxelCommand(_tree, addVoxelDetail, getVoxelPacketSender()); + + // As QUndoStack automatically executes redo() on push, we don't need to execute the command ourselves. _undoStack->push(command); } else { // queue the add packet @@ -89,11 +91,12 @@ void VoxelsScriptingInterface::setVoxel(float x, float y, float z, float scale, deleteVoxelDetail, getVoxelPacketSender()); _undoStack->beginMacro(addCommand->text()); - qDebug() << "Macro"; + // As QUndoStack automatically executes redo() on push, we don't need to execute the command ourselves. _undoStack->push(delCommand); _undoStack->push(addCommand); _undoStack->endMacro(); } else { + // As QUndoStack automatically executes redo() on push, we don't need to execute the command ourselves. _undoStack->push(addCommand); } } else { @@ -123,6 +126,7 @@ void VoxelsScriptingInterface::eraseVoxel(float x, float y, float z, float scale DeleteVoxelCommand* command = new DeleteVoxelCommand(_tree, deleteVoxelDetail, getVoxelPacketSender()); + // As QUndoStack automatically executes redo() on push, we don't need to execute the command ourselves. _undoStack->push(command); } else { getVoxelPacketSender()->queueVoxelEditMessages(PacketTypeVoxelErase, 1, &deleteVoxelDetail); diff --git a/libraries/voxels/src/VoxelsScriptingInterface.h b/libraries/voxels/src/VoxelsScriptingInterface.h index 339e527ebc..da51259eeb 100644 --- a/libraries/voxels/src/VoxelsScriptingInterface.h +++ b/libraries/voxels/src/VoxelsScriptingInterface.h @@ -18,6 +18,8 @@ #include "VoxelEditPacketSender.h" #include "VoxelTree.h" +class QUndoStack; + /// handles scripting of voxel commands from JS passed to assigned clients class VoxelsScriptingInterface : public OctreeScriptingInterface { Q_OBJECT From c2ff43818236d44801a6fed6490f0edc3903955a Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 8 Apr 2014 13:37:07 -0700 Subject: [PATCH 202/595] add a CL + JSON settings reader --- domain-server/src/DomainServer.cpp | 196 ++++++------------ domain-server/src/DomainServer.h | 8 +- libraries/shared/src/HifiConfigVariantMap.cpp | 92 ++++++++ libraries/shared/src/HifiConfigVariantMap.h | 19 ++ 4 files changed, 181 insertions(+), 134 deletions(-) create mode 100644 libraries/shared/src/HifiConfigVariantMap.cpp create mode 100644 libraries/shared/src/HifiConfigVariantMap.h diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index af3e9a643f..ad531998c3 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -47,7 +48,7 @@ DomainServer::DomainServer(int argc, char* argv[]) : setApplicationName("domain-server"); QSettings::setDefaultFormat(QSettings::IniFormat); - _argumentList = arguments(); + _argumentVariantMap = HifiConfigVariantMap::mergeCLParametersWithJSONConfig(arguments()); if (optionallySetupDTLS()) { // we either read a certificate and private key or were not passed one, good to load assignments @@ -132,14 +133,14 @@ bool DomainServer::optionallySetupDTLS() { } bool DomainServer::readX509KeyAndCertificate() { - const QString X509_CERTIFICATE_OPTION = "--cert"; - const QString X509_PRIVATE_KEY_OPTION = "--key"; + const QString X509_CERTIFICATE_OPTION = "cert"; + const QString X509_PRIVATE_KEY_OPTION = "key"; const QString X509_KEY_PASSPHRASE_ENV = "DOMAIN_SERVER_KEY_PASSPHRASE"; - int certIndex = _argumentList.indexOf(X509_CERTIFICATE_OPTION); - int keyIndex = _argumentList.indexOf(X509_PRIVATE_KEY_OPTION); + QString certPath = _argumentVariantMap.value(X509_CERTIFICATE_OPTION).toString(); + QString keyPath = _argumentVariantMap.value(X509_PRIVATE_KEY_OPTION).toString(); - if (certIndex != -1 && keyIndex != -1) { + if (!certPath.isEmpty() && !keyPath.isEmpty()) { // the user wants to use DTLS to encrypt communication with nodes // let's make sure we can load the key and certificate _x509Credentials = new gnutls_certificate_credentials_t; @@ -148,8 +149,8 @@ bool DomainServer::readX509KeyAndCertificate() { QString keyPassphraseString = QProcessEnvironment::systemEnvironment().value(X509_KEY_PASSPHRASE_ENV); int gnutlsReturn = gnutls_certificate_set_x509_key_file2(*_x509Credentials, - _argumentList[certIndex + 1].toLocal8Bit().constData(), - _argumentList[keyIndex + 1].toLocal8Bit().constData(), + certPath.toLocal8Bit().constData(), + keyPath.toLocal8Bit().constData(), GNUTLS_X509_FMT_PEM, keyPassphraseString.toLocal8Bit().constData(), 0); @@ -162,7 +163,7 @@ bool DomainServer::readX509KeyAndCertificate() { qDebug() << "Successfully read certificate and private key."; - } else if (certIndex != -1 || keyIndex != -1) { + } else if (!certPath.isEmpty() || !keyPath.isEmpty()) { qDebug() << "Missing certificate or private key. domain-server will now quit."; QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection); return false; @@ -193,13 +194,11 @@ void DomainServer::processCreateResponseFromDataServer(const QJsonObject& jsonOb void DomainServer::setupNodeListAndAssignments(const QUuid& sessionUUID) { - int argumentIndex = 0; - - const QString CUSTOM_PORT_OPTION = "-p"; + const QString CUSTOM_PORT_OPTION = "port"; unsigned short domainServerPort = DEFAULT_DOMAIN_SERVER_PORT; - if ((argumentIndex = _argumentList.indexOf(CUSTOM_PORT_OPTION)) != -1) { - domainServerPort = _argumentList.value(argumentIndex + 1).toUShort(); + if (_argumentVariantMap.contains(CUSTOM_PORT_OPTION)) { + domainServerPort = (unsigned short) _argumentVariantMap.value(CUSTOM_PORT_OPTION).toUInt(); } unsigned short domainServerDTLSPort = 0; @@ -207,21 +206,15 @@ void DomainServer::setupNodeListAndAssignments(const QUuid& sessionUUID) { if (_isUsingDTLS) { domainServerDTLSPort = DEFAULT_DOMAIN_SERVER_DTLS_PORT; - const QString CUSTOM_DTLS_PORT_OPTION = "--dtlsPort"; + const QString CUSTOM_DTLS_PORT_OPTION = "dtls-port"; - if ((argumentIndex = _argumentList.indexOf(CUSTOM_DTLS_PORT_OPTION)) != -1) { - domainServerDTLSPort = _argumentList.value(argumentIndex + 1).toUShort(); + if (_argumentVariantMap.contains(CUSTOM_DTLS_PORT_OPTION)) { + domainServerDTLSPort = (unsigned short) _argumentVariantMap.value(CUSTOM_DTLS_PORT_OPTION).toUInt(); } } QSet parsedTypes(QSet() << Assignment::AgentType); - parseCommandLineTypeConfigs(_argumentList, parsedTypes); - - const QString CONFIG_FILE_OPTION = "--configFile"; - if ((argumentIndex = _argumentList.indexOf(CONFIG_FILE_OPTION)) != -1) { - QString configFilePath = _argumentList.value(argumentIndex + 1); - readConfigFile(configFilePath, parsedTypes); - } + parseAssignmentConfigs(parsedTypes); populateDefaultStaticAssignmentsExcludingTypes(parsedTypes); @@ -240,130 +233,75 @@ void DomainServer::setupNodeListAndAssignments(const QUuid& sessionUUID) { addStaticAssignmentsToQueue(); } -void DomainServer::parseCommandLineTypeConfigs(const QStringList& argumentList, QSet& excludedTypes) { +void DomainServer::parseAssignmentConfigs(QSet& excludedTypes) { // check for configs from the command line, these take precedence - const QString CONFIG_TYPE_OPTION = "--configType"; - int clConfigIndex = argumentList.indexOf(CONFIG_TYPE_OPTION); + const QString ASSIGNMENT_CONFIG_REGEX_STRING = "config-([\\d]+)"; + QRegExp assignmentConfigRegex(ASSIGNMENT_CONFIG_REGEX_STRING); - // enumerate all CL config overrides and parse them to files - while (clConfigIndex != -1) { - int clConfigType = argumentList.value(clConfigIndex + 1).toInt(); - if (clConfigType < Assignment::AllTypes && !excludedTypes.contains((Assignment::Type) clConfigIndex)) { - Assignment::Type assignmentType = (Assignment::Type) clConfigType; - createStaticAssignmentsForTypeGivenConfigString((Assignment::Type) assignmentType, - argumentList.value(clConfigIndex + 2)); - excludedTypes.insert(assignmentType); + // scan for assignment config keys + QStringList variantMapKeys = _argumentVariantMap.keys(); + int configIndex = variantMapKeys.indexOf(assignmentConfigRegex); + + while (configIndex != -1) { + // figure out which assignment type this matches + Assignment::Type assignmentType = (Assignment::Type) assignmentConfigRegex.cap().toInt(); + + QVariant mapValue = _argumentVariantMap[variantMapKeys[configIndex]]; + + if (mapValue.type() == QVariant::String) { + QJsonDocument deserializedDocument = QJsonDocument::fromJson(mapValue.toString().toUtf8()); + createStaticAssignmentsForType(assignmentType, deserializedDocument.array()); + } else { + createStaticAssignmentsForType(assignmentType, mapValue.toJsonArray()); } - clConfigIndex = argumentList.indexOf(CONFIG_TYPE_OPTION, clConfigIndex + 1); - } -} - -// Attempts to read configuration from specified path -// returns true on success, false otherwise -void DomainServer::readConfigFile(const QString& path, QSet& excludedTypes) { - if (path.isEmpty()) { - // config file not specified - return; - } - - if (!QFile::exists(path)) { - qWarning("Specified configuration file does not exist!"); - return; - } - - QFile configFile(path); - if (!configFile.open(QIODevice::ReadOnly | QIODevice::Text)) { - qWarning("Can't open specified configuration file!"); - return; - } else { - qDebug() << "Reading configuration from" << path; - } - - QTextStream configStream(&configFile); - QByteArray configStringByteArray = configStream.readAll().toUtf8(); - QJsonObject configDocObject = QJsonDocument::fromJson(configStringByteArray).object(); - configFile.close(); - - QSet appendedExcludedTypes = excludedTypes; - - foreach (const QString& rootStringValue, configDocObject.keys()) { - int possibleConfigType = rootStringValue.toInt(); + excludedTypes.insert(assignmentType); - if (possibleConfigType < Assignment::AllTypes - && !excludedTypes.contains((Assignment::Type) possibleConfigType)) { - // this is an appropriate config type and isn't already in our excluded types - // we are good to parse it - Assignment::Type assignmentType = (Assignment::Type) possibleConfigType; - QString configString = readServerAssignmentConfig(configDocObject, rootStringValue); - createStaticAssignmentsForTypeGivenConfigString(assignmentType, configString); - - excludedTypes.insert(assignmentType); - } + configIndex = variantMapKeys.indexOf(assignmentConfigRegex); } } -// find assignment configurations on the specified node name and json object -// returns a string in the form of its equivalent cmd line params -QString DomainServer::readServerAssignmentConfig(const QJsonObject& jsonObject, const QString& nodeName) { - QJsonArray nodeArray = jsonObject[nodeName].toArray(); - - QStringList serverConfig; - foreach (const QJsonValue& childValue, nodeArray) { - QString cmdParams; - QJsonObject childObject = childValue.toObject(); - QStringList keys = childObject.keys(); - for (int i = 0; i < keys.size(); i++) { - QString key = keys[i]; - QString value = childObject[key].toString(); - // both cmd line params and json keys are the same - cmdParams += QString("--%1 %2 ").arg(key, value); - } - serverConfig << cmdParams; - } - - // according to split() calls from DomainServer::prepopulateStaticAssignmentFile - // we shold simply join them with semicolons - return serverConfig.join(';'); -} - void DomainServer::addStaticAssignmentToAssignmentHash(Assignment* newAssignment) { qDebug() << "Inserting assignment" << *newAssignment << "to static assignment hash."; _staticAssignmentHash.insert(newAssignment->getUUID(), SharedAssignmentPointer(newAssignment)); } -void DomainServer::createStaticAssignmentsForTypeGivenConfigString(Assignment::Type type, const QString& configString) { +void DomainServer::createStaticAssignmentsForType(Assignment::Type type, const QJsonArray& configArray) { // we have a string for config for this type qDebug() << "Parsing command line config for assignment type" << type; - QStringList multiConfigList = configString.split(";", QString::SkipEmptyParts); + int configCounter = 0; - const QString ASSIGNMENT_CONFIG_POOL_REGEX = "--pool\\s*([\\w-]+)"; - QRegExp poolRegex(ASSIGNMENT_CONFIG_POOL_REGEX); - - // read each config to a payload for this type of assignment - for (int i = 0; i < multiConfigList.size(); i++) { - QString config = multiConfigList.at(i); - - // check the config string for a pool - QString assignmentPool; - - int poolIndex = poolRegex.indexIn(config); - - if (poolIndex != -1) { - assignmentPool = poolRegex.cap(1); + foreach(const QJsonValue& jsonValue, configArray) { + if (jsonValue.isObject()) { + QJsonObject jsonObject = jsonValue.toObject(); - // remove the pool from the config string, the assigned node doesn't need it - config.remove(poolIndex, poolRegex.matchedLength()); + // check the config string for a pool + const QString ASSIGNMENT_POOL_KEY = "pool"; + QString assignmentPool; + + QJsonValue poolValue = jsonObject[ASSIGNMENT_POOL_KEY]; + if (!poolValue.isUndefined()) { + assignmentPool = poolValue.toString(); + + jsonObject.remove(ASSIGNMENT_POOL_KEY); + } + + ++configCounter; + qDebug() << "Type" << type << "config" << configCounter << "=" << jsonObject; + + Assignment* configAssignment = new Assignment(Assignment::CreateCommand, type, assignmentPool); + + // setup the payload as a semi-colon separated list of key = value + QStringList payloadStringList; + foreach(const QString& payloadKey, jsonObject.keys()) { + payloadStringList << QString("%1=%2").arg(payloadKey).arg(jsonObject[payloadKey].toString()); + } + + configAssignment->setPayload(payloadStringList.join(';').toUtf8()); + + addStaticAssignmentToAssignmentHash(configAssignment); } - - qDebug("Type %d config[%d] = %s", type, i, config.toLocal8Bit().constData()); - - Assignment* configAssignment = new Assignment(Assignment::CreateCommand, type, assignmentPool); - - configAssignment->setPayload(config.toUtf8()); - - addStaticAssignmentToAssignmentHash(configAssignment); } } diff --git a/domain-server/src/DomainServer.h b/domain-server/src/DomainServer.h index 78e48f1468..2f570fe5ad 100644 --- a/domain-server/src/DomainServer.h +++ b/domain-server/src/DomainServer.h @@ -64,11 +64,9 @@ private: void sendDomainListToNode(const SharedNodePointer& node, const HifiSockAddr& senderSockAddr, const NodeSet& nodeInterestList); - void parseCommandLineTypeConfigs(const QStringList& argumentList, QSet& excludedTypes); - void readConfigFile(const QString& path, QSet& excludedTypes); - QString readServerAssignmentConfig(const QJsonObject& jsonObject, const QString& nodeName); + void parseAssignmentConfigs(QSet& excludedTypes); void addStaticAssignmentToAssignmentHash(Assignment* newAssignment); - void createStaticAssignmentsForTypeGivenConfigString(Assignment::Type type, const QString& configString); + void createStaticAssignmentsForType(Assignment::Type type, const QJsonArray& configArray); void populateDefaultStaticAssignmentsExcludingTypes(const QSet& excludedTypes); SharedAssignmentPointer matchingStaticAssignmentForCheckIn(const QUuid& checkInUUID, NodeType_t nodeType); @@ -85,7 +83,7 @@ private: QHash _staticAssignmentHash; QQueue _assignmentQueue; - QStringList _argumentList; + QVariantMap _argumentVariantMap; bool _isUsingDTLS; gnutls_certificate_credentials_t* _x509Credentials; diff --git a/libraries/shared/src/HifiConfigVariantMap.cpp b/libraries/shared/src/HifiConfigVariantMap.cpp new file mode 100644 index 0000000000..f0dc012ffa --- /dev/null +++ b/libraries/shared/src/HifiConfigVariantMap.cpp @@ -0,0 +1,92 @@ +// +// HifiConfigVariantMap.cpp +// hifi +// +// Created by Stephen Birarda on 2014-04-08. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// + +#include +#include +#include +#include +#include +#include + +#include "HifiConfigVariantMap.h" + +QVariantMap HifiConfigVariantMap::mergeCLParametersWithJSONConfig(const QStringList& argumentList) { + + QVariantMap mergedMap; + + // Add anything in the CL parameter list to the variant map. + // Take anything with a dash in it as a key, and the values after it as the value. + + const QString DASHED_KEY_REGEX_STRING = "(^-{1,2})([\\w-]+)"; + QRegExp dashedKeyRegex(DASHED_KEY_REGEX_STRING); + + int keyIndex = argumentList.indexOf(dashedKeyRegex); + int nextKeyIndex = 0; + + // check if there is a config file to read where we can pull config info not passed on command line + const QString CONFIG_FILE_OPTION = "--config"; + + while (keyIndex != -1) { + if (argumentList[keyIndex] != CONFIG_FILE_OPTION) { + // we have a key - look forward to see how many values associate to it + QString key = dashedKeyRegex.cap(2); + + nextKeyIndex = argumentList.indexOf(dashedKeyRegex, keyIndex + 1); + + if (nextKeyIndex == keyIndex + 1) { + // there's no value associated with this option, it's a boolean + // so add it to the variant map with NULL as value + mergedMap.insertMulti(key, QVariant()); + } else { + int maxIndex = (nextKeyIndex == -1) ? argumentList.size() : nextKeyIndex; + + // there's at least one value associated with the option + // pull the first value to start + QString value = argumentList[keyIndex + 1]; + + // for any extra values, append them, with a space, to the value string + for (int i = keyIndex + 2; i < maxIndex; i++) { + value += " " + argumentList[i]; + } + + // add the finalized value to the merged map + mergedMap.insert(key, value); + } + + keyIndex = nextKeyIndex; + } else { + keyIndex = argumentList.indexOf(dashedKeyRegex, keyIndex + 1); + } + } + + int configIndex = argumentList.indexOf(CONFIG_FILE_OPTION); + + if (configIndex != -1) { + // we have a config file - try and read it + QString configFilePath = argumentList[configIndex + 1]; + QFile configFile(configFilePath); + + if (configFile.exists()) { + configFile.open(QIODevice::ReadOnly); + + QJsonDocument configDocument = QJsonDocument::fromJson(configFile.readAll()); + QJsonObject rootObject = configDocument.object(); + + // enumerate the keys of the configDocument object + foreach(const QString& key, rootObject.keys()) { + + if (!mergedMap.contains(key)) { + // no match in existing list, add it + mergedMap.insert(key, QVariant(rootObject[key])); + } + } + } + } + + return mergedMap; +} diff --git a/libraries/shared/src/HifiConfigVariantMap.h b/libraries/shared/src/HifiConfigVariantMap.h new file mode 100644 index 0000000000..c652278b0d --- /dev/null +++ b/libraries/shared/src/HifiConfigVariantMap.h @@ -0,0 +1,19 @@ +// +// HifiConfigVariantMap.h +// hifi +// +// Created by Stephen Birarda on 2014-04-08. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// + +#ifndef __hifi__HifiConfigVariantMap__ +#define __hifi__HifiConfigVariantMap__ + +#include + +class HifiConfigVariantMap { +public: + static QVariantMap mergeCLParametersWithJSONConfig(const QStringList& argumentList); +}; + +#endif /* defined(__hifi__HifiConfigVariantMap__) */ From 8ad7c3b239c4b3998069414f8183f995105e00a6 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 8 Apr 2014 14:03:27 -0700 Subject: [PATCH 203/595] Moved ModelUploader to interface + New error messages --- .../src/ModelUploader.cpp | 80 +++++++++++-------- .../shared => interface}/src/ModelUploader.h | 4 +- 2 files changed, 48 insertions(+), 36 deletions(-) rename {libraries/shared => interface}/src/ModelUploader.cpp (82%) rename {libraries/shared => interface}/src/ModelUploader.h (94%) diff --git a/libraries/shared/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp similarity index 82% rename from libraries/shared/src/ModelUploader.cpp rename to interface/src/ModelUploader.cpp index 4386704559..1881d84d85 100644 --- a/libraries/shared/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -18,7 +18,9 @@ #include #include -#include "AccountManager.h" +#include + +#include "renderer/FBXReader.h" #include "ModelUploader.h" @@ -59,11 +61,13 @@ bool ModelUploader::zip() { "Select your .fst file ...", QStandardPaths::writableLocation(QStandardPaths::HomeLocation), "*.fst"); - qDebug() << QStandardPaths::writableLocation(QStandardPaths::HomeLocation); if (filename == "") { // If the user canceled we return. return false; } + QString texDir; + QString fbxFile; + // First we check the FST file QFile fst(filename); @@ -100,22 +104,24 @@ bool ModelUploader::zip() { _dataMultiPart->append(textPart); _url = S3_URL + ((_isHead)? "/models/heads/" : "/models/skeletons/") + line[1].toUtf8() + ".fst"; } else if (line[0] == FILENAME_FIELD) { - QFileInfo fbx(QFileInfo(fst).path() + "/" + line[1]); - if (!fbx.exists() || !fbx.isFile()) { // Check existence + fbxFile = QFileInfo(fst).path() + "/" + line[1]; + QFileInfo fbxInfo(fbxFile); + if (!fbxInfo.exists() || !fbxInfo.isFile()) { // Check existence QMessageBox::warning(NULL, QString("ModelUploader::zip()"), - QString("FBX file %1 could not be found.").arg(fbx.fileName()), + QString("FBX file %1 could not be found.").arg(fbxInfo.fileName()), QMessageBox::Ok); - qDebug() << "[Warning] " << QString("FBX file %1 could not be found.").arg(fbx.fileName()); + qDebug() << "[Warning] " << QString("FBX file %1 could not be found.").arg(fbxInfo.fileName()); return false; } // Compress and copy - if (!addPart(fbx.filePath(), "fbx")) { + if (!addPart(fbxInfo.filePath(), "fbx")) { return false; } } else if (line[0] == TEXDIR_FIELD) { // Check existence - QFileInfo texdir(QFileInfo(fst).path() + "/" + line[1]); - if (!texdir.exists() || !texdir.isDir()) { + texDir = QFileInfo(fst).path() + "/" + line[1]; + QFileInfo texInfo(texDir); + if (!texInfo.exists() || !texInfo.isDir()) { QMessageBox::warning(NULL, QString("ModelUploader::zip()"), QString("Texture directory could not be found."), @@ -123,18 +129,14 @@ bool ModelUploader::zip() { qDebug() << "[Warning] " << QString("Texture directory could not be found."); return false; } - if (!addTextures(texdir)) { // Recursive compress and copy - return false; - } } else if (line[0] == LOD_FIELD) { QFileInfo lod(QFileInfo(fst).path() + "/" + line[1]); if (!lod.exists() || !lod.isFile()) { // Check existence QMessageBox::warning(NULL, QString("ModelUploader::zip()"), - QString("FBX file %1 could not be found.").arg(lod.fileName()), + QString("LOD file %1 could not be found.").arg(lod.fileName()), QMessageBox::Ok); qDebug() << "[Warning] " << QString("FBX file %1 could not be found.").arg(lod.fileName()); - return false; } // Compress and copy if (!addPart(lod.filePath(), QString("lod%1").arg(++_lodCount))) { @@ -143,6 +145,10 @@ bool ModelUploader::zip() { } } + if (!addTextures(texDir, fbxFile)) { + return false; + } + QHttpPart textPart; textPart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data;" " name=\"model_category\""); @@ -159,6 +165,7 @@ bool ModelUploader::zip() { void ModelUploader::send() { if (!zip()) { + deleteLater(); return; } @@ -202,7 +209,7 @@ void ModelUploader::uploadSuccess(const QJsonObject& jsonResponse) { } QMessageBox::information(NULL, QString("ModelUploader::uploadSuccess()"), - QString("Your model is being processed by the system."), + QString("We are reading your model information."), QMessageBox::Ok); qDebug() << "Model sent with success"; checkS3(); @@ -214,7 +221,7 @@ void ModelUploader::uploadFailed(QNetworkReply::NetworkError errorCode, const QS } QMessageBox::warning(NULL, QString("ModelUploader::uploadFailed()"), - QString("Model could not be sent to the data server."), + QString("There was a problem with your upload, please try again later."), QMessageBox::Ok); qDebug() << "Model upload failed (" << errorCode << "): " << errorString; deleteLater(); @@ -247,7 +254,8 @@ void ModelUploader::processCheck() { default: QMessageBox::warning(NULL, QString("ModelUploader::processCheck()"), - QString("Could not verify that the model is present on the server."), + QString("We could not verify that your model was sent sucessfully\n" + "but it may have. If you do not see it in the model browser, try to upload again."), QMessageBox::Ok); deleteLater(); break; @@ -256,24 +264,29 @@ void ModelUploader::processCheck() { delete reply; } -bool ModelUploader::addTextures(const QFileInfo& texdir) { - QStringList filter; - filter << "*.png" << "*.tif" << "*.jpg" << "*.jpeg"; +bool ModelUploader::addTextures(const QString& texdir, const QString fbxFile) { + QFile fbx(fbxFile); + if (!fbx.open(QIODevice::ReadOnly)) { + return false; + } - QFileInfoList list = QDir(texdir.filePath()).entryInfoList(filter, - QDir::Files | - QDir::AllDirs | - QDir::NoDotAndDotDot | - QDir::NoSymLinks); - foreach (QFileInfo info, list) { - if (info.isFile()) { - // Compress and copy - if (!addPart(info.filePath(), QString("texture%1").arg(++_texturesCount))) { - return false; + QByteArray buffer = fbx.readAll(); + QVariantHash variantHash = readMapping(buffer); + FBXGeometry geometry = readFBX(buffer, variantHash); + + foreach (FBXMesh mesh, geometry.meshes) { + foreach (FBXMeshPart part, mesh.parts) { + if (!part.diffuseFilename.isEmpty()) { + if (!addPart(QFileInfo(fbxFile).path() + "/" + part.diffuseFilename, + QString("texture%1").arg(++_texturesCount))) { + return false; + } } - } else if (info.isDir()) { - if (!addTextures(info)) { - return false; + if (!part.normalFilename.isEmpty()) { + if (!addPart(QFileInfo(fbxFile).path() + "/" + part.normalFilename, + QString("texture%1").arg(++_texturesCount))) { + return false; + } } } } @@ -282,6 +295,7 @@ bool ModelUploader::addTextures(const QFileInfo& texdir) { } bool ModelUploader::addPart(const QString &path, const QString& name) { + qDebug() << path; QFile file(path); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::warning(NULL, diff --git a/libraries/shared/src/ModelUploader.h b/interface/src/ModelUploader.h similarity index 94% rename from libraries/shared/src/ModelUploader.h rename to interface/src/ModelUploader.h index 0e62ab8705..0d18ef9022 100644 --- a/libraries/shared/src/ModelUploader.h +++ b/interface/src/ModelUploader.h @@ -17,8 +17,6 @@ class QFileInfo; class QHttpMultiPart; class QProgressBar; -class TemporaryDir; - class ModelUploader : public QObject { Q_OBJECT @@ -55,7 +53,7 @@ private: bool zip(); - bool addTextures(const QFileInfo& texdir); + bool addTextures(const QString& texdir, const QString fbxFile); bool addPart(const QString& path, const QString& name); }; From 9a9939c11a6778a739de24fa6b70c5f227fb29ad Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 8 Apr 2014 14:03:42 -0700 Subject: [PATCH 204/595] repairs for assignment parsing from command line and JSON --- domain-server/src/DomainServer.cpp | 34 ++++++++---------------------- domain-server/src/DomainServer.h | 2 -- 2 files changed, 9 insertions(+), 27 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index ad531998c3..2f4f4666cc 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -172,26 +172,6 @@ bool DomainServer::readX509KeyAndCertificate() { return true; } -void DomainServer::requestCreationFromDataServer() { - // this slot is fired when we get a valid access token from the data-server - // now let's ask it to set us up with a UUID - JSONCallbackParameters callbackParams; - callbackParams.jsonCallbackReceiver = this; - callbackParams.jsonCallbackMethod = "processCreateResponseFromDataServer"; - - AccountManager::getInstance().authenticatedRequest("/api/v1/domains/create", - QNetworkAccessManager::PostOperation, - callbackParams); -} - -void DomainServer::processCreateResponseFromDataServer(const QJsonObject& jsonObject) { - if (jsonObject["status"].toString() == "success") { - // pull out the UUID the data-server is telling us to use, and complete our setup with it - QUuid newSessionUUID = QUuid(jsonObject["data"].toObject()["uuid"].toString()); - setupNodeListAndAssignments(newSessionUUID); - } -} - void DomainServer::setupNodeListAndAssignments(const QUuid& sessionUUID) { const QString CUSTOM_PORT_OPTION = "port"; @@ -244,20 +224,21 @@ void DomainServer::parseAssignmentConfigs(QSet& excludedTypes) while (configIndex != -1) { // figure out which assignment type this matches - Assignment::Type assignmentType = (Assignment::Type) assignmentConfigRegex.cap().toInt(); + Assignment::Type assignmentType = (Assignment::Type) assignmentConfigRegex.cap(1).toInt(); QVariant mapValue = _argumentVariantMap[variantMapKeys[configIndex]]; if (mapValue.type() == QVariant::String) { + qDebug() << mapValue.toString(); QJsonDocument deserializedDocument = QJsonDocument::fromJson(mapValue.toString().toUtf8()); createStaticAssignmentsForType(assignmentType, deserializedDocument.array()); } else { - createStaticAssignmentsForType(assignmentType, mapValue.toJsonArray()); + createStaticAssignmentsForType(assignmentType, mapValue.toJsonValue().toArray()); } excludedTypes.insert(assignmentType); - configIndex = variantMapKeys.indexOf(assignmentConfigRegex); + configIndex = variantMapKeys.indexOf(assignmentConfigRegex, configIndex + 1); } } @@ -272,6 +253,8 @@ void DomainServer::createStaticAssignmentsForType(Assignment::Type type, const Q int configCounter = 0; + qDebug() << configArray; + foreach(const QJsonValue& jsonValue, configArray) { if (jsonValue.isObject()) { QJsonObject jsonObject = jsonValue.toObject(); @@ -295,10 +278,11 @@ void DomainServer::createStaticAssignmentsForType(Assignment::Type type, const Q // setup the payload as a semi-colon separated list of key = value QStringList payloadStringList; foreach(const QString& payloadKey, jsonObject.keys()) { - payloadStringList << QString("%1=%2").arg(payloadKey).arg(jsonObject[payloadKey].toString()); + QString dashes = payloadKey.size() == 1 ? "-" : "--"; + payloadStringList << QString("%1%2 %3").arg(dashes).arg(payloadKey).arg(jsonObject[payloadKey].toString()); } - configAssignment->setPayload(payloadStringList.join(';').toUtf8()); + configAssignment->setPayload(payloadStringList.join(' ').toUtf8()); addStaticAssignmentToAssignmentHash(configAssignment); } diff --git a/domain-server/src/DomainServer.h b/domain-server/src/DomainServer.h index 2f570fe5ad..48c77625bb 100644 --- a/domain-server/src/DomainServer.h +++ b/domain-server/src/DomainServer.h @@ -44,8 +44,6 @@ public slots: void nodeKilled(SharedNodePointer node); private slots: - void requestCreationFromDataServer(); - void processCreateResponseFromDataServer(const QJsonObject& jsonObject); void readAvailableDatagrams(); void readAvailableDTLSDatagrams(); From 9ca864bb501cca4d2bb856dff599e4fb4183a269 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 8 Apr 2014 14:05:26 -0700 Subject: [PATCH 205/595] don't parse excluded types from config variant map --- domain-server/src/DomainServer.cpp | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 2f4f4666cc..322f88188b 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -226,17 +226,18 @@ void DomainServer::parseAssignmentConfigs(QSet& excludedTypes) // figure out which assignment type this matches Assignment::Type assignmentType = (Assignment::Type) assignmentConfigRegex.cap(1).toInt(); - QVariant mapValue = _argumentVariantMap[variantMapKeys[configIndex]]; - - if (mapValue.type() == QVariant::String) { - qDebug() << mapValue.toString(); - QJsonDocument deserializedDocument = QJsonDocument::fromJson(mapValue.toString().toUtf8()); - createStaticAssignmentsForType(assignmentType, deserializedDocument.array()); - } else { - createStaticAssignmentsForType(assignmentType, mapValue.toJsonValue().toArray()); - } - - excludedTypes.insert(assignmentType); + if (assignmentType < Assignment::AllTypes && !excludedTypes.contains(assignmentType)) { + QVariant mapValue = _argumentVariantMap[variantMapKeys[configIndex]]; + + if (mapValue.type() == QVariant::String) { + QJsonDocument deserializedDocument = QJsonDocument::fromJson(mapValue.toString().toUtf8()); + createStaticAssignmentsForType(assignmentType, deserializedDocument.array()); + } else { + createStaticAssignmentsForType(assignmentType, mapValue.toJsonValue().toArray()); + } + + excludedTypes.insert(assignmentType); + } configIndex = variantMapKeys.indexOf(assignmentConfigRegex, configIndex + 1); } From e417e7670b0bef8816f136adac0f3f02d394e1d1 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 8 Apr 2014 14:07:31 -0700 Subject: [PATCH 206/595] cleanup DomainServer debug during config parsing --- domain-server/src/DomainServer.cpp | 6 ++---- libraries/shared/src/HifiConfigVariantMap.cpp | 3 +++ 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 322f88188b..090e781be0 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -237,7 +237,7 @@ void DomainServer::parseAssignmentConfigs(QSet& excludedTypes) } excludedTypes.insert(assignmentType); - } + } configIndex = variantMapKeys.indexOf(assignmentConfigRegex, configIndex + 1); } @@ -250,12 +250,10 @@ void DomainServer::addStaticAssignmentToAssignmentHash(Assignment* newAssignment void DomainServer::createStaticAssignmentsForType(Assignment::Type type, const QJsonArray& configArray) { // we have a string for config for this type - qDebug() << "Parsing command line config for assignment type" << type; + qDebug() << "Parsing config for assignment type" << type; int configCounter = 0; - qDebug() << configArray; - foreach(const QJsonValue& jsonValue, configArray) { if (jsonValue.isObject()) { QJsonObject jsonObject = jsonValue.toObject(); diff --git a/libraries/shared/src/HifiConfigVariantMap.cpp b/libraries/shared/src/HifiConfigVariantMap.cpp index f0dc012ffa..f68c64581b 100644 --- a/libraries/shared/src/HifiConfigVariantMap.cpp +++ b/libraries/shared/src/HifiConfigVariantMap.cpp @@ -72,6 +72,7 @@ QVariantMap HifiConfigVariantMap::mergeCLParametersWithJSONConfig(const QStringL QFile configFile(configFilePath); if (configFile.exists()) { + qDebug() << "Reading JSON config file at" << configFilePath; configFile.open(QIODevice::ReadOnly); QJsonDocument configDocument = QJsonDocument::fromJson(configFile.readAll()); @@ -85,6 +86,8 @@ QVariantMap HifiConfigVariantMap::mergeCLParametersWithJSONConfig(const QStringL mergedMap.insert(key, QVariant(rootObject[key])); } } + } else { + qDebug() << "Could not find JSON config file at" << configFilePath; } } From ea61ccff7f474bfe4305af0e70b442e527e37e6e Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 8 Apr 2014 14:10:04 -0700 Subject: [PATCH 207/595] add some more debugging when reading X509 cert files for DTLS --- domain-server/src/DomainServer.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 090e781be0..1f7b73cda2 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -148,6 +148,9 @@ bool DomainServer::readX509KeyAndCertificate() { QString keyPassphraseString = QProcessEnvironment::systemEnvironment().value(X509_KEY_PASSPHRASE_ENV); + qDebug() << "Reading certificate file at" << certPath << "for DTLS."; + qDebug() << "Reading key file at" << keyPath << "for DTLS."; + int gnutlsReturn = gnutls_certificate_set_x509_key_file2(*_x509Credentials, certPath.toLocal8Bit().constData(), keyPath.toLocal8Bit().constData(), From 6754a6ca69f022ba8558aa5c3d85552abfe02429 Mon Sep 17 00:00:00 2001 From: Thijs Wenker Date: Tue, 8 Apr 2014 23:45:27 +0200 Subject: [PATCH 208/595] Fixed some style --- interface/src/Audio.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 7e7dfd9df1..597373ffe8 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -161,7 +161,8 @@ QAudioDeviceInfo defaultAudioDeviceForMode(QAudio::Mode mode) { ZeroMemory(&osvi, sizeof(OSVERSIONINFO)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&osvi); - if (osvi.dwMajorVersion < 6) {// lower then vista + const DWORD VISTA_MAJOR_VERSION = 6; + if (osvi.dwMajorVersion < VISTA_MAJOR_VERSION) {// lower then vista if (mode == QAudio::AudioInput) { WAVEINCAPS wic; // first use WAVE_MAPPER to get the default devices manufacturer ID @@ -182,11 +183,11 @@ QAudioDeviceInfo defaultAudioDeviceForMode(QAudio::Mode mode) { } else { HRESULT hr = S_OK; CoInitialize(NULL); - IMMDeviceEnumerator *pMMDeviceEnumerator = NULL; + IMMDeviceEnumerator* pMMDeviceEnumerator = NULL; CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&pMMDeviceEnumerator); - IMMDevice *pEndpoint; + IMMDevice* pEndpoint; pMMDeviceEnumerator->GetDefaultAudioEndpoint(mode == QAudio::AudioOutput ? eRender : eCapture, eMultimedia, &pEndpoint); - IPropertyStore *pPropertyStore; + IPropertyStore* pPropertyStore; pEndpoint->OpenPropertyStore(STGM_READ, &pPropertyStore); pEndpoint->Release(); pEndpoint = NULL; @@ -196,7 +197,8 @@ QAudioDeviceInfo defaultAudioDeviceForMode(QAudio::Mode mode) { pPropertyStore->Release(); pPropertyStore = NULL; //QAudio devices seems to only take the 31 first characters of the Friendly Device Name. - deviceName = QString::fromWCharArray((wchar_t *)pv.pwszVal).left(31); + const DWORD QT_WIN_MAX_AUDIO_DEVICENAME_LEN = 31; + deviceName = QString::fromWCharArray((wchar_t*)pv.pwszVal).left(QT_WIN_MAX_AUDIO_DEVICENAME_LEN); qDebug() << (mode == QAudio::AudioOutput ? "output" : "input") << " device:" << deviceName; PropVariantClear(&pv); pMMDeviceEnumerator->Release(); From 5776514e6a0943c9151d2676fa9e29ac1fa7486f Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Tue, 8 Apr 2014 14:48:01 -0700 Subject: [PATCH 209/595] Working on pushing the mirror camera back to prevent intersecting the near clip plane. Closes #2617. --- interface/src/Application.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 6bc8bb62df..db75034e7f 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -528,6 +528,16 @@ void Application::paintGL() { _myCamera.setDistance(MIRROR_FULLSCREEN_DISTANCE * _myAvatar->getScale()); _myCamera.setTargetPosition(_myAvatar->getPosition() + glm::vec3(0, headHeight, 0)); _myCamera.setTargetRotation(_myAvatar->getWorldAlignedOrientation() * glm::quat(glm::vec3(0.0f, PI, 0.0f))); + + // if the head would intersect the near clip plane, we must push the camera out + glm::vec3 relativePosition = glm::inverse(_myCamera.getTargetRotation()) * + (_myAvatar->getHead()->getPosition() - _myCamera.getTargetPosition()); + const float HEAD_RADIUS = 0.1f; + float pushback = relativePosition.z + _myCamera.getNearClip() + HEAD_RADIUS; + if (pushback > 0.0f) { + _myCamera.setTargetPosition(_myCamera.getTargetPosition() + + _myCamera.getTargetRotation() * glm::vec3(0.0f, 0.0f, pushback)); + } } // Update camera position From add7bb26ed4d731d8167b3c6eed21a358c4c8166 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Tue, 8 Apr 2014 14:55:46 -0700 Subject: [PATCH 210/595] Use the head height to determine the pushback amount. --- interface/src/Application.cpp | 4 ++-- interface/src/avatar/Avatar.cpp | 10 +++++----- interface/src/avatar/Avatar.h | 3 ++- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index db75034e7f..0b702c98a0 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -532,8 +532,8 @@ void Application::paintGL() { // if the head would intersect the near clip plane, we must push the camera out glm::vec3 relativePosition = glm::inverse(_myCamera.getTargetRotation()) * (_myAvatar->getHead()->getPosition() - _myCamera.getTargetPosition()); - const float HEAD_RADIUS = 0.1f; - float pushback = relativePosition.z + _myCamera.getNearClip() + HEAD_RADIUS; + const float HEAD_EXPANSION = 1.1f; + float pushback = relativePosition.z + _myCamera.getNearClip() + _myAvatar->getHeadHeight() * HEAD_EXPANSION; if (pushback > 0.0f) { _myCamera.setTargetPosition(_myCamera.getTargetPosition() + _myCamera.getTargetRotation() * glm::vec3(0.0f, 0.0f, pushback)); diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 05f74755df..86378c6cdf 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -524,6 +524,11 @@ void Avatar::updateShapePositions() { headModel.updateShapePositions(); } +float Avatar::getHeadHeight() const { + Extents extents = getHead()->getFaceModel().getBindExtents(); + return extents.maximum.y - extents.minimum.y; +} + bool Avatar::findCollisions(const QVector& shapes, CollisionList& collisions) { // TODO: Andrew to fix: also collide against _skeleton //bool collided = _skeletonModel.findCollisions(shapes, collisions); @@ -750,11 +755,6 @@ float Avatar::getSkeletonHeight() const { return extents.maximum.y - extents.minimum.y; } -float Avatar::getHeadHeight() const { - Extents extents = getHead()->getFaceModel().getBindExtents(); - return extents.maximum.y - extents.minimum.y; -} - bool Avatar::collisionWouldMoveAvatar(CollisionInfo& collision) const { if (!collision._data || collision._type != MODEL_COLLISION) { return false; diff --git a/interface/src/avatar/Avatar.h b/interface/src/avatar/Avatar.h index f57982b514..fca7173add 100755 --- a/interface/src/avatar/Avatar.h +++ b/interface/src/avatar/Avatar.h @@ -151,6 +151,8 @@ public: virtual float getBoundingRadius() const; void updateShapePositions(); + float getHeadHeight() const; + public slots: void updateCollisionFlags(); @@ -179,7 +181,6 @@ protected: void setScale(float scale); float getSkeletonHeight() const; - float getHeadHeight() const; float getPelvisFloatingHeight() const; float getPelvisToHeadLength() const; From faf8c353588b0e6fe238f34c8633fcf762414a35 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Tue, 8 Apr 2014 15:01:56 -0700 Subject: [PATCH 211/595] Head height's kind of screwy; let's use the eye position. --- interface/src/Application.cpp | 9 +++++---- interface/src/avatar/Avatar.cpp | 10 +++++----- interface/src/avatar/Avatar.h | 3 +-- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 0b702c98a0..87cdaf8038 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -524,16 +524,17 @@ void Application::paintGL() { } else if (_myCamera.getMode() == CAMERA_MODE_MIRROR) { _myCamera.setTightness(0.0f); - float headHeight = _myAvatar->getHead()->calculateAverageEyePosition().y - _myAvatar->getPosition().y; + glm::vec3 eyePosition = _myAvatar->getHead()->calculateAverageEyePosition(); + float headHeight = eyePosition.y - _myAvatar->getPosition().y; _myCamera.setDistance(MIRROR_FULLSCREEN_DISTANCE * _myAvatar->getScale()); _myCamera.setTargetPosition(_myAvatar->getPosition() + glm::vec3(0, headHeight, 0)); _myCamera.setTargetRotation(_myAvatar->getWorldAlignedOrientation() * glm::quat(glm::vec3(0.0f, PI, 0.0f))); // if the head would intersect the near clip plane, we must push the camera out glm::vec3 relativePosition = glm::inverse(_myCamera.getTargetRotation()) * - (_myAvatar->getHead()->getPosition() - _myCamera.getTargetPosition()); - const float HEAD_EXPANSION = 1.1f; - float pushback = relativePosition.z + _myCamera.getNearClip() + _myAvatar->getHeadHeight() * HEAD_EXPANSION; + (eyePosition - _myCamera.getTargetPosition()); + const float PUSHBACK_RADIUS = 0.01f; + float pushback = relativePosition.z + _myCamera.getNearClip() + _myAvatar->getScale() * PUSHBACK_RADIUS; if (pushback > 0.0f) { _myCamera.setTargetPosition(_myCamera.getTargetPosition() + _myCamera.getTargetRotation() * glm::vec3(0.0f, 0.0f, pushback)); diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 86378c6cdf..05f74755df 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -524,11 +524,6 @@ void Avatar::updateShapePositions() { headModel.updateShapePositions(); } -float Avatar::getHeadHeight() const { - Extents extents = getHead()->getFaceModel().getBindExtents(); - return extents.maximum.y - extents.minimum.y; -} - bool Avatar::findCollisions(const QVector& shapes, CollisionList& collisions) { // TODO: Andrew to fix: also collide against _skeleton //bool collided = _skeletonModel.findCollisions(shapes, collisions); @@ -755,6 +750,11 @@ float Avatar::getSkeletonHeight() const { return extents.maximum.y - extents.minimum.y; } +float Avatar::getHeadHeight() const { + Extents extents = getHead()->getFaceModel().getBindExtents(); + return extents.maximum.y - extents.minimum.y; +} + bool Avatar::collisionWouldMoveAvatar(CollisionInfo& collision) const { if (!collision._data || collision._type != MODEL_COLLISION) { return false; diff --git a/interface/src/avatar/Avatar.h b/interface/src/avatar/Avatar.h index fca7173add..f57982b514 100755 --- a/interface/src/avatar/Avatar.h +++ b/interface/src/avatar/Avatar.h @@ -151,8 +151,6 @@ public: virtual float getBoundingRadius() const; void updateShapePositions(); - float getHeadHeight() const; - public slots: void updateCollisionFlags(); @@ -181,6 +179,7 @@ protected: void setScale(float scale); float getSkeletonHeight() const; + float getHeadHeight() const; float getPelvisFloatingHeight() const; float getPelvisToHeadLength() const; From 083e9076a96ff7e3f8276a24144ddf6a3b2803b3 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Tue, 8 Apr 2014 15:17:05 -0700 Subject: [PATCH 212/595] Missed a spot. --- interface/src/Application.cpp | 3 ++- interface/src/Camera.h | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 87cdaf8038..a30ed648d8 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -534,7 +534,8 @@ void Application::paintGL() { glm::vec3 relativePosition = glm::inverse(_myCamera.getTargetRotation()) * (eyePosition - _myCamera.getTargetPosition()); const float PUSHBACK_RADIUS = 0.01f; - float pushback = relativePosition.z + _myCamera.getNearClip() + _myAvatar->getScale() * PUSHBACK_RADIUS; + float pushback = relativePosition.z + _myCamera.getNearClip() + + _myAvatar->getScale() * PUSHBACK_RADIUS - _myCamera.getDistance(); if (pushback > 0.0f) { _myCamera.setTargetPosition(_myCamera.getTargetPosition() + _myCamera.getTargetRotation() * glm::vec3(0.0f, 0.0f, pushback)); diff --git a/interface/src/Camera.h b/interface/src/Camera.h index 9973fd246e..3fd0efd50a 100644 --- a/interface/src/Camera.h +++ b/interface/src/Camera.h @@ -54,6 +54,7 @@ public: const glm::quat& getRotation() const { return _rotation; } CameraMode getMode() const { return _mode; } float getModeShiftPeriod() const { return _modeShiftPeriod; } + float getDistance() const { return _distance; } const glm::vec3& getTargetPosition() const { return _targetPosition; } const glm::quat& getTargetRotation() const { return _targetRotation; } float getFieldOfView() const { return _fieldOfView; } From 597d750af906117ca2cb71a1b8fb4675a5cad3d4 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Tue, 8 Apr 2014 15:25:10 -0700 Subject: [PATCH 213/595] Better radius. --- interface/src/Application.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index a30ed648d8..45ae36a23b 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -533,7 +533,7 @@ void Application::paintGL() { // if the head would intersect the near clip plane, we must push the camera out glm::vec3 relativePosition = glm::inverse(_myCamera.getTargetRotation()) * (eyePosition - _myCamera.getTargetPosition()); - const float PUSHBACK_RADIUS = 0.01f; + const float PUSHBACK_RADIUS = 0.2f; float pushback = relativePosition.z + _myCamera.getNearClip() + _myAvatar->getScale() * PUSHBACK_RADIUS - _myCamera.getDistance(); if (pushback > 0.0f) { From 94a7ded212fd1b3cf857ab9bc3cac56afae6ef33 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Tue, 8 Apr 2014 15:36:21 -0700 Subject: [PATCH 214/595] Slip in a fix for Windows build warnings on mtc-generated code. --- tools/mtc/src/main.cpp | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/tools/mtc/src/main.cpp b/tools/mtc/src/main.cpp index 9c77851961..b7e2929d49 100644 --- a/tools/mtc/src/main.cpp +++ b/tools/mtc/src/main.cpp @@ -143,13 +143,15 @@ void generateOutput (QTextStream& out, const QList& streamables) { out << " }\n"; out << " index = nextIndex;\n"; } - out << " switch (index) {\n"; - for (int i = 0; i < str.fields.size(); i++) { - out << " case " << i << ":\n"; - out << " this->" << str.fields.at(i).name << " = value.value<" << str.fields.at(i).type << ">();\n"; - out << " break;\n"; + if (!str.fields.isEmpty()) { + out << " switch (index) {\n"; + for (int i = 0; i < str.fields.size(); i++) { + out << " case " << i << ":\n"; + out << " this->" << str.fields.at(i).name << " = value.value<" << str.fields.at(i).type << ">();\n"; + out << " break;\n"; + } + out << " }\n"; } - out << " }\n"; out << "}\n"; out << "QVariant " << name << "::getField(int index) const {\n"; @@ -162,12 +164,14 @@ void generateOutput (QTextStream& out, const QList& streamables) { out << " }\n"; out << " index = nextIndex;\n"; } - out << " switch (index) {\n"; - for (int i = 0; i < str.fields.size(); i++) { - out << " case " << i << ":\n"; - out << " return QVariant::fromValue(this->" << str.fields.at(i).name << ");\n"; + if (!str.fields.isEmpty()) { + out << " switch (index) {\n"; + for (int i = 0; i < str.fields.size(); i++) { + out << " case " << i << ":\n"; + out << " return QVariant::fromValue(this->" << str.fields.at(i).name << ");\n"; + } + out << " }\n"; } - out << " }\n"; out << " return QVariant();\n"; out << "}\n"; From 039450aeec47ea58364de4b352d1320fe7bcc1eb Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 8 Apr 2014 16:35:07 -0700 Subject: [PATCH 215/595] Checking model name is present in the .fst file --- interface/src/ModelUploader.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index 1881d84d85..93a2c96c7c 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -65,6 +65,7 @@ bool ModelUploader::zip() { // If the user canceled we return. return false; } + bool _nameIsPresent = false; QString texDir; QString fbxFile; @@ -103,6 +104,7 @@ bool ModelUploader::zip() { textPart.setBody(line[1].toUtf8()); _dataMultiPart->append(textPart); _url = S3_URL + ((_isHead)? "/models/heads/" : "/models/skeletons/") + line[1].toUtf8() + ".fst"; + _nameIsPresent = true; } else if (line[0] == FILENAME_FIELD) { fbxFile = QFileInfo(fst).path() + "/" + line[1]; QFileInfo fbxInfo(fbxFile); @@ -159,6 +161,15 @@ bool ModelUploader::zip() { } _dataMultiPart->append(textPart); + if (!_nameIsPresent) { + QMessageBox::warning(NULL, + QString("ModelUploader::zip()"), + QString("Model name is missing in the .fst file."), + QMessageBox::Ok); + qDebug() << "[Warning] " << QString("Model name is missing in the .fst file."); + return false; + } + _readyToSend = true; return true; } From 98011da1efd15a7dca395b611a3d4df4ad43133e Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Tue, 8 Apr 2014 17:07:45 -0700 Subject: [PATCH 216/595] Starting on Faceplus integration. --- cmake/modules/FindFaceplus.cmake | 42 ++++++++++++++++++++++++++ interface/CMakeLists.txt | 9 ++++++ interface/external/faceplus/readme.txt | 9 ++++++ 3 files changed, 60 insertions(+) create mode 100644 cmake/modules/FindFaceplus.cmake create mode 100644 interface/external/faceplus/readme.txt diff --git a/cmake/modules/FindFaceplus.cmake b/cmake/modules/FindFaceplus.cmake new file mode 100644 index 0000000000..2a2083d6e4 --- /dev/null +++ b/cmake/modules/FindFaceplus.cmake @@ -0,0 +1,42 @@ +# Try to find the Faceplus library +# +# You must provide a FACEPLUS_ROOT_DIR which contains lib and include directories +# +# Once done this will define +# +# FACEPLUS_FOUND - system found Faceplus +# FACEPLUS_INCLUDE_DIRS - the Faceplus include directory +# FACEPLUS_LIBRARIES - Link this to use Faceplus +# +# Created on 4/8/2014 by Andrzej Kapolka +# Copyright (c) 2014 High Fidelity +# + +if (FACEPLUS_LIBRARIES AND FACEPLUS_INCLUDE_DIRS) + # in cache already + set(FACEPLUS_FOUND TRUE) +else (FACEPLUS_LIBRARIES AND FACEPLUS_INCLUDE_DIRS) + find_path(FACEPLUS_INCLUDE_DIRS faceplus.h ${FACEPLUS_ROOT_DIR}/include) + + if (WIN32) + find_library(FACEPLUS_LIBRARIES faceplus.lib ${FACEPLUS_ROOT_DIR}/win32/) + endif (WIN32) + + if (FACEPLUS_INCLUDE_DIRS AND FACEPLUS_LIBRARIES) + set(FACEPLUS_FOUND TRUE) + endif (FACEPLUS_INCLUDE_DIRS AND FACEPLUS_LIBRARIES) + + if (FACEPLUS_FOUND) + if (NOT FACEPLUS_FIND_QUIETLY) + message(STATUS "Found Faceplus... ${FACEPLUS_LIBRARIES}") + endif (NOT FACEPLUS_FIND_QUIETLY) + else () + if (FACEPLUS_FIND_REQUIRED) + message(FATAL_ERROR "Could not find Faceplus") + endif (FACEPLUS_FIND_REQUIRED) + endif () + + # show the FACEPLUS_INCLUDE_DIRS and FACEPLUS_LIBRARIES variables only in the advanced view + mark_as_advanced(FACEPLUS_INCLUDE_DIRS FACEPLUS_LIBRARIES) + +endif (FACEPLUS_LIBRARIES AND FACEPLUS_INCLUDE_DIRS) diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index 55d0a86d87..29943eb4cb 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -12,6 +12,7 @@ project(${TARGET_NAME}) # setup for find modules set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/../cmake/modules/") +set(FACEPLUS_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/external/faceplus") set(FACESHIFT_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/external/faceshift") set(LIBOVR_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/external/oculus") set(SIXENSE_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/external/Sixense") @@ -130,6 +131,7 @@ link_hifi_library(audio ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(script-engine ${TARGET_NAME} "${ROOT_DIR}") # find any optional libraries +find_package(Faceplus) find_package(Faceshift) find_package(LibOVR) find_package(Sixense) @@ -163,6 +165,13 @@ if (VISAGE_FOUND AND NOT DISABLE_VISAGE) target_link_libraries(${TARGET_NAME} "${VISAGE_LIBRARIES}") endif (VISAGE_FOUND AND NOT DISABLE_VISAGE) +# and with Faceplus library, also for webcam feature tracking +if (FACEPLUS_FOUND AND NOT DISABLE_FACEPLUS) + add_definitions(-DHAVE_FACEPLUS) + include_directories(SYSTEM "${FACEPLUS_INCLUDE_DIRS}") + target_link_libraries(${TARGET_NAME} "${FACEPLUS_LIBRARIES}") +endif (FACEPLUS_FOUND AND NOT DISABLE_FACEPLUS) + # and with LibOVR for Oculus Rift if (LIBOVR_FOUND AND NOT DISABLE_LIBOVR) add_definitions(-DHAVE_LIBOVR) diff --git a/interface/external/faceplus/readme.txt b/interface/external/faceplus/readme.txt new file mode 100644 index 0000000000..322ea846bb --- /dev/null +++ b/interface/external/faceplus/readme.txt @@ -0,0 +1,9 @@ + +Instructions for adding the Faceplus driver to Interface +Andrzej Kapolka, April 8, 2014 + +1. Copy the Faceplus sdk folders (include, win32) into the interface/external/faceplus folder. + This readme.txt should be there as well. + +2. Delete your build directory, run cmake and build, and you should be all set. + From f3cbd120ce58246d1e326a7c924582bf4f1e2762 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 8 Apr 2014 17:19:23 -0700 Subject: [PATCH 217/595] header comment tweaks prior to regex match --- interface/src/scripting/ControllerScriptingInterface.h | 1 - interface/src/ui/RearMirrorTools.h | 2 +- interface/src/ui/RunningScriptsWidget.h | 1 + interface/src/world.h | 2 +- libraries/octree/src/OctreeConstants.h | 1 - libraries/octree/src/Plane.h | 3 +-- libraries/shared/src/PacketHeaders.h | 2 +- libraries/shared/src/RegisteredMetaTypes.h | 1 + libraries/voxels/src/VoxelConstants.h | 1 - 9 files changed, 6 insertions(+), 8 deletions(-) diff --git a/interface/src/scripting/ControllerScriptingInterface.h b/interface/src/scripting/ControllerScriptingInterface.h index 6fe5a60fa4..ada146ff02 100644 --- a/interface/src/scripting/ControllerScriptingInterface.h +++ b/interface/src/scripting/ControllerScriptingInterface.h @@ -1,4 +1,3 @@ - // // ControllerScriptingInterface.h // hifi diff --git a/interface/src/ui/RearMirrorTools.h b/interface/src/ui/RearMirrorTools.h index 7f13eafbee..007b54f129 100644 --- a/interface/src/ui/RearMirrorTools.h +++ b/interface/src/ui/RearMirrorTools.h @@ -4,7 +4,7 @@ // // Created by stojce on 23.10.2013. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. - +// #ifndef __hifi__RearMirrorTools__ #define __hifi__RearMirrorTools__ diff --git a/interface/src/ui/RunningScriptsWidget.h b/interface/src/ui/RunningScriptsWidget.h index d92927347f..5d365dae91 100644 --- a/interface/src/ui/RunningScriptsWidget.h +++ b/interface/src/ui/RunningScriptsWidget.h @@ -4,6 +4,7 @@ // // Created by Mohammed Nafees on 03/28/2014. // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// #ifndef __hifi__RunningScriptsWidget__ #define __hifi__RunningScriptsWidget__ diff --git a/interface/src/world.h b/interface/src/world.h index bc8dab9106..8d857303ae 100644 --- a/interface/src/world.h +++ b/interface/src/world.h @@ -4,7 +4,7 @@ // // Created by Philip Rosedale on 8/23/12. // Copyright (c) 2012 High Fidelity, Inc. All rights reserved. -// +// #ifndef __interface__world__ #define __interface__world__ diff --git a/libraries/octree/src/OctreeConstants.h b/libraries/octree/src/OctreeConstants.h index a78d778f70..82f4acea66 100644 --- a/libraries/octree/src/OctreeConstants.h +++ b/libraries/octree/src/OctreeConstants.h @@ -7,7 +7,6 @@ // // Various important constants used throughout the system related to voxels // -// #ifndef __hifi_OctreeConstants_h__ #define __hifi_OctreeConstants_h__ diff --git a/libraries/octree/src/Plane.h b/libraries/octree/src/Plane.h index 8ce0e5042e..48bef064f6 100755 --- a/libraries/octree/src/Plane.h +++ b/libraries/octree/src/Plane.h @@ -13,8 +13,7 @@ #include -class Plane -{ +class Plane { public: Plane(const glm::vec3 &v1, const glm::vec3 &v2, const glm::vec3 &v3) { set3Points(v1,v2,v3); } Plane() : _normal(0,0,0), _point(0,0,0), _dCoefficient(0) {}; diff --git a/libraries/shared/src/PacketHeaders.h b/libraries/shared/src/PacketHeaders.h index a9bc5d3763..0e1e152a02 100644 --- a/libraries/shared/src/PacketHeaders.h +++ b/libraries/shared/src/PacketHeaders.h @@ -7,7 +7,7 @@ // // The packet headers below refer to the first byte of a received UDP packet transmitted between // any two Hifi components. For example, a packet whose first byte is 'P' is always a ping packet. -// +// #ifndef hifi_PacketHeaders_h #define hifi_PacketHeaders_h diff --git a/libraries/shared/src/RegisteredMetaTypes.h b/libraries/shared/src/RegisteredMetaTypes.h index 0e7732c057..4e6a071dd6 100644 --- a/libraries/shared/src/RegisteredMetaTypes.h +++ b/libraries/shared/src/RegisteredMetaTypes.h @@ -7,6 +7,7 @@ // // Used to register meta-types with Qt so that they can be used as properties for objects exposed to our // Agent scripting. +// #ifndef hifi_RegisteredMetaTypes_h #define hifi_RegisteredMetaTypes_h diff --git a/libraries/voxels/src/VoxelConstants.h b/libraries/voxels/src/VoxelConstants.h index d4cbc54f18..16d75873d9 100644 --- a/libraries/voxels/src/VoxelConstants.h +++ b/libraries/voxels/src/VoxelConstants.h @@ -7,7 +7,6 @@ // // Various important constants used throughout the system related to voxels // -// #ifndef __hifi_VoxelConstants_h__ #define __hifi_VoxelConstants_h__ From 6a51df9e38d5689566146ed62a17a3b736dbc67e Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 8 Apr 2014 17:30:36 -0700 Subject: [PATCH 218/595] initial regex replacement of headers --- animation-server/src/AnimationServer.h | 7 ++- assignment-client/src/Agent.h | 7 ++- assignment-client/src/AssignmentClient.h | 7 ++- .../src/AssignmentClientMonitor.h | 7 ++- assignment-client/src/AssignmentFactory.h | 7 ++- assignment-client/src/AssignmentThread.h | 9 ++- assignment-client/src/audio/AudioMixer.h | 7 ++- .../src/audio/AudioMixerClientData.h | 7 ++- .../src/audio/AvatarAudioRingBuffer.h | 7 ++- assignment-client/src/avatars/AvatarMixer.h | 7 ++- .../src/avatars/AvatarMixerClientData.h | 7 ++- .../src/metavoxels/MetavoxelServer.h | 7 ++- .../src/octree/OctreeInboundPacketProcessor.h | 9 +-- .../src/octree/OctreeQueryNode.h | 5 +- .../src/octree/OctreeSendThread.h | 8 ++- assignment-client/src/octree/OctreeServer.h | 8 ++- .../src/octree/OctreeServerConsts.h | 9 ++- .../src/particles/ParticleNodeData.h | 8 ++- .../src/particles/ParticleServer.h | 8 ++- .../src/particles/ParticleServerConsts.h | 9 ++- assignment-client/src/voxels/VoxelNodeData.h | 7 ++- assignment-client/src/voxels/VoxelServer.h | 8 ++- .../src/voxels/VoxelServerConsts.h | 9 ++- domain-server/src/DomainServer.h | 7 ++- domain-server/src/DomainServerNodeData.h | 7 ++- interface/src/AbstractLoggerInterface.h | 7 ++- interface/src/Application.h | 7 ++- interface/src/Audio.h | 7 ++- interface/src/BuckyBalls.h | 5 +- interface/src/Camera.h | 7 ++- interface/src/DatagramProcessor.h | 7 ++- interface/src/Environment.h | 7 ++- interface/src/FileLogger.h | 5 +- interface/src/GLCanvas.h | 7 ++- interface/src/Menu.h | 7 ++- interface/src/MetavoxelSystem.h | 7 ++- interface/src/ParticleTreeRenderer.h | 8 ++- interface/src/Physics.h | 7 ++- interface/src/Stars.h | 11 ++-- interface/src/Util.h | 7 ++- interface/src/XmppClient.h | 9 ++- interface/src/avatar/Avatar.h | 7 ++- interface/src/avatar/AvatarManager.h | 7 ++- interface/src/avatar/FaceModel.h | 7 ++- interface/src/avatar/Hand.h | 7 ++- interface/src/avatar/Head.h | 7 ++- interface/src/avatar/MyAvatar.h | 7 ++- interface/src/avatar/SkeletonModel.h | 7 ++- interface/src/devices/Faceshift.h | 7 ++- interface/src/devices/OculusManager.h | 7 ++- interface/src/devices/SixenseManager.h | 7 ++- interface/src/devices/TV3DManager.h | 9 ++- interface/src/devices/Visage.h | 7 ++- interface/src/location/LocationManager.h | 5 +- interface/src/location/NamedLocation.h | 5 +- .../src/renderer/AmbientOcclusionEffect.h | 7 ++- interface/src/renderer/FBXReader.h | 7 ++- interface/src/renderer/GeometryCache.h | 7 ++- interface/src/renderer/GlowEffect.h | 7 ++- interface/src/renderer/Model.h | 7 ++- interface/src/renderer/PointShader.h | 7 ++- interface/src/renderer/ProgramObject.h | 7 ++- interface/src/renderer/RenderUtil.h | 7 ++- interface/src/renderer/TextureCache.h | 7 ++- interface/src/renderer/VoxelShader.h | 7 ++- .../scripting/AudioDeviceScriptingInterface.h | 9 ++- .../scripting/ClipboardScriptingInterface.h | 7 ++- .../scripting/ControllerScriptingInterface.h | 9 ++- .../src/scripting/MenuScriptingInterface.h | 9 ++- .../scripting/SettingsScriptingInterface.h | 9 ++- interface/src/starfield/Config.h | 16 ++--- interface/src/starfield/Controller.h | 12 ++-- interface/src/starfield/Generator.h | 13 +++-- interface/src/starfield/data/GpuVertex.h | 12 ++-- interface/src/starfield/data/InputVertex.h | 12 ++-- interface/src/starfield/data/Tile.h | 11 ++-- interface/src/starfield/renderer/Renderer.h | 58 ++----------------- interface/src/starfield/renderer/Tiling.h | 11 ++-- .../src/starfield/renderer/VertexOrder.h | 11 ++-- interface/src/ui/BandwidthDialog.h | 7 ++- interface/src/ui/BandwidthMeter.h | 7 ++- interface/src/ui/ChatWindow.h | 7 ++- interface/src/ui/ImportDialog.h | 7 ++- interface/src/ui/InfoView.h | 7 ++- interface/src/ui/LodToolsDialog.h | 7 ++- interface/src/ui/LogDialog.h | 7 ++- interface/src/ui/MetavoxelEditor.h | 7 ++- interface/src/ui/ModelsBrowser.h | 7 ++- interface/src/ui/OctreeStatsDialog.h | 7 ++- interface/src/ui/Oscilloscope.h | 7 ++- interface/src/ui/RearMirrorTools.h | 9 ++- interface/src/ui/RunningScriptsWidget.h | 9 ++- interface/src/ui/Snapshot.h | 7 ++- interface/src/ui/Stats.h | 9 ++- interface/src/ui/TextRenderer.h | 7 ++- interface/src/ui/UpdateDialog.h | 8 ++- interface/src/ui/overlays/Base3DOverlay.h | 7 ++- interface/src/ui/overlays/Cube3DOverlay.h | 7 ++- interface/src/ui/overlays/ImageOverlay.h | 7 ++- interface/src/ui/overlays/Line3DOverlay.h | 7 ++- .../src/ui/overlays/LocalVoxelsOverlay.h | 7 ++- interface/src/ui/overlays/Overlay.h | 7 ++- interface/src/ui/overlays/Overlay2D.h | 7 ++- interface/src/ui/overlays/Overlays.h | 7 ++- interface/src/ui/overlays/Sphere3DOverlay.h | 7 ++- interface/src/ui/overlays/TextOverlay.h | 7 ++- interface/src/ui/overlays/Volume3DOverlay.h | 7 ++- interface/src/voxels/PrimitiveRenderer.h | 16 ++--- interface/src/voxels/VoxelFade.h | 7 ++- interface/src/voxels/VoxelHideShowThread.h | 9 +-- interface/src/voxels/VoxelImporter.h | 7 ++- interface/src/voxels/VoxelPacketProcessor.h | 7 ++- interface/src/voxels/VoxelSystem.h | 7 ++- interface/src/windowshacks.h | 9 +-- interface/src/world.h | 7 ++- libraries/audio/src/AbstractAudioInterface.h | 8 ++- libraries/audio/src/AudioInjector.h | 7 ++- libraries/audio/src/AudioInjectorOptions.h | 7 ++- libraries/audio/src/AudioRingBuffer.h | 7 ++- libraries/audio/src/AudioScriptingInterface.h | 7 ++- libraries/audio/src/InjectedAudioRingBuffer.h | 7 ++- libraries/audio/src/MixedAudioRingBuffer.h | 9 ++- .../audio/src/PositionalAudioRingBuffer.h | 7 ++- libraries/audio/src/Sound.h | 8 ++- libraries/avatars/src/AvatarData.h | 7 ++- libraries/avatars/src/AvatarHashMap.h | 7 ++- libraries/avatars/src/HandData.h | 7 ++- libraries/avatars/src/HeadData.h | 7 ++- .../embedded-webserver/src/HTTPConnection.h | 9 ++- .../embedded-webserver/src/HTTPManager.h | 9 ++- libraries/metavoxels/src/AttributeRegistry.h | 7 ++- libraries/metavoxels/src/Bitstream.h | 7 ++- libraries/metavoxels/src/DatagramSequencer.h | 7 ++- libraries/metavoxels/src/MetavoxelData.h | 7 ++- libraries/metavoxels/src/MetavoxelMessages.h | 7 ++- libraries/metavoxels/src/MetavoxelUtil.h | 7 ++- libraries/metavoxels/src/ScriptCache.h | 7 ++- libraries/metavoxels/src/SharedObject.h | 7 ++- libraries/octree/src/AABox.h | 11 ++-- libraries/octree/src/CoverageMap.h | 11 ++-- libraries/octree/src/CoverageMapV2.h | 11 ++-- libraries/octree/src/JurisdictionListener.h | 7 ++- libraries/octree/src/JurisdictionMap.h | 7 ++- libraries/octree/src/JurisdictionSender.h | 7 ++- libraries/octree/src/Octree.h | 7 ++- libraries/octree/src/OctreeConstants.h | 9 +-- libraries/octree/src/OctreeEditPacketSender.h | 7 ++- libraries/octree/src/OctreeElement.h | 7 ++- libraries/octree/src/OctreeElementBag.h | 12 ++-- libraries/octree/src/OctreeHeadlessViewer.h | 10 ++-- libraries/octree/src/OctreePacketData.h | 17 ++---- libraries/octree/src/OctreePersistThread.h | 9 +-- libraries/octree/src/OctreeProjectedPolygon.h | 10 +++- libraries/octree/src/OctreeQuery.h | 7 ++- libraries/octree/src/OctreeRenderer.h | 8 ++- libraries/octree/src/OctreeSceneStats.h | 6 +- .../octree/src/OctreeScriptingInterface.h | 9 ++- libraries/octree/src/Plane.h | 8 ++- libraries/octree/src/ViewFrustum.h | 7 ++- libraries/particles/src/Particle.h | 6 +- .../particles/src/ParticleCollisionSystem.h | 6 +- .../particles/src/ParticleEditPacketSender.h | 7 ++- libraries/particles/src/ParticleTree.h | 7 ++- libraries/particles/src/ParticleTreeElement.h | 6 +- .../src/ParticleTreeHeadlessViewer.h | 10 ++-- .../src/ParticlesScriptingInterface.h | 9 ++- .../AbstractControllerScriptingInterface.h | 9 ++- libraries/script-engine/src/EventTypes.h | 7 ++- libraries/script-engine/src/LocalVoxels.h | 7 ++- .../script-engine/src/MenuItemProperties.h | 7 ++- libraries/script-engine/src/Quat.h | 10 ++-- libraries/script-engine/src/ScriptEngine.h | 7 ++- libraries/script-engine/src/Vec3.h | 10 ++-- libraries/shared/src/AccountManager.h | 7 ++- libraries/shared/src/AngleUtil.h | 11 ++-- libraries/shared/src/Assignment.h | 7 ++- libraries/shared/src/CapsuleShape.h | 9 ++- libraries/shared/src/CollisionInfo.h | 9 ++- libraries/shared/src/DataServerAccountInfo.h | 7 ++- libraries/shared/src/DomainInfo.h | 7 ++- libraries/shared/src/FileUtils.h | 7 ++- libraries/shared/src/FloodFill.h | 8 ++- libraries/shared/src/GenericThread.h | 7 ++- libraries/shared/src/GeometryUtil.h | 7 ++- libraries/shared/src/HifiSockAddr.h | 7 ++- libraries/shared/src/ListShape.h | 8 ++- libraries/shared/src/Logging.h | 7 ++- libraries/shared/src/ModelUploader.h | 6 +- libraries/shared/src/NetworkPacket.h | 7 ++- libraries/shared/src/Node.h | 7 ++- libraries/shared/src/NodeData.h | 7 ++- libraries/shared/src/NodeList.h | 7 ++- libraries/shared/src/OAuthAccessToken.h | 7 ++- libraries/shared/src/OctalCode.h | 7 ++- libraries/shared/src/PacketHeaders.h | 8 +-- libraries/shared/src/PacketSender.h | 7 ++- libraries/shared/src/PerfStat.h | 11 ++-- libraries/shared/src/Radix2InplaceSort.h | 11 ++-- libraries/shared/src/Radix2IntegerScanner.h | 11 ++-- .../shared/src/ReceivedPacketProcessor.h | 7 ++- libraries/shared/src/RegisteredMetaTypes.h | 8 +-- libraries/shared/src/ResourceCache.h | 7 ++- libraries/shared/src/Shape.h | 8 ++- libraries/shared/src/ShapeCollider.h | 9 ++- libraries/shared/src/SharedUtil.h | 7 ++- libraries/shared/src/SimpleMovingAverage.h | 7 ++- libraries/shared/src/SphereShape.h | 9 ++- libraries/shared/src/StdDev.h | 5 +- libraries/shared/src/StreamUtils.h | 8 ++- libraries/shared/src/ThreadedAssignment.h | 7 ++- libraries/shared/src/UUID.h | 7 ++- libraries/voxels/src/EnvironmentData.h | 7 ++- libraries/voxels/src/LocalVoxelsList.h | 7 ++- libraries/voxels/src/Tags.h | 7 ++- libraries/voxels/src/VoxelConstants.h | 9 +-- libraries/voxels/src/VoxelDetail.h | 10 ++-- libraries/voxels/src/VoxelEditPacketSender.h | 7 ++- libraries/voxels/src/VoxelTree.h | 7 ++- libraries/voxels/src/VoxelTreeCommands.h | 7 ++- libraries/voxels/src/VoxelTreeElement.h | 5 +- .../voxels/src/VoxelTreeHeadlessViewer.h | 10 ++-- .../voxels/src/VoxelsScriptingInterface.h | 7 ++- voxel-edit/src/SceneUtils.h | 5 +- 223 files changed, 1148 insertions(+), 637 deletions(-) diff --git a/animation-server/src/AnimationServer.h b/animation-server/src/AnimationServer.h index cda5f8fb24..924e973599 100644 --- a/animation-server/src/AnimationServer.h +++ b/animation-server/src/AnimationServer.h @@ -1,9 +1,12 @@ // // AnimationServer.h -// hifi +// animation-server/src // // Created by Stephen Birarda on 12/5/2013. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AnimationServer__ diff --git a/assignment-client/src/Agent.h b/assignment-client/src/Agent.h index 9e5f31213c..6423514894 100644 --- a/assignment-client/src/Agent.h +++ b/assignment-client/src/Agent.h @@ -1,9 +1,12 @@ // // Agent.h -// hifi +// assignment-client/src // // Created by Stephen Birarda on 7/1/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__Agent__ diff --git a/assignment-client/src/AssignmentClient.h b/assignment-client/src/AssignmentClient.h index c267c6238b..26e3a47255 100644 --- a/assignment-client/src/AssignmentClient.h +++ b/assignment-client/src/AssignmentClient.h @@ -1,9 +1,12 @@ // // AssignmentClient.h -// hifi +// assignment-client/src // // Created by Stephen Birarda on 11/25/2013. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AssignmentClient__ diff --git a/assignment-client/src/AssignmentClientMonitor.h b/assignment-client/src/AssignmentClientMonitor.h index 259a6d6db7..4bb82ab715 100644 --- a/assignment-client/src/AssignmentClientMonitor.h +++ b/assignment-client/src/AssignmentClientMonitor.h @@ -1,9 +1,12 @@ // // AssignmentClientMonitor.h -// hifi +// assignment-client/src // // Created by Stephen Birarda on 1/10/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AssignmentClientMonitor__ diff --git a/assignment-client/src/AssignmentFactory.h b/assignment-client/src/AssignmentFactory.h index 9eff29a468..2a63bffd37 100644 --- a/assignment-client/src/AssignmentFactory.h +++ b/assignment-client/src/AssignmentFactory.h @@ -1,9 +1,12 @@ // // AssignmentFactory.h -// hifi +// assignment-client/src // // Created by Stephen Birarda on 9/17/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AssignmentFactory__ diff --git a/assignment-client/src/AssignmentThread.h b/assignment-client/src/AssignmentThread.h index b55ac10676..a76c118192 100644 --- a/assignment-client/src/AssignmentThread.h +++ b/assignment-client/src/AssignmentThread.h @@ -1,9 +1,12 @@ // // AssignmentThread.h -// hifi +// assignment-client/src // -// Created by Stephen Birarda on 2014-03-28. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Stephen Birarda on 2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AssignmentThread__ diff --git a/assignment-client/src/audio/AudioMixer.h b/assignment-client/src/audio/AudioMixer.h index 0ca241c5ed..cea8bba083 100644 --- a/assignment-client/src/audio/AudioMixer.h +++ b/assignment-client/src/audio/AudioMixer.h @@ -1,9 +1,12 @@ // // AudioMixer.h -// hifi +// assignment-client/src/audio // // Created by Stephen Birarda on 8/22/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AudioMixer__ diff --git a/assignment-client/src/audio/AudioMixerClientData.h b/assignment-client/src/audio/AudioMixerClientData.h index 7f44390ec5..aa449d20a3 100644 --- a/assignment-client/src/audio/AudioMixerClientData.h +++ b/assignment-client/src/audio/AudioMixerClientData.h @@ -1,9 +1,12 @@ // // AudioMixerClientData.h -// hifi +// assignment-client/src/audio // // Created by Stephen Birarda on 10/18/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AudioMixerClientData__ diff --git a/assignment-client/src/audio/AvatarAudioRingBuffer.h b/assignment-client/src/audio/AvatarAudioRingBuffer.h index 0d4f28467b..fb9e68543f 100644 --- a/assignment-client/src/audio/AvatarAudioRingBuffer.h +++ b/assignment-client/src/audio/AvatarAudioRingBuffer.h @@ -1,9 +1,12 @@ // // AvatarAudioRingBuffer.h -// hifi +// assignment-client/src/audio // // Created by Stephen Birarda on 6/5/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AvatarAudioRingBuffer__ diff --git a/assignment-client/src/avatars/AvatarMixer.h b/assignment-client/src/avatars/AvatarMixer.h index c9a145d2da..af25a6f0e2 100644 --- a/assignment-client/src/avatars/AvatarMixer.h +++ b/assignment-client/src/avatars/AvatarMixer.h @@ -1,9 +1,12 @@ // // AvatarMixer.h -// hifi +// assignment-client/src/avatars // // Created by Stephen Birarda on 9/5/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AvatarMixer__ diff --git a/assignment-client/src/avatars/AvatarMixerClientData.h b/assignment-client/src/avatars/AvatarMixerClientData.h index bc0a54f06b..75affca7ff 100644 --- a/assignment-client/src/avatars/AvatarMixerClientData.h +++ b/assignment-client/src/avatars/AvatarMixerClientData.h @@ -1,9 +1,12 @@ // // AvatarMixerClientData.h -// hifi +// assignment-client/src/avatars // // Created by Stephen Birarda on 2/4/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AvatarMixerClientData__ diff --git a/assignment-client/src/metavoxels/MetavoxelServer.h b/assignment-client/src/metavoxels/MetavoxelServer.h index d178127ac7..749ab93b2a 100644 --- a/assignment-client/src/metavoxels/MetavoxelServer.h +++ b/assignment-client/src/metavoxels/MetavoxelServer.h @@ -1,9 +1,12 @@ // // MetavoxelServer.h -// hifi +// assignment-client/src/metavoxels // // Created by Andrzej Kapolka on 12/18/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__MetavoxelServer__ diff --git a/assignment-client/src/octree/OctreeInboundPacketProcessor.h b/assignment-client/src/octree/OctreeInboundPacketProcessor.h index e2ec1b5c50..1a4f80b925 100644 --- a/assignment-client/src/octree/OctreeInboundPacketProcessor.h +++ b/assignment-client/src/octree/OctreeInboundPacketProcessor.h @@ -1,11 +1,12 @@ // // OctreeInboundPacketProcessor.h -// voxel-server +// assignment-client/src/octree // -// Created by Brad Hefta-Gaub on 8/21/13 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 8/21/13. +// Copyright 2013 High Fidelity, Inc. // -// Threaded or non-threaded network packet processor for the voxel-server +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __octree_server__OctreeInboundPacketProcessor__ diff --git a/assignment-client/src/octree/OctreeQueryNode.h b/assignment-client/src/octree/OctreeQueryNode.h index 17d6f6337c..6c46679a0c 100644 --- a/assignment-client/src/octree/OctreeQueryNode.h +++ b/assignment-client/src/octree/OctreeQueryNode.h @@ -1,9 +1,12 @@ // // OctreeQueryNode.h -// hifi +// assignment-client/src/octree // // Created by Brad Hefta-Gaub on 12/4/13. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__OctreeQueryNode__ diff --git a/assignment-client/src/octree/OctreeSendThread.h b/assignment-client/src/octree/OctreeSendThread.h index 4b1b6d8c92..09d5809acc 100644 --- a/assignment-client/src/octree/OctreeSendThread.h +++ b/assignment-client/src/octree/OctreeSendThread.h @@ -1,10 +1,12 @@ // // OctreeSendThread.h +// assignment-client/src/octree // -// Created by Brad Hefta-Gaub on 8/21/13 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 8/21/13. +// Copyright 2013 High Fidelity, Inc. // -// Threaded or non-threaded object for sending voxels to a client +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __octree_server__OctreeSendThread__ diff --git a/assignment-client/src/octree/OctreeServer.h b/assignment-client/src/octree/OctreeServer.h index 63d43b6634..bd37b4f896 100644 --- a/assignment-client/src/octree/OctreeServer.h +++ b/assignment-client/src/octree/OctreeServer.h @@ -1,10 +1,12 @@ // // OctreeServer.h -// voxel-server +// assignment-client/src/octree // -// Created by Brad Hefta-Gaub on 8/21/13 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 8/21/13. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __octree_server__OctreeServer__ diff --git a/assignment-client/src/octree/OctreeServerConsts.h b/assignment-client/src/octree/OctreeServerConsts.h index fae03a73ca..995a7d5b24 100644 --- a/assignment-client/src/octree/OctreeServerConsts.h +++ b/assignment-client/src/octree/OctreeServerConsts.h @@ -1,9 +1,12 @@ +// // OctreeServerConsts.h -// octree-server +// assignment-client/src/octree // -// Created by Brad Hefta-Gaub on 12/4/13 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 12/4/13. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __octree_server__OctreeServerConsts__ diff --git a/assignment-client/src/particles/ParticleNodeData.h b/assignment-client/src/particles/ParticleNodeData.h index 450767613e..d6995ebb0c 100644 --- a/assignment-client/src/particles/ParticleNodeData.h +++ b/assignment-client/src/particles/ParticleNodeData.h @@ -1,10 +1,12 @@ // // ParticleNodeData.h -// hifi +// assignment-client/src/particles // -// Created by Brad Hefta-Gaub on 12/4/13 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 12/4/13. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__ParticleNodeData__ diff --git a/assignment-client/src/particles/ParticleServer.h b/assignment-client/src/particles/ParticleServer.h index 4e6a896475..8371ba0301 100644 --- a/assignment-client/src/particles/ParticleServer.h +++ b/assignment-client/src/particles/ParticleServer.h @@ -1,10 +1,12 @@ // // ParticleServer.h -// particle-server +// assignment-client/src/particles // -// Created by Brad Hefta-Gaub on 12/2/13 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 12/2/13. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __particle_server__ParticleServer__ diff --git a/assignment-client/src/particles/ParticleServerConsts.h b/assignment-client/src/particles/ParticleServerConsts.h index 5ac2a1534b..be9764ffbf 100644 --- a/assignment-client/src/particles/ParticleServerConsts.h +++ b/assignment-client/src/particles/ParticleServerConsts.h @@ -1,9 +1,12 @@ +// // ParticleServerConsts.h -// particle-server +// assignment-client/src/particles // -// Created by Brad Hefta-Gaub on 8/21/13 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 8/21/13. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __particle_server__ParticleServerConsts__ diff --git a/assignment-client/src/voxels/VoxelNodeData.h b/assignment-client/src/voxels/VoxelNodeData.h index c24bfad6ce..da6f41c10e 100644 --- a/assignment-client/src/voxels/VoxelNodeData.h +++ b/assignment-client/src/voxels/VoxelNodeData.h @@ -1,9 +1,12 @@ // // VoxelNodeData.h -// hifi +// assignment-client/src/voxels // // Created by Stephen Birarda on 3/21/13. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__VoxelNodeData__ diff --git a/assignment-client/src/voxels/VoxelServer.h b/assignment-client/src/voxels/VoxelServer.h index 2e97736963..2014012f2c 100644 --- a/assignment-client/src/voxels/VoxelServer.h +++ b/assignment-client/src/voxels/VoxelServer.h @@ -1,10 +1,12 @@ // // VoxelServer.h -// voxel-server +// assignment-client/src/voxels // -// Created by Brad Hefta-Gaub on 8/21/13 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 8/21/13. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __voxel_server__VoxelServer__ diff --git a/assignment-client/src/voxels/VoxelServerConsts.h b/assignment-client/src/voxels/VoxelServerConsts.h index ce6fd86a32..373a75f1e8 100644 --- a/assignment-client/src/voxels/VoxelServerConsts.h +++ b/assignment-client/src/voxels/VoxelServerConsts.h @@ -1,9 +1,12 @@ +// // VoxelServerConsts.h -// voxel-server +// assignment-client/src/voxels // -// Created by Brad Hefta-Gaub on 8/21/13 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 8/21/13. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __voxel_server__VoxelServerConsts__ diff --git a/domain-server/src/DomainServer.h b/domain-server/src/DomainServer.h index 597be7f50d..9a1853bdcc 100644 --- a/domain-server/src/DomainServer.h +++ b/domain-server/src/DomainServer.h @@ -1,9 +1,12 @@ // // DomainServer.h -// hifi +// domain-server/src // // Created by Stephen Birarda on 9/26/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__DomainServer__ diff --git a/domain-server/src/DomainServerNodeData.h b/domain-server/src/DomainServerNodeData.h index 20531839f4..6da91c54fb 100644 --- a/domain-server/src/DomainServerNodeData.h +++ b/domain-server/src/DomainServerNodeData.h @@ -1,9 +1,12 @@ // // DomainServerNodeData.h -// hifi +// domain-server/src // // Created by Stephen Birarda on 2/6/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__DomainServerNodeData__ diff --git a/interface/src/AbstractLoggerInterface.h b/interface/src/AbstractLoggerInterface.h index cedab1fad2..647c104743 100644 --- a/interface/src/AbstractLoggerInterface.h +++ b/interface/src/AbstractLoggerInterface.h @@ -1,9 +1,12 @@ // // AbstractLoggerInterface.h -// interface +// interface/src // // Created by Stojce Slavkovski on 12/22/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__AbstractLoggerInterface__ diff --git a/interface/src/Application.h b/interface/src/Application.h index 7c1cb9cab1..e7af91e997 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -1,9 +1,12 @@ // // Application.h -// interface +// interface/src // // Created by Andrzej Kapolka on 5/10/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Application__ diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 88488922f3..647b88a4a9 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -1,9 +1,12 @@ // // Audio.h -// interface +// interface/src // // Created by Stephen Birarda on 1/22/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Audio__ diff --git a/interface/src/BuckyBalls.h b/interface/src/BuckyBalls.h index 705f85517f..305ac4640c 100644 --- a/interface/src/BuckyBalls.h +++ b/interface/src/BuckyBalls.h @@ -1,9 +1,12 @@ // // BuckyBalls.h -// hifi +// interface/src // // Created by Philip on 1/2/14. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__BuckyBalls__ diff --git a/interface/src/Camera.h b/interface/src/Camera.h index 3fd0efd50a..6e4b533cdc 100644 --- a/interface/src/Camera.h +++ b/interface/src/Camera.h @@ -1,8 +1,11 @@ // // Camera.h -// interface +// interface/src // -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__camera__ diff --git a/interface/src/DatagramProcessor.h b/interface/src/DatagramProcessor.h index 722e5a9d41..6a55820e9d 100644 --- a/interface/src/DatagramProcessor.h +++ b/interface/src/DatagramProcessor.h @@ -1,9 +1,12 @@ // // DatagramProcessor.h -// hifi +// interface/src // // Created by Stephen Birarda on 1/23/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__DatagramProcessor__ diff --git a/interface/src/Environment.h b/interface/src/Environment.h index 1c9ee578c3..aca5fac9d8 100644 --- a/interface/src/Environment.h +++ b/interface/src/Environment.h @@ -1,9 +1,12 @@ // // Environment.h -// interface +// interface/src // // Created by Andrzej Kapolka on 5/6/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Environment__ diff --git a/interface/src/FileLogger.h b/interface/src/FileLogger.h index 35cafa4db7..a65aa3321c 100644 --- a/interface/src/FileLogger.h +++ b/interface/src/FileLogger.h @@ -1,9 +1,12 @@ // // FileLogger.h -// hifi +// interface/src // // Created by Stojce Slavkovski on 12/22/13. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef hifi_FileLogger_h diff --git a/interface/src/GLCanvas.h b/interface/src/GLCanvas.h index f7f7fb7c20..0b75ef5c5f 100644 --- a/interface/src/GLCanvas.h +++ b/interface/src/GLCanvas.h @@ -1,9 +1,12 @@ // // GLCanvas.h -// hifi +// interface/src // // Created by Stephen Birarda on 8/14/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__GLCanvas__ diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 7bb0b75675..2b90d4e3c9 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -1,9 +1,12 @@ // // Menu.h -// hifi +// interface/src // // Created by Stephen Birarda on 8/12/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__Menu__ diff --git a/interface/src/MetavoxelSystem.h b/interface/src/MetavoxelSystem.h index ecab30d535..cc6fa6e743 100644 --- a/interface/src/MetavoxelSystem.h +++ b/interface/src/MetavoxelSystem.h @@ -1,9 +1,12 @@ // // MetavoxelSystem.h -// interface +// interface/src // // Created by Andrzej Kapolka on 12/10/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__MetavoxelSystem__ diff --git a/interface/src/ParticleTreeRenderer.h b/interface/src/ParticleTreeRenderer.h index fe346ae730..531cbc23f7 100644 --- a/interface/src/ParticleTreeRenderer.h +++ b/interface/src/ParticleTreeRenderer.h @@ -1,10 +1,12 @@ // // ParticleTreeRenderer.h -// hifi +// interface/src // // Created by Brad Hefta-Gaub on 12/6/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__ParticleTreeRenderer__ @@ -49,4 +51,4 @@ protected: QMap _particleModels; }; -#endif /* defined(__hifi__ParticleTreeRenderer__) */ \ No newline at end of file +#endif /* defined(__hifi__ParticleTreeRenderer__) */ diff --git a/interface/src/Physics.h b/interface/src/Physics.h index 699497c187..bf1673a0fe 100644 --- a/interface/src/Physics.h +++ b/interface/src/Physics.h @@ -1,9 +1,12 @@ // -// Balls.h -// hifi +// Physics.h +// interface/src // // Created by Philip on 4/25/13. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef hifi_Physics_h diff --git a/interface/src/Stars.h b/interface/src/Stars.h index f6fe7cfb80..b38c1a2748 100755 --- a/interface/src/Stars.h +++ b/interface/src/Stars.h @@ -1,9 +1,12 @@ // -// Stars.h -// interface +// Stars.h +// interface/src // -// Created by Tobias Schwinger on 3/22/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Tobias Schwinger on 3/22/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Stars__ diff --git a/interface/src/Util.h b/interface/src/Util.h index 732a36b98d..26a3c85e3c 100644 --- a/interface/src/Util.h +++ b/interface/src/Util.h @@ -1,9 +1,12 @@ // // Util.h -// interface +// interface/src // // Created by Philip Rosedale on 8/24/12. -// Copyright (c) 2012 High Fidelity, Inc. All rights reserved. +// Copyright 2012 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 __interface__Util__ diff --git a/interface/src/XmppClient.h b/interface/src/XmppClient.h index 905d6e64fb..ac724a4d68 100644 --- a/interface/src/XmppClient.h +++ b/interface/src/XmppClient.h @@ -1,9 +1,12 @@ // // XmppClient.h -// interface +// interface/src // -// Created by Dimitar Dobrev on 10/3/14 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Dimitar Dobrev on 10/3/14. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifdef HAVE_QXMPP diff --git a/interface/src/avatar/Avatar.h b/interface/src/avatar/Avatar.h index f57982b514..a1bc7ad0bd 100755 --- a/interface/src/avatar/Avatar.h +++ b/interface/src/avatar/Avatar.h @@ -1,8 +1,11 @@ // // Avatar.h -// interface +// interface/src/avatar // -// Copyright (c) 2012 High Fidelity, Inc. All rights reserved. +// Copyright 2012 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 __interface__avatar__ diff --git a/interface/src/avatar/AvatarManager.h b/interface/src/avatar/AvatarManager.h index bd04dddb78..db3c9dbf44 100644 --- a/interface/src/avatar/AvatarManager.h +++ b/interface/src/avatar/AvatarManager.h @@ -1,9 +1,12 @@ // // AvatarManager.h -// hifi +// interface/src/avatar // // Created by Stephen Birarda on 1/23/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AvatarManager__ diff --git a/interface/src/avatar/FaceModel.h b/interface/src/avatar/FaceModel.h index d675495e6b..3fec640bdd 100644 --- a/interface/src/avatar/FaceModel.h +++ b/interface/src/avatar/FaceModel.h @@ -1,9 +1,12 @@ // // FaceModel.h -// interface +// interface/src/avatar // // Created by Andrzej Kapolka on 9/16/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__FaceModel__ diff --git a/interface/src/avatar/Hand.h b/interface/src/avatar/Hand.h index 3be3bc0f77..f3054a7080 100755 --- a/interface/src/avatar/Hand.h +++ b/interface/src/avatar/Hand.h @@ -1,8 +1,11 @@ // // Hand.h -// interface +// interface/src/avatar // -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef hifi_Hand_h diff --git a/interface/src/avatar/Head.h b/interface/src/avatar/Head.h index 36ab6a9229..f4840121a6 100644 --- a/interface/src/avatar/Head.h +++ b/interface/src/avatar/Head.h @@ -1,8 +1,11 @@ // // Head.h -// interface +// interface/src/avatar // -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef hifi_Head_h diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index 2125b126b3..d0589687df 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -1,9 +1,12 @@ // // MyAvatar.h -// interface +// interface/src/avatar // // Created by Mark Peng on 8/16/13. -// Copyright (c) 2012 High Fidelity, Inc. All rights reserved. +// Copyright 2012 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 __interface__myavatar__ diff --git a/interface/src/avatar/SkeletonModel.h b/interface/src/avatar/SkeletonModel.h index 31867dec5c..b3a7c4c7e4 100644 --- a/interface/src/avatar/SkeletonModel.h +++ b/interface/src/avatar/SkeletonModel.h @@ -1,9 +1,12 @@ // // SkeletonModel.h -// interface +// interface/src/avatar // // Created by Andrzej Kapolka on 10/17/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__SkeletonModel__ diff --git a/interface/src/devices/Faceshift.h b/interface/src/devices/Faceshift.h index f878056b57..abac2c74a1 100644 --- a/interface/src/devices/Faceshift.h +++ b/interface/src/devices/Faceshift.h @@ -1,9 +1,12 @@ // // Faceshift.h -// interface +// interface/src/devices // // Created by Andrzej Kapolka on 9/3/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Faceshift__ diff --git a/interface/src/devices/OculusManager.h b/interface/src/devices/OculusManager.h index b3cd400ac8..7927c84341 100644 --- a/interface/src/devices/OculusManager.h +++ b/interface/src/devices/OculusManager.h @@ -1,9 +1,12 @@ // // OculusManager.h -// hifi +// interface/src/devices // // Created by Stephen Birarda on 5/9/13. -// Copyright (c) 2012 High Fidelity, Inc. All rights reserved. +// Copyright 2012 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__OculusManager__ diff --git a/interface/src/devices/SixenseManager.h b/interface/src/devices/SixenseManager.h index de4cccb399..24c37a027f 100644 --- a/interface/src/devices/SixenseManager.h +++ b/interface/src/devices/SixenseManager.h @@ -1,9 +1,12 @@ // // SixenseManager.h -// interface +// interface/src/devices // // Created by Andrzej Kapolka on 11/15/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__SixenseManager__ diff --git a/interface/src/devices/TV3DManager.h b/interface/src/devices/TV3DManager.h index edea489745..aa1f927676 100644 --- a/interface/src/devices/TV3DManager.h +++ b/interface/src/devices/TV3DManager.h @@ -1,9 +1,12 @@ // // TV3DManager.h -// hifi +// interface/src/devices // -// Created by Brad Hefta-Gaub on 12/24/2013 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 12/24/2013. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__TV3DManager__ diff --git a/interface/src/devices/Visage.h b/interface/src/devices/Visage.h index 6e98abbb61..02cceb8afa 100644 --- a/interface/src/devices/Visage.h +++ b/interface/src/devices/Visage.h @@ -1,9 +1,12 @@ // // Visage.h -// interface +// interface/src/devices // // Created by Andrzej Kapolka on 2/11/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Visage__ diff --git a/interface/src/location/LocationManager.h b/interface/src/location/LocationManager.h index a6bdaf66b4..cda64e5058 100644 --- a/interface/src/location/LocationManager.h +++ b/interface/src/location/LocationManager.h @@ -1,9 +1,12 @@ // // LocationManager.h -// hifi +// interface/src/location // // Created by Stojce Slavkovski on 2/7/14. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__LocationManager__ diff --git a/interface/src/location/NamedLocation.h b/interface/src/location/NamedLocation.h index 81af03b45e..7aa020f8e9 100644 --- a/interface/src/location/NamedLocation.h +++ b/interface/src/location/NamedLocation.h @@ -1,9 +1,12 @@ // // NamedLocation.h -// hifi +// interface/src/location // // Created by Stojce Slavkovski on 2/1/14. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__NamedLocation__ diff --git a/interface/src/renderer/AmbientOcclusionEffect.h b/interface/src/renderer/AmbientOcclusionEffect.h index e56164bad4..1711b89d16 100644 --- a/interface/src/renderer/AmbientOcclusionEffect.h +++ b/interface/src/renderer/AmbientOcclusionEffect.h @@ -1,9 +1,12 @@ // // AmbientOcclusionEffect.h -// interface +// interface/src/renderer // // Created by Andrzej Kapolka on 7/14/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__AmbientOcclusionEffect__ diff --git a/interface/src/renderer/FBXReader.h b/interface/src/renderer/FBXReader.h index 2847d2a971..85ca23c53f 100644 --- a/interface/src/renderer/FBXReader.h +++ b/interface/src/renderer/FBXReader.h @@ -1,9 +1,12 @@ // // FBXReader.h -// interface +// interface/src/renderer // // Created by Andrzej Kapolka on 9/18/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__FBXReader__ diff --git a/interface/src/renderer/GeometryCache.h b/interface/src/renderer/GeometryCache.h index 252a0c401b..ea6b3c2e0f 100644 --- a/interface/src/renderer/GeometryCache.h +++ b/interface/src/renderer/GeometryCache.h @@ -1,9 +1,12 @@ // // GeometryCache.h -// interface +// interface/src/renderer // // Created by Andrzej Kapolka on 6/21/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__GeometryCache__ diff --git a/interface/src/renderer/GlowEffect.h b/interface/src/renderer/GlowEffect.h index 65d3d6c8ce..cf635083c6 100644 --- a/interface/src/renderer/GlowEffect.h +++ b/interface/src/renderer/GlowEffect.h @@ -1,9 +1,12 @@ // // GlowEffect.h -// interface +// interface/src/renderer // // Created by Andrzej Kapolka on 8/7/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__GlowEffect__ diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index 134a3e2172..dea5e3aa59 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -1,9 +1,12 @@ // // Model.h -// interface +// interface/src/renderer // // Created by Andrzej Kapolka on 10/18/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Model__ diff --git a/interface/src/renderer/PointShader.h b/interface/src/renderer/PointShader.h index b7e1b8c008..f67e2239cc 100644 --- a/interface/src/renderer/PointShader.h +++ b/interface/src/renderer/PointShader.h @@ -1,9 +1,12 @@ // // PointShader.h -// interface +// interface/src/renderer // // Created by Brad Hefta-Gaub on 10/30/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__PointShader__ diff --git a/interface/src/renderer/ProgramObject.h b/interface/src/renderer/ProgramObject.h index 78f07b7a1b..3c902cd215 100644 --- a/interface/src/renderer/ProgramObject.h +++ b/interface/src/renderer/ProgramObject.h @@ -1,9 +1,12 @@ // // ProgramObject.h -// interface +// interface/src/renderer // // Created by Andrzej Kapolka on 5/7/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__ProgramObject__ diff --git a/interface/src/renderer/RenderUtil.h b/interface/src/renderer/RenderUtil.h index 5e7e9b5d64..fb71f46e9e 100644 --- a/interface/src/renderer/RenderUtil.h +++ b/interface/src/renderer/RenderUtil.h @@ -1,9 +1,12 @@ // // RenderUtil.h -// interface +// interface/src/renderer // // Created by Andrzej Kapolka on 8/15/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__RenderUtil__ diff --git a/interface/src/renderer/TextureCache.h b/interface/src/renderer/TextureCache.h index dc874ab7b0..d8884c310f 100644 --- a/interface/src/renderer/TextureCache.h +++ b/interface/src/renderer/TextureCache.h @@ -1,9 +1,12 @@ // // TextureCache.h -// interface +// interface/src/renderer // // Created by Andrzej Kapolka on 8/6/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__TextureCache__ diff --git a/interface/src/renderer/VoxelShader.h b/interface/src/renderer/VoxelShader.h index 33e8ea0073..4d8a4c749c 100644 --- a/interface/src/renderer/VoxelShader.h +++ b/interface/src/renderer/VoxelShader.h @@ -1,9 +1,12 @@ // // VoxelShader.h -// interface +// interface/src/renderer // // Created by Brad Hefta-Gaub on 9/23/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__VoxelShader__ diff --git a/interface/src/scripting/AudioDeviceScriptingInterface.h b/interface/src/scripting/AudioDeviceScriptingInterface.h index adc86cb15c..0495517139 100644 --- a/interface/src/scripting/AudioDeviceScriptingInterface.h +++ b/interface/src/scripting/AudioDeviceScriptingInterface.h @@ -1,9 +1,12 @@ // // AudioDeviceScriptingInterface.h -// hifi +// interface/src/scripting // -// Created by Brad Hefta-Gaub on 3/22/14 -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 3/22/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AudioDeviceScriptingInterface__ diff --git a/interface/src/scripting/ClipboardScriptingInterface.h b/interface/src/scripting/ClipboardScriptingInterface.h index 78e72d6de0..16872b1952 100644 --- a/interface/src/scripting/ClipboardScriptingInterface.h +++ b/interface/src/scripting/ClipboardScriptingInterface.h @@ -1,10 +1,11 @@ // // ClipboardScriptingInterface.h -// interface +// interface/src/scripting // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // -// Scriptable interface for the Application clipboard +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Clipboard__ diff --git a/interface/src/scripting/ControllerScriptingInterface.h b/interface/src/scripting/ControllerScriptingInterface.h index ada146ff02..ebe5f4d943 100644 --- a/interface/src/scripting/ControllerScriptingInterface.h +++ b/interface/src/scripting/ControllerScriptingInterface.h @@ -1,9 +1,12 @@ // // ControllerScriptingInterface.h -// hifi +// interface/src/scripting // -// Created by Brad Hefta-Gaub on 12/17/13 -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 12/17/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__ControllerScriptingInterface__ diff --git a/interface/src/scripting/MenuScriptingInterface.h b/interface/src/scripting/MenuScriptingInterface.h index a4496e3054..15042fd355 100644 --- a/interface/src/scripting/MenuScriptingInterface.h +++ b/interface/src/scripting/MenuScriptingInterface.h @@ -1,9 +1,12 @@ // // MenuScriptingInterface.h -// hifi +// interface/src/scripting // -// Created by Brad Hefta-Gaub on 2/25/14 -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 2/25/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__MenuScriptingInterface__ diff --git a/interface/src/scripting/SettingsScriptingInterface.h b/interface/src/scripting/SettingsScriptingInterface.h index 12bda2173f..84855c1b3c 100644 --- a/interface/src/scripting/SettingsScriptingInterface.h +++ b/interface/src/scripting/SettingsScriptingInterface.h @@ -1,9 +1,12 @@ // // SettingsScriptingInterface.h -// hifi +// interface/src/scripting // -// Created by Brad Hefta-Gaub on 3/22/14 -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 3/22/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__SettingsScriptingInterface__ diff --git a/interface/src/starfield/Config.h b/interface/src/starfield/Config.h index b92aec9a4c..6f44f24093 100755 --- a/interface/src/starfield/Config.h +++ b/interface/src/starfield/Config.h @@ -1,16 +1,12 @@ // -// starfield/Config.h -// interface +// Config.h +// interface/src/starfield // -// Created by Tobias Schwinger on 3/29/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Tobias Schwinger on 3/29/13. +// Copyright 2013 High Fidelity, Inc. // - -#ifndef __interface__starfield__Config__ -#define __interface__starfield__Config__ - -// -// Dependencies: +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "InterfaceConfig.h" diff --git a/interface/src/starfield/Controller.h b/interface/src/starfield/Controller.h index 5403d2fb75..12963fa2e2 100755 --- a/interface/src/starfield/Controller.h +++ b/interface/src/starfield/Controller.h @@ -1,10 +1,12 @@ // -// starfield/Controller.h -// interface +// Controller.h +// interface/src/starfield // -// Created by Tobias Schwinger on 3/29/13. -// Modified by Chris Barnard 10/16/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Tobias Schwinger on 3/29/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__starfield__Controller__ diff --git a/interface/src/starfield/Generator.h b/interface/src/starfield/Generator.h index 1029bd6a52..238ff99f80 100644 --- a/interface/src/starfield/Generator.h +++ b/interface/src/starfield/Generator.h @@ -1,9 +1,12 @@ // -// starfield/Generator.h -// interface +// Generator.h +// interface/src/starfield // -// Created by Chris Barnard on 10/13/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Chris Barnard on 10/13/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__starfield__Generator__ @@ -34,4 +37,4 @@ namespace starfield { }; } -#endif \ No newline at end of file +#endif diff --git a/interface/src/starfield/data/GpuVertex.h b/interface/src/starfield/data/GpuVertex.h index 39eeb19634..7c435a559f 100755 --- a/interface/src/starfield/data/GpuVertex.h +++ b/interface/src/starfield/data/GpuVertex.h @@ -1,10 +1,12 @@ // -// starfield/data/GpuVertex.h -// interface +// GpuVertex.h +// interface/src/starfield/data // -// Created by Tobias Schwinger on 3/29/13. -// Modified 10/17/13 Chris Barnard. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Tobias Schwinger on 3/29/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__starfield__data__GpuVertex__ diff --git a/interface/src/starfield/data/InputVertex.h b/interface/src/starfield/data/InputVertex.h index d8c21a37a2..01b15c297f 100755 --- a/interface/src/starfield/data/InputVertex.h +++ b/interface/src/starfield/data/InputVertex.h @@ -1,10 +1,12 @@ // -// starfield/data/InputVertex.h -// interface +// InputVertex.h +// interface/src/starfield/data // -// Created by Tobias Schwinger on 3/29/13. -// Modified by Chris Barnard 10/17/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Tobias Schwinger on 3/29/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__starfield__data__InputVertex__ diff --git a/interface/src/starfield/data/Tile.h b/interface/src/starfield/data/Tile.h index bdef4e612f..17e737af38 100755 --- a/interface/src/starfield/data/Tile.h +++ b/interface/src/starfield/data/Tile.h @@ -1,9 +1,12 @@ // -// starfield/data/Tile.h -// interface +// Tile.h +// interface/src/starfield/data // -// Created by Tobias Schwinger on 3/22/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Tobias Schwinger on 3/22/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__starfield__data__Tile__ diff --git a/interface/src/starfield/renderer/Renderer.h b/interface/src/starfield/renderer/Renderer.h index 7504dd0182..7eaeb1444e 100755 --- a/interface/src/starfield/renderer/Renderer.h +++ b/interface/src/starfield/renderer/Renderer.h @@ -1,58 +1,12 @@ // -// starfield/renderer/Renderer.h -// interface +// Renderer.h +// interface/src/starfield/renderer // -// Created by Tobias Schwinger on 3/22/13. -// Modified 10/17/13 Chris Barnard. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Tobias Schwinger on 3/22/13. +// Copyright 2013 High Fidelity, Inc. // - -#ifndef __interface__starfield__renderer__Renderer__ -#define __interface__starfield__renderer__Renderer__ - -#include "starfield/Config.h" -#include "starfield/data/InputVertex.h" -#include "starfield/data/Tile.h" -#include "starfield/data/GpuVertex.h" -#include "starfield/renderer/Tiling.h" - -// -// FOV culling -// =========== -// -// As stars can be thought of as at infinity distance, the field of view only -// depends on perspective and rotation: -// -// _----_ <-- visible stars -// from above +-near-+ - - -// \ / | -// near width: \ / | cos(p/2) -// 2sin(p/2) \/ _ -// center -// -// -// Now it is important to note that a change in altitude maps uniformly to a -// distance on a sphere. This is NOT the case for azimuthal angles: In this -// case a factor of 'cos(alt)' (the orbital radius) applies: -// -// -// |<-cos alt ->| | |<-|<----->|->| d_azi cos(alt) -// | -// __--* | --------- - -// __-- * | | | ^ d_alt -// __-- alt) * | | | v -// --------------*- | ------------- - -// | -// side view | tile on sphere -// -// -// This lets us find a worst-case (Eigen) angle from the center to the edge -// of a tile as -// -// hypot( 0.5 d_alt, 0.5 d_azi cos(alt_absmin) ). -// -// This angle must be added to 'p' (the perspective angle) in order to find -// an altered near plane for the culling decision. +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // namespace starfield { diff --git a/interface/src/starfield/renderer/Tiling.h b/interface/src/starfield/renderer/Tiling.h index d4a1446690..91547d87ca 100755 --- a/interface/src/starfield/renderer/Tiling.h +++ b/interface/src/starfield/renderer/Tiling.h @@ -1,9 +1,12 @@ // -// starfield/renderer/Tiling.h -// interface +// Tiling.h +// interface/src/starfield/renderer // -// Created by Tobias Schwinger on 3/22/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Tobias Schwinger on 3/22/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__starfield__renderer__Tiling__ diff --git a/interface/src/starfield/renderer/VertexOrder.h b/interface/src/starfield/renderer/VertexOrder.h index 85c738ce0d..704af857cf 100755 --- a/interface/src/starfield/renderer/VertexOrder.h +++ b/interface/src/starfield/renderer/VertexOrder.h @@ -1,9 +1,12 @@ // -// starfield/renderer/VertexOrder.h -// interface +// VertexOrder.h +// interface/src/starfield/renderer // -// Created by Tobias Schwinger on 3/22/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Tobias Schwinger on 3/22/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__starfield__renderer__VertexOrder__ diff --git a/interface/src/ui/BandwidthDialog.h b/interface/src/ui/BandwidthDialog.h index a702b1be23..51ed3453cd 100644 --- a/interface/src/ui/BandwidthDialog.h +++ b/interface/src/ui/BandwidthDialog.h @@ -1,9 +1,12 @@ // // BandwidthDialog.h -// interface +// interface/src/ui // // Created by Tobias Schwinger on 6/21/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__BandwidthDialog__ diff --git a/interface/src/ui/BandwidthMeter.h b/interface/src/ui/BandwidthMeter.h index c1577da8e4..830bc6502d 100644 --- a/interface/src/ui/BandwidthMeter.h +++ b/interface/src/ui/BandwidthMeter.h @@ -1,9 +1,12 @@ // // BandwidthMeter.h -// interface +// interface/src/ui // // Created by Tobias Schwinger on 6/20/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__BandwidthMeter__ diff --git a/interface/src/ui/ChatWindow.h b/interface/src/ui/ChatWindow.h index da8d423b9d..9ab17c067b 100644 --- a/interface/src/ui/ChatWindow.h +++ b/interface/src/ui/ChatWindow.h @@ -1,9 +1,12 @@ // // ChatWindow.h -// interface +// interface/src/ui // // Created by Dimitar Dobrev on 3/6/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__ChatWindow__ diff --git a/interface/src/ui/ImportDialog.h b/interface/src/ui/ImportDialog.h index 278fac932d..dc707395de 100644 --- a/interface/src/ui/ImportDialog.h +++ b/interface/src/ui/ImportDialog.h @@ -1,9 +1,12 @@ // // ImportDialog.h -// hifi +// interface/src/ui // // Created by Clement Brisset on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__ImportDialog__ diff --git a/interface/src/ui/InfoView.h b/interface/src/ui/InfoView.h index 009587c1d5..a400e8dacf 100644 --- a/interface/src/ui/InfoView.h +++ b/interface/src/ui/InfoView.h @@ -1,9 +1,12 @@ // // InfoView.h -// hifi +// interface/src/ui // // Created by Stojce Slavkovski on 9/7/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__InfoView__ diff --git a/interface/src/ui/LodToolsDialog.h b/interface/src/ui/LodToolsDialog.h index 98a5fce5f8..200fb44ca1 100644 --- a/interface/src/ui/LodToolsDialog.h +++ b/interface/src/ui/LodToolsDialog.h @@ -1,9 +1,12 @@ // // LodToolsDialog.h -// interface +// interface/src/ui // // Created by Brad Hefta-Gaub on 7/19/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__LodToolsDialog__ diff --git a/interface/src/ui/LogDialog.h b/interface/src/ui/LogDialog.h index 5138e231c7..c4d4676189 100644 --- a/interface/src/ui/LogDialog.h +++ b/interface/src/ui/LogDialog.h @@ -1,9 +1,12 @@ // // LogDialog.h -// interface +// interface/src/ui // // Created by Stojce Slavkovski on 12/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__LogDialog__ diff --git a/interface/src/ui/MetavoxelEditor.h b/interface/src/ui/MetavoxelEditor.h index 7f3521bd1a..f0e8dff7ec 100644 --- a/interface/src/ui/MetavoxelEditor.h +++ b/interface/src/ui/MetavoxelEditor.h @@ -1,9 +1,12 @@ // // MetavoxelEditor.h -// interface +// interface/src/ui // // Created by Andrzej Kapolka on 1/21/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__MetavoxelEditor__ diff --git a/interface/src/ui/ModelsBrowser.h b/interface/src/ui/ModelsBrowser.h index 30320de1c1..01b3e2e405 100644 --- a/interface/src/ui/ModelsBrowser.h +++ b/interface/src/ui/ModelsBrowser.h @@ -1,9 +1,12 @@ // // ModelsBrowser.h -// hifi +// interface/src/ui // // Created by Clement on 3/17/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__ModelsBrowser__ diff --git a/interface/src/ui/OctreeStatsDialog.h b/interface/src/ui/OctreeStatsDialog.h index ef190e6a52..0a0d7af5fd 100644 --- a/interface/src/ui/OctreeStatsDialog.h +++ b/interface/src/ui/OctreeStatsDialog.h @@ -1,9 +1,12 @@ // // OctreeStatsDialog.h -// interface +// interface/src/ui // // Created by Brad Hefta-Gaub on 7/19/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__OctreeStatsDialog__ diff --git a/interface/src/ui/Oscilloscope.h b/interface/src/ui/Oscilloscope.h index a245f79f05..d51a1d8242 100644 --- a/interface/src/ui/Oscilloscope.h +++ b/interface/src/ui/Oscilloscope.h @@ -1,9 +1,12 @@ // // Oscilloscope.h -// interface +// interface/src/ui // // Created by Philip on 1/28/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Oscilloscope__ diff --git a/interface/src/ui/RearMirrorTools.h b/interface/src/ui/RearMirrorTools.h index 007b54f129..f410b0b5ff 100644 --- a/interface/src/ui/RearMirrorTools.h +++ b/interface/src/ui/RearMirrorTools.h @@ -1,9 +1,12 @@ // // RearMirrorTools.h -// interface +// interface/src/ui // -// Created by stojce on 23.10.2013. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by stojce on 23. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__RearMirrorTools__ diff --git a/interface/src/ui/RunningScriptsWidget.h b/interface/src/ui/RunningScriptsWidget.h index 5d365dae91..718c417ba8 100644 --- a/interface/src/ui/RunningScriptsWidget.h +++ b/interface/src/ui/RunningScriptsWidget.h @@ -1,9 +1,12 @@ // -// RunningScripts.h -// interface +// RunningScriptsWidget.h +// interface/src/ui // // Created by Mohammed Nafees on 03/28/2014. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__RunningScriptsWidget__ diff --git a/interface/src/ui/Snapshot.h b/interface/src/ui/Snapshot.h index 1b78e8328e..ec5e9d5f13 100644 --- a/interface/src/ui/Snapshot.h +++ b/interface/src/ui/Snapshot.h @@ -1,9 +1,12 @@ // // Snapshot.h -// hifi +// interface/src/ui // // Created by Stojce Slavkovski on 1/26/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__Snapshot__ diff --git a/interface/src/ui/Stats.h b/interface/src/ui/Stats.h index 7920c35953..ad2a3c9bf5 100644 --- a/interface/src/ui/Stats.h +++ b/interface/src/ui/Stats.h @@ -1,9 +1,12 @@ // // Stats.h -// interface +// interface/src/ui // // Created by Lucas Crisman on 22/03/14. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include @@ -38,4 +41,4 @@ private: int _voxelStatsWidth; int _lastHorizontalOffset; -}; \ No newline at end of file +}; diff --git a/interface/src/ui/TextRenderer.h b/interface/src/ui/TextRenderer.h index d6c24c1ce8..a24612ab93 100644 --- a/interface/src/ui/TextRenderer.h +++ b/interface/src/ui/TextRenderer.h @@ -1,9 +1,12 @@ // // TextRenderer.h -// interface +// interface/src/ui // // Created by Andrzej Kapolka on 4/26/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__TextRenderer__ diff --git a/interface/src/ui/UpdateDialog.h b/interface/src/ui/UpdateDialog.h index 14f4e6f39c..e346330f71 100644 --- a/interface/src/ui/UpdateDialog.h +++ b/interface/src/ui/UpdateDialog.h @@ -1,9 +1,11 @@ // // UpdateDialog.h -// interface +// interface/src/ui // -// Created by Leonardo Murillo on 1/8/14. -// Copyright (c) 2013, 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__UpdateDialog__ diff --git a/interface/src/ui/overlays/Base3DOverlay.h b/interface/src/ui/overlays/Base3DOverlay.h index 286193393c..c464bfc2a7 100644 --- a/interface/src/ui/overlays/Base3DOverlay.h +++ b/interface/src/ui/overlays/Base3DOverlay.h @@ -1,8 +1,11 @@ // // Base3DOverlay.h -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Base3DOverlay__ diff --git a/interface/src/ui/overlays/Cube3DOverlay.h b/interface/src/ui/overlays/Cube3DOverlay.h index a1705d47d0..0bdebea5b2 100644 --- a/interface/src/ui/overlays/Cube3DOverlay.h +++ b/interface/src/ui/overlays/Cube3DOverlay.h @@ -1,8 +1,11 @@ // // Cube3DOverlay.h -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Cube3DOverlay__ diff --git a/interface/src/ui/overlays/ImageOverlay.h b/interface/src/ui/overlays/ImageOverlay.h index d6165e388d..9d3f21fdae 100644 --- a/interface/src/ui/overlays/ImageOverlay.h +++ b/interface/src/ui/overlays/ImageOverlay.h @@ -1,8 +1,11 @@ // // ImageOverlay.h -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__ImageOverlay__ diff --git a/interface/src/ui/overlays/Line3DOverlay.h b/interface/src/ui/overlays/Line3DOverlay.h index d52b639d59..250be03cd4 100644 --- a/interface/src/ui/overlays/Line3DOverlay.h +++ b/interface/src/ui/overlays/Line3DOverlay.h @@ -1,8 +1,11 @@ // // Line3DOverlay.h -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Line3DOverlay__ diff --git a/interface/src/ui/overlays/LocalVoxelsOverlay.h b/interface/src/ui/overlays/LocalVoxelsOverlay.h index 2b3ba1f535..bdc4273693 100644 --- a/interface/src/ui/overlays/LocalVoxelsOverlay.h +++ b/interface/src/ui/overlays/LocalVoxelsOverlay.h @@ -1,11 +1,12 @@ // // LocalVoxelsOverlay.h -// hifi +// interface/src/ui/overlays // // Created by Clément Brisset on 2/28/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // -// Scriptable interface for LocalVoxels +// 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__LocalVoxelsOverlay__ diff --git a/interface/src/ui/overlays/Overlay.h b/interface/src/ui/overlays/Overlay.h index ad1084e889..a80d6a403f 100644 --- a/interface/src/ui/overlays/Overlay.h +++ b/interface/src/ui/overlays/Overlay.h @@ -1,8 +1,11 @@ // // Overlay.h -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Overlay__ diff --git a/interface/src/ui/overlays/Overlay2D.h b/interface/src/ui/overlays/Overlay2D.h index 3da8f8bca4..cb9c588603 100644 --- a/interface/src/ui/overlays/Overlay2D.h +++ b/interface/src/ui/overlays/Overlay2D.h @@ -1,8 +1,11 @@ // // Overlay2D.h -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Overlay2D__ diff --git a/interface/src/ui/overlays/Overlays.h b/interface/src/ui/overlays/Overlays.h index c28f3ab83b..f6cbabe1f9 100644 --- a/interface/src/ui/overlays/Overlays.h +++ b/interface/src/ui/overlays/Overlays.h @@ -1,8 +1,11 @@ // // Overlays.h -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Overlays__ diff --git a/interface/src/ui/overlays/Sphere3DOverlay.h b/interface/src/ui/overlays/Sphere3DOverlay.h index 58ed0d7776..0fbfc5e3de 100644 --- a/interface/src/ui/overlays/Sphere3DOverlay.h +++ b/interface/src/ui/overlays/Sphere3DOverlay.h @@ -1,8 +1,11 @@ // // Sphere3DOverlay.h -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Sphere3DOverlay__ diff --git a/interface/src/ui/overlays/TextOverlay.h b/interface/src/ui/overlays/TextOverlay.h index d565aeb70d..9ea7a724b8 100644 --- a/interface/src/ui/overlays/TextOverlay.h +++ b/interface/src/ui/overlays/TextOverlay.h @@ -1,8 +1,11 @@ // // TextOverlay.h -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__TextOverlay__ diff --git a/interface/src/ui/overlays/Volume3DOverlay.h b/interface/src/ui/overlays/Volume3DOverlay.h index 8badbf2c33..a90074822b 100644 --- a/interface/src/ui/overlays/Volume3DOverlay.h +++ b/interface/src/ui/overlays/Volume3DOverlay.h @@ -1,8 +1,11 @@ // // Volume3DOverlay.h -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Volume3DOverlay__ diff --git a/interface/src/voxels/PrimitiveRenderer.h b/interface/src/voxels/PrimitiveRenderer.h index 51d96e0840..92536190e2 100644 --- a/interface/src/voxels/PrimitiveRenderer.h +++ b/interface/src/voxels/PrimitiveRenderer.h @@ -1,10 +1,12 @@ -/// -/// @file PrimitiveRenderer.h -/// A geometric primitive renderer. -/// -/// @author: Norman Crafts -/// @copyright 2014, High Fidelity, Inc. All rights reserved. -/// +// +// PrimitiveRenderer.h +// interface/src/voxels +// +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// #ifndef __interface__PrimitiveRenderer__ #define __interface__PrimitiveRenderer__ diff --git a/interface/src/voxels/VoxelFade.h b/interface/src/voxels/VoxelFade.h index fd7a73135b..2bfe65f03b 100644 --- a/interface/src/voxels/VoxelFade.h +++ b/interface/src/voxels/VoxelFade.h @@ -1,9 +1,12 @@ // // VoxelFade.h -// interface +// interface/src/voxels // // Created by Brad Hefta-Gaub on 8/6/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__VoxelFade__ diff --git a/interface/src/voxels/VoxelHideShowThread.h b/interface/src/voxels/VoxelHideShowThread.h index dc1f2062c1..29aa53f430 100644 --- a/interface/src/voxels/VoxelHideShowThread.h +++ b/interface/src/voxels/VoxelHideShowThread.h @@ -1,11 +1,12 @@ // // VoxelHideShowThread.h -// voxel-server +// interface/src/voxels // -// Created by Brad Hefta-Gaub on 12/1/13 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 12/1/13. +// Copyright 2013 High Fidelity, Inc. // -// Threaded or non-threaded voxel persistence +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__VoxelHideShowThread__ diff --git a/interface/src/voxels/VoxelImporter.h b/interface/src/voxels/VoxelImporter.h index 9ebfc2eef2..fb9fe7b589 100644 --- a/interface/src/voxels/VoxelImporter.h +++ b/interface/src/voxels/VoxelImporter.h @@ -1,9 +1,12 @@ // // VoxelImporter.h -// hifi +// interface/src/voxels // // Created by Clement Brisset on 8/9/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__VoxelImporter__ diff --git a/interface/src/voxels/VoxelPacketProcessor.h b/interface/src/voxels/VoxelPacketProcessor.h index 2acd347e99..c71bc07c31 100644 --- a/interface/src/voxels/VoxelPacketProcessor.h +++ b/interface/src/voxels/VoxelPacketProcessor.h @@ -1,11 +1,12 @@ // // VoxelPacketProcessor.h -// interface +// interface/src/voxels // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Voxel Packet Receiver +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __shared__VoxelPacketProcessor__ diff --git a/interface/src/voxels/VoxelSystem.h b/interface/src/voxels/VoxelSystem.h index bdc55450dd..eae7e21246 100644 --- a/interface/src/voxels/VoxelSystem.h +++ b/interface/src/voxels/VoxelSystem.h @@ -1,9 +1,12 @@ // // VoxelSystem.h -// interface +// interface/src/voxels // // Created by Philip on 12/31/12. -// Copyright (c) 2012 High Fidelity, Inc. All rights reserved. +// Copyright 2012 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 __interface__VoxelSystem__ diff --git a/interface/src/windowshacks.h b/interface/src/windowshacks.h index aae7b2f923..07ef69c6f0 100644 --- a/interface/src/windowshacks.h +++ b/interface/src/windowshacks.h @@ -1,11 +1,12 @@ // // windowshacks.h -// hifi +// interface/src // // Created by Brad Hefta-Gaub on 1/12/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // -// hacks to get windows to compile +// 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__windowshacks__ @@ -54,4 +55,4 @@ inline int c99_snprintf(char* str, size_t size, const char* format, ...) { #endif // WIN32 -#endif // __hifi__windowshacks__ \ No newline at end of file +#endif // __hifi__windowshacks__ diff --git a/interface/src/world.h b/interface/src/world.h index 8d857303ae..95767e7b15 100644 --- a/interface/src/world.h +++ b/interface/src/world.h @@ -1,9 +1,12 @@ // // world.h -// interface +// interface/src // // Created by Philip Rosedale on 8/23/12. -// Copyright (c) 2012 High Fidelity, Inc. All rights reserved. +// Copyright 2012 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 __interface__world__ diff --git a/libraries/audio/src/AbstractAudioInterface.h b/libraries/audio/src/AbstractAudioInterface.h index dc3872efd5..28cb0653f8 100644 --- a/libraries/audio/src/AbstractAudioInterface.h +++ b/libraries/audio/src/AbstractAudioInterface.h @@ -1,10 +1,12 @@ // // AbstractAudioInterface.h -// hifi +// libraries/audio/src // // Created by Brad Hefta-Gaub on 12/4/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AbstractAudioInterface__ @@ -25,4 +27,4 @@ public slots: Q_DECLARE_METATYPE(AbstractAudioInterface*) -#endif /* defined(__hifi__AbstractAudioInterface__) */ \ No newline at end of file +#endif /* defined(__hifi__AbstractAudioInterface__) */ diff --git a/libraries/audio/src/AudioInjector.h b/libraries/audio/src/AudioInjector.h index beff33a9ef..988ea46444 100644 --- a/libraries/audio/src/AudioInjector.h +++ b/libraries/audio/src/AudioInjector.h @@ -1,9 +1,12 @@ // // AudioInjector.h -// hifi +// libraries/audio/src // // Created by Stephen Birarda on 1/2/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AudioInjector__ diff --git a/libraries/audio/src/AudioInjectorOptions.h b/libraries/audio/src/AudioInjectorOptions.h index 0c70ad43cb..866f95bde4 100644 --- a/libraries/audio/src/AudioInjectorOptions.h +++ b/libraries/audio/src/AudioInjectorOptions.h @@ -1,9 +1,12 @@ // // AudioInjectorOptions.h -// hifi +// libraries/audio/src // // Created by Stephen Birarda on 1/2/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AudioInjectorOptions__ diff --git a/libraries/audio/src/AudioRingBuffer.h b/libraries/audio/src/AudioRingBuffer.h index e55eeda40e..7a1a75e43b 100644 --- a/libraries/audio/src/AudioRingBuffer.h +++ b/libraries/audio/src/AudioRingBuffer.h @@ -1,9 +1,12 @@ // // AudioRingBuffer.h -// interface +// libraries/audio/src // // Created by Stephen Birarda on 2/1/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__AudioRingBuffer__ diff --git a/libraries/audio/src/AudioScriptingInterface.h b/libraries/audio/src/AudioScriptingInterface.h index f758923513..9371597075 100644 --- a/libraries/audio/src/AudioScriptingInterface.h +++ b/libraries/audio/src/AudioScriptingInterface.h @@ -1,9 +1,12 @@ // // AudioScriptingInterface.h -// hifi +// libraries/audio/src // // Created by Stephen Birarda on 1/2/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AudioScriptingInterface__ diff --git a/libraries/audio/src/InjectedAudioRingBuffer.h b/libraries/audio/src/InjectedAudioRingBuffer.h index d4dfb5e360..8a1a430c78 100644 --- a/libraries/audio/src/InjectedAudioRingBuffer.h +++ b/libraries/audio/src/InjectedAudioRingBuffer.h @@ -1,9 +1,12 @@ // // InjectedAudioRingBuffer.h -// hifi +// libraries/audio/src // // Created by Stephen Birarda on 6/5/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__InjectedAudioRingBuffer__ diff --git a/libraries/audio/src/MixedAudioRingBuffer.h b/libraries/audio/src/MixedAudioRingBuffer.h index c116361689..2d672f6ada 100644 --- a/libraries/audio/src/MixedAudioRingBuffer.h +++ b/libraries/audio/src/MixedAudioRingBuffer.h @@ -1,9 +1,12 @@ // // MixedAudioRingBuffer.h -// hifi +// libraries/audio/src // -// Created by Stephen Birarda on 2014-03-26. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Created by Stephen Birarda on 2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__MixedAudioRingBuffer__ diff --git a/libraries/audio/src/PositionalAudioRingBuffer.h b/libraries/audio/src/PositionalAudioRingBuffer.h index a82df0b857..c34e6f8bc7 100644 --- a/libraries/audio/src/PositionalAudioRingBuffer.h +++ b/libraries/audio/src/PositionalAudioRingBuffer.h @@ -1,9 +1,12 @@ // // PositionalAudioRingBuffer.h -// hifi +// libraries/audio/src // // Created by Stephen Birarda on 6/5/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__PositionalAudioRingBuffer__ diff --git a/libraries/audio/src/Sound.h b/libraries/audio/src/Sound.h index 7956343d46..27e46bec57 100644 --- a/libraries/audio/src/Sound.h +++ b/libraries/audio/src/Sound.h @@ -1,10 +1,12 @@ // // Sound.h -// hifi +// libraries/audio/src // // Created by Stephen Birarda on 1/2/2014. -// Modified by Athanasios Gaitatzes to add WAVE file support. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__Sound__ diff --git a/libraries/avatars/src/AvatarData.h b/libraries/avatars/src/AvatarData.h index cf645855e8..79c2075323 100755 --- a/libraries/avatars/src/AvatarData.h +++ b/libraries/avatars/src/AvatarData.h @@ -1,9 +1,12 @@ // // AvatarData.h -// hifi +// libraries/avatars/src // // Created by Stephen Birarda on 4/9/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AvatarData__ diff --git a/libraries/avatars/src/AvatarHashMap.h b/libraries/avatars/src/AvatarHashMap.h index 19b6623402..fcfd735073 100644 --- a/libraries/avatars/src/AvatarHashMap.h +++ b/libraries/avatars/src/AvatarHashMap.h @@ -1,9 +1,12 @@ // // AvatarHashMap.h -// hifi +// libraries/avatars/src // // Created by Stephen AndrewMeadows on 1/28/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AvatarHashMap__ diff --git a/libraries/avatars/src/HandData.h b/libraries/avatars/src/HandData.h index 9ebdc8dcf6..662ad493b1 100755 --- a/libraries/avatars/src/HandData.h +++ b/libraries/avatars/src/HandData.h @@ -1,9 +1,12 @@ // // HandData.h -// hifi +// libraries/avatars/src // // Created by Eric Johnston on 6/26/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__HandData__ diff --git a/libraries/avatars/src/HeadData.h b/libraries/avatars/src/HeadData.h index c60627e3f9..044966da04 100644 --- a/libraries/avatars/src/HeadData.h +++ b/libraries/avatars/src/HeadData.h @@ -1,9 +1,12 @@ // // HeadData.h -// hifi +// libraries/avatars/src // // Created by Stephen Birarda on 5/20/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__HeadData__ diff --git a/libraries/embedded-webserver/src/HTTPConnection.h b/libraries/embedded-webserver/src/HTTPConnection.h index dbf1e31f47..2da4027334 100644 --- a/libraries/embedded-webserver/src/HTTPConnection.h +++ b/libraries/embedded-webserver/src/HTTPConnection.h @@ -1,13 +1,12 @@ // // HTTPConnection.h -// hifi +// libraries/embedded-webserver/src // // Created by Stephen Birarda on 1/16/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // -// Heavily based on Andrzej Kapolka's original HTTPConnection class -// found from another one of his projects. -// https://github.com/ey6es/witgap/tree/master/src/cpp/server/http +// 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__HTTPConnection__ diff --git a/libraries/embedded-webserver/src/HTTPManager.h b/libraries/embedded-webserver/src/HTTPManager.h index a8f9d723fa..91f185de2e 100755 --- a/libraries/embedded-webserver/src/HTTPManager.h +++ b/libraries/embedded-webserver/src/HTTPManager.h @@ -1,13 +1,12 @@ // // HTTPManager.h -// hifi +// libraries/embedded-webserver/src // // Created by Stephen Birarda on 1/16/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // -// Heavily based on Andrzej Kapolka's original HTTPManager class -// found from another one of his projects. -// https://github.com/ey6es/witgap/tree/master/src/cpp/server/http +// 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__HTTPManager__ diff --git a/libraries/metavoxels/src/AttributeRegistry.h b/libraries/metavoxels/src/AttributeRegistry.h index db13ea9f4e..084ef4426f 100644 --- a/libraries/metavoxels/src/AttributeRegistry.h +++ b/libraries/metavoxels/src/AttributeRegistry.h @@ -1,9 +1,12 @@ // // AttributeRegistry.h -// metavoxels +// libraries/metavoxels/src // // Created by Andrzej Kapolka on 12/6/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__AttributeRegistry__ diff --git a/libraries/metavoxels/src/Bitstream.h b/libraries/metavoxels/src/Bitstream.h index d7b16fcc4a..3c5f738730 100644 --- a/libraries/metavoxels/src/Bitstream.h +++ b/libraries/metavoxels/src/Bitstream.h @@ -1,9 +1,12 @@ // // Bitstream.h -// metavoxels +// libraries/metavoxels/src // // Created by Andrzej Kapolka on 12/2/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__Bitstream__ diff --git a/libraries/metavoxels/src/DatagramSequencer.h b/libraries/metavoxels/src/DatagramSequencer.h index 30a131390d..40a8a7e9e7 100644 --- a/libraries/metavoxels/src/DatagramSequencer.h +++ b/libraries/metavoxels/src/DatagramSequencer.h @@ -1,9 +1,12 @@ // // DatagramSequencer.h -// metavoxels +// libraries/metavoxels/src // // Created by Andrzej Kapolka on 12/20/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__DatagramSequencer__ diff --git a/libraries/metavoxels/src/MetavoxelData.h b/libraries/metavoxels/src/MetavoxelData.h index 7a53598042..49df417b71 100644 --- a/libraries/metavoxels/src/MetavoxelData.h +++ b/libraries/metavoxels/src/MetavoxelData.h @@ -1,9 +1,12 @@ // // MetavoxelData.h -// metavoxels +// libraries/metavoxels/src // // Created by Andrzej Kapolka on 12/6/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__MetavoxelData__ diff --git a/libraries/metavoxels/src/MetavoxelMessages.h b/libraries/metavoxels/src/MetavoxelMessages.h index 4f90a52e4c..d4d2183091 100644 --- a/libraries/metavoxels/src/MetavoxelMessages.h +++ b/libraries/metavoxels/src/MetavoxelMessages.h @@ -1,9 +1,12 @@ // // MetavoxelMessages.h -// metavoxels +// libraries/metavoxels/src // // Created by Andrzej Kapolka on 12/31/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__MetavoxelMessages__ diff --git a/libraries/metavoxels/src/MetavoxelUtil.h b/libraries/metavoxels/src/MetavoxelUtil.h index cc6c540151..e72408b9ed 100644 --- a/libraries/metavoxels/src/MetavoxelUtil.h +++ b/libraries/metavoxels/src/MetavoxelUtil.h @@ -1,9 +1,12 @@ // // MetavoxelUtil.h -// metavoxels +// libraries/metavoxels/src // // Created by Andrzej Kapolka on 12/30/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__MetavoxelUtil__ diff --git a/libraries/metavoxels/src/ScriptCache.h b/libraries/metavoxels/src/ScriptCache.h index ac53e602f8..810da46eb2 100644 --- a/libraries/metavoxels/src/ScriptCache.h +++ b/libraries/metavoxels/src/ScriptCache.h @@ -1,9 +1,12 @@ // // ScriptCache.h -// metavoxels +// libraries/metavoxels/src // // Created by Andrzej Kapolka on 2/4/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__ScriptCache__ diff --git a/libraries/metavoxels/src/SharedObject.h b/libraries/metavoxels/src/SharedObject.h index 2751a66db3..736984fa41 100644 --- a/libraries/metavoxels/src/SharedObject.h +++ b/libraries/metavoxels/src/SharedObject.h @@ -1,9 +1,12 @@ // // SharedObject.h -// metavoxels +// libraries/metavoxels/src // // Created by Andrzej Kapolka on 2/5/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__SharedObject__ diff --git a/libraries/octree/src/AABox.h b/libraries/octree/src/AABox.h index 731b82be4c..2b9be1246f 100644 --- a/libraries/octree/src/AABox.h +++ b/libraries/octree/src/AABox.h @@ -1,11 +1,12 @@ // -// AABox.h - Axis Aligned Boxes -// hifi +// AABox.h +// libraries/octree/src // -// Added by Brad Hefta-Gaub on 04/11/13. -// Originally from lighthouse3d. Modified to utilize glm::vec3 and clean up to our coding standards +// Created by Brad Hefta-Gaub on 04/11/13. +// Copyright 2013 High Fidelity, Inc. // -// Simple axis aligned box class. +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef _AABOX_ diff --git a/libraries/octree/src/CoverageMap.h b/libraries/octree/src/CoverageMap.h index 9cdda579e8..d1fada141e 100644 --- a/libraries/octree/src/CoverageMap.h +++ b/libraries/octree/src/CoverageMap.h @@ -1,9 +1,12 @@ // -// CoverageMap.h - 2D CoverageMap Quad tree for storage of OctreeProjectedPolygons -// hifi +// CoverageMap.h +// libraries/octree/src // -// Added by Brad Hefta-Gaub on 06/11/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 06/11/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef _COVERAGE_MAP_ diff --git a/libraries/octree/src/CoverageMapV2.h b/libraries/octree/src/CoverageMapV2.h index e7c2eed4fe..7221c7d5de 100644 --- a/libraries/octree/src/CoverageMapV2.h +++ b/libraries/octree/src/CoverageMapV2.h @@ -1,9 +1,12 @@ // -// CoverageMapV2.h - 2D CoverageMapV2 Quad tree for storage of OctreeProjectedPolygons -// hifi +// CoverageMapV2.h +// libraries/octree/src // -// Added by Brad Hefta-Gaub on 06/11/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 06/11/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef _COVERAGE_MAP_V2_ diff --git a/libraries/octree/src/JurisdictionListener.h b/libraries/octree/src/JurisdictionListener.h index b3dc9664d7..981f7d1a42 100644 --- a/libraries/octree/src/JurisdictionListener.h +++ b/libraries/octree/src/JurisdictionListener.h @@ -1,11 +1,12 @@ // // JurisdictionListener.h -// shared +// libraries/octree/src // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Voxel Packet Sender +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __shared__JurisdictionListener__ diff --git a/libraries/octree/src/JurisdictionMap.h b/libraries/octree/src/JurisdictionMap.h index 06305254d1..4c189bfac0 100644 --- a/libraries/octree/src/JurisdictionMap.h +++ b/libraries/octree/src/JurisdictionMap.h @@ -1,9 +1,12 @@ // // JurisdictionMap.h -// hifi +// libraries/octree/src // // Created by Brad Hefta-Gaub on 8/1/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__JurisdictionMap__ diff --git a/libraries/octree/src/JurisdictionSender.h b/libraries/octree/src/JurisdictionSender.h index 18365fda63..20c54824e7 100644 --- a/libraries/octree/src/JurisdictionSender.h +++ b/libraries/octree/src/JurisdictionSender.h @@ -1,11 +1,12 @@ // // JurisdictionSender.h -// shared +// libraries/octree/src // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Jurisdiction Sender +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __shared__JurisdictionSender__ diff --git a/libraries/octree/src/Octree.h b/libraries/octree/src/Octree.h index f029431d87..6451b91a26 100644 --- a/libraries/octree/src/Octree.h +++ b/libraries/octree/src/Octree.h @@ -1,9 +1,12 @@ // // Octree.h -// hifi +// libraries/octree/src // // Created by Stephen Birarda on 3/13/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__Octree__ diff --git a/libraries/octree/src/OctreeConstants.h b/libraries/octree/src/OctreeConstants.h index 82f4acea66..ceb3a4de20 100644 --- a/libraries/octree/src/OctreeConstants.h +++ b/libraries/octree/src/OctreeConstants.h @@ -1,11 +1,12 @@ // // OctreeConstants.h -// hifi +// libraries/octree/src // // Created by Brad Hefta-Gaub on 4/29/13. +// Copyright 2013 High Fidelity, Inc. // -// -// Various important constants used throughout the system related to voxels +// 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_OctreeConstants_h__ @@ -43,4 +44,4 @@ const int DANGEROUSLY_DEEP_RECURSION = 200; // use this for something that needs const int DEFAULT_MAX_OCTREE_PPS = 600; // the default maximum PPS we think any octree based server should send to a client -#endif \ No newline at end of file +#endif diff --git a/libraries/octree/src/OctreeEditPacketSender.h b/libraries/octree/src/OctreeEditPacketSender.h index 75ad02a1c6..36d2f837cf 100644 --- a/libraries/octree/src/OctreeEditPacketSender.h +++ b/libraries/octree/src/OctreeEditPacketSender.h @@ -1,11 +1,12 @@ // // OctreeEditPacketSender.h -// shared +// libraries/octree/src // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Octree Edit Packet Sender +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __shared__OctreeEditPacketSender__ diff --git a/libraries/octree/src/OctreeElement.h b/libraries/octree/src/OctreeElement.h index a37866bdbe..b634acdf2a 100644 --- a/libraries/octree/src/OctreeElement.h +++ b/libraries/octree/src/OctreeElement.h @@ -1,9 +1,12 @@ // // OctreeElement.h -// hifi +// libraries/octree/src // // Created by Stephen Birarda on 3/13/13. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__OctreeElement__ @@ -316,4 +319,4 @@ protected: static quint64 _childrenCount[NUMBER_OF_CHILDREN + 1]; }; -#endif /* defined(__hifi__OctreeElement__) */ \ No newline at end of file +#endif /* defined(__hifi__OctreeElement__) */ diff --git a/libraries/octree/src/OctreeElementBag.h b/libraries/octree/src/OctreeElementBag.h index ba74a05516..fa3cbf0319 100644 --- a/libraries/octree/src/OctreeElementBag.h +++ b/libraries/octree/src/OctreeElementBag.h @@ -1,14 +1,12 @@ // // OctreeElementBag.h -// hifi +// libraries/octree/src // -// Created by Brad Hefta-Gaub on 4/25/2013 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 4/25/2013. +// Copyright 2013 High Fidelity, Inc. // -// This class is used by the VoxelTree:encodeTreeBitstream() functions to store extra nodes that need to be sent -// it's a generic bag style storage mechanism. But It has the property that you can't put the same node into the bag -// more than once (in other words, it de-dupes automatically), also, it supports collapsing it's several peer nodes -// into a parent node in cases where you add enough peers that it makes more sense to just add the parent. +// 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__OctreeElementBag__ diff --git a/libraries/octree/src/OctreeHeadlessViewer.h b/libraries/octree/src/OctreeHeadlessViewer.h index fc32dbc682..5d98d0291f 100644 --- a/libraries/octree/src/OctreeHeadlessViewer.h +++ b/libraries/octree/src/OctreeHeadlessViewer.h @@ -1,10 +1,12 @@ // // OctreeHeadlessViewer.h -// hifi +// libraries/octree/src // -// Created by Brad Hefta-Gaub on 2/26/14 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 2/26/14. +// Copyright 2014 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__OctreeHeadlessViewer__ @@ -70,4 +72,4 @@ private: int _maxPacketsPerSecond; }; -#endif /* defined(__hifi__OctreeHeadlessViewer__) */ \ No newline at end of file +#endif /* defined(__hifi__OctreeHeadlessViewer__) */ diff --git a/libraries/octree/src/OctreePacketData.h b/libraries/octree/src/OctreePacketData.h index 5d7a904a4c..1efea6c217 100644 --- a/libraries/octree/src/OctreePacketData.h +++ b/libraries/octree/src/OctreePacketData.h @@ -1,19 +1,12 @@ // // OctreePacketData.h -// hifi +// libraries/octree/src // -// Created by Brad Hefta-Gaub on 11/19/2013 +// Created by Brad Hefta-Gaub on 11/19/2013. +// Copyright 2013 High Fidelity, Inc. // -// TO DO: -// -// * add stats tracking for number of unique colors and consecutive identical colors. -// (as research for color dictionaries and RLE) -// -// * further testing of compression to determine optimal configuration for performance and compression -// -// * improve semantics for "reshuffle" - current approach will work for now and with compression -// but wouldn't work with RLE because the colors in the levels would get reordered and RLE would need -// to be recalculated +// 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__OctreePacketData__ diff --git a/libraries/octree/src/OctreePersistThread.h b/libraries/octree/src/OctreePersistThread.h index ce6190b0e6..8d96ac945d 100644 --- a/libraries/octree/src/OctreePersistThread.h +++ b/libraries/octree/src/OctreePersistThread.h @@ -1,11 +1,12 @@ // // OctreePersistThread.h -// Octree-server +// libraries/octree/src // -// Created by Brad Hefta-Gaub on 8/21/13 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 8/21/13. +// Copyright 2013 High Fidelity, Inc. // -// Threaded or non-threaded Octree persistence +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __Octree_server__OctreePersistThread__ diff --git a/libraries/octree/src/OctreeProjectedPolygon.h b/libraries/octree/src/OctreeProjectedPolygon.h index 94e55a11d5..e551a6c005 100644 --- a/libraries/octree/src/OctreeProjectedPolygon.h +++ b/libraries/octree/src/OctreeProjectedPolygon.h @@ -1,8 +1,12 @@ // -// OctreeProjectedPolygon.h - The projected shadow (on the 2D view plane) for a voxel -// hifi +// OctreeProjectedPolygon.h +// libraries/octree/src // -// Added by Brad Hefta-Gaub on 06/11/13. +// Created by Brad Hefta-Gaub on 06/11/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef _VOXEL_PROJECTED_SHADOW_ diff --git a/libraries/octree/src/OctreeQuery.h b/libraries/octree/src/OctreeQuery.h index 3b53aaa501..6e2b651a5b 100644 --- a/libraries/octree/src/OctreeQuery.h +++ b/libraries/octree/src/OctreeQuery.h @@ -1,9 +1,12 @@ // // OctreeQuery.h -// hifi +// libraries/octree/src // // Created by Stephen Birarda on 4/9/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__OctreeQuery__ diff --git a/libraries/octree/src/OctreeRenderer.h b/libraries/octree/src/OctreeRenderer.h index 2e9762a883..e61ac145b8 100644 --- a/libraries/octree/src/OctreeRenderer.h +++ b/libraries/octree/src/OctreeRenderer.h @@ -1,10 +1,12 @@ // // OctreeRenderer.h -// hifi +// libraries/octree/src // // Created by Brad Hefta-Gaub on 12/6/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__OctreeRenderer__ @@ -69,4 +71,4 @@ protected: ViewFrustum* _viewFrustum; }; -#endif /* defined(__hifi__OctreeRenderer__) */ \ No newline at end of file +#endif /* defined(__hifi__OctreeRenderer__) */ diff --git a/libraries/octree/src/OctreeSceneStats.h b/libraries/octree/src/OctreeSceneStats.h index 866c5d0b85..b74fbbc8d1 100644 --- a/libraries/octree/src/OctreeSceneStats.h +++ b/libraries/octree/src/OctreeSceneStats.h @@ -1,10 +1,12 @@ // // OctreeSceneStats.h -// hifi +// libraries/octree/src // // Created by Brad Hefta-Gaub on 7/18/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__OctreeSceneStats__ diff --git a/libraries/octree/src/OctreeScriptingInterface.h b/libraries/octree/src/OctreeScriptingInterface.h index 3003950bbf..4c6c6aa54f 100644 --- a/libraries/octree/src/OctreeScriptingInterface.h +++ b/libraries/octree/src/OctreeScriptingInterface.h @@ -1,9 +1,12 @@ // // OctreeScriptingInterface.h -// hifi +// libraries/octree/src // -// Created by Brad Hefta-Gaub on 12/6/13 -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 12/6/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__OctreeScriptingInterface__ diff --git a/libraries/octree/src/Plane.h b/libraries/octree/src/Plane.h index 48bef064f6..1a37499183 100755 --- a/libraries/octree/src/Plane.h +++ b/libraries/octree/src/Plane.h @@ -1,12 +1,16 @@ // // Plane.h -// hifi +// libraries/octree/src/ // // Created by Brad Hefta-Gaub on 04/11/13. -// Originally from lighthouse3d. Modified to utilize glm::vec3 and clean up to our coding standards +// Copyright 2013 High Fidelity, Inc. // +// Originally from lighthouse3d. Modified to utilize glm::vec3 and clean up to our coding standards // Simple plane class. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// #ifndef _PLANE_ #define _PLANE_ diff --git a/libraries/octree/src/ViewFrustum.h b/libraries/octree/src/ViewFrustum.h index 7a1c3b49ba..6553dab1a1 100644 --- a/libraries/octree/src/ViewFrustum.h +++ b/libraries/octree/src/ViewFrustum.h @@ -1,11 +1,12 @@ // // ViewFrustum.h -// hifi +// libraries/octree/src // // Created by Brad Hefta-Gaub on 04/11/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Simple view frustum class. +// 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__ViewFrustum__ diff --git a/libraries/particles/src/Particle.h b/libraries/particles/src/Particle.h index dbe98c5bf6..8a49dd273a 100644 --- a/libraries/particles/src/Particle.h +++ b/libraries/particles/src/Particle.h @@ -1,10 +1,12 @@ // // Particle.h -// hifi +// libraries/particles/src // // Created by Brad Hefta-Gaub on 12/4/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__Particle__ diff --git a/libraries/particles/src/ParticleCollisionSystem.h b/libraries/particles/src/ParticleCollisionSystem.h index c6ab97c02b..50e262a736 100644 --- a/libraries/particles/src/ParticleCollisionSystem.h +++ b/libraries/particles/src/ParticleCollisionSystem.h @@ -1,10 +1,12 @@ // // ParticleCollisionSystem.h -// hifi +// libraries/particles/src // // Created by Brad Hefta-Gaub on 12/4/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__ParticleCollisionSystem__ diff --git a/libraries/particles/src/ParticleEditPacketSender.h b/libraries/particles/src/ParticleEditPacketSender.h index 3169c5629d..3a22b311a5 100644 --- a/libraries/particles/src/ParticleEditPacketSender.h +++ b/libraries/particles/src/ParticleEditPacketSender.h @@ -1,11 +1,12 @@ // // ParticleEditPacketSender.h -// shared +// libraries/particles/src // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Voxel Packet Sender +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __shared__ParticleEditPacketSender__ diff --git a/libraries/particles/src/ParticleTree.h b/libraries/particles/src/ParticleTree.h index f3b8f5183d..20503085a2 100644 --- a/libraries/particles/src/ParticleTree.h +++ b/libraries/particles/src/ParticleTree.h @@ -1,9 +1,12 @@ // // ParticleTree.h -// hifi +// libraries/particles/src // // Created by Brad Hefta-Gaub on 12/4/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__ParticleTree__ diff --git a/libraries/particles/src/ParticleTreeElement.h b/libraries/particles/src/ParticleTreeElement.h index 2854066f3b..95ba27b51e 100644 --- a/libraries/particles/src/ParticleTreeElement.h +++ b/libraries/particles/src/ParticleTreeElement.h @@ -1,10 +1,12 @@ // // ParticleTreeElement.h -// hifi +// libraries/particles/src // // Created by Brad Hefta-Gaub on 12/4/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__ParticleTreeElement__ diff --git a/libraries/particles/src/ParticleTreeHeadlessViewer.h b/libraries/particles/src/ParticleTreeHeadlessViewer.h index 08aa12280c..eafef3cf34 100644 --- a/libraries/particles/src/ParticleTreeHeadlessViewer.h +++ b/libraries/particles/src/ParticleTreeHeadlessViewer.h @@ -1,10 +1,12 @@ // // ParticleTreeHeadlessViewer.h -// hifi +// libraries/particles/src // -// Created by Brad Hefta-Gaub on 2/26/14 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 2/26/14. +// Copyright 2014 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__ParticleTreeHeadlessViewer__ @@ -39,4 +41,4 @@ public: virtual void init(); }; -#endif /* defined(__hifi__ParticleTreeHeadlessViewer__) */ \ No newline at end of file +#endif /* defined(__hifi__ParticleTreeHeadlessViewer__) */ diff --git a/libraries/particles/src/ParticlesScriptingInterface.h b/libraries/particles/src/ParticlesScriptingInterface.h index 8de44e20bb..dbf80efa61 100644 --- a/libraries/particles/src/ParticlesScriptingInterface.h +++ b/libraries/particles/src/ParticlesScriptingInterface.h @@ -1,9 +1,12 @@ // // ParticlesScriptingInterface.h -// hifi +// libraries/particles/src // -// Created by Brad Hefta-Gaub on 12/6/13 -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 12/6/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__ParticlesScriptingInterface__ diff --git a/libraries/script-engine/src/AbstractControllerScriptingInterface.h b/libraries/script-engine/src/AbstractControllerScriptingInterface.h index 1878edd4d6..23f1cc8477 100644 --- a/libraries/script-engine/src/AbstractControllerScriptingInterface.h +++ b/libraries/script-engine/src/AbstractControllerScriptingInterface.h @@ -1,9 +1,12 @@ // // AbstractControllerScriptingInterface.h -// hifi +// libraries/script-engine/src // -// Created by Brad Hefta-Gaub on 12/17/13 -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 12/17/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AbstractControllerScriptingInterface__ diff --git a/libraries/script-engine/src/EventTypes.h b/libraries/script-engine/src/EventTypes.h index f5a4fa5c9b..66f7523162 100644 --- a/libraries/script-engine/src/EventTypes.h +++ b/libraries/script-engine/src/EventTypes.h @@ -1,9 +1,12 @@ // // EventTypes.h -// hifi +// libraries/script-engine/src // // Created by Brad Hefta-Gaub on 1/28/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi_EventTypes_h__ diff --git a/libraries/script-engine/src/LocalVoxels.h b/libraries/script-engine/src/LocalVoxels.h index c64379ab27..82ed95fa66 100644 --- a/libraries/script-engine/src/LocalVoxels.h +++ b/libraries/script-engine/src/LocalVoxels.h @@ -1,9 +1,12 @@ // // LocalVoxels.h -// hifi +// libraries/script-engine/src // // Created by Clément Brisset on 2/24/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__LocalVoxels__ diff --git a/libraries/script-engine/src/MenuItemProperties.h b/libraries/script-engine/src/MenuItemProperties.h index 82f00a2bc4..22853d7fca 100644 --- a/libraries/script-engine/src/MenuItemProperties.h +++ b/libraries/script-engine/src/MenuItemProperties.h @@ -1,9 +1,12 @@ // // MenuItemProperties.h -// hifi +// libraries/script-engine/src // // Created by Brad Hefta-Gaub on 1/28/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi_MenuItemProperties_h__ diff --git a/libraries/script-engine/src/Quat.h b/libraries/script-engine/src/Quat.h index 02c0a3e147..4b3f0b58db 100644 --- a/libraries/script-engine/src/Quat.h +++ b/libraries/script-engine/src/Quat.h @@ -1,12 +1,12 @@ // // Quat.h -// hifi +// libraries/script-engine/src // -// Created by Brad Hefta-Gaub on 1/29/14 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. -// -// Scriptable Quaternion class library. +// Created by Brad Hefta-Gaub on 1/29/14. +// Copyright 2014 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__Quat__ diff --git a/libraries/script-engine/src/ScriptEngine.h b/libraries/script-engine/src/ScriptEngine.h index 964f64a005..7fe4f23b53 100644 --- a/libraries/script-engine/src/ScriptEngine.h +++ b/libraries/script-engine/src/ScriptEngine.h @@ -1,9 +1,12 @@ // // ScriptEngine.h -// hifi +// libraries/script-engine/src // // Created by Brad Hefta-Gaub on 12/14/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__ScriptEngine__ diff --git a/libraries/script-engine/src/Vec3.h b/libraries/script-engine/src/Vec3.h index cbec55b992..9e962ca4fd 100644 --- a/libraries/script-engine/src/Vec3.h +++ b/libraries/script-engine/src/Vec3.h @@ -1,12 +1,12 @@ // // Vec3.h -// hifi +// libraries/script-engine/src // -// Created by Brad Hefta-Gaub on 1/29/14 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. -// -// Scriptable Vec3 class library. +// Created by Brad Hefta-Gaub on 1/29/14. +// Copyright 2014 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__Vec3__ diff --git a/libraries/shared/src/AccountManager.h b/libraries/shared/src/AccountManager.h index 05a2e6a08a..992223f9ce 100644 --- a/libraries/shared/src/AccountManager.h +++ b/libraries/shared/src/AccountManager.h @@ -1,9 +1,12 @@ // // AccountManager.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/18/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AccountManager__ diff --git a/libraries/shared/src/AngleUtil.h b/libraries/shared/src/AngleUtil.h index cecee31188..e4d8abc28f 100644 --- a/libraries/shared/src/AngleUtil.h +++ b/libraries/shared/src/AngleUtil.h @@ -1,9 +1,12 @@ // -// AngleUtils.h -// hifi +// AngleUtil.h +// libraries/shared/src // -// Created by Tobias Schwinger on 3/23/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Tobias Schwinger on 3/23/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__AngleUtils__ diff --git a/libraries/shared/src/Assignment.h b/libraries/shared/src/Assignment.h index a8ab3be4a8..437112a64f 100644 --- a/libraries/shared/src/Assignment.h +++ b/libraries/shared/src/Assignment.h @@ -1,9 +1,12 @@ // // Assignment.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 8/22/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__Assignment__ diff --git a/libraries/shared/src/CapsuleShape.h b/libraries/shared/src/CapsuleShape.h index 6d7e0a50be..b721633601 100644 --- a/libraries/shared/src/CapsuleShape.h +++ b/libraries/shared/src/CapsuleShape.h @@ -1,9 +1,12 @@ // // CapsuleShape.h -// hifi +// libraries/shared/src // -// Created by Andrew Meadows on 2014.02.20 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrew Meadows on 2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__CapsuleShape__ diff --git a/libraries/shared/src/CollisionInfo.h b/libraries/shared/src/CollisionInfo.h index 868d259ce3..fb7450671b 100644 --- a/libraries/shared/src/CollisionInfo.h +++ b/libraries/shared/src/CollisionInfo.h @@ -1,9 +1,12 @@ // // CollisionInfo.h -// hifi +// libraries/shared/src // -// Created by Andrew Meadows on 2014.01.13 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrew Meadows on 2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__CollisionInfo__ diff --git a/libraries/shared/src/DataServerAccountInfo.h b/libraries/shared/src/DataServerAccountInfo.h index c840468319..04d2e7fabd 100644 --- a/libraries/shared/src/DataServerAccountInfo.h +++ b/libraries/shared/src/DataServerAccountInfo.h @@ -1,9 +1,12 @@ // // DataServerAccountInfo.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/21/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__DataServerAccountInfo__ diff --git a/libraries/shared/src/DomainInfo.h b/libraries/shared/src/DomainInfo.h index da65525f9d..563e2f8db0 100644 --- a/libraries/shared/src/DomainInfo.h +++ b/libraries/shared/src/DomainInfo.h @@ -1,9 +1,12 @@ // // DomainInfo.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/18/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__DomainInfo__ diff --git a/libraries/shared/src/FileUtils.h b/libraries/shared/src/FileUtils.h index dd4605218e..6953676b83 100644 --- a/libraries/shared/src/FileUtils.h +++ b/libraries/shared/src/FileUtils.h @@ -1,9 +1,12 @@ // // FileUtils.h -// hifi +// libraries/shared/src // // Created by Stojce Slavkovski on 12/23/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef hifi_FileUtils_h diff --git a/libraries/shared/src/FloodFill.h b/libraries/shared/src/FloodFill.h index 40a89bfd1b..5aeede2450 100644 --- a/libraries/shared/src/FloodFill.h +++ b/libraries/shared/src/FloodFill.h @@ -1,9 +1,11 @@ // // FloodFill.h -// hifi +// libraries/shared/src // -// Created by Tobias Schwinger 3/26/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__FloodFill__ diff --git a/libraries/shared/src/GenericThread.h b/libraries/shared/src/GenericThread.h index 1b5b05db5d..dc5c33d341 100644 --- a/libraries/shared/src/GenericThread.h +++ b/libraries/shared/src/GenericThread.h @@ -1,11 +1,12 @@ // // GenericThread.h -// shared +// libraries/shared/src // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Generic Threaded or non-threaded processing class. +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __shared__GenericThread__ diff --git a/libraries/shared/src/GeometryUtil.h b/libraries/shared/src/GeometryUtil.h index 12afc7c59c..3446956ffd 100644 --- a/libraries/shared/src/GeometryUtil.h +++ b/libraries/shared/src/GeometryUtil.h @@ -1,9 +1,12 @@ // // GeometryUtil.h -// interface +// libraries/shared/src // // Created by Andrzej Kapolka on 5/21/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__GeometryUtil__ diff --git a/libraries/shared/src/HifiSockAddr.h b/libraries/shared/src/HifiSockAddr.h index e8f928c36d..da8c75baee 100644 --- a/libraries/shared/src/HifiSockAddr.h +++ b/libraries/shared/src/HifiSockAddr.h @@ -1,9 +1,12 @@ // // HifiSockAddr.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 11/26/2013. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__HifiSockAddr__ diff --git a/libraries/shared/src/ListShape.h b/libraries/shared/src/ListShape.h index d6005ddfb9..393f937946 100644 --- a/libraries/shared/src/ListShape.h +++ b/libraries/shared/src/ListShape.h @@ -1,10 +1,12 @@ // // ListShape.h +// libraries/shared/src // -// ListShape: A collection of shapes, each with a local transform. +// Created by Andrew Meadows on 2014. +// Copyright 2014 High Fidelity, Inc. // -// Created by Andrew Meadows on 2014.02.20 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// 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__ListShape__ diff --git a/libraries/shared/src/Logging.h b/libraries/shared/src/Logging.h index abd5bfaab1..e17f3f3019 100644 --- a/libraries/shared/src/Logging.h +++ b/libraries/shared/src/Logging.h @@ -1,9 +1,12 @@ // // Logging.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 6/11/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__Logging__ diff --git a/libraries/shared/src/ModelUploader.h b/libraries/shared/src/ModelUploader.h index 0e62ab8705..7500b0fbb1 100644 --- a/libraries/shared/src/ModelUploader.h +++ b/libraries/shared/src/ModelUploader.h @@ -1,10 +1,12 @@ // // ModelUploader.h -// hifi +// libraries/shared/src // // Created by Clément Brisset on 3/4/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__ModelUploader__ diff --git a/libraries/shared/src/NetworkPacket.h b/libraries/shared/src/NetworkPacket.h index 0875b9f131..00c7caaa58 100644 --- a/libraries/shared/src/NetworkPacket.h +++ b/libraries/shared/src/NetworkPacket.h @@ -1,11 +1,12 @@ // // NetworkPacket.h -// shared +// libraries/shared/src // // Created by Brad Hefta-Gaub on 8/9/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// A really simple class that stores a network packet between being received and being processed +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __shared_NetworkPacket__ diff --git a/libraries/shared/src/Node.h b/libraries/shared/src/Node.h index 5d30d6f7b0..fd3c123df8 100644 --- a/libraries/shared/src/Node.h +++ b/libraries/shared/src/Node.h @@ -1,9 +1,12 @@ // // Node.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/15/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__Node__ diff --git a/libraries/shared/src/NodeData.h b/libraries/shared/src/NodeData.h index b6b75443a2..6dea803b3f 100644 --- a/libraries/shared/src/NodeData.h +++ b/libraries/shared/src/NodeData.h @@ -1,9 +1,12 @@ // // NodeData.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/19/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef hifi_NodeData_h diff --git a/libraries/shared/src/NodeList.h b/libraries/shared/src/NodeList.h index 34078b6a94..4071127131 100644 --- a/libraries/shared/src/NodeList.h +++ b/libraries/shared/src/NodeList.h @@ -1,9 +1,12 @@ // // NodeList.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/15/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__NodeList__ diff --git a/libraries/shared/src/OAuthAccessToken.h b/libraries/shared/src/OAuthAccessToken.h index e2a5eb4ce2..2159f595f2 100644 --- a/libraries/shared/src/OAuthAccessToken.h +++ b/libraries/shared/src/OAuthAccessToken.h @@ -1,9 +1,12 @@ // // OAuthAccessToken.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/18/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__OAuthAccessToken__ diff --git a/libraries/shared/src/OctalCode.h b/libraries/shared/src/OctalCode.h index c80aa82a2d..535b8a0021 100644 --- a/libraries/shared/src/OctalCode.h +++ b/libraries/shared/src/OctalCode.h @@ -1,9 +1,12 @@ // // OctalCode.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 3/15/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__OctalCode__ diff --git a/libraries/shared/src/PacketHeaders.h b/libraries/shared/src/PacketHeaders.h index 0e1e152a02..491bdf5ac5 100644 --- a/libraries/shared/src/PacketHeaders.h +++ b/libraries/shared/src/PacketHeaders.h @@ -1,12 +1,12 @@ // // PacketHeaders.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 4/8/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// The packet headers below refer to the first byte of a received UDP packet transmitted between -// any two Hifi components. For example, a packet whose first byte is 'P' is always a ping packet. +// 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_PacketHeaders_h diff --git a/libraries/shared/src/PacketSender.h b/libraries/shared/src/PacketSender.h index bd8de9a1b1..01023f8ca3 100644 --- a/libraries/shared/src/PacketSender.h +++ b/libraries/shared/src/PacketSender.h @@ -1,11 +1,12 @@ // // PacketSender.h -// shared +// libraries/shared/src // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Threaded or non-threaded packet sender. +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __shared__PacketSender__ diff --git a/libraries/shared/src/PerfStat.h b/libraries/shared/src/PerfStat.h index a7a10b97b8..4b4604feb3 100644 --- a/libraries/shared/src/PerfStat.h +++ b/libraries/shared/src/PerfStat.h @@ -1,13 +1,12 @@ // -// HiFiPerfStat.h -// hifi +// PerfStat.h +// libraries/shared/src // // Created by Brad Hefta-Gaub on 3/29/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. -// -// Poor-man's performance stats collector class. Useful for collecting timing -// details from various portions of the code. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__PerfStat__ diff --git a/libraries/shared/src/Radix2InplaceSort.h b/libraries/shared/src/Radix2InplaceSort.h index abd650b2a6..38c7b0b73c 100644 --- a/libraries/shared/src/Radix2InplaceSort.h +++ b/libraries/shared/src/Radix2InplaceSort.h @@ -1,9 +1,12 @@ // -// Radix2InplaceSort.h -// hifi +// Radix2InplaceSort.h +// libraries/shared/src // -// Created by Tobias Schwinger on 3/22/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Tobias Schwinger on 3/22/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__Radix2InplaceSort__ diff --git a/libraries/shared/src/Radix2IntegerScanner.h b/libraries/shared/src/Radix2IntegerScanner.h index 84e7c7077e..2137db0548 100644 --- a/libraries/shared/src/Radix2IntegerScanner.h +++ b/libraries/shared/src/Radix2IntegerScanner.h @@ -1,9 +1,12 @@ // -// Radix2IntegerScanner.h -// hifi +// Radix2IntegerScanner.h +// libraries/shared/src // -// Created by Tobias Schwinger on 3/23/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Tobias Schwinger on 3/23/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__Radix2IntegerScanner__ diff --git a/libraries/shared/src/ReceivedPacketProcessor.h b/libraries/shared/src/ReceivedPacketProcessor.h index f88512639b..e4365f4e18 100644 --- a/libraries/shared/src/ReceivedPacketProcessor.h +++ b/libraries/shared/src/ReceivedPacketProcessor.h @@ -1,11 +1,12 @@ // // ReceivedPacketProcessor.h -// shared +// libraries/shared/src // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Threaded or non-threaded received packet processor. +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __shared__ReceivedPacketProcessor__ diff --git a/libraries/shared/src/RegisteredMetaTypes.h b/libraries/shared/src/RegisteredMetaTypes.h index 4e6a071dd6..93fb4e7f57 100644 --- a/libraries/shared/src/RegisteredMetaTypes.h +++ b/libraries/shared/src/RegisteredMetaTypes.h @@ -1,12 +1,12 @@ // // RegisteredMetaTypes.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 10/3/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Used to register meta-types with Qt so that they can be used as properties for objects exposed to our -// Agent scripting. +// 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_RegisteredMetaTypes_h diff --git a/libraries/shared/src/ResourceCache.h b/libraries/shared/src/ResourceCache.h index 2fcda0bb98..984ab7aaa2 100644 --- a/libraries/shared/src/ResourceCache.h +++ b/libraries/shared/src/ResourceCache.h @@ -1,9 +1,12 @@ // // ResourceCache.h -// shared +// libraries/shared/src // // Created by Andrzej Kapolka on 2/27/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __shared__ResourceCache__ diff --git a/libraries/shared/src/Shape.h b/libraries/shared/src/Shape.h index 924d13000e..11ce41d103 100644 --- a/libraries/shared/src/Shape.h +++ b/libraries/shared/src/Shape.h @@ -1,8 +1,12 @@ // // Shape.h +// libraries/shared/src // -// Created by Andrew Meadows on 2014.02.20 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrew Meadows on 2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__Shape__ diff --git a/libraries/shared/src/ShapeCollider.h b/libraries/shared/src/ShapeCollider.h index e3e044c8fe..7154a158d0 100644 --- a/libraries/shared/src/ShapeCollider.h +++ b/libraries/shared/src/ShapeCollider.h @@ -1,9 +1,12 @@ // // ShapeCollider.h -// hifi +// libraries/shared/src // -// Created by Andrew Meadows on 2014.02.20 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrew Meadows on 2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__ShapeCollider__ diff --git a/libraries/shared/src/SharedUtil.h b/libraries/shared/src/SharedUtil.h index d8d686c63b..90dd0ccfe8 100644 --- a/libraries/shared/src/SharedUtil.h +++ b/libraries/shared/src/SharedUtil.h @@ -1,9 +1,12 @@ // // SharedUtil.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/22/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__SharedUtil__ diff --git a/libraries/shared/src/SimpleMovingAverage.h b/libraries/shared/src/SimpleMovingAverage.h index f11cd16e58..8b862f9d63 100644 --- a/libraries/shared/src/SimpleMovingAverage.h +++ b/libraries/shared/src/SimpleMovingAverage.h @@ -1,11 +1,12 @@ // // SimpleMovingAverage.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 4/18/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Replaces Brad Hefta-Gaub's CounterStats class (RIP) +// 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__Stats__ diff --git a/libraries/shared/src/SphereShape.h b/libraries/shared/src/SphereShape.h index d720dd2289..746f93be80 100644 --- a/libraries/shared/src/SphereShape.h +++ b/libraries/shared/src/SphereShape.h @@ -1,9 +1,12 @@ // // SphereShape.h -// hifi +// libraries/shared/src // -// Created by Andrew Meadows on 2014.02.20 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrew Meadows on 2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__SphereShape__ diff --git a/libraries/shared/src/StdDev.h b/libraries/shared/src/StdDev.h index eea0cff3bb..82fccdd79a 100644 --- a/libraries/shared/src/StdDev.h +++ b/libraries/shared/src/StdDev.h @@ -1,9 +1,12 @@ // // StdDev.h -// hifi +// libraries/shared/src // // Created by Philip Rosedale on 3/12/13. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__StdDev__ diff --git a/libraries/shared/src/StreamUtils.h b/libraries/shared/src/StreamUtils.h index 1a17a94658..d70096bd27 100644 --- a/libraries/shared/src/StreamUtils.h +++ b/libraries/shared/src/StreamUtils.h @@ -1,8 +1,12 @@ // // StreamUtils.h +// libraries/shared/src // -// Created by Andrew Meadows on 2014.02.21 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrew Meadows on 2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __tests__StreamUtils__ diff --git a/libraries/shared/src/ThreadedAssignment.h b/libraries/shared/src/ThreadedAssignment.h index f9652dd98d..9f1f45c1a9 100644 --- a/libraries/shared/src/ThreadedAssignment.h +++ b/libraries/shared/src/ThreadedAssignment.h @@ -1,9 +1,12 @@ // // ThreadedAssignment.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 12/3/2013. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__ThreadedAssignment__ diff --git a/libraries/shared/src/UUID.h b/libraries/shared/src/UUID.h index cacadf5a04..da0025d425 100644 --- a/libraries/shared/src/UUID.h +++ b/libraries/shared/src/UUID.h @@ -1,9 +1,12 @@ // // UUID.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 10/7/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__UUID__ diff --git a/libraries/voxels/src/EnvironmentData.h b/libraries/voxels/src/EnvironmentData.h index 627a661e1c..fe0e279ba8 100644 --- a/libraries/voxels/src/EnvironmentData.h +++ b/libraries/voxels/src/EnvironmentData.h @@ -1,9 +1,12 @@ // // EnvironmentData.h -// interface +// libraries/voxels/src // // Created by Andrzej Kapolka on 5/6/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__EnvironmentData__ diff --git a/libraries/voxels/src/LocalVoxelsList.h b/libraries/voxels/src/LocalVoxelsList.h index e4b4decf8e..2ec68d3234 100644 --- a/libraries/voxels/src/LocalVoxelsList.h +++ b/libraries/voxels/src/LocalVoxelsList.h @@ -1,9 +1,12 @@ // // LocalVoxelsList.h -// hifi +// libraries/voxels/src // // Created by Clément Brisset on 2/24/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__LocalVoxelsList__ diff --git a/libraries/voxels/src/Tags.h b/libraries/voxels/src/Tags.h index caf4303c51..ec1ae8c0e8 100644 --- a/libraries/voxels/src/Tags.h +++ b/libraries/voxels/src/Tags.h @@ -1,9 +1,12 @@ // // Tags.h -// hifi +// libraries/voxels/src // // Created by Clement Brisset on 7/3/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__Tags__ diff --git a/libraries/voxels/src/VoxelConstants.h b/libraries/voxels/src/VoxelConstants.h index 16d75873d9..a375e23b7c 100644 --- a/libraries/voxels/src/VoxelConstants.h +++ b/libraries/voxels/src/VoxelConstants.h @@ -1,11 +1,12 @@ // // VoxelConstants.h -// hifi +// libraries/voxels/src // // Created by Brad Hefta-Gaub on 4/29/13. +// Copyright 2013 High Fidelity, Inc. // -// -// Various important constants used throughout the system related to voxels +// 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_VoxelConstants_h__ @@ -44,4 +45,4 @@ const quint64 CLIENT_TO_SERVER_VOXEL_SEND_INTERVAL_USECS = 1000 * 5; // 1 packet const int DEFAULT_MAX_VOXEL_PPS = 600; // the default maximum PPS we think a voxel server should send to a client -#endif \ No newline at end of file +#endif diff --git a/libraries/voxels/src/VoxelDetail.h b/libraries/voxels/src/VoxelDetail.h index 1604a022a0..5ed68f540e 100644 --- a/libraries/voxels/src/VoxelDetail.h +++ b/libraries/voxels/src/VoxelDetail.h @@ -1,10 +1,12 @@ // // VoxelDetail.h -// hifi +// libraries/voxels/src // -// Created by Brad Hefta-Gaub on 1/29/2014 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 1/29/2014. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__VoxelDetail__ @@ -48,4 +50,4 @@ Q_DECLARE_METATYPE(RayToVoxelIntersectionResult) QScriptValue rayToVoxelIntersectionResultToScriptValue(QScriptEngine* engine, const RayToVoxelIntersectionResult& results); void rayToVoxelIntersectionResultFromScriptValue(const QScriptValue& object, RayToVoxelIntersectionResult& results); -#endif /* defined(__hifi__VoxelDetail__) */ \ No newline at end of file +#endif /* defined(__hifi__VoxelDetail__) */ diff --git a/libraries/voxels/src/VoxelEditPacketSender.h b/libraries/voxels/src/VoxelEditPacketSender.h index 4a1aa87a1c..37c65207f6 100644 --- a/libraries/voxels/src/VoxelEditPacketSender.h +++ b/libraries/voxels/src/VoxelEditPacketSender.h @@ -1,11 +1,12 @@ // // VoxelEditPacketSender.h -// shared +// libraries/voxels/src // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Voxel Packet Sender +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __shared__VoxelEditPacketSender__ diff --git a/libraries/voxels/src/VoxelTree.h b/libraries/voxels/src/VoxelTree.h index 2079ab91b2..1fafd429ed 100644 --- a/libraries/voxels/src/VoxelTree.h +++ b/libraries/voxels/src/VoxelTree.h @@ -1,9 +1,12 @@ // // VoxelTree.h -// hifi +// libraries/voxels/src // // Created by Stephen Birarda on 3/13/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__VoxelTree__ diff --git a/libraries/voxels/src/VoxelTreeCommands.h b/libraries/voxels/src/VoxelTreeCommands.h index ca7700417c..314a49b845 100644 --- a/libraries/voxels/src/VoxelTreeCommands.h +++ b/libraries/voxels/src/VoxelTreeCommands.h @@ -1,9 +1,12 @@ // // VoxelTreeCommands.h -// hifi +// libraries/voxels/src // // Created by Clement on 4/4/14. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__VoxelTreeCommands__ diff --git a/libraries/voxels/src/VoxelTreeElement.h b/libraries/voxels/src/VoxelTreeElement.h index c88fd6d207..757cffc8bc 100644 --- a/libraries/voxels/src/VoxelTreeElement.h +++ b/libraries/voxels/src/VoxelTreeElement.h @@ -1,9 +1,12 @@ // // VoxelTreeElement.h -// hifi +// libraries/voxels/src // // Created by Stephen Birarda on 3/13/13. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__VoxelTreeElement__ diff --git a/libraries/voxels/src/VoxelTreeHeadlessViewer.h b/libraries/voxels/src/VoxelTreeHeadlessViewer.h index 9c7481c929..55366010ad 100644 --- a/libraries/voxels/src/VoxelTreeHeadlessViewer.h +++ b/libraries/voxels/src/VoxelTreeHeadlessViewer.h @@ -1,10 +1,12 @@ // // VoxelTreeHeadlessViewer.h -// hifi +// libraries/voxels/src // -// Created by Brad Hefta-Gaub on 2/26/14 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 2/26/14. +// Copyright 2014 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__VoxelTreeHeadlessViewer__ @@ -35,4 +37,4 @@ public: virtual void init(); }; -#endif /* defined(__hifi__VoxelTreeHeadlessViewer__) */ \ No newline at end of file +#endif /* defined(__hifi__VoxelTreeHeadlessViewer__) */ diff --git a/libraries/voxels/src/VoxelsScriptingInterface.h b/libraries/voxels/src/VoxelsScriptingInterface.h index da51259eeb..05c93aab8e 100644 --- a/libraries/voxels/src/VoxelsScriptingInterface.h +++ b/libraries/voxels/src/VoxelsScriptingInterface.h @@ -1,9 +1,12 @@ // // VoxelsScriptingInterface.h -// hifi +// libraries/voxels/src // // Created by Stephen Birarda on 9/17/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__VoxelsScriptingInterface__ diff --git a/voxel-edit/src/SceneUtils.h b/voxel-edit/src/SceneUtils.h index 6f52a14f05..90b605f2c7 100644 --- a/voxel-edit/src/SceneUtils.h +++ b/voxel-edit/src/SceneUtils.h @@ -1,9 +1,12 @@ // // SceneUtils.h -// hifi +// voxel-edit/src // // Created by Brad Hefta-Gaub on 5/7/2013. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__SceneUtil__ From 638b49e47d3d833f2399b084caf56038bec2ee9b Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 8 Apr 2014 17:31:02 -0700 Subject: [PATCH 219/595] switch to apache license in root license file --- LICENSE | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 1ecd0026f5..93c9a953d4 100644 --- a/LICENSE +++ b/LICENSE @@ -1 +1,13 @@ -All rights reserved. © High Fidelity, Inc. 2013 \ No newline at end of file +Copyright 2014 High Fidelity, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file From ab3a9af6bfc36e5ebeaff1f2e969185cb4faded6 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 8 Apr 2014 17:31:30 -0700 Subject: [PATCH 220/595] repair the starfield renderer --- interface/src/starfield/renderer/Renderer.h | 51 ++++++++++++++++++++- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/interface/src/starfield/renderer/Renderer.h b/interface/src/starfield/renderer/Renderer.h index 7eaeb1444e..8b75f4e953 100755 --- a/interface/src/starfield/renderer/Renderer.h +++ b/interface/src/starfield/renderer/Renderer.h @@ -9,6 +9,54 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#ifndef __interface__starfield__renderer__Renderer__ +#define __interface__starfield__renderer__Renderer__ + +#include "starfield/Config.h" +#include "starfield/data/InputVertex.h" +#include "starfield/data/Tile.h" +#include "starfield/data/GpuVertex.h" +#include "starfield/renderer/Tiling.h" + +// +// FOV culling +// =========== +// +// As stars can be thought of as at infinity distance, the field of view only +// depends on perspective and rotation: +// +// _----_ <-- visible stars +// from above +-near-+ - - +// \ / | +// near width: \ / | cos(p/2) +// 2sin(p/2) \/ _ +// center +// +// +// Now it is important to note that a change in altitude maps uniformly to a +// distance on a sphere. This is NOT the case for azimuthal angles: In this +// case a factor of 'cos(alt)' (the orbital radius) applies: +// +// +// |<-cos alt ->| | |<-|<----->|->| d_azi cos(alt) +// | +// __--* | --------- - +// __-- * | | | ^ d_alt +// __-- alt) * | | | v +// --------------*- | ------------- - +// | +// side view | tile on sphere +// +// +// This lets us find a worst-case (Eigen) angle from the center to the edge +// of a tile as +// +// hypot( 0.5 d_alt, 0.5 d_azi cos(alt_absmin) ). +// +// This angle must be added to 'p' (the perspective angle) in order to find +// an altered near plane for the culling decision. +// + namespace starfield { class Renderer { @@ -90,5 +138,4 @@ namespace starfield { } -#endif - +#endif \ No newline at end of file From 387179b38fe22d93d1d449eac6de0be0deb7103e Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 8 Apr 2014 17:31:53 -0700 Subject: [PATCH 221/595] add Norman's tagline back to PrimitiveRenderer --- interface/src/voxels/PrimitiveRenderer.h | 1 + 1 file changed, 1 insertion(+) diff --git a/interface/src/voxels/PrimitiveRenderer.h b/interface/src/voxels/PrimitiveRenderer.h index 92536190e2..268b4f3175 100644 --- a/interface/src/voxels/PrimitiveRenderer.h +++ b/interface/src/voxels/PrimitiveRenderer.h @@ -2,6 +2,7 @@ // PrimitiveRenderer.h // interface/src/voxels // +// Created by Norman Craft. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. From 7ce91b3f968e1ac4377fb26b47eaf8727f83d7da Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 8 Apr 2014 17:43:35 -0700 Subject: [PATCH 222/595] fix headers who had their comments removed --- .../src/octree/OctreeInboundPacketProcessor.h | 2 ++ assignment-client/src/octree/OctreeSendThread.h | 2 ++ interface/src/ui/RearMirrorTools.h | 2 +- interface/src/voxels/VoxelHideShowThread.h | 2 ++ interface/src/windowshacks.h | 2 ++ libraries/embedded-webserver/src/HTTPManager.h | 4 ++++ libraries/octree/src/AABox.h | 4 +++- libraries/octree/src/JurisdictionListener.h | 3 ++- libraries/octree/src/OctreeElementBag.h | 5 +++++ libraries/octree/src/OctreePacketData.h | 10 ++++++++++ libraries/octree/src/OctreePersistThread.h | 2 ++ libraries/octree/src/OctreeProjectedPolygon.h | 2 ++ libraries/octree/src/ViewFrustum.h | 2 ++ libraries/script-engine/src/Quat.h | 2 ++ libraries/shared/src/GenericThread.h | 2 ++ libraries/shared/src/ListShape.h | 4 +++- libraries/shared/src/NetworkPacket.h | 2 ++ libraries/shared/src/PerfStat.h | 3 +++ libraries/shared/src/SimpleMovingAverage.h | 2 ++ libraries/voxels/src/VoxelConstants.h | 2 ++ libraries/voxels/src/VoxelEditPacketSender.h | 2 ++ 21 files changed, 57 insertions(+), 4 deletions(-) diff --git a/assignment-client/src/octree/OctreeInboundPacketProcessor.h b/assignment-client/src/octree/OctreeInboundPacketProcessor.h index 1a4f80b925..e14065a9c1 100644 --- a/assignment-client/src/octree/OctreeInboundPacketProcessor.h +++ b/assignment-client/src/octree/OctreeInboundPacketProcessor.h @@ -5,6 +5,8 @@ // Created by Brad Hefta-Gaub on 8/21/13. // Copyright 2013 High Fidelity, Inc. // +// Threaded or non-threaded network packet processor for the voxel-server +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/assignment-client/src/octree/OctreeSendThread.h b/assignment-client/src/octree/OctreeSendThread.h index 09d5809acc..423d9fc2bb 100644 --- a/assignment-client/src/octree/OctreeSendThread.h +++ b/assignment-client/src/octree/OctreeSendThread.h @@ -5,6 +5,8 @@ // Created by Brad Hefta-Gaub on 8/21/13. // Copyright 2013 High Fidelity, Inc. // +// Threaded or non-threaded object for sending voxels to a client +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/interface/src/ui/RearMirrorTools.h b/interface/src/ui/RearMirrorTools.h index f410b0b5ff..6230771b4b 100644 --- a/interface/src/ui/RearMirrorTools.h +++ b/interface/src/ui/RearMirrorTools.h @@ -2,7 +2,7 @@ // RearMirrorTools.h // interface/src/ui // -// Created by stojce on 23. +// Created by stojce on 10/23/2013. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. diff --git a/interface/src/voxels/VoxelHideShowThread.h b/interface/src/voxels/VoxelHideShowThread.h index 29aa53f430..b12befc9de 100644 --- a/interface/src/voxels/VoxelHideShowThread.h +++ b/interface/src/voxels/VoxelHideShowThread.h @@ -5,6 +5,8 @@ // Created by Brad Hefta-Gaub on 12/1/13. // Copyright 2013 High Fidelity, Inc. // +// Threaded or non-threaded voxel persistence +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/interface/src/windowshacks.h b/interface/src/windowshacks.h index 07ef69c6f0..3563c2a765 100644 --- a/interface/src/windowshacks.h +++ b/interface/src/windowshacks.h @@ -5,6 +5,8 @@ // Created by Brad Hefta-Gaub on 1/12/14. // Copyright 2014 High Fidelity, Inc. // +// hacks to get windows to compile +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/embedded-webserver/src/HTTPManager.h b/libraries/embedded-webserver/src/HTTPManager.h index 91f185de2e..c7bb479ab2 100755 --- a/libraries/embedded-webserver/src/HTTPManager.h +++ b/libraries/embedded-webserver/src/HTTPManager.h @@ -5,6 +5,10 @@ // Created by Stephen Birarda on 1/16/14. // Copyright 2014 High Fidelity, Inc. // +// Heavily based on Andrzej Kapolka's original HTTPManager class +// found from another one of his projects. +// https://github.com/ey6es/witgap/tree/master/src/cpp/server/http +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/octree/src/AABox.h b/libraries/octree/src/AABox.h index 2b9be1246f..1d5fad696c 100644 --- a/libraries/octree/src/AABox.h +++ b/libraries/octree/src/AABox.h @@ -5,6 +5,9 @@ // Created by Brad Hefta-Gaub on 04/11/13. // Copyright 2013 High Fidelity, Inc. // +// Originally from lighthouse3d. Modified to utilize glm::vec3 and clean up to our coding standards +// Simple axis aligned box class. +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // @@ -23,7 +26,6 @@ enum BoxFace { MAX_Z_FACE }; - enum BoxVertex { BOTTOM_LEFT_NEAR = 0, BOTTOM_RIGHT_NEAR = 1, diff --git a/libraries/octree/src/JurisdictionListener.h b/libraries/octree/src/JurisdictionListener.h index 981f7d1a42..2d5cd75560 100644 --- a/libraries/octree/src/JurisdictionListener.h +++ b/libraries/octree/src/JurisdictionListener.h @@ -5,6 +5,8 @@ // Created by Brad Hefta-Gaub on 8/12/13. // Copyright 2013 High Fidelity, Inc. // +// Voxel Packet Sender +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // @@ -16,7 +18,6 @@ #include #include - #include "JurisdictionMap.h" /// Sends out PacketType_JURISDICTION_REQUEST packets to all voxel servers and then listens for and processes diff --git a/libraries/octree/src/OctreeElementBag.h b/libraries/octree/src/OctreeElementBag.h index fa3cbf0319..0c17d9f1fa 100644 --- a/libraries/octree/src/OctreeElementBag.h +++ b/libraries/octree/src/OctreeElementBag.h @@ -5,6 +5,11 @@ // Created by Brad Hefta-Gaub on 4/25/2013. // Copyright 2013 High Fidelity, Inc. // +// This class is used by the VoxelTree:encodeTreeBitstream() functions to store extra nodes that need to be sent +// it's a generic bag style storage mechanism. But It has the property that you can't put the same node into the bag +// more than once (in other words, it de-dupes automatically), also, it supports collapsing it's several peer nodes +// into a parent node in cases where you add enough peers that it makes more sense to just add the parent. +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/octree/src/OctreePacketData.h b/libraries/octree/src/OctreePacketData.h index 1efea6c217..64e7c07161 100644 --- a/libraries/octree/src/OctreePacketData.h +++ b/libraries/octree/src/OctreePacketData.h @@ -5,6 +5,16 @@ // Created by Brad Hefta-Gaub on 11/19/2013. // Copyright 2013 High Fidelity, Inc. // +// TO DO: +// * add stats tracking for number of unique colors and consecutive identical colors. +// (as research for color dictionaries and RLE) +// +// * further testing of compression to determine optimal configuration for performance and compression +// +// * improve semantics for "reshuffle" - current approach will work for now and with compression +// but wouldn't work with RLE because the colors in the levels would get reordered and RLE would need +// to be recalculated +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/octree/src/OctreePersistThread.h b/libraries/octree/src/OctreePersistThread.h index 8d96ac945d..90b83b4c86 100644 --- a/libraries/octree/src/OctreePersistThread.h +++ b/libraries/octree/src/OctreePersistThread.h @@ -5,6 +5,8 @@ // Created by Brad Hefta-Gaub on 8/21/13. // Copyright 2013 High Fidelity, Inc. // +// Threaded or non-threaded Octree persistence +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/octree/src/OctreeProjectedPolygon.h b/libraries/octree/src/OctreeProjectedPolygon.h index e551a6c005..ff3a28649e 100644 --- a/libraries/octree/src/OctreeProjectedPolygon.h +++ b/libraries/octree/src/OctreeProjectedPolygon.h @@ -5,6 +5,8 @@ // Created by Brad Hefta-Gaub on 06/11/13. // Copyright 2013 High Fidelity, Inc. // +// The projected shadow (on the 2D view plane) for a voxel +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/octree/src/ViewFrustum.h b/libraries/octree/src/ViewFrustum.h index 6553dab1a1..65ff992ee4 100644 --- a/libraries/octree/src/ViewFrustum.h +++ b/libraries/octree/src/ViewFrustum.h @@ -5,6 +5,8 @@ // Created by Brad Hefta-Gaub on 04/11/13. // Copyright 2013 High Fidelity, Inc. // +// Simple view frustum class. +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/script-engine/src/Quat.h b/libraries/script-engine/src/Quat.h index 4b3f0b58db..418488fe2e 100644 --- a/libraries/script-engine/src/Quat.h +++ b/libraries/script-engine/src/Quat.h @@ -5,6 +5,8 @@ // Created by Brad Hefta-Gaub on 1/29/14. // Copyright 2014 High Fidelity, Inc. // +// Scriptable Quaternion class library. +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/shared/src/GenericThread.h b/libraries/shared/src/GenericThread.h index dc5c33d341..2aaa081aa8 100644 --- a/libraries/shared/src/GenericThread.h +++ b/libraries/shared/src/GenericThread.h @@ -5,6 +5,8 @@ // Created by Brad Hefta-Gaub on 8/12/13. // Copyright 2013 High Fidelity, Inc. // +// Generic Threaded or non-threaded processing class. +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/shared/src/ListShape.h b/libraries/shared/src/ListShape.h index 393f937946..b8a8fb018d 100644 --- a/libraries/shared/src/ListShape.h +++ b/libraries/shared/src/ListShape.h @@ -2,9 +2,11 @@ // ListShape.h // libraries/shared/src // -// Created by Andrew Meadows on 2014. +// Created by Andrew Meadows on 02/20/2014. // Copyright 2014 High Fidelity, Inc. // +// ListShape: A collection of shapes, each with a local transform. +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/shared/src/NetworkPacket.h b/libraries/shared/src/NetworkPacket.h index 00c7caaa58..bc9e3def40 100644 --- a/libraries/shared/src/NetworkPacket.h +++ b/libraries/shared/src/NetworkPacket.h @@ -5,6 +5,8 @@ // Created by Brad Hefta-Gaub on 8/9/13. // Copyright 2013 High Fidelity, Inc. // +// A really simple class that stores a network packet between being received and being processed +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/shared/src/PerfStat.h b/libraries/shared/src/PerfStat.h index 4b4604feb3..c3ae12a825 100644 --- a/libraries/shared/src/PerfStat.h +++ b/libraries/shared/src/PerfStat.h @@ -5,6 +5,9 @@ // Created by Brad Hefta-Gaub on 3/29/13. // Copyright 2013 High Fidelity, Inc. // +// Poor-man's performance stats collector class. Useful for collecting timing +// details from various portions of the code. +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/shared/src/SimpleMovingAverage.h b/libraries/shared/src/SimpleMovingAverage.h index 8b862f9d63..16d30279b0 100644 --- a/libraries/shared/src/SimpleMovingAverage.h +++ b/libraries/shared/src/SimpleMovingAverage.h @@ -5,6 +5,8 @@ // Created by Stephen Birarda on 4/18/13. // Copyright 2013 High Fidelity, Inc. // +// Replaces Brad Hefta-Gaub's CounterStats class (RIP) +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/voxels/src/VoxelConstants.h b/libraries/voxels/src/VoxelConstants.h index a375e23b7c..fc2c502a65 100644 --- a/libraries/voxels/src/VoxelConstants.h +++ b/libraries/voxels/src/VoxelConstants.h @@ -5,6 +5,8 @@ // Created by Brad Hefta-Gaub on 4/29/13. // Copyright 2013 High Fidelity, Inc. // +// Various important constants used throughout the system related to voxels +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/voxels/src/VoxelEditPacketSender.h b/libraries/voxels/src/VoxelEditPacketSender.h index 37c65207f6..fdf70fb96d 100644 --- a/libraries/voxels/src/VoxelEditPacketSender.h +++ b/libraries/voxels/src/VoxelEditPacketSender.h @@ -5,6 +5,8 @@ // Created by Brad Hefta-Gaub on 8/12/13. // Copyright 2013 High Fidelity, Inc. // +// Voxel Packet Sender +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // From ff9fd2d8e9742808ffe6ee0515ad017787b36efa Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 8 Apr 2014 17:49:30 -0700 Subject: [PATCH 223/595] tweak headers in cmake find modules --- cmake/macros/AutoMTC.cmake | 4 +--- cmake/modules/FindFaceshift.cmake | 6 +++++ cmake/modules/FindGLEW.cmake | 21 ++++++++++------- cmake/modules/FindGLUT.cmake | 23 ++++++++++++------- cmake/modules/FindLibOVR.cmake | 8 ++++++- .../modules/FindQt5LinguistToolsMacros.cmake | 2 -- cmake/modules/FindQxmpp.cmake | 6 +++++ cmake/modules/FindSixense.cmake | 6 +++++ cmake/modules/FindVisage.cmake | 6 +++++ 9 files changed, 60 insertions(+), 22 deletions(-) diff --git a/cmake/macros/AutoMTC.cmake b/cmake/macros/AutoMTC.cmake index 6619419b59..a2f5047ac7 100644 --- a/cmake/macros/AutoMTC.cmake +++ b/cmake/macros/AutoMTC.cmake @@ -8,6 +8,4 @@ macro(AUTO_MTC TARGET ROOT_DIR) file(GLOB INCLUDE_FILES src/*.h) add_custom_command(OUTPUT ${AUTOMTC_SRC} COMMAND mtc -o ${AUTOMTC_SRC} ${INCLUDE_FILES} DEPENDS mtc ${INCLUDE_FILES}) -endmacro() - - +endmacro() \ No newline at end of file diff --git a/cmake/modules/FindFaceshift.cmake b/cmake/modules/FindFaceshift.cmake index c89cbbab6f..9b407c353f 100644 --- a/cmake/modules/FindFaceshift.cmake +++ b/cmake/modules/FindFaceshift.cmake @@ -1,3 +1,6 @@ +# +# FindFaceshift.cmake +# # Try to find the Faceshift networking library # # You must provide a FACESHIFT_ROOT_DIR which contains lib and include directories @@ -11,6 +14,9 @@ # Created on 8/30/2013 by Andrzej Kapolka # Copyright (c) 2013 High Fidelity # +# Distributed under the Apache License, Version 2.0. +# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +# if (FACESHIFT_LIBRARIES AND FACESHIFT_INCLUDE_DIRS) # in cache already diff --git a/cmake/modules/FindGLEW.cmake b/cmake/modules/FindGLEW.cmake index 684acca762..160cfedc5a 100644 --- a/cmake/modules/FindGLEW.cmake +++ b/cmake/modules/FindGLEW.cmake @@ -1,16 +1,21 @@ # -# Try to find GLEW library and include path. -# Once done this will define -# -# GLEW_FOUND -# GLEW_INCLUDE_DIRS -# GLEW_LIBRARY +# FindGLEW.cmake +# +# Try to find GLEW library and include path. +# Once done this will define +# +# GLEW_FOUND +# GLEW_INCLUDE_DIRS +# GLEW_LIBRARY # - # Created on 2/6/2014 by Stephen Birarda # -# Adapted from FindGLEW.cmake available in the nvidia-texture-tools repository +# Adapted from FindGLEW.cmake available in the nvidia-texture-tools repository # (https://code.google.com/p/nvidia-texture-tools/source/browse/trunk/cmake/FindGLEW.cmake?r=96) +# +# Distributed under the Apache License, Version 2.0. +# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +# if (GLEW_INCLUDE_DIRS AND GLEW_LIBRARY) set(GLEW_FOUND TRUE) diff --git a/cmake/modules/FindGLUT.cmake b/cmake/modules/FindGLUT.cmake index 173f5a24ae..fe41dc5df8 100644 --- a/cmake/modules/FindGLUT.cmake +++ b/cmake/modules/FindGLUT.cmake @@ -1,15 +1,22 @@ -# Try to find GLUT library and include path. -# Once done this will define +# +# FindGLUT.cmake +# +# Try to find GLUT library and include path. +# Once done this will define # -# GLUT_FOUND -# GLUT_INCLUDE_DIR -# GLUT_LIBRARIES -# GLUT_DLL_PATH - Optionally defined for Win32, if not in path +# GLUT_FOUND +# GLUT_INCLUDE_DIR +# GLUT_LIBRARIES +# GLUT_DLL_PATH - Optionally defined for Win32, if not in path # # Created on 2/6/2014 by Stephen Birarda # -# Adapted from FindGLUT.cmake available in tlorach's OpenGLText Repository -# https://raw.github.com/tlorach/OpenGLText/master/cmake/FindGLUT.cmake +# Adapted from FindGLUT.cmake available in tlorach's OpenGLText Repository +# https://raw.github.com/tlorach/OpenGLText/master/cmake/FindGLUT.cmake +# +# Distributed under the Apache License, Version 2.0. +# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +# if (GLUT_INCLUDE_DIR AND GLUT_LIBRARIES) set(GLUT_FOUND TRUE) diff --git a/cmake/modules/FindLibOVR.cmake b/cmake/modules/FindLibOVR.cmake index 47b7d27015..811fdb73d4 100644 --- a/cmake/modules/FindLibOVR.cmake +++ b/cmake/modules/FindLibOVR.cmake @@ -1,4 +1,7 @@ -# - Try to find the LibOVR library to use the Oculus +# +# FindLibOVR.cmake +# +# Try to find the LibOVR library to use the Oculus # # You must provide a LIBOVR_ROOT_DIR which contains Lib and Include directories # @@ -11,6 +14,9 @@ # Created on 5/9/2013 by Stephen Birarda # Copyright (c) 2013 High Fidelity # +# Distributed under the Apache License, Version 2.0. +# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +# if (LIBOVR_LIBRARIES AND LIBOVR_INCLUDE_DIRS) # in cache already diff --git a/cmake/modules/FindQt5LinguistToolsMacros.cmake b/cmake/modules/FindQt5LinguistToolsMacros.cmake index cd2d1eb74f..bd9d55cb16 100644 --- a/cmake/modules/FindQt5LinguistToolsMacros.cmake +++ b/cmake/modules/FindQt5LinguistToolsMacros.cmake @@ -30,8 +30,6 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #============================================================================= - - function(QT5_CREATE_TRANSLATION_CUSTOM _qm_files) set(options) set(oneValueArgs) diff --git a/cmake/modules/FindQxmpp.cmake b/cmake/modules/FindQxmpp.cmake index 415b184a65..caeb35219d 100644 --- a/cmake/modules/FindQxmpp.cmake +++ b/cmake/modules/FindQxmpp.cmake @@ -1,3 +1,6 @@ +# +# FindQxmpp.cmake +# # Try to find the qxmpp library # # You can provide a QXMPP_ROOT_DIR which contains lib and include directories @@ -11,6 +14,9 @@ # Created on 3/10/2014 by Stephen Birarda # Copyright (c) 2014 High Fidelity # +# Distributed under the Apache License, Version 2.0. +# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +# if (QXMPP_LIBRARIES AND QXMPP_INCLUDE_DIRS) # in cache already diff --git a/cmake/modules/FindSixense.cmake b/cmake/modules/FindSixense.cmake index 1585095ba8..74965f5734 100644 --- a/cmake/modules/FindSixense.cmake +++ b/cmake/modules/FindSixense.cmake @@ -1,3 +1,6 @@ +# +# FindSixense.cmake +# # Try to find the Sixense controller library # # You must provide a SIXENSE_ROOT_DIR which contains lib and include directories @@ -11,6 +14,9 @@ # Created on 11/15/2013 by Andrzej Kapolka # Copyright (c) 2013 High Fidelity # +# Distributed under the Apache License, Version 2.0. +# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +# if (SIXENSE_LIBRARIES AND SIXENSE_INCLUDE_DIRS) # in cache already diff --git a/cmake/modules/FindVisage.cmake b/cmake/modules/FindVisage.cmake index aa7f0f9faf..6d204e4649 100644 --- a/cmake/modules/FindVisage.cmake +++ b/cmake/modules/FindVisage.cmake @@ -1,3 +1,6 @@ +# +# FindVisage.cmake +# # Try to find the Visage controller library # # You must provide a VISAGE_ROOT_DIR which contains lib and include directories @@ -11,6 +14,9 @@ # Created on 2/11/2014 by Andrzej Kapolka # Copyright (c) 2014 High Fidelity # +# Distributed under the Apache License, Version 2.0. +# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +# if (VISAGE_LIBRARIES AND VISAGE_INCLUDE_DIRS) # in cache already From d9fdd87aa3c48d843e43db64af8814abb473f4f0 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 8 Apr 2014 17:50:11 -0700 Subject: [PATCH 224/595] add apache header to mtc main --- tools/mtc/src/main.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tools/mtc/src/main.cpp b/tools/mtc/src/main.cpp index b7e2929d49..b1cd154a48 100644 --- a/tools/mtc/src/main.cpp +++ b/tools/mtc/src/main.cpp @@ -1,10 +1,12 @@ // // main.cpp -// mtc +// tools/mtc/src // // Created by Andrzej Kapolka on 12/31/13. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html #include From 5b822dc57c9b9ffe493c4bf345efd5d4a887d76d Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 8 Apr 2014 17:54:54 -0700 Subject: [PATCH 225/595] inital licensing fixes for JS headers --- examples/addVoxelOnMouseClickExample.js | 6 ++++-- examples/audioBall.js | 7 +++++-- examples/audioDeviceExample.js | 8 +++++--- examples/bot.js | 6 ++++-- examples/cameraExample.js | 6 ++++-- examples/clipboardExample.js | 6 ++++-- examples/collidingParticles.js | 6 ++++-- examples/controllerExample.js | 6 ++++-- examples/count.js | 8 ++++++-- examples/crazylegs.js | 7 +++++-- examples/defaultScripts.js | 9 ++++++++- examples/editParticleExample.js | 7 +++++-- 12 files changed, 58 insertions(+), 24 deletions(-) diff --git a/examples/addVoxelOnMouseClickExample.js b/examples/addVoxelOnMouseClickExample.js index 244a017ae4..4fa175577c 100644 --- a/examples/addVoxelOnMouseClickExample.js +++ b/examples/addVoxelOnMouseClickExample.js @@ -1,13 +1,15 @@ // // addVoxelOnMouseClickExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 2/6/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates use of the Camera and Voxels class to implement // clicking on a voxel and adding a new voxel on the clicked on face // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // function mousePressEvent(event) { diff --git a/examples/audioBall.js b/examples/audioBall.js index 0889d9eb31..2a77a0999f 100644 --- a/examples/audioBall.js +++ b/examples/audioBall.js @@ -1,14 +1,17 @@ // // audioBall.js -// hifi +// examples // // Created by Athanasios Gaitatzes on 2/10/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // // This script creates a particle in front of the user that stays in front of // the user's avatar as they move, and animates it's radius and color // in response to the audio intensity. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// var sound = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Animals/mexicanWhipoorwill.raw"); var CHANCE_OF_PLAYING_SOUND = 0.01; diff --git a/examples/audioDeviceExample.js b/examples/audioDeviceExample.js index 1ee00a1582..959b21f848 100644 --- a/examples/audioDeviceExample.js +++ b/examples/audioDeviceExample.js @@ -1,13 +1,15 @@ // // audioDeviceExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 3/22/14 -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // // This is an example script that demonstrates use of the Menu object // - +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// var outputDevices = AudioDevice.getOutputDevices(); var defaultOutputDevice = AudioDevice.getDefaultOutputDevice(); diff --git a/examples/bot.js b/examples/bot.js index ccbc24bc3d..f7a0429c53 100644 --- a/examples/bot.js +++ b/examples/bot.js @@ -1,13 +1,15 @@ // // bot.js -// hifi +// examples // // Created by Stephen Birarda on 2/20/14. // Modified by Philip on 3/3/14 -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates an NPC avatar. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // function getRandomFloat(min, max) { diff --git a/examples/cameraExample.js b/examples/cameraExample.js index 6e3c51a348..332cc0fbca 100644 --- a/examples/cameraExample.js +++ b/examples/cameraExample.js @@ -1,12 +1,14 @@ // // cameraExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 2/6/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates use of the Camera class // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // var damping = 0.9; diff --git a/examples/clipboardExample.js b/examples/clipboardExample.js index 4972505dfe..e9f581f581 100644 --- a/examples/clipboardExample.js +++ b/examples/clipboardExample.js @@ -1,12 +1,14 @@ // // clipboardExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 1/28/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 HighFidelity, Inc. All rights reserved. // // This is an example script that demonstrates use of the Clipboard class // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // var selectedVoxel = { x: 0, y: 0, z: 0, s: 0 }; diff --git a/examples/collidingParticles.js b/examples/collidingParticles.js index 95520df757..1f1899c8f2 100644 --- a/examples/collidingParticles.js +++ b/examples/collidingParticles.js @@ -1,14 +1,16 @@ // // collidingParticles.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 12/31/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // // This is an example script that creates a couple particles, and sends them on a collision course. // One of the particles has a script that when it collides with another particle, it swaps colors with that particle. // The other particle has a script that when it collides with another particle it set's it's script to a suicide script. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // var currentIteration = 0; diff --git a/examples/controllerExample.js b/examples/controllerExample.js index ebb013913e..66a9e40c56 100644 --- a/examples/controllerExample.js +++ b/examples/controllerExample.js @@ -1,12 +1,14 @@ // // controllerExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 1/28/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates use of the Controller class // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // initialize our triggers diff --git a/examples/count.js b/examples/count.js index e04bc2c94b..1a59d6af36 100644 --- a/examples/count.js +++ b/examples/count.js @@ -1,12 +1,16 @@ // // count.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 12/31/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. All rights reserved. // // This is an example script that runs in a loop and displays a counter to the log // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// +// var count = 0; diff --git a/examples/crazylegs.js b/examples/crazylegs.js index 19a171dbdf..6311aea6e4 100644 --- a/examples/crazylegs.js +++ b/examples/crazylegs.js @@ -1,9 +1,12 @@ // // crazylegs.js -// hifi +// examples // // Created by Andrzej Kapolka on 3/6/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // var FREQUENCY = 5.0; diff --git a/examples/defaultScripts.js b/examples/defaultScripts.js index 722b21844f..ede2d0f6b6 100644 --- a/examples/defaultScripts.js +++ b/examples/defaultScripts.js @@ -1,5 +1,12 @@ +// // defaultScripts.js -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// examples +// +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html + Script.include("lookWithTouch.js"); Script.include("editVoxels.js"); Script.include("selectAudioDevice.js"); diff --git a/examples/editParticleExample.js b/examples/editParticleExample.js index b632e0229b..54c94d0ef3 100644 --- a/examples/editParticleExample.js +++ b/examples/editParticleExample.js @@ -1,12 +1,15 @@ // // editParticleExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 12/31/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates creating and editing a particle // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// var count = 0; var moveUntil = 2000; From 71c3443614e9981ab9648f6b80598413ae1ab48c Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 8 Apr 2014 17:56:56 -0700 Subject: [PATCH 226/595] mass replacement of js of hifi with examples --- examples/editVoxels.js | 7 +++++-- examples/findParticleExample.js | 2 +- examples/flockingBirds.js | 2 +- examples/globalCollisionsExample.js | 2 +- examples/gun.js | 2 +- examples/hideAvatarExample.js | 2 +- examples/hydraMove.js | 2 +- examples/includeExample.js | 2 +- examples/inspect.js | 2 +- examples/lookAtExample.js | 2 +- examples/lookWithMouse.js | 2 +- examples/lookWithTouch.js | 2 +- examples/menuExample.js | 2 +- examples/multitouchExample.js | 2 +- examples/overlaysExample.js | 2 +- examples/paintGun.js | 2 +- examples/particleBird.js | 2 +- examples/particleModelExample.js | 2 +- examples/rayPickExample.js | 2 +- examples/ribbon.js | 2 +- examples/rideAlongWithAParticleExample.js | 2 +- examples/seeingVoxelsExample.js | 2 +- examples/selectAudioDevice.js | 2 +- examples/settingsExample.js | 2 +- examples/spaceInvadersExample.js | 2 +- examples/toyball.js | 2 +- examples/voxelDrumming.js | 2 +- 27 files changed, 31 insertions(+), 28 deletions(-) diff --git a/examples/editVoxels.js b/examples/editVoxels.js index 2a0ed98000..31e8da8e74 100644 --- a/examples/editVoxels.js +++ b/examples/editVoxels.js @@ -1,9 +1,9 @@ // // editVoxels.js -// hifi +// examples // // Created by Philip Rosedale on February 8, 2014 -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // // Captures mouse clicks and edits voxels accordingly. // @@ -15,6 +15,9 @@ // // Click and drag to create more new voxels in the same direction // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// var windowDimensions = Controller.getViewportDimensions(); diff --git a/examples/findParticleExample.js b/examples/findParticleExample.js index 4a0e9b832a..7b95103f0e 100644 --- a/examples/findParticleExample.js +++ b/examples/findParticleExample.js @@ -1,6 +1,6 @@ // // findParticleExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 1/24/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/flockingBirds.js b/examples/flockingBirds.js index 12b402ab40..5b0e26267e 100644 --- a/examples/flockingBirds.js +++ b/examples/flockingBirds.js @@ -1,6 +1,6 @@ // // flockingBirds.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 3/4/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/globalCollisionsExample.js b/examples/globalCollisionsExample.js index 7abf707cbf..bd282086ea 100644 --- a/examples/globalCollisionsExample.js +++ b/examples/globalCollisionsExample.js @@ -1,6 +1,6 @@ // // globalCollisionsExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 1/29/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/gun.js b/examples/gun.js index 7bdde19d94..b340b7c7c9 100644 --- a/examples/gun.js +++ b/examples/gun.js @@ -1,6 +1,6 @@ // // gun.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 12/31/13. // Modified by Philip on 3/3/14 diff --git a/examples/hideAvatarExample.js b/examples/hideAvatarExample.js index 7a0ece76eb..c22e0e0593 100644 --- a/examples/hideAvatarExample.js +++ b/examples/hideAvatarExample.js @@ -1,6 +1,6 @@ // // hideAvatarExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 1/28/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/hydraMove.js b/examples/hydraMove.js index 6268a38ba3..21e974d0af 100644 --- a/examples/hydraMove.js +++ b/examples/hydraMove.js @@ -1,6 +1,6 @@ // // hydraMove.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 2/10/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/includeExample.js b/examples/includeExample.js index 489928d759..03b3f22858 100644 --- a/examples/includeExample.js +++ b/examples/includeExample.js @@ -1,6 +1,6 @@ // // includeExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 3/24/14 // Copyright (c) 2013 HighFidelity, Inc. All rights reserved. diff --git a/examples/inspect.js b/examples/inspect.js index 2443eadf9b..be9675afd4 100644 --- a/examples/inspect.js +++ b/examples/inspect.js @@ -1,6 +1,6 @@ // // inspect.js -// hifi +// examples // // Created by Clément Brisset on March 20, 2014 // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/lookAtExample.js b/examples/lookAtExample.js index 46e0863231..6a68b6c4fb 100644 --- a/examples/lookAtExample.js +++ b/examples/lookAtExample.js @@ -1,6 +1,6 @@ // // lookAtExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 2/6/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/lookWithMouse.js b/examples/lookWithMouse.js index ef8f11ec16..84aad1d553 100644 --- a/examples/lookWithMouse.js +++ b/examples/lookWithMouse.js @@ -1,6 +1,6 @@ // // lookWithMouse.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 1/28/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/lookWithTouch.js b/examples/lookWithTouch.js index 4406b4567e..d7bf00e67f 100644 --- a/examples/lookWithTouch.js +++ b/examples/lookWithTouch.js @@ -1,6 +1,6 @@ // // lookWithTouch.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 1/28/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/menuExample.js b/examples/menuExample.js index 874d95ec31..656983e243 100644 --- a/examples/menuExample.js +++ b/examples/menuExample.js @@ -1,6 +1,6 @@ // // menuExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 2/24/14 // Copyright (c) 2013 HighFidelity, Inc. All rights reserved. diff --git a/examples/multitouchExample.js b/examples/multitouchExample.js index 51bbcc2c20..0c169c27cb 100644 --- a/examples/multitouchExample.js +++ b/examples/multitouchExample.js @@ -1,6 +1,6 @@ // // multitouchExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 2/9/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/overlaysExample.js b/examples/overlaysExample.js index 60f924338f..c7beafad53 100644 --- a/examples/overlaysExample.js +++ b/examples/overlaysExample.js @@ -1,6 +1,6 @@ // // overlaysExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 2/14/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/paintGun.js b/examples/paintGun.js index 0b30d99fb5..a4327b9a3f 100644 --- a/examples/paintGun.js +++ b/examples/paintGun.js @@ -1,6 +1,6 @@ // // paintGun.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 12/31/13. // Copyright (c) 2013 HighFidelity, Inc. All rights reserved. diff --git a/examples/particleBird.js b/examples/particleBird.js index 5cd068bd60..464e1de2a1 100644 --- a/examples/particleBird.js +++ b/examples/particleBird.js @@ -1,6 +1,6 @@ // // particleBird.js -// hifi +// examples // // This sample script moves a voxel around like a bird and sometimes makes tweeting noises // diff --git a/examples/particleModelExample.js b/examples/particleModelExample.js index c43956cd3e..08f718e3ae 100644 --- a/examples/particleModelExample.js +++ b/examples/particleModelExample.js @@ -1,6 +1,6 @@ // // particleModelExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 1/28/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/rayPickExample.js b/examples/rayPickExample.js index 9c34cca1de..a4dfd93fdf 100644 --- a/examples/rayPickExample.js +++ b/examples/rayPickExample.js @@ -1,6 +1,6 @@ // // rayPickExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 2/6/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/ribbon.js b/examples/ribbon.js index a6e1edfa4a..d4ae887c28 100644 --- a/examples/ribbon.js +++ b/examples/ribbon.js @@ -1,6 +1,6 @@ // // ribbon.js -// hifi +// examples // // Created by Andrzej Kapolka on 2/24/14. // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. diff --git a/examples/rideAlongWithAParticleExample.js b/examples/rideAlongWithAParticleExample.js index 1148b96b4d..0d2dee2ddd 100644 --- a/examples/rideAlongWithAParticleExample.js +++ b/examples/rideAlongWithAParticleExample.js @@ -1,6 +1,6 @@ // // rideAlongWithAParticleExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 1/24/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/seeingVoxelsExample.js b/examples/seeingVoxelsExample.js index 0cfe54d89e..2b17f08ac1 100644 --- a/examples/seeingVoxelsExample.js +++ b/examples/seeingVoxelsExample.js @@ -1,6 +1,6 @@ // // seeingVoxelsExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 2/26/14 // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/selectAudioDevice.js b/examples/selectAudioDevice.js index 958ca7babf..872e98d95e 100644 --- a/examples/selectAudioDevice.js +++ b/examples/selectAudioDevice.js @@ -1,6 +1,6 @@ // // audioDeviceExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 3/22/14 // Copyright (c) 2013 HighFidelity, Inc. All rights reserved. diff --git a/examples/settingsExample.js b/examples/settingsExample.js index 0dcc5482b6..6d06f2eb46 100644 --- a/examples/settingsExample.js +++ b/examples/settingsExample.js @@ -1,6 +1,6 @@ // // settingsExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 3/22/14 // Copyright (c) 2013 HighFidelity, Inc. All rights reserved. diff --git a/examples/spaceInvadersExample.js b/examples/spaceInvadersExample.js index df985e2e18..ee2a0547b5 100644 --- a/examples/spaceInvadersExample.js +++ b/examples/spaceInvadersExample.js @@ -1,6 +1,6 @@ // // spaceInvadersExample.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 1/30/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/toyball.js b/examples/toyball.js index 36f1aa11e5..9a89f601b7 100644 --- a/examples/toyball.js +++ b/examples/toyball.js @@ -1,6 +1,6 @@ // // toyball.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 1/20/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/voxelDrumming.js b/examples/voxelDrumming.js index 178c6734d8..0485f1b9e2 100644 --- a/examples/voxelDrumming.js +++ b/examples/voxelDrumming.js @@ -1,6 +1,6 @@ // // voxelDrumming.js -// hifi +// examples // // Created by Brad Hefta-Gaub on 2/14/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. From 8ff244cc1a81e03b04e25b5b2ed185b00bd9ddd3 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 8 Apr 2014 17:58:02 -0700 Subject: [PATCH 227/595] add missing space for example replace in javascripts --- examples/findParticleExample.js | 2 +- examples/flockingBirds.js | 2 +- examples/globalCollisionsExample.js | 2 +- examples/gun.js | 2 +- examples/hideAvatarExample.js | 2 +- examples/hydraMove.js | 2 +- examples/includeExample.js | 2 +- examples/inspect.js | 2 +- examples/lookAtExample.js | 2 +- examples/lookWithMouse.js | 2 +- examples/lookWithTouch.js | 2 +- examples/menuExample.js | 2 +- examples/multitouchExample.js | 2 +- examples/overlaysExample.js | 2 +- examples/paintGun.js | 2 +- examples/particleBird.js | 2 +- examples/particleModelExample.js | 2 +- examples/rayPickExample.js | 2 +- examples/ribbon.js | 2 +- examples/rideAlongWithAParticleExample.js | 2 +- examples/seeingVoxelsExample.js | 2 +- examples/selectAudioDevice.js | 2 +- examples/settingsExample.js | 2 +- examples/spaceInvadersExample.js | 2 +- examples/toyball.js | 2 +- examples/voxelDrumming.js | 2 +- 26 files changed, 26 insertions(+), 26 deletions(-) diff --git a/examples/findParticleExample.js b/examples/findParticleExample.js index 7b95103f0e..0b07471273 100644 --- a/examples/findParticleExample.js +++ b/examples/findParticleExample.js @@ -1,6 +1,6 @@ // // findParticleExample.js -// examples +// examples // // Created by Brad Hefta-Gaub on 1/24/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/flockingBirds.js b/examples/flockingBirds.js index 5b0e26267e..a45bcc9f97 100644 --- a/examples/flockingBirds.js +++ b/examples/flockingBirds.js @@ -1,6 +1,6 @@ // // flockingBirds.js -// examples +// examples // // Created by Brad Hefta-Gaub on 3/4/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/globalCollisionsExample.js b/examples/globalCollisionsExample.js index bd282086ea..6dfd4ee3f8 100644 --- a/examples/globalCollisionsExample.js +++ b/examples/globalCollisionsExample.js @@ -1,6 +1,6 @@ // // globalCollisionsExample.js -// examples +// examples // // Created by Brad Hefta-Gaub on 1/29/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/gun.js b/examples/gun.js index b340b7c7c9..6d3bbb2193 100644 --- a/examples/gun.js +++ b/examples/gun.js @@ -1,6 +1,6 @@ // // gun.js -// examples +// examples // // Created by Brad Hefta-Gaub on 12/31/13. // Modified by Philip on 3/3/14 diff --git a/examples/hideAvatarExample.js b/examples/hideAvatarExample.js index c22e0e0593..046ebc1a3b 100644 --- a/examples/hideAvatarExample.js +++ b/examples/hideAvatarExample.js @@ -1,6 +1,6 @@ // // hideAvatarExample.js -// examples +// examples // // Created by Brad Hefta-Gaub on 1/28/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/hydraMove.js b/examples/hydraMove.js index 21e974d0af..9ff776c0eb 100644 --- a/examples/hydraMove.js +++ b/examples/hydraMove.js @@ -1,6 +1,6 @@ // // hydraMove.js -// examples +// examples // // Created by Brad Hefta-Gaub on 2/10/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/includeExample.js b/examples/includeExample.js index 03b3f22858..68c9828630 100644 --- a/examples/includeExample.js +++ b/examples/includeExample.js @@ -1,6 +1,6 @@ // // includeExample.js -// examples +// examples // // Created by Brad Hefta-Gaub on 3/24/14 // Copyright (c) 2013 HighFidelity, Inc. All rights reserved. diff --git a/examples/inspect.js b/examples/inspect.js index be9675afd4..1b220ad333 100644 --- a/examples/inspect.js +++ b/examples/inspect.js @@ -1,6 +1,6 @@ // // inspect.js -// examples +// examples // // Created by Clément Brisset on March 20, 2014 // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/lookAtExample.js b/examples/lookAtExample.js index 6a68b6c4fb..c76273a3c7 100644 --- a/examples/lookAtExample.js +++ b/examples/lookAtExample.js @@ -1,6 +1,6 @@ // // lookAtExample.js -// examples +// examples // // Created by Brad Hefta-Gaub on 2/6/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/lookWithMouse.js b/examples/lookWithMouse.js index 84aad1d553..02bf9fbe13 100644 --- a/examples/lookWithMouse.js +++ b/examples/lookWithMouse.js @@ -1,6 +1,6 @@ // // lookWithMouse.js -// examples +// examples // // Created by Brad Hefta-Gaub on 1/28/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/lookWithTouch.js b/examples/lookWithTouch.js index d7bf00e67f..71d0137533 100644 --- a/examples/lookWithTouch.js +++ b/examples/lookWithTouch.js @@ -1,6 +1,6 @@ // // lookWithTouch.js -// examples +// examples // // Created by Brad Hefta-Gaub on 1/28/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/menuExample.js b/examples/menuExample.js index 656983e243..92081038f5 100644 --- a/examples/menuExample.js +++ b/examples/menuExample.js @@ -1,6 +1,6 @@ // // menuExample.js -// examples +// examples // // Created by Brad Hefta-Gaub on 2/24/14 // Copyright (c) 2013 HighFidelity, Inc. All rights reserved. diff --git a/examples/multitouchExample.js b/examples/multitouchExample.js index 0c169c27cb..4a4b6427f8 100644 --- a/examples/multitouchExample.js +++ b/examples/multitouchExample.js @@ -1,6 +1,6 @@ // // multitouchExample.js -// examples +// examples // // Created by Brad Hefta-Gaub on 2/9/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/overlaysExample.js b/examples/overlaysExample.js index c7beafad53..5b2c89391e 100644 --- a/examples/overlaysExample.js +++ b/examples/overlaysExample.js @@ -1,6 +1,6 @@ // // overlaysExample.js -// examples +// examples // // Created by Brad Hefta-Gaub on 2/14/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/paintGun.js b/examples/paintGun.js index a4327b9a3f..e7477318ed 100644 --- a/examples/paintGun.js +++ b/examples/paintGun.js @@ -1,6 +1,6 @@ // // paintGun.js -// examples +// examples // // Created by Brad Hefta-Gaub on 12/31/13. // Copyright (c) 2013 HighFidelity, Inc. All rights reserved. diff --git a/examples/particleBird.js b/examples/particleBird.js index 464e1de2a1..86ee6e7aa4 100644 --- a/examples/particleBird.js +++ b/examples/particleBird.js @@ -1,6 +1,6 @@ // // particleBird.js -// examples +// examples // // This sample script moves a voxel around like a bird and sometimes makes tweeting noises // diff --git a/examples/particleModelExample.js b/examples/particleModelExample.js index 08f718e3ae..5f99c46d7b 100644 --- a/examples/particleModelExample.js +++ b/examples/particleModelExample.js @@ -1,6 +1,6 @@ // // particleModelExample.js -// examples +// examples // // Created by Brad Hefta-Gaub on 1/28/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/rayPickExample.js b/examples/rayPickExample.js index a4dfd93fdf..7e20a4e95d 100644 --- a/examples/rayPickExample.js +++ b/examples/rayPickExample.js @@ -1,6 +1,6 @@ // // rayPickExample.js -// examples +// examples // // Created by Brad Hefta-Gaub on 2/6/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/ribbon.js b/examples/ribbon.js index d4ae887c28..be8b521f7c 100644 --- a/examples/ribbon.js +++ b/examples/ribbon.js @@ -1,6 +1,6 @@ // // ribbon.js -// examples +// examples // // Created by Andrzej Kapolka on 2/24/14. // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. diff --git a/examples/rideAlongWithAParticleExample.js b/examples/rideAlongWithAParticleExample.js index 0d2dee2ddd..ce0133b25c 100644 --- a/examples/rideAlongWithAParticleExample.js +++ b/examples/rideAlongWithAParticleExample.js @@ -1,6 +1,6 @@ // // rideAlongWithAParticleExample.js -// examples +// examples // // Created by Brad Hefta-Gaub on 1/24/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/seeingVoxelsExample.js b/examples/seeingVoxelsExample.js index 2b17f08ac1..e7a9e9f07a 100644 --- a/examples/seeingVoxelsExample.js +++ b/examples/seeingVoxelsExample.js @@ -1,6 +1,6 @@ // // seeingVoxelsExample.js -// examples +// examples // // Created by Brad Hefta-Gaub on 2/26/14 // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/selectAudioDevice.js b/examples/selectAudioDevice.js index 872e98d95e..be3f621cdb 100644 --- a/examples/selectAudioDevice.js +++ b/examples/selectAudioDevice.js @@ -1,6 +1,6 @@ // // audioDeviceExample.js -// examples +// examples // // Created by Brad Hefta-Gaub on 3/22/14 // Copyright (c) 2013 HighFidelity, Inc. All rights reserved. diff --git a/examples/settingsExample.js b/examples/settingsExample.js index 6d06f2eb46..53e8a8a63c 100644 --- a/examples/settingsExample.js +++ b/examples/settingsExample.js @@ -1,6 +1,6 @@ // // settingsExample.js -// examples +// examples // // Created by Brad Hefta-Gaub on 3/22/14 // Copyright (c) 2013 HighFidelity, Inc. All rights reserved. diff --git a/examples/spaceInvadersExample.js b/examples/spaceInvadersExample.js index ee2a0547b5..7dd5037cda 100644 --- a/examples/spaceInvadersExample.js +++ b/examples/spaceInvadersExample.js @@ -1,6 +1,6 @@ // // spaceInvadersExample.js -// examples +// examples // // Created by Brad Hefta-Gaub on 1/30/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/toyball.js b/examples/toyball.js index 9a89f601b7..9b57987eca 100644 --- a/examples/toyball.js +++ b/examples/toyball.js @@ -1,6 +1,6 @@ // // toyball.js -// examples +// examples // // Created by Brad Hefta-Gaub on 1/20/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. diff --git a/examples/voxelDrumming.js b/examples/voxelDrumming.js index 0485f1b9e2..e8f852ccf2 100644 --- a/examples/voxelDrumming.js +++ b/examples/voxelDrumming.js @@ -1,6 +1,6 @@ // // voxelDrumming.js -// examples +// examples // // Created by Brad Hefta-Gaub on 2/14/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. From 0f204f932c9e505920f74acc8c48f909686a6dab Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 8 Apr 2014 18:00:24 -0700 Subject: [PATCH 228/595] add apache license information to more js files --- examples/globalCollisionsExample.js | 2 ++ examples/gun.js | 2 ++ examples/hideAvatarExample.js | 2 ++ examples/hydraMove.js | 2 ++ examples/includeExample.js | 3 +++ examples/inspect.js | 3 +++ examples/lookAtExample.js | 2 ++ examples/lookWithMouse.js | 2 ++ examples/lookWithTouch.js | 2 ++ examples/menuExample.js | 3 +++ examples/multitouchExample.js | 3 +++ examples/overlaysExample.js | 2 ++ examples/paintGun.js | 3 +++ examples/particleBird.js | 3 +++ examples/particleModelExample.js | 3 +++ examples/playSound.js | 2 ++ examples/rayPickExample.js | 2 ++ examples/ribbon.js | 3 +++ examples/rideAlongWithAParticleExample.js | 3 +++ examples/seeingVoxelsExample.js | 3 +++ examples/selectAudioDevice.js | 3 +++ examples/settingsExample.js | 6 +++--- examples/spaceInvadersExample.js | 3 +++ examples/toyball.js | 2 ++ examples/voxelDrumming.js | 3 +++ 25 files changed, 64 insertions(+), 3 deletions(-) diff --git a/examples/globalCollisionsExample.js b/examples/globalCollisionsExample.js index 6dfd4ee3f8..b9d1dceefe 100644 --- a/examples/globalCollisionsExample.js +++ b/examples/globalCollisionsExample.js @@ -7,6 +7,8 @@ // // This is an example script that demonstrates use of the Controller class // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/examples/gun.js b/examples/gun.js index 6d3bbb2193..85d0f9c1e5 100644 --- a/examples/gun.js +++ b/examples/gun.js @@ -10,6 +10,8 @@ // It reads the controller, watches for trigger pulls, and launches particles. // When particles collide with voxels they blow little holes out of the voxels. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/examples/hideAvatarExample.js b/examples/hideAvatarExample.js index 046ebc1a3b..d9e4b350f4 100644 --- a/examples/hideAvatarExample.js +++ b/examples/hideAvatarExample.js @@ -7,6 +7,8 @@ // // This is an example script that demonstrates how to enable or disable local rendering of your own avatar // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // function keyReleaseEvent(event) { diff --git a/examples/hydraMove.js b/examples/hydraMove.js index 9ff776c0eb..e2dd608b4a 100644 --- a/examples/hydraMove.js +++ b/examples/hydraMove.js @@ -8,6 +8,8 @@ // This is an example script that demonstrates use of the Controller and MyAvatar classes to implement // avatar flying through the hydra/controller joysticks // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // var damping = 0.9; diff --git a/examples/includeExample.js b/examples/includeExample.js index 68c9828630..e82a95fc63 100644 --- a/examples/includeExample.js +++ b/examples/includeExample.js @@ -7,6 +7,9 @@ // // This is an example script that demonstrates use of the Script.include() feature // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// // You can include scripts from URLs Script.include("http://public.highfidelity.io/scripts/lookWithTouch.js"); diff --git a/examples/inspect.js b/examples/inspect.js index 1b220ad333..5402a6a830 100644 --- a/examples/inspect.js +++ b/examples/inspect.js @@ -13,6 +13,9 @@ // Once you are in a mode left click on the object to inspect and hold the click // Dragging the mouse will move your camera according to the mode you are in. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// var PI = 3.14 // No need for something more precise diff --git a/examples/lookAtExample.js b/examples/lookAtExample.js index c76273a3c7..6e208ddbdd 100644 --- a/examples/lookAtExample.js +++ b/examples/lookAtExample.js @@ -12,6 +12,8 @@ // on the face of the voxel that you clicked. Click again and it will stop looking at that point. While in this fixed mode // you can use the arrow keys to change the position of the camera. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // var lookingAtSomething = false; diff --git a/examples/lookWithMouse.js b/examples/lookWithMouse.js index 02bf9fbe13..4293654ae5 100644 --- a/examples/lookWithMouse.js +++ b/examples/lookWithMouse.js @@ -7,6 +7,8 @@ // // This is an example script that demonstrates use of the Controller class // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // var alwaysLook = true; // if you want the mouse look to happen only when you click, change this to false diff --git a/examples/lookWithTouch.js b/examples/lookWithTouch.js index 71d0137533..0278d2b7b2 100644 --- a/examples/lookWithTouch.js +++ b/examples/lookWithTouch.js @@ -7,6 +7,8 @@ // // This is an example script that demonstrates use of the Controller class // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // var startedTouching = false; diff --git a/examples/menuExample.js b/examples/menuExample.js index 92081038f5..d448c32bf8 100644 --- a/examples/menuExample.js +++ b/examples/menuExample.js @@ -7,6 +7,9 @@ // // This is an example script that demonstrates use of the Menu object // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// function setupMenus() { diff --git a/examples/multitouchExample.js b/examples/multitouchExample.js index 4a4b6427f8..b76902f57a 100644 --- a/examples/multitouchExample.js +++ b/examples/multitouchExample.js @@ -11,6 +11,9 @@ // * Four finger rotate gesture will rotate your avatar. // * Three finger swipe up/down will adjust the pitch of your avatars head. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// var lastX = 0; var lastY = 0; diff --git a/examples/overlaysExample.js b/examples/overlaysExample.js index 5b2c89391e..ec54438692 100644 --- a/examples/overlaysExample.js +++ b/examples/overlaysExample.js @@ -7,6 +7,8 @@ // // This is an example script that demonstrates use of the Overlays class // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/examples/paintGun.js b/examples/paintGun.js index e7477318ed..fa2d4f1e1f 100644 --- a/examples/paintGun.js +++ b/examples/paintGun.js @@ -5,6 +5,9 @@ // Created by Brad Hefta-Gaub on 12/31/13. // Copyright (c) 2013 HighFidelity, Inc. All rights reserved. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// // initialize our triggers var triggerPulled = new Array(); diff --git a/examples/particleBird.js b/examples/particleBird.js index 86ee6e7aa4..59ada1950e 100644 --- a/examples/particleBird.js +++ b/examples/particleBird.js @@ -4,6 +4,9 @@ // // This sample script moves a voxel around like a bird and sometimes makes tweeting noises // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// function vLength(v) { return Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z); diff --git a/examples/particleModelExample.js b/examples/particleModelExample.js index 5f99c46d7b..96b16c503d 100644 --- a/examples/particleModelExample.js +++ b/examples/particleModelExample.js @@ -7,6 +7,9 @@ // // This is an example script that demonstrates creating and editing a particle // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// var count = 0; var stopAfter = 100; diff --git a/examples/playSound.js b/examples/playSound.js index 18857826ea..7715604de2 100644 --- a/examples/playSound.js +++ b/examples/playSound.js @@ -1,6 +1,8 @@ // // This sample script loads a sound file and plays it at the 'fingertip' of the // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // First, load the clap sound from a URL var clap = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Animals/bushtit_1.raw"); diff --git a/examples/rayPickExample.js b/examples/rayPickExample.js index 7e20a4e95d..13ab285af5 100644 --- a/examples/rayPickExample.js +++ b/examples/rayPickExample.js @@ -7,6 +7,8 @@ // // This is an example script that demonstrates use of the Camera class // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // function mouseMoveEvent(event) { diff --git a/examples/ribbon.js b/examples/ribbon.js index be8b521f7c..5e48ee3193 100644 --- a/examples/ribbon.js +++ b/examples/ribbon.js @@ -5,6 +5,9 @@ // Created by Andrzej Kapolka on 2/24/14. // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// function vectorMultiply(vector, scalar) { return [ vector[0] * scalar, vector[1] * scalar, vector[2] * scalar ]; diff --git a/examples/rideAlongWithAParticleExample.js b/examples/rideAlongWithAParticleExample.js index ce0133b25c..a6decbc2c2 100644 --- a/examples/rideAlongWithAParticleExample.js +++ b/examples/rideAlongWithAParticleExample.js @@ -7,6 +7,9 @@ // // This is an example script that demonstrates "finding" particles // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// var iteration = 0; var lengthOfRide = 2000; // in iterations diff --git a/examples/seeingVoxelsExample.js b/examples/seeingVoxelsExample.js index e7a9e9f07a..e0f991ea40 100644 --- a/examples/seeingVoxelsExample.js +++ b/examples/seeingVoxelsExample.js @@ -7,6 +7,9 @@ // // This is an example script // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// var count = 0; var yawDirection = -1; diff --git a/examples/selectAudioDevice.js b/examples/selectAudioDevice.js index be3f621cdb..668e467254 100644 --- a/examples/selectAudioDevice.js +++ b/examples/selectAudioDevice.js @@ -7,6 +7,9 @@ // // This is an example script that demonstrates use of the Menu object // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// if (typeof String.prototype.startsWith != 'function') { String.prototype.startsWith = function (str){ diff --git a/examples/settingsExample.js b/examples/settingsExample.js index 53e8a8a63c..816fc956a3 100644 --- a/examples/settingsExample.js +++ b/examples/settingsExample.js @@ -7,9 +7,9 @@ // // This is an example script that demonstrates use of the Menu object // - - - +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// print("mySetting: " + Settings.getValue("mySetting")); Settings.setValue("mySetting", "spam"); diff --git a/examples/spaceInvadersExample.js b/examples/spaceInvadersExample.js index 7dd5037cda..be4fcf445f 100644 --- a/examples/spaceInvadersExample.js +++ b/examples/spaceInvadersExample.js @@ -7,6 +7,9 @@ // // This is an example script that demonstrates a simple space invaders style of game // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// var iteration = 0; diff --git a/examples/toyball.js b/examples/toyball.js index 9b57987eca..52646c94b4 100644 --- a/examples/toyball.js +++ b/examples/toyball.js @@ -11,6 +11,8 @@ // The particles it creates have a script that when they collide with Voxels, the // particle will change it's color to match the voxel it hits. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // maybe we should make these constants... diff --git a/examples/voxelDrumming.js b/examples/voxelDrumming.js index e8f852ccf2..f064d6736e 100644 --- a/examples/voxelDrumming.js +++ b/examples/voxelDrumming.js @@ -9,6 +9,9 @@ // // It adds Hydra controller "fingertip on voxels" drumming // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// Menu.addMenuItem({ menuName: "Developer > Hand Options", From 5b0e7f818d623c064e21acc0566563a2a4326ad8 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Tue, 8 Apr 2014 18:03:49 -0700 Subject: [PATCH 229/595] More work on Faceplus integration/cleaning up support for multiple face trackers. --- interface/src/Application.cpp | 56 ++++++++++++++++----------- interface/src/Application.h | 7 +++- interface/src/avatar/MyAvatar.cpp | 24 ++++-------- interface/src/devices/FaceTracker.cpp | 14 +++++++ interface/src/devices/FaceTracker.h | 43 ++++++++++++++++++++ interface/src/devices/Faceplus.cpp | 32 +++++++++++++++ interface/src/devices/Faceplus.h | 34 ++++++++++++++++ interface/src/devices/Faceshift.cpp | 4 +- interface/src/devices/Faceshift.h | 19 ++------- interface/src/devices/Visage.cpp | 4 +- interface/src/devices/Visage.h | 21 ++-------- 11 files changed, 178 insertions(+), 80 deletions(-) create mode 100644 interface/src/devices/FaceTracker.cpp create mode 100644 interface/src/devices/FaceTracker.h create mode 100644 interface/src/devices/Faceplus.cpp create mode 100644 interface/src/devices/Faceplus.h diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 45ae36a23b..5c50f76767 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1342,6 +1342,12 @@ glm::vec3 Application::getMouseVoxelWorldCoordinates(const VoxelDetail& mouseVox (mouseVoxel.z + mouseVoxel.s / 2.f) * TREE_SCALE); } +FaceTracker* Application::getActiveFaceTracker() { + return _faceshift.isActive() ? static_cast(&_faceshift) : + (_faceplus.isActive() ? static_cast(&_faceplus) : + (_visage.isActive() ? static_cast(&_visage) : NULL)); +} + struct SendVoxelsOperationArgs { const unsigned char* newBaseOctCode; }; @@ -1561,7 +1567,8 @@ void Application::init() { } qDebug("Loaded settings"); - // initialize Visage and Faceshift after loading the menu settings + // initialize our face trackers after loading the menu settings + _faceplus.init(); _faceshift.init(); _visage.init(); @@ -1682,6 +1689,15 @@ void Application::updateMouseRay() { _myAvatar->setMouseRay(_mouseRayOrigin, _mouseRayDirection); } +void Application::updateFaceplus() { + + bool showWarnings = Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings); + PerformanceWarning warn(showWarnings, "Application::updateFaceplus()"); + + // Update faceplus + _faceplus.update(); +} + void Application::updateFaceshift() { bool showWarnings = Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings); @@ -1726,19 +1742,11 @@ void Application::updateMyAvatarLookAtPosition() { glm::distance(_mouseRayOrigin, _myAvatar->getHead()->calculateAverageEyePosition())); lookAtSpot = _mouseRayOrigin + _mouseRayDirection * qMax(minEyeDistance, distance); } - bool trackerActive = false; - float eyePitch, eyeYaw; - if (_faceshift.isActive()) { - eyePitch = _faceshift.getEstimatedEyePitch(); - eyeYaw = _faceshift.getEstimatedEyeYaw(); - trackerActive = true; - - } else if (_visage.isActive()) { - eyePitch = _visage.getEstimatedEyePitch(); - eyeYaw = _visage.getEstimatedEyeYaw(); - trackerActive = true; - } - if (trackerActive) { + FaceTracker* tracker = getActiveFaceTracker(); + if (tracker) { + float eyePitch = tracker->getEstimatedEyePitch(); + float eyeYaw = tracker->getEstimatedEyeYaw(); + // deflect using Faceshift gaze data glm::vec3 origin = _myAvatar->getHead()->calculateAverageEyePosition(); float pitchSign = (_myCamera.getMode() == CAMERA_MODE_MIRROR) ? -1.0f : 1.0f; @@ -1824,15 +1832,15 @@ void Application::updateCamera(float deltaTime) { bool showWarnings = Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings); PerformanceWarning warn(showWarnings, "Application::updateCamera()"); - if (!OculusManager::isConnected() && !TV3DManager::isConnected()) { - if (Menu::getInstance()->isOptionChecked(MenuOption::OffAxisProjection)) { - float xSign = _myCamera.getMode() == CAMERA_MODE_MIRROR ? 1.0f : -1.0f; - if (_faceshift.isActive()) { - const float EYE_OFFSET_SCALE = 0.025f; - glm::vec3 position = _faceshift.getHeadTranslation() * EYE_OFFSET_SCALE; - _myCamera.setEyeOffsetPosition(glm::vec3(position.x * xSign, position.y, -position.z)); - updateProjectionMatrix(); - } + if (!OculusManager::isConnected() && !TV3DManager::isConnected() && + Menu::getInstance()->isOptionChecked(MenuOption::OffAxisProjection)) { + FaceTracker* tracker = getActiveFaceTracker(); + if (tracker) { + const float EYE_OFFSET_SCALE = 0.025f; + glm::vec3 position = tracker->getHeadTranslation() * EYE_OFFSET_SCALE; + float xSign = (_myCamera.getMode() == CAMERA_MODE_MIRROR) ? 1.0f : -1.0f; + _myCamera.setEyeOffsetPosition(glm::vec3(position.x * xSign, position.y, -position.z)); + updateProjectionMatrix(); } } } @@ -1886,6 +1894,7 @@ void Application::update(float deltaTime) { // check what's under the mouse and update the mouse voxel updateMouseRay(); + updateFaceplus(); updateFaceshift(); updateVisage(); _myAvatar->updateLookAtTargetAvatar(); @@ -2936,6 +2945,7 @@ void Application::resetSensors() { _mouseX = _glWidget->width() / 2; _mouseY = _glWidget->height() / 2; + _faceplus.reset(); _faceshift.reset(); _visage.reset(); diff --git a/interface/src/Application.h b/interface/src/Application.h index 7c1cb9cab1..c6b38b1644 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -49,6 +49,7 @@ #include "avatar/Avatar.h" #include "avatar/AvatarManager.h" #include "avatar/MyAvatar.h" +#include "devices/Faceplus.h" #include "devices/Faceshift.h" #include "devices/SixenseManager.h" #include "devices/Visage.h" @@ -173,8 +174,10 @@ public: bool isMouseHidden() const { return _mouseHidden; } const glm::vec3& getMouseRayOrigin() const { return _mouseRayOrigin; } const glm::vec3& getMouseRayDirection() const { return _mouseRayDirection; } + Faceplus* getFaceplus() { return &_faceplus; } Faceshift* getFaceshift() { return &_faceshift; } Visage* getVisage() { return &_visage; } + FaceTracker* getActiveFaceTracker(); SixenseManager* getSixenseManager() { return &_sixenseManager; } BandwidthMeter* getBandwidthMeter() { return &_bandwidthMeter; } QUndoStack* getUndoStack() { return &_undoStack; } @@ -313,6 +316,7 @@ private: // Various helper functions called during update() void updateLOD(); void updateMouseRay(); + void updateFaceplus(); void updateFaceshift(); void updateVisage(); void updateMyAvatarLookAtPosition(); @@ -412,9 +416,10 @@ private: AvatarManager _avatarManager; MyAvatar* _myAvatar; // TODO: move this and relevant code to AvatarManager (or MyAvatar as the case may be) + Faceplus _faceplus; Faceshift _faceshift; Visage _visage; - + SixenseManager _sixenseManager; Camera _myCamera; // My view onto the world diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 73d2a84eb7..6c7ac5b82c 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -309,24 +309,13 @@ void MyAvatar::simulate(float deltaTime) { // Update avatar head rotation with sensor data void MyAvatar::updateFromGyros(float deltaTime) { - Faceshift* faceshift = Application::getInstance()->getFaceshift(); - Visage* visage = Application::getInstance()->getVisage(); glm::vec3 estimatedPosition, estimatedRotation; - bool trackerActive = false; - if (faceshift->isActive()) { - estimatedPosition = faceshift->getHeadTranslation(); - estimatedRotation = glm::degrees(safeEulerAngles(faceshift->getHeadRotation())); - trackerActive = true; - - } else if (visage->isActive()) { - estimatedPosition = visage->getHeadTranslation(); - estimatedRotation = glm::degrees(safeEulerAngles(visage->getHeadRotation())); - trackerActive = true; - } - - Head* head = getHead(); - if (trackerActive) { + FaceTracker* tracker = Application::getInstance()->getActiveFaceTracker(); + if (tracker) { + estimatedPosition = tracker->getHeadTranslation(); + estimatedRotation = glm::degrees(safeEulerAngles(tracker->getHeadRotation())); + // Rotate the body if the head is turned beyond the screen if (Menu::getInstance()->isOptionChecked(MenuOption::TurnWithHead)) { const float TRACKER_YAW_TURN_SENSITIVITY = 0.5f; @@ -341,13 +330,14 @@ void MyAvatar::updateFromGyros(float deltaTime) { } } } - } + } // Set the rotation of the avatar's head (as seen by others, not affecting view frustum) // to be scaled. Pitch is greater to emphasize nodding behavior / synchrony. const float AVATAR_HEAD_PITCH_MAGNIFY = 1.0f; const float AVATAR_HEAD_YAW_MAGNIFY = 1.0f; const float AVATAR_HEAD_ROLL_MAGNIFY = 1.0f; + Head* head = getHead(); head->setDeltaPitch(estimatedRotation.x * AVATAR_HEAD_PITCH_MAGNIFY); head->setDeltaYaw(estimatedRotation.y * AVATAR_HEAD_YAW_MAGNIFY); head->setDeltaRoll(estimatedRotation.z * AVATAR_HEAD_ROLL_MAGNIFY); diff --git a/interface/src/devices/FaceTracker.cpp b/interface/src/devices/FaceTracker.cpp new file mode 100644 index 0000000000..45f789fbfe --- /dev/null +++ b/interface/src/devices/FaceTracker.cpp @@ -0,0 +1,14 @@ +// +// FaceTracker.cpp +// interface +// +// Created by Andrzej Kapolka on 4/8/14. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// + +#include "FaceTracker.h" + +FaceTracker::FaceTracker() : + _estimatedEyePitch(0.0f), + _estimatedEyeYaw(0.0f) { +} diff --git a/interface/src/devices/FaceTracker.h b/interface/src/devices/FaceTracker.h new file mode 100644 index 0000000000..659defe591 --- /dev/null +++ b/interface/src/devices/FaceTracker.h @@ -0,0 +1,43 @@ +// +// FaceTracker.h +// interface +// +// Created by Andrzej Kapolka on 4/8/14. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// + +#ifndef __interface__FaceTracker__ +#define __interface__FaceTracker__ + +#include +#include + +#include +#include + +/// Base class for face trackers (Faceshift, Visage, Faceplus). +class FaceTracker : public QObject { + Q_OBJECT + +public: + + FaceTracker(); + + const glm::vec3& getHeadTranslation() const { return _headTranslation; } + const glm::quat& getHeadRotation() const { return _headRotation; } + + float getEstimatedEyePitch() const { return _estimatedEyePitch; } + float getEstimatedEyeYaw() const { return _estimatedEyeYaw; } + + const QVector& getBlendshapeCoefficients() const { return _blendshapeCoefficients; } + +protected: + + glm::vec3 _headTranslation; + glm::quat _headRotation; + float _estimatedEyePitch; + float _estimatedEyeYaw; + QVector _blendshapeCoefficients; +}; + +#endif /* defined(__interface__FaceTracker__) */ diff --git a/interface/src/devices/Faceplus.cpp b/interface/src/devices/Faceplus.cpp new file mode 100644 index 0000000000..64dd4bf52d --- /dev/null +++ b/interface/src/devices/Faceplus.cpp @@ -0,0 +1,32 @@ +// +// Faceplus.cpp +// interface +// +// Created by Andrzej Kapolka on 4/8/14. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// + +#ifdef HAVE_FACEPLUS +#include +#endif + +#include "Faceplus.h" + +Faceplus::Faceplus() : + _active(false) { +} + +void Faceplus::init() { +#ifdef HAVE_FACEPLUS + // these are ignored--any values will do + faceplus_log_in("username", "password"); +#endif +} + +void Faceplus::update() { +} + +void Faceplus::reset() { +} + + diff --git a/interface/src/devices/Faceplus.h b/interface/src/devices/Faceplus.h new file mode 100644 index 0000000000..cf7a6583a1 --- /dev/null +++ b/interface/src/devices/Faceplus.h @@ -0,0 +1,34 @@ +// +// Faceplus.h +// interface +// +// Created by Andrzej Kapolka on 4/8/14. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// + +#ifndef __interface__Faceplus__ +#define __interface__Faceplus__ + +#include "FaceTracker.h" + +/// Interface for Mixamo FacePlus. +class Faceplus : public FaceTracker { + Q_OBJECT + +public: + + Faceplus(); + + void init(); + + bool isActive() const { return _active; } + + void update(); + void reset(); + +private: + + bool _active; +}; + +#endif /* defined(__interface__Faceplus__) */ diff --git a/interface/src/devices/Faceshift.cpp b/interface/src/devices/Faceshift.cpp index 9f1734c7e5..05abcfd0d7 100644 --- a/interface/src/devices/Faceshift.cpp +++ b/interface/src/devices/Faceshift.cpp @@ -42,9 +42,7 @@ Faceshift::Faceshift() : _jawOpenIndex(21), _longTermAverageEyePitch(0.0f), _longTermAverageEyeYaw(0.0f), - _longTermAverageInitialized(false), - _estimatedEyePitch(0.0f), - _estimatedEyeYaw(0.0f) + _longTermAverageInitialized(false) { connect(&_tcpSocket, SIGNAL(connected()), SLOT(noteConnected())); connect(&_tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(noteError(QAbstractSocket::SocketError))); diff --git a/interface/src/devices/Faceshift.h b/interface/src/devices/Faceshift.h index f878056b57..c49c6661e7 100644 --- a/interface/src/devices/Faceshift.h +++ b/interface/src/devices/Faceshift.h @@ -17,8 +17,10 @@ #include +#include "FaceTracker.h" + /// Handles interaction with the Faceshift software, which provides head position/orientation and facial features. -class Faceshift : public QObject { +class Faceshift : public FaceTracker { Q_OBJECT public: @@ -31,9 +33,7 @@ public: bool isActive() const; - const glm::quat& getHeadRotation() const { return _headRotation; } const glm::vec3& getHeadAngularVelocity() const { return _headAngularVelocity; } - const glm::vec3& getHeadTranslation() const { return _headTranslation; } // these pitch/yaw angles are in degrees float getEyeGazeLeftPitch() const { return _eyeGazeLeftPitch; } @@ -42,11 +42,6 @@ public: float getEyeGazeRightPitch() const { return _eyeGazeRightPitch; } float getEyeGazeRightYaw() const { return _eyeGazeRightYaw; } - float getEstimatedEyePitch() const { return _estimatedEyePitch; } - float getEstimatedEyeYaw() const { return _estimatedEyeYaw; } - - const QVector& getBlendshapeCoefficients() const { return _blendshapeCoefficients; } - float getLeftBlink() const { return getBlendshapeCoefficient(_leftBlinkIndex); } float getRightBlink() const { return getBlendshapeCoefficient(_rightBlinkIndex); } float getLeftEyeOpen() const { return getBlendshapeCoefficient(_leftEyeOpenIndex); } @@ -99,9 +94,7 @@ private: bool _tracking; quint64 _lastTrackingStateReceived; - glm::quat _headRotation; glm::vec3 _headAngularVelocity; - glm::vec3 _headTranslation; // degrees float _eyeGazeLeftPitch; @@ -109,8 +102,6 @@ private: float _eyeGazeRightPitch; float _eyeGazeRightYaw; - QVector _blendshapeCoefficients; - int _leftBlinkIndex; int _rightBlinkIndex; int _leftEyeOpenIndex; @@ -132,10 +123,6 @@ private: float _longTermAverageEyePitch; float _longTermAverageEyeYaw; bool _longTermAverageInitialized; - - // degrees - float _estimatedEyePitch; - float _estimatedEyeYaw; }; #endif /* defined(__interface__Faceshift__) */ diff --git a/interface/src/devices/Visage.cpp b/interface/src/devices/Visage.cpp index b96ef1ee72..0cb534f8c3 100644 --- a/interface/src/devices/Visage.cpp +++ b/interface/src/devices/Visage.cpp @@ -34,9 +34,7 @@ const glm::vec3 DEFAULT_HEAD_ORIGIN(0.0f, 0.0f, 0.7f); Visage::Visage() : _enabled(false), _active(false), - _headOrigin(DEFAULT_HEAD_ORIGIN), - _estimatedEyePitch(0.0f), - _estimatedEyeYaw(0.0f) { + _headOrigin(DEFAULT_HEAD_ORIGIN) { #ifdef HAVE_VISAGE QByteArray licensePath = Application::resourcesPath().toLatin1() + "visage/license.vlc"; diff --git a/interface/src/devices/Visage.h b/interface/src/devices/Visage.h index 6e98abbb61..0da87fb332 100644 --- a/interface/src/devices/Visage.h +++ b/interface/src/devices/Visage.h @@ -16,13 +16,15 @@ #include #include +#include "FaceTracker.h" + namespace VisageSDK { class VisageTracker2; struct FaceData; } /// Handles input from the Visage webcam feature tracking software. -class Visage : public QObject { +class Visage : public FaceTracker { Q_OBJECT public: @@ -34,14 +36,6 @@ public: bool isActive() const { return _active; } - const glm::quat& getHeadRotation() const { return _headRotation; } - const glm::vec3& getHeadTranslation() const { return _headTranslation; } - - float getEstimatedEyePitch() const { return _estimatedEyePitch; } - float getEstimatedEyeYaw() const { return _estimatedEyeYaw; } - - const QVector& getBlendshapeCoefficients() const { return _blendshapeCoefficients; } - void update(); void reset(); @@ -61,15 +55,8 @@ private: bool _enabled; bool _active; - glm::quat _headRotation; - glm::vec3 _headTranslation; - + glm::vec3 _headOrigin; - - float _estimatedEyePitch; - float _estimatedEyeYaw; - - QVector _blendshapeCoefficients; }; #endif /* defined(__interface__Visage__) */ From 34aefe1b496089861904bc1d838febe9d99f4e0f Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 8 Apr 2014 18:33:08 -0700 Subject: [PATCH 230/595] fix glitchy oculus when looking directly behind --- interface/src/avatar/MyAvatar.cpp | 67 +++++++++++++++++++------ interface/src/avatar/MyAvatar.h | 2 +- interface/src/devices/OculusManager.cpp | 10 ---- interface/src/devices/OculusManager.h | 1 - 4 files changed, 52 insertions(+), 28 deletions(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 05636166e2..8b02605a62 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -62,7 +62,8 @@ MyAvatar::MyAvatar() : _moveTargetStepCounter(0), _lookAtTargetAvatar(), _shouldRender(true), - _billboardValid(false) + _billboardValid(false), + _oculusYawOffset(0.f) { for (int i = 0; i < MAX_DRIVE_KEYS; i++) { _driveKeys[i] = 0.0f; @@ -85,6 +86,7 @@ void MyAvatar::reset() { _skeletonModel.reset(); getHead()->reset(); getHand()->reset(); + _oculusYawOffset = 0.f; setVelocity(glm::vec3(0.f)); setThrust(glm::vec3(0.f)); @@ -121,16 +123,6 @@ void MyAvatar::update(float deltaTime) { //_headMouseY = glm::clamp(_headMouseY, 0, _glWidget->height()); } - if (OculusManager::isConnected()) { - float yaw, pitch, roll; // these angles will be in radians - OculusManager::getEulerAngles(yaw, pitch, roll); - - // but these euler angles are stored in degrees - head->setBaseYaw(yaw * DEGREES_PER_RADIAN); - head->setBasePitch(pitch * DEGREES_PER_RADIAN); - head->setBaseRoll(roll * DEGREES_PER_RADIAN); - } - // Get audio loudness data from audio input device Audio* audio = Application::getInstance()->getAudio(); head->setAudioLoudness(audio->getLastInputLoudness()); @@ -222,6 +214,54 @@ void MyAvatar::simulate(float deltaTime) { applyDamping(deltaTime, _velocity, linearDamping, SQUARED_DAMPING_STRENGTH); } + if (OculusManager::isConnected()) { + // these angles will be in radians + float yaw, pitch, roll; + OculusManager::getEulerAngles(yaw, pitch, roll); + // ... so they need to be converted to degrees before we do math... + + // The neck is limited in how much it can yaw, so we check its relative + // yaw from the body and yaw the body if necessary. + yaw *= DEGREES_PER_RADIAN; + float bodyToHeadYaw = yaw - _oculusYawOffset; + const float MAX_NECK_YAW = 85.f; // degrees + if ((fabs(bodyToHeadYaw) > 2.f * MAX_NECK_YAW) && (yaw * _oculusYawOffset < 0.f)) { + // We've wrapped around the range for yaw so adjust + // the measured yaw to be relative to _oculusYawOffset. + if (yaw > 0.f) { + yaw -= 360.f; + } else { + yaw += 360.f; + } + bodyToHeadYaw = yaw - _oculusYawOffset; + } + + float delta = fabs(bodyToHeadYaw) - MAX_NECK_YAW; + if (delta > 0.f) { + yaw = MAX_NECK_YAW; + if (bodyToHeadYaw < 0.f) { + delta *= -1.f; + bodyToHeadYaw = -MAX_NECK_YAW; + } else { + bodyToHeadYaw = MAX_NECK_YAW; + } + // constrain _oculusYawOffset to be within range [-180,180] + _oculusYawOffset = fmod((_oculusYawOffset + delta) + 180.f, 360.f) - 180.f; + + // We must adjust the body orientation using a delta rotation (rather than + // doing yaw math) because the body's yaw ranges are not the same + // as what the Oculus API provides. + glm::vec3 UP_AXIS = glm::vec3(0.f, 1.f, 0.f); + glm::quat bodyCorrection = glm::angleAxis(glm::radians(delta), UP_AXIS); + orientation = orientation * bodyCorrection; + } + Head* head = getHead(); + head->setBaseYaw(bodyToHeadYaw); + + head->setBasePitch(pitch * DEGREES_PER_RADIAN); + head->setBaseRoll(roll * DEGREES_PER_RADIAN); + } + // update the euler angles setOrientation(orientation); @@ -575,11 +615,6 @@ void MyAvatar::clearLookAtTargetAvatar() { _lookAtTargetAvatar.clear(); } -float MyAvatar::getAbsoluteHeadYaw() const { - const Head* head = static_cast(_headData); - return glm::yaw(head->getOrientation()); -} - glm::vec3 MyAvatar::getUprightHeadPosition() const { return _position + getWorldAlignedOrientation() * glm::vec3(0.0f, getPelvisToHeadLength(), 0.0f); } diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index 2125b126b3..90b0129037 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -125,8 +125,8 @@ private: QWeakPointer _lookAtTargetAvatar; glm::vec3 _targetAvatarPosition; bool _shouldRender; - bool _billboardValid; + float _oculusYawOffset; // private methods void updateThrust(float deltaTime); diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index c5377ce428..5619b4b58d 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -27,7 +27,6 @@ int OculusManager::_scaleLocation; int OculusManager::_scaleInLocation; int OculusManager::_hmdWarpParamLocation; bool OculusManager::_isConnected = false; -float OculusManager::_yawOffset = 0.0f; // radians #ifdef HAVE_LIBOVR using namespace OVR; @@ -187,18 +186,9 @@ void OculusManager::reset() { #endif } -void OculusManager::updateYawOffset() { -#ifdef HAVE_LIBOVR - float yaw, pitch, roll; - _sensorFusion->GetOrientation().GetEulerAngles(&yaw, &pitch, &roll); - _yawOffset = yaw; -#endif -} - void OculusManager::getEulerAngles(float& yaw, float& pitch, float& roll) { #ifdef HAVE_LIBOVR _sensorFusion->GetOrientation().GetEulerAngles(&yaw, &pitch, &roll); - yaw = yaw - _yawOffset; #endif } diff --git a/interface/src/devices/OculusManager.h b/interface/src/devices/OculusManager.h index b3cd400ac8..19bbec31dd 100644 --- a/interface/src/devices/OculusManager.h +++ b/interface/src/devices/OculusManager.h @@ -48,7 +48,6 @@ private: static int _scaleInLocation; static int _hmdWarpParamLocation; static bool _isConnected; - static float _yawOffset; #ifdef HAVE_LIBOVR static OVR::Ptr _deviceManager; From 2eef95f67e922865d4d55a2f4b952e55acdfe419 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 8 Apr 2014 18:44:34 -0700 Subject: [PATCH 231/595] remove getAbsoluteHeadYaw() from the header --- interface/src/avatar/MyAvatar.h | 1 - 1 file changed, 1 deletion(-) diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index 90b0129037..60874cc886 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -54,7 +54,6 @@ public: float getLeanScale() const { return _leanScale; } float getElapsedTimeStopped() const { return _elapsedTimeStopped; } float getElapsedTimeMoving() const { return _elapsedTimeMoving; } - float getAbsoluteHeadYaw() const; // degrees const glm::vec3& getMouseRayOrigin() const { return _mouseRayOrigin; } const glm::vec3& getMouseRayDirection() const { return _mouseRayDirection; } glm::vec3 getGravity() const { return _gravity; } From b8232b5dfdc70db8cc811dce1815bb5e1ac2c60b Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 9 Apr 2014 08:11:15 -0700 Subject: [PATCH 232/595] AvatarData now stores sessionUUID --- interface/src/Application.cpp | 5 ++++- libraries/avatars/src/AvatarData.cpp | 1 + libraries/avatars/src/AvatarData.h | 8 +++++--- libraries/avatars/src/AvatarHashMap.cpp | 2 +- 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 15d45b614d..f8aaf45f7c 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1205,7 +1205,10 @@ void Application::timer() { // ask the node list to check in with the domain server NodeList::getInstance()->sendDomainServerCheckIn(); - + // as soon as we have a valid sessionUUID, store it in the avatar for reference + if (_myAvatar->getSessionUUID().isNull()) { + _myAvatar->setSessionUUID(NodeList::getInstance()->getSessionUUID()); + } } void Application::idle() { diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index 930e3f7350..7bdd8fb752 100644 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -32,6 +32,7 @@ using namespace std; QNetworkAccessManager* AvatarData::networkAccessManager = NULL; AvatarData::AvatarData() : + _sessionUUID(), _handPosition(0,0,0), _bodyYaw(-90.f), _bodyPitch(0.0f), diff --git a/libraries/avatars/src/AvatarData.h b/libraries/avatars/src/AvatarData.h index 2637b5a0c3..0f4df39f87 100755 --- a/libraries/avatars/src/AvatarData.h +++ b/libraries/avatars/src/AvatarData.h @@ -94,12 +94,14 @@ class AvatarData : public QObject { Q_PROPERTY(QString faceModelURL READ getFaceModelURLFromScript WRITE setFaceModelURLFromScript) Q_PROPERTY(QString skeletonModelURL READ getSkeletonModelURLFromScript WRITE setSkeletonModelURLFromScript) Q_PROPERTY(QString billboardURL READ getBillboardURL WRITE setBillboardFromURL) + + Q_PROPERTY(QUuid sessionUUID READ getSessionUUID); public: AvatarData(); virtual ~AvatarData(); - const QUuid& getSessionID() { return _sessionID; } - void setSessionID(const QUuid& id) { _sessionID = id; } + const QUuid& getSessionUUID() { return _sessionUUID; } + void setSessionUUID(const QUuid& id) { _sessionUUID = id; } const glm::vec3& getPosition() const { return _position; } void setPosition(const glm::vec3 position) { _position = position; } @@ -222,7 +224,7 @@ public slots: void sendBillboardPacket(); void setBillboardFromNetworkReply(); protected: - QUuid _sessionID; + QUuid _sessionUUID; glm::vec3 _position; glm::vec3 _handPosition; diff --git a/libraries/avatars/src/AvatarHashMap.cpp b/libraries/avatars/src/AvatarHashMap.cpp index 5a56e3d5dc..3dd5c9991f 100644 --- a/libraries/avatars/src/AvatarHashMap.cpp +++ b/libraries/avatars/src/AvatarHashMap.cpp @@ -15,7 +15,7 @@ AvatarHashMap::AvatarHashMap() : void AvatarHashMap::insert(const QUuid& id, AvatarSharedPointer avatar) { _avatarHash.insert(id, avatar); - avatar->setSessionID(id); + avatar->setSessionUUID(id); } AvatarHash::iterator AvatarHashMap::erase(const AvatarHash::iterator& iterator) { From 2f97dd2574e617454046de514ad1aaaca0281fec Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 9 Apr 2014 08:22:35 -0700 Subject: [PATCH 233/595] sessionID --> sessionUUID for consistency --- interface/src/avatar/AvatarManager.cpp | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/interface/src/avatar/AvatarManager.cpp b/interface/src/avatar/AvatarManager.cpp index 5b98d933ff..fbbaad4e84 100644 --- a/interface/src/avatar/AvatarManager.cpp +++ b/interface/src/avatar/AvatarManager.cpp @@ -123,8 +123,8 @@ void AvatarManager::renderAvatarFades(const glm::vec3& cameraPosition, Avatar::R } } -AvatarSharedPointer AvatarManager::matchingOrNewAvatar(const QUuid& sessionID, const QWeakPointer& mixerWeakPointer) { - AvatarSharedPointer matchingAvatar = _avatarHash.value(sessionID); +AvatarSharedPointer AvatarManager::matchingOrNewAvatar(const QUuid& sessionUUID, const QWeakPointer& mixerWeakPointer) { + AvatarSharedPointer matchingAvatar = _avatarHash.value(sessionUUID); if (!matchingAvatar) { // construct a new Avatar for this node @@ -133,9 +133,9 @@ AvatarSharedPointer AvatarManager::matchingOrNewAvatar(const QUuid& sessionID, c // insert the new avatar into our hash matchingAvatar = AvatarSharedPointer(avatar); - _avatarHash.insert(sessionID, matchingAvatar); + _avatarHash.insert(sessionUUID, matchingAvatar); - qDebug() << "Adding avatar with sessionID " << sessionID << "to AvatarManager hash."; + qDebug() << "Adding avatar with sessionUUID " << sessionUUID << "to AvatarManager hash."; } return matchingAvatar; @@ -166,10 +166,10 @@ void AvatarManager::processAvatarDataPacket(const QByteArray &datagram, const QW // enumerate over all of the avatars in this packet // only add them if mixerWeakPointer points to something (meaning that mixer is still around) while (bytesRead < datagram.size() && mixerWeakPointer.data()) { - QUuid sessionID = QUuid::fromRfc4122(datagram.mid(bytesRead, NUM_BYTES_RFC4122_UUID)); + QUuid sessionUUID = QUuid::fromRfc4122(datagram.mid(bytesRead, NUM_BYTES_RFC4122_UUID)); bytesRead += NUM_BYTES_RFC4122_UUID; - AvatarSharedPointer matchingAvatarData = matchingOrNewAvatar(sessionID, mixerWeakPointer); + AvatarSharedPointer matchingAvatarData = matchingOrNewAvatar(sessionUUID, mixerWeakPointer); // have the matching (or new) avatar parse the data from the packet bytesRead += matchingAvatarData->parseDataAtOffset(datagram, bytesRead); @@ -188,16 +188,16 @@ void AvatarManager::processAvatarIdentityPacket(const QByteArray &packet, const QDataStream identityStream(packet); identityStream.skipRawData(numBytesForPacketHeader(packet)); - QUuid sessionID; + QUuid sessionUUID; while (!identityStream.atEnd()) { QUrl faceMeshURL, skeletonURL; QString displayName; - identityStream >> sessionID >> faceMeshURL >> skeletonURL >> displayName; + identityStream >> sessionUUID >> faceMeshURL >> skeletonURL >> displayName; // mesh URL for a UUID, find avatar in our list - AvatarSharedPointer matchingAvatar = matchingOrNewAvatar(sessionID, mixerWeakPointer); + AvatarSharedPointer matchingAvatar = matchingOrNewAvatar(sessionUUID, mixerWeakPointer); if (matchingAvatar) { Avatar* avatar = static_cast(matchingAvatar.data()); @@ -218,9 +218,9 @@ void AvatarManager::processAvatarIdentityPacket(const QByteArray &packet, const void AvatarManager::processAvatarBillboardPacket(const QByteArray& packet, const QWeakPointer& mixerWeakPointer) { int headerSize = numBytesForPacketHeader(packet); - QUuid sessionID = QUuid::fromRfc4122(QByteArray::fromRawData(packet.constData() + headerSize, NUM_BYTES_RFC4122_UUID)); + QUuid sessionUUID = QUuid::fromRfc4122(QByteArray::fromRawData(packet.constData() + headerSize, NUM_BYTES_RFC4122_UUID)); - AvatarSharedPointer matchingAvatar = matchingOrNewAvatar(sessionID, mixerWeakPointer); + AvatarSharedPointer matchingAvatar = matchingOrNewAvatar(sessionUUID, mixerWeakPointer); if (matchingAvatar) { Avatar* avatar = static_cast(matchingAvatar.data()); QByteArray billboard = packet.mid(headerSize + NUM_BYTES_RFC4122_UUID); @@ -232,10 +232,10 @@ void AvatarManager::processAvatarBillboardPacket(const QByteArray& packet, const void AvatarManager::processKillAvatar(const QByteArray& datagram) { // read the node id - QUuid sessionID = QUuid::fromRfc4122(datagram.mid(numBytesForPacketHeader(datagram), NUM_BYTES_RFC4122_UUID)); + QUuid sessionUUID = QUuid::fromRfc4122(datagram.mid(numBytesForPacketHeader(datagram), NUM_BYTES_RFC4122_UUID)); // remove the avatar with that UUID from our hash, if it exists - AvatarHash::iterator matchedAvatar = _avatarHash.find(sessionID); + AvatarHash::iterator matchedAvatar = _avatarHash.find(sessionUUID); if (matchedAvatar != _avatarHash.end()) { erase(matchedAvatar); } From 995084556604a7a3838ad3b5ffce16a5eae97c4d Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 09:19:29 -0700 Subject: [PATCH 234/595] more apache licensing tweaks to JS files --- examples/clap.js | 8 ++++++++ examples/clipboardExample.js | 2 +- examples/count.js | 2 +- examples/drumStick.js | 8 ++++++++ examples/findParticleExample.js | 5 ++++- examples/flockingBirds.js | 8 ++++++-- examples/fountain.js | 10 +++++++++- examples/gameoflife.js | 14 +++++++++++--- examples/globalCollisionsExample.js | 2 +- examples/gun.js | 3 +-- examples/hideAvatarExample.js | 2 +- examples/hydraMove.js | 2 +- examples/includeExample.js | 2 +- examples/inspect.js | 2 +- examples/localVoxelsExample.js | 9 +++++++++ examples/lookAtExample.js | 2 +- examples/lookWithMouse.js | 2 +- examples/lookWithTouch.js | 2 +- examples/menuExample.js | 2 +- examples/movingVoxel.js | 8 ++++++++ examples/multitouchExample.js | 2 +- examples/overlaysExample.js | 2 +- examples/paintGun.js | 2 +- examples/particleBird.js | 2 ++ examples/particleModelExample.js | 2 +- examples/playSound.js | 4 ++++ examples/rayPickExample.js | 2 +- examples/ribbon.js | 2 +- examples/rideAlongWithAParticleExample.js | 2 +- examples/seeingVoxelsExample.js | 4 +--- examples/selectAudioDevice.js | 2 +- examples/settingsExample.js | 2 +- examples/spaceInvadersExample.js | 2 +- examples/timer.js | 10 ++++++++++ examples/toyball.js | 2 +- examples/voxelDrumming.js | 2 +- 36 files changed, 104 insertions(+), 35 deletions(-) diff --git a/examples/clap.js b/examples/clap.js index ef8b61f05a..a0efcfab7b 100644 --- a/examples/clap.js +++ b/examples/clap.js @@ -1,6 +1,14 @@ // +// cameraExample.js +// examples +// +// Copyright 2014 High Fidelity, Inc. +// // This sample script watches your hydra hands and makes clapping sound when they come close together fast // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// function length(v) { return Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z); diff --git a/examples/clipboardExample.js b/examples/clipboardExample.js index e9f581f581..d36b077451 100644 --- a/examples/clipboardExample.js +++ b/examples/clipboardExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 1/28/14. -// Copyright 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 HighFidelity, Inc. // // This is an example script that demonstrates use of the Clipboard class // diff --git a/examples/count.js b/examples/count.js index 1a59d6af36..2a8699ac55 100644 --- a/examples/count.js +++ b/examples/count.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 12/31/13. -// Copyright 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // // This is an example script that runs in a loop and displays a counter to the log // diff --git a/examples/drumStick.js b/examples/drumStick.js index 9b0a8ccbca..e9ac54f814 100644 --- a/examples/drumStick.js +++ b/examples/drumStick.js @@ -1,6 +1,14 @@ // +// drumStick.js +// examples +// +// Copyright 2014 High Fidelity, Inc. +// // This example musical instrument script plays 'air drums' when you move your hands downward // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// function length(v) { return Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z); diff --git a/examples/findParticleExample.js b/examples/findParticleExample.js index 0b07471273..b37890d766 100644 --- a/examples/findParticleExample.js +++ b/examples/findParticleExample.js @@ -3,10 +3,13 @@ // examples // // Created by Brad Hefta-Gaub on 1/24/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 HighFidelity, Inc. // // This is an example script that demonstrates "finding" particles // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// var iteration = 0; diff --git a/examples/flockingBirds.js b/examples/flockingBirds.js index a45bcc9f97..f85b4b38c4 100644 --- a/examples/flockingBirds.js +++ b/examples/flockingBirds.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 3/4/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 HighFidelity, Inc. All rights reserved. // // This is an example script that generates particles that act like flocking birds // @@ -13,12 +13,16 @@ // go back to gliding // birds don't like to be below a certain altitude // if they are below that altitude they will keep thrusting up, until they get ove - +// // flocking // try to align your velocity with velocity of other birds // try to fly toward center of flock // but dont get too close // +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// var birdsInFlock = 40; diff --git a/examples/fountain.js b/examples/fountain.js index 8816dab09a..ab1b82cb76 100644 --- a/examples/fountain.js +++ b/examples/fountain.js @@ -1,4 +1,12 @@ - +// +// fountain.js +// examples +// +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// function vLength(v) { return Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z); diff --git a/examples/gameoflife.js b/examples/gameoflife.js index c0122c604a..3fcbfa8138 100644 --- a/examples/gameoflife.js +++ b/examples/gameoflife.js @@ -1,6 +1,14 @@ -// Add your JavaScript for assignment below this line - -// The following is an example of Conway's Game of Life (http://en.wikipedia.org/wiki/Conway's_Game_of_Life) +// +// gameoflife.js +// examples +// +// Copyright 2014 High Fidelity, Inc. +// +// The following is an example of Conway's Game of Life (http://en.wikipedia.org/wiki/Conway's_Game_of_Life) +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// var NUMBER_OF_CELLS_EACH_DIMENSION = 64; var NUMBER_OF_CELLS = NUMBER_OF_CELLS_EACH_DIMENSION * NUMBER_OF_CELLS_EACH_DIMENSION; diff --git a/examples/globalCollisionsExample.js b/examples/globalCollisionsExample.js index b9d1dceefe..a9667396a4 100644 --- a/examples/globalCollisionsExample.js +++ b/examples/globalCollisionsExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 1/29/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 HighFidelity, Inc. // // This is an example script that demonstrates use of the Controller class // diff --git a/examples/gun.js b/examples/gun.js index 85d0f9c1e5..95d3905cc7 100644 --- a/examples/gun.js +++ b/examples/gun.js @@ -4,7 +4,7 @@ // // Created by Brad Hefta-Gaub on 12/31/13. // Modified by Philip on 3/3/14 -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 HighFidelity, Inc. // // This is an example script that turns the hydra controllers and mouse into a particle gun. // It reads the controller, watches for trigger pulls, and launches particles. @@ -14,7 +14,6 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // - function getRandomFloat(min, max) { return Math.random() * (max - min) + min; } diff --git a/examples/hideAvatarExample.js b/examples/hideAvatarExample.js index d9e4b350f4..cea503b205 100644 --- a/examples/hideAvatarExample.js +++ b/examples/hideAvatarExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 1/28/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 HighFidelity, Inc. // // This is an example script that demonstrates how to enable or disable local rendering of your own avatar // diff --git a/examples/hydraMove.js b/examples/hydraMove.js index e2dd608b4a..6df6784ea1 100644 --- a/examples/hydraMove.js +++ b/examples/hydraMove.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 2/10/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 HighFidelity, Inc. // // This is an example script that demonstrates use of the Controller and MyAvatar classes to implement // avatar flying through the hydra/controller joysticks diff --git a/examples/includeExample.js b/examples/includeExample.js index e82a95fc63..d3ed398c94 100644 --- a/examples/includeExample.js +++ b/examples/includeExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 3/24/14 -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 HighFidelity, Inc. // // This is an example script that demonstrates use of the Script.include() feature // diff --git a/examples/inspect.js b/examples/inspect.js index 5402a6a830..39b74c9117 100644 --- a/examples/inspect.js +++ b/examples/inspect.js @@ -3,7 +3,7 @@ // examples // // Created by Clément Brisset on March 20, 2014 -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 HighFidelity, Inc. // // Allows you to inspect non moving objects (Voxels or Avatars) using Atl, Control (Command on Mac) and Shift // diff --git a/examples/localVoxelsExample.js b/examples/localVoxelsExample.js index 7d9007f590..d64138b214 100644 --- a/examples/localVoxelsExample.js +++ b/examples/localVoxelsExample.js @@ -1,3 +1,12 @@ +// +// localVoxelsExample.js +// examples +// +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// var TREE_SCALE = 16384; var tree = LocalVoxels("tree"); diff --git a/examples/lookAtExample.js b/examples/lookAtExample.js index 6e208ddbdd..58dcfc9184 100644 --- a/examples/lookAtExample.js +++ b/examples/lookAtExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 2/6/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 HighFidelity, Inc. // // This is an example script that demonstrates use of the Camera class's lookAt(), keepLookingAt(), and stopLookingAt() // features. diff --git a/examples/lookWithMouse.js b/examples/lookWithMouse.js index 4293654ae5..b269da3c7a 100644 --- a/examples/lookWithMouse.js +++ b/examples/lookWithMouse.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 1/28/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright (c) 2014 HighFidelity, Inc. // // This is an example script that demonstrates use of the Controller class // diff --git a/examples/lookWithTouch.js b/examples/lookWithTouch.js index 0278d2b7b2..29920a5b4e 100644 --- a/examples/lookWithTouch.js +++ b/examples/lookWithTouch.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 1/28/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright (c) 2014 HighFidelity, Inc. // // This is an example script that demonstrates use of the Controller class // diff --git a/examples/menuExample.js b/examples/menuExample.js index d448c32bf8..b4f956218a 100644 --- a/examples/menuExample.js +++ b/examples/menuExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 2/24/14 -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright (c) 2013 HighFidelity, Inc. // // This is an example script that demonstrates use of the Menu object // diff --git a/examples/movingVoxel.js b/examples/movingVoxel.js index 0ddce48334..c55957cd04 100644 --- a/examples/movingVoxel.js +++ b/examples/movingVoxel.js @@ -1,6 +1,14 @@ // +// movingVoxel.js +// examples +// +// Copyright 2014 High Fidelity, Inc. +// // This sample script creates a voxel moving back and forth in a line // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// var position = { x: 0, y: 0, z: 0 }; var oldPosition = { x: 0, y: 0, z:0 }; diff --git a/examples/multitouchExample.js b/examples/multitouchExample.js index b76902f57a..55d1d834bd 100644 --- a/examples/multitouchExample.js +++ b/examples/multitouchExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 2/9/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 HighFidelity, Inc. // // This is an example script that demonstrates use of the Controller class's multi-touch features // diff --git a/examples/overlaysExample.js b/examples/overlaysExample.js index ec54438692..420500faf1 100644 --- a/examples/overlaysExample.js +++ b/examples/overlaysExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 2/14/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 HighFidelity, Inc. // // This is an example script that demonstrates use of the Overlays class // diff --git a/examples/paintGun.js b/examples/paintGun.js index fa2d4f1e1f..7d2ec54351 100644 --- a/examples/paintGun.js +++ b/examples/paintGun.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 12/31/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 HighFidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html diff --git a/examples/particleBird.js b/examples/particleBird.js index 59ada1950e..5241b3550b 100644 --- a/examples/particleBird.js +++ b/examples/particleBird.js @@ -2,6 +2,8 @@ // particleBird.js // examples // +// Copyright 2014 High Fidelity, Inc. +// // This sample script moves a voxel around like a bird and sometimes makes tweeting noises // // Distributed under the Apache License, Version 2.0. diff --git a/examples/particleModelExample.js b/examples/particleModelExample.js index 96b16c503d..b489e704c9 100644 --- a/examples/particleModelExample.js +++ b/examples/particleModelExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 1/28/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates creating and editing a particle // diff --git a/examples/playSound.js b/examples/playSound.js index 7715604de2..fb589bc9e3 100644 --- a/examples/playSound.js +++ b/examples/playSound.js @@ -1,4 +1,8 @@ // +// playSound.js +// examples +// +// Copyright 2014 High Fidelity, Inc. // This sample script loads a sound file and plays it at the 'fingertip' of the // // Distributed under the Apache License, Version 2.0. diff --git a/examples/rayPickExample.js b/examples/rayPickExample.js index 13ab285af5..c09a7b1e57 100644 --- a/examples/rayPickExample.js +++ b/examples/rayPickExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 2/6/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates use of the Camera class // diff --git a/examples/ribbon.js b/examples/ribbon.js index 5e48ee3193..9f0cc02e52 100644 --- a/examples/ribbon.js +++ b/examples/ribbon.js @@ -3,7 +3,7 @@ // examples // // Created by Andrzej Kapolka on 2/24/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. All rights reserved. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html diff --git a/examples/rideAlongWithAParticleExample.js b/examples/rideAlongWithAParticleExample.js index a6decbc2c2..552f6fb7fe 100644 --- a/examples/rideAlongWithAParticleExample.js +++ b/examples/rideAlongWithAParticleExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 1/24/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates "finding" particles // diff --git a/examples/seeingVoxelsExample.js b/examples/seeingVoxelsExample.js index e0f991ea40..35e2f95dd7 100644 --- a/examples/seeingVoxelsExample.js +++ b/examples/seeingVoxelsExample.js @@ -3,9 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 2/26/14 -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. -// -// This is an example script +// Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html diff --git a/examples/selectAudioDevice.js b/examples/selectAudioDevice.js index 668e467254..23606f774c 100644 --- a/examples/selectAudioDevice.js +++ b/examples/selectAudioDevice.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 3/22/14 -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // // This is an example script that demonstrates use of the Menu object // diff --git a/examples/settingsExample.js b/examples/settingsExample.js index 816fc956a3..bef347ff07 100644 --- a/examples/settingsExample.js +++ b/examples/settingsExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 3/22/14 -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // // This is an example script that demonstrates use of the Menu object // diff --git a/examples/spaceInvadersExample.js b/examples/spaceInvadersExample.js index be4fcf445f..5b25fa1236 100644 --- a/examples/spaceInvadersExample.js +++ b/examples/spaceInvadersExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 1/30/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates a simple space invaders style of game // diff --git a/examples/timer.js b/examples/timer.js index c7ad0290ab..b3af1d902c 100644 --- a/examples/timer.js +++ b/examples/timer.js @@ -1,3 +1,13 @@ +// +// timer.js +// examples +// +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + var one_timer = Script.setTimeout(function() { print("One time timer fired!"); }, 10000); var multiple_timer = Script.setInterval(function() { print("Repeating timer fired!"); }, 1000); diff --git a/examples/toyball.js b/examples/toyball.js index 52646c94b4..de68e97357 100644 --- a/examples/toyball.js +++ b/examples/toyball.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 1/20/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that turns the hydra controllers into a toy ball catch and throw game. // It reads the controller, watches for button presses and trigger pulls, and launches particles. diff --git a/examples/voxelDrumming.js b/examples/voxelDrumming.js index f064d6736e..7f3495dea7 100644 --- a/examples/voxelDrumming.js +++ b/examples/voxelDrumming.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 2/14/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates use of the Overlays, Controller, and Audio classes // From 4a398494b1965b5d7f88a271a7ed13d74a73f1f6 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 09:21:54 -0700 Subject: [PATCH 235/595] ensure spacing in company name for JS licenses --- examples/clipboardExample.js | 2 +- examples/findParticleExample.js | 2 +- examples/flockingBirds.js | 2 +- examples/globalCollisionsExample.js | 2 +- examples/gun.js | 2 +- examples/hideAvatarExample.js | 2 +- examples/hydraMove.js | 2 +- examples/includeExample.js | 2 +- examples/inspect.js | 2 +- examples/lookAtExample.js | 2 +- examples/lookWithMouse.js | 2 +- examples/lookWithTouch.js | 2 +- examples/menuExample.js | 2 +- examples/multitouchExample.js | 2 +- examples/overlaysExample.js | 2 +- 15 files changed, 15 insertions(+), 15 deletions(-) diff --git a/examples/clipboardExample.js b/examples/clipboardExample.js index d36b077451..e6db44054f 100644 --- a/examples/clipboardExample.js +++ b/examples/clipboardExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 1/28/14. -// Copyright 2014 HighFidelity, Inc. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates use of the Clipboard class // diff --git a/examples/findParticleExample.js b/examples/findParticleExample.js index b37890d766..635e30f344 100644 --- a/examples/findParticleExample.js +++ b/examples/findParticleExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 1/24/14. -// Copyright 2014 HighFidelity, Inc. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates "finding" particles // diff --git a/examples/flockingBirds.js b/examples/flockingBirds.js index f85b4b38c4..17c60d88aa 100644 --- a/examples/flockingBirds.js +++ b/examples/flockingBirds.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 3/4/14. -// Copyright 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that generates particles that act like flocking birds // diff --git a/examples/globalCollisionsExample.js b/examples/globalCollisionsExample.js index a9667396a4..11d90cd15b 100644 --- a/examples/globalCollisionsExample.js +++ b/examples/globalCollisionsExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 1/29/14. -// Copyright 2014 HighFidelity, Inc. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates use of the Controller class // diff --git a/examples/gun.js b/examples/gun.js index 95d3905cc7..8cf6c9f654 100644 --- a/examples/gun.js +++ b/examples/gun.js @@ -4,7 +4,7 @@ // // Created by Brad Hefta-Gaub on 12/31/13. // Modified by Philip on 3/3/14 -// Copyright 2013 HighFidelity, Inc. +// Copyright 2013 High Fidelity, Inc. // // This is an example script that turns the hydra controllers and mouse into a particle gun. // It reads the controller, watches for trigger pulls, and launches particles. diff --git a/examples/hideAvatarExample.js b/examples/hideAvatarExample.js index cea503b205..66d85becf1 100644 --- a/examples/hideAvatarExample.js +++ b/examples/hideAvatarExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 1/28/14. -// Copyright 2014 HighFidelity, Inc. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates how to enable or disable local rendering of your own avatar // diff --git a/examples/hydraMove.js b/examples/hydraMove.js index 6df6784ea1..b73f990446 100644 --- a/examples/hydraMove.js +++ b/examples/hydraMove.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 2/10/14. -// Copyright 2014 HighFidelity, Inc. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates use of the Controller and MyAvatar classes to implement // avatar flying through the hydra/controller joysticks diff --git a/examples/includeExample.js b/examples/includeExample.js index d3ed398c94..50a1234772 100644 --- a/examples/includeExample.js +++ b/examples/includeExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 3/24/14 -// Copyright 2013 HighFidelity, Inc. +// Copyright 2013 High Fidelity, Inc. // // This is an example script that demonstrates use of the Script.include() feature // diff --git a/examples/inspect.js b/examples/inspect.js index 39b74c9117..28db1e7735 100644 --- a/examples/inspect.js +++ b/examples/inspect.js @@ -3,7 +3,7 @@ // examples // // Created by Clément Brisset on March 20, 2014 -// Copyright 2014 HighFidelity, Inc. +// Copyright 2014 High Fidelity, Inc. // // Allows you to inspect non moving objects (Voxels or Avatars) using Atl, Control (Command on Mac) and Shift // diff --git a/examples/lookAtExample.js b/examples/lookAtExample.js index 58dcfc9184..1cf8aabb96 100644 --- a/examples/lookAtExample.js +++ b/examples/lookAtExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 2/6/14. -// Copyright 2014 HighFidelity, Inc. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates use of the Camera class's lookAt(), keepLookingAt(), and stopLookingAt() // features. diff --git a/examples/lookWithMouse.js b/examples/lookWithMouse.js index b269da3c7a..9110218026 100644 --- a/examples/lookWithMouse.js +++ b/examples/lookWithMouse.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 1/28/14. -// Copyright (c) 2014 HighFidelity, Inc. +// Copyright (c) 2014 High Fidelity, Inc. // // This is an example script that demonstrates use of the Controller class // diff --git a/examples/lookWithTouch.js b/examples/lookWithTouch.js index 29920a5b4e..5f5e2ee41c 100644 --- a/examples/lookWithTouch.js +++ b/examples/lookWithTouch.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 1/28/14. -// Copyright (c) 2014 HighFidelity, Inc. +// Copyright (c) 2014 High Fidelity, Inc. // // This is an example script that demonstrates use of the Controller class // diff --git a/examples/menuExample.js b/examples/menuExample.js index b4f956218a..ed6f29d53a 100644 --- a/examples/menuExample.js +++ b/examples/menuExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 2/24/14 -// Copyright (c) 2013 HighFidelity, Inc. +// Copyright (c) 2013 High Fidelity, Inc. // // This is an example script that demonstrates use of the Menu object // diff --git a/examples/multitouchExample.js b/examples/multitouchExample.js index 55d1d834bd..9d27b7ae2a 100644 --- a/examples/multitouchExample.js +++ b/examples/multitouchExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 2/9/14. -// Copyright 2014 HighFidelity, Inc. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates use of the Controller class's multi-touch features // diff --git a/examples/overlaysExample.js b/examples/overlaysExample.js index 420500faf1..d0b3870803 100644 --- a/examples/overlaysExample.js +++ b/examples/overlaysExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 2/14/14. -// Copyright 2014 HighFidelity, Inc. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates use of the Overlays class // From 067ea5b5b6010510ac912c94ed0cc89fa0b51105 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 09:22:19 -0700 Subject: [PATCH 236/595] add a missing space in company name in paintGun --- examples/paintGun.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/paintGun.js b/examples/paintGun.js index 7d2ec54351..b5bb2a49da 100644 --- a/examples/paintGun.js +++ b/examples/paintGun.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 12/31/13. -// Copyright 2013 HighFidelity, Inc. +// Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html From fbd2066b0cd7345ff067b1bd923fde9a2eeab8d7 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 09:25:34 -0700 Subject: [PATCH 237/595] more apache licensing for cmake files --- cmake/macros/AutoMTC.cmake | 10 ++++++++++ cmake/macros/IncludeGLM.cmake | 9 +++++++++ cmake/macros/LinkHifiLibrary.cmake | 9 +++++++++ cmake/macros/SetupHifiLibrary.cmake | 9 +++++++++ cmake/macros/SetupHifiProject.cmake | 9 +++++++++ 5 files changed, 46 insertions(+) diff --git a/cmake/macros/AutoMTC.cmake b/cmake/macros/AutoMTC.cmake index a2f5047ac7..1682b9cd56 100644 --- a/cmake/macros/AutoMTC.cmake +++ b/cmake/macros/AutoMTC.cmake @@ -1,3 +1,13 @@ +# +# AutoMTC.cmake +# +# Created by Andrzej Kapolka on 12/31/13. +# Copyright 2013 High Fidelity, Inc. +# +# Distributed under the Apache License, Version 2.0. +# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +# + macro(AUTO_MTC TARGET ROOT_DIR) if (NOT TARGET mtc) add_subdirectory("${ROOT_DIR}/tools/mtc" "${ROOT_DIR}/tools/mtc") diff --git a/cmake/macros/IncludeGLM.cmake b/cmake/macros/IncludeGLM.cmake index 7f5fe039c6..65974a51c5 100644 --- a/cmake/macros/IncludeGLM.cmake +++ b/cmake/macros/IncludeGLM.cmake @@ -1,3 +1,12 @@ +# +# IncludeGLM.cmake +# +# Copyright (c) 2013 High Fidelity +# +# Distributed under the Apache License, Version 2.0. +# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +# + macro(INCLUDE_GLM TARGET ROOT_DIR) find_package(GLM REQUIRED) diff --git a/cmake/macros/LinkHifiLibrary.cmake b/cmake/macros/LinkHifiLibrary.cmake index 02ebc983c2..6300e50c34 100644 --- a/cmake/macros/LinkHifiLibrary.cmake +++ b/cmake/macros/LinkHifiLibrary.cmake @@ -1,3 +1,12 @@ +# +# LinkHifiLibrary.cmake +# +# Copyright 2013 High Fidelity, Inc. +# +# Distributed under the Apache License, Version 2.0. +# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +# + macro(LINK_HIFI_LIBRARY LIBRARY TARGET ROOT_DIR) if (NOT TARGET ${LIBRARY}) diff --git a/cmake/macros/SetupHifiLibrary.cmake b/cmake/macros/SetupHifiLibrary.cmake index 19428b6723..ff4ae3b4f3 100644 --- a/cmake/macros/SetupHifiLibrary.cmake +++ b/cmake/macros/SetupHifiLibrary.cmake @@ -1,3 +1,12 @@ +# +# SetupHifiLibrary.cmake +# +# Copyright 2013 High Fidelity, Inc. +# +# Distributed under the Apache License, Version 2.0. +# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +# + macro(SETUP_HIFI_LIBRARY TARGET) project(${TARGET}) diff --git a/cmake/macros/SetupHifiProject.cmake b/cmake/macros/SetupHifiProject.cmake index a707626254..11252e2a74 100644 --- a/cmake/macros/SetupHifiProject.cmake +++ b/cmake/macros/SetupHifiProject.cmake @@ -1,3 +1,12 @@ +# +# SetupHifiProject.cmake +# +# Copyright (c) 2013 High Fidelity +# +# Distributed under the Apache License, Version 2.0. +# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +# + macro(SETUP_HIFI_PROJECT TARGET INCLUDE_QT) project(${TARGET}) From 974d8c042724757d1d20629bc2a2e1c0241309c2 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 09:35:05 -0700 Subject: [PATCH 238/595] prepare header files for regex run against cpp --- assignment-client/src/avatars/AvatarMixer.cpp | 1 + interface/src/Application.cpp | 1 + interface/src/Camera.cpp | 1 + interface/src/Environment.cpp | 1 + interface/src/avatar/Avatar.cpp | 1 + interface/src/avatar/AvatarManager.cpp | 1 + interface/src/avatar/Hand.cpp | 1 + interface/src/avatar/Head.cpp | 1 + interface/src/renderer/GeometryCache.cpp | 1 + interface/src/renderer/GlowEffect.cpp | 1 + interface/src/renderer/PointShader.cpp | 1 + interface/src/renderer/ProgramObject.cpp | 1 + interface/src/renderer/RenderUtil.cpp | 1 + interface/src/renderer/TextureCache.cpp | 1 + interface/src/renderer/VoxelShader.cpp | 1 + interface/src/starfield/data/GpuVertex.cpp | 1 + interface/src/starfield/renderer/Renderer.cpp | 10 +++++----- interface/src/ui/MetavoxelEditor.cpp | 1 + interface/src/ui/RearMirrorTools.cpp | 1 + interface/src/ui/RunningScriptsWidget.cpp | 1 + interface/src/ui/TextRenderer.cpp | 1 + interface/src/ui/overlays/LocalVoxelsOverlay.cpp | 2 +- libraries/octree/src/Plane.cpp | 2 +- libraries/script-engine/src/EventTypes.cpp | 1 + libraries/script-engine/src/MenuItemProperties.cpp | 1 + libraries/shared/src/RegisteredMetaTypes.cpp | 1 + libraries/voxels/src/EnvironmentData.cpp | 1 + 27 files changed, 31 insertions(+), 7 deletions(-) diff --git a/assignment-client/src/avatars/AvatarMixer.cpp b/assignment-client/src/avatars/AvatarMixer.cpp index c4c0dcda24..6d0201f872 100644 --- a/assignment-client/src/avatars/AvatarMixer.cpp +++ b/assignment-client/src/avatars/AvatarMixer.cpp @@ -9,6 +9,7 @@ // // The avatar mixer receives head, hand and positional data from all connected // nodes, and broadcasts that data back to them, every BROADCAST_INTERVAL ms. +// #include #include diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 45ae36a23b..4013989b99 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -4,6 +4,7 @@ // // Created by Andrzej Kapolka on 5/10/13. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// #ifdef WIN32 #include diff --git a/interface/src/Camera.cpp b/interface/src/Camera.cpp index 252b3be685..8918a3018d 100644 --- a/interface/src/Camera.cpp +++ b/interface/src/Camera.cpp @@ -3,6 +3,7 @@ // interface // // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// #include diff --git a/interface/src/Environment.cpp b/interface/src/Environment.cpp index 096b8770fb..36292c56a1 100644 --- a/interface/src/Environment.cpp +++ b/interface/src/Environment.cpp @@ -4,6 +4,7 @@ // // Created by Andrzej Kapolka on 5/6/13. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// #include "InterfaceConfig.h" diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 05f74755df..494c45c295 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -4,6 +4,7 @@ // // Created by Philip Rosedale on 9/11/12. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// #include diff --git a/interface/src/avatar/AvatarManager.cpp b/interface/src/avatar/AvatarManager.cpp index c2ba28ac7b..9f8e7feb2e 100644 --- a/interface/src/avatar/AvatarManager.cpp +++ b/interface/src/avatar/AvatarManager.cpp @@ -5,6 +5,7 @@ // Created by Stephen Birarda on 1/23/2014. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. // + #include #include diff --git a/interface/src/avatar/Hand.cpp b/interface/src/avatar/Hand.cpp index fc47520c83..c2ce17022d 100644 --- a/interface/src/avatar/Hand.cpp +++ b/interface/src/avatar/Hand.cpp @@ -3,6 +3,7 @@ // interface // // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// #include diff --git a/interface/src/avatar/Head.cpp b/interface/src/avatar/Head.cpp index f42220c0f4..fed86ed81f 100644 --- a/interface/src/avatar/Head.cpp +++ b/interface/src/avatar/Head.cpp @@ -3,6 +3,7 @@ // interface // // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// #include diff --git a/interface/src/renderer/GeometryCache.cpp b/interface/src/renderer/GeometryCache.cpp index b835e91a12..a3984b9306 100644 --- a/interface/src/renderer/GeometryCache.cpp +++ b/interface/src/renderer/GeometryCache.cpp @@ -4,6 +4,7 @@ // // Created by Andrzej Kapolka on 6/21/13. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// #include diff --git a/interface/src/renderer/GlowEffect.cpp b/interface/src/renderer/GlowEffect.cpp index f926a81941..1aea22367f 100644 --- a/interface/src/renderer/GlowEffect.cpp +++ b/interface/src/renderer/GlowEffect.cpp @@ -4,6 +4,7 @@ // // Created by Andrzej Kapolka on 8/7/13. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// // include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL #include "InterfaceConfig.h" diff --git a/interface/src/renderer/PointShader.cpp b/interface/src/renderer/PointShader.cpp index 6dd4aae485..4191a116e3 100644 --- a/interface/src/renderer/PointShader.cpp +++ b/interface/src/renderer/PointShader.cpp @@ -4,6 +4,7 @@ // // Created by Brad Hefta-Gaub on 10/30/13. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// // include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL #include "InterfaceConfig.h" diff --git a/interface/src/renderer/ProgramObject.cpp b/interface/src/renderer/ProgramObject.cpp index 5108c15068..71d6c100f1 100644 --- a/interface/src/renderer/ProgramObject.cpp +++ b/interface/src/renderer/ProgramObject.cpp @@ -4,6 +4,7 @@ // // Created by Andrzej Kapolka on 5/7/13. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// #include "ProgramObject.h" diff --git a/interface/src/renderer/RenderUtil.cpp b/interface/src/renderer/RenderUtil.cpp index 11ec8b572c..32cf36a650 100644 --- a/interface/src/renderer/RenderUtil.cpp +++ b/interface/src/renderer/RenderUtil.cpp @@ -4,6 +4,7 @@ // // Created by Andrzej Kapolka on 8/15/13. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// #include "InterfaceConfig.h" #include "RenderUtil.h" diff --git a/interface/src/renderer/TextureCache.cpp b/interface/src/renderer/TextureCache.cpp index b3820abf25..c959340f6b 100644 --- a/interface/src/renderer/TextureCache.cpp +++ b/interface/src/renderer/TextureCache.cpp @@ -4,6 +4,7 @@ // // Created by Andrzej Kapolka on 8/6/13. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// // include this before QGLWidget, which includes an earlier version of OpenGL #include "InterfaceConfig.h" diff --git a/interface/src/renderer/VoxelShader.cpp b/interface/src/renderer/VoxelShader.cpp index fab40fc338..0377e5fe72 100644 --- a/interface/src/renderer/VoxelShader.cpp +++ b/interface/src/renderer/VoxelShader.cpp @@ -4,6 +4,7 @@ // // Created by Brad Hefta-Gaub on 9/22/13. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// // include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL #include "InterfaceConfig.h" diff --git a/interface/src/starfield/data/GpuVertex.cpp b/interface/src/starfield/data/GpuVertex.cpp index 58db1d499a..85fc6f8f7e 100755 --- a/interface/src/starfield/data/GpuVertex.cpp +++ b/interface/src/starfield/data/GpuVertex.cpp @@ -6,6 +6,7 @@ // Based on code by Tobias Schwinger on 3/29/13. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. // + #include "starfield/data/GpuVertex.h" using namespace starfield; diff --git a/interface/src/starfield/renderer/Renderer.cpp b/interface/src/starfield/renderer/Renderer.cpp index 0be9850338..356e46c468 100755 --- a/interface/src/starfield/renderer/Renderer.cpp +++ b/interface/src/starfield/renderer/Renderer.cpp @@ -1,10 +1,10 @@ // -// starfield/renderer/Renderer.cpp -// interface +// starfield/renderer/Renderer.cpp +// interface // -// Created by Chris Barnard on 10/17/13. -// Based on earlier work by Tobias Schwinger 3/22/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Chris Barnard on 10/17/13. +// Based on earlier work by Tobias Schwinger 3/22/13. +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. // #include "starfield/renderer/Renderer.h" diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index ee1b4b0460..73a2476aa4 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -4,6 +4,7 @@ // // Created by Andrzej Kapolka on 1/21/14. // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// // include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL #include "InterfaceConfig.h" diff --git a/interface/src/ui/RearMirrorTools.cpp b/interface/src/ui/RearMirrorTools.cpp index 314fd7157b..c86770d4f0 100644 --- a/interface/src/ui/RearMirrorTools.cpp +++ b/interface/src/ui/RearMirrorTools.cpp @@ -4,6 +4,7 @@ // // Created by stojce on 23.10.2013. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// #include "InterfaceConfig.h" diff --git a/interface/src/ui/RunningScriptsWidget.cpp b/interface/src/ui/RunningScriptsWidget.cpp index 2238cab2df..dcb9210d56 100644 --- a/interface/src/ui/RunningScriptsWidget.cpp +++ b/interface/src/ui/RunningScriptsWidget.cpp @@ -4,6 +4,7 @@ // // Created by Mohammed Nafees on 03/28/2014. // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// #include "ui_runningScriptsWidget.h" #include "RunningScriptsWidget.h" diff --git a/interface/src/ui/TextRenderer.cpp b/interface/src/ui/TextRenderer.cpp index cacd730fd6..06c657e96e 100644 --- a/interface/src/ui/TextRenderer.cpp +++ b/interface/src/ui/TextRenderer.cpp @@ -4,6 +4,7 @@ // // Created by Andrzej Kapolka on 4/24/13. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// #include #include diff --git a/interface/src/ui/overlays/LocalVoxelsOverlay.cpp b/interface/src/ui/overlays/LocalVoxelsOverlay.cpp index 460f4eadb6..e605f8879d 100644 --- a/interface/src/ui/overlays/LocalVoxelsOverlay.cpp +++ b/interface/src/ui/overlays/LocalVoxelsOverlay.cpp @@ -5,7 +5,7 @@ // Created by Clément Brisset on 2/28/14. // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. // -// + // include this before QGLWidget, which includes an earlier version of OpenGL #include "InterfaceConfig.h" diff --git a/libraries/octree/src/Plane.cpp b/libraries/octree/src/Plane.cpp index 6a356784b7..727e16724c 100755 --- a/libraries/octree/src/Plane.cpp +++ b/libraries/octree/src/Plane.cpp @@ -1,5 +1,5 @@ // -// Plane.h +// Plane.cpp // hifi // // Created by Brad Hefta-Gaub on 04/11/13. diff --git a/libraries/script-engine/src/EventTypes.cpp b/libraries/script-engine/src/EventTypes.cpp index 9885b8d9dc..d5c2d72786 100644 --- a/libraries/script-engine/src/EventTypes.cpp +++ b/libraries/script-engine/src/EventTypes.cpp @@ -7,6 +7,7 @@ // // Used to register meta-types with Qt for very various event types so that they can be exposed to our // scripting engine +// #include #include diff --git a/libraries/script-engine/src/MenuItemProperties.cpp b/libraries/script-engine/src/MenuItemProperties.cpp index f071723233..8c91ad8fef 100644 --- a/libraries/script-engine/src/MenuItemProperties.cpp +++ b/libraries/script-engine/src/MenuItemProperties.cpp @@ -7,6 +7,7 @@ // // Used to register meta-types with Qt for very various event types so that they can be exposed to our // scripting engine +// #include #include diff --git a/libraries/shared/src/RegisteredMetaTypes.cpp b/libraries/shared/src/RegisteredMetaTypes.cpp index af074c59bc..0354fedba9 100644 --- a/libraries/shared/src/RegisteredMetaTypes.cpp +++ b/libraries/shared/src/RegisteredMetaTypes.cpp @@ -7,6 +7,7 @@ // // Used to register meta-types with Qt so that they can be used as properties for objects exposed to our // Agent scripting. +// #include "RegisteredMetaTypes.h" diff --git a/libraries/voxels/src/EnvironmentData.cpp b/libraries/voxels/src/EnvironmentData.cpp index 1c9af55abd..dc82844bd0 100644 --- a/libraries/voxels/src/EnvironmentData.cpp +++ b/libraries/voxels/src/EnvironmentData.cpp @@ -4,6 +4,7 @@ // // Created by Andrzej Kapolka on 5/6/13. // Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// #include From 684c6b5372b934e83b1222c2c9296eab2ad0a4f6 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 09:35:42 -0700 Subject: [PATCH 239/595] run regex header replacement on all cpp files --- animation-server/src/AnimationServer.cpp | 7 +- animation-server/src/main.cpp | 9 +- assignment-client/src/Agent.cpp | 7 +- assignment-client/src/AssignmentClient.cpp | 7 +- .../src/AssignmentClientMonitor.cpp | 9 +- assignment-client/src/AssignmentFactory.cpp | 7 +- assignment-client/src/AssignmentThread.cpp | 11 +- assignment-client/src/audio/AudioMixer.cpp | 7 +- .../src/audio/AudioMixerClientData.cpp | 7 +- .../src/audio/AvatarAudioRingBuffer.cpp | 9 +- assignment-client/src/avatars/AvatarMixer.cpp | 10 +- .../src/avatars/AvatarMixerClientData.cpp | 7 +- assignment-client/src/main.cpp | 9 +- .../src/metavoxels/MetavoxelServer.cpp | 7 +- .../octree/OctreeInboundPacketProcessor.cpp | 9 +- .../src/octree/OctreeQueryNode.cpp | 5 +- .../src/octree/OctreeSendThread.cpp | 8 +- assignment-client/src/octree/OctreeServer.cpp | 7 +- .../src/particles/ParticleServer.cpp | 9 +- assignment-client/src/voxels/VoxelServer.cpp | 7 +- domain-server/src/DomainServer.cpp | 7 +- domain-server/src/DomainServerNodeData.cpp | 9 +- domain-server/src/main.cpp | 11 +- interface/src/Application.cpp | 7 +- interface/src/Audio.cpp | 7 +- interface/src/BuckyBalls.cpp | 5 +- interface/src/Camera.cpp | 7 +- interface/src/DatagramProcessor.cpp | 7 +- interface/src/Environment.cpp | 7 +- interface/src/FileLogger.cpp | 5 +- interface/src/GLCanvas.cpp | 7 +- interface/src/Menu.cpp | 7 +- interface/src/MetavoxelSystem.cpp | 7 +- interface/src/ParticleTreeRenderer.cpp | 6 +- interface/src/Physics.cpp | 30 +- interface/src/Stars.cpp | 11 +- interface/src/Util.cpp | 41 +-- interface/src/XmppClient.cpp | 9 +- interface/src/avatar/Avatar.cpp | 7 +- interface/src/avatar/AvatarManager.cpp | 7 +- interface/src/avatar/FaceModel.cpp | 7 +- interface/src/avatar/Hand.cpp | 7 +- interface/src/avatar/Head.cpp | 7 +- interface/src/avatar/MyAvatar.cpp | 7 +- interface/src/avatar/SkeletonModel.cpp | 7 +- interface/src/devices/Faceshift.cpp | 7 +- interface/src/devices/OculusManager.cpp | 7 +- interface/src/devices/SixenseManager.cpp | 9 +- interface/src/devices/TV3DManager.cpp | 7 +- interface/src/devices/Visage.cpp | 7 +- interface/src/location/LocationManager.cpp | 5 +- interface/src/location/NamedLocation.cpp | 7 +- interface/src/main.cpp | 17 +- .../src/renderer/AmbientOcclusionEffect.cpp | 7 +- interface/src/renderer/FBXReader.cpp | 7 +- interface/src/renderer/GeometryCache.cpp | 7 +- interface/src/renderer/GlowEffect.cpp | 7 +- interface/src/renderer/Model.cpp | 7 +- interface/src/renderer/PointShader.cpp | 7 +- interface/src/renderer/ProgramObject.cpp | 7 +- interface/src/renderer/RenderUtil.cpp | 7 +- interface/src/renderer/TextureCache.cpp | 7 +- interface/src/renderer/VoxelShader.cpp | 7 +- .../AudioDeviceScriptingInterface.cpp | 9 +- .../scripting/ClipboardScriptingInterface.cpp | 9 +- .../ControllerScriptingInterface.cpp | 11 +- .../src/scripting/MenuScriptingInterface.cpp | 9 +- .../scripting/SettingsScriptingInterface.cpp | 9 +- interface/src/starfield/Controller.cpp | 12 +- interface/src/starfield/Generator.cpp | 11 +- interface/src/starfield/data/GpuVertex.cpp | 12 +- interface/src/starfield/data/InputVertex.cpp | 12 +- interface/src/starfield/renderer/Renderer.cpp | 10 +- .../src/starfield/renderer/VertexOrder.cpp | 13 +- interface/src/ui/BandwidthDialog.cpp | 9 +- interface/src/ui/BandwidthMeter.cpp | 9 +- interface/src/ui/ChatWindow.cpp | 7 +- interface/src/ui/ImportDialog.cpp | 7 +- interface/src/ui/InfoView.cpp | 9 +- interface/src/ui/LodToolsDialog.cpp | 7 +- interface/src/ui/LogDialog.cpp | 7 +- interface/src/ui/MetavoxelEditor.cpp | 7 +- interface/src/ui/ModelsBrowser.cpp | 7 +- interface/src/ui/OctreeStatsDialog.cpp | 7 +- interface/src/ui/Oscilloscope.cpp | 7 +- interface/src/ui/RearMirrorTools.cpp | 9 +- interface/src/ui/RunningScriptsWidget.cpp | 9 +- interface/src/ui/Snapshot.cpp | 7 +- interface/src/ui/Stats.cpp | 7 +- interface/src/ui/TextRenderer.cpp | 7 +- interface/src/ui/UpdateDialog.cpp | 10 +- interface/src/ui/overlays/Base3DOverlay.cpp | 7 +- interface/src/ui/overlays/Cube3DOverlay.cpp | 7 +- interface/src/ui/overlays/ImageOverlay.cpp | 7 +- interface/src/ui/overlays/Line3DOverlay.cpp | 7 +- .../src/ui/overlays/LocalVoxelsOverlay.cpp | 7 +- interface/src/ui/overlays/Overlay.cpp | 7 +- interface/src/ui/overlays/Overlay2D.cpp | 7 +- interface/src/ui/overlays/Overlays.cpp | 7 +- interface/src/ui/overlays/Sphere3DOverlay.cpp | 7 +- interface/src/ui/overlays/TextOverlay.cpp | 7 +- interface/src/ui/overlays/Volume3DOverlay.cpp | 7 +- interface/src/voxels/PrimitiveRenderer.cpp | 18 +- interface/src/voxels/VoxelFade.cpp | 7 +- interface/src/voxels/VoxelHideShowThread.cpp | 9 +- interface/src/voxels/VoxelImporter.cpp | 7 +- interface/src/voxels/VoxelPacketProcessor.cpp | 7 +- interface/src/voxels/VoxelSystem.cpp | 6 +- libraries/audio/src/AudioInjector.cpp | 7 +- libraries/audio/src/AudioInjectorOptions.cpp | 9 +- libraries/audio/src/AudioRingBuffer.cpp | 7 +- .../audio/src/AudioScriptingInterface.cpp | 7 +- .../audio/src/InjectedAudioRingBuffer.cpp | 7 +- libraries/audio/src/MixedAudioRingBuffer.cpp | 11 +- .../audio/src/PositionalAudioRingBuffer.cpp | 7 +- libraries/audio/src/Sound.cpp | 151 +-------- libraries/avatars/src/AvatarData.cpp | 7 +- libraries/avatars/src/AvatarHashMap.cpp | 7 +- libraries/avatars/src/HandData.cpp | 7 +- libraries/avatars/src/HeadData.cpp | 7 +- .../embedded-webserver/src/HTTPConnection.cpp | 7 +- .../embedded-webserver/src/HTTPManager.cpp | 7 +- .../metavoxels/src/AttributeRegistry.cpp | 7 +- libraries/metavoxels/src/Bitstream.cpp | 7 +- .../metavoxels/src/DatagramSequencer.cpp | 7 +- libraries/metavoxels/src/MetavoxelData.cpp | 7 +- .../metavoxels/src/MetavoxelMessages.cpp | 7 +- libraries/metavoxels/src/MetavoxelUtil.cpp | 7 +- libraries/metavoxels/src/ScriptCache.cpp | 7 +- libraries/metavoxels/src/SharedObject.cpp | 7 +- libraries/octree/src/AABox.cpp | 11 +- libraries/octree/src/CoverageMap.cpp | 44 +-- libraries/octree/src/CoverageMapV2.cpp | 45 +-- libraries/octree/src/JurisdictionListener.cpp | 7 +- libraries/octree/src/JurisdictionMap.cpp | 7 +- libraries/octree/src/JurisdictionSender.cpp | 7 +- libraries/octree/src/Octree.cpp | 7 +- .../octree/src/OctreeEditPacketSender.cpp | 7 +- libraries/octree/src/OctreeElement.cpp | 7 +- libraries/octree/src/OctreeElementBag.cpp | 9 +- libraries/octree/src/OctreeHeadlessViewer.cpp | 8 +- libraries/octree/src/OctreePacketData.cpp | 7 +- libraries/octree/src/OctreePersistThread.cpp | 9 +- .../octree/src/OctreeProjectedPolygon.cpp | 10 +- libraries/octree/src/OctreeQuery.cpp | 7 +- libraries/octree/src/OctreeRenderer.cpp | 6 +- libraries/octree/src/OctreeSceneStats.cpp | 6 +- .../octree/src/OctreeScriptingInterface.cpp | 9 +- libraries/octree/src/ViewFrustum.cpp | 7 +- libraries/particles/src/Particle.cpp | 6 +- .../particles/src/ParticleCollisionSystem.cpp | 6 +- .../src/ParticleEditPacketSender.cpp | 7 +- libraries/particles/src/ParticleTree.cpp | 7 +- .../particles/src/ParticleTreeElement.cpp | 7 +- .../src/ParticleTreeHeadlessViewer.cpp | 8 +- .../src/ParticlesScriptingInterface.cpp | 9 +- libraries/script-engine/src/EventTypes.cpp | 8 +- libraries/script-engine/src/LocalVoxels.cpp | 7 +- .../script-engine/src/MenuItemProperties.cpp | 8 +- libraries/script-engine/src/Quat.cpp | 10 +- libraries/script-engine/src/ScriptEngine.cpp | 7 +- libraries/script-engine/src/Vec3.cpp | 10 +- libraries/shared/src/AccountManager.cpp | 7 +- libraries/shared/src/Assignment.cpp | 7 +- libraries/shared/src/CapsuleShape.cpp | 9 +- libraries/shared/src/CollisionInfo.cpp | 9 +- .../shared/src/DataServerAccountInfo.cpp | 7 +- libraries/shared/src/DomainInfo.cpp | 7 +- libraries/shared/src/FileUtils.cpp | 5 +- libraries/shared/src/GenericThread.cpp | 7 +- libraries/shared/src/GeometryUtil.cpp | 295 +----------------- libraries/shared/src/HifiSockAddr.cpp | 7 +- libraries/shared/src/ListShape.cpp | 8 +- libraries/shared/src/Logging.cpp | 7 +- libraries/shared/src/ModelUploader.cpp | 6 +- libraries/shared/src/NetworkPacket.cpp | 7 +- libraries/shared/src/Node.cpp | 7 +- libraries/shared/src/NodeData.cpp | 9 +- libraries/shared/src/NodeList.cpp | 7 +- libraries/shared/src/OAuthAccessToken.cpp | 7 +- libraries/shared/src/OctalCode.cpp | 7 +- libraries/shared/src/PacketHeaders.cpp | 7 +- libraries/shared/src/PacketSender.cpp | 9 +- libraries/shared/src/PerfStat.cpp | 11 +- .../shared/src/ReceivedPacketProcessor.cpp | 7 +- libraries/shared/src/RegisteredMetaTypes.cpp | 8 +- libraries/shared/src/ResourceCache.cpp | 7 +- libraries/shared/src/ShapeCollider.cpp | 9 +- libraries/shared/src/SharedUtil.cpp | 7 +- libraries/shared/src/SimpleMovingAverage.cpp | 9 +- libraries/shared/src/StdDev.cpp | 9 +- libraries/shared/src/StreamUtils.cpp | 8 +- libraries/shared/src/ThreadedAssignment.cpp | 7 +- libraries/shared/src/UUID.cpp | 9 +- libraries/voxels/src/EnvironmentData.cpp | 7 +- libraries/voxels/src/LocalVoxelsList.cpp | 9 +- libraries/voxels/src/Tags.cpp | 7 +- libraries/voxels/src/VoxelDetail.cpp | 9 +- .../voxels/src/VoxelEditPacketSender.cpp | 7 +- libraries/voxels/src/VoxelTree.cpp | 7 +- libraries/voxels/src/VoxelTreeCommands.cpp | 8 +- libraries/voxels/src/VoxelTreeElement.cpp | 7 +- .../voxels/src/VoxelTreeHeadlessViewer.cpp | 8 +- .../voxels/src/VoxelsScriptingInterface.cpp | 7 +- voxel-edit/src/SceneUtils.cpp | 7 +- voxel-edit/src/main.cpp | 7 +- 206 files changed, 1065 insertions(+), 1094 deletions(-) diff --git a/animation-server/src/AnimationServer.cpp b/animation-server/src/AnimationServer.cpp index 1f0828ec17..6a4d1ea76d 100644 --- a/animation-server/src/AnimationServer.cpp +++ b/animation-server/src/AnimationServer.cpp @@ -1,9 +1,12 @@ // // AnimationServer.cpp -// hifi +// animation-server/src // // Created by Stephen Birarda on 12/5/2013. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/animation-server/src/main.cpp b/animation-server/src/main.cpp index 3cdb7f04be..8acf3b8db2 100644 --- a/animation-server/src/main.cpp +++ b/animation-server/src/main.cpp @@ -1,9 +1,12 @@ // // main.cpp -// Animation Server +// animation-server/src // -// Created by Brad Hefta-Gaub on 05/16/2013 -// Copyright (c) 2012 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 05/16/2013. +// Copyright 2012 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 "AnimationServer.h" diff --git a/assignment-client/src/Agent.cpp b/assignment-client/src/Agent.cpp index b5199e87e8..f376c4e981 100644 --- a/assignment-client/src/Agent.cpp +++ b/assignment-client/src/Agent.cpp @@ -1,9 +1,12 @@ // // Agent.cpp -// hifi +// assignment-client/src // // Created by Stephen Birarda on 7/1/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/assignment-client/src/AssignmentClient.cpp b/assignment-client/src/AssignmentClient.cpp index aa20f2ff29..9d9bfa3113 100644 --- a/assignment-client/src/AssignmentClient.cpp +++ b/assignment-client/src/AssignmentClient.cpp @@ -1,9 +1,12 @@ // // AssignmentClient.cpp -// hifi +// assignment-client/src // // Created by Stephen Birarda on 11/25/2013. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/assignment-client/src/AssignmentClientMonitor.cpp b/assignment-client/src/AssignmentClientMonitor.cpp index 64c9b31147..af09ff1535 100644 --- a/assignment-client/src/AssignmentClientMonitor.cpp +++ b/assignment-client/src/AssignmentClientMonitor.cpp @@ -1,9 +1,12 @@ // // AssignmentClientMonitor.cpp -// hifi +// assignment-client/src // // Created by Stephen Birarda on 1/10/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include @@ -53,4 +56,4 @@ void AssignmentClientMonitor::spawnChildClient() { void AssignmentClientMonitor::childProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) { qDebug("Replacing dead child assignment client with a new one"); spawnChildClient(); -} \ No newline at end of file +} diff --git a/assignment-client/src/AssignmentFactory.cpp b/assignment-client/src/AssignmentFactory.cpp index cde5666ab9..cdf5c591e1 100644 --- a/assignment-client/src/AssignmentFactory.cpp +++ b/assignment-client/src/AssignmentFactory.cpp @@ -1,9 +1,12 @@ // // AssignmentFactory.cpp -// hifi +// assignment-client/src // // Created by Stephen Birarda on 9/17/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/assignment-client/src/AssignmentThread.cpp b/assignment-client/src/AssignmentThread.cpp index dfe093aa7b..848fa7afae 100644 --- a/assignment-client/src/AssignmentThread.cpp +++ b/assignment-client/src/AssignmentThread.cpp @@ -1,9 +1,12 @@ // // AssignmentThread.cpp -// hifi +// assignment-client/src // -// Created by Stephen Birarda on 2014-03-28. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Stephen Birarda on 2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "AssignmentThread.h" @@ -13,4 +16,4 @@ AssignmentThread::AssignmentThread(const SharedAssignmentPointer& assignment, QO _assignment(assignment) { -} \ No newline at end of file +} diff --git a/assignment-client/src/audio/AudioMixer.cpp b/assignment-client/src/audio/AudioMixer.cpp index f183abade9..35b522ff2f 100644 --- a/assignment-client/src/audio/AudioMixer.cpp +++ b/assignment-client/src/audio/AudioMixer.cpp @@ -1,9 +1,12 @@ // // AudioMixer.cpp -// hifi +// assignment-client/src/audio // // Created by Stephen Birarda on 8/22/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/assignment-client/src/audio/AudioMixerClientData.cpp b/assignment-client/src/audio/AudioMixerClientData.cpp index 4a9f1f84de..85b8dde690 100644 --- a/assignment-client/src/audio/AudioMixerClientData.cpp +++ b/assignment-client/src/audio/AudioMixerClientData.cpp @@ -1,9 +1,12 @@ // // AudioMixerClientData.cpp -// hifi +// assignment-client/src/audio // // Created by Stephen Birarda on 10/18/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/assignment-client/src/audio/AvatarAudioRingBuffer.cpp b/assignment-client/src/audio/AvatarAudioRingBuffer.cpp index 4b1907efb8..9a7c2839d8 100644 --- a/assignment-client/src/audio/AvatarAudioRingBuffer.cpp +++ b/assignment-client/src/audio/AvatarAudioRingBuffer.cpp @@ -1,9 +1,12 @@ // // AvatarAudioRingBuffer.cpp -// hifi +// assignment-client/src/audio // // Created by Stephen Birarda on 6/5/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include @@ -18,4 +21,4 @@ AvatarAudioRingBuffer::AvatarAudioRingBuffer() : int AvatarAudioRingBuffer::parseData(const QByteArray& packet) { _shouldLoopbackForNode = (packetTypeForPacket(packet) == PacketTypeMicrophoneAudioWithEcho); return PositionalAudioRingBuffer::parseData(packet); -} \ No newline at end of file +} diff --git a/assignment-client/src/avatars/AvatarMixer.cpp b/assignment-client/src/avatars/AvatarMixer.cpp index 6d0201f872..93f38e3608 100644 --- a/assignment-client/src/avatars/AvatarMixer.cpp +++ b/assignment-client/src/avatars/AvatarMixer.cpp @@ -1,14 +1,12 @@ // // AvatarMixer.cpp -// hifi +// assignment-client/src/avatars // // Created by Stephen Birarda on 9/5/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Original avatar-mixer main created by Leonardo Murillo on 03/25/13. -// -// The avatar mixer receives head, hand and positional data from all connected -// nodes, and broadcasts that data back to them, every BROADCAST_INTERVAL ms. +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/assignment-client/src/avatars/AvatarMixerClientData.cpp b/assignment-client/src/avatars/AvatarMixerClientData.cpp index d1449e956e..9289d640f5 100644 --- a/assignment-client/src/avatars/AvatarMixerClientData.cpp +++ b/assignment-client/src/avatars/AvatarMixerClientData.cpp @@ -1,9 +1,12 @@ // // AvatarMixerClientData.cpp -// hifi +// assignment-client/src/avatars // // Created by Stephen Birarda on 2/4/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "AvatarMixerClientData.h" diff --git a/assignment-client/src/main.cpp b/assignment-client/src/main.cpp index 0151f93319..24d19ddef6 100644 --- a/assignment-client/src/main.cpp +++ b/assignment-client/src/main.cpp @@ -1,9 +1,12 @@ // // main.cpp -// assignment-client +// assignment-client/src // // Created by Stephen Birarda on 8/22/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include @@ -37,4 +40,4 @@ int main(int argc, char* argv[]) { AssignmentClient client(argc, argv); return client.exec(); } -} \ No newline at end of file +} diff --git a/assignment-client/src/metavoxels/MetavoxelServer.cpp b/assignment-client/src/metavoxels/MetavoxelServer.cpp index 23c8f2189c..3bf1632074 100644 --- a/assignment-client/src/metavoxels/MetavoxelServer.cpp +++ b/assignment-client/src/metavoxels/MetavoxelServer.cpp @@ -1,9 +1,12 @@ // // MetavoxelServer.cpp -// hifi +// assignment-client/src/metavoxels // // Created by Andrzej Kapolka on 12/18/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/assignment-client/src/octree/OctreeInboundPacketProcessor.cpp b/assignment-client/src/octree/OctreeInboundPacketProcessor.cpp index 5e8de3a1b3..41158bf339 100644 --- a/assignment-client/src/octree/OctreeInboundPacketProcessor.cpp +++ b/assignment-client/src/octree/OctreeInboundPacketProcessor.cpp @@ -1,11 +1,12 @@ // // OctreeInboundPacketProcessor.cpp -// voxel-server +// assignment-client/src/octree // -// Created by Brad Hefta-Gaub on 8/21/13 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 8/21/13. +// Copyright 2013 High Fidelity, Inc. // -// Threaded or non-threaded network packet processor for the voxel-server +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/assignment-client/src/octree/OctreeQueryNode.cpp b/assignment-client/src/octree/OctreeQueryNode.cpp index 984ce42631..00526cc967 100644 --- a/assignment-client/src/octree/OctreeQueryNode.cpp +++ b/assignment-client/src/octree/OctreeQueryNode.cpp @@ -1,9 +1,12 @@ // // OctreeQueryNode.cpp -// hifi +// assignment-client/src/octree // // Created by Stephen Birarda on 3/21/13. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "PacketHeaders.h" diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index 4105b21eb8..0a53160b8f 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -1,8 +1,12 @@ // // OctreeSendThread.cpp +// assignment-client/src/octree // -// Created by Brad Hefta-Gaub on 8/21/13 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 8/21/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index fd3f9e6cb7..2e8a354c6a 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -1,9 +1,12 @@ // // OctreeServer.cpp -// hifi +// assignment-client/src/octree // // Created by Brad Hefta-Gaub on 9/16/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/assignment-client/src/particles/ParticleServer.cpp b/assignment-client/src/particles/ParticleServer.cpp index 1785ef46d6..649ee0cff9 100644 --- a/assignment-client/src/particles/ParticleServer.cpp +++ b/assignment-client/src/particles/ParticleServer.cpp @@ -1,9 +1,12 @@ // // ParticleServer.cpp -// hifi +// assignment-client/src/particles // -// Created by Brad Hefta-Gaub on 12/4/13 -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 12/4/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/assignment-client/src/voxels/VoxelServer.cpp b/assignment-client/src/voxels/VoxelServer.cpp index 771c91570f..7747b8336b 100644 --- a/assignment-client/src/voxels/VoxelServer.cpp +++ b/assignment-client/src/voxels/VoxelServer.cpp @@ -1,9 +1,12 @@ // // VoxelServer.cpp -// hifi +// assignment-client/src/voxels // // Created by Brad Hefta-Gaub on 9/16/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 8d1ee9d3dd..05d1fcd534 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -1,9 +1,12 @@ // // DomainServer.cpp -// hifi +// domain-server/src // // Created by Stephen Birarda on 9/26/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/domain-server/src/DomainServerNodeData.cpp b/domain-server/src/DomainServerNodeData.cpp index f1e08e3bc4..9e118faff6 100644 --- a/domain-server/src/DomainServerNodeData.cpp +++ b/domain-server/src/DomainServerNodeData.cpp @@ -1,9 +1,12 @@ // // DomainServerNodeData.cpp -// hifi +// domain-server/src // // Created by Stephen Birarda on 2/6/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include @@ -45,4 +48,4 @@ QJsonObject DomainServerNodeData::mergeJSONStatsFromNewObject(const QJsonObject& } return destinationObject; -} \ No newline at end of file +} diff --git a/domain-server/src/main.cpp b/domain-server/src/main.cpp index 970d1dad70..d79f06365d 100644 --- a/domain-server/src/main.cpp +++ b/domain-server/src/main.cpp @@ -1,15 +1,12 @@ // // main.cpp -// Domain Server +// domain-server/src // // Created by Philip Rosedale on 11/20/12. -// Copyright (c) 2012 High Fidelity, Inc. All rights reserved. +// Copyright 2012 High Fidelity, Inc. // -// The Domain Server keeps a list of nodes that have connected to it, and echoes that list of -// nodes out to nodes when they check in. -// -// The connection is stateless... the domain server will set you inactive if it does not hear from -// you in LOGOFF_CHECK_INTERVAL milliseconds, meaning your info will not be sent to other users. +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 4013989b99..1faf1d4f0d 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1,9 +1,12 @@ // // Application.cpp -// interface +// interface/src // // Created by Andrzej Kapolka on 5/10/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifdef WIN32 diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 63c683dbb0..719bfd8aa1 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -1,9 +1,12 @@ // // Audio.cpp -// interface +// interface/src // // Created by Stephen Birarda on 1/22/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/BuckyBalls.cpp b/interface/src/BuckyBalls.cpp index 8e489db74b..e1ec41dca1 100644 --- a/interface/src/BuckyBalls.cpp +++ b/interface/src/BuckyBalls.cpp @@ -1,9 +1,12 @@ // // BuckyBalls.cpp -// hifi +// interface/src // // Created by Philip on 1/2/14. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "BuckyBalls.h" diff --git a/interface/src/Camera.cpp b/interface/src/Camera.cpp index 8918a3018d..2ef32dac5f 100644 --- a/interface/src/Camera.cpp +++ b/interface/src/Camera.cpp @@ -1,8 +1,11 @@ // // Camera.cpp -// interface +// interface/src // -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/DatagramProcessor.cpp b/interface/src/DatagramProcessor.cpp index 50e84db7b5..92260ad9dc 100644 --- a/interface/src/DatagramProcessor.cpp +++ b/interface/src/DatagramProcessor.cpp @@ -1,9 +1,12 @@ // // DatagramProcessor.cpp -// hifi +// interface/src // // Created by Stephen Birarda on 1/23/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/Environment.cpp b/interface/src/Environment.cpp index 36292c56a1..1ba2f0501c 100644 --- a/interface/src/Environment.cpp +++ b/interface/src/Environment.cpp @@ -1,9 +1,12 @@ // // Environment.cpp -// interface +// interface/src // // Created by Andrzej Kapolka on 5/6/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "InterfaceConfig.h" diff --git a/interface/src/FileLogger.cpp b/interface/src/FileLogger.cpp index 81c626a46e..c4e75b21b2 100644 --- a/interface/src/FileLogger.cpp +++ b/interface/src/FileLogger.cpp @@ -1,9 +1,12 @@ // // FileLogger.cpp -// hifi +// interface/src // // Created by Stojce Slavkovski on 12/22/13. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "FileLogger.h" diff --git a/interface/src/GLCanvas.cpp b/interface/src/GLCanvas.cpp index 513dcfe40c..9f1bf303fa 100644 --- a/interface/src/GLCanvas.cpp +++ b/interface/src/GLCanvas.cpp @@ -1,9 +1,12 @@ // // GLCanvas.cpp -// hifi +// interface/src // // Created by Stephen Birarda on 8/14/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "Application.h" diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 8a97c98f02..70e69597f6 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -1,9 +1,12 @@ // // Menu.cpp -// hifi +// interface/src // // Created by Stephen Birarda on 8/12/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index 6b4d817f7f..78c97c1703 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -1,9 +1,12 @@ // // MetavoxelSystem.cpp -// interface +// interface/src // // Created by Andrzej Kapolka on 12/10/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/ParticleTreeRenderer.cpp b/interface/src/ParticleTreeRenderer.cpp index 59784c8c1f..aa498082d9 100644 --- a/interface/src/ParticleTreeRenderer.cpp +++ b/interface/src/ParticleTreeRenderer.cpp @@ -1,10 +1,12 @@ // // ParticleTreeRenderer.cpp -// hifi +// interface/src // // Created by Brad Hefta-Gaub on 12/6/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/Physics.cpp b/interface/src/Physics.cpp index 101087b1ef..a9f9f6b17d 100644 --- a/interface/src/Physics.cpp +++ b/interface/src/Physics.cpp @@ -1,33 +1,11 @@ // // Physics.cpp -// hifi +// interface/src // -// Created by Philip on July 11, 2013 +// Copyright 2013 High Fidelity, Inc. // -// Routines to help with doing virtual world physics -// - -#include -#include - -#include "Util.h" -#include "world.h" -#include "Physics.h" - -// -// Applies static friction: maxVelocity is the largest velocity for which there -// there is friction, and strength is the amount of friction force applied to reduce -// velocity. -// -void applyStaticFriction(float deltaTime, glm::vec3& velocity, float maxVelocity, float strength) { - float v = glm::length(velocity); - if (v < maxVelocity) { - velocity *= glm::clamp((1.0f - deltaTime * strength * (1.f - v / maxVelocity)), 0.0f, 1.0f); - } -} - -// -// Applies velocity damping, with a strength value for linear and squared velocity damping +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // void applyDamping(float deltaTime, glm::vec3& velocity, float linearStrength, float squaredStrength) { diff --git a/interface/src/Stars.cpp b/interface/src/Stars.cpp index dcfe726fff..e5662005d5 100755 --- a/interface/src/Stars.cpp +++ b/interface/src/Stars.cpp @@ -1,9 +1,12 @@ // -// Stars.cpp -// interface +// Stars.cpp +// interface/src // -// Created by Tobias Schwinger on 3/22/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Tobias Schwinger on 3/22/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "InterfaceConfig.h" diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 1921fe924b..4fe5636329 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -1,42 +1,13 @@ // -// util.cpp -// interface +// Util.cpp +// interface/src // // Created by Philip Rosedale on 8/24/12. -// Copyright (c) 2012 High Fidelity, Inc. All rights reserved. +// Copyright 2012 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 -#include - -#include -#include -#include -#include - -#include - -#include "InterfaceConfig.h" -#include "ui/TextRenderer.h" -#include "VoxelConstants.h" -#include "world.h" - -#include "Util.h" - -using namespace std; - -// no clue which versions are affected... -#define WORKAROUND_BROKEN_GLUT_STROKES -// see http://www.opengl.org/resources/libraries/glut/spec3/node78.html - -void eulerToOrthonormals(glm::vec3 * angles, glm::vec3 * front, glm::vec3 * right, glm::vec3 * up) { - // - // Converts from three euler angles to the associated orthonormal vectors - // - // Angles contains (pitch, yaw, roll) in radians - // // First, create the quaternion associated with these euler angles glm::quat q(glm::vec3(angles->x, -(angles->y), angles->z)); diff --git a/interface/src/XmppClient.cpp b/interface/src/XmppClient.cpp index df8cf34874..d930c16b53 100644 --- a/interface/src/XmppClient.cpp +++ b/interface/src/XmppClient.cpp @@ -1,9 +1,12 @@ // // XmppClient.cpp -// interface +// interface/src // -// Created by Dimitar Dobrev on 10/3/14 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Dimitar Dobrev on 10/3/14. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifdef HAVE_QXMPP diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 494c45c295..47ced025aa 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -1,9 +1,12 @@ // // Avatar.cpp -// interface +// interface/src/avatar // // Created by Philip Rosedale on 9/11/12. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/avatar/AvatarManager.cpp b/interface/src/avatar/AvatarManager.cpp index 9f8e7feb2e..38163ef326 100644 --- a/interface/src/avatar/AvatarManager.cpp +++ b/interface/src/avatar/AvatarManager.cpp @@ -1,9 +1,12 @@ // // AvatarManager.cpp -// hifi +// interface/src/avatar // // Created by Stephen Birarda on 1/23/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/avatar/FaceModel.cpp b/interface/src/avatar/FaceModel.cpp index e81e1da117..709a9fc79d 100644 --- a/interface/src/avatar/FaceModel.cpp +++ b/interface/src/avatar/FaceModel.cpp @@ -1,9 +1,12 @@ // // FaceModel.cpp -// interface +// interface/src/avatar // // Created by Andrzej Kapolka on 9/16/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/avatar/Hand.cpp b/interface/src/avatar/Hand.cpp index c2ce17022d..832a3da6ca 100644 --- a/interface/src/avatar/Hand.cpp +++ b/interface/src/avatar/Hand.cpp @@ -1,8 +1,11 @@ // // Hand.cpp -// interface +// interface/src/avatar // -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/avatar/Head.cpp b/interface/src/avatar/Head.cpp index fed86ed81f..8316c90aca 100644 --- a/interface/src/avatar/Head.cpp +++ b/interface/src/avatar/Head.cpp @@ -1,8 +1,11 @@ // // Head.cpp -// interface +// interface/src/avatar // -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 73d2a84eb7..af105de04a 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -1,9 +1,12 @@ // // MyAvatar.cpp -// interface +// interface/src/avatar // // Created by Mark Peng on 8/16/13. -// Copyright (c) 2012 High Fidelity, Inc. All rights reserved. +// Copyright 2012 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 diff --git a/interface/src/avatar/SkeletonModel.cpp b/interface/src/avatar/SkeletonModel.cpp index 93eaf22ab8..b9ac280711 100644 --- a/interface/src/avatar/SkeletonModel.cpp +++ b/interface/src/avatar/SkeletonModel.cpp @@ -1,9 +1,12 @@ // // SkeletonModel.cpp -// interface +// interface/src/avatar // // Created by Andrzej Kapolka on 10/17/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/devices/Faceshift.cpp b/interface/src/devices/Faceshift.cpp index 9f1734c7e5..1fd4b4bf1d 100644 --- a/interface/src/devices/Faceshift.cpp +++ b/interface/src/devices/Faceshift.cpp @@ -1,9 +1,12 @@ // // Faceshift.cpp -// interface +// interface/src/devices // // Created by Andrzej Kapolka on 9/3/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index c5377ce428..a69fd48087 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -1,9 +1,12 @@ // // OculusManager.cpp -// hifi +// interface/src/devices // // Created by Stephen Birarda on 5/9/13. -// Copyright (c) 2012 High Fidelity, Inc. All rights reserved. +// Copyright 2012 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 "InterfaceConfig.h" diff --git a/interface/src/devices/SixenseManager.cpp b/interface/src/devices/SixenseManager.cpp index 8e54e034ac..b950e6097c 100644 --- a/interface/src/devices/SixenseManager.cpp +++ b/interface/src/devices/SixenseManager.cpp @@ -1,9 +1,12 @@ // -// Sixense.cpp -// interface +// SixenseManager.cpp +// interface/src/devices // // Created by Andrzej Kapolka on 11/15/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/devices/TV3DManager.cpp b/interface/src/devices/TV3DManager.cpp index 07aeea92b4..fcbef0385c 100644 --- a/interface/src/devices/TV3DManager.cpp +++ b/interface/src/devices/TV3DManager.cpp @@ -1,9 +1,12 @@ // // TV3DManager.cpp -// hifi +// interface/src/devices // // Created by Brad Hefta-Gaub on 12/24/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "InterfaceConfig.h" diff --git a/interface/src/devices/Visage.cpp b/interface/src/devices/Visage.cpp index b96ef1ee72..72f0306e79 100644 --- a/interface/src/devices/Visage.cpp +++ b/interface/src/devices/Visage.cpp @@ -1,9 +1,12 @@ // // Visage.cpp -// interface +// interface/src/devices // // Created by Andrzej Kapolka on 2/11/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/location/LocationManager.cpp b/interface/src/location/LocationManager.cpp index b83094ba4c..7d22dde040 100644 --- a/interface/src/location/LocationManager.cpp +++ b/interface/src/location/LocationManager.cpp @@ -1,9 +1,12 @@ // // LocationManager.cpp -// hifi +// interface/src/location // // Created by Stojce Slavkovski on 2/7/14. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "Application.h" diff --git a/interface/src/location/NamedLocation.cpp b/interface/src/location/NamedLocation.cpp index c6daef4961..ed7701a391 100644 --- a/interface/src/location/NamedLocation.cpp +++ b/interface/src/location/NamedLocation.cpp @@ -1,9 +1,12 @@ // -// LocationManager.cpp -// hifi +// NamedLocation.cpp +// interface/src/location // // Created by Stojce Slavkovski on 2/1/14. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "NamedLocation.h" diff --git a/interface/src/main.cpp b/interface/src/main.cpp index f2c516792b..40e2a9ab27 100644 --- a/interface/src/main.cpp +++ b/interface/src/main.cpp @@ -1,18 +1,11 @@ -// -// Interface // -// Allows you to connect to and see/hear the shared 3D space. -// Optionally uses serialUSB connection to get gyro data for head movement. -// Optionally gets UDP stream from transmitter to animate controller/hand. -// -// Usage: The interface client first attempts to contact a domain server to -// discover the appropriate audio, voxel, and avatar servers to contact. -// Right now, the default domain server is "highfidelity.below92.com" -// You can change the domain server to use your own by editing the -// DOMAIN_HOSTNAME or DOMAIN_IP strings in the file NodeList.cpp +// main.cpp +// interface/src // +// Copyright 2013 High Fidelity, Inc. // -// Welcome Aboard! +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "Application.h" diff --git a/interface/src/renderer/AmbientOcclusionEffect.cpp b/interface/src/renderer/AmbientOcclusionEffect.cpp index a492552e7c..635e6c9bd6 100644 --- a/interface/src/renderer/AmbientOcclusionEffect.cpp +++ b/interface/src/renderer/AmbientOcclusionEffect.cpp @@ -1,9 +1,12 @@ // // AmbientOcclusionEffect.cpp -// interface +// interface/src/renderer // // Created by Andrzej Kapolka on 7/14/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL diff --git a/interface/src/renderer/FBXReader.cpp b/interface/src/renderer/FBXReader.cpp index c1e1e42abf..959c015eea 100644 --- a/interface/src/renderer/FBXReader.cpp +++ b/interface/src/renderer/FBXReader.cpp @@ -1,9 +1,12 @@ // // FBXReader.cpp -// interface +// interface/src/renderer // // Created by Andrzej Kapolka on 9/18/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/renderer/GeometryCache.cpp b/interface/src/renderer/GeometryCache.cpp index a3984b9306..7b4eef1ac1 100644 --- a/interface/src/renderer/GeometryCache.cpp +++ b/interface/src/renderer/GeometryCache.cpp @@ -1,9 +1,12 @@ // // GeometryCache.cpp -// interface +// interface/src/renderer // // Created by Andrzej Kapolka on 6/21/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/renderer/GlowEffect.cpp b/interface/src/renderer/GlowEffect.cpp index 1aea22367f..b52e8d8531 100644 --- a/interface/src/renderer/GlowEffect.cpp +++ b/interface/src/renderer/GlowEffect.cpp @@ -1,9 +1,12 @@ // // GlowEffect.cpp -// interface +// interface/src/renderer // // Created by Andrzej Kapolka on 8/7/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 36fbbe3833..819d1164c0 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -1,9 +1,12 @@ // // Model.cpp -// interface +// interface/src/renderer // // Created by Andrzej Kapolka on 10/18/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/renderer/PointShader.cpp b/interface/src/renderer/PointShader.cpp index 4191a116e3..68df69f284 100644 --- a/interface/src/renderer/PointShader.cpp +++ b/interface/src/renderer/PointShader.cpp @@ -1,9 +1,12 @@ // // PointShader.cpp -// interface +// interface/src/renderer // // Created by Brad Hefta-Gaub on 10/30/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL diff --git a/interface/src/renderer/ProgramObject.cpp b/interface/src/renderer/ProgramObject.cpp index 71d6c100f1..b88be69f07 100644 --- a/interface/src/renderer/ProgramObject.cpp +++ b/interface/src/renderer/ProgramObject.cpp @@ -1,9 +1,12 @@ // // ProgramObject.cpp -// interface +// interface/src/renderer // // Created by Andrzej Kapolka on 5/7/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "ProgramObject.h" diff --git a/interface/src/renderer/RenderUtil.cpp b/interface/src/renderer/RenderUtil.cpp index 32cf36a650..0575ceaa88 100644 --- a/interface/src/renderer/RenderUtil.cpp +++ b/interface/src/renderer/RenderUtil.cpp @@ -1,9 +1,12 @@ // // RenderUtil.cpp -// interface +// interface/src/renderer // // Created by Andrzej Kapolka on 8/15/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "InterfaceConfig.h" diff --git a/interface/src/renderer/TextureCache.cpp b/interface/src/renderer/TextureCache.cpp index c959340f6b..17146dc2bb 100644 --- a/interface/src/renderer/TextureCache.cpp +++ b/interface/src/renderer/TextureCache.cpp @@ -1,9 +1,12 @@ // // TextureCache.cpp -// interface +// interface/src/renderer // // Created by Andrzej Kapolka on 8/6/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QGLWidget, which includes an earlier version of OpenGL diff --git a/interface/src/renderer/VoxelShader.cpp b/interface/src/renderer/VoxelShader.cpp index 0377e5fe72..0982304adf 100644 --- a/interface/src/renderer/VoxelShader.cpp +++ b/interface/src/renderer/VoxelShader.cpp @@ -1,9 +1,12 @@ // // VoxelShader.cpp -// interface +// interface/src/renderer // // Created by Brad Hefta-Gaub on 9/22/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL diff --git a/interface/src/scripting/AudioDeviceScriptingInterface.cpp b/interface/src/scripting/AudioDeviceScriptingInterface.cpp index a184e8a2f6..688b0942d5 100644 --- a/interface/src/scripting/AudioDeviceScriptingInterface.cpp +++ b/interface/src/scripting/AudioDeviceScriptingInterface.cpp @@ -1,9 +1,12 @@ // // AudioDeviceScriptingInterface.cpp -// hifi +// interface/src/scripting // -// Created by Brad Hefta-Gaub on 3/23/14 -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 3/23/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "Application.h" diff --git a/interface/src/scripting/ClipboardScriptingInterface.cpp b/interface/src/scripting/ClipboardScriptingInterface.cpp index 2ddef524aa..b11c0fdbff 100644 --- a/interface/src/scripting/ClipboardScriptingInterface.cpp +++ b/interface/src/scripting/ClipboardScriptingInterface.cpp @@ -1,8 +1,11 @@ // // ClipboardScriptingInterface.cpp -// interface +// interface/src/scripting // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "Application.h" @@ -96,4 +99,4 @@ void ClipboardScriptingInterface::nudgeVoxel(float x, float y, float z, float s, s / (float)TREE_SCALE }; Application::getInstance()->nudgeVoxelsByVector(sourceVoxel, nudgeVecInTreeSpace); -} \ No newline at end of file +} diff --git a/interface/src/scripting/ControllerScriptingInterface.cpp b/interface/src/scripting/ControllerScriptingInterface.cpp index f5ab1653f5..aa14f769de 100644 --- a/interface/src/scripting/ControllerScriptingInterface.cpp +++ b/interface/src/scripting/ControllerScriptingInterface.cpp @@ -1,9 +1,12 @@ // -// ControllerScriptingInterface.h -// hifi +// ControllerScriptingInterface.cpp +// interface/src/scripting // -// Created by Brad Hefta-Gaub on 12/17/13 -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 12/17/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/scripting/MenuScriptingInterface.cpp b/interface/src/scripting/MenuScriptingInterface.cpp index 4f9003b288..11d681bfc7 100644 --- a/interface/src/scripting/MenuScriptingInterface.cpp +++ b/interface/src/scripting/MenuScriptingInterface.cpp @@ -1,9 +1,12 @@ // // MenuScriptingInterface.cpp -// hifi +// interface/src/scripting // -// Created by Brad Hefta-Gaub on 2/25/14 -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 2/25/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "Application.h" diff --git a/interface/src/scripting/SettingsScriptingInterface.cpp b/interface/src/scripting/SettingsScriptingInterface.cpp index 2a788c2776..ea9d645a94 100644 --- a/interface/src/scripting/SettingsScriptingInterface.cpp +++ b/interface/src/scripting/SettingsScriptingInterface.cpp @@ -1,9 +1,12 @@ // // SettingsScriptingInterface.cpp -// hifi +// interface/src/scripting // -// Created by Brad Hefta-Gaub on 2/25/14 -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 2/25/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "Application.h" diff --git a/interface/src/starfield/Controller.cpp b/interface/src/starfield/Controller.cpp index 0987a14dd5..b50c393f00 100755 --- a/interface/src/starfield/Controller.cpp +++ b/interface/src/starfield/Controller.cpp @@ -1,10 +1,12 @@ // -// starfield/Controller.cpp -// interface +// Controller.cpp +// interface/src/starfield // -// Created by Chris Barnard on 10/16/13 -// Portions of code based on earlier work by Tobias Schwinger. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Chris Barnard on 10/16/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifdef _WIN32 diff --git a/interface/src/starfield/Generator.cpp b/interface/src/starfield/Generator.cpp index 6065140505..15d1736e4e 100644 --- a/interface/src/starfield/Generator.cpp +++ b/interface/src/starfield/Generator.cpp @@ -1,9 +1,12 @@ // -// starfield/Generator.cpp -// interface +// Generator.cpp +// interface/src/starfield // -// Created by Chris Barnard on 10/13/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Chris Barnard on 10/13/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifdef _WIN32 diff --git a/interface/src/starfield/data/GpuVertex.cpp b/interface/src/starfield/data/GpuVertex.cpp index 85fc6f8f7e..5c1a8ea711 100755 --- a/interface/src/starfield/data/GpuVertex.cpp +++ b/interface/src/starfield/data/GpuVertex.cpp @@ -1,10 +1,12 @@ // -// starfield/data/GpuVertex.cpp -// interface +// GpuVertex.cpp +// interface/src/starfield/data // -// Created by Chris Barnard on 10/17/13. -// Based on code by Tobias Schwinger on 3/29/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Chris Barnard on 10/17/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "starfield/data/GpuVertex.h" diff --git a/interface/src/starfield/data/InputVertex.cpp b/interface/src/starfield/data/InputVertex.cpp index 28bffb0ec0..ffb7e725fc 100755 --- a/interface/src/starfield/data/InputVertex.cpp +++ b/interface/src/starfield/data/InputVertex.cpp @@ -1,10 +1,12 @@ // -// starfield/data/InputVertex.cpp -// interface +// InputVertex.cpp +// interface/src/starfield/data // -// Created by Chris Barnard on 10/17.13. -// Based on code by Tobias Schwinger 3/29/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Chris Barnard on 10/17. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "starfield/data/InputVertex.h" diff --git a/interface/src/starfield/renderer/Renderer.cpp b/interface/src/starfield/renderer/Renderer.cpp index 356e46c468..c571cb0977 100755 --- a/interface/src/starfield/renderer/Renderer.cpp +++ b/interface/src/starfield/renderer/Renderer.cpp @@ -1,10 +1,12 @@ // -// starfield/renderer/Renderer.cpp -// interface +// Renderer.cpp +// interface/src/starfield/renderer // // Created by Chris Barnard on 10/17/13. -// Based on earlier work by Tobias Schwinger 3/22/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "starfield/renderer/Renderer.h" diff --git a/interface/src/starfield/renderer/VertexOrder.cpp b/interface/src/starfield/renderer/VertexOrder.cpp index 78f5229f90..baffb81f4e 100755 --- a/interface/src/starfield/renderer/VertexOrder.cpp +++ b/interface/src/starfield/renderer/VertexOrder.cpp @@ -1,11 +1,12 @@ // -// starfield/renderer/VertexOrder.cpp -// interface +// VertexOrder.cpp +// interface/src/starfield/renderer // -// Created by Chris Barnard on 10/17/13. -// Based on code by Tobias Schwinger on 3/22/13. +// Created by Chris Barnard on 10/17/13. +// Copyright 2013 High Fidelity, Inc. // -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "starfield/renderer/VertexOrder.h" @@ -15,4 +16,4 @@ using namespace starfield; bool VertexOrder::bit(InputVertex const& vertex, state_type const& state) const { unsigned key = _tiling.getTileIndex(vertex.getAzimuth(), vertex.getAltitude()); return base::bit(key, state); -} \ No newline at end of file +} diff --git a/interface/src/ui/BandwidthDialog.cpp b/interface/src/ui/BandwidthDialog.cpp index 8cefc9cf93..3e6d9d876b 100644 --- a/interface/src/ui/BandwidthDialog.cpp +++ b/interface/src/ui/BandwidthDialog.cpp @@ -1,9 +1,12 @@ // -// BandwidthDialog.h -// interface +// BandwidthDialog.cpp +// interface/src/ui // // Created by Tobias Schwinger on 6/21/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/ui/BandwidthMeter.cpp b/interface/src/ui/BandwidthMeter.cpp index 962e8a857b..3ed66c53e1 100644 --- a/interface/src/ui/BandwidthMeter.cpp +++ b/interface/src/ui/BandwidthMeter.cpp @@ -1,9 +1,12 @@ // -// BandwidthMeter.h -// interface +// BandwidthMeter.cpp +// interface/src/ui // // Created by Tobias Schwinger on 6/20/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/ui/ChatWindow.cpp b/interface/src/ui/ChatWindow.cpp index b079b56584..0060cb839c 100644 --- a/interface/src/ui/ChatWindow.cpp +++ b/interface/src/ui/ChatWindow.cpp @@ -1,9 +1,12 @@ // // ChatWindow.cpp -// interface +// interface/src/ui // // Created by Dimitar Dobrev on 3/6/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/ui/ImportDialog.cpp b/interface/src/ui/ImportDialog.cpp index 2741fada0a..67b89773fb 100644 --- a/interface/src/ui/ImportDialog.cpp +++ b/interface/src/ui/ImportDialog.cpp @@ -1,9 +1,12 @@ // // ImportDialog.cpp -// hifi +// interface/src/ui // // Created by Clement Brisset on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "InterfaceConfig.h" diff --git a/interface/src/ui/InfoView.cpp b/interface/src/ui/InfoView.cpp index 8ed4da254c..06de3fdf2e 100644 --- a/interface/src/ui/InfoView.cpp +++ b/interface/src/ui/InfoView.cpp @@ -1,9 +1,12 @@ // -// InfoView -// hifi +// InfoView.cpp +// interface/src/ui // // Created by Stojce Slavkovski on 9/7/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "InfoView.h" diff --git a/interface/src/ui/LodToolsDialog.cpp b/interface/src/ui/LodToolsDialog.cpp index 564669757c..35d5eada41 100644 --- a/interface/src/ui/LodToolsDialog.cpp +++ b/interface/src/ui/LodToolsDialog.cpp @@ -1,9 +1,12 @@ // // LodToolsDialog.cpp -// interface +// interface/src/ui // // Created by Brad Hefta-Gaub on 7/19/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/ui/LogDialog.cpp b/interface/src/ui/LogDialog.cpp index d219c08698..5db704b230 100644 --- a/interface/src/ui/LogDialog.cpp +++ b/interface/src/ui/LogDialog.cpp @@ -1,9 +1,12 @@ // // LogDialog.cpp -// interface +// interface/src/ui // // Created by Stojce Slavkovski on 12/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "InterfaceConfig.h" diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index 73a2476aa4..a42c84470b 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -1,9 +1,12 @@ // // MetavoxelEditor.cpp -// interface +// interface/src/ui // // Created by Andrzej Kapolka on 1/21/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL diff --git a/interface/src/ui/ModelsBrowser.cpp b/interface/src/ui/ModelsBrowser.cpp index 616aba3881..6c421863c8 100644 --- a/interface/src/ui/ModelsBrowser.cpp +++ b/interface/src/ui/ModelsBrowser.cpp @@ -1,9 +1,12 @@ // // ModelsBrowser.cpp -// hifi +// interface/src/ui // // Created by Clement on 3/17/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/ui/OctreeStatsDialog.cpp b/interface/src/ui/OctreeStatsDialog.cpp index daf5a68587..c56aa0b6ab 100644 --- a/interface/src/ui/OctreeStatsDialog.cpp +++ b/interface/src/ui/OctreeStatsDialog.cpp @@ -1,9 +1,12 @@ // // OctreeStatsDialog.cpp -// interface +// interface/src/ui // // Created by Brad Hefta-Gaub on 7/19/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/ui/Oscilloscope.cpp b/interface/src/ui/Oscilloscope.cpp index a47586b436..af10539c43 100644 --- a/interface/src/ui/Oscilloscope.cpp +++ b/interface/src/ui/Oscilloscope.cpp @@ -1,9 +1,12 @@ // // Oscilloscope.cpp -// interface +// interface/src/ui // // Created by Philip on 1/28/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/ui/RearMirrorTools.cpp b/interface/src/ui/RearMirrorTools.cpp index c86770d4f0..e52d59e81a 100644 --- a/interface/src/ui/RearMirrorTools.cpp +++ b/interface/src/ui/RearMirrorTools.cpp @@ -1,9 +1,12 @@ // // RearMirrorTools.cpp -// interface +// interface/src/ui // -// Created by stojce on 23.10.2013. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by stojce on 23. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "InterfaceConfig.h" diff --git a/interface/src/ui/RunningScriptsWidget.cpp b/interface/src/ui/RunningScriptsWidget.cpp index dcb9210d56..dc9ae7c5f8 100644 --- a/interface/src/ui/RunningScriptsWidget.cpp +++ b/interface/src/ui/RunningScriptsWidget.cpp @@ -1,9 +1,12 @@ // -// RunningScripts.cpp -// interface +// RunningScriptsWidget.cpp +// interface/src/ui // // Created by Mohammed Nafees on 03/28/2014. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "ui_runningScriptsWidget.h" diff --git a/interface/src/ui/Snapshot.cpp b/interface/src/ui/Snapshot.cpp index a29a96f009..5360924e63 100644 --- a/interface/src/ui/Snapshot.cpp +++ b/interface/src/ui/Snapshot.cpp @@ -1,9 +1,12 @@ // // Snapshot.cpp -// hifi +// interface/src/ui // // Created by Stojce Slavkovski on 1/26/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp index dbcbb3d8bb..0c4d8a35fd 100644 --- a/interface/src/ui/Stats.cpp +++ b/interface/src/ui/Stats.cpp @@ -1,9 +1,12 @@ // // Stats.cpp -// interface +// interface/src/ui // // Created by Lucas Crisman on 22/03/14. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/ui/TextRenderer.cpp b/interface/src/ui/TextRenderer.cpp index 06c657e96e..2743e3e572 100644 --- a/interface/src/ui/TextRenderer.cpp +++ b/interface/src/ui/TextRenderer.cpp @@ -1,9 +1,12 @@ // // TextRenderer.cpp -// interface +// interface/src/ui // // Created by Andrzej Kapolka on 4/24/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/ui/UpdateDialog.cpp b/interface/src/ui/UpdateDialog.cpp index 9919cd0a7b..ace022b683 100644 --- a/interface/src/ui/UpdateDialog.cpp +++ b/interface/src/ui/UpdateDialog.cpp @@ -1,9 +1,11 @@ // // UpdateDialog.cpp -// interface +// interface/src/ui // -// Created by Leonardo Murillo on 1/8/14. -// Copyright (c) 2013, 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "Application.h" // HACK ATTACK WARNING: for windows build to work, we need this ahead of QtGui @@ -49,4 +51,4 @@ void UpdateDialog::handleDownload() { void UpdateDialog::handleSkip() { Application::getInstance()->skipVersion(_latestVersion); this->close(); -} \ No newline at end of file +} diff --git a/interface/src/ui/overlays/Base3DOverlay.cpp b/interface/src/ui/overlays/Base3DOverlay.cpp index bcd2ca1cd2..3500f400ab 100644 --- a/interface/src/ui/overlays/Base3DOverlay.cpp +++ b/interface/src/ui/overlays/Base3DOverlay.cpp @@ -1,8 +1,11 @@ // // Base3DOverlay.cpp -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QGLWidget, which includes an earlier version of OpenGL diff --git a/interface/src/ui/overlays/Cube3DOverlay.cpp b/interface/src/ui/overlays/Cube3DOverlay.cpp index 992a18e451..ab9418206f 100644 --- a/interface/src/ui/overlays/Cube3DOverlay.cpp +++ b/interface/src/ui/overlays/Cube3DOverlay.cpp @@ -1,8 +1,11 @@ // // Cube3DOverlay.cpp -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QGLWidget, which includes an earlier version of OpenGL diff --git a/interface/src/ui/overlays/ImageOverlay.cpp b/interface/src/ui/overlays/ImageOverlay.cpp index ac5c8ecefa..aa4766488a 100644 --- a/interface/src/ui/overlays/ImageOverlay.cpp +++ b/interface/src/ui/overlays/ImageOverlay.cpp @@ -1,8 +1,11 @@ // // ImageOverlay.cpp -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QGLWidget, which includes an earlier version of OpenGL diff --git a/interface/src/ui/overlays/Line3DOverlay.cpp b/interface/src/ui/overlays/Line3DOverlay.cpp index c357233329..6c036a898d 100644 --- a/interface/src/ui/overlays/Line3DOverlay.cpp +++ b/interface/src/ui/overlays/Line3DOverlay.cpp @@ -1,8 +1,11 @@ // // Line3DOverlay.cpp -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QGLWidget, which includes an earlier version of OpenGL diff --git a/interface/src/ui/overlays/LocalVoxelsOverlay.cpp b/interface/src/ui/overlays/LocalVoxelsOverlay.cpp index e605f8879d..93736ddccb 100644 --- a/interface/src/ui/overlays/LocalVoxelsOverlay.cpp +++ b/interface/src/ui/overlays/LocalVoxelsOverlay.cpp @@ -1,9 +1,12 @@ // // LocalVoxelsOverlay.cpp -// hifi +// interface/src/ui/overlays // // Created by Clément Brisset on 2/28/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QGLWidget, which includes an earlier version of OpenGL diff --git a/interface/src/ui/overlays/Overlay.cpp b/interface/src/ui/overlays/Overlay.cpp index 40da2253f4..3b38addb76 100644 --- a/interface/src/ui/overlays/Overlay.cpp +++ b/interface/src/ui/overlays/Overlay.cpp @@ -1,8 +1,11 @@ // // Overlay.cpp -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QGLWidget, which includes an earlier version of OpenGL diff --git a/interface/src/ui/overlays/Overlay2D.cpp b/interface/src/ui/overlays/Overlay2D.cpp index 0c459811c4..0bdb8790cc 100644 --- a/interface/src/ui/overlays/Overlay2D.cpp +++ b/interface/src/ui/overlays/Overlay2D.cpp @@ -1,8 +1,11 @@ // // Overlay2D.cpp -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QGLWidget, which includes an earlier version of OpenGL diff --git a/interface/src/ui/overlays/Overlays.cpp b/interface/src/ui/overlays/Overlays.cpp index 0c9415fa73..4eb4f030ac 100644 --- a/interface/src/ui/overlays/Overlays.cpp +++ b/interface/src/ui/overlays/Overlays.cpp @@ -1,8 +1,11 @@ // // Overlays.cpp -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/interface/src/ui/overlays/Sphere3DOverlay.cpp b/interface/src/ui/overlays/Sphere3DOverlay.cpp index 7fded5bedb..e5f31fa1be 100644 --- a/interface/src/ui/overlays/Sphere3DOverlay.cpp +++ b/interface/src/ui/overlays/Sphere3DOverlay.cpp @@ -1,8 +1,11 @@ // // Sphere3DOverlay.cpp -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QGLWidget, which includes an earlier version of OpenGL diff --git a/interface/src/ui/overlays/TextOverlay.cpp b/interface/src/ui/overlays/TextOverlay.cpp index 1a6edb3ea2..e26c772b06 100644 --- a/interface/src/ui/overlays/TextOverlay.cpp +++ b/interface/src/ui/overlays/TextOverlay.cpp @@ -1,8 +1,11 @@ // // TextOverlay.cpp -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QGLWidget, which includes an earlier version of OpenGL diff --git a/interface/src/ui/overlays/Volume3DOverlay.cpp b/interface/src/ui/overlays/Volume3DOverlay.cpp index dbc1582cc5..ee780d8329 100644 --- a/interface/src/ui/overlays/Volume3DOverlay.cpp +++ b/interface/src/ui/overlays/Volume3DOverlay.cpp @@ -1,8 +1,11 @@ // // Volume3DOverlay.cpp -// interface +// interface/src/ui/overlays // -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QGLWidget, which includes an earlier version of OpenGL diff --git a/interface/src/voxels/PrimitiveRenderer.cpp b/interface/src/voxels/PrimitiveRenderer.cpp index 7f3607e363..a212245289 100644 --- a/interface/src/voxels/PrimitiveRenderer.cpp +++ b/interface/src/voxels/PrimitiveRenderer.cpp @@ -1,10 +1,12 @@ -/// -/// @file PrimitiveRenderer.cpp -/// A geometric primitive renderer. -/// -/// @author: Norman Crafts -/// @copyright 2014, High Fidelity, Inc. All rights reserved. -/// +// +// PrimitiveRenderer.cpp +// interface/src/voxels +// +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// #include @@ -737,4 +739,4 @@ unsigned long PrimitiveRenderer::vGetMemoryUsage() { unsigned long PrimitiveRenderer::vGetMemoryUsageGPU() { return _gpuMemoryUsage; -} \ No newline at end of file +} diff --git a/interface/src/voxels/VoxelFade.cpp b/interface/src/voxels/VoxelFade.cpp index 8ce68c9724..c720717d7c 100644 --- a/interface/src/voxels/VoxelFade.cpp +++ b/interface/src/voxels/VoxelFade.cpp @@ -1,9 +1,12 @@ // // VoxelFade.cpp -// interface +// interface/src/voxels // // Created by Brad Hefta-Gaub on 8/6/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "InterfaceConfig.h" diff --git a/interface/src/voxels/VoxelHideShowThread.cpp b/interface/src/voxels/VoxelHideShowThread.cpp index d7a25b4b6d..089da0d1da 100644 --- a/interface/src/voxels/VoxelHideShowThread.cpp +++ b/interface/src/voxels/VoxelHideShowThread.cpp @@ -1,11 +1,12 @@ // // VoxelHideShowThread.cpp -// interface +// interface/src/voxels // -// Created by Brad Hefta-Gaub on 12/1/13 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 12/1/13. +// Copyright 2013 High Fidelity, Inc. // -// Threaded or non-threaded interface thread for hiding and showing voxels in the local tree. +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/voxels/VoxelImporter.cpp b/interface/src/voxels/VoxelImporter.cpp index d3c1b259ae..f7d5562c06 100644 --- a/interface/src/voxels/VoxelImporter.cpp +++ b/interface/src/voxels/VoxelImporter.cpp @@ -1,9 +1,12 @@ // // VoxelImporter.cpp -// hifi +// interface/src/voxels // // Created by Clement Brisset on 8/9/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QGLWidget, which includes an earlier version of OpenGL diff --git a/interface/src/voxels/VoxelPacketProcessor.cpp b/interface/src/voxels/VoxelPacketProcessor.cpp index 142285664e..d9d001b644 100644 --- a/interface/src/voxels/VoxelPacketProcessor.cpp +++ b/interface/src/voxels/VoxelPacketProcessor.cpp @@ -1,11 +1,12 @@ // // VoxelPacketProcessor.cpp -// interface +// interface/src/voxels // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Threaded or non-threaded voxel packet receiver for the Application +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/voxels/VoxelSystem.cpp b/interface/src/voxels/VoxelSystem.cpp index bb907c8a9a..692f299bdc 100644 --- a/interface/src/voxels/VoxelSystem.cpp +++ b/interface/src/voxels/VoxelSystem.cpp @@ -1,8 +1,12 @@ // // VoxelSystem.cpp +// interface/src/voxels // // Created by Philip on 12/31/12. -// Copyright (c) 2012 High Fidelity, Inc. All rights reserved. +// Copyright 2012 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 // diff --git a/libraries/audio/src/AudioInjector.cpp b/libraries/audio/src/AudioInjector.cpp index 7f0e5c7f1a..6370e51826 100644 --- a/libraries/audio/src/AudioInjector.cpp +++ b/libraries/audio/src/AudioInjector.cpp @@ -1,9 +1,12 @@ // // AudioInjector.cpp -// hifi +// libraries/audio/src // // Created by Stephen Birarda on 1/2/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/audio/src/AudioInjectorOptions.cpp b/libraries/audio/src/AudioInjectorOptions.cpp index 30e8c3e490..cd6b08f6c7 100644 --- a/libraries/audio/src/AudioInjectorOptions.cpp +++ b/libraries/audio/src/AudioInjectorOptions.cpp @@ -1,9 +1,12 @@ // // AudioInjectorOptions.cpp -// hifi +// libraries/audio/src // // Created by Stephen Birarda on 1/2/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "AudioInjectorOptions.h" @@ -23,4 +26,4 @@ AudioInjectorOptions::AudioInjectorOptions(const AudioInjectorOptions& other) { _volume = other._volume; _orientation = other._orientation; _loopbackAudioInterface = other._loopbackAudioInterface; -} \ No newline at end of file +} diff --git a/libraries/audio/src/AudioRingBuffer.cpp b/libraries/audio/src/AudioRingBuffer.cpp index 376b60ffa1..603a8c89ac 100644 --- a/libraries/audio/src/AudioRingBuffer.cpp +++ b/libraries/audio/src/AudioRingBuffer.cpp @@ -1,9 +1,12 @@ // // AudioRingBuffer.cpp -// interface +// libraries/audio/src // // Created by Stephen Birarda on 2/1/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/audio/src/AudioScriptingInterface.cpp b/libraries/audio/src/AudioScriptingInterface.cpp index 1fe2c19922..0d76a42757 100644 --- a/libraries/audio/src/AudioScriptingInterface.cpp +++ b/libraries/audio/src/AudioScriptingInterface.cpp @@ -1,9 +1,12 @@ // // AudioScriptingInterface.cpp -// hifi +// libraries/audio/src // // Created by Stephen Birarda on 1/2/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "AudioScriptingInterface.h" diff --git a/libraries/audio/src/InjectedAudioRingBuffer.cpp b/libraries/audio/src/InjectedAudioRingBuffer.cpp index f8205a846f..2658b4c336 100644 --- a/libraries/audio/src/InjectedAudioRingBuffer.cpp +++ b/libraries/audio/src/InjectedAudioRingBuffer.cpp @@ -1,9 +1,12 @@ // // InjectedAudioRingBuffer.cpp -// hifi +// libraries/audio/src // // Created by Stephen Birarda on 6/5/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/audio/src/MixedAudioRingBuffer.cpp b/libraries/audio/src/MixedAudioRingBuffer.cpp index 0ffab23519..c975d7b68e 100644 --- a/libraries/audio/src/MixedAudioRingBuffer.cpp +++ b/libraries/audio/src/MixedAudioRingBuffer.cpp @@ -1,9 +1,12 @@ // // MixedAudioRingBuffer.cpp -// hifi +// libraries/audio/src // -// Created by Stephen Birarda on 2014-03-26. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Created by Stephen Birarda on 2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "MixedAudioRingBuffer.h" @@ -46,4 +49,4 @@ qint64 MixedAudioRingBuffer::readSamples(int16_t* destination, qint64 maxSamples _lastReadFrameAverageLoudness = averageLoudness; return AudioRingBuffer::readSamples(destination, maxSamples); -} \ No newline at end of file +} diff --git a/libraries/audio/src/PositionalAudioRingBuffer.cpp b/libraries/audio/src/PositionalAudioRingBuffer.cpp index 7bdedfc793..70da363267 100644 --- a/libraries/audio/src/PositionalAudioRingBuffer.cpp +++ b/libraries/audio/src/PositionalAudioRingBuffer.cpp @@ -1,9 +1,12 @@ // // PositionalAudioRingBuffer.cpp -// hifi +// libraries/audio/src // // Created by Stephen Birarda on 6/5/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/audio/src/Sound.cpp b/libraries/audio/src/Sound.cpp index 91a47b7d2c..4e657f3302 100644 --- a/libraries/audio/src/Sound.cpp +++ b/libraries/audio/src/Sound.cpp @@ -1,155 +1,12 @@ // // Sound.cpp -// hifi +// libraries/audio/src // // Created by Stephen Birarda on 1/2/2014. -// Modified by Athanasios Gaitatzes to add WAVE file support. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // - -#include - -#include - -#include -#include -#include -#include -#include -#include - -#include - -#include "AudioRingBuffer.h" -#include "Sound.h" - -// procedural audio version of Sound -Sound::Sound(float volume, float frequency, float duration, float decay, QObject* parent) : - QObject(parent) -{ - static char monoAudioData[MAX_PACKET_SIZE]; - static int16_t* monoAudioSamples = (int16_t*)(monoAudioData); - - float t; - const float AUDIO_CALLBACK_MSECS = (float) NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL / (float)SAMPLE_RATE * 1000.0; - const float MAX_VOLUME = 32000.f; - const float MAX_DURATION = 2.f; - const float MIN_AUDIBLE_VOLUME = 0.001f; - const float NOISE_MAGNITUDE = 0.02f; - const int MAX_SAMPLE_VALUE = std::numeric_limits::max(); - const int MIN_SAMPLE_VALUE = std::numeric_limits::min(); - int numSamples = NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL; // we add sounds in chunks of this many samples - - int chunkStartingSample = 0; - float waveFrequency = (frequency / SAMPLE_RATE) * TWO_PI; - while (volume > 0.f) { - for (int i = 0; i < numSamples; i++) { - t = (float)chunkStartingSample + (float)i; - float sample = sinf(t * waveFrequency); - sample += ((randFloat() - 0.5f) * NOISE_MAGNITUDE); - sample *= volume * MAX_VOLUME; - - monoAudioSamples[i] = glm::clamp((int)sample, MIN_SAMPLE_VALUE, MAX_SAMPLE_VALUE); - volume *= (1.f - decay); - } - // add the monoAudioSamples to our actual output Byte Array - _byteArray.append(monoAudioData, numSamples * sizeof(int16_t)); - chunkStartingSample += numSamples; - duration = glm::clamp(duration - (AUDIO_CALLBACK_MSECS / 1000.f), 0.f, MAX_DURATION); - //qDebug() << "decaying... _duration=" << _duration; - if (duration == 0.f || (volume < MIN_AUDIBLE_VOLUME)) { - volume = 0.f; - } - } -} - -Sound::Sound(const QUrl& sampleURL, QObject* parent) : - QObject(parent) -{ - // assume we have a QApplication or QCoreApplication instance and use the - // QNetworkAccess manager to grab the raw audio file at the given URL - - QNetworkAccessManager *manager = new QNetworkAccessManager(this); - connect(manager, SIGNAL(finished(QNetworkReply*)), - this, SLOT(replyFinished(QNetworkReply*))); - - qDebug() << "Requesting audio file" << sampleURL.toDisplayString(); - manager->get(QNetworkRequest(sampleURL)); -} - -void Sound::replyFinished(QNetworkReply* reply) { - - // replace our byte array with the downloaded data - QByteArray rawAudioByteArray = reply->readAll(); - - // foreach(QByteArray b, reply->rawHeaderList()) - // qDebug() << b.constData() << ": " << reply->rawHeader(b).constData(); - - if (reply->hasRawHeader("Content-Type")) { - - QByteArray headerContentType = reply->rawHeader("Content-Type"); - - // WAV audio file encountered - if (headerContentType == "audio/x-wav" - || headerContentType == "audio/wav" - || headerContentType == "audio/wave") { - - QByteArray outputAudioByteArray; - - interpretAsWav(rawAudioByteArray, outputAudioByteArray); - downSample(outputAudioByteArray); - } else { - // Process as RAW file - downSample(rawAudioByteArray); - } - } else { - qDebug() << "Network reply without 'Content-Type'."; - } -} - -void Sound::downSample(const QByteArray& rawAudioByteArray) { - - // assume that this was a RAW file and is now an array of samples that are - // signed, 16-bit, 48Khz, mono - - // we want to convert it to the format that the audio-mixer wants - // which is signed, 16-bit, 24Khz, mono - - _byteArray.resize(rawAudioByteArray.size() / 2); - - int numSourceSamples = rawAudioByteArray.size() / sizeof(int16_t); - int16_t* sourceSamples = (int16_t*) rawAudioByteArray.data(); - int16_t* destinationSamples = (int16_t*) _byteArray.data(); - - for (int i = 1; i < numSourceSamples; i += 2) { - if (i + 1 >= numSourceSamples) { - destinationSamples[(i - 1) / 2] = (sourceSamples[i - 1] / 2) + (sourceSamples[i] / 2); - } else { - destinationSamples[(i - 1) / 2] = (sourceSamples[i - 1] / 4) + (sourceSamples[i] / 2) + (sourceSamples[i + 1] / 4); - } - } -} - -// -// Format description from https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ -// -// The header for a WAV file looks like this: -// Positions Sample Value Description -// 00-03 "RIFF" Marks the file as a riff file. Characters are each 1 byte long. -// 04-07 File size (int) Size of the overall file - 8 bytes, in bytes (32-bit integer). -// 08-11 "WAVE" File Type Header. For our purposes, it always equals "WAVE". -// 12-15 "fmt " Format chunk marker. -// 16-19 16 Length of format data as listed above -// 20-21 1 Type of format: (1=PCM, 257=Mu-Law, 258=A-Law, 259=ADPCM) - 2 byte integer -// 22-23 2 Number of Channels - 2 byte integer -// 24-27 44100 Sample Rate - 32 byte integer. Sample Rate = Number of Samples per second, or Hertz. -// 28-31 176400 (Sample Rate * BitsPerSample * Channels) / 8. -// 32-33 4 (BitsPerSample * Channels) / 8 - 8 bit mono2 - 8 bit stereo/16 bit mono4 - 16 bit stereo -// 34-35 16 Bits per sample -// 36-39 "data" Chunk header. Marks the beginning of the data section. -// 40-43 File size (int) Size of the data section. -// 44-?? Actual sound data -// Sample values are given above for a 16-bit stereo source. +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // struct chunk diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index e84636b5a4..606df649a4 100644 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -1,9 +1,12 @@ // // AvatarData.cpp -// hifi +// libraries/avatars/src // // Created by Stephen Birarda on 4/9/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/avatars/src/AvatarHashMap.cpp b/libraries/avatars/src/AvatarHashMap.cpp index 82485691c5..27dc1bf0bb 100644 --- a/libraries/avatars/src/AvatarHashMap.cpp +++ b/libraries/avatars/src/AvatarHashMap.cpp @@ -1,9 +1,12 @@ // // AvatarHashMap.cpp -// hifi +// libraries/avatars/src // // Created by AndrewMeadows on 1/28/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "AvatarHashMap.h" diff --git a/libraries/avatars/src/HandData.cpp b/libraries/avatars/src/HandData.cpp index 201d17d3f5..c2e3b51cb3 100644 --- a/libraries/avatars/src/HandData.cpp +++ b/libraries/avatars/src/HandData.cpp @@ -1,9 +1,12 @@ // // HandData.cpp -// hifi +// libraries/avatars/src // // Created by Stephen Birarda on 5/20/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/avatars/src/HeadData.cpp b/libraries/avatars/src/HeadData.cpp index e74ac043fb..c691a2c28a 100644 --- a/libraries/avatars/src/HeadData.cpp +++ b/libraries/avatars/src/HeadData.cpp @@ -1,9 +1,12 @@ // // HeadData.cpp -// hifi +// libraries/avatars/src // // Created by Stephen Birarda on 5/20/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/embedded-webserver/src/HTTPConnection.cpp b/libraries/embedded-webserver/src/HTTPConnection.cpp index 8fc0a25dca..276b4e7f64 100755 --- a/libraries/embedded-webserver/src/HTTPConnection.cpp +++ b/libraries/embedded-webserver/src/HTTPConnection.cpp @@ -1,9 +1,12 @@ // // HTTPConnection.cpp -// hifi +// libraries/embedded-webserver/src // // Created by Stephen Birarda on 1/16/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/embedded-webserver/src/HTTPManager.cpp b/libraries/embedded-webserver/src/HTTPManager.cpp index d106b6df59..1fc859014a 100755 --- a/libraries/embedded-webserver/src/HTTPManager.cpp +++ b/libraries/embedded-webserver/src/HTTPManager.cpp @@ -1,9 +1,12 @@ // // HTTPManager.cpp -// hifi +// libraries/embedded-webserver/src // // Created by Stephen Birarda on 1/16/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/metavoxels/src/AttributeRegistry.cpp b/libraries/metavoxels/src/AttributeRegistry.cpp index 8914a9e3c9..e7a7f41850 100644 --- a/libraries/metavoxels/src/AttributeRegistry.cpp +++ b/libraries/metavoxels/src/AttributeRegistry.cpp @@ -1,9 +1,12 @@ // // AttributeRegistry.cpp -// metavoxels +// libraries/metavoxels/src // // Created by Andrzej Kapolka on 12/6/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/metavoxels/src/Bitstream.cpp b/libraries/metavoxels/src/Bitstream.cpp index 3f3d6e5423..ad929e533c 100644 --- a/libraries/metavoxels/src/Bitstream.cpp +++ b/libraries/metavoxels/src/Bitstream.cpp @@ -1,9 +1,12 @@ // // Bitstream.cpp -// metavoxels +// libraries/metavoxels/src // // Created by Andrzej Kapolka on 12/2/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/metavoxels/src/DatagramSequencer.cpp b/libraries/metavoxels/src/DatagramSequencer.cpp index 5c605dc0f4..9fadef8afc 100644 --- a/libraries/metavoxels/src/DatagramSequencer.cpp +++ b/libraries/metavoxels/src/DatagramSequencer.cpp @@ -1,9 +1,12 @@ // // DatagramSequencer.cpp -// metavoxels +// libraries/metavoxels/src // // Created by Andrzej Kapolka on 12/20/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/metavoxels/src/MetavoxelData.cpp b/libraries/metavoxels/src/MetavoxelData.cpp index 6ae847cea3..0d52fc5ed6 100644 --- a/libraries/metavoxels/src/MetavoxelData.cpp +++ b/libraries/metavoxels/src/MetavoxelData.cpp @@ -1,9 +1,12 @@ // // MetavoxelData.cpp -// metavoxels +// libraries/metavoxels/src // // Created by Andrzej Kapolka on 12/6/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/metavoxels/src/MetavoxelMessages.cpp b/libraries/metavoxels/src/MetavoxelMessages.cpp index c930688cbd..dba9bc9c5c 100644 --- a/libraries/metavoxels/src/MetavoxelMessages.cpp +++ b/libraries/metavoxels/src/MetavoxelMessages.cpp @@ -1,9 +1,12 @@ // // MetavoxelMessages.cpp -// metavoxels +// libraries/metavoxels/src // // Created by Andrzej Kapolka on 1/24/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "MetavoxelMessages.h" diff --git a/libraries/metavoxels/src/MetavoxelUtil.cpp b/libraries/metavoxels/src/MetavoxelUtil.cpp index 2ec1c3cb57..f2f434b24d 100644 --- a/libraries/metavoxels/src/MetavoxelUtil.cpp +++ b/libraries/metavoxels/src/MetavoxelUtil.cpp @@ -1,9 +1,12 @@ // // MetavoxelUtil.cpp -// metavoxels +// libraries/metavoxels/src // // Created by Andrzej Kapolka on 12/30/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/metavoxels/src/ScriptCache.cpp b/libraries/metavoxels/src/ScriptCache.cpp index cabf075563..dd090613b7 100644 --- a/libraries/metavoxels/src/ScriptCache.cpp +++ b/libraries/metavoxels/src/ScriptCache.cpp @@ -1,9 +1,12 @@ // // ScriptCache.cpp -// metavoxels +// libraries/metavoxels/src // // Created by Andrzej Kapolka on 2/4/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/metavoxels/src/SharedObject.cpp b/libraries/metavoxels/src/SharedObject.cpp index 64ea48e016..b578d70959 100644 --- a/libraries/metavoxels/src/SharedObject.cpp +++ b/libraries/metavoxels/src/SharedObject.cpp @@ -1,9 +1,12 @@ // // SharedObject.cpp -// metavoxels +// libraries/metavoxels/src // // Created by Andrzej Kapolka on 2/5/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/octree/src/AABox.cpp b/libraries/octree/src/AABox.cpp index 97fd706c21..51b31d4466 100644 --- a/libraries/octree/src/AABox.cpp +++ b/libraries/octree/src/AABox.cpp @@ -1,11 +1,12 @@ // -// AABox.h - Axis Aligned Boxes -// hifi +// AABox.cpp +// libraries/octree/src // -// Added by Brad Hefta-Gaub on 04/11/13. -// Originally from lighthouse3d. Modified to utilize glm::vec3 and clean up to our coding standards +// Created by Brad Hefta-Gaub on 04/11/13. +// Copyright 2013 High Fidelity, Inc. // -// Simple axis aligned box class. +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "SharedUtil.h" diff --git a/libraries/octree/src/CoverageMap.cpp b/libraries/octree/src/CoverageMap.cpp index a7717b8107..88d2292812 100644 --- a/libraries/octree/src/CoverageMap.cpp +++ b/libraries/octree/src/CoverageMap.cpp @@ -1,44 +1,12 @@ // -// CoverageMap.cpp - -// hifi +// CoverageMap.cpp +// libraries/octree/src // -// Added by Brad Hefta-Gaub on 06/11/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 06/11/13. +// Copyright 2013 High Fidelity, Inc. // - -#include - -#include - -#include - -#include "CoverageMap.h" - -int CoverageMap::_mapCount = 0; -int CoverageMap::_checkMapRootCalls = 0; -int CoverageMap::_notAllInView = 0; -bool CoverageMap::wantDebugging = false; - -const int MAX_POLYGONS_PER_REGION = 50; - -const BoundingBox CoverageMap::ROOT_BOUNDING_BOX = BoundingBox(glm::vec2(-1.f,-1.f), glm::vec2(2.f,2.f)); - -// Coverage Map's polygon coordinates are from -1 to 1 in the following mapping to screen space. -// -// (0,0) (windowWidth, 0) -// -1,1 1,1 -// +-----------------------+ -// | | | -// | | | -// | -1,0 | | -// |-----------+-----------| -// | 0,0 | -// | | | -// | | | -// | | | -// +-----------------------+ -// -1,-1 1,-1 -// (0,windowHeight) (windowWidth,windowHeight) +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // Choosing a minimum sized polygon. Since we know a typical window is approximately 1500 pixels wide diff --git a/libraries/octree/src/CoverageMapV2.cpp b/libraries/octree/src/CoverageMapV2.cpp index afb341fcba..6535066eed 100644 --- a/libraries/octree/src/CoverageMapV2.cpp +++ b/libraries/octree/src/CoverageMapV2.cpp @@ -1,43 +1,12 @@ // -// CoverageMapV2.cpp - -// hifi +// CoverageMapV2.cpp +// libraries/octree/src // -// Added by Brad Hefta-Gaub on 06/11/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 06/11/13. +// Copyright 2013 High Fidelity, Inc. // - -#include -#include - -#include - -#include - -#include "CoverageMapV2.h" - -int CoverageMapV2::_mapCount = 0; -int CoverageMapV2::_checkMapRootCalls = 0; -int CoverageMapV2::_notAllInView = 0; -bool CoverageMapV2::wantDebugging = false; - -const BoundingBox CoverageMapV2::ROOT_BOUNDING_BOX = BoundingBox(glm::vec2(-1.f,-1.f), glm::vec2(2.f,2.f)); - -// Coverage Map's polygon coordinates are from -1 to 1 in the following mapping to screen space. -// -// (0,0) (windowWidth, 0) -// -1,1 1,1 -// +-----------------------+ -// | | | -// | | | -// | -1,0 | | -// |-----------+-----------| -// | 0,0 | -// | | | -// | | | -// | | | -// +-----------------------+ -// -1,-1 1,-1 -// (0,windowHeight) (windowWidth,windowHeight) +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // Choosing a minimum sized polygon. Since we know a typical window is approximately 1500 pixels wide @@ -245,4 +214,4 @@ void CoverageMapV2::recurseMap(const OctreeProjectedPolygon* polygon, bool store } // normal exit case... return... -} \ No newline at end of file +} diff --git a/libraries/octree/src/JurisdictionListener.cpp b/libraries/octree/src/JurisdictionListener.cpp index c280b48c99..453ff10a42 100644 --- a/libraries/octree/src/JurisdictionListener.cpp +++ b/libraries/octree/src/JurisdictionListener.cpp @@ -1,11 +1,12 @@ // // JurisdictionListener.cpp -// shared +// libraries/octree/src // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Threaded or non-threaded jurisdiction Sender for the Application +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/octree/src/JurisdictionMap.cpp b/libraries/octree/src/JurisdictionMap.cpp index 0271c77012..747a05e90a 100644 --- a/libraries/octree/src/JurisdictionMap.cpp +++ b/libraries/octree/src/JurisdictionMap.cpp @@ -1,9 +1,12 @@ // // JurisdictionMap.cpp -// hifi +// libraries/octree/src // // Created by Brad Hefta-Gaub on 8/1/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/octree/src/JurisdictionSender.cpp b/libraries/octree/src/JurisdictionSender.cpp index 1d26e4a53a..c151999305 100644 --- a/libraries/octree/src/JurisdictionSender.cpp +++ b/libraries/octree/src/JurisdictionSender.cpp @@ -1,11 +1,12 @@ // // JurisdictionSender.cpp -// shared +// libraries/octree/src // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Threaded or non-threaded jurisdiction Sender for the Application +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/octree/src/Octree.cpp b/libraries/octree/src/Octree.cpp index 58cfd9b15d..696a65b4b5 100644 --- a/libraries/octree/src/Octree.cpp +++ b/libraries/octree/src/Octree.cpp @@ -1,9 +1,12 @@ // // Octree.cpp -// hifi +// libraries/octree/src // // Created by Stephen Birarda on 3/13/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifdef _WIN32 diff --git a/libraries/octree/src/OctreeEditPacketSender.cpp b/libraries/octree/src/OctreeEditPacketSender.cpp index bb8ff9d8a0..b606dffe44 100644 --- a/libraries/octree/src/OctreeEditPacketSender.cpp +++ b/libraries/octree/src/OctreeEditPacketSender.cpp @@ -1,11 +1,12 @@ // // OctreeEditPacketSender.cpp -// interface +// libraries/octree/src // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Threaded or non-threaded packet Sender for the Application +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/octree/src/OctreeElement.cpp b/libraries/octree/src/OctreeElement.cpp index 7697338a28..e21148df5e 100644 --- a/libraries/octree/src/OctreeElement.cpp +++ b/libraries/octree/src/OctreeElement.cpp @@ -1,9 +1,12 @@ // // OctreeElement.cpp -// hifi +// libraries/octree/src // // Created by Stephen Birarda on 3/13/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/octree/src/OctreeElementBag.cpp b/libraries/octree/src/OctreeElementBag.cpp index 3ecdfaf2e3..f929980a75 100644 --- a/libraries/octree/src/OctreeElementBag.cpp +++ b/libraries/octree/src/OctreeElementBag.cpp @@ -1,9 +1,12 @@ // // OctreeElementBag.cpp -// hifi +// libraries/octree/src // -// Created by Brad Hefta-Gaub on 4/25/2013 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 4/25/2013. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "OctreeElementBag.h" diff --git a/libraries/octree/src/OctreeHeadlessViewer.cpp b/libraries/octree/src/OctreeHeadlessViewer.cpp index 5d2ce2d287..b25cb4ff8a 100644 --- a/libraries/octree/src/OctreeHeadlessViewer.cpp +++ b/libraries/octree/src/OctreeHeadlessViewer.cpp @@ -1,10 +1,12 @@ // // OctreeHeadlessViewer.cpp -// hifi +// libraries/octree/src // -// Created by Brad Hefta-Gaub on 2/26/14 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 2/26/14. +// Copyright 2014 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/octree/src/OctreePacketData.cpp b/libraries/octree/src/OctreePacketData.cpp index 5bd4fdce49..2edf560de6 100644 --- a/libraries/octree/src/OctreePacketData.cpp +++ b/libraries/octree/src/OctreePacketData.cpp @@ -1,9 +1,12 @@ // // OctreePacketData.cpp -// hifi +// libraries/octree/src // // Created by Brad Hefta-Gaub on 11/19/2013. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/octree/src/OctreePersistThread.cpp b/libraries/octree/src/OctreePersistThread.cpp index 29715f9d90..7613e2332b 100644 --- a/libraries/octree/src/OctreePersistThread.cpp +++ b/libraries/octree/src/OctreePersistThread.cpp @@ -1,11 +1,12 @@ // // OctreePersistThread.cpp -// Octree-server +// libraries/octree/src // -// Created by Brad Hefta-Gaub on 8/21/13 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 8/21/13. +// Copyright 2013 High Fidelity, Inc. // -// Threaded or non-threaded Octree persistence +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/octree/src/OctreeProjectedPolygon.cpp b/libraries/octree/src/OctreeProjectedPolygon.cpp index 6e5cea28cd..f86d598a87 100644 --- a/libraries/octree/src/OctreeProjectedPolygon.cpp +++ b/libraries/octree/src/OctreeProjectedPolygon.cpp @@ -1,8 +1,12 @@ // -// OctreeProjectedPolygon.cpp - The projected shadow (on the 2D view plane) for a voxel -// hifi +// OctreeProjectedPolygon.cpp +// libraries/octree/src // -// Added by Brad Hefta-Gaub on 06/11/13. +// Created by Brad Hefta-Gaub on 06/11/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/octree/src/OctreeQuery.cpp b/libraries/octree/src/OctreeQuery.cpp index 51e235c4e2..687dd18037 100644 --- a/libraries/octree/src/OctreeQuery.cpp +++ b/libraries/octree/src/OctreeQuery.cpp @@ -1,9 +1,12 @@ // // OctreeQuery.cpp -// hifi +// libraries/octree/src // // Created by Brad Hefta-Gaub on 10/24/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/octree/src/OctreeRenderer.cpp b/libraries/octree/src/OctreeRenderer.cpp index 5d4543e3aa..cde1f0923d 100644 --- a/libraries/octree/src/OctreeRenderer.cpp +++ b/libraries/octree/src/OctreeRenderer.cpp @@ -1,10 +1,12 @@ // // OctreeRenderer.cpp -// hifi +// libraries/octree/src // // Created by Brad Hefta-Gaub on 12/6/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/octree/src/OctreeSceneStats.cpp b/libraries/octree/src/OctreeSceneStats.cpp index a21ab60493..ad8702adc2 100644 --- a/libraries/octree/src/OctreeSceneStats.cpp +++ b/libraries/octree/src/OctreeSceneStats.cpp @@ -1,10 +1,12 @@ // // OctreeSceneStats.cpp -// hifi +// libraries/octree/src // // Created by Brad Hefta-Gaub on 7/18/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/octree/src/OctreeScriptingInterface.cpp b/libraries/octree/src/OctreeScriptingInterface.cpp index 982496bc58..97e7f67ff5 100644 --- a/libraries/octree/src/OctreeScriptingInterface.cpp +++ b/libraries/octree/src/OctreeScriptingInterface.cpp @@ -1,9 +1,12 @@ // // OctreeScriptingInterface.cpp -// hifi +// libraries/octree/src // -// Created by Brad Hefta-Gaub on 12/6/13 -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 12/6/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/octree/src/ViewFrustum.cpp b/libraries/octree/src/ViewFrustum.cpp index fa6873b093..9b77d39fdc 100644 --- a/libraries/octree/src/ViewFrustum.cpp +++ b/libraries/octree/src/ViewFrustum.cpp @@ -1,11 +1,12 @@ // // ViewFrustum.cpp -// hifi +// libraries/octree/src // // Created by Brad Hefta-Gaub on 04/11/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Simple view frustum class. +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/particles/src/Particle.cpp b/libraries/particles/src/Particle.cpp index f4a5785bad..a36998aad4 100644 --- a/libraries/particles/src/Particle.cpp +++ b/libraries/particles/src/Particle.cpp @@ -1,10 +1,12 @@ // // Particle.cpp -// hifi +// libraries/particles/src // // Created by Brad Hefta-Gaub on 12/4/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/particles/src/ParticleCollisionSystem.cpp b/libraries/particles/src/ParticleCollisionSystem.cpp index 028cf80df9..57a339d81f 100644 --- a/libraries/particles/src/ParticleCollisionSystem.cpp +++ b/libraries/particles/src/ParticleCollisionSystem.cpp @@ -1,10 +1,12 @@ // // ParticleCollisionSystem.cpp -// hifi +// libraries/particles/src // // Created by Brad Hefta-Gaub on 12/4/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/particles/src/ParticleEditPacketSender.cpp b/libraries/particles/src/ParticleEditPacketSender.cpp index f06b19aa2d..21a910ff16 100644 --- a/libraries/particles/src/ParticleEditPacketSender.cpp +++ b/libraries/particles/src/ParticleEditPacketSender.cpp @@ -1,11 +1,12 @@ // // ParticleEditPacketSender.cpp -// interface +// libraries/particles/src // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Threaded or non-threaded voxel packet Sender for the Application +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/particles/src/ParticleTree.cpp b/libraries/particles/src/ParticleTree.cpp index 57f6a6e665..aeaf25e23c 100644 --- a/libraries/particles/src/ParticleTree.cpp +++ b/libraries/particles/src/ParticleTree.cpp @@ -1,9 +1,12 @@ // // ParticleTree.cpp -// hifi +// libraries/particles/src // // Created by Brad Hefta-Gaub on 12/4/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "ParticleTree.h" diff --git a/libraries/particles/src/ParticleTreeElement.cpp b/libraries/particles/src/ParticleTreeElement.cpp index ee916dcf2f..19353c427a 100644 --- a/libraries/particles/src/ParticleTreeElement.cpp +++ b/libraries/particles/src/ParticleTreeElement.cpp @@ -1,9 +1,12 @@ // // ParticleTreeElement.cpp -// hifi +// libraries/particles/src // // Created by Brad Hefta-Gaub on 12/4/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/particles/src/ParticleTreeHeadlessViewer.cpp b/libraries/particles/src/ParticleTreeHeadlessViewer.cpp index f5384c3fec..1c47447b1a 100644 --- a/libraries/particles/src/ParticleTreeHeadlessViewer.cpp +++ b/libraries/particles/src/ParticleTreeHeadlessViewer.cpp @@ -1,10 +1,12 @@ // // ParticleTreeHeadlessViewer.cpp -// hifi +// libraries/particles/src // -// Created by Brad Hefta-Gaub on 2/26/14 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 2/26/14. +// Copyright 2014 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "ParticleTreeHeadlessViewer.h" diff --git a/libraries/particles/src/ParticlesScriptingInterface.cpp b/libraries/particles/src/ParticlesScriptingInterface.cpp index a25dde1b9e..4adfed358e 100644 --- a/libraries/particles/src/ParticlesScriptingInterface.cpp +++ b/libraries/particles/src/ParticlesScriptingInterface.cpp @@ -1,9 +1,12 @@ // // ParticlesScriptingInterface.cpp -// hifi +// libraries/particles/src // -// Created by Brad Hefta-Gaub on 12/6/13 -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 12/6/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "ParticlesScriptingInterface.h" diff --git a/libraries/script-engine/src/EventTypes.cpp b/libraries/script-engine/src/EventTypes.cpp index d5c2d72786..e785f53c19 100644 --- a/libraries/script-engine/src/EventTypes.cpp +++ b/libraries/script-engine/src/EventTypes.cpp @@ -1,12 +1,12 @@ // // EventTypes.cpp -// hifi +// libraries/script-engine/src // // Created by Brad Hefta-Gaub on 1/28/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // -// Used to register meta-types with Qt for very various event types so that they can be exposed to our -// scripting engine +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/script-engine/src/LocalVoxels.cpp b/libraries/script-engine/src/LocalVoxels.cpp index 075dfb9e9a..1645c229d6 100644 --- a/libraries/script-engine/src/LocalVoxels.cpp +++ b/libraries/script-engine/src/LocalVoxels.cpp @@ -1,9 +1,12 @@ // // LocalVoxels.cpp -// hifi +// libraries/script-engine/src // // Created by Clément Brisset on 2/24/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "LocalVoxels.h" diff --git a/libraries/script-engine/src/MenuItemProperties.cpp b/libraries/script-engine/src/MenuItemProperties.cpp index 8c91ad8fef..c1f3e92447 100644 --- a/libraries/script-engine/src/MenuItemProperties.cpp +++ b/libraries/script-engine/src/MenuItemProperties.cpp @@ -1,12 +1,12 @@ // // MenuItemProperties.cpp -// hifi +// libraries/script-engine/src // // Created by Brad Hefta-Gaub on 1/28/14. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // -// Used to register meta-types with Qt for very various event types so that they can be exposed to our -// scripting engine +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/script-engine/src/Quat.cpp b/libraries/script-engine/src/Quat.cpp index c939811db4..4acc60e7b4 100644 --- a/libraries/script-engine/src/Quat.cpp +++ b/libraries/script-engine/src/Quat.cpp @@ -1,12 +1,12 @@ // // Quat.cpp -// hifi +// libraries/script-engine/src // -// Created by Brad Hefta-Gaub on 1/29/14 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. -// -// Scriptable Quaternion class library. +// Created by Brad Hefta-Gaub on 1/29/14. +// Copyright 2014 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index 7572638a30..9c459518ae 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -1,9 +1,12 @@ // // ScriptEngine.cpp -// hifi +// libraries/script-engine/src // // Created by Brad Hefta-Gaub on 12/14/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/script-engine/src/Vec3.cpp b/libraries/script-engine/src/Vec3.cpp index dc5dcd9773..bab529df1f 100644 --- a/libraries/script-engine/src/Vec3.cpp +++ b/libraries/script-engine/src/Vec3.cpp @@ -1,12 +1,12 @@ // // Vec3.cpp -// hifi +// libraries/script-engine/src // -// Created by Brad Hefta-Gaub on 1/29/14 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. -// -// Scriptable Vec3 class library. +// Created by Brad Hefta-Gaub on 1/29/14. +// Copyright 2014 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/AccountManager.cpp b/libraries/shared/src/AccountManager.cpp index d284640924..6c0bcb33cb 100644 --- a/libraries/shared/src/AccountManager.cpp +++ b/libraries/shared/src/AccountManager.cpp @@ -1,9 +1,12 @@ // // AccountManager.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/18/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/Assignment.cpp b/libraries/shared/src/Assignment.cpp index 992ec96a67..4d6740b400 100644 --- a/libraries/shared/src/Assignment.cpp +++ b/libraries/shared/src/Assignment.cpp @@ -1,9 +1,12 @@ // // Assignment.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 8/22/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "PacketHeaders.h" diff --git a/libraries/shared/src/CapsuleShape.cpp b/libraries/shared/src/CapsuleShape.cpp index bae5f201ca..15586c4938 100644 --- a/libraries/shared/src/CapsuleShape.cpp +++ b/libraries/shared/src/CapsuleShape.cpp @@ -1,9 +1,12 @@ // // CapsuleShape.cpp -// hifi +// libraries/shared/src // -// Created by Andrew Meadows on 2014.02.20 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrew Meadows on 2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/CollisionInfo.cpp b/libraries/shared/src/CollisionInfo.cpp index f6c0d057a1..bf986705f5 100644 --- a/libraries/shared/src/CollisionInfo.cpp +++ b/libraries/shared/src/CollisionInfo.cpp @@ -1,9 +1,12 @@ // // CollisionInfo.cpp -// hifi +// libraries/shared/src // -// Created by Andrew Meadows on 2014.02.14 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrew Meadows on 2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "CollisionInfo.h" diff --git a/libraries/shared/src/DataServerAccountInfo.cpp b/libraries/shared/src/DataServerAccountInfo.cpp index 1884517515..1c53bca30f 100644 --- a/libraries/shared/src/DataServerAccountInfo.cpp +++ b/libraries/shared/src/DataServerAccountInfo.cpp @@ -1,9 +1,12 @@ // // DataServerAccountInfo.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/18/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/DomainInfo.cpp b/libraries/shared/src/DomainInfo.cpp index bed638bf59..34498f4c50 100644 --- a/libraries/shared/src/DomainInfo.cpp +++ b/libraries/shared/src/DomainInfo.cpp @@ -1,9 +1,12 @@ // // DomainInfo.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/18/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/FileUtils.cpp b/libraries/shared/src/FileUtils.cpp index efbe1a189b..b890717a66 100644 --- a/libraries/shared/src/FileUtils.cpp +++ b/libraries/shared/src/FileUtils.cpp @@ -1,9 +1,12 @@ // // FileUtils.cpp -// hifi +// libraries/shared/src // // Created by Stojce Slavkovski on 12/23/13. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "FileUtils.h" diff --git a/libraries/shared/src/GenericThread.cpp b/libraries/shared/src/GenericThread.cpp index 59f2426bdb..4be253f045 100644 --- a/libraries/shared/src/GenericThread.cpp +++ b/libraries/shared/src/GenericThread.cpp @@ -1,11 +1,12 @@ // // GenericThread.cpp -// shared +// libraries/shared/src // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Generic Threaded or non-threaded processing class +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/GeometryUtil.cpp b/libraries/shared/src/GeometryUtil.cpp index ac8e4e97c4..d586dad90e 100644 --- a/libraries/shared/src/GeometryUtil.cpp +++ b/libraries/shared/src/GeometryUtil.cpp @@ -1,299 +1,12 @@ // // GeometryUtil.cpp -// interface +// libraries/shared/src // // Created by Andrzej Kapolka on 5/21/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. - -#include -#include - -#include "SharedUtil.h" -#include "GeometryUtil.h" - -glm::vec3 computeVectorFromPointToSegment(const glm::vec3& point, const glm::vec3& start, const glm::vec3& end) { - // compute the projection of the point vector onto the segment vector - glm::vec3 segmentVector = end - start; - float lengthSquared = glm::dot(segmentVector, segmentVector); - if (lengthSquared < EPSILON) { - return start - point; // start and end the same - } - float proj = glm::dot(point - start, segmentVector) / lengthSquared; - if (proj <= 0.0f) { // closest to the start - return start - point; - - } else if (proj >= 1.0f) { // closest to the end - return end - point; - - } else { // closest to the middle - return start + segmentVector*proj - point; - } -} - -// Computes the penetration between a point and a sphere (centered at the origin) -// if point is inside sphere: returns true and stores the result in 'penetration' -// (the vector that would move the point outside the sphere) -// otherwise returns false -bool findSpherePenetration(const glm::vec3& point, const glm::vec3& defaultDirection, float sphereRadius, - glm::vec3& penetration) { - float vectorLength = glm::length(point); - if (vectorLength < EPSILON) { - penetration = defaultDirection * sphereRadius; - return true; - } - float distance = vectorLength - sphereRadius; - if (distance < 0.0f) { - penetration = point * (-distance / vectorLength); - return true; - } - return false; -} - -bool findSpherePointPenetration(const glm::vec3& sphereCenter, float sphereRadius, - const glm::vec3& point, glm::vec3& penetration) { - return findSpherePenetration(point - sphereCenter, glm::vec3(0.0f, -1.0f, 0.0f), sphereRadius, penetration); -} - -bool findPointSpherePenetration(const glm::vec3& point, const glm::vec3& sphereCenter, - float sphereRadius, glm::vec3& penetration) { - return findSpherePenetration(sphereCenter - point, glm::vec3(0.0f, -1.0f, 0.0f), sphereRadius, penetration); -} - -bool findSphereSpherePenetration(const glm::vec3& firstCenter, float firstRadius, - const glm::vec3& secondCenter, float secondRadius, glm::vec3& penetration) { - return findSpherePointPenetration(firstCenter, firstRadius + secondRadius, secondCenter, penetration); -} - -bool findSphereSegmentPenetration(const glm::vec3& sphereCenter, float sphereRadius, - const glm::vec3& segmentStart, const glm::vec3& segmentEnd, glm::vec3& penetration) { - return findSpherePenetration(computeVectorFromPointToSegment(sphereCenter, segmentStart, segmentEnd), - glm::vec3(0.0f, -1.0f, 0.0f), sphereRadius, penetration); -} - -bool findSphereCapsulePenetration(const glm::vec3& sphereCenter, float sphereRadius, const glm::vec3& capsuleStart, - const glm::vec3& capsuleEnd, float capsuleRadius, glm::vec3& penetration) { - return findSphereSegmentPenetration(sphereCenter, sphereRadius + capsuleRadius, - capsuleStart, capsuleEnd, penetration); -} - -bool findPointCapsuleConePenetration(const glm::vec3& point, const glm::vec3& capsuleStart, - const glm::vec3& capsuleEnd, float startRadius, float endRadius, glm::vec3& penetration) { - // compute the projection of the point vector onto the segment vector - glm::vec3 segmentVector = capsuleEnd - capsuleStart; - float lengthSquared = glm::dot(segmentVector, segmentVector); - if (lengthSquared < EPSILON) { // start and end the same - return findPointSpherePenetration(point, capsuleStart, - glm::max(startRadius, endRadius), penetration); - } - float proj = glm::dot(point - capsuleStart, segmentVector) / lengthSquared; - if (proj <= 0.0f) { // closest to the start - return findPointSpherePenetration(point, capsuleStart, startRadius, penetration); - - } else if (proj >= 1.0f) { // closest to the end - return findPointSpherePenetration(point, capsuleEnd, endRadius, penetration); - - } else { // closest to the middle - return findPointSpherePenetration(point, capsuleStart + segmentVector * proj, - glm::mix(startRadius, endRadius, proj), penetration); - } -} - -bool findSphereCapsuleConePenetration(const glm::vec3& sphereCenter, - float sphereRadius, const glm::vec3& capsuleStart, const glm::vec3& capsuleEnd, - float startRadius, float endRadius, glm::vec3& penetration) { - return findPointCapsuleConePenetration(sphereCenter, capsuleStart, capsuleEnd, - startRadius + sphereRadius, endRadius + sphereRadius, penetration); -} - -bool findSpherePlanePenetration(const glm::vec3& sphereCenter, float sphereRadius, - const glm::vec4& plane, glm::vec3& penetration) { - float distance = glm::dot(plane, glm::vec4(sphereCenter, 1.0f)) - sphereRadius; - if (distance < 0.0f) { - penetration = glm::vec3(plane) * distance; - return true; - } - return false; -} - -bool findSphereDiskPenetration(const glm::vec3& sphereCenter, float sphereRadius, - const glm::vec3& diskCenter, float diskRadius, float diskThickness, const glm::vec3& diskNormal, - glm::vec3& penetration) { - glm::vec3 localCenter = sphereCenter - diskCenter; - float axialDistance = glm::dot(localCenter, diskNormal); - if (std::fabs(axialDistance) < (sphereRadius + 0.5f * diskThickness)) { - // sphere hit the plane, but does it hit the disk? - // Note: this algorithm ignores edge hits. - glm::vec3 axialOffset = axialDistance * diskNormal; - if (glm::length(localCenter - axialOffset) < diskRadius) { - // yes, hit the disk - penetration = (std::fabs(axialDistance) - (sphereRadius + 0.5f * diskThickness) ) * diskNormal; - if (axialDistance < 0.f) { - // hit the backside of the disk, so negate penetration vector - penetration *= -1.f; - } - return true; - } - } - return false; -} - -bool findCapsuleSpherePenetration(const glm::vec3& capsuleStart, const glm::vec3& capsuleEnd, float capsuleRadius, - const glm::vec3& sphereCenter, float sphereRadius, glm::vec3& penetration) { - if (findSphereCapsulePenetration(sphereCenter, sphereRadius, - capsuleStart, capsuleEnd, capsuleRadius, penetration)) { - penetration = -penetration; - return true; - } - return false; -} - -bool findCapsulePlanePenetration(const glm::vec3& capsuleStart, const glm::vec3& capsuleEnd, float capsuleRadius, - const glm::vec4& plane, glm::vec3& penetration) { - float distance = glm::min(glm::dot(plane, glm::vec4(capsuleStart, 1.0f)), - glm::dot(plane, glm::vec4(capsuleEnd, 1.0f))) - capsuleRadius; - if (distance < 0.0f) { - penetration = glm::vec3(plane) * distance; - return true; - } - return false; -} - -glm::vec3 addPenetrations(const glm::vec3& currentPenetration, const glm::vec3& newPenetration) { - // find the component of the new penetration in the direction of the current - float currentLength = glm::length(currentPenetration); - if (currentLength == 0.0f) { - return newPenetration; - } - glm::vec3 currentDirection = currentPenetration / currentLength; - float directionalComponent = glm::dot(newPenetration, currentDirection); - - // if orthogonal or in the opposite direction, we can simply add - if (directionalComponent <= 0.0f) { - return currentPenetration + newPenetration; - } - - // otherwise, we need to take the maximum component of current and new - return currentDirection * glm::max(directionalComponent, currentLength) + - newPenetration - (currentDirection * directionalComponent); -} - -bool findRaySphereIntersection(const glm::vec3& origin, const glm::vec3& direction, - const glm::vec3& center, float radius, float& distance) { - glm::vec3 relativeOrigin = origin - center; - float c = glm::dot(relativeOrigin, relativeOrigin) - radius * radius; - if (c < 0.0f) { - distance = 0.0f; - return true; // starts inside the sphere - } - float b = glm::dot(direction, relativeOrigin); - float radicand = b * b - c; - if (radicand < 0.0f) { - return false; // doesn't hit the sphere - } - float t = -b - sqrtf(radicand); - if (t < 0.0f) { - return false; // doesn't hit the sphere - } - distance = t; - return true; -} - -bool findRayCapsuleIntersection(const glm::vec3& origin, const glm::vec3& direction, - const glm::vec3& start, const glm::vec3& end, float radius, float& distance) { - if (start == end) { - return findRaySphereIntersection(origin, direction, start, radius, distance); // handle degenerate case - } - glm::vec3 relativeOrigin = origin - start; - glm::vec3 relativeEnd = end - start; - float capsuleLength = glm::length(relativeEnd); - relativeEnd /= capsuleLength; - float originProjection = glm::dot(relativeEnd, relativeOrigin); - glm::vec3 constant = relativeOrigin - relativeEnd * originProjection; - float c = glm::dot(constant, constant) - radius * radius; - if (c < 0.0f) { // starts inside cylinder - if (originProjection < 0.0f) { // below start - return findRaySphereIntersection(origin, direction, start, radius, distance); - - } else if (originProjection > capsuleLength) { // above end - return findRaySphereIntersection(origin, direction, end, radius, distance); - - } else { // between start and end - distance = 0.0f; - return true; - } - } - glm::vec3 coefficient = direction - relativeEnd * glm::dot(relativeEnd, direction); - float a = glm::dot(coefficient, coefficient); - if (a == 0.0f) { - return false; // parallel to enclosing cylinder - } - float b = 2.0f * glm::dot(constant, coefficient); - float radicand = b * b - 4.0f * a * c; - if (radicand < 0.0f) { - return false; // doesn't hit the enclosing cylinder - } - float t = (-b - sqrtf(radicand)) / (2.0f * a); - if (t < 0.0f) { - return false; // doesn't hit the enclosing cylinder - } - glm::vec3 intersection = relativeOrigin + direction * t; - float intersectionProjection = glm::dot(relativeEnd, intersection); - if (intersectionProjection < 0.0f) { // below start - return findRaySphereIntersection(origin, direction, start, radius, distance); - - } else if (intersectionProjection > capsuleLength) { // above end - return findRaySphereIntersection(origin, direction, end, radius, distance); - } - distance = t; // between start and end - return true; -} - -// Do line segments (r1p1.x, r1p1.y)--(r1p2.x, r1p2.y) and (r2p1.x, r2p1.y)--(r2p2.x, r2p2.y) intersect? -// from: http://ptspts.blogspot.com/2010/06/how-to-determine-if-two-line-segments.html -bool doLineSegmentsIntersect(glm::vec2 r1p1, glm::vec2 r1p2, glm::vec2 r2p1, glm::vec2 r2p2) { - int d1 = computeDirection(r2p1.x, r2p1.y, r2p2.x, r2p2.y, r1p1.x, r1p1.y); - int d2 = computeDirection(r2p1.x, r2p1.y, r2p2.x, r2p2.y, r1p2.x, r1p2.y); - int d3 = computeDirection(r1p1.x, r1p1.y, r1p2.x, r1p2.y, r2p1.x, r2p1.y); - int d4 = computeDirection(r1p1.x, r1p1.y, r1p2.x, r1p2.y, r2p2.x, r2p2.y); - return (((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) && - ((d3 > 0 && d4 < 0) || (d3 < 0 && d4 > 0))) || - (d1 == 0 && isOnSegment(r2p1.x, r2p1.y, r2p2.x, r2p2.y, r1p1.x, r1p1.y)) || - (d2 == 0 && isOnSegment(r2p1.x, r2p1.y, r2p2.x, r2p2.y, r1p2.x, r1p2.y)) || - (d3 == 0 && isOnSegment(r1p1.x, r1p1.y, r1p2.x, r1p2.y, r2p1.x, r2p1.y)) || - (d4 == 0 && isOnSegment(r1p1.x, r1p1.y, r1p2.x, r1p2.y, r2p2.x, r2p2.y)); -} - -bool isOnSegment(float xi, float yi, float xj, float yj, float xk, float yk) { - return (xi <= xk || xj <= xk) && (xk <= xi || xk <= xj) && - (yi <= yk || yj <= yk) && (yk <= yi || yk <= yj); -} - -int computeDirection(float xi, float yi, float xj, float yj, float xk, float yk) { - float a = (xk - xi) * (yj - yi); - float b = (xj - xi) * (yk - yi); - return a < b ? -1 : a > b ? 1 : 0; -} - - +// Copyright 2013 High Fidelity, Inc. // -// Polygon Clipping routines inspired by, pseudo code found here: http://www.cs.rit.edu/~icss571/clipTrans/PolyClipBack.html -// -// Coverage Map's polygon coordinates are from -1 to 1 in the following mapping to screen space. -// -// (0,0) (windowWidth, 0) -// -1,1 1,1 -// +-----------------------+ -// | | | -// | | | -// | -1,0 | | -// |-----------+-----------| -// | 0,0 | -// | | | -// | | | -// | | | -// +-----------------------+ -// -1,-1 1,-1 -// (0,windowHeight) (windowWidth,windowHeight) +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // const float PolygonClip::TOP_OF_CLIPPING_WINDOW = 1.0f; diff --git a/libraries/shared/src/HifiSockAddr.cpp b/libraries/shared/src/HifiSockAddr.cpp index cc031525d8..25e9e5637b 100644 --- a/libraries/shared/src/HifiSockAddr.cpp +++ b/libraries/shared/src/HifiSockAddr.cpp @@ -1,9 +1,12 @@ // // HifiSockAddr.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 11/26/2013. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "HifiSockAddr.h" diff --git a/libraries/shared/src/ListShape.cpp b/libraries/shared/src/ListShape.cpp index 593304c75a..26d1c7fea5 100644 --- a/libraries/shared/src/ListShape.cpp +++ b/libraries/shared/src/ListShape.cpp @@ -1,10 +1,12 @@ // // ListShape.cpp +// libraries/shared/src // -// ListShape: A collection of shapes, each with a local transform. +// Created by Andrew Meadows on 2014. +// Copyright 2014 High Fidelity, Inc. // -// Created by Andrew Meadows on 2014.02.20 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "ListShape.h" diff --git a/libraries/shared/src/Logging.cpp b/libraries/shared/src/Logging.cpp index f0dcd7b67b..2625cc744a 100644 --- a/libraries/shared/src/Logging.cpp +++ b/libraries/shared/src/Logging.cpp @@ -1,9 +1,12 @@ // // Logging.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 6/11/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/ModelUploader.cpp b/libraries/shared/src/ModelUploader.cpp index 4386704559..da809283d8 100644 --- a/libraries/shared/src/ModelUploader.cpp +++ b/libraries/shared/src/ModelUploader.cpp @@ -1,10 +1,12 @@ // // ModelUploader.cpp -// hifi +// libraries/shared/src // // Created by Clément Brisset on 3/4/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/NetworkPacket.cpp b/libraries/shared/src/NetworkPacket.cpp index 1671dc2435..b948b10c96 100644 --- a/libraries/shared/src/NetworkPacket.cpp +++ b/libraries/shared/src/NetworkPacket.cpp @@ -1,11 +1,12 @@ // // NetworkPacket.cpp -// shared +// libraries/shared/src // // Created by Brad Hefta-Gaub on 8/9/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// A really simple class that stores a network packet between being received and being processed +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/Node.cpp b/libraries/shared/src/Node.cpp index 1e78bc3feb..13f700ad5a 100644 --- a/libraries/shared/src/Node.cpp +++ b/libraries/shared/src/Node.cpp @@ -1,9 +1,12 @@ // // Node.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/15/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/NodeData.cpp b/libraries/shared/src/NodeData.cpp index e3800f8b93..6b71ef8f37 100644 --- a/libraries/shared/src/NodeData.cpp +++ b/libraries/shared/src/NodeData.cpp @@ -1,9 +1,12 @@ // // NodeData.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/19/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "NodeData.h" @@ -16,4 +19,4 @@ NodeData::NodeData() : NodeData::~NodeData() { -} \ No newline at end of file +} diff --git a/libraries/shared/src/NodeList.cpp b/libraries/shared/src/NodeList.cpp index b725914bfd..7ca6202398 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/shared/src/NodeList.cpp @@ -1,9 +1,12 @@ // // NodeList.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/15/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/OAuthAccessToken.cpp b/libraries/shared/src/OAuthAccessToken.cpp index 20a9dc3aa5..ab5ec6462a 100644 --- a/libraries/shared/src/OAuthAccessToken.cpp +++ b/libraries/shared/src/OAuthAccessToken.cpp @@ -1,9 +1,12 @@ // // OAuthAccessToken.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/18/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/OctalCode.cpp b/libraries/shared/src/OctalCode.cpp index ba0a001fb9..82bd471975 100644 --- a/libraries/shared/src/OctalCode.cpp +++ b/libraries/shared/src/OctalCode.cpp @@ -1,9 +1,12 @@ // // OctalCode.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 3/15/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include // std:min diff --git a/libraries/shared/src/PacketHeaders.cpp b/libraries/shared/src/PacketHeaders.cpp index c7518708ce..2832fde56e 100644 --- a/libraries/shared/src/PacketHeaders.cpp +++ b/libraries/shared/src/PacketHeaders.cpp @@ -1,9 +1,12 @@ // // PacketHeaders.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 6/28/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/PacketSender.cpp b/libraries/shared/src/PacketSender.cpp index 9fac115a39..489b083d92 100644 --- a/libraries/shared/src/PacketSender.cpp +++ b/libraries/shared/src/PacketSender.cpp @@ -1,11 +1,12 @@ // // PacketSender.cpp -// shared +// libraries/shared/src // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Threaded or non-threaded packet sender. +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include @@ -281,4 +282,4 @@ bool PacketSender::nonThreadedProcess() { _lastSendTime = now; } return isStillRunning(); -} \ No newline at end of file +} diff --git a/libraries/shared/src/PerfStat.cpp b/libraries/shared/src/PerfStat.cpp index 7bea51dd6e..9235cb3f25 100644 --- a/libraries/shared/src/PerfStat.cpp +++ b/libraries/shared/src/PerfStat.cpp @@ -1,13 +1,12 @@ // -// HiFiPerfStat.cpp -// hifi +// PerfStat.cpp +// libraries/shared/src // // Created by Brad Hefta-Gaub on 3/29/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. -// -// Poor-man's performance stats collector class. Useful for collecting timing -// details from various portions of the code. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/ReceivedPacketProcessor.cpp b/libraries/shared/src/ReceivedPacketProcessor.cpp index df7bfad165..8394559524 100644 --- a/libraries/shared/src/ReceivedPacketProcessor.cpp +++ b/libraries/shared/src/ReceivedPacketProcessor.cpp @@ -1,11 +1,12 @@ // // ReceivedPacketProcessor.cpp -// shared +// libraries/shared/src // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Threaded or non-threaded packet receiver. +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "NodeList.h" diff --git a/libraries/shared/src/RegisteredMetaTypes.cpp b/libraries/shared/src/RegisteredMetaTypes.cpp index 0354fedba9..3e21a72fd5 100644 --- a/libraries/shared/src/RegisteredMetaTypes.cpp +++ b/libraries/shared/src/RegisteredMetaTypes.cpp @@ -1,12 +1,12 @@ // // RegisteredMetaTypes.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 10/3/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Used to register meta-types with Qt so that they can be used as properties for objects exposed to our -// Agent scripting. +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "RegisteredMetaTypes.h" diff --git a/libraries/shared/src/ResourceCache.cpp b/libraries/shared/src/ResourceCache.cpp index c7858e6e20..30a725c010 100644 --- a/libraries/shared/src/ResourceCache.cpp +++ b/libraries/shared/src/ResourceCache.cpp @@ -1,9 +1,12 @@ // // ResourceCache.cpp -// shared +// libraries/shared/src // // Created by Andrzej Kapolka on 2/27/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/ShapeCollider.cpp b/libraries/shared/src/ShapeCollider.cpp index 70f9b9c4bf..2462663405 100644 --- a/libraries/shared/src/ShapeCollider.cpp +++ b/libraries/shared/src/ShapeCollider.cpp @@ -1,9 +1,12 @@ // // ShapeCollider.cpp -// hifi +// libraries/shared/src // -// Created by Andrew Meadows on 2014.02.20 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrew Meadows on 2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index efd5180d03..fc54c62d51 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -1,9 +1,12 @@ // // SharedUtil.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/22/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/SimpleMovingAverage.cpp b/libraries/shared/src/SimpleMovingAverage.cpp index 676c85598e..9f7e541c9a 100644 --- a/libraries/shared/src/SimpleMovingAverage.cpp +++ b/libraries/shared/src/SimpleMovingAverage.cpp @@ -1,9 +1,12 @@ // // SimpleMovingAverage.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 4/18/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "SharedUtil.h" @@ -53,4 +56,4 @@ float SimpleMovingAverage::getEventDeltaAverage() const { float SimpleMovingAverage::getAverageSampleValuePerSecond() const { return _average * (1 / getEventDeltaAverage()); -} \ No newline at end of file +} diff --git a/libraries/shared/src/StdDev.cpp b/libraries/shared/src/StdDev.cpp index 17bf60e8be..4528d0fa4f 100644 --- a/libraries/shared/src/StdDev.cpp +++ b/libraries/shared/src/StdDev.cpp @@ -1,9 +1,12 @@ // // StdDev.cpp -// hifi +// libraries/shared/src // // Created by Philip Rosedale on 3/12/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include @@ -56,4 +59,4 @@ float StDev::getStDev() { return sqrt(stdev/(float)(sampleCount - 1.0)); else return 0; -} \ No newline at end of file +} diff --git a/libraries/shared/src/StreamUtils.cpp b/libraries/shared/src/StreamUtils.cpp index 44c81f9464..d7b0c83c1f 100644 --- a/libraries/shared/src/StreamUtils.cpp +++ b/libraries/shared/src/StreamUtils.cpp @@ -1,8 +1,12 @@ // // StreamUtils.cpp +// libraries/shared/src // -// Created by Andrew Meadows on 2014.02.21 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrew Meadows on 2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/ThreadedAssignment.cpp b/libraries/shared/src/ThreadedAssignment.cpp index fdf2d91c36..1bd79895ab 100644 --- a/libraries/shared/src/ThreadedAssignment.cpp +++ b/libraries/shared/src/ThreadedAssignment.cpp @@ -1,9 +1,12 @@ // // ThreadedAssignment.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 12/3/2013. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/UUID.cpp b/libraries/shared/src/UUID.cpp index e24c81ebe3..eafd7dd181 100644 --- a/libraries/shared/src/UUID.cpp +++ b/libraries/shared/src/UUID.cpp @@ -1,9 +1,12 @@ // // UUID.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 10/7/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "UUID.h" @@ -11,4 +14,4 @@ QString uuidStringWithoutCurlyBraces(const QUuid& uuid) { QString uuidStringNoBraces = uuid.toString().mid(1, uuid.toString().length() - 2); return uuidStringNoBraces; -} \ No newline at end of file +} diff --git a/libraries/voxels/src/EnvironmentData.cpp b/libraries/voxels/src/EnvironmentData.cpp index dc82844bd0..b9b64f72d1 100644 --- a/libraries/voxels/src/EnvironmentData.cpp +++ b/libraries/voxels/src/EnvironmentData.cpp @@ -1,9 +1,12 @@ // // EnvironmentData.cpp -// interface +// libraries/voxels/src // // Created by Andrzej Kapolka on 5/6/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/voxels/src/LocalVoxelsList.cpp b/libraries/voxels/src/LocalVoxelsList.cpp index e8f5a09d6d..4324306161 100644 --- a/libraries/voxels/src/LocalVoxelsList.cpp +++ b/libraries/voxels/src/LocalVoxelsList.cpp @@ -1,9 +1,12 @@ // // LocalVoxelsList.cpp -// hifi +// libraries/voxels/src // // Created by Clément Brisset on 2/24/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "LocalVoxelsList.h" @@ -61,4 +64,4 @@ void LocalVoxelsList::remove(QString treeName) { } else { qDebug() << "[DEBUG] LocalVoxelsList : tree still in use (" << treeName << ")"; } -} \ No newline at end of file +} diff --git a/libraries/voxels/src/Tags.cpp b/libraries/voxels/src/Tags.cpp index 4d1fb322cd..8f8228faae 100644 --- a/libraries/voxels/src/Tags.cpp +++ b/libraries/voxels/src/Tags.cpp @@ -1,9 +1,12 @@ // // Tags.cpp -// hifi +// libraries/voxels/src // // Created by Clement Brisset on 7/3/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/voxels/src/VoxelDetail.cpp b/libraries/voxels/src/VoxelDetail.cpp index 4527f7ca2c..6c385c9387 100644 --- a/libraries/voxels/src/VoxelDetail.cpp +++ b/libraries/voxels/src/VoxelDetail.cpp @@ -1,9 +1,12 @@ // // VoxelDetail.cpp -// hifi +// libraries/voxels/src // -// Created by Brad Hefta-Gaub on 1/29/2014 -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 1/29/2014. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/voxels/src/VoxelEditPacketSender.cpp b/libraries/voxels/src/VoxelEditPacketSender.cpp index 90884f19f4..1832d5436e 100644 --- a/libraries/voxels/src/VoxelEditPacketSender.cpp +++ b/libraries/voxels/src/VoxelEditPacketSender.cpp @@ -1,11 +1,12 @@ // // VoxelEditPacketSender.cpp -// interface +// libraries/voxels/src // // Created by Brad Hefta-Gaub on 8/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// Threaded or non-threaded voxel packet Sender for the Application +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/voxels/src/VoxelTree.cpp b/libraries/voxels/src/VoxelTree.cpp index 5c48244a39..bb9de72e9d 100644 --- a/libraries/voxels/src/VoxelTree.cpp +++ b/libraries/voxels/src/VoxelTree.cpp @@ -1,9 +1,12 @@ // // VoxelTree.cpp -// hifi +// libraries/voxels/src // // Created by Stephen Birarda on 3/13/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/voxels/src/VoxelTreeCommands.cpp b/libraries/voxels/src/VoxelTreeCommands.cpp index d919f0e150..f0f092fd04 100644 --- a/libraries/voxels/src/VoxelTreeCommands.cpp +++ b/libraries/voxels/src/VoxelTreeCommands.cpp @@ -1,10 +1,12 @@ // // VoxelTreeCommands.cpp -// hifi +// libraries/voxels/src // // Created by Clement on 4/4/14. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "VoxelTree.h" @@ -61,4 +63,4 @@ void DeleteVoxelCommand::undo() { if (_packetSender) { _packetSender->queueVoxelEditMessages(PacketTypeVoxelSet, 1, &_voxel); } -} \ No newline at end of file +} diff --git a/libraries/voxels/src/VoxelTreeElement.cpp b/libraries/voxels/src/VoxelTreeElement.cpp index debcfee987..2582980816 100644 --- a/libraries/voxels/src/VoxelTreeElement.cpp +++ b/libraries/voxels/src/VoxelTreeElement.cpp @@ -1,9 +1,12 @@ // // VoxelTreeElement.cpp -// hifi +// libraries/voxels/src // // Created by Stephen Birarda on 3/13/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/voxels/src/VoxelTreeHeadlessViewer.cpp b/libraries/voxels/src/VoxelTreeHeadlessViewer.cpp index 999ef4fa36..5aaa8c8d97 100644 --- a/libraries/voxels/src/VoxelTreeHeadlessViewer.cpp +++ b/libraries/voxels/src/VoxelTreeHeadlessViewer.cpp @@ -1,10 +1,12 @@ // // VoxelTreeHeadlessViewer.cpp -// hifi +// libraries/voxels/src // -// Created by Brad Hefta-Gaub on 2/26/14 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Brad Hefta-Gaub on 2/26/14. +// Copyright 2014 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "VoxelTreeHeadlessViewer.h" diff --git a/libraries/voxels/src/VoxelsScriptingInterface.cpp b/libraries/voxels/src/VoxelsScriptingInterface.cpp index 61ee4b317d..08dcfd3f47 100644 --- a/libraries/voxels/src/VoxelsScriptingInterface.cpp +++ b/libraries/voxels/src/VoxelsScriptingInterface.cpp @@ -1,9 +1,12 @@ // // VoxelsScriptingInterface.cpp -// hifi +// libraries/voxels/src // // Created by Stephen Birarda on 9/17/13. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "VoxelTreeCommands.h" diff --git a/voxel-edit/src/SceneUtils.cpp b/voxel-edit/src/SceneUtils.cpp index 2cbe73c74e..19e227c71a 100644 --- a/voxel-edit/src/SceneUtils.cpp +++ b/voxel-edit/src/SceneUtils.cpp @@ -1,9 +1,12 @@ // // SceneUtils.cpp -// hifi +// voxel-edit/src // // Created by Brad Hefta-Gaub on 5/7/2013. -// Copyright (c) 2013 HighFidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/voxel-edit/src/main.cpp b/voxel-edit/src/main.cpp index 35401aa1d0..01e4cc0189 100644 --- a/voxel-edit/src/main.cpp +++ b/voxel-edit/src/main.cpp @@ -1,9 +1,12 @@ // // main.cpp -// Voxel Edit +// voxel-edit/src // // Created by Brad Hefta-Gaub on 05/03/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include From a65f8faea90887fbf4d7eed9bae41e854c679c88 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 09:36:13 -0700 Subject: [PATCH 240/595] fix Plane header that was not caught --- libraries/octree/src/Plane.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/libraries/octree/src/Plane.cpp b/libraries/octree/src/Plane.cpp index 727e16724c..d7cb2c54ff 100755 --- a/libraries/octree/src/Plane.cpp +++ b/libraries/octree/src/Plane.cpp @@ -1,12 +1,16 @@ // // Plane.cpp -// hifi +// libraries/octree/src/ // // Created by Brad Hefta-Gaub on 04/11/13. -// Originally from lighthouse3d. Modified to utilize glm::vec3 and clean up to our coding standards +// Copyright 2013 High Fidelity, Inc. // +// Originally from lighthouse3d. Modified to utilize glm::vec3 and clean up to our coding standards // Simple plane class. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// #include "Plane.h" From 6ce5a244603d06d255e2bdb6ff44537d5684a7f1 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 09:44:38 -0700 Subject: [PATCH 241/595] missed copyright cleanups in apache header --- cmake/macros/IncludeGLM.cmake | 2 +- cmake/macros/SetupHifiProject.cmake | 2 +- cmake/modules/FindFaceshift.cmake | 2 +- cmake/modules/FindGLEW.cmake | 3 ++- cmake/modules/FindGLUT.cmake | 1 + cmake/modules/FindLibOVR.cmake | 2 +- cmake/modules/FindQxmpp.cmake | 2 +- cmake/modules/FindSixense.cmake | 2 +- cmake/modules/FindVisage.cmake | 2 +- domain-server/src/main.cpp | 6 ++++++ examples/defaultScripts.js | 1 + examples/lookWithMouse.js | 2 +- examples/lookWithTouch.js | 2 +- examples/menuExample.js | 2 +- interface/InterfaceConfig.h.in | 7 +++++-- interface/InterfaceVersion.h.in | 9 +++++++-- 16 files changed, 32 insertions(+), 15 deletions(-) diff --git a/cmake/macros/IncludeGLM.cmake b/cmake/macros/IncludeGLM.cmake index 65974a51c5..a31324993e 100644 --- a/cmake/macros/IncludeGLM.cmake +++ b/cmake/macros/IncludeGLM.cmake @@ -1,7 +1,7 @@ # # IncludeGLM.cmake # -# Copyright (c) 2013 High Fidelity +# Copyright 2013 High Fidelity, Inc. # # Distributed under the Apache License, Version 2.0. # See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html diff --git a/cmake/macros/SetupHifiProject.cmake b/cmake/macros/SetupHifiProject.cmake index 11252e2a74..50cd3a4150 100644 --- a/cmake/macros/SetupHifiProject.cmake +++ b/cmake/macros/SetupHifiProject.cmake @@ -1,7 +1,7 @@ # # SetupHifiProject.cmake # -# Copyright (c) 2013 High Fidelity +# Copyright 2013 High Fidelity, Inc. # # Distributed under the Apache License, Version 2.0. # See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html diff --git a/cmake/modules/FindFaceshift.cmake b/cmake/modules/FindFaceshift.cmake index 9b407c353f..faf556e06c 100644 --- a/cmake/modules/FindFaceshift.cmake +++ b/cmake/modules/FindFaceshift.cmake @@ -12,7 +12,7 @@ # FACESHIFT_LIBRARIES - Link this to use Faceshift # # Created on 8/30/2013 by Andrzej Kapolka -# Copyright (c) 2013 High Fidelity +# Copyright 2013 High Fidelity, Inc. # # Distributed under the Apache License, Version 2.0. # See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html diff --git a/cmake/modules/FindGLEW.cmake b/cmake/modules/FindGLEW.cmake index 160cfedc5a..68e3248850 100644 --- a/cmake/modules/FindGLEW.cmake +++ b/cmake/modules/FindGLEW.cmake @@ -9,9 +9,10 @@ # GLEW_LIBRARY # # Created on 2/6/2014 by Stephen Birarda +# Copyright 2014 High Fidelity, Inc. # # Adapted from FindGLEW.cmake available in the nvidia-texture-tools repository -# (https://code.google.com/p/nvidia-texture-tools/source/browse/trunk/cmake/FindGLEW.cmake?r=96) +# (https://code.google.com/p/nvidia-texture-tools/source/browse/trunk/cmake/FindGLEW.cmake?r=96) # # Distributed under the Apache License, Version 2.0. # See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html diff --git a/cmake/modules/FindGLUT.cmake b/cmake/modules/FindGLUT.cmake index fe41dc5df8..280a6ac6db 100644 --- a/cmake/modules/FindGLUT.cmake +++ b/cmake/modules/FindGLUT.cmake @@ -10,6 +10,7 @@ # GLUT_DLL_PATH - Optionally defined for Win32, if not in path # # Created on 2/6/2014 by Stephen Birarda +# Copyright 2014 High Fidelity, Inc. # # Adapted from FindGLUT.cmake available in tlorach's OpenGLText Repository # https://raw.github.com/tlorach/OpenGLText/master/cmake/FindGLUT.cmake diff --git a/cmake/modules/FindLibOVR.cmake b/cmake/modules/FindLibOVR.cmake index 811fdb73d4..c07b4c14c1 100644 --- a/cmake/modules/FindLibOVR.cmake +++ b/cmake/modules/FindLibOVR.cmake @@ -12,7 +12,7 @@ # LIBOVR_LIBRARIES - Link this to use LibOVR # # Created on 5/9/2013 by Stephen Birarda -# Copyright (c) 2013 High Fidelity +# Copyright 2013 High Fidelity, Inc. # # Distributed under the Apache License, Version 2.0. # See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html diff --git a/cmake/modules/FindQxmpp.cmake b/cmake/modules/FindQxmpp.cmake index caeb35219d..d5f23143f6 100644 --- a/cmake/modules/FindQxmpp.cmake +++ b/cmake/modules/FindQxmpp.cmake @@ -12,7 +12,7 @@ # QXMPP_LIBRARIES - Link this to use qxmpp # # Created on 3/10/2014 by Stephen Birarda -# Copyright (c) 2014 High Fidelity +# Copyright 2014 High Fidelity, Inc. # # Distributed under the Apache License, Version 2.0. # See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html diff --git a/cmake/modules/FindSixense.cmake b/cmake/modules/FindSixense.cmake index 74965f5734..02b6e3fc21 100644 --- a/cmake/modules/FindSixense.cmake +++ b/cmake/modules/FindSixense.cmake @@ -12,7 +12,7 @@ # SIXENSE_LIBRARIES - Link this to use Sixense # # Created on 11/15/2013 by Andrzej Kapolka -# Copyright (c) 2013 High Fidelity +# Copyright 2013 High Fidelity, Inc. # # Distributed under the Apache License, Version 2.0. # See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html diff --git a/cmake/modules/FindVisage.cmake b/cmake/modules/FindVisage.cmake index 6d204e4649..0aa57f6508 100644 --- a/cmake/modules/FindVisage.cmake +++ b/cmake/modules/FindVisage.cmake @@ -12,7 +12,7 @@ # VISAGE_LIBRARIES - Link this to use Visage # # Created on 2/11/2014 by Andrzej Kapolka -# Copyright (c) 2014 High Fidelity +# Copyright 2014 High Fidelity, Inc. # # Distributed under the Apache License, Version 2.0. # See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html diff --git a/domain-server/src/main.cpp b/domain-server/src/main.cpp index d79f06365d..2c8c3bd4c4 100644 --- a/domain-server/src/main.cpp +++ b/domain-server/src/main.cpp @@ -5,6 +5,12 @@ // Created by Philip Rosedale on 11/20/12. // Copyright 2012 High Fidelity, Inc. // +// The Domain Server keeps a list of nodes that have connected to it, and echoes that list of +// nodes out to nodes when they check in. +// +// The connection is stateless... the domain server will set you inactive if it does not hear from +// you in LOGOFF_CHECK_INTERVAL milliseconds, meaning your info will not be sent to other users. +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/examples/defaultScripts.js b/examples/defaultScripts.js index ede2d0f6b6..b3f9649883 100644 --- a/examples/defaultScripts.js +++ b/examples/defaultScripts.js @@ -6,6 +6,7 @@ // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// Script.include("lookWithTouch.js"); Script.include("editVoxels.js"); diff --git a/examples/lookWithMouse.js b/examples/lookWithMouse.js index 9110218026..256a3ea67c 100644 --- a/examples/lookWithMouse.js +++ b/examples/lookWithMouse.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 1/28/14. -// Copyright (c) 2014 High Fidelity, Inc. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates use of the Controller class // diff --git a/examples/lookWithTouch.js b/examples/lookWithTouch.js index 5f5e2ee41c..68b29c305b 100644 --- a/examples/lookWithTouch.js +++ b/examples/lookWithTouch.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 1/28/14. -// Copyright (c) 2014 High Fidelity, Inc. +// Copyright 2014 High Fidelity, Inc. // // This is an example script that demonstrates use of the Controller class // diff --git a/examples/menuExample.js b/examples/menuExample.js index ed6f29d53a..00c6418269 100644 --- a/examples/menuExample.js +++ b/examples/menuExample.js @@ -3,7 +3,7 @@ // examples // // Created by Brad Hefta-Gaub on 2/24/14 -// Copyright (c) 2013 High Fidelity, Inc. +// Copyright 2013 High Fidelity, Inc. // // This is an example script that demonstrates use of the Menu object // diff --git a/interface/InterfaceConfig.h.in b/interface/InterfaceConfig.h.in index 0b570f622f..b2b1881d67 100644 --- a/interface/InterfaceConfig.h.in +++ b/interface/InterfaceConfig.h.in @@ -1,9 +1,12 @@ // // InterfaceConfig.h -// interface +// interface/src // // Created by Stephen Birarda on 2/8/13. -// Copyright (c) 2013 High Fidelity, Inc.. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef interface__InterfaceConfig__ diff --git a/interface/InterfaceVersion.h.in b/interface/InterfaceVersion.h.in index 60e51b4ab6..2f902de41c 100644 --- a/interface/InterfaceVersion.h.in +++ b/interface/InterfaceVersion.h.in @@ -1,9 +1,14 @@ // // InterfaceVersion.h -// Declaration of version and build data +// interface/src // // Created by Leonardo Murillo on 12/16/13. -// Copyright (c) 2013 High Fidelity, Inc.. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Declaration of version and build data +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // const QString BUILD_VERSION = "@BUILD_SEQ@"; From cb402e3eb39935311fc3b02d6d2db37fcefd14ac Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 09:46:43 -0700 Subject: [PATCH 242/595] run apache header script on tests --- tests/metavoxels/src/MetavoxelTests.cpp | 7 +++++-- tests/metavoxels/src/main.cpp | 8 ++++++-- tests/physics/src/CollisionInfoTests.cpp | 9 ++++++--- tests/physics/src/PhysicsTestUtil.cpp | 9 ++++++--- tests/physics/src/ShapeColliderTests.cpp | 9 ++++++--- tests/physics/src/main.cpp | 7 ++++++- 6 files changed, 35 insertions(+), 14 deletions(-) diff --git a/tests/metavoxels/src/MetavoxelTests.cpp b/tests/metavoxels/src/MetavoxelTests.cpp index a1b79319b5..2400e086eb 100644 --- a/tests/metavoxels/src/MetavoxelTests.cpp +++ b/tests/metavoxels/src/MetavoxelTests.cpp @@ -1,9 +1,12 @@ // // MetavoxelTests.cpp -// metavoxel-tests +// tests/metavoxels/src // // Created by Andrzej Kapolka on 2/7/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/tests/metavoxels/src/main.cpp b/tests/metavoxels/src/main.cpp index 10bf786957..51d4e565b2 100644 --- a/tests/metavoxels/src/main.cpp +++ b/tests/metavoxels/src/main.cpp @@ -1,9 +1,13 @@ // // main.cpp -// metavoxel-tests +// tests/metavoxels/src // // Created by Andrzej Kapolka on 2/7/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// #include diff --git a/tests/physics/src/CollisionInfoTests.cpp b/tests/physics/src/CollisionInfoTests.cpp index 241204d036..c4d585cedf 100644 --- a/tests/physics/src/CollisionInfoTests.cpp +++ b/tests/physics/src/CollisionInfoTests.cpp @@ -1,9 +1,12 @@ // // CollisionInfoTests.cpp -// physics-tests +// tests/physics/src // -// Created by Andrew Meadows on 2014.02.21 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrew Meadows on 2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/tests/physics/src/PhysicsTestUtil.cpp b/tests/physics/src/PhysicsTestUtil.cpp index fb940d2043..90f0952c08 100644 --- a/tests/physics/src/PhysicsTestUtil.cpp +++ b/tests/physics/src/PhysicsTestUtil.cpp @@ -1,9 +1,12 @@ // // PhysicsTestUtil.cpp -// physics-tests +// tests/physics/src // -// Created by Andrew Meadows on 2014.02.21 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrew Meadows on 2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/tests/physics/src/ShapeColliderTests.cpp b/tests/physics/src/ShapeColliderTests.cpp index 7aeec84651..dedf364b9f 100644 --- a/tests/physics/src/ShapeColliderTests.cpp +++ b/tests/physics/src/ShapeColliderTests.cpp @@ -1,9 +1,12 @@ // // ShapeColliderTests.cpp -// physics-tests +// tests/physics/src // -// Created by Andrew Meadows on 2014.02.21 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrew Meadows on 2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // //#include diff --git a/tests/physics/src/main.cpp b/tests/physics/src/main.cpp index b0a7adde4e..ca98f4d546 100644 --- a/tests/physics/src/main.cpp +++ b/tests/physics/src/main.cpp @@ -1,6 +1,11 @@ // // main.cpp -// physics-tests +// tests/physics/src +// +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "ShapeColliderTests.h" From c9b58c0ee9e64c28ae9ca516b32e8ac0cb66261e Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 09:49:47 -0700 Subject: [PATCH 243/595] fix headers in h files in tests, fix Andrew's dates --- tests/metavoxels/src/MetavoxelTests.h | 7 +++++-- tests/physics/src/CollisionInfoTests.cpp | 2 +- tests/physics/src/CollisionInfoTests.h | 9 ++++++--- tests/physics/src/PhysicsTestUtil.cpp | 2 +- tests/physics/src/PhysicsTestUtil.h | 9 ++++++--- tests/physics/src/ShapeColliderTests.cpp | 2 +- tests/physics/src/ShapeColliderTests.h | 9 ++++++--- 7 files changed, 26 insertions(+), 14 deletions(-) diff --git a/tests/metavoxels/src/MetavoxelTests.h b/tests/metavoxels/src/MetavoxelTests.h index 22a680acbb..71f44080d3 100644 --- a/tests/metavoxels/src/MetavoxelTests.h +++ b/tests/metavoxels/src/MetavoxelTests.h @@ -1,9 +1,12 @@ // // MetavoxelTests.h -// metavoxel-tests +// tests/metavoxels/src // // Created by Andrzej Kapolka on 2/7/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __interface__MetavoxelTests__ diff --git a/tests/physics/src/CollisionInfoTests.cpp b/tests/physics/src/CollisionInfoTests.cpp index c4d585cedf..ffc7e94cc4 100644 --- a/tests/physics/src/CollisionInfoTests.cpp +++ b/tests/physics/src/CollisionInfoTests.cpp @@ -2,7 +2,7 @@ // CollisionInfoTests.cpp // tests/physics/src // -// Created by Andrew Meadows on 2014. +// Created by Andrew Meadows on 2/21/2014. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. diff --git a/tests/physics/src/CollisionInfoTests.h b/tests/physics/src/CollisionInfoTests.h index 51579e8f11..7877de4392 100644 --- a/tests/physics/src/CollisionInfoTests.h +++ b/tests/physics/src/CollisionInfoTests.h @@ -1,9 +1,12 @@ // // CollisionInfoTests.h -// physics-tests +// tests/physics/src // -// Created by Andrew Meadows on 2014.02.21 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrew Meadows on 2/21/2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __tests__CollisionInfoTests__ diff --git a/tests/physics/src/PhysicsTestUtil.cpp b/tests/physics/src/PhysicsTestUtil.cpp index 90f0952c08..f176d5e637 100644 --- a/tests/physics/src/PhysicsTestUtil.cpp +++ b/tests/physics/src/PhysicsTestUtil.cpp @@ -2,7 +2,7 @@ // PhysicsTestUtil.cpp // tests/physics/src // -// Created by Andrew Meadows on 2014. +// Created by Andrew Meadows on 02/21/2014. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. diff --git a/tests/physics/src/PhysicsTestUtil.h b/tests/physics/src/PhysicsTestUtil.h index c4c7962466..cc758c71bc 100644 --- a/tests/physics/src/PhysicsTestUtil.h +++ b/tests/physics/src/PhysicsTestUtil.h @@ -1,9 +1,12 @@ // // PhysicsTestUtil.h -// physics-tests +// tests/physics/src // -// Created by Andrew Meadows on 2014.02.21 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrew Meadows on 02/21/2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __tests__PhysicsTestUtil__ diff --git a/tests/physics/src/ShapeColliderTests.cpp b/tests/physics/src/ShapeColliderTests.cpp index dedf364b9f..2c25decdee 100644 --- a/tests/physics/src/ShapeColliderTests.cpp +++ b/tests/physics/src/ShapeColliderTests.cpp @@ -2,7 +2,7 @@ // ShapeColliderTests.cpp // tests/physics/src // -// Created by Andrew Meadows on 2014. +// Created by Andrew Meadows on 02/21/2014. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. diff --git a/tests/physics/src/ShapeColliderTests.h b/tests/physics/src/ShapeColliderTests.h index ecd4a7f045..9fee17b228 100644 --- a/tests/physics/src/ShapeColliderTests.h +++ b/tests/physics/src/ShapeColliderTests.h @@ -1,9 +1,12 @@ // // ShapeColliderTests.h -// physics-tests +// tests/physics/src // -// Created by Andrew Meadows on 2014.02.21 -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrew Meadows on 02/21/2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __tests__ShapeColliderTests__ From 619e9d7cd3d19583fe91a96449be72236669c30e Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 09:52:00 -0700 Subject: [PATCH 244/595] more header repairs caught via find --- examples/ribbon.js | 2 +- tools/mtc/src/main.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/ribbon.js b/examples/ribbon.js index 9f0cc02e52..dd3d46fbfc 100644 --- a/examples/ribbon.js +++ b/examples/ribbon.js @@ -3,7 +3,7 @@ // examples // // Created by Andrzej Kapolka on 2/24/14. -// Copyright 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html diff --git a/tools/mtc/src/main.cpp b/tools/mtc/src/main.cpp index b1cd154a48..096ade4625 100644 --- a/tools/mtc/src/main.cpp +++ b/tools/mtc/src/main.cpp @@ -3,7 +3,7 @@ // tools/mtc/src // // Created by Andrzej Kapolka on 12/31/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html From ce85e67a42c6f520844ce4cf73266ba50e9377df Mon Sep 17 00:00:00 2001 From: stojce Date: Wed, 9 Apr 2014 18:54:59 +0200 Subject: [PATCH 245/595] Modify icons in Interface "mirror" --- interface/resources/images/audio-box.svg | 12 +++ interface/resources/images/body.png | Bin 4801 -> 0 bytes interface/resources/images/close.png | Bin 3817 -> 0 bytes interface/resources/images/close.svg | 26 +++-- interface/resources/images/head.png | Bin 4453 -> 0 bytes interface/resources/images/mic-mute.svg | 115 +++++++++++++++++++++ interface/resources/images/mic.svg | 121 +++++++++++++++++++---- interface/resources/images/minus.svg | 11 +++ interface/resources/images/mute.svg | 20 ---- interface/resources/images/plus.svg | 12 +++ interface/src/Application.cpp | 25 +++-- interface/src/Audio.cpp | 69 ++++++++----- interface/src/Audio.h | 3 +- interface/src/ui/RearMirrorTools.cpp | 31 +++--- 14 files changed, 348 insertions(+), 97 deletions(-) create mode 100644 interface/resources/images/audio-box.svg delete mode 100644 interface/resources/images/body.png delete mode 100644 interface/resources/images/close.png delete mode 100644 interface/resources/images/head.png create mode 100644 interface/resources/images/mic-mute.svg create mode 100644 interface/resources/images/minus.svg delete mode 100644 interface/resources/images/mute.svg create mode 100644 interface/resources/images/plus.svg diff --git a/interface/resources/images/audio-box.svg b/interface/resources/images/audio-box.svg new file mode 100644 index 0000000000..0c0db4f51f --- /dev/null +++ b/interface/resources/images/audio-box.svg @@ -0,0 +1,12 @@ + + + Slice 1 + Created with Sketch (http://www.bohemiancoding.com/sketch) + + + + + + + + \ No newline at end of file diff --git a/interface/resources/images/body.png b/interface/resources/images/body.png deleted file mode 100644 index dda65bad07774cab5372349673b487775b22baa0..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4801 zcmZ`*c{tST`yNc$*X${iED3ga3J;$%#`M%fn{_)=Tb3gaGgvN_pfQcRlFzF2`tA~j5&C({B zSGEht{{X(;OqP_tD<{vJ&6x98WTvg$bE|Ofd|lTAiuk8&K~%56OT`Rwo#{lX*mN!# zm~HbwY|1tFCOxL!0+9-s-99%k@crQ>fGl^4eb2mjwr8Zg9=E`1KtO@(rzl_~!l{6B_yKnI^DCF#jY{(!C%N-Ut(T|&2)IPutYV3k<-1jmzpqCl zhQg(|#jlhKt*oHl&AII~j!d2oF+b3F6}V@)A-+t_&?aY~COwxQL+W_}TcXx!rz#tg zEdf=y<65)Rk4@G&W2Q+3`=+Z^`e9}h-^QKKmS&%m z7{epo>h7qMkoUmOOyQwJ)1myz67&Kg=^or}e)fRiJ1VBt2>Mre4FK#cov4>)AZ_r{ zH4ZtZR}C-SO5@9YQkj11( z0?X1$JFp7fQt+mm00F{p8F0|urvn?%Vzq!zwW03;OxkkqY5Z@ydjkeZfp3AvVande zZGcysSiPB9Zo##f?lv3A(oB%B3}NdWJUQBr?(ycar|7)nIBCsr1Ey_yk(;g^7I}{& zL2Ku&coDzU?MK-#Q;p5D1i@Mc+uOTY^lw3m#}8lFiCpFWb|nP;u{Zm!JKa3fz!WMJdU`TWxT8_x9-}qTBaHpbeUPZ9s0D{0!#u-5 zIA@EZ8L7yGAaa-EMw^Y3L;Gh`XYES41UKsz??HcM)504e|OjiCwDB za36k@mYqqNXeP*Bj6FfqH0hi;w~3*Up3aD|ieZh`4Xqon{41jVoAJ5@)9LT%p_@;LZsM(GbQZLgc|-?uwPAU)~wZRPRgyY%GRH* zYSFlZ&`ZrpcKX99)hW{H_D7|5GqINmq=Xk-CdFC{75!rQX9RTy@^AE4S6!}B{ebx( zdkTIbZ*L%Rp?y>MbNwbGMhtUp_S~${tl(_r>nq1wWF5XMToK48Cz9*PabFeZYN#{R zQRQ;1-H(@&$vaYBQa6)Dl3kK%lH(p-vcwN@52ZiCJu(@Tbr*McbRTiw8v>WaPz$NV z3~IW);*U@J5sMYIk%85_?%!G$H5L;EQw19Y1q3YxDT*CR0;yi9U8%FF^NO8SZr04t zfY!6t^Uv&LlT%iEEL_AYqgAp?%T@|y`k;B^B^ssZqDrJ|u5o4W3EKqlwF}xWY+jfX zbxe#PNQiy8*;+Q#EVDE-uMysOE%bHMThIrGXzjG-qU@;bM#l`t+-daLNAV?nQn}W- zY8@BR&#y;qKxeLrS45^G5)d(6m(AY~PFOh9Qmd#e9&>KuiX}>QojDa_DAZ&9cUdZ} z>aT9*-bmXy&#V!Rj85kr=e3t!kv5lEk`_iuqK+YPRf`q7tsmM_J#5jzop;@5(3QOf z<8#kSi)AML8&`tWQf({7dFzbps9S7XB75R{a`YMz0TK0V+wTef=jy_Phd7r$PgnPD zkZ0&6f+U^{APOhbQN5DAti8F+EPU&HgEIU+eb=X}g?!?{&S0{AfOqzw8ol|2ACP__+VI@aWE@!o+z&Dzn`ml=7?bSIb`{Y&)&FuN6X7p^?xS z=!pjZhLT{&cgF+T1OMIeufyx}yTf}Xz>C1gjGvkEfciiydML9zBiAuMU~4l?b6uD) zq~BiDW{{UwXCLN&N1aiL#g=E+mme&x_*i`TMzv)?NB|Kiir%P$GjYK2L5Il$(S`+POQ+`kFzmPr^C*4cRl~gG1D}I9wulim!pd;oO zRdL={K|`V*(yEv%3#)yN9a^?4Osu8IVQO#BQUQE8U+?xWX}+ zug!Wm=Qcm3e)8%*)%CS&FGR^jiRkCr;Q!~{{br?A54O@f@5*dOYmAAu&9&3t8kXX4 zAe_O-dbfUe4CdsdSJcFyS(aHvgM(Y;+FXZDjgHxLy-e>lHqUlX9?z9=m&#K2QHqFN z-#4f3k5L~@#KsbqCQ-pxcgB0R!dL3^xAOOhQ~nIZvGIl4ugDZ9l-)ymsAz9UJEyS0!KcwBE4X9X?dJn72q0j7y!XUkrM&lK!D{bhvR67dk)_ zL)T6ZJWSkQ@*1yhCGn(x4iXH+&mc77LL%V1F-xe*ooXhGs2bL;tA z>nQ8&cVq7&pXVuKgDwS4F5DVOKh=9mMlDWfR>bO1a%ejZg7t{ocMMrNp&N#a1miJ-B}5?m^7E({&m5 z?UzHa3(wYY^$XsW2lr=6V;hbI&+ppqK_<3pgJ)xZq@SdVKEAsOZV38eH>R-=JaN!R zU(9Z&*%Ns2!0iCNJd-2AWFnRENVD`{==-osasB3U*02M$@(*=%3$CQ}Ax?lemN`FuOMuOu^sxL5D$)YZ1`(YKVMX*f~T zptAdJ3pell`O^RqyH-#bHBr)_xkWn2-a~J8#xE?Jd^btXjL{_CWZeG}AdYjHo7@in zx+kxS3IPBBjNS$)UjTsl#Nnm^q(0;a0DvM`3nT$~`I0Icj{`e8J?r6zvMp7E*c_k1cJ9J1VSVd!9)cx-p3Upr=p?)k(GzY%ggvUyU6(7@FF+{ z$awjl{gvdud2}(pXdkRM0gLwn9p-g(!ut_4L_`ja{$9W8Bw$_saq{y0t1UDh2RURQ za$s4=zsWEG*#99rWd5hj8U1%x-hMuwKYMaULol8g9L9^_3y}lM{i|I7&iilS|0y!S z(fgO#&msO=>W7u9Ucva{J^cG4DX5eG52;vV-5@Znd=Djd-P8m)c>+MLL3n~qg8$VoZK;J!V&bp z|E!LqE93~Q4*Az;^#Gi=>Seq$*5!t-BLM@Imz7hHk&~5?SFwJPw3AsaEC{b0$BE!@+kk8R2_17i;mo?pTsZpimpDCNgeX{{f9C+ zZC<_)0MLC$=xSRa8Q&o5j8AHFkK4|`_i41WZvz?3b+zd7va_bnFc@&|)A4X=>@)ju z(FA|c%^`(xF&i)exsI#F#?-T$tfE%fW^A{V>f+`5-PU>@2F(Rz5Fg8TK+i{giF|6f z6KY6qyJ?94kuN2bEopG@FddUQp(D~2USw4wu(!9jJ2qy+p0d0;Fp!uLX+U;J)y;J& zD=mG7U~vg^9n6+ty>K(R3dqODS84-xjr{14%Z9`5n44VB?W;Jqqs+hfR^Q1ye~?x} zLc$0JgKf=mBxkYVoYIrh{h6jh34}o@O1C&;#W2Wo5YwDKBIg?tG67Xlc~ThY;Sv3& zxA%U&e$Px&iWWQGrJW>Ou(ucF@9W#@)_nfa;wb%CasgK%Dcy|mahl32G{8j7R^Zer z%ZP{wSl6VD)QbP8H4^#R3{IAB_#vXONottj)=nnXUCgAGBpc=zVg=c*N#E&FsP3cR z{lc>DA!kryj?YL>A0iTo!f<{4)K9Z&_ljdDPs`z$ZKi-1zMTjhZEHY;n5#meWjIey z^?tdJbsuutn&}&+09V_Z*5}^S*3hHtM@L6LG&gHMvyeK7;?jSR+0+toF_6|o+FTzb zF)=#2$0^3azY1~$dT}jYlxJmQv&zxBF6$^%4D46g0h5JrhX*XsnnI!I^Q(LiA`>hU z^|S2ChdDvv;`C=v*%~n`UN%=?$>n$yD@dYIX5t$JuNa(73m*52BoWJt<~r@VtGe?1@?!P*q{Kub;W zG|Ohr@!Hz;iO+i^G#WiQWnOBfIkhDErnz=j*B(nEG(0PkfJSl4`x%>)nF&n+l&qvs*doJdHR>AJf-|T^FBLY1qFrOwl<)BXc^rB zBsVrLt}%;6`sUbkQG3b4r6rI3e9UC4k&zK((`Ab>PXd#o&$(nl!wW@(*B~WHRT*R7 zT>6b>HA_e-h{=C5?|t%S408jWo3`Qee?UezWz3=k8%Gh0M`Uy7AA>2Pnn~h zU4H$_yIY_@^nF8o`{vDTX0_}jCIR&9K!ws D(=uVu diff --git a/interface/resources/images/close.png b/interface/resources/images/close.png deleted file mode 100644 index 8090e3d3d090a60ec2e8b0591b6e088baef2db03..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3817 zcmVX+uL$Nkc;* zP;zf(X>4Tx07wm;mUmQB*%pV-y*Itk5+Wca^cs2zAksTX6$DXM^`x7XQc?|s+0 z08spb1j2M!0f022SQPH-!CVp(%f$Br7!UytSOLJ{W@ZFO_(THK{JlMynW#v{v-a*T zfMmPdEWc1DbJqWVks>!kBnAKqMb$PuekK>?0+ds;#ThdH1j_W4DKdsJG8Ul;qO2n0 z#IJ1jr{*iW$(WZWsE0n`c;fQ!l&-AnmjxZO1uWyz`0VP>&nP`#itsL#`S=Q!g`M=rU9)45( zJ;-|dRq-b5&z?byo>|{)?5r=n76A4nTALlSzLiw~v~31J<>9PP?;rs31pu_(obw)r zY+jPY;tVGXi|p)da{-@gE-UCa`=5eu%D;v=_nFJ?`&K)q7e9d`Nfk3?MdhZarb|T3 z%nS~f&t(1g5dY)AIcd$w!z`Siz!&j_=v7hZlnI21XuE|xfmo0(WD10T)!}~_HYW!e zew}L+XmwuzeT6wtxJd`dZ#@7*BLgIEKY9Xv>st^p3dp{^Xswa2bB{85{^$B13tWnB z;Y>jyQ|9&zk7RNsqAVGs--K+z0uqo1bf5|}fi5rtEMN^BfHQCd-XH*kfJhJnmIE$G z0%<@5vOzxB0181d*a3EfYH$G5fqKvcPJ%XY23!PJzzuK<41h;K3WmW;Fah3yX$XSw z5EY_9s*o0>51B&N5F1(uc|$=^I1~fLLy3?Ol0f;;Ca4%HgQ}rJP(Ab`bQ-z{U4#0d z2hboi2K@njgb|nm(_szR0JebHusa+GN5aeCM0gdP2N%HG;Yzp`J`T6S7vUT504#-H z!jlL<$Or?`Mpy_N@kBz9SR?@vA#0H$qyni$nvf2p8@Y{0k#Xb$28W?xm>3qu8RLgp zjNxKdVb)?wFx8l2m{v>|<~C*!GlBVnrDD~wrdTJeKXwT=5u1%I#8zOBU|X=4u>;s) z>^mF|$G{ol9B_WP7+f-LHLe7=57&&lfa}8z;U@8Tyei%l?}87(bMRt(A-)QK9Dg3) zj~~XrCy)tR1Z#p1A(kK{Y$Q|=8VKhI{e%(1G*N-5Pjn)N5P8I0VkxnX*g?EW941ba z6iJ387g8iCnY4jaNopcpCOsy-A(P2EWJhusSwLP-t|XrzUnLKcKTwn?CKOLf97RIe zPB}`sKzTrUL#0v;sBY9)s+hW+T2H-1eM)^VN0T#`^Oxhvt&^*fYnAJldnHel*Ozyf zUoM{~Um<@={-*r60#U(0!Bc^wuvVc);k3d%g-J!4qLpHZVwz%!VuRu}#Ze`^l7W)9 z5>Kf>>9Eozr6C$Z)1`URxU@~QI@)F0FdauXr2Es8>BaOP=)Lp_WhG@>R;lZ?BJkMlIuMhw8ApiF&yDYW2hFJ?fJhni{?u z85&g@mo&yT8JcdI$(rSw=QPK(Xj%)k1X|@<=e1rim6`6$RAwc!i#egKuI;BS(LSWz zt39n_sIypSqfWEV6J3%nTQ@-4i zi$R;gsG*9XzhRzXqv2yCs*$VFDx+GXJH|L;wsDH_KI2;^u!)^Xl1YupO;gy^-c(?^ z&$Q1BYvyPsG^;hc$D**@Sy`+`)}T4VJji^bd7Jqw3q6Zii=7tT7GEswEK@D(EFW1Z zSp`^awCb?>!`j4}Yh7b~$A)U-W3$et-R8BesV(1jzwLcHnq9En7Q0Tn&-M=XBKs!$ zF$X<|c!#|X_tWYh)GZit z(Q)Cp9CDE^WG;+fcyOWARoj*0TI>4EP1lX*cEoMO-Pk?Z{kZ!p4@(b`M~lalr<3Oz z&kJ6Nm#vN_+kA5{dW4@^Vjg_`q%qU1ULk& z3Fr!>1V#i_2R;ij2@(Z$1jE4r!MlPVFVbHmT+|iPIq0wy5aS{>yK?9ZAjVh%SOwMWgFjair&;wpi!{CU}&@N=Eg#~ zLQ&zpEzVmGY{hI9Z0+4-0xS$$Xe-OToc?Y*V;rTcf_ zb_jRe-RZjXSeas3UfIyD;9afd%<`i0x4T#DzE)vdabOQ=k7SRuGN`h>O0Q~1)u-yD z>VX=Mn&!Rgd$;YK+Q-}1zu#?t(*cbG#Ronf6db&N$oEidtwC+YVcg-Y!_VuY>bk#Y ze_ww@?MU&F&qswvrN_dLb=5o6*Egs)ls3YRlE$&)amR1{;Ppd$6RYV^Go!iq1UMl% z@#4q$AMc(FJlT1QeX8jv{h#)>&{~RGq1N2iiMFIRX?sk2-|2wUogK~{EkB$8eDsX= znVPf8XG_nK&J~=SIiGia@9y}|z3FhX{g&gcj=lwb=lWgyFW&aLedUh- zof`v-2Kw$UzI*>(+&$@i-u=-BsSjR1%z8NeX#HdC`Hh-Z(6xI-`hmHDqv!v)W&&nrf>M(RhcN6(D;jNN*%^u_SYjF;2ng}*8Ow)d6M ztDk;%`@Lsk$;9w$(d(H%O5UixIr`T2ZRcd@fIj#Yr0i@`Lw2CjpP;8*akA`j7< z!F%8`C?og<_nv@B@C5kB(Ta$#z$g)}d!O;#9k3AmZB!t_bI_ISF!oKvxt2{)BEsQ3 z?mYrIK0+ugEEIKhb)u}SOcWOvi*!0I*4Ea~kflN}u$a$;ga?(XhN7v|>XAp=X+!n!Fd}AGTGj%ykS`AGjT8Cr)jJ;M*!co2a&kT#tep%V=pQt}`a$B#Pr>#;mNY)cG>GFDo^tO)*%3t&3h%LJn3AU^5Qe zwq8`CdU|?-{&$t2Ml(=jW21T|bajccEqqa87f-S65r_E2AZkmzaWB>1lA+ z{ui+1@e)%I%T5iJ5K%yHi>|INF+4nMb;A}Rnwy)&;v%b9H`do#>H44z=U~>~ldGx= zuJM!0pdK6?)HyTx?<;x7&|nR$9azr<;S$3EoXfPYudnA~sB@xy1Jqzau5YrqG7%+4 zRRD2(R7_R?m>l~?PF9a6wHh>%#!au%V{t_sCQ)49zP`R4GauS7K_7Tj;pss4k}5s6 zx3^_&ZLPM`Cu*J9-`}^c+O4gv-V3g-uFCxU{O@Kiv~PhS+<`?W=0IhoN3e^Ps3 zGyVj7iqA5}-rk;UXlQtE=0W={=-XKF+XK%{o1hlOvXhk_!GL^AHD)|x#2+O}iJ@zE zclQS~ex`jLS0{LG(t_A#*~wXy3;6l?$=NdwF)8HWS{MoLx;{}XUs>tp0*)EWXJY)< zAjfW2P%+OocvK1XR*tq5o{ROF;OE2{+~HB>cSLb& zb2iy}4CdUxqY6(4!9B<&l-mJUU@m&rbq4kjTw^HYXc!p$5_l2h{=@&Em4K{gSi6w3 f;4| - - - - - - - - - + + + Slice 1 + Created with Sketch (http://www.bohemiancoding.com/sketch) + + + + + + + + \ No newline at end of file diff --git a/interface/resources/images/head.png b/interface/resources/images/head.png deleted file mode 100644 index d21b453beef1d2cb597665bfb4abc647be1de990..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4453 zcmZ`)c{r5&`+hO9FUb-qlPnQ4V{C`)W1A>s$=D4u46|qqLuJj9kljQ{Qr0X**~wB! zr%ARXTefUT$(npGI^T2r`kn9Rx;}rr_x;?@{XEb6KGz##e$I%CU4$I~04}7l{&@fZ zPVQdT0{{TT{j4Sc0J|;@fiOoR5MXmM35&yH0Kk|lE1ha(IVc!SZ%}P`!zT`wToJj% z27Y_mSO8=ZgA6rijEa!**Jn25KPY44ZuN}8C|cajfS==PIC_BXE3f&BW($3Tso^+p zwxtr~ZzGx8?WobgnW}+7kENi2TEP5AIH-kU%MhxRW6S?}zS)8AP*>X;<6&L~Zd-K2uJa~MYBEOz^;)=I=}ugo`ADYZcy1gh z$Kj^rm`Cmv7EFT`G833uJK58-e%lm)@n<-{nvu%E$G{Evg+Ir9WdvAL+tljG+_4*K zo_BzNJderipco`N@8G~q+|;KI?B;TXYw)9Xc`P#hdRc0Len&U%4r&y?@DSP{2&_uj-8x#)m}U)B z5)SB0jXyM70s~)}fy$BF-;PD$os!!=a!PZ=E-c`E8M3`0r#`7}WrveqHbtqeWpsVs zvN@e6q#bqwDWHfkn99q~Gtqzbij$j0ci&#)-I;i%hWoR#Rql57Goj_kPu3QnQrRM6 zJnJGg!fX>E?(7jEed8gARis&jgR{K(J^h@4phz|IY9vbsNfSVvV3HteUt$cJx93%0 z?`W*|EJ-T!O@LqeIkPFo;c%TeZmKJ8Ilao6;7*pjCnuac8i8+Sr1L(pt zE*}ogP$M1osAdxw!$=s8HT(;&z&+ifM8W$!8G8M^N9ukJ{ zDmW~AwI~N+uDNo8B2vrhcy;qG%NwxLfo+DMh=Vs7dtABR0Z&5*%TJ548ntwd=?4hh zW)XTeG=8R9P>Z{&MQHrU7eFr3xg~{Fr-PNL+t8Nv$g;j(qOAnO!Q4)0>Y$^wD#ml$ZxFopPm(w0Gy>neSEy~^gO!%XyPjK~N2RKo=6ja4C5LXvE-^w*E zwH#0{JHo#d&eQDs1%2gsBYTKw$g$A`u@_C!iEMTt?{J>u>0k-GgcYv{>kR95#K9IN zi?9MSig*-nV4DM4=FyFJy7fp=sdFj($S4V+^Aa){m0?y$FL6gHO{s?CDV^%>M&!dN z9VfF=iEOa5Bu}!odFn|iezP;826}_%)XvoC1nLAL9-QYYAoki8-K@>BGi%TfIuisn zN>QYJqfK;{q!cH4r_IwYOPZw)(5N(LNVc@|@sKk=^L|t_S~Tl4TZZM9+vFIISGH(I zA`LR{rJ=8(Gtn{Vs~?r0TS(R?hb33>nHB2HmcNyJa9l*M=Rx4x>dLc~>hCe{VMmQr z?{D>_%syWc`_!<)hLObBPo10+of4U3%7`jAQ) z&S|G!CT&BOD0?MMJPn)1kd{znYEA0n@5?G86q)tHyrjHby#~Fu`XI&e^n5z?4n50R zX=n0B^jvvu%%$p0ukWpMnsX^4nIerM!XnlpG^H2H!kNU(&djOI8Kw40Pdkn$AiF8M znI}%Lw2aTMtgw<5v1&ObrHlFU-CFmDi#1E!3MyY159 zZK2L(7E3u=7TG1)_nVBG>_c8Ydjo#&603Wwxgh6yPLt~$*W7Wp6GchI-LkoMxu;+J z;r8_6^<}LId#Uo6EMzh=zVoc*yWSBims)xyozr{TQ%b2=xvu?Q`3Ds0p<(}BwN{Oe zE4hKUHcoM9#@fba2@VT7%Pq=T%FoM*p=40ZwuH*L^3B%wZJFMVZb9u)UK4H=uk(hd zpOh5JkNP()2A$4yEFTuEJ6A_v7mp@V6}BXZ~zq~k2cUpwAC3WbiC~_ij5aE z5u_S+8a+4YGdgQ<*??wXLbH`aRZJSj*~NkLGzG)?XTEydsZhcytV~iWJ6e)n5U^LTxGUoT#`D@r@VQOM(u8d+~cj2G7h|2ZK9z99d z>*c2$6*Z+Bpsh-|FhuQ3T;FHwL-%yLlT1(gqOf&0Z~Qdqn+P6w}O?i%2Yp(M*p8tKbn<4dvljW_Ln*g)tsX`HrI}SZ=6pc zfCX<((^~3ON?Kj&DG|Fl4P3f3p$<(W_ z_r6xuU07(eakanb!h=h2PpE_!JZ?Bs=4I5EKX-pFOe7(5x?%2e)neBB_Mw5MQ9?)$ zLp;-S7Oi9aqV*viYv$f1x`gMhAI2ZH(&z8Z)i!yAIEUyj8ZRf&jUtU6w6`Sq^_}h= zP%ThRRcVP&e(`AHVmoPj>^tJ}q2gI{#oU^8&>zRumOr+yi!I&Z)EErB9#k|dy`8=K z^o`whyPWBXiKqrsEcLWVJSE>c&pi5vJG!o1Y<#mv@{#XwC+W zYjT)rhLwf811|K6YaR(v)d=WL+D4gK zD>J>2e#)@YaL%a2h#t2QH+<>Q%JVN>akQR^$R?SePuJ4Ai?f5NTMZuQ&bBY!-SZjR zXGRJd)i(QA2{Z1WCVQy3rM&#>BgKu{t6|$YTW%}uNwW)P>t<=$@!HfYY(KsRND;8p zqiYf0w&3chU;qHve2h`P0Kjo*_c8#Pw+{mVNE~NnOR+s`s_sT2KwRBPXbdEP-~;R) zjR5rkf)4>haRmnu@I+tr08R0|2z8>b`YsF=2k(VYyfwvb&zge~Br*o93{ir>#I@ML zV6X<+9jks`-|#Ov*&VAX?n$Bes6(MtDiuOigpkM{Pz5zLH7E=Yg~R2^?pS%>KqAF8 zK%VG(;#ZRY=F!Lax{+}{6dZ{N-p%WZCizh`#l?4x{yx9zq~NgsI1zpSYRip8fbKF- z1qclKZ!$~(?tjR3ng1zscl*05A3rjFuP1jmC{hOR9^*^G`|Xavnuw!lDQN69^gH~|M1H9dB!Uka6lI+KR zkGK8DMoSg`mta5myTFW$!w@O1yLJ6t(|+vtc+|fc><9M=c1N#njtjuxZS`>k3~{du zC78zEJNbXa??MC#Pa<3TxVm9>3){=J5BfcN&j$6sZ1xfRgzj$YzJ6#gj2mSi`rmI> z&(#CE57vPGYqUlH!AJcp$sLCc)OV#|wBRrWMR^67JY3BR4pUcvsjDb!K!1zbSHUiW zAY)u9B(fEWgxA{Zg0TAtR)oNQDfjb#Nj0FmTeNSh_K08Td3{4Ib`9v?`>(|w!OS@g z0F1Yh`np!OY>Tu%OONaFw-+n(i5)tKmQkq>P2>6~fSq8gkBKlUM&q zXz{XZSr;j>r>p6Sm)4xK_C1kek2EOW%=Qf~EcGq2gL6)>xGkKfux*}FW^xHW16<>Q z4#`1H{28|xmA0ZDVvpWlR6c7tF#o+fyKCz0L!07l4Ug#oC6}rpM?rRGle*!j3}Z>m z07_2K9s?IXArc>~$kYLgWxkd9CsrW3HHQ(f38x;NF=zT|-F!F-<^rKv0%z)&{gv~k zzHK;Xv%j1Fo_;R>TlOg`v*+EXqf0x2Vf?a+56*W!9>n7TJ+A_J!B{x*iXR;0@lyTLcB=xZw-git3*wwFdJE+e$`VV`m_RLab_)MzJFUSfo zzaAQvzuTqI8@lSt@jXzosIQ2R^MEQqsg6+B6mucQXI3~(4y?r6S)}^aIH-ukNBKRn z6(zxrC3w(`B~~cv@*CU1LI8(qPiRY0OwDvAHDUh~{GtoJ9*Vtc&~n$9-&Rn2pf(bYmm?6^pWg9rKCgxiL?rw^y{pM)Zv% zH|}s>!A&d&n1x9!Hro_qUSSoJ)4z^1(>~x;WX``wX=KxDR%IpOebPAVfJ5Po#@~^Q z_d!?Er+0uhk=0Lz-;s8@)oj|C2^K-gj}?z4R9MMAk7^x9=pb@<5!tDRjejnzT|VH9 z< + + +image/svg+xml + + + + + + + + Mic + Created with Sketch (http://www.bohemiancoding.com/sketch) + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/interface/resources/images/mic.svg b/interface/resources/images/mic.svg index a6dee50740..3329f19647 100644 --- a/interface/resources/images/mic.svg +++ b/interface/resources/images/mic.svg @@ -1,20 +1,105 @@ - - Mic - Created with Sketch (http://www.bohemiancoding.com/sketch) - - - - - - - - - - - - - - - + + +image/svg+xml + + + + + + + + Mic + Created with Sketch (http://www.bohemiancoding.com/sketch) + + + + + + + + + + + + + + \ No newline at end of file diff --git a/interface/resources/images/minus.svg b/interface/resources/images/minus.svg new file mode 100644 index 0000000000..463b24aa4c --- /dev/null +++ b/interface/resources/images/minus.svg @@ -0,0 +1,11 @@ + + + Slice 1 + Created with Sketch (http://www.bohemiancoding.com/sketch) + + + + + + + \ No newline at end of file diff --git a/interface/resources/images/mute.svg b/interface/resources/images/mute.svg deleted file mode 100644 index 1f1b238463..0000000000 --- a/interface/resources/images/mute.svg +++ /dev/null @@ -1,20 +0,0 @@ - - - mute - Created with Sketch (http://www.bohemiancoding.com/sketch) - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/interface/resources/images/plus.svg b/interface/resources/images/plus.svg new file mode 100644 index 0000000000..6efaa31abc --- /dev/null +++ b/interface/resources/images/plus.svg @@ -0,0 +1,12 @@ + + + Slice 1 + Created with Sketch (http://www.bohemiancoding.com/sketch) + + + + + + + + \ No newline at end of file diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index d54cceb245..deaab1ac10 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2503,20 +2503,19 @@ void Application::displayOverlay() { // Audio VU Meter and Mute Icon const int MUTE_ICON_SIZE = 24; const int AUDIO_METER_INSET = 2; - const int AUDIO_METER_WIDTH = MIRROR_VIEW_WIDTH - MUTE_ICON_SIZE - AUDIO_METER_INSET; + const int MUTE_ICON_PADDING = 10; + const int AUDIO_METER_WIDTH = MIRROR_VIEW_WIDTH - MUTE_ICON_SIZE - AUDIO_METER_INSET - MUTE_ICON_PADDING; const int AUDIO_METER_SCALE_WIDTH = AUDIO_METER_WIDTH - 2 * AUDIO_METER_INSET; const int AUDIO_METER_HEIGHT = 8; - const int AUDIO_METER_Y_GAP = 8; - const int AUDIO_METER_X = MIRROR_VIEW_LEFT_PADDING + MUTE_ICON_SIZE + AUDIO_METER_INSET; + const int AUDIO_METER_GAP = 5; + const int AUDIO_METER_X = MIRROR_VIEW_LEFT_PADDING + MUTE_ICON_SIZE + AUDIO_METER_INSET + AUDIO_METER_GAP; int audioMeterY; if (Menu::getInstance()->isOptionChecked(MenuOption::Mirror)) { - audioMeterY = MIRROR_VIEW_HEIGHT + AUDIO_METER_Y_GAP; + audioMeterY = MIRROR_VIEW_HEIGHT + AUDIO_METER_GAP + MUTE_ICON_PADDING; } else { - audioMeterY = AUDIO_METER_Y_GAP; + audioMeterY = AUDIO_METER_GAP + MUTE_ICON_PADDING; } - _audio.renderMuteIcon(MIRROR_VIEW_LEFT_PADDING, audioMeterY); - const float AUDIO_METER_BLUE[] = {0.0, 0.0, 1.0}; const float AUDIO_METER_GREEN[] = {0.0, 1.0, 0.0}; @@ -2545,18 +2544,27 @@ void Application::displayOverlay() { bool isClipping = ((_audio.getTimeSinceLastClip() > 0.f) && (_audio.getTimeSinceLastClip() < CLIPPING_INDICATOR_TIME)); + _audio.renderToolBox(MIRROR_VIEW_LEFT_PADDING + AUDIO_METER_GAP, + audioMeterY, + Menu::getInstance()->isOptionChecked(MenuOption::Mirror)); + glBegin(GL_QUADS); if (isClipping) { glColor3f(1, 0, 0); } else { - glColor3f(0, 0, 0); + glColor3f(0.475f, 0.475f, 0.475f); } + + audioMeterY += AUDIO_METER_HEIGHT; + + glColor3f(0, 0, 0); // Draw audio meter background Quad glVertex2i(AUDIO_METER_X, audioMeterY); glVertex2i(AUDIO_METER_X + AUDIO_METER_WIDTH, audioMeterY); glVertex2i(AUDIO_METER_X + AUDIO_METER_WIDTH, audioMeterY + AUDIO_METER_HEIGHT); glVertex2i(AUDIO_METER_X, audioMeterY + AUDIO_METER_HEIGHT); + if (audioLevel > AUDIO_RED_START) { if (!isClipping) { glColor3fv(AUDIO_METER_RED); @@ -2596,6 +2604,7 @@ void Application::displayOverlay() { glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET); glEnd(); + if (Menu::getInstance()->isOptionChecked(MenuOption::HeadMouse)) { _myAvatar->renderHeadMouse(); } diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 63c683dbb0..4843b2f462 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -86,7 +86,8 @@ Audio::Audio(Oscilloscope* scope, int16_t initialJitterBufferSamples, QObject* p void Audio::init(QGLWidget *parent) { _micTextureId = parent->bindTexture(QImage(Application::resourcesPath() + "images/mic.svg")); - _muteTextureId = parent->bindTexture(QImage(Application::resourcesPath() + "images/mute.svg")); + _muteTextureId = parent->bindTexture(QImage(Application::resourcesPath() + "images/mic-mute.svg")); + _boxTextureId = parent->bindTexture(QImage(Application::resourcesPath() + "images/audio-box.svg")); } void Audio::reset() { @@ -817,13 +818,52 @@ void Audio::handleAudioByteArray(const QByteArray& audioByteArray) { // or send to the mixer and use delayed loopback } -void Audio::renderMuteIcon(int x, int y) { +void Audio::renderToolBox(int x, int y, bool boxed) { - _iconBounds = QRect(x, y, MUTE_ICON_SIZE, MUTE_ICON_SIZE); glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, _micTextureId); - glColor3f(.93f, .93f, .93f); + if (boxed) { + + bool isClipping = ((getTimeSinceLastClip() > 0.f) && (getTimeSinceLastClip() < 1.f)); + const int BOX_LEFT_PADDING = 5; + const int BOX_TOP_PADDING = 10; + const int BOX_WIDTH = 266; + const int BOX_HEIGHT = 44; + + QRect boxBounds = QRect(x - BOX_LEFT_PADDING, y - BOX_TOP_PADDING, BOX_WIDTH, BOX_HEIGHT); + + glBindTexture(GL_TEXTURE_2D, _boxTextureId); + + if (isClipping) { + glColor3f(1.f,0.f,0.f); + } else { + glColor3f(.41f,.41f,.41f); + } + glBegin(GL_QUADS); + + glTexCoord2f(1, 1); + glVertex2f(boxBounds.left(), boxBounds.top()); + + glTexCoord2f(0, 1); + glVertex2f(boxBounds.right(), boxBounds.top()); + + glTexCoord2f(0, 0); + glVertex2f(boxBounds.right(), boxBounds.bottom()); + + glTexCoord2f(1, 0); + glVertex2f(boxBounds.left(), boxBounds.bottom()); + + glEnd(); + } + + _iconBounds = QRect(x, y, MUTE_ICON_SIZE, MUTE_ICON_SIZE); + if (!_muted) { + glBindTexture(GL_TEXTURE_2D, _micTextureId); + } else { + glBindTexture(GL_TEXTURE_2D, _muteTextureId); + } + + glColor3f(1,1,1); glBegin(GL_QUADS); glTexCoord2f(1, 1); @@ -840,25 +880,6 @@ void Audio::renderMuteIcon(int x, int y) { glEnd(); - if (_muted) { - glBindTexture(GL_TEXTURE_2D, _muteTextureId); - glBegin(GL_QUADS); - - glTexCoord2f(1, 1); - glVertex2f(_iconBounds.left(), _iconBounds.top()); - - glTexCoord2f(0, 1); - glVertex2f(_iconBounds.right(), _iconBounds.top()); - - glTexCoord2f(0, 0); - glVertex2f(_iconBounds.right(), _iconBounds.bottom()); - - glTexCoord2f(1, 0); - glVertex2f(_iconBounds.left(), _iconBounds.bottom()); - - glEnd(); - } - glDisable(GL_TEXTURE_2D); } diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 88488922f3..c6a3619865 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -69,7 +69,7 @@ public: void init(QGLWidget *parent = 0); bool mousePressEvent(int x, int y); - void renderMuteIcon(int x, int y); + void renderToolBox(int x, int y, bool boxed); int getNetworkSampleRate() { return SAMPLE_RATE; } int getNetworkBufferLengthSamplesPerChannel() { return NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL; } @@ -161,6 +161,7 @@ private: bool _localEcho; GLuint _micTextureId; GLuint _muteTextureId; + GLuint _boxTextureId; QRect _iconBounds; // Audio callback in class context. diff --git a/interface/src/ui/RearMirrorTools.cpp b/interface/src/ui/RearMirrorTools.cpp index 314fd7157b..07503c8cb2 100644 --- a/interface/src/ui/RearMirrorTools.cpp +++ b/interface/src/ui/RearMirrorTools.cpp @@ -18,9 +18,8 @@ const char SETTINGS_GROUP_NAME[] = "Rear View Tools"; const char ZOOM_LEVEL_SETTINGS[] = "ZoomLevel"; -const int ICON_SIZE = 20; +const int ICON_SIZE = 24; const int ICON_PADDING = 5; -const int MID_ICON_PADDING = 70; RearMirrorTools::RearMirrorTools(QGLWidget* parent, QRect& bounds, QSettings* settings) : _parent(parent), @@ -29,16 +28,19 @@ RearMirrorTools::RearMirrorTools(QGLWidget* parent, QRect& bounds, QSettings* se _fullScreen(false) { _zoomLevel = HEAD; - _closeTextureId = _parent->bindTexture(QImage(Application::resourcesPath() + "images/close.png")); - _resetTextureId = _parent->bindTexture(QImage(Application::resourcesPath() + "images/reset.png")); - _zoomHeadTextureId = _parent->bindTexture(QImage(Application::resourcesPath() + "images/head.png")); - _zoomBodyTextureId = _parent->bindTexture(QImage(Application::resourcesPath() + "images/body.png")); + _closeTextureId = _parent->bindTexture(QImage(Application::resourcesPath() + "images/close.svg")); + + // Disabled for now https://worklist.net/19548 + // _resetTextureId = _parent->bindTexture(QImage(Application::resourcesPath() + "images/reset.png")); + + _zoomHeadTextureId = _parent->bindTexture(QImage(Application::resourcesPath() + "images/plus.svg")); + _zoomBodyTextureId = _parent->bindTexture(QImage(Application::resourcesPath() + "images/minus.svg")); _shrinkIconRect = QRect(ICON_PADDING, ICON_PADDING, ICON_SIZE, ICON_SIZE); _closeIconRect = QRect(_bounds.left() + ICON_PADDING, _bounds.top() + ICON_PADDING, ICON_SIZE, ICON_SIZE); _resetIconRect = QRect(_bounds.width() - ICON_SIZE - ICON_PADDING, _bounds.top() + ICON_PADDING, ICON_SIZE, ICON_SIZE); - _bodyZoomIconRect = QRect(_bounds.width() - MID_ICON_PADDING - ICON_SIZE, _bounds.bottom() - ICON_PADDING - ICON_SIZE, ICON_SIZE, ICON_SIZE); - _headZoomIconRect = QRect(_bounds.left() + MID_ICON_PADDING, _bounds.bottom() - ICON_PADDING - ICON_SIZE, ICON_SIZE, ICON_SIZE); + _bodyZoomIconRect = QRect(_bounds.width() - ICON_SIZE - ICON_PADDING, _bounds.bottom() - ICON_PADDING - ICON_SIZE, ICON_SIZE, ICON_SIZE); + _headZoomIconRect = QRect(_bounds.left() + ICON_PADDING, _bounds.bottom() - ICON_PADDING - ICON_SIZE, ICON_SIZE, ICON_SIZE); settings->beginGroup(SETTINGS_GROUP_NAME); _zoomLevel = loadSetting(settings, ZOOM_LEVEL_SETTINGS, 0) == HEAD ? HEAD : BODY; @@ -55,7 +57,10 @@ void RearMirrorTools::render(bool fullScreen) { _windowed = _bounds.contains(mousePosition.x(), mousePosition.y()); if (_windowed) { displayIcon(_bounds, _closeIconRect, _closeTextureId); - displayIcon(_bounds, _resetIconRect, _resetTextureId); + + // Disabled for now https://worklist.net/19548 + // displayIcon(_bounds, _resetIconRect, _resetTextureId); + displayIcon(_bounds, _headZoomIconRect, _zoomHeadTextureId, _zoomLevel == HEAD); displayIcon(_bounds, _bodyZoomIconRect, _zoomBodyTextureId, _zoomLevel == BODY); } @@ -69,11 +74,13 @@ bool RearMirrorTools::mousePressEvent(int x, int y) { emit closeView(); return true; } - + + /* Disabled for now https://worklist.net/19548 if (_resetIconRect.contains(x, y)) { emit resetView(); return true; } + */ if (_headZoomIconRect.contains(x, y)) { _zoomLevel = HEAD; @@ -84,7 +91,7 @@ bool RearMirrorTools::mousePressEvent(int x, int y) { _zoomLevel = BODY; return true; } - + if (_bounds.contains(x, y)) { _windowed = false; emit restoreView(); @@ -120,7 +127,7 @@ void RearMirrorTools::displayIcon(QRect bounds, QRect iconBounds, GLuint texture glEnable(GL_TEXTURE_2D); if (selected) { - glColor3f(1, 1, 0); + glColor3f(.5f, .5f, .5f); } else { glColor3f(1, 1, 1); } From f969e050cd294bc70924abcbecaba0eecc1d58b9 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 09:59:05 -0700 Subject: [PATCH 246/595] add apache license to shader headers --- interface/resources/shaders/ambient_occlusion.frag | 5 ++++- interface/resources/shaders/ambient_occlusion.vert | 5 ++++- interface/resources/shaders/diffuse.frag | 5 ++++- interface/resources/shaders/glow_add.frag | 5 ++++- interface/resources/shaders/glow_add_separate.frag | 5 ++++- interface/resources/shaders/grid.frag | 5 ++++- interface/resources/shaders/horizontal_blur.frag | 5 ++++- interface/resources/shaders/metavoxel_point.vert | 5 ++++- interface/resources/shaders/model.frag | 5 ++++- interface/resources/shaders/model.vert | 5 ++++- interface/resources/shaders/model_normal_map.frag | 5 ++++- interface/resources/shaders/model_normal_map.vert | 5 ++++- interface/resources/shaders/model_shadow.frag | 5 ++++- interface/resources/shaders/model_shadow.vert | 5 ++++- interface/resources/shaders/occlusion_blur.frag | 5 ++++- interface/resources/shaders/oculus.frag | 11 +++++++---- interface/resources/shaders/passthrough.vert | 11 +++++++++++ interface/resources/shaders/perlin_modulate.frag | 5 ++++- interface/resources/shaders/perlin_modulate.vert | 5 ++++- interface/resources/shaders/point_size.vert | 10 ++++++++++ interface/resources/shaders/shadow_map.frag | 5 ++++- interface/resources/shaders/shadow_map.vert | 5 ++++- interface/resources/shaders/skin_model.vert | 5 ++++- .../resources/shaders/skin_model_normal_map.vert | 5 ++++- interface/resources/shaders/skin_model_shadow.vert | 5 ++++- interface/resources/shaders/vertical_blur.frag | 5 ++++- interface/resources/shaders/vertical_blur_add.frag | 5 ++++- interface/resources/shaders/voxel.geom | 10 ++++++++++ 28 files changed, 134 insertions(+), 28 deletions(-) diff --git a/interface/resources/shaders/ambient_occlusion.frag b/interface/resources/shaders/ambient_occlusion.frag index 6e9ed82d95..512922ca43 100644 --- a/interface/resources/shaders/ambient_occlusion.frag +++ b/interface/resources/shaders/ambient_occlusion.frag @@ -5,7 +5,10 @@ // fragment shader // // Created by Andrzej Kapolka on 7/5/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // the depth texture diff --git a/interface/resources/shaders/ambient_occlusion.vert b/interface/resources/shaders/ambient_occlusion.vert index ca6af718bd..a95a0cda7d 100644 --- a/interface/resources/shaders/ambient_occlusion.vert +++ b/interface/resources/shaders/ambient_occlusion.vert @@ -5,7 +5,10 @@ // vertex shader // // Created by Andrzej Kapolka on 8/16/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // void main(void) { diff --git a/interface/resources/shaders/diffuse.frag b/interface/resources/shaders/diffuse.frag index ebf11dace2..bc88b6598d 100644 --- a/interface/resources/shaders/diffuse.frag +++ b/interface/resources/shaders/diffuse.frag @@ -5,7 +5,10 @@ // fragment shader // // Created by Andrzej Kapolka on 8/14/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // the texture containing the original color diff --git a/interface/resources/shaders/glow_add.frag b/interface/resources/shaders/glow_add.frag index 0947292109..e8a1b504ea 100644 --- a/interface/resources/shaders/glow_add.frag +++ b/interface/resources/shaders/glow_add.frag @@ -5,7 +5,10 @@ // fragment shader // // Created by Andrzej Kapolka on 8/14/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // the texture containing the original color diff --git a/interface/resources/shaders/glow_add_separate.frag b/interface/resources/shaders/glow_add_separate.frag index 7b7f538a03..e798a3b11f 100644 --- a/interface/resources/shaders/glow_add_separate.frag +++ b/interface/resources/shaders/glow_add_separate.frag @@ -5,7 +5,10 @@ // fragment shader // // Created by Andrzej Kapolka on 8/14/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // the texture containing the original color diff --git a/interface/resources/shaders/grid.frag b/interface/resources/shaders/grid.frag index b9e3baccd4..17ad0fed5c 100644 --- a/interface/resources/shaders/grid.frag +++ b/interface/resources/shaders/grid.frag @@ -5,7 +5,10 @@ // fragment shader // // Created by Andrzej Kapolka on 1/21/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // void main(void) { diff --git a/interface/resources/shaders/horizontal_blur.frag b/interface/resources/shaders/horizontal_blur.frag index 695de1a538..916fe4b52d 100644 --- a/interface/resources/shaders/horizontal_blur.frag +++ b/interface/resources/shaders/horizontal_blur.frag @@ -5,7 +5,10 @@ // fragment shader // // Created by Andrzej Kapolka on 8/8/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // the texture containing the original color diff --git a/interface/resources/shaders/metavoxel_point.vert b/interface/resources/shaders/metavoxel_point.vert index b0472088c0..fa585be099 100644 --- a/interface/resources/shaders/metavoxel_point.vert +++ b/interface/resources/shaders/metavoxel_point.vert @@ -5,7 +5,10 @@ // vertex shader // // Created by Andrzej Kapolka on 12/12/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // uniform float pointScale; diff --git a/interface/resources/shaders/model.frag b/interface/resources/shaders/model.frag index e035f9bfe9..29579d07ac 100644 --- a/interface/resources/shaders/model.frag +++ b/interface/resources/shaders/model.frag @@ -5,7 +5,10 @@ // fragment shader // // Created by Andrzej Kapolka on 10/14/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // the diffuse texture diff --git a/interface/resources/shaders/model.vert b/interface/resources/shaders/model.vert index d07a657d25..904e3c2a8b 100644 --- a/interface/resources/shaders/model.vert +++ b/interface/resources/shaders/model.vert @@ -5,7 +5,10 @@ // vertex shader // // Created by Andrzej Kapolka on 10/14/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // the interpolated normal diff --git a/interface/resources/shaders/model_normal_map.frag b/interface/resources/shaders/model_normal_map.frag index 9a0e964500..2a4af2073a 100644 --- a/interface/resources/shaders/model_normal_map.frag +++ b/interface/resources/shaders/model_normal_map.frag @@ -5,7 +5,10 @@ // fragment shader // // Created by Andrzej Kapolka on 10/29/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // the diffuse texture diff --git a/interface/resources/shaders/model_normal_map.vert b/interface/resources/shaders/model_normal_map.vert index c367a30e06..3607501acf 100644 --- a/interface/resources/shaders/model_normal_map.vert +++ b/interface/resources/shaders/model_normal_map.vert @@ -5,7 +5,10 @@ // vertex shader // // Created by Andrzej Kapolka on 10/14/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // the tangent vector diff --git a/interface/resources/shaders/model_shadow.frag b/interface/resources/shaders/model_shadow.frag index bcb597b13c..50a4d3895d 100644 --- a/interface/resources/shaders/model_shadow.frag +++ b/interface/resources/shaders/model_shadow.frag @@ -5,7 +5,10 @@ // fragment shader // // Created by Andrzej Kapolka on 3/24/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // void main(void) { diff --git a/interface/resources/shaders/model_shadow.vert b/interface/resources/shaders/model_shadow.vert index ae7e871887..a18f5fcd5d 100644 --- a/interface/resources/shaders/model_shadow.vert +++ b/interface/resources/shaders/model_shadow.vert @@ -5,7 +5,10 @@ // vertex shader // // Created by Andrzej Kapolka on 3/24/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // void main(void) { diff --git a/interface/resources/shaders/occlusion_blur.frag b/interface/resources/shaders/occlusion_blur.frag index 5b86aec68d..ab4b656e71 100644 --- a/interface/resources/shaders/occlusion_blur.frag +++ b/interface/resources/shaders/occlusion_blur.frag @@ -5,7 +5,10 @@ // fragment shader // // Created by Andrzej Kapolka on 8/16/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // the original texture diff --git a/interface/resources/shaders/oculus.frag b/interface/resources/shaders/oculus.frag index 3e7d1a4c3e..f2b066a974 100644 --- a/interface/resources/shaders/oculus.frag +++ b/interface/resources/shaders/oculus.frag @@ -5,11 +5,14 @@ // fragment shader // // Created by Andrzej Kapolka on 11/26/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. // -// this shader is an adaptation (HLSL -> GLSL, removed conditional) of the one in the Oculus sample -// code (Samples/OculusRoomTiny/RenderTiny_D3D1X_Device.cpp), which is under the Apache license -// (http://www.apache.org/licenses/LICENSE-2.0) +// this shader is an adaptation (HLSL -> GLSL, removed conditional) of the one in the Oculus sample +// code (Samples/OculusRoomTiny/RenderTiny_D3D1X_Device.cpp), which is under the Apache license +// (http://www.apache.org/licenses/LICENSE-2.0) +// +// 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 texture; diff --git a/interface/resources/shaders/passthrough.vert b/interface/resources/shaders/passthrough.vert index f3d5c5b504..bb0a18eefa 100644 --- a/interface/resources/shaders/passthrough.vert +++ b/interface/resources/shaders/passthrough.vert @@ -1,4 +1,15 @@ #version 120 + +// +// passthrough.vert +// vertex shader +// +// Copyright 2013 High Fidelity, Inc. +// +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// attribute float voxelSizeIn; varying float voxelSize; diff --git a/interface/resources/shaders/perlin_modulate.frag b/interface/resources/shaders/perlin_modulate.frag index 8ead57c238..8693b14e1b 100644 --- a/interface/resources/shaders/perlin_modulate.frag +++ b/interface/resources/shaders/perlin_modulate.frag @@ -5,7 +5,10 @@ // fragment shader // // Created by Andrzej Kapolka on 5/15/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // the texture containing our permutations and normals diff --git a/interface/resources/shaders/perlin_modulate.vert b/interface/resources/shaders/perlin_modulate.vert index 5cf87fc5fd..428615017a 100644 --- a/interface/resources/shaders/perlin_modulate.vert +++ b/interface/resources/shaders/perlin_modulate.vert @@ -5,7 +5,10 @@ // vertex shader // // Created by Andrzej Kapolka on 5/15/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // the position in model space diff --git a/interface/resources/shaders/point_size.vert b/interface/resources/shaders/point_size.vert index 9c93385768..88c56bf0c4 100644 --- a/interface/resources/shaders/point_size.vert +++ b/interface/resources/shaders/point_size.vert @@ -1,4 +1,14 @@ #version 120 + +// +// point_size.vert +// vertex shader +// +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// attribute float voxelSizeIn; varying float voxelSize; diff --git a/interface/resources/shaders/shadow_map.frag b/interface/resources/shaders/shadow_map.frag index b683ed5af2..70c459ecf8 100644 --- a/interface/resources/shaders/shadow_map.frag +++ b/interface/resources/shaders/shadow_map.frag @@ -5,7 +5,10 @@ // fragment shader // // Created by Andrzej Kapolka on 11/21/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // uniform sampler2DShadow shadowMap; diff --git a/interface/resources/shaders/shadow_map.vert b/interface/resources/shaders/shadow_map.vert index 6809ca6e2b..abe5f99b44 100644 --- a/interface/resources/shaders/shadow_map.vert +++ b/interface/resources/shaders/shadow_map.vert @@ -5,7 +5,10 @@ // vertex shader // // Created by Andrzej Kapolka on 3/27/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // varying vec4 shadowColor; diff --git a/interface/resources/shaders/skin_model.vert b/interface/resources/shaders/skin_model.vert index 57e3928241..12320ba9a9 100644 --- a/interface/resources/shaders/skin_model.vert +++ b/interface/resources/shaders/skin_model.vert @@ -5,7 +5,10 @@ // vertex shader // // Created by Andrzej Kapolka on 10/14/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // const int MAX_CLUSTERS = 128; diff --git a/interface/resources/shaders/skin_model_normal_map.vert b/interface/resources/shaders/skin_model_normal_map.vert index 97e21dae73..872cbe2fc3 100644 --- a/interface/resources/shaders/skin_model_normal_map.vert +++ b/interface/resources/shaders/skin_model_normal_map.vert @@ -5,7 +5,10 @@ // vertex shader // // Created by Andrzej Kapolka on 10/29/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // const int MAX_CLUSTERS = 128; diff --git a/interface/resources/shaders/skin_model_shadow.vert b/interface/resources/shaders/skin_model_shadow.vert index b9ef05ad8a..6d9d5ebbf5 100644 --- a/interface/resources/shaders/skin_model_shadow.vert +++ b/interface/resources/shaders/skin_model_shadow.vert @@ -5,7 +5,10 @@ // vertex shader // // Created by Andrzej Kapolka on 3/24/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // const int MAX_CLUSTERS = 128; diff --git a/interface/resources/shaders/vertical_blur.frag b/interface/resources/shaders/vertical_blur.frag index 96ab95ea9e..1b8c447cc7 100644 --- a/interface/resources/shaders/vertical_blur.frag +++ b/interface/resources/shaders/vertical_blur.frag @@ -5,7 +5,10 @@ // fragment shader // // Created by Andrzej Kapolka on 8/14/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // the texture containing the horizontally blurred color diff --git a/interface/resources/shaders/vertical_blur_add.frag b/interface/resources/shaders/vertical_blur_add.frag index 5cda2622b4..919e9d1268 100644 --- a/interface/resources/shaders/vertical_blur_add.frag +++ b/interface/resources/shaders/vertical_blur_add.frag @@ -5,7 +5,10 @@ // fragment shader // // Created by Andrzej Kapolka on 8/8/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // the texture containing the original color diff --git a/interface/resources/shaders/voxel.geom b/interface/resources/shaders/voxel.geom index ca8f729542..4c850ed608 100644 --- a/interface/resources/shaders/voxel.geom +++ b/interface/resources/shaders/voxel.geom @@ -1,6 +1,16 @@ #version 120 #extension GL_ARB_geometry_shader4 : enable +// +// voxel.geom +// geometry shader +// +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + // // VOXEL GEOMETRY SHADER // From b8bfe325a029fe78372df7198cf33d8657f4b9f9 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 10:03:26 -0700 Subject: [PATCH 247/595] add back code blow away in regex replacements --- interface/src/Physics.cpp | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/interface/src/Physics.cpp b/interface/src/Physics.cpp index a9f9f6b17d..30ea829c4e 100644 --- a/interface/src/Physics.cpp +++ b/interface/src/Physics.cpp @@ -8,6 +8,29 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include +#include + +#include "Util.h" +#include "world.h" +#include "Physics.h" + +// +// Applies static friction: maxVelocity is the largest velocity for which there +// there is friction, and strength is the amount of friction force applied to reduce +// velocity. +// +void applyStaticFriction(float deltaTime, glm::vec3& velocity, float maxVelocity, float strength) { + float v = glm::length(velocity); + if (v < maxVelocity) { + velocity *= glm::clamp((1.0f - deltaTime * strength * (1.f - v / maxVelocity)), 0.0f, 1.0f); + } +} + +// +// Applies velocity damping, with a strength value for linear and squared velocity damping +// + void applyDamping(float deltaTime, glm::vec3& velocity, float linearStrength, float squaredStrength) { if (squaredStrength == 0.f) { velocity *= glm::clamp(1.f - deltaTime * linearStrength, 0.f, 1.f); @@ -18,5 +41,4 @@ void applyDamping(float deltaTime, glm::vec3& velocity, float linearStrength, fl void applyDampedSpring(float deltaTime, glm::vec3& velocity, glm::vec3& position, glm::vec3& targetPosition, float k, float damping) { -} - +} \ No newline at end of file From b5a641d60f022a1778d4260c2e55b9d97817a8f9 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 10:04:19 -0700 Subject: [PATCH 248/595] add back Util code blown away in merge --- interface/src/Util.cpp | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 4fe5636329..36e39a46a5 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -9,6 +9,38 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include "InterfaceConfig.h" +#include "ui/TextRenderer.h" +#include "VoxelConstants.h" +#include "world.h" + +#include "Util.h" + +using namespace std; + +// no clue which versions are affected... +#define WORKAROUND_BROKEN_GLUT_STROKES +// see http://www.opengl.org/resources/libraries/glut/spec3/node78.html + +void eulerToOrthonormals(glm::vec3 * angles, glm::vec3 * front, glm::vec3 * right, glm::vec3 * up) { + // + // Converts from three euler angles to the associated orthonormal vectors + // + // Angles contains (pitch, yaw, roll) in radians + // + // First, create the quaternion associated with these euler angles glm::quat q(glm::vec3(angles->x, -(angles->y), angles->z)); @@ -597,4 +629,4 @@ bool pointInSphere(glm::vec3& point, glm::vec3& sphereCenter, double sphereRadiu return true; } return false; -} +} \ No newline at end of file From d2c6ea238ee75772f4324885e64ac26c18f300b3 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 10:10:00 -0700 Subject: [PATCH 249/595] repairs to starfield headers --- interface/src/starfield/Config.h | 6 ++++-- interface/src/starfield/Controller.h | 1 + interface/src/starfield/data/GpuVertex.cpp | 1 + interface/src/starfield/data/GpuVertex.h | 1 + interface/src/starfield/data/InputVertex.cpp | 3 ++- interface/src/starfield/data/InputVertex.h | 1 + interface/src/starfield/renderer/Renderer.cpp | 1 + interface/src/starfield/renderer/Renderer.h | 1 + interface/src/starfield/renderer/VertexOrder.cpp | 1 + 9 files changed, 13 insertions(+), 3 deletions(-) diff --git a/interface/src/starfield/Config.h b/interface/src/starfield/Config.h index 6f44f24093..a44006fb17 100755 --- a/interface/src/starfield/Config.h +++ b/interface/src/starfield/Config.h @@ -9,6 +9,9 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#ifndef __interface__starfield__Config__ +#define __interface__starfield__Config__ + #include "InterfaceConfig.h" #include "renderer/ProgramObject.h" @@ -55,5 +58,4 @@ namespace starfield { } -#endif - +#endif \ No newline at end of file diff --git a/interface/src/starfield/Controller.h b/interface/src/starfield/Controller.h index 12963fa2e2..b994d48580 100755 --- a/interface/src/starfield/Controller.h +++ b/interface/src/starfield/Controller.h @@ -3,6 +3,7 @@ // interface/src/starfield // // Created by Tobias Schwinger on 3/29/13. +// Modified by Chris Barnard on 10/16/13. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. diff --git a/interface/src/starfield/data/GpuVertex.cpp b/interface/src/starfield/data/GpuVertex.cpp index 5c1a8ea711..b7fee1f2b1 100755 --- a/interface/src/starfield/data/GpuVertex.cpp +++ b/interface/src/starfield/data/GpuVertex.cpp @@ -3,6 +3,7 @@ // interface/src/starfield/data // // Created by Chris Barnard on 10/17/13. +// Based on code by Tobias Schwinger on 3/29/13. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. diff --git a/interface/src/starfield/data/GpuVertex.h b/interface/src/starfield/data/GpuVertex.h index 7c435a559f..71cef97061 100755 --- a/interface/src/starfield/data/GpuVertex.h +++ b/interface/src/starfield/data/GpuVertex.h @@ -3,6 +3,7 @@ // interface/src/starfield/data // // Created by Tobias Schwinger on 3/29/13. +// Modified by Chris Barnard on 10/17/13. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. diff --git a/interface/src/starfield/data/InputVertex.cpp b/interface/src/starfield/data/InputVertex.cpp index ffb7e725fc..5dead34beb 100755 --- a/interface/src/starfield/data/InputVertex.cpp +++ b/interface/src/starfield/data/InputVertex.cpp @@ -2,7 +2,8 @@ // InputVertex.cpp // interface/src/starfield/data // -// Created by Chris Barnard on 10/17. +// Created by Chris Barnard on 10/17/13. +// Based on code by Tobias Schwinger 3/29/13. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. diff --git a/interface/src/starfield/data/InputVertex.h b/interface/src/starfield/data/InputVertex.h index 01b15c297f..f78f3ea136 100755 --- a/interface/src/starfield/data/InputVertex.h +++ b/interface/src/starfield/data/InputVertex.h @@ -3,6 +3,7 @@ // interface/src/starfield/data // // Created by Tobias Schwinger on 3/29/13. +// Modified by Chris Barnard on 10/17/13. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. diff --git a/interface/src/starfield/renderer/Renderer.cpp b/interface/src/starfield/renderer/Renderer.cpp index c571cb0977..034a571814 100755 --- a/interface/src/starfield/renderer/Renderer.cpp +++ b/interface/src/starfield/renderer/Renderer.cpp @@ -3,6 +3,7 @@ // interface/src/starfield/renderer // // Created by Chris Barnard on 10/17/13. +// Based on earlier work by Tobias Schwinger 3/22/13. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. diff --git a/interface/src/starfield/renderer/Renderer.h b/interface/src/starfield/renderer/Renderer.h index 8b75f4e953..2494377180 100755 --- a/interface/src/starfield/renderer/Renderer.h +++ b/interface/src/starfield/renderer/Renderer.h @@ -3,6 +3,7 @@ // interface/src/starfield/renderer // // Created by Tobias Schwinger on 3/22/13. +// Modified by Chris Barnard on 10/17/13. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. diff --git a/interface/src/starfield/renderer/VertexOrder.cpp b/interface/src/starfield/renderer/VertexOrder.cpp index baffb81f4e..ec36f1eea2 100755 --- a/interface/src/starfield/renderer/VertexOrder.cpp +++ b/interface/src/starfield/renderer/VertexOrder.cpp @@ -3,6 +3,7 @@ // interface/src/starfield/renderer // // Created by Chris Barnard on 10/17/13. +// Based on code by Tobias Schwinger on 3/22/13. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. From 86d236faef58bcd6be422885d809f6798112a7cf Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 10:11:04 -0700 Subject: [PATCH 250/595] repairs to date and author name in RearMirrorTools --- interface/src/ui/RearMirrorTools.cpp | 2 +- interface/src/ui/RearMirrorTools.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/ui/RearMirrorTools.cpp b/interface/src/ui/RearMirrorTools.cpp index e52d59e81a..d416805e6f 100644 --- a/interface/src/ui/RearMirrorTools.cpp +++ b/interface/src/ui/RearMirrorTools.cpp @@ -2,7 +2,7 @@ // RearMirrorTools.cpp // interface/src/ui // -// Created by stojce on 23. +// Created by Stojce Slavkovski on 10/23/2013. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. diff --git a/interface/src/ui/RearMirrorTools.h b/interface/src/ui/RearMirrorTools.h index 6230771b4b..a25aeec1bd 100644 --- a/interface/src/ui/RearMirrorTools.h +++ b/interface/src/ui/RearMirrorTools.h @@ -2,7 +2,7 @@ // RearMirrorTools.h // interface/src/ui // -// Created by stojce on 10/23/2013. +// Created by Stojce Slavkovski on 10/23/2013. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. From 11c235a29e6b1acdaa3ae444f78db6b5504cffbb Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 10:16:56 -0700 Subject: [PATCH 251/595] fixes to source files for code remove in regex replace --- libraries/octree/src/CoverageMap.cpp | 37 +++- libraries/shared/src/GeometryUtil.cpp | 293 +++++++++++++++++++++++++- 2 files changed, 328 insertions(+), 2 deletions(-) diff --git a/libraries/octree/src/CoverageMap.cpp b/libraries/octree/src/CoverageMap.cpp index 88d2292812..65d5734b68 100644 --- a/libraries/octree/src/CoverageMap.cpp +++ b/libraries/octree/src/CoverageMap.cpp @@ -9,6 +9,41 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include + +#include + +#include + +#include "CoverageMap.h" + +int CoverageMap::_mapCount = 0; +int CoverageMap::_checkMapRootCalls = 0; +int CoverageMap::_notAllInView = 0; +bool CoverageMap::wantDebugging = false; + +const int MAX_POLYGONS_PER_REGION = 50; + +const BoundingBox CoverageMap::ROOT_BOUNDING_BOX = BoundingBox(glm::vec2(-1.f,-1.f), glm::vec2(2.f,2.f)); + +// Coverage Map's polygon coordinates are from -1 to 1 in the following mapping to screen space. +// +// (0,0) (windowWidth, 0) +// -1,1 1,1 +// +-----------------------+ +// | | | +// | | | +// | -1,0 | | +// |-----------+-----------| +// | 0,0 | +// | | | +// | | | +// | | | +// +-----------------------+ +// -1,-1 1,-1 +// (0,windowHeight) (windowWidth,windowHeight) +// + // Choosing a minimum sized polygon. Since we know a typical window is approximately 1500 pixels wide // then a pixel on our screen will be ~ 2.0/1500 or 0.0013 "units" wide, similarly pixels are typically // about that tall as well. If we say that polygons should be at least 10x10 pixels to be considered "big enough" @@ -523,4 +558,4 @@ CoverageMapStorageResult CoverageRegion::checkRegion(OctreeProjectedPolygon* pol } } return result; -} +} \ No newline at end of file diff --git a/libraries/shared/src/GeometryUtil.cpp b/libraries/shared/src/GeometryUtil.cpp index d586dad90e..cb2e829811 100644 --- a/libraries/shared/src/GeometryUtil.cpp +++ b/libraries/shared/src/GeometryUtil.cpp @@ -9,6 +9,297 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include +#include + +#include "SharedUtil.h" +#include "GeometryUtil.h" + +glm::vec3 computeVectorFromPointToSegment(const glm::vec3& point, const glm::vec3& start, const glm::vec3& end) { + // compute the projection of the point vector onto the segment vector + glm::vec3 segmentVector = end - start; + float lengthSquared = glm::dot(segmentVector, segmentVector); + if (lengthSquared < EPSILON) { + return start - point; // start and end the same + } + float proj = glm::dot(point - start, segmentVector) / lengthSquared; + if (proj <= 0.0f) { // closest to the start + return start - point; + + } else if (proj >= 1.0f) { // closest to the end + return end - point; + + } else { // closest to the middle + return start + segmentVector*proj - point; + } +} + +// Computes the penetration between a point and a sphere (centered at the origin) +// if point is inside sphere: returns true and stores the result in 'penetration' +// (the vector that would move the point outside the sphere) +// otherwise returns false +bool findSpherePenetration(const glm::vec3& point, const glm::vec3& defaultDirection, float sphereRadius, + glm::vec3& penetration) { + float vectorLength = glm::length(point); + if (vectorLength < EPSILON) { + penetration = defaultDirection * sphereRadius; + return true; + } + float distance = vectorLength - sphereRadius; + if (distance < 0.0f) { + penetration = point * (-distance / vectorLength); + return true; + } + return false; +} + +bool findSpherePointPenetration(const glm::vec3& sphereCenter, float sphereRadius, + const glm::vec3& point, glm::vec3& penetration) { + return findSpherePenetration(point - sphereCenter, glm::vec3(0.0f, -1.0f, 0.0f), sphereRadius, penetration); +} + +bool findPointSpherePenetration(const glm::vec3& point, const glm::vec3& sphereCenter, + float sphereRadius, glm::vec3& penetration) { + return findSpherePenetration(sphereCenter - point, glm::vec3(0.0f, -1.0f, 0.0f), sphereRadius, penetration); +} + +bool findSphereSpherePenetration(const glm::vec3& firstCenter, float firstRadius, + const glm::vec3& secondCenter, float secondRadius, glm::vec3& penetration) { + return findSpherePointPenetration(firstCenter, firstRadius + secondRadius, secondCenter, penetration); +} + +bool findSphereSegmentPenetration(const glm::vec3& sphereCenter, float sphereRadius, + const glm::vec3& segmentStart, const glm::vec3& segmentEnd, glm::vec3& penetration) { + return findSpherePenetration(computeVectorFromPointToSegment(sphereCenter, segmentStart, segmentEnd), + glm::vec3(0.0f, -1.0f, 0.0f), sphereRadius, penetration); +} + +bool findSphereCapsulePenetration(const glm::vec3& sphereCenter, float sphereRadius, const glm::vec3& capsuleStart, + const glm::vec3& capsuleEnd, float capsuleRadius, glm::vec3& penetration) { + return findSphereSegmentPenetration(sphereCenter, sphereRadius + capsuleRadius, + capsuleStart, capsuleEnd, penetration); +} + +bool findPointCapsuleConePenetration(const glm::vec3& point, const glm::vec3& capsuleStart, + const glm::vec3& capsuleEnd, float startRadius, float endRadius, glm::vec3& penetration) { + // compute the projection of the point vector onto the segment vector + glm::vec3 segmentVector = capsuleEnd - capsuleStart; + float lengthSquared = glm::dot(segmentVector, segmentVector); + if (lengthSquared < EPSILON) { // start and end the same + return findPointSpherePenetration(point, capsuleStart, + glm::max(startRadius, endRadius), penetration); + } + float proj = glm::dot(point - capsuleStart, segmentVector) / lengthSquared; + if (proj <= 0.0f) { // closest to the start + return findPointSpherePenetration(point, capsuleStart, startRadius, penetration); + + } else if (proj >= 1.0f) { // closest to the end + return findPointSpherePenetration(point, capsuleEnd, endRadius, penetration); + + } else { // closest to the middle + return findPointSpherePenetration(point, capsuleStart + segmentVector * proj, + glm::mix(startRadius, endRadius, proj), penetration); + } +} + +bool findSphereCapsuleConePenetration(const glm::vec3& sphereCenter, + float sphereRadius, const glm::vec3& capsuleStart, const glm::vec3& capsuleEnd, + float startRadius, float endRadius, glm::vec3& penetration) { + return findPointCapsuleConePenetration(sphereCenter, capsuleStart, capsuleEnd, + startRadius + sphereRadius, endRadius + sphereRadius, penetration); +} + +bool findSpherePlanePenetration(const glm::vec3& sphereCenter, float sphereRadius, + const glm::vec4& plane, glm::vec3& penetration) { + float distance = glm::dot(plane, glm::vec4(sphereCenter, 1.0f)) - sphereRadius; + if (distance < 0.0f) { + penetration = glm::vec3(plane) * distance; + return true; + } + return false; +} + +bool findSphereDiskPenetration(const glm::vec3& sphereCenter, float sphereRadius, + const glm::vec3& diskCenter, float diskRadius, float diskThickness, const glm::vec3& diskNormal, + glm::vec3& penetration) { + glm::vec3 localCenter = sphereCenter - diskCenter; + float axialDistance = glm::dot(localCenter, diskNormal); + if (std::fabs(axialDistance) < (sphereRadius + 0.5f * diskThickness)) { + // sphere hit the plane, but does it hit the disk? + // Note: this algorithm ignores edge hits. + glm::vec3 axialOffset = axialDistance * diskNormal; + if (glm::length(localCenter - axialOffset) < diskRadius) { + // yes, hit the disk + penetration = (std::fabs(axialDistance) - (sphereRadius + 0.5f * diskThickness) ) * diskNormal; + if (axialDistance < 0.f) { + // hit the backside of the disk, so negate penetration vector + penetration *= -1.f; + } + return true; + } + } + return false; +} + +bool findCapsuleSpherePenetration(const glm::vec3& capsuleStart, const glm::vec3& capsuleEnd, float capsuleRadius, + const glm::vec3& sphereCenter, float sphereRadius, glm::vec3& penetration) { + if (findSphereCapsulePenetration(sphereCenter, sphereRadius, + capsuleStart, capsuleEnd, capsuleRadius, penetration)) { + penetration = -penetration; + return true; + } + return false; +} + +bool findCapsulePlanePenetration(const glm::vec3& capsuleStart, const glm::vec3& capsuleEnd, float capsuleRadius, + const glm::vec4& plane, glm::vec3& penetration) { + float distance = glm::min(glm::dot(plane, glm::vec4(capsuleStart, 1.0f)), + glm::dot(plane, glm::vec4(capsuleEnd, 1.0f))) - capsuleRadius; + if (distance < 0.0f) { + penetration = glm::vec3(plane) * distance; + return true; + } + return false; +} + +glm::vec3 addPenetrations(const glm::vec3& currentPenetration, const glm::vec3& newPenetration) { + // find the component of the new penetration in the direction of the current + float currentLength = glm::length(currentPenetration); + if (currentLength == 0.0f) { + return newPenetration; + } + glm::vec3 currentDirection = currentPenetration / currentLength; + float directionalComponent = glm::dot(newPenetration, currentDirection); + + // if orthogonal or in the opposite direction, we can simply add + if (directionalComponent <= 0.0f) { + return currentPenetration + newPenetration; + } + + // otherwise, we need to take the maximum component of current and new + return currentDirection * glm::max(directionalComponent, currentLength) + + newPenetration - (currentDirection * directionalComponent); +} + +bool findRaySphereIntersection(const glm::vec3& origin, const glm::vec3& direction, + const glm::vec3& center, float radius, float& distance) { + glm::vec3 relativeOrigin = origin - center; + float c = glm::dot(relativeOrigin, relativeOrigin) - radius * radius; + if (c < 0.0f) { + distance = 0.0f; + return true; // starts inside the sphere + } + float b = glm::dot(direction, relativeOrigin); + float radicand = b * b - c; + if (radicand < 0.0f) { + return false; // doesn't hit the sphere + } + float t = -b - sqrtf(radicand); + if (t < 0.0f) { + return false; // doesn't hit the sphere + } + distance = t; + return true; +} + +bool findRayCapsuleIntersection(const glm::vec3& origin, const glm::vec3& direction, + const glm::vec3& start, const glm::vec3& end, float radius, float& distance) { + if (start == end) { + return findRaySphereIntersection(origin, direction, start, radius, distance); // handle degenerate case + } + glm::vec3 relativeOrigin = origin - start; + glm::vec3 relativeEnd = end - start; + float capsuleLength = glm::length(relativeEnd); + relativeEnd /= capsuleLength; + float originProjection = glm::dot(relativeEnd, relativeOrigin); + glm::vec3 constant = relativeOrigin - relativeEnd * originProjection; + float c = glm::dot(constant, constant) - radius * radius; + if (c < 0.0f) { // starts inside cylinder + if (originProjection < 0.0f) { // below start + return findRaySphereIntersection(origin, direction, start, radius, distance); + + } else if (originProjection > capsuleLength) { // above end + return findRaySphereIntersection(origin, direction, end, radius, distance); + + } else { // between start and end + distance = 0.0f; + return true; + } + } + glm::vec3 coefficient = direction - relativeEnd * glm::dot(relativeEnd, direction); + float a = glm::dot(coefficient, coefficient); + if (a == 0.0f) { + return false; // parallel to enclosing cylinder + } + float b = 2.0f * glm::dot(constant, coefficient); + float radicand = b * b - 4.0f * a * c; + if (radicand < 0.0f) { + return false; // doesn't hit the enclosing cylinder + } + float t = (-b - sqrtf(radicand)) / (2.0f * a); + if (t < 0.0f) { + return false; // doesn't hit the enclosing cylinder + } + glm::vec3 intersection = relativeOrigin + direction * t; + float intersectionProjection = glm::dot(relativeEnd, intersection); + if (intersectionProjection < 0.0f) { // below start + return findRaySphereIntersection(origin, direction, start, radius, distance); + + } else if (intersectionProjection > capsuleLength) { // above end + return findRaySphereIntersection(origin, direction, end, radius, distance); + } + distance = t; // between start and end + return true; +} + +// Do line segments (r1p1.x, r1p1.y)--(r1p2.x, r1p2.y) and (r2p1.x, r2p1.y)--(r2p2.x, r2p2.y) intersect? +// from: http://ptspts.blogspot.com/2010/06/how-to-determine-if-two-line-segments.html +bool doLineSegmentsIntersect(glm::vec2 r1p1, glm::vec2 r1p2, glm::vec2 r2p1, glm::vec2 r2p2) { + int d1 = computeDirection(r2p1.x, r2p1.y, r2p2.x, r2p2.y, r1p1.x, r1p1.y); + int d2 = computeDirection(r2p1.x, r2p1.y, r2p2.x, r2p2.y, r1p2.x, r1p2.y); + int d3 = computeDirection(r1p1.x, r1p1.y, r1p2.x, r1p2.y, r2p1.x, r2p1.y); + int d4 = computeDirection(r1p1.x, r1p1.y, r1p2.x, r1p2.y, r2p2.x, r2p2.y); + return (((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) && + ((d3 > 0 && d4 < 0) || (d3 < 0 && d4 > 0))) || + (d1 == 0 && isOnSegment(r2p1.x, r2p1.y, r2p2.x, r2p2.y, r1p1.x, r1p1.y)) || + (d2 == 0 && isOnSegment(r2p1.x, r2p1.y, r2p2.x, r2p2.y, r1p2.x, r1p2.y)) || + (d3 == 0 && isOnSegment(r1p1.x, r1p1.y, r1p2.x, r1p2.y, r2p1.x, r2p1.y)) || + (d4 == 0 && isOnSegment(r1p1.x, r1p1.y, r1p2.x, r1p2.y, r2p2.x, r2p2.y)); +} + +bool isOnSegment(float xi, float yi, float xj, float yj, float xk, float yk) { + return (xi <= xk || xj <= xk) && (xk <= xi || xk <= xj) && + (yi <= yk || yj <= yk) && (yk <= yi || yk <= yj); +} + +int computeDirection(float xi, float yi, float xj, float yj, float xk, float yk) { + float a = (xk - xi) * (yj - yi); + float b = (xj - xi) * (yk - yi); + return a < b ? -1 : a > b ? 1 : 0; +} + + +// +// Polygon Clipping routines inspired by, pseudo code found here: http://www.cs.rit.edu/~icss571/clipTrans/PolyClipBack.html +// +// Coverage Map's polygon coordinates are from -1 to 1 in the following mapping to screen space. +// +// (0,0) (windowWidth, 0) +// -1,1 1,1 +// +-----------------------+ +// | | | +// | | | +// | -1,0 | | +// |-----------+-----------| +// | 0,0 | +// | | | +// | | | +// | | | +// +-----------------------+ +// -1,-1 1,-1 +// (0,windowHeight) (windowWidth,windowHeight) +// + const float PolygonClip::TOP_OF_CLIPPING_WINDOW = 1.0f; const float PolygonClip::BOTTOM_OF_CLIPPING_WINDOW = -1.0f; const float PolygonClip::LEFT_OF_CLIPPING_WINDOW = -1.0f; @@ -175,4 +466,4 @@ void PolygonClip::copyCleanArray(int& lengthA, glm::vec2* vertexArrayA, int& len vertexArrayA[i] = vertexArrayB[i]; } } -} +} \ No newline at end of file From 2d755adfc05f623a8fe33b132c93222bf7ac3278 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 10:46:20 -0700 Subject: [PATCH 252/595] repairs to good code blown away by regex --- assignment-client/src/avatars/AvatarMixer.h | 3 + interface/src/Audio.cpp | 75 +++++++-- libraries/audio/src/Sound.cpp | 158 +++++++++++++++++- .../embedded-webserver/src/HTTPConnection.h | 4 + libraries/octree/src/CoverageMap.h | 2 + libraries/octree/src/CoverageMapV2.cpp | 36 +++- libraries/script-engine/src/Vec3.h | 2 + libraries/shared/src/CapsuleShape.cpp | 2 +- libraries/shared/src/CollisionInfo.cpp | 2 +- libraries/shared/src/CollisionInfo.h | 2 +- libraries/shared/src/ListShape.cpp | 2 +- libraries/shared/src/PacketSender.h | 2 + libraries/shared/src/ShapeCollider.cpp | 2 +- libraries/shared/src/ShapeCollider.h | 2 +- 14 files changed, 261 insertions(+), 33 deletions(-) diff --git a/assignment-client/src/avatars/AvatarMixer.h b/assignment-client/src/avatars/AvatarMixer.h index af25a6f0e2..b9add245a6 100644 --- a/assignment-client/src/avatars/AvatarMixer.h +++ b/assignment-client/src/avatars/AvatarMixer.h @@ -5,6 +5,9 @@ // Created by Stephen Birarda on 9/5/13. // Copyright 2013 High Fidelity, Inc. // +// The avatar mixer receives head, hand and positional data from all connected +// nodes, and broadcasts that data back to them, every BROADCAST_INTERVAL ms. +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 719bfd8aa1..90797c7eef 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -18,6 +18,15 @@ #include #endif +#ifdef WIN32 +#define WIN32_LEAN_AND_MEAN +#include +#include +#include +#include +#include +#endif + #include #include #include @@ -150,24 +159,56 @@ QAudioDeviceInfo defaultAudioDeviceForMode(QAudio::Mode mode) { #endif #ifdef WIN32 QString deviceName; - if (mode == QAudio::AudioInput) { - WAVEINCAPS wic; - // first use WAVE_MAPPER to get the default devices manufacturer ID - waveInGetDevCaps(WAVE_MAPPER, &wic, sizeof(wic)); - //Use the received manufacturer id to get the device's real name - waveInGetDevCaps(wic.wMid, &wic, sizeof(wic)); - qDebug() << "input device:" << wic.szPname; - deviceName = wic.szPname; + //Check for Windows Vista or higher, IMMDeviceEnumerator doesn't work below that. + OSVERSIONINFO osvi; + ZeroMemory(&osvi, sizeof(OSVERSIONINFO)); + osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + GetVersionEx(&osvi); + const DWORD VISTA_MAJOR_VERSION = 6; + if (osvi.dwMajorVersion < VISTA_MAJOR_VERSION) {// lower then vista + if (mode == QAudio::AudioInput) { + WAVEINCAPS wic; + // first use WAVE_MAPPER to get the default devices manufacturer ID + waveInGetDevCaps(WAVE_MAPPER, &wic, sizeof(wic)); + //Use the received manufacturer id to get the device's real name + waveInGetDevCaps(wic.wMid, &wic, sizeof(wic)); + qDebug() << "input device:" << wic.szPname; + deviceName = wic.szPname; + } else { + WAVEOUTCAPS woc; + // first use WAVE_MAPPER to get the default devices manufacturer ID + waveOutGetDevCaps(WAVE_MAPPER, &woc, sizeof(woc)); + //Use the received manufacturer id to get the device's real name + waveOutGetDevCaps(woc.wMid, &woc, sizeof(woc)); + qDebug() << "output device:" << woc.szPname; + deviceName = woc.szPname; + } } else { - WAVEOUTCAPS woc; - // first use WAVE_MAPPER to get the default devices manufacturer ID - waveOutGetDevCaps(WAVE_MAPPER, &woc, sizeof(woc)); - //Use the received manufacturer id to get the device's real name - waveOutGetDevCaps(woc.wMid, &woc, sizeof(woc)); - qDebug() << "output device:" << woc.szPname; - deviceName = woc.szPname; + HRESULT hr = S_OK; + CoInitialize(NULL); + IMMDeviceEnumerator* pMMDeviceEnumerator = NULL; + CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&pMMDeviceEnumerator); + IMMDevice* pEndpoint; + pMMDeviceEnumerator->GetDefaultAudioEndpoint(mode == QAudio::AudioOutput ? eRender : eCapture, eMultimedia, &pEndpoint); + IPropertyStore* pPropertyStore; + pEndpoint->OpenPropertyStore(STGM_READ, &pPropertyStore); + pEndpoint->Release(); + pEndpoint = NULL; + PROPVARIANT pv; + PropVariantInit(&pv); + hr = pPropertyStore->GetValue(PKEY_Device_FriendlyName, &pv); + pPropertyStore->Release(); + pPropertyStore = NULL; + //QAudio devices seems to only take the 31 first characters of the Friendly Device Name. + const DWORD QT_WIN_MAX_AUDIO_DEVICENAME_LEN = 31; + deviceName = QString::fromWCharArray((wchar_t*)pv.pwszVal).left(QT_WIN_MAX_AUDIO_DEVICENAME_LEN); + qDebug() << (mode == QAudio::AudioOutput ? "output" : "input") << " device:" << deviceName; + PropVariantClear(&pv); + pMMDeviceEnumerator->Release(); + pMMDeviceEnumerator = NULL; + CoUninitialize(); } - qDebug() << "DEBUG [" << deviceName << "] [" << getNamedAudioDeviceForMode(mode, deviceName).deviceName() << "]"; + qDebug() << "DEBUG [" << deviceName << "] [" << getNamedAudioDeviceForMode(mode, deviceName).deviceName() << "]"; return getNamedAudioDeviceForMode(mode, deviceName); #endif @@ -988,4 +1029,4 @@ float Audio::calculateDeviceToNetworkInputRatio(int numBytes) { int Audio::calculateNumberOfFrameSamples(int numBytes) { int frameSamples = (int)(numBytes * CALLBACK_ACCELERATOR_RATIO + 0.5f) / sizeof(int16_t); return frameSamples; -} +} \ No newline at end of file diff --git a/libraries/audio/src/Sound.cpp b/libraries/audio/src/Sound.cpp index 4e657f3302..420576ece9 100644 --- a/libraries/audio/src/Sound.cpp +++ b/libraries/audio/src/Sound.cpp @@ -9,20 +9,162 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -struct chunk +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include "AudioRingBuffer.h" +#include "Sound.h" + +// procedural audio version of Sound +Sound::Sound(float volume, float frequency, float duration, float decay, QObject* parent) : + QObject(parent) { + static char monoAudioData[MAX_PACKET_SIZE]; + static int16_t* monoAudioSamples = (int16_t*)(monoAudioData); + + float t; + const float AUDIO_CALLBACK_MSECS = (float) NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL / (float)SAMPLE_RATE * 1000.0; + const float MAX_VOLUME = 32000.f; + const float MAX_DURATION = 2.f; + const float MIN_AUDIBLE_VOLUME = 0.001f; + const float NOISE_MAGNITUDE = 0.02f; + const int MAX_SAMPLE_VALUE = std::numeric_limits::max(); + const int MIN_SAMPLE_VALUE = std::numeric_limits::min(); + int numSamples = NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL; // we add sounds in chunks of this many samples + + int chunkStartingSample = 0; + float waveFrequency = (frequency / SAMPLE_RATE) * TWO_PI; + while (volume > 0.f) { + for (int i = 0; i < numSamples; i++) { + t = (float)chunkStartingSample + (float)i; + float sample = sinf(t * waveFrequency); + sample += ((randFloat() - 0.5f) * NOISE_MAGNITUDE); + sample *= volume * MAX_VOLUME; + + monoAudioSamples[i] = glm::clamp((int)sample, MIN_SAMPLE_VALUE, MAX_SAMPLE_VALUE); + volume *= (1.f - decay); + } + // add the monoAudioSamples to our actual output Byte Array + _byteArray.append(monoAudioData, numSamples * sizeof(int16_t)); + chunkStartingSample += numSamples; + duration = glm::clamp(duration - (AUDIO_CALLBACK_MSECS / 1000.f), 0.f, MAX_DURATION); + //qDebug() << "decaying... _duration=" << _duration; + if (duration == 0.f || (volume < MIN_AUDIBLE_VOLUME)) { + volume = 0.f; + } + } +} + +Sound::Sound(const QUrl& sampleURL, QObject* parent) : + QObject(parent) +{ + // assume we have a QApplication or QCoreApplication instance and use the + // QNetworkAccess manager to grab the raw audio file at the given URL + + QNetworkAccessManager *manager = new QNetworkAccessManager(this); + connect(manager, SIGNAL(finished(QNetworkReply*)), + this, SLOT(replyFinished(QNetworkReply*))); + + qDebug() << "Requesting audio file" << sampleURL.toDisplayString(); + manager->get(QNetworkRequest(sampleURL)); +} + +void Sound::replyFinished(QNetworkReply* reply) { + + // replace our byte array with the downloaded data + QByteArray rawAudioByteArray = reply->readAll(); + + // foreach(QByteArray b, reply->rawHeaderList()) + // qDebug() << b.constData() << ": " << reply->rawHeader(b).constData(); + + if (reply->hasRawHeader("Content-Type")) { + + QByteArray headerContentType = reply->rawHeader("Content-Type"); + + // WAV audio file encountered + if (headerContentType == "audio/x-wav" + || headerContentType == "audio/wav" + || headerContentType == "audio/wave") { + + QByteArray outputAudioByteArray; + + interpretAsWav(rawAudioByteArray, outputAudioByteArray); + downSample(outputAudioByteArray); + } else { + // Process as RAW file + downSample(rawAudioByteArray); + } + } else { + qDebug() << "Network reply without 'Content-Type'."; + } +} + +void Sound::downSample(const QByteArray& rawAudioByteArray) { + + // assume that this was a RAW file and is now an array of samples that are + // signed, 16-bit, 48Khz, mono + + // we want to convert it to the format that the audio-mixer wants + // which is signed, 16-bit, 24Khz, mono + + _byteArray.resize(rawAudioByteArray.size() / 2); + + int numSourceSamples = rawAudioByteArray.size() / sizeof(int16_t); + int16_t* sourceSamples = (int16_t*) rawAudioByteArray.data(); + int16_t* destinationSamples = (int16_t*) _byteArray.data(); + + for (int i = 1; i < numSourceSamples; i += 2) { + if (i + 1 >= numSourceSamples) { + destinationSamples[(i - 1) / 2] = (sourceSamples[i - 1] / 2) + (sourceSamples[i] / 2); + } else { + destinationSamples[(i - 1) / 2] = (sourceSamples[i - 1] / 4) + (sourceSamples[i] / 2) + (sourceSamples[i + 1] / 4); + } + } +} + +// +// Format description from https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ +// +// The header for a WAV file looks like this: +// Positions Sample Value Description +// 00-03 "RIFF" Marks the file as a riff file. Characters are each 1 byte long. +// 04-07 File size (int) Size of the overall file - 8 bytes, in bytes (32-bit integer). +// 08-11 "WAVE" File Type Header. For our purposes, it always equals "WAVE". +// 12-15 "fmt " Format chunk marker. +// 16-19 16 Length of format data as listed above +// 20-21 1 Type of format: (1=PCM, 257=Mu-Law, 258=A-Law, 259=ADPCM) - 2 byte integer +// 22-23 2 Number of Channels - 2 byte integer +// 24-27 44100 Sample Rate - 32 byte integer. Sample Rate = Number of Samples per second, or Hertz. +// 28-31 176400 (Sample Rate * BitsPerSample * Channels) / 8. +// 32-33 4 (BitsPerSample * Channels) / 8 - 8 bit mono2 - 8 bit stereo/16 bit mono4 - 16 bit stereo +// 34-35 16 Bits per sample +// 36-39 "data" Chunk header. Marks the beginning of the data section. +// 40-43 File size (int) Size of the data section. +// 44-?? Actual sound data +// Sample values are given above for a 16-bit stereo source. +// + +struct chunk { char id[4]; quint32 size; }; -struct RIFFHeader -{ +struct RIFFHeader { chunk descriptor; // "RIFF" char type[4]; // "WAVE" }; -struct WAVEHeader -{ +struct WAVEHeader { chunk descriptor; quint16 audioFormat; // Format type: 1=PCM, 257=Mu-Law, 258=A-Law, 259=ADPCM quint16 numChannels; // Number of channels: 1=mono, 2=stereo @@ -32,13 +174,11 @@ struct WAVEHeader quint16 bitsPerSample; }; -struct DATAHeader -{ +struct DATAHeader { chunk descriptor; }; -struct CombinedHeader -{ +struct CombinedHeader { RIFFHeader riff; WAVEHeader wave; }; diff --git a/libraries/embedded-webserver/src/HTTPConnection.h b/libraries/embedded-webserver/src/HTTPConnection.h index 2da4027334..7eb0c6108d 100644 --- a/libraries/embedded-webserver/src/HTTPConnection.h +++ b/libraries/embedded-webserver/src/HTTPConnection.h @@ -5,6 +5,10 @@ // Created by Stephen Birarda on 1/16/14. // Copyright 2014 High Fidelity, Inc. // +// Heavily based on Andrzej Kapolka's original HTTPConnection class +// found from another one of his projects. +// https://github.com/ey6es/witgap/tree/master/src/cpp/server/http +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/octree/src/CoverageMap.h b/libraries/octree/src/CoverageMap.h index d1fada141e..e06696ff66 100644 --- a/libraries/octree/src/CoverageMap.h +++ b/libraries/octree/src/CoverageMap.h @@ -5,6 +5,8 @@ // Created by Brad Hefta-Gaub on 06/11/13. // Copyright 2013 High Fidelity, Inc. // +// 2D CoverageMap Quad tree for storage of OctreeProjectedPolygons +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/octree/src/CoverageMapV2.cpp b/libraries/octree/src/CoverageMapV2.cpp index 6535066eed..1ad800ab6b 100644 --- a/libraries/octree/src/CoverageMapV2.cpp +++ b/libraries/octree/src/CoverageMapV2.cpp @@ -9,6 +9,40 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include +#include + +#include + +#include + +#include "CoverageMapV2.h" + +int CoverageMapV2::_mapCount = 0; +int CoverageMapV2::_checkMapRootCalls = 0; +int CoverageMapV2::_notAllInView = 0; +bool CoverageMapV2::wantDebugging = false; + +const BoundingBox CoverageMapV2::ROOT_BOUNDING_BOX = BoundingBox(glm::vec2(-1.f,-1.f), glm::vec2(2.f,2.f)); + +// Coverage Map's polygon coordinates are from -1 to 1 in the following mapping to screen space. +// +// (0,0) (windowWidth, 0) +// -1,1 1,1 +// +-----------------------+ +// | | | +// | | | +// | -1,0 | | +// |-----------+-----------| +// | 0,0 | +// | | | +// | | | +// | | | +// +-----------------------+ +// -1,-1 1,-1 +// (0,windowHeight) (windowWidth,windowHeight) +// + // Choosing a minimum sized polygon. Since we know a typical window is approximately 1500 pixels wide // then a pixel on our screen will be ~ 2.0/1500 or 0.0013 "units" wide, similarly pixels are typically // about that tall as well. If we say that polygons should be at least 10x10 pixels to be considered "big enough" @@ -214,4 +248,4 @@ void CoverageMapV2::recurseMap(const OctreeProjectedPolygon* polygon, bool store } // normal exit case... return... -} +} \ No newline at end of file diff --git a/libraries/script-engine/src/Vec3.h b/libraries/script-engine/src/Vec3.h index 9e962ca4fd..7d420adca3 100644 --- a/libraries/script-engine/src/Vec3.h +++ b/libraries/script-engine/src/Vec3.h @@ -5,6 +5,8 @@ // Created by Brad Hefta-Gaub on 1/29/14. // Copyright 2014 High Fidelity, Inc. // +// Scriptable Vec3 class library. +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/shared/src/CapsuleShape.cpp b/libraries/shared/src/CapsuleShape.cpp index 15586c4938..be3a165082 100644 --- a/libraries/shared/src/CapsuleShape.cpp +++ b/libraries/shared/src/CapsuleShape.cpp @@ -2,7 +2,7 @@ // CapsuleShape.cpp // libraries/shared/src // -// Created by Andrew Meadows on 2014. +// Created by Andrew Meadows on 02/20/2014. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. diff --git a/libraries/shared/src/CollisionInfo.cpp b/libraries/shared/src/CollisionInfo.cpp index bf986705f5..5a4188a1ef 100644 --- a/libraries/shared/src/CollisionInfo.cpp +++ b/libraries/shared/src/CollisionInfo.cpp @@ -2,7 +2,7 @@ // CollisionInfo.cpp // libraries/shared/src // -// Created by Andrew Meadows on 2014. +// Created by Andrew Meadows on 02/14/2014. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. diff --git a/libraries/shared/src/CollisionInfo.h b/libraries/shared/src/CollisionInfo.h index fb7450671b..b8c4aa6523 100644 --- a/libraries/shared/src/CollisionInfo.h +++ b/libraries/shared/src/CollisionInfo.h @@ -2,7 +2,7 @@ // CollisionInfo.h // libraries/shared/src // -// Created by Andrew Meadows on 2014. +// Created by Andrew Meadows on 02/14/2014. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. diff --git a/libraries/shared/src/ListShape.cpp b/libraries/shared/src/ListShape.cpp index 26d1c7fea5..dcea97826e 100644 --- a/libraries/shared/src/ListShape.cpp +++ b/libraries/shared/src/ListShape.cpp @@ -2,7 +2,7 @@ // ListShape.cpp // libraries/shared/src // -// Created by Andrew Meadows on 2014. +// Created by Andrew Meadows on 02/20/2014. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. diff --git a/libraries/shared/src/PacketSender.h b/libraries/shared/src/PacketSender.h index 01023f8ca3..d517da6d17 100644 --- a/libraries/shared/src/PacketSender.h +++ b/libraries/shared/src/PacketSender.h @@ -5,6 +5,8 @@ // Created by Brad Hefta-Gaub on 8/12/13. // Copyright 2013 High Fidelity, Inc. // +// Threaded or non-threaded packet sender. +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/libraries/shared/src/ShapeCollider.cpp b/libraries/shared/src/ShapeCollider.cpp index 2462663405..b13775dfa8 100644 --- a/libraries/shared/src/ShapeCollider.cpp +++ b/libraries/shared/src/ShapeCollider.cpp @@ -2,7 +2,7 @@ // ShapeCollider.cpp // libraries/shared/src // -// Created by Andrew Meadows on 2014. +// Created by Andrew Meadows on 02/20/2014. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. diff --git a/libraries/shared/src/ShapeCollider.h b/libraries/shared/src/ShapeCollider.h index 7154a158d0..c1018bec42 100644 --- a/libraries/shared/src/ShapeCollider.h +++ b/libraries/shared/src/ShapeCollider.h @@ -2,7 +2,7 @@ // ShapeCollider.h // libraries/shared/src // -// Created by Andrew Meadows on 2014. +// Created by Andrew Meadows on 02/20/2014. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. From ced5e72d39bb59bd5627a8f68403ec3f769a4a08 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 10:46:36 -0700 Subject: [PATCH 253/595] add date to capsule shape --- libraries/shared/src/CapsuleShape.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/shared/src/CapsuleShape.h b/libraries/shared/src/CapsuleShape.h index b721633601..062c3aff6f 100644 --- a/libraries/shared/src/CapsuleShape.h +++ b/libraries/shared/src/CapsuleShape.h @@ -2,7 +2,7 @@ // CapsuleShape.h // libraries/shared/src // -// Created by Andrew Meadows on 2014. +// Created by Andrew Meadows on 02/20/2014. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. From 55e0035fc890b0e618e0c6439cc4a8a9c316a990 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Wed, 9 Apr 2014 11:14:47 -0700 Subject: [PATCH 254/595] More progress on Faceplus integration. --- interface/src/Menu.cpp | 5 ++ interface/src/Menu.h | 1 + interface/src/devices/Faceplus.cpp | 113 ++++++++++++++++++++++++++++- interface/src/devices/Faceplus.h | 17 +++++ interface/src/devices/Faceshift.h | 3 - interface/src/devices/Visage.cpp | 1 + interface/src/devices/Visage.h | 3 - 7 files changed, 135 insertions(+), 8 deletions(-) diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 8a97c98f02..b85f83ab05 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -301,6 +301,11 @@ Menu::Menu() : true, appInstance->getFaceshift(), SLOT(setTCPEnabled(bool))); +#ifdef HAVE_FACEPLUS + addCheckableActionToQMenuAndActionHash(avatarOptionsMenu, MenuOption::Faceplus, 0, true, + appInstance->getFaceplus(), SLOT(updateEnabled())); +#endif + #ifdef HAVE_VISAGE addCheckableActionToQMenuAndActionHash(avatarOptionsMenu, MenuOption::Visage, 0, true, appInstance->getVisage(), SLOT(updateEnabled())); diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 7bb0b75675..b7a82b0b0e 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -250,6 +250,7 @@ namespace MenuOption { const QString EchoLocalAudio = "Echo Local Audio"; const QString EchoServerAudio = "Echo Server Audio"; const QString Enable3DTVMode = "Enable 3DTV Mode"; + const QString Faceplus = "Faceplus"; const QString Faceshift = "Faceshift"; const QString FilterSixense = "Smooth Sixense Movement"; const QString FirstPerson = "First Person"; diff --git a/interface/src/devices/Faceplus.cpp b/interface/src/devices/Faceplus.cpp index 64dd4bf52d..2e02126240 100644 --- a/interface/src/devices/Faceplus.cpp +++ b/interface/src/devices/Faceplus.cpp @@ -10,23 +10,132 @@ #include #endif +#include "Application.h" #include "Faceplus.h" +#include "renderer/FBXReader.h" Faceplus::Faceplus() : + _enabled(false), _active(false) { -} -void Faceplus::init() { #ifdef HAVE_FACEPLUS // these are ignored--any values will do faceplus_log_in("username", "password"); #endif } +Faceplus::~Faceplus() { + setEnabled(false); +} + +void Faceplus::init() { + connect(Application::getInstance()->getFaceshift(), SIGNAL(connectionStateChanged()), SLOT(updateEnabled())); + updateEnabled(); +} + +#ifdef HAVE_FACEPLUS +static QMultiHash > createChannelNameMap() { + QMultiHash > blendshapeMap; + blendshapeMap.insert("JawFwd", QPair("au_jaw_z_push", 1.0f)); + blendshapeMap.insert("JawLeft", QPair("au_jaw_x_push", 1.0f)); + blendshapeMap.insert("JawOpen", QPair("au_jaw_drop", 1.0f)); + blendshapeMap.insert("LipsLowerDown", QPair("au_lower_lip_drop", 1.0f)); + blendshapeMap.insert("LipsUpperOpen", QPair("au_upper_lip_raiser", 1.0f)); + blendshapeMap.insert("LipsStretch_R", QPair("au_lip_stretcher_left", 0.5f)); + blendshapeMap.insert("MouthSmile_L", QPair("au_lip_corner_depressor", -1.0f)); + blendshapeMap.insert("MouthSmile_R", QPair("au_lip_corner_depressor", -1.0f)); + blendshapeMap.insert("BrowsU_R", QPair("au_left_outer_brow_raiser", 1.0f)); + blendshapeMap.insert("BrowsU_C", QPair("au_left_inner_brow_raiser", 1.0f)); + blendshapeMap.insert("BrowsD_R", QPair("au_left_brow_lowerer", 1.0f)); + blendshapeMap.insert("EyeBlink_L", QPair("au_leye_closed", 1.0f)); + blendshapeMap.insert("EyeBlink_R", QPair("au_reye_closed", 1.0f)); + blendshapeMap.insert("EyeOpen_L", QPair("au_upper_lid_raiser", 1.0f)); + blendshapeMap.insert("EyeOpen_R", QPair("au_upper_lid_raiser", 1.0f)); + blendshapeMap.insert("LipLowerOpen", QPair("au_lower_lip_x_push", 1.0f)); + blendshapeMap.insert("LipsStretch_L", QPair("au_lip_stretcher_right", 0.5f)); + blendshapeMap.insert("BrowsU_L", QPair("au_right_outer_brow_raiser", 1.0f)); + blendshapeMap.insert("BrowsU_C", QPair("au_right_inner_brow_raiser", 1.0f)); + blendshapeMap.insert("BrowsD_L", QPair("au_right_brow_lowerer", 1.0f)); + + QMultiHash > channelNameMap; + for (int i = 0;; i++) { + QByteArray blendshape = FACESHIFT_BLENDSHAPES[i]; + if (blendshape.isEmpty()) { + break; + } + for (QMultiHash >::const_iterator it = blendshapeMap.constFind(blendshape); + it != blendshapeMap.constEnd() && it.key() == blendshape; it++) { + channelNameMap.insert(it.value().first, QPair(i, it.value().second)); + } + } + + return channelNameMap; +} + +static const QMultiHash >& getChannelNameMap() { + static QMultiHash > channelNameMap = createChannelNameMap(); + return channelNameMap; +} +#endif + void Faceplus::update() { +#ifdef HAVE_FACEPLUS + if (!_active) { + return; + } + if (!(_active = faceplus_current_output_vector(_outputVector.data()))) { + return; + } + qFill(_blendshapeCoefficients.begin(), _blendshapeCoefficients.end(), 0.0f); + for (int i = 0; i < _outputVector.size(); i++) { + for (QMultiHash >::const_iterator it = _channelIndexMap.constFind(i); + it != _channelIndexMap.constEnd() && it.key() == i; it++) { + _blendshapeCoefficients[it.value().first] += _outputVector.at(i) * it.value().second; + } + } +#endif } void Faceplus::reset() { } +void Faceplus::updateEnabled() { + setEnabled(Menu::getInstance()->isOptionChecked(MenuOption::Faceplus) && + !(Menu::getInstance()->isOptionChecked(MenuOption::Faceshift) && + Application::getInstance()->getFaceshift()->isConnectedOrConnecting())); +} +void Faceplus::setEnabled(bool enabled) { +#ifdef HAVE_FACEPLUS + if (_enabled == enabled) { + return; + } + if ((_enabled = enabled)) { + if (faceplus_init("VGA")) { + qDebug() << "Faceplus initialized."; + _active = true; + + int channelCount = faceplus_output_channels_count(); + _outputVector.resize(channelCount); + + int maxIndex = -1; + _channelIndexMap.clear(); + for (int i = 0; i < channelCount; i++) { + QByteArray channelName = faceplus_output_channel_name(i); + + qDebug() << channelName; + + for (QMultiHash >::const_iterator it = getChannelNameMap().constFind(name); + it != getChannelNameMap().constEnd() && it.key() == name; it++) { + _channelIndexMap.insert(i, it.value()); + maxIndex = qMax(maxIndex, it.value().first); + } + } + _blendshapeCoefficients.resize(maxIndex + 1); + } + } else if (faceplus_teardown()) { + qDebug() << "Faceplus torn down."; + _active = false; + } +#endif +} diff --git a/interface/src/devices/Faceplus.h b/interface/src/devices/Faceplus.h index cf7a6583a1..a511313d0c 100644 --- a/interface/src/devices/Faceplus.h +++ b/interface/src/devices/Faceplus.h @@ -9,6 +9,10 @@ #ifndef __interface__Faceplus__ #define __interface__Faceplus__ +#include +#include +#include + #include "FaceTracker.h" /// Interface for Mixamo FacePlus. @@ -18,6 +22,7 @@ class Faceplus : public FaceTracker { public: Faceplus(); + virtual ~Faceplus(); void init(); @@ -26,9 +31,21 @@ public: void update(); void reset(); +public slots: + + void updateEnabled(); + private: + void setEnabled(bool enabled); + + bool _enabled; bool _active; + +#ifdef HAVE_VISAGE + QMultiHash > _channelIndexMap; + QVector _outputVector; +#endif }; #endif /* defined(__interface__Faceplus__) */ diff --git a/interface/src/devices/Faceshift.h b/interface/src/devices/Faceshift.h index c49c6661e7..c245d648b8 100644 --- a/interface/src/devices/Faceshift.h +++ b/interface/src/devices/Faceshift.h @@ -12,9 +12,6 @@ #include #include -#include -#include - #include #include "FaceTracker.h" diff --git a/interface/src/devices/Visage.cpp b/interface/src/devices/Visage.cpp index 0cb534f8c3..3792cc913d 100644 --- a/interface/src/devices/Visage.cpp +++ b/interface/src/devices/Visage.cpp @@ -159,6 +159,7 @@ void Visage::reset() { void Visage::updateEnabled() { setEnabled(Menu::getInstance()->isOptionChecked(MenuOption::Visage) && + !Menu::getInstance()->isOptionChecked(MenuOption::Faceplus) && !(Menu::getInstance()->isOptionChecked(MenuOption::Faceshift) && Application::getInstance()->getFaceshift()->isConnectedOrConnecting())); } diff --git a/interface/src/devices/Visage.h b/interface/src/devices/Visage.h index 0da87fb332..1a02f5d7c3 100644 --- a/interface/src/devices/Visage.h +++ b/interface/src/devices/Visage.h @@ -13,9 +13,6 @@ #include #include -#include -#include - #include "FaceTracker.h" namespace VisageSDK { From 4b306401afd026e8a737af85d0520988c9998c9b Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 9 Apr 2014 11:32:52 -0700 Subject: [PATCH 255/595] use slot to change AvatarData::_sessionUUID --- interface/src/Application.cpp | 6 +----- libraries/avatars/src/AvatarData.h | 2 +- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 2a97e536e4..ae80cdef48 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -232,6 +232,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : connect(nodeList, SIGNAL(nodeAdded(SharedNodePointer)), &_voxels, SLOT(nodeAdded(SharedNodePointer))); connect(nodeList, SIGNAL(nodeKilled(SharedNodePointer)), &_voxels, SLOT(nodeKilled(SharedNodePointer))); connect(nodeList, &NodeList::uuidChanged, this, &Application::updateWindowTitle); + connect(nodeList, SIGNAL(uuidChanged(const QUuid&)), _myAvatar, SLOT(setSessionUUID(const QUuid&))); connect(nodeList, &NodeList::limitOfSilentDomainCheckInsReached, nodeList, &NodeList::reset); // connect to appropriate slots on AccountManager @@ -1216,11 +1217,6 @@ void Application::timer() { // ask the node list to check in with the domain server NodeList::getInstance()->sendDomainServerCheckIn(); - - // as soon as we have a valid sessionUUID, store it in the avatar for reference - if (_myAvatar->getSessionUUID().isNull()) { - _myAvatar->setSessionUUID(NodeList::getInstance()->getSessionUUID()); - } } void Application::idle() { diff --git a/libraries/avatars/src/AvatarData.h b/libraries/avatars/src/AvatarData.h index e8b287ceed..2b8dfe8861 100755 --- a/libraries/avatars/src/AvatarData.h +++ b/libraries/avatars/src/AvatarData.h @@ -102,7 +102,6 @@ public: virtual ~AvatarData(); const QUuid& getSessionUUID() { return _sessionUUID; } - void setSessionUUID(const QUuid& id) { _sessionUUID = id; } const glm::vec3& getPosition() const { return _position; } void setPosition(const glm::vec3 position) { _position = position; } @@ -225,6 +224,7 @@ public slots: void sendBillboardPacket(); void setBillboardFromNetworkReply(); void setJointMappingsFromNetworkReply(); + void setSessionUUID(const QUuid& id) { _sessionUUID = id; } protected: QUuid _sessionUUID; glm::vec3 _position; From 0a9c7e3d744ce9003643e653c2422fa6e766289d Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 11:35:20 -0700 Subject: [PATCH 256/595] add an include guard to Stats --- interface/src/ui/Stats.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/interface/src/ui/Stats.h b/interface/src/ui/Stats.h index ad2a3c9bf5..3d3e930b85 100644 --- a/interface/src/ui/Stats.h +++ b/interface/src/ui/Stats.h @@ -9,6 +9,9 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#ifndef _hifi_Stats_h +#define _hifi_Stats_h + #include #include @@ -42,3 +45,5 @@ private: int _lastHorizontalOffset; }; + +#endif From 4deb052d5dde2f36d1c0771a015d81b57d487655 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Wed, 9 Apr 2014 11:54:55 -0700 Subject: [PATCH 257/595] More work on Faceplus integration. --- .gitignore | 4 ++ interface/external/faceplus/readme.txt | 4 +- interface/src/devices/Faceplus.cpp | 53 +++++++++++++++++++++++++- interface/src/devices/Faceplus.h | 2 +- 4 files changed, 59 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index eb2f3ec303..c296a918af 100644 --- a/.gitignore +++ b/.gitignore @@ -42,5 +42,9 @@ interface/external/visage/* interface/resources/visage/* !interface/resources/visage/tracker.cfg +# Ignore Faceplus +interface/external/faceplus/* +!interface/external/faceplus/readme.txt + # Ignore interfaceCache for Linux users interface/interfaceCache/ diff --git a/interface/external/faceplus/readme.txt b/interface/external/faceplus/readme.txt index 322ea846bb..e98f8becdc 100644 --- a/interface/external/faceplus/readme.txt +++ b/interface/external/faceplus/readme.txt @@ -5,5 +5,7 @@ Andrzej Kapolka, April 8, 2014 1. Copy the Faceplus sdk folders (include, win32) into the interface/external/faceplus folder. This readme.txt should be there as well. -2. Delete your build directory, run cmake and build, and you should be all set. +2. Copy the Faceplus DLLs from the win32 folder into your path. + +3. Delete your build directory, run cmake and build, and you should be all set. diff --git a/interface/src/devices/Faceplus.cpp b/interface/src/devices/Faceplus.cpp index 2e02126240..89197a5acf 100644 --- a/interface/src/devices/Faceplus.cpp +++ b/interface/src/devices/Faceplus.cpp @@ -33,6 +33,55 @@ void Faceplus::init() { updateEnabled(); } +/* +[2014-04-09T11:42:11] "Mix::Blink_Left" +[2014-04-09T11:42:11] "Mix::Blink_Right" +[2014-04-09T11:42:11] "Mix::BrowsDown_Left" +[2014-04-09T11:42:11] "Mix::BrowsDown_Right" +[2014-04-09T11:42:11] "Mix::BrowsIn_Left" +[2014-04-09T11:42:11] "Mix::BrowsIn_Right" +[2014-04-09T11:42:11] "Mix::BrowsOuterLower_Left" +[2014-04-09T11:42:11] "Mix::BrowsOuterLower_Right" +[2014-04-09T11:42:11] "Mix::BrowsUp_Left" +[2014-04-09T11:42:11] "Mix::BrowsUp_Right" +[2014-04-09T11:42:11] "Mix::EyesWide_Left" +[2014-04-09T11:42:11] "Mix::EyesWide_Right" +[2014-04-09T11:42:11] "Mix::Frown_Left" +[2014-04-09T11:42:11] "Mix::Frown_Right" +[2014-04-09T11:42:11] "Mix::Jaw_RotateY_Left" +[2014-04-09T11:42:11] "Mix::Jaw_RotateY_Right" +[2014-04-09T11:42:11] "Mix::LowerLipDown_Left" +[2014-04-09T11:42:11] "Mix::LowerLipDown_Right" +[2014-04-09T11:42:11] "Mix::LowerLipIn" +[2014-04-09T11:42:11] "Mix::LowerLipOut" +[2014-04-09T11:42:11] "Mix::Midmouth_Left" +[2014-04-09T11:42:11] "Mix::Midmouth_Right" +[2014-04-09T11:42:11] "Mix::MouthDown" +[2014-04-09T11:42:11] "Mix::MouthNarrow_Left" +[2014-04-09T11:42:11] "Mix::MouthNarrow_Right" +[2014-04-09T11:42:11] "Mix::MouthOpen" +[2014-04-09T11:42:11] "Mix::MouthUp" +[2014-04-09T11:42:11] "Mix::MouthWhistle_NarrowAdjust_Left" +[2014-04-09T11:42:11] "Mix::MouthWhistle_NarrowAdjust_Right" +[2014-04-09T11:42:11] "Mix::NoseScrunch_Left" +[2014-04-09T11:42:11] "Mix::NoseScrunch_Right" +[2014-04-09T11:42:11] "Mix::Smile_Left" +[2014-04-09T11:42:11] "Mix::Smile_Right" +[2014-04-09T11:42:11] "Mix::Squint_Left" +[2014-04-09T11:42:11] "Mix::Squint_Right" +[2014-04-09T11:42:11] "Mix::UpperLipIn" +[2014-04-09T11:42:11] "Mix::UpperLipOut" +[2014-04-09T11:42:11] "Mix::UpperLipUp_Left" +[2014-04-09T11:42:11] "Mix::UpperLipUp_Right" +[2014-04-09T11:42:11] "Head_Joint::Rotation_X" +[2014-04-09T11:42:11] "Head_Joint::Rotation_Y" +[2014-04-09T11:42:11] "Head_Joint::Rotation_Z" +[2014-04-09T11:42:11] "Left_Eye_Joint::Rotation_X" +[2014-04-09T11:42:11] "Left_Eye_Joint::Rotation_Y" +[2014-04-09T11:42:11] "Right_Eye_Joint::Rotation_X" +[2014-04-09T11:42:11] "Right_Eye_Joint::Rotation_Y" +*/ + #ifdef HAVE_FACEPLUS static QMultiHash > createChannelNameMap() { QMultiHash > blendshapeMap; @@ -121,9 +170,9 @@ void Faceplus::setEnabled(bool enabled) { int maxIndex = -1; _channelIndexMap.clear(); for (int i = 0; i < channelCount; i++) { - QByteArray channelName = faceplus_output_channel_name(i); + QByteArray name = faceplus_output_channel_name(i); - qDebug() << channelName; + qDebug() << name; for (QMultiHash >::const_iterator it = getChannelNameMap().constFind(name); it != getChannelNameMap().constEnd() && it.key() == name; it++) { diff --git a/interface/src/devices/Faceplus.h b/interface/src/devices/Faceplus.h index a511313d0c..1e3272906c 100644 --- a/interface/src/devices/Faceplus.h +++ b/interface/src/devices/Faceplus.h @@ -42,7 +42,7 @@ private: bool _enabled; bool _active; -#ifdef HAVE_VISAGE +#ifdef HAVE_FACEPLUS QMultiHash > _channelIndexMap; QVector _outputVector; #endif From ae4b8348a246c5a398aee743c5498862cdf0ca5e Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 12:03:17 -0700 Subject: [PATCH 258/595] fix header include guards via regex --- animation-server/src/AnimationServer.h | 6 +++--- assignment-client/src/Agent.h | 6 +++--- assignment-client/src/AssignmentClient.h | 6 +++--- assignment-client/src/AssignmentClientMonitor.h | 6 +++--- assignment-client/src/AssignmentFactory.h | 6 +++--- assignment-client/src/AssignmentThread.h | 6 +++--- assignment-client/src/audio/AudioMixer.h | 6 +++--- assignment-client/src/audio/AudioMixerClientData.h | 6 +++--- assignment-client/src/audio/AvatarAudioRingBuffer.h | 6 +++--- assignment-client/src/avatars/AvatarMixer.h | 6 +++--- assignment-client/src/avatars/AvatarMixerClientData.h | 6 +++--- assignment-client/src/metavoxels/MetavoxelServer.h | 6 +++--- .../src/octree/OctreeInboundPacketProcessor.h | 6 +++--- assignment-client/src/octree/OctreeQueryNode.h | 6 +++--- assignment-client/src/octree/OctreeSendThread.h | 6 +++--- assignment-client/src/octree/OctreeServer.h | 6 +++--- assignment-client/src/octree/OctreeServerConsts.h | 6 +++--- assignment-client/src/particles/ParticleNodeData.h | 6 +++--- assignment-client/src/particles/ParticleServer.h | 6 +++--- assignment-client/src/particles/ParticleServerConsts.h | 6 +++--- assignment-client/src/voxels/VoxelNodeData.h | 6 +++--- assignment-client/src/voxels/VoxelServer.h | 6 +++--- assignment-client/src/voxels/VoxelServerConsts.h | 6 +++--- domain-server/src/DomainServer.h | 6 +++--- domain-server/src/DomainServerNodeData.h | 6 +++--- interface/src/AbstractLoggerInterface.h | 6 +++--- interface/src/Application.h | 6 +++--- interface/src/Audio.h | 6 +++--- interface/src/BuckyBalls.h | 6 +++--- interface/src/Camera.h | 6 +++--- interface/src/DatagramProcessor.h | 6 +++--- interface/src/Environment.h | 6 +++--- interface/src/FileLogger.h | 2 +- interface/src/GLCanvas.h | 6 +++--- interface/src/Menu.h | 6 +++--- interface/src/MetavoxelSystem.h | 6 +++--- interface/src/ParticleTreeRenderer.h | 6 +++--- interface/src/Physics.h | 2 +- interface/src/Stars.h | 7 +++---- interface/src/Util.h | 6 +++--- interface/src/XmppClient.h | 6 +++--- interface/src/avatar/Avatar.h | 6 +++--- interface/src/avatar/AvatarManager.h | 6 +++--- interface/src/avatar/FaceModel.h | 6 +++--- interface/src/avatar/Hand.h | 3 +-- interface/src/avatar/Head.h | 2 +- interface/src/avatar/MyAvatar.h | 6 +++--- interface/src/avatar/SkeletonModel.h | 6 +++--- interface/src/devices/Faceshift.h | 6 +++--- interface/src/devices/OculusManager.h | 6 +++--- interface/src/devices/SixenseManager.h | 7 +++---- interface/src/devices/TV3DManager.h | 6 +++--- interface/src/devices/Visage.h | 6 +++--- interface/src/location/LocationManager.h | 6 +++--- interface/src/location/NamedLocation.h | 6 +++--- interface/src/renderer/AmbientOcclusionEffect.h | 6 +++--- interface/src/renderer/FBXReader.h | 6 +++--- interface/src/renderer/GeometryCache.h | 6 +++--- interface/src/renderer/GlowEffect.h | 6 +++--- interface/src/renderer/Model.h | 6 +++--- interface/src/renderer/PointShader.h | 6 +++--- interface/src/renderer/ProgramObject.h | 6 +++--- interface/src/renderer/RenderUtil.h | 6 +++--- interface/src/renderer/TextureCache.h | 6 +++--- interface/src/renderer/VoxelShader.h | 6 +++--- interface/src/scripting/AudioDeviceScriptingInterface.h | 6 +++--- interface/src/scripting/ClipboardScriptingInterface.h | 6 +++--- interface/src/scripting/ControllerScriptingInterface.h | 6 +++--- interface/src/scripting/MenuScriptingInterface.h | 6 +++--- interface/src/scripting/SettingsScriptingInterface.h | 6 +++--- interface/src/starfield/Config.h | 6 +++--- interface/src/starfield/Controller.h | 6 +++--- interface/src/starfield/Generator.h | 6 +++--- interface/src/starfield/data/GpuVertex.h | 7 +++---- interface/src/starfield/data/InputVertex.h | 7 +++---- interface/src/starfield/data/Tile.h | 7 +++---- interface/src/starfield/renderer/Renderer.h | 6 +++--- interface/src/starfield/renderer/Tiling.h | 7 +++---- interface/src/starfield/renderer/VertexOrder.h | 7 +++---- interface/src/ui/BandwidthDialog.h | 7 +++---- interface/src/ui/BandwidthMeter.h | 7 +++---- interface/src/ui/ChatWindow.h | 6 +++--- interface/src/ui/ImportDialog.h | 6 +++--- interface/src/ui/InfoView.h | 6 +++--- interface/src/ui/LodToolsDialog.h | 7 +++---- interface/src/ui/LogDialog.h | 7 +++---- interface/src/ui/MetavoxelEditor.h | 6 +++--- interface/src/ui/ModelsBrowser.h | 6 +++--- interface/src/ui/OctreeStatsDialog.h | 7 +++---- interface/src/ui/Oscilloscope.h | 6 +++--- interface/src/ui/RearMirrorTools.h | 6 +++--- interface/src/ui/RunningScriptsWidget.h | 6 +++--- interface/src/ui/Snapshot.h | 6 +++--- interface/src/ui/Stats.h | 6 +++--- interface/src/ui/TextRenderer.h | 6 +++--- interface/src/ui/UpdateDialog.h | 6 +++--- interface/src/ui/overlays/Base3DOverlay.h | 6 +++--- interface/src/ui/overlays/Cube3DOverlay.h | 6 +++--- interface/src/ui/overlays/ImageOverlay.h | 6 +++--- interface/src/ui/overlays/Line3DOverlay.h | 6 +++--- interface/src/ui/overlays/LocalVoxelsOverlay.h | 6 +++--- interface/src/ui/overlays/Overlay.h | 6 +++--- interface/src/ui/overlays/Overlay2D.h | 6 +++--- interface/src/ui/overlays/Overlays.h | 6 +++--- interface/src/ui/overlays/Sphere3DOverlay.h | 6 +++--- interface/src/ui/overlays/TextOverlay.h | 6 +++--- interface/src/ui/overlays/Volume3DOverlay.h | 6 +++--- interface/src/voxels/PrimitiveRenderer.h | 6 +++--- interface/src/voxels/VoxelFade.h | 6 +++--- interface/src/voxels/VoxelHideShowThread.h | 6 +++--- interface/src/voxels/VoxelImporter.h | 6 +++--- interface/src/voxels/VoxelPacketProcessor.h | 6 +++--- interface/src/voxels/VoxelSystem.h | 6 +++--- interface/src/windowshacks.h | 6 +++--- interface/src/world.h | 6 +++--- libraries/audio/src/AbstractAudioInterface.h | 6 +++--- libraries/audio/src/AudioInjector.h | 6 +++--- libraries/audio/src/AudioInjectorOptions.h | 6 +++--- libraries/audio/src/AudioRingBuffer.h | 6 +++--- libraries/audio/src/AudioScriptingInterface.h | 6 +++--- libraries/audio/src/InjectedAudioRingBuffer.h | 6 +++--- libraries/audio/src/MixedAudioRingBuffer.h | 6 +++--- libraries/audio/src/PositionalAudioRingBuffer.h | 6 +++--- libraries/audio/src/Sound.h | 6 +++--- libraries/avatars/src/AvatarData.h | 6 +++--- libraries/avatars/src/AvatarHashMap.h | 6 +++--- libraries/avatars/src/HandData.h | 6 +++--- libraries/avatars/src/HeadData.h | 6 +++--- libraries/embedded-webserver/src/HTTPConnection.h | 6 +++--- libraries/embedded-webserver/src/HTTPManager.h | 6 +++--- libraries/metavoxels/src/AttributeRegistry.h | 6 +++--- libraries/metavoxels/src/Bitstream.h | 6 +++--- libraries/metavoxels/src/DatagramSequencer.h | 6 +++--- libraries/metavoxels/src/MetavoxelData.h | 6 +++--- libraries/metavoxels/src/MetavoxelMessages.h | 6 +++--- libraries/metavoxels/src/MetavoxelUtil.h | 6 +++--- libraries/metavoxels/src/ScriptCache.h | 6 +++--- libraries/metavoxels/src/SharedObject.h | 6 +++--- libraries/octree/src/AABox.h | 6 +++--- libraries/octree/src/CoverageMap.h | 6 +++--- libraries/octree/src/CoverageMapV2.h | 6 +++--- libraries/octree/src/JurisdictionListener.h | 6 +++--- libraries/octree/src/JurisdictionMap.h | 8 +++----- libraries/octree/src/JurisdictionSender.h | 6 +++--- libraries/octree/src/Octree.h | 6 +++--- libraries/octree/src/OctreeConstants.h | 6 +++--- libraries/octree/src/OctreeEditPacketSender.h | 6 +++--- libraries/octree/src/OctreeElement.h | 6 +++--- libraries/octree/src/OctreeElementBag.h | 6 +++--- libraries/octree/src/OctreeHeadlessViewer.h | 6 +++--- libraries/octree/src/OctreePacketData.h | 6 +++--- libraries/octree/src/OctreePersistThread.h | 6 +++--- libraries/octree/src/OctreeProjectedPolygon.h | 6 +++--- libraries/octree/src/OctreeQuery.h | 6 +++--- libraries/octree/src/OctreeRenderer.h | 6 +++--- libraries/octree/src/OctreeSceneStats.h | 6 +++--- libraries/octree/src/OctreeScriptingInterface.h | 6 +++--- libraries/octree/src/ViewFrustum.h | 6 +++--- libraries/particles/src/Particle.h | 6 +++--- libraries/particles/src/ParticleCollisionSystem.h | 6 +++--- libraries/particles/src/ParticleEditPacketSender.h | 6 +++--- libraries/particles/src/ParticleTree.h | 6 +++--- libraries/particles/src/ParticleTreeElement.h | 6 +++--- libraries/particles/src/ParticleTreeHeadlessViewer.h | 6 +++--- libraries/particles/src/ParticlesScriptingInterface.h | 6 +++--- .../src/AbstractControllerScriptingInterface.h | 6 +++--- libraries/script-engine/src/EventTypes.h | 6 +++--- libraries/script-engine/src/LocalVoxels.h | 6 +++--- libraries/script-engine/src/MenuItemProperties.h | 6 +++--- libraries/script-engine/src/Quat.h | 6 +++--- libraries/script-engine/src/ScriptEngine.h | 6 +++--- libraries/script-engine/src/Vec3.h | 6 +++--- libraries/shared/src/AccountManager.h | 6 +++--- libraries/shared/src/AngleUtil.h | 7 +++---- libraries/shared/src/Assignment.h | 6 +++--- libraries/shared/src/CapsuleShape.h | 6 +++--- libraries/shared/src/CollisionInfo.h | 6 +++--- libraries/shared/src/DataServerAccountInfo.h | 6 +++--- libraries/shared/src/DomainInfo.h | 6 +++--- libraries/shared/src/FileUtils.h | 2 +- libraries/shared/src/FloodFill.h | 7 +++---- libraries/shared/src/GenericThread.h | 6 +++--- libraries/shared/src/GeometryUtil.h | 6 +++--- libraries/shared/src/HifiSockAddr.h | 6 +++--- libraries/shared/src/ListShape.h | 6 +++--- libraries/shared/src/Logging.h | 6 +++--- libraries/shared/src/ModelUploader.h | 6 +++--- libraries/shared/src/NetworkPacket.h | 6 +++--- libraries/shared/src/Node.h | 6 +++--- libraries/shared/src/NodeData.h | 2 +- libraries/shared/src/NodeList.h | 6 +++--- libraries/shared/src/OAuthAccessToken.h | 6 +++--- libraries/shared/src/OctalCode.h | 6 +++--- libraries/shared/src/PacketHeaders.h | 2 +- libraries/shared/src/PacketSender.h | 6 +++--- libraries/shared/src/PerfStat.h | 6 +++--- libraries/shared/src/Radix2InplaceSort.h | 6 +++--- libraries/shared/src/Radix2IntegerScanner.h | 7 +++---- libraries/shared/src/ReceivedPacketProcessor.h | 6 +++--- libraries/shared/src/RegisteredMetaTypes.h | 2 +- libraries/shared/src/ResourceCache.h | 6 +++--- libraries/shared/src/Shape.h | 6 +++--- libraries/shared/src/ShapeCollider.h | 6 +++--- libraries/shared/src/SharedUtil.h | 6 +++--- libraries/shared/src/SimpleMovingAverage.h | 6 +++--- libraries/shared/src/SphereShape.h | 6 +++--- libraries/shared/src/StdDev.h | 6 +++--- libraries/shared/src/StreamUtils.h | 6 +++--- libraries/shared/src/ThreadedAssignment.h | 6 +++--- libraries/shared/src/UUID.h | 6 +++--- libraries/voxels/src/EnvironmentData.h | 6 +++--- libraries/voxels/src/LocalVoxelsList.h | 6 +++--- libraries/voxels/src/Tags.h | 6 +++--- libraries/voxels/src/VoxelConstants.h | 6 +++--- libraries/voxels/src/VoxelDetail.h | 6 +++--- libraries/voxels/src/VoxelEditPacketSender.h | 6 +++--- libraries/voxels/src/VoxelTree.h | 6 +++--- libraries/voxels/src/VoxelTreeCommands.h | 6 +++--- libraries/voxels/src/VoxelTreeElement.h | 7 +++---- libraries/voxels/src/VoxelTreeHeadlessViewer.h | 6 +++--- libraries/voxels/src/VoxelsScriptingInterface.h | 6 +++--- tests/metavoxels/src/MetavoxelTests.h | 6 +++--- tests/physics/src/CollisionInfoTests.h | 7 +++---- tests/physics/src/PhysicsTestUtil.h | 6 +++--- tests/physics/src/ShapeColliderTests.h | 6 +++--- voxel-edit/src/SceneUtils.h | 6 +++--- 226 files changed, 662 insertions(+), 682 deletions(-) diff --git a/animation-server/src/AnimationServer.h b/animation-server/src/AnimationServer.h index 924e973599..58f05c32c5 100644 --- a/animation-server/src/AnimationServer.h +++ b/animation-server/src/AnimationServer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AnimationServer__ -#define __hifi__AnimationServer__ +#ifndef hifi_AnimationServer_h +#define hifi_AnimationServer_h #include @@ -24,4 +24,4 @@ private slots: }; -#endif /* defined(__hifi__AnimationServer__) */ +#endif // hifi_AnimationServer_h diff --git a/assignment-client/src/Agent.h b/assignment-client/src/Agent.h index 6423514894..2dcd7e3107 100644 --- a/assignment-client/src/Agent.h +++ b/assignment-client/src/Agent.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__Agent__ -#define __hifi__Agent__ +#ifndef hifi_Agent_h +#define hifi_Agent_h #include @@ -67,4 +67,4 @@ private: MixedAudioRingBuffer _receivedAudioBuffer; }; -#endif /* defined(__hifi__Agent__) */ +#endif // hifi_Agent_h diff --git a/assignment-client/src/AssignmentClient.h b/assignment-client/src/AssignmentClient.h index 26e3a47255..1ad8cca244 100644 --- a/assignment-client/src/AssignmentClient.h +++ b/assignment-client/src/AssignmentClient.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AssignmentClient__ -#define __hifi__AssignmentClient__ +#ifndef hifi_AssignmentClient_h +#define hifi_AssignmentClient_h #include @@ -30,4 +30,4 @@ private: SharedAssignmentPointer _currentAssignment; }; -#endif /* defined(__hifi__AssignmentClient__) */ +#endif // hifi_AssignmentClient_h diff --git a/assignment-client/src/AssignmentClientMonitor.h b/assignment-client/src/AssignmentClientMonitor.h index 4bb82ab715..1df08a345e 100644 --- a/assignment-client/src/AssignmentClientMonitor.h +++ b/assignment-client/src/AssignmentClientMonitor.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AssignmentClientMonitor__ -#define __hifi__AssignmentClientMonitor__ +#ifndef hifi_AssignmentClientMonitor_h +#define hifi_AssignmentClientMonitor_h #include #include @@ -31,4 +31,4 @@ private: QStringList _childArguments; }; -#endif /* defined(__hifi__AssignmentClientMonitor__) */ +#endif // hifi_AssignmentClientMonitor_h diff --git a/assignment-client/src/AssignmentFactory.h b/assignment-client/src/AssignmentFactory.h index 2a63bffd37..9c197f5747 100644 --- a/assignment-client/src/AssignmentFactory.h +++ b/assignment-client/src/AssignmentFactory.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AssignmentFactory__ -#define __hifi__AssignmentFactory__ +#ifndef hifi_AssignmentFactory_h +#define hifi_AssignmentFactory_h #include @@ -19,4 +19,4 @@ public: static ThreadedAssignment* unpackAssignment(const QByteArray& packet); }; -#endif /* defined(__hifi__AssignmentFactory__) */ +#endif // hifi_AssignmentFactory_h diff --git a/assignment-client/src/AssignmentThread.h b/assignment-client/src/AssignmentThread.h index a76c118192..848c4614ba 100644 --- a/assignment-client/src/AssignmentThread.h +++ b/assignment-client/src/AssignmentThread.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AssignmentThread__ -#define __hifi__AssignmentThread__ +#ifndef hifi_AssignmentThread_h +#define hifi_AssignmentThread_h #include @@ -23,4 +23,4 @@ private: SharedAssignmentPointer _assignment; }; -#endif /* defined(__hifi__AssignmentThread__) */ +#endif // hifi_AssignmentThread_h diff --git a/assignment-client/src/audio/AudioMixer.h b/assignment-client/src/audio/AudioMixer.h index cea8bba083..659227dffb 100644 --- a/assignment-client/src/audio/AudioMixer.h +++ b/assignment-client/src/audio/AudioMixer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AudioMixer__ -#define __hifi__AudioMixer__ +#ifndef hifi_AudioMixer_h +#define hifi_AudioMixer_h #include @@ -53,4 +53,4 @@ private: int _sumMixes; }; -#endif /* defined(__hifi__AudioMixer__) */ +#endif // hifi_AudioMixer_h diff --git a/assignment-client/src/audio/AudioMixerClientData.h b/assignment-client/src/audio/AudioMixerClientData.h index aa449d20a3..a5f03ebd15 100644 --- a/assignment-client/src/audio/AudioMixerClientData.h +++ b/assignment-client/src/audio/AudioMixerClientData.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AudioMixerClientData__ -#define __hifi__AudioMixerClientData__ +#ifndef hifi_AudioMixerClientData_h +#define hifi_AudioMixerClientData_h #include @@ -34,4 +34,4 @@ private: std::vector _ringBuffers; }; -#endif /* defined(__hifi__AudioMixerClientData__) */ +#endif // hifi_AudioMixerClientData_h diff --git a/assignment-client/src/audio/AvatarAudioRingBuffer.h b/assignment-client/src/audio/AvatarAudioRingBuffer.h index fb9e68543f..1e61a82f68 100644 --- a/assignment-client/src/audio/AvatarAudioRingBuffer.h +++ b/assignment-client/src/audio/AvatarAudioRingBuffer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AvatarAudioRingBuffer__ -#define __hifi__AvatarAudioRingBuffer__ +#ifndef hifi_AvatarAudioRingBuffer_h +#define hifi_AvatarAudioRingBuffer_h #include @@ -27,4 +27,4 @@ private: AvatarAudioRingBuffer& operator= (const AvatarAudioRingBuffer&); }; -#endif /* defined(__hifi__AvatarAudioRingBuffer__) */ +#endif // hifi_AvatarAudioRingBuffer_h diff --git a/assignment-client/src/avatars/AvatarMixer.h b/assignment-client/src/avatars/AvatarMixer.h index b9add245a6..a69019427b 100644 --- a/assignment-client/src/avatars/AvatarMixer.h +++ b/assignment-client/src/avatars/AvatarMixer.h @@ -12,8 +12,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AvatarMixer__ -#define __hifi__AvatarMixer__ +#ifndef hifi_AvatarMixer_h +#define hifi_AvatarMixer_h #include @@ -49,4 +49,4 @@ private: int _sumIdentityPackets; }; -#endif /* defined(__hifi__AvatarMixer__) */ +#endif // hifi_AvatarMixer_h diff --git a/assignment-client/src/avatars/AvatarMixerClientData.h b/assignment-client/src/avatars/AvatarMixerClientData.h index 75affca7ff..18c29c4b0f 100644 --- a/assignment-client/src/avatars/AvatarMixerClientData.h +++ b/assignment-client/src/avatars/AvatarMixerClientData.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AvatarMixerClientData__ -#define __hifi__AvatarMixerClientData__ +#ifndef hifi_AvatarMixerClientData_h +#define hifi_AvatarMixerClientData_h #include @@ -40,4 +40,4 @@ private: quint64 _identityChangeTimestamp; }; -#endif /* defined(__hifi__AvatarMixerClientData__) */ +#endif // hifi_AvatarMixerClientData_h diff --git a/assignment-client/src/metavoxels/MetavoxelServer.h b/assignment-client/src/metavoxels/MetavoxelServer.h index 749ab93b2a..b01bb9b412 100644 --- a/assignment-client/src/metavoxels/MetavoxelServer.h +++ b/assignment-client/src/metavoxels/MetavoxelServer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__MetavoxelServer__ -#define __hifi__MetavoxelServer__ +#ifndef hifi_MetavoxelServer_h +#define hifi_MetavoxelServer_h #include #include @@ -95,4 +95,4 @@ private: QList _sendRecords; }; -#endif /* defined(__hifi__MetavoxelServer__) */ +#endif // hifi_MetavoxelServer_h diff --git a/assignment-client/src/octree/OctreeInboundPacketProcessor.h b/assignment-client/src/octree/OctreeInboundPacketProcessor.h index e14065a9c1..f637a9e7c9 100644 --- a/assignment-client/src/octree/OctreeInboundPacketProcessor.h +++ b/assignment-client/src/octree/OctreeInboundPacketProcessor.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __octree_server__OctreeInboundPacketProcessor__ -#define __octree_server__OctreeInboundPacketProcessor__ +#ifndef hifi_OctreeInboundPacketProcessor_h +#define hifi_OctreeInboundPacketProcessor_h #include @@ -83,4 +83,4 @@ private: NodeToSenderStatsMap _singleSenderStats; }; -#endif // __octree_server__OctreeInboundPacketProcessor__ +#endif // hifi_OctreeInboundPacketProcessor_h diff --git a/assignment-client/src/octree/OctreeQueryNode.h b/assignment-client/src/octree/OctreeQueryNode.h index 6c46679a0c..aa445db8a6 100644 --- a/assignment-client/src/octree/OctreeQueryNode.h +++ b/assignment-client/src/octree/OctreeQueryNode.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__OctreeQueryNode__ -#define __hifi__OctreeQueryNode__ +#ifndef hifi_OctreeQueryNode_h +#define hifi_OctreeQueryNode_h #include #include @@ -138,4 +138,4 @@ private: bool _isShuttingDown; }; -#endif /* defined(__hifi__OctreeQueryNode__) */ +#endif // hifi_OctreeQueryNode_h diff --git a/assignment-client/src/octree/OctreeSendThread.h b/assignment-client/src/octree/OctreeSendThread.h index 423d9fc2bb..95205af32f 100644 --- a/assignment-client/src/octree/OctreeSendThread.h +++ b/assignment-client/src/octree/OctreeSendThread.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __octree_server__OctreeSendThread__ -#define __octree_server__OctreeSendThread__ +#ifndef hifi_OctreeSendThread_h +#define hifi_OctreeSendThread_h #include #include @@ -55,4 +55,4 @@ private: bool _isShuttingDown; }; -#endif // __octree_server__OctreeSendThread__ +#endif // hifi_OctreeSendThread_h diff --git a/assignment-client/src/octree/OctreeServer.h b/assignment-client/src/octree/OctreeServer.h index bd37b4f896..d02764bc59 100644 --- a/assignment-client/src/octree/OctreeServer.h +++ b/assignment-client/src/octree/OctreeServer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __octree_server__OctreeServer__ -#define __octree_server__OctreeServer__ +#ifndef hifi_OctreeServer_h +#define hifi_OctreeServer_h #include #include @@ -219,4 +219,4 @@ protected: static QMutex _threadsDidCallWriteDatagramMutex; }; -#endif // __octree_server__OctreeServer__ +#endif // hifi_OctreeServer_h diff --git a/assignment-client/src/octree/OctreeServerConsts.h b/assignment-client/src/octree/OctreeServerConsts.h index 995a7d5b24..a10c81494c 100644 --- a/assignment-client/src/octree/OctreeServerConsts.h +++ b/assignment-client/src/octree/OctreeServerConsts.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __octree_server__OctreeServerConsts__ -#define __octree_server__OctreeServerConsts__ +#ifndef hifi_OctreeServerConsts_h +#define hifi_OctreeServerConsts_h #include #include // for MAX_PACKET_SIZE @@ -21,4 +21,4 @@ const int INTERVALS_PER_SECOND = 60; const int OCTREE_SEND_INTERVAL_USECS = (1000 * 1000)/INTERVALS_PER_SECOND; const int SENDING_TIME_TO_SPARE = 5 * 1000; // usec of sending interval to spare for calculating voxels -#endif // __octree_server__OctreeServerConsts__ +#endif // hifi_OctreeServerConsts_h diff --git a/assignment-client/src/particles/ParticleNodeData.h b/assignment-client/src/particles/ParticleNodeData.h index d6995ebb0c..340ce4844f 100644 --- a/assignment-client/src/particles/ParticleNodeData.h +++ b/assignment-client/src/particles/ParticleNodeData.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__ParticleNodeData__ -#define __hifi__ParticleNodeData__ +#ifndef hifi_ParticleNodeData_h +#define hifi_ParticleNodeData_h #include @@ -31,4 +31,4 @@ private: quint64 _lastDeletedParticlesSentAt; }; -#endif /* defined(__hifi__ParticleNodeData__) */ +#endif // hifi_ParticleNodeData_h diff --git a/assignment-client/src/particles/ParticleServer.h b/assignment-client/src/particles/ParticleServer.h index 8371ba0301..495fc02c68 100644 --- a/assignment-client/src/particles/ParticleServer.h +++ b/assignment-client/src/particles/ParticleServer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __particle_server__ParticleServer__ -#define __particle_server__ParticleServer__ +#ifndef hifi_ParticleServer_h +#define hifi_ParticleServer_h #include "../octree/OctreeServer.h" @@ -47,4 +47,4 @@ public slots: private: }; -#endif // __particle_server__ParticleServer__ +#endif // hifi_ParticleServer_h diff --git a/assignment-client/src/particles/ParticleServerConsts.h b/assignment-client/src/particles/ParticleServerConsts.h index be9764ffbf..49df2a181e 100644 --- a/assignment-client/src/particles/ParticleServerConsts.h +++ b/assignment-client/src/particles/ParticleServerConsts.h @@ -9,11 +9,11 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __particle_server__ParticleServerConsts__ -#define __particle_server__ParticleServerConsts__ +#ifndef hifi_ParticleServerConsts_h +#define hifi_ParticleServerConsts_h extern const char* PARTICLE_SERVER_NAME; extern const char* PARTICLE_SERVER_LOGGING_TARGET_NAME; extern const char* LOCAL_PARTICLES_PERSIST_FILE; -#endif // __particle_server__ParticleServerConsts__ +#endif // hifi_ParticleServerConsts_h diff --git a/assignment-client/src/voxels/VoxelNodeData.h b/assignment-client/src/voxels/VoxelNodeData.h index da6f41c10e..86d241852d 100644 --- a/assignment-client/src/voxels/VoxelNodeData.h +++ b/assignment-client/src/voxels/VoxelNodeData.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__VoxelNodeData__ -#define __hifi__VoxelNodeData__ +#ifndef hifi_VoxelNodeData_h +#define hifi_VoxelNodeData_h #include @@ -22,4 +22,4 @@ public: virtual PacketType getMyPacketType() const { return PacketTypeVoxelData; } }; -#endif /* defined(__hifi__VoxelNodeData__) */ +#endif // hifi_VoxelNodeData_h diff --git a/assignment-client/src/voxels/VoxelServer.h b/assignment-client/src/voxels/VoxelServer.h index 2014012f2c..e81c16fc38 100644 --- a/assignment-client/src/voxels/VoxelServer.h +++ b/assignment-client/src/voxels/VoxelServer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __voxel_server__VoxelServer__ -#define __voxel_server__VoxelServer__ +#ifndef hifi_VoxelServer_h +#define hifi_VoxelServer_h #include #include @@ -55,4 +55,4 @@ private: unsigned char _tempOutputBuffer[MAX_PACKET_SIZE]; }; -#endif // __voxel_server__VoxelServer__ +#endif // hifi_VoxelServer_h diff --git a/assignment-client/src/voxels/VoxelServerConsts.h b/assignment-client/src/voxels/VoxelServerConsts.h index 373a75f1e8..5764e7d4cf 100644 --- a/assignment-client/src/voxels/VoxelServerConsts.h +++ b/assignment-client/src/voxels/VoxelServerConsts.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __voxel_server__VoxelServerConsts__ -#define __voxel_server__VoxelServerConsts__ +#ifndef hifi_VoxelServerConsts_h +#define hifi_VoxelServerConsts_h extern const char* VOXEL_SERVER_NAME; extern const char* VOXEL_SERVER_LOGGING_TARGET_NAME; @@ -18,4 +18,4 @@ extern const char* LOCAL_VOXELS_PERSIST_FILE; const int ENVIRONMENT_SEND_INTERVAL_USECS = 1000000; -#endif // __voxel_server__VoxelServerConsts__ +#endif // hifi_VoxelServerConsts_h diff --git a/domain-server/src/DomainServer.h b/domain-server/src/DomainServer.h index 9a1853bdcc..c2f0eee995 100644 --- a/domain-server/src/DomainServer.h +++ b/domain-server/src/DomainServer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__DomainServer__ -#define __hifi__DomainServer__ +#ifndef hifi_DomainServer_h +#define hifi_DomainServer_h #include #include @@ -89,4 +89,4 @@ private slots: void readAvailableDatagrams(); }; -#endif /* defined(__hifi__DomainServer__) */ +#endif // hifi_DomainServer_h diff --git a/domain-server/src/DomainServerNodeData.h b/domain-server/src/DomainServerNodeData.h index 6da91c54fb..3b73ec17d2 100644 --- a/domain-server/src/DomainServerNodeData.h +++ b/domain-server/src/DomainServerNodeData.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__DomainServerNodeData__ -#define __hifi__DomainServerNodeData__ +#ifndef hifi_DomainServerNodeData_h +#define hifi_DomainServerNodeData_h #include #include @@ -38,4 +38,4 @@ private: QJsonObject _statsJSONObject; }; -#endif /* defined(__hifi__DomainServerNodeData__) */ +#endif // hifi_DomainServerNodeData_h diff --git a/interface/src/AbstractLoggerInterface.h b/interface/src/AbstractLoggerInterface.h index 647c104743..f6cf136a71 100644 --- a/interface/src/AbstractLoggerInterface.h +++ b/interface/src/AbstractLoggerInterface.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__AbstractLoggerInterface__ -#define __interface__AbstractLoggerInterface__ +#ifndef hifi_AbstractLoggerInterface_h +#define hifi_AbstractLoggerInterface_h #include #include @@ -35,4 +35,4 @@ private: bool _extraDebugging; }; -#endif /* defined(__interface__AbstractLoggerInterface__) */ +#endif // hifi_AbstractLoggerInterface_h diff --git a/interface/src/Application.h b/interface/src/Application.h index e7af91e997..61c2a15f95 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Application__ -#define __interface__Application__ +#ifndef hifi_Application_h +#define hifi_Application_h #include #include @@ -508,4 +508,4 @@ private: QHash _scriptEnginesHash; }; -#endif /* defined(__interface__Application__) */ +#endif // hifi_Application_h diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 647b88a4a9..84ab6c69cf 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Audio__ -#define __interface__Audio__ +#ifndef hifi_Audio_h +#define hifi_Audio_h #ifdef _WIN32 #define WANT_TIMEVAL @@ -192,4 +192,4 @@ private: }; -#endif /* defined(__interface__audio__) */ +#endif // hifi_Audio_h diff --git a/interface/src/BuckyBalls.h b/interface/src/BuckyBalls.h index 305ac4640c..f7690408d3 100644 --- a/interface/src/BuckyBalls.h +++ b/interface/src/BuckyBalls.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__BuckyBalls__ -#define __hifi__BuckyBalls__ +#ifndef hifi_BuckyBalls_h +#define hifi_BuckyBalls_h #include @@ -47,4 +47,4 @@ private: }; -#endif /* defined(__hifi__BuckyBalls__) */ +#endif // hifi_BuckyBalls_h diff --git a/interface/src/Camera.h b/interface/src/Camera.h index 6e4b533cdc..5e189c1111 100644 --- a/interface/src/Camera.h +++ b/interface/src/Camera.h @@ -8,8 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__camera__ -#define __interface__camera__ +#ifndef hifi_Camera_h +#define hifi_Camera_h #include #include @@ -154,4 +154,4 @@ private: Camera* _camera; ViewFrustum* _viewFrustum; }; -#endif +#endif // hifi_Camera_h diff --git a/interface/src/DatagramProcessor.h b/interface/src/DatagramProcessor.h index 6a55820e9d..7d337ec02b 100644 --- a/interface/src/DatagramProcessor.h +++ b/interface/src/DatagramProcessor.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__DatagramProcessor__ -#define __hifi__DatagramProcessor__ +#ifndef hifi_DatagramProcessor_h +#define hifi_DatagramProcessor_h #include @@ -31,4 +31,4 @@ private: int _byteCount; }; -#endif /* defined(__hifi__DatagramProcessor__) */ +#endif // hifi_DatagramProcessor_h diff --git a/interface/src/Environment.h b/interface/src/Environment.h index aca5fac9d8..525f3b7eb4 100644 --- a/interface/src/Environment.h +++ b/interface/src/Environment.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Environment__ -#define __interface__Environment__ +#ifndef hifi_Environment_h +#define hifi_Environment_h #include #include @@ -78,4 +78,4 @@ private: QMutex _mutex; }; -#endif /* defined(__interface__Environment__) */ +#endif // hifi_Environment_h diff --git a/interface/src/FileLogger.h b/interface/src/FileLogger.h index a65aa3321c..5da86044ab 100644 --- a/interface/src/FileLogger.h +++ b/interface/src/FileLogger.h @@ -32,4 +32,4 @@ private: }; -#endif +#endif // hifi_FileLogger_h diff --git a/interface/src/GLCanvas.h b/interface/src/GLCanvas.h index 0b75ef5c5f..73b70de19e 100644 --- a/interface/src/GLCanvas.h +++ b/interface/src/GLCanvas.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__GLCanvas__ -#define __hifi__GLCanvas__ +#ifndef hifi_GLCanvas_h +#define hifi_GLCanvas_h #include #include @@ -52,4 +52,4 @@ private slots: void throttleRender(); }; -#endif /* defined(__hifi__GLCanvas__) */ +#endif // hifi_GLCanvas_h diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 2b90d4e3c9..5bc48f916f 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__Menu__ -#define __hifi__Menu__ +#ifndef hifi_Menu_h +#define hifi_Menu_h #include #include @@ -323,4 +323,4 @@ namespace MenuOption { void sendFakeEnterEvent(); -#endif /* defined(__hifi__Menu__) */ +#endif // hifi_Menu_h diff --git a/interface/src/MetavoxelSystem.h b/interface/src/MetavoxelSystem.h index cc6fa6e743..f98a260ab1 100644 --- a/interface/src/MetavoxelSystem.h +++ b/interface/src/MetavoxelSystem.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__MetavoxelSystem__ -#define __interface__MetavoxelSystem__ +#ifndef hifi_MetavoxelSystem_h +#define hifi_MetavoxelSystem_h #include #include @@ -201,4 +201,4 @@ private: Model* _model; }; -#endif /* defined(__interface__MetavoxelSystem__) */ +#endif // hifi_MetavoxelSystem_h diff --git a/interface/src/ParticleTreeRenderer.h b/interface/src/ParticleTreeRenderer.h index 531cbc23f7..7dc866c731 100644 --- a/interface/src/ParticleTreeRenderer.h +++ b/interface/src/ParticleTreeRenderer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__ParticleTreeRenderer__ -#define __hifi__ParticleTreeRenderer__ +#ifndef hifi_ParticleTreeRenderer_h +#define hifi_ParticleTreeRenderer_h #include #include @@ -51,4 +51,4 @@ protected: QMap _particleModels; }; -#endif /* defined(__hifi__ParticleTreeRenderer__) */ +#endif // hifi_ParticleTreeRenderer_h diff --git a/interface/src/Physics.h b/interface/src/Physics.h index bf1673a0fe..97e873d920 100644 --- a/interface/src/Physics.h +++ b/interface/src/Physics.h @@ -15,4 +15,4 @@ void applyStaticFriction(float deltaTime, glm::vec3& velocity, float maxVelocity, float strength); void applyDamping(float deltaTime, glm::vec3& velocity, float linearStrength, float squaredStrength); -#endif +#endif // hifi_Physics_h diff --git a/interface/src/Stars.h b/interface/src/Stars.h index b38c1a2748..08f218b9fa 100755 --- a/interface/src/Stars.h +++ b/interface/src/Stars.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Stars__ -#define __interface__Stars__ +#ifndef hifi_Stars_h +#define hifi_Stars_h #include @@ -52,5 +52,4 @@ private: }; -#endif - +#endif // hifi_Stars_h diff --git a/interface/src/Util.h b/interface/src/Util.h index 26a3c85e3c..4f0e76adf8 100644 --- a/interface/src/Util.h +++ b/interface/src/Util.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Util__ -#define __interface__Util__ +#ifndef hifi_Util_h +#define hifi_Util_h #ifdef _WIN32 #include "Systime.h" @@ -80,4 +80,4 @@ bool rayIntersectsSphere(const glm::vec3& rayStarting, const glm::vec3& rayNorma bool pointInSphere(glm::vec3& point, glm::vec3& sphereCenter, double sphereRadius); -#endif +#endif // hifi_Util_h diff --git a/interface/src/XmppClient.h b/interface/src/XmppClient.h index ac724a4d68..8af3204377 100644 --- a/interface/src/XmppClient.h +++ b/interface/src/XmppClient.h @@ -11,8 +11,8 @@ #ifdef HAVE_QXMPP -#ifndef __interface__XmppClient__ -#define __interface__XmppClient__ +#ifndef hifi_XmppClient_h +#define hifi_XmppClient_h #include #include @@ -47,4 +47,4 @@ private: #endif // __interface__XmppClient__ -#endif +#endif // hifi_XmppClient_h diff --git a/interface/src/avatar/Avatar.h b/interface/src/avatar/Avatar.h index a1bc7ad0bd..4e24c00c7e 100755 --- a/interface/src/avatar/Avatar.h +++ b/interface/src/avatar/Avatar.h @@ -8,8 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__avatar__ -#define __interface__avatar__ +#ifndef hifi_Avatar_h +#define hifi_Avatar_h #include #include @@ -202,4 +202,4 @@ private: float getBillboardSize() const; }; -#endif +#endif // hifi_Avatar_h diff --git a/interface/src/avatar/AvatarManager.h b/interface/src/avatar/AvatarManager.h index db3c9dbf44..78491b3a5d 100644 --- a/interface/src/avatar/AvatarManager.h +++ b/interface/src/avatar/AvatarManager.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AvatarManager__ -#define __hifi__AvatarManager__ +#ifndef hifi_AvatarManager_h +#define hifi_AvatarManager_h #include #include @@ -59,4 +59,4 @@ private: QSharedPointer _myAvatar; }; -#endif /* defined(__hifi__AvatarManager__) */ +#endif // hifi_AvatarManager_h diff --git a/interface/src/avatar/FaceModel.h b/interface/src/avatar/FaceModel.h index 3fec640bdd..fdf8ab1fd2 100644 --- a/interface/src/avatar/FaceModel.h +++ b/interface/src/avatar/FaceModel.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__FaceModel__ -#define __interface__FaceModel__ +#ifndef hifi_FaceModel_h +#define hifi_FaceModel_h #include "renderer/Model.h" @@ -36,4 +36,4 @@ private: Head* _owningHead; }; -#endif /* defined(__interface__FaceModel__) */ +#endif // hifi_FaceModel_h diff --git a/interface/src/avatar/Hand.h b/interface/src/avatar/Hand.h index f3054a7080..1c857a198a 100755 --- a/interface/src/avatar/Hand.h +++ b/interface/src/avatar/Hand.h @@ -84,5 +84,4 @@ private: void playSlaps(PalmData& palm, Avatar* avatar); }; -#endif - +#endif // hifi_Hand_h diff --git a/interface/src/avatar/Head.h b/interface/src/avatar/Head.h index f4840121a6..a6cda5622c 100644 --- a/interface/src/avatar/Head.h +++ b/interface/src/avatar/Head.h @@ -140,4 +140,4 @@ private: friend class FaceModel; }; -#endif +#endif // hifi_Head_h diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index d0589687df..946481f3e6 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__myavatar__ -#define __interface__myavatar__ +#ifndef hifi_MyAvatar_h +#define hifi_MyAvatar_h #include @@ -143,4 +143,4 @@ private: void maybeUpdateBillboard(); }; -#endif +#endif // hifi_MyAvatar_h diff --git a/interface/src/avatar/SkeletonModel.h b/interface/src/avatar/SkeletonModel.h index b3a7c4c7e4..2020ccf3b2 100644 --- a/interface/src/avatar/SkeletonModel.h +++ b/interface/src/avatar/SkeletonModel.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__SkeletonModel__ -#define __interface__SkeletonModel__ +#ifndef hifi_SkeletonModel_h +#define hifi_SkeletonModel_h #include "renderer/Model.h" @@ -50,4 +50,4 @@ private: Avatar* _owningAvatar; }; -#endif /* defined(__interface__SkeletonModel__) */ +#endif // hifi_SkeletonModel_h diff --git a/interface/src/devices/Faceshift.h b/interface/src/devices/Faceshift.h index abac2c74a1..157409882c 100644 --- a/interface/src/devices/Faceshift.h +++ b/interface/src/devices/Faceshift.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Faceshift__ -#define __interface__Faceshift__ +#ifndef hifi_Faceshift_h +#define hifi_Faceshift_h #include #include @@ -141,4 +141,4 @@ private: float _estimatedEyeYaw; }; -#endif /* defined(__interface__Faceshift__) */ +#endif // hifi_Faceshift_h diff --git a/interface/src/devices/OculusManager.h b/interface/src/devices/OculusManager.h index 7927c84341..09e204d795 100644 --- a/interface/src/devices/OculusManager.h +++ b/interface/src/devices/OculusManager.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__OculusManager__ -#define __hifi__OculusManager__ +#ifndef hifi_OculusManager_h +#define hifi_OculusManager_h #include @@ -62,4 +62,4 @@ private: #endif }; -#endif /* defined(__hifi__OculusManager__) */ +#endif // hifi_OculusManager_h diff --git a/interface/src/devices/SixenseManager.h b/interface/src/devices/SixenseManager.h index 24c37a027f..2fc6b3dcb3 100644 --- a/interface/src/devices/SixenseManager.h +++ b/interface/src/devices/SixenseManager.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__SixenseManager__ -#define __interface__SixenseManager__ +#ifndef hifi_SixenseManager_h +#define hifi_SixenseManager_h #include @@ -66,5 +66,4 @@ private: quint64 _lastMovement; }; -#endif /* defined(__interface__SixenseManager__) */ - +#endif // hifi_SixenseManager_h diff --git a/interface/src/devices/TV3DManager.h b/interface/src/devices/TV3DManager.h index aa1f927676..91a78e9bce 100644 --- a/interface/src/devices/TV3DManager.h +++ b/interface/src/devices/TV3DManager.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__TV3DManager__ -#define __hifi__TV3DManager__ +#ifndef hifi_TV3DManager_h +#define hifi_TV3DManager_h #include @@ -41,4 +41,4 @@ private: static eyeFrustum _rightEye; }; -#endif /* defined(__hifi__TV3DManager__) */ +#endif // hifi_TV3DManager_h diff --git a/interface/src/devices/Visage.h b/interface/src/devices/Visage.h index 02cceb8afa..68c5055954 100644 --- a/interface/src/devices/Visage.h +++ b/interface/src/devices/Visage.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Visage__ -#define __interface__Visage__ +#ifndef hifi_Visage_h +#define hifi_Visage_h #include #include @@ -75,4 +75,4 @@ private: QVector _blendshapeCoefficients; }; -#endif /* defined(__interface__Visage__) */ +#endif // hifi_Visage_h diff --git a/interface/src/location/LocationManager.h b/interface/src/location/LocationManager.h index cda64e5058..26e1cb52d5 100644 --- a/interface/src/location/LocationManager.h +++ b/interface/src/location/LocationManager.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__LocationManager__ -#define __hifi__LocationManager__ +#ifndef hifi_LocationManager_h +#define hifi_LocationManager_h #include @@ -58,4 +58,4 @@ private slots: }; -#endif /* defined(__hifi__LocationManager__) */ +#endif // hifi_LocationManager_h diff --git a/interface/src/location/NamedLocation.h b/interface/src/location/NamedLocation.h index 7aa020f8e9..ffbd157263 100644 --- a/interface/src/location/NamedLocation.h +++ b/interface/src/location/NamedLocation.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__NamedLocation__ -#define __hifi__NamedLocation__ +#ifndef hifi_NamedLocation_h +#define hifi_NamedLocation_h #include #include @@ -58,4 +58,4 @@ private: }; -#endif /* defined(__hifi__NamedLocation__) */ +#endif // hifi_NamedLocation_h diff --git a/interface/src/renderer/AmbientOcclusionEffect.h b/interface/src/renderer/AmbientOcclusionEffect.h index 1711b89d16..3b22c7629a 100644 --- a/interface/src/renderer/AmbientOcclusionEffect.h +++ b/interface/src/renderer/AmbientOcclusionEffect.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__AmbientOcclusionEffect__ -#define __interface__AmbientOcclusionEffect__ +#ifndef hifi_AmbientOcclusionEffect_h +#define hifi_AmbientOcclusionEffect_h class ProgramObject; @@ -40,4 +40,4 @@ private: GLuint _rotationTextureID; }; -#endif /* defined(__interface__AmbientOcclusionEffect__) */ +#endif // hifi_AmbientOcclusionEffect_h diff --git a/interface/src/renderer/FBXReader.h b/interface/src/renderer/FBXReader.h index 85ca23c53f..73c305e2eb 100644 --- a/interface/src/renderer/FBXReader.h +++ b/interface/src/renderer/FBXReader.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__FBXReader__ -#define __interface__FBXReader__ +#ifndef hifi_FBXReader_h +#define hifi_FBXReader_h #include #include @@ -203,4 +203,4 @@ FBXGeometry readFBX(const QByteArray& model, const QVariantHash& mapping); /// Reads SVO geometry from the supplied model data. FBXGeometry readSVO(const QByteArray& model); -#endif /* defined(__interface__FBXReader__) */ +#endif // hifi_FBXReader_h diff --git a/interface/src/renderer/GeometryCache.h b/interface/src/renderer/GeometryCache.h index ea6b3c2e0f..c2d276fb5e 100644 --- a/interface/src/renderer/GeometryCache.h +++ b/interface/src/renderer/GeometryCache.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__GeometryCache__ -#define __interface__GeometryCache__ +#ifndef hifi_GeometryCache_h +#define hifi_GeometryCache_h // include this before QOpenGLBuffer, which includes an earlier version of OpenGL #include "InterfaceConfig.h" @@ -140,4 +140,4 @@ public: int getTranslucentPartCount() const; }; -#endif /* defined(__interface__GeometryCache__) */ +#endif // hifi_GeometryCache_h diff --git a/interface/src/renderer/GlowEffect.h b/interface/src/renderer/GlowEffect.h index cf635083c6..b675589526 100644 --- a/interface/src/renderer/GlowEffect.h +++ b/interface/src/renderer/GlowEffect.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__GlowEffect__ -#define __interface__GlowEffect__ +#ifndef hifi_GlowEffect_h +#define hifi_GlowEffect_h #include #include @@ -83,4 +83,4 @@ public: ~Glower(); }; -#endif /* defined(__interface__GlowEffect__) */ +#endif // hifi_GlowEffect_h diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index dea5e3aa59..30625cc16f 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Model__ -#define __interface__Model__ +#ifndef hifi_Model_h +#define hifi_Model_h #include #include @@ -309,4 +309,4 @@ Q_DECLARE_METATYPE(QPointer) Q_DECLARE_METATYPE(QWeakPointer) Q_DECLARE_METATYPE(QVector) -#endif /* defined(__interface__Model__) */ +#endif // hifi_Model_h diff --git a/interface/src/renderer/PointShader.h b/interface/src/renderer/PointShader.h index f67e2239cc..1db4f1b201 100644 --- a/interface/src/renderer/PointShader.h +++ b/interface/src/renderer/PointShader.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__PointShader__ -#define __interface__PointShader__ +#ifndef hifi_PointShader_h +#define hifi_PointShader_h #include @@ -45,4 +45,4 @@ private: ProgramObject* _program; }; -#endif /* defined(__interface__PointShader__) */ +#endif // hifi_PointShader_h diff --git a/interface/src/renderer/ProgramObject.h b/interface/src/renderer/ProgramObject.h index 3c902cd215..21e01ac8b3 100644 --- a/interface/src/renderer/ProgramObject.h +++ b/interface/src/renderer/ProgramObject.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__ProgramObject__ -#define __interface__ProgramObject__ +#ifndef hifi_ProgramObject_h +#define hifi_ProgramObject_h #include @@ -25,4 +25,4 @@ public: void setUniform(const char* name, const glm::vec3& value); }; -#endif /* defined(__interface__ProgramObject__) */ +#endif // hifi_ProgramObject_h diff --git a/interface/src/renderer/RenderUtil.h b/interface/src/renderer/RenderUtil.h index fb71f46e9e..637596c78b 100644 --- a/interface/src/renderer/RenderUtil.h +++ b/interface/src/renderer/RenderUtil.h @@ -9,10 +9,10 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__RenderUtil__ -#define __interface__RenderUtil__ +#ifndef hifi_RenderUtil_h +#define hifi_RenderUtil_h /// Renders a quad from (-1, -1, 0) to (1, 1, 0) with texture coordinates from (sMin, 0) to (sMax, 1). void renderFullscreenQuad(float sMin = 0.0f, float sMax = 1.0f); -#endif /* defined(__interface__RenderUtil__) */ +#endif // hifi_RenderUtil_h diff --git a/interface/src/renderer/TextureCache.h b/interface/src/renderer/TextureCache.h index d8884c310f..e66044d843 100644 --- a/interface/src/renderer/TextureCache.h +++ b/interface/src/renderer/TextureCache.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__TextureCache__ -#define __interface__TextureCache__ +#ifndef hifi_TextureCache_h +#define hifi_TextureCache_h #include #include @@ -158,4 +158,4 @@ private: QMap > _dilatedTextures; }; -#endif /* defined(__interface__TextureCache__) */ +#endif // hifi_TextureCache_h diff --git a/interface/src/renderer/VoxelShader.h b/interface/src/renderer/VoxelShader.h index 4d8a4c749c..cfcd27bba7 100644 --- a/interface/src/renderer/VoxelShader.h +++ b/interface/src/renderer/VoxelShader.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__VoxelShader__ -#define __interface__VoxelShader__ +#ifndef hifi_VoxelShader_h +#define hifi_VoxelShader_h #include @@ -46,4 +46,4 @@ private: ProgramObject* _program; }; -#endif /* defined(__interface__VoxelShader__) */ +#endif // hifi_VoxelShader_h diff --git a/interface/src/scripting/AudioDeviceScriptingInterface.h b/interface/src/scripting/AudioDeviceScriptingInterface.h index 0495517139..62f1153a0b 100644 --- a/interface/src/scripting/AudioDeviceScriptingInterface.h +++ b/interface/src/scripting/AudioDeviceScriptingInterface.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AudioDeviceScriptingInterface__ -#define __hifi__AudioDeviceScriptingInterface__ +#ifndef hifi_AudioDeviceScriptingInterface_h +#define hifi_AudioDeviceScriptingInterface_h #include #include @@ -41,4 +41,4 @@ public slots: void setInputVolume(float volume); }; -#endif /* defined(__hifi__AudioDeviceScriptingInterface__) */ +#endif // hifi_AudioDeviceScriptingInterface_h diff --git a/interface/src/scripting/ClipboardScriptingInterface.h b/interface/src/scripting/ClipboardScriptingInterface.h index 16872b1952..f0258b0cc7 100644 --- a/interface/src/scripting/ClipboardScriptingInterface.h +++ b/interface/src/scripting/ClipboardScriptingInterface.h @@ -8,8 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Clipboard__ -#define __interface__Clipboard__ +#ifndef hifi_ClipboardScriptingInterface_h +#define hifi_ClipboardScriptingInterface_h #include #include @@ -44,4 +44,4 @@ public slots: void nudgeVoxel(float x, float y, float z, float s, const glm::vec3& nudgeVec); }; -#endif // __interface__Clipboard__ +#endif // hifi_ClipboardScriptingInterface_h diff --git a/interface/src/scripting/ControllerScriptingInterface.h b/interface/src/scripting/ControllerScriptingInterface.h index ebe5f4d943..c5d805dca5 100644 --- a/interface/src/scripting/ControllerScriptingInterface.h +++ b/interface/src/scripting/ControllerScriptingInterface.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__ControllerScriptingInterface__ -#define __hifi__ControllerScriptingInterface__ +#ifndef hifi_ControllerScriptingInterface_h +#define hifi_ControllerScriptingInterface_h #include @@ -98,4 +98,4 @@ const int NUMBER_OF_BUTTONS_PER_PALM = 6; const int PALM_SPATIALCONTROL = 0; const int TIP_SPATIALCONTROL = 1; -#endif /* defined(__hifi__ControllerScriptingInterface__) */ +#endif // hifi_ControllerScriptingInterface_h diff --git a/interface/src/scripting/MenuScriptingInterface.h b/interface/src/scripting/MenuScriptingInterface.h index 15042fd355..d127bd6edc 100644 --- a/interface/src/scripting/MenuScriptingInterface.h +++ b/interface/src/scripting/MenuScriptingInterface.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__MenuScriptingInterface__ -#define __hifi__MenuScriptingInterface__ +#ifndef hifi_MenuScriptingInterface_h +#define hifi_MenuScriptingInterface_h #include #include @@ -50,4 +50,4 @@ signals: void menuItemEvent(const QString& menuItem); }; -#endif /* defined(__hifi__MenuScriptingInterface__) */ +#endif // hifi_MenuScriptingInterface_h diff --git a/interface/src/scripting/SettingsScriptingInterface.h b/interface/src/scripting/SettingsScriptingInterface.h index 84855c1b3c..e3138be4a0 100644 --- a/interface/src/scripting/SettingsScriptingInterface.h +++ b/interface/src/scripting/SettingsScriptingInterface.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__SettingsScriptingInterface__ -#define __hifi__SettingsScriptingInterface__ +#ifndef hifi_SettingsScriptingInterface_h +#define hifi_SettingsScriptingInterface_h #include #include @@ -30,4 +30,4 @@ public slots: void setValue(const QString& setting, const QVariant& value); }; -#endif /* defined(__hifi__SettingsScriptingInterface__) */ +#endif // hifi_SettingsScriptingInterface_h diff --git a/interface/src/starfield/Config.h b/interface/src/starfield/Config.h index a44006fb17..7777c5207b 100755 --- a/interface/src/starfield/Config.h +++ b/interface/src/starfield/Config.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__starfield__Config__ -#define __interface__starfield__Config__ +#ifndef hifi_Config_h +#define hifi_Config_h #include "InterfaceConfig.h" #include "renderer/ProgramObject.h" @@ -58,4 +58,4 @@ namespace starfield { } -#endif \ No newline at end of file +#endif // hifi_Config_h diff --git a/interface/src/starfield/Controller.h b/interface/src/starfield/Controller.h index b994d48580..06db5cb833 100755 --- a/interface/src/starfield/Controller.h +++ b/interface/src/starfield/Controller.h @@ -10,8 +10,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__starfield__Controller__ -#define __interface__starfield__Controller__ +#ifndef hifi_Controller_h +#define hifi_Controller_h #include @@ -41,4 +41,4 @@ namespace starfield { Renderer* _renderer; }; } -#endif +#endif // hifi_Controller_h diff --git a/interface/src/starfield/Generator.h b/interface/src/starfield/Generator.h index 238ff99f80..5352b3daf1 100644 --- a/interface/src/starfield/Generator.h +++ b/interface/src/starfield/Generator.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__starfield__Generator__ -#define __interface__starfield__Generator__ +#ifndef hifi_Generator_h +#define hifi_Generator_h #include #include @@ -37,4 +37,4 @@ namespace starfield { }; } -#endif +#endif // hifi_Generator_h diff --git a/interface/src/starfield/data/GpuVertex.h b/interface/src/starfield/data/GpuVertex.h index 71cef97061..f3b3ccd451 100755 --- a/interface/src/starfield/data/GpuVertex.h +++ b/interface/src/starfield/data/GpuVertex.h @@ -10,8 +10,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__starfield__data__GpuVertex__ -#define __interface__starfield__data__GpuVertex__ +#ifndef hifi_GpuVertex_h +#define hifi_GpuVertex_h #include "starfield/data/InputVertex.h" @@ -34,5 +34,4 @@ namespace starfield { } -#endif - +#endif // hifi_GpuVertex_h diff --git a/interface/src/starfield/data/InputVertex.h b/interface/src/starfield/data/InputVertex.h index f78f3ea136..2eeda183ec 100755 --- a/interface/src/starfield/data/InputVertex.h +++ b/interface/src/starfield/data/InputVertex.h @@ -10,8 +10,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__starfield__data__InputVertex__ -#define __interface__starfield__data__InputVertex__ +#ifndef hifi_InputVertex_h +#define hifi_InputVertex_h #include "starfield/Config.h" @@ -36,5 +36,4 @@ namespace starfield { } -#endif - +#endif // hifi_InputVertex_h diff --git a/interface/src/starfield/data/Tile.h b/interface/src/starfield/data/Tile.h index 17e737af38..7273394984 100755 --- a/interface/src/starfield/data/Tile.h +++ b/interface/src/starfield/data/Tile.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__starfield__data__Tile__ -#define __interface__starfield__data__Tile__ +#ifndef hifi_Tile_h +#define hifi_Tile_h #include "starfield/Config.h" @@ -29,5 +29,4 @@ namespace starfield { } -#endif - +#endif // hifi_Tile_h diff --git a/interface/src/starfield/renderer/Renderer.h b/interface/src/starfield/renderer/Renderer.h index 2494377180..1e271512d2 100755 --- a/interface/src/starfield/renderer/Renderer.h +++ b/interface/src/starfield/renderer/Renderer.h @@ -10,8 +10,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__starfield__renderer__Renderer__ -#define __interface__starfield__renderer__Renderer__ +#ifndef hifi_Renderer_h +#define hifi_Renderer_h #include "starfield/Config.h" #include "starfield/data/InputVertex.h" @@ -139,4 +139,4 @@ namespace starfield { } -#endif \ No newline at end of file +#endif // hifi_Renderer_h diff --git a/interface/src/starfield/renderer/Tiling.h b/interface/src/starfield/renderer/Tiling.h index 91547d87ca..e299b0998f 100755 --- a/interface/src/starfield/renderer/Tiling.h +++ b/interface/src/starfield/renderer/Tiling.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__starfield__renderer__Tiling__ -#define __interface__starfield__renderer__Tiling__ +#ifndef hifi_Tiling_h +#define hifi_Tiling_h #include "starfield/Config.h" @@ -45,5 +45,4 @@ namespace starfield { }; } -#endif - +#endif // hifi_Tiling_h diff --git a/interface/src/starfield/renderer/VertexOrder.h b/interface/src/starfield/renderer/VertexOrder.h index 704af857cf..e45ccdedb0 100755 --- a/interface/src/starfield/renderer/VertexOrder.h +++ b/interface/src/starfield/renderer/VertexOrder.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__starfield__renderer__VertexOrder__ -#define __interface__starfield__renderer__VertexOrder__ +#ifndef hifi_VertexOrder_h +#define hifi_VertexOrder_h #include "starfield/Config.h" #include "starfield/data/InputVertex.h" @@ -38,5 +38,4 @@ namespace starfield { } // anonymous namespace -#endif - +#endif // hifi_VertexOrder_h diff --git a/interface/src/ui/BandwidthDialog.h b/interface/src/ui/BandwidthDialog.h index 51ed3453cd..c1e9c5b82e 100644 --- a/interface/src/ui/BandwidthDialog.h +++ b/interface/src/ui/BandwidthDialog.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__BandwidthDialog__ -#define __hifi__BandwidthDialog__ +#ifndef hifi_BandwidthDialog_h +#define hifi_BandwidthDialog_h #include #include @@ -46,5 +46,4 @@ private: QLabel* _labels[BandwidthMeter::N_STREAMS]; }; -#endif /* defined(__interface__BandwidthDialog__) */ - +#endif // hifi_BandwidthDialog_h diff --git a/interface/src/ui/BandwidthMeter.h b/interface/src/ui/BandwidthMeter.h index 830bc6502d..45226c8e82 100644 --- a/interface/src/ui/BandwidthMeter.h +++ b/interface/src/ui/BandwidthMeter.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__BandwidthMeter__ -#define __interface__BandwidthMeter__ +#ifndef hifi_BandwidthMeter_h +#define hifi_BandwidthMeter_h #ifdef _WIN32 #define WANT_TIMEVAL @@ -87,5 +87,4 @@ private: int _scaleMaxIndex; }; -#endif /* defined(__interface__BandwidthMeter__) */ - +#endif // hifi_BandwidthMeter_h diff --git a/interface/src/ui/ChatWindow.h b/interface/src/ui/ChatWindow.h index 9ab17c067b..cb9619cc42 100644 --- a/interface/src/ui/ChatWindow.h +++ b/interface/src/ui/ChatWindow.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__ChatWindow__ -#define __interface__ChatWindow__ +#ifndef hifi_ChatWindow_h +#define hifi_ChatWindow_h #include #include @@ -63,4 +63,4 @@ private slots: #endif }; -#endif /* defined(__interface__ChatWindow__) */ +#endif // hifi_ChatWindow_h diff --git a/interface/src/ui/ImportDialog.h b/interface/src/ui/ImportDialog.h index dc707395de..88cfda7a7c 100644 --- a/interface/src/ui/ImportDialog.h +++ b/interface/src/ui/ImportDialog.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__ImportDialog__ -#define __hifi__ImportDialog__ +#ifndef hifi_ImportDialog_h +#define hifi_ImportDialog_h #include "InterfaceConfig.h" @@ -70,4 +70,4 @@ private: void setImportTypes(); }; -#endif /* defined(__hifi__ImportDialog__) */ +#endif // hifi_ImportDialog_h diff --git a/interface/src/ui/InfoView.h b/interface/src/ui/InfoView.h index a400e8dacf..94d18ff6a1 100644 --- a/interface/src/ui/InfoView.h +++ b/interface/src/ui/InfoView.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__InfoView__ -#define __hifi__InfoView__ +#ifndef hifi_InfoView_h +#define hifi_InfoView_h #include @@ -29,4 +29,4 @@ private slots: void loaded(bool ok); }; -#endif /* defined(__hifi__InfoView__) */ +#endif // hifi_InfoView_h diff --git a/interface/src/ui/LodToolsDialog.h b/interface/src/ui/LodToolsDialog.h index 200fb44ca1..a3223806aa 100644 --- a/interface/src/ui/LodToolsDialog.h +++ b/interface/src/ui/LodToolsDialog.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__LodToolsDialog__ -#define __hifi__LodToolsDialog__ +#ifndef hifi_LodToolsDialog_h +#define hifi_LodToolsDialog_h #include #include @@ -44,5 +44,4 @@ private: QLabel* _feedback; }; -#endif /* defined(__interface__LodToolsDialog__) */ - +#endif // hifi_LodToolsDialog_h diff --git a/interface/src/ui/LogDialog.h b/interface/src/ui/LogDialog.h index c4d4676189..914e1b4949 100644 --- a/interface/src/ui/LogDialog.h +++ b/interface/src/ui/LogDialog.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__LogDialog__ -#define __interface__LogDialog__ +#ifndef hifi_LogDialog_h +#define hifi_LogDialog_h #include "InterfaceConfig.h" @@ -74,5 +74,4 @@ private: void showLogData(); }; -#endif - +#endif // hifi_LogDialog_h diff --git a/interface/src/ui/MetavoxelEditor.h b/interface/src/ui/MetavoxelEditor.h index f0e8dff7ec..79ffd1e64c 100644 --- a/interface/src/ui/MetavoxelEditor.h +++ b/interface/src/ui/MetavoxelEditor.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__MetavoxelEditor__ -#define __interface__MetavoxelEditor__ +#ifndef hifi_MetavoxelEditor_h +#define hifi_MetavoxelEditor_h #include #include @@ -223,4 +223,4 @@ protected: virtual void applyEdit(const AttributePointer& attribute, const SharedObjectPointer& spanner); }; -#endif /* defined(__interface__MetavoxelEditor__) */ +#endif // hifi_MetavoxelEditor_h diff --git a/interface/src/ui/ModelsBrowser.h b/interface/src/ui/ModelsBrowser.h index 01b3e2e405..81f64c6730 100644 --- a/interface/src/ui/ModelsBrowser.h +++ b/interface/src/ui/ModelsBrowser.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__ModelsBrowser__ -#define __hifi__ModelsBrowser__ +#ifndef hifi_ModelsBrowser_h +#define hifi_ModelsBrowser_h #include #include @@ -78,4 +78,4 @@ private: QTreeView _view; }; -#endif /* defined(__hifi__ModelBrowser__) */ +#endif // hifi_ModelsBrowser_h diff --git a/interface/src/ui/OctreeStatsDialog.h b/interface/src/ui/OctreeStatsDialog.h index 0a0d7af5fd..2488667a09 100644 --- a/interface/src/ui/OctreeStatsDialog.h +++ b/interface/src/ui/OctreeStatsDialog.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__OctreeStatsDialog__ -#define __hifi__OctreeStatsDialog__ +#ifndef hifi_OctreeStatsDialog_h +#define hifi_OctreeStatsDialog_h #include #include @@ -69,5 +69,4 @@ private: details _extraServerDetails[MAX_VOXEL_SERVERS]; }; -#endif /* defined(__interface__OctreeStatsDialog__) */ - +#endif // hifi_OctreeStatsDialog_h diff --git a/interface/src/ui/Oscilloscope.h b/interface/src/ui/Oscilloscope.h index d51a1d8242..6eff547530 100644 --- a/interface/src/ui/Oscilloscope.h +++ b/interface/src/ui/Oscilloscope.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Oscilloscope__ -#define __interface__Oscilloscope__ +#ifndef hifi_Oscilloscope_h +#define hifi_Oscilloscope_h #include @@ -81,4 +81,4 @@ private: unsigned _colors[MAX_CHANNELS]; }; -#endif /* defined(__interface__oscilloscope__) */ +#endif // hifi_Oscilloscope_h diff --git a/interface/src/ui/RearMirrorTools.h b/interface/src/ui/RearMirrorTools.h index a25aeec1bd..a595572e7a 100644 --- a/interface/src/ui/RearMirrorTools.h +++ b/interface/src/ui/RearMirrorTools.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__RearMirrorTools__ -#define __hifi__RearMirrorTools__ +#ifndef hifi_RearMirrorTools_h +#define hifi_RearMirrorTools_h #include "InterfaceConfig.h" @@ -58,4 +58,4 @@ private: void displayIcon(QRect bounds, QRect iconBounds, GLuint textureId, bool selected = false); }; -#endif /* defined(__hifi__RearMirrorTools__) */ +#endif // hifi_RearMirrorTools_h diff --git a/interface/src/ui/RunningScriptsWidget.h b/interface/src/ui/RunningScriptsWidget.h index 718c417ba8..c4e1316e15 100644 --- a/interface/src/ui/RunningScriptsWidget.h +++ b/interface/src/ui/RunningScriptsWidget.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__RunningScriptsWidget__ -#define __hifi__RunningScriptsWidget__ +#ifndef hifi_RunningScriptsWidget_h +#define hifi_RunningScriptsWidget_h // Qt #include @@ -47,4 +47,4 @@ private: void createRecentlyLoadedScriptsTable(); }; -#endif /* defined(__hifi__RunningScriptsWidget__) */ +#endif // hifi_RunningScriptsWidget_h diff --git a/interface/src/ui/Snapshot.h b/interface/src/ui/Snapshot.h index ec5e9d5f13..0fa9017b0a 100644 --- a/interface/src/ui/Snapshot.h +++ b/interface/src/ui/Snapshot.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__Snapshot__ -#define __hifi__Snapshot__ +#ifndef hifi_Snapshot_h +#define hifi_Snapshot_h #include "InterfaceConfig.h" @@ -45,4 +45,4 @@ public: static SnapshotMetaData* parseSnapshotData(QString snapshotPath); }; -#endif /* defined(__hifi__Snapshot__) */ +#endif // hifi_Snapshot_h diff --git a/interface/src/ui/Stats.h b/interface/src/ui/Stats.h index 3d3e930b85..1ce0807ee8 100644 --- a/interface/src/ui/Stats.h +++ b/interface/src/ui/Stats.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef _hifi_Stats_h -#define _hifi_Stats_h +#ifndef hifi_Stats_h +#define hifi_Stats_h #include @@ -46,4 +46,4 @@ private: int _lastHorizontalOffset; }; -#endif +#endif // hifi_Stats_h diff --git a/interface/src/ui/TextRenderer.h b/interface/src/ui/TextRenderer.h index a24612ab93..813f15a5ac 100644 --- a/interface/src/ui/TextRenderer.h +++ b/interface/src/ui/TextRenderer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__TextRenderer__ -#define __interface__TextRenderer__ +#ifndef hifi_TextRenderer_h +#define hifi_TextRenderer_h #include #include @@ -114,4 +114,4 @@ private: int _width; }; -#endif /* defined(__interface__TextRenderer__) */ +#endif // hifi_TextRenderer_h diff --git a/interface/src/ui/UpdateDialog.h b/interface/src/ui/UpdateDialog.h index e346330f71..15a97bf024 100644 --- a/interface/src/ui/UpdateDialog.h +++ b/interface/src/ui/UpdateDialog.h @@ -8,8 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__UpdateDialog__ -#define __hifi__UpdateDialog__ +#ifndef hifi_UpdateDialog_h +#define hifi_UpdateDialog_h #include @@ -28,4 +28,4 @@ private slots: void handleSkip(); }; -#endif /* defined(__hifi__UpdateDialog__) */ +#endif // hifi_UpdateDialog_h diff --git a/interface/src/ui/overlays/Base3DOverlay.h b/interface/src/ui/overlays/Base3DOverlay.h index c464bfc2a7..e2dcb82454 100644 --- a/interface/src/ui/overlays/Base3DOverlay.h +++ b/interface/src/ui/overlays/Base3DOverlay.h @@ -8,8 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Base3DOverlay__ -#define __interface__Base3DOverlay__ +#ifndef hifi_Base3DOverlay_h +#define hifi_Base3DOverlay_h #include "Overlay.h" @@ -36,4 +36,4 @@ protected: }; -#endif /* defined(__interface__Base3DOverlay__) */ +#endif // hifi_Base3DOverlay_h diff --git a/interface/src/ui/overlays/Cube3DOverlay.h b/interface/src/ui/overlays/Cube3DOverlay.h index 0bdebea5b2..828048e697 100644 --- a/interface/src/ui/overlays/Cube3DOverlay.h +++ b/interface/src/ui/overlays/Cube3DOverlay.h @@ -8,8 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Cube3DOverlay__ -#define __interface__Cube3DOverlay__ +#ifndef hifi_Cube3DOverlay_h +#define hifi_Cube3DOverlay_h #include "Volume3DOverlay.h" @@ -23,4 +23,4 @@ public: }; -#endif /* defined(__interface__Cube3DOverlay__) */ +#endif // hifi_Cube3DOverlay_h diff --git a/interface/src/ui/overlays/ImageOverlay.h b/interface/src/ui/overlays/ImageOverlay.h index 9d3f21fdae..613cd95989 100644 --- a/interface/src/ui/overlays/ImageOverlay.h +++ b/interface/src/ui/overlays/ImageOverlay.h @@ -8,8 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__ImageOverlay__ -#define __interface__ImageOverlay__ +#ifndef hifi_ImageOverlay_h +#define hifi_ImageOverlay_h // include this before QGLWidget, which includes an earlier version of OpenGL #include "InterfaceConfig.h" @@ -62,4 +62,4 @@ private: }; -#endif /* defined(__interface__ImageOverlay__) */ +#endif // hifi_ImageOverlay_h diff --git a/interface/src/ui/overlays/Line3DOverlay.h b/interface/src/ui/overlays/Line3DOverlay.h index 250be03cd4..5b802f49c8 100644 --- a/interface/src/ui/overlays/Line3DOverlay.h +++ b/interface/src/ui/overlays/Line3DOverlay.h @@ -8,8 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Line3DOverlay__ -#define __interface__Line3DOverlay__ +#ifndef hifi_Line3DOverlay_h +#define hifi_Line3DOverlay_h #include "Base3DOverlay.h" @@ -34,4 +34,4 @@ protected: }; -#endif /* defined(__interface__Line3DOverlay__) */ +#endif // hifi_Line3DOverlay_h diff --git a/interface/src/ui/overlays/LocalVoxelsOverlay.h b/interface/src/ui/overlays/LocalVoxelsOverlay.h index bdc4273693..cc23b05ff6 100644 --- a/interface/src/ui/overlays/LocalVoxelsOverlay.h +++ b/interface/src/ui/overlays/LocalVoxelsOverlay.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__LocalVoxelsOverlay__ -#define __hifi__LocalVoxelsOverlay__ +#ifndef hifi_LocalVoxelsOverlay_h +#define hifi_LocalVoxelsOverlay_h // include this before QGLWidget, which includes an earlier version of OpenGL #include "InterfaceConfig.h" @@ -48,4 +48,4 @@ private: StrongVoxelSystemPointer _voxelSystem; }; -#endif /* defined(__hifi__LocalVoxelsOverlay__) */ +#endif // hifi_LocalVoxelsOverlay_h diff --git a/interface/src/ui/overlays/Overlay.h b/interface/src/ui/overlays/Overlay.h index a80d6a403f..6feb159e05 100644 --- a/interface/src/ui/overlays/Overlay.h +++ b/interface/src/ui/overlays/Overlay.h @@ -8,8 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Overlay__ -#define __interface__Overlay__ +#ifndef hifi_Overlay_h +#define hifi_Overlay_h // include this before QGLWidget, which includes an earlier version of OpenGL #include "InterfaceConfig.h" @@ -54,4 +54,4 @@ protected: }; -#endif /* defined(__interface__Overlay__) */ +#endif // hifi_Overlay_h diff --git a/interface/src/ui/overlays/Overlay2D.h b/interface/src/ui/overlays/Overlay2D.h index cb9c588603..34028de89a 100644 --- a/interface/src/ui/overlays/Overlay2D.h +++ b/interface/src/ui/overlays/Overlay2D.h @@ -8,8 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Overlay2D__ -#define __interface__Overlay2D__ +#ifndef hifi_Overlay2D_h +#define hifi_Overlay2D_h // include this before QGLWidget, which includes an earlier version of OpenGL #include "InterfaceConfig.h" @@ -51,4 +51,4 @@ protected: }; -#endif /* defined(__interface__Overlay2D__) */ +#endif // hifi_Overlay2D_h diff --git a/interface/src/ui/overlays/Overlays.h b/interface/src/ui/overlays/Overlays.h index f6cbabe1f9..b3477be0c2 100644 --- a/interface/src/ui/overlays/Overlays.h +++ b/interface/src/ui/overlays/Overlays.h @@ -8,8 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Overlays__ -#define __interface__Overlays__ +#ifndef hifi_Overlays_h +#define hifi_Overlays_h #include @@ -48,4 +48,4 @@ private: }; -#endif /* defined(__interface__Overlays__) */ +#endif // hifi_Overlays_h diff --git a/interface/src/ui/overlays/Sphere3DOverlay.h b/interface/src/ui/overlays/Sphere3DOverlay.h index 0fbfc5e3de..9a2816611b 100644 --- a/interface/src/ui/overlays/Sphere3DOverlay.h +++ b/interface/src/ui/overlays/Sphere3DOverlay.h @@ -8,8 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Sphere3DOverlay__ -#define __interface__Sphere3DOverlay__ +#ifndef hifi_Sphere3DOverlay_h +#define hifi_Sphere3DOverlay_h #include "Volume3DOverlay.h" @@ -23,4 +23,4 @@ public: }; -#endif /* defined(__interface__Sphere3DOverlay__) */ +#endif // hifi_Sphere3DOverlay_h diff --git a/interface/src/ui/overlays/TextOverlay.h b/interface/src/ui/overlays/TextOverlay.h index 9ea7a724b8..fc04966d07 100644 --- a/interface/src/ui/overlays/TextOverlay.h +++ b/interface/src/ui/overlays/TextOverlay.h @@ -8,8 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__TextOverlay__ -#define __interface__TextOverlay__ +#ifndef hifi_TextOverlay_h +#define hifi_TextOverlay_h // include this before QGLWidget, which includes an earlier version of OpenGL #include "InterfaceConfig.h" @@ -59,4 +59,4 @@ private: }; -#endif /* defined(__interface__TextOverlay__) */ +#endif // hifi_TextOverlay_h diff --git a/interface/src/ui/overlays/Volume3DOverlay.h b/interface/src/ui/overlays/Volume3DOverlay.h index a90074822b..b06aea27fd 100644 --- a/interface/src/ui/overlays/Volume3DOverlay.h +++ b/interface/src/ui/overlays/Volume3DOverlay.h @@ -8,8 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Volume3DOverlay__ -#define __interface__Volume3DOverlay__ +#ifndef hifi_Volume3DOverlay_h +#define hifi_Volume3DOverlay_h // include this before QGLWidget, which includes an earlier version of OpenGL #include "InterfaceConfig.h" @@ -42,4 +42,4 @@ protected: }; -#endif /* defined(__interface__Volume3DOverlay__) */ +#endif // hifi_Volume3DOverlay_h diff --git a/interface/src/voxels/PrimitiveRenderer.h b/interface/src/voxels/PrimitiveRenderer.h index 268b4f3175..8626e2e2a4 100644 --- a/interface/src/voxels/PrimitiveRenderer.h +++ b/interface/src/voxels/PrimitiveRenderer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__PrimitiveRenderer__ -#define __interface__PrimitiveRenderer__ +#ifndef hifi_PrimitiveRenderer_h +#define hifi_PrimitiveRenderer_h #include #include @@ -488,4 +488,4 @@ private: }; -#endif +#endif // hifi_PrimitiveRenderer_h diff --git a/interface/src/voxels/VoxelFade.h b/interface/src/voxels/VoxelFade.h index 2bfe65f03b..1843fa2d67 100644 --- a/interface/src/voxels/VoxelFade.h +++ b/interface/src/voxels/VoxelFade.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__VoxelFade__ -#define __interface__VoxelFade__ +#ifndef hifi_VoxelFade_h +#define hifi_VoxelFade_h #include // for VoxelPositionSize @@ -43,4 +43,4 @@ public: bool isDone() const; }; -#endif // __interface__VoxelFade__ +#endif // hifi_VoxelFade_h diff --git a/interface/src/voxels/VoxelHideShowThread.h b/interface/src/voxels/VoxelHideShowThread.h index b12befc9de..6aa3c108ba 100644 --- a/interface/src/voxels/VoxelHideShowThread.h +++ b/interface/src/voxels/VoxelHideShowThread.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__VoxelHideShowThread__ -#define __interface__VoxelHideShowThread__ +#ifndef hifi_VoxelHideShowThread_h +#define hifi_VoxelHideShowThread_h #include #include "VoxelSystem.h" @@ -32,4 +32,4 @@ private: VoxelSystem* _theSystem; }; -#endif // __interface__VoxelHideShowThread__ +#endif // hifi_VoxelHideShowThread_h diff --git a/interface/src/voxels/VoxelImporter.h b/interface/src/voxels/VoxelImporter.h index fb9fe7b589..7da89c5a11 100644 --- a/interface/src/voxels/VoxelImporter.h +++ b/interface/src/voxels/VoxelImporter.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__VoxelImporter__ -#define __hifi__VoxelImporter__ +#ifndef hifi_VoxelImporter_h +#define hifi_VoxelImporter_h #include #include @@ -47,4 +47,4 @@ private: void cleanupTask(); }; -#endif /* defined(__hifi__VoxelImporter__) */ +#endif // hifi_VoxelImporter_h diff --git a/interface/src/voxels/VoxelPacketProcessor.h b/interface/src/voxels/VoxelPacketProcessor.h index c71bc07c31..36456c5cc2 100644 --- a/interface/src/voxels/VoxelPacketProcessor.h +++ b/interface/src/voxels/VoxelPacketProcessor.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __shared__VoxelPacketProcessor__ -#define __shared__VoxelPacketProcessor__ +#ifndef hifi_VoxelPacketProcessor_h +#define hifi_VoxelPacketProcessor_h #include @@ -21,4 +21,4 @@ class VoxelPacketProcessor : public ReceivedPacketProcessor { protected: virtual void processPacket(const SharedNodePointer& sendingNode, const QByteArray& packet); }; -#endif // __shared__VoxelPacketProcessor__ +#endif // hifi_VoxelPacketProcessor_h diff --git a/interface/src/voxels/VoxelSystem.h b/interface/src/voxels/VoxelSystem.h index eae7e21246..b134fe1539 100644 --- a/interface/src/voxels/VoxelSystem.h +++ b/interface/src/voxels/VoxelSystem.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__VoxelSystem__ -#define __interface__VoxelSystem__ +#ifndef hifi_VoxelSystem_h +#define hifi_VoxelSystem_h #include "InterfaceConfig.h" #include @@ -274,4 +274,4 @@ private: }; -#endif +#endif // hifi_VoxelSystem_h diff --git a/interface/src/windowshacks.h b/interface/src/windowshacks.h index 3563c2a765..fcd2f5a7f2 100644 --- a/interface/src/windowshacks.h +++ b/interface/src/windowshacks.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__windowshacks__ -#define __hifi__windowshacks__ +#ifndef hifi_windowshacks_h +#define hifi_windowshacks_h #ifdef WIN32 #undef NOMINMAX @@ -57,4 +57,4 @@ inline int c99_snprintf(char* str, size_t size, const char* format, ...) { #endif // WIN32 -#endif // __hifi__windowshacks__ +#endif // hifi_windowshacks_h diff --git a/interface/src/world.h b/interface/src/world.h index 95767e7b15..8e680f3d95 100644 --- a/interface/src/world.h +++ b/interface/src/world.h @@ -9,10 +9,10 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__world__ -#define __interface__world__ +#ifndef hifi_world_h +#define hifi_world_h const float GRAVITY_EARTH = 9.80665f; const float EDGE_SIZE_GROUND_PLANE = 20.f; -#endif +#endif // hifi_world_h diff --git a/libraries/audio/src/AbstractAudioInterface.h b/libraries/audio/src/AbstractAudioInterface.h index 28cb0653f8..f950eefcbd 100644 --- a/libraries/audio/src/AbstractAudioInterface.h +++ b/libraries/audio/src/AbstractAudioInterface.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AbstractAudioInterface__ -#define __hifi__AbstractAudioInterface__ +#ifndef hifi_AbstractAudioInterface_h +#define hifi_AbstractAudioInterface_h #include @@ -27,4 +27,4 @@ public slots: Q_DECLARE_METATYPE(AbstractAudioInterface*) -#endif /* defined(__hifi__AbstractAudioInterface__) */ +#endif // hifi_AbstractAudioInterface_h diff --git a/libraries/audio/src/AudioInjector.h b/libraries/audio/src/AudioInjector.h index 988ea46444..abaa804fb0 100644 --- a/libraries/audio/src/AudioInjector.h +++ b/libraries/audio/src/AudioInjector.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AudioInjector__ -#define __hifi__AudioInjector__ +#ifndef hifi_AudioInjector_h +#define hifi_AudioInjector_h #include #include @@ -34,4 +34,4 @@ signals: void finished(); }; -#endif /* defined(__hifi__AudioInjector__) */ +#endif // hifi_AudioInjector_h diff --git a/libraries/audio/src/AudioInjectorOptions.h b/libraries/audio/src/AudioInjectorOptions.h index 866f95bde4..bbe3d57b08 100644 --- a/libraries/audio/src/AudioInjectorOptions.h +++ b/libraries/audio/src/AudioInjectorOptions.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AudioInjectorOptions__ -#define __hifi__AudioInjectorOptions__ +#ifndef hifi_AudioInjectorOptions_h +#define hifi_AudioInjectorOptions_h #include @@ -49,4 +49,4 @@ private: AbstractAudioInterface* _loopbackAudioInterface; }; -#endif /* defined(__hifi__AudioInjectorOptions__) */ +#endif // hifi_AudioInjectorOptions_h diff --git a/libraries/audio/src/AudioRingBuffer.h b/libraries/audio/src/AudioRingBuffer.h index 7a1a75e43b..ef4427d633 100644 --- a/libraries/audio/src/AudioRingBuffer.h +++ b/libraries/audio/src/AudioRingBuffer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__AudioRingBuffer__ -#define __interface__AudioRingBuffer__ +#ifndef hifi_AudioRingBuffer_h +#define hifi_AudioRingBuffer_h #include #include @@ -89,4 +89,4 @@ protected: bool _hasStarted; }; -#endif /* defined(__interface__AudioRingBuffer__) */ +#endif // hifi_AudioRingBuffer_h diff --git a/libraries/audio/src/AudioScriptingInterface.h b/libraries/audio/src/AudioScriptingInterface.h index 9371597075..f2e9b02e9a 100644 --- a/libraries/audio/src/AudioScriptingInterface.h +++ b/libraries/audio/src/AudioScriptingInterface.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AudioScriptingInterface__ -#define __hifi__AudioScriptingInterface__ +#ifndef hifi_AudioScriptingInterface_h +#define hifi_AudioScriptingInterface_h #include "AudioInjector.h" #include "Sound.h" @@ -25,4 +25,4 @@ public slots: const AudioInjectorOptions* injectorOptions = NULL); }; -#endif /* defined(__hifi__AudioScriptingInterface__) */ +#endif // hifi_AudioScriptingInterface_h diff --git a/libraries/audio/src/InjectedAudioRingBuffer.h b/libraries/audio/src/InjectedAudioRingBuffer.h index 8a1a430c78..fd766e2848 100644 --- a/libraries/audio/src/InjectedAudioRingBuffer.h +++ b/libraries/audio/src/InjectedAudioRingBuffer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__InjectedAudioRingBuffer__ -#define __hifi__InjectedAudioRingBuffer__ +#ifndef hifi_InjectedAudioRingBuffer_h +#define hifi_InjectedAudioRingBuffer_h #include @@ -35,4 +35,4 @@ private: float _attenuationRatio; }; -#endif /* defined(__hifi__InjectedAudioRingBuffer__) */ +#endif // hifi_InjectedAudioRingBuffer_h diff --git a/libraries/audio/src/MixedAudioRingBuffer.h b/libraries/audio/src/MixedAudioRingBuffer.h index 2d672f6ada..25574a3ea6 100644 --- a/libraries/audio/src/MixedAudioRingBuffer.h +++ b/libraries/audio/src/MixedAudioRingBuffer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__MixedAudioRingBuffer__ -#define __hifi__MixedAudioRingBuffer__ +#ifndef hifi_MixedAudioRingBuffer_h +#define hifi_MixedAudioRingBuffer_h #include "AudioRingBuffer.h" @@ -26,4 +26,4 @@ private: float _lastReadFrameAverageLoudness; }; -#endif /* defined(__hifi__MixedAudioRingBuffer__) */ +#endif // hifi_MixedAudioRingBuffer_h diff --git a/libraries/audio/src/PositionalAudioRingBuffer.h b/libraries/audio/src/PositionalAudioRingBuffer.h index c34e6f8bc7..b130a9b216 100644 --- a/libraries/audio/src/PositionalAudioRingBuffer.h +++ b/libraries/audio/src/PositionalAudioRingBuffer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__PositionalAudioRingBuffer__ -#define __hifi__PositionalAudioRingBuffer__ +#ifndef hifi_PositionalAudioRingBuffer_h +#define hifi_PositionalAudioRingBuffer_h #include #include @@ -60,4 +60,4 @@ protected: float _nextOutputTrailingLoudness; }; -#endif /* defined(__hifi__PositionalAudioRingBuffer__) */ +#endif // hifi_PositionalAudioRingBuffer_h diff --git a/libraries/audio/src/Sound.h b/libraries/audio/src/Sound.h index 27e46bec57..e1613fec51 100644 --- a/libraries/audio/src/Sound.h +++ b/libraries/audio/src/Sound.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__Sound__ -#define __hifi__Sound__ +#ifndef hifi_Sound_h +#define hifi_Sound_h #include @@ -34,4 +34,4 @@ private slots: void replyFinished(QNetworkReply* reply); }; -#endif /* defined(__hifi__Sound__) */ +#endif // hifi_Sound_h diff --git a/libraries/avatars/src/AvatarData.h b/libraries/avatars/src/AvatarData.h index 79c2075323..24910034b3 100755 --- a/libraries/avatars/src/AvatarData.h +++ b/libraries/avatars/src/AvatarData.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AvatarData__ -#define __hifi__AvatarData__ +#ifndef hifi_AvatarData_h +#define hifi_AvatarData_h #include /* VS2010 defines stdint.h, but not inttypes.h */ @@ -285,4 +285,4 @@ public: glm::quat rotation; }; -#endif /* defined(__hifi__AvatarData__) */ +#endif // hifi_AvatarData_h diff --git a/libraries/avatars/src/AvatarHashMap.h b/libraries/avatars/src/AvatarHashMap.h index fcfd735073..aee9cd09f1 100644 --- a/libraries/avatars/src/AvatarHashMap.h +++ b/libraries/avatars/src/AvatarHashMap.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AvatarHashMap__ -#define __hifi__AvatarHashMap__ +#ifndef hifi_AvatarHashMap_h +#define hifi_AvatarHashMap_h #include #include @@ -36,4 +36,4 @@ protected: AvatarHash _avatarHash; }; -#endif /* defined(__hifi__AvatarHashMap__) */ +#endif // hifi_AvatarHashMap_h diff --git a/libraries/avatars/src/HandData.h b/libraries/avatars/src/HandData.h index 662ad493b1..a37e3a5814 100755 --- a/libraries/avatars/src/HandData.h +++ b/libraries/avatars/src/HandData.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__HandData__ -#define __hifi__HandData__ +#ifndef hifi_HandData_h +#define hifi_HandData_h #include #include @@ -226,4 +226,4 @@ private: quint64 _collisionlessPaddleExpiry; /// Timestamp after which paddle starts colliding }; -#endif /* defined(__hifi__HandData__) */ +#endif // hifi_HandData_h diff --git a/libraries/avatars/src/HeadData.h b/libraries/avatars/src/HeadData.h index 044966da04..b76bd189bf 100644 --- a/libraries/avatars/src/HeadData.h +++ b/libraries/avatars/src/HeadData.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__HeadData__ -#define __hifi__HeadData__ +#ifndef hifi_HeadData_h +#define hifi_HeadData_h #include @@ -95,4 +95,4 @@ private: HeadData& operator= (const HeadData&); }; -#endif /* defined(__hifi__HeadData__) */ +#endif // hifi_HeadData_h diff --git a/libraries/embedded-webserver/src/HTTPConnection.h b/libraries/embedded-webserver/src/HTTPConnection.h index 7eb0c6108d..a131a22a9e 100644 --- a/libraries/embedded-webserver/src/HTTPConnection.h +++ b/libraries/embedded-webserver/src/HTTPConnection.h @@ -13,8 +13,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__HTTPConnection__ -#define __hifi__HTTPConnection__ +#ifndef hifi_HTTPConnection_h +#define hifi_HTTPConnection_h #include #include @@ -121,4 +121,4 @@ protected: QByteArray _requestContent; }; -#endif /* defined(__hifi__HTTPConnection__) */ +#endif // hifi_HTTPConnection_h diff --git a/libraries/embedded-webserver/src/HTTPManager.h b/libraries/embedded-webserver/src/HTTPManager.h index c7bb479ab2..1e3afca1b5 100755 --- a/libraries/embedded-webserver/src/HTTPManager.h +++ b/libraries/embedded-webserver/src/HTTPManager.h @@ -13,8 +13,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__HTTPManager__ -#define __hifi__HTTPManager__ +#ifndef hifi_HTTPManager_h +#define hifi_HTTPManager_h #include @@ -43,4 +43,4 @@ protected: HTTPRequestHandler* _requestHandler; }; -#endif /* defined(__hifi__HTTPManager__) */ +#endif // hifi_HTTPManager_h diff --git a/libraries/metavoxels/src/AttributeRegistry.h b/libraries/metavoxels/src/AttributeRegistry.h index 084ef4426f..00d974b8b6 100644 --- a/libraries/metavoxels/src/AttributeRegistry.h +++ b/libraries/metavoxels/src/AttributeRegistry.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__AttributeRegistry__ -#define __interface__AttributeRegistry__ +#ifndef hifi_AttributeRegistry_h +#define hifi_AttributeRegistry_h #include #include @@ -464,4 +464,4 @@ public: virtual void writeMetavoxelSubdivision(const MetavoxelNode& root, MetavoxelStreamState& state); }; -#endif /* defined(__interface__AttributeRegistry__) */ +#endif // hifi_AttributeRegistry_h diff --git a/libraries/metavoxels/src/Bitstream.h b/libraries/metavoxels/src/Bitstream.h index 3c5f738730..34b66eb9f2 100644 --- a/libraries/metavoxels/src/Bitstream.h +++ b/libraries/metavoxels/src/Bitstream.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Bitstream__ -#define __interface__Bitstream__ +#ifndef hifi_Bitstream_h +#define hifi_Bitstream_h #include #include @@ -953,4 +953,4 @@ template int registerStreamableMetaType() { /// Flags a field or base class as streaming. #define STREAM -#endif /* defined(__interface__Bitstream__) */ +#endif // hifi_Bitstream_h diff --git a/libraries/metavoxels/src/DatagramSequencer.h b/libraries/metavoxels/src/DatagramSequencer.h index 40a8a7e9e7..ce9f36ba33 100644 --- a/libraries/metavoxels/src/DatagramSequencer.h +++ b/libraries/metavoxels/src/DatagramSequencer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__DatagramSequencer__ -#define __interface__DatagramSequencer__ +#ifndef hifi_DatagramSequencer_h +#define hifi_DatagramSequencer_h #include #include @@ -321,4 +321,4 @@ private: bool _messagesEnabled; }; -#endif /* defined(__interface__DatagramSequencer__) */ +#endif // hifi_DatagramSequencer_h diff --git a/libraries/metavoxels/src/MetavoxelData.h b/libraries/metavoxels/src/MetavoxelData.h index 49df417b71..2e6f6c4437 100644 --- a/libraries/metavoxels/src/MetavoxelData.h +++ b/libraries/metavoxels/src/MetavoxelData.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__MetavoxelData__ -#define __interface__MetavoxelData__ +#ifndef hifi_MetavoxelData_h +#define hifi_MetavoxelData_h #include #include @@ -631,4 +631,4 @@ private: QUrl _url; }; -#endif /* defined(__interface__MetavoxelData__) */ +#endif // hifi_MetavoxelData_h diff --git a/libraries/metavoxels/src/MetavoxelMessages.h b/libraries/metavoxels/src/MetavoxelMessages.h index d4d2183091..8f819fe3d8 100644 --- a/libraries/metavoxels/src/MetavoxelMessages.h +++ b/libraries/metavoxels/src/MetavoxelMessages.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__MetavoxelMessages__ -#define __interface__MetavoxelMessages__ +#ifndef hifi_MetavoxelMessages_h +#define hifi_MetavoxelMessages_h #include "MetavoxelData.h" @@ -196,4 +196,4 @@ public: DECLARE_STREAMABLE_METATYPE(SetDataEdit) -#endif /* defined(__interface__MetavoxelMessages__) */ +#endif // hifi_MetavoxelMessages_h diff --git a/libraries/metavoxels/src/MetavoxelUtil.h b/libraries/metavoxels/src/MetavoxelUtil.h index e72408b9ed..34c2bac6be 100644 --- a/libraries/metavoxels/src/MetavoxelUtil.h +++ b/libraries/metavoxels/src/MetavoxelUtil.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__MetavoxelUtil__ -#define __interface__MetavoxelUtil__ +#ifndef hifi_MetavoxelUtil_h +#define hifi_MetavoxelUtil_h #include #include @@ -283,4 +283,4 @@ private: QUrlEditor _urlEditor; }; -#endif /* defined(__interface__MetavoxelUtil__) */ +#endif // hifi_MetavoxelUtil_h diff --git a/libraries/metavoxels/src/ScriptCache.h b/libraries/metavoxels/src/ScriptCache.h index 810da46eb2..f393d0e0a8 100644 --- a/libraries/metavoxels/src/ScriptCache.h +++ b/libraries/metavoxels/src/ScriptCache.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__ScriptCache__ -#define __interface__ScriptCache__ +#ifndef hifi_ScriptCache_h +#define hifi_ScriptCache_h #include #include @@ -145,4 +145,4 @@ private: ScriptHash _parameters; }; -#endif /* defined(__interface__ScriptCache__) */ +#endif // hifi_ScriptCache_h diff --git a/libraries/metavoxels/src/SharedObject.h b/libraries/metavoxels/src/SharedObject.h index 736984fa41..aba6b86bea 100644 --- a/libraries/metavoxels/src/SharedObject.h +++ b/libraries/metavoxels/src/SharedObject.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__SharedObject__ -#define __interface__SharedObject__ +#ifndef hifi_SharedObject_h +#define hifi_SharedObject_h #include #include @@ -218,4 +218,4 @@ private: SharedObjectPointer _object; }; -#endif /* defined(__interface__SharedObject__) */ +#endif // hifi_SharedObject_h diff --git a/libraries/octree/src/AABox.h b/libraries/octree/src/AABox.h index 1d5fad696c..093a111a69 100644 --- a/libraries/octree/src/AABox.h +++ b/libraries/octree/src/AABox.h @@ -12,8 +12,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef _AABOX_ -#define _AABOX_ +#ifndef hifi_AABox_h +#define hifi_AABox_h #include @@ -82,4 +82,4 @@ private: float _scale; }; -#endif +#endif // hifi_AABox_h diff --git a/libraries/octree/src/CoverageMap.h b/libraries/octree/src/CoverageMap.h index e06696ff66..bff6bb1078 100644 --- a/libraries/octree/src/CoverageMap.h +++ b/libraries/octree/src/CoverageMap.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef _COVERAGE_MAP_ -#define _COVERAGE_MAP_ +#ifndef hifi_CoverageMap_h +#define hifi_CoverageMap_h #include #include "OctreeProjectedPolygon.h" @@ -117,4 +117,4 @@ private: }; -#endif // _COVERAGE_MAP_ +#endif // hifi_CoverageMap_h diff --git a/libraries/octree/src/CoverageMapV2.h b/libraries/octree/src/CoverageMapV2.h index 7221c7d5de..fc9a3ea70e 100644 --- a/libraries/octree/src/CoverageMapV2.h +++ b/libraries/octree/src/CoverageMapV2.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef _COVERAGE_MAP_V2_ -#define _COVERAGE_MAP_V2_ +#ifndef hifi_CoverageMapV2_h +#define hifi_CoverageMapV2_h #include @@ -69,4 +69,4 @@ private: }; -#endif // _COVERAGE_MAP_V2_ +#endif // hifi_CoverageMapV2_h diff --git a/libraries/octree/src/JurisdictionListener.h b/libraries/octree/src/JurisdictionListener.h index 2d5cd75560..01f0392796 100644 --- a/libraries/octree/src/JurisdictionListener.h +++ b/libraries/octree/src/JurisdictionListener.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __shared__JurisdictionListener__ -#define __shared__JurisdictionListener__ +#ifndef hifi_JurisdictionListener_h +#define hifi_JurisdictionListener_h #include #include @@ -61,4 +61,4 @@ private: PacketSender _packetSender; }; -#endif // __shared__JurisdictionListener__ +#endif // hifi_JurisdictionListener_h diff --git a/libraries/octree/src/JurisdictionMap.h b/libraries/octree/src/JurisdictionMap.h index 4c189bfac0..b4174e6432 100644 --- a/libraries/octree/src/JurisdictionMap.h +++ b/libraries/octree/src/JurisdictionMap.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__JurisdictionMap__ -#define __hifi__JurisdictionMap__ +#ifndef hifi_JurisdictionMap_h +#define hifi_JurisdictionMap_h #include #include @@ -86,6 +86,4 @@ typedef QMap NodeToJurisdictionMap; typedef QMap::iterator NodeToJurisdictionMapIterator; -#endif /* defined(__hifi__JurisdictionMap__) */ - - +#endif // hifi_JurisdictionMap_h diff --git a/libraries/octree/src/JurisdictionSender.h b/libraries/octree/src/JurisdictionSender.h index 20c54824e7..bfa370c6ca 100644 --- a/libraries/octree/src/JurisdictionSender.h +++ b/libraries/octree/src/JurisdictionSender.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __shared__JurisdictionSender__ -#define __shared__JurisdictionSender__ +#ifndef hifi_JurisdictionSender_h +#define hifi_JurisdictionSender_h #include #include @@ -55,4 +55,4 @@ private: PacketSender _packetSender; }; -#endif // __shared__JurisdictionSender__ +#endif // hifi_JurisdictionSender_h diff --git a/libraries/octree/src/Octree.h b/libraries/octree/src/Octree.h index 6451b91a26..839e61d1c2 100644 --- a/libraries/octree/src/Octree.h +++ b/libraries/octree/src/Octree.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__Octree__ -#define __hifi__Octree__ +#ifndef hifi_Octree_h +#define hifi_Octree_h #include #include @@ -314,4 +314,4 @@ protected: float boundaryDistanceForRenderLevel(unsigned int renderLevel, float voxelSizeScale); -#endif /* defined(__hifi__Octree__) */ +#endif // hifi_Octree_h diff --git a/libraries/octree/src/OctreeConstants.h b/libraries/octree/src/OctreeConstants.h index ceb3a4de20..18c5eb0108 100644 --- a/libraries/octree/src/OctreeConstants.h +++ b/libraries/octree/src/OctreeConstants.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi_OctreeConstants_h__ -#define __hifi_OctreeConstants_h__ +#ifndef hifi_OctreeConstants_h +#define hifi_OctreeConstants_h #include #include @@ -44,4 +44,4 @@ const int DANGEROUSLY_DEEP_RECURSION = 200; // use this for something that needs const int DEFAULT_MAX_OCTREE_PPS = 600; // the default maximum PPS we think any octree based server should send to a client -#endif +#endif // hifi_OctreeConstants_h diff --git a/libraries/octree/src/OctreeEditPacketSender.h b/libraries/octree/src/OctreeEditPacketSender.h index 36d2f837cf..f9326b6ed3 100644 --- a/libraries/octree/src/OctreeEditPacketSender.h +++ b/libraries/octree/src/OctreeEditPacketSender.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __shared__OctreeEditPacketSender__ -#define __shared__OctreeEditPacketSender__ +#ifndef hifi_OctreeEditPacketSender_h +#define hifi_OctreeEditPacketSender_h #include #include @@ -115,4 +115,4 @@ protected: unsigned short int _sequenceNumber; int _maxPacketSize; }; -#endif // __shared__OctreeEditPacketSender__ +#endif // hifi_OctreeEditPacketSender_h diff --git a/libraries/octree/src/OctreeElement.h b/libraries/octree/src/OctreeElement.h index b634acdf2a..682516cf0a 100644 --- a/libraries/octree/src/OctreeElement.h +++ b/libraries/octree/src/OctreeElement.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__OctreeElement__ -#define __hifi__OctreeElement__ +#ifndef hifi_OctreeElement_h +#define hifi_OctreeElement_h //#define HAS_AUDIT_CHILDREN //#define SIMPLE_CHILD_ARRAY @@ -319,4 +319,4 @@ protected: static quint64 _childrenCount[NUMBER_OF_CHILDREN + 1]; }; -#endif /* defined(__hifi__OctreeElement__) */ +#endif // hifi_OctreeElement_h diff --git a/libraries/octree/src/OctreeElementBag.h b/libraries/octree/src/OctreeElementBag.h index 0c17d9f1fa..afc34bf1a6 100644 --- a/libraries/octree/src/OctreeElementBag.h +++ b/libraries/octree/src/OctreeElementBag.h @@ -14,8 +14,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__OctreeElementBag__ -#define __hifi__OctreeElementBag__ +#ifndef hifi_OctreeElementBag_h +#define hifi_OctreeElementBag_h #include "OctreeElement.h" @@ -40,4 +40,4 @@ private: QSet _bagElements; }; -#endif /* defined(__hifi__OctreeElementBag__) */ +#endif // hifi_OctreeElementBag_h diff --git a/libraries/octree/src/OctreeHeadlessViewer.h b/libraries/octree/src/OctreeHeadlessViewer.h index 5d98d0291f..ebabf1dbad 100644 --- a/libraries/octree/src/OctreeHeadlessViewer.h +++ b/libraries/octree/src/OctreeHeadlessViewer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__OctreeHeadlessViewer__ -#define __hifi__OctreeHeadlessViewer__ +#ifndef hifi_OctreeHeadlessViewer_h +#define hifi_OctreeHeadlessViewer_h #include #include @@ -72,4 +72,4 @@ private: int _maxPacketsPerSecond; }; -#endif /* defined(__hifi__OctreeHeadlessViewer__) */ +#endif // hifi_OctreeHeadlessViewer_h diff --git a/libraries/octree/src/OctreePacketData.h b/libraries/octree/src/OctreePacketData.h index 64e7c07161..d802f8e808 100644 --- a/libraries/octree/src/OctreePacketData.h +++ b/libraries/octree/src/OctreePacketData.h @@ -19,8 +19,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__OctreePacketData__ -#define __hifi__OctreePacketData__ +#ifndef hifi_OctreePacketData_h +#define hifi_OctreePacketData_h #include #include "OctreeConstants.h" @@ -227,4 +227,4 @@ private: static quint64 _totalBytesOfRawData; }; -#endif /* defined(__hifi__OctreePacketData__) */ +#endif // hifi_OctreePacketData_h diff --git a/libraries/octree/src/OctreePersistThread.h b/libraries/octree/src/OctreePersistThread.h index 90b83b4c86..2f86320b2e 100644 --- a/libraries/octree/src/OctreePersistThread.h +++ b/libraries/octree/src/OctreePersistThread.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __Octree_server__OctreePersistThread__ -#define __Octree_server__OctreePersistThread__ +#ifndef hifi_OctreePersistThread_h +#define hifi_OctreePersistThread_h #include #include @@ -45,4 +45,4 @@ private: quint64 _lastCheck; }; -#endif // __Octree_server__OctreePersistThread__ +#endif // hifi_OctreePersistThread_h diff --git a/libraries/octree/src/OctreeProjectedPolygon.h b/libraries/octree/src/OctreeProjectedPolygon.h index ff3a28649e..5a2a36f280 100644 --- a/libraries/octree/src/OctreeProjectedPolygon.h +++ b/libraries/octree/src/OctreeProjectedPolygon.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef _VOXEL_PROJECTED_SHADOW_ -#define _VOXEL_PROJECTED_SHADOW_ +#ifndef hifi_OctreeProjectedPolygon_h +#define hifi_OctreeProjectedPolygon_h #include @@ -132,4 +132,4 @@ private: }; -#endif // _VOXEL_PROJECTED_SHADOW_ +#endif // hifi_OctreeProjectedPolygon_h diff --git a/libraries/octree/src/OctreeQuery.h b/libraries/octree/src/OctreeQuery.h index 6e2b651a5b..8c4460bc73 100644 --- a/libraries/octree/src/OctreeQuery.h +++ b/libraries/octree/src/OctreeQuery.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__OctreeQuery__ -#define __hifi__OctreeQuery__ +#ifndef hifi_OctreeQuery_h +#define hifi_OctreeQuery_h /* VS2010 defines stdint.h, but not inttypes.h */ #if defined(_MSC_VER) @@ -116,4 +116,4 @@ private: OctreeQuery& operator= (const OctreeQuery&); }; -#endif /* defined(__hifi__OctreeQuery__) */ +#endif // hifi_OctreeQuery_h diff --git a/libraries/octree/src/OctreeRenderer.h b/libraries/octree/src/OctreeRenderer.h index e61ac145b8..fbd82fad8f 100644 --- a/libraries/octree/src/OctreeRenderer.h +++ b/libraries/octree/src/OctreeRenderer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__OctreeRenderer__ -#define __hifi__OctreeRenderer__ +#ifndef hifi_OctreeRenderer_h +#define hifi_OctreeRenderer_h #include #include @@ -71,4 +71,4 @@ protected: ViewFrustum* _viewFrustum; }; -#endif /* defined(__hifi__OctreeRenderer__) */ +#endif // hifi_OctreeRenderer_h diff --git a/libraries/octree/src/OctreeSceneStats.h b/libraries/octree/src/OctreeSceneStats.h index b74fbbc8d1..140e33aedf 100644 --- a/libraries/octree/src/OctreeSceneStats.h +++ b/libraries/octree/src/OctreeSceneStats.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__OctreeSceneStats__ -#define __hifi__OctreeSceneStats__ +#ifndef hifi_OctreeSceneStats_h +#define hifi_OctreeSceneStats_h #include #include @@ -292,4 +292,4 @@ private: typedef std::map NodeToOctreeSceneStats; typedef std::map::iterator NodeToOctreeSceneStatsIterator; -#endif /* defined(__hifi__OctreeSceneStats__) */ +#endif // hifi_OctreeSceneStats_h diff --git a/libraries/octree/src/OctreeScriptingInterface.h b/libraries/octree/src/OctreeScriptingInterface.h index 4c6c6aa54f..52d7c8be34 100644 --- a/libraries/octree/src/OctreeScriptingInterface.h +++ b/libraries/octree/src/OctreeScriptingInterface.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__OctreeScriptingInterface__ -#define __hifi__OctreeScriptingInterface__ +#ifndef hifi_OctreeScriptingInterface_h +#define hifi_OctreeScriptingInterface_h #include @@ -99,4 +99,4 @@ protected: bool _initialized; }; -#endif /* defined(__hifi__OctreeScriptingInterface__) */ +#endif // hifi_OctreeScriptingInterface_h diff --git a/libraries/octree/src/ViewFrustum.h b/libraries/octree/src/ViewFrustum.h index 65ff992ee4..5c9d7f06c2 100644 --- a/libraries/octree/src/ViewFrustum.h +++ b/libraries/octree/src/ViewFrustum.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__ViewFrustum__ -#define __hifi__ViewFrustum__ +#ifndef hifi_ViewFrustum_h +#define hifi_ViewFrustum_h #include #include @@ -175,4 +175,4 @@ private: }; -#endif /* defined(__hifi__ViewFrustum__) */ +#endif // hifi_ViewFrustum_h diff --git a/libraries/particles/src/Particle.h b/libraries/particles/src/Particle.h index 8a49dd273a..c243363241 100644 --- a/libraries/particles/src/Particle.h +++ b/libraries/particles/src/Particle.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__Particle__ -#define __hifi__Particle__ +#ifndef hifi_Particle_h +#define hifi_Particle_h #include #include @@ -430,4 +430,4 @@ private: -#endif /* defined(__hifi__Particle__) */ +#endif // hifi_Particle_h diff --git a/libraries/particles/src/ParticleCollisionSystem.h b/libraries/particles/src/ParticleCollisionSystem.h index 50e262a736..cf9c4b938c 100644 --- a/libraries/particles/src/ParticleCollisionSystem.h +++ b/libraries/particles/src/ParticleCollisionSystem.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__ParticleCollisionSystem__ -#define __hifi__ParticleCollisionSystem__ +#ifndef hifi_ParticleCollisionSystem_h +#define hifi_ParticleCollisionSystem_h #include #include @@ -71,4 +71,4 @@ private: CollisionList _collisions; }; -#endif /* defined(__hifi__ParticleCollisionSystem__) */ +#endif // hifi_ParticleCollisionSystem_h diff --git a/libraries/particles/src/ParticleEditPacketSender.h b/libraries/particles/src/ParticleEditPacketSender.h index 3a22b311a5..15e3196785 100644 --- a/libraries/particles/src/ParticleEditPacketSender.h +++ b/libraries/particles/src/ParticleEditPacketSender.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __shared__ParticleEditPacketSender__ -#define __shared__ParticleEditPacketSender__ +#ifndef hifi_ParticleEditPacketSender_h +#define hifi_ParticleEditPacketSender_h #include #include "Particle.h" @@ -33,4 +33,4 @@ public: virtual unsigned char getMyNodeType() const { return NodeType::ParticleServer; } virtual void adjustEditPacketForClockSkew(unsigned char* codeColorBuffer, ssize_t length, int clockSkew); }; -#endif // __shared__ParticleEditPacketSender__ +#endif // hifi_ParticleEditPacketSender_h diff --git a/libraries/particles/src/ParticleTree.h b/libraries/particles/src/ParticleTree.h index 20503085a2..a31c2d38aa 100644 --- a/libraries/particles/src/ParticleTree.h +++ b/libraries/particles/src/ParticleTree.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__ParticleTree__ -#define __hifi__ParticleTree__ +#ifndef hifi_ParticleTree_h +#define hifi_ParticleTree_h #include #include "ParticleTreeElement.h" @@ -95,4 +95,4 @@ private: QMultiMap _recentlyDeletedParticleIDs; }; -#endif /* defined(__hifi__ParticleTree__) */ +#endif // hifi_ParticleTree_h diff --git a/libraries/particles/src/ParticleTreeElement.h b/libraries/particles/src/ParticleTreeElement.h index 95ba27b51e..59f80d588a 100644 --- a/libraries/particles/src/ParticleTreeElement.h +++ b/libraries/particles/src/ParticleTreeElement.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__ParticleTreeElement__ -#define __hifi__ParticleTreeElement__ +#ifndef hifi_ParticleTreeElement_h +#define hifi_ParticleTreeElement_h //#include @@ -129,4 +129,4 @@ protected: QList* _particles; }; -#endif /* defined(__hifi__ParticleTreeElement__) */ +#endif // hifi_ParticleTreeElement_h diff --git a/libraries/particles/src/ParticleTreeHeadlessViewer.h b/libraries/particles/src/ParticleTreeHeadlessViewer.h index eafef3cf34..1d539bd46f 100644 --- a/libraries/particles/src/ParticleTreeHeadlessViewer.h +++ b/libraries/particles/src/ParticleTreeHeadlessViewer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__ParticleTreeHeadlessViewer__ -#define __hifi__ParticleTreeHeadlessViewer__ +#ifndef hifi_ParticleTreeHeadlessViewer_h +#define hifi_ParticleTreeHeadlessViewer_h #include #include @@ -41,4 +41,4 @@ public: virtual void init(); }; -#endif /* defined(__hifi__ParticleTreeHeadlessViewer__) */ +#endif // hifi_ParticleTreeHeadlessViewer_h diff --git a/libraries/particles/src/ParticlesScriptingInterface.h b/libraries/particles/src/ParticlesScriptingInterface.h index dbf80efa61..e1d628f45a 100644 --- a/libraries/particles/src/ParticlesScriptingInterface.h +++ b/libraries/particles/src/ParticlesScriptingInterface.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__ParticlesScriptingInterface__ -#define __hifi__ParticlesScriptingInterface__ +#ifndef hifi_ParticlesScriptingInterface_h +#define hifi_ParticlesScriptingInterface_h #include @@ -70,4 +70,4 @@ private: ParticleTree* _particleTree; }; -#endif /* defined(__hifi__ParticlesScriptingInterface__) */ +#endif // hifi_ParticlesScriptingInterface_h diff --git a/libraries/script-engine/src/AbstractControllerScriptingInterface.h b/libraries/script-engine/src/AbstractControllerScriptingInterface.h index 23f1cc8477..677ca27e04 100644 --- a/libraries/script-engine/src/AbstractControllerScriptingInterface.h +++ b/libraries/script-engine/src/AbstractControllerScriptingInterface.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AbstractControllerScriptingInterface__ -#define __hifi__AbstractControllerScriptingInterface__ +#ifndef hifi_AbstractControllerScriptingInterface_h +#define hifi_AbstractControllerScriptingInterface_h #include @@ -76,4 +76,4 @@ signals: }; -#endif /* defined(__hifi__AbstractControllerScriptingInterface__) */ +#endif // hifi_AbstractControllerScriptingInterface_h diff --git a/libraries/script-engine/src/EventTypes.h b/libraries/script-engine/src/EventTypes.h index 66f7523162..6994225fd7 100644 --- a/libraries/script-engine/src/EventTypes.h +++ b/libraries/script-engine/src/EventTypes.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi_EventTypes_h__ -#define __hifi_EventTypes_h__ +#ifndef hifi_EventTypes_h +#define hifi_EventTypes_h #include @@ -126,4 +126,4 @@ void touchEventFromScriptValue(const QScriptValue& object, TouchEvent& event); QScriptValue wheelEventToScriptValue(QScriptEngine* engine, const WheelEvent& event); void wheelEventFromScriptValue(const QScriptValue& object, WheelEvent& event); -#endif // __hifi_EventTypes_h__ +#endif // hifi_EventTypes_h diff --git a/libraries/script-engine/src/LocalVoxels.h b/libraries/script-engine/src/LocalVoxels.h index 82ed95fa66..c382d35c09 100644 --- a/libraries/script-engine/src/LocalVoxels.h +++ b/libraries/script-engine/src/LocalVoxels.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__LocalVoxels__ -#define __hifi__LocalVoxels__ +#ifndef hifi_LocalVoxels_h +#define hifi_LocalVoxels_h #include @@ -90,4 +90,4 @@ private: -#endif /* defined(__hifi__LocalVoxels__) */ +#endif // hifi_LocalVoxels_h diff --git a/libraries/script-engine/src/MenuItemProperties.h b/libraries/script-engine/src/MenuItemProperties.h index 22853d7fca..9dd3c6107c 100644 --- a/libraries/script-engine/src/MenuItemProperties.h +++ b/libraries/script-engine/src/MenuItemProperties.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi_MenuItemProperties_h__ -#define __hifi_MenuItemProperties_h__ +#ifndef hifi_MenuItemProperties_h +#define hifi_MenuItemProperties_h #include @@ -51,4 +51,4 @@ void registerMenuItemProperties(QScriptEngine* engine); -#endif // __hifi_MenuItemProperties_h__ +#endif // hifi_MenuItemProperties_h diff --git a/libraries/script-engine/src/Quat.h b/libraries/script-engine/src/Quat.h index 418488fe2e..c97ccf9a1e 100644 --- a/libraries/script-engine/src/Quat.h +++ b/libraries/script-engine/src/Quat.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__Quat__ -#define __hifi__Quat__ +#ifndef hifi_Quat_h +#define hifi_Quat_h #include @@ -39,4 +39,4 @@ public slots: void print(const QString& lable, const glm::quat& q); }; -#endif /* defined(__hifi__Quat__) */ +#endif // hifi_Quat_h diff --git a/libraries/script-engine/src/ScriptEngine.h b/libraries/script-engine/src/ScriptEngine.h index 7fe4f23b53..0796aa4f50 100644 --- a/libraries/script-engine/src/ScriptEngine.h +++ b/libraries/script-engine/src/ScriptEngine.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__ScriptEngine__ -#define __hifi__ScriptEngine__ +#ifndef hifi_ScriptEngine_h +#define hifi_ScriptEngine_h #include @@ -126,4 +126,4 @@ private: Vec3 _vec3Library; }; -#endif /* defined(__hifi__ScriptEngine__) */ +#endif // hifi_ScriptEngine_h diff --git a/libraries/script-engine/src/Vec3.h b/libraries/script-engine/src/Vec3.h index 7d420adca3..b30e274d89 100644 --- a/libraries/script-engine/src/Vec3.h +++ b/libraries/script-engine/src/Vec3.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__Vec3__ -#define __hifi__Vec3__ +#ifndef hifi_Vec3_h +#define hifi_Vec3_h #include #include @@ -37,4 +37,4 @@ public slots: -#endif /* defined(__hifi__Vec3__) */ +#endif // hifi_Vec3_h diff --git a/libraries/shared/src/AccountManager.h b/libraries/shared/src/AccountManager.h index 992223f9ce..fed6a61772 100644 --- a/libraries/shared/src/AccountManager.h +++ b/libraries/shared/src/AccountManager.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AccountManager__ -#define __hifi__AccountManager__ +#ifndef hifi_AccountManager_h +#define hifi_AccountManager_h #include #include @@ -94,4 +94,4 @@ private: DataServerAccountInfo _accountInfo; }; -#endif /* defined(__hifi__AccountManager__) */ +#endif // hifi_AccountManager_h diff --git a/libraries/shared/src/AngleUtil.h b/libraries/shared/src/AngleUtil.h index e4d8abc28f..d700e41f3d 100644 --- a/libraries/shared/src/AngleUtil.h +++ b/libraries/shared/src/AngleUtil.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__AngleUtils__ -#define __hifi__AngleUtils__ +#ifndef hifi_AngleUtil_h +#define hifi_AngleUtil_h #include @@ -98,5 +98,4 @@ void angleHorizontalPolar(float& azimuth, float& altitude) { azimuth = angleUnsignedNormal(azimuth); } -#endif - +#endif // hifi_AngleUtil_h diff --git a/libraries/shared/src/Assignment.h b/libraries/shared/src/Assignment.h index 437112a64f..c5a83cf417 100644 --- a/libraries/shared/src/Assignment.h +++ b/libraries/shared/src/Assignment.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__Assignment__ -#define __hifi__Assignment__ +#ifndef hifi_Assignment_h +#define hifi_Assignment_h #ifdef _WIN32 #include "Systime.h" @@ -101,4 +101,4 @@ protected: QByteArray _payload; /// an optional payload attached to this assignment, a maximum for 1024 bytes will be packed }; -#endif /* defined(__hifi__Assignment__) */ +#endif // hifi_Assignment_h diff --git a/libraries/shared/src/CapsuleShape.h b/libraries/shared/src/CapsuleShape.h index 062c3aff6f..9421bf1789 100644 --- a/libraries/shared/src/CapsuleShape.h +++ b/libraries/shared/src/CapsuleShape.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__CapsuleShape__ -#define __hifi__CapsuleShape__ +#ifndef hifi_CapsuleShape_h +#define hifi_CapsuleShape_h #include "Shape.h" @@ -46,4 +46,4 @@ protected: float _halfHeight; }; -#endif /* defined(__hifi__CapsuleShape__) */ +#endif // hifi_CapsuleShape_h diff --git a/libraries/shared/src/CollisionInfo.h b/libraries/shared/src/CollisionInfo.h index b8c4aa6523..f575dd8595 100644 --- a/libraries/shared/src/CollisionInfo.h +++ b/libraries/shared/src/CollisionInfo.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__CollisionInfo__ -#define __hifi__CollisionInfo__ +#ifndef hifi_CollisionInfo_h +#define hifi_CollisionInfo_h #include #include @@ -101,4 +101,4 @@ private: QVector _collisions; }; -#endif /* defined(__hifi__CollisionInfo__) */ +#endif // hifi_CollisionInfo_h diff --git a/libraries/shared/src/DataServerAccountInfo.h b/libraries/shared/src/DataServerAccountInfo.h index 04d2e7fabd..ae5de6de64 100644 --- a/libraries/shared/src/DataServerAccountInfo.h +++ b/libraries/shared/src/DataServerAccountInfo.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__DataServerAccountInfo__ -#define __hifi__DataServerAccountInfo__ +#ifndef hifi_DataServerAccountInfo_h +#define hifi_DataServerAccountInfo_h #include @@ -42,4 +42,4 @@ private: QString _xmppPassword; }; -#endif /* defined(__hifi__DataServerAccountInfo__) */ +#endif // hifi_DataServerAccountInfo_h diff --git a/libraries/shared/src/DomainInfo.h b/libraries/shared/src/DomainInfo.h index 563e2f8db0..b52b2f71c3 100644 --- a/libraries/shared/src/DomainInfo.h +++ b/libraries/shared/src/DomainInfo.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__DomainInfo__ -#define __hifi__DomainInfo__ +#ifndef hifi_DomainInfo_h +#define hifi_DomainInfo_h #include #include @@ -80,4 +80,4 @@ private: bool _isConnected; }; -#endif /* defined(__hifi__DomainInfo__) */ +#endif // hifi_DomainInfo_h diff --git a/libraries/shared/src/FileUtils.h b/libraries/shared/src/FileUtils.h index 6953676b83..8b31d1473b 100644 --- a/libraries/shared/src/FileUtils.h +++ b/libraries/shared/src/FileUtils.h @@ -22,4 +22,4 @@ public: }; -#endif +#endif // hifi_FileUtils_h diff --git a/libraries/shared/src/FloodFill.h b/libraries/shared/src/FloodFill.h index 5aeede2450..cd77534697 100644 --- a/libraries/shared/src/FloodFill.h +++ b/libraries/shared/src/FloodFill.h @@ -8,8 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__FloodFill__ -#define __hifi__FloodFill__ +#ifndef hifi_FloodFill_h +#define hifi_FloodFill_h // // Line scanning, iterative flood fill algorithm. @@ -106,5 +106,4 @@ void floodFill(Cursor const& p, Strategy const& s) { } -#endif /* defined(__hifi__FloodFill__) */ - +#endif // hifi_FloodFill_h diff --git a/libraries/shared/src/GenericThread.h b/libraries/shared/src/GenericThread.h index 2aaa081aa8..bbb01894ed 100644 --- a/libraries/shared/src/GenericThread.h +++ b/libraries/shared/src/GenericThread.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __shared__GenericThread__ -#define __shared__GenericThread__ +#ifndef hifi_GenericThread_h +#define hifi_GenericThread_h #include #include @@ -65,4 +65,4 @@ private: QThread* _thread; }; -#endif // __shared__GenericThread__ +#endif // hifi_GenericThread_h diff --git a/libraries/shared/src/GeometryUtil.h b/libraries/shared/src/GeometryUtil.h index 3446956ffd..b521a79771 100644 --- a/libraries/shared/src/GeometryUtil.h +++ b/libraries/shared/src/GeometryUtil.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__GeometryUtil__ -#define __interface__GeometryUtil__ +#ifndef hifi_GeometryUtil_h +#define hifi_GeometryUtil_h #include @@ -115,4 +115,4 @@ private: }; -#endif /* defined(__interface__GeometryUtil__) */ +#endif // hifi_GeometryUtil_h diff --git a/libraries/shared/src/HifiSockAddr.h b/libraries/shared/src/HifiSockAddr.h index da8c75baee..f44ebf6dbd 100644 --- a/libraries/shared/src/HifiSockAddr.h +++ b/libraries/shared/src/HifiSockAddr.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__HifiSockAddr__ -#define __hifi__HifiSockAddr__ +#ifndef hifi_HifiSockAddr_h +#define hifi_HifiSockAddr_h #include @@ -52,4 +52,4 @@ quint32 getHostOrderLocalAddress(); Q_DECLARE_METATYPE(HifiSockAddr) -#endif /* defined(__hifi__HifiSockAddr__) */ +#endif // hifi_HifiSockAddr_h diff --git a/libraries/shared/src/ListShape.h b/libraries/shared/src/ListShape.h index b8a8fb018d..7ba2410a23 100644 --- a/libraries/shared/src/ListShape.h +++ b/libraries/shared/src/ListShape.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__ListShape__ -#define __hifi__ListShape__ +#ifndef hifi_ListShape_h +#define hifi_ListShape_h #include @@ -66,4 +66,4 @@ private: ListShape(const ListShape& otherList); // don't implement this }; -#endif // __hifi__ListShape__ +#endif // hifi_ListShape_h diff --git a/libraries/shared/src/Logging.h b/libraries/shared/src/Logging.h index e17f3f3019..edbe8f62ee 100644 --- a/libraries/shared/src/Logging.h +++ b/libraries/shared/src/Logging.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__Logging__ -#define __hifi__Logging__ +#ifndef hifi_Logging_h +#define hifi_Logging_h #ifdef _WIN32 #include "Syssocket.h" @@ -57,4 +57,4 @@ private: static QString _targetName; }; -#endif /* defined(__hifi__Logstash__) */ +#endif // hifi_Logging_h diff --git a/libraries/shared/src/ModelUploader.h b/libraries/shared/src/ModelUploader.h index 7500b0fbb1..26c34d4eb7 100644 --- a/libraries/shared/src/ModelUploader.h +++ b/libraries/shared/src/ModelUploader.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__ModelUploader__ -#define __hifi__ModelUploader__ +#ifndef hifi_ModelUploader_h +#define hifi_ModelUploader_h #include @@ -61,4 +61,4 @@ private: bool addPart(const QString& path, const QString& name); }; -#endif /* defined(__hifi__ModelUploader__) */ +#endif // hifi_ModelUploader_h diff --git a/libraries/shared/src/NetworkPacket.h b/libraries/shared/src/NetworkPacket.h index bc9e3def40..6c086e2f5a 100644 --- a/libraries/shared/src/NetworkPacket.h +++ b/libraries/shared/src/NetworkPacket.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __shared_NetworkPacket__ -#define __shared_NetworkPacket__ +#ifndef hifi_NetworkPacket_h +#define hifi_NetworkPacket_h #include @@ -46,4 +46,4 @@ private: QByteArray _byteArray; }; -#endif /* defined(__shared_NetworkPacket__) */ +#endif // hifi_NetworkPacket_h diff --git a/libraries/shared/src/Node.h b/libraries/shared/src/Node.h index fd3c123df8..e7ebbcfb13 100644 --- a/libraries/shared/src/Node.h +++ b/libraries/shared/src/Node.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__Node__ -#define __hifi__Node__ +#ifndef hifi_Node_h +#define hifi_Node_h #include #include @@ -129,4 +129,4 @@ private: QDebug operator<<(QDebug debug, const Node &message); -#endif /* defined(__hifi__Node__) */ +#endif // hifi_Node_h diff --git a/libraries/shared/src/NodeData.h b/libraries/shared/src/NodeData.h index 6dea803b3f..3b26d5b6d5 100644 --- a/libraries/shared/src/NodeData.h +++ b/libraries/shared/src/NodeData.h @@ -30,4 +30,4 @@ private: QMutex _mutex; }; -#endif +#endif // hifi_NodeData_h diff --git a/libraries/shared/src/NodeList.h b/libraries/shared/src/NodeList.h index 4071127131..86c487e2d6 100644 --- a/libraries/shared/src/NodeList.h +++ b/libraries/shared/src/NodeList.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__NodeList__ -#define __hifi__NodeList__ +#ifndef hifi_NodeList_h +#define hifi_NodeList_h #ifdef _WIN32 #include "Syssocket.h" @@ -183,4 +183,4 @@ private: QElapsedTimer _packetStatTimer; }; -#endif /* defined(__hifi__NodeList__) */ +#endif // hifi_NodeList_h diff --git a/libraries/shared/src/OAuthAccessToken.h b/libraries/shared/src/OAuthAccessToken.h index 2159f595f2..7f7c621231 100644 --- a/libraries/shared/src/OAuthAccessToken.h +++ b/libraries/shared/src/OAuthAccessToken.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__OAuthAccessToken__ -#define __hifi__OAuthAccessToken__ +#ifndef hifi_OAuthAccessToken_h +#define hifi_OAuthAccessToken_h #include #include @@ -37,4 +37,4 @@ private: void swap(OAuthAccessToken& otherToken); }; -#endif /* defined(__hifi__OAuthAccessToken__) */ +#endif // hifi_OAuthAccessToken_h diff --git a/libraries/shared/src/OctalCode.h b/libraries/shared/src/OctalCode.h index 535b8a0021..07895ff67f 100644 --- a/libraries/shared/src/OctalCode.h +++ b/libraries/shared/src/OctalCode.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__OctalCode__ -#define __hifi__OctalCode__ +#ifndef hifi_OctalCode_h +#define hifi_OctalCode_h #include #include @@ -65,4 +65,4 @@ OctalCodeComparison compareOctalCodes(const unsigned char* code1, const unsigned QString octalCodeToHexString(const unsigned char* octalCode); unsigned char* hexStringToOctalCode(const QString& input); -#endif /* defined(__hifi__OctalCode__) */ +#endif // hifi_OctalCode_h diff --git a/libraries/shared/src/PacketHeaders.h b/libraries/shared/src/PacketHeaders.h index 491bdf5ac5..3183e8f12d 100644 --- a/libraries/shared/src/PacketHeaders.h +++ b/libraries/shared/src/PacketHeaders.h @@ -92,4 +92,4 @@ PacketType packetTypeForPacket(const char* packet); int arithmeticCodingValueFromBuffer(const char* checkValue); int numBytesArithmeticCodingFromBuffer(const char* checkValue); -#endif +#endif // hifi_PacketHeaders_h diff --git a/libraries/shared/src/PacketSender.h b/libraries/shared/src/PacketSender.h index d517da6d17..cc65564461 100644 --- a/libraries/shared/src/PacketSender.h +++ b/libraries/shared/src/PacketSender.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __shared__PacketSender__ -#define __shared__PacketSender__ +#ifndef hifi_PacketSender_h +#define hifi_PacketSender_h #include @@ -124,4 +124,4 @@ private: QMutex _waitingOnPacketsMutex; }; -#endif // __shared__PacketSender__ +#endif // hifi_PacketSender_h diff --git a/libraries/shared/src/PerfStat.h b/libraries/shared/src/PerfStat.h index c3ae12a825..478c9afead 100644 --- a/libraries/shared/src/PerfStat.h +++ b/libraries/shared/src/PerfStat.h @@ -12,8 +12,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__PerfStat__ -#define __hifi__PerfStat__ +#ifndef hifi_PerfStat_h +#define hifi_PerfStat_h #include #include "SharedUtil.h" @@ -56,4 +56,4 @@ public: }; -#endif /* defined(__hifi__PerfStat__) */ +#endif // hifi_PerfStat_h diff --git a/libraries/shared/src/Radix2InplaceSort.h b/libraries/shared/src/Radix2InplaceSort.h index 38c7b0b73c..dfa455a32d 100644 --- a/libraries/shared/src/Radix2InplaceSort.h +++ b/libraries/shared/src/Radix2InplaceSort.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__Radix2InplaceSort__ -#define __hifi__Radix2InplaceSort__ +#ifndef hifi_Radix2InplaceSort_h +#define hifi_Radix2InplaceSort_h #include @@ -94,4 +94,4 @@ void radix2InplaceSort( BidiIterator from, BidiIterator to, .go(from, to, scanner.initial_state()); } -#endif /* defined(__hifi__Radix2InplaceSort__) */ +#endif // hifi_Radix2InplaceSort_h diff --git a/libraries/shared/src/Radix2IntegerScanner.h b/libraries/shared/src/Radix2IntegerScanner.h index 2137db0548..16a6224778 100644 --- a/libraries/shared/src/Radix2IntegerScanner.h +++ b/libraries/shared/src/Radix2IntegerScanner.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__Radix2IntegerScanner__ -#define __hifi__Radix2IntegerScanner__ +#ifndef hifi_Radix2IntegerScanner_h +#define hifi_Radix2IntegerScanner_h #include #include @@ -85,5 +85,4 @@ class Radix2IntegerScanner< Int, true > bool bit(Int const& v, state_type const& s) const { return !!((v-valMsb) & s); } }; -#endif /* defined(__hifi__Radix2IntegerScanner__) */ - +#endif // hifi_Radix2IntegerScanner_h diff --git a/libraries/shared/src/ReceivedPacketProcessor.h b/libraries/shared/src/ReceivedPacketProcessor.h index e4365f4e18..a34b43626c 100644 --- a/libraries/shared/src/ReceivedPacketProcessor.h +++ b/libraries/shared/src/ReceivedPacketProcessor.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __shared__ReceivedPacketProcessor__ -#define __shared__ReceivedPacketProcessor__ +#ifndef hifi_ReceivedPacketProcessor_h +#define hifi_ReceivedPacketProcessor_h #include @@ -56,4 +56,4 @@ private: QMutex _waitingOnPacketsMutex; }; -#endif // __shared__PacketReceiver__ +#endif // hifi_ReceivedPacketProcessor_h diff --git a/libraries/shared/src/RegisteredMetaTypes.h b/libraries/shared/src/RegisteredMetaTypes.h index 93fb4e7f57..d876965723 100644 --- a/libraries/shared/src/RegisteredMetaTypes.h +++ b/libraries/shared/src/RegisteredMetaTypes.h @@ -56,4 +56,4 @@ Q_DECLARE_METATYPE(CollisionInfo) QScriptValue collisionToScriptValue(QScriptEngine* engine, const CollisionInfo& collision); void collisionFromScriptValue(const QScriptValue &object, CollisionInfo& collision); -#endif +#endif // hifi_RegisteredMetaTypes_h diff --git a/libraries/shared/src/ResourceCache.h b/libraries/shared/src/ResourceCache.h index 984ab7aaa2..da217516e1 100644 --- a/libraries/shared/src/ResourceCache.h +++ b/libraries/shared/src/ResourceCache.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __shared__ResourceCache__ -#define __shared__ResourceCache__ +#ifndef hifi_ResourceCache_h +#define hifi_ResourceCache_h #include #include @@ -177,4 +177,4 @@ private: uint qHash(const QPointer& value, uint seed = 0); -#endif /* defined(__shared__ResourceCache__) */ +#endif // hifi_ResourceCache_h diff --git a/libraries/shared/src/Shape.h b/libraries/shared/src/Shape.h index 11ce41d103..fd16eafeae 100644 --- a/libraries/shared/src/Shape.h +++ b/libraries/shared/src/Shape.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__Shape__ -#define __hifi__Shape__ +#ifndef hifi_Shape_h +#define hifi_Shape_h #include #include @@ -55,4 +55,4 @@ protected: glm::quat _rotation; }; -#endif /* defined(__hifi__Shape__) */ +#endif // hifi_Shape_h diff --git a/libraries/shared/src/ShapeCollider.h b/libraries/shared/src/ShapeCollider.h index c1018bec42..7f02acf15c 100644 --- a/libraries/shared/src/ShapeCollider.h +++ b/libraries/shared/src/ShapeCollider.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__ShapeCollider__ -#define __hifi__ShapeCollider__ +#ifndef hifi_ShapeCollider_h +#define hifi_ShapeCollider_h #include "CapsuleShape.h" #include "CollisionInfo.h" @@ -82,4 +82,4 @@ namespace ShapeCollider { } // namespace ShapeCollider -#endif // __hifi__ShapeCollider__ +#endif // hifi_ShapeCollider_h diff --git a/libraries/shared/src/SharedUtil.h b/libraries/shared/src/SharedUtil.h index 90dd0ccfe8..f07995dce1 100644 --- a/libraries/shared/src/SharedUtil.h +++ b/libraries/shared/src/SharedUtil.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__SharedUtil__ -#define __hifi__SharedUtil__ +#ifndef hifi_SharedUtil_h +#define hifi_SharedUtil_h #include #include @@ -171,4 +171,4 @@ int unpackFloatVec3FromSignedTwoByteFixed(const unsigned char* sourceBuffer, glm /// \return vec3 with euler angles in radians glm::vec3 safeEulerAngles(const glm::quat& q); -#endif /* defined(__hifi__SharedUtil__) */ +#endif // hifi_SharedUtil_h diff --git a/libraries/shared/src/SimpleMovingAverage.h b/libraries/shared/src/SimpleMovingAverage.h index 16d30279b0..3eec9d5be8 100644 --- a/libraries/shared/src/SimpleMovingAverage.h +++ b/libraries/shared/src/SimpleMovingAverage.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__Stats__ -#define __hifi__Stats__ +#ifndef hifi_SimpleMovingAverage_h +#define hifi_SimpleMovingAverage_h #include @@ -37,4 +37,4 @@ private: float ONE_MINUS_WEIGHTING; }; -#endif /* defined(__hifi__Stats__) */ +#endif // hifi_SimpleMovingAverage_h diff --git a/libraries/shared/src/SphereShape.h b/libraries/shared/src/SphereShape.h index 746f93be80..62783ab340 100644 --- a/libraries/shared/src/SphereShape.h +++ b/libraries/shared/src/SphereShape.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__SphereShape__ -#define __hifi__SphereShape__ +#ifndef hifi_SphereShape_h +#define hifi_SphereShape_h #include "Shape.h" @@ -31,4 +31,4 @@ public: void setRadius(float radius) { _boundingRadius = radius; } }; -#endif /* defined(__hifi__SphereShape__) */ +#endif // hifi_SphereShape_h diff --git a/libraries/shared/src/StdDev.h b/libraries/shared/src/StdDev.h index 82fccdd79a..77873a3549 100644 --- a/libraries/shared/src/StdDev.h +++ b/libraries/shared/src/StdDev.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__StdDev__ -#define __hifi__StdDev__ +#ifndef hifi_StdDev_h +#define hifi_StdDev_h class StDev { public: @@ -25,4 +25,4 @@ class StDev { int sampleCount; }; -#endif /* defined(__hifi__StdDev__) */ +#endif // hifi_StdDev_h diff --git a/libraries/shared/src/StreamUtils.h b/libraries/shared/src/StreamUtils.h index d70096bd27..2546d49ffc 100644 --- a/libraries/shared/src/StreamUtils.h +++ b/libraries/shared/src/StreamUtils.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __tests__StreamUtils__ -#define __tests__StreamUtils__ +#ifndef hifi_StreamUtils_h +#define hifi_StreamUtils_h #include @@ -40,4 +40,4 @@ std::ostream& operator<<(std::ostream& s, const CapsuleShape& capsule); #endif // DEBUG -#endif // __tests__StreamUtils__ +#endif // hifi_StreamUtils_h diff --git a/libraries/shared/src/ThreadedAssignment.h b/libraries/shared/src/ThreadedAssignment.h index 9f1f45c1a9..e9241d0272 100644 --- a/libraries/shared/src/ThreadedAssignment.h +++ b/libraries/shared/src/ThreadedAssignment.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__ThreadedAssignment__ -#define __hifi__ThreadedAssignment__ +#ifndef hifi_ThreadedAssignment_h +#define hifi_ThreadedAssignment_h #include @@ -42,4 +42,4 @@ signals: typedef QSharedPointer SharedAssignmentPointer; -#endif /* defined(__hifi__ThreadedAssignment__) */ +#endif // hifi_ThreadedAssignment_h diff --git a/libraries/shared/src/UUID.h b/libraries/shared/src/UUID.h index da0025d425..7e7048486f 100644 --- a/libraries/shared/src/UUID.h +++ b/libraries/shared/src/UUID.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__UUID__ -#define __hifi__UUID__ +#ifndef hifi_UUID_h +#define hifi_UUID_h #include @@ -18,4 +18,4 @@ const int NUM_BYTES_RFC4122_UUID = 16; QString uuidStringWithoutCurlyBraces(const QUuid& uuid); -#endif /* defined(__hifi__UUID__) */ +#endif // hifi_UUID_h diff --git a/libraries/voxels/src/EnvironmentData.h b/libraries/voxels/src/EnvironmentData.h index fe0e279ba8..3eac4048c2 100644 --- a/libraries/voxels/src/EnvironmentData.h +++ b/libraries/voxels/src/EnvironmentData.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__EnvironmentData__ -#define __interface__EnvironmentData__ +#ifndef hifi_EnvironmentData_h +#define hifi_EnvironmentData_h #include @@ -75,4 +75,4 @@ private: float _sunBrightness; }; -#endif /* defined(__interface__EnvironmentData__) */ +#endif // hifi_EnvironmentData_h diff --git a/libraries/voxels/src/LocalVoxelsList.h b/libraries/voxels/src/LocalVoxelsList.h index 2ec68d3234..d22d72446f 100644 --- a/libraries/voxels/src/LocalVoxelsList.h +++ b/libraries/voxels/src/LocalVoxelsList.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__LocalVoxelsList__ -#define __hifi__LocalVoxelsList__ +#ifndef hifi_LocalVoxelsList_h +#define hifi_LocalVoxelsList_h #include #include @@ -59,4 +59,4 @@ private: QList _persistantTrees; }; -#endif /* defined(__hifi__LocalVoxelsList__) */ +#endif // hifi_LocalVoxelsList_h diff --git a/libraries/voxels/src/Tags.h b/libraries/voxels/src/Tags.h index ec1ae8c0e8..1ac231f27c 100644 --- a/libraries/voxels/src/Tags.h +++ b/libraries/voxels/src/Tags.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__Tags__ -#define __hifi__Tags__ +#ifndef hifi_Tags_h +#define hifi_Tags_h #include @@ -180,4 +180,4 @@ private: int* _data; }; -#endif /* defined(__hifi__Tags__) */ +#endif // hifi_Tags_h diff --git a/libraries/voxels/src/VoxelConstants.h b/libraries/voxels/src/VoxelConstants.h index fc2c502a65..34a7667273 100644 --- a/libraries/voxels/src/VoxelConstants.h +++ b/libraries/voxels/src/VoxelConstants.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi_VoxelConstants_h__ -#define __hifi_VoxelConstants_h__ +#ifndef hifi_VoxelConstants_h +#define hifi_VoxelConstants_h #include #include @@ -47,4 +47,4 @@ const quint64 CLIENT_TO_SERVER_VOXEL_SEND_INTERVAL_USECS = 1000 * 5; // 1 packet const int DEFAULT_MAX_VOXEL_PPS = 600; // the default maximum PPS we think a voxel server should send to a client -#endif +#endif // hifi_VoxelConstants_h diff --git a/libraries/voxels/src/VoxelDetail.h b/libraries/voxels/src/VoxelDetail.h index 5ed68f540e..d30255bbb1 100644 --- a/libraries/voxels/src/VoxelDetail.h +++ b/libraries/voxels/src/VoxelDetail.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__VoxelDetail__ -#define __hifi__VoxelDetail__ +#ifndef hifi_VoxelDetail_h +#define hifi_VoxelDetail_h #include @@ -50,4 +50,4 @@ Q_DECLARE_METATYPE(RayToVoxelIntersectionResult) QScriptValue rayToVoxelIntersectionResultToScriptValue(QScriptEngine* engine, const RayToVoxelIntersectionResult& results); void rayToVoxelIntersectionResultFromScriptValue(const QScriptValue& object, RayToVoxelIntersectionResult& results); -#endif /* defined(__hifi__VoxelDetail__) */ +#endif // hifi_VoxelDetail_h diff --git a/libraries/voxels/src/VoxelEditPacketSender.h b/libraries/voxels/src/VoxelEditPacketSender.h index fdf70fb96d..ff72e5704a 100644 --- a/libraries/voxels/src/VoxelEditPacketSender.h +++ b/libraries/voxels/src/VoxelEditPacketSender.h @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __shared__VoxelEditPacketSender__ -#define __shared__VoxelEditPacketSender__ +#ifndef hifi_VoxelEditPacketSender_h +#define hifi_VoxelEditPacketSender_h #include #include "VoxelDetail.h" @@ -50,4 +50,4 @@ public: // My server type is the voxel server virtual unsigned char getMyNodeType() const { return NodeType::VoxelServer; } }; -#endif // __shared__VoxelEditPacketSender__ +#endif // hifi_VoxelEditPacketSender_h diff --git a/libraries/voxels/src/VoxelTree.h b/libraries/voxels/src/VoxelTree.h index 1fafd429ed..e0bc1d9a47 100644 --- a/libraries/voxels/src/VoxelTree.h +++ b/libraries/voxels/src/VoxelTree.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__VoxelTree__ -#define __hifi__VoxelTree__ +#ifndef hifi_VoxelTree_h +#define hifi_VoxelTree_h #include @@ -57,4 +57,4 @@ private: void readCodeColorBufferToTreeRecursion(VoxelTreeElement* node, ReadCodeColorBufferToTreeArgs& args); }; -#endif /* defined(__hifi__VoxelTree__) */ +#endif // hifi_VoxelTree_h diff --git a/libraries/voxels/src/VoxelTreeCommands.h b/libraries/voxels/src/VoxelTreeCommands.h index 314a49b845..4f2610577e 100644 --- a/libraries/voxels/src/VoxelTreeCommands.h +++ b/libraries/voxels/src/VoxelTreeCommands.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__VoxelTreeCommands__ -#define __hifi__VoxelTreeCommands__ +#ifndef hifi_VoxelTreeCommands_h +#define hifi_VoxelTreeCommands_h #include #include @@ -46,4 +46,4 @@ private: VoxelDetail _voxel; }; -#endif /* defined(__hifi__VoxelTreeCommands__) */ +#endif // hifi_VoxelTreeCommands_h diff --git a/libraries/voxels/src/VoxelTreeElement.h b/libraries/voxels/src/VoxelTreeElement.h index 757cffc8bc..140744afb0 100644 --- a/libraries/voxels/src/VoxelTreeElement.h +++ b/libraries/voxels/src/VoxelTreeElement.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__VoxelTreeElement__ -#define __hifi__VoxelTreeElement__ +#ifndef hifi_VoxelTreeElement_h +#define hifi_VoxelTreeElement_h //#define HAS_AUDIT_CHILDREN //#define SIMPLE_CHILD_ARRAY @@ -120,5 +120,4 @@ inline unsigned char VoxelTreeElement::getExteriorOcclusions() const { return _exteriorOcclusions; } -#endif /* defined(__hifi__VoxelTreeElement__) */ - +#endif // hifi_VoxelTreeElement_h diff --git a/libraries/voxels/src/VoxelTreeHeadlessViewer.h b/libraries/voxels/src/VoxelTreeHeadlessViewer.h index 55366010ad..3a9f00d754 100644 --- a/libraries/voxels/src/VoxelTreeHeadlessViewer.h +++ b/libraries/voxels/src/VoxelTreeHeadlessViewer.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__VoxelTreeHeadlessViewer__ -#define __hifi__VoxelTreeHeadlessViewer__ +#ifndef hifi_VoxelTreeHeadlessViewer_h +#define hifi_VoxelTreeHeadlessViewer_h #include #include @@ -37,4 +37,4 @@ public: virtual void init(); }; -#endif /* defined(__hifi__VoxelTreeHeadlessViewer__) */ +#endif // hifi_VoxelTreeHeadlessViewer_h diff --git a/libraries/voxels/src/VoxelsScriptingInterface.h b/libraries/voxels/src/VoxelsScriptingInterface.h index 05c93aab8e..71a8405be6 100644 --- a/libraries/voxels/src/VoxelsScriptingInterface.h +++ b/libraries/voxels/src/VoxelsScriptingInterface.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__VoxelsScriptingInterface__ -#define __hifi__VoxelsScriptingInterface__ +#ifndef hifi_VoxelsScriptingInterface_h +#define hifi_VoxelsScriptingInterface_h #include @@ -88,4 +88,4 @@ private: QUndoStack* _undoStack; }; -#endif /* defined(__hifi__VoxelsScriptingInterface__) */ +#endif // hifi_VoxelsScriptingInterface_h diff --git a/tests/metavoxels/src/MetavoxelTests.h b/tests/metavoxels/src/MetavoxelTests.h index 71f44080d3..206c818c6e 100644 --- a/tests/metavoxels/src/MetavoxelTests.h +++ b/tests/metavoxels/src/MetavoxelTests.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__MetavoxelTests__ -#define __interface__MetavoxelTests__ +#ifndef hifi_MetavoxelTests_h +#define hifi_MetavoxelTests_h #include #include @@ -160,4 +160,4 @@ public: DECLARE_STREAMABLE_METATYPE(SequencedTestMessage) -#endif /* defined(__interface__MetavoxelTests__) */ +#endif // hifi_MetavoxelTests_h diff --git a/tests/physics/src/CollisionInfoTests.h b/tests/physics/src/CollisionInfoTests.h index 7877de4392..54c4e89e95 100644 --- a/tests/physics/src/CollisionInfoTests.h +++ b/tests/physics/src/CollisionInfoTests.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __tests__CollisionInfoTests__ -#define __tests__CollisionInfoTests__ +#ifndef hifi_CollisionInfoTests_h +#define hifi_CollisionInfoTests_h namespace CollisionInfoTests { @@ -20,5 +20,4 @@ namespace CollisionInfoTests { void runAllTests(); } -#endif // __tests__CollisionInfoTests__ - +#endif // hifi_CollisionInfoTests_h diff --git a/tests/physics/src/PhysicsTestUtil.h b/tests/physics/src/PhysicsTestUtil.h index cc758c71bc..998a18ff5d 100644 --- a/tests/physics/src/PhysicsTestUtil.h +++ b/tests/physics/src/PhysicsTestUtil.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __tests__PhysicsTestUtil__ -#define __tests__PhysicsTestUtil__ +#ifndef hifi_PhysicsTestUtil_h +#define hifi_PhysicsTestUtil_h #include #include @@ -26,4 +26,4 @@ std::ostream& operator<<(std::ostream& s, const glm::quat& q); std::ostream& operator<<(std::ostream& s, const glm::mat4& m); std::ostream& operator<<(std::ostream& s, const CollisionInfo& c); -#endif // __tests__PhysicsTestUtil__ +#endif // hifi_PhysicsTestUtil_h diff --git a/tests/physics/src/ShapeColliderTests.h b/tests/physics/src/ShapeColliderTests.h index 9fee17b228..1d468a65d2 100644 --- a/tests/physics/src/ShapeColliderTests.h +++ b/tests/physics/src/ShapeColliderTests.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __tests__ShapeColliderTests__ -#define __tests__ShapeColliderTests__ +#ifndef hifi_ShapeColliderTests_h +#define hifi_ShapeColliderTests_h namespace ShapeColliderTests { @@ -26,4 +26,4 @@ namespace ShapeColliderTests { void runAllTests(); } -#endif // __tests__ShapeColliderTests__ +#endif // hifi_ShapeColliderTests_h diff --git a/voxel-edit/src/SceneUtils.h b/voxel-edit/src/SceneUtils.h index 90b605f2c7..26c8130c4b 100644 --- a/voxel-edit/src/SceneUtils.h +++ b/voxel-edit/src/SceneUtils.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__SceneUtil__ -#define __hifi__SceneUtil__ +#ifndef hifi_SceneUtils_h +#define hifi_SceneUtils_h #include "VoxelTree.h" #include @@ -19,4 +19,4 @@ void addCornersAndAxisLines(VoxelTree* tree); void addSurfaceScene(VoxelTree * tree); -#endif /* defined(__hifi__SceneUtil__) */ +#endif // hifi_SceneUtils_h From 29f8ed3c0920aec1fa10615e3321b692f169a64a Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 12:03:57 -0700 Subject: [PATCH 259/595] manually fix Plane include guard since regex did not catch --- libraries/octree/src/Plane.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries/octree/src/Plane.h b/libraries/octree/src/Plane.h index 1a37499183..0f481dee57 100755 --- a/libraries/octree/src/Plane.h +++ b/libraries/octree/src/Plane.h @@ -12,8 +12,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef _PLANE_ -#define _PLANE_ +#ifndef hifi_Plane_h +#define hifi_Plane_h #include @@ -44,4 +44,4 @@ private: }; -#endif \ No newline at end of file +#endif // hifi_Plane_h \ No newline at end of file From 4d9f3a4aee436af3295455201df83923560d2b52 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Wed, 9 Apr 2014 12:36:02 -0700 Subject: [PATCH 260/595] Added basic mappings to start off with. --- interface/src/devices/Faceplus.cpp | 133 ++++++++++++++--------------- interface/src/devices/Faceplus.h | 3 + 2 files changed, 66 insertions(+), 70 deletions(-) diff --git a/interface/src/devices/Faceplus.cpp b/interface/src/devices/Faceplus.cpp index 89197a5acf..ccbc494fe3 100644 --- a/interface/src/devices/Faceplus.cpp +++ b/interface/src/devices/Faceplus.cpp @@ -33,78 +33,48 @@ void Faceplus::init() { updateEnabled(); } -/* -[2014-04-09T11:42:11] "Mix::Blink_Left" -[2014-04-09T11:42:11] "Mix::Blink_Right" -[2014-04-09T11:42:11] "Mix::BrowsDown_Left" -[2014-04-09T11:42:11] "Mix::BrowsDown_Right" -[2014-04-09T11:42:11] "Mix::BrowsIn_Left" -[2014-04-09T11:42:11] "Mix::BrowsIn_Right" -[2014-04-09T11:42:11] "Mix::BrowsOuterLower_Left" -[2014-04-09T11:42:11] "Mix::BrowsOuterLower_Right" -[2014-04-09T11:42:11] "Mix::BrowsUp_Left" -[2014-04-09T11:42:11] "Mix::BrowsUp_Right" -[2014-04-09T11:42:11] "Mix::EyesWide_Left" -[2014-04-09T11:42:11] "Mix::EyesWide_Right" -[2014-04-09T11:42:11] "Mix::Frown_Left" -[2014-04-09T11:42:11] "Mix::Frown_Right" -[2014-04-09T11:42:11] "Mix::Jaw_RotateY_Left" -[2014-04-09T11:42:11] "Mix::Jaw_RotateY_Right" -[2014-04-09T11:42:11] "Mix::LowerLipDown_Left" -[2014-04-09T11:42:11] "Mix::LowerLipDown_Right" -[2014-04-09T11:42:11] "Mix::LowerLipIn" -[2014-04-09T11:42:11] "Mix::LowerLipOut" -[2014-04-09T11:42:11] "Mix::Midmouth_Left" -[2014-04-09T11:42:11] "Mix::Midmouth_Right" -[2014-04-09T11:42:11] "Mix::MouthDown" -[2014-04-09T11:42:11] "Mix::MouthNarrow_Left" -[2014-04-09T11:42:11] "Mix::MouthNarrow_Right" -[2014-04-09T11:42:11] "Mix::MouthOpen" -[2014-04-09T11:42:11] "Mix::MouthUp" -[2014-04-09T11:42:11] "Mix::MouthWhistle_NarrowAdjust_Left" -[2014-04-09T11:42:11] "Mix::MouthWhistle_NarrowAdjust_Right" -[2014-04-09T11:42:11] "Mix::NoseScrunch_Left" -[2014-04-09T11:42:11] "Mix::NoseScrunch_Right" -[2014-04-09T11:42:11] "Mix::Smile_Left" -[2014-04-09T11:42:11] "Mix::Smile_Right" -[2014-04-09T11:42:11] "Mix::Squint_Left" -[2014-04-09T11:42:11] "Mix::Squint_Right" -[2014-04-09T11:42:11] "Mix::UpperLipIn" -[2014-04-09T11:42:11] "Mix::UpperLipOut" -[2014-04-09T11:42:11] "Mix::UpperLipUp_Left" -[2014-04-09T11:42:11] "Mix::UpperLipUp_Right" -[2014-04-09T11:42:11] "Head_Joint::Rotation_X" -[2014-04-09T11:42:11] "Head_Joint::Rotation_Y" -[2014-04-09T11:42:11] "Head_Joint::Rotation_Z" -[2014-04-09T11:42:11] "Left_Eye_Joint::Rotation_X" -[2014-04-09T11:42:11] "Left_Eye_Joint::Rotation_Y" -[2014-04-09T11:42:11] "Right_Eye_Joint::Rotation_X" -[2014-04-09T11:42:11] "Right_Eye_Joint::Rotation_Y" -*/ - #ifdef HAVE_FACEPLUS static QMultiHash > createChannelNameMap() { QMultiHash > blendshapeMap; - blendshapeMap.insert("JawFwd", QPair("au_jaw_z_push", 1.0f)); - blendshapeMap.insert("JawLeft", QPair("au_jaw_x_push", 1.0f)); - blendshapeMap.insert("JawOpen", QPair("au_jaw_drop", 1.0f)); - blendshapeMap.insert("LipsLowerDown", QPair("au_lower_lip_drop", 1.0f)); - blendshapeMap.insert("LipsUpperOpen", QPair("au_upper_lip_raiser", 1.0f)); - blendshapeMap.insert("LipsStretch_R", QPair("au_lip_stretcher_left", 0.5f)); - blendshapeMap.insert("MouthSmile_L", QPair("au_lip_corner_depressor", -1.0f)); - blendshapeMap.insert("MouthSmile_R", QPair("au_lip_corner_depressor", -1.0f)); - blendshapeMap.insert("BrowsU_R", QPair("au_left_outer_brow_raiser", 1.0f)); - blendshapeMap.insert("BrowsU_C", QPair("au_left_inner_brow_raiser", 1.0f)); - blendshapeMap.insert("BrowsD_R", QPair("au_left_brow_lowerer", 1.0f)); - blendshapeMap.insert("EyeBlink_L", QPair("au_leye_closed", 1.0f)); - blendshapeMap.insert("EyeBlink_R", QPair("au_reye_closed", 1.0f)); - blendshapeMap.insert("EyeOpen_L", QPair("au_upper_lid_raiser", 1.0f)); - blendshapeMap.insert("EyeOpen_R", QPair("au_upper_lid_raiser", 1.0f)); - blendshapeMap.insert("LipLowerOpen", QPair("au_lower_lip_x_push", 1.0f)); - blendshapeMap.insert("LipsStretch_L", QPair("au_lip_stretcher_right", 0.5f)); - blendshapeMap.insert("BrowsU_L", QPair("au_right_outer_brow_raiser", 1.0f)); - blendshapeMap.insert("BrowsU_C", QPair("au_right_inner_brow_raiser", 1.0f)); - blendshapeMap.insert("BrowsD_L", QPair("au_right_brow_lowerer", 1.0f)); + blendshapeMap.insert("EyeBlink_L", QPair("Mix::Blink_Left", 1.0f)); + blendshapeMap.insert("EyeBlink_R", QPair("Mix::Blink_Right", 1.0f)); + blendshapeMap.insert("BrowsD_L", QPair("Mix::BrowsDown_Left", 1.0f)); + blendshapeMap.insert("BrowsD_R", QPair("Mix::BrowsDown_Right", 1.0f)); + blendshapeMap.insert("...", QPair("Mix::BrowsIn_Left", 1.0f)); + blendshapeMap.insert("...", QPair("Mix::BrowsIn_Right", 1.0f)); + blendshapeMap.insert("...", QPair("Mix::BrowsOuterLower_Left", 1.0f)); + blendshapeMap.insert("...", QPair("Mix::BrowsOuterLower_Right", 1.0f)); + blendshapeMap.insert("BrowsU_L", QPair("Mix::BrowsUp_Left", 1.0f)); + blendshapeMap.insert("BrowsU_R", QPair("Mix::BrowsUp_Right", 1.0f)); + blendshapeMap.insert("EyeOpen_L", QPair("Mix::EyesWide_Left", 1.0f)); + blendshapeMap.insert("EyeOpen_R", QPair("Mix::EyesWide_Right", 1.0f)); + blendshapeMap.insert("MouthFrown_L", QPair("Mix::Frown_Left", 1.0f)); + blendshapeMap.insert("MouthFrown_R", QPair("Mix::Frown_Right", 1.0f)); + blendshapeMap.insert("JawLeft", QPair("Mix::Jaw_RotateY_Left", 1.0f)); + blendshapeMap.insert("JawRight", QPair("Mix::Jaw_RotateY_Right", 1.0f)); + blendshapeMap.insert("LipsLowerDown", QPair("Mix::LowerLipDown_Left", 0.5f)); + blendshapeMap.insert("LipsLowerDown", QPair("Mix::LowerLipDown_Right", 0.5f)); + blendshapeMap.insert("...", QPair("Mix::LowerLipIn", 1.0f)); + blendshapeMap.insert("...", QPair("Mix::LowerLipOut", 1.0f)); + blendshapeMap.insert("MouthLeft", QPair("Mix::Midmouth_Left", 1.0f)); + blendshapeMap.insert("MouthRight", QPair("Mix::Midmouth_Right", 1.0f)); + blendshapeMap.insert("...", QPair("Mix::MouthDown", 1.0f)); + blendshapeMap.insert("...", QPair("Mix::MouthNarrow_Left", 1.0f)); + blendshapeMap.insert("...", QPair("Mix::MouthNarrow_Right", 1.0f)); + blendshapeMap.insert("JawOpen", QPair("Mix::MouthOpen", 1.0f)); + blendshapeMap.insert("...", QPair("Mix::MouthUp", 1.0f)); + blendshapeMap.insert("LipsPucker", QPair("Mix::MouthWhistle_NarrowAdjust_Left", 0.5f)); + blendshapeMap.insert("LipsPucker", QPair("Mix::MouthWhistle_NarrowAdjust_Right", 0.5f)); + blendshapeMap.insert("Sneer", QPair("Mix::NoseScrunch_Left", 0.5f)); + blendshapeMap.insert("Sneer", QPair("Mix::NoseScrunch_Right", 0.5f)); + blendshapeMap.insert("MouthSmile_L", QPair("Mix::Smile_Left", 1.0f)); + blendshapeMap.insert("MouthSmile_R", QPair("Mix::Smile_Right", 1.0f)); + blendshapeMap.insert("EyeSquint_L", QPair("Mix::Squint_Left", 1.0f)); + blendshapeMap.insert("EyeSquint_R", QPair("Mix::Squint_Right", 1.0f)); + blendshapeMap.insert("...", QPair("Mix::UpperLipIn", 1.0f)); + blendshapeMap.insert("...", QPair("Mix::UpperLipOut", 1.0f)); + blendshapeMap.insert("LipsUpperUp", QPair("Mix::UpperLipUp_Left", 0.5f)); + blendshapeMap.insert("LipsUpperUp", QPair("Mix::UpperLipUp_Right", 0.5f)); QMultiHash > channelNameMap; for (int i = 0;; i++) { @@ -135,6 +105,11 @@ void Faceplus::update() { if (!(_active = faceplus_current_output_vector(_outputVector.data()))) { return; } + _headRotation = glm::quat(glm::radians(_outputVector.at(_headRotationIndices[0]), + _outputVector.at(_headRotationIndices[1]), _outputVector.at(_headRotationIndices[2]))); + _estimatedEyePitch = (_outputVector.at(_leftEyeRotationIndices[0]) + _outputVector.at(_rightEyeRotationIndices[0])) * 0.5f; + _estimatedEyeYaw = (_outputVector.at(_leftEyeRotationIndices[1]) + _outputVector.at(_rightEyeRotationIndices[1])) * 0.5f; + qFill(_blendshapeCoefficients.begin(), _blendshapeCoefficients.end(), 0.0f); for (int i = 0; i < _outputVector.size(); i++) { for (QMultiHash >::const_iterator it = _channelIndexMap.constFind(i); @@ -171,9 +146,27 @@ void Faceplus::setEnabled(bool enabled) { _channelIndexMap.clear(); for (int i = 0; i < channelCount; i++) { QByteArray name = faceplus_output_channel_name(i); + if (name == "Head_Joint::Rotation_X") { + _headRotationIndices[0] = i; - qDebug() << name; + } else if (name == "Head_Joint::Rotation_Y") { + _headRotationIndices[1] = i; + } else if (name == "Head_Joint::Rotation_Z") { + _headRotationIndices[2] = i; + + } else if (name == "Left_Eye_Joint::Rotation_X") { + _leftEyeRotationIndices[0] = i; + + } else if (name == "Left_Eye_Joint::Rotation_Y") { + _leftEyeRotationIndices[1] = i; + + } else if (name == "Right_Eye_Joint::Rotation_X") { + _rightEyeRotationIndices[0] = i; + + } else if (name == "Right_Eye_Joint::Rotation_Y") { + _rightEyeRotationIndices[1] = i; + } for (QMultiHash >::const_iterator it = getChannelNameMap().constFind(name); it != getChannelNameMap().constEnd() && it.key() == name; it++) { _channelIndexMap.insert(i, it.value()); diff --git a/interface/src/devices/Faceplus.h b/interface/src/devices/Faceplus.h index 1e3272906c..164cf4d031 100644 --- a/interface/src/devices/Faceplus.h +++ b/interface/src/devices/Faceplus.h @@ -45,6 +45,9 @@ private: #ifdef HAVE_FACEPLUS QMultiHash > _channelIndexMap; QVector _outputVector; + int _headRotationIndices[3]; + int _leftEyeRotationIndices[2]; + int _rightEyeRotationIndices[2]; #endif }; From 7304049f83df687ea9df7b11b5e7e4fa8c4011f2 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 9 Apr 2014 12:55:29 -0700 Subject: [PATCH 261/595] update boiler plate to abide by new standard --- libraries/script-engine/src/ScriptUUID.cpp | 11 ++++++++--- libraries/script-engine/src/ScriptUUID.h | 19 +++++++++++-------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/libraries/script-engine/src/ScriptUUID.cpp b/libraries/script-engine/src/ScriptUUID.cpp index cea7247e90..f19ed99417 100644 --- a/libraries/script-engine/src/ScriptUUID.cpp +++ b/libraries/script-engine/src/ScriptUUID.cpp @@ -1,10 +1,15 @@ // -// ScriptUUID.h -// hifi +// ScriptUUID.cpp +// libraries/script-engine/src/ // -// Created by Andrew Meadows on 2014.04.07 +// Created by Andrew Meadows on 2014-04-07 // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. // +// Scriptable interface for a UUID helper class object. Used exclusively in the JavaScript API +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// #include diff --git a/libraries/script-engine/src/ScriptUUID.h b/libraries/script-engine/src/ScriptUUID.h index 43e885cf98..32ab40a106 100644 --- a/libraries/script-engine/src/ScriptUUID.h +++ b/libraries/script-engine/src/ScriptUUID.h @@ -1,17 +1,22 @@ // // ScriptUUID.h -// hifi +// libraries/script-engine/src/ // -// Created by Andrew Meadows on 2014.04.07 +// Created by Andrew Meadows on 2014-04-07 // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. // +// Scriptable interface for a UUID helper class object. Used exclusively in the JavaScript API +// +// 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__ScriptUUID__ -#define __hifi__ScriptUUID__ +#ifndef hifi_ScriptUUID_h +#define hifi_ScriptUUID_h #include -/// Scriptable interface a UUID helper class object. Used exclusively in the JavaScript API +/// Scriptable interface for a UUID helper class object. Used exclusively in the JavaScript API class ScriptUUID : public QObject { Q_OBJECT @@ -24,6 +29,4 @@ public slots: void print(const QString& lable, const QUuid& id); }; - - -#endif /* defined(__hifi__Vec3__) */ +#endif // hifi_ScriptUUID_h From 635f832dfe486bd83f55e86702745e66b2c09e48 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 9 Apr 2014 13:04:17 -0700 Subject: [PATCH 262/595] rename shapeShape() to be collideShapes() Also add collideShapesCoarse() --- libraries/shared/src/ShapeCollider.cpp | 29 +++++++++++- libraries/shared/src/ShapeCollider.h | 10 ++++- tests/physics/src/ShapeColliderTests.cpp | 56 ++++++++++++------------ 3 files changed, 63 insertions(+), 32 deletions(-) diff --git a/libraries/shared/src/ShapeCollider.cpp b/libraries/shared/src/ShapeCollider.cpp index 70f9b9c4bf..6ccf9df9c6 100644 --- a/libraries/shared/src/ShapeCollider.cpp +++ b/libraries/shared/src/ShapeCollider.cpp @@ -10,6 +10,7 @@ #include +#include "GeometryUtil.h" #include "ShapeCollider.h" // NOTE: @@ -19,7 +20,7 @@ namespace ShapeCollider { -bool shapeShape(const Shape* shapeA, const Shape* shapeB, CollisionList& collisions) { +bool collideShapes(const Shape* shapeA, const Shape* shapeB, CollisionList& collisions) { // ATM we only have two shape types so we just check every case. // TODO: make a fast lookup for correct method int typeA = shapeA->getType(); @@ -49,6 +50,30 @@ bool shapeShape(const Shape* shapeA, const Shape* shapeB, CollisionList& collisi return false; } +static CollisionList tempCollisions(32); + +bool collideShapesCoarse(const QVector& shapesA, const QVector& shapesB, CollisionInfo& collision) { + tempCollisions.clear(); + foreach (const Shape* shapeA, shapesA) { + foreach (const Shape* shapeB, shapesB) { + ShapeCollider::collideShapes(shapeA, shapeB, tempCollisions); + } + } + if (tempCollisions.size() > 0) { + glm::vec3 totalPenetration(0.f); + glm::vec3 averageContactPoint(0.f); + for (int j = 0; j < tempCollisions.size(); ++j) { + CollisionInfo* c = tempCollisions.getCollision(j); + totalPenetration = addPenetrations(totalPenetration, c->_penetration); + averageContactPoint += c->_contactPoint; + } + collision._penetration = totalPenetration; + collision._contactPoint = averageContactPoint / (float)(tempCollisions.size()); + return true; + } + return false; +} + bool sphereSphere(const SphereShape* sphereA, const SphereShape* sphereB, CollisionList& collisions) { glm::vec3 BA = sphereB->getPosition() - sphereA->getPosition(); float distanceSquared = glm::dot(BA, BA); @@ -407,7 +432,7 @@ bool listList(const ListShape* listA, const ListShape* listB, CollisionList& col for (int i = 0; i < listA->size() && !collisions.isFull(); ++i) { const Shape* subShape = listA->getSubShape(i); for (int j = 0; j < listB->size() && !collisions.isFull(); ++j) { - touching = shapeShape(subShape, listB->getSubShape(j), collisions) || touching; + touching = collideShapes(subShape, listB->getSubShape(j), collisions) || touching; } } return touching; diff --git a/libraries/shared/src/ShapeCollider.h b/libraries/shared/src/ShapeCollider.h index e3e044c8fe..841a607bc3 100644 --- a/libraries/shared/src/ShapeCollider.h +++ b/libraries/shared/src/ShapeCollider.h @@ -19,9 +19,15 @@ namespace ShapeCollider { /// \param shapeA pointer to first shape /// \param shapeB pointer to second shape - /// \param[out] collisions where to append collision details + /// \param collisions[out] collision details /// \return true if shapes collide - bool shapeShape(const Shape* shapeA, const Shape* shapeB, CollisionList& collisions); + bool collideShapes(const Shape* shapeA, const Shape* shapeB, CollisionList& collisions); + + /// \param shapesA list of shapes + /// \param shapeB list of shapes + /// \param collisions[out] average collision details + /// \return true if any shapes collide + bool collideShapesCoarse(const QVector& shapesA, const QVector& shapesB, CollisionInfo& collision); /// \param sphereA pointer to first shape /// \param sphereB pointer to second shape diff --git a/tests/physics/src/ShapeColliderTests.cpp b/tests/physics/src/ShapeColliderTests.cpp index 7aeec84651..0960f7628a 100644 --- a/tests/physics/src/ShapeColliderTests.cpp +++ b/tests/physics/src/ShapeColliderTests.cpp @@ -40,7 +40,7 @@ void ShapeColliderTests::sphereMissesSphere() { // collide A to B... { - bool touching = ShapeCollider::shapeShape(&sphereA, &sphereB, collisions); + bool touching = ShapeCollider::collideShapes(&sphereA, &sphereB, collisions); if (touching) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphereA and sphereB should NOT touch" << std::endl; @@ -49,7 +49,7 @@ void ShapeColliderTests::sphereMissesSphere() { // collide B to A... { - bool touching = ShapeCollider::shapeShape(&sphereB, &sphereA, collisions); + bool touching = ShapeCollider::collideShapes(&sphereB, &sphereA, collisions); if (touching) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphereA and sphereB should NOT touch" << std::endl; @@ -58,7 +58,7 @@ void ShapeColliderTests::sphereMissesSphere() { // also test shapeShape { - bool touching = ShapeCollider::shapeShape(&sphereB, &sphereA, collisions); + bool touching = ShapeCollider::collideShapes(&sphereB, &sphereA, collisions); if (touching) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphereA and sphereB should NOT touch" << std::endl; @@ -90,7 +90,7 @@ void ShapeColliderTests::sphereTouchesSphere() { // collide A to B... { - bool touching = ShapeCollider::shapeShape(&sphereA, &sphereB, collisions); + bool touching = ShapeCollider::collideShapes(&sphereA, &sphereB, collisions); if (!touching) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphereA and sphereB should touch" << std::endl; @@ -133,7 +133,7 @@ void ShapeColliderTests::sphereTouchesSphere() { // collide B to A... { - bool touching = ShapeCollider::shapeShape(&sphereB, &sphereA, collisions); + bool touching = ShapeCollider::collideShapes(&sphereB, &sphereA, collisions); if (!touching) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphereA and sphereB should touch" << std::endl; @@ -196,7 +196,7 @@ void ShapeColliderTests::sphereMissesCapsule() { sphereA.setPosition(rotation * localPosition + translation); // sphereA agains capsuleB - if (ShapeCollider::shapeShape(&sphereA, &capsuleB, collisions)) + if (ShapeCollider::collideShapes(&sphereA, &capsuleB, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere and capsule should NOT touch" @@ -204,7 +204,7 @@ void ShapeColliderTests::sphereMissesCapsule() { } // capsuleB against sphereA - if (ShapeCollider::shapeShape(&capsuleB, &sphereA, collisions)) + if (ShapeCollider::collideShapes(&capsuleB, &sphereA, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere and capsule should NOT touch" @@ -238,7 +238,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { { // sphereA collides with capsuleB's cylindrical wall sphereA.setPosition(radialOffset * xAxis); - if (!ShapeCollider::shapeShape(&sphereA, &capsuleB, collisions)) + if (!ShapeCollider::collideShapes(&sphereA, &capsuleB, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere and capsule should touch" @@ -269,7 +269,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { } // capsuleB collides with sphereA - if (!ShapeCollider::shapeShape(&capsuleB, &sphereA, collisions)) + if (!ShapeCollider::collideShapes(&capsuleB, &sphereA, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and sphere should touch" @@ -305,7 +305,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { glm::vec3 axialOffset = (halfHeightB + alpha * radiusA + beta * radiusB) * yAxis; sphereA.setPosition(axialOffset * yAxis); - if (!ShapeCollider::shapeShape(&sphereA, &capsuleB, collisions)) + if (!ShapeCollider::collideShapes(&sphereA, &capsuleB, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere and capsule should touch" @@ -336,7 +336,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { } // capsuleB collides with sphereA - if (!ShapeCollider::shapeShape(&capsuleB, &sphereA, collisions)) + if (!ShapeCollider::collideShapes(&capsuleB, &sphereA, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and sphere should touch" @@ -372,7 +372,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { glm::vec3 axialOffset = - (halfHeightB + alpha * radiusA + beta * radiusB) * yAxis; sphereA.setPosition(axialOffset * yAxis); - if (!ShapeCollider::shapeShape(&sphereA, &capsuleB, collisions)) + if (!ShapeCollider::collideShapes(&sphereA, &capsuleB, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere and capsule should touch" @@ -403,7 +403,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { } // capsuleB collides with sphereA - if (!ShapeCollider::shapeShape(&capsuleB, &sphereA, collisions)) + if (!ShapeCollider::collideShapes(&capsuleB, &sphereA, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and sphere should touch" @@ -459,13 +459,13 @@ void ShapeColliderTests::capsuleMissesCapsule() { // side by side capsuleB.setPosition((1.01f * totalRadius) * xAxis); - if (ShapeCollider::shapeShape(&capsuleA, &capsuleB, collisions)) + if (ShapeCollider::collideShapes(&capsuleA, &capsuleB, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and capsule should NOT touch" << std::endl; } - if (ShapeCollider::shapeShape(&capsuleB, &capsuleA, collisions)) + if (ShapeCollider::collideShapes(&capsuleB, &capsuleA, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and capsule should NOT touch" @@ -474,13 +474,13 @@ void ShapeColliderTests::capsuleMissesCapsule() { // end to end capsuleB.setPosition((1.01f * totalHalfLength) * xAxis); - if (ShapeCollider::shapeShape(&capsuleA, &capsuleB, collisions)) + if (ShapeCollider::collideShapes(&capsuleA, &capsuleB, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and capsule should NOT touch" << std::endl; } - if (ShapeCollider::shapeShape(&capsuleB, &capsuleA, collisions)) + if (ShapeCollider::collideShapes(&capsuleB, &capsuleA, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and capsule should NOT touch" @@ -491,13 +491,13 @@ void ShapeColliderTests::capsuleMissesCapsule() { glm::quat rotation = glm::angleAxis(PI_OVER_TWO, zAxis); capsuleB.setRotation(rotation); capsuleB.setPosition((1.01f * (totalRadius + capsuleB.getHalfHeight())) * xAxis); - if (ShapeCollider::shapeShape(&capsuleA, &capsuleB, collisions)) + if (ShapeCollider::collideShapes(&capsuleA, &capsuleB, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and capsule should NOT touch" << std::endl; } - if (ShapeCollider::shapeShape(&capsuleB, &capsuleA, collisions)) + if (ShapeCollider::collideShapes(&capsuleB, &capsuleA, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and capsule should NOT touch" @@ -529,7 +529,7 @@ void ShapeColliderTests::capsuleTouchesCapsule() { { // side by side capsuleB.setPosition((0.99f * totalRadius) * xAxis); - if (!ShapeCollider::shapeShape(&capsuleA, &capsuleB, collisions)) + if (!ShapeCollider::collideShapes(&capsuleA, &capsuleB, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and capsule should touch" @@ -537,7 +537,7 @@ void ShapeColliderTests::capsuleTouchesCapsule() { } else { ++numCollisions; } - if (!ShapeCollider::shapeShape(&capsuleB, &capsuleA, collisions)) + if (!ShapeCollider::collideShapes(&capsuleB, &capsuleA, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and capsule should touch" @@ -550,7 +550,7 @@ void ShapeColliderTests::capsuleTouchesCapsule() { { // end to end capsuleB.setPosition((0.99f * totalHalfLength) * yAxis); - if (!ShapeCollider::shapeShape(&capsuleA, &capsuleB, collisions)) + if (!ShapeCollider::collideShapes(&capsuleA, &capsuleB, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and capsule should touch" @@ -558,7 +558,7 @@ void ShapeColliderTests::capsuleTouchesCapsule() { } else { ++numCollisions; } - if (!ShapeCollider::shapeShape(&capsuleB, &capsuleA, collisions)) + if (!ShapeCollider::collideShapes(&capsuleB, &capsuleA, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and capsule should touch" @@ -573,7 +573,7 @@ void ShapeColliderTests::capsuleTouchesCapsule() { capsuleB.setRotation(rotation); capsuleB.setPosition((0.99f * (totalRadius + capsuleB.getHalfHeight())) * xAxis); - if (!ShapeCollider::shapeShape(&capsuleA, &capsuleB, collisions)) + if (!ShapeCollider::collideShapes(&capsuleA, &capsuleB, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and capsule should touch" @@ -581,7 +581,7 @@ void ShapeColliderTests::capsuleTouchesCapsule() { } else { ++numCollisions; } - if (!ShapeCollider::shapeShape(&capsuleB, &capsuleA, collisions)) + if (!ShapeCollider::collideShapes(&capsuleB, &capsuleA, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and capsule should touch" @@ -599,7 +599,7 @@ void ShapeColliderTests::capsuleTouchesCapsule() { capsuleB.setPosition(positionB); // capsuleA vs capsuleB - if (!ShapeCollider::shapeShape(&capsuleA, &capsuleB, collisions)) + if (!ShapeCollider::collideShapes(&capsuleA, &capsuleB, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and capsule should touch" @@ -628,7 +628,7 @@ void ShapeColliderTests::capsuleTouchesCapsule() { } // capsuleB vs capsuleA - if (!ShapeCollider::shapeShape(&capsuleB, &capsuleA, collisions)) + if (!ShapeCollider::collideShapes(&capsuleB, &capsuleA, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and capsule should touch" @@ -666,7 +666,7 @@ void ShapeColliderTests::capsuleTouchesCapsule() { capsuleB.setPosition(positionB); // capsuleA vs capsuleB - if (!ShapeCollider::shapeShape(&capsuleA, &capsuleB, collisions)) + if (!ShapeCollider::collideShapes(&capsuleA, &capsuleB, collisions)) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: capsule and capsule should touch" From f8e66b4e0d196d306c719a3706b21a99b9e8906b Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 9 Apr 2014 13:05:26 -0700 Subject: [PATCH 263/595] remove cruft --- interface/src/avatar/Avatar.h | 2 -- libraries/script-engine/src/ScriptEngine.h | 1 - 2 files changed, 3 deletions(-) diff --git a/interface/src/avatar/Avatar.h b/interface/src/avatar/Avatar.h index f57982b514..e23ed316ac 100755 --- a/interface/src/avatar/Avatar.h +++ b/interface/src/avatar/Avatar.h @@ -140,8 +140,6 @@ public: static void renderJointConnectingCone(glm::vec3 position1, glm::vec3 position2, float radius1, float radius2); - - /// \return true if we expect the avatar would move as a result of the collision bool collisionWouldMoveAvatar(CollisionInfo& collision) const; diff --git a/libraries/script-engine/src/ScriptEngine.h b/libraries/script-engine/src/ScriptEngine.h index 2b98549d66..99f4e81ea1 100644 --- a/libraries/script-engine/src/ScriptEngine.h +++ b/libraries/script-engine/src/ScriptEngine.h @@ -113,7 +113,6 @@ private: static VoxelsScriptingInterface _voxelsScriptingInterface; static ParticlesScriptingInterface _particlesScriptingInterface; - static int _scriptNumber; AbstractControllerScriptingInterface* _controllerScriptingInterface; AudioScriptingInterface _audioScriptingInterface; From 698e3783e0fb05fb172424c3459f0d1a81bc77a0 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 9 Apr 2014 13:06:29 -0700 Subject: [PATCH 264/595] fixing formatting --- libraries/script-engine/src/ScriptUUID.cpp | 2 +- libraries/script-engine/src/ScriptUUID.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/script-engine/src/ScriptUUID.cpp b/libraries/script-engine/src/ScriptUUID.cpp index f19ed99417..9e00f9c095 100644 --- a/libraries/script-engine/src/ScriptUUID.cpp +++ b/libraries/script-engine/src/ScriptUUID.cpp @@ -5,7 +5,7 @@ // Created by Andrew Meadows on 2014-04-07 // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. // -// Scriptable interface for a UUID helper class object. Used exclusively in the JavaScript API +// Scriptable interface for a UUID helper class object. Used exclusively in the JavaScript API // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html diff --git a/libraries/script-engine/src/ScriptUUID.h b/libraries/script-engine/src/ScriptUUID.h index 32ab40a106..db94b5082b 100644 --- a/libraries/script-engine/src/ScriptUUID.h +++ b/libraries/script-engine/src/ScriptUUID.h @@ -5,7 +5,7 @@ // Created by Andrew Meadows on 2014-04-07 // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. // -// Scriptable interface for a UUID helper class object. Used exclusively in the JavaScript API +// Scriptable interface for a UUID helper class object. Used exclusively in the JavaScript API // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html From 79455d5850936f1483dc7e2532be76311c46ae7b Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Wed, 9 Apr 2014 13:07:02 -0700 Subject: [PATCH 265/595] More Faceplus work. Starting to get results. --- interface/src/Application.cpp | 4 ++-- interface/src/avatar/Head.cpp | 19 +++++++------------ interface/src/devices/Faceplus.cpp | 12 ++++++------ 3 files changed, 15 insertions(+), 20 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 5c50f76767..dedbbced30 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1568,9 +1568,9 @@ void Application::init() { qDebug("Loaded settings"); // initialize our face trackers after loading the menu settings - _faceplus.init(); _faceshift.init(); - _visage.init(); + _faceplus.init(); + _visage.init(); // fire off an immediate domain-server check in now that settings are loaded NodeList::getInstance()->sendDomainServerCheckIn(); diff --git a/interface/src/avatar/Head.cpp b/interface/src/avatar/Head.cpp index f42220c0f4..c3cff15c70 100644 --- a/interface/src/avatar/Head.cpp +++ b/interface/src/avatar/Head.cpp @@ -60,17 +60,11 @@ void Head::reset() { void Head::simulate(float deltaTime, bool isMine, bool billboard) { // Update audio trailing average for rendering facial animations - Faceshift* faceshift = Application::getInstance()->getFaceshift(); - Visage* visage = Application::getInstance()->getVisage(); if (isMine) { - _isFaceshiftConnected = false; - if (faceshift->isActive()) { - _blendshapeCoefficients = faceshift->getBlendshapeCoefficients(); - _isFaceshiftConnected = true; - - } else if (visage->isActive()) { - _blendshapeCoefficients = visage->getBlendshapeCoefficients(); - _isFaceshiftConnected = true; + FaceTracker* faceTracker = Application::getInstance()->getActiveFaceTracker(); + if ((_isFaceshiftConnected = faceTracker)) { + _blendshapeCoefficients = faceTracker->getBlendshapeCoefficients(); + _isFaceshiftConnected = true; } } @@ -152,8 +146,9 @@ void Head::simulate(float deltaTime, bool isMine, bool billboard) { const float BROW_LIFT_SCALE = 500.0f; const float JAW_OPEN_SCALE = 0.01f; const float JAW_OPEN_DEAD_ZONE = 0.75f; - faceshift->updateFakeCoefficients(_leftEyeBlink, _rightEyeBlink, min(1.0f, _browAudioLift * BROW_LIFT_SCALE), - glm::clamp(sqrt(_averageLoudness * JAW_OPEN_SCALE) - JAW_OPEN_DEAD_ZONE, 0.0f, 1.0f), _blendshapeCoefficients); + Application::getInstance()->getFaceshift()->updateFakeCoefficients(_leftEyeBlink, _rightEyeBlink, + min(1.0f, _browAudioLift * BROW_LIFT_SCALE), glm::clamp(sqrt(_averageLoudness * JAW_OPEN_SCALE) - + JAW_OPEN_DEAD_ZONE, 0.0f, 1.0f), _blendshapeCoefficients); } if (!isMine) { diff --git a/interface/src/devices/Faceplus.cpp b/interface/src/devices/Faceplus.cpp index ccbc494fe3..9a3067e48f 100644 --- a/interface/src/devices/Faceplus.cpp +++ b/interface/src/devices/Faceplus.cpp @@ -44,8 +44,8 @@ static QMultiHash > createChannelNameMap() { blendshapeMap.insert("...", QPair("Mix::BrowsIn_Right", 1.0f)); blendshapeMap.insert("...", QPair("Mix::BrowsOuterLower_Left", 1.0f)); blendshapeMap.insert("...", QPair("Mix::BrowsOuterLower_Right", 1.0f)); - blendshapeMap.insert("BrowsU_L", QPair("Mix::BrowsUp_Left", 1.0f)); - blendshapeMap.insert("BrowsU_R", QPair("Mix::BrowsUp_Right", 1.0f)); + blendshapeMap.insert("BrowsU_L", QPair("Mix::BrowsUp_Left", 5.0f)); + blendshapeMap.insert("BrowsU_R", QPair("Mix::BrowsUp_Right", 5.0f)); blendshapeMap.insert("EyeOpen_L", QPair("Mix::EyesWide_Left", 1.0f)); blendshapeMap.insert("EyeOpen_R", QPair("Mix::EyesWide_Right", 1.0f)); blendshapeMap.insert("MouthFrown_L", QPair("Mix::Frown_Left", 1.0f)); @@ -102,12 +102,12 @@ void Faceplus::update() { if (!_active) { return; } - if (!(_active = faceplus_current_output_vector(_outputVector.data()))) { + if (!(_active = faceplus_synchronous_track() && faceplus_current_output_vector(_outputVector.data()))) { return; } - _headRotation = glm::quat(glm::radians(_outputVector.at(_headRotationIndices[0]), - _outputVector.at(_headRotationIndices[1]), _outputVector.at(_headRotationIndices[2]))); - _estimatedEyePitch = (_outputVector.at(_leftEyeRotationIndices[0]) + _outputVector.at(_rightEyeRotationIndices[0])) * 0.5f; + _headRotation = glm::quat(glm::radians(glm::vec3(-_outputVector.at(_headRotationIndices[0]), + _outputVector.at(_headRotationIndices[1]), -_outputVector.at(_headRotationIndices[2])))); + _estimatedEyePitch = (_outputVector.at(_leftEyeRotationIndices[0]) + _outputVector.at(_rightEyeRotationIndices[0])) * -0.5f; _estimatedEyeYaw = (_outputVector.at(_leftEyeRotationIndices[1]) + _outputVector.at(_rightEyeRotationIndices[1])) * 0.5f; qFill(_blendshapeCoefficients.begin(), _blendshapeCoefficients.end(), 0.0f); From e480064e6637f012fd3d3d0935ba3374be2246a8 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 9 Apr 2014 13:07:54 -0700 Subject: [PATCH 266/595] rename more shapeShape() to be collideShapes() --- interface/src/renderer/Model.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 36fbbe3833..4118c483ec 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -592,7 +592,7 @@ bool Model::findCollisions(const QVector shapes, CollisionList& co const Shape* theirShape = shapes[i]; for (int j = 0; j < _jointShapes.size(); ++j) { const Shape* ourShape = _jointShapes[j]; - if (ShapeCollider::shapeShape(theirShape, ourShape, collisions)) { + if (ShapeCollider::collideShapes(theirShape, ourShape, collisions)) { collided = true; } } @@ -619,7 +619,7 @@ bool Model::findSphereCollisions(const glm::vec3& sphereCenter, float sphereRadi } while (ancestorIndex != -1); } } - if (ShapeCollider::shapeShape(&sphere, _jointShapes[i], collisions)) { + if (ShapeCollider::collideShapes(&sphere, _jointShapes[i], collisions)) { CollisionInfo* collision = collisions.getLastCollision(); collision->_type = MODEL_COLLISION; collision->_data = (void*)(this); From a1c6843bd409555ce44b9f1a36fe02508295bffd Mon Sep 17 00:00:00 2001 From: stojce Date: Wed, 9 Apr 2014 22:14:35 +0200 Subject: [PATCH 267/595] CR Fixes --- interface/src/ui/FramelessDialog.cpp | 15 ++++----------- interface/src/ui/FramelessDialog.h | 13 ++++++++----- interface/src/ui/PreferencesDialog.cpp | 8 ++++++-- interface/src/ui/PreferencesDialog.h | 13 ++++++++----- 4 files changed, 26 insertions(+), 23 deletions(-) diff --git a/interface/src/ui/FramelessDialog.cpp b/interface/src/ui/FramelessDialog.cpp index 14f7e57f3b..18e3bca89a 100644 --- a/interface/src/ui/FramelessDialog.cpp +++ b/interface/src/ui/FramelessDialog.cpp @@ -1,9 +1,12 @@ // // FramelessDialog.cpp -// hifi +// interface/src/ui // // Created by Stojce Slavkovski on 2/20/14. +// Copyright 2014 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "Application.h" @@ -25,20 +28,17 @@ QDialog(parent, flags | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint) { bool FramelessDialog::eventFilter(QObject* sender, QEvent* event) { switch (event->type()) { case QEvent::Move: - if (sender == parentWidget()) { // move to upper left corner on app move move(parentWidget()->geometry().topLeft()); } break; - case QEvent::Resize: if (sender == parentWidget()) { // keep full app height on resizing the app setFixedHeight(parentWidget()->size().height()); } break; - case QEvent::WindowStateChange: if (parentWidget()->isMinimized()) { setHidden(true); @@ -46,16 +46,13 @@ bool FramelessDialog::eventFilter(QObject* sender, QEvent* event) { setHidden(false); } break; - case QEvent::ApplicationDeactivate: // hide on minimize and focus lost setHidden(true); break; - case QEvent::ApplicationActivate: setHidden(false); break; - default: break; } @@ -63,10 +60,6 @@ bool FramelessDialog::eventFilter(QObject* sender, QEvent* event) { return false; } -FramelessDialog::~FramelessDialog() { - deleteLater(); -} - void FramelessDialog::setStyleSheetFile(const QString& fileName) { QFile globalStyleSheet(Application::resourcesPath() + "styles/global.qss"); QFile styleSheet(Application::resourcesPath() + fileName); diff --git a/interface/src/ui/FramelessDialog.h b/interface/src/ui/FramelessDialog.h index aa83960b8b..db9f6dfd6c 100644 --- a/interface/src/ui/FramelessDialog.h +++ b/interface/src/ui/FramelessDialog.h @@ -1,13 +1,17 @@ // // FramelessDialog.h -// hifi +// interface/src/ui // // Created by Stojce Slavkovski on 2/20/14. +// Copyright 2014 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__FramelessDialog__ -#define __hifi__FramelessDialog__ + +#ifndef hifi_FramelessDialog_h +#define hifi_FramelessDialog_h #include @@ -16,7 +20,6 @@ class FramelessDialog : public QDialog { public: FramelessDialog(QWidget* parent = 0, Qt::WindowFlags flags = 0); - ~FramelessDialog(); void setStyleSheetFile(const QString& fileName); protected: @@ -32,4 +35,4 @@ private: }; -#endif /* defined(__hifi__FramelessDialog__) */ +#endif // hifi_FramelessDialog_h diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index 96ffe662c7..c6a994b4d5 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -1,11 +1,15 @@ // // PreferencesDialog.cpp -// hifi +// interface/src/ui // -// Created by Stojce Slavkovski on 2/22/14. +// Created by Stojce Slavkovski on 2/20/14. +// Copyright 2014 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // + #include "Application.h" #include "Menu.h" #include "PreferencesDialog.h" diff --git a/interface/src/ui/PreferencesDialog.h b/interface/src/ui/PreferencesDialog.h index c7f8f43616..25a1e1b6cf 100644 --- a/interface/src/ui/PreferencesDialog.h +++ b/interface/src/ui/PreferencesDialog.h @@ -1,13 +1,16 @@ // // PreferencesDialog.h -// hifi +// interface/src/ui // -// Created by Stojce Slavkovski on 2/22/14. +// Created by Stojce Slavkovski on 2/20/14. +// Copyright 2014 High Fidelity, Inc. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__PreferencesDialog__ -#define __hifi__PreferencesDialog__ +#ifndef hifi_PreferencesDialog_h +#define hifi_PreferencesDialog_h #include "FramelessDialog.h" #include "ui_preferencesDialog.h" @@ -42,4 +45,4 @@ private slots: }; -#endif /* defined(__hifi__PreferencesDialog__) */ +#endif // hifi_PreferencesDialog_h From 9ab61faacbabbe448ad45735042fc4423b0f3781 Mon Sep 17 00:00:00 2001 From: stojce Date: Wed, 9 Apr 2014 22:32:15 +0200 Subject: [PATCH 268/595] additional CR fixes --- interface/src/ui/PreferencesDialog.cpp | 4 ---- interface/src/ui/PreferencesDialog.h | 1 - 2 files changed, 5 deletions(-) diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index c6a994b4d5..d1c9b4f6ca 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -30,10 +30,6 @@ PreferencesDialog::PreferencesDialog(QWidget* parent, Qt::WindowFlags flags) : F connect(ui.buttonBrowseBody, &QPushButton::clicked, this, &PreferencesDialog::openBodyModelBrowser); } -PreferencesDialog::~PreferencesDialog() { - deleteLater(); -} - void PreferencesDialog::accept() { savePreferences(); close(); diff --git a/interface/src/ui/PreferencesDialog.h b/interface/src/ui/PreferencesDialog.h index 25a1e1b6cf..c9514e584a 100644 --- a/interface/src/ui/PreferencesDialog.h +++ b/interface/src/ui/PreferencesDialog.h @@ -22,7 +22,6 @@ class PreferencesDialog : public FramelessDialog { public: PreferencesDialog(QWidget* parent = 0, Qt::WindowFlags flags = 0); - ~PreferencesDialog(); protected: void resizeEvent(QResizeEvent* resizeEvent); From 7578b282e296c2e79d654dba5c384f2e764483d8 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 9 Apr 2014 14:12:11 -0700 Subject: [PATCH 269/595] CR --- interface/src/ModelUploader.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index 93a2c96c7c..3f496c9890 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -306,7 +306,6 @@ bool ModelUploader::addTextures(const QString& texdir, const QString fbxFile) { } bool ModelUploader::addPart(const QString &path, const QString& name) { - qDebug() << path; QFile file(path); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::warning(NULL, From 034f518d40c59bb1b2a7ca22f0b6c3bcbe455101 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 9 Apr 2014 14:15:45 -0700 Subject: [PATCH 270/595] emit signal on avatar body-body collisions --- interface/src/avatar/MyAvatar.cpp | 29 +++++++++++------------------ interface/src/avatar/MyAvatar.h | 3 +++ 2 files changed, 14 insertions(+), 18 deletions(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 73d2a84eb7..ebcba72f7e 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include @@ -868,8 +869,7 @@ bool findAvatarAvatarPenetration(const glm::vec3 positionA, float radiusA, float return false; } -static CollisionList bodyCollisions(16); -const float BODY_COLLISION_RESOLVE_TIMESCALE = 0.5f; // seconds +const float BODY_COLLISION_RESOLUTION_TIMESCALE = 0.5f; // seconds void MyAvatar::updateCollisionWithAvatars(float deltaTime) { // Reset detector for nearest avatar @@ -882,7 +882,7 @@ void MyAvatar::updateCollisionWithAvatars(float deltaTime) { updateShapePositions(); float myBoundingRadius = getBoundingRadius(); - const float BODY_COLLISION_RESOLVE_FACTOR = deltaTime / BODY_COLLISION_RESOLVE_TIMESCALE; + const float BODY_COLLISION_RESOLUTION_FACTOR = deltaTime / BODY_COLLISION_RESOLUTION_TIMESCALE; foreach (const AvatarSharedPointer& avatarPointer, avatars) { Avatar* avatar = static_cast(avatarPointer.data()); @@ -902,26 +902,19 @@ void MyAvatar::updateCollisionWithAvatars(float deltaTime) { _skeletonModel.getBodyShapes(myShapes); QVector theirShapes; avatar->getSkeletonModel().getBodyShapes(theirShapes); - bodyCollisions.clear(); - // TODO: add method to ShapeCollider for colliding lists of shapes - foreach (const Shape* myShape, myShapes) { - foreach (const Shape* theirShape, theirShapes) { - ShapeCollider::shapeShape(myShape, theirShape, bodyCollisions); + + CollisionInfo collision; + if (ShapeCollider::collideShapesCoarse(myShapes, theirShapes, collision)) { + if (glm::length2(collision._penetration) > EPSILON) { + setPosition(getPosition() - BODY_COLLISION_RESOLUTION_FACTOR * collision._penetration); + _lastBodyPenetration += collision._penetration; + emit collisionWithAvatar(getSessionUUID(), avatar->getSessionUUID(), collision); } } - glm::vec3 totalPenetration(0.f); - for (int j = 0; j < bodyCollisions.size(); ++j) { - CollisionInfo* collision = bodyCollisions.getCollision(j); - totalPenetration = addPenetrations(totalPenetration, collision->_penetration); - } - if (glm::length2(totalPenetration) > EPSILON) { - setPosition(getPosition() - BODY_COLLISION_RESOLVE_FACTOR * totalPenetration); - } - _lastBodyPenetration += totalPenetration; // collide our hands against them // TODO: make this work when we can figure out when the other avatar won't yeild - // (for example, we're colling against their chest or leg) + // (for example, we're colliding against their chest or leg) //getHand()->collideAgainstAvatar(avatar, true); // collide their hands against us diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index 2125b126b3..08e1054829 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -104,6 +104,9 @@ public slots: glm::vec3 getThrust() { return _thrust; }; void setThrust(glm::vec3 newThrust) { _thrust = newThrust; } +signals: + void collisionWithAvatar(const QUuid&, const QUuid&, const CollisionInfo&); + private: bool _mousePressed; float _bodyPitchDelta; // degrees From 07b343ec03fe4c8ca2565fa58cb422f61acc91d7 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 9 Apr 2014 14:32:57 -0700 Subject: [PATCH 271/595] emit events for hand-avatar collisions --- interface/src/avatar/Avatar.h | 3 +++ interface/src/avatar/Hand.cpp | 5 +++++ interface/src/avatar/MyAvatar.h | 3 --- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/interface/src/avatar/Avatar.h b/interface/src/avatar/Avatar.h index e23ed316ac..32700d5d99 100755 --- a/interface/src/avatar/Avatar.h +++ b/interface/src/avatar/Avatar.h @@ -152,6 +152,9 @@ public: public slots: void updateCollisionFlags(); +signals: + void collisionWithAvatar(const QUuid&, const QUuid&, const CollisionInfo&); + protected: SkeletonModel _skeletonModel; float _bodyYawDelta; diff --git a/interface/src/avatar/Hand.cpp b/interface/src/avatar/Hand.cpp index fc47520c83..e50c73d573 100644 --- a/interface/src/avatar/Hand.cpp +++ b/interface/src/avatar/Hand.cpp @@ -159,6 +159,11 @@ void Hand::collideAgainstAvatar(Avatar* avatar, bool isMyHand) { // TODO: submit collision info to MyAvatar which should lean accordingly averageContactPoint /= (float)handCollisions.size(); avatar->applyCollision(averageContactPoint, totalPenetration); + + CollisionInfo collision; + collision._penetration = totalPenetration; + collision._contactPoint = averageContactPoint; + emit avatar->collisionWithAvatar(avatar->getSessionUUID(), _owningAvatar->getSessionUUID(), collision); } } } diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index 08e1054829..2125b126b3 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -104,9 +104,6 @@ public slots: glm::vec3 getThrust() { return _thrust; }; void setThrust(glm::vec3 newThrust) { _thrust = newThrust; } -signals: - void collisionWithAvatar(const QUuid&, const QUuid&, const CollisionInfo&); - private: bool _mousePressed; float _bodyPitchDelta; // degrees From 5d812c8cb221253e160f1664609e05dfb9db129f Mon Sep 17 00:00:00 2001 From: Thijs Wenker Date: Wed, 9 Apr 2014 23:44:40 +0200 Subject: [PATCH 272/595] Fixed loading local stored scripts on Windows machines --- libraries/script-engine/src/ScriptEngine.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index 7d3dd650ae..c5c1fdb2bf 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -92,8 +92,9 @@ ScriptEngine::ScriptEngine(const QUrl& scriptURL, QUrl url(scriptURL); - // if the scheme is empty, maybe they typed in a file, let's try - if (url.scheme().isEmpty()) { + // if the scheme length is one or lower, maybe they typed in a file, let's try + const DWORD WINDOWS_DRIVE_LETTER_SIZE = 1; + if (url.scheme().size() <= WINDOWS_DRIVE_LETTER_SIZE) { url = QUrl::fromLocalFile(scriptURLString); } From 7dec499b79467966e59f15fae08a56f62478f09a Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 14:52:01 -0700 Subject: [PATCH 273/595] fix accidental changes to Audio.cpp --- interface/src/Audio.cpp | 69 +++++++++++++++++++++++++++-------------- 1 file changed, 45 insertions(+), 24 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 90797c7eef..108a785e95 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -98,7 +98,8 @@ Audio::Audio(Oscilloscope* scope, int16_t initialJitterBufferSamples, QObject* p void Audio::init(QGLWidget *parent) { _micTextureId = parent->bindTexture(QImage(Application::resourcesPath() + "images/mic.svg")); - _muteTextureId = parent->bindTexture(QImage(Application::resourcesPath() + "images/mute.svg")); + _muteTextureId = parent->bindTexture(QImage(Application::resourcesPath() + "images/mic-mute.svg")); + _boxTextureId = parent->bindTexture(QImage(Application::resourcesPath() + "images/audio-box.svg")); } void Audio::reset() { @@ -861,13 +862,52 @@ void Audio::handleAudioByteArray(const QByteArray& audioByteArray) { // or send to the mixer and use delayed loopback } -void Audio::renderMuteIcon(int x, int y) { +void Audio::renderToolBox(int x, int y, bool boxed) { - _iconBounds = QRect(x, y, MUTE_ICON_SIZE, MUTE_ICON_SIZE); glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, _micTextureId); - glColor3f(.93f, .93f, .93f); + if (boxed) { + + bool isClipping = ((getTimeSinceLastClip() > 0.f) && (getTimeSinceLastClip() < 1.f)); + const int BOX_LEFT_PADDING = 5; + const int BOX_TOP_PADDING = 10; + const int BOX_WIDTH = 266; + const int BOX_HEIGHT = 44; + + QRect boxBounds = QRect(x - BOX_LEFT_PADDING, y - BOX_TOP_PADDING, BOX_WIDTH, BOX_HEIGHT); + + glBindTexture(GL_TEXTURE_2D, _boxTextureId); + + if (isClipping) { + glColor3f(1.f,0.f,0.f); + } else { + glColor3f(.41f,.41f,.41f); + } + glBegin(GL_QUADS); + + glTexCoord2f(1, 1); + glVertex2f(boxBounds.left(), boxBounds.top()); + + glTexCoord2f(0, 1); + glVertex2f(boxBounds.right(), boxBounds.top()); + + glTexCoord2f(0, 0); + glVertex2f(boxBounds.right(), boxBounds.bottom()); + + glTexCoord2f(1, 0); + glVertex2f(boxBounds.left(), boxBounds.bottom()); + + glEnd(); + } + + _iconBounds = QRect(x, y, MUTE_ICON_SIZE, MUTE_ICON_SIZE); + if (!_muted) { + glBindTexture(GL_TEXTURE_2D, _micTextureId); + } else { + glBindTexture(GL_TEXTURE_2D, _muteTextureId); + } + + glColor3f(1,1,1); glBegin(GL_QUADS); glTexCoord2f(1, 1); @@ -884,25 +924,6 @@ void Audio::renderMuteIcon(int x, int y) { glEnd(); - if (_muted) { - glBindTexture(GL_TEXTURE_2D, _muteTextureId); - glBegin(GL_QUADS); - - glTexCoord2f(1, 1); - glVertex2f(_iconBounds.left(), _iconBounds.top()); - - glTexCoord2f(0, 1); - glVertex2f(_iconBounds.right(), _iconBounds.top()); - - glTexCoord2f(0, 0); - glVertex2f(_iconBounds.right(), _iconBounds.bottom()); - - glTexCoord2f(1, 0); - glVertex2f(_iconBounds.left(), _iconBounds.bottom()); - - glEnd(); - } - glDisable(GL_TEXTURE_2D); } From 28d3eae12b08eed5655a3419d3eace5036d068da Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Wed, 9 Apr 2014 14:52:27 -0700 Subject: [PATCH 274/595] Move Faceplus reading to its own thread to avoid blocking the main one. --- interface/src/Application.cpp | 11 -- interface/src/Application.h | 1 - interface/src/devices/Faceplus.cpp | 173 ++++++++++++++++++----------- interface/src/devices/Faceplus.h | 24 +++- 4 files changed, 127 insertions(+), 82 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index dedbbced30..6e05167d6f 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1689,15 +1689,6 @@ void Application::updateMouseRay() { _myAvatar->setMouseRay(_mouseRayOrigin, _mouseRayDirection); } -void Application::updateFaceplus() { - - bool showWarnings = Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings); - PerformanceWarning warn(showWarnings, "Application::updateFaceplus()"); - - // Update faceplus - _faceplus.update(); -} - void Application::updateFaceshift() { bool showWarnings = Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings); @@ -1894,7 +1885,6 @@ void Application::update(float deltaTime) { // check what's under the mouse and update the mouse voxel updateMouseRay(); - updateFaceplus(); updateFaceshift(); updateVisage(); _myAvatar->updateLookAtTargetAvatar(); @@ -2945,7 +2935,6 @@ void Application::resetSensors() { _mouseX = _glWidget->width() / 2; _mouseY = _glWidget->height() / 2; - _faceplus.reset(); _faceshift.reset(); _visage.reset(); diff --git a/interface/src/Application.h b/interface/src/Application.h index c6b38b1644..7182010050 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -174,7 +174,6 @@ public: bool isMouseHidden() const { return _mouseHidden; } const glm::vec3& getMouseRayOrigin() const { return _mouseRayOrigin; } const glm::vec3& getMouseRayDirection() const { return _mouseRayDirection; } - Faceplus* getFaceplus() { return &_faceplus; } Faceshift* getFaceshift() { return &_faceshift; } Visage* getVisage() { return &_visage; } FaceTracker* getActiveFaceTracker(); diff --git a/interface/src/devices/Faceplus.cpp b/interface/src/devices/Faceplus.cpp index 9a3067e48f..34547c2a6a 100644 --- a/interface/src/devices/Faceplus.cpp +++ b/interface/src/devices/Faceplus.cpp @@ -6,6 +6,8 @@ // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. // +#include + #ifdef HAVE_FACEPLUS #include #endif @@ -33,6 +35,41 @@ void Faceplus::init() { updateEnabled(); } +void Faceplus::setState(const glm::quat& headRotation, float estimatedEyePitch, float estimatedEyeYaw, + const QVector& blendshapeCoefficients) { + _headRotation = headRotation; + _estimatedEyePitch = estimatedEyePitch; + _estimatedEyeYaw = estimatedEyeYaw; + _blendshapeCoefficients = blendshapeCoefficients; + _active = true; +} + +void Faceplus::updateEnabled() { + setEnabled(Menu::getInstance()->isOptionChecked(MenuOption::Faceplus) && + !(Menu::getInstance()->isOptionChecked(MenuOption::Faceshift) && + Application::getInstance()->getFaceshift()->isConnectedOrConnecting())); +} + +void Faceplus::setEnabled(bool enabled) { + if (_enabled == enabled) { + return; + } + if ((_enabled = enabled)) { + _reader = new FaceplusReader(); + QThread* readerThread = new QThread(this); + _reader->moveToThread(readerThread); + readerThread->start(); + QMetaObject::invokeMethod(_reader, "init"); + + } else { + QThread* readerThread = _reader->thread(); + QMetaObject::invokeMethod(_reader, "shutdown"); + readerThread->wait(); + delete readerThread; + _active = false; + } +} + #ifdef HAVE_FACEPLUS static QMultiHash > createChannelNameMap() { QMultiHash > blendshapeMap; @@ -97,18 +134,76 @@ static const QMultiHash >& getChannelNameMap() { } #endif -void Faceplus::update() { +void FaceplusReader::init() { #ifdef HAVE_FACEPLUS - if (!_active) { + if (!faceplus_init("VGA")) { + qDebug() << "Failed to initialized Faceplus."; return; } - if (!(_active = faceplus_synchronous_track() && faceplus_current_output_vector(_outputVector.data()))) { + qDebug() << "Faceplus initialized."; + + int channelCount = faceplus_output_channels_count(); + _outputVector.resize(channelCount); + + int maxIndex = -1; + _channelIndexMap.clear(); + for (int i = 0; i < channelCount; i++) { + QByteArray name = faceplus_output_channel_name(i); + if (name == "Head_Joint::Rotation_X") { + _headRotationIndices[0] = i; + + } else if (name == "Head_Joint::Rotation_Y") { + _headRotationIndices[1] = i; + + } else if (name == "Head_Joint::Rotation_Z") { + _headRotationIndices[2] = i; + + } else if (name == "Left_Eye_Joint::Rotation_X") { + _leftEyeRotationIndices[0] = i; + + } else if (name == "Left_Eye_Joint::Rotation_Y") { + _leftEyeRotationIndices[1] = i; + + } else if (name == "Right_Eye_Joint::Rotation_X") { + _rightEyeRotationIndices[0] = i; + + } else if (name == "Right_Eye_Joint::Rotation_Y") { + _rightEyeRotationIndices[1] = i; + } + for (QMultiHash >::const_iterator it = getChannelNameMap().constFind(name); + it != getChannelNameMap().constEnd() && it.key() == name; it++) { + _channelIndexMap.insert(i, it.value()); + maxIndex = qMax(maxIndex, it.value().first); + } + } + _blendshapeCoefficients.resize(maxIndex + 1); + + QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection); +#endif +} + +void FaceplusReader::shutdown() { +#ifdef HAVE_FACEPLUS + if (faceplus_teardown()) { + qDebug() << "Faceplus torn down."; + } +#endif + deleteLater(); + thread()->quit(); +} + +void FaceplusReader::update() { +#ifdef HAVE_FACEPLUS + if (!(faceplus_synchronous_track() && faceplus_current_output_vector(_outputVector.data()))) { + QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection); return; } - _headRotation = glm::quat(glm::radians(glm::vec3(-_outputVector.at(_headRotationIndices[0]), + glm::quat headRotation(glm::radians(glm::vec3(-_outputVector.at(_headRotationIndices[0]), _outputVector.at(_headRotationIndices[1]), -_outputVector.at(_headRotationIndices[2])))); - _estimatedEyePitch = (_outputVector.at(_leftEyeRotationIndices[0]) + _outputVector.at(_rightEyeRotationIndices[0])) * -0.5f; - _estimatedEyeYaw = (_outputVector.at(_leftEyeRotationIndices[1]) + _outputVector.at(_rightEyeRotationIndices[1])) * 0.5f; + float estimatedEyePitch = (_outputVector.at(_leftEyeRotationIndices[0]) + + _outputVector.at(_rightEyeRotationIndices[0])) * -0.5f; + float estimatedEyeYaw = (_outputVector.at(_leftEyeRotationIndices[1]) + + _outputVector.at(_rightEyeRotationIndices[1])) * 0.5f; qFill(_blendshapeCoefficients.begin(), _blendshapeCoefficients.end(), 0.0f); for (int i = 0; i < _outputVector.size(); i++) { @@ -117,67 +212,11 @@ void Faceplus::update() { _blendshapeCoefficients[it.value().first] += _outputVector.at(i) * it.value().second; } } + + QMetaObject::invokeMethod(Application::getInstance()->getFaceplus(), "setState", Q_ARG(const glm::quat&, headRotation), + Q_ARG(float, estimatedEyePitch), Q_ARG(float, estimatedEyeYaw), Q_ARG(const QVector&, _blendshapeCoefficients)); + + QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection); #endif } -void Faceplus::reset() { -} - -void Faceplus::updateEnabled() { - setEnabled(Menu::getInstance()->isOptionChecked(MenuOption::Faceplus) && - !(Menu::getInstance()->isOptionChecked(MenuOption::Faceshift) && - Application::getInstance()->getFaceshift()->isConnectedOrConnecting())); -} - -void Faceplus::setEnabled(bool enabled) { -#ifdef HAVE_FACEPLUS - if (_enabled == enabled) { - return; - } - if ((_enabled = enabled)) { - if (faceplus_init("VGA")) { - qDebug() << "Faceplus initialized."; - _active = true; - - int channelCount = faceplus_output_channels_count(); - _outputVector.resize(channelCount); - - int maxIndex = -1; - _channelIndexMap.clear(); - for (int i = 0; i < channelCount; i++) { - QByteArray name = faceplus_output_channel_name(i); - if (name == "Head_Joint::Rotation_X") { - _headRotationIndices[0] = i; - - } else if (name == "Head_Joint::Rotation_Y") { - _headRotationIndices[1] = i; - - } else if (name == "Head_Joint::Rotation_Z") { - _headRotationIndices[2] = i; - - } else if (name == "Left_Eye_Joint::Rotation_X") { - _leftEyeRotationIndices[0] = i; - - } else if (name == "Left_Eye_Joint::Rotation_Y") { - _leftEyeRotationIndices[1] = i; - - } else if (name == "Right_Eye_Joint::Rotation_X") { - _rightEyeRotationIndices[0] = i; - - } else if (name == "Right_Eye_Joint::Rotation_Y") { - _rightEyeRotationIndices[1] = i; - } - for (QMultiHash >::const_iterator it = getChannelNameMap().constFind(name); - it != getChannelNameMap().constEnd() && it.key() == name; it++) { - _channelIndexMap.insert(i, it.value()); - maxIndex = qMax(maxIndex, it.value().first); - } - } - _blendshapeCoefficients.resize(maxIndex + 1); - } - } else if (faceplus_teardown()) { - qDebug() << "Faceplus torn down."; - _active = false; - } -#endif -} diff --git a/interface/src/devices/Faceplus.h b/interface/src/devices/Faceplus.h index 164cf4d031..5c5f26e64d 100644 --- a/interface/src/devices/Faceplus.h +++ b/interface/src/devices/Faceplus.h @@ -15,6 +15,8 @@ #include "FaceTracker.h" +class FaceplusReader; + /// Interface for Mixamo FacePlus. class Faceplus : public FaceTracker { Q_OBJECT @@ -28,9 +30,9 @@ public: bool isActive() const { return _active; } - void update(); - void reset(); - + Q_INVOKABLE void setState(const glm::quat& headRotation, float estimatedEyePitch, float estimatedEyeYaw, + const QVector& blendshapeCoefficients); + public slots: void updateEnabled(); @@ -42,12 +44,28 @@ private: bool _enabled; bool _active; + FaceplusReader* _reader; +}; + +/// The reader object that lives in its own thread. +class FaceplusReader : public QObject { + Q_OBJECT + +public: + + Q_INVOKABLE void init(); + Q_INVOKABLE void shutdown(); + Q_INVOKABLE void update(); + +private: + #ifdef HAVE_FACEPLUS QMultiHash > _channelIndexMap; QVector _outputVector; int _headRotationIndices[3]; int _leftEyeRotationIndices[2]; int _rightEyeRotationIndices[2]; + QVector _blendshapeIndices; #endif }; From 3f84f36d600b63588c9f1624a69a3f7be89eb246 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 15:00:57 -0700 Subject: [PATCH 275/595] add proper boilerplate to GnuTLS find module --- cmake/modules/FindGnuTLS.cmake | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/cmake/modules/FindGnuTLS.cmake b/cmake/modules/FindGnuTLS.cmake index f56a0db7d2..fcfd1909f8 100644 --- a/cmake/modules/FindGnuTLS.cmake +++ b/cmake/modules/FindGnuTLS.cmake @@ -1,3 +1,6 @@ +# +# FindFaceshift.cmake +# # Try to find the GnuTLS library # # You can provide a GNUTLS_ROOT_DIR which contains lib and include directories @@ -11,6 +14,9 @@ # Created on 3/31/2014 by Stephen Birarda # Copyright (c) 2014 High Fidelity # +# Distributed under the Apache License, Version 2.0. +# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +# if (GNUTLS_LIBRARY AND GNUTLS_INCLUDE_DIRS) # in cache already From 5a79079c090d7a004126e4ee5fc8beddff3c2dc6 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 15:03:56 -0700 Subject: [PATCH 276/595] fix boilerplates in new DTLS files --- domain-server/src/DTLSServerSession.cpp | 7 +++++-- domain-server/src/DTLSServerSession.h | 7 +++++-- libraries/shared/src/DTLSClientSession.cpp | 7 +++++-- libraries/shared/src/DTLSClientSession.h | 7 +++++-- libraries/shared/src/DTLSSession.cpp | 7 +++++-- libraries/shared/src/DTLSSession.h | 7 +++++-- libraries/shared/src/DummyDTLSSession.cpp | 7 +++++-- libraries/shared/src/DummyDTLSSession.h | 7 +++++-- 8 files changed, 40 insertions(+), 16 deletions(-) diff --git a/domain-server/src/DTLSServerSession.cpp b/domain-server/src/DTLSServerSession.cpp index 994b196357..a80c54ee02 100644 --- a/domain-server/src/DTLSServerSession.cpp +++ b/domain-server/src/DTLSServerSession.cpp @@ -1,9 +1,12 @@ // // DTLSServerSession.cpp -// hifi +// domain-server/src // // Created by Stephen Birarda on 2014-04-01. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "DTLSServerSession.h" diff --git a/domain-server/src/DTLSServerSession.h b/domain-server/src/DTLSServerSession.h index 86f642b104..cc94c9dc2e 100644 --- a/domain-server/src/DTLSServerSession.h +++ b/domain-server/src/DTLSServerSession.h @@ -1,9 +1,12 @@ // // DTLSServerSession.h -// hifi +// domain-server/src // // Created by Stephen Birarda on 2014-04-01. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__DTLSServerSession__ diff --git a/libraries/shared/src/DTLSClientSession.cpp b/libraries/shared/src/DTLSClientSession.cpp index ec8e121013..bd626dfcd8 100644 --- a/libraries/shared/src/DTLSClientSession.cpp +++ b/libraries/shared/src/DTLSClientSession.cpp @@ -1,9 +1,12 @@ // // DTLSClientSession.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2014-04-01. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "DomainHandler.h" diff --git a/libraries/shared/src/DTLSClientSession.h b/libraries/shared/src/DTLSClientSession.h index fe8dec49b9..8dece76a5c 100644 --- a/libraries/shared/src/DTLSClientSession.h +++ b/libraries/shared/src/DTLSClientSession.h @@ -1,9 +1,12 @@ // // DTLSClientSession.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2014-04-01. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__DTLSClientSession__ diff --git a/libraries/shared/src/DTLSSession.cpp b/libraries/shared/src/DTLSSession.cpp index 4685a05970..8e84c38edc 100644 --- a/libraries/shared/src/DTLSSession.cpp +++ b/libraries/shared/src/DTLSSession.cpp @@ -1,9 +1,12 @@ // // DTLSSession.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2014-04-01. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/DTLSSession.h b/libraries/shared/src/DTLSSession.h index 2d5a7098f1..f7849999ae 100644 --- a/libraries/shared/src/DTLSSession.h +++ b/libraries/shared/src/DTLSSession.h @@ -1,9 +1,12 @@ // // DTLSSession.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2014-04-01. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__DTLSSession__ diff --git a/libraries/shared/src/DummyDTLSSession.cpp b/libraries/shared/src/DummyDTLSSession.cpp index df7e82274c..96207477cf 100644 --- a/libraries/shared/src/DummyDTLSSession.cpp +++ b/libraries/shared/src/DummyDTLSSession.cpp @@ -1,9 +1,12 @@ // // DummyDTLSSession.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2014-04-04. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "DummyDTLSSession.h" diff --git a/libraries/shared/src/DummyDTLSSession.h b/libraries/shared/src/DummyDTLSSession.h index 394bb82ae5..336d473c63 100644 --- a/libraries/shared/src/DummyDTLSSession.h +++ b/libraries/shared/src/DummyDTLSSession.h @@ -1,9 +1,12 @@ // // DummyDTLSSession.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2014-04-04. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef __hifi__DummyDTLSSession__ From 3fe5af1505bde2c9ca8eff6d57b6854250b97af8 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 15:08:56 -0700 Subject: [PATCH 277/595] update boilerplate and include guards for other new files --- domain-server/src/DTLSServerSession.h | 6 +++--- libraries/shared/src/DTLSClientSession.h | 6 +++--- libraries/shared/src/DTLSSession.h | 6 +++--- libraries/shared/src/DomainHandler.cpp | 7 +++++-- libraries/shared/src/DomainHandler.h | 13 ++++++++----- libraries/shared/src/DummyDTLSSession.h | 6 +++--- libraries/shared/src/HifiConfigVariantMap.cpp | 7 +++++-- libraries/shared/src/HifiConfigVariantMap.h | 13 ++++++++----- libraries/shared/src/LimitedNodeList.cpp | 7 +++++-- libraries/shared/src/LimitedNodeList.h | 13 ++++++++----- 10 files changed, 51 insertions(+), 33 deletions(-) diff --git a/domain-server/src/DTLSServerSession.h b/domain-server/src/DTLSServerSession.h index cc94c9dc2e..5fdc602df7 100644 --- a/domain-server/src/DTLSServerSession.h +++ b/domain-server/src/DTLSServerSession.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__DTLSServerSession__ -#define __hifi__DTLSServerSession__ +#ifndef hifi_DTLSServerSession_h +#define hifi_DTLSServerSession_h #include @@ -21,4 +21,4 @@ public: DTLSServerSession(QUdpSocket& dtlsSocket, HifiSockAddr& destinationSocket); }; -#endif /* defined(__hifi__DTLSServerSession__) */ +#endif // hifi_DTLSServerSession_h diff --git a/libraries/shared/src/DTLSClientSession.h b/libraries/shared/src/DTLSClientSession.h index 8dece76a5c..fcd5a3b5e9 100644 --- a/libraries/shared/src/DTLSClientSession.h +++ b/libraries/shared/src/DTLSClientSession.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__DTLSClientSession__ -#define __hifi__DTLSClientSession__ +#ifndef hifi_DTLSClientSession_h +#define hifi_DTLSClientSession_h #include "DTLSSession.h" @@ -27,4 +27,4 @@ public: static bool _wasGloballyInitialized; }; -#endif /* defined(__hifi__DTLSClientSession__) */ +#endif // hifi_DTLSClientSession_h diff --git a/libraries/shared/src/DTLSSession.h b/libraries/shared/src/DTLSSession.h index f7849999ae..4b69f13c78 100644 --- a/libraries/shared/src/DTLSSession.h +++ b/libraries/shared/src/DTLSSession.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__DTLSSession__ -#define __hifi__DTLSSession__ +#ifndef hifi_DTLSSession_h +#define hifi_DTLSSession_h #include @@ -41,4 +41,4 @@ protected: bool _completedHandshake; }; -#endif /* defined(__hifi__DTLSSession__) */ +#endif // hifi_DTLSSession_h diff --git a/libraries/shared/src/DomainHandler.cpp b/libraries/shared/src/DomainHandler.cpp index 4773a368a4..85c452f01c 100644 --- a/libraries/shared/src/DomainHandler.cpp +++ b/libraries/shared/src/DomainHandler.cpp @@ -1,9 +1,12 @@ // // DomainHandler.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/18/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/DomainHandler.h b/libraries/shared/src/DomainHandler.h index 106eff67f1..f31e2a6817 100644 --- a/libraries/shared/src/DomainHandler.h +++ b/libraries/shared/src/DomainHandler.h @@ -1,13 +1,16 @@ // // DomainHandler.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/18/2014. -// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__DomainHandler__ -#define __hifi__DomainHandler__ +#ifndef hifi_DomainHandler_h +#define hifi_DomainHandler_h #include #include @@ -76,4 +79,4 @@ private: QTimer* _handshakeTimer; }; -#endif /* defined(__hifi__DomainHandler__) */ +#endif // hifi_DomainHandler_h diff --git a/libraries/shared/src/DummyDTLSSession.h b/libraries/shared/src/DummyDTLSSession.h index 336d473c63..e13686ac51 100644 --- a/libraries/shared/src/DummyDTLSSession.h +++ b/libraries/shared/src/DummyDTLSSession.h @@ -9,8 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__DummyDTLSSession__ -#define __hifi__DummyDTLSSession__ +#ifndef hifi_DummyDTLSSession_h +#define hifi_DummyDTLSSession_h #include @@ -31,4 +31,4 @@ protected: HifiSockAddr _destinationSocket; }; -#endif /* defined(__hifi__DummyDTLSSession__) */ +#endif // hifi_DummyDTLSSession_h diff --git a/libraries/shared/src/HifiConfigVariantMap.cpp b/libraries/shared/src/HifiConfigVariantMap.cpp index f68c64581b..d20f4276f1 100644 --- a/libraries/shared/src/HifiConfigVariantMap.cpp +++ b/libraries/shared/src/HifiConfigVariantMap.cpp @@ -1,9 +1,12 @@ // // HifiConfigVariantMap.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2014-04-08. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/HifiConfigVariantMap.h b/libraries/shared/src/HifiConfigVariantMap.h index c652278b0d..378aa749c5 100644 --- a/libraries/shared/src/HifiConfigVariantMap.h +++ b/libraries/shared/src/HifiConfigVariantMap.h @@ -1,13 +1,16 @@ // // HifiConfigVariantMap.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2014-04-08. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__HifiConfigVariantMap__ -#define __hifi__HifiConfigVariantMap__ +#ifndef hifi_HifiConfigVariantMap_h +#define hifi_HifiConfigVariantMap_h #include @@ -16,4 +19,4 @@ public: static QVariantMap mergeCLParametersWithJSONConfig(const QStringList& argumentList); }; -#endif /* defined(__hifi__HifiConfigVariantMap__) */ +#endif // hifi_HifiConfigVariantMap_h diff --git a/libraries/shared/src/LimitedNodeList.cpp b/libraries/shared/src/LimitedNodeList.cpp index e9fdaa493c..b4a65475d6 100644 --- a/libraries/shared/src/LimitedNodeList.cpp +++ b/libraries/shared/src/LimitedNodeList.cpp @@ -1,9 +1,12 @@ // // LimitedNodeList.cpp -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/15/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/libraries/shared/src/LimitedNodeList.h b/libraries/shared/src/LimitedNodeList.h index adbc94e8d2..d428805511 100644 --- a/libraries/shared/src/LimitedNodeList.h +++ b/libraries/shared/src/LimitedNodeList.h @@ -1,13 +1,16 @@ // // LimitedNodeList.h -// hifi +// libraries/shared/src // // Created by Stephen Birarda on 2/15/13. -// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __hifi__LimitedNodeList__ -#define __hifi__LimitedNodeList__ +#ifndef hifi_LimitedNodeList_h +#define hifi_LimitedNodeList_h #ifdef _WIN32 #include "Syssocket.h" @@ -132,4 +135,4 @@ protected: QElapsedTimer _packetStatTimer; }; -#endif /* defined(__hifi__LimitedNodeList__) */ +#endif // hifi_LimitedNodeList_h From 11d8d0596a62a403daae132820fb6ebe61941b29 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 15:15:43 -0700 Subject: [PATCH 278/595] fix ModelUploader header after move --- interface/src/ModelUploader.cpp | 2 +- interface/src/ModelUploader.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index 9a0c305bf7..9c4755e388 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -1,6 +1,6 @@ // // ModelUploader.cpp -// libraries/shared/src +// interface/src // // Created by Clément Brisset on 3/4/14. // Copyright 2014 High Fidelity, Inc. diff --git a/interface/src/ModelUploader.h b/interface/src/ModelUploader.h index bec75903af..ff22673cdd 100644 --- a/interface/src/ModelUploader.h +++ b/interface/src/ModelUploader.h @@ -1,6 +1,6 @@ // // ModelUploader.h -// libraries/shared/src +// interface/src // // Created by Clément Brisset on 3/4/14. // Copyright 2014 High Fidelity, Inc. From cbfaf9709efc948f591611e5e14112f0dc6448ce Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Wed, 9 Apr 2014 15:18:22 -0700 Subject: [PATCH 279/595] Faceplus fixes. --- interface/src/Application.h | 1 + interface/src/devices/Faceplus.cpp | 19 ++++++++++++------- interface/src/devices/Faceplus.h | 6 +++++- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/interface/src/Application.h b/interface/src/Application.h index 7182010050..d76bd38c5f 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -174,6 +174,7 @@ public: bool isMouseHidden() const { return _mouseHidden; } const glm::vec3& getMouseRayOrigin() const { return _mouseRayOrigin; } const glm::vec3& getMouseRayDirection() const { return _mouseRayDirection; } + Faceplus* getFaceplus() { return &_faceplus; } Faceshift* getFaceshift() { return &_faceshift; } Visage* getVisage() { return &_visage; } FaceTracker* getActiveFaceTracker(); diff --git a/interface/src/devices/Faceplus.cpp b/interface/src/devices/Faceplus.cpp index 34547c2a6a..62f39d3b91 100644 --- a/interface/src/devices/Faceplus.cpp +++ b/interface/src/devices/Faceplus.cpp @@ -16,6 +16,8 @@ #include "Faceplus.h" #include "renderer/FBXReader.h" +static int floatVectorMetaTypeId = qRegisterMetaType >(); + Faceplus::Faceplus() : _enabled(false), _active(false) { @@ -81,8 +83,8 @@ static QMultiHash > createChannelNameMap() { blendshapeMap.insert("...", QPair("Mix::BrowsIn_Right", 1.0f)); blendshapeMap.insert("...", QPair("Mix::BrowsOuterLower_Left", 1.0f)); blendshapeMap.insert("...", QPair("Mix::BrowsOuterLower_Right", 1.0f)); - blendshapeMap.insert("BrowsU_L", QPair("Mix::BrowsUp_Left", 5.0f)); - blendshapeMap.insert("BrowsU_R", QPair("Mix::BrowsUp_Right", 5.0f)); + blendshapeMap.insert("BrowsU_L", QPair("Mix::BrowsUp_Left", 10.0f)); + blendshapeMap.insert("BrowsU_R", QPair("Mix::BrowsUp_Right", 10.0f)); blendshapeMap.insert("EyeOpen_L", QPair("Mix::EyesWide_Left", 1.0f)); blendshapeMap.insert("EyeOpen_R", QPair("Mix::EyesWide_Right", 1.0f)); blendshapeMap.insert("MouthFrown_L", QPair("Mix::Frown_Left", 1.0f)); @@ -134,6 +136,14 @@ static const QMultiHash >& getChannelNameMap() { } #endif +FaceplusReader::~FaceplusReader() { +#ifdef HAVE_FACEPLUS + if (faceplus_teardown()) { + qDebug() << "Faceplus torn down."; + } +#endif +} + void FaceplusReader::init() { #ifdef HAVE_FACEPLUS if (!faceplus_init("VGA")) { @@ -183,11 +193,6 @@ void FaceplusReader::init() { } void FaceplusReader::shutdown() { -#ifdef HAVE_FACEPLUS - if (faceplus_teardown()) { - qDebug() << "Faceplus torn down."; - } -#endif deleteLater(); thread()->quit(); } diff --git a/interface/src/devices/Faceplus.h b/interface/src/devices/Faceplus.h index 5c5f26e64d..f90c3449bf 100644 --- a/interface/src/devices/Faceplus.h +++ b/interface/src/devices/Faceplus.h @@ -47,12 +47,16 @@ private: FaceplusReader* _reader; }; +Q_DECLARE_METATYPE(QVector) + /// The reader object that lives in its own thread. class FaceplusReader : public QObject { Q_OBJECT public: + virtual ~FaceplusReader(); + Q_INVOKABLE void init(); Q_INVOKABLE void shutdown(); Q_INVOKABLE void update(); @@ -65,7 +69,7 @@ private: int _headRotationIndices[3]; int _leftEyeRotationIndices[2]; int _rightEyeRotationIndices[2]; - QVector _blendshapeIndices; + QVector _blendshapeCoefficients; #endif }; From ead05c4d992481693daa49957bc83abd8eab214e Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Wed, 9 Apr 2014 15:22:53 -0700 Subject: [PATCH 280/595] Tab fixes. --- interface/src/Application.cpp | 2 +- interface/src/Application.h | 2 +- interface/src/devices/Faceplus.h | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 6e05167d6f..0d0ec96ce5 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1570,7 +1570,7 @@ void Application::init() { // initialize our face trackers after loading the menu settings _faceshift.init(); _faceplus.init(); - _visage.init(); + _visage.init(); // fire off an immediate domain-server check in now that settings are loaded NodeList::getInstance()->sendDomainServerCheckIn(); diff --git a/interface/src/Application.h b/interface/src/Application.h index d76bd38c5f..c6b38b1644 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -174,7 +174,7 @@ public: bool isMouseHidden() const { return _mouseHidden; } const glm::vec3& getMouseRayOrigin() const { return _mouseRayOrigin; } const glm::vec3& getMouseRayDirection() const { return _mouseRayDirection; } - Faceplus* getFaceplus() { return &_faceplus; } + Faceplus* getFaceplus() { return &_faceplus; } Faceshift* getFaceshift() { return &_faceshift; } Visage* getVisage() { return &_visage; } FaceTracker* getActiveFaceTracker(); diff --git a/interface/src/devices/Faceplus.h b/interface/src/devices/Faceplus.h index f90c3449bf..6cfdac2640 100644 --- a/interface/src/devices/Faceplus.h +++ b/interface/src/devices/Faceplus.h @@ -55,7 +55,7 @@ class FaceplusReader : public QObject { public: - virtual ~FaceplusReader(); + virtual ~FaceplusReader(); Q_INVOKABLE void init(); Q_INVOKABLE void shutdown(); From 3a93096093c2a706860b37b4bf24272af1310a1c Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 9 Apr 2014 15:31:26 -0700 Subject: [PATCH 281/595] fixing floats to be *.0f instead of *.f --- interface/src/avatar/MyAvatar.cpp | 152 +++++++++++++++--------------- 1 file changed, 76 insertions(+), 76 deletions(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 99fe020cb6..65a958dfb9 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -63,7 +63,7 @@ MyAvatar::MyAvatar() : _lookAtTargetAvatar(), _shouldRender(true), _billboardValid(false), - _oculusYawOffset(0.f) + _oculusYawOffset(0.0f) { for (int i = 0; i < MAX_DRIVE_KEYS; i++) { _driveKeys[i] = 0.0f; @@ -86,11 +86,11 @@ void MyAvatar::reset() { _skeletonModel.reset(); getHead()->reset(); getHand()->reset(); - _oculusYawOffset = 0.f; + _oculusYawOffset = 0.0f; - setVelocity(glm::vec3(0.f)); - setThrust(glm::vec3(0.f)); - setOrientation(glm::quat(glm::vec3(0.f))); + setVelocity(glm::vec3(0.0f)); + setThrust(glm::vec3(0.0f)); + setOrientation(glm::quat(glm::vec3(0.0f))); } void MyAvatar::setMoveTarget(const glm::vec3 moveTarget) { @@ -113,8 +113,8 @@ void MyAvatar::update(float deltaTime) { // TODO? resurrect headMouse stuff? //glm::vec3 headVelocity = faceshift->getHeadAngularVelocity(); //// sets how quickly head angular rotation moves the head mouse - //const float HEADMOUSE_FACESHIFT_YAW_SCALE = 40.f; - //const float HEADMOUSE_FACESHIFT_PITCH_SCALE = 30.f; + //const float HEADMOUSE_FACESHIFT_YAW_SCALE = 40.0f; + //const float HEADMOUSE_FACESHIFT_PITCH_SCALE = 30.0f; //_headMouseX -= headVelocity.y * HEADMOUSE_FACESHIFT_YAW_SCALE; //_headMouseY -= headVelocity.x * HEADMOUSE_FACESHIFT_PITCH_SCALE; // @@ -145,15 +145,15 @@ void MyAvatar::simulate(float deltaTime) { _elapsedTimeSinceCollision += deltaTime; const float VELOCITY_MOVEMENT_TIMER_THRESHOLD = 0.2f; if (glm::length(_velocity) < VELOCITY_MOVEMENT_TIMER_THRESHOLD) { - _elapsedTimeMoving = 0.f; + _elapsedTimeMoving = 0.0f; _elapsedTimeStopped += deltaTime; } else { - _elapsedTimeStopped = 0.f; + _elapsedTimeStopped = 0.0f; _elapsedTimeMoving += deltaTime; } if (_scale != _targetScale) { - float scale = (1.f - SMOOTHING_RATIO) * _scale + SMOOTHING_RATIO * _targetScale; + float scale = (1.0f - SMOOTHING_RATIO) * _scale + SMOOTHING_RATIO * _targetScale; setScale(scale); Application::getInstance()->getCamera()->setScale(scale); } @@ -181,19 +181,19 @@ void MyAvatar::simulate(float deltaTime) { // decay body rotation momentum const float BODY_SPIN_FRICTION = 7.5f; - float bodySpinMomentum = 1.f - BODY_SPIN_FRICTION * deltaTime; + float bodySpinMomentum = 1.0f - BODY_SPIN_FRICTION * deltaTime; if (bodySpinMomentum < 0.0f) { bodySpinMomentum = 0.0f; } _bodyPitchDelta *= bodySpinMomentum; _bodyYawDelta *= bodySpinMomentum; _bodyRollDelta *= bodySpinMomentum; float MINIMUM_ROTATION_RATE = 2.0f; - if (fabs(_bodyYawDelta) < MINIMUM_ROTATION_RATE) { _bodyYawDelta = 0.f; } - if (fabs(_bodyRollDelta) < MINIMUM_ROTATION_RATE) { _bodyRollDelta = 0.f; } - if (fabs(_bodyPitchDelta) < MINIMUM_ROTATION_RATE) { _bodyPitchDelta = 0.f; } + if (fabs(_bodyYawDelta) < MINIMUM_ROTATION_RATE) { _bodyYawDelta = 0.0f; } + if (fabs(_bodyRollDelta) < MINIMUM_ROTATION_RATE) { _bodyRollDelta = 0.0f; } + if (fabs(_bodyPitchDelta) < MINIMUM_ROTATION_RATE) { _bodyPitchDelta = 0.0f; } const float MAX_STATIC_FRICTION_SPEED = 0.5f; - const float STATIC_FRICTION_STRENGTH = _scale * 20.f; + const float STATIC_FRICTION_STRENGTH = _scale * 20.0f; applyStaticFriction(deltaTime, _velocity, MAX_STATIC_FRICTION_SPEED, STATIC_FRICTION_STRENGTH); // Damp avatar velocity @@ -201,11 +201,11 @@ void MyAvatar::simulate(float deltaTime) { const float SPEED_BRAKE_POWER = _scale * 10.0f; const float SQUARED_DAMPING_STRENGTH = 0.007f; - const float SLOW_NEAR_RADIUS = 5.f; + const float SLOW_NEAR_RADIUS = 5.0f; float linearDamping = LINEAR_DAMPING_STRENGTH; - const float NEAR_AVATAR_DAMPING_FACTOR = 50.f; + const float NEAR_AVATAR_DAMPING_FACTOR = 50.0f; if (_distanceToNearestAvatar < _scale * SLOW_NEAR_RADIUS) { - linearDamping *= 1.f + NEAR_AVATAR_DAMPING_FACTOR * + linearDamping *= 1.0f + NEAR_AVATAR_DAMPING_FACTOR * ((SLOW_NEAR_RADIUS - _distanceToNearestAvatar) / SLOW_NEAR_RADIUS); } if (_speedBrakes) { @@ -224,34 +224,34 @@ void MyAvatar::simulate(float deltaTime) { // yaw from the body and yaw the body if necessary. yaw *= DEGREES_PER_RADIAN; float bodyToHeadYaw = yaw - _oculusYawOffset; - const float MAX_NECK_YAW = 85.f; // degrees - if ((fabs(bodyToHeadYaw) > 2.f * MAX_NECK_YAW) && (yaw * _oculusYawOffset < 0.f)) { + const float MAX_NECK_YAW = 85.0f; // degrees + if ((fabs(bodyToHeadYaw) > 2.0f * MAX_NECK_YAW) && (yaw * _oculusYawOffset < 0.0f)) { // We've wrapped around the range for yaw so adjust // the measured yaw to be relative to _oculusYawOffset. - if (yaw > 0.f) { - yaw -= 360.f; + if (yaw > 0.0f) { + yaw -= 360.0f; } else { - yaw += 360.f; + yaw += 360.0f; } bodyToHeadYaw = yaw - _oculusYawOffset; } float delta = fabs(bodyToHeadYaw) - MAX_NECK_YAW; - if (delta > 0.f) { + if (delta > 0.0f) { yaw = MAX_NECK_YAW; - if (bodyToHeadYaw < 0.f) { - delta *= -1.f; + if (bodyToHeadYaw < 0.0f) { + delta *= -1.0f; bodyToHeadYaw = -MAX_NECK_YAW; } else { bodyToHeadYaw = MAX_NECK_YAW; } // constrain _oculusYawOffset to be within range [-180,180] - _oculusYawOffset = fmod((_oculusYawOffset + delta) + 180.f, 360.f) - 180.f; + _oculusYawOffset = fmod((_oculusYawOffset + delta) + 180.0f, 360.0f) - 180.0f; // We must adjust the body orientation using a delta rotation (rather than // doing yaw math) because the body's yaw ranges are not the same // as what the Oculus API provides. - glm::vec3 UP_AXIS = glm::vec3(0.f, 1.f, 0.f); + glm::vec3 UP_AXIS = glm::vec3(0.0f, 1.0f, 0.0f); glm::quat bodyCorrection = glm::angleAxis(glm::radians(delta), UP_AXIS); orientation = orientation * bodyCorrection; } @@ -280,7 +280,7 @@ void MyAvatar::simulate(float deltaTime) { // If a move target is set, update position explicitly const float MOVE_FINISHED_TOLERANCE = 0.1f; - const float MOVE_SPEED_FACTOR = 2.f; + const float MOVE_SPEED_FACTOR = 2.0f; const int MOVE_TARGET_MAX_STEPS = 250; if ((glm::length(_moveTarget) > EPSILON) && (_moveTargetStepCounter < MOVE_TARGET_MAX_STEPS)) { if (glm::length(_position - _moveTarget) > MOVE_FINISHED_TOLERANCE) { @@ -320,7 +320,7 @@ void MyAvatar::simulate(float deltaTime) { head->simulate(deltaTime, true); // Zero thrust out now that we've added it to velocity in this frame - _thrust = glm::vec3(0.f); + _thrust = glm::vec3(0.0f); // now that we're done stepping the avatar forward in time, compute new collisions if (_collisionFlags != 0) { @@ -328,7 +328,7 @@ void MyAvatar::simulate(float deltaTime) { float radius = getSkeletonHeight() * COLLISION_RADIUS_SCALE; if (myCamera->getMode() == CAMERA_MODE_FIRST_PERSON && !OculusManager::isConnected()) { - radius = myCamera->getAspectRatio() * (myCamera->getNearClip() / cos(myCamera->getFieldOfView() / 2.f)); + radius = myCamera->getAspectRatio() * (myCamera->getNearClip() / cos(myCamera->getFieldOfView() / 2.0f)); radius *= COLLISION_RADIUS_SCALAR; } @@ -370,11 +370,11 @@ void MyAvatar::updateFromGyros(float deltaTime) { // Rotate the body if the head is turned beyond the screen if (Menu::getInstance()->isOptionChecked(MenuOption::TurnWithHead)) { const float TRACKER_YAW_TURN_SENSITIVITY = 0.5f; - const float TRACKER_MIN_YAW_TURN = 15.f; - const float TRACKER_MAX_YAW_TURN = 50.f; + const float TRACKER_MIN_YAW_TURN = 15.0f; + const float TRACKER_MAX_YAW_TURN = 50.0f; if ( (fabs(estimatedRotation.y) > TRACKER_MIN_YAW_TURN) && (fabs(estimatedRotation.y) < TRACKER_MAX_YAW_TURN) ) { - if (estimatedRotation.y > 0.f) { + if (estimatedRotation.y > 0.0f) { _bodyYawDelta += (estimatedRotation.y - TRACKER_MIN_YAW_TURN) * TRACKER_YAW_TURN_SENSITIVITY; } else { _bodyYawDelta += (estimatedRotation.y + TRACKER_MIN_YAW_TURN) * TRACKER_YAW_TURN_SENSITIVITY; @@ -412,20 +412,20 @@ void MyAvatar::moveWithLean() { float leanSideways = head->getLeanSideways(); // Degrees of 'dead zone' when leaning, and amount of acceleration to apply to lean angle - const float LEAN_FWD_DEAD_ZONE = 15.f; - const float LEAN_SIDEWAYS_DEAD_ZONE = 10.f; - const float LEAN_FWD_THRUST_SCALE = 4.f; - const float LEAN_SIDEWAYS_THRUST_SCALE = 3.f; + const float LEAN_FWD_DEAD_ZONE = 15.0f; + const float LEAN_SIDEWAYS_DEAD_ZONE = 10.0f; + const float LEAN_FWD_THRUST_SCALE = 4.0f; + const float LEAN_SIDEWAYS_THRUST_SCALE = 3.0f; if (fabs(leanForward) > LEAN_FWD_DEAD_ZONE) { - if (leanForward > 0.f) { + if (leanForward > 0.0f) { addThrust(front * -(leanForward - LEAN_FWD_DEAD_ZONE) * LEAN_FWD_THRUST_SCALE); } else { addThrust(front * -(leanForward + LEAN_FWD_DEAD_ZONE) * LEAN_FWD_THRUST_SCALE); } } if (fabs(leanSideways) > LEAN_SIDEWAYS_DEAD_ZONE) { - if (leanSideways > 0.f) { + if (leanSideways > 0.0f) { addThrust(right * -(leanSideways - LEAN_SIDEWAYS_DEAD_ZONE) * LEAN_SIDEWAYS_THRUST_SCALE); } else { addThrust(right * -(leanSideways + LEAN_SIDEWAYS_DEAD_ZONE) * LEAN_SIDEWAYS_THRUST_SCALE); @@ -472,7 +472,7 @@ void MyAvatar::renderHeadMouse() const { // TODO? resurrect headMouse stuff? /* // Display small target box at center or head mouse target that can also be used to measure LOD - glColor3f(1.f, 1.f, 1.f); + glColor3f(1.0f, 1.0f, 1.0f); glDisable(GL_LINE_SMOOTH); const int PIXEL_BOX = 16; glBegin(GL_LINES); @@ -482,7 +482,7 @@ void MyAvatar::renderHeadMouse() const { glVertex2f(_headMouseX, _headMouseY + PIXEL_BOX/2); glEnd(); glEnable(GL_LINE_SMOOTH); - glColor3f(1.f, 0.f, 0.f); + glColor3f(1.0f, 0.0f, 0.0f); glPointSize(3.0f); glDisable(GL_POINT_SMOOTH); glBegin(GL_POINTS); @@ -494,7 +494,7 @@ void MyAvatar::renderHeadMouse() const { int eyeTargetX = (_glWidget->width() / 2) - _faceshift.getEstimatedEyeYaw() * EYE_TARGET_PIXELS_PER_DEGREE; int eyeTargetY = (_glWidget->height() / 2) - _faceshift.getEstimatedEyePitch() * EYE_TARGET_PIXELS_PER_DEGREE; - glColor3f(0.f, 1.f, 1.f); + glColor3f(0.0f, 1.0f, 1.0f); glDisable(GL_LINE_SMOOTH); glBegin(GL_LINES); glVertex2f(eyeTargetX - PIXEL_BOX/2, eyeTargetY); @@ -673,11 +673,11 @@ void MyAvatar::updateThrust(float deltaTime) { glm::vec3 up = orientation * IDENTITY_UP; const float THRUST_MAG_UP = 800.0f; - const float THRUST_MAG_DOWN = 300.f; - const float THRUST_MAG_FWD = 500.f; - const float THRUST_MAG_BACK = 300.f; - const float THRUST_MAG_LATERAL = 250.f; - const float THRUST_JUMP = 120.f; + const float THRUST_MAG_DOWN = 300.0f; + const float THRUST_MAG_FWD = 500.0f; + const float THRUST_MAG_BACK = 300.0f; + const float THRUST_MAG_LATERAL = 250.0f; + const float THRUST_JUMP = 120.0f; // Add Thrusts from keyboard _thrust += _driveKeys[FWD] * _scale * THRUST_MAG_FWD * _thrustMultiplier * deltaTime * front; @@ -688,25 +688,25 @@ void MyAvatar::updateThrust(float deltaTime) { _thrust -= _driveKeys[DOWN] * _scale * THRUST_MAG_DOWN * _thrustMultiplier * deltaTime * up; // attenuate thrust when in penetration - if (glm::dot(_thrust, _lastBodyPenetration) > 0.f) { + if (glm::dot(_thrust, _lastBodyPenetration) > 0.0f) { const float MAX_BODY_PENETRATION_DEPTH = 0.6f * _skeletonModel.getBoundingShapeRadius(); - float penetrationFactor = glm::min(1.f, glm::length(_lastBodyPenetration) / MAX_BODY_PENETRATION_DEPTH); + float penetrationFactor = glm::min(1.0f, glm::length(_lastBodyPenetration) / MAX_BODY_PENETRATION_DEPTH); glm::vec3 penetrationDirection = glm::normalize(_lastBodyPenetration); // attenuate parallel component glm::vec3 parallelThrust = glm::dot(_thrust, penetrationDirection) * penetrationDirection; // attenuate perpendicular component (friction) glm::vec3 perpendicularThrust = _thrust - parallelThrust; // recombine to get the final thrust - _thrust = (1.f - penetrationFactor) * parallelThrust + (1.f - penetrationFactor * penetrationFactor) * perpendicularThrust; + _thrust = (1.0f - penetrationFactor) * parallelThrust + (1.0f - penetrationFactor * penetrationFactor) * perpendicularThrust; // attenuate the growth of _thrustMultiplier when in penetration // otherwise the avatar will eventually be able to tunnel through the obstacle - _thrustMultiplier *= (1.f - penetrationFactor * penetrationFactor); - } else if (_thrustMultiplier < 1.f) { + _thrustMultiplier *= (1.0f - penetrationFactor * penetrationFactor); + } else if (_thrustMultiplier < 1.0f) { // rapid healing of attenuated thrustMultiplier after penetration event - _thrustMultiplier = 1.f; + _thrustMultiplier = 1.0f; } - _lastBodyPenetration = glm::vec3(0.f); + _lastBodyPenetration = glm::vec3(0.0f); _bodyYawDelta -= _driveKeys[ROT_RIGHT] * YAW_SPEED * deltaTime; _bodyYawDelta += _driveKeys[ROT_LEFT] * YAW_SPEED * deltaTime; @@ -716,12 +716,12 @@ void MyAvatar::updateThrust(float deltaTime) { if (_driveKeys[FWD] || _driveKeys[BACK] || _driveKeys[RIGHT] || _driveKeys[LEFT] || _driveKeys[UP] || _driveKeys[DOWN]) { const float THRUST_INCREASE_RATE = 1.05f; const float MAX_THRUST_MULTIPLIER = 75.0f; - _thrustMultiplier *= 1.f + deltaTime * THRUST_INCREASE_RATE; + _thrustMultiplier *= 1.0f + deltaTime * THRUST_INCREASE_RATE; if (_thrustMultiplier > MAX_THRUST_MULTIPLIER) { _thrustMultiplier = MAX_THRUST_MULTIPLIER; } } else { - _thrustMultiplier = 1.f; + _thrustMultiplier = 1.0f; } // Add one time jumping force if requested @@ -826,11 +826,11 @@ void MyAvatar::applyHardCollision(const glm::vec3& penetration, float elasticity if (penetrationLength > EPSILON) { _elapsedTimeSinceCollision = 0.0f; glm::vec3 direction = penetration / penetrationLength; - _velocity -= glm::dot(_velocity, direction) * direction * (1.f + elasticity); - _velocity *= glm::clamp(1.f - damping, 0.0f, 1.0f); - if ((glm::length(_velocity) < HALTING_VELOCITY) && (glm::length(_thrust) == 0.f)) { + _velocity -= glm::dot(_velocity, direction) * direction * (1.0f + elasticity); + _velocity *= glm::clamp(1.0f - damping, 0.0f, 1.0f); + if ((glm::length(_velocity) < HALTING_VELOCITY) && (glm::length(_thrust) == 0.0f)) { // If moving really slowly after a collision, and not applying forces, stop altogether - _velocity *= 0.f; + _velocity *= 0.0f; } } } @@ -838,7 +838,7 @@ void MyAvatar::applyHardCollision(const glm::vec3& penetration, float elasticity void MyAvatar::updateCollisionSound(const glm::vec3 &penetration, float deltaTime, float frequency) { // consider whether to have the collision make a sound const float AUDIBLE_COLLISION_THRESHOLD = 0.02f; - const float COLLISION_LOUDNESS = 1.f; + const float COLLISION_LOUDNESS = 1.0f; const float DURATION_SCALING = 0.004f; const float NOISE_SCALING = 0.1f; glm::vec3 velocity = _velocity; @@ -858,10 +858,10 @@ void MyAvatar::updateCollisionSound(const glm::vec3 &penetration, float deltaTim // Noise is a function of the angle of collision // Duration of the sound is a function of both base frequency and velocity of impact Application::getInstance()->getAudio()->startCollisionSound( - std::min(COLLISION_LOUDNESS * velocityTowardCollision, 1.f), - frequency * (1.f + velocityTangentToCollision / velocityTowardCollision), - std::min(velocityTangentToCollision / velocityTowardCollision * NOISE_SCALING, 1.f), - 1.f - DURATION_SCALING * powf(frequency, 0.5f) / velocityTowardCollision, true); + std::min(COLLISION_LOUDNESS * velocityTowardCollision, 1.0f), + frequency * (1.0f + velocityTangentToCollision / velocityTowardCollision), + std::min(velocityTangentToCollision / velocityTowardCollision * NOISE_SCALING, 1.0f), + 1.0f - DURATION_SCALING * powf(frequency, 0.5f) / velocityTowardCollision, true); } } @@ -874,8 +874,8 @@ bool findAvatarAvatarPenetration(const glm::vec3 positionA, float radiusA, float float halfHeights = 0.5 * (heightA + heightB); if (yDistance < halfHeights) { // cylinders collide - if (xzDistance > 0.f) { - positionBA.y = 0.f; + if (xzDistance > 0.0f) { + positionBA.y = 0.0f; // note, penetration should point from A into B penetration = positionBA * ((radiusA + radiusB - xzDistance) / xzDistance); return true; @@ -885,7 +885,7 @@ bool findAvatarAvatarPenetration(const glm::vec3 positionA, float radiusA, float } } else if (yDistance < halfHeights + radiusA + radiusB) { // caps collide - if (positionBA.y < 0.f) { + if (positionBA.y < 0.0f) { // A is above B positionBA.y += halfHeights; float BA = glm::length(positionBA); @@ -944,7 +944,7 @@ void MyAvatar::updateCollisionWithAvatars(float deltaTime) { ShapeCollider::shapeShape(myShape, theirShape, bodyCollisions); } } - glm::vec3 totalPenetration(0.f); + glm::vec3 totalPenetration(0.0f); for (int j = 0; j < bodyCollisions.size(); ++j) { CollisionInfo* collision = bodyCollisions.getCollision(j); totalPenetration = addPenetrations(totalPenetration, collision->_penetration); @@ -1108,15 +1108,15 @@ void MyAvatar::goHome() { } void MyAvatar::increaseSize() { - if ((1.f + SCALING_RATIO) * _targetScale < MAX_AVATAR_SCALE) { - _targetScale *= (1.f + SCALING_RATIO); + if ((1.0f + SCALING_RATIO) * _targetScale < MAX_AVATAR_SCALE) { + _targetScale *= (1.0f + SCALING_RATIO); qDebug("Changed scale to %f", _targetScale); } } void MyAvatar::decreaseSize() { - if (MIN_AVATAR_SCALE < (1.f - SCALING_RATIO) * _targetScale) { - _targetScale *= (1.f - SCALING_RATIO); + if (MIN_AVATAR_SCALE < (1.0f - SCALING_RATIO) * _targetScale) { + _targetScale *= (1.0f - SCALING_RATIO); qDebug("Changed scale to %f", _targetScale); } } @@ -1192,8 +1192,8 @@ void MyAvatar::applyCollision(const glm::vec3& contactPoint, const glm::vec3& pe if (leverLength > EPSILON) { // compute lean perturbation angles glm::quat bodyRotation = getOrientation(); - glm::vec3 xAxis = bodyRotation * glm::vec3(1.f, 0.f, 0.f); - glm::vec3 zAxis = bodyRotation * glm::vec3(0.f, 0.f, 1.f); + glm::vec3 xAxis = bodyRotation * glm::vec3(1.0f, 0.0f, 0.0f); + glm::vec3 zAxis = bodyRotation * glm::vec3(0.0f, 0.0f, 1.0f); leverAxis = leverAxis / leverLength; glm::vec3 effectivePenetration = penetration - glm::dot(penetration, leverAxis) * leverAxis; From f0dfb7fc38cc05cc1d6e32f702353cd1ea309c5c Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Wed, 9 Apr 2014 15:38:54 -0700 Subject: [PATCH 282/595] Updated headers to match the new standard. --- interface/src/devices/FaceTracker.cpp | 9 ++++++--- interface/src/devices/FaceTracker.h | 15 +++++++++------ interface/src/devices/Faceplus.cpp | 9 ++++++--- interface/src/devices/Faceplus.h | 15 +++++++++------ 4 files changed, 30 insertions(+), 18 deletions(-) diff --git a/interface/src/devices/FaceTracker.cpp b/interface/src/devices/FaceTracker.cpp index 45f789fbfe..52fe04de77 100644 --- a/interface/src/devices/FaceTracker.cpp +++ b/interface/src/devices/FaceTracker.cpp @@ -1,9 +1,12 @@ // // FaceTracker.cpp -// interface +// interface/src/devices // -// Created by Andrzej Kapolka on 4/8/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrzej Kapolka on 4/9/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "FaceTracker.h" diff --git a/interface/src/devices/FaceTracker.h b/interface/src/devices/FaceTracker.h index 659defe591..459f38cafc 100644 --- a/interface/src/devices/FaceTracker.h +++ b/interface/src/devices/FaceTracker.h @@ -1,13 +1,16 @@ // // FaceTracker.h -// interface +// interface/src/devices // -// Created by Andrzej Kapolka on 4/8/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrzej Kapolka on 4/9/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__FaceTracker__ -#define __interface__FaceTracker__ +#ifndef hifi_FaceTracker_h +#define hifi_FaceTracker_h #include #include @@ -40,4 +43,4 @@ protected: QVector _blendshapeCoefficients; }; -#endif /* defined(__interface__FaceTracker__) */ +#endif // hifi_FaceTracker_h diff --git a/interface/src/devices/Faceplus.cpp b/interface/src/devices/Faceplus.cpp index 62f39d3b91..f7f2f1f1bd 100644 --- a/interface/src/devices/Faceplus.cpp +++ b/interface/src/devices/Faceplus.cpp @@ -1,9 +1,12 @@ // // Faceplus.cpp -// interface +// interface/src/devices // -// Created by Andrzej Kapolka on 4/8/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrzej Kapolka on 4/9/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include diff --git a/interface/src/devices/Faceplus.h b/interface/src/devices/Faceplus.h index 6cfdac2640..2b9219f3fd 100644 --- a/interface/src/devices/Faceplus.h +++ b/interface/src/devices/Faceplus.h @@ -1,13 +1,16 @@ // // Faceplus.h -// interface +// interface/src/devices // -// Created by Andrzej Kapolka on 4/8/14. -// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// Created by Andrzej Kapolka on 4/9/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __interface__Faceplus__ -#define __interface__Faceplus__ +#ifndef hifi_Faceplus_h +#define hifi_Faceplus_h #include #include @@ -73,4 +76,4 @@ private: #endif }; -#endif /* defined(__interface__Faceplus__) */ +#endif // hifi_Faceplus_h From e33da2a74198b40c426a0fb06a7b9bd21aa64d49 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 9 Apr 2014 17:08:50 -0700 Subject: [PATCH 283/595] Some QSettings cleanup + persistant script location --- interface/src/Application.cpp | 102 +++++++++++++++++++--------------- interface/src/Application.h | 2 + 2 files changed, 60 insertions(+), 44 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 331ba51643..acd4e07c6a 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -338,7 +338,8 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : // clear the scripts, and set out script to our default scripts clearScriptsBeforeRunning(); loadScript("http://public.highfidelity.io/scripts/defaultScripts.js"); - + + QMutexLocker locker(&_settingsMutex); _settings->setValue("firstRun",QVariant(false)); } else { // do this as late as possible so that all required subsystems are inialized @@ -352,16 +353,12 @@ Application::~Application() { // make sure we don't call the idle timer any more delete idleTimer; - - Menu::getInstance()->saveSettings(); - _rearMirrorTools->saveSettings(_settings); - + _sharedVoxelSystem.changeTree(new VoxelTree); - if (_voxelImporter) { - _voxelImporter->saveSettings(_settings); - delete _voxelImporter; - } - _settings->sync(); + + saveSettings(); + + delete _voxelImporter; // let the avatar mixer know we're out MyAvatar::sendKillAvatar(); @@ -395,35 +392,45 @@ Application::~Application() { AccountManager::getInstance().destroy(); } +void Application::saveSettings() { + Menu::getInstance()->saveSettings(); + _rearMirrorTools->saveSettings(_settings); + + if (_voxelImporter) { + _voxelImporter->saveSettings(_settings); + } + _settings->sync(); +} + + void Application::restoreSizeAndPosition() { - QSettings* settings = new QSettings(this); QRect available = desktop()->availableGeometry(); - settings->beginGroup("Window"); + QMutexLocker locker(&_settingsMutex); + _settings->beginGroup("Window"); - int x = (int)loadSetting(settings, "x", 0); - int y = (int)loadSetting(settings, "y", 0); + int x = (int)loadSetting(_settings, "x", 0); + int y = (int)loadSetting(_settings, "y", 0); _window->move(x, y); - int width = (int)loadSetting(settings, "width", available.width()); - int height = (int)loadSetting(settings, "height", available.height()); + int width = (int)loadSetting(_settings, "width", available.width()); + int height = (int)loadSetting(_settings, "height", available.height()); _window->resize(width, height); - settings->endGroup(); + _settings->endGroup(); } void Application::storeSizeAndPosition() { - QSettings* settings = new QSettings(this); + QMutexLocker locker(&_settingsMutex); + _settings->beginGroup("Window"); - settings->beginGroup("Window"); + _settings->setValue("width", _window->rect().width()); + _settings->setValue("height", _window->rect().height()); - settings->setValue("width", _window->rect().width()); - settings->setValue("height", _window->rect().height()); + _settings->setValue("x", _window->pos().x()); + _settings->setValue("y", _window->pos().y()); - settings->setValue("x", _window->pos().x()); - settings->setValue("y", _window->pos().y()); - - settings->endGroup(); + _settings->endGroup(); } void Application::initializeGL() { @@ -3177,35 +3184,37 @@ void Application::packetSent(quint64 length) { void Application::loadScripts() { // loads all saved scripts - QSettings* settings = new QSettings(this); - int size = settings->beginReadArray("Settings"); - + + lockSettings(); + int size = _settings->beginReadArray("Settings"); for (int i = 0; i < size; ++i){ - settings->setArrayIndex(i); - QString string = settings->value("script").toString(); - loadScript(string); + _settings->setArrayIndex(i); + QString string = _settings->value("script").toString(); + unlockSettings(); + if (!string.isEmpty()) { + loadScript(string); + } } - - settings->endArray(); + + QMutexLocker locker(&_settingsMutex); + _settings->endArray(); } void Application::clearScriptsBeforeRunning() { // clears all scripts from the settings - QSettings* settings = new QSettings(this); - settings->beginWriteArray("Settings"); - settings->endArray(); + QMutexLocker locker(&_settingsMutex); + _settings->remove("Settings"); } void Application::saveScripts() { // saves all current running scripts - QSettings* settings = new QSettings(this); - settings->beginWriteArray("Settings"); + QMutexLocker locker(&_settingsMutex); + _settings->beginWriteArray("Settings"); for (int i = 0; i < getRunningScripts().size(); ++i){ - settings->setArrayIndex(i); - settings->setValue("script", getRunningScripts().at(i)); + _settings->setArrayIndex(i); + _settings->setValue("script", getRunningScripts().at(i)); } - - settings->endArray(); + _settings->endArray(); } void Application::stopAllScripts() { @@ -3346,7 +3355,10 @@ void Application::loadDialog() { if (_previousScriptLocation.isEmpty()) { QString desktopLocation = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); +// Temporary fix to Qt bug: http://stackoverflow.com/questions/16194475 +#ifdef __APPLE__ suggestedName = desktopLocation.append("/script.js"); +#endif } else { suggestedName = _previousScriptLocation; } @@ -3355,9 +3367,11 @@ void Application::loadDialog() { tr("JavaScript Files (*.js)")); if (!fileNameString.isEmpty()) { _previousScriptLocation = fileNameString; + QMutexLocker locker(&_settingsMutex); + _settings->setValue("LastScriptLocation", _previousScriptLocation); + + loadScript(fileNameString); } - - loadScript(fileNameString); } void Application::loadScriptURLDialog() { diff --git a/interface/src/Application.h b/interface/src/Application.h index 7c1cb9cab1..c1c2b9bf01 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -182,6 +182,8 @@ public: /// if you need to access the application settings, use lockSettings()/unlockSettings() QSettings* lockSettings() { _settingsMutex.lock(); return _settings; } void unlockSettings() { _settingsMutex.unlock(); } + + void saveSettings(); QMainWindow* getWindow() { return _window; } NodeToOctreeSceneStats* getOcteeSceneStats() { return &_octreeServerSceneStats; } From cf47418d5883b4f54cf92b568ea10b92ccb7aeaf Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 17:16:29 -0700 Subject: [PATCH 284/595] remove the audio scope --- interface/src/Application.cpp | 15 +-- interface/src/Application.h | 1 - interface/src/Audio.cpp | 14 +-- interface/src/Audio.h | 6 +- interface/src/Menu.cpp | 1 - interface/src/Menu.h | 1 - interface/src/ui/Oscilloscope.cpp | 192 ------------------------------ interface/src/ui/Oscilloscope.h | 84 ------------- 8 files changed, 3 insertions(+), 311 deletions(-) delete mode 100644 interface/src/ui/Oscilloscope.cpp delete mode 100644 interface/src/ui/Oscilloscope.h diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 6005ae085e..85efdcc2b4 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -150,7 +150,6 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : _viewFrustum(), _lastQueriedViewFrustum(), _lastQueriedTime(usecTimestampNow()), - _audioScope(256, 200, true), _mirrorViewRect(QRect(MIRROR_VIEW_LEFT_PADDING, MIRROR_VIEW_TOP_PADDING, MIRROR_VIEW_WIDTH, MIRROR_VIEW_HEIGHT)), _mouseX(0), _mouseY(0), @@ -161,7 +160,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : _touchAvgY(0.0f), _isTouchPressed(false), _mousePressed(false), - _audio(&_audioScope, STARTUP_JITTER_SAMPLES), + _audio(STARTUP_JITTER_SAMPLES), _enableProcessVoxelsThread(true), _voxelProcessor(), _voxelHideShowThread(&_voxels), @@ -744,9 +743,6 @@ void Application::keyPressEvent(QKeyEvent* event) { case Qt::Key_Period: Menu::getInstance()->handleViewFrustumOffsetKeyModifier(event->key()); break; - case Qt::Key_Apostrophe: - _audioScope.inputPaused = !_audioScope.inputPaused; - break; case Qt::Key_L: if (isShifted) { Menu::getInstance()->triggerOption(MenuOption::LodTools); @@ -2509,15 +2505,6 @@ void Application::displayOverlay() { } } - // Audio Scope - const int AUDIO_SCOPE_Y_OFFSET = 135; - if (Menu::getInstance()->isOptionChecked(MenuOption::Stats)) { - if (Menu::getInstance()->isOptionChecked(MenuOption::Oscilloscope)) { - int oscilloscopeTop = _glWidget->height() - AUDIO_SCOPE_Y_OFFSET; - _audioScope.render(MIRROR_VIEW_LEFT_PADDING, oscilloscopeTop); - } - } - // Audio VU Meter and Mute Icon const int MUTE_ICON_SIZE = 24; const int AUDIO_METER_INSET = 2; diff --git a/interface/src/Application.h b/interface/src/Application.h index 61c2a15f95..6238d09ded 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -407,7 +407,6 @@ private: ViewFrustum _shadowViewFrustum; quint64 _lastQueriedTime; - Oscilloscope _audioScope; float _trailingAudioLoudness; OctreeQuery _octreeQuery; // NodeData derived class for querying voxels from voxel server diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index a98d276acc..5dcd54050c 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -50,7 +50,7 @@ static const int NUMBER_OF_NOISE_SAMPLE_FRAMES = 300; // Mute icon configration static const int MUTE_ICON_SIZE = 24; -Audio::Audio(Oscilloscope* scope, int16_t initialJitterBufferSamples, QObject* parent) : +Audio::Audio(int16_t initialJitterBufferSamples, QObject* parent) : AbstractAudioInterface(parent), _audioInput(NULL), _desiredInputFormat(), @@ -67,7 +67,6 @@ Audio::Audio(Oscilloscope* scope, int16_t initialJitterBufferSamples, QObject* p _proceduralOutputDevice(NULL), _inputRingBuffer(0), _ringBuffer(NETWORK_BUFFER_LENGTH_BYTES_PER_CHANNEL), - _scope(scope), _averagedLatency(0.0), _measuredJitter(0), _jitterBufferSamples(initialJitterBufferSamples), @@ -555,12 +554,6 @@ void Audio::handleAudioInput() { _lastInputLoudness = 0; } } - - // add input data just written to the scope - QMetaObject::invokeMethod(_scope, "addSamples", Qt::QueuedConnection, - Q_ARG(QByteArray, QByteArray((char*) monoAudioSamples, - NETWORK_BUFFER_LENGTH_BYTES_PER_CHANNEL)), - Q_ARG(bool, false), Q_ARG(bool, true)); } else { // our input loudness is 0, since we're muted _lastInputLoudness = 0; @@ -724,11 +717,6 @@ void Audio::processReceivedAudio(const QByteArray& audioByteArray) { if (_outputDevice) { _outputDevice->write(outputBuffer); - - // add output (@speakers) data just written to the scope - QMetaObject::invokeMethod(_scope, "addSamples", Qt::QueuedConnection, - Q_ARG(QByteArray, QByteArray((char*) ringBufferSamples, numNetworkOutputSamples)), - Q_ARG(bool, true), Q_ARG(bool, false)); } delete[] ringBufferSamples; } diff --git a/interface/src/Audio.h b/interface/src/Audio.h index c529fc2651..bfb3450d72 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -34,9 +34,6 @@ #include #include -#include "ui/Oscilloscope.h" - - static const int NUM_AUDIO_CHANNELS = 2; class QAudioInput; @@ -47,7 +44,7 @@ class Audio : public AbstractAudioInterface { Q_OBJECT public: // setup for audio I/O - Audio(Oscilloscope* scope, int16_t initialJitterBufferSamples, QObject* parent = 0); + Audio(int16_t initialJitterBufferSamples, QObject* parent = 0); float getLastInputLoudness() const { return glm::max(_lastInputLoudness - _noiseGateMeasuredFloor, 0.f); } float getTimeSinceLastClip() const { return _timeSinceLastClip; } @@ -126,7 +123,6 @@ private: QString _inputAudioDeviceName; QString _outputAudioDeviceName; - Oscilloscope* _scope; StDev _stdev; timeval _lastReceiveTime; float _averagedLatency; diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 70e69597f6..f0aa746d00 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -252,7 +252,6 @@ Menu::Menu() : addDisabledActionAndSeparator(viewMenu, "Stats"); addCheckableActionToQMenuAndActionHash(viewMenu, MenuOption::Stats, Qt::Key_Slash); addActionToQMenuAndActionHash(viewMenu, MenuOption::Log, Qt::CTRL | Qt::Key_L, appInstance, SLOT(toggleLogDialog())); - addCheckableActionToQMenuAndActionHash(viewMenu, MenuOption::Oscilloscope, 0, false); addCheckableActionToQMenuAndActionHash(viewMenu, MenuOption::Bandwidth, 0, true); addActionToQMenuAndActionHash(viewMenu, MenuOption::BandwidthDetails, 0, this, SLOT(bandwidthDetails())); addActionToQMenuAndActionHash(viewMenu, MenuOption::OctreeStats, 0, this, SLOT(octreeStatsDetails())); diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 5bc48f916f..cdefa18273 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -287,7 +287,6 @@ namespace MenuOption { const QString OctreeStats = "Voxel and Particle Statistics"; const QString OffAxisProjection = "Off-Axis Projection"; const QString OldVoxelCullingMode = "Old Voxel Culling Mode"; - const QString Oscilloscope = "Audio Oscilloscope"; const QString Pair = "Pair"; const QString Particles = "Particles"; const QString PasteToVoxel = "Paste to Voxel..."; diff --git a/interface/src/ui/Oscilloscope.cpp b/interface/src/ui/Oscilloscope.cpp deleted file mode 100644 index af10539c43..0000000000 --- a/interface/src/ui/Oscilloscope.cpp +++ /dev/null @@ -1,192 +0,0 @@ -// -// Oscilloscope.cpp -// interface/src/ui -// -// Created by Philip on 1/28/13. -// Copyright 2013 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#include -#include -#include - -#include -#include - -#include "InterfaceConfig.h" - -#include "Oscilloscope.h" - -// Reimplemented 4/26/13 (tosh) - don't blame Philip for bugs - -using namespace std; - -namespace { // everything in here only exists while compiling this .cpp file - - // one sample buffer per channel - unsigned const MAX_SAMPLES = Oscilloscope::MAX_SAMPLES_PER_CHANNEL * Oscilloscope::MAX_CHANNELS; - - // adding an x-coordinate yields twice the amount of vertices - unsigned const MAX_COORDS_PER_CHANNEL = Oscilloscope::MAX_SAMPLES_PER_CHANNEL * 2; - // allocated once for each channel - unsigned const MAX_COORDS = MAX_COORDS_PER_CHANNEL * Oscilloscope::MAX_CHANNELS; - - // total amount of memory to allocate (in 16-bit integers) - unsigned const N_INT16_TO_ALLOC = MAX_SAMPLES + MAX_COORDS; -} - - -Oscilloscope::Oscilloscope(int w, int h, bool isEnabled) : - enabled(isEnabled), - inputPaused(false), - _width(w), - _height(h), - _samples(0l), - _vertices(0l), - // some filtering (see details in Log.h) - _lowPassCoeff(0.4f), - // three in -> one out - _downsampleRatio(3) { - - // allocate enough space for the sample data and to turn it into - // vertices and since they're all 'short', do so in one shot - _samples = new short[N_INT16_TO_ALLOC]; - memset(_samples, 0, N_INT16_TO_ALLOC * sizeof(short)); - _vertices = _samples + MAX_SAMPLES; - - // initialize write positions to start of each channel's region - for (unsigned ch = 0; ch < MAX_CHANNELS; ++ch) { - _writePos[ch] = MAX_SAMPLES_PER_CHANNEL * ch; - } - - _colors[0] = 0xffffff; - _colors[1] = 0x00ffff; - _colors[2] = 0x00ffff; -} - -Oscilloscope::~Oscilloscope() { - - delete[] _samples; -} - -void Oscilloscope::addSamples(const QByteArray& audioByteArray, bool isStereo, bool isInput) { - - if (! enabled || inputPaused) { - return; - } - - unsigned numSamplesPerChannel = audioByteArray.size() / (sizeof(int16_t) * (isStereo ? 2 : 1)); - int16_t* samples = (int16_t*) audioByteArray.data(); - - for (int channel = 0; channel < (isStereo ? 2 : 1); channel++) { - // add samples for each of the channels - - // determine start/end offset of this channel's region - unsigned baseOffs = MAX_SAMPLES_PER_CHANNEL * (channel + !isInput); - unsigned endOffs = baseOffs + MAX_SAMPLES_PER_CHANNEL; - - // fetch write position for this channel - unsigned writePos = _writePos[channel + !isInput]; - - // determine write position after adding the samples - unsigned newWritePos = writePos + numSamplesPerChannel; - unsigned n2 = 0; - if (newWritePos >= endOffs) { - // passed boundary of the circular buffer? -> we need to copy two blocks - n2 = newWritePos - endOffs; - newWritePos = baseOffs + n2; - numSamplesPerChannel -= n2; - } - - if (!isStereo) { - // copy data - memcpy(_samples + writePos, samples, numSamplesPerChannel * sizeof(int16_t)); - if (n2 > 0) { - memcpy(_samples + baseOffs, samples + numSamplesPerChannel, n2 * sizeof(int16_t)); - } - } else { - // we have interleaved samples we need to separate into two channels - for (unsigned i = 0; i < numSamplesPerChannel + n2; i++) { - if (i < numSamplesPerChannel - n2) { - _samples[writePos] = samples[(i * 2) + channel]; - } else { - _samples[baseOffs] = samples[(i * 2) + channel]; - } - } - } - - // set new write position for this channel - _writePos[channel + !isInput] = newWritePos; - } -} - -void Oscilloscope::render(int x, int y) { - - if (! enabled) { - return; - } - - // fetch low pass factor (and convert to fix point) / downsample factor - int lowPassFixPt = -(int)(std::numeric_limits::min()) * _lowPassCoeff; - unsigned downsample = _downsampleRatio; - // keep half of the buffer for writing and ensure an even vertex count - unsigned usedWidth = min(_width, MAX_SAMPLES_PER_CHANNEL / (downsample * 2)) & ~1u; - unsigned usedSamples = usedWidth * downsample; - - // expand samples to vertex data - for (unsigned ch = 0; ch < MAX_CHANNELS; ++ch) { - // for each channel: determine memory regions - short const* basePtr = _samples + MAX_SAMPLES_PER_CHANNEL * ch; - short const* endPtr = basePtr + MAX_SAMPLES_PER_CHANNEL; - short const* inPtr = _samples + _writePos[ch]; - short* outPtr = _vertices + MAX_COORDS_PER_CHANNEL * ch; - int sample = 0, x = usedWidth; - for (int i = (int)usedSamples; --i >= 0 ;) { - if (inPtr == basePtr) { - // handle boundary, reading the circular sample buffer - inPtr = endPtr; - } - // read and (eventually) filter sample - sample += ((*--inPtr - sample) * lowPassFixPt) >> 15; - // write every nth as y with a corresponding x-coordinate - if (i % downsample == 0) { - *outPtr++ = short(--x); - *outPtr++ = short(sample); - } - } - } - - // set up rendering state (vertex data lives at _vertices) - glLineWidth(1.0); - glDisable(GL_LINE_SMOOTH); - glPushMatrix(); - glTranslatef((float)x + 0.0f, (float)y + _height / 2.0f, 0.0f); - glScaled(1.0f, _height / 32767.0f, 1.0f); - glVertexPointer(2, GL_SHORT, 0, _vertices); - glEnableClientState(GL_VERTEX_ARRAY); - glDisableClientState(GL_COLOR_ARRAY); - glDisableClientState(GL_INDEX_ARRAY); - glDisableClientState(GL_NORMAL_ARRAY); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - - // render channel 0 - glColor3ub(GLubyte(_colors[0] >> 16), GLubyte((_colors[0] >> 8) & 0xff), GLubyte(_colors[0] & 0xff)); - glDrawArrays(GL_LINES, MAX_SAMPLES_PER_CHANNEL * 0, usedWidth); - - // render channel 1 - glColor3f(0.0f, 1.0f ,1.0f); - glColor3ub(GLubyte(_colors[1] >> 16), GLubyte((_colors[1] >> 8) & 0xff), GLubyte(_colors[1] & 0xff)); - glDrawArrays(GL_LINES, MAX_SAMPLES_PER_CHANNEL * 1, usedWidth); - - // render channel 2 - glColor3ub(GLubyte(_colors[2] >> 16), GLubyte((_colors[2] >> 8) & 0xff), GLubyte(_colors[2] & 0xff)); - glDrawArrays(GL_LINES, MAX_SAMPLES_PER_CHANNEL * 2, usedWidth); - - // reset rendering state - glDisableClientState(GL_VERTEX_ARRAY); - glPopMatrix(); -} - diff --git a/interface/src/ui/Oscilloscope.h b/interface/src/ui/Oscilloscope.h deleted file mode 100644 index 6eff547530..0000000000 --- a/interface/src/ui/Oscilloscope.h +++ /dev/null @@ -1,84 +0,0 @@ -// -// Oscilloscope.h -// interface/src/ui -// -// Created by Philip on 1/28/13. -// Copyright 2013 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#ifndef hifi_Oscilloscope_h -#define hifi_Oscilloscope_h - -#include - -#include - -class Oscilloscope : public QObject { - Q_OBJECT -public: - Oscilloscope(int width, int height, bool isEnabled); - ~Oscilloscope(); - - void render(int x, int y); - - // Switches: On/Off, Stop Time - volatile bool enabled; - volatile bool inputPaused; - - // Limits - static unsigned const MAX_CHANNELS = 3; - static unsigned const MAX_SAMPLES_PER_CHANNEL = 4096; - - // Sets the color for a specific channel. - void setColor(unsigned ch, unsigned rgb) { assert(ch < MAX_CHANNELS); if (! inputPaused) { _colors[ch] = rgb; } } - - // Controls a simple one pole IIR low pass filter that is provided to - // reduce high frequencies aliasing (to lower ones) when downsampling. - // - // The parameter sets the influence of the input in respect to the - // feed-back signal on the output. - // - // +---------+ - // in O--------------|+ ideal |--o--------------O out - // .---|- op amp | | - // | +---------+ | - // | | - // o-------||-------o - // | | - // | __V__ - // -------------|_____|-------+ - // : : | - // 0.0 - 1.0 (GND) - // - // The values in range 0.0 - 1.0 correspond to "all closed" (input has - // no influence on the output) to "all open" (feedback has no influence - // on the output) configurations. - void setLowpassOpenness(float w) { assert(w >= 0.0f && w <= 1.0f); _lowPassCoeff = w; } - - // Sets the number of input samples per output sample. Without filtering - // just uses every nTh sample. - void setDownsampleRatio(unsigned n) { assert(n > 0); _downsampleRatio = n; } -public slots: - void addSamples(const QByteArray& audioByteArray, bool isStereo, bool isInput); -private: - // don't copy/assign - Oscilloscope(Oscilloscope const&); // = delete; - Oscilloscope& operator=(Oscilloscope const&); // = delete; - - // state variables - - unsigned _width; - unsigned _height; - short* _samples; - short* _vertices; - unsigned _writePos[MAX_CHANNELS]; - - float _lowPassCoeff; - unsigned _downsampleRatio; - unsigned _colors[MAX_CHANNELS]; -}; - -#endif // hifi_Oscilloscope_h From 03bb2573d19934f531e36bec088ee36e9d9b7057 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 17:18:34 -0700 Subject: [PATCH 285/595] look in bin folder to find GnuTLS on windows --- cmake/modules/FindGnuTLS.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/modules/FindGnuTLS.cmake b/cmake/modules/FindGnuTLS.cmake index fcfd1909f8..8d9823962f 100644 --- a/cmake/modules/FindGnuTLS.cmake +++ b/cmake/modules/FindGnuTLS.cmake @@ -27,7 +27,7 @@ else () find_path(GNUTLS_INCLUDE_DIR gnutls.h PATH_SUFFIXES include gnutls HINTS ${GNUTLS_SEARCH_DIRS}) - find_library(GNUTLS_LIBRARY NAMES gnutls PATH_SUFFIXES lib HINTS ${GNUTLS_SEARCH_DIRS}) + find_library(GNUTLS_LIBRARY NAMES gnutls gnutls-28 PATH_SUFFIXES lib bin HINTS ${GNUTLS_SEARCH_DIRS}) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(GNUTLS DEFAULT_MSG GNUTLS_INCLUDE_DIR GNUTLS_LIBRARY) From f27f8e39c8950701684ad4f931f986838447e19c Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 9 Apr 2014 17:22:17 -0700 Subject: [PATCH 286/595] example JS for handling avatar collisions --- examples/avatarCollision.js | 68 +++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 examples/avatarCollision.js diff --git a/examples/avatarCollision.js b/examples/avatarCollision.js new file mode 100644 index 0000000000..5ade894365 --- /dev/null +++ b/examples/avatarCollision.js @@ -0,0 +1,68 @@ +// +// avatarCollision.js +// examples +// +// Created by Andrew Meadows on 2014-04-09 +// Copyright 2014 High Fidelity, Inc. +// +// Play a sound on collisions with your avatar +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +var SOUND_TRIGGER_CLEAR = 1000; // milliseconds +var SOUND_TRIGGER_DELAY = 200; // milliseconds +var soundExpiry = 0; +var DateObj = new Date(); +var audioOptions = new AudioInjectionOptions(); +audioOptions.volume = 0.5; +audioOptions.position = { x: 0, y: 0, z: 0 }; + +var hitSounds = new Array(); +hitSounds[0] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit1.raw"); +hitSounds[1] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit2.raw"); +hitSounds[2] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit3.raw"); +hitSounds[3] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit4.raw"); +hitSounds[4] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit5.raw"); +hitSounds[5] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit6.raw"); +hitSounds[6] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit7.raw"); +hitSounds[7] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit8.raw"); +hitSounds[8] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit9.raw"); +hitSounds[9] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit10.raw"); +hitSounds[10] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit11.raw"); +hitSounds[11] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit12.raw"); +hitSounds[12] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit13.raw"); +hitSounds[13] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit14.raw"); +hitSounds[14] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit15.raw"); +hitSounds[15] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit16.raw"); +hitSounds[16] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit17.raw"); +hitSounds[17] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit18.raw"); +hitSounds[18] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit19.raw"); +hitSounds[19] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit20.raw"); +hitSounds[20] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit21.raw"); +hitSounds[21] = new Sound("http://highfidelity-public.s3-us-west-1.amazonaws.com/sounds/Collisions-hitsandslaps/Hit22.raw"); + +function playHitSound(mySessionID, theirSessionID, collision) { + var now = new Date(); + var msec = now.getTime(); + if (msec > soundExpiry) { + // this is a new contact --> play a new sound + var soundIndex = Math.floor((Math.random() * hitSounds.length) % hitSounds.length); + audioOptions.position = collision.contactPoint; + Audio.playSound(hitSounds[soundIndex], audioOptions); + + // bump the expiry + soundExpiry = msec + SOUND_TRIGGER_CLEAR; + + // log the collision info + Uuid.print("my sessionID = ", mySessionID); + Uuid.print(" their sessionID = ", theirSessionID); + Vec3.print(" penetration = ", collision.penetration); + Vec3.print(" contactPoint = ", collision.contactPoint); + } else { + // this is a recurring contact --> continue to delay sound trigger + soundExpiry = msec + SOUND_TRIGGER_DELAY; + } +} +MyAvatar.collisionWithAvatar.connect(playHitSound); From d54c21cdf13c839e5695e725b3bc0e0a4ee9921d Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 17:23:13 -0700 Subject: [PATCH 287/595] fix path suffixes for gnutls headers --- cmake/modules/FindGnuTLS.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/modules/FindGnuTLS.cmake b/cmake/modules/FindGnuTLS.cmake index 8d9823962f..58b10a9ed3 100644 --- a/cmake/modules/FindGnuTLS.cmake +++ b/cmake/modules/FindGnuTLS.cmake @@ -25,7 +25,7 @@ else () set(GNUTLS_SEARCH_DIRS "${GNUTLS_ROOT_DIR}" "$ENV{HIFI_LIB_DIR}/gnutls") - find_path(GNUTLS_INCLUDE_DIR gnutls.h PATH_SUFFIXES include gnutls HINTS ${GNUTLS_SEARCH_DIRS}) + find_path(GNUTLS_INCLUDE_DIR gnutls.h PATH_SUFFIXES include/gnutls gnutls HINTS ${GNUTLS_SEARCH_DIRS}) find_library(GNUTLS_LIBRARY NAMES gnutls gnutls-28 PATH_SUFFIXES lib bin HINTS ${GNUTLS_SEARCH_DIRS}) From c88be1ac3475e446bcc874bc96fe0fde13fd3df2 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 9 Apr 2014 17:26:05 -0700 Subject: [PATCH 288/595] remove unnecessary change --- interface/src/avatar/MyAvatar.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 3c358646a9..72c8544165 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -23,7 +23,6 @@ #include #include #include -#include #include From 35519e07dc6efbd472de9d7d8e06886ce1292079 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 17:27:37 -0700 Subject: [PATCH 289/595] quote dashed library name to potentially fix find on windows --- cmake/modules/FindGnuTLS.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/modules/FindGnuTLS.cmake b/cmake/modules/FindGnuTLS.cmake index 58b10a9ed3..24b414bcc0 100644 --- a/cmake/modules/FindGnuTLS.cmake +++ b/cmake/modules/FindGnuTLS.cmake @@ -27,7 +27,7 @@ else () find_path(GNUTLS_INCLUDE_DIR gnutls.h PATH_SUFFIXES include/gnutls gnutls HINTS ${GNUTLS_SEARCH_DIRS}) - find_library(GNUTLS_LIBRARY NAMES gnutls gnutls-28 PATH_SUFFIXES lib bin HINTS ${GNUTLS_SEARCH_DIRS}) + find_library(GNUTLS_LIBRARY NAMES gnutls "gnutls-28" PATH_SUFFIXES lib bin HINTS ${GNUTLS_SEARCH_DIRS}) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(GNUTLS DEFAULT_MSG GNUTLS_INCLUDE_DIR GNUTLS_LIBRARY) From 8b23addc470b818df0948cbf0449139377074942 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 17:31:11 -0700 Subject: [PATCH 290/595] prepend the gnutls library with lib for windows find --- cmake/modules/FindGnuTLS.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/modules/FindGnuTLS.cmake b/cmake/modules/FindGnuTLS.cmake index 24b414bcc0..24baaff358 100644 --- a/cmake/modules/FindGnuTLS.cmake +++ b/cmake/modules/FindGnuTLS.cmake @@ -27,7 +27,7 @@ else () find_path(GNUTLS_INCLUDE_DIR gnutls.h PATH_SUFFIXES include/gnutls gnutls HINTS ${GNUTLS_SEARCH_DIRS}) - find_library(GNUTLS_LIBRARY NAMES gnutls "gnutls-28" PATH_SUFFIXES lib bin HINTS ${GNUTLS_SEARCH_DIRS}) + find_library(GNUTLS_LIBRARY NAMES gnutls libgnutls libgnutls-28 PATH_SUFFIXES lib bin HINTS ${GNUTLS_SEARCH_DIRS}) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(GNUTLS DEFAULT_MSG GNUTLS_INCLUDE_DIR GNUTLS_LIBRARY) From 17d2e14f0fc5c4c6681f66cb9fc3c16b49c1b416 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 17:33:41 -0700 Subject: [PATCH 291/595] find correct parent include folder for gnutls --- cmake/modules/FindGnuTLS.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/modules/FindGnuTLS.cmake b/cmake/modules/FindGnuTLS.cmake index 24baaff358..f718bea68b 100644 --- a/cmake/modules/FindGnuTLS.cmake +++ b/cmake/modules/FindGnuTLS.cmake @@ -25,7 +25,7 @@ else () set(GNUTLS_SEARCH_DIRS "${GNUTLS_ROOT_DIR}" "$ENV{HIFI_LIB_DIR}/gnutls") - find_path(GNUTLS_INCLUDE_DIR gnutls.h PATH_SUFFIXES include/gnutls gnutls HINTS ${GNUTLS_SEARCH_DIRS}) + find_path(GNUTLS_INCLUDE_DIR gnutls/gnutls.h PATH_SUFFIXES include HINTS ${GNUTLS_SEARCH_DIRS}) find_library(GNUTLS_LIBRARY NAMES gnutls libgnutls libgnutls-28 PATH_SUFFIXES lib bin HINTS ${GNUTLS_SEARCH_DIRS}) From 2b44b03a27d8e9461355db4fd9f64a3345725b40 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 9 Apr 2014 17:34:17 -0700 Subject: [PATCH 292/595] Added temp fix to ModelUploader dialog too --- interface/src/Application.cpp | 10 ++++++---- interface/src/ModelUploader.cpp | 26 ++++++++++++++++++++++---- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index acd4e07c6a..a6d4819016 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -344,6 +344,9 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : } else { // do this as late as possible so that all required subsystems are inialized loadScripts(); + + QMutexLocker locker(&_settingsMutex); + _previousScriptLocation = _settings->value("LastScriptLocation", QVariant("")).toString(); } } @@ -3184,11 +3187,10 @@ void Application::packetSent(quint64 length) { void Application::loadScripts() { // loads all saved scripts - - lockSettings(); - int size = _settings->beginReadArray("Settings"); + int size = lockSettings()->beginReadArray("Settings"); + unlockSettings(); for (int i = 0; i < size; ++i){ - _settings->setArrayIndex(i); + lockSettings()->setArrayIndex(i); QString string = _settings->value("script").toString(); unlockSettings(); if (!string.isEmpty()) { diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index 3f496c9890..ddb7c57cf3 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -20,7 +20,9 @@ #include +#include "Application.h" #include "renderer/FBXReader.h" + #include "ModelUploader.h" @@ -32,6 +34,8 @@ static const QString LOD_FIELD = "lod"; static const QString S3_URL = "http://highfidelity-public.s3-us-west-1.amazonaws.com"; static const QString MODEL_URL = "/api/v1/models"; +static const QString SETTING_NAME = "LastModelUploadLocation"; + static const int MAX_SIZE = 10 * 1024 * 1024; // 10 MB static const int TIMEOUT = 1000; static const int MAX_CHECK = 30; @@ -49,6 +53,7 @@ ModelUploader::ModelUploader(bool isHead) : _numberOfChecks(MAX_CHECK) { connect(&_timer, SIGNAL(timeout()), SLOT(checkS3())); + } ModelUploader::~ModelUploader() { @@ -57,14 +62,27 @@ ModelUploader::~ModelUploader() { bool ModelUploader::zip() { // File Dialog - QString filename = QFileDialog::getOpenFileName(NULL, - "Select your .fst file ...", - QStandardPaths::writableLocation(QStandardPaths::HomeLocation), - "*.fst"); + QSettings* settings = Application::getInstance()->lockSettings(); + QString lastLocation = settings->value(SETTING_NAME).toString(); + + if (lastLocation.isEmpty()) { + lastLocation = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation); + // Temporary fix to Qt bug: http://stackoverflow.com/questions/16194475 +#ifdef __APPLE__ + lastLocation.append("/model.fst"); +#endif + } + + + QString filename = QFileDialog::getOpenFileName(NULL, "Select your .fst file ...", lastLocation, "*.fst"); if (filename == "") { // If the user canceled we return. + Application::getInstance()->unlockSettings(); return false; } + settings->setValue(SETTING_NAME, filename); + Application::getInstance()->unlockSettings(); + bool _nameIsPresent = false; QString texDir; QString fbxFile; From 3d071e85d5684fef60a8f59fefe78f8273c028e4 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 17:37:23 -0700 Subject: [PATCH 293/595] link GnuTLS to the assignment-client --- assignment-client/CMakeLists.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/assignment-client/CMakeLists.txt b/assignment-client/CMakeLists.txt index 505708a899..1611b1e2b4 100644 --- a/assignment-client/CMakeLists.txt +++ b/assignment-client/CMakeLists.txt @@ -13,6 +13,7 @@ set(MACRO_DIR "${ROOT_DIR}/cmake/macros") set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/../cmake/modules/") find_package(Qt5 COMPONENTS Network Script Widgets) +find_package(GnuTLS REQUIRED) include("${MACRO_DIR}/SetupHifiProject.cmake") setup_hifi_project(${TARGET_NAME} TRUE) @@ -41,4 +42,5 @@ IF (WIN32) target_link_libraries(${TARGET_NAME} Winmm Ws2_32) ENDIF(WIN32) -target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets Qt5::Script) +include_directories("${GNUTLS_INCLUDE_DIR}") +target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets Qt5::Script "${GNUTLS_LIBRARY}") \ No newline at end of file From ef89b8c3868602fd1a582973ed9890bd49dc7b2e Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 9 Apr 2014 17:37:37 -0700 Subject: [PATCH 294/595] Removed extra line --- interface/src/ModelUploader.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index 4c3a6758fe..d22097a00c 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -55,7 +55,6 @@ ModelUploader::ModelUploader(bool isHead) : _numberOfChecks(MAX_CHECK) { connect(&_timer, SIGNAL(timeout()), SLOT(checkS3())); - } ModelUploader::~ModelUploader() { From 31382b7e121a167d401f7d8a9034e14ab5f7346f Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 9 Apr 2014 17:41:18 -0700 Subject: [PATCH 295/595] add a message for Win32 users to generate the MSVC GnuTLS import library --- cmake/modules/FindGnuTLS.cmake | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/cmake/modules/FindGnuTLS.cmake b/cmake/modules/FindGnuTLS.cmake index f718bea68b..ac0f30877f 100644 --- a/cmake/modules/FindGnuTLS.cmake +++ b/cmake/modules/FindGnuTLS.cmake @@ -21,8 +21,7 @@ if (GNUTLS_LIBRARY AND GNUTLS_INCLUDE_DIRS) # in cache already set(GNUTLS_FOUND TRUE) -else () - +else () set(GNUTLS_SEARCH_DIRS "${GNUTLS_ROOT_DIR}" "$ENV{HIFI_LIB_DIR}/gnutls") find_path(GNUTLS_INCLUDE_DIR gnutls/gnutls.h PATH_SUFFIXES include HINTS ${GNUTLS_SEARCH_DIRS}) @@ -31,4 +30,12 @@ else () include(FindPackageHandleStandardArgs) find_package_handle_standard_args(GNUTLS DEFAULT_MSG GNUTLS_INCLUDE_DIR GNUTLS_LIBRARY) + + if (WIN32 AND NOT GNUTLS_FOUND) + message(STATUS "If you're generating a MSVC environment, you'll need to run the command") + message(STATUS "$GnuTLS-DIR\\bin>lib /def:libgnutls-28.def") + message(STATUS "From the MSVC command prompt to generate the .lib file and copy it into") + message(STATUS "your lib folder. Replace $GnuTLS-DIR in the command with the directory") + message(STATUS "containing GnuTLS.") + endif () endif () \ No newline at end of file From 9f58264cb692f6518013e7da8cecdfbba2c8974e Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Wed, 9 Apr 2014 18:07:56 -0700 Subject: [PATCH 296/595] Working on plane collisions, pushing back camera from intersecting avatars. --- interface/src/Application.cpp | 13 ++++ interface/src/avatar/Avatar.cpp | 5 ++ interface/src/avatar/Avatar.h | 6 ++ interface/src/renderer/Model.cpp | 15 +++++ interface/src/renderer/Model.h | 2 + libraries/shared/src/PlaneShape.h | 30 +++++++++ libraries/shared/src/Shape.h | 1 + libraries/shared/src/ShapeCollider.cpp | 86 ++++++++++++++++++++++++++ libraries/shared/src/ShapeCollider.h | 43 +++++++++++++ 9 files changed, 201 insertions(+) create mode 100644 libraries/shared/src/PlaneShape.h diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 6005ae085e..f91ede9f3e 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -522,6 +522,19 @@ void Application::paintGL() { _myCamera.setTargetPosition(_myAvatar->getHead()->calculateAverageEyePosition()); _myCamera.setTargetRotation(_myAvatar->getHead()->getCameraOrientation()); + // push camera out of any intersecting avatars + float pushback = 0.0f; + foreach (const AvatarSharedPointer& avatarData, _avatarManager.getAvatarHash()) { + Avatar* avatar = static_cast(avatarData.data()); + const float RADIUS_MULTIPLIER = 2.0f; + CollisionList collisions(4); + if (!avatar->isMyAvatar() && avatar->findSphereCollisions(_myCamera.getTargetPosition(), + _myCamera.getNearClip() * RADIUS_MULTIPLIER, collisions)) { + for (int i = 0; i < collisions.size(); i++) { + collisions.getCollision(i)->_penetration; + } + } + } } else if (_myCamera.getMode() == CAMERA_MODE_THIRD_PERSON) { _myCamera.setTightness(0.0f); // Camera is directly connected to head without smoothing _myCamera.setTargetPosition(_myAvatar->getUprightHeadPosition()); diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 47ced025aa..70a328eeea 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -522,6 +522,11 @@ bool Avatar::findSphereCollisions(const glm::vec3& penetratorCenter, float penet //return getHead()->getFaceModel().findSphereCollisions(penetratorCenter, penetratorRadius, collisions); } +bool Avatar::findPlaneCollisions(const glm::vec4& plane, CollisionList& collisions) { + return _skeletonModel.findPlaneCollisions(plane, collisions) || + getHead()->getFaceModel().findPlaneCollisions(plane, collisions); +} + void Avatar::updateShapePositions() { _skeletonModel.updateShapePositions(); Model& headModel = getHead()->getFaceModel(); diff --git a/interface/src/avatar/Avatar.h b/interface/src/avatar/Avatar.h index 4e24c00c7e..78a815cca5 100755 --- a/interface/src/avatar/Avatar.h +++ b/interface/src/avatar/Avatar.h @@ -119,6 +119,12 @@ public: bool findSphereCollisions(const glm::vec3& penetratorCenter, float penetratorRadius, CollisionList& collisions, int skeletonSkipIndex = -1); + /// Checks for penetration between the described plane and the avatar. + /// \param plane the penetration plane + /// \param collisions[out] a list to which collisions get appended + /// \return whether or not the plane penetrated + bool findPlaneCollisions(const glm::vec4& plane, CollisionList& collisions); + /// Checks for collision between the a spherical particle and the avatar (including paddle hands) /// \param collisionCenter the center of particle's bounding sphere /// \param collisionRadius the radius of particle's bounding sphere diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 819d1164c0..2635c6a8bc 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -634,6 +634,21 @@ bool Model::findSphereCollisions(const glm::vec3& sphereCenter, float sphereRadi return collided; } +bool Model::findPlaneCollisions(const glm::vec4& plane, CollisionList& collisions) { + bool collided = false; + PlaneShape planeShape(plane); + for (int i = 0; i < _jointShapes.size(); i++) { + if (ShapeCollider::shapeShape(&planeShape, _jointShapes[i], collisions)) { + CollisionInfo* collision = collisions.getLastCollision(); + collision->_type = MODEL_COLLISION; + collision->_data = (void*)(this); + collision->_flags = i; + collided = true; + } + } + return collided; +} + class Blender : public QRunnable { public: diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index 30625cc16f..65b79fffdd 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -176,6 +176,8 @@ public: bool findSphereCollisions(const glm::vec3& penetratorCenter, float penetratorRadius, CollisionList& collisions, int skipIndex = -1); + + bool findPlaneCollisions(const glm::vec4& plane, CollisionList& collisions); /// \param collision details about the collisions /// \return true if the collision is against a moveable joint diff --git a/libraries/shared/src/PlaneShape.h b/libraries/shared/src/PlaneShape.h new file mode 100644 index 0000000000..11823da701 --- /dev/null +++ b/libraries/shared/src/PlaneShape.h @@ -0,0 +1,30 @@ +// +// PlaneShape.h +// libraries/shared/src +// +// Created by Andrzej Kapolka on 4/9/2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_PlaneShape_h +#define hifi_PlaneShape_h + +#include "Shape.h" + +class PlaneShape : public Shape { +public: + PlaneShape() : Shape(Shape::PLANE_SHAPE) {} + + PlaneShape(const glm::vec4& coefficients) : Shape(Shape::PLANE_SHAPE), _coefficients(coefficients) { } + + const glm::vec4& getCoefficients() const { return _coefficients; } + +private: + + glm::vec4 _coefficients; +}; + +#endif // hifi_PlaneShape_h diff --git a/libraries/shared/src/Shape.h b/libraries/shared/src/Shape.h index fd16eafeae..87b84ea73b 100644 --- a/libraries/shared/src/Shape.h +++ b/libraries/shared/src/Shape.h @@ -22,6 +22,7 @@ public: UNKNOWN_SHAPE = 0, SPHERE_SHAPE, CAPSULE_SHAPE, + PLANE_SHAPE, BOX_SHAPE, LIST_SHAPE }; diff --git a/libraries/shared/src/ShapeCollider.cpp b/libraries/shared/src/ShapeCollider.cpp index b13775dfa8..15b01719af 100644 --- a/libraries/shared/src/ShapeCollider.cpp +++ b/libraries/shared/src/ShapeCollider.cpp @@ -13,6 +13,7 @@ #include +#include "GeometryUtil.h" #include "ShapeCollider.h" // NOTE: @@ -33,6 +34,8 @@ bool shapeShape(const Shape* shapeA, const Shape* shapeB, CollisionList& collisi return sphereSphere(sphereA, static_cast(shapeB), collisions); } else if (typeB == Shape::CAPSULE_SHAPE) { return sphereCapsule(sphereA, static_cast(shapeB), collisions); + } else if (typeB == Shape::PLANE_SHAPE) { + return spherePlane(sphereA, static_cast(shapeB), collisions); } } else if (typeA == Shape::CAPSULE_SHAPE) { const CapsuleShape* capsuleA = static_cast(shapeA); @@ -40,6 +43,17 @@ bool shapeShape(const Shape* shapeA, const Shape* shapeB, CollisionList& collisi return capsuleSphere(capsuleA, static_cast(shapeB), collisions); } else if (typeB == Shape::CAPSULE_SHAPE) { return capsuleCapsule(capsuleA, static_cast(shapeB), collisions); + } else if (typeB == Shape::PLANE_SHAPE) { + return capsulePlane(capsuleA, static_cast(shapeB), collisions); + } + } else if (typeA == Shape::PLANE_SHAPE) { + const PlaneShape* planeA = static_cast(shapeA); + if (typeB == Shape::SPHERE_SHAPE) { + return planeSphere(planeA, static_cast(shapeB), collisions); + } else if (typeB == Shape::CAPSULE_SHAPE) { + return planeCapsule(planeA, static_cast(shapeB), collisions); + } else if (typeB == Shape::PLANE_SHAPE) { + return planePlane(planeA, static_cast(shapeB), collisions); } } else if (typeA == Shape::LIST_SHAPE) { const ListShape* listA = static_cast(shapeA); @@ -47,6 +61,8 @@ bool shapeShape(const Shape* shapeA, const Shape* shapeB, CollisionList& collisi return listSphere(listA, static_cast(shapeB), collisions); } else if (typeB == Shape::CAPSULE_SHAPE) { return listCapsule(listA, static_cast(shapeB), collisions); + } else if (typeB == Shape::PLANE_SHAPE) { + return listPlane(listA, static_cast(shapeB), collisions); } } return false; @@ -143,6 +159,20 @@ bool sphereCapsule(const SphereShape* sphereA, const CapsuleShape* capsuleB, Col return false; } +bool spherePlane(const SphereShape* sphereA, const PlaneShape* planeB, CollisionList& collisions) { + glm::vec3 penetration; + if (findSpherePlanePenetration(sphereA->getPosition(), sphereA->getRadius(), planeB->getCoefficients(), penetration)) { + CollisionInfo* collision = collisions.getNewCollision(); + if (!collision) { + return false; // collision list is full + } + collision->_penetration = penetration; + collision->_contactPoint = glm::vec3(); + return true; + } + return false; +} + bool capsuleSphere(const CapsuleShape* capsuleA, const SphereShape* sphereB, CollisionList& collisions) { // find sphereB's closest approach to axis of capsuleA glm::vec3 AB = capsuleA->getPosition() - sphereB->getPosition(); @@ -349,6 +379,22 @@ bool capsuleCapsule(const CapsuleShape* capsuleA, const CapsuleShape* capsuleB, return false; } +bool capsulePlane(const CapsuleShape* capsuleA, const PlaneShape* planeB, CollisionList& collisions) { + return false; +} + +bool planeSphere(const PlaneShape* planeA, const SphereShape* sphereB, CollisionList& collisions) { + return false; +} + +bool planeCapsule(const PlaneShape* planeA, const CapsuleShape* capsuleB, CollisionList& collisions) { + return false; +} + +bool planePlane(const PlaneShape* planeA, const PlaneShape* planeB, CollisionList& collisions) { + return false; +} + bool sphereList(const SphereShape* sphereA, const ListShape* listB, CollisionList& collisions) { bool touching = false; for (int i = 0; i < listB->size() && !collisions.isFull(); ++i) { @@ -358,6 +404,8 @@ bool sphereList(const SphereShape* sphereA, const ListShape* listB, CollisionLis touching = sphereSphere(sphereA, static_cast(subShape), collisions) || touching; } else if (subType == Shape::CAPSULE_SHAPE) { touching = sphereCapsule(sphereA, static_cast(subShape), collisions) || touching; + } else if (subType == Shape::PLANE_SHAPE) { + touching = spherePlane(sphereA, static_cast(subShape), collisions) || touching; } } return touching; @@ -372,6 +420,24 @@ bool capsuleList(const CapsuleShape* capsuleA, const ListShape* listB, Collision touching = capsuleSphere(capsuleA, static_cast(subShape), collisions) || touching; } else if (subType == Shape::CAPSULE_SHAPE) { touching = capsuleCapsule(capsuleA, static_cast(subShape), collisions) || touching; + } else if (subType == Shape::PLANE_SHAPE) { + touching = capsulePlane(capsuleA, static_cast(subShape), collisions) || touching; + } + } + return touching; +} + +bool planeList(const PlaneShape* planeA, const ListShape* listB, CollisionList& collisions) { + bool touching = false; + for (int i = 0; i < listB->size() && !collisions.isFull(); ++i) { + const Shape* subShape = listB->getSubShape(i); + int subType = subShape->getType(); + if (subType == Shape::SPHERE_SHAPE) { + touching = planeSphere(planeA, static_cast(subShape), collisions) || touching; + } else if (subType == Shape::CAPSULE_SHAPE) { + touching = planeCapsule(planeA, static_cast(subShape), collisions) || touching; + } else if (subType == Shape::PLANE_SHAPE) { + touching = planePlane(planeA, static_cast(subShape), collisions) || touching; } } return touching; @@ -386,6 +452,8 @@ bool listSphere(const ListShape* listA, const SphereShape* sphereB, CollisionLis touching = sphereSphere(static_cast(subShape), sphereB, collisions) || touching; } else if (subType == Shape::CAPSULE_SHAPE) { touching = capsuleSphere(static_cast(subShape), sphereB, collisions) || touching; + } else if (subType == Shape::PLANE_SHAPE) { + touching = planeSphere(static_cast(subShape), sphereB, collisions) || touching; } } return touching; @@ -400,6 +468,24 @@ bool listCapsule(const ListShape* listA, const CapsuleShape* capsuleB, Collision touching = sphereCapsule(static_cast(subShape), capsuleB, collisions) || touching; } else if (subType == Shape::CAPSULE_SHAPE) { touching = capsuleCapsule(static_cast(subShape), capsuleB, collisions) || touching; + } else if (subType == Shape::PLANE_SHAPE) { + touching = planeCapsule(static_cast(subShape), capsuleB, collisions) || touching; + } + } + return touching; +} + +bool listPlane(const ListShape* listA, const PlaneShape* planeB, CollisionList& collisions) { + bool touching = false; + for (int i = 0; i < listA->size() && !collisions.isFull(); ++i) { + const Shape* subShape = listA->getSubShape(i); + int subType = subShape->getType(); + if (subType == Shape::SPHERE_SHAPE) { + touching = spherePlane(static_cast(subShape), planeB, collisions) || touching; + } else if (subType == Shape::CAPSULE_SHAPE) { + touching = capsulePlane(static_cast(subShape), planeB, collisions) || touching; + } else if (subType == Shape::PLANE_SHAPE) { + touching = planePlane(static_cast(subShape), planeB, collisions) || touching; } } return touching; diff --git a/libraries/shared/src/ShapeCollider.h b/libraries/shared/src/ShapeCollider.h index 7f02acf15c..0e6dac208c 100644 --- a/libraries/shared/src/ShapeCollider.h +++ b/libraries/shared/src/ShapeCollider.h @@ -15,6 +15,7 @@ #include "CapsuleShape.h" #include "CollisionInfo.h" #include "ListShape.h" +#include "PlaneShape.h" #include "SharedUtil.h" #include "SphereShape.h" @@ -38,6 +39,12 @@ namespace ShapeCollider { /// \return true if shapes collide bool sphereCapsule(const SphereShape* sphereA, const CapsuleShape* capsuleB, CollisionList& collisions); + /// \param sphereA pointer to first shape + /// \param planeB pointer to second shape + /// \param[out] collisions where to append collision details + /// \return true if shapes collide + bool spherePlane(const SphereShape* sphereA, const PlaneShape* planeB, CollisionList& collisions); + /// \param capsuleA pointer to first shape /// \param sphereB pointer to second shape /// \param[out] collisions where to append collision details @@ -50,6 +57,30 @@ namespace ShapeCollider { /// \return true if shapes collide bool capsuleCapsule(const CapsuleShape* capsuleA, const CapsuleShape* capsuleB, CollisionList& collisions); + /// \param capsuleA pointer to first shape + /// \param planeB pointer to second shape + /// \param[out] collisions where to append collision details + /// \return true if shapes collide + bool capsulePlane(const CapsuleShape* capsuleA, const PlaneShape* planeB, CollisionList& collisions); + + /// \param planeA pointer to first shape + /// \param sphereB pointer to second shape + /// \param[out] collisions where to append collision details + /// \return true if shapes collide + bool planeSphere(const PlaneShape* planeA, const SphereShape* sphereB, CollisionList& collisions); + + /// \param planeA pointer to first shape + /// \param capsuleB pointer to second shape + /// \param[out] collisions where to append collision details + /// \return true if shapes collide + bool planeCapsule(const PlaneShape* planeA, const CapsuleShape* capsuleB, CollisionList& collisions); + + /// \param planeA pointer to first shape + /// \param planeB pointer to second shape + /// \param[out] collisions where to append collision details + /// \return true if shapes collide + bool planePlane(const PlaneShape* planeA, const PlaneShape* planeB, CollisionList& collisions); + /// \param sphereA pointer to first shape /// \param listB pointer to second shape /// \param[out] collisions where to append collision details @@ -62,6 +93,12 @@ namespace ShapeCollider { /// \return true if shapes collide bool capsuleList(const CapsuleShape* capsuleA, const ListShape* listB, CollisionList& collisions); + /// \param planeA pointer to first shape + /// \param listB pointer to second shape + /// \param[out] collisions where to append collision details + /// \return true if shapes collide + bool planeList(const PlaneShape* planeA, const ListShape* listB, CollisionList& collisions); + /// \param listA pointer to first shape /// \param sphereB pointer to second shape /// \param[out] collisions where to append collision details @@ -74,6 +111,12 @@ namespace ShapeCollider { /// \return true if shapes collide bool listCapsule(const ListShape* listA, const CapsuleShape* capsuleB, CollisionList& collisions); + /// \param listA pointer to first shape + /// \param planeB pointer to second shape + /// \param[out] collisions where to append collision details + /// \return true if shapes collide + bool listPlane(const ListShape* listA, const PlaneShape* planeB, CollisionList& collisions); + /// \param listA pointer to first shape /// \param capsuleB pointer to second shape /// \param[out] collisions where to append collision details From 825acbbd9cfe529745af12a45cf5a6e8efa1532d Mon Sep 17 00:00:00 2001 From: Thijs Wenker Date: Thu, 10 Apr 2014 10:47:21 +0200 Subject: [PATCH 297/595] Update ScriptEngine.cpp DWORD is not defined in UNIX based systems. int should be fine --- libraries/script-engine/src/ScriptEngine.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index c5c1fdb2bf..c857e1193a 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -93,7 +93,7 @@ ScriptEngine::ScriptEngine(const QUrl& scriptURL, QUrl url(scriptURL); // if the scheme length is one or lower, maybe they typed in a file, let's try - const DWORD WINDOWS_DRIVE_LETTER_SIZE = 1; + const int WINDOWS_DRIVE_LETTER_SIZE = 1; if (url.scheme().size() <= WINDOWS_DRIVE_LETTER_SIZE) { url = QUrl::fromLocalFile(scriptURLString); } From 4942e93daacf3298feac28f89105888dcb3ceb99 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Thu, 10 Apr 2014 07:53:11 -0700 Subject: [PATCH 298/595] replace .f with .0f as per coding standard --- interface/src/avatar/Avatar.cpp | 28 +++++++++++++------------- libraries/shared/src/ShapeCollider.cpp | 28 +++++++++++++------------- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 47ced025aa..698d58c25a 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -233,22 +233,22 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode) { // quick check before falling into the code below: // (a 10 degree breadth of an almost 2 meter avatar kicks in at about 12m) - const float MIN_VOICE_SPHERE_DISTANCE = 12.f; + const float MIN_VOICE_SPHERE_DISTANCE = 12.0f; if (distanceToTarget > MIN_VOICE_SPHERE_DISTANCE) { // render voice intensity sphere for avatars that are farther away - const float MAX_SPHERE_ANGLE = 10.f * RADIANS_PER_DEGREE; - const float MIN_SPHERE_ANGLE = 1.f * RADIANS_PER_DEGREE; + const float MAX_SPHERE_ANGLE = 10.0f * RADIANS_PER_DEGREE; + const float MIN_SPHERE_ANGLE = 1.0f * RADIANS_PER_DEGREE; const float MIN_SPHERE_SIZE = 0.01f; const float SPHERE_LOUDNESS_SCALING = 0.0005f; const float SPHERE_COLOR[] = { 0.5f, 0.8f, 0.8f }; float height = getSkeletonHeight(); - glm::vec3 delta = height * (getHead()->getCameraOrientation() * IDENTITY_UP) / 2.f; + glm::vec3 delta = height * (getHead()->getCameraOrientation() * IDENTITY_UP) / 2.0f; float angle = abs(angleBetween(toTarget + delta, toTarget - delta)); float sphereRadius = getHead()->getAverageLoudness() * SPHERE_LOUDNESS_SCALING; if (renderMode == NORMAL_RENDER_MODE && (sphereRadius > MIN_SPHERE_SIZE) && (angle < MAX_SPHERE_ANGLE) && (angle > MIN_SPHERE_ANGLE)) { - glColor4f(SPHERE_COLOR[0], SPHERE_COLOR[1], SPHERE_COLOR[2], 1.f - angle / MAX_SPHERE_ANGLE); + glColor4f(SPHERE_COLOR[0], SPHERE_COLOR[1], SPHERE_COLOR[2], 1.0f - angle / MAX_SPHERE_ANGLE); glPushMatrix(); glTranslatef(_position.x, _position.y, _position.z); glScalef(height, height, height); @@ -280,9 +280,9 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode) { glm::vec3 chatAxis = glm::axis(chatRotation); glRotatef(glm::degrees(glm::angle(chatRotation)), chatAxis.x, chatAxis.y, chatAxis.z); - glColor3f(0.f, 0.8f, 0.f); - glRotatef(180.f, 0.f, 1.f, 0.f); - glRotatef(180.f, 0.f, 0.f, 1.f); + glColor3f(0.0f, 0.8f, 0.0f); + glRotatef(180.0f, 0.0f, 1.0f, 0.0f); + glRotatef(180.0f, 0.0f, 0.0f, 1.0f); glScalef(_scale * CHAT_MESSAGE_SCALE, _scale * CHAT_MESSAGE_SCALE, 1.0f); glDisable(GL_LIGHTING); @@ -298,7 +298,7 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode) { _chatMessage[lastIndex] = '\0'; textRenderer(CHAT)->draw(-width / 2.0f, 0, _chatMessage.c_str()); _chatMessage[lastIndex] = lastChar; - glColor3f(0.f, 1.f, 0.f); + glColor3f(0.0f, 1.0f, 0.0f); textRenderer(CHAT)->draw(width / 2.0f - lastWidth, 0, _chatMessage.c_str() + lastIndex); } glEnable(GL_LIGHTING); @@ -550,7 +550,7 @@ bool Avatar::findParticleCollisions(const glm::vec3& particleCenter, float parti const PalmData* palm = handData->getPalm(i); if (palm && palm->hasPaddle()) { // create a disk collision proxy where the hand is - glm::vec3 fingerAxis(0.f); + glm::vec3 fingerAxis(0.0f); for (size_t f = 0; f < palm->getNumFingers(); ++f) { const FingerData& finger = (palm->getFingers())[f]; if (finger.isActive()) { @@ -692,8 +692,8 @@ void Avatar::renderJointConnectingCone(glm::vec3 position1, glm::vec3 position2, glm::vec3 perpCos = glm::normalize(glm::cross(axis, perpSin)); perpSin = glm::cross(perpCos, axis); - float anglea = 0.f; - float angleb = 0.f; + float anglea = 0.0f; + float angleb = 0.0f; for (int i = 0; i < NUM_BODY_CONE_SIDES; i ++) { @@ -743,8 +743,8 @@ void Avatar::updateCollisionFlags() { void Avatar::setScale(float scale) { _scale = scale; - if (_targetScale * (1.f - RESCALING_TOLERANCE) < _scale && - _scale < _targetScale * (1.f + RESCALING_TOLERANCE)) { + if (_targetScale * (1.0f - RESCALING_TOLERANCE) < _scale && + _scale < _targetScale * (1.0f + RESCALING_TOLERANCE)) { _scale = _targetScale; } } diff --git a/libraries/shared/src/ShapeCollider.cpp b/libraries/shared/src/ShapeCollider.cpp index 217009ecf3..32789aa388 100644 --- a/libraries/shared/src/ShapeCollider.cpp +++ b/libraries/shared/src/ShapeCollider.cpp @@ -63,8 +63,8 @@ bool collideShapesCoarse(const QVector& shapesA, const QVector 0) { - glm::vec3 totalPenetration(0.f); - glm::vec3 averageContactPoint(0.f); + glm::vec3 totalPenetration(0.0f); + glm::vec3 averageContactPoint(0.0f); for (int j = 0; j < tempCollisions.size(); ++j) { CollisionInfo* c = tempCollisions.getCollision(j); totalPenetration = addPenetrations(totalPenetration, c->_penetration); @@ -86,7 +86,7 @@ bool sphereSphere(const SphereShape* sphereA, const SphereShape* sphereB, Collis float distance = sqrtf(distanceSquared); if (distance < EPSILON) { // the spheres are on top of each other, so we pick an arbitrary penetration direction - BA = glm::vec3(0.f, 1.f, 0.f); + BA = glm::vec3(0.0f, 1.0f, 0.0f); distance = totalRadius; } else { BA /= distance; @@ -121,7 +121,7 @@ bool sphereCapsule(const SphereShape* sphereA, const CapsuleShape* capsuleB, Col } if (absAxialDistance > capsuleB->getHalfHeight()) { // sphere hits capsule on a cap --> recompute radialAxis to point from spherA to cap center - float sign = (axialDistance > 0.f) ? 1.f : -1.f; + float sign = (axialDistance > 0.0f) ? 1.0f : -1.0f; radialAxis = BA + (sign * capsuleB->getHalfHeight()) * capsuleAxis; radialDistance2 = glm::length2(radialAxis); if (radialDistance2 > totalRadius2) { @@ -153,12 +153,12 @@ bool sphereCapsule(const SphereShape* sphereA, const CapsuleShape* capsuleB, Col return false; } // ... but still defined for the cap case - if (axialDistance < 0.f) { + if (axialDistance < 0.0f) { // we're hitting the start cap, so we negate the capsuleAxis capsuleAxis *= -1; } // penetration points from A into B - float sign = (axialDistance > 0.f) ? -1.f : 1.f; + float sign = (axialDistance > 0.0f) ? -1.0f : 1.0f; collision->_penetration = (sign * (totalRadius + capsuleB->getHalfHeight() - absAxialDistance)) * capsuleAxis; // contactPoint is on surface of sphereA collision->_contactPoint = sphereA->getPosition() + (sign * sphereA->getRadius()) * capsuleAxis; @@ -191,7 +191,7 @@ bool capsuleSphere(const CapsuleShape* capsuleA, const SphereShape* sphereB, Col if (absAxialDistance > capsuleA->getHalfHeight()) { // sphere hits capsule on a cap // --> recompute radialAxis and closestApproach - float sign = (axialDistance > 0.f) ? 1.f : -1.f; + float sign = (axialDistance > 0.0f) ? 1.0f : -1.0f; closestApproach = capsuleA->getPosition() + (sign * capsuleA->getHalfHeight()) * capsuleAxis; radialAxis = closestApproach - sphereB->getPosition(); radialDistance2 = glm::length2(radialAxis); @@ -224,11 +224,11 @@ bool capsuleSphere(const CapsuleShape* capsuleA, const SphereShape* sphereB, Col return false; } // ... but still defined for the cap case - if (axialDistance < 0.f) { + if (axialDistance < 0.0f) { // we're hitting the start cap, so we negate the capsuleAxis capsuleAxis *= -1; } - float sign = (axialDistance > 0.f) ? 1.f : -1.f; + float sign = (axialDistance > 0.0f) ? 1.0f : -1.0f; collision->_penetration = (sign * (totalRadius + capsuleA->getHalfHeight() - absAxialDistance)) * capsuleAxis; // contactPoint is on surface of sphereA collision->_contactPoint = closestApproach + (sign * capsuleA->getRadius()) * capsuleAxis; @@ -251,7 +251,7 @@ bool capsuleCapsule(const CapsuleShape* capsuleA, const CapsuleShape* capsuleB, // d = [(B - A) . (a - (a.b)b)] / (1 - (a.b)^2) float aDotB = glm::dot(axisA, axisB); - float denominator = 1.f - aDotB * aDotB; + float denominator = 1.0f - aDotB * aDotB; float totalRadius = capsuleA->getRadius() + capsuleB->getRadius(); if (denominator > EPSILON) { // distances to points of closest approach @@ -261,12 +261,12 @@ bool capsuleCapsule(const CapsuleShape* capsuleA, const CapsuleShape* capsuleB, // clamp the distances to the ends of the capsule line segments float absDistanceA = fabs(distanceA); if (absDistanceA > capsuleA->getHalfHeight() + capsuleA->getRadius()) { - float signA = distanceA < 0.f ? -1.f : 1.f; + float signA = distanceA < 0.0f ? -1.0f : 1.0f; distanceA = signA * capsuleA->getHalfHeight(); } float absDistanceB = fabs(distanceB); if (absDistanceB > capsuleB->getHalfHeight() + capsuleB->getRadius()) { - float signB = distanceB < 0.f ? -1.f : 1.f; + float signB = distanceB < 0.0f ? -1.0f : 1.0f; distanceB = signB * capsuleB->getHalfHeight(); } @@ -293,7 +293,7 @@ bool capsuleCapsule(const CapsuleShape* capsuleA, const CapsuleShape* capsuleB, { // the capsule centers are on top of each other! // give up on a valid penetration direction and just use the yAxis - BA = glm::vec3(0.f, 1.f, 0.f); + BA = glm::vec3(0.0f, 1.0f, 0.0f); distance = glm::max(capsuleB->getRadius(), capsuleA->getRadius()); } } else { @@ -325,7 +325,7 @@ bool capsuleCapsule(const CapsuleShape* capsuleA, const CapsuleShape* capsuleB, float distance = sqrtf(distanceSquared); if (distance < EPSILON) { // the spheres are on top of each other, so we pick an arbitrary penetration direction - BA = glm::vec3(0.f, 1.f, 0.f); + BA = glm::vec3(0.0f, 1.0f, 0.0f); } else { BA /= distance; } From f9fb8b46a54ee2518a10c64a50a6d8cd0f415f5f Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Thu, 10 Apr 2014 07:53:39 -0700 Subject: [PATCH 299/595] adding names to arguments in collisionWithAvatar() declaration --- interface/src/avatar/Avatar.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/avatar/Avatar.h b/interface/src/avatar/Avatar.h index 2dd7b6b037..cad0ddcdf0 100755 --- a/interface/src/avatar/Avatar.h +++ b/interface/src/avatar/Avatar.h @@ -64,7 +64,7 @@ enum ScreenTintLayer { // Where one's own Avatar begins in the world (will be overwritten if avatar data file is found) // this is basically in the center of the ground plane. Slightly adjusted. This was asked for by // Grayson as he's building a street around here for demo dinner 2 -const glm::vec3 START_LOCATION(0.485f * TREE_SCALE, 0.f, 0.5f * TREE_SCALE); +const glm::vec3 START_LOCATION(0.485f * TREE_SCALE, 0.0f, 0.5f * TREE_SCALE); class Texture; @@ -156,7 +156,7 @@ public slots: void updateCollisionFlags(); signals: - void collisionWithAvatar(const QUuid&, const QUuid&, const CollisionInfo&); + void collisionWithAvatar(const QUuid& myUUID, const QUuid& theirUUID, const CollisionInfo& collision); protected: SkeletonModel _skeletonModel; From d5d52f804f5d5b3223fb65c4ae7d08b9e19abff1 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 09:32:17 -0700 Subject: [PATCH 300/595] add a networking library and link from appropriate targets --- animation-server/CMakeLists.txt | 3 ++- assignment-client/CMakeLists.txt | 5 ++-- .../src/avatars/AvatarMixerClientData.cpp | 2 ++ domain-server/CMakeLists.txt | 1 + interface/CMakeLists.txt | 9 ++++--- libraries/audio/CMakeLists.txt | 3 ++- libraries/avatars/CMakeLists.txt | 1 + libraries/metavoxels/CMakeLists.txt | 7 ++++-- libraries/networking/CMakeLists.txt | 24 +++++++++++++++++++ .../src/AccountManager.cpp | 2 +- .../src/AccountManager.h | 2 +- .../{shared => networking}/src/Assignment.cpp | 2 +- .../{shared => networking}/src/Assignment.h | 2 +- .../src/DTLSClientSession.cpp | 2 +- .../src/DTLSClientSession.h | 2 +- .../src/DTLSSession.cpp | 2 +- .../{shared => networking}/src/DTLSSession.h | 2 +- .../src/DataServerAccountInfo.cpp | 2 +- .../src/DataServerAccountInfo.h | 2 +- .../src/DomainHandler.cpp | 2 +- .../src/DomainHandler.h | 2 +- .../src/DummyDTLSSession.cpp | 2 +- .../src/DummyDTLSSession.h | 2 +- .../src/HifiSockAddr.cpp | 2 +- .../{shared => networking}/src/HifiSockAddr.h | 2 +- .../src/LimitedNodeList.cpp | 2 +- .../src/LimitedNodeList.h | 2 +- .../{shared => networking}/src/Logging.cpp | 2 +- .../{shared => networking}/src/Logging.h | 2 +- .../src/NetworkPacket.cpp | 2 +- .../src/NetworkPacket.h | 2 +- libraries/{shared => networking}/src/Node.cpp | 2 +- libraries/{shared => networking}/src/Node.h | 2 +- .../{shared => networking}/src/NodeData.cpp | 2 +- .../{shared => networking}/src/NodeData.h | 2 +- .../{shared => networking}/src/NodeList.cpp | 2 +- .../{shared => networking}/src/NodeList.h | 2 +- .../src/OAuthAccessToken.cpp | 2 +- .../src/OAuthAccessToken.h | 2 +- .../src/PacketHeaders.cpp | 2 +- .../src/PacketHeaders.h | 2 +- .../src/PacketSender.cpp | 2 +- .../{shared => networking}/src/PacketSender.h | 2 +- .../src/ReceivedPacketProcessor.cpp | 2 +- .../src/ReceivedPacketProcessor.h | 2 +- .../{shared => networking}/src/Syssocket.h | 0 .../src/ThreadedAssignment.cpp | 0 .../src/ThreadedAssignment.h | 0 libraries/octree/CMakeLists.txt | 1 + libraries/particles/CMakeLists.txt | 1 + libraries/shared/CMakeLists.txt | 4 +--- libraries/shared/src/SharedUtil.cpp | 1 - libraries/shared/src/SharedUtil.h | 2 -- libraries/voxels/CMakeLists.txt | 1 + voxel-edit/CMakeLists.txt | 3 +++ 55 files changed, 86 insertions(+), 54 deletions(-) create mode 100644 libraries/networking/CMakeLists.txt rename libraries/{shared => networking}/src/AccountManager.cpp (99%) rename libraries/{shared => networking}/src/AccountManager.h (99%) rename libraries/{shared => networking}/src/Assignment.cpp (99%) rename libraries/{shared => networking}/src/Assignment.h (99%) rename libraries/{shared => networking}/src/DTLSClientSession.cpp (98%) rename libraries/{shared => networking}/src/DTLSClientSession.h (96%) rename libraries/{shared => networking}/src/DTLSSession.cpp (99%) rename libraries/{shared => networking}/src/DTLSSession.h (97%) rename libraries/{shared => networking}/src/DataServerAccountInfo.cpp (98%) rename libraries/{shared => networking}/src/DataServerAccountInfo.h (97%) rename libraries/{shared => networking}/src/DomainHandler.cpp (99%) rename libraries/{shared => networking}/src/DomainHandler.h (98%) rename libraries/{shared => networking}/src/DummyDTLSSession.cpp (97%) rename libraries/{shared => networking}/src/DummyDTLSSession.h (96%) rename libraries/{shared => networking}/src/HifiSockAddr.cpp (99%) rename libraries/{shared => networking}/src/HifiSockAddr.h (98%) rename libraries/{shared => networking}/src/LimitedNodeList.cpp (99%) rename libraries/{shared => networking}/src/LimitedNodeList.h (99%) rename libraries/{shared => networking}/src/Logging.cpp (99%) rename libraries/{shared => networking}/src/Logging.h (98%) rename libraries/{shared => networking}/src/NetworkPacket.cpp (98%) rename libraries/{shared => networking}/src/NetworkPacket.h (98%) rename libraries/{shared => networking}/src/Node.cpp (99%) rename libraries/{shared => networking}/src/Node.h (99%) rename libraries/{shared => networking}/src/NodeData.cpp (92%) rename libraries/{shared => networking}/src/NodeData.h (95%) rename libraries/{shared => networking}/src/NodeList.cpp (99%) rename libraries/{shared => networking}/src/NodeList.h (99%) rename libraries/{shared => networking}/src/OAuthAccessToken.cpp (98%) rename libraries/{shared => networking}/src/OAuthAccessToken.h (97%) rename libraries/{shared => networking}/src/PacketHeaders.cpp (99%) rename libraries/{shared => networking}/src/PacketHeaders.h (99%) rename libraries/{shared => networking}/src/PacketSender.cpp (99%) rename libraries/{shared => networking}/src/PacketSender.h (99%) rename libraries/{shared => networking}/src/ReceivedPacketProcessor.cpp (98%) rename libraries/{shared => networking}/src/ReceivedPacketProcessor.h (98%) rename libraries/{shared => networking}/src/Syssocket.h (100%) rename libraries/{shared => networking}/src/ThreadedAssignment.cpp (100%) rename libraries/{shared => networking}/src/ThreadedAssignment.h (100%) diff --git a/animation-server/CMakeLists.txt b/animation-server/CMakeLists.txt index 7d3222327a..d8fa8d97b2 100644 --- a/animation-server/CMakeLists.txt +++ b/animation-server/CMakeLists.txt @@ -29,4 +29,5 @@ link_hifi_library(octree ${TARGET_NAME} "${ROOT_DIR}") # link in the hifi voxels library link_hifi_library(voxels ${TARGET_NAME} "${ROOT_DIR}") - +# link the hifi networking library +link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") \ No newline at end of file diff --git a/assignment-client/CMakeLists.txt b/assignment-client/CMakeLists.txt index 1611b1e2b4..fa8d23051a 100644 --- a/assignment-client/CMakeLists.txt +++ b/assignment-client/CMakeLists.txt @@ -13,7 +13,6 @@ set(MACRO_DIR "${ROOT_DIR}/cmake/macros") set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/../cmake/modules/") find_package(Qt5 COMPONENTS Network Script Widgets) -find_package(GnuTLS REQUIRED) include("${MACRO_DIR}/SetupHifiProject.cmake") setup_hifi_project(${TARGET_NAME} TRUE) @@ -31,6 +30,7 @@ link_hifi_library(octree ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(voxels ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(particles ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(metavoxels ${TARGET_NAME} "${ROOT_DIR}") +link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(script-engine ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(embedded-webserver ${TARGET_NAME} "${ROOT_DIR}") @@ -42,5 +42,4 @@ IF (WIN32) target_link_libraries(${TARGET_NAME} Winmm Ws2_32) ENDIF(WIN32) -include_directories("${GNUTLS_INCLUDE_DIR}") -target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets Qt5::Script "${GNUTLS_LIBRARY}") \ No newline at end of file +target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets Qt5::Script) \ No newline at end of file diff --git a/assignment-client/src/avatars/AvatarMixerClientData.cpp b/assignment-client/src/avatars/AvatarMixerClientData.cpp index 9289d640f5..f35285124f 100644 --- a/assignment-client/src/avatars/AvatarMixerClientData.cpp +++ b/assignment-client/src/avatars/AvatarMixerClientData.cpp @@ -9,6 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include + #include "AvatarMixerClientData.h" AvatarMixerClientData::AvatarMixerClientData() : diff --git a/domain-server/CMakeLists.txt b/domain-server/CMakeLists.txt index 4cbc29c62d..0db22542b0 100644 --- a/domain-server/CMakeLists.txt +++ b/domain-server/CMakeLists.txt @@ -34,6 +34,7 @@ add_custom_command(TARGET ${TARGET_NAME} POST_BUILD # link the shared hifi library include(${MACRO_DIR}/LinkHifiLibrary.cmake) +link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(embedded-webserver ${TARGET_NAME} "${ROOT_DIR}") diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index 251553f3c3..6a3186bb70 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -32,8 +32,8 @@ elseif (UNIX) # include the right GL headers for UNIX set(GL_HEADERS "#include \n#include \n#include ") elseif (WIN32) - add_definitions( -D_USE_MATH_DEFINES ) # apparently needed to get M_PI and other defines from cmath/math.h - add_definitions( -DWINDOWS_LEAN_AND_MEAN ) # needed to make sure windows doesn't go to crazy with its defines + add_definitions(-D_USE_MATH_DEFINES) # apparently needed to get M_PI and other defines from cmath/math.h + add_definitions(-DWINDOWS_LEAN_AND_MEAN) # needed to make sure windows doesn't go to crazy with its defines set(GL_HEADERS "#include \n#include \n#include ") endif () @@ -67,7 +67,6 @@ foreach(EXTERNAL_SOURCE_SUBDIR ${EXTERNAL_SOURCE_SUBDIRS}) endforeach(EXTERNAL_SOURCE_SUBDIR) find_package(Qt5 COMPONENTS Core Gui Multimedia Network OpenGL Script Svg WebKit WebKitWidgets Xml UiTools) -find_package(GnuTLS REQUIRED) # grab the ui files in resources/ui file (GLOB_RECURSE QT_UI_FILES ui/*.ui) @@ -125,6 +124,7 @@ link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(octree ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(voxels ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(metavoxels ${TARGET_NAME} "${ROOT_DIR}") +link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(particles ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(avatars ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(audio ${TARGET_NAME} "${ROOT_DIR}") @@ -189,7 +189,7 @@ include_directories("${PROJECT_SOURCE_DIR}/src" "${PROJECT_BINARY_DIR}/includes" # include external library headers # use system flag so warnings are supressed -include_directories(SYSTEM "${FACESHIFT_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") +include_directories(SYSTEM "${FACESHIFT_INCLUDE_DIRS}") target_link_libraries( ${TARGET_NAME} @@ -197,7 +197,6 @@ target_link_libraries( "${ZLIB_LIBRARIES}" Qt5::Core Qt5::Gui Qt5::Multimedia Qt5::Network Qt5::OpenGL Qt5::Script Qt5::Svg Qt5::WebKit Qt5::WebKitWidgets Qt5::Xml Qt5::UiTools - "${GNUTLS_LIBRARY}" ) if (APPLE) diff --git a/libraries/audio/CMakeLists.txt b/libraries/audio/CMakeLists.txt index 8d2feb22a2..0bf0ba9904 100644 --- a/libraries/audio/CMakeLists.txt +++ b/libraries/audio/CMakeLists.txt @@ -20,4 +20,5 @@ include(${MACRO_DIR}/IncludeGLM.cmake) include_glm(${TARGET_NAME} "${ROOT_DIR}") include(${MACRO_DIR}/LinkHifiLibrary.cmake) -link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") \ No newline at end of file +link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") +link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") \ No newline at end of file diff --git a/libraries/avatars/CMakeLists.txt b/libraries/avatars/CMakeLists.txt index 4cc97e56a5..9816282dda 100644 --- a/libraries/avatars/CMakeLists.txt +++ b/libraries/avatars/CMakeLists.txt @@ -26,5 +26,6 @@ link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") # link in the hifi voxels library link_hifi_library(octree ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(voxels ${TARGET_NAME} "${ROOT_DIR}") +link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") target_link_libraries(${TARGET_NAME} Qt5::Script) \ No newline at end of file diff --git a/libraries/metavoxels/CMakeLists.txt b/libraries/metavoxels/CMakeLists.txt index acc060b270..7a8319815a 100644 --- a/libraries/metavoxels/CMakeLists.txt +++ b/libraries/metavoxels/CMakeLists.txt @@ -20,8 +20,11 @@ auto_mtc(${TARGET_NAME} "${ROOT_DIR}") include(${MACRO_DIR}/SetupHifiLibrary.cmake) setup_hifi_library(${TARGET_NAME} "${AUTOMTC_SRC}") +# link in the networking library +include(${MACRO_DIR}/LinkHifiLibrary.cmake) +link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") + include(${MACRO_DIR}/IncludeGLM.cmake) include_glm(${TARGET_NAME} "${ROOT_DIR}") -target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets Qt5::Script) - +target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets Qt5::Script) \ No newline at end of file diff --git a/libraries/networking/CMakeLists.txt b/libraries/networking/CMakeLists.txt new file mode 100644 index 0000000000..101e739fea --- /dev/null +++ b/libraries/networking/CMakeLists.txt @@ -0,0 +1,24 @@ +cmake_minimum_required(VERSION 2.8) + +if (WIN32) + cmake_policy (SET CMP0020 NEW) +endif (WIN32) + +set(ROOT_DIR ../..) +set(MACRO_DIR "${ROOT_DIR}/cmake/macros") + +set(TARGET_NAME networking) +project(${TARGET_NAME}) + +find_package(Qt5 COMPONENTS Network) +find_package(GnuTLS REQUIRED) + +include(${MACRO_DIR}/SetupHifiLibrary.cmake) +setup_hifi_library(${TARGET_NAME}) + +# include GLM +include(${MACRO_DIR}/IncludeGLM.cmake) +include_glm(${TARGET_NAME} "${ROOT_DIR}") + +include_directories("${GNUTLS_INCLUDE_DIR}") +target_link_libraries(${TARGET_NAME} Qt5::Network "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/shared/src/AccountManager.cpp b/libraries/networking/src/AccountManager.cpp similarity index 99% rename from libraries/shared/src/AccountManager.cpp rename to libraries/networking/src/AccountManager.cpp index 6c0bcb33cb..d1e4edf2ea 100644 --- a/libraries/shared/src/AccountManager.cpp +++ b/libraries/networking/src/AccountManager.cpp @@ -1,6 +1,6 @@ // // AccountManager.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2/18/2014. // Copyright 2014 High Fidelity, Inc. diff --git a/libraries/shared/src/AccountManager.h b/libraries/networking/src/AccountManager.h similarity index 99% rename from libraries/shared/src/AccountManager.h rename to libraries/networking/src/AccountManager.h index fed6a61772..cb76786f4e 100644 --- a/libraries/shared/src/AccountManager.h +++ b/libraries/networking/src/AccountManager.h @@ -1,6 +1,6 @@ // // AccountManager.h -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2/18/2014. // Copyright 2014 High Fidelity, Inc. diff --git a/libraries/shared/src/Assignment.cpp b/libraries/networking/src/Assignment.cpp similarity index 99% rename from libraries/shared/src/Assignment.cpp rename to libraries/networking/src/Assignment.cpp index 4d6740b400..dd318aad8e 100644 --- a/libraries/shared/src/Assignment.cpp +++ b/libraries/networking/src/Assignment.cpp @@ -1,6 +1,6 @@ // // Assignment.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 8/22/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/Assignment.h b/libraries/networking/src/Assignment.h similarity index 99% rename from libraries/shared/src/Assignment.h rename to libraries/networking/src/Assignment.h index c5a83cf417..041121f760 100644 --- a/libraries/shared/src/Assignment.h +++ b/libraries/networking/src/Assignment.h @@ -1,6 +1,6 @@ // // Assignment.h -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 8/22/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/DTLSClientSession.cpp b/libraries/networking/src/DTLSClientSession.cpp similarity index 98% rename from libraries/shared/src/DTLSClientSession.cpp rename to libraries/networking/src/DTLSClientSession.cpp index bd626dfcd8..b17de8e168 100644 --- a/libraries/shared/src/DTLSClientSession.cpp +++ b/libraries/networking/src/DTLSClientSession.cpp @@ -1,6 +1,6 @@ // // DTLSClientSession.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2014-04-01. // Copyright 2014 High Fidelity, Inc. diff --git a/libraries/shared/src/DTLSClientSession.h b/libraries/networking/src/DTLSClientSession.h similarity index 96% rename from libraries/shared/src/DTLSClientSession.h rename to libraries/networking/src/DTLSClientSession.h index fcd5a3b5e9..eeca1aaa68 100644 --- a/libraries/shared/src/DTLSClientSession.h +++ b/libraries/networking/src/DTLSClientSession.h @@ -1,6 +1,6 @@ // // DTLSClientSession.h -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2014-04-01. // Copyright 2014 High Fidelity, Inc. diff --git a/libraries/shared/src/DTLSSession.cpp b/libraries/networking/src/DTLSSession.cpp similarity index 99% rename from libraries/shared/src/DTLSSession.cpp rename to libraries/networking/src/DTLSSession.cpp index 8e84c38edc..7d375ec327 100644 --- a/libraries/shared/src/DTLSSession.cpp +++ b/libraries/networking/src/DTLSSession.cpp @@ -1,6 +1,6 @@ // // DTLSSession.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2014-04-01. // Copyright 2014 High Fidelity, Inc. diff --git a/libraries/shared/src/DTLSSession.h b/libraries/networking/src/DTLSSession.h similarity index 97% rename from libraries/shared/src/DTLSSession.h rename to libraries/networking/src/DTLSSession.h index 4b69f13c78..9e9542e147 100644 --- a/libraries/shared/src/DTLSSession.h +++ b/libraries/networking/src/DTLSSession.h @@ -1,6 +1,6 @@ // // DTLSSession.h -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2014-04-01. // Copyright 2014 High Fidelity, Inc. diff --git a/libraries/shared/src/DataServerAccountInfo.cpp b/libraries/networking/src/DataServerAccountInfo.cpp similarity index 98% rename from libraries/shared/src/DataServerAccountInfo.cpp rename to libraries/networking/src/DataServerAccountInfo.cpp index 1c53bca30f..87d3b694a7 100644 --- a/libraries/shared/src/DataServerAccountInfo.cpp +++ b/libraries/networking/src/DataServerAccountInfo.cpp @@ -1,6 +1,6 @@ // // DataServerAccountInfo.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2/18/2014. // Copyright 2014 High Fidelity, Inc. diff --git a/libraries/shared/src/DataServerAccountInfo.h b/libraries/networking/src/DataServerAccountInfo.h similarity index 97% rename from libraries/shared/src/DataServerAccountInfo.h rename to libraries/networking/src/DataServerAccountInfo.h index ae5de6de64..21380c0855 100644 --- a/libraries/shared/src/DataServerAccountInfo.h +++ b/libraries/networking/src/DataServerAccountInfo.h @@ -1,6 +1,6 @@ // // DataServerAccountInfo.h -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2/21/2014. // Copyright 2014 High Fidelity, Inc. diff --git a/libraries/shared/src/DomainHandler.cpp b/libraries/networking/src/DomainHandler.cpp similarity index 99% rename from libraries/shared/src/DomainHandler.cpp rename to libraries/networking/src/DomainHandler.cpp index 85c452f01c..6c2fb0274a 100644 --- a/libraries/shared/src/DomainHandler.cpp +++ b/libraries/networking/src/DomainHandler.cpp @@ -1,6 +1,6 @@ // // DomainHandler.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2/18/2014. // Copyright 2014 High Fidelity, Inc. diff --git a/libraries/shared/src/DomainHandler.h b/libraries/networking/src/DomainHandler.h similarity index 98% rename from libraries/shared/src/DomainHandler.h rename to libraries/networking/src/DomainHandler.h index ef698fd826..9a18feb1ed 100644 --- a/libraries/shared/src/DomainHandler.h +++ b/libraries/networking/src/DomainHandler.h @@ -1,6 +1,6 @@ // // DomainHandler.h -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2/18/2014. // Copyright 2014 High Fidelity, Inc. diff --git a/libraries/shared/src/DummyDTLSSession.cpp b/libraries/networking/src/DummyDTLSSession.cpp similarity index 97% rename from libraries/shared/src/DummyDTLSSession.cpp rename to libraries/networking/src/DummyDTLSSession.cpp index 96207477cf..a42e3f1599 100644 --- a/libraries/shared/src/DummyDTLSSession.cpp +++ b/libraries/networking/src/DummyDTLSSession.cpp @@ -1,6 +1,6 @@ // // DummyDTLSSession.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2014-04-04. // Copyright 2014 High Fidelity, Inc. diff --git a/libraries/shared/src/DummyDTLSSession.h b/libraries/networking/src/DummyDTLSSession.h similarity index 96% rename from libraries/shared/src/DummyDTLSSession.h rename to libraries/networking/src/DummyDTLSSession.h index e13686ac51..352b2c23e2 100644 --- a/libraries/shared/src/DummyDTLSSession.h +++ b/libraries/networking/src/DummyDTLSSession.h @@ -1,6 +1,6 @@ // // DummyDTLSSession.h -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2014-04-04. // Copyright 2014 High Fidelity, Inc. diff --git a/libraries/shared/src/HifiSockAddr.cpp b/libraries/networking/src/HifiSockAddr.cpp similarity index 99% rename from libraries/shared/src/HifiSockAddr.cpp rename to libraries/networking/src/HifiSockAddr.cpp index fd79341850..be482cfe02 100644 --- a/libraries/shared/src/HifiSockAddr.cpp +++ b/libraries/networking/src/HifiSockAddr.cpp @@ -1,6 +1,6 @@ // // HifiSockAddr.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 11/26/2013. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/HifiSockAddr.h b/libraries/networking/src/HifiSockAddr.h similarity index 98% rename from libraries/shared/src/HifiSockAddr.h rename to libraries/networking/src/HifiSockAddr.h index 229587e523..49db336d19 100644 --- a/libraries/shared/src/HifiSockAddr.h +++ b/libraries/networking/src/HifiSockAddr.h @@ -1,6 +1,6 @@ // // HifiSockAddr.h -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 11/26/2013. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp similarity index 99% rename from libraries/shared/src/LimitedNodeList.cpp rename to libraries/networking/src/LimitedNodeList.cpp index b4a65475d6..b0b048dde4 100644 --- a/libraries/shared/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -1,6 +1,6 @@ // // LimitedNodeList.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2/15/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/LimitedNodeList.h b/libraries/networking/src/LimitedNodeList.h similarity index 99% rename from libraries/shared/src/LimitedNodeList.h rename to libraries/networking/src/LimitedNodeList.h index d428805511..7fc0346a74 100644 --- a/libraries/shared/src/LimitedNodeList.h +++ b/libraries/networking/src/LimitedNodeList.h @@ -1,6 +1,6 @@ // // LimitedNodeList.h -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2/15/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/Logging.cpp b/libraries/networking/src/Logging.cpp similarity index 99% rename from libraries/shared/src/Logging.cpp rename to libraries/networking/src/Logging.cpp index 2625cc744a..17a4706de0 100644 --- a/libraries/shared/src/Logging.cpp +++ b/libraries/networking/src/Logging.cpp @@ -1,6 +1,6 @@ // // Logging.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 6/11/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/Logging.h b/libraries/networking/src/Logging.h similarity index 98% rename from libraries/shared/src/Logging.h rename to libraries/networking/src/Logging.h index edbe8f62ee..b37962e931 100644 --- a/libraries/shared/src/Logging.h +++ b/libraries/networking/src/Logging.h @@ -1,6 +1,6 @@ // // Logging.h -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 6/11/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/NetworkPacket.cpp b/libraries/networking/src/NetworkPacket.cpp similarity index 98% rename from libraries/shared/src/NetworkPacket.cpp rename to libraries/networking/src/NetworkPacket.cpp index b948b10c96..bf18aa9b37 100644 --- a/libraries/shared/src/NetworkPacket.cpp +++ b/libraries/networking/src/NetworkPacket.cpp @@ -1,6 +1,6 @@ // // NetworkPacket.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Brad Hefta-Gaub on 8/9/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/NetworkPacket.h b/libraries/networking/src/NetworkPacket.h similarity index 98% rename from libraries/shared/src/NetworkPacket.h rename to libraries/networking/src/NetworkPacket.h index 6c086e2f5a..94ddf8d56e 100644 --- a/libraries/shared/src/NetworkPacket.h +++ b/libraries/networking/src/NetworkPacket.h @@ -1,6 +1,6 @@ // // NetworkPacket.h -// libraries/shared/src +// libraries/networking/src // // Created by Brad Hefta-Gaub on 8/9/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/Node.cpp b/libraries/networking/src/Node.cpp similarity index 99% rename from libraries/shared/src/Node.cpp rename to libraries/networking/src/Node.cpp index 13f700ad5a..f6445de58d 100644 --- a/libraries/shared/src/Node.cpp +++ b/libraries/networking/src/Node.cpp @@ -1,6 +1,6 @@ // // Node.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2/15/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/Node.h b/libraries/networking/src/Node.h similarity index 99% rename from libraries/shared/src/Node.h rename to libraries/networking/src/Node.h index e7ebbcfb13..6cc8d5bfaf 100644 --- a/libraries/shared/src/Node.h +++ b/libraries/networking/src/Node.h @@ -1,6 +1,6 @@ // // Node.h -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2/15/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/NodeData.cpp b/libraries/networking/src/NodeData.cpp similarity index 92% rename from libraries/shared/src/NodeData.cpp rename to libraries/networking/src/NodeData.cpp index 6b71ef8f37..2e6fa9e8e1 100644 --- a/libraries/shared/src/NodeData.cpp +++ b/libraries/networking/src/NodeData.cpp @@ -1,6 +1,6 @@ // // NodeData.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2/19/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/NodeData.h b/libraries/networking/src/NodeData.h similarity index 95% rename from libraries/shared/src/NodeData.h rename to libraries/networking/src/NodeData.h index 3b26d5b6d5..b865e444a9 100644 --- a/libraries/shared/src/NodeData.h +++ b/libraries/networking/src/NodeData.h @@ -1,6 +1,6 @@ // // NodeData.h -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2/19/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/NodeList.cpp b/libraries/networking/src/NodeList.cpp similarity index 99% rename from libraries/shared/src/NodeList.cpp rename to libraries/networking/src/NodeList.cpp index cb4bacc5f9..93377c7763 100644 --- a/libraries/shared/src/NodeList.cpp +++ b/libraries/networking/src/NodeList.cpp @@ -1,6 +1,6 @@ // // NodeList.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2/15/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/NodeList.h b/libraries/networking/src/NodeList.h similarity index 99% rename from libraries/shared/src/NodeList.h rename to libraries/networking/src/NodeList.h index 06505cc36c..1cc824c294 100644 --- a/libraries/shared/src/NodeList.h +++ b/libraries/networking/src/NodeList.h @@ -1,6 +1,6 @@ // // NodeList.h -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2/15/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/OAuthAccessToken.cpp b/libraries/networking/src/OAuthAccessToken.cpp similarity index 98% rename from libraries/shared/src/OAuthAccessToken.cpp rename to libraries/networking/src/OAuthAccessToken.cpp index ab5ec6462a..365b07a935 100644 --- a/libraries/shared/src/OAuthAccessToken.cpp +++ b/libraries/networking/src/OAuthAccessToken.cpp @@ -1,6 +1,6 @@ // // OAuthAccessToken.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2/18/2014. // Copyright 2014 High Fidelity, Inc. diff --git a/libraries/shared/src/OAuthAccessToken.h b/libraries/networking/src/OAuthAccessToken.h similarity index 97% rename from libraries/shared/src/OAuthAccessToken.h rename to libraries/networking/src/OAuthAccessToken.h index 7f7c621231..36859b79f8 100644 --- a/libraries/shared/src/OAuthAccessToken.h +++ b/libraries/networking/src/OAuthAccessToken.h @@ -1,6 +1,6 @@ // // OAuthAccessToken.h -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 2/18/2014. // Copyright 2014 High Fidelity, Inc. diff --git a/libraries/shared/src/PacketHeaders.cpp b/libraries/networking/src/PacketHeaders.cpp similarity index 99% rename from libraries/shared/src/PacketHeaders.cpp rename to libraries/networking/src/PacketHeaders.cpp index 5916c542dd..fe999fed96 100644 --- a/libraries/shared/src/PacketHeaders.cpp +++ b/libraries/networking/src/PacketHeaders.cpp @@ -1,6 +1,6 @@ // // PacketHeaders.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 6/28/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/PacketHeaders.h b/libraries/networking/src/PacketHeaders.h similarity index 99% rename from libraries/shared/src/PacketHeaders.h rename to libraries/networking/src/PacketHeaders.h index 924445e276..3e2ff3d8b0 100644 --- a/libraries/shared/src/PacketHeaders.h +++ b/libraries/networking/src/PacketHeaders.h @@ -1,6 +1,6 @@ // // PacketHeaders.h -// libraries/shared/src +// libraries/networking/src // // Created by Stephen Birarda on 4/8/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/PacketSender.cpp b/libraries/networking/src/PacketSender.cpp similarity index 99% rename from libraries/shared/src/PacketSender.cpp rename to libraries/networking/src/PacketSender.cpp index 489b083d92..5f7502a738 100644 --- a/libraries/shared/src/PacketSender.cpp +++ b/libraries/networking/src/PacketSender.cpp @@ -1,6 +1,6 @@ // // PacketSender.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Brad Hefta-Gaub on 8/12/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/PacketSender.h b/libraries/networking/src/PacketSender.h similarity index 99% rename from libraries/shared/src/PacketSender.h rename to libraries/networking/src/PacketSender.h index cc65564461..7d2c0dc8aa 100644 --- a/libraries/shared/src/PacketSender.h +++ b/libraries/networking/src/PacketSender.h @@ -1,6 +1,6 @@ // // PacketSender.h -// libraries/shared/src +// libraries/networking/src // // Created by Brad Hefta-Gaub on 8/12/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/ReceivedPacketProcessor.cpp b/libraries/networking/src/ReceivedPacketProcessor.cpp similarity index 98% rename from libraries/shared/src/ReceivedPacketProcessor.cpp rename to libraries/networking/src/ReceivedPacketProcessor.cpp index 8394559524..d54e165285 100644 --- a/libraries/shared/src/ReceivedPacketProcessor.cpp +++ b/libraries/networking/src/ReceivedPacketProcessor.cpp @@ -1,6 +1,6 @@ // // ReceivedPacketProcessor.cpp -// libraries/shared/src +// libraries/networking/src // // Created by Brad Hefta-Gaub on 8/12/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/ReceivedPacketProcessor.h b/libraries/networking/src/ReceivedPacketProcessor.h similarity index 98% rename from libraries/shared/src/ReceivedPacketProcessor.h rename to libraries/networking/src/ReceivedPacketProcessor.h index a34b43626c..f8306b4896 100644 --- a/libraries/shared/src/ReceivedPacketProcessor.h +++ b/libraries/networking/src/ReceivedPacketProcessor.h @@ -1,6 +1,6 @@ // // ReceivedPacketProcessor.h -// libraries/shared/src +// libraries/networking/src // // Created by Brad Hefta-Gaub on 8/12/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/Syssocket.h b/libraries/networking/src/Syssocket.h similarity index 100% rename from libraries/shared/src/Syssocket.h rename to libraries/networking/src/Syssocket.h diff --git a/libraries/shared/src/ThreadedAssignment.cpp b/libraries/networking/src/ThreadedAssignment.cpp similarity index 100% rename from libraries/shared/src/ThreadedAssignment.cpp rename to libraries/networking/src/ThreadedAssignment.cpp diff --git a/libraries/shared/src/ThreadedAssignment.h b/libraries/networking/src/ThreadedAssignment.h similarity index 100% rename from libraries/shared/src/ThreadedAssignment.h rename to libraries/networking/src/ThreadedAssignment.h diff --git a/libraries/octree/CMakeLists.txt b/libraries/octree/CMakeLists.txt index 422089a57d..5f4e66ea11 100644 --- a/libraries/octree/CMakeLists.txt +++ b/libraries/octree/CMakeLists.txt @@ -22,6 +22,7 @@ include_glm(${TARGET_NAME} "${ROOT_DIR}") include(${MACRO_DIR}/LinkHifiLibrary.cmake) link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") +link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") # link ZLIB find_package(ZLIB) diff --git a/libraries/particles/CMakeLists.txt b/libraries/particles/CMakeLists.txt index b483e3e479..e6c554dbdf 100644 --- a/libraries/particles/CMakeLists.txt +++ b/libraries/particles/CMakeLists.txt @@ -23,6 +23,7 @@ include_glm(${TARGET_NAME} "${ROOT_DIR}") include(${MACRO_DIR}/LinkHifiLibrary.cmake) link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(octree ${TARGET_NAME} "${ROOT_DIR}") +link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") # link ZLIB find_package(ZLIB) diff --git a/libraries/shared/CMakeLists.txt b/libraries/shared/CMakeLists.txt index 6b4dafd8d4..7f9a34492d 100644 --- a/libraries/shared/CMakeLists.txt +++ b/libraries/shared/CMakeLists.txt @@ -11,7 +11,6 @@ set(TARGET_NAME shared) project(${TARGET_NAME}) find_package(Qt5 COMPONENTS Network Widgets Xml) -find_package(GnuTLS REQUIRED) include(${MACRO_DIR}/SetupHifiLibrary.cmake) setup_hifi_library(${TARGET_NAME}) @@ -33,5 +32,4 @@ if (UNIX AND NOT APPLE) target_link_libraries(${TARGET_NAME} "${CMAKE_THREAD_LIBS_INIT}") endif (UNIX AND NOT APPLE) -include_directories("${GNUTLS_INCLUDE_DIR}") -target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets "${GNUTLS_LIBRARY}") \ No newline at end of file +target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets) \ No newline at end of file diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index fc54c62d51..42aed77fcb 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -26,7 +26,6 @@ #include #include "OctalCode.h" -#include "PacketHeaders.h" #include "SharedUtil.h" quint64 usecTimestamp(const timeval *time) { diff --git a/libraries/shared/src/SharedUtil.h b/libraries/shared/src/SharedUtil.h index c4abd4965f..f41c5b8aa2 100644 --- a/libraries/shared/src/SharedUtil.h +++ b/libraries/shared/src/SharedUtil.h @@ -30,8 +30,6 @@ #include #endif -#include "PacketHeaders.h" - const int BYTES_PER_COLOR = 3; const int BYTES_PER_FLAGS = 1; typedef unsigned char rgbColor[BYTES_PER_COLOR]; diff --git a/libraries/voxels/CMakeLists.txt b/libraries/voxels/CMakeLists.txt index afc0b34b64..1cb838a6f0 100644 --- a/libraries/voxels/CMakeLists.txt +++ b/libraries/voxels/CMakeLists.txt @@ -24,6 +24,7 @@ include_glm(${TARGET_NAME} "${ROOT_DIR}") include(${MACRO_DIR}/LinkHifiLibrary.cmake) link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(octree ${TARGET_NAME} "${ROOT_DIR}") +link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") # link ZLIB find_package(ZLIB) diff --git a/voxel-edit/CMakeLists.txt b/voxel-edit/CMakeLists.txt index 0de8fd059e..ce3c542691 100644 --- a/voxel-edit/CMakeLists.txt +++ b/voxel-edit/CMakeLists.txt @@ -31,6 +31,9 @@ link_hifi_library(octree ${TARGET_NAME} "${ROOT_DIR}") # link in the hifi voxels library link_hifi_library(voxels ${TARGET_NAME} "${ROOT_DIR}") +# link in the hifi networking library +link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") + IF (WIN32) target_link_libraries(${TARGET_NAME} Winmm Ws2_32) ENDIF(WIN32) From f51b7a78c62ea84bfce04d526ff419b0c79587c4 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 09:32:44 -0700 Subject: [PATCH 301/595] look only in lib for GnuTLS library --- cmake/modules/FindGnuTLS.cmake | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmake/modules/FindGnuTLS.cmake b/cmake/modules/FindGnuTLS.cmake index ac0f30877f..724dcbe171 100644 --- a/cmake/modules/FindGnuTLS.cmake +++ b/cmake/modules/FindGnuTLS.cmake @@ -26,7 +26,7 @@ else () find_path(GNUTLS_INCLUDE_DIR gnutls/gnutls.h PATH_SUFFIXES include HINTS ${GNUTLS_SEARCH_DIRS}) - find_library(GNUTLS_LIBRARY NAMES gnutls libgnutls libgnutls-28 PATH_SUFFIXES lib bin HINTS ${GNUTLS_SEARCH_DIRS}) + find_library(GNUTLS_LIBRARY NAMES gnutls libgnutls libgnutls-28 PATH_SUFFIXES lib HINTS ${GNUTLS_SEARCH_DIRS}) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(GNUTLS DEFAULT_MSG GNUTLS_INCLUDE_DIR GNUTLS_LIBRARY) @@ -35,7 +35,7 @@ else () message(STATUS "If you're generating a MSVC environment, you'll need to run the command") message(STATUS "$GnuTLS-DIR\\bin>lib /def:libgnutls-28.def") message(STATUS "From the MSVC command prompt to generate the .lib file and copy it into") - message(STATUS "your lib folder. Replace $GnuTLS-DIR in the command with the directory") + message(STATUS "the GnuTLS lib folder. Replace $GnuTLS-DIR in the command with the directory") message(STATUS "containing GnuTLS.") endif () endif () \ No newline at end of file From 7e2b73906c5ae6f14434821b825285744a9b0bb3 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 09:35:25 -0700 Subject: [PATCH 302/595] remove Syssocket include from SharedUtil --- libraries/shared/src/SharedUtil.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index 42aed77fcb..9a59bb5493 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -15,10 +15,6 @@ #include #include -#ifdef _WIN32 -#include "Syssocket.h" -#endif - #ifdef __APPLE__ #include #endif From 1d5644a85fb4bbed1e4d213d7690d80618d32a09 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 09:45:57 -0700 Subject: [PATCH 303/595] link GnuTLS to octree library --- animation-server/CMakeLists.txt | 10 +++++++++- domain-server/CMakeLists.txt | 6 +++--- libraries/octree/CMakeLists.txt | 8 +++++--- libraries/shared/src/SharedUtil.cpp | 5 +++++ 4 files changed, 22 insertions(+), 7 deletions(-) diff --git a/animation-server/CMakeLists.txt b/animation-server/CMakeLists.txt index d8fa8d97b2..490e01ffec 100644 --- a/animation-server/CMakeLists.txt +++ b/animation-server/CMakeLists.txt @@ -30,4 +30,12 @@ link_hifi_library(octree ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(voxels ${TARGET_NAME} "${ROOT_DIR}") # link the hifi networking library -link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") \ No newline at end of file +link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") + +find_package(GnuTLS REQUIRED) + +# include the GnuTLS dir +include_directories("${GNUTLS_INCLUDE_DIR}") + +# link GnuTLS +target_link_libraries(${TARGET_NAME} "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/domain-server/CMakeLists.txt b/domain-server/CMakeLists.txt index 0db22542b0..c960005995 100644 --- a/domain-server/CMakeLists.txt +++ b/domain-server/CMakeLists.txt @@ -38,12 +38,12 @@ link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(embedded-webserver ${TARGET_NAME} "${ROOT_DIR}") -# include the QCA dir -include_directories(GNUTLS_INCLUDE_DIR) +# include the GnuTLS dir +include_directories("${GNUTLS_INCLUDE_DIR}") IF (WIN32) target_link_libraries(${TARGET_NAME} Winmm Ws2_32) ENDIF(WIN32) -# link QtNetwork and QCA +# link QtNetwork and GnuTLS target_link_libraries(${TARGET_NAME} Qt5::Network "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/octree/CMakeLists.txt b/libraries/octree/CMakeLists.txt index 5f4e66ea11..a4758e52f3 100644 --- a/libraries/octree/CMakeLists.txt +++ b/libraries/octree/CMakeLists.txt @@ -24,8 +24,10 @@ include(${MACRO_DIR}/LinkHifiLibrary.cmake) link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") -# link ZLIB +# link ZLIB and GnuTLS find_package(ZLIB) -include_directories("${ZLIB_INCLUDE_DIRS}") +find_package(GnuTLS REQUIRED) -target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" Qt5::Widgets) +include_directories("${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") + +target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" Qt5::Widgets "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index 9a59bb5493..0eecd00333 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -15,6 +15,11 @@ #include #include +#ifdef _WIN32 +#ifndef _timeval_ +#define _timeval_ +#endif + #ifdef __APPLE__ #include #endif From 58298984d35520bfe38697b2395158711b4e8124 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 09:48:47 -0700 Subject: [PATCH 304/595] link GnuTLS to the assignment-client, fix timeval in SharedUtil --- assignment-client/CMakeLists.txt | 5 ++++- libraries/shared/src/SharedUtil.cpp | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/assignment-client/CMakeLists.txt b/assignment-client/CMakeLists.txt index fa8d23051a..4930c2ace1 100644 --- a/assignment-client/CMakeLists.txt +++ b/assignment-client/CMakeLists.txt @@ -34,6 +34,9 @@ link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(script-engine ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(embedded-webserver ${TARGET_NAME} "${ROOT_DIR}") +find_package(GnuTLS REQUIRED) +include_directories("${GNUTLS_INCLUDE_DIR}") + if (UNIX) target_link_libraries(${TARGET_NAME} ${CMAKE_DL_LIBS}) endif (UNIX) @@ -42,4 +45,4 @@ IF (WIN32) target_link_libraries(${TARGET_NAME} Winmm Ws2_32) ENDIF(WIN32) -target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets Qt5::Script) \ No newline at end of file +target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets Qt5::Script "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index 0eecd00333..7be21dfb52 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -15,7 +15,7 @@ #include #include -#ifdef _WIN32 +#ifdef WIN32 #ifndef _timeval_ #define _timeval_ #endif From ba6f861ad8b4cadcfc9ff54f61b4cdfa16032f0b Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 09:54:37 -0700 Subject: [PATCH 305/595] fix unmatched #ifdef in Syssocket --- libraries/networking/src/Syssocket.h | 3 --- libraries/shared/src/SharedUtil.cpp | 5 +++-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/libraries/networking/src/Syssocket.h b/libraries/networking/src/Syssocket.h index 36713a2b7b..7d7955426f 100644 --- a/libraries/networking/src/Syssocket.h +++ b/libraries/networking/src/Syssocket.h @@ -4,9 +4,6 @@ #ifdef _WIN32 #define WINSOCK_API_LINKAGE #include -#ifndef _timeval_ -#define _timeval_ -#endif typedef SSIZE_T ssize_t; typedef ULONG32 in_addr_t; typedef USHORT in_port_t; diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index 7be21dfb52..3569c700ed 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -15,10 +15,11 @@ #include #include -#ifdef WIN32 +#ifdef _WIN32 #ifndef _timeval_ #define _timeval_ #endif +#endif #ifdef __APPLE__ #include @@ -44,7 +45,7 @@ quint64 usecTimestampNow() { return (now.tv_sec * 1000000 + now.tv_usec) + ::usecTimestampNowAdjust; } -float randFloat () { +float randFloat() { return (rand() % 10000)/10000.f; } From 68c445e7183a74930fc1534fb8cb8f06bc57d732 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 10:00:10 -0700 Subject: [PATCH 306/595] link GnuTLS to targets linking the networking library --- interface/CMakeLists.txt | 4 +++- libraries/audio/CMakeLists.txt | 7 ++++++- libraries/avatars/CMakeLists.txt | 4 +++- libraries/metavoxels/CMakeLists.txt | 4 +++- libraries/particles/CMakeLists.txt | 7 ++++--- libraries/voxels/CMakeLists.txt | 8 +++++--- voxel-edit/CMakeLists.txt | 6 +++++- 7 files changed, 29 insertions(+), 11 deletions(-) diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index 6a3186bb70..d435f048ab 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -67,6 +67,7 @@ foreach(EXTERNAL_SOURCE_SUBDIR ${EXTERNAL_SOURCE_SUBDIRS}) endforeach(EXTERNAL_SOURCE_SUBDIR) find_package(Qt5 COMPONENTS Core Gui Multimedia Network OpenGL Script Svg WebKit WebKitWidgets Xml UiTools) +find_package(GnuTLS REQUIRED) # grab the ui files in resources/ui file (GLOB_RECURSE QT_UI_FILES ui/*.ui) @@ -189,7 +190,7 @@ include_directories("${PROJECT_SOURCE_DIR}/src" "${PROJECT_BINARY_DIR}/includes" # include external library headers # use system flag so warnings are supressed -include_directories(SYSTEM "${FACESHIFT_INCLUDE_DIRS}") +include_directories(SYSTEM "${FACESHIFT_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") target_link_libraries( ${TARGET_NAME} @@ -197,6 +198,7 @@ target_link_libraries( "${ZLIB_LIBRARIES}" Qt5::Core Qt5::Gui Qt5::Multimedia Qt5::Network Qt5::OpenGL Qt5::Script Qt5::Svg Qt5::WebKit Qt5::WebKitWidgets Qt5::Xml Qt5::UiTools + "${GNUTLS_LIBRARY}" ) if (APPLE) diff --git a/libraries/audio/CMakeLists.txt b/libraries/audio/CMakeLists.txt index 0bf0ba9904..213e04c43a 100644 --- a/libraries/audio/CMakeLists.txt +++ b/libraries/audio/CMakeLists.txt @@ -21,4 +21,9 @@ include_glm(${TARGET_NAME} "${ROOT_DIR}") include(${MACRO_DIR}/LinkHifiLibrary.cmake) link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") -link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") \ No newline at end of file +link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") + +# link GnuTLS +find_package(GnuTLS REQUIRED) +include_directories("${GNUTLS_INCLUDE_DIR}") +target_link_libraries(${TARGET_NAME} "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/avatars/CMakeLists.txt b/libraries/avatars/CMakeLists.txt index 9816282dda..fe31eb6a06 100644 --- a/libraries/avatars/CMakeLists.txt +++ b/libraries/avatars/CMakeLists.txt @@ -28,4 +28,6 @@ link_hifi_library(octree ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(voxels ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") -target_link_libraries(${TARGET_NAME} Qt5::Script) \ No newline at end of file +find_package(GnuTLS REQUIRED) +include_directories("${GNUTLS_INCLUDE_DIR}") +target_link_libraries(${TARGET_NAME} Qt5::Script "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/metavoxels/CMakeLists.txt b/libraries/metavoxels/CMakeLists.txt index 7a8319815a..4ef9fcc9cb 100644 --- a/libraries/metavoxels/CMakeLists.txt +++ b/libraries/metavoxels/CMakeLists.txt @@ -27,4 +27,6 @@ link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") include(${MACRO_DIR}/IncludeGLM.cmake) include_glm(${TARGET_NAME} "${ROOT_DIR}") -target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets Qt5::Script) \ No newline at end of file +find_package(GnuTLS REQUIRED) +include_directories("${GNUTLS_INCLUDE_DIR}") +target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets Qt5::Script "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/particles/CMakeLists.txt b/libraries/particles/CMakeLists.txt index e6c554dbdf..4df0859195 100644 --- a/libraries/particles/CMakeLists.txt +++ b/libraries/particles/CMakeLists.txt @@ -25,8 +25,9 @@ link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(octree ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") -# link ZLIB +# link ZLIB and GnuTLS find_package(ZLIB) -include_directories("${ZLIB_INCLUDE_DIRS}") +find_package(GnuTLS REQUIRED) -target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" Qt5::Widgets) +include_directories("${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") +target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" Qt5::Widgets "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/voxels/CMakeLists.txt b/libraries/voxels/CMakeLists.txt index 1cb838a6f0..68ce7c13aa 100644 --- a/libraries/voxels/CMakeLists.txt +++ b/libraries/voxels/CMakeLists.txt @@ -26,8 +26,10 @@ link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(octree ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") -# link ZLIB +# link ZLIB and GnuTLS find_package(ZLIB) -include_directories("${ZLIB_INCLUDE_DIRS}") +find_package(GnuTLS REQUIRED) -target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" Qt5::Widgets Qt5::Script) +include_directories("${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") + +target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" "${GNUTLS_LIBRARY}" Qt5::Widgets Qt5::Script) \ No newline at end of file diff --git a/voxel-edit/CMakeLists.txt b/voxel-edit/CMakeLists.txt index ce3c542691..883b1debe4 100644 --- a/voxel-edit/CMakeLists.txt +++ b/voxel-edit/CMakeLists.txt @@ -34,8 +34,12 @@ link_hifi_library(voxels ${TARGET_NAME} "${ROOT_DIR}") # link in the hifi networking library link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") +# link GnuTLS +find_package(GnuTLS REQUIRED) +include_directories("${GNUTLS_INCLUDE_DIR}") + IF (WIN32) target_link_libraries(${TARGET_NAME} Winmm Ws2_32) ENDIF(WIN32) -target_link_libraries(${TARGET_NAME} Qt5::Script) \ No newline at end of file +target_link_libraries(${TARGET_NAME} Qt5::Script "${GNUTLS_LIBRARY}") \ No newline at end of file From 16bb28a4fa53bde55af503f4c615bf5c032e4a81 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 10:04:02 -0700 Subject: [PATCH 307/595] make GnuTLS a system include to suppress warnings --- animation-server/CMakeLists.txt | 2 +- assignment-client/CMakeLists.txt | 2 +- domain-server/CMakeLists.txt | 2 +- libraries/audio/CMakeLists.txt | 2 +- libraries/avatars/CMakeLists.txt | 2 +- libraries/metavoxels/CMakeLists.txt | 2 +- libraries/networking/CMakeLists.txt | 2 +- libraries/octree/CMakeLists.txt | 2 +- libraries/particles/CMakeLists.txt | 2 +- libraries/voxels/CMakeLists.txt | 2 +- voxel-edit/CMakeLists.txt | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) diff --git a/animation-server/CMakeLists.txt b/animation-server/CMakeLists.txt index 490e01ffec..80544c103a 100644 --- a/animation-server/CMakeLists.txt +++ b/animation-server/CMakeLists.txt @@ -35,7 +35,7 @@ link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") find_package(GnuTLS REQUIRED) # include the GnuTLS dir -include_directories("${GNUTLS_INCLUDE_DIR}") +include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") # link GnuTLS target_link_libraries(${TARGET_NAME} "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/assignment-client/CMakeLists.txt b/assignment-client/CMakeLists.txt index 4930c2ace1..ce2c6b6d4e 100644 --- a/assignment-client/CMakeLists.txt +++ b/assignment-client/CMakeLists.txt @@ -35,7 +35,7 @@ link_hifi_library(script-engine ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(embedded-webserver ${TARGET_NAME} "${ROOT_DIR}") find_package(GnuTLS REQUIRED) -include_directories("${GNUTLS_INCLUDE_DIR}") +include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") if (UNIX) target_link_libraries(${TARGET_NAME} ${CMAKE_DL_LIBS}) diff --git a/domain-server/CMakeLists.txt b/domain-server/CMakeLists.txt index c960005995..5388d5d8e0 100644 --- a/domain-server/CMakeLists.txt +++ b/domain-server/CMakeLists.txt @@ -39,7 +39,7 @@ link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(embedded-webserver ${TARGET_NAME} "${ROOT_DIR}") # include the GnuTLS dir -include_directories("${GNUTLS_INCLUDE_DIR}") +include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") IF (WIN32) target_link_libraries(${TARGET_NAME} Winmm Ws2_32) diff --git a/libraries/audio/CMakeLists.txt b/libraries/audio/CMakeLists.txt index 213e04c43a..e34dfa65f5 100644 --- a/libraries/audio/CMakeLists.txt +++ b/libraries/audio/CMakeLists.txt @@ -25,5 +25,5 @@ link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") # link GnuTLS find_package(GnuTLS REQUIRED) -include_directories("${GNUTLS_INCLUDE_DIR}") +include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") target_link_libraries(${TARGET_NAME} "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/avatars/CMakeLists.txt b/libraries/avatars/CMakeLists.txt index fe31eb6a06..c4eff1c45b 100644 --- a/libraries/avatars/CMakeLists.txt +++ b/libraries/avatars/CMakeLists.txt @@ -29,5 +29,5 @@ link_hifi_library(voxels ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") find_package(GnuTLS REQUIRED) -include_directories("${GNUTLS_INCLUDE_DIR}") +include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") target_link_libraries(${TARGET_NAME} Qt5::Script "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/metavoxels/CMakeLists.txt b/libraries/metavoxels/CMakeLists.txt index 4ef9fcc9cb..220cca1f11 100644 --- a/libraries/metavoxels/CMakeLists.txt +++ b/libraries/metavoxels/CMakeLists.txt @@ -28,5 +28,5 @@ include(${MACRO_DIR}/IncludeGLM.cmake) include_glm(${TARGET_NAME} "${ROOT_DIR}") find_package(GnuTLS REQUIRED) -include_directories("${GNUTLS_INCLUDE_DIR}") +include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets Qt5::Script "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/networking/CMakeLists.txt b/libraries/networking/CMakeLists.txt index 101e739fea..56e937e0d7 100644 --- a/libraries/networking/CMakeLists.txt +++ b/libraries/networking/CMakeLists.txt @@ -20,5 +20,5 @@ setup_hifi_library(${TARGET_NAME}) include(${MACRO_DIR}/IncludeGLM.cmake) include_glm(${TARGET_NAME} "${ROOT_DIR}") -include_directories("${GNUTLS_INCLUDE_DIR}") +include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") target_link_libraries(${TARGET_NAME} Qt5::Network "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/octree/CMakeLists.txt b/libraries/octree/CMakeLists.txt index a4758e52f3..9118ee6215 100644 --- a/libraries/octree/CMakeLists.txt +++ b/libraries/octree/CMakeLists.txt @@ -28,6 +28,6 @@ link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") find_package(ZLIB) find_package(GnuTLS REQUIRED) -include_directories("${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") +include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" Qt5::Widgets "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/particles/CMakeLists.txt b/libraries/particles/CMakeLists.txt index 4df0859195..2cd5a1644b 100644 --- a/libraries/particles/CMakeLists.txt +++ b/libraries/particles/CMakeLists.txt @@ -29,5 +29,5 @@ link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") find_package(ZLIB) find_package(GnuTLS REQUIRED) -include_directories("${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") +include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" Qt5::Widgets "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/voxels/CMakeLists.txt b/libraries/voxels/CMakeLists.txt index 68ce7c13aa..c39525e279 100644 --- a/libraries/voxels/CMakeLists.txt +++ b/libraries/voxels/CMakeLists.txt @@ -30,6 +30,6 @@ link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") find_package(ZLIB) find_package(GnuTLS REQUIRED) -include_directories("${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") +include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" "${GNUTLS_LIBRARY}" Qt5::Widgets Qt5::Script) \ No newline at end of file diff --git a/voxel-edit/CMakeLists.txt b/voxel-edit/CMakeLists.txt index 883b1debe4..0717aea479 100644 --- a/voxel-edit/CMakeLists.txt +++ b/voxel-edit/CMakeLists.txt @@ -36,7 +36,7 @@ link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") # link GnuTLS find_package(GnuTLS REQUIRED) -include_directories("${GNUTLS_INCLUDE_DIR}") +include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") IF (WIN32) target_link_libraries(${TARGET_NAME} Winmm Ws2_32) From 11cce7640e4d339cf2e7f7b43bd90b20f8b53056 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 10:12:09 -0700 Subject: [PATCH 308/595] link to GnuTLS library from script-engine --- libraries/script-engine/CMakeLists.txt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/libraries/script-engine/CMakeLists.txt b/libraries/script-engine/CMakeLists.txt index 615000e260..f1bdde1b93 100644 --- a/libraries/script-engine/CMakeLists.txt +++ b/libraries/script-engine/CMakeLists.txt @@ -28,6 +28,7 @@ link_hifi_library(particles ${TARGET_NAME} "${ROOT_DIR}") # link ZLIB find_package(ZLIB) -include_directories("${ZLIB_INCLUDE_DIRS}") +find_package(GnuTLS REQUIRED) +include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIRS}") -target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" Qt5::Widgets) +target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" "${GNUTLS_LIBRARY}" Qt5::Widgets) From 4e2e3b7b6d4ab6bafe1f11af73e86dee45e69614 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 10:15:18 -0700 Subject: [PATCH 309/595] fix GnuTLS include dir variable name --- libraries/script-engine/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/script-engine/CMakeLists.txt b/libraries/script-engine/CMakeLists.txt index f1bdde1b93..78f698a7d1 100644 --- a/libraries/script-engine/CMakeLists.txt +++ b/libraries/script-engine/CMakeLists.txt @@ -29,6 +29,6 @@ link_hifi_library(particles ${TARGET_NAME} "${ROOT_DIR}") # link ZLIB find_package(ZLIB) find_package(GnuTLS REQUIRED) -include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIRS}") +include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" "${GNUTLS_LIBRARY}" Qt5::Widgets) From 2518d314ac8f329b36ce120fb92cd515c1bd948a Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 10:19:45 -0700 Subject: [PATCH 310/595] add ssize_t definition for gnutls.h include on Windows --- animation-server/CMakeLists.txt | 5 +++++ assignment-client/CMakeLists.txt | 5 +++++ domain-server/CMakeLists.txt | 5 +++++ interface/CMakeLists.txt | 5 +++++ libraries/audio/CMakeLists.txt | 6 ++++++ libraries/avatars/CMakeLists.txt | 6 ++++++ libraries/metavoxels/CMakeLists.txt | 6 ++++++ libraries/octree/CMakeLists.txt | 5 +++++ libraries/particles/CMakeLists.txt | 6 ++++++ libraries/script-engine/CMakeLists.txt | 5 +++++ libraries/voxels/CMakeLists.txt | 5 +++++ voxel-edit/CMakeLists.txt | 3 +++ 12 files changed, 62 insertions(+) diff --git a/animation-server/CMakeLists.txt b/animation-server/CMakeLists.txt index 80544c103a..5d9f3604bc 100644 --- a/animation-server/CMakeLists.txt +++ b/animation-server/CMakeLists.txt @@ -37,5 +37,10 @@ find_package(GnuTLS REQUIRED) # include the GnuTLS dir include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") +# add a definition for ssize_t so that windows doesn't bail on gnutls.h +if (WIN32) + add_definitions(-Dssize_t=long) +endif () + # link GnuTLS target_link_libraries(${TARGET_NAME} "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/assignment-client/CMakeLists.txt b/assignment-client/CMakeLists.txt index ce2c6b6d4e..d63d09520a 100644 --- a/assignment-client/CMakeLists.txt +++ b/assignment-client/CMakeLists.txt @@ -37,6 +37,11 @@ link_hifi_library(embedded-webserver ${TARGET_NAME} "${ROOT_DIR}") find_package(GnuTLS REQUIRED) include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") +# add a definition for ssize_t so that windows doesn't bail on gnutls.h +if (WIN32) + add_definitions(-Dssize_t=long) +endif () + if (UNIX) target_link_libraries(${TARGET_NAME} ${CMAKE_DL_LIBS}) endif (UNIX) diff --git a/domain-server/CMakeLists.txt b/domain-server/CMakeLists.txt index 5388d5d8e0..4736c2438b 100644 --- a/domain-server/CMakeLists.txt +++ b/domain-server/CMakeLists.txt @@ -41,6 +41,11 @@ link_hifi_library(embedded-webserver ${TARGET_NAME} "${ROOT_DIR}") # include the GnuTLS dir include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") +# add a definition for ssize_t so that windows doesn't bail on gnutls.h +if (WIN32) + add_definitions(-Dssize_t=long) +endif () + IF (WIN32) target_link_libraries(${TARGET_NAME} Winmm Ws2_32) ENDIF(WIN32) diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index d435f048ab..d205719c21 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -192,6 +192,11 @@ include_directories("${PROJECT_SOURCE_DIR}/src" "${PROJECT_BINARY_DIR}/includes" # use system flag so warnings are supressed include_directories(SYSTEM "${FACESHIFT_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") +# add a definition for ssize_t so that windows doesn't bail on gnutls.h +if (WIN32) + add_definitions(-Dssize_t=long) +endif () + target_link_libraries( ${TARGET_NAME} "${FACESHIFT_LIBRARIES}" diff --git a/libraries/audio/CMakeLists.txt b/libraries/audio/CMakeLists.txt index e34dfa65f5..d5cd02f083 100644 --- a/libraries/audio/CMakeLists.txt +++ b/libraries/audio/CMakeLists.txt @@ -26,4 +26,10 @@ link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") # link GnuTLS find_package(GnuTLS REQUIRED) include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") + +# add a definition for ssize_t so that windows doesn't bail on gnutls.h +if (WIN32) + add_definitions(-Dssize_t=long) +endif () + target_link_libraries(${TARGET_NAME} "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/avatars/CMakeLists.txt b/libraries/avatars/CMakeLists.txt index c4eff1c45b..8c6b6417a1 100644 --- a/libraries/avatars/CMakeLists.txt +++ b/libraries/avatars/CMakeLists.txt @@ -30,4 +30,10 @@ link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") find_package(GnuTLS REQUIRED) include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") + +# add a definition for ssize_t so that windows doesn't bail on gnutls.h +if (WIN32) + add_definitions(-Dssize_t=long) +endif () + target_link_libraries(${TARGET_NAME} Qt5::Script "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/metavoxels/CMakeLists.txt b/libraries/metavoxels/CMakeLists.txt index 220cca1f11..6d88006d84 100644 --- a/libraries/metavoxels/CMakeLists.txt +++ b/libraries/metavoxels/CMakeLists.txt @@ -29,4 +29,10 @@ include_glm(${TARGET_NAME} "${ROOT_DIR}") find_package(GnuTLS REQUIRED) include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") + +# add a definition for ssize_t so that windows doesn't bail on gnutls.h +if (WIN32) + add_definitions(-Dssize_t=long) +endif () + target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets Qt5::Script "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/octree/CMakeLists.txt b/libraries/octree/CMakeLists.txt index 9118ee6215..0d2cb330b6 100644 --- a/libraries/octree/CMakeLists.txt +++ b/libraries/octree/CMakeLists.txt @@ -30,4 +30,9 @@ find_package(GnuTLS REQUIRED) include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") +# add a definition for ssize_t so that windows doesn't bail on gnutls.h +if (WIN32) + add_definitions(-Dssize_t=long) +endif () + target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" Qt5::Widgets "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/particles/CMakeLists.txt b/libraries/particles/CMakeLists.txt index 2cd5a1644b..fa97f87854 100644 --- a/libraries/particles/CMakeLists.txt +++ b/libraries/particles/CMakeLists.txt @@ -30,4 +30,10 @@ find_package(ZLIB) find_package(GnuTLS REQUIRED) include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") + +# add a definition for ssize_t so that windows doesn't bail on gnutls.h +if (WIN32) + add_definitions(-Dssize_t=long) +endif () + target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" Qt5::Widgets "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/script-engine/CMakeLists.txt b/libraries/script-engine/CMakeLists.txt index 78f698a7d1..414ac1e9eb 100644 --- a/libraries/script-engine/CMakeLists.txt +++ b/libraries/script-engine/CMakeLists.txt @@ -31,4 +31,9 @@ find_package(ZLIB) find_package(GnuTLS REQUIRED) include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") +# add a definition for ssize_t so that windows doesn't bail on gnutls.h +if (WIN32) + add_definitions(-Dssize_t=long) +endif () + target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" "${GNUTLS_LIBRARY}" Qt5::Widgets) diff --git a/libraries/voxels/CMakeLists.txt b/libraries/voxels/CMakeLists.txt index c39525e279..dc13603450 100644 --- a/libraries/voxels/CMakeLists.txt +++ b/libraries/voxels/CMakeLists.txt @@ -32,4 +32,9 @@ find_package(GnuTLS REQUIRED) include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") +# add a definition for ssize_t so that windows doesn't bail on gnutls.h +if (WIN32) + add_definitions(-Dssize_t=long) +endif () + target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" "${GNUTLS_LIBRARY}" Qt5::Widgets Qt5::Script) \ No newline at end of file diff --git a/voxel-edit/CMakeLists.txt b/voxel-edit/CMakeLists.txt index 0717aea479..65e82932b2 100644 --- a/voxel-edit/CMakeLists.txt +++ b/voxel-edit/CMakeLists.txt @@ -40,6 +40,9 @@ include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") IF (WIN32) target_link_libraries(${TARGET_NAME} Winmm Ws2_32) + + # add a definition for ssize_t so that windows doesn't bail on gnutls.h + add_definitions(-Dssize_t=long) ENDIF(WIN32) target_link_libraries(${TARGET_NAME} Qt5::Script "${GNUTLS_LIBRARY}") \ No newline at end of file From 54647f0f085f34e964ceb485bf959165713e0097 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 10:27:08 -0700 Subject: [PATCH 311/595] make sure gnutls define for ssize_t comes before gnutls include --- assignment-client/CMakeLists.txt | 3 ++- interface/CMakeLists.txt | 8 ++++---- libraries/audio/CMakeLists.txt | 2 +- libraries/avatars/CMakeLists.txt | 3 ++- libraries/metavoxels/CMakeLists.txt | 2 +- libraries/networking/CMakeLists.txt | 5 +++++ libraries/octree/CMakeLists.txt | 4 ++-- libraries/particles/CMakeLists.txt | 3 +-- libraries/script-engine/CMakeLists.txt | 4 ++-- libraries/voxels/CMakeLists.txt | 4 ++-- voxel-edit/CMakeLists.txt | 3 ++- 11 files changed, 24 insertions(+), 17 deletions(-) diff --git a/assignment-client/CMakeLists.txt b/assignment-client/CMakeLists.txt index d63d09520a..a8343e94ad 100644 --- a/assignment-client/CMakeLists.txt +++ b/assignment-client/CMakeLists.txt @@ -35,13 +35,14 @@ link_hifi_library(script-engine ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(embedded-webserver ${TARGET_NAME} "${ROOT_DIR}") find_package(GnuTLS REQUIRED) -include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") # add a definition for ssize_t so that windows doesn't bail on gnutls.h if (WIN32) add_definitions(-Dssize_t=long) endif () +include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") + if (UNIX) target_link_libraries(${TARGET_NAME} ${CMAKE_DL_LIBS}) endif (UNIX) diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index d205719c21..6b1a0e81f9 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -188,15 +188,15 @@ endif (QXMPP_FOUND AND NOT DISABLE_QXMPP) # include headers for interface and InterfaceConfig. include_directories("${PROJECT_SOURCE_DIR}/src" "${PROJECT_BINARY_DIR}/includes") -# include external library headers -# use system flag so warnings are supressed -include_directories(SYSTEM "${FACESHIFT_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") - # add a definition for ssize_t so that windows doesn't bail on gnutls.h if (WIN32) add_definitions(-Dssize_t=long) endif () +# include external library headers +# use system flag so warnings are supressed +include_directories(SYSTEM "${FACESHIFT_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") + target_link_libraries( ${TARGET_NAME} "${FACESHIFT_LIBRARIES}" diff --git a/libraries/audio/CMakeLists.txt b/libraries/audio/CMakeLists.txt index d5cd02f083..d946ae5b34 100644 --- a/libraries/audio/CMakeLists.txt +++ b/libraries/audio/CMakeLists.txt @@ -25,11 +25,11 @@ link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") # link GnuTLS find_package(GnuTLS REQUIRED) -include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") # add a definition for ssize_t so that windows doesn't bail on gnutls.h if (WIN32) add_definitions(-Dssize_t=long) endif () +include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") target_link_libraries(${TARGET_NAME} "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/avatars/CMakeLists.txt b/libraries/avatars/CMakeLists.txt index 8c6b6417a1..3fa1ebcfe2 100644 --- a/libraries/avatars/CMakeLists.txt +++ b/libraries/avatars/CMakeLists.txt @@ -29,11 +29,12 @@ link_hifi_library(voxels ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") find_package(GnuTLS REQUIRED) -include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") # add a definition for ssize_t so that windows doesn't bail on gnutls.h if (WIN32) add_definitions(-Dssize_t=long) endif () + +include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") target_link_libraries(${TARGET_NAME} Qt5::Script "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/metavoxels/CMakeLists.txt b/libraries/metavoxels/CMakeLists.txt index 6d88006d84..e2a90cb085 100644 --- a/libraries/metavoxels/CMakeLists.txt +++ b/libraries/metavoxels/CMakeLists.txt @@ -28,11 +28,11 @@ include(${MACRO_DIR}/IncludeGLM.cmake) include_glm(${TARGET_NAME} "${ROOT_DIR}") find_package(GnuTLS REQUIRED) -include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") # add a definition for ssize_t so that windows doesn't bail on gnutls.h if (WIN32) add_definitions(-Dssize_t=long) endif () +include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets Qt5::Script "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/networking/CMakeLists.txt b/libraries/networking/CMakeLists.txt index 56e937e0d7..6d805cae6c 100644 --- a/libraries/networking/CMakeLists.txt +++ b/libraries/networking/CMakeLists.txt @@ -20,5 +20,10 @@ setup_hifi_library(${TARGET_NAME}) include(${MACRO_DIR}/IncludeGLM.cmake) include_glm(${TARGET_NAME} "${ROOT_DIR}") +# add a definition for ssize_t so that windows doesn't bail on gnutls.h +if (WIN32) + add_definitions(-Dssize_t=long) +endif () + include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") target_link_libraries(${TARGET_NAME} Qt5::Network "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/octree/CMakeLists.txt b/libraries/octree/CMakeLists.txt index 0d2cb330b6..88554ed5f8 100644 --- a/libraries/octree/CMakeLists.txt +++ b/libraries/octree/CMakeLists.txt @@ -28,11 +28,11 @@ link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") find_package(ZLIB) find_package(GnuTLS REQUIRED) -include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") - # add a definition for ssize_t so that windows doesn't bail on gnutls.h if (WIN32) add_definitions(-Dssize_t=long) endif () + +include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" Qt5::Widgets "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/particles/CMakeLists.txt b/libraries/particles/CMakeLists.txt index fa97f87854..26d2b7fc26 100644 --- a/libraries/particles/CMakeLists.txt +++ b/libraries/particles/CMakeLists.txt @@ -29,11 +29,10 @@ link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") find_package(ZLIB) find_package(GnuTLS REQUIRED) -include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") - # add a definition for ssize_t so that windows doesn't bail on gnutls.h if (WIN32) add_definitions(-Dssize_t=long) endif () +include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" Qt5::Widgets "${GNUTLS_LIBRARY}") \ No newline at end of file diff --git a/libraries/script-engine/CMakeLists.txt b/libraries/script-engine/CMakeLists.txt index 414ac1e9eb..20569e2fe0 100644 --- a/libraries/script-engine/CMakeLists.txt +++ b/libraries/script-engine/CMakeLists.txt @@ -29,11 +29,11 @@ link_hifi_library(particles ${TARGET_NAME} "${ROOT_DIR}") # link ZLIB find_package(ZLIB) find_package(GnuTLS REQUIRED) -include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") # add a definition for ssize_t so that windows doesn't bail on gnutls.h if (WIN32) add_definitions(-Dssize_t=long) endif () -target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" "${GNUTLS_LIBRARY}" Qt5::Widgets) +include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") +target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" "${GNUTLS_LIBRARY}" Qt5::Widgets) \ No newline at end of file diff --git a/libraries/voxels/CMakeLists.txt b/libraries/voxels/CMakeLists.txt index dc13603450..bdba388594 100644 --- a/libraries/voxels/CMakeLists.txt +++ b/libraries/voxels/CMakeLists.txt @@ -30,11 +30,11 @@ link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") find_package(ZLIB) find_package(GnuTLS REQUIRED) -include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") - # add a definition for ssize_t so that windows doesn't bail on gnutls.h if (WIN32) add_definitions(-Dssize_t=long) endif () + +include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" "${GNUTLS_LIBRARY}" Qt5::Widgets Qt5::Script) \ No newline at end of file diff --git a/voxel-edit/CMakeLists.txt b/voxel-edit/CMakeLists.txt index 65e82932b2..cc0a122bf0 100644 --- a/voxel-edit/CMakeLists.txt +++ b/voxel-edit/CMakeLists.txt @@ -36,7 +36,6 @@ link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") # link GnuTLS find_package(GnuTLS REQUIRED) -include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") IF (WIN32) target_link_libraries(${TARGET_NAME} Winmm Ws2_32) @@ -45,4 +44,6 @@ IF (WIN32) add_definitions(-Dssize_t=long) ENDIF(WIN32) +include_directories(SYSTEM "${GNUTLS_INCLUDE_DIR}") + target_link_libraries(${TARGET_NAME} Qt5::Script "${GNUTLS_LIBRARY}") \ No newline at end of file From 7cef2def66e70d68bc30f994e62b52bd03190371 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 10:34:31 -0700 Subject: [PATCH 312/595] remove Syssocket which is from our pre-Qt days --- assignment-client/src/audio/AudioMixer.cpp | 1 - libraries/networking/src/LimitedNodeList.h | 5 ----- libraries/networking/src/Node.cpp | 6 ------ libraries/networking/src/NodeList.h | 5 ----- libraries/networking/src/Syssocket.h | 15 --------------- 5 files changed, 32 deletions(-) delete mode 100644 libraries/networking/src/Syssocket.h diff --git a/assignment-client/src/audio/AudioMixer.cpp b/assignment-client/src/audio/AudioMixer.cpp index 779e56af9e..407a64d7a8 100644 --- a/assignment-client/src/audio/AudioMixer.cpp +++ b/assignment-client/src/audio/AudioMixer.cpp @@ -21,7 +21,6 @@ #include #ifdef _WIN32 -#include "Syssocket.h" #include "Systime.h" #include #else diff --git a/libraries/networking/src/LimitedNodeList.h b/libraries/networking/src/LimitedNodeList.h index 7fc0346a74..f941a8aa5d 100644 --- a/libraries/networking/src/LimitedNodeList.h +++ b/libraries/networking/src/LimitedNodeList.h @@ -12,11 +12,6 @@ #ifndef hifi_LimitedNodeList_h #define hifi_LimitedNodeList_h -#ifdef _WIN32 -#include "Syssocket.h" -#else -#include -#endif #include #include diff --git a/libraries/networking/src/Node.cpp b/libraries/networking/src/Node.cpp index f6445de58d..9e6ea0dfec 100644 --- a/libraries/networking/src/Node.cpp +++ b/libraries/networking/src/Node.cpp @@ -12,12 +12,6 @@ #include #include -#ifdef _WIN32 -#include "Syssocket.h" -#else -#include // not available on windows, apparently not needed on mac -#endif - #include "Node.h" #include "SharedUtil.h" diff --git a/libraries/networking/src/NodeList.h b/libraries/networking/src/NodeList.h index 1cc824c294..c55f08e7f0 100644 --- a/libraries/networking/src/NodeList.h +++ b/libraries/networking/src/NodeList.h @@ -12,11 +12,6 @@ #ifndef hifi_NodeList_h #define hifi_NodeList_h -#ifdef _WIN32 -#include "Syssocket.h" -#else -#include -#endif #include #include diff --git a/libraries/networking/src/Syssocket.h b/libraries/networking/src/Syssocket.h deleted file mode 100644 index 7d7955426f..0000000000 --- a/libraries/networking/src/Syssocket.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef __Syssocket__ -#define __Syssocket__ - -#ifdef _WIN32 -#define WINSOCK_API_LINKAGE -#include -typedef SSIZE_T ssize_t; -typedef ULONG32 in_addr_t; -typedef USHORT in_port_t; -typedef USHORT uint16_t; -typedef ULONG32 socklen_t; - -#endif _Win32 - -#endif __Syssocket__ \ No newline at end of file From 8b19982e61754bf72c4b324151794416d754f4e7 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 10:36:30 -0700 Subject: [PATCH 313/595] commit missing Syssocket removals to Node and Logging --- libraries/networking/src/Logging.h | 6 ------ libraries/networking/src/Node.h | 6 ------ 2 files changed, 12 deletions(-) diff --git a/libraries/networking/src/Logging.h b/libraries/networking/src/Logging.h index b37962e931..c52812bd33 100644 --- a/libraries/networking/src/Logging.h +++ b/libraries/networking/src/Logging.h @@ -12,12 +12,6 @@ #ifndef hifi_Logging_h #define hifi_Logging_h -#ifdef _WIN32 -#include "Syssocket.h" -#else -#include -#endif - #include const int LOGSTASH_UDP_PORT = 9500; diff --git a/libraries/networking/src/Node.h b/libraries/networking/src/Node.h index 6cc8d5bfaf..3b3237cf6e 100644 --- a/libraries/networking/src/Node.h +++ b/libraries/networking/src/Node.h @@ -15,12 +15,6 @@ #include #include -#ifdef _WIN32 -#include "Syssocket.h" -#else -#include -#endif - #include #include #include From b87c04444ed36fd95bfc4736908ff0477b07480e Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 10:41:01 -0700 Subject: [PATCH 314/595] include winsock2 from HifiSockAddr --- libraries/networking/src/HifiSockAddr.cpp | 2 -- libraries/networking/src/HifiSockAddr.h | 6 ++++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/libraries/networking/src/HifiSockAddr.cpp b/libraries/networking/src/HifiSockAddr.cpp index be482cfe02..33f5c0bb70 100644 --- a/libraries/networking/src/HifiSockAddr.cpp +++ b/libraries/networking/src/HifiSockAddr.cpp @@ -9,8 +9,6 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#include - #include #include #include diff --git a/libraries/networking/src/HifiSockAddr.h b/libraries/networking/src/HifiSockAddr.h index 49db336d19..5ecf944aef 100644 --- a/libraries/networking/src/HifiSockAddr.h +++ b/libraries/networking/src/HifiSockAddr.h @@ -12,6 +12,12 @@ #ifndef hifi_HifiSockAddr_h #define hifi_HifiSockAddr_h +#ifdef WIN32 +#include +#else +#include +#endif + #include class HifiSockAddr { From da24483d7c72ea6e32bd3cfd7772198a051e7153 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 10:45:43 -0700 Subject: [PATCH 315/595] include WS2tcpip for socklen_t on windows --- libraries/networking/src/HifiSockAddr.h | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries/networking/src/HifiSockAddr.h b/libraries/networking/src/HifiSockAddr.h index 5ecf944aef..8a591a60b8 100644 --- a/libraries/networking/src/HifiSockAddr.h +++ b/libraries/networking/src/HifiSockAddr.h @@ -14,6 +14,7 @@ #ifdef WIN32 #include +#include #else #include #endif From 186c588d5ae4f11403caf378e09517e39ff3fc01 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 10:48:50 -0700 Subject: [PATCH 316/595] remove doubled timeval definition from SharedUtil --- libraries/shared/src/SharedUtil.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index 3569c700ed..cd98fbdbd2 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -15,12 +15,6 @@ #include #include -#ifdef _WIN32 -#ifndef _timeval_ -#define _timeval_ -#endif -#endif - #ifdef __APPLE__ #include #endif From 714db42f873f527525d8049af58168139fbf6935 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 10:51:20 -0700 Subject: [PATCH 317/595] include QNetworkConfigManager to fix HifiSockAddr error on windows --- libraries/networking/src/HifiSockAddr.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries/networking/src/HifiSockAddr.cpp b/libraries/networking/src/HifiSockAddr.cpp index 33f5c0bb70..240d02631e 100644 --- a/libraries/networking/src/HifiSockAddr.cpp +++ b/libraries/networking/src/HifiSockAddr.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include "HifiSockAddr.h" From ad0776be4e2d7b833a70d7a1d70a403367dde80b Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 10:55:02 -0700 Subject: [PATCH 318/595] repair QNetworkConfigurationManager include --- libraries/networking/src/HifiSockAddr.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/networking/src/HifiSockAddr.cpp b/libraries/networking/src/HifiSockAddr.cpp index 240d02631e..1e1b13ff9a 100644 --- a/libraries/networking/src/HifiSockAddr.cpp +++ b/libraries/networking/src/HifiSockAddr.cpp @@ -11,7 +11,7 @@ #include #include -#include +#include #include #include "HifiSockAddr.h" From 52203bd36e879181480ab5792fbbdcb2ae54912c Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 10:58:20 -0700 Subject: [PATCH 319/595] another attempt to repair QNetworkInterface call on windows --- libraries/networking/src/HifiSockAddr.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/networking/src/HifiSockAddr.cpp b/libraries/networking/src/HifiSockAddr.cpp index 1e1b13ff9a..5e8293e629 100644 --- a/libraries/networking/src/HifiSockAddr.cpp +++ b/libraries/networking/src/HifiSockAddr.cpp @@ -11,7 +11,7 @@ #include #include -#include +#include #include #include "HifiSockAddr.h" From 7d4399da3507fb6bd59c13dec7c7dbbfe436e000 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 11:01:17 -0700 Subject: [PATCH 320/595] don't use reserved word causing issues on windows --- libraries/networking/src/HifiSockAddr.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/libraries/networking/src/HifiSockAddr.cpp b/libraries/networking/src/HifiSockAddr.cpp index 5e8293e629..d30f7944d7 100644 --- a/libraries/networking/src/HifiSockAddr.cpp +++ b/libraries/networking/src/HifiSockAddr.cpp @@ -11,7 +11,6 @@ #include #include -#include #include #include "HifiSockAddr.h" @@ -96,13 +95,13 @@ quint32 getHostOrderLocalAddress() { static int localAddress = 0; if (localAddress == 0) { - foreach(const QNetworkInterface &interface, QNetworkInterface::allInterfaces()) { - if (interface.flags() & QNetworkInterface::IsUp - && interface.flags() & QNetworkInterface::IsRunning - && interface.flags() & ~QNetworkInterface::IsLoopBack) { + foreach(const QNetworkInterface &networkInterface, QNetworkInterface::allInterfaces()) { + if (networkInterface.flags() & QNetworkInterface::IsUp + && networkInterface.flags() & QNetworkInterface::IsRunning + && networkInterface.flags() & ~QNetworkInterface::IsLoopBack) { // we've decided that this is the active NIC // enumerate it's addresses to grab the IPv4 address - foreach(const QNetworkAddressEntry &entry, interface.addressEntries()) { + foreach(const QNetworkAddressEntry &entry, networkInterface.addressEntries()) { // make sure it's an IPv4 address that isn't the loopback if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol && !entry.ip().isLoopback()) { qDebug("Node's local address is %s", entry.ip().toString().toLocal8Bit().constData()); From 53aafd689707299f18f51e7f4c8c7c3102ffefa0 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 11:06:22 -0700 Subject: [PATCH 321/595] rely on winsock2 for timeval declaration --- libraries/shared/src/Systime.cpp | 5 ++--- libraries/shared/src/Systime.h | 26 ++------------------------ 2 files changed, 4 insertions(+), 27 deletions(-) diff --git a/libraries/shared/src/Systime.cpp b/libraries/shared/src/Systime.cpp index 7d8764e3f9..505703a7ee 100644 --- a/libraries/shared/src/Systime.cpp +++ b/libraries/shared/src/Systime.cpp @@ -1,14 +1,13 @@ #ifdef _WIN32 #include -#define _timeval_ #include "Systime.h" - int gettimeofday( timeval* p_tv, timezone* p_tz ) - { + int gettimeofday(timeval* p_tv, timezone* p_tz) { int tt = timeGetTime(); p_tv->tv_sec = tt / 1000; p_tv->tv_usec = tt % 1000 * 1000; return 0; } + #endif diff --git a/libraries/shared/src/Systime.h b/libraries/shared/src/Systime.h index 1d25de0b80..5d96b53e7a 100644 --- a/libraries/shared/src/Systime.h +++ b/libraries/shared/src/Systime.h @@ -1,38 +1,16 @@ #ifndef __Systime__ #define __Systime__ - #ifdef _WIN32 -#ifdef _WINSOCK2API_ -#define _timeval_ -#endif - -#ifndef _timeval_ -#define _timeval_ -/* - * Structure returned by gettimeofday(2) system call, - * and used in other calls. - */ - -// this is a bit of a hack for now, but sometimes on windows -// we need timeval defined here, sometimes we get it -// from winsock.h -#ifdef WANT_TIMEVAL -struct timeval { - long tv_sec; /* seconds */ - long tv_usec; /* and microseconds */ -}; -#endif - -#endif _timeval_ +#include struct timezone { int tz_minuteswest; /* minutes west of Greenwich */ int tz_dsttime; /* type of dst correction */ }; -int gettimeofday( struct timeval* p_tv, struct timezone* p_tz ); +int gettimeofday(struct timeval* p_tv, struct timezone* p_tz); #endif _Win32 From ef418f09b3648afeb10c55b183ead157b0befdfd Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 11:15:33 -0700 Subject: [PATCH 322/595] don't let windows.h include winsock --- interface/src/Audio.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index a98d276acc..a29f5aaa6e 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -20,6 +20,7 @@ #ifdef WIN32 #define WIN32_LEAN_AND_MEAN +#define _WINSOCKAPI_ #include #include #include From 7c9e0927abda212a21f6003f1fc4d400b086314c Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 11:17:03 -0700 Subject: [PATCH 323/595] define WIN32_LEAN_AND_MEAN before include windows.h in Systime --- interface/src/Audio.cpp | 1 - libraries/shared/src/Systime.cpp | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index a29f5aaa6e..a98d276acc 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -20,7 +20,6 @@ #ifdef WIN32 #define WIN32_LEAN_AND_MEAN -#define _WINSOCKAPI_ #include #include #include diff --git a/libraries/shared/src/Systime.cpp b/libraries/shared/src/Systime.cpp index 505703a7ee..1fc6778dad 100644 --- a/libraries/shared/src/Systime.cpp +++ b/libraries/shared/src/Systime.cpp @@ -1,4 +1,5 @@ #ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN #include #include "Systime.h" From a12dd916fafe29cdc532c267af84e169c1392ab0 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 10 Apr 2014 11:24:45 -0700 Subject: [PATCH 324/595] More plane intersection bits. --- interface/src/renderer/Model.cpp | 2 +- libraries/shared/src/PlaneShape.h | 10 ++---- libraries/shared/src/ShapeCollider.cpp | 43 +++++++++++++++++++++++++- 3 files changed, 45 insertions(+), 10 deletions(-) diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index a317ddc07a..2d47a077b7 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -638,7 +638,7 @@ bool Model::findPlaneCollisions(const glm::vec4& plane, CollisionList& collision bool collided = false; PlaneShape planeShape(plane); for (int i = 0; i < _jointShapes.size(); i++) { - if (ShapeCollider::shapeShape(&planeShape, _jointShapes[i], collisions)) { + if (ShapeCollider::collideShapes(&planeShape, _jointShapes[i], collisions)) { CollisionInfo* collision = collisions.getLastCollision(); collision->_type = MODEL_COLLISION; collision->_data = (void*)(this); diff --git a/libraries/shared/src/PlaneShape.h b/libraries/shared/src/PlaneShape.h index 11823da701..524d53ec73 100644 --- a/libraries/shared/src/PlaneShape.h +++ b/libraries/shared/src/PlaneShape.h @@ -16,15 +16,9 @@ class PlaneShape : public Shape { public: - PlaneShape() : Shape(Shape::PLANE_SHAPE) {} - - PlaneShape(const glm::vec4& coefficients) : Shape(Shape::PLANE_SHAPE), _coefficients(coefficients) { } + PlaneShape(const glm::vec4& coefficients = glm::vec4(0.0f, 1.0f, 0.0f, 0.0f)); - const glm::vec4& getCoefficients() const { return _coefficients; } - -private: - - glm::vec4 _coefficients; + glm::vec4 getCoefficients() const; }; #endif // hifi_PlaneShape_h diff --git a/libraries/shared/src/ShapeCollider.cpp b/libraries/shared/src/ShapeCollider.cpp index 10211f1d78..c53c7fab7d 100644 --- a/libraries/shared/src/ShapeCollider.cpp +++ b/libraries/shared/src/ShapeCollider.cpp @@ -191,7 +191,7 @@ bool spherePlane(const SphereShape* sphereA, const PlaneShape* planeB, Collision return false; // collision list is full } collision->_penetration = penetration; - collision->_contactPoint = glm::vec3(); + collision->_contactPoint = sphereA->getPosition() + sphereA->getRadius() * glm::normalize(penetration); return true; } return false; @@ -404,18 +404,59 @@ bool capsuleCapsule(const CapsuleShape* capsuleA, const CapsuleShape* capsuleB, } bool capsulePlane(const CapsuleShape* capsuleA, const PlaneShape* planeB, CollisionList& collisions) { + glm::vec3 start, end, penetration; + capsuleA->getStartPoint(start); + capsuleA->getEndPoint(end); + glm::vec4 plane = planeB->getCoefficients(); + if (findCapsulePlanePenetration(start, end, capsuleA->getRadius(), plane, penetration)) { + CollisionInfo* collision = collisions.getNewCollision(); + if (!collision) { + return false; // collision list is full + } + collision->_penetration = penetration; + glm::vec3 deepestEnd = (glm::dot(start, glm::vec3(plane)) < glm::dot(end, glm::vec3(plane))) ? start : end; + collision->_contactPoint = deepestEnd + capsuleA->getRadius() * glm::normalize(penetration); + return true; + } return false; } bool planeSphere(const PlaneShape* planeA, const SphereShape* sphereB, CollisionList& collisions) { + glm::vec3 penetration; + if (findSpherePlanePenetration(sphereB->getPosition(), sphereB->getRadius(), planeA->getCoefficients(), penetration)) { + CollisionInfo* collision = collisions.getNewCollision(); + if (!collision) { + return false; // collision list is full + } + collision->_penetration = -penetration; + collision->_contactPoint = sphereB->getPosition() + + (sphereB->getRadius() / glm::length(penetration) - 1.0f) * penetration; + return true; + } return false; } bool planeCapsule(const PlaneShape* planeA, const CapsuleShape* capsuleB, CollisionList& collisions) { + glm::vec3 start, end, penetration; + capsuleB->getStartPoint(start); + capsuleB->getEndPoint(end); + glm::vec4 plane = planeA->getCoefficients(); + if (findCapsulePlanePenetration(start, end, capsuleB->getRadius(), plane, penetration)) { + CollisionInfo* collision = collisions.getNewCollision(); + if (!collision) { + return false; // collision list is full + } + collision->_penetration = -penetration; + glm::vec3 deepestEnd = (glm::dot(start, glm::vec3(plane)) < glm::dot(end, glm::vec3(plane))) ? start : end; + collision->_contactPoint = deepestEnd + (capsuleB->getRadius() / glm::length(penetration) - 1.0f) * penetration; + return true; + } return false; } bool planePlane(const PlaneShape* planeA, const PlaneShape* planeB, CollisionList& collisions) { + // technically, planes always collide unless they're parallel and not coincident; however, that's + // not going to give us any useful information return false; } From 3651eff3d631658b8fcdb30b9d63e0acb66a1204 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 11:24:54 -0700 Subject: [PATCH 325/595] cleanup Systime to gettimeofday without lean and mean windows --- interface/src/Audio.h | 1 - interface/src/starfield/Controller.cpp | 1 - interface/src/starfield/Generator.cpp | 1 - interface/src/ui/BandwidthMeter.h | 1 - libraries/shared/src/Systime.cpp | 62 +++++++++++++++++++++----- libraries/shared/src/Systime.h | 23 +++++----- 6 files changed, 63 insertions(+), 26 deletions(-) diff --git a/interface/src/Audio.h b/interface/src/Audio.h index c529fc2651..a0c7398328 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -13,7 +13,6 @@ #define hifi_Audio_h #ifdef _WIN32 -#define WANT_TIMEVAL #include #endif diff --git a/interface/src/starfield/Controller.cpp b/interface/src/starfield/Controller.cpp index b50c393f00..771029c689 100755 --- a/interface/src/starfield/Controller.cpp +++ b/interface/src/starfield/Controller.cpp @@ -10,7 +10,6 @@ // #ifdef _WIN32 -#define WANT_TIMEVAL #include #endif diff --git a/interface/src/starfield/Generator.cpp b/interface/src/starfield/Generator.cpp index 15d1736e4e..b18e1834be 100644 --- a/interface/src/starfield/Generator.cpp +++ b/interface/src/starfield/Generator.cpp @@ -10,7 +10,6 @@ // #ifdef _WIN32 -#define WANT_TIMEVAL #include #endif diff --git a/interface/src/ui/BandwidthMeter.h b/interface/src/ui/BandwidthMeter.h index 45226c8e82..6838f28c70 100644 --- a/interface/src/ui/BandwidthMeter.h +++ b/interface/src/ui/BandwidthMeter.h @@ -13,7 +13,6 @@ #define hifi_BandwidthMeter_h #ifdef _WIN32 -#define WANT_TIMEVAL #include #endif diff --git a/libraries/shared/src/Systime.cpp b/libraries/shared/src/Systime.cpp index 1fc6778dad..a63336f777 100644 --- a/libraries/shared/src/Systime.cpp +++ b/libraries/shared/src/Systime.cpp @@ -1,14 +1,56 @@ -#ifdef _WIN32 +// +// Systime.cpp +// libraries/shared/src +// +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +/** + * gettimeofday + * Implementation according to: + * The Open Group Base Specifications Issue 6 + * IEEE Std 1003.1, 2004 Edition + */ + +/** + * THIS SOFTWARE IS NOT COPYRIGHTED + * + * This source code is offered for use in the public domain. You may + * use, modify or distribute it freely. + * + * This code is distributed in the hope that it will be useful but + * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY + * DISCLAIMED. This includes but is not limited to warranties of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * + * Contributed by: + * Danny Smith + */ + +#include #define WIN32_LEAN_AND_MEAN #include -#include "Systime.h" - int gettimeofday(timeval* p_tv, timezone* p_tz) { - int tt = timeGetTime(); +/** Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */ +#define _W32_FT_OFFSET (116444736000000000ULL) - p_tv->tv_sec = tt / 1000; - p_tv->tv_usec = tt % 1000 * 1000; - return 0; - } - -#endif +int __cdecl gettimeofday(struct timeval *__restrict__ tp, + void *__restrict__ tzp __attribute__((unused))) { + union { + unsigned long long ns100; /**time since 1 Jan 1601 in 100ns units */ + FILETIME ft; + } _now; + + if (tp) { + GetSystemTimeAsFileTime (&_now.ft); + tp->tv_usec=(long)((_now.ns100 / 10ULL) % 1000000ULL ); + tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000ULL); + } + + /** Always return 0 as per Open Group Base Specifications Issue 6. + Do not set errno on error. */ + return 0; +} \ No newline at end of file diff --git a/libraries/shared/src/Systime.h b/libraries/shared/src/Systime.h index 5d96b53e7a..07d467e63d 100644 --- a/libraries/shared/src/Systime.h +++ b/libraries/shared/src/Systime.h @@ -1,17 +1,16 @@ +// +// Systime.h +// libraries/shared/src +// +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + #ifndef __Systime__ #define __Systime__ -#ifdef _WIN32 - #include -struct timezone { - int tz_minuteswest; /* minutes west of Greenwich */ - int tz_dsttime; /* type of dst correction */ -}; - -int gettimeofday(struct timeval* p_tv, struct timezone* p_tz); - -#endif _Win32 - -#endif __Systime__ +#endif __Systime__ \ No newline at end of file From 1daaf561de524f06d3aecb2af1fd171f364c5686 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 11:26:47 -0700 Subject: [PATCH 326/595] don't include missing sys/time, declare gettimeofday in Systime header --- libraries/shared/src/Systime.cpp | 1 - libraries/shared/src/Systime.h | 2 ++ 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/libraries/shared/src/Systime.cpp b/libraries/shared/src/Systime.cpp index a63336f777..157dc99990 100644 --- a/libraries/shared/src/Systime.cpp +++ b/libraries/shared/src/Systime.cpp @@ -30,7 +30,6 @@ * Danny Smith */ -#include #define WIN32_LEAN_AND_MEAN #include diff --git a/libraries/shared/src/Systime.h b/libraries/shared/src/Systime.h index 07d467e63d..6197c46c02 100644 --- a/libraries/shared/src/Systime.h +++ b/libraries/shared/src/Systime.h @@ -13,4 +13,6 @@ #include +int __cdecl gettimeofday(struct timeval *__restrict__, void *__restrict__); + #endif __Systime__ \ No newline at end of file From 885cee28c5007b9c5adddeb42f5dd02daec553b7 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 11:28:22 -0700 Subject: [PATCH 327/595] guard Systime against being included on UNIX/OS X --- libraries/shared/src/Systime.cpp | 6 +++++- libraries/shared/src/Systime.h | 10 +++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/libraries/shared/src/Systime.cpp b/libraries/shared/src/Systime.cpp index 157dc99990..eab02ce2ab 100644 --- a/libraries/shared/src/Systime.cpp +++ b/libraries/shared/src/Systime.cpp @@ -8,6 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#ifdef WIN32 + /** * gettimeofday * Implementation according to: @@ -52,4 +54,6 @@ int __cdecl gettimeofday(struct timeval *__restrict__ tp, /** Always return 0 as per Open Group Base Specifications Issue 6. Do not set errno on error. */ return 0; -} \ No newline at end of file +} + +#endif \ No newline at end of file diff --git a/libraries/shared/src/Systime.h b/libraries/shared/src/Systime.h index 6197c46c02..d8b1dc9f77 100644 --- a/libraries/shared/src/Systime.h +++ b/libraries/shared/src/Systime.h @@ -8,11 +8,15 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef __Systime__ -#define __Systime__ +#ifndef hifi_Systime_h +#define hifi_Systime_h + +#ifdef WIN32 #include int __cdecl gettimeofday(struct timeval *__restrict__, void *__restrict__); -#endif __Systime__ \ No newline at end of file +#endif + +#endif // hifi_Systime_h \ No newline at end of file From ea8f0df17d4f3820193c0b1d9b32c4da8b47d6af Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 11:30:20 -0700 Subject: [PATCH 328/595] use extern C in Systime header --- libraries/shared/src/Systime.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libraries/shared/src/Systime.h b/libraries/shared/src/Systime.h index d8b1dc9f77..b6eaa70cab 100644 --- a/libraries/shared/src/Systime.h +++ b/libraries/shared/src/Systime.h @@ -15,8 +15,12 @@ #include +extern "C" { + int __cdecl gettimeofday(struct timeval *__restrict__, void *__restrict__); +} + #endif #endif // hifi_Systime_h \ No newline at end of file From 00a826330e9988afeab2c602a95973832f9f9c57 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 11:34:43 -0700 Subject: [PATCH 329/595] use GetSystemTimeAsFileTime with previous gettimeofday setup --- libraries/shared/src/Systime.cpp | 12 ++++++------ libraries/shared/src/Systime.h | 9 +++++---- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/libraries/shared/src/Systime.cpp b/libraries/shared/src/Systime.cpp index eab02ce2ab..0b2d782bbf 100644 --- a/libraries/shared/src/Systime.cpp +++ b/libraries/shared/src/Systime.cpp @@ -38,21 +38,21 @@ /** Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */ #define _W32_FT_OFFSET (116444736000000000ULL) -int __cdecl gettimeofday(struct timeval *__restrict__ tp, - void *__restrict__ tzp __attribute__((unused))) { +int gettimeofday(timeval* p_tv, timezone* p_tz) { + union { unsigned long long ns100; /**time since 1 Jan 1601 in 100ns units */ FILETIME ft; } _now; - if (tp) { + if (p_tv) { GetSystemTimeAsFileTime (&_now.ft); - tp->tv_usec=(long)((_now.ns100 / 10ULL) % 1000000ULL ); - tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000ULL); + p_tv->tv_usec=(long)((_now.ns100 / 10ULL) % 1000000ULL ); + p_tv->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000ULL); } /** Always return 0 as per Open Group Base Specifications Issue 6. - Do not set errno on error. */ + Do not set errno on error. */ return 0; } diff --git a/libraries/shared/src/Systime.h b/libraries/shared/src/Systime.h index b6eaa70cab..3098f09ecd 100644 --- a/libraries/shared/src/Systime.h +++ b/libraries/shared/src/Systime.h @@ -15,11 +15,12 @@ #include -extern "C" { +struct timezone { + int tz_minuteswest; /* minutes west of Greenwich */ + int tz_dsttime; /* type of dst correction */ +}; -int __cdecl gettimeofday(struct timeval *__restrict__, void *__restrict__); - -} +int gettimeofday(struct timeval* p_tv, struct timezone* p_tz); #endif From cfc2431a59638ee1cda339c2e79c7ab5977be21c Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 11:37:09 -0700 Subject: [PATCH 330/595] don't be a dummy and include Systime header from implementation --- libraries/shared/src/Systime.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libraries/shared/src/Systime.cpp b/libraries/shared/src/Systime.cpp index 0b2d782bbf..ab32821a0f 100644 --- a/libraries/shared/src/Systime.cpp +++ b/libraries/shared/src/Systime.cpp @@ -10,6 +10,8 @@ #ifdef WIN32 +#include "Systime.h" + /** * gettimeofday * Implementation according to: From 5099a0e06126edce98b7df50cd8b2fdcee2af76a Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Thu, 10 Apr 2014 11:41:10 -0700 Subject: [PATCH 331/595] Remove chat window opening animation --- interface/src/Menu.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 70e69597f6..ba3ea45229 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -1212,12 +1212,6 @@ void Menu::showChat() { _chatWindow->resize(0, _chatWindow->height()); _chatWindow->toggleViewAction()->trigger(); - QPropertyAnimation* slideAnimation = new QPropertyAnimation(_chatWindow, "geometry", _chatWindow); - slideAnimation->setStartValue(_chatWindow->geometry()); - slideAnimation->setEndValue(QRect(mainWindow->width() - width, _chatWindow->y(), - width, _chatWindow->height())); - slideAnimation->setDuration(250); - slideAnimation->start(QAbstractAnimation::DeleteWhenStopped); } } From 2d481dda4e4d5ff345dcec0cda9cbc56515ce342 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Thu, 10 Apr 2014 11:46:28 -0700 Subject: [PATCH 332/595] Update chat menu to properly position itself when opening The previous implementation seemed to assume a full-screen main window - it will now open on the right side of the window, vertically centered, regardless of where the main window is. --- interface/src/Menu.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index ba3ea45229..7b67aadfba 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -1206,12 +1206,12 @@ void Menu::showChat() { mainWindow->addDockWidget(Qt::NoDockWidgetArea, _chatWindow = new ChatWindow()); } if (!_chatWindow->toggleViewAction()->isChecked()) { - int width = _chatWindow->width(); - int y = qMax((mainWindow->height() - _chatWindow->height()) / 2, 0); - _chatWindow->move(mainWindow->width(), y); + const QRect& windowGeometry = mainWindow->geometry(); + _chatWindow->move(windowGeometry.topRight().x() - _chatWindow->width(), + windowGeometry.topRight().y() + (windowGeometry.height() / 2) - (_chatWindow->height() / 2)); + _chatWindow->resize(0, _chatWindow->height()); _chatWindow->toggleViewAction()->trigger(); - } } From 2c96ce08aebcb24a213d35164808d46d01e30aa1 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 11:50:26 -0700 Subject: [PATCH 333/595] add stackoverflow fix for lnk2001 error in gnutls_free --- libraries/networking/src/DTLSClientSession.cpp | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/libraries/networking/src/DTLSClientSession.cpp b/libraries/networking/src/DTLSClientSession.cpp index b17de8e168..51151a7d36 100644 --- a/libraries/networking/src/DTLSClientSession.cpp +++ b/libraries/networking/src/DTLSClientSession.cpp @@ -33,6 +33,17 @@ void DTLSClientSession::globalDeinit() { gnutls_global_deinit(); } +// fix for lnk2001 link error on windows +// call xgnutls_free instead of gnutls_free +// http://stackoverflow.com/questions/14593949/getting-error-lnk2001-unresolved-external-symbol-gnutls-free-when-using-gnut + +typedef void (*gnutls_free_function) (void *); +__declspec(dllimport) extern gnutls_free_function gnutls_free; + +void xgnutls_free(void* p){ + gnutls_free(p); +} + int DTLSClientSession::verifyServerCertificate(gnutls_session_t session) { unsigned int verifyStatus = 0; @@ -60,7 +71,7 @@ int DTLSClientSession::verifyServerCertificate(gnutls_session_t session) { } qDebug() << "Gnutls certificate verification status:" << reinterpret_cast(printOut.data); - gnutls_free(printOut.data); + xgnutls_free(printOut.data); if (verifyStatus != 0) { qDebug() << "Server provided certificate for DTLS is not trusted. Can not complete handshake."; From 2cc21496478cb5aea6852f69fd80dff9e5fd7c46 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Thu, 10 Apr 2014 11:54:14 -0700 Subject: [PATCH 334/595] Glow when you talk, flash when you clip closes #2592 --- interface/src/Application.cpp | 6 ++++++ interface/src/Util.cpp | 4 ++-- interface/src/Util.h | 2 +- interface/src/avatar/Avatar.cpp | 5 ++++- 4 files changed, 13 insertions(+), 4 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index f6b0d37dd4..ad216458bd 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2557,6 +2557,12 @@ void Application::displayOverlay() { } bool isClipping = ((_audio.getTimeSinceLastClip() > 0.f) && (_audio.getTimeSinceLastClip() < CLIPPING_INDICATOR_TIME)); + + if ((_audio.getTimeSinceLastClip() > 0.f) && (_audio.getTimeSinceLastClip() < CLIPPING_INDICATOR_TIME)) { + const float MAX_MAGNITUDE = 0.7f; + float magnitude = MAX_MAGNITUDE * (1 - _audio.getTimeSinceLastClip() / CLIPPING_INDICATOR_TIME); + renderCollisionOverlay(_glWidget->width(), _glWidget->height(), magnitude, 1.0f); + } _audio.renderToolBox(MIRROR_VIEW_LEFT_PADDING + AUDIO_METER_GAP, audioMeterY, diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 36e39a46a5..cecc363daa 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -351,10 +351,10 @@ void drawvec3(int x, int y, float scale, float radians, float thick, int mono, g glPopMatrix(); } -void renderCollisionOverlay(int width, int height, float magnitude) { +void renderCollisionOverlay(int width, int height, float magnitude, float red, float blue, float green) { const float MIN_VISIBLE_COLLISION = 0.01f; if (magnitude > MIN_VISIBLE_COLLISION) { - glColor4f(0, 0, 0, magnitude); + glColor4f(red, blue, green, magnitude); glBegin(GL_QUADS); glVertex2f(0, 0); glVertex2d(width, 0); diff --git a/interface/src/Util.h b/interface/src/Util.h index 4f0e76adf8..ac680645a9 100644 --- a/interface/src/Util.h +++ b/interface/src/Util.h @@ -62,7 +62,7 @@ float extractUniformScale(const glm::vec3& scale); double diffclock(timeval *clock1,timeval *clock2); -void renderCollisionOverlay(int width, int height, float magnitude); +void renderCollisionOverlay(int width, int height, float magnitude, float red = 0, float blue = 0, float green = 0); void renderOrientationDirections( glm::vec3 position, const glm::quat& orientation, float size ); diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 698d58c25a..1107bcd21a 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -210,7 +210,10 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode) { { // glow when moving far away const float GLOW_DISTANCE = 20.0f; - Glower glower(_moving && distanceToTarget > GLOW_DISTANCE && renderMode == NORMAL_RENDER_MODE ? 1.0f : 0.0f); + const float GLOW_MAX_LOUDNESS = 2500.0f; + const float MAX_GLOW = 0.7f; + const float GLOW_FROM_AVERAGE_LOUDNESS = MAX_GLOW * getHeadData()->getAudioLoudness() / GLOW_MAX_LOUDNESS; + Glower glower(_moving && distanceToTarget > GLOW_DISTANCE && renderMode == NORMAL_RENDER_MODE ? 1.0f : GLOW_FROM_AVERAGE_LOUDNESS); // render body if (Menu::getInstance()->isOptionChecked(MenuOption::Avatars)) { From 873541dd7bcfae76691e6b9b12d0f429db8bdf32 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 10 Apr 2014 11:56:17 -0700 Subject: [PATCH 335/595] Trying out basic pushback for other avatars. --- interface/src/Application.cpp | 30 +++++++++++++++++------- libraries/shared/src/PlaneShape.cpp | 36 +++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 8 deletions(-) create mode 100644 libraries/shared/src/PlaneShape.cpp diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index de612c80c0..d90b5835e5 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -519,6 +519,7 @@ void Application::paintGL() { glEnable(GL_LINE_SMOOTH); + const float PUSHBACK_RADIUS = 0.2f; if (OculusManager::isConnected()) { _myCamera.setUpShift(0.0f); _myCamera.setDistance(0.0f); @@ -531,18 +532,32 @@ void Application::paintGL() { _myCamera.setTargetPosition(_myAvatar->getHead()->calculateAverageEyePosition()); _myCamera.setTargetRotation(_myAvatar->getHead()->getCameraOrientation()); + glm::vec3 planeNormal = _myCamera.getTargetRotation() * IDENTITY_FRONT; + float combinedRadius = _myCamera.getNearClip() + _myAvatar->getScale() * PUSHBACK_RADIUS; + glm::vec4 plane(planeNormal, -glm::dot(planeNormal, _myCamera.getTargetPosition()) - combinedRadius); + // push camera out of any intersecting avatars float pushback = 0.0f; foreach (const AvatarSharedPointer& avatarData, _avatarManager.getAvatarHash()) { Avatar* avatar = static_cast(avatarData.data()); - const float RADIUS_MULTIPLIER = 2.0f; - CollisionList collisions(4); - if (!avatar->isMyAvatar() && avatar->findSphereCollisions(_myCamera.getTargetPosition(), - _myCamera.getNearClip() * RADIUS_MULTIPLIER, collisions)) { - for (int i = 0; i < collisions.size(); i++) { - collisions.getCollision(i)->_penetration; - } + if (avatar->isMyAvatar()) { + continue; } + if (glm::distance(avatar->getPosition(), _myCamera.getTargetPosition()) > + avatar->getBoundingRadius() + combinedRadius) { + continue; + } + CollisionList collisions(4); + if (!avatar->findPlaneCollisions(plane, collisions)) { + continue; + } + for (int i = 0; i < collisions.size(); i++) { + pushback = qMax(pushback, glm::length(collisions.getCollision(i)->_penetration)); + } + } + if (pushback > 0.0f) { + _myCamera.setTargetPosition(_myCamera.getTargetPosition() + + _myCamera.getTargetRotation() * glm::vec3(0.0f, 0.0f, pushback)); } } else if (_myCamera.getMode() == CAMERA_MODE_THIRD_PERSON) { _myCamera.setTightness(0.0f); // Camera is directly connected to head without smoothing @@ -560,7 +575,6 @@ void Application::paintGL() { // if the head would intersect the near clip plane, we must push the camera out glm::vec3 relativePosition = glm::inverse(_myCamera.getTargetRotation()) * (eyePosition - _myCamera.getTargetPosition()); - const float PUSHBACK_RADIUS = 0.2f; float pushback = relativePosition.z + _myCamera.getNearClip() + _myAvatar->getScale() * PUSHBACK_RADIUS - _myCamera.getDistance(); if (pushback > 0.0f) { diff --git a/libraries/shared/src/PlaneShape.cpp b/libraries/shared/src/PlaneShape.cpp new file mode 100644 index 0000000000..a8b4468c93 --- /dev/null +++ b/libraries/shared/src/PlaneShape.cpp @@ -0,0 +1,36 @@ +// +// PlaneShape.cpp +// libraries/shared/src +// +// Created by Andrzej Kapolka on 4/10/2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "PlaneShape.h" +#include "SharedUtil.h" + +const glm::vec3 UNROTATED_NORMAL(0.0f, 1.0f, 0.0f); + +PlaneShape::PlaneShape(const glm::vec4& coefficients) : + Shape(Shape::PLANE_SHAPE) { + + glm::vec3 normal = glm::vec3(coefficients); + _position = -normal * coefficients.w; + + float angle = acosf(glm::dot(normal, UNROTATED_NORMAL)); + if (angle > EPSILON) { + if (angle > PI - EPSILON) { + _rotation = glm::angleAxis(PI, glm::vec3(1.0f, 0.0f, 0.0f)); + } else { + _rotation = glm::angleAxis(angle, glm::normalize(glm::cross(UNROTATED_NORMAL, normal))); + } + } +} + +glm::vec4 PlaneShape::getCoefficients() const { + glm::vec3 normal = _rotation * UNROTATED_NORMAL; + return glm::vec4(normal.x, normal.y, normal.z, -glm::dot(normal, _position)); +} From ff3ebd1eda1e8a69210be650df3c87b35c83a7e6 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Thu, 10 Apr 2014 12:04:30 -0700 Subject: [PATCH 336/595] Fix centering of timestamp in chat window --- interface/src/ui/ChatWindow.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/interface/src/ui/ChatWindow.cpp b/interface/src/ui/ChatWindow.cpp index 0060cb839c..63f76295bd 100644 --- a/interface/src/ui/ChatWindow.cpp +++ b/interface/src/ui/ChatWindow.cpp @@ -155,6 +155,8 @@ void ChatWindow::addTimeStamp() { timeLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); timeLabel->setAlignment(Qt::AlignHCenter); ui->messagesGridLayout->addWidget(timeLabel, ui->messagesGridLayout->rowCount(), 0, 1, 2); + ui->messagesGridLayout->parentWidget()->updateGeometry(); + numMessagesAfterLastTimeStamp = 0; } } From 37f9f47488a4ef48c27c930cc43354c5b659fdba Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Thu, 10 Apr 2014 12:09:06 -0700 Subject: [PATCH 337/595] Fix odd resizing of chat messages When calling updateGeometry on the message labels the layout system seems to resize the widgets in weird ways. There may be a different way to keep it from doing this. --- interface/src/ui/ChatWindow.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/interface/src/ui/ChatWindow.cpp b/interface/src/ui/ChatWindow.cpp index 63f76295bd..1230140fc8 100644 --- a/interface/src/ui/ChatWindow.cpp +++ b/interface/src/ui/ChatWindow.cpp @@ -251,7 +251,6 @@ void ChatWindow::messageReceived(const QXmppMessage& message) { Application::processEvents(); QScrollBar* verticalScrollBar = ui->messagesScrollArea->verticalScrollBar(); verticalScrollBar->setSliderPosition(verticalScrollBar->maximum()); - messageLabel->updateGeometry(); ++numMessagesAfterLastTimeStamp; if (message.stamp().isValid()) { From 97444eac1c5457e9fbe7190c5d89f8e68f1f1310 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 12:11:37 -0700 Subject: [PATCH 338/595] put gnutls_free fix in DTLSSession header --- libraries/networking/src/DTLSClientSession.cpp | 12 ------------ libraries/networking/src/DTLSSession.h | 13 +++++++++++++ 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/libraries/networking/src/DTLSClientSession.cpp b/libraries/networking/src/DTLSClientSession.cpp index 51151a7d36..14de3dfb0c 100644 --- a/libraries/networking/src/DTLSClientSession.cpp +++ b/libraries/networking/src/DTLSClientSession.cpp @@ -33,17 +33,6 @@ void DTLSClientSession::globalDeinit() { gnutls_global_deinit(); } -// fix for lnk2001 link error on windows -// call xgnutls_free instead of gnutls_free -// http://stackoverflow.com/questions/14593949/getting-error-lnk2001-unresolved-external-symbol-gnutls-free-when-using-gnut - -typedef void (*gnutls_free_function) (void *); -__declspec(dllimport) extern gnutls_free_function gnutls_free; - -void xgnutls_free(void* p){ - gnutls_free(p); -} - int DTLSClientSession::verifyServerCertificate(gnutls_session_t session) { unsigned int verifyStatus = 0; @@ -63,7 +52,6 @@ int DTLSClientSession::verifyServerCertificate(gnutls_session_t session) { gnutls_datum_t printOut; - certReturn = gnutls_certificate_verification_status_print(verifyStatus, typeReturn, &printOut, 0); if (certReturn < 0) { diff --git a/libraries/networking/src/DTLSSession.h b/libraries/networking/src/DTLSSession.h index 9e9542e147..e379e20a2d 100644 --- a/libraries/networking/src/DTLSSession.h +++ b/libraries/networking/src/DTLSSession.h @@ -19,6 +19,19 @@ #include "DummyDTLSSession.h" #include "HifiSockAddr.h" +// fix for lnk2001 link error on windows +// call xgnutls_free instead of gnutls_free +// http://stackoverflow.com/questions/14593949/getting-error-lnk2001-unresolved-external-symbol-gnutls-free-when-using-gnut + +#ifdef WIN32 +typedef void (*gnutls_free_function) (void *); +__declspec(dllimport) extern gnutls_free_function gnutls_free; +#endif + +void xgnutls_free(void* gnutlsPtr){ + gnutls_free(gnutlsPtr); +} + class DTLSSession : public DummyDTLSSession { Q_OBJECT public: From 38867a2f099b8cf35bfdf8de7507524d8ec1222c Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 12:14:37 -0700 Subject: [PATCH 339/595] fix for re-declarations of xgnutls_free --- libraries/networking/src/DTLSSession.cpp | 4 ++++ libraries/networking/src/DTLSSession.h | 4 +--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/libraries/networking/src/DTLSSession.cpp b/libraries/networking/src/DTLSSession.cpp index 7d375ec327..addfd7b09a 100644 --- a/libraries/networking/src/DTLSSession.cpp +++ b/libraries/networking/src/DTLSSession.cpp @@ -14,6 +14,10 @@ #include "NodeList.h" #include "DTLSSession.h" +void xgnutls_free(void* gnutlsPtr){ + gnutls_free(gnutlsPtr); +} + int DTLSSession::socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms) { DTLSSession* session = static_cast(ptr); QUdpSocket& dtlsSocket = session->_dtlsSocket; diff --git a/libraries/networking/src/DTLSSession.h b/libraries/networking/src/DTLSSession.h index e379e20a2d..0db791c8f8 100644 --- a/libraries/networking/src/DTLSSession.h +++ b/libraries/networking/src/DTLSSession.h @@ -28,9 +28,7 @@ typedef void (*gnutls_free_function) (void *); __declspec(dllimport) extern gnutls_free_function gnutls_free; #endif -void xgnutls_free(void* gnutlsPtr){ - gnutls_free(gnutlsPtr); -} +void xgnutls_free(void* gnutlsPtr); class DTLSSession : public DummyDTLSSession { Q_OBJECT From de475ee46cafd67d4ffea57e680d81309445b020 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Thu, 10 Apr 2014 12:19:27 -0700 Subject: [PATCH 340/595] Update behavior of chat window close button Use a stylesheet to suppress highlighting of the background when pressing the button down. Instead, it will change the image. Unfortunately I wasn't able to find a way to do this without requiring an extra image, or by doing it through the icon system. The different icon states didn't seem to take effect for button presses, and using opacity in the stylesheet doesn't work yet for `QPushButton`s. --- interface/resources/images/close_down.svg | 79 +++++++++++++++++++++++ interface/resources/resources.qrc | 13 ++-- interface/ui/chatWindow.ui | 18 ++++-- 3 files changed, 100 insertions(+), 10 deletions(-) create mode 100644 interface/resources/images/close_down.svg diff --git a/interface/resources/images/close_down.svg b/interface/resources/images/close_down.svg new file mode 100644 index 0000000000..f36865fff1 --- /dev/null +++ b/interface/resources/images/close_down.svg @@ -0,0 +1,79 @@ + + + + + + image/svg+xml + + Slice 1 + + + + + Slice 1 + Created with Sketch (http://www.bohemiancoding.com/sketch) + + + + + + + + diff --git a/interface/resources/resources.qrc b/interface/resources/resources.qrc index 35c0e40270..bc41f41784 100644 --- a/interface/resources/resources.qrc +++ b/interface/resources/resources.qrc @@ -1,8 +1,9 @@ - - images/close.svg - images/kill-script.svg - images/reload.svg - images/stop.svg - + + images/close_down.svg + images/close.svg + images/kill-script.svg + images/reload.svg + images/stop.svg + diff --git a/interface/ui/chatWindow.ui b/interface/ui/chatWindow.ui index 60a0c6badd..095a2ba8f9 100644 --- a/interface/ui/chatWindow.ui +++ b/interface/ui/chatWindow.ui @@ -96,13 +96,23 @@ Qt::NoFocus + + QPushButton { + background-color: rgba( 0, 0, 0, 0% ); + border: none; + image: url(:images/close.svg) +} + + +QPushButton:pressed { + background-color: rgba( 0, 0, 0, 0% ); + border: none; + image: url(:images/close_down.svg) +} + - - - :/images/close.svg:/images/close.svg - true From 9912c4c9a7af818bc5df08245dd74357b399af97 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 12:24:41 -0700 Subject: [PATCH 341/595] just call free instead of gnutls_free on windows --- libraries/networking/src/DTLSClientSession.cpp | 7 ++++++- libraries/networking/src/DTLSSession.cpp | 4 ---- libraries/networking/src/DTLSSession.h | 11 ----------- 3 files changed, 6 insertions(+), 16 deletions(-) diff --git a/libraries/networking/src/DTLSClientSession.cpp b/libraries/networking/src/DTLSClientSession.cpp index 14de3dfb0c..367f162cbe 100644 --- a/libraries/networking/src/DTLSClientSession.cpp +++ b/libraries/networking/src/DTLSClientSession.cpp @@ -59,7 +59,12 @@ int DTLSClientSession::verifyServerCertificate(gnutls_session_t session) { } qDebug() << "Gnutls certificate verification status:" << reinterpret_cast(printOut.data); - xgnutls_free(printOut.data); + +#ifdef WIN32 + free(printOut.data) +#else + gnutls_free(printOut.data); +#endif if (verifyStatus != 0) { qDebug() << "Server provided certificate for DTLS is not trusted. Can not complete handshake."; diff --git a/libraries/networking/src/DTLSSession.cpp b/libraries/networking/src/DTLSSession.cpp index addfd7b09a..7d375ec327 100644 --- a/libraries/networking/src/DTLSSession.cpp +++ b/libraries/networking/src/DTLSSession.cpp @@ -14,10 +14,6 @@ #include "NodeList.h" #include "DTLSSession.h" -void xgnutls_free(void* gnutlsPtr){ - gnutls_free(gnutlsPtr); -} - int DTLSSession::socketPullTimeout(gnutls_transport_ptr_t ptr, unsigned int ms) { DTLSSession* session = static_cast(ptr); QUdpSocket& dtlsSocket = session->_dtlsSocket; diff --git a/libraries/networking/src/DTLSSession.h b/libraries/networking/src/DTLSSession.h index 0db791c8f8..9e9542e147 100644 --- a/libraries/networking/src/DTLSSession.h +++ b/libraries/networking/src/DTLSSession.h @@ -19,17 +19,6 @@ #include "DummyDTLSSession.h" #include "HifiSockAddr.h" -// fix for lnk2001 link error on windows -// call xgnutls_free instead of gnutls_free -// http://stackoverflow.com/questions/14593949/getting-error-lnk2001-unresolved-external-symbol-gnutls-free-when-using-gnut - -#ifdef WIN32 -typedef void (*gnutls_free_function) (void *); -__declspec(dllimport) extern gnutls_free_function gnutls_free; -#endif - -void xgnutls_free(void* gnutlsPtr); - class DTLSSession : public DummyDTLSSession { Q_OBJECT public: From 86b0b786925235f03d3149d70f788d297bd97a28 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 10 Apr 2014 12:27:52 -0700 Subject: [PATCH 342/595] add a missing semi-colon for windows build --- libraries/networking/src/DTLSClientSession.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/networking/src/DTLSClientSession.cpp b/libraries/networking/src/DTLSClientSession.cpp index 367f162cbe..72384fbd10 100644 --- a/libraries/networking/src/DTLSClientSession.cpp +++ b/libraries/networking/src/DTLSClientSession.cpp @@ -61,7 +61,7 @@ int DTLSClientSession::verifyServerCertificate(gnutls_session_t session) { qDebug() << "Gnutls certificate verification status:" << reinterpret_cast(printOut.data); #ifdef WIN32 - free(printOut.data) + free(printOut.data); #else gnutls_free(printOut.data); #endif From 16a2367b294b28284db382a60671a63df1af1b6f Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Thu, 10 Apr 2014 12:34:45 -0700 Subject: [PATCH 343/595] Update chat window to only scroll when at the bottom It can be frustrating when scrolling up to read a message to have the window forcibly scrolled to the bottom when a new message appears. --- interface/src/ui/ChatWindow.cpp | 28 ++++++++++++++++++++++++++-- interface/src/ui/ChatWindow.h | 2 ++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/interface/src/ui/ChatWindow.cpp b/interface/src/ui/ChatWindow.cpp index 1230140fc8..c164ea3fb3 100644 --- a/interface/src/ui/ChatWindow.cpp +++ b/interface/src/ui/ChatWindow.cpp @@ -154,10 +154,18 @@ void ChatWindow::addTimeStamp() { "padding: 4px;"); timeLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); timeLabel->setAlignment(Qt::AlignHCenter); + + bool atBottom = isAtBottom(); + ui->messagesGridLayout->addWidget(timeLabel, ui->messagesGridLayout->rowCount(), 0, 1, 2); ui->messagesGridLayout->parentWidget()->updateGeometry(); + Application::processEvents(); numMessagesAfterLastTimeStamp = 0; + + if (atBottom) { + scrollToBottom(); + } } } @@ -245,12 +253,15 @@ void ChatWindow::messageReceived(const QXmppMessage& message) { messageLabel->setStyleSheet(messageLabel->styleSheet() + "; background-color: #e1e8ea"); } + bool atBottom = isAtBottom(); ui->messagesGridLayout->addWidget(userLabel, ui->messagesGridLayout->rowCount(), 0); ui->messagesGridLayout->addWidget(messageLabel, ui->messagesGridLayout->rowCount() - 1, 1); ui->messagesGridLayout->parentWidget()->updateGeometry(); Application::processEvents(); - QScrollBar* verticalScrollBar = ui->messagesScrollArea->verticalScrollBar(); - verticalScrollBar->setSliderPosition(verticalScrollBar->maximum()); + + if (atBottom) { + scrollToBottom(); + } ++numMessagesAfterLastTimeStamp; if (message.stamp().isValid()) { @@ -260,4 +271,17 @@ void ChatWindow::messageReceived(const QXmppMessage& message) { } } +bool ChatWindow::isAtBottom() { + QScrollBar* verticalScrollBar = ui->messagesScrollArea->verticalScrollBar(); + qDebug() << "Checking for bottom " << verticalScrollBar->sliderPosition() << " " << verticalScrollBar->maximum(); + return verticalScrollBar->sliderPosition() == verticalScrollBar->maximum(); +} + +// Scroll chat message area to bottom. +void ChatWindow::scrollToBottom() { + QScrollBar* verticalScrollBar = ui->messagesScrollArea->verticalScrollBar(); + qDebug() << "Scrolling to " << verticalScrollBar->maximum(); + verticalScrollBar->setSliderPosition(verticalScrollBar->maximum()); +} + #endif diff --git a/interface/src/ui/ChatWindow.h b/interface/src/ui/ChatWindow.h index cb9619cc42..46e7de1c39 100644 --- a/interface/src/ui/ChatWindow.h +++ b/interface/src/ui/ChatWindow.h @@ -48,6 +48,8 @@ private: #endif void startTimerForTimeStamps(); void addTimeStamp(); + bool isAtBottom(); + void scrollToBottom(); Ui::ChatWindow* ui; int numMessagesAfterLastTimeStamp; From ea93be15f1b59df4c2568f0ab65d6f37cb54d612 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Thu, 10 Apr 2014 12:44:51 -0700 Subject: [PATCH 344/595] Fixed dometime using wrong texdir --- interface/src/ModelUploader.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index d22097a00c..edbc6c0ad9 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -307,13 +307,13 @@ bool ModelUploader::addTextures(const QString& texdir, const QString fbxFile) { foreach (FBXMesh mesh, geometry.meshes) { foreach (FBXMeshPart part, mesh.parts) { if (!part.diffuseFilename.isEmpty()) { - if (!addPart(QFileInfo(fbxFile).path() + "/" + part.diffuseFilename, + if (!addPart(texdir + "/" + part.diffuseFilename, QString("texture%1").arg(++_texturesCount))) { return false; } } if (!part.normalFilename.isEmpty()) { - if (!addPart(QFileInfo(fbxFile).path() + "/" + part.normalFilename, + if (!addPart(texdir + "/" + part.normalFilename, QString("texture%1").arg(++_texturesCount))) { return false; } From ac9ead36e29baf63709c017e1f746817bd21aa39 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Thu, 10 Apr 2014 13:10:24 -0700 Subject: [PATCH 345/595] fix crash: don't access null action In particular, don't crash on pressing Enter when lacking qxmpp support --- interface/src/Menu.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 8eead4acdc..80007da485 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -707,7 +707,12 @@ bool Menu::isOptionChecked(const QString& menuOption) { } void Menu::triggerOption(const QString& menuOption) { - _actionHash.value(menuOption)->trigger(); + QAction* action = _actionHash.value(menuOption); + if (action) { + action->trigger(); + } else { + qDebug() << "NULL Action for menuOption '" << menuOption << "'"; + } } QAction* Menu::getActionForOption(const QString& menuOption) { From 9c662acc9d6dba0202c27044f5c4299d73c6b81d Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Thu, 10 Apr 2014 14:40:35 -0700 Subject: [PATCH 346/595] Modified max glow + don't glow you own avatar --- interface/src/avatar/Avatar.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 1107bcd21a..4a6d0fbcf2 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -211,9 +211,13 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode) { // glow when moving far away const float GLOW_DISTANCE = 20.0f; const float GLOW_MAX_LOUDNESS = 2500.0f; - const float MAX_GLOW = 0.7f; - const float GLOW_FROM_AVERAGE_LOUDNESS = MAX_GLOW * getHeadData()->getAudioLoudness() / GLOW_MAX_LOUDNESS; - Glower glower(_moving && distanceToTarget > GLOW_DISTANCE && renderMode == NORMAL_RENDER_MODE ? 1.0f : GLOW_FROM_AVERAGE_LOUDNESS); + const float MAX_GLOW = 0.5f; + const float GLOW_FROM_AVERAGE_LOUDNESS = ((this == Application::getInstance()->getAvatar()) + ? 0.0f + : MAX_GLOW * getHeadData()->getAudioLoudness() / GLOW_MAX_LOUDNESS); + Glower glower(_moving && distanceToTarget > GLOW_DISTANCE && renderMode == NORMAL_RENDER_MODE + ? 1.0f + : GLOW_FROM_AVERAGE_LOUDNESS); // render body if (Menu::getInstance()->isOptionChecked(MenuOption::Avatars)) { From 6cf971c849b6d9dd623aa4f40e29310709102202 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 10 Apr 2014 14:51:43 -0700 Subject: [PATCH 347/595] More intersection-avoidance tweaks. --- interface/src/Application.cpp | 21 ++++++++++++--------- interface/src/avatar/MyAvatar.cpp | 2 +- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index d90b5835e5..2ab73c9daf 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -519,7 +519,6 @@ void Application::paintGL() { glEnable(GL_LINE_SMOOTH); - const float PUSHBACK_RADIUS = 0.2f; if (OculusManager::isConnected()) { _myCamera.setUpShift(0.0f); _myCamera.setDistance(0.0f); @@ -533,8 +532,9 @@ void Application::paintGL() { _myCamera.setTargetRotation(_myAvatar->getHead()->getCameraOrientation()); glm::vec3 planeNormal = _myCamera.getTargetRotation() * IDENTITY_FRONT; - float combinedRadius = _myCamera.getNearClip() + _myAvatar->getScale() * PUSHBACK_RADIUS; - glm::vec4 plane(planeNormal, -glm::dot(planeNormal, _myCamera.getTargetPosition()) - combinedRadius); + const float BASE_PUSHBACK_RADIUS = 0.25f; + float pushbackRadius = _myCamera.getNearClip() + _myAvatar->getScale() * BASE_PUSHBACK_RADIUS; + glm::vec4 plane(planeNormal, -glm::dot(planeNormal, _myCamera.getTargetPosition()) - pushbackRadius); // push camera out of any intersecting avatars float pushback = 0.0f; @@ -544,10 +544,11 @@ void Application::paintGL() { continue; } if (glm::distance(avatar->getPosition(), _myCamera.getTargetPosition()) > - avatar->getBoundingRadius() + combinedRadius) { + avatar->getBoundingRadius() + pushbackRadius) { continue; } - CollisionList collisions(4); + static CollisionList collisions(64); + collisions.clear(); if (!avatar->findPlaneCollisions(plane, collisions)) { continue; } @@ -555,10 +556,11 @@ void Application::paintGL() { pushback = qMax(pushback, glm::length(collisions.getCollision(i)->_penetration)); } } - if (pushback > 0.0f) { - _myCamera.setTargetPosition(_myCamera.getTargetPosition() + - _myCamera.getTargetRotation() * glm::vec3(0.0f, 0.0f, pushback)); - } + const float MAX_PUSHBACK = 0.35f; + const float PUSHBACK_DECAY = 0.5f; + _myCamera.setDistance(qMax(qMin(pushback, MAX_PUSHBACK * _myAvatar->getScale()), + _myCamera.getDistance() * PUSHBACK_DECAY)); + } else if (_myCamera.getMode() == CAMERA_MODE_THIRD_PERSON) { _myCamera.setTightness(0.0f); // Camera is directly connected to head without smoothing _myCamera.setTargetPosition(_myAvatar->getUprightHeadPosition()); @@ -575,6 +577,7 @@ void Application::paintGL() { // if the head would intersect the near clip plane, we must push the camera out glm::vec3 relativePosition = glm::inverse(_myCamera.getTargetRotation()) * (eyePosition - _myCamera.getTargetPosition()); + const float PUSHBACK_RADIUS = 0.2f; float pushback = relativePosition.z + _myCamera.getNearClip() + _myAvatar->getScale() * PUSHBACK_RADIUS - _myCamera.getDistance(); if (pushback > 0.0f) { diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 7a05c593db..a4f4cce79d 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -647,7 +647,7 @@ void MyAvatar::renderBody(RenderMode renderMode) { _skeletonModel.render(1.0f, modelRenderMode); // Render head so long as the camera isn't inside it - const float RENDER_HEAD_CUTOFF_DISTANCE = 0.40f; + const float RENDER_HEAD_CUTOFF_DISTANCE = 0.50f; Camera* myCamera = Application::getInstance()->getCamera(); if (renderMode != NORMAL_RENDER_MODE || (glm::length(myCamera->getPosition() - getHead()->calculateAverageEyePosition()) > RENDER_HEAD_CUTOFF_DISTANCE * _scale)) { From f0463a5679eb9ce774582403b1bd57ba5e7b88d8 Mon Sep 17 00:00:00 2001 From: Thijs Wenker Date: Fri, 11 Apr 2014 00:45:38 +0200 Subject: [PATCH 348/595] Fixed docking of ChatWindow Temporary Pin Icon, replace with a nice looking one please --- interface/resources/images/pin.svg | 98 ++++++++++++++++++++++++ interface/resources/images/pinned.svg | 106 ++++++++++++++++++++++++++ interface/resources/resources.qrc | 2 + interface/src/Menu.cpp | 2 +- interface/src/ui/ChatWindow.cpp | 19 ++++- interface/src/ui/ChatWindow.h | 2 + interface/ui/chatWindow.ui | 57 +++++++++++++- 7 files changed, 283 insertions(+), 3 deletions(-) create mode 100644 interface/resources/images/pin.svg create mode 100644 interface/resources/images/pinned.svg diff --git a/interface/resources/images/pin.svg b/interface/resources/images/pin.svg new file mode 100644 index 0000000000..ec968a1ec1 --- /dev/null +++ b/interface/resources/images/pin.svg @@ -0,0 +1,98 @@ + + + + + + image/svg+xml + + Slice 1 + + + + + Slice 1 + Created with Sketch (http://www.bohemiancoding.com/sketch) + + + + + + + + diff --git a/interface/resources/images/pinned.svg b/interface/resources/images/pinned.svg new file mode 100644 index 0000000000..bda6f0e747 --- /dev/null +++ b/interface/resources/images/pinned.svg @@ -0,0 +1,106 @@ + + + + + + image/svg+xml + + Slice 1 + + + + + Slice 1 + Created with Sketch (http://www.bohemiancoding.com/sketch) + + + + + + + + + diff --git a/interface/resources/resources.qrc b/interface/resources/resources.qrc index 35c0e40270..40428f0f80 100644 --- a/interface/resources/resources.qrc +++ b/interface/resources/resources.qrc @@ -4,5 +4,7 @@ images/kill-script.svg images/reload.svg images/stop.svg + images/pin.svg + images/pinned.svg diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 8eead4acdc..9408f18c24 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -1207,7 +1207,7 @@ void Menu::showMetavoxelEditor() { void Menu::showChat() { QMainWindow* mainWindow = Application::getInstance()->getWindow(); if (!_chatWindow) { - mainWindow->addDockWidget(Qt::NoDockWidgetArea, _chatWindow = new ChatWindow()); + mainWindow->addDockWidget(Qt::RightDockWidgetArea, _chatWindow = new ChatWindow()); } if (!_chatWindow->toggleViewAction()->isChecked()) { int width = _chatWindow->width(); diff --git a/interface/src/ui/ChatWindow.cpp b/interface/src/ui/ChatWindow.cpp index 0060cb839c..8a83ba680b 100644 --- a/interface/src/ui/ChatWindow.cpp +++ b/interface/src/ui/ChatWindow.cpp @@ -12,10 +12,12 @@ #include #include #include +#include #include #include #include #include +#include #include "Application.h" #include "FlowLayout.h" @@ -35,7 +37,9 @@ ChatWindow::ChatWindow() : { ui->setupUi(this); - // remove the title bar (see the Qt docs on setTitleBarWidget) + // remove the title bar (see the Qt docs on setTitleBarWidget), but we keep it for undocking + // + titleBar = titleBarWidget(); setTitleBarWidget(new QWidget()); FlowLayout* flowLayout = new FlowLayout(0, 4, 4); @@ -260,3 +264,16 @@ void ChatWindow::messageReceived(const QXmppMessage& message) { } #endif + +void ChatWindow::togglePinned() { + QMainWindow* mainWindow = Application::getInstance()->getWindow(); + mainWindow->removeDockWidget(this); + if (ui->togglePinnedButton->isChecked()) { + mainWindow->addDockWidget(ui->togglePinnedButton->isChecked() ? Qt::RightDockWidgetArea : Qt::NoDockWidgetArea, this); + } + if (!this->toggleViewAction()->isChecked()) { + this->toggleViewAction()->trigger(); + } + this->setFloating(!ui->togglePinnedButton->isChecked()); + setTitleBarWidget(ui->togglePinnedButton->isChecked()?new QWidget():titleBar); +} \ No newline at end of file diff --git a/interface/src/ui/ChatWindow.h b/interface/src/ui/ChatWindow.h index cb9619cc42..614afc1ef1 100644 --- a/interface/src/ui/ChatWindow.h +++ b/interface/src/ui/ChatWindow.h @@ -50,12 +50,14 @@ private: void addTimeStamp(); Ui::ChatWindow* ui; + QWidget* titleBar; int numMessagesAfterLastTimeStamp; QDateTime lastMessageStamp; private slots: void connected(); void timeout(); + void togglePinned(); #ifdef HAVE_QXMPP void error(QXmppClient::Error error); void participantsChanged(); diff --git a/interface/ui/chatWindow.ui b/interface/ui/chatWindow.ui index 60a0c6badd..c46e692fc6 100644 --- a/interface/ui/chatWindow.ui +++ b/interface/ui/chatWindow.ui @@ -20,7 +20,7 @@ font-family: Helvetica, Arial, sans-serif; - QDockWidget::NoDockWidgetFeatures + QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable Qt::NoDockWidgetArea @@ -79,6 +79,45 @@ + + + + + 0 + 0 + + + + + 16 + 16 + + + + Qt::NoFocus + + + + + + + :/images/pin.svg + :/images/pinned.svg:/images/pin.svg + + + true + + + true + + + false + + + true + + + @@ -204,6 +243,22 @@ + + togglePinnedButton + clicked() + ChatWindow + togglePinned() + + + 390 + 42 + + + 550 + 42 + + + closeButton clicked() From 3af3b29588d0f9060425e5af4e1d00e5f7b2842b Mon Sep 17 00:00:00 2001 From: Stojce Slavkovski Date: Fri, 11 Apr 2014 00:54:54 +0200 Subject: [PATCH 349/595] removed dependency on QT resource --- interface/resources/styles/preferences.qss | 10 ++++++ interface/ui/preferencesDialog.ui | 42 +++++++++++++--------- 2 files changed, 35 insertions(+), 17 deletions(-) diff --git a/interface/resources/styles/preferences.qss b/interface/resources/styles/preferences.qss index ee587b70da..643fd13a77 100644 --- a/interface/resources/styles/preferences.qss +++ b/interface/resources/styles/preferences.qss @@ -9,3 +9,13 @@ QLabel#advancedTuningLabel { background-repeat: no-repeat; background-position: left center; } + +QPushButton#buttonBrowseHead, +QPushButton#buttonBrowseBody { + background-image: url(styles/search.svg); + background-repeat: no-repeat; + background-position: center center; + background-color: #fff; + border-radius: 0; + padding: 0; +} diff --git a/interface/ui/preferencesDialog.ui b/interface/ui/preferencesDialog.ui index f28bcde60c..a151a499c6 100644 --- a/interface/ui/preferencesDialog.ui +++ b/interface/ui/preferencesDialog.ui @@ -351,18 +351,23 @@ color: #0e7077 30 + + + 30 + 30 + + - background-color: #fff; -border-radius: 0; -padding: 0; + - - - :/styles/search.svg - + + + 30 + 30 + @@ -449,18 +454,23 @@ padding: 0; 30 + + + 30 + 30 + + - background-color: #fff; -border-radius: 0; -padding: 0; + - - - :/styles/search.svg - + + + 30 + 30 + @@ -1327,9 +1337,7 @@ padding: 0; 1 - - - + cancelButton From 66b6328687114ff429ac00b00f0103db316ac3ab Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Thu, 10 Apr 2014 16:58:52 -0700 Subject: [PATCH 350/595] protection against bad avatar-avatar collisions Also with logging if we encounter incorrectly large penetration depths --- interface/src/avatar/MyAvatar.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 7a05c593db..6c69fd3e3a 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -62,6 +62,7 @@ MyAvatar::MyAvatar() : _isThrustOn(false), _thrustMultiplier(1.0f), _moveTarget(0,0,0), + _lastBodyPenetration(0.0f), _moveTargetStepCounter(0), _lookAtTargetAvatar(), _shouldRender(true), @@ -681,7 +682,7 @@ void MyAvatar::updateThrust(float deltaTime) { _thrust -= _driveKeys[DOWN] * _scale * THRUST_MAG_DOWN * _thrustMultiplier * deltaTime * up; // attenuate thrust when in penetration - if (glm::dot(_thrust, _lastBodyPenetration) > 0.0f) { + if (glm::dot(_thrust, _lastBodyPenetration) > EPSILON) { const float MAX_BODY_PENETRATION_DEPTH = 0.6f * _skeletonModel.getBoundingShapeRadius(); float penetrationFactor = glm::min(1.0f, glm::length(_lastBodyPenetration) / MAX_BODY_PENETRATION_DEPTH); glm::vec3 penetrationDirection = glm::normalize(_lastBodyPenetration); @@ -932,7 +933,11 @@ void MyAvatar::updateCollisionWithAvatars(float deltaTime) { CollisionInfo collision; if (ShapeCollider::collideShapesCoarse(myShapes, theirShapes, collision)) { - if (glm::length2(collision._penetration) > EPSILON) { + float penetrationDepth = glm::length(collision._penetration); + if (penetrationDepth > myBoundingRadius) { + qDebug() << "WARNING: ignoring avatar-avatar penetration depth " << penetrationDepth; + } + else if (penetrationDepth > EPSILON) { setPosition(getPosition() - BODY_COLLISION_RESOLUTION_FACTOR * collision._penetration); _lastBodyPenetration += collision._penetration; emit collisionWithAvatar(getSessionUUID(), avatar->getSessionUUID(), collision); From 197adce4debef454f373a40169341b8c8044723f Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 10 Apr 2014 17:14:49 -0700 Subject: [PATCH 351/595] Fall intersection off with angle to other avatar. --- interface/src/Application.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 8caf339a75..1f7ca11d71 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -547,13 +547,19 @@ void Application::paintGL() { avatar->getBoundingRadius() + pushbackRadius) { continue; } + float angle = angleBetween(avatar->getPosition() - _myCamera.getTargetPosition(), planeNormal); + if (angle > PI_OVER_TWO) { + continue; + } + float scale = qMax(angle / PI_OVER_TWO, 0.0f); + scale = 1.0f - powf(scale, 4.0f); static CollisionList collisions(64); collisions.clear(); if (!avatar->findPlaneCollisions(plane, collisions)) { continue; } for (int i = 0; i < collisions.size(); i++) { - pushback = qMax(pushback, glm::length(collisions.getCollision(i)->_penetration)); + pushback = qMax(pushback, glm::length(collisions.getCollision(i)->_penetration) * scale); } } const float MAX_PUSHBACK = 0.35f; From a436b599718580f0325566f1af01e76449f8f876 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Thu, 10 Apr 2014 17:14:51 -0700 Subject: [PATCH 352/595] save settings for change in: identity, position --- interface/src/Application.cpp | 6 ++++++ interface/src/Application.h | 3 +++ interface/src/Menu.cpp | 2 +- interface/src/avatar/MyAvatar.cpp | 1 + interface/src/avatar/MyAvatar.h | 3 +++ interface/src/location/LocationManager.cpp | 4 ++-- interface/src/location/LocationManager.h | 1 - 7 files changed, 16 insertions(+), 4 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index f6b0d37dd4..768009183e 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -250,6 +250,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : QMetaObject::invokeMethod(&accountManager, "checkAndSignalForAccessToken", Qt::QueuedConnection); _settings = new QSettings(this); + _numChangedSettings = 0; // Check to see if the user passed in a command line option for loading a local // Voxel File. @@ -406,6 +407,7 @@ void Application::saveSettings() { _voxelImporter->saveSettings(_settings); } _settings->sync(); + _numChangedSettings = 0; } @@ -1271,6 +1273,9 @@ void Application::idle() { // After finishing all of the above work, restart the idle timer, allowing 2ms to process events. idleTimer->start(2); } + if (_numChangedSettings > 0) { + saveSettings(); + } } } @@ -1617,6 +1622,7 @@ void Application::init() { connect(_rearMirrorTools, SIGNAL(restoreView()), SLOT(restoreMirrorView())); connect(_rearMirrorTools, SIGNAL(shrinkView()), SLOT(shrinkMirrorView())); connect(_rearMirrorTools, SIGNAL(resetView()), SLOT(resetSensors())); + connect(_myAvatar, SIGNAL(transformChanged()), this, SLOT(bumpSettings())); } void Application::closeMirrorView() { diff --git a/interface/src/Application.h b/interface/src/Application.h index eedb866d53..278283a7e2 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -286,6 +286,8 @@ public slots: void uploadHead(); void uploadSkeleton(); + void bumpSettings() { ++_numChangedSettings; } + private slots: void timer(); void idle(); @@ -376,6 +378,7 @@ private: QNetworkAccessManager* _networkAccessManager; QMutex _settingsMutex; QSettings* _settings; + int _numChangedSettings; QUndoStack _undoStack; diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 8eead4acdc..a074a7995b 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -898,6 +898,7 @@ void Menu::editPreferences() { if (shouldDispatchIdentityPacket) { applicationInstance->getAvatar()->sendIdentityPacket(); + applicationInstance->bumpSettings(); } applicationInstance->getAvatar()->getHead()->setPupilDilation(pupilDilation->value() / (float)pupilDilation->maximum()); @@ -1063,7 +1064,6 @@ void Menu::goToLocation() { QString currentLocation = QString("%1, %2, %3").arg(QString::number(avatarPos.x), QString::number(avatarPos.y), QString::number(avatarPos.z)); - QInputDialog coordinateDialog(Application::getInstance()->getWindow()); coordinateDialog.setWindowTitle("Go to Location"); coordinateDialog.setLabelText("Coordinate as x,y,z:"); diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 8f77f6226a..e587f38ed0 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -1175,6 +1175,7 @@ void MyAvatar::goToLocationFromResponse(const QJsonObject& jsonObject) { glm::vec3 newPosition = glm::vec3(coordinateItems[0].toFloat(), coordinateItems[1].toFloat(), coordinateItems[2].toFloat()) - newOrientation * IDENTITY_FRONT * DISTANCE_TO_USER; setPosition(newPosition); + emit transformChanged(); } } diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index ec33847255..66ab322444 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -106,6 +106,9 @@ public slots: glm::vec3 getThrust() { return _thrust; }; void setThrust(glm::vec3 newThrust) { _thrust = newThrust; } +signals: + void transformChanged(); + private: bool _mousePressed; float _bodyPitchDelta; // degrees diff --git a/interface/src/location/LocationManager.cpp b/interface/src/location/LocationManager.cpp index 7d22dde040..8009551b6c 100644 --- a/interface/src/location/LocationManager.cpp +++ b/interface/src/location/LocationManager.cpp @@ -118,8 +118,6 @@ void LocationManager::checkForMultipleDestinations() { Application::getInstance()->getAvatar()->goToLocationFromResponse(_placeData); return; } - - emit locationChanged(); } } @@ -178,6 +176,7 @@ void LocationManager::goToOrientation(QString orientation) { glm::quat avatarOrientation = myAvatar->getOrientation(); if (newAvatarOrientation != avatarOrientation) { myAvatar->setOrientation(newAvatarOrientation); + emit myAvatar->transformChanged(); } } } @@ -211,6 +210,7 @@ bool LocationManager::goToDestination(QString destination) { qDebug("Going To Location: %f, %f, %f...", x, y, z); myAvatar->setPosition(newAvatarPos); + emit myAvatar->transformChanged(); } return true; diff --git a/interface/src/location/LocationManager.h b/interface/src/location/LocationManager.h index 26e1cb52d5..ac66b3d08b 100644 --- a/interface/src/location/LocationManager.h +++ b/interface/src/location/LocationManager.h @@ -48,7 +48,6 @@ private: signals: void creationCompleted(LocationManager::NamedLocationCreateResponse response); void multipleDestinationsFound(const QJsonObject& userData, const QJsonObject& placeData); - void locationChanged(); private slots: void namedLocationDataReceived(const QJsonObject& data); From af158a3a94b55d74db036c45131724eb58cf450f Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Thu, 10 Apr 2014 17:34:12 -0700 Subject: [PATCH 353/595] save settings when any checkable menu item changes --- interface/src/Menu.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index a074a7995b..ece747221e 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -683,6 +683,7 @@ QAction* Menu::addCheckableActionToQMenuAndActionHash(QMenu* destinationMenu, QAction::NoRole, menuItemLocation); action->setCheckable(true); action->setChecked(checked); + connect(action, SIGNAL(changed()), Application::getInstance(), SLOT(bumpSettings())); return action; } From d712588b3616d20ef865267cf3633d07f728fe34 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 10 Apr 2014 17:35:47 -0700 Subject: [PATCH 354/595] Better rolloff. --- interface/src/Application.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 1f7ca11d71..84ce1f7efe 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -551,8 +551,8 @@ void Application::paintGL() { if (angle > PI_OVER_TWO) { continue; } - float scale = qMax(angle / PI_OVER_TWO, 0.0f); - scale = 1.0f - powf(scale, 4.0f); + float scale = 1.0f - angle / PI_OVER_TWO; + scale = qMin(1.0f, scale * 2.5f); static CollisionList collisions(64); collisions.clear(); if (!avatar->findPlaneCollisions(plane, collisions)) { From f7862eb600056e6f9955af89137281c7aac95164 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Fri, 11 Apr 2014 08:58:26 -0700 Subject: [PATCH 355/595] check for bad deltaTime during avatar-avatar collisions --- 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 6c69fd3e3a..a716d6f49a 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -910,7 +910,7 @@ void MyAvatar::updateCollisionWithAvatars(float deltaTime) { updateShapePositions(); float myBoundingRadius = getBoundingRadius(); - const float BODY_COLLISION_RESOLUTION_FACTOR = deltaTime / BODY_COLLISION_RESOLUTION_TIMESCALE; + const float BODY_COLLISION_RESOLUTION_FACTOR = glm::max(1.0f, deltaTime / BODY_COLLISION_RESOLUTION_TIMESCALE); foreach (const AvatarSharedPointer& avatarPointer, avatars) { Avatar* avatar = static_cast(avatarPointer.data()); From 9fcb656027458de398910f281a0a3dcafc76bec8 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 11 Apr 2014 09:26:45 -0700 Subject: [PATCH 356/595] add a newline to FindGnuTLS and fix filename in header --- cmake/modules/FindGnuTLS.cmake | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmake/modules/FindGnuTLS.cmake b/cmake/modules/FindGnuTLS.cmake index 724dcbe171..0e1899864b 100644 --- a/cmake/modules/FindGnuTLS.cmake +++ b/cmake/modules/FindGnuTLS.cmake @@ -1,5 +1,5 @@ # -# FindFaceshift.cmake +# FindGnuTLS.cmake # # Try to find the GnuTLS library # @@ -38,4 +38,4 @@ else () message(STATUS "the GnuTLS lib folder. Replace $GnuTLS-DIR in the command with the directory") message(STATUS "containing GnuTLS.") endif () -endif () \ No newline at end of file +endif () From 00e2ff93e39a53f92830bbe0ff38446939f9fd17 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Fri, 11 Apr 2014 10:08:44 -0700 Subject: [PATCH 357/595] Playing around with zooming in while pulling back. --- interface/src/Application.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 84ce1f7efe..b3b8c24b69 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -589,6 +589,9 @@ void Application::paintGL() { if (pushback > 0.0f) { _myCamera.setTargetPosition(_myCamera.getTargetPosition() + _myCamera.getTargetRotation() * glm::vec3(0.0f, 0.0f, pushback)); + float enlargement = _myCamera.getDistance() / (_myCamera.getDistance() + pushback); + _myCamera.setFieldOfView(glm::degrees(2.0f * atanf(enlargement * tanf( + glm::radians(Menu::getInstance()->getFieldOfView() * 0.5f))))); } } From b7725f094da474fbd1068cd686679560cbd590a1 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Fri, 11 Apr 2014 10:19:16 -0700 Subject: [PATCH 358/595] Trying the narrowing effect with pushback for other avatars. --- interface/src/Application.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index b3b8c24b69..df31349624 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -566,6 +566,9 @@ void Application::paintGL() { const float PUSHBACK_DECAY = 0.5f; _myCamera.setDistance(qMax(qMin(pushback, MAX_PUSHBACK * _myAvatar->getScale()), _myCamera.getDistance() * PUSHBACK_DECAY)); + float enlargement = pushbackRadius / (pushbackRadius + _myCamera.getDistance()); + _myCamera.setFieldOfView(glm::degrees(2.0f * atanf(enlargement * tanf( + glm::radians(Menu::getInstance()->getFieldOfView() * 0.5f))))); } else if (_myCamera.getMode() == CAMERA_MODE_THIRD_PERSON) { _myCamera.setTightness(0.0f); // Camera is directly connected to head without smoothing @@ -583,15 +586,17 @@ void Application::paintGL() { // if the head would intersect the near clip plane, we must push the camera out glm::vec3 relativePosition = glm::inverse(_myCamera.getTargetRotation()) * (eyePosition - _myCamera.getTargetPosition()); - const float PUSHBACK_RADIUS = 0.2f; - float pushback = relativePosition.z + _myCamera.getNearClip() + - _myAvatar->getScale() * PUSHBACK_RADIUS - _myCamera.getDistance(); + const float BASE_PUSHBACK_RADIUS = 0.2f; + float pushbackRadius = _myCamera.getNearClip() + _myAvatar->getScale() * BASE_PUSHBACK_RADIUS; + float pushback = relativePosition.z + pushbackRadius - _myCamera.getDistance(); if (pushback > 0.0f) { _myCamera.setTargetPosition(_myCamera.getTargetPosition() + _myCamera.getTargetRotation() * glm::vec3(0.0f, 0.0f, pushback)); - float enlargement = _myCamera.getDistance() / (_myCamera.getDistance() + pushback); + float enlargement = pushbackRadius / (pushbackRadius + pushback); _myCamera.setFieldOfView(glm::degrees(2.0f * atanf(enlargement * tanf( glm::radians(Menu::getInstance()->getFieldOfView() * 0.5f))))); + } else { + _myCamera.setFieldOfView(Menu::getInstance()->getFieldOfView()); } } From 6431d35f86778ea23bfd7fe6ff11cf0bc187ccf5 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 11 Apr 2014 10:19:31 -0700 Subject: [PATCH 359/595] add a missing newline to DomainHandler --- libraries/networking/src/DomainHandler.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/networking/src/DomainHandler.h b/libraries/networking/src/DomainHandler.h index 9a18feb1ed..2cc520991c 100644 --- a/libraries/networking/src/DomainHandler.h +++ b/libraries/networking/src/DomainHandler.h @@ -79,4 +79,4 @@ private: QTimer* _handshakeTimer; }; -#endif // hifi_DomainHandler_h \ No newline at end of file +#endif // hifi_DomainHandler_h From d6534d6026a26b8a68a9ffe21e8b8903f7694a31 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Fri, 11 Apr 2014 11:10:22 -0700 Subject: [PATCH 360/595] Tweak to zoom on pushback. --- interface/src/Application.cpp | 29 ++++++++++++++++++----------- interface/src/Application.h | 1 + 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index df31349624..a7f2d7d7ec 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -151,6 +151,7 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : _lastQueriedViewFrustum(), _lastQueriedTime(usecTimestampNow()), _mirrorViewRect(QRect(MIRROR_VIEW_LEFT_PADDING, MIRROR_VIEW_TOP_PADDING, MIRROR_VIEW_WIDTH, MIRROR_VIEW_HEIGHT)), + _cameraPushback(0.0f), _mouseX(0), _mouseY(0), _lastMouseMove(usecTimestampNow()), @@ -519,6 +520,8 @@ void Application::paintGL() { glEnable(GL_LINE_SMOOTH); + float pushback = 0.0f; + float pushbackFocalLength = 0.0f; if (OculusManager::isConnected()) { _myCamera.setUpShift(0.0f); _myCamera.setDistance(0.0f); @@ -537,7 +540,6 @@ void Application::paintGL() { glm::vec4 plane(planeNormal, -glm::dot(planeNormal, _myCamera.getTargetPosition()) - pushbackRadius); // push camera out of any intersecting avatars - float pushback = 0.0f; foreach (const AvatarSharedPointer& avatarData, _avatarManager.getAvatarHash()) { Avatar* avatar = static_cast(avatarData.data()); if (avatar->isMyAvatar()) { @@ -563,12 +565,9 @@ void Application::paintGL() { } } const float MAX_PUSHBACK = 0.35f; - const float PUSHBACK_DECAY = 0.5f; - _myCamera.setDistance(qMax(qMin(pushback, MAX_PUSHBACK * _myAvatar->getScale()), - _myCamera.getDistance() * PUSHBACK_DECAY)); - float enlargement = pushbackRadius / (pushbackRadius + _myCamera.getDistance()); - _myCamera.setFieldOfView(glm::degrees(2.0f * atanf(enlargement * tanf( - glm::radians(Menu::getInstance()->getFieldOfView() * 0.5f))))); + pushback = qMin(pushback, MAX_PUSHBACK * _myAvatar->getScale()); + const float BASE_PUSHBACK_FOCAL_LENGTH = 0.5f; + pushbackFocalLength = BASE_PUSHBACK_FOCAL_LENGTH * _myAvatar->getScale(); } else if (_myCamera.getMode() == CAMERA_MODE_THIRD_PERSON) { _myCamera.setTightness(0.0f); // Camera is directly connected to head without smoothing @@ -588,16 +587,24 @@ void Application::paintGL() { (eyePosition - _myCamera.getTargetPosition()); const float BASE_PUSHBACK_RADIUS = 0.2f; float pushbackRadius = _myCamera.getNearClip() + _myAvatar->getScale() * BASE_PUSHBACK_RADIUS; - float pushback = relativePosition.z + pushbackRadius - _myCamera.getDistance(); - if (pushback > 0.0f) { + pushback = relativePosition.z + pushbackRadius - _myCamera.getDistance(); + pushbackFocalLength = _myCamera.getDistance(); + } + + // handle pushback, if any + if (pushbackFocalLength > 0.0f) { + const float PUSHBACK_DECAY = 0.5f; + _cameraPushback = qMax(pushback, _cameraPushback * PUSHBACK_DECAY); + if (_cameraPushback > EPSILON) { _myCamera.setTargetPosition(_myCamera.getTargetPosition() + - _myCamera.getTargetRotation() * glm::vec3(0.0f, 0.0f, pushback)); - float enlargement = pushbackRadius / (pushbackRadius + pushback); + _myCamera.getTargetRotation() * glm::vec3(0.0f, 0.0f, _cameraPushback)); + float enlargement = pushbackFocalLength / (pushbackFocalLength + _cameraPushback); _myCamera.setFieldOfView(glm::degrees(2.0f * atanf(enlargement * tanf( glm::radians(Menu::getInstance()->getFieldOfView() * 0.5f))))); } else { _myCamera.setFieldOfView(Menu::getInstance()->getFieldOfView()); } + updateProjectionMatrix(_myCamera, true); } // Update camera position diff --git a/interface/src/Application.h b/interface/src/Application.h index eedb866d53..ed269226fe 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -432,6 +432,7 @@ private: QRect _mirrorViewRect; RearMirrorTools* _rearMirrorTools; + float _cameraPushback; glm::mat4 _untranslatedViewMatrix; glm::vec3 _viewMatrixTranslation; glm::mat4 _projectionMatrix; From 1cd5fec71cc628ec6ea90007204bbed61239d4d5 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 11 Apr 2014 11:42:33 -0700 Subject: [PATCH 361/595] push packet version for assignments --- libraries/networking/src/PacketHeaders.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/networking/src/PacketHeaders.cpp b/libraries/networking/src/PacketHeaders.cpp index fe999fed96..fdbdca3db7 100644 --- a/libraries/networking/src/PacketHeaders.cpp +++ b/libraries/networking/src/PacketHeaders.cpp @@ -58,7 +58,7 @@ PacketVersion versionForPacketType(PacketType type) { return 2; case PacketTypeCreateAssignment: case PacketTypeRequestAssignment: - return 1; + return 2; case PacketTypeVoxelSet: case PacketTypeVoxelSetDestructive: return 1; From 18b364d9d90ecacccb8524ca771b444c9dbfe219 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Fri, 11 Apr 2014 11:57:25 -0700 Subject: [PATCH 362/595] Removed QResources from Interface --- interface/resources/resources.qrc | 9 --------- 1 file changed, 9 deletions(-) delete mode 100644 interface/resources/resources.qrc diff --git a/interface/resources/resources.qrc b/interface/resources/resources.qrc deleted file mode 100644 index 0dc5a27651..0000000000 --- a/interface/resources/resources.qrc +++ /dev/null @@ -1,9 +0,0 @@ - - - styles/search.svg - images/close.svg - images/kill-script.svg - images/reload.svg - images/stop.svg - - From 100c3f8da40658161255f9307db6cd4332caff11 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Fri, 11 Apr 2014 11:59:23 -0700 Subject: [PATCH 363/595] Modify UIs that were using the qrc --- interface/CMakeLists.txt | 5 ----- interface/src/ui/RunningScriptsWidget.cpp | 2 +- interface/ui/chatWindow.ui | 8 +++----- interface/ui/runningScriptsWidget.ui | 16 +++++++--------- 4 files changed, 11 insertions(+), 20 deletions(-) diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index 29943eb4cb..4e58d898af 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -74,11 +74,6 @@ file (GLOB_RECURSE QT_UI_FILES ui/*.ui) # have qt5 wrap them and generate the appropriate header files qt5_wrap_ui(QT_UI_HEADERS "${QT_UI_FILES}") -# grab the resource files in resources -file (GLOB_RECURSE QT_RESOURCE_FILES resources/*.qrc) -# have qt5 wrap them and generate the appropriate source files -qt5_add_resources(QT_RESOURCES "${QT_RESOURCE_FILES}") - # add them to the interface source files set(INTERFACE_SRCS ${INTERFACE_SRCS} "${QT_UI_HEADERS}" "${QT_RESOURCES}") diff --git a/interface/src/ui/RunningScriptsWidget.cpp b/interface/src/ui/RunningScriptsWidget.cpp index dc9ae7c5f8..9a9a1c7486 100644 --- a/interface/src/ui/RunningScriptsWidget.cpp +++ b/interface/src/ui/RunningScriptsWidget.cpp @@ -77,7 +77,7 @@ void RunningScriptsWidget::setRunningScripts(const QStringList& list) scriptName->setToolTip(list.at(i)); scriptName->setTextAlignment(Qt::AlignCenter); QTableWidgetItem *closeIcon = new QTableWidgetItem; - closeIcon->setIcon(QIcon(":/images/kill-script.svg")); + closeIcon->setIcon(QIcon(Application::resourcesPath() + "/images/kill-script.svg")); ui->runningScriptsTableWidget->setItem(i, 0, scriptName); ui->runningScriptsTableWidget->setItem(i, 1, closeIcon); diff --git a/interface/ui/chatWindow.ui b/interface/ui/chatWindow.ui index 60a0c6badd..3c0fe4cd80 100644 --- a/interface/ui/chatWindow.ui +++ b/interface/ui/chatWindow.ui @@ -100,8 +100,8 @@ - - :/images/close.svg:/images/close.svg + + ../resources/images/close.svg../resources/images/close.svg true @@ -200,9 +200,7 @@ messagePlainTextEdit messagesScrollArea - - - + closeButton diff --git a/interface/ui/runningScriptsWidget.ui b/interface/ui/runningScriptsWidget.ui index 9494d4ed09..c7fc9e43e8 100644 --- a/interface/ui/runningScriptsWidget.ui +++ b/interface/ui/runningScriptsWidget.ui @@ -70,8 +70,8 @@ border-radius: 6px; Reload All - - :/images/reload.svg:/images/reload.svg + + ../resources/images/reload.svg../resources/images/reload.svg @@ -95,8 +95,8 @@ border-radius: 6px; Stop All - - :/images/stop.svg:/images/stop.svg + + ../resources/images/stop.svg../resources/images/stop.svg @@ -166,8 +166,8 @@ border-radius: 6px; - - :/images/close.svg:/images/close.svg + + ../resources/images/close.svg../resources/images/close.svg @@ -241,8 +241,6 @@ border-radius: 6px; - - - + From 508d4f216df93ee608c481c3375de2836a4c7668 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Fri, 11 Apr 2014 15:55:18 -0700 Subject: [PATCH 364/595] fix #2656 avatar jumps very far away This was caused by a bad CapsuleShape::_radius when the default CapsuleShape was used to create a default bounding capsule. The penetration against such a shape could be arbitrarily large. --- libraries/shared/src/CapsuleShape.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/libraries/shared/src/CapsuleShape.cpp b/libraries/shared/src/CapsuleShape.cpp index be3a165082..5055b3636e 100644 --- a/libraries/shared/src/CapsuleShape.cpp +++ b/libraries/shared/src/CapsuleShape.cpp @@ -17,9 +17,9 @@ // default axis of CapsuleShape is Y-axis -const glm::vec3 localAxis(0.f, 1.f, 0.f); +const glm::vec3 localAxis(0.0f, 1.0f, 0.0f); -CapsuleShape::CapsuleShape() : Shape(Shape::CAPSULE_SHAPE) {} +CapsuleShape::CapsuleShape() : Shape(Shape::CAPSULE_SHAPE), _radius(0.0f), _halfHeight(0.0f) {} CapsuleShape::CapsuleShape(float radius, float halfHeight) : Shape(Shape::CAPSULE_SHAPE), _radius(radius), _halfHeight(halfHeight) { @@ -32,13 +32,13 @@ CapsuleShape::CapsuleShape(float radius, float halfHeight, const glm::vec3& posi } CapsuleShape::CapsuleShape(float radius, const glm::vec3& startPoint, const glm::vec3& endPoint) : - Shape(Shape::CAPSULE_SHAPE), _radius(radius), _halfHeight(0.f) { + Shape(Shape::CAPSULE_SHAPE), _radius(radius), _halfHeight(0.0f) { glm::vec3 axis = endPoint - startPoint; float height = glm::length(axis); if (height > EPSILON) { _halfHeight = 0.5f * height; axis /= height; - glm::vec3 yAxis(0.f, 1.f, 0.f); + glm::vec3 yAxis(0.0f, 1.0f, 0.0f); float angle = glm::angle(axis, yAxis); if (angle > EPSILON) { axis = glm::normalize(glm::cross(yAxis, axis)); @@ -50,17 +50,17 @@ CapsuleShape::CapsuleShape(float radius, const glm::vec3& startPoint, const glm: /// \param[out] startPoint is the center of start cap void CapsuleShape::getStartPoint(glm::vec3& startPoint) const { - startPoint = getPosition() - _rotation * glm::vec3(0.f, _halfHeight, 0.f); + startPoint = getPosition() - _rotation * glm::vec3(0.0f, _halfHeight, 0.0f); } /// \param[out] endPoint is the center of the end cap void CapsuleShape::getEndPoint(glm::vec3& endPoint) const { - endPoint = getPosition() + _rotation * glm::vec3(0.f, _halfHeight, 0.f); + endPoint = getPosition() + _rotation * glm::vec3(0.0f, _halfHeight, 0.0f); } void CapsuleShape::computeNormalizedAxis(glm::vec3& axis) const { // default axis of a capsule is along the yAxis - axis = _rotation * glm::vec3(0.f, 1.f, 0.f); + axis = _rotation * glm::vec3(0.0f, 1.0f, 0.0f); } void CapsuleShape::setRadius(float radius) { From fe7a359545afb2e5cacc4f8ea0e579c23d5ae66d Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Fri, 11 Apr 2014 15:55:48 -0700 Subject: [PATCH 365/595] Added tools to adjust avatar LOD to LOD tools dialog. Closes #2624. --- interface/src/Menu.cpp | 51 +++++++++++++++----------- interface/src/Menu.h | 14 ++++++++ interface/src/ui/LodToolsDialog.cpp | 56 +++++++++++++++++++++++++++++ interface/src/ui/LodToolsDialog.h | 9 +++++ 4 files changed, 110 insertions(+), 20 deletions(-) diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 0d3c66e3e7..4b5d24e376 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -79,6 +79,9 @@ Menu::Menu() : _lodToolsDialog(NULL), _maxVoxels(DEFAULT_MAX_VOXELS_PER_SYSTEM), _voxelSizeScale(DEFAULT_OCTREE_SIZE_SCALE), + _automaticAvatarLOD(true), + _avatarLODDecreaseFPS(DEFAULT_ADJUST_AVATAR_LOD_DOWN_FPS), + _avatarLODIncreaseFPS(ADJUST_LOD_UP_FPS), _avatarLODDistanceMultiplier(DEFAULT_AVATAR_LOD_DISTANCE_MULTIPLIER), _boundaryLevelAdjust(0), _maxVoxelPacketsPerSecond(DEFAULT_MAX_VOXEL_PPS), @@ -273,7 +276,7 @@ Menu::Menu() : addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::Metavoxels, 0, true); addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::BuckyBalls, 0, true); addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::Particles, 0, true); - + addActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::LodTools, Qt::SHIFT | Qt::Key_L, this, SLOT(lodTools())); QMenu* voxelOptionsMenu = developerMenu->addMenu("Voxel Options"); @@ -286,7 +289,6 @@ Menu::Menu() : addCheckableActionToQMenuAndActionHash(voxelOptionsMenu, MenuOption::VoxelTextures); addCheckableActionToQMenuAndActionHash(voxelOptionsMenu, MenuOption::AmbientOcclusion); - addActionToQMenuAndActionHash(voxelOptionsMenu, MenuOption::LodTools, Qt::SHIFT | Qt::Key_L, this, SLOT(lodTools())); addCheckableActionToQMenuAndActionHash(voxelOptionsMenu, MenuOption::DontFadeOnVoxelServerChanges); addCheckableActionToQMenuAndActionHash(voxelOptionsMenu, MenuOption::DisableAutoAdjustLOD); @@ -415,6 +417,11 @@ void Menu::loadSettings(QSettings* settings) { _maxVoxels = loadSetting(settings, "maxVoxels", DEFAULT_MAX_VOXELS_PER_SYSTEM); _maxVoxelPacketsPerSecond = loadSetting(settings, "maxVoxelsPPS", DEFAULT_MAX_VOXEL_PPS); _voxelSizeScale = loadSetting(settings, "voxelSizeScale", DEFAULT_OCTREE_SIZE_SCALE); + _automaticAvatarLOD = settings->value("automaticAvatarLOD", true).toBool(); + _avatarLODDecreaseFPS = loadSetting(settings, "avatarLODDecreaseFPS", DEFAULT_ADJUST_AVATAR_LOD_DOWN_FPS); + _avatarLODIncreaseFPS = loadSetting(settings, "avatarLODIncreaseFPS", ADJUST_LOD_UP_FPS); + _avatarLODDistanceMultiplier = loadSetting(settings, "avatarLODDistanceMultiplier", + DEFAULT_AVATAR_LOD_DISTANCE_MULTIPLIER); _boundaryLevelAdjust = loadSetting(settings, "boundaryLevelAdjust", 0); settings->beginGroup("View Frustum Offset Camera"); @@ -454,6 +461,10 @@ void Menu::saveSettings(QSettings* settings) { settings->setValue("maxVoxels", _maxVoxels); settings->setValue("maxVoxelsPPS", _maxVoxelPacketsPerSecond); settings->setValue("voxelSizeScale", _voxelSizeScale); + settings->setValue("automaticAvatarLOD", _automaticAvatarLOD); + settings->setValue("avatarLODDecreaseFPS", _avatarLODDecreaseFPS); + settings->setValue("avatarLODIncreaseFPS", _avatarLODIncreaseFPS); + settings->setValue("avatarLODDistanceMultiplier", _avatarLODDistanceMultiplier); settings->setValue("boundaryLevelAdjust", _boundaryLevelAdjust); settings->beginGroup("View Frustum Offset Camera"); settings->setValue("viewFrustumOffsetYaw", _viewFrustumOffset.yaw); @@ -1165,27 +1176,27 @@ void Menu::autoAdjustLOD(float currentFPS) { quint64 now = usecTimestampNow(); - const float ADJUST_AVATAR_LOD_DOWN_FPS = 30.0f; const quint64 ADJUST_AVATAR_LOD_DOWN_DELAY = 1000 * 1000; - if (_fastFPSAverage.getAverage() < ADJUST_AVATAR_LOD_DOWN_FPS) { - if (now - _lastAvatarDetailDrop > ADJUST_AVATAR_LOD_DOWN_DELAY) { - // attempt to lower the detail in proportion to the fps difference - float targetFps = (ADJUST_AVATAR_LOD_DOWN_FPS + ADJUST_LOD_UP_FPS) * 0.5f; - float averageFps = _fastFPSAverage.getAverage(); - const float MAXIMUM_MULTIPLIER_SCALE = 2.0f; - const float MAXIMUM_DISTANCE_MULTIPLIER = 15.0f; - _avatarLODDistanceMultiplier = qMin(MAXIMUM_DISTANCE_MULTIPLIER, _avatarLODDistanceMultiplier * - (averageFps < EPSILON ? MAXIMUM_MULTIPLIER_SCALE : qMin(MAXIMUM_MULTIPLIER_SCALE, targetFps / averageFps))); - _lastAvatarDetailDrop = now; + if (_automaticAvatarLOD) { + if (_fastFPSAverage.getAverage() < _avatarLODDecreaseFPS) { + if (now - _lastAvatarDetailDrop > ADJUST_AVATAR_LOD_DOWN_DELAY) { + // attempt to lower the detail in proportion to the fps difference + float targetFps = (_avatarLODDecreaseFPS + _avatarLODIncreaseFPS) * 0.5f; + float averageFps = _fastFPSAverage.getAverage(); + const float MAXIMUM_MULTIPLIER_SCALE = 2.0f; + _avatarLODDistanceMultiplier = qMin(MAXIMUM_AVATAR_LOD_DISTANCE_MULTIPLIER, _avatarLODDistanceMultiplier * + (averageFps < EPSILON ? MAXIMUM_MULTIPLIER_SCALE : + qMin(MAXIMUM_MULTIPLIER_SCALE, targetFps / averageFps))); + _lastAvatarDetailDrop = now; + } + } else if (_fastFPSAverage.getAverage() > _avatarLODIncreaseFPS) { + // let the detail level creep slowly upwards + const float DISTANCE_DECREASE_RATE = 0.05f; + _avatarLODDistanceMultiplier = qMax(MINIMUM_AVATAR_LOD_DISTANCE_MULTIPLIER, + _avatarLODDistanceMultiplier - DISTANCE_DECREASE_RATE); } - } else if (_fastFPSAverage.getAverage() > ADJUST_LOD_UP_FPS) { - // let the detail level creep slowly upwards - const float DISTANCE_DECREASE_RATE = 0.05f; - const float MINIMUM_DISTANCE_MULTIPLIER = 0.1f; - _avatarLODDistanceMultiplier = qMax(MINIMUM_DISTANCE_MULTIPLIER, - _avatarLODDistanceMultiplier - DISTANCE_DECREASE_RATE); } - + bool changed = false; quint64 elapsed = now - _lastAdjust; diff --git a/interface/src/Menu.h b/interface/src/Menu.h index e827e43014..7151aeeb4c 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -27,6 +27,7 @@ const float ADJUST_LOD_DOWN_FPS = 40.0; const float ADJUST_LOD_UP_FPS = 55.0; +const float DEFAULT_ADJUST_AVATAR_LOD_DOWN_FPS = 30.0f; const quint64 ADJUST_LOD_DOWN_DELAY = 1000 * 1000 * 5; const quint64 ADJUST_LOD_UP_DELAY = ADJUST_LOD_DOWN_DELAY * 2; @@ -37,6 +38,9 @@ const float ADJUST_LOD_UP_BY = 1.1f; const float ADJUST_LOD_MIN_SIZE_SCALE = DEFAULT_OCTREE_SIZE_SCALE * 0.25f; const float ADJUST_LOD_MAX_SIZE_SCALE = DEFAULT_OCTREE_SIZE_SCALE; +const float MINIMUM_AVATAR_LOD_DISTANCE_MULTIPLIER = 0.1f; +const float MAXIMUM_AVATAR_LOD_DISTANCE_MULTIPLIER = 15.0f; + enum FrustumDrawMode { FRUSTUM_DRAW_MODE_ALL, FRUSTUM_DRAW_MODE_VECTORS, @@ -95,6 +99,13 @@ public: void resetLODAdjust(); void setVoxelSizeScale(float sizeScale); float getVoxelSizeScale() const { return _voxelSizeScale; } + void setAutomaticAvatarLOD(bool automaticAvatarLOD) { _automaticAvatarLOD = automaticAvatarLOD; } + bool getAutomaticAvatarLOD() const { return _automaticAvatarLOD; } + void setAvatarLODDecreaseFPS(float avatarLODDecreaseFPS) { _avatarLODDecreaseFPS = avatarLODDecreaseFPS; } + float getAvatarLODDecreaseFPS() const { return _avatarLODDecreaseFPS; } + void setAvatarLODIncreaseFPS(float avatarLODIncreaseFPS) { _avatarLODIncreaseFPS = avatarLODIncreaseFPS; } + float getAvatarLODIncreaseFPS() const { return _avatarLODIncreaseFPS; } + void setAvatarLODDistanceMultiplier(float multiplier) { _avatarLODDistanceMultiplier = multiplier; } float getAvatarLODDistanceMultiplier() const { return _avatarLODDistanceMultiplier; } void setBoundaryLevelAdjust(int boundaryLevelAdjust); int getBoundaryLevelAdjust() const { return _boundaryLevelAdjust; } @@ -217,6 +228,9 @@ private: LodToolsDialog* _lodToolsDialog; int _maxVoxels; float _voxelSizeScale; + bool _automaticAvatarLOD; + float _avatarLODDecreaseFPS; + float _avatarLODIncreaseFPS; float _avatarLODDistanceMultiplier; int _boundaryLevelAdjust; QAction* _useVoxelShader; diff --git a/interface/src/ui/LodToolsDialog.cpp b/interface/src/ui/LodToolsDialog.cpp index 35d5eada41..92456956e3 100644 --- a/interface/src/ui/LodToolsDialog.cpp +++ b/interface/src/ui/LodToolsDialog.cpp @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -75,6 +76,27 @@ LodToolsDialog::LodToolsDialog(QWidget* parent) : const int FEEDBACK_WIDTH = 350; _feedback->setFixedWidth(FEEDBACK_WIDTH); form->addRow("You can see... ", _feedback); + + form->addRow("Automatic Avatar LOD Adjustment:", _automaticAvatarLOD = new QCheckBox()); + _automaticAvatarLOD->setChecked(Menu::getInstance()->getAutomaticAvatarLOD()); + connect(_automaticAvatarLOD, SIGNAL(toggled(bool)), SLOT(updateAvatarLODControls())); + + form->addRow("Decrease Avatar LOD Below FPS:", _avatarLODDecreaseFPS = new QDoubleSpinBox()); + _avatarLODDecreaseFPS->setValue(Menu::getInstance()->getAvatarLODDecreaseFPS()); + _avatarLODDecreaseFPS->setDecimals(0); + connect(_avatarLODDecreaseFPS, SIGNAL(valueChanged(double)), SLOT(updateAvatarLODValues())); + + form->addRow("Increase Avatar LOD Above FPS:", _avatarLODIncreaseFPS = new QDoubleSpinBox()); + _avatarLODIncreaseFPS->setValue(Menu::getInstance()->getAvatarLODIncreaseFPS()); + _avatarLODIncreaseFPS->setDecimals(0); + connect(_avatarLODIncreaseFPS, SIGNAL(valueChanged(double)), SLOT(updateAvatarLODValues())); + + form->addRow("Avatar LOD:", _avatarLOD = new QDoubleSpinBox()); + _avatarLOD->setDecimals(3); + _avatarLOD->setRange(1.0 / MAXIMUM_AVATAR_LOD_DISTANCE_MULTIPLIER, 1.0 / MINIMUM_AVATAR_LOD_DISTANCE_MULTIPLIER); + _avatarLOD->setSingleStep(0.001); + _avatarLOD->setValue(1.0 / Menu::getInstance()->getAvatarLODDistanceMultiplier()); + connect(_avatarLOD, SIGNAL(valueChanged(double)), SLOT(updateAvatarLODValues())); // Add a button to reset QPushButton* resetButton = new QPushButton("Reset"); @@ -82,6 +104,8 @@ LodToolsDialog::LodToolsDialog(QWidget* parent) : connect(resetButton,SIGNAL(clicked(bool)),this,SLOT(resetClicked(bool))); this->QDialog::setLayout(form); + + updateAvatarLODControls(); } LodToolsDialog::~LodToolsDialog() { @@ -96,6 +120,35 @@ void LodToolsDialog::reloadSliders() { _feedback->setText(Menu::getInstance()->getLODFeedbackText()); } +void LodToolsDialog::updateAvatarLODControls() { + QFormLayout* form = static_cast(layout()); + + Menu::getInstance()->setAutomaticAvatarLOD(_automaticAvatarLOD->isChecked()); + + _avatarLODDecreaseFPS->setVisible(_automaticAvatarLOD->isChecked()); + form->labelForField(_avatarLODDecreaseFPS)->setVisible(_automaticAvatarLOD->isChecked()); + + _avatarLODIncreaseFPS->setVisible(_automaticAvatarLOD->isChecked()); + form->labelForField(_avatarLODIncreaseFPS)->setVisible(_automaticAvatarLOD->isChecked()); + + _avatarLOD->setVisible(!_automaticAvatarLOD->isChecked()); + form->labelForField(_avatarLOD)->setVisible(!_automaticAvatarLOD->isChecked()); + + if (!_automaticAvatarLOD->isChecked()) { + _avatarLOD->setValue(1.0 / Menu::getInstance()->getAvatarLODDistanceMultiplier()); + } +} + +void LodToolsDialog::updateAvatarLODValues() { + if (_automaticAvatarLOD->isChecked()) { + Menu::getInstance()->setAvatarLODDecreaseFPS(_avatarLODDecreaseFPS->value()); + Menu::getInstance()->setAvatarLODIncreaseFPS(_avatarLODIncreaseFPS->value()); + + } else { + Menu::getInstance()->setAvatarLODDistanceMultiplier(1.0 / _avatarLOD->value()); + } +} + void LodToolsDialog::sizeScaleValueChanged(int value) { float realValue = value * TREE_SCALE; Menu::getInstance()->setVoxelSizeScale(realValue); @@ -113,6 +166,9 @@ void LodToolsDialog::resetClicked(bool checked) { //sizeScaleValueChanged(sliderValue); _lodSize->setValue(sliderValue); _boundaryLevelAdjust->setValue(0); + _automaticAvatarLOD->setChecked(true); + _avatarLODDecreaseFPS->setValue(DEFAULT_ADJUST_AVATAR_LOD_DOWN_FPS); + _avatarLODIncreaseFPS->setValue(ADJUST_LOD_UP_FPS); } void LodToolsDialog::reject() { diff --git a/interface/src/ui/LodToolsDialog.h b/interface/src/ui/LodToolsDialog.h index a3223806aa..5b34a5efd0 100644 --- a/interface/src/ui/LodToolsDialog.h +++ b/interface/src/ui/LodToolsDialog.h @@ -16,6 +16,9 @@ #include #include +class QCheckBox; +class QDoubleSpinBox; + class LodToolsDialog : public QDialog { Q_OBJECT public: @@ -32,6 +35,8 @@ public slots: void boundaryLevelValueChanged(int value); void resetClicked(bool checked); void reloadSliders(); + void updateAvatarLODControls(); + void updateAvatarLODValues(); protected: @@ -41,6 +46,10 @@ protected: private: QSlider* _lodSize; QSlider* _boundaryLevelAdjust; + QCheckBox* _automaticAvatarLOD; + QDoubleSpinBox* _avatarLODDecreaseFPS; + QDoubleSpinBox* _avatarLODIncreaseFPS; + QDoubleSpinBox* _avatarLOD; QLabel* _feedback; }; From 4265617c3edf787cf97164681310b403d4cc6b30 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Fri, 11 Apr 2014 16:02:46 -0700 Subject: [PATCH 366/595] Add missing include. --- interface/src/ui/LodToolsDialog.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/interface/src/ui/LodToolsDialog.cpp b/interface/src/ui/LodToolsDialog.cpp index 92456956e3..3612e06e34 100644 --- a/interface/src/ui/LodToolsDialog.cpp +++ b/interface/src/ui/LodToolsDialog.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include From 0ad841edfb44466cf5248e0263d9c2f0dc4d6912 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Fri, 11 Apr 2014 17:44:51 -0700 Subject: [PATCH 367/595] don't render avatar boundary shapes in first person --- interface/src/avatar/Avatar.cpp | 20 ++++++++++++++------ interface/src/avatar/Avatar.h | 1 + interface/src/avatar/Head.h | 2 +- interface/src/avatar/MyAvatar.cpp | 13 +++++++++---- interface/src/avatar/MyAvatar.h | 1 + 5 files changed, 26 insertions(+), 11 deletions(-) diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 475e7a1abc..e9d804d227 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -228,14 +228,18 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode) { _skeletonModel.renderJointCollisionShapes(0.7f); } if (Menu::getInstance()->isOptionChecked(MenuOption::RenderHeadCollisionShapes)) { - getHead()->getFaceModel().updateShapePositions(); - getHead()->getFaceModel().renderJointCollisionShapes(0.7f); + if (shouldRenderHead(cameraPosition, renderMode)) { + getHead()->getFaceModel().updateShapePositions(); + getHead()->getFaceModel().renderJointCollisionShapes(0.7f); + } } if (Menu::getInstance()->isOptionChecked(MenuOption::RenderBoundingCollisionShapes)) { - getHead()->getFaceModel().updateShapePositions(); - getHead()->getFaceModel().renderBoundingCollisionShapes(0.7f); - _skeletonModel.updateShapePositions(); - _skeletonModel.renderBoundingCollisionShapes(0.7f); + if (shouldRenderHead(cameraPosition, renderMode)) { + getHead()->getFaceModel().updateShapePositions(); + getHead()->getFaceModel().renderBoundingCollisionShapes(0.7f); + _skeletonModel.updateShapePositions(); + _skeletonModel.renderBoundingCollisionShapes(0.7f); + } } // quick check before falling into the code below: @@ -344,6 +348,10 @@ void Avatar::renderBody(RenderMode renderMode) { getHand()->render(false); } +bool Avatar::shouldRenderHead(const glm::vec3& cameraPosition, RenderMode renderMode) const { + return true; +} + void Avatar::updateJointMappings() { // no-op; joint mappings come from skeleton model } diff --git a/interface/src/avatar/Avatar.h b/interface/src/avatar/Avatar.h index ca05e5dbbf..4d68f2168b 100755 --- a/interface/src/avatar/Avatar.h +++ b/interface/src/avatar/Avatar.h @@ -195,6 +195,7 @@ protected: void renderDisplayName(); virtual void renderBody(RenderMode renderMode); + virtual bool shouldRenderHead(const glm::vec3& cameraPosition, RenderMode renderMode) const; virtual void updateJointMappings(); diff --git a/interface/src/avatar/Head.h b/interface/src/avatar/Head.h index a6cda5622c..5f0c6519ef 100644 --- a/interface/src/avatar/Head.h +++ b/interface/src/avatar/Head.h @@ -78,7 +78,7 @@ public: const bool getReturnToCenter() const { return _returnHeadToCenter; } // Do you want head to try to return to center (depends on interface detected) float getAverageLoudness() const { return _averageLoudness; } - glm::vec3 calculateAverageEyePosition() { return _leftEyePosition + (_rightEyePosition - _leftEyePosition ) * ONE_HALF; } + glm::vec3 calculateAverageEyePosition() const { return _leftEyePosition + (_rightEyePosition - _leftEyePosition ) * ONE_HALF; } /// \return the point about which scaling occurs. glm::vec3 getScalePivot() const; diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index a258cd341b..fa15117cb2 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -647,15 +647,20 @@ void MyAvatar::renderBody(RenderMode renderMode) { _skeletonModel.render(1.0f, modelRenderMode); // Render head so long as the camera isn't inside it - const float RENDER_HEAD_CUTOFF_DISTANCE = 0.50f; - Camera* myCamera = Application::getInstance()->getCamera(); - if (renderMode != NORMAL_RENDER_MODE || (glm::length(myCamera->getPosition() - getHead()->calculateAverageEyePosition()) > - RENDER_HEAD_CUTOFF_DISTANCE * _scale)) { + if (shouldRenderHead(Application::getInstance()->getCamera()->getPosition(), renderMode)) { getHead()->render(1.0f, modelRenderMode); } getHand()->render(true); } +const float RENDER_HEAD_CUTOFF_DISTANCE = 0.50f; + +bool MyAvatar::shouldRenderHead(const glm::vec3& cameraPosition, RenderMode renderMode) const { + const Head* head = getHead(); + return (renderMode != NORMAL_RENDER_MODE) || + (glm::length(cameraPosition - head->calculateAverageEyePosition()) > RENDER_HEAD_CUTOFF_DISTANCE * _scale); +} + void MyAvatar::updateThrust(float deltaTime) { // // Gather thrust information from keyboard and sensors to apply to avatar motion diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index 66ab322444..71c74f7c91 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -41,6 +41,7 @@ public: void render(const glm::vec3& cameraPosition, RenderMode renderMode = NORMAL_RENDER_MODE); void renderBody(RenderMode renderMode); + bool shouldRenderHead(const glm::vec3& cameraPosition, RenderMode renderMode) const; void renderDebugBodyPoints(); void renderHeadMouse() const; From 0ca68e4cb4c2fad9f840d203cae32d61d4c2bf7e Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Fri, 11 Apr 2014 17:53:02 -0700 Subject: [PATCH 368/595] Adjust the size when we toggle the avatar LOD options. --- interface/src/ui/LodToolsDialog.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/interface/src/ui/LodToolsDialog.cpp b/interface/src/ui/LodToolsDialog.cpp index 3612e06e34..6df5121104 100644 --- a/interface/src/ui/LodToolsDialog.cpp +++ b/interface/src/ui/LodToolsDialog.cpp @@ -138,6 +138,10 @@ void LodToolsDialog::updateAvatarLODControls() { if (!_automaticAvatarLOD->isChecked()) { _avatarLOD->setValue(1.0 / Menu::getInstance()->getAvatarLODDistanceMultiplier()); } + + if (isVisible()) { + adjustSize(); + } } void LodToolsDialog::updateAvatarLODValues() { From f84249ac6cce0750d14646c1ac94cc6f8a5a9858 Mon Sep 17 00:00:00 2001 From: Leonardo Murillo Date: Fri, 11 Apr 2014 19:58:49 -0600 Subject: [PATCH 369/595] switching to https --- interface/src/Application.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 9e812ac954..d63fa2293e 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -112,7 +112,7 @@ const float MIRROR_REARVIEW_DISTANCE = 0.65f; const float MIRROR_REARVIEW_BODY_DISTANCE = 2.3f; const float MIRROR_FIELD_OF_VIEW = 30.0f; -const QString CHECK_VERSION_URL = "http://highfidelity.io/latestVersion.xml"; +const QString CHECK_VERSION_URL = "https://highfidelity.io/latestVersion.xml"; const QString SKIP_FILENAME = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/hifi.skipversion"; void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message) { From 13cf0c80e687f4bf34d5d5532af01d84f29b25eb Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Sat, 12 Apr 2014 00:20:43 -0700 Subject: [PATCH 370/595] Fix chat message formatting and word wrapping By switching from a QLabel to a QTextBrowser widget more formatting options and word wrapping that breaks words is possible. It comes with an issue I have been unable to resolve * Selecting text and going down with the cursor will cause it to scroll. It's possible to increase padding to remove this behavior, but it doesn't look great. --- interface/src/ui/ChatMessageArea.cpp | 44 ++++++++++++++++++++++++++++ interface/src/ui/ChatMessageArea.h | 33 +++++++++++++++++++++ interface/src/ui/ChatWindow.cpp | 35 +++++++++++++++------- 3 files changed, 102 insertions(+), 10 deletions(-) create mode 100644 interface/src/ui/ChatMessageArea.cpp create mode 100644 interface/src/ui/ChatMessageArea.h diff --git a/interface/src/ui/ChatMessageArea.cpp b/interface/src/ui/ChatMessageArea.cpp new file mode 100644 index 0000000000..936f2dba18 --- /dev/null +++ b/interface/src/ui/ChatMessageArea.cpp @@ -0,0 +1,44 @@ +// +// ChatMessageArea.cpp +// interface/src/ui +// +// Created by Ryan Huffman on 4/11/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "ChatMessageArea.h" +#include +#include + +ChatMessageArea::ChatMessageArea() : QTextBrowser() { + connect(document()->documentLayout(), &QAbstractTextDocumentLayout::documentSizeChanged, + this, &ChatMessageArea::updateLayout); +}; + +void ChatMessageArea::setHtml(const QString& html) { + // Create format with updated line height + QTextBlockFormat format; + format.setLineHeight(CHAT_MESSAGE_LINE_HEIGHT, QTextBlockFormat::ProportionalHeight); + + // Possibly a bug in QT, the format won't take effect if `insertHtml` is used first. Inserting a space and deleting + // it after ensures the format is applied. + QTextCursor cursor = textCursor(); + cursor.setBlockFormat(format); + cursor.insertText(" "); + cursor.insertHtml(html); + cursor.setPosition(0); + cursor.deleteChar(); +}; + +void ChatMessageArea::updateLayout() { + setFixedHeight(document()->size().height()); + updateGeometry(); +} + +void ChatMessageArea::wheelEvent(QWheelEvent* event) { + // Capture wheel events to stop Ctrl-WheelUp/Down zooming + event->ignore(); +}; diff --git a/interface/src/ui/ChatMessageArea.h b/interface/src/ui/ChatMessageArea.h new file mode 100644 index 0000000000..1c49c60b08 --- /dev/null +++ b/interface/src/ui/ChatMessageArea.h @@ -0,0 +1,33 @@ +// +// ChatMessageArea.h +// interface/src/ui +// +// Created by Ryan Huffman on 4/11/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_ChatMessageArea_h +#define hifi_ChatMessageArea_h + +#include + +const int CHAT_MESSAGE_LINE_HEIGHT = 130; + +class ChatMessageArea : public QTextBrowser { + Q_OBJECT +public: + ChatMessageArea(); + virtual void setHtml(const QString& html); + +public slots: + void updateLayout(); + +protected: + virtual void wheelEvent(QWheelEvent* event); + +}; + +#endif // hifi_ChatMessageArea_h diff --git a/interface/src/ui/ChatWindow.cpp b/interface/src/ui/ChatWindow.cpp index c164ea3fb3..9cd0690536 100644 --- a/interface/src/ui/ChatWindow.cpp +++ b/interface/src/ui/ChatWindow.cpp @@ -22,6 +22,7 @@ #include "qtimespan.h" #include "ui_chatWindow.h" #include "XmppClient.h" +#include "ChatMessageArea.h" #include "ChatWindow.h" @@ -241,25 +242,39 @@ void ChatWindow::messageReceived(const QXmppMessage& message) { userLabel->setStyleSheet("padding: 2px; font-weight: bold"); userLabel->setAlignment(Qt::AlignTop | Qt::AlignRight); - QLabel* messageLabel = new QLabel(message.body().replace(regexLinks, "\\1")); - messageLabel->setWordWrap(true); - messageLabel->setTextInteractionFlags(Qt::TextBrowserInteraction); - messageLabel->setOpenExternalLinks(true); - messageLabel->setStyleSheet("padding-bottom: 2px; padding-left: 2px; padding-top: 2px; padding-right: 20px"); - messageLabel->setAlignment(Qt::AlignTop | Qt::AlignLeft); + ChatMessageArea* messageArea = new ChatMessageArea(); - if (getParticipantName(message.from()) == AccountManager::getInstance().getUsername()) { + messageArea->setOpenLinks(true); + messageArea->setOpenExternalLinks(true); + messageArea->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); + messageArea->setTextInteractionFlags(Qt::TextBrowserInteraction); + messageArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + messageArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + messageArea->setReadOnly(true); + + messageArea->setStyleSheet("padding-bottom: 2px;" + "padding-left: 2px;" + "padding-top: 2px;" + "padding-right: 20px;" + "background-color: rgba(0, 0, 0, 0%);" + "border: 0;"); + + bool fromSelf = getParticipantName(message.from()) == AccountManager::getInstance().getUsername(); + if (fromSelf) { userLabel->setStyleSheet(userLabel->styleSheet() + "; background-color: #e1e8ea"); - messageLabel->setStyleSheet(messageLabel->styleSheet() + "; background-color: #e1e8ea"); + messageArea->setStyleSheet(messageArea->styleSheet() + "; background-color: #e1e8ea"); } + messageArea->setHtml(message.body().replace(regexLinks, "\\1")); + bool atBottom = isAtBottom(); ui->messagesGridLayout->addWidget(userLabel, ui->messagesGridLayout->rowCount(), 0); - ui->messagesGridLayout->addWidget(messageLabel, ui->messagesGridLayout->rowCount() - 1, 1); + ui->messagesGridLayout->addWidget(messageArea, ui->messagesGridLayout->rowCount() - 1, 1); + ui->messagesGridLayout->parentWidget()->updateGeometry(); Application::processEvents(); - if (atBottom) { + if (atBottom || fromSelf) { scrollToBottom(); } From 45402336ac9ff702c9440f0a6118b069e23b9f02 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Sat, 12 Apr 2014 00:25:53 -0700 Subject: [PATCH 371/595] Add chat window dragging This was originally implemented by Mohammed Nafees, shared on Basecamp. I've noticed an issue with dragging across screens (monitors) where the chat window will jump vertically. I've tried debugging it, and ultimately it looks like an issue with the `move` method. The coordinates are valid (I tried using global coordinates as well), and the amount to move is correct, but when moving to coordinates on a different screen it doesn't do the right thing. --- interface/src/ui/ChatWindow.cpp | 23 ++++++++++++++++++++++- interface/src/ui/ChatWindow.h | 6 ++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/interface/src/ui/ChatWindow.cpp b/interface/src/ui/ChatWindow.cpp index 9cd0690536..de1362273b 100644 --- a/interface/src/ui/ChatWindow.cpp +++ b/interface/src/ui/ChatWindow.cpp @@ -32,7 +32,9 @@ const QRegularExpression regexLinks("((?:(?:ftp)|(?:https?))://\\S+)"); ChatWindow::ChatWindow() : ui(new Ui::ChatWindow), - numMessagesAfterLastTimeStamp(0) + numMessagesAfterLastTimeStamp(0), + _mousePressed(false), + _mouseStartPosition() { ui->setupUi(this); @@ -83,6 +85,25 @@ ChatWindow::~ChatWindow() { delete ui; } +void ChatWindow::mousePressEvent(QMouseEvent *e) { + if (e->button() == Qt::LeftButton) { + _mousePressed = true; + _mouseStartPosition = e->pos(); + } +} + +void ChatWindow::mouseMoveEvent(QMouseEvent *e) { + if (_mousePressed) { + move(mapToParent(e->pos() - _mouseStartPosition)); + } +} + +void ChatWindow::mouseReleaseEvent( QMouseEvent *e ) { + if ( e->button() == Qt::LeftButton ) { + _mousePressed = false; + } +} + void ChatWindow::keyPressEvent(QKeyEvent* event) { QDockWidget::keyPressEvent(event); if (event->key() == Qt::Key_Escape) { diff --git a/interface/src/ui/ChatWindow.h b/interface/src/ui/ChatWindow.h index 46e7de1c39..4a339ad278 100644 --- a/interface/src/ui/ChatWindow.h +++ b/interface/src/ui/ChatWindow.h @@ -39,6 +39,10 @@ public: virtual void keyPressEvent(QKeyEvent *event); virtual void showEvent(QShowEvent* event); + virtual void mousePressEvent(QMouseEvent *e); + virtual void mouseMoveEvent(QMouseEvent *e); + virtual void mouseReleaseEvent(QMouseEvent *e); + protected: bool eventFilter(QObject* sender, QEvent* event); @@ -54,6 +58,8 @@ private: Ui::ChatWindow* ui; int numMessagesAfterLastTimeStamp; QDateTime lastMessageStamp; + bool _mousePressed; + QPoint _mouseStartPosition; private slots: void connected(); From 8b904b91eaf812537525431af5a1b162a9696332 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Sat, 12 Apr 2014 00:53:43 -0700 Subject: [PATCH 372/595] Cleanup ChatMessageArea.cpp --- interface/src/ui/ChatMessageArea.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/interface/src/ui/ChatMessageArea.cpp b/interface/src/ui/ChatMessageArea.cpp index 936f2dba18..f15b788990 100644 --- a/interface/src/ui/ChatMessageArea.cpp +++ b/interface/src/ui/ChatMessageArea.cpp @@ -16,7 +16,7 @@ ChatMessageArea::ChatMessageArea() : QTextBrowser() { connect(document()->documentLayout(), &QAbstractTextDocumentLayout::documentSizeChanged, this, &ChatMessageArea::updateLayout); -}; +} void ChatMessageArea::setHtml(const QString& html) { // Create format with updated line height @@ -31,7 +31,7 @@ void ChatMessageArea::setHtml(const QString& html) { cursor.insertHtml(html); cursor.setPosition(0); cursor.deleteChar(); -}; +} void ChatMessageArea::updateLayout() { setFixedHeight(document()->size().height()); @@ -41,4 +41,4 @@ void ChatMessageArea::updateLayout() { void ChatMessageArea::wheelEvent(QWheelEvent* event) { // Capture wheel events to stop Ctrl-WheelUp/Down zooming event->ignore(); -}; +} From 2c10b558589d913ecd181c0b7f92f4a5ee5b1406 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Sat, 12 Apr 2014 01:09:29 -0700 Subject: [PATCH 373/595] Remove extraneous debug messages --- interface/src/ui/ChatWindow.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/interface/src/ui/ChatWindow.cpp b/interface/src/ui/ChatWindow.cpp index de1362273b..78d5adf394 100644 --- a/interface/src/ui/ChatWindow.cpp +++ b/interface/src/ui/ChatWindow.cpp @@ -309,14 +309,12 @@ void ChatWindow::messageReceived(const QXmppMessage& message) { bool ChatWindow::isAtBottom() { QScrollBar* verticalScrollBar = ui->messagesScrollArea->verticalScrollBar(); - qDebug() << "Checking for bottom " << verticalScrollBar->sliderPosition() << " " << verticalScrollBar->maximum(); return verticalScrollBar->sliderPosition() == verticalScrollBar->maximum(); } // Scroll chat message area to bottom. void ChatWindow::scrollToBottom() { QScrollBar* verticalScrollBar = ui->messagesScrollArea->verticalScrollBar(); - qDebug() << "Scrolling to " << verticalScrollBar->maximum(); verticalScrollBar->setSliderPosition(verticalScrollBar->maximum()); } From a37921c1d5304194d8a41836965d0072b0786260 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Sun, 13 Apr 2014 19:09:07 -0700 Subject: [PATCH 374/595] move isNaN() to shared utils --- libraries/octree/src/ViewFrustum.cpp | 6 +----- libraries/shared/src/SharedUtil.cpp | 19 +++++++++++++++++++ libraries/shared/src/SharedUtil.h | 9 +++++++++ 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/libraries/octree/src/ViewFrustum.cpp b/libraries/octree/src/ViewFrustum.cpp index fa6873b093..bc617c9bc7 100644 --- a/libraries/octree/src/ViewFrustum.cpp +++ b/libraries/octree/src/ViewFrustum.cpp @@ -424,10 +424,6 @@ bool ViewFrustum::matches(const ViewFrustum& compareTo, bool debug) const { return result; } -bool isNaN(float f) { - return f != f; -} - bool ViewFrustum::isVerySimilar(const ViewFrustum& compareTo, bool debug) const { // Compute distance between the two positions @@ -449,7 +445,7 @@ bool ViewFrustum::isVerySimilar(const ViewFrustum& compareTo, bool debug) const float angleEyeOffsetOrientation = compareTo._eyeOffsetOrientation == _eyeOffsetOrientation ? 0.0f : glm::degrees(glm::angle(dQEyeOffsetOrientation)); if (isNaN(angleEyeOffsetOrientation)) { - angleOrientation = 0.0f; + angleEyeOffsetOrientation = 0.0f; } bool result = diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index efd5180d03..786302ae2a 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -661,3 +661,22 @@ glm::vec3 safeEulerAngles(const glm::quat& q) { } } +bool isNaN(float f) { + return f != f; +} + + +bool isSimilarOrientation(const glm::quat& orientionA, const glm::quat& orientionB, float similarEnough) { + // Compute the angular distance between the two orientations + float angleOrientation = orientionA == orientionB ? 0.0f : glm::degrees(glm::angle(orientionA * glm::inverse(orientionB))); + if (isNaN(angleOrientation)) { + angleOrientation = 0.0f; + } + return (angleOrientation <= similarEnough); +} + +bool isSimilarPosition(const glm::vec3& positionA, const glm::vec3& positionB, float similarEnough) { + // Compute the distance between the two points + float positionDistance = glm::distance(positionA, positionB); + return (positionDistance <= similarEnough); +} diff --git a/libraries/shared/src/SharedUtil.h b/libraries/shared/src/SharedUtil.h index d8d686c63b..91b0054794 100644 --- a/libraries/shared/src/SharedUtil.h +++ b/libraries/shared/src/SharedUtil.h @@ -168,4 +168,13 @@ int unpackFloatVec3FromSignedTwoByteFixed(const unsigned char* sourceBuffer, glm /// \return vec3 with euler angles in radians glm::vec3 safeEulerAngles(const glm::quat& q); +/// \return bool are two orientations similar to each other +const float ORIENTATION_SIMILAR_ENOUGH = 5.0f; // 10 degrees in any direction +bool isSimilarOrientation(const glm::quat& orientionA, const glm::quat& orientionB, + float similarEnough = ORIENTATION_SIMILAR_ENOUGH); +const float POSITION_SIMILAR_ENOUGH = 0.1f; // 0.1 meter +bool isSimilarPosition(const glm::vec3& positionA, const glm::vec3& positionB, float similarEnough = POSITION_SIMILAR_ENOUGH); + +bool isNaN(float f); + #endif /* defined(__hifi__SharedUtil__) */ From 38dbc56d1ad8ffb0aa0bc659a46e388099a616db Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Sun, 13 Apr 2014 19:09:28 -0700 Subject: [PATCH 375/595] first cut at new version of audio refelctor --- interface/src/AudioReflector.cpp | 377 ++++++++++++++++++++++++++++++- interface/src/AudioReflector.h | 81 ++++++- 2 files changed, 445 insertions(+), 13 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 6c4e78eae2..e870e01539 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -17,15 +17,22 @@ const float DEFAULT_MS_DELAY_PER_METER = 3.0f; const float MINIMUM_ATTENUATION_TO_REFLECT = 1.0f / 256.0f; const float DEFAULT_DISTANCE_SCALING_FACTOR = 2.0f; const float MAXIMUM_DELAY_MS = 1000.0 * 20.0f; // stop reflecting after path is this long -const int DEFAULT_DIFFUSION_FANOUT = 2; +const int DEFAULT_DIFFUSION_FANOUT = 5; const int ABSOLUTE_MAXIMUM_BOUNCE_COUNT = 10; +const float SLIGHTLY_SHORT = 0.999f; // slightly inside the distance so we're on the inside of the reflection point + +const float DEFAULT_ABSORPTION_RATIO = 0.125; // 12.5% is absorbed +const float DEFAULT_DIFFUSION_RATIO = 0.125; // 12.5% is diffused + AudioReflector::AudioReflector(QObject* parent) : QObject(parent), _preDelay(DEFAULT_PRE_DELAY), _soundMsPerMeter(DEFAULT_MS_DELAY_PER_METER), _distanceAttenuationScalingFactor(DEFAULT_DISTANCE_SCALING_FACTOR), - _diffusionFanout(DEFAULT_DIFFUSION_FANOUT) + _diffusionFanout(DEFAULT_DIFFUSION_FANOUT), + _absorptionRatio(DEFAULT_ABSORPTION_RATIO), + _diffusionRatio(DEFAULT_DIFFUSION_RATIO) { reset(); } @@ -37,7 +44,7 @@ void AudioReflector::render() { } if (_audio->getProcessSpatialAudio()) { - drawRays(); + newDrawRays(); } } @@ -187,7 +194,8 @@ void AudioReflector::calculateAllReflections() { _origin = _myAvatar->getHead()->getPosition(); glm::vec3 averageEarPosition = _myAvatar->getHead()->getPosition(); - + _listenerPosition = averageEarPosition; +qDebug() << "_listenerPosition:" << _listenerPosition.x << "," << _listenerPosition.y << "," << _listenerPosition.z; _orientation = orientation; glm::vec3 right = glm::normalize(_orientation * IDENTITY_RIGHT); glm::vec3 up = glm::normalize(_orientation * IDENTITY_UP); @@ -340,13 +348,6 @@ QVector AudioReflector::calculateReflections(const glm::vec3& earPosi direction = glm::normalize(glm::reflect(direction,faceNormal)); start = end; bounceCount++; - - // handle diffusion here - if (_diffusionFanout > 0) { - glm::vec3 thisReflection = end; - calculateDiffusions(earPosition, origin, end, totalDistance, - currentAttenuation, bounceCount, face, reflectionPoints); - } } } else { currentAttenuation = 0.0f; @@ -478,6 +479,10 @@ void AudioReflector::processLocalAudio(unsigned int sampleTime, const QByteArray } void AudioReflector::processInboundAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { + return; // + +// DO NOTHING.... + //quint64 start = usecTimestampNow(); _maxDelay = 0; @@ -650,3 +655,353 @@ void AudioReflector::drawVector(const glm::vec3& start, const glm::vec3& end, co glEnable(GL_LIGHTING); // ?? } + + + +AudioPath::AudioPath(const glm::vec3& origin, const glm::vec3& direction, float attenuation, float delay, int bounceCount) : + startPoint(origin), + startDirection(direction), + startDelay(delay), + startAttenuation(attenuation), + + lastPoint(origin), + lastDirection(direction), + lastDistance(0.0f), + lastDelay(delay), + lastAttenuation(attenuation), + bounceCount(bounceCount), + + finalized(false), + reflections() +{ +} + + +void AudioReflector::addSoundSource(const glm::vec3& origin, const glm::vec3& initialDirection, + float initialAttenuation, float initialDelay) { + + AudioPath* path = new AudioPath(origin, initialDirection, initialAttenuation, initialDelay, 0); + _audioPaths.push_back(path); +} + +void AudioReflector::newCalculateAllReflections() { + // only recalculate when we've moved... + // TODO: what about case where new voxels are added in front of us??? + bool wantHeadOrientation = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingHeadOriented); + glm::quat orientation = wantHeadOrientation ? _myAvatar->getHead()->getFinalOrientation() : _myAvatar->getOrientation(); + glm::vec3 origin = _myAvatar->getHead()->getPosition(); + glm::vec3 listenerPosition = _myAvatar->getHead()->getPosition(); + + bool shouldRecalc = _audiblePoints.size() == 0 + || !isSimilarPosition(origin, _origin) + || !isSimilarOrientation(orientation, _orientation) + || !isSimilarPosition(listenerPosition, _listenerPosition); + + if (shouldRecalc) { + + /* + qDebug() << "_audiblePoints.size()=" << _audiblePoints.size(); + qDebug() << "isSimilarPosition(origin, _origin)=" << isSimilarPosition(origin, _origin); + qDebug() << "isSimilarPosition(listenerPosition, _listenerPosition)=" << isSimilarPosition(listenerPosition, _listenerPosition); + qDebug() << "isSimilarOrientation(orientation, _orientation)=" << isSimilarOrientation(orientation, _orientation); + if (!isSimilarOrientation(orientation, _orientation)) { + qDebug() << " orientation=" << orientation.x << "," << orientation.y << "," + << orientation.y << "," << orientation.w; + + qDebug() << " _orientation=" << _orientation.x << "," << _orientation.y << "," + << _orientation.y << "," << _orientation.w; + } + */ + + QMutexLocker locker(&_mutex); + quint64 start = usecTimestampNow(); + _origin = origin; + _orientation = orientation; + _listenerPosition = listenerPosition; + + anylizePaths(); // actually does the work + + quint64 end = usecTimestampNow(); + //reset(); + } +} + +void AudioReflector::newDrawRays() { + newCalculateAllReflections(); + + const glm::vec3 RED(1,0,0); + const glm::vec3 GREEN(0,1,0); + + int diffusionNumber = 0; + + QMutexLocker locker(&_mutex); + foreach(AudioPath* const& path, _audioPaths) { + + // if this is an original reflection, draw it in RED + if (path->startPoint == _origin) { + drawPath(path, RED); + } else { + diffusionNumber++; +//qDebug() << "drawing diffusion path:" << diffusionNumber << "length:" << path->reflections.size(); + drawPath(path, GREEN); + } + } +} + +void AudioReflector::drawPath(AudioPath* path, const glm::vec3& originalColor) { + glm::vec3 start = path->startPoint; + glm::vec3 color = originalColor; + const float COLOR_ADJUST_PER_BOUNCE = 0.75f; + + foreach (glm::vec3 end, path->reflections) { + drawVector(start, end, color); + start = end; + color = color * COLOR_ADJUST_PER_BOUNCE; + } +} + + +void AudioReflector::anylizePaths() { + +qDebug() << "AudioReflector::anylizePaths()..."; + + // clear our _audioPaths + foreach(AudioPath* const& path, _audioPaths) { + delete path; + } + _audioPaths.clear(); + + _audiblePoints.clear(); // clear our audible points + + // add our initial paths + glm::vec3 averageEarPosition = _myAvatar->getHead()->getPosition(); + glm::vec3 right = glm::normalize(_orientation * IDENTITY_RIGHT); + glm::vec3 up = glm::normalize(_orientation * IDENTITY_UP); + glm::vec3 front = glm::normalize(_orientation * IDENTITY_FRONT); + glm::vec3 left = -right; + glm::vec3 down = -up; + glm::vec3 back = -front; + glm::vec3 frontRightUp = glm::normalize(front + right + up); + glm::vec3 frontLeftUp = glm::normalize(front + left + up); + glm::vec3 backRightUp = glm::normalize(back + right + up); + glm::vec3 backLeftUp = glm::normalize(back + left + up); + glm::vec3 frontRightDown = glm::normalize(front + right + down); + glm::vec3 frontLeftDown = glm::normalize(front + left + down); + glm::vec3 backRightDown = glm::normalize(back + right + down); + glm::vec3 backLeftDown = glm::normalize(back + left + down); + + float initialAttenuation = 1.0f; + + addSoundSource(_origin, right, initialAttenuation, _preDelay); + addSoundSource(_origin, front, initialAttenuation, _preDelay); + addSoundSource(_origin, up, initialAttenuation, _preDelay); + addSoundSource(_origin, down, initialAttenuation, _preDelay); + addSoundSource(_origin, back, initialAttenuation, _preDelay); + addSoundSource(_origin, left, initialAttenuation, _preDelay); + + addSoundSource(_origin, frontRightUp, initialAttenuation, _preDelay); + addSoundSource(_origin, frontLeftUp, initialAttenuation, _preDelay); + addSoundSource(_origin, backRightUp, initialAttenuation, _preDelay); + addSoundSource(_origin, backLeftUp, initialAttenuation, _preDelay); + addSoundSource(_origin, frontRightDown, initialAttenuation, _preDelay); + addSoundSource(_origin, frontLeftDown, initialAttenuation, _preDelay); + addSoundSource(_origin, backRightDown, initialAttenuation, _preDelay); + addSoundSource(_origin, backLeftDown, initialAttenuation, _preDelay); + + // loop through all our + int steps = 0; + int acitvePaths = _audioPaths.size(); // when we start, all paths are active + while(acitvePaths > 0) { + acitvePaths = anylizePathsSingleStep(); + steps++; + qDebug() << "acitvePaths=" << acitvePaths << "steps=" << steps << "_audioPaths.size()=" << _audioPaths.size(); + } +} + +int AudioReflector::anylizePathsSingleStep() { + // iterate all the active sound paths, calculate one step per active path + + int activePaths = 0; + foreach(AudioPath* const& path, _audioPaths) { + + bool isDiffusion = (path->startPoint != _origin); + + /* + qDebug() << "ray intersection... " + << " startPoint=[" << path->startPoint.x << "," << path->startPoint.y << "," << path->startPoint.z << "]" + << " _origin=[" << _origin.x << "," << _origin.y << "," << _origin.z << "]" + << " bouceCount= " << path->bounceCount + << " isDiffusion=" << isDiffusion; + */ + + glm::vec3 start = path->lastPoint; + glm::vec3 direction = path->lastDirection; + OctreeElement* elementHit; // output from findRayIntersection + float distance; // output from findRayIntersection + BoxFace face; // output from findRayIntersection + + float currentAttenuation = path->lastAttenuation; + float currentDelay = path->lastDelay; // start with our delay so far + float pathDistance = path->lastDistance; + float totalDelay = path->lastDelay; // start with our delay so far + unsigned int bounceCount = path->bounceCount; + + if (!path->finalized) { + activePaths++; + + // quick hack to stop early reflections right away... + //if (!isDiffusion && path->bounceCount > 1) { + // path->finalized = true; + // qDebug() << "stopping reflections on first bounce!"; + //} else + if (path->bounceCount > ABSOLUTE_MAXIMUM_BOUNCE_COUNT) { + path->finalized = true; + if (isDiffusion) { + qDebug() << "diffusion bounceCount too high!"; + } + } else if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { + glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); + + pathDistance += glm::distance(start, end); + + + /* + qDebug() << "ray intersection... " + << " startPoint=[" << path->startPoint.x << "," << path->startPoint.y << "," << path->startPoint.z << "]" + << " bouceCount= " << path->bounceCount + << " end=[" << end.x << "," << end.y << "," << end.z << "]" + << " pathDistance=" << pathDistance; + */ + + + // We aren't using this... should we be???? + float toListenerDistance = glm::distance(end, _listenerPosition); + float totalDistance = toListenerDistance + pathDistance; + + // adjust our current delay by just the delay from the most recent ray + currentDelay += getDelayFromDistance(distance); + + // adjust our previous attenuation based on the distance traveled in last ray + currentAttenuation *= getDistanceAttenuationCoefficient(distance); + + // now we know the current attenuation for the "perfect" reflection case, but we now incorporate + // our surface materials to determine how much of this ray is absorbed, reflected, and diffused + SurfaceCharacteristics material = getSurfaceCharacteristics(elementHit); + + float reflectiveAttenuation = currentAttenuation * material.reflectiveRatio; + float totalDiffusionAttenuation = currentAttenuation * material.diffusionRatio; + float partialDiffusionAttenuation = totalDiffusionAttenuation / _diffusionFanout; + + // total delay includes the bounce back to listener + totalDelay = getDelayFromDistance(totalDistance); + float toListenerAttenuation = getDistanceAttenuationCoefficient(toListenerDistance); + //qDebug() << "toListenerDistance=" << toListenerDistance; + //qDebug() << "toListenerAttenuation=" << toListenerAttenuation; + + // if our resulting partial diffusion attenuation, is still above our minimum attenuation + // then we add new paths for each diffusion point + if ((partialDiffusionAttenuation * toListenerAttenuation) > MINIMUM_ATTENUATION_TO_REFLECT + && totalDelay < MAXIMUM_DELAY_MS) { + + // add sound sources for the normal + glm::vec3 faceNormal = getFaceNormal(face); + addSoundSource(end, faceNormal, partialDiffusionAttenuation, currentDelay); + + // diffusions fan out from random places on the semisphere of the collision point + for(int i = 1; i < _diffusionFanout; i++) { + glm::vec3 randomDirection; + + float surfaceRandomness = randFloatInRange(0.5f,1.0f); + float surfaceRemainder = (1.0f - surfaceRandomness)/2.0f; + float altRemainderSignA = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; + float altRemainderSignB = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; + + if (face == MIN_X_FACE) { + randomDirection = glm::vec3(-surfaceRandomness, surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB); + } else if (face == MAX_X_FACE) { + randomDirection = glm::vec3(surfaceRandomness, surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB); + } else if (face == MIN_Y_FACE) { + randomDirection = glm::vec3(surfaceRemainder * altRemainderSignA, -surfaceRandomness, surfaceRemainder * altRemainderSignB); + } else if (face == MAX_Y_FACE) { + randomDirection = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRandomness, surfaceRemainder * altRemainderSignB); + } else if (face == MIN_Z_FACE) { + randomDirection = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB, -surfaceRandomness); + } else if (face == MAX_Z_FACE) { + randomDirection = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB, surfaceRandomness); + } + + randomDirection = glm::normalize(randomDirection); + + /* + qDebug() << "DIFFUSION... addSoundSource()... partialDiffusionAttenuation=" << partialDiffusionAttenuation << "\n" << + " MINIMUM_ATTENUATION_TO_REFLECT=" << MINIMUM_ATTENUATION_TO_REFLECT << "\n" << + " previous direction=[" << direction.x << "," << direction.y << "," << direction.z << "]" << "\n" << + " randomDirection=[" << randomDirection.x << "," << randomDirection.y << "," << randomDirection.z << "]" << "\n" << + " end=[" << end.x << "," << end.y << "," << end.z << "]"; + */ + + // add sound sources for these diffusions + addSoundSource(end, randomDirection, partialDiffusionAttenuation, currentDelay); + } + } + + // if our reflective attenuation is above our minimum, then add our reflection point and + // allow our path to continue + if (isDiffusion) { + qDebug() << "checking diffusion"; + qDebug() << "reflectiveAttenuation=" << reflectiveAttenuation; + qDebug() << "totalDiffusionAttenuation=" << totalDiffusionAttenuation; + qDebug() << "toListenerAttenuation=" << toListenerAttenuation; + qDebug() << "(reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation=" << ((reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation); + } + + if (((reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation) > MINIMUM_ATTENUATION_TO_REFLECT + && totalDelay < MAXIMUM_DELAY_MS) { + + // add this location, as the reflective attenuation as well as the total diffusion attenuation + AudioPoint point = { end, totalDelay, reflectiveAttenuation + totalDiffusionAttenuation }; + _audiblePoints.push_back(point); + + // add this location to the path points, so we can visualize it + path->reflections.push_back(end); + + // now, if our reflective attenuation is over our minimum then keep going... + if (reflectiveAttenuation * toListenerAttenuation > MINIMUM_ATTENUATION_TO_REFLECT) { + glm::vec3 faceNormal = getFaceNormal(face); + path->lastDirection = glm::normalize(glm::reflect(direction,faceNormal)); + path->lastPoint = end; + path->lastAttenuation = reflectiveAttenuation; + path->lastDelay = currentDelay; + path->lastDistance = pathDistance; + path->bounceCount++; + +//qDebug() << "whichPath=" << activePaths << "path->lastAttenuation=" << path->lastAttenuation << "path->lastDistance=" << path->lastDistance; + + } else { + path->finalized = true; // if we're too quiet, then we're done + } + } else { + path->finalized = true; // if we're too quiet, then we're done + if (isDiffusion) { + qDebug() << "diffusion too quiet!"; + } + } + } else { +//qDebug() << "whichPath=" << activePaths << "path->bounceCount=" << path->bounceCount << "ray missed..."; + path->finalized = true; // if it doesn't intersect, then it is finished + if (isDiffusion) { + qDebug() << "diffusion doesn't intersect!"; + } + } + } + } + return activePaths; +} + +SurfaceCharacteristics AudioReflector::getSurfaceCharacteristics(OctreeElement* elementHit) { + float reflectiveRatio = (1.0f - (_absorptionRatio + _diffusionRatio)); + SurfaceCharacteristics result = { reflectiveRatio, _absorptionRatio, _diffusionRatio }; + return result; +} + + diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index a2cc39d20e..8ae5413b40 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -16,6 +16,41 @@ #include "Audio.h" #include "avatar/MyAvatar.h" +class AudioPath { +public: + AudioPath(const glm::vec3& origin = glm::vec3(0), const glm::vec3& direction = glm::vec3(0), float attenuation = 1.0f, + float delay = 0.0f, int bounceCount = 0); + glm::vec3 startPoint; + glm::vec3 startDirection; + float startDelay; + float startAttenuation; + + glm::vec3 lastPoint; + glm::vec3 lastDirection; + float lastDistance; + float lastDelay; + float lastAttenuation; + unsigned int bounceCount; + + bool finalized; + QVector reflections; +}; + +class AudioPoint { +public: + glm::vec3 location; + float delay; + float attenuation; +}; + +class SurfaceCharacteristics { +public: + float reflectiveRatio; + float absorptionRatio; + float diffusionRatio; +}; + + class AudioReflector : public QObject { Q_OBJECT public: @@ -58,40 +93,51 @@ private: MyAvatar* _myAvatar; // access to listener Audio* _audio; // access to audio API + // Helpers for drawing void drawRays(); void drawVector(const glm::vec3& start, const glm::vec3& end, const glm::vec3& color); + // OLD helper for playing audio void echoReflections(const glm::vec3& origin, const QVector& reflections, const QByteArray& samples, unsigned int sampleTime, int sampleRate); + // OLD helper for calculating reflections QVector calculateReflections(const glm::vec3& earPosition, const glm::vec3& origin, const glm::vec3& originalDirection); void calculateDiffusions(const glm::vec3& earPosition, const glm::vec3& origin, const glm::vec3& thisReflection, float thisDistance, float thisAttenuation, int thisBounceCount, BoxFace thisReflectionFace, QVector reflectionPoints); + // OLD helper for drawing refections void drawReflections(const glm::vec3& origin, const glm::vec3& originalColor, const QVector& reflections); + // OLD helper for calculating reflections void calculateAllReflections(); + + // resets statistics void reset(); + + // helper for generically calculating attenuation based on distance float getDistanceAttenuationCoefficient(float distance); + // statistics int _reflections; - int _delayCount; float _totalDelay; float _averageDelay; float _maxDelay; float _minDelay; - int _attenuationCount; float _totalAttenuation; float _averageAttenuation; float _maxAttenuation; float _minAttenuation; + glm::vec3 _listenerPosition; glm::vec3 _origin; glm::quat _orientation; + + // old way of doing this... QVector _frontRightUpReflections; QVector _frontLeftUpReflections; QVector _backRightUpReflections; @@ -107,6 +153,32 @@ private: QVector _upReflections; QVector _downReflections; + + // NOTE: Here's the new way, we will have an array of AudioPaths, we will loop on all of our currently calculating audio + // paths, and calculate one ray per path. If that ray doesn't reflect, or reaches a max distance/attenuation, then it + // is considered finalized. + // If the ray hits a surface, then, based on the characteristics of that surface, it will create calculate the new + // attenuation, path length, and delay for the primary path. For surfaces that have diffusion, it will also create + // fanout number of new paths, those new paths will have an origin of the reflection point, and an initial attenuation + // of their diffusion ratio. Those new paths will be added to the active audio paths, and be analyzed for the next loop. + QVector _audioPaths; + QVector _audiblePoints; + + // adds a sound source to begin an audio path trace, these can be the initial sound sources with their directional properties, + // as well as diffusion sound sources + void addSoundSource(const glm::vec3& origin, const glm::vec3& initialDirection, float initialAttenuation, float initialDelay); + + // helper that handles audioPath analysis + int anylizePathsSingleStep(); + void anylizePaths(); + void newDrawRays(); + void drawPath(AudioPath* path, const glm::vec3& originalColor); + void newCalculateAllReflections(); + + // return the surface characteristics of the element we hit + SurfaceCharacteristics getSurfaceCharacteristics(OctreeElement* elementHit); + + QMutex _mutex; float _preDelay; @@ -114,6 +186,11 @@ private: float _distanceAttenuationScalingFactor; int _diffusionFanout; // number of points of diffusion from each reflection point + + // all elements have the same material for now... + float _absorptionRatio; + float _diffusionRatio; + float _reflectiveRatio; }; From 030de00e882814821cb9904d22830edc8353c15b Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Sun, 13 Apr 2014 19:11:25 -0700 Subject: [PATCH 376/595] first cut at new version of audio refelctor --- interface/interface_en.ts | 12 ++++++------ interface/src/AudioReflector.cpp | 3 ++- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/interface/interface_en.ts b/interface/interface_en.ts index 43ec129c99..8a8a877a32 100644 --- a/interface/interface_en.ts +++ b/interface/interface_en.ts @@ -14,12 +14,12 @@ - + Open Script - + JavaScript Files (*.js) @@ -113,18 +113,18 @@ Menu - + Open .ini config file - - + + Text files (*.ini) - + Save .ini config file diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index e870e01539..6e0b72c9fa 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -770,7 +770,6 @@ qDebug() << "AudioReflector::anylizePaths()..."; delete path; } _audioPaths.clear(); - _audiblePoints.clear(); // clear our audible points // add our initial paths @@ -816,6 +815,8 @@ qDebug() << "AudioReflector::anylizePaths()..."; steps++; qDebug() << "acitvePaths=" << acitvePaths << "steps=" << steps << "_audioPaths.size()=" << _audioPaths.size(); } + + qDebug() << "_audiblePoints.size()=" << _audiblePoints.size(); } int AudioReflector::anylizePathsSingleStep() { From 22f7facc4e15b1291076ec9751778c069e091e77 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Sun, 13 Apr 2014 19:41:54 -0700 Subject: [PATCH 377/595] first cut at new version of audio refelctor --- interface/src/AudioReflector.cpp | 117 +++++++++++++++++++++++++++++-- interface/src/AudioReflector.h | 4 ++ 2 files changed, 116 insertions(+), 5 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 6e0b72c9fa..89cc678a0e 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -44,7 +44,8 @@ void AudioReflector::render() { } if (_audio->getProcessSpatialAudio()) { - newDrawRays(); + //newDrawRays(); + drawRays(); } } @@ -474,15 +475,121 @@ void AudioReflector::echoReflections(const glm::vec3& origin, const QVectorisOptionChecked(MenuOption::AudioSpatialProcessingSeparateEars); + bool wantStereo = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingStereoSource); + glm::vec3 rightEarPosition = wantEarSeparation ? _myAvatar->getHead()->getRightEarPosition() : + _myAvatar->getHead()->getPosition(); + glm::vec3 leftEarPosition = wantEarSeparation ? _myAvatar->getHead()->getLeftEarPosition() : + _myAvatar->getHead()->getPosition(); + + int totalNumberOfSamples = samples.size() / sizeof(int16_t); + int totalNumberOfStereoSamples = samples.size() / (sizeof(int16_t) * NUMBER_OF_CHANNELS); + + const int16_t* originalSamplesData = (const int16_t*)samples.constData(); + QByteArray attenuatedLeftSamples; + QByteArray attenuatedRightSamples; + attenuatedLeftSamples.resize(samples.size()); + attenuatedRightSamples.resize(samples.size()); + + int16_t* attenuatedLeftSamplesData = (int16_t*)attenuatedLeftSamples.data(); + int16_t* attenuatedRightSamplesData = (int16_t*)attenuatedRightSamples.data(); + + // calculate the distance to the ears + float rightEarDistance = glm::distance(audiblePoint.location, rightEarPosition); + float leftEarDistance = glm::distance(audiblePoint.location, leftEarPosition); + + float rightEarDelayMsecs = getDelayFromDistance(rightEarDistance) + audiblePoint.delay; + float leftEarDelayMsecs = getDelayFromDistance(leftEarDistance) + audiblePoint.delay; + + _totalDelay += rightEarDelayMsecs + leftEarDelayMsecs; + _delayCount += 2; + _maxDelay = std::max(_maxDelay,rightEarDelayMsecs); + _maxDelay = std::max(_maxDelay,leftEarDelayMsecs); + _minDelay = std::min(_minDelay,rightEarDelayMsecs); + _minDelay = std::min(_minDelay,leftEarDelayMsecs); + + int rightEarDelay = rightEarDelayMsecs * sampleRate / MSECS_PER_SECOND; + int leftEarDelay = leftEarDelayMsecs * sampleRate / MSECS_PER_SECOND; + + //qDebug() << "leftTotalDistance=" << leftTotalDistance << "rightTotalDistance=" << rightTotalDistance; + //qDebug() << "leftEarDelay=" << leftEarDelay << "rightEarDelay=" << rightEarDelay; + + float rightEarAttenuation = getDistanceAttenuationCoefficient(rightEarDistance) * audiblePoint.attenuation; + float leftEarAttenuation = getDistanceAttenuationCoefficient(leftEarDistance) * audiblePoint.attenuation; + + _totalAttenuation += rightEarAttenuation + leftEarAttenuation; + _attenuationCount += 2; + _maxAttenuation = std::max(_maxAttenuation,rightEarAttenuation); + _maxAttenuation = std::max(_maxAttenuation,leftEarAttenuation); + _minAttenuation = std::min(_minAttenuation,rightEarAttenuation); + _minAttenuation = std::min(_minAttenuation,leftEarAttenuation); + + // run through the samples, and attenuate them + for (int sample = 0; sample < totalNumberOfStereoSamples; sample++) { + int16_t leftSample = originalSamplesData[sample * NUMBER_OF_CHANNELS]; + int16_t rightSample = leftSample; + if (wantStereo) { + rightSample = originalSamplesData[(sample * NUMBER_OF_CHANNELS) + 1]; + } + + //qDebug() << "leftSample=" << leftSample << "rightSample=" << rightSample; + attenuatedLeftSamplesData[sample * NUMBER_OF_CHANNELS] = leftSample * leftEarAttenuation; + attenuatedLeftSamplesData[sample * NUMBER_OF_CHANNELS + 1] = 0; + + attenuatedRightSamplesData[sample * NUMBER_OF_CHANNELS] = 0; + attenuatedRightSamplesData[sample * NUMBER_OF_CHANNELS + 1] = rightSample * rightEarAttenuation; + + //qDebug() << "attenuated... leftSample=" << (leftSample * leftEarAttenuation) << "rightSample=" << (rightSample * rightEarAttenuation); + } + + // now inject the attenuated array with the appropriate delay + + unsigned int sampleTimeLeft = sampleTime + leftEarDelay; + unsigned int sampleTimeRight = sampleTime + rightEarDelay; + + //qDebug() << "sampleTimeLeft=" << sampleTimeLeft << "sampleTimeRight=" << sampleTimeRight; + + _audio->addSpatialAudioToBuffer(sampleTimeLeft, attenuatedLeftSamples, totalNumberOfSamples); + _audio->addSpatialAudioToBuffer(sampleTimeRight, attenuatedRightSamples, totalNumberOfSamples); +} void AudioReflector::processLocalAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { // nothing yet, but will do local reflections too... } void AudioReflector::processInboundAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { - return; // - -// DO NOTHING.... - + //newEchoAudio(sampleTime, samples, format); + oldEchoAudio(sampleTime, samples, format); +} + +void AudioReflector::newEchoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { + //quint64 start = usecTimestampNow(); + + _maxDelay = 0; + _maxAttenuation = 0.0f; + _minDelay = std::numeric_limits::max(); + _minAttenuation = std::numeric_limits::max(); + _totalDelay = 0.0f; + _delayCount = 0; + _totalAttenuation = 0.0f; + _attenuationCount = 0; + + QMutexLocker locker(&_mutex); + + foreach(const AudioPoint& audiblePoint, _audiblePoints) { + injectAudiblePoint(audiblePoint, samples, sampleTime, format.sampleRate()); + } + + _averageDelay = _delayCount == 0 ? 0 : _totalDelay / _delayCount; + _averageAttenuation = _attenuationCount == 0 ? 0 : _totalAttenuation / _attenuationCount; + + //quint64 end = usecTimestampNow(); + //qDebug() << "AudioReflector::addSamples()... elapsed=" << (end - start); +} + +void AudioReflector::oldEchoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { //quint64 start = usecTimestampNow(); _maxDelay = 0; diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 8ae5413b40..3e8f06e8a7 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -174,6 +174,10 @@ private: void newDrawRays(); void drawPath(AudioPath* path, const glm::vec3& originalColor); void newCalculateAllReflections(); + + void injectAudiblePoint(const AudioPoint& audiblePoint, const QByteArray& samples, unsigned int sampleTime, int sampleRate); + void oldEchoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); + void newEchoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); // return the surface characteristics of the element we hit SurfaceCharacteristics getSurfaceCharacteristics(OctreeElement* elementHit); From ddd2b0843cac71b97b43efd7119b329f95adeba4 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Sun, 13 Apr 2014 20:43:40 -0700 Subject: [PATCH 378/595] more work on new diffusion model --- examples/audioReflectorTools.js | 65 ++++++++++++- interface/src/Application.cpp | 5 +- interface/src/AudioReflector.cpp | 157 +++++++++---------------------- interface/src/Menu.cpp | 4 + interface/src/Menu.h | 1 + 5 files changed, 116 insertions(+), 116 deletions(-) diff --git a/examples/audioReflectorTools.js b/examples/audioReflectorTools.js index e19e757367..99baf7260c 100644 --- a/examples/audioReflectorTools.js +++ b/examples/audioReflectorTools.js @@ -11,12 +11,13 @@ var delayScale = 100.0; +var fanoutScale = 10.0; var speedScale = 20; var factorScale = 5.0; // This will create a couple of image overlays that make a "slider", we will demonstrate how to trap mouse messages to // move the slider -var delayY = 300; +var delayY = 250; var delaySlider = Overlays.addOverlay("image", { // alternate form of expressing bounds bounds: { x: 100, y: delayY, width: 150, height: 35}, @@ -36,10 +37,37 @@ var delayThumb = Overlays.addOverlay("image", { width: 18, height: 17, imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/thumb.png", + color: { red: 255, green: 0, blue: 0}, + alpha: 1 + }); + +// This will create a couple of image overlays that make a "slider", we will demonstrate how to trap mouse messages to +// move the slider +var fanoutY = 300; +var fanoutSlider = Overlays.addOverlay("image", { + // alternate form of expressing bounds + bounds: { x: 100, y: fanoutY, width: 150, height: 35}, + subImage: { x: 46, y: 0, width: 200, height: 71 }, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/slider.png", color: { red: 255, green: 255, blue: 255}, alpha: 1 }); +// This is the thumb of our slider +var fanoutMinThumbX = 110; +var fanoutMaxThumbX = fanoutMinThumbX + 110; +var fanoutThumbX = (fanoutMinThumbX + fanoutMaxThumbX) / 2; +var fanoutThumb = Overlays.addOverlay("image", { + x: fanoutThumbX, + y: fanoutY + 9, + width: 18, + height: 17, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/thumb.png", + color: { red: 255, green: 255, blue: 0}, + alpha: 1 + }); + + // This will create a couple of image overlays that make a "slider", we will demonstrate how to trap mouse messages to // move the slider var speedY = 350; @@ -62,7 +90,7 @@ var speedThumb = Overlays.addOverlay("image", { width: 18, height: 17, imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/thumb.png", - color: { red: 255, green: 255, blue: 255}, + color: { red: 0, green: 255, blue: 0}, alpha: 1 }); @@ -88,7 +116,7 @@ var factorThumb = Overlays.addOverlay("image", { width: 18, height: 17, imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/thumb.png", - color: { red: 255, green: 255, blue: 255}, + color: { red: 0, green: 0, blue: 255}, alpha: 1 }); @@ -101,6 +129,8 @@ function scriptEnding() { Overlays.deleteOverlay(speedSlider); Overlays.deleteOverlay(delayThumb); Overlays.deleteOverlay(delaySlider); + Overlays.deleteOverlay(fanoutThumb); + Overlays.deleteOverlay(fanoutSlider); } Script.scriptEnding.connect(scriptEnding); @@ -116,6 +146,7 @@ Script.update.connect(update); // The slider is handled in the mouse event callbacks. var movingSliderDelay = false; +var movingSliderFanout = false; var movingSliderSpeed = false; var movingSliderFactor = false; var thumbClickOffsetX = 0; @@ -130,8 +161,22 @@ function mouseMoveEvent(event) { } Overlays.editOverlay(delayThumb, { x: newThumbX } ); var delay = ((newThumbX - delayMinThumbX) / (delayMaxThumbX - delayMinThumbX)) * delayScale; + print("delay="+delay); AudioReflector.setPreDelay(delay); } + if (movingSliderFanout) { + newThumbX = event.x - thumbClickOffsetX; + if (newThumbX < fanoutMinThumbX) { + newThumbX = fanoutMinThumbX; + } + if (newThumbX > fanoutMaxThumbX) { + newThumbX = fanoutMaxThumbX; + } + Overlays.editOverlay(fanoutThumb, { x: newThumbX } ); + var fanout = Math.round(((newThumbX - fanoutMinThumbX) / (fanoutMaxThumbX - fanoutMinThumbX)) * fanoutScale); + print("fanout="+fanout); + AudioReflector.setDiffusionFanout(fanout); + } if (movingSliderSpeed) { newThumbX = event.x - thumbClickOffsetX; if (newThumbX < speedMinThumbX) { @@ -167,7 +212,11 @@ function mousePressEvent(event) { movingSliderDelay = true; thumbClickOffsetX = event.x - delayThumbX; } - + // If the user clicked on the thumb, handle the slider logic + if (clickedOverlay == fanoutThumb) { + movingSliderFanout = true; + thumbClickOffsetX = event.x - fanoutThumbX; + } // If the user clicked on the thumb, handle the slider logic if (clickedOverlay == speedThumb) { movingSliderSpeed = true; @@ -185,9 +234,17 @@ function mouseReleaseEvent(event) { if (movingSliderDelay) { movingSliderDelay = false; var delay = ((newThumbX - delayMinThumbX) / (delayMaxThumbX - delayMinThumbX)) * delayScale; + print("delay="+delay); AudioReflector.setPreDelay(delay); delayThumbX = newThumbX; } + if (movingSliderFanout) { + movingSliderFanout = false; + var fanout = Math.round(((newThumbX - fanoutMinThumbX) / (fanoutMaxThumbX - fanoutMinThumbX)) * fanoutScale); + print("fanout="+fanout); + AudioReflector.setDiffusionFanout(fanout); + fanoutThumbX = newThumbX; + } if (movingSliderSpeed) { movingSliderSpeed = false; var speed = ((newThumbX - speedMinThumbX) / (speedMaxThumbX - speedMinThumbX)) * speedScale; diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 4a7da51887..e3e59bbab6 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2854,8 +2854,11 @@ void Application::displayStats() { verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, WHITE_TEXT); + float preDelay = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingPreDelay) ? + _audioReflector.getPreDelay() : 0.0f; + sprintf(reflectionsStatus, "Delay: pre: %f, average %f, max %f, min %f, speed: %f", - _audioReflector.getDelayFromDistance(0.0f), + preDelay, _audioReflector.getAverageDelayMsecs(), _audioReflector.getMaxDelayMsecs(), _audioReflector.getMinDelayMsecs(), diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 89cc678a0e..28e9f6161b 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -44,8 +44,11 @@ void AudioReflector::render() { } if (_audio->getProcessSpatialAudio()) { - //newDrawRays(); - drawRays(); + if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions)) { + newDrawRays(); + } else { + drawRays(); + } } } @@ -59,11 +62,12 @@ void AudioReflector::render() { float AudioReflector::getDelayFromDistance(float distance) { float delay = (_soundMsPerMeter * distance); - if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingPreDelay)) { + if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingPreDelay) && + !Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions)) { + delay += _preDelay; } - return delay; } @@ -237,87 +241,6 @@ qDebug() << "_listenerPosition:" << _listenerPosition.x << "," << _listenerPosit } } -// TODO: add diffusion ratio. percentage of echo energy that diffuses -// so say that 50% of the energy that hits the echo point diffuses in fanout directions -void AudioReflector::calculateDiffusions(const glm::vec3& earPosition, const glm::vec3& origin, - const glm::vec3& thisReflection, float thisDistance, float thisAttenuation, int thisBounceCount, - BoxFace thisReflectionFace, QVector reflectionPoints) { - - //return; // do nothing - - QVector diffusionDirections; - - // diffusions fan out from random places on the semisphere of the collision point - for(int i = 0; i < _diffusionFanout; i++) { - glm::vec3 randomDirection; - - float surfaceRandomness = randFloatInRange(0.5f,1.0f); - float surfaceRemainder = (1.0f - surfaceRandomness)/2.0f; - float altRemainderSignA = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; - float altRemainderSignB = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; - - if (thisReflectionFace == MIN_X_FACE) { - randomDirection = glm::vec3(-surfaceRandomness, surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB); - } else if (thisReflectionFace == MAX_X_FACE) { - randomDirection = glm::vec3(surfaceRandomness, surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB); - } else if (thisReflectionFace == MIN_Y_FACE) { - randomDirection = glm::vec3(surfaceRemainder * altRemainderSignA, -surfaceRandomness, surfaceRemainder * altRemainderSignB); - } else if (thisReflectionFace == MAX_Y_FACE) { - randomDirection = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRandomness, surfaceRemainder * altRemainderSignB); - } else if (thisReflectionFace == MIN_Z_FACE) { - randomDirection = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB, -surfaceRandomness); - } else if (thisReflectionFace == MAX_Z_FACE) { - randomDirection = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB, surfaceRandomness); - } - diffusionDirections.push_back(randomDirection); - } - - foreach(glm::vec3 direction, diffusionDirections) { - - glm::vec3 start = thisReflection; - OctreeElement* elementHit; - float distance; - BoxFace face; - const float SLIGHTLY_SHORT = 0.999f; // slightly inside the distance so we're on the inside of the reflection point - float currentAttenuation = thisAttenuation; - float totalDistance = thisDistance; - float totalDelay = getDelayFromDistance(totalDistance); - int bounceCount = thisBounceCount; - - while (currentAttenuation > MINIMUM_ATTENUATION_TO_REFLECT && totalDelay < MAXIMUM_DELAY_MS && bounceCount < ABSOLUTE_MAXIMUM_BOUNCE_COUNT) { - if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { - glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); - - totalDistance += glm::distance(start, end); - float earDistance = glm::distance(end, earPosition); - float totalDistanceToEar = earDistance + distance; - totalDelay = getDelayFromDistance(totalDistanceToEar); - currentAttenuation = getDistanceAttenuationCoefficient(totalDistanceToEar) * getBounceAttenuationCoefficient(bounceCount); - - if (currentAttenuation > MINIMUM_ATTENUATION_TO_REFLECT && totalDelay < MAXIMUM_DELAY_MS) { - reflectionPoints.push_back(end); - glm::vec3 faceNormal = getFaceNormal(face); - direction = glm::normalize(glm::reflect(direction,faceNormal)); - start = end; - bounceCount++; - - /* - // handle diffusion here - if (_diffusionFanout > 0 && bounceCount < ABSOLUTE_MAXIMUM_BOUNCE_COUNT) { - glm::vec3 thisReflection = end; - calculateDiffusions(earPosition, origin, end, totalDistance, - currentAttenuation, bounceCount, face, reflectionPoints); - } - */ - } - } else { - currentAttenuation = 0.0f; - } - } - } -} - - QVector AudioReflector::calculateReflections(const glm::vec3& earPosition, const glm::vec3& origin, const glm::vec3& originalDirection) { @@ -560,8 +483,11 @@ void AudioReflector::processLocalAudio(unsigned int sampleTime, const QByteArray } void AudioReflector::processInboundAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { - //newEchoAudio(sampleTime, samples, format); - oldEchoAudio(sampleTime, samples, format); + if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions)) { + newEchoAudio(sampleTime, samples, format); + } else { + oldEchoAudio(sampleTime, samples, format); + } } void AudioReflector::newEchoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { @@ -829,7 +755,6 @@ void AudioReflector::newCalculateAllReflections() { anylizePaths(); // actually does the work quint64 end = usecTimestampNow(); - //reset(); } } @@ -898,21 +823,23 @@ qDebug() << "AudioReflector::anylizePaths()..."; float initialAttenuation = 1.0f; - addSoundSource(_origin, right, initialAttenuation, _preDelay); - addSoundSource(_origin, front, initialAttenuation, _preDelay); - addSoundSource(_origin, up, initialAttenuation, _preDelay); - addSoundSource(_origin, down, initialAttenuation, _preDelay); - addSoundSource(_origin, back, initialAttenuation, _preDelay); - addSoundSource(_origin, left, initialAttenuation, _preDelay); + float preDelay = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingPreDelay) ? _preDelay : 0.0f; + + addSoundSource(_origin, right, initialAttenuation, preDelay); + addSoundSource(_origin, front, initialAttenuation, preDelay); + addSoundSource(_origin, up, initialAttenuation, preDelay); + addSoundSource(_origin, down, initialAttenuation, preDelay); + addSoundSource(_origin, back, initialAttenuation, preDelay); + addSoundSource(_origin, left, initialAttenuation, preDelay); - addSoundSource(_origin, frontRightUp, initialAttenuation, _preDelay); - addSoundSource(_origin, frontLeftUp, initialAttenuation, _preDelay); - addSoundSource(_origin, backRightUp, initialAttenuation, _preDelay); - addSoundSource(_origin, backLeftUp, initialAttenuation, _preDelay); - addSoundSource(_origin, frontRightDown, initialAttenuation, _preDelay); - addSoundSource(_origin, frontLeftDown, initialAttenuation, _preDelay); - addSoundSource(_origin, backRightDown, initialAttenuation, _preDelay); - addSoundSource(_origin, backLeftDown, initialAttenuation, _preDelay); + addSoundSource(_origin, frontRightUp, initialAttenuation, preDelay); + addSoundSource(_origin, frontLeftUp, initialAttenuation, preDelay); + addSoundSource(_origin, backRightUp, initialAttenuation, preDelay); + addSoundSource(_origin, backLeftUp, initialAttenuation, preDelay); + addSoundSource(_origin, frontRightDown, initialAttenuation, preDelay); + addSoundSource(_origin, frontLeftDown, initialAttenuation, preDelay); + addSoundSource(_origin, backRightDown, initialAttenuation, preDelay); + addSoundSource(_origin, backLeftDown, initialAttenuation, preDelay); // loop through all our int steps = 0; @@ -920,9 +847,11 @@ qDebug() << "AudioReflector::anylizePaths()..."; while(acitvePaths > 0) { acitvePaths = anylizePathsSingleStep(); steps++; - qDebug() << "acitvePaths=" << acitvePaths << "steps=" << steps << "_audioPaths.size()=" << _audioPaths.size(); + //qDebug() << "acitvePaths=" << acitvePaths << "steps=" << steps << "_audioPaths.size()=" << _audioPaths.size(); } + _reflections = _audiblePoints.size(); + qDebug() << "_audiblePoints.size()=" << _audiblePoints.size(); } @@ -964,9 +893,11 @@ int AudioReflector::anylizePathsSingleStep() { //} else if (path->bounceCount > ABSOLUTE_MAXIMUM_BOUNCE_COUNT) { path->finalized = true; + /* if (isDiffusion) { qDebug() << "diffusion bounceCount too high!"; } + */ } else if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); @@ -998,7 +929,7 @@ int AudioReflector::anylizePathsSingleStep() { float reflectiveAttenuation = currentAttenuation * material.reflectiveRatio; float totalDiffusionAttenuation = currentAttenuation * material.diffusionRatio; - float partialDiffusionAttenuation = totalDiffusionAttenuation / _diffusionFanout; + float partialDiffusionAttenuation = _diffusionFanout < 1 ? 0.0f : totalDiffusionAttenuation / _diffusionFanout; // total delay includes the bounce back to listener totalDelay = getDelayFromDistance(totalDistance); @@ -1012,11 +943,11 @@ int AudioReflector::anylizePathsSingleStep() { && totalDelay < MAXIMUM_DELAY_MS) { // add sound sources for the normal - glm::vec3 faceNormal = getFaceNormal(face); - addSoundSource(end, faceNormal, partialDiffusionAttenuation, currentDelay); + //glm::vec3 faceNormal = getFaceNormal(face); + //addSoundSource(end, faceNormal, partialDiffusionAttenuation, currentDelay); // diffusions fan out from random places on the semisphere of the collision point - for(int i = 1; i < _diffusionFanout; i++) { + for(int i = 0; i < _diffusionFanout; i++) { glm::vec3 randomDirection; float surfaceRandomness = randFloatInRange(0.5f,1.0f); @@ -1055,6 +986,7 @@ int AudioReflector::anylizePathsSingleStep() { // if our reflective attenuation is above our minimum, then add our reflection point and // allow our path to continue + /* if (isDiffusion) { qDebug() << "checking diffusion"; qDebug() << "reflectiveAttenuation=" << reflectiveAttenuation; @@ -1062,6 +994,7 @@ int AudioReflector::anylizePathsSingleStep() { qDebug() << "toListenerAttenuation=" << toListenerAttenuation; qDebug() << "(reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation=" << ((reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation); } + */ if (((reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation) > MINIMUM_ATTENUATION_TO_REFLECT && totalDelay < MAXIMUM_DELAY_MS) { @@ -1082,24 +1015,26 @@ int AudioReflector::anylizePathsSingleStep() { path->lastDelay = currentDelay; path->lastDistance = pathDistance; path->bounceCount++; - -//qDebug() << "whichPath=" << activePaths << "path->lastAttenuation=" << path->lastAttenuation << "path->lastDistance=" << path->lastDistance; - } else { path->finalized = true; // if we're too quiet, then we're done } } else { path->finalized = true; // if we're too quiet, then we're done + /* if (isDiffusion) { qDebug() << "diffusion too quiet!"; } + */ } } else { -//qDebug() << "whichPath=" << activePaths << "path->bounceCount=" << path->bounceCount << "ray missed..."; + //qDebug() << "whichPath=" << activePaths << "path->bounceCount=" << path->bounceCount << "ray missed..."; path->finalized = true; // if it doesn't intersect, then it is finished + + /* if (isDiffusion) { qDebug() << "diffusion doesn't intersect!"; } + */ } } } diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 1a0adb5550..1bdbabec44 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -392,6 +392,10 @@ Menu::Menu() : Qt::CTRL | Qt::SHIFT | Qt::Key_H, true); + addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingWithDiffusions, + Qt::CTRL | Qt::SHIFT | Qt::Key_W, + true); + addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::LowPassFilter, Qt::CTRL | Qt::SHIFT | Qt::Key_F, false); diff --git a/interface/src/Menu.h b/interface/src/Menu.h index fd7873fae9..6e42e21b06 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -249,6 +249,7 @@ namespace MenuOption { const QString AudioSpatialProcessingPreDelay = "Audio Spatial Processing add Pre-Delay"; const QString AudioSpatialProcessingStereoSource = "Audio Spatial Processing Stereo Source"; const QString AudioSpatialProcessingHeadOriented = "Audio Spatial Processing Head Oriented"; + const QString AudioSpatialProcessingWithDiffusions = "Audio Spatial Processing With Diffusions"; const QString EchoServerAudio = "Echo Server Audio"; const QString EchoLocalAudio = "Echo Local Audio"; const QString MuteAudio = "Mute Microphone"; From d3a9c6940cb7e44ec24e4e961490c290dbd4bb65 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 14 Apr 2014 10:12:08 -0700 Subject: [PATCH 379/595] some audio reflection cleanup --- interface/src/AudioReflector.cpp | 144 ++++--------------------------- interface/src/ui/Stats.cpp | 111 +++++++++++++----------- 2 files changed, 77 insertions(+), 178 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 28e9f6161b..e3c5e19b2a 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -510,6 +510,7 @@ void AudioReflector::newEchoAudio(unsigned int sampleTime, const QByteArray& sam _averageDelay = _delayCount == 0 ? 0 : _totalDelay / _delayCount; _averageAttenuation = _attenuationCount == 0 ? 0 : _totalAttenuation / _attenuationCount; + _reflections = _audiblePoints.size(); //quint64 end = usecTimestampNow(); //qDebug() << "AudioReflector::addSamples()... elapsed=" << (end - start); @@ -554,125 +555,26 @@ void AudioReflector::oldEchoAudio(unsigned int sampleTime, const QByteArray& sam } void AudioReflector::drawRays() { - //qDebug() << "AudioReflector::drawRays()"; - calculateAllReflections(); const glm::vec3 RED(1,0,0); - const glm::vec3 GREEN(0,1,0); - const glm::vec3 BLUE(0,0,1); - const glm::vec3 PURPLE(1,0,1); - const glm::vec3 YELLOW(1,1,0); - const glm::vec3 CYAN(0,1,1); - const glm::vec3 DARK_RED(0.8f,0.2f,0.2f); - const glm::vec3 DARK_GREEN(0.2f,0.8f,0.2f); - const glm::vec3 DARK_BLUE(0.2f,0.2f,0.8f); - const glm::vec3 DARK_PURPLE(0.8f,0.2f,0.8f); - const glm::vec3 DARK_YELLOW(0.8f,0.8f,0.2f); - const glm::vec3 DARK_CYAN(0.2f,0.8f,0.8f); - const glm::vec3 WHITE(1,1,1); - const glm::vec3 GRAY(0.5f,0.5f,0.5f); - glm::vec3 frontRightUpColor = RED; - glm::vec3 frontLeftUpColor = GREEN; - glm::vec3 backRightUpColor = BLUE; - glm::vec3 backLeftUpColor = CYAN; - glm::vec3 frontRightDownColor = PURPLE; - glm::vec3 frontLeftDownColor = YELLOW; - glm::vec3 backRightDownColor = WHITE; - glm::vec3 backLeftDownColor = DARK_RED; - glm::vec3 frontColor = GRAY; - glm::vec3 backColor = DARK_GREEN; - glm::vec3 leftColor = DARK_BLUE; - glm::vec3 rightColor = DARK_CYAN; - glm::vec3 upColor = DARK_PURPLE; - glm::vec3 downColor = DARK_YELLOW; - - // attempt to determine insidness/outsideness based on number of directional rays that reflect - bool inside = false; - - bool blockedUp = (_frontRightUpReflections.size() > 0) && - (_frontLeftUpReflections.size() > 0) && - (_backRightUpReflections.size() > 0) && - (_backLeftUpReflections.size() > 0) && - (_upReflections.size() > 0); - - bool blockedDown = (_frontRightDownReflections.size() > 0) && - (_frontLeftDownReflections.size() > 0) && - (_backRightDownReflections.size() > 0) && - (_backLeftDownReflections.size() > 0) && - (_downReflections.size() > 0); - - bool blockedFront = (_frontRightUpReflections.size() > 0) && - (_frontLeftUpReflections.size() > 0) && - (_frontRightDownReflections.size() > 0) && - (_frontLeftDownReflections.size() > 0) && - (_frontReflections.size() > 0); - - bool blockedBack = (_backRightUpReflections.size() > 0) && - (_backLeftUpReflections.size() > 0) && - (_backRightDownReflections.size() > 0) && - (_backLeftDownReflections.size() > 0) && - (_backReflections.size() > 0); - - bool blockedLeft = (_frontLeftUpReflections.size() > 0) && - (_backLeftUpReflections.size() > 0) && - (_frontLeftDownReflections.size() > 0) && - (_backLeftDownReflections.size() > 0) && - (_leftReflections.size() > 0); - - bool blockedRight = (_frontRightUpReflections.size() > 0) && - (_backRightUpReflections.size() > 0) && - (_frontRightDownReflections.size() > 0) && - (_backRightDownReflections.size() > 0) && - (_rightReflections.size() > 0); - - inside = blockedUp && blockedDown && blockedFront && blockedBack && blockedLeft && blockedRight; - - if (inside) { - frontRightUpColor = RED; - frontLeftUpColor = RED; - backRightUpColor = RED; - backLeftUpColor = RED; - frontRightDownColor = RED; - frontLeftDownColor = RED; - backRightDownColor = RED; - backLeftDownColor = RED; - frontColor = RED; - backColor = RED; - leftColor = RED; - rightColor = RED; - upColor = RED; - downColor = RED; - } - QMutexLocker locker(&_mutex); - drawReflections(_origin, frontRightUpColor, _frontRightUpReflections); - drawReflections(_origin, frontLeftUpColor, _frontLeftUpReflections); - drawReflections(_origin, backRightUpColor, _backRightUpReflections); - drawReflections(_origin, backLeftUpColor, _backLeftUpReflections); - drawReflections(_origin, frontRightDownColor, _frontRightDownReflections); - drawReflections(_origin, frontLeftDownColor, _frontLeftDownReflections); - drawReflections(_origin, backRightDownColor, _backRightDownReflections); - drawReflections(_origin, backLeftDownColor, _backLeftDownReflections); - drawReflections(_origin, frontColor, _frontReflections); - drawReflections(_origin, backColor, _backReflections); - drawReflections(_origin, leftColor, _leftReflections); - drawReflections(_origin, rightColor, _rightReflections); - drawReflections(_origin, upColor, _upReflections); - drawReflections(_origin, downColor, _downReflections); - - /* - qDebug() << "_reflections:" << _reflections - << "_averageDelay:" << _averageDelay - << "_maxDelay:" << _maxDelay - << "_minDelay:" << _minDelay; - - qDebug() << "_averageAttenuation:" << _averageAttenuation - << "_maxAttenuation:" << _maxAttenuation - << "_minAttenuation:" << _minAttenuation; - */ + drawReflections(_origin, RED, _frontRightUpReflections); + drawReflections(_origin, RED, _frontLeftUpReflections); + drawReflections(_origin, RED, _backRightUpReflections); + drawReflections(_origin, RED, _backLeftUpReflections); + drawReflections(_origin, RED, _frontRightDownReflections); + drawReflections(_origin, RED, _frontLeftDownReflections); + drawReflections(_origin, RED, _backRightDownReflections); + drawReflections(_origin, RED, _backLeftDownReflections); + drawReflections(_origin, RED, _frontReflections); + drawReflections(_origin, RED, _backReflections); + drawReflections(_origin, RED, _leftReflections); + drawReflections(_origin, RED, _rightReflections); + drawReflections(_origin, RED, _upReflections); + drawReflections(_origin, RED, _downReflections); } void AudioReflector::drawVector(const glm::vec3& start, const glm::vec3& end, const glm::vec3& color) { @@ -774,7 +676,6 @@ void AudioReflector::newDrawRays() { drawPath(path, RED); } else { diffusionNumber++; -//qDebug() << "drawing diffusion path:" << diffusionNumber << "length:" << path->reflections.size(); drawPath(path, GREEN); } } @@ -794,9 +695,6 @@ void AudioReflector::drawPath(AudioPath* path, const glm::vec3& originalColor) { void AudioReflector::anylizePaths() { - -qDebug() << "AudioReflector::anylizePaths()..."; - // clear our _audioPaths foreach(AudioPath* const& path, _audioPaths) { delete path; @@ -847,12 +745,8 @@ qDebug() << "AudioReflector::anylizePaths()..."; while(acitvePaths > 0) { acitvePaths = anylizePathsSingleStep(); steps++; - //qDebug() << "acitvePaths=" << acitvePaths << "steps=" << steps << "_audioPaths.size()=" << _audioPaths.size(); } - _reflections = _audiblePoints.size(); - - qDebug() << "_audiblePoints.size()=" << _audiblePoints.size(); } int AudioReflector::anylizePathsSingleStep() { @@ -863,14 +757,6 @@ int AudioReflector::anylizePathsSingleStep() { bool isDiffusion = (path->startPoint != _origin); - /* - qDebug() << "ray intersection... " - << " startPoint=[" << path->startPoint.x << "," << path->startPoint.y << "," << path->startPoint.z << "]" - << " _origin=[" << _origin.x << "," << _origin.y << "," << _origin.z << "]" - << " bouceCount= " << path->bounceCount - << " isDiffusion=" << isDiffusion; - */ - glm::vec3 start = path->lastPoint; glm::vec3 direction = path->lastDirection; OctreeElement* elementHit; // output from findRayIntersection diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp index c540877262..befa710903 100644 --- a/interface/src/ui/Stats.cpp +++ b/interface/src/ui/Stats.cpp @@ -293,11 +293,7 @@ void Stats::display( glm::vec3 avatarPos = myAvatar->getPosition(); lines = _expanded ? 5 : 3; - if (_expanded && Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessing)) { - lines += 3; // spatial audio processing adds 3 extra lines - } - - + drawBackground(backgroundColor, horizontalOffset, 0, _geoStatsWidth, lines * STATS_PELS_PER_LINE + 10); horizontalOffset += 5; @@ -338,49 +334,6 @@ void Stats::display( verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, downloads.str().c_str(), color); - - if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessing)) { - const AudioReflector* audioReflector = Application::getInstance()->getAudioReflector(); - - - // add some reflection stats - char reflectionsStatus[128]; - - sprintf(reflectionsStatus, "Reflections: %d, Original: %s, Ears: %s, Source: %s", - audioReflector->getReflections(), - (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingIncudeOriginal) - ? "with" : "without"), - (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingSeparateEars) - ? "two" : "one"), - (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingStereoSource) - ? "stereo" : "mono") - ); - - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); - - float preDelay = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingPreDelay) ? - audioReflector->getPreDelay() : 0.0f; - - sprintf(reflectionsStatus, "Delay: pre: %f, average %f, max %f, min %f, speed: %f", - preDelay, - audioReflector->getAverageDelayMsecs(), - audioReflector->getMaxDelayMsecs(), - audioReflector->getMinDelayMsecs(), - audioReflector->getSoundMsPerMeter()); - - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); - - sprintf(reflectionsStatus, "Attenuation: average %f, max %f, min %f, distance scale: %f", - audioReflector->getAverageAttenuation(), - audioReflector->getMaxAttenuation(), - audioReflector->getMinAttenuation(), - audioReflector->getDistanceAttenuationScalingFactor()); - - verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); - } } verticalOffset = 0; @@ -389,6 +342,10 @@ void Stats::display( VoxelSystem* voxels = Application::getInstance()->getVoxels(); lines = _expanded ? 12 : 3; + if (_expanded && Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessing)) { + lines += 5; // spatial audio processing adds 1 spacing line and 4 extra lines of info + } + drawBackground(backgroundColor, horizontalOffset, 0, glWidget->width() - horizontalOffset, lines * STATS_PELS_PER_LINE + 10); horizontalOffset += 5; @@ -545,5 +502,61 @@ void Stats::display( voxelStats << "LOD: You can see " << qPrintable(displayLODDetails.trimmed()); verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); - } + } + + + if (_expanded && Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessing)) { + verticalOffset += STATS_PELS_PER_LINE; // space one line... + + const AudioReflector* audioReflector = Application::getInstance()->getAudioReflector(); + + // add some reflection stats + char reflectionsStatus[128]; + + sprintf(reflectionsStatus, "Reflections: %d, Diffusion: %s, Original: %s, Ears: %s, Source: %s", + audioReflector->getReflections(), + (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions) + ? "yes" : "no"), + (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingIncudeOriginal) + ? "included" : "silent"), + (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingSeparateEars) + ? "two" : "one"), + (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingStereoSource) + ? "stereo" : "mono") + ); + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + + float preDelay = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingPreDelay) ? + audioReflector->getPreDelay() : 0.0f; + + sprintf(reflectionsStatus, "Delay: pre: %6.3f, average %6.3f, max %6.3f, min %6.3f, speed: %6.3f", + preDelay, + audioReflector->getAverageDelayMsecs(), + audioReflector->getMaxDelayMsecs(), + audioReflector->getMinDelayMsecs(), + audioReflector->getSoundMsPerMeter()); + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + + sprintf(reflectionsStatus, "Attenuation: average %5.3f, max %5.3f, min %5.3f, distance scale: %5.3f", + audioReflector->getAverageAttenuation(), + audioReflector->getMaxAttenuation(), + audioReflector->getMinAttenuation(), + audioReflector->getDistanceAttenuationScalingFactor()); + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + + bool diffusionEnabled = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions); + int fanout = diffusionEnabled ? audioReflector->getDiffusionFanout() : 0; + sprintf(reflectionsStatus, "Diffusion: %s, Fanout: %d", (diffusionEnabled ? "yes" : "no"), fanout); + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + + } + } From 5630ed65af40a0a74731ba5b819d96e94da2af0b Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 14 Apr 2014 10:35:55 -0700 Subject: [PATCH 380/595] more cleanup --- interface/src/AudioReflector.cpp | 159 ++++++++++--------------------- interface/src/AudioReflector.h | 4 +- 2 files changed, 50 insertions(+), 113 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index e3c5e19b2a..726cbfac57 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -163,44 +163,14 @@ void AudioReflector::calculateAllReflections() { bool shouldRecalc = _reflections == 0 || _myAvatar->getHead()->getPosition() != _origin || (orientation != _orientation); - /* - qDebug() << "wantHeadOrientation=" << wantHeadOrientation; - - qDebug(" _myAvatar->getHead()->getPosition()=%f,%f,%f", - _myAvatar->getHead()->getPosition().x, - _myAvatar->getHead()->getPosition().y, - _myAvatar->getHead()->getPosition().z); - - qDebug(" _origin=%f,%f,%f", - _origin.x, - _origin.y, - _origin.z); - - qDebug(" orientation=%f,%f,%f,%f", - orientation.x, - orientation.y, - orientation.z, - orientation.w); - - qDebug(" _orientation=%f,%f,%f,%f", - _orientation.x, - _orientation.y, - _orientation.z, - _orientation.w); - */ if (shouldRecalc) { - //qDebug() << "origin or orientation has changed..."; - QMutexLocker locker(&_mutex); - - - quint64 start = usecTimestampNow(); + quint64 start = usecTimestampNow(); _origin = _myAvatar->getHead()->getPosition(); glm::vec3 averageEarPosition = _myAvatar->getHead()->getPosition(); _listenerPosition = averageEarPosition; -qDebug() << "_listenerPosition:" << _listenerPosition.x << "," << _listenerPosition.y << "," << _listenerPosition.z; _orientation = orientation; glm::vec3 right = glm::normalize(_orientation * IDENTITY_RIGHT); glm::vec3 up = glm::normalize(_orientation * IDENTITY_UP); @@ -235,9 +205,11 @@ qDebug() << "_listenerPosition:" << _listenerPosition.x << "," << _listenerPosit quint64 end = usecTimestampNow(); reset(); - - //qDebug() << "Reflections recalculated in " << (end - start) << "usecs"; - + + const bool wantDebugging = false; + if (wantDebugging) { + qDebug() << "calculateAllReflections() elapsed=" << (end - start); + } } } @@ -633,30 +605,17 @@ void AudioReflector::newCalculateAllReflections() { || !isSimilarPosition(listenerPosition, _listenerPosition); if (shouldRecalc) { - - /* - qDebug() << "_audiblePoints.size()=" << _audiblePoints.size(); - qDebug() << "isSimilarPosition(origin, _origin)=" << isSimilarPosition(origin, _origin); - qDebug() << "isSimilarPosition(listenerPosition, _listenerPosition)=" << isSimilarPosition(listenerPosition, _listenerPosition); - qDebug() << "isSimilarOrientation(orientation, _orientation)=" << isSimilarOrientation(orientation, _orientation); - if (!isSimilarOrientation(orientation, _orientation)) { - qDebug() << " orientation=" << orientation.x << "," << orientation.y << "," - << orientation.y << "," << orientation.w; - - qDebug() << " _orientation=" << _orientation.x << "," << _orientation.y << "," - << _orientation.y << "," << _orientation.w; - } - */ - QMutexLocker locker(&_mutex); quint64 start = usecTimestampNow(); _origin = origin; _orientation = orientation; _listenerPosition = listenerPosition; - - anylizePaths(); // actually does the work - + analyzePaths(); // actually does the work quint64 end = usecTimestampNow(); + const bool wantDebugging = false; + if (wantDebugging) { + qDebug() << "newCalculateAllReflections() elapsed=" << (end - start); + } } } @@ -694,7 +653,7 @@ void AudioReflector::drawPath(AudioPath* path, const glm::vec3& originalColor) { } -void AudioReflector::anylizePaths() { +void AudioReflector::analyzePaths() { // clear our _audioPaths foreach(AudioPath* const& path, _audioPaths) { delete path; @@ -703,7 +662,6 @@ void AudioReflector::anylizePaths() { _audiblePoints.clear(); // clear our audible points // add our initial paths - glm::vec3 averageEarPosition = _myAvatar->getHead()->getPosition(); glm::vec3 right = glm::normalize(_orientation * IDENTITY_RIGHT); glm::vec3 up = glm::normalize(_orientation * IDENTITY_UP); glm::vec3 front = glm::normalize(_orientation * IDENTITY_FRONT); @@ -739,22 +697,23 @@ void AudioReflector::anylizePaths() { addSoundSource(_origin, backRightDown, initialAttenuation, preDelay); addSoundSource(_origin, backLeftDown, initialAttenuation, preDelay); - // loop through all our + // loop through all our audio paths and keep analyzing them until they complete int steps = 0; int acitvePaths = _audioPaths.size(); // when we start, all paths are active while(acitvePaths > 0) { - acitvePaths = anylizePathsSingleStep(); + acitvePaths = analyzePathsSingleStep(); steps++; } _reflections = _audiblePoints.size(); } -int AudioReflector::anylizePathsSingleStep() { +int AudioReflector::analyzePathsSingleStep() { // iterate all the active sound paths, calculate one step per active path int activePaths = 0; foreach(AudioPath* const& path, _audioPaths) { + bool wantExtraDebuggging = false; bool isDiffusion = (path->startPoint != _origin); glm::vec3 start = path->lastPoint; @@ -767,37 +726,28 @@ int AudioReflector::anylizePathsSingleStep() { float currentDelay = path->lastDelay; // start with our delay so far float pathDistance = path->lastDistance; float totalDelay = path->lastDelay; // start with our delay so far - unsigned int bounceCount = path->bounceCount; if (!path->finalized) { activePaths++; - // quick hack to stop early reflections right away... - //if (!isDiffusion && path->bounceCount > 1) { - // path->finalized = true; - // qDebug() << "stopping reflections on first bounce!"; - //} else if (path->bounceCount > ABSOLUTE_MAXIMUM_BOUNCE_COUNT) { path->finalized = true; - /* - if (isDiffusion) { + if (wantExtraDebuggging && isDiffusion) { qDebug() << "diffusion bounceCount too high!"; } - */ } else if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); pathDistance += glm::distance(start, end); - /* - qDebug() << "ray intersection... " - << " startPoint=[" << path->startPoint.x << "," << path->startPoint.y << "," << path->startPoint.z << "]" - << " bouceCount= " << path->bounceCount - << " end=[" << end.x << "," << end.y << "," << end.z << "]" - << " pathDistance=" << pathDistance; - */ - + if (wantExtraDebuggging) { + qDebug() << "ray intersection... " + << " startPoint=[" << path->startPoint.x << "," << path->startPoint.y << "," << path->startPoint.z << "]" + << " bouceCount= " << path->bounceCount + << " end=[" << end.x << "," << end.y << "," << end.z << "]" + << " pathDistance=" << pathDistance; + } // We aren't using this... should we be???? float toListenerDistance = glm::distance(end, _listenerPosition); @@ -820,67 +770,60 @@ int AudioReflector::anylizePathsSingleStep() { // total delay includes the bounce back to listener totalDelay = getDelayFromDistance(totalDistance); float toListenerAttenuation = getDistanceAttenuationCoefficient(toListenerDistance); - //qDebug() << "toListenerDistance=" << toListenerDistance; - //qDebug() << "toListenerAttenuation=" << toListenerAttenuation; // if our resulting partial diffusion attenuation, is still above our minimum attenuation // then we add new paths for each diffusion point if ((partialDiffusionAttenuation * toListenerAttenuation) > MINIMUM_ATTENUATION_TO_REFLECT && totalDelay < MAXIMUM_DELAY_MS) { - // add sound sources for the normal - //glm::vec3 faceNormal = getFaceNormal(face); - //addSoundSource(end, faceNormal, partialDiffusionAttenuation, currentDelay); - // diffusions fan out from random places on the semisphere of the collision point for(int i = 0; i < _diffusionFanout; i++) { - glm::vec3 randomDirection; + glm::vec3 diffusion; - float surfaceRandomness = randFloatInRange(0.5f,1.0f); - float surfaceRemainder = (1.0f - surfaceRandomness)/2.0f; - float altRemainderSignA = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; - float altRemainderSignB = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; + float randomness = randFloatInRange(0.5f,1.0f); + float remainder = (1.0f - randomness)/2.0f; + float remainderSignA = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; + float remainderSignB = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; if (face == MIN_X_FACE) { - randomDirection = glm::vec3(-surfaceRandomness, surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB); + diffusion = glm::vec3(-randomness, remainder * remainderSignA, remainder * remainderSignB); } else if (face == MAX_X_FACE) { - randomDirection = glm::vec3(surfaceRandomness, surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB); + diffusion = glm::vec3(randomness, remainder * remainderSignA, remainder * remainderSignB); } else if (face == MIN_Y_FACE) { - randomDirection = glm::vec3(surfaceRemainder * altRemainderSignA, -surfaceRandomness, surfaceRemainder * altRemainderSignB); + diffusion = glm::vec3(remainder * remainderSignA, -randomness, remainder * remainderSignB); } else if (face == MAX_Y_FACE) { - randomDirection = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRandomness, surfaceRemainder * altRemainderSignB); + diffusion = glm::vec3(remainder * remainderSignA, randomness, remainder * remainderSignB); } else if (face == MIN_Z_FACE) { - randomDirection = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB, -surfaceRandomness); + diffusion = glm::vec3(remainder * remainderSignA, remainder * remainderSignB, -randomness); } else if (face == MAX_Z_FACE) { - randomDirection = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB, surfaceRandomness); + diffusion = glm::vec3(remainder * remainderSignA, remainder * remainderSignB, randomness); } - randomDirection = glm::normalize(randomDirection); + diffusion = glm::normalize(diffusion); - /* - qDebug() << "DIFFUSION... addSoundSource()... partialDiffusionAttenuation=" << partialDiffusionAttenuation << "\n" << - " MINIMUM_ATTENUATION_TO_REFLECT=" << MINIMUM_ATTENUATION_TO_REFLECT << "\n" << - " previous direction=[" << direction.x << "," << direction.y << "," << direction.z << "]" << "\n" << - " randomDirection=[" << randomDirection.x << "," << randomDirection.y << "," << randomDirection.z << "]" << "\n" << - " end=[" << end.x << "," << end.y << "," << end.z << "]"; - */ + if (wantExtraDebuggging) { + qDebug() << "DIFFUSION... addSoundSource()... " << + " partialDiffusionAttenuation=" << partialDiffusionAttenuation << "\n" << + " MINIMUM_ATTENUATION_TO_REFLECT=" << MINIMUM_ATTENUATION_TO_REFLECT << "\n" << + " direction=[" << direction.x << "," << direction.y << "," << direction.z << "]\n" << + " diffusion=[" << diffusion.x << "," << diffusion.y << "," << diffusion.z << "]\n" << + " end=[" << end.x << "," << end.y << "," << end.z << "]"; + } // add sound sources for these diffusions - addSoundSource(end, randomDirection, partialDiffusionAttenuation, currentDelay); + addSoundSource(end, diffusion, partialDiffusionAttenuation, currentDelay); } } // if our reflective attenuation is above our minimum, then add our reflection point and // allow our path to continue - /* - if (isDiffusion) { + if (wantExtraDebuggging && isDiffusion) { qDebug() << "checking diffusion"; qDebug() << "reflectiveAttenuation=" << reflectiveAttenuation; qDebug() << "totalDiffusionAttenuation=" << totalDiffusionAttenuation; qDebug() << "toListenerAttenuation=" << toListenerAttenuation; qDebug() << "(reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation=" << ((reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation); } - */ if (((reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation) > MINIMUM_ATTENUATION_TO_REFLECT && totalDelay < MAXIMUM_DELAY_MS) { @@ -906,21 +849,15 @@ int AudioReflector::anylizePathsSingleStep() { } } else { path->finalized = true; // if we're too quiet, then we're done - /* - if (isDiffusion) { + if (wantExtraDebuggging && isDiffusion) { qDebug() << "diffusion too quiet!"; } - */ } } else { - //qDebug() << "whichPath=" << activePaths << "path->bounceCount=" << path->bounceCount << "ray missed..."; path->finalized = true; // if it doesn't intersect, then it is finished - - /* - if (isDiffusion) { + if (wantExtraDebuggging && isDiffusion) { qDebug() << "diffusion doesn't intersect!"; } - */ } } } diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 3e8f06e8a7..02e43c4b4f 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -169,8 +169,8 @@ private: void addSoundSource(const glm::vec3& origin, const glm::vec3& initialDirection, float initialAttenuation, float initialDelay); // helper that handles audioPath analysis - int anylizePathsSingleStep(); - void anylizePaths(); + int analyzePathsSingleStep(); + void analyzePaths(); void newDrawRays(); void drawPath(AudioPath* path, const glm::vec3& originalColor); void newCalculateAllReflections(); From 6b4a7d365f69cb23b39ed87d88d36d1b7107d8fd Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 14 Apr 2014 10:43:42 -0700 Subject: [PATCH 381/595] update build guide with extra info for GnuTLS --- BUILD.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/BUILD.md b/BUILD.md index 6464f14d08..7e35c9569b 100644 --- a/BUILD.md +++ b/BUILD.md @@ -5,6 +5,8 @@ Dependencies * [zLib](http://www.zlib.net/) ~> 1.2.8 * [glm](http://glm.g-truc.net/0.9.5/index.html) ~> 0.9.5.2 * [qxmpp](https://code.google.com/p/qxmpp/) ~> 0.7.6 +* [GnuTLS](http://gnutls.org/download.html) ~> 3.2.12 + * IMPORTANT: GnuTLS 3.2.12 is crtiical to avoid a security vulnerability. #####Linux only * [freeglut](http://freeglut.sourceforge.net/) ~> 2.8.0 @@ -50,12 +52,18 @@ Should you choose not to install Qt5 via a package manager that handles dependen libasound2 libxmu-dev libxi-dev freeglut3-dev libasound2-dev libjack-dev +#####GnuTLS + +If `libgnutls28-dev` 3.2.12 or higher is available via your package manager, it would be easiest to grab it from there. At the time of this writing that is not the case for any version of Ubuntu, so it will need to be built from source. + +gmplib is a dependency for GnuTLS. On Ubuntu, we were unable to build hogweed (part of libnettle) with gmp 6.x.x. If nettle is not built with hogweed, GnuTLS will fail to build. If you run into this problem, try version 4.2.1 of gmplib. + ####OS X #####Package Managers [Homebrew](http://brew.sh/) is an excellent package manager for OS X. It makes install of all hifi dependencies very simple. brew tap highfidelity/homebrew-formulas - brew install cmake glm zlib + brew install cmake glm zlib gnutls brew install highfidelity/formulas/qt5 brew link qt5 --force brew install highfidelity/formulas/qxmpp @@ -128,6 +136,15 @@ For many of the external libraries where precompiled binaries are readily availa *NOTE: Qt does not support 64-bit builds on Windows 7, so you must use the 32-bit version of libraries for interface.exe to run. The 32-bit version of the static library is the one linked by our CMake find modules* +#####GnuTLS +You can get a precompiled version of GnuTLS for Windows [here](ftp://ftp.gnutls.org/gcrypt/gnutls/w32/). + +To use GnuTLS with Visual Studio, you will need to create `libgnutls-28.lib`, the import library for Visual Studio projects. this is done using the `lib` command in the `bin` folder of your GnuTLS download. + + $GNUTLS_DIR\bin> lib /def:libgnutls-28.def + +This will create `libgnutls-28.lib`. Copy that file to the `lib` folder of you GnuTLS folder, and the Cmake FindGnuTLS module in this repo will find it during the Cmake run. As will other external dependencies for this project, the associated GnuTLS DLL will need to be in your path. + #### DLLs As with the Qt libraries, you will need to make sure the directory containing dynamically-linked libraries is in your path. For example, for a dynamically linked build of freeglut, the directory to add to your path in which the DLL is found is `FREEGLUT_DIR/bin`. Where possible, you can use static builds of the external dependencies to avoid this requirement. From 007a477400705af7a0ad71ec09a1b203c31c5ba0 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 14 Apr 2014 10:46:42 -0700 Subject: [PATCH 382/595] fix a typo in build guide --- BUILD.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BUILD.md b/BUILD.md index 7e35c9569b..e29c20b6d2 100644 --- a/BUILD.md +++ b/BUILD.md @@ -6,7 +6,7 @@ Dependencies * [glm](http://glm.g-truc.net/0.9.5/index.html) ~> 0.9.5.2 * [qxmpp](https://code.google.com/p/qxmpp/) ~> 0.7.6 * [GnuTLS](http://gnutls.org/download.html) ~> 3.2.12 - * IMPORTANT: GnuTLS 3.2.12 is crtiical to avoid a security vulnerability. + * IMPORTANT: GnuTLS 3.2.12 is critical to avoid a security vulnerability. #####Linux only * [freeglut](http://freeglut.sourceforge.net/) ~> 2.8.0 From 6cb5497242e3714fdbf271713be752693d87260e Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 14 Apr 2014 10:49:11 -0700 Subject: [PATCH 383/595] codify some library names and fix some other spelling --- BUILD.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BUILD.md b/BUILD.md index e29c20b6d2..265e21e031 100644 --- a/BUILD.md +++ b/BUILD.md @@ -56,7 +56,7 @@ Should you choose not to install Qt5 via a package manager that handles dependen If `libgnutls28-dev` 3.2.12 or higher is available via your package manager, it would be easiest to grab it from there. At the time of this writing that is not the case for any version of Ubuntu, so it will need to be built from source. -gmplib is a dependency for GnuTLS. On Ubuntu, we were unable to build hogweed (part of libnettle) with gmp 6.x.x. If nettle is not built with hogweed, GnuTLS will fail to build. If you run into this problem, try version 4.2.1 of gmplib. +`gmplib` is a dependency for GnuTLS. On Ubuntu, we were unable to build `hogweed` (part of `libnettle`) with `gmpib` 6.x.x. If nettle is not built with `hogweed`, GnuTLS will fail to build. If you run into this problem, try version 4.2.1 of `gmplib`. ####OS X #####Package Managers @@ -143,7 +143,7 @@ To use GnuTLS with Visual Studio, you will need to create `libgnutls-28.lib`, th $GNUTLS_DIR\bin> lib /def:libgnutls-28.def -This will create `libgnutls-28.lib`. Copy that file to the `lib` folder of you GnuTLS folder, and the Cmake FindGnuTLS module in this repo will find it during the Cmake run. As will other external dependencies for this project, the associated GnuTLS DLL will need to be in your path. +This will create `libgnutls-28.lib` in the `bin` folder. Copy that file to the `lib` sub-folder of your GnuTLS folder, and the Cmake FindGnuTLS module in this repo will find it during the Cmake run. As with other external dependencies for this project, the associated GnuTLS DLL will need to be in your path. #### DLLs As with the Qt libraries, you will need to make sure the directory containing dynamically-linked libraries is in your path. For example, for a dynamically linked build of freeglut, the directory to add to your path in which the DLL is found is `FREEGLUT_DIR/bin`. Where possible, you can use static builds of the external dependencies to avoid this requirement. From 1c7f8c87bcf9e9b1bb625025046489bc713cf384 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 14 Apr 2014 10:50:03 -0700 Subject: [PATCH 384/595] don't codify directories in OS X section --- BUILD.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BUILD.md b/BUILD.md index 265e21e031..d6ec7c82b1 100644 --- a/BUILD.md +++ b/BUILD.md @@ -79,7 +79,7 @@ If Xcode is your editor of choice, you can ask CMake to generate Xcode project f After running cmake, you will have the make files or Xcode project file necessary to build all of the components. Open the hifi.xcodeproj file, choose ALL_BUILD from the Product > Scheme menu (or target drop down), and click Run. -If the build completes successfully, you will have built targets for all components located in the `build/${target_name}/Debug directories`. +If the build completes successfully, you will have built targets for all components located in the `build/${target_name}/Debug` directories. Windows === From 95abc74d83294039f9b3c3c4d6a3ea52fe8eb095 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 14 Apr 2014 10:50:57 -0700 Subject: [PATCH 385/595] add GnuTLS to example windows folder structure --- BUILD.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/BUILD.md b/BUILD.md index d6ec7c82b1..24618ff7ac 100644 --- a/BUILD.md +++ b/BUILD.md @@ -129,6 +129,10 @@ The recommended route for CMake to find external dependencies is to place all of -> qxmpp -> include -> lib + -> gnutls + -> bin + -> include + -> lib *NOTE: Be careful with glm. For the folder other libraries would normally call 'include', the folder containing the headers, glm opts to use 'glm'. You will have a glm folder nested inside the top-level glm folder.* From 70191111c737cca0adecbab9682e61b577b5d99b Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 14 Apr 2014 10:51:36 -0700 Subject: [PATCH 386/595] remove GnuTLS DLL tip since DLL section is right below --- BUILD.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BUILD.md b/BUILD.md index 24618ff7ac..f789437d60 100644 --- a/BUILD.md +++ b/BUILD.md @@ -147,7 +147,7 @@ To use GnuTLS with Visual Studio, you will need to create `libgnutls-28.lib`, th $GNUTLS_DIR\bin> lib /def:libgnutls-28.def -This will create `libgnutls-28.lib` in the `bin` folder. Copy that file to the `lib` sub-folder of your GnuTLS folder, and the Cmake FindGnuTLS module in this repo will find it during the Cmake run. As with other external dependencies for this project, the associated GnuTLS DLL will need to be in your path. +This will create `libgnutls-28.lib` in the `bin` folder. Copy that file to the `lib` sub-folder of your GnuTLS folder, and the Cmake FindGnuTLS module in this repo will find it during the Cmake run. #### DLLs As with the Qt libraries, you will need to make sure the directory containing dynamically-linked libraries is in your path. For example, for a dynamically linked build of freeglut, the directory to add to your path in which the DLL is found is `FREEGLUT_DIR/bin`. Where possible, you can use static builds of the external dependencies to avoid this requirement. From c5c8327359eabbd583336d0fd476bfe783ce59c0 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 14 Apr 2014 10:57:34 -0700 Subject: [PATCH 387/595] update required version of cmake to 2.8.12.2 --- BUILD.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BUILD.md b/BUILD.md index f789437d60..c5a7a604b4 100644 --- a/BUILD.md +++ b/BUILD.md @@ -1,6 +1,6 @@ Dependencies === -* [cmake](http://www.cmake.org/cmake/resources/software.html) ~> 2.8.11 +* [cmake](http://www.cmake.org/cmake/resources/software.html) ~> 2.8.12.2 * [Qt](http://qt-project.org/downloads) ~> 5.2.0 * [zLib](http://www.zlib.net/) ~> 1.2.8 * [glm](http://glm.g-truc.net/0.9.5/index.html) ~> 0.9.5.2 From f698f3375aae2da4ed3fc86e8e2f874d27509bc5 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Mon, 14 Apr 2014 11:34:27 -0700 Subject: [PATCH 388/595] Update resource urls for chat window close button --- interface/ui/chatWindow.ui | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/ui/chatWindow.ui b/interface/ui/chatWindow.ui index 9321e1e8ea..0372e00c09 100644 --- a/interface/ui/chatWindow.ui +++ b/interface/ui/chatWindow.ui @@ -139,14 +139,14 @@ QPushButton { background-color: rgba( 0, 0, 0, 0% ); border: none; - image: url(:images/close.svg) + image: url(../resources/images/close.svg) } QPushButton:pressed { background-color: rgba( 0, 0, 0, 0% ); border: none; - image: url(:images/close_down.svg) + image: url(../resources/images/close_down.svg) } From 4ae148ff19d141199648595685593897d67f3f71 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Mon, 14 Apr 2014 11:34:35 -0700 Subject: [PATCH 389/595] Update chat window to not allow movement while docked --- interface/src/ui/ChatWindow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/ui/ChatWindow.cpp b/interface/src/ui/ChatWindow.cpp index 38e9553723..97fa81afc5 100644 --- a/interface/src/ui/ChatWindow.cpp +++ b/interface/src/ui/ChatWindow.cpp @@ -90,7 +90,7 @@ ChatWindow::~ChatWindow() { } void ChatWindow::mousePressEvent(QMouseEvent *e) { - if (e->button() == Qt::LeftButton) { + if (e->button() == Qt::LeftButton && isFloating()) { _mousePressed = true; _mouseStartPosition = e->pos(); } From 0d308e7cb99a88a79c0df5aed158e26ad4b09f5d Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 14 Apr 2014 11:58:49 -0700 Subject: [PATCH 390/595] more cleanup add support for enable/disable rendering of paths --- interface/src/Audio.cpp | 2 - interface/src/AudioReflector.cpp | 105 ++++++++++++++++++++----------- interface/src/AudioReflector.h | 8 ++- interface/src/Menu.cpp | 4 ++ interface/src/Menu.h | 1 + interface/src/ui/Stats.cpp | 8 +-- 6 files changed, 85 insertions(+), 43 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 77b9fbb16b..2cc02b1368 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -822,8 +822,6 @@ void Audio::processReceivedAudio(AudioRingBuffer& ringBuffer) { // add the next numNetworkOutputSamples from each QByteArray // in our _localInjectionByteArrays QVector to the localInjectedSamples - - if (Menu::getInstance()->isOptionChecked(MenuOption::LowPassFilter)) { int channels = _desiredOutputFormat.channelCount(); int filterSamples = numNetworkOutputSamples / channels; diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 726cbfac57..80eebb990d 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -39,12 +39,24 @@ AudioReflector::AudioReflector(QObject* parent) : void AudioReflector::render() { - if (!_myAvatar) { - return; // exit early if not set up correctly + + // if we're not set up yet, or we're not processing spatial audio, then exit early + if (!_myAvatar || !_audio->getProcessSpatialAudio()) { + return; + } + + bool withDiffusions = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions); + + // Even if we're not rendering, use this as a chance to recalculate our reflections + if (withDiffusions) { + newCalculateAllReflections(); + } else { + calculateAllReflections(); } - if (_audio->getProcessSpatialAudio()) { - if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions)) { + if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingRenderPaths)) { + // here's where we actually render + if (withDiffusions) { newDrawRays(); } else { drawRays(); @@ -52,8 +64,6 @@ void AudioReflector::render() { } } - - // delay = 1ms per foot // = 3ms per meter // attenuation = @@ -62,6 +72,9 @@ void AudioReflector::render() { float AudioReflector::getDelayFromDistance(float distance) { float delay = (_soundMsPerMeter * distance); + // NOTE: kind of hacky, the old code (which didn't handle diffusions, assumes that this function + // will add in any and all pre delay. But the new method (which includes diffusions) handles pre delay + // on it's own. So we only add in pre delay if the pre delay is enabled, and we're not in diffusion mode if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingPreDelay) && !Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions)) { @@ -71,17 +84,6 @@ float AudioReflector::getDelayFromDistance(float distance) { return delay; } -// **option 1**: this is what we're using -const float PER_BOUNCE_ATTENUATION_FACTOR = 0.5f; - -// **option 2**: we're not using these -//const float BOUNCE_ATTENUATION_FACTOR = 0.125f; -// each bounce we adjust our attenuation by this factor, the result is an asymptotically decreasing attenuation... -// 0.125, 0.25, 0.5, ... -//const float PER_BOUNCE_ATTENUATION_ADJUSTMENT = 2.0f; -// we don't grow larger than this, which means by the 4th bounce we don't get that much less quiet -//const float MAX_BOUNCE_ATTENUATION = 0.99f; - float AudioReflector::getDistanceAttenuationCoefficient(float distance) { const float DISTANCE_SCALE = 2.5f; const float GEOMETRIC_AMPLITUDE_SCALAR = 0.3f; @@ -100,8 +102,12 @@ float AudioReflector::getDistanceAttenuationCoefficient(float distance) { return distanceCoefficient; } -float getBounceAttenuationCoefficient(int bounceCount) { - return PER_BOUNCE_ATTENUATION_FACTOR * bounceCount; +// This is used in the "old" model with diffusions... it's essentially the amount of energy that is reflected on each bounce +float AudioReflector::getBounceAttenuationCoefficient(int bounceCount) { + // now we know the current attenuation for the "perfect" reflection case, but we now incorporate + // our surface materials to determine how much of this ray is absorbed, reflected, and diffused + SurfaceCharacteristics material = getSurfaceCharacteristics(); + return material.reflectiveRatio * bounceCount; } glm::vec3 getFaceNormal(BoxFace face) { @@ -130,6 +136,7 @@ glm::vec3 getFaceNormal(BoxFace face) { void AudioReflector::reset() { _reflections = 0; + _diffusionPathCount = 0; _averageAttenuation = 0.0f; _maxAttenuation = 0.0f; _minAttenuation = 0.0f; @@ -151,7 +158,6 @@ void AudioReflector::reset() { _rightReflections.size() + _upReflections.size() + _downReflections.size(); - } void AudioReflector::calculateAllReflections() { @@ -161,7 +167,9 @@ void AudioReflector::calculateAllReflections() { bool wantHeadOrientation = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingHeadOriented); glm::quat orientation = wantHeadOrientation ? _myAvatar->getHead()->getFinalOrientation() : _myAvatar->getOrientation(); - bool shouldRecalc = _reflections == 0 || _myAvatar->getHead()->getPosition() != _origin || (orientation != _orientation); + bool shouldRecalc = _reflections == 0 + || !isSimilarPosition(_myAvatar->getHead()->getPosition(), _origin) + || !isSimilarOrientation(orientation, _orientation); if (shouldRecalc) { QMutexLocker locker(&_mutex); @@ -236,7 +244,8 @@ QVector AudioReflector::calculateReflections(const glm::vec3& earPosi float earDistance = glm::distance(end, earPosition); float totalDistance = earDistance + distance; totalDelay = getDelayFromDistance(totalDistance); - currentAttenuation = getDistanceAttenuationCoefficient(totalDistance) * getBounceAttenuationCoefficient(bounceCount); + currentAttenuation = getDistanceAttenuationCoefficient(totalDistance) * + getBounceAttenuationCoefficient(bounceCount); if (currentAttenuation > MINIMUM_ATTENUATION_TO_REFLECT && totalDelay < MAXIMUM_DELAY_MS) { reflectionPoints.push_back(end); @@ -409,9 +418,6 @@ void AudioReflector::injectAudiblePoint(const AudioPoint& audiblePoint, int rightEarDelay = rightEarDelayMsecs * sampleRate / MSECS_PER_SECOND; int leftEarDelay = leftEarDelayMsecs * sampleRate / MSECS_PER_SECOND; - //qDebug() << "leftTotalDistance=" << leftTotalDistance << "rightTotalDistance=" << rightTotalDistance; - //qDebug() << "leftEarDelay=" << leftEarDelay << "rightEarDelay=" << rightEarDelay; - float rightEarAttenuation = getDistanceAttenuationCoefficient(rightEarDistance) * audiblePoint.attenuation; float leftEarAttenuation = getDistanceAttenuationCoefficient(leftEarDistance) * audiblePoint.attenuation; @@ -463,8 +469,6 @@ void AudioReflector::processInboundAudio(unsigned int sampleTime, const QByteArr } void AudioReflector::newEchoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { - //quint64 start = usecTimestampNow(); - _maxDelay = 0; _maxAttenuation = 0.0f; _minDelay = std::numeric_limits::max(); @@ -483,9 +487,12 @@ void AudioReflector::newEchoAudio(unsigned int sampleTime, const QByteArray& sam _averageDelay = _delayCount == 0 ? 0 : _totalDelay / _delayCount; _averageAttenuation = _attenuationCount == 0 ? 0 : _totalAttenuation / _attenuationCount; _reflections = _audiblePoints.size(); - - //quint64 end = usecTimestampNow(); - //qDebug() << "AudioReflector::addSamples()... elapsed=" << (end - start); + _diffusionPathCount = countDiffusionPaths(); + + if (_reflections == 0) { + _minDelay = 0.0f; + _minAttenuation = 0.0f; + } } void AudioReflector::oldEchoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { @@ -521,14 +528,29 @@ void AudioReflector::oldEchoAudio(unsigned int sampleTime, const QByteArray& sam _averageDelay = _delayCount == 0 ? 0 : _totalDelay / _delayCount; _averageAttenuation = _attenuationCount == 0 ? 0 : _totalAttenuation / _attenuationCount; + _reflections = _frontRightUpReflections.size() + + _frontLeftUpReflections.size() + + _backRightUpReflections.size() + + _backLeftUpReflections.size() + + _frontRightDownReflections.size() + + _frontLeftDownReflections.size() + + _backRightDownReflections.size() + + _backLeftDownReflections.size() + + _frontReflections.size() + + _backReflections.size() + + _leftReflections.size() + + _rightReflections.size() + + _upReflections.size() + + _downReflections.size(); + _diffusionPathCount = 0; - //quint64 end = usecTimestampNow(); - //qDebug() << "AudioReflector::addSamples()... elapsed=" << (end - start); + if (_reflections == 0) { + _minDelay = 0.0f; + _minAttenuation = 0.0f; + } } void AudioReflector::drawRays() { - calculateAllReflections(); - const glm::vec3 RED(1,0,0); QMutexLocker locker(&_mutex); @@ -620,8 +642,6 @@ void AudioReflector::newCalculateAllReflections() { } void AudioReflector::newDrawRays() { - newCalculateAllReflections(); - const glm::vec3 RED(1,0,0); const glm::vec3 GREEN(0,1,0); @@ -705,6 +725,19 @@ void AudioReflector::analyzePaths() { steps++; } _reflections = _audiblePoints.size(); + _diffusionPathCount = countDiffusionPaths(); +} + +int AudioReflector::countDiffusionPaths() { + int diffusionCount = 0; + + foreach(AudioPath* const& path, _audioPaths) { + // if this is NOT an original reflection then it's a diffusion path + if (path->startPoint != _origin) { + diffusionCount++; + } + } + return diffusionCount; } int AudioReflector::analyzePathsSingleStep() { diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 02e43c4b4f..931942da3f 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -70,6 +70,7 @@ public: float getMinDelayMsecs() const { return _minDelay; } float getMinAttenuation() const { return _minAttenuation; } float getDelayFromDistance(float distance); + int getDiffusionPathCount() const { return _diffusionPathCount; } void processInboundAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); void processLocalAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); @@ -119,9 +120,13 @@ private: // helper for generically calculating attenuation based on distance float getDistanceAttenuationCoefficient(float distance); + + // helper for generically calculating attenuation based on bounce count, used in old/non-diffusion mode + float getBounceAttenuationCoefficient(int bounceCount); // statistics int _reflections; + int _diffusionPathCount; int _delayCount; float _totalDelay; float _averageDelay; @@ -174,13 +179,14 @@ private: void newDrawRays(); void drawPath(AudioPath* path, const glm::vec3& originalColor); void newCalculateAllReflections(); + int countDiffusionPaths(); void injectAudiblePoint(const AudioPoint& audiblePoint, const QByteArray& samples, unsigned int sampleTime, int sampleRate); void oldEchoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); void newEchoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); // return the surface characteristics of the element we hit - SurfaceCharacteristics getSurfaceCharacteristics(OctreeElement* elementHit); + SurfaceCharacteristics getSurfaceCharacteristics(OctreeElement* elementHit = NULL); QMutex _mutex; diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index eb23d227bf..baa9aa314b 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -411,6 +411,10 @@ Menu::Menu() : addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingWithDiffusions, Qt::CTRL | Qt::SHIFT | Qt::Key_W, true); + + addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingRenderPaths, + Qt::CTRL | Qt::SHIFT | Qt::Key_R, + true); addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::LowPassFilter, Qt::CTRL | Qt::SHIFT | Qt::Key_F, diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 9a659e894d..fe68d78269 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -244,6 +244,7 @@ namespace MenuOption { const QString AudioSpatialProcessingStereoSource = "Audio Spatial Processing Stereo Source"; const QString AudioSpatialProcessingHeadOriented = "Audio Spatial Processing Head Oriented"; const QString AudioSpatialProcessingWithDiffusions = "Audio Spatial Processing With Diffusions"; + const QString AudioSpatialProcessingRenderPaths = "Audio Spatial Processing Render Paths"; const QString Avatars = "Avatars"; const QString Bandwidth = "Bandwidth Display"; const QString BandwidthDetails = "Bandwidth Details"; diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp index befa710903..83b700484c 100644 --- a/interface/src/ui/Stats.cpp +++ b/interface/src/ui/Stats.cpp @@ -513,10 +513,8 @@ void Stats::display( // add some reflection stats char reflectionsStatus[128]; - sprintf(reflectionsStatus, "Reflections: %d, Diffusion: %s, Original: %s, Ears: %s, Source: %s", + sprintf(reflectionsStatus, "Reflections: %d, Original: %s, Ears: %s, Source: %s", audioReflector->getReflections(), - (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions) - ? "yes" : "no"), (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingIncudeOriginal) ? "included" : "silent"), (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingSeparateEars) @@ -552,7 +550,9 @@ void Stats::display( bool diffusionEnabled = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions); int fanout = diffusionEnabled ? audioReflector->getDiffusionFanout() : 0; - sprintf(reflectionsStatus, "Diffusion: %s, Fanout: %d", (diffusionEnabled ? "yes" : "no"), fanout); + int diffusionPaths = diffusionEnabled ? audioReflector->getDiffusionPathCount() : 0; + sprintf(reflectionsStatus, "Diffusion: %s, Fanout: %d, Paths: %d", + (diffusionEnabled ? "yes" : "no"), fanout, diffusionPaths); verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); From 873620e60174984eb3c64ebe3bbb78923ee1491a Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Mon, 14 Apr 2014 12:27:15 -0700 Subject: [PATCH 391/595] Make sure we set the texture data even if the texture URL is invalid. --- interface/src/renderer/TextureCache.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/interface/src/renderer/TextureCache.cpp b/interface/src/renderer/TextureCache.cpp index 17146dc2bb..3f523cf4bb 100644 --- a/interface/src/renderer/TextureCache.cpp +++ b/interface/src/renderer/TextureCache.cpp @@ -244,7 +244,6 @@ NetworkTexture::NetworkTexture(const QUrl& url, bool normalMap) : if (!url.isValid()) { _loaded = true; - return; } // default to white/blue From 1aacba3b4600c3ea48ede248ba78d3f81d74dac2 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 14 Apr 2014 12:31:41 -0700 Subject: [PATCH 392/595] changes to Windows instructions for GnuTLS --- BUILD.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BUILD.md b/BUILD.md index c5a7a604b4..33e18545e0 100644 --- a/BUILD.md +++ b/BUILD.md @@ -141,9 +141,9 @@ For many of the external libraries where precompiled binaries are readily availa *NOTE: Qt does not support 64-bit builds on Windows 7, so you must use the 32-bit version of libraries for interface.exe to run. The 32-bit version of the static library is the one linked by our CMake find modules* #####GnuTLS -You can get a precompiled version of GnuTLS for Windows [here](ftp://ftp.gnutls.org/gcrypt/gnutls/w32/). +You can get a precompiled version of GnuTLS for Windows [here](http://gnutls.org/download.html). -To use GnuTLS with Visual Studio, you will need to create `libgnutls-28.lib`, the import library for Visual Studio projects. this is done using the `lib` command in the `bin` folder of your GnuTLS download. +To use GnuTLS with Visual Studio, you will need to create `libgnutls-28.lib`, the import library for Visual Studio projects. this is done using the `lib` command in the `bin` folder of your GnuTLS download. Run the following in a Visual Studio Command Prompt (found in the tools menu of Visual Studio). $GNUTLS_DIR\bin> lib /def:libgnutls-28.def From 5e42daaa5160c793811f25618390da21be685590 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 14 Apr 2014 12:32:23 -0700 Subject: [PATCH 393/595] fix predelay in the diffusion case --- examples/audioReflectorTools.js | 2 +- interface/src/AudioReflector.cpp | 20 ++++++++++++++------ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/examples/audioReflectorTools.js b/examples/audioReflectorTools.js index 99baf7260c..711f2a8e1f 100644 --- a/examples/audioReflectorTools.js +++ b/examples/audioReflectorTools.js @@ -10,7 +10,7 @@ // -var delayScale = 100.0; +var delayScale = 500.0; var fanoutScale = 10.0; var speedScale = 20; var factorScale = 5.0; diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 80eebb990d..b6143f8744 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -407,7 +407,14 @@ void AudioReflector::injectAudiblePoint(const AudioPoint& audiblePoint, float rightEarDelayMsecs = getDelayFromDistance(rightEarDistance) + audiblePoint.delay; float leftEarDelayMsecs = getDelayFromDistance(leftEarDistance) + audiblePoint.delay; - + +/* +qDebug() << "injectAudiblePoint()... "; +qDebug() << " audiblePoint.delay=" << audiblePoint.delay; +qDebug() << " rightEarDelayMsecs=" << rightEarDelayMsecs; +qDebug() << " leftEarDelayMsecs=" << leftEarDelayMsecs; +*/ + _totalDelay += rightEarDelayMsecs + leftEarDelayMsecs; _delayCount += 2; _maxDelay = std::max(_maxDelay,rightEarDelayMsecs); @@ -700,7 +707,7 @@ void AudioReflector::analyzePaths() { float initialAttenuation = 1.0f; float preDelay = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingPreDelay) ? _preDelay : 0.0f; - + addSoundSource(_origin, right, initialAttenuation, preDelay); addSoundSource(_origin, front, initialAttenuation, preDelay); addSoundSource(_origin, up, initialAttenuation, preDelay); @@ -758,7 +765,6 @@ int AudioReflector::analyzePathsSingleStep() { float currentAttenuation = path->lastAttenuation; float currentDelay = path->lastDelay; // start with our delay so far float pathDistance = path->lastDistance; - float totalDelay = path->lastDelay; // start with our delay so far if (!path->finalized) { activePaths++; @@ -784,7 +790,6 @@ int AudioReflector::analyzePathsSingleStep() { // We aren't using this... should we be???? float toListenerDistance = glm::distance(end, _listenerPosition); - float totalDistance = toListenerDistance + pathDistance; // adjust our current delay by just the delay from the most recent ray currentDelay += getDelayFromDistance(distance); @@ -801,7 +806,7 @@ int AudioReflector::analyzePathsSingleStep() { float partialDiffusionAttenuation = _diffusionFanout < 1 ? 0.0f : totalDiffusionAttenuation / _diffusionFanout; // total delay includes the bounce back to listener - totalDelay = getDelayFromDistance(totalDistance); + float totalDelay = currentDelay + getDelayFromDistance(toListenerDistance); float toListenerAttenuation = getDistanceAttenuationCoefficient(toListenerDistance); // if our resulting partial diffusion attenuation, is still above our minimum attenuation @@ -862,7 +867,10 @@ int AudioReflector::analyzePathsSingleStep() { && totalDelay < MAXIMUM_DELAY_MS) { // add this location, as the reflective attenuation as well as the total diffusion attenuation - AudioPoint point = { end, totalDelay, reflectiveAttenuation + totalDiffusionAttenuation }; + // NOTE: we add the delay to the audible point, not back to the listener. The additional delay + // and attenuation to the listener is recalculated at the point where we actually inject the + // audio so that it can be adjusted to ear position + AudioPoint point = { end, currentDelay, reflectiveAttenuation + totalDiffusionAttenuation }; _audiblePoints.push_back(point); // add this location to the path points, so we can visualize it From d3776afc93b7eed1d9b61ffd1859f2de3482ab07 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 14 Apr 2014 12:36:13 -0700 Subject: [PATCH 394/595] fix for DLL section in BUILD guide --- BUILD.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/BUILD.md b/BUILD.md index 33e18545e0..b855ed1450 100644 --- a/BUILD.md +++ b/BUILD.md @@ -140,6 +140,11 @@ For many of the external libraries where precompiled binaries are readily availa *NOTE: Qt does not support 64-bit builds on Windows 7, so you must use the 32-bit version of libraries for interface.exe to run. The 32-bit version of the static library is the one linked by our CMake find modules* +##### DLLs +As with the Qt libraries, you will need to make sure the directories containing dynamically-linked libraries is in your path. + +For example, for a dynamically linked build of freeglut, the directory to add to your path in which the DLL is found is `FREEGLUT_DIR/bin`. Where possible, you can use static builds of the external dependencies to avoid this requirement. + #####GnuTLS You can get a precompiled version of GnuTLS for Windows [here](http://gnutls.org/download.html). @@ -149,9 +154,6 @@ To use GnuTLS with Visual Studio, you will need to create `libgnutls-28.lib`, th This will create `libgnutls-28.lib` in the `bin` folder. Copy that file to the `lib` sub-folder of your GnuTLS folder, and the Cmake FindGnuTLS module in this repo will find it during the Cmake run. -#### DLLs -As with the Qt libraries, you will need to make sure the directory containing dynamically-linked libraries is in your path. For example, for a dynamically linked build of freeglut, the directory to add to your path in which the DLL is found is `FREEGLUT_DIR/bin`. Where possible, you can use static builds of the external dependencies to avoid this requirement. - ####Building in Visual Studio Follow the same build steps from the CMake section, but pass a different generator to CMake. From 55172c6f437a23506004d802cf4cd9184a8a1a15 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 14 Apr 2014 12:39:43 -0700 Subject: [PATCH 395/595] more cleanup to BUILD guide for windows --- BUILD.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/BUILD.md b/BUILD.md index b855ed1450..487bcb0eb1 100644 --- a/BUILD.md +++ b/BUILD.md @@ -108,11 +108,12 @@ Once Qt is installed, you need to manually configure the following: NOTE: zLib should configure itself correctly on install. However, sometimes zLib doesn't properly detect system components and fails to configure itself correctly. When it fails, it will not correctly set the #if HAVE_UNISTD_H at line 287 of zconf.h to #if 0... if it fails, you're build will have errors in the voxels target. You can correct this by setting the #if to 0 instead of 1, since Windows does not have unistd.h. ####External Libraries -We don't currently have a Windows installer, so before running Interface, you will need to ensure that all required resources are loadable. -CMake will need to know where the headers and libraries for required external dependencies are. If you installed ZLIB using the installer, the FindZLIB cmake module will be able to find it. This isn't the case for the others. +CMake will need to know where the headers and libraries for required external dependencies are. -The recommended route for CMake to find external dependencies is to place all of the dependencies in one folder and set one ENV variable - HIFI_LIB_DIR. That ENV variable should point to a directory with the following structure: +If you installed zLib using the installer, the Cmake find module for zLib should locate it on your system. + +The recommended route for CMake to find the other external dependencies is to place all of the dependencies in one folder and set one ENV variable - HIFI_LIB_DIR. That ENV variable should point to a directory with the following structure: root_lib_dir -> glm @@ -134,10 +135,10 @@ The recommended route for CMake to find external dependencies is to place all of -> include -> lib -*NOTE: Be careful with glm. For the folder other libraries would normally call 'include', the folder containing the headers, glm opts to use 'glm'. You will have a glm folder nested inside the top-level glm folder.* - For many of the external libraries where precompiled binaries are readily available you should be able to simply copy the extracted folder that you get from the download links provided at the top of the guide. Otherwise you may need to build from source and install the built product to this directory. The `root_lib_dir` in the above example can be wherever you choose on your system - as long as the environment variable HIFI_LIB_DIR is set to it. +*NOTE: Be careful with glm. For the folder other libraries would normally call 'include', the folder containing the headers, glm opts to use 'glm'. You will have a glm folder nested inside the top-level glm folder.* + *NOTE: Qt does not support 64-bit builds on Windows 7, so you must use the 32-bit version of libraries for interface.exe to run. The 32-bit version of the static library is the one linked by our CMake find modules* ##### DLLs From 8a6da915aeb361610e26e78a300ffa35770f26d4 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 14 Apr 2014 13:25:01 -0700 Subject: [PATCH 396/595] fix predelay in the diffusion case --- interface/src/AudioReflector.cpp | 105 ++++++++++++++++++++----------- interface/src/AudioReflector.h | 2 + interface/src/Menu.cpp | 8 ++- interface/src/Menu.h | 1 + 4 files changed, 76 insertions(+), 40 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index b6143f8744..31ceaa2594 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -32,7 +32,8 @@ AudioReflector::AudioReflector(QObject* parent) : _distanceAttenuationScalingFactor(DEFAULT_DISTANCE_SCALING_FACTOR), _diffusionFanout(DEFAULT_DIFFUSION_FANOUT), _absorptionRatio(DEFAULT_ABSORPTION_RATIO), - _diffusionRatio(DEFAULT_DIFFUSION_RATIO) + _diffusionRatio(DEFAULT_DIFFUSION_RATIO), + _withDiffusion(false) { reset(); } @@ -110,28 +111,30 @@ float AudioReflector::getBounceAttenuationCoefficient(int bounceCount) { return material.reflectiveRatio * bounceCount; } -glm::vec3 getFaceNormal(BoxFace face) { - glm::vec3 slightlyRandomFaceNormal; +glm::vec3 AudioReflector::getFaceNormal(BoxFace face) { + bool wantSlightRandomness = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingSlightlyRandomSurfaces); - float surfaceRandomness = randFloatInRange(0.99f,1.0f); - float surfaceRemainder = (1.0f - surfaceRandomness)/2.0f; - float altRemainderSignA = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; - float altRemainderSignB = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; + glm::vec3 faceNormal; + + float normalLength = wantSlightRandomness ? randFloatInRange(0.99f,1.0f) : 1.0f; + float remainder = (1.0f - normalLength)/2.0f; + float remainderSignA = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; + float remainderSignB = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; if (face == MIN_X_FACE) { - slightlyRandomFaceNormal = glm::vec3(-surfaceRandomness, surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB); + faceNormal = glm::vec3(-normalLength, remainder * remainderSignA, remainder * remainderSignB); } else if (face == MAX_X_FACE) { - slightlyRandomFaceNormal = glm::vec3(surfaceRandomness, surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB); + faceNormal = glm::vec3(normalLength, remainder * remainderSignA, remainder * remainderSignB); } else if (face == MIN_Y_FACE) { - slightlyRandomFaceNormal = glm::vec3(surfaceRemainder * altRemainderSignA, -surfaceRandomness, surfaceRemainder * altRemainderSignB); + faceNormal = glm::vec3(remainder * remainderSignA, -normalLength, remainder * remainderSignB); } else if (face == MAX_Y_FACE) { - slightlyRandomFaceNormal = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRandomness, surfaceRemainder * altRemainderSignB); + faceNormal = glm::vec3(remainder * remainderSignA, normalLength, remainder * remainderSignB); } else if (face == MIN_Z_FACE) { - slightlyRandomFaceNormal = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB, -surfaceRandomness); + faceNormal = glm::vec3(remainder * remainderSignA, remainder * remainderSignB, -normalLength); } else if (face == MAX_Z_FACE) { - slightlyRandomFaceNormal = glm::vec3(surfaceRemainder * altRemainderSignA, surfaceRemainder * altRemainderSignB, surfaceRandomness); + faceNormal = glm::vec3(remainder * remainderSignA, remainder * remainderSignB, normalLength); } - return slightlyRandomFaceNormal; + return faceNormal; } void AudioReflector::reset() { @@ -166,20 +169,30 @@ void AudioReflector::calculateAllReflections() { // TODO: what about case where new voxels are added in front of us??? bool wantHeadOrientation = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingHeadOriented); glm::quat orientation = wantHeadOrientation ? _myAvatar->getHead()->getFinalOrientation() : _myAvatar->getOrientation(); - + glm::vec3 origin = _myAvatar->getHead()->getPosition(); + glm::vec3 listenerPosition = _myAvatar->getHead()->getPosition(); + + bool withDiffusion = false; // this is the non-diffusion mode. + bool shouldRecalc = _reflections == 0 - || !isSimilarPosition(_myAvatar->getHead()->getPosition(), _origin) - || !isSimilarOrientation(orientation, _orientation); + || !isSimilarPosition(origin, _origin) + || !isSimilarOrientation(orientation, _orientation) + || !isSimilarPosition(listenerPosition, _listenerPosition) + || (withDiffusion != _withDiffusion); if (shouldRecalc) { + +qDebug() << "RECALC...... !!!!!!!!!!!!!!!!!!!!!!!!!!!!"; + QMutexLocker locker(&_mutex); quint64 start = usecTimestampNow(); - _origin = _myAvatar->getHead()->getPosition(); - glm::vec3 averageEarPosition = _myAvatar->getHead()->getPosition(); - _listenerPosition = averageEarPosition; + _origin = origin; + _listenerPosition = listenerPosition; _orientation = orientation; + _withDiffusion = withDiffusion; + glm::vec3 right = glm::normalize(_orientation * IDENTITY_RIGHT); glm::vec3 up = glm::normalize(_orientation * IDENTITY_UP); glm::vec3 front = glm::normalize(_orientation * IDENTITY_FRONT); @@ -195,20 +208,20 @@ void AudioReflector::calculateAllReflections() { glm::vec3 backRightDown = glm::normalize(back + right + down); glm::vec3 backLeftDown = glm::normalize(back + left + down); - _frontRightUpReflections = calculateReflections(averageEarPosition, _origin, frontRightUp); - _frontLeftUpReflections = calculateReflections(averageEarPosition, _origin, frontLeftUp); - _backRightUpReflections = calculateReflections(averageEarPosition, _origin, backRightUp); - _backLeftUpReflections = calculateReflections(averageEarPosition, _origin, backLeftUp); - _frontRightDownReflections = calculateReflections(averageEarPosition, _origin, frontRightDown); - _frontLeftDownReflections = calculateReflections(averageEarPosition, _origin, frontLeftDown); - _backRightDownReflections = calculateReflections(averageEarPosition, _origin, backRightDown); - _backLeftDownReflections = calculateReflections(averageEarPosition, _origin, backLeftDown); - _frontReflections = calculateReflections(averageEarPosition, _origin, front); - _backReflections = calculateReflections(averageEarPosition, _origin, back); - _leftReflections = calculateReflections(averageEarPosition, _origin, left); - _rightReflections = calculateReflections(averageEarPosition, _origin, right); - _upReflections = calculateReflections(averageEarPosition, _origin, up); - _downReflections = calculateReflections(averageEarPosition, _origin, down); + _frontRightUpReflections = calculateReflections(listenerPosition, _origin, frontRightUp); + _frontLeftUpReflections = calculateReflections(listenerPosition, _origin, frontLeftUp); + _backRightUpReflections = calculateReflections(listenerPosition, _origin, backRightUp); + _backLeftUpReflections = calculateReflections(listenerPosition, _origin, backLeftUp); + _frontRightDownReflections = calculateReflections(listenerPosition, _origin, frontRightDown); + _frontLeftDownReflections = calculateReflections(listenerPosition, _origin, frontLeftDown); + _backRightDownReflections = calculateReflections(listenerPosition, _origin, backRightDown); + _backLeftDownReflections = calculateReflections(listenerPosition, _origin, backLeftDown); + _frontReflections = calculateReflections(listenerPosition, _origin, front); + _backReflections = calculateReflections(listenerPosition, _origin, back); + _leftReflections = calculateReflections(listenerPosition, _origin, left); + _rightReflections = calculateReflections(listenerPosition, _origin, right); + _upReflections = calculateReflections(listenerPosition, _origin, up); + _downReflections = calculateReflections(listenerPosition, _origin, down); quint64 end = usecTimestampNow(); @@ -237,7 +250,7 @@ QVector AudioReflector::calculateReflections(const glm::vec3& earPosi int bounceCount = 1; while (currentAttenuation > MINIMUM_ATTENUATION_TO_REFLECT && totalDelay < MAXIMUM_DELAY_MS && bounceCount < ABSOLUTE_MAXIMUM_BOUNCE_COUNT) { - if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { + if (_voxels->findRayIntersection(start, direction, elementHit, distance, face, Octree::Lock)) { glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); totalDistance += glm::distance(start, end); @@ -627,18 +640,26 @@ void AudioReflector::newCalculateAllReflections() { glm::quat orientation = wantHeadOrientation ? _myAvatar->getHead()->getFinalOrientation() : _myAvatar->getOrientation(); glm::vec3 origin = _myAvatar->getHead()->getPosition(); glm::vec3 listenerPosition = _myAvatar->getHead()->getPosition(); + + bool withDiffusion = true; // this is the diffusion mode. - bool shouldRecalc = _audiblePoints.size() == 0 + // _audiblePoints.size() == 0 ?? + bool shouldRecalc = _reflections == 0 || !isSimilarPosition(origin, _origin) || !isSimilarOrientation(orientation, _orientation) - || !isSimilarPosition(listenerPosition, _listenerPosition); + || !isSimilarPosition(listenerPosition, _listenerPosition) + || (withDiffusion != _withDiffusion); if (shouldRecalc) { + +qDebug() << "RECALC...... !!!!!!!!!!!!!!!!!!!!!!!!!!!!"; + QMutexLocker locker(&_mutex); quint64 start = usecTimestampNow(); _origin = origin; _orientation = orientation; _listenerPosition = listenerPosition; + _withDiffusion = withDiffusion; analyzePaths(); // actually does the work quint64 end = usecTimestampNow(); const bool wantDebugging = false; @@ -774,7 +795,7 @@ int AudioReflector::analyzePathsSingleStep() { if (wantExtraDebuggging && isDiffusion) { qDebug() << "diffusion bounceCount too high!"; } - } else if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { + } else if (_voxels->findRayIntersection(start, direction, elementHit, distance, face, Octree::Lock)) { glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); pathDistance += glm::distance(start, end); @@ -893,12 +914,20 @@ int AudioReflector::analyzePathsSingleStep() { if (wantExtraDebuggging && isDiffusion) { qDebug() << "diffusion too quiet!"; } + + if (((reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation) <= MINIMUM_ATTENUATION_TO_REFLECT) { + qDebug() << "too quiet!"; + } + if (totalDelay >= MAXIMUM_DELAY_MS) { + qDebug() << "too much delay!"; + } } } else { path->finalized = true; // if it doesn't intersect, then it is finished if (wantExtraDebuggging && isDiffusion) { qDebug() << "diffusion doesn't intersect!"; } + qDebug() << "doesn't intersect!"; } } } diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 931942da3f..6cbb4b433e 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -180,6 +180,7 @@ private: void drawPath(AudioPath* path, const glm::vec3& originalColor); void newCalculateAllReflections(); int countDiffusionPaths(); + glm::vec3 getFaceNormal(BoxFace face); void injectAudiblePoint(const AudioPoint& audiblePoint, const QByteArray& samples, unsigned int sampleTime, int sampleRate); void oldEchoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); @@ -202,6 +203,7 @@ private: float _diffusionRatio; float _reflectiveRatio; + bool _withDiffusion; }; diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index baa9aa314b..a1a74bc6ce 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -359,7 +359,7 @@ Menu::Menu() : addCheckableActionToQMenuAndActionHash(renderDebugMenu, MenuOption::ShowCulledSharedFaces, - Qt::CTRL | Qt::SHIFT | Qt::Key_X, + 0, false, appInstance->getVoxels(), SLOT(showCulledSharedFaces())); @@ -415,7 +415,11 @@ Menu::Menu() : addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingRenderPaths, Qt::CTRL | Qt::SHIFT | Qt::Key_R, true); - + + addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingSlightlyRandomSurfaces, + Qt::CTRL | Qt::SHIFT | Qt::Key_X, + true); + addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::LowPassFilter, Qt::CTRL | Qt::SHIFT | Qt::Key_F, false); diff --git a/interface/src/Menu.h b/interface/src/Menu.h index fe68d78269..578d4e8dc6 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -245,6 +245,7 @@ namespace MenuOption { const QString AudioSpatialProcessingHeadOriented = "Audio Spatial Processing Head Oriented"; const QString AudioSpatialProcessingWithDiffusions = "Audio Spatial Processing With Diffusions"; const QString AudioSpatialProcessingRenderPaths = "Audio Spatial Processing Render Paths"; + const QString AudioSpatialProcessingSlightlyRandomSurfaces = "Audio Spatial Processing Slightly Random Surfaces"; const QString Avatars = "Avatars"; const QString Bandwidth = "Bandwidth Display"; const QString BandwidthDetails = "Bandwidth Details"; From 06235decae206efa7caffa868b8ee18babc9c454 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Mon, 14 Apr 2014 14:10:12 -0700 Subject: [PATCH 397/595] Move ChatWindow isAtBottom and moveToBottom outside of HAVE_QXMPP --- interface/src/ui/ChatWindow.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/ui/ChatWindow.cpp b/interface/src/ui/ChatWindow.cpp index 97fa81afc5..635f1f3d10 100644 --- a/interface/src/ui/ChatWindow.cpp +++ b/interface/src/ui/ChatWindow.cpp @@ -311,6 +311,8 @@ void ChatWindow::messageReceived(const QXmppMessage& message) { } } +#endif + bool ChatWindow::isAtBottom() { QScrollBar* verticalScrollBar = ui->messagesScrollArea->verticalScrollBar(); return verticalScrollBar->sliderPosition() == verticalScrollBar->maximum(); @@ -322,8 +324,6 @@ void ChatWindow::scrollToBottom() { verticalScrollBar->setSliderPosition(verticalScrollBar->maximum()); } -#endif - void ChatWindow::togglePinned() { QMainWindow* mainWindow = Application::getInstance()->getWindow(); mainWindow->removeDockWidget(this); From af47510b051f4c73e2d56ce91b4a66d8bc5e6b9e Mon Sep 17 00:00:00 2001 From: Thijs Wenker Date: Tue, 15 Apr 2014 00:30:01 +0200 Subject: [PATCH 398/595] Initial script editor widget / icons made by MaximillianMerlin ty --- interface/resources/icons/load-script.svg | 125 ++++ interface/resources/icons/new-script.svg | 129 +++++ interface/resources/icons/save-script.svg | 674 ++++++++++++++++++++++ interface/src/Application.h | 1 + interface/src/Menu.cpp | 8 + interface/src/Menu.h | 4 + interface/src/ScriptHighlighting.cpp | 18 + interface/src/ScriptHighlighting.h | 25 + interface/src/ui/ScriptEditorWidget.cpp | 39 ++ interface/src/ui/ScriptEditorWidget.h | 34 ++ interface/src/ui/ScriptEditorWindow.cpp | 62 ++ interface/src/ui/ScriptEditorWindow.h | 39 ++ interface/ui/ScriptEditorWidget.ui | 89 +++ interface/ui/ScriptEditorWindow.ui | 290 ++++++++++ 14 files changed, 1537 insertions(+) create mode 100644 interface/resources/icons/load-script.svg create mode 100644 interface/resources/icons/new-script.svg create mode 100644 interface/resources/icons/save-script.svg create mode 100644 interface/src/ScriptHighlighting.cpp create mode 100644 interface/src/ScriptHighlighting.h create mode 100644 interface/src/ui/ScriptEditorWidget.cpp create mode 100644 interface/src/ui/ScriptEditorWidget.h create mode 100644 interface/src/ui/ScriptEditorWindow.cpp create mode 100644 interface/src/ui/ScriptEditorWindow.h create mode 100644 interface/ui/ScriptEditorWidget.ui create mode 100644 interface/ui/ScriptEditorWindow.ui diff --git a/interface/resources/icons/load-script.svg b/interface/resources/icons/load-script.svg new file mode 100644 index 0000000000..21be61c321 --- /dev/null +++ b/interface/resources/icons/load-script.svg @@ -0,0 +1,125 @@ + + + + + + + + + + image/svg+xml + + + + + T.Hofmeister + + + + + + + + + + + + + + + + + + + + + + diff --git a/interface/resources/icons/new-script.svg b/interface/resources/icons/new-script.svg new file mode 100644 index 0000000000..f68fcfa967 --- /dev/null +++ b/interface/resources/icons/new-script.svg @@ -0,0 +1,129 @@ + + + + + + + + + + image/svg+xml + + + + + T.Hofmeister + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/interface/resources/icons/save-script.svg b/interface/resources/icons/save-script.svg new file mode 100644 index 0000000000..04d41b8302 --- /dev/null +++ b/interface/resources/icons/save-script.svg @@ -0,0 +1,674 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + T.Hofmeister + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/interface/src/Application.h b/interface/src/Application.h index 6a14788caa..761b24bb31 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -244,6 +244,7 @@ public: void skipVersion(QString latestVersion); QStringList getRunningScripts() { return _scriptEnginesHash.keys(); } + ScriptEngine* getScriptEngine(QString scriptHash) { return _scriptEnginesHash.contains(scriptHash) ? _scriptEnginesHash[scriptHash] : NULL; } signals: diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 8ad55dec5b..87ab75cf3f 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -192,6 +192,7 @@ Menu::Menu() : QMenu* toolsMenu = addMenu("Tools"); addActionToQMenuAndActionHash(toolsMenu, MenuOption::MetavoxelEditor, 0, this, SLOT(showMetavoxelEditor())); + addActionToQMenuAndActionHash(toolsMenu, MenuOption::ScriptEditor, 0, this, SLOT(showScriptEditor())); #ifdef HAVE_QXMPP _chatAction = addActionToQMenuAndActionHash(toolsMenu, @@ -1058,6 +1059,13 @@ void Menu::showMetavoxelEditor() { _MetavoxelEditor->raise(); } +void Menu::showScriptEditor() { + if(!_ScriptEditor) { + _ScriptEditor = new ScriptEditorWindow(); + } + _ScriptEditor->raise(); +} + void Menu::showChat() { QMainWindow* mainWindow = Application::getInstance()->getWindow(); if (!_chatWindow) { diff --git a/interface/src/Menu.h b/interface/src/Menu.h index e827e43014..14ebbf356d 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -24,6 +24,7 @@ #include "location/LocationManager.h" #include "ui/PreferencesDialog.h" #include "ui/ChatWindow.h" +#include "ui/ScriptEditorWindow.h" const float ADJUST_LOD_DOWN_FPS = 40.0; const float ADJUST_LOD_UP_FPS = 55.0; @@ -161,6 +162,7 @@ private slots: void cycleFrustumRenderMode(); void runTests(); void showMetavoxelEditor(); + void showScriptEditor(); void showChat(); void toggleChat(); void audioMuteToggled(); @@ -212,6 +214,7 @@ private: FrustumDrawMode _frustumDrawMode; ViewFrustumOffset _viewFrustumOffset; QPointer _MetavoxelEditor; + QPointer _ScriptEditor; QPointer _chatWindow; OctreeStatsDialog* _octreeStatsDialog; LodToolsDialog* _lodToolsDialog; @@ -308,6 +311,7 @@ namespace MenuOption { const QString ResetAvatarSize = "Reset Avatar Size"; const QString RunningScripts = "Running Scripts"; const QString RunTimingTests = "Run Timing Tests"; + const QString ScriptEditor = "Script Editor..."; const QString SettingsExport = "Export Settings"; const QString SettingsImport = "Import Settings"; const QString Shadows = "Shadows"; diff --git a/interface/src/ScriptHighlighting.cpp b/interface/src/ScriptHighlighting.cpp new file mode 100644 index 0000000000..15505ac49a --- /dev/null +++ b/interface/src/ScriptHighlighting.cpp @@ -0,0 +1,18 @@ +// +// ScriptHighlighting.cpp +// interface/src +// +// Created by Thijs Wenker on 4/15/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "ScriptHighlighting.h" + +ScriptHighlighting::ScriptHighlighting(QObject* parent) : + QSyntaxHighlighter(parent) +{ + +} \ No newline at end of file diff --git a/interface/src/ScriptHighlighting.h b/interface/src/ScriptHighlighting.h new file mode 100644 index 0000000000..f2bd97930e --- /dev/null +++ b/interface/src/ScriptHighlighting.h @@ -0,0 +1,25 @@ +// +// ScriptHighlighting.h +// interface/src +// +// Created by Thijs Wenker on 4/15/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_ScriptHighlighting_h +#define hifi_ScriptHighlighting_h + +#include + +class ScriptHighlighting : public QSyntaxHighlighter { + Q_OBJECT + +public: + ScriptHighlighting(QObject* parent = 0); + +}; + +#endif // hifi_ScriptHighlighting_h diff --git a/interface/src/ui/ScriptEditorWidget.cpp b/interface/src/ui/ScriptEditorWidget.cpp new file mode 100644 index 0000000000..4adf01a28a --- /dev/null +++ b/interface/src/ui/ScriptEditorWidget.cpp @@ -0,0 +1,39 @@ +// +// ScriptEditorWidget.cpp +// interface/src/ui +// +// Created by Thijs Wenker on 4/14/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Application.h" +#include "ui_scriptEditorWidget.h" + +#include "ScriptEditorWidget.h" + +ScriptEditorWidget::ScriptEditorWidget() : + ui(new Ui::ScriptEditorWidget) +{ + ui->setupUi(this); + + // remove the title bar (see the Qt docs on setTitleBarWidget) + setTitleBarWidget(new QWidget()); + //QSyntaxHighlighter* highlighter = new QSyntaxHighlighter(); +} + +ScriptEditorWidget::~ScriptEditorWidget() { + delete ui; +} \ No newline at end of file diff --git a/interface/src/ui/ScriptEditorWidget.h b/interface/src/ui/ScriptEditorWidget.h new file mode 100644 index 0000000000..931ec105c9 --- /dev/null +++ b/interface/src/ui/ScriptEditorWidget.h @@ -0,0 +1,34 @@ +// +// ScriptEditorWidget.h +// interface/src/ui +// +// Created by Thijs Wenker on 4/14/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_ScriptEditorWidget_h +#define hifi_ScriptEditorWidget_h + +#include + +#include + +namespace Ui { +class ScriptEditorWidget; +} + +class ScriptEditorWidget : public QDockWidget { + Q_OBJECT + +public: + ScriptEditorWidget(); + ~ScriptEditorWidget(); + +private: + Ui::ScriptEditorWidget* ui; +}; + +#endif // hifi_ScriptEditorWidget_h diff --git a/interface/src/ui/ScriptEditorWindow.cpp b/interface/src/ui/ScriptEditorWindow.cpp new file mode 100644 index 0000000000..38fa26622a --- /dev/null +++ b/interface/src/ui/ScriptEditorWindow.cpp @@ -0,0 +1,62 @@ +// +// ScriptEditorWindow.cpp +// interface/src/ui +// +// Created by Thijs Wenker on 4/14/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Application.h" +#include "FlowLayout.h" +#include "ui_scriptEditorWindow.h" +#include "ScriptEditorWidget.h" + +#include "ScriptEditorWindow.h" + +ScriptEditorWindow::ScriptEditorWindow() : + ui(new Ui::ScriptEditorWindow) +{ + ui->setupUi(this); + show(); +} + +ScriptEditorWindow::~ScriptEditorWindow() { + delete ui; +} + +void ScriptEditorWindow::loadScriptClicked(){ + +} + +void ScriptEditorWindow::newScriptClicked(){ + addScriptEditorWidget(QString("new Script")); +} + +void ScriptEditorWindow::toggleRunScriptClicked(){ + +} + +void ScriptEditorWindow::saveScriptClicked(){ + +} + +void ScriptEditorWindow::addScriptEditorWidget(QString title){ + ScriptEditorWidget* newScriptEditorWidget = new ScriptEditorWidget();//ScriptEditorWidget(); + ui->tabWidget->addTab(newScriptEditorWidget, title); + ui->tabWidget->setCurrentWidget(newScriptEditorWidget); + newScriptEditorWidget->setUpdatesEnabled(true); + newScriptEditorWidget->adjustSize(); +} \ No newline at end of file diff --git a/interface/src/ui/ScriptEditorWindow.h b/interface/src/ui/ScriptEditorWindow.h new file mode 100644 index 0000000000..718826cf9d --- /dev/null +++ b/interface/src/ui/ScriptEditorWindow.h @@ -0,0 +1,39 @@ +// +// ScriptEditorWindow.h +// interface/src/ui +// +// Created by Thijs Wenker on 4/14/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_ScriptEditorWindow_h +#define hifi_ScriptEditorWindow_h + +#include + +namespace Ui { +class ScriptEditorWindow; +} + +class ScriptEditorWindow : public QWidget { + Q_OBJECT + +public: + ScriptEditorWindow(); + ~ScriptEditorWindow(); + +private: + Ui::ScriptEditorWindow* ui; + void addScriptEditorWidget(QString title); + +private slots: + void loadScriptClicked(); + void newScriptClicked(); + void toggleRunScriptClicked(); + void saveScriptClicked(); +}; + +#endif // hifi_ScriptEditorWindow_h diff --git a/interface/ui/ScriptEditorWidget.ui b/interface/ui/ScriptEditorWidget.ui new file mode 100644 index 0000000000..82398d587c --- /dev/null +++ b/interface/ui/ScriptEditorWidget.ui @@ -0,0 +1,89 @@ + + + ScriptEditorWidget + + + + 0 + 0 + 702 + 543 + + + + + 0 + 0 + + + + + 400 + 238 + + + + font-family: Helvetica, Arial, sans-serif; + + + QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable + + + Qt::NoDockWidgetArea + + + Edit Script + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + Courier + 9 + 50 + false + false + + + + font: 9pt "Courier"; + + + + + + + Debug Log: + + + + + + + font: 8pt "Courier"; + + + + + + + + + diff --git a/interface/ui/ScriptEditorWindow.ui b/interface/ui/ScriptEditorWindow.ui new file mode 100644 index 0000000000..a612b2b1c9 --- /dev/null +++ b/interface/ui/ScriptEditorWindow.ui @@ -0,0 +1,290 @@ + + + ScriptEditorWindow + + + Qt::WindowModal + + + + 0 + 0 + 474 + 638 + + + + + 400 + 250 + + + + Script editor [] + + + font-family: Helvetica, Arial, sans-serif; + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 3 + + + QLayout::SetNoConstraint + + + 0 + + + 0 + + + + + New Script + + + New + + + + ../resources/icons/new-script.svg + ../resources/images/pinned.svg../resources/icons/new-script.svg + + + + 32 + 32 + + + + + + + + + 30 + 0 + + + + + 25 + 0 + + + + Load Script + + + Load + + + + ../resources/icons/load-script.svg../resources/icons/load-script.svg + + + + 32 + 32 + + + + false + + + QToolButton::MenuButtonPopup + + + Qt::ToolButtonIconOnly + + + + + + + + 0 + 2 + + + + Qt::NoFocus + + + Qt::NoContextMenu + + + Save Script + + + Save + + + + ../resources/icons/save-script.svg../resources/icons/save-script.svg + + + + 32 + 32 + + + + 316 + + + + + + + Toggle Run Script + + + Run/Stop + + + + ../resources/images/plus.svg../resources/images/plus.svg + + + + 32 + 32 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + true + + + + 250 + 80 + + + + QTabWidget::West + + + QTabWidget::Triangular + + + -1 + + + Qt::ElideNone + + + true + + + true + + + + + + + + + saveButton + clicked() + ScriptEditorWindow + saveScriptClicked() + + + 236 + 10 + + + 199 + 264 + + + + + toggleRunButton + clicked() + ScriptEditorWindow + toggleRunScriptClicked() + + + 330 + 10 + + + 199 + 264 + + + + + newButton + clicked() + ScriptEditorWindow + newScriptClicked() + + + 58 + 10 + + + 199 + 264 + + + + + loadButton + clicked() + ScriptEditorWindow + loadScriptClicked() + + + 85 + 10 + + + 199 + 264 + + + + + From 588231cebfa22cd4a9685be901568b8d391b9882 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 14 Apr 2014 15:36:20 -0700 Subject: [PATCH 399/595] reconcile old and new implmentations so that 0 fan out produces same results --- interface/src/AudioReflector.cpp | 78 +++++++++++++++++++++++++------- interface/src/AudioReflector.h | 10 ++-- 2 files changed, 67 insertions(+), 21 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 31ceaa2594..fdafa3d762 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -108,7 +108,7 @@ float AudioReflector::getBounceAttenuationCoefficient(int bounceCount) { // now we know the current attenuation for the "perfect" reflection case, but we now incorporate // our surface materials to determine how much of this ray is absorbed, reflected, and diffused SurfaceCharacteristics material = getSurfaceCharacteristics(); - return material.reflectiveRatio * bounceCount; + return powf(material.reflectiveRatio, bounceCount); } glm::vec3 AudioReflector::getFaceNormal(BoxFace face) { @@ -183,6 +183,21 @@ void AudioReflector::calculateAllReflections() { if (shouldRecalc) { qDebug() << "RECALC...... !!!!!!!!!!!!!!!!!!!!!!!!!!!!"; +if (_reflections == 0) { + qDebug() << "RECALC...... No reflections!!!!!!!!!!!!!!!!!!!!!!!!!!!!"; +} +if (!isSimilarPosition(origin, _origin)) { + qDebug() << "RECALC...... origin changed...!!!!!!!!!!!!!!!!!!!!!!!!!!!!"; +} +if (!isSimilarOrientation(orientation, _orientation)) { + qDebug() << "RECALC...... orientation changed...!!!!!!!!!!!!!!!!!!!!!!!!!!!!"; +} +if (!isSimilarPosition(listenerPosition, _listenerPosition)) { + qDebug() << "RECALC...... listenerPosition changed...!!!!!!!!!!!!!!!!!!!!!!!!!!!!"; +} +if (withDiffusion != _withDiffusion) { + qDebug() << "RECALC...... withDiffusion changed...!!!!!!!!!!!!!!!!!!!!!!!!!!!!"; +} QMutexLocker locker(&_mutex); @@ -208,6 +223,7 @@ qDebug() << "RECALC...... !!!!!!!!!!!!!!!!!!!!!!!!!!!!"; glm::vec3 backRightDown = glm::normalize(back + right + down); glm::vec3 backLeftDown = glm::normalize(back + left + down); + _rightReflections = calculateReflections(listenerPosition, _origin, right); _frontRightUpReflections = calculateReflections(listenerPosition, _origin, frontRightUp); _frontLeftUpReflections = calculateReflections(listenerPosition, _origin, frontLeftUp); _backRightUpReflections = calculateReflections(listenerPosition, _origin, backRightUp); @@ -219,7 +235,6 @@ qDebug() << "RECALC...... !!!!!!!!!!!!!!!!!!!!!!!!!!!!"; _frontReflections = calculateReflections(listenerPosition, _origin, front); _backReflections = calculateReflections(listenerPosition, _origin, back); _leftReflections = calculateReflections(listenerPosition, _origin, left); - _rightReflections = calculateReflections(listenerPosition, _origin, right); _upReflections = calculateReflections(listenerPosition, _origin, up); _downReflections = calculateReflections(listenerPosition, _origin, down); @@ -352,6 +367,14 @@ void AudioReflector::echoReflections(const glm::vec3& origin, const QVector modelIDs; @@ -1277,6 +1336,17 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) appendModelIDs(parentMap.value(topID), childMap, models, remainingModels, modelIDs); } + // figure the number of animation frames from the curves + int frameCount = 0; + foreach (const AnimationCurve& curve, animationCurves) { + frameCount = qMax(frameCount, curve.values.size()); + } + for (int i = 0; i < frameCount; i++) { + FBXAnimationFrame frame; + frame.rotations.resize(modelIDs.size()); + geometry.animationFrames.append(frame); + } + // convert the models to joints QVariantList freeJoints = mapping.values("freeJoint"); foreach (const QString& modelID, modelIDs) { @@ -1286,7 +1356,8 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) joint.parentIndex = model.parentIndex; // get the indices of all ancestors starting with the first free one (if any) - joint.freeLineage.append(geometry.joints.size()); + int jointIndex = geometry.joints.size(); + joint.freeLineage.append(jointIndex); int lastFreeIndex = joint.isFree ? 0 : -1; for (int index = joint.parentIndex; index != -1; index = geometry.joints.at(index).parentIndex) { if (geometry.joints.at(index).isFree) { @@ -1325,6 +1396,18 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) joint.shapeType = Shape::UNKNOWN_SHAPE; geometry.joints.append(joint); geometry.jointIndices.insert(model.name, geometry.joints.size()); + + QString rotationID = localRotations.value(modelID); + AnimationCurve xCurve = animationCurves.value(xComponents.value(rotationID)); + AnimationCurve yCurve = animationCurves.value(yComponents.value(rotationID)); + AnimationCurve zCurve = animationCurves.value(zComponents.value(rotationID)); + glm::vec3 defaultValues = glm::degrees(safeEulerAngles(joint.rotation)); + for (int i = 0; i < frameCount; i++) { + geometry.animationFrames[i].rotations[jointIndex] = glm::quat(glm::radians(glm::vec3( + xCurve.values.isEmpty() ? defaultValues.x : xCurve.values.at(i % xCurve.values.size()), + yCurve.values.isEmpty() ? defaultValues.y : yCurve.values.at(i % yCurve.values.size()), + zCurve.values.isEmpty() ? defaultValues.z : zCurve.values.at(i % zCurve.values.size())))); + } } // for each joint we allocate a JointShapeInfo in which we'll store collision shape info QVector jointShapeInfos; diff --git a/interface/src/renderer/FBXReader.h b/interface/src/renderer/FBXReader.h index 73c305e2eb..8d45c2ae23 100644 --- a/interface/src/renderer/FBXReader.h +++ b/interface/src/renderer/FBXReader.h @@ -139,6 +139,13 @@ public: QVector blendshapes; }; +/// A single animation frame extracted from an FBX document. +class FBXAnimationFrame { +public: + + QVector rotations; +}; + /// An attachment to an FBX document. class FBXAttachment { public: @@ -183,6 +190,8 @@ public: Extents bindExtents; Extents meshExtents; + QVector animationFrames; + QVector attachments; int getJointIndex(const QString& name) const { return jointIndices.value(name) - 1; } From 6639fc737ad1ca81c85ff602a32eca2c4b724afe Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 14 Apr 2014 16:45:55 -0700 Subject: [PATCH 401/595] include diffusion ratio in point attenuation --- interface/src/AudioReflector.cpp | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index fdafa3d762..fe1c26950a 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -917,7 +917,7 @@ int AudioReflector::analyzePathsSingleStep() { // we used to use... ((reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation) > MINIMUM_ATTENUATION_TO_REFLECT - if ((reflectiveAttenuation * toListenerAttenuation) > MINIMUM_ATTENUATION_TO_REFLECT + if (((reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation) > MINIMUM_ATTENUATION_TO_REFLECT && totalDelay < MAXIMUM_DELAY_MS) { // add this location, as the reflective attenuation as well as the total diffusion attenuation @@ -925,7 +925,7 @@ int AudioReflector::analyzePathsSingleStep() { // and attenuation to the listener is recalculated at the point where we actually inject the // audio so that it can be adjusted to ear position AudioPoint point = { end, currentDelay, - reflectiveAttenuation, + (reflectiveAttenuation + totalDiffusionAttenuation), pathDistance}; /* @@ -955,23 +955,9 @@ int AudioReflector::analyzePathsSingleStep() { } } else { path->finalized = true; // if we're too quiet, then we're done - if (wantExtraDebuggging && isDiffusion) { - qDebug() << "diffusion too quiet!"; - } - - if (((reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation) <= MINIMUM_ATTENUATION_TO_REFLECT) { - qDebug() << "too quiet!"; - } - if (totalDelay >= MAXIMUM_DELAY_MS) { - qDebug() << "too much delay!"; - } } } else { path->finalized = true; // if it doesn't intersect, then it is finished - if (wantExtraDebuggging && isDiffusion) { - qDebug() << "diffusion doesn't intersect!"; - } - qDebug() << "doesn't intersect!"; } } } From 839df97687fba31eafdafdfeefbcbdc3f49a1c3e Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 14 Apr 2014 16:46:25 -0700 Subject: [PATCH 402/595] make audio sliders initialize to defaul starting points --- examples/audioReflectorTools.js | 92 ++++++++++++++++++++++++++++----- 1 file changed, 79 insertions(+), 13 deletions(-) diff --git a/examples/audioReflectorTools.js b/examples/audioReflectorTools.js index 711f2a8e1f..ae9f43fddb 100644 --- a/examples/audioReflectorTools.js +++ b/examples/audioReflectorTools.js @@ -10,17 +10,33 @@ // -var delayScale = 500.0; +var delayScale = 100.0; var fanoutScale = 10.0; var speedScale = 20; var factorScale = 5.0; +var topY = 250; +var sliderHeight = 35; + // This will create a couple of image overlays that make a "slider", we will demonstrate how to trap mouse messages to // move the slider -var delayY = 250; +var delayY = topY; +topY += sliderHeight; +var delayLabel = Overlays.addOverlay("text", { + x: 40, + y: delayY, + width: 60, + height: sliderHeight, + color: { red: 0, green: 0, blue: 0}, + textColor: { red: 255, green: 0, blue: 0}, + topMargin: 12, + leftMargin: 5, + text: "Delay:" + }); + var delaySlider = Overlays.addOverlay("image", { // alternate form of expressing bounds - bounds: { x: 100, y: delayY, width: 150, height: 35}, + bounds: { x: 100, y: delayY, width: 150, height: sliderHeight}, subImage: { x: 46, y: 0, width: 200, height: 71 }, imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/slider.png", color: { red: 255, green: 255, blue: 255}, @@ -30,7 +46,7 @@ var delaySlider = Overlays.addOverlay("image", { // This is the thumb of our slider var delayMinThumbX = 110; var delayMaxThumbX = delayMinThumbX + 110; -var delayThumbX = (delayMinThumbX + delayMaxThumbX) / 2; +var delayThumbX = delayMinThumbX + ((delayMaxThumbX - delayMinThumbX) * (AudioReflector.getPreDelay() / delayScale)); var delayThumb = Overlays.addOverlay("image", { x: delayThumbX, y: delayY + 9, @@ -43,10 +59,24 @@ var delayThumb = Overlays.addOverlay("image", { // This will create a couple of image overlays that make a "slider", we will demonstrate how to trap mouse messages to // move the slider -var fanoutY = 300; +var fanoutY = topY; +topY += sliderHeight; + +var fanoutLabel = Overlays.addOverlay("text", { + x: 40, + y: fanoutY, + width: 60, + height: sliderHeight, + color: { red: 0, green: 0, blue: 0}, + textColor: { red: 255, green: 0, blue: 0}, + topMargin: 12, + leftMargin: 5, + text: "Fanout:" + }); + var fanoutSlider = Overlays.addOverlay("image", { // alternate form of expressing bounds - bounds: { x: 100, y: fanoutY, width: 150, height: 35}, + bounds: { x: 100, y: fanoutY, width: 150, height: sliderHeight}, subImage: { x: 46, y: 0, width: 200, height: 71 }, imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/slider.png", color: { red: 255, green: 255, blue: 255}, @@ -56,7 +86,7 @@ var fanoutSlider = Overlays.addOverlay("image", { // This is the thumb of our slider var fanoutMinThumbX = 110; var fanoutMaxThumbX = fanoutMinThumbX + 110; -var fanoutThumbX = (fanoutMinThumbX + fanoutMaxThumbX) / 2; +var fanoutThumbX = fanoutMinThumbX + ((fanoutMaxThumbX - fanoutMinThumbX) * (AudioReflector.getDiffusionFanout() / fanoutScale)); var fanoutThumb = Overlays.addOverlay("image", { x: fanoutThumbX, y: fanoutY + 9, @@ -70,10 +100,24 @@ var fanoutThumb = Overlays.addOverlay("image", { // This will create a couple of image overlays that make a "slider", we will demonstrate how to trap mouse messages to // move the slider -var speedY = 350; +var speedY = topY; +topY += sliderHeight; + +var speedLabel = Overlays.addOverlay("text", { + x: 40, + y: speedY, + width: 60, + height: sliderHeight, + color: { red: 0, green: 0, blue: 0}, + textColor: { red: 255, green: 0, blue: 0}, + topMargin: 6, + leftMargin: 5, + text: "Speed\nin ms/m:" + }); + var speedSlider = Overlays.addOverlay("image", { // alternate form of expressing bounds - bounds: { x: 100, y: speedY, width: 150, height: 35}, + bounds: { x: 100, y: speedY, width: 150, height: sliderHeight}, subImage: { x: 46, y: 0, width: 200, height: 71 }, imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/slider.png", color: { red: 255, green: 255, blue: 255}, @@ -83,7 +127,7 @@ var speedSlider = Overlays.addOverlay("image", { // This is the thumb of our slider var speedMinThumbX = 110; var speedMaxThumbX = speedMinThumbX + 110; -var speedThumbX = (speedMinThumbX + speedMaxThumbX) / 2; +var speedThumbX = speedMinThumbX + ((speedMaxThumbX - speedMinThumbX) * (AudioReflector.getSoundMsPerMeter() / speedScale)); var speedThumb = Overlays.addOverlay("image", { x: speedThumbX, y: speedY+9, @@ -96,10 +140,25 @@ var speedThumb = Overlays.addOverlay("image", { // This will create a couple of image overlays that make a "slider", we will demonstrate how to trap mouse messages to // move the slider -var factorY = 400; +var factorY = topY; +topY += sliderHeight; + +var factorLabel = Overlays.addOverlay("text", { + x: 40, + y: factorY, + width: 60, + height: sliderHeight, + color: { red: 0, green: 0, blue: 0}, + textColor: { red: 255, green: 0, blue: 0}, + topMargin: 6, + leftMargin: 5, + text: "Attenuation\nFactor:" + }); + + var factorSlider = Overlays.addOverlay("image", { // alternate form of expressing bounds - bounds: { x: 100, y: factorY, width: 150, height: 35}, + bounds: { x: 100, y: factorY, width: 150, height: sliderHeight}, subImage: { x: 46, y: 0, width: 200, height: 71 }, imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/slider.png", color: { red: 255, green: 255, blue: 255}, @@ -109,7 +168,7 @@ var factorSlider = Overlays.addOverlay("image", { // This is the thumb of our slider var factorMinThumbX = 110; var factorMaxThumbX = factorMinThumbX + 110; -var factorThumbX = (factorMinThumbX + factorMaxThumbX) / 2; +var factorThumbX = factorMinThumbX + ((factorMaxThumbX - factorMinThumbX) * (AudioReflector.getDistanceAttenuationScalingFactor() / factorScale)); var factorThumb = Overlays.addOverlay("image", { x: factorThumbX, y: factorY+9, @@ -123,12 +182,19 @@ var factorThumb = Overlays.addOverlay("image", { // When our script shuts down, we should clean up all of our overlays function scriptEnding() { + Overlays.deleteOverlay(factorLabel); Overlays.deleteOverlay(factorThumb); Overlays.deleteOverlay(factorSlider); + + Overlays.deleteOverlay(speedLabel); Overlays.deleteOverlay(speedThumb); Overlays.deleteOverlay(speedSlider); + + Overlays.deleteOverlay(delayLabel); Overlays.deleteOverlay(delayThumb); Overlays.deleteOverlay(delaySlider); + + Overlays.deleteOverlay(fanoutLabel); Overlays.deleteOverlay(fanoutThumb); Overlays.deleteOverlay(fanoutSlider); } From a2dc58f7f94ba579a2ccc45a49446166b7c83d00 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Mon, 14 Apr 2014 17:15:58 -0700 Subject: [PATCH 403/595] Moved FBX code to its own library so that we can use it for bots. --- interface/CMakeLists.txt | 1 + interface/src/ModelUploader.cpp | 4 +- interface/src/Util.cpp | 108 +----------------- interface/src/Util.h | 16 --- interface/src/devices/Faceplus.cpp | 3 +- interface/src/devices/Visage.cpp | 3 +- interface/src/renderer/GeometryCache.h | 2 +- libraries/fbx/CMakeLists.txt | 38 ++++++ .../fbx/src}/FBXReader.cpp | 6 +- .../fbx/src}/FBXReader.h | 0 libraries/shared/src/SharedUtil.cpp | 103 +++++++++++++++++ libraries/shared/src/SharedUtil.h | 16 +++ 12 files changed, 169 insertions(+), 131 deletions(-) create mode 100644 libraries/fbx/CMakeLists.txt rename {interface/src/renderer => libraries/fbx/src}/FBXReader.cpp (99%) rename {interface/src/renderer => libraries/fbx/src}/FBXReader.h (100%) diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index 6295095b43..557af35e12 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -120,6 +120,7 @@ include(${MACRO_DIR}/LinkHifiLibrary.cmake) link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(octree ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(voxels ${TARGET_NAME} "${ROOT_DIR}") +link_hifi_library(fbx ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(metavoxels ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(particles ${TARGET_NAME} "${ROOT_DIR}") diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index edbc6c0ad9..5b2688169f 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -22,9 +22,9 @@ #include -#include "Application.h" -#include "renderer/FBXReader.h" +#include +#include "Application.h" #include "ModelUploader.h" diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index cecc363daa..1dae3a4fd6 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -78,112 +78,6 @@ float angle_to(glm::vec3 head_pos, glm::vec3 source_pos, float render_yaw, float return atan2(head_pos.x - source_pos.x, head_pos.z - source_pos.z) + render_yaw + head_yaw; } -// Helper function returns the positive angle (in radians) between two 3D vectors -float angleBetween(const glm::vec3& v1, const glm::vec3& v2) { - return acosf((glm::dot(v1, v2)) / (glm::length(v1) * glm::length(v2))); -} - -// Helper function return the rotation from the first vector onto the second -glm::quat rotationBetween(const glm::vec3& v1, const glm::vec3& v2) { - float angle = angleBetween(v1, v2); - if (glm::isnan(angle) || angle < EPSILON) { - return glm::quat(); - } - glm::vec3 axis; - if (angle > 179.99f * RADIANS_PER_DEGREE) { // 180 degree rotation; must use another axis - axis = glm::cross(v1, glm::vec3(1.0f, 0.0f, 0.0f)); - float axisLength = glm::length(axis); - if (axisLength < EPSILON) { // parallel to x; y will work - axis = glm::normalize(glm::cross(v1, glm::vec3(0.0f, 1.0f, 0.0f))); - } else { - axis /= axisLength; - } - } else { - axis = glm::normalize(glm::cross(v1, v2)); - } - return glm::angleAxis(angle, axis); -} - - - -glm::vec3 extractTranslation(const glm::mat4& matrix) { - return glm::vec3(matrix[3][0], matrix[3][1], matrix[3][2]); -} - -void setTranslation(glm::mat4& matrix, const glm::vec3& translation) { - matrix[3][0] = translation.x; - matrix[3][1] = translation.y; - matrix[3][2] = translation.z; -} - -glm::quat extractRotation(const glm::mat4& matrix, bool assumeOrthogonal) { - // uses the iterative polar decomposition algorithm described by Ken Shoemake at - // http://www.cs.wisc.edu/graphics/Courses/838-s2002/Papers/polar-decomp.pdf - // code adapted from Clyde, https://github.com/threerings/clyde/blob/master/src/main/java/com/threerings/math/Matrix4f.java - - // start with the contents of the upper 3x3 portion of the matrix - glm::mat3 upper = glm::mat3(matrix); - if (!assumeOrthogonal) { - for (int i = 0; i < 10; i++) { - // store the results of the previous iteration - glm::mat3 previous = upper; - - // compute average of the matrix with its inverse transpose - float sd00 = previous[1][1] * previous[2][2] - previous[2][1] * previous[1][2]; - float sd10 = previous[0][1] * previous[2][2] - previous[2][1] * previous[0][2]; - float sd20 = previous[0][1] * previous[1][2] - previous[1][1] * previous[0][2]; - float det = previous[0][0] * sd00 + previous[2][0] * sd20 - previous[1][0] * sd10; - if (fabs(det) == 0.0f) { - // determinant is zero; matrix is not invertible - break; - } - float hrdet = 0.5f / det; - upper[0][0] = +sd00 * hrdet + previous[0][0] * 0.5f; - upper[1][0] = -sd10 * hrdet + previous[1][0] * 0.5f; - upper[2][0] = +sd20 * hrdet + previous[2][0] * 0.5f; - - upper[0][1] = -(previous[1][0] * previous[2][2] - previous[2][0] * previous[1][2]) * hrdet + previous[0][1] * 0.5f; - upper[1][1] = +(previous[0][0] * previous[2][2] - previous[2][0] * previous[0][2]) * hrdet + previous[1][1] * 0.5f; - upper[2][1] = -(previous[0][0] * previous[1][2] - previous[1][0] * previous[0][2]) * hrdet + previous[2][1] * 0.5f; - - upper[0][2] = +(previous[1][0] * previous[2][1] - previous[2][0] * previous[1][1]) * hrdet + previous[0][2] * 0.5f; - upper[1][2] = -(previous[0][0] * previous[2][1] - previous[2][0] * previous[0][1]) * hrdet + previous[1][2] * 0.5f; - upper[2][2] = +(previous[0][0] * previous[1][1] - previous[1][0] * previous[0][1]) * hrdet + previous[2][2] * 0.5f; - - // compute the difference; if it's small enough, we're done - glm::mat3 diff = upper - previous; - if (diff[0][0] * diff[0][0] + diff[1][0] * diff[1][0] + diff[2][0] * diff[2][0] + diff[0][1] * diff[0][1] + - diff[1][1] * diff[1][1] + diff[2][1] * diff[2][1] + diff[0][2] * diff[0][2] + diff[1][2] * diff[1][2] + - diff[2][2] * diff[2][2] < EPSILON) { - break; - } - } - } - - // now that we have a nice orthogonal matrix, we can extract the rotation quaternion - // using the method described in http://en.wikipedia.org/wiki/Rotation_matrix#Conversions - float x2 = fabs(1.0f + upper[0][0] - upper[1][1] - upper[2][2]); - float y2 = fabs(1.0f - upper[0][0] + upper[1][1] - upper[2][2]); - float z2 = fabs(1.0f - upper[0][0] - upper[1][1] + upper[2][2]); - float w2 = fabs(1.0f + upper[0][0] + upper[1][1] + upper[2][2]); - return glm::normalize(glm::quat(0.5f * sqrtf(w2), - 0.5f * sqrtf(x2) * (upper[1][2] >= upper[2][1] ? 1.0f : -1.0f), - 0.5f * sqrtf(y2) * (upper[2][0] >= upper[0][2] ? 1.0f : -1.0f), - 0.5f * sqrtf(z2) * (upper[0][1] >= upper[1][0] ? 1.0f : -1.0f))); -} - -glm::vec3 extractScale(const glm::mat4& matrix) { - return glm::vec3(glm::length(matrix[0]), glm::length(matrix[1]), glm::length(matrix[2])); -} - -float extractUniformScale(const glm::mat4& matrix) { - return extractUniformScale(extractScale(matrix)); -} - -float extractUniformScale(const glm::vec3& scale) { - return (scale.x + scale.y + scale.z) / 3.0f; -} - // Draw a 3D vector floating in space void drawVector(glm::vec3 * vector) { glDisable(GL_LIGHTING); @@ -629,4 +523,4 @@ bool pointInSphere(glm::vec3& point, glm::vec3& sphereCenter, double sphereRadiu return true; } return false; -} \ No newline at end of file +} diff --git a/interface/src/Util.h b/interface/src/Util.h index ac680645a9..4bd1ed604c 100644 --- a/interface/src/Util.h +++ b/interface/src/Util.h @@ -44,22 +44,6 @@ void drawVector(glm::vec3* vector); void printVector(glm::vec3 vec); -float angleBetween(const glm::vec3& v1, const glm::vec3& v2); - -glm::quat rotationBetween(const glm::vec3& v1, const glm::vec3& v2); - -glm::vec3 extractTranslation(const glm::mat4& matrix); - -void setTranslation(glm::mat4& matrix, const glm::vec3& translation); - -glm::quat extractRotation(const glm::mat4& matrix, bool assumeOrthogonal = false); - -glm::vec3 extractScale(const glm::mat4& matrix); - -float extractUniformScale(const glm::mat4& matrix); - -float extractUniformScale(const glm::vec3& scale); - double diffclock(timeval *clock1,timeval *clock2); void renderCollisionOverlay(int width, int height, float magnitude, float red = 0, float blue = 0, float green = 0); diff --git a/interface/src/devices/Faceplus.cpp b/interface/src/devices/Faceplus.cpp index f7f2f1f1bd..f155b994e7 100644 --- a/interface/src/devices/Faceplus.cpp +++ b/interface/src/devices/Faceplus.cpp @@ -15,9 +15,10 @@ #include #endif +#include + #include "Application.h" #include "Faceplus.h" -#include "renderer/FBXReader.h" static int floatVectorMetaTypeId = qRegisterMetaType >(); diff --git a/interface/src/devices/Visage.cpp b/interface/src/devices/Visage.cpp index e2f40e4741..a467d2d4a8 100644 --- a/interface/src/devices/Visage.cpp +++ b/interface/src/devices/Visage.cpp @@ -13,9 +13,10 @@ #include +#include + #include "Application.h" #include "Visage.h" -#include "renderer/FBXReader.h" // this has to go after our normal includes, because its definition of HANDLE conflicts with Qt's #ifdef HAVE_VISAGE diff --git a/interface/src/renderer/GeometryCache.h b/interface/src/renderer/GeometryCache.h index c2d276fb5e..0ad4f73904 100644 --- a/interface/src/renderer/GeometryCache.h +++ b/interface/src/renderer/GeometryCache.h @@ -20,7 +20,7 @@ #include -#include "FBXReader.h" +#include class Model; class NetworkGeometry; diff --git a/libraries/fbx/CMakeLists.txt b/libraries/fbx/CMakeLists.txt new file mode 100644 index 0000000000..10dd3f49f5 --- /dev/null +++ b/libraries/fbx/CMakeLists.txt @@ -0,0 +1,38 @@ +cmake_minimum_required(VERSION 2.8) + +if (WIN32) + cmake_policy (SET CMP0020 NEW) +endif (WIN32) + +set(ROOT_DIR ../..) +set(MACRO_DIR "${ROOT_DIR}/cmake/macros") + +# setup for find modules +set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/modules/") + +set(TARGET_NAME fbx) + +include(${MACRO_DIR}/SetupHifiLibrary.cmake) +setup_hifi_library(${TARGET_NAME}) + +include(${MACRO_DIR}/IncludeGLM.cmake) +include_glm(${TARGET_NAME} "${ROOT_DIR}") + +include(${MACRO_DIR}/LinkHifiLibrary.cmake) +link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") +link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") +link_hifi_library(octree ${TARGET_NAME} "${ROOT_DIR}") +link_hifi_library(voxels ${TARGET_NAME} "${ROOT_DIR}") + +# link ZLIB and GnuTLS +find_package(ZLIB) +find_package(GnuTLS REQUIRED) + +# add a definition for ssize_t so that windows doesn't bail on gnutls.h +if (WIN32) + add_definitions(-Dssize_t=long) +endif () + + +include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") +target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" Qt5::Widgets "${GNUTLS_LIBRARY}") diff --git a/interface/src/renderer/FBXReader.cpp b/libraries/fbx/src/FBXReader.cpp similarity index 99% rename from interface/src/renderer/FBXReader.cpp rename to libraries/fbx/src/FBXReader.cpp index 43f6ccc065..6c51e11150 100644 --- a/interface/src/renderer/FBXReader.cpp +++ b/libraries/fbx/src/FBXReader.cpp @@ -22,14 +22,14 @@ #include #include -#include - #include +#include #include +#include + #include #include "FBXReader.h" -#include "Util.h" using namespace std; diff --git a/interface/src/renderer/FBXReader.h b/libraries/fbx/src/FBXReader.h similarity index 100% rename from interface/src/renderer/FBXReader.h rename to libraries/fbx/src/FBXReader.h diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index cd98fbdbd2..0541d7fddc 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -659,3 +659,106 @@ glm::vec3 safeEulerAngles(const glm::quat& q) { } } +// Helper function returns the positive angle (in radians) between two 3D vectors +float angleBetween(const glm::vec3& v1, const glm::vec3& v2) { + return acosf((glm::dot(v1, v2)) / (glm::length(v1) * glm::length(v2))); +} + +// Helper function return the rotation from the first vector onto the second +glm::quat rotationBetween(const glm::vec3& v1, const glm::vec3& v2) { + float angle = angleBetween(v1, v2); + if (glm::isnan(angle) || angle < EPSILON) { + return glm::quat(); + } + glm::vec3 axis; + if (angle > 179.99f * RADIANS_PER_DEGREE) { // 180 degree rotation; must use another axis + axis = glm::cross(v1, glm::vec3(1.0f, 0.0f, 0.0f)); + float axisLength = glm::length(axis); + if (axisLength < EPSILON) { // parallel to x; y will work + axis = glm::normalize(glm::cross(v1, glm::vec3(0.0f, 1.0f, 0.0f))); + } else { + axis /= axisLength; + } + } else { + axis = glm::normalize(glm::cross(v1, v2)); + } + return glm::angleAxis(angle, axis); +} + +glm::vec3 extractTranslation(const glm::mat4& matrix) { + return glm::vec3(matrix[3][0], matrix[3][1], matrix[3][2]); +} + +void setTranslation(glm::mat4& matrix, const glm::vec3& translation) { + matrix[3][0] = translation.x; + matrix[3][1] = translation.y; + matrix[3][2] = translation.z; +} + +glm::quat extractRotation(const glm::mat4& matrix, bool assumeOrthogonal) { + // uses the iterative polar decomposition algorithm described by Ken Shoemake at + // http://www.cs.wisc.edu/graphics/Courses/838-s2002/Papers/polar-decomp.pdf + // code adapted from Clyde, https://github.com/threerings/clyde/blob/master/src/main/java/com/threerings/math/Matrix4f.java + + // start with the contents of the upper 3x3 portion of the matrix + glm::mat3 upper = glm::mat3(matrix); + if (!assumeOrthogonal) { + for (int i = 0; i < 10; i++) { + // store the results of the previous iteration + glm::mat3 previous = upper; + + // compute average of the matrix with its inverse transpose + float sd00 = previous[1][1] * previous[2][2] - previous[2][1] * previous[1][2]; + float sd10 = previous[0][1] * previous[2][2] - previous[2][1] * previous[0][2]; + float sd20 = previous[0][1] * previous[1][2] - previous[1][1] * previous[0][2]; + float det = previous[0][0] * sd00 + previous[2][0] * sd20 - previous[1][0] * sd10; + if (fabs(det) == 0.0f) { + // determinant is zero; matrix is not invertible + break; + } + float hrdet = 0.5f / det; + upper[0][0] = +sd00 * hrdet + previous[0][0] * 0.5f; + upper[1][0] = -sd10 * hrdet + previous[1][0] * 0.5f; + upper[2][0] = +sd20 * hrdet + previous[2][0] * 0.5f; + + upper[0][1] = -(previous[1][0] * previous[2][2] - previous[2][0] * previous[1][2]) * hrdet + previous[0][1] * 0.5f; + upper[1][1] = +(previous[0][0] * previous[2][2] - previous[2][0] * previous[0][2]) * hrdet + previous[1][1] * 0.5f; + upper[2][1] = -(previous[0][0] * previous[1][2] - previous[1][0] * previous[0][2]) * hrdet + previous[2][1] * 0.5f; + + upper[0][2] = +(previous[1][0] * previous[2][1] - previous[2][0] * previous[1][1]) * hrdet + previous[0][2] * 0.5f; + upper[1][2] = -(previous[0][0] * previous[2][1] - previous[2][0] * previous[0][1]) * hrdet + previous[1][2] * 0.5f; + upper[2][2] = +(previous[0][0] * previous[1][1] - previous[1][0] * previous[0][1]) * hrdet + previous[2][2] * 0.5f; + + // compute the difference; if it's small enough, we're done + glm::mat3 diff = upper - previous; + if (diff[0][0] * diff[0][0] + diff[1][0] * diff[1][0] + diff[2][0] * diff[2][0] + diff[0][1] * diff[0][1] + + diff[1][1] * diff[1][1] + diff[2][1] * diff[2][1] + diff[0][2] * diff[0][2] + diff[1][2] * diff[1][2] + + diff[2][2] * diff[2][2] < EPSILON) { + break; + } + } + } + + // now that we have a nice orthogonal matrix, we can extract the rotation quaternion + // using the method described in http://en.wikipedia.org/wiki/Rotation_matrix#Conversions + float x2 = fabs(1.0f + upper[0][0] - upper[1][1] - upper[2][2]); + float y2 = fabs(1.0f - upper[0][0] + upper[1][1] - upper[2][2]); + float z2 = fabs(1.0f - upper[0][0] - upper[1][1] + upper[2][2]); + float w2 = fabs(1.0f + upper[0][0] + upper[1][1] + upper[2][2]); + return glm::normalize(glm::quat(0.5f * sqrtf(w2), + 0.5f * sqrtf(x2) * (upper[1][2] >= upper[2][1] ? 1.0f : -1.0f), + 0.5f * sqrtf(y2) * (upper[2][0] >= upper[0][2] ? 1.0f : -1.0f), + 0.5f * sqrtf(z2) * (upper[0][1] >= upper[1][0] ? 1.0f : -1.0f))); +} + +glm::vec3 extractScale(const glm::mat4& matrix) { + return glm::vec3(glm::length(matrix[0]), glm::length(matrix[1]), glm::length(matrix[2])); +} + +float extractUniformScale(const glm::mat4& matrix) { + return extractUniformScale(extractScale(matrix)); +} + +float extractUniformScale(const glm::vec3& scale) { + return (scale.x + scale.y + scale.z) / 3.0f; +} diff --git a/libraries/shared/src/SharedUtil.h b/libraries/shared/src/SharedUtil.h index f41c5b8aa2..4f7c643511 100644 --- a/libraries/shared/src/SharedUtil.h +++ b/libraries/shared/src/SharedUtil.h @@ -166,4 +166,20 @@ int unpackFloatVec3FromSignedTwoByteFixed(const unsigned char* sourceBuffer, glm /// \return vec3 with euler angles in radians glm::vec3 safeEulerAngles(const glm::quat& q); +float angleBetween(const glm::vec3& v1, const glm::vec3& v2); + +glm::quat rotationBetween(const glm::vec3& v1, const glm::vec3& v2); + +glm::vec3 extractTranslation(const glm::mat4& matrix); + +void setTranslation(glm::mat4& matrix, const glm::vec3& translation); + +glm::quat extractRotation(const glm::mat4& matrix, bool assumeOrthogonal = false); + +glm::vec3 extractScale(const glm::mat4& matrix); + +float extractUniformScale(const glm::mat4& matrix); + +float extractUniformScale(const glm::vec3& scale); + #endif // hifi_SharedUtil_h From 38c0e99cbecc03134e1a4b028b71558abc455a84 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Mon, 14 Apr 2014 18:12:32 -0700 Subject: [PATCH 404/595] More work on animation loading. --- assignment-client/CMakeLists.txt | 3 +- libraries/particles/CMakeLists.txt | 3 +- libraries/script-engine/CMakeLists.txt | 3 +- .../script-engine/src/AnimationCache.cpp | 65 +++++++++++++++++++ libraries/script-engine/src/AnimationCache.h | 56 ++++++++++++++++ libraries/script-engine/src/ScriptEngine.cpp | 3 +- libraries/script-engine/src/ScriptEngine.h | 2 + 7 files changed, 131 insertions(+), 4 deletions(-) create mode 100644 libraries/script-engine/src/AnimationCache.cpp create mode 100644 libraries/script-engine/src/AnimationCache.h diff --git a/assignment-client/CMakeLists.txt b/assignment-client/CMakeLists.txt index a8343e94ad..b78d4f81f9 100644 --- a/assignment-client/CMakeLists.txt +++ b/assignment-client/CMakeLists.txt @@ -28,6 +28,7 @@ link_hifi_library(audio ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(avatars ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(octree ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(voxels ${TARGET_NAME} "${ROOT_DIR}") +link_hifi_library(fbx ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(particles ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(metavoxels ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") @@ -51,4 +52,4 @@ IF (WIN32) target_link_libraries(${TARGET_NAME} Winmm Ws2_32) ENDIF(WIN32) -target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets Qt5::Script "${GNUTLS_LIBRARY}") \ No newline at end of file +target_link_libraries(${TARGET_NAME} Qt5::Network Qt5::Widgets Qt5::Script "${GNUTLS_LIBRARY}") diff --git a/libraries/particles/CMakeLists.txt b/libraries/particles/CMakeLists.txt index 26d2b7fc26..1cb60756a2 100644 --- a/libraries/particles/CMakeLists.txt +++ b/libraries/particles/CMakeLists.txt @@ -23,6 +23,7 @@ include_glm(${TARGET_NAME} "${ROOT_DIR}") include(${MACRO_DIR}/LinkHifiLibrary.cmake) link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(octree ${TARGET_NAME} "${ROOT_DIR}") +link_hifi_library(fbx ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(networking ${TARGET_NAME} "${ROOT_DIR}") # link ZLIB and GnuTLS @@ -35,4 +36,4 @@ if (WIN32) endif () include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") -target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" Qt5::Widgets "${GNUTLS_LIBRARY}") \ No newline at end of file +target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" Qt5::Widgets "${GNUTLS_LIBRARY}") diff --git a/libraries/script-engine/CMakeLists.txt b/libraries/script-engine/CMakeLists.txt index 20569e2fe0..48d13e7742 100644 --- a/libraries/script-engine/CMakeLists.txt +++ b/libraries/script-engine/CMakeLists.txt @@ -24,6 +24,7 @@ include(${MACRO_DIR}/LinkHifiLibrary.cmake) link_hifi_library(shared ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(octree ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(voxels ${TARGET_NAME} "${ROOT_DIR}") +link_hifi_library(fbx ${TARGET_NAME} "${ROOT_DIR}") link_hifi_library(particles ${TARGET_NAME} "${ROOT_DIR}") # link ZLIB @@ -36,4 +37,4 @@ if (WIN32) endif () include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}" "${GNUTLS_INCLUDE_DIR}") -target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" "${GNUTLS_LIBRARY}" Qt5::Widgets) \ No newline at end of file +target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}" "${GNUTLS_LIBRARY}" Qt5::Widgets) diff --git a/libraries/script-engine/src/AnimationCache.cpp b/libraries/script-engine/src/AnimationCache.cpp new file mode 100644 index 0000000000..2a6aac1992 --- /dev/null +++ b/libraries/script-engine/src/AnimationCache.cpp @@ -0,0 +1,65 @@ +// +// AnimationCache.cpp +// libraries/script-engine/src/ +// +// Created by Andrzej Kapolka on 4/14/14. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// +// 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 "AnimationCache.h" + +QSharedPointer AnimationCache::getAnimation(const QUrl& url) { + return getResource(url).staticCast(); +} + +QSharedPointer AnimationCache::createResource(const QUrl& url, const QSharedPointer& fallback, + bool delayLoad, const void* extra) { + return QSharedPointer(new Animation(url), &Resource::allReferencesCleared); +} + +Animation::Animation(const QUrl& url) : + Resource(url) { +} + +class AnimationReader : public QRunnable { +public: + + AnimationReader(const QWeakPointer& animation, QNetworkReply* reply); + + virtual void run(); + +private: + + QWeakPointer _animation; + QNetworkReply* _reply; +}; + +AnimationReader::AnimationReader(const QWeakPointer& animation, QNetworkReply* reply) : + _animation(animation), + _reply(reply) { +} + +void AnimationReader::run() { + QSharedPointer animation = _animation.toStrongRef(); + if (!animation.isNull()) { + QMetaObject::invokeMethod(animation.data(), "setGeometry", + Q_ARG(const FBXGeometry&, readFBX(_reply->readAll(), QVariantHash()))); + } + _reply->deleteLater(); +} + +void Animation::setGeometry(const FBXGeometry& geometry) { + _geometry = geometry; + finishedLoading(true); +} + +void Animation::downloadFinished(QNetworkReply* reply) { + // send the reader off to the thread pool + QThreadPool::globalInstance()->start(new AnimationReader(_self, reply)); +} diff --git a/libraries/script-engine/src/AnimationCache.h b/libraries/script-engine/src/AnimationCache.h new file mode 100644 index 0000000000..bb8a0f2313 --- /dev/null +++ b/libraries/script-engine/src/AnimationCache.h @@ -0,0 +1,56 @@ +// +// AnimationCache.h +// libraries/script-engine/src/ +// +// Created by Andrzej Kapolka on 4/14/14. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// +// 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_AnimationCache_h +#define hifi_AnimationCache_h + +#include + +#include + +class Animation; + +/// Scriptable interface for FBX animation loading. +class AnimationCache : public ResourceCache { + Q_OBJECT + +public: + + QSharedPointer getAnimation(const QUrl& url); + +protected: + + virtual QSharedPointer createResource(const QUrl& url, + const QSharedPointer& fallback, bool delayLoad, const void* extra); +}; + +/// An animation loaded from the network. +class Animation : public Resource { + Q_OBJECT + +public: + + Animation(const QUrl& url); + + const FBXGeometry& getGeometry() const { return _geometry; } + +protected: + + Q_INVOKABLE void setGeometry(const FBXGeometry& geometry); + + virtual void downloadFinished(QNetworkReply* reply); + +private: + + FBXGeometry _geometry; +}; + +#endif // hifi_AnimationCache_h diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index b5291a6a2f..b0e2d1495b 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -204,7 +204,8 @@ void ScriptEngine::init() { registerGlobalObject("Quat", &_quatLibrary); registerGlobalObject("Vec3", &_vec3Library); registerGlobalObject("Uuid", &_uuidLibrary); - + registerGlobalObject("AnimationCache", &_animationCache); + registerGlobalObject("Voxels", &_voxelsScriptingInterface); QScriptValue treeScaleValue = _engine.newVariant(QVariant(TREE_SCALE)); diff --git a/libraries/script-engine/src/ScriptEngine.h b/libraries/script-engine/src/ScriptEngine.h index 9719c83107..73747cd3e1 100644 --- a/libraries/script-engine/src/ScriptEngine.h +++ b/libraries/script-engine/src/ScriptEngine.h @@ -23,6 +23,7 @@ #include +#include "AnimationCache.h" #include "AbstractControllerScriptingInterface.h" #include "Quat.h" #include "ScriptUUID.h" @@ -125,6 +126,7 @@ private: Quat _quatLibrary; Vec3 _vec3Library; ScriptUUID _uuidLibrary; + AnimationCache _animationCache; }; #endif // hifi_ScriptEngine_h From 7448e0ab16342212cd9d9153e9b5da8ae53a066b Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 14 Apr 2014 20:28:20 -0700 Subject: [PATCH 405/595] move to sub menu --- interface/src/Menu.cpp | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index a1a74bc6ce..e7c5b84a42 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -382,48 +382,51 @@ Menu::Menu() : false, appInstance->getAudio(), SLOT(toggleToneInjection())); - addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessing, + + addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::LowPassFilter, + Qt::CTRL | Qt::SHIFT | Qt::Key_F, + false); + + QMenu* spatialAudioMenu = audioDebugMenu->addMenu("Spatial Audio"); + + addCheckableActionToQMenuAndActionHash(spatialAudioMenu, MenuOption::AudioSpatialProcessing, Qt::CTRL | Qt::SHIFT | Qt::Key_M, false, appInstance->getAudio(), SLOT(toggleAudioSpatialProcessing())); - addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingIncudeOriginal, + addCheckableActionToQMenuAndActionHash(spatialAudioMenu, MenuOption::AudioSpatialProcessingIncudeOriginal, Qt::CTRL | Qt::SHIFT | Qt::Key_O, true); - addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingSeparateEars, + addCheckableActionToQMenuAndActionHash(spatialAudioMenu, MenuOption::AudioSpatialProcessingSeparateEars, Qt::CTRL | Qt::SHIFT | Qt::Key_E, true); - addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingPreDelay, + addCheckableActionToQMenuAndActionHash(spatialAudioMenu, MenuOption::AudioSpatialProcessingPreDelay, Qt::CTRL | Qt::SHIFT | Qt::Key_D, true); - addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingStereoSource, + addCheckableActionToQMenuAndActionHash(spatialAudioMenu, MenuOption::AudioSpatialProcessingStereoSource, Qt::CTRL | Qt::SHIFT | Qt::Key_S, true); - addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingHeadOriented, + addCheckableActionToQMenuAndActionHash(spatialAudioMenu, MenuOption::AudioSpatialProcessingHeadOriented, Qt::CTRL | Qt::SHIFT | Qt::Key_H, true); - addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingWithDiffusions, + addCheckableActionToQMenuAndActionHash(spatialAudioMenu, MenuOption::AudioSpatialProcessingWithDiffusions, Qt::CTRL | Qt::SHIFT | Qt::Key_W, true); - addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingRenderPaths, + addCheckableActionToQMenuAndActionHash(spatialAudioMenu, MenuOption::AudioSpatialProcessingRenderPaths, Qt::CTRL | Qt::SHIFT | Qt::Key_R, true); - addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioSpatialProcessingSlightlyRandomSurfaces, + addCheckableActionToQMenuAndActionHash(spatialAudioMenu, MenuOption::AudioSpatialProcessingSlightlyRandomSurfaces, Qt::CTRL | Qt::SHIFT | Qt::Key_X, true); - addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::LowPassFilter, - Qt::CTRL | Qt::SHIFT | Qt::Key_F, - false); - addActionToQMenuAndActionHash(developerMenu, MenuOption::PasteToVoxel, Qt::CTRL | Qt::SHIFT | Qt::Key_V, this, From 1ed5512925873dd664220204dbb2ded78b3731c0 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 14 Apr 2014 21:02:09 -0700 Subject: [PATCH 406/595] remove old mode, replaced by new mode --- interface/src/AudioReflector.cpp | 508 +++---------------------------- interface/src/AudioReflector.h | 54 +--- interface/src/ui/Stats.cpp | 6 +- 3 files changed, 44 insertions(+), 524 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index fe1c26950a..d9dc678886 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -35,7 +35,14 @@ AudioReflector::AudioReflector(QObject* parent) : _diffusionRatio(DEFAULT_DIFFUSION_RATIO), _withDiffusion(false) { - reset(); + _reflections = 0; + _diffusionPathCount = 0; + _averageAttenuation = 0.0f; + _maxAttenuation = 0.0f; + _minAttenuation = 0.0f; + _averageDelay = 0; + _maxDelay = 0; + _minDelay = 0; } @@ -45,46 +52,27 @@ void AudioReflector::render() { if (!_myAvatar || !_audio->getProcessSpatialAudio()) { return; } - - bool withDiffusions = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions); - - // Even if we're not rendering, use this as a chance to recalculate our reflections - if (withDiffusions) { - newCalculateAllReflections(); - } else { - calculateAllReflections(); - } + // use this oportunity to calculate our reflections + calculateAllReflections(); + + // only render if we've been asked to do so if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingRenderPaths)) { - // here's where we actually render - if (withDiffusions) { - newDrawRays(); - } else { - drawRays(); - } + drawRays(); } } // delay = 1ms per foot // = 3ms per meter -// attenuation = -// BOUNCE_ATTENUATION_FACTOR [0.5] * (1/(1+distance)) - float AudioReflector::getDelayFromDistance(float distance) { float delay = (_soundMsPerMeter * distance); - - // NOTE: kind of hacky, the old code (which didn't handle diffusions, assumes that this function - // will add in any and all pre delay. But the new method (which includes diffusions) handles pre delay - // on it's own. So we only add in pre delay if the pre delay is enabled, and we're not in diffusion mode - if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingPreDelay) && - !Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions)) { - + if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingPreDelay)) { delay += _preDelay; } - return delay; } +// attenuation = from the Audio Mixer float AudioReflector::getDistanceAttenuationCoefficient(float distance) { const float DISTANCE_SCALE = 2.5f; const float GEOMETRIC_AMPLITUDE_SCALAR = 0.3f; @@ -103,14 +91,6 @@ float AudioReflector::getDistanceAttenuationCoefficient(float distance) { return distanceCoefficient; } -// This is used in the "old" model with diffusions... it's essentially the amount of energy that is reflected on each bounce -float AudioReflector::getBounceAttenuationCoefficient(int bounceCount) { - // now we know the current attenuation for the "perfect" reflection case, but we now incorporate - // our surface materials to determine how much of this ray is absorbed, reflected, and diffused - SurfaceCharacteristics material = getSurfaceCharacteristics(); - return powf(material.reflectiveRatio, bounceCount); -} - glm::vec3 AudioReflector::getFaceNormal(BoxFace face) { bool wantSlightRandomness = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingSlightlyRandomSurfaces); @@ -137,285 +117,10 @@ glm::vec3 AudioReflector::getFaceNormal(BoxFace face) { return faceNormal; } -void AudioReflector::reset() { - _reflections = 0; - _diffusionPathCount = 0; - _averageAttenuation = 0.0f; - _maxAttenuation = 0.0f; - _minAttenuation = 0.0f; - _averageDelay = 0; - _maxDelay = 0; - _minDelay = 0; - - _reflections = _frontRightUpReflections.size() + - _frontLeftUpReflections.size() + - _backRightUpReflections.size() + - _backLeftUpReflections.size() + - _frontRightDownReflections.size() + - _frontLeftDownReflections.size() + - _backRightDownReflections.size() + - _backLeftDownReflections.size() + - _frontReflections.size() + - _backReflections.size() + - _leftReflections.size() + - _rightReflections.size() + - _upReflections.size() + - _downReflections.size(); -} - -void AudioReflector::calculateAllReflections() { - - // only recalculate when we've moved... - // TODO: what about case where new voxels are added in front of us??? - bool wantHeadOrientation = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingHeadOriented); - glm::quat orientation = wantHeadOrientation ? _myAvatar->getHead()->getFinalOrientation() : _myAvatar->getOrientation(); - glm::vec3 origin = _myAvatar->getHead()->getPosition(); - glm::vec3 listenerPosition = _myAvatar->getHead()->getPosition(); - - bool withDiffusion = false; // this is the non-diffusion mode. - - bool shouldRecalc = _reflections == 0 - || !isSimilarPosition(origin, _origin) - || !isSimilarOrientation(orientation, _orientation) - || !isSimilarPosition(listenerPosition, _listenerPosition) - || (withDiffusion != _withDiffusion); - - if (shouldRecalc) { - -qDebug() << "RECALC...... !!!!!!!!!!!!!!!!!!!!!!!!!!!!"; -if (_reflections == 0) { - qDebug() << "RECALC...... No reflections!!!!!!!!!!!!!!!!!!!!!!!!!!!!"; -} -if (!isSimilarPosition(origin, _origin)) { - qDebug() << "RECALC...... origin changed...!!!!!!!!!!!!!!!!!!!!!!!!!!!!"; -} -if (!isSimilarOrientation(orientation, _orientation)) { - qDebug() << "RECALC...... orientation changed...!!!!!!!!!!!!!!!!!!!!!!!!!!!!"; -} -if (!isSimilarPosition(listenerPosition, _listenerPosition)) { - qDebug() << "RECALC...... listenerPosition changed...!!!!!!!!!!!!!!!!!!!!!!!!!!!!"; -} -if (withDiffusion != _withDiffusion) { - qDebug() << "RECALC...... withDiffusion changed...!!!!!!!!!!!!!!!!!!!!!!!!!!!!"; -} - - QMutexLocker locker(&_mutex); - - quint64 start = usecTimestampNow(); - - _origin = origin; - _listenerPosition = listenerPosition; - _orientation = orientation; - _withDiffusion = withDiffusion; - - glm::vec3 right = glm::normalize(_orientation * IDENTITY_RIGHT); - glm::vec3 up = glm::normalize(_orientation * IDENTITY_UP); - glm::vec3 front = glm::normalize(_orientation * IDENTITY_FRONT); - glm::vec3 left = -right; - glm::vec3 down = -up; - glm::vec3 back = -front; - glm::vec3 frontRightUp = glm::normalize(front + right + up); - glm::vec3 frontLeftUp = glm::normalize(front + left + up); - glm::vec3 backRightUp = glm::normalize(back + right + up); - glm::vec3 backLeftUp = glm::normalize(back + left + up); - glm::vec3 frontRightDown = glm::normalize(front + right + down); - glm::vec3 frontLeftDown = glm::normalize(front + left + down); - glm::vec3 backRightDown = glm::normalize(back + right + down); - glm::vec3 backLeftDown = glm::normalize(back + left + down); - - _rightReflections = calculateReflections(listenerPosition, _origin, right); - _frontRightUpReflections = calculateReflections(listenerPosition, _origin, frontRightUp); - _frontLeftUpReflections = calculateReflections(listenerPosition, _origin, frontLeftUp); - _backRightUpReflections = calculateReflections(listenerPosition, _origin, backRightUp); - _backLeftUpReflections = calculateReflections(listenerPosition, _origin, backLeftUp); - _frontRightDownReflections = calculateReflections(listenerPosition, _origin, frontRightDown); - _frontLeftDownReflections = calculateReflections(listenerPosition, _origin, frontLeftDown); - _backRightDownReflections = calculateReflections(listenerPosition, _origin, backRightDown); - _backLeftDownReflections = calculateReflections(listenerPosition, _origin, backLeftDown); - _frontReflections = calculateReflections(listenerPosition, _origin, front); - _backReflections = calculateReflections(listenerPosition, _origin, back); - _leftReflections = calculateReflections(listenerPosition, _origin, left); - _upReflections = calculateReflections(listenerPosition, _origin, up); - _downReflections = calculateReflections(listenerPosition, _origin, down); - - quint64 end = usecTimestampNow(); - - reset(); - - const bool wantDebugging = false; - if (wantDebugging) { - qDebug() << "calculateAllReflections() elapsed=" << (end - start); - } - } -} - -QVector AudioReflector::calculateReflections(const glm::vec3& earPosition, - const glm::vec3& origin, const glm::vec3& originalDirection) { - - QVector reflectionPoints; - glm::vec3 start = origin; - glm::vec3 direction = originalDirection; - OctreeElement* elementHit; - float distance; - BoxFace face; - const float SLIGHTLY_SHORT = 0.999f; // slightly inside the distance so we're on the inside of the reflection point - float currentAttenuation = 1.0f; - float totalDistance = 0.0f; - float totalDelay = 0.0f; - int bounceCount = 1; - - while (currentAttenuation > MINIMUM_ATTENUATION_TO_REFLECT && totalDelay < MAXIMUM_DELAY_MS && bounceCount < ABSOLUTE_MAXIMUM_BOUNCE_COUNT) { - if (_voxels->findRayIntersection(start, direction, elementHit, distance, face, Octree::Lock)) { - glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); - - totalDistance += glm::distance(start, end); - float earDistance = glm::distance(end, earPosition); - float totalDistance = earDistance + distance; - totalDelay = getDelayFromDistance(totalDistance); - currentAttenuation = getDistanceAttenuationCoefficient(totalDistance) * - getBounceAttenuationCoefficient(bounceCount); - - if (currentAttenuation > MINIMUM_ATTENUATION_TO_REFLECT && totalDelay < MAXIMUM_DELAY_MS) { - reflectionPoints.push_back(end); - glm::vec3 faceNormal = getFaceNormal(face); - direction = glm::normalize(glm::reflect(direction,faceNormal)); - start = end; - bounceCount++; - } - } else { - currentAttenuation = 0.0f; - } - } - return reflectionPoints; -} - - -void AudioReflector::drawReflections(const glm::vec3& origin, const glm::vec3& originalColor, const QVector& reflections) { - - glm::vec3 start = origin; - glm::vec3 color = originalColor; - const float COLOR_ADJUST_PER_BOUNCE = 0.75f; - - foreach (glm::vec3 end, reflections) { - drawVector(start, end, color); - start = end; - color = color * COLOR_ADJUST_PER_BOUNCE; - } -} - // set up our buffers for our attenuated and delayed samples const int NUMBER_OF_CHANNELS = 2; - -void AudioReflector::echoReflections(const glm::vec3& origin, const QVector& reflections, const QByteArray& samples, - unsigned int sampleTime, int sampleRate) { - - bool wantEarSeparation = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingSeparateEars); - bool wantStereo = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingStereoSource); - glm::vec3 rightEarPosition = wantEarSeparation ? _myAvatar->getHead()->getRightEarPosition() : - _myAvatar->getHead()->getPosition(); - glm::vec3 leftEarPosition = wantEarSeparation ? _myAvatar->getHead()->getLeftEarPosition() : - _myAvatar->getHead()->getPosition(); - glm::vec3 start = origin; - - int totalNumberOfSamples = samples.size() / sizeof(int16_t); - int totalNumberOfStereoSamples = samples.size() / (sizeof(int16_t) * NUMBER_OF_CHANNELS); - - const int16_t* originalSamplesData = (const int16_t*)samples.constData(); - QByteArray attenuatedLeftSamples; - QByteArray attenuatedRightSamples; - attenuatedLeftSamples.resize(samples.size()); - attenuatedRightSamples.resize(samples.size()); - - int16_t* attenuatedLeftSamplesData = (int16_t*)attenuatedLeftSamples.data(); - int16_t* attenuatedRightSamplesData = (int16_t*)attenuatedRightSamples.data(); - - float rightDistance = 0; - float leftDistance = 0; - int bounceCount = 0; - - foreach (glm::vec3 end, reflections) { - bounceCount++; - - rightDistance += glm::distance(start, end); - leftDistance += glm::distance(start, end); - - // calculate the distance to the ears - float rightEarDistance = glm::distance(end, rightEarPosition); - float leftEarDistance = glm::distance(end, leftEarPosition); - - float rightTotalDistance = rightEarDistance + rightDistance; - float leftTotalDistance = leftEarDistance + leftDistance; - - float rightEarDelayMsecs = getDelayFromDistance(rightTotalDistance); - float leftEarDelayMsecs = getDelayFromDistance(leftTotalDistance); - - _totalDelay += rightEarDelayMsecs + leftEarDelayMsecs; - _delayCount += 2; - _maxDelay = std::max(_maxDelay,rightEarDelayMsecs); - _maxDelay = std::max(_maxDelay,leftEarDelayMsecs); - _minDelay = std::min(_minDelay,rightEarDelayMsecs); - _minDelay = std::min(_minDelay,leftEarDelayMsecs); - - int rightEarDelay = rightEarDelayMsecs * sampleRate / MSECS_PER_SECOND; - int leftEarDelay = leftEarDelayMsecs * sampleRate / MSECS_PER_SECOND; - - //qDebug() << "leftTotalDistance=" << leftTotalDistance << "rightTotalDistance=" << rightTotalDistance; - //qDebug() << "leftEarDelay=" << leftEarDelay << "rightEarDelay=" << rightEarDelay; - - float bounceAttenuation = getBounceAttenuationCoefficient(bounceCount); - float rightEarAttenuation = getDistanceAttenuationCoefficient(rightTotalDistance) * bounceAttenuation; - float leftEarAttenuation = getDistanceAttenuationCoefficient(leftTotalDistance) * bounceAttenuation; - - /* - qDebug() << "audible point..."; - qDebug() << " bounceCount=" << bounceCount; - qDebug() << " bounceAttenuation=" << bounceAttenuation; - qDebug() << " rightEarAttenuation=" << rightEarAttenuation; - qDebug() << " leftEarAttenuation=" << leftEarAttenuation; - */ - - _totalAttenuation += rightEarAttenuation + leftEarAttenuation; - _attenuationCount += 2; - _maxAttenuation = std::max(_maxAttenuation,rightEarAttenuation); - _maxAttenuation = std::max(_maxAttenuation,leftEarAttenuation); - _minAttenuation = std::min(_minAttenuation,rightEarAttenuation); - _minAttenuation = std::min(_minAttenuation,leftEarAttenuation); - - // run through the samples, and attenuate them - for (int sample = 0; sample < totalNumberOfStereoSamples; sample++) { - int16_t leftSample = originalSamplesData[sample * NUMBER_OF_CHANNELS]; - int16_t rightSample = leftSample; - if (wantStereo) { - rightSample = originalSamplesData[(sample * NUMBER_OF_CHANNELS) + 1]; - } - - //qDebug() << "leftSample=" << leftSample << "rightSample=" << rightSample; - attenuatedLeftSamplesData[sample * NUMBER_OF_CHANNELS] = leftSample * leftEarAttenuation; - attenuatedLeftSamplesData[sample * NUMBER_OF_CHANNELS + 1] = 0; - - attenuatedRightSamplesData[sample * NUMBER_OF_CHANNELS] = 0; - attenuatedRightSamplesData[sample * NUMBER_OF_CHANNELS + 1] = rightSample * rightEarAttenuation; - - //qDebug() << "attenuated... leftSample=" << (leftSample * leftEarAttenuation) << "rightSample=" << (rightSample * rightEarAttenuation); - } - - // now inject the attenuated array with the appropriate delay - - unsigned int sampleTimeLeft = sampleTime + leftEarDelay; - unsigned int sampleTimeRight = sampleTime + rightEarDelay; - - //qDebug() << "sampleTimeLeft=" << sampleTimeLeft << "sampleTimeRight=" << sampleTimeRight; - - _audio->addSpatialAudioToBuffer(sampleTimeLeft, attenuatedLeftSamples, totalNumberOfSamples); - _audio->addSpatialAudioToBuffer(sampleTimeRight, attenuatedRightSamples, totalNumberOfSamples); - - - start = end; - } -} - -void AudioReflector::injectAudiblePoint(const AudioPoint& audiblePoint, +void AudioReflector::injectAudiblePoint(const AudiblePoint& audiblePoint, const QByteArray& samples, unsigned int sampleTime, int sampleRate) { bool wantEarSeparation = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingSeparateEars); @@ -444,13 +149,6 @@ void AudioReflector::injectAudiblePoint(const AudioPoint& audiblePoint, float rightEarDelayMsecs = getDelayFromDistance(rightEarDistance) + audiblePoint.delay; float leftEarDelayMsecs = getDelayFromDistance(leftEarDistance) + audiblePoint.delay; -/* -qDebug() << "injectAudiblePoint()... "; -qDebug() << " audiblePoint.delay=" << audiblePoint.delay; -qDebug() << " rightEarDelayMsecs=" << rightEarDelayMsecs; -qDebug() << " leftEarDelayMsecs=" << leftEarDelayMsecs; -*/ - _totalDelay += rightEarDelayMsecs + leftEarDelayMsecs; _delayCount += 2; _maxDelay = std::max(_maxDelay,rightEarDelayMsecs); @@ -464,13 +162,6 @@ qDebug() << " leftEarDelayMsecs=" << leftEarDelayMsecs; float rightEarAttenuation = audiblePoint.attenuation * getDistanceAttenuationCoefficient(rightEarDistance + audiblePoint.distance); float leftEarAttenuation = audiblePoint.attenuation * getDistanceAttenuationCoefficient(leftEarDistance + audiblePoint.distance); - /* - qDebug() << "audible point..."; - qDebug() << " audiblePoint.attenuation=" << audiblePoint.attenuation; - qDebug() << " rightEarAttenuation=" << rightEarAttenuation; - qDebug() << " leftEarAttenuation=" << leftEarAttenuation; - */ - _totalAttenuation += rightEarAttenuation + leftEarAttenuation; _attenuationCount += 2; _maxAttenuation = std::max(_maxAttenuation,rightEarAttenuation); @@ -486,23 +177,17 @@ qDebug() << " leftEarDelayMsecs=" << leftEarDelayMsecs; rightSample = originalSamplesData[(sample * NUMBER_OF_CHANNELS) + 1]; } - //qDebug() << "leftSample=" << leftSample << "rightSample=" << rightSample; attenuatedLeftSamplesData[sample * NUMBER_OF_CHANNELS] = leftSample * leftEarAttenuation; attenuatedLeftSamplesData[sample * NUMBER_OF_CHANNELS + 1] = 0; attenuatedRightSamplesData[sample * NUMBER_OF_CHANNELS] = 0; attenuatedRightSamplesData[sample * NUMBER_OF_CHANNELS + 1] = rightSample * rightEarAttenuation; - - //qDebug() << "attenuated... leftSample=" << (leftSample * leftEarAttenuation) << "rightSample=" << (rightSample * rightEarAttenuation); } // now inject the attenuated array with the appropriate delay - unsigned int sampleTimeLeft = sampleTime + leftEarDelay; unsigned int sampleTimeRight = sampleTime + rightEarDelay; - //qDebug() << "sampleTimeLeft=" << sampleTimeLeft << "sampleTimeRight=" << sampleTimeRight; - _audio->addSpatialAudioToBuffer(sampleTimeLeft, attenuatedLeftSamples, totalNumberOfSamples); _audio->addSpatialAudioToBuffer(sampleTimeRight, attenuatedRightSamples, totalNumberOfSamples); } @@ -511,14 +196,10 @@ void AudioReflector::processLocalAudio(unsigned int sampleTime, const QByteArray } void AudioReflector::processInboundAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { - if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions)) { - newEchoAudio(sampleTime, samples, format); - } else { - oldEchoAudio(sampleTime, samples, format); - } + echoAudio(sampleTime, samples, format); } -void AudioReflector::newEchoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { +void AudioReflector::echoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { _maxDelay = 0; _maxAttenuation = 0.0f; _minDelay = std::numeric_limits::max(); @@ -530,7 +211,7 @@ void AudioReflector::newEchoAudio(unsigned int sampleTime, const QByteArray& sam QMutexLocker locker(&_mutex); - foreach(const AudioPoint& audiblePoint, _audiblePoints) { + foreach(const AudiblePoint& audiblePoint, _audiblePoints) { injectAudiblePoint(audiblePoint, samples, sampleTime, format.sampleRate()); } @@ -545,84 +226,8 @@ void AudioReflector::newEchoAudio(unsigned int sampleTime, const QByteArray& sam } } -void AudioReflector::oldEchoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { - //quint64 start = usecTimestampNow(); - - _maxDelay = 0; - _maxAttenuation = 0.0f; - _minDelay = std::numeric_limits::max(); - _minAttenuation = std::numeric_limits::max(); - _totalDelay = 0.0f; - _delayCount = 0; - _totalAttenuation = 0.0f; - _attenuationCount = 0; - - QMutexLocker locker(&_mutex); - - echoReflections(_origin, _frontRightUpReflections, samples, sampleTime, format.sampleRate()); - echoReflections(_origin, _frontLeftUpReflections, samples, sampleTime, format.sampleRate()); - echoReflections(_origin, _backRightUpReflections, samples, sampleTime, format.sampleRate()); - echoReflections(_origin, _backLeftUpReflections, samples, sampleTime, format.sampleRate()); - echoReflections(_origin, _frontRightDownReflections, samples, sampleTime, format.sampleRate()); - echoReflections(_origin, _frontLeftDownReflections, samples, sampleTime, format.sampleRate()); - echoReflections(_origin, _backRightDownReflections, samples, sampleTime, format.sampleRate()); - echoReflections(_origin, _backLeftDownReflections, samples, sampleTime, format.sampleRate()); - - echoReflections(_origin, _frontReflections, samples, sampleTime, format.sampleRate()); - echoReflections(_origin, _backReflections, samples, sampleTime, format.sampleRate()); - echoReflections(_origin, _leftReflections, samples, sampleTime, format.sampleRate()); - echoReflections(_origin, _rightReflections, samples, sampleTime, format.sampleRate()); - echoReflections(_origin, _upReflections, samples, sampleTime, format.sampleRate()); - echoReflections(_origin, _downReflections, samples, sampleTime, format.sampleRate()); - - - _averageDelay = _delayCount == 0 ? 0 : _totalDelay / _delayCount; - _averageAttenuation = _attenuationCount == 0 ? 0 : _totalAttenuation / _attenuationCount; - _reflections = _frontRightUpReflections.size() + - _frontLeftUpReflections.size() + - _backRightUpReflections.size() + - _backLeftUpReflections.size() + - _frontRightDownReflections.size() + - _frontLeftDownReflections.size() + - _backRightDownReflections.size() + - _backLeftDownReflections.size() + - _frontReflections.size() + - _backReflections.size() + - _leftReflections.size() + - _rightReflections.size() + - _upReflections.size() + - _downReflections.size(); - _diffusionPathCount = 0; - - if (_reflections == 0) { - _minDelay = 0.0f; - _minAttenuation = 0.0f; - } -} - -void AudioReflector::drawRays() { - const glm::vec3 RED(1,0,0); - - QMutexLocker locker(&_mutex); - - drawReflections(_origin, RED, _frontRightUpReflections); - drawReflections(_origin, RED, _frontLeftUpReflections); - drawReflections(_origin, RED, _backRightUpReflections); - drawReflections(_origin, RED, _backLeftUpReflections); - drawReflections(_origin, RED, _frontRightDownReflections); - drawReflections(_origin, RED, _frontLeftDownReflections); - drawReflections(_origin, RED, _backRightDownReflections); - drawReflections(_origin, RED, _backLeftDownReflections); - drawReflections(_origin, RED, _frontReflections); - drawReflections(_origin, RED, _backReflections); - drawReflections(_origin, RED, _leftReflections); - drawReflections(_origin, RED, _rightReflections); - drawReflections(_origin, RED, _upReflections); - drawReflections(_origin, RED, _downReflections); -} - void AudioReflector::drawVector(const glm::vec3& start, const glm::vec3& end, const glm::vec3& color) { - glDisable(GL_LIGHTING); // ?? + glDisable(GL_LIGHTING); glLineWidth(2.0); // Draw the vector itself @@ -632,7 +237,7 @@ void AudioReflector::drawVector(const glm::vec3& start, const glm::vec3& end, co glVertex3f(end.x, end.y, end.z); glEnd(); - glEnable(GL_LIGHTING); // ?? + glEnable(GL_LIGHTING); } @@ -657,7 +262,6 @@ AudioPath::AudioPath(const glm::vec3& origin, const glm::vec3& direction, { } - void AudioReflector::addSoundSource(const glm::vec3& origin, const glm::vec3& initialDirection, float initialAttenuation, float initialDelay, float initialDistance) { @@ -665,7 +269,7 @@ void AudioReflector::addSoundSource(const glm::vec3& origin, const glm::vec3& in _audioPaths.push_back(path); } -void AudioReflector::newCalculateAllReflections() { +void AudioReflector::calculateAllReflections() { // only recalculate when we've moved... // TODO: what about case where new voxels are added in front of us??? bool wantHeadOrientation = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingHeadOriented); @@ -673,19 +277,15 @@ void AudioReflector::newCalculateAllReflections() { glm::vec3 origin = _myAvatar->getHead()->getPosition(); glm::vec3 listenerPosition = _myAvatar->getHead()->getPosition(); - bool withDiffusion = true; // this is the diffusion mode. + bool withDiffusion = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions); - // _audiblePoints.size() == 0 ?? - bool shouldRecalc = _reflections == 0 + bool shouldRecalc = _reflections == 0 || !isSimilarPosition(origin, _origin) || !isSimilarOrientation(orientation, _orientation) || !isSimilarPosition(listenerPosition, _listenerPosition) || (withDiffusion != _withDiffusion); if (shouldRecalc) { - -qDebug() << "RECALC...... !!!!!!!!!!!!!!!!!!!!!!!!!!!!"; - QMutexLocker locker(&_mutex); quint64 start = usecTimestampNow(); _origin = origin; @@ -701,7 +301,7 @@ qDebug() << "RECALC...... !!!!!!!!!!!!!!!!!!!!!!!!!!!!"; } } -void AudioReflector::newDrawRays() { +void AudioReflector::drawRays() { const glm::vec3 RED(1,0,0); const glm::vec3 GREEN(0,1,0); @@ -805,8 +405,8 @@ int AudioReflector::analyzePathsSingleStep() { int activePaths = 0; foreach(AudioPath* const& path, _audioPaths) { - bool wantExtraDebuggging = false; - bool isDiffusion = (path->startPoint != _origin); + //bool wantExtraDebuggging = false; + //bool isDiffusion = (path->startPoint != _origin); glm::vec3 start = path->lastPoint; glm::vec3 direction = path->lastDirection; @@ -823,22 +423,10 @@ int AudioReflector::analyzePathsSingleStep() { if (path->bounceCount > ABSOLUTE_MAXIMUM_BOUNCE_COUNT) { path->finalized = true; - if (wantExtraDebuggging && isDiffusion) { - qDebug() << "diffusion bounceCount too high!"; - } } else if (_voxels->findRayIntersection(start, direction, elementHit, distance, face, Octree::Lock)) { glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); pathDistance += glm::distance(start, end); - - - if (wantExtraDebuggging) { - qDebug() << "ray intersection... " - << " startPoint=[" << path->startPoint.x << "," << path->startPoint.y << "," << path->startPoint.z << "]" - << " bouceCount= " << path->bounceCount - << " end=[" << end.x << "," << end.y << "," << end.z << "]" - << " pathDistance=" << pathDistance; - } // We aren't using this... should we be???? float toListenerDistance = glm::distance(end, _listenerPosition); @@ -846,16 +434,17 @@ int AudioReflector::analyzePathsSingleStep() { // adjust our current delay by just the delay from the most recent ray currentDelay += getDelayFromDistance(distance); - // adjust our previous attenuation based on the distance traveled in last ray - //float distanceAttenuation = getDistanceAttenuationCoefficient(pathDistance); - // now we know the current attenuation for the "perfect" reflection case, but we now incorporate // our surface materials to determine how much of this ray is absorbed, reflected, and diffused SurfaceCharacteristics material = getSurfaceCharacteristics(elementHit); float reflectiveAttenuation = currentReflectiveAttenuation * material.reflectiveRatio; float totalDiffusionAttenuation = currentReflectiveAttenuation * material.diffusionRatio; - float partialDiffusionAttenuation = _diffusionFanout < 1 ? 0.0f : totalDiffusionAttenuation / _diffusionFanout; + + bool wantDiffusions = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions); + int fanout = wantDiffusions ? _diffusionFanout : 0; + + float partialDiffusionAttenuation = fanout < 1 ? 0.0f : totalDiffusionAttenuation / fanout; // total delay includes the bounce back to listener float totalDelay = currentDelay + getDelayFromDistance(toListenerDistance); @@ -867,7 +456,7 @@ int AudioReflector::analyzePathsSingleStep() { && totalDelay < MAXIMUM_DELAY_MS) { // diffusions fan out from random places on the semisphere of the collision point - for(int i = 0; i < _diffusionFanout; i++) { + for(int i = 0; i < fanout; i++) { glm::vec3 diffusion; float randomness = randFloatInRange(0.5f,1.0f); @@ -891,15 +480,6 @@ int AudioReflector::analyzePathsSingleStep() { diffusion = glm::normalize(diffusion); - if (wantExtraDebuggging) { - qDebug() << "DIFFUSION... addSoundSource()... " << - " partialDiffusionAttenuation=" << partialDiffusionAttenuation << "\n" << - " MINIMUM_ATTENUATION_TO_REFLECT=" << MINIMUM_ATTENUATION_TO_REFLECT << "\n" << - " direction=[" << direction.x << "," << direction.y << "," << direction.z << "]\n" << - " diffusion=[" << diffusion.x << "," << diffusion.y << "," << diffusion.z << "]\n" << - " end=[" << end.x << "," << end.y << "," << end.z << "]"; - } - // add sound sources for these diffusions addSoundSource(end, diffusion, partialDiffusionAttenuation, currentDelay, pathDistance); } @@ -907,16 +487,6 @@ int AudioReflector::analyzePathsSingleStep() { // if our reflective attenuation is above our minimum, then add our reflection point and // allow our path to continue - if (wantExtraDebuggging && isDiffusion) { - qDebug() << "checking diffusion"; - qDebug() << "reflectiveAttenuation=" << reflectiveAttenuation; - qDebug() << "totalDiffusionAttenuation=" << totalDiffusionAttenuation; - qDebug() << "toListenerAttenuation=" << toListenerAttenuation; - qDebug() << "(reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation=" << ((reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation); - } - - // we used to use... ((reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation) > MINIMUM_ATTENUATION_TO_REFLECT - if (((reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation) > MINIMUM_ATTENUATION_TO_REFLECT && totalDelay < MAXIMUM_DELAY_MS) { @@ -924,18 +494,8 @@ int AudioReflector::analyzePathsSingleStep() { // NOTE: we add the delay to the audible point, not back to the listener. The additional delay // and attenuation to the listener is recalculated at the point where we actually inject the // audio so that it can be adjusted to ear position - AudioPoint point = { end, currentDelay, - (reflectiveAttenuation + totalDiffusionAttenuation), - pathDistance}; + AudiblePoint point = {end, currentDelay, (reflectiveAttenuation + totalDiffusionAttenuation), pathDistance}; - /* - qDebug() << "audible point..."; - qDebug() << " reflectiveAttenuation=" << reflectiveAttenuation; - qDebug() << " toListenerAttenuation=" << toListenerAttenuation; - qDebug() << " likely attenuation=" << (reflectiveAttenuation * toListenerAttenuation); - qDebug() << " totalDiffusionAttenuation=" << totalDiffusionAttenuation; - */ - _audiblePoints.push_back(point); // add this location to the path points, so we can visualize it diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 9e5756e62c..54df80e938 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -36,7 +36,7 @@ public: QVector reflections; }; -class AudioPoint { +class AudiblePoint { public: glm::vec3 location; float delay; // includes total delay including pre delay to the point of the audible location, not to the listener's ears @@ -96,35 +96,11 @@ private: Audio* _audio; // access to audio API // Helpers for drawing - void drawRays(); void drawVector(const glm::vec3& start, const glm::vec3& end, const glm::vec3& color); - // OLD helper for playing audio - void echoReflections(const glm::vec3& origin, const QVector& reflections, const QByteArray& samples, - unsigned int sampleTime, int sampleRate); - - // OLD helper for calculating reflections - QVector calculateReflections(const glm::vec3& earPosition, const glm::vec3& origin, const glm::vec3& originalDirection); - void calculateDiffusions(const glm::vec3& earPosition, const glm::vec3& origin, - const glm::vec3& thisReflection, float thisDistance, float thisAttenuation, int thisBounceCount, - BoxFace thisReflectionFace, QVector reflectionPoints); - - - // OLD helper for drawing refections - void drawReflections(const glm::vec3& origin, const glm::vec3& originalColor, const QVector& reflections); - - // OLD helper for calculating reflections - void calculateAllReflections(); - - // resets statistics - void reset(); - // helper for generically calculating attenuation based on distance float getDistanceAttenuationCoefficient(float distance); - // helper for generically calculating attenuation based on bounce count, used in old/non-diffusion mode - float getBounceAttenuationCoefficient(int bounceCount); - // statistics int _reflections; int _diffusionPathCount; @@ -143,23 +119,6 @@ private: glm::vec3 _origin; glm::quat _orientation; - // old way of doing this... - QVector _frontRightUpReflections; - QVector _frontLeftUpReflections; - QVector _backRightUpReflections; - QVector _backLeftUpReflections; - QVector _frontRightDownReflections; - QVector _frontLeftDownReflections; - QVector _backRightDownReflections; - QVector _backLeftDownReflections; - QVector _frontReflections; - QVector _backReflections; - QVector _leftReflections; - QVector _rightReflections; - QVector _upReflections; - QVector _downReflections; - - // NOTE: Here's the new way, we will have an array of AudioPaths, we will loop on all of our currently calculating audio // paths, and calculate one ray per path. If that ray doesn't reflect, or reaches a max distance/attenuation, then it // is considered finalized. @@ -168,7 +127,7 @@ private: // fanout number of new paths, those new paths will have an origin of the reflection point, and an initial attenuation // of their diffusion ratio. Those new paths will be added to the active audio paths, and be analyzed for the next loop. QVector _audioPaths; - QVector _audiblePoints; + QVector _audiblePoints; // adds a sound source to begin an audio path trace, these can be the initial sound sources with their directional properties, // as well as diffusion sound sources @@ -178,15 +137,14 @@ private: // helper that handles audioPath analysis int analyzePathsSingleStep(); void analyzePaths(); - void newDrawRays(); + void drawRays(); void drawPath(AudioPath* path, const glm::vec3& originalColor); - void newCalculateAllReflections(); + void calculateAllReflections(); int countDiffusionPaths(); glm::vec3 getFaceNormal(BoxFace face); - void injectAudiblePoint(const AudioPoint& audiblePoint, const QByteArray& samples, unsigned int sampleTime, int sampleRate); - void oldEchoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); - void newEchoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); + void injectAudiblePoint(const AudiblePoint& audiblePoint, const QByteArray& samples, unsigned int sampleTime, int sampleRate); + void echoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); // return the surface characteristics of the element we hit SurfaceCharacteristics getSurfaceCharacteristics(OctreeElement* elementHit = NULL); diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp index 83b700484c..df47c9ad88 100644 --- a/interface/src/ui/Stats.cpp +++ b/interface/src/ui/Stats.cpp @@ -513,14 +513,16 @@ void Stats::display( // add some reflection stats char reflectionsStatus[128]; - sprintf(reflectionsStatus, "Reflections: %d, Original: %s, Ears: %s, Source: %s", + sprintf(reflectionsStatus, "Reflections: %d, Original: %s, Ears: %s, Source: %s, Normals: %s", audioReflector->getReflections(), (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingIncudeOriginal) ? "included" : "silent"), (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingSeparateEars) ? "two" : "one"), (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingStereoSource) - ? "stereo" : "mono") + ? "stereo" : "mono"), + (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingSlightlyRandomSurfaces) + ? "random" : "regular") ); verticalOffset += STATS_PELS_PER_LINE; From 8a16986294bb601e1e9a5d1689c4404589e4c9af Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 09:58:35 -0700 Subject: [PATCH 407/595] add sliders for reflection, diffusion, absorption --- examples/audioReflectorTools.js | 297 ++++++++++++++++++++++++++++--- interface/src/AudioReflector.cpp | 26 ++- interface/src/AudioReflector.h | 10 +- interface/src/ui/Stats.cpp | 14 +- 4 files changed, 309 insertions(+), 38 deletions(-) diff --git a/examples/audioReflectorTools.js b/examples/audioReflectorTools.js index ae9f43fddb..0467a4f937 100644 --- a/examples/audioReflectorTools.js +++ b/examples/audioReflectorTools.js @@ -14,12 +14,62 @@ var delayScale = 100.0; var fanoutScale = 10.0; var speedScale = 20; var factorScale = 5.0; +var reflectiveScale = 100.0; +var diffusionScale = 100.0; +var absorptionScale = 100.0; + +// these three properties are bound together, if you change one, the others will also change +var reflectiveRatio = AudioReflector.getReflectiveRatio(); +var diffusionRatio = AudioReflector.getDiffusionRatio(); +var absorptionRatio = AudioReflector.getAbsorptionRatio(); + +var reflectiveThumbX; +var diffusionThumbX; +var absorptionThumbX; + +function setReflectiveRatio(reflective) { + var total = diffusionRatio + absorptionRatio + (reflective / reflectiveScale); + diffusionRatio = diffusionRatio / total; + absorptionRatio = absorptionRatio / total; + reflectiveRatio = (reflective / reflectiveScale) / total; + updateRatioValues(); +} + +function setDiffusionRatio(diffusion) { + var total = (diffusion / diffusionScale) + absorptionRatio + reflectiveRatio; + diffusionRatio = (diffusion / diffusionScale) / total; + absorptionRatio = absorptionRatio / total; + reflectiveRatio = reflectiveRatio / total; + updateRatioValues(); +} + +function setAbsorptionRatio(absorption) { + var total = diffusionRatio + (absorption / absorptionScale) + reflectiveRatio; + diffusionRatio = diffusionRatio / total; + absorptionRatio = (absorption / absorptionScale) / total; + reflectiveRatio = reflectiveRatio / total; + updateRatioValues(); +} + +function updateRatioSliders() { + reflectiveThumbX = reflectiveMinThumbX + ((reflectiveMaxThumbX - reflectiveMinThumbX) * reflectiveRatio); + diffusionThumbX = diffusionMinThumbX + ((diffusionMaxThumbX - diffusionMinThumbX) * diffusionRatio); + absorptionThumbX = absorptionMinThumbX + ((absorptionMaxThumbX - absorptionMinThumbX) * absorptionRatio); + + Overlays.editOverlay(reflectiveThumb, { x: reflectiveThumbX } ); + Overlays.editOverlay(diffusionThumb, { x: diffusionThumbX } ); + Overlays.editOverlay(absorptionThumb, { x: absorptionThumbX } ); +} + +function updateRatioValues() { + AudioReflector.setReflectiveRatio(reflectiveRatio); + AudioReflector.setDiffusionRatio(diffusionRatio); + AudioReflector.setAbsorptionRatio(absorptionRatio); +} var topY = 250; var sliderHeight = 35; -// This will create a couple of image overlays that make a "slider", we will demonstrate how to trap mouse messages to -// move the slider var delayY = topY; topY += sliderHeight; var delayLabel = Overlays.addOverlay("text", { @@ -28,7 +78,7 @@ var delayLabel = Overlays.addOverlay("text", { width: 60, height: sliderHeight, color: { red: 0, green: 0, blue: 0}, - textColor: { red: 255, green: 0, blue: 0}, + textColor: { red: 255, green: 255, blue: 255}, topMargin: 12, leftMargin: 5, text: "Delay:" @@ -43,7 +93,7 @@ var delaySlider = Overlays.addOverlay("image", { alpha: 1 }); -// This is the thumb of our slider + var delayMinThumbX = 110; var delayMaxThumbX = delayMinThumbX + 110; var delayThumbX = delayMinThumbX + ((delayMaxThumbX - delayMinThumbX) * (AudioReflector.getPreDelay() / delayScale)); @@ -57,8 +107,6 @@ var delayThumb = Overlays.addOverlay("image", { alpha: 1 }); -// This will create a couple of image overlays that make a "slider", we will demonstrate how to trap mouse messages to -// move the slider var fanoutY = topY; topY += sliderHeight; @@ -68,7 +116,7 @@ var fanoutLabel = Overlays.addOverlay("text", { width: 60, height: sliderHeight, color: { red: 0, green: 0, blue: 0}, - textColor: { red: 255, green: 0, blue: 0}, + textColor: { red: 255, green: 255, blue: 255}, topMargin: 12, leftMargin: 5, text: "Fanout:" @@ -83,7 +131,7 @@ var fanoutSlider = Overlays.addOverlay("image", { alpha: 1 }); -// This is the thumb of our slider + var fanoutMinThumbX = 110; var fanoutMaxThumbX = fanoutMinThumbX + 110; var fanoutThumbX = fanoutMinThumbX + ((fanoutMaxThumbX - fanoutMinThumbX) * (AudioReflector.getDiffusionFanout() / fanoutScale)); @@ -98,8 +146,6 @@ var fanoutThumb = Overlays.addOverlay("image", { }); -// This will create a couple of image overlays that make a "slider", we will demonstrate how to trap mouse messages to -// move the slider var speedY = topY; topY += sliderHeight; @@ -109,7 +155,7 @@ var speedLabel = Overlays.addOverlay("text", { width: 60, height: sliderHeight, color: { red: 0, green: 0, blue: 0}, - textColor: { red: 255, green: 0, blue: 0}, + textColor: { red: 255, green: 255, blue: 255}, topMargin: 6, leftMargin: 5, text: "Speed\nin ms/m:" @@ -124,7 +170,7 @@ var speedSlider = Overlays.addOverlay("image", { alpha: 1 }); -// This is the thumb of our slider + var speedMinThumbX = 110; var speedMaxThumbX = speedMinThumbX + 110; var speedThumbX = speedMinThumbX + ((speedMaxThumbX - speedMinThumbX) * (AudioReflector.getSoundMsPerMeter() / speedScale)); @@ -138,8 +184,6 @@ var speedThumb = Overlays.addOverlay("image", { alpha: 1 }); -// This will create a couple of image overlays that make a "slider", we will demonstrate how to trap mouse messages to -// move the slider var factorY = topY; topY += sliderHeight; @@ -149,7 +193,7 @@ var factorLabel = Overlays.addOverlay("text", { width: 60, height: sliderHeight, color: { red: 0, green: 0, blue: 0}, - textColor: { red: 255, green: 0, blue: 0}, + textColor: { red: 255, green: 255, blue: 255}, topMargin: 6, leftMargin: 5, text: "Attenuation\nFactor:" @@ -165,7 +209,7 @@ var factorSlider = Overlays.addOverlay("image", { alpha: 1 }); -// This is the thumb of our slider + var factorMinThumbX = 110; var factorMaxThumbX = factorMinThumbX + 110; var factorThumbX = factorMinThumbX + ((factorMaxThumbX - factorMinThumbX) * (AudioReflector.getDistanceAttenuationScalingFactor() / factorScale)); @@ -179,6 +223,123 @@ var factorThumb = Overlays.addOverlay("image", { alpha: 1 }); +var reflectiveY = topY; +topY += sliderHeight; + +var reflectiveLabel = Overlays.addOverlay("text", { + x: 40, + y: reflectiveY, + width: 60, + height: sliderHeight, + color: { red: 0, green: 0, blue: 0}, + textColor: { red: 255, green: 255, blue: 255}, + topMargin: 6, + leftMargin: 5, + text: "Reflective\nRatio:" + }); + + +var reflectiveSlider = Overlays.addOverlay("image", { + // alternate form of expressing bounds + bounds: { x: 100, y: reflectiveY, width: 150, height: sliderHeight}, + subImage: { x: 46, y: 0, width: 200, height: 71 }, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/slider.png", + color: { red: 255, green: 255, blue: 255}, + alpha: 1 + }); + + +var reflectiveMinThumbX = 110; +var reflectiveMaxThumbX = reflectiveMinThumbX + 110; +reflectiveThumbX = reflectiveMinThumbX + ((reflectiveMaxThumbX - reflectiveMinThumbX) * AudioReflector.getReflectiveRatio()); +var reflectiveThumb = Overlays.addOverlay("image", { + x: reflectiveThumbX, + y: reflectiveY+9, + width: 18, + height: 17, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/thumb.png", + color: { red: 255, green: 255, blue: 255}, + alpha: 1 + }); + +var diffusionY = topY; +topY += sliderHeight; + +var diffusionLabel = Overlays.addOverlay("text", { + x: 40, + y: diffusionY, + width: 60, + height: sliderHeight, + color: { red: 0, green: 0, blue: 0}, + textColor: { red: 255, green: 255, blue: 255}, + topMargin: 6, + leftMargin: 5, + text: "Diffusion\nRatio:" + }); + + +var diffusionSlider = Overlays.addOverlay("image", { + // alternate form of expressing bounds + bounds: { x: 100, y: diffusionY, width: 150, height: sliderHeight}, + subImage: { x: 46, y: 0, width: 200, height: 71 }, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/slider.png", + color: { red: 255, green: 255, blue: 255}, + alpha: 1 + }); + + +var diffusionMinThumbX = 110; +var diffusionMaxThumbX = diffusionMinThumbX + 110; +diffusionThumbX = diffusionMinThumbX + ((diffusionMaxThumbX - diffusionMinThumbX) * AudioReflector.getDiffusionRatio()); +var diffusionThumb = Overlays.addOverlay("image", { + x: diffusionThumbX, + y: diffusionY+9, + width: 18, + height: 17, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/thumb.png", + color: { red: 0, green: 255, blue: 255}, + alpha: 1 + }); + +var absorptionY = topY; +topY += sliderHeight; + +var absorptionLabel = Overlays.addOverlay("text", { + x: 40, + y: absorptionY, + width: 60, + height: sliderHeight, + color: { red: 0, green: 0, blue: 0}, + textColor: { red: 255, green: 255, blue: 255}, + topMargin: 6, + leftMargin: 5, + text: "Absorption\nRatio:" + }); + + +var absorptionSlider = Overlays.addOverlay("image", { + // alternate form of expressing bounds + bounds: { x: 100, y: absorptionY, width: 150, height: sliderHeight}, + subImage: { x: 46, y: 0, width: 200, height: 71 }, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/slider.png", + color: { red: 255, green: 255, blue: 255}, + alpha: 1 + }); + + +var absorptionMinThumbX = 110; +var absorptionMaxThumbX = absorptionMinThumbX + 110; +absorptionThumbX = absorptionMinThumbX + ((absorptionMaxThumbX - absorptionMinThumbX) * AudioReflector.getAbsorptionRatio()); +var absorptionThumb = Overlays.addOverlay("image", { + x: absorptionThumbX, + y: absorptionY+9, + width: 18, + height: 17, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/thumb.png", + color: { red: 255, green: 0, blue: 255}, + alpha: 1 + }); + // When our script shuts down, we should clean up all of our overlays function scriptEnding() { @@ -197,6 +358,19 @@ function scriptEnding() { Overlays.deleteOverlay(fanoutLabel); Overlays.deleteOverlay(fanoutThumb); Overlays.deleteOverlay(fanoutSlider); + + Overlays.deleteOverlay(reflectiveLabel); + Overlays.deleteOverlay(reflectiveThumb); + Overlays.deleteOverlay(reflectiveSlider); + + Overlays.deleteOverlay(diffusionLabel); + Overlays.deleteOverlay(diffusionThumb); + Overlays.deleteOverlay(diffusionSlider); + + Overlays.deleteOverlay(absorptionLabel); + Overlays.deleteOverlay(absorptionThumb); + Overlays.deleteOverlay(absorptionSlider); + } Script.scriptEnding.connect(scriptEnding); @@ -215,6 +389,10 @@ var movingSliderDelay = false; var movingSliderFanout = false; var movingSliderSpeed = false; var movingSliderFactor = false; +var movingSliderReflective = false; +var movingSliderDiffusion = false; +var movingSliderAbsorption = false; + var thumbClickOffsetX = 0; function mouseMoveEvent(event) { if (movingSliderDelay) { @@ -227,7 +405,6 @@ function mouseMoveEvent(event) { } Overlays.editOverlay(delayThumb, { x: newThumbX } ); var delay = ((newThumbX - delayMinThumbX) / (delayMaxThumbX - delayMinThumbX)) * delayScale; - print("delay="+delay); AudioReflector.setPreDelay(delay); } if (movingSliderFanout) { @@ -240,7 +417,6 @@ function mouseMoveEvent(event) { } Overlays.editOverlay(fanoutThumb, { x: newThumbX } ); var fanout = Math.round(((newThumbX - fanoutMinThumbX) / (fanoutMaxThumbX - fanoutMinThumbX)) * fanoutScale); - print("fanout="+fanout); AudioReflector.setDiffusionFanout(fanout); } if (movingSliderSpeed) { @@ -267,47 +443,90 @@ function mouseMoveEvent(event) { var factor = ((newThumbX - factorMinThumbX) / (factorMaxThumbX - factorMinThumbX)) * factorScale; AudioReflector.setDistanceAttenuationScalingFactor(factor); } + + if (movingSliderAbsorption) { + newThumbX = event.x - thumbClickOffsetX; + if (newThumbX < absorptionMinThumbX) { + newThumbX = absorptionMminThumbX; + } + if (newThumbX > absorptionMaxThumbX) { + newThumbX = absorptionMaxThumbX; + } + Overlays.editOverlay(absorptionThumb, { x: newThumbX } ); + var absorption = ((newThumbX - absorptionMinThumbX) / (absorptionMaxThumbX - absorptionMinThumbX)) * absorptionScale; + setAbsorptionRatio(absorption); + } + + if (movingSliderReflective) { + newThumbX = event.x - thumbClickOffsetX; + if (newThumbX < reflectiveMinThumbX) { + newThumbX = reflectiveMminThumbX; + } + if (newThumbX > reflectiveMaxThumbX) { + newThumbX = reflectiveMaxThumbX; + } + Overlays.editOverlay(reflectiveThumb, { x: newThumbX } ); + var reflective = ((newThumbX - reflectiveMinThumbX) / (reflectiveMaxThumbX - reflectiveMinThumbX)) * reflectiveScale; + setReflectiveRatio(reflective); + } + + if (movingSliderDiffusion) { + newThumbX = event.x - thumbClickOffsetX; + if (newThumbX < diffusionMinThumbX) { + newThumbX = diffusionMminThumbX; + } + if (newThumbX > diffusionMaxThumbX) { + newThumbX = diffusionMaxThumbX; + } + Overlays.editOverlay(diffusionThumb, { x: newThumbX } ); + var diffusion = ((newThumbX - diffusionMinThumbX) / (diffusionMaxThumbX - diffusionMinThumbX)) * diffusionScale; + setDiffusionRatio(diffusion); + } + } // we also handle click detection in our mousePressEvent() function mousePressEvent(event) { var clickedOverlay = Overlays.getOverlayAtPoint({x: event.x, y: event.y}); - - // If the user clicked on the thumb, handle the slider logic if (clickedOverlay == delayThumb) { movingSliderDelay = true; thumbClickOffsetX = event.x - delayThumbX; } - // If the user clicked on the thumb, handle the slider logic if (clickedOverlay == fanoutThumb) { movingSliderFanout = true; thumbClickOffsetX = event.x - fanoutThumbX; } - // If the user clicked on the thumb, handle the slider logic if (clickedOverlay == speedThumb) { movingSliderSpeed = true; thumbClickOffsetX = event.x - speedThumbX; } - - // If the user clicked on the thumb, handle the slider logic if (clickedOverlay == factorThumb) { -print("movingSliderFactor..."); movingSliderFactor = true; thumbClickOffsetX = event.x - factorThumbX; } + if (clickedOverlay == diffusionThumb) { + movingSliderDiffusion = true; + thumbClickOffsetX = event.x - diffusionThumbX; + } + if (clickedOverlay == absorptionThumb) { + movingSliderAbsorption = true; + thumbClickOffsetX = event.x - absorptionThumbX; + } + if (clickedOverlay == reflectiveThumb) { + movingSliderReflective = true; + thumbClickOffsetX = event.x - reflectiveThumbX; + } } function mouseReleaseEvent(event) { if (movingSliderDelay) { movingSliderDelay = false; var delay = ((newThumbX - delayMinThumbX) / (delayMaxThumbX - delayMinThumbX)) * delayScale; - print("delay="+delay); AudioReflector.setPreDelay(delay); delayThumbX = newThumbX; } if (movingSliderFanout) { movingSliderFanout = false; var fanout = Math.round(((newThumbX - fanoutMinThumbX) / (fanoutMaxThumbX - fanoutMinThumbX)) * fanoutScale); - print("fanout="+fanout); AudioReflector.setDiffusionFanout(fanout); fanoutThumbX = newThumbX; } @@ -323,6 +542,30 @@ function mouseReleaseEvent(event) { AudioReflector.setDistanceAttenuationScalingFactor(factor); factorThumbX = newThumbX; } + + if (movingSliderReflective) { + movingSliderReflective = false; + var reflective = ((newThumbX - reflectiveMinThumbX) / (reflectiveMaxThumbX - reflectiveMinThumbX)) * reflectiveScale; + setReflectiveRatio(reflective); + reflectiveThumbX = newThumbX; + updateRatioSliders(); + } + + if (movingSliderDiffusion) { + movingSliderDiffusion = false; + var diffusion = ((newThumbX - diffusionMinThumbX) / (diffusionMaxThumbX - diffusionMinThumbX)) * diffusionScale; + setDiffusionRatio(diffusion); + diffusionThumbX = newThumbX; + updateRatioSliders(); + } + + if (movingSliderAbsorption) { + movingSliderAbsorption = false; + var absorption = ((newThumbX - absorptionMinThumbX) / (absorptionMaxThumbX - absorptionMinThumbX)) * absorptionScale; + setAbsorptionRatio(absorption); + absorptionThumbX = newThumbX; + updateRatioSliders(); + } } Controller.mouseMoveEvent.connect(mouseMoveEvent); diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index d9dc678886..1a1c1e3b10 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -11,7 +11,6 @@ #include "AudioReflector.h" #include "Menu.h" - const float DEFAULT_PRE_DELAY = 20.0f; // this delay in msecs will always be added to all reflections const float DEFAULT_MS_DELAY_PER_METER = 3.0f; const float MINIMUM_ATTENUATION_TO_REFLECT = 1.0f / 256.0f; @@ -45,7 +44,6 @@ AudioReflector::AudioReflector(QObject* parent) : _minDelay = 0; } - void AudioReflector::render() { // if we're not set up yet, or we're not processing spatial audio, then exit early @@ -159,8 +157,11 @@ void AudioReflector::injectAudiblePoint(const AudiblePoint& audiblePoint, int rightEarDelay = rightEarDelayMsecs * sampleRate / MSECS_PER_SECOND; int leftEarDelay = leftEarDelayMsecs * sampleRate / MSECS_PER_SECOND; - float rightEarAttenuation = audiblePoint.attenuation * getDistanceAttenuationCoefficient(rightEarDistance + audiblePoint.distance); - float leftEarAttenuation = audiblePoint.attenuation * getDistanceAttenuationCoefficient(leftEarDistance + audiblePoint.distance); + float rightEarAttenuation = audiblePoint.attenuation * + getDistanceAttenuationCoefficient(rightEarDistance + audiblePoint.distance); + + float leftEarAttenuation = audiblePoint.attenuation * + getDistanceAttenuationCoefficient(leftEarDistance + audiblePoint.distance); _totalAttenuation += rightEarAttenuation + leftEarAttenuation; _attenuationCount += 2; @@ -423,7 +424,12 @@ int AudioReflector::analyzePathsSingleStep() { if (path->bounceCount > ABSOLUTE_MAXIMUM_BOUNCE_COUNT) { path->finalized = true; - } else if (_voxels->findRayIntersection(start, direction, elementHit, distance, face, Octree::Lock)) { + } else if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { + // TODO: we need to decide how we want to handle locking on the ray intersection, if we force lock, + // we get an accurate picture, but it could prevent rendering of the voxels. If we trylock (default), + // we might not get ray intersections where they may exist, but we can't really detect that case... + // add last parameter of Octree::Lock to force locking + glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); pathDistance += glm::distance(start, end); @@ -525,9 +531,15 @@ int AudioReflector::analyzePathsSingleStep() { } SurfaceCharacteristics AudioReflector::getSurfaceCharacteristics(OctreeElement* elementHit) { - float reflectiveRatio = (1.0f - (_absorptionRatio + _diffusionRatio)); - SurfaceCharacteristics result = { reflectiveRatio, _absorptionRatio, _diffusionRatio }; + SurfaceCharacteristics result = { getReflectiveRatio(), _absorptionRatio, _diffusionRatio }; return result; } +void AudioReflector::setReflectiveRatio(float ratio) { + float currentReflectiveRatio = (1.0f - (_absorptionRatio + _diffusionRatio)); + float halfDifference = (ratio - currentReflectiveRatio) / 2.0f; + // evenly distribute the difference between the two other ratios + _absorptionRatio -= halfDifference; + _diffusionRatio -= halfDifference; +} diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 54df80e938..3a806e2267 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -84,10 +84,16 @@ public slots: void setSoundMsPerMeter(float soundMsPerMeter) { _soundMsPerMeter = soundMsPerMeter; } float getDistanceAttenuationScalingFactor() const { return _distanceAttenuationScalingFactor; } /// ms per meter, larger means slower void setDistanceAttenuationScalingFactor(float factor) { _distanceAttenuationScalingFactor = factor; } - int getDiffusionFanout() const { return _diffusionFanout; } /// number of points of diffusion from each reflection point void setDiffusionFanout(int fanout) { _diffusionFanout = fanout; } /// number of points of diffusion from each reflection point - + + float getAbsorptionRatio() const { return _absorptionRatio; } + void setAbsorptionRatio(float ratio) { _absorptionRatio = ratio; } + float getDiffusionRatio() const { return _diffusionRatio; } + void setDiffusionRatio(float ratio) { _diffusionRatio = ratio; } + float getReflectiveRatio() const { return (1.0f - (_absorptionRatio + _diffusionRatio)); } + void setReflectiveRatio(float ratio); + signals: private: diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp index df47c9ad88..2b70b3538c 100644 --- a/interface/src/ui/Stats.cpp +++ b/interface/src/ui/Stats.cpp @@ -343,7 +343,7 @@ void Stats::display( lines = _expanded ? 12 : 3; if (_expanded && Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessing)) { - lines += 5; // spatial audio processing adds 1 spacing line and 4 extra lines of info + lines += 6; // spatial audio processing adds 1 spacing line and 5 extra lines of info } drawBackground(backgroundColor, horizontalOffset, 0, glWidget->width() - horizontalOffset, lines * STATS_PELS_PER_LINE + 10); @@ -541,7 +541,7 @@ void Stats::display( verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); - sprintf(reflectionsStatus, "Attenuation: average %5.3f, max %5.3f, min %5.3f, distance scale: %5.3f", + sprintf(reflectionsStatus, "Attenuation: average %5.3f, max %5.3f, min %5.3f, Factor: %5.3f", audioReflector->getAverageAttenuation(), audioReflector->getMaxAttenuation(), audioReflector->getMinAttenuation(), @@ -559,6 +559,16 @@ void Stats::display( verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + const float AS_PERCENT = 100.0f; + float reflectiveRatio = audioReflector->getReflectiveRatio() * AS_PERCENT; + float diffusionRatio = audioReflector->getDiffusionRatio() * AS_PERCENT; + float absorptionRatio = audioReflector->getAbsorptionRatio() * AS_PERCENT; + sprintf(reflectionsStatus, "Ratios: Reflective: %5.3f, Diffusion: %5.3f, Absorption: %5.3f", + reflectiveRatio, diffusionRatio, absorptionRatio); + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + } } From 08b24343e5596ae22a2e8a06d34eb54aefcc1a80 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 15 Apr 2014 10:34:18 -0700 Subject: [PATCH 408/595] Added sounds provided by grayson and randomized their use. --- examples/editVoxels.js | 141 ++++++++++++++++++++++++++++++++--------- 1 file changed, 111 insertions(+), 30 deletions(-) diff --git a/examples/editVoxels.js b/examples/editVoxels.js index 31e8da8e74..b7b67a88f5 100644 --- a/examples/editVoxels.js +++ b/examples/editVoxels.js @@ -64,19 +64,92 @@ colors[8] = { red: 31, green: 64, blue: 64 }; var numColors = 9; var whichColor = -1; // Starting color is 'Copy' mode -// Create sounds for adding, deleting, recoloring voxels -var addSound1 = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Voxels/voxel+create+2.raw"); -var addSound2 = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Voxels/voxel+create+4.raw"); - -var addSound3 = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Voxels/voxel+create+3.raw"); -var deleteSound = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Voxels/voxel+delete+2.raw"); -var changeColorSound = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Voxels/voxel+edit+2.raw"); -var clickSound = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Switches+and+sliders/toggle+switch+-+medium.raw"); +// Create sounds for for every script actions that require one var audioOptions = new AudioInjectionOptions(); - -audioOptions.volume = 0.5; +audioOptions.volume = 1.0; audioOptions.position = Vec3.sum(MyAvatar.position, { x: 0, y: 1, z: 0 } ); // start with audio slightly above the avatar +function SoundArray() { + this.audioOptions = audioOptions + this.sounds = new Array(); + this.addSound = function (soundURL) { + this.sounds[this.sounds.length] = new Sound(soundURL); + } + this.play = function (index) { + if (0 <= index && index < this.sounds.length) { + Audio.playSound(this.sounds[index], this.audioOptions); + } else { + print("[ERROR] editVoxels.js:randSound.play() : Index " + index + " out of range."); + } + } + this.playRandom = function () { + if (this.sounds.length > 0) { + rand = Math.floor(Math.random() * this.sounds.length); + Audio.playSound(this.sounds[rand], this.audioOptions); + } else { + print("[ERROR] editVoxels.js:randSound.playRandom() : Array is empty."); + } + } +} + +var addVoxelSound = new SoundArray(); +addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+1.wav"); +addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+2.wav"); +addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+3.wav"); +addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+4.wav"); +addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+5.wav"); +addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+6.wav"); + +var delVoxelSound = new SoundArray(); +delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+A1.wav"); +delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+A2.wav"); +delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+A3.wav"); +delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+B1.wav"); +delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+B2.wav"); +delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+B3.wav"); + +var resizeVoxelSound = new SoundArray(); +resizeVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Size/V+Size+Minus.wav"); +resizeVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Size/V+Size+Plus.wav"); +var voxelSizeMinus = 0; +var voxelSizePlus = 1; + +var swatchesSound = new SoundArray(); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+1.wav"); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+2.wav"); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+3.wav"); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+4.wav"); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+5.wav"); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+6.wav"); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+7.wav"); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+8.wav"); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+9.wav"); + +var undoSound = new SoundArray(); +undoSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Undo/Undo+1.wav"); +undoSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Undo/Undo+2.wav"); +undoSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Undo/Undo+3.wav"); + +var scriptInitSound = new SoundArray(); +scriptInitSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Script+Init/Script+Init+A.wav"); +scriptInitSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Script+Init/Script+Init+B.wav"); +scriptInitSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Script+Init/Script+Init+C.wav"); +scriptInitSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Script+Init/Script+Init+D.wav"); + +var modeSwitchSound = new SoundArray(); +modeSwitchSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Mode+Switch/Mode+1.wav"); +modeSwitchSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Mode+Switch/Mode+2.wav"); +modeSwitchSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Mode+Switch/Mode+3.wav"); + +var initialVoxelSound = new SoundArray(); +initialVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Initial+Voxel/Initial+V.wav"); + +var colorInheritSound = new SoundArray(); +colorInheritSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Color+Inherit/Inherit+A.wav"); +colorInheritSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Color+Inherit/Inherit+B.wav"); +colorInheritSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Color+Inherit/Inherit+C.wav"); + + var editToolsOn = true; // starts out off // previewAsVoxel - by default, we will preview adds/deletes/recolors as just 4 lines on the intersecting face. But if you @@ -379,8 +452,17 @@ function calcThumbFromScale(scale) { if (thumbStep > pointerVoxelScaleSteps) { thumbStep = pointerVoxelScaleSteps; } + var oldThumbX = thumbX; thumbX = (thumbDeltaPerStep * (thumbStep - 1)) + minThumbX; Overlays.editOverlay(thumb, { x: thumbX + sliderX } ); + + if (thumbX > oldThumbX) { + resizeVoxelSound.play(voxelSizePlus); + print("Plus"); + } else if (thumbX < oldThumbX) { + resizeVoxelSound.play(voxelSizeMinus); + print("Minus"); + } } function calcScaleFromThumb(newThumbX) { @@ -443,15 +525,6 @@ var recolorToolSelected = false; var eyedropperToolSelected = false; var pasteMode = false; -function playRandomAddSound(audioOptions) { - if (Math.random() < 0.33) { - Audio.playSound(addSound1, audioOptions); - } else if (Math.random() < 0.5) { - Audio.playSound(addSound2, audioOptions); - } else { - Audio.playSound(addSound3, audioOptions); - } -} function calculateVoxelFromIntersection(intersection, operation) { //print("calculateVoxelFromIntersection() operation="+operation); @@ -744,7 +817,7 @@ function trackKeyReleaseEvent(event) { moveTools(); setAudioPosition(); // make sure we set the audio position before playing sounds showPreviewGuides(); - Audio.playSound(clickSound, audioOptions); + scriptInitSound.playRandom(); } if (event.text == "ALT") { @@ -808,21 +881,24 @@ function mousePressEvent(event) { Overlays.editOverlay(thumb, { imageURL: toolIconUrl + "voxel-size-slider-handle.svg", }); } else if (clickedOverlay == voxelTool) { - voxelToolSelected = true; + modeSwitchSound.play(0); + voxelToolSelected = !voxelToolSelected; recolorToolSelected = false; eyedropperToolSelected = false; moveTools(); clickedOnSomething = true; } else if (clickedOverlay == recolorTool) { + modeSwitchSound.play(1); voxelToolSelected = false; - recolorToolSelected = true; + recolorToolSelected = !recolorToolSelected; eyedropperToolSelected = false; moveTools(); clickedOnSomething = true; } else if (clickedOverlay == eyedropperTool) { + modeSwitchSound.play(2); voxelToolSelected = false; recolorToolSelected = false; - eyedropperToolSelected = true; + eyedropperToolSelected = !eyedropperToolSelected; moveTools(); clickedOnSomething = true; } else if (clickedOverlay == slider) { @@ -846,6 +922,7 @@ function mousePressEvent(event) { whichColor = s; moveTools(); clickedOnSomething = true; + swatchesSound.play(whichColor); break; } } @@ -888,7 +965,7 @@ function mousePressEvent(event) { // Delete voxel voxelDetails = calculateVoxelFromIntersection(intersection,"delete"); Voxels.eraseVoxel(voxelDetails.x, voxelDetails.y, voxelDetails.z, voxelDetails.s); - Audio.playSound(deleteSound, audioOptions); + delVoxelSound.playRandom(); Overlays.editOverlay(voxelPreview, { visible: false }); } else if (eyedropperToolSelected || trackAsEyedropper) { if (whichColor != -1) { @@ -896,6 +973,7 @@ function mousePressEvent(event) { colors[whichColor].green = intersection.voxel.green; colors[whichColor].blue = intersection.voxel.blue; moveTools(); + swatchesSound.play(whichColor); } } else if (recolorToolSelected || trackAsRecolor) { @@ -903,10 +981,9 @@ function mousePressEvent(event) { voxelDetails = calculateVoxelFromIntersection(intersection,"recolor"); // doing this erase then set will make sure we only recolor just the target voxel - Voxels.eraseVoxel(voxelDetails.x, voxelDetails.y, voxelDetails.z, voxelDetails.s); Voxels.setVoxel(voxelDetails.x, voxelDetails.y, voxelDetails.z, voxelDetails.s, colors[whichColor].red, colors[whichColor].green, colors[whichColor].blue); - Audio.playSound(changeColorSound, audioOptions); + swatchesSound.play(whichColor); Overlays.editOverlay(voxelPreview, { visible: false }); } else if (voxelToolSelected) { // Add voxel on face @@ -930,7 +1007,7 @@ function mousePressEvent(event) { lastVoxelColor = { red: newColor.red, green: newColor.green, blue: newColor.blue }; lastVoxelScale = voxelDetails.s; - playRandomAddSound(audioOptions); + addVoxelSound.playRandom(); Overlays.editOverlay(voxelPreview, { visible: false }); dragStart = { x: event.x, y: event.y }; @@ -946,12 +1023,12 @@ function keyPressEvent(event) { if (event.text == "`") { print("Color = Copy"); whichColor = -1; - Audio.playSound(clickSound, audioOptions); + colorInheritSound.playRandom(); moveTools(); } else if ((nVal > 0) && (nVal <= numColors)) { whichColor = nVal - 1; print("Color = " + (whichColor + 1)); - Audio.playSound(clickSound, audioOptions); + swatchesSound.play(whichColor); moveTools(); } else if (event.text == "0") { // Create a brand new 1 meter voxel in front of your avatar @@ -969,8 +1046,12 @@ function keyPressEvent(event) { Voxels.eraseVoxel(newVoxel.x, newVoxel.y, newVoxel.z, newVoxel.s); Voxels.setVoxel(newVoxel.x, newVoxel.y, newVoxel.z, newVoxel.s, newVoxel.red, newVoxel.green, newVoxel.blue); setAudioPosition(); - playRandomAddSound(audioOptions); + initialVoxelSound.playRandom(); + } else if (event.text == "z") { + undoSound.playRandom(); } + + } trackKeyPressEvent(event); // used by preview support From 1a3e6595c50507551864cc28545a225fffb094f2 Mon Sep 17 00:00:00 2001 From: Stojce Slavkovski Date: Tue, 15 Apr 2014 19:36:02 +0200 Subject: [PATCH 409/595] Allow users to set the destination of Snapshots --- interface/resources/styles/preferences.qss | 3 +- interface/src/Menu.cpp | 7 +- interface/src/Menu.h | 11 ++ interface/src/ui/PreferencesDialog.cpp | 18 +++ interface/src/ui/PreferencesDialog.h | 1 + interface/src/ui/Snapshot.cpp | 9 +- interface/ui/preferencesDialog.ui | 143 ++++++++++++++++++++- libraries/shared/src/FileUtils.cpp | 3 +- 8 files changed, 186 insertions(+), 9 deletions(-) diff --git a/interface/resources/styles/preferences.qss b/interface/resources/styles/preferences.qss index 643fd13a77..e678acd0c9 100644 --- a/interface/resources/styles/preferences.qss +++ b/interface/resources/styles/preferences.qss @@ -11,7 +11,8 @@ QLabel#advancedTuningLabel { } QPushButton#buttonBrowseHead, -QPushButton#buttonBrowseBody { +QPushButton#buttonBrowseBody, +QPushButton#buttonBrowseLocation { background-image: url(styles/search.svg); background-repeat: no-repeat; background-position: center center; diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 272dc39eb3..c9a1087618 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -25,7 +25,6 @@ #include #include #include -#include #include #include @@ -87,7 +86,8 @@ Menu::Menu() : _fpsAverage(FIVE_SECONDS_OF_FRAMES), _fastFPSAverage(ONE_SECOND_OF_FRAMES), _loginAction(NULL), - _preferencesDialog(NULL) + _preferencesDialog(NULL), + _snapshotsLocation() { Application *appInstance = Application::getInstance(); @@ -416,6 +416,8 @@ void Menu::loadSettings(QSettings* settings) { _maxVoxelPacketsPerSecond = loadSetting(settings, "maxVoxelsPPS", DEFAULT_MAX_VOXEL_PPS); _voxelSizeScale = loadSetting(settings, "voxelSizeScale", DEFAULT_OCTREE_SIZE_SCALE); _boundaryLevelAdjust = loadSetting(settings, "boundaryLevelAdjust", 0); + _snapshotsLocation = settings->value("snapshotsLocation", + QStandardPaths::writableLocation(QStandardPaths::DesktopLocation)).toString(); settings->beginGroup("View Frustum Offset Camera"); // in case settings is corrupt or missing loadSetting() will check for NaN @@ -455,6 +457,7 @@ void Menu::saveSettings(QSettings* settings) { settings->setValue("maxVoxelsPPS", _maxVoxelPacketsPerSecond); settings->setValue("voxelSizeScale", _voxelSizeScale); settings->setValue("boundaryLevelAdjust", _boundaryLevelAdjust); + settings->setValue("snapshotsLocation", _snapshotsLocation); settings->beginGroup("View Frustum Offset Camera"); settings->setValue("viewFrustumOffsetYaw", _viewFrustumOffset.yaw); settings->setValue("viewFrustumOffsetPitch", _viewFrustumOffset.pitch); diff --git a/interface/src/Menu.h b/interface/src/Menu.h index e827e43014..2c39ea3b99 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -12,10 +12,12 @@ #ifndef hifi_Menu_h #define hifi_Menu_h +#include #include #include #include #include +#include #include #include @@ -79,6 +81,14 @@ public: void setFieldOfView(float fieldOfView) { _fieldOfView = fieldOfView; } float getFaceshiftEyeDeflection() const { return _faceshiftEyeDeflection; } void setFaceshiftEyeDeflection(float faceshiftEyeDeflection) { _faceshiftEyeDeflection = faceshiftEyeDeflection; } + QString getSnapshotsLocation() const { + if (_snapshotsLocation.isNull() || _snapshotsLocation.isEmpty() || QDir(_snapshotsLocation).exists() == false) { + return QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); + } + return _snapshotsLocation; + } + void setSnapshotsLocation(QString snapshotsLocation) { _snapshotsLocation = snapshotsLocation; } + BandwidthDialog* getBandwidthDialog() const { return _bandwidthDialog; } FrustumDrawMode getFrustumDrawMode() const { return _frustumDrawMode; } ViewFrustumOffset getViewFrustumOffset() const { return _viewFrustumOffset; } @@ -229,6 +239,7 @@ private: QAction* _loginAction; QPointer _preferencesDialog; QAction* _chatAction; + QString _snapshotsLocation; }; namespace MenuOption { diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index a14e80e62f..36508e94d1 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -28,6 +28,7 @@ PreferencesDialog::PreferencesDialog(QWidget* parent, Qt::WindowFlags flags) : F connect(ui.buttonBrowseHead, &QPushButton::clicked, this, &PreferencesDialog::openHeadModelBrowser); connect(ui.buttonBrowseBody, &QPushButton::clicked, this, &PreferencesDialog::openBodyModelBrowser); + connect(ui.buttonBrowseLocation, &QPushButton::clicked, this, &PreferencesDialog::openSnapshotLocationBrowser); } void PreferencesDialog::accept() { @@ -59,6 +60,17 @@ void PreferencesDialog::openBodyModelBrowser() { modelBrowser.browse(); } +void PreferencesDialog::openSnapshotLocationBrowser() { + setWindowFlags(windowFlags() & ~Qt::WindowStaysOnTopHint); + QString dir = QFileDialog::getExistingDirectory(this, tr("Snapshots Location"), + QStandardPaths::writableLocation(QStandardPaths::DesktopLocation), + QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); + if (!dir.isNull() && !dir.isEmpty()) { + ui.snapshotLocationEdit->setText(dir); + } + setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint); +} + void PreferencesDialog::resizeEvent(QResizeEvent *resizeEvent) { // keep buttons panel at the bottom @@ -94,6 +106,8 @@ void PreferencesDialog::loadPreferences() { _skeletonURLString = myAvatar->getSkeletonModel().getURL().toString(); ui.skeletonURLEdit->setText(_skeletonURLString); + ui.snapshotLocationEdit->setText(menuInstance->getSnapshotsLocation()); + ui.pupilDilationSlider->setValue(myAvatar->getHead()->getPupilDilation() * ui.pupilDilationSlider->maximum()); @@ -143,6 +157,10 @@ void PreferencesDialog::savePreferences() { Application::getInstance()->bumpSettings(); } + if (!ui.snapshotLocationEdit->text().isEmpty() && QDir(ui.snapshotLocationEdit->text()).exists()) { + Menu::getInstance()->setSnapshotsLocation(ui.snapshotLocationEdit->text()); + } + myAvatar->getHead()->setPupilDilation(ui.pupilDilationSlider->value() / (float)ui.pupilDilationSlider->maximum()); myAvatar->setLeanScale(ui.leanScaleSpin->value()); myAvatar->setClampedTargetScale(ui.avatarScaleSpin->value()); diff --git a/interface/src/ui/PreferencesDialog.h b/interface/src/ui/PreferencesDialog.h index c9514e584a..c52986cc5c 100644 --- a/interface/src/ui/PreferencesDialog.h +++ b/interface/src/ui/PreferencesDialog.h @@ -41,6 +41,7 @@ private slots: void accept(); void setHeadUrl(QString modelUrl); void setSkeletonUrl(QString modelUrl); + void openSnapshotLocationBrowser(); }; diff --git a/interface/src/ui/Snapshot.cpp b/interface/src/ui/Snapshot.cpp index 77b19373f4..29c2d3c90f 100644 --- a/interface/src/ui/Snapshot.cpp +++ b/interface/src/ui/Snapshot.cpp @@ -16,6 +16,7 @@ #include #include "Snapshot.h" +#include "Menu.h" // filename format: hifi-snap-by-%username%-on-%date%_%time%_@-%location%.jpg // %1 <= username, %2 <= date and time, %3 <= current location @@ -90,8 +91,12 @@ void Snapshot::saveSnapshot(QGLWidget* widget, Avatar* avatar) { username.replace(QRegExp("[^A-Za-z0-9_]"), "-"); QDateTime now = QDateTime::currentDateTime(); - - QString fileName = FileUtils::standardPath(SNAPSHOTS_DIRECTORY); + QString fileName = Menu::getInstance()->getSnapshotsLocation(); + + if (!fileName.endsWith(QDir::separator())) { + fileName.append(QDir::separator()); + } + fileName.append(QString(FILENAME_PATH_FORMAT.arg(username, now.toString(DATETIME_FORMAT), formattedLocation))); shot.save(fileName, 0, 100); } diff --git a/interface/ui/preferencesDialog.ui b/interface/ui/preferencesDialog.ui index a151a499c6..3ad824a35e 100644 --- a/interface/ui/preferencesDialog.ui +++ b/interface/ui/preferencesDialog.ui @@ -156,7 +156,7 @@ color: #0e7077 0 0 615 - 833 + 936 @@ -300,7 +300,7 @@ color: #0e7077 0 - faceURLEdit + snapshotLocationEdit @@ -476,6 +476,145 @@ color: #0e7077 + + + + + 0 + 0 + + + + + 0 + 40 + + + + + Arial + 20 + 50 + false + + + + color: #0e7077 + + + Snapshots + + + Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft + + + + + + + + 0 + 0 + + + + + 0 + 30 + + + + + Arial + 16 + + + + color: #0e7077 + + + Snapshots location + + + Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft + + + 0 + + + snapshotLocationEdit + + + + + + + + + + 0 + 0 + + + + + Arial + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + + 0 + 0 + + + + + 30 + 30 + + + + + 30 + 30 + + + + + + + + + + + 30 + 30 + + + + + + diff --git a/libraries/shared/src/FileUtils.cpp b/libraries/shared/src/FileUtils.cpp index b890717a66..fe79f6c527 100644 --- a/libraries/shared/src/FileUtils.cpp +++ b/libraries/shared/src/FileUtils.cpp @@ -61,8 +61,7 @@ void FileUtils::locateFile(QString filePath) { QString FileUtils::standardPath(QString subfolder) { // standard path // Mac: ~/Library/Application Support/Interface - QString path = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation); - path.append("/Interface"); + QString path = QStandardPaths::writableLocation(QStandardPaths::DataLocation); if (!subfolder.startsWith("/")) { subfolder.prepend("/"); From c323249039577a3607160b7caca0c6182fbabff0 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 15 Apr 2014 10:38:28 -0700 Subject: [PATCH 410/595] Remove bad change --- examples/editVoxels.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/editVoxels.js b/examples/editVoxels.js index b7b67a88f5..059b4186a3 100644 --- a/examples/editVoxels.js +++ b/examples/editVoxels.js @@ -882,7 +882,7 @@ function mousePressEvent(event) { } else if (clickedOverlay == voxelTool) { modeSwitchSound.play(0); - voxelToolSelected = !voxelToolSelected; + voxelToolSelected = true; recolorToolSelected = false; eyedropperToolSelected = false; moveTools(); @@ -890,7 +890,7 @@ function mousePressEvent(event) { } else if (clickedOverlay == recolorTool) { modeSwitchSound.play(1); voxelToolSelected = false; - recolorToolSelected = !recolorToolSelected; + recolorToolSelected = true; eyedropperToolSelected = false; moveTools(); clickedOnSomething = true; @@ -898,7 +898,7 @@ function mousePressEvent(event) { modeSwitchSound.play(2); voxelToolSelected = false; recolorToolSelected = false; - eyedropperToolSelected = !eyedropperToolSelected; + eyedropperToolSelected = true; moveTools(); clickedOnSomething = true; } else if (clickedOverlay == slider) { From 60c6b27ab2785ca7d37d912722cefdda2702cceb Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 11:38:11 -0700 Subject: [PATCH 411/595] cleanup code a bit, add support for diffusions even with no ray intersection --- interface/src/AudioReflector.cpp | 277 ++++++++++++++++----------- interface/src/AudioReflector.h | 9 +- libraries/octree/src/AABox.h | 3 +- libraries/shared/src/SharedUtil.cpp | 4 + libraries/shared/src/SharedUtil.h | 1 + libraries/voxels/src/VoxelDetail.cpp | 3 + 6 files changed, 185 insertions(+), 112 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 1a1c1e3b10..7801c26924 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -91,13 +91,14 @@ float AudioReflector::getDistanceAttenuationCoefficient(float distance) { glm::vec3 AudioReflector::getFaceNormal(BoxFace face) { bool wantSlightRandomness = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingSlightlyRandomSurfaces); - glm::vec3 faceNormal; - - float normalLength = wantSlightRandomness ? randFloatInRange(0.99f,1.0f) : 1.0f; + const float MIN_RANDOM_LENGTH = 0.99f; + const float MAX_RANDOM_LENGTH = 1.0f; + const float NON_RANDOM_LENGTH = 1.0f; + float normalLength = wantSlightRandomness ? randFloatInRange(MIN_RANDOM_LENGTH, MAX_RANDOM_LENGTH) : NON_RANDOM_LENGTH; float remainder = (1.0f - normalLength)/2.0f; - float remainderSignA = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; - float remainderSignB = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; + float remainderSignA = randomSign(); + float remainderSignB = randomSign(); if (face == MIN_X_FACE) { faceNormal = glm::vec3(-normalLength, remainder * remainderSignA, remainder * remainderSignB); @@ -244,8 +245,9 @@ void AudioReflector::drawVector(const glm::vec3& start, const glm::vec3& end, co AudioPath::AudioPath(const glm::vec3& origin, const glm::vec3& direction, - float attenuation, float delay, float distance, int bounceCount) : + float attenuation, float delay, float distance,bool isDiffusion, int bounceCount) : + isDiffusion(isDiffusion), startPoint(origin), startDirection(direction), startDelay(delay), @@ -264,9 +266,10 @@ AudioPath::AudioPath(const glm::vec3& origin, const glm::vec3& direction, } void AudioReflector::addSoundSource(const glm::vec3& origin, const glm::vec3& initialDirection, - float initialAttenuation, float initialDelay, float initialDistance) { + float initialAttenuation, float initialDelay, float initialDistance, bool isDiffusion) { - AudioPath* path = new AudioPath(origin, initialDirection, initialAttenuation, initialDelay, initialDistance, 0); + AudioPath* path = new AudioPath(origin, initialDirection, initialAttenuation, initialDelay, + initialDistance, isDiffusion, 0); _audioPaths.push_back(path); } @@ -312,11 +315,11 @@ void AudioReflector::drawRays() { foreach(AudioPath* const& path, _audioPaths) { // if this is an original reflection, draw it in RED - if (path->startPoint == _origin) { - drawPath(path, RED); - } else { + if (path->isDiffusion) { diffusionNumber++; drawPath(path, GREEN); + } else { + drawPath(path, RED); } } } @@ -415,10 +418,6 @@ int AudioReflector::analyzePathsSingleStep() { float distance; // output from findRayIntersection BoxFace face; // output from findRayIntersection - float currentReflectiveAttenuation = path->lastAttenuation; // only the reflective components - float currentDelay = path->lastDelay; // start with our delay so far - float pathDistance = path->lastDistance; - if (!path->finalized) { activePaths++; @@ -429,107 +428,169 @@ int AudioReflector::analyzePathsSingleStep() { // we get an accurate picture, but it could prevent rendering of the voxels. If we trylock (default), // we might not get ray intersections where they may exist, but we can't really detect that case... // add last parameter of Octree::Lock to force locking - - glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); + handlePathPoint(path, distance, elementHit, face); - pathDistance += glm::distance(start, end); - - // We aren't using this... should we be???? - float toListenerDistance = glm::distance(end, _listenerPosition); - - // adjust our current delay by just the delay from the most recent ray - currentDelay += getDelayFromDistance(distance); - - // now we know the current attenuation for the "perfect" reflection case, but we now incorporate - // our surface materials to determine how much of this ray is absorbed, reflected, and diffused - SurfaceCharacteristics material = getSurfaceCharacteristics(elementHit); - - float reflectiveAttenuation = currentReflectiveAttenuation * material.reflectiveRatio; - float totalDiffusionAttenuation = currentReflectiveAttenuation * material.diffusionRatio; - - bool wantDiffusions = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions); - int fanout = wantDiffusions ? _diffusionFanout : 0; - - float partialDiffusionAttenuation = fanout < 1 ? 0.0f : totalDiffusionAttenuation / fanout; - - // total delay includes the bounce back to listener - float totalDelay = currentDelay + getDelayFromDistance(toListenerDistance); - float toListenerAttenuation = getDistanceAttenuationCoefficient(toListenerDistance + pathDistance); - - // if our resulting partial diffusion attenuation, is still above our minimum attenuation - // then we add new paths for each diffusion point - if ((partialDiffusionAttenuation * toListenerAttenuation) > MINIMUM_ATTENUATION_TO_REFLECT - && totalDelay < MAXIMUM_DELAY_MS) { - - // diffusions fan out from random places on the semisphere of the collision point - for(int i = 0; i < fanout; i++) { - glm::vec3 diffusion; - - float randomness = randFloatInRange(0.5f,1.0f); - float remainder = (1.0f - randomness)/2.0f; - float remainderSignA = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; - float remainderSignB = (randFloatInRange(-1.0f,1.0f) < 0.0f) ? -1.0 : 1.0; - - if (face == MIN_X_FACE) { - diffusion = glm::vec3(-randomness, remainder * remainderSignA, remainder * remainderSignB); - } else if (face == MAX_X_FACE) { - diffusion = glm::vec3(randomness, remainder * remainderSignA, remainder * remainderSignB); - } else if (face == MIN_Y_FACE) { - diffusion = glm::vec3(remainder * remainderSignA, -randomness, remainder * remainderSignB); - } else if (face == MAX_Y_FACE) { - diffusion = glm::vec3(remainder * remainderSignA, randomness, remainder * remainderSignB); - } else if (face == MIN_Z_FACE) { - diffusion = glm::vec3(remainder * remainderSignA, remainder * remainderSignB, -randomness); - } else if (face == MAX_Z_FACE) { - diffusion = glm::vec3(remainder * remainderSignA, remainder * remainderSignB, randomness); - } - - diffusion = glm::normalize(diffusion); - - // add sound sources for these diffusions - addSoundSource(end, diffusion, partialDiffusionAttenuation, currentDelay, pathDistance); - } - } - - // if our reflective attenuation is above our minimum, then add our reflection point and - // allow our path to continue - if (((reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation) > MINIMUM_ATTENUATION_TO_REFLECT - && totalDelay < MAXIMUM_DELAY_MS) { - - // add this location, as the reflective attenuation as well as the total diffusion attenuation - // NOTE: we add the delay to the audible point, not back to the listener. The additional delay - // and attenuation to the listener is recalculated at the point where we actually inject the - // audio so that it can be adjusted to ear position - AudiblePoint point = {end, currentDelay, (reflectiveAttenuation + totalDiffusionAttenuation), pathDistance}; - - _audiblePoints.push_back(point); - - // add this location to the path points, so we can visualize it - path->reflections.push_back(end); - - // now, if our reflective attenuation is over our minimum then keep going... - if (reflectiveAttenuation * toListenerAttenuation > MINIMUM_ATTENUATION_TO_REFLECT) { - glm::vec3 faceNormal = getFaceNormal(face); - path->lastDirection = glm::normalize(glm::reflect(direction,faceNormal)); - path->lastPoint = end; - path->lastAttenuation = reflectiveAttenuation; - path->lastDelay = currentDelay; - path->lastDistance = pathDistance; - path->bounceCount++; - } else { - path->finalized = true; // if we're too quiet, then we're done - } - } else { - path->finalized = true; // if we're too quiet, then we're done - } } else { - path->finalized = true; // if it doesn't intersect, then it is finished + // If we didn't intersect, but this was a diffusion ray, then we will go ahead and cast a short ray out + // from our last known point, in the last known direction, and leave that sound source hanging there + if (path->isDiffusion) { + const float MINIMUM_RANDOM_DISTANCE = 0.25f; + const float MAXIMUM_RANDOM_DISTANCE = 0.5f; + float distance = randFloatInRange(MINIMUM_RANDOM_DISTANCE, MAXIMUM_RANDOM_DISTANCE); + handlePathPoint(path, distance, NULL, UNKNOWN_FACE); + } else { + path->finalized = true; // if it doesn't intersect, then it is finished + } } } } return activePaths; } +void AudioReflector::handlePathPoint(AudioPath* path, float distance, OctreeElement* elementHit, BoxFace face) { + glm::vec3 start = path->lastPoint; + glm::vec3 direction = path->lastDirection; + glm::vec3 end = start + (direction * (distance * SLIGHTLY_SHORT)); + + float currentReflectiveAttenuation = path->lastAttenuation; // only the reflective components + float currentDelay = path->lastDelay; // start with our delay so far + float pathDistance = path->lastDistance; + + pathDistance += glm::distance(start, end); + + // We aren't using this... should we be???? + float toListenerDistance = glm::distance(end, _listenerPosition); + + // adjust our current delay by just the delay from the most recent ray + currentDelay += getDelayFromDistance(distance); + + // now we know the current attenuation for the "perfect" reflection case, but we now incorporate + // our surface materials to determine how much of this ray is absorbed, reflected, and diffused + SurfaceCharacteristics material = getSurfaceCharacteristics(elementHit); + + float reflectiveAttenuation = currentReflectiveAttenuation * material.reflectiveRatio; + float totalDiffusionAttenuation = currentReflectiveAttenuation * material.diffusionRatio; + + bool wantDiffusions = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions); + int fanout = wantDiffusions ? _diffusionFanout : 0; + + float partialDiffusionAttenuation = fanout < 1 ? 0.0f : totalDiffusionAttenuation / fanout; + + // total delay includes the bounce back to listener + float totalDelay = currentDelay + getDelayFromDistance(toListenerDistance); + float toListenerAttenuation = getDistanceAttenuationCoefficient(toListenerDistance + pathDistance); + + // if our resulting partial diffusion attenuation, is still above our minimum attenuation + // then we add new paths for each diffusion point + if ((partialDiffusionAttenuation * toListenerAttenuation) > MINIMUM_ATTENUATION_TO_REFLECT + && totalDelay < MAXIMUM_DELAY_MS) { + + // diffusions fan out from random places on the semisphere of the collision point + for(int i = 0; i < fanout; i++) { + glm::vec3 diffusion; + + // We're creating a random normal here. But we want it to be relatively dramatic compared to how we handle + // our slightly random surface normals. + const float MINIMUM_RANDOM_LENGTH = 0.5f; + const float MAXIMUM_RANDOM_LENGTH = 1.0f; + float randomness = randFloatInRange(MINIMUM_RANDOM_LENGTH, MAXIMUM_RANDOM_LENGTH); + float remainder = (1.0f - randomness)/2.0f; + float remainderSignA = randomSign(); + float remainderSignB = randomSign(); + + if (face == MIN_X_FACE) { + diffusion = glm::vec3(-randomness, remainder * remainderSignA, remainder * remainderSignB); + } else if (face == MAX_X_FACE) { + diffusion = glm::vec3(randomness, remainder * remainderSignA, remainder * remainderSignB); + } else if (face == MIN_Y_FACE) { + diffusion = glm::vec3(remainder * remainderSignA, -randomness, remainder * remainderSignB); + } else if (face == MAX_Y_FACE) { + diffusion = glm::vec3(remainder * remainderSignA, randomness, remainder * remainderSignB); + } else if (face == MIN_Z_FACE) { + diffusion = glm::vec3(remainder * remainderSignA, remainder * remainderSignB, -randomness); + } else if (face == MAX_Z_FACE) { + diffusion = glm::vec3(remainder * remainderSignA, remainder * remainderSignB, randomness); + } else if (face == UNKNOWN_FACE) { + float randomnessX = randFloatInRange(MINIMUM_RANDOM_LENGTH, MAXIMUM_RANDOM_LENGTH); + float randomnessY = randFloatInRange(MINIMUM_RANDOM_LENGTH, MAXIMUM_RANDOM_LENGTH); + float randomnessZ = randFloatInRange(MINIMUM_RANDOM_LENGTH, MAXIMUM_RANDOM_LENGTH); + diffusion = glm::vec3(direction.x * randomnessX, direction.y * randomnessY, direction.z * randomnessZ); + } + + diffusion = glm::normalize(diffusion); + + // add sound sources for these diffusions + addSoundSource(end, diffusion, partialDiffusionAttenuation, currentDelay, pathDistance, true); + } + } else { + const bool wantDebugging = false; + if (wantDebugging) { + if ((partialDiffusionAttenuation * toListenerAttenuation) <= MINIMUM_ATTENUATION_TO_REFLECT) { + qDebug() << "too quiet to diffuse"; + qDebug() << " partialDiffusionAttenuation=" << partialDiffusionAttenuation; + qDebug() << " toListenerAttenuation=" << toListenerAttenuation; + qDebug() << " result=" << (partialDiffusionAttenuation * toListenerAttenuation); + qDebug() << " MINIMUM_ATTENUATION_TO_REFLECT=" << MINIMUM_ATTENUATION_TO_REFLECT; + } + if (totalDelay > MAXIMUM_DELAY_MS) { + qDebug() << "too delayed to diffuse"; + qDebug() << " totalDelay=" << totalDelay; + qDebug() << " MAXIMUM_DELAY_MS=" << MAXIMUM_DELAY_MS; + } + } + } + + // if our reflective attenuation is above our minimum, then add our reflection point and + // allow our path to continue + if (((reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation) > MINIMUM_ATTENUATION_TO_REFLECT + && totalDelay < MAXIMUM_DELAY_MS) { + + // add this location, as the reflective attenuation as well as the total diffusion attenuation + // NOTE: we add the delay to the audible point, not back to the listener. The additional delay + // and attenuation to the listener is recalculated at the point where we actually inject the + // audio so that it can be adjusted to ear position + AudiblePoint point = {end, currentDelay, (reflectiveAttenuation + totalDiffusionAttenuation), pathDistance}; + + _audiblePoints.push_back(point); + + // add this location to the path points, so we can visualize it + path->reflections.push_back(end); + + // now, if our reflective attenuation is over our minimum then keep going... + if (reflectiveAttenuation * toListenerAttenuation > MINIMUM_ATTENUATION_TO_REFLECT) { + glm::vec3 faceNormal = getFaceNormal(face); + path->lastDirection = glm::normalize(glm::reflect(direction,faceNormal)); + path->lastPoint = end; + path->lastAttenuation = reflectiveAttenuation; + path->lastDelay = currentDelay; + path->lastDistance = pathDistance; + path->bounceCount++; + } else { + path->finalized = true; // if we're too quiet, then we're done + } + } else { + const bool wantDebugging = false; + if (wantDebugging) { + if (((reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation) <= MINIMUM_ATTENUATION_TO_REFLECT) { + qDebug() << "too quiet to add audible point"; + qDebug() << " reflectiveAttenuation + totalDiffusionAttenuation=" << (reflectiveAttenuation + totalDiffusionAttenuation); + qDebug() << " toListenerAttenuation=" << toListenerAttenuation; + qDebug() << " result=" << ((reflectiveAttenuation + totalDiffusionAttenuation) * toListenerAttenuation); + qDebug() << " MINIMUM_ATTENUATION_TO_REFLECT=" << MINIMUM_ATTENUATION_TO_REFLECT; + } + if (totalDelay > MAXIMUM_DELAY_MS) { + qDebug() << "too delayed to add audible point"; + qDebug() << " totalDelay=" << totalDelay; + qDebug() << " MAXIMUM_DELAY_MS=" << MAXIMUM_DELAY_MS; + } + } + path->finalized = true; // if we're too quiet, then we're done + } +} + +// TODO: eventually we will add support for different surface characteristics based on the element +// that is hit, which is why we pass in the elementHit to this helper function. But for now, all +// surfaces have the same characteristics SurfaceCharacteristics AudioReflector::getSurfaceCharacteristics(OctreeElement* elementHit) { SurfaceCharacteristics result = { getReflectiveRatio(), _absorptionRatio, _diffusionRatio }; return result; diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 3a806e2267..72eca9aac2 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -19,7 +19,9 @@ class AudioPath { public: AudioPath(const glm::vec3& origin = glm::vec3(0), const glm::vec3& direction = glm::vec3(0), float attenuation = 1.0f, - float delay = 0.0f, float distance = 0.0f, int bounceCount = 0); + float delay = 0.0f, float distance = 0.0f, bool isDiffusion = false, int bounceCount = 0); + + bool isDiffusion; glm::vec3 startPoint; glm::vec3 startDirection; float startDelay; @@ -137,11 +139,12 @@ private: // adds a sound source to begin an audio path trace, these can be the initial sound sources with their directional properties, // as well as diffusion sound sources - void addSoundSource(const glm::vec3& origin, const glm::vec3& initialDirection, - float initialAttenuation, float initialDelay, float initialDistance = 0.0f); + void addSoundSource(const glm::vec3& origin, const glm::vec3& initialDirection, float initialAttenuation, + float initialDelay, float initialDistance = 0.0f, bool isDiffusion = false); // helper that handles audioPath analysis int analyzePathsSingleStep(); + void handlePathPoint(AudioPath* path, float distance, OctreeElement* elementHit, BoxFace face); void analyzePaths(); void drawRays(); void drawPath(AudioPath* path, const glm::vec3& originalColor); diff --git a/libraries/octree/src/AABox.h b/libraries/octree/src/AABox.h index 093a111a69..1aa0849b70 100644 --- a/libraries/octree/src/AABox.h +++ b/libraries/octree/src/AABox.h @@ -23,7 +23,8 @@ enum BoxFace { MIN_Y_FACE, MAX_Y_FACE, MIN_Z_FACE, - MAX_Z_FACE + MAX_Z_FACE, + UNKNOWN_FACE }; enum BoxVertex { diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index d91e01d17f..db62f33f06 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -56,6 +56,10 @@ float randFloatInRange (float min,float max) { return min + ((rand() % 10000)/10000.f * (max-min)); } +float randomSign() { + return randomBoolean() ? -1.0 : 1.0; +} + unsigned char randomColorValue(int miniumum) { return miniumum + (rand() % (256 - miniumum)); } diff --git a/libraries/shared/src/SharedUtil.h b/libraries/shared/src/SharedUtil.h index 236c1f74a1..c909b80b13 100644 --- a/libraries/shared/src/SharedUtil.h +++ b/libraries/shared/src/SharedUtil.h @@ -78,6 +78,7 @@ void usecTimestampNowForceClockSkew(int clockSkew); float randFloat(); int randIntInRange (int min, int max); float randFloatInRange (float min,float max); +float randomSign(); /// \return -1.0 or 1.0 unsigned char randomColorValue(int minimum); bool randomBoolean(); diff --git a/libraries/voxels/src/VoxelDetail.cpp b/libraries/voxels/src/VoxelDetail.cpp index 6c385c9387..f1855f5f81 100644 --- a/libraries/voxels/src/VoxelDetail.cpp +++ b/libraries/voxels/src/VoxelDetail.cpp @@ -75,6 +75,9 @@ QScriptValue rayToVoxelIntersectionResultToScriptValue(QScriptEngine* engine, co case MAX_Z_FACE: faceName = "MAX_Z_FACE"; break; + case UNKNOWN_FACE: + faceName = "UNKNOWN_FACE"; + break; } obj.setProperty("face", faceName); From 57513610fdb45111d501b385c9cb9fe48fdacb2c Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 12:43:02 -0700 Subject: [PATCH 412/595] recalc on any attribute changes --- interface/src/AudioReflector.cpp | 39 +++++++++++++++++++++++++++----- interface/src/AudioReflector.h | 11 ++++++++- 2 files changed, 43 insertions(+), 7 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 7801c26924..6c3e1e0f0b 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -32,7 +32,13 @@ AudioReflector::AudioReflector(QObject* parent) : _diffusionFanout(DEFAULT_DIFFUSION_FANOUT), _absorptionRatio(DEFAULT_ABSORPTION_RATIO), _diffusionRatio(DEFAULT_DIFFUSION_RATIO), - _withDiffusion(false) + _withDiffusion(false), + _lastPreDelay(DEFAULT_PRE_DELAY), + _lastSoundMsPerMeter(DEFAULT_MS_DELAY_PER_METER), + _lastDistanceAttenuationScalingFactor(DEFAULT_DISTANCE_SCALING_FACTOR), + _lastDiffusionFanout(DEFAULT_DIFFUSION_FANOUT), + _lastAbsorptionRatio(DEFAULT_ABSORPTION_RATIO), + _lastDiffusionRatio(DEFAULT_DIFFUSION_RATIO) { _reflections = 0; _diffusionPathCount = 0; @@ -44,6 +50,30 @@ AudioReflector::AudioReflector(QObject* parent) : _minDelay = 0; } +bool AudioReflector::haveAttributesChanged() { + bool withDiffusion = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions); + + bool attributesChange = (_withDiffusion != withDiffusion + || _lastPreDelay != _preDelay + || _lastSoundMsPerMeter != _soundMsPerMeter + || _lastDistanceAttenuationScalingFactor != _distanceAttenuationScalingFactor + || _lastDiffusionFanout != _diffusionFanout + || _lastAbsorptionRatio != _absorptionRatio + || _lastDiffusionRatio != _diffusionRatio); + + if (attributesChange) { + _withDiffusion = withDiffusion; + _lastPreDelay = _preDelay; + _lastSoundMsPerMeter = _soundMsPerMeter; + _lastDistanceAttenuationScalingFactor = _distanceAttenuationScalingFactor; + _lastDiffusionFanout = _diffusionFanout; + _lastAbsorptionRatio = _absorptionRatio; + _lastDiffusionRatio = _diffusionRatio; + } + + return attributesChange; +} + void AudioReflector::render() { // if we're not set up yet, or we're not processing spatial audio, then exit early @@ -274,20 +304,18 @@ void AudioReflector::addSoundSource(const glm::vec3& origin, const glm::vec3& in } void AudioReflector::calculateAllReflections() { - // only recalculate when we've moved... + // only recalculate when we've moved, or if the attributes have changed // TODO: what about case where new voxels are added in front of us??? bool wantHeadOrientation = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingHeadOriented); glm::quat orientation = wantHeadOrientation ? _myAvatar->getHead()->getFinalOrientation() : _myAvatar->getOrientation(); glm::vec3 origin = _myAvatar->getHead()->getPosition(); glm::vec3 listenerPosition = _myAvatar->getHead()->getPosition(); - bool withDiffusion = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions); - bool shouldRecalc = _reflections == 0 || !isSimilarPosition(origin, _origin) || !isSimilarOrientation(orientation, _orientation) || !isSimilarPosition(listenerPosition, _listenerPosition) - || (withDiffusion != _withDiffusion); + || haveAttributesChanged(); if (shouldRecalc) { QMutexLocker locker(&_mutex); @@ -295,7 +323,6 @@ void AudioReflector::calculateAllReflections() { _origin = origin; _orientation = orientation; _listenerPosition = listenerPosition; - _withDiffusion = withDiffusion; analyzePaths(); // actually does the work quint64 end = usecTimestampNow(); const bool wantDebugging = false; diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 72eca9aac2..6a4d10524f 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -171,8 +171,17 @@ private: float _absorptionRatio; float _diffusionRatio; float _reflectiveRatio; - + + // remember the last known values at calculation + bool haveAttributesChanged(); + bool _withDiffusion; + float _lastPreDelay; + float _lastSoundMsPerMeter; + float _lastDistanceAttenuationScalingFactor; + int _lastDiffusionFanout; + float _lastAbsorptionRatio; + float _lastDiffusionRatio; }; From f3f9325a42d4f819c22f5b58caf40c77d08f19ff Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 12:45:28 -0700 Subject: [PATCH 413/595] fixed comment --- examples/audioReflectorTools.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/audioReflectorTools.js b/examples/audioReflectorTools.js index 0467a4f937..acab563d4c 100644 --- a/examples/audioReflectorTools.js +++ b/examples/audioReflectorTools.js @@ -1,11 +1,11 @@ // -// overlaysExample.js +// audioReflectorTools.js // hifi // // Created by Brad Hefta-Gaub on 2/14/14. // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. // -// This is an example script that demonstrates use of the Overlays class +// Tools for manipulating the attributes of the AudioReflector behavior // // From 9d49a5343417c50f097dcd1f253752789ac20dd0 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 12:50:05 -0700 Subject: [PATCH 414/595] coding standard cleanup --- interface/src/Audio.cpp | 1 - interface/src/AudioReflector.h | 6 +++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 2cc02b1368..daaffe85a0 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -518,7 +518,6 @@ void Audio::handleAudioInput() { // Add tone injection if enabled const float TONE_FREQ = 220.f / SAMPLE_RATE * TWO_PI; - //const float TONE_FREQ = 5000.f / SAMPLE_RATE * TWO_PI; const float QUARTER_VOLUME = 8192.f; if (_toneInjectionEnabled) { loudness = 0.f; diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 6a4d10524f..b3faf4ff03 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -6,8 +6,8 @@ // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. // -#ifndef __interface__AudioReflector__ -#define __interface__AudioReflector__ +#ifndef interface_AudioReflector_h +#define interface_AudioReflector_h #include @@ -185,4 +185,4 @@ private: }; -#endif /* defined(__interface__AudioReflector__) */ +#endif // interface_AudioReflector_h From 74828a321503ef9305d24af43eac9a9f00a5b1b6 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 12:54:59 -0700 Subject: [PATCH 415/595] removed non-functional low pass filter --- interface/src/Audio.cpp | 39 --------------------------------------- interface/src/Audio.h | 2 -- interface/src/Menu.cpp | 4 ---- interface/src/Menu.h | 1 - 4 files changed, 46 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index daaffe85a0..9ef687710a 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -819,14 +819,6 @@ void Audio::processReceivedAudio(AudioRingBuffer& ringBuffer) { } - // add the next numNetworkOutputSamples from each QByteArray - // in our _localInjectionByteArrays QVector to the localInjectedSamples - if (Menu::getInstance()->isOptionChecked(MenuOption::LowPassFilter)) { - int channels = _desiredOutputFormat.channelCount(); - int filterSamples = numNetworkOutputSamples / channels; - lowPassFilter(ringBufferSamples, filterSamples, channels); - } - // copy the packet from the RB to the output linearResampling(ringBufferSamples, (int16_t*) outputBuffer.data(), @@ -956,37 +948,6 @@ void Audio::addProceduralSounds(int16_t* monoInput, int numSamples) { } } - -// simple 3 pole low pass filter -void Audio::lowPassFilter(int16_t* inputBuffer, int samples, int channels) { - - //qDebug() << "lowPassFilter() samples=" << samples << " channels=" << channels; - //const int POLE_COUNT = 3; - - for (int c = 0; c < channels; c++) { - const float C1 = 0.25f; // 0.0f; // - const float C2 = 0.5f; // 1.0f; // - const float C3 = 0.25f; // 0.0f; // - int16_t S1,S2,S3; - S1 = inputBuffer[c]; // start with the Nth sample, based on the current channel, this is the fist sample for the channel - for (int i = 0; i < samples; i++) { - int sampleAt = (i * channels) + c; - int nextSampleAt = sampleAt + channels; - S2 = inputBuffer[sampleAt]; - if (i == samples - 1) { - S3 = inputBuffer[sampleAt]; - } else { - S3 = inputBuffer[nextSampleAt]; - } - // save our S1 for next time before we mod this - S1 = inputBuffer[sampleAt]; - inputBuffer[sampleAt] = (C1 * S1) + (C2 * S2) + (C3 * S3); - //qDebug() << "channel=" << c << " sampleAt=" << sampleAt; - } - } -} - - // Starts a collision sound. magnitude is 0-1, with 1 the loudest possible sound. void Audio::startCollisionSound(float magnitude, float frequency, float noise, float duration, bool flashScreen) { _collisionSoundMagnitude = magnitude; diff --git a/interface/src/Audio.h b/interface/src/Audio.h index bac8d48ccf..8ed93efbe0 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -55,8 +55,6 @@ public: void setJitterBufferSamples(int samples) { _jitterBufferSamples = samples; } int getJitterBufferSamples() { return _jitterBufferSamples; } - void lowPassFilter(int16_t* inputBuffer, int samples, int channels); - virtual void startCollisionSound(float magnitude, float frequency, float noise, float duration, bool flashScreen); virtual void startDrumSound(float volume, float frequency, float duration, float decay); diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index e7c5b84a42..a02c8342a7 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -383,10 +383,6 @@ Menu::Menu() : appInstance->getAudio(), SLOT(toggleToneInjection())); - addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::LowPassFilter, - Qt::CTRL | Qt::SHIFT | Qt::Key_F, - false); - QMenu* spatialAudioMenu = audioDebugMenu->addMenu("Spatial Audio"); addCheckableActionToQMenuAndActionHash(spatialAudioMenu, MenuOption::AudioSpatialProcessing, diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 578d4e8dc6..5fcbf11724 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -293,7 +293,6 @@ namespace MenuOption { const QString Login = "Login"; const QString Logout = "Logout"; const QString LookAtVectors = "Look-at Vectors"; - const QString LowPassFilter = "Low Pass Filter"; const QString MetavoxelEditor = "Metavoxel Editor..."; const QString Metavoxels = "Metavoxels"; const QString Mirror = "Mirror"; From cd23b95b42535354fc1f75a3ababd53a0517410b Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 13:16:52 -0700 Subject: [PATCH 416/595] revert back to using QByteArray for processReceivedAudio() --- interface/src/Audio.cpp | 24 ++++++++++++------------ interface/src/Audio.h | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 9ef687710a..bb7ee1a704 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -652,8 +652,7 @@ void Audio::addReceivedAudioToBuffer(const QByteArray& audioByteArray) { if (_audioOutput) { // Audio output must exist and be correctly set up if we're going to process received audio - _ringBuffer.parseData(audioByteArray); - processReceivedAudio(_ringBuffer); + processReceivedAudio(audioByteArray); } Application::getInstance()->getBandwidthMeter()->inputStream(BandwidthMeter::AUDIO).updateValue(audioByteArray.size()); @@ -753,23 +752,24 @@ void Audio::toggleAudioNoiseReduction() { _noiseGateEnabled = !_noiseGateEnabled; } -void Audio::processReceivedAudio(AudioRingBuffer& ringBuffer) { - +void Audio::processReceivedAudio(const QByteArray& audioByteArray) { + _ringBuffer.parseData(audioByteArray); + float networkOutputToOutputRatio = (_desiredOutputFormat.sampleRate() / (float) _outputFormat.sampleRate()) * (_desiredOutputFormat.channelCount() / (float) _outputFormat.channelCount()); - if (!ringBuffer.isStarved() && _audioOutput && _audioOutput->bytesFree() == _audioOutput->bufferSize()) { + if (!_ringBuffer.isStarved() && _audioOutput && _audioOutput->bytesFree() == _audioOutput->bufferSize()) { // we don't have any audio data left in the output buffer // we just starved //qDebug() << "Audio output just starved."; - ringBuffer.setIsStarved(true); + _ringBuffer.setIsStarved(true); _numFramesDisplayStarve = 10; } // if there is anything in the ring buffer, decide what to do - if (ringBuffer.samplesAvailable() > 0) { + if (_ringBuffer.samplesAvailable() > 0) { - int numNetworkOutputSamples = ringBuffer.samplesAvailable(); + int numNetworkOutputSamples = _ringBuffer.samplesAvailable(); int numDeviceOutputSamples = numNetworkOutputSamples / networkOutputToOutputRatio; QByteArray outputBuffer; @@ -777,13 +777,13 @@ void Audio::processReceivedAudio(AudioRingBuffer& ringBuffer) { int numSamplesNeededToStartPlayback = NETWORK_BUFFER_LENGTH_SAMPLES_STEREO + (_jitterBufferSamples * 2); - if (!ringBuffer.isNotStarvedOrHasMinimumSamples(numSamplesNeededToStartPlayback)) { + if (!_ringBuffer.isNotStarvedOrHasMinimumSamples(numSamplesNeededToStartPlayback)) { // We are still waiting for enough samples to begin playback // qDebug() << numNetworkOutputSamples << " samples so far, waiting for " << numSamplesNeededToStartPlayback; } else { // We are either already playing back, or we have enough audio to start playing back. //qDebug() << "pushing " << numNetworkOutputSamples; - ringBuffer.setIsStarved(false); + _ringBuffer.setIsStarved(false); int16_t* ringBufferSamples = new int16_t[numNetworkOutputSamples]; if (_processSpatialAudio) { @@ -791,7 +791,7 @@ void Audio::processReceivedAudio(AudioRingBuffer& ringBuffer) { QByteArray buffer; buffer.resize(numNetworkOutputSamples * sizeof(int16_t)); - ringBuffer.readSamples((int16_t*)buffer.data(), numNetworkOutputSamples); + _ringBuffer.readSamples((int16_t*)buffer.data(), numNetworkOutputSamples); // Accumulate direct transmission of audio from sender to receiver if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingIncudeOriginal)) { addSpatialAudioToBuffer(sampleTime, buffer, numNetworkOutputSamples); @@ -814,7 +814,7 @@ void Audio::processReceivedAudio(AudioRingBuffer& ringBuffer) { // copy the samples we'll resample from the ring buffer - this also // pushes the read pointer of the ring buffer forwards - ringBuffer.readSamples(ringBufferSamples, numNetworkOutputSamples); + _ringBuffer.readSamples(ringBufferSamples, numNetworkOutputSamples); } diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 8ed93efbe0..196058047d 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -187,7 +187,7 @@ private: void addProceduralSounds(int16_t* monoInput, int numSamples); // Process received audio - void processReceivedAudio(AudioRingBuffer& ringBuffer); + void processReceivedAudio(const QByteArray& audioByteArray); bool switchInputToAudioDevice(const QAudioDeviceInfo& inputDeviceInfo); bool switchOutputToAudioDevice(const QAudioDeviceInfo& outputDeviceInfo); From 579710e4bd16c5d753a2c5c5eeb57cfc233c5ef3 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 13:36:20 -0700 Subject: [PATCH 417/595] some cleanup --- interface/src/Audio.cpp | 2 +- libraries/audio/src/AudioRingBuffer.cpp | 44 +++++++++++++++---------- libraries/audio/src/AudioRingBuffer.h | 3 +- 3 files changed, 30 insertions(+), 19 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index bb7ee1a704..da10f4cfe1 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -92,7 +92,7 @@ Audio::Audio(int16_t initialJitterBufferSamples, QObject* parent) : _processSpatialAudio(false), _spatialAudioStart(0), _spatialAudioFinish(0), - _spatialAudioRingBuffer(NETWORK_BUFFER_LENGTH_BYTES_PER_CHANNEL) + _spatialAudioRingBuffer(NETWORK_BUFFER_LENGTH_BYTES_PER_CHANNEL, true) // random access mode { // clear the array of locally injected samples memset(_localProceduralSamples, 0, NETWORK_BUFFER_LENGTH_BYTES_PER_CHANNEL); diff --git a/libraries/audio/src/AudioRingBuffer.cpp b/libraries/audio/src/AudioRingBuffer.cpp index 45dafdca58..9b50ed0bcb 100644 --- a/libraries/audio/src/AudioRingBuffer.cpp +++ b/libraries/audio/src/AudioRingBuffer.cpp @@ -18,16 +18,19 @@ #include "AudioRingBuffer.h" -AudioRingBuffer::AudioRingBuffer(int numFrameSamples) : +AudioRingBuffer::AudioRingBuffer(int numFrameSamples, bool randomAccessMode) : NodeData(), _sampleCapacity(numFrameSamples * RING_BUFFER_LENGTH_FRAMES), _numFrameSamples(numFrameSamples), _isStarved(true), - _hasStarted(false) + _hasStarted(false), + _randomAccessMode(randomAccessMode) { if (numFrameSamples) { _buffer = new int16_t[_sampleCapacity]; - memset(_buffer, 0, _sampleCapacity * sizeof(int16_t)); + if (_randomAccessMode) { + memset(_buffer, 0, _sampleCapacity * sizeof(int16_t)); + } _nextOutput = _buffer; _endOfLastWrite = _buffer; } else { @@ -51,7 +54,9 @@ void AudioRingBuffer::resizeForFrameSize(qint64 numFrameSamples) { delete[] _buffer; _sampleCapacity = numFrameSamples * RING_BUFFER_LENGTH_FRAMES; _buffer = new int16_t[_sampleCapacity]; - memset(_buffer, 0, _sampleCapacity * sizeof(int16_t)); + if (_randomAccessMode) { + memset(_buffer, 0, _sampleCapacity * sizeof(int16_t)); + } _nextOutput = _buffer; _endOfLastWrite = _buffer; } @@ -68,8 +73,14 @@ qint64 AudioRingBuffer::readSamples(int16_t* destination, qint64 maxSamples) { qint64 AudioRingBuffer::readData(char *data, qint64 maxSize) { // only copy up to the number of samples we have available - //int numReadSamples = std::min((unsigned) (maxSize / sizeof(int16_t)), samplesAvailable()); - int numReadSamples = _endOfLastWrite ? (maxSize / sizeof(int16_t)) : samplesAvailable(); + int numReadSamples = std::min((unsigned) (maxSize / sizeof(int16_t)), samplesAvailable()); + + // If we're in random access mode, then we consider our number of available read samples slightly + // differently. Namely, if anything has been written, we say we have as many samples as they ask for + // otherwise we say we have nothing available + if (_randomAccessMode) { + numReadSamples = _endOfLastWrite ? (maxSize / sizeof(int16_t)) : 0; + } if (_nextOutput + numReadSamples > _buffer + _sampleCapacity) { // we're going to need to do two reads to get this data, it wraps around the edge @@ -77,15 +88,21 @@ qint64 AudioRingBuffer::readData(char *data, qint64 maxSize) { // read to the end of the buffer int numSamplesToEnd = (_buffer + _sampleCapacity) - _nextOutput; memcpy(data, _nextOutput, numSamplesToEnd * sizeof(int16_t)); - memset(_nextOutput, 0, numSamplesToEnd * sizeof(int16_t)); // clear it + if (_randomAccessMode) { + memset(_nextOutput, 0, numSamplesToEnd * sizeof(int16_t)); // clear it + } // read the rest from the beginning of the buffer memcpy(data + (numSamplesToEnd * sizeof(int16_t)), _buffer, (numReadSamples - numSamplesToEnd) * sizeof(int16_t)); - memset(_buffer, 0, (numReadSamples - numSamplesToEnd) * sizeof(int16_t)); // clear it + if (_randomAccessMode) { + memset(_buffer, 0, (numReadSamples - numSamplesToEnd) * sizeof(int16_t)); // clear it + } } else { // read the data memcpy(data, _nextOutput, numReadSamples * sizeof(int16_t)); - memset(_nextOutput, 0, numReadSamples * sizeof(int16_t)); // clear it + if (_randomAccessMode) { + memset(_nextOutput, 0, numReadSamples * sizeof(int16_t)); // clear it + } } // push the position of _nextOutput by the number of samples read @@ -111,7 +128,7 @@ qint64 AudioRingBuffer::writeData(const char* data, qint64 maxSize) { && (less(_endOfLastWrite, _nextOutput) && lessEqual(_nextOutput, shiftedPositionAccomodatingWrap(_endOfLastWrite, samplesToCopy)))) { // this read will cross the next output, so call us starved and reset the buffer - qDebug() << "Filled the ring buffer. Resetting. <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"; + qDebug() << "Filled the ring buffer. Resetting."; _endOfLastWrite = _buffer; _nextOutput = _buffer; _isStarved = true; @@ -151,13 +168,6 @@ unsigned int AudioRingBuffer::samplesAvailable() const { if (sampleDifference < 0) { sampleDifference += _sampleCapacity; } - - if (sampleDifference == 0) { - qDebug() << "ran dry!!! _endOfLastWrite=" << _endOfLastWrite - << "_nextOutput=" << _nextOutput - << "_buffer + _sampleCapacity=" << (_buffer + _sampleCapacity) - << " samplesAvailable() == 0!!!!!!!!!!!!!!!!!!!!"; - } return sampleDifference; } diff --git a/libraries/audio/src/AudioRingBuffer.h b/libraries/audio/src/AudioRingBuffer.h index 7ec686f1ac..04cc67c8ac 100644 --- a/libraries/audio/src/AudioRingBuffer.h +++ b/libraries/audio/src/AudioRingBuffer.h @@ -39,7 +39,7 @@ const int MIN_SAMPLE_VALUE = std::numeric_limits::min(); class AudioRingBuffer : public NodeData { Q_OBJECT public: - AudioRingBuffer(int numFrameSamples); + AudioRingBuffer(int numFrameSamples, bool randomAccessMode = false); ~AudioRingBuffer(); void reset(); @@ -88,6 +88,7 @@ protected: int16_t* _buffer; bool _isStarved; bool _hasStarted; + bool _randomAccessMode; /// will this ringbuffer be used for random access? if so, do some special processing }; #endif // hifi_AudioRingBuffer_h From 5a0963a73183fce52e77d32760630bf872681234 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 13:58:31 -0700 Subject: [PATCH 418/595] cleaned up comments and range protected some settings --- interface/src/AudioReflector.cpp | 22 +++++++++++++- interface/src/AudioReflector.h | 50 ++++++++++++++++++++------------ 2 files changed, 53 insertions(+), 19 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 6c3e1e0f0b..6d74228233 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -624,10 +624,30 @@ SurfaceCharacteristics AudioReflector::getSurfaceCharacteristics(OctreeElement* } void AudioReflector::setReflectiveRatio(float ratio) { + float safeRatio = std::max(0.0f, std::min(ratio, 1.0f)); float currentReflectiveRatio = (1.0f - (_absorptionRatio + _diffusionRatio)); - float halfDifference = (ratio - currentReflectiveRatio) / 2.0f; + float halfDifference = (safeRatio - currentReflectiveRatio) / 2.0f; + // evenly distribute the difference between the two other ratios _absorptionRatio -= halfDifference; _diffusionRatio -= halfDifference; } +void AudioReflector::setAbsorptionRatio(float ratio) { + float safeRatio = std::max(0.0f, std::min(ratio, 1.0f)); + _absorptionRatio = safeRatio; + const float MAX_COMBINED_RATIO = 1.0f; + if (_absorptionRatio + _diffusionRatio > MAX_COMBINED_RATIO) { + _diffusionRatio = MAX_COMBINED_RATIO - _absorptionRatio; + } +} + +void AudioReflector::setDiffusionRatio(float ratio) { + float safeRatio = std::max(0.0f, std::min(ratio, 1.0f)); + _diffusionRatio = safeRatio; + const float MAX_COMBINED_RATIO = 1.0f; + if (_absorptionRatio + _diffusionRatio > MAX_COMBINED_RATIO) { + _absorptionRatio = MAX_COMBINED_RATIO - _diffusionRatio; + } +} + diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index b3faf4ff03..0dea3b1d61 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -40,10 +40,10 @@ public: class AudiblePoint { public: - glm::vec3 location; - float delay; // includes total delay including pre delay to the point of the audible location, not to the listener's ears - float attenuation; // only the reflective & diffusive portion of attenuation, doesn't include distance attenuation - float distance; // includes total distance to the point of the audible location, not to the listener's ears + glm::vec3 location; /// location of the audible point + float delay; /// includes total delay including pre delay to the point of the audible location, not to the listener's ears + float attenuation; /// only the reflective & diffusive portion of attenuation, doesn't include distance attenuation + float distance; /// includes total distance to the point of the audible location, not to the listener's ears }; class SurfaceCharacteristics { @@ -59,12 +59,18 @@ class AudioReflector : public QObject { public: AudioReflector(QObject* parent = NULL); + // setup functions to configure the resources used by the AudioReflector void setVoxels(VoxelTree* voxels) { _voxels = voxels; } void setMyAvatar(MyAvatar* myAvatar) { _myAvatar = myAvatar; } void setAudio(Audio* audio) { _audio = audio; } - void render(); + void render(); /// must be called in the application render loop + void processInboundAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); + void processLocalAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); + +public slots: + // statistics int getReflections() const { return _reflections; } float getAverageDelayMsecs() const { return _averageDelay; } float getAverageAttenuation() const { return _averageAttenuation; } @@ -75,24 +81,32 @@ public: float getDelayFromDistance(float distance); int getDiffusionPathCount() const { return _diffusionPathCount; } - void processInboundAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); - void processLocalAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); - -public slots: - + /// ms of delay added to all echos float getPreDelay() const { return _preDelay; } void setPreDelay(float preDelay) { _preDelay = preDelay; } - float getSoundMsPerMeter() const { return _soundMsPerMeter; } /// ms per meter, larger means slower - void setSoundMsPerMeter(float soundMsPerMeter) { _soundMsPerMeter = soundMsPerMeter; } - float getDistanceAttenuationScalingFactor() const { return _distanceAttenuationScalingFactor; } /// ms per meter, larger means slower - void setDistanceAttenuationScalingFactor(float factor) { _distanceAttenuationScalingFactor = factor; } - int getDiffusionFanout() const { return _diffusionFanout; } /// number of points of diffusion from each reflection point - void setDiffusionFanout(int fanout) { _diffusionFanout = fanout; } /// number of points of diffusion from each reflection point + /// ms per meter that sound travels, larger means slower, which sounds bigger + float getSoundMsPerMeter() const { return _soundMsPerMeter; } + void setSoundMsPerMeter(float soundMsPerMeter) { _soundMsPerMeter = soundMsPerMeter; } + + /// scales attenuation to be louder or softer than the default distance attenuation + float getDistanceAttenuationScalingFactor() const { return _distanceAttenuationScalingFactor; } + void setDistanceAttenuationScalingFactor(float factor) { _distanceAttenuationScalingFactor = factor; } + + /// number of points of diffusion from each reflection point, as fanout increases there are more chances for secondary + /// echoes, but each diffusion ray is quieter and therefore more likely to be below the sound floor + int getDiffusionFanout() const { return _diffusionFanout; } + void setDiffusionFanout(int fanout) { _diffusionFanout = fanout; } + + /// ratio 0.0 - 1.0 of amount of each ray that is absorbed upon hitting a surface float getAbsorptionRatio() const { return _absorptionRatio; } - void setAbsorptionRatio(float ratio) { _absorptionRatio = ratio; } + void setAbsorptionRatio(float ratio); + + // ratio 0.0 - 1.0 of amount of each ray that is diffused upon hitting a surface float getDiffusionRatio() const { return _diffusionRatio; } - void setDiffusionRatio(float ratio) { _diffusionRatio = ratio; } + void setDiffusionRatio(float ratio); + + // remaining ratio 0.0 - 1.0 of amount of each ray that is cleanly reflected upon hitting a surface float getReflectiveRatio() const { return (1.0f - (_absorptionRatio + _diffusionRatio)); } void setReflectiveRatio(float ratio); From f12ac3b03608f9b88f8da5a2c2f709667e68d1ee Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 14:14:51 -0700 Subject: [PATCH 419/595] some cleanup --- interface/src/AudioReflector.cpp | 21 ++++++++++++--------- interface/src/AudioReflector.h | 11 ++--------- 2 files changed, 14 insertions(+), 18 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 6d74228233..fa4573b1b4 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -249,8 +249,6 @@ void AudioReflector::echoAudio(unsigned int sampleTime, const QByteArray& sample _averageDelay = _delayCount == 0 ? 0 : _totalDelay / _delayCount; _averageAttenuation = _attenuationCount == 0 ? 0 : _totalAttenuation / _attenuationCount; - _reflections = _audiblePoints.size(); - _diffusionPathCount = countDiffusionPaths(); if (_reflections == 0) { _minDelay = 0.0f; @@ -364,6 +362,13 @@ void AudioReflector::drawPath(AudioPath* path, const glm::vec3& originalColor) { } +// Here's how this works: we have an array of AudioPaths, we loop on all of our currently calculating audio +// paths, and calculate one ray per path. If that ray doesn't reflect, or reaches a max distance/attenuation, then it +// is considered finalized. +// If the ray hits a surface, then, based on the characteristics of that surface, it will calculate the new +// attenuation, path length, and delay for the primary path. For surfaces that have diffusion, it will also create +// fanout number of new paths, those new paths will have an origin of the reflection point, and an initial attenuation +// of their diffusion ratio. Those new paths will be added to the active audio paths, and be analyzed for the next loop. void AudioReflector::analyzePaths() { // clear our _audioPaths foreach(AudioPath* const& path, _audioPaths) { @@ -391,7 +396,10 @@ void AudioReflector::analyzePaths() { float initialAttenuation = 1.0f; float preDelay = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingPreDelay) ? _preDelay : 0.0f; - + + // NOTE: we're still calculating our initial paths based on the listeners position. But the analysis code has been + // updated to support individual sound sources (which is how we support diffusion), we can use this new paradigm to + // add support for individual sound sources, and more directional sound sources addSoundSource(_origin, right, initialAttenuation, preDelay); addSoundSource(_origin, front, initialAttenuation, preDelay); addSoundSource(_origin, up, initialAttenuation, preDelay); @@ -422,8 +430,7 @@ int AudioReflector::countDiffusionPaths() { int diffusionCount = 0; foreach(AudioPath* const& path, _audioPaths) { - // if this is NOT an original reflection then it's a diffusion path - if (path->startPoint != _origin) { + if (path->isDiffusion) { diffusionCount++; } } @@ -432,13 +439,9 @@ int AudioReflector::countDiffusionPaths() { int AudioReflector::analyzePathsSingleStep() { // iterate all the active sound paths, calculate one step per active path - int activePaths = 0; foreach(AudioPath* const& path, _audioPaths) { - //bool wantExtraDebuggging = false; - //bool isDiffusion = (path->startPoint != _origin); - glm::vec3 start = path->lastPoint; glm::vec3 direction = path->lastDirection; OctreeElement* elementHit; // output from findRayIntersection diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 0dea3b1d61..7867df3d9b 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -141,15 +141,8 @@ private: glm::vec3 _origin; glm::quat _orientation; - // NOTE: Here's the new way, we will have an array of AudioPaths, we will loop on all of our currently calculating audio - // paths, and calculate one ray per path. If that ray doesn't reflect, or reaches a max distance/attenuation, then it - // is considered finalized. - // If the ray hits a surface, then, based on the characteristics of that surface, it will create calculate the new - // attenuation, path length, and delay for the primary path. For surfaces that have diffusion, it will also create - // fanout number of new paths, those new paths will have an origin of the reflection point, and an initial attenuation - // of their diffusion ratio. Those new paths will be added to the active audio paths, and be analyzed for the next loop. - QVector _audioPaths; - QVector _audiblePoints; + QVector _audioPaths; /// the various audio paths we're processing + QVector _audiblePoints; /// the audible points that have been calculated from the paths // adds a sound source to begin an audio path trace, these can be the initial sound sources with their directional properties, // as well as diffusion sound sources From 24f0f37eb9a020244a261a80badc06945549b986 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 14:21:28 -0700 Subject: [PATCH 420/595] cleanup --- interface/src/Audio.cpp | 7 ------- 1 file changed, 7 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index da10f4cfe1..50f50a3347 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -806,17 +806,10 @@ void Audio::processReceivedAudio(const QByteArray& audioByteArray) { // Advance the start point for the next packet of audio to arrive _spatialAudioStart += numNetworkOutputSamples / _desiredOutputFormat.channelCount(); - - // Advance the read position by the same amount - //ringBuffer.shiftReadPosition(numNetworkOutputSamples); - } else { - // copy the samples we'll resample from the ring buffer - this also // pushes the read pointer of the ring buffer forwards _ringBuffer.readSamples(ringBufferSamples, numNetworkOutputSamples); - - } // copy the packet from the RB to the output From 05023a2585fbcab011065e6db8474d63a6c8d1b0 Mon Sep 17 00:00:00 2001 From: Stojce Slavkovski Date: Tue, 15 Apr 2014 23:29:28 +0200 Subject: [PATCH 421/595] Snapshot preferences title --- interface/ui/preferencesDialog.ui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/ui/preferencesDialog.ui b/interface/ui/preferencesDialog.ui index 3ad824a35e..278e3c5dab 100644 --- a/interface/ui/preferencesDialog.ui +++ b/interface/ui/preferencesDialog.ui @@ -533,7 +533,7 @@ color: #0e7077 color: #0e7077 - Snapshots location + Place my Snapshots here: Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft From e514c9564211f345e27b0a1bdb094dc5cc39caef Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 14:47:38 -0700 Subject: [PATCH 422/595] variable names cleanup to match coding standard --- interface/src/Audio.cpp | 55 ++++++++++++++++++----------------------- 1 file changed, 24 insertions(+), 31 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 50f50a3347..1d8dadea81 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -674,49 +674,42 @@ void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, const QByteArray& s // Locate where in the accumulation buffer the new samples need to go if (sampleTime >= _spatialAudioFinish) { if (_spatialAudioStart == _spatialAudioFinish) { - - // Nothing in the spatial audio ring buffer yet - // Just do a straight copy, clipping if necessary - unsigned int sampleCt = (remaining < numSamples) ? remaining : numSamples; - if (sampleCt) { - _spatialAudioRingBuffer.writeSamples((int16_t*)spatialAudio.data(), sampleCt); + // Nothing in the spatial audio ring buffer yet, Just do a straight copy, clipping if necessary + unsigned int sampleCount = (remaining < numSamples) ? remaining : numSamples; + if (sampleCount) { + _spatialAudioRingBuffer.writeSamples((int16_t*)spatialAudio.data(), sampleCount); } - _spatialAudioFinish = _spatialAudioStart + sampleCt / _desiredOutputFormat.channelCount(); - + _spatialAudioFinish = _spatialAudioStart + sampleCount / _desiredOutputFormat.channelCount(); } else { - // Spatial audio ring buffer already has data, but there is no overlap with the new sample. // Compute the appropriate time delay and pad with silence until the new start time. unsigned int delay = sampleTime - _spatialAudioFinish; - unsigned int ct = delay * _desiredOutputFormat.channelCount(); - unsigned int silentCt = (remaining < ct) ? remaining : ct; - if (silentCt) { - _spatialAudioRingBuffer.addSilentFrame(silentCt); + unsigned int delayCount = delay * _desiredOutputFormat.channelCount(); + unsigned int silentCount = (remaining < delayCount) ? remaining : delayCount; + if (silentCount) { + _spatialAudioRingBuffer.addSilentFrame(silentCount); } // Recalculate the number of remaining samples - remaining -= silentCt; - unsigned int sampleCt = (remaining < numSamples) ? remaining : numSamples; + remaining -= silentCount; + unsigned int sampleCount = (remaining < numSamples) ? remaining : numSamples; // Copy the new spatial audio to the accumulation ring buffer - if (sampleCt) { - _spatialAudioRingBuffer.writeSamples((int16_t*)spatialAudio.data(), sampleCt); + if (sampleCount) { + _spatialAudioRingBuffer.writeSamples((int16_t*)spatialAudio.data(), sampleCount); } - _spatialAudioFinish += (sampleCt + silentCt) / _desiredOutputFormat.channelCount(); + _spatialAudioFinish += (sampleCount + silentCount) / _desiredOutputFormat.channelCount(); } } else { - - // There is overlap between the spatial audio buffer and the new sample, - // acumulate the overlap - + // There is overlap between the spatial audio buffer and the new sample, mix the overlap // Calculate the offset from the buffer's current read position, which should be located at _spatialAudioStart unsigned int offset = (sampleTime - _spatialAudioStart) * _desiredOutputFormat.channelCount(); - unsigned int accumulationCt = (_spatialAudioFinish - sampleTime) * _desiredOutputFormat.channelCount(); - accumulationCt = (accumulationCt < numSamples) ? accumulationCt : numSamples; + unsigned int mixedSamplesCount = (_spatialAudioFinish - sampleTime) * _desiredOutputFormat.channelCount(); + mixedSamplesCount = (mixedSamplesCount < numSamples) ? mixedSamplesCount : numSamples; const int16_t* spatial = reinterpret_cast(spatialAudio.data()); int j = 0; - for (int i = accumulationCt; --i >= 0; j++) { + for (int i = mixedSamplesCount; --i >= 0; j++) { int t1 = _spatialAudioRingBuffer[j + offset]; int t2 = spatial[j]; int tmp = t1 + t2; @@ -724,13 +717,13 @@ void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, const QByteArray& s static_cast(glm::clamp(tmp, std::numeric_limits::min(), std::numeric_limits::max())); } - // Copy the remaining unoverlapped spatial audio to the accumulation buffer, if any - unsigned int sampleCt = numSamples - accumulationCt; - sampleCt = (remaining < sampleCt) ? remaining : sampleCt; - if (sampleCt) { - _spatialAudioRingBuffer.writeSamples((int16_t*)spatialAudio.data() + accumulationCt, sampleCt); + // Copy the remaining unoverlapped spatial audio to the spatial audio buffer, if any + unsigned int nonMixedSampleCount = numSamples - mixedSamplesCount; + nonMixedSampleCount = (remaining < nonMixedSampleCount) ? remaining : nonMixedSampleCount; + if (nonMixedSampleCount) { + _spatialAudioRingBuffer.writeSamples((int16_t*)spatialAudio.data() + mixedSamplesCount, nonMixedSampleCount); // Extend the finish time by the amount of unoverlapped samples - _spatialAudioFinish += sampleCt / _desiredOutputFormat.channelCount(); + _spatialAudioFinish += nonMixedSampleCount / _desiredOutputFormat.channelCount(); } } } From 5bc8c83706f2f247baf4c283aec9ef8dcc754581 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 15:16:55 -0700 Subject: [PATCH 423/595] loop and variable name cleanup --- interface/src/Audio.cpp | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 1d8dadea81..d212f41098 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -708,13 +708,12 @@ void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, const QByteArray& s mixedSamplesCount = (mixedSamplesCount < numSamples) ? mixedSamplesCount : numSamples; const int16_t* spatial = reinterpret_cast(spatialAudio.data()); - int j = 0; - for (int i = mixedSamplesCount; --i >= 0; j++) { - int t1 = _spatialAudioRingBuffer[j + offset]; - int t2 = spatial[j]; - int tmp = t1 + t2; - _spatialAudioRingBuffer[j + offset] = - static_cast(glm::clamp(tmp, std::numeric_limits::min(), std::numeric_limits::max())); + for (int i = 0; i < mixedSamplesCount; i++) { + int existingSample = _spatialAudioRingBuffer[i + offset]; + int newSample = spatial[i]; + int sumOfSamples = existingSample + newSample; + _spatialAudioRingBuffer[i + offset] = static_cast(glm::clamp(sumOfSamples, + std::numeric_limits::min(), std::numeric_limits::max())); } // Copy the remaining unoverlapped spatial audio to the spatial audio buffer, if any From f9b658543535261cd29eebee21a7ead6a335605e Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 15:20:03 -0700 Subject: [PATCH 424/595] some cleanup --- interface/src/Audio.cpp | 1 - interface/src/Audio.h | 6 +++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index d212f41098..0328327249 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -666,7 +666,6 @@ unsigned int Audio::timeValToSampleTick(const quint64 time, int sampleRate) { } void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, const QByteArray& spatialAudio, unsigned int numSamples) { - // Calculate the number of remaining samples available. The source spatial audio buffer will get // clipped if there are insufficient samples available in the accumulation buffer. unsigned int remaining = _spatialAudioRingBuffer.getSampleCapacity() - _spatialAudioRingBuffer.samplesAvailable(); diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 196058047d..99d9bd4884 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -172,9 +172,9 @@ private: // Process received audio by spatial attenuation geometric response bool _processSpatialAudio; - unsigned int _spatialAudioStart; ///< Start of spatial audio interval (in sample rate time base) - unsigned int _spatialAudioFinish; ///< End of spatial audio interval (in sample rate time base) - AudioRingBuffer _spatialAudioRingBuffer; ///< Spatially processed audio + unsigned int _spatialAudioStart; /// Start of spatial audio interval (in sample rate time base) + unsigned int _spatialAudioFinish; /// End of spatial audio interval (in sample rate time base) + AudioRingBuffer _spatialAudioRingBuffer; /// Spatially processed audio unsigned int timeValToSampleTick(const quint64 time, int sampleRate); From e66822c6ee56cc12854628e6b1448bdc635fdb82 Mon Sep 17 00:00:00 2001 From: Thijs Wenker Date: Wed, 16 Apr 2014 00:55:06 +0200 Subject: [PATCH 425/595] ScriptEditor: Syntax highlighting update --- interface/src/ScriptHighlighting.cpp | 57 ++++++++++++++++++++- interface/src/ScriptHighlighting.h | 20 +++++++- interface/src/ui/ScriptEditorWidget.cpp | 5 +- interface/ui/ScriptEditorWidget.ui | 66 ++++++++++++++++++++++--- 4 files changed, 137 insertions(+), 11 deletions(-) diff --git a/interface/src/ScriptHighlighting.cpp b/interface/src/ScriptHighlighting.cpp index 15505ac49a..119926742c 100644 --- a/interface/src/ScriptHighlighting.cpp +++ b/interface/src/ScriptHighlighting.cpp @@ -11,8 +11,61 @@ #include "ScriptHighlighting.h" -ScriptHighlighting::ScriptHighlighting(QObject* parent) : +ScriptHighlighting::ScriptHighlighting(QTextDocument* parent) : QSyntaxHighlighter(parent) { + keywordRegex = QRegExp("\\b(break|case|catch|continue|debugger|default|delete|do|else|finally|for|function|if|in|instanceof|new|return|switch|this|throw|try|typeof|var|void|while|with)\\b"); + qoutedTextRegex = QRegExp("\".*\""); + multiLineCommentBegin = QRegExp("/\\*"); + multiLineCommentEnd = QRegExp("\\*/"); + numberRegex = QRegExp("[0-9]+(\\.[0-9]+){0,1}"); +} -} \ No newline at end of file +void ScriptHighlighting::highlightBlock(const QString &text) { + this->highlightKeywords(text); + this->formatComments(text); + this->formatQoutedText(text); + this->formatNumbers(text); +} + +void ScriptHighlighting::highlightKeywords(const QString &text) { + int index = keywordRegex.indexIn(text); + while (index >= 0) { + int length = keywordRegex.matchedLength(); + setFormat(index, length, Qt::blue); + index = keywordRegex.indexIn(text, index + length); + } +} + +void ScriptHighlighting::formatComments(const QString &text) { + + setCurrentBlockState(BlockStateClean); + + int start = (previousBlockState() != BlockStateInMultiComment) ? text.indexOf(multiLineCommentBegin) : 0; + + while (start > -1) { + int end = text.indexOf(multiLineCommentEnd, start); + int length = (end == -1 ? text.length() : (end + multiLineCommentEnd.matchedLength())) - start; + setFormat(start, length, Qt::lightGray); + start = text.indexOf(multiLineCommentBegin, start + length); + if (end == -1) setCurrentBlockState(BlockStateInMultiComment); + } +} + +void ScriptHighlighting::formatQoutedText(const QString &text){ + int index = qoutedTextRegex.indexIn(text); + while (index >= 0) { + int length = qoutedTextRegex.matchedLength(); + setFormat(index, length, Qt::red); + index = qoutedTextRegex.indexIn(text, index + length); + } +} + +void ScriptHighlighting::formatNumbers(const QString &text){ + int index = numberRegex.indexIn(text); + while (index >= 0) { + int length = numberRegex.matchedLength(); + setFormat(index, length, Qt::green); + index = numberRegex.indexIn(text, index + length); + } +} diff --git a/interface/src/ScriptHighlighting.h b/interface/src/ScriptHighlighting.h index f2bd97930e..b9567cb06a 100644 --- a/interface/src/ScriptHighlighting.h +++ b/interface/src/ScriptHighlighting.h @@ -18,8 +18,26 @@ class ScriptHighlighting : public QSyntaxHighlighter { Q_OBJECT public: - ScriptHighlighting(QObject* parent = 0); + ScriptHighlighting(QTextDocument* parent = 0); + enum BlockState { + BlockStateClean, + BlockStateInMultiComment + }; + +protected: + void highlightBlock(const QString &text); + void highlightKeywords(const QString &text); + void formatComments(const QString &text); + void formatQoutedText(const QString &text); + void formatNumbers(const QString &text); + +private: + QRegExp keywordRegex; + QRegExp qoutedTextRegex; + QRegExp multiLineCommentBegin; + QRegExp multiLineCommentEnd; + QRegExp numberRegex; }; #endif // hifi_ScriptHighlighting_h diff --git a/interface/src/ui/ScriptEditorWidget.cpp b/interface/src/ui/ScriptEditorWidget.cpp index 4adf01a28a..618e405448 100644 --- a/interface/src/ui/ScriptEditorWidget.cpp +++ b/interface/src/ui/ScriptEditorWidget.cpp @@ -20,6 +20,7 @@ #include #include "Application.h" +#include "ScriptHighlighting.h" #include "ui_scriptEditorWidget.h" #include "ScriptEditorWidget.h" @@ -31,7 +32,9 @@ ScriptEditorWidget::ScriptEditorWidget() : // remove the title bar (see the Qt docs on setTitleBarWidget) setTitleBarWidget(new QWidget()); - //QSyntaxHighlighter* highlighter = new QSyntaxHighlighter(); + QFontMetrics fm(this->ui->scriptEdit->font()); + this->ui->scriptEdit->setTabStopWidth(fm.width('0') * 4); + ScriptHighlighting* highlighting = new ScriptHighlighting(this->ui->scriptEdit->document()); } ScriptEditorWidget::~ScriptEditorWidget() { diff --git a/interface/ui/ScriptEditorWidget.ui b/interface/ui/ScriptEditorWidget.ui index 82398d587c..5878f26c69 100644 --- a/interface/ui/ScriptEditorWidget.ui +++ b/interface/ui/ScriptEditorWidget.ui @@ -52,7 +52,7 @@ 0 - + Courier @@ -68,22 +68,74 @@ - - - Debug Log: + + + 0 - + + 0 + + + 0 + + + + + + 0 + 0 + + + + Debug Log: + + + + + + + Clear + + + + 16 + 16 + + + + + - + font: 8pt "Courier"; + + true + - + + + clearButton + clicked() + debugText + clear() + + + 663 + 447 + + + 350 + 501 + + + + From 585024d70ec0a502a94c095d7bb996ecccb38e4f Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 16:04:33 -0700 Subject: [PATCH 426/595] resample the local audio before sending it to any registered listeners --- interface/src/Audio.cpp | 53 ++++++++++++++++++++++++++--------------- 1 file changed, 34 insertions(+), 19 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 0328327249..96af5f5f3b 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -403,13 +403,39 @@ void Audio::handleAudioInput() { unsigned int inputSamplesRequired = NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL * inputToNetworkInputRatio; QByteArray inputByteArray = _inputDevice->readAll(); + + // we may need to check for resampling our input audio in a couple cases: + // 1) the local loopback is enabled + // 2) spatial audio is enabled + bool spatialAudioEnabled = (_processSpatialAudio && !_muted && _audioOutput); + bool localLoopbackEnabled = (Menu::getInstance()->isOptionChecked(MenuOption::EchoLocalAudio) && !_muted && _audioOutput); + bool possiblyResampleInputAudio = spatialAudioEnabled || localLoopbackEnabled; + bool resampleNeeded = (_inputFormat != _outputFormat); + QByteArray resampledInputByteArray; + + if (possiblyResampleInputAudio && resampleNeeded) { + float loopbackOutputToInputRatio = (_outputFormat.sampleRate() / (float) _inputFormat.sampleRate()) + * (_outputFormat.channelCount() / _inputFormat.channelCount()); - // send our local loopback to any interested parties - if (_processSpatialAudio && !_muted && _audioOutput) { - emit processLocalAudio(_spatialAudioStart, inputByteArray, _inputFormat); + resampledInputByteArray.fill(0, inputByteArray.size() * loopbackOutputToInputRatio); + + linearResampling((int16_t*) inputByteArray.data(), (int16_t*) resampledInputByteArray.data(), + inputByteArray.size() / sizeof(int16_t), + resampledInputByteArray.size() / sizeof(int16_t), _inputFormat, _outputFormat); } - if (Menu::getInstance()->isOptionChecked(MenuOption::EchoLocalAudio) && !_muted && _audioOutput) { + // send our local loopback to any interested parties + if (spatialAudioEnabled) { + if (resampleNeeded) { + // local audio is sent already resampled to match the output format, so processors + // can easily handle the audio in a format ready to post back to the audio device + emit processLocalAudio(_spatialAudioStart, resampledInputByteArray, _outputFormat); + } else { + emit processLocalAudio(_spatialAudioStart, inputByteArray, _outputFormat); + } + } + + if (localLoopbackEnabled) { // if this person wants local loopback add that to the locally injected audio if (!_loopbackOutputDevice && _loopbackAudioOutput) { @@ -417,23 +443,12 @@ void Audio::handleAudioInput() { _loopbackOutputDevice = _loopbackAudioOutput->start(); } - if (_inputFormat == _outputFormat) { - if (_loopbackOutputDevice) { + if (_loopbackOutputDevice) { + if (resampleNeeded) { + _loopbackOutputDevice->write(resampledInputByteArray); + } else { _loopbackOutputDevice->write(inputByteArray); } - } else { - float loopbackOutputToInputRatio = (_outputFormat.sampleRate() / (float) _inputFormat.sampleRate()) - * (_outputFormat.channelCount() / _inputFormat.channelCount()); - - QByteArray loopBackByteArray(inputByteArray.size() * loopbackOutputToInputRatio, 0); - - linearResampling((int16_t*) inputByteArray.data(), (int16_t*) loopBackByteArray.data(), - inputByteArray.size() / sizeof(int16_t), - loopBackByteArray.size() / sizeof(int16_t), _inputFormat, _outputFormat); - - if (_loopbackOutputDevice) { - _loopbackOutputDevice->write(loopBackByteArray); - } } } From a7cbf7f667909c3519fa49cd0de6d04d2bce699d Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 16:26:46 -0700 Subject: [PATCH 427/595] revert some code --- interface/src/Audio.cpp | 39 ++++++++++++++------------------------- 1 file changed, 14 insertions(+), 25 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 96af5f5f3b..0c910ab927 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -404,38 +404,18 @@ void Audio::handleAudioInput() { QByteArray inputByteArray = _inputDevice->readAll(); - // we may need to check for resampling our input audio in a couple cases: - // 1) the local loopback is enabled - // 2) spatial audio is enabled - bool spatialAudioEnabled = (_processSpatialAudio && !_muted && _audioOutput); - bool localLoopbackEnabled = (Menu::getInstance()->isOptionChecked(MenuOption::EchoLocalAudio) && !_muted && _audioOutput); - bool possiblyResampleInputAudio = spatialAudioEnabled || localLoopbackEnabled; - bool resampleNeeded = (_inputFormat != _outputFormat); - QByteArray resampledInputByteArray; - - if (possiblyResampleInputAudio && resampleNeeded) { - float loopbackOutputToInputRatio = (_outputFormat.sampleRate() / (float) _inputFormat.sampleRate()) - * (_outputFormat.channelCount() / _inputFormat.channelCount()); - - resampledInputByteArray.fill(0, inputByteArray.size() * loopbackOutputToInputRatio); - - linearResampling((int16_t*) inputByteArray.data(), (int16_t*) resampledInputByteArray.data(), - inputByteArray.size() / sizeof(int16_t), - resampledInputByteArray.size() / sizeof(int16_t), _inputFormat, _outputFormat); - } - // send our local loopback to any interested parties - if (spatialAudioEnabled) { - if (resampleNeeded) { + if (_processSpatialAudio && !_muted && _audioOutput) { + if (false) { // local audio is sent already resampled to match the output format, so processors // can easily handle the audio in a format ready to post back to the audio device - emit processLocalAudio(_spatialAudioStart, resampledInputByteArray, _outputFormat); + //emit processLocalAudio(_spatialAudioStart, resampledInputByteArray, _outputFormat); } else { emit processLocalAudio(_spatialAudioStart, inputByteArray, _outputFormat); } } - if (localLoopbackEnabled) { + if (Menu::getInstance()->isOptionChecked(MenuOption::EchoLocalAudio) && !_muted && _audioOutput) { // if this person wants local loopback add that to the locally injected audio if (!_loopbackOutputDevice && _loopbackAudioOutput) { @@ -444,7 +424,16 @@ void Audio::handleAudioInput() { } if (_loopbackOutputDevice) { - if (resampleNeeded) { + if (_inputFormat != _outputFormat) { + float loopbackOutputToInputRatio = (_outputFormat.sampleRate() / (float) _inputFormat.sampleRate()) + * (_outputFormat.channelCount() / _inputFormat.channelCount()); + + QByteArray resampledInputByteArray(inputByteArray.size() * loopbackOutputToInputRatio, 0); + + linearResampling((int16_t*) inputByteArray.data(), (int16_t*) resampledInputByteArray.data(), + inputByteArray.size() / sizeof(int16_t), + resampledInputByteArray.size() / sizeof(int16_t), _inputFormat, _outputFormat); + _loopbackOutputDevice->write(resampledInputByteArray); } else { _loopbackOutputDevice->write(inputByteArray); From 523cc4bdfe0bc28cf4e9c2aaa59b56595c0d683c Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 16:30:47 -0700 Subject: [PATCH 428/595] revert some code --- interface/src/Audio.cpp | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 0c910ab927..daf6a4a7ee 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -423,21 +423,23 @@ void Audio::handleAudioInput() { _loopbackOutputDevice = _loopbackAudioOutput->start(); } - if (_loopbackOutputDevice) { - if (_inputFormat != _outputFormat) { - float loopbackOutputToInputRatio = (_outputFormat.sampleRate() / (float) _inputFormat.sampleRate()) - * (_outputFormat.channelCount() / _inputFormat.channelCount()); - - QByteArray resampledInputByteArray(inputByteArray.size() * loopbackOutputToInputRatio, 0); - - linearResampling((int16_t*) inputByteArray.data(), (int16_t*) resampledInputByteArray.data(), - inputByteArray.size() / sizeof(int16_t), - resampledInputByteArray.size() / sizeof(int16_t), _inputFormat, _outputFormat); - - _loopbackOutputDevice->write(resampledInputByteArray); - } else { + if (_inputFormat == _outputFormat) { + if (_loopbackOutputDevice) { _loopbackOutputDevice->write(inputByteArray); } + } else { + float loopbackOutputToInputRatio = (_outputFormat.sampleRate() / (float) _inputFormat.sampleRate()) + * (_outputFormat.channelCount() / _inputFormat.channelCount()); + + QByteArray loopBackByteArray(inputByteArray.size() * loopbackOutputToInputRatio, 0); + + linearResampling((int16_t*) inputByteArray.data(), (int16_t*) loopBackByteArray.data(), + inputByteArray.size() / sizeof(int16_t), + loopBackByteArray.size() / sizeof(int16_t), _inputFormat, _outputFormat); + + if (_loopbackOutputDevice) { + _loopbackOutputDevice->write(loopBackByteArray); + } } } From 8cbad1bf548049fb3c2593e147fd8c750514d716 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Tue, 15 Apr 2014 19:37:28 -0700 Subject: [PATCH 429/595] More work on animation loading. --- examples/crazylegs.js | 14 +++++ interface/src/Application.cpp | 1 + interface/src/Application.h | 1 + libraries/fbx/src/FBXReader.cpp | 2 + libraries/fbx/src/FBXReader.h | 3 + .../script-engine/src/AnimationCache.cpp | 55 ++++++++++++++++++- libraries/script-engine/src/AnimationCache.h | 41 +++++++++++++- libraries/script-engine/src/ScriptEngine.cpp | 2 + 8 files changed, 117 insertions(+), 2 deletions(-) diff --git a/examples/crazylegs.js b/examples/crazylegs.js index 6311aea6e4..3554def63a 100644 --- a/examples/crazylegs.js +++ b/examples/crazylegs.js @@ -22,6 +22,8 @@ for (var i = 0; i < jointList.length; i++) { } print("# Joint list end"); +var foo = AnimationCache.getAnimation("http://www.fungibleinsight.com/faces/hip_hop_dancing_2.fbx"); + Script.update.connect(function(deltaTime) { cumulativeTime += deltaTime; MyAvatar.setJointData("joint_R_hip", Quat.fromPitchYawRollDegrees(0.0, 0.0, AMPLITUDE * Math.sin(cumulativeTime * FREQUENCY))); @@ -30,6 +32,18 @@ Script.update.connect(function(deltaTime) { AMPLITUDE * (1.0 + Math.sin(cumulativeTime * FREQUENCY)))); MyAvatar.setJointData("joint_L_knee", Quat.fromPitchYawRollDegrees(0.0, 0.0, AMPLITUDE * (1.0 - Math.sin(cumulativeTime * FREQUENCY)))); + + if (foo.jointNames.length > 0) { + print(foo.jointNames); + print(foo.frames.length); + if (foo.frames.length > 0) { + print(foo.frames[0].rotations.length); + if (foo.frames[0].rotations.length > 0) { + var rot = foo.frames[0].rotations[0]; + print(rot.x + " " + rot.y + " " + rot.z + " " + rot.w); + } + } + } }); Script.scriptEnding.connect(function() { diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 1fabca3711..91fdff96b5 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3387,6 +3387,7 @@ void Application::loadScript(const QString& scriptName) { scriptEngine->registerGlobalObject("Menu", MenuScriptingInterface::getInstance()); scriptEngine->registerGlobalObject("Settings", SettingsScriptingInterface::getInstance()); scriptEngine->registerGlobalObject("AudioDevice", AudioDeviceScriptingInterface::getInstance()); + scriptEngine->registerGlobalObject("AnimationCache", &_animationCache); QThread* workerThread = new QThread(this); diff --git a/interface/src/Application.h b/interface/src/Application.h index 6a14788caa..4606a3d622 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -468,6 +468,7 @@ private: QSet _keysPressed; GeometryCache _geometryCache; + AnimationCache _animationCache; TextureCache _textureCache; GlowEffect _glowEffect; diff --git a/libraries/fbx/src/FBXReader.cpp b/libraries/fbx/src/FBXReader.cpp index 6c51e11150..5fad95be3d 100644 --- a/libraries/fbx/src/FBXReader.cpp +++ b/libraries/fbx/src/FBXReader.cpp @@ -72,6 +72,8 @@ bool FBXGeometry::hasBlendedMeshes() const { } static int fbxGeometryMetaTypeId = qRegisterMetaType(); +static int fbxAnimationFrameMetaTypeId = qRegisterMetaType(); +static int fbxAnimationFrameVectorMetaTypeId = qRegisterMetaType >(); template QVariant readBinaryArray(QDataStream& in) { quint32 arrayLength; diff --git a/libraries/fbx/src/FBXReader.h b/libraries/fbx/src/FBXReader.h index 8d45c2ae23..2f840e868e 100644 --- a/libraries/fbx/src/FBXReader.h +++ b/libraries/fbx/src/FBXReader.h @@ -146,6 +146,9 @@ public: QVector rotations; }; +Q_DECLARE_METATYPE(FBXAnimationFrame) +Q_DECLARE_METATYPE(QVector) + /// An attachment to an FBX document. class FBXAttachment { public: diff --git a/libraries/script-engine/src/AnimationCache.cpp b/libraries/script-engine/src/AnimationCache.cpp index 2a6aac1992..078dc382c4 100644 --- a/libraries/script-engine/src/AnimationCache.cpp +++ b/libraries/script-engine/src/AnimationCache.cpp @@ -10,11 +10,20 @@ // #include +#include #include #include "AnimationCache.h" -QSharedPointer AnimationCache::getAnimation(const QUrl& url) { +static int animationPointerMetaTypeId = qRegisterMetaType(); + +AnimationPointer AnimationCache::getAnimation(const QUrl& url) { + if (QThread::currentThread() != thread()) { + AnimationPointer result; + QMetaObject::invokeMethod(this, "getAnimation", Qt::BlockingQueuedConnection, + Q_RETURN_ARG(AnimationPointer, result), Q_ARG(const QUrl&, url)); + return result; + } return getResource(url).staticCast(); } @@ -54,6 +63,30 @@ void AnimationReader::run() { _reply->deleteLater(); } +QStringList Animation::getJointNames() const { + if (QThread::currentThread() != thread()) { + QStringList result; + QMetaObject::invokeMethod(const_cast(this), "getJointNames", Qt::BlockingQueuedConnection, + Q_RETURN_ARG(QStringList, result)); + return result; + } + QStringList names; + foreach (const FBXJoint& joint, _geometry.joints) { + names.append(joint.name); + } + return names; +} + +QVector Animation::getFrames() const { + if (QThread::currentThread() != thread()) { + QVector result; + QMetaObject::invokeMethod(const_cast(this), "getFrames", Qt::BlockingQueuedConnection, + Q_RETURN_ARG(QVector, result)); + return result; + } + return _geometry.animationFrames; +} + void Animation::setGeometry(const FBXGeometry& geometry) { _geometry = geometry; finishedLoading(true); @@ -63,3 +96,23 @@ void Animation::downloadFinished(QNetworkReply* reply) { // send the reader off to the thread pool QThreadPool::globalInstance()->start(new AnimationReader(_self, reply)); } + +QStringList AnimationObject::getJointNames() const { + return qscriptvalue_cast(thisObject())->getJointNames(); +} + +QVector AnimationObject::getFrames() const { + return qscriptvalue_cast(thisObject())->getFrames(); +} + +QVector AnimationFrameObject::getRotations() const { + return qscriptvalue_cast(thisObject()).rotations; +} + +void registerAnimationTypes(QScriptEngine* engine) { + qScriptRegisterSequenceMetaType >(engine); + engine->setDefaultPrototype(qMetaTypeId(), engine->newQObject( + new AnimationFrameObject(), QScriptEngine::ScriptOwnership)); + engine->setDefaultPrototype(qMetaTypeId(), engine->newQObject( + new AnimationObject(), QScriptEngine::ScriptOwnership)); +} diff --git a/libraries/script-engine/src/AnimationCache.h b/libraries/script-engine/src/AnimationCache.h index bb8a0f2313..a382ef40d7 100644 --- a/libraries/script-engine/src/AnimationCache.h +++ b/libraries/script-engine/src/AnimationCache.h @@ -12,19 +12,27 @@ #ifndef hifi_AnimationCache_h #define hifi_AnimationCache_h +#include + #include #include +class QScriptEngine; + class Animation; +typedef QSharedPointer AnimationPointer; + /// Scriptable interface for FBX animation loading. class AnimationCache : public ResourceCache { Q_OBJECT public: - QSharedPointer getAnimation(const QUrl& url); + Q_INVOKABLE AnimationPointer getAnimation(const QString& url) { return getAnimation(QUrl(url)); } + + Q_INVOKABLE AnimationPointer getAnimation(const QUrl& url); protected: @@ -32,6 +40,8 @@ protected: const QSharedPointer& fallback, bool delayLoad, const void* extra); }; +Q_DECLARE_METATYPE(AnimationPointer) + /// An animation loaded from the network. class Animation : public Resource { Q_OBJECT @@ -42,6 +52,10 @@ public: const FBXGeometry& getGeometry() const { return _geometry; } + Q_INVOKABLE QStringList getJointNames() const; + + Q_INVOKABLE QVector getFrames() const; + protected: Q_INVOKABLE void setGeometry(const FBXGeometry& geometry); @@ -53,4 +67,29 @@ private: FBXGeometry _geometry; }; +/// Scriptable wrapper for animation pointers. +class AnimationObject : public QObject, protected QScriptable { + Q_OBJECT + Q_PROPERTY(QStringList jointNames READ getJointNames) + Q_PROPERTY(QVector frames READ getFrames) + +public: + + Q_INVOKABLE QStringList getJointNames() const; + + Q_INVOKABLE QVector getFrames() const; +}; + +/// Scriptable wrapper for animation frames. +class AnimationFrameObject : public QObject, protected QScriptable { + Q_OBJECT + Q_PROPERTY(QVector rotations READ getRotations) + +public: + + Q_INVOKABLE QVector getRotations() const; +}; + +void registerAnimationTypes(QScriptEngine* engine); + #endif // hifi_AnimationCache_h diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index b0e2d1495b..60321e7c54 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -180,11 +180,13 @@ void ScriptEngine::init() { registerVoxelMetaTypes(&_engine); registerEventTypes(&_engine); registerMenuItemProperties(&_engine); + registerAnimationTypes(&_engine); qScriptRegisterMetaType(&_engine, ParticlePropertiesToScriptValue, ParticlePropertiesFromScriptValue); qScriptRegisterMetaType(&_engine, ParticleIDtoScriptValue, ParticleIDfromScriptValue); qScriptRegisterSequenceMetaType >(&_engine); qScriptRegisterSequenceMetaType >(&_engine); + qScriptRegisterSequenceMetaType >(&_engine); qScriptRegisterSequenceMetaType >(&_engine); QScriptValue soundConstructorValue = _engine.newFunction(soundConstructor); From a46d3fd254e30f0095a555ccd1fd09b701002ed7 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 19:57:37 -0700 Subject: [PATCH 430/595] first cut at local audio spatialization working --- interface/src/Audio.cpp | 31 ++++++++++++++++++++----------- interface/src/AudioReflector.cpp | 2 +- interface/src/Menu.cpp | 4 ++++ interface/src/Menu.h | 19 +++++++++++-------- 4 files changed, 36 insertions(+), 20 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index daf6a4a7ee..94e1cd336a 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -404,17 +404,6 @@ void Audio::handleAudioInput() { QByteArray inputByteArray = _inputDevice->readAll(); - // send our local loopback to any interested parties - if (_processSpatialAudio && !_muted && _audioOutput) { - if (false) { - // local audio is sent already resampled to match the output format, so processors - // can easily handle the audio in a format ready to post back to the audio device - //emit processLocalAudio(_spatialAudioStart, resampledInputByteArray, _outputFormat); - } else { - emit processLocalAudio(_spatialAudioStart, inputByteArray, _outputFormat); - } - } - if (Menu::getInstance()->isOptionChecked(MenuOption::EchoLocalAudio) && !_muted && _audioOutput) { // if this person wants local loopback add that to the locally injected audio @@ -575,6 +564,26 @@ void Audio::handleAudioInput() { _lastInputLoudness = 0; } + // at this point we have clean monoAudioSamples, which match our target output... this is what we should send + // to our interested listeners + // send our local loopback to any interested parties + if (_processSpatialAudio && !_muted && _audioOutput && + (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingProcessLocalAudio))) { + // local audio is sent already resampled to match the network input format, so processors + // can easily handle the audio in a format ready to post back to the audio device + const int NUM_CHANNELS = 2; + QByteArray stereoInputData; + stereoInputData.resize(NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL * NUM_CHANNELS * sizeof(int16_t)); + int16_t* stereoSamples = (int16_t*)stereoInputData.data(); + const float LOCAL_SIGNAL_ATTENUATION = 0.125f; + for (int i = 0; i < NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL; i++) { + stereoSamples[i* NUM_CHANNELS] = monoAudioSamples[i] * LOCAL_SIGNAL_ATTENUATION; + stereoSamples[(i * NUM_CHANNELS) + 1] = monoAudioSamples[i] * LOCAL_SIGNAL_ATTENUATION; + } + + emit processLocalAudio(_spatialAudioStart, stereoInputData, _desiredOutputFormat); + } + if (_proceduralAudioOutput) { processProceduralAudio(monoAudioSamples, NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL); } diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index fa4573b1b4..0bb2e7224e 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -224,7 +224,7 @@ void AudioReflector::injectAudiblePoint(const AudiblePoint& audiblePoint, _audio->addSpatialAudioToBuffer(sampleTimeRight, attenuatedRightSamples, totalNumberOfSamples); } void AudioReflector::processLocalAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { - // nothing yet, but will do local reflections too... + echoAudio(sampleTime, samples, format); } void AudioReflector::processInboundAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index a02c8342a7..af4825fac8 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -423,6 +423,10 @@ Menu::Menu() : Qt::CTRL | Qt::SHIFT | Qt::Key_X, true); + addCheckableActionToQMenuAndActionHash(spatialAudioMenu, MenuOption::AudioSpatialProcessingProcessLocalAudio, + Qt::CTRL | Qt::SHIFT | Qt::Key_A, + true); + addActionToQMenuAndActionHash(developerMenu, MenuOption::PasteToVoxel, Qt::CTRL | Qt::SHIFT | Qt::Key_V, this, diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 5fcbf11724..bc05e8921b 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -237,15 +237,18 @@ namespace MenuOption { const QString Atmosphere = "Atmosphere"; const QString AudioNoiseReduction = "Audio Noise Reduction"; const QString AudioToneInjection = "Inject Test Tone"; + const QString AudioSpatialProcessing = "Audio Spatial Processing"; - const QString AudioSpatialProcessingIncudeOriginal = "Audio Spatial Processing includes Original"; - const QString AudioSpatialProcessingSeparateEars = "Audio Spatial Processing separates ears"; - const QString AudioSpatialProcessingPreDelay = "Audio Spatial Processing add Pre-Delay"; - const QString AudioSpatialProcessingStereoSource = "Audio Spatial Processing Stereo Source"; - const QString AudioSpatialProcessingHeadOriented = "Audio Spatial Processing Head Oriented"; - const QString AudioSpatialProcessingWithDiffusions = "Audio Spatial Processing With Diffusions"; - const QString AudioSpatialProcessingRenderPaths = "Audio Spatial Processing Render Paths"; - const QString AudioSpatialProcessingSlightlyRandomSurfaces = "Audio Spatial Processing Slightly Random Surfaces"; + const QString AudioSpatialProcessingHeadOriented = "Head Oriented"; + const QString AudioSpatialProcessingIncudeOriginal = "Includes Network Original"; + const QString AudioSpatialProcessingPreDelay = "Add Pre-Delay"; + const QString AudioSpatialProcessingProcessLocalAudio = "Process Local Audio"; + const QString AudioSpatialProcessingRenderPaths = "Render Paths"; + const QString AudioSpatialProcessingSeparateEars = "Separate Ears"; + const QString AudioSpatialProcessingSlightlyRandomSurfaces = "Slightly Random Surfaces"; + const QString AudioSpatialProcessingStereoSource = "Stereo Source"; + const QString AudioSpatialProcessingWithDiffusions = "With Diffusions"; + const QString Avatars = "Avatars"; const QString Bandwidth = "Bandwidth Display"; const QString BandwidthDetails = "Bandwidth Details"; From 82d9c50dc5250016b14997e6ccf2459db028d28e Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 20:11:53 -0700 Subject: [PATCH 431/595] moved all local processing to AudioReflector --- interface/src/Audio.cpp | 16 +++------------- interface/src/AudioReflector.cpp | 22 +++++++++++++++++++++- 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 94e1cd336a..551acaad84 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -567,21 +567,11 @@ void Audio::handleAudioInput() { // at this point we have clean monoAudioSamples, which match our target output... this is what we should send // to our interested listeners // send our local loopback to any interested parties - if (_processSpatialAudio && !_muted && _audioOutput && - (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingProcessLocalAudio))) { + if (_processSpatialAudio && !_muted && _audioOutput) { // local audio is sent already resampled to match the network input format, so processors // can easily handle the audio in a format ready to post back to the audio device - const int NUM_CHANNELS = 2; - QByteArray stereoInputData; - stereoInputData.resize(NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL * NUM_CHANNELS * sizeof(int16_t)); - int16_t* stereoSamples = (int16_t*)stereoInputData.data(); - const float LOCAL_SIGNAL_ATTENUATION = 0.125f; - for (int i = 0; i < NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL; i++) { - stereoSamples[i* NUM_CHANNELS] = monoAudioSamples[i] * LOCAL_SIGNAL_ATTENUATION; - stereoSamples[(i * NUM_CHANNELS) + 1] = monoAudioSamples[i] * LOCAL_SIGNAL_ATTENUATION; - } - - emit processLocalAudio(_spatialAudioStart, stereoInputData, _desiredOutputFormat); + QByteArray monoInputData((char*)monoAudioSamples, NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL * sizeof(int16_t)); + emit processLocalAudio(_spatialAudioStart, monoInputData, _desiredInputFormat); } if (_proceduralAudioOutput) { diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 0bb2e7224e..0450a66e7b 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -223,8 +223,28 @@ void AudioReflector::injectAudiblePoint(const AudiblePoint& audiblePoint, _audio->addSpatialAudioToBuffer(sampleTimeLeft, attenuatedLeftSamples, totalNumberOfSamples); _audio->addSpatialAudioToBuffer(sampleTimeRight, attenuatedRightSamples, totalNumberOfSamples); } + void AudioReflector::processLocalAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { - echoAudio(sampleTime, samples, format); + if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingProcessLocalAudio)) { + const int NUM_CHANNELS_INPUT = 1; + const int NUM_CHANNELS_OUTPUT = 2; + const int EXPECTED_SAMPLE_RATE = 24000; + if (format.channelCount() == NUM_CHANNELS_INPUT && format.sampleRate() == EXPECTED_SAMPLE_RATE) { + QAudioFormat outputFormat = format; + outputFormat.setChannelCount(NUM_CHANNELS_OUTPUT); + QByteArray stereoInputData; + stereoInputData.resize(samples.size() * NUM_CHANNELS_OUTPUT); + int numberOfSamples = samples.size() / sizeof(int16_t); + int16_t* monoSamples = (int16_t*)samples.data(); + int16_t* stereoSamples = (int16_t*)stereoInputData.data(); + const float LOCAL_SIGNAL_ATTENUATION = 0.125f; + for (int i = 0; i < numberOfSamples; i++) { + stereoSamples[i* NUM_CHANNELS_OUTPUT] = monoSamples[i] * LOCAL_SIGNAL_ATTENUATION; + stereoSamples[(i * NUM_CHANNELS_OUTPUT) + 1] = monoSamples[i] * LOCAL_SIGNAL_ATTENUATION; + } + echoAudio(sampleTime, stereoInputData, outputFormat); + } + } } void AudioReflector::processInboundAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { From 040df97be27cf5b0b2635ae2f83d500294cfd1b2 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 20:23:47 -0700 Subject: [PATCH 432/595] more cleanup --- interface/src/Audio.cpp | 5 ----- interface/src/Audio.h | 14 ++++++-------- 2 files changed, 6 insertions(+), 13 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 551acaad84..d6deb66e2a 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -665,11 +665,6 @@ void Audio::addReceivedAudioToBuffer(const QByteArray& audioByteArray) { _lastReceiveTime = currentReceiveTime; } -unsigned int Audio::timeValToSampleTick(const quint64 time, int sampleRate) { - unsigned int sample = (unsigned int)(time / 1000000 * sampleRate); - return sample; -} - void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, const QByteArray& spatialAudio, unsigned int numSamples) { // Calculate the number of remaining samples available. The source spatial audio buffer will get // clipped if there are insufficient samples available in the accumulation buffer. diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 99d9bd4884..f2fed15f65 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -167,16 +167,14 @@ private: GLuint _boxTextureId; QRect _iconBounds; - // Audio callback in class context. + /// Audio callback in class context. inline void performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* outputRight); - // Process received audio by spatial attenuation geometric response - bool _processSpatialAudio; - unsigned int _spatialAudioStart; /// Start of spatial audio interval (in sample rate time base) - unsigned int _spatialAudioFinish; /// End of spatial audio interval (in sample rate time base) - AudioRingBuffer _spatialAudioRingBuffer; /// Spatially processed audio - - unsigned int timeValToSampleTick(const quint64 time, int sampleRate); + + bool _processSpatialAudio; /// Process received audio by spatial audio hooks + unsigned int _spatialAudioStart; /// Start of spatial audio interval (in sample rate time base) + unsigned int _spatialAudioFinish; /// End of spatial audio interval (in sample rate time base) + AudioRingBuffer _spatialAudioRingBuffer; /// Spatially processed audio // Process procedural audio by // 1. Echo to the local procedural output device From 67de87d1141c204a679dd246c13164832323b1a6 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 21:31:35 -0700 Subject: [PATCH 433/595] added slider for local audio attenuation --- examples/audioReflectorTools.js | 69 ++++++++++++++++++++++++++++++++ interface/src/AudioReflector.cpp | 8 ++-- interface/src/AudioReflector.h | 6 +++ 3 files changed, 80 insertions(+), 3 deletions(-) diff --git a/examples/audioReflectorTools.js b/examples/audioReflectorTools.js index acab563d4c..532cae84bc 100644 --- a/examples/audioReflectorTools.js +++ b/examples/audioReflectorTools.js @@ -14,6 +14,7 @@ var delayScale = 100.0; var fanoutScale = 10.0; var speedScale = 20; var factorScale = 5.0; +var localFactorScale = 1.0; var reflectiveScale = 100.0; var diffusionScale = 100.0; var absorptionScale = 100.0; @@ -223,6 +224,45 @@ var factorThumb = Overlays.addOverlay("image", { alpha: 1 }); +var localFactorY = topY; +topY += sliderHeight; + +var localFactorLabel = Overlays.addOverlay("text", { + x: 40, + y: localFactorY, + width: 60, + height: sliderHeight, + color: { red: 0, green: 0, blue: 0}, + textColor: { red: 255, green: 255, blue: 255}, + topMargin: 6, + leftMargin: 5, + text: "Local\nFactor:" + }); + + +var localFactorSlider = Overlays.addOverlay("image", { + // alternate form of expressing bounds + bounds: { x: 100, y: localFactorY, width: 150, height: sliderHeight}, + subImage: { x: 46, y: 0, width: 200, height: 71 }, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/slider.png", + color: { red: 255, green: 255, blue: 255}, + alpha: 1 + }); + + +var localFactorMinThumbX = 110; +var localFactorMaxThumbX = localFactorMinThumbX + 110; +var localFactorThumbX = localFactorMinThumbX + ((localFactorMaxThumbX - localFactorMinThumbX) * (AudioReflector.getLocalAudioAttenuationFactor() / localFactorScale)); +var localFactorThumb = Overlays.addOverlay("image", { + x: localFactorThumbX, + y: localFactorY+9, + width: 18, + height: 17, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/thumb.png", + color: { red: 0, green: 128, blue: 128}, + alpha: 1 + }); + var reflectiveY = topY; topY += sliderHeight; @@ -347,6 +387,10 @@ function scriptEnding() { Overlays.deleteOverlay(factorThumb); Overlays.deleteOverlay(factorSlider); + Overlays.deleteOverlay(localFactorLabel); + Overlays.deleteOverlay(localFactorThumb); + Overlays.deleteOverlay(localFactorSlider); + Overlays.deleteOverlay(speedLabel); Overlays.deleteOverlay(speedThumb); Overlays.deleteOverlay(speedSlider); @@ -389,6 +433,7 @@ var movingSliderDelay = false; var movingSliderFanout = false; var movingSliderSpeed = false; var movingSliderFactor = false; +var movingSliderLocalFactor = false; var movingSliderReflective = false; var movingSliderDiffusion = false; var movingSliderAbsorption = false; @@ -444,6 +489,19 @@ function mouseMoveEvent(event) { AudioReflector.setDistanceAttenuationScalingFactor(factor); } + if (movingSliderLocalFactor) { + newThumbX = event.x - thumbClickOffsetX; + if (newThumbX < localFactorMinThumbX) { + newThumbX = localFactorMminThumbX; + } + if (newThumbX > localFactorMaxThumbX) { + newThumbX = localFactorMaxThumbX; + } + Overlays.editOverlay(localFactorThumb, { x: newThumbX } ); + var localFactor = ((newThumbX - localFactorMinThumbX) / (localFactorMaxThumbX - localFactorMinThumbX)) * localFactorScale; + AudioReflector.setLocalAudioAttenuationFactor(localFactor); + } + if (movingSliderAbsorption) { newThumbX = event.x - thumbClickOffsetX; if (newThumbX < absorptionMinThumbX) { @@ -504,6 +562,10 @@ function mousePressEvent(event) { movingSliderFactor = true; thumbClickOffsetX = event.x - factorThumbX; } + if (clickedOverlay == localFactorThumb) { + movingSliderLocalFactor = true; + thumbClickOffsetX = event.x - localFactorThumbX; + } if (clickedOverlay == diffusionThumb) { movingSliderDiffusion = true; thumbClickOffsetX = event.x - diffusionThumbX; @@ -543,6 +605,13 @@ function mouseReleaseEvent(event) { factorThumbX = newThumbX; } + if (movingSliderLocalFactor) { + movingSliderLocalFactor = false; + var localFactor = ((newThumbX - localFactorMinThumbX) / (localFactorMaxThumbX - localFactorMinThumbX)) * localFactorScale; + AudioReflector.setLocalAudioAttenuationFactor(localFactor); + localFactorThumbX = newThumbX; + } + if (movingSliderReflective) { movingSliderReflective = false; var reflective = ((newThumbX - reflectiveMinThumbX) / (reflectiveMaxThumbX - reflectiveMinThumbX)) * reflectiveScale; diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 0450a66e7b..0640ed038e 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -18,6 +18,7 @@ const float DEFAULT_DISTANCE_SCALING_FACTOR = 2.0f; const float MAXIMUM_DELAY_MS = 1000.0 * 20.0f; // stop reflecting after path is this long const int DEFAULT_DIFFUSION_FANOUT = 5; const int ABSOLUTE_MAXIMUM_BOUNCE_COUNT = 10; +const float DEFAULT_LOCAL_ATTENUATION_FACTOR = 0.125; const float SLIGHTLY_SHORT = 0.999f; // slightly inside the distance so we're on the inside of the reflection point @@ -29,6 +30,7 @@ AudioReflector::AudioReflector(QObject* parent) : _preDelay(DEFAULT_PRE_DELAY), _soundMsPerMeter(DEFAULT_MS_DELAY_PER_METER), _distanceAttenuationScalingFactor(DEFAULT_DISTANCE_SCALING_FACTOR), + _localAudioAttenuationFactor(DEFAULT_LOCAL_ATTENUATION_FACTOR), _diffusionFanout(DEFAULT_DIFFUSION_FANOUT), _absorptionRatio(DEFAULT_ABSORPTION_RATIO), _diffusionRatio(DEFAULT_DIFFUSION_RATIO), @@ -36,6 +38,7 @@ AudioReflector::AudioReflector(QObject* parent) : _lastPreDelay(DEFAULT_PRE_DELAY), _lastSoundMsPerMeter(DEFAULT_MS_DELAY_PER_METER), _lastDistanceAttenuationScalingFactor(DEFAULT_DISTANCE_SCALING_FACTOR), + _lastLocalAudioAttenuationFactor(DEFAULT_LOCAL_ATTENUATION_FACTOR), _lastDiffusionFanout(DEFAULT_DIFFUSION_FANOUT), _lastAbsorptionRatio(DEFAULT_ABSORPTION_RATIO), _lastDiffusionRatio(DEFAULT_DIFFUSION_RATIO) @@ -237,10 +240,9 @@ void AudioReflector::processLocalAudio(unsigned int sampleTime, const QByteArray int numberOfSamples = samples.size() / sizeof(int16_t); int16_t* monoSamples = (int16_t*)samples.data(); int16_t* stereoSamples = (int16_t*)stereoInputData.data(); - const float LOCAL_SIGNAL_ATTENUATION = 0.125f; for (int i = 0; i < numberOfSamples; i++) { - stereoSamples[i* NUM_CHANNELS_OUTPUT] = monoSamples[i] * LOCAL_SIGNAL_ATTENUATION; - stereoSamples[(i * NUM_CHANNELS_OUTPUT) + 1] = monoSamples[i] * LOCAL_SIGNAL_ATTENUATION; + stereoSamples[i* NUM_CHANNELS_OUTPUT] = monoSamples[i] * _localAudioAttenuationFactor; + stereoSamples[(i * NUM_CHANNELS_OUTPUT) + 1] = monoSamples[i] * _localAudioAttenuationFactor; } echoAudio(sampleTime, stereoInputData, outputFormat); } diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 7867df3d9b..79fcdda68d 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -93,6 +93,10 @@ public slots: float getDistanceAttenuationScalingFactor() const { return _distanceAttenuationScalingFactor; } void setDistanceAttenuationScalingFactor(float factor) { _distanceAttenuationScalingFactor = factor; } + /// scales attenuation of local audio to be louder or softer than the default attenuation + float getLocalAudioAttenuationFactor() const { return _localAudioAttenuationFactor; } + void setLocalAudioAttenuationFactor(float factor) { _localAudioAttenuationFactor = factor; } + /// number of points of diffusion from each reflection point, as fanout increases there are more chances for secondary /// echoes, but each diffusion ray is quieter and therefore more likely to be below the sound floor int getDiffusionFanout() const { return _diffusionFanout; } @@ -171,6 +175,7 @@ private: float _preDelay; float _soundMsPerMeter; float _distanceAttenuationScalingFactor; + float _localAudioAttenuationFactor; int _diffusionFanout; // number of points of diffusion from each reflection point @@ -186,6 +191,7 @@ private: float _lastPreDelay; float _lastSoundMsPerMeter; float _lastDistanceAttenuationScalingFactor; + float _lastLocalAudioAttenuationFactor; int _lastDiffusionFanout; float _lastAbsorptionRatio; float _lastDiffusionRatio; From ba361b0f62bb0834638efe7fdb88d32a8fb903fa Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 15 Apr 2014 21:50:44 -0700 Subject: [PATCH 434/595] add local audio stats --- interface/src/ui/Stats.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp index 2b70b3538c..98955b34f5 100644 --- a/interface/src/ui/Stats.cpp +++ b/interface/src/ui/Stats.cpp @@ -343,7 +343,7 @@ void Stats::display( lines = _expanded ? 12 : 3; if (_expanded && Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessing)) { - lines += 6; // spatial audio processing adds 1 spacing line and 5 extra lines of info + lines += 7; // spatial audio processing adds 1 spacing line and 6 extra lines of info } drawBackground(backgroundColor, horizontalOffset, 0, glWidget->width() - horizontalOffset, lines * STATS_PELS_PER_LINE + 10); @@ -550,6 +550,14 @@ void Stats::display( verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + sprintf(reflectionsStatus, "Local Audio: %s Attenuation: %5.3f", + (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingProcessLocalAudio) + ? "yes" : "no"), + audioReflector->getLocalAudioAttenuationFactor()); + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + bool diffusionEnabled = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions); int fanout = diffusionEnabled ? audioReflector->getDiffusionFanout() : 0; int diffusionPaths = diffusionEnabled ? audioReflector->getDiffusionPathCount() : 0; From c67e42be5e0087e9d142b2c19fc5bcdb56bdd403 Mon Sep 17 00:00:00 2001 From: Stojce Slavkovski Date: Wed, 16 Apr 2014 07:46:15 +0200 Subject: [PATCH 435/595] Moved function into .cpp --- interface/src/Menu.cpp | 7 +++++++ interface/src/Menu.h | 7 +------ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index c9a1087618..e4de93c9bf 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -1505,3 +1505,10 @@ void Menu::removeMenuItem(const QString& menu, const QString& menuitem) { QMenuBar::repaint(); }; +QString Menu::getSnapshotsLocation() const { + if (_snapshotsLocation.isNull() || _snapshotsLocation.isEmpty() || QDir(_snapshotsLocation).exists() == false) { + return QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); + } + return _snapshotsLocation; +} + diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 2c39ea3b99..45291802cb 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -81,12 +81,7 @@ public: void setFieldOfView(float fieldOfView) { _fieldOfView = fieldOfView; } float getFaceshiftEyeDeflection() const { return _faceshiftEyeDeflection; } void setFaceshiftEyeDeflection(float faceshiftEyeDeflection) { _faceshiftEyeDeflection = faceshiftEyeDeflection; } - QString getSnapshotsLocation() const { - if (_snapshotsLocation.isNull() || _snapshotsLocation.isEmpty() || QDir(_snapshotsLocation).exists() == false) { - return QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); - } - return _snapshotsLocation; - } + QString getSnapshotsLocation() const; void setSnapshotsLocation(QString snapshotsLocation) { _snapshotsLocation = snapshotsLocation; } BandwidthDialog* getBandwidthDialog() const { return _bandwidthDialog; } From 97e45e8fe5b675b4425b0b1d0f4ad97e71b7fa7d Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 16 Apr 2014 10:56:27 -0700 Subject: [PATCH 436/595] re-instate connect behavior in DS so killed nodes re-connect, amend #2675 --- domain-server/src/DomainServer.cpp | 35 +++++--------------- domain-server/src/DomainServer.h | 5 ++- libraries/networking/src/LimitedNodeList.cpp | 2 +- libraries/networking/src/LimitedNodeList.h | 2 +- libraries/networking/src/Node.cpp | 3 +- libraries/networking/src/Node.h | 2 +- libraries/networking/src/NodeList.cpp | 10 ++++-- libraries/networking/src/PacketHeaders.h | 5 +-- 8 files changed, 25 insertions(+), 39 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 1bda2aa75c..6634dde5b7 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -311,8 +311,7 @@ const NodeSet STATICALLY_ASSIGNED_NODES = NodeSet() << NodeType::AudioMixer << NodeType::MetavoxelServer; -void DomainServer::addNodeToNodeListAndConfirmConnection(const QByteArray& packet, const HifiSockAddr& senderSockAddr, - const QJsonObject& authJsonObject) { +void DomainServer::addNodeToNodeListAndConfirmConnection(const QByteArray& packet, const HifiSockAddr& senderSockAddr) { NodeType_t nodeType; HifiSockAddr publicSockAddr, localSockAddr; @@ -336,7 +335,8 @@ void DomainServer::addNodeToNodeListAndConfirmConnection(const QByteArray& packe // create a new session UUID for this node QUuid nodeUUID = QUuid::createUuid(); - SharedNodePointer newNode = LimitedNodeList::getInstance()->addOrUpdateNode(nodeUUID, nodeType, publicSockAddr, localSockAddr); + SharedNodePointer newNode = LimitedNodeList::getInstance()->addOrUpdateNode(nodeUUID, nodeType, + publicSockAddr, localSockAddr); // when the newNode is created the linked data is also created // if this was a static assignment set the UUID, set the sendingSockAddr @@ -345,12 +345,6 @@ void DomainServer::addNodeToNodeListAndConfirmConnection(const QByteArray& packe nodeData->setStaticAssignmentUUID(assignmentUUID); nodeData->setSendingSockAddr(senderSockAddr); - if (!authJsonObject.isEmpty()) { - // pull the connection secret from the authJsonObject and set it as the connection secret for this node - QUuid connectionSecret(authJsonObject["data"].toObject()["connection_secret"].toString()); - newNode->setConnectionSecret(connectionSecret); - } - // reply back to the user with a PacketTypeDomainList sendDomainListToNode(newNode, senderSockAddr, nodeInterestListFromPacket(packet, numPreInterestBytes)); } @@ -361,18 +355,6 @@ int DomainServer::parseNodeDataFromByteArray(NodeType_t& nodeType, HifiSockAddr& QDataStream packetStream(packet); packetStream.skipRawData(numBytesForPacketHeader(packet)); - if (packetTypeForPacket(packet) == PacketTypeDomainConnectRequest) { - // we need to skip a quint8 that indicates if there is a registration token - // and potentially the registration token itself - quint8 hasRegistrationToken; - packetStream >> hasRegistrationToken; - - if (hasRegistrationToken) { - QByteArray registrationToken; - packetStream >> registrationToken; - } - } - packetStream >> nodeType; packetStream >> publicSockAddr >> localSockAddr; @@ -648,7 +630,11 @@ void DomainServer::processDatagram(const QByteArray& receivedPacket, const HifiS if (nodeList->packetVersionAndHashMatch(receivedPacket)) { PacketType requestType = packetTypeForPacket(receivedPacket); - if (requestType == PacketTypeDomainListRequest) { + if (requestType == PacketTypeDomainConnectRequest) { + // add this node to our NodeList + // and send back session UUID right away + addNodeToNodeListAndConfirmConnection(receivedPacket, senderSockAddr); + } else if (requestType == PacketTypeDomainListRequest) { QUuid nodeUUID = uuidFromPacketHeader(receivedPacket); if (!nodeUUID.isNull() && nodeList->nodeWithUUID(nodeUUID)) { @@ -665,12 +651,7 @@ void DomainServer::processDatagram(const QByteArray& receivedPacket, const HifiS checkInNode->setLastHeardMicrostamp(timeNow); sendDomainListToNode(checkInNode, senderSockAddr, nodeInterestListFromPacket(receivedPacket, numNodeInfoBytes)); - } else { - // new node - add this node to our NodeList - // and send back session UUID right away - addNodeToNodeListAndConfirmConnection(receivedPacket, senderSockAddr); } - } else if (requestType == PacketTypeNodeJsonStats) { SharedNodePointer matchingNode = nodeList->sendingNodeForPacket(receivedPacket); if (matchingNode) { diff --git a/domain-server/src/DomainServer.h b/domain-server/src/DomainServer.h index 1400fadee3..0153fac49d 100644 --- a/domain-server/src/DomainServer.h +++ b/domain-server/src/DomainServer.h @@ -24,7 +24,7 @@ #include #include -#include +#include #include "DTLSServerSession.h" @@ -57,8 +57,7 @@ private: void processDatagram(const QByteArray& receivedPacket, const HifiSockAddr& senderSockAddr); - void addNodeToNodeListAndConfirmConnection(const QByteArray& packet, const HifiSockAddr& senderSockAddr, - const QJsonObject& authJsonObject = QJsonObject()); + void addNodeToNodeListAndConfirmConnection(const QByteArray& packet, const HifiSockAddr& senderSockAddr); int parseNodeDataFromByteArray(NodeType_t& nodeType, HifiSockAddr& publicSockAddr, HifiSockAddr& localSockAddr, const QByteArray& packet, const HifiSockAddr& senderSockAddr); NodeSet nodeInterestListFromPacket(const QByteArray& packet, int numPreceedingBytes); diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index b0b048dde4..60fbe9b3a6 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -331,7 +331,7 @@ void LimitedNodeList::processKillNode(const QByteArray& dataByteArray) { killNodeWithUUID(nodeUUID); } -SharedNodePointer LimitedNodeList::addOrUpdateNode(const QUuid& uuid, char nodeType, +SharedNodePointer LimitedNodeList::addOrUpdateNode(const QUuid& uuid, NodeType_t nodeType, const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket) { _nodeHashMutex.lock(); diff --git a/libraries/networking/src/LimitedNodeList.h b/libraries/networking/src/LimitedNodeList.h index f941a8aa5d..ea9cb42436 100644 --- a/libraries/networking/src/LimitedNodeList.h +++ b/libraries/networking/src/LimitedNodeList.h @@ -78,7 +78,7 @@ public: SharedNodePointer nodeWithUUID(const QUuid& nodeUUID, bool blockingLock = true); SharedNodePointer sendingNodeForPacket(const QByteArray& packet); - SharedNodePointer addOrUpdateNode(const QUuid& uuid, char nodeType, + SharedNodePointer addOrUpdateNode(const QUuid& uuid, NodeType_t nodeType, const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket); SharedNodePointer updateSocketsForNode(const QUuid& uuid, const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket); diff --git a/libraries/networking/src/Node.cpp b/libraries/networking/src/Node.cpp index 9e6ea0dfec..15ee443e1f 100644 --- a/libraries/networking/src/Node.cpp +++ b/libraries/networking/src/Node.cpp @@ -42,7 +42,7 @@ const QString& NodeType::getNodeTypeName(NodeType_t nodeType) { return matchedTypeName != TypeNameHash.end() ? matchedTypeName.value() : UNKNOWN_NodeType_t_NAME; } -Node::Node(const QUuid& uuid, char type, const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket) : +Node::Node(const QUuid& uuid, NodeType_t type, const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket) : _type(type), _uuid(uuid), _wakeTimestamp(QDateTime::currentMSecsSinceEpoch()), @@ -58,6 +58,7 @@ Node::Node(const QUuid& uuid, char type, const HifiSockAddr& publicSocket, const _clockSkewUsec(0), _mutex() { + } Node::~Node() { diff --git a/libraries/networking/src/Node.h b/libraries/networking/src/Node.h index 3b3237cf6e..0f63d01525 100644 --- a/libraries/networking/src/Node.h +++ b/libraries/networking/src/Node.h @@ -45,7 +45,7 @@ namespace NodeType { class Node : public QObject { Q_OBJECT public: - Node(const QUuid& uuid, char type, const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket); + Node(const QUuid& uuid, NodeType_t type, const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket); ~Node(); bool operator==(const Node& otherNode) const { return _uuid == otherNode._uuid; } diff --git a/libraries/networking/src/NodeList.cpp b/libraries/networking/src/NodeList.cpp index 93377c7763..006d5e0509 100644 --- a/libraries/networking/src/NodeList.cpp +++ b/libraries/networking/src/NodeList.cpp @@ -376,10 +376,14 @@ void NodeList::sendDomainServerCheckIn() { } } - // construct the DS check in packet - QUuid packetUUID = (!_sessionUUID.isNull() ? _sessionUUID : _domainHandler.getAssignmentUUID()); + PacketType domainPacketType = _sessionUUID.isNull() + ? PacketTypeDomainConnectRequest : PacketTypeDomainListRequest; - QByteArray domainServerPacket = byteArrayWithPopulatedHeader(PacketTypeDomainListRequest, packetUUID); + // construct the DS check in packet + QUuid packetUUID = (domainPacketType == PacketTypeDomainListRequest + ? _sessionUUID : _domainHandler.getAssignmentUUID()); + + QByteArray domainServerPacket = byteArrayWithPopulatedHeader(domainPacketType, packetUUID); QDataStream packetStream(&domainServerPacket, QIODevice::Append); // pack our data to send to the domain-server diff --git a/libraries/networking/src/PacketHeaders.h b/libraries/networking/src/PacketHeaders.h index 3e2ff3d8b0..0f52f90962 100644 --- a/libraries/networking/src/PacketHeaders.h +++ b/libraries/networking/src/PacketHeaders.h @@ -58,7 +58,7 @@ enum PacketType { PacketTypeMetavoxelData, PacketTypeAvatarIdentity, PacketTypeAvatarBillboard, - PacketTypeDomainConnectRequest, // reusable + PacketTypeDomainConnectRequest, PacketTypeDomainServerRequireDTLS, PacketTypeNodeJsonStats, }; @@ -66,7 +66,8 @@ enum PacketType { typedef char PacketVersion; const QSet NON_VERIFIED_PACKETS = QSet() - << PacketTypeDomainServerRequireDTLS << PacketTypeDomainList << PacketTypeDomainListRequest + << PacketTypeDomainServerRequireDTLS << PacketTypeDomainConnectRequest + << PacketTypeDomainList << PacketTypeDomainListRequest << PacketTypeCreateAssignment << PacketTypeRequestAssignment << PacketTypeStunResponse << PacketTypeNodeJsonStats; From 57567becc8776048f0765459c26d55a5aaf6a287 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 16 Apr 2014 11:02:08 -0700 Subject: [PATCH 437/595] fix unexpected null parameter to disconnect, closes, #2663 --- libraries/networking/src/NodeList.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/libraries/networking/src/NodeList.cpp b/libraries/networking/src/NodeList.cpp index 006d5e0509..fbf2655269 100644 --- a/libraries/networking/src/NodeList.cpp +++ b/libraries/networking/src/NodeList.cpp @@ -209,8 +209,10 @@ void NodeList::reset() { // clear the domain connection information _domainHandler.clearConnectionInfo(); - // also disconnect from the DTLS socket readyRead() so it can handle handshaking - disconnect(_dtlsSocket, 0, this, 0); + // if we setup the DTLS socket, also disconnect from the DTLS socket readyRead() so it can handle handshaking + if (_dtlsSocket) { + disconnect(_dtlsSocket, 0, this, 0); + } } void NodeList::addNodeTypeToInterestSet(NodeType_t nodeTypeToAdd) { From 55d540a0eb6947192f51607fcf313ce4f387091b Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 16 Apr 2014 11:24:26 -0700 Subject: [PATCH 438/595] fix a typo in DomainServer.cpp --- domain-server/src/DomainServer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 6634dde5b7..1268ae739e 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -71,7 +71,7 @@ DomainServer::DomainServer(int argc, char* argv[]) : int socketHandle = LimitedNodeList::getInstance()->getDTLSSocket().socketDescriptor(); #if defined(IP_DONTFRAG) - int optValue = 1;yea + int optValue = 1; setsockopt(socketHandle, IPPROTO_IP, IP_DONTFRAG, (const void*) optValue, sizeof(optValue)); #elif defined(IP_MTU_DISCOVER) int optValue = 1; From a25ef5824707d9de5707ea11153d19cb36e15006 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 16 Apr 2014 11:25:35 -0700 Subject: [PATCH 439/595] move DTLS socket changes to LimitedNodeList --- domain-server/src/DomainServer.cpp | 12 ------------ libraries/networking/src/LimitedNodeList.cpp | 14 ++++++++++++++ 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 1268ae739e..969b83f64f 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -66,18 +66,6 @@ DomainServer::DomainServer(int argc, char* argv[]) : LimitedNodeList* nodeList = LimitedNodeList::getInstance(); -#if defined(IP_DONTFRAG) || defined(IP_MTU_DISCOVER) - qDebug() << "Making required DTLS changes to NodeList DTLS socket."; - - int socketHandle = LimitedNodeList::getInstance()->getDTLSSocket().socketDescriptor(); -#if defined(IP_DONTFRAG) - int optValue = 1; - setsockopt(socketHandle, IPPROTO_IP, IP_DONTFRAG, (const void*) optValue, sizeof(optValue)); -#elif defined(IP_MTU_DISCOVER) - int optValue = 1; - setsockopt(socketHandle, IPPROTO_IP, IP_MTU_DISCOVER, (const void*) optValue, sizeof(optValue)); -#endif -#endif // connect our socket to read datagrams received on the DTLS socket connect(&nodeList->getDTLSSocket(), &QUdpSocket::readyRead, this, &DomainServer::readAvailableDTLSDatagrams); } diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index 60fbe9b3a6..d85c01a9eb 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -105,6 +105,20 @@ QUdpSocket& LimitedNodeList::getDTLSSocket() { _dtlsSocket = new QUdpSocket(this); _dtlsSocket->bind(QHostAddress::AnyIPv4, 0, QAbstractSocket::DontShareAddress); + +#if defined(IP_DONTFRAG) || defined(IP_MTU_DISCOVER) + qDebug() << "Making required DTLS changes to LimitedNodeList DTLS socket."; + + int socketHandle = _dtlsSocket->socketDescriptor(); +#if defined(IP_DONTFRAG) + int optValue = 1; + setsockopt(socketHandle, IPPROTO_IP, IP_DONTFRAG, (const void*) optValue, sizeof(optValue)); +#elif defined(IP_MTU_DISCOVER) + int optValue = 1; + setsockopt(socketHandle, IPPROTO_IP, IP_MTU_DISCOVER, (const void*) optValue, sizeof(optValue)); +#endif +#endif + qDebug() << "NodeList DTLS socket is listening on" << _dtlsSocket->localPort(); } From 06a976041b507c8aa1c215e69176029aa89e9532 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 16 Apr 2014 11:27:30 -0700 Subject: [PATCH 440/595] take pointer of optValue and not actual optValue --- libraries/networking/src/LimitedNodeList.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index d85c01a9eb..223ab3c306 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -112,10 +112,10 @@ QUdpSocket& LimitedNodeList::getDTLSSocket() { int socketHandle = _dtlsSocket->socketDescriptor(); #if defined(IP_DONTFRAG) int optValue = 1; - setsockopt(socketHandle, IPPROTO_IP, IP_DONTFRAG, (const void*) optValue, sizeof(optValue)); + setsockopt(socketHandle, IPPROTO_IP, IP_DONTFRAG, reinterpret_cast(&optValue), sizeof(optValue)); #elif defined(IP_MTU_DISCOVER) int optValue = 1; - setsockopt(socketHandle, IPPROTO_IP, IP_MTU_DISCOVER, (const void*) optValue, sizeof(optValue)); + setsockopt(socketHandle, IPPROTO_IP, IP_MTU_DISCOVER, reinterpret_cast(&optValue), sizeof(optValue)); #endif #endif From afcb542bbec5e3a0e879b9bcf167c7625b8ae910 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 16 Apr 2014 11:28:34 -0700 Subject: [PATCH 441/595] fix a debug line in LimitedNodeList --- libraries/networking/src/LimitedNodeList.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index 223ab3c306..9b19e9d921 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -112,14 +112,14 @@ QUdpSocket& LimitedNodeList::getDTLSSocket() { int socketHandle = _dtlsSocket->socketDescriptor(); #if defined(IP_DONTFRAG) int optValue = 1; - setsockopt(socketHandle, IPPROTO_IP, IP_DONTFRAG, reinterpret_cast(&optValue), sizeof(optValue)); + setsockopt(socketHandle, IPPROTO_IP, IP_DONTFRAG, reinterpret_cast(&optValue, sizeof(optValue)); #elif defined(IP_MTU_DISCOVER) int optValue = 1; setsockopt(socketHandle, IPPROTO_IP, IP_MTU_DISCOVER, reinterpret_cast(&optValue), sizeof(optValue)); #endif #endif - qDebug() << "NodeList DTLS socket is listening on" << _dtlsSocket->localPort(); + qDebug() << "LimitedNodeList DTLS socket is listening on" << _dtlsSocket->localPort(); } return *_dtlsSocket; From d34e6ff86483125a0ac9e554ad7f5a323688546c Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 16 Apr 2014 12:01:41 -0700 Subject: [PATCH 442/595] Removed gettimeofday in AudioInjector --- libraries/audio/src/AudioInjector.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries/audio/src/AudioInjector.cpp b/libraries/audio/src/AudioInjector.cpp index 6370e51826..eed41ac849 100644 --- a/libraries/audio/src/AudioInjector.cpp +++ b/libraries/audio/src/AudioInjector.cpp @@ -71,8 +71,8 @@ void AudioInjector::injectAudio() { quint8 volume = MAX_INJECTOR_VOLUME * _options.getVolume(); packetStream << volume; - timeval startTime = {}; - gettimeofday(&startTime, NULL); + QElapsedTimer timer; + timer.start(); int nextFrame = 0; int currentSendPosition = 0; @@ -104,7 +104,7 @@ void AudioInjector::injectAudio() { if (currentSendPosition != bytesToCopy && currentSendPosition < soundByteArray.size()) { // not the first packet and not done // sleep for the appropriate time - int usecToSleep = usecTimestamp(&startTime) + (++nextFrame * BUFFER_SEND_INTERVAL_USECS) - usecTimestampNow(); + int usecToSleep = (++nextFrame * BUFFER_SEND_INTERVAL_USECS) - timer.nsecsElapsed() / 1000; if (usecToSleep > 0) { usleep(usecToSleep); From 505145f6934a702ebd5a9289d7f8198b2ae312ba Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 16 Apr 2014 12:02:02 -0700 Subject: [PATCH 443/595] add a missing bracket to IP_DONTFRAG --- libraries/networking/src/LimitedNodeList.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index 9b19e9d921..db8a689001 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -112,7 +112,7 @@ QUdpSocket& LimitedNodeList::getDTLSSocket() { int socketHandle = _dtlsSocket->socketDescriptor(); #if defined(IP_DONTFRAG) int optValue = 1; - setsockopt(socketHandle, IPPROTO_IP, IP_DONTFRAG, reinterpret_cast(&optValue, sizeof(optValue)); + setsockopt(socketHandle, IPPROTO_IP, IP_DONTFRAG, reinterpret_cast(&optValue), sizeof(optValue)); #elif defined(IP_MTU_DISCOVER) int optValue = 1; setsockopt(socketHandle, IPPROTO_IP, IP_MTU_DISCOVER, reinterpret_cast(&optValue), sizeof(optValue)); From 8cfc8faa019bf5a583fd8bcb93ea47627800f060 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 16 Apr 2014 12:08:17 -0700 Subject: [PATCH 444/595] Removed gettimeofday in Audio --- interface/src/Audio.cpp | 13 +++++-------- interface/src/Audio.h | 3 ++- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 5dcd54050c..c7f7c2c354 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -616,12 +616,11 @@ void Audio::handleAudioInput() { void Audio::addReceivedAudioToBuffer(const QByteArray& audioByteArray) { const int NUM_INITIAL_PACKETS_DISCARD = 3; const int STANDARD_DEVIATION_SAMPLE_COUNT = 500; - - timeval currentReceiveTime; - gettimeofday(¤tReceiveTime, NULL); + + _timeSinceLastRecieved.start(); _totalPacketsReceived++; - - double timeDiff = diffclock(&_lastReceiveTime, ¤tReceiveTime); + + double timeDiff = (double)_timeSinceLastRecieved.nsecsElapsed() / 1000000.0; // ns to ms // Discard first few received packets for computing jitter (often they pile up on start) if (_totalPacketsReceived > NUM_INITIAL_PACKETS_DISCARD) { @@ -646,8 +645,6 @@ void Audio::addReceivedAudioToBuffer(const QByteArray& audioByteArray) { } Application::getInstance()->getBandwidthMeter()->inputStream(BandwidthMeter::AUDIO).updateValue(audioByteArray.size()); - - _lastReceiveTime = currentReceiveTime; } bool Audio::mousePressEvent(int x, int y) { @@ -995,7 +992,7 @@ bool Audio::switchOutputToAudioDevice(const QAudioDeviceInfo& outputDeviceInfo) // setup a procedural audio output device _proceduralAudioOutput = new QAudioOutput(outputDeviceInfo, _outputFormat, this); - gettimeofday(&_lastReceiveTime, NULL); + _timeSinceLastRecieved.start(); supportedFormat = true; } } diff --git a/interface/src/Audio.h b/interface/src/Audio.h index b78bcc661e..3fa4175573 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -23,6 +23,7 @@ #include #include +#include #include #include #include @@ -123,7 +124,7 @@ private: QString _outputAudioDeviceName; StDev _stdev; - timeval _lastReceiveTime; + QElapsedTimer _timeSinceLastRecieved; float _averagedLatency; float _measuredJitter; int16_t _jitterBufferSamples; From dd8a0e355055476af97f6f668d451b4182e4e5a4 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 16 Apr 2014 12:16:49 -0700 Subject: [PATCH 445/595] Removed gettimeofday in AudioMixer --- assignment-client/src/audio/AudioMixer.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/assignment-client/src/audio/AudioMixer.cpp b/assignment-client/src/audio/AudioMixer.cpp index 407a64d7a8..65d09f1b00 100644 --- a/assignment-client/src/audio/AudioMixer.cpp +++ b/assignment-client/src/audio/AudioMixer.cpp @@ -389,9 +389,8 @@ void AudioMixer::run() { nodeList->linkedDataCreateCallback = attachNewBufferToNode; int nextFrame = 0; - timeval startTime; - - gettimeofday(&startTime, NULL); + QElapsedTimer timer; + timer.start(); char* clientMixBuffer = new char[NETWORK_BUFFER_LENGTH_BYTES_STEREO + numBytesForPacketHeaderGivenPacketType(PacketTypeMixedAudio)]; @@ -490,7 +489,7 @@ void AudioMixer::run() { break; } - usecToSleep = usecTimestamp(&startTime) + (++nextFrame * BUFFER_SEND_INTERVAL_USECS) - usecTimestampNow(); + usecToSleep = (++nextFrame * BUFFER_SEND_INTERVAL_USECS) - timer.nsecsElapsed() / 1000; // ns to us if (usecToSleep > 0) { usleep(usecToSleep); From 6b23da40d66e78bac9ba036a72460dd31237212b Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 16 Apr 2014 12:18:40 -0700 Subject: [PATCH 446/595] use correct name for signal connect --- interface/src/Application.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 1fabca3711..0d0ae262a7 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1663,7 +1663,7 @@ void Application::init() { connect(&_particleCollisionSystem, SIGNAL(particleCollisionWithVoxel(const ParticleID&, const VoxelDetail&, const CollisionInfo&)), ScriptEngine::getParticlesScriptingInterface(), - SIGNAL(particleCollisionWithVoxels(const ParticleID&, const VoxelDetail&, const CollisionInfo&))); + SIGNAL(particleCollisionWithVoxel(const ParticleID&, const VoxelDetail&, const CollisionInfo&))); connect(&_particleCollisionSystem, SIGNAL(particleCollisionWithParticle(const ParticleID&, const ParticleID&, const CollisionInfo&)), From 9ab1b76484bb38c9594df4b8af08b90f48bb9f4d Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 16 Apr 2014 13:28:54 -0700 Subject: [PATCH 447/595] use new Qt connect syntax for compile-time checks --- interface/src/Application.cpp | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 0d0ae262a7..f0e2103743 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1659,16 +1659,12 @@ void Application::init() { _particleCollisionSystem.init(&_particleEditSender, _particles.getTree(), _voxels.getTree(), &_audio, &_avatarManager); - // connect the _particleCollisionSystem to our script engine's ParticleScriptingInterface - connect(&_particleCollisionSystem, - SIGNAL(particleCollisionWithVoxel(const ParticleID&, const VoxelDetail&, const CollisionInfo&)), - ScriptEngine::getParticlesScriptingInterface(), - SIGNAL(particleCollisionWithVoxel(const ParticleID&, const VoxelDetail&, const CollisionInfo&))); + // connect the _particleCollisionSystem to our script engine's ParticlesScriptingInterface + connect(&_particleCollisionSystem, &ParticleCollisionSystem::particleCollisionWithVoxel, + ScriptEngine::getParticlesScriptingInterface(), &ParticlesScriptingInterface::particleCollisionWithVoxel); - connect(&_particleCollisionSystem, - SIGNAL(particleCollisionWithParticle(const ParticleID&, const ParticleID&, const CollisionInfo&)), - ScriptEngine::getParticlesScriptingInterface(), - SIGNAL(particleCollisionWithParticle(const ParticleID&, const ParticleID&, const CollisionInfo&))); + connect(&_particleCollisionSystem, &ParticleCollisionSystem::particleCollisionWithParticle, + ScriptEngine::getParticlesScriptingInterface(), &ParticlesScriptingInterface::particleCollisionWithParticle); _audio.init(_glWidget); From 49e7842d25ff4e025f8f1d0fa65b4a1608c996f9 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 16 Apr 2014 13:37:41 -0700 Subject: [PATCH 448/595] push packet version to force an update --- libraries/networking/src/PacketHeaders.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/networking/src/PacketHeaders.cpp b/libraries/networking/src/PacketHeaders.cpp index fdbdca3db7..29238220e1 100644 --- a/libraries/networking/src/PacketHeaders.cpp +++ b/libraries/networking/src/PacketHeaders.cpp @@ -55,7 +55,7 @@ PacketVersion versionForPacketType(PacketType type) { return 1; case PacketTypeDomainList: case PacketTypeDomainListRequest: - return 2; + return 3; case PacketTypeCreateAssignment: case PacketTypeRequestAssignment: return 2; From b00a67cb5705e00cd60c45ad0a0542a7c8703b79 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 16 Apr 2014 13:55:39 -0700 Subject: [PATCH 449/595] added support for local audio spatialization independent of inbound audio --- interface/src/Audio.cpp | 2 + interface/src/AudioReflector.cpp | 186 ++++++++++++++++++++----------- interface/src/AudioReflector.h | 22 +++- 3 files changed, 139 insertions(+), 71 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index d6deb66e2a..06cb1fe461 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -665,6 +665,8 @@ void Audio::addReceivedAudioToBuffer(const QByteArray& audioByteArray) { _lastReceiveTime = currentReceiveTime; } +// NOTE: numSamples is the total number of single channel samples, since callers will always call this with stereo +// data we know that we will have 2x samples for each stereo time sample at the format's sample rate void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, const QByteArray& spatialAudio, unsigned int numSamples) { // Calculate the number of remaining samples available. The source spatial audio buffer will get // clipped if there are insufficient samples available in the accumulation buffer. diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 0640ed038e..847f1dc0bf 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -203,7 +203,7 @@ void AudioReflector::injectAudiblePoint(const AudiblePoint& audiblePoint, _maxAttenuation = std::max(_maxAttenuation,leftEarAttenuation); _minAttenuation = std::min(_minAttenuation,rightEarAttenuation); _minAttenuation = std::min(_minAttenuation,leftEarAttenuation); - + // run through the samples, and attenuate them for (int sample = 0; sample < totalNumberOfStereoSamples; sample++) { int16_t leftSample = originalSamplesData[sample * NUMBER_OF_CHANNELS]; @@ -235,25 +235,25 @@ void AudioReflector::processLocalAudio(unsigned int sampleTime, const QByteArray if (format.channelCount() == NUM_CHANNELS_INPUT && format.sampleRate() == EXPECTED_SAMPLE_RATE) { QAudioFormat outputFormat = format; outputFormat.setChannelCount(NUM_CHANNELS_OUTPUT); - QByteArray stereoInputData; - stereoInputData.resize(samples.size() * NUM_CHANNELS_OUTPUT); - int numberOfSamples = samples.size() / sizeof(int16_t); + QByteArray stereoInputData(samples.size() * NUM_CHANNELS_OUTPUT, 0); + int numberOfSamples = (samples.size() / sizeof(int16_t)); int16_t* monoSamples = (int16_t*)samples.data(); int16_t* stereoSamples = (int16_t*)stereoInputData.data(); + for (int i = 0; i < numberOfSamples; i++) { stereoSamples[i* NUM_CHANNELS_OUTPUT] = monoSamples[i] * _localAudioAttenuationFactor; stereoSamples[(i * NUM_CHANNELS_OUTPUT) + 1] = monoSamples[i] * _localAudioAttenuationFactor; } - echoAudio(sampleTime, stereoInputData, outputFormat); + echoAudio(LOCAL_AUDIO, sampleTime, stereoInputData, outputFormat); } } } void AudioReflector::processInboundAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { - echoAudio(sampleTime, samples, format); + echoAudio(INBOUND_AUDIO, sampleTime, samples, format); } -void AudioReflector::echoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { +void AudioReflector::echoAudio(AudioSource source, unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { _maxDelay = 0; _maxAttenuation = 0.0f; _minDelay = std::numeric_limits::max(); @@ -265,7 +265,10 @@ void AudioReflector::echoAudio(unsigned int sampleTime, const QByteArray& sample QMutexLocker locker(&_mutex); - foreach(const AudiblePoint& audiblePoint, _audiblePoints) { + // depending on if we're processing local or external audio, pick the correct points vector + QVector& audiblePoints = source == INBOUND_AUDIO ? _inboundAudiblePoints : _localAudiblePoints; + + foreach(const AudiblePoint& audiblePoint, audiblePoints) { injectAudiblePoint(audiblePoint, samples, sampleTime, format.sampleRate()); } @@ -294,9 +297,10 @@ void AudioReflector::drawVector(const glm::vec3& start, const glm::vec3& end, co -AudioPath::AudioPath(const glm::vec3& origin, const glm::vec3& direction, +AudioPath::AudioPath(AudioSource source, const glm::vec3& origin, const glm::vec3& direction, float attenuation, float delay, float distance,bool isDiffusion, int bounceCount) : + source(source), isDiffusion(isDiffusion), startPoint(origin), startDirection(direction), @@ -315,12 +319,15 @@ AudioPath::AudioPath(const glm::vec3& origin, const glm::vec3& direction, { } -void AudioReflector::addSoundSource(const glm::vec3& origin, const glm::vec3& initialDirection, +void AudioReflector::addAudioPath(AudioSource source, const glm::vec3& origin, const glm::vec3& initialDirection, float initialAttenuation, float initialDelay, float initialDistance, bool isDiffusion) { - AudioPath* path = new AudioPath(origin, initialDirection, initialAttenuation, initialDelay, + AudioPath* path = new AudioPath(source, origin, initialDirection, initialAttenuation, initialDelay, initialDistance, isDiffusion, 0); - _audioPaths.push_back(path); + + QVector& audioPaths = source == INBOUND_AUDIO ? _inboundAudioPaths : _localAudioPaths; + + audioPaths.push_back(path); } void AudioReflector::calculateAllReflections() { @@ -355,12 +362,15 @@ void AudioReflector::calculateAllReflections() { void AudioReflector::drawRays() { const glm::vec3 RED(1,0,0); const glm::vec3 GREEN(0,1,0); + const glm::vec3 BLUE(0,0,1); + const glm::vec3 CYAN(0,1,1); int diffusionNumber = 0; QMutexLocker locker(&_mutex); - foreach(AudioPath* const& path, _audioPaths) { - + + // draw the paths for inbound audio + foreach(AudioPath* const& path, _inboundAudioPaths) { // if this is an original reflection, draw it in RED if (path->isDiffusion) { diffusionNumber++; @@ -369,6 +379,19 @@ void AudioReflector::drawRays() { drawPath(path, RED); } } + + if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingProcessLocalAudio)) { + // draw the paths for local audio + foreach(AudioPath* const& path, _localAudioPaths) { + // if this is an original reflection, draw it in RED + if (path->isDiffusion) { + diffusionNumber++; + drawPath(path, CYAN); + } else { + drawPath(path, BLUE); + } + } + } } void AudioReflector::drawPath(AudioPath* path, const glm::vec3& originalColor) { @@ -383,6 +406,21 @@ void AudioReflector::drawPath(AudioPath* path, const glm::vec3& originalColor) { } } +void AudioReflector::clearPaths() { + // clear our inbound audio paths + foreach(AudioPath* const& path, _inboundAudioPaths) { + delete path; + } + _inboundAudioPaths.clear(); + _inboundAudiblePoints.clear(); // clear our inbound audible points + + // clear our local audio paths + foreach(AudioPath* const& path, _localAudioPaths) { + delete path; + } + _localAudioPaths.clear(); + _localAudiblePoints.clear(); // clear our local audible points +} // Here's how this works: we have an array of AudioPaths, we loop on all of our currently calculating audio // paths, and calculate one ray per path. If that ray doesn't reflect, or reaches a max distance/attenuation, then it @@ -392,12 +430,7 @@ void AudioReflector::drawPath(AudioPath* path, const glm::vec3& originalColor) { // fanout number of new paths, those new paths will have an origin of the reflection point, and an initial attenuation // of their diffusion ratio. Those new paths will be added to the active audio paths, and be analyzed for the next loop. void AudioReflector::analyzePaths() { - // clear our _audioPaths - foreach(AudioPath* const& path, _audioPaths) { - delete path; - } - _audioPaths.clear(); - _audiblePoints.clear(); // clear our audible points + clearPaths(); // add our initial paths glm::vec3 right = glm::normalize(_orientation * IDENTITY_RIGHT); @@ -422,36 +455,49 @@ void AudioReflector::analyzePaths() { // NOTE: we're still calculating our initial paths based on the listeners position. But the analysis code has been // updated to support individual sound sources (which is how we support diffusion), we can use this new paradigm to // add support for individual sound sources, and more directional sound sources - addSoundSource(_origin, right, initialAttenuation, preDelay); - addSoundSource(_origin, front, initialAttenuation, preDelay); - addSoundSource(_origin, up, initialAttenuation, preDelay); - addSoundSource(_origin, down, initialAttenuation, preDelay); - addSoundSource(_origin, back, initialAttenuation, preDelay); - addSoundSource(_origin, left, initialAttenuation, preDelay); - addSoundSource(_origin, frontRightUp, initialAttenuation, preDelay); - addSoundSource(_origin, frontLeftUp, initialAttenuation, preDelay); - addSoundSource(_origin, backRightUp, initialAttenuation, preDelay); - addSoundSource(_origin, backLeftUp, initialAttenuation, preDelay); - addSoundSource(_origin, frontRightDown, initialAttenuation, preDelay); - addSoundSource(_origin, frontLeftDown, initialAttenuation, preDelay); - addSoundSource(_origin, backRightDown, initialAttenuation, preDelay); - addSoundSource(_origin, backLeftDown, initialAttenuation, preDelay); + + addAudioPath(INBOUND_AUDIO, _origin, front, initialAttenuation, preDelay); + addAudioPath(INBOUND_AUDIO, _origin, right, initialAttenuation, preDelay); + addAudioPath(INBOUND_AUDIO, _origin, up, initialAttenuation, preDelay); + addAudioPath(INBOUND_AUDIO, _origin, down, initialAttenuation, preDelay); + addAudioPath(INBOUND_AUDIO, _origin, back, initialAttenuation, preDelay); + addAudioPath(INBOUND_AUDIO, _origin, left, initialAttenuation, preDelay); + addAudioPath(INBOUND_AUDIO, _origin, frontRightUp, initialAttenuation, preDelay); + addAudioPath(INBOUND_AUDIO, _origin, frontLeftUp, initialAttenuation, preDelay); + addAudioPath(INBOUND_AUDIO, _origin, backRightUp, initialAttenuation, preDelay); + addAudioPath(INBOUND_AUDIO, _origin, backLeftUp, initialAttenuation, preDelay); + addAudioPath(INBOUND_AUDIO, _origin, frontRightDown, initialAttenuation, preDelay); + addAudioPath(INBOUND_AUDIO, _origin, frontLeftDown, initialAttenuation, preDelay); + addAudioPath(INBOUND_AUDIO, _origin, backRightDown, initialAttenuation, preDelay); + addAudioPath(INBOUND_AUDIO, _origin, backLeftDown, initialAttenuation, preDelay); + + // the original paths for the local audio are directional to the front of the origin + addAudioPath(LOCAL_AUDIO, _origin, front, initialAttenuation, preDelay); + addAudioPath(LOCAL_AUDIO, _origin, frontRightUp, initialAttenuation, preDelay); + addAudioPath(LOCAL_AUDIO, _origin, frontLeftUp, initialAttenuation, preDelay); + addAudioPath(LOCAL_AUDIO, _origin, frontRightDown, initialAttenuation, preDelay); + addAudioPath(LOCAL_AUDIO, _origin, frontLeftDown, initialAttenuation, preDelay); // loop through all our audio paths and keep analyzing them until they complete int steps = 0; - int acitvePaths = _audioPaths.size(); // when we start, all paths are active + int acitvePaths = _inboundAudioPaths.size() + _localAudioPaths.size(); // when we start, all paths are active while(acitvePaths > 0) { acitvePaths = analyzePathsSingleStep(); steps++; } - _reflections = _audiblePoints.size(); + _reflections = _inboundAudiblePoints.size() + _localAudiblePoints.size(); _diffusionPathCount = countDiffusionPaths(); } int AudioReflector::countDiffusionPaths() { int diffusionCount = 0; - foreach(AudioPath* const& path, _audioPaths) { + foreach(AudioPath* const& path, _inboundAudioPaths) { + if (path->isDiffusion) { + diffusionCount++; + } + } + foreach(AudioPath* const& path, _localAudioPaths) { if (path->isDiffusion) { diffusionCount++; } @@ -462,36 +508,44 @@ int AudioReflector::countDiffusionPaths() { int AudioReflector::analyzePathsSingleStep() { // iterate all the active sound paths, calculate one step per active path int activePaths = 0; - foreach(AudioPath* const& path, _audioPaths) { + + QVector* pathsLists[] = { &_inboundAudioPaths, &_localAudioPaths }; + + for(int i = 0; i < sizeof(pathsLists) / sizeof(pathsLists[0]); i ++) { + + QVector& pathList = *pathsLists[i]; + + foreach(AudioPath* const& path, pathList) { - glm::vec3 start = path->lastPoint; - glm::vec3 direction = path->lastDirection; - OctreeElement* elementHit; // output from findRayIntersection - float distance; // output from findRayIntersection - BoxFace face; // output from findRayIntersection + glm::vec3 start = path->lastPoint; + glm::vec3 direction = path->lastDirection; + OctreeElement* elementHit; // output from findRayIntersection + float distance; // output from findRayIntersection + BoxFace face; // output from findRayIntersection - if (!path->finalized) { - activePaths++; + if (!path->finalized) { + activePaths++; - if (path->bounceCount > ABSOLUTE_MAXIMUM_BOUNCE_COUNT) { - path->finalized = true; - } else if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { - // TODO: we need to decide how we want to handle locking on the ray intersection, if we force lock, - // we get an accurate picture, but it could prevent rendering of the voxels. If we trylock (default), - // we might not get ray intersections where they may exist, but we can't really detect that case... - // add last parameter of Octree::Lock to force locking - handlePathPoint(path, distance, elementHit, face); + if (path->bounceCount > ABSOLUTE_MAXIMUM_BOUNCE_COUNT) { + path->finalized = true; + } else if (_voxels->findRayIntersection(start, direction, elementHit, distance, face)) { + // TODO: we need to decide how we want to handle locking on the ray intersection, if we force lock, + // we get an accurate picture, but it could prevent rendering of the voxels. If we trylock (default), + // we might not get ray intersections where they may exist, but we can't really detect that case... + // add last parameter of Octree::Lock to force locking + handlePathPoint(path, distance, elementHit, face); - } else { - // If we didn't intersect, but this was a diffusion ray, then we will go ahead and cast a short ray out - // from our last known point, in the last known direction, and leave that sound source hanging there - if (path->isDiffusion) { - const float MINIMUM_RANDOM_DISTANCE = 0.25f; - const float MAXIMUM_RANDOM_DISTANCE = 0.5f; - float distance = randFloatInRange(MINIMUM_RANDOM_DISTANCE, MAXIMUM_RANDOM_DISTANCE); - handlePathPoint(path, distance, NULL, UNKNOWN_FACE); } else { - path->finalized = true; // if it doesn't intersect, then it is finished + // If we didn't intersect, but this was a diffusion ray, then we will go ahead and cast a short ray out + // from our last known point, in the last known direction, and leave that sound source hanging there + if (path->isDiffusion) { + const float MINIMUM_RANDOM_DISTANCE = 0.25f; + const float MAXIMUM_RANDOM_DISTANCE = 0.5f; + float distance = randFloatInRange(MINIMUM_RANDOM_DISTANCE, MAXIMUM_RANDOM_DISTANCE); + handlePathPoint(path, distance, NULL, UNKNOWN_FACE); + } else { + path->finalized = true; // if it doesn't intersect, then it is finished + } } } } @@ -571,8 +625,8 @@ void AudioReflector::handlePathPoint(AudioPath* path, float distance, OctreeElem diffusion = glm::normalize(diffusion); - // add sound sources for these diffusions - addSoundSource(end, diffusion, partialDiffusionAttenuation, currentDelay, pathDistance, true); + // add new audio path for these diffusions, the new path's source is the same as the original source + addAudioPath(path->source, end, diffusion, partialDiffusionAttenuation, currentDelay, pathDistance, true); } } else { const bool wantDebugging = false; @@ -603,7 +657,9 @@ void AudioReflector::handlePathPoint(AudioPath* path, float distance, OctreeElem // audio so that it can be adjusted to ear position AudiblePoint point = {end, currentDelay, (reflectiveAttenuation + totalDiffusionAttenuation), pathDistance}; - _audiblePoints.push_back(point); + QVector& audiblePoints = path->source == INBOUND_AUDIO ? _inboundAudiblePoints : _localAudiblePoints; + + audiblePoints.push_back(point); // add this location to the path points, so we can visualize it path->reflections.push_back(end); diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 79fcdda68d..900f567920 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -16,11 +16,18 @@ #include "Audio.h" #include "avatar/MyAvatar.h" +enum AudioSource { + LOCAL_AUDIO, + INBOUND_AUDIO +}; + class AudioPath { public: - AudioPath(const glm::vec3& origin = glm::vec3(0), const glm::vec3& direction = glm::vec3(0), float attenuation = 1.0f, + AudioPath(AudioSource source = INBOUND_AUDIO, const glm::vec3& origin = glm::vec3(0), + const glm::vec3& direction = glm::vec3(0), float attenuation = 1.0f, float delay = 0.0f, float distance = 0.0f, bool isDiffusion = false, int bounceCount = 0); + AudioSource source; bool isDiffusion; glm::vec3 startPoint; glm::vec3 startDirection; @@ -53,7 +60,6 @@ public: float diffusionRatio; }; - class AudioReflector : public QObject { Q_OBJECT public: @@ -145,17 +151,21 @@ private: glm::vec3 _origin; glm::quat _orientation; - QVector _audioPaths; /// the various audio paths we're processing - QVector _audiblePoints; /// the audible points that have been calculated from the paths + QVector _inboundAudioPaths; /// audio paths we're processing for inbound audio + QVector _inboundAudiblePoints; /// the audible points that have been calculated from the inbound audio paths + + QVector _localAudioPaths; /// audio paths we're processing for local audio + QVector _localAudiblePoints; /// the audible points that have been calculated from the local audio paths // adds a sound source to begin an audio path trace, these can be the initial sound sources with their directional properties, // as well as diffusion sound sources - void addSoundSource(const glm::vec3& origin, const glm::vec3& initialDirection, float initialAttenuation, + void addAudioPath(AudioSource source, const glm::vec3& origin, const glm::vec3& initialDirection, float initialAttenuation, float initialDelay, float initialDistance = 0.0f, bool isDiffusion = false); // helper that handles audioPath analysis int analyzePathsSingleStep(); void handlePathPoint(AudioPath* path, float distance, OctreeElement* elementHit, BoxFace face); + void clearPaths(); void analyzePaths(); void drawRays(); void drawPath(AudioPath* path, const glm::vec3& originalColor); @@ -164,7 +174,7 @@ private: glm::vec3 getFaceNormal(BoxFace face); void injectAudiblePoint(const AudiblePoint& audiblePoint, const QByteArray& samples, unsigned int sampleTime, int sampleRate); - void echoAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); + void echoAudio(AudioSource source, unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); // return the surface characteristics of the element we hit SurfaceCharacteristics getSurfaceCharacteristics(OctreeElement* elementHit = NULL); From 0b644b5738b8ed3324f61fbb7957529865b79b63 Mon Sep 17 00:00:00 2001 From: Thijs Wenker Date: Wed, 16 Apr 2014 22:58:44 +0200 Subject: [PATCH 450/595] ctrl+shift+s to open the script editor --- interface/src/Menu.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index cfeba0705f..303e155da6 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -192,7 +192,7 @@ Menu::Menu() : QMenu* toolsMenu = addMenu("Tools"); addActionToQMenuAndActionHash(toolsMenu, MenuOption::MetavoxelEditor, 0, this, SLOT(showMetavoxelEditor())); - addActionToQMenuAndActionHash(toolsMenu, MenuOption::ScriptEditor, 0, this, SLOT(showScriptEditor())); + addActionToQMenuAndActionHash(toolsMenu, MenuOption::ScriptEditor, Qt::CTRL | Qt::SHIFT | Qt::Key_S, this, SLOT(showScriptEditor())); #ifdef HAVE_QXMPP _chatAction = addActionToQMenuAndActionHash(toolsMenu, From fe1123ea97c8d47909856432c04e52e571775e6d Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 16 Apr 2014 14:22:47 -0700 Subject: [PATCH 451/595] gun.js correctly deletes voxel again on collision --- examples/gun.js | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/examples/gun.js b/examples/gun.js index 8cf6c9f654..4bfdb140b8 100644 --- a/examples/gun.js +++ b/examples/gun.js @@ -152,11 +152,10 @@ function particleCollisionWithVoxel(particle, voxel, collision) { var position = particleProperties.position; Particles.deleteParticle(particle); // Make a hole in this voxel - Vec3.print("penetration", collision.penetration); - Vec3.print("contactPoint", collision.contactPoint); - Voxels.eraseVoxel(contactPoint.x, contactPoint.y, contactPoint.z, HOLE_SIZE); - Voxels.eraseVoxel(position.x, position.y, position.z, HOLE_SIZE); - audioOptions.position = Vec3.sum(Camera.getPosition(), Quat.getFront(Camera.getOrientation())); + //Vec3.print("voxel penetration", collision.penetration); + //Vec3.print("voxel contactPoint", collision.contactPoint); + Voxels.eraseVoxel(collision.contactPoint.x, collision.contactPoint.y, collision.contactPoint.z, HOLE_SIZE); + audioOptions.position = collision.contactPoint; Audio.playSound(impactSound, audioOptions); } @@ -171,9 +170,9 @@ function particleCollisionWithParticle(particle1, particle2, collision) { // Record shot time var endTime = new Date(); var msecs = endTime.valueOf() - shotTime.valueOf(); - print("hit, msecs = " + msecs); - Vec3.print("penetration = ", collision.penetration); - Vec3.print("contactPoint = ", collision.contactPoint); + //print("hit, msecs = " + msecs); + //Vec3.print("penetration = ", collision.penetration); + //Vec3.print("contactPoint = ", collision.contactPoint); Particles.deleteParticle(particle1); Particles.deleteParticle(particle2); // play the sound near the camera so the shooter can hear it From 83dc8717aa5d210ad47ec30280edc2c8a3174830 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 16 Apr 2014 14:46:49 -0700 Subject: [PATCH 452/595] bumpSettings on load/stop script --- interface/src/Application.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index f0e2103743..b904dfc1c1 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1674,7 +1674,7 @@ void Application::init() { connect(_rearMirrorTools, SIGNAL(restoreView()), SLOT(restoreMirrorView())); connect(_rearMirrorTools, SIGNAL(shrinkView()), SLOT(shrinkMirrorView())); connect(_rearMirrorTools, SIGNAL(resetView()), SLOT(resetSensors())); - connect(_myAvatar, SIGNAL(transformChanged()), this, SLOT(bumpSettings())); + connect(_myAvatar, &MyAvatar::transformChanged, this, &Application::bumpSettings); } void Application::closeMirrorView() { @@ -3280,6 +3280,7 @@ void Application::stopAllScripts() { } _scriptEnginesHash.clear(); _runningScriptsWidget->setRunningScripts(getRunningScripts()); + bumpSettings(); } void Application::stopScript(const QString &scriptName) @@ -3288,6 +3289,7 @@ void Application::stopScript(const QString &scriptName) qDebug() << "stopping script..." << scriptName; _scriptEnginesHash.remove(scriptName); _runningScriptsWidget->setRunningScripts(getRunningScripts()); + bumpSettings(); } void Application::reloadAllScripts() { @@ -3403,6 +3405,7 @@ void Application::loadScript(const QString& scriptName) { // restore the main window's active state _window->activateWindow(); + bumpSettings(); } void Application::loadDialog() { From 8120700787b354ed4bfba0993c6d4ca988a8d9e6 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Thu, 17 Apr 2014 00:03:11 +0200 Subject: [PATCH 453/595] Added urlGoTo --- interface/src/Application.cpp | 39 +++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 1fabca3711..a7a00bf7c7 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -356,6 +356,8 @@ Application::Application(int& argc, char** argv, timeval &startup_time) : QMutexLocker locker(&_settingsMutex); _previousScriptLocation = _settings->value("LastScriptLocation", QVariant("")).toString(); } + //When -url in command line, teleport to location + urlGoTo(argc, constArgv); } Application::~Application() { @@ -3548,3 +3550,40 @@ void Application::takeSnapshot() { Snapshot::saveSnapshot(_glWidget, _myAvatar); } + +void Application::urlGoTo(int argc, const char * constArgv[]) { + //Gets the url (hifi://domain/destination/orientation) + QString customUrl = getCmdOption(argc, constArgv, "-url"); + + if (customUrl.startsWith("hifi://")) { + QStringList urlParts = customUrl.remove(0, CUSTOM_URL_SCHEME.length() + 2).split('/', QString::SkipEmptyParts); + + if (urlParts.count() > 1) { + // if url has 2 or more parts, the first one is domain name + QString domain = urlParts[0]; + + // second part is either a destination coordinate or + // a place name + QString destination = urlParts[1]; + + // any third part is an avatar orientation. + QString orientation = urlParts.count() > 2 ? urlParts[2] : QString(); + + Menu::goToDomain(domain); + + // goto either @user, #place, or x-xx,y-yy,z-zz + // style co-ordinate. + Menu::goTo(destination); + + if (!orientation.isEmpty()) { + // location orientation + Menu::goToOrientation(orientation); + } + } else if (urlParts.count() == 1) { + // location coordinates or place name + QString destination = urlParts[0]; + Menu::goTo(destination); + } + + } +} From d55fb60862a1fdc237a20db3d2a942fba50e6be4 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Thu, 17 Apr 2014 00:03:33 +0200 Subject: [PATCH 454/595] Added urlGoTo --- interface/src/Application.h | 1 + 1 file changed, 1 insertion(+) diff --git a/interface/src/Application.h b/interface/src/Application.h index 6a14788caa..de5f1fe113 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -509,6 +509,7 @@ private: void displayUpdateDialog(); bool shouldSkipVersion(QString latestVersion); void takeSnapshot(); + void urlGoTo(int argc, const char * constArgv[]); TouchEvent _lastTouchEvent; From b3ce36f1309140f9cf4e84c113bff670d0455b39 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Thu, 17 Apr 2014 00:04:27 +0200 Subject: [PATCH 455/595] Changed goTo's to statics --- interface/src/Menu.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 40ed8efdc7..c2aac5672b 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -135,10 +135,10 @@ public: void removeAction(QMenu* menu, const QString& actionName); - bool goToDestination(QString destination); - void goToOrientation(QString orientation); - void goToDomain(const QString newDomain); - void goTo(QString destination); + bool static goToDestination(QString destination); + void static goToOrientation(QString orientation); + void static goToDomain(const QString newDomain); + void static goTo(QString destination); public slots: From fca4e2abba27f4676fe7bdacbb6c1531763444c8 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Thu, 17 Apr 2014 00:09:58 +0200 Subject: [PATCH 456/595] Update Application.h --- interface/src/Application.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/Application.h b/interface/src/Application.h index de5f1fe113..a09483a1ba 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -128,6 +128,7 @@ public: void initializeGL(); void paintGL(); void resizeGL(int width, int height); + void urlGoTo(int argc, const char * constArgv[]); void keyPressEvent(QKeyEvent* event); void keyReleaseEvent(QKeyEvent* event); @@ -509,7 +510,6 @@ private: void displayUpdateDialog(); bool shouldSkipVersion(QString latestVersion); void takeSnapshot(); - void urlGoTo(int argc, const char * constArgv[]); TouchEvent _lastTouchEvent; From 2e0c5fc81be6ef6326d227c42fc7cfa1f64c1de5 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 16 Apr 2014 15:13:20 -0700 Subject: [PATCH 457/595] implement support for comb filter suppression window --- examples/audioReflectorTools.js | 68 ++++++++++++++++++ interface/src/AudioReflector.cpp | 120 ++++++++++++++++++++----------- interface/src/AudioReflector.h | 15 +++- interface/src/ui/Stats.cpp | 10 ++- 4 files changed, 167 insertions(+), 46 deletions(-) diff --git a/examples/audioReflectorTools.js b/examples/audioReflectorTools.js index 532cae84bc..3cc6a1a21e 100644 --- a/examples/audioReflectorTools.js +++ b/examples/audioReflectorTools.js @@ -18,6 +18,7 @@ var localFactorScale = 1.0; var reflectiveScale = 100.0; var diffusionScale = 100.0; var absorptionScale = 100.0; +var combFilterScale = 50.0; // these three properties are bound together, if you change one, the others will also change var reflectiveRatio = AudioReflector.getReflectiveRatio(); @@ -263,6 +264,46 @@ var localFactorThumb = Overlays.addOverlay("image", { alpha: 1 }); +var combFilterY = topY; +topY += sliderHeight; + +var combFilterLabel = Overlays.addOverlay("text", { + x: 40, + y: combFilterY, + width: 60, + height: sliderHeight, + color: { red: 0, green: 0, blue: 0}, + textColor: { red: 255, green: 255, blue: 255}, + topMargin: 6, + leftMargin: 5, + text: "Comb Filter\nWindow:" + }); + + +var combFilterSlider = Overlays.addOverlay("image", { + // alternate form of expressing bounds + bounds: { x: 100, y: combFilterY, width: 150, height: sliderHeight}, + subImage: { x: 46, y: 0, width: 200, height: 71 }, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/slider.png", + color: { red: 255, green: 255, blue: 255}, + alpha: 1 + }); + + +var combFilterMinThumbX = 110; +var combFilterMaxThumbX = combFilterMinThumbX + 110; +var combFilterThumbX = combFilterMinThumbX + ((combFilterMaxThumbX - combFilterMinThumbX) * (AudioReflector.getCombFilterWindow() / combFilterScale)); +var combFilterThumb = Overlays.addOverlay("image", { + x: combFilterThumbX, + y: combFilterY+9, + width: 18, + height: 17, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/thumb.png", + color: { red: 128, green: 128, blue: 0}, + alpha: 1 + }); + + var reflectiveY = topY; topY += sliderHeight; @@ -387,6 +428,10 @@ function scriptEnding() { Overlays.deleteOverlay(factorThumb); Overlays.deleteOverlay(factorSlider); + Overlays.deleteOverlay(combFilterLabel); + Overlays.deleteOverlay(combFilterThumb); + Overlays.deleteOverlay(combFilterSlider); + Overlays.deleteOverlay(localFactorLabel); Overlays.deleteOverlay(localFactorThumb); Overlays.deleteOverlay(localFactorSlider); @@ -433,6 +478,7 @@ var movingSliderDelay = false; var movingSliderFanout = false; var movingSliderSpeed = false; var movingSliderFactor = false; +var movingSliderCombFilter = false; var movingSliderLocalFactor = false; var movingSliderReflective = false; var movingSliderDiffusion = false; @@ -488,6 +534,18 @@ function mouseMoveEvent(event) { var factor = ((newThumbX - factorMinThumbX) / (factorMaxThumbX - factorMinThumbX)) * factorScale; AudioReflector.setDistanceAttenuationScalingFactor(factor); } + if (movingSliderCombFilter) { + newThumbX = event.x - thumbClickOffsetX; + if (newThumbX < combFilterMinThumbX) { + newThumbX = combFilterMminThumbX; + } + if (newThumbX > combFilterMaxThumbX) { + newThumbX = combFilterMaxThumbX; + } + Overlays.editOverlay(combFilterThumb, { x: newThumbX } ); + var combFilter = ((newThumbX - combFilterMinThumbX) / (combFilterMaxThumbX - combFilterMinThumbX)) * combFilterScale; + AudioReflector.setCombFilterWindow(combFilter); + } if (movingSliderLocalFactor) { newThumbX = event.x - thumbClickOffsetX; @@ -566,6 +624,10 @@ function mousePressEvent(event) { movingSliderLocalFactor = true; thumbClickOffsetX = event.x - localFactorThumbX; } + if (clickedOverlay == combFilterThumb) { + movingSliderCombFilter = true; + thumbClickOffsetX = event.x - combFilterThumbX; + } if (clickedOverlay == diffusionThumb) { movingSliderDiffusion = true; thumbClickOffsetX = event.x - diffusionThumbX; @@ -604,6 +666,12 @@ function mouseReleaseEvent(event) { AudioReflector.setDistanceAttenuationScalingFactor(factor); factorThumbX = newThumbX; } + if (movingSliderCombFilter) { + movingSliderCombFilter = false; + var combFilter = ((newThumbX - combFilterMinThumbX) / (combFilterMaxThumbX - combFilterMinThumbX)) * combFilterScale; + AudioReflector.setCombFilterWindow(combFilter); + combFilterThumbX = newThumbX; + } if (movingSliderLocalFactor) { movingSliderLocalFactor = false; diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 847f1dc0bf..6cfc23da97 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -19,6 +19,7 @@ const float MAXIMUM_DELAY_MS = 1000.0 * 20.0f; // stop reflecting after path is const int DEFAULT_DIFFUSION_FANOUT = 5; const int ABSOLUTE_MAXIMUM_BOUNCE_COUNT = 10; const float DEFAULT_LOCAL_ATTENUATION_FACTOR = 0.125; +const float DEFAULT_COMB_FILTER_WINDOW = 0.05f; //ms delay differential to avoid const float SLIGHTLY_SHORT = 0.999f; // slightly inside the distance so we're on the inside of the reflection point @@ -31,6 +32,7 @@ AudioReflector::AudioReflector(QObject* parent) : _soundMsPerMeter(DEFAULT_MS_DELAY_PER_METER), _distanceAttenuationScalingFactor(DEFAULT_DISTANCE_SCALING_FACTOR), _localAudioAttenuationFactor(DEFAULT_LOCAL_ATTENUATION_FACTOR), + _combFilterWindow(DEFAULT_COMB_FILTER_WINDOW), _diffusionFanout(DEFAULT_DIFFUSION_FANOUT), _absorptionRatio(DEFAULT_ABSORPTION_RATIO), _diffusionRatio(DEFAULT_DIFFUSION_RATIO), @@ -152,7 +154,7 @@ glm::vec3 AudioReflector::getFaceNormal(BoxFace face) { // set up our buffers for our attenuated and delayed samples const int NUMBER_OF_CHANNELS = 2; -void AudioReflector::injectAudiblePoint(const AudiblePoint& audiblePoint, +void AudioReflector::injectAudiblePoint(AudioSource source, const AudiblePoint& audiblePoint, const QByteArray& samples, unsigned int sampleTime, int sampleRate) { bool wantEarSeparation = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingSeparateEars); @@ -180,51 +182,77 @@ void AudioReflector::injectAudiblePoint(const AudiblePoint& audiblePoint, float rightEarDelayMsecs = getDelayFromDistance(rightEarDistance) + audiblePoint.delay; float leftEarDelayMsecs = getDelayFromDistance(leftEarDistance) + audiblePoint.delay; - - _totalDelay += rightEarDelayMsecs + leftEarDelayMsecs; - _delayCount += 2; - _maxDelay = std::max(_maxDelay,rightEarDelayMsecs); - _maxDelay = std::max(_maxDelay,leftEarDelayMsecs); - _minDelay = std::min(_minDelay,rightEarDelayMsecs); - _minDelay = std::min(_minDelay,leftEarDelayMsecs); - - int rightEarDelay = rightEarDelayMsecs * sampleRate / MSECS_PER_SECOND; - int leftEarDelay = leftEarDelayMsecs * sampleRate / MSECS_PER_SECOND; - - float rightEarAttenuation = audiblePoint.attenuation * - getDistanceAttenuationCoefficient(rightEarDistance + audiblePoint.distance); - - float leftEarAttenuation = audiblePoint.attenuation * - getDistanceAttenuationCoefficient(leftEarDistance + audiblePoint.distance); - - _totalAttenuation += rightEarAttenuation + leftEarAttenuation; - _attenuationCount += 2; - _maxAttenuation = std::max(_maxAttenuation,rightEarAttenuation); - _maxAttenuation = std::max(_maxAttenuation,leftEarAttenuation); - _minAttenuation = std::min(_minAttenuation,rightEarAttenuation); - _minAttenuation = std::min(_minAttenuation,leftEarAttenuation); + float averageEarDelayMsecs = (leftEarDelayMsecs + rightEarDelayMsecs) / 2.0f; - // run through the samples, and attenuate them - for (int sample = 0; sample < totalNumberOfStereoSamples; sample++) { - int16_t leftSample = originalSamplesData[sample * NUMBER_OF_CHANNELS]; - int16_t rightSample = leftSample; - if (wantStereo) { - rightSample = originalSamplesData[(sample * NUMBER_OF_CHANNELS) + 1]; + bool safeToInject = true; // assume the best + + QMap& knownDelays = (source == INBOUND_AUDIO) ? _inboundAudioDelays : _localAudioDelays; + + // check to see if the known delays is too close + QMap::const_iterator lowerBound = knownDelays.lowerBound(averageEarDelayMsecs - _combFilterWindow); + if (lowerBound != knownDelays.end()) { + float closestFound = lowerBound.value(); + float deltaToClosest = (averageEarDelayMsecs - closestFound); + //qDebug() << "knownDelays=" << knownDelays; + //qDebug() << "averageEarDelayMsecs=" << averageEarDelayMsecs << " closestFound=" << closestFound; + //qDebug() << "deltaToClosest=" << deltaToClosest; + if (deltaToClosest > -_combFilterWindow && deltaToClosest < _combFilterWindow) { + //qDebug() << "**** WE THINK WE'RE TOO CLOSE!! ****"; + safeToInject = false; } - - attenuatedLeftSamplesData[sample * NUMBER_OF_CHANNELS] = leftSample * leftEarAttenuation; - attenuatedLeftSamplesData[sample * NUMBER_OF_CHANNELS + 1] = 0; - - attenuatedRightSamplesData[sample * NUMBER_OF_CHANNELS] = 0; - attenuatedRightSamplesData[sample * NUMBER_OF_CHANNELS + 1] = rightSample * rightEarAttenuation; } - - // now inject the attenuated array with the appropriate delay - unsigned int sampleTimeLeft = sampleTime + leftEarDelay; - unsigned int sampleTimeRight = sampleTime + rightEarDelay; - _audio->addSpatialAudioToBuffer(sampleTimeLeft, attenuatedLeftSamples, totalNumberOfSamples); - _audio->addSpatialAudioToBuffer(sampleTimeRight, attenuatedRightSamples, totalNumberOfSamples); + if (!safeToInject) { + QVector& suppressedEchoes = (source == INBOUND_AUDIO) ? _inboundEchoesSuppressed : _localEchoesSuppressed; + suppressedEchoes << averageEarDelayMsecs; + } else { + knownDelays[averageEarDelayMsecs] = averageEarDelayMsecs; + + _totalDelay += rightEarDelayMsecs + leftEarDelayMsecs; + _delayCount += 2; + _maxDelay = std::max(_maxDelay,rightEarDelayMsecs); + _maxDelay = std::max(_maxDelay,leftEarDelayMsecs); + _minDelay = std::min(_minDelay,rightEarDelayMsecs); + _minDelay = std::min(_minDelay,leftEarDelayMsecs); + + int rightEarDelay = rightEarDelayMsecs * sampleRate / MSECS_PER_SECOND; + int leftEarDelay = leftEarDelayMsecs * sampleRate / MSECS_PER_SECOND; + + float rightEarAttenuation = audiblePoint.attenuation * + getDistanceAttenuationCoefficient(rightEarDistance + audiblePoint.distance); + + float leftEarAttenuation = audiblePoint.attenuation * + getDistanceAttenuationCoefficient(leftEarDistance + audiblePoint.distance); + + _totalAttenuation += rightEarAttenuation + leftEarAttenuation; + _attenuationCount += 2; + _maxAttenuation = std::max(_maxAttenuation,rightEarAttenuation); + _maxAttenuation = std::max(_maxAttenuation,leftEarAttenuation); + _minAttenuation = std::min(_minAttenuation,rightEarAttenuation); + _minAttenuation = std::min(_minAttenuation,leftEarAttenuation); + + // run through the samples, and attenuate them + for (int sample = 0; sample < totalNumberOfStereoSamples; sample++) { + int16_t leftSample = originalSamplesData[sample * NUMBER_OF_CHANNELS]; + int16_t rightSample = leftSample; + if (wantStereo) { + rightSample = originalSamplesData[(sample * NUMBER_OF_CHANNELS) + 1]; + } + + attenuatedLeftSamplesData[sample * NUMBER_OF_CHANNELS] = leftSample * leftEarAttenuation; + attenuatedLeftSamplesData[sample * NUMBER_OF_CHANNELS + 1] = 0; + + attenuatedRightSamplesData[sample * NUMBER_OF_CHANNELS] = 0; + attenuatedRightSamplesData[sample * NUMBER_OF_CHANNELS + 1] = rightSample * rightEarAttenuation; + } + + // now inject the attenuated array with the appropriate delay + unsigned int sampleTimeLeft = sampleTime + leftEarDelay; + unsigned int sampleTimeRight = sampleTime + rightEarDelay; + + _audio->addSpatialAudioToBuffer(sampleTimeLeft, attenuatedLeftSamples, totalNumberOfSamples); + _audio->addSpatialAudioToBuffer(sampleTimeRight, attenuatedRightSamples, totalNumberOfSamples); + } } void AudioReflector::processLocalAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { @@ -244,13 +272,19 @@ void AudioReflector::processLocalAudio(unsigned int sampleTime, const QByteArray stereoSamples[i* NUM_CHANNELS_OUTPUT] = monoSamples[i] * _localAudioAttenuationFactor; stereoSamples[(i * NUM_CHANNELS_OUTPUT) + 1] = monoSamples[i] * _localAudioAttenuationFactor; } + _localAudioDelays.clear(); + _localEchoesSuppressed.clear(); echoAudio(LOCAL_AUDIO, sampleTime, stereoInputData, outputFormat); + //qDebug() << _localAudioDelays; } } } void AudioReflector::processInboundAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { + _inboundAudioDelays.clear(); + _inboundEchoesSuppressed.clear(); echoAudio(INBOUND_AUDIO, sampleTime, samples, format); + //qDebug() << _inboundAudioDelays; } void AudioReflector::echoAudio(AudioSource source, unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { @@ -269,7 +303,7 @@ void AudioReflector::echoAudio(AudioSource source, unsigned int sampleTime, cons QVector& audiblePoints = source == INBOUND_AUDIO ? _inboundAudiblePoints : _localAudiblePoints; foreach(const AudiblePoint& audiblePoint, audiblePoints) { - injectAudiblePoint(audiblePoint, samples, sampleTime, format.sampleRate()); + injectAudiblePoint(source, audiblePoint, samples, sampleTime, format.sampleRate()); } _averageDelay = _delayCount == 0 ? 0 : _totalDelay / _delayCount; diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 900f567920..9e697b4918 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -86,6 +86,8 @@ public slots: float getMinAttenuation() const { return _minAttenuation; } float getDelayFromDistance(float distance); int getDiffusionPathCount() const { return _diffusionPathCount; } + int getEchoesInjected() const { return _inboundAudioDelays.size() + _localAudioDelays.size(); } + int getEchoesSuppressed() const { return _inboundEchoesSuppressed.size() + _localEchoesSuppressed.size(); } /// ms of delay added to all echos float getPreDelay() const { return _preDelay; } @@ -103,6 +105,10 @@ public slots: float getLocalAudioAttenuationFactor() const { return _localAudioAttenuationFactor; } void setLocalAudioAttenuationFactor(float factor) { _localAudioAttenuationFactor = factor; } + /// ms window in which we will suppress echoes to reduce comb filter effects + float getCombFilterWindow() const { return _combFilterWindow; } + void setCombFilterWindow(float value) { _combFilterWindow = value; } + /// number of points of diffusion from each reflection point, as fanout increases there are more chances for secondary /// echoes, but each diffusion ray is quieter and therefore more likely to be below the sound floor int getDiffusionFanout() const { return _diffusionFanout; } @@ -153,10 +159,14 @@ private: QVector _inboundAudioPaths; /// audio paths we're processing for inbound audio QVector _inboundAudiblePoints; /// the audible points that have been calculated from the inbound audio paths + QMap _inboundAudioDelays; /// delay times for currently injected audio points + QVector _inboundEchoesSuppressed; /// delay times for currently injected audio points QVector _localAudioPaths; /// audio paths we're processing for local audio QVector _localAudiblePoints; /// the audible points that have been calculated from the local audio paths - + QMap _localAudioDelays; /// delay times for currently injected audio points + QVector _localEchoesSuppressed; /// delay times for currently injected audio points + // adds a sound source to begin an audio path trace, these can be the initial sound sources with their directional properties, // as well as diffusion sound sources void addAudioPath(AudioSource source, const glm::vec3& origin, const glm::vec3& initialDirection, float initialAttenuation, @@ -173,7 +183,7 @@ private: int countDiffusionPaths(); glm::vec3 getFaceNormal(BoxFace face); - void injectAudiblePoint(const AudiblePoint& audiblePoint, const QByteArray& samples, unsigned int sampleTime, int sampleRate); + void injectAudiblePoint(AudioSource source, const AudiblePoint& audiblePoint, const QByteArray& samples, unsigned int sampleTime, int sampleRate); void echoAudio(AudioSource source, unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); // return the surface characteristics of the element we hit @@ -186,6 +196,7 @@ private: float _soundMsPerMeter; float _distanceAttenuationScalingFactor; float _localAudioAttenuationFactor; + float _combFilterWindow; int _diffusionFanout; // number of points of diffusion from each reflection point diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp index 98955b34f5..153e39452c 100644 --- a/interface/src/ui/Stats.cpp +++ b/interface/src/ui/Stats.cpp @@ -343,7 +343,7 @@ void Stats::display( lines = _expanded ? 12 : 3; if (_expanded && Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessing)) { - lines += 7; // spatial audio processing adds 1 spacing line and 6 extra lines of info + lines += 8; // spatial audio processing adds 1 spacing line and 7 extra lines of info } drawBackground(backgroundColor, horizontalOffset, 0, glWidget->width() - horizontalOffset, lines * STATS_PELS_PER_LINE + 10); @@ -577,6 +577,14 @@ void Stats::display( verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + sprintf(reflectionsStatus, "Comb Filter Window: %5.3f ms, Allowed: %d, Suppressed: %d", + audioReflector->getCombFilterWindow(), + audioReflector->getEchoesInjected(), + audioReflector->getEchoesSuppressed()); + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + } } From 3cb109ec89a240ce8ff79f2b64b32b7e9e2475fd Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 16 Apr 2014 15:21:04 -0700 Subject: [PATCH 458/595] clean up --- interface/src/Audio.cpp | 7 ++----- interface/src/AudioReflector.cpp | 11 +++-------- 2 files changed, 5 insertions(+), 13 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 06cb1fe461..cdd549752b 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -564,12 +564,9 @@ void Audio::handleAudioInput() { _lastInputLoudness = 0; } - // at this point we have clean monoAudioSamples, which match our target output... this is what we should send - // to our interested listeners - // send our local loopback to any interested parties + // at this point we have clean monoAudioSamples, which match our target output... + // this is what we should send to our interested listeners if (_processSpatialAudio && !_muted && _audioOutput) { - // local audio is sent already resampled to match the network input format, so processors - // can easily handle the audio in a format ready to post back to the audio device QByteArray monoInputData((char*)monoAudioSamples, NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL * sizeof(int16_t)); emit processLocalAudio(_spatialAudioStart, monoInputData, _desiredInputFormat); } diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 6cfc23da97..e71c53857f 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -186,22 +186,19 @@ void AudioReflector::injectAudiblePoint(AudioSource source, const AudiblePoint& bool safeToInject = true; // assume the best + // check to see if this new injection point would be within the comb filter + // suppression window for any of the existing known delays QMap& knownDelays = (source == INBOUND_AUDIO) ? _inboundAudioDelays : _localAudioDelays; - - // check to see if the known delays is too close QMap::const_iterator lowerBound = knownDelays.lowerBound(averageEarDelayMsecs - _combFilterWindow); if (lowerBound != knownDelays.end()) { float closestFound = lowerBound.value(); float deltaToClosest = (averageEarDelayMsecs - closestFound); - //qDebug() << "knownDelays=" << knownDelays; - //qDebug() << "averageEarDelayMsecs=" << averageEarDelayMsecs << " closestFound=" << closestFound; - //qDebug() << "deltaToClosest=" << deltaToClosest; if (deltaToClosest > -_combFilterWindow && deltaToClosest < _combFilterWindow) { - //qDebug() << "**** WE THINK WE'RE TOO CLOSE!! ****"; safeToInject = false; } } + // keep track of any of our suppressed echoes so we can report them in our statistics if (!safeToInject) { QVector& suppressedEchoes = (source == INBOUND_AUDIO) ? _inboundEchoesSuppressed : _localEchoesSuppressed; suppressedEchoes << averageEarDelayMsecs; @@ -275,7 +272,6 @@ void AudioReflector::processLocalAudio(unsigned int sampleTime, const QByteArray _localAudioDelays.clear(); _localEchoesSuppressed.clear(); echoAudio(LOCAL_AUDIO, sampleTime, stereoInputData, outputFormat); - //qDebug() << _localAudioDelays; } } } @@ -284,7 +280,6 @@ void AudioReflector::processInboundAudio(unsigned int sampleTime, const QByteArr _inboundAudioDelays.clear(); _inboundEchoesSuppressed.clear(); echoAudio(INBOUND_AUDIO, sampleTime, samples, format); - //qDebug() << _inboundAudioDelays; } void AudioReflector::echoAudio(AudioSource source, unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { From 67cc186964909449818eca8c3b11d158608071d5 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 16 Apr 2014 16:29:22 -0700 Subject: [PATCH 459/595] optional sending of assignment pool from ds assignment page --- domain-server/resources/web/assignment/css/style.css | 6 +++--- domain-server/resources/web/assignment/index.shtml | 9 +++++++-- domain-server/resources/web/assignment/js/assignment.js | 5 +++++ 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/domain-server/resources/web/assignment/css/style.css b/domain-server/resources/web/assignment/css/style.css index b6c26ca9fd..51813a4d73 100644 --- a/domain-server/resources/web/assignment/css/style.css +++ b/domain-server/resources/web/assignment/css/style.css @@ -42,13 +42,13 @@ body { background-color: #28FF57; } -#instance-field { +#extra-fields { position: absolute; right: 20px; - top: 40px; + top: 30px; } -#instance-field input { +#extra-fields input { width: 80px; } diff --git a/domain-server/resources/web/assignment/index.shtml b/domain-server/resources/web/assignment/index.shtml index 64a6d8825f..27c84be985 100644 --- a/domain-server/resources/web/assignment/index.shtml +++ b/domain-server/resources/web/assignment/index.shtml @@ -14,8 +14,13 @@ Run -
- +
+
+ +
+
+ +
diff --git a/domain-server/resources/web/assignment/js/assignment.js b/domain-server/resources/web/assignment/js/assignment.js index a04c8192f4..71f4373251 100644 --- a/domain-server/resources/web/assignment/js/assignment.js +++ b/domain-server/resources/web/assignment/js/assignment.js @@ -22,9 +22,14 @@ $(document).ready(function(){ + '--' + boundary + '--\r\n'; var headers = {}; + if ($('#instance-field input').val()) { headers['ASSIGNMENT-INSTANCES'] = $('#instance-field input').val(); } + + if ($('#pool-field input').val()) { + headers['ASSIGNMENT-POOL'] = $('#pool-field input').val(); + } // post form to assignment in order to create an assignment $.ajax({ From 4c6471caa4b67dd106e2b01dd5ad226242a20c51 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 16 Apr 2014 16:43:01 -0700 Subject: [PATCH 460/595] fix typo --- interface/src/Audio.cpp | 2 +- interface/src/Menu.cpp | 2 +- interface/src/Menu.h | 2 +- interface/src/ui/Stats.cpp | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index cdd549752b..674eaa0d70 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -783,7 +783,7 @@ void Audio::processReceivedAudio(const QByteArray& audioByteArray) { _ringBuffer.readSamples((int16_t*)buffer.data(), numNetworkOutputSamples); // Accumulate direct transmission of audio from sender to receiver - if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingIncudeOriginal)) { + if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingIncludeOriginal)) { addSpatialAudioToBuffer(sampleTime, buffer, numNetworkOutputSamples); } diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 4e620d38e8..85c3d5b0c3 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -393,7 +393,7 @@ Menu::Menu() : appInstance->getAudio(), SLOT(toggleAudioSpatialProcessing())); - addCheckableActionToQMenuAndActionHash(spatialAudioMenu, MenuOption::AudioSpatialProcessingIncudeOriginal, + addCheckableActionToQMenuAndActionHash(spatialAudioMenu, MenuOption::AudioSpatialProcessingIncludeOriginal, Qt::CTRL | Qt::SHIFT | Qt::Key_O, true); diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 057e6165e3..a62f54b0c6 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -260,7 +260,7 @@ namespace MenuOption { const QString AudioSpatialProcessing = "Audio Spatial Processing"; const QString AudioSpatialProcessingHeadOriented = "Head Oriented"; - const QString AudioSpatialProcessingIncudeOriginal = "Includes Network Original"; + const QString AudioSpatialProcessingIncludeOriginal = "Includes Network Original"; const QString AudioSpatialProcessingPreDelay = "Add Pre-Delay"; const QString AudioSpatialProcessingProcessLocalAudio = "Process Local Audio"; const QString AudioSpatialProcessingRenderPaths = "Render Paths"; diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp index 153e39452c..64616cbdf8 100644 --- a/interface/src/ui/Stats.cpp +++ b/interface/src/ui/Stats.cpp @@ -515,7 +515,7 @@ void Stats::display( sprintf(reflectionsStatus, "Reflections: %d, Original: %s, Ears: %s, Source: %s, Normals: %s", audioReflector->getReflections(), - (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingIncudeOriginal) + (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingIncludeOriginal) ? "included" : "silent"), (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingSeparateEars) ? "two" : "one"), From b269a26441b54e6e8fc7211aa793d3447302da36 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 16 Apr 2014 17:08:06 -0700 Subject: [PATCH 461/595] CR feedback --- interface/src/AudioReflector.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index e71c53857f..9e4b97bf46 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -593,7 +593,6 @@ void AudioReflector::handlePathPoint(AudioPath* path, float distance, OctreeElem pathDistance += glm::distance(start, end); - // We aren't using this... should we be???? float toListenerDistance = glm::distance(end, _listenerPosition); // adjust our current delay by just the delay from the most recent ray @@ -609,7 +608,7 @@ void AudioReflector::handlePathPoint(AudioPath* path, float distance, OctreeElem bool wantDiffusions = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions); int fanout = wantDiffusions ? _diffusionFanout : 0; - float partialDiffusionAttenuation = fanout < 1 ? 0.0f : totalDiffusionAttenuation / fanout; + float partialDiffusionAttenuation = fanout < 1 ? 0.0f : totalDiffusionAttenuation / (float)fanout; // total delay includes the bounce back to listener float totalDelay = currentDelay + getDelayFromDistance(toListenerDistance); From 9fc650dd6e7af6432f0ed8e581bcc168411418ce Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 16 Apr 2014 17:10:26 -0700 Subject: [PATCH 462/595] CR feedback --- interface/src/AudioReflector.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 9e697b4918..2408b70a96 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -23,8 +23,8 @@ enum AudioSource { class AudioPath { public: - AudioPath(AudioSource source = INBOUND_AUDIO, const glm::vec3& origin = glm::vec3(0), - const glm::vec3& direction = glm::vec3(0), float attenuation = 1.0f, + AudioPath(AudioSource source = INBOUND_AUDIO, const glm::vec3& origin = glm::vec3(0.0f), + const glm::vec3& direction = glm::vec3(0.0f), float attenuation = 1.0f, float delay = 0.0f, float distance = 0.0f, bool isDiffusion = false, int bounceCount = 0); AudioSource source; From 1c89d8f3edc33502bcb043b748ede938be41801c Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 16 Apr 2014 17:33:15 -0700 Subject: [PATCH 463/595] editVoxels reformat --- examples/editVoxels.js | 510 ++++++++++++++++++++--------------------- 1 file changed, 255 insertions(+), 255 deletions(-) diff --git a/examples/editVoxels.js b/examples/editVoxels.js index 059b4186a3..030436cbc3 100644 --- a/examples/editVoxels.js +++ b/examples/editVoxels.js @@ -8,10 +8,10 @@ // Captures mouse clicks and edits voxels accordingly. // // click = create a new voxel on this face, same color as old (default color picker state) -// right click or control + click = delete this voxel +// right click or control + click = delete this voxel // shift + click = recolor this voxel // 1 - 8 = pick new color from palette -// 9 = create a new voxel in front of the camera +// 9 = create a new voxel in front of the camera // // Click and drag to create more new voxels in the same direction // @@ -36,7 +36,7 @@ var zFightingSizeAdjust = 0.002; // used to adjust preview voxels to prevent z f var previewLineWidth = 1.5; var inspectJsIsRunning = false; -var isAdding = false; +var isAdding = false; var isExtruding = false; var extrudeDirection = { x: 0, y: 0, z: 0 }; var extrudeScale = 0.0; @@ -48,7 +48,7 @@ var wheelPixelsMoved = 0; var mouseX = 0; -var mouseY = 0; +var mouseY = 0; // Create a table of the different colors you can choose var colors = new Array(); @@ -154,53 +154,53 @@ var editToolsOn = true; // starts out off // previewAsVoxel - by default, we will preview adds/deletes/recolors as just 4 lines on the intersecting face. But if you // the preview to show a full voxel then set this to true and the voxel will be displayed for voxel editing -var previewAsVoxel = false; +var previewAsVoxel = false; var voxelPreview = Overlays.addOverlay("cube", { - position: { x: 0, y: 0, z: 0}, - size: 1, - color: { red: 255, green: 0, blue: 0}, - alpha: 1, - solid: false, - visible: false, - lineWidth: 4 - }); - + position: { x: 0, y: 0, z: 0}, + size: 1, + color: { red: 255, green: 0, blue: 0}, + alpha: 1, + solid: false, + visible: false, + lineWidth: 4 + }); + var linePreviewTop = Overlays.addOverlay("line3d", { - position: { x: 0, y: 0, z: 0}, - end: { x: 0, y: 0, z: 0}, - color: { red: 255, green: 255, blue: 255}, - alpha: 1, - visible: false, - lineWidth: previewLineWidth - }); + position: { x: 0, y: 0, z: 0}, + end: { x: 0, y: 0, z: 0}, + color: { red: 255, green: 255, blue: 255}, + alpha: 1, + visible: false, + lineWidth: previewLineWidth + }); var linePreviewBottom = Overlays.addOverlay("line3d", { - position: { x: 0, y: 0, z: 0}, - end: { x: 0, y: 0, z: 0}, - color: { red: 255, green: 255, blue: 255}, - alpha: 1, - visible: false, - lineWidth: previewLineWidth - }); + position: { x: 0, y: 0, z: 0}, + end: { x: 0, y: 0, z: 0}, + color: { red: 255, green: 255, blue: 255}, + alpha: 1, + visible: false, + lineWidth: previewLineWidth + }); var linePreviewLeft = Overlays.addOverlay("line3d", { - position: { x: 0, y: 0, z: 0}, - end: { x: 0, y: 0, z: 0}, - color: { red: 255, green: 255, blue: 255}, - alpha: 1, - visible: false, - lineWidth: previewLineWidth - }); + position: { x: 0, y: 0, z: 0}, + end: { x: 0, y: 0, z: 0}, + color: { red: 255, green: 255, blue: 255}, + alpha: 1, + visible: false, + lineWidth: previewLineWidth + }); var linePreviewRight = Overlays.addOverlay("line3d", { - position: { x: 0, y: 0, z: 0}, - end: { x: 0, y: 0, z: 0}, - color: { red: 255, green: 255, blue: 255}, - alpha: 1, - visible: false, - lineWidth: previewLineWidth - }); + position: { x: 0, y: 0, z: 0}, + end: { x: 0, y: 0, z: 0}, + color: { red: 255, green: 255, blue: 255}, + alpha: 1, + visible: false, + lineWidth: previewLineWidth + }); // these will be used below @@ -221,33 +221,33 @@ var toolIconUrl = "http://highfidelity-public.s3-us-west-1.amazonaws.com/images/ // create the overlays, position them in a row, set their colors, and for the selected one, use a different source image // location so that it displays the "selected" marker for (s = 0; s < numColors; s++) { - + var extraWidth = 0; - + if (s == 0) { extraWidth = swatchExtraPadding; } - + var imageFromX = swatchExtraPadding - extraWidth + s * swatchWidth; var imageFromY = swatchHeight + 1; - + var swatchX = swatchExtraPadding - extraWidth + swatchesX + ((swatchWidth - 1) * s); - + if (s == (numColors - 1)) { extraWidth = swatchExtraPadding; } - + swatches[s] = Overlays.addOverlay("image", { - x: swatchX, - y: swatchesY, - width: swatchWidth + extraWidth, - height: swatchHeight, - subImage: { x: imageFromX, y: imageFromY, width: swatchWidth + extraWidth, height: swatchHeight }, - imageURL: toolIconUrl + "swatches.svg", - color: colors[s], - alpha: 1, - visible: editToolsOn - }); + x: swatchX, + y: swatchesY, + width: swatchWidth + extraWidth, + height: swatchHeight, + subImage: { x: imageFromX, y: imageFromY, width: swatchWidth + extraWidth, height: swatchHeight }, + imageURL: toolIconUrl + "swatches.svg", + color: colors[s], + alpha: 1, + visible: editToolsOn + }); } @@ -267,29 +267,29 @@ var eyedropperToolAt = 2; var pasteModeColor = { red: 132, green: 61, blue: 255 }; var voxelTool = Overlays.addOverlay("image", { - x: 0, y: 0, width: toolWidth, height: toolHeight, - subImage: { x: 0, y: toolHeight, width: toolWidth, height: toolHeight }, - imageURL: toolIconUrl + "voxel-tool.svg", - visible: false, - alpha: 0.9 - }); + x: 0, y: 0, width: toolWidth, height: toolHeight, + subImage: { x: 0, y: toolHeight, width: toolWidth, height: toolHeight }, + imageURL: toolIconUrl + "voxel-tool.svg", + visible: false, + alpha: 0.9 + }); var recolorTool = Overlays.addOverlay("image", { - x: 0, y: 0, width: toolWidth, height: toolHeight, - subImage: { x: 0, y: toolHeight, width: toolWidth, height: toolHeight }, - imageURL: toolIconUrl + "paint-tool.svg", - visible: false, - alpha: 0.9 - }); + x: 0, y: 0, width: toolWidth, height: toolHeight, + subImage: { x: 0, y: toolHeight, width: toolWidth, height: toolHeight }, + imageURL: toolIconUrl + "paint-tool.svg", + visible: false, + alpha: 0.9 + }); var eyedropperTool = Overlays.addOverlay("image", { - x: 0, y: 0, width: toolWidth, height: toolHeight, - subImage: { x: 0, y: toolHeight, width: toolWidth, height: toolHeight }, - imageURL: toolIconUrl + "eyedropper-tool.svg", - visible: false, - alpha: 0.9 - }); - + x: 0, y: 0, width: toolWidth, height: toolHeight, + subImage: { x: 0, y: toolHeight, width: toolWidth, height: toolHeight }, + imageURL: toolIconUrl + "eyedropper-tool.svg", + visible: false, + alpha: 0.9 + }); + // This will create a couple of image overlays that make a "slider", we will demonstrate how to trap mouse messages to // move the slider @@ -301,12 +301,12 @@ var sliderOffsetX = 17; var sliderX = swatchesX - swatchWidth - sliderOffsetX; var sliderY = windowDimensions.y - sliderHeight + 1; var slider = Overlays.addOverlay("image", { - // alternate form of expressing bounds - bounds: { x: sliderX, y: sliderY, width: sliderWidth, height: sliderHeight}, - imageURL: toolIconUrl + "voxel-size-slider-bg.svg", - alpha: 1, - visible: false - }); + // alternate form of expressing bounds + bounds: { x: sliderX, y: sliderY, width: sliderWidth, height: sliderHeight}, + imageURL: toolIconUrl + "voxel-size-slider-bg.svg", + alpha: 1, + visible: false + }); // The slider is handled in the mouse event callbacks. var isMovingSlider = false; @@ -320,14 +320,14 @@ var thumbX = (minThumbX + maxThumbX) / 2; var thumbOffsetY = 11; var thumbY = sliderY + thumbOffsetY; var thumb = Overlays.addOverlay("image", { - x: sliderX + thumbX, - y: thumbY, - width: 17, - height: 17, - imageURL: toolIconUrl + "voxel-size-slider-handle.svg", - alpha: 1, - visible: false - }); + x: sliderX + thumbX, + y: thumbY, + width: 17, + height: 17, + imageURL: toolIconUrl + "voxel-size-slider-handle.svg", + alpha: 1, + visible: false + }); var pointerVoxelScale = Math.floor(MAX_VOXEL_SCALE + MIN_VOXEL_SCALE) / 2; // this is the voxel scale used for click to add or delete var pointerVoxelScaleSet = false; // if voxel scale has not yet been set, we use the intersection size @@ -377,7 +377,7 @@ function importVoxels() { } else { isImporting = false; } - + return isImporting; } @@ -471,13 +471,13 @@ function calcScaleFromThumb(newThumbX) { thumbAt = newThumbX - minThumbX; thumbStep = Math.floor((thumbAt/ thumbExtents) * (pointerVoxelScaleSteps-1)) + 1; pointerVoxelScale = Math.pow(2, (thumbStep-pointerVoxelScaleOriginStep)); - + // if importing, rescale import ... if (isImporting) { var importScale = (pointerVoxelScale / MAX_VOXEL_SCALE) * MAX_PASTE_VOXEL_SCALE; rescaleImport(importScale); } - + // now reset the display accordingly... calcThumbFromScale(pointerVoxelScale); @@ -492,18 +492,18 @@ function setAudioPosition() { } function getNewPasteVoxel(pickRay) { - + var voxelSize = MIN_PASTE_VOXEL_SCALE + (MAX_PASTE_VOXEL_SCALE - MIN_PASTE_VOXEL_SCALE) * pointerVoxelScale - 1; var origin = { x: pickRay.direction.x, y: pickRay.direction.y, z: pickRay.direction.z }; - + origin.x += pickRay.origin.x; origin.y += pickRay.origin.y; origin.z += pickRay.origin.z; - + origin.x -= voxelSize / 2; origin.y -= voxelSize / 2; origin.z += voxelSize / 2; - + return {origin: origin, voxelSize: voxelSize}; } @@ -529,26 +529,26 @@ var pasteMode = false; function calculateVoxelFromIntersection(intersection, operation) { //print("calculateVoxelFromIntersection() operation="+operation); var resultVoxel; - + var wantDebug = false; if (wantDebug) { - print(">>>>> calculateVoxelFromIntersection().... intersection voxel.red/green/blue=" + intersection.voxel.red + ", " - + intersection.voxel.green + ", " + intersection.voxel.blue); - print(" intersection voxel.x/y/z/s=" + intersection.voxel.x + ", " - + intersection.voxel.y + ", " + intersection.voxel.z+ ": " + intersection.voxel.s); + print(">>>>> calculateVoxelFromIntersection().... intersection voxel.red/green/blue=" + intersection.voxel.red + ", " + + intersection.voxel.green + ", " + intersection.voxel.blue); + print(" intersection voxel.x/y/z/s=" + intersection.voxel.x + ", " + + intersection.voxel.y + ", " + intersection.voxel.z+ ": " + intersection.voxel.s); print(" intersection face=" + intersection.face); print(" intersection distance=" + intersection.distance); - print(" intersection intersection.x/y/z=" + intersection.intersection.x + ", " - + intersection.intersection.y + ", " + intersection.intersection.z); + print(" intersection intersection.x/y/z=" + intersection.intersection.x + ", " + + intersection.intersection.y + ", " + intersection.intersection.z); } var voxelSize; if (pointerVoxelScaleSet) { - voxelSize = pointerVoxelScale; + voxelSize = pointerVoxelScale; } else { - voxelSize = intersection.voxel.s; + voxelSize = intersection.voxel.s; } - + var x; var y; var z; @@ -578,17 +578,17 @@ function calculateVoxelFromIntersection(intersection, operation) { } resultVoxel = { x: x, y: y, z: z, s: voxelSize }; highlightAt = { x: x, y: y, z: z, s: voxelSize }; - + // we only do the "add to the face we're pointing at" adjustment, if the operation is an add // operation, and the target voxel size is equal to or smaller than the intersecting voxel. var wantAddAdjust = (operation == "add" && (voxelSize <= intersection.voxel.s)); if (wantDebug) { print("wantAddAdjust="+wantAddAdjust); } - + // now we also want to calculate the "edge square" for the face for this voxel if (intersection.face == "MIN_X_FACE") { - + highlightAt.x = x - zFightingSizeAdjust; if (wantAddAdjust) { resultVoxel.x -= voxelSize; @@ -598,21 +598,21 @@ function calculateVoxelFromIntersection(intersection, operation) { resultVoxel.bottomRight = {x: highlightAt.x, y: highlightAt.y + zFightingSizeAdjust, z: highlightAt.z + voxelSize - zFightingSizeAdjust }; resultVoxel.topLeft = {x: highlightAt.x, y: highlightAt.y + voxelSize - zFightingSizeAdjust, z: highlightAt.z + zFightingSizeAdjust }; resultVoxel.topRight = {x: highlightAt.x, y: highlightAt.y + voxelSize - zFightingSizeAdjust, z: highlightAt.z + voxelSize - zFightingSizeAdjust }; - + } else if (intersection.face == "MAX_X_FACE") { - + highlightAt.x = x + voxelSize + zFightingSizeAdjust; if (wantAddAdjust) { resultVoxel.x += resultVoxel.s; } - + resultVoxel.bottomRight = {x: highlightAt.x, y: highlightAt.y + zFightingSizeAdjust, z: highlightAt.z + zFightingSizeAdjust }; resultVoxel.bottomLeft = {x: highlightAt.x, y: highlightAt.y + zFightingSizeAdjust, z: highlightAt.z + voxelSize - zFightingSizeAdjust }; resultVoxel.topRight = {x: highlightAt.x, y: highlightAt.y + voxelSize - zFightingSizeAdjust, z: highlightAt.z + zFightingSizeAdjust }; resultVoxel.topLeft = {x: highlightAt.x, y: highlightAt.y + voxelSize - zFightingSizeAdjust, z: highlightAt.z + voxelSize - zFightingSizeAdjust }; - + } else if (intersection.face == "MIN_Y_FACE") { - + highlightAt.y = y - zFightingSizeAdjust; if (wantAddAdjust) { resultVoxel.y -= voxelSize; @@ -622,9 +622,9 @@ function calculateVoxelFromIntersection(intersection, operation) { resultVoxel.topLeft = {x: highlightAt.x + voxelSize - zFightingSizeAdjust, y: highlightAt.y, z: highlightAt.z + zFightingSizeAdjust }; resultVoxel.bottomRight = {x: highlightAt.x + zFightingSizeAdjust , y: highlightAt.y, z: highlightAt.z + voxelSize - zFightingSizeAdjust }; resultVoxel.bottomLeft = {x: highlightAt.x + voxelSize - zFightingSizeAdjust , y: highlightAt.y, z: highlightAt.z + voxelSize - zFightingSizeAdjust }; - + } else if (intersection.face == "MAX_Y_FACE") { - + highlightAt.y = y + voxelSize + zFightingSizeAdjust; if (wantAddAdjust) { resultVoxel.y += voxelSize; @@ -634,9 +634,9 @@ function calculateVoxelFromIntersection(intersection, operation) { resultVoxel.bottomLeft = {x: highlightAt.x + voxelSize - zFightingSizeAdjust, y: highlightAt.y, z: highlightAt.z + zFightingSizeAdjust}; resultVoxel.topRight = {x: highlightAt.x + zFightingSizeAdjust, y: highlightAt.y, z: highlightAt.z + voxelSize - zFightingSizeAdjust}; resultVoxel.topLeft = {x: highlightAt.x + voxelSize - zFightingSizeAdjust, y: highlightAt.y, z: highlightAt.z + voxelSize - zFightingSizeAdjust}; - + } else if (intersection.face == "MIN_Z_FACE") { - + highlightAt.z = z - zFightingSizeAdjust; if (wantAddAdjust) { resultVoxel.z -= voxelSize; @@ -646,19 +646,19 @@ function calculateVoxelFromIntersection(intersection, operation) { resultVoxel.bottomLeft = {x: highlightAt.x + voxelSize - zFightingSizeAdjust, y: highlightAt.y + zFightingSizeAdjust, z: highlightAt.z}; resultVoxel.topRight = {x: highlightAt.x + zFightingSizeAdjust, y: highlightAt.y + voxelSize - zFightingSizeAdjust, z: highlightAt.z }; resultVoxel.topLeft = {x: highlightAt.x + voxelSize - zFightingSizeAdjust, y: highlightAt.y + voxelSize - zFightingSizeAdjust, z: highlightAt.z}; - + } else if (intersection.face == "MAX_Z_FACE") { - + highlightAt.z = z + voxelSize + zFightingSizeAdjust; if (wantAddAdjust) { resultVoxel.z += voxelSize; } - + resultVoxel.bottomLeft = {x: highlightAt.x + zFightingSizeAdjust, y: highlightAt.y + zFightingSizeAdjust, z: highlightAt.z }; resultVoxel.bottomRight = {x: highlightAt.x + voxelSize - zFightingSizeAdjust, y: highlightAt.y + zFightingSizeAdjust, z: highlightAt.z}; resultVoxel.topLeft = {x: highlightAt.x + zFightingSizeAdjust, y: highlightAt.y + voxelSize - zFightingSizeAdjust, z: highlightAt.z }; resultVoxel.topRight = {x: highlightAt.x + voxelSize - zFightingSizeAdjust, y: highlightAt.y + voxelSize - zFightingSizeAdjust, z: highlightAt.z}; - + } return resultVoxel; @@ -666,26 +666,26 @@ function calculateVoxelFromIntersection(intersection, operation) { function showPreviewVoxel() { var voxelColor; - + var pickRay = Camera.computePickRay(trackLastMouseX, trackLastMouseY); var intersection = Voxels.findRayIntersection(pickRay); - - // if the user hasn't updated the + + // if the user hasn't updated the if (!pointerVoxelScaleSet) { calcThumbFromScale(intersection.voxel.s); } - + if (whichColor == -1) { // Copy mode - use clicked voxel color voxelColor = { red: intersection.voxel.red, - green: intersection.voxel.green, - blue: intersection.voxel.blue }; + green: intersection.voxel.green, + blue: intersection.voxel.blue }; } else { voxelColor = { red: colors[whichColor].red, - green: colors[whichColor].green, - blue: colors[whichColor].blue }; + green: colors[whichColor].green, + blue: colors[whichColor].blue }; } - + var guidePosition; if (trackAsRecolor || recolorToolSelected || trackAsEyedropper || eyedropperToolSelected) { Overlays.editOverlay(voxelPreview, { visible: true }); @@ -697,49 +697,49 @@ function showPreviewVoxel() { } function showPreviewLines() { - + var pickRay = Camera.computePickRay(trackLastMouseX, trackLastMouseY); - + if (pasteMode) { // free voxel pasting - + Overlays.editOverlay(voxelPreview, { visible: false }); Overlays.editOverlay(linePreviewLeft, { visible: false }); - + var pasteVoxel = getNewPasteVoxel(pickRay); - + // X axis Overlays.editOverlay(linePreviewBottom, { - position: pasteVoxel.origin, - end: {x: pasteVoxel.origin.x + pasteVoxel.voxelSize, y: pasteVoxel.origin.y, z: pasteVoxel.origin.z }, - visible: true - }); - + position: pasteVoxel.origin, + end: {x: pasteVoxel.origin.x + pasteVoxel.voxelSize, y: pasteVoxel.origin.y, z: pasteVoxel.origin.z }, + visible: true + }); + // Y axis Overlays.editOverlay(linePreviewRight, { - position: pasteVoxel.origin, - end: {x: pasteVoxel.origin.x, y: pasteVoxel.origin.y + pasteVoxel.voxelSize, z: pasteVoxel.origin.z }, - visible: true - }); - + position: pasteVoxel.origin, + end: {x: pasteVoxel.origin.x, y: pasteVoxel.origin.y + pasteVoxel.voxelSize, z: pasteVoxel.origin.z }, + visible: true + }); + // Z axis Overlays.editOverlay(linePreviewTop, { - position: pasteVoxel.origin, - end: {x: pasteVoxel.origin.x, y: pasteVoxel.origin.y, z: pasteVoxel.origin.z - pasteVoxel.voxelSize }, - visible: true - }); - + position: pasteVoxel.origin, + end: {x: pasteVoxel.origin.x, y: pasteVoxel.origin.y, z: pasteVoxel.origin.z - pasteVoxel.voxelSize }, + visible: true + }); + return; } - + var intersection = Voxels.findRayIntersection(pickRay); if (intersection.intersects) { - - // if the user hasn't updated the + + // if the user hasn't updated the if (!pointerVoxelScaleSet) { calcThumbFromScale(intersection.voxel.s); } - + resultVoxel = calculateVoxelFromIntersection(intersection,""); Overlays.editOverlay(voxelPreview, { visible: false }); Overlays.editOverlay(linePreviewTop, { position: resultVoxel.topLeft, end: resultVoxel.topRight, visible: true }); @@ -759,7 +759,7 @@ function showPreviewGuides() { if (editToolsOn) { if (previewAsVoxel) { showPreviewVoxel(); - + // make sure alternative is hidden Overlays.editOverlay(linePreviewTop, { visible: false }); Overlays.editOverlay(linePreviewBottom, { visible: false }); @@ -791,7 +791,7 @@ function trackKeyPressEvent(event) { if (!editToolsOn) { return; } - + if (event.text == "CONTROL") { trackAsDelete = true; moveTools(); @@ -819,11 +819,11 @@ function trackKeyReleaseEvent(event) { showPreviewGuides(); scriptInitSound.playRandom(); } - + if (event.text == "ALT") { inspectJsIsRunning = false; } - + if (editToolsOn) { if (event.text == "ESC") { pointerVoxelScaleSet = false; @@ -855,15 +855,15 @@ function trackKeyReleaseEvent(event) { if (event.text == "F1") { previewAsVoxel = !previewAsVoxel; } - + showPreviewGuides(); - } + } } function mousePressEvent(event) { // if our tools are off, then don't do anything if (!editToolsOn) { - return; + return; } if (inspectJsIsRunning) { return; @@ -878,7 +878,7 @@ function mousePressEvent(event) { thumbClickOffsetX = event.x - (sliderX + thumbX); // this should be the position of the mouse relative to the thumb clickedOnSomething = true; - Overlays.editOverlay(thumb, { imageURL: toolIconUrl + "voxel-size-slider-handle.svg", }); + //Overlays.editOverlay(thumb, { imageURL: toolIconUrl + "voxel-size-slider-handle.svg", }); } else if (clickedOverlay == voxelTool) { modeSwitchSound.play(0); @@ -930,7 +930,7 @@ function mousePressEvent(event) { if (clickedOnSomething) { return; // no further processing } - + // TODO: does any of this stuff need to execute if we're panning or orbiting? trackMouseEvent(event); // used by preview support mouseX = event.x; @@ -938,7 +938,7 @@ function mousePressEvent(event) { var pickRay = Camera.computePickRay(event.x, event.y); var intersection = Voxels.findRayIntersection(pickRay); audioOptions.position = Vec3.sum(pickRay.origin, pickRay.direction); - + if (isImporting) { print("placing import..."); placeImport(); @@ -946,7 +946,7 @@ function mousePressEvent(event) { moveTools(); return; } - + if (pasteMode) { var pasteVoxel = getNewPasteVoxel(pickRay); Clipboard.pasteVoxel(pasteVoxel.origin.x, pasteVoxel.origin.y, pasteVoxel.origin.z, pasteVoxel.voxelSize); @@ -954,9 +954,9 @@ function mousePressEvent(event) { moveTools(); return; } - + if (intersection.intersects) { - // if the user hasn't updated the + // if the user hasn't updated the if (!pointerVoxelScaleSet) { calcThumbFromScale(intersection.voxel.s); } @@ -979,9 +979,9 @@ function mousePressEvent(event) { } else if (recolorToolSelected || trackAsRecolor) { // Recolor Voxel voxelDetails = calculateVoxelFromIntersection(intersection,"recolor"); - + // doing this erase then set will make sure we only recolor just the target voxel - Voxels.setVoxel(voxelDetails.x, voxelDetails.y, voxelDetails.z, voxelDetails.s, + Voxels.setVoxel(voxelDetails.x, voxelDetails.y, voxelDetails.z, voxelDetails.s, colors[whichColor].red, colors[whichColor].green, colors[whichColor].blue); swatchesSound.play(whichColor); Overlays.editOverlay(voxelPreview, { visible: false }); @@ -989,30 +989,30 @@ function mousePressEvent(event) { // Add voxel on face if (whichColor == -1) { // Copy mode - use clicked voxel color - newColor = { - red: intersection.voxel.red, - green: intersection.voxel.green, + newColor = { + red: intersection.voxel.red, + green: intersection.voxel.green, blue: intersection.voxel.blue }; } else { - newColor = { - red: colors[whichColor].red, - green: colors[whichColor].green, + newColor = { + red: colors[whichColor].red, + green: colors[whichColor].green, blue: colors[whichColor].blue }; } - + voxelDetails = calculateVoxelFromIntersection(intersection,"add"); Voxels.setVoxel(voxelDetails.x, voxelDetails.y, voxelDetails.z, voxelDetails.s, - newColor.red, newColor.green, newColor.blue); + newColor.red, newColor.green, newColor.blue); lastVoxelPosition = { x: voxelDetails.x, y: voxelDetails.y, z: voxelDetails.z }; lastVoxelColor = { red: newColor.red, green: newColor.green, blue: newColor.blue }; lastVoxelScale = voxelDetails.s; - + addVoxelSound.playRandom(); Overlays.editOverlay(voxelPreview, { visible: false }); dragStart = { x: event.x, y: event.y }; isAdding = true; - } + } } } @@ -1031,18 +1031,18 @@ function keyPressEvent(event) { swatchesSound.play(whichColor); moveTools(); } else if (event.text == "0") { - // Create a brand new 1 meter voxel in front of your avatar - var color = whichColor; + // Create a brand new 1 meter voxel in front of your avatar + var color = whichColor; if (color == -1) color = 0; var newPosition = getNewVoxelPosition(); - var newVoxel = { - x: newPosition.x, - y: newPosition.y , - z: newPosition.z, - s: NEW_VOXEL_SIZE, - red: colors[color].red, - green: colors[color].green, - blue: colors[color].blue }; + var newVoxel = { + x: newPosition.x, + y: newPosition.y , + z: newPosition.z, + s: NEW_VOXEL_SIZE, + red: colors[color].red, + green: colors[color].green, + blue: colors[color].blue }; Voxels.eraseVoxel(newVoxel.x, newVoxel.y, newVoxel.z, newVoxel.s); Voxels.setVoxel(newVoxel.x, newVoxel.y, newVoxel.z, newVoxel.s, newVoxel.red, newVoxel.green, newVoxel.blue); setAudioPosition(); @@ -1064,7 +1064,7 @@ function keyReleaseEvent(event) { function setupMenus() { // hook up menus Menu.menuItemEvent.connect(menuItemEvent); - + // add our menuitems Menu.addMenuItem({ menuName: "Edit", menuItemName: "Voxels", isSeparator: true, beforeItem: "Physics" }); Menu.addMenuItem({ menuName: "Edit", menuItemName: "Cut", shortcutKey: "CTRL+X", afterItem: "Voxels" }); @@ -1072,7 +1072,7 @@ function setupMenus() { Menu.addMenuItem({ menuName: "Edit", menuItemName: "Paste", shortcutKey: "CTRL+V", afterItem: "Copy" }); Menu.addMenuItem({ menuName: "Edit", menuItemName: "Nudge", shortcutKey: "CTRL+N", afterItem: "Paste" }); Menu.addMenuItem({ menuName: "Edit", menuItemName: "Delete", shortcutKeyEvent: { text: "backspace" }, afterItem: "Nudge" }); - + Menu.addMenuItem({ menuName: "File", menuItemName: "Voxels", isSeparator: true, beforeItem: "Settings" }); Menu.addMenuItem({ menuName: "File", menuItemName: "Export Voxels", shortcutKey: "CTRL+E", afterItem: "Voxels" }); Menu.addMenuItem({ menuName: "File", menuItemName: "Import Voxels", shortcutKey: "CTRL+I", afterItem: "Export Voxels" }); @@ -1092,10 +1092,10 @@ function cleanupMenus() { } function menuItemEvent(menuItem) { - + // handle clipboard items if (editToolsOn) { - + var pickRay = Camera.computePickRay(trackLastMouseX, trackLastMouseY); var intersection = Voxels.findRayIntersection(pickRay); selectedVoxel = calculateVoxelFromIntersection(intersection,"select"); @@ -1131,7 +1131,7 @@ function menuItemEvent(menuItem) { Clipboard.deleteVoxel(selectedVoxel.x, selectedVoxel.y, selectedVoxel.z, selectedVoxel.s); } } - + if (menuItem == "Export Voxels") { print("export"); Clipboard.exportVoxel(selectedVoxel.x, selectedVoxel.y, selectedVoxel.z, selectedVoxel.s); @@ -1172,9 +1172,9 @@ function mouseMoveEvent(event) { // Watch the drag direction to tell which way to 'extrude' this voxel if (!isExtruding) { var pickRay = Camera.computePickRay(event.x, event.y); - var lastVoxelDistance = { x: pickRay.origin.x - lastVoxelPosition.x, - y: pickRay.origin.y - lastVoxelPosition.y, - z: pickRay.origin.z - lastVoxelPosition.z }; + var lastVoxelDistance = { x: pickRay.origin.x - lastVoxelPosition.x, + y: pickRay.origin.y - lastVoxelPosition.y, + z: pickRay.origin.z - lastVoxelPosition.z }; var distance = Vec3.length(lastVoxelDistance); var mouseSpot = { x: pickRay.direction.x * distance, y: pickRay.direction.y * distance, z: pickRay.direction.z * distance }; mouseSpot.x += pickRay.origin.x; @@ -1192,15 +1192,15 @@ function mouseMoveEvent(event) { else if (dy < -lastVoxelScale) extrudeDirection.y = -extrudeScale; else if (dz > lastVoxelScale) extrudeDirection.z = extrudeScale; else if (dz < -lastVoxelScale) extrudeDirection.z = -extrudeScale; - else isExtruding = false; + else isExtruding = false; } else { // We have got an extrusion direction, now look for mouse move beyond threshold to add new voxel - var dx = event.x - mouseX; + var dx = event.x - mouseX; var dy = event.y - mouseY; if (Math.sqrt(dx*dx + dy*dy) > PIXELS_PER_EXTRUDE_VOXEL) { lastVoxelPosition = Vec3.sum(lastVoxelPosition, extrudeDirection); - Voxels.setVoxel(lastVoxelPosition.x, lastVoxelPosition.y, lastVoxelPosition.z, - extrudeScale, lastVoxelColor.red, lastVoxelColor.green, lastVoxelColor.blue); + Voxels.setVoxel(lastVoxelPosition.x, lastVoxelPosition.y, lastVoxelPosition.z, + extrudeScale, lastVoxelColor.red, lastVoxelColor.green, lastVoxelColor.blue); mouseX = event.x; mouseY = event.y; } @@ -1214,64 +1214,64 @@ function mouseMoveEvent(event) { function mouseReleaseEvent(event) { // if our tools are off, then don't do anything if (!editToolsOn) { - return; + return; } if (inspectJsIsRunning) { return; } - + if (isMovingSlider) { isMovingSlider = false; } isAdding = false; - isExtruding = false; + isExtruding = false; } function moveTools() { // move the swatches swatchesX = (windowDimensions.x - (swatchesWidth + sliderWidth)) / 2; swatchesY = windowDimensions.y - swatchHeight + 1; - + // create the overlays, position them in a row, set their colors, and for the selected one, use a different source image // location so that it displays the "selected" marker for (s = 0; s < numColors; s++) { var extraWidth = 0; - + if (s == 0) { extraWidth = swatchExtraPadding; } - + var imageFromX = swatchExtraPadding - extraWidth + s * swatchWidth; var imageFromY = swatchHeight + 1; if (s == whichColor) { imageFromY = 0; } - + var swatchX = swatchExtraPadding - extraWidth + swatchesX + ((swatchWidth - 1) * s); - + if (s == (numColors - 1)) { extraWidth = swatchExtraPadding; } Overlays.editOverlay(swatches[s], { - x: swatchX, - y: swatchesY, - subImage: { x: imageFromX, y: imageFromY, width: swatchWidth + extraWidth, height: swatchHeight }, - color: colors[s], - alpha: 1, - visible: editToolsOn - }); + x: swatchX, + y: swatchesY, + subImage: { x: imageFromX, y: imageFromY, width: swatchWidth + extraWidth, height: swatchHeight }, + color: colors[s], + alpha: 1, + visible: editToolsOn + }); } - + // move the tools toolsY = (windowDimensions.y - toolsHeight) / 2; - + var voxelToolOffset = 1, - recolorToolOffset = 1, - eyedropperToolOffset = 1; - + recolorToolOffset = 1, + eyedropperToolOffset = 1; + var voxelToolColor = WHITE_COLOR; - + if (recolorToolSelected) { recolorToolOffset = 2; } else if (eyedropperToolSelected) { @@ -1282,34 +1282,34 @@ function moveTools() { } voxelToolOffset = 2; } - + Overlays.editOverlay(voxelTool, { - subImage: { x: 0, y: toolHeight * voxelToolOffset, width: toolWidth, height: toolHeight }, - x: toolsX, y: toolsY + ((toolHeight + toolVerticalSpacing) * voxelToolAt), width: toolWidth, height: toolHeight, - color: voxelToolColor, - visible: editToolsOn - }); - + subImage: { x: 0, y: toolHeight * voxelToolOffset, width: toolWidth, height: toolHeight }, + x: toolsX, y: toolsY + ((toolHeight + toolVerticalSpacing) * voxelToolAt), width: toolWidth, height: toolHeight, + color: voxelToolColor, + visible: editToolsOn + }); + Overlays.editOverlay(recolorTool, { - subImage: { x: 0, y: toolHeight * recolorToolOffset, width: toolWidth, height: toolHeight }, - x: toolsX, y: toolsY + ((toolHeight + toolVerticalSpacing) * recolorToolAt), width: toolWidth, height: toolHeight, - visible: editToolsOn - }); - + subImage: { x: 0, y: toolHeight * recolorToolOffset, width: toolWidth, height: toolHeight }, + x: toolsX, y: toolsY + ((toolHeight + toolVerticalSpacing) * recolorToolAt), width: toolWidth, height: toolHeight, + visible: editToolsOn + }); + Overlays.editOverlay(eyedropperTool, { - subImage: { x: 0, y: toolHeight * eyedropperToolOffset, width: toolWidth, height: toolHeight }, - x: toolsX, y: toolsY + ((toolHeight + toolVerticalSpacing) * eyedropperToolAt), width: toolWidth, height: toolHeight, - visible: editToolsOn - }); - + subImage: { x: 0, y: toolHeight * eyedropperToolOffset, width: toolWidth, height: toolHeight }, + x: toolsX, y: toolsY + ((toolHeight + toolVerticalSpacing) * eyedropperToolAt), width: toolWidth, height: toolHeight, + visible: editToolsOn + }); + sliderX = swatchesX + swatchesWidth - sliderOffsetX; sliderY = windowDimensions.y - sliderHeight + 1; thumbY = sliderY + thumbOffsetY; Overlays.editOverlay(slider, { x: sliderX, y: sliderY, visible: editToolsOn }); - + // This is the thumb of our slider Overlays.editOverlay(thumb, { x: sliderX + thumbX, y: thumbY, visible: editToolsOn }); - + } var lastFingerAddVoxel = { x: -1, y: -1, z: -1}; // off of the build-able area @@ -1318,8 +1318,8 @@ var lastFingerDeleteVoxel = { x: -1, y: -1, z: -1}; // off of the build-able are function checkControllers() { var controllersPerPalm = 2; // palm and finger for (var palm = 0; palm < 2; palm++) { - var palmController = palm * controllersPerPalm; - var fingerTipController = palmController + 1; + var palmController = palm * controllersPerPalm; + var fingerTipController = palmController + 1; var fingerTipPosition = Controller.getSpatialControlPosition(fingerTipController); var BUTTON_COUNT = 6; @@ -1327,7 +1327,7 @@ function checkControllers() { var BUTTON_1 = BUTTON_BASE + 1; var BUTTON_2 = BUTTON_BASE + 2; var FINGERTIP_VOXEL_SIZE = 0.05; - + if (Controller.isButtonPressed(BUTTON_1)) { if (Vec3.length(Vec3.subtract(fingerTipPosition,lastFingerAddVoxel)) > (FINGERTIP_VOXEL_SIZE / 2)) { if (whichColor == -1) { @@ -1335,10 +1335,10 @@ function checkControllers() { } else { newColor = { red: colors[whichColor].red, green: colors[whichColor].green, blue: colors[whichColor].blue }; } - + Voxels.eraseVoxel(fingerTipPosition.x, fingerTipPosition.y, fingerTipPosition.z, FINGERTIP_VOXEL_SIZE); Voxels.setVoxel(fingerTipPosition.x, fingerTipPosition.y, fingerTipPosition.z, FINGERTIP_VOXEL_SIZE, - newColor.red, newColor.green, newColor.blue); + newColor.red, newColor.green, newColor.blue); lastFingerAddVoxel = fingerTipPosition; } @@ -1358,18 +1358,18 @@ function update(deltaTime) { windowDimensions = newWindowDimensions; moveTools(); } - + checkControllers(); - + // Move Import Preview if (isImporting) { var position = MyAvatar.position; var forwardVector = Quat.getFront(MyAvatar.orientation); var targetPosition = Vec3.sum(position, Vec3.multiply(forwardVector, importScale)); var newPosition = { - x: Math.floor(targetPosition.x / importScale) * importScale, - y: Math.floor(targetPosition.y / importScale) * importScale, - z: Math.floor(targetPosition.z / importScale) * importScale + x: Math.floor(targetPosition.x / importScale) * importScale, + y: Math.floor(targetPosition.y / importScale) * importScale, + z: Math.floor(targetPosition.z / importScale) * importScale } moveImport(newPosition); } @@ -1398,7 +1398,7 @@ function wheelEvent(event) { calcThumbFromScale(pointerVoxelScale); trackMouseEvent(event); wheelPixelsMoved = 0; - + if (isImporting) { var importScale = (pointerVoxelScale / MAX_VOXEL_SCALE) * MAX_PASTE_VOXEL_SCALE; rescaleImport(importScale); From dcccd66c51776e4876a10eff7ce79d3b8aa19147 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 16 Apr 2014 17:49:35 -0700 Subject: [PATCH 464/595] Changed sound files to raw --- examples/editVoxels.js | 74 +++++++++++++++++++++--------------------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/examples/editVoxels.js b/examples/editVoxels.js index 059b4186a3..ee86d9b599 100644 --- a/examples/editVoxels.js +++ b/examples/editVoxels.js @@ -93,61 +93,61 @@ function SoundArray() { } var addVoxelSound = new SoundArray(); -addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+1.wav"); -addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+2.wav"); -addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+3.wav"); -addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+4.wav"); -addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+5.wav"); -addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+6.wav"); +addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+1.raw"); +addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+2.raw"); +addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+3.raw"); +addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+4.raw"); +addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+5.raw"); +addVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Add/VA+6.raw"); var delVoxelSound = new SoundArray(); -delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+A1.wav"); -delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+A2.wav"); -delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+A3.wav"); -delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+B1.wav"); -delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+B2.wav"); -delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+B3.wav"); +delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+A1.raw"); +delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+A2.raw"); +delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+A3.raw"); +delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+B1.raw"); +delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+B2.raw"); +delVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Del/VD+B3.raw"); var resizeVoxelSound = new SoundArray(); -resizeVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Size/V+Size+Minus.wav"); -resizeVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Size/V+Size+Plus.wav"); +resizeVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Size/V+Size+Minus.raw"); +resizeVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Voxel+Size/V+Size+Plus.raw"); var voxelSizeMinus = 0; var voxelSizePlus = 1; var swatchesSound = new SoundArray(); -swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+1.wav"); -swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+2.wav"); -swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+3.wav"); -swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+4.wav"); -swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+5.wav"); -swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+6.wav"); -swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+7.wav"); -swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+8.wav"); -swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+9.wav"); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+1.raw"); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+2.raw"); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+3.raw"); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+4.raw"); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+5.raw"); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+6.raw"); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+7.raw"); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+8.raw"); +swatchesSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Swatches/Swatch+9.raw"); var undoSound = new SoundArray(); -undoSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Undo/Undo+1.wav"); -undoSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Undo/Undo+2.wav"); -undoSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Undo/Undo+3.wav"); +undoSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Undo/Undo+1.raw"); +undoSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Undo/Undo+2.raw"); +undoSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Undo/Undo+3.raw"); var scriptInitSound = new SoundArray(); -scriptInitSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Script+Init/Script+Init+A.wav"); -scriptInitSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Script+Init/Script+Init+B.wav"); -scriptInitSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Script+Init/Script+Init+C.wav"); -scriptInitSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Script+Init/Script+Init+D.wav"); +scriptInitSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Script+Init/Script+Init+A.raw"); +scriptInitSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Script+Init/Script+Init+B.raw"); +scriptInitSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Script+Init/Script+Init+C.raw"); +scriptInitSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Script+Init/Script+Init+D.raw"); var modeSwitchSound = new SoundArray(); -modeSwitchSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Mode+Switch/Mode+1.wav"); -modeSwitchSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Mode+Switch/Mode+2.wav"); -modeSwitchSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Mode+Switch/Mode+3.wav"); +modeSwitchSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Mode+Switch/Mode+1.raw"); +modeSwitchSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Mode+Switch/Mode+2.raw"); +modeSwitchSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Mode+Switch/Mode+3.raw"); var initialVoxelSound = new SoundArray(); -initialVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Initial+Voxel/Initial+V.wav"); +initialVoxelSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Initial+Voxel/Initial+V.raw"); var colorInheritSound = new SoundArray(); -colorInheritSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Color+Inherit/Inherit+A.wav"); -colorInheritSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Color+Inherit/Inherit+B.wav"); -colorInheritSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Color+Inherit/Inherit+C.wav"); +colorInheritSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Color+Inherit/Inherit+A.raw"); +colorInheritSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Color+Inherit/Inherit+B.raw"); +colorInheritSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Color+Inherit/Inherit+C.raw"); var editToolsOn = true; // starts out off From 0f69bbe23fd5f80cdb7da7db2aec7713b203d7df Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Wed, 16 Apr 2014 20:39:55 -0700 Subject: [PATCH 465/595] More work on animation loading. --- assignment-client/src/Agent.cpp | 11 +++++- examples/crazylegs.js | 14 -------- examples/dancing_bot.js | 35 +++++++++++++++++++ libraries/avatars/src/AvatarData.h | 2 ++ libraries/fbx/src/FBXReader.cpp | 5 ++- .../script-engine/src/AnimationCache.cpp | 6 ++++ libraries/script-engine/src/AnimationCache.h | 2 ++ libraries/script-engine/src/ScriptEngine.cpp | 6 ++-- 8 files changed, 61 insertions(+), 20 deletions(-) create mode 100644 examples/dancing_bot.js diff --git a/assignment-client/src/Agent.cpp b/assignment-client/src/Agent.cpp index f48c4b9401..f4f6e3e37e 100644 --- a/assignment-client/src/Agent.cpp +++ b/assignment-client/src/Agent.cpp @@ -11,8 +11,10 @@ #include #include +#include #include #include +#include #include #include @@ -20,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -152,8 +155,13 @@ void Agent::run() { scriptURLString = scriptURLString.arg(NodeList::getInstance()->getDomainHandler().getIP().toString(), uuidStringWithoutCurlyBraces(_uuid)); + QString cachePath = QStandardPaths::writableLocation(QStandardPaths::DataLocation); + QNetworkAccessManager *networkManager = new QNetworkAccessManager(this); QNetworkReply *reply = networkManager->get(QNetworkRequest(QUrl(scriptURLString))); + QNetworkDiskCache* cache = new QNetworkDiskCache(networkManager); + cache->setCacheDirectory(!cachePath.isEmpty() ? cachePath : "agentCache"); + networkManager->setCache(cache); qDebug() << "Downloading script at" << scriptURLString; @@ -162,8 +170,9 @@ void Agent::run() { loop.exec(); - // let the AvatarData class use our QNetworkAcessManager + // let the AvatarData and ResourceCache classes use our QNetworkAccessManager AvatarData::setNetworkAccessManager(networkManager); + ResourceCache::setNetworkAccessManager(networkManager); QString scriptContents(reply->readAll()); diff --git a/examples/crazylegs.js b/examples/crazylegs.js index 3554def63a..6311aea6e4 100644 --- a/examples/crazylegs.js +++ b/examples/crazylegs.js @@ -22,8 +22,6 @@ for (var i = 0; i < jointList.length; i++) { } print("# Joint list end"); -var foo = AnimationCache.getAnimation("http://www.fungibleinsight.com/faces/hip_hop_dancing_2.fbx"); - Script.update.connect(function(deltaTime) { cumulativeTime += deltaTime; MyAvatar.setJointData("joint_R_hip", Quat.fromPitchYawRollDegrees(0.0, 0.0, AMPLITUDE * Math.sin(cumulativeTime * FREQUENCY))); @@ -32,18 +30,6 @@ Script.update.connect(function(deltaTime) { AMPLITUDE * (1.0 + Math.sin(cumulativeTime * FREQUENCY)))); MyAvatar.setJointData("joint_L_knee", Quat.fromPitchYawRollDegrees(0.0, 0.0, AMPLITUDE * (1.0 - Math.sin(cumulativeTime * FREQUENCY)))); - - if (foo.jointNames.length > 0) { - print(foo.jointNames); - print(foo.frames.length); - if (foo.frames.length > 0) { - print(foo.frames[0].rotations.length); - if (foo.frames[0].rotations.length > 0) { - var rot = foo.frames[0].rotations[0]; - print(rot.x + " " + rot.y + " " + rot.z + " " + rot.w); - } - } - } }); Script.scriptEnding.connect(function() { diff --git a/examples/dancing_bot.js b/examples/dancing_bot.js new file mode 100644 index 0000000000..91d1cd3f57 --- /dev/null +++ b/examples/dancing_bot.js @@ -0,0 +1,35 @@ +// +// dancing_bot.js +// examples +// +// Created by Andrzej Kapolka on 4/16/14. +// Copyright 2014 High Fidelity, Inc. +// +// This is an example script that demonstrates an NPC avatar running an FBX animation loop. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +var animation = AnimationCache.getAnimation("http://www.fungibleinsight.com/faces/hip_hop_dancing_2.fbx"); + +Avatar.skeletonModelURL = "http://www.fungibleinsight.com/faces/vincent.fst"; + +Agent.isAvatar = true; + +var jointMapping; + +Script.update.connect(function(deltaTime) { + if (!jointMapping) { + var avatarJointNames = Avatar.jointNames; + var animationJointNames = animation.jointNames; + if (avatarJointNames === 0 || animationJointNames.length === 0) { + return; + } + print(avatarJointNames); + print(animationJointNames); + jointMapping = { }; + } +}); + + diff --git a/libraries/avatars/src/AvatarData.h b/libraries/avatars/src/AvatarData.h index 0ac12649cf..947fbc41d4 100755 --- a/libraries/avatars/src/AvatarData.h +++ b/libraries/avatars/src/AvatarData.h @@ -99,6 +99,8 @@ class AvatarData : public QObject { Q_PROPERTY(QString skeletonModelURL READ getSkeletonModelURLFromScript WRITE setSkeletonModelURLFromScript) Q_PROPERTY(QString billboardURL READ getBillboardURL WRITE setBillboardFromURL) + Q_PROPERTY(QStringList jointNames READ getJointNames) + Q_PROPERTY(QUuid sessionUUID READ getSessionUUID); public: AvatarData(); diff --git a/libraries/fbx/src/FBXReader.cpp b/libraries/fbx/src/FBXReader.cpp index 5fad95be3d..bb862ad918 100644 --- a/libraries/fbx/src/FBXReader.cpp +++ b/libraries/fbx/src/FBXReader.cpp @@ -508,8 +508,7 @@ glm::vec3 parseVec3(const QString& string) { QString processID(const QString& id) { // Blender (at least) prepends a type to the ID, so strip it out - int index = id.indexOf("::"); - return (index == -1) ? id : id.mid(index + 2); + return id.mid(id.lastIndexOf(':') + 1); } QString getID(const QVariantList& properties, int index = 0) { @@ -1014,7 +1013,7 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) QString name; if (object.properties.size() == 3) { name = object.properties.at(1).toString(); - name = name.left(name.indexOf(QChar('\0'))); + name = processID(name.left(name.indexOf(QChar('\0')))); } else { name = getID(object.properties); diff --git a/libraries/script-engine/src/AnimationCache.cpp b/libraries/script-engine/src/AnimationCache.cpp index 078dc382c4..570de7ed10 100644 --- a/libraries/script-engine/src/AnimationCache.cpp +++ b/libraries/script-engine/src/AnimationCache.cpp @@ -17,8 +17,14 @@ static int animationPointerMetaTypeId = qRegisterMetaType(); +AnimationCache::AnimationCache(QObject* parent) : + ResourceCache(parent) { +} + AnimationPointer AnimationCache::getAnimation(const QUrl& url) { if (QThread::currentThread() != thread()) { + qDebug() << "blocking call!"; + AnimationPointer result; QMetaObject::invokeMethod(this, "getAnimation", Qt::BlockingQueuedConnection, Q_RETURN_ARG(AnimationPointer, result), Q_ARG(const QUrl&, url)); diff --git a/libraries/script-engine/src/AnimationCache.h b/libraries/script-engine/src/AnimationCache.h index a382ef40d7..38fabad57f 100644 --- a/libraries/script-engine/src/AnimationCache.h +++ b/libraries/script-engine/src/AnimationCache.h @@ -30,6 +30,8 @@ class AnimationCache : public ResourceCache { public: + AnimationCache(QObject* parent = NULL); + Q_INVOKABLE AnimationPointer getAnimation(const QString& url) { return getAnimation(QUrl(url)); } Q_INVOKABLE AnimationPointer getAnimation(const QUrl& url); diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index 60321e7c54..4dee35c6a5 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -64,7 +64,8 @@ ScriptEngine::ScriptEngine(const QString& scriptContents, const QString& fileNam _fileNameString(fileNameString), _quatLibrary(), _vec3Library(), - _uuidLibrary() + _uuidLibrary(), + _animationCache(this) { } @@ -88,7 +89,8 @@ ScriptEngine::ScriptEngine(const QUrl& scriptURL, _fileNameString(), _quatLibrary(), _vec3Library(), - _uuidLibrary() + _uuidLibrary(), + _animationCache(this) { QString scriptURLString = scriptURL.toString(); _fileNameString = scriptURLString; From 00829e028982d83b0c7cf3ca873d0b6c3e062fc4 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Wed, 16 Apr 2014 21:10:59 -0700 Subject: [PATCH 466/595] The actual animation business. --- examples/dancing_bot.js | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/examples/dancing_bot.js b/examples/dancing_bot.js index 91d1cd3f57..de4f8224c3 100644 --- a/examples/dancing_bot.js +++ b/examples/dancing_bot.js @@ -19,6 +19,10 @@ Agent.isAvatar = true; var jointMapping; +var frameIndex = 0.0; + +var FRAME_RATE = 30.0; // frames per second + Script.update.connect(function(deltaTime) { if (!jointMapping) { var avatarJointNames = Avatar.jointNames; @@ -26,9 +30,19 @@ Script.update.connect(function(deltaTime) { if (avatarJointNames === 0 || animationJointNames.length === 0) { return; } - print(avatarJointNames); - print(animationJointNames); - jointMapping = { }; + jointMapping = new Array(avatarJointNames.length); + for (var i = 0; i < avatarJointNames.length; i++) { + jointMapping[i] = animationJointNames.indexOf(avatarJointNames[i]); + } + } + frameIndex += deltaTime * FRAME_RATE; + var frames = animation.frames; + var rotations = frames[Math.floor(frameIndex) % frames.length].rotations; + for (var j = 0; j < jointMapping.length; j++) { + var rotationIndex = jointMapping[j]; + if (rotationIndex != -1) { + Avatar.setJointData(j, rotations[rotationIndex]); + } } }); From e139a6dc95492ca6b4388a4b86a620d39cec3c85 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Thu, 17 Apr 2014 08:46:41 -0700 Subject: [PATCH 467/595] remove warnings about signed-unsigned comparison --- interface/src/Audio.cpp | 4 ++-- interface/src/AudioReflector.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 674eaa0d70..daa7c036eb 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -529,7 +529,7 @@ void Audio::handleAudioInput() { _noiseSampleFrames[_noiseGateSampleCounter++] = _lastInputLoudness; if (_noiseGateSampleCounter == NUMBER_OF_NOISE_SAMPLE_FRAMES) { float smallestSample = FLT_MAX; - for (int i = 0; i <= NUMBER_OF_NOISE_SAMPLE_FRAMES - NOISE_GATE_FRAMES_TO_AVERAGE; i+= NOISE_GATE_FRAMES_TO_AVERAGE) { + for (int i = 0; i <= NUMBER_OF_NOISE_SAMPLE_FRAMES - NOISE_GATE_FRAMES_TO_AVERAGE; i += NOISE_GATE_FRAMES_TO_AVERAGE) { float thisAverage = 0.0f; for (int j = i; j < i + NOISE_GATE_FRAMES_TO_AVERAGE; j++) { thisAverage += _noiseSampleFrames[j]; @@ -706,7 +706,7 @@ void Audio::addSpatialAudioToBuffer(unsigned int sampleTime, const QByteArray& s mixedSamplesCount = (mixedSamplesCount < numSamples) ? mixedSamplesCount : numSamples; const int16_t* spatial = reinterpret_cast(spatialAudio.data()); - for (int i = 0; i < mixedSamplesCount; i++) { + for (unsigned int i = 0; i < mixedSamplesCount; i++) { int existingSample = _spatialAudioRingBuffer[i + offset]; int newSample = spatial[i]; int sumOfSamples = existingSample + newSample; diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 9e4b97bf46..52558f1d59 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -540,7 +540,7 @@ int AudioReflector::analyzePathsSingleStep() { QVector* pathsLists[] = { &_inboundAudioPaths, &_localAudioPaths }; - for(int i = 0; i < sizeof(pathsLists) / sizeof(pathsLists[0]); i ++) { + for(unsigned int i = 0; i < sizeof(pathsLists) / sizeof(pathsLists[0]); i++) { QVector& pathList = *pathsLists[i]; From 142932bed02561554081faca83188a9dcb1deaa9 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 17 Apr 2014 10:14:11 -0700 Subject: [PATCH 468/595] allow passing of scripted assignments to DS via parameters --- domain-server/src/DomainServer.cpp | 55 +++++++++++++++++++++++++++--- domain-server/src/DomainServer.h | 1 + 2 files changed, 51 insertions(+), 5 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 969b83f64f..9dbb1e478e 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -187,7 +187,7 @@ void DomainServer::setupNodeListAndAssignments(const QUuid& sessionUUID) { } } - QSet parsedTypes(QSet() << Assignment::AgentType); + QSet parsedTypes; parseAssignmentConfigs(parsedTypes); populateDefaultStaticAssignmentsExcludingTypes(parsedTypes); @@ -222,12 +222,19 @@ void DomainServer::parseAssignmentConfigs(QSet& excludedTypes) if (assignmentType < Assignment::AllTypes && !excludedTypes.contains(assignmentType)) { QVariant mapValue = _argumentVariantMap[variantMapKeys[configIndex]]; + QJsonArray assignmentArray; if (mapValue.type() == QVariant::String) { QJsonDocument deserializedDocument = QJsonDocument::fromJson(mapValue.toString().toUtf8()); - createStaticAssignmentsForType(assignmentType, deserializedDocument.array()); + assignmentArray = deserializedDocument.array(); } else { - createStaticAssignmentsForType(assignmentType, mapValue.toJsonValue().toArray()); + assignmentArray = mapValue.toJsonValue().toArray(); + } + + if (assignmentType != Assignment::AgentType) { + createStaticAssignmentsForType(assignmentType, assignmentArray); + } else { + createScriptedAssignmentsFromArray(assignmentArray); } excludedTypes.insert(assignmentType); @@ -242,6 +249,42 @@ void DomainServer::addStaticAssignmentToAssignmentHash(Assignment* newAssignment _staticAssignmentHash.insert(newAssignment->getUUID(), SharedAssignmentPointer(newAssignment)); } +void DomainServer::createScriptedAssignmentsFromArray(const QJsonArray &configArray) { + foreach(const QJsonValue& jsonValue, configArray) { + if (jsonValue.isObject()) { + QJsonObject jsonObject = jsonValue.toObject(); + + // make sure we were passed a URL, otherwise this is an invalid scripted assignment + const QString ASSIGNMENT_URL_KEY = "url"; + QString assignmentURL = jsonObject[ASSIGNMENT_URL_KEY].toString(); + + if (!assignmentURL.isEmpty()) { + // check the json for a pool + const QString ASSIGNMENT_POOL_KEY = "pool"; + QString assignmentPool = jsonObject[ASSIGNMENT_POOL_KEY].toString(); + + // check for a number of instances, if not passed then default is 1 + const QString ASSIGNMENT_INSTANCES_KEY = "instances"; + int numInstances = jsonObject[ASSIGNMENT_INSTANCES_KEY].toInt(); + numInstances = (numInstances == 0 ? 1 : numInstances); + + for (int i = 0; i < numInstances; i++) { + // add a scripted assignment to the queue for this instance + Assignment* scriptAssignment = new Assignment(Assignment::CreateCommand, + Assignment::AgentType, + assignmentPool); + scriptAssignment->setPayload(assignmentURL.toUtf8()); + + qDebug() << "Adding scripted assignment to queue -" << *scriptAssignment; + qDebug() << "URL for script is" << assignmentURL; + + _assignmentQueue.enqueue(SharedAssignmentPointer(scriptAssignment)); + } + } + } + } +} + void DomainServer::createStaticAssignmentsForType(Assignment::Type type, const QJsonArray& configArray) { // we have a string for config for this type qDebug() << "Parsing config for assignment type" << type; @@ -284,8 +327,10 @@ void DomainServer::createStaticAssignmentsForType(Assignment::Type type, const Q void DomainServer::populateDefaultStaticAssignmentsExcludingTypes(const QSet& excludedTypes) { // enumerate over all assignment types and see if we've already excluded it - for (int defaultedType = Assignment::AudioMixerType; defaultedType != Assignment::AllTypes; defaultedType++) { - if (!excludedTypes.contains((Assignment::Type) defaultedType)) { + for (Assignment::Type defaultedType = Assignment::AudioMixerType; + defaultedType != Assignment::AllTypes; + defaultedType = static_cast(static_cast(defaultedType) + 1)) { + if (!excludedTypes.contains(defaultedType) && defaultedType != Assignment::AgentType) { // type has not been set from a command line or config file config, use the default // by clearing whatever exists and writing a single default assignment with no payload Assignment* newAssignment = new Assignment(Assignment::CreateCommand, (Assignment::Type) defaultedType); diff --git a/domain-server/src/DomainServer.h b/domain-server/src/DomainServer.h index 0153fac49d..9bd10b8c60 100644 --- a/domain-server/src/DomainServer.h +++ b/domain-server/src/DomainServer.h @@ -66,6 +66,7 @@ private: void parseAssignmentConfigs(QSet& excludedTypes); void addStaticAssignmentToAssignmentHash(Assignment* newAssignment); + void createScriptedAssignmentsFromArray(const QJsonArray& configArray); void createStaticAssignmentsForType(Assignment::Type type, const QJsonArray& configArray); void populateDefaultStaticAssignmentsExcludingTypes(const QSet& excludedTypes); From a137dd03623969ff6346e8014fe253acc95db77e Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 17 Apr 2014 10:18:42 -0700 Subject: [PATCH 469/595] grab URL for script from payload if it exists --- assignment-client/src/Agent.cpp | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/assignment-client/src/Agent.cpp b/assignment-client/src/Agent.cpp index f48c4b9401..4163991a75 100644 --- a/assignment-client/src/Agent.cpp +++ b/assignment-client/src/Agent.cpp @@ -148,14 +148,19 @@ void Agent::run() { << NodeType::ParticleServer); // figure out the URL for the script for this agent assignment - QString scriptURLString("http://%1:8080/assignment/%2"); - scriptURLString = scriptURLString.arg(NodeList::getInstance()->getDomainHandler().getIP().toString(), - uuidStringWithoutCurlyBraces(_uuid)); - + QUrl scriptURL; + if (_payload.isEmpty()) { + scriptURL = QUrl(QString("http://%1:8080/assignment/%2") + .arg(NodeList::getInstance()->getDomainHandler().getIP().toString(), + uuidStringWithoutCurlyBraces(_uuid))); + } else { + scriptURL = QUrl(_payload); + } + QNetworkAccessManager *networkManager = new QNetworkAccessManager(this); - QNetworkReply *reply = networkManager->get(QNetworkRequest(QUrl(scriptURLString))); + QNetworkReply *reply = networkManager->get(QNetworkRequest(scriptURL)); - qDebug() << "Downloading script at" << scriptURLString; + qDebug() << "Downloading script at" << scriptURL.toString(); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); From 03c3952e525e87cf3793a2734b25add87924e4a9 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 17 Apr 2014 10:41:46 -0700 Subject: [PATCH 470/595] Better joint mappings, switch to working (more or less) model. --- examples/crazylegs.js | 6 +++--- examples/dancing_bot.js | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/crazylegs.js b/examples/crazylegs.js index 6311aea6e4..b0f8e937bc 100644 --- a/examples/crazylegs.js +++ b/examples/crazylegs.js @@ -15,12 +15,12 @@ var AMPLITUDE = 45.0; var cumulativeTime = 0.0; -print("# Joint list start"); var jointList = MyAvatar.getJointNames(); +var jointMappings = "\n# Joint list start"; for (var i = 0; i < jointList.length; i++) { - print("jointIndex = " + jointList[i] + " = " + i); + jointMappings = jointMappings + "\njointIndex = " + jointList[i] + " = " + i; } -print("# Joint list end"); +print(jointMappings + "\n# Joint list end"); Script.update.connect(function(deltaTime) { cumulativeTime += deltaTime; diff --git a/examples/dancing_bot.js b/examples/dancing_bot.js index de4f8224c3..b86047d2de 100644 --- a/examples/dancing_bot.js +++ b/examples/dancing_bot.js @@ -13,7 +13,7 @@ var animation = AnimationCache.getAnimation("http://www.fungibleinsight.com/faces/hip_hop_dancing_2.fbx"); -Avatar.skeletonModelURL = "http://www.fungibleinsight.com/faces/vincent.fst"; +Avatar.skeletonModelURL = "http://www.fungibleinsight.com/faces/beta.fst"; Agent.isAvatar = true; From a6136b42ff193bf854c5f16849a5fb8538946763 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 17 Apr 2014 10:55:11 -0700 Subject: [PATCH 471/595] Switch to a working (and more amusing) animation. --- examples/dancing_bot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/dancing_bot.js b/examples/dancing_bot.js index b86047d2de..3572cc5a11 100644 --- a/examples/dancing_bot.js +++ b/examples/dancing_bot.js @@ -11,7 +11,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -var animation = AnimationCache.getAnimation("http://www.fungibleinsight.com/faces/hip_hop_dancing_2.fbx"); +var animation = AnimationCache.getAnimation("http://www.fungibleinsight.com/faces/gangnam_style_2.fbx"); Avatar.skeletonModelURL = "http://www.fungibleinsight.com/faces/beta.fst"; From 197ce036c4cf48aaf3c8a2f3dd04bd5de2f54af5 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 17 Apr 2014 11:06:28 -0700 Subject: [PATCH 472/595] Remove debugging line. --- libraries/script-engine/src/AnimationCache.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/libraries/script-engine/src/AnimationCache.cpp b/libraries/script-engine/src/AnimationCache.cpp index 570de7ed10..defcce525e 100644 --- a/libraries/script-engine/src/AnimationCache.cpp +++ b/libraries/script-engine/src/AnimationCache.cpp @@ -23,8 +23,6 @@ AnimationCache::AnimationCache(QObject* parent) : AnimationPointer AnimationCache::getAnimation(const QUrl& url) { if (QThread::currentThread() != thread()) { - qDebug() << "blocking call!"; - AnimationPointer result; QMetaObject::invokeMethod(this, "getAnimation", Qt::BlockingQueuedConnection, Q_RETURN_ARG(AnimationPointer, result), Q_ARG(const QUrl&, url)); From 58b063ee1275feb72e55429ed28534e23973abb8 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 17 Apr 2014 11:13:22 -0700 Subject: [PATCH 473/595] Make sure we call allReferencesCleared on the right thread. --- libraries/shared/src/ResourceCache.cpp | 5 +++++ libraries/shared/src/ResourceCache.h | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/libraries/shared/src/ResourceCache.cpp b/libraries/shared/src/ResourceCache.cpp index 30a725c010..04b6265513 100644 --- a/libraries/shared/src/ResourceCache.cpp +++ b/libraries/shared/src/ResourceCache.cpp @@ -12,6 +12,7 @@ #include #include +#include #include #include @@ -174,6 +175,10 @@ float Resource::getLoadPriority() { } void Resource::allReferencesCleared() { + if (QThread::currentThread() != thread()) { + QMetaObject::invokeMethod(this, "allReferencesCleared"); + return; + } if (_cache) { // create and reinsert new shared pointer QSharedPointer self(this, &Resource::allReferencesCleared); diff --git a/libraries/shared/src/ResourceCache.h b/libraries/shared/src/ResourceCache.h index da217516e1..0cfabd26fc 100644 --- a/libraries/shared/src/ResourceCache.h +++ b/libraries/shared/src/ResourceCache.h @@ -123,7 +123,7 @@ public: void setCache(ResourceCache* cache) { _cache = cache; } - void allReferencesCleared(); + Q_INVOKABLE void allReferencesCleared(); protected slots: From a12b90c65becd64ca9d78cf75ac123b6c49abf5b Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 17 Apr 2014 13:34:37 -0700 Subject: [PATCH 474/595] Add head translation to Faceplus. Closes #2684. --- interface/src/Application.cpp | 1 + interface/src/devices/Faceplus.cpp | 44 ++++++++++++++++++++++++------ interface/src/devices/Faceplus.h | 14 +++++++--- 3 files changed, 47 insertions(+), 12 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index bd7a82b439..978e457ae9 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3020,6 +3020,7 @@ void Application::resetSensors() { _mouseX = _glWidget->width() / 2; _mouseY = _glWidget->height() / 2; + _faceplus.reset(); _faceshift.reset(); _visage.reset(); diff --git a/interface/src/devices/Faceplus.cpp b/interface/src/devices/Faceplus.cpp index f7f2f1f1bd..f06433b663 100644 --- a/interface/src/devices/Faceplus.cpp +++ b/interface/src/devices/Faceplus.cpp @@ -40,9 +40,16 @@ void Faceplus::init() { updateEnabled(); } -void Faceplus::setState(const glm::quat& headRotation, float estimatedEyePitch, float estimatedEyeYaw, - const QVector& blendshapeCoefficients) { - _headRotation = headRotation; +void Faceplus::reset() { + if (_enabled) { + QMetaObject::invokeMethod(_reader, "reset"); + } +} + +void Faceplus::setState(const glm::vec3& headTranslation, const glm::quat& headRotation, + float estimatedEyePitch, float estimatedEyeYaw, const QVector& blendshapeCoefficients) { + _headTranslation = headTranslation; + _headRotation = headRotation; _estimatedEyePitch = estimatedEyePitch; _estimatedEyeYaw = estimatedEyeYaw; _blendshapeCoefficients = blendshapeCoefficients; @@ -149,7 +156,7 @@ FaceplusReader::~FaceplusReader() { void FaceplusReader::init() { #ifdef HAVE_FACEPLUS - if (!faceplus_init("VGA")) { + if (!faceplus_init("hHD")) { qDebug() << "Failed to initialized Faceplus."; return; } @@ -190,7 +197,8 @@ void FaceplusReader::init() { } } _blendshapeCoefficients.resize(maxIndex + 1); - + _referenceInitialized = false; + QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection); #endif } @@ -202,10 +210,24 @@ void FaceplusReader::shutdown() { void FaceplusReader::update() { #ifdef HAVE_FACEPLUS - if (!(faceplus_synchronous_track() && faceplus_current_output_vector(_outputVector.data()))) { + float x, y, rotation, scale; + if (!(faceplus_synchronous_track() && faceplus_current_face_location(&x, &y, &rotation, &scale) && !glm::isnan(x) && + faceplus_current_output_vector(_outputVector.data()))) { QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection); return; } + if (!_referenceInitialized) { + _referenceX = x; + _referenceY = y; + _referenceScale = scale; + _referenceInitialized = true; + } + const float TRANSLATION_SCALE = 10.0f; + const float REFERENCE_DISTANCE = 10.0f; + float depthScale = _referenceScale / scale; + float z = REFERENCE_DISTANCE * (depthScale - 1.0f); + glm::vec3 headTranslation((x - _referenceX) * depthScale * TRANSLATION_SCALE, + (y - _referenceY) * depthScale * TRANSLATION_SCALE, z); glm::quat headRotation(glm::radians(glm::vec3(-_outputVector.at(_headRotationIndices[0]), _outputVector.at(_headRotationIndices[1]), -_outputVector.at(_headRotationIndices[2])))); float estimatedEyePitch = (_outputVector.at(_leftEyeRotationIndices[0]) + @@ -221,10 +243,16 @@ void FaceplusReader::update() { } } - QMetaObject::invokeMethod(Application::getInstance()->getFaceplus(), "setState", Q_ARG(const glm::quat&, headRotation), - Q_ARG(float, estimatedEyePitch), Q_ARG(float, estimatedEyeYaw), Q_ARG(const QVector&, _blendshapeCoefficients)); + QMetaObject::invokeMethod(Application::getInstance()->getFaceplus(), "setState", Q_ARG(const glm::vec3&, headTranslation), + Q_ARG(const glm::quat&, headRotation), Q_ARG(float, estimatedEyePitch), Q_ARG(float, estimatedEyeYaw), + Q_ARG(const QVector&, _blendshapeCoefficients)); QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection); #endif } +void FaceplusReader::reset() { +#ifdef HAVE_FACEPLUS + _referenceInitialized = false; +#endif +} diff --git a/interface/src/devices/Faceplus.h b/interface/src/devices/Faceplus.h index 2b9219f3fd..f819dadca3 100644 --- a/interface/src/devices/Faceplus.h +++ b/interface/src/devices/Faceplus.h @@ -30,11 +30,12 @@ public: virtual ~Faceplus(); void init(); - + void reset(); + bool isActive() const { return _active; } - Q_INVOKABLE void setState(const glm::quat& headRotation, float estimatedEyePitch, float estimatedEyeYaw, - const QVector& blendshapeCoefficients); + Q_INVOKABLE void setState(const glm::vec3& headTranslation, const glm::quat& headRotation, + float estimatedEyePitch, float estimatedEyeYaw, const QVector& blendshapeCoefficients); public slots: @@ -63,6 +64,7 @@ public: Q_INVOKABLE void init(); Q_INVOKABLE void shutdown(); Q_INVOKABLE void update(); + Q_INVOKABLE void reset(); private: @@ -72,7 +74,11 @@ private: int _headRotationIndices[3]; int _leftEyeRotationIndices[2]; int _rightEyeRotationIndices[2]; - QVector _blendshapeCoefficients; + float _referenceX; + float _referenceY; + float _referenceScale; + bool _referenceInitialized; + QVector _blendshapeCoefficients; #endif }; From 0a2670ea23b60de1749d94f7715a84c4867a70a5 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 17 Apr 2014 13:42:29 -0700 Subject: [PATCH 475/595] Detabbed. --- interface/src/Application.cpp | 2 +- interface/src/devices/Faceplus.cpp | 44 +++++++++++++++--------------- interface/src/devices/Faceplus.h | 12 ++++---- 3 files changed, 29 insertions(+), 29 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 978e457ae9..119fd72f17 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3020,7 +3020,7 @@ void Application::resetSensors() { _mouseX = _glWidget->width() / 2; _mouseY = _glWidget->height() / 2; - _faceplus.reset(); + _faceplus.reset(); _faceshift.reset(); _visage.reset(); diff --git a/interface/src/devices/Faceplus.cpp b/interface/src/devices/Faceplus.cpp index f06433b663..a5601932b6 100644 --- a/interface/src/devices/Faceplus.cpp +++ b/interface/src/devices/Faceplus.cpp @@ -41,15 +41,15 @@ void Faceplus::init() { } void Faceplus::reset() { - if (_enabled) { - QMetaObject::invokeMethod(_reader, "reset"); - } + if (_enabled) { + QMetaObject::invokeMethod(_reader, "reset"); + } } void Faceplus::setState(const glm::vec3& headTranslation, const glm::quat& headRotation, - float estimatedEyePitch, float estimatedEyeYaw, const QVector& blendshapeCoefficients) { + float estimatedEyePitch, float estimatedEyeYaw, const QVector& blendshapeCoefficients) { _headTranslation = headTranslation; - _headRotation = headRotation; + _headRotation = headRotation; _estimatedEyePitch = estimatedEyePitch; _estimatedEyeYaw = estimatedEyeYaw; _blendshapeCoefficients = blendshapeCoefficients; @@ -211,23 +211,23 @@ void FaceplusReader::shutdown() { void FaceplusReader::update() { #ifdef HAVE_FACEPLUS float x, y, rotation, scale; - if (!(faceplus_synchronous_track() && faceplus_current_face_location(&x, &y, &rotation, &scale) && !glm::isnan(x) && - faceplus_current_output_vector(_outputVector.data()))) { + if (!(faceplus_synchronous_track() && faceplus_current_face_location(&x, &y, &rotation, &scale) && !glm::isnan(x) && + faceplus_current_output_vector(_outputVector.data()))) { QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection); return; } - if (!_referenceInitialized) { - _referenceX = x; - _referenceY = y; - _referenceScale = scale; - _referenceInitialized = true; - } - const float TRANSLATION_SCALE = 10.0f; - const float REFERENCE_DISTANCE = 10.0f; - float depthScale = _referenceScale / scale; - float z = REFERENCE_DISTANCE * (depthScale - 1.0f); - glm::vec3 headTranslation((x - _referenceX) * depthScale * TRANSLATION_SCALE, - (y - _referenceY) * depthScale * TRANSLATION_SCALE, z); + if (!_referenceInitialized) { + _referenceX = x; + _referenceY = y; + _referenceScale = scale; + _referenceInitialized = true; + } + const float TRANSLATION_SCALE = 10.0f; + const float REFERENCE_DISTANCE = 10.0f; + float depthScale = _referenceScale / scale; + float z = REFERENCE_DISTANCE * (depthScale - 1.0f); + glm::vec3 headTranslation((x - _referenceX) * depthScale * TRANSLATION_SCALE, + (y - _referenceY) * depthScale * TRANSLATION_SCALE, z); glm::quat headRotation(glm::radians(glm::vec3(-_outputVector.at(_headRotationIndices[0]), _outputVector.at(_headRotationIndices[1]), -_outputVector.at(_headRotationIndices[2])))); float estimatedEyePitch = (_outputVector.at(_leftEyeRotationIndices[0]) + @@ -244,8 +244,8 @@ void FaceplusReader::update() { } QMetaObject::invokeMethod(Application::getInstance()->getFaceplus(), "setState", Q_ARG(const glm::vec3&, headTranslation), - Q_ARG(const glm::quat&, headRotation), Q_ARG(float, estimatedEyePitch), Q_ARG(float, estimatedEyeYaw), - Q_ARG(const QVector&, _blendshapeCoefficients)); + Q_ARG(const glm::quat&, headRotation), Q_ARG(float, estimatedEyePitch), Q_ARG(float, estimatedEyeYaw), + Q_ARG(const QVector&, _blendshapeCoefficients)); QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection); #endif @@ -253,6 +253,6 @@ void FaceplusReader::update() { void FaceplusReader::reset() { #ifdef HAVE_FACEPLUS - _referenceInitialized = false; + _referenceInitialized = false; #endif } diff --git a/interface/src/devices/Faceplus.h b/interface/src/devices/Faceplus.h index f819dadca3..f3c680c2d6 100644 --- a/interface/src/devices/Faceplus.h +++ b/interface/src/devices/Faceplus.h @@ -35,7 +35,7 @@ public: bool isActive() const { return _active; } Q_INVOKABLE void setState(const glm::vec3& headTranslation, const glm::quat& headRotation, - float estimatedEyePitch, float estimatedEyeYaw, const QVector& blendshapeCoefficients); + float estimatedEyePitch, float estimatedEyeYaw, const QVector& blendshapeCoefficients); public slots: @@ -64,7 +64,7 @@ public: Q_INVOKABLE void init(); Q_INVOKABLE void shutdown(); Q_INVOKABLE void update(); - Q_INVOKABLE void reset(); + Q_INVOKABLE void reset(); private: @@ -75,10 +75,10 @@ private: int _leftEyeRotationIndices[2]; int _rightEyeRotationIndices[2]; float _referenceX; - float _referenceY; - float _referenceScale; - bool _referenceInitialized; - QVector _blendshapeCoefficients; + float _referenceY; + float _referenceScale; + bool _referenceInitialized; + QVector _blendshapeCoefficients; #endif }; From 6251b6b81939d4fbb32391cb39fae64a3701d79e Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 17 Apr 2014 13:55:16 -0700 Subject: [PATCH 476/595] Merge fix. --- assignment-client/src/Agent.cpp | 1 + libraries/fbx/src/FBXReader.cpp | 2 ++ 2 files changed, 3 insertions(+) diff --git a/assignment-client/src/Agent.cpp b/assignment-client/src/Agent.cpp index 2138914fe2..2e4c251005 100644 --- a/assignment-client/src/Agent.cpp +++ b/assignment-client/src/Agent.cpp @@ -163,6 +163,7 @@ void Agent::run() { QNetworkAccessManager *networkManager = new QNetworkAccessManager(this); QNetworkReply *reply = networkManager->get(QNetworkRequest(scriptURL)); QNetworkDiskCache* cache = new QNetworkDiskCache(networkManager); + QString cachePath = QStandardPaths::writableLocation(QStandardPaths::DataLocation); cache->setCacheDirectory(!cachePath.isEmpty() ? cachePath : "agentCache"); networkManager->setCache(cache); diff --git a/libraries/fbx/src/FBXReader.cpp b/libraries/fbx/src/FBXReader.cpp index bb862ad918..eae8eb3920 100644 --- a/libraries/fbx/src/FBXReader.cpp +++ b/libraries/fbx/src/FBXReader.cpp @@ -952,6 +952,8 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) QHash yComponents; QHash zComponents; + printNode(node, 0); + QVariantHash joints = mapping.value("joint").toHash(); QString jointEyeLeftName = processID(getString(joints.value("jointEyeLeft", "jointEyeLeft"))); QString jointEyeRightName = processID(getString(joints.value("jointEyeRight", "jointEyeRight"))); From 3acc518e8a3f8dcbed27f699a7471f75fa373232 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Thu, 17 Apr 2014 15:18:15 -0700 Subject: [PATCH 477/595] make float literals obey the coding standard --- interface/src/Camera.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/interface/src/Camera.cpp b/interface/src/Camera.cpp index 2ef32dac5f..f9ee5bdd25 100644 --- a/interface/src/Camera.cpp +++ b/interface/src/Camera.cpp @@ -45,7 +45,7 @@ Camera::Camera() : _idealPosition(0.0f, 0.0f, 0.0f), _targetPosition(0.0f, 0.0f, 0.0f), _fieldOfView(DEFAULT_FIELD_OF_VIEW_DEGREES), - _aspectRatio(16.f/9.f), + _aspectRatio(16.0f/9.0f), _nearClip(0.08f), // default _farClip(50.0f * TREE_SCALE), // default _upShift(0.0f), @@ -94,8 +94,8 @@ void Camera::updateFollowMode(float deltaTime) { // derive t from tightness float t = _tightness * _modeShift * deltaTime; - if (t > 1.0) { - t = 1.0; + if (t > 1.0f) { + t = 1.0f; } // handle keepLookingAt From 3072161a303e43b69847ececadb97623304e0b9c Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Thu, 17 Apr 2014 15:18:46 -0700 Subject: [PATCH 478/595] improved collision shapes of models --- interface/src/renderer/FBXReader.cpp | 21 ++++++++++++++++++--- interface/src/renderer/Model.cpp | 26 ++++++++++++++++++++------ 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/interface/src/renderer/FBXReader.cpp b/interface/src/renderer/FBXReader.cpp index 959c015eea..32b5686558 100644 --- a/interface/src/renderer/FBXReader.cpp +++ b/interface/src/renderer/FBXReader.cpp @@ -1516,7 +1516,6 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) } float radiusScale = extractUniformScale(joint.transform * fbxCluster.inverseBindMatrix); JointShapeInfo& jointShapeInfo = jointShapeInfos[jointIndex]; - jointShapeInfo.boneBegin = rotateMeshToJoint * (radiusScale * (boneBegin - boneEnd)); float totalWeight = 0.0f; for (int j = 0; j < cluster.indices.size(); j++) { @@ -1578,7 +1577,6 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) } } float radiusScale = extractUniformScale(joint.transform * firstFBXCluster.inverseBindMatrix); - jointShapeInfo.boneBegin = rotateMeshToJoint * (radiusScale * (boneBegin - boneEnd)); glm::vec3 averageVertex(0.f); foreach (const glm::vec3& vertex, extracted.mesh.vertices) { @@ -1614,6 +1612,14 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) FBXJoint& joint = geometry.joints[i]; JointShapeInfo& jointShapeInfo = jointShapeInfos[i]; + if (joint.parentIndex == -1) { + jointShapeInfo.boneBegin = glm::vec3(0.0f); + } else { + const FBXJoint& parentJoint = geometry.joints[joint.parentIndex]; + glm::quat inverseRotation = glm::inverse(extractRotation(joint.transform)); + jointShapeInfo.boneBegin = inverseRotation * (extractTranslation(parentJoint.transform) - extractTranslation(joint.transform)); + } + // we use a capsule if the joint ANY mesh vertices successfully projected onto the bone // AND its boneRadius is not too close to zero bool collideLikeCapsule = jointShapeInfo.numProjectedVertices > 0 @@ -1625,12 +1631,12 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) joint.shapeType = Shape::CAPSULE_SHAPE; } else { // collide the joint like a sphere + joint.shapeType = Shape::SPHERE_SHAPE; if (jointShapeInfo.numVertices > 0) { jointShapeInfo.averageVertex /= (float)jointShapeInfo.numVertices; joint.shapePosition = jointShapeInfo.averageVertex; } else { joint.shapePosition = glm::vec3(0.f); - joint.shapeType = Shape::SPHERE_SHAPE; } if (jointShapeInfo.numProjectedVertices == 0 && jointShapeInfo.numVertices > 0) { @@ -1639,6 +1645,15 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) jointShapeInfo.averageRadius /= (float)jointShapeInfo.numVertices; joint.boneRadius = jointShapeInfo.averageRadius; } + + float distanceFromEnd = glm::length(joint.shapePosition); + float distanceFromBegin = glm::distance(joint.shapePosition, jointShapeInfo.boneBegin); + if (distanceFromEnd > joint.distanceToParent && distanceFromBegin > joint.distanceToParent) { + // The shape is further from both joint endpoints than the endpoints are from each other + // which probably means the model has a bad transform somewhere. We disable this shape + // by setting its radius to zero. + joint.boneRadius = 0.0f; + } } } geometry.palmDirection = parseVec3(mapping.value("palmDirection", "0, -1, 0").toString()); diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 2d47a077b7..bcde861e84 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -510,24 +510,38 @@ void Model::rebuildShapes() { capsule->getEndPoint(endPoint); glm::vec3 startPoint; capsule->getStartPoint(startPoint); - glm::vec3 axis = (halfHeight + radius) * glm::normalize(endPoint - startPoint); + + // add some points that bound a sphere at the center of the capsule + glm::vec3 axis = glm::vec3(radius); shapeExtents.addPoint(worldPosition + axis); shapeExtents.addPoint(worldPosition - axis); + + // add the two furthest surface points of the capsule + axis = (halfHeight + radius) * glm::normalize(endPoint - startPoint); + shapeExtents.addPoint(worldPosition + axis); + shapeExtents.addPoint(worldPosition - axis); + + + totalExtents.addExtents(shapeExtents); } else { SphereShape* sphere = new SphereShape(radius, worldPosition); _jointShapes.push_back(sphere); - glm::vec3 axis = glm::vec3(radius); - shapeExtents.addPoint(worldPosition + axis); - shapeExtents.addPoint(worldPosition - axis); + if (radius > 0.0f) { + // only include sphere shapes with non-zero radius + glm::vec3 axis = glm::vec3(radius); + shapeExtents.addPoint(worldPosition + axis); + shapeExtents.addPoint(worldPosition - axis); + totalExtents.addExtents(shapeExtents); + } } - totalExtents.addExtents(shapeExtents); } // bounding shape // NOTE: we assume that the longest side of totalExtents is the yAxis glm::vec3 diagonal = totalExtents.maximum - totalExtents.minimum; - float capsuleRadius = 0.25f * (diagonal.x + diagonal.z); // half the average of x and z + // the radius is half the RMS of the X and Z sides: + float capsuleRadius = 0.5f * sqrtf(0.5f * (diagonal.x * diagonal.x + diagonal.z * diagonal.z)); _boundingShape.setRadius(capsuleRadius); _boundingShape.setHalfHeight(0.5f * diagonal.y - capsuleRadius); _boundingShapeLocalOffset = inverseRotation * (0.5f * (totalExtents.maximum + totalExtents.minimum) - rootPosition); From 197127fbde4d454707d45f9505e3d5726123a4ee Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 17 Apr 2014 15:42:23 -0700 Subject: [PATCH 479/595] Added ability to read FBX textures embedded in FBX files. --- interface/src/ModelUploader.cpp | 8 +-- interface/src/renderer/GeometryCache.cpp | 8 +-- interface/src/renderer/TextureCache.cpp | 66 ++++++++++++++++++------ interface/src/renderer/TextureCache.h | 13 +++-- libraries/fbx/src/FBXReader.cpp | 52 +++++++++++++------ libraries/fbx/src/FBXReader.h | 12 ++++- 6 files changed, 112 insertions(+), 47 deletions(-) diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index 5b2688169f..7f4ed0d36e 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -306,14 +306,14 @@ bool ModelUploader::addTextures(const QString& texdir, const QString fbxFile) { foreach (FBXMesh mesh, geometry.meshes) { foreach (FBXMeshPart part, mesh.parts) { - if (!part.diffuseFilename.isEmpty()) { - if (!addPart(texdir + "/" + part.diffuseFilename, + if (!part.diffuseTexture.filename.isEmpty()) { + if (!addPart(texdir + "/" + part.diffuseTexture.filename, QString("texture%1").arg(++_texturesCount))) { return false; } } - if (!part.normalFilename.isEmpty()) { - if (!addPart(texdir + "/" + part.normalFilename, + if (!part.normalTexture.filename.isEmpty()) { + if (!addPart(texdir + "/" + part.normalTexture.filename, QString("texture%1").arg(++_texturesCount))) { return false; } diff --git a/interface/src/renderer/GeometryCache.cpp b/interface/src/renderer/GeometryCache.cpp index 7b4eef1ac1..3a410ac5e2 100644 --- a/interface/src/renderer/GeometryCache.cpp +++ b/interface/src/renderer/GeometryCache.cpp @@ -543,14 +543,14 @@ void NetworkGeometry::setGeometry(const FBXGeometry& geometry) { int totalIndices = 0; foreach (const FBXMeshPart& part, mesh.parts) { NetworkMeshPart networkPart; - if (!part.diffuseFilename.isEmpty()) { + if (!part.diffuseTexture.filename.isEmpty()) { networkPart.diffuseTexture = Application::getInstance()->getTextureCache()->getTexture( - _textureBase.resolved(QUrl(part.diffuseFilename)), false, mesh.isEye); + _textureBase.resolved(QUrl(part.diffuseTexture.filename)), false, mesh.isEye, part.diffuseTexture.content); networkPart.diffuseTexture->setLoadPriorities(_loadPriorities); } - if (!part.normalFilename.isEmpty()) { + if (!part.normalTexture.filename.isEmpty()) { networkPart.normalTexture = Application::getInstance()->getTextureCache()->getTexture( - _textureBase.resolved(QUrl(part.normalFilename)), true); + _textureBase.resolved(QUrl(part.normalTexture.filename)), true, false, part.normalTexture.content); networkPart.normalTexture->setLoadPriorities(_loadPriorities); } networkMesh.parts.append(networkPart); diff --git a/interface/src/renderer/TextureCache.cpp b/interface/src/renderer/TextureCache.cpp index 3f523cf4bb..f31e4f9060 100644 --- a/interface/src/renderer/TextureCache.cpp +++ b/interface/src/renderer/TextureCache.cpp @@ -105,13 +105,22 @@ GLuint TextureCache::getBlueTextureID() { return _blueTextureID; } -QSharedPointer TextureCache::getTexture(const QUrl& url, bool normalMap, bool dilatable) { +/// Extra data for creating textures. +class TextureExtra { +public: + bool normalMap; + const QByteArray& content; +}; + +QSharedPointer TextureCache::getTexture(const QUrl& url, bool normalMap, + bool dilatable, const QByteArray& content) { if (!dilatable) { - return ResourceCache::getResource(url, QUrl(), false, &normalMap).staticCast(); + TextureExtra extra = { normalMap, content }; + return ResourceCache::getResource(url, QUrl(), false, &extra).staticCast(); } QSharedPointer texture = _dilatableNetworkTextures.value(url); if (texture.isNull()) { - texture = QSharedPointer(new DilatableNetworkTexture(url), &Resource::allReferencesCleared); + texture = QSharedPointer(new DilatableNetworkTexture(url, content), &Resource::allReferencesCleared); texture->setSelf(texture); texture->setCache(this); _dilatableNetworkTextures.insert(url, texture); @@ -215,7 +224,9 @@ bool TextureCache::eventFilter(QObject* watched, QEvent* event) { QSharedPointer TextureCache::createResource(const QUrl& url, const QSharedPointer& fallback, bool delayLoad, const void* extra) { - return QSharedPointer(new NetworkTexture(url, *(const bool*)extra), &Resource::allReferencesCleared); + const TextureExtra* textureExtra = static_cast(extra); + return QSharedPointer(new NetworkTexture(url, textureExtra->normalMap, textureExtra->content), + &Resource::allReferencesCleared); } QOpenGLFramebufferObject* TextureCache::createFramebufferObject() { @@ -238,8 +249,8 @@ Texture::~Texture() { glDeleteTextures(1, &_id); } -NetworkTexture::NetworkTexture(const QUrl& url, bool normalMap) : - Resource(url), +NetworkTexture::NetworkTexture(const QUrl& url, bool normalMap, const QByteArray& content) : + Resource(url, !content.isEmpty()), _translucent(false) { if (!url.isValid()) { @@ -250,12 +261,19 @@ NetworkTexture::NetworkTexture(const QUrl& url, bool normalMap) : glBindTexture(GL_TEXTURE_2D, getID()); loadSingleColorTexture(normalMap ? OPAQUE_BLUE : OPAQUE_WHITE); glBindTexture(GL_TEXTURE_2D, 0); + + // if we have content, load it after we have our self pointer + if (!content.isEmpty()) { + _startedLoading = true; + QMetaObject::invokeMethod(this, "loadContent", Qt::QueuedConnection, Q_ARG(const QByteArray&, content)); + } } class ImageReader : public QRunnable { public: - ImageReader(const QWeakPointer& texture, QNetworkReply* reply); + ImageReader(const QWeakPointer& texture, QNetworkReply* reply, const QUrl& url = QUrl(), + const QByteArray& content = QByteArray()); virtual void run(); @@ -263,27 +281,37 @@ private: QWeakPointer _texture; QNetworkReply* _reply; + QUrl _url; + QByteArray _content; }; -ImageReader::ImageReader(const QWeakPointer& texture, QNetworkReply* reply) : +ImageReader::ImageReader(const QWeakPointer& texture, QNetworkReply* reply, + const QUrl& url, const QByteArray& content) : _texture(texture), - _reply(reply) { + _reply(reply), + _url(url), + _content(content) { } void ImageReader::run() { QSharedPointer texture = _texture.toStrongRef(); if (texture.isNull()) { - _reply->deleteLater(); + if (_reply) { + _reply->deleteLater(); + } return; } - QUrl url = _reply->url(); - QImage image = QImage::fromData(_reply->readAll()); - _reply->deleteLater(); + if (_reply) { + _url = _reply->url(); + _content = _reply->readAll(); + _reply->deleteLater(); + } + QImage image = QImage::fromData(_content); // enforce a fixed maximum const int MAXIMUM_SIZE = 1024; if (image.width() > MAXIMUM_SIZE || image.height() > MAXIMUM_SIZE) { - qDebug() << "Image greater than maximum size:" << url << image.width() << image.height(); + qDebug() << "Image greater than maximum size:" << _url << image.width() << image.height(); image = image.scaled(MAXIMUM_SIZE, MAXIMUM_SIZE, Qt::KeepAspectRatio); } @@ -315,7 +343,7 @@ void ImageReader::run() { } int imageArea = image.width() * image.height(); if (opaquePixels == imageArea) { - qDebug() << "Image with alpha channel is completely opaque:" << url; + qDebug() << "Image with alpha channel is completely opaque:" << _url; image = image.convertToFormat(QImage::Format_RGB888); } QMetaObject::invokeMethod(texture.data(), "setImage", Q_ARG(const QImage&, image), @@ -327,6 +355,10 @@ void NetworkTexture::downloadFinished(QNetworkReply* reply) { QThreadPool::globalInstance()->start(new ImageReader(_self, reply)); } +void NetworkTexture::loadContent(const QByteArray& content) { + QThreadPool::globalInstance()->start(new ImageReader(_self, NULL, _url, content)); +} + void NetworkTexture::setImage(const QImage& image, bool translucent) { _translucent = translucent; @@ -348,8 +380,8 @@ void NetworkTexture::imageLoaded(const QImage& image) { // nothing by default } -DilatableNetworkTexture::DilatableNetworkTexture(const QUrl& url) : - NetworkTexture(url, false), +DilatableNetworkTexture::DilatableNetworkTexture(const QUrl& url, const QByteArray& content) : + NetworkTexture(url, false, content), _innerRadius(0), _outerRadius(0) { diff --git a/interface/src/renderer/TextureCache.h b/interface/src/renderer/TextureCache.h index e66044d843..f4444b6dfc 100644 --- a/interface/src/renderer/TextureCache.h +++ b/interface/src/renderer/TextureCache.h @@ -44,7 +44,8 @@ public: GLuint getBlueTextureID(); /// Loads a texture from the specified URL. - QSharedPointer getTexture(const QUrl& url, bool normalMap = false, bool dilatable = false); + QSharedPointer getTexture(const QUrl& url, bool normalMap = false, bool dilatable = false, + const QByteArray& content = QByteArray()); /// Returns a pointer to the primary framebuffer object. This render target includes a depth component, and is /// used for scene rendering. @@ -115,7 +116,7 @@ class NetworkTexture : public Resource, public Texture { public: - NetworkTexture(const QUrl& url, bool normalMap); + NetworkTexture(const QUrl& url, bool normalMap, const QByteArray& content); /// Checks whether it "looks like" this texture is translucent /// (majority of pixels neither fully opaque or fully transparent). @@ -124,10 +125,12 @@ public: protected: virtual void downloadFinished(QNetworkReply* reply); - virtual void imageLoaded(const QImage& image); - + + Q_INVOKABLE void loadContent(const QByteArray& content); Q_INVOKABLE void setImage(const QImage& image, bool translucent); + virtual void imageLoaded(const QImage& image); + private: bool _translucent; @@ -139,7 +142,7 @@ class DilatableNetworkTexture : public NetworkTexture { public: - DilatableNetworkTexture(const QUrl& url); + DilatableNetworkTexture(const QUrl& url, const QByteArray& content); /// Returns a pointer to a texture with the requested amount of dilation. QSharedPointer getDilatedTexture(float dilation); diff --git a/libraries/fbx/src/FBXReader.cpp b/libraries/fbx/src/FBXReader.cpp index eae8eb3920..dc4e7f617e 100644 --- a/libraries/fbx/src/FBXReader.cpp +++ b/libraries/fbx/src/FBXReader.cpp @@ -935,6 +935,14 @@ public: QVector values; }; +FBXTexture getTexture(const QString& textureID, const QHash& textureFilenames, + const QHash& textureContent) { + FBXTexture texture; + texture.filename = textureFilenames.value(textureID); + texture.content = textureContent.value(texture.filename); + return texture; +} + FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) { QHash meshes; QVector blendshapes; @@ -944,6 +952,7 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) QHash clusters; QHash animationCurves; QHash textureFilenames; + QHash textureContent; QHash materials; QHash diffuseTextures; QHash bumpTextures; @@ -952,8 +961,6 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) QHash yComponents; QHash zComponents; - printNode(node, 0); - QVariantHash joints = mapping.value("joint").toHash(); QString jointEyeLeftName = processID(getString(joints.value("jointEyeLeft", "jointEyeLeft"))); QString jointEyeRightName = processID(getString(joints.value("jointEyeRight", "jointEyeRight"))); @@ -1182,6 +1189,21 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) textureFilenames.insert(getID(object.properties), filename); } } + } else if (object.name == "Video") { + QByteArray filename; + QByteArray content; + foreach (const FBXNode& subobject, object.children) { + if (subobject.name == "RelativeFilename") { + filename = subobject.properties.at(0).toByteArray(); + filename = filename.mid(qMax(filename.lastIndexOf('\\'), filename.lastIndexOf('/')) + 1); + + } else if (subobject.name == "Content" && !subobject.properties.isEmpty()) { + content = subobject.properties.at(0).toByteArray(); + } + } + if (!content.isEmpty()) { + textureContent.insert(filename, content); + } } else if (object.name == "Material") { Material material = { glm::vec3(1.0f, 1.0f, 1.0f), glm::vec3(1.0f, 1.0f, 1.0f), 96.0f }; foreach (const FBXNode& subobject, object.children) { @@ -1263,7 +1285,7 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) if (type.contains("diffuse")) { diffuseTextures.insert(getID(connection.properties, 2), getID(connection.properties, 1)); - } else if (type.contains("bump")) { + } else if (type.contains("bump") || type.contains("normal")) { bumpTextures.insert(getID(connection.properties, 2), getID(connection.properties, 1)); } else if (type == "lcl rotation") { @@ -1463,23 +1485,23 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) if (materials.contains(childID)) { Material material = materials.value(childID); - QByteArray diffuseFilename; + FBXTexture diffuseTexture; QString diffuseTextureID = diffuseTextures.value(childID); if (!diffuseTextureID.isNull()) { - diffuseFilename = textureFilenames.value(diffuseTextureID); - + diffuseTexture = getTexture(diffuseTextureID, textureFilenames, textureContent); + // FBX files generated by 3DSMax have an intermediate texture parent, apparently foreach (const QString& childTextureID, childMap.values(diffuseTextureID)) { if (textureFilenames.contains(childTextureID)) { - diffuseFilename = textureFilenames.value(childTextureID); + diffuseTexture = getTexture(diffuseTextureID, textureFilenames, textureContent); } } } - QByteArray normalFilename; + FBXTexture normalTexture; QString bumpTextureID = bumpTextures.value(childID); if (!bumpTextureID.isNull()) { - normalFilename = textureFilenames.value(bumpTextureID); + normalTexture = getTexture(bumpTextureID, textureFilenames, textureContent); generateTangents = true; } @@ -1489,21 +1511,21 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) part.diffuseColor = material.diffuse; part.specularColor = material.specular; part.shininess = material.shininess; - if (!diffuseFilename.isNull()) { - part.diffuseFilename = diffuseFilename; + if (!diffuseTexture.filename.isNull()) { + part.diffuseTexture = diffuseTexture; } - if (!normalFilename.isNull()) { - part.normalFilename = normalFilename; + if (!normalTexture.filename.isNull()) { + part.normalTexture = normalTexture; } } } materialIndex++; } else if (textureFilenames.contains(childID)) { - QByteArray filename = textureFilenames.value(childID); + FBXTexture texture = getTexture(childID, textureFilenames, textureContent); for (int j = 0; j < extracted.partMaterialTextures.size(); j++) { if (extracted.partMaterialTextures.at(j).second == textureIndex) { - extracted.mesh.parts[j].diffuseFilename = filename; + extracted.mesh.parts[j].diffuseTexture = texture; } } textureIndex++; diff --git a/libraries/fbx/src/FBXReader.h b/libraries/fbx/src/FBXReader.h index 2f840e868e..9445daa7df 100644 --- a/libraries/fbx/src/FBXReader.h +++ b/libraries/fbx/src/FBXReader.h @@ -103,6 +103,14 @@ public: glm::mat4 inverseBindMatrix; }; +/// A texture map in an FBX document. +class FBXTexture { +public: + + QByteArray filename; + QByteArray content; +}; + /// A single part of a mesh (with the same material). class FBXMeshPart { public: @@ -114,8 +122,8 @@ public: glm::vec3 specularColor; float shininess; - QByteArray diffuseFilename; - QByteArray normalFilename; + FBXTexture diffuseTexture; + FBXTexture normalTexture; }; /// A single mesh (with optional blendshapes) extracted from an FBX document. From 15d4f59cebb0d272494be04e6fea80b91383c4e2 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 17 Apr 2014 15:52:32 -0700 Subject: [PATCH 480/595] Moved AnimationObject to separate source files. --- .../script-engine/src/AnimationCache.cpp | 20 -------- libraries/script-engine/src/AnimationCache.h | 29 ------------ .../script-engine/src/AnimationObject.cpp | 36 ++++++++++++++ libraries/script-engine/src/AnimationObject.h | 47 +++++++++++++++++++ libraries/script-engine/src/ScriptEngine.cpp | 1 + 5 files changed, 84 insertions(+), 49 deletions(-) create mode 100644 libraries/script-engine/src/AnimationObject.cpp create mode 100644 libraries/script-engine/src/AnimationObject.h diff --git a/libraries/script-engine/src/AnimationCache.cpp b/libraries/script-engine/src/AnimationCache.cpp index defcce525e..8e1493f075 100644 --- a/libraries/script-engine/src/AnimationCache.cpp +++ b/libraries/script-engine/src/AnimationCache.cpp @@ -10,7 +10,6 @@ // #include -#include #include #include "AnimationCache.h" @@ -101,22 +100,3 @@ void Animation::downloadFinished(QNetworkReply* reply) { QThreadPool::globalInstance()->start(new AnimationReader(_self, reply)); } -QStringList AnimationObject::getJointNames() const { - return qscriptvalue_cast(thisObject())->getJointNames(); -} - -QVector AnimationObject::getFrames() const { - return qscriptvalue_cast(thisObject())->getFrames(); -} - -QVector AnimationFrameObject::getRotations() const { - return qscriptvalue_cast(thisObject()).rotations; -} - -void registerAnimationTypes(QScriptEngine* engine) { - qScriptRegisterSequenceMetaType >(engine); - engine->setDefaultPrototype(qMetaTypeId(), engine->newQObject( - new AnimationFrameObject(), QScriptEngine::ScriptOwnership)); - engine->setDefaultPrototype(qMetaTypeId(), engine->newQObject( - new AnimationObject(), QScriptEngine::ScriptOwnership)); -} diff --git a/libraries/script-engine/src/AnimationCache.h b/libraries/script-engine/src/AnimationCache.h index 38fabad57f..23183adf10 100644 --- a/libraries/script-engine/src/AnimationCache.h +++ b/libraries/script-engine/src/AnimationCache.h @@ -12,14 +12,10 @@ #ifndef hifi_AnimationCache_h #define hifi_AnimationCache_h -#include - #include #include -class QScriptEngine; - class Animation; typedef QSharedPointer AnimationPointer; @@ -69,29 +65,4 @@ private: FBXGeometry _geometry; }; -/// Scriptable wrapper for animation pointers. -class AnimationObject : public QObject, protected QScriptable { - Q_OBJECT - Q_PROPERTY(QStringList jointNames READ getJointNames) - Q_PROPERTY(QVector frames READ getFrames) - -public: - - Q_INVOKABLE QStringList getJointNames() const; - - Q_INVOKABLE QVector getFrames() const; -}; - -/// Scriptable wrapper for animation frames. -class AnimationFrameObject : public QObject, protected QScriptable { - Q_OBJECT - Q_PROPERTY(QVector rotations READ getRotations) - -public: - - Q_INVOKABLE QVector getRotations() const; -}; - -void registerAnimationTypes(QScriptEngine* engine); - #endif // hifi_AnimationCache_h diff --git a/libraries/script-engine/src/AnimationObject.cpp b/libraries/script-engine/src/AnimationObject.cpp new file mode 100644 index 0000000000..ede1e82623 --- /dev/null +++ b/libraries/script-engine/src/AnimationObject.cpp @@ -0,0 +1,36 @@ +// +// AnimationObject.cpp +// libraries/script-engine/src/ +// +// Created by Andrzej Kapolka on 4/17/14. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// +// 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 "AnimationCache.h" +#include "AnimationObject.h" + +QStringList AnimationObject::getJointNames() const { + return qscriptvalue_cast(thisObject())->getJointNames(); +} + +QVector AnimationObject::getFrames() const { + return qscriptvalue_cast(thisObject())->getFrames(); +} + +QVector AnimationFrameObject::getRotations() const { + return qscriptvalue_cast(thisObject()).rotations; +} + +void registerAnimationTypes(QScriptEngine* engine) { + qScriptRegisterSequenceMetaType >(engine); + engine->setDefaultPrototype(qMetaTypeId(), engine->newQObject( + new AnimationFrameObject(), QScriptEngine::ScriptOwnership)); + engine->setDefaultPrototype(qMetaTypeId(), engine->newQObject( + new AnimationObject(), QScriptEngine::ScriptOwnership)); +} + diff --git a/libraries/script-engine/src/AnimationObject.h b/libraries/script-engine/src/AnimationObject.h new file mode 100644 index 0000000000..078fc31fb3 --- /dev/null +++ b/libraries/script-engine/src/AnimationObject.h @@ -0,0 +1,47 @@ +// +// AnimationObject.h +// libraries/script-engine/src/ +// +// Created by Andrzej Kapolka on 4/17/14. +// Copyright (c) 2014 High Fidelity, Inc. All rights reserved. +// +// 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_AnimationObject_h +#define hifi_AnimationObject_h + +#include +#include + +#include + +class QScriptEngine; + +/// Scriptable wrapper for animation pointers. +class AnimationObject : public QObject, protected QScriptable { + Q_OBJECT + Q_PROPERTY(QStringList jointNames READ getJointNames) + Q_PROPERTY(QVector frames READ getFrames) + +public: + + Q_INVOKABLE QStringList getJointNames() const; + + Q_INVOKABLE QVector getFrames() const; +}; + +/// Scriptable wrapper for animation frames. +class AnimationFrameObject : public QObject, protected QScriptable { + Q_OBJECT + Q_PROPERTY(QVector rotations READ getRotations) + +public: + + Q_INVOKABLE QVector getRotations() const; +}; + +void registerAnimationTypes(QScriptEngine* engine); + +#endif // hifi_AnimationObject_h diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index 4dee35c6a5..950ba899de 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -28,6 +28,7 @@ #include +#include "AnimationObject.h" #include "MenuItemProperties.h" #include "LocalVoxels.h" #include "ScriptEngine.h" From 6d1f4ed9420f2c238a2afb9834e189d0651be913 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Fri, 18 Apr 2014 01:13:06 +0200 Subject: [PATCH 481/595] Fix format --- interface/src/Application.cpp | 47 +++++++++++++++++------------------ 1 file changed, 23 insertions(+), 24 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index a7a00bf7c7..592370705a 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3555,35 +3555,34 @@ void Application::urlGoTo(int argc, const char * constArgv[]) { //Gets the url (hifi://domain/destination/orientation) QString customUrl = getCmdOption(argc, constArgv, "-url"); - if (customUrl.startsWith("hifi://")) { - QStringList urlParts = customUrl.remove(0, CUSTOM_URL_SCHEME.length() + 2).split('/', QString::SkipEmptyParts); + if (customUrl.startsWith("hifi://")) { + QStringList urlParts = customUrl.remove(0, CUSTOM_URL_SCHEME.length() + 2).split('/', QString::SkipEmptyParts); + if (urlParts.count() > 1) { + // if url has 2 or more parts, the first one is domain name + QString domain = urlParts[0]; - if (urlParts.count() > 1) { - // if url has 2 or more parts, the first one is domain name - QString domain = urlParts[0]; + // second part is either a destination coordinate or + // a place name + QString destination = urlParts[1]; - // second part is either a destination coordinate or - // a place name - QString destination = urlParts[1]; + // any third part is an avatar orientation. + QString orientation = urlParts.count() > 2 ? urlParts[2] : QString(); - // any third part is an avatar orientation. - QString orientation = urlParts.count() > 2 ? urlParts[2] : QString(); - - Menu::goToDomain(domain); + Menu::goToDomain(domain); - // goto either @user, #place, or x-xx,y-yy,z-zz - // style co-ordinate. - Menu::goTo(destination); + // goto either @user, #place, or x-xx,y-yy,z-zz + // style co-ordinate. + Menu::goTo(destination); - if (!orientation.isEmpty()) { - // location orientation - Menu::goToOrientation(orientation); - } - } else if (urlParts.count() == 1) { - // location coordinates or place name - QString destination = urlParts[0]; - Menu::goTo(destination); + if (!orientation.isEmpty()) { + // location orientation + Menu::goToOrientation(orientation); } - + } else if (urlParts.count() == 1) { + // location coordinates or place name + QString destination = urlParts[0]; + Menu::goTo(destination); } + + } } From cfdbdad2d8823dcd7d4591502049b1a861ce4e2f Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Thu, 17 Apr 2014 16:22:35 -0700 Subject: [PATCH 482/595] improved method for disabling bad joint shapes --- interface/src/renderer/FBXReader.cpp | 4 ++-- interface/src/renderer/FBXReader.h | 4 +++- interface/src/renderer/Model.cpp | 28 +++++++++++++++++++--------- 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/interface/src/renderer/FBXReader.cpp b/interface/src/renderer/FBXReader.cpp index 32b5686558..ff3fa8667f 100644 --- a/interface/src/renderer/FBXReader.cpp +++ b/interface/src/renderer/FBXReader.cpp @@ -1651,8 +1651,8 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping) if (distanceFromEnd > joint.distanceToParent && distanceFromBegin > joint.distanceToParent) { // The shape is further from both joint endpoints than the endpoints are from each other // which probably means the model has a bad transform somewhere. We disable this shape - // by setting its radius to zero. - joint.boneRadius = 0.0f; + // by setting its type to UNKNOWN_SHAPE. + joint.shapeType = Shape::UNKNOWN_SHAPE; } } } diff --git a/interface/src/renderer/FBXReader.h b/interface/src/renderer/FBXReader.h index 73c305e2eb..366ab12180 100644 --- a/interface/src/renderer/FBXReader.h +++ b/interface/src/renderer/FBXReader.h @@ -18,6 +18,8 @@ #include #include +#include + #include #include @@ -91,7 +93,7 @@ public: QString name; glm::vec3 shapePosition; // in joint frame glm::quat shapeRotation; // in joint frame - int shapeType; + Shape::Type shapeType; }; diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index bcde861e84..ca0b46841d 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -500,7 +500,12 @@ void Model::rebuildShapes() { float radius = uniformScale * joint.boneRadius; float halfHeight = 0.5f * uniformScale * joint.distanceToParent; - if (joint.shapeType == Shape::CAPSULE_SHAPE && halfHeight > EPSILON) { + Shape::Type type = joint.shapeType; + if (type == Shape::CAPSULE_SHAPE && halfHeight < EPSILON) { + // this capsule is effectively a sphere + type = Shape::SPHERE_SHAPE; + } + if (type == Shape::CAPSULE_SHAPE) { CapsuleShape* capsule = new CapsuleShape(radius, halfHeight); capsule->setPosition(worldPosition); capsule->setRotation(_jointStates[i].combinedRotation * joint.shapeRotation); @@ -523,18 +528,23 @@ void Model::rebuildShapes() { totalExtents.addExtents(shapeExtents); - } else { + } else if (type == Shape::SPHERE_SHAPE) { SphereShape* sphere = new SphereShape(radius, worldPosition); _jointShapes.push_back(sphere); - if (radius > 0.0f) { - // only include sphere shapes with non-zero radius - glm::vec3 axis = glm::vec3(radius); - shapeExtents.addPoint(worldPosition + axis); - shapeExtents.addPoint(worldPosition - axis); - totalExtents.addExtents(shapeExtents); - } + glm::vec3 axis = glm::vec3(radius); + shapeExtents.addPoint(worldPosition + axis); + shapeExtents.addPoint(worldPosition - axis); + totalExtents.addExtents(shapeExtents); + } else { + // this shape type is not handled and the joint shouldn't collide, + // however we must have a shape for each joint, + // so we make a bogus sphere and put it at the center of the model + // TODO: implement collision groups for more control over what collides with what + SphereShape* sphere = new SphereShape(0.f, _offset); + _jointShapes.push_back(sphere); } + } // bounding shape From a040c997d801fb360bbcf0b15f39827a198388f7 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Thu, 17 Apr 2014 16:30:23 -0700 Subject: [PATCH 483/595] ModelUploader update --- interface/src/ModelUploader.cpp | 68 ++++++++++++++++++++++++++++++--- interface/src/ModelUploader.h | 1 + 2 files changed, 63 insertions(+), 6 deletions(-) diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index edbc6c0ad9..5f219e03c8 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -34,6 +34,7 @@ static const QString TEXDIR_FIELD = "texdir"; static const QString LOD_FIELD = "lod"; static const QString S3_URL = "http://highfidelity-public.s3-us-west-1.amazonaws.com"; +static const QString DATA_SERVER_URL = "https://data-web.highfidelity.io"; static const QString MODEL_URL = "/api/v1/models"; static const QString SETTING_NAME = "LastModelUploadLocation"; @@ -201,14 +202,14 @@ void ModelUploader::send() { JSONCallbackParameters callbackParams; callbackParams.jsonCallbackReceiver = this; - callbackParams.jsonCallbackMethod = "uploadSuccess"; + callbackParams.jsonCallbackMethod = "checkJSON"; callbackParams.errorCallbackReceiver = this; callbackParams.errorCallbackMethod = "uploadFailed"; - callbackParams.updateReciever = this; - callbackParams.updateSlot = SLOT(uploadUpdate(qint64, qint64)); - AccountManager::getInstance().authenticatedRequest(MODEL_URL, QNetworkAccessManager::PostOperation, callbackParams, QByteArray(), _dataMultiPart); - _dataMultiPart = NULL; + AccountManager::getInstance().authenticatedRequest(MODEL_URL + "/" + QFileInfo(_url).baseName(), + QNetworkAccessManager::GetOperation, + callbackParams); + qDebug() << "Sending model..."; _progressDialog = new QDialog(); _progressBar = new QProgressBar(_progressDialog); @@ -226,6 +227,61 @@ void ModelUploader::send() { _progressBar = NULL; } +void ModelUploader::checkJSON(const QJsonObject& jsonResponse) { + if (jsonResponse.contains("status") && jsonResponse.value("status").toString() == "success") { + qDebug() << "status : success"; + JSONCallbackParameters callbackParams; + callbackParams.jsonCallbackReceiver = this; + callbackParams.jsonCallbackMethod = "uploadSuccess"; + callbackParams.errorCallbackReceiver = this; + callbackParams.errorCallbackMethod = "uploadFailed"; + callbackParams.updateReciever = this; + callbackParams.updateSlot = SLOT(uploadUpdate(qint64, qint64)); + + if (jsonResponse.contains("exists") && jsonResponse.value("exists").toString() == "true") { + qDebug() << "exists : true"; + if (jsonResponse.contains("can_update") && jsonResponse.value("can_update").toString() == "true") { + qDebug() << "can_update : true"; + + AccountManager::getInstance().authenticatedRequest(MODEL_URL + "/" + QFileInfo(_url).baseName(), + QNetworkAccessManager::PutOperation, + callbackParams, + QByteArray(), + _dataMultiPart); + _dataMultiPart = NULL; + } else { + qDebug() << "can_update : false"; + if (_progressDialog) { + _progressDialog->reject(); + } + QMessageBox::warning(NULL, + QString("ModelUploader::checkJSON()"), + QString("This model already exist and is own by someone else."), + QMessageBox::Ok); + deleteLater(); + } + } else { + qDebug() << "exists : false"; + AccountManager::getInstance().authenticatedRequest(MODEL_URL, + QNetworkAccessManager::PostOperation, + callbackParams, + QByteArray(), + _dataMultiPart); + _dataMultiPart = NULL; + } + } else { + qDebug() << "status : failed"; + if (_progressDialog) { + _progressDialog->reject(); + } + QMessageBox::warning(NULL, + QString("ModelUploader::checkJSON()"), + QString("Something went wrong with the data-server."), + QMessageBox::Ok); + deleteLater(); + } +} + void ModelUploader::uploadUpdate(qint64 bytesSent, qint64 bytesTotal) { if (_progressDialog) { _progressBar->setRange(0, bytesTotal); @@ -249,11 +305,11 @@ void ModelUploader::uploadFailed(QNetworkReply::NetworkError errorCode, const QS if (_progressDialog) { _progressDialog->reject(); } + qDebug() << "Model upload failed (" << errorCode << "): " << errorString; QMessageBox::warning(NULL, QString("ModelUploader::uploadFailed()"), QString("There was a problem with your upload, please try again later."), QMessageBox::Ok); - qDebug() << "Model upload failed (" << errorCode << "): " << errorString; deleteLater(); } diff --git a/interface/src/ModelUploader.h b/interface/src/ModelUploader.h index ff22673cdd..54702d6420 100644 --- a/interface/src/ModelUploader.h +++ b/interface/src/ModelUploader.h @@ -30,6 +30,7 @@ public slots: void send(); private slots: + void checkJSON(const QJsonObject& jsonResponse); void uploadUpdate(qint64 bytesSent, qint64 bytesTotal); void uploadSuccess(const QJsonObject& jsonResponse); void uploadFailed(QNetworkReply::NetworkError errorCode, const QString& errorString); From e303ce1a12ca7a6c51010c809101baacaf0085dd Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 17 Apr 2014 16:37:40 -0700 Subject: [PATCH 484/595] move some Avatar management to AvatarHashMap --- interface/src/avatar/Avatar.cpp | 5 ++ interface/src/avatar/AvatarManager.cpp | 100 +----------------------- interface/src/avatar/AvatarManager.h | 7 +- libraries/avatars/src/AvatarHashMap.cpp | 94 ++++++++++++++++++++++ libraries/avatars/src/AvatarHashMap.h | 12 +++ 5 files changed, 115 insertions(+), 103 deletions(-) diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index e9d804d227..78d5131b77 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -685,6 +685,11 @@ void Avatar::setBillboard(const QByteArray& billboard) { } int Avatar::parseDataAtOffset(const QByteArray& packet, int offset) { + if (!_initialized) { + // now that we have data for this Avatar we are go for init + init(); + } + // change in position implies movement glm::vec3 oldPosition = _position; diff --git a/interface/src/avatar/AvatarManager.cpp b/interface/src/avatar/AvatarManager.cpp index 5798f33d0f..a8d8c8f6e3 100644 --- a/interface/src/avatar/AvatarManager.cpp +++ b/interface/src/avatar/AvatarManager.cpp @@ -127,22 +127,9 @@ void AvatarManager::renderAvatarFades(const glm::vec3& cameraPosition, Avatar::R } } -AvatarSharedPointer AvatarManager::matchingOrNewAvatar(const QUuid& sessionUUID, const QWeakPointer& mixerWeakPointer) { - AvatarSharedPointer matchingAvatar = _avatarHash.value(sessionUUID); - - if (!matchingAvatar) { - // construct a new Avatar for this node - Avatar* avatar = new Avatar(); - avatar->setOwningAvatarMixer(mixerWeakPointer); - - // insert the new avatar into our hash - matchingAvatar = AvatarSharedPointer(avatar); - _avatarHash.insert(sessionUUID, matchingAvatar); - - qDebug() << "Adding avatar with sessionUUID " << sessionUUID << "to AvatarManager hash."; - } - - return matchingAvatar; +void AvatarManager::sharedAvatarAddedToHash(const AvatarSharedPointer& sharedAvatar, + const QWeakPointer& mixerWeakPointer) { + reinterpret_cast(sharedAvatar.data())->setOwningAvatarMixer(mixerWeakPointer); } void AvatarManager::processAvatarMixerDatagram(const QByteArray& datagram, const QWeakPointer& mixerWeakPointer) { @@ -164,87 +151,6 @@ void AvatarManager::processAvatarMixerDatagram(const QByteArray& datagram, const } } -void AvatarManager::processAvatarDataPacket(const QByteArray &datagram, const QWeakPointer &mixerWeakPointer) { - int bytesRead = numBytesForPacketHeader(datagram); - - // enumerate over all of the avatars in this packet - // only add them if mixerWeakPointer points to something (meaning that mixer is still around) - while (bytesRead < datagram.size() && mixerWeakPointer.data()) { - QUuid sessionUUID = QUuid::fromRfc4122(datagram.mid(bytesRead, NUM_BYTES_RFC4122_UUID)); - bytesRead += NUM_BYTES_RFC4122_UUID; - - AvatarSharedPointer matchingAvatarData = matchingOrNewAvatar(sessionUUID, mixerWeakPointer); - - // have the matching (or new) avatar parse the data from the packet - bytesRead += matchingAvatarData->parseDataAtOffset(datagram, bytesRead); - - Avatar* matchingAvatar = reinterpret_cast(matchingAvatarData.data()); - - if (!matchingAvatar->isInitialized()) { - // now that we have AvatarData for this Avatar we are go for init - matchingAvatar->init(); - } - } -} - -void AvatarManager::processAvatarIdentityPacket(const QByteArray &packet, const QWeakPointer& mixerWeakPointer) { - // setup a data stream to parse the packet - QDataStream identityStream(packet); - identityStream.skipRawData(numBytesForPacketHeader(packet)); - - QUuid sessionUUID; - - while (!identityStream.atEnd()) { - - QUrl faceMeshURL, skeletonURL; - QString displayName; - identityStream >> sessionUUID >> faceMeshURL >> skeletonURL >> displayName; - - // mesh URL for a UUID, find avatar in our list - AvatarSharedPointer matchingAvatar = matchingOrNewAvatar(sessionUUID, mixerWeakPointer); - if (matchingAvatar) { - Avatar* avatar = static_cast(matchingAvatar.data()); - - if (avatar->getFaceModelURL() != faceMeshURL) { - avatar->setFaceModelURL(faceMeshURL); - } - - if (avatar->getSkeletonModelURL() != skeletonURL) { - avatar->setSkeletonModelURL(skeletonURL); - } - - if (avatar->getDisplayName() != displayName) { - avatar->setDisplayName(displayName); - } - } - } -} - -void AvatarManager::processAvatarBillboardPacket(const QByteArray& packet, const QWeakPointer& mixerWeakPointer) { - int headerSize = numBytesForPacketHeader(packet); - QUuid sessionUUID = QUuid::fromRfc4122(QByteArray::fromRawData(packet.constData() + headerSize, NUM_BYTES_RFC4122_UUID)); - - AvatarSharedPointer matchingAvatar = matchingOrNewAvatar(sessionUUID, mixerWeakPointer); - if (matchingAvatar) { - Avatar* avatar = static_cast(matchingAvatar.data()); - QByteArray billboard = packet.mid(headerSize + NUM_BYTES_RFC4122_UUID); - if (avatar->getBillboard() != billboard) { - avatar->setBillboard(billboard); - } - } -} - -void AvatarManager::processKillAvatar(const QByteArray& datagram) { - // read the node id - QUuid sessionUUID = QUuid::fromRfc4122(datagram.mid(numBytesForPacketHeader(datagram), NUM_BYTES_RFC4122_UUID)); - - // remove the avatar with that UUID from our hash, if it exists - AvatarHash::iterator matchedAvatar = _avatarHash.find(sessionUUID); - if (matchedAvatar != _avatarHash.end()) { - erase(matchedAvatar); - } -} - AvatarHash::iterator AvatarManager::erase(const AvatarHash::iterator& iterator) { if (iterator.key() != MY_AVATAR_KEY) { qDebug() << "Removing Avatar with UUID" << iterator.key() << "from AvatarManager hash."; diff --git a/interface/src/avatar/AvatarManager.h b/interface/src/avatar/AvatarManager.h index 78491b3a5d..db2bb0b5ac 100644 --- a/interface/src/avatar/AvatarManager.h +++ b/interface/src/avatar/AvatarManager.h @@ -42,12 +42,7 @@ public slots: private: AvatarManager(const AvatarManager& other); - AvatarSharedPointer matchingOrNewAvatar(const QUuid& nodeUUID, const QWeakPointer& mixerWeakPointer); - - void processAvatarDataPacket(const QByteArray& packet, const QWeakPointer& mixerWeakPointer); - void processAvatarIdentityPacket(const QByteArray& packet, const QWeakPointer& mixerWeakPointer); - void processAvatarBillboardPacket(const QByteArray& packet, const QWeakPointer& mixerWeakPointer); - void processKillAvatar(const QByteArray& datagram); + void sharedAvatarAddedToHash(const AvatarSharedPointer& sharedAvatar, const QWeakPointer& mixerWeakPointer); void simulateAvatarFades(float deltaTime); void renderAvatarFades(const glm::vec3& cameraPosition, Avatar::RenderMode renderMode); diff --git a/libraries/avatars/src/AvatarHashMap.cpp b/libraries/avatars/src/AvatarHashMap.cpp index 1c2cd4bf92..e3446637ef 100644 --- a/libraries/avatars/src/AvatarHashMap.cpp +++ b/libraries/avatars/src/AvatarHashMap.cpp @@ -9,6 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include + #include "AvatarHashMap.h" AvatarHashMap::AvatarHashMap() : @@ -25,3 +27,95 @@ AvatarHash::iterator AvatarHashMap::erase(const AvatarHash::iterator& iterator) return _avatarHash.erase(iterator); } +AvatarSharedPointer AvatarHashMap::newSharedAvatar() { + AvatarData* avatarData = new AvatarData(); + return AvatarSharedPointer(avatarData); +} + +AvatarSharedPointer AvatarHashMap::matchingOrNewAvatar(const QUuid& sessionUUID, const QWeakPointer& mixerWeakPointer) { + AvatarSharedPointer matchingAvatar = _avatarHash.value(sessionUUID); + + if (!matchingAvatar) { + // insert the new avatar into our hash + matchingAvatar = newSharedAvatar(); + + qDebug() << "Adding avatar with sessionUUID " << sessionUUID << "to AvatarManager hash."; + _avatarHash.insert(sessionUUID, matchingAvatar); + + sharedAvatarAddedToHash(matchingAvatar, mixerWeakPointer); + } + + return matchingAvatar; +} + +void AvatarHashMap::processAvatarDataPacket(const QByteArray &datagram, const QWeakPointer &mixerWeakPointer) { + int bytesRead = numBytesForPacketHeader(datagram); + + // enumerate over all of the avatars in this packet + // only add them if mixerWeakPointer points to something (meaning that mixer is still around) + while (bytesRead < datagram.size() && mixerWeakPointer.data()) { + QUuid sessionUUID = QUuid::fromRfc4122(datagram.mid(bytesRead, NUM_BYTES_RFC4122_UUID)); + bytesRead += NUM_BYTES_RFC4122_UUID; + + AvatarSharedPointer matchingAvatarData = matchingOrNewAvatar(sessionUUID, mixerWeakPointer); + + // have the matching (or new) avatar parse the data from the packet + bytesRead += matchingAvatarData->parseDataAtOffset(datagram, bytesRead); + } +} + +void AvatarHashMap::processAvatarIdentityPacket(const QByteArray &packet, const QWeakPointer& mixerWeakPointer) { + // setup a data stream to parse the packet + QDataStream identityStream(packet); + identityStream.skipRawData(numBytesForPacketHeader(packet)); + + QUuid sessionUUID; + + while (!identityStream.atEnd()) { + + QUrl faceMeshURL, skeletonURL; + QString displayName; + identityStream >> sessionUUID >> faceMeshURL >> skeletonURL >> displayName; + + // mesh URL for a UUID, find avatar in our list + AvatarSharedPointer matchingAvatar = matchingOrNewAvatar(sessionUUID, mixerWeakPointer); + if (matchingAvatar) { + + if (matchingAvatar->getFaceModelURL() != faceMeshURL) { + matchingAvatar->setFaceModelURL(faceMeshURL); + } + + if (matchingAvatar->getSkeletonModelURL() != skeletonURL) { + matchingAvatar->setSkeletonModelURL(skeletonURL); + } + + if (matchingAvatar->getDisplayName() != displayName) { + matchingAvatar->setDisplayName(displayName); + } + } + } +} + +void AvatarHashMap::processAvatarBillboardPacket(const QByteArray& packet, const QWeakPointer& mixerWeakPointer) { + int headerSize = numBytesForPacketHeader(packet); + QUuid sessionUUID = QUuid::fromRfc4122(QByteArray::fromRawData(packet.constData() + headerSize, NUM_BYTES_RFC4122_UUID)); + + AvatarSharedPointer matchingAvatar = matchingOrNewAvatar(sessionUUID, mixerWeakPointer); + if (matchingAvatar) { + QByteArray billboard = packet.mid(headerSize + NUM_BYTES_RFC4122_UUID); + if (matchingAvatar->getBillboard() != billboard) { + matchingAvatar->setBillboard(billboard); + } + } +} + +void AvatarHashMap::processKillAvatar(const QByteArray& datagram) { + // read the node id + QUuid sessionUUID = QUuid::fromRfc4122(datagram.mid(numBytesForPacketHeader(datagram), NUM_BYTES_RFC4122_UUID)); + + // remove the avatar with that UUID from our hash, if it exists + AvatarHash::iterator matchedAvatar = _avatarHash.find(sessionUUID); + if (matchedAvatar != _avatarHash.end()) { + erase(matchedAvatar); + } +} \ No newline at end of file diff --git a/libraries/avatars/src/AvatarHashMap.h b/libraries/avatars/src/AvatarHashMap.h index aee9cd09f1..c9b318dee8 100644 --- a/libraries/avatars/src/AvatarHashMap.h +++ b/libraries/avatars/src/AvatarHashMap.h @@ -16,6 +16,8 @@ #include #include +#include + #include "AvatarData.h" typedef QSharedPointer AvatarSharedPointer; @@ -32,6 +34,16 @@ public: protected: virtual AvatarHash::iterator erase(const AvatarHash::iterator& iterator); + + virtual AvatarSharedPointer newSharedAvatar(); + virtual void sharedAvatarAddedToHash(const AvatarSharedPointer& sharedAvatar, + const QWeakPointer& mixerWeakPointer) = 0; + AvatarSharedPointer matchingOrNewAvatar(const QUuid& nodeUUID, const QWeakPointer& mixerWeakPointer); + + void processAvatarDataPacket(const QByteArray& packet, const QWeakPointer& mixerWeakPointer); + void processAvatarIdentityPacket(const QByteArray& packet, const QWeakPointer& mixerWeakPointer); + void processAvatarBillboardPacket(const QByteArray& packet, const QWeakPointer& mixerWeakPointer); + void processKillAvatar(const QByteArray& datagram); AvatarHash _avatarHash; }; From 69d3360675e53cd92d817ebf237b5ee43eb0b103 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 17 Apr 2014 16:48:24 -0700 Subject: [PATCH 485/595] add a convenience method to AvatarHashMap to check for avatar removal --- interface/src/avatar/Avatar.cpp | 1 - interface/src/avatar/Avatar.h | 4 ---- interface/src/avatar/AvatarManager.cpp | 13 +++++-------- interface/src/avatar/AvatarManager.h | 2 -- libraries/avatars/src/AvatarData.cpp | 3 ++- libraries/avatars/src/AvatarData.h | 6 ++++++ libraries/avatars/src/AvatarHashMap.cpp | 6 +++++- libraries/avatars/src/AvatarHashMap.h | 4 ++-- 8 files changed, 20 insertions(+), 19 deletions(-) diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 78d5131b77..8cfab7da03 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -56,7 +56,6 @@ Avatar::Avatar() : _mouseRayOrigin(0.0f, 0.0f, 0.0f), _mouseRayDirection(0.0f, 0.0f, 0.0f), _moving(false), - _owningAvatarMixer(), _collisionFlags(0), _initialized(false), _shouldRenderBillboard(true) diff --git a/interface/src/avatar/Avatar.h b/interface/src/avatar/Avatar.h index 4d68f2168b..ecf1be4899 100755 --- a/interface/src/avatar/Avatar.h +++ b/interface/src/avatar/Avatar.h @@ -99,9 +99,6 @@ public: /// Returns the distance to use as a LOD parameter. float getLODDistance() const; - - Node* getOwningAvatarMixer() { return _owningAvatarMixer.data(); } - void setOwningAvatarMixer(const QWeakPointer& owningAvatarMixer) { _owningAvatarMixer = owningAvatarMixer; } bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance) const; @@ -177,7 +174,6 @@ protected: glm::vec3 _mouseRayDirection; float _stringLength; bool _moving; ///< set when position is changing - QWeakPointer _owningAvatarMixer; uint32_t _collisionFlags; diff --git a/interface/src/avatar/AvatarManager.cpp b/interface/src/avatar/AvatarManager.cpp index a8d8c8f6e3..b4969bae39 100644 --- a/interface/src/avatar/AvatarManager.cpp +++ b/interface/src/avatar/AvatarManager.cpp @@ -51,14 +51,16 @@ void AvatarManager::updateOtherAvatars(float deltaTime) { // simulate avatars AvatarHash::iterator avatarIterator = _avatarHash.begin(); while (avatarIterator != _avatarHash.end()) { - Avatar* avatar = static_cast(avatarIterator.value().data()); - if (avatar == static_cast(_myAvatar.data()) || !avatar->isInitialized()) { + AvatarSharedPointer sharedAvatar = avatarIterator.value(); + Avatar* avatar = reinterpret_cast(sharedAvatar.data()); + + if (sharedAvatar == _myAvatar || !avatar->isInitialized()) { // DO NOT update _myAvatar! Its update has already been done earlier in the main loop. // DO NOT update uninitialized Avatars ++avatarIterator; continue; } - if (avatar->getOwningAvatarMixer()) { + if (!shouldKillAvatar(sharedAvatar)) { // this avatar's mixer is still around, go ahead and simulate it avatar->simulate(deltaTime); avatar->setMouseRay(mouseOrigin, mouseDirection); @@ -127,11 +129,6 @@ void AvatarManager::renderAvatarFades(const glm::vec3& cameraPosition, Avatar::R } } -void AvatarManager::sharedAvatarAddedToHash(const AvatarSharedPointer& sharedAvatar, - const QWeakPointer& mixerWeakPointer) { - reinterpret_cast(sharedAvatar.data())->setOwningAvatarMixer(mixerWeakPointer); -} - void AvatarManager::processAvatarMixerDatagram(const QByteArray& datagram, const QWeakPointer& mixerWeakPointer) { switch (packetTypeForPacket(datagram)) { case PacketTypeBulkAvatarData: diff --git a/interface/src/avatar/AvatarManager.h b/interface/src/avatar/AvatarManager.h index db2bb0b5ac..1b72052c7e 100644 --- a/interface/src/avatar/AvatarManager.h +++ b/interface/src/avatar/AvatarManager.h @@ -41,8 +41,6 @@ public slots: private: AvatarManager(const AvatarManager& other); - - void sharedAvatarAddedToHash(const AvatarSharedPointer& sharedAvatar, const QWeakPointer& mixerWeakPointer); void simulateAvatarFades(float deltaTime); void renderAvatarFades(const glm::vec3& cameraPosition, Avatar::RenderMode renderMode); diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index 2f412b5e9a..a59e0d9df3 100644 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -51,7 +51,8 @@ AvatarData::AvatarData() : _displayNameTargetAlpha(0.0f), _displayNameAlpha(0.0f), _billboard(), - _errorLogExpiry(0) + _errorLogExpiry(0), + _owningAvatarMixer() { } diff --git a/libraries/avatars/src/AvatarData.h b/libraries/avatars/src/AvatarData.h index 947fbc41d4..80482cc165 100755 --- a/libraries/avatars/src/AvatarData.h +++ b/libraries/avatars/src/AvatarData.h @@ -44,6 +44,7 @@ typedef unsigned long long quint64; #include #include +#include #include "HeadData.h" #include "HandData.h" @@ -220,6 +221,9 @@ public: QString getSkeletonModelURLFromScript() const { return _skeletonModelURL.toString(); } void setSkeletonModelURLFromScript(const QString& skeletonModelString) { setSkeletonModelURL(QUrl(skeletonModelString)); } + Node* getOwningAvatarMixer() { return _owningAvatarMixer.data(); } + void setOwningAvatarMixer(const QWeakPointer& owningAvatarMixer) { _owningAvatarMixer = owningAvatarMixer; } + virtual float getBoundingRadius() const { return 1.f; } static void setNetworkAccessManager(QNetworkAccessManager* sharedAccessManager) { networkAccessManager = sharedAccessManager; } @@ -278,6 +282,8 @@ protected: static QNetworkAccessManager* networkAccessManager; quint64 _errorLogExpiry; ///< time in future when to log an error + + QWeakPointer _owningAvatarMixer; /// Loads the joint indices, names from the FST file (if any) virtual void updateJointMappings(); diff --git a/libraries/avatars/src/AvatarHashMap.cpp b/libraries/avatars/src/AvatarHashMap.cpp index e3446637ef..c878eef4c7 100644 --- a/libraries/avatars/src/AvatarHashMap.cpp +++ b/libraries/avatars/src/AvatarHashMap.cpp @@ -27,6 +27,10 @@ AvatarHash::iterator AvatarHashMap::erase(const AvatarHash::iterator& iterator) return _avatarHash.erase(iterator); } +bool AvatarHashMap::shouldKillAvatar(const AvatarSharedPointer& sharedAvatar) { + return (sharedAvatar->getOwningAvatarMixer() == NULL); +} + AvatarSharedPointer AvatarHashMap::newSharedAvatar() { AvatarData* avatarData = new AvatarData(); return AvatarSharedPointer(avatarData); @@ -42,7 +46,7 @@ AvatarSharedPointer AvatarHashMap::matchingOrNewAvatar(const QUuid& sessionUUID, qDebug() << "Adding avatar with sessionUUID " << sessionUUID << "to AvatarManager hash."; _avatarHash.insert(sessionUUID, matchingAvatar); - sharedAvatarAddedToHash(matchingAvatar, mixerWeakPointer); + matchingAvatar->setOwningAvatarMixer(mixerWeakPointer); } return matchingAvatar; diff --git a/libraries/avatars/src/AvatarHashMap.h b/libraries/avatars/src/AvatarHashMap.h index c9b318dee8..2db6c79ed2 100644 --- a/libraries/avatars/src/AvatarHashMap.h +++ b/libraries/avatars/src/AvatarHashMap.h @@ -35,9 +35,9 @@ public: protected: virtual AvatarHash::iterator erase(const AvatarHash::iterator& iterator); + bool shouldKillAvatar(const AvatarSharedPointer& sharedAvatar); + virtual AvatarSharedPointer newSharedAvatar(); - virtual void sharedAvatarAddedToHash(const AvatarSharedPointer& sharedAvatar, - const QWeakPointer& mixerWeakPointer) = 0; AvatarSharedPointer matchingOrNewAvatar(const QUuid& nodeUUID, const QWeakPointer& mixerWeakPointer); void processAvatarDataPacket(const QByteArray& packet, const QWeakPointer& mixerWeakPointer); From 3e4369f2fff8f3315fe7219ff32f9b9ef55e3cee Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 17 Apr 2014 16:56:57 -0700 Subject: [PATCH 486/595] kill avatars in hash map after a timeout threshold --- libraries/avatars/src/AvatarData.cpp | 7 ++++++- libraries/avatars/src/AvatarData.h | 6 +++++- libraries/avatars/src/AvatarHashMap.cpp | 6 +++++- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index a59e0d9df3..2e716296ff 100644 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -52,7 +52,8 @@ AvatarData::AvatarData() : _displayNameAlpha(0.0f), _billboard(), _errorLogExpiry(0), - _owningAvatarMixer() + _owningAvatarMixer(), + _lastUpdateTimer() { } @@ -194,6 +195,10 @@ bool AvatarData::shouldLogError(const quint64& now) { // read data in packet starting at byte offset and return number of bytes parsed int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { + + // reset the last heard timer since we have new data for this AvatarData + _lastUpdateTimer.restart(); + // lazily allocate memory for HeadData in case we're not an Avatar instance if (!_headData) { _headData = new HeadData(this); diff --git a/libraries/avatars/src/AvatarData.h b/libraries/avatars/src/AvatarData.h index 80482cc165..d1a63c9a58 100755 --- a/libraries/avatars/src/AvatarData.h +++ b/libraries/avatars/src/AvatarData.h @@ -32,6 +32,7 @@ typedef unsigned long long quint64; #include #include +#include #include #include #include @@ -224,6 +225,8 @@ public: Node* getOwningAvatarMixer() { return _owningAvatarMixer.data(); } void setOwningAvatarMixer(const QWeakPointer& owningAvatarMixer) { _owningAvatarMixer = owningAvatarMixer; } + QElapsedTimer& getLastUpdateTimer() { return _lastUpdateTimer; } + virtual float getBoundingRadius() const { return 1.f; } static void setNetworkAccessManager(QNetworkAccessManager* sharedAccessManager) { networkAccessManager = sharedAccessManager; } @@ -284,7 +287,8 @@ protected: quint64 _errorLogExpiry; ///< time in future when to log an error QWeakPointer _owningAvatarMixer; - + QElapsedTimer _lastUpdateTimer; + /// Loads the joint indices, names from the FST file (if any) virtual void updateJointMappings(); diff --git a/libraries/avatars/src/AvatarHashMap.cpp b/libraries/avatars/src/AvatarHashMap.cpp index c878eef4c7..5f2d27c1a6 100644 --- a/libraries/avatars/src/AvatarHashMap.cpp +++ b/libraries/avatars/src/AvatarHashMap.cpp @@ -16,6 +16,7 @@ AvatarHashMap::AvatarHashMap() : _avatarHash() { + } void AvatarHashMap::insert(const QUuid& id, AvatarSharedPointer avatar) { @@ -27,8 +28,11 @@ AvatarHash::iterator AvatarHashMap::erase(const AvatarHash::iterator& iterator) return _avatarHash.erase(iterator); } +const qint64 AVATAR_SILENCE_THRESHOLD_MSECS = 5 * 1000; + bool AvatarHashMap::shouldKillAvatar(const AvatarSharedPointer& sharedAvatar) { - return (sharedAvatar->getOwningAvatarMixer() == NULL); + return (sharedAvatar->getOwningAvatarMixer() == NULL + && sharedAvatar->getLastUpdateTimer().elapsed() > AVATAR_SILENCE_THRESHOLD_MSECS); } AvatarSharedPointer AvatarHashMap::newSharedAvatar() { From 828bedc3e80088777000bf73af7c89fa10c652bb Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 17 Apr 2014 17:07:02 -0700 Subject: [PATCH 487/595] Slight fix for dancing bot script. --- examples/dancing_bot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/dancing_bot.js b/examples/dancing_bot.js index 3572cc5a11..2c0a35adb7 100644 --- a/examples/dancing_bot.js +++ b/examples/dancing_bot.js @@ -27,7 +27,7 @@ Script.update.connect(function(deltaTime) { if (!jointMapping) { var avatarJointNames = Avatar.jointNames; var animationJointNames = animation.jointNames; - if (avatarJointNames === 0 || animationJointNames.length === 0) { + if (avatarJointNames.length === 0 || animationJointNames.length === 0) { return; } jointMapping = new Array(avatarJointNames.length); From e75d14139f0062dae884b92ce9845a7b4cea3e7c Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 17 Apr 2014 17:21:38 -0700 Subject: [PATCH 488/595] fix avatar kill behaviour --- interface/src/avatar/AvatarManager.cpp | 4 ++++ interface/src/avatar/AvatarManager.h | 2 ++ libraries/avatars/src/AvatarHashMap.cpp | 5 ++--- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/interface/src/avatar/AvatarManager.cpp b/interface/src/avatar/AvatarManager.cpp index b4969bae39..3ff41a85b1 100644 --- a/interface/src/avatar/AvatarManager.cpp +++ b/interface/src/avatar/AvatarManager.cpp @@ -148,6 +148,10 @@ void AvatarManager::processAvatarMixerDatagram(const QByteArray& datagram, const } } +AvatarSharedPointer AvatarManager::newSharedAvatar() { + return AvatarSharedPointer(new Avatar()); +} + AvatarHash::iterator AvatarManager::erase(const AvatarHash::iterator& iterator) { if (iterator.key() != MY_AVATAR_KEY) { qDebug() << "Removing Avatar with UUID" << iterator.key() << "from AvatarManager hash."; diff --git a/interface/src/avatar/AvatarManager.h b/interface/src/avatar/AvatarManager.h index 1b72052c7e..a31162ec1a 100644 --- a/interface/src/avatar/AvatarManager.h +++ b/interface/src/avatar/AvatarManager.h @@ -45,6 +45,8 @@ private: void simulateAvatarFades(float deltaTime); void renderAvatarFades(const glm::vec3& cameraPosition, Avatar::RenderMode renderMode); + AvatarSharedPointer newSharedAvatar(); + // virtual override AvatarHash::iterator erase(const AvatarHash::iterator& iterator); diff --git a/libraries/avatars/src/AvatarHashMap.cpp b/libraries/avatars/src/AvatarHashMap.cpp index 5f2d27c1a6..f6ff848ffa 100644 --- a/libraries/avatars/src/AvatarHashMap.cpp +++ b/libraries/avatars/src/AvatarHashMap.cpp @@ -32,12 +32,11 @@ const qint64 AVATAR_SILENCE_THRESHOLD_MSECS = 5 * 1000; bool AvatarHashMap::shouldKillAvatar(const AvatarSharedPointer& sharedAvatar) { return (sharedAvatar->getOwningAvatarMixer() == NULL - && sharedAvatar->getLastUpdateTimer().elapsed() > AVATAR_SILENCE_THRESHOLD_MSECS); + || sharedAvatar->getLastUpdateTimer().elapsed() > AVATAR_SILENCE_THRESHOLD_MSECS); } AvatarSharedPointer AvatarHashMap::newSharedAvatar() { - AvatarData* avatarData = new AvatarData(); - return AvatarSharedPointer(avatarData); + return AvatarSharedPointer(new AvatarData()); } AvatarSharedPointer AvatarHashMap::matchingOrNewAvatar(const QUuid& sessionUUID, const QWeakPointer& mixerWeakPointer) { From 47d4ef0b2d6298bcee8d39a565ff15c806a2df06 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 17 Apr 2014 17:44:41 -0700 Subject: [PATCH 489/595] add a method to determine if avatar with display name exists --- interface/src/avatar/AvatarManager.h | 2 +- libraries/avatars/src/AvatarHashMap.cpp | 24 ++++++++++++++++++++++++ libraries/avatars/src/AvatarHashMap.h | 6 +++++- 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/interface/src/avatar/AvatarManager.h b/interface/src/avatar/AvatarManager.h index a31162ec1a..fd15554666 100644 --- a/interface/src/avatar/AvatarManager.h +++ b/interface/src/avatar/AvatarManager.h @@ -22,7 +22,7 @@ class MyAvatar; -class AvatarManager : public QObject, public AvatarHashMap { +class AvatarManager : public AvatarHashMap { Q_OBJECT public: AvatarManager(QObject* parent = 0); diff --git a/libraries/avatars/src/AvatarHashMap.cpp b/libraries/avatars/src/AvatarHashMap.cpp index f6ff848ffa..17fdaeb5bd 100644 --- a/libraries/avatars/src/AvatarHashMap.cpp +++ b/libraries/avatars/src/AvatarHashMap.cpp @@ -35,6 +35,30 @@ bool AvatarHashMap::shouldKillAvatar(const AvatarSharedPointer& sharedAvatar) { || sharedAvatar->getLastUpdateTimer().elapsed() > AVATAR_SILENCE_THRESHOLD_MSECS); } +bool AvatarHashMap::containsAvatarWithDisplayName(const QString& displayName) { + + AvatarHash::iterator avatarIterator = _avatarHash.begin(); + while (avatarIterator != _avatarHash.end()) { + AvatarSharedPointer sharedAvatar = avatarIterator.value(); + if (avatarIterator.value()->getDisplayName() == displayName) { + // this is a match + // check if this avatar should still be around + if (!shouldKillAvatar(sharedAvatar)) { + // we have a match, return true + return true; + } else { + // we should remove this avatar, do that now + erase(avatarIterator); + } + + break; + } + } + + // return false, no match + return false; +} + AvatarSharedPointer AvatarHashMap::newSharedAvatar() { return AvatarSharedPointer(new AvatarData()); } diff --git a/libraries/avatars/src/AvatarHashMap.h b/libraries/avatars/src/AvatarHashMap.h index 2db6c79ed2..98e64fb8de 100644 --- a/libraries/avatars/src/AvatarHashMap.h +++ b/libraries/avatars/src/AvatarHashMap.h @@ -23,7 +23,8 @@ typedef QSharedPointer AvatarSharedPointer; typedef QHash AvatarHash; -class AvatarHashMap { +class AvatarHashMap : public QObject { + Q_OBJECT public: AvatarHashMap(); @@ -31,6 +32,9 @@ public: int size() const { return _avatarHash.size(); } virtual void insert(const QUuid& id, AvatarSharedPointer avatar); + +public slots: + bool containsAvatarWithDisplayName(const QString& displayName); protected: virtual AvatarHash::iterator erase(const AvatarHash::iterator& iterator); From f8106e50639ddc459b7700c3b41aa427e4349782 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 17 Apr 2014 17:49:55 -0700 Subject: [PATCH 490/595] add an AvatarHashMap to the Agent --- assignment-client/src/Agent.cpp | 13 ++++++++++++- assignment-client/src/Agent.h | 2 ++ interface/src/avatar/AvatarManager.cpp | 19 ------------------- interface/src/avatar/AvatarManager.h | 3 --- libraries/avatars/src/AvatarHashMap.cpp | 21 ++++++++++++++++++++- libraries/avatars/src/AvatarHashMap.h | 1 + 6 files changed, 35 insertions(+), 24 deletions(-) diff --git a/assignment-client/src/Agent.cpp b/assignment-client/src/Agent.cpp index 2e4c251005..7f4e811c32 100644 --- a/assignment-client/src/Agent.cpp +++ b/assignment-client/src/Agent.cpp @@ -33,7 +33,8 @@ Agent::Agent(const QByteArray& packet) : ThreadedAssignment(packet), _voxelEditSender(), _particleEditSender(), - _receivedAudioBuffer(NETWORK_BUFFER_LENGTH_SAMPLES_STEREO) + _receivedAudioBuffer(NETWORK_BUFFER_LENGTH_SAMPLES_STEREO), + _avatarHashMap() { // be the parent of the script engine so it gets moved when we do _scriptEngine.setParent(this); @@ -131,6 +132,16 @@ void Agent::readPendingDatagrams() { // let this continue through to the NodeList so it updates last heard timestamp // for the sending audio mixer NodeList::getInstance()->processNodeData(senderSockAddr, receivedPacket); + } else if (datagramPacketType == PacketTypeAvatarData + || datagramPacketType == PacketTypeAvatarIdentity + || datagramPacketType == PacketTypeAvatarBillboard + || datagramPacketType == PacketTypeKillAvatar) { + // let the avatar hash map process it + _avatarHashMap.processAvatarMixerDatagram(receivedPacket, nodeList->sendingNodeForPacket(receivedPacket)); + + // let this continue through to the NodeList so it updates last heard timestamp + // for the sending avatar-mixer + NodeList::getInstance()->processNodeData(senderSockAddr, receivedPacket); } else { NodeList::getInstance()->processNodeData(senderSockAddr, receivedPacket); } diff --git a/assignment-client/src/Agent.h b/assignment-client/src/Agent.h index 2dcd7e3107..9f6a8089cf 100644 --- a/assignment-client/src/Agent.h +++ b/assignment-client/src/Agent.h @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -65,6 +66,7 @@ private: VoxelTreeHeadlessViewer _voxelViewer; MixedAudioRingBuffer _receivedAudioBuffer; + AvatarHashMap _avatarHashMap; }; #endif // hifi_Agent_h diff --git a/interface/src/avatar/AvatarManager.cpp b/interface/src/avatar/AvatarManager.cpp index 3ff41a85b1..f235d6f2e3 100644 --- a/interface/src/avatar/AvatarManager.cpp +++ b/interface/src/avatar/AvatarManager.cpp @@ -129,25 +129,6 @@ void AvatarManager::renderAvatarFades(const glm::vec3& cameraPosition, Avatar::R } } -void AvatarManager::processAvatarMixerDatagram(const QByteArray& datagram, const QWeakPointer& mixerWeakPointer) { - switch (packetTypeForPacket(datagram)) { - case PacketTypeBulkAvatarData: - processAvatarDataPacket(datagram, mixerWeakPointer); - break; - case PacketTypeAvatarIdentity: - processAvatarIdentityPacket(datagram, mixerWeakPointer); - break; - case PacketTypeAvatarBillboard: - processAvatarBillboardPacket(datagram, mixerWeakPointer); - break; - case PacketTypeKillAvatar: - processKillAvatar(datagram); - break; - default: - break; - } -} - AvatarSharedPointer AvatarManager::newSharedAvatar() { return AvatarSharedPointer(new Avatar()); } diff --git a/interface/src/avatar/AvatarManager.h b/interface/src/avatar/AvatarManager.h index fd15554666..048844ddf2 100644 --- a/interface/src/avatar/AvatarManager.h +++ b/interface/src/avatar/AvatarManager.h @@ -35,9 +35,6 @@ public: void renderAvatars(Avatar::RenderMode renderMode, bool selfAvatarOnly = false); void clearOtherAvatars(); - -public slots: - void processAvatarMixerDatagram(const QByteArray& datagram, const QWeakPointer& mixerWeakPointer); private: AvatarManager(const AvatarManager& other); diff --git a/libraries/avatars/src/AvatarHashMap.cpp b/libraries/avatars/src/AvatarHashMap.cpp index 17fdaeb5bd..01dba89b02 100644 --- a/libraries/avatars/src/AvatarHashMap.cpp +++ b/libraries/avatars/src/AvatarHashMap.cpp @@ -35,6 +35,25 @@ bool AvatarHashMap::shouldKillAvatar(const AvatarSharedPointer& sharedAvatar) { || sharedAvatar->getLastUpdateTimer().elapsed() > AVATAR_SILENCE_THRESHOLD_MSECS); } +void AvatarHashMap::processAvatarMixerDatagram(const QByteArray& datagram, const QWeakPointer& mixerWeakPointer) { + switch (packetTypeForPacket(datagram)) { + case PacketTypeBulkAvatarData: + processAvatarDataPacket(datagram, mixerWeakPointer); + break; + case PacketTypeAvatarIdentity: + processAvatarIdentityPacket(datagram, mixerWeakPointer); + break; + case PacketTypeAvatarBillboard: + processAvatarBillboardPacket(datagram, mixerWeakPointer); + break; + case PacketTypeKillAvatar: + processKillAvatar(datagram); + break; + default: + break; + } +} + bool AvatarHashMap::containsAvatarWithDisplayName(const QString& displayName) { AvatarHash::iterator avatarIterator = _avatarHash.begin(); @@ -70,7 +89,7 @@ AvatarSharedPointer AvatarHashMap::matchingOrNewAvatar(const QUuid& sessionUUID, // insert the new avatar into our hash matchingAvatar = newSharedAvatar(); - qDebug() << "Adding avatar with sessionUUID " << sessionUUID << "to AvatarManager hash."; + qDebug() << "Adding avatar with sessionUUID " << sessionUUID << "to AvatarHashMap."; _avatarHash.insert(sessionUUID, matchingAvatar); matchingAvatar->setOwningAvatarMixer(mixerWeakPointer); diff --git a/libraries/avatars/src/AvatarHashMap.h b/libraries/avatars/src/AvatarHashMap.h index 98e64fb8de..542a2d62ab 100644 --- a/libraries/avatars/src/AvatarHashMap.h +++ b/libraries/avatars/src/AvatarHashMap.h @@ -34,6 +34,7 @@ public: virtual void insert(const QUuid& id, AvatarSharedPointer avatar); public slots: + void processAvatarMixerDatagram(const QByteArray& datagram, const QWeakPointer& mixerWeakPointer); bool containsAvatarWithDisplayName(const QString& displayName); protected: From 75f35c58586ecd54a379ce00a0e10441c2a3d094 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 17 Apr 2014 17:55:16 -0700 Subject: [PATCH 491/595] optionally add an AvatarHashMap instance to the ScriptEngine --- assignment-client/src/Agent.cpp | 1 + libraries/script-engine/src/ScriptEngine.cpp | 8 ++++++++ libraries/script-engine/src/ScriptEngine.h | 2 ++ 3 files changed, 11 insertions(+) diff --git a/assignment-client/src/Agent.cpp b/assignment-client/src/Agent.cpp index 7f4e811c32..6b8dbde79f 100644 --- a/assignment-client/src/Agent.cpp +++ b/assignment-client/src/Agent.cpp @@ -202,6 +202,7 @@ void Agent::run() { // give this AvatarData object to the script engine _scriptEngine.setAvatarData(&scriptedAvatar, "Avatar"); + _scriptEngine.setAvatarHashMap(&_avatarHashMap, "AvatarHash"); // register ourselves to the script engine _scriptEngine.registerGlobalObject("Agent", this); diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index 950ba899de..684c55fbb0 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -156,6 +156,14 @@ void ScriptEngine::setAvatarData(AvatarData* avatarData, const QString& objectNa registerGlobalObject(objectName, _avatarData); } +void ScriptEngine::setAvatarHashMap(AvatarHashMap* avatarHashMap, const QString& objectName) { + // remove the old Avatar property, if it exists + _engine.globalObject().setProperty(objectName, QScriptValue()); + + // give the script engine the new avatar hash map + registerGlobalObject(objectName, avatarHashMap); +} + bool ScriptEngine::setScriptContents(const QString& scriptContents, const QString& fileNameString) { if (_isRunning) { return false; diff --git a/libraries/script-engine/src/ScriptEngine.h b/libraries/script-engine/src/ScriptEngine.h index 73747cd3e1..941c6bbe27 100644 --- a/libraries/script-engine/src/ScriptEngine.h +++ b/libraries/script-engine/src/ScriptEngine.h @@ -22,6 +22,7 @@ #include #include +#include #include "AnimationCache.h" #include "AbstractControllerScriptingInterface.h" @@ -63,6 +64,7 @@ public: bool isAvatar() const { return _isAvatar; } void setAvatarData(AvatarData* avatarData, const QString& objectName); + void setAvatarHashMap(AvatarHashMap* avatarHashMap, const QString& objectName); bool isListeningToAudioStream() const { return _isListeningToAudioStream; } void setIsListeningToAudioStream(bool isListeningToAudioStream) { _isListeningToAudioStream = isListeningToAudioStream; } From 77202af20d4db593caa6894de343d4a1dfe602a3 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 17 Apr 2014 18:05:22 -0700 Subject: [PATCH 492/595] add debug for erase from AvatarHashMap, repair check for display name --- assignment-client/src/Agent.cpp | 2 +- interface/src/avatar/AvatarManager.cpp | 1 - libraries/avatars/src/AvatarHashMap.cpp | 3 +++ 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/assignment-client/src/Agent.cpp b/assignment-client/src/Agent.cpp index 6b8dbde79f..0d2103c748 100644 --- a/assignment-client/src/Agent.cpp +++ b/assignment-client/src/Agent.cpp @@ -132,7 +132,7 @@ void Agent::readPendingDatagrams() { // let this continue through to the NodeList so it updates last heard timestamp // for the sending audio mixer NodeList::getInstance()->processNodeData(senderSockAddr, receivedPacket); - } else if (datagramPacketType == PacketTypeAvatarData + } else if (datagramPacketType == PacketTypeBulkAvatarData || datagramPacketType == PacketTypeAvatarIdentity || datagramPacketType == PacketTypeAvatarBillboard || datagramPacketType == PacketTypeKillAvatar) { diff --git a/interface/src/avatar/AvatarManager.cpp b/interface/src/avatar/AvatarManager.cpp index f235d6f2e3..59f31388f8 100644 --- a/interface/src/avatar/AvatarManager.cpp +++ b/interface/src/avatar/AvatarManager.cpp @@ -135,7 +135,6 @@ AvatarSharedPointer AvatarManager::newSharedAvatar() { AvatarHash::iterator AvatarManager::erase(const AvatarHash::iterator& iterator) { if (iterator.key() != MY_AVATAR_KEY) { - qDebug() << "Removing Avatar with UUID" << iterator.key() << "from AvatarManager hash."; if (reinterpret_cast(iterator.value().data())->isInitialized()) { _avatarFades.push_back(iterator.value()); } diff --git a/libraries/avatars/src/AvatarHashMap.cpp b/libraries/avatars/src/AvatarHashMap.cpp index 01dba89b02..6b17a3fab8 100644 --- a/libraries/avatars/src/AvatarHashMap.cpp +++ b/libraries/avatars/src/AvatarHashMap.cpp @@ -25,6 +25,7 @@ void AvatarHashMap::insert(const QUuid& id, AvatarSharedPointer avatar) { } AvatarHash::iterator AvatarHashMap::erase(const AvatarHash::iterator& iterator) { + qDebug() << "Removing Avatar with UUID" << iterator.key() << "from AvatarHashMap."; return _avatarHash.erase(iterator); } @@ -71,6 +72,8 @@ bool AvatarHashMap::containsAvatarWithDisplayName(const QString& displayName) { } break; + } else { + ++avatarIterator; } } From fa787adce2f26c7f4257508cb03fc45b890d84db Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 18 Apr 2014 08:55:32 -0700 Subject: [PATCH 493/595] added wet/dry mix, and alternate distance attenuation features --- examples/audioReflectorTools.js | 140 ++++++++++++++++++++++++++++-- interface/src/Application.cpp | 4 + interface/src/Audio.cpp | 1 + interface/src/Audio.h | 1 + interface/src/AudioReflector.cpp | 142 ++++++++++++++++++++++++++----- interface/src/AudioReflector.h | 47 ++++++++-- interface/src/Menu.cpp | 8 ++ interface/src/Menu.h | 4 + interface/src/ui/Stats.cpp | 19 ++++- 9 files changed, 327 insertions(+), 39 deletions(-) diff --git a/examples/audioReflectorTools.js b/examples/audioReflectorTools.js index 3cc6a1a21e..76869de578 100644 --- a/examples/audioReflectorTools.js +++ b/examples/audioReflectorTools.js @@ -19,6 +19,8 @@ var reflectiveScale = 100.0; var diffusionScale = 100.0; var absorptionScale = 100.0; var combFilterScale = 50.0; +var originalScale = 2.0; +var echoesScale = 2.0; // these three properties are bound together, if you change one, the others will also change var reflectiveRatio = AudioReflector.getReflectiveRatio(); @@ -421,6 +423,84 @@ var absorptionThumb = Overlays.addOverlay("image", { alpha: 1 }); +var originalY = topY; +topY += sliderHeight; + +var originalLabel = Overlays.addOverlay("text", { + x: 40, + y: originalY, + width: 60, + height: sliderHeight, + color: { red: 0, green: 0, blue: 0}, + textColor: { red: 255, green: 255, blue: 255}, + topMargin: 6, + leftMargin: 5, + text: "Original\nMix:" + }); + + +var originalSlider = Overlays.addOverlay("image", { + // alternate form of expressing bounds + bounds: { x: 100, y: originalY, width: 150, height: sliderHeight}, + subImage: { x: 46, y: 0, width: 200, height: 71 }, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/slider.png", + color: { red: 255, green: 255, blue: 255}, + alpha: 1 + }); + + +var originalMinThumbX = 110; +var originalMaxThumbX = originalMinThumbX + 110; +var originalThumbX = originalMinThumbX + ((originalMaxThumbX - originalMinThumbX) * (AudioReflector.getOriginalSourceAttenuation() / originalScale)); +var originalThumb = Overlays.addOverlay("image", { + x: originalThumbX, + y: originalY+9, + width: 18, + height: 17, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/thumb.png", + color: { red: 128, green: 128, blue: 0}, + alpha: 1 + }); + +var echoesY = topY; +topY += sliderHeight; + +var echoesLabel = Overlays.addOverlay("text", { + x: 40, + y: echoesY, + width: 60, + height: sliderHeight, + color: { red: 0, green: 0, blue: 0}, + textColor: { red: 255, green: 255, blue: 255}, + topMargin: 6, + leftMargin: 5, + text: "Echoes\nMix:" + }); + + +var echoesSlider = Overlays.addOverlay("image", { + // alternate form of expressing bounds + bounds: { x: 100, y: echoesY, width: 150, height: sliderHeight}, + subImage: { x: 46, y: 0, width: 200, height: 71 }, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/slider.png", + color: { red: 255, green: 255, blue: 255}, + alpha: 1 + }); + + +var echoesMinThumbX = 110; +var echoesMaxThumbX = echoesMinThumbX + 110; +var echoesThumbX = echoesMinThumbX + ((echoesMaxThumbX - echoesMinThumbX) * (AudioReflector.getEchoesAttenuation() / echoesScale)); +var echoesThumb = Overlays.addOverlay("image", { + x: echoesThumbX, + y: echoesY+9, + width: 18, + height: 17, + imageURL: "https://s3-us-west-1.amazonaws.com/highfidelity-public/images/thumb.png", + color: { red: 128, green: 128, blue: 0}, + alpha: 1 + }); + // When our script shuts down, we should clean up all of our overlays function scriptEnding() { @@ -460,6 +540,14 @@ function scriptEnding() { Overlays.deleteOverlay(absorptionThumb); Overlays.deleteOverlay(absorptionSlider); + Overlays.deleteOverlay(echoesLabel); + Overlays.deleteOverlay(echoesThumb); + Overlays.deleteOverlay(echoesSlider); + + Overlays.deleteOverlay(originalLabel); + Overlays.deleteOverlay(originalThumb); + Overlays.deleteOverlay(originalSlider); + } Script.scriptEnding.connect(scriptEnding); @@ -483,6 +571,8 @@ var movingSliderLocalFactor = false; var movingSliderReflective = false; var movingSliderDiffusion = false; var movingSliderAbsorption = false; +var movingSliderOriginal = false; +var movingSliderEchoes = false; var thumbClickOffsetX = 0; function mouseMoveEvent(event) { @@ -546,7 +636,6 @@ function mouseMoveEvent(event) { var combFilter = ((newThumbX - combFilterMinThumbX) / (combFilterMaxThumbX - combFilterMinThumbX)) * combFilterScale; AudioReflector.setCombFilterWindow(combFilter); } - if (movingSliderLocalFactor) { newThumbX = event.x - thumbClickOffsetX; if (newThumbX < localFactorMinThumbX) { @@ -598,6 +687,30 @@ function mouseMoveEvent(event) { var diffusion = ((newThumbX - diffusionMinThumbX) / (diffusionMaxThumbX - diffusionMinThumbX)) * diffusionScale; setDiffusionRatio(diffusion); } + if (movingSliderEchoes) { + newThumbX = event.x - thumbClickOffsetX; + if (newThumbX < echoesMinThumbX) { + newThumbX = echoesMminThumbX; + } + if (newThumbX > echoesMaxThumbX) { + newThumbX = echoesMaxThumbX; + } + Overlays.editOverlay(echoesThumb, { x: newThumbX } ); + var echoes = ((newThumbX - echoesMinThumbX) / (echoesMaxThumbX - echoesMinThumbX)) * echoesScale; + AudioReflector.setEchoesAttenuation(echoes); + } + if (movingSliderOriginal) { + newThumbX = event.x - thumbClickOffsetX; + if (newThumbX < originalMinThumbX) { + newThumbX = originalMminThumbX; + } + if (newThumbX > originalMaxThumbX) { + newThumbX = originalMaxThumbX; + } + Overlays.editOverlay(originalThumb, { x: newThumbX } ); + var original = ((newThumbX - originalMinThumbX) / (originalMaxThumbX - originalMinThumbX)) * originalScale; + AudioReflector.setOriginalSourceAttenuation(original); + } } @@ -640,7 +753,16 @@ function mousePressEvent(event) { movingSliderReflective = true; thumbClickOffsetX = event.x - reflectiveThumbX; } + if (clickedOverlay == originalThumb) { + movingSliderOriginal = true; + thumbClickOffsetX = event.x - originalThumbX; + } + if (clickedOverlay == echoesThumb) { + movingSliderEchoes = true; + thumbClickOffsetX = event.x - echoesThumbX; + } } + function mouseReleaseEvent(event) { if (movingSliderDelay) { movingSliderDelay = false; @@ -672,14 +794,12 @@ function mouseReleaseEvent(event) { AudioReflector.setCombFilterWindow(combFilter); combFilterThumbX = newThumbX; } - if (movingSliderLocalFactor) { movingSliderLocalFactor = false; var localFactor = ((newThumbX - localFactorMinThumbX) / (localFactorMaxThumbX - localFactorMinThumbX)) * localFactorScale; AudioReflector.setLocalAudioAttenuationFactor(localFactor); localFactorThumbX = newThumbX; } - if (movingSliderReflective) { movingSliderReflective = false; var reflective = ((newThumbX - reflectiveMinThumbX) / (reflectiveMaxThumbX - reflectiveMinThumbX)) * reflectiveScale; @@ -687,7 +807,6 @@ function mouseReleaseEvent(event) { reflectiveThumbX = newThumbX; updateRatioSliders(); } - if (movingSliderDiffusion) { movingSliderDiffusion = false; var diffusion = ((newThumbX - diffusionMinThumbX) / (diffusionMaxThumbX - diffusionMinThumbX)) * diffusionScale; @@ -695,7 +814,6 @@ function mouseReleaseEvent(event) { diffusionThumbX = newThumbX; updateRatioSliders(); } - if (movingSliderAbsorption) { movingSliderAbsorption = false; var absorption = ((newThumbX - absorptionMinThumbX) / (absorptionMaxThumbX - absorptionMinThumbX)) * absorptionScale; @@ -703,6 +821,18 @@ function mouseReleaseEvent(event) { absorptionThumbX = newThumbX; updateRatioSliders(); } + if (movingSliderEchoes) { + movingSliderEchoes = false; + var echoes = ((newThumbX - echoesMinThumbX) / (echoesMaxThumbX - echoesMinThumbX)) * echoesScale; + AudioReflector.setEchoesAttenuation(echoes); + echoesThumbX = newThumbX; + } + if (movingSliderOriginal) { + movingSliderOriginal = false; + var original = ((newThumbX - originalMinThumbX) / (originalMaxThumbX - originalMinThumbX)) * originalScale; + AudioReflector.setOriginalSourceAttenuation(original); + originalThumbX = newThumbX; + } } Controller.mouseMoveEvent.connect(mouseMoveEvent); diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index bd7a82b439..7480b16334 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1679,8 +1679,12 @@ void Application::init() { _audioReflector.setMyAvatar(getAvatar()); _audioReflector.setVoxels(_voxels.getTree()); _audioReflector.setAudio(getAudio()); + _audioReflector.setAvatarManager(&_avatarManager); + connect(getAudio(), &Audio::processInboundAudio, &_audioReflector, &AudioReflector::processInboundAudio,Qt::DirectConnection); connect(getAudio(), &Audio::processLocalAudio, &_audioReflector, &AudioReflector::processLocalAudio,Qt::DirectConnection); + connect(getAudio(), &Audio::preProcessOriginalInboundAudio, &_audioReflector, + &AudioReflector::preProcessOriginalInboundAudio,Qt::DirectConnection); // save settings when avatar changes connect(_myAvatar, &MyAvatar::transformChanged, this, &Application::bumpSettings); diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index daa7c036eb..830e2fe69b 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -784,6 +784,7 @@ void Audio::processReceivedAudio(const QByteArray& audioByteArray) { _ringBuffer.readSamples((int16_t*)buffer.data(), numNetworkOutputSamples); // Accumulate direct transmission of audio from sender to receiver if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingIncludeOriginal)) { + emit preProcessOriginalInboundAudio(sampleTime, buffer, _desiredOutputFormat); addSpatialAudioToBuffer(sampleTime, buffer, numNetworkOutputSamples); } diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 3b19d98146..96def43dd2 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -99,6 +99,7 @@ public slots: signals: bool muteToggled(); + void preProcessOriginalInboundAudio(unsigned int sampleTime, QByteArray& samples, const QAudioFormat& format); void processInboundAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); void processLocalAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 52558f1d59..67b6120354 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -25,6 +25,8 @@ const float SLIGHTLY_SHORT = 0.999f; // slightly inside the distance so we're on const float DEFAULT_ABSORPTION_RATIO = 0.125; // 12.5% is absorbed const float DEFAULT_DIFFUSION_RATIO = 0.125; // 12.5% is diffused +const float DEFAULT_ORIGINAL_ATTENUATION = 1.0f; +const float DEFAULT_ECHO_ATTENUATION = 1.0f; AudioReflector::AudioReflector(QObject* parent) : QObject(parent), @@ -36,6 +38,8 @@ AudioReflector::AudioReflector(QObject* parent) : _diffusionFanout(DEFAULT_DIFFUSION_FANOUT), _absorptionRatio(DEFAULT_ABSORPTION_RATIO), _diffusionRatio(DEFAULT_DIFFUSION_RATIO), + _originalSourceAttenuation(DEFAULT_ORIGINAL_ATTENUATION), + _allEchoesAttenuation(DEFAULT_ECHO_ATTENUATION), _withDiffusion(false), _lastPreDelay(DEFAULT_PRE_DELAY), _lastSoundMsPerMeter(DEFAULT_MS_DELAY_PER_METER), @@ -43,20 +47,29 @@ AudioReflector::AudioReflector(QObject* parent) : _lastLocalAudioAttenuationFactor(DEFAULT_LOCAL_ATTENUATION_FACTOR), _lastDiffusionFanout(DEFAULT_DIFFUSION_FANOUT), _lastAbsorptionRatio(DEFAULT_ABSORPTION_RATIO), - _lastDiffusionRatio(DEFAULT_DIFFUSION_RATIO) + _lastDiffusionRatio(DEFAULT_DIFFUSION_RATIO), + _lastDontDistanceAttenuate(false), + _lastAlternateDistanceAttenuate(false) { _reflections = 0; _diffusionPathCount = 0; - _averageAttenuation = 0.0f; - _maxAttenuation = 0.0f; - _minAttenuation = 0.0f; - _averageDelay = 0; - _maxDelay = 0; - _minDelay = 0; + _averageAttenuationOfficial = _averageAttenuation = 0.0f; + _maxAttenuationOfficial = _maxAttenuation = 0.0f; + _minAttenuationOfficial = _minAttenuation = 0.0f; + _averageDelayOfficial = _averageDelay = 0; + _maxDelayOfficial = _maxDelay = 0; + _minDelayOfficial = _minDelay = 0; + _inboundEchoesCount = 0; + _inboundEchoesSuppressedCount = 0; + _localEchoesCount = 0; + _localEchoesSuppressedCount = 0; } bool AudioReflector::haveAttributesChanged() { bool withDiffusion = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions); + bool dontDistanceAttenuate = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingDontDistanceAttenuate); + bool alternateDistanceAttenuate = Menu::getInstance()->isOptionChecked( + MenuOption::AudioSpatialProcessingAlternateDistanceAttenuate); bool attributesChange = (_withDiffusion != withDiffusion || _lastPreDelay != _preDelay @@ -64,7 +77,9 @@ bool AudioReflector::haveAttributesChanged() { || _lastDistanceAttenuationScalingFactor != _distanceAttenuationScalingFactor || _lastDiffusionFanout != _diffusionFanout || _lastAbsorptionRatio != _absorptionRatio - || _lastDiffusionRatio != _diffusionRatio); + || _lastDiffusionRatio != _diffusionRatio + || _lastDontDistanceAttenuate != dontDistanceAttenuate + || _lastAlternateDistanceAttenuate != alternateDistanceAttenuate); if (attributesChange) { _withDiffusion = withDiffusion; @@ -74,6 +89,8 @@ bool AudioReflector::haveAttributesChanged() { _lastDiffusionFanout = _diffusionFanout; _lastAbsorptionRatio = _absorptionRatio; _lastDiffusionRatio = _diffusionRatio; + _lastDontDistanceAttenuate = dontDistanceAttenuate; + _lastAlternateDistanceAttenuate = alternateDistanceAttenuate; } return attributesChange; @@ -107,19 +124,47 @@ float AudioReflector::getDelayFromDistance(float distance) { // attenuation = from the Audio Mixer float AudioReflector::getDistanceAttenuationCoefficient(float distance) { - const float DISTANCE_SCALE = 2.5f; - const float GEOMETRIC_AMPLITUDE_SCALAR = 0.3f; - const float DISTANCE_LOG_BASE = 2.5f; - const float DISTANCE_SCALE_LOG = logf(DISTANCE_SCALE) / logf(DISTANCE_LOG_BASE); + + + bool doDistanceAttenuation = !Menu::getInstance()->isOptionChecked( + MenuOption::AudioSpatialProcessingDontDistanceAttenuate); + + bool originalFormula = !Menu::getInstance()->isOptionChecked( + MenuOption::AudioSpatialProcessingAlternateDistanceAttenuate); - float distanceSquareToSource = distance * distance; + + float distanceCoefficient = 1.0f; + + if (doDistanceAttenuation) { + + if (originalFormula) { + const float DISTANCE_SCALE = 2.5f; + const float GEOMETRIC_AMPLITUDE_SCALAR = 0.3f; + const float DISTANCE_LOG_BASE = 2.5f; + const float DISTANCE_SCALE_LOG = logf(DISTANCE_SCALE) / logf(DISTANCE_LOG_BASE); + + float distanceSquareToSource = distance * distance; - // calculate the distance coefficient using the distance to this node - float distanceCoefficient = powf(GEOMETRIC_AMPLITUDE_SCALAR, - DISTANCE_SCALE_LOG + - (0.5f * logf(distanceSquareToSource) / logf(DISTANCE_LOG_BASE)) - 1); - - distanceCoefficient = std::min(1.0f, distanceCoefficient * getDistanceAttenuationScalingFactor()); + // calculate the distance coefficient using the distance to this node + distanceCoefficient = powf(GEOMETRIC_AMPLITUDE_SCALAR, + DISTANCE_SCALE_LOG + + (0.5f * logf(distanceSquareToSource) / logf(DISTANCE_LOG_BASE)) - 1); + distanceCoefficient = std::min(1.0f, distanceCoefficient * getDistanceAttenuationScalingFactor()); + } else { + + // From Fred: If we wanted something that would produce a tail that could go up to 5 seconds in a + // really big room, that would suggest the sound still has to be in the audible after traveling about + // 1500 meters. If it’s a sound of average volume, we probably have about 30 db, or 5 base2 orders + // of magnitude we can drop down before the sound becomes inaudible. (That’s approximate headroom + // based on a few sloppy assumptions.) So we could try a factor like 1 / (2^(D/300)) for starters. + // 1 / (2^(D/300)) + const float DISTANCE_BASE = 2.0f; + const float DISTANCE_DENOMINATOR = 300.0f; + const float DISTANCE_NUMERATOR = 300.0f; + distanceCoefficient = DISTANCE_NUMERATOR / powf(DISTANCE_BASE, (distance / DISTANCE_DENOMINATOR )); + distanceCoefficient = std::min(1.0f, distanceCoefficient * getDistanceAttenuationScalingFactor()); + } + } return distanceCoefficient; } @@ -236,11 +281,13 @@ void AudioReflector::injectAudiblePoint(AudioSource source, const AudiblePoint& rightSample = originalSamplesData[(sample * NUMBER_OF_CHANNELS) + 1]; } - attenuatedLeftSamplesData[sample * NUMBER_OF_CHANNELS] = leftSample * leftEarAttenuation; + attenuatedLeftSamplesData[sample * NUMBER_OF_CHANNELS] = + leftSample * leftEarAttenuation * _allEchoesAttenuation; attenuatedLeftSamplesData[sample * NUMBER_OF_CHANNELS + 1] = 0; attenuatedRightSamplesData[sample * NUMBER_OF_CHANNELS] = 0; - attenuatedRightSamplesData[sample * NUMBER_OF_CHANNELS + 1] = rightSample * rightEarAttenuation; + attenuatedRightSamplesData[sample * NUMBER_OF_CHANNELS + 1] = + rightSample * rightEarAttenuation * _allEchoesAttenuation; } // now inject the attenuated array with the appropriate delay @@ -249,9 +296,25 @@ void AudioReflector::injectAudiblePoint(AudioSource source, const AudiblePoint& _audio->addSpatialAudioToBuffer(sampleTimeLeft, attenuatedLeftSamples, totalNumberOfSamples); _audio->addSpatialAudioToBuffer(sampleTimeRight, attenuatedRightSamples, totalNumberOfSamples); + + _injectedEchoes++; } } + +void AudioReflector::preProcessOriginalInboundAudio(unsigned int sampleTime, + QByteArray& samples, const QAudioFormat& format) { + + if (_originalSourceAttenuation != 1.0f) { + int numberOfSamples = (samples.size() / sizeof(int16_t)); + int16_t* sampleData = (int16_t*)samples.data(); + for (int i = 0; i < numberOfSamples; i++) { + sampleData[i] = sampleData[i] * _originalSourceAttenuation; + } + } + +} + void AudioReflector::processLocalAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { if (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingProcessLocalAudio)) { const int NUM_CHANNELS_INPUT = 1; @@ -272,6 +335,8 @@ void AudioReflector::processLocalAudio(unsigned int sampleTime, const QByteArray _localAudioDelays.clear(); _localEchoesSuppressed.clear(); echoAudio(LOCAL_AUDIO, sampleTime, stereoInputData, outputFormat); + _localEchoesCount = _localAudioDelays.size(); + _localEchoesSuppressedCount = _localEchoesSuppressed.size(); } } } @@ -280,9 +345,13 @@ void AudioReflector::processInboundAudio(unsigned int sampleTime, const QByteArr _inboundAudioDelays.clear(); _inboundEchoesSuppressed.clear(); echoAudio(INBOUND_AUDIO, sampleTime, samples, format); + _inboundEchoesCount = _inboundAudioDelays.size(); + _inboundEchoesSuppressedCount = _inboundEchoesSuppressed.size(); } void AudioReflector::echoAudio(AudioSource source, unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format) { + QMutexLocker locker(&_mutex); + _maxDelay = 0; _maxAttenuation = 0.0f; _minDelay = std::numeric_limits::max(); @@ -292,14 +361,20 @@ void AudioReflector::echoAudio(AudioSource source, unsigned int sampleTime, cons _totalAttenuation = 0.0f; _attenuationCount = 0; - QMutexLocker locker(&_mutex); - // depending on if we're processing local or external audio, pick the correct points vector QVector& audiblePoints = source == INBOUND_AUDIO ? _inboundAudiblePoints : _localAudiblePoints; + int injectCalls = 0; + _injectedEchoes = 0; foreach(const AudiblePoint& audiblePoint, audiblePoints) { + injectCalls++; injectAudiblePoint(source, audiblePoint, samples, sampleTime, format.sampleRate()); } + + /* + qDebug() << "injectCalls=" << injectCalls; + qDebug() << "_injectedEchoes=" << _injectedEchoes; + */ _averageDelay = _delayCount == 0 ? 0 : _totalDelay / _delayCount; _averageAttenuation = _attenuationCount == 0 ? 0 : _totalAttenuation / _attenuationCount; @@ -308,6 +383,14 @@ void AudioReflector::echoAudio(AudioSource source, unsigned int sampleTime, cons _minDelay = 0.0f; _minAttenuation = 0.0f; } + + _maxDelayOfficial = _maxDelay; + _minDelayOfficial = _minDelay; + _maxAttenuationOfficial = _maxAttenuation; + _minAttenuationOfficial = _minAttenuation; + _averageDelayOfficial = _averageDelay; + _averageAttenuationOfficial = _averageAttenuation; + } void AudioReflector::drawVector(const glm::vec3& start, const glm::vec3& end, const glm::vec3& color) { @@ -359,6 +442,19 @@ void AudioReflector::addAudioPath(AudioSource source, const glm::vec3& origin, c audioPaths.push_back(path); } +// NOTE: This is a prototype of an eventual utility that will identify the speaking sources for the inbound audio +// stream. It's not currently called but will be added soon. +void AudioReflector::identifyAudioSources() { + // looking for audio sources.... + foreach (const AvatarSharedPointer& avatarPointer, _avatarManager->getAvatarHash()) { + Avatar* avatar = static_cast(avatarPointer.data()); + if (!avatar->isInitialized()) { + continue; + } + qDebug() << "avatar["<< avatar <<"] loudness:" << avatar->getAudioLoudness(); + } +} + void AudioReflector::calculateAllReflections() { // only recalculate when we've moved, or if the attributes have changed // TODO: what about case where new voxels are added in front of us??? diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 2408b70a96..cd5aaad276 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -15,6 +15,7 @@ #include "Audio.h" #include "avatar/MyAvatar.h" +#include "avatar/AvatarManager.h" enum AudioSource { LOCAL_AUDIO, @@ -69,25 +70,27 @@ public: void setVoxels(VoxelTree* voxels) { _voxels = voxels; } void setMyAvatar(MyAvatar* myAvatar) { _myAvatar = myAvatar; } void setAudio(Audio* audio) { _audio = audio; } + void setAvatarManager(AvatarManager* avatarManager) { _avatarManager = avatarManager; } void render(); /// must be called in the application render loop + void preProcessOriginalInboundAudio(unsigned int sampleTime, QByteArray& samples, const QAudioFormat& format); void processInboundAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); void processLocalAudio(unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); public slots: // statistics int getReflections() const { return _reflections; } - float getAverageDelayMsecs() const { return _averageDelay; } - float getAverageAttenuation() const { return _averageAttenuation; } - float getMaxDelayMsecs() const { return _maxDelay; } - float getMaxAttenuation() const { return _maxAttenuation; } - float getMinDelayMsecs() const { return _minDelay; } - float getMinAttenuation() const { return _minAttenuation; } + float getAverageDelayMsecs() const { return _averageDelayOfficial; } + float getAverageAttenuation() const { return _averageAttenuationOfficial; } + float getMaxDelayMsecs() const { return _maxDelayOfficial; } + float getMaxAttenuation() const { return _maxAttenuationOfficial; } + float getMinDelayMsecs() const { return _minDelayOfficial; } + float getMinAttenuation() const { return _minAttenuationOfficial; } float getDelayFromDistance(float distance); int getDiffusionPathCount() const { return _diffusionPathCount; } - int getEchoesInjected() const { return _inboundAudioDelays.size() + _localAudioDelays.size(); } - int getEchoesSuppressed() const { return _inboundEchoesSuppressed.size() + _localEchoesSuppressed.size(); } + int getEchoesInjected() const { return _inboundEchoesCount + _localEchoesCount; } + int getEchoesSuppressed() const { return _inboundEchoesSuppressedCount + _localEchoesSuppressedCount; } /// ms of delay added to all echos float getPreDelay() const { return _preDelay; } @@ -126,12 +129,19 @@ public slots: float getReflectiveRatio() const { return (1.0f - (_absorptionRatio + _diffusionRatio)); } void setReflectiveRatio(float ratio); + // wet/dry mix - these don't affect any reflection calculations, only the final mix volumes + float getOriginalSourceAttenuation() const { return _originalSourceAttenuation; } + void setOriginalSourceAttenuation(float value) { _originalSourceAttenuation = value; } + float getEchoesAttenuation() const { return _allEchoesAttenuation; } + void setEchoesAttenuation(float value) { _allEchoesAttenuation = value; } + signals: private: VoxelTree* _voxels; // used to access voxel scene MyAvatar* _myAvatar; // access to listener Audio* _audio; // access to audio API + AvatarManager* _avatarManager; // access to avatar manager API // Helpers for drawing void drawVector(const glm::vec3& start, const glm::vec3& end, const glm::vec3& color); @@ -147,11 +157,18 @@ private: float _averageDelay; float _maxDelay; float _minDelay; + float _averageDelayOfficial; + float _maxDelayOfficial; + float _minDelayOfficial; int _attenuationCount; float _totalAttenuation; float _averageAttenuation; float _maxAttenuation; float _minAttenuation; + float _averageAttenuationOfficial; + float _maxAttenuationOfficial; + float _minAttenuationOfficial; + glm::vec3 _listenerPosition; glm::vec3 _origin; @@ -161,11 +178,15 @@ private: QVector _inboundAudiblePoints; /// the audible points that have been calculated from the inbound audio paths QMap _inboundAudioDelays; /// delay times for currently injected audio points QVector _inboundEchoesSuppressed; /// delay times for currently injected audio points + int _inboundEchoesCount; + int _inboundEchoesSuppressedCount; QVector _localAudioPaths; /// audio paths we're processing for local audio QVector _localAudiblePoints; /// the audible points that have been calculated from the local audio paths QMap _localAudioDelays; /// delay times for currently injected audio points QVector _localEchoesSuppressed; /// delay times for currently injected audio points + int _localEchoesCount; + int _localEchoesSuppressedCount; // adds a sound source to begin an audio path trace, these can be the initial sound sources with their directional properties, // as well as diffusion sound sources @@ -182,6 +203,7 @@ private: void calculateAllReflections(); int countDiffusionPaths(); glm::vec3 getFaceNormal(BoxFace face); + void identifyAudioSources(); void injectAudiblePoint(AudioSource source, const AudiblePoint& audiblePoint, const QByteArray& samples, unsigned int sampleTime, int sampleRate); void echoAudio(AudioSource source, unsigned int sampleTime, const QByteArray& samples, const QAudioFormat& format); @@ -197,13 +219,16 @@ private: float _distanceAttenuationScalingFactor; float _localAudioAttenuationFactor; float _combFilterWindow; - int _diffusionFanout; // number of points of diffusion from each reflection point // all elements have the same material for now... float _absorptionRatio; float _diffusionRatio; float _reflectiveRatio; + + // wet/dry mix - these don't affect any reflection calculations, only the final mix volumes + float _originalSourceAttenuation; /// each sample of original signal will be multiplied by this + float _allEchoesAttenuation; /// each sample of all echo signals will be multiplied by this // remember the last known values at calculation bool haveAttributesChanged(); @@ -216,6 +241,10 @@ private: int _lastDiffusionFanout; float _lastAbsorptionRatio; float _lastDiffusionRatio; + bool _lastDontDistanceAttenuate; + bool _lastAlternateDistanceAttenuate; + + int _injectedEchoes; }; diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 85c3d5b0c3..b05e5c91bc 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -429,6 +429,14 @@ Menu::Menu() : Qt::CTRL | Qt::SHIFT | Qt::Key_A, true); + addCheckableActionToQMenuAndActionHash(spatialAudioMenu, MenuOption::AudioSpatialProcessingDontDistanceAttenuate, + Qt::CTRL | Qt::SHIFT | Qt::Key_Y, + false); + + addCheckableActionToQMenuAndActionHash(spatialAudioMenu, MenuOption::AudioSpatialProcessingAlternateDistanceAttenuate, + Qt::CTRL | Qt::SHIFT | Qt::Key_U, + false); + addActionToQMenuAndActionHash(developerMenu, MenuOption::PasteToVoxel, Qt::CTRL | Qt::SHIFT | Qt::Key_V, this, diff --git a/interface/src/Menu.h b/interface/src/Menu.h index a62f54b0c6..c17c9cc507 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -268,6 +268,10 @@ namespace MenuOption { const QString AudioSpatialProcessingSlightlyRandomSurfaces = "Slightly Random Surfaces"; const QString AudioSpatialProcessingStereoSource = "Stereo Source"; const QString AudioSpatialProcessingWithDiffusions = "With Diffusions"; + const QString AudioSpatialProcessingDontDistanceAttenuate = "Don't calculate distance attenuation"; + const QString AudioSpatialProcessingAlternateDistanceAttenuate = "Alternate distance attenuation"; + + const QString Avatars = "Avatars"; const QString Bandwidth = "Bandwidth Display"; diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp index 64616cbdf8..a2d615e04d 100644 --- a/interface/src/ui/Stats.cpp +++ b/interface/src/ui/Stats.cpp @@ -343,7 +343,7 @@ void Stats::display( lines = _expanded ? 12 : 3; if (_expanded && Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessing)) { - lines += 8; // spatial audio processing adds 1 spacing line and 7 extra lines of info + lines += 9; // spatial audio processing adds 1 spacing line and 8 extra lines of info } drawBackground(backgroundColor, horizontalOffset, 0, glWidget->width() - horizontalOffset, lines * STATS_PELS_PER_LINE + 10); @@ -540,11 +540,19 @@ void Stats::display( verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + + bool distanceAttenuationDisabled = Menu::getInstance()->isOptionChecked( + MenuOption::AudioSpatialProcessingDontDistanceAttenuate); - sprintf(reflectionsStatus, "Attenuation: average %5.3f, max %5.3f, min %5.3f, Factor: %5.3f", + bool alternateDistanceAttenuationEnabled = Menu::getInstance()->isOptionChecked( + MenuOption::AudioSpatialProcessingAlternateDistanceAttenuate); + + sprintf(reflectionsStatus, "Attenuation: average %5.3f, max %5.3f, min %5.3f, %s: %5.3f", audioReflector->getAverageAttenuation(), audioReflector->getMaxAttenuation(), audioReflector->getMinAttenuation(), + (distanceAttenuationDisabled ? "Distance Factor [DISABLED]" : + alternateDistanceAttenuationEnabled ? "Distance Factor [ALTERNATE]" : "Distance Factor [STANARD]"), audioReflector->getDistanceAttenuationScalingFactor()); verticalOffset += STATS_PELS_PER_LINE; @@ -585,6 +593,13 @@ void Stats::display( verticalOffset += STATS_PELS_PER_LINE; drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + sprintf(reflectionsStatus, "Wet/Dry Mix: Original: %5.3f Echoes: %5.3f", + audioReflector->getOriginalSourceAttenuation(), + audioReflector->getEchoesAttenuation()); + + verticalOffset += STATS_PELS_PER_LINE; + drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + } } From 9713edbba90eaf3a5055ad55731da8c267185d93 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 18 Apr 2014 09:00:43 -0700 Subject: [PATCH 494/595] Update dancing_bot.js conceal URL from dancing_bot script (even though it will stay in history) --- examples/dancing_bot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/dancing_bot.js b/examples/dancing_bot.js index 3572cc5a11..7924614d82 100644 --- a/examples/dancing_bot.js +++ b/examples/dancing_bot.js @@ -11,7 +11,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -var animation = AnimationCache.getAnimation("http://www.fungibleinsight.com/faces/gangnam_style_2.fbx"); +var animation = AnimationCache.getAnimation("FBX_URL"); Avatar.skeletonModelURL = "http://www.fungibleinsight.com/faces/beta.fst"; From 6adfb91e935ba472d301fb1c0ee79486a964151d Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 18 Apr 2014 09:40:35 -0700 Subject: [PATCH 495/595] rename AvatarHash to AvatarList --- assignment-client/src/Agent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assignment-client/src/Agent.cpp b/assignment-client/src/Agent.cpp index 0d2103c748..e39cb39307 100644 --- a/assignment-client/src/Agent.cpp +++ b/assignment-client/src/Agent.cpp @@ -202,7 +202,7 @@ void Agent::run() { // give this AvatarData object to the script engine _scriptEngine.setAvatarData(&scriptedAvatar, "Avatar"); - _scriptEngine.setAvatarHashMap(&_avatarHashMap, "AvatarHash"); + _scriptEngine.setAvatarHashMap(&_avatarHashMap, "AvatarList"); // register ourselves to the script engine _scriptEngine.registerGlobalObject("Agent", this); From 2dc39512a2ef555b11831e036a51de8f23f25c92 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 18 Apr 2014 10:19:09 -0700 Subject: [PATCH 496/595] CR feedback --- interface/src/AudioReflector.cpp | 24 ++++++++++++------------ interface/src/AudioReflector.h | 24 ++++++++++++------------ 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/interface/src/AudioReflector.cpp b/interface/src/AudioReflector.cpp index 67b6120354..e66735c403 100644 --- a/interface/src/AudioReflector.cpp +++ b/interface/src/AudioReflector.cpp @@ -53,12 +53,12 @@ AudioReflector::AudioReflector(QObject* parent) : { _reflections = 0; _diffusionPathCount = 0; - _averageAttenuationOfficial = _averageAttenuation = 0.0f; - _maxAttenuationOfficial = _maxAttenuation = 0.0f; - _minAttenuationOfficial = _minAttenuation = 0.0f; - _averageDelayOfficial = _averageDelay = 0; - _maxDelayOfficial = _maxDelay = 0; - _minDelayOfficial = _minDelay = 0; + _officialAverageAttenuation = _averageAttenuation = 0.0f; + _officialMaxAttenuation = _maxAttenuation = 0.0f; + _officialMinAttenuation = _minAttenuation = 0.0f; + _officialAverageDelay = _averageDelay = 0; + _officialMaxDelay = _maxDelay = 0; + _officialMinDelay = _minDelay = 0; _inboundEchoesCount = 0; _inboundEchoesSuppressedCount = 0; _localEchoesCount = 0; @@ -384,12 +384,12 @@ void AudioReflector::echoAudio(AudioSource source, unsigned int sampleTime, cons _minAttenuation = 0.0f; } - _maxDelayOfficial = _maxDelay; - _minDelayOfficial = _minDelay; - _maxAttenuationOfficial = _maxAttenuation; - _minAttenuationOfficial = _minAttenuation; - _averageDelayOfficial = _averageDelay; - _averageAttenuationOfficial = _averageAttenuation; + _officialMaxDelay = _maxDelay; + _officialMinDelay = _minDelay; + _officialMaxAttenuation = _maxAttenuation; + _officialMinAttenuation = _minAttenuation; + _officialAverageDelay = _averageDelay; + _officialAverageAttenuation = _averageAttenuation; } diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index cd5aaad276..582345e064 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -81,12 +81,12 @@ public: public slots: // statistics int getReflections() const { return _reflections; } - float getAverageDelayMsecs() const { return _averageDelayOfficial; } - float getAverageAttenuation() const { return _averageAttenuationOfficial; } - float getMaxDelayMsecs() const { return _maxDelayOfficial; } - float getMaxAttenuation() const { return _maxAttenuationOfficial; } - float getMinDelayMsecs() const { return _minDelayOfficial; } - float getMinAttenuation() const { return _minAttenuationOfficial; } + float getAverageDelayMsecs() const { return _officialAverageDelay; } + float getAverageAttenuation() const { return _officialAverageAttenuation; } + float getMaxDelayMsecs() const { return _officialMaxDelay; } + float getMaxAttenuation() const { return _officialMaxAttenuation; } + float getMinDelayMsecs() const { return _officialMinDelay; } + float getMinAttenuation() const { return _officialMinAttenuation; } float getDelayFromDistance(float distance); int getDiffusionPathCount() const { return _diffusionPathCount; } int getEchoesInjected() const { return _inboundEchoesCount + _localEchoesCount; } @@ -157,17 +157,17 @@ private: float _averageDelay; float _maxDelay; float _minDelay; - float _averageDelayOfficial; - float _maxDelayOfficial; - float _minDelayOfficial; + float _officialAverageDelay; + float _officialMaxDelay; + float _officialMinDelay; int _attenuationCount; float _totalAttenuation; float _averageAttenuation; float _maxAttenuation; float _minAttenuation; - float _averageAttenuationOfficial; - float _maxAttenuationOfficial; - float _minAttenuationOfficial; + float _officialAverageAttenuation; + float _officialMaxAttenuation; + float _officialMinAttenuation; glm::vec3 _listenerPosition; From e4d30c5f1f314a559a73b4df6fd43986ca4c02c2 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 18 Apr 2014 10:57:50 -0700 Subject: [PATCH 497/595] Update dancing_bot.js put gangnam style animation back - it's royalty free --- examples/dancing_bot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/dancing_bot.js b/examples/dancing_bot.js index 7924614d82..3572cc5a11 100644 --- a/examples/dancing_bot.js +++ b/examples/dancing_bot.js @@ -11,7 +11,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -var animation = AnimationCache.getAnimation("FBX_URL"); +var animation = AnimationCache.getAnimation("http://www.fungibleinsight.com/faces/gangnam_style_2.fbx"); Avatar.skeletonModelURL = "http://www.fungibleinsight.com/faces/beta.fst"; From 26487aad0682f0a1c845fcce0467ad2685f67b9e Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Fri, 18 Apr 2014 11:19:21 -0700 Subject: [PATCH 498/595] more correct bounding shapes for Models --- interface/src/renderer/Model.cpp | 78 ++++++++++++++++++++++---------- 1 file changed, 54 insertions(+), 24 deletions(-) diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index ca0b46841d..f8de7210ea 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -60,11 +60,11 @@ Model::SkinLocations Model::_skinNormalMapLocations; Model::SkinLocations Model::_skinShadowLocations; void Model::setScale(const glm::vec3& scale) { - glm::vec3 deltaScale = _scale - scale; + float scaleLength = glm::length(_scale); + float relativeDeltaScale = glm::length(_scale - scale) / scaleLength; - // decreased epsilon because this wasn't handling scale changes of 0.01 - const float SMALLER_EPSILON = EPSILON * 0.0001f; - if (glm::length2(deltaScale) > SMALLER_EPSILON) { + const float ONE_PERCENT = 0.01f; + if (relativeDeltaScale > ONE_PERCENT || scaleLength < EPSILON) { _scale = scale; rebuildShapes(); } @@ -468,20 +468,51 @@ void Model::clearShapes() { void Model::rebuildShapes() { clearShapes(); + const FBXGeometry& geometry = _geometry->getFBXGeometry(); - if (_jointStates.isEmpty()) { + if (geometry.joints.isEmpty()) { return; } - // make sure all the joints are updated correctly before we try to create their shapes - for (int i = 0; i < _jointStates.size(); i++) { - updateJointState(i); - } - - const FBXGeometry& geometry = _geometry->getFBXGeometry(); + int numJoints = geometry.joints.size(); + QVector transforms; + transforms.fill(glm::mat4(), numJoints); + QVector combinedRotations; + combinedRotations.fill(glm::quat(), numJoints); + QVector shapeIsSet; + shapeIsSet.fill(false, numJoints); + int rootIndex = 0; + float uniformScale = extractUniformScale(_scale); - glm::quat inverseRotation = glm::inverse(_rotation); - glm::vec3 rootPosition(0.f); + int numShapesSet = 0; + int lastNumShapesSet = -1; + while (numShapesSet < numJoints && numShapesSet != lastNumShapesSet) { + lastNumShapesSet = numShapesSet; + for (int i = 0; i < numJoints; ++i) { + if (shapeIsSet[i]) { + continue; + } + const FBXJoint& joint = geometry.joints[i]; + int parentIndex = joint.parentIndex; + if (parentIndex == -1) { + rootIndex = i; + glm::mat4 baseTransform = glm::mat4_cast(_rotation) * uniformScale * glm::translate(_offset); + glm::quat combinedRotation = joint.preRotation * joint.rotation * joint.postRotation; + transforms[i] = baseTransform * geometry.offset * glm::translate(joint.translation) * joint.preTransform * + glm::mat4_cast(combinedRotation) * joint.postTransform; + combinedRotations[i] = _rotation * combinedRotation; + ++numShapesSet; + shapeIsSet[i] = true; + } else if (shapeIsSet[parentIndex]) { + glm::quat combinedRotation = joint.preRotation * joint.rotation * joint.postRotation; + transforms[i] = transforms[parentIndex] * glm::translate(joint.translation) * joint.preTransform * + glm::mat4_cast(combinedRotation) * joint.postTransform; + combinedRotations[i] = combinedRotations[parentIndex] * combinedRotation; + ++numShapesSet; + shapeIsSet[i] = true; + } + } + } // joint shapes Extents totalExtents; @@ -489,15 +520,10 @@ void Model::rebuildShapes() { for (int i = 0; i < _jointStates.size(); i++) { const FBXJoint& joint = geometry.joints[i]; - glm::vec3 jointToShapeOffset = uniformScale * (_jointStates[i].combinedRotation * joint.shapePosition); - glm::vec3 worldPosition = extractTranslation(_jointStates[i].transform) + jointToShapeOffset + _translation; + glm::vec3 worldPosition = extractTranslation(transforms[i]); Extents shapeExtents; shapeExtents.reset(); - if (joint.parentIndex == -1) { - rootPosition = worldPosition; - } - float radius = uniformScale * joint.boneRadius; float halfHeight = 0.5f * uniformScale * joint.distanceToParent; Shape::Type type = joint.shapeType; @@ -508,7 +534,7 @@ void Model::rebuildShapes() { if (type == Shape::CAPSULE_SHAPE) { CapsuleShape* capsule = new CapsuleShape(radius, halfHeight); capsule->setPosition(worldPosition); - capsule->setRotation(_jointStates[i].combinedRotation * joint.shapeRotation); + capsule->setRotation(combinedRotations[i] * joint.shapeRotation); _jointShapes.push_back(capsule); glm::vec3 endPoint; @@ -526,7 +552,6 @@ void Model::rebuildShapes() { shapeExtents.addPoint(worldPosition + axis); shapeExtents.addPoint(worldPosition - axis); - totalExtents.addExtents(shapeExtents); } else if (type == Shape::SPHERE_SHAPE) { SphereShape* sphere = new SphereShape(radius, worldPosition); @@ -539,12 +564,11 @@ void Model::rebuildShapes() { } else { // this shape type is not handled and the joint shouldn't collide, // however we must have a shape for each joint, - // so we make a bogus sphere and put it at the center of the model + // so we make a bogus sphere with zero radius. // TODO: implement collision groups for more control over what collides with what - SphereShape* sphere = new SphereShape(0.f, _offset); + SphereShape* sphere = new SphereShape(0.f, worldPosition); _jointShapes.push_back(sphere); } - } // bounding shape @@ -554,7 +578,12 @@ void Model::rebuildShapes() { float capsuleRadius = 0.5f * sqrtf(0.5f * (diagonal.x * diagonal.x + diagonal.z * diagonal.z)); _boundingShape.setRadius(capsuleRadius); _boundingShape.setHalfHeight(0.5f * diagonal.y - capsuleRadius); + + glm::quat inverseRotation = glm::inverse(_rotation); + glm::vec3 rootPosition = extractTranslation(transforms[rootIndex]); _boundingShapeLocalOffset = inverseRotation * (0.5f * (totalExtents.maximum + totalExtents.minimum) - rootPosition); + _boundingShape.setPosition(_translation - _rotation * _boundingShapeLocalOffset); + _boundingShape.setRotation(_rotation); } void Model::updateShapePositions() { @@ -581,6 +610,7 @@ void Model::updateShapePositions() { _boundingRadius = sqrtf(_boundingRadius); _shapesAreDirty = false; _boundingShape.setPosition(rootPosition + _rotation * _boundingShapeLocalOffset); + _boundingShape.setRotation(_rotation); } } From e9768ca4fc190453515b6e3d48d53e73b15445d6 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 18 Apr 2014 13:34:30 -0700 Subject: [PATCH 499/595] add missing pool handling to DS --- domain-server/src/DomainServer.cpp | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 9dbb1e478e..f32eb99733 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -847,8 +847,9 @@ bool DomainServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url // this is a script upload - ask the HTTPConnection to parse the form data QList formData = connection->parseFormData(); - // check how many instances of this assignment the user wants by checking the ASSIGNMENT-INSTANCES header + // check optional headers for # of instances and pool const QString ASSIGNMENT_INSTANCES_HEADER = "ASSIGNMENT-INSTANCES"; + const QString ASSIGNMENT_POOL_HEADER = "ASSIGNMENT-POOL"; QByteArray assignmentInstancesValue = connection->requestHeaders().value(ASSIGNMENT_INSTANCES_HEADER.toLocal8Bit()); @@ -860,25 +861,34 @@ bool DomainServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url numInstances = assignmentInstancesValue.toInt(); } - + + QString assignmentPool = emptyPool; + QByteArray assignmentPoolValue = connection->requestHeaders().value(ASSIGNMENT_POOL_HEADER.toLocal8Bit()); + + if (!assignmentPoolValue.isEmpty()) { + // specific pool requested, set that on the created assignment + assignmentPool = QString(assignmentPoolValue); + } + const char ASSIGNMENT_SCRIPT_HOST_LOCATION[] = "resources/web/assignment"; for (int i = 0; i < numInstances; i++) { // create an assignment for this saved script - Assignment* scriptAssignment = new Assignment(Assignment::CreateCommand, Assignment::AgentType); + Assignment* scriptAssignment = new Assignment(Assignment::CreateCommand, Assignment::AgentType, assignmentPool); QString newPath(ASSIGNMENT_SCRIPT_HOST_LOCATION); newPath += "/"; // append the UUID for this script as the new filename, remove the curly braces newPath += uuidStringWithoutCurlyBraces(scriptAssignment->getUUID()); - // create a file with the GUID of the assignment in the script host locaiton + // create a file with the GUID of the assignment in the script host location QFile scriptFile(newPath); scriptFile.open(QIODevice::WriteOnly); scriptFile.write(formData[0].second); - qDebug("Saved a script for assignment at %s", qPrintable(newPath)); + qDebug() << qPrintable(QString("Saved a script for assignment at %1%2") + .arg(newPath).arg(assignmentPool == emptyPool ? "" : " - pool is " + assignmentPool)); // add the script assigment to the assignment queue _assignmentQueue.enqueue(SharedAssignmentPointer(scriptAssignment)); From 6ef4e145c59281a63178d9a26c10f63906b21f2a Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 18 Apr 2014 13:51:58 -0700 Subject: [PATCH 500/595] add better Sound error handling --- libraries/audio/src/Sound.cpp | 16 ++++++++++++---- libraries/audio/src/Sound.h | 6 +++--- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/libraries/audio/src/Sound.cpp b/libraries/audio/src/Sound.cpp index 001f863e03..3aae6b995d 100644 --- a/libraries/audio/src/Sound.cpp +++ b/libraries/audio/src/Sound.cpp @@ -73,15 +73,18 @@ Sound::Sound(const QUrl& sampleURL, QObject* parent) : // QNetworkAccess manager to grab the raw audio file at the given URL QNetworkAccessManager *manager = new QNetworkAccessManager(this); - connect(manager, SIGNAL(finished(QNetworkReply*)), - this, SLOT(replyFinished(QNetworkReply*))); qDebug() << "Requesting audio file" << sampleURL.toDisplayString(); - manager->get(QNetworkRequest(sampleURL)); + + QNetworkReply* soundDownload = manager->get(QNetworkRequest(sampleURL)); + connect(soundDownload, &QNetworkReply::finished, this, &Sound::replyFinished); + connect(soundDownload, SLOT(error(QNetworkReply::NetworkError)), this, SIGNAL(error(QNetworkReply::NetworkError))); } -void Sound::replyFinished(QNetworkReply* reply) { +void Sound::replyFinished() { + QNetworkReply* reply = reinterpret_cast(sender()); + // replace our byte array with the downloaded data QByteArray rawAudioByteArray = reply->readAll(); @@ -110,6 +113,11 @@ void Sound::replyFinished(QNetworkReply* reply) { } } +void Sound::replyError(QNetworkReply::NetworkError code) { + QNetworkReply* reply = reinterpret_cast(sender()); + qDebug() << "Error downloading sound file at" << reply->url().toString() << "-" << reply->errorString(); +} + void Sound::downSample(const QByteArray& rawAudioByteArray) { // assume that this was a RAW file and is now an array of samples that are diff --git a/libraries/audio/src/Sound.h b/libraries/audio/src/Sound.h index e1613fec51..50b2bbadaa 100644 --- a/libraries/audio/src/Sound.h +++ b/libraries/audio/src/Sound.h @@ -13,8 +13,7 @@ #define hifi_Sound_h #include - -class QNetworkReply; +#include class Sound : public QObject { Q_OBJECT @@ -31,7 +30,8 @@ private: void interpretAsWav(const QByteArray& inputAudioByteArray, QByteArray& outputAudioByteArray); private slots: - void replyFinished(QNetworkReply* reply); + void replyFinished(); + void replyError(QNetworkReply::NetworkError code); }; #endif // hifi_Sound_h From 3b8cf8c172dd4470edb579c3a1b2e32220dacee5 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 18 Apr 2014 13:55:22 -0700 Subject: [PATCH 501/595] fix mixed signal and slot --- libraries/audio/src/Sound.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/audio/src/Sound.cpp b/libraries/audio/src/Sound.cpp index 3aae6b995d..793fd51a56 100644 --- a/libraries/audio/src/Sound.cpp +++ b/libraries/audio/src/Sound.cpp @@ -78,7 +78,7 @@ Sound::Sound(const QUrl& sampleURL, QObject* parent) : QNetworkReply* soundDownload = manager->get(QNetworkRequest(sampleURL)); connect(soundDownload, &QNetworkReply::finished, this, &Sound::replyFinished); - connect(soundDownload, SLOT(error(QNetworkReply::NetworkError)), this, SIGNAL(error(QNetworkReply::NetworkError))); + connect(soundDownload, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error(QNetworkReply::NetworkError))); } void Sound::replyFinished() { From aa5d7aa0b1963b236e2385378a4c2d92a6ac1f03 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 18 Apr 2014 13:58:33 -0700 Subject: [PATCH 502/595] fix incorrectly named slot in Sound --- libraries/audio/src/Sound.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/audio/src/Sound.cpp b/libraries/audio/src/Sound.cpp index 793fd51a56..bcae878259 100644 --- a/libraries/audio/src/Sound.cpp +++ b/libraries/audio/src/Sound.cpp @@ -78,7 +78,7 @@ Sound::Sound(const QUrl& sampleURL, QObject* parent) : QNetworkReply* soundDownload = manager->get(QNetworkRequest(sampleURL)); connect(soundDownload, &QNetworkReply::finished, this, &Sound::replyFinished); - connect(soundDownload, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error(QNetworkReply::NetworkError))); + connect(soundDownload, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(replyError(QNetworkReply::NetworkError))); } void Sound::replyFinished() { From 1a895b9342d410607c0ff92d382b181b9c84672d Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 18 Apr 2014 14:24:50 -0700 Subject: [PATCH 503/595] add property for display name to JS --- libraries/avatars/src/AvatarData.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libraries/avatars/src/AvatarData.h b/libraries/avatars/src/AvatarData.h index d1a63c9a58..250ae07b01 100755 --- a/libraries/avatars/src/AvatarData.h +++ b/libraries/avatars/src/AvatarData.h @@ -97,13 +97,14 @@ class AvatarData : public QObject { Q_PROPERTY(float audioLoudness READ getAudioLoudness WRITE setAudioLoudness) Q_PROPERTY(float audioAverageLoudness READ getAudioAverageLoudness WRITE setAudioAverageLoudness) + Q_PROPERTY(QString displayName READ getDisplayName WRITE setDisplayName) Q_PROPERTY(QString faceModelURL READ getFaceModelURLFromScript WRITE setFaceModelURLFromScript) Q_PROPERTY(QString skeletonModelURL READ getSkeletonModelURLFromScript WRITE setSkeletonModelURLFromScript) Q_PROPERTY(QString billboardURL READ getBillboardURL WRITE setBillboardFromURL) Q_PROPERTY(QStringList jointNames READ getJointNames) - Q_PROPERTY(QUuid sessionUUID READ getSessionUUID); + Q_PROPERTY(QUuid sessionUUID READ getSessionUUID) public: AvatarData(); virtual ~AvatarData(); From 92f2794ea80a552f50a36ac66e43f9cea5a71e1d Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 18 Apr 2014 14:26:56 -0700 Subject: [PATCH 504/595] add a property to Sound to tell if empty --- libraries/audio/src/Sound.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libraries/audio/src/Sound.h b/libraries/audio/src/Sound.h index 50b2bbadaa..ae2fd391a1 100644 --- a/libraries/audio/src/Sound.h +++ b/libraries/audio/src/Sound.h @@ -17,10 +17,14 @@ class Sound : public QObject { Q_OBJECT + + Q_PROPERTY(bool empty READ isEmpty) public: Sound(const QUrl& sampleURL, QObject* parent = NULL); Sound(float volume, float frequency, float duration, float decay, QObject* parent = NULL); + bool isEmpty() const { return _byteArray.isEmpty(); } + const QByteArray& getByteArray() { return _byteArray; } private: From c1e54d370c3e56adf84bcd6d2205ff229a4b35a5 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 18 Apr 2014 14:46:56 -0700 Subject: [PATCH 505/595] change Sound property to hasDownloaded --- libraries/audio/src/Sound.cpp | 5 ++++- libraries/audio/src/Sound.h | 5 +++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/libraries/audio/src/Sound.cpp b/libraries/audio/src/Sound.cpp index bcae878259..5bd63b7959 100644 --- a/libraries/audio/src/Sound.cpp +++ b/libraries/audio/src/Sound.cpp @@ -67,7 +67,8 @@ Sound::Sound(float volume, float frequency, float duration, float decay, QObject } Sound::Sound(const QUrl& sampleURL, QObject* parent) : - QObject(parent) + QObject(parent), + _hasDownloaded(false) { // assume we have a QApplication or QCoreApplication instance and use the // QNetworkAccess manager to grab the raw audio file at the given URL @@ -111,6 +112,8 @@ void Sound::replyFinished() { } else { qDebug() << "Network reply without 'Content-Type'."; } + + _hasDownloaded = true; } void Sound::replyError(QNetworkReply::NetworkError code) { diff --git a/libraries/audio/src/Sound.h b/libraries/audio/src/Sound.h index ae2fd391a1..c953ae1b33 100644 --- a/libraries/audio/src/Sound.h +++ b/libraries/audio/src/Sound.h @@ -23,13 +23,14 @@ public: Sound(const QUrl& sampleURL, QObject* parent = NULL); Sound(float volume, float frequency, float duration, float decay, QObject* parent = NULL); - bool isEmpty() const { return _byteArray.isEmpty(); } + bool hasDownloaded() const { return _hasDownloaded; } const QByteArray& getByteArray() { return _byteArray; } private: QByteArray _byteArray; - + bool _hasDownloaded; + void downSample(const QByteArray& rawAudioByteArray); void interpretAsWav(const QByteArray& inputAudioByteArray, QByteArray& outputAudioByteArray); From 72fe9b94b1c25f5e11086bea97346ba9ab32c75e Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 18 Apr 2014 14:48:26 -0700 Subject: [PATCH 506/595] fix property in sound --- libraries/audio/src/Sound.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/audio/src/Sound.h b/libraries/audio/src/Sound.h index c953ae1b33..c473cdff83 100644 --- a/libraries/audio/src/Sound.h +++ b/libraries/audio/src/Sound.h @@ -18,7 +18,7 @@ class Sound : public QObject { Q_OBJECT - Q_PROPERTY(bool empty READ isEmpty) + Q_PROPERTY(bool downloaded READ hasDownloaded) public: Sound(const QUrl& sampleURL, QObject* parent = NULL); Sound(float volume, float frequency, float duration, float decay, QObject* parent = NULL); From d489e9dcd403114263c6d360b00e4aba75c3fca3 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Fri, 18 Apr 2014 23:55:45 +0200 Subject: [PATCH 507/595] Fix format --- interface/src/Application.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 592370705a..0abcd9d1af 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3552,11 +3552,11 @@ void Application::takeSnapshot() { } void Application::urlGoTo(int argc, const char * constArgv[]) { - //Gets the url (hifi://domain/destination/orientation) - QString customUrl = getCmdOption(argc, constArgv, "-url"); + //Gets the url (hifi://domain/destination/orientation) + QString customUrl = getCmdOption(argc, constArgv, "-url"); - if (customUrl.startsWith("hifi://")) { - QStringList urlParts = customUrl.remove(0, CUSTOM_URL_SCHEME.length() + 2).split('/', QString::SkipEmptyParts); + if (customUrl.startsWith("hifi://")) { + QStringList urlParts = customUrl.remove(0, CUSTOM_URL_SCHEME.length() + 2).split('/', QString::SkipEmptyParts); if (urlParts.count() > 1) { // if url has 2 or more parts, the first one is domain name QString domain = urlParts[0]; @@ -3583,6 +3583,5 @@ void Application::urlGoTo(int argc, const char * constArgv[]) { QString destination = urlParts[0]; Menu::goTo(destination); } - } } From 50f7db8fe167c07bf01d1a6ff403443d1281f6db Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 18 Apr 2014 15:02:10 -0700 Subject: [PATCH 508/595] quiet some debugging --- assignment-client/src/octree/OctreeServer.cpp | 15 ++++++++++----- assignment-client/src/octree/OctreeServer.h | 1 + libraries/networking/src/ThreadedAssignment.cpp | 2 +- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index e878959e51..1a593f3be7 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -253,9 +253,11 @@ OctreeServer::OctreeServer(const QByteArray& packet) : qDebug() << "Octree server starting... [" << this << "]"; + /* QTimer* timer = new QTimer(this); connect(timer, SIGNAL(timeout()), SLOT(doNothing())); timer->start(0); + */ } @@ -842,7 +844,7 @@ quint64 lastProcessNodeData = usecTimestampNow(); void OctreeServer::readPendingDatagrams() { quint64 now = usecTimestampNow(); if ((now - lastReadPendingDatagrams) > 100000) { - qDebug() << "OctreeServer::readPendingDatagrams(): since lastReadPendingDatagrams=" << (now - lastReadPendingDatagrams) << "usecs"; + //qDebug() << "OctreeServer::readPendingDatagrams(): since lastReadPendingDatagrams=" << (now - lastReadPendingDatagrams) << "usecs"; } lastReadPendingDatagrams = now; @@ -884,10 +886,13 @@ void OctreeServer::readPendingDatagrams() { matchingElapsed += (endNodeLookup - startNodeLookup); if ((endNodeLookup - startNodeLookup) > 100000) { - qDebug() << "OctreeServer::readPendingDatagrams(): sendingNodeForPacket() took" << (endNodeLookup - startNodeLookup) << "usecs"; + //qDebug() << "OctreeServer::readPendingDatagrams(): sendingNodeForPacket() took" << (endNodeLookup - startNodeLookup) << "usecs"; } if (packetType == getMyQueryMessageType()) { + +qDebug() << "got a query..."; + quint64 queryStart = usecTimestampNow(); queryPackets++; @@ -898,7 +903,7 @@ void OctreeServer::readPendingDatagrams() { nodeList->updateNodeWithDataFromPacket(matchingNode, receivedPacket); quint64 endUpdateNode = usecTimestampNow(); if ((endUpdateNode - startUpdateNode) > 100000) { - qDebug() << "OctreeServer::readPendingDatagrams(): updateNodeWithDataFromPacket() took" << (endUpdateNode - startUpdateNode) << "usecs"; + //qDebug() << "OctreeServer::readPendingDatagrams(): updateNodeWithDataFromPacket() took" << (endUpdateNode - startUpdateNode) << "usecs"; } OctreeQueryNode* nodeData = (OctreeQueryNode*) matchingNode->getLinkedData(); @@ -927,7 +932,7 @@ void OctreeServer::readPendingDatagrams() { nodeListPackets++; quint64 now = usecTimestampNow(); if ((now - lastProcessNodeData) > 500000) { - qDebug() << "OctreeServer::readPendingDatagrams(): since lastProcessNodeData=" << (now - lastProcessNodeData) << "usecs"; + //qDebug() << "OctreeServer::readPendingDatagrams(): since lastProcessNodeData=" << (now - lastProcessNodeData) << "usecs"; } lastProcessNodeData = now; @@ -936,7 +941,7 @@ void OctreeServer::readPendingDatagrams() { NodeList::getInstance()->processNodeData(senderSockAddr, receivedPacket); quint64 endProcessNodeData = usecTimestampNow(); if ((endProcessNodeData - startProcessNodeData) > 100000) { - qDebug() << "OctreeServer::readPendingDatagrams(): processNodeData() took" << (endProcessNodeData - startProcessNodeData) << "usecs"; + //qDebug() << "OctreeServer::readPendingDatagrams(): processNodeData() took" << (endProcessNodeData - startProcessNodeData) << "usecs"; } quint64 nodeListEnd = usecTimestampNow(); diff --git a/assignment-client/src/octree/OctreeServer.h b/assignment-client/src/octree/OctreeServer.h index d7139b5c3d..7427ee0dbe 100644 --- a/assignment-client/src/octree/OctreeServer.h +++ b/assignment-client/src/octree/OctreeServer.h @@ -126,6 +126,7 @@ public slots: void nodeAdded(SharedNodePointer node); void nodeKilled(SharedNodePointer node); void sendStatsPacket(); + void doNothing(); protected: void parsePayload(); diff --git a/libraries/networking/src/ThreadedAssignment.cpp b/libraries/networking/src/ThreadedAssignment.cpp index 3b00a6a620..528c0b0ff3 100644 --- a/libraries/networking/src/ThreadedAssignment.cpp +++ b/libraries/networking/src/ThreadedAssignment.cpp @@ -81,7 +81,7 @@ quint64 lastCheckIn = usecTimestampNow(); void ThreadedAssignment::checkInWithDomainServerOrExit() { quint64 now = usecTimestampNow(); if ((now - lastCheckIn) > 100000) { - qDebug() << "ThreadedAssignment::checkInWithDomainServerOrExit(): since lastCheckIn=" << (now - lastCheckIn) << "usecs"; + //qDebug() << "ThreadedAssignment::checkInWithDomainServerOrExit(): since lastCheckIn=" << (now - lastCheckIn) << "usecs"; } lastCheckIn = now; From 0a7ea17d43c7ad69645e496c458e21074d4235be Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 18 Apr 2014 15:10:15 -0700 Subject: [PATCH 509/595] fix a geometry race condition crash --- interface/src/renderer/Model.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index f8de7210ea..ef0911f673 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -468,8 +468,13 @@ void Model::clearShapes() { void Model::rebuildShapes() { clearShapes(); + + if (!_geometry) { + return; + } + const FBXGeometry& geometry = _geometry->getFBXGeometry(); - + if (geometry.joints.isEmpty()) { return; } From 334f688e4ee591a58e20618debc447ea9b8d3a40 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 18 Apr 2014 15:30:45 -0700 Subject: [PATCH 510/595] add support for sending unverified datagrams to nodes --- interface/src/Application.cpp | 2 +- libraries/networking/src/LimitedNodeList.cpp | 29 ++++++++++++++++++++ libraries/networking/src/LimitedNodeList.h | 7 +++++ 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index b01b694662..a1fffff78f 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2205,7 +2205,7 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType, Node int packetLength = endOfQueryPacket - queryPacket; // make sure we still have an active socket - nodeList->writeDatagram(reinterpret_cast(queryPacket), packetLength, node); + nodeList->writeUnverifiedDatagram(reinterpret_cast(queryPacket), packetLength, node); // Feed number of bytes to corresponding channel of the bandwidth meter _bandwidthMeter.outputStream(BandwidthMeter::VOXELS).updateValue(packetLength); diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index db8a689001..2c7ab2f5a8 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -234,6 +234,30 @@ qint64 LimitedNodeList::writeDatagram(const QByteArray& datagram, const SharedNo return 0; } +qint64 LimitedNodeList::writeUnverifiedDatagram(const QByteArray& datagram, const SharedNodePointer& destinationNode, + const HifiSockAddr& overridenSockAddr) { + if (destinationNode) { + // if we don't have an ovveriden address, assume they want to send to the node's active socket + const HifiSockAddr* destinationSockAddr = &overridenSockAddr; + if (overridenSockAddr.isNull()) { + if (destinationNode->getActiveSocket()) { + // use the node's active socket as the destination socket + destinationSockAddr = destinationNode->getActiveSocket(); + } else { + // we don't have a socket to send to, return 0 + return 0; + } + } + + + // don't use the node secret! + writeDatagram(datagram, *destinationSockAddr, QUuid()); + } + + // didn't have a destinationNode to send to, return 0 + return 0; +} + qint64 LimitedNodeList::writeUnverifiedDatagram(const QByteArray& datagram, const HifiSockAddr& destinationSockAddr) { return writeDatagram(datagram, destinationSockAddr, QUuid()); } @@ -243,6 +267,11 @@ qint64 LimitedNodeList::writeDatagram(const char* data, qint64 size, const Share return writeDatagram(QByteArray(data, size), destinationNode, overridenSockAddr); } +qint64 LimitedNodeList::writeUnverifiedDatagram(const char* data, qint64 size, const SharedNodePointer& destinationNode, + const HifiSockAddr& overridenSockAddr) { + return writeUnverifiedDatagram(QByteArray(data, size), destinationNode, overridenSockAddr); +} + void LimitedNodeList::processNodeData(const HifiSockAddr& senderSockAddr, const QByteArray& packet) { // the node decided not to do anything with this packet // if it comes from a known source we should keep that node alive diff --git a/libraries/networking/src/LimitedNodeList.h b/libraries/networking/src/LimitedNodeList.h index ea9cb42436..2a98dc536f 100644 --- a/libraries/networking/src/LimitedNodeList.h +++ b/libraries/networking/src/LimitedNodeList.h @@ -66,10 +66,17 @@ public: qint64 writeDatagram(const QByteArray& datagram, const SharedNodePointer& destinationNode, const HifiSockAddr& overridenSockAddr = HifiSockAddr()); + + qint64 writeUnverifiedDatagram(const QByteArray& datagram, const SharedNodePointer& destinationNode, + const HifiSockAddr& overridenSockAddr = HifiSockAddr()); + qint64 writeUnverifiedDatagram(const QByteArray& datagram, const HifiSockAddr& destinationSockAddr); qint64 writeDatagram(const char* data, qint64 size, const SharedNodePointer& destinationNode, const HifiSockAddr& overridenSockAddr = HifiSockAddr()); + qint64 writeUnverifiedDatagram(const char* data, qint64 size, const SharedNodePointer& destinationNode, + const HifiSockAddr& overridenSockAddr = HifiSockAddr()); + void(*linkedDataCreateCallback)(Node *); NodeHash getNodeHash(); From c2bcb328049fa0fc331fdbd4938f5b5c252d7431 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 18 Apr 2014 15:33:27 -0700 Subject: [PATCH 511/595] add support for sending unverified datagrams to nodes --- libraries/octree/src/OctreeHeadlessViewer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/octree/src/OctreeHeadlessViewer.cpp b/libraries/octree/src/OctreeHeadlessViewer.cpp index b25cb4ff8a..5574b376cb 100644 --- a/libraries/octree/src/OctreeHeadlessViewer.cpp +++ b/libraries/octree/src/OctreeHeadlessViewer.cpp @@ -221,7 +221,7 @@ void OctreeHeadlessViewer::queryOctree() { int packetLength = endOfQueryPacket - queryPacket; // make sure we still have an active socket - nodeList->writeDatagram(reinterpret_cast(queryPacket), packetLength, node); + nodeList->writeUnverifiedDatagram(reinterpret_cast(queryPacket), packetLength, node); } } } From aa73527157921dae7fcb2be1dc0de8cf7e4c8b15 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Fri, 18 Apr 2014 15:58:56 -0700 Subject: [PATCH 512/595] Some code cleaning --- interface/src/Application.cpp | 2 +- interface/src/Util.cpp | 12 ++++-- interface/src/ui/Stats.cpp | 69 ++++++++++++++++++----------------- 3 files changed, 46 insertions(+), 37 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index a46201a4d6..7a4c930bc6 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2728,7 +2728,7 @@ void Application::displayOverlay() { (Menu::getInstance()->isOptionChecked(MenuOption::Stats) && Menu::getInstance()->isOptionChecked(MenuOption::Bandwidth)) ? 80 : 20; - drawText(_glWidget->width() - 100, _glWidget->height() - timerBottom, 0.30f, 1.0f, 0.f, frameTimer, WHITE_TEXT); + drawText(_glWidget->width() - 100, _glWidget->height() - timerBottom, 0.30f, 0.0f, 0, frameTimer, WHITE_TEXT); } _overlays.render2D(); diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 1dae3a4fd6..5238db9b13 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -186,16 +186,22 @@ const glm::vec3 randVector() { } static TextRenderer* textRenderer(int mono) { - static TextRenderer* monoRenderer = new TextRenderer(MONO_FONT_FAMILY); - static TextRenderer* proportionalRenderer = new TextRenderer(SANS_FONT_FAMILY, -1, -1, false, TextRenderer::SHADOW_EFFECT); - static TextRenderer* inconsolataRenderer = new TextRenderer(INCONSOLATA_FONT_FAMILY, -1, QFont::Bold, false); switch (mono) { case 1: + static TextRenderer* monoRenderer = new TextRenderer(MONO_FONT_FAMILY); return monoRenderer; case 2: + static TextRenderer* inconsolataRenderer = new TextRenderer(INCONSOLATA_FONT_FAMILY, + -1, + QFont::Bold, false); return inconsolataRenderer; case 0: default: + static TextRenderer* proportionalRenderer = new TextRenderer(SANS_FONT_FAMILY, + -1, + -1, + false, + TextRenderer::SHADOW_EFFECT); return proportionalRenderer; } } diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp index 64616cbdf8..8807f3ff34 100644 --- a/interface/src/ui/Stats.cpp +++ b/interface/src/ui/Stats.cpp @@ -171,6 +171,9 @@ void Stats::display( unsigned int backgroundColor = 0x33333399; int verticalOffset = 0, lines = 0; + float scale = 0.10f; + float rotation = 0.0f; + int font = 2; QLocale locale(QLocale::English); std::stringstream voxelStats; @@ -198,11 +201,11 @@ void Stats::display( sprintf(framesPerSecond, "Framerate: %3.0f FPS", fps); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, serverNodes, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, serverNodes, color); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarNodes, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, avatarNodes, color); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, framesPerSecond, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, framesPerSecond, color); if (_expanded) { char packetsPerSecondString[30]; @@ -211,9 +214,9 @@ void Stats::display( sprintf(averageMegabitsPerSecond, "Mbps: %3.2f", (float)bytesPerSecond * 8.f / 1000000.f); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, packetsPerSecondString, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, packetsPerSecondString, color); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, averageMegabitsPerSecond, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, averageMegabitsPerSecond, color); } verticalOffset = 0; @@ -258,7 +261,7 @@ void Stats::display( "Buffer msecs %.1f", (float) (audio->getNetworkBufferLengthSamplesPerChannel() + (float) audio->getJitterBufferSamples()) / (float) audio->getNetworkSampleRate() * 1000.f); - drawText(30, glWidget->height() - 22, 0.10f, 0.f, 2.f, audioJitter, color); + drawText(30, glWidget->height() - 22, scale, rotation, font, audioJitter, color); char audioPing[30]; @@ -271,18 +274,18 @@ void Stats::display( sprintf(voxelAvgPing, "Voxel avg ping: %d", pingVoxel); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, audioPing, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, audioPing, color); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarPing, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, avatarPing, color); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, voxelAvgPing, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, voxelAvgPing, color); if (_expanded) { char voxelMaxPing[30]; sprintf(voxelMaxPing, "Voxel max ping: %d", pingVoxelMax); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, voxelMaxPing, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, voxelMaxPing, color); } verticalOffset = 0; @@ -306,11 +309,11 @@ void Stats::display( char avatarMixerStats[200]; verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarPosition, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, avatarPosition, color); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarVelocity, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, avatarVelocity, color); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarBodyYaw, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, avatarBodyYaw, color); if (_expanded) { SharedNodePointer avatarMixer = NodeList::getInstance()->soloNodeOfType(NodeType::AvatarMixer); @@ -323,7 +326,7 @@ void Stats::display( } verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, avatarMixerStats, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, avatarMixerStats, color); stringstream downloads; downloads << "Downloads: "; @@ -333,7 +336,7 @@ void Stats::display( downloads << "(" << ResourceCache::getPendingRequestCount() << " pending)"; verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, downloads.str().c_str(), color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, downloads.str().c_str(), color); } verticalOffset = 0; @@ -354,7 +357,7 @@ void Stats::display( voxelStats.str(""); voxelStats << "Voxels Memory Nodes: " << VoxelTreeElement::getTotalMemoryUsage() / 1000000.f << "MB"; verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, (char*)voxelStats.str().c_str(), color); voxelStats.str(""); voxelStats << @@ -364,14 +367,14 @@ void Stats::display( voxelStats << " / GPU: " << voxels->getVoxelMemoryUsageGPU() / 1000000.f << "MB"; } verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, (char*)voxelStats.str().c_str(), color); // Voxel Rendering voxelStats.str(""); voxelStats.precision(4); voxelStats << "Voxel Rendering Slots Max: " << voxels->getMaxVoxels() / 1000.f << "K"; verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, (char*)voxelStats.str().c_str(), color); } voxelStats.str(""); @@ -379,7 +382,7 @@ void Stats::display( voxelStats << "Drawn: " << voxels->getVoxelsWritten() / 1000.f << "K " << "Abandoned: " << voxels->getAbandonedVoxels() / 1000.f << "K "; verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, (char*)voxelStats.str().c_str(), color); // iterate all the current voxel stats, and list their sending modes, and total voxel counts std::stringstream sendingMode(""); @@ -424,7 +427,7 @@ void Stats::display( sendingMode << " "; } verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)sendingMode.str().c_str(), color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, (char*)sendingMode.str().c_str(), color); } // Incoming packets @@ -435,7 +438,7 @@ void Stats::display( voxelStats << "Voxel Packets to Process: " << qPrintable(packetsString) << " [Recent Max: " << qPrintable(maxString) << "]"; verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, (char*)voxelStats.str().c_str(), color); } if (_resetRecentMaxPacketsSoon && voxelPacketsToProcess > 0) { @@ -458,7 +461,7 @@ void Stats::display( voxelStats.str(""); voxelStats << "Server voxels: " << qPrintable(serversTotalString); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, (char*)voxelStats.str().c_str(), color); if (_expanded) { QString serversInternalString = locale.toString((uint)totalInternal); @@ -469,7 +472,7 @@ void Stats::display( "Internal: " << qPrintable(serversInternalString) << " " << "Leaves: " << qPrintable(serversLeavesString) << ""; verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, (char*)voxelStats.str().c_str(), color); } unsigned long localTotal = VoxelTreeElement::getNodeCount(); @@ -479,7 +482,7 @@ void Stats::display( voxelStats.str(""); voxelStats << "Local voxels: " << qPrintable(localTotalString); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, (char*)voxelStats.str().c_str(), color); if (_expanded) { unsigned long localInternal = VoxelTreeElement::getInternalNodeCount(); @@ -492,7 +495,7 @@ void Stats::display( "Internal: " << qPrintable(localInternalString) << " " << "Leaves: " << qPrintable(localLeavesString) << ""; verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0, 2, (char*)voxelStats.str().c_str(), color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, (char*)voxelStats.str().c_str(), color); } // LOD Details @@ -501,7 +504,7 @@ void Stats::display( QString displayLODDetails = Menu::getInstance()->getLODFeedbackText(); voxelStats << "LOD: You can see " << qPrintable(displayLODDetails.trimmed()); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, (char*)voxelStats.str().c_str(), color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, (char*)voxelStats.str().c_str(), color); } @@ -526,7 +529,7 @@ void Stats::display( ); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, reflectionsStatus, color); float preDelay = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingPreDelay) ? audioReflector->getPreDelay() : 0.0f; @@ -539,7 +542,7 @@ void Stats::display( audioReflector->getSoundMsPerMeter()); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, reflectionsStatus, color); sprintf(reflectionsStatus, "Attenuation: average %5.3f, max %5.3f, min %5.3f, Factor: %5.3f", audioReflector->getAverageAttenuation(), @@ -548,7 +551,7 @@ void Stats::display( audioReflector->getDistanceAttenuationScalingFactor()); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, reflectionsStatus, color); sprintf(reflectionsStatus, "Local Audio: %s Attenuation: %5.3f", (Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingProcessLocalAudio) @@ -556,7 +559,7 @@ void Stats::display( audioReflector->getLocalAudioAttenuationFactor()); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, reflectionsStatus, color); bool diffusionEnabled = Menu::getInstance()->isOptionChecked(MenuOption::AudioSpatialProcessingWithDiffusions); int fanout = diffusionEnabled ? audioReflector->getDiffusionFanout() : 0; @@ -565,7 +568,7 @@ void Stats::display( (diffusionEnabled ? "yes" : "no"), fanout, diffusionPaths); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, reflectionsStatus, color); const float AS_PERCENT = 100.0f; float reflectiveRatio = audioReflector->getReflectiveRatio() * AS_PERCENT; @@ -575,7 +578,7 @@ void Stats::display( reflectiveRatio, diffusionRatio, absorptionRatio); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, reflectionsStatus, color); sprintf(reflectionsStatus, "Comb Filter Window: %5.3f ms, Allowed: %d, Suppressed: %d", audioReflector->getCombFilterWindow(), @@ -583,7 +586,7 @@ void Stats::display( audioReflector->getEchoesSuppressed()); verticalOffset += STATS_PELS_PER_LINE; - drawText(horizontalOffset, verticalOffset, 0.10f, 0.f, 2.f, reflectionsStatus, color); + drawText(horizontalOffset, verticalOffset, scale, rotation, font, reflectionsStatus, color); } From b098a7a294c7fbc8bc2e1a243bcca1cfad21ba30 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Fri, 18 Apr 2014 15:59:37 -0700 Subject: [PATCH 513/595] Fixed wire cube overlay not drawn with right line width --- interface/src/ui/overlays/Cube3DOverlay.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/interface/src/ui/overlays/Cube3DOverlay.cpp b/interface/src/ui/overlays/Cube3DOverlay.cpp index ab9418206f..e9a366c6dc 100644 --- a/interface/src/ui/overlays/Cube3DOverlay.cpp +++ b/interface/src/ui/overlays/Cube3DOverlay.cpp @@ -40,6 +40,7 @@ void Cube3DOverlay::render() { if (_isSolid) { glutSolidCube(_size); } else { + glLineWidth(_lineWidth); glutWireCube(_size); } glPopMatrix(); From 61981b9470476eed3ced3f791abb837087d7a30c Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Fri, 18 Apr 2014 16:00:44 -0700 Subject: [PATCH 514/595] Added getter for tree scale in js --- libraries/voxels/src/VoxelsScriptingInterface.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/libraries/voxels/src/VoxelsScriptingInterface.h b/libraries/voxels/src/VoxelsScriptingInterface.h index 71a8405be6..d5322fdc4d 100644 --- a/libraries/voxels/src/VoxelsScriptingInterface.h +++ b/libraries/voxels/src/VoxelsScriptingInterface.h @@ -36,6 +36,9 @@ public: void setUndoStack(QUndoStack* undoStack) { _undoStack = undoStack; } public slots: + + /// provide the world scale + const int getTreeScale() const { return TREE_SCALE; } /// checks the local voxel tree for a voxel at the specified location and scale /// \param x the x-coordinate of the voxel (in meter units) From d6e7caa4db3e6e058ff60c10b03ae59df67a45a0 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Fri, 18 Apr 2014 16:02:01 -0700 Subject: [PATCH 515/595] Removed Debug --- interface/src/scripting/ClipboardScriptingInterface.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/scripting/ClipboardScriptingInterface.cpp b/interface/src/scripting/ClipboardScriptingInterface.cpp index b11c0fdbff..e8fb545343 100644 --- a/interface/src/scripting/ClipboardScriptingInterface.cpp +++ b/interface/src/scripting/ClipboardScriptingInterface.cpp @@ -78,7 +78,7 @@ void ClipboardScriptingInterface::exportVoxel(float x, float y, float z, float s } bool ClipboardScriptingInterface::importVoxels() { - qDebug() << "[DEBUG] Importing ... "; + qDebug() << "Importing ... "; QEventLoop loop; connect(Application::getInstance(), SIGNAL(importDone()), &loop, SLOT(quit())); emit readyToImport(); From c4102e3af0d580dce5bbccfe4a90749120fb6369 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Fri, 18 Apr 2014 16:04:20 -0700 Subject: [PATCH 516/595] Improved scale selector, changed first swatch behaviours, improved placement tool --- examples/editVoxels.js | 582 +++++++++++++++++++++-------------------- 1 file changed, 298 insertions(+), 284 deletions(-) diff --git a/examples/editVoxels.js b/examples/editVoxels.js index 752f4cbf9b..d9d1af8461 100644 --- a/examples/editVoxels.js +++ b/examples/editVoxels.js @@ -19,7 +19,10 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +var editToolsOn = true; // starts out off + var windowDimensions = Controller.getViewportDimensions(); +var WORLD_SCALE = Voxels.getTreeScale(); var NEW_VOXEL_SIZE = 1.0; var NEW_VOXEL_DISTANCE_FROM_CAMERA = 3.0; @@ -62,7 +65,7 @@ colors[6] = { red: 211, green: 115, blue: 0 }; colors[7] = { red: 48, green: 116, blue: 119 }; colors[8] = { red: 31, green: 64, blue: 64 }; var numColors = 9; -var whichColor = -1; // Starting color is 'Copy' mode +var whichColor = 0; // Starting color is 'Copy' mode // Create sounds for for every script actions that require one var audioOptions = new AudioInjectionOptions(); @@ -149,9 +152,6 @@ colorInheritSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/ colorInheritSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Color+Inherit/Inherit+B.raw"); colorInheritSound.addSound("https://highfidelity-public.s3.amazonaws.com/sounds/Voxel+Editing/Color+Inherit/Inherit+C.raw"); - -var editToolsOn = true; // starts out off - // previewAsVoxel - by default, we will preview adds/deletes/recolors as just 4 lines on the intersecting face. But if you // the preview to show a full voxel then set this to true and the voxel will be displayed for voxel editing var previewAsVoxel = false; @@ -204,8 +204,8 @@ var linePreviewRight = Overlays.addOverlay("line3d", { // these will be used below -var sliderWidth = 154; -var sliderHeight = 37; +var scaleSelectorWidth = 144; +var scaleSelectorHeight = 37; // These will be our "overlay IDs" var swatches = new Array(); @@ -213,7 +213,7 @@ var swatchExtraPadding = 5; var swatchHeight = 37; var swatchWidth = 27; var swatchesWidth = swatchWidth * numColors + numColors + swatchExtraPadding * 2; -var swatchesX = (windowDimensions.x - (swatchesWidth + sliderWidth)) / 2; +var swatchesX = (windowDimensions.x - (swatchesWidth + scaleSelectorWidth)) / 2; var swatchesY = windowDimensions.y - swatchHeight + 1; var toolIconUrl = "http://highfidelity-public.s3-us-west-1.amazonaws.com/images/tools/"; @@ -270,7 +270,7 @@ var voxelTool = Overlays.addOverlay("image", { x: 0, y: 0, width: toolWidth, height: toolHeight, subImage: { x: 0, y: toolHeight, width: toolWidth, height: toolHeight }, imageURL: toolIconUrl + "voxel-tool.svg", - visible: false, + visible: editToolsOn, alpha: 0.9 }); @@ -278,7 +278,7 @@ var recolorTool = Overlays.addOverlay("image", { x: 0, y: 0, width: toolWidth, height: toolHeight, subImage: { x: 0, y: toolHeight, width: toolWidth, height: toolHeight }, imageURL: toolIconUrl + "paint-tool.svg", - visible: false, + visible: editToolsOn, alpha: 0.9 }); @@ -286,58 +286,142 @@ var eyedropperTool = Overlays.addOverlay("image", { x: 0, y: 0, width: toolWidth, height: toolHeight, subImage: { x: 0, y: toolHeight, width: toolWidth, height: toolHeight }, imageURL: toolIconUrl + "eyedropper-tool.svg", - visible: false, + visible: editToolsOn, alpha: 0.9 }); -// This will create a couple of image overlays that make a "slider", we will demonstrate how to trap mouse messages to -// move the slider - -// see above... -//var sliderWidth = 158; -//var sliderHeight = 35; - -var sliderOffsetX = 17; -var sliderX = swatchesX - swatchWidth - sliderOffsetX; -var sliderY = windowDimensions.y - sliderHeight + 1; -var slider = Overlays.addOverlay("image", { - // alternate form of expressing bounds - bounds: { x: sliderX, y: sliderY, width: sliderWidth, height: sliderHeight}, - imageURL: toolIconUrl + "voxel-size-slider-bg.svg", - alpha: 1, +function ScaleSelector() { + this.x = swatchesX + swatchesWidth; + this.y = swatchesY; + this.width = scaleSelectorWidth; + this.height = scaleSelectorHeight; + + this.displayPower = false; + this.scale = 1.0; + this.power = 0; + + this.FIRST_PART = this.width * 40.0 / 100.0; + this.SECOND_PART = this.width * 37.0 / 100.0; + + this.buttonsOverlay = Overlays.addOverlay("image", { + x: this.x, y: this.y, + width: this.width, height: this.height, + //subImage: { x: 0, y: toolHeight, width: toolWidth, height: toolHeight }, + imageURL: toolIconUrl + "voxel-size-selector.svg", + alpha: 0.9, + visible: editToolsOn + }); + this.textOverlay = Overlays.addOverlay("text", { + x: this.x + this.FIRST_PART, y: this.y, + width: this.SECOND_PART, height: this.height, + topMargin: 13, + text: this.scale.toString(), + alpha: 0.0, + visible: editToolsOn + }); + this.powerOverlay = Overlays.addOverlay("text", { + x: this.x + this.FIRST_PART, y: this.y, + width: this.SECOND_PART, height: this.height, + leftMargin: 28, + text: this.power.toString(), + alpha: 0.0, + visible: false + }); + this.show = function(doShow) { + Overlays.editOverlay(this.buttonsOverlay, {visible: doShow}); + Overlays.editOverlay(this.textOverlay, {visible: doShow}); + Overlays.editOverlay(this.powerOverlay, {visible: doShow && this.displayPower}); + } + + this.move = function() { + this.x = swatchesX + swatchesWidth; + this.y = swatchesY; + + Overlays.editOverlay(this.buttonsOverlay, { + x: this.x, y: this.y, + }); + Overlays.editOverlay(this.textOverlay, { + x: this.x + this.FIRST_PART, y: this.y, + }); + Overlays.editOverlay(this.powerOverlay, { + x: this.x + this.FIRST_PART, y: this.y, + }); + } + + + this.switchDisplay = function() { + this.displayPower = !this.displayPower; + + if (this.displayPower) { + Overlays.editOverlay(this.textOverlay, { + leftMargin: 18, + text: "2" + }); + Overlays.editOverlay(this.powerOverlay, { + text: this.power.toString(), + visible: editToolsOn + }); + } else { + Overlays.editOverlay(this.textOverlay, { + leftMargin: 13, + text: this.scale.toString() + }); + Overlays.editOverlay(this.powerOverlay, { visible: false }); - -// The slider is handled in the mouse event callbacks. -var isMovingSlider = false; -var thumbClickOffsetX = 0; - -// This is the thumb of our slider -var minThumbX = 20; // relative to the x of the slider -var maxThumbX = minThumbX + 90; -var thumbExtents = maxThumbX - minThumbX; -var thumbX = (minThumbX + maxThumbX) / 2; -var thumbOffsetY = 11; -var thumbY = sliderY + thumbOffsetY; -var thumb = Overlays.addOverlay("image", { - x: sliderX + thumbX, - y: thumbY, - width: 17, - height: 17, - imageURL: toolIconUrl + "voxel-size-slider-handle.svg", - alpha: 1, - visible: false - }); - -var pointerVoxelScale = Math.floor(MAX_VOXEL_SCALE + MIN_VOXEL_SCALE) / 2; // this is the voxel scale used for click to add or delete -var pointerVoxelScaleSet = false; // if voxel scale has not yet been set, we use the intersection size - -var pointerVoxelScaleSteps = 8; // the number of slider position steps -var pointerVoxelScaleOriginStep = 8; // the position of slider for the 1 meter size voxel -var pointerVoxelScaleMin = Math.pow(2, (1-pointerVoxelScaleOriginStep)); -var pointerVoxelScaleMax = Math.pow(2, (pointerVoxelScaleSteps-pointerVoxelScaleOriginStep)); -var thumbDeltaPerStep = thumbExtents / (pointerVoxelScaleSteps - 1); - + } + } + + this.update = function() { + if (this.displayPower) { + Overlays.editOverlay(this.powerOverlay, {text: this.power.toString()}); + } else { + Overlays.editOverlay(this.textOverlay, {text: this.scale.toString()}); + } + } + + this.incrementScale = function() { + if (this.power < 13) { + ++this.power; + this.scale *= 2.0; + this.update(); + resizeVoxelSound.play(voxelSizePlus); + } + } + + this.decrementScale = function() { + if (-4 < this.power) { + --this.power; + this.scale /= 2.0; + this.update(); + resizeVoxelSound.play(voxelSizePlus); + } + } + + this.clicked = function(x, y) { + if (this.x < x && x < this.x + this.width && + this.y < y && y < this.y + this.height) { + + if (x < this.x + this.FIRST_PART) { + this.decrementScale(); + } else if (x < this.x + this.FIRST_PART + this.SECOND_PART) { + this.switchDisplay(); + } else { + this.incrementScale(); + } + return true; + } + return false; + } + + this.cleanup = function() { + Overlays.deleteOverlay(this.buttonsOverlay); + Overlays.deleteOverlay(this.textOverlay); + Overlays.deleteOverlay(this.powerOverlay); + } + +} +var scaleSelector = new ScaleSelector(); ///////////////////////////////////// IMPORT MODULE /////////////////////////////// @@ -345,9 +429,12 @@ var thumbDeltaPerStep = thumbExtents / (pointerVoxelScaleSteps - 1); var importTree; var importPreview; var importBoundaries; +var xImportGuide; +var yImportGuide; +var zImportGuide; var isImporting; var importPosition; -var importScale; +var importDistance; function initImport() { importPreview = Overlays.addOverlay("localvoxels", { @@ -358,49 +445,90 @@ function initImport() { }); importBoundaries = Overlays.addOverlay("cube", { position: { x: 0, y: 0, z: 0 }, - scale: 1, + size: 1, color: { red: 128, blue: 128, green: 128 }, + lineWIdth: 4, solid: false, visible: false - }) + }); + + xImportGuide = Overlays.addOverlay("line3d", { + position: { x: 0, y: 0, z: 0}, + end: { x: 0, y: 0, z: 0}, + color: { red: 255, green: 0, blue: 0}, + alpha: 1, + visible: false, + lineWidth: previewLineWidth + }); + yImportGuide = Overlays.addOverlay("line3d", { + position: { x: 0, y: 0, z: 0}, + end: { x: 0, y: 0, z: 0}, + color: { red: 0, green: 255, blue: 0}, + alpha: 1, + visible: false, + lineWidth: previewLineWidth + }); + zImportGuide = Overlays.addOverlay("line3d", { + position: { x: 0, y: 0, z: 0}, + end: { x: 0, y: 0, z: 0}, + color: { red: 0, green: 0, blue: 255}, + alpha: 1, + visible: false, + lineWidth: previewLineWidth + }); + + isImporting = false; importPosition = { x: 0, y: 0, z: 0 }; - importScale = 0; } function importVoxels() { - if (Clipboard.importVoxels()) { - isImporting = true; - if (importScale <= 0) { - importScale = 1; - } - } else { - isImporting = false; - } - + isImporting = Clipboard.importVoxels(); return isImporting; } function moveImport(position) { - if (0 < position.x && 0 < position.y && 0 < position.z) { - importPosition = position; - Overlays.editOverlay(importPreview, { - position: { x: importPosition.x, y: importPosition.y, z: importPosition.z } - }); - Overlays.editOverlay(importBoundaries, { - position: { x: importPosition.x, y: importPosition.y, z: importPosition.z } - }); - } + importPosition = position; + Overlays.editOverlay(importPreview, { + position: { x: importPosition.x, y: importPosition.y, z: importPosition.z } + }); + Overlays.editOverlay(importBoundaries, { + position: { x: importPosition.x, y: importPosition.y, z: importPosition.z } + }); + + + Overlays.editOverlay(xImportGuide, { + position: { x: importPosition.x, y: 0, z: importPosition.z }, + end: { x: importPosition.x + scaleSelector.scale, y: 0, z: importPosition.z } + }); + Overlays.editOverlay(yImportGuide, { + position: { x: importPosition.x, y: importPosition.y, z: importPosition.z }, + end: { x: importPosition.x, y: 0, z: importPosition.z } + }); + Overlays.editOverlay(zImportGuide, { + position: { x: importPosition.x, y: 0, z: importPosition.z }, + end: { x: importPosition.x, y: 0, z: importPosition.z + scaleSelector.scale } + }); + rescaleImport(); } -function rescaleImport(scale) { - if (0 < scale) { - importScale = scale; +function rescaleImport() { + if (0 < scaleSelector.scale) { Overlays.editOverlay(importPreview, { - scale: importScale + scale: scaleSelector.scale }); Overlays.editOverlay(importBoundaries, { - scale: importScale + size: scaleSelector.scale + }); + + Overlays.editOverlay(xImportGuide, { + end: { x: importPosition.x + scaleSelector.scale, y: 0, z: importPosition.z } + }); + Overlays.editOverlay(yImportGuide, { + end: { x: importPosition.x, y: 0, z: importPosition.z } + }); + Overlays.editOverlay(zImportGuide, { + end: { x: importPosition.x, y: 0, z: importPosition.z + scaleSelector.scale } }); } } @@ -412,11 +540,21 @@ function showImport(doShow) { Overlays.editOverlay(importBoundaries, { visible: doShow }); + + Overlays.editOverlay(xImportGuide, { + visible: doShow + }); + Overlays.editOverlay(yImportGuide, { + visible: doShow + }); + Overlays.editOverlay(zImportGuide, { + visible: doShow + }); } function placeImport() { if (isImporting) { - Clipboard.pasteVoxel(importPosition.x, importPosition.y, importPosition.z, importScale); + Clipboard.pasteVoxel(importPosition.x, importPosition.y, importPosition.z, scaleSelector.scale); isImporting = false; } } @@ -431,9 +569,11 @@ function cancelImport() { function cleanupImport() { Overlays.deleteOverlay(importPreview); Overlays.deleteOverlay(importBoundaries); + Overlays.deleteOverlay(xImportGuide); + Overlays.deleteOverlay(yImportGuide); + Overlays.deleteOverlay(zImportGuide); isImporting = false; importPostion = { x: 0, y: 0, z: 0 }; - importScale = 0; } /////////////////////////////////// END IMPORT MODULE ///////////////////////////// initImport(); @@ -442,49 +582,6 @@ if (editToolsOn) { moveTools(); } - -function calcThumbFromScale(scale) { - var scaleLog = Math.log(scale)/Math.log(2); - var thumbStep = scaleLog + pointerVoxelScaleOriginStep; - if (thumbStep < 1) { - thumbStep = 1; - } - if (thumbStep > pointerVoxelScaleSteps) { - thumbStep = pointerVoxelScaleSteps; - } - var oldThumbX = thumbX; - thumbX = (thumbDeltaPerStep * (thumbStep - 1)) + minThumbX; - Overlays.editOverlay(thumb, { x: thumbX + sliderX } ); - - if (thumbX > oldThumbX) { - resizeVoxelSound.play(voxelSizePlus); - print("Plus"); - } else if (thumbX < oldThumbX) { - resizeVoxelSound.play(voxelSizeMinus); - print("Minus"); - } -} - -function calcScaleFromThumb(newThumbX) { - // newThumbX is the pixel location relative to start of slider, - // we need to figure out the actual offset in the allowed slider area - thumbAt = newThumbX - minThumbX; - thumbStep = Math.floor((thumbAt/ thumbExtents) * (pointerVoxelScaleSteps-1)) + 1; - pointerVoxelScale = Math.pow(2, (thumbStep-pointerVoxelScaleOriginStep)); - - // if importing, rescale import ... - if (isImporting) { - var importScale = (pointerVoxelScale / MAX_VOXEL_SCALE) * MAX_PASTE_VOXEL_SCALE; - rescaleImport(importScale); - } - - // now reset the display accordingly... - calcThumbFromScale(pointerVoxelScale); - - // if the user moved the thumb, then they are fixing the voxel scale - pointerVoxelScaleSet = true; -} - function setAudioPosition() { var position = MyAvatar.position; var forwardVector = Quat.getFront(MyAvatar.orientation); @@ -493,7 +590,7 @@ function setAudioPosition() { function getNewPasteVoxel(pickRay) { - var voxelSize = MIN_PASTE_VOXEL_SCALE + (MAX_PASTE_VOXEL_SCALE - MIN_PASTE_VOXEL_SCALE) * pointerVoxelScale - 1; + var voxelSize = scaleSelector.scale; var origin = { x: pickRay.direction.x, y: pickRay.direction.y, z: pickRay.direction.z }; origin.x += pickRay.origin.x; @@ -542,13 +639,7 @@ function calculateVoxelFromIntersection(intersection, operation) { + intersection.intersection.y + ", " + intersection.intersection.z); } - var voxelSize; - if (pointerVoxelScaleSet) { - voxelSize = pointerVoxelScale; - } else { - voxelSize = intersection.voxel.s; - } - + var voxelSize = scaleSelector.scale; var x; var y; var z; @@ -670,21 +761,9 @@ function showPreviewVoxel() { var pickRay = Camera.computePickRay(trackLastMouseX, trackLastMouseY); var intersection = Voxels.findRayIntersection(pickRay); - // if the user hasn't updated the - if (!pointerVoxelScaleSet) { - calcThumbFromScale(intersection.voxel.s); - } - - if (whichColor == -1) { - // Copy mode - use clicked voxel color - voxelColor = { red: intersection.voxel.red, - green: intersection.voxel.green, - blue: intersection.voxel.blue }; - } else { - voxelColor = { red: colors[whichColor].red, + voxelColor = { red: colors[whichColor].red, green: colors[whichColor].green, - blue: colors[whichColor].blue }; - } + blue: colors[whichColor].blue }; var guidePosition; if (trackAsRecolor || recolorToolSelected || trackAsEyedropper || eyedropperToolSelected) { @@ -734,18 +813,14 @@ function showPreviewLines() { var intersection = Voxels.findRayIntersection(pickRay); if (intersection.intersects) { - - // if the user hasn't updated the - if (!pointerVoxelScaleSet) { - calcThumbFromScale(intersection.voxel.s); - } - resultVoxel = calculateVoxelFromIntersection(intersection,""); Overlays.editOverlay(voxelPreview, { visible: false }); Overlays.editOverlay(linePreviewTop, { position: resultVoxel.topLeft, end: resultVoxel.topRight, visible: true }); Overlays.editOverlay(linePreviewBottom, { position: resultVoxel.bottomLeft, end: resultVoxel.bottomRight, visible: true }); Overlays.editOverlay(linePreviewLeft, { position: resultVoxel.topLeft, end: resultVoxel.bottomLeft, visible: true }); Overlays.editOverlay(linePreviewRight, { position: resultVoxel.topRight, end: resultVoxel.bottomRight, visible: true }); + colors[0] = {red: intersection.voxel.red, green: intersection.voxel.green , blue: intersection.voxel.blue }; + moveTools(); } else { Overlays.editOverlay(voxelPreview, { visible: false }); Overlays.editOverlay(linePreviewTop, { visible: false }); @@ -756,7 +831,7 @@ function showPreviewLines() { } function showPreviewGuides() { - if (editToolsOn) { + if (editToolsOn && !isImporting) { if (previewAsVoxel) { showPreviewVoxel(); @@ -817,6 +892,7 @@ function trackKeyReleaseEvent(event) { moveTools(); setAudioPosition(); // make sure we set the audio position before playing sounds showPreviewGuides(); + scaleSelector.show(editToolsOn); scriptInitSound.playRandom(); } @@ -826,17 +902,14 @@ function trackKeyReleaseEvent(event) { if (editToolsOn) { if (event.text == "ESC") { - pointerVoxelScaleSet = false; pasteMode = false; moveTools(); } if (event.text == "-") { - thumbX -= thumbDeltaPerStep; - calcScaleFromThumb(thumbX); + scaleSelector.decrementScale(); } if (event.text == "+") { - thumbX += thumbDeltaPerStep; - calcScaleFromThumb(thumbX); + scaleSelector.incrementScale(); } if (event.text == "CONTROL") { trackAsDelete = false; @@ -872,15 +945,7 @@ function mousePressEvent(event) { var clickedOnSomething = false; var clickedOverlay = Overlays.getOverlayAtPoint({x: event.x, y: event.y}); - // If the user clicked on the thumb, handle the slider logic - if (clickedOverlay == thumb) { - isMovingSlider = true; - thumbClickOffsetX = event.x - (sliderX + thumbX); // this should be the position of the mouse relative to the thumb - clickedOnSomething = true; - - //Overlays.editOverlay(thumb, { imageURL: toolIconUrl + "voxel-size-slider-handle.svg", }); - - } else if (clickedOverlay == voxelTool) { + if (clickedOverlay == voxelTool) { modeSwitchSound.play(0); voxelToolSelected = true; recolorToolSelected = false; @@ -901,19 +966,10 @@ function mousePressEvent(event) { eyedropperToolSelected = true; moveTools(); clickedOnSomething = true; - } else if (clickedOverlay == slider) { - - if (event.x < sliderX + minThumbX) { - thumbX -= thumbDeltaPerStep; - calcScaleFromThumb(thumbX); + } else if (scaleSelector.clicked(event.x, event.y)) { + if (isImporting) { + rescaleImport(); } - - if (event.x > sliderX + maxThumbX) { - thumbX += thumbDeltaPerStep; - calcScaleFromThumb(thumbX); - } - - moveTools(); clickedOnSomething = true; } else { // if the user clicked on one of the color swatches, update the selectedSwatch @@ -927,7 +983,7 @@ function mousePressEvent(event) { } } } - if (clickedOnSomething) { + if (clickedOnSomething || isImporting) { return; // no further processing } @@ -939,14 +995,6 @@ function mousePressEvent(event) { var intersection = Voxels.findRayIntersection(pickRay); audioOptions.position = Vec3.sum(pickRay.origin, pickRay.direction); - if (isImporting) { - print("placing import..."); - placeImport(); - showImport(false); - moveTools(); - return; - } - if (pasteMode) { var pasteVoxel = getNewPasteVoxel(pickRay); Clipboard.pasteVoxel(pasteVoxel.origin.x, pasteVoxel.origin.y, pasteVoxel.origin.z, pasteVoxel.voxelSize); @@ -956,11 +1004,6 @@ function mousePressEvent(event) { } if (intersection.intersects) { - // if the user hasn't updated the - if (!pointerVoxelScaleSet) { - calcThumbFromScale(intersection.voxel.s); - } - if (trackAsDelete || event.isRightButton && !trackAsEyedropper) { // Delete voxel voxelDetails = calculateVoxelFromIntersection(intersection,"delete"); @@ -968,13 +1011,11 @@ function mousePressEvent(event) { delVoxelSound.playRandom(); Overlays.editOverlay(voxelPreview, { visible: false }); } else if (eyedropperToolSelected || trackAsEyedropper) { - if (whichColor != -1) { - colors[whichColor].red = intersection.voxel.red; - colors[whichColor].green = intersection.voxel.green; - colors[whichColor].blue = intersection.voxel.blue; - moveTools(); - swatchesSound.play(whichColor); - } + colors[whichColor].red = intersection.voxel.red; + colors[whichColor].green = intersection.voxel.green; + colors[whichColor].blue = intersection.voxel.blue; + moveTools(); + swatchesSound.play(whichColor); } else if (recolorToolSelected || trackAsRecolor) { // Recolor Voxel @@ -987,18 +1028,10 @@ function mousePressEvent(event) { Overlays.editOverlay(voxelPreview, { visible: false }); } else if (voxelToolSelected) { // Add voxel on face - if (whichColor == -1) { - // Copy mode - use clicked voxel color - newColor = { - red: intersection.voxel.red, - green: intersection.voxel.green, - blue: intersection.voxel.blue }; - } else { - newColor = { - red: colors[whichColor].red, - green: colors[whichColor].green, - blue: colors[whichColor].blue }; - } + newColor = { red: colors[whichColor].red, + green: colors[whichColor].green, + blue: colors[whichColor].blue + }; voxelDetails = calculateVoxelFromIntersection(intersection,"add"); Voxels.setVoxel(voxelDetails.x, voxelDetails.y, voxelDetails.z, voxelDetails.s, @@ -1020,29 +1053,22 @@ function keyPressEvent(event) { // if our tools are off, then don't do anything if (editToolsOn) { var nVal = parseInt(event.text); - if (event.text == "`") { - print("Color = Copy"); - whichColor = -1; - colorInheritSound.playRandom(); - moveTools(); - } else if ((nVal > 0) && (nVal <= numColors)) { + if ((nVal > 0) && (nVal <= numColors)) { whichColor = nVal - 1; print("Color = " + (whichColor + 1)); swatchesSound.play(whichColor); moveTools(); } else if (event.text == "0") { // Create a brand new 1 meter voxel in front of your avatar - var color = whichColor; - if (color == -1) color = 0; var newPosition = getNewVoxelPosition(); var newVoxel = { x: newPosition.x, y: newPosition.y , z: newPosition.z, s: NEW_VOXEL_SIZE, - red: colors[color].red, - green: colors[color].green, - blue: colors[color].blue }; + red: colors[whichColor].red, + green: colors[whichColor].green, + blue: colors[whichColor].blue }; Voxels.eraseVoxel(newVoxel.x, newVoxel.y, newVoxel.z, newVoxel.s); Voxels.setVoxel(newVoxel.x, newVoxel.y, newVoxel.z, newVoxel.s, newVoxel.red, newVoxel.green, newVoxel.blue); setAudioPosition(); @@ -1158,17 +1184,44 @@ function mouseMoveEvent(event) { return; } - if (isMovingSlider) { - thumbX = (event.x - thumbClickOffsetX) - sliderX; - if (thumbX < minThumbX) { - thumbX = minThumbX; - } - if (thumbX > maxThumbX) { - thumbX = maxThumbX; - } - calcScaleFromThumb(thumbX); + // Move Import Preview + if (isImporting) { + var pickRay = Camera.computePickRay(event.x, event.y); + var intersection = Voxels.findRayIntersection(pickRay); - } else if (isAdding) { + var distance = 2 * scaleSelector.scale; + + if (intersection.intersects) { + var intersectionDistance = Vec3.length(Vec3.subtract(pickRay.origin, intersection.intersection)); + if (intersectionDistance < distance) { + distance = intersectionDistance * 0.99; + } + + } + + var targetPosition = { x: pickRay.direction.x * distance, + y: pickRay.direction.y * distance, + z: pickRay.direction.z * distance + }; + targetPosition.x += pickRay.origin.x; + targetPosition.y += pickRay.origin.y; + targetPosition.z += pickRay.origin.z; + + if (targetPosition.x < 0) targetPosition.x = 0; + if (targetPosition.y < 0) targetPosition.y = 0; + if (targetPosition.z < 0) targetPosition.z = 0; + + var nudgeFactor = scaleSelector.scale; + var newPosition = { + x: Math.floor(targetPosition.x / nudgeFactor) * nudgeFactor, + y: Math.floor(targetPosition.y / nudgeFactor) * nudgeFactor, + z: Math.floor(targetPosition.z / nudgeFactor) * nudgeFactor + } + + moveImport(newPosition); + } + + if (isAdding) { // Watch the drag direction to tell which way to 'extrude' this voxel if (!isExtruding) { var pickRay = Camera.computePickRay(event.x, event.y); @@ -1220,16 +1273,13 @@ function mouseReleaseEvent(event) { return; } - if (isMovingSlider) { - isMovingSlider = false; - } isAdding = false; isExtruding = false; } function moveTools() { // move the swatches - swatchesX = (windowDimensions.x - (swatchesWidth + sliderWidth)) / 2; + swatchesX = (windowDimensions.x - (swatchesWidth + scaleSelectorWidth)) / 2; swatchesY = windowDimensions.y - swatchHeight + 1; // create the overlays, position them in a row, set their colors, and for the selected one, use a different source image @@ -1302,14 +1352,7 @@ function moveTools() { visible: editToolsOn }); - sliderX = swatchesX + swatchesWidth - sliderOffsetX; - sliderY = windowDimensions.y - sliderHeight + 1; - thumbY = sliderY + thumbOffsetY; - Overlays.editOverlay(slider, { x: sliderX, y: sliderY, visible: editToolsOn }); - - // This is the thumb of our slider - Overlays.editOverlay(thumb, { x: sliderX + thumbX, y: thumbY, visible: editToolsOn }); - + scaleSelector.move(); } var lastFingerAddVoxel = { x: -1, y: -1, z: -1}; // off of the build-able area @@ -1330,11 +1373,7 @@ function checkControllers() { if (Controller.isButtonPressed(BUTTON_1)) { if (Vec3.length(Vec3.subtract(fingerTipPosition,lastFingerAddVoxel)) > (FINGERTIP_VOXEL_SIZE / 2)) { - if (whichColor == -1) { - newColor = { red: colors[0].red, green: colors[0].green, blue: colors[0].blue }; - } else { - newColor = { red: colors[whichColor].red, green: colors[whichColor].green, blue: colors[whichColor].blue }; - } + newColor = { red: colors[whichColor].red, green: colors[whichColor].green, blue: colors[whichColor].blue }; Voxels.eraseVoxel(fingerTipPosition.x, fingerTipPosition.y, fingerTipPosition.z, FINGERTIP_VOXEL_SIZE); Voxels.setVoxel(fingerTipPosition.x, fingerTipPosition.y, fingerTipPosition.z, FINGERTIP_VOXEL_SIZE, @@ -1360,19 +1399,6 @@ function update(deltaTime) { } checkControllers(); - - // Move Import Preview - if (isImporting) { - var position = MyAvatar.position; - var forwardVector = Quat.getFront(MyAvatar.orientation); - var targetPosition = Vec3.sum(position, Vec3.multiply(forwardVector, importScale)); - var newPosition = { - x: Math.floor(targetPosition.x / importScale) * importScale, - y: Math.floor(targetPosition.y / importScale) * importScale, - z: Math.floor(targetPosition.z / importScale) * importScale - } - moveImport(newPosition); - } } } @@ -1380,28 +1406,17 @@ function wheelEvent(event) { wheelPixelsMoved += event.delta; if (Math.abs(wheelPixelsMoved) > WHEEL_PIXELS_PER_SCALE_CHANGE) { - if (!pointerVoxelScaleSet) { - pointerVoxelScale = 1.0; - pointerVoxelScaleSet = true; - } + if (wheelPixelsMoved > 0) { - pointerVoxelScale /= 2.0; - if (pointerVoxelScale < MIN_VOXEL_SCALE) { - pointerVoxelScale = MIN_VOXEL_SCALE; - } + scaleSelector.decrementScale(); } else { - pointerVoxelScale *= 2.0; - if (pointerVoxelScale > MAX_VOXEL_SCALE) { - pointerVoxelScale = MAX_VOXEL_SCALE; - } + scaleSelector.incrementScale(); } - calcThumbFromScale(pointerVoxelScale); trackMouseEvent(event); wheelPixelsMoved = 0; if (isImporting) { - var importScale = (pointerVoxelScale / MAX_VOXEL_SCALE) * MAX_PASTE_VOXEL_SCALE; - rescaleImport(importScale); + rescaleImport(); } } } @@ -1428,11 +1443,10 @@ function scriptEnding() { Overlays.deleteOverlay(voxelTool); Overlays.deleteOverlay(recolorTool); Overlays.deleteOverlay(eyedropperTool); - Overlays.deleteOverlay(slider); - Overlays.deleteOverlay(thumb); Controller.releaseKeyEvents({ text: "+" }); Controller.releaseKeyEvents({ text: "-" }); cleanupImport(); + scaleSelector.cleanup(); cleanupMenus(); } Script.scriptEnding.connect(scriptEnding); From 7782e53363cbccec15fd5d2931e13d35b19ab6c7 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Fri, 18 Apr 2014 16:26:10 -0700 Subject: [PATCH 517/595] Restored scale copy --- examples/editVoxels.js | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/examples/editVoxels.js b/examples/editVoxels.js index d9d1af8461..d9284a940d 100644 --- a/examples/editVoxels.js +++ b/examples/editVoxels.js @@ -290,6 +290,8 @@ var eyedropperTool = Overlays.addOverlay("image", { alpha: 0.9 }); + +var copyScale = true; function ScaleSelector() { this.x = swatchesX + swatchesWidth; this.y = swatchesY; @@ -327,6 +329,11 @@ function ScaleSelector() { alpha: 0.0, visible: false }); + this.setScale = function(scale) { + this.scale = scale; + this.power = Math.floor(Math.log(scale)); + } + this.show = function(doShow) { Overlays.editOverlay(this.buttonsOverlay, {visible: doShow}); Overlays.editOverlay(this.textOverlay, {visible: doShow}); @@ -381,6 +388,7 @@ function ScaleSelector() { } this.incrementScale = function() { + copyScale = false; if (this.power < 13) { ++this.power; this.scale *= 2.0; @@ -390,6 +398,7 @@ function ScaleSelector() { } this.decrementScale = function() { + copyScale = false; if (-4 < this.power) { --this.power; this.scale /= 2.0; @@ -820,6 +829,11 @@ function showPreviewLines() { Overlays.editOverlay(linePreviewLeft, { position: resultVoxel.topLeft, end: resultVoxel.bottomLeft, visible: true }); Overlays.editOverlay(linePreviewRight, { position: resultVoxel.topRight, end: resultVoxel.bottomRight, visible: true }); colors[0] = {red: intersection.voxel.red, green: intersection.voxel.green , blue: intersection.voxel.blue }; + + if (copyScale) { + scaleSelector.setScale(intersection.voxel.s); + scaleSelector.update(); + } moveTools(); } else { Overlays.editOverlay(voxelPreview, { visible: false }); @@ -1053,7 +1067,9 @@ function keyPressEvent(event) { // if our tools are off, then don't do anything if (editToolsOn) { var nVal = parseInt(event.text); - if ((nVal > 0) && (nVal <= numColors)) { + if (event.text == "`") { + copyScale = true; + } else if ((nVal > 0) && (nVal <= numColors)) { whichColor = nVal - 1; print("Color = " + (whichColor + 1)); swatchesSound.play(whichColor); From 178f845ad02ceaf0e2a36a068dc1e323e4ecda9d Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Fri, 18 Apr 2014 16:40:13 -0700 Subject: [PATCH 518/595] Rescale import when using keys +/- --- examples/editVoxels.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/examples/editVoxels.js b/examples/editVoxels.js index d9284a940d..12c571b09c 100644 --- a/examples/editVoxels.js +++ b/examples/editVoxels.js @@ -332,6 +332,7 @@ function ScaleSelector() { this.setScale = function(scale) { this.scale = scale; this.power = Math.floor(Math.log(scale)); + rescaleImport(); } this.show = function(doShow) { @@ -393,6 +394,7 @@ function ScaleSelector() { ++this.power; this.scale *= 2.0; this.update(); + rescaleImport(); resizeVoxelSound.play(voxelSizePlus); } } @@ -403,6 +405,7 @@ function ScaleSelector() { --this.power; this.scale /= 2.0; this.update(); + rescaleImport(); resizeVoxelSound.play(voxelSizePlus); } } From c664b4a087c7d0489890d0d2eedc24e472ec4be0 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Fri, 18 Apr 2014 17:04:38 -0700 Subject: [PATCH 519/595] Fixed JSON parsing --- interface/src/ModelUploader.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index c6376430db..048e13bdf2 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -238,9 +238,9 @@ void ModelUploader::checkJSON(const QJsonObject& jsonResponse) { callbackParams.updateReciever = this; callbackParams.updateSlot = SLOT(uploadUpdate(qint64, qint64)); - if (jsonResponse.contains("exists") && jsonResponse.value("exists").toString() == "true") { + if (jsonResponse.contains("exists") && jsonResponse.value("exists").toBool()) { qDebug() << "exists : true"; - if (jsonResponse.contains("can_update") && jsonResponse.value("can_update").toString() == "true") { + if (jsonResponse.contains("can_update") && jsonResponse.value("can_update").toBool()) { qDebug() << "can_update : true"; AccountManager::getInstance().authenticatedRequest(MODEL_URL + "/" + QFileInfo(_url).baseName(), From 05545b684d02ebb589007e8b62d1905400fa2738 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Fri, 18 Apr 2014 17:47:21 -0700 Subject: [PATCH 520/595] Made glowing when speaking an option --- interface/src/Menu.cpp | 3 ++- interface/src/Menu.h | 1 + interface/src/avatar/Avatar.cpp | 11 ++++++++--- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index b05e5c91bc..7cdd72afd5 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -315,7 +315,8 @@ Menu::Menu() : addCheckableActionToQMenuAndActionHash(avatarOptionsMenu, MenuOption::Visage, 0, true, appInstance->getVisage(), SLOT(updateEnabled())); #endif - + + addCheckableActionToQMenuAndActionHash(avatarOptionsMenu, MenuOption::GlowWhenSpeaking, 0, true); addCheckableActionToQMenuAndActionHash(avatarOptionsMenu, MenuOption::ChatCircling, 0, false); QMenu* handOptionsMenu = developerMenu->addMenu("Hand Options"); diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 10d3376be5..597ae4a74b 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -304,6 +304,7 @@ namespace MenuOption { const QString Fullscreen = "Fullscreen"; const QString FullscreenMirror = "Fullscreen Mirror"; const QString GlowMode = "Cycle Glow Mode"; + const QString GlowWhenSpeaking = "Glow When Speaking"; const QString GoHome = "Go Home"; const QString GoTo = "Go To..."; const QString GoToDomain = "Go To Domain..."; diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 8cfab7da03..fe685b89f8 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -211,9 +211,14 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode) { const float GLOW_DISTANCE = 20.0f; const float GLOW_MAX_LOUDNESS = 2500.0f; const float MAX_GLOW = 0.5f; - const float GLOW_FROM_AVERAGE_LOUDNESS = ((this == Application::getInstance()->getAvatar()) - ? 0.0f - : MAX_GLOW * getHeadData()->getAudioLoudness() / GLOW_MAX_LOUDNESS); + + float GLOW_FROM_AVERAGE_LOUDNESS = ((this == Application::getInstance()->getAvatar()) + ? 0.0f + : MAX_GLOW * getHeadData()->getAudioLoudness() / GLOW_MAX_LOUDNESS); + if (!Menu::getInstance()->isOptionChecked(MenuOption::GlowWhenSpeaking)) { + GLOW_FROM_AVERAGE_LOUDNESS = 0.0f; + } + Glower glower(_moving && distanceToTarget > GLOW_DISTANCE && renderMode == NORMAL_RENDER_MODE ? 1.0f : GLOW_FROM_AVERAGE_LOUDNESS); From 716bc58c2d5f2f2a6d326d4eee8fe511a7a9b824 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Fri, 18 Apr 2014 18:10:11 -0700 Subject: [PATCH 521/595] Fixed Jenkins failure --- interface/src/Util.cpp | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 5238db9b13..1dae3a4fd6 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -186,22 +186,16 @@ const glm::vec3 randVector() { } static TextRenderer* textRenderer(int mono) { + static TextRenderer* monoRenderer = new TextRenderer(MONO_FONT_FAMILY); + static TextRenderer* proportionalRenderer = new TextRenderer(SANS_FONT_FAMILY, -1, -1, false, TextRenderer::SHADOW_EFFECT); + static TextRenderer* inconsolataRenderer = new TextRenderer(INCONSOLATA_FONT_FAMILY, -1, QFont::Bold, false); switch (mono) { case 1: - static TextRenderer* monoRenderer = new TextRenderer(MONO_FONT_FAMILY); return monoRenderer; case 2: - static TextRenderer* inconsolataRenderer = new TextRenderer(INCONSOLATA_FONT_FAMILY, - -1, - QFont::Bold, false); return inconsolataRenderer; case 0: default: - static TextRenderer* proportionalRenderer = new TextRenderer(SANS_FONT_FAMILY, - -1, - -1, - false, - TextRenderer::SHADOW_EFFECT); return proportionalRenderer; } } From 6c376d6fa6701f981310dc1126fe1871f81ee368 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Sat, 19 Apr 2014 15:02:57 +0200 Subject: [PATCH 522/595] Add PageUp/Down to controls When you press PageUp/Down now you fly up and down. --- interface/src/Application.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 0abcd9d1af..ca5bb260b6 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -821,7 +821,7 @@ void Application::keyPressEvent(QKeyEvent* event) { } break; - case Qt::Key_E: + case Qt::Key_E: case Qt::Key_PageUp: if (!_myAvatar->getDriveKeys(UP)) { _myAvatar->jump(); } @@ -832,7 +832,7 @@ void Application::keyPressEvent(QKeyEvent* event) { Menu::getInstance()->triggerOption(MenuOption::Stars); break; - case Qt::Key_C: + case Qt::Key_C: case Qt::Key_PageDown: _myAvatar->setDriveKeys(DOWN, 1.f); break; @@ -1018,11 +1018,11 @@ void Application::keyReleaseEvent(QKeyEvent* event) { } switch (event->key()) { - case Qt::Key_E: + case Qt::Key_E: case Qt::Key_PageUp: _myAvatar->setDriveKeys(UP, 0.f); break; - case Qt::Key_C: + case Qt::Key_C: case Qt::Key_PageDown: _myAvatar->setDriveKeys(DOWN, 0.f); break; From 615f8b8dadb703e5be7f432f842deb065a6d5764 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Sat, 19 Apr 2014 16:35:48 +0200 Subject: [PATCH 523/595] Fix spacing --- interface/src/Application.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index ca5bb260b6..107d3c6482 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -821,7 +821,8 @@ void Application::keyPressEvent(QKeyEvent* event) { } break; - case Qt::Key_E: case Qt::Key_PageUp: + case Qt::Key_E: + case Qt::Key_PageUp: if (!_myAvatar->getDriveKeys(UP)) { _myAvatar->jump(); } @@ -832,7 +833,8 @@ void Application::keyPressEvent(QKeyEvent* event) { Menu::getInstance()->triggerOption(MenuOption::Stars); break; - case Qt::Key_C: case Qt::Key_PageDown: + case Qt::Key_C: + case Qt::Key_PageDown: _myAvatar->setDriveKeys(DOWN, 1.f); break; @@ -1018,11 +1020,13 @@ void Application::keyReleaseEvent(QKeyEvent* event) { } switch (event->key()) { - case Qt::Key_E: case Qt::Key_PageUp: + case Qt::Key_E: + case Qt::Key_PageUp: _myAvatar->setDriveKeys(UP, 0.f); break; - case Qt::Key_C: case Qt::Key_PageDown: + case Qt::Key_C: + case Qt::Key_PageDown: _myAvatar->setDriveKeys(DOWN, 0.f); break; From 59cbda20c67432858d837b1b518cb702e8679504 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Sun, 20 Apr 2014 19:48:17 -0700 Subject: [PATCH 524/595] added some threading and event debugging --- assignment-client/src/AssignmentClient.cpp | 11 +++++++++++ assignment-client/src/octree/OctreeServer.cpp | 19 +++++++++++++++++++ assignment-client/src/octree/OctreeServer.h | 2 ++ .../networking/src/ThreadedAssignment.cpp | 8 ++++++++ 4 files changed, 40 insertions(+) diff --git a/assignment-client/src/AssignmentClient.cpp b/assignment-client/src/AssignmentClient.cpp index d60885e2a7..e4b38258f0 100644 --- a/assignment-client/src/AssignmentClient.cpp +++ b/assignment-client/src/AssignmentClient.cpp @@ -17,11 +17,13 @@ #include #include +#include #include #include #include #include + #include "AssignmentFactory.h" #include "AssignmentThread.h" @@ -144,6 +146,11 @@ void AssignmentClient::readPendingDatagrams() { // start the deployed assignment AssignmentThread* workerThread = new AssignmentThread(_currentAssignment, this); + qDebug() << "workerThread->eventDispatcher()=" << workerThread->eventDispatcher(); + qDebug() << "thread()->eventDispatcher()=" << thread()->eventDispatcher(); + + //DebuggingEventDispatcher* debugDispatcher = new DebuggingEventDispatcher(workerThread); + connect(workerThread, &QThread::started, _currentAssignment.data(), &ThreadedAssignment::run); connect(_currentAssignment.data(), &ThreadedAssignment::finished, workerThread, &QThread::quit); connect(_currentAssignment.data(), &ThreadedAssignment::finished, @@ -162,6 +169,10 @@ void AssignmentClient::readPendingDatagrams() { // Starts an event loop, and emits workerThread->started() workerThread->start(); + + qDebug() << "workerThread->eventDispatcher()=" << workerThread->eventDispatcher(); + qDebug() << "thread()->eventDispatcher()=" << thread()->eventDispatcher(); + } else { qDebug() << "Received an assignment that could not be unpacked. Re-requesting."; } diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 1a593f3be7..24d179b707 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -9,6 +9,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include #include #include #include @@ -842,6 +843,9 @@ quint64 lastReadPendingDatagrams = usecTimestampNow(); quint64 lastProcessNodeData = usecTimestampNow(); void OctreeServer::readPendingDatagrams() { + qDebug() << "OctreeServer::readPendingDatagrams()... thread()->eventDispatcher()=" << thread()->eventDispatcher(); + + quint64 now = usecTimestampNow(); if ((now - lastReadPendingDatagrams) > 100000) { //qDebug() << "OctreeServer::readPendingDatagrams(): since lastReadPendingDatagrams=" << (now - lastReadPendingDatagrams) << "usecs"; @@ -969,7 +973,22 @@ qDebug() << "got a query..."; } +void OctreeServer::aboutToBlock() { + qDebug() << "OctreeServer::aboutToBlock()..."; +} + +void OctreeServer::awake() { + qDebug() << "OctreeServer::awake()..."; +} + void OctreeServer::run() { + + QAbstractEventDispatcher* eventDispatcher = thread()->eventDispatcher(); + qDebug() << "OctreeServer::run()... thread()->eventDispatcher()=" << eventDispatcher; + + connect(eventDispatcher, &QAbstractEventDispatcher::aboutToBlock, this, &OctreeServer::aboutToBlock); + connect(eventDispatcher, &QAbstractEventDispatcher::awake, this, &OctreeServer::awake); + _safeServerName = getMyServerName(); // Before we do anything else, create our tree... diff --git a/assignment-client/src/octree/OctreeServer.h b/assignment-client/src/octree/OctreeServer.h index 7427ee0dbe..1b57f3e63d 100644 --- a/assignment-client/src/octree/OctreeServer.h +++ b/assignment-client/src/octree/OctreeServer.h @@ -127,6 +127,8 @@ public slots: void nodeKilled(SharedNodePointer node); void sendStatsPacket(); void doNothing(); + void awake(); + void aboutToBlock(); protected: void parsePayload(); diff --git a/libraries/networking/src/ThreadedAssignment.cpp b/libraries/networking/src/ThreadedAssignment.cpp index 528c0b0ff3..d3de3cdd74 100644 --- a/libraries/networking/src/ThreadedAssignment.cpp +++ b/libraries/networking/src/ThreadedAssignment.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include "Logging.h" #include "SharedUtil.h" @@ -57,6 +58,9 @@ void ThreadedAssignment::commonInit(const QString& targetName, NodeType_t nodeTy connect(statsTimer, &QTimer::timeout, this, &ThreadedAssignment::sendStatsPacket); statsTimer->start(1000); } + + qDebug() << "ThreadedAssignment::commonInit()... thread()->eventDispatcher()=" << thread()->eventDispatcher(); + } void ThreadedAssignment::addPacketStatsAndSendStatsPacket(QJsonObject &statsObject) { @@ -79,6 +83,10 @@ void ThreadedAssignment::sendStatsPacket() { quint64 lastCheckIn = usecTimestampNow(); void ThreadedAssignment::checkInWithDomainServerOrExit() { + + qDebug() << "ThreadedAssignment::checkInWithDomainServerOrExit()... thread()->eventDispatcher()=" << thread()->eventDispatcher(); + + quint64 now = usecTimestampNow(); if ((now - lastCheckIn) > 100000) { //qDebug() << "ThreadedAssignment::checkInWithDomainServerOrExit(): since lastCheckIn=" << (now - lastCheckIn) << "usecs"; From 80dd0c33568c4977ff2ab805a2d74e7e2ea9afb9 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Sun, 20 Apr 2014 20:18:56 -0700 Subject: [PATCH 525/595] fix switching audio device bug --- interface/src/Audio.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 830e2fe69b..698a8db725 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -1068,7 +1068,6 @@ bool Audio::switchOutputToAudioDevice(const QAudioDeviceInfo& outputDeviceInfo) delete _audioOutput; _audioOutput = NULL; - _numInputCallbackBytes = 0; _loopbackOutputDevice = NULL; delete _loopbackAudioOutput; From c016d6557ef5f473b866a0e850718aa2401bde67 Mon Sep 17 00:00:00 2001 From: Thijs Wenker Date: Mon, 21 Apr 2014 05:25:28 +0200 Subject: [PATCH 526/595] - few Adjustments in Application class for Script editor - Shortkey for script editor (Alt+S) - highlighter: bold true/false , single line comments - Run scripts from the editor works - More icons from Maximillian, Thanks - Run on the fly checkbox, works if the script is running. - Load/save features --- interface/resources/icons/start-script.svg | 557 +++++++++++++++++++ interface/resources/icons/stop-script.svg | 163 ++++++ interface/src/Application.cpp | 35 +- interface/src/Application.h | 2 +- interface/src/Menu.cpp | 4 +- interface/src/ScriptHighlighting.cpp | 26 +- interface/src/ScriptHighlighting.h | 13 +- interface/src/ui/ScriptEditorWidget.cpp | 114 ++++ interface/src/ui/ScriptEditorWidget.h | 22 + interface/src/ui/ScriptEditorWindow.cpp | 148 ++++- interface/src/ui/ScriptEditorWindow.h | 17 +- interface/ui/ScriptEditorWidget.ui | 13 +- interface/ui/ScriptEditorWindow.ui | 69 ++- libraries/script-engine/src/ScriptEngine.cpp | 24 +- libraries/script-engine/src/ScriptEngine.h | 7 + 15 files changed, 1163 insertions(+), 51 deletions(-) create mode 100644 interface/resources/icons/start-script.svg create mode 100644 interface/resources/icons/stop-script.svg diff --git a/interface/resources/icons/start-script.svg b/interface/resources/icons/start-script.svg new file mode 100644 index 0000000000..86354a555d --- /dev/null +++ b/interface/resources/icons/start-script.svg @@ -0,0 +1,557 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + Maximillian Merlin + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/interface/resources/icons/stop-script.svg b/interface/resources/icons/stop-script.svg new file mode 100644 index 0000000000..31cdcee749 --- /dev/null +++ b/interface/resources/icons/stop-script.svg @@ -0,0 +1,163 @@ + + + + + + + + + + image/svg+xml + + + + + Maximillian Merlin + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 438722df17..769791d09f 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -797,6 +797,7 @@ void Application::keyPressEvent(QKeyEvent* event) { if (activeWindow() == _window) { bool isShifted = event->modifiers().testFlag(Qt::ShiftModifier); bool isMeta = event->modifiers().testFlag(Qt::ControlModifier); + bool isOption = event->modifiers().testFlag(Qt::AltModifier); switch (event->key()) { break; case Qt::Key_BracketLeft: @@ -839,9 +840,11 @@ void Application::keyPressEvent(QKeyEvent* event) { break; case Qt::Key_S: - if (isShifted && isMeta) { + if (isShifted && isMeta && !isOption) { Menu::getInstance()->triggerOption(MenuOption::SuppressShortTimings); - } else if (!isShifted && isMeta) { + } else if (isOption && !isShifted && !isMeta) { + Menu::getInstance()->triggerOption(MenuOption::ScriptEditor); + } else if (!isOption && !isShifted && isMeta) { takeSnapshot(); } else { _myAvatar->setDriveKeys(BACK, 1.f); @@ -3299,13 +3302,14 @@ void Application::stopAllScripts() { bumpSettings(); } -void Application::stopScript(const QString &scriptName) -{ - _scriptEnginesHash.value(scriptName)->stop(); - qDebug() << "stopping script..." << scriptName; - _scriptEnginesHash.remove(scriptName); - _runningScriptsWidget->setRunningScripts(getRunningScripts()); - bumpSettings(); +void Application::stopScript(const QString &scriptName) { + if (_scriptEnginesHash.contains(scriptName)) { + _scriptEnginesHash.value(scriptName)->stop(); + qDebug() << "stopping script..." << scriptName; + _scriptEnginesHash.remove(scriptName); + _runningScriptsWidget->setRunningScripts(getRunningScripts()); + bumpSettings(); + } } void Application::reloadAllScripts() { @@ -3366,7 +3370,10 @@ void Application::uploadSkeleton() { uploadFST(false); } -void Application::loadScript(const QString& scriptName) { +ScriptEngine* Application::loadScript(const QString& scriptName, bool focusMainWindow) { + if(_scriptEnginesHash.contains(scriptName) && !_scriptEnginesHash[scriptName]->isFinished()){ + return _scriptEnginesHash[scriptName]; + } // start the script on a new thread... ScriptEngine* scriptEngine = new ScriptEngine(QUrl(scriptName), &_controllerScriptingInterface); @@ -3374,7 +3381,7 @@ void Application::loadScript(const QString& scriptName) { if (!scriptEngine->hasScript()) { qDebug() << "Application::loadScript(), script failed to load..."; - return; + return NULL; } _runningScriptsWidget->setRunningScripts(getRunningScripts()); @@ -3422,8 +3429,12 @@ void Application::loadScript(const QString& scriptName) { workerThread->start(); // restore the main window's active state - _window->activateWindow(); + if (focusMainWindow) { + _window->activateWindow(); + } bumpSettings(); + + return scriptEngine; } void Application::loadDialog() { diff --git a/interface/src/Application.h b/interface/src/Application.h index 00b71c4ce7..3254c874b6 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -121,7 +121,7 @@ public: ~Application(); void restoreSizeAndPosition(); - void loadScript(const QString& fileNameString); + ScriptEngine* loadScript(const QString& fileNameString, bool focusMainWindow = true); void loadScripts(); void storeSizeAndPosition(); void clearScriptsBeforeRunning(); diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 6f70c5616c..4e6dd2eec2 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -195,7 +195,7 @@ Menu::Menu() : QMenu* toolsMenu = addMenu("Tools"); addActionToQMenuAndActionHash(toolsMenu, MenuOption::MetavoxelEditor, 0, this, SLOT(showMetavoxelEditor())); - addActionToQMenuAndActionHash(toolsMenu, MenuOption::ScriptEditor, Qt::CTRL | Qt::SHIFT | Qt::Key_S, this, SLOT(showScriptEditor())); + addActionToQMenuAndActionHash(toolsMenu, MenuOption::ScriptEditor, Qt::ALT | Qt::Key_S, this, SLOT(showScriptEditor())); #ifdef HAVE_QXMPP _chatAction = addActionToQMenuAndActionHash(toolsMenu, @@ -1125,7 +1125,7 @@ void Menu::showMetavoxelEditor() { } void Menu::showScriptEditor() { - if(!_ScriptEditor) { + if(!_ScriptEditor || !_ScriptEditor->isVisible()) { _ScriptEditor = new ScriptEditorWindow(); } _ScriptEditor->raise(); diff --git a/interface/src/ScriptHighlighting.cpp b/interface/src/ScriptHighlighting.cpp index 119926742c..b2c5ca2ec6 100644 --- a/interface/src/ScriptHighlighting.cpp +++ b/interface/src/ScriptHighlighting.cpp @@ -10,6 +10,7 @@ // #include "ScriptHighlighting.h" +#include ScriptHighlighting::ScriptHighlighting(QTextDocument* parent) : QSyntaxHighlighter(parent) @@ -19,13 +20,16 @@ ScriptHighlighting::ScriptHighlighting(QTextDocument* parent) : multiLineCommentBegin = QRegExp("/\\*"); multiLineCommentEnd = QRegExp("\\*/"); numberRegex = QRegExp("[0-9]+(\\.[0-9]+){0,1}"); + singleLineComment = QRegExp("//[^\n]*"); + truefalseRegex = QRegExp("\\b(true|false)\\b"); } void ScriptHighlighting::highlightBlock(const QString &text) { this->highlightKeywords(text); - this->formatComments(text); - this->formatQoutedText(text); this->formatNumbers(text); + this->formatTrueFalse(text); + this->formatQoutedText(text); + this->formatComments(text); } void ScriptHighlighting::highlightKeywords(const QString &text) { @@ -50,6 +54,13 @@ void ScriptHighlighting::formatComments(const QString &text) { start = text.indexOf(multiLineCommentBegin, start + length); if (end == -1) setCurrentBlockState(BlockStateInMultiComment); } + + int index = singleLineComment.indexIn(text); + while (index >= 0) { + int length = singleLineComment.matchedLength(); + setFormat(index, length, Qt::lightGray); + index = singleLineComment.indexIn(text, index + length); + } } void ScriptHighlighting::formatQoutedText(const QString &text){ @@ -69,3 +80,14 @@ void ScriptHighlighting::formatNumbers(const QString &text){ index = numberRegex.indexIn(text, index + length); } } + +void ScriptHighlighting::formatTrueFalse(const QString text){ + int index = truefalseRegex.indexIn(text); + while (index >= 0) { + int length = truefalseRegex.matchedLength(); + QFont* font = new QFont(this->document()->defaultFont()); + font->setBold(true); + setFormat(index, length, *font); + index = truefalseRegex.indexIn(text, index + length); + } +} \ No newline at end of file diff --git a/interface/src/ScriptHighlighting.h b/interface/src/ScriptHighlighting.h index b9567cb06a..9cbbf277cc 100644 --- a/interface/src/ScriptHighlighting.h +++ b/interface/src/ScriptHighlighting.h @@ -26,11 +26,12 @@ public: }; protected: - void highlightBlock(const QString &text); - void highlightKeywords(const QString &text); - void formatComments(const QString &text); - void formatQoutedText(const QString &text); - void formatNumbers(const QString &text); + void highlightBlock(const QString& text); + void highlightKeywords(const QString& text); + void formatComments(const QString& text); + void formatQoutedText(const QString& text); + void formatNumbers(const QString& text); + void formatTrueFalse(const QString text); private: QRegExp keywordRegex; @@ -38,6 +39,8 @@ private: QRegExp multiLineCommentBegin; QRegExp multiLineCommentEnd; QRegExp numberRegex; + QRegExp singleLineComment; + QRegExp truefalseRegex; }; #endif // hifi_ScriptHighlighting_h diff --git a/interface/src/ui/ScriptEditorWidget.cpp b/interface/src/ui/ScriptEditorWidget.cpp index 618e405448..98b6f2fe96 100644 --- a/interface/src/ui/ScriptEditorWidget.cpp +++ b/interface/src/ui/ScriptEditorWidget.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -30,13 +31,126 @@ ScriptEditorWidget::ScriptEditorWidget() : { ui->setupUi(this); + scriptEngine = NULL; + + connect(ui->scriptEdit->document(), SIGNAL(modificationChanged(bool)), this, SIGNAL(scriptModified())); + connect(ui->scriptEdit->document(), SIGNAL(contentsChanged()), this, SLOT(onScriptModified())); + // remove the title bar (see the Qt docs on setTitleBarWidget) setTitleBarWidget(new QWidget()); QFontMetrics fm(this->ui->scriptEdit->font()); this->ui->scriptEdit->setTabStopWidth(fm.width('0') * 4); ScriptHighlighting* highlighting = new ScriptHighlighting(this->ui->scriptEdit->document()); + QTimer::singleShot(0, this->ui->scriptEdit, SLOT(setFocus())); } ScriptEditorWidget::~ScriptEditorWidget() { delete ui; +} + +void ScriptEditorWidget::onScriptModified() { + if(ui->onTheFlyCheckBox->isChecked() && isRunning()) { + setRunning(false); + setRunning(true); + } +} + +bool ScriptEditorWidget::isModified() { + return ui->scriptEdit->document()->isModified(); +} + +bool ScriptEditorWidget::isRunning() { + return (scriptEngine != NULL) ? scriptEngine->isRunning() : false; +} + +bool ScriptEditorWidget::setRunning(bool run) { + if (run && !save()) { + return false; + } + // Clean-up old connections. + disconnect(this, SLOT(onScriptError(const QString&))); + disconnect(this, SLOT(onScriptPrint(const QString&))); + + if (run) { + scriptEngine = Application::getInstance()->loadScript(this->currentScript, false); + connect(scriptEngine, SIGNAL(runningStateChanged()), this, SIGNAL(runningStateChanged())); + + // Make new connections. + connect(scriptEngine, SIGNAL(errorMessage(const QString&)), this, SLOT(onScriptError(const QString&))); + connect(scriptEngine, SIGNAL(printedMessage(const QString&)), this, SLOT(onScriptPrint(const QString&))); + } else { + Application::getInstance()->stopScript(this->currentScript); + scriptEngine = NULL; + } + return true; +} + +bool ScriptEditorWidget::saveFile(const QString &scriptPath) { + QFile file(scriptPath); + if (!file.open(QFile::WriteOnly | QFile::Text)) { + QMessageBox::warning(this, tr("Interface"), tr("Cannot write script %1:\n%2.").arg(scriptPath).arg(file.errorString())); + return false; + } + + QTextStream out(&file); + out << ui->scriptEdit->toPlainText(); + + setScriptFile(scriptPath); + return true; +} + +void ScriptEditorWidget::loadFile(const QString &scriptPath) { + QFile file(scriptPath); + if (!file.open(QFile::ReadOnly | QFile::Text)) { + QMessageBox::warning(this, tr("Interface"), tr("Cannot read script %1:\n%2.").arg(scriptPath).arg(file.errorString())); + return; + } + + QTextStream in(&file); + ui->scriptEdit->setPlainText(in.readAll()); + + setScriptFile(scriptPath); + + disconnect(this, SLOT(onScriptError(const QString&))); + disconnect(this, SLOT(onScriptPrint(const QString&))); + + scriptEngine = Application::getInstance()->getScriptEngine(scriptPath); + if (scriptEngine != NULL) { + connect(scriptEngine, SIGNAL(runningStateChanged()), this, SIGNAL(runningStateChanged())); + connect(scriptEngine, SIGNAL(errorMessage(const QString&)), this, SLOT(onScriptError(const QString&))); + connect(scriptEngine, SIGNAL(printedMessage(const QString&)), this, SLOT(onScriptPrint(const QString&))); + } +} + +bool ScriptEditorWidget::save() { + return currentScript.isEmpty() ? saveAs() : saveFile(currentScript); +} + +bool ScriptEditorWidget::saveAs() { + QString fileName = QFileDialog::getSaveFileName(this, tr("Save script"), QString(), tr("Javascript (*.js)")); + return !fileName.isEmpty() ? saveFile(fileName) : false; +} + +void ScriptEditorWidget::setScriptFile(const QString& scriptPath) { + currentScript = scriptPath; + ui->scriptEdit->document()->setModified(false); + setWindowModified(false); + + emit scriptnameChanged(); +} + +bool ScriptEditorWidget::questionSave() { + if (ui->scriptEdit->document()->isModified()) { + QMessageBox::StandardButton button = QMessageBox::warning(this, tr("Interface"), tr("The script has been modified.\nDo you want to save your changes?"), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Save); + return button == QMessageBox::Save ? save() : (button == QMessageBox::Cancel ? false : true); + } + return true; +} + +void ScriptEditorWidget::onScriptError(const QString& message) { + ui->debugText->appendPlainText("ERROR: "+ message); +} + +void ScriptEditorWidget::onScriptPrint(const QString& message) { + ui->debugText->appendPlainText("> "+message); } \ No newline at end of file diff --git a/interface/src/ui/ScriptEditorWidget.h b/interface/src/ui/ScriptEditorWidget.h index 931ec105c9..674304acb6 100644 --- a/interface/src/ui/ScriptEditorWidget.h +++ b/interface/src/ui/ScriptEditorWidget.h @@ -27,8 +27,30 @@ public: ScriptEditorWidget(); ~ScriptEditorWidget(); + bool isModified(); + bool isRunning(); + bool setRunning(bool run); + bool saveFile(const QString& scriptPath); + void loadFile(const QString& scriptPath); + void setScriptFile(const QString& scriptPath); + bool save(); + bool saveAs(); + bool questionSave(); + const QString getScriptName() const { return currentScript; }; +signals: + void runningStateChanged(); + void scriptnameChanged(); + void scriptModified(); + +private slots: + void onScriptError(const QString& message); + void onScriptPrint(const QString& message); + void onScriptModified(); + private: Ui::ScriptEditorWidget* ui; + ScriptEngine* scriptEngine; + QString currentScript; }; #endif // hifi_ScriptEditorWidget_h diff --git a/interface/src/ui/ScriptEditorWindow.cpp b/interface/src/ui/ScriptEditorWindow.cpp index 38fa26622a..687b992c5f 100644 --- a/interface/src/ui/ScriptEditorWindow.cpp +++ b/interface/src/ui/ScriptEditorWindow.cpp @@ -13,8 +13,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -31,32 +33,158 @@ ScriptEditorWindow::ScriptEditorWindow() : { ui->setupUi(this); show(); + addScriptEditorWidget("New script"); + loadMenu = new QMenu(); + connect(loadMenu, SIGNAL(aboutToShow()), this, SLOT(loadMenuAboutToShow())); + ui->loadButton->setMenu(loadMenu); + + saveMenu = new QMenu(); + saveMenu->addAction("Save as..", this, SLOT(saveScriptAsClicked()), Qt::CTRL|Qt::SHIFT|Qt::Key_S); + + ui->saveButton->setMenu(saveMenu); + + connect(new QShortcut(QKeySequence("Ctrl+N"), this), SIGNAL(activated()), this, SLOT(newScriptClicked())); + connect(new QShortcut(QKeySequence("Ctrl+S"), this), SIGNAL(activated()), this, SLOT(saveScriptClicked())); + connect(new QShortcut(QKeySequence("Ctrl+O"), this), SIGNAL(activated()), this, SLOT(loadScriptClicked())); + connect(new QShortcut(QKeySequence("F5"), this), SIGNAL(activated()), this, SLOT(toggleRunScriptClicked())); } ScriptEditorWindow::~ScriptEditorWindow() { delete ui; } -void ScriptEditorWindow::loadScriptClicked(){ - +void ScriptEditorWindow::setRunningState(bool run) { + if (ui->tabWidget->currentIndex() != -1) { + ((ScriptEditorWidget*)ui->tabWidget->currentWidget())->setRunning(run); + } + this->updateButtons(); } -void ScriptEditorWindow::newScriptClicked(){ - addScriptEditorWidget(QString("new Script")); +void ScriptEditorWindow::updateButtons() { + ui->toggleRunButton->setEnabled(ui->tabWidget->currentIndex() != -1); + ui->toggleRunButton->setIcon(ui->tabWidget->currentIndex() != -1 && ((ScriptEditorWidget*)ui->tabWidget->currentWidget())->isRunning() ? QIcon("../resources/icons/stop-script.svg"):QIcon("../resources/icons/start-script.svg")); } -void ScriptEditorWindow::toggleRunScriptClicked(){ - +void ScriptEditorWindow::loadScriptMenu(const QString& scriptName) { + addScriptEditorWidget("loading...")->loadFile(scriptName); + updateButtons(); } -void ScriptEditorWindow::saveScriptClicked(){ - +void ScriptEditorWindow::loadScriptClicked() { + QString scriptName = QFileDialog::getOpenFileName(this, tr("Interface"), QString(), tr("Javascript (*.js)")); + if (!scriptName.isEmpty()) { + addScriptEditorWidget("loading...")->loadFile(scriptName); + updateButtons(); + } } -void ScriptEditorWindow::addScriptEditorWidget(QString title){ - ScriptEditorWidget* newScriptEditorWidget = new ScriptEditorWidget();//ScriptEditorWidget(); +void ScriptEditorWindow::loadMenuAboutToShow() { + loadMenu->clear(); + QStringList runningScripts = Application::getInstance()->getRunningScripts(); + if (runningScripts.count() > 0) { + QSignalMapper* signalMapper = new QSignalMapper(this); + foreach (const QString& runningScript, runningScripts) { + QAction* runningScriptAction = new QAction(runningScript, loadMenu); + connect(runningScriptAction, SIGNAL(triggered()), signalMapper, SLOT(map())); + signalMapper->setMapping(runningScriptAction, runningScript); + loadMenu->addAction(runningScriptAction); + } + connect(signalMapper, SIGNAL(mapped(const QString &)), this, SLOT(loadScriptMenu(const QString &))); + } else { + QAction* naAction = new QAction("(no running scripts)",loadMenu); + naAction->setDisabled(true); + loadMenu->addAction(naAction); + } +} + +void ScriptEditorWindow::newScriptClicked() { + addScriptEditorWidget(QString("New script")); +} + +void ScriptEditorWindow::toggleRunScriptClicked() { + this->setRunningState(!(ui->tabWidget->currentIndex() !=-1 && ((ScriptEditorWidget*)ui->tabWidget->currentWidget())->isRunning())); +} + +void ScriptEditorWindow::saveScriptClicked() { + if (ui->tabWidget->currentIndex() != -1) { + ScriptEditorWidget* currentScriptWidget = (ScriptEditorWidget*)ui->tabWidget->currentWidget(); + currentScriptWidget->save(); + } +} + +void ScriptEditorWindow::saveScriptAsClicked() { + if (ui->tabWidget->currentIndex() != -1) { + ScriptEditorWidget* currentScriptWidget = (ScriptEditorWidget*)ui->tabWidget->currentWidget(); + currentScriptWidget->saveAs(); + } +} + +ScriptEditorWidget* ScriptEditorWindow::addScriptEditorWidget(QString title) { + ScriptEditorWidget* newScriptEditorWidget = new ScriptEditorWidget(); + connect(newScriptEditorWidget, SIGNAL(scriptnameChanged()), this, SLOT(updateScriptNameOrStatus())); + connect(newScriptEditorWidget, SIGNAL(scriptModified()), this, SLOT(updateScriptNameOrStatus())); + connect(newScriptEditorWidget, SIGNAL(runningStateChanged()), this, SLOT(updateButtons())); ui->tabWidget->addTab(newScriptEditorWidget, title); ui->tabWidget->setCurrentWidget(newScriptEditorWidget); newScriptEditorWidget->setUpdatesEnabled(true); newScriptEditorWidget->adjustSize(); + return newScriptEditorWidget; +} + +void ScriptEditorWindow::tabSwitched(int tabIndex) { + this->updateButtons(); + if (ui->tabWidget->currentIndex() != -1) { + ScriptEditorWidget* currentScriptWidget = (ScriptEditorWidget*)ui->tabWidget->currentWidget(); + QString modifiedStar = (currentScriptWidget->isModified()?"*":""); + if (currentScriptWidget->getScriptName().length() > 0) { + this->setWindowTitle("Script Editor ["+currentScriptWidget->getScriptName()+modifiedStar+"]"); + } else { + this->setWindowTitle("Script Editor [New script"+modifiedStar+"]"); + } + } else { + this->setWindowTitle("Script Editor"); + } +} + +void ScriptEditorWindow::tabCloseRequested(int tabIndex) { + ScriptEditorWidget* closingScriptWidget = (ScriptEditorWidget*)ui->tabWidget->widget(tabIndex); + if(closingScriptWidget->questionSave()) { + ui->tabWidget->removeTab(tabIndex); + } +} + +void ScriptEditorWindow::closeEvent(QCloseEvent *event) { + bool unsaved_docs_warning = false; + for (int i = 0; i < ui->tabWidget->count(); i++ && !unsaved_docs_warning){ + if(((ScriptEditorWidget*)ui->tabWidget->widget(i))->isModified()){ + unsaved_docs_warning = true; + } + } + + if (!unsaved_docs_warning || QMessageBox::warning(this, tr("Interface"), tr("There are some unsaved scripts, are you sure you want to close the editor? Changes will be lost!"), QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel) == QMessageBox::Discard) { + event->accept(); + } else { + event->ignore(); + } +} + +void ScriptEditorWindow::updateScriptNameOrStatus() { + ScriptEditorWidget* source = (ScriptEditorWidget*)QObject::sender(); + QString modifiedStar = (source->isModified()?"*":""); + if (source->getScriptName().length() > 0) { + for (int i = 0; i < ui->tabWidget->count(); i++){ + if (ui->tabWidget->widget(i) == source) { + ui->tabWidget->setTabText(i,modifiedStar+QFileInfo(source->getScriptName()).fileName()); + ui->tabWidget->setTabToolTip(i, source->getScriptName()); + } + } + } + + if (ui->tabWidget->currentWidget() == source) { + if (source->getScriptName().length() > 0) { + this->setWindowTitle("Script Editor ["+source->getScriptName()+modifiedStar+"]"); + } else { + this->setWindowTitle("Script Editor [New script"+modifiedStar+"]"); + } + } } \ No newline at end of file diff --git a/interface/src/ui/ScriptEditorWindow.h b/interface/src/ui/ScriptEditorWindow.h index 718826cf9d..290a9d6051 100644 --- a/interface/src/ui/ScriptEditorWindow.h +++ b/interface/src/ui/ScriptEditorWindow.h @@ -13,6 +13,7 @@ #define hifi_ScriptEditorWindow_h #include +#include "ScriptEditorWidget.h" namespace Ui { class ScriptEditorWindow; @@ -25,15 +26,29 @@ public: ScriptEditorWindow(); ~ScriptEditorWindow(); +protected: + void closeEvent(QCloseEvent *event); + private: Ui::ScriptEditorWindow* ui; - void addScriptEditorWidget(QString title); + QMenu* loadMenu; + QMenu* saveMenu; + ScriptEditorWidget* addScriptEditorWidget(QString title); + void setRunningState(bool run); + void setScriptName(const QString& scriptName); private slots: + void loadScriptMenu(const QString& scriptName); void loadScriptClicked(); void newScriptClicked(); void toggleRunScriptClicked(); void saveScriptClicked(); + void saveScriptAsClicked(); + void loadMenuAboutToShow(); + void tabSwitched(int tabIndex); + void tabCloseRequested(int tabIndex); + void updateScriptNameOrStatus(); + void updateButtons(); }; #endif // hifi_ScriptEditorWindow_h diff --git a/interface/ui/ScriptEditorWidget.ui b/interface/ui/ScriptEditorWidget.ui index 5878f26c69..88761c91c5 100644 --- a/interface/ui/ScriptEditorWidget.ui +++ b/interface/ui/ScriptEditorWidget.ui @@ -6,8 +6,8 @@ 0 0 - 702 - 543 + 691 + 549 @@ -18,7 +18,7 @@ - 400 + 541 238 @@ -91,6 +91,13 @@ + + + + Run on the fly (Careful: Any valid change made to the code will run immediately) + + + diff --git a/interface/ui/ScriptEditorWindow.ui b/interface/ui/ScriptEditorWindow.ui index a612b2b1c9..9e1b08de3e 100644 --- a/interface/ui/ScriptEditorWindow.ui +++ b/interface/ui/ScriptEditorWindow.ui @@ -9,8 +9,8 @@ 0 0 - 474 - 638 + 706 + 682 @@ -20,7 +20,7 @@ - Script editor [] + Script Editor font-family: Helvetica, Arial, sans-serif; @@ -58,7 +58,7 @@ - New Script + New Script (Ctrl+N) New @@ -66,7 +66,7 @@ ../resources/icons/new-script.svg - ../resources/images/pinned.svg../resources/icons/new-script.svg + ../resources/icons/new-script.svg../resources/icons/new-script.svg @@ -91,7 +91,7 @@ - Load Script + Load Script (Ctrl+O) Load @@ -119,11 +119,17 @@ - - - 0 - 2 - + + + 30 + 0 + + + + + 32 + 0 + Qt::NoFocus @@ -132,7 +138,7 @@ Qt::NoContextMenu - Save Script + Save Script (Ctrl+S) Save @@ -150,19 +156,22 @@ 316 + + QToolButton::MenuButtonPopup + - Toggle Run Script + Toggle Run Script (F5) Run/Stop - ../resources/images/plus.svg../resources/images/plus.svg + ../resources/icons/start-script.svg../resources/icons/start-script.svg @@ -286,5 +295,37 @@ + + tabWidget + currentChanged(int) + ScriptEditorWindow + tabSwitched(int) + + + 352 + 360 + + + 352 + 340 + + + + + tabWidget + tabCloseRequested(int) + ScriptEditorWindow + tabCloseRequested(int) + + + 352 + 360 + + + 352 + 340 + + + diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index 684c55fbb0..eeb1cebe09 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -43,6 +43,11 @@ static QScriptValue soundConstructor(QScriptContext* context, QScriptEngine* eng return soundScriptValue; } +static QScriptValue debugPrint(QScriptContext* context, QScriptEngine* engine){ + qDebug() << "script:print()<<" << context->argument(0).toString(); + engine->evaluate("Script.print('"+context->argument(0).toString()+"')"); + return QScriptValue(); +} ScriptEngine::ScriptEngine(const QString& scriptContents, const QString& fileNameString, AbstractControllerScriptingInterface* controllerScriptingInterface) : @@ -115,6 +120,7 @@ ScriptEngine::ScriptEngine(const QUrl& scriptURL, _scriptContents = in.readAll(); } else { qDebug() << "ERROR Loading file:" << fileName; + emit errorMessage("ERROR Loading file:" + fileName); } } else { QNetworkAccessManager* networkManager = new QNetworkAccessManager(this); @@ -200,6 +206,9 @@ void ScriptEngine::init() { qScriptRegisterSequenceMetaType >(&_engine); qScriptRegisterSequenceMetaType >(&_engine); + QScriptValue printConstructorValue = _engine.newFunction(debugPrint); + _engine.globalObject().setProperty("print", printConstructorValue); + QScriptValue soundConstructorValue = _engine.newFunction(soundConstructor); QScriptValue soundMetaObject = _engine.newQMetaObject(&Sound::staticMetaObject, soundConstructorValue); _engine.globalObject().setProperty("Sound", soundMetaObject); @@ -246,6 +255,7 @@ void ScriptEngine::evaluate() { if (_engine.hasUncaughtException()) { int line = _engine.uncaughtExceptionLineNumber(); qDebug() << "Uncaught exception at line" << line << ":" << result.toString(); + emit errorMessage("Uncaught exception at line" + QString::number(line) + ":" + result.toString()); } } @@ -266,11 +276,14 @@ void ScriptEngine::run() { init(); } _isRunning = true; + emit runningStateChanged(); QScriptValue result = _engine.evaluate(_scriptContents); if (_engine.hasUncaughtException()) { int line = _engine.uncaughtExceptionLineNumber(); + qDebug() << "Uncaught exception at line" << line << ":" << result.toString(); + emit errorMessage("Uncaught exception at line" + QString::number(line) + ":" + result.toString()); } timeval startTime; @@ -401,6 +414,7 @@ void ScriptEngine::run() { if (_engine.hasUncaughtException()) { int line = _engine.uncaughtExceptionLineNumber(); qDebug() << "Uncaught exception at line" << line << ":" << _engine.uncaughtException().toString(); + emit errorMessage("Uncaught exception at line" + QString::number(line) + ":" + _engine.uncaughtException().toString()); } } emit scriptEnding(); @@ -436,10 +450,12 @@ void ScriptEngine::run() { emit finished(_fileNameString); _isRunning = false; + emit runningStateChanged(); } void ScriptEngine::stop() { _isFinished = true; + emit runningStateChanged(); } void ScriptEngine::timerFired() { @@ -510,6 +526,10 @@ QUrl ScriptEngine::resolveInclude(const QString& include) const { return url; } +void ScriptEngine::print(const QString& message) { + emit printedMessage(message); +} + void ScriptEngine::include(const QString& includeFile) { QUrl url = resolveInclude(includeFile); QString includeContents; @@ -523,6 +543,7 @@ void ScriptEngine::include(const QString& includeFile) { includeContents = in.readAll(); } else { qDebug() << "ERROR Loading file:" << fileName; + emit errorMessage("ERROR Loading file:" + fileName); } } else { QNetworkAccessManager* networkManager = new QNetworkAccessManager(this); @@ -538,5 +559,6 @@ void ScriptEngine::include(const QString& includeFile) { if (_engine.hasUncaughtException()) { int line = _engine.uncaughtExceptionLineNumber(); qDebug() << "Uncaught exception at (" << includeFile << ") line" << line << ":" << result.toString(); + emit errorMessage("Uncaught exception at (" + includeFile + ") line" + QString::number(line) + ":" + result.toString()); } -} +} \ No newline at end of file diff --git a/libraries/script-engine/src/ScriptEngine.h b/libraries/script-engine/src/ScriptEngine.h index 941c6bbe27..9ea99276d3 100644 --- a/libraries/script-engine/src/ScriptEngine.h +++ b/libraries/script-engine/src/ScriptEngine.h @@ -80,6 +80,9 @@ public: bool hasScript() const { return !_scriptContents.isEmpty(); } + bool isFinished() const { return _isFinished; } + bool isRunning() const { return _isRunning; } + public slots: void stop(); @@ -88,12 +91,16 @@ public slots: void clearInterval(QObject* timer) { stopTimer(reinterpret_cast(timer)); } void clearTimeout(QObject* timer) { stopTimer(reinterpret_cast(timer)); } void include(const QString& includeFile); + void print(const QString& message); signals: void update(float deltaTime); void scriptEnding(); void finished(const QString& fileNameString); void cleanupMenuItem(const QString& menuItemString); + void printedMessage(const QString& message); + void errorMessage(const QString& message); + void runningStateChanged(); protected: QString _scriptContents; From 5bffb17643f013e267deeeea6efe615449386232 Mon Sep 17 00:00:00 2001 From: Thijs Wenker Date: Mon, 21 Apr 2014 05:51:34 +0200 Subject: [PATCH 527/595] #include -> #include --- interface/src/ui/ScriptEditorWindow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/ui/ScriptEditorWindow.cpp b/interface/src/ui/ScriptEditorWindow.cpp index 687b992c5f..0774ed02f0 100644 --- a/interface/src/ui/ScriptEditorWindow.cpp +++ b/interface/src/ui/ScriptEditorWindow.cpp @@ -13,7 +13,7 @@ #include #include #include -#include +#include #include #include #include From 77994ae0cbaecdb0175051de3ae04d4db80ca123 Mon Sep 17 00:00:00 2001 From: Thijs Wenker Date: Mon, 21 Apr 2014 06:20:18 +0200 Subject: [PATCH 528/595] header cleanup (hopefully the ubuntu test-build will like this) --- interface/src/ui/ScriptEditorWidget.cpp | 6 +++--- interface/src/ui/ScriptEditorWidget.h | 4 ++-- interface/src/ui/ScriptEditorWindow.cpp | 8 ++++---- interface/src/ui/ScriptEditorWindow.h | 1 - 4 files changed, 9 insertions(+), 10 deletions(-) diff --git a/interface/src/ui/ScriptEditorWidget.cpp b/interface/src/ui/ScriptEditorWidget.cpp index 98b6f2fe96..91e3efe1df 100644 --- a/interface/src/ui/ScriptEditorWidget.cpp +++ b/interface/src/ui/ScriptEditorWidget.cpp @@ -9,6 +9,9 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include "ui_scriptEditorWidget.h" +#include "ScriptEditorWidget.h" + #include #include #include @@ -22,9 +25,6 @@ #include "Application.h" #include "ScriptHighlighting.h" -#include "ui_scriptEditorWidget.h" - -#include "ScriptEditorWidget.h" ScriptEditorWidget::ScriptEditorWidget() : ui(new Ui::ScriptEditorWidget) diff --git a/interface/src/ui/ScriptEditorWidget.h b/interface/src/ui/ScriptEditorWidget.h index 674304acb6..5fed373658 100644 --- a/interface/src/ui/ScriptEditorWidget.h +++ b/interface/src/ui/ScriptEditorWidget.h @@ -13,8 +13,8 @@ #define hifi_ScriptEditorWidget_h #include - -#include +#include "ScriptEditorWidget.h" +#include "ScriptEngine.h" namespace Ui { class ScriptEditorWidget; diff --git a/interface/src/ui/ScriptEditorWindow.cpp b/interface/src/ui/ScriptEditorWindow.cpp index 0774ed02f0..69283feccf 100644 --- a/interface/src/ui/ScriptEditorWindow.cpp +++ b/interface/src/ui/ScriptEditorWindow.cpp @@ -9,6 +9,10 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include "ui_scriptEditorWindow.h" +#include "ScriptEditorWindow.h" +#include "ScriptEditorWidget.h" + #include #include #include @@ -23,10 +27,6 @@ #include "Application.h" #include "FlowLayout.h" -#include "ui_scriptEditorWindow.h" -#include "ScriptEditorWidget.h" - -#include "ScriptEditorWindow.h" ScriptEditorWindow::ScriptEditorWindow() : ui(new Ui::ScriptEditorWindow) diff --git a/interface/src/ui/ScriptEditorWindow.h b/interface/src/ui/ScriptEditorWindow.h index 290a9d6051..a1b72423ec 100644 --- a/interface/src/ui/ScriptEditorWindow.h +++ b/interface/src/ui/ScriptEditorWindow.h @@ -12,7 +12,6 @@ #ifndef hifi_ScriptEditorWindow_h #define hifi_ScriptEditorWindow_h -#include #include "ScriptEditorWidget.h" namespace Ui { From 0e28ff2fcda7ee5e1bd13decb5cb6b20eed2506c Mon Sep 17 00:00:00 2001 From: "U-Uthoypia\\Thijs" Date: Mon, 21 Apr 2014 06:33:20 +0200 Subject: [PATCH 529/595] This should fix the ubuntu build --- interface/ui/{ScriptEditorWidget.ui => scriptEditorWidget.ui} | 0 interface/ui/{ScriptEditorWindow.ui => scriptEditorWindow.ui} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename interface/ui/{ScriptEditorWidget.ui => scriptEditorWidget.ui} (100%) rename interface/ui/{ScriptEditorWindow.ui => scriptEditorWindow.ui} (100%) diff --git a/interface/ui/ScriptEditorWidget.ui b/interface/ui/scriptEditorWidget.ui similarity index 100% rename from interface/ui/ScriptEditorWidget.ui rename to interface/ui/scriptEditorWidget.ui diff --git a/interface/ui/ScriptEditorWindow.ui b/interface/ui/scriptEditorWindow.ui similarity index 100% rename from interface/ui/ScriptEditorWindow.ui rename to interface/ui/scriptEditorWindow.ui From 36b58b178c33abc9633c9ad5c066f7e044787099 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 21 Apr 2014 01:00:56 -0700 Subject: [PATCH 530/595] have scripted assignments added via config be static --- domain-server/src/DomainServer.cpp | 48 +++++++++++++++++++----------- 1 file changed, 30 insertions(+), 18 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index f32eb99733..da51009e6a 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -278,7 +278,8 @@ void DomainServer::createScriptedAssignmentsFromArray(const QJsonArray &configAr qDebug() << "Adding scripted assignment to queue -" << *scriptAssignment; qDebug() << "URL for script is" << assignmentURL; - _assignmentQueue.enqueue(SharedAssignmentPointer(scriptAssignment)); + // scripts passed on CL or via JSON are static - so they are added back to the queue if the node dies + addStaticAssignmentToAssignmentHash(scriptAssignment); } } } @@ -740,6 +741,16 @@ QJsonObject DomainServer::jsonObjectForNode(const SharedNodePointer& node) { return nodeJson; } +const char ASSIGNMENT_SCRIPT_HOST_LOCATION[] = "resources/web/assignment"; + +QString pathForAssignmentScript(const QUuid& assignmentUUID) { + QString newPath(ASSIGNMENT_SCRIPT_HOST_LOCATION); + newPath += "/"; + // append the UUID for this script as the new filename, remove the curly braces + newPath += uuidStringWithoutCurlyBraces(assignmentUUID); + return newPath; +} + bool DomainServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url) { const QString JSON_MIME_TYPE = "application/json"; @@ -870,17 +881,13 @@ bool DomainServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url assignmentPool = QString(assignmentPoolValue); } - const char ASSIGNMENT_SCRIPT_HOST_LOCATION[] = "resources/web/assignment"; for (int i = 0; i < numInstances; i++) { // create an assignment for this saved script Assignment* scriptAssignment = new Assignment(Assignment::CreateCommand, Assignment::AgentType, assignmentPool); - QString newPath(ASSIGNMENT_SCRIPT_HOST_LOCATION); - newPath += "/"; - // append the UUID for this script as the new filename, remove the curly braces - newPath += uuidStringWithoutCurlyBraces(scriptAssignment->getUUID()); + QString newPath = pathForAssignmentScript(scriptAssignment->getUUID()); // create a file with the GUID of the assignment in the script host location QFile scriptFile(newPath); @@ -945,6 +952,12 @@ void DomainServer::refreshStaticAssignmentAndAddToQueue(SharedAssignmentPointer& qDebug() << "Reset UUID for assignment -" << *assignment.data() << "- and added to queue. Old UUID was" << uuidStringWithoutCurlyBraces(oldUUID); + if (assignment->getType() == Assignment::AgentType && assignment->getPayload().isEmpty()) { +\ + // if this was an Agent without a script URL, we need to rename the old file so it can be retrieved at the new UUID + QFile::rename(pathForAssignmentScript(oldUUID), pathForAssignmentScript(assignment->getUUID())); + } + // add the static assignment back under the right UUID, and to the queue _staticAssignmentHash.insert(assignment->getUUID(), assignment); @@ -1019,22 +1032,21 @@ SharedAssignmentPointer DomainServer::deployableAssignmentForRequest(const Assig bool assignmentPoolsMatch = assignment->getPool() == requestAssignment.getPool(); if ((requestIsAllTypes || assignmentTypesMatch) && (nietherHasPool || assignmentPoolsMatch)) { - - if (assignment->getType() == Assignment::AgentType) { - // if there is more than one instance to send out, simply decrease the number of instances - return _assignmentQueue.takeAt(sharedAssignment - _assignmentQueue.begin()); - } else { - // remove the assignment from the queue - SharedAssignmentPointer deployableAssignment = _assignmentQueue.takeAt(sharedAssignment - - _assignmentQueue.begin()); - + + // remove the assignment from the queue + SharedAssignmentPointer deployableAssignment = _assignmentQueue.takeAt(sharedAssignment + - _assignmentQueue.begin()); + + if (deployableAssignment->getType() != Assignment::AgentType + || _staticAssignmentHash.contains(deployableAssignment->getUUID())) { + // this is a static assignment // until we get a check-in from that GUID // put assignment back in queue but stick it at the back so the others have a chance to go out _assignmentQueue.enqueue(deployableAssignment); - - // stop looping, we've handed out an assignment - return deployableAssignment; } + + // stop looping, we've handed out an assignment + return deployableAssignment; } else { // push forward the iterator to check the next assignment ++sharedAssignment; From c64ae353746a1a5a25e575b534632a9a5dd2f25a Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 21 Apr 2014 01:01:38 -0700 Subject: [PATCH 531/595] remove an extra bracket --- domain-server/src/DomainServer.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index da51009e6a..d882bea1c8 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -953,7 +953,6 @@ void DomainServer::refreshStaticAssignmentAndAddToQueue(SharedAssignmentPointer& << uuidStringWithoutCurlyBraces(oldUUID); if (assignment->getType() == Assignment::AgentType && assignment->getPayload().isEmpty()) { -\ // if this was an Agent without a script URL, we need to rename the old file so it can be retrieved at the new UUID QFile::rename(pathForAssignmentScript(oldUUID), pathForAssignmentScript(assignment->getUUID())); } From c9b04443105f29af8343a1864cf327db19816db3 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 21 Apr 2014 08:47:14 -0700 Subject: [PATCH 532/595] correct re-assignment of static assignments --- domain-server/src/DomainServer.cpp | 51 ++++++++++++++++-------------- 1 file changed, 28 insertions(+), 23 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index d882bea1c8..003a53027e 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -344,7 +344,6 @@ const NodeSet STATICALLY_ASSIGNED_NODES = NodeSet() << NodeType::AudioMixer << NodeType::AvatarMixer << NodeType::VoxelServer << NodeType::ParticleServer << NodeType::MetavoxelServer; - void DomainServer::addNodeToNodeListAndConfirmConnection(const QByteArray& packet, const HifiSockAddr& senderSockAddr) { NodeType_t nodeType; @@ -353,34 +352,40 @@ void DomainServer::addNodeToNodeListAndConfirmConnection(const QByteArray& packe int numPreInterestBytes = parseNodeDataFromByteArray(nodeType, publicSockAddr, localSockAddr, packet, senderSockAddr); QUuid assignmentUUID = uuidFromPacketHeader(packet); - SharedAssignmentPointer matchingAssignment; + bool isStaticAssignment = _staticAssignmentHash.contains(assignmentUUID); + SharedAssignmentPointer matchingAssignment = SharedAssignmentPointer(); - if (!assignmentUUID.isNull() && (matchingAssignment = matchingStaticAssignmentForCheckIn(assignmentUUID, nodeType)) - && matchingAssignment) { - // this is an assigned node, make sure the UUID sent is for an assignment we're actually trying to give out + if (isStaticAssignment) { + // this is a static assignment, make sure the UUID sent is for an assignment we're actually trying to give out + matchingAssignment = matchingStaticAssignmentForCheckIn(assignmentUUID, nodeType); - // remove the matching assignment from the assignment queue so we don't take the next check in - // (if it exists) - removeMatchingAssignmentFromQueue(matchingAssignment); + if (matchingAssignment) { + // remove the matching assignment from the assignment queue so we don't take the next check in + // (if it exists) + removeMatchingAssignmentFromQueue(matchingAssignment); + } } else { assignmentUUID = QUuid(); } - // create a new session UUID for this node - QUuid nodeUUID = QUuid::createUuid(); - - SharedNodePointer newNode = LimitedNodeList::getInstance()->addOrUpdateNode(nodeUUID, nodeType, - publicSockAddr, localSockAddr); - - // when the newNode is created the linked data is also created - // if this was a static assignment set the UUID, set the sendingSockAddr - DomainServerNodeData* nodeData = reinterpret_cast(newNode->getLinkedData()); - - nodeData->setStaticAssignmentUUID(assignmentUUID); - nodeData->setSendingSockAddr(senderSockAddr); - - // reply back to the user with a PacketTypeDomainList - sendDomainListToNode(newNode, senderSockAddr, nodeInterestListFromPacket(packet, numPreInterestBytes)); + // make sure this was either not a static assignment or it was and we had a matching one in teh queue + if ((!isStaticAssignment && !STATICALLY_ASSIGNED_NODES.contains(nodeType)) || (isStaticAssignment && matchingAssignment)) { + // create a new session UUID for this node + QUuid nodeUUID = QUuid::createUuid(); + + SharedNodePointer newNode = LimitedNodeList::getInstance()->addOrUpdateNode(nodeUUID, nodeType, + publicSockAddr, localSockAddr); + + // when the newNode is created the linked data is also created + // if this was a static assignment set the UUID, set the sendingSockAddr + DomainServerNodeData* nodeData = reinterpret_cast(newNode->getLinkedData()); + + nodeData->setStaticAssignmentUUID(assignmentUUID); + nodeData->setSendingSockAddr(senderSockAddr); + + // reply back to the user with a PacketTypeDomainList + sendDomainListToNode(newNode, senderSockAddr, nodeInterestListFromPacket(packet, numPreInterestBytes)); + } } int DomainServer::parseNodeDataFromByteArray(NodeType_t& nodeType, HifiSockAddr& publicSockAddr, From 419e0928585dee5fe77bfbd5730527982cf7bd4d Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 21 Apr 2014 08:48:29 -0700 Subject: [PATCH 533/595] rename matching static method in DS --- domain-server/src/DomainServer.cpp | 4 ++-- domain-server/src/DomainServer.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 003a53027e..856078b8a9 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -357,7 +357,7 @@ void DomainServer::addNodeToNodeListAndConfirmConnection(const QByteArray& packe if (isStaticAssignment) { // this is a static assignment, make sure the UUID sent is for an assignment we're actually trying to give out - matchingAssignment = matchingStaticAssignmentForCheckIn(assignmentUUID, nodeType); + matchingAssignment = matchingQueuedAssignmentForCheckIn(assignmentUUID, nodeType); if (matchingAssignment) { // remove the matching assignment from the assignment queue so we don't take the next check in @@ -1009,7 +1009,7 @@ void DomainServer::nodeKilled(SharedNodePointer node) { } } -SharedAssignmentPointer DomainServer::matchingStaticAssignmentForCheckIn(const QUuid& checkInUUID, NodeType_t nodeType) { +SharedAssignmentPointer DomainServer::matchingQueuedAssignmentForCheckIn(const QUuid& checkInUUID, NodeType_t nodeType) { QQueue::iterator i = _assignmentQueue.begin(); while (i != _assignmentQueue.end()) { diff --git a/domain-server/src/DomainServer.h b/domain-server/src/DomainServer.h index 9bd10b8c60..1bc9b71064 100644 --- a/domain-server/src/DomainServer.h +++ b/domain-server/src/DomainServer.h @@ -70,7 +70,7 @@ private: void createStaticAssignmentsForType(Assignment::Type type, const QJsonArray& configArray); void populateDefaultStaticAssignmentsExcludingTypes(const QSet& excludedTypes); - SharedAssignmentPointer matchingStaticAssignmentForCheckIn(const QUuid& checkInUUID, NodeType_t nodeType); + SharedAssignmentPointer matchingQueuedAssignmentForCheckIn(const QUuid& checkInUUID, NodeType_t nodeType); SharedAssignmentPointer deployableAssignmentForRequest(const Assignment& requestAssignment); void removeMatchingAssignmentFromQueue(const SharedAssignmentPointer& removableAssignment); void refreshStaticAssignmentAndAddToQueue(SharedAssignmentPointer& assignment); From cc7d9863989b797c1b860b24d5d0d954184d6196 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 21 Apr 2014 09:29:08 -0700 Subject: [PATCH 534/595] don't make scripts statically assigned --- domain-server/src/DomainServer.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 856078b8a9..f42eb6c005 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -279,7 +279,7 @@ void DomainServer::createScriptedAssignmentsFromArray(const QJsonArray &configAr qDebug() << "URL for script is" << assignmentURL; // scripts passed on CL or via JSON are static - so they are added back to the queue if the node dies - addStaticAssignmentToAssignmentHash(scriptAssignment); + _assignmentQueue.enqueue(SharedAssignmentPointer(scriptAssignment)); } } } @@ -991,6 +991,8 @@ void DomainServer::nodeKilled(SharedNodePointer node) { } } + if (node->getType() == NodeType::Agent && n + // cleanup the connection secrets that we set up for this node (on the other nodes) foreach (const QUuid& otherNodeSessionUUID, nodeData->getSessionSecretHash().keys()) { SharedNodePointer otherNode = LimitedNodeList::getInstance()->nodeWithUUID(otherNodeSessionUUID); From 07387a132e80a37938f3dc8c07f4967d88aa40cf Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 21 Apr 2014 09:31:21 -0700 Subject: [PATCH 535/595] fix broken DS build --- domain-server/src/DomainServer.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index f42eb6c005..eb62dacf79 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -991,8 +991,6 @@ void DomainServer::nodeKilled(SharedNodePointer node) { } } - if (node->getType() == NodeType::Agent && n - // cleanup the connection secrets that we set up for this node (on the other nodes) foreach (const QUuid& otherNodeSessionUUID, nodeData->getSessionSecretHash().keys()) { SharedNodePointer otherNode = LimitedNodeList::getInstance()->nodeWithUUID(otherNodeSessionUUID); From 241df7a7675c83ab7fbbabaf6c9903ac398d667d Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Mon, 21 Apr 2014 10:27:20 -0700 Subject: [PATCH 536/595] Move AABox from octree lib to shared lib Stubbed out Shape vs Octree collisions --- libraries/octree/src/Octree.cpp | 58 ++++++++++++++++++++-- libraries/octree/src/Octree.h | 5 ++ libraries/octree/src/OctreeElement.cpp | 2 +- libraries/octree/src/OctreeElement.h | 3 +- libraries/octree/src/ViewFrustum.h | 2 +- libraries/{octree => shared}/src/AABox.cpp | 2 +- libraries/{octree => shared}/src/AABox.h | 2 +- libraries/shared/src/ShapeCollider.cpp | 5 ++ libraries/shared/src/ShapeCollider.h | 7 +++ libraries/voxels/src/VoxelTreeElement.h | 2 +- 10 files changed, 79 insertions(+), 9 deletions(-) rename libraries/{octree => shared}/src/AABox.cpp (99%) rename libraries/{octree => shared}/src/AABox.h (98%) diff --git a/libraries/octree/src/Octree.cpp b/libraries/octree/src/Octree.cpp index 696a65b4b5..a06b8a41bb 100644 --- a/libraries/octree/src/Octree.cpp +++ b/libraries/octree/src/Octree.cpp @@ -20,18 +20,20 @@ #include -#include "CoverageMap.h" #include -#include "OctalCode.h" +#include #include #include +#include +#include //#include "Tags.h" -#include "ViewFrustum.h" +#include "CoverageMap.h" #include "OctreeConstants.h" #include "OctreeElementBag.h" #include "Octree.h" +#include "ViewFrustum.h" float boundaryDistanceForRenderLevel(unsigned int renderLevel, float voxelSizeScale) { return voxelSizeScale / powf(2, renderLevel); @@ -676,6 +678,13 @@ public: bool found; }; +class ShapeArgs { +public: + const Shape* shape; + CollisionList& collisions; + bool found; +}; + bool findCapsulePenetrationOp(OctreeElement* node, void* extraData) { CapsuleArgs* args = static_cast(extraData); @@ -697,6 +706,24 @@ bool findCapsulePenetrationOp(OctreeElement* node, void* extraData) { return false; } +bool findShapeCollisionsOp(OctreeElement* node, void* extraData) { + const ShapeArgs* args = static_cast(extraData); + + // coarse check against bounds + AABox box = node->getAABox(); + box.scale(TREE_SCALE); + if (!box.expandedContains(args->shape->getPosition(), args->shape->getBoundingRadius())) { + return false; + } + if (!node->isLeaf()) { + return true; // recurse on children + } + if (node->hasContent()) { + return ShapeCollider::collideShapeWithBox(args->shape, box, args->collisions); + } + return false; +} + bool Octree::findCapsulePenetration(const glm::vec3& start, const glm::vec3& end, float radius, glm::vec3& penetration, Octree::lockType lockType) { @@ -727,6 +754,31 @@ bool Octree::findCapsulePenetration(const glm::vec3& start, const glm::vec3& end return args.found; } +bool Octree::findShapeCollisions(const Shape* shape, CollisionList& collisions, Octree::lockType lockType) { + + ShapeArgs args = { shape, + collisions, + false }; + + bool gotLock = false; + if (lockType == Octree::Lock) { + lockForRead(); + gotLock = true; + } else if (lockType == Octree::TryLock) { + gotLock = tryLockForRead(); + if (!gotLock) { + return args.found; // if we wanted to tryLock, and we couldn't then just bail... + } + } + + recurseTreeWithOperation(findShapeCollisionsOp, &args); + + if (gotLock) { + unlock(); + } + return args.found; +} + class GetElementEnclosingArgs { public: OctreeElement* element; diff --git a/libraries/octree/src/Octree.h b/libraries/octree/src/Octree.h index 839e61d1c2..4c47c0ce9f 100644 --- a/libraries/octree/src/Octree.h +++ b/libraries/octree/src/Octree.h @@ -21,6 +21,7 @@ class Octree; class OctreeElement; class OctreeElementBag; class OctreePacketData; +class Shape; #include "JurisdictionMap.h" @@ -30,6 +31,8 @@ class OctreePacketData; #include "OctreePacketData.h" #include "OctreeSceneStats.h" +#include + #include #include @@ -246,6 +249,8 @@ public: bool findCapsulePenetration(const glm::vec3& start, const glm::vec3& end, float radius, glm::vec3& penetration, Octree::lockType lockType = Octree::TryLock); + bool findShapeCollisions(const Shape* shape, CollisionList& collisions, Octree::lockType = Octree::TryLock); + OctreeElement* getElementEnclosingPoint(const glm::vec3& point, Octree::lockType lockType = Octree::TryLock); // Note: this assumes the fileFormat is the HIO individual voxels code files diff --git a/libraries/octree/src/OctreeElement.cpp b/libraries/octree/src/OctreeElement.cpp index e21148df5e..c951803247 100644 --- a/libraries/octree/src/OctreeElement.cpp +++ b/libraries/octree/src/OctreeElement.cpp @@ -15,11 +15,11 @@ #include +#include #include #include #include -#include "AABox.h" #include "OctalCode.h" #include "SharedUtil.h" #include "OctreeConstants.h" diff --git a/libraries/octree/src/OctreeElement.h b/libraries/octree/src/OctreeElement.h index 682516cf0a..15d5063818 100644 --- a/libraries/octree/src/OctreeElement.h +++ b/libraries/octree/src/OctreeElement.h @@ -18,8 +18,9 @@ #include +#include #include -#include "AABox.h" + #include "ViewFrustum.h" #include "OctreeConstants.h" //#include "Octree.h" diff --git a/libraries/octree/src/ViewFrustum.h b/libraries/octree/src/ViewFrustum.h index 5c9d7f06c2..43812827f5 100644 --- a/libraries/octree/src/ViewFrustum.h +++ b/libraries/octree/src/ViewFrustum.h @@ -17,7 +17,7 @@ #include #include -#include "AABox.h" +#include #include "Plane.h" #include "OctreeConstants.h" diff --git a/libraries/octree/src/AABox.cpp b/libraries/shared/src/AABox.cpp similarity index 99% rename from libraries/octree/src/AABox.cpp rename to libraries/shared/src/AABox.cpp index 51b31d4466..ed99a24d38 100644 --- a/libraries/octree/src/AABox.cpp +++ b/libraries/shared/src/AABox.cpp @@ -1,6 +1,6 @@ // // AABox.cpp -// libraries/octree/src +// libraries/shared/src // // Created by Brad Hefta-Gaub on 04/11/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/octree/src/AABox.h b/libraries/shared/src/AABox.h similarity index 98% rename from libraries/octree/src/AABox.h rename to libraries/shared/src/AABox.h index 1aa0849b70..6531db4250 100644 --- a/libraries/octree/src/AABox.h +++ b/libraries/shared/src/AABox.h @@ -1,6 +1,6 @@ // // AABox.h -// libraries/octree/src +// libraries/shared/src // // Created by Brad Hefta-Gaub on 04/11/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/shared/src/ShapeCollider.cpp b/libraries/shared/src/ShapeCollider.cpp index c53c7fab7d..0eddc80c62 100644 --- a/libraries/shared/src/ShapeCollider.cpp +++ b/libraries/shared/src/ShapeCollider.cpp @@ -92,6 +92,11 @@ bool collideShapesCoarse(const QVector& shapesA, const QVectorgetPosition() - sphereA->getPosition(); float distanceSquared = glm::dot(BA, BA); diff --git a/libraries/shared/src/ShapeCollider.h b/libraries/shared/src/ShapeCollider.h index d554775e7b..a020050662 100644 --- a/libraries/shared/src/ShapeCollider.h +++ b/libraries/shared/src/ShapeCollider.h @@ -12,6 +12,7 @@ #ifndef hifi_ShapeCollider_h #define hifi_ShapeCollider_h +#include "AABox.h" #include "CapsuleShape.h" #include "CollisionInfo.h" #include "ListShape.h" @@ -33,6 +34,12 @@ namespace ShapeCollider { /// \return true if any shapes collide bool collideShapesCoarse(const QVector& shapesA, const QVector& shapesB, CollisionInfo& collision); + /// \param shapeA a pointer to a shape + /// \param boxB an axis aligned box + /// \param collisions[out] average collision details + /// \return true if shapeA collides with boxB + bool collideShapeWithBox(const Shape* shapeA, const AABox& boxB, CollisionList& collisions); + /// \param sphereA pointer to first shape /// \param sphereB pointer to second shape /// \param[out] collisions where to append collision details diff --git a/libraries/voxels/src/VoxelTreeElement.h b/libraries/voxels/src/VoxelTreeElement.h index 140744afb0..8733987df4 100644 --- a/libraries/voxels/src/VoxelTreeElement.h +++ b/libraries/voxels/src/VoxelTreeElement.h @@ -18,10 +18,10 @@ #include +#include #include #include -#include "AABox.h" #include "ViewFrustum.h" #include "VoxelConstants.h" From ffc73e04ebdcbf2638ff56900ffacac1ee4a3e80 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 21 Apr 2014 11:48:42 -0700 Subject: [PATCH 537/595] added new load testing example script --- examples/testingVoxelViewerRestart.js | 93 +++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 examples/testingVoxelViewerRestart.js diff --git a/examples/testingVoxelViewerRestart.js b/examples/testingVoxelViewerRestart.js new file mode 100644 index 0000000000..309f970cd8 --- /dev/null +++ b/examples/testingVoxelViewerRestart.js @@ -0,0 +1,93 @@ +// +// seeingVoxelsExample.js +// hifi +// +// Created by Brad Hefta-Gaub on 2/26/14 +// Copyright (c) 2014 HighFidelity, Inc. All rights reserved. +// +// This is an example script +// + +var count = 0; +var yawDirection = -1; +var yaw = 45; +var yawMax = 70; +var yawMin = 20; +var vantagePoint = {x: 5000, y: 500, z: 5000}; + +var isLocal = false; + +// set up our VoxelViewer with a position and orientation +var orientation = Quat.fromPitchYawRollDegrees(0, yaw, 0); + +function getRandomInt(min, max) { + return Math.floor(Math.random() * (max - min + 1)) + min; +} + +function init() { + if (isLocal) { + MyAvatar.position = vantagePoint; + MyAvatar.orientation = orientation; + } else { + VoxelViewer.setPosition(vantagePoint); + VoxelViewer.setOrientation(orientation); + VoxelViewer.queryOctree(); + Agent.isAvatar = true; + } +} + +function keepLooking(deltaTime) { + //print("count =" + count); + + if (count == 0) { + init(); + } + count++; + if (count % getRandomInt(5, 15) == 0) { + yaw += yawDirection; + orientation = Quat.fromPitchYawRollDegrees(0, yaw, 0); + if (yaw > yawMax || yaw < yawMin) { + yawDirection = yawDirection * -1; + } + + //if (count % 10000 == 0) { + // print("calling VoxelViewer.queryOctree()... count=" + count + " yaw=" + yaw); + //} + + if (isLocal) { + MyAvatar.orientation = orientation; + } else { + VoxelViewer.setOrientation(orientation); + VoxelViewer.queryOctree(); + + //if (count % 10000 == 0) { + // print("VoxelViewer.getOctreeElementsCount()=" + VoxelViewer.getOctreeElementsCount()); + //} + } + } + + // approximately every second, consider stopping + if (count % 60 == 0) { + print("considering stop.... elementCount:" + VoxelViewer.getOctreeElementsCount()); + var stopProbability = 0.05; // 5% chance of stopping + if (Math.random() < stopProbability) { + print("stopping.... elementCount:" + VoxelViewer.getOctreeElementsCount()); + Script.stop(); + } + } +} + +function scriptEnding() { + print("SCRIPT ENDNG!!!\n"); +} + +// register the call back so it fires before each data send +Script.update.connect(keepLooking); + +// register our scriptEnding callback +Script.scriptEnding.connect(scriptEnding); + + +// test for local... +Menu.isOptionChecked("Voxels"); +isLocal = true; // will only get here on local client From 7798c6eb09f41e5a19482e10a8b0e14c8cf04bcd Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 21 Apr 2014 11:48:58 -0700 Subject: [PATCH 538/595] some debugging --- assignment-client/src/octree/OctreeServer.cpp | 38 +++++++++++-------- .../networking/src/ThreadedAssignment.cpp | 8 ++-- 2 files changed, 27 insertions(+), 19 deletions(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 24d179b707..a73701d695 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -843,12 +843,14 @@ quint64 lastReadPendingDatagrams = usecTimestampNow(); quint64 lastProcessNodeData = usecTimestampNow(); void OctreeServer::readPendingDatagrams() { - qDebug() << "OctreeServer::readPendingDatagrams()... thread()->eventDispatcher()=" << thread()->eventDispatcher(); + //qDebug() << "OctreeServer::readPendingDatagrams()... thread()->eventDispatcher()=" << thread()->eventDispatcher(); quint64 now = usecTimestampNow(); - if ((now - lastReadPendingDatagrams) > 100000) { - //qDebug() << "OctreeServer::readPendingDatagrams(): since lastReadPendingDatagrams=" << (now - lastReadPendingDatagrams) << "usecs"; + + // more than 1.1 second is probably a problem + if ((now - lastReadPendingDatagrams) > 1100000) { + qDebug() << "OctreeServer::readPendingDatagrams(): since lastReadPendingDatagrams=" << (now - lastReadPendingDatagrams) << "usecs"; } lastReadPendingDatagrams = now; @@ -890,13 +892,11 @@ void OctreeServer::readPendingDatagrams() { matchingElapsed += (endNodeLookup - startNodeLookup); if ((endNodeLookup - startNodeLookup) > 100000) { - //qDebug() << "OctreeServer::readPendingDatagrams(): sendingNodeForPacket() took" << (endNodeLookup - startNodeLookup) << "usecs"; + qDebug() << "OctreeServer::readPendingDatagrams(): sendingNodeForPacket() took" << (endNodeLookup - startNodeLookup) << "usecs"; } if (packetType == getMyQueryMessageType()) { -qDebug() << "got a query..."; - quint64 queryStart = usecTimestampNow(); queryPackets++; @@ -907,7 +907,7 @@ qDebug() << "got a query..."; nodeList->updateNodeWithDataFromPacket(matchingNode, receivedPacket); quint64 endUpdateNode = usecTimestampNow(); if ((endUpdateNode - startUpdateNode) > 100000) { - //qDebug() << "OctreeServer::readPendingDatagrams(): updateNodeWithDataFromPacket() took" << (endUpdateNode - startUpdateNode) << "usecs"; + qDebug() << "OctreeServer::readPendingDatagrams(): updateNodeWithDataFromPacket() took" << (endUpdateNode - startUpdateNode) << "usecs"; } OctreeQueryNode* nodeData = (OctreeQueryNode*) matchingNode->getLinkedData(); @@ -935,8 +935,10 @@ qDebug() << "got a query..."; nodeListPackets++; quint64 now = usecTimestampNow(); - if ((now - lastProcessNodeData) > 500000) { - //qDebug() << "OctreeServer::readPendingDatagrams(): since lastProcessNodeData=" << (now - lastProcessNodeData) << "usecs"; + + // more than 1.1 second is probably a problem + if ((now - lastProcessNodeData) > 1100000) { + qDebug() << "OctreeServer::readPendingDatagrams(): since lastProcessNodeData=" << (now - lastProcessNodeData) << "usecs"; } lastProcessNodeData = now; @@ -945,7 +947,7 @@ qDebug() << "got a query..."; NodeList::getInstance()->processNodeData(senderSockAddr, receivedPacket); quint64 endProcessNodeData = usecTimestampNow(); if ((endProcessNodeData - startProcessNodeData) > 100000) { - //qDebug() << "OctreeServer::readPendingDatagrams(): processNodeData() took" << (endProcessNodeData - startProcessNodeData) << "usecs"; + qDebug() << "OctreeServer::readPendingDatagrams(): processNodeData() took" << (endProcessNodeData - startProcessNodeData) << "usecs"; } quint64 nodeListEnd = usecTimestampNow(); @@ -974,11 +976,17 @@ qDebug() << "got a query..."; } void OctreeServer::aboutToBlock() { - qDebug() << "OctreeServer::aboutToBlock()..."; + const bool wantDebug = false; + if (wantDebug) { + qDebug() << "OctreeServer::aboutToBlock()..."; + } } void OctreeServer::awake() { - qDebug() << "OctreeServer::awake()..."; + const bool wantDebug = false; + if (wantDebug) { + qDebug() << "OctreeServer::awake()..."; + } } void OctreeServer::run() { @@ -1322,6 +1330,8 @@ QString OctreeServer::getStatusLink() { } void OctreeServer::sendStatsPacket() { + + /* quint64 start = usecTimestampNow(); static QJsonObject statsObject1; ThreadedAssignment::addPacketStatsAndSendStatsPacket(statsObject1); @@ -1329,8 +1339,8 @@ void OctreeServer::sendStatsPacket() { if (end - start > 1000) { qDebug() << "OctreeServer::sendStatsPacket() took:" << (end - start); } + */ - /** // TODO: we have too many stats to fit in a single MTU... so for now, we break it into multiple JSON objects and // send them separately. What we really should do is change the NodeList::sendStatsToDomainServer() to handle the // the following features: @@ -1404,8 +1414,6 @@ void OctreeServer::sendStatsPacket() { (double)_octreeInboundPacketProcessor->getAverageLockWaitTimePerElement(); NodeList::getInstance()->sendStatsToDomainServer(statsObject3); - - **/ } QMap OctreeServer::_threadsDidProcess; diff --git a/libraries/networking/src/ThreadedAssignment.cpp b/libraries/networking/src/ThreadedAssignment.cpp index d3de3cdd74..ebb1435e63 100644 --- a/libraries/networking/src/ThreadedAssignment.cpp +++ b/libraries/networking/src/ThreadedAssignment.cpp @@ -59,7 +59,7 @@ void ThreadedAssignment::commonInit(const QString& targetName, NodeType_t nodeTy statsTimer->start(1000); } - qDebug() << "ThreadedAssignment::commonInit()... thread()->eventDispatcher()=" << thread()->eventDispatcher(); + //qDebug() << "ThreadedAssignment::commonInit()... thread()->eventDispatcher()=" << thread()->eventDispatcher(); } @@ -84,12 +84,12 @@ void ThreadedAssignment::sendStatsPacket() { quint64 lastCheckIn = usecTimestampNow(); void ThreadedAssignment::checkInWithDomainServerOrExit() { - qDebug() << "ThreadedAssignment::checkInWithDomainServerOrExit()... thread()->eventDispatcher()=" << thread()->eventDispatcher(); + //qDebug() << "ThreadedAssignment::checkInWithDomainServerOrExit()... thread()->eventDispatcher()=" << thread()->eventDispatcher(); quint64 now = usecTimestampNow(); - if ((now - lastCheckIn) > 100000) { - //qDebug() << "ThreadedAssignment::checkInWithDomainServerOrExit(): since lastCheckIn=" << (now - lastCheckIn) << "usecs"; + if ((now - lastCheckIn) > 1100000) { + qDebug() << "ThreadedAssignment::checkInWithDomainServerOrExit(): since lastCheckIn=" << (now - lastCheckIn) << "usecs"; } lastCheckIn = now; From c1ed38f4deddbd7e9873b522e6bb3d3f3d559cc0 Mon Sep 17 00:00:00 2001 From: Thijs Wenker Date: Mon, 21 Apr 2014 21:23:39 +0200 Subject: [PATCH 539/595] Style --- interface/src/ScriptHighlighting.cpp | 68 +++++++++--------- interface/src/ScriptHighlighting.h | 18 ++--- interface/src/ui/ScriptEditorWidget.cpp | 74 +++++++++---------- interface/src/ui/ScriptEditorWidget.h | 11 +-- interface/src/ui/ScriptEditorWindow.cpp | 96 ++++++++++++++----------- interface/src/ui/ScriptEditorWindow.h | 11 +-- 6 files changed, 147 insertions(+), 131 deletions(-) diff --git a/interface/src/ScriptHighlighting.cpp b/interface/src/ScriptHighlighting.cpp index b2c5ca2ec6..9b58298b62 100644 --- a/interface/src/ScriptHighlighting.cpp +++ b/interface/src/ScriptHighlighting.cpp @@ -15,16 +15,16 @@ ScriptHighlighting::ScriptHighlighting(QTextDocument* parent) : QSyntaxHighlighter(parent) { - keywordRegex = QRegExp("\\b(break|case|catch|continue|debugger|default|delete|do|else|finally|for|function|if|in|instanceof|new|return|switch|this|throw|try|typeof|var|void|while|with)\\b"); - qoutedTextRegex = QRegExp("\".*\""); - multiLineCommentBegin = QRegExp("/\\*"); - multiLineCommentEnd = QRegExp("\\*/"); - numberRegex = QRegExp("[0-9]+(\\.[0-9]+){0,1}"); - singleLineComment = QRegExp("//[^\n]*"); - truefalseRegex = QRegExp("\\b(true|false)\\b"); + _keywordRegex = QRegExp("\\b(break|case|catch|continue|debugger|default|delete|do|else|finally|for|function|if|in|instanceof|new|return|switch|this|throw|try|typeof|var|void|while|with)\\b"); + _qoutedTextRegex = QRegExp("\".*\""); + _multiLineCommentBegin = QRegExp("/\\*"); + _multiLineCommentEnd = QRegExp("\\*/"); + _numberRegex = QRegExp("[0-9]+(\\.[0-9]+){0,1}"); + _singleLineComment = QRegExp("//[^\n]*"); + _truefalseRegex = QRegExp("\\b(true|false)\\b"); } -void ScriptHighlighting::highlightBlock(const QString &text) { +void ScriptHighlighting::highlightBlock(const QString& text) { this->highlightKeywords(text); this->formatNumbers(text); this->formatTrueFalse(text); @@ -32,62 +32,64 @@ void ScriptHighlighting::highlightBlock(const QString &text) { this->formatComments(text); } -void ScriptHighlighting::highlightKeywords(const QString &text) { - int index = keywordRegex.indexIn(text); +void ScriptHighlighting::highlightKeywords(const QString& text) { + int index = _keywordRegex.indexIn(text); while (index >= 0) { - int length = keywordRegex.matchedLength(); + int length = _keywordRegex.matchedLength(); setFormat(index, length, Qt::blue); - index = keywordRegex.indexIn(text, index + length); + index = _keywordRegex.indexIn(text, index + length); } } -void ScriptHighlighting::formatComments(const QString &text) { +void ScriptHighlighting::formatComments(const QString& text) { setCurrentBlockState(BlockStateClean); - int start = (previousBlockState() != BlockStateInMultiComment) ? text.indexOf(multiLineCommentBegin) : 0; + int start = (previousBlockState() != BlockStateInMultiComment) ? text.indexOf(_multiLineCommentBegin) : 0; while (start > -1) { - int end = text.indexOf(multiLineCommentEnd, start); - int length = (end == -1 ? text.length() : (end + multiLineCommentEnd.matchedLength())) - start; + int end = text.indexOf(_multiLineCommentEnd, start); + int length = (end == -1 ? text.length() : (end + _multiLineCommentEnd.matchedLength())) - start; setFormat(start, length, Qt::lightGray); - start = text.indexOf(multiLineCommentBegin, start + length); - if (end == -1) setCurrentBlockState(BlockStateInMultiComment); + start = text.indexOf(_multiLineCommentBegin, start + length); + if (end == -1) { + setCurrentBlockState(BlockStateInMultiComment); + } } - int index = singleLineComment.indexIn(text); + int index = _singleLineComment.indexIn(text); while (index >= 0) { - int length = singleLineComment.matchedLength(); + int length = _singleLineComment.matchedLength(); setFormat(index, length, Qt::lightGray); - index = singleLineComment.indexIn(text, index + length); + index = _singleLineComment.indexIn(text, index + length); } } -void ScriptHighlighting::formatQoutedText(const QString &text){ - int index = qoutedTextRegex.indexIn(text); +void ScriptHighlighting::formatQoutedText(const QString& text){ + int index = _qoutedTextRegex.indexIn(text); while (index >= 0) { - int length = qoutedTextRegex.matchedLength(); + int length = _qoutedTextRegex.matchedLength(); setFormat(index, length, Qt::red); - index = qoutedTextRegex.indexIn(text, index + length); + index = _qoutedTextRegex.indexIn(text, index + length); } } -void ScriptHighlighting::formatNumbers(const QString &text){ - int index = numberRegex.indexIn(text); +void ScriptHighlighting::formatNumbers(const QString& text){ + int index = _numberRegex.indexIn(text); while (index >= 0) { - int length = numberRegex.matchedLength(); + int length = _numberRegex.matchedLength(); setFormat(index, length, Qt::green); - index = numberRegex.indexIn(text, index + length); + index = _numberRegex.indexIn(text, index + length); } } -void ScriptHighlighting::formatTrueFalse(const QString text){ - int index = truefalseRegex.indexIn(text); +void ScriptHighlighting::formatTrueFalse(const QString& text){ + int index = _truefalseRegex.indexIn(text); while (index >= 0) { - int length = truefalseRegex.matchedLength(); + int length = _truefalseRegex.matchedLength(); QFont* font = new QFont(this->document()->defaultFont()); font->setBold(true); setFormat(index, length, *font); - index = truefalseRegex.indexIn(text, index + length); + index = _truefalseRegex.indexIn(text, index + length); } } \ No newline at end of file diff --git a/interface/src/ScriptHighlighting.h b/interface/src/ScriptHighlighting.h index 9cbbf277cc..d86d6f4d77 100644 --- a/interface/src/ScriptHighlighting.h +++ b/interface/src/ScriptHighlighting.h @@ -18,7 +18,7 @@ class ScriptHighlighting : public QSyntaxHighlighter { Q_OBJECT public: - ScriptHighlighting(QTextDocument* parent = 0); + ScriptHighlighting(QTextDocument* parent = NULL); enum BlockState { BlockStateClean, @@ -31,16 +31,16 @@ protected: void formatComments(const QString& text); void formatQoutedText(const QString& text); void formatNumbers(const QString& text); - void formatTrueFalse(const QString text); + void formatTrueFalse(const QString& text); private: - QRegExp keywordRegex; - QRegExp qoutedTextRegex; - QRegExp multiLineCommentBegin; - QRegExp multiLineCommentEnd; - QRegExp numberRegex; - QRegExp singleLineComment; - QRegExp truefalseRegex; + QRegExp _keywordRegex; + QRegExp _qoutedTextRegex; + QRegExp _multiLineCommentBegin; + QRegExp _multiLineCommentEnd; + QRegExp _numberRegex; + QRegExp _singleLineComment; + QRegExp _truefalseRegex; }; #endif // hifi_ScriptHighlighting_h diff --git a/interface/src/ui/ScriptEditorWidget.cpp b/interface/src/ui/ScriptEditorWidget.cpp index 91e3efe1df..d24c68a613 100644 --- a/interface/src/ui/ScriptEditorWidget.cpp +++ b/interface/src/ui/ScriptEditorWidget.cpp @@ -27,40 +27,39 @@ #include "ScriptHighlighting.h" ScriptEditorWidget::ScriptEditorWidget() : - ui(new Ui::ScriptEditorWidget) + _scriptEditorWidgetUI(new Ui::ScriptEditorWidget), + _scriptEngine(NULL) { - ui->setupUi(this); + _scriptEditorWidgetUI->setupUi(this); - scriptEngine = NULL; - - connect(ui->scriptEdit->document(), SIGNAL(modificationChanged(bool)), this, SIGNAL(scriptModified())); - connect(ui->scriptEdit->document(), SIGNAL(contentsChanged()), this, SLOT(onScriptModified())); + connect(_scriptEditorWidgetUI->scriptEdit->document(), SIGNAL(modificationChanged(bool)), this, SIGNAL(scriptModified())); + connect(_scriptEditorWidgetUI->scriptEdit->document(), SIGNAL(contentsChanged()), this, SLOT(onScriptModified())); // remove the title bar (see the Qt docs on setTitleBarWidget) setTitleBarWidget(new QWidget()); - QFontMetrics fm(this->ui->scriptEdit->font()); - this->ui->scriptEdit->setTabStopWidth(fm.width('0') * 4); - ScriptHighlighting* highlighting = new ScriptHighlighting(this->ui->scriptEdit->document()); - QTimer::singleShot(0, this->ui->scriptEdit, SLOT(setFocus())); + QFontMetrics fm(_scriptEditorWidgetUI->scriptEdit->font()); + _scriptEditorWidgetUI->scriptEdit->setTabStopWidth(fm.width('0') * 4); + ScriptHighlighting* highlighting = new ScriptHighlighting(_scriptEditorWidgetUI->scriptEdit->document()); + QTimer::singleShot(0, _scriptEditorWidgetUI->scriptEdit, SLOT(setFocus())); } ScriptEditorWidget::~ScriptEditorWidget() { - delete ui; + delete _scriptEditorWidgetUI; } void ScriptEditorWidget::onScriptModified() { - if(ui->onTheFlyCheckBox->isChecked() && isRunning()) { + if(_scriptEditorWidgetUI->onTheFlyCheckBox->isChecked() && isRunning()) { setRunning(false); setRunning(true); } } bool ScriptEditorWidget::isModified() { - return ui->scriptEdit->document()->isModified(); + return _scriptEditorWidgetUI->scriptEdit->document()->isModified(); } bool ScriptEditorWidget::isRunning() { - return (scriptEngine != NULL) ? scriptEngine->isRunning() : false; + return (_scriptEngine != NULL) ? _scriptEngine->isRunning() : false; } bool ScriptEditorWidget::setRunning(bool run) { @@ -72,15 +71,15 @@ bool ScriptEditorWidget::setRunning(bool run) { disconnect(this, SLOT(onScriptPrint(const QString&))); if (run) { - scriptEngine = Application::getInstance()->loadScript(this->currentScript, false); - connect(scriptEngine, SIGNAL(runningStateChanged()), this, SIGNAL(runningStateChanged())); + _scriptEngine = Application::getInstance()->loadScript(_currentScript, false); + connect(_scriptEngine, SIGNAL(runningStateChanged()), this, SIGNAL(runningStateChanged())); // Make new connections. - connect(scriptEngine, SIGNAL(errorMessage(const QString&)), this, SLOT(onScriptError(const QString&))); - connect(scriptEngine, SIGNAL(printedMessage(const QString&)), this, SLOT(onScriptPrint(const QString&))); + connect(_scriptEngine, SIGNAL(errorMessage(const QString&)), this, SLOT(onScriptError(const QString&))); + connect(_scriptEngine, SIGNAL(printedMessage(const QString&)), this, SLOT(onScriptPrint(const QString&))); } else { - Application::getInstance()->stopScript(this->currentScript); - scriptEngine = NULL; + Application::getInstance()->stopScript(_currentScript); + _scriptEngine = NULL; } return true; } @@ -88,18 +87,19 @@ bool ScriptEditorWidget::setRunning(bool run) { bool ScriptEditorWidget::saveFile(const QString &scriptPath) { QFile file(scriptPath); if (!file.open(QFile::WriteOnly | QFile::Text)) { - QMessageBox::warning(this, tr("Interface"), tr("Cannot write script %1:\n%2.").arg(scriptPath).arg(file.errorString())); + QMessageBox::warning(this, tr("Interface"), tr("Cannot write script %1:\n%2.").arg(scriptPath) + .arg(file.errorString())); return false; } QTextStream out(&file); - out << ui->scriptEdit->toPlainText(); + out << _scriptEditorWidgetUI->scriptEdit->toPlainText(); setScriptFile(scriptPath); return true; } -void ScriptEditorWidget::loadFile(const QString &scriptPath) { +void ScriptEditorWidget::loadFile(const QString& scriptPath) { QFile file(scriptPath); if (!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this, tr("Interface"), tr("Cannot read script %1:\n%2.").arg(scriptPath).arg(file.errorString())); @@ -107,23 +107,23 @@ void ScriptEditorWidget::loadFile(const QString &scriptPath) { } QTextStream in(&file); - ui->scriptEdit->setPlainText(in.readAll()); + _scriptEditorWidgetUI->scriptEdit->setPlainText(in.readAll()); setScriptFile(scriptPath); disconnect(this, SLOT(onScriptError(const QString&))); disconnect(this, SLOT(onScriptPrint(const QString&))); - scriptEngine = Application::getInstance()->getScriptEngine(scriptPath); - if (scriptEngine != NULL) { - connect(scriptEngine, SIGNAL(runningStateChanged()), this, SIGNAL(runningStateChanged())); - connect(scriptEngine, SIGNAL(errorMessage(const QString&)), this, SLOT(onScriptError(const QString&))); - connect(scriptEngine, SIGNAL(printedMessage(const QString&)), this, SLOT(onScriptPrint(const QString&))); + _scriptEngine = Application::getInstance()->getScriptEngine(scriptPath); + if (_scriptEngine != NULL) { + connect(_scriptEngine, SIGNAL(runningStateChanged()), this, SIGNAL(runningStateChanged())); + connect(_scriptEngine, SIGNAL(errorMessage(const QString&)), this, SLOT(onScriptError(const QString&))); + connect(_scriptEngine, SIGNAL(printedMessage(const QString&)), this, SLOT(onScriptPrint(const QString&))); } } bool ScriptEditorWidget::save() { - return currentScript.isEmpty() ? saveAs() : saveFile(currentScript); + return _currentScript.isEmpty() ? saveAs() : saveFile(_currentScript); } bool ScriptEditorWidget::saveAs() { @@ -132,25 +132,27 @@ bool ScriptEditorWidget::saveAs() { } void ScriptEditorWidget::setScriptFile(const QString& scriptPath) { - currentScript = scriptPath; - ui->scriptEdit->document()->setModified(false); + _currentScript = scriptPath; + _scriptEditorWidgetUI->scriptEdit->document()->setModified(false); setWindowModified(false); emit scriptnameChanged(); } bool ScriptEditorWidget::questionSave() { - if (ui->scriptEdit->document()->isModified()) { - QMessageBox::StandardButton button = QMessageBox::warning(this, tr("Interface"), tr("The script has been modified.\nDo you want to save your changes?"), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Save); + if (_scriptEditorWidgetUI->scriptEdit->document()->isModified()) { + QMessageBox::StandardButton button = QMessageBox::warning(this, tr("Interface"), + tr("The script has been modified.\nDo you want to save your changes?"), QMessageBox::Save | QMessageBox::Discard | + QMessageBox::Cancel, QMessageBox::Save); return button == QMessageBox::Save ? save() : (button == QMessageBox::Cancel ? false : true); } return true; } void ScriptEditorWidget::onScriptError(const QString& message) { - ui->debugText->appendPlainText("ERROR: "+ message); + _scriptEditorWidgetUI->debugText->appendPlainText("ERROR: " + message); } void ScriptEditorWidget::onScriptPrint(const QString& message) { - ui->debugText->appendPlainText("> "+message); + _scriptEditorWidgetUI->debugText->appendPlainText("> " + message); } \ No newline at end of file diff --git a/interface/src/ui/ScriptEditorWidget.h b/interface/src/ui/ScriptEditorWidget.h index 5fed373658..3e50280a62 100644 --- a/interface/src/ui/ScriptEditorWidget.h +++ b/interface/src/ui/ScriptEditorWidget.h @@ -17,7 +17,7 @@ #include "ScriptEngine.h" namespace Ui { -class ScriptEditorWidget; + class ScriptEditorWidget; } class ScriptEditorWidget : public QDockWidget { @@ -36,7 +36,8 @@ public: bool save(); bool saveAs(); bool questionSave(); - const QString getScriptName() const { return currentScript; }; + const QString getScriptName() const { return _currentScript; }; + signals: void runningStateChanged(); void scriptnameChanged(); @@ -48,9 +49,9 @@ private slots: void onScriptModified(); private: - Ui::ScriptEditorWidget* ui; - ScriptEngine* scriptEngine; - QString currentScript; + Ui::ScriptEditorWidget* _scriptEditorWidgetUI; + ScriptEngine* _scriptEngine; + QString _currentScript; }; #endif // hifi_ScriptEditorWidget_h diff --git a/interface/src/ui/ScriptEditorWindow.cpp b/interface/src/ui/ScriptEditorWindow.cpp index 69283feccf..00a3ef9f0c 100644 --- a/interface/src/ui/ScriptEditorWindow.cpp +++ b/interface/src/ui/ScriptEditorWindow.cpp @@ -29,19 +29,19 @@ #include "FlowLayout.h" ScriptEditorWindow::ScriptEditorWindow() : - ui(new Ui::ScriptEditorWindow) + _ScriptEditorWindowUI(new Ui::ScriptEditorWindow), + _loadMenu(new QMenu), + _saveMenu(new QMenu) { - ui->setupUi(this); + _ScriptEditorWindowUI->setupUi(this); show(); addScriptEditorWidget("New script"); - loadMenu = new QMenu(); - connect(loadMenu, SIGNAL(aboutToShow()), this, SLOT(loadMenuAboutToShow())); - ui->loadButton->setMenu(loadMenu); + connect(_loadMenu, SIGNAL(aboutToShow()), this, SLOT(loadMenuAboutToShow())); + _ScriptEditorWindowUI->loadButton->setMenu(_loadMenu); - saveMenu = new QMenu(); - saveMenu->addAction("Save as..", this, SLOT(saveScriptAsClicked()), Qt::CTRL|Qt::SHIFT|Qt::Key_S); + _saveMenu->addAction("Save as..", this, SLOT(saveScriptAsClicked()), Qt::CTRL | Qt::SHIFT | Qt::Key_S); - ui->saveButton->setMenu(saveMenu); + _ScriptEditorWindowUI->saveButton->setMenu(_saveMenu); connect(new QShortcut(QKeySequence("Ctrl+N"), this), SIGNAL(activated()), this, SLOT(newScriptClicked())); connect(new QShortcut(QKeySequence("Ctrl+S"), this), SIGNAL(activated()), this, SLOT(saveScriptClicked())); @@ -50,19 +50,21 @@ ScriptEditorWindow::ScriptEditorWindow() : } ScriptEditorWindow::~ScriptEditorWindow() { - delete ui; + delete _ScriptEditorWindowUI; } void ScriptEditorWindow::setRunningState(bool run) { - if (ui->tabWidget->currentIndex() != -1) { - ((ScriptEditorWidget*)ui->tabWidget->currentWidget())->setRunning(run); + if (_ScriptEditorWindowUI->tabWidget->currentIndex() != -1) { + static_cast(_ScriptEditorWindowUI->tabWidget->currentWidget())->setRunning(run); } this->updateButtons(); } void ScriptEditorWindow::updateButtons() { - ui->toggleRunButton->setEnabled(ui->tabWidget->currentIndex() != -1); - ui->toggleRunButton->setIcon(ui->tabWidget->currentIndex() != -1 && ((ScriptEditorWidget*)ui->tabWidget->currentWidget())->isRunning() ? QIcon("../resources/icons/stop-script.svg"):QIcon("../resources/icons/start-script.svg")); + _ScriptEditorWindowUI->toggleRunButton->setEnabled(_ScriptEditorWindowUI->tabWidget->currentIndex() != -1); + _ScriptEditorWindowUI->toggleRunButton->setIcon(_ScriptEditorWindowUI->tabWidget->currentIndex() != -1 && + static_cast(_ScriptEditorWindowUI->tabWidget->currentWidget())->isRunning() ? + QIcon("../resources/icons/stop-script.svg") : QIcon("../resources/icons/start-script.svg")); } void ScriptEditorWindow::loadScriptMenu(const QString& scriptName) { @@ -79,21 +81,21 @@ void ScriptEditorWindow::loadScriptClicked() { } void ScriptEditorWindow::loadMenuAboutToShow() { - loadMenu->clear(); + _loadMenu->clear(); QStringList runningScripts = Application::getInstance()->getRunningScripts(); if (runningScripts.count() > 0) { QSignalMapper* signalMapper = new QSignalMapper(this); foreach (const QString& runningScript, runningScripts) { - QAction* runningScriptAction = new QAction(runningScript, loadMenu); + QAction* runningScriptAction = new QAction(runningScript, _loadMenu); connect(runningScriptAction, SIGNAL(triggered()), signalMapper, SLOT(map())); signalMapper->setMapping(runningScriptAction, runningScript); - loadMenu->addAction(runningScriptAction); + _loadMenu->addAction(runningScriptAction); } - connect(signalMapper, SIGNAL(mapped(const QString &)), this, SLOT(loadScriptMenu(const QString &))); + connect(signalMapper, SIGNAL(mapped(const QString &)), this, SLOT(loadScriptMenu(const QString&))); } else { - QAction* naAction = new QAction("(no running scripts)",loadMenu); + QAction* naAction = new QAction("(no running scripts)", _loadMenu); naAction->setDisabled(true); - loadMenu->addAction(naAction); + _loadMenu->addAction(naAction); } } @@ -102,19 +104,22 @@ void ScriptEditorWindow::newScriptClicked() { } void ScriptEditorWindow::toggleRunScriptClicked() { - this->setRunningState(!(ui->tabWidget->currentIndex() !=-1 && ((ScriptEditorWidget*)ui->tabWidget->currentWidget())->isRunning())); + this->setRunningState(!(_ScriptEditorWindowUI->tabWidget->currentIndex() !=-1 + && static_cast(_ScriptEditorWindowUI->tabWidget->currentWidget())->isRunning())); } void ScriptEditorWindow::saveScriptClicked() { - if (ui->tabWidget->currentIndex() != -1) { - ScriptEditorWidget* currentScriptWidget = (ScriptEditorWidget*)ui->tabWidget->currentWidget(); + if (_ScriptEditorWindowUI->tabWidget->currentIndex() != -1) { + ScriptEditorWidget* currentScriptWidget = static_cast(_ScriptEditorWindowUI->tabWidget + ->currentWidget()); currentScriptWidget->save(); } } void ScriptEditorWindow::saveScriptAsClicked() { - if (ui->tabWidget->currentIndex() != -1) { - ScriptEditorWidget* currentScriptWidget = (ScriptEditorWidget*)ui->tabWidget->currentWidget(); + if (_ScriptEditorWindowUI->tabWidget->currentIndex() != -1) { + ScriptEditorWidget* currentScriptWidget = static_cast(_ScriptEditorWindowUI->tabWidget + ->currentWidget()); currentScriptWidget->saveAs(); } } @@ -124,8 +129,8 @@ ScriptEditorWidget* ScriptEditorWindow::addScriptEditorWidget(QString title) { connect(newScriptEditorWidget, SIGNAL(scriptnameChanged()), this, SLOT(updateScriptNameOrStatus())); connect(newScriptEditorWidget, SIGNAL(scriptModified()), this, SLOT(updateScriptNameOrStatus())); connect(newScriptEditorWidget, SIGNAL(runningStateChanged()), this, SLOT(updateButtons())); - ui->tabWidget->addTab(newScriptEditorWidget, title); - ui->tabWidget->setCurrentWidget(newScriptEditorWidget); + _ScriptEditorWindowUI->tabWidget->addTab(newScriptEditorWidget, title); + _ScriptEditorWindowUI->tabWidget->setCurrentWidget(newScriptEditorWidget); newScriptEditorWidget->setUpdatesEnabled(true); newScriptEditorWidget->adjustSize(); return newScriptEditorWidget; @@ -133,13 +138,14 @@ ScriptEditorWidget* ScriptEditorWindow::addScriptEditorWidget(QString title) { void ScriptEditorWindow::tabSwitched(int tabIndex) { this->updateButtons(); - if (ui->tabWidget->currentIndex() != -1) { - ScriptEditorWidget* currentScriptWidget = (ScriptEditorWidget*)ui->tabWidget->currentWidget(); - QString modifiedStar = (currentScriptWidget->isModified()?"*":""); + if (_ScriptEditorWindowUI->tabWidget->currentIndex() != -1) { + ScriptEditorWidget* currentScriptWidget = static_cast(_ScriptEditorWindowUI->tabWidget + ->currentWidget()); + QString modifiedStar = (currentScriptWidget->isModified() ? "*" : ""); if (currentScriptWidget->getScriptName().length() > 0) { - this->setWindowTitle("Script Editor ["+currentScriptWidget->getScriptName()+modifiedStar+"]"); + this->setWindowTitle("Script Editor [" + currentScriptWidget->getScriptName() + modifiedStar + "]"); } else { - this->setWindowTitle("Script Editor [New script"+modifiedStar+"]"); + this->setWindowTitle("Script Editor [New script" + modifiedStar + "]"); } } else { this->setWindowTitle("Script Editor"); @@ -147,21 +153,25 @@ void ScriptEditorWindow::tabSwitched(int tabIndex) { } void ScriptEditorWindow::tabCloseRequested(int tabIndex) { - ScriptEditorWidget* closingScriptWidget = (ScriptEditorWidget*)ui->tabWidget->widget(tabIndex); + ScriptEditorWidget* closingScriptWidget = static_cast(_ScriptEditorWindowUI->tabWidget + ->widget(tabIndex)); if(closingScriptWidget->questionSave()) { - ui->tabWidget->removeTab(tabIndex); + _ScriptEditorWindowUI->tabWidget->removeTab(tabIndex); } } void ScriptEditorWindow::closeEvent(QCloseEvent *event) { bool unsaved_docs_warning = false; - for (int i = 0; i < ui->tabWidget->count(); i++ && !unsaved_docs_warning){ - if(((ScriptEditorWidget*)ui->tabWidget->widget(i))->isModified()){ + for (int i = 0; i < _ScriptEditorWindowUI->tabWidget->count(); i++){ + if(static_cast(_ScriptEditorWindowUI->tabWidget->widget(i))->isModified()){ unsaved_docs_warning = true; + break; } } - if (!unsaved_docs_warning || QMessageBox::warning(this, tr("Interface"), tr("There are some unsaved scripts, are you sure you want to close the editor? Changes will be lost!"), QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel) == QMessageBox::Discard) { + if (!unsaved_docs_warning || QMessageBox::warning(this, tr("Interface"), + tr("There are some unsaved scripts, are you sure you want to close the editor? Changes will be lost!"), + QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel) == QMessageBox::Discard) { event->accept(); } else { event->ignore(); @@ -172,19 +182,19 @@ void ScriptEditorWindow::updateScriptNameOrStatus() { ScriptEditorWidget* source = (ScriptEditorWidget*)QObject::sender(); QString modifiedStar = (source->isModified()?"*":""); if (source->getScriptName().length() > 0) { - for (int i = 0; i < ui->tabWidget->count(); i++){ - if (ui->tabWidget->widget(i) == source) { - ui->tabWidget->setTabText(i,modifiedStar+QFileInfo(source->getScriptName()).fileName()); - ui->tabWidget->setTabToolTip(i, source->getScriptName()); + for (int i = 0; i < _ScriptEditorWindowUI->tabWidget->count(); i++){ + if (_ScriptEditorWindowUI->tabWidget->widget(i) == source) { + _ScriptEditorWindowUI->tabWidget->setTabText(i,modifiedStar + QFileInfo(source->getScriptName()).fileName()); + _ScriptEditorWindowUI->tabWidget->setTabToolTip(i, source->getScriptName()); } } } - if (ui->tabWidget->currentWidget() == source) { + if (_ScriptEditorWindowUI->tabWidget->currentWidget() == source) { if (source->getScriptName().length() > 0) { - this->setWindowTitle("Script Editor ["+source->getScriptName()+modifiedStar+"]"); + this->setWindowTitle("Script Editor [" + source->getScriptName() + modifiedStar + "]"); } else { - this->setWindowTitle("Script Editor [New script"+modifiedStar+"]"); + this->setWindowTitle("Script Editor [New script" + modifiedStar + "]"); } } } \ No newline at end of file diff --git a/interface/src/ui/ScriptEditorWindow.h b/interface/src/ui/ScriptEditorWindow.h index a1b72423ec..0bf5015ccf 100644 --- a/interface/src/ui/ScriptEditorWindow.h +++ b/interface/src/ui/ScriptEditorWindow.h @@ -15,7 +15,7 @@ #include "ScriptEditorWidget.h" namespace Ui { -class ScriptEditorWindow; + class ScriptEditorWindow; } class ScriptEditorWindow : public QWidget { @@ -26,12 +26,13 @@ public: ~ScriptEditorWindow(); protected: - void closeEvent(QCloseEvent *event); + void closeEvent(QCloseEvent* event); private: - Ui::ScriptEditorWindow* ui; - QMenu* loadMenu; - QMenu* saveMenu; + Ui::ScriptEditorWindow* _ScriptEditorWindowUI; + QMenu* _loadMenu; + QMenu* _saveMenu; + ScriptEditorWidget* addScriptEditorWidget(QString title); void setRunningState(bool run); void setScriptName(const QString& scriptName); From 9faee0d82d9a42938778075f5bc43d38bf16e21d Mon Sep 17 00:00:00 2001 From: Thijs Wenker Date: Mon, 21 Apr 2014 21:37:49 +0200 Subject: [PATCH 540/595] - Style - Script Editor can run script file once at time, but you can still start multiple scripts through the original ways. --- interface/src/Application.cpp | 6 +++--- interface/src/Application.h | 2 +- interface/src/ui/ScriptEditorWidget.cpp | 2 +- interface/src/ui/ScriptEditorWindow.cpp | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 79d3e7597e..4ba465bbe1 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3377,8 +3377,8 @@ void Application::uploadSkeleton() { uploadFST(false); } -ScriptEngine* Application::loadScript(const QString& scriptName, bool focusMainWindow) { - if(_scriptEnginesHash.contains(scriptName) && !_scriptEnginesHash[scriptName]->isFinished()){ +ScriptEngine* Application::loadScript(const QString& scriptName, bool loadScriptFromEditor) { + if(loadScriptFromEditor && _scriptEnginesHash.contains(scriptName) && !_scriptEnginesHash[scriptName]->isFinished()){ return _scriptEnginesHash[scriptName]; } @@ -3436,7 +3436,7 @@ ScriptEngine* Application::loadScript(const QString& scriptName, bool focusMainW workerThread->start(); // restore the main window's active state - if (focusMainWindow) { + if (!loadScriptFromEditor) { _window->activateWindow(); } bumpSettings(); diff --git a/interface/src/Application.h b/interface/src/Application.h index e66e7e2975..fb48acb721 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -121,7 +121,7 @@ public: ~Application(); void restoreSizeAndPosition(); - ScriptEngine* loadScript(const QString& fileNameString, bool focusMainWindow = true); + ScriptEngine* loadScript(const QString& fileNameString, bool loadScriptFromEditor = false); void loadScripts(); void storeSizeAndPosition(); void clearScriptsBeforeRunning(); diff --git a/interface/src/ui/ScriptEditorWidget.cpp b/interface/src/ui/ScriptEditorWidget.cpp index d24c68a613..74b74e1ad6 100644 --- a/interface/src/ui/ScriptEditorWidget.cpp +++ b/interface/src/ui/ScriptEditorWidget.cpp @@ -71,7 +71,7 @@ bool ScriptEditorWidget::setRunning(bool run) { disconnect(this, SLOT(onScriptPrint(const QString&))); if (run) { - _scriptEngine = Application::getInstance()->loadScript(_currentScript, false); + _scriptEngine = Application::getInstance()->loadScript(_currentScript, true); connect(_scriptEngine, SIGNAL(runningStateChanged()), this, SIGNAL(runningStateChanged())); // Make new connections. diff --git a/interface/src/ui/ScriptEditorWindow.cpp b/interface/src/ui/ScriptEditorWindow.cpp index 00a3ef9f0c..26488f0223 100644 --- a/interface/src/ui/ScriptEditorWindow.cpp +++ b/interface/src/ui/ScriptEditorWindow.cpp @@ -180,11 +180,11 @@ void ScriptEditorWindow::closeEvent(QCloseEvent *event) { void ScriptEditorWindow::updateScriptNameOrStatus() { ScriptEditorWidget* source = (ScriptEditorWidget*)QObject::sender(); - QString modifiedStar = (source->isModified()?"*":""); + QString modifiedStar = (source->isModified()? "*" : ""); if (source->getScriptName().length() > 0) { for (int i = 0; i < _ScriptEditorWindowUI->tabWidget->count(); i++){ if (_ScriptEditorWindowUI->tabWidget->widget(i) == source) { - _ScriptEditorWindowUI->tabWidget->setTabText(i,modifiedStar + QFileInfo(source->getScriptName()).fileName()); + _ScriptEditorWindowUI->tabWidget->setTabText(i, modifiedStar + QFileInfo(source->getScriptName()).fileName()); _ScriptEditorWindowUI->tabWidget->setTabToolTip(i, source->getScriptName()); } } From 70ac93c20d8153ca32fbc7a6f49633462c6c17f8 Mon Sep 17 00:00:00 2001 From: Thijs Wenker Date: Mon, 21 Apr 2014 21:44:50 +0200 Subject: [PATCH 541/595] Style --- interface/src/ui/ScriptEditorWindow.cpp | 2 +- libraries/script-engine/src/ScriptEngine.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/ui/ScriptEditorWindow.cpp b/interface/src/ui/ScriptEditorWindow.cpp index 26488f0223..ec63e0341d 100644 --- a/interface/src/ui/ScriptEditorWindow.cpp +++ b/interface/src/ui/ScriptEditorWindow.cpp @@ -179,7 +179,7 @@ void ScriptEditorWindow::closeEvent(QCloseEvent *event) { } void ScriptEditorWindow::updateScriptNameOrStatus() { - ScriptEditorWidget* source = (ScriptEditorWidget*)QObject::sender(); + ScriptEditorWidget* source = static_cast(QObject::sender()); QString modifiedStar = (source->isModified()? "*" : ""); if (source->getScriptName().length() > 0) { for (int i = 0; i < _ScriptEditorWindowUI->tabWidget->count(); i++){ diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index eeb1cebe09..2e92567fe7 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -45,7 +45,7 @@ static QScriptValue soundConstructor(QScriptContext* context, QScriptEngine* eng static QScriptValue debugPrint(QScriptContext* context, QScriptEngine* engine){ qDebug() << "script:print()<<" << context->argument(0).toString(); - engine->evaluate("Script.print('"+context->argument(0).toString()+"')"); + engine->evaluate("Script.print('" + context->argument(0).toString() + "')"); return QScriptValue(); } From 14e1fa269a78c50454b9b8e3b9eab4d2b7eaeca8 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 21 Apr 2014 13:28:03 -0700 Subject: [PATCH 542/595] cleanup --- assignment-client/src/AssignmentClient.cpp | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/assignment-client/src/AssignmentClient.cpp b/assignment-client/src/AssignmentClient.cpp index e4b38258f0..ff876596b0 100644 --- a/assignment-client/src/AssignmentClient.cpp +++ b/assignment-client/src/AssignmentClient.cpp @@ -17,7 +17,6 @@ #include #include -#include #include #include #include @@ -146,11 +145,6 @@ void AssignmentClient::readPendingDatagrams() { // start the deployed assignment AssignmentThread* workerThread = new AssignmentThread(_currentAssignment, this); - qDebug() << "workerThread->eventDispatcher()=" << workerThread->eventDispatcher(); - qDebug() << "thread()->eventDispatcher()=" << thread()->eventDispatcher(); - - //DebuggingEventDispatcher* debugDispatcher = new DebuggingEventDispatcher(workerThread); - connect(workerThread, &QThread::started, _currentAssignment.data(), &ThreadedAssignment::run); connect(_currentAssignment.data(), &ThreadedAssignment::finished, workerThread, &QThread::quit); connect(_currentAssignment.data(), &ThreadedAssignment::finished, @@ -169,10 +163,6 @@ void AssignmentClient::readPendingDatagrams() { // Starts an event loop, and emits workerThread->started() workerThread->start(); - - qDebug() << "workerThread->eventDispatcher()=" << workerThread->eventDispatcher(); - qDebug() << "thread()->eventDispatcher()=" << thread()->eventDispatcher(); - } else { qDebug() << "Received an assignment that could not be unpacked. Re-requesting."; } From 9a63fa7550b168220290d7972d4ab000d588f501 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 21 Apr 2014 13:36:13 -0700 Subject: [PATCH 543/595] some cleanup --- assignment-client/src/octree/OctreeSendThread.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index 71dc819844..d8a9f3d1ea 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -32,23 +32,23 @@ OctreeSendThread::OctreeSendThread(const SharedAssignmentPointer& myAssignment, _nodeMissingCount(0), _isShuttingDown(false) { - QString serverName("Octree"); + QString safeServerName("Octree"); if (_myServer) { - serverName = _myServer->getMyServerName(); + safeServerName = _myServer->getMyServerName(); } - qDebug() << qPrintable(serverName) << "server [" << _myServer << "]: client connected " + qDebug() << qPrintable(safeServerName) << "server [" << _myServer << "]: client connected " "- starting sending thread [" << this << "]"; OctreeServer::clientConnected(); } OctreeSendThread::~OctreeSendThread() { - QString serverName("Octree"); + QString safeServerName("Octree"); if (_myServer) { - serverName = _myServer->getMyServerName(); + safeServerName = _myServer->getMyServerName(); } - qDebug() << qPrintable(serverName) << "server [" << _myServer << "]: client disconnected " + qDebug() << qPrintable(safeServerName) << "server [" << _myServer << "]: client disconnected " "- ending sending thread [" << this << "]"; OctreeServer::clientDisconnected(); From 06784aa960b46612dceed11a13a2398666012600 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Mon, 21 Apr 2014 14:07:40 -0700 Subject: [PATCH 544/595] move AABox back to octree lib Fleshing out ShapeCollider::collideShapeWithAACube() --- libraries/{shared => octree}/src/AABox.cpp | 0 libraries/{shared => octree}/src/AABox.h | 0 libraries/octree/src/Octree.cpp | 8 +-- libraries/octree/src/OctreeElement.cpp | 4 +- libraries/octree/src/OctreeElement.h | 2 +- libraries/octree/src/ViewFrustum.h | 3 +- libraries/shared/src/ShapeCollider.cpp | 80 +++++++++++++++++++++- libraries/shared/src/ShapeCollider.h | 22 ++++-- 8 files changed, 104 insertions(+), 15 deletions(-) rename libraries/{shared => octree}/src/AABox.cpp (100%) rename libraries/{shared => octree}/src/AABox.h (100%) diff --git a/libraries/shared/src/AABox.cpp b/libraries/octree/src/AABox.cpp similarity index 100% rename from libraries/shared/src/AABox.cpp rename to libraries/octree/src/AABox.cpp diff --git a/libraries/shared/src/AABox.h b/libraries/octree/src/AABox.h similarity index 100% rename from libraries/shared/src/AABox.h rename to libraries/octree/src/AABox.h diff --git a/libraries/octree/src/Octree.cpp b/libraries/octree/src/Octree.cpp index a06b8a41bb..83b84b3c50 100644 --- a/libraries/octree/src/Octree.cpp +++ b/libraries/octree/src/Octree.cpp @@ -710,16 +710,16 @@ bool findShapeCollisionsOp(OctreeElement* node, void* extraData) { const ShapeArgs* args = static_cast(extraData); // coarse check against bounds - AABox box = node->getAABox(); - box.scale(TREE_SCALE); - if (!box.expandedContains(args->shape->getPosition(), args->shape->getBoundingRadius())) { + AABox cube = node->getAABox(); + cube.scale(TREE_SCALE); + if (!cube.expandedContains(args->shape->getPosition(), args->shape->getBoundingRadius())) { return false; } if (!node->isLeaf()) { return true; // recurse on children } if (node->hasContent()) { - return ShapeCollider::collideShapeWithBox(args->shape, box, args->collisions); + return ShapeCollider::collideShapeWithAACube(args->shape, cube.calcCenter(), cube.getScale(), args->collisions); } return false; } diff --git a/libraries/octree/src/OctreeElement.cpp b/libraries/octree/src/OctreeElement.cpp index c951803247..7ca15eddb5 100644 --- a/libraries/octree/src/OctreeElement.cpp +++ b/libraries/octree/src/OctreeElement.cpp @@ -15,16 +15,16 @@ #include -#include #include #include #include +#include "AABox.h" #include "OctalCode.h" -#include "SharedUtil.h" #include "OctreeConstants.h" #include "OctreeElement.h" #include "Octree.h" +#include "SharedUtil.h" quint64 OctreeElement::_voxelMemoryUsage = 0; quint64 OctreeElement::_octcodeMemoryUsage = 0; diff --git a/libraries/octree/src/OctreeElement.h b/libraries/octree/src/OctreeElement.h index 15d5063818..c5eec1c9e2 100644 --- a/libraries/octree/src/OctreeElement.h +++ b/libraries/octree/src/OctreeElement.h @@ -18,9 +18,9 @@ #include -#include #include +#include "AABox.h" #include "ViewFrustum.h" #include "OctreeConstants.h" //#include "Octree.h" diff --git a/libraries/octree/src/ViewFrustum.h b/libraries/octree/src/ViewFrustum.h index 43812827f5..acd5c639f7 100644 --- a/libraries/octree/src/ViewFrustum.h +++ b/libraries/octree/src/ViewFrustum.h @@ -17,9 +17,8 @@ #include #include -#include +#include "AABox.h" #include "Plane.h" - #include "OctreeConstants.h" #include "OctreeProjectedPolygon.h" diff --git a/libraries/shared/src/ShapeCollider.cpp b/libraries/shared/src/ShapeCollider.cpp index 0eddc80c62..1b49caab22 100644 --- a/libraries/shared/src/ShapeCollider.cpp +++ b/libraries/shared/src/ShapeCollider.cpp @@ -92,8 +92,26 @@ bool collideShapesCoarse(const QVector& shapesA, const QVectorgetType(); + if (typeA == Shape::SPHERE_SHAPE) { + return sphereAACube(static_cast(shapeA), cubeCenter, cubeSide, collisions); + } else if (typeA == Shape::CAPSULE_SHAPE) { + return capsuleAACube(static_cast(shapeA), cubeCenter, cubeSide, collisions); + } else if (typeA == Shape::LIST_SHAPE) { + const ListShape* listA = static_cast(shapeA); + bool touching = false; + for (int i = 0; i < listA->size() && !collisions.isFull(); ++i) { + const Shape* subShape = listA->getSubShape(i); + int subType = subShape->getType(); + if (subType == Shape::SPHERE_SHAPE) { + touching = sphereAACube(static_cast(subShape), cubeCenter, cubeSide, collisions) || touching; + } else if (subType == Shape::CAPSULE_SHAPE) { + touching = capsuleAACube(static_cast(subShape), cubeCenter, cubeSide, collisions) || touching; + } + } + return touching; + } return false; } @@ -572,4 +590,62 @@ bool listList(const ListShape* listA, const ListShape* listB, CollisionList& col return touching; } +// helper function +bool sphereAACube(const glm::vec3& sphereCenter, float sphereRadius, const glm::vec3& cubeCenter, float cubeSide, CollisionList& collisions) { + glm::vec3 BA = cubeCenter - sphereCenter; + float distance = glm::length(BA); + if (distance > EPSILON) { + BA /= distance; // BA is now normalized + // compute the nearest point on sphere + glm::vec3 surfaceA = sphereCenter + sphereRadius * BA; + // compute the nearest point on cube + float maxBA = glm::max(glm::max(fabs(BA.x), fabs(BA.y)), fabs(BA.z)); + glm::vec3 surfaceB = cubeCenter - (0.5f * cubeSide / maxBA) * BA; + // collision happens when "vector to surfaceB from surfaceA" dots with BA to produce a positive value + glm::vec3 surfaceBA = surfaceB - surfaceA; + if (glm::dot(surfaceBA, BA) > 0.f) { + CollisionInfo* collision = collisions.getNewCollision(); + if (collision) { + collision->_penetration = surfaceBA; + // contactPoint is on surface of A + collision->_contactPoint = surfaceA; + return true; + } + } + } else if (sphereRadius + 0.5f * cubeSide > distance) { + // NOTE: for cocentric approximation we collide sphere and cube as two spheres which means + // this algorithm will probably be wrong when both sphere and cube are very small (both ~EPSILON) + CollisionInfo* collision = collisions.getNewCollision(); + if (collision) { + // the penetration and contactPoint are undefined, so we pick a penetration direction (-yAxis) + collision->_penetration = (sphereRadius + 0.5f * cubeSide) * glm::vec3(0.0f, -1.0f, 0.0f); + // contactPoint is on surface of A + collision->_contactPoint = sphereCenter + collision->_penetration; + return true; + } + } + return false; +} + +bool sphereAACube(const SphereShape* sphereA, const glm::vec3& cubeCenter, float cubeSide, CollisionList& collisions) { + return sphereAACube(sphereA->getPosition(), sphereA->getRadius(), cubeCenter, cubeSide, collisions); +} + +bool capsuleAACube(const CapsuleShape* capsuleA, const glm::vec3& cubeCenter, float cubeSide, CollisionList& collisions) { + // find nerest approach of capsule line segment to cube + glm::vec3 capsuleAxis; + capsuleA->computeNormalizedAxis(capsuleAxis); + float offset = glm::dot(cubeCenter - capsuleA->getPosition(), capsuleAxis); + float halfHeight = capsuleA->getHalfHeight(); + if (offset > halfHeight) { + offset = halfHeight; + } else if (offset < -halfHeight) { + offset = -halfHeight; + } + glm::vec3 nearestApproach = capsuleA->getPosition() + offset * capsuleAxis; + // collide nearest approach like a sphere at that point + return sphereAACube(nearestApproach, capsuleA->getRadius(), cubeCenter, cubeSide, collisions); +} + + } // namespace ShapeCollider diff --git a/libraries/shared/src/ShapeCollider.h b/libraries/shared/src/ShapeCollider.h index a020050662..9e83e31571 100644 --- a/libraries/shared/src/ShapeCollider.h +++ b/libraries/shared/src/ShapeCollider.h @@ -12,7 +12,6 @@ #ifndef hifi_ShapeCollider_h #define hifi_ShapeCollider_h -#include "AABox.h" #include "CapsuleShape.h" #include "CollisionInfo.h" #include "ListShape.h" @@ -35,10 +34,11 @@ namespace ShapeCollider { bool collideShapesCoarse(const QVector& shapesA, const QVector& shapesB, CollisionInfo& collision); /// \param shapeA a pointer to a shape - /// \param boxB an axis aligned box + /// \param cubeCenter center of cube + /// \param cubeSide lenght of side of cube /// \param collisions[out] average collision details - /// \return true if shapeA collides with boxB - bool collideShapeWithBox(const Shape* shapeA, const AABox& boxB, CollisionList& collisions); + /// \return true if shapeA collides with axis aligned cube + bool collideShapeWithAACube(const Shape* shapeA, const glm::vec3& cubeCenter, float cubeSide, CollisionList& collisions); /// \param sphereA pointer to first shape /// \param sphereB pointer to second shape @@ -136,6 +136,20 @@ namespace ShapeCollider { /// \return true if shapes collide bool listList(const ListShape* listA, const ListShape* listB, CollisionList& collisions); + /// \param sphereA pointer to sphere + /// \param cubeCenter center of cube + /// \param cubeSide lenght of side of cube + /// \param[out] collisions where to append collision details + /// \return true if sphereA collides with axis aligned cube + bool sphereAACube(const SphereShape* sphereA, const glm::vec3& cubeCenter, float cubeSide, CollisionList& collisions); + + /// \param capsuleA pointer to capsule + /// \param cubeCenter center of cube + /// \param cubeSide lenght of side of cube + /// \param[out] collisions where to append collision details + /// \return true if capsuleA collides with axis aligned cube + bool capsuleAACube(const CapsuleShape* capsuleA, const glm::vec3& cubeCenter, float cubeSide, CollisionList& collisions); + } // namespace ShapeCollider #endif // hifi_ShapeCollider_h From 75f079e2b37a8162a697c7578d18e4b0e9593c75 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 21 Apr 2014 14:15:13 -0700 Subject: [PATCH 545/595] tweak debugging --- assignment-client/src/octree/OctreeServer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index a73701d695..cf0cf725a9 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -956,7 +956,7 @@ void OctreeServer::readPendingDatagrams() { } } quint64 endReadAvailable = usecTimestampNow(); - if (endReadAvailable - startReadAvailable > 1000) { + if (endReadAvailable - startReadAvailable > 500000) { qDebug() << "OctreeServer::readPendingDatagrams(): while(readAvailable) took" << (endReadAvailable - startReadAvailable) << "usecs" << " readDataGrams=" << readDataGrams << " nodeListPackets=" << nodeListPackets From 7a8a8e2fac32cf5dfc173f31438f266b1b573f55 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 21 Apr 2014 15:14:06 -0700 Subject: [PATCH 546/595] delete tree on server shutdown --- assignment-client/src/octree/OctreeServer.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index cf0cf725a9..4f435cd371 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -298,6 +298,12 @@ OctreeServer::~OctreeServer() { delete _jurisdiction; _jurisdiction = NULL; + // cleanup our tree here... + qDebug() << qPrintable(_safeServerName) << "server cleaning up octree... [" << this << "]"; + delete _tree; + _tree = NULL; + qDebug() << qPrintable(_safeServerName) << "server DONE cleaning up octree... [" << this << "]"; + if (_instance == this) { _instance = NULL; // we are gone } From a473fe3aee736e0e282e5cd5eb83459d902c81ae Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 21 Apr 2014 15:14:14 -0700 Subject: [PATCH 547/595] fix header --- examples/testingVoxelViewerRestart.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/testingVoxelViewerRestart.js b/examples/testingVoxelViewerRestart.js index 309f970cd8..4fbdee1223 100644 --- a/examples/testingVoxelViewerRestart.js +++ b/examples/testingVoxelViewerRestart.js @@ -1,5 +1,5 @@ // -// seeingVoxelsExample.js +// testingVoxelSeeingRestart.js // hifi // // Created by Brad Hefta-Gaub on 2/26/14 From f7f30e118c4f1b36178a3e0d4f4bd603f4519221 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 21 Apr 2014 15:17:11 -0700 Subject: [PATCH 548/595] More gettimeofday cleanup --- interface/src/Application.cpp | 27 ++++----- interface/src/Application.h | 8 +-- interface/src/Util.cpp | 47 +++++---------- interface/src/Util.h | 2 - interface/src/main.cpp | 6 +- interface/src/starfield/Controller.cpp | 10 ++-- interface/src/starfield/Generator.cpp | 9 ++- interface/src/ui/BandwidthMeter.cpp | 13 ++--- interface/src/ui/BandwidthMeter.h | 4 +- libraries/script-engine/src/ScriptEngine.cpp | 6 +- libraries/shared/src/SharedUtil.cpp | 4 -- libraries/shared/src/SharedUtil.h | 1 - libraries/shared/src/Systime.cpp | 61 -------------------- libraries/shared/src/Systime.h | 27 --------- 14 files changed, 57 insertions(+), 168 deletions(-) delete mode 100644 libraries/shared/src/Systime.cpp delete mode 100644 libraries/shared/src/Systime.h diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index cd07f21300..92c63dacf3 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -134,7 +134,7 @@ QString& Application::resourcesPath() { return staticResourcePath; } -Application::Application(int& argc, char** argv, timeval &startup_time) : +Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : QApplication(argc, argv), _window(new QMainWindow(desktop())), _glWidget(new GLCanvas()), @@ -507,7 +507,7 @@ void Application::initializeGL() { _idleLoopStdev.reset(); if (_justStarted) { - float startupTime = (usecTimestampNow() - usecTimestamp(&_applicationStartupTime)) / 1000000.0; + float startupTime = _applicationStartupTime.elapsed() / 1000.0; _justStarted = false; qDebug("Startup time: %4.2f seconds.", startupTime); const char LOGSTASH_INTERFACE_START_TIME_KEY[] = "interface-start-time"; @@ -1273,21 +1273,21 @@ void Application::sendPingPackets() { // Every second, check the frame rates and other stuff void Application::timer() { - gettimeofday(&_timerEnd, NULL); - if (Menu::getInstance()->isOptionChecked(MenuOption::TestPing)) { sendPingPackets(); } + + float diffTime = (float)_timerStart.nsecsElapsed() / 1000000000.0; - _fps = (float)_frameCount / ((float)diffclock(&_timerStart, &_timerEnd) / 1000.f); + _fps = (float)_frameCount / diffTime; - _packetsPerSecond = (float) _datagramProcessor.getPacketCount() / ((float)diffclock(&_timerStart, &_timerEnd) / 1000.f); - _bytesPerSecond = (float) _datagramProcessor.getByteCount() / ((float)diffclock(&_timerStart, &_timerEnd) / 1000.f); + _packetsPerSecond = (float) _datagramProcessor.getPacketCount() / diffTime; + _bytesPerSecond = (float) _datagramProcessor.getByteCount() / diffTime; _frameCount = 0; _datagramProcessor.resetCounters(); - gettimeofday(&_timerStart, NULL); + _timerStart.start(); // ask the node list to check in with the domain server NodeList::getInstance()->sendDomainServerCheckIn(); @@ -1300,13 +1300,11 @@ void Application::idle() { bool showWarnings = getLogger()->extraDebugging(); PerformanceWarning warn(showWarnings, "Application::idle()"); - timeval check; - gettimeofday(&check, NULL); - // Only run simulation code if more than IDLE_SIMULATE_MSECS have passed since last time we ran - double timeSinceLastUpdate = diffclock(&_lastTimeUpdated, &check); + double timeSinceLastUpdate = (double)_lastTimeUpdated.nsecsElapsed() / 1000000.0; if (timeSinceLastUpdate > IDLE_SIMULATE_MSECS) { + _lastTimeUpdated.start(); { PerformanceWarning warn(showWarnings, "Application::idle()... update()"); const float BIGGEST_DELTA_TIME_SECS = 0.25f; @@ -1318,7 +1316,6 @@ void Application::idle() { } { PerformanceWarning warn(showWarnings, "Application::idle()... rest of it"); - _lastTimeUpdated = check; _idleLoopStdev.addValue(timeSinceLastUpdate); // Record standard deviation and reset counter if needed @@ -1634,8 +1631,8 @@ void Application::init() { Qt::QueuedConnection); } - gettimeofday(&_timerStart, NULL); - gettimeofday(&_lastTimeUpdated, NULL); + _timerStart.start(); + _lastTimeUpdated.start(); Menu::getInstance()->loadSettings(); if (Menu::getInstance()->getAudioJitterBufferSamples() != 0) { diff --git a/interface/src/Application.h b/interface/src/Application.h index 9d609ad5f5..36758a26db 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -117,7 +117,7 @@ public: static Application* getInstance() { return static_cast(QCoreApplication::instance()); } static QString& resourcesPath(); - Application(int& argc, char** argv, timeval &startup_time); + Application(int& argc, char** argv, QElapsedTimer &startup_time); ~Application(); void restoreSizeAndPosition(); @@ -391,9 +391,9 @@ private: int _frameCount; float _fps; - timeval _applicationStartupTime; - timeval _timerStart, _timerEnd; - timeval _lastTimeUpdated; + QElapsedTimer _applicationStartupTime; + QElapsedTimer _timerStart; + QElapsedTimer _lastTimeUpdated; bool _justStarted; Stars _stars; diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 1dae3a4fd6..9dfe9d8002 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -172,14 +172,6 @@ void renderWorldBox() { } -double diffclock(timeval *clock1,timeval *clock2) -{ - double diffms = (clock2->tv_sec - clock1->tv_sec) * 1000.0; - diffms += (clock2->tv_usec - clock1->tv_usec) / 1000.0; // us to ms - - return diffms; -} - // Return a random vector of average length 1 const glm::vec3 randVector() { return glm::vec3(randFloat() - 0.5f, randFloat() - 0.5f, randFloat() - 0.5f) * 2.f; @@ -411,68 +403,61 @@ void runTimingTests() { int iResults[numTests]; float fTest = 1.0; float fResults[numTests]; - timeval startTime, endTime; + QElapsedTimer startTime; + startTime.start(); float elapsedMsecs; - gettimeofday(&startTime, NULL); - for (int i = 1; i < numTests; i++) { - gettimeofday(&endTime, NULL); - } - elapsedMsecs = diffclock(&startTime, &endTime); - qDebug("gettimeofday() usecs: %f", 1000.0f * elapsedMsecs / (float) numTests); + + elapsedMsecs = (float)startTime.nsecsElapsed() / 1000.0; + qDebug("QElapsedTimer::nsecElapsed() usecs: %f", 1000.0f * elapsedMsecs / (float) numTests); // Random number generation - gettimeofday(&startTime, NULL); + startTime.start(); for (int i = 1; i < numTests; i++) { iResults[i] = rand(); } - gettimeofday(&endTime, NULL); - elapsedMsecs = diffclock(&startTime, &endTime); + elapsedMsecs = (float)startTime.nsecsElapsed() / 1000.0; qDebug("rand() stored in array usecs: %f, first result:%d", 1000.0f * elapsedMsecs / (float) numTests, iResults[0]); // Random number generation using randFloat() - gettimeofday(&startTime, NULL); + startTime.start(); for (int i = 1; i < numTests; i++) { fResults[i] = randFloat(); } - gettimeofday(&endTime, NULL); - elapsedMsecs = diffclock(&startTime, &endTime); + elapsedMsecs = (float)startTime.nsecsElapsed() / 1000.0; qDebug("randFloat() stored in array usecs: %f, first result: %f", 1000.0f * elapsedMsecs / (float) numTests, fResults[0]); // PowF function fTest = 1145323.2342f; - gettimeofday(&startTime, NULL); + startTime.start(); for (int i = 1; i < numTests; i++) { fTest = powf(fTest, 0.5f); } - gettimeofday(&endTime, NULL); - elapsedMsecs = diffclock(&startTime, &endTime); + elapsedMsecs = (float)startTime.nsecsElapsed() / 1000.0; qDebug("powf(f, 0.5) usecs: %f", 1000.0f * elapsedMsecs / (float) numTests); // Vector Math float distance; glm::vec3 pointA(randVector()), pointB(randVector()); - gettimeofday(&startTime, NULL); + startTime.start(); for (int i = 1; i < numTests; i++) { //glm::vec3 temp = pointA - pointB; //float distanceSquared = glm::dot(temp, temp); distance = glm::distance(pointA, pointB); } - gettimeofday(&endTime, NULL); - elapsedMsecs = diffclock(&startTime, &endTime); + elapsedMsecs = (float)startTime.nsecsElapsed() / 1000.0; qDebug("vector math usecs: %f [%f msecs total for %d tests], last result:%f", 1000.0f * elapsedMsecs / (float) numTests, elapsedMsecs, numTests, distance); // Vec3 test glm::vec3 vecA(randVector()), vecB(randVector()); float result; - - gettimeofday(&startTime, NULL); + + startTime.start(); for (int i = 1; i < numTests; i++) { glm::vec3 temp = vecA-vecB; result = glm::dot(temp,temp); } - gettimeofday(&endTime, NULL); - elapsedMsecs = diffclock(&startTime, &endTime); + elapsedMsecs = (float)startTime.nsecsElapsed() / 1000.0; qDebug("vec3 assign and dot() usecs: %f, last result:%f", 1000.0f * elapsedMsecs / (float) numTests, result); } diff --git a/interface/src/Util.h b/interface/src/Util.h index 4bd1ed604c..dee0f864b4 100644 --- a/interface/src/Util.h +++ b/interface/src/Util.h @@ -44,8 +44,6 @@ void drawVector(glm::vec3* vector); void printVector(glm::vec3 vec); -double diffclock(timeval *clock1,timeval *clock2); - void renderCollisionOverlay(int width, int height, float magnitude, float red = 0, float blue = 0, float green = 0); void renderOrientationDirections( glm::vec3 position, const glm::quat& orientation, float size ); diff --git a/interface/src/main.cpp b/interface/src/main.cpp index 40e2a9ab27..2bb0633f24 100644 --- a/interface/src/main.cpp +++ b/interface/src/main.cpp @@ -16,8 +16,8 @@ #include int main(int argc, const char * argv[]) { - timeval startup_time; - gettimeofday(&startup_time, NULL); + QElapsedTimer startupTime; + startupTime.start(); // Debug option to demonstrate that the client's local time does not // need to be in sync with any other network node. This forces clock @@ -33,7 +33,7 @@ int main(int argc, const char * argv[]) { int exitCode; { QSettings::setDefaultFormat(QSettings::IniFormat); - Application app(argc, const_cast(argv), startup_time); + Application app(argc, const_cast(argv), startupTime); QTranslator translator; translator.load("interface_en"); diff --git a/interface/src/starfield/Controller.cpp b/interface/src/starfield/Controller.cpp index 771029c689..2476c33d45 100755 --- a/interface/src/starfield/Controller.cpp +++ b/interface/src/starfield/Controller.cpp @@ -13,20 +13,22 @@ #include #endif +#include + #include "starfield/Controller.h" using namespace starfield; bool Controller::computeStars(unsigned numStars, unsigned seed) { - timeval startTime; - gettimeofday(&startTime, NULL); + QElapsedTimer startTime; + startTime.start(); Generator::computeStarPositions(_inputSequence, numStars, seed); this->retile(numStars, _tileResolution); - qDebug() << "Total time to retile and generate stars: " - << ((usecTimestampNow() - usecTimestamp(&startTime)) / 1000) << "msec"; + double timeDiff = (double)startTime.nsecsElapsed() / 1000000.0; // ns to ms + qDebug() << "Total time to retile and generate stars: " << timeDiff << "msec"; return true; } diff --git a/interface/src/starfield/Generator.cpp b/interface/src/starfield/Generator.cpp index b18e1834be..869abc90a5 100644 --- a/interface/src/starfield/Generator.cpp +++ b/interface/src/starfield/Generator.cpp @@ -13,6 +13,8 @@ #include #endif +#include + #include "starfield/Generator.h" using namespace starfield; @@ -24,8 +26,8 @@ void Generator::computeStarPositions(InputVertices& destination, unsigned limit, InputVertices* vertices = & destination; //_limit = limit; - timeval startTime; - gettimeofday(&startTime, NULL); + QElapsedTimer startTime; + startTime.start(); srand(seed); @@ -70,7 +72,8 @@ void Generator::computeStarPositions(InputVertices& destination, unsigned limit, vertices->push_back(InputVertex(azimuth, altitude, computeStarColor(STAR_COLORIZATION))); } - qDebug() << "Total time to generate stars: " << ((usecTimestampNow() - usecTimestamp(&startTime)) / 1000) << " msec"; + double timeDiff = (double)startTime.nsecsElapsed() / 1000000.0; // ns to ms + qDebug() << "Total time to generate stars: " << timeDiff << " msec"; } // computeStarColor diff --git a/interface/src/ui/BandwidthMeter.cpp b/interface/src/ui/BandwidthMeter.cpp index 3ed66c53e1..0f41a1a5cf 100644 --- a/interface/src/ui/BandwidthMeter.cpp +++ b/interface/src/ui/BandwidthMeter.cpp @@ -62,26 +62,21 @@ BandwidthMeter::~BandwidthMeter() { free(_channels); } -BandwidthMeter::Stream::Stream(float msToAverage) : - _value(0.0f), - _msToAverage(msToAverage) { - - gettimeofday(& _prevTime, NULL); +BandwidthMeter::Stream::Stream(float msToAverage) : _value(0.0f), _msToAverage(msToAverage) { + _prevTime.start(); } void BandwidthMeter::Stream::updateValue(double amount) { // Determine elapsed time - timeval now; - gettimeofday(& now, NULL); - double dt = diffclock(& _prevTime, & now); + double dt = (double)_prevTime.nsecsElapsed() / 1000000.0; // ns to ms // Ignore this value when timer imprecision yields dt = 0 if (dt == 0.0) { return; } - memcpy(& _prevTime, & now, sizeof(timeval)); + _prevTime.start(); // Compute approximate average _value = glm::mix(_value, amount / dt, diff --git a/interface/src/ui/BandwidthMeter.h b/interface/src/ui/BandwidthMeter.h index 6838f28c70..6cf7e9ea63 100644 --- a/interface/src/ui/BandwidthMeter.h +++ b/interface/src/ui/BandwidthMeter.h @@ -16,6 +16,8 @@ #include #endif +#include + #include #include "ui/TextRenderer.h" @@ -59,7 +61,7 @@ public: private: double _value; // Current value. double _msToAverage; // Milliseconds to average. - timeval _prevTime; // Time of last feed. + QElapsedTimer _prevTime; // Time of last feed. }; // Data model accessors diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index 684c55fbb0..dcf64dfe2c 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -273,8 +273,8 @@ void ScriptEngine::run() { qDebug() << "Uncaught exception at line" << line << ":" << result.toString(); } - timeval startTime; - gettimeofday(&startTime, NULL); + QElapsedTimer startTime; + startTime.start(); int thisFrame = 0; @@ -283,7 +283,7 @@ void ScriptEngine::run() { qint64 lastUpdate = usecTimestampNow(); while (!_isFinished) { - int usecToSleep = usecTimestamp(&startTime) + (thisFrame++ * SCRIPT_DATA_CALLBACK_USECS) - usecTimestampNow(); + int usecToSleep = (thisFrame++ * SCRIPT_DATA_CALLBACK_USECS) - startTime.nsecsElapsed() / 1000; // nsec to usec if (usecToSleep > 0) { usleep(usecToSleep); } diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index f4e4b28f93..dca9426cb4 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -24,10 +24,6 @@ #include "OctalCode.h" #include "SharedUtil.h" -quint64 usecTimestamp(const timeval *time) { - return (time->tv_sec * 1000000 + time->tv_usec); -} - int usecTimestampNowAdjust = 0; void usecTimestampNowForceClockSkew(int clockSkew) { ::usecTimestampNowAdjust = clockSkew; diff --git a/libraries/shared/src/SharedUtil.h b/libraries/shared/src/SharedUtil.h index a8403d617c..87647a9e73 100644 --- a/libraries/shared/src/SharedUtil.h +++ b/libraries/shared/src/SharedUtil.h @@ -66,7 +66,6 @@ static const quint64 USECS_PER_SECOND = USECS_PER_MSEC * MSECS_PER_SECOND; const int BITS_IN_BYTE = 8; -quint64 usecTimestamp(const timeval *time); quint64 usecTimestampNow(); void usecTimestampNowForceClockSkew(int clockSkew); diff --git a/libraries/shared/src/Systime.cpp b/libraries/shared/src/Systime.cpp deleted file mode 100644 index ab32821a0f..0000000000 --- a/libraries/shared/src/Systime.cpp +++ /dev/null @@ -1,61 +0,0 @@ -// -// Systime.cpp -// libraries/shared/src -// -// Copyright 2013 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#ifdef WIN32 - -#include "Systime.h" - -/** - * gettimeofday - * Implementation according to: - * The Open Group Base Specifications Issue 6 - * IEEE Std 1003.1, 2004 Edition - */ - -/** - * THIS SOFTWARE IS NOT COPYRIGHTED - * - * This source code is offered for use in the public domain. You may - * use, modify or distribute it freely. - * - * This code is distributed in the hope that it will be useful but - * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY - * DISCLAIMED. This includes but is not limited to warranties of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * Contributed by: - * Danny Smith - */ - -#define WIN32_LEAN_AND_MEAN -#include - -/** Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */ -#define _W32_FT_OFFSET (116444736000000000ULL) - -int gettimeofday(timeval* p_tv, timezone* p_tz) { - - union { - unsigned long long ns100; /**time since 1 Jan 1601 in 100ns units */ - FILETIME ft; - } _now; - - if (p_tv) { - GetSystemTimeAsFileTime (&_now.ft); - p_tv->tv_usec=(long)((_now.ns100 / 10ULL) % 1000000ULL ); - p_tv->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000ULL); - } - - /** Always return 0 as per Open Group Base Specifications Issue 6. - Do not set errno on error. */ - return 0; -} - -#endif \ No newline at end of file diff --git a/libraries/shared/src/Systime.h b/libraries/shared/src/Systime.h deleted file mode 100644 index 3098f09ecd..0000000000 --- a/libraries/shared/src/Systime.h +++ /dev/null @@ -1,27 +0,0 @@ -// -// Systime.h -// libraries/shared/src -// -// Copyright 2013 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#ifndef hifi_Systime_h -#define hifi_Systime_h - -#ifdef WIN32 - -#include - -struct timezone { - int tz_minuteswest; /* minutes west of Greenwich */ - int tz_dsttime; /* type of dst correction */ -}; - -int gettimeofday(struct timeval* p_tv, struct timezone* p_tz); - -#endif - -#endif // hifi_Systime_h \ No newline at end of file From 0479aaba4651594b760979f0ed460665234d7f1e Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 21 Apr 2014 15:26:43 -0700 Subject: [PATCH 549/595] Some gettimeofday removal fixes --- interface/src/Application.cpp | 2 +- interface/src/Util.cpp | 28 ++++++++++++++-------------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 92c63dacf3..b13013cbe2 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -507,7 +507,7 @@ void Application::initializeGL() { _idleLoopStdev.reset(); if (_justStarted) { - float startupTime = _applicationStartupTime.elapsed() / 1000.0; + float startupTime = (float)_applicationStartupTime.elapsed() / 1000.0; _justStarted = false; qDebug("Startup time: %4.2f seconds.", startupTime); const char LOGSTASH_INTERFACE_START_TIME_KEY[] = "interface-start-time"; diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 9dfe9d8002..7913ff2f47 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -405,26 +405,26 @@ void runTimingTests() { float fResults[numTests]; QElapsedTimer startTime; startTime.start(); - float elapsedMsecs; + float elapsedUsecs; - elapsedMsecs = (float)startTime.nsecsElapsed() / 1000.0; - qDebug("QElapsedTimer::nsecElapsed() usecs: %f", 1000.0f * elapsedMsecs / (float) numTests); + elapsedUsecs = (float)startTime.nsecsElapsed() / 1000.0; + qDebug("QElapsedTimer::nsecElapsed() usecs: %f", 1000.0f * elapsedUsecs / (float) numTests); // Random number generation startTime.start(); for (int i = 1; i < numTests; i++) { iResults[i] = rand(); } - elapsedMsecs = (float)startTime.nsecsElapsed() / 1000.0; - qDebug("rand() stored in array usecs: %f, first result:%d", 1000.0f * elapsedMsecs / (float) numTests, iResults[0]); + elapsedUsecs = (float)startTime.nsecsElapsed() / 1000.0; + qDebug("rand() stored in array usecs: %f, first result:%d", 1000.0f * elapsedUsecs / (float) numTests, iResults[0]); // Random number generation using randFloat() startTime.start(); for (int i = 1; i < numTests; i++) { fResults[i] = randFloat(); } - elapsedMsecs = (float)startTime.nsecsElapsed() / 1000.0; - qDebug("randFloat() stored in array usecs: %f, first result: %f", 1000.0f * elapsedMsecs / (float) numTests, fResults[0]); + elapsedUsecs = (float)startTime.nsecsElapsed() / 1000.0; + qDebug("randFloat() stored in array usecs: %f, first result: %f", 1000.0f * elapsedUsecs / (float) numTests, fResults[0]); // PowF function fTest = 1145323.2342f; @@ -432,8 +432,8 @@ void runTimingTests() { for (int i = 1; i < numTests; i++) { fTest = powf(fTest, 0.5f); } - elapsedMsecs = (float)startTime.nsecsElapsed() / 1000.0; - qDebug("powf(f, 0.5) usecs: %f", 1000.0f * elapsedMsecs / (float) numTests); + elapsedUsecs = (float)startTime.nsecsElapsed() / 1000.0; + qDebug("powf(f, 0.5) usecs: %f", 1000.0f * elapsedUsecs / (float) numTests); // Vector Math float distance; @@ -444,9 +444,9 @@ void runTimingTests() { //float distanceSquared = glm::dot(temp, temp); distance = glm::distance(pointA, pointB); } - elapsedMsecs = (float)startTime.nsecsElapsed() / 1000.0; - qDebug("vector math usecs: %f [%f msecs total for %d tests], last result:%f", - 1000.0f * elapsedMsecs / (float) numTests, elapsedMsecs, numTests, distance); + elapsedUsecs = (float)startTime.nsecsElapsed() / 1000.0; + qDebug("vector math usecs: %f [%f usecs total for %d tests], last result:%f", + 1000.0f * elapsedUsecs / (float) numTests, elapsedUsecs, numTests, distance); // Vec3 test glm::vec3 vecA(randVector()), vecB(randVector()); @@ -457,8 +457,8 @@ void runTimingTests() { glm::vec3 temp = vecA-vecB; result = glm::dot(temp,temp); } - elapsedMsecs = (float)startTime.nsecsElapsed() / 1000.0; - qDebug("vec3 assign and dot() usecs: %f, last result:%f", 1000.0f * elapsedMsecs / (float) numTests, result); + elapsedUsecs = (float)startTime.nsecsElapsed() / 1000.0; + qDebug("vec3 assign and dot() usecs: %f, last result:%f", 1000.0f * elapsedUsecs / (float) numTests, result); } float loadSetting(QSettings* settings, const char* name, float defaultValue) { From 779b5a682775131c738e0703eb09a97f50c3c365 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 21 Apr 2014 15:32:44 -0700 Subject: [PATCH 550/595] debug --- libraries/octree/src/OctreeElementBag.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries/octree/src/OctreeElementBag.cpp b/libraries/octree/src/OctreeElementBag.cpp index f929980a75..9f63b5b071 100644 --- a/libraries/octree/src/OctreeElementBag.cpp +++ b/libraries/octree/src/OctreeElementBag.cpp @@ -24,6 +24,7 @@ OctreeElementBag::~OctreeElementBag() { } void OctreeElementBag::elementDeleted(OctreeElement* element) { +qDebug() << "OctreeElementBag::elementDeleted()..."; remove(element); // note: remove can safely handle nodes that aren't in it, so we don't need to check contains() } From f3aa9d3b8fad2a1dc6d1a5d0de179c0d5e40c3b1 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 21 Apr 2014 15:45:12 -0700 Subject: [PATCH 551/595] unhook node bag from element notifications on shutdown to speed up cleanup --- assignment-client/src/octree/OctreeQueryNode.cpp | 1 + libraries/octree/src/OctreeElementBag.cpp | 9 ++++++++- libraries/octree/src/OctreeElementBag.h | 3 +++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/assignment-client/src/octree/OctreeQueryNode.cpp b/assignment-client/src/octree/OctreeQueryNode.cpp index 5c882fd032..dfaf641753 100644 --- a/assignment-client/src/octree/OctreeQueryNode.cpp +++ b/assignment-client/src/octree/OctreeQueryNode.cpp @@ -62,6 +62,7 @@ void OctreeQueryNode::nodeKilled() { // while the thread actually shuts down _octreeSendThread->setIsShuttingDown(); } + nodeBag.unhookNotifications(); // if our node is shutting down, then we no longer need octree element notifications } void OctreeQueryNode::forceNodeShutdown() { diff --git a/libraries/octree/src/OctreeElementBag.cpp b/libraries/octree/src/OctreeElementBag.cpp index 9f63b5b071..d4084101cb 100644 --- a/libraries/octree/src/OctreeElementBag.cpp +++ b/libraries/octree/src/OctreeElementBag.cpp @@ -16,13 +16,20 @@ OctreeElementBag::OctreeElementBag() : _bagElements() { OctreeElement::addDeleteHook(this); + _hooked = true; }; OctreeElementBag::~OctreeElementBag() { - OctreeElement::removeDeleteHook(this); + unhookNotifications(); deleteAll(); } +void OctreeElementBag::unhookNotifications() { + if (_hooked) { + OctreeElement::removeDeleteHook(this); + } +} + void OctreeElementBag::elementDeleted(OctreeElement* element) { qDebug() << "OctreeElementBag::elementDeleted()..."; remove(element); // note: remove can safely handle nodes that aren't in it, so we don't need to check contains() diff --git a/libraries/octree/src/OctreeElementBag.h b/libraries/octree/src/OctreeElementBag.h index afc34bf1a6..8c18ece773 100644 --- a/libraries/octree/src/OctreeElementBag.h +++ b/libraries/octree/src/OctreeElementBag.h @@ -36,8 +36,11 @@ public: void deleteAll(); virtual void elementDeleted(OctreeElement* element); + void unhookNotifications(); + private: QSet _bagElements; + bool _hooked; }; #endif // hifi_OctreeElementBag_h From 003e3ae507d96761b048720e3afc1875e5f4f39e Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 21 Apr 2014 16:01:37 -0700 Subject: [PATCH 552/595] properly unhook delete notifications --- assignment-client/src/octree/OctreeQueryNode.cpp | 3 ++- libraries/octree/src/OctreeElementBag.cpp | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/assignment-client/src/octree/OctreeQueryNode.cpp b/assignment-client/src/octree/OctreeQueryNode.cpp index dfaf641753..10d30ad1ae 100644 --- a/assignment-client/src/octree/OctreeQueryNode.cpp +++ b/assignment-client/src/octree/OctreeQueryNode.cpp @@ -57,16 +57,17 @@ OctreeQueryNode::~OctreeQueryNode() { void OctreeQueryNode::nodeKilled() { _isShuttingDown = true; + nodeBag.unhookNotifications(); // if our node is shutting down, then we no longer need octree element notifications if (_octreeSendThread) { // just tell our thread we want to shutdown, this is asynchronous, and fast, we don't need or want it to block // while the thread actually shuts down _octreeSendThread->setIsShuttingDown(); } - nodeBag.unhookNotifications(); // if our node is shutting down, then we no longer need octree element notifications } void OctreeQueryNode::forceNodeShutdown() { _isShuttingDown = true; + nodeBag.unhookNotifications(); // if our node is shutting down, then we no longer need octree element notifications if (_octreeSendThread) { // we really need to force our thread to shutdown, this is synchronous, we will block while the thread actually // shuts down because we really need it to shutdown, and it's ok if we wait for it to complete diff --git a/libraries/octree/src/OctreeElementBag.cpp b/libraries/octree/src/OctreeElementBag.cpp index d4084101cb..92a8fe5bff 100644 --- a/libraries/octree/src/OctreeElementBag.cpp +++ b/libraries/octree/src/OctreeElementBag.cpp @@ -27,11 +27,11 @@ OctreeElementBag::~OctreeElementBag() { void OctreeElementBag::unhookNotifications() { if (_hooked) { OctreeElement::removeDeleteHook(this); + _hooked = false; } } void OctreeElementBag::elementDeleted(OctreeElement* element) { -qDebug() << "OctreeElementBag::elementDeleted()..."; remove(element); // note: remove can safely handle nodes that aren't in it, so we don't need to check contains() } From 681aab5bf036a75383918a6822f1f01f9277e3b3 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 21 Apr 2014 16:17:45 -0700 Subject: [PATCH 553/595] Remove printf and replace them by qDebug() --- animation-server/src/AnimationServer.cpp | 36 +++++++++---------- .../octree/OctreeInboundPacketProcessor.cpp | 10 +++--- assignment-client/src/octree/OctreeServer.cpp | 18 +++++----- interface/src/Application.cpp | 6 ++-- interface/src/DatagramProcessor.cpp | 2 +- interface/src/Util.cpp | 2 +- interface/src/avatar/MyAvatar.cpp | 2 +- interface/src/devices/SixenseManager.cpp | 2 +- interface/src/voxels/VoxelSystem.cpp | 2 +- libraries/networking/src/Logging.cpp | 2 +- libraries/octree/src/Octree.cpp | 10 +++--- libraries/octree/src/Octree.h | 20 +++++------ .../octree/src/OctreeEditPacketSender.cpp | 4 +-- libraries/octree/src/OctreeElement.cpp | 4 +-- libraries/octree/src/OctreePacketData.cpp | 14 ++++---- .../octree/src/OctreeProjectedPolygon.cpp | 8 ++--- libraries/octree/src/Plane.cpp | 4 ++- libraries/particles/src/Particle.cpp | 28 +++++++-------- .../particles/src/ParticleTreeElement.cpp | 6 ++-- voxel-edit/src/SceneUtils.cpp | 8 ++--- 20 files changed, 95 insertions(+), 93 deletions(-) diff --git a/animation-server/src/AnimationServer.cpp b/animation-server/src/AnimationServer.cpp index ffb98b4ae0..32a95b48ea 100644 --- a/animation-server/src/AnimationServer.cpp +++ b/animation-server/src/AnimationServer.cpp @@ -171,7 +171,7 @@ static void renderMovingBug() { } } else { - //printf("bugPathCenter=(%f,%f,%f)\n", bugPathCenter.x, bugPathCenter.y, bugPathCenter.z); + //qDebug("bugPathCenter=(%f,%f,%f)", bugPathCenter.x, bugPathCenter.y, bugPathCenter.z); bugPathTheta += bugAngleDelta; // move slightly bugRotation -= bugAngleDelta; // rotate slightly @@ -187,12 +187,12 @@ static void renderMovingBug() { float y = bugPathCenter.y; bugPosition = glm::vec3(x, y, z); - //printf("bugPathTheta=%f\n", bugPathTheta); - //printf("bugRotation=%f\n", bugRotation); + //qDebug("bugPathTheta=%f", bugPathTheta); + //qDebug("bugRotation=%f", bugRotation); } - //printf("bugPosition=(%f,%f,%f)\n", bugPosition.x, bugPosition.y, bugPosition.z); - //printf("bugDirection=(%f,%f,%f)\n", bugDirection.x, bugDirection.y, bugDirection.z); + //qDebug("bugPosition=(%f,%f,%f)", bugPosition.x, bugPosition.y, bugPosition.z); + //qDebug("bugDirection=(%f,%f,%f)", bugDirection.x, bugDirection.y, bugDirection.z); // would be nice to add some randomness here... // Generate voxels for where bug is going to @@ -690,32 +690,32 @@ AnimationServer::AnimationServer(int &argc, char **argv) : // Handle Local Domain testing with the --local command line const char* NON_THREADED_PACKETSENDER = "--NonThreadedPacketSender"; ::nonThreadedPacketSender = cmdOptionExists(argc, (const char**) argv, NON_THREADED_PACKETSENDER); - printf("nonThreadedPacketSender=%s\n", debug::valueOf(::nonThreadedPacketSender)); + qDebug("nonThreadedPacketSender=%s", debug::valueOf(::nonThreadedPacketSender)); // Handle Local Domain testing with the --local command line const char* NO_BILLBOARD = "--NoBillboard"; ::includeBillboard = !cmdOptionExists(argc, (const char**) argv, NO_BILLBOARD); - printf("includeBillboard=%s\n", debug::valueOf(::includeBillboard)); + qDebug("includeBillboard=%s", debug::valueOf(::includeBillboard)); const char* NO_BORDER_TRACER = "--NoBorderTracer"; ::includeBorderTracer = !cmdOptionExists(argc, (const char**) argv, NO_BORDER_TRACER); - printf("includeBorderTracer=%s\n", debug::valueOf(::includeBorderTracer)); + qDebug("includeBorderTracer=%s", debug::valueOf(::includeBorderTracer)); const char* NO_MOVING_BUG = "--NoMovingBug"; ::includeMovingBug = !cmdOptionExists(argc, (const char**) argv, NO_MOVING_BUG); - printf("includeMovingBug=%s\n", debug::valueOf(::includeMovingBug)); + qDebug("includeMovingBug=%s", debug::valueOf(::includeMovingBug)); const char* INCLUDE_BLINKING_VOXEL = "--includeBlinkingVoxel"; ::includeBlinkingVoxel = cmdOptionExists(argc, (const char**) argv, INCLUDE_BLINKING_VOXEL); - printf("includeBlinkingVoxel=%s\n", debug::valueOf(::includeBlinkingVoxel)); + qDebug("includeBlinkingVoxel=%s", debug::valueOf(::includeBlinkingVoxel)); const char* NO_DANCE_FLOOR = "--NoDanceFloor"; ::includeDanceFloor = !cmdOptionExists(argc, (const char**) argv, NO_DANCE_FLOOR); - printf("includeDanceFloor=%s\n", debug::valueOf(::includeDanceFloor)); + qDebug("includeDanceFloor=%s", debug::valueOf(::includeDanceFloor)); const char* BUILD_STREET = "--BuildStreet"; ::buildStreet = cmdOptionExists(argc, (const char**) argv, BUILD_STREET); - printf("buildStreet=%s\n", debug::valueOf(::buildStreet)); + qDebug("buildStreet=%s", debug::valueOf(::buildStreet)); // Handle Local Domain testing with the --local command line const char* showPPS = "--showPPS"; @@ -725,7 +725,7 @@ AnimationServer::AnimationServer(int &argc, char **argv) : const char* local = "--local"; ::wantLocalDomain = cmdOptionExists(argc, (const char**) argv,local); if (::wantLocalDomain) { - printf("Local Domain MODE!\n"); + qDebug("Local Domain MODE!"); nodeList->getDomainHandler().setIPToLocalhost(); } @@ -738,7 +738,7 @@ AnimationServer::AnimationServer(int &argc, char **argv) : if (packetsPerSecondCommand) { ::packetsPerSecond = atoi(packetsPerSecondCommand); } - printf("packetsPerSecond=%d\n",packetsPerSecond); + qDebug("packetsPerSecond=%d",packetsPerSecond); const char* animateFPSCommand = getCmdOption(argc, (const char**) argv, "--AnimateFPS"); const char* animateIntervalCommand = getCmdOption(argc, (const char**) argv, "--AnimateInterval"); @@ -753,8 +753,8 @@ AnimationServer::AnimationServer(int &argc, char **argv) : ::ANIMATE_VOXELS_INTERVAL_USECS = (ANIMATE_FPS_IN_MILLISECONDS * 1000.0); // converts from milliseconds to usecs } } - printf("ANIMATE_FPS=%d\n",ANIMATE_FPS); - printf("ANIMATE_VOXELS_INTERVAL_USECS=%llu\n",ANIMATE_VOXELS_INTERVAL_USECS); + qDebug("ANIMATE_FPS=%d",ANIMATE_FPS); + qDebug("ANIMATE_VOXELS_INTERVAL_USECS=%llu",ANIMATE_VOXELS_INTERVAL_USECS); const char* processingFPSCommand = getCmdOption(argc, (const char**) argv, "--ProcessingFPS"); const char* processingIntervalCommand = getCmdOption(argc, (const char**) argv, "--ProcessingInterval"); @@ -769,8 +769,8 @@ AnimationServer::AnimationServer(int &argc, char **argv) : ::PROCESSING_INTERVAL_USECS = (PROCESSING_FPS_IN_MILLISECONDS * 1000.0) - FUDGE_USECS; // converts from milliseconds to usecs } } - printf("PROCESSING_FPS=%d\n",PROCESSING_FPS); - printf("PROCESSING_INTERVAL_USECS=%llu\n",PROCESSING_INTERVAL_USECS); + qDebug("PROCESSING_FPS=%d",PROCESSING_FPS); + qDebug("PROCESSING_INTERVAL_USECS=%llu",PROCESSING_INTERVAL_USECS); nodeList->linkedDataCreateCallback = NULL; // do we need a callback? diff --git a/assignment-client/src/octree/OctreeInboundPacketProcessor.cpp b/assignment-client/src/octree/OctreeInboundPacketProcessor.cpp index 41158bf339..545c502036 100644 --- a/assignment-client/src/octree/OctreeInboundPacketProcessor.cpp +++ b/assignment-client/src/octree/OctreeInboundPacketProcessor.cpp @@ -45,7 +45,7 @@ void OctreeInboundPacketProcessor::processPacket(const SharedNodePointer& sendin bool debugProcessPacket = _myServer->wantsVerboseDebug(); if (debugProcessPacket) { - printf("OctreeInboundPacketProcessor::processPacket() packetData=%p packetLength=%d\n", &packet, packet.size()); + qDebug("OctreeInboundPacketProcessor::processPacket() packetData=%p packetLength=%d", &packet, packet.size()); } int numBytesPacketHeader = numBytesForPacketHeader(packet); @@ -78,8 +78,8 @@ void OctreeInboundPacketProcessor::processPacket(const SharedNodePointer& sendin int maxSize = packet.size() - atByte; if (debugProcessPacket) { - printf("OctreeInboundPacketProcessor::processPacket() %c " - "packetData=%p packetLength=%d voxelData=%p atByte=%d maxSize=%d\n", + qDebug("OctreeInboundPacketProcessor::processPacket() %c " + "packetData=%p packetLength=%d voxelData=%p atByte=%d maxSize=%d", packetType, packetData, packet.size(), editData, atByte, maxSize); } @@ -105,8 +105,8 @@ void OctreeInboundPacketProcessor::processPacket(const SharedNodePointer& sendin } if (debugProcessPacket) { - printf("OctreeInboundPacketProcessor::processPacket() DONE LOOPING FOR %c " - "packetData=%p packetLength=%d voxelData=%p atByte=%d\n", + qDebug("OctreeInboundPacketProcessor::processPacket() DONE LOOPING FOR %c " + "packetData=%p packetLength=%d voxelData=%p atByte=%d", packetType, packetData, packet.size(), editData, atByte); } diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 2e8a354c6a..21762f1534 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -486,7 +486,7 @@ bool OctreeServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url // encode float averageEncodeTime = getAverageEncodeTime(); - statsString += QString().sprintf(" Average encode time: %9.2f usecs\r\n", averageEncodeTime); + statsString += QString().sqDebug(" Average encode time: %9.2f usecs\r", averageEncodeTime); int allEncodeTimes = _noEncode + _shortEncode + _longEncode + _extraLongEncode; @@ -554,9 +554,9 @@ bool OctreeServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url noVsTotalSend * AS_PERCENT, _noSend); float averageNodeWaitTime = getAverageNodeWaitTime(); - statsString += QString().sprintf(" Average node lock wait time: %9.2f usecs\r\n", averageNodeWaitTime); + statsString += QString().sqDebug(" Average node lock wait time: %9.2f usecs\r", averageNodeWaitTime); - statsString += QString().sprintf("--------------------------------------------------------------\r\n"); + statsString += QString().sqDebug("--------------------------------------------------------------\r"); float encodeToInsidePercent = averageInsideTime == 0.0f ? 0.0f : (averageEncodeTime / averageInsideTime) * AS_PERCENT; statsString += QString().sprintf(" encode ratio: %5.2f%%\r\n", @@ -564,7 +564,7 @@ bool OctreeServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url float waitToInsidePercent = averageInsideTime == 0.0f ? 0.0f : ((averageTreeWaitTime + averageNodeWaitTime) / averageInsideTime) * AS_PERCENT; - statsString += QString().sprintf(" waiting ratio: %5.2f%%\r\n", waitToInsidePercent); + statsString += QString().sqDebug(" waiting ratio: %5.2f%%\r", waitToInsidePercent); float compressAndWriteToInsidePercent = averageInsideTime == 0.0f ? 0.0f : (averageCompressAndWriteTime / averageInsideTime) * AS_PERCENT; @@ -573,7 +573,7 @@ bool OctreeServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url float sendingToInsidePercent = averageInsideTime == 0.0f ? 0.0f : (averagePacketSendingTime / averageInsideTime) * AS_PERCENT; - statsString += QString().sprintf(" sending ratio: %5.2f%%\r\n", sendingToInsidePercent); + statsString += QString().sqDebug(" sending ratio: %5.2f%%\r", sendingToInsidePercent); @@ -615,7 +615,7 @@ bool OctreeServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url .arg(locale.toString((uint)totalPacketsProcessed).rightJustified(COLUMN_WIDTH, ' ')); statsString += QString(" Total Inbound Elements: %1 elements\r\n") .arg(locale.toString((uint)totalElementsProcessed).rightJustified(COLUMN_WIDTH, ' ')); - statsString += QString().sprintf(" Average Inbound Elements/Packet: %f elements/packet\r\n", averageElementsPerPacket); + statsString += QString().sqDebug(" Average Inbound Elements/Packet: %f elements/packet\r", averageElementsPerPacket); statsString += QString(" Average Transit Time/Packet: %1 usecs\r\n") .arg(locale.toString((uint)averageTransitTimePerPacket).rightJustified(COLUMN_WIDTH, ' ')); statsString += QString(" Average Process Time/Packet: %1 usecs\r\n") @@ -671,7 +671,7 @@ bool OctreeServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url // display memory usage stats statsString += "Current Memory Usage Statistics\r\n"; - statsString += QString().sprintf("\r\nOctreeElement size... %ld bytes\r\n", sizeof(OctreeElement)); + statsString += QString().sqDebug("\r\nOctreeElement size... %ld bytes\r", sizeof(OctreeElement)); statsString += "\r\n"; const char* memoryScaleLabel; @@ -738,8 +738,8 @@ bool OctreeServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url OctreeElement::getExternalChildrenCount(); statsString += " ----------------\r\n"; - statsString += QString().sprintf(" Total: %10.llu nodes\r\n", checkSum); - statsString += QString().sprintf(" Expected: %10.lu nodes\r\n", nodeCount); + statsString += QString().sqDebug(" Total: %10.llu nodes\r", checkSum); + statsString += QString().sqDebug(" Expected: %10.lu nodes\r", nodeCount); statsString += "\r\n"; statsString += "In other news....\r\n"; diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index cd07f21300..a885c80968 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3122,7 +3122,7 @@ void Application::nodeKilled(SharedNodePointer node) { VoxelPositionSize rootDetails; voxelDetailsForCode(rootCode, rootDetails); - printf("voxel server going away...... v[%f, %f, %f, %f]\n", + qDebug("voxel server going away...... v[%f, %f, %f, %f]", rootDetails.x, rootDetails.y, rootDetails.z, rootDetails.s); // Add the jurisditionDetails object to the list of "fade outs" @@ -3153,7 +3153,7 @@ void Application::nodeKilled(SharedNodePointer node) { VoxelPositionSize rootDetails; voxelDetailsForCode(rootCode, rootDetails); - printf("particle server going away...... v[%f, %f, %f, %f]\n", + qDebug("particle server going away...... v[%f, %f, %f, %f]", rootDetails.x, rootDetails.y, rootDetails.z, rootDetails.s); // Add the jurisditionDetails object to the list of "fade outs" @@ -3234,7 +3234,7 @@ int Application::parseOctreeStats(const QByteArray& packet, const SharedNodePoin if (jurisdiction->find(nodeUUID) == jurisdiction->end()) { - printf("stats from new server... v[%f, %f, %f, %f]\n", + qDebug("stats from new server... v[%f, %f, %f, %f]", rootDetails.x, rootDetails.y, rootDetails.z, rootDetails.s); // Add the jurisditionDetails object to the list of "fade outs" diff --git a/interface/src/DatagramProcessor.cpp b/interface/src/DatagramProcessor.cpp index 92260ad9dc..6525e79cf2 100644 --- a/interface/src/DatagramProcessor.cpp +++ b/interface/src/DatagramProcessor.cpp @@ -78,7 +78,7 @@ void DatagramProcessor::processDatagrams() { OCTREE_PACKET_SENT_TIME arrivedAt = usecTimestampNow(); int flightTime = arrivedAt - sentAt; - printf("got PacketType_VOXEL_DATA, sequence:%d flightTime:%d\n", sequence, flightTime); + qDebug("got PacketType_VOXEL_DATA, sequence:%d flightTime:%d", sequence, flightTime); } SharedNodePointer matchedNode = NodeList::getInstance()->sendingNodeForPacket(incomingPacket); diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 1dae3a4fd6..febcb2f36e 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -63,7 +63,7 @@ void eulerToOrthonormals(glm::vec3 * angles, glm::vec3 * front, glm::vec3 * righ } void printVector(glm::vec3 vec) { - printf("%4.2f, %4.2f, %4.2f\n", vec.x, vec.y, vec.z); + qDebug("%4.2f, %4.2f, %4.2f", vec.x, vec.y, vec.z); } // Return the azimuth angle (in radians) between two points. diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 8229611646..317f408aa7 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -432,7 +432,7 @@ void MyAvatar::renderDebugBodyPoints() { glm::vec3 headPosition(getHead()->getEyePosition()); float torsoToHead = glm::length(headPosition - torsoPosition); glm::vec3 position; - printf("head-above-torso %.2f, scale = %0.2f\n", torsoToHead, getScale()); + qDebug("head-above-torso %.2f, scale = %0.2f", torsoToHead, getScale()); // Torso Sphere position = torsoPosition; diff --git a/interface/src/devices/SixenseManager.cpp b/interface/src/devices/SixenseManager.cpp index b950e6097c..f7c00411c1 100644 --- a/interface/src/devices/SixenseManager.cpp +++ b/interface/src/devices/SixenseManager.cpp @@ -96,7 +96,7 @@ void SixenseManager::update(float deltaTime) { hand->getPalms().push_back(newPalm); palm = &(hand->getPalms()[hand->getNumPalms() - 1]); palm->setSixenseID(data->controller_index); - printf("Found new Sixense controller, ID %i\n", data->controller_index); + qDebug("Found new Sixense controller, ID %i", data->controller_index); } palm->setActive(true); diff --git a/interface/src/voxels/VoxelSystem.cpp b/interface/src/voxels/VoxelSystem.cpp index 692f299bdc..8d59f33674 100644 --- a/interface/src/voxels/VoxelSystem.cpp +++ b/interface/src/voxels/VoxelSystem.cpp @@ -117,7 +117,7 @@ void VoxelSystem::elementDeleted(OctreeElement* element) { forceRemoveNodeFromArrays(voxel); } else { if (Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings)) { - printf("VoxelSystem::elementDeleted() while _voxelsInWriteArrays==0, is that expected? \n"); + qDebug("VoxelSystem::elementDeleted() while _voxelsInWriteArrays==0, is that expected? "); } } } diff --git a/libraries/networking/src/Logging.cpp b/libraries/networking/src/Logging.cpp index 17a4706de0..f42f1bda58 100644 --- a/libraries/networking/src/Logging.cpp +++ b/libraries/networking/src/Logging.cpp @@ -46,7 +46,7 @@ const HifiSockAddr& Logging::socket() { // use the first IP address _logstashSocket.setAddress(hostInfo.addresses().first()); } else { - printf("Failed to lookup logstash IP - will try again on next log attempt.\n"); + qDebug("Failed to lookup logstash IP - will try again on next log attempt."); } } diff --git a/libraries/octree/src/Octree.cpp b/libraries/octree/src/Octree.cpp index 696a65b4b5..d7fc7713cf 100644 --- a/libraries/octree/src/Octree.cpp +++ b/libraries/octree/src/Octree.cpp @@ -471,8 +471,8 @@ void Octree::processRemoveOctreeElementsBitstream(const unsigned char* bitstream int codeLength = numberOfThreeBitSectionsInCode(voxelCode, maxSize); if (codeLength == OVERFLOWED_OCTCODE_BUFFER) { - printf("WARNING! Got remove voxel bitstream that would overflow buffer in numberOfThreeBitSectionsInCode(), "); - printf("bailing processing of packet!\n"); + qDebug("WARNING! Got remove voxel bitstream that would overflow buffer in numberOfThreeBitSectionsInCode()," + " bailing processing of packet!"); break; } int voxelDataSize = bytesRequiredForCodeLength(codeLength) + SIZE_OF_COLOR_DATA; @@ -482,7 +482,7 @@ void Octree::processRemoveOctreeElementsBitstream(const unsigned char* bitstream voxelCode += voxelDataSize; atByte += voxelDataSize; } else { - printf("WARNING! Got remove voxel bitstream that would overflow buffer, bailing processing!\n"); + qDebug("WARNING! Got remove voxel bitstream that would overflow buffer, bailing processing!"); break; } } @@ -1404,7 +1404,7 @@ int Octree::encodeTreeBitstreamRecursion(OctreeElement* node, outputBits(childrenExistInPacketBits, false, true); printf(" childrenColored:"); outputBits(childrenColoredBits, false, true); - printf("\n"); + qDebug(""); **/ // if we were unable to fit this level in our packet, then rewind and add it to the node bag for @@ -1620,7 +1620,7 @@ void Octree::copyFromTreeIntoSubTree(Octree* sourceTree, OctreeElement* destinat } void dumpSetContents(const char* name, std::set set) { - printf("set %s has %ld elements\n", name, set.size()); + qDebug("set %s has %ld elements", name, set.size()); /* for (std::set::iterator i = set.begin(); i != set.end(); ++i) { printOctalCode(*i); diff --git a/libraries/octree/src/Octree.h b/libraries/octree/src/Octree.h index 839e61d1c2..3c868ab172 100644 --- a/libraries/octree/src/Octree.h +++ b/libraries/octree/src/Octree.h @@ -129,17 +129,17 @@ public: printf("StopReason: "); switch (stopReason) { default: - case UNKNOWN: printf("UNKNOWN\n"); break; + case UNKNOWN: qDebug("UNKNOWN"); break; - case DIDNT_FIT: printf("DIDNT_FIT\n"); break; - case NULL_NODE: printf("NULL_NODE\n"); break; - case TOO_DEEP: printf("TOO_DEEP\n"); break; - case OUT_OF_JURISDICTION: printf("OUT_OF_JURISDICTION\n"); break; - case LOD_SKIP: printf("LOD_SKIP\n"); break; - case OUT_OF_VIEW: printf("OUT_OF_VIEW\n"); break; - case WAS_IN_VIEW: printf("WAS_IN_VIEW\n"); break; - case NO_CHANGE: printf("NO_CHANGE\n"); break; - case OCCLUDED: printf("OCCLUDED\n"); break; + case DIDNT_FIT: qDebug("DIDNT_FIT"); break; + case NULL_NODE: qDebug("NULL_NODE"); break; + case TOO_DEEP: qDebug("TOO_DEEP"); break; + case OUT_OF_JURISDICTION: qDebug("OUT_OF_JURISDICTION"); break; + case LOD_SKIP: qDebug("LOD_SKIP"); break; + case OUT_OF_VIEW: qDebug("OUT_OF_VIEW"); break; + case WAS_IN_VIEW: qDebug("WAS_IN_VIEW"); break; + case NO_CHANGE: qDebug("NO_CHANGE"); break; + case OCCLUDED: qDebug("OCCLUDED"); break; } } }; diff --git a/libraries/octree/src/OctreeEditPacketSender.cpp b/libraries/octree/src/OctreeEditPacketSender.cpp index b606dffe44..7e59b3ae7f 100644 --- a/libraries/octree/src/OctreeEditPacketSender.cpp +++ b/libraries/octree/src/OctreeEditPacketSender.cpp @@ -37,7 +37,7 @@ OctreeEditPacketSender::OctreeEditPacketSender() : _serverJurisdictions(NULL), _sequenceNumber(0), _maxPacketSize(MAX_PACKET_SIZE) { - //printf("OctreeEditPacketSender::OctreeEditPacketSender() [%p] created... \n", this); + //qDebug("OctreeEditPacketSender::OctreeEditPacketSender() [%p] created... ", this); } OctreeEditPacketSender::~OctreeEditPacketSender() { @@ -53,7 +53,7 @@ OctreeEditPacketSender::~OctreeEditPacketSender() { _preServerPackets.erase(_preServerPackets.begin()); } _pendingPacketsLock.unlock(); - //printf("OctreeEditPacketSender::~OctreeEditPacketSender() [%p] destroyed... \n", this); + //qDebug("OctreeEditPacketSender::~OctreeEditPacketSender() [%p] destroyed... ", this); } diff --git a/libraries/octree/src/OctreeElement.cpp b/libraries/octree/src/OctreeElement.cpp index e21148df5e..96311ceabd 100644 --- a/libraries/octree/src/OctreeElement.cpp +++ b/libraries/octree/src/OctreeElement.cpp @@ -204,7 +204,7 @@ void OctreeElement::calculateAABox() { void OctreeElement::deleteChildAtIndex(int childIndex) { OctreeElement* childAt = getChildAtIndex(childIndex); if (childAt) { - //printf("deleteChildAtIndex()... about to call delete childAt=%p\n",childAt); + //qDebug("deleteChildAtIndex()... about to call delete childAt=%p",childAt); delete childAt; setChildAtIndex(childIndex, NULL); _isDirty = true; @@ -1315,7 +1315,7 @@ OctreeElement* OctreeElement::getOrCreateChildElementAt(float x, float y, float float halfOurScale = ourScale / 2.0f; if(s > ourScale) { - printf("UNEXPECTED -- OctreeElement::getOrCreateChildElementAt() s=[%f] > ourScale=[%f] \n", s, ourScale); + qDebug("UNEXPECTED -- OctreeElement::getOrCreateChildElementAt() s=[%f] > ourScale=[%f] ", s, ourScale); } if (s > halfOurScale) { diff --git a/libraries/octree/src/OctreePacketData.cpp b/libraries/octree/src/OctreePacketData.cpp index 2edf560de6..b54a87bef8 100644 --- a/libraries/octree/src/OctreePacketData.cpp +++ b/libraries/octree/src/OctreePacketData.cpp @@ -125,7 +125,7 @@ const unsigned char* OctreePacketData::getFinalizedData() { if (_dirty) { if (_debug) { - printf("getFinalizedData() _compressedBytes=%d _bytesInUse=%d\n",_compressedBytes, _bytesInUse); + qDebug("getFinalizedData() _compressedBytes=%d _bytesInUse=%d",_compressedBytes, _bytesInUse); } compressContent(); } @@ -139,7 +139,7 @@ int OctreePacketData::getFinalizedSize() { if (_dirty) { if (_debug) { - printf("getFinalizedSize() _compressedBytes=%d _bytesInUse=%d\n",_compressedBytes, _bytesInUse); + qDebug("getFinalizedSize() _compressedBytes=%d _bytesInUse=%d",_compressedBytes, _bytesInUse); } compressContent(); } @@ -187,7 +187,7 @@ void OctreePacketData::discardLevel(LevelDetails key) { _totalBytesOfColor -= reduceBytesOfColor; if (_debug) { - printf("discardLevel() BEFORE _dirty=%s bytesInLevel=%d _compressedBytes=%d _bytesInUse=%d\n", + qDebug("discardLevel() BEFORE _dirty=%s bytesInLevel=%d _compressedBytes=%d _bytesInUse=%d", debug::valueOf(_dirty), bytesInLevel, _compressedBytes, _bytesInUse); } @@ -196,7 +196,7 @@ void OctreePacketData::discardLevel(LevelDetails key) { _dirty = true; if (_debug) { - printf("discardLevel() AFTER _dirty=%s bytesInLevel=%d _compressedBytes=%d _bytesInUse=%d\n", + qDebug("discardLevel() AFTER _dirty=%s bytesInLevel=%d _compressedBytes=%d _bytesInUse=%d", debug::valueOf(_dirty), bytesInLevel, _compressedBytes, _bytesInUse); } } @@ -413,13 +413,13 @@ void OctreePacketData::loadFinalizedContent(const unsigned char* data, int lengt } } else { if (_debug) { - printf("OctreePacketData::loadCompressedContent()... length = 0, nothing to do...\n"); + qDebug("OctreePacketData::loadCompressedContent()... length = 0, nothing to do..."); } } } void OctreePacketData::debugContent() { - printf("OctreePacketData::debugContent()... COMPRESSED DATA.... size=%d\n",_compressedBytes); + qDebug("OctreePacketData::debugContent()... COMPRESSED DATA.... size=%d",_compressedBytes); int perline=0; for (int i = 0; i < _compressedBytes; i++) { printf("%.2x ",_compressed[i]); @@ -431,7 +431,7 @@ void OctreePacketData::debugContent() { } printf("\n"); - printf("OctreePacketData::debugContent()... UNCOMPRESSED DATA.... size=%d\n",_bytesInUse); + qDebug("OctreePacketData::debugContent()... UNCOMPRESSED DATA.... size=%d",_bytesInUse); perline=0; for (int i = 0; i < _bytesInUse; i++) { printf("%.2x ",_uncompressed[i]); diff --git a/libraries/octree/src/OctreeProjectedPolygon.cpp b/libraries/octree/src/OctreeProjectedPolygon.cpp index f86d598a87..92a5b2ac18 100644 --- a/libraries/octree/src/OctreeProjectedPolygon.cpp +++ b/libraries/octree/src/OctreeProjectedPolygon.cpp @@ -263,12 +263,12 @@ bool OctreeProjectedPolygon::pointInside(const glm::vec2& point, bool* matchesVe } void OctreeProjectedPolygon::printDebugDetails() const { - printf("OctreeProjectedPolygon..."); - printf(" minX=%f maxX=%f minY=%f maxY=%f\n", getMinX(), getMaxX(), getMinY(), getMaxY()); - printf(" vertex count=%d distance=%f\n", getVertexCount(), getDistance()); + qDebug("OctreeProjectedPolygon..." + " minX=%f maxX=%f minY=%f maxY=%f", getMinX(), getMaxX(), getMinY(), getMaxY()); + qDebug(" vertex count=%d distance=%f", getVertexCount(), getDistance()); for (int i = 0; i < getVertexCount(); i++) { glm::vec2 point = getVertex(i); - printf(" vertex[%d] = %f, %f \n", i, point.x, point.y); + qDebug(" vertex[%d] = %f, %f ", i, point.x, point.y); } } diff --git a/libraries/octree/src/Plane.cpp b/libraries/octree/src/Plane.cpp index d7cb2c54ff..d9e5633233 100755 --- a/libraries/octree/src/Plane.cpp +++ b/libraries/octree/src/Plane.cpp @@ -14,6 +14,8 @@ #include "Plane.h" +#include + #include void Plane::set3Points(const glm::vec3 &v1, const glm::vec3 &v2, const glm::vec3 &v3) { @@ -61,6 +63,6 @@ float Plane::distance(const glm::vec3 &point) const { } void Plane::print() const { - printf("Plane - point (x=%f y=%f z=%f) normal (x=%f y=%f z=%f) d=%f\n", + qDebug("Plane - point (x=%f y=%f z=%f) normal (x=%f y=%f z=%f) d=%f", _point.x, _point.y, _point.z, _normal.x, _normal.y, _normal.z, _dCoefficient); } diff --git a/libraries/particles/src/Particle.cpp b/libraries/particles/src/Particle.cpp index a36998aad4..59265c00dc 100644 --- a/libraries/particles/src/Particle.cpp +++ b/libraries/particles/src/Particle.cpp @@ -146,7 +146,7 @@ bool Particle::appendParticleData(OctreePacketData* packetData) const { bool success = packetData->appendValue(getID()); - //printf("Particle::appendParticleData()... getID()=%d\n", getID()); + //qDebug("Particle::appendParticleData()... getID()=%d", getID()); if (success) { success = packetData->appendValue(getAge()); @@ -541,15 +541,15 @@ Particle Particle::fromEditPacket(const unsigned char* data, int length, int& pr } void Particle::debugDump() const { - printf("Particle id :%u\n", _id); - printf(" age:%f\n", getAge()); - printf(" edited ago:%f\n", getEditedAgo()); - printf(" should die:%s\n", debug::valueOf(getShouldDie())); - printf(" position:%f,%f,%f\n", _position.x, _position.y, _position.z); - printf(" radius:%f\n", getRadius()); - printf(" velocity:%f,%f,%f\n", _velocity.x, _velocity.y, _velocity.z); - printf(" gravity:%f,%f,%f\n", _gravity.x, _gravity.y, _gravity.z); - printf(" color:%d,%d,%d\n", _color[0], _color[1], _color[2]); + qDebug("Particle id :%u", _id); + qDebug(" age:%f", getAge()); + qDebug(" edited ago:%f", getEditedAgo()); + qDebug(" should die:%s", debug::valueOf(getShouldDie())); + qDebug(" position:%f,%f,%f", _position.x, _position.y, _position.z); + qDebug(" radius:%f", getRadius()); + qDebug(" velocity:%f,%f,%f", _velocity.x, _velocity.y, _velocity.z); + qDebug(" gravity:%f,%f,%f", _gravity.x, _gravity.y, _gravity.z); + qDebug(" color:%d,%d,%d", _color[0], _color[1], _color[2]); } bool Particle::encodeParticleEditMessageDetails(PacketType command, ParticleID id, const ParticleProperties& properties, @@ -732,9 +732,9 @@ bool Particle::encodeParticleEditMessageDetails(PacketType command, ParticleID i bool wantDebugging = false; if (wantDebugging) { - printf("encodeParticleEditMessageDetails()....\n"); - printf("Particle id :%u\n", id.id); - printf(" nextID:%u\n", _nextID); + qDebug("encodeParticleEditMessageDetails()...."); + qDebug("Particle id :%u", id.id); + qDebug(" nextID:%u", _nextID); } // cleanup @@ -844,7 +844,7 @@ void Particle::update(const quint64& now) { // handle damping glm::vec3 dampingResistance = _velocity * _damping; _velocity -= dampingResistance * timeElapsed; - //printf("applying damping to Particle timeElapsed=%f\n",timeElapsed); + //qDebug("applying damping to Particle timeElapsed=%f",timeElapsed); } } diff --git a/libraries/particles/src/ParticleTreeElement.cpp b/libraries/particles/src/ParticleTreeElement.cpp index 19353c427a..d28ccf2f5e 100644 --- a/libraries/particles/src/ParticleTreeElement.cpp +++ b/libraries/particles/src/ParticleTreeElement.cpp @@ -142,7 +142,7 @@ bool ParticleTreeElement::updateParticle(const Particle& particle) { bool localOlder = thisParticle.getLastUpdated() < particle.getLastUpdated(); if (changedOnServer || localOlder) { if (wantDebug) { - printf("local particle [id:%d] %s and %s than server particle by %d, particle.isNewlyCreated()=%s\n", + qDebug("local particle [id:%d] %s and %s than server particle by %d, particle.isNewlyCreated()=%s", particle.getID(), (changedOnServer ? "CHANGED" : "same"), (localOlder ? "OLDER" : "NEWER"), difference, debug::valueOf(particle.isNewlyCreated()) ); @@ -150,8 +150,8 @@ bool ParticleTreeElement::updateParticle(const Particle& particle) { thisParticle.copyChangedProperties(particle); } else { if (wantDebug) { - printf(">>> IGNORING SERVER!!! Would've caused jutter! <<< " - "local particle [id:%d] %s and %s than server particle by %d, particle.isNewlyCreated()=%s\n", + qDebug(">>> IGNORING SERVER!!! Would've caused jutter! <<< " + "local particle [id:%d] %s and %s than server particle by %d, particle.isNewlyCreated()=%s", particle.getID(), (changedOnServer ? "CHANGED" : "same"), (localOlder ? "OLDER" : "NEWER"), difference, debug::valueOf(particle.isNewlyCreated()) ); diff --git a/voxel-edit/src/SceneUtils.cpp b/voxel-edit/src/SceneUtils.cpp index 19e227c71a..937b03cc39 100644 --- a/voxel-edit/src/SceneUtils.cpp +++ b/voxel-edit/src/SceneUtils.cpp @@ -20,7 +20,7 @@ void addCornersAndAxisLines(VoxelTree* tree) { float voxelSize = 0.5f / TREE_SCALE; // Now some more examples... a little more complex - printf("creating corner points...\n"); + qDebug("creating corner points..."); tree->createVoxel(0 , 0 , 0 , voxelSize, 255, 255 ,255); tree->createVoxel(1.0 - voxelSize, 0 , 0 , voxelSize, 255, 0 ,0 ); tree->createVoxel(0 , 1.0 - voxelSize, 0 , voxelSize, 0 , 255 ,0 ); @@ -29,11 +29,11 @@ void addCornersAndAxisLines(VoxelTree* tree) { tree->createVoxel(0 , 1.0 - voxelSize, 1.0 - voxelSize, voxelSize, 0 , 255 ,255); tree->createVoxel(1.0 - voxelSize, 1.0 - voxelSize, 0 , voxelSize, 255, 255 ,0 ); tree->createVoxel(1.0 - voxelSize, 1.0 - voxelSize, 1.0 - voxelSize, voxelSize, 255, 255 ,255); - printf("DONE creating corner points...\n"); + qDebug("DONE creating corner points..."); } void addSurfaceScene(VoxelTree * tree) { - printf("adding surface scene...\n"); + qDebug("adding surface scene..."); float voxelSize = 1.f / (8 * TREE_SCALE); // color 1= blue, color 2=green @@ -57,5 +57,5 @@ void addSurfaceScene(VoxelTree * tree) { } } } - printf("DONE adding surface scene...\n"); + qDebug("DONE adding surface scene..."); } From e55c488964adf79d26283fd4dba33f7c943bc4e0 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 21 Apr 2014 16:17:59 -0700 Subject: [PATCH 554/595] clean up some old debugging --- assignment-client/src/octree/OctreeServer.cpp | 151 +----------------- assignment-client/src/octree/OctreeServer.h | 3 - 2 files changed, 2 insertions(+), 152 deletions(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 4f435cd371..04a69ff7e8 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -9,7 +9,6 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#include #include #include #include @@ -209,16 +208,11 @@ void OctreeServer::trackProcessWaitTime(float time) { } void OctreeServer::attachQueryNodeToNode(Node* newNode) { - quint64 start = usecTimestampNow(); if (!newNode->getLinkedData() && _instance) { OctreeQueryNode* newQueryNodeData = _instance->createOctreeQueryNode(); newQueryNodeData->init(); newNode->setLinkedData(newQueryNodeData); } - quint64 end = usecTimestampNow(); - if (end - start > 1000) { - qDebug() << "OctreeServer::attachQueryNodeToNode() took:" << (end - start); - } } OctreeServer::OctreeServer(const QByteArray& packet) : @@ -242,7 +236,6 @@ OctreeServer::OctreeServer(const QByteArray& packet) : _started(time(0)), _startedUSecs(usecTimestampNow()) { - //assert(!_instance); // you should only ever have one instance at a time! if (_instance) { qDebug() << "Octree Server starting... while old instance still running _instance=["<<_instance<<"] this=[" << this << "]"; } @@ -252,23 +245,6 @@ OctreeServer::OctreeServer(const QByteArray& packet) : _averageLoopTime.updateAverage(0); qDebug() << "Octree server starting... [" << this << "]"; - - - /* - QTimer* timer = new QTimer(this); - connect(timer, SIGNAL(timeout()), SLOT(doNothing())); - timer->start(0); - */ - -} - -quint64 lastNothing = usecTimestampNow(); -void OctreeServer::doNothing() { - quint64 now = usecTimestampNow(); - if (now - lastNothing > 100) { - qDebug() << "since last doNothing:" << (now - lastNothing); - } - lastNothing = now; } OctreeServer::~OctreeServer() { @@ -299,7 +275,7 @@ OctreeServer::~OctreeServer() { _jurisdiction = NULL; // cleanup our tree here... - qDebug() << qPrintable(_safeServerName) << "server cleaning up octree... [" << this << "]"; + qDebug() << qPrintable(_safeServerName) << "server START cleaning up octree... [" << this << "]"; delete _tree; _tree = NULL; qDebug() << qPrintable(_safeServerName) << "server DONE cleaning up octree... [" << this << "]"; @@ -845,164 +821,41 @@ void OctreeServer::parsePayload() { } } -quint64 lastReadPendingDatagrams = usecTimestampNow(); -quint64 lastProcessNodeData = usecTimestampNow(); - void OctreeServer::readPendingDatagrams() { - //qDebug() << "OctreeServer::readPendingDatagrams()... thread()->eventDispatcher()=" << thread()->eventDispatcher(); - - - quint64 now = usecTimestampNow(); - - // more than 1.1 second is probably a problem - if ((now - lastReadPendingDatagrams) > 1100000) { - qDebug() << "OctreeServer::readPendingDatagrams(): since lastReadPendingDatagrams=" << (now - lastReadPendingDatagrams) << "usecs"; - } - lastReadPendingDatagrams = now; - QByteArray receivedPacket; HifiSockAddr senderSockAddr; NodeList* nodeList = NodeList::getInstance(); - quint64 startReadAvailable = usecTimestampNow(); - int readDataGrams = 0; - - int queryPackets = 0; - int jurisdictionRequests = 0; - int editPackets = 0; - int nodeListPackets = 0; - - quint64 queryElapsed = 0; - quint64 jurisdictionElapsed = 0; - quint64 editElapsed = 0; - quint64 nodeListElapsed = 0; - quint64 versionMatchElapsed = 0; - quint64 matchingElapsed = 0; - - while (readAvailableDatagram(receivedPacket, senderSockAddr)) { - readDataGrams++; - - quint64 versionMatchStart = usecTimestampNow(); - bool matches = nodeList->packetVersionAndHashMatch(receivedPacket); - quint64 versionMatchEnd = usecTimestampNow(); - versionMatchElapsed += (versionMatchEnd - versionMatchStart); - - if (matches) { + if (nodeList->packetVersionAndHashMatch(receivedPacket)) { PacketType packetType = packetTypeForPacket(receivedPacket); - - quint64 startNodeLookup = usecTimestampNow(); SharedNodePointer matchingNode = nodeList->sendingNodeForPacket(receivedPacket); - quint64 endNodeLookup = usecTimestampNow(); - matchingElapsed += (endNodeLookup - startNodeLookup); - - if ((endNodeLookup - startNodeLookup) > 100000) { - qDebug() << "OctreeServer::readPendingDatagrams(): sendingNodeForPacket() took" << (endNodeLookup - startNodeLookup) << "usecs"; - } - if (packetType == getMyQueryMessageType()) { - quint64 queryStart = usecTimestampNow(); - queryPackets++; - // If we got a PacketType_VOXEL_QUERY, then we're talking to an NodeType_t_AVATAR, and we // need to make sure we have it in our nodeList. if (matchingNode) { - quint64 startUpdateNode = usecTimestampNow(); nodeList->updateNodeWithDataFromPacket(matchingNode, receivedPacket); - quint64 endUpdateNode = usecTimestampNow(); - if ((endUpdateNode - startUpdateNode) > 100000) { - qDebug() << "OctreeServer::readPendingDatagrams(): updateNodeWithDataFromPacket() took" << (endUpdateNode - startUpdateNode) << "usecs"; - } - OctreeQueryNode* nodeData = (OctreeQueryNode*) matchingNode->getLinkedData(); if (nodeData && !nodeData->isOctreeSendThreadInitalized()) { SharedAssignmentPointer sharedAssignment = AssignmentClient::getCurrentAssignment(); nodeData->initializeOctreeSendThread(sharedAssignment, matchingNode); } } - quint64 queryEnd = usecTimestampNow(); - queryElapsed += (queryEnd - queryStart); } else if (packetType == PacketTypeJurisdictionRequest) { - quint64 jurisdictionStart = usecTimestampNow(); - jurisdictionRequests++; _jurisdictionSender->queueReceivedPacket(matchingNode, receivedPacket); - quint64 jurisdictionEnd = usecTimestampNow(); - jurisdictionElapsed += (jurisdictionEnd - jurisdictionStart); } else if (_octreeInboundPacketProcessor && getOctree()->handlesEditPacketType(packetType)) { - quint64 editStart = usecTimestampNow(); - editPackets++; _octreeInboundPacketProcessor->queueReceivedPacket(matchingNode, receivedPacket); - quint64 editEnd = usecTimestampNow(); - editElapsed += (editEnd - editStart); } else { - quint64 nodeListStart = usecTimestampNow(); - - nodeListPackets++; - quint64 now = usecTimestampNow(); - - // more than 1.1 second is probably a problem - if ((now - lastProcessNodeData) > 1100000) { - qDebug() << "OctreeServer::readPendingDatagrams(): since lastProcessNodeData=" << (now - lastProcessNodeData) << "usecs"; - } - lastProcessNodeData = now; - // let processNodeData handle it. - quint64 startProcessNodeData = usecTimestampNow(); NodeList::getInstance()->processNodeData(senderSockAddr, receivedPacket); - quint64 endProcessNodeData = usecTimestampNow(); - if ((endProcessNodeData - startProcessNodeData) > 100000) { - qDebug() << "OctreeServer::readPendingDatagrams(): processNodeData() took" << (endProcessNodeData - startProcessNodeData) << "usecs"; - } - - quint64 nodeListEnd = usecTimestampNow(); - nodeListElapsed += (nodeListEnd - nodeListStart); } } } - quint64 endReadAvailable = usecTimestampNow(); - if (endReadAvailable - startReadAvailable > 500000) { - qDebug() << "OctreeServer::readPendingDatagrams(): while(readAvailable) took" << (endReadAvailable - startReadAvailable) << "usecs" - << " readDataGrams=" << readDataGrams - << " nodeListPackets=" << nodeListPackets - << " editPackets=" << editPackets - << " jurisdictionRequests=" << jurisdictionRequests - << " queryPackets=" << queryPackets; - - qDebug() << "OctreeServer::readPendingDatagrams(): while(readAvailable) took" << (endReadAvailable - startReadAvailable) << "usecs" - << " nodeListElapsed=" << nodeListElapsed - << " editElapsed=" << editElapsed - << " jurisdictionElapsed=" << jurisdictionElapsed - << " queryElapsed=" << queryElapsed - << " versionMatchElapsed=" << versionMatchElapsed - << " matchingElapsed=" << matchingElapsed; - } - -} - -void OctreeServer::aboutToBlock() { - const bool wantDebug = false; - if (wantDebug) { - qDebug() << "OctreeServer::aboutToBlock()..."; - } -} - -void OctreeServer::awake() { - const bool wantDebug = false; - if (wantDebug) { - qDebug() << "OctreeServer::awake()..."; - } } void OctreeServer::run() { - - QAbstractEventDispatcher* eventDispatcher = thread()->eventDispatcher(); - qDebug() << "OctreeServer::run()... thread()->eventDispatcher()=" << eventDispatcher; - - connect(eventDispatcher, &QAbstractEventDispatcher::aboutToBlock, this, &OctreeServer::aboutToBlock); - connect(eventDispatcher, &QAbstractEventDispatcher::awake, this, &OctreeServer::awake); - _safeServerName = getMyServerName(); // Before we do anything else, create our tree... diff --git a/assignment-client/src/octree/OctreeServer.h b/assignment-client/src/octree/OctreeServer.h index 1b57f3e63d..d7139b5c3d 100644 --- a/assignment-client/src/octree/OctreeServer.h +++ b/assignment-client/src/octree/OctreeServer.h @@ -126,9 +126,6 @@ public slots: void nodeAdded(SharedNodePointer node); void nodeKilled(SharedNodePointer node); void sendStatsPacket(); - void doNothing(); - void awake(); - void aboutToBlock(); protected: void parsePayload(); From cfc778d10c3c3fddffb6acdaa89b3eb9b6f0185a Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 21 Apr 2014 16:32:17 -0700 Subject: [PATCH 555/595] Fix regexp fail --- assignment-client/src/octree/OctreeServer.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 21762f1534..2e8a354c6a 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -486,7 +486,7 @@ bool OctreeServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url // encode float averageEncodeTime = getAverageEncodeTime(); - statsString += QString().sqDebug(" Average encode time: %9.2f usecs\r", averageEncodeTime); + statsString += QString().sprintf(" Average encode time: %9.2f usecs\r\n", averageEncodeTime); int allEncodeTimes = _noEncode + _shortEncode + _longEncode + _extraLongEncode; @@ -554,9 +554,9 @@ bool OctreeServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url noVsTotalSend * AS_PERCENT, _noSend); float averageNodeWaitTime = getAverageNodeWaitTime(); - statsString += QString().sqDebug(" Average node lock wait time: %9.2f usecs\r", averageNodeWaitTime); + statsString += QString().sprintf(" Average node lock wait time: %9.2f usecs\r\n", averageNodeWaitTime); - statsString += QString().sqDebug("--------------------------------------------------------------\r"); + statsString += QString().sprintf("--------------------------------------------------------------\r\n"); float encodeToInsidePercent = averageInsideTime == 0.0f ? 0.0f : (averageEncodeTime / averageInsideTime) * AS_PERCENT; statsString += QString().sprintf(" encode ratio: %5.2f%%\r\n", @@ -564,7 +564,7 @@ bool OctreeServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url float waitToInsidePercent = averageInsideTime == 0.0f ? 0.0f : ((averageTreeWaitTime + averageNodeWaitTime) / averageInsideTime) * AS_PERCENT; - statsString += QString().sqDebug(" waiting ratio: %5.2f%%\r", waitToInsidePercent); + statsString += QString().sprintf(" waiting ratio: %5.2f%%\r\n", waitToInsidePercent); float compressAndWriteToInsidePercent = averageInsideTime == 0.0f ? 0.0f : (averageCompressAndWriteTime / averageInsideTime) * AS_PERCENT; @@ -573,7 +573,7 @@ bool OctreeServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url float sendingToInsidePercent = averageInsideTime == 0.0f ? 0.0f : (averagePacketSendingTime / averageInsideTime) * AS_PERCENT; - statsString += QString().sqDebug(" sending ratio: %5.2f%%\r", sendingToInsidePercent); + statsString += QString().sprintf(" sending ratio: %5.2f%%\r\n", sendingToInsidePercent); @@ -615,7 +615,7 @@ bool OctreeServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url .arg(locale.toString((uint)totalPacketsProcessed).rightJustified(COLUMN_WIDTH, ' ')); statsString += QString(" Total Inbound Elements: %1 elements\r\n") .arg(locale.toString((uint)totalElementsProcessed).rightJustified(COLUMN_WIDTH, ' ')); - statsString += QString().sqDebug(" Average Inbound Elements/Packet: %f elements/packet\r", averageElementsPerPacket); + statsString += QString().sprintf(" Average Inbound Elements/Packet: %f elements/packet\r\n", averageElementsPerPacket); statsString += QString(" Average Transit Time/Packet: %1 usecs\r\n") .arg(locale.toString((uint)averageTransitTimePerPacket).rightJustified(COLUMN_WIDTH, ' ')); statsString += QString(" Average Process Time/Packet: %1 usecs\r\n") @@ -671,7 +671,7 @@ bool OctreeServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url // display memory usage stats statsString += "Current Memory Usage Statistics\r\n"; - statsString += QString().sqDebug("\r\nOctreeElement size... %ld bytes\r", sizeof(OctreeElement)); + statsString += QString().sprintf("\r\nOctreeElement size... %ld bytes\r\n", sizeof(OctreeElement)); statsString += "\r\n"; const char* memoryScaleLabel; @@ -738,8 +738,8 @@ bool OctreeServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url OctreeElement::getExternalChildrenCount(); statsString += " ----------------\r\n"; - statsString += QString().sqDebug(" Total: %10.llu nodes\r", checkSum); - statsString += QString().sqDebug(" Expected: %10.lu nodes\r", nodeCount); + statsString += QString().sprintf(" Total: %10.llu nodes\r\n", checkSum); + statsString += QString().sprintf(" Expected: %10.lu nodes\r\n", nodeCount); statsString += "\r\n"; statsString += "In other news....\r\n"; From 7d18dbdfb8da3e2c31e5827aab2e025690133eed Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 21 Apr 2014 16:35:42 -0700 Subject: [PATCH 556/595] more cleanup --- assignment-client/src/octree/OctreeServer.cpp | 24 +++++-------------- .../networking/src/ThreadedAssignment.cpp | 16 ------------- 2 files changed, 6 insertions(+), 34 deletions(-) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 04a69ff7e8..2b4a1d620d 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -1040,25 +1040,24 @@ void OctreeServer::run() { void OctreeServer::nodeAdded(SharedNodePointer node) { // we might choose to use this notifier to track clients in a pending state - //qDebug() << qPrintable(_safeServerName) << "server added node:" << *node; + qDebug() << qPrintable(_safeServerName) << "server added node:" << *node; } void OctreeServer::nodeKilled(SharedNodePointer node) { quint64 start = usecTimestampNow(); - //qDebug() << qPrintable(_safeServerName) << "server killed node:" << *node; + qDebug() << qPrintable(_safeServerName) << "server killed node:" << *node; OctreeQueryNode* nodeData = static_cast(node->getLinkedData()); if (nodeData) { nodeData->nodeKilled(); // tell our node data and sending threads that we'd like to shut down } else { - //qDebug() << qPrintable(_safeServerName) << "server node missing linked data node:" << *node; + qDebug() << qPrintable(_safeServerName) << "server node missing linked data node:" << *node; } quint64 end = usecTimestampNow(); quint64 usecsElapsed = (end - start); if (usecsElapsed > 1000) { - qDebug() << qPrintable(_safeServerName) << "server nodeKilled() took: " << usecsElapsed << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"; - // << " usecs for node:" << *node; + qDebug() << qPrintable(_safeServerName) << "server nodeKilled() took: " << usecsElapsed << " usecs for node:" << *node; } } @@ -1075,8 +1074,8 @@ void OctreeServer::forceNodeShutdown(SharedNodePointer node) { quint64 end = usecTimestampNow(); quint64 usecsElapsed = (end - start); - qDebug() << qPrintable(_safeServerName) << "server forceNodeShutdown() took: " - << usecsElapsed << " usecs for node:" << *node; + qDebug() << qPrintable(_safeServerName) << "server forceNodeShutdown() took: " + << usecsElapsed << " usecs for node:" << *node; } @@ -1189,17 +1188,6 @@ QString OctreeServer::getStatusLink() { } void OctreeServer::sendStatsPacket() { - - /* - quint64 start = usecTimestampNow(); - static QJsonObject statsObject1; - ThreadedAssignment::addPacketStatsAndSendStatsPacket(statsObject1); - quint64 end = usecTimestampNow(); - if (end - start > 1000) { - qDebug() << "OctreeServer::sendStatsPacket() took:" << (end - start); - } - */ - // TODO: we have too many stats to fit in a single MTU... so for now, we break it into multiple JSON objects and // send them separately. What we really should do is change the NodeList::sendStatsToDomainServer() to handle the // the following features: diff --git a/libraries/networking/src/ThreadedAssignment.cpp b/libraries/networking/src/ThreadedAssignment.cpp index ebb1435e63..4b92f8ba38 100644 --- a/libraries/networking/src/ThreadedAssignment.cpp +++ b/libraries/networking/src/ThreadedAssignment.cpp @@ -12,10 +12,8 @@ #include #include #include -#include #include "Logging.h" -#include "SharedUtil.h" #include "ThreadedAssignment.h" ThreadedAssignment::ThreadedAssignment(const QByteArray& packet) : @@ -58,9 +56,6 @@ void ThreadedAssignment::commonInit(const QString& targetName, NodeType_t nodeTy connect(statsTimer, &QTimer::timeout, this, &ThreadedAssignment::sendStatsPacket); statsTimer->start(1000); } - - //qDebug() << "ThreadedAssignment::commonInit()... thread()->eventDispatcher()=" << thread()->eventDispatcher(); - } void ThreadedAssignment::addPacketStatsAndSendStatsPacket(QJsonObject &statsObject) { @@ -81,18 +76,7 @@ void ThreadedAssignment::sendStatsPacket() { addPacketStatsAndSendStatsPacket(statsObject); } -quint64 lastCheckIn = usecTimestampNow(); void ThreadedAssignment::checkInWithDomainServerOrExit() { - - //qDebug() << "ThreadedAssignment::checkInWithDomainServerOrExit()... thread()->eventDispatcher()=" << thread()->eventDispatcher(); - - - quint64 now = usecTimestampNow(); - if ((now - lastCheckIn) > 1100000) { - qDebug() << "ThreadedAssignment::checkInWithDomainServerOrExit(): since lastCheckIn=" << (now - lastCheckIn) << "usecs"; - } - lastCheckIn = now; - if (NodeList::getInstance()->getNumNoReplyDomainCheckIns() == MAX_SILENT_DOMAIN_SERVER_CHECK_INS) { setFinished(true); } else { From a64d3ffc3204901953fb53123adef1bda543e87e Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 21 Apr 2014 16:38:45 -0700 Subject: [PATCH 557/595] more cleanup --- assignment-client/src/octree/OctreeSendThread.h | 1 - 1 file changed, 1 deletion(-) diff --git a/assignment-client/src/octree/OctreeSendThread.h b/assignment-client/src/octree/OctreeSendThread.h index 470b707fac..d8eed27802 100644 --- a/assignment-client/src/octree/OctreeSendThread.h +++ b/assignment-client/src/octree/OctreeSendThread.h @@ -17,7 +17,6 @@ #include #include #include -#include #include "OctreeQueryNode.h" From be2db49e08be2fa49faed4d0f62b3106b226d4cd Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 21 Apr 2014 16:44:21 -0700 Subject: [PATCH 558/595] Last touch to removing gettimeofday --- libraries/shared/src/SharedUtil.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index dca9426cb4..a13772d862 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -20,6 +20,7 @@ #endif #include +#include #include "OctalCode.h" #include "SharedUtil.h" @@ -30,9 +31,8 @@ void usecTimestampNowForceClockSkew(int clockSkew) { } quint64 usecTimestampNow() { - timeval now; - gettimeofday(&now, NULL); - return (now.tv_sec * 1000000 + now.tv_usec) + ::usecTimestampNowAdjust; + qint64 msecSinceEpoch = QDateTime::currentMSecsSinceEpoch(); + return msecSinceEpoch * 1000 + ::usecTimestampNowAdjust; } float randFloat() { From fd20686f0f854a33d897c5973535fd57c2e1fd60 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 21 Apr 2014 17:23:06 -0700 Subject: [PATCH 559/595] Removed Systime.h includes --- assignment-client/src/audio/AudioMixer.cpp | 2 -- interface/src/Application.cpp | 4 ---- interface/src/Audio.h | 4 ---- interface/src/Util.h | 6 ------ interface/src/devices/OculusManager.cpp | 4 ---- interface/src/devices/TV3DManager.cpp | 5 ----- interface/src/starfield/Controller.cpp | 4 ---- interface/src/starfield/Generator.cpp | 4 ---- interface/src/ui/BandwidthMeter.h | 4 ---- libraries/networking/src/Assignment.h | 6 ------ libraries/shared/src/PerfStat.h | 6 ------ libraries/shared/src/SharedUtil.h | 6 ------ 12 files changed, 55 deletions(-) diff --git a/assignment-client/src/audio/AudioMixer.cpp b/assignment-client/src/audio/AudioMixer.cpp index 65d09f1b00..5fd9efedd7 100644 --- a/assignment-client/src/audio/AudioMixer.cpp +++ b/assignment-client/src/audio/AudioMixer.cpp @@ -21,12 +21,10 @@ #include #ifdef _WIN32 -#include "Systime.h" #include #else #include #include -#include #include #endif //_WIN32 diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index b13013cbe2..1e3d3a2259 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -9,10 +9,6 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifdef WIN32 -#include -#endif - #include #include diff --git a/interface/src/Audio.h b/interface/src/Audio.h index f8315b1aab..7ad1ddd926 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -12,10 +12,6 @@ #ifndef hifi_Audio_h #define hifi_Audio_h -#ifdef _WIN32 -#include -#endif - #include #include diff --git a/interface/src/Util.h b/interface/src/Util.h index dee0f864b4..02cfd99f9a 100644 --- a/interface/src/Util.h +++ b/interface/src/Util.h @@ -12,12 +12,6 @@ #ifndef hifi_Util_h #define hifi_Util_h -#ifdef _WIN32 -#include "Systime.h" -#else -#include -#endif - #include #include #include diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index d3da8fe7c3..854b19236d 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -11,10 +11,6 @@ #include "InterfaceConfig.h" -#ifdef WIN32 -#include -#endif - #include #include diff --git a/interface/src/devices/TV3DManager.cpp b/interface/src/devices/TV3DManager.cpp index fcbef0385c..b5cc28b07f 100644 --- a/interface/src/devices/TV3DManager.cpp +++ b/interface/src/devices/TV3DManager.cpp @@ -15,11 +15,6 @@ #include - -#ifdef WIN32 -#include -#endif - #include "Application.h" #include "TV3DManager.h" diff --git a/interface/src/starfield/Controller.cpp b/interface/src/starfield/Controller.cpp index 2476c33d45..e68243752c 100755 --- a/interface/src/starfield/Controller.cpp +++ b/interface/src/starfield/Controller.cpp @@ -9,10 +9,6 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifdef _WIN32 -#include -#endif - #include #include "starfield/Controller.h" diff --git a/interface/src/starfield/Generator.cpp b/interface/src/starfield/Generator.cpp index 869abc90a5..d9773e4452 100644 --- a/interface/src/starfield/Generator.cpp +++ b/interface/src/starfield/Generator.cpp @@ -9,10 +9,6 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifdef _WIN32 -#include -#endif - #include #include "starfield/Generator.h" diff --git a/interface/src/ui/BandwidthMeter.h b/interface/src/ui/BandwidthMeter.h index 6cf7e9ea63..c6a28a21c3 100644 --- a/interface/src/ui/BandwidthMeter.h +++ b/interface/src/ui/BandwidthMeter.h @@ -12,10 +12,6 @@ #ifndef hifi_BandwidthMeter_h #define hifi_BandwidthMeter_h -#ifdef _WIN32 -#include -#endif - #include #include diff --git a/libraries/networking/src/Assignment.h b/libraries/networking/src/Assignment.h index 041121f760..f0f7e8db1a 100644 --- a/libraries/networking/src/Assignment.h +++ b/libraries/networking/src/Assignment.h @@ -12,12 +12,6 @@ #ifndef hifi_Assignment_h #define hifi_Assignment_h -#ifdef _WIN32 -#include "Systime.h" -#else -#include -#endif - #include #include "NodeList.h" diff --git a/libraries/shared/src/PerfStat.h b/libraries/shared/src/PerfStat.h index 478c9afead..22cf14f207 100644 --- a/libraries/shared/src/PerfStat.h +++ b/libraries/shared/src/PerfStat.h @@ -18,12 +18,6 @@ #include #include "SharedUtil.h" -#ifdef _WIN32 -#include "Systime.h" -#else -#include -#endif - #include #include #include diff --git a/libraries/shared/src/SharedUtil.h b/libraries/shared/src/SharedUtil.h index 87647a9e73..4a3fe2a129 100644 --- a/libraries/shared/src/SharedUtil.h +++ b/libraries/shared/src/SharedUtil.h @@ -24,12 +24,6 @@ #include -#ifdef _WIN32 -#include "Systime.h" -#else -#include -#endif - const int BYTES_PER_COLOR = 3; const int BYTES_PER_FLAGS = 1; typedef unsigned char rgbColor[BYTES_PER_COLOR]; From 91d8e113930942e61084c027b2a1391372c2e436 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 21 Apr 2014 17:34:01 -0700 Subject: [PATCH 560/595] return the bytes sent in writeDatagram() and writeUnverifiedDatagram() --- libraries/networking/src/LimitedNodeList.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index 2c7ab2f5a8..ce78ec2d10 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -227,7 +227,7 @@ qint64 LimitedNodeList::writeDatagram(const QByteArray& datagram, const SharedNo } } - writeDatagram(datagram, *destinationSockAddr, destinationNode->getConnectionSecret()); + return writeDatagram(datagram, *destinationSockAddr, destinationNode->getConnectionSecret()); } // didn't have a destinationNode to send to, return 0 @@ -249,9 +249,8 @@ qint64 LimitedNodeList::writeUnverifiedDatagram(const QByteArray& datagram, cons } } - // don't use the node secret! - writeDatagram(datagram, *destinationSockAddr, QUuid()); + return writeDatagram(datagram, *destinationSockAddr, QUuid()); } // didn't have a destinationNode to send to, return 0 From 60b8ab0de5e98c6bb66c45c879603473aa648df0 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 21 Apr 2014 17:45:38 -0700 Subject: [PATCH 561/595] CR feedback --- assignment-client/src/octree/OctreeServer.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 2b4a1d620d..bd04dd85d7 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -839,6 +839,11 @@ void OctreeServer::readPendingDatagrams() { nodeList->updateNodeWithDataFromPacket(matchingNode, receivedPacket); OctreeQueryNode* nodeData = (OctreeQueryNode*) matchingNode->getLinkedData(); if (nodeData && !nodeData->isOctreeSendThreadInitalized()) { + + // NOTE: this is an important aspect of the proper ref counting. The send threads/node data need to + // know that the OctreeServer/Assignment will not get deleted on it while it's still active. The + // solution is to get the shared pointer for the current assignment. We need to make sure this is the + // same SharedAssignmentPointer that was ref counted by the assignment client. SharedAssignmentPointer sharedAssignment = AssignmentClient::getCurrentAssignment(); nodeData->initializeOctreeSendThread(sharedAssignment, matchingNode); } From 8d6fa8f90471a5cc60ea444e52c1e03e2614d562 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Mon, 21 Apr 2014 18:19:59 -0700 Subject: [PATCH 562/595] fix sphere-vs-axis-aligned-cube logic --- libraries/shared/src/ShapeCollider.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/libraries/shared/src/ShapeCollider.cpp b/libraries/shared/src/ShapeCollider.cpp index 1b49caab22..c0de3cb90b 100644 --- a/libraries/shared/src/ShapeCollider.cpp +++ b/libraries/shared/src/ShapeCollider.cpp @@ -15,6 +15,7 @@ #include "GeometryUtil.h" #include "ShapeCollider.h" +#include "StreamUtils.h" // NOTE: // @@ -601,9 +602,9 @@ bool sphereAACube(const glm::vec3& sphereCenter, float sphereRadius, const glm:: // compute the nearest point on cube float maxBA = glm::max(glm::max(fabs(BA.x), fabs(BA.y)), fabs(BA.z)); glm::vec3 surfaceB = cubeCenter - (0.5f * cubeSide / maxBA) * BA; - // collision happens when "vector to surfaceB from surfaceA" dots with BA to produce a positive value + // collision happens when "vector to surfaceB from surfaceA" dots with BA to produce a negative value glm::vec3 surfaceBA = surfaceB - surfaceA; - if (glm::dot(surfaceBA, BA) > 0.f) { + if (glm::dot(surfaceBA, BA) < 0.f) { CollisionInfo* collision = collisions.getNewCollision(); if (collision) { collision->_penetration = surfaceBA; From 1782e803c9d7c82a50f04fdeb99aa950c860a1ec Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Mon, 21 Apr 2014 18:21:39 -0700 Subject: [PATCH 563/595] remove include StreamUtils.h --- libraries/shared/src/ShapeCollider.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/libraries/shared/src/ShapeCollider.cpp b/libraries/shared/src/ShapeCollider.cpp index c0de3cb90b..16624f9fec 100644 --- a/libraries/shared/src/ShapeCollider.cpp +++ b/libraries/shared/src/ShapeCollider.cpp @@ -15,7 +15,6 @@ #include "GeometryUtil.h" #include "ShapeCollider.h" -#include "StreamUtils.h" // NOTE: // From 63c02f2b04e846bb861b1176d39710a992999b7a Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Mon, 21 Apr 2014 18:22:34 -0700 Subject: [PATCH 564/595] add subscript operator for CollisionList --- libraries/shared/src/CollisionInfo.cpp | 3 +++ libraries/shared/src/CollisionInfo.h | 2 ++ 2 files changed, 5 insertions(+) diff --git a/libraries/shared/src/CollisionInfo.cpp b/libraries/shared/src/CollisionInfo.cpp index 5a4188a1ef..6b2f48f4d0 100644 --- a/libraries/shared/src/CollisionInfo.cpp +++ b/libraries/shared/src/CollisionInfo.cpp @@ -48,3 +48,6 @@ void CollisionList::clear() { _size = 0; } +const CollisionInfo* CollisionList::operator[](int index) const { + return (index > -1 && index < _size) ? &(_collisions[index]) : NULL; +} diff --git a/libraries/shared/src/CollisionInfo.h b/libraries/shared/src/CollisionInfo.h index f575dd8595..209a7e6127 100644 --- a/libraries/shared/src/CollisionInfo.h +++ b/libraries/shared/src/CollisionInfo.h @@ -95,6 +95,8 @@ public: /// Clear valid collisions. void clear(); + const CollisionInfo* operator[](int index) const; + private: int _maxSize; // the container cannot get larger than this int _size; // the current number of valid collisions in the list From 06794f33f3a4b480ec8158656af4e40c4ac7c472 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Mon, 21 Apr 2014 18:23:19 -0700 Subject: [PATCH 565/595] add accessor for Model::_boundingShape --- interface/src/renderer/Model.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index 65b79fffdd..a14b58c11a 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -193,6 +193,8 @@ public: /// Sets blended vertices computed in a separate thread. void setBlendedVertices(const QVector& vertices, const QVector& normals); + const CapsuleShape& getBoundingShape() const { return _boundingShape; } + protected: QSharedPointer _geometry; From 1846036659ae4bd9194351d0430a4ce021cfb926 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 21 Apr 2014 20:58:43 -0700 Subject: [PATCH 566/595] quite the error messages about faild locks --- interface/src/voxels/VoxelSystem.cpp | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/interface/src/voxels/VoxelSystem.cpp b/interface/src/voxels/VoxelSystem.cpp index 8d59f33674..b93662cd0d 100644 --- a/interface/src/voxels/VoxelSystem.cpp +++ b/interface/src/voxels/VoxelSystem.cpp @@ -938,6 +938,8 @@ void VoxelSystem::copyWrittenDataSegmentToReadArrays(glBufferIndex segmentStart, } void VoxelSystem::copyWrittenDataToReadArrays(bool fullVBOs) { + static unsigned int lockForReadAttempt = 0; + static unsigned int lockForWriteAttempt = 0; PerformanceWarning warn(Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings), "copyWrittenDataToReadArrays()"); @@ -946,7 +948,9 @@ void VoxelSystem::copyWrittenDataToReadArrays(bool fullVBOs) { // time around, the only side effect is the VBOs won't be updated this frame const int WAIT_FOR_LOCK_IN_MS = 5; if (_readArraysLock.tryLockForWrite(WAIT_FOR_LOCK_IN_MS)) { + lockForWriteAttempt = 0; if (_writeArraysLock.tryLockForRead(WAIT_FOR_LOCK_IN_MS)) { + lockForReadAttempt = 0; if (_voxelsDirty && _voxelsUpdated) { if (fullVBOs) { copyWrittenDataToReadArraysFullVBOs(); @@ -956,11 +960,19 @@ void VoxelSystem::copyWrittenDataToReadArrays(bool fullVBOs) { } _writeArraysLock.unlock(); } else { - qDebug() << "couldn't get _writeArraysLock.LockForRead()..."; + lockForReadAttempt++; + // only report error of first failure + if (lockForReadAttempt == 1) { + qDebug() << "couldn't get _writeArraysLock.LockForRead()..."; + } } _readArraysLock.unlock(); } else { - qDebug() << "couldn't get _readArraysLock.LockForWrite()..."; + lockForWriteAttempt++; + // only report error of first failure + if (lockForWriteAttempt == 1) { + qDebug() << "couldn't get _readArraysLock.LockForWrite()..."; + } } } From ff7a1bd60fb615c68744cf93c8ee47037a2e4e08 Mon Sep 17 00:00:00 2001 From: matsukaze Date: Tue, 22 Apr 2014 06:53:59 -0400 Subject: [PATCH 567/595] Job #19574. Add audio oscilloscope.' --- interface/src/Application.cpp | 2 + interface/src/Audio.cpp | 174 +++++++++++++++++++++++++++++++++- interface/src/Audio.h | 26 +++++ interface/src/Menu.cpp | 8 ++ interface/src/Menu.h | 3 +- interface/src/ui/InfoView.cpp | 4 +- 6 files changed, 213 insertions(+), 4 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index cd07f21300..a9f4c8eed7 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2648,6 +2648,8 @@ void Application::displayOverlay() { audioMeterY, Menu::getInstance()->isOptionChecked(MenuOption::Mirror)); + _audio.renderScope(_glWidget->width(), _glWidget->height()); + glBegin(GL_QUADS); if (isClipping) { glColor3f(1, 0, 0); diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 698a8db725..1e85e77883 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -92,7 +92,14 @@ Audio::Audio(int16_t initialJitterBufferSamples, QObject* parent) : _processSpatialAudio(false), _spatialAudioStart(0), _spatialAudioFinish(0), - _spatialAudioRingBuffer(NETWORK_BUFFER_LENGTH_BYTES_PER_CHANNEL, true) // random access mode + _spatialAudioRingBuffer(NETWORK_BUFFER_LENGTH_BYTES_PER_CHANNEL, true), // random access mode + _scopeEnabled(false), + _scopeEnabledPause(false), + _scopeInputOffset(0), + _scopeOutputOffset(0), + _scopeInput(SAMPLES_PER_SCOPE_H * sizeof(int16_t), 0), + _scopeOutputLeft(SAMPLES_PER_SCOPE_H * sizeof(int16_t), 0), + _scopeOutputRight(SAMPLES_PER_SCOPE_H * sizeof(int16_t), 0) { // clear the array of locally injected samples memset(_localProceduralSamples, 0, NETWORK_BUFFER_LENGTH_BYTES_PER_CHANNEL); @@ -575,6 +582,14 @@ void Audio::handleAudioInput() { processProceduralAudio(monoAudioSamples, NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL); } + if (_scopeEnabled && !_scopeEnabledPause) { + unsigned int numMonoAudioChannels = 1; + unsigned int monoAudioChannel = 0; + addBufferToScope(_scopeInput, _scopeInputOffset, monoAudioSamples, monoAudioChannel, numMonoAudioChannels); + _scopeInputOffset += NETWORK_SAMPLES_PER_FRAME; + _scopeInputOffset %= SAMPLES_PER_SCOPE_H; + } + NodeList* nodeList = NodeList::getInstance(); SharedNodePointer audioMixer = nodeList->soloNodeOfType(NodeType::AudioMixer); @@ -813,6 +828,30 @@ void Audio::processReceivedAudio(const QByteArray& audioByteArray) { if (_outputDevice) { _outputDevice->write(outputBuffer); } + + if (_scopeEnabled && !_scopeEnabledPause) { + unsigned int numAudioChannels = _desiredOutputFormat.channelCount(); + int16_t* samples = ringBufferSamples; + for (int numSamples = numNetworkOutputSamples / numAudioChannels; numSamples > 0; numSamples -= NETWORK_SAMPLES_PER_FRAME) { + + unsigned int audioChannel = 0; + addBufferToScope( + _scopeOutputLeft, + _scopeOutputOffset, + samples, audioChannel, numAudioChannels); + + audioChannel = 1; + addBufferToScope( + _scopeOutputRight, + _scopeOutputOffset, + samples, audioChannel, numAudioChannels); + + _scopeOutputOffset += NETWORK_SAMPLES_PER_FRAME; + _scopeOutputOffset %= SAMPLES_PER_SCOPE_H; + samples += NETWORK_SAMPLES_PER_FRAME * numAudioChannels; + } + } + delete[] ringBufferSamples; } } @@ -1019,6 +1058,139 @@ void Audio::renderToolBox(int x, int y, bool boxed) { glDisable(GL_TEXTURE_2D); } +void Audio::toggleScopePause() { + _scopeEnabledPause = !_scopeEnabledPause; +} + +void Audio::toggleScope() { + _scopeEnabled = !_scopeEnabled; + if (_scopeEnabled) { + static const int width = SAMPLES_PER_SCOPE_H; + _scopeInputOffset = 0; + _scopeOutputOffset = 0; + memset(_scopeInput.data(), 0, width * sizeof(int16_t)); + memset(_scopeOutputLeft.data(), 0, width * sizeof(int16_t)); + memset(_scopeOutputRight.data(), 0, width * sizeof(int16_t)); + } +} + +void Audio::addBufferToScope( + QByteArray& byteArray, unsigned int frameOffset, const int16_t* src, unsigned int srcChannel, unsigned int srcNumChannels) { + + int16_t* tgt = (int16_t*)byteArray.data() + frameOffset; + src += srcChannel; + + for (int i = NETWORK_SAMPLES_PER_FRAME; --i >= 0; src += srcNumChannels) { + float sample = (float)*src; + float multiplier = (float)MULTIPLIER_SCOPE_V / logf(2.0f); + int16_t value; + + if (sample > 0) { + value = (int16_t)(multiplier * logf(sample)); + } else if (sample < 0) { + value = (int16_t)(-multiplier * logf(-sample)); + } else { + value = 0; + } + + *tgt++ = value; + //*tgt++ = sample / 0x7fff * (SAMPLES_PER_SCOPE_V / 2); + } +} + +void Audio::renderScope(int width, int height) { + + if (!_scopeEnabled) + return; + + static const unsigned int backgroundColor = 0x33333399; + static const unsigned int gridColor = 0x44444499; + static const unsigned int inputColor = 0x44aa4499; + static const unsigned int outputLeftColor = 0xaa444499; + static const unsigned int outputRightColor = 0x4444aa99; + static const int gridRows = 2; + static const int gridCols = 5; + + int x = (width - SAMPLES_PER_SCOPE_H) / 2; + int y = (height - SAMPLES_PER_SCOPE_V) / 2; + int w = SAMPLES_PER_SCOPE_H; + int h = SAMPLES_PER_SCOPE_V; + + renderBackground(backgroundColor, x, y, w, h); + renderGrid(gridColor, x, y, w, h, gridRows, gridCols); + renderLineStrip(inputColor, x, y, w, _scopeInputOffset, _scopeInput); + renderLineStrip(outputLeftColor, x, y, w, _scopeOutputOffset, _scopeOutputLeft); + renderLineStrip(outputRightColor, x, y, w, _scopeOutputOffset, _scopeOutputRight); +} + +void Audio::renderBackground(unsigned int rgba, int x, int y, int width, int height) { + glBegin(GL_QUADS); + glColor4f(((rgba >> 24) & 0xff) / 255.0f, + ((rgba >> 16) & 0xff) / 255.0f, + ((rgba >> 8) & 0xff) / 255.0f, + (rgba & 0xff) / 255.0f); + glVertex2i(x, y); + glVertex2i(x + width, y); + glVertex2i(x + width, y + height); + glVertex2i(x , y + height); + glEnd(); + glColor4f(1, 1, 1, 1); +} + +void Audio::renderGrid(unsigned int rgba, int x, int y, int width, int height, int rows, int cols) { + glBegin(GL_LINES); + glColor4f(((rgba >> 24) & 0xff) / 255.0f, + ((rgba >> 16) & 0xff) / 255.0f, + ((rgba >> 8) & 0xff) / 255.0f, + (rgba & 0xff) / 255.0f); + + int dx = width / cols; + int dy = height / rows; + int tx = x; + int ty = y; + + // Draw horizontal grid lines + for (int i = rows + 1; --i >= 0; ) { + glVertex2i(x, ty); + glVertex2i(x + width, ty); + ty += dy; + } + // Draw vertical grid lines + for (int i = cols + 1; --i >= 0; ) { + glVertex2i(tx, y); + glVertex2i(tx, y + height); + tx += dx; + } + glEnd(); + glColor4f(1, 1, 1, 1); +} + +void Audio::renderLineStrip(unsigned int rgba, int x, int y, int n, int offset, const QByteArray& byteArray) { + + glColor4f(((rgba >> 24) & 0xff) / 255.0f, + ((rgba >> 16) & 0xff) / 255.0f, + ((rgba >> 8) & 0xff) / 255.0f, + (rgba & 0xff) / 255.0f); + + glBegin(GL_LINE_STRIP); + + int16_t sample; + int16_t* samples = ((int16_t*) byteArray.data()) + offset; + y += SAMPLES_PER_SCOPE_V / 2; + for (int i = n - offset; --i >= 0; ) { + sample = *samples++; + glVertex2i(x++, y - sample); + } + samples = (int16_t*) byteArray.data(); + for (int i = offset; --i >= 0; ) { + sample = *samples++; + glVertex2i(x++, y - sample); + } + glEnd(); + glColor4f(1, 1, 1, 1); +} + + bool Audio::switchInputToAudioDevice(const QAudioDeviceInfo& inputDeviceInfo) { bool supportedFormat = false; diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 96def43dd2..4d4501c93d 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -28,6 +28,7 @@ #include #include #include +#include #include #include @@ -67,6 +68,7 @@ public: bool mousePressEvent(int x, int y); void renderToolBox(int x, int y, bool boxed); + void renderScope(int width, int height); int getNetworkSampleRate() { return SAMPLE_RATE; } int getNetworkBufferLengthSamplesPerChannel() { return NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL; } @@ -83,6 +85,8 @@ public slots: void toggleMute(); void toggleAudioNoiseReduction(); void toggleToneInjection(); + void toggleScope(); + void toggleScopePause(); void toggleAudioSpatialProcessing(); virtual void handleAudioByteArray(const QByteArray& audioByteArray); @@ -196,6 +200,28 @@ private: int calculateNumberOfFrameSamples(int numBytes); float calculateDeviceToNetworkInputRatio(int numBytes); + // Audio scope methods for data acquisition + void addBufferToScope(QByteArray& byteArray, unsigned int frameOffset, const int16_t* src, unsigned int srcChannel, unsigned int srcNumChannels); + + // Audio scope methods for rendering + void renderBackground(unsigned int rgba, int x, int y, int width, int height); + void renderGrid(unsigned int rgba, int x, int y, int width, int height, int rows, int cols); + void renderLineStrip(unsigned int rgba, int x, int y, int n, int offset, const QByteArray& byteArray); + + // Audio scope data + static const unsigned int NETWORK_SAMPLES_PER_FRAME = NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL; + static const unsigned int FRAMES_PER_SCOPE = 5; + static const unsigned int SAMPLES_PER_SCOPE_H = FRAMES_PER_SCOPE * NETWORK_SAMPLES_PER_FRAME; + static const unsigned int MULTIPLIER_SCOPE_V = 20; + static const unsigned int SAMPLES_PER_SCOPE_V = 2 * 15 * MULTIPLIER_SCOPE_V; + bool _scopeEnabled; + bool _scopeEnabledPause; + int _scopeInputOffset; + int _scopeOutputOffset; + QByteArray _scopeInput; + QByteArray _scopeOutputLeft; + QByteArray _scopeOutputRight; + }; diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 7cdd72afd5..2e4abaa17d 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -259,6 +259,9 @@ Menu::Menu() : addCheckableActionToQMenuAndActionHash(viewMenu, MenuOption::Bandwidth, 0, true); addActionToQMenuAndActionHash(viewMenu, MenuOption::BandwidthDetails, 0, this, SLOT(bandwidthDetails())); addActionToQMenuAndActionHash(viewMenu, MenuOption::OctreeStats, 0, this, SLOT(octreeStatsDetails())); + addCheckableActionToQMenuAndActionHash(viewMenu, MenuOption::AudioScope, 0, false, + appInstance->getAudio(), + SLOT(toggleScope())); QMenu* developerMenu = addMenu("Developer"); @@ -385,6 +388,11 @@ Menu::Menu() : false, appInstance->getAudio(), SLOT(toggleToneInjection())); + addCheckableActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioScopePause, + Qt::CTRL | Qt::Key_P, + false, + appInstance->getAudio(), + SLOT(toggleScopePause())); QMenu* spatialAudioMenu = audioDebugMenu->addMenu("Spatial Audio"); diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 597ae4a74b..ddcd0571f8 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -256,8 +256,9 @@ namespace MenuOption { const QString AmbientOcclusion = "Ambient Occlusion"; const QString Atmosphere = "Atmosphere"; const QString AudioNoiseReduction = "Audio Noise Reduction"; + const QString AudioScope = "Audio Scope"; + const QString AudioScopePause = "Pause Audio Scope"; const QString AudioToneInjection = "Inject Test Tone"; - const QString AudioSpatialProcessing = "Audio Spatial Processing"; const QString AudioSpatialProcessingHeadOriented = "Head Oriented"; const QString AudioSpatialProcessingIncludeOriginal = "Includes Network Original"; diff --git a/interface/src/ui/InfoView.cpp b/interface/src/ui/InfoView.cpp index 06de3fdf2e..99a4f8cb06 100644 --- a/interface/src/ui/InfoView.cpp +++ b/interface/src/ui/InfoView.cpp @@ -28,8 +28,8 @@ InfoView::InfoView(bool forced) : QString absPath = QFileInfo(Application::resourcesPath() + "html/interface-welcome-allsvg.html").absoluteFilePath(); QUrl url = QUrl::fromLocalFile(absPath); - load(url); - connect(this, SIGNAL(loadFinished(bool)), this, SLOT(loaded(bool))); +// load(url); +// connect(this, SIGNAL(loadFinished(bool)), this, SLOT(loaded(bool))); } void InfoView::showFirstTime() { From 6c89521f1d136486fde387c256e85c7c31650701 Mon Sep 17 00:00:00 2001 From: Thijs Wenker Date: Tue, 22 Apr 2014 13:12:21 +0200 Subject: [PATCH 568/595] Style --- interface/src/ScriptHighlighting.cpp | 6 +++--- interface/src/ui/ScriptEditorWidget.cpp | 2 +- interface/src/ui/ScriptEditorWindow.cpp | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/interface/src/ScriptHighlighting.cpp b/interface/src/ScriptHighlighting.cpp index 9b58298b62..3ab1394097 100644 --- a/interface/src/ScriptHighlighting.cpp +++ b/interface/src/ScriptHighlighting.cpp @@ -29,7 +29,7 @@ void ScriptHighlighting::highlightBlock(const QString& text) { this->formatNumbers(text); this->formatTrueFalse(text); this->formatQoutedText(text); - this->formatComments(text); + this->formatComments(text); } void ScriptHighlighting::highlightKeywords(const QString& text) { @@ -54,7 +54,7 @@ void ScriptHighlighting::formatComments(const QString& text) { start = text.indexOf(_multiLineCommentBegin, start + length); if (end == -1) { setCurrentBlockState(BlockStateInMultiComment); - } + } } int index = _singleLineComment.indexIn(text); @@ -92,4 +92,4 @@ void ScriptHighlighting::formatTrueFalse(const QString& text){ setFormat(index, length, *font); index = _truefalseRegex.indexIn(text, index + length); } -} \ No newline at end of file +} diff --git a/interface/src/ui/ScriptEditorWidget.cpp b/interface/src/ui/ScriptEditorWidget.cpp index 74b74e1ad6..1765a5ea1a 100644 --- a/interface/src/ui/ScriptEditorWidget.cpp +++ b/interface/src/ui/ScriptEditorWidget.cpp @@ -155,4 +155,4 @@ void ScriptEditorWidget::onScriptError(const QString& message) { void ScriptEditorWidget::onScriptPrint(const QString& message) { _scriptEditorWidgetUI->debugText->appendPlainText("> " + message); -} \ No newline at end of file +} diff --git a/interface/src/ui/ScriptEditorWindow.cpp b/interface/src/ui/ScriptEditorWindow.cpp index ec63e0341d..0c34959353 100644 --- a/interface/src/ui/ScriptEditorWindow.cpp +++ b/interface/src/ui/ScriptEditorWindow.cpp @@ -197,4 +197,4 @@ void ScriptEditorWindow::updateScriptNameOrStatus() { this->setWindowTitle("Script Editor [New script" + modifiedStar + "]"); } } -} \ No newline at end of file +} From 99cb1da5ec16eaeeda12a9b1a131594859aa6cae Mon Sep 17 00:00:00 2001 From: matsukaze Date: Tue, 22 Apr 2014 07:40:31 -0400 Subject: [PATCH 569/595] Reverting inadvertently committed local changes. --- interface/src/ui/InfoView.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/ui/InfoView.cpp b/interface/src/ui/InfoView.cpp index 99a4f8cb06..06de3fdf2e 100644 --- a/interface/src/ui/InfoView.cpp +++ b/interface/src/ui/InfoView.cpp @@ -28,8 +28,8 @@ InfoView::InfoView(bool forced) : QString absPath = QFileInfo(Application::resourcesPath() + "html/interface-welcome-allsvg.html").absoluteFilePath(); QUrl url = QUrl::fromLocalFile(absPath); -// load(url); -// connect(this, SIGNAL(loadFinished(bool)), this, SLOT(loaded(bool))); + load(url); + connect(this, SIGNAL(loadFinished(bool)), this, SLOT(loaded(bool))); } void InfoView::showFirstTime() { From 7cb6856415178e09a01c4e38e712f65c56143400 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 22 Apr 2014 10:44:41 -0700 Subject: [PATCH 570/595] Adding some collision tests for sphere-vs-AACube --- tests/physics/src/ShapeColliderTests.cpp | 113 +++++++++++++++++++++++ tests/physics/src/ShapeColliderTests.h | 3 + 2 files changed, 116 insertions(+) diff --git a/tests/physics/src/ShapeColliderTests.cpp b/tests/physics/src/ShapeColliderTests.cpp index f9e76bac0b..fe1d79b456 100644 --- a/tests/physics/src/ShapeColliderTests.cpp +++ b/tests/physics/src/ShapeColliderTests.cpp @@ -699,6 +699,116 @@ void ShapeColliderTests::capsuleTouchesCapsule() { } } +void ShapeColliderTests::sphereTouchesAACube() { + CollisionList collisions(16); + + glm::vec3 cubeCenter(1.23f, 4.56f, 7.89f); + float cubeSide = 2.0f; + + float sphereRadius = 1.0f; + glm::vec3 sphereCenter(0.f); + SphereShape sphere(sphereRadius, sphereCenter); + + float sphereOffset = (0.5f * cubeSide + sphereRadius - 0.25f); + + // top + sphereCenter = cubeCenter + sphereOffset * yAxis; + sphere.setPosition(sphereCenter); + if (!ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should collide with cube" << std::endl; + } + + // bottom + sphereCenter = cubeCenter - sphereOffset * yAxis; + sphere.setPosition(sphereCenter); + if (!ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should collide with cube" << std::endl; + } + + // left + sphereCenter = cubeCenter + sphereOffset * xAxis; + sphere.setPosition(sphereCenter); + if (!ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should collide with cube" << std::endl; + } + + // right + sphereCenter = cubeCenter - sphereOffset * xAxis; + sphere.setPosition(sphereCenter); + if (!ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should collide with cube" << std::endl; + } + + // forward + sphereCenter = cubeCenter + sphereOffset * zAxis; + sphere.setPosition(sphereCenter); + if (!ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should collide with cube" << std::endl; + } + + // back + sphereCenter = cubeCenter - sphereOffset * zAxis; + sphere.setPosition(sphereCenter); + if (!ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should collide with cube" << std::endl; + } +} + +void ShapeColliderTests::sphereMissesAACube() { + CollisionList collisions(16); + + glm::vec3 cubeCenter(1.23f, 4.56f, 7.89f); + float cubeSide = 2.0f; + + float sphereRadius = 1.0f; + glm::vec3 sphereCenter(0.0f); + SphereShape sphere(sphereRadius, sphereCenter); + + float sphereOffset = (0.5f * cubeSide + sphereRadius + 0.25f); + + // top + sphereCenter = cubeCenter + sphereOffset * yAxis; + sphere.setPosition(sphereCenter); + if (ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should NOT collide with cube" << std::endl; + } + + // bottom + sphereCenter = cubeCenter - sphereOffset * yAxis; + sphere.setPosition(sphereCenter); + if (ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should NOT collide with cube" << std::endl; + } + + // left + sphereCenter = cubeCenter + sphereOffset * xAxis; + sphere.setPosition(sphereCenter); + if (ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should NOT collide with cube" << std::endl; + } + + // right + sphereCenter = cubeCenter - sphereOffset * xAxis; + sphere.setPosition(sphereCenter); + if (ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should NOT collide with cube" << std::endl; + } + + // forward + sphereCenter = cubeCenter + sphereOffset * zAxis; + sphere.setPosition(sphereCenter); + if (ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should NOT collide with cube" << std::endl; + } + + // back + sphereCenter = cubeCenter - sphereOffset * zAxis; + sphere.setPosition(sphereCenter); + if (ShapeCollider::sphereAACube(&sphere, cubeCenter, cubeSide, collisions)){ + std::cout << __FILE__ << ":" << __LINE__ << " ERROR: sphere should NOT collide with cube" << std::endl; + } +} + void ShapeColliderTests::runAllTests() { sphereMissesSphere(); @@ -709,4 +819,7 @@ void ShapeColliderTests::runAllTests() { capsuleMissesCapsule(); capsuleTouchesCapsule(); + + sphereTouchesAACube(); + sphereMissesAACube(); } diff --git a/tests/physics/src/ShapeColliderTests.h b/tests/physics/src/ShapeColliderTests.h index 1d468a65d2..a94f5050ff 100644 --- a/tests/physics/src/ShapeColliderTests.h +++ b/tests/physics/src/ShapeColliderTests.h @@ -23,6 +23,9 @@ namespace ShapeColliderTests { void capsuleMissesCapsule(); void capsuleTouchesCapsule(); + void sphereTouchesAACube(); + void sphereMissesAACube(); + void runAllTests(); } From a45bc6c110355a5d187b7906a55e6c550b7c36b7 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 22 Apr 2014 10:48:05 -0700 Subject: [PATCH 571/595] remove const from CollisionList subscript operator --- libraries/octree/src/Octree.cpp | 7 +++++-- libraries/shared/src/CollisionInfo.cpp | 2 +- libraries/shared/src/CollisionInfo.h | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/libraries/octree/src/Octree.cpp b/libraries/octree/src/Octree.cpp index 83b84b3c50..4bd37d873a 100644 --- a/libraries/octree/src/Octree.cpp +++ b/libraries/octree/src/Octree.cpp @@ -707,7 +707,7 @@ bool findCapsulePenetrationOp(OctreeElement* node, void* extraData) { } bool findShapeCollisionsOp(OctreeElement* node, void* extraData) { - const ShapeArgs* args = static_cast(extraData); + ShapeArgs* args = static_cast(extraData); // coarse check against bounds AABox cube = node->getAABox(); @@ -719,7 +719,10 @@ bool findShapeCollisionsOp(OctreeElement* node, void* extraData) { return true; // recurse on children } if (node->hasContent()) { - return ShapeCollider::collideShapeWithAACube(args->shape, cube.calcCenter(), cube.getScale(), args->collisions); + if (ShapeCollider::collideShapeWithAACube(args->shape, cube.calcCenter(), cube.getScale(), args->collisions)) { + args->found = true; + return true; + } } return false; } diff --git a/libraries/shared/src/CollisionInfo.cpp b/libraries/shared/src/CollisionInfo.cpp index 6b2f48f4d0..5d97842530 100644 --- a/libraries/shared/src/CollisionInfo.cpp +++ b/libraries/shared/src/CollisionInfo.cpp @@ -48,6 +48,6 @@ void CollisionList::clear() { _size = 0; } -const CollisionInfo* CollisionList::operator[](int index) const { +CollisionInfo* CollisionList::operator[](int index) { return (index > -1 && index < _size) ? &(_collisions[index]) : NULL; } diff --git a/libraries/shared/src/CollisionInfo.h b/libraries/shared/src/CollisionInfo.h index 209a7e6127..7db965fe64 100644 --- a/libraries/shared/src/CollisionInfo.h +++ b/libraries/shared/src/CollisionInfo.h @@ -95,7 +95,7 @@ public: /// Clear valid collisions. void clear(); - const CollisionInfo* operator[](int index) const; + CollisionInfo* operator[](int index); private: int _maxSize; // the container cannot get larger than this From 7537d240bb7a43db04d7020eb9ce02da5c1de142 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 22 Apr 2014 10:48:42 -0700 Subject: [PATCH 572/595] toward working avatar-vs-voxel collisions again --- interface/src/avatar/MyAvatar.cpp | 28 ++++++++++++++++++++++++++ libraries/shared/src/ShapeCollider.cpp | 14 ++++++++----- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 8229611646..4ce1c2ad39 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include @@ -795,7 +796,33 @@ void MyAvatar::updateCollisionWithEnvironment(float deltaTime, float radius) { } } +static CollisionList myCollisions(64); + void MyAvatar::updateCollisionWithVoxels(float deltaTime, float radius) { + static int foo = 0; + ++foo; + +// const float VOXEL_ELASTICITY = 0.4f; +// const float VOXEL_DAMPING = 0.0f; + const float VOXEL_COLLISION_FREQUENCY = 0.5f; + + myCollisions.clear(); + const CapsuleShape& boundingShape = _skeletonModel.getBoundingShape(); + if (Application::getInstance()->getVoxelTree()->findShapeCollisions(&boundingShape, myCollisions)) { + for (int i = 0; i < myCollisions.size(); ++i) { + CollisionInfo* collision = myCollisions[i]; + //if (0 == (foo % 100)) { + std::cout << "adebug " << myCollisions.size() << " collisions p = " << collision->_penetration << std::endl; // adebug + //} + //applyHardCollision(collision->_penetration, VOXEL_ELASTICITY, VOXEL_DAMPING); + } + updateCollisionSound(myCollisions[0]->_penetration, deltaTime, VOXEL_COLLISION_FREQUENCY); + } else if (myCollisions.size() == 0) { + if (0 == (foo % 100)) { + std::cout << "adebug 0 collisions capC = " << boundingShape.getPosition() << " capR = " << boundingShape.getRadius() << std::endl; // adebug + } + } + /* const float VOXEL_ELASTICITY = 0.4f; const float VOXEL_DAMPING = 0.0f; const float VOXEL_COLLISION_FREQUENCY = 0.5f; @@ -808,6 +835,7 @@ void MyAvatar::updateCollisionWithVoxels(float deltaTime, float radius) { updateCollisionSound(penetration, deltaTime, VOXEL_COLLISION_FREQUENCY); applyHardCollision(penetration, VOXEL_ELASTICITY, VOXEL_DAMPING); } + */ } void MyAvatar::applyHardCollision(const glm::vec3& penetration, float elasticity, float damping) { diff --git a/libraries/shared/src/ShapeCollider.cpp b/libraries/shared/src/ShapeCollider.cpp index 16624f9fec..30bea1fef1 100644 --- a/libraries/shared/src/ShapeCollider.cpp +++ b/libraries/shared/src/ShapeCollider.cpp @@ -15,6 +15,7 @@ #include "GeometryUtil.h" #include "ShapeCollider.h" +#include "StreamUtils.h" // NOTE: // @@ -601,14 +602,17 @@ bool sphereAACube(const glm::vec3& sphereCenter, float sphereRadius, const glm:: // compute the nearest point on cube float maxBA = glm::max(glm::max(fabs(BA.x), fabs(BA.y)), fabs(BA.z)); glm::vec3 surfaceB = cubeCenter - (0.5f * cubeSide / maxBA) * BA; - // collision happens when "vector to surfaceB from surfaceA" dots with BA to produce a negative value - glm::vec3 surfaceBA = surfaceB - surfaceA; - if (glm::dot(surfaceBA, BA) < 0.f) { + // collision happens when "vector to surfaceA from surfaceB" dots with BA to produce a positive value + glm::vec3 surfaceAB = surfaceA - surfaceB; + if (glm::dot(surfaceAB, BA) > 0.f) { CollisionInfo* collision = collisions.getNewCollision(); if (collision) { - collision->_penetration = surfaceBA; + glm::vec3 normal(floorf(BA.x/maxBA), floorf(BA.y/maxBA), floorf(BA.z/maxBA)); + std::cout << "adebug normal = " << normal << std::endl; // adebug + normal = glm::normalize(normal); + collision->_penetration = glm::dot(surfaceAB, normal) * normal; // contactPoint is on surface of A - collision->_contactPoint = surfaceA; + collision->_contactPoint = sphereCenter - sphereRadius * normal; return true; } } From ae443a3136d40a2fb2a4643a2f784e05861f7137 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 22 Apr 2014 11:27:50 -0700 Subject: [PATCH 573/595] fix headers --- examples/audioReflectorTools.js | 2 ++ examples/testingVoxelViewerRestart.js | 3 ++- interface/src/AudioReflector.h | 3 +++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/examples/audioReflectorTools.js b/examples/audioReflectorTools.js index 76869de578..f299407e54 100644 --- a/examples/audioReflectorTools.js +++ b/examples/audioReflectorTools.js @@ -7,6 +7,8 @@ // // Tools for manipulating the attributes of the AudioReflector behavior // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // diff --git a/examples/testingVoxelViewerRestart.js b/examples/testingVoxelViewerRestart.js index 4fbdee1223..c4ab67e8ba 100644 --- a/examples/testingVoxelViewerRestart.js +++ b/examples/testingVoxelViewerRestart.js @@ -5,7 +5,8 @@ // Created by Brad Hefta-Gaub on 2/26/14 // Copyright (c) 2014 HighFidelity, Inc. All rights reserved. // -// This is an example script +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // var count = 0; diff --git a/interface/src/AudioReflector.h b/interface/src/AudioReflector.h index 582345e064..1bfb52ea09 100644 --- a/interface/src/AudioReflector.h +++ b/interface/src/AudioReflector.h @@ -5,6 +5,9 @@ // Created by Brad Hefta-Gaub on 4/2/2014 // Copyright (c) 2014 High Fidelity, Inc. All rights reserved. // +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// #ifndef interface_AudioReflector_h #define interface_AudioReflector_h From 65d3b4dc39ebe0887d52943f74f1ddf2e0c92370 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 22 Apr 2014 11:43:23 -0700 Subject: [PATCH 574/595] fix penetration direction for sphere-vs-AACube --- libraries/shared/src/ShapeCollider.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/libraries/shared/src/ShapeCollider.cpp b/libraries/shared/src/ShapeCollider.cpp index 30bea1fef1..b4a1aaf90c 100644 --- a/libraries/shared/src/ShapeCollider.cpp +++ b/libraries/shared/src/ShapeCollider.cpp @@ -607,12 +607,15 @@ bool sphereAACube(const glm::vec3& sphereCenter, float sphereRadius, const glm:: if (glm::dot(surfaceAB, BA) > 0.f) { CollisionInfo* collision = collisions.getNewCollision(); if (collision) { - glm::vec3 normal(floorf(BA.x/maxBA), floorf(BA.y/maxBA), floorf(BA.z/maxBA)); - std::cout << "adebug normal = " << normal << std::endl; // adebug - normal = glm::normalize(normal); - collision->_penetration = glm::dot(surfaceAB, normal) * normal; + // penetration is parallel to box side direction + glm::vec3 direction; + modff(BA.x/maxBA, &(direction.x)); + modff(BA.y/maxBA, &(direction.y)); + modff(BA.z/maxBA, &(direction.z)); + direction = glm::normalize(direction); + collision->_penetration = glm::dot(surfaceAB, direction) * direction; // contactPoint is on surface of A - collision->_contactPoint = sphereCenter - sphereRadius * normal; + collision->_contactPoint = sphereCenter - sphereRadius * direction; return true; } } From 62121b1232e8d8c55f873fae2ec00129f540daed Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 22 Apr 2014 11:46:15 -0700 Subject: [PATCH 575/595] remove include of StreamUtils.h again --- libraries/shared/src/ShapeCollider.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/libraries/shared/src/ShapeCollider.cpp b/libraries/shared/src/ShapeCollider.cpp index b4a1aaf90c..458c355221 100644 --- a/libraries/shared/src/ShapeCollider.cpp +++ b/libraries/shared/src/ShapeCollider.cpp @@ -15,7 +15,6 @@ #include "GeometryUtil.h" #include "ShapeCollider.h" -#include "StreamUtils.h" // NOTE: // From 3eeb3a539dda788907121e1f32a5e9dc6883e242 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 22 Apr 2014 11:48:43 -0700 Subject: [PATCH 576/595] Fixed lack of resolution in usecTimestampNow() --- assignment-client/src/main.cpp | 1 + domain-server/src/main.cpp | 2 ++ interface/src/main.cpp | 1 + libraries/shared/src/SharedUtil.cpp | 22 +++++++++++++++++++--- libraries/shared/src/SharedUtil.h | 1 + 5 files changed, 24 insertions(+), 3 deletions(-) diff --git a/assignment-client/src/main.cpp b/assignment-client/src/main.cpp index 24d19ddef6..7132b5c38a 100644 --- a/assignment-client/src/main.cpp +++ b/assignment-client/src/main.cpp @@ -17,6 +17,7 @@ #include "AssignmentClientMonitor.h" int main(int argc, char* argv[]) { + initialiseUsecTimestampNow(); #ifndef WIN32 setvbuf(stdout, NULL, _IOLBF, 0); diff --git a/domain-server/src/main.cpp b/domain-server/src/main.cpp index bdb10cb56f..871c16a215 100644 --- a/domain-server/src/main.cpp +++ b/domain-server/src/main.cpp @@ -18,10 +18,12 @@ #include #include +#include #include "DomainServer.h" int main(int argc, char* argv[]) { + initialiseUsecTimestampNow(); #ifndef WIN32 setvbuf(stdout, NULL, _IOLBF, 0); diff --git a/interface/src/main.cpp b/interface/src/main.cpp index 2bb0633f24..6f9dc5e3bd 100644 --- a/interface/src/main.cpp +++ b/interface/src/main.cpp @@ -16,6 +16,7 @@ #include int main(int argc, const char * argv[]) { + initialiseUsecTimestampNow(); QElapsedTimer startupTime; startupTime.start(); diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index a13772d862..78ef997c35 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -21,18 +21,34 @@ #include #include +#include #include "OctalCode.h" #include "SharedUtil.h" -int usecTimestampNowAdjust = 0; + +static qint64 TIME_REFERENCE = 0; // in usec +static QElapsedTimer timestampTimer; +static int usecTimestampNowAdjust = 0; // in usec + +void initialiseUsecTimestampNow() { + static bool initialised = false; + if (initialised) { + qDebug() << "[WARNING] Double initialisation of usecTimestampNow()."; + return; + } + + TIME_REFERENCE = QDateTime::currentMSecsSinceEpoch() * 1000; // ms to usec + initialised = true; +} + void usecTimestampNowForceClockSkew(int clockSkew) { ::usecTimestampNowAdjust = clockSkew; } quint64 usecTimestampNow() { - qint64 msecSinceEpoch = QDateTime::currentMSecsSinceEpoch(); - return msecSinceEpoch * 1000 + ::usecTimestampNowAdjust; + // usec nsec to usec usec + return TIME_REFERENCE + timestampTimer.nsecsElapsed() / 1000 + ::usecTimestampNowAdjust; } float randFloat() { diff --git a/libraries/shared/src/SharedUtil.h b/libraries/shared/src/SharedUtil.h index 4a3fe2a129..54d599070d 100644 --- a/libraries/shared/src/SharedUtil.h +++ b/libraries/shared/src/SharedUtil.h @@ -60,6 +60,7 @@ static const quint64 USECS_PER_SECOND = USECS_PER_MSEC * MSECS_PER_SECOND; const int BITS_IN_BYTE = 8; +void initialiseUsecTimestampNow(); quint64 usecTimestampNow(); void usecTimestampNowForceClockSkew(int clockSkew); From 0b9ebe4c081670c1d09a94e7033a62e2940a2fb9 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 22 Apr 2014 11:51:36 -0700 Subject: [PATCH 577/595] avatar-voxels collisions work again --- interface/src/avatar/MyAvatar.cpp | 35 +++++-------------------------- 1 file changed, 5 insertions(+), 30 deletions(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 99e6cba0c2..b7290641cb 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -799,43 +799,18 @@ void MyAvatar::updateCollisionWithEnvironment(float deltaTime, float radius) { static CollisionList myCollisions(64); void MyAvatar::updateCollisionWithVoxels(float deltaTime, float radius) { - static int foo = 0; - ++foo; - -// const float VOXEL_ELASTICITY = 0.4f; -// const float VOXEL_DAMPING = 0.0f; - const float VOXEL_COLLISION_FREQUENCY = 0.5f; - myCollisions.clear(); const CapsuleShape& boundingShape = _skeletonModel.getBoundingShape(); if (Application::getInstance()->getVoxelTree()->findShapeCollisions(&boundingShape, myCollisions)) { + const float VOXEL_ELASTICITY = 0.4f; + const float VOXEL_DAMPING = 0.0f; for (int i = 0; i < myCollisions.size(); ++i) { CollisionInfo* collision = myCollisions[i]; - //if (0 == (foo % 100)) { - std::cout << "adebug " << myCollisions.size() << " collisions p = " << collision->_penetration << std::endl; // adebug - //} - //applyHardCollision(collision->_penetration, VOXEL_ELASTICITY, VOXEL_DAMPING); + applyHardCollision(collision->_penetration, VOXEL_ELASTICITY, VOXEL_DAMPING); } + const float VOXEL_COLLISION_FREQUENCY = 0.5f; updateCollisionSound(myCollisions[0]->_penetration, deltaTime, VOXEL_COLLISION_FREQUENCY); - } else if (myCollisions.size() == 0) { - if (0 == (foo % 100)) { - std::cout << "adebug 0 collisions capC = " << boundingShape.getPosition() << " capR = " << boundingShape.getRadius() << std::endl; // adebug - } - } - /* - const float VOXEL_ELASTICITY = 0.4f; - const float VOXEL_DAMPING = 0.0f; - const float VOXEL_COLLISION_FREQUENCY = 0.5f; - glm::vec3 penetration; - float pelvisFloatingHeight = getPelvisFloatingHeight(); - if (Application::getInstance()->getVoxelTree()->findCapsulePenetration( - _position - glm::vec3(0.0f, pelvisFloatingHeight - radius, 0.0f), - _position + glm::vec3(0.0f, getSkeletonHeight() - pelvisFloatingHeight + radius, 0.0f), radius, penetration)) { - _lastCollisionPosition = _position; - updateCollisionSound(penetration, deltaTime, VOXEL_COLLISION_FREQUENCY); - applyHardCollision(penetration, VOXEL_ELASTICITY, VOXEL_DAMPING); - } - */ + } } void MyAvatar::applyHardCollision(const glm::vec3& penetration, float elasticity, float damping) { From fea0a262a67f6316de8e32f418e413eaa0a54675 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 22 Apr 2014 12:35:50 -0700 Subject: [PATCH 578/595] Put back missing windows header --- libraries/shared/src/SharedUtil.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index 78ef997c35..b865d9c717 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -15,6 +15,10 @@ #include #include +#ifdef _WIN32 +#include +#endif + #ifdef __APPLE__ #include #endif From 364431328f25893420da51f25762830da3925309 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 22 Apr 2014 14:26:40 -0700 Subject: [PATCH 579/595] remove include StreamUtils.h --- interface/src/avatar/MyAvatar.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index b7290641cb..c5639d5f00 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -23,7 +23,6 @@ #include #include #include -#include #include From f3fd81ca59fbe54d59dcd6c0ac3a3190cd4993e6 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 22 Apr 2014 14:26:52 -0700 Subject: [PATCH 580/595] use glm::modf() for less code --- libraries/shared/src/ShapeCollider.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/libraries/shared/src/ShapeCollider.cpp b/libraries/shared/src/ShapeCollider.cpp index 458c355221..3cd21cbcba 100644 --- a/libraries/shared/src/ShapeCollider.cpp +++ b/libraries/shared/src/ShapeCollider.cpp @@ -607,10 +607,9 @@ bool sphereAACube(const glm::vec3& sphereCenter, float sphereRadius, const glm:: CollisionInfo* collision = collisions.getNewCollision(); if (collision) { // penetration is parallel to box side direction + BA /= maxBA; glm::vec3 direction; - modff(BA.x/maxBA, &(direction.x)); - modff(BA.y/maxBA, &(direction.y)); - modff(BA.z/maxBA, &(direction.z)); + glm::modf(BA, direction); direction = glm::normalize(direction); collision->_penetration = glm::dot(surfaceAB, direction) * direction; // contactPoint is on surface of A From 015cbce32217b94801f5ac08ee12e746a7fb2c06 Mon Sep 17 00:00:00 2001 From: matsukaze Date: Tue, 22 Apr 2014 18:57:22 -0400 Subject: [PATCH 581/595] Changed constant names for improved readability. --- interface/src/Audio.cpp | 45 ++++++++++++++++++++++++----------------- interface/src/Audio.h | 6 +++--- 2 files changed, 29 insertions(+), 22 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 1e85e77883..5e9d343df6 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -97,9 +97,9 @@ Audio::Audio(int16_t initialJitterBufferSamples, QObject* parent) : _scopeEnabledPause(false), _scopeInputOffset(0), _scopeOutputOffset(0), - _scopeInput(SAMPLES_PER_SCOPE_H * sizeof(int16_t), 0), - _scopeOutputLeft(SAMPLES_PER_SCOPE_H * sizeof(int16_t), 0), - _scopeOutputRight(SAMPLES_PER_SCOPE_H * sizeof(int16_t), 0) + _scopeInput(SAMPLES_PER_SCOPE_WIDTH * sizeof(int16_t), 0), + _scopeOutputLeft(SAMPLES_PER_SCOPE_WIDTH * sizeof(int16_t), 0), + _scopeOutputRight(SAMPLES_PER_SCOPE_WIDTH * sizeof(int16_t), 0) { // clear the array of locally injected samples memset(_localProceduralSamples, 0, NETWORK_BUFFER_LENGTH_BYTES_PER_CHANNEL); @@ -587,7 +587,7 @@ void Audio::handleAudioInput() { unsigned int monoAudioChannel = 0; addBufferToScope(_scopeInput, _scopeInputOffset, monoAudioSamples, monoAudioChannel, numMonoAudioChannels); _scopeInputOffset += NETWORK_SAMPLES_PER_FRAME; - _scopeInputOffset %= SAMPLES_PER_SCOPE_H; + _scopeInputOffset %= SAMPLES_PER_SCOPE_WIDTH; } NodeList* nodeList = NodeList::getInstance(); @@ -847,7 +847,7 @@ void Audio::processReceivedAudio(const QByteArray& audioByteArray) { samples, audioChannel, numAudioChannels); _scopeOutputOffset += NETWORK_SAMPLES_PER_FRAME; - _scopeOutputOffset %= SAMPLES_PER_SCOPE_H; + _scopeOutputOffset %= SAMPLES_PER_SCOPE_WIDTH; samples += NETWORK_SAMPLES_PER_FRAME * numAudioChannels; } } @@ -1065,7 +1065,7 @@ void Audio::toggleScopePause() { void Audio::toggleScope() { _scopeEnabled = !_scopeEnabled; if (_scopeEnabled) { - static const int width = SAMPLES_PER_SCOPE_H; + static const int width = SAMPLES_PER_SCOPE_WIDTH; _scopeInputOffset = 0; _scopeOutputOffset = 0; memset(_scopeInput.data(), 0, width * sizeof(int16_t)); @@ -1077,13 +1077,21 @@ void Audio::toggleScope() { void Audio::addBufferToScope( QByteArray& byteArray, unsigned int frameOffset, const int16_t* src, unsigned int srcChannel, unsigned int srcNumChannels) { - int16_t* tgt = (int16_t*)byteArray.data() + frameOffset; - src += srcChannel; + // Constant multiplier to map sample value to vertical size of scope + float multiplier = (float)MULTIPLIER_SCOPE_HEIGHT / logf(2.0f); - for (int i = NETWORK_SAMPLES_PER_FRAME; --i >= 0; src += srcNumChannels) { - float sample = (float)*src; - float multiplier = (float)MULTIPLIER_SCOPE_V / logf(2.0f); - int16_t value; + // Temporary variable receives sample value + float sample; + + // Temporary variable receives mapping of sample value + int16_t value; + + // Short int pointer to mapped samples in byte array + int16_t* tgt = (int16_t*) byteArray.data(); + + for (int i = 0; i < NETWORK_SAMPLES_PER_FRAME; i++) { + + sample = (float)src[i * srcNumChannels + srcChannel]; if (sample > 0) { value = (int16_t)(multiplier * logf(sample)); @@ -1093,8 +1101,7 @@ void Audio::addBufferToScope( value = 0; } - *tgt++ = value; - //*tgt++ = sample / 0x7fff * (SAMPLES_PER_SCOPE_V / 2); + tgt[i + frameOffset] = value; } } @@ -1111,10 +1118,10 @@ void Audio::renderScope(int width, int height) { static const int gridRows = 2; static const int gridCols = 5; - int x = (width - SAMPLES_PER_SCOPE_H) / 2; - int y = (height - SAMPLES_PER_SCOPE_V) / 2; - int w = SAMPLES_PER_SCOPE_H; - int h = SAMPLES_PER_SCOPE_V; + int x = (width - SAMPLES_PER_SCOPE_WIDTH) / 2; + int y = (height - SAMPLES_PER_SCOPE_HEIGHT) / 2; + int w = SAMPLES_PER_SCOPE_WIDTH; + int h = SAMPLES_PER_SCOPE_HEIGHT; renderBackground(backgroundColor, x, y, w, h); renderGrid(gridColor, x, y, w, h, gridRows, gridCols); @@ -1176,7 +1183,7 @@ void Audio::renderLineStrip(unsigned int rgba, int x, int y, int n, int offset, int16_t sample; int16_t* samples = ((int16_t*) byteArray.data()) + offset; - y += SAMPLES_PER_SCOPE_V / 2; + y += SAMPLES_PER_SCOPE_HEIGHT / 2; for (int i = n - offset; --i >= 0; ) { sample = *samples++; glVertex2i(x++, y - sample); diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 4d4501c93d..71030e39e3 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -211,9 +211,9 @@ private: // Audio scope data static const unsigned int NETWORK_SAMPLES_PER_FRAME = NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL; static const unsigned int FRAMES_PER_SCOPE = 5; - static const unsigned int SAMPLES_PER_SCOPE_H = FRAMES_PER_SCOPE * NETWORK_SAMPLES_PER_FRAME; - static const unsigned int MULTIPLIER_SCOPE_V = 20; - static const unsigned int SAMPLES_PER_SCOPE_V = 2 * 15 * MULTIPLIER_SCOPE_V; + static const unsigned int SAMPLES_PER_SCOPE_WIDTH = FRAMES_PER_SCOPE * NETWORK_SAMPLES_PER_FRAME; + static const unsigned int MULTIPLIER_SCOPE_HEIGHT = 20; + static const unsigned int SAMPLES_PER_SCOPE_HEIGHT = 2 * 15 * MULTIPLIER_SCOPE_HEIGHT; bool _scopeEnabled; bool _scopeEnabledPause; int _scopeInputOffset; From 1ff3b83644e5eeaeb67ba168f08b78d8b8345af6 Mon Sep 17 00:00:00 2001 From: matsukaze Date: Tue, 22 Apr 2014 19:42:51 -0400 Subject: [PATCH 582/595] Changed const color data and method signatures. Changed constant color data and method signatures from unsigned int to array of float. Changed glColor4f to glColor4fv. --- interface/src/Audio.cpp | 36 +++++++++++++++--------------------- interface/src/Audio.h | 6 +++--- 2 files changed, 18 insertions(+), 24 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 5e9d343df6..29aaa3b34b 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -1110,11 +1110,11 @@ void Audio::renderScope(int width, int height) { if (!_scopeEnabled) return; - static const unsigned int backgroundColor = 0x33333399; - static const unsigned int gridColor = 0x44444499; - static const unsigned int inputColor = 0x44aa4499; - static const unsigned int outputLeftColor = 0xaa444499; - static const unsigned int outputRightColor = 0x4444aa99; + static const float backgroundColor[4] = { 0.2f, 0.2f, 0.2f, 0.6f }; + static const float gridColor[4] = { 0.3f, 0.3f, 0.3f, 0.6f }; + static const float inputColor[4] = { 0.3f, .7f, 0.3f, 0.6f }; + static const float outputLeftColor[4] = { 0.7f, .3f, 0.3f, 0.6f }; + static const float outputRightColor[4] = { 0.3f, .3f, 0.7f, 0.6f }; static const int gridRows = 2; static const int gridCols = 5; @@ -1130,26 +1130,24 @@ void Audio::renderScope(int width, int height) { renderLineStrip(outputRightColor, x, y, w, _scopeOutputOffset, _scopeOutputRight); } -void Audio::renderBackground(unsigned int rgba, int x, int y, int width, int height) { +void Audio::renderBackground(const float* color, int x, int y, int width, int height) { + + glColor4fv(color); glBegin(GL_QUADS); - glColor4f(((rgba >> 24) & 0xff) / 255.0f, - ((rgba >> 16) & 0xff) / 255.0f, - ((rgba >> 8) & 0xff) / 255.0f, - (rgba & 0xff) / 255.0f); + glVertex2i(x, y); glVertex2i(x + width, y); glVertex2i(x + width, y + height); glVertex2i(x , y + height); + glEnd(); glColor4f(1, 1, 1, 1); } -void Audio::renderGrid(unsigned int rgba, int x, int y, int width, int height, int rows, int cols) { +void Audio::renderGrid(const float* color, int x, int y, int width, int height, int rows, int cols) { + + glColor4fv(color); glBegin(GL_LINES); - glColor4f(((rgba >> 24) & 0xff) / 255.0f, - ((rgba >> 16) & 0xff) / 255.0f, - ((rgba >> 8) & 0xff) / 255.0f, - (rgba & 0xff) / 255.0f); int dx = width / cols; int dy = height / rows; @@ -1172,13 +1170,9 @@ void Audio::renderGrid(unsigned int rgba, int x, int y, int width, int height, i glColor4f(1, 1, 1, 1); } -void Audio::renderLineStrip(unsigned int rgba, int x, int y, int n, int offset, const QByteArray& byteArray) { - - glColor4f(((rgba >> 24) & 0xff) / 255.0f, - ((rgba >> 16) & 0xff) / 255.0f, - ((rgba >> 8) & 0xff) / 255.0f, - (rgba & 0xff) / 255.0f); +void Audio::renderLineStrip(const float* color, int x, int y, int n, int offset, const QByteArray& byteArray) { + glColor4fv(color); glBegin(GL_LINE_STRIP); int16_t sample; diff --git a/interface/src/Audio.h b/interface/src/Audio.h index 71030e39e3..c42b442a81 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -204,9 +204,9 @@ private: void addBufferToScope(QByteArray& byteArray, unsigned int frameOffset, const int16_t* src, unsigned int srcChannel, unsigned int srcNumChannels); // Audio scope methods for rendering - void renderBackground(unsigned int rgba, int x, int y, int width, int height); - void renderGrid(unsigned int rgba, int x, int y, int width, int height, int rows, int cols); - void renderLineStrip(unsigned int rgba, int x, int y, int n, int offset, const QByteArray& byteArray); + void renderBackground(const float* color, int x, int y, int width, int height); + void renderGrid(const float* color, int x, int y, int width, int height, int rows, int cols); + void renderLineStrip(const float* color, int x, int y, int n, int offset, const QByteArray& byteArray); // Audio scope data static const unsigned int NETWORK_SAMPLES_PER_FRAME = NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL; From d6e4f217f5adeb7ee26e6e3a05cba405e1a31d43 Mon Sep 17 00:00:00 2001 From: matsukaze Date: Tue, 22 Apr 2014 21:57:41 -0400 Subject: [PATCH 583/595] Expanded variable names. --- interface/src/Audio.cpp | 8 ++++---- interface/src/Audio.h | 3 ++- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 29aaa3b34b..eb4a751356 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -1075,7 +1075,7 @@ void Audio::toggleScope() { } void Audio::addBufferToScope( - QByteArray& byteArray, unsigned int frameOffset, const int16_t* src, unsigned int srcChannel, unsigned int srcNumChannels) { + QByteArray& byteArray, unsigned int frameOffset, const int16_t* source, unsigned int sourceChannel, unsigned int sourceNumberOfChannels) { // Constant multiplier to map sample value to vertical size of scope float multiplier = (float)MULTIPLIER_SCOPE_HEIGHT / logf(2.0f); @@ -1087,11 +1087,11 @@ void Audio::addBufferToScope( int16_t value; // Short int pointer to mapped samples in byte array - int16_t* tgt = (int16_t*) byteArray.data(); + int16_t* destination = (int16_t*) byteArray.data(); for (int i = 0; i < NETWORK_SAMPLES_PER_FRAME; i++) { - sample = (float)src[i * srcNumChannels + srcChannel]; + sample = (float)source[i * sourceNumberOfChannels + sourceChannel]; if (sample > 0) { value = (int16_t)(multiplier * logf(sample)); @@ -1101,7 +1101,7 @@ void Audio::addBufferToScope( value = 0; } - tgt[i + frameOffset] = value; + destination[i + frameOffset] = value; } } diff --git a/interface/src/Audio.h b/interface/src/Audio.h index c42b442a81..ebd7f8612a 100644 --- a/interface/src/Audio.h +++ b/interface/src/Audio.h @@ -201,7 +201,8 @@ private: float calculateDeviceToNetworkInputRatio(int numBytes); // Audio scope methods for data acquisition - void addBufferToScope(QByteArray& byteArray, unsigned int frameOffset, const int16_t* src, unsigned int srcChannel, unsigned int srcNumChannels); + void addBufferToScope( + QByteArray& byteArray, unsigned int frameOffset, const int16_t* source, unsigned int sourceChannel, unsigned int sourceNumberOfChannels); // Audio scope methods for rendering void renderBackground(const float* color, int x, int y, int width, int height); From 1986ac6be334933c2b3bbba5e78c79fb4c2f8d3f Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 22 Apr 2014 20:53:12 -0700 Subject: [PATCH 584/595] collisions with cube get rounded normals at edges --- libraries/shared/src/ShapeCollider.cpp | 36 ++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/libraries/shared/src/ShapeCollider.cpp b/libraries/shared/src/ShapeCollider.cpp index 3cd21cbcba..256c1aa388 100644 --- a/libraries/shared/src/ShapeCollider.cpp +++ b/libraries/shared/src/ShapeCollider.cpp @@ -606,11 +606,37 @@ bool sphereAACube(const glm::vec3& sphereCenter, float sphereRadius, const glm:: if (glm::dot(surfaceAB, BA) > 0.f) { CollisionInfo* collision = collisions.getNewCollision(); if (collision) { - // penetration is parallel to box side direction - BA /= maxBA; - glm::vec3 direction; - glm::modf(BA, direction); - direction = glm::normalize(direction); + // At this point imagine that sphereCenter touches a "normalized" cube with rounded edges. + // This cube has a sidelength of 2 and its smoothing radius is sphereRadius/maxBA. + // We're going to try to compute the "negative normal" (and hence direction of penetration) + // of this surface. + + float radius = sphereRadius / (distance * maxBA); // normalized radius + float shortLength = maxBA - radius; + glm::vec3 direction = BA; + if (shortLength > 0.0f) { + direction = glm::abs(BA) - glm::vec3(shortLength); + // Set any negative components to zero, and adopt the sign of the original BA component. + // Unfortunately there isn't an easy way to make this fast. + if (direction.x < 0.0f) { + direction.x = 0.f; + } else if (BA.x < 0.f) { + direction.x = -direction.x; + } + if (direction.y < 0.0f) { + direction.y = 0.f; + } else if (BA.y < 0.f) { + direction.y = -direction.y; + } + if (direction.z < 0.0f) { + direction.z = 0.f; + } else if (BA.z < 0.f) { + direction.z = -direction.z; + } + } + direction = glm::normalize(direction); + + // penetration is the projection of surfaceAB on direction collision->_penetration = glm::dot(surfaceAB, direction) * direction; // contactPoint is on surface of A collision->_contactPoint = sphereCenter - sphereRadius * direction; From 5992651c278e7e911525a3c9253dad13571163c1 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Tue, 22 Apr 2014 20:55:28 -0700 Subject: [PATCH 585/595] update avatar collision shapes when necessary --- interface/src/avatar/MyAvatar.cpp | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index c5639d5f00..e1d7463aa3 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -335,15 +335,17 @@ void MyAvatar::simulate(float deltaTime) { radius = myCamera->getAspectRatio() * (myCamera->getNearClip() / cos(myCamera->getFieldOfView() / 2.0f)); radius *= COLLISION_RADIUS_SCALAR; } - - if (_collisionFlags & COLLISION_GROUP_ENVIRONMENT) { - updateCollisionWithEnvironment(deltaTime, radius); - } - if (_collisionFlags & COLLISION_GROUP_VOXELS) { - updateCollisionWithVoxels(deltaTime, radius); - } - if (_collisionFlags & COLLISION_GROUP_AVATARS) { - updateCollisionWithAvatars(deltaTime); + if (_collisionFlags) { + updateShapePositions(); + if (_collisionFlags & COLLISION_GROUP_ENVIRONMENT) { + updateCollisionWithEnvironment(deltaTime, radius); + } + if (_collisionFlags & COLLISION_GROUP_VOXELS) { + updateCollisionWithVoxels(deltaTime, radius); + } + if (_collisionFlags & COLLISION_GROUP_AVATARS) { + updateCollisionWithAvatars(deltaTime); + } } } @@ -914,7 +916,6 @@ void MyAvatar::updateCollisionWithAvatars(float deltaTime) { // no need to compute a bunch of stuff if we have one or fewer avatars return; } - updateShapePositions(); float myBoundingRadius = getBoundingRadius(); const float BODY_COLLISION_RESOLUTION_FACTOR = glm::max(1.0f, deltaTime / BODY_COLLISION_RESOLUTION_TIMESCALE); From ebc6f4e78ee4f3444e7e300254daf033daa9d379 Mon Sep 17 00:00:00 2001 From: Thijs Wenker Date: Wed, 23 Apr 2014 14:40:06 +0200 Subject: [PATCH 586/595] Removed UTF-8 new line characters, QT script errors on those lines in Windows. --- examples/clap.js | 2 +- examples/drumStick.js | 2 +- examples/playSound.js | 4 ++-- examples/spaceInvadersExample.js | 7 +++---- examples/toyball.js | 6 +++--- examples/voxelDrumming.js | 2 +- 6 files changed, 11 insertions(+), 12 deletions(-) diff --git a/examples/clap.js b/examples/clap.js index a0efcfab7b..9da36ba094 100644 --- a/examples/clap.js +++ b/examples/clap.js @@ -50,7 +50,7 @@ function maybePlaySound(deltaTime) { const CLAP_DISTANCE = 0.2; if (!clapping[palm] && (distanceBetween < CLAP_DISTANCE) && (speed > CLAP_SPEED)) { - var options = new AudioInjectionOptions();
 + var options = new AudioInjectionOptions(); options.position = palm1Position; options.volume = speed / 2.0; if (options.volume > 1.0) options.volume = 1.0; diff --git a/examples/drumStick.js b/examples/drumStick.js index e9ac54f814..188661b000 100644 --- a/examples/drumStick.js +++ b/examples/drumStick.js @@ -61,7 +61,7 @@ function checkSticks(deltaTime) { // Waiting for change in velocity direction or slowing to trigger drum sound if ((palmVelocity.y > 0.0) || (speed < STOP_SPEED)) { state[palm] = 0; - var options = new AudioInjectionOptions();
 + var options = new AudioInjectionOptions(); options.position = Controller.getSpatialControlPosition(palm * 2 + 1); if (strokeSpeed[palm] > 1.0) { strokeSpeed[palm] = 1.0; } options.volume = strokeSpeed[palm]; diff --git a/examples/playSound.js b/examples/playSound.js index fb589bc9e3..317581ba36 100644 --- a/examples/playSound.js +++ b/examples/playSound.js @@ -9,12 +9,12 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // First, load the clap sound from a URL -var clap = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Animals/bushtit_1.raw"); +var clap = new Sound("https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Animals/bushtit_1.raw"); function maybePlaySound(deltaTime) { if (Math.random() < 0.01) { // Set the location and other info for the sound to play - var options = new AudioInjectionOptions();
 + var options = new AudioInjectionOptions(); var palmPosition = Controller.getSpatialControlPosition(0); options.position = palmPosition; options.volume = 0.5; diff --git a/examples/spaceInvadersExample.js b/examples/spaceInvadersExample.js index 5b25fa1236..5d62102d71 100644 --- a/examples/spaceInvadersExample.js +++ b/examples/spaceInvadersExample.js @@ -217,7 +217,7 @@ function update(deltaTime) { if (invaderStepOfCycle % stepsPerSound == 0) { // play the move sound - var options = new AudioInjectionOptions();
 + var options = new AudioInjectionOptions(); if (soundInMyHead) { options.position = { x: MyAvatar.position.x + 0.0, y: MyAvatar.position.y + 0.1, @@ -329,7 +329,7 @@ function fireMissile() { lifetime: 5 }); - var options = new AudioInjectionOptions();
 + var options = new AudioInjectionOptions(); if (soundInMyHead) { options.position = { x: MyAvatar.position.x + 0.0, y: MyAvatar.position.y + 0.1, @@ -379,7 +379,7 @@ function deleteIfInvader(possibleInvaderParticle) { Particles.deleteParticle(myMissile); // play the hit sound - var options = new AudioInjectionOptions();
 + var options = new AudioInjectionOptions(); if (soundInMyHead) { options.position = { x: MyAvatar.position.x + 0.0, y: MyAvatar.position.y + 0.1, @@ -417,4 +417,3 @@ initializeInvaders(); // shut down the game after 1 minute var gameTimer = Script.setTimeout(endGame, itemLifetimes * 1000); - diff --git a/examples/toyball.js b/examples/toyball.js index de68e97357..d312c1bc94 100644 --- a/examples/toyball.js +++ b/examples/toyball.js @@ -111,7 +111,7 @@ function checkControllerSide(whichSide) { velocity : { x: 0, y: 0, z: 0}, inHand: true }; Particles.editParticle(closestParticle, properties); - var options = new AudioInjectionOptions();
 + var options = new AudioInjectionOptions(); options.position = ballPosition; options.volume = 1.0; Audio.playSound(catchSound, options); @@ -152,7 +152,7 @@ function checkControllerSide(whichSide) { } // Play a new ball sound - var options = new AudioInjectionOptions();
 + var options = new AudioInjectionOptions(); options.position = ballPosition; options.volume = 1.0; Audio.playSound(catchSound, options); @@ -201,7 +201,7 @@ function checkControllerSide(whichSide) { rightHandParticle = false; } - var options = new AudioInjectionOptions();
 + var options = new AudioInjectionOptions(); options.position = ballPosition; options.volume = 1.0; Audio.playSound(throwSound, options); diff --git a/examples/voxelDrumming.js b/examples/voxelDrumming.js index 7f3495dea7..1b320ed755 100644 --- a/examples/voxelDrumming.js +++ b/examples/voxelDrumming.js @@ -64,7 +64,7 @@ collisionBubble[1] = Overlays.addOverlay("sphere", visible: false }); -var audioOptions = new AudioInjectionOptions();
 +var audioOptions = new AudioInjectionOptions(); audioOptions.position = { x: MyAvatar.position.x, y: MyAvatar.position.y + 1, z: MyAvatar.position.z }; audioOptions.volume = 1; From 7464ca0879bf8eb71a31e15ba61936ad6cf1b836 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 23 Apr 2014 08:38:58 -0700 Subject: [PATCH 587/595] non-rounded collision solution in comments --- libraries/shared/src/ShapeCollider.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/libraries/shared/src/ShapeCollider.cpp b/libraries/shared/src/ShapeCollider.cpp index 256c1aa388..31d57f14ad 100644 --- a/libraries/shared/src/ShapeCollider.cpp +++ b/libraries/shared/src/ShapeCollider.cpp @@ -606,6 +606,16 @@ bool sphereAACube(const glm::vec3& sphereCenter, float sphereRadius, const glm:: if (glm::dot(surfaceAB, BA) > 0.f) { CollisionInfo* collision = collisions.getNewCollision(); if (collision) { + /* KEEP THIS CODE -- this is how to collide the cube with stark face normals (no rounding). + * We might want to use this code later for sealing boundaries between adjacent voxels. + // penetration is parallel to box side direction + BA /= maxBA; + glm::vec3 direction; + glm::modf(BA, direction); + direction = glm::normalize(direction); + */ + + // For rounded normals at edges and corners: // At this point imagine that sphereCenter touches a "normalized" cube with rounded edges. // This cube has a sidelength of 2 and its smoothing radius is sphereRadius/maxBA. // We're going to try to compute the "negative normal" (and hence direction of penetration) From da5ac3d6645665b5e1443c666396ec5b922da2ea Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 23 Apr 2014 08:47:25 -0700 Subject: [PATCH 588/595] remove warning about signed/unsigned comparison --- domain-server/src/DomainServer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index eb62dacf79..e65f3968e0 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -449,7 +449,7 @@ void DomainServer::sendDomainListToNode(const SharedNodePointer& node, const Hif if (nodeInterestList.size() > 0) { DTLSServerSession* dtlsSession = _isUsingDTLS ? _dtlsSessions[senderSockAddr] : NULL; - unsigned int dataMTU = dtlsSession ? gnutls_dtls_get_data_mtu(*dtlsSession->getGnuTLSSession()) : MAX_PACKET_SIZE; + int dataMTU = dtlsSession ? (int)gnutls_dtls_get_data_mtu(*dtlsSession->getGnuTLSSession()) : MAX_PACKET_SIZE; // if the node has any interest types, send back those nodes as well foreach (const SharedNodePointer& otherNode, nodeList->getNodeHash()) { From bfe1ee377ba16d3d3b9f377b4c912fa25caf0dd5 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 23 Apr 2014 08:56:53 -0700 Subject: [PATCH 589/595] remove warning about signed/unsigned comparison Also change n.f to be n.0f as per coding standard --- interface/src/Audio.cpp | 53 +++++++++++++++++++---------------------- 1 file changed, 25 insertions(+), 28 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index eb4a751356..0aba5a8ae5 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -480,7 +480,7 @@ void Audio::handleAudioInput() { float thisSample = 0; int samplesOverNoiseGate = 0; - const float NOISE_GATE_HEIGHT = 7.f; + const float NOISE_GATE_HEIGHT = 7.0f; const int NOISE_GATE_WIDTH = 5; const int NOISE_GATE_CLOSE_FRAME_DELAY = 5; const int NOISE_GATE_FRAMES_TO_AVERAGE = 5; @@ -490,7 +490,7 @@ void Audio::handleAudioInput() { // // Check clipping, adjust DC offset, and check if should open noise gate // - float measuredDcOffset = 0.f; + float measuredDcOffset = 0.0f; // Increment the time since the last clip if (_timeSinceLastClip >= 0.0f) { _timeSinceLastClip += (float) NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL / (float) SAMPLE_RATE; @@ -500,7 +500,7 @@ void Audio::handleAudioInput() { measuredDcOffset += monoAudioSamples[i]; monoAudioSamples[i] -= (int16_t) _dcOffset; thisSample = fabsf(monoAudioSamples[i]); - if (thisSample >= (32767.f * CLIPPING_THRESHOLD)) { + if (thisSample >= (32767.0f * CLIPPING_THRESHOLD)) { _timeSinceLastClip = 0.0f; } loudness += thisSample; @@ -511,18 +511,18 @@ void Audio::handleAudioInput() { } measuredDcOffset /= NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL; - if (_dcOffset == 0.f) { + if (_dcOffset == 0.0f) { // On first frame, copy over measured offset _dcOffset = measuredDcOffset; } else { - _dcOffset = DC_OFFSET_AVERAGING * _dcOffset + (1.f - DC_OFFSET_AVERAGING) * measuredDcOffset; + _dcOffset = DC_OFFSET_AVERAGING * _dcOffset + (1.0f - DC_OFFSET_AVERAGING) * measuredDcOffset; } // Add tone injection if enabled - const float TONE_FREQ = 220.f / SAMPLE_RATE * TWO_PI; - const float QUARTER_VOLUME = 8192.f; + const float TONE_FREQ = 220.0f / SAMPLE_RATE * TWO_PI; + const float QUARTER_VOLUME = 8192.0f; if (_toneInjectionEnabled) { - loudness = 0.f; + loudness = 0.0f; for (int i = 0; i < NETWORK_BUFFER_LENGTH_SAMPLES_PER_CHANNEL; i++) { monoAudioSamples[i] = QUARTER_VOLUME * sinf(TONE_FREQ * (float)(i + _proceduralEffectSample)); loudness += fabsf(monoAudioSamples[i]); @@ -532,7 +532,7 @@ void Audio::handleAudioInput() { // If Noise Gate is enabled, check and turn the gate on and off if (!_toneInjectionEnabled && _noiseGateEnabled) { - float averageOfAllSampleFrames = 0.f; + float averageOfAllSampleFrames = 0.0f; _noiseSampleFrames[_noiseGateSampleCounter++] = _lastInputLoudness; if (_noiseGateSampleCounter == NUMBER_OF_NOISE_SAMPLE_FRAMES) { float smallestSample = FLT_MAX; @@ -660,9 +660,9 @@ void Audio::addReceivedAudioToBuffer(const QByteArray& audioByteArray) { _stdev.reset(); // Set jitter buffer to be a multiple of the measured standard deviation const int MAX_JITTER_BUFFER_SAMPLES = _ringBuffer.getSampleCapacity() / 2; - const float NUM_STANDARD_DEVIATIONS = 3.f; + const float NUM_STANDARD_DEVIATIONS = 3.0f; if (Menu::getInstance()->getAudioJitterBufferSamples() == 0) { - float newJitterBufferSamples = (NUM_STANDARD_DEVIATIONS * _measuredJitter) / 1000.f * SAMPLE_RATE; + float newJitterBufferSamples = (NUM_STANDARD_DEVIATIONS * _measuredJitter) / 1000.0f * SAMPLE_RATE; setJitterBufferSamples(glm::clamp((int)newJitterBufferSamples, 0, MAX_JITTER_BUFFER_SAMPLES)); } } @@ -903,10 +903,10 @@ void Audio::toggleAudioSpatialProcessing() { void Audio::addProceduralSounds(int16_t* monoInput, int numSamples) { float sample; const float COLLISION_SOUND_CUTOFF_LEVEL = 0.01f; - const float COLLISION_SOUND_MAX_VOLUME = 1000.f; + const float COLLISION_SOUND_MAX_VOLUME = 1000.0f; const float UP_MAJOR_FIFTH = powf(1.5f, 4.0f); - const float DOWN_TWO_OCTAVES = 4.f; - const float DOWN_FOUR_OCTAVES = 16.f; + const float DOWN_TWO_OCTAVES = 4.0f; + const float DOWN_FOUR_OCTAVES = 16.0f; float t; if (_collisionSoundMagnitude > COLLISION_SOUND_CUTOFF_LEVEL) { for (int i = 0; i < numSamples; i++) { @@ -936,12 +936,12 @@ void Audio::addProceduralSounds(int16_t* monoInput, int numSamples) { _proceduralEffectSample += numSamples; // Add a drum sound - const float MAX_VOLUME = 32000.f; - const float MAX_DURATION = 2.f; + const float MAX_VOLUME = 32000.0f; + const float MAX_DURATION = 2.0f; const float MIN_AUDIBLE_VOLUME = 0.001f; const float NOISE_MAGNITUDE = 0.02f; float frequency = (_drumSoundFrequency / SAMPLE_RATE) * TWO_PI; - if (_drumSoundVolume > 0.f) { + if (_drumSoundVolume > 0.0f) { for (int i = 0; i < numSamples; i++) { t = (float) _drumSoundSample + (float) i; sample = sinf(t * frequency); @@ -961,12 +961,12 @@ void Audio::addProceduralSounds(int16_t* monoInput, int numSamples) { _localProceduralSamples[i] = glm::clamp(_localProceduralSamples[i] + collisionSample, MIN_SAMPLE_VALUE, MAX_SAMPLE_VALUE); - _drumSoundVolume *= (1.f - _drumSoundDecay); + _drumSoundVolume *= (1.0f - _drumSoundDecay); } _drumSoundSample += numSamples; - _drumSoundDuration = glm::clamp(_drumSoundDuration - (AUDIO_CALLBACK_MSECS / 1000.f), 0.f, MAX_DURATION); - if (_drumSoundDuration == 0.f || (_drumSoundVolume < MIN_AUDIBLE_VOLUME)) { - _drumSoundVolume = 0.f; + _drumSoundDuration = glm::clamp(_drumSoundDuration - (AUDIO_CALLBACK_MSECS / 1000.0f), 0.0f, MAX_DURATION); + if (_drumSoundDuration == 0.0f || (_drumSoundVolume < MIN_AUDIBLE_VOLUME)) { + _drumSoundVolume = 0.0f; } } } @@ -999,7 +999,7 @@ void Audio::renderToolBox(int x, int y, bool boxed) { if (boxed) { - bool isClipping = ((getTimeSinceLastClip() > 0.f) && (getTimeSinceLastClip() < 1.f)); + bool isClipping = ((getTimeSinceLastClip() > 0.0f) && (getTimeSinceLastClip() < 1.0f)); const int BOX_LEFT_PADDING = 5; const int BOX_TOP_PADDING = 10; const int BOX_WIDTH = 266; @@ -1010,9 +1010,9 @@ void Audio::renderToolBox(int x, int y, bool boxed) { glBindTexture(GL_TEXTURE_2D, _boxTextureId); if (isClipping) { - glColor3f(1.f,0.f,0.f); + glColor3f(1.0f, 0.0f, 0.0f); } else { - glColor3f(.41f,.41f,.41f); + glColor3f(0.41f, 0.41f, 0.41f); } glBegin(GL_QUADS); @@ -1089,10 +1089,8 @@ void Audio::addBufferToScope( // Short int pointer to mapped samples in byte array int16_t* destination = (int16_t*) byteArray.data(); - for (int i = 0; i < NETWORK_SAMPLES_PER_FRAME; i++) { - + for (unsigned int i = 0; i < NETWORK_SAMPLES_PER_FRAME; i++) { sample = (float)source[i * sourceNumberOfChannels + sourceChannel]; - if (sample > 0) { value = (int16_t)(multiplier * logf(sample)); } else if (sample < 0) { @@ -1100,7 +1098,6 @@ void Audio::addBufferToScope( } else { value = 0; } - destination[i + frameOffset] = value; } } From a7771bc142e48d2ebf022445f78878346315fce0 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 23 Apr 2014 09:05:11 -0700 Subject: [PATCH 590/595] repair header comments for AABox.* --- libraries/octree/src/AABox.cpp | 2 +- libraries/octree/src/AABox.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/octree/src/AABox.cpp b/libraries/octree/src/AABox.cpp index ed99a24d38..51b31d4466 100644 --- a/libraries/octree/src/AABox.cpp +++ b/libraries/octree/src/AABox.cpp @@ -1,6 +1,6 @@ // // AABox.cpp -// libraries/shared/src +// libraries/octree/src // // Created by Brad Hefta-Gaub on 04/11/13. // Copyright 2013 High Fidelity, Inc. diff --git a/libraries/octree/src/AABox.h b/libraries/octree/src/AABox.h index 6531db4250..1aa0849b70 100644 --- a/libraries/octree/src/AABox.h +++ b/libraries/octree/src/AABox.h @@ -1,6 +1,6 @@ // // AABox.h -// libraries/shared/src +// libraries/octree/src // // Created by Brad Hefta-Gaub on 04/11/13. // Copyright 2013 High Fidelity, Inc. From f46a5dc96670f77ece6acf7c189db2ba4cb53624 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 23 Apr 2014 10:13:05 -0700 Subject: [PATCH 591/595] fix #2718 for warning about unused variable --- interface/src/ui/ScriptEditorWidget.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/interface/src/ui/ScriptEditorWidget.cpp b/interface/src/ui/ScriptEditorWidget.cpp index 1765a5ea1a..3f9b0137ef 100644 --- a/interface/src/ui/ScriptEditorWidget.cpp +++ b/interface/src/ui/ScriptEditorWidget.cpp @@ -39,7 +39,8 @@ ScriptEditorWidget::ScriptEditorWidget() : setTitleBarWidget(new QWidget()); QFontMetrics fm(_scriptEditorWidgetUI->scriptEdit->font()); _scriptEditorWidgetUI->scriptEdit->setTabStopWidth(fm.width('0') * 4); - ScriptHighlighting* highlighting = new ScriptHighlighting(_scriptEditorWidgetUI->scriptEdit->document()); + // We create a new ScriptHighligting QObject and provide it with a parent so this is NOT a memory leak. + new ScriptHighlighting(_scriptEditorWidgetUI->scriptEdit->document()); QTimer::singleShot(0, _scriptEditorWidgetUI->scriptEdit, SLOT(setFocus())); } From ceb5208102f6d5ea8c2a5a5909c966b2c8ac5a77 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 23 Apr 2014 11:00:44 -0700 Subject: [PATCH 592/595] CR --- interface/src/Application.cpp | 5 ++--- interface/src/Util.cpp | 25 +++++++++++++------------ interface/src/starfield/Controller.cpp | 3 ++- 3 files changed, 17 insertions(+), 16 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index bfbc88a666..265ff2e7a1 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1218,8 +1218,7 @@ void Application::touchEndEvent(QTouchEvent* event) { if (_controllerScriptingInterface.isTouchCaptured()) { return; } - - // put any application specific touch behavior below here.. +s // put any application specific touch behavior below here.. _touchDragStartedAvgX = _touchAvgX; _touchDragStartedAvgY = _touchAvgY; _isTouchPressed = false; @@ -1276,7 +1275,7 @@ void Application::timer() { sendPingPackets(); } - float diffTime = (float)_timerStart.nsecsElapsed() / 1000000000.0; + float diffTime = (float)_timerStart.nsecsElapsed() / 1000000000.0f; _fps = (float)_frameCount / diffTime; diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 16dd35f316..79a2e31d80 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -407,24 +407,25 @@ void runTimingTests() { startTime.start(); float elapsedUsecs; - elapsedUsecs = (float)startTime.nsecsElapsed() / 1000.0; - qDebug("QElapsedTimer::nsecElapsed() usecs: %f", 1000.0f * elapsedUsecs / (float) numTests); + float NSEC_TO_USEC = 1.0f / 1000.0f; + elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; + qDebug("QElapsedTimer::nsecElapsed() usecs: %f", elapsedUsecs / (float) numTests); // Random number generation startTime.start(); for (int i = 1; i < numTests; i++) { iResults[i] = rand(); } - elapsedUsecs = (float)startTime.nsecsElapsed() / 1000.0; - qDebug("rand() stored in array usecs: %f, first result:%d", 1000.0f * elapsedUsecs / (float) numTests, iResults[0]); + elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; + qDebug("rand() stored in array usecs: %f, first result:%d", elapsedUsecs / (float) numTests, iResults[0]); // Random number generation using randFloat() startTime.start(); for (int i = 1; i < numTests; i++) { fResults[i] = randFloat(); } - elapsedUsecs = (float)startTime.nsecsElapsed() / 1000.0; - qDebug("randFloat() stored in array usecs: %f, first result: %f", 1000.0f * elapsedUsecs / (float) numTests, fResults[0]); + elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; + qDebug("randFloat() stored in array usecs: %f, first result: %f", elapsedUsecs / (float) numTests, fResults[0]); // PowF function fTest = 1145323.2342f; @@ -432,8 +433,8 @@ void runTimingTests() { for (int i = 1; i < numTests; i++) { fTest = powf(fTest, 0.5f); } - elapsedUsecs = (float)startTime.nsecsElapsed() / 1000.0; - qDebug("powf(f, 0.5) usecs: %f", 1000.0f * elapsedUsecs / (float) numTests); + elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; + qDebug("powf(f, 0.5) usecs: %f", elapsedUsecs / (float) numTests); // Vector Math float distance; @@ -444,9 +445,9 @@ void runTimingTests() { //float distanceSquared = glm::dot(temp, temp); distance = glm::distance(pointA, pointB); } - elapsedUsecs = (float)startTime.nsecsElapsed() / 1000.0; + elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; qDebug("vector math usecs: %f [%f usecs total for %d tests], last result:%f", - 1000.0f * elapsedUsecs / (float) numTests, elapsedUsecs, numTests, distance); + elapsedUsecs / (float) numTests, elapsedUsecs, numTests, distance); // Vec3 test glm::vec3 vecA(randVector()), vecB(randVector()); @@ -457,8 +458,8 @@ void runTimingTests() { glm::vec3 temp = vecA-vecB; result = glm::dot(temp,temp); } - elapsedUsecs = (float)startTime.nsecsElapsed() / 1000.0; - qDebug("vec3 assign and dot() usecs: %f, last result:%f", 1000.0f * elapsedUsecs / (float) numTests, result); + elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; + qDebug("vec3 assign and dot() usecs: %f, last result:%f", elapsedUsecs / (float) numTests, result); } float loadSetting(QSettings* settings, const char* name, float defaultValue) { diff --git a/interface/src/starfield/Controller.cpp b/interface/src/starfield/Controller.cpp index e68243752c..2279a68422 100755 --- a/interface/src/starfield/Controller.cpp +++ b/interface/src/starfield/Controller.cpp @@ -23,7 +23,8 @@ bool Controller::computeStars(unsigned numStars, unsigned seed) { this->retile(numStars, _tileResolution); - double timeDiff = (double)startTime.nsecsElapsed() / 1000000.0; // ns to ms + double NSEC_TO_MSEC = 1.0 / 1000000.0; + double timeDiff = (double)startTime.nsecsElapsed() * NSEC_TO_MSEC; qDebug() << "Total time to retile and generate stars: " << timeDiff << "msec"; return true; From f68d2d16a83449fb6a61c6cb19bf3453ffb8bdc3 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 23 Apr 2014 11:05:16 -0700 Subject: [PATCH 593/595] Inserted a char by mistake --- interface/src/Application.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 265ff2e7a1..4adb2f772a 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1218,7 +1218,7 @@ void Application::touchEndEvent(QTouchEvent* event) { if (_controllerScriptingInterface.isTouchCaptured()) { return; } -s // put any application specific touch behavior below here.. + // put any application specific touch behavior below here.. _touchDragStartedAvgX = _touchAvgX; _touchDragStartedAvgY = _touchAvgY; _isTouchPressed = false; From fe42f66cc9afc856a850ab5944c498a061dae79d Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 23 Apr 2014 13:27:43 -0700 Subject: [PATCH 594/595] change x.f to be x.0f as per the coding standard --- tests/physics/src/ShapeColliderTests.cpp | 112 ++++++++++------------- 1 file changed, 47 insertions(+), 65 deletions(-) diff --git a/tests/physics/src/ShapeColliderTests.cpp b/tests/physics/src/ShapeColliderTests.cpp index fe1d79b456..3f952236e2 100644 --- a/tests/physics/src/ShapeColliderTests.cpp +++ b/tests/physics/src/ShapeColliderTests.cpp @@ -23,18 +23,18 @@ #include "ShapeColliderTests.h" -const glm::vec3 origin(0.f); -static const glm::vec3 xAxis(1.f, 0.f, 0.f); -static const glm::vec3 yAxis(0.f, 1.f, 0.f); -static const glm::vec3 zAxis(0.f, 0.f, 1.f); +const glm::vec3 origin(0.0f); +static const glm::vec3 xAxis(1.0f, 0.0f, 0.0f); +static const glm::vec3 yAxis(0.0f, 1.0f, 0.0f); +static const glm::vec3 zAxis(0.0f, 0.0f, 1.0f); void ShapeColliderTests::sphereMissesSphere() { // non-overlapping spheres of unequal size - float radiusA = 7.f; - float radiusB = 3.f; + float radiusA = 7.0f; + float radiusB = 3.0f; float alpha = 1.2f; float beta = 1.3f; - glm::vec3 offsetDirection = glm::normalize(glm::vec3(1.f, 2.f, 3.f)); + glm::vec3 offsetDirection = glm::normalize(glm::vec3(1.0f, 2.0f, 3.0f)); float offsetDistance = alpha * radiusA + beta * radiusB; SphereShape sphereA(radiusA, origin); @@ -77,13 +77,13 @@ void ShapeColliderTests::sphereMissesSphere() { void ShapeColliderTests::sphereTouchesSphere() { // overlapping spheres of unequal size - float radiusA = 7.f; - float radiusB = 3.f; + float radiusA = 7.0f; + float radiusB = 3.0f; float alpha = 0.2f; float beta = 0.3f; - glm::vec3 offsetDirection = glm::normalize(glm::vec3(1.f, 2.f, 3.f)); + glm::vec3 offsetDirection = glm::normalize(glm::vec3(1.0f, 2.0f, 3.0f)); float offsetDistance = alpha * radiusA + beta * radiusB; - float expectedPenetrationDistance = (1.f - alpha) * radiusA + (1.f - beta) * radiusB; + float expectedPenetrationDistance = (1.0f - alpha) * radiusA + (1.0f - beta) * radiusB; glm::vec3 expectedPenetration = expectedPenetrationDistance * offsetDirection; SphereShape sphereA(radiusA, origin); @@ -118,8 +118,7 @@ void ShapeColliderTests::sphereTouchesSphere() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } // contactPoint is on surface of sphereA @@ -129,8 +128,7 @@ void ShapeColliderTests::sphereTouchesSphere() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } } @@ -150,8 +148,7 @@ void ShapeColliderTests::sphereTouchesSphere() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } // contactPoint is on surface of sphereA @@ -161,8 +158,7 @@ void ShapeColliderTests::sphereTouchesSphere() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } } } @@ -181,7 +177,7 @@ void ShapeColliderTests::sphereMissesCapsule() { // give the capsule some arbirary transform float angle = 37.8f; - glm::vec3 axis = glm::normalize( glm::vec3(-7.f, 2.8f, 9.3f) ); + glm::vec3 axis = glm::normalize( glm::vec3(-7.0f, 2.8f, 9.3f) ); glm::quat rotation = glm::angleAxis(angle, axis); glm::vec3 translation(15.1f, -27.1f, -38.6f); capsuleB.setRotation(rotation); @@ -190,7 +186,7 @@ void ShapeColliderTests::sphereMissesCapsule() { CollisionList collisions(16); // walk sphereA along the local yAxis next to, but not touching, capsuleB - glm::vec3 localStartPosition(radialOffset, axialOffset, 0.f); + glm::vec3 localStartPosition(radialOffset, axialOffset, 0.0f); int numberOfSteps = 10; float delta = 1.3f * (totalRadius + halfHeightB) / (numberOfSteps - 1); for (int i = 0; i < numberOfSteps; ++i) { @@ -224,10 +220,10 @@ void ShapeColliderTests::sphereMissesCapsule() { void ShapeColliderTests::sphereTouchesCapsule() { // overlapping sphere and capsule - float radiusA = 2.f; - float radiusB = 1.f; + float radiusA = 2.0f; + float radiusB = 1.0f; float totalRadius = radiusA + radiusB; - float halfHeightB = 2.f; + float halfHeightB = 2.0f; float alpha = 0.5f; float beta = 0.5f; float radialOffset = alpha * radiusA + beta * radiusB; @@ -257,8 +253,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } // contactPoint is on surface of sphereA @@ -267,8 +262,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } // capsuleB collides with sphereA @@ -288,8 +282,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } // contactPoint is on surface of capsuleB @@ -300,8 +293,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } } { // sphereA hits end cap at axis @@ -319,13 +311,12 @@ void ShapeColliderTests::sphereTouchesCapsule() { // penetration points from sphereA into capsuleB CollisionInfo* collision = collisions.getCollision(numCollisions - 1); - glm::vec3 expectedPenetration = - ((1.f - alpha) * radiusA + (1.f - beta) * radiusB) * yAxis; + glm::vec3 expectedPenetration = - ((1.0f - alpha) * radiusA + (1.0f - beta) * radiusB) * yAxis; float inaccuracy = glm::length(collision->_penetration - expectedPenetration); if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } // contactPoint is on surface of sphereA @@ -334,8 +325,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } // capsuleB collides with sphereA @@ -350,13 +340,12 @@ void ShapeColliderTests::sphereTouchesCapsule() { // penetration points from sphereA into capsuleB collision = collisions.getCollision(numCollisions - 1); - expectedPenetration = ((1.f - alpha) * radiusA + (1.f - beta) * radiusB) * yAxis; + expectedPenetration = ((1.0f - alpha) * radiusA + (1.0f - beta) * radiusB) * yAxis; inaccuracy = glm::length(collision->_penetration - expectedPenetration); if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } // contactPoint is on surface of capsuleB @@ -367,8 +356,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } } { // sphereA hits start cap at axis @@ -386,13 +374,12 @@ void ShapeColliderTests::sphereTouchesCapsule() { // penetration points from sphereA into capsuleB CollisionInfo* collision = collisions.getCollision(numCollisions - 1); - glm::vec3 expectedPenetration = ((1.f - alpha) * radiusA + (1.f - beta) * radiusB) * yAxis; + glm::vec3 expectedPenetration = ((1.0f - alpha) * radiusA + (1.0f - beta) * radiusB) * yAxis; float inaccuracy = glm::length(collision->_penetration - expectedPenetration); if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } // contactPoint is on surface of sphereA @@ -401,8 +388,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } // capsuleB collides with sphereA @@ -417,13 +403,12 @@ void ShapeColliderTests::sphereTouchesCapsule() { // penetration points from sphereA into capsuleB collision = collisions.getCollision(numCollisions - 1); - expectedPenetration = - ((1.f - alpha) * radiusA + (1.f - beta) * radiusB) * yAxis; + expectedPenetration = - ((1.0f - alpha) * radiusA + (1.0f - beta) * radiusB) * yAxis; inaccuracy = glm::length(collision->_penetration - expectedPenetration); if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } // contactPoint is on surface of capsuleB @@ -434,8 +419,7 @@ void ShapeColliderTests::sphereTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } } if (collisions.size() != numCollisions) { @@ -447,10 +431,10 @@ void ShapeColliderTests::sphereTouchesCapsule() { void ShapeColliderTests::capsuleMissesCapsule() { // non-overlapping capsules - float radiusA = 2.f; - float halfHeightA = 3.f; - float radiusB = 3.f; - float halfHeightB = 4.f; + float radiusA = 2.0f; + float halfHeightA = 3.0f; + float radiusB = 3.0f; + float halfHeightB = 4.0f; float totalRadius = radiusA + radiusB; float totalHalfLength = totalRadius + halfHeightA + halfHeightB; @@ -516,10 +500,10 @@ void ShapeColliderTests::capsuleMissesCapsule() { void ShapeColliderTests::capsuleTouchesCapsule() { // overlapping capsules - float radiusA = 2.f; - float halfHeightA = 3.f; - float radiusB = 3.f; - float halfHeightB = 4.f; + float radiusA = 2.0f; + float halfHeightA = 3.0f; + float radiusB = 3.0f; + float halfHeightB = 4.0f; float totalRadius = radiusA + radiusB; float totalHalfLength = totalRadius + halfHeightA + halfHeightB; @@ -617,8 +601,7 @@ void ShapeColliderTests::capsuleTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad penetration: expected = " << expectedPenetration - << " actual = " << collision->_penetration - << std::endl; + << " actual = " << collision->_penetration; } glm::vec3 expectedContactPoint = capsuleA.getPosition() + radiusA * xAxis; @@ -626,8 +609,7 @@ void ShapeColliderTests::capsuleTouchesCapsule() { if (fabs(inaccuracy) > EPSILON) { std::cout << __FILE__ << ":" << __LINE__ << " ERROR: bad contactPoint: expected = " << expectedContactPoint - << " actual = " << collision->_contactPoint - << std::endl; + << " actual = " << collision->_contactPoint; } // capsuleB vs capsuleA @@ -706,7 +688,7 @@ void ShapeColliderTests::sphereTouchesAACube() { float cubeSide = 2.0f; float sphereRadius = 1.0f; - glm::vec3 sphereCenter(0.f); + glm::vec3 sphereCenter(0.0f); SphereShape sphere(sphereRadius, sphereCenter); float sphereOffset = (0.5f * cubeSide + sphereRadius - 0.25f); From c5f1a8abd67228477dc90a361f55f47b542d23c9 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 23 Apr 2014 13:37:13 -0700 Subject: [PATCH 595/595] formatting --- libraries/octree/src/Octree.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/libraries/octree/src/Octree.cpp b/libraries/octree/src/Octree.cpp index 06db337b70..ebfb954bd8 100644 --- a/libraries/octree/src/Octree.cpp +++ b/libraries/octree/src/Octree.cpp @@ -759,9 +759,7 @@ bool Octree::findCapsulePenetration(const glm::vec3& start, const glm::vec3& end bool Octree::findShapeCollisions(const Shape* shape, CollisionList& collisions, Octree::lockType lockType) { - ShapeArgs args = { shape, - collisions, - false }; + ShapeArgs args = { shape, collisions, false }; bool gotLock = false; if (lockType == Octree::Lock) {