<commit_before>/*************************************************************************
 *
 *  $RCSfile: dlgeps.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: sj $ $Date: 2002-08-15 09:23:15 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DLGEPS_HXX_
#define _DLGEPS_HXX_
#include <svtools/fltcall.hxx>
#include <vcl/dialog.hxx>
#include <vcl/button.hxx>
#include <vcl/fixed.hxx>
#include <vcl/field.hxx>
#include <vcl/lstbox.hxx>
#include <svtools/stdctrl.hxx>

/*************************************************************************
|*
|* Dialog zum Einstellen von Filteroptionen
|*
\************************************************************************/

class FilterConfigItem;
class ResMgr;

class DlgExportEPS : public ModalDialog
{
private:

    FltCallDialogParameter& rFltCallPara;

    FixedLine           aGrpPreview;
    CheckBox            aCBPreviewTiff;
    CheckBox            aCBPreviewEPSI;
    FixedLine           aGrpVersion;
    RadioButton         aRBLevel1;
    RadioButton         aRBLevel2;
    FixedLine           aGrpColor;
    RadioButton         aRBColor;
    RadioButton         aRBGrayscale;
    FixedLine           aGrpCompression;
    RadioButton         aRBCompressionLZW;
    RadioButton         aRBCompressionNone;
    OKButton            aBtnOK;
    CancelButton        aBtnCancel;
    HelpButton          aBtnHelp;

    FilterConfigItem*   pConfigItem;
    ResMgr*             pMgr;

    DECL_LINK( OK, void * );
    DECL_LINK( LEVEL1, void* );
    DECL_LINK( LEVEL2, void* );

public:
            DlgExportEPS( FltCallDialogParameter& rPara );
            ~DlgExportEPS();
};

#endif // _DLGEPS_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.286); FILE MERGED 2005/09/05 15:12:35 rt 1.6.286.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dlgeps.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:44:20 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _DLGEPS_HXX_
#define _DLGEPS_HXX_
#include <svtools/fltcall.hxx>
#include <vcl/dialog.hxx>
#include <vcl/button.hxx>
#include <vcl/fixed.hxx>
#include <vcl/field.hxx>
#include <vcl/lstbox.hxx>
#include <svtools/stdctrl.hxx>

/*************************************************************************
|*
|* Dialog zum Einstellen von Filteroptionen
|*
\************************************************************************/

class FilterConfigItem;
class ResMgr;

class DlgExportEPS : public ModalDialog
{
private:

    FltCallDialogParameter& rFltCallPara;

    FixedLine           aGrpPreview;
    CheckBox            aCBPreviewTiff;
    CheckBox            aCBPreviewEPSI;
    FixedLine           aGrpVersion;
    RadioButton         aRBLevel1;
    RadioButton         aRBLevel2;
    FixedLine           aGrpColor;
    RadioButton         aRBColor;
    RadioButton         aRBGrayscale;
    FixedLine           aGrpCompression;
    RadioButton         aRBCompressionLZW;
    RadioButton         aRBCompressionNone;
    OKButton            aBtnOK;
    CancelButton        aBtnCancel;
    HelpButton          aBtnHelp;

    FilterConfigItem*   pConfigItem;
    ResMgr*             pMgr;

    DECL_LINK( OK, void * );
    DECL_LINK( LEVEL1, void* );
    DECL_LINK( LEVEL2, void* );

public:
            DlgExportEPS( FltCallDialogParameter& rPara );
            ~DlgExportEPS();
};

#endif // _DLGEPS_HXX_
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdlib>
#include <QtCore/QBasicTimer>
#include <QtCore/QMetaType>
#include <QtCore/QMutexLocker>
#include <QtCore/QThread>
#ifdef Q_OS_MAC
#include <pthread.h>
#endif

#include "Manager.h"
#include "Object.h"

// Declarations for part of Qt's internal API
Q_DECL_IMPORT const QVariant::Handler* qcoreVariantHandler();
namespace QVariantPrivate {
Q_DECL_IMPORT void registerHandler(
    const int name, const QVariant::Handler *handler);
}

static const char* cCounterNames[] = {
    "ClassCounter",
    "ObjectCounter",
    "QObjectCounter",
    "VariantCounter",
    "ClassSerial",
    "ObjectSerial"
};

extern "C" void hsqml_dump_counters()
{
    Q_ASSERT (gManager);
    if (gManager->checkLogLevel(1)) {
        for (int i=0; i<HsQMLManager::TotalCounters; i++) {
            gManager->log(QString().sprintf("%s = %d.",
                cCounterNames[i], gManager->updateCounter(
                    static_cast<HsQMLManager::CounterId>(i), 0)));
        }
    }
}

static void hooked_construct(QVariant::Private* p, const void* copy)
{
    gManager->hookedConstruct(p, copy);
}

static void hooked_clear(QVariant::Private* p)
{
    gManager->hookedClear(p);
}

ManagerPointer gManager;

HsQMLManager::HsQMLManager(
    void (*freeFun)(HsFunPtr),
    void (*freeStable)(HsStablePtr))
    : mLogLevel(0)
    , mAtExit(false)
    , mFreeFun(freeFun)
    , mFreeStable(freeStable)
    , mOriginalHandler(qcoreVariantHandler())
    , mHookedHandler(*mOriginalHandler)
    , mApp(NULL)
    , mLock(QMutex::Recursive)
    , mRunning(false)
    , mRunCount(0)
    , mStackBase(NULL)
    , mStartCb(NULL)
    , mJobsCb(NULL)
    , mYieldCb(NULL)
    , mActiveEngine(NULL)
{
    // Get log level from environment
    const char* env = std::getenv("HSQML_DEBUG_LOG_LEVEL");
    if (env) {
        setLogLevel(QString(env).toInt());
    }

    // Set hooked handler functions
    mHookedHandler.construct = &hooked_construct;
    mHookedHandler.clear = &hooked_clear;
}

void HsQMLManager::setLogLevel(int ll)
{
    mLogLevel = ll;
    if (ll > 0 && !mAtExit) {
        if (atexit(&hsqml_dump_counters) == 0) {
            mAtExit = true;
        }
        else {
            log("Failed to register callback with atexit().");
        }
    }
}

bool HsQMLManager::checkLogLevel(int ll)
{
    return mLogLevel >= ll;
}

void HsQMLManager::log(const QString& msg)
{
    std::cerr << "HsQML: " << msg.toStdString() << std::endl;
}

int HsQMLManager::updateCounter(CounterId id, int delta)
{
    return mCounters[id].fetchAndAddRelaxed(delta);
}

void HsQMLManager::freeFun(HsFunPtr funPtr)
{
    mFreeFun(funPtr);
}

void HsQMLManager::freeStable(HsStablePtr stablePtr)
{
    mFreeStable(stablePtr);
}

void HsQMLManager::hookedConstruct(QVariant::Private* p, const void* copy)
{
    char guard;
    mOriginalHandler->construct(p, copy);
    void* pp = reinterpret_cast<void*>(p);
    // The QVariant internals sometimes use a special code path for pointer
    // values which avoids calling the handler functions. This makes it
    // difficult to use them to keep a reference count. However, it's my
    // observation that this only affects transient QVariants created on the
    // stack inside the JavaScript engine's marshalling code. The persistent
    // QVariants stored in the heap are manipulated using a more restricted set
    // of operations which always use the handler functions. Hence, by assuming
    // that the stack can be discounted, it's possible to keep an accurate
    // count of heap references using these hooks.
    if ((pp < &guard || pp > mStackBase) && p->type == QMetaType::QObjectStar) {
        if (HsQMLObject* obj = dynamic_cast<HsQMLObject*>(p->data.o)) {
            HsQMLObjectProxy* proxy = obj->proxy();
            proxy->ref(HsQMLObjectProxy::Variant);
            proxy->tryGCLock();
            updateCounter(VariantCount, 1);
        }
    }
}

void HsQMLManager::hookedClear(QVariant::Private* p)
{
    char guard;
    void* pp = reinterpret_cast<void*>(p);
    if ((pp < &guard || pp > mStackBase) && p->type == QMetaType::QObjectStar) {
        if (HsQMLObject* obj = dynamic_cast<HsQMLObject*>(p->data.o)) {
            obj->proxy()->deref(HsQMLObjectProxy::Variant);
            updateCounter(VariantCount, -1);
        }
    }
    mOriginalHandler->clear(p);
}

bool HsQMLManager::isEventThread()
{
    return mApp && mApp->thread() == QThread::currentThread();
}

HsQMLManager::EventLoopStatus HsQMLManager::runEventLoop(
    HsQMLTrivialCb startCb,
    HsQMLTrivialCb jobsCb,
    HsQMLTrivialCb yieldCb)
{
    QMutexLocker locker(&mLock);

    // Check if already running
    if (mRunning) {
        return HSQML_EVLOOP_ALREADY_RUNNING;
    }

    // Check if event loop bound to a different thread
    if (mApp && !isEventThread()) {
        return HSQML_EVLOOP_WRONG_THREAD;
    }

#ifdef Q_OS_MAC
    if (!pthread_main_np()) {
        // Cocoa can only be run on the primordial thread and exec() doesn't
        // check this.
        return HSQML_EVLOOP_WRONG_THREAD;
    }
#endif

    // Check for non-threaded RTS
    if (yieldCb) {
        HSQML_LOG(0,
            "Warning: CPU cannot idle when using the non-threaded RTS.");
    }

    // Perform one-time initialisation
    if (!mApp) {
        // Install hooked handler for QVariants
        QVariantPrivate::registerHandler(0, &mHookedHandler);

        // Register custom type
        qRegisterMetaType<HsQMLEngineConfig>("HsQMLEngineConfig");

        // Create application object
        mApp = new HsQMLManagerApp();
    }

    // Save stack base and callbacks
    mStackBase = &locker;
    mStartCb = startCb;
    mJobsCb = jobsCb;
    mYieldCb = yieldCb;

    // Setup events
    QCoreApplication::postEvent(
        mApp, new QEvent(HsQMLManagerApp::StartedLoopEvent),
        Qt::HighEventPriority);
    QBasicTimer idleTimer;
    if (yieldCb) {
        idleTimer.start(0, mApp);
    }

    // Run loop
    int ret = mApp->exec();

    // Remove redundant events
    QCoreApplication::removePostedEvents(
        mApp, HsQMLManagerApp::RemoveGCLockEvent);

    // Cleanup callbacks
    freeFun(startCb);
    mStartCb = NULL;
    freeFun(jobsCb);
    mJobsCb = NULL;
    if (yieldCb) {
        freeFun(yieldCb);
        mYieldCb = NULL;
    }

    // Return
    if (ret == 0) {
        return HSQML_EVLOOP_OK;
    }
    else {
        QCoreApplication::removePostedEvents(
            mApp, HsQMLManagerApp::StartedLoopEvent);
        return HSQML_EVLOOP_OTHER_ERROR;
    }
}

HsQMLManager::EventLoopStatus HsQMLManager::requireEventLoop()
{
    QMutexLocker locker(&mLock);
    if (mRunCount > 0) {
        mRunCount++;
        return HSQML_EVLOOP_OK;
    }
    else {
        return HSQML_EVLOOP_NOT_RUNNING;
    }
}

void HsQMLManager::releaseEventLoop()
{
    QMutexLocker locker(&mLock);
    if (--mRunCount == 0) {
        QCoreApplication::postEvent(
            mApp, new QEvent(HsQMLManagerApp::StopLoopEvent),
            Qt::LowEventPriority);
    }
}

void HsQMLManager::notifyJobs()
{
    QMutexLocker locker(&mLock);
    if (mRunCount > 0) {
        QCoreApplication::postEvent(
            mApp, new QEvent(HsQMLManagerApp::PendingJobsEvent));
    }
}

void HsQMLManager::createEngine(const HsQMLEngineConfig& config)
{
    Q_ASSERT (mApp);
    QMetaObject::invokeMethod(
        mApp, "createEngine", Q_ARG(HsQMLEngineConfig, config));
}

void HsQMLManager::setActiveEngine(HsQMLEngine* engine)
{
    Q_ASSERT(!mActiveEngine || !engine);
    mActiveEngine = engine;
}

HsQMLEngine* HsQMLManager::activeEngine()
{
    return mActiveEngine;
}

void HsQMLManager::postObjectEvent(HsQMLObjectEvent* ev)
{
    QCoreApplication::postEvent(mApp, ev);
}

HsQMLManagerApp::HsQMLManagerApp()
    : mArgC(1)
    , mArg0(0)
    , mArgV(&mArg0)
    , mApp(mArgC, &mArgV)
{
    mApp.setQuitOnLastWindowClosed(false);
}

HsQMLManagerApp::~HsQMLManagerApp()
{}

void HsQMLManagerApp::customEvent(QEvent* ev)
{
    switch (ev->type()) {
    case HsQMLManagerApp::StartedLoopEvent: {
        gManager->mRunning = true;
        gManager->mRunCount++;
        gManager->mLock.unlock();
        gManager->mStartCb();
        gManager->mJobsCb();
        break;}
    case HsQMLManagerApp::StopLoopEvent: {
        gManager->mLock.lock();
        const QObjectList& cs = gManager->mApp->children();
        while (!cs.empty()) {
            delete cs.front();
        }
        gManager->mRunning = false;
        gManager->mApp->mApp.quit();
        break;}
    case HsQMLManagerApp::PendingJobsEvent: {
        gManager->mJobsCb();
        break;}
    case HsQMLManagerApp::RemoveGCLockEvent: {
        static_cast<HsQMLObjectEvent*>(ev)->process();
        break;}
    }
}

void HsQMLManagerApp::timerEvent(QTimerEvent*)
{
    Q_ASSERT(gManager->mYieldCb);
    gManager->mYieldCb();
}

void HsQMLManagerApp::createEngine(HsQMLEngineConfig config)
{
    HsQMLEngine* engine = new HsQMLEngine(config);
    engine->setParent(this);
}

int HsQMLManagerApp::exec()
{
    return mApp.exec();
}

extern "C" void hsqml_init(
    void (*freeFun)(HsFunPtr),
    void (*freeStable)(HsStablePtr))
{
    if (gManager == NULL) {
        HsQMLManager* manager = new HsQMLManager(freeFun, freeStable);
        if (!gManager.testAndSetOrdered(NULL, manager)) {
            delete manager;
        }
    }
}

extern "C" HsQMLEventLoopStatus hsqml_evloop_run(
    HsQMLTrivialCb startCb,
    HsQMLTrivialCb jobsCb,
    HsQMLTrivialCb yieldCb)
{
    return gManager->runEventLoop(startCb, jobsCb, yieldCb);
}

extern "C" HsQMLEventLoopStatus hsqml_evloop_require()
{
    return gManager->requireEventLoop();
}

extern "C" void hsqml_evloop_release()
{
    gManager->releaseEventLoop();
}

extern "C" void hsqml_evloop_notify_jobs()
{
    gManager->notifyJobs();
}

extern "C" void hsqml_set_debug_loglevel(int ll)
{
    Q_ASSERT (gManager);
    gManager->setLogLevel(ll);
}
<commit_msg>Fix crash when using Cmd-Q to exit program on MacOS.<commit_after>#include <iostream>
#include <cstdlib>
#include <QtCore/QBasicTimer>
#include <QtCore/QMetaType>
#include <QtCore/QMutexLocker>
#include <QtCore/QThread>
#ifdef Q_OS_MAC
#include <pthread.h>
#endif

#include "Manager.h"
#include "Object.h"

// Declarations for part of Qt's internal API
Q_DECL_IMPORT const QVariant::Handler* qcoreVariantHandler();
namespace QVariantPrivate {
Q_DECL_IMPORT void registerHandler(
    const int name, const QVariant::Handler *handler);
}

static const char* cCounterNames[] = {
    "ClassCounter",
    "ObjectCounter",
    "QObjectCounter",
    "VariantCounter",
    "ClassSerial",
    "ObjectSerial"
};

extern "C" void hsqml_dump_counters()
{
    Q_ASSERT (gManager);
    if (gManager->checkLogLevel(1)) {
        for (int i=0; i<HsQMLManager::TotalCounters; i++) {
            gManager->log(QString().sprintf("%s = %d.",
                cCounterNames[i], gManager->updateCounter(
                    static_cast<HsQMLManager::CounterId>(i), 0)));
        }
    }
}

static void hooked_construct(QVariant::Private* p, const void* copy)
{
    gManager->hookedConstruct(p, copy);
}

static void hooked_clear(QVariant::Private* p)
{
    gManager->hookedClear(p);
}

ManagerPointer gManager;

HsQMLManager::HsQMLManager(
    void (*freeFun)(HsFunPtr),
    void (*freeStable)(HsStablePtr))
    : mLogLevel(0)
    , mAtExit(false)
    , mFreeFun(freeFun)
    , mFreeStable(freeStable)
    , mOriginalHandler(qcoreVariantHandler())
    , mHookedHandler(*mOriginalHandler)
    , mApp(NULL)
    , mLock(QMutex::Recursive)
    , mRunning(false)
    , mRunCount(0)
    , mStackBase(NULL)
    , mStartCb(NULL)
    , mJobsCb(NULL)
    , mYieldCb(NULL)
    , mActiveEngine(NULL)
{
    // Get log level from environment
    const char* env = std::getenv("HSQML_DEBUG_LOG_LEVEL");
    if (env) {
        setLogLevel(QString(env).toInt());
    }

    // Set hooked handler functions
    mHookedHandler.construct = &hooked_construct;
    mHookedHandler.clear = &hooked_clear;
}

void HsQMLManager::setLogLevel(int ll)
{
    mLogLevel = ll;
    if (ll > 0 && !mAtExit) {
        if (atexit(&hsqml_dump_counters) == 0) {
            mAtExit = true;
        }
        else {
            log("Failed to register callback with atexit().");
        }
    }
}

bool HsQMLManager::checkLogLevel(int ll)
{
    return mLogLevel >= ll;
}

void HsQMLManager::log(const QString& msg)
{
    std::cerr << "HsQML: " << msg.toStdString() << std::endl;
}

int HsQMLManager::updateCounter(CounterId id, int delta)
{
    return mCounters[id].fetchAndAddRelaxed(delta);
}

void HsQMLManager::freeFun(HsFunPtr funPtr)
{
    mFreeFun(funPtr);
}

void HsQMLManager::freeStable(HsStablePtr stablePtr)
{
    mFreeStable(stablePtr);
}

void HsQMLManager::hookedConstruct(QVariant::Private* p, const void* copy)
{
    char guard;
    mOriginalHandler->construct(p, copy);
    void* pp = reinterpret_cast<void*>(p);
    // The QVariant internals sometimes use a special code path for pointer
    // values which avoids calling the handler functions. This makes it
    // difficult to use them to keep a reference count. However, it's my
    // observation that this only affects transient QVariants created on the
    // stack inside the JavaScript engine's marshalling code. The persistent
    // QVariants stored in the heap are manipulated using a more restricted set
    // of operations which always use the handler functions. Hence, by assuming
    // that the stack can be discounted, it's possible to keep an accurate
    // count of heap references using these hooks.
    if ((pp < &guard || pp > mStackBase) && p->type == QMetaType::QObjectStar) {
        if (HsQMLObject* obj = dynamic_cast<HsQMLObject*>(p->data.o)) {
            HsQMLObjectProxy* proxy = obj->proxy();
            proxy->ref(HsQMLObjectProxy::Variant);
            proxy->tryGCLock();
            updateCounter(VariantCount, 1);
        }
    }
}

void HsQMLManager::hookedClear(QVariant::Private* p)
{
    char guard;
    void* pp = reinterpret_cast<void*>(p);
    if ((pp < &guard || pp > mStackBase) && p->type == QMetaType::QObjectStar) {
        if (HsQMLObject* obj = dynamic_cast<HsQMLObject*>(p->data.o)) {
            obj->proxy()->deref(HsQMLObjectProxy::Variant);
            updateCounter(VariantCount, -1);
        }
    }
    mOriginalHandler->clear(p);
}

bool HsQMLManager::isEventThread()
{
    return mApp && mApp->thread() == QThread::currentThread();
}

HsQMLManager::EventLoopStatus HsQMLManager::runEventLoop(
    HsQMLTrivialCb startCb,
    HsQMLTrivialCb jobsCb,
    HsQMLTrivialCb yieldCb)
{
    QMutexLocker locker(&mLock);

    // Check if already running
    if (mRunning) {
        return HSQML_EVLOOP_ALREADY_RUNNING;
    }

    // Check if event loop bound to a different thread
    if (mApp && !isEventThread()) {
        return HSQML_EVLOOP_WRONG_THREAD;
    }

#ifdef Q_OS_MAC
    if (!pthread_main_np()) {
        // Cocoa can only be run on the primordial thread and exec() doesn't
        // check this.
        return HSQML_EVLOOP_WRONG_THREAD;
    }
#endif

    // Check for non-threaded RTS
    if (yieldCb) {
        HSQML_LOG(0,
            "Warning: CPU cannot idle when using the non-threaded RTS.");
    }

    // Perform one-time initialisation
    if (!mApp) {
        // Install hooked handler for QVariants
        QVariantPrivate::registerHandler(0, &mHookedHandler);

        // Register custom type
        qRegisterMetaType<HsQMLEngineConfig>("HsQMLEngineConfig");

        // Create application object
        mApp = new HsQMLManagerApp();
    }

    // Save stack base and callbacks
    mStackBase = &locker;
    mStartCb = startCb;
    mJobsCb = jobsCb;
    mYieldCb = yieldCb;

    // Setup events
    QCoreApplication::postEvent(
        mApp, new QEvent(HsQMLManagerApp::StartedLoopEvent),
        Qt::HighEventPriority);
    QBasicTimer idleTimer;
    if (yieldCb) {
        idleTimer.start(0, mApp);
    }

    // Run loop
    int ret;
    do {
        ret = mApp->exec();

        // Kill all engines
        const QObjectList& cs = gManager->mApp->children();
        while (!cs.empty()) {
            delete cs.front();
        }

        // Cmd-Q on MacOS can kill the event loop before we're ready
        // Keep it running until a StopLoopEvent is received
    } while (ret == 0 && mRunning);

    // Remove redundant events
    QCoreApplication::removePostedEvents(
        mApp, HsQMLManagerApp::RemoveGCLockEvent);

    // Cleanup callbacks
    freeFun(startCb);
    mStartCb = NULL;
    freeFun(jobsCb);
    mJobsCb = NULL;
    if (yieldCb) {
        freeFun(yieldCb);
        mYieldCb = NULL;
    }

    // Return
    if (ret == 0) {
        return HSQML_EVLOOP_OK;
    }
    else {
        QCoreApplication::removePostedEvents(
            mApp, HsQMLManagerApp::StartedLoopEvent);
        return HSQML_EVLOOP_OTHER_ERROR;
    }
}

HsQMLManager::EventLoopStatus HsQMLManager::requireEventLoop()
{
    QMutexLocker locker(&mLock);
    if (mRunCount > 0) {
        mRunCount++;
        return HSQML_EVLOOP_OK;
    }
    else {
        return HSQML_EVLOOP_NOT_RUNNING;
    }
}

void HsQMLManager::releaseEventLoop()
{
    QMutexLocker locker(&mLock);
    if (--mRunCount == 0) {
        QCoreApplication::postEvent(
            mApp, new QEvent(HsQMLManagerApp::StopLoopEvent),
            Qt::LowEventPriority);
    }
}

void HsQMLManager::notifyJobs()
{
    QMutexLocker locker(&mLock);
    if (mRunCount > 0) {
        QCoreApplication::postEvent(
            mApp, new QEvent(HsQMLManagerApp::PendingJobsEvent));
    }
}

void HsQMLManager::createEngine(const HsQMLEngineConfig& config)
{
    Q_ASSERT (mApp);
    QMetaObject::invokeMethod(
        mApp, "createEngine", Q_ARG(HsQMLEngineConfig, config));
}

void HsQMLManager::setActiveEngine(HsQMLEngine* engine)
{
    Q_ASSERT(!mActiveEngine || !engine);
    mActiveEngine = engine;
}

HsQMLEngine* HsQMLManager::activeEngine()
{
    return mActiveEngine;
}

void HsQMLManager::postObjectEvent(HsQMLObjectEvent* ev)
{
    QCoreApplication::postEvent(mApp, ev);
}

HsQMLManagerApp::HsQMLManagerApp()
    : mArgC(1)
    , mArg0(0)
    , mArgV(&mArg0)
    , mApp(mArgC, &mArgV)
{
    mApp.setQuitOnLastWindowClosed(false);
}

HsQMLManagerApp::~HsQMLManagerApp()
{}

void HsQMLManagerApp::customEvent(QEvent* ev)
{
    switch (ev->type()) {
    case HsQMLManagerApp::StartedLoopEvent: {
        gManager->mRunning = true;
        gManager->mRunCount++;
        gManager->mLock.unlock();
        gManager->mStartCb();
        gManager->mJobsCb();
        break;}
    case HsQMLManagerApp::StopLoopEvent: {
        gManager->mLock.lock();
        gManager->mRunning = false;
        gManager->mApp->mApp.quit();
        break;}
    case HsQMLManagerApp::PendingJobsEvent: {
        gManager->mJobsCb();
        break;}
    case HsQMLManagerApp::RemoveGCLockEvent: {
        static_cast<HsQMLObjectEvent*>(ev)->process();
        break;}
    }
}

void HsQMLManagerApp::timerEvent(QTimerEvent*)
{
    Q_ASSERT(gManager->mYieldCb);
    gManager->mYieldCb();
}

void HsQMLManagerApp::createEngine(HsQMLEngineConfig config)
{
    HsQMLEngine* engine = new HsQMLEngine(config);
    engine->setParent(this);
}

int HsQMLManagerApp::exec()
{
    return mApp.exec();
}

extern "C" void hsqml_init(
    void (*freeFun)(HsFunPtr),
    void (*freeStable)(HsStablePtr))
{
    if (gManager == NULL) {
        HsQMLManager* manager = new HsQMLManager(freeFun, freeStable);
        if (!gManager.testAndSetOrdered(NULL, manager)) {
            delete manager;
        }
    }
}

extern "C" HsQMLEventLoopStatus hsqml_evloop_run(
    HsQMLTrivialCb startCb,
    HsQMLTrivialCb jobsCb,
    HsQMLTrivialCb yieldCb)
{
    return gManager->runEventLoop(startCb, jobsCb, yieldCb);
}

extern "C" HsQMLEventLoopStatus hsqml_evloop_require()
{
    return gManager->requireEventLoop();
}

extern "C" void hsqml_evloop_release()
{
    gManager->releaseEventLoop();
}

extern "C" void hsqml_evloop_notify_jobs()
{
    gManager->notifyJobs();
}

extern "C" void hsqml_set_debug_loglevel(int ll)
{
    Q_ASSERT (gManager);
    gManager->setLogLevel(ll);
}
<|endoftext|>


<commit_before>/*
 *  This file is part of SmartLamp application.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

/*
 * Built for Attiny84 8Mhz, using AVR USBasp programmer.
 * VERSION 0.1
 */

#include <avr/io.h>
#include <avr/sleep.h>
#include <time.h>

#include <Arduino.h>

#include <DS3232RTC.h>
//#include <USIWire.h>

// Input/output defines
#define LED_BLUE            5
#define LED_GR              3
#define LED_RED             2

#define BLU_STATE           1
#define BLU_RESET           0

#define RTC_INT_SQW        10

// Serial defines
#define SERIAL_BAUD      9600   // For at mode and for data mode (CC41, HM-10 and MLT-BT05)

// I2C defines
#define SDA                 4
#define SCL                 6

#define SLEEP_TIMEOUT   5000L   // Timeout before sleep
#define LENGTH             80   // Command buffer length

// Global variables
USI_TWI bus;                    // TinyWireM instance (I2C bus)
//USIWire bus;                    // USIWire instance (I2C bus)
DS3232RTC RTC(bus);

boolean data = false;
unsigned long prevMillis = 0;
bool rtcInitOk = false;

time_t timeProvider() {
  return RTC.get();
}

// Put the micro to sleep
void system_sleep() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  sleep_mode();

  // sleeping ...
  sleep_disable(); // wake up fully
}

void printDigits(int digits) {
  // Utility function for digital clock display: prints preceding colon and leading 0
  Serial.print(':');
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

void digitalClockDisplay(void) {
  time_t now = timeProvider();

  // Digital clock display of the time
  Serial.print(hour(now));
  printDigits(minute(now));
  printDigits(second(now));
  Serial.print(' ');
  Serial.print(day(now));
  Serial.print('/');
  Serial.print(month(now));
  Serial.print('/');
  Serial.println(year(now));
}

// PCINT Interrupt Service Routine (unused)
ISR(PCINT0_vect) {
  // Don't do anything here but we must include this
  // block of code otherwise the interrupt calls an
  // uninitialized interrupt handler.
}

void setup() {
  OSCCAL = 0x86;                    // Calibrated OSSCAL value with TinyTuner

  Serial.begin(SERIAL_BAUD);
  bus.begin();

  // Pinmode set
  pinMode(LED_BLUE, OUTPUT);
  pinMode(LED_GR, OUTPUT);
  pinMode(LED_RED, OUTPUT);
  pinMode(BLU_STATE, INPUT);
  pinMode(BLU_RESET, OUTPUT);
  pinMode(RTC_INT_SQW, INPUT);

  Serial.println(F("START SERIAL"));
  Serial.print(F("Initial value of OSCCAL is 0x"));
  Serial.println(OSCCAL, HEX);

  //setSyncProvider(RTC.get);     // The function to get the time from the RTC
  // Real time clock
  setSyncProvider(timeProvider);  // Pointer to function to get the time from the RTC

  if (timeStatus() != timeSet) {
    Serial.println(F("Unable to sync with the RTC"));
  }
  else {
    Serial.println(F("RTC has set the system time"));
    rtcInitOk = true;
  }

  if (rtcInitOk) {
    time_t t;
    tmElements_t tm;

    tm.Year = 47;
    tm.Month = 10;
    tm.Day = 18;
    tm.Hour = 21;
    tm.Minute = 45;
    tm.Second = 00;
    t = makeTime(tm);
    RTC.set(t);        //use the time_t value to ensure correct weekday is set
    setTime(t);
    Serial.print(F("RTC set to: "));
    digitalClockDisplay();
  }

  ADCSRA  = 0;                      // Disable ADC to save power
  MCUCR  |= _BV(BODS);              // BOD disabled

  PCMSK0 |= _BV(PCINT0);            // Pin change mask: listen to portA bit 0 (D10)
  PCMSK0 |= _BV(PCINT2);            // Pin change mask: listen to portA bit 2 (D8)
  GIMSK  |= _BV(PCIE0);             // Enable PCINT interrupt on portA
}

void loop() {
  size_t count = 0;
  char buffer[LENGTH];

  // FIXME Wake from sleep with new CORE can't read first serial bytes....

  if (millis() - prevMillis >= SLEEP_TIMEOUT) {
    prevMillis = millis();
    Serial.println(F("Sleeping..."));
    system_sleep();
    Serial.println(F("Waking up..."));
    digitalClockDisplay();

    // Necessary to reset the alarm flag on RTC!
    if (RTC.alarm(ALARM_1)) {
      Serial.println(F("From alarm..."));
    }
  }

  while (Serial.available() && count < LENGTH - 1) {
    delay(2);
    char c = (char) Serial.read();

    prevMillis = millis();      // Update prevMillis to reset sleep timeout

    if (c == '\r' || c == '\n') {
      if (c == '\n') {
        data = true;
        Serial.flush();
        break;
      }
      continue;
    }

    buffer[count] = c;
    count++;
  }

  if (data) {
    buffer[count] = '\0';
    //Serial.print("COUNT = ");
    //Serial.println(count);
    //Serial.println(buffer);

    count = 0;
    data = false;

    if (strcmp(buffer, "ON") == 0) {
      digitalWrite(LED_BLUE, HIGH);

      RTC.setAlarm(ALM1_MATCH_MINUTES, 45, 45, 21, 0);
      RTC.alarmInterrupt(ALARM_1, true);

//      for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
//          analogWrite(LED_BLUE, fadeValue);
//          delay(100);
//        }
//      delay(1000);
//      digitalWrite(LED_BLUE, LOW);
//
//      for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
//        analogWrite(LED_RED, fadeValue);
//        delay(100);
//      }
//      delay(1000);
//      digitalWrite(LED_RED, LOW);
//
//      for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
//        analogWrite(LED_GR, fadeValue);
//        delay(100);
//      }
//      delay(1000);
//      digitalWrite(LED_GR, LOW);
    }

    if (strcmp(buffer, "OFF") == 0) {
      digitalWrite(LED_BLUE, LOW);
      digitalWrite(LED_RED, LOW);
      digitalWrite(LED_GR, LOW);
    }

    digitalClockDisplay();
  }
}
<commit_msg>Converted RTc lib to use time.h from avr-libc.<commit_after>/*
 *  This file is part of SmartLamp application.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

/*
 * Built for Attiny84 8Mhz, using AVR USBasp programmer.
 * VERSION 0.1
 */

#include <avr/io.h>
#include <avr/sleep.h>
#include <time.h>

#include <Arduino.h>

#include <DS3232RTC.h>
//#include <USIWire.h>

// Input/output defines
#define LED_BLUE            5
#define LED_GR              3
#define LED_RED             2

#define BLU_STATE           1
#define BLU_RESET           0

#define RTC_INT_SQW        10

// Serial defines
#define SERIAL_BAUD      9600   // For at mode and for data mode (CC41, HM-10 and MLT-BT05)

// I2C defines
#define SDA                 4
#define SCL                 6

#define SLEEP_TIMEOUT   5000L   // Timeout before sleep
#define LENGTH             80   // Command buffer length

// Global variables
USI_TWI bus;                    // TinyWireM instance (I2C bus)
//USIWire bus;                    // USIWire instance (I2C bus)
DS3232RTC RTC(bus);

boolean data = false;
unsigned long prevMillis = 0;
bool rtcInitOk = false;

// Put the micro to sleep
void system_sleep() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  sleep_mode();

  // sleeping ...
  sleep_disable(); // wake up fully
}

time_t tmConvert_t(int16_t YYYY, int8_t MM, int8_t DD, int8_t hh, int8_t mm, int8_t ss) {
  struct tm tm;
  tm.tm_year = YYYY - 1900 + 30;    // avr-libc time.h: years since 1900 + y2k epoch difference (2000 - 1970)
  tm.tm_mon = MM - 1;               // avr-libc time.h: months in [0, 11]
  tm.tm_mday = DD;
  tm.tm_hour = hh;
  tm.tm_min = mm;
  tm.tm_sec = ss;
  return mk_gmtime(&tm);
}

void printDigits(int digits) {
  Serial.print(':');
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

void digitalClockDisplay(time_t time) {
  struct tm tm;

  gmtime_r(&time, &tm);

  // Digital clock display of the time
  Serial.print(tm.tm_hour);
  printDigits(tm.tm_min);
  printDigits(tm.tm_sec);
  Serial.print(' ');
  Serial.print(tm.tm_mday);
  Serial.print('/');
  Serial.print(tm.tm_mon + 1);              // avr-libc time.h: months in [0, 11]
  Serial.print('/');
  Serial.println(tm.tm_year + 1900 - 30);   // avr-libc time.h: years since 1900 + y2k epoch difference (2000 - 1970)
}

// PCINT Interrupt Service Routine (unused)
ISR(PCINT0_vect) {
  // Don't do anything here but we must include this
  // block of code otherwise the interrupt calls an
  // uninitialized interrupt handler.
}

void setup() {
  byte retcode;
  time_t ts;

  OSCCAL = 0x86;                    // Calibrated OSSCAL value with TinyTuner

  Serial.begin(SERIAL_BAUD);
  bus.begin();

  // Pinmode set
  pinMode(LED_BLUE, OUTPUT);
  pinMode(LED_GR, OUTPUT);
  pinMode(LED_RED, OUTPUT);
  pinMode(BLU_STATE, INPUT);
  pinMode(BLU_RESET, OUTPUT);
  pinMode(RTC_INT_SQW, INPUT);

  Serial.println(F("START SERIAL"));
  Serial.print(F("Initial value of OSCCAL is 0x"));
  Serial.println(OSCCAL, HEX);

  ts = tmConvert_t(2017, 10, 20, 23, 05, 00);

  if ((retcode = RTC.set(ts)) == 0)
    rtcInitOk = true;
  else {
    Serial.print(F("RTC Set error: "));
    Serial.print(retcode);
  }

  Serial.print(F("TS: "));
  Serial.println(ts);
  digitalClockDisplay(ts);

  Serial.print(F("RTC set to: "));
  Serial.println(RTC.get());
  digitalClockDisplay(RTC.get());

  ADCSRA  = 0;                      // Disable ADC to save power
  MCUCR  |= _BV(BODS);              // BOD disabled

  PCMSK0 |= _BV(PCINT0);            // Pin change mask: listen to portA bit 0 (D10)
  PCMSK0 |= _BV(PCINT2);            // Pin change mask: listen to portA bit 2 (D8)
  GIMSK  |= _BV(PCIE0);             // Enable PCINT interrupt on portA
}

void loop() {
  size_t count = 0;
  char buffer[LENGTH];

  // FIXME Wake from sleep with new CORE can't read first serial bytes....

  if (millis() - prevMillis >= SLEEP_TIMEOUT) {
    prevMillis = millis();
    Serial.println(F("Sleeping..."));
    system_sleep();
    Serial.println(F("Waking up..."));
    digitalClockDisplay(RTC.get());

    // Necessary to reset the alarm flag on RTC!
    if (RTC.alarm(ALARM_1)) {
      Serial.println(F("From alarm..."));
    }
  }

  while (Serial.available() && count < LENGTH - 1) {
    delay(2);
    char c = (char) Serial.read();

    prevMillis = millis();      // Update prevMillis to reset sleep timeout

    if (c == '\r' || c == '\n') {
      if (c == '\n') {
        data = true;
        Serial.flush();
        break;
      }
      continue;
    }

    buffer[count] = c;
    count++;
  }

  if (data) {
    buffer[count] = '\0';
    //Serial.print("COUNT = ");
    //Serial.println(count);
    Serial.println(buffer);

    count = 0;
    data = false;

    if (strcmp(buffer, "ON") == 0) {
      digitalWrite(LED_BLUE, HIGH);

      RTC.setAlarm(ALM1_MATCH_MINUTES, 00, 10, 23, 0);
      RTC.alarmInterrupt(ALARM_1, true);

//      for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
//          analogWrite(LED_BLUE, fadeValue);
//          delay(100);
//        }
//      delay(1000);
//      digitalWrite(LED_BLUE, LOW);
//
//      for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
//        analogWrite(LED_RED, fadeValue);
//        delay(100);
//      }
//      delay(1000);
//      digitalWrite(LED_RED, LOW);
//
//      for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
//        analogWrite(LED_GR, fadeValue);
//        delay(100);
//      }
//      delay(1000);
//      digitalWrite(LED_GR, LOW);
    }

    if (strcmp(buffer, "OFF") == 0) {
      digitalWrite(LED_BLUE, LOW);
      digitalWrite(LED_RED, LOW);
      digitalWrite(LED_GR, LOW);
    }

    digitalClockDisplay(RTC.get());
  }
}
<|endoftext|>


<commit_before>#include <deal.II/base/conditional_ostream.h>
#include <deal.II/base/quadrature_lib.h>

#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_tools.h>

#include <deal.II/fe/fe_q.h>

#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/manifold_lib.h>

#include <deal.II/lac/dynamic_sparsity_pattern.h>
#include <deal.II/lac/constraint_matrix.h>

#include <deal.II/numerics/error_estimator.h>

// These headers are for distributed computations:
#include <deal.II/base/utilities.h>
#include <deal.II/base/index_set.h>
#include <deal.II/distributed/tria.h>
#include <deal.II/distributed/grid_refinement.h>
#include <deal.II/distributed/solution_transfer.h>
#include <deal.II/lac/sparsity_tools.h>

#include <deal.II/lac/trilinos_solver.h>
#include <deal.II/lac/trilinos_sparse_matrix.h>
#include <deal.II/lac/trilinos_precondition.h>
#include <deal.II/lac/trilinos_vector.h>

#include <chrono>
#include <functional>
#include <iostream>

#include <deal.II-cdr/system_matrix.h>
#include <deal.II-cdr/system_rhs.h>
#include <deal.II-cdr/parameters.h>
#include <deal.II-cdr/write_pvtu_output.h>

using namespace dealii;

constexpr int manifold_id {0};

// This is the actual solver class which performs time iteration and calls the
// appropriate library functions to do it.
template<int dim>
class CDRProblem
{
public:
  CDRProblem(const CDR::Parameters &parameters);
  void run();
private:
  const CDR::Parameters parameters;
  const double time_step;
  double current_time;

  MPI_Comm mpi_communicator;
  const unsigned int n_mpi_processes;
  const unsigned int this_mpi_process;

  FE_Q<dim> fe;
  QGauss<dim> quad;
  const SphericalManifold<dim> boundary_description;
  parallel::distributed::Triangulation<dim> triangulation;
  DoFHandler<dim> dof_handler;

  const std::function<Tensor<1, dim>(const Point<dim>)> convection_function;
  const std::function<double(double, const Point<dim>)> forcing_function;

  IndexSet locally_owned_dofs;
  IndexSet locally_relevant_dofs;

  ConstraintMatrix constraints;
  bool first_run;

  // As is usual in parallel programs, I keep two copies of parts of the
  // complete solution: locally_relevant_solution contains both
  // the locally calculated solution as well as the layer of cells at its
  // boundary (the @ref GlossGhostCells "ghost cells") while
  // completely_distributed_solution only contains the parts of
  // the solution computed on the current @ref GlossMPIProcess "MPI process".
  TrilinosWrappers::MPI::Vector locally_relevant_solution;
  TrilinosWrappers::MPI::Vector completely_distributed_solution;
  TrilinosWrappers::MPI::Vector system_rhs;
  TrilinosWrappers::SparseMatrix system_matrix;
  TrilinosWrappers::PreconditionAMG preconditioner;

  ConditionalOStream pcout;

  void setup_geometry();
  void setup_system();
  void setup_dofs();
  void refine_mesh();
  void time_iterate();
};

template<int dim>
CDRProblem<dim>::CDRProblem(const CDR::Parameters &parameters) :
  parameters(parameters),
  time_step {(parameters.stop_time - parameters.start_time)
             /parameters.n_time_steps},
  current_time {parameters.start_time},
  mpi_communicator (MPI_COMM_WORLD),
  n_mpi_processes {Utilities::MPI::n_mpi_processes(mpi_communicator)},
  this_mpi_process {Utilities::MPI::this_mpi_process(mpi_communicator)},
  fe(parameters.fe_order),
  quad(3*(2 + parameters.fe_order)/2),
  boundary_description(Point<dim>()),
  triangulation(mpi_communicator, typename Triangulation<dim>::MeshSmoothing
                (Triangulation<dim>::smoothing_on_refinement |
                 Triangulation<dim>::smoothing_on_coarsening)),
  dof_handler(triangulation),
  convection_function
  {
    [](const Point<dim> p) -> Tensor<1, dim>
      {Tensor<1, dim> v; v[0] = -p[1]; v[1] = p[0]; return v;}
  },
  forcing_function
  {
    [](double t, const Point<dim> p) -> double
      {
        return std::exp(-8*t)*std::exp(-40*Utilities::fixed_power<6>(p[0] - 1.5))
          *std::exp(-40*Utilities::fixed_power<6>(p[1]));
      }
  },
  first_run {true},
  pcout (std::cout, this_mpi_process == 0)
{
  Assert(dim == 2, ExcNotImplemented());
}

template<int dim>
void CDRProblem<dim>::setup_geometry()
{
  const Point<dim> center;
  GridGenerator::hyper_shell(triangulation, center, parameters.inner_radius,
                             parameters.outer_radius);
  triangulation.set_manifold(manifold_id, boundary_description);
  for (const auto &cell : triangulation.active_cell_iterators())
    {
      cell->set_all_manifold_ids(0);
    }
  triangulation.refine_global(parameters.initial_refinement_level);
}

template<int dim>
void CDRProblem<dim>::setup_dofs()
{
  dof_handler.distribute_dofs(fe);
  pcout << "Number of degrees of freedom: "
        << dof_handler.n_dofs()
        << std::endl;
  locally_owned_dofs = dof_handler.locally_owned_dofs();
  DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs);

  constraints.clear();
  constraints.reinit(locally_relevant_dofs);
  DoFTools::make_hanging_node_constraints(dof_handler, constraints);
  DoFTools::make_zero_boundary_constraints(dof_handler, manifold_id, constraints);
  constraints.close();

  completely_distributed_solution.reinit
  (locally_owned_dofs, mpi_communicator);

  locally_relevant_solution.reinit(locally_owned_dofs, locally_relevant_dofs,
                                   mpi_communicator);
}

template<int dim>
void CDRProblem<dim>::setup_system()
{
  DynamicSparsityPattern dynamic_sparsity_pattern(dof_handler.n_dofs());
  DoFTools::make_sparsity_pattern(dof_handler, dynamic_sparsity_pattern,
                                  constraints, /*keep_constrained_dofs*/true);
  SparsityTools::distribute_sparsity_pattern
  (dynamic_sparsity_pattern, dof_handler.n_locally_owned_dofs_per_processor(),
   mpi_communicator, locally_relevant_dofs);

  system_rhs.reinit(locally_owned_dofs, mpi_communicator);
  system_matrix.reinit(locally_owned_dofs, dynamic_sparsity_pattern,
                       mpi_communicator);

  CDR::create_system_matrix<dim>
  (dof_handler, quad, convection_function, parameters, time_step, constraints,
   system_matrix);
  system_matrix.compress(VectorOperation::add);
  preconditioner.initialize(system_matrix);
}

template<int dim>
void CDRProblem<dim>::time_iterate()
{
  double current_time = parameters.start_time;
  CDR::WritePVTUOutput pvtu_output(parameters.patch_level);
  for (unsigned int time_step_n = 0; time_step_n < parameters.n_time_steps;
       ++time_step_n)
    {
      current_time += time_step;

      system_rhs = 0.0;
      CDR::create_system_rhs<dim>
      (dof_handler, quad, convection_function, forcing_function, parameters,
       locally_relevant_solution, constraints, current_time, system_rhs);
      system_rhs.compress(VectorOperation::add);

      SolverControl solver_control(dof_handler.n_dofs(),
                                   1e-6*system_rhs.l2_norm(),
                                   /*log_history = */ false,
                                   /*log_result = */ false);
      TrilinosWrappers::SolverGMRES solver(solver_control);
      solver.solve(system_matrix, completely_distributed_solution, system_rhs,
                   preconditioner);
      constraints.distribute(completely_distributed_solution);
      locally_relevant_solution = completely_distributed_solution;

      if (time_step_n % parameters.save_interval == 0)
        {
          pvtu_output.write_output(dof_handler, locally_relevant_solution,
                                   time_step_n, current_time);
        }

      refine_mesh();
    }
}

template<int dim>
void CDRProblem<dim>::refine_mesh()
{
  parallel::distributed::SolutionTransfer<dim, TrilinosWrappers::MPI::Vector>
  solution_transfer(dof_handler);

  Vector<float> estimated_error_per_cell(triangulation.n_active_cells());
  KellyErrorEstimator<dim>::estimate
  (dof_handler, QGauss<dim - 1>(fe.degree + 1), typename FunctionMap<dim>::type(),
   locally_relevant_solution, estimated_error_per_cell);

  // Poor man's version of refine and coarsen
  for (const auto &cell : triangulation.active_cell_iterators())
    {
      if (std::abs(estimated_error_per_cell[cell->active_cell_index()]) >= 1e-3)
        {
          cell->set_refine_flag();
        }
      else if (std::abs(estimated_error_per_cell[cell->active_cell_index()]) <= 1e-5)
        {
          cell->set_coarsen_flag();
        }
    }

  if (triangulation.n_levels() > parameters.max_refinement_level)
    {
      for (const auto &cell :
           triangulation.cell_iterators_on_level(parameters.max_refinement_level))
        {
          cell->clear_refine_flag();
        }
    }

  triangulation.prepare_coarsening_and_refinement();
  solution_transfer.prepare_for_coarsening_and_refinement
  (locally_relevant_solution);
  triangulation.execute_coarsening_and_refinement();

  setup_dofs();

  TrilinosWrappers::MPI::Vector temporary
  (locally_owned_dofs, mpi_communicator);
  solution_transfer.interpolate(temporary);
  locally_relevant_solution = temporary;
  constraints.distribute(locally_relevant_solution);
  setup_system();
}

template<int dim>
void CDRProblem<dim>::run()
{
  setup_geometry();
  setup_dofs();
  setup_system();
  time_iterate();
}

constexpr int dim {2};

int main(int argc, char *argv[])
{
  // One of the new features in C++11 is the chrono component of
  // the standard library. This gives us an easy way to time the output.
  auto t0 = std::chrono::high_resolution_clock::now();

  Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);
  CDR::Parameters parameters;
  parameters.read_parameter_file("parameters.prm");
  CDRProblem<dim> cdr_problem(parameters);
  cdr_problem.run();

  auto t1 = std::chrono::high_resolution_clock::now();
  if (Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0)
    {
      std::cout << "time elapsed: "
                << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count()
                << " milliseconds."
                << std::endl;
    }

  return 0;
}
<commit_msg>Use a more reasonable quadrature order.<commit_after>#include <deal.II/base/conditional_ostream.h>
#include <deal.II/base/quadrature_lib.h>

#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_tools.h>

#include <deal.II/fe/fe_q.h>

#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/manifold_lib.h>

#include <deal.II/lac/dynamic_sparsity_pattern.h>
#include <deal.II/lac/constraint_matrix.h>

#include <deal.II/numerics/error_estimator.h>

// These headers are for distributed computations:
#include <deal.II/base/utilities.h>
#include <deal.II/base/index_set.h>
#include <deal.II/distributed/tria.h>
#include <deal.II/distributed/grid_refinement.h>
#include <deal.II/distributed/solution_transfer.h>
#include <deal.II/lac/sparsity_tools.h>

#include <deal.II/lac/trilinos_solver.h>
#include <deal.II/lac/trilinos_sparse_matrix.h>
#include <deal.II/lac/trilinos_precondition.h>
#include <deal.II/lac/trilinos_vector.h>

#include <chrono>
#include <functional>
#include <iostream>

#include <deal.II-cdr/system_matrix.h>
#include <deal.II-cdr/system_rhs.h>
#include <deal.II-cdr/parameters.h>
#include <deal.II-cdr/write_pvtu_output.h>

using namespace dealii;

constexpr int manifold_id {0};

// This is the actual solver class which performs time iteration and calls the
// appropriate library functions to do it.
template<int dim>
class CDRProblem
{
public:
  CDRProblem(const CDR::Parameters &parameters);
  void run();
private:
  const CDR::Parameters parameters;
  const double time_step;
  double current_time;

  MPI_Comm mpi_communicator;
  const unsigned int n_mpi_processes;
  const unsigned int this_mpi_process;

  FE_Q<dim> fe;
  QGauss<dim> quad;
  const SphericalManifold<dim> boundary_description;
  parallel::distributed::Triangulation<dim> triangulation;
  DoFHandler<dim> dof_handler;

  const std::function<Tensor<1, dim>(const Point<dim>)> convection_function;
  const std::function<double(double, const Point<dim>)> forcing_function;

  IndexSet locally_owned_dofs;
  IndexSet locally_relevant_dofs;

  ConstraintMatrix constraints;
  bool first_run;

  // As is usual in parallel programs, I keep two copies of parts of the
  // complete solution: locally_relevant_solution contains both
  // the locally calculated solution as well as the layer of cells at its
  // boundary (the @ref GlossGhostCells "ghost cells") while
  // completely_distributed_solution only contains the parts of
  // the solution computed on the current @ref GlossMPIProcess "MPI process".
  TrilinosWrappers::MPI::Vector locally_relevant_solution;
  TrilinosWrappers::MPI::Vector completely_distributed_solution;
  TrilinosWrappers::MPI::Vector system_rhs;
  TrilinosWrappers::SparseMatrix system_matrix;
  TrilinosWrappers::PreconditionAMG preconditioner;

  ConditionalOStream pcout;

  void setup_geometry();
  void setup_system();
  void setup_dofs();
  void refine_mesh();
  void time_iterate();
};

template<int dim>
CDRProblem<dim>::CDRProblem(const CDR::Parameters &parameters) :
  parameters(parameters),
  time_step {(parameters.stop_time - parameters.start_time)
             /parameters.n_time_steps},
  current_time {parameters.start_time},
  mpi_communicator (MPI_COMM_WORLD),
  n_mpi_processes {Utilities::MPI::n_mpi_processes(mpi_communicator)},
  this_mpi_process {Utilities::MPI::this_mpi_process(mpi_communicator)},
  fe(parameters.fe_order),
  quad(parameters.fe_order + 2),
  boundary_description(Point<dim>()),
  triangulation(mpi_communicator, typename Triangulation<dim>::MeshSmoothing
                (Triangulation<dim>::smoothing_on_refinement |
                 Triangulation<dim>::smoothing_on_coarsening)),
  dof_handler(triangulation),
  convection_function
  {
    [](const Point<dim> p) -> Tensor<1, dim>
      {Tensor<1, dim> v; v[0] = -p[1]; v[1] = p[0]; return v;}
  },
  forcing_function
  {
    [](double t, const Point<dim> p) -> double
      {
        return std::exp(-8*t)*std::exp(-40*Utilities::fixed_power<6>(p[0] - 1.5))
          *std::exp(-40*Utilities::fixed_power<6>(p[1]));
      }
  },
  first_run {true},
  pcout (std::cout, this_mpi_process == 0)
{
  Assert(dim == 2, ExcNotImplemented());
}

template<int dim>
void CDRProblem<dim>::setup_geometry()
{
  const Point<dim> center;
  GridGenerator::hyper_shell(triangulation, center, parameters.inner_radius,
                             parameters.outer_radius);
  triangulation.set_manifold(manifold_id, boundary_description);
  for (const auto &cell : triangulation.active_cell_iterators())
    {
      cell->set_all_manifold_ids(0);
    }
  triangulation.refine_global(parameters.initial_refinement_level);
}

template<int dim>
void CDRProblem<dim>::setup_dofs()
{
  dof_handler.distribute_dofs(fe);
  pcout << "Number of degrees of freedom: "
        << dof_handler.n_dofs()
        << std::endl;
  locally_owned_dofs = dof_handler.locally_owned_dofs();
  DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs);

  constraints.clear();
  constraints.reinit(locally_relevant_dofs);
  DoFTools::make_hanging_node_constraints(dof_handler, constraints);
  DoFTools::make_zero_boundary_constraints(dof_handler, manifold_id, constraints);
  constraints.close();

  completely_distributed_solution.reinit
  (locally_owned_dofs, mpi_communicator);

  locally_relevant_solution.reinit(locally_owned_dofs, locally_relevant_dofs,
                                   mpi_communicator);
}

template<int dim>
void CDRProblem<dim>::setup_system()
{
  DynamicSparsityPattern dynamic_sparsity_pattern(dof_handler.n_dofs());
  DoFTools::make_sparsity_pattern(dof_handler, dynamic_sparsity_pattern,
                                  constraints, /*keep_constrained_dofs*/true);
  SparsityTools::distribute_sparsity_pattern
  (dynamic_sparsity_pattern, dof_handler.n_locally_owned_dofs_per_processor(),
   mpi_communicator, locally_relevant_dofs);

  system_rhs.reinit(locally_owned_dofs, mpi_communicator);
  system_matrix.reinit(locally_owned_dofs, dynamic_sparsity_pattern,
                       mpi_communicator);

  CDR::create_system_matrix<dim>
  (dof_handler, quad, convection_function, parameters, time_step, constraints,
   system_matrix);
  system_matrix.compress(VectorOperation::add);
  preconditioner.initialize(system_matrix);
}

template<int dim>
void CDRProblem<dim>::time_iterate()
{
  double current_time = parameters.start_time;
  CDR::WritePVTUOutput pvtu_output(parameters.patch_level);
  for (unsigned int time_step_n = 0; time_step_n < parameters.n_time_steps;
       ++time_step_n)
    {
      current_time += time_step;

      system_rhs = 0.0;
      CDR::create_system_rhs<dim>
      (dof_handler, quad, convection_function, forcing_function, parameters,
       locally_relevant_solution, constraints, current_time, system_rhs);
      system_rhs.compress(VectorOperation::add);

      SolverControl solver_control(dof_handler.n_dofs(),
                                   1e-6*system_rhs.l2_norm(),
                                   /*log_history = */ false,
                                   /*log_result = */ false);
      TrilinosWrappers::SolverGMRES solver(solver_control);
      solver.solve(system_matrix, completely_distributed_solution, system_rhs,
                   preconditioner);
      constraints.distribute(completely_distributed_solution);
      locally_relevant_solution = completely_distributed_solution;

      if (time_step_n % parameters.save_interval == 0)
        {
          pvtu_output.write_output(dof_handler, locally_relevant_solution,
                                   time_step_n, current_time);
        }

      refine_mesh();
    }
}

template<int dim>
void CDRProblem<dim>::refine_mesh()
{
  parallel::distributed::SolutionTransfer<dim, TrilinosWrappers::MPI::Vector>
  solution_transfer(dof_handler);

  Vector<float> estimated_error_per_cell(triangulation.n_active_cells());
  KellyErrorEstimator<dim>::estimate
  (dof_handler, QGauss<dim - 1>(fe.degree + 1), typename FunctionMap<dim>::type(),
   locally_relevant_solution, estimated_error_per_cell);

  // Poor man's version of refine and coarsen
  for (const auto &cell : triangulation.active_cell_iterators())
    {
      if (std::abs(estimated_error_per_cell[cell->active_cell_index()]) >= 1e-3)
        {
          cell->set_refine_flag();
        }
      else if (std::abs(estimated_error_per_cell[cell->active_cell_index()]) <= 1e-5)
        {
          cell->set_coarsen_flag();
        }
    }

  if (triangulation.n_levels() > parameters.max_refinement_level)
    {
      for (const auto &cell :
           triangulation.cell_iterators_on_level(parameters.max_refinement_level))
        {
          cell->clear_refine_flag();
        }
    }

  triangulation.prepare_coarsening_and_refinement();
  solution_transfer.prepare_for_coarsening_and_refinement
  (locally_relevant_solution);
  triangulation.execute_coarsening_and_refinement();

  setup_dofs();

  TrilinosWrappers::MPI::Vector temporary
  (locally_owned_dofs, mpi_communicator);
  solution_transfer.interpolate(temporary);
  locally_relevant_solution = temporary;
  constraints.distribute(locally_relevant_solution);
  setup_system();
}

template<int dim>
void CDRProblem<dim>::run()
{
  setup_geometry();
  setup_dofs();
  setup_system();
  time_iterate();
}

constexpr int dim {2};

int main(int argc, char *argv[])
{
  // One of the new features in C++11 is the chrono component of
  // the standard library. This gives us an easy way to time the output.
  auto t0 = std::chrono::high_resolution_clock::now();

  Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);
  CDR::Parameters parameters;
  parameters.read_parameter_file("parameters.prm");
  CDRProblem<dim> cdr_problem(parameters);
  cdr_problem.run();

  auto t1 = std::chrono::high_resolution_clock::now();
  if (Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0)
    {
      std::cout << "time elapsed: "
                << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count()
                << " milliseconds."
                << std::endl;
    }

  return 0;
}
<|endoftext|>


<commit_before>/**
 * Copyright 2008 Matthew Graham
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "server_message.h"
#include "connection_test.h"
#include <testpp/test.h>

/**
 * Test that the constructor for the server message sets fields
 * into the correct state.
 */
TESTPP( test_server_message_constructor )
{
	mock_client_server_connection_c cs( 3 );
	server_message_c msg( "create dog cat", cs.server() );

	assertpp( msg.request_type() ) == "create";
	// assertpp( msg.request().extra_argc() ) == 3;
	assertpp( msg.port() ) == 3;
}

<commit_msg>fixed the server_message test to take connection *<commit_after>/**
 * Copyright 2008 Matthew Graham
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "server_message.h"
#include "connection_test.h"
#include <testpp/test.h>

/**
 * Test that the constructor for the server message sets fields
 * into the correct state.
 */
TESTPP( test_server_message_constructor )
{
	mock_client_server_connection_c cs( 3 );
	server_message_c msg( "create dog cat", &cs.server() );

	assertpp( msg.request_type() ) == "create";
	// assertpp( msg.request().extra_argc() ) == 3;
	assertpp( msg.port() ) == 3;
}

<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2010, Willow Garage, Inc.
 *  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 Willow Garage, Inc. nor the names of its
 *     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.
 *
 */

#ifndef PCL_SURFACE_IMPL_POISSON_H_
#define PCL_SURFACE_IMPL_POISSON_H_

#include "pcl/surface/poisson.h"
#include <pcl/common/common.h>
#include <pcl/common/vector_average.h>
#include <pcl/Vertices.h>

#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include "pcl/surface/poisson/octree.h"
#include "pcl/surface/poisson/sparse_matrix.h"
#include "pcl/surface/poisson/function_data.h"
#include "pcl/surface/poisson/ppolynomial.h"
#include "pcl/surface/poisson/multi_grid_octree_data.h"

#define MEMORY_ALLOCATOR_BLOCK_SIZE 1<<12

#include <stdarg.h>
#include <string>

using namespace pcl::surface::poisson;

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointNT>
pcl::surface::Poisson<PointNT>::Poisson ()
  : no_reset_samples_(false),
    no_clip_tree_(false),
    confidence_(false),
    manifold_(false),
    depth_(10),
    solver_divide_(8),
    iso_divide_(8),
    refine_(3),
    kernel_depth_(8),
    degree_ (2),
    samples_per_node_(1.0),
    scale_(1.25)
{
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointNT>
pcl::surface::Poisson<PointNT>::~Poisson ()
{
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointNT> template <int Degree> void
pcl::surface::Poisson<PointNT>::execute (CoredMeshData &mesh,
                                         Point3D<float> &center)
{
  float scale = 1;
  //////////////////////////////////
  // Fix courtesy of David Gallup //
  // TreeNodeData::UseIndex = 1;  //
  //////////////////////////////////
  Octree<Degree> tree;
  PPolynomial<Degree> ReconstructionFunction=PPolynomial<Degree>::GaussianApproximation();

  center.coords[0]=center.coords[1]=center.coords[2]=0;

  TreeOctNode::SetAllocator(MEMORY_ALLOCATOR_BLOCK_SIZE);

  int kernel_depth=depth_-2;
  if(kernel_depth_){kernel_depth=kernel_depth_;}

  tree.setFunctionData(ReconstructionFunction,depth_,0,float(1.0)/(1<<depth_));
  if (kernel_depth > depth_)
  {
    PCL_ERROR ("KernelDepth can't be greater than Depth: %d <= %d\n",kernel_depth,depth_);
    return;
  }

  tree.setTree (depth_, kernel_depth, float(samples_per_node_), scale_, center, scale, !no_reset_samples_, confidence_, input_);

  if(!no_clip_tree_)
    tree.ClipTree();

  tree.finalize1(refine_);

  tree.SetLaplacianWeights();

  tree.finalize2(refine_);

  tree.LaplacianMatrixIteration(solver_divide_);

  float isoValue=tree.GetIsoValue();

  if (iso_divide_)
    tree.GetMCIsoTriangles (isoValue, iso_divide_, &mesh, 0, 1, manifold_);
  else
    tree.GetMCIsoTriangles (isoValue, &mesh, 0, 1, manifold_);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointNT> void
pcl::surface::Poisson<PointNT>::performReconstruction (PolygonMesh &output)
{
  CoredVectorMeshData mesh;
  Point3D<float> center;

  switch(degree_)
  {
    case 1:
      execute<1> (mesh, center);
      break;
    case 2:
      execute<2> (mesh, center);
      break;
    case 3:
      execute<3> (mesh, center);
      break;
    case 4:
      execute<4> (mesh, center);
      break;
    case 5:
      execute<5> (mesh, center);
      break;
    default:
      PCL_ERROR (stderr,"Degree %d not supported\n", degree_);
  }

  /// Write output PolygonMesh
  float scale = 1;
   // write vertices
   pcl::PointCloud < pcl::PointXYZ > cloud;
   cloud.points.resize (int (mesh.outOfCorePointCount()+mesh.inCorePoints.size ()) );
   Point3D<float> p;
   for (int i = 0; i < int(mesh.inCorePoints.size()); i++)
   {
     p = mesh.inCorePoints[i];
     cloud.points[i].x = p.coords[0]*scale+center.coords[0];
     cloud.points[i].y = p.coords[1]*scale+center.coords[1];
     cloud.points[i].z = p.coords[2]*scale+center.coords[2];
   }
   for (int i = int(mesh.inCorePoints.size()); i < int (mesh.outOfCorePointCount() + mesh.inCorePoints.size ()); i++)
   {
     mesh.nextOutOfCorePoint(p);
     cloud.points[i].x = p.coords[0]*scale+center.coords[0];
     cloud.points[i].y = p.coords[1]*scale+center.coords[1];
     cloud.points[i].z = p.coords[2]*scale+center.coords[2];
   }
   pcl::toROSMsg (cloud, output.cloud);
   output.polygons.resize (mesh.triangleCount ());

   // write faces
   TriangleIndex tIndex;
   int inCoreFlag;
   for (int i = 0; i < mesh.triangleCount(); i++)
   {
     // create and fill a struct that the ply code can handle
     pcl::Vertices v;
     v.vertices.resize (3);

     mesh.nextTriangle(tIndex,inCoreFlag);
     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[0])) { tIndex.idx[0] += int(mesh.inCorePoints.size()); }
     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[1])) { tIndex.idx[1] += int(mesh.inCorePoints.size()); }
     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[2])) { tIndex.idx[2] += int(mesh.inCorePoints.size()); }
     for (int j = 0; j < 3; j++) {v.vertices[j] = tIndex.idx[j];}
     output.polygons[i] = v;
   }  // for, write faces
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointNT> void
pcl::surface::Poisson<PointNT>::performReconstruction (pcl::PointCloud<PointNT> &points,
                                                       std::vector<pcl::Vertices> &polygons)
{
  CoredVectorMeshData mesh;
  Point3D<float> center;

  switch(degree_)
  {
    case 1:
      execute<1> (mesh, center);
      break;
    case 2:
      execute<2> (mesh, center);
      break;
    case 3:
      execute<3> (mesh, center);
      break;
    case 4:
      execute<4> (mesh, center);
      break;
    case 5:
      execute<5> (mesh, center);
      break;
    default:
      PCL_ERROR (stderr,"Degree %d not supported\n", degree_);
  }

  /// Write output PolygonMesh
  float scale = 1;
   // write vertices
   points.points.resize (int (mesh.outOfCorePointCount()+mesh.inCorePoints.size ()) );
   Point3D<float> p;
   for (int i = 0; i < int(mesh.inCorePoints.size()); i++)
   {
     p = mesh.inCorePoints[i];
     points.points[i].x = p.coords[0]*scale+center.coords[0];
     points.points[i].y = p.coords[1]*scale+center.coords[1];
     points.points[i].z = p.coords[2]*scale+center.coords[2];
   }
   for (int i = int(mesh.inCorePoints.size()); i < int (mesh.outOfCorePointCount() + mesh.inCorePoints.size ()); i++)
   {
     mesh.nextOutOfCorePoint(p);
     points.points[i].x = p.coords[0]*scale+center.coords[0];
     points.points[i].y = p.coords[1]*scale+center.coords[1];
     points.points[i].z = p.coords[2]*scale+center.coords[2];
   }

   polygons.resize (mesh.triangleCount ());

   // write faces
   TriangleIndex tIndex;
   int inCoreFlag;
   for (int i = 0; i < mesh.triangleCount(); i++)
   {
     // create and fill a struct that the ply code can handle
     pcl::Vertices v;
     v.vertices.resize (3);

     mesh.nextTriangle(tIndex,inCoreFlag);
     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[0])) { tIndex.idx[0] += int(mesh.inCorePoints.size()); }
     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[1])) { tIndex.idx[1] += int(mesh.inCorePoints.size()); }
     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[2])) { tIndex.idx[2] += int(mesh.inCorePoints.size()); }
     for (int j = 0; j < 3; j++) {v.vertices[j] = tIndex.idx[j];}
     polygons[i] = v;
   }  // for, write faces

}

#define PCL_INSTANTIATE_Poisson(T) template class PCL_EXPORTS pcl::surface::Poisson<T>;

#endif    // PCL_SURFACE_IMPL_POISSON_H_

<commit_msg>poisson beautification<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2010, Willow Garage, Inc.
 *  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 Willow Garage, Inc. nor the names of its
 *     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.
 *
 */

#ifndef PCL_SURFACE_IMPL_POISSON_H_
#define PCL_SURFACE_IMPL_POISSON_H_

#include "pcl/surface/poisson.h"
#include <pcl/common/common.h>
#include <pcl/common/vector_average.h>
#include <pcl/Vertices.h>

#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include "pcl/surface/poisson/octree.h"
#include "pcl/surface/poisson/sparse_matrix.h"
#include "pcl/surface/poisson/function_data.h"
#include "pcl/surface/poisson/ppolynomial.h"
#include "pcl/surface/poisson/multi_grid_octree_data.h"

#define MEMORY_ALLOCATOR_BLOCK_SIZE 1<<12

#include <stdarg.h>
#include <string>

using namespace pcl::surface::poisson;

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointNT>
pcl::surface::Poisson<PointNT>::Poisson ()
  : no_reset_samples_ (false),
    no_clip_tree_ (false),
    confidence_ (false),
    manifold_ (false),
    depth_ (10),
    solver_divide_ (8),
    iso_divide_ (8),
    refine_ (3),
    kernel_depth_ (8),
    degree_ (2),
    samples_per_node_ (1.0),
    scale_ (1.25)
{
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointNT>
pcl::surface::Poisson<PointNT>::~Poisson ()
{
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointNT> template <int Degree> void
pcl::surface::Poisson<PointNT>::execute (CoredMeshData &mesh,
                                         Point3D<float> &center)
{
  float scale = 1;
  //////////////////////////////////
  // Fix courtesy of David Gallup //
  // TreeNodeData::UseIndex = 1;  //
  //////////////////////////////////
  Octree<Degree> tree;
  PPolynomial<Degree> ReconstructionFunction = PPolynomial<Degree>::GaussianApproximation ();

  center.coords[0] = center.coords[1] = center.coords[2] = 0;

  TreeOctNode::SetAllocator(MEMORY_ALLOCATOR_BLOCK_SIZE);

  int kernel_depth=depth_-2;
  if (kernel_depth_)
    kernel_depth=kernel_depth_;

  tree.setFunctionData (ReconstructionFunction,depth_, 0, float (1.0) / (1<<depth_));
  if (kernel_depth > depth_)
  {
    PCL_ERROR ("KernelDepth can't be greater than Depth: %d <= %d\n", kernel_depth, depth_);
    return;
  }

  tree.setTree (depth_, kernel_depth, float (samples_per_node_), scale_, center, scale, !no_reset_samples_, confidence_, input_);

  if(!no_clip_tree_)
    tree.ClipTree ();

  tree.finalize1 (refine_);
  tree.SetLaplacianWeights ();
  tree.finalize2 (refine_);

  tree.LaplacianMatrixIteration (solver_divide_);

  float isoValue=tree.GetIsoValue ();

  if (iso_divide_)
    tree.GetMCIsoTriangles (isoValue, iso_divide_, &mesh, 0, 1, manifold_);
  else
    tree.GetMCIsoTriangles (isoValue, &mesh, 0, 1, manifold_);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointNT> void
pcl::surface::Poisson<PointNT>::performReconstruction (PolygonMesh &output)
{
  CoredVectorMeshData mesh;
  Point3D<float> center;

  printf ("Before execution\n");
  switch (degree_)
  {
    case 1:
      execute<1> (mesh, center);
      break;
    case 2:
      execute<2> (mesh, center);
      break;
    case 3:
      execute<3> (mesh, center);
      break;
    case 4:
      execute<4> (mesh, center);
      break;
    case 5:
      execute<5> (mesh, center);
      break;
    default:
      PCL_ERROR (stderr,"Degree %d not supported\n", degree_);
  }

  printf ("Done execution \n");

  /// Write output PolygonMesh
  float scale = 1;
   // write vertices
   pcl::PointCloud < pcl::PointXYZ > cloud;
   cloud.points.resize (int (mesh.outOfCorePointCount()+mesh.inCorePoints.size ()));
   Point3D<float> p;
   for (int i = 0; i < int (mesh.inCorePoints.size()); i++)
   {
     p = mesh.inCorePoints[i];
     cloud.points[i].x = p.coords[0]*scale+center.coords[0];
     cloud.points[i].y = p.coords[1]*scale+center.coords[1];
     cloud.points[i].z = p.coords[2]*scale+center.coords[2];
   }
   for (int i = int (mesh.inCorePoints.size ()); i < int (mesh.outOfCorePointCount () + mesh.inCorePoints.size ()); i++)
   {
     mesh.nextOutOfCorePoint (p);
     cloud.points[i].x = p.coords[0]*scale+center.coords[0];
     cloud.points[i].y = p.coords[1]*scale+center.coords[1];
     cloud.points[i].z = p.coords[2]*scale+center.coords[2];
   }
   pcl::toROSMsg (cloud, output.cloud);
   output.polygons.resize (mesh.triangleCount ());

   // Write faces
   TriangleIndex tIndex;
   int inCoreFlag;
   for (int i = 0; i < mesh.triangleCount(); i++)
   {
     // Create and fill a struct that the ply code can handle
     pcl::Vertices v;
     v.vertices.resize (3);

     mesh.nextTriangle(tIndex,inCoreFlag);
     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[0]))
       tIndex.idx[0] += int(mesh.inCorePoints.size());
     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[1]))
       tIndex.idx[1] += int(mesh.inCorePoints.size());
     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[2]))
       tIndex.idx[2] += int(mesh.inCorePoints.size());

     for (int j = 0; j < 3; j++)
       v.vertices[j] = tIndex.idx[j];
     output.polygons[i] = v;
   }
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointNT> void
pcl::surface::Poisson<PointNT>::performReconstruction (pcl::PointCloud<PointNT> &points,
                                                       std::vector<pcl::Vertices> &polygons)
{
  CoredVectorMeshData mesh;
  Point3D<float> center;

  switch(degree_)
  {
    case 1:
      execute<1> (mesh, center);
      break;
    case 2:
      execute<2> (mesh, center);
      break;
    case 3:
      execute<3> (mesh, center);
      break;
    case 4:
      execute<4> (mesh, center);
      break;
    case 5:
      execute<5> (mesh, center);
      break;
    default:
      PCL_ERROR (stderr,"Degree %d not supported\n", degree_);
  }

  /// Write output PolygonMesh
  float scale = 1;
   // write vertices
   points.points.resize (int (mesh.outOfCorePointCount ()+mesh.inCorePoints.size ()));
   Point3D<float> p;
   for (int i = 0; i < int(mesh.inCorePoints.size()); i++)
   {
     p = mesh.inCorePoints[i];
     points.points[i].x = p.coords[0]*scale+center.coords[0];
     points.points[i].y = p.coords[1]*scale+center.coords[1];
     points.points[i].z = p.coords[2]*scale+center.coords[2];
   }
   for (int i = int(mesh.inCorePoints.size()); i < int (mesh.outOfCorePointCount() + mesh.inCorePoints.size ()); i++)
   {
     mesh.nextOutOfCorePoint(p);
     points.points[i].x = p.coords[0]*scale+center.coords[0];
     points.points[i].y = p.coords[1]*scale+center.coords[1];
     points.points[i].z = p.coords[2]*scale+center.coords[2];
   }

   polygons.resize (mesh.triangleCount ());

   // write faces
   TriangleIndex tIndex;
   int inCoreFlag;
   for (int i = 0; i < mesh.triangleCount (); i++)
   {
     // create and fill a struct that the ply code can handle
     pcl::Vertices v;
     v.vertices.resize (3);

     mesh.nextTriangle(tIndex,inCoreFlag);
     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[0]))
       tIndex.idx[0] += int(mesh.inCorePoints.size());
     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[1]))
       tIndex.idx[1] += int(mesh.inCorePoints.size());
     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[2]))
       tIndex.idx[2] += int(mesh.inCorePoints.size());
     for (int j = 0; j < 3; j++)
       v.vertices[j] = tIndex.idx[j];
     polygons[i] = v;
   }
}

#define PCL_INSTANTIATE_Poisson(T) template class PCL_EXPORTS pcl::surface::Poisson<T>;

#endif    // PCL_SURFACE_IMPL_POISSON_H_

<|endoftext|>


<commit_before>/*"name": "sensorflare",
Author: "LPFraile <lidiapf0@gmail.com>",
License: "BSD",
Version: "0.0.1",
Description: "Include your Particle Core on Sensorflare"
File: Examplo:Publish on sensorflare different variables of the code upload on Particle core
*/
//Include the SensorFlare library
#include "sensorflare/sensorflare.h"

//Initialize objects from the library

//One object of the class "PWMOut" is initialized for
//every PWM output that will be remote control
SensorFlare::PWMOut pwm(A0);

//One object of the class "VarPublish" is initialized for every variable
//that will be published in order to access remotly from the cloud
//The argument that name the varible has a maximum of 12 characters
//Both methods initialized the variable that will be published as PUBLIC
SensorFlare::VarPublish varTem("temperature");
SensorFlare::VarPublish varPir("pir","PUBLIC");
//Initialized the variable that will be published as PRIVATE
SensorFlare::VarPublish varLight("light","PRIVATE");

// Initialize the different variables that will be used in the program
int tem_pin=A3;
int light_pin=A4;
int pir_pin=D0;
int status;
int new_status;
bool change;

void setup() {

// Call the begin() functions for every object of the classes "DigitalOut" and
//"PWMout" to be wired up correct and available.

    pwm.begin();

//Set the extra pins that are used on the program, but are not controlled remotely
    pinMode(pir_pin,INPUT);

}

void loop() {

    // Temperature sensor
    float tem= analogRead(tem_pin); // read value from the sensor
    // The returned value from the Core is going to be in the range from 0 to 4095
    // Calculate the voltage from the sensor reading
    float voltage = (tem * 3.3) / 4095;
    float deg =voltage* 100; // multiply by 100 to get degrees in K
    float temperature = deg - 273.15; // subtract absolute zero to get degrees Celsius

    //Luminosity
    float photocell= analogRead(light_pin); // read value from the sensor
    // The returned value from the Core is going to be in the range from 0 to 4095
    // Calculate the voltage from the sensor reading
    float Vphotocell = ((photocell * 3.3) / 4095);
    float rl=(Vphotocell*10)/(3.3-Vphotocell);//Photoresistor value in KΩ
    float value=500/rl;//luminosity
    int light= (int) value;

    //Find the change of state of the PIR sensor. Recognize move
    new_status=digitalRead(pir_pin);
    if (status!=new_status){
        status=new_status;
        change=TRUE;
    }

    //Publish every time that exist a change in the pin on which is connect the output of the PIR
    if (change==TRUE) {
        varPir.Publish(status,0);//Publish the variable at the called method time
        change=FALSE;
    }

    //Publish the variables every 15 seconds.
    varTem.Publish(temperature,15);
    varLight.Publish(light,15);

}
<commit_msg>Update senorflare-publish.cpp<commit_after>/*"name": "sensorflare",
Author: "LPFraile <lidiapf0@gmail.com>",
License: "BSD",
Version: "0.0.1",
Description: "Include your Particle Core on Sensorflare"
File: Examplo:Publish on your Sensorflare account some variables of the code upload on your Particle core.
*/
//Include the SensorFlare library
#include "sensorflare/sensorflare.h"

//Initialize objects from the library

//One object of the class "PWMOut" is initialized for
//every PWM output that will be remote control
SensorFlare::PWMOut pwm(A0);

//One object of the class "VarPublish" is initialized for every variable
//that will be published in order to access remotly from the cloud
//The argument that name the varible has a maximum of 12 characters
//Both methods initialized the variable that will be published as PUBLIC
SensorFlare::VarPublish varTem("temperature");
SensorFlare::VarPublish varPir("pir","PUBLIC");
//Initialized the variable that will be published as PRIVATE
SensorFlare::VarPublish varLight("light","PRIVATE");

// Initialize the different variables that will be used in the program
int tem_pin=A3;
int light_pin=A4;
int pir_pin=D0;
int status;
int new_status;
bool change;

void setup() {

// Call the begin() functions for every object of the classes "DigitalOut" and
//"PWMout" to be wired up correct and available.

    pwm.begin();

//Set the extra pins that are used on the program, but are not controlled remotely
    pinMode(pir_pin,INPUT);

}

void loop() {

    // Temperature sensor
    float tem= analogRead(tem_pin); // read value from the sensor
    // The returned value from the Core is going to be in the range from 0 to 4095
    // Calculate the voltage from the sensor reading
    float voltage = (tem * 3.3) / 4095;
    float deg =voltage* 100; // multiply by 100 to get degrees in K
    float temperature = deg - 273.15; // subtract absolute zero to get degrees Celsius

    //Luminosity
    float photocell= analogRead(light_pin); // read value from the sensor
    // The returned value from the Core is going to be in the range from 0 to 4095
    // Calculate the voltage from the sensor reading
    float Vphotocell = ((photocell * 3.3) / 4095);
    float rl=(Vphotocell*10)/(3.3-Vphotocell);//Photoresistor value in KΩ
    float value=500/rl;//luminosity
    int light= (int) value;

    //Find the change of state of the PIR sensor. Recognize move
    new_status=digitalRead(pir_pin);
    if (status!=new_status){
        status=new_status;
        change=TRUE;
    }

    //Publish every time that exist a change in the pin on which is connect the output of the PIR
    if (change==TRUE) {
        varPir.Publish(status,0);//Publish the variable at the called method time
        change=FALSE;
    }

    //Publish the variables every 15 seconds.
    varTem.Publish(temperature,15);
    varLight.Publish(light,15);

}
<|endoftext|>


<commit_before>/*
*	ExtraWork - Allows PvPGN clients to load this DLL and executes code for specific clients
*	Copyright (C) 2014  xboi209 (xboi209@gmail.com)
*
*	This program is free software: you can redistribute it and/or modify
*	it under the terms of the GNU General Public License as published by
*	the Free Software Foundation, either version 3 of the License, or
*	(at your option) any later version.
*
*	This program is distributed in the hope that it will be useful,
*	but WITHOUT ANY WARRANTY; without even the implied warranty of
*	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*	GNU General Public License for more details.
*
*	You should have received a copy of the GNU General Public License
*	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#define WIN32_LEAN_AND_MEAN

#include <Windows.h>
#include <TlHelp32.h>
#include "ExtraWork.h"

BOOL __fastcall ExtraWork(EXTRAWORK *inStruct, int /*unused*/ )
{
	if (inStruct)
		strcpy_s(inStruct->OutBuffer, sizeof(inStruct->OutBuffer), "IX86ExtraWork v1.0 by xboi209");
	else
		return FALSE;

	game.pid = GetCurrentProcessId();
	game.handle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION | PROCESS_SUSPEND_RESUME | PROCESS_TERMINATE | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, game.pid);
	EnumWindows((WNDENUMPROC)enumWindowsProc, NULL);
	GetClassName(game.hWnd, (LPTSTR)game.classname, 256/*number of characters, not bytes*/);

	//Check what the game is and call a function specifically for that game
	if (strcmp(game.classname, SEXP) == 0)
		sexp();
	else if (strcmp(game.classname, W3XP) == 0)
		w3xp();
	else if (strcmp(game.classname, D2XP) == 0)
		d2xp();
	else
		return FALSE;

	return TRUE;
}

void sexp()
{
	return;
}

void w3xp()
{
	return;
}

void d2xp()
{
	return;
}

BOOL CALLBACK enumWindowsProc(HWND hWnd, LPARAM /*lParam*/)
{
	DWORD tempPID;
	char className[256];

	GetWindowThreadProcessId(hWnd, &tempPID);

	if (tempPID == game.pid)
	{
		GetClassName(hWnd, className, 256/*number of characters, not bytes*/);

		for (int i = 0; i < classNameElementSize; ++i)
		{
			if (strcmp(classNames[i], className) == 0)
			{
				game.hWnd = hWnd;
				return FALSE;
			}
		}
	}

	return TRUE;
}
<commit_msg>Update ExtraWork.cpp<commit_after>/*
*	ExtraWork - Allows PvPGN clients to load this DLL and executes code for specific clients
*	Copyright (C) 2014  xboi209 (xboi209@gmail.com)
*
*	This program is free software: you can redistribute it and/or modify
*	it under the terms of the GNU General Public License as published by
*	the Free Software Foundation, either version 3 of the License, or
*	(at your option) any later version.
*
*	This program is distributed in the hope that it will be useful,
*	but WITHOUT ANY WARRANTY; without even the implied warranty of
*	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*	GNU General Public License for more details.
*
*	You should have received a copy of the GNU General Public License
*	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#define WIN32_LEAN_AND_MEAN

#include <Windows.h>
#include <TlHelp32.h>
#include "ExtraWork.h"

__declspec(dllexport) BOOL __fastcall ExtraWork(EXTRAWORK *inStruct, int /*unused*/ )
{
	if (inStruct)
		strcpy_s(inStruct->OutBuffer, sizeof(inStruct->OutBuffer), "IX86ExtraWork v1.0 by xboi209");
	else
		return FALSE;

	game.pid = GetCurrentProcessId();
	game.handle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION | PROCESS_SUSPEND_RESUME | PROCESS_TERMINATE | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, game.pid);
	EnumWindows((WNDENUMPROC)enumWindowsProc, NULL);
	GetClassName(game.hWnd, (LPTSTR)game.classname, 256/*number of characters, not bytes*/);

	//Check what the game is and call a function specifically for that game
	if (strcmp(game.classname, SEXP) == 0)
		sexp();
	else if (strcmp(game.classname, W3XP) == 0)
		w3xp();
	else if (strcmp(game.classname, D2XP) == 0)
		d2xp();
	else
		return FALSE;

	return TRUE;
}

void sexp()
{
	return;
}

void w3xp()
{
	return;
}

void d2xp()
{
	return;
}

BOOL CALLBACK enumWindowsProc(HWND hWnd, LPARAM /*lParam*/)
{
	DWORD tempPID;
	char className[256];

	GetWindowThreadProcessId(hWnd, &tempPID);

	if (tempPID == game.pid)
	{
		GetClassName(hWnd, className, 256/*number of characters, not bytes*/);

		for (int i = 0; i < classNameElementSize; ++i)
		{
			if (strcmp(classNames[i], className) == 0)
			{
				game.hWnd = hWnd;
				return FALSE;
			}
		}
	}

	return TRUE;
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "DataCache.h"

CDataCache::CDataCache(CFxQueue& queue)
    : m_queue(queue)
    , m_isEventGenerated(false)
    , m_isSessionInfoInitialized(false)
{
}

CFxSessionInfo CDataCache::GetSessionInfo() const
{
	CSharedLocker lock(m_synchronizer);
	return m_sessionInfo;
}

void CDataCache::UpdateSessionInfo(const CFxSessionInfo& sessionInfo)
{
	CExclusiveLocker lock(m_synchronizer);
	m_sessionInfo = sessionInfo;
	m_isSessionInfoInitialized = true;
}

void CDataCache::Clear()
{
	m_sessionInfo = CFxSessionInfo();
	m_isSessionInfoInitialized = false;
	m_isEventGenerated = false;
}

void CDataCache::Update(bool isInitialized)
{
	const bool isCacheInitialized = isInitialized && m_isSessionInfoInitialized;

	if (!isCacheInitialized)
	{
		return;
	}

	if (!m_isEventGenerated)
	{
		CFxEventInfo eventInfo;
		CFxMessage message(FX_MSG_CACHE_UPDATED, eventInfo);
		m_queue.ProcessMessage(message);
		m_isEventGenerated = true;
	}

}
<commit_msg>Bugfix problem with deadlock in cache initializaion<commit_after>#include "stdafx.h"
#include "DataCache.h"

CDataCache::CDataCache(CFxQueue& queue)
    : m_queue(queue)
    , m_isEventGenerated(false)
    , m_isSessionInfoInitialized(false)
{
}

CFxSessionInfo CDataCache::GetSessionInfo() const
{
    CSharedLocker lock(m_synchronizer);
    return m_sessionInfo;
}

void CDataCache::UpdateSessionInfo(const CFxSessionInfo& sessionInfo)
{
    CExclusiveLocker lock(m_synchronizer);
    m_sessionInfo = sessionInfo;
    m_isSessionInfoInitialized = true;
}

void CDataCache::Clear()
{
    m_sessionInfo = CFxSessionInfo();
    m_isSessionInfoInitialized = false;
    m_isEventGenerated = false;
}

void CDataCache::Update(bool isInitialized)
{
    // Bugfix problem with deadlock in cache initializaion
    // const bool isCacheInitialized = isInitialized && m_isSessionInfoInitialized;
    const bool isCacheInitialized = isInitialized;

    if (!isCacheInitialized)
    {
        return;
    }

    if (!m_isEventGenerated)
    {
        CFxEventInfo eventInfo;
        CFxMessage message(FX_MSG_CACHE_UPDATED, eventInfo);
        m_queue.ProcessMessage(message);
        m_isEventGenerated = true;
    }

}
<|endoftext|>