3978 lines · 156.6 KB · C++
RawDownload
////  Application.cpp//  interface/src////  Created by Andrzej Kapolka on 5/10/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 <sstream> #include <stdlib.h>#include <cmath>#include <math.h> #include <glm/glm.hpp>#include <glm/gtx/component_wise.hpp>#include <glm/gtx/quaternion.hpp>#include <glm/gtx/vector_angle.hpp> // include this before QGLWidget, which includes an earlier version of OpenGL#include "InterfaceConfig.h" #include <QActionGroup>#include <QColorDialog>#include <QDesktopWidget>#include <QCheckBox>#include <QImage>#include <QInputDialog>#include <QKeyEvent>#include <QMenuBar>#include <QMouseEvent>#include <QNetworkReply>#include <QNetworkDiskCache>#include <QOpenGLFramebufferObject>#include <QObject>#include <QWheelEvent>#include <QScreen>#include <QShortcut>#include <QSystemTrayIcon>#include <QTimer>#include <QUrl>#include <QWindow>#include <QtDebug>#include <QFileDialog>#include <QDesktopServices>#include <QXmlStreamReader>#include <QXmlStreamAttributes>#include <QMediaPlayer>#include <QMimeData>#include <QMessageBox> #include <AddressManager.h>#include <AccountManager.h>#include <AmbientOcclusionEffect.h>#include <AudioInjector.h>#include <DeferredLightingEffect.h>#include <DependencyManager.h>#include <EntityScriptingInterface.h>#include <GlowEffect.h>#include <HFActionEvent.h>#include <HFBackEvent.h>#include <LogHandler.h>#include <MainWindow.h>#include <NetworkAccessManager.h>#include <OctalCode.h>#include <OctreeSceneStats.h>#include <PacketHeaders.h>#include <PathUtils.h>#include <PerfStat.h>#include <PhysicsEngine.h>#include <ProgramObject.h>#include <ResourceCache.h>#include <ScriptCache.h>#include <SettingHandle.h>#include <SoundCache.h>#include <TextRenderer.h>#include <UserActivityLogger.h>#include <UUID.h> #include "Application.h"#include "Audio.h"#include "InterfaceVersion.h"#include "LODManager.h"#include "Menu.h"#include "ModelUploader.h"#include "Util.h" #include "audio/AudioToolBox.h"#include "audio/AudioIOStatsRenderer.h"#include "audio/AudioScope.h" #include "devices/DdeFaceTracker.h"#include "devices/Faceshift.h"#include "devices/Leapmotion.h"#include "devices/RealSense.h"#include "devices/MIDIManager.h"#include "devices/OculusManager.h"#include "devices/TV3DManager.h"#include "devices/Visage.h" #include "gpu/Batch.h"#include "gpu/GLBackend.h" #include "scripting/AccountScriptingInterface.h"#include "scripting/AudioDeviceScriptingInterface.h"#include "scripting/ClipboardScriptingInterface.h"#include "scripting/JoystickScriptingInterface.h"#include "scripting/GlobalServicesScriptingInterface.h"#include "scripting/LocationScriptingInterface.h"#include "scripting/MenuScriptingInterface.h"#include "scripting/SettingsScriptingInterface.h"#include "scripting/WindowScriptingInterface.h"#include "scripting/WebWindowClass.h" #if defined(Q_OS_MAC) || defined(Q_OS_WIN)#include "SpeechRecognizer.h"#endif #include "ui/DataWebDialog.h"#include "ui/DialogsManager.h"#include "ui/InfoView.h"#include "ui/LoginDialog.h"#include "ui/Snapshot.h"#include "ui/StandAloneJSConsole.h"#include "ui/Stats.h"   using namespace std; //  Starfield informationstatic unsigned STARFIELD_NUM_STARS = 50000;static unsigned STARFIELD_SEED = 1; static const int BANDWIDTH_METER_CLICK_MAX_DRAG_LENGTH = 6; // farther dragged clicks are ignored  const qint64 MAXIMUM_CACHE_SIZE = 10737418240;  // 10GB static QTimer* idleTimer = NULL; const QString CHECK_VERSION_URL = "https://highfidelity.io/latestVersion.xml";const QString SKIP_FILENAME = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/hifi.skipversion"; const QString DEFAULT_SCRIPTS_JS_URL = "http://s3.amazonaws.com/hifi-public/scripts/defaultScripts.js"; void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message) {    QString logMessage = LogHandler::getInstance().printMessage((LogMsgType) type, context, message);        if (!logMessage.isEmpty()) {        Application::getInstance()->getLogger()->addMessage(qPrintable(logMessage + "\n"));    }} bool setupEssentials(int& argc, char** argv) {    unsigned int listenPort = 0; // bind to an ephemeral port by default    const char** constArgv = const_cast<const char**>(argv);    const char* portStr = getCmdOption(argc, constArgv, "--listenPort");    if (portStr) {        listenPort = atoi(portStr);    }    // Set build version    QCoreApplication::setApplicationVersion(BUILD_VERSION);        DependencyManager::registerInheritance<LimitedNodeList, NodeList>();        // Set dependencies    auto glCanvas = DependencyManager::set<GLCanvas>();    auto addressManager = DependencyManager::set<AddressManager>();    auto nodeList = DependencyManager::set<NodeList>(NodeType::Agent, listenPort);    auto geometryCache = DependencyManager::set<GeometryCache>();    auto glowEffect = DependencyManager::set<GlowEffect>();    auto faceshift = DependencyManager::set<Faceshift>();    auto audio = DependencyManager::set<Audio>();    auto audioScope = DependencyManager::set<AudioScope>();    auto audioIOStatsRenderer = DependencyManager::set<AudioIOStatsRenderer>();    auto deferredLightingEffect = DependencyManager::set<DeferredLightingEffect>();    auto ambientOcclusionEffect = DependencyManager::set<AmbientOcclusionEffect>();    auto textureCache = DependencyManager::set<TextureCache>();    auto animationCache = DependencyManager::set<AnimationCache>();    auto visage = DependencyManager::set<Visage>();    auto ddeFaceTracker = DependencyManager::set<DdeFaceTracker>();    auto modelBlender = DependencyManager::set<ModelBlender>();    auto audioToolBox = DependencyManager::set<AudioToolBox>();    auto lodManager = DependencyManager::set<LODManager>();    auto jsConsole = DependencyManager::set<StandAloneJSConsole>();    auto dialogsManager = DependencyManager::set<DialogsManager>();    auto bandwidthRecorder = DependencyManager::set<BandwidthRecorder>();    auto resouceCacheSharedItems = DependencyManager::set<ResouceCacheSharedItems>();#if defined(Q_OS_MAC) || defined(Q_OS_WIN)    auto speechRecognizer = DependencyManager::set<SpeechRecognizer>();#endif        return true;} Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) :        QApplication(argc, argv),        _dependencyManagerIsSetup(setupEssentials(argc, argv)),        _window(new MainWindow(desktop())),        _toolWindow(NULL),        _nodeThread(new QThread(this)),        _datagramProcessor(),        _undoStack(),        _undoStackScriptingInterface(&_undoStack),        _frameCount(0),        _fps(60.0f),        _justStarted(true),        _physicsEngine(glm::vec3(0.0f)),        _entities(true, this, this),        _entityClipboardRenderer(false, this, this),        _entityClipboard(),        _viewFrustum(),        _lastQueriedViewFrustum(),        _lastQueriedTime(usecTimestampNow()),        _mirrorViewRect(QRect(MIRROR_VIEW_LEFT_PADDING, MIRROR_VIEW_TOP_PADDING, MIRROR_VIEW_WIDTH, MIRROR_VIEW_HEIGHT)),        _firstRun("firstRun", true),        _previousScriptLocation("LastScriptLocation"),        _scriptsLocationHandle("scriptsLocation"),        _fieldOfView("fieldOfView", DEFAULT_FIELD_OF_VIEW_DEGREES),        _viewTransform(),        _scaleMirror(1.0f),        _rotateMirror(0.0f),        _raiseMirror(0.0f),        _lastMouseMove(usecTimestampNow()),        _lastMouseMoveWasSimulated(false),        _touchAvgX(0.0f),        _touchAvgY(0.0f),        _isTouchPressed(false),        _mousePressed(false),        _enableProcessOctreeThread(true),        _octreeProcessor(),        _nodeBoundsDisplay(this),        _applicationOverlay(),        _runningScriptsWidget(NULL),        _runningScriptsWidgetWasVisible(false),        _trayIcon(new QSystemTrayIcon(_window)),        _lastNackTime(usecTimestampNow()),        _lastSendDownstreamAudioStats(usecTimestampNow()),        _isVSyncOn(true),        _aboutToQuit(false),        _notifiedPacketVersionMismatchThisDomain(false){    _logger = new FileLogger(this);  // After setting organization name in order to get correct directory    qInstallMessageHandler(messageHandler);        QFontDatabase::addApplicationFont(PathUtils::resourcesPath() + "styles/Inconsolata.otf");    _window->setWindowTitle("Interface");        Model::setAbstractViewStateInterface(this); // The model class will sometimes need to know view state details from us        auto glCanvas = DependencyManager::get<GLCanvas>();    auto nodeList = DependencyManager::get<NodeList>();     _myAvatar = _avatarManager.getMyAvatar();     _applicationStartupTime = startup_time;     qDebug() << "[VERSION] Build sequence: " << qPrintable(applicationVersion());     _bookmarks = new Bookmarks();  // Before setting up the menu     // call Menu getInstance static method to set up the menu    _window->setMenuBar(Menu::getInstance());     _runningScriptsWidget = new RunningScriptsWidget(_window);        // start the nodeThread so its event loop is running    _nodeThread->setObjectName("Datagram Processor Thread");    _nodeThread->start();     // make sure the node thread is given highest priority    _nodeThread->setPriority(QThread::TimeCriticalPriority);        // put the NodeList and datagram processing on the node thread    nodeList->moveToThread(_nodeThread);    _datagramProcessor.moveToThread(_nodeThread);     // connect the DataProcessor processDatagrams slot to the QUDPSocket readyRead() signal    connect(&nodeList->getNodeSocket(), SIGNAL(readyRead()), &_datagramProcessor, SLOT(processDatagrams()));     // put the audio processing on a separate thread    QThread* audioThread = new QThread(this);    audioThread->setObjectName("Audio Thread");        auto audioIO = DependencyManager::get<Audio>();    audioIO->moveToThread(audioThread);    connect(audioThread, &QThread::started, audioIO.data(), &Audio::start);    connect(audioIO.data(), SIGNAL(muteToggled()), this, SLOT(audioMuteToggled()));     audioThread->start();        const DomainHandler& domainHandler = nodeList->getDomainHandler();     connect(&domainHandler, SIGNAL(hostnameChanged(const QString&)), SLOT(domainChanged(const QString&)));    connect(&domainHandler, SIGNAL(connectedToDomain(const QString&)), SLOT(connectedToDomain(const QString&)));    connect(&domainHandler, SIGNAL(connectedToDomain(const QString&)), SLOT(updateWindowTitle()));    connect(&domainHandler, SIGNAL(disconnectedFromDomain()), SLOT(updateWindowTitle()));    connect(&domainHandler, SIGNAL(disconnectedFromDomain()), SLOT(clearDomainOctreeDetails()));    connect(&domainHandler, &DomainHandler::settingsReceived, this, &Application::domainSettingsReceived);    connect(&domainHandler, &DomainHandler::hostnameChanged,            DependencyManager::get<AddressManager>().data(), &AddressManager::storeCurrentAddress);     // update our location every 5 seconds in the data-server, assuming that we are authenticated with one    const qint64 DATA_SERVER_LOCATION_CHANGE_UPDATE_MSECS = 5 * 1000;     QTimer* locationUpdateTimer = new QTimer(this);    connect(locationUpdateTimer, &QTimer::timeout, this, &Application::updateLocationInServer);    locationUpdateTimer->start(DATA_SERVER_LOCATION_CHANGE_UPDATE_MSECS);     connect(nodeList.data(), &NodeList::nodeAdded, this, &Application::nodeAdded);    connect(nodeList.data(), &NodeList::nodeKilled, this, &Application::nodeKilled);    connect(nodeList.data(), SIGNAL(nodeKilled(SharedNodePointer)), SLOT(nodeKilled(SharedNodePointer)));    connect(nodeList.data(), &NodeList::uuidChanged, _myAvatar, &MyAvatar::setSessionUUID);    connect(nodeList.data(), &NodeList::limitOfSilentDomainCheckInsReached, nodeList.data(), &NodeList::reset);    connect(nodeList.data(), &NodeList::packetVersionMismatch, this, &Application::notifyPacketVersionMismatch);     // connect to appropriate slots on AccountManager    AccountManager& accountManager = AccountManager::getInstance();     const qint64 BALANCE_UPDATE_INTERVAL_MSECS = 5 * 1000;     QTimer* balanceUpdateTimer = new QTimer(this);    connect(balanceUpdateTimer, &QTimer::timeout, &accountManager, &AccountManager::updateBalance);    balanceUpdateTimer->start(BALANCE_UPDATE_INTERVAL_MSECS);     connect(&accountManager, &AccountManager::balanceChanged, this, &Application::updateWindowTitle);     auto dialogsManager = DependencyManager::get<DialogsManager>();    connect(&accountManager, &AccountManager::authRequired, dialogsManager.data(), &DialogsManager::showLoginDialog);    connect(&accountManager, &AccountManager::usernameChanged, this, &Application::updateWindowTitle);        // once we have a profile in account manager make sure we generate a new keypair    connect(&accountManager, &AccountManager::profileChanged, &accountManager, &AccountManager::generateNewKeypair);     // set the account manager's root URL and trigger a login request if we don't have the access token    accountManager.setAuthURL(DEFAULT_NODE_AUTH_URL);    UserActivityLogger::getInstance().launch(applicationVersion());     // once the event loop has started, check and signal for an access token    QMetaObject::invokeMethod(&accountManager, "checkAndSignalForAccessToken", Qt::QueuedConnection);        auto addressManager = DependencyManager::get<AddressManager>();        // use our MyAvatar position and quat for address manager path    addressManager->setPositionGetter(getPositionForPath);    addressManager->setOrientationGetter(getOrientationForPath);        connect(addressManager.data(), &AddressManager::rootPlaceNameChanged, this, &Application::updateWindowTitle);     #ifdef _WIN32    WSADATA WsaData;    int wsaresult = WSAStartup(MAKEWORD(2,2), &WsaData);    #endif     // tell the NodeList instance who to tell the domain server we care about    nodeList->addSetOfNodeTypesToNodeInterestSet(NodeSet() << NodeType::AudioMixer << NodeType::AvatarMixer                                                 << NodeType::EntityServer                                                 << NodeType::MetavoxelServer);     // connect to the packet sent signal of the _entityEditSender    connect(&_entityEditSender, &EntityEditPacketSender::packetSent, this, &Application::packetSent);     // move the silentNodeTimer to the _nodeThread    QTimer* silentNodeTimer = new QTimer();    connect(silentNodeTimer, SIGNAL(timeout()), nodeList.data(), SLOT(removeSilentNodes()));    silentNodeTimer->start(NODE_SILENCE_THRESHOLD_MSECS);    silentNodeTimer->moveToThread(_nodeThread);     // send the identity packet for our avatar each second to our avatar mixer    QTimer* identityPacketTimer = new QTimer();    connect(identityPacketTimer, &QTimer::timeout, _myAvatar, &MyAvatar::sendIdentityPacket);    identityPacketTimer->start(AVATAR_IDENTITY_PACKET_SEND_INTERVAL_MSECS);     // send the billboard packet for our avatar every few seconds    QTimer* billboardPacketTimer = new QTimer();    connect(billboardPacketTimer, &QTimer::timeout, _myAvatar, &MyAvatar::sendBillboardPacket);    billboardPacketTimer->start(AVATAR_BILLBOARD_PACKET_SEND_INTERVAL_MSECS);     QString cachePath = QStandardPaths::writableLocation(QStandardPaths::DataLocation);    QNetworkAccessManager& networkAccessManager = NetworkAccessManager::getInstance();    QNetworkDiskCache* cache = new QNetworkDiskCache();    cache->setMaximumCacheSize(MAXIMUM_CACHE_SIZE);    cache->setCacheDirectory(!cachePath.isEmpty() ? cachePath : "interfaceCache");    networkAccessManager.setCache(cache);     ResourceCache::setRequestLimit(3);     _window->setCentralWidget(glCanvas.data());     _window->restoreGeometry();     _window->setVisible(true);    glCanvas->setFocusPolicy(Qt::StrongFocus);    glCanvas->setFocus();     // enable mouse tracking; otherwise, we only get drag events    glCanvas->setMouseTracking(true);     _toolWindow = new ToolWindow();    _toolWindow->setWindowFlags(_toolWindow->windowFlags() | Qt::WindowStaysOnTopHint);    _toolWindow->setWindowTitle("Tools");     // initialization continues in initializeGL when OpenGL context is ready     // Tell our entity edit sender about our known jurisdictions    _entityEditSender.setServerJurisdictions(&_entityServerJurisdictions);     // For now we're going to set the PPS for outbound packets to be super high, this is    // probably not the right long term solution. But for now, we're going to do this to    // allow you to move an entity around in your hand    _entityEditSender.setPacketsPerSecond(3000); // super high!!     checkVersion();     _overlays.init(glCanvas.data()); // do this before scripts load     _runningScriptsWidget->setRunningScripts(getRunningScripts());    connect(_runningScriptsWidget, &RunningScriptsWidget::stopScriptName, this, &Application::stopScript);     connect(this, SIGNAL(aboutToQuit()), this, SLOT(saveScripts()));    connect(this, SIGNAL(aboutToQuit()), this, SLOT(aboutToQuit()));     // hook up bandwidth estimator    QSharedPointer<BandwidthRecorder> bandwidthRecorder = DependencyManager::get<BandwidthRecorder>();    connect(nodeList.data(), SIGNAL(dataSent(const quint8, const int)),            bandwidthRecorder.data(), SLOT(updateOutboundData(const quint8, const int)));    connect(nodeList.data(), SIGNAL(dataReceived(const quint8, const int)),            bandwidthRecorder.data(), SLOT(updateInboundData(const quint8, const int)));     // check first run...    if (_firstRun.get()) {        qDebug() << "This is a first run...";        // clear the scripts, and set out script to our default scripts        clearScriptsBeforeRunning();        loadScript(DEFAULT_SCRIPTS_JS_URL);         _firstRun.set(false);    } else {        // do this as late as possible so that all required subsystems are initialized        loadScripts();    }        loadSettings();    int SAVE_SETTINGS_INTERVAL = 10 * MSECS_PER_SECOND; // Let's save every seconds for now    connect(&_settingsTimer, &QTimer::timeout, this, &Application::saveSettings);    connect(&_settingsThread, SIGNAL(started()), &_settingsTimer, SLOT(start()));    connect(&_settingsThread, SIGNAL(finished()), &_settingsTimer, SLOT(stop()));    _settingsTimer.moveToThread(&_settingsThread);    _settingsTimer.setSingleShot(false);    _settingsTimer.setInterval(SAVE_SETTINGS_INTERVAL);    _settingsThread.start();        _trayIcon->show();        // set the local loopback interface for local sounds from audio scripts    AudioScriptingInterface::getInstance().setLocalAudioInterface(audioIO.data());    #ifdef HAVE_RTMIDI    // setup the MIDIManager    MIDIManager& midiManagerInstance = MIDIManager::getInstance();    midiManagerInstance.openDefaultPort();#endif     this->installEventFilter(this);} void Application::aboutToQuit() {    _aboutToQuit = true;    setFullscreen(false); // if you exit while in full screen, you'll get bad behavior when you restart.} Application::~Application() {    QMetaObject::invokeMethod(&_settingsTimer, "stop", Qt::BlockingQueuedConnection);    _settingsThread.quit();    saveSettings();        _entities.getTree()->setSimulation(NULL);    qInstallMessageHandler(NULL);        _window->saveGeometry();        int DELAY_TIME = 1000;    UserActivityLogger::getInstance().close(DELAY_TIME);        // make sure we don't call the idle timer any more    delete idleTimer;        // 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();        // kill any audio injectors that are still around    AudioScriptingInterface::getInstance().stopAllInjectors();

Lines 1–500 of 3978.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t