<commit_before>/*
   Copyright (c) 2008 Sebastian Trueg <trueg@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "queryserviceclient.h"
#include "dbusoperators.h"
#include "result.h"
#include "queryserviceinterface.h"
#include "queryinterface.h"

#include <QtDBus/QDBusInterface>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusConnectionInterface>
#include <QtDBus/QDBusReply>

#include <QtCore/QEventLoop>
#include <QtCore/QTimer>

namespace {
    /**
     * Each thread needs its own QDBusConnection. We do it the very easy
     * way and just create a new connection for each client
     * Why does Qt not handle this automatically?
     */
    class QDBusConnectionPerThreadHelper
    {
    public:
        QDBusConnectionPerThreadHelper()
            : m_connection( QDBusConnection::connectToBus(
                                QDBusConnection::SessionBus,
                                QString::fromLatin1("NepomukQueryServiceConnection%1").arg(newNumber()) ) )
        {
        }
        ~QDBusConnectionPerThreadHelper() {
            QDBusConnection::disconnectFromBus( m_connection.name() );
        }

        static QDBusConnection threadConnection();

    private:
        int newNumber() {
            return m_counter.fetchAndAddAcquire(1);
        }
        QAtomicInt m_counter;
        QDBusConnection m_connection;
    };

    QThreadStorage<QDBusConnectionPerThreadHelper *> s_perThreadConnection;

    QDBusConnection QDBusConnectionPerThreadHelper::threadConnection()
    {
        if (!s_perThreadConnection.hasLocalData()) {
            s_perThreadConnection.setLocalData(new QDBusConnectionPerThreadHelper);
        }
        return s_perThreadConnection.localData()->m_connection;
    }
}

class Nepomuk::Search::QueryServiceClient::Private
{
public:
    Private()
        : queryServiceInterface( 0 ),
          queryInterface( 0 ),
          dbusConnection( QDBusConnectionPerThreadHelper::threadConnection() ),
          loop( 0 ) {
    }

    void _k_entriesRemoved( const QStringList& );
    void _k_finishedListing();
    bool handleQueryReply( QDBusReply<QDBusObjectPath> reply );

    org::kde::nepomuk::QueryService* queryServiceInterface;
    org::kde::nepomuk::Query* queryInterface;

    QueryServiceClient* q;

    QDBusConnection dbusConnection;

    QEventLoop* loop;
};

void Nepomuk::Search::QueryServiceClient::Private::_k_entriesRemoved( const QStringList& uris )
{
    QList<QUrl> ul;
    foreach( const QString& s, uris ) {
        ul.append( QUrl( s ) );
    }
    emit q->entriesRemoved( ul );
}

void Nepomuk::Search::QueryServiceClient::Private::_k_finishedListing()
{
    emit q->finishedListing();
    if( loop ) {
        q->close();
    }
}

bool Nepomuk::Search::QueryServiceClient::Private::handleQueryReply( QDBusReply<QDBusObjectPath> r )
{
    if ( r.isValid() ) {
        queryInterface = new org::kde::nepomuk::Query( queryServiceInterface->service(),
                                                       r.value().path(),
                                                       dbusConnection  );
        connect( queryInterface, SIGNAL( newEntries( QList<Nepomuk::Search::Result> ) ),
                 q, SIGNAL( newEntries( QList<Nepomuk::Search::Result> ) ) );
        connect( queryInterface, SIGNAL( entriesRemoved( QStringList ) ),
                 q, SLOT( _k_entriesRemoved( QStringList ) ) );
        connect( queryInterface, SIGNAL( finishedListing() ),
                 q, SLOT( _k_finishedListing() ) );
        // run the listing async in case the event loop below is the only one we have
        // and we need it to handle the signals and list returns results immediately
        QTimer::singleShot( 0, queryInterface, SLOT(list()) );
        return true;
    }
    else {
        qDebug() << "Query failed:" << r.error().message();
        return false;
    }
}

Nepomuk::Search::QueryServiceClient::QueryServiceClient( QObject* parent )
    : QObject( parent ),
      d( new Private() )
{
    d->q = this;

    Nepomuk::Search::registerDBusTypes();

    // we use our own connection to be thread-safe
    d->queryServiceInterface = new org::kde::nepomuk::QueryService( QLatin1String("org.kde.nepomuk.services.nepomukqueryservice"),
                                                                    QLatin1String("/nepomukqueryservice"),
                                                                    d->dbusConnection );
}

Nepomuk::Search::QueryServiceClient::~QueryServiceClient()
{
    delete d->queryServiceInterface;
    close();
    delete d;
}

bool Nepomuk::Search::QueryServiceClient::query( const QString& query )
{
    close();

    if ( d->queryServiceInterface->isValid() ) {
        return d->handleQueryReply( d->queryServiceInterface->sparqlQuery( query, QHash<QString, QString>() ) );
    }
    else {
        qDebug() << "Could not contact query service.";
        return false;
    }
}

bool Nepomuk::Search::QueryServiceClient::blockingQuery( const QString& q )
{
    if( query( q ) ) {
        QEventLoop loop;
        d->loop = &loop;
        loop.exec();
        d->loop = 0;
        return true;
    }
    else {
        return false;
    }
}

void Nepomuk::Search::QueryServiceClient::close()
{
    if ( d->queryInterface ) {
        qDebug() << Q_FUNC_INFO;
        d->queryInterface->close();
        delete d->queryInterface;
        d->queryInterface = 0;
        if( d->loop )
            d->loop->exit();
    }
}

bool Nepomuk::Search::QueryServiceClient::serviceAvailable()
{
    return QDBusConnection::sessionBus().interface()->isServiceRegistered( QLatin1String("org.kde.nepomuk.services.nepomukqueryservice") );
}

#include "queryserviceclient.moc"
<commit_msg>apply fix r1089483 by trueg: use a static counter to make sure we use unique names<commit_after>/*
   Copyright (c) 2008 Sebastian Trueg <trueg@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "queryserviceclient.h"
#include "dbusoperators.h"
#include "result.h"
#include "queryserviceinterface.h"
#include "queryinterface.h"

#include <QtDBus/QDBusInterface>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusConnectionInterface>
#include <QtDBus/QDBusReply>

#include <QtCore/QEventLoop>
#include <QtCore/QTimer>

namespace {

    QAtomicInt s_connectionCounter;
    /**
     * Each thread needs its own QDBusConnection. We do it the very easy
     * way and just create a new connection for each client
     * Why does Qt not handle this automatically?
     */
    class QDBusConnectionPerThreadHelper
    {
    public:
        QDBusConnectionPerThreadHelper()
            : m_connection( QDBusConnection::connectToBus(
                                QDBusConnection::SessionBus,
                                QString::fromLatin1("NepomukQueryServiceConnection%1").arg(newNumber()) ) )
        {
        }
        ~QDBusConnectionPerThreadHelper() {
            QDBusConnection::disconnectFromBus( m_connection.name() );
        }

        static QDBusConnection threadConnection();

    private:
        static int newNumber() {
            return s_connectionCounter.fetchAndAddAcquire(1);
        }
        QDBusConnection m_connection;
    };

    QThreadStorage<QDBusConnectionPerThreadHelper *> s_perThreadConnection;

    QDBusConnection QDBusConnectionPerThreadHelper::threadConnection()
    {
        if (!s_perThreadConnection.hasLocalData()) {
            s_perThreadConnection.setLocalData(new QDBusConnectionPerThreadHelper);
        }
        return s_perThreadConnection.localData()->m_connection;
    }
}

class Nepomuk::Search::QueryServiceClient::Private
{
public:
    Private()
        : queryServiceInterface( 0 ),
          queryInterface( 0 ),
          dbusConnection( QDBusConnectionPerThreadHelper::threadConnection() ),
          loop( 0 ) {
    }

    void _k_entriesRemoved( const QStringList& );
    void _k_finishedListing();
    bool handleQueryReply( QDBusReply<QDBusObjectPath> reply );

    org::kde::nepomuk::QueryService* queryServiceInterface;
    org::kde::nepomuk::Query* queryInterface;

    QueryServiceClient* q;

    QDBusConnection dbusConnection;

    QEventLoop* loop;
};

void Nepomuk::Search::QueryServiceClient::Private::_k_entriesRemoved( const QStringList& uris )
{
    QList<QUrl> ul;
    foreach( const QString& s, uris ) {
        ul.append( QUrl( s ) );
    }
    emit q->entriesRemoved( ul );
}

void Nepomuk::Search::QueryServiceClient::Private::_k_finishedListing()
{
    emit q->finishedListing();
    if( loop ) {
        q->close();
    }
}

bool Nepomuk::Search::QueryServiceClient::Private::handleQueryReply( QDBusReply<QDBusObjectPath> r )
{
    if ( r.isValid() ) {
        queryInterface = new org::kde::nepomuk::Query( queryServiceInterface->service(),
                                                       r.value().path(),
                                                       dbusConnection  );
        connect( queryInterface, SIGNAL( newEntries( QList<Nepomuk::Search::Result> ) ),
                 q, SIGNAL( newEntries( QList<Nepomuk::Search::Result> ) ) );
        connect( queryInterface, SIGNAL( entriesRemoved( QStringList ) ),
                 q, SLOT( _k_entriesRemoved( QStringList ) ) );
        connect( queryInterface, SIGNAL( finishedListing() ),
                 q, SLOT( _k_finishedListing() ) );
        // run the listing async in case the event loop below is the only one we have
        // and we need it to handle the signals and list returns results immediately
        QTimer::singleShot( 0, queryInterface, SLOT(list()) );
        return true;
    }
    else {
        qDebug() << "Query failed:" << r.error().message();
        return false;
    }
}

Nepomuk::Search::QueryServiceClient::QueryServiceClient( QObject* parent )
    : QObject( parent ),
      d( new Private() )
{
    d->q = this;

    Nepomuk::Search::registerDBusTypes();

    // we use our own connection to be thread-safe
    d->queryServiceInterface = new org::kde::nepomuk::QueryService( QLatin1String("org.kde.nepomuk.services.nepomukqueryservice"),
                                                                    QLatin1String("/nepomukqueryservice"),
                                                                    d->dbusConnection );
}

Nepomuk::Search::QueryServiceClient::~QueryServiceClient()
{
    delete d->queryServiceInterface;
    close();
    delete d;
}

bool Nepomuk::Search::QueryServiceClient::query( const QString& query )
{
    close();

    if ( d->queryServiceInterface->isValid() ) {
        return d->handleQueryReply( d->queryServiceInterface->sparqlQuery( query, QHash<QString, QString>() ) );
    }
    else {
        qDebug() << "Could not contact query service.";
        return false;
    }
}

bool Nepomuk::Search::QueryServiceClient::blockingQuery( const QString& q )
{
    if( query( q ) ) {
        QEventLoop loop;
        d->loop = &loop;
        loop.exec();
        d->loop = 0;
        return true;
    }
    else {
        return false;
    }
}

void Nepomuk::Search::QueryServiceClient::close()
{
    if ( d->queryInterface ) {
        qDebug() << Q_FUNC_INFO;
        d->queryInterface->close();
        delete d->queryInterface;
        d->queryInterface = 0;
        if( d->loop )
            d->loop->exit();
    }
}

bool Nepomuk::Search::QueryServiceClient::serviceAvailable()
{
    return QDBusConnection::sessionBus().interface()->isServiceRegistered( QLatin1String("org.kde.nepomuk.services.nepomukqueryservice") );
}

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


<commit_before>//
// Copyright (C) Alexandr Vorontsov. 2017
// Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
//

#include "stdafx.h"

#include "Render/Geometry/ParserFBX.h"

namespace Kioto
{

namespace
{
Vector4 FbxVector4ToKioto(const FbxVector4& vec)
{
    return { static_cast<float32>(vec.mData[0]), static_cast<float32>(vec.mData[1]), static_cast<float32>(vec.mData[2]), static_cast<float32>(vec.mData[3]) };
}
}

void ParserFBX::Initialize(std::string path)
{
    bool result = false;
    m_fbxManager = FbxManager::Create();
    if (m_fbxManager == nullptr)
    {
        throw "Cant create manager.";
    }

    FbxIOSettings* ios = FbxIOSettings::Create(m_fbxManager, IOSROOT);
    m_fbxManager->SetIOSettings(ios);

    m_scene = FbxScene::Create(m_fbxManager, "ImportFbxScene");
    if (m_scene == nullptr)
    {
        throw "cant create fbx scene";
    }

    bool res = LoadScene(m_fbxManager, m_scene, path.c_str());
    FbxDocumentInfo* sceneInfo = m_scene->GetSceneInfo();
    TraverseHiererchy(m_scene);
}

void ParserFBX::Shutdown()
{
    m_fbxManager->Destroy();
}

bool ParserFBX::LoadScene(FbxManager* manager, FbxDocument* scene, const char* filename)
{
    int32 fileMajor = 0;
    int32 fileMinor = 0;
    int32 fileRevision = 0;

    int32 skdMajor = 0;
    int32 sdkMinor = 0;
    int32 sdkRevision = 0;

    int32 i = 0;
    int32 animStackCount = 0;
    bool status = false;

    FbxManager::GetFileFormatVersion(skdMajor, sdkMinor, sdkRevision);

    FbxImporter* importer = FbxImporter::Create(m_fbxManager, "");
    bool importStatus = importer->Initialize(filename, -1, m_fbxManager->GetIOSettings());
    importer->GetFileVersion(fileMajor, fileMinor, fileRevision);
    if (!importStatus)
    {
        FbxString error = importer->GetStatus().GetErrorString();
        //FBXSDK_printf("Call to FbxImporter::Initialize() failed.\n");
        //FBXSDK_printf("Error returned: %s\n\n", error.Buffer());

        if (importer->GetStatus().GetCode() == FbxStatus::eInvalidFileVersion)
        {
            //FBXSDK_printf("FBX file format version for this FBX SDK is %d.%d.%d\n", lSDKMajor, lSDKMinor, lSDKRevision);
            //FBXSDK_printf("FBX file format version for file '%s' is %d.%d.%d\n\n", pFilename, lFileMajor, lFileMinor, lFileRevision);
        }
        return false;
    }
    FbxSystemUnit::m.ConvertScene(m_scene);
    if (importer->IsFBX())
    {
        animStackCount = importer->GetAnimStackCount();

        //IOS_REF.SetBoolProp(IMP_FBX_MATERIAL, true);
        //IOS_REF.SetBoolProp(IMP_FBX_TEXTURE, true);
        //IOS_REF.SetBoolProp(IMP_FBX_LINK, true);
        //IOS_REF.SetBoolProp(IMP_FBX_SHAPE, true);
        //IOS_REF.SetBoolProp(IMP_FBX_GOBO, true);
        //IOS_REF.SetBoolProp(IMP_FBX_ANIMATION, true);
        //IOS_REF.SetBoolProp(IMP_FBX_GLOBAL_SETTINGS, true);
    }

    status = importer->Import(scene);
    if (!status)
        throw "cant open fbx";
    importer->Destroy();

    return status;
}

void ParserFBX::TraverseHiererchy(FbxScene* scene)
{
    FbxNode* root = scene->GetRootNode();
    for (int32 i = 0; i < root->GetChildCount(); ++i)
        TraverseHiererchy(root->GetChild(i), 0);
}

void ParserFBX::TraverseHiererchy(FbxNode* node, int32 depth)
{
    FbxString string = node->GetName();
    std::string name(string.Buffer());

    FbxNodeAttribute::EType attribType = FbxNodeAttribute::eUnknown;
    if (node->GetNodeAttribute() == nullptr)
        throw "Null node attribute";
    else
    {
        attribType = node->GetNodeAttribute()->GetAttributeType();
        auto unit = m_scene->GetGlobalSettings().GetSystemUnit();
        int p = 0;
        if (unit == FbxSystemUnit::cm)
        {
            ++p;
        }
        else if (unit == FbxSystemUnit::m)
        {
            ++p;
        }
        else if (unit == FbxSystemUnit::Inch)
        {
            ++p;
        }
        else if (unit == FbxSystemUnit::Foot)
        {
            ++p;
        }

        if (attribType == FbxNodeAttribute::eMesh)
        {
            FbxVector4 mat = node->EvaluateLocalRotation(0);
            //Matrix4 loclaTransform(reinterpret_cast<float32>(mat.mData));

            FbxMesh* mesh = reinterpret_cast<FbxMesh*>(node->GetNodeAttribute());

            int32 polygonCount = mesh->GetPolygonCount();
            FbxVector4* controlPoints = mesh->GetControlPoints();
            int32 vertexId = 0;
            for (int32 i = 0; i < polygonCount; ++i)
            {
                for (int32 l = 0; l < mesh->GetElementPolygonGroupCount(); l++)
                {
                    FbxGeometryElementPolygonGroup* polGroup = mesh->GetElementPolygonGroup(i);
                }
                int32 polygonSize = mesh->GetPolygonSize(i);

                for (int32 j = 0; j < polygonSize; ++j)
                {
                    int32 controlPointIndex = mesh->GetPolygonVertex(i, j);
                    FbxVector4 coord = controlPoints[controlPointIndex];
                    Vector4 v4c = FbxVector4ToKioto(coord);
                }

            }

        }
    }

    for (int32 i = 0; i < node->GetChildCount(); ++i)
        TraverseHiererchy(node->GetChild(i), depth + 1);
}

}<commit_msg>Uv, normal, binormal from fbx.<commit_after>//
// Copyright (C) Alexandr Vorontsov. 2017
// Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
//

#include "stdafx.h"

#include "Render/Geometry/ParserFBX.h"

namespace Kioto
{

namespace
{
Vector4 FbxVector4ToKioto(const FbxVector4& vec)
{
    return { static_cast<float32>(vec.mData[0]), static_cast<float32>(vec.mData[1]), static_cast<float32>(vec.mData[2]), static_cast<float32>(vec.mData[3]) };
}

Vector4 FbxColorToKioto(const FbxColor& color)
{
    return { static_cast<float32>(color.mRed), static_cast<float32>(color.mGreen), static_cast<float32>(color.mBlue), static_cast<float32>(color.mAlpha) };
}

Vector2 FbxVector2ToKioto(const FbxVector2& vec)
{
    return { static_cast<float32>(vec.mData[0]), static_cast<float32>(vec.mData[1]) };
}
}

void ParserFBX::Initialize(std::string path)
{
    bool result = false;
    m_fbxManager = FbxManager::Create();
    if (m_fbxManager == nullptr)
    {
        throw "Cant create manager.";
    }

    FbxIOSettings* ios = FbxIOSettings::Create(m_fbxManager, IOSROOT);
    m_fbxManager->SetIOSettings(ios);

    m_scene = FbxScene::Create(m_fbxManager, "ImportFbxScene");
    if (m_scene == nullptr)
    {
        throw "cant create fbx scene";
    }

    bool res = LoadScene(m_fbxManager, m_scene, path.c_str());
    FbxDocumentInfo* sceneInfo = m_scene->GetSceneInfo();
    TraverseHiererchy(m_scene);
}

void ParserFBX::Shutdown()
{
    m_fbxManager->Destroy();
}

bool ParserFBX::LoadScene(FbxManager* manager, FbxDocument* scene, const char* filename)
{
    int32 fileMajor = 0;
    int32 fileMinor = 0;
    int32 fileRevision = 0;

    int32 skdMajor = 0;
    int32 sdkMinor = 0;
    int32 sdkRevision = 0;

    int32 i = 0;
    int32 animStackCount = 0;
    bool status = false;

    FbxManager::GetFileFormatVersion(skdMajor, sdkMinor, sdkRevision);

    FbxImporter* importer = FbxImporter::Create(m_fbxManager, "");
    bool importStatus = importer->Initialize(filename, -1, m_fbxManager->GetIOSettings());
    importer->GetFileVersion(fileMajor, fileMinor, fileRevision);
    if (!importStatus)
    {
        FbxString error = importer->GetStatus().GetErrorString();
        //FBXSDK_printf("Call to FbxImporter::Initialize() failed.\n");
        //FBXSDK_printf("Error returned: %s\n\n", error.Buffer());

        if (importer->GetStatus().GetCode() == FbxStatus::eInvalidFileVersion)
        {
            //FBXSDK_printf("FBX file format version for this FBX SDK is %d.%d.%d\n", lSDKMajor, lSDKMinor, lSDKRevision);
            //FBXSDK_printf("FBX file format version for file '%s' is %d.%d.%d\n\n", pFilename, lFileMajor, lFileMinor, lFileRevision);
        }
        return false;
    }
    FbxSystemUnit::m.ConvertScene(m_scene);
    if (importer->IsFBX())
    {
        animStackCount = importer->GetAnimStackCount();

        //IOS_REF.SetBoolProp(IMP_FBX_MATERIAL, true);
        //IOS_REF.SetBoolProp(IMP_FBX_TEXTURE, true);
        //IOS_REF.SetBoolProp(IMP_FBX_LINK, true);
        //IOS_REF.SetBoolProp(IMP_FBX_SHAPE, true);
        //IOS_REF.SetBoolProp(IMP_FBX_GOBO, true);
        //IOS_REF.SetBoolProp(IMP_FBX_ANIMATION, true);
        //IOS_REF.SetBoolProp(IMP_FBX_GLOBAL_SETTINGS, true);
    }

    status = importer->Import(scene);
    if (!status)
        throw "cant open fbx";
    importer->Destroy();

    return status;
}

void ParserFBX::TraverseHiererchy(FbxScene* scene)
{
    FbxNode* root = scene->GetRootNode();
    for (int32 i = 0; i < root->GetChildCount(); ++i)
        TraverseHiererchy(root->GetChild(i), 0);
}

void ParserFBX::TraverseHiererchy(FbxNode* node, int32 depth)
{
    FbxString string = node->GetName();
    std::string name(string.Buffer());

    FbxNodeAttribute::EType attribType = FbxNodeAttribute::eUnknown;
    if (node->GetNodeAttribute() == nullptr)
        throw "Null node attribute";
    else
    {
        attribType = node->GetNodeAttribute()->GetAttributeType();
        auto unit = m_scene->GetGlobalSettings().GetSystemUnit();
        int p = 0;
        if (unit == FbxSystemUnit::cm)
        {
            ++p;
        }
        else if (unit == FbxSystemUnit::m)
        {
            ++p;
        }
        else if (unit == FbxSystemUnit::Inch)
        {
            ++p;
        }
        else if (unit == FbxSystemUnit::Foot)
        {
            ++p;
        }

        if (attribType == FbxNodeAttribute::eMesh)
        {
            FbxVector4 mat = node->EvaluateLocalRotation(0);
            //Matrix4 loclaTransform(reinterpret_cast<float32>(mat.mData));

            FbxMesh* mesh = reinterpret_cast<FbxMesh*>(node->GetNodeAttribute());

            int32 polygonCount = mesh->GetPolygonCount();
            FbxVector4* controlPoints = mesh->GetControlPoints();
            int32 vertexId = 0;
            for (int32 i = 0; i < polygonCount; ++i)
            {
                for (int32 l = 0; l < mesh->GetElementPolygonGroupCount(); l++)
                {
                    FbxGeometryElementPolygonGroup* polGroup = mesh->GetElementPolygonGroup(i);
                }
                int32 polygonSize = mesh->GetPolygonSize(i);
                assert(polygonSize == 3);

                for (int32 j = 0; j < polygonSize; ++j)
                {
                    int32 controlPointIndex = mesh->GetPolygonVertex(i, j);
                    FbxVector4 coord = controlPoints[controlPointIndex];
                    Vector4 vectorCoord = FbxVector4ToKioto(coord);

                    for (int32 l = 0; l < mesh->GetElementVertexColorCount(); ++l)
                    {
                        FbxGeometryElementVertexColor* vertexColorElement = mesh->GetElementVertexColor(l);
                        Vector4 color;
                        if (vertexColorElement->GetMappingMode() == FbxLayerElement::eByControlPoint)
                        {
                            switch (vertexColorElement->GetReferenceMode())
                            {
                            case FbxGeometryElement::eDirect:
                                color = FbxColorToKioto(vertexColorElement->GetDirectArray().GetAt(controlPointIndex));
                                break;
                            case FbxGeometryElement::eIndexToDirect:
                            {
                                int id = vertexColorElement->GetIndexArray().GetAt(controlPointIndex);
                                color = FbxColorToKioto(vertexColorElement->GetDirectArray().GetAt(id));
                            }
                            break;
                            default:
                                assert(false);
                            }
                        }
                        else if (vertexColorElement->GetMappingMode() == FbxGeometryElement::eByPolygonVertex)
                        {
                            switch (vertexColorElement->GetReferenceMode())
                            {
                            case FbxGeometryElement::eDirect:
                                color = FbxColorToKioto(vertexColorElement->GetDirectArray().GetAt(vertexId));
                                break;
                            case FbxGeometryElement::eIndexToDirect:
                            {
                                int id = vertexColorElement->GetIndexArray().GetAt(vertexId);
                                color = FbxColorToKioto(vertexColorElement->GetDirectArray().GetAt(id));
                            }
                            break;
                            default:
                                assert(false);;
                            }
                        }
                        else
                        {
                            assert(false);
                        }
                    }

                    //************************** UV
                    for (uint32 l = 0; l < mesh->GetElementUVCount(); ++l)
                    {
                        Vector2 uvCoord;
                        FbxGeometryElementUV* uv = mesh->GetElementUV(l);
                        if (uv->GetMappingMode() == FbxLayerElement::eByControlPoint)
                        {
                            switch (uv->GetReferenceMode())
                            {
                            case FbxGeometryElement::eDirect:
                                uvCoord = FbxVector2ToKioto(uv->GetDirectArray().GetAt(controlPointIndex));
                                break;
                            case FbxGeometryElement::eIndexToDirect:
                            {
                                int id = uv->GetIndexArray().GetAt(controlPointIndex);
                                uvCoord = FbxVector2ToKioto(uv->GetDirectArray().GetAt(id));
                            }
                            break;
                            default:
                                assert(false);;
                            }
                        }
                        else if (uv->GetMappingMode() == FbxLayerElement::eByPolygonVertex)
                        {
                            int textureUVIndex = mesh->GetTextureUVIndex(i, j);
                            uvCoord = FbxVector2ToKioto(uv->GetDirectArray().GetAt(textureUVIndex));
                        }
                        else
                        {
                            assert(false);
                        }
                    }

                    // normals////////////////////////////////////////

                    for (int32 l = 0; l < mesh->GetElementNormalCount(); ++l)
                    {
                        Vector4 normal;
                        FbxGeometryElementNormal* normals = mesh->GetElementNormal(l);
                        if (normals->GetMappingMode() == FbxLayerElement::eByPolygonVertex)
                        {
                            switch (normals->GetReferenceMode())
                            {
                            case FbxGeometryElement::eDirect:
                                normal = FbxVector4ToKioto(normals->GetDirectArray().GetAt(vertexId));
                                break;
                            case FbxGeometryElement::eIndexToDirect:
                            {
                                int id = normals->GetIndexArray().GetAt(vertexId);
                                normal = FbxVector4ToKioto(normals->GetDirectArray().GetAt(id));
                            }
                            break;
                            default:
                                assert(false);
                            }
                        }
                        else
                        {
                            assert(false);
                        }
                    }

                    // tangent////////////////////////////////////////

                    for (int32 l = 0; l < mesh->GetElementTangentCount(); ++l)
                    {
                        Vector4 tangent;
                        FbxGeometryElementTangent* tangents = mesh->GetElementTangent(l);
                        if (tangents->GetMappingMode() == FbxLayerElement::eByPolygonVertex)
                        {
                            switch (tangents->GetReferenceMode())
                            {
                            case FbxGeometryElement::eDirect:
                                tangent = FbxVector4ToKioto(tangents->GetDirectArray().GetAt(vertexId));
                                break;
                            case FbxGeometryElement::eIndexToDirect:
                            {
                                int id = tangents->GetIndexArray().GetAt(vertexId);
                                tangent = FbxVector4ToKioto(tangents->GetDirectArray().GetAt(id));
                            }
                            break;
                            default:
                                assert(false);
                            }
                        }
                        else
                        {
                            assert(false);
                        }
                    }

                    // binormal////////////////////////////////////////

                    for (int32 l = 0; l < mesh->GetElementBinormalCount(); ++l)
                    {
                        Vector4 binormal;
                        FbxGeometryElementBinormal* binormals = mesh->GetElementBinormal(l);
                        if (binormals->GetMappingMode() == FbxLayerElement::eByPolygonVertex)
                        {
                            switch (binormals->GetReferenceMode())
                            {
                            case FbxGeometryElement::eDirect:
                                binormal = FbxVector4ToKioto(binormals->GetDirectArray().GetAt(vertexId));
                                break;
                            case FbxGeometryElement::eIndexToDirect:
                            {
                                int id = binormals->GetIndexArray().GetAt(vertexId);
                                binormal = FbxVector4ToKioto(binormals->GetDirectArray().GetAt(id));
                            }
                            break;
                            default:
                                assert(false);
                            }
                        }
                        else
                        {
                            assert(false);
                        }
                    }

                    ++vertexId;
                }

            }

        }
    }

    for (int32 i = 0; i < node->GetChildCount(); ++i)
        TraverseHiererchy(node->GetChild(i), depth + 1);
}

}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011, The University of Oxford
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. Neither the name of the University of Oxford 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 HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <mex.h>
#include <cstring>

#include "utility/oskar_vector_types.h"
#include "utility/matlab/oskar_mex_pointer.h"
#include "utility/oskar_Mem.h"
#include "utility/matlab/oskar_get_type_string.h"

// MATLAB entry function.
void mexFunction(int num_out, mxArray** out, int num_in, const mxArray** in)
{
    // Check number of input arguments.
    if (num_out != 1 || num_in != 4)
    {
        mexErrMsgTxt("Usage: pointer = oskar_mem_set_values(pointer, type, "
                "location, values)");
    }

    // Parse input arguments.
    oskar_Mem* mem     = covert_mxArray_to_pointer<oskar_Mem>(in[0]);
    int type           = (int)mxGetScalar(in[1]);
    int location       = (int)mxGetScalar(in[2]);
    int num_elements   = mem->num_elements();

    // Properties of the values array.
    mwSize num_dims    = mxGetNumberOfDimensions(in[3]);
    const mwSize* dims = mxGetDimensions(in[3]);
    mxClassID class_id = mxGetClassID(in[3]);
    bool complex       = mxIsComplex(in[3]);

    // Only support 3 or 2 dimensions for matrix data and 1 dimension for scalar
    // data.
    if (num_dims > 3)
    {
        mexErrMsgTxt("Specified values array has unsupported dimensions");
    }

    // Work out the OSKAR type of the values array.
    int values_type = 0;
    switch (class_id)
    {
        case mxSINGLE_CLASS:
            values_type = OSKAR_SINGLE;
            break;
        case mxDOUBLE_CLASS:
            values_type = OSKAR_DOUBLE;
            break;
        case mxINT32_CLASS:
            values_type = OSKAR_INT;
            break;
        default:
            mexErrMsgTxt("Incompatible data type for specified values array");
            break;
    };

    mexPrintf("values type = %i %s\n", values_type, oskar_get_type_string(values_type));

    if (complex && values_type != OSKAR_INT)
    {
        values_type |= OSKAR_COMPLEX;
    }
    mexPrintf("values type = %i %s\n", values_type, oskar_get_type_string(values_type));

    // Work out if this is matrix data.
    // Matrix data is (2,2,n) where for the case of n = 1 the dimension will
    // be collapsed.
    bool matrix = false;
    if (num_dims >=2 && num_dims <= 3)
    {
        if (dims[0] == 2 && dims[1] == 2)
            matrix = true;
    }
    if (matrix)
    {
        values_type |= OSKAR_MATRIX;
    }

    mexPrintf("values type = %i %s\n", values_type, oskar_get_type_string(values_type));

}

<commit_msg>updated error condition on mex oskar_Mem function<commit_after>/*
 * Copyright (c) 2011, The University of Oxford
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. Neither the name of the University of Oxford 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 HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <mex.h>
#include <cstring>

#include "utility/oskar_vector_types.h"
#include "utility/matlab/oskar_mex_pointer.h"
#include "utility/oskar_Mem.h"
#include "utility/matlab/oskar_get_type_string.h"

// MATLAB entry function.
void mexFunction(int num_out, mxArray** out, int num_in, const mxArray** in)
{
    // Check number of input arguments.
    if (num_out != 1 || num_in != 4)
    {
        mexErrMsgTxt("Usage: pointer = oskar_mem_set_values(pointer, type, "
                "location, values)");
    }

    // Parse input arguments.
    oskar_Mem* mem     = covert_mxArray_to_pointer<oskar_Mem>(in[0]);
    int type           = (int)mxGetScalar(in[1]);
    int location       = (int)mxGetScalar(in[2]);
    int num_elements   = mem->num_elements();

    // Properties of the values array.
    mwSize num_dims    = mxGetNumberOfDimensions(in[3]);
    const mwSize* dims = mxGetDimensions(in[3]);
    mxClassID class_id = mxGetClassID(in[3]);
    bool complex       = mxIsComplex(in[3]);

    // Only support 3 or 2 dimensions for matrix data and 1 dimension for scalar
    // data.
    if (num_dims > 3)
    {
        mexErrMsgTxt("Specified values array has unsupported dimensions");
    }

    // Work out the OSKAR type of the values array.
    int values_type = 0;
    switch (class_id)
    {
        case mxSINGLE_CLASS:
            values_type = OSKAR_SINGLE;
            break;
        case mxDOUBLE_CLASS:
            values_type = OSKAR_DOUBLE;
            break;
        case mxINT32_CLASS:
            values_type = OSKAR_INT;
            break;
        default:
            mexErrMsgTxt("Incompatible data type for specified values array");
            break;
    };

    mexPrintf("values type = %i %s\n", values_type, oskar_get_type_string(values_type));

    if (complex && values_type != OSKAR_INT)
    {
        values_type |= OSKAR_COMPLEX;
    }
    mexPrintf("values type = %i %s\n", values_type, oskar_get_type_string(values_type));

    // Work out if this is matrix data.
    // Matrix data is (2,2,n) where for the case of n = 1 the dimension will
    // be collapsed.
    bool matrix = false;
    if (num_dims >=2 && num_dims <= 3)
    {
        if (dims[0] == 2 && dims[1] == 2)
            matrix = true;
        else
            mexErrMsgTxt("Values array has invalid dimensions");
    }
    if (matrix)
    {
        values_type |= OSKAR_MATRIX;
    }
    mexPrintf("values type = %i %s\n", values_type, oskar_get_type_string(values_type));

}

<|endoftext|>


<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_VAL_HPP_
#define RDB_PROTOCOL_VAL_HPP_

#include <set>
#include <string>
#include <utility>
#include <vector>

#include "containers/counted.hpp"
#include "containers/wire_string.hpp"
#include "rdb_protocol/datum_stream.hpp"
#include "rdb_protocol/ql2.pb.h"

namespace ql {
class datum_t;
class rdb_namespace_access_t;
class env_t;
template <class> class protob_t;
class scope_env_t;
class stream_cache_t;
class term_t;
class val_t;

class db_t : public single_threaded_countable_t<db_t> {
public:
    db_t(uuid_u _id, const std::string &_name) : id(_id), name(_name) { }
    const uuid_u id;
    const std::string name;
};

class table_t : public single_threaded_countable_t<table_t>, public pb_rcheckable_t {
public:
    table_t(env_t *env,
            counted_t<const db_t> db, const std::string &name,
            bool use_outdated, const protob_t<const Backtrace> &src);
    counted_t<datum_stream_t> as_datum_stream(env_t *env,
                                              const protob_t<const Backtrace> &bt);
    const std::string &get_pkey();
    counted_t<const datum_t> get_row(env_t *env, counted_t<const datum_t> pval);
    counted_t<datum_stream_t> get_all(
            env_t *env,
            counted_t<const datum_t> value,
            const std::string &sindex_id,
            const protob_t<const Backtrace> &bt);
    void add_sorting(
        const std::string &sindex_id, sorting_t sorting,
        const rcheckable_t *parent);
    void add_bounds(datum_range_t &&new_bounds,
                    const std::string &new_sindex_id,
                    const rcheckable_t *parent);

    counted_t<const datum_t> make_error_datum(const base_exc_t &exception);

    counted_t<const datum_t> batched_replace(
        env_t *env,
        const std::vector<counted_t<const datum_t> > &vals,
        const std::vector<counted_t<const datum_t> > &keys,
        counted_t<func_t> replacement_generator,
        bool nondeterministic_replacements_ok,
        durability_requirement_t durability_requirement,
        bool return_vals);

    counted_t<const datum_t> batched_insert(
        env_t *env,
        std::vector<counted_t<const datum_t> > &&insert_datums,
        bool upsert,
        durability_requirement_t durability_requirement,
        bool return_vals);

    MUST_USE bool sindex_create(
        env_t *env, const std::string &name,
        counted_t<func_t> index_func, sindex_multi_bool_t multi);
    MUST_USE bool sindex_drop(env_t *env, const std::string &name);
    counted_t<const datum_t> sindex_list(env_t *env);
    counted_t<const datum_t> sindex_status(env_t *env,
        std::set<std::string> sindex);
    MUST_USE bool sync(env_t *env, const rcheckable_t *parent);

    counted_t<const db_t> db;
    const std::string name;
    std::string display_name() {
        return db->name + "." + name;
    }

    uuid_u get_uuid() const { return uuid; }
private:
    friend class distinct_term_t;

    template<class T>
    counted_t<const datum_t> do_batched_write(
        env_t *env, T &&t, durability_requirement_t durability_requirement);

    counted_t<const datum_t> batched_insert_with_keys(
        env_t *env,
        const std::vector<store_key_t> &keys,
        const std::vector<counted_t<const datum_t> > &insert_datums,
        bool upsert,
        durability_requirement_t durability_requirement);

    MUST_USE bool sync_depending_on_durability(
        env_t *env, durability_requirement_t durability_requirement);

    bool use_outdated;
    std::string pkey;
    scoped_ptr_t<rdb_namespace_access_t> access;

    boost::optional<std::string> sindex_id;

    datum_range_t bounds;
    sorting_t sorting;

    // The uuid of the table in the metadata.
    uuid_u uuid;
};

enum function_shortcut_t {
    NO_SHORTCUT = 0,
    CONSTANT_SHORTCUT = 1,
    GET_FIELD_SHORTCUT = 2,
    PLUCK_SHORTCUT = 3
};

// A value is anything RQL can pass around -- a datum, a sequence, a function, a
// selection, whatever.
class val_t : public single_threaded_countable_t<val_t>, public pb_rcheckable_t {
public:
    // This type is intentionally opaque.  It is almost always an error to
    // compare two `val_t` types rather than testing whether one is convertible
    // to another.
    class type_t {
        friend class val_t;
        friend void run(Query *q, scoped_ptr_t<env_t> *env_ptr,
                        Response *res, stream_cache_t *stream_cache,
                        bool *response_needed_out);
    public:
        enum raw_type_t {
            DB               = 1, // db
            TABLE            = 2, // table
            SELECTION        = 3, // table, sequence
            SEQUENCE         = 4, // sequence
            SINGLE_SELECTION = 5, // table, datum (object)
            DATUM            = 6, // datum
            FUNC             = 7, // func
            GROUPED_DATA     = 8  // grouped_data
        };
        type_t(raw_type_t _raw_type); // NOLINT
        bool is_convertible(type_t rhs) const;

        raw_type_t get_raw_type() const { return raw_type; }
        const char *name() const;

    private:
        friend class coerce_term_t;
        friend class typeof_term_t;
        friend int val_type(counted_t<val_t> v);
        raw_type_t raw_type;
    };
    type_t get_type() const;
    const char *get_type_name() const;

    val_t(counted_t<const datum_t> _datum, protob_t<const Backtrace> backtrace);
    val_t(const counted_t<grouped_data_t> &groups,
          protob_t<const Backtrace> bt);
    val_t(counted_t<const datum_t> _datum, counted_t<table_t> _table,
          protob_t<const Backtrace> backtrace);
    val_t(counted_t<const datum_t> _datum,
          counted_t<const datum_t> _orig_key,
          counted_t<table_t> _table,
          protob_t<const Backtrace> backtrace);
    val_t(env_t *env, counted_t<datum_stream_t> _sequence,
          protob_t<const Backtrace> backtrace);
    val_t(counted_t<table_t> _table, protob_t<const Backtrace> backtrace);
    val_t(counted_t<table_t> _table, counted_t<datum_stream_t> _sequence,
          protob_t<const Backtrace> backtrace);
    val_t(counted_t<const db_t> _db, protob_t<const Backtrace> backtrace);
    val_t(counted_t<func_t> _func, protob_t<const Backtrace> backtrace);
    ~val_t();

    counted_t<const db_t> as_db() const;
    counted_t<table_t> as_table();
    std::pair<counted_t<table_t> , counted_t<datum_stream_t> > as_selection(env_t *env);
    counted_t<datum_stream_t> as_seq(env_t *env);
    std::pair<counted_t<table_t> , counted_t<const datum_t> > as_single_selection();
    // See func.hpp for an explanation of shortcut functions.
    counted_t<func_t> as_func(function_shortcut_t shortcut = NO_SHORTCUT);

    // This set of interfaces is atrocious.  Basically there are some places
    // where we want grouped_data, some places where we maybe want grouped_data,
    // and some places where we maybe want grouped data even if we have to
    // coerce to grouped data from a grouped stream.  (We can't use the usual
    // `is_convertible` interface because the type information is actually a
    // property of the stream, because I'm a terrible programmer.)
    counted_t<grouped_data_t> as_grouped_data();
    counted_t<grouped_data_t> as_promiscuous_grouped_data(env_t *env);
    counted_t<grouped_data_t> maybe_as_grouped_data();
    counted_t<grouped_data_t> maybe_as_promiscuous_grouped_data(env_t *env);

    counted_t<const datum_t> as_datum() const; // prefer the 4 below
    counted_t<const datum_t> as_ptype(const std::string s = "");
    bool as_bool();
    double as_num();
    template<class T>
    T as_int() {
        int64_t i = as_int();
        T t = static_cast<T>(i);
        rcheck(static_cast<int64_t>(t) == i,
               base_exc_t::GENERIC,
               strprintf("Integer too large: %" PRIi64, i));
        return t;
    }
    int64_t as_int();
    const wire_string_t &as_str();

    std::string print() const;
    std::string trunc_print() const;

    counted_t<const datum_t> get_orig_key() const;

private:
    friend int val_type(counted_t<val_t> v); // type_manip version
    void rcheck_literal_type(type_t::raw_type_t expected_raw_type) const;

    type_t type;
    counted_t<table_t> table;
    counted_t<const datum_t> orig_key;

    // We pretend that this variant is a union -- as if it doesn't have type
    // information.  The sequence, datum, func, and db_ptr functions get the
    // fields of the variant.
    boost::variant<counted_t<const db_t>,
                   counted_t<datum_stream_t>,
                   counted_t<const datum_t>,
                   counted_t<func_t>,
                   counted_t<grouped_data_t> > u;

    const counted_t<const db_t> &db() const {
        return boost::get<counted_t<const db_t> >(u);
    }
    counted_t<datum_stream_t> &sequence() {
        return boost::get<counted_t<datum_stream_t> >(u);
    }
    counted_t<const datum_t> &datum() {
        return boost::get<counted_t<const datum_t> >(u);
    }
    const counted_t<const datum_t> &datum() const {
        return boost::get<counted_t<const datum_t> >(u);
    }
    counted_t<func_t> &func() { return boost::get<counted_t<func_t> >(u); }

    DISABLE_COPYING(val_t);
};

}  // namespace ql

#endif // RDB_PROTOCOL_VAL_HPP_
<commit_msg>Removed some stupid whitespace.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_VAL_HPP_
#define RDB_PROTOCOL_VAL_HPP_

#include <set>
#include <string>
#include <utility>
#include <vector>

#include "containers/counted.hpp"
#include "containers/wire_string.hpp"
#include "rdb_protocol/datum_stream.hpp"
#include "rdb_protocol/ql2.pb.h"

namespace ql {
class datum_t;
class rdb_namespace_access_t;
class env_t;
template <class> class protob_t;
class scope_env_t;
class stream_cache_t;
class term_t;
class val_t;

class db_t : public single_threaded_countable_t<db_t> {
public:
    db_t(uuid_u _id, const std::string &_name) : id(_id), name(_name) { }
    const uuid_u id;
    const std::string name;
};

class table_t : public single_threaded_countable_t<table_t>, public pb_rcheckable_t {
public:
    table_t(env_t *env,
            counted_t<const db_t> db, const std::string &name,
            bool use_outdated, const protob_t<const Backtrace> &src);
    counted_t<datum_stream_t> as_datum_stream(env_t *env,
                                              const protob_t<const Backtrace> &bt);
    const std::string &get_pkey();
    counted_t<const datum_t> get_row(env_t *env, counted_t<const datum_t> pval);
    counted_t<datum_stream_t> get_all(
            env_t *env,
            counted_t<const datum_t> value,
            const std::string &sindex_id,
            const protob_t<const Backtrace> &bt);
    void add_sorting(
        const std::string &sindex_id, sorting_t sorting,
        const rcheckable_t *parent);
    void add_bounds(datum_range_t &&new_bounds,
                    const std::string &new_sindex_id,
                    const rcheckable_t *parent);

    counted_t<const datum_t> make_error_datum(const base_exc_t &exception);

    counted_t<const datum_t> batched_replace(
        env_t *env,
        const std::vector<counted_t<const datum_t> > &vals,
        const std::vector<counted_t<const datum_t> > &keys,
        counted_t<func_t> replacement_generator,
        bool nondeterministic_replacements_ok,
        durability_requirement_t durability_requirement,
        bool return_vals);

    counted_t<const datum_t> batched_insert(
        env_t *env,
        std::vector<counted_t<const datum_t> > &&insert_datums,
        bool upsert,
        durability_requirement_t durability_requirement,
        bool return_vals);

    MUST_USE bool sindex_create(
        env_t *env, const std::string &name,
        counted_t<func_t> index_func, sindex_multi_bool_t multi);
    MUST_USE bool sindex_drop(env_t *env, const std::string &name);
    counted_t<const datum_t> sindex_list(env_t *env);
    counted_t<const datum_t> sindex_status(env_t *env,
        std::set<std::string> sindex);
    MUST_USE bool sync(env_t *env, const rcheckable_t *parent);

    counted_t<const db_t> db;
    const std::string name;
    std::string display_name() {
        return db->name + "." + name;
    }

    uuid_u get_uuid() const { return uuid; }
private:
    friend class distinct_term_t;

    template<class T>
    counted_t<const datum_t> do_batched_write(
        env_t *env, T &&t, durability_requirement_t durability_requirement);

    counted_t<const datum_t> batched_insert_with_keys(
        env_t *env,
        const std::vector<store_key_t> &keys,
        const std::vector<counted_t<const datum_t> > &insert_datums,
        bool upsert,
        durability_requirement_t durability_requirement);

    MUST_USE bool sync_depending_on_durability(
        env_t *env, durability_requirement_t durability_requirement);

    bool use_outdated;
    std::string pkey;
    scoped_ptr_t<rdb_namespace_access_t> access;

    boost::optional<std::string> sindex_id;

    datum_range_t bounds;
    sorting_t sorting;

    // The uuid of the table in the metadata.
    uuid_u uuid;
};

enum function_shortcut_t {
    NO_SHORTCUT = 0,
    CONSTANT_SHORTCUT = 1,
    GET_FIELD_SHORTCUT = 2,
    PLUCK_SHORTCUT = 3
};

// A value is anything RQL can pass around -- a datum, a sequence, a function, a
// selection, whatever.
class val_t : public single_threaded_countable_t<val_t>, public pb_rcheckable_t {
public:
    // This type is intentionally opaque.  It is almost always an error to
    // compare two `val_t` types rather than testing whether one is convertible
    // to another.
    class type_t {
        friend class val_t;
        friend void run(Query *q, scoped_ptr_t<env_t> *env_ptr,
                        Response *res, stream_cache_t *stream_cache,
                        bool *response_needed_out);
    public:
        enum raw_type_t {
            DB               = 1, // db
            TABLE            = 2, // table
            SELECTION        = 3, // table, sequence
            SEQUENCE         = 4, // sequence
            SINGLE_SELECTION = 5, // table, datum (object)
            DATUM            = 6, // datum
            FUNC             = 7, // func
            GROUPED_DATA     = 8  // grouped_data
        };
        type_t(raw_type_t _raw_type); // NOLINT
        bool is_convertible(type_t rhs) const;

        raw_type_t get_raw_type() const { return raw_type; }
        const char *name() const;

    private:
        friend class coerce_term_t;
        friend class typeof_term_t;
        friend int val_type(counted_t<val_t> v);
        raw_type_t raw_type;
    };
    type_t get_type() const;
    const char *get_type_name() const;

    val_t(counted_t<const datum_t> _datum, protob_t<const Backtrace> backtrace);
    val_t(const counted_t<grouped_data_t> &groups,
          protob_t<const Backtrace> bt);
    val_t(counted_t<const datum_t> _datum, counted_t<table_t> _table,
          protob_t<const Backtrace> backtrace);
    val_t(counted_t<const datum_t> _datum,
          counted_t<const datum_t> _orig_key,
          counted_t<table_t> _table,
          protob_t<const Backtrace> backtrace);
    val_t(env_t *env, counted_t<datum_stream_t> _sequence,
          protob_t<const Backtrace> backtrace);
    val_t(counted_t<table_t> _table, protob_t<const Backtrace> backtrace);
    val_t(counted_t<table_t> _table, counted_t<datum_stream_t> _sequence,
          protob_t<const Backtrace> backtrace);
    val_t(counted_t<const db_t> _db, protob_t<const Backtrace> backtrace);
    val_t(counted_t<func_t> _func, protob_t<const Backtrace> backtrace);
    ~val_t();

    counted_t<const db_t> as_db() const;
    counted_t<table_t> as_table();
    std::pair<counted_t<table_t>, counted_t<datum_stream_t> > as_selection(env_t *env);
    counted_t<datum_stream_t> as_seq(env_t *env);
    std::pair<counted_t<table_t>, counted_t<const datum_t> > as_single_selection();
    // See func.hpp for an explanation of shortcut functions.
    counted_t<func_t> as_func(function_shortcut_t shortcut = NO_SHORTCUT);

    // This set of interfaces is atrocious.  Basically there are some places
    // where we want grouped_data, some places where we maybe want grouped_data,
    // and some places where we maybe want grouped data even if we have to
    // coerce to grouped data from a grouped stream.  (We can't use the usual
    // `is_convertible` interface because the type information is actually a
    // property of the stream, because I'm a terrible programmer.)
    counted_t<grouped_data_t> as_grouped_data();
    counted_t<grouped_data_t> as_promiscuous_grouped_data(env_t *env);
    counted_t<grouped_data_t> maybe_as_grouped_data();
    counted_t<grouped_data_t> maybe_as_promiscuous_grouped_data(env_t *env);

    counted_t<const datum_t> as_datum() const; // prefer the 4 below
    counted_t<const datum_t> as_ptype(const std::string s = "");
    bool as_bool();
    double as_num();
    template<class T>
    T as_int() {
        int64_t i = as_int();
        T t = static_cast<T>(i);
        rcheck(static_cast<int64_t>(t) == i,
               base_exc_t::GENERIC,
               strprintf("Integer too large: %" PRIi64, i));
        return t;
    }
    int64_t as_int();
    const wire_string_t &as_str();

    std::string print() const;
    std::string trunc_print() const;

    counted_t<const datum_t> get_orig_key() const;

private:
    friend int val_type(counted_t<val_t> v); // type_manip version
    void rcheck_literal_type(type_t::raw_type_t expected_raw_type) const;

    type_t type;
    counted_t<table_t> table;
    counted_t<const datum_t> orig_key;

    // We pretend that this variant is a union -- as if it doesn't have type
    // information.  The sequence, datum, func, and db_ptr functions get the
    // fields of the variant.
    boost::variant<counted_t<const db_t>,
                   counted_t<datum_stream_t>,
                   counted_t<const datum_t>,
                   counted_t<func_t>,
                   counted_t<grouped_data_t> > u;

    const counted_t<const db_t> &db() const {
        return boost::get<counted_t<const db_t> >(u);
    }
    counted_t<datum_stream_t> &sequence() {
        return boost::get<counted_t<datum_stream_t> >(u);
    }
    counted_t<const datum_t> &datum() {
        return boost::get<counted_t<const datum_t> >(u);
    }
    const counted_t<const datum_t> &datum() const {
        return boost::get<counted_t<const datum_t> >(u);
    }
    counted_t<func_t> &func() { return boost::get<counted_t<func_t> >(u); }

    DISABLE_COPYING(val_t);
};

}  // namespace ql

#endif // RDB_PROTOCOL_VAL_HPP_
<|endoftext|>


<commit_before>#include "audio.hpp"

#include "etl_audio.hpp"

using namespace std;
using namespace nervana;

bool audio::config::set_config(nlohmann::json js) {
    // TODO
}

shared_ptr<audio::params> audio::param_factory::make_params(std::shared_ptr<const decoded>) {
    auto params = shared_ptr<audio::params>(new audio::params());

    params->_width = _cfg->_width;
    params->_height = _cfg->_height;

    return params;
}

audio::decoded::decoded(shared_ptr<RawMedia> raw)
    : _raw(raw) {
}

MediaType audio::decoded::get_type() {
    return MediaType::AUDIO;
}

size_t audio::decoded::getSize() {
    return _raw->numSamples();
}

audio::extractor::extractor(std::shared_ptr<const audio::config> config) {
    // TODO: this MediaParams is never freed
    _codec = new Codec(config);
    avcodec_register_all();
}

audio::extractor::~extractor() {
    delete _codec;
}

std::shared_ptr<audio::decoded> audio::extractor::extract(const char* item, int itemSize) {
    return make_shared<audio::decoded>(_codec->decode(item, itemSize));
}

audio::transformer::transformer(std::shared_ptr<const audio::config> config)
    : _noiseClips(0) {
    // TODO: this MediaParams is never freed
    _codec = new Codec(config);
    _specgram = new Specgram(config, config->_randomSeed);

    if (config->_noiseIndexFile != 0) {
        _noiseClips = new NoiseClips(
            config->_noiseIndexFile, config->_noiseDir, _codec
        );
    }
}

audio::transformer::~transformer() {
    delete _specgram;
    delete _codec;
}

std::shared_ptr<audio::decoded> audio::transformer::transform(
      std::shared_ptr<audio::params> params,
      std::shared_ptr<audio::decoded> decoded) {
    if (_noiseClips != 0) {
        _noiseClips->addNoise(decoded->_raw, _rng);
    }

    // set up _buf in decoded to accept data from generate
    decoded->_buf.resize(params->_width * params->_height);

    // convert from time domain to frequency domain
    int len = _specgram->generate(
        decoded->_raw, decoded->_buf.data(), params->_width * params->_height
    );

    // TODO: in private-neon the length of the uterance is used
    // later on down the road somewhere.  Still need to figure out
    // how to pass this through ...

    // if (meta != 0) {
    //     *meta = len;
    // }

    return decoded;
}
<commit_msg>remove completed TODOs<commit_after>#include "audio.hpp"

#include "etl_audio.hpp"

using namespace std;
using namespace nervana;

bool audio::config::set_config(nlohmann::json js) {
    // TODO
}

shared_ptr<audio::params> audio::param_factory::make_params(std::shared_ptr<const decoded>) {
    auto params = shared_ptr<audio::params>(new audio::params());

    params->_width = _cfg->_width;
    params->_height = _cfg->_height;

    return params;
}

audio::decoded::decoded(shared_ptr<RawMedia> raw)
    : _raw(raw) {
}

MediaType audio::decoded::get_type() {
    return MediaType::AUDIO;
}

size_t audio::decoded::getSize() {
    return _raw->numSamples();
}

audio::extractor::extractor(std::shared_ptr<const audio::config> config) {
    _codec = new Codec(config);
    avcodec_register_all();
}

audio::extractor::~extractor() {
    delete _codec;
}

std::shared_ptr<audio::decoded> audio::extractor::extract(const char* item, int itemSize) {
    return make_shared<audio::decoded>(_codec->decode(item, itemSize));
}

audio::transformer::transformer(std::shared_ptr<const audio::config> config)
    : _noiseClips(0) {
    _codec = new Codec(config);
    _specgram = new Specgram(config, config->_randomSeed);

    if (config->_noiseIndexFile != 0) {
        _noiseClips = new NoiseClips(
            config->_noiseIndexFile, config->_noiseDir, _codec
        );
    }
}

audio::transformer::~transformer() {
    delete _specgram;
    delete _codec;
}

std::shared_ptr<audio::decoded> audio::transformer::transform(
      std::shared_ptr<audio::params> params,
      std::shared_ptr<audio::decoded> decoded) {
    if (_noiseClips != 0) {
        _noiseClips->addNoise(decoded->_raw, _rng);
    }

    // set up _buf in decoded to accept data from generate
    decoded->_buf.resize(params->_width * params->_height);

    // convert from time domain to frequency domain
    int len = _specgram->generate(
        decoded->_raw, decoded->_buf.data(), params->_width * params->_height
    );

    // TODO: in private-neon the length of the uterance is used
    // later on down the road somewhere.  Still need to figure out
    // how to pass this through ...

    // if (meta != 0) {
    //     *meta = len;
    // }

    return decoded;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLTextListAutoStylePool.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 15:22:04 $
 *
 *  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 _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _CNTRSRT_HXX
#include <svtools/cntnrsrt.hxx>
#endif

#ifndef _COM_SUN_STAR_UCB_XANYCOMPAREFACTORY_HPP_
#include <com/sun/star/ucb/XAnyCompareFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_
#include <com/sun/star/container/XIndexReplace.hpp>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _XMLOFF_XMLNUME_HXX
#include "xmlnume.hxx"
#endif
#ifndef _XMLOFF_XMLTEXTLISTAUTOSTYLEPOOL_HXX
#include "XMLTextListAutoStylePool.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::style;

int XMLTextListAutoStylePoolNameCmp_Impl( const OUString& r1,
                                           const OUString& r2 )
{
    return (int)r1.compareTo( r2 );
}

DECLARE_CONTAINER_SORT_DEL( XMLTextListAutoStylePoolNames_Impl,
                            OUString )
IMPL_CONTAINER_SORT( XMLTextListAutoStylePoolNames_Impl,
                     OUString,
                     XMLTextListAutoStylePoolNameCmp_Impl )

class XMLTextListAutoStylePoolEntry_Impl
{
    OUString    sName;
    OUString    sInternalName;
    Reference < XIndexReplace > xNumRules;
    sal_uInt32  nPos;
    sal_Bool    bIsNamed;

public:

    XMLTextListAutoStylePoolEntry_Impl(
            sal_uInt32 nPos,
            const Reference < XIndexReplace > & rNumRules,
            XMLTextListAutoStylePoolNames_Impl& rNames,
            const OUString& rPrefix,
            sal_uInt32& rName );

    XMLTextListAutoStylePoolEntry_Impl(
            const Reference < XIndexReplace > & rNumRules ) :
        nPos( 0 ),
        xNumRules( rNumRules ),
        bIsNamed( sal_False )
    {
        Reference < XNamed > xNamed( xNumRules, UNO_QUERY );
        if( xNamed.is() )
        {
            sInternalName = xNamed->getName();
            bIsNamed = sal_True;
        }
    }

    XMLTextListAutoStylePoolEntry_Impl(
            const OUString& rInternalName ) :
        nPos( 0 ),
        sInternalName( rInternalName ),
        bIsNamed( sal_True )
    {
    }

    const OUString& GetName() const { return sName; }
    const OUString& GetInternalName() const { return sInternalName; }
    const Reference < XIndexReplace > & GetNumRules() const { return xNumRules; }
    sal_uInt32 GetPos() const { return nPos; }
    sal_Bool IsNamed() const { return bIsNamed; }
};

XMLTextListAutoStylePoolEntry_Impl::XMLTextListAutoStylePoolEntry_Impl(
        sal_uInt32 nP,
        const Reference < XIndexReplace > & rNumRules,
        XMLTextListAutoStylePoolNames_Impl& rNames,
        const OUString& rPrefix,
        sal_uInt32& rName ) :
    nPos( nP ),
    xNumRules( rNumRules ),
    bIsNamed( sal_False )
{
    Reference < XNamed > xNamed( xNumRules, UNO_QUERY );
    if( xNamed.is() )
    {
        sInternalName = xNamed->getName();
        bIsNamed = sal_True;
    }

    // create a name that hasn't been used before. The created name has not
    // to be added to the array, because it will never tried again
    OUStringBuffer sBuffer( 7 );
    do
    {
        rName++;
        sBuffer.append( rPrefix );
        sBuffer.append( (sal_Int32)rName );
        sName = sBuffer.makeStringAndClear();
    }
    while( rNames.Seek_Entry( &sName, 0 ) );
}

int XMLTextListAutoStylePoolEntryCmp_Impl(
        const XMLTextListAutoStylePoolEntry_Impl& r1,
        const XMLTextListAutoStylePoolEntry_Impl& r2 )
{
    int nRet;
    if( r1.IsNamed() )
    {
        if( r2.IsNamed() )
             nRet = (int)r1.GetInternalName().compareTo( r2.GetInternalName());
        else
            nRet = -1;
    }
    else
    {
        if( r2.IsNamed() )
            nRet = 1;
        else
             nRet = (int)(r1.GetNumRules().get() - r2.GetNumRules().get());
    }

    return nRet;
}

typedef XMLTextListAutoStylePoolEntry_Impl *XMLTextListAutoStylePoolEntryPtr;
DECLARE_CONTAINER_SORT( XMLTextListAutoStylePool_Impl,
                        XMLTextListAutoStylePoolEntry_Impl )
IMPL_CONTAINER_SORT( XMLTextListAutoStylePool_Impl,
                     XMLTextListAutoStylePoolEntry_Impl,
                     XMLTextListAutoStylePoolEntryCmp_Impl )

XMLTextListAutoStylePool::XMLTextListAutoStylePool( SvXMLExport& rExp ) :
    rExport( rExp ),
    pPool( new XMLTextListAutoStylePool_Impl( 5, 5 ) ),
    pNames( new XMLTextListAutoStylePoolNames_Impl( 5, 5 ) ),
    nName( 0 ),
    sPrefix( RTL_CONSTASCII_USTRINGPARAM("L") )
{
    Reference<ucb::XAnyCompareFactory> xCompareFac( rExp.GetModel(), uno::UNO_QUERY );
    if( xCompareFac.is() )
        mxNumRuleCompare = xCompareFac->createAnyCompareByName( OUString( RTL_CONSTASCII_USTRINGPARAM( "NumberingRules" ) ) );
}

XMLTextListAutoStylePool::~XMLTextListAutoStylePool()
{
    delete pPool;
    delete pNames;
}

void XMLTextListAutoStylePool::RegisterName( const OUString& rName )
{
    OUString *pName = new OUString( rName );
    if( !pNames->Insert( pName ) )
        delete pName;
}

sal_Bool XMLTextListAutoStylePool::HasName( const OUString& rName ) const
{
    return pNames->Seek_Entry( &rName, 0 );
}

sal_uInt32 XMLTextListAutoStylePool::Find( XMLTextListAutoStylePoolEntry_Impl* pEntry ) const
{
    sal_uInt32 nPos;
    if( !pEntry->IsNamed() && mxNumRuleCompare.is() )
    {
        const sal_uInt32 nCount = pPool->Count();

        uno::Any aAny1, aAny2;
        aAny1 <<= pEntry->GetNumRules();

        for( nPos = 0; nPos < nCount; nPos++ )
        {
            aAny2 <<= pPool->GetObject(nPos)->GetNumRules();

            if( mxNumRuleCompare->compare( aAny1, aAny2 ) == 0 )
                return nPos;
        }
    }
    else if( pPool->Seek_Entry( pEntry, &nPos ) )
    {
        return nPos;
    }

    return (sal_uInt32)-1;
}

OUString XMLTextListAutoStylePool::Add(
            const Reference < XIndexReplace > & rNumRules )
{
    OUString sName;
    XMLTextListAutoStylePoolEntry_Impl aTmp( rNumRules );

    sal_uInt32 nPos = Find( &aTmp );
    if( nPos != (sal_uInt32)-1 )
    {
        sName = pPool->GetObject( nPos )->GetName();
    }
    else
    {
        XMLTextListAutoStylePoolEntry_Impl *pEntry =
            new XMLTextListAutoStylePoolEntry_Impl( pPool->Count(),
                                               rNumRules, *pNames, sPrefix,
                                               nName );
        pPool->Insert( pEntry );
        sName = pEntry->GetName();
    }

    return sName;
}

::rtl::OUString XMLTextListAutoStylePool::Find(
            const Reference < XIndexReplace > & rNumRules ) const
{
    OUString sName;
    XMLTextListAutoStylePoolEntry_Impl aTmp( rNumRules );

    sal_uInt32 nPos = Find( &aTmp );
    if( nPos != (sal_uInt32)-1 )
        sName = pPool->GetObject( nPos )->GetName();

    return sName;
}

::rtl::OUString XMLTextListAutoStylePool::Find(
            const OUString& rInternalName ) const
{
    OUString sName;
    XMLTextListAutoStylePoolEntry_Impl aTmp( rInternalName );
    sal_uInt32 nPos = Find( &aTmp );
    if( nPos != (sal_uInt32)-1 )
        sName = pPool->GetObject( nPos )->GetName();

    return sName;
}

void XMLTextListAutoStylePool::exportXML() const
{
    sal_uInt32 nCount = pPool->Count();
    if( !nCount )
        return;

    XMLTextListAutoStylePoolEntry_Impl **aExpEntries =
        new XMLTextListAutoStylePoolEntryPtr[nCount];

    sal_uInt32 i;
    for( i=0; i < nCount; i++ )
    {
        aExpEntries[i] = 0;
    }
    for( i=0; i < nCount; i++ )
    {
        XMLTextListAutoStylePoolEntry_Impl *pEntry = pPool->GetObject(i);
        DBG_ASSERT( pEntry->GetPos() < nCount, "Illegal pos" );
        aExpEntries[pEntry->GetPos()] = pEntry;
    }

    SvxXMLNumRuleExport aNumRuleExp( rExport );

    for( i=0; i < nCount; i++ )
    {
        XMLTextListAutoStylePoolEntry_Impl *pEntry = aExpEntries[i];
        aNumRuleExp.exportNumberingRule( pEntry->GetName(),
                                         pEntry->GetNumRules() );
    }
    delete [] aExpEntries;
}

<commit_msg>INTEGRATION: CWS sixtyfour02 (1.5.78); FILE MERGED 2006/02/21 12:28:06 cmc 1.5.78.1: #i62331# match IMPL_CONTAINER_SORT argument of ULONG<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLTextListAutoStylePool.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2006-03-16 12:20:55 $
 *
 *  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 _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _CNTRSRT_HXX
#include <svtools/cntnrsrt.hxx>
#endif

#ifndef _COM_SUN_STAR_UCB_XANYCOMPAREFACTORY_HPP_
#include <com/sun/star/ucb/XAnyCompareFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_
#include <com/sun/star/container/XIndexReplace.hpp>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _XMLOFF_XMLNUME_HXX
#include "xmlnume.hxx"
#endif
#ifndef _XMLOFF_XMLTEXTLISTAUTOSTYLEPOOL_HXX
#include "XMLTextListAutoStylePool.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::style;

int XMLTextListAutoStylePoolNameCmp_Impl( const OUString& r1,
                                           const OUString& r2 )
{
    return (int)r1.compareTo( r2 );
}

DECLARE_CONTAINER_SORT_DEL( XMLTextListAutoStylePoolNames_Impl,
                            OUString )
IMPL_CONTAINER_SORT( XMLTextListAutoStylePoolNames_Impl,
                     OUString,
                     XMLTextListAutoStylePoolNameCmp_Impl )

class XMLTextListAutoStylePoolEntry_Impl
{
    OUString    sName;
    OUString    sInternalName;
    Reference < XIndexReplace > xNumRules;
    sal_uInt32  nPos;
    sal_Bool    bIsNamed;

public:

    XMLTextListAutoStylePoolEntry_Impl(
            sal_uInt32 nPos,
            const Reference < XIndexReplace > & rNumRules,
            XMLTextListAutoStylePoolNames_Impl& rNames,
            const OUString& rPrefix,
            sal_uInt32& rName );

    XMLTextListAutoStylePoolEntry_Impl(
            const Reference < XIndexReplace > & rNumRules ) :
        nPos( 0 ),
        xNumRules( rNumRules ),
        bIsNamed( sal_False )
    {
        Reference < XNamed > xNamed( xNumRules, UNO_QUERY );
        if( xNamed.is() )
        {
            sInternalName = xNamed->getName();
            bIsNamed = sal_True;
        }
    }

    XMLTextListAutoStylePoolEntry_Impl(
            const OUString& rInternalName ) :
        nPos( 0 ),
        sInternalName( rInternalName ),
        bIsNamed( sal_True )
    {
    }

    const OUString& GetName() const { return sName; }
    const OUString& GetInternalName() const { return sInternalName; }
    const Reference < XIndexReplace > & GetNumRules() const { return xNumRules; }
    sal_uInt32 GetPos() const { return nPos; }
    sal_Bool IsNamed() const { return bIsNamed; }
};

XMLTextListAutoStylePoolEntry_Impl::XMLTextListAutoStylePoolEntry_Impl(
        sal_uInt32 nP,
        const Reference < XIndexReplace > & rNumRules,
        XMLTextListAutoStylePoolNames_Impl& rNames,
        const OUString& rPrefix,
        sal_uInt32& rName ) :
    nPos( nP ),
    xNumRules( rNumRules ),
    bIsNamed( sal_False )
{
    Reference < XNamed > xNamed( xNumRules, UNO_QUERY );
    if( xNamed.is() )
    {
        sInternalName = xNamed->getName();
        bIsNamed = sal_True;
    }

    // create a name that hasn't been used before. The created name has not
    // to be added to the array, because it will never tried again
    OUStringBuffer sBuffer( 7 );
    do
    {
        rName++;
        sBuffer.append( rPrefix );
        sBuffer.append( (sal_Int32)rName );
        sName = sBuffer.makeStringAndClear();
    }
    while( rNames.Seek_Entry( &sName, 0 ) );
}

int XMLTextListAutoStylePoolEntryCmp_Impl(
        const XMLTextListAutoStylePoolEntry_Impl& r1,
        const XMLTextListAutoStylePoolEntry_Impl& r2 )
{
    int nRet;
    if( r1.IsNamed() )
    {
        if( r2.IsNamed() )
             nRet = (int)r1.GetInternalName().compareTo( r2.GetInternalName());
        else
            nRet = -1;
    }
    else
    {
        if( r2.IsNamed() )
            nRet = 1;
        else
             nRet = (int)(r1.GetNumRules().get() - r2.GetNumRules().get());
    }

    return nRet;
}

typedef XMLTextListAutoStylePoolEntry_Impl *XMLTextListAutoStylePoolEntryPtr;
DECLARE_CONTAINER_SORT( XMLTextListAutoStylePool_Impl,
                        XMLTextListAutoStylePoolEntry_Impl )
IMPL_CONTAINER_SORT( XMLTextListAutoStylePool_Impl,
                     XMLTextListAutoStylePoolEntry_Impl,
                     XMLTextListAutoStylePoolEntryCmp_Impl )

XMLTextListAutoStylePool::XMLTextListAutoStylePool( SvXMLExport& rExp ) :
    rExport( rExp ),
    pPool( new XMLTextListAutoStylePool_Impl( 5, 5 ) ),
    pNames( new XMLTextListAutoStylePoolNames_Impl( 5, 5 ) ),
    nName( 0 ),
    sPrefix( RTL_CONSTASCII_USTRINGPARAM("L") )
{
    Reference<ucb::XAnyCompareFactory> xCompareFac( rExp.GetModel(), uno::UNO_QUERY );
    if( xCompareFac.is() )
        mxNumRuleCompare = xCompareFac->createAnyCompareByName( OUString( RTL_CONSTASCII_USTRINGPARAM( "NumberingRules" ) ) );
}

XMLTextListAutoStylePool::~XMLTextListAutoStylePool()
{
    delete pPool;
    delete pNames;
}

void XMLTextListAutoStylePool::RegisterName( const OUString& rName )
{
    OUString *pName = new OUString( rName );
    if( !pNames->Insert( pName ) )
        delete pName;
}

sal_Bool XMLTextListAutoStylePool::HasName( const OUString& rName ) const
{
    return pNames->Seek_Entry( &rName, 0 );
}

sal_uInt32 XMLTextListAutoStylePool::Find( XMLTextListAutoStylePoolEntry_Impl* pEntry ) const
{
    ULONG nPos;
    if( !pEntry->IsNamed() && mxNumRuleCompare.is() )
    {
        const sal_uInt32 nCount = pPool->Count();

        uno::Any aAny1, aAny2;
        aAny1 <<= pEntry->GetNumRules();

        for( nPos = 0; nPos < nCount; nPos++ )
        {
            aAny2 <<= pPool->GetObject(nPos)->GetNumRules();

            if( mxNumRuleCompare->compare( aAny1, aAny2 ) == 0 )
                return nPos;
        }
    }
    else if( pPool->Seek_Entry( pEntry, &nPos ) )
    {
        return nPos;
    }

    return (sal_uInt32)-1;
}

OUString XMLTextListAutoStylePool::Add(
            const Reference < XIndexReplace > & rNumRules )
{
    OUString sName;
    XMLTextListAutoStylePoolEntry_Impl aTmp( rNumRules );

    sal_uInt32 nPos = Find( &aTmp );
    if( nPos != (sal_uInt32)-1 )
    {
        sName = pPool->GetObject( nPos )->GetName();
    }
    else
    {
        XMLTextListAutoStylePoolEntry_Impl *pEntry =
            new XMLTextListAutoStylePoolEntry_Impl( pPool->Count(),
                                               rNumRules, *pNames, sPrefix,
                                               nName );
        pPool->Insert( pEntry );
        sName = pEntry->GetName();
    }

    return sName;
}

::rtl::OUString XMLTextListAutoStylePool::Find(
            const Reference < XIndexReplace > & rNumRules ) const
{
    OUString sName;
    XMLTextListAutoStylePoolEntry_Impl aTmp( rNumRules );

    sal_uInt32 nPos = Find( &aTmp );
    if( nPos != (sal_uInt32)-1 )
        sName = pPool->GetObject( nPos )->GetName();

    return sName;
}

::rtl::OUString XMLTextListAutoStylePool::Find(
            const OUString& rInternalName ) const
{
    OUString sName;
    XMLTextListAutoStylePoolEntry_Impl aTmp( rInternalName );
    sal_uInt32 nPos = Find( &aTmp );
    if( nPos != (sal_uInt32)-1 )
        sName = pPool->GetObject( nPos )->GetName();

    return sName;
}

void XMLTextListAutoStylePool::exportXML() const
{
    sal_uInt32 nCount = pPool->Count();
    if( !nCount )
        return;

    XMLTextListAutoStylePoolEntry_Impl **aExpEntries =
        new XMLTextListAutoStylePoolEntryPtr[nCount];

    sal_uInt32 i;
    for( i=0; i < nCount; i++ )
    {
        aExpEntries[i] = 0;
    }
    for( i=0; i < nCount; i++ )
    {
        XMLTextListAutoStylePoolEntry_Impl *pEntry = pPool->GetObject(i);
        DBG_ASSERT( pEntry->GetPos() < nCount, "Illegal pos" );
        aExpEntries[pEntry->GetPos()] = pEntry;
    }

    SvxXMLNumRuleExport aNumRuleExp( rExport );

    for( i=0; i < nCount; i++ )
    {
        XMLTextListAutoStylePoolEntry_Impl *pEntry = aExpEntries[i];
        aNumRuleExp.exportNumberingRule( pEntry->GetName(),
                                         pEntry->GetNumRules() );
    }
    delete [] aExpEntries;
}

<|endoftext|>


<commit_before>#include "mini_ion.h"

namespace Halide { namespace Runtime { namespace Internal { namespace Ion {

// Allocate an ION buffer, and map it, returning the mapped pointer.
WEAK void *ion_alloc(void *user_context, size_t len, int heap_id, int *out_fd) {
    void *ret = halide_malloc(user_context, len);
    if (ret && out_fd) {
        *out_fd = -1;
    }

    return ret;
}

// Free a previously allocated ION buffer.
WEAK void ion_free(void *user_context, void *ion) {
    halide_free(user_context, ion);
}

}}}}  // namespace Halide::Runtime::Internal::Ion
<commit_msg>fake_ion needs to align to 128-byte boundaries<commit_after>#include "mini_ion.h"

namespace Halide { namespace Runtime { namespace Internal { namespace Ion {

struct allocation_record {
    void *original;
};

// Allocate an ION buffer, and map it, returning the mapped pointer.
WEAK void *ion_alloc(void *user_context, size_t len, int heap_id, int *out_fd) {
    const size_t align = 128;

    // Align the allocation size.
    len = (len + align - 1) & ~(align - 1);

    // Allocate enough space to hold information about the allocation prior to the pointer we return.
    len += align;

    void *original = halide_malloc(user_context, len);

    // Store the original ptr before the pointer we return.
    allocation_record rec = { original };
    void *ret = reinterpret_cast<char *>(original) + align;
    halide_assert(user_context, sizeof(allocation_record) <= align);
    memcpy(reinterpret_cast<allocation_record *>(ret) - 1, &rec, sizeof(rec));

    if (ret && out_fd) {
        *out_fd = -1;
    }
    return ret;
}

// Free a previously allocated ION buffer.
WEAK void ion_free(void *user_context, void *ion) {
    if (!ion) return;
    allocation_record rec = *(reinterpret_cast<allocation_record *>(ion) - 1);
    halide_free(user_context, rec.original);
}

}}}}  // namespace Halide::Runtime::Internal::Ion
<|endoftext|>