<commit_before>//------------------------------------------------------------------------------
//  emscURLLoader.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "emscURLLoader.h"
#include "IO/MemoryStream.h"
#include <emscripten/emscripten.h>

namespace Oryol {
namespace HTTP {

using namespace Core;
using namespace IO;

//------------------------------------------------------------------------------
void
emscURLLoader::doWork() {
    while (!this->requestQueue.Empty()) {
        this->startRequest(this->requestQueue.Dequeue());
    }
}

//------------------------------------------------------------------------------
void
emscURLLoader::startRequest(const Ptr<HTTPProtocol::HTTPRequest>& req) {
    o_assert(req.isValid() && !req->Handled());

    // currently only support GET
    o_assert(req->GetMethod() == HTTPMethod::Get);

    // bump the requests refcount and get a raw pointer
    HTTPProtocol::HTTPRequest* reqPtr = req.get();
    reqPtr->addRef();

    // start the asynchronous XHR
    // NOTE: we can only load from our own HTTP server, so the host part of
    // the URL is completely irrelevant...
    String urlPath = req->GetURL().PathToEnd().AsCStr();
    Log::Dbg("emscURLLoader::startRequest(): %s\n", urlPath.AsCStr());
    emscripten_async_wget_data(urlPath.AsCStr(), (void*) reqPtr, emscURLLoader::onLoaded, emscURLLoader::onFailed);
}

//------------------------------------------------------------------------------
void
emscURLLoader::onLoaded(void* userData, void* buffer, int size) {
    o_assert(0 != userData);
    o_assert(0 != buffer);
    o_assert(size > 0);

    // user data is a HTTPRequest ptr, put it back into a smart pointer
    Ptr<HTTPProtocol::HTTPRequest> req = userData;
    req->release();
    Log::Dbg("emscURLLoader::onLoaded(url=%s, size=%d)\n", req->GetURL().AsCStr(), size);

    // create a HTTPResponse and fill it out
    Ptr<HTTPProtocol::HTTPResponse> response = HTTPProtocol::HTTPResponse::Create();
    response->SetStatus(IOStatus::OK);

    // create a MemoryStream object and fill it with the received data
    Ptr<MemoryStream> responseBody = MemoryStream::Create();
    responseBody->Open(OpenMode::WriteOnly);
    responseBody->Write(buffer, size);
    responseBody->Close();
    response->SetBody(responseBody);

    // set the response on the request, mark the request as handled
    req->SetResponse(response);
    req->SetHandled();
}

//------------------------------------------------------------------------------
void
emscURLLoader::onFailed(void* userData) {
    o_assert(0 != userData);

    // user data is a HTTPRequest ptr, put it back into a smart pointer
    Ptr<HTTPProtocol::HTTPRequest> req = userData;
    req->release();
    Log::Dbg("emscURLLoader::onFailed(url=%s)\n", req->GetURL().AsCStr());

    // hmm we don't know why it failed, so make something up, we should definitely
    // fix this somehow (looks like the wget2 functions also pass a HTTP status code)
    Ptr<HTTPProtocol::HTTPResponse> response = HTTPProtocol::HTTPResponse::Create();
    response->SetStatus(IOStatus::NotFound);
    req->SetResponse(response);
    req->SetHandled();
}

} // namespace HTTP
} // naespace Oryol
<commit_msg>Fixed minor inefficiency when getting URL path<commit_after>//------------------------------------------------------------------------------
//  emscURLLoader.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "emscURLLoader.h"
#include "IO/MemoryStream.h"
#include <emscripten/emscripten.h>

namespace Oryol {
namespace HTTP {

using namespace Core;
using namespace IO;

//------------------------------------------------------------------------------
void
emscURLLoader::doWork() {
    while (!this->requestQueue.Empty()) {
        this->startRequest(this->requestQueue.Dequeue());
    }
}

//------------------------------------------------------------------------------
void
emscURLLoader::startRequest(const Ptr<HTTPProtocol::HTTPRequest>& req) {
    o_assert(req.isValid() && !req->Handled());

    // currently only support GET
    o_assert(req->GetMethod() == HTTPMethod::Get);

    // bump the requests refcount and get a raw pointer
    HTTPProtocol::HTTPRequest* reqPtr = req.get();
    reqPtr->addRef();

    // start the asynchronous XHR
    // NOTE: we can only load from our own HTTP server, so the host part of
    // the URL is completely irrelevant...
    String urlPath = req->GetURL().PathToEnd();
    Log::Dbg("emscURLLoader::startRequest(): %s\n", urlPath.AsCStr());
    emscripten_async_wget_data(urlPath.AsCStr(), (void*) reqPtr, emscURLLoader::onLoaded, emscURLLoader::onFailed);
}

//------------------------------------------------------------------------------
void
emscURLLoader::onLoaded(void* userData, void* buffer, int size) {
    o_assert(0 != userData);
    o_assert(0 != buffer);
    o_assert(size > 0);

    // user data is a HTTPRequest ptr, put it back into a smart pointer
    Ptr<HTTPProtocol::HTTPRequest> req = userData;
    req->release();
    Log::Dbg("emscURLLoader::onLoaded(url=%s, size=%d)\n", req->GetURL().AsCStr(), size);

    // create a HTTPResponse and fill it out
    Ptr<HTTPProtocol::HTTPResponse> response = HTTPProtocol::HTTPResponse::Create();
    response->SetStatus(IOStatus::OK);

    // create a MemoryStream object and fill it with the received data
    Ptr<MemoryStream> responseBody = MemoryStream::Create();
    responseBody->Open(OpenMode::WriteOnly);
    responseBody->Write(buffer, size);
    responseBody->Close();
    response->SetBody(responseBody);

    // set the response on the request, mark the request as handled
    req->SetResponse(response);
    req->SetHandled();
}

//------------------------------------------------------------------------------
void
emscURLLoader::onFailed(void* userData) {
    o_assert(0 != userData);

    // user data is a HTTPRequest ptr, put it back into a smart pointer
    Ptr<HTTPProtocol::HTTPRequest> req = userData;
    req->release();
    Log::Dbg("emscURLLoader::onFailed(url=%s)\n", req->GetURL().AsCStr());

    // hmm we don't know why it failed, so make something up, we should definitely
    // fix this somehow (looks like the wget2 functions also pass a HTTP status code)
    Ptr<HTTPProtocol::HTTPResponse> response = HTTPProtocol::HTTPResponse::Create();
    response->SetStatus(IOStatus::NotFound);
    req->SetResponse(response);
    req->SetHandled();
}

} // namespace HTTP
} // naespace Oryol
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
//  Paclone.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/App.h"
#include "Gfx/Gfx.h"
#include "Input/Input.h"
#include "canvas.h"
#include "game.h"

using namespace Oryol;
using namespace Paclone;

class PacloneApp : public App {
public:
    AppState::Code OnRunning();
    AppState::Code OnInit();
    AppState::Code OnCleanup();

private:
    game::Direction getInput();

    canvas spriteCanvas;
    game gameState;
    int32 tick;
};
OryolMain(PacloneApp);

//------------------------------------------------------------------------------
AppState::Code
PacloneApp::OnInit() {

    this->tick = 0;
    const int dispWidth = game::Width * 8 * 2;
    const int dispHeight = game::Height * 8 * 2;
    Gfx::Setup(GfxSetup::Window(dispWidth, dispHeight, "Oryol Pacman Clone Sample"));
    Input::Setup();

    this->spriteCanvas.Setup(game::Width, game::Height, 8, 8, game::NumSprites);
    this->gameState.Init(&this->spriteCanvas);

    return App::OnInit();
}

//------------------------------------------------------------------------------
AppState::Code
PacloneApp::OnRunning() {

    Gfx::ApplyDefaultRenderTarget();
    Gfx::Clear(PixelChannel::All, glm::vec4(0.0f), 1.0f, 0);
    game::Direction input = this->getInput();
    this->gameState.Update(this->tick, &this->spriteCanvas, input);
    this->spriteCanvas.Render();

    Gfx::CommitFrame();
    this->tick++;

    // continue running or quit?
    return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;
}

//------------------------------------------------------------------------------
AppState::Code
PacloneApp::OnCleanup() {
    this->gameState.Cleanup();
    this->spriteCanvas.Discard();
    Input::Discard();
    Gfx::Discard();
    return App::OnCleanup();
}

//------------------------------------------------------------------------------
game::Direction
PacloneApp::getInput() {
    // FIXME: add more input options
    game::Direction input = game::NoDirection;
    const Keyboard& kbd = Input::Keyboard();
    if (kbd.Attached) {
        if (kbd.KeyPressed(Key::Left))       input = game::Left;
        else if (kbd.KeyPressed(Key::Right)) input = game::Right;
        else if (kbd.KeyPressed(Key::Up))    input = game::Up;
        else if (kbd.KeyPressed(Key::Down))  input = game::Down;
    }
    return input;
}
<commit_msg>Paclone: set viewport to retain proper aspect ratio<commit_after>//------------------------------------------------------------------------------
//  Paclone.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/App.h"
#include "Gfx/Gfx.h"
#include "Input/Input.h"
#include "canvas.h"
#include "game.h"

using namespace Oryol;
using namespace Paclone;

class PacloneApp : public App {
public:
    AppState::Code OnRunning();
    AppState::Code OnInit();
    AppState::Code OnCleanup();

private:
    game::Direction getInput();

    canvas spriteCanvas;
    game gameState;
    int32 tick;
    int32 viewPortX;
    int32 viewPortY;
    int32 viewPortW;
    int32 viewPortH;
};
OryolMain(PacloneApp);

//------------------------------------------------------------------------------
AppState::Code
PacloneApp::OnInit() {

    this->tick = 0;
    const int dispWidth = game::Width * 8 * 2;
    const int dispHeight = game::Height * 8 * 2;
    Gfx::Setup(GfxSetup::Window(dispWidth, dispHeight, "Oryol Pacman Clone Sample"));
    Input::Setup();

    this->spriteCanvas.Setup(game::Width, game::Height, 8, 8, game::NumSprites);
    this->gameState.Init(&this->spriteCanvas);

    // get actual display width and height and compute viewport
    float aspect = float(dispWidth) / float(dispHeight);
    const int actWidth = Gfx::DisplayAttrs().WindowWidth;
    const int actHeight = Gfx::DisplayAttrs().WindowHeight;
    this->viewPortY = 0;
    this->viewPortH = actHeight;
    this->viewPortW = actHeight * aspect;
    this->viewPortX = (actWidth - this->viewPortW) / 2;

    return App::OnInit();
}

//------------------------------------------------------------------------------
AppState::Code
PacloneApp::OnRunning() {

    Gfx::ApplyDefaultRenderTarget();
    Gfx::ApplyViewPort(this->viewPortX, this->viewPortY, this->viewPortW, this->viewPortH);
    Gfx::Clear(PixelChannel::All, glm::vec4(0.0f), 1.0f, 0);
    game::Direction input = this->getInput();
    this->gameState.Update(this->tick, &this->spriteCanvas, input);
    this->spriteCanvas.Render();

    Gfx::CommitFrame();
    this->tick++;

    // continue running or quit?
    return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;
}

//------------------------------------------------------------------------------
AppState::Code
PacloneApp::OnCleanup() {
    this->gameState.Cleanup();
    this->spriteCanvas.Discard();
    Input::Discard();
    Gfx::Discard();
    return App::OnCleanup();
}

//------------------------------------------------------------------------------
game::Direction
PacloneApp::getInput() {
    // FIXME: add more input options
    game::Direction input = game::NoDirection;
    const Keyboard& kbd = Input::Keyboard();
    if (kbd.Attached) {
        if (kbd.KeyPressed(Key::Left))       input = game::Left;
        else if (kbd.KeyPressed(Key::Right)) input = game::Right;
        else if (kbd.KeyPressed(Key::Up))    input = game::Up;
        else if (kbd.KeyPressed(Key::Down))  input = game::Down;
    }
    return input;
}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2019 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
//    * Neither the name of the author nor the names of other contributors may
//      be used to endorse or promote products derived from this software
//      without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////

#include "Constants.h"
#include "OpenMptDecoder.h"
#include <core/sdk/IDebug.h>
#include <cassert>

extern IDebug* debug;

OpenMptDecoder::OpenMptDecoder() {
}

OpenMptDecoder::~OpenMptDecoder() {
}

bool OpenMptDecoder::Open(musik::core::sdk::IDataStream *stream) {
}

void OpenMptDecoder::Release() {
    delete this;
}

double OpenMptDecoder::SetPosition(double seconds) {
    return 0.0;
}

double OpenMptDecoder::GetDuration() {
    return 0.0;
}

bool OpenMptDecoder::GetBuffer(IBuffer *target) {
    return false;
}

bool OpenMptDecoder::Exhausted() {
    return false;
}
<commit_msg>Scaffolding compiles in *nix platforms. Next up: Windows<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2019 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
//    * Neither the name of the author nor the names of other contributors may
//      be used to endorse or promote products derived from this software
//      without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////

#include "OpenMptDecoder.h"
#include <core/sdk/IDebug.h>
#include <cassert>

extern IDebug* debug;

OpenMptDecoder::OpenMptDecoder() {
}

OpenMptDecoder::~OpenMptDecoder() {
}

bool OpenMptDecoder::Open(musik::core::sdk::IDataStream *stream) {
    return false;
}

void OpenMptDecoder::Release() {
    delete this;
}

double OpenMptDecoder::SetPosition(double seconds) {
    return 0.0;
}

double OpenMptDecoder::GetDuration() {
    return 0.0;
}

bool OpenMptDecoder::GetBuffer(IBuffer *target) {
    return false;
}

bool OpenMptDecoder::Exhausted() {
    return false;
}
<|endoftext|>


<commit_before>//==============================================================================
// Compiler plugin
//==============================================================================

#include "compilerplugin.h"

//==============================================================================

namespace OpenCOR {
namespace Compiler {

//==============================================================================

PLUGININFO_FUNC CompilerPluginInfo()
{
    Descriptions descriptions;

    descriptions.insert("en", QString::fromUtf8("A plugin to support code compilation"));
    descriptions.insert("fr", QString::fromUtf8("Une extension pour supporter la compilation de code"));

    return new PluginInfo(PluginInfo::InterfaceVersion001,
                          PluginInfo::General,
                          PluginInfo::Miscellaneous,
                          false,
                          QStringList() << "CoreSolver" << "LLVM",
                          descriptions);
}

//==============================================================================

}   // namespace Compiler
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up.<commit_after>//==============================================================================
// Compiler plugin
//==============================================================================

#include "compilerplugin.h"

//==============================================================================

namespace OpenCOR {
namespace Compiler {

//==============================================================================

PLUGININFO_FUNC CompilerPluginInfo()
{
    Descriptions descriptions;

    descriptions.insert("en", QString::fromUtf8("A plugin to support code compilation"));
    descriptions.insert("fr", QString::fromUtf8("Une extension pour supporter la compilation de code"));

    return new PluginInfo(PluginInfo::InterfaceVersion001,
                          PluginInfo::General,
                          PluginInfo::Miscellaneous,
                          false,
                          QStringList() << "LLVM",
                          descriptions);
}

//==============================================================================

}   // namespace Compiler
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<|endoftext|>


<commit_before>/*
 * basic.cpp
 *
 * Implementation of Basic cluster server.
 * Send ZCL attribute response to read request on Basic Cluster attributes.
 *
 * 0x0000 ZCL Version    / Just to test
 * 0xF000 Running time   / Used for Legrand device
 *
 */

#include "de_web_plugin.h"
#include "de_web_plugin_private.h"

/*! Handle packets related to the ZCL Basic cluster.
    \param ind the APS level data indication containing the ZCL packet
    \param zclFrame the actual ZCL frame which holds the read attribute request
 */
void DeRestPluginPrivate::handleBasicClusterIndication(const deCONZ::ApsDataIndication &ind, deCONZ::ZclFrame &zclFrame)
{
    if (zclFrame.isProfileWideCommand() && zclFrame.commandId() == deCONZ::ZclReadAttributesId)
    {
        sendBasicClusterResponse(ind, zclFrame);
    }
}

/*! Sends read attributes response to Basic client.
    \param ind the APS level data indication containing the ZCL packet
    \param zclFrame the actual ZCL frame which holds the read attributes request
 */
void DeRestPluginPrivate::sendBasicClusterResponse(const deCONZ::ApsDataIndication &ind, deCONZ::ZclFrame &zclFrame)
{
    deCONZ::ApsDataRequest req;
    deCONZ::ZclFrame outZclFrame;

    req.setProfileId(ind.profileId());
    req.setClusterId(ind.clusterId());
    req.setDstAddressMode(ind.srcAddressMode());
    req.dstAddress() = ind.srcAddress();
    req.setDstEndpoint(ind.srcEndpoint());
    req.setSrcEndpoint(endpoint());

    outZclFrame.setSequenceNumber(zclFrame.sequenceNumber());
    outZclFrame.setCommandId(deCONZ::ZclReadAttributesResponseId);

    outZclFrame.setFrameControl(deCONZ::ZclFCProfileCommand |
                                deCONZ::ZclFCDirectionServerToClient |
                                deCONZ::ZclFCDisableDefaultResponse);

    //is there manufacture field in the request, if yes add it.
    if (zclFrame.frameControl() & deCONZ::ZclFCManufacturerSpecific)
    {
        quint16 manucode = zclFrame.manufacturerCode();
        outZclFrame.setFrameControl(outZclFrame.frameControl() | deCONZ::ZclFCManufacturerSpecific);
        outZclFrame.setManufacturerCode(manucode);
    }

    { // payload
        QDataStream stream(&outZclFrame.payload(), QIODevice::WriteOnly);
        stream.setByteOrder(QDataStream::LittleEndian);

        QDataStream instream(zclFrame.payload());
        instream.setByteOrder(QDataStream::LittleEndian);
        quint8 code = 0x00; // success
        quint16 attr;

        while (!instream.atEnd())
        {
            instream >> attr;
            stream << attr;

            switch(attr)
            {
            case 0x0000:
                //ZCL version
                stream << code;
                stream << (quint8) deCONZ::Zcl8BitUint;
                stream << 0x02;
                break;

            case 0xF000:
                //Legrand attribute used for pairing
                stream << code;
                stream << (quint8) deCONZ::Zcl32BitUint;
                stream << 0x000000d5;
                break;

            default:
            {
                stream << (quint8) 0x86;  // unsupported_attribute
            }
            break;
            }
        }
    }

    { // ZCL frame
        QDataStream stream(&req.asdu(), QIODevice::WriteOnly);
        stream.setByteOrder(QDataStream::LittleEndian);
        outZclFrame.writeToStream(stream);
    }

    if (apsCtrl && apsCtrl->apsdeDataRequest(req) != deCONZ::Success)
    {
        DBG_Printf(DBG_INFO, "Basic failed to send reponse\n");
    }

}
<commit_msg>Update basic.cpp<commit_after>/*
 * basic.cpp
 *
 * Implementation of Basic cluster server.
 * Send ZCL attribute response to read request on Basic Cluster attributes.
 *
 * 0x0000 ZCL Version    / Just to test
 * 0xF000 Running time   / Used for Legrand device
 *
 */

#include "de_web_plugin.h"
#include "de_web_plugin_private.h"

/*! Handle packets related to the ZCL Basic cluster.
    \param ind the APS level data indication containing the ZCL packet
    \param zclFrame the actual ZCL frame which holds the read attribute request
 */
void DeRestPluginPrivate::handleBasicClusterIndication(const deCONZ::ApsDataIndication &ind, deCONZ::ZclFrame &zclFrame)
{
    if (zclFrame.isProfileWideCommand() && zclFrame.commandId() == deCONZ::ZclReadAttributesId)
    {
        sendBasicClusterResponse(ind, zclFrame);
    }
}

/*! Sends read attributes response to Basic client.
    \param ind the APS level data indication containing the ZCL packet
    \param zclFrame the actual ZCL frame which holds the read attributes request
 */
void DeRestPluginPrivate::sendBasicClusterResponse(const deCONZ::ApsDataIndication &ind, deCONZ::ZclFrame &zclFrame)
{
    deCONZ::ApsDataRequest req;
    deCONZ::ZclFrame outZclFrame;

    req.setProfileId(ind.profileId());
    req.setClusterId(ind.clusterId());
    req.setDstAddressMode(ind.srcAddressMode());
    req.dstAddress() = ind.srcAddress();
    req.setDstEndpoint(ind.srcEndpoint());
    req.setSrcEndpoint(endpoint());

    outZclFrame.setSequenceNumber(zclFrame.sequenceNumber());
    outZclFrame.setCommandId(deCONZ::ZclReadAttributesResponseId);

    outZclFrame.setFrameControl(deCONZ::ZclFCProfileCommand |
                                deCONZ::ZclFCDirectionServerToClient |
                                deCONZ::ZclFCDisableDefaultResponse);

    //is there manufacture field in the request, if yes add it.
    if (zclFrame.frameControl() & deCONZ::ZclFCManufacturerSpecific)
    {
        quint16 manucode = zclFrame.manufacturerCode();
        outZclFrame.setFrameControl(outZclFrame.frameControl() | deCONZ::ZclFCManufacturerSpecific);
        outZclFrame.setManufacturerCode(manucode);
    }

    { // payload
        QDataStream stream(&outZclFrame.payload(), QIODevice::WriteOnly);
        stream.setByteOrder(QDataStream::LittleEndian);

        QDataStream instream(zclFrame.payload());
        instream.setByteOrder(QDataStream::LittleEndian);
        quint8 code = 0x00; // success
        quint16 attr;

        while (!instream.atEnd())
        {
            instream >> attr;
            stream << attr;

            switch (attr)
            {
            case 0x0000: // ZCL Version
                stream << code;
                stream << (quint8) deCONZ::Zcl8BitUint;
                stream << (quint8) 0x02;
                break;

            case 0x0001: // Application Version
                stream << code;
                stream << (quint8) deCONZ::Zcl8BitUint;
                stream << (quint8) 0x00;
                break;

            case 0x0002: // Stack Version
                stream << code;
                stream << (quint8) deCONZ::Zcl8BitUint;
                stream << (quint8) 0x00;
                break;

            case 0x0003: // HW Version
                stream << code;
                stream << (quint8) deCONZ::Zcl8BitUint;
                stream << (quint8) 0x00;
                break;

            case 0x0004: // Manufacturer Name
            {
                const char *name = "dresden elektronik";
                const quint8 length = strlen(name);

                stream << code;
                stream << (quint8) deCONZ::ZclCharacterString;
                stream << length;
                for (uint i = 0; i < length; i++)
                {
                    stream << (quint8) name[i];
                }
            }
                break;

            case 0x0005: // Model Identifier
            {
                const QByteArray id = gwDeviceName.toLatin1();
                const quint8 length = id.length();

                stream << code;
                stream << (quint8) deCONZ::ZclCharacterString;
                stream << length;
                for (uint i = 0; i < length; i++)
                {
                    stream << (quint8) id[i];
                }
            }
                break;

            case 0x0007: // Power Source
                stream << code;
                stream << (quint8) deCONZ::Zcl8BitEnum;
                stream << (quint8) 0x04; // DC Power
                break;

            case 0x4000: // SW Build ID
            {
                const QByteArray version = gwFirmwareVersion.toLatin1();
                const quint8 length = version.length();

                stream << code;
                stream << (quint8) deCONZ::ZclCharacterString;
                stream << length;
                for (uint i = 0; i < length; i++)
                {
                    stream << (quint8) version[i];
                }
            }
                break;

            case 0xF000: // Legrand attribute used for pairing
                // FIXME: check Legrand manufacturer code
                stream << code;
                stream << (quint8) deCONZ::Zcl32BitUint;
                stream << (quint32) 0x000000d5;
                break;

            default:
            {
                stream << (quint8) 0x86;  // unsupported_attribute
            }
            break;
            }
        }
    }

    { // ZCL frame
        QDataStream stream(&req.asdu(), QIODevice::WriteOnly);
        stream.setByteOrder(QDataStream::LittleEndian);
        outZclFrame.writeToStream(stream);
    }

    if (apsCtrl && apsCtrl->apsdeDataRequest(req) != deCONZ::Success)
    {
        DBG_Printf(DBG_INFO, "Basic failed to send reponse\n");
    }

}
<|endoftext|>


<commit_before>/***********************************************************************
    created:    Tue Feb 17 2009
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/RendererModules/Ogre/RenderTarget.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/RenderQueue.h"
#include "CEGUI/RendererModules/Ogre/GeometryBuffer.h"

#include <OgreRenderSystem.h>
#include <OgreCamera.h>
#include <OgreViewport.h>

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

// Start of CEGUI namespace section
namespace CEGUI
{

//----------------------------------------------------------------------------//
template <typename T>
const float OgreRenderTarget<T>::d_yfov_tan = 0.267949192431123f;

//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::OgreRenderTarget(OgreRenderer& owner,
                                      Ogre::RenderSystem& rs) :
    d_owner(owner),
    d_renderSystem(rs),
    d_area(0, 0, 0, 0),
    d_renderTarget(0),
    d_viewport(0),
    d_ogreViewportDimensions(0, 0, 0, 0),
    d_matrix(Ogre::Matrix4::IDENTITY),
    d_matrixValid(false),
    d_viewportValid(false),
    d_viewDistance(0)
{
}

//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::~OgreRenderTarget()
{
    delete d_viewport;
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const GeometryBuffer& buffer)
{
    buffer.draw();
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const RenderQueue& queue)
{
    queue.draw();
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setArea(const Rectf& area)
{
    d_area = area;
    setOgreViewportDimensions(area);

    d_matrixValid = false;

    RenderTargetEventArgs args(this);
    T::fireEvent(RenderTarget::EventAreaChanged, args);
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setOgreViewportDimensions(const Rectf& area)
{
    d_ogreViewportDimensions = area;

    if (d_viewport)
        updateOgreViewportDimensions(d_viewport->getTarget());

    d_viewportValid = false;
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateOgreViewportDimensions(
                                            const Ogre::RenderTarget* const rt)
{
    if (rt)
    {
        if(d_viewport)
            d_viewport->setDimensions(
            d_ogreViewportDimensions.left() / rt->getWidth(),
            d_ogreViewportDimensions.top() / rt->getHeight(),
            d_ogreViewportDimensions.getWidth() / rt->getWidth(),
            d_ogreViewportDimensions.getHeight() / rt->getHeight());
    }
}

//----------------------------------------------------------------------------//
template <typename T>
const Rectf& OgreRenderTarget<T>::getArea() const
{
    return d_area;
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::activate()
{
    if (!d_matrixValid)
        updateMatrix();

    if (!d_viewportValid)
        updateViewport();

    d_renderSystem._setViewport(d_viewport);

    d_owner.setProjectionMatrix(d_matrix);
    d_owner.setViewMatrix(Ogre::Matrix4::IDENTITY);

    RenderTarget::activate();
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::deactivate()
{
    // currently nothing to do in the basic case
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,
                                         const glm::vec2& p_in,
                                         glm::vec2& p_out) const
{
    if (!d_matrixValid)
        updateMatrix();

    const OgreGeometryBuffer& gb = static_cast<const OgreGeometryBuffer&>(buff);

    const Ogre::Real midx = d_area.getWidth() * 0.5f;
    const Ogre::Real midy = d_area.getHeight() * 0.5f;

    // viewport matrix
    const Ogre::Matrix4 vpmat(
        midx,    0,    0,    d_area.left() + midx,
         0,    -midy,  0,    d_area.top() + midy,
         0,      0,    1,    0,
         0,      0,    0,    1
    );

    // matrices used for projecting and unprojecting points

    const Ogre::Matrix4 proj(OgreRenderer::glmToOgreMatrix(gb.getModelMatrix()) * d_matrix * vpmat);
    const Ogre::Matrix4 unproj(proj.inverse());

    Ogre::Vector3 in;

    // unproject the ends of the ray
    in.x = midx;
    in.y = midy;
    in.z = -d_viewDistance;
    const Ogre::Vector3 r1(unproj * in);
    in.x = p_in.x;
    in.y = p_in.y;
    in.z = 0;
    // calculate vector of picking ray
    const Ogre::Vector3 rv(r1 - unproj * in);

    // project points to orientate them with GeometryBuffer plane
    in.x = 0.0;
    in.y = 0.0;
    const Ogre::Vector3 p1(proj * in);
    in.x = 1.0;
    in.y = 0.0;
    const Ogre::Vector3 p2(proj * in);
    in.x = 0.0;
    in.y = 1.0;
    const Ogre::Vector3 p3(proj * in);

    // calculate the plane normal
    const Ogre::Vector3 pn((p2 - p1).crossProduct(p3 - p1));
    // calculate distance from origin
    const Ogre::Real plen = pn.length();
    const Ogre::Real dist = -(p1.x * (pn.x / plen) +
                              p1.y * (pn.y / plen) +
                              p1.z * (pn.z / plen));

    // calculate intersection of ray and plane
    const Ogre::Real pn_dot_rv = pn.dotProduct(rv);
    const Ogre::Real tmp = pn_dot_rv != 0.0 ?
                            (pn.dotProduct(r1) + dist) / pn_dot_rv :
                            0.0f;

    p_out.x = static_cast<float>(r1.x - rv.x * tmp);
    p_out.y = static_cast<float>(r1.y - rv.y * tmp);
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateMatrix() const
{
    // Now with updated code from OpenGL renderer

    const float w = d_area.getWidth();
    const float h = d_area.getHeight();

    // We need to check if width or height are zero and act accordingly to prevent running into issues
    // with divisions by zero which would lead to undefined values, as well as faulty clipping planes
    // This is mostly important for avoiding asserts
    const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f);

    const float aspect = widthAndHeightNotZero ? w / h : 1.0f;
    const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f;
    const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f;
    d_viewDistance = midx / (aspect * 0.267949192431123f);

    const float nearZ = d_viewDistance * 0.5f;
    const float farZ = d_viewDistance * 2.0f;
    const float nr_sub_far = nearZ - farZ;

    Ogre::Matrix4 tmp(Ogre::Matrix4::ZERO);
    tmp[0][0] = 3.732050808f / aspect;
    tmp[0][3] = -d_viewDistance;
    tmp[1][1] = -3.732050808f;
    tmp[1][3] = d_viewDistance;
    tmp[2][2] = -((farZ + nearZ) / nr_sub_far);
    tmp[3][2] = 1.0f;
    tmp[3][3] = d_viewDistance;

    d_renderSystem._convertProjectionMatrix(tmp, d_matrix);

    d_matrixValid = true;
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateViewport()
{
    if (!d_viewport)
    {
#ifdef CEGUI_USE_OGRE_COMPOSITOR2

        d_viewport = OGRE_NEW Ogre::Viewport(d_renderTarget, 0, 0, 1, 1);
#else
        d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0);
#endif // CEGUI_USE_OGRE_COMPOSITOR2

        updateOgreViewportDimensions(d_renderTarget);
    }

    d_viewport->_updateDimensions();

    d_viewportValid = true;
}

//----------------------------------------------------------------------------//
template <typename T>
Renderer& OgreRenderTarget<T>::getOwner()
{
    return d_owner;
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<commit_msg>MOD: Adding missing activationCounter reset<commit_after>/***********************************************************************
    created:    Tue Feb 17 2009
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/RendererModules/Ogre/RenderTarget.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/RenderQueue.h"
#include "CEGUI/RendererModules/Ogre/GeometryBuffer.h"

#include <OgreRenderSystem.h>
#include <OgreCamera.h>
#include <OgreViewport.h>

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

// Start of CEGUI namespace section
namespace CEGUI
{

//----------------------------------------------------------------------------//
template <typename T>
const float OgreRenderTarget<T>::d_yfov_tan = 0.267949192431123f;

//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::OgreRenderTarget(OgreRenderer& owner,
                                      Ogre::RenderSystem& rs) :
    d_owner(owner),
    d_renderSystem(rs),
    d_area(0, 0, 0, 0),
    d_renderTarget(0),
    d_viewport(0),
    d_ogreViewportDimensions(0, 0, 0, 0),
    d_matrix(Ogre::Matrix4::IDENTITY),
    d_matrixValid(false),
    d_viewportValid(false),
    d_viewDistance(0)
{
}

//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::~OgreRenderTarget()
{
    delete d_viewport;
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const GeometryBuffer& buffer)
{
    buffer.draw();
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const RenderQueue& queue)
{
    queue.draw();
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setArea(const Rectf& area)
{
    d_area = area;
    setOgreViewportDimensions(area);

    d_matrixValid = false;

    RenderTargetEventArgs args(this);
    T::fireEvent(RenderTarget::EventAreaChanged, args);
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setOgreViewportDimensions(const Rectf& area)
{
    d_ogreViewportDimensions = area;

    if (d_viewport)
        updateOgreViewportDimensions(d_viewport->getTarget());

    d_viewportValid = false;
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateOgreViewportDimensions(
                                            const Ogre::RenderTarget* const rt)
{
    if (rt)
    {
        if(d_viewport)
            d_viewport->setDimensions(
            d_ogreViewportDimensions.left() / rt->getWidth(),
            d_ogreViewportDimensions.top() / rt->getHeight(),
            d_ogreViewportDimensions.getWidth() / rt->getWidth(),
            d_ogreViewportDimensions.getHeight() / rt->getHeight());
    }
}

//----------------------------------------------------------------------------//
template <typename T>
const Rectf& OgreRenderTarget<T>::getArea() const
{
    return d_area;
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::activate()
{
    if (!d_matrixValid)
        updateMatrix();

    if (!d_viewportValid)
        updateViewport();

    d_renderSystem._setViewport(d_viewport);

    d_owner.setProjectionMatrix(d_matrix);
    d_owner.setViewMatrix(Ogre::Matrix4::IDENTITY);

    RenderTarget::activate();
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::deactivate()
{
    // currently nothing to do in the basic case
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,
                                         const glm::vec2& p_in,
                                         glm::vec2& p_out) const
{
    if (!d_matrixValid)
        updateMatrix();

    const OgreGeometryBuffer& gb = static_cast<const OgreGeometryBuffer&>(buff);

    const Ogre::Real midx = d_area.getWidth() * 0.5f;
    const Ogre::Real midy = d_area.getHeight() * 0.5f;

    // viewport matrix
    const Ogre::Matrix4 vpmat(
        midx,    0,    0,    d_area.left() + midx,
         0,    -midy,  0,    d_area.top() + midy,
         0,      0,    1,    0,
         0,      0,    0,    1
    );

    // matrices used for projecting and unprojecting points

    const Ogre::Matrix4 proj(OgreRenderer::glmToOgreMatrix(gb.getModelMatrix()) * d_matrix * vpmat);
    const Ogre::Matrix4 unproj(proj.inverse());

    Ogre::Vector3 in;

    // unproject the ends of the ray
    in.x = midx;
    in.y = midy;
    in.z = -d_viewDistance;
    const Ogre::Vector3 r1(unproj * in);
    in.x = p_in.x;
    in.y = p_in.y;
    in.z = 0;
    // calculate vector of picking ray
    const Ogre::Vector3 rv(r1 - unproj * in);

    // project points to orientate them with GeometryBuffer plane
    in.x = 0.0;
    in.y = 0.0;
    const Ogre::Vector3 p1(proj * in);
    in.x = 1.0;
    in.y = 0.0;
    const Ogre::Vector3 p2(proj * in);
    in.x = 0.0;
    in.y = 1.0;
    const Ogre::Vector3 p3(proj * in);

    // calculate the plane normal
    const Ogre::Vector3 pn((p2 - p1).crossProduct(p3 - p1));
    // calculate distance from origin
    const Ogre::Real plen = pn.length();
    const Ogre::Real dist = -(p1.x * (pn.x / plen) +
                              p1.y * (pn.y / plen) +
                              p1.z * (pn.z / plen));

    // calculate intersection of ray and plane
    const Ogre::Real pn_dot_rv = pn.dotProduct(rv);
    const Ogre::Real tmp = pn_dot_rv != 0.0 ?
                            (pn.dotProduct(r1) + dist) / pn_dot_rv :
                            0.0f;

    p_out.x = static_cast<float>(r1.x - rv.x * tmp);
    p_out.y = static_cast<float>(r1.y - rv.y * tmp);
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateMatrix() const
{
    // Now with updated code from OpenGL renderer

    const float w = d_area.getWidth();
    const float h = d_area.getHeight();

    // We need to check if width or height are zero and act accordingly to prevent running into issues
    // with divisions by zero which would lead to undefined values, as well as faulty clipping planes
    // This is mostly important for avoiding asserts
    const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f);

    const float aspect = widthAndHeightNotZero ? w / h : 1.0f;
    const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f;
    const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f;
    d_viewDistance = midx / (aspect * 0.267949192431123f);

    const float nearZ = d_viewDistance * 0.5f;
    const float farZ = d_viewDistance * 2.0f;
    const float nr_sub_far = nearZ - farZ;

    Ogre::Matrix4 tmp(Ogre::Matrix4::ZERO);
    tmp[0][0] = 3.732050808f / aspect;
    tmp[0][3] = -d_viewDistance;
    tmp[1][1] = -3.732050808f;
    tmp[1][3] = d_viewDistance;
    tmp[2][2] = -((farZ + nearZ) / nr_sub_far);
    tmp[3][2] = 1.0f;
    tmp[3][3] = d_viewDistance;

    d_renderSystem._convertProjectionMatrix(tmp, d_matrix);

    d_matrixValid = true;
    //! This will trigger the RenderTarget to notify all of its GeometryBuffers to regenerate their matrices
    RenderTarget::d_activationCounter = -1;
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateViewport()
{
    if (!d_viewport)
    {
#ifdef CEGUI_USE_OGRE_COMPOSITOR2

        d_viewport = OGRE_NEW Ogre::Viewport(d_renderTarget, 0, 0, 1, 1);
#else
        d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0);
#endif // CEGUI_USE_OGRE_COMPOSITOR2

        updateOgreViewportDimensions(d_renderTarget);
    }

    d_viewport->_updateDimensions();

    d_viewportValid = true;
}

//----------------------------------------------------------------------------//
template <typename T>
Renderer& OgreRenderTarget<T>::getOwner()
{
    return d_owner;
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before><commit_msg>Fix declaration for ctor functions in generated headers.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix a bug<commit_after><|endoftext|>


<commit_before>#include "keyEventSender.h"

#include <QVBoxLayout>
#include <QPushButton>
#include <iostream>

#include "keyboard.h"

Sender::Sender():
    QWidget(0//, Qt::ToolTip
            //| Qt::WindowStaysOnTopHint
#ifdef UNIX
            | Qt::X11BypassWindowManagerHint
#endif
    ),
    focusWindow_(0)
{
    setFocusPolicy(Qt::NoFocus);
    QVBoxLayout* vbox = new QVBoxLayout(this);
    QPushButton* sendButton = new QPushButton("send key event", this);
    QPushButton* quitButton = new QPushButton("close", this);
    vbox->addWidget(sendButton);
    vbox->addWidget(quitButton);

    setLayout(vbox);

    connect(sendButton, SIGNAL(pressed()), this, SLOT(sendPress()));
    connect(sendButton, SIGNAL(released()), this, SLOT(sendRelease()));
    connect(quitButton, SIGNAL(pressed()), this, SLOT(hide()));

#ifdef UNIX
    display_ = XOpenDisplay(0);
#endif
}

Sender::~Sender() {}

#ifdef WIN32
bool Sender::winEvent(MSG* message, long* result)
{
    if(message->message == WM_ACTIVATE)
    {
        focusWindow_ = (HWND)message->lParam;
    }

    return false;
}
#endif

void Sender::setKey(wc::Key key)
{
    key_ = key;
}

void Sender::sendPress()
{
#ifdef WIN32
    SetActiveWindow(focusWindow_);
#endif
    wc::Keyboard::pressKey(key_);
}

void Sender::sendRelease()
{
#ifdef WIN32
    SetActiveWindow(focusWindow_);
#endif
    wc::Keyboard::releaseKey(key_);
}
<commit_msg>fix key events on linux<commit_after>#include "keyEventSender.h"

#include <QVBoxLayout>
#include <QPushButton>
#include <iostream>

#include "keyboard.h"

Sender::Sender():
    QWidget(0, Qt::WindowStaysOnTopHint
#ifdef UNIX
            | Qt::X11BypassWindowManagerHint
#endif
    )
{
    setFocusPolicy(Qt::NoFocus);
    QVBoxLayout* vbox = new QVBoxLayout(this);
    QPushButton* sendButton = new QPushButton("send key event", this);
    QPushButton* quitButton = new QPushButton("close", this);
    vbox->addWidget(sendButton);
    vbox->addWidget(quitButton);

    setLayout(vbox);

    connect(sendButton, SIGNAL(pressed()), this, SLOT(sendPress()));
    connect(sendButton, SIGNAL(released()), this, SLOT(sendRelease()));
    connect(quitButton, SIGNAL(pressed()), this, SLOT(hide()));

#ifdef UNIX
    display_ = XOpenDisplay(0);
#endif
}

Sender::~Sender() {}

#ifdef WIN32
bool Sender::winEvent(MSG* message, long* result)
{
    if(message->message == WM_ACTIVATE)
    {
        focusWindow_ = (HWND)message->lParam;
    }

    return false;
}
#endif

void Sender::setKey(wc::Key key)
{
    key_ = key;
}

void Sender::sendPress()
{
#ifdef WIN32
    SetActiveWindow(focusWindow_);
#endif
    wc::Keyboard::pressKey(key_);
}

void Sender::sendRelease()
{
#ifdef WIN32
    SetActiveWindow(focusWindow_);
#endif
    wc::Keyboard::releaseKey(key_);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <fstream>

#include <iostream>     // std::cout, std::right, std::endl
#include <iomanip>      // std::setw
#include <sstream>

#include <sys/time.h>
#include <sys/types.h>
#include <omp.h>
#include <math.h>
#include <malloc.h>

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

// Vectorial
#include <emmintrin.h>
#include <immintrin.h>

// Solver
#include "includes/defines.h"
#include "includes/stencils.h"
#include "includes/file_io.h"

#include "includes/utils.h"

const double PI = 3.14159265;

uint N = 0;
uint OutputStep = 0;

double dx = 0;
double dt = 0.1;
double h = 16;
double omega = 1;
double maxv = 0.0;
double CFL = 2;

typedef double Triple[3];

template <typename T>
void Initialize(T * gridA, T * gridB,
    const uint &X, const uint &Y, const uint &Z) {

  for(uint k = BWP; k < Z - BWP; k++) {
    for(uint j = BWP; j < Y - BWP; j++) {
      for(uint i = BWP; i < X - BWP; i++ ) {
        gridA[k*(Z+BW)*(Y+BW)+j*(Y+BW)+i] = 0.0;
        gridB[k*(Z+BW)*(Y+BW)+j*(Y+BW)+i] = 0.0;
      }
    }
  }

}

void InitializeVelocity(Triple * field,
    const uint &X, const uint &Y, const uint &Z) {

  for(uint k = 0; k < Z + BW; k++) {
    for(uint j = 0; j < Y + BW; j++) {
      for(uint i = 0; i < X + BW; i++) {
        field[k*(Y+BW)*(X+BW)+j*(X+BW)+i][0] = 0.0;
        field[k*(Y+BW)*(X+BW)+j*(X+BW)+i][1] = 0.0;
        field[k*(Y+BW)*(X+BW)+j*(X+BW)+i][2] = 0.0;
      }
    }
  }

  for(uint k = BWP; k < Z + BWP; k++) {
    for(uint j = BWP; j < Y + BWP; j++) {
      for(uint i = BWP; i < X + BWP; i++ ) {
        field[k*(Z+BW)*(Y+BW)+j*(Y+BW)+i][0] = -omega * (double)(j-(Y+1.0)/2.0);
        field[k*(Z+BW)*(Y+BW)+j*(Y+BW)+i][1] =  omega * (double)(i-(X+1.0)/2.0);
        field[k*(Z+BW)*(Y+BW)+j*(Y+BW)+i][2] =  0.0;

        maxv = std::max((double)abs(field[k*(Z+BW)*(Y+BW)+j*(Y+BW)+i][0]),maxv);
        maxv = std::max((double)abs(field[k*(Z+BW)*(Y+BW)+j*(Y+BW)+i][1]),maxv);
      }
    }
  }

}

template <typename T>
void WriteHeatFocus(T * gridA,
    const uint &X, const uint &Y, const uint &Z) {

  uint Xc, Yc, Zc;

  Xc = 2.0/5.0*(X);
  Yc = 2.0/5.5*(Y);
  Zc = 1.0/2.0*(Z);

  for(uint k = 0; k < Z + BW; k++) {
    for(uint j = 0; j < Y + BW; j++) {
      for(uint i = 0; i < Z + BW; i++) {

        double d2 = pow((Xc - (double)(i)),2) + pow((Yc - (double)(j)),2) + pow((Zc - (double)(k)),2);
        double rr = pow(X/6.0,2);

        if(d2 < rr)
          gridA[k*(Y+BW)*(X+BW)+j*(X+BW)+i] = 1.0 - d2/rr;
      }
    }
  }

}

void Interpolate(Triple prevDelta, Triple prevVeloc, Triple * field,
    const uint &X, const uint &Y, const uint &Z) {

  uint pi,pj,pk,ni,nj,nk;

  GlobalToLocal(prevDelta,idx);

  pi = floor(prevDelta[0]); ni = pi+1;
  pj = floor(prevDelta[1]); nj = pj+1;
  pk = floor(prevDelta[2]); nk = pk+1;

  PrecisionType Nx, Ny, Nz;

  Nx = 1-(prevDelta[0] - floor(prevDelta[0]));
  Ny = 1-(prevDelta[1] - floor(prevDelta[1]));
  Nz = 1-(prevDelta[2] - floor(prevDelta[2]));

  for(int d = 0; d < 3; d++) {
    prevVeloc[d] = (
      field[pk*(Z+BW)*(Y+BW)+pj*(Y+BW)+pi][d] * (    Nx) * (    Ny) * (    Nz) +
      field[pk*(Z+BW)*(Y+BW)+pj*(Y+BW)+ni][d] * (1 - Nx) * (    Ny) * (    Nz) +
      field[pk*(Z+BW)*(Y+BW)+nj*(Y+BW)+pi][d] * (    Nx) * (1 - Ny) * (    Nz) +
      field[pk*(Z+BW)*(Y+BW)+nj*(Y+BW)+ni][d] * (1 - Nx) * (1 - Ny) * (    Nz) +
      field[nk*(Z+BW)*(Y+BW)+pj*(Y+BW)+pi][d] * (    Nx) * (    Ny) * (1 - Nz) +
      field[nk*(Z+BW)*(Y+BW)+pj*(Y+BW)+ni][d] * (1 - Nx) * (    Ny) * (1 - Nz) +
      field[nk*(Z+BW)*(Y+BW)+nj*(Y+BW)+pi][d] * (    Nx) * (1 - Ny) * (1 - Nz) +
      field[nk*(Z+BW)*(Y+BW)+nj*(Y+BW)+ni][d] * (1 - Nx) * (1 - Ny) * (1 - Nz)
    );
  }
}

template <typename T>
double Interpolate(Triple prevDelta, T * gridA,
    const uint &X, const uint &Y, const uint &Z) {

  uint pi,pj,pk,ni,nj,nk;

  pi = floor(prevDelta[0]); ni = pi+1;
  pj = floor(prevDelta[1]); nj = pj+1;
  pk = floor(prevDelta[2]); nk = pk+1;

  double Nx, Ny, Nz;

  Nx = 1-(prevDelta[0] - floor(prevDelta[0]));
  Ny = 1-(prevDelta[1] - floor(prevDelta[1]));
  Nz = 1-(prevDelta[2] - floor(prevDelta[2]));

  return (
    gridA[pk*(Z+BW)*(Y+BW)+pj*(Y+BW)+pi] * (    Nx) * (    Ny) * (    Nz) +
    gridA[pk*(Z+BW)*(Y+BW)+pj*(Y+BW)+ni] * (1 - Nx) * (    Ny) * (    Nz) +
    gridA[pk*(Z+BW)*(Y+BW)+nj*(Y+BW)+pi] * (    Nx) * (1 - Ny) * (    Nz) +
    gridA[pk*(Z+BW)*(Y+BW)+nj*(Y+BW)+ni] * (1 - Nx) * (1 - Ny) * (    Nz) +
    gridA[nk*(Z+BW)*(Y+BW)+pj*(Y+BW)+pi] * (    Nx) * (    Ny) * (1 - Nz) +
    gridA[nk*(Z+BW)*(Y+BW)+pj*(Y+BW)+ni] * (1 - Nx) * (    Ny) * (1 - Nz) +
    gridA[nk*(Z+BW)*(Y+BW)+nj*(Y+BW)+pi] * (    Nx) * (1 - Ny) * (1 - Nz) +
    gridA[nk*(Z+BW)*(Y+BW)+nj*(Y+BW)+ni] * (1 - Nx) * (1 - Ny) * (1 - Nz)
  );
}

template <typename U>
void precalculateBackAndForw(U * fieldA, U * backward, U * forward,
    const uint &X, const uint &Y, const uint &Z) {

  Triple origin;

  for(uint k = BWP + omp_get_thread_num(); k < Z + BWP; k+=omp_get_num_threads()) {
    for(uint j = BWP; j < Y + BWP; j++) {
      for(uint i = BWP; i < X + BWP; i++) {
        uint cell = k*(Z+BW)*(Y+BW)+j*(Y+BW)+i;

        origin[0] = i;
        origin[1] = j;
        origin[2] = k;

        for(int d = 0; d < 3; d++) {
          backward[cell][d] = origin[d]*h-fieldA[cell][d]*dt;
          forward[cell][d]  = origin[d]*h+fieldA[cell][d]*dt;
        }
      }
    }
  }

}

template <typename T, typename U>
void advection(T * gridA, T * gridB, T * gridC, U * fieldA, U * backward, U * forward,
    const uint &X, const uint &Y, const uint &Z) {

  for(uint k = BWP + omp_get_thread_num(); k < Z + BWP; k+=omp_get_num_threads()) {
    for(uint j = BWP; j < Y + BWP; j++) {
      for(uint i = BWP; i < X + BWP; i++) {
        uint cell = k*(Z+BW)*(Y+BW)+j*(Y+BW)+i;
        gridB[cell] = Interpolate(backward[cell],gridA,N,N,N);
      }
    }
  }

  #pragma omp barrier

  for(uint k = BWP + omp_get_thread_num(); k < Z + BWP; k+=omp_get_num_threads()) {
    for(uint j = BWP; j < Y + BWP; j++) {
      for(uint i = BWP; i < X + BWP; i++) {
        uint cell = k*(Z+BW)*(Y+BW)+j*(Y+BW)+i;
        gridC[cell] = 1.5 * gridA[cell] - 0.5 * Interpolate(forward[cell],gridB,N,N,N);
      }
    }
  }

  #pragma omp barrier

  for(uint k = BWP + omp_get_thread_num(); k < Z + BWP; k+=omp_get_num_threads()) {
    for(uint j = BWP; j < Y + BWP; j++) {
      for(uint i = BWP; i < X + BWP; i++) {
        uint cell = k*(Z+BW)*(Y+BW)+j*(Y+BW)+i;
        gridA[cell] = Interpolate(backward[cell],gridC,N,N,N);
      }
    }
  }
}

template <typename T>
void difussion(T * &gridA, T * &gridB,
    const uint &X, const uint &Y, const uint &Z) {

  for(uint k = BWP + omp_get_thread_num(); k < Z + BWP; k+=omp_get_num_threads()) {
    for(uint j = BWP; j < Y + BWP; j++) {
      uint cell = k*(Z+BW)*(Y+BW)+j*(Y+BW)+BWP;
      for(uint i = BWP; i < X + BWP; i++) {
        stencilCross(gridA,gridB,cell++,X,Y,Z);
      }
    }
  }
}

int main(int argc, char *argv[]) {

  N  = atoi(argv[1]);
  int steeps = atoi(argv[2]);
  h = 1;
  dx = h/N;

  struct timeval start, end;

  FileIO<PrecisionType> io("grid",N);

  PrecisionType * step0 = NULL;
  PrecisionType * step1 = NULL;
  PrecisionType * step2 = NULL;

  Triple * velf0 = NULL;
  Triple * velf1 = NULL;
  Triple * velf2 = NULL;

  double duration = 0.0;

  // Temperature
  AllocateGrid(&step0,N,N,N);
  AllocateGrid(&step1,N,N,N);
  AllocateGrid(&step2,N,N,N);

  // Velocity
  AllocateGrid(&velf0,N,N,N);
  AllocateGrid(&velf1,N,N,N);
  AllocateGrid(&velf2,N,N,N);

  printf("Allocation correct\n");
  printf("Initialize\n");

  Initialize(step0,step1,N,N,N);
  WriteHeatFocus(step0,N,N,N);
  InitializeVelocity(velf0,N,N,N);

  dt = 0.25 * CFL*h/maxv;

  io.WriteGidMesh(step0,N,N,N);

  printf("Begin\n");
  printf("--------------------------\n");
  #pragma omp parallel
  #pragma omp single
  printf("Runing with %d OMP Threads\n",omp_get_num_threads());
  printf("--------------------------\n");

  gettimeofday(&start, NULL);

  #pragma omp parallel
  {
    precalculateBackAndForw(velf0,velf1,velf2,N,N,N);
    for(int i = 0; i < steeps; i++) {
        advection(step0,step1,step2,velf0,velf1,velf2,N,N,N);
    }
  }

  gettimeofday(&end, NULL);

  duration = FETCHTIME

  std::cout << "Total time:\t" << duration << std::endl;
  std::cout << "Step  time:\t" << duration / steeps << std::endl;

  ReleaseGrid(&step0);
  ReleaseGrid(&step1);
  ReleaseGrid(&step2);

  ReleaseGrid(&velf0);
  ReleaseGrid(&velf1);

  printf("De-Allocation correct\n");
}<commit_msg>Added missing functions to bfecc main Added parameters to bfecc main Corrected several includes in bfecc main<commit_after>#include <iostream>
#include <iomanip>
#include <fstream>

#include <iostream>     // std::cout, std::right, std::endl
#include <iomanip>      // std::setw
#include <sstream>

#include <sys/time.h>
#include <sys/types.h>
#include <omp.h>
#include <math.h>
#include <malloc.h>

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

// Vectorial
#include <emmintrin.h>
#include <immintrin.h>

// Solver
#include "include/defines.h"
#include "include/stencils.h"
#include "include/file_io.h"

#include "include/utils.h"

const double PI = 3.14159265;

uint N = 0;
uint OutputStep = 0;

double dx       =  0.0;
double idx      =  0.0;
double dt       =  0.1;
double h        = 16.0;
double omega    =  1.0;
double maxv     =  0.0;
double CFL      =  2.0;
double cellSize =  1.0;

typedef double Triple[3];

void GlobalToLocal(Triple coord, double f) {
  if(f==1.0)
    return;
  for(int d = 0; d < 3; d++) {
    coord[d] *= f;
  }
}

void LocalToGlobal(Triple coord, double f) {
  if(f==1.0)
    return;
  for(int d = 0; d < 3; d++) {
    coord[d] *= f;
  }
}

template <typename T>
void Initialize(T * gridA, T * gridB,
    const uint &X, const uint &Y, const uint &Z) {

  for(uint k = BWP; k < Z - BWP; k++) {
    for(uint j = BWP; j < Y - BWP; j++) {
      for(uint i = BWP; i < X - BWP; i++ ) {
        gridA[k*(Z+BW)*(Y+BW)+j*(Y+BW)+i] = 0.0;
        gridB[k*(Z+BW)*(Y+BW)+j*(Y+BW)+i] = 0.0;
      }
    }
  }

}

void InitializeVelocity(Triple * field,
    const uint &X, const uint &Y, const uint &Z) {

  for(uint k = 0; k < Z + BW; k++) {
    for(uint j = 0; j < Y + BW; j++) {
      for(uint i = 0; i < X + BW; i++) {
        field[k*(Y+BW)*(X+BW)+j*(X+BW)+i][0] = 0.0;
        field[k*(Y+BW)*(X+BW)+j*(X+BW)+i][1] = 0.0;
        field[k*(Y+BW)*(X+BW)+j*(X+BW)+i][2] = 0.0;
      }
    }
  }

  for(uint k = BWP; k < Z + BWP; k++) {
    for(uint j = BWP; j < Y + BWP; j++) {
      for(uint i = BWP; i < X + BWP; i++ ) {
        field[k*(Z+BW)*(Y+BW)+j*(Y+BW)+i][0] = -omega * (double)(j-(Y+1.0)/2.0);
        field[k*(Z+BW)*(Y+BW)+j*(Y+BW)+i][1] =  omega * (double)(i-(X+1.0)/2.0);
        field[k*(Z+BW)*(Y+BW)+j*(Y+BW)+i][2] =  0.0;

        maxv = std::max((double)abs(field[k*(Z+BW)*(Y+BW)+j*(Y+BW)+i][0]),maxv);
        maxv = std::max((double)abs(field[k*(Z+BW)*(Y+BW)+j*(Y+BW)+i][1]),maxv);
      }
    }
  }

}

template <typename T>
void WriteHeatFocus(T * gridA,
    const uint &X, const uint &Y, const uint &Z) {

  uint Xc, Yc, Zc;

  Xc = 2.0/5.0*(X);
  Yc = 2.0/5.5*(Y);
  Zc = 1.0/2.0*(Z);

  for(uint k = 0; k < Z + BW; k++) {
    for(uint j = 0; j < Y + BW; j++) {
      for(uint i = 0; i < Z + BW; i++) {

        double d2 = pow((Xc - (double)(i)),2) + pow((Yc - (double)(j)),2) + pow((Zc - (double)(k)),2);
        double rr = pow(X/6.0,2);

        if(d2 < rr)
          gridA[k*(Y+BW)*(X+BW)+j*(X+BW)+i] = 1.0 - d2/rr;
      }
    }
  }

}

void Interpolate(Triple prevDelta, Triple prevVeloc, Triple * field,
    const uint &X, const uint &Y, const uint &Z) {

  uint pi,pj,pk,ni,nj,nk;

  GlobalToLocal(prevDelta,idx);

  pi = floor(prevDelta[0]); ni = pi+1;
  pj = floor(prevDelta[1]); nj = pj+1;
  pk = floor(prevDelta[2]); nk = pk+1;

  PrecisionType Nx, Ny, Nz;

  Nx = 1-(prevDelta[0] - floor(prevDelta[0]));
  Ny = 1-(prevDelta[1] - floor(prevDelta[1]));
  Nz = 1-(prevDelta[2] - floor(prevDelta[2]));

  for(int d = 0; d < 3; d++) {
    prevVeloc[d] = (
      field[pk*(Z+BW)*(Y+BW)+pj*(Y+BW)+pi][d] * (    Nx) * (    Ny) * (    Nz) +
      field[pk*(Z+BW)*(Y+BW)+pj*(Y+BW)+ni][d] * (1 - Nx) * (    Ny) * (    Nz) +
      field[pk*(Z+BW)*(Y+BW)+nj*(Y+BW)+pi][d] * (    Nx) * (1 - Ny) * (    Nz) +
      field[pk*(Z+BW)*(Y+BW)+nj*(Y+BW)+ni][d] * (1 - Nx) * (1 - Ny) * (    Nz) +
      field[nk*(Z+BW)*(Y+BW)+pj*(Y+BW)+pi][d] * (    Nx) * (    Ny) * (1 - Nz) +
      field[nk*(Z+BW)*(Y+BW)+pj*(Y+BW)+ni][d] * (1 - Nx) * (    Ny) * (1 - Nz) +
      field[nk*(Z+BW)*(Y+BW)+nj*(Y+BW)+pi][d] * (    Nx) * (1 - Ny) * (1 - Nz) +
      field[nk*(Z+BW)*(Y+BW)+nj*(Y+BW)+ni][d] * (1 - Nx) * (1 - Ny) * (1 - Nz)
    );
  }
}

template <typename T>
double Interpolate(Triple prevDelta, T * gridA,
    const uint &X, const uint &Y, const uint &Z) {

  uint pi,pj,pk,ni,nj,nk;

  pi = floor(prevDelta[0]); ni = pi+1;
  pj = floor(prevDelta[1]); nj = pj+1;
  pk = floor(prevDelta[2]); nk = pk+1;

  double Nx, Ny, Nz;

  Nx = 1-(prevDelta[0] - floor(prevDelta[0]));
  Ny = 1-(prevDelta[1] - floor(prevDelta[1]));
  Nz = 1-(prevDelta[2] - floor(prevDelta[2]));

  return (
    gridA[pk*(Z+BW)*(Y+BW)+pj*(Y+BW)+pi] * (    Nx) * (    Ny) * (    Nz) +
    gridA[pk*(Z+BW)*(Y+BW)+pj*(Y+BW)+ni] * (1 - Nx) * (    Ny) * (    Nz) +
    gridA[pk*(Z+BW)*(Y+BW)+nj*(Y+BW)+pi] * (    Nx) * (1 - Ny) * (    Nz) +
    gridA[pk*(Z+BW)*(Y+BW)+nj*(Y+BW)+ni] * (1 - Nx) * (1 - Ny) * (    Nz) +
    gridA[nk*(Z+BW)*(Y+BW)+pj*(Y+BW)+pi] * (    Nx) * (    Ny) * (1 - Nz) +
    gridA[nk*(Z+BW)*(Y+BW)+pj*(Y+BW)+ni] * (1 - Nx) * (    Ny) * (1 - Nz) +
    gridA[nk*(Z+BW)*(Y+BW)+nj*(Y+BW)+pi] * (    Nx) * (1 - Ny) * (1 - Nz) +
    gridA[nk*(Z+BW)*(Y+BW)+nj*(Y+BW)+ni] * (1 - Nx) * (1 - Ny) * (1 - Nz)
  );
}

template <typename U>
void precalculateBackAndForw(U * fieldA, U * backward, U * forward,
    const uint &X, const uint &Y, const uint &Z) {

  Triple origin;

  for(uint k = BWP + omp_get_thread_num(); k < Z + BWP; k+=omp_get_num_threads()) {
    for(uint j = BWP; j < Y + BWP; j++) {
      for(uint i = BWP; i < X + BWP; i++) {
        uint cell = k*(Z+BW)*(Y+BW)+j*(Y+BW)+i;

        origin[0] = i;
        origin[1] = j;
        origin[2] = k;

        for(int d = 0; d < 3; d++) {
          backward[cell][d] = origin[d]*h-fieldA[cell][d]*dt;
          forward[cell][d]  = origin[d]*h+fieldA[cell][d]*dt;
        }
      }
    }
  }

}

template <typename T, typename U>
void advection(T * gridA, T * gridB, T * gridC, U * fieldA, U * backward, U * forward,
    const uint &X, const uint &Y, const uint &Z) {

  for(uint k = BWP + omp_get_thread_num(); k < Z + BWP; k+=omp_get_num_threads()) {
    for(uint j = BWP; j < Y + BWP; j++) {
      for(uint i = BWP; i < X + BWP; i++) {
        uint cell = k*(Z+BW)*(Y+BW)+j*(Y+BW)+i;
        gridB[cell] = Interpolate(backward[cell],gridA,N,N,N);
      }
    }
  }

  #pragma omp barrier

  for(uint k = BWP + omp_get_thread_num(); k < Z + BWP; k+=omp_get_num_threads()) {
    for(uint j = BWP; j < Y + BWP; j++) {
      for(uint i = BWP; i < X + BWP; i++) {
        uint cell = k*(Z+BW)*(Y+BW)+j*(Y+BW)+i;
        gridC[cell] = 1.5 * gridA[cell] - 0.5 * Interpolate(forward[cell],gridB,N,N,N);
      }
    }
  }

  #pragma omp barrier

  for(uint k = BWP + omp_get_thread_num(); k < Z + BWP; k+=omp_get_num_threads()) {
    for(uint j = BWP; j < Y + BWP; j++) {
      for(uint i = BWP; i < X + BWP; i++) {
        uint cell = k*(Z+BW)*(Y+BW)+j*(Y+BW)+i;
        gridA[cell] = Interpolate(backward[cell],gridC,N,N,N);
      }
    }
  }
}

template <typename T>
void difussion(T * &gridA, T * &gridB,
    const uint &X, const uint &Y, const uint &Z) {

  for(uint k = BWP + omp_get_thread_num(); k < Z + BWP; k+=omp_get_num_threads()) {
    for(uint j = BWP; j < Y + BWP; j++) {
      uint cell = k*(Z+BW)*(Y+BW)+j*(Y+BW)+BWP;
      for(uint i = BWP; i < X + BWP; i++) {
        stencilCross(gridA,gridB,cell++,X,Y,Z);
      }
    }
  }
}

int main(int argc, char *argv[]) {

  N  = atoi(argv[1]);
  int steeps = atoi(argv[2]);
  h = 1;
  dx = h/N;

  struct timeval start, end;

  FileIO<PrecisionType> io("grid",N);

  PrecisionType * step0 = NULL;
  PrecisionType * step1 = NULL;
  PrecisionType * step2 = NULL;

  Triple * velf0 = NULL;
  Triple * velf1 = NULL;
  Triple * velf2 = NULL;

  double duration = 0.0;

  // Temperature
  AllocateGrid(&step0,N,N,N);
  AllocateGrid(&step1,N,N,N);
  AllocateGrid(&step2,N,N,N);

  // Velocity
  AllocateGrid(&velf0,N,N,N);
  AllocateGrid(&velf1,N,N,N);
  AllocateGrid(&velf2,N,N,N);

  printf("Allocation correct\n");
  printf("Initialize\n");

  Initialize(step0,step1,N,N,N);
  WriteHeatFocus(step0,N,N,N);
  InitializeVelocity(velf0,N,N,N);

  dt = 0.25 * CFL*h/maxv;

  io.WriteGidMesh(step0,N,N,N);

  printf("Begin\n");
  printf("--------------------------\n");
  #pragma omp parallel
  #pragma omp single
  printf("Runing with %d OMP Threads\n",omp_get_num_threads());
  printf("--------------------------\n");

  gettimeofday(&start, NULL);

  #pragma omp parallel
  {
    precalculateBackAndForw(velf0,velf1,velf2,N,N,N);
    for(int i = 0; i < steeps; i++) {
        advection(step0,step1,step2,velf0,velf1,velf2,N,N,N);
    }
  }

  gettimeofday(&end, NULL);

  duration = FETCHTIME

  std::cout << "Total time:\t" << duration << std::endl;
  std::cout << "Step  time:\t" << duration / steeps << std::endl;

  ReleaseGrid(&step0);
  ReleaseGrid(&step1);
  ReleaseGrid(&step2);

  ReleaseGrid(&velf0);
  ReleaseGrid(&velf1);

  printf("De-Allocation correct\n");
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007 Kevin Wolf
 *
 * This program is free software. It comes without any warranty, to
 * the extent permitted by applicable law. You can redistribute it
 * and/or modify it under the terms of the Do What The Fuck You Want
 * To Public License, Version 2, as published by Sam Hocevar. See
 * http://sam.zoy.org/projects/COPYING.WTFPL for more details.
 */

//#include <stdlib.h>

#include <Module.h>
#include <machine/Device.h>

#include <cdi.h>
#include <cdi-osdep.h>
#include <cdi/lists.h>
#include <cdi/pci.h>

static cdi_list_t drivers = NULL;
static cdi_list_t devices = NULL;

static void cdi_destroy(void);

void iterateDeviceTree(Device *root)
{
    for(size_t i = 0; i < root->getNumChildren(); i++)
    {
        Device *p = root->getChild(i);

        struct cdi_pci_device *dev = new struct cdi_pci_device;
        dev->bus_data.bus_type = CDI_PCI;

        dev->bus = p->getPciBusPosition();
        dev->dev = p->getPciDevicePosition();
        dev->function = p->getPciFunctionNumber();

        dev->vendor_id = p->getPciVendorId();
        dev->device_id = p->getPciDeviceId();

        dev->class_id = p->getPciClassCode();
        dev->subclass_id = p->getPciSubclassCode();
        dev->interface_id = p->getPciProgInterface();

        dev->rev_id = 0; /// \todo Implement into Device

        dev->irq = p->getInterruptNumber();

        dev->resources = cdi_list_create();
        for(size_t j = 0; j < p->addresses().count(); j++)
        {
            Device::Address *addr = p->addresses()[j];
            struct cdi_pci_resource *res = new struct cdi_pci_resource;
            if(addr->m_IsIoSpace)
                res->type = CDI_PCI_IOPORTS;
            else
                res->type = CDI_PCI_MEMORY;
            res->start = addr->m_Address;
            res->length = addr->m_Size;
            res->index = j;
            res->address = reinterpret_cast<void*>(res->start);

            cdi_list_push(dev->resources, res);
        }

        dev->meta.backdev = reinterpret_cast<void *>(p);

        cdi_list_push(devices, dev);

        if(p->getNumChildren())
            iterateDeviceTree(p);
    }
}

/**
 * Muss vor dem ersten Aufruf einer anderen CDI-Funktion aufgerufen werden.
 * Initialisiert interne Datenstruktur der Implementierung fuer das jeweilige
 * Betriebssystem.
 */
void cdi_init(void)
{
    drivers = cdi_list_create();
    devices = cdi_list_create();

    // Iterate the device tree and add cdi_bus_data structs to the device list
    // for each found device.
    Device *root = &Device::root();
    iterateDeviceTree(root);
}

void cdi_pedigree_walk_dev_list_init(struct cdi_driver *dev)
{
    struct cdi_driver* driver = dev;
    struct cdi_bus_data* device;
    int i;
    for (i = 0; (device = reinterpret_cast<struct cdi_bus_data*>(cdi_list_get(devices, i))); i++) {
        if (driver->init_device) {
            struct cdi_device *p = driver->init_device(device);
            if(p)
            {
                p->driver = driver;
            }
        }
    }
}

void cdi_pedigree_walk_dev_list_destroy(struct cdi_driver *dev)
{
    struct cdi_driver* driver = dev;
    struct cdi_device* device;
    int i;
    for (i = 0; (device = reinterpret_cast<struct cdi_device*>(cdi_list_get(devices, i))); i++) {
        if (driver->remove_device) {
            driver->remove_device(device);
        }
    }
}

/**
 * Wird bei der Deinitialisierung aufgerufen
 */
static void cdi_destroy(void)
{
    // Drivers are already destroyed by the module exit function
}

/**
 * Fuehrt alle registrierten Treiber aus. Nach dem Aufruf dieser Funktion
 * duerfen keine weiteren Befehle ausgefuehrt werden, da nicht definiert ist,
 * ob und wann die Funktion zurueckkehrt.
 */
void cdi_run_drivers(void)
{
    // Geraete initialisieren
    struct cdi_driver* driver;
    int i;
    for (i = 0; (driver = reinterpret_cast<struct cdi_driver*>(cdi_list_get(drivers, i))); i++) {
        cdi_pedigree_walk_dev_list_init(driver);
    }
}

/**
 * Initialisiert die Datenstrukturen fuer einen Treiber
 */
void cdi_driver_init(struct cdi_driver* driver)
{
    driver->devices = cdi_list_create();
}

/**
 * Deinitialisiert die Datenstrukturen fuer einen Treiber
 */
void cdi_driver_destroy(struct cdi_driver* driver)
{
    cdi_list_destroy(driver->devices);
}

/**
 * Registriert den Treiber fuer ein neues Geraet
 *
 * @param driver Zu registierender Treiber
 */
void cdi_driver_register(struct cdi_driver* driver)
{
    cdi_list_push(drivers, driver);
}

int cdi_provide_device(struct cdi_bus_data *device)
{
    // What type is the device?
    switch(device->bus_type)
    {
        case CDI_PCI:
            {
                // Grab the cdi_pci_device for this device
                struct cdi_pci_device *pci = reinterpret_cast<struct cdi_pci_device *>(device);

                // Don't re-create existing devices
                if(pci->meta.backdev)
                    return -1;

                // Create a new device object to add to the tree
                Device *pDevice = new Device();

                // PCI data
                pDevice->setPciPosition(pci->bus, pci->dev, pci->function);
                pDevice->setPciIdentifiers(pci->class_id, pci->subclass_id, pci->vendor_id, pci->device_id, pci->interface_id);
                pDevice->setInterruptNumber(pci->irq);

                // PCI BARs
                struct cdi_pci_resource *pResource = 0;
                for(int i = 0; (pResource = reinterpret_cast<struct cdi_pci_resource *>(cdi_list_get(pci->resources, i))); i++)
                {
                    TinyStaticString barName("BAR");
                    barName.append(i, 10);

                    Device::Address *pAddress = new Device::Address(String(barName), pResource->start, pResource->length, pResource->type == CDI_PCI_IOPORTS);

                    pDevice->addresses().pushBack(pAddress);
                }

                // Link into the tree
                pDevice->setParent(&Device::root());
                Device::root().addChild(pDevice);

                return 0;
            }
            break;

        default:
            WARNING("CDI: Unimplemented device type for cdi_provide_device(): " << static_cast<int>(device->bus_type));
            break;
    };

    return -1;
}

MODULE_INFO("cdi", &cdi_init, &cdi_destroy, "dma", "network-stack", "vfs");
<commit_msg>CDI: updated PCI enumeration to turn on bus mastering and enable both x86 I/O and MMIO for x86 targets. Fixes pcnet in vmware.<commit_after>/*
 * Copyright (c) 2007 Kevin Wolf
 *
 * This program is free software. It comes without any warranty, to
 * the extent permitted by applicable law. You can redistribute it
 * and/or modify it under the terms of the Do What The Fuck You Want
 * To Public License, Version 2, as published by Sam Hocevar. See
 * http://sam.zoy.org/projects/COPYING.WTFPL for more details.
 */

//#include <stdlib.h>

#include <Module.h>
#include <machine/Device.h>

#include <cdi.h>
#include <cdi-osdep.h>
#include <cdi/lists.h>
#include <cdi/pci.h>

#ifdef X86_COMMON
#include <machine/Pci.h>
#endif

static cdi_list_t drivers = NULL;
static cdi_list_t devices = NULL;

static void cdi_destroy(void);

void iterateDeviceTree(Device *root)
{
    for(size_t i = 0; i < root->getNumChildren(); i++)
    {
        Device *p = root->getChild(i);

        struct cdi_pci_device *dev = new struct cdi_pci_device;
        dev->bus_data.bus_type = CDI_PCI;

        // Enable bus mastering and standard I/O as needed.
#ifdef X86_COMMON
    uint32_t nPciCmdSts = PciBus::instance().readConfigSpace(p, 1);
    PciBus::instance().writeConfigSpace(p, 1, nPciCmdSts | 0x7);
#endif

        dev->bus = p->getPciBusPosition();
        dev->dev = p->getPciDevicePosition();
        dev->function = p->getPciFunctionNumber();

        dev->vendor_id = p->getPciVendorId();
        dev->device_id = p->getPciDeviceId();

        dev->class_id = p->getPciClassCode();
        dev->subclass_id = p->getPciSubclassCode();
        dev->interface_id = p->getPciProgInterface();

        dev->rev_id = 0; /// \todo Implement into Device

        dev->irq = p->getInterruptNumber();

        dev->resources = cdi_list_create();
        for(size_t j = 0; j < p->addresses().count(); j++)
        {
            Device::Address *addr = p->addresses()[j];
            struct cdi_pci_resource *res = new struct cdi_pci_resource;
            if(addr->m_IsIoSpace)
                res->type = CDI_PCI_IOPORTS;
            else
                res->type = CDI_PCI_MEMORY;
            res->start = addr->m_Address;
            res->length = addr->m_Size;
            res->index = j;
            res->address = reinterpret_cast<void*>(res->start);

            cdi_list_push(dev->resources, res);
        }

        dev->meta.backdev = reinterpret_cast<void *>(p);

        cdi_list_push(devices, dev);

        if(p->getNumChildren())
            iterateDeviceTree(p);
    }
}

/**
 * Muss vor dem ersten Aufruf einer anderen CDI-Funktion aufgerufen werden.
 * Initialisiert interne Datenstruktur der Implementierung fuer das jeweilige
 * Betriebssystem.
 */
void cdi_init(void)
{
    drivers = cdi_list_create();
    devices = cdi_list_create();

    // Iterate the device tree and add cdi_bus_data structs to the device list
    // for each found device.
    Device *root = &Device::root();
    iterateDeviceTree(root);
}

void cdi_pedigree_walk_dev_list_init(struct cdi_driver *dev)
{
    struct cdi_driver* driver = dev;
    struct cdi_bus_data* device;
    int i;
    for (i = 0; (device = reinterpret_cast<struct cdi_bus_data*>(cdi_list_get(devices, i))); i++) {
        if (driver->init_device) {
            struct cdi_device *p = driver->init_device(device);
            if(p)
            {
                p->driver = driver;
            }
        }
    }
}

void cdi_pedigree_walk_dev_list_destroy(struct cdi_driver *dev)
{
    struct cdi_driver* driver = dev;
    struct cdi_device* device;
    int i;
    for (i = 0; (device = reinterpret_cast<struct cdi_device*>(cdi_list_get(devices, i))); i++) {
        if (driver->remove_device) {
            driver->remove_device(device);
        }
    }
}

/**
 * Wird bei der Deinitialisierung aufgerufen
 */
static void cdi_destroy(void)
{
    // Drivers are already destroyed by the module exit function
}

/**
 * Fuehrt alle registrierten Treiber aus. Nach dem Aufruf dieser Funktion
 * duerfen keine weiteren Befehle ausgefuehrt werden, da nicht definiert ist,
 * ob und wann die Funktion zurueckkehrt.
 */
void cdi_run_drivers(void)
{
    // Geraete initialisieren
    struct cdi_driver* driver;
    int i;
    for (i = 0; (driver = reinterpret_cast<struct cdi_driver*>(cdi_list_get(drivers, i))); i++) {
        cdi_pedigree_walk_dev_list_init(driver);
    }
}

/**
 * Initialisiert die Datenstrukturen fuer einen Treiber
 */
void cdi_driver_init(struct cdi_driver* driver)
{
    driver->devices = cdi_list_create();
}

/**
 * Deinitialisiert die Datenstrukturen fuer einen Treiber
 */
void cdi_driver_destroy(struct cdi_driver* driver)
{
    cdi_list_destroy(driver->devices);
}

/**
 * Registriert den Treiber fuer ein neues Geraet
 *
 * @param driver Zu registierender Treiber
 */
void cdi_driver_register(struct cdi_driver* driver)
{
    cdi_list_push(drivers, driver);
}

int cdi_provide_device(struct cdi_bus_data *device)
{
    // What type is the device?
    switch(device->bus_type)
    {
        case CDI_PCI:
            {
                // Grab the cdi_pci_device for this device
                struct cdi_pci_device *pci = reinterpret_cast<struct cdi_pci_device *>(device);

                // Don't re-create existing devices
                if(pci->meta.backdev)
                    return -1;

                // Create a new device object to add to the tree
                Device *pDevice = new Device();

                // PCI data
                pDevice->setPciPosition(pci->bus, pci->dev, pci->function);
                pDevice->setPciIdentifiers(pci->class_id, pci->subclass_id, pci->vendor_id, pci->device_id, pci->interface_id);
                pDevice->setInterruptNumber(pci->irq);

                // PCI BARs
                struct cdi_pci_resource *pResource = 0;
                for(int i = 0; (pResource = reinterpret_cast<struct cdi_pci_resource *>(cdi_list_get(pci->resources, i))); i++)
                {
                    TinyStaticString barName("BAR");
                    barName.append(i, 10);

                    Device::Address *pAddress = new Device::Address(String(barName), pResource->start, pResource->length, pResource->type == CDI_PCI_IOPORTS);

                    pDevice->addresses().pushBack(pAddress);
                }

                // Link into the tree
                pDevice->setParent(&Device::root());
                Device::root().addChild(pDevice);

                return 0;
            }
            break;

        default:
            WARNING("CDI: Unimplemented device type for cdi_provide_device(): " << static_cast<int>(device->bus_type));
            break;
    };

    return -1;
}

MODULE_INFO("cdi", &cdi_init, &cdi_destroy, "dma", "network-stack", "vfs");
<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011 Guillaume Martres <smarter@ubuntu.com>
//

#include "SatellitesItem.h"

#include "MarbleDebug.h"
#include "global.h"
#include "GeoPainter.h"
#include "GeoDataCoordinates.h"
#include "GeoDataLinearRing.h"

#include "sgp4/sgp4ext.h"

#include <QtCore/QDateTime>
#include <QtGui/QAction>
#include <QtGui/QLabel>
#include <QtGui/QVBoxLayout>

#include <cmath>
#include <QDialog>
#include <QCheckBox>

using namespace Marble;

SatellitesItem::SatellitesItem( const QString &name, const elsetrec &satrec, QObject *parent )
    : AbstractDataPluginItem( parent ),
      m_dialog( 0 )
{
    setTarget( "earth" );
    setSize( QSizeF( 15, 15 ) );
    setId( name );
    setVisible( true );

    double tumin, mu, xke, j2, j3, j4, j3oj2;
    double radiusearthkm;
    getgravconst( wgs84, tumin, mu, radiusearthkm, xke, j2, j3, j4, j3oj2 );
    m_earthRadius = radiusearthkm;

    m_satrec = satrec;
    m_action = new QAction( id(), this );
    connect( m_action, SIGNAL(triggered(bool)), SLOT(showInfoDialog()));

    double r[3], v[3];
    sgp4( wgs84, m_satrec, timeSinceEpoch(), r, v );
    setCoordinate( fromCartesian( r[0], r[1], r[2] ) );
}

SatellitesItem::~SatellitesItem()
{
    m_dialog->deleteLater();
}

bool SatellitesItem::initialized()
{
    return true;
}

QString SatellitesItem::itemType() const
{
    return "satellitesitem";
}

bool SatellitesItem::operator<( const Marble::AbstractDataPluginItem *other ) const
{
    return this->id() < other->id();
}

QAction* SatellitesItem::action()
{
    return m_action;
}

void SatellitesItem::showInfoDialog()
{
    if (m_dialog == 0) {
        m_dialog = new QDialog();
        m_dialog->setWindowTitle( id() );
        QVBoxLayout *layout = new QVBoxLayout( m_dialog );
        QLabel *label = new QLabel(
            tr( "NORAD ID: \t\t%2\n"
                "Perigee: \t\t%3 km\n"
                "Apogee: \t\t%4 km\n"
                "Inclination: \t\t%5 degrees\n"
                "Period: \t\t%6 minutes\n"
                "Semi-major axis: \t%7 km\n" )
            .arg( QString::number(m_satrec.satnum), QString::number( perigee() ),
                  QString::number( apogee() ), QString::number( inclination() ),
                  QString::number( period() ), QString::number( semiMajorAxis() )),
             m_dialog );
        layout->addWidget( label );
    }
    m_dialog->show();
}

void SatellitesItem::paintViewport( GeoPainter *painter, ViewportParams *viewport, const QString &renderPos, GeoSceneLayer *layer )
{
    Q_UNUSED( viewport );
    Q_UNUSED( renderPos );
    Q_UNUSED( layer );

    painter->save();

    double r[3], v[3];
    GeoDataLineString orbit;
    int startTime = timeSinceEpoch();
    int endTime = startTime + period() + 1;
    for ( int i = startTime; i < endTime; i++ ) {
        sgp4( wgs84, m_satrec, i, r, v );
        orbit << fromCartesian( r[0], r[1], r[2] );
    }

    painter->setPen( oxygenBrickRed4 );
    painter->setBrush( Qt::NoBrush );
    painter->drawPolyline( orbit );

    painter->restore();
}

void SatellitesItem::paint( GeoPainter *painter, ViewportParams *viewport, const QString &renderPos, GeoSceneLayer *layer )
{
    Q_UNUSED( viewport );
    Q_UNUSED( renderPos );
    Q_UNUSED( layer );

    double r[3], v[3];
    sgp4( wgs84, m_satrec, timeSinceEpoch(), r, v );

    //FIXME: this should be done in a function that is guaranteed to be called regularly
    setCoordinate( fromCartesian( r[0], r[1], r[2] ) );

    if ( m_satrec.error != 0 ) {
        mDebug() << "Error: " << m_satrec.error;
        return;
    }

    painter->save();

    painter->setPen( oxygenSkyBlue4 );
    painter->setBrush( oxygenSkyBlue4 );
    painter->drawRect( 0, 0, size().width(), size().height() );

    painter->setPen( Qt::white );
    painter->drawText( 0, 0, id() );

    painter->restore();
}

// Hopefully this is correct enough
double SatellitesItem::timeSinceEpoch()
{
    int year = m_satrec.epochyr + ( m_satrec.epochyr < 57 ? 2000 : 1900 );

    int month, day, hours, minutes;
    double seconds;
    days2mdhms( year, m_satrec.epochdays, month, day, hours , minutes, seconds );
    QDateTime time = QDateTime( QDate( year, month, day ),
                                QTime( hours, minutes, (int)seconds, (int)( seconds / 1000.0 ) ) );
    return (double)( QDateTime::currentMSecsSinceEpoch() - time.toMSecsSinceEpoch() ) / ( 1000.0 * 60.0 );
}

double SatellitesItem::period()
{
    // no := mean motion (rad / min)
    double T = 1 / m_satrec.no;
    return T * 2 * M_PI;
}

double SatellitesItem::apogee()
{
    return m_satrec.alta * m_earthRadius;
}

double SatellitesItem::perigee()
{
    return m_satrec.altp * m_earthRadius;
}

double SatellitesItem::semiMajorAxis()
{

    return m_satrec.a * m_earthRadius;
}

double SatellitesItem::inclination()
{
    return m_satrec.inclo / M_PI * 180;
}

GeoDataCoordinates SatellitesItem::fromCartesian( double x, double y, double z )
{
    double lat = atan2( y, x );
    double lon = atan2( z, sqrt( x*x + y*y ) );
    double alt = sqrt( x*x + y*y + z*z );
    return GeoDataCoordinates( lat, lon, alt*1000 - m_earthRadius*1000 );
}

#include "SatellitesItem.moc"
<commit_msg>SatellitesItem: don't call deleteLater when m_dialog is NULL<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011 Guillaume Martres <smarter@ubuntu.com>
//

#include "SatellitesItem.h"

#include "MarbleDebug.h"
#include "global.h"
#include "GeoPainter.h"
#include "GeoDataCoordinates.h"
#include "GeoDataLinearRing.h"

#include "sgp4/sgp4ext.h"

#include <QtCore/QDateTime>
#include <QtGui/QAction>
#include <QtGui/QLabel>
#include <QtGui/QVBoxLayout>

#include <cmath>
#include <QDialog>
#include <QCheckBox>

using namespace Marble;

SatellitesItem::SatellitesItem( const QString &name, const elsetrec &satrec, QObject *parent )
    : AbstractDataPluginItem( parent ),
      m_dialog( 0 )
{
    setTarget( "earth" );
    setSize( QSizeF( 15, 15 ) );
    setId( name );
    setVisible( true );

    double tumin, mu, xke, j2, j3, j4, j3oj2;
    double radiusearthkm;
    getgravconst( wgs84, tumin, mu, radiusearthkm, xke, j2, j3, j4, j3oj2 );
    m_earthRadius = radiusearthkm;

    m_satrec = satrec;
    m_action = new QAction( id(), this );
    connect( m_action, SIGNAL(triggered(bool)), SLOT(showInfoDialog()));

    double r[3], v[3];
    sgp4( wgs84, m_satrec, timeSinceEpoch(), r, v );
    setCoordinate( fromCartesian( r[0], r[1], r[2] ) );
}

SatellitesItem::~SatellitesItem()
{
    if (m_dialog != 0) {
        m_dialog->deleteLater();
    }
}

bool SatellitesItem::initialized()
{
    return true;
}

QString SatellitesItem::itemType() const
{
    return "satellitesitem";
}

bool SatellitesItem::operator<( const Marble::AbstractDataPluginItem *other ) const
{
    return this->id() < other->id();
}

QAction* SatellitesItem::action()
{
    return m_action;
}

void SatellitesItem::showInfoDialog()
{
    if (m_dialog == 0) {
        m_dialog = new QDialog();
        m_dialog->setWindowTitle( id() );
        QVBoxLayout *layout = new QVBoxLayout( m_dialog );
        QLabel *label = new QLabel(
            tr( "NORAD ID: \t\t%2\n"
                "Perigee: \t\t%3 km\n"
                "Apogee: \t\t%4 km\n"
                "Inclination: \t\t%5 degrees\n"
                "Period: \t\t%6 minutes\n"
                "Semi-major axis: \t%7 km\n" )
            .arg( QString::number(m_satrec.satnum), QString::number( perigee() ),
                  QString::number( apogee() ), QString::number( inclination() ),
                  QString::number( period() ), QString::number( semiMajorAxis() )),
             m_dialog );
        layout->addWidget( label );
    }
    m_dialog->show();
}

void SatellitesItem::paintViewport( GeoPainter *painter, ViewportParams *viewport, const QString &renderPos, GeoSceneLayer *layer )
{
    Q_UNUSED( viewport );
    Q_UNUSED( renderPos );
    Q_UNUSED( layer );

    painter->save();

    double r[3], v[3];
    GeoDataLineString orbit;
    int startTime = timeSinceEpoch();
    int endTime = startTime + period() + 1;
    for ( int i = startTime; i < endTime; i++ ) {
        sgp4( wgs84, m_satrec, i, r, v );
        orbit << fromCartesian( r[0], r[1], r[2] );
    }

    painter->setPen( oxygenBrickRed4 );
    painter->setBrush( Qt::NoBrush );
    painter->drawPolyline( orbit );

    painter->restore();
}

void SatellitesItem::paint( GeoPainter *painter, ViewportParams *viewport, const QString &renderPos, GeoSceneLayer *layer )
{
    Q_UNUSED( viewport );
    Q_UNUSED( renderPos );
    Q_UNUSED( layer );

    double r[3], v[3];
    sgp4( wgs84, m_satrec, timeSinceEpoch(), r, v );

    //FIXME: this should be done in a function that is guaranteed to be called regularly
    setCoordinate( fromCartesian( r[0], r[1], r[2] ) );

    if ( m_satrec.error != 0 ) {
        mDebug() << "Error: " << m_satrec.error;
        return;
    }

    painter->save();

    painter->setPen( oxygenSkyBlue4 );
    painter->setBrush( oxygenSkyBlue4 );
    painter->drawRect( 0, 0, size().width(), size().height() );

    painter->setPen( Qt::white );
    painter->drawText( 0, 0, id() );

    painter->restore();
}

// Hopefully this is correct enough
double SatellitesItem::timeSinceEpoch()
{
    int year = m_satrec.epochyr + ( m_satrec.epochyr < 57 ? 2000 : 1900 );

    int month, day, hours, minutes;
    double seconds;
    days2mdhms( year, m_satrec.epochdays, month, day, hours , minutes, seconds );
    QDateTime time = QDateTime( QDate( year, month, day ),
                                QTime( hours, minutes, (int)seconds, (int)( seconds / 1000.0 ) ) );
    return (double)( QDateTime::currentMSecsSinceEpoch() - time.toMSecsSinceEpoch() ) / ( 1000.0 * 60.0 );
}

double SatellitesItem::period()
{
    // no := mean motion (rad / min)
    double T = 1 / m_satrec.no;
    return T * 2 * M_PI;
}

double SatellitesItem::apogee()
{
    return m_satrec.alta * m_earthRadius;
}

double SatellitesItem::perigee()
{
    return m_satrec.altp * m_earthRadius;
}

double SatellitesItem::semiMajorAxis()
{

    return m_satrec.a * m_earthRadius;
}

double SatellitesItem::inclination()
{
    return m_satrec.inclo / M_PI * 180;
}

GeoDataCoordinates SatellitesItem::fromCartesian( double x, double y, double z )
{
    double lat = atan2( y, x );
    double lon = atan2( z, sqrt( x*x + y*y ) );
    double alt = sqrt( x*x + y*y + z*z );
    return GeoDataCoordinates( lat, lon, alt*1000 - m_earthRadius*1000 );
}

#include "SatellitesItem.moc"
<|endoftext|>