<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org

Copyright (c) 2000-2013 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreVolumeGridSource.h"
#include "OgreTextureManager.h"
#include "OgreHardwarePixelBuffer.h"
#include "OgreVector3.h"
#include "OgreColourValue.h"
#include "OgreMemoryAllocatorConfig.h"
#include "OgreLogManager.h"
#include "OgreTimer.h"

namespace Ogre {
namespace Volume {

    Vector3 GridSource::getIntersectionStart(const Ray &ray, Real maxDistance) const
    {
        AxisAlignedBox box((Real)0, (Real)0, (Real)0, (Real)mWidth, (Real)mHeight, (Real)mDepth);

        // Inside the grid
        if (box.intersects(ray.getOrigin()))
        {
            return ray.getOrigin();
        }

        // Outside the grid, ray intersects it
        std::pair<bool, Real> intersection = ray.intersects(box);
        if (intersection.first)
        {
            Vector3 direction = ray.getDirection().normalisedCopy();
            return ray.getOrigin() + direction * intersection.second;
        }

        // Outside the grid, ray doesn't intersect it
        return ray.getOrigin();
    }

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

    Vector3 GridSource::getIntersectionEnd(const Ray &ray, Real maxDistance) const
    {
        AxisAlignedBox box((Real)0, (Real)0, (Real)0, (Real)mWidth, (Real)mHeight, (Real)mDepth);
        Vector3 direction = ray.getDirection().normalisedCopy();
        Vector3 invertedDirection = (Real)-1.0 * direction;
        Vector3 origin = ray.getOrigin() + direction * box.getSize().length();

        Ray inverted(origin, invertedDirection);
        std::pair<bool, Real> intersection = inverted.intersects(box);
        if (intersection.first)
        {
            return origin + invertedDirection * intersection.second;
        }
        return ray.getOrigin() + direction * maxDistance;
    }

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

    GridSource::GridSource(bool trilinearValue, bool trilinearGradient, bool sobelGradient) :
        mTrilinearValue(trilinearValue), mTrilinearGradient(trilinearGradient), mSobelGradient(sobelGradient)
    {
    }

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

    GridSource::~GridSource(void)
    {
    }

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

    Vector4 GridSource::getValueAndGradient(const Vector3 &position) const
    {
        Vector3 scaledPosition(position.x * mPosXScale, position.y * mPosYScale, position.z * mPosZScale);
        Vector3 normal;
        if (mTrilinearGradient)
        {
            size_t x0 = (size_t)scaledPosition.x;
            size_t x1 = (size_t)ceil(scaledPosition.x);
            size_t y0 = (size_t)scaledPosition.y;
            size_t y1 = (size_t)ceil(scaledPosition.y);
            size_t z0 = (size_t)scaledPosition.z;
            size_t z1 = (size_t)ceil(scaledPosition.z);

            Real dX = scaledPosition.x - (Real)x0;
            Real dY = scaledPosition.y - (Real)y0;
            Real dZ = scaledPosition.z - (Real)z0;

            Vector3 f000 = getGradient(x0, y0, z0);
            Vector3 f100 = getGradient(x1, y0, z0);
            Vector3 f010 = getGradient(x0, y1, z0);
            Vector3 f001 = getGradient(x0, y0, z1);
            Vector3 f101 = getGradient(x1, y0, z1);
            Vector3 f011 = getGradient(x0, y1, z1);
            Vector3 f110 = getGradient(x1, y1, z0);
            Vector3 f111 = getGradient(x1, y1, z1);

            Real oneMinX = (Real)1.0 - dX;
            Real oneMinY = (Real)1.0 - dY;
            Real oneMinZ = (Real)1.0 - dZ;
            Real oneMinXoneMinY = oneMinX * oneMinY;
            Real dXOneMinY = dX * oneMinY;

            normal = oneMinZ * (f000 * oneMinXoneMinY
                + f100 * dXOneMinY
                + f010 * oneMinX * dY)
                + dZ * (f001 * oneMinXoneMinY
                + f101 * dXOneMinY
                + f011 * oneMinX * dY)
                + dX * dY * (f110 * oneMinZ
                + f111 * dZ);

            normal *= (Real)-1.0;
        }
        else
        {
            normal = getGradient((size_t)(scaledPosition.x + (Real)0.5), (size_t)(scaledPosition.y + (Real)0.5), (size_t)(scaledPosition.z + (Real)0.5));
            normal *= (Real)-1.0;
        }
        return Vector4(normal.x, normal.y, normal.z, getValue(position));
    }

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

    Real GridSource::getValue(const Vector3 &position) const
    {
        Vector3 scaledPosition(position.x * mPosXScale, position.y * mPosYScale, position.z * mPosZScale);
        Real value;
        if (mTrilinearValue)
        {
            size_t x0 = (size_t)scaledPosition.x;
            size_t x1 = (size_t)ceil(scaledPosition.x);
            size_t y0 = (size_t)scaledPosition.y;
            size_t y1 = (size_t)ceil(scaledPosition.y);
            size_t z0 = (size_t)scaledPosition.z;
            size_t z1 = (size_t)ceil(scaledPosition.z);

            Real dX = scaledPosition.x - (Real)x0;
            Real dY = scaledPosition.y - (Real)y0;
            Real dZ = scaledPosition.z - (Real)z0;

            Real f000 = getVolumeGridValue(x0, y0, z0);
            Real f100 = getVolumeGridValue(x1, y0, z0);
            Real f010 = getVolumeGridValue(x0, y1, z0);
            Real f001 = getVolumeGridValue(x0, y0, z1);
            Real f101 = getVolumeGridValue(x1, y0, z1);
            Real f011 = getVolumeGridValue(x0, y1, z1);
            Real f110 = getVolumeGridValue(x1, y1, z0);
            Real f111 = getVolumeGridValue(x1, y1, z1);

            Real oneMinX = (Real)1.0 - dX;
            Real oneMinY = (Real)1.0 - dY;
            Real oneMinZ = (Real)1.0 - dZ;
            Real oneMinXoneMinY = oneMinX * oneMinY;
            Real dXOneMinY = dX * oneMinY;

            value = oneMinZ * (f000 * oneMinXoneMinY
                + f100 * dXOneMinY
                + f010 * oneMinX * dY)
                + dZ * (f001 * oneMinXoneMinY
                + f101 * dXOneMinY
                + f011 * oneMinX * dY)
                + dX * dY * (f110 * oneMinZ
                + f111 * dZ);

        }
        else
        {
            // Nearest neighbour else
            size_t x = (size_t)(scaledPosition.x + (Real)0.5);
            size_t y = (size_t)(scaledPosition.y + (Real)0.5);
            size_t z = (size_t)(scaledPosition.z + (Real)0.5);
            value = (Real)getVolumeGridValue(x, y, z);
        }
        return value;
    }

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

    size_t GridSource::getWidth(void) const
    {
        return mWidth;
    }

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

    size_t GridSource::getHeight(void) const
    {
        return mHeight;
    }

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

    size_t GridSource::getDepth(void) const
    {
        return mDepth;
    }

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

    void GridSource::combineWithSource(CSGOperationSource *operation, Source *source, const Vector3 &center, Real radius)
    {
        Real worldWidthScale = (Real)1.0 / mPosXScale;
        Real worldHeightScale = (Real)1.0 / mPosYScale;
        Real worldDepthScale = (Real)1.0 / mPosZScale;

        operation->setSourceA(this);
        operation->setSourceB(source);
        // No need for trilineaer interpolation here as we iterate over the
        // cells anyway.
        bool oldTrilinearValue = mTrilinearValue;
        mTrilinearValue = false;
        float value;
        int x, y;
        Vector3 scaledCenter(center.x * mPosXScale, center.y * mPosYScale, center.z * mPosZScale);
        int xStart = Math::Clamp((int)(scaledCenter.x - radius * mPosXScale), 0, mWidth);
        int xEnd = Math::Clamp((int)(scaledCenter.x + radius * mPosXScale), 0, mWidth);
        int yStart = Math::Clamp((int)(scaledCenter.y - radius * mPosYScale), 0, mHeight);
        int yEnd = Math::Clamp((int)(scaledCenter.y + radius * mPosYScale), 0, mHeight);
        int zStart = Math::Clamp((int)(scaledCenter.z - radius * mPosZScale), 0, mDepth);
        int zEnd = Math::Clamp((int)(scaledCenter.z + radius * mPosZScale), 0, mDepth);
        Vector3 pos;
        for (int z = zStart; z < zEnd; ++z)
        {
            for (y = yStart; y < yEnd; ++y)
            {
                for (x = xStart; x < xEnd; ++x)
                {
                    pos.x = x * worldWidthScale;
                    pos.y =  y * worldHeightScale;
                    pos.z = z * worldDepthScale;
                    value = operation->getValue(pos);
                    setVolumeGridValue(x, y, z, value);
                }
            }
        }

        mTrilinearValue = oldTrilinearValue;
    }

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

    Real GridSource::getVolumeSpaceToWorldSpaceFactor(void) const
    {
        return mVolumeSpaceToWorldSpaceFactor;
    }
}
}<commit_msg>Volume Rendering: taking the actual volume dimension of the grid into account when intersecting with a ray<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org

Copyright (c) 2000-2013 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreVolumeGridSource.h"
#include "OgreTextureManager.h"
#include "OgreHardwarePixelBuffer.h"
#include "OgreVector3.h"
#include "OgreColourValue.h"
#include "OgreMemoryAllocatorConfig.h"
#include "OgreLogManager.h"
#include "OgreTimer.h"

namespace Ogre {
namespace Volume {

    Vector3 GridSource::getIntersectionStart(const Ray &ray, Real maxDistance) const
    {
        AxisAlignedBox box((Real)0, (Real)0, (Real)0, (Real)mWidth / mPosXScale, (Real)mHeight / mPosYScale, (Real)mDepth / mPosZScale);

        // Inside the grid
        if (box.intersects(ray.getOrigin()))
        {
            return ray.getOrigin();
        }

        // Outside the grid, ray intersects it
        std::pair<bool, Real> intersection = ray.intersects(box);
        if (intersection.first)
        {
            Vector3 direction = ray.getDirection().normalisedCopy();
            return ray.getOrigin() + direction * intersection.second;
        }

        // Outside the grid, ray doesn't intersect it
        return ray.getOrigin();
    }

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

    Vector3 GridSource::getIntersectionEnd(const Ray &ray, Real maxDistance) const
    {
        AxisAlignedBox box((Real)0, (Real)0, (Real)0, (Real)mWidth / mPosXScale, (Real)mHeight / mPosYScale, (Real)mDepth / mPosZScale);
        Vector3 direction = ray.getDirection().normalisedCopy();
        Vector3 invertedDirection = (Real)-1.0 * direction;
        Vector3 origin = ray.getOrigin() + direction * box.getSize().length();

        Ray inverted(origin, invertedDirection);
        std::pair<bool, Real> intersection = inverted.intersects(box);
        if (intersection.first)
        {
            return origin + invertedDirection * intersection.second;
        }
        return ray.getOrigin() + direction * maxDistance;
    }

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

    GridSource::GridSource(bool trilinearValue, bool trilinearGradient, bool sobelGradient) :
        mTrilinearValue(trilinearValue), mTrilinearGradient(trilinearGradient), mSobelGradient(sobelGradient)
    {
    }

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

    GridSource::~GridSource(void)
    {
    }

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

    Vector4 GridSource::getValueAndGradient(const Vector3 &position) const
    {
        Vector3 scaledPosition(position.x * mPosXScale, position.y * mPosYScale, position.z * mPosZScale);
        Vector3 normal;
        if (mTrilinearGradient)
        {
            size_t x0 = (size_t)scaledPosition.x;
            size_t x1 = (size_t)ceil(scaledPosition.x);
            size_t y0 = (size_t)scaledPosition.y;
            size_t y1 = (size_t)ceil(scaledPosition.y);
            size_t z0 = (size_t)scaledPosition.z;
            size_t z1 = (size_t)ceil(scaledPosition.z);

            Real dX = scaledPosition.x - (Real)x0;
            Real dY = scaledPosition.y - (Real)y0;
            Real dZ = scaledPosition.z - (Real)z0;

            Vector3 f000 = getGradient(x0, y0, z0);
            Vector3 f100 = getGradient(x1, y0, z0);
            Vector3 f010 = getGradient(x0, y1, z0);
            Vector3 f001 = getGradient(x0, y0, z1);
            Vector3 f101 = getGradient(x1, y0, z1);
            Vector3 f011 = getGradient(x0, y1, z1);
            Vector3 f110 = getGradient(x1, y1, z0);
            Vector3 f111 = getGradient(x1, y1, z1);

            Real oneMinX = (Real)1.0 - dX;
            Real oneMinY = (Real)1.0 - dY;
            Real oneMinZ = (Real)1.0 - dZ;
            Real oneMinXoneMinY = oneMinX * oneMinY;
            Real dXOneMinY = dX * oneMinY;

            normal = oneMinZ * (f000 * oneMinXoneMinY
                + f100 * dXOneMinY
                + f010 * oneMinX * dY)
                + dZ * (f001 * oneMinXoneMinY
                + f101 * dXOneMinY
                + f011 * oneMinX * dY)
                + dX * dY * (f110 * oneMinZ
                + f111 * dZ);

            normal *= (Real)-1.0;
        }
        else
        {
            normal = getGradient((size_t)(scaledPosition.x + (Real)0.5), (size_t)(scaledPosition.y + (Real)0.5), (size_t)(scaledPosition.z + (Real)0.5));
            normal *= (Real)-1.0;
        }
        return Vector4(normal.x, normal.y, normal.z, getValue(position));
    }

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

    Real GridSource::getValue(const Vector3 &position) const
    {
        Vector3 scaledPosition(position.x * mPosXScale, position.y * mPosYScale, position.z * mPosZScale);
        Real value;
        if (mTrilinearValue)
        {
            size_t x0 = (size_t)scaledPosition.x;
            size_t x1 = (size_t)ceil(scaledPosition.x);
            size_t y0 = (size_t)scaledPosition.y;
            size_t y1 = (size_t)ceil(scaledPosition.y);
            size_t z0 = (size_t)scaledPosition.z;
            size_t z1 = (size_t)ceil(scaledPosition.z);

            Real dX = scaledPosition.x - (Real)x0;
            Real dY = scaledPosition.y - (Real)y0;
            Real dZ = scaledPosition.z - (Real)z0;

            Real f000 = getVolumeGridValue(x0, y0, z0);
            Real f100 = getVolumeGridValue(x1, y0, z0);
            Real f010 = getVolumeGridValue(x0, y1, z0);
            Real f001 = getVolumeGridValue(x0, y0, z1);
            Real f101 = getVolumeGridValue(x1, y0, z1);
            Real f011 = getVolumeGridValue(x0, y1, z1);
            Real f110 = getVolumeGridValue(x1, y1, z0);
            Real f111 = getVolumeGridValue(x1, y1, z1);

            Real oneMinX = (Real)1.0 - dX;
            Real oneMinY = (Real)1.0 - dY;
            Real oneMinZ = (Real)1.0 - dZ;
            Real oneMinXoneMinY = oneMinX * oneMinY;
            Real dXOneMinY = dX * oneMinY;

            value = oneMinZ * (f000 * oneMinXoneMinY
                + f100 * dXOneMinY
                + f010 * oneMinX * dY)
                + dZ * (f001 * oneMinXoneMinY
                + f101 * dXOneMinY
                + f011 * oneMinX * dY)
                + dX * dY * (f110 * oneMinZ
                + f111 * dZ);

        }
        else
        {
            // Nearest neighbour else
            size_t x = (size_t)(scaledPosition.x + (Real)0.5);
            size_t y = (size_t)(scaledPosition.y + (Real)0.5);
            size_t z = (size_t)(scaledPosition.z + (Real)0.5);
            value = (Real)getVolumeGridValue(x, y, z);
        }
        return value;
    }

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

    size_t GridSource::getWidth(void) const
    {
        return mWidth;
    }

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

    size_t GridSource::getHeight(void) const
    {
        return mHeight;
    }

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

    size_t GridSource::getDepth(void) const
    {
        return mDepth;
    }

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

    void GridSource::combineWithSource(CSGOperationSource *operation, Source *source, const Vector3 &center, Real radius)
    {
        Real worldWidthScale = (Real)1.0 / mPosXScale;
        Real worldHeightScale = (Real)1.0 / mPosYScale;
        Real worldDepthScale = (Real)1.0 / mPosZScale;

        operation->setSourceA(this);
        operation->setSourceB(source);
        // No need for trilineaer interpolation here as we iterate over the
        // cells anyway.
        bool oldTrilinearValue = mTrilinearValue;
        mTrilinearValue = false;
        float value;
        int x, y;
        Vector3 scaledCenter(center.x * mPosXScale, center.y * mPosYScale, center.z * mPosZScale);
        int xStart = Math::Clamp((int)(scaledCenter.x - radius * mPosXScale), 0, mWidth);
        int xEnd = Math::Clamp((int)(scaledCenter.x + radius * mPosXScale), 0, mWidth);
        int yStart = Math::Clamp((int)(scaledCenter.y - radius * mPosYScale), 0, mHeight);
        int yEnd = Math::Clamp((int)(scaledCenter.y + radius * mPosYScale), 0, mHeight);
        int zStart = Math::Clamp((int)(scaledCenter.z - radius * mPosZScale), 0, mDepth);
        int zEnd = Math::Clamp((int)(scaledCenter.z + radius * mPosZScale), 0, mDepth);
        Vector3 pos;
        for (int z = zStart; z < zEnd; ++z)
        {
            for (y = yStart; y < yEnd; ++y)
            {
                for (x = xStart; x < xEnd; ++x)
                {
                    pos.x = x * worldWidthScale;
                    pos.y =  y * worldHeightScale;
                    pos.z = z * worldDepthScale;
                    value = operation->getValue(pos);
                    setVolumeGridValue(x, y, z, value);
                }
            }
        }

        mTrilinearValue = oldTrilinearValue;
    }

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

    Real GridSource::getVolumeSpaceToWorldSpaceFactor(void) const
    {
        return mVolumeSpaceToWorldSpaceFactor;
    }
}
}<|endoftext|>


<commit_before>#include <cmath>
#include <Eigen/Dense>
#include <gtest/gtest.h>

class ReferenceFilter
{
public:
    ReferenceFilter( unsigned inputCount, unsigned outputCount )
        : mW( Eigen::MatrixXf::Random( outputCount, inputCount ) )
    {}

    Eigen::VectorXf operator()( Eigen::VectorXf inputs )
    {
        return mW * inputs;
    }

    Eigen::MatrixXf mW;
};

class Model
{
    const unsigned kInputCount = 100;
    const unsigned kOutputCount = 3;
    const float kMaxAmplitude = 1.0f;
    const float kMaxFrequency = 10.0f;
    const float kStep = 0.1f * 1.0f / kMaxFrequency;

public:
    Model()
        : mAmplitude( kMaxAmplitude / 2.0f *
            ( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f ) )
        , mOmega( kMaxFrequency / 2.0f *
            ( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f ) )
        , mInput( kInputCount )
        , mW( Eigen::MatrixXf::Random( kOutputCount, kInputCount ) )
        , mOutput( kOutputCount )
        , mReferenceFilter( kInputCount, kOutputCount )
        , mReferenceOutput( kOutputCount )
        , mTime( 0.0f )
    {}

    void Update()
    {
        mTime += kStep;
        mInput = mAmplitude.array() * ( mOmega.array() * mTime ).unaryExpr(
            std::ptr_fun< float, float >( std::sin ) );
        mOutput = mW * mInput;
        mReferenceOutput = mReferenceFilter( mInput );
    }

    Eigen::VectorXf mAmplitude;
    Eigen::VectorXf mOmega;
    Eigen::VectorXf mInput;
    Eigen::MatrixXf mW;
    Eigen::VectorXf mOutput;
    ReferenceFilter mReferenceFilter;
    Eigen::VectorXf mReferenceOutput;
    float mTime;
};

TEST( AdaptiveFilter, LMS )
{
    const unsigned kStepCount = 10000;
    const float kTrainStep = 0.1f;

    Model model;

    for ( int i = 0; i < kStepCount; ++ i )
    {
        model.Update();
        Eigen::VectorXf error = model.mReferenceOutput - model.mOutput;
        model.mW += ( kTrainStep * error * model.mInput.transpose() /
            model.mInput.squaredNorm() );
    }
}
<commit_msg>esn : tests : AdaptiveFilter : NLMS : renamed test-case LMS -> NLMS<commit_after>#include <cmath>
#include <Eigen/Dense>
#include <gtest/gtest.h>

class ReferenceFilter
{
public:
    ReferenceFilter( unsigned inputCount, unsigned outputCount )
        : mW( Eigen::MatrixXf::Random( outputCount, inputCount ) )
    {}

    Eigen::VectorXf operator()( Eigen::VectorXf inputs )
    {
        return mW * inputs;
    }

    Eigen::MatrixXf mW;
};

class Model
{
    const unsigned kInputCount = 100;
    const unsigned kOutputCount = 3;
    const float kMaxAmplitude = 1.0f;
    const float kMaxFrequency = 10.0f;
    const float kStep = 0.1f * 1.0f / kMaxFrequency;

public:
    Model()
        : mAmplitude( kMaxAmplitude / 2.0f *
            ( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f ) )
        , mOmega( kMaxFrequency / 2.0f *
            ( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f ) )
        , mInput( kInputCount )
        , mW( Eigen::MatrixXf::Random( kOutputCount, kInputCount ) )
        , mOutput( kOutputCount )
        , mReferenceFilter( kInputCount, kOutputCount )
        , mReferenceOutput( kOutputCount )
        , mTime( 0.0f )
    {}

    void Update()
    {
        mTime += kStep;
        mInput = mAmplitude.array() * ( mOmega.array() * mTime ).unaryExpr(
            std::ptr_fun< float, float >( std::sin ) );
        mOutput = mW * mInput;
        mReferenceOutput = mReferenceFilter( mInput );
    }

    Eigen::VectorXf mAmplitude;
    Eigen::VectorXf mOmega;
    Eigen::VectorXf mInput;
    Eigen::MatrixXf mW;
    Eigen::VectorXf mOutput;
    ReferenceFilter mReferenceFilter;
    Eigen::VectorXf mReferenceOutput;
    float mTime;
};

TEST( AdaptiveFilter, NLMS )
{
    const unsigned kStepCount = 10000;
    const float kTrainStep = 0.1f;

    Model model;

    for ( int i = 0; i < kStepCount; ++ i )
    {
        model.Update();
        Eigen::VectorXf error = model.mReferenceOutput - model.mOutput;
        model.mW += ( kTrainStep * error * model.mInput.transpose() /
            model.mInput.squaredNorm() );
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: propertystatecontainer.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 22:52:36 $
 *
 *  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 COMPHELPER_PROPERTYSTATECONTAINER_HXX
#include "comphelper/propertystatecontainer.hxx"
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

//.........................................................................
namespace comphelper
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::lang;

    namespace
    {
        static ::rtl::OUString lcl_getUnknownPropertyErrorMessage( const ::rtl::OUString& _rPropertyName )
        {
            // TODO: perhaps it's time to think about resources in the comphelper module?
            // Would be nice to have localized exception strings (a simply resource file containing
            // strings only would suffice, and could be realized with an UNO service, so we do not
            // need the dependency to the Tools project)
            ::rtl::OUStringBuffer sMessage;
            sMessage.appendAscii( "The property \"" );
            sMessage.append( _rPropertyName );
            sMessage.appendAscii( "\" is unknown." );
            return sMessage.makeStringAndClear();
        }
    }

    //=====================================================================
    //= OPropertyStateContainer
    //=====================================================================
    //---------------------------------------------------------------------
    OPropertyStateContainer::OPropertyStateContainer( ::cppu::OBroadcastHelper& _rBHelper )
        :OPropertyContainer( _rBHelper )
    {
    }

    //--------------------------------------------------------------------
    Any SAL_CALL OPropertyStateContainer::queryInterface( const Type& _rType ) throw (RuntimeException)
    {
        Any aReturn = OPropertyContainer::queryInterface( _rType );
        if ( !aReturn.hasValue() )
            aReturn = OPropertyStateContainer_TBase::queryInterface( _rType );
        return aReturn;
    }

    //--------------------------------------------------------------------
    IMPLEMENT_FORWARD_XTYPEPROVIDER2( OPropertyStateContainer, OPropertyContainer, OPropertyStateContainer_TBase )

    //--------------------------------------------------------------------
    sal_Int32 OPropertyStateContainer::getHandleForName( const ::rtl::OUString& _rPropertyName ) SAL_THROW( ( UnknownPropertyException ) )
    {
        // look up the handle for the name
        ::cppu::IPropertyArrayHelper& rPH = getInfoHelper();
        sal_Int32 nHandle = rPH.getHandleByName( _rPropertyName );

        if ( -1 == nHandle )
            throw  UnknownPropertyException( lcl_getUnknownPropertyErrorMessage( _rPropertyName ), static_cast< XPropertyState* >( this ) );

        return nHandle;
    }

    //--------------------------------------------------------------------
    PropertyState SAL_CALL OPropertyStateContainer::getPropertyState( const ::rtl::OUString& _rPropertyName ) throw (UnknownPropertyException, RuntimeException)
    {
        return getPropertyStateByHandle( getHandleForName( _rPropertyName ) );
    }

    //--------------------------------------------------------------------
    Sequence< PropertyState > SAL_CALL OPropertyStateContainer::getPropertyStates( const Sequence< ::rtl::OUString >& _rPropertyNames ) throw (UnknownPropertyException, RuntimeException)
    {
        sal_Int32 nProperties = _rPropertyNames.getLength();
        Sequence< PropertyState> aStates( nProperties );
        if ( !nProperties )
            return aStates;

#ifdef _DEBUG
        // precondition: property sequence is sorted (the algorythm below relies on this)
        {
            const ::rtl::OUString* pNames = _rPropertyNames.getConstArray();
            const ::rtl::OUString* pNamesCompare = pNames + 1;
            const ::rtl::OUString* pNamesEnd = _rPropertyNames.getConstArray() + _rPropertyNames.getLength();
            for ( ; pNamesCompare != pNamesEnd; ++pNames, ++pNamesCompare )
                OSL_PRECOND( pNames->compareTo( *pNamesCompare ) < 0,
                    "OPropertyStateContainer::getPropertyStates: property sequence not sorted!" );
        }
#endif

        const ::rtl::OUString* pLookup = _rPropertyNames.getConstArray();
        const ::rtl::OUString* pLookupEnd = pLookup + nProperties;
        PropertyState* pStates = aStates.getArray();

        cppu::IPropertyArrayHelper& rHelper = getInfoHelper();
        Sequence< Property> aAllProperties  = rHelper.getProperties();
        sal_Int32 nAllProperties            = aAllProperties.getLength();
        const  Property* pAllProperties     = aAllProperties.getConstArray();
        const  Property* pAllPropertiesEnd  = pAllProperties + nAllProperties;

        osl::MutexGuard aGuard( rBHelper.rMutex );
        for ( ; ( pAllProperties != pAllPropertiesEnd ) && ( pLookup != pLookupEnd ); ++pAllProperties )
        {
#ifdef _DEBUG
            if ( pAllProperties < pAllPropertiesEnd - 1 )
                OSL_ENSURE( pAllProperties->Name.compareTo( (pAllProperties + 1)->Name ) < 0,
                    "OPropertyStateContainer::getPropertyStates: all-properties not sorted!" );
#endif
            if ( pAllProperties->Name.equals( *pLookup ) )
            {
                *pStates++ = getPropertyState( *pLookup );
                ++pLookup;
            }
        }

        if ( pLookup != pLookupEnd )
            // we run out of properties from the IPropertyArrayHelper, but still have properties to lookup
            // -> we were asked for a nonexistent property
            throw UnknownPropertyException( lcl_getUnknownPropertyErrorMessage( *pLookup ), static_cast< XPropertyState* >( this ) );

        return aStates;
    }

    //--------------------------------------------------------------------
    void SAL_CALL OPropertyStateContainer::setPropertyToDefault( const ::rtl::OUString& _rPropertyName ) throw (UnknownPropertyException, RuntimeException)
    {
        setPropertyToDefaultByHandle( getHandleForName( _rPropertyName ) );
    }

    //--------------------------------------------------------------------
    Any SAL_CALL OPropertyStateContainer::getPropertyDefault( const ::rtl::OUString& _rPropertyName ) throw (UnknownPropertyException, WrappedTargetException, RuntimeException)
    {
        return getPropertyDefaultByHandle( getHandleForName( _rPropertyName ) );
    }

    //--------------------------------------------------------------------
    PropertyState OPropertyStateContainer::getPropertyStateByHandle( sal_Int32 _nHandle )
    {
        // simply compare the current and the default value
        Any aCurrentValue; getFastPropertyValue( aCurrentValue, _nHandle );
        Any aDefaultValue = getPropertyDefaultByHandle( _nHandle );

        sal_Bool bEqual = uno_type_equalData(
                const_cast< void* >( aCurrentValue.getValue() ), aCurrentValue.getValueType().getTypeLibType(),
                const_cast< void* >( aDefaultValue.getValue() ), aDefaultValue.getValueType().getTypeLibType(),
                reinterpret_cast< uno_QueryInterfaceFunc >(cpp_queryInterface),
                reinterpret_cast< uno_ReleaseFunc >(cpp_release)
            );
        if ( bEqual )
            return PropertyState_DEFAULT_VALUE;
        else
            return PropertyState_DIRECT_VALUE;
    }

    //--------------------------------------------------------------------
    void OPropertyStateContainer::setPropertyToDefaultByHandle( sal_Int32 _nHandle )
    {
        setFastPropertyValue( _nHandle, getPropertyDefaultByHandle( _nHandle ) );
    }

//.........................................................................
}   // namespace comphelper
//.........................................................................

#ifdef FS_PRIV_DEBUG
#define STATECONTAINER_TEST
#endif

#ifdef STATECONTAINER_TEST

#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif

//.........................................................................
namespace comphelper
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;

    //=====================================================================
    //= Test - compiler test
    //=====================================================================
    typedef ::cppu::OWeakAggObject  Test_RefCountBase;
    class Test  :public OMutexAndBroadcastHelper
                ,public OPropertyStateContainer
                ,public OPropertyArrayUsageHelper< Test >
                ,public Test_RefCountBase
    {
    private:
        ::rtl::OUString         m_sStringProperty;
        Reference< XInterface > m_xInterfaceProperty;
        Any                     m_aMayBeVoidProperty;

    protected:
        Test( );

        DECLARE_XINTERFACE( )

    public:
        static Test* Create( );

    protected:
        virtual Reference< XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(RuntimeException);
        virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
        virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;

    protected:
        // OPropertyStateContainer overridables
        virtual Any getPropertyDefaultByHandle( sal_Int32 _nHandle ) const;
    };

    //---------------------------------------------------------------------
    Test::Test( )
        :OPropertyStateContainer( GetBroadcastHelper() )
    {
        registerProperty(
            ::rtl::OUString::createFromAscii( "StringProperty" ),
            1,
            PropertyAttribute::BOUND,
            &m_sStringProperty,
            ::getCppuType( &m_sStringProperty )
        );

        registerProperty(
            ::rtl::OUString::createFromAscii( "InterfaceProperty" ),
            2,
            PropertyAttribute::BOUND,
            &m_xInterfaceProperty,
            ::getCppuType( &m_xInterfaceProperty )
        );

        registerMayBeVoidProperty(
            ::rtl::OUString::createFromAscii( "IntProperty" ),
            3,
            PropertyAttribute::BOUND,
            &m_aMayBeVoidProperty,
            ::getCppuType( static_cast< sal_Int32* >( NULL ) )
        );

        registerPropertyNoMember(
            ::rtl::OUString::createFromAscii( "OtherInterfaceProperty" ),
            4,
            PropertyAttribute::BOUND | PropertyAttribute::MAYBEVOID,
            ::getCppuType( static_cast< Reference< XInterface >* >( NULL ) ),
            NULL
        );
    }

    //---------------------------------------------------------------------
    IMPLEMENT_FORWARD_XINTERFACE2( Test, Test_RefCountBase, OPropertyStateContainer )

    //---------------------------------------------------------------------
    Any Test::getPropertyDefaultByHandle( sal_Int32 _nHandle ) const
    {
        Any aDefault;
        switch ( _nHandle )
        {
            case 1:
                aDefault = makeAny( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "StringPropertyDefault" ) ) );
                break;
            case 2:
                aDefault = makeAny( Reference< XInterface >( ) );
                break;
            case 3:
                // void
                break;
            case 4:
                aDefault = makeAny( Reference< XInterface >( ) );
                break;
            default:
                OSL_ENSURE( sal_False, "Test::getPropertyDefaultByHandle: invalid handle!" );
        }
        return aDefault;
    }

    //---------------------------------------------------------------------
    Reference< XPropertySetInfo > SAL_CALL Test::getPropertySetInfo(  ) throw(RuntimeException)
    {
        return createPropertySetInfo( getInfoHelper() );
    }

    //---------------------------------------------------------------------
    ::cppu::IPropertyArrayHelper& SAL_CALL Test::getInfoHelper()
    {
        return *getArrayHelper();
    }

    //---------------------------------------------------------------------
    ::cppu::IPropertyArrayHelper* Test::createArrayHelper( ) const
    {
        Sequence< Property > aProps;
        describeProperties( aProps );
        return new ::cppu::OPropertyArrayHelper( aProps );
    }

    //---------------------------------------------------------------------
    Test* Test::Create( )
    {
        Test* pInstance = new Test;
        return pInstance;
    }

//.........................................................................
}   // namespace comphelper
//.........................................................................

#endif

<commit_msg>INTEGRATION: CWS dba30 (1.2.86); FILE MERGED 2006/07/19 12:05:34 fs 1.2.86.4: RESYNC: (1.3-1.4); FILE MERGED 2005/09/30 06:03:55 fs 1.2.86.3: RESYNC: (1.2-1.3); FILE MERGED 2005/04/06 08:28:19 fs 1.2.86.2: #i10000# 2005/04/06 07:07:05 fs 1.2.86.1: #i46768# getPropertyDefaultByHandle signature changed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: propertystatecontainer.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-15 11:04:09 $
 *
 *  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 COMPHELPER_PROPERTYSTATECONTAINER_HXX
#include "comphelper/propertystatecontainer.hxx"
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

//.........................................................................
namespace comphelper
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::lang;

    namespace
    {
        static ::rtl::OUString lcl_getUnknownPropertyErrorMessage( const ::rtl::OUString& _rPropertyName )
        {
            // TODO: perhaps it's time to think about resources in the comphelper module?
            // Would be nice to have localized exception strings (a simply resource file containing
            // strings only would suffice, and could be realized with an UNO service, so we do not
            // need the dependency to the Tools project)
            ::rtl::OUStringBuffer sMessage;
            sMessage.appendAscii( "The property \"" );
            sMessage.append( _rPropertyName );
            sMessage.appendAscii( "\" is unknown." );
            return sMessage.makeStringAndClear();
        }
    }

    //=====================================================================
    //= OPropertyStateContainer
    //=====================================================================
    //---------------------------------------------------------------------
    OPropertyStateContainer::OPropertyStateContainer( ::cppu::OBroadcastHelper& _rBHelper )
        :OPropertyContainer( _rBHelper )
    {
    }

    //--------------------------------------------------------------------
    Any SAL_CALL OPropertyStateContainer::queryInterface( const Type& _rType ) throw (RuntimeException)
    {
        Any aReturn = OPropertyContainer::queryInterface( _rType );
        if ( !aReturn.hasValue() )
            aReturn = OPropertyStateContainer_TBase::queryInterface( _rType );
        return aReturn;
    }

    //--------------------------------------------------------------------
    IMPLEMENT_FORWARD_XTYPEPROVIDER2( OPropertyStateContainer, OPropertyContainer, OPropertyStateContainer_TBase )

    //--------------------------------------------------------------------
    sal_Int32 OPropertyStateContainer::getHandleForName( const ::rtl::OUString& _rPropertyName ) SAL_THROW( ( UnknownPropertyException ) )
    {
        // look up the handle for the name
        ::cppu::IPropertyArrayHelper& rPH = getInfoHelper();
        sal_Int32 nHandle = rPH.getHandleByName( _rPropertyName );

        if ( -1 == nHandle )
            throw  UnknownPropertyException( lcl_getUnknownPropertyErrorMessage( _rPropertyName ), static_cast< XPropertyState* >( this ) );

        return nHandle;
    }

    //--------------------------------------------------------------------
    PropertyState SAL_CALL OPropertyStateContainer::getPropertyState( const ::rtl::OUString& _rPropertyName ) throw (UnknownPropertyException, RuntimeException)
    {
        return getPropertyStateByHandle( getHandleForName( _rPropertyName ) );
    }

    //--------------------------------------------------------------------
    Sequence< PropertyState > SAL_CALL OPropertyStateContainer::getPropertyStates( const Sequence< ::rtl::OUString >& _rPropertyNames ) throw (UnknownPropertyException, RuntimeException)
    {
        sal_Int32 nProperties = _rPropertyNames.getLength();
        Sequence< PropertyState> aStates( nProperties );
        if ( !nProperties )
            return aStates;

#ifdef _DEBUG
        // precondition: property sequence is sorted (the algorythm below relies on this)
        {
            const ::rtl::OUString* pNames = _rPropertyNames.getConstArray();
            const ::rtl::OUString* pNamesCompare = pNames + 1;
            const ::rtl::OUString* pNamesEnd = _rPropertyNames.getConstArray() + _rPropertyNames.getLength();
            for ( ; pNamesCompare != pNamesEnd; ++pNames, ++pNamesCompare )
                OSL_PRECOND( pNames->compareTo( *pNamesCompare ) < 0,
                    "OPropertyStateContainer::getPropertyStates: property sequence not sorted!" );
        }
#endif

        const ::rtl::OUString* pLookup = _rPropertyNames.getConstArray();
        const ::rtl::OUString* pLookupEnd = pLookup + nProperties;
        PropertyState* pStates = aStates.getArray();

        cppu::IPropertyArrayHelper& rHelper = getInfoHelper();
        Sequence< Property> aAllProperties  = rHelper.getProperties();
        sal_Int32 nAllProperties            = aAllProperties.getLength();
        const  Property* pAllProperties     = aAllProperties.getConstArray();
        const  Property* pAllPropertiesEnd  = pAllProperties + nAllProperties;

        osl::MutexGuard aGuard( rBHelper.rMutex );
        for ( ; ( pAllProperties != pAllPropertiesEnd ) && ( pLookup != pLookupEnd ); ++pAllProperties )
        {
#ifdef _DEBUG
            if ( pAllProperties < pAllPropertiesEnd - 1 )
                OSL_ENSURE( pAllProperties->Name.compareTo( (pAllProperties + 1)->Name ) < 0,
                    "OPropertyStateContainer::getPropertyStates: all-properties not sorted!" );
#endif
            if ( pAllProperties->Name.equals( *pLookup ) )
            {
                *pStates++ = getPropertyState( *pLookup );
                ++pLookup;
            }
        }

        if ( pLookup != pLookupEnd )
            // we run out of properties from the IPropertyArrayHelper, but still have properties to lookup
            // -> we were asked for a nonexistent property
            throw UnknownPropertyException( lcl_getUnknownPropertyErrorMessage( *pLookup ), static_cast< XPropertyState* >( this ) );

        return aStates;
    }

    //--------------------------------------------------------------------
    void SAL_CALL OPropertyStateContainer::setPropertyToDefault( const ::rtl::OUString& _rPropertyName ) throw (UnknownPropertyException, RuntimeException)
    {
        setPropertyToDefaultByHandle( getHandleForName( _rPropertyName ) );
    }

    //--------------------------------------------------------------------
    Any SAL_CALL OPropertyStateContainer::getPropertyDefault( const ::rtl::OUString& _rPropertyName ) throw (UnknownPropertyException, WrappedTargetException, RuntimeException)
    {
        Any aDefault;
        getPropertyDefaultByHandle( getHandleForName( _rPropertyName ), aDefault );
        return aDefault;
    }

    //--------------------------------------------------------------------
    PropertyState OPropertyStateContainer::getPropertyStateByHandle( sal_Int32 _nHandle )
    {
        // simply compare the current and the default value
        Any aCurrentValue; getFastPropertyValue( aCurrentValue, _nHandle );
        Any aDefaultValue; getPropertyDefaultByHandle( _nHandle, aDefaultValue );

        sal_Bool bEqual = uno_type_equalData(
                const_cast< void* >( aCurrentValue.getValue() ), aCurrentValue.getValueType().getTypeLibType(),
                const_cast< void* >( aDefaultValue.getValue() ), aDefaultValue.getValueType().getTypeLibType(),
                reinterpret_cast< uno_QueryInterfaceFunc >(cpp_queryInterface),
                reinterpret_cast< uno_ReleaseFunc >(cpp_release)
            );
        if ( bEqual )
            return PropertyState_DEFAULT_VALUE;
        else
            return PropertyState_DIRECT_VALUE;
    }

    //--------------------------------------------------------------------
    void OPropertyStateContainer::setPropertyToDefaultByHandle( sal_Int32 _nHandle )
    {
        Any aDefault;
        getPropertyDefaultByHandle( _nHandle, aDefault );
        setFastPropertyValue( _nHandle, aDefault );
    }

//.........................................................................
}   // namespace comphelper
//.........................................................................

#ifdef FS_PRIV_DEBUG
#define STATECONTAINER_TEST
#endif

#ifdef STATECONTAINER_TEST

#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif

//.........................................................................
namespace comphelper
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;

    //=====================================================================
    //= Test - compiler test
    //=====================================================================
    typedef ::cppu::OWeakAggObject  Test_RefCountBase;
    class Test  :public OMutexAndBroadcastHelper
                ,public OPropertyStateContainer
                ,public OPropertyArrayUsageHelper< Test >
                ,public Test_RefCountBase
    {
    private:
        ::rtl::OUString         m_sStringProperty;
        Reference< XInterface > m_xInterfaceProperty;
        Any                     m_aMayBeVoidProperty;

    protected:
        Test( );

        DECLARE_XINTERFACE( )

    public:
        static Test* Create( );

    protected:
        virtual Reference< XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(RuntimeException);
        virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
        virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;

    protected:
        // OPropertyStateContainer overridables
        virtual void getPropertyDefaultByHandle( sal_Int32 _nHandle, Any& _rDefault ) const;
    };

    //---------------------------------------------------------------------
    Test::Test( )
        :OPropertyStateContainer( GetBroadcastHelper() )
    {
        registerProperty(
            ::rtl::OUString::createFromAscii( "StringProperty" ),
            1,
            PropertyAttribute::BOUND,
            &m_sStringProperty,
            ::getCppuType( &m_sStringProperty )
        );

        registerProperty(
            ::rtl::OUString::createFromAscii( "InterfaceProperty" ),
            2,
            PropertyAttribute::BOUND,
            &m_xInterfaceProperty,
            ::getCppuType( &m_xInterfaceProperty )
        );

        registerMayBeVoidProperty(
            ::rtl::OUString::createFromAscii( "IntProperty" ),
            3,
            PropertyAttribute::BOUND,
            &m_aMayBeVoidProperty,
            ::getCppuType( static_cast< sal_Int32* >( NULL ) )
        );

        registerPropertyNoMember(
            ::rtl::OUString::createFromAscii( "OtherInterfaceProperty" ),
            4,
            PropertyAttribute::BOUND | PropertyAttribute::MAYBEVOID,
            ::getCppuType( static_cast< Reference< XInterface >* >( NULL ) ),
            NULL
        );
    }

    //---------------------------------------------------------------------
    IMPLEMENT_FORWARD_XINTERFACE2( Test, Test_RefCountBase, OPropertyStateContainer )

    //---------------------------------------------------------------------
    void Test::getPropertyDefaultByHandle( sal_Int32 _nHandle, Any& _rDefault ) const
    {
        switch ( _nHandle )
        {
            case 1:
                _rDefault = makeAny( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "StringPropertyDefault" ) ) );
                break;
            case 2:
                _rDefault = makeAny( Reference< XInterface >( ) );
                break;
            case 3:
                // void
                break;
            case 4:
                _rDefault = makeAny( Reference< XInterface >( ) );
                break;
            default:
                OSL_ENSURE( sal_False, "Test::getPropertyDefaultByHandle: invalid handle!" );
        }
    }

    //---------------------------------------------------------------------
    Reference< XPropertySetInfo > SAL_CALL Test::getPropertySetInfo(  ) throw(RuntimeException)
    {
        return createPropertySetInfo( getInfoHelper() );
    }

    //---------------------------------------------------------------------
    ::cppu::IPropertyArrayHelper& SAL_CALL Test::getInfoHelper()
    {
        return *getArrayHelper();
    }

    //---------------------------------------------------------------------
    ::cppu::IPropertyArrayHelper* Test::createArrayHelper( ) const
    {
        Sequence< Property > aProps;
        describeProperties( aProps );
        return new ::cppu::OPropertyArrayHelper( aProps );
    }

    //---------------------------------------------------------------------
    Test* Test::Create( )
    {
        Test* pInstance = new Test;
        return pInstance;
    }

//.........................................................................
}   // namespace comphelper
//.........................................................................

#endif

<|endoftext|>


<commit_before>/** @file
    WCCP static data and compile time checks.

    @section license License

    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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 "WccpLocal.h"
#include "WccpMeta.h"
#include "ts/ink_error.h"
#include "ts/ink_defs.h"

/* Solaris considers SIOCGIFCONF obsolete and only defines it if
 * BSD compatibility activated. */
#if defined(solaris)
#define BSD_COMP
#endif
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>

namespace wccp
{
// ------------------------------------------------------
// Compile time checks for internal consistency.

struct CompileTimeChecks {
  static unsigned int const BUCKET_SIZE = sizeof(AssignInfoComp::Bucket);
  static unsigned int const UINT8_SIZE  = sizeof(uint8_t);
  // A compiler error for the following line means that the size of
  // an assignment bucket is incorrect. It must be exactly 1 byte.
  ts::TEST_IF_TRUE<BUCKET_SIZE == UINT8_SIZE> m_check_bucket_size;
};

ts::Errata::Code LVL_TMP   = 1; ///< Temporary message.
ts::Errata::Code LVL_FATAL = 3; ///< Fatal, cannot continue.
ts::Errata::Code LVL_WARN  = 2; ///< Significant, should be fixed.
ts::Errata::Code LVL_INFO  = 1; /// Interesting, not necessarily a problem.
ts::Errata::Code LVL_DEBUG = 0; /// Debugging information.

// Find a valid local IP address given an open socket.
uint32_t
Get_Local_Address(int s)
{
  // If we can't find a good address in the first 255, just give up
  // and make the user specify an address.
  static int const N_REQ = 255;
  ifconf conf;
  ifreq req[N_REQ];
  uint32_t zret;

  conf.ifc_len = sizeof(req);
  conf.ifc_req = req;
  if (0 == ioctl(s, SIOCGIFCONF, &conf)) {
    int idx      = 0;
    ifreq *ptr   = req;
    ifreq *limit = req + (conf.ifc_len / sizeof(*req));
    for (; idx < N_REQ && ptr < limit; ++idx, ++ptr) {
      zret = reinterpret_cast<sockaddr_in &>(ptr->ifr_addr).sin_addr.s_addr;
      if ((zret & 0xFF) != 0x7F)
        return zret;
    }
  }
  return INADDR_ANY; // fail
}

// Cheap, can't even be used twice in the same argument list.
char const *
ip_addr_to_str(uint32_t addr)
{
  static char buff[4 * 3 + 3 + 1];
  unsigned char *octet = reinterpret_cast<unsigned char *>(&addr);
  sprintf(buff, "%d.%d.%d.%d", octet[0], octet[1], octet[2], octet[3]);
  return buff;
}

// ------------------------------------------------------
ts::Errata &
log(ts::Errata &err, ts::Errata::Id id, ts::Errata::Code code, char const *text)
{
  err.push(id, code, text);
  return err;
}

ts::Errata &
log(ts::Errata &err, ts::Errata::Code code, char const *text)
{
  err.push(0, code, text);
  return err;
}

ts::Errata
log(ts::Errata::Code code, char const *text)
{
  ts::Errata err;
  err.push(0, code, text);
  return err;
}

ts::Errata &
vlogf(ts::Errata &err, ts::Errata::Id id, ts::Errata::Code code, char const *format, va_list &rest)
{
  static size_t const SIZE = 8192;
  char buffer[SIZE];

  vsnprintf(buffer, SIZE, format, rest);
  err.push(id, code, buffer);
  return err;
}

ts::Errata &
logf(ts::Errata &err, ts::Errata::Id id, ts::Errata::Code code, char const *format, ...)
{
  va_list rest;
  va_start(rest, format);
  return vlogf(err, id, code, format, rest);
}

ts::Errata
logf(ts::Errata::Code code, char const *format, ...)
{
  ts::Errata err;
  va_list rest;
  va_start(rest, format);
  return vlogf(err, ts::Errata::Id(0), code, format, rest);
}

ts::Errata &
logf(ts::Errata &err, ts::Errata::Code code, char const *format, ...)
{
  va_list rest;
  va_start(rest, format);
  return vlogf(err, ts::Errata::Id(0), code, format, rest);
}

ts::Errata
log_errno(ts::Errata::Code code, char const *text)
{
  static size_t const SIZE = 1024;
  char buffer[SIZE];
  ATS_UNUSED_RETURN(strerror_r(errno, buffer, SIZE));
  return logf(code, "%s [%d] %s", text, errno, buffer);
}

ts::Errata
vlogf_errno(ts::Errata::Code code, char const *format, va_list &rest)
{
  int e = errno; // Preserve value before making system calls.
  ts::Errata err;
  int n;
  static int const E_SIZE = 1024;
  char e_buffer[E_SIZE];
  static int const T_SIZE = 8192;
  char t_buffer[T_SIZE];

  n = vsnprintf(t_buffer, T_SIZE, format, rest);
  if (0 <= n && n < T_SIZE) { // still have room.
    ATS_UNUSED_RETURN(strerror_r(e, e_buffer, E_SIZE));
    n += snprintf(t_buffer + n, T_SIZE - n, "[%d] %s", e, e_buffer);
  }
  err.push(ts::Errata::Id(0), code, t_buffer);
  return err;
}

ts::Errata
logf_errno(ts::Errata::Code code, char const *format, ...)
{
  va_list rest;
  va_start(rest, format);
  return vlogf_errno(code, format, rest);
}
// ------------------------------------------------------
} // namespace wccp
<commit_msg>WCCP: CV 1267996, 1267997, 1267988, 1267999 Fix va_end issues.<commit_after>/** @file
    WCCP static data and compile time checks.

    @section license License

    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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 "WccpLocal.h"
#include "WccpMeta.h"
#include "ts/ink_error.h"
#include "ts/ink_defs.h"

/* Solaris considers SIOCGIFCONF obsolete and only defines it if
 * BSD compatibility activated. */
#if defined(solaris)
#define BSD_COMP
#endif
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>

namespace wccp
{
// ------------------------------------------------------
// Compile time checks for internal consistency.

struct CompileTimeChecks {
  static unsigned int const BUCKET_SIZE = sizeof(AssignInfoComp::Bucket);
  static unsigned int const UINT8_SIZE  = sizeof(uint8_t);
  // A compiler error for the following line means that the size of
  // an assignment bucket is incorrect. It must be exactly 1 byte.
  ts::TEST_IF_TRUE<BUCKET_SIZE == UINT8_SIZE> m_check_bucket_size;
};

ts::Errata::Code LVL_TMP   = 1; ///< Temporary message.
ts::Errata::Code LVL_FATAL = 3; ///< Fatal, cannot continue.
ts::Errata::Code LVL_WARN  = 2; ///< Significant, should be fixed.
ts::Errata::Code LVL_INFO  = 1; /// Interesting, not necessarily a problem.
ts::Errata::Code LVL_DEBUG = 0; /// Debugging information.

// Find a valid local IP address given an open socket.
uint32_t
Get_Local_Address(int s)
{
  // If we can't find a good address in the first 255, just give up
  // and make the user specify an address.
  static int const N_REQ = 255;
  ifconf conf;
  ifreq req[N_REQ];
  uint32_t zret;

  conf.ifc_len = sizeof(req);
  conf.ifc_req = req;
  if (0 == ioctl(s, SIOCGIFCONF, &conf)) {
    int idx      = 0;
    ifreq *ptr   = req;
    ifreq *limit = req + (conf.ifc_len / sizeof(*req));
    for (; idx < N_REQ && ptr < limit; ++idx, ++ptr) {
      zret = reinterpret_cast<sockaddr_in &>(ptr->ifr_addr).sin_addr.s_addr;
      if ((zret & 0xFF) != 0x7F)
        return zret;
    }
  }
  return INADDR_ANY; // fail
}

// Cheap, can't even be used twice in the same argument list.
char const *
ip_addr_to_str(uint32_t addr)
{
  static char buff[4 * 3 + 3 + 1];
  unsigned char *octet = reinterpret_cast<unsigned char *>(&addr);
  sprintf(buff, "%d.%d.%d.%d", octet[0], octet[1], octet[2], octet[3]);
  return buff;
}

// ------------------------------------------------------
ts::Errata &
log(ts::Errata &err, ts::Errata::Id id, ts::Errata::Code code, char const *text)
{
  err.push(id, code, text);
  return err;
}

ts::Errata &
log(ts::Errata &err, ts::Errata::Code code, char const *text)
{
  err.push(0, code, text);
  return err;
}

ts::Errata
log(ts::Errata::Code code, char const *text)
{
  ts::Errata err;
  err.push(0, code, text);
  return err;
}

ts::Errata &
vlogf(ts::Errata &err, ts::Errata::Id id, ts::Errata::Code code, char const *format, va_list &rest)
{
  static size_t const SIZE = 8192;
  char buffer[SIZE];

  vsnprintf(buffer, SIZE, format, rest);
  err.push(id, code, buffer);
  return err;
}

ts::Errata &
logf(ts::Errata &err, ts::Errata::Id id, ts::Errata::Code code, char const *format, ...)
{
  va_list rest;
  va_start(rest, format);
  va_end(rest);
  return vlogf(err, id, code, format, rest);
}

ts::Errata
logf(ts::Errata::Code code, char const *format, ...)
{
  ts::Errata err;
  va_list rest;
  va_start(rest, format);
  va_end(rest);
  return vlogf(err, ts::Errata::Id(0), code, format, rest);
}

ts::Errata &
logf(ts::Errata &err, ts::Errata::Code code, char const *format, ...)
{
  va_list rest;
  va_start(rest, format);
  va_end(rest);
  return vlogf(err, ts::Errata::Id(0), code, format, rest);
}

ts::Errata
log_errno(ts::Errata::Code code, char const *text)
{
  static size_t const SIZE = 1024;
  char buffer[SIZE];
  ATS_UNUSED_RETURN(strerror_r(errno, buffer, SIZE));
  return logf(code, "%s [%d] %s", text, errno, buffer);
}

ts::Errata
vlogf_errno(ts::Errata::Code code, char const *format, va_list &rest)
{
  int e = errno; // Preserve value before making system calls.
  ts::Errata err;
  int n;
  static int const E_SIZE = 1024;
  char e_buffer[E_SIZE];
  static int const T_SIZE = 8192;
  char t_buffer[T_SIZE];

  n = vsnprintf(t_buffer, T_SIZE, format, rest);
  if (0 <= n && n < T_SIZE) { // still have room.
    ATS_UNUSED_RETURN(strerror_r(e, e_buffer, E_SIZE));
    n += snprintf(t_buffer + n, T_SIZE - n, "[%d] %s", e, e_buffer);
  }
  err.push(ts::Errata::Id(0), code, t_buffer);
  return err;
}

ts::Errata
logf_errno(ts::Errata::Code code, char const *format, ...)
{
  va_list rest;
  va_start(rest, format);
  va_end(rest);
  return vlogf_errno(code, format, rest);
}
// ------------------------------------------------------
} // namespace wccp
<|endoftext|>


<commit_before>#include "TestScene.h"
#include <fstream>
#include "ShaderManager.h"
#include "Mesh.h"
#include "LightCulling.h"

#include "Director.h"
#include "ResourceManager.h"

#include "PhysicallyBasedMaterial.h"

using namespace Rendering;
using namespace Core;
using namespace Rendering::Camera;
using namespace Rendering::Geometry;
using namespace Rendering::Light;
using namespace Rendering::Geometry;
using namespace Resource;
using namespace Device;
using namespace Math;
using namespace Importer;

TestScene::TestScene(void)
{

}

TestScene::~TestScene(void)
{
}

void TestScene::OnInitialize()
{
	_camera = new Object("Default");
	MeshCamera* cam = _camera->AddComponent<MeshCamera>();
	_camera->GetTransform()->UpdatePosition(Vector3(0, 0, 0));
	cam->SetFieldOfViewDegree(60.0f);

	const ResourceManager* resourceMgr = ResourceManager::GetInstance();
	MeshImporter* importer = resourceMgr->GetMeshImporter();

#if 0
	_testObject = importer->Load("./Resources/Capsule/capsule.obj");
	_testObject->GetTransform()->UpdatePosition(Vector3(0, 0, 5));
#else
	//_testObject = importer.Load("./Resources/House/SanFranciscoHouse.fbx");
	//_testObject->GetTransform()->UpdatePosition(Vector3(0, -5, 15));
	//_testObject->GetTransform()->UpdateEulerAngles(Vector3(-90, 0, 0));

	_testObject = importer->Load("./Resources/CornellBox/box.obj", false);
	_testObject->GetTransform()->UpdatePosition(Vector3(0, 0, 0));
	_testObject->GetTransform()->UpdateEulerAngles(Vector3(-90, 180.0f, 180));
	_testObject->GetTransform()->UpdateScale(Vector3(5, 5, 5));

	//_testObject2 = importer->Load("./Resources/CornellBox/box.obj", false);
	//_testObject2->GetTransform()->UpdatePosition(Vector3(0, 0, 0));
	//_testObject2->GetTransform()->UpdateEulerAngles(Vector3(-90, 180.0f, 180));
	//AddObject(_testObject2);
#endif
	AddObject(_testObject);

#if 0
	_light = new Object("Light");
	_light->GetTransform()->UpdateEulerAngles(Vector3(-60, -60, 0));
	_light->GetTransform()->UpdatePosition(Vector3(-1, 1.5,  12));

	SpotLight* light = _light->AddComponent<SpotLight>();
	light->SetLumen(150);
	light->SetRadius(10.0f);
	light->ActiveShadow(true);
	light->SetSpotAngleDegree(120.0f);
#elif 0
	_light = new Object("Light");
//	_light->GetTransform()->UpdateEulerAngles(Vector3(315, 340, 0));
	_light->GetTransform()->UpdateEulerAngles(Vector3(90, 0, 0));
	_light->GetTransform()->UpdatePosition(Vector3(-1, 1.5,  12));

	DirectionalLight* light = _light->AddComponent<DirectionalLight>();
	light->SetIntensity(1);
	light->ActiveShadow(true);
#elif 1
	_light = new Object("Light");
	_light->GetTransform()->UpdateEulerAngles(Vector3(60, 60, 0));
	_light->GetTransform()->UpdatePosition(Vector3(-1, 1.5,  12));

	PointLight* light = _light->AddComponent<PointLight>();
	light->SetLumen(150);
	light->SetRadius(10.0f);
	light->ActiveShadow(true);
	light->GetShadow()->SetUnderScanSize(0.0f);
#endif

	AddObject(_light);
}

void TestScene::OnRenderPreview()
{
}

void TestScene::OnInput(const Device::Win32::Mouse& mouse, const  Device::Win32::Keyboard& keyboard)
{
	Transform* control = _light->GetTransform();
	float value = 1;

	if(keyboard.states['W'] == Win32::Keyboard::Type::Up)
	{
		Vector3 pos = control->GetLocalPosition();
		control->UpdatePosition(pos + Vector3(0, 0.1f, 0));
	}
	if(keyboard.states['A'] == Win32::Keyboard::Type::Up)
	{
		Vector3 pos = control->GetLocalPosition();
		control->UpdatePosition(pos + Vector3(-0.1f, 0, 0));
	}
	if(keyboard.states['S'] == Win32::Keyboard::Type::Up)
	{
		Vector3 pos = control->GetLocalPosition();
		control->UpdatePosition(pos + Vector3(0, -0.1f, 0));
	}
	if(keyboard.states['D'] == Win32::Keyboard::Type::Up)
	{
		Vector3 pos = control->GetLocalPosition();
		control->UpdatePosition(pos + Vector3(0.1f, 0, 0));
	}

	if(keyboard.states['T'] == Win32::Keyboard::Type::Up)
	{
		Vector3 pos = control->GetLocalPosition();
		control->UpdatePosition(pos + Vector3(0, 0, 0.1f));
	}
	if(keyboard.states['G'] == Win32::Keyboard::Type::Up)
	{
		Vector3 pos = control->GetLocalPosition();
		control->UpdatePosition(pos + Vector3(0, 0, -0.1f));
	}

	if(keyboard.states['U'] == Win32::Keyboard::Type::Up)
	{
		Vector3 e = control->GetLocalEulerAngle();
		control->UpdateEulerAngles(e + Vector3(5, 0, 0));
	}
	if(keyboard.states['J'] == Win32::Keyboard::Type::Up)
	{
		Vector3 e = control->GetLocalEulerAngle();
		control->UpdateEulerAngles(e + Vector3(-5, 0, 0));
	}
	if(keyboard.states['H'] == Win32::Keyboard::Type::Up)
	{
		Vector3 e = control->GetLocalEulerAngle();
		control->UpdateEulerAngles(e + Vector3(0, 5, 0));
	}
	if(keyboard.states['K'] == Win32::Keyboard::Type::Up)
	{
		Vector3 e = control->GetLocalEulerAngle();
		control->UpdateEulerAngles(e + Vector3(0, -5, 0));
	}

}

void TestScene::OnUpdate(float dt)
{
	//Transform* tf = _testObject->GetTransform();

	//Vector3 euler = tf->GetLocalEulerAngle();
	//tf->UpdateEulerAngles(euler - Vector3(0, 0.1f, 0));

	//Vector3 pos = tf->GetLocalPosition();
	//tf->UpdatePosition(pos - Vector3(0, 0.2f, 0));
}

void TestScene::OnRenderPost()
{

}

void TestScene::OnDestroy()
{

}<commit_msg>TestCode<commit_after>#include "TestScene.h"
#include <fstream>
#include "ShaderManager.h"
#include "Mesh.h"
#include "LightCulling.h"

#include "Director.h"
#include "ResourceManager.h"

#include "PhysicallyBasedMaterial.h"

using namespace Rendering;
using namespace Core;
using namespace Rendering::Camera;
using namespace Rendering::Geometry;
using namespace Rendering::Light;
using namespace Rendering::Geometry;
using namespace Resource;
using namespace Device;
using namespace Math;
using namespace Importer;

TestScene::TestScene(void)
{

}

TestScene::~TestScene(void)
{
}

void TestScene::OnInitialize()
{
	_camera = new Object("Default");
	MeshCamera* cam = _camera->AddComponent<MeshCamera>();
	_camera->GetTransform()->UpdatePosition(Vector3(0, 0, 0));
	cam->SetFieldOfViewDegree(60.0f);

	const ResourceManager* resourceMgr = ResourceManager::GetInstance();
	MeshImporter* importer = resourceMgr->GetMeshImporter();

#if 0
	_testObject = importer->Load("./Resources/Capsule/capsule.obj");
	_testObject->GetTransform()->UpdatePosition(Vector3(0, 0, 5));
#else
	_testObject = importer->Load("./Resources/House/SanFranciscoHouse.fbx");
	_camera->GetTransform()->UpdatePosition(Vector3(0, 5, -15));
	_testObject->GetTransform()->UpdateEulerAngles(Vector3(-90, -90, 0));

	//_testObject = importer->Load("./Resources/CornellBox/box.obj", false);
	//_testObject->GetTransform()->UpdatePosition(Vector3(0, 0, 0));
	//_testObject->GetTransform()->UpdateEulerAngles(Vector3(-90, 180.0f, 180));
	//_testObject->GetTransform()->UpdateScale(Vector3(5, 5, 5));

	//_testObject2 = importer->Load("./Resources/CornellBox/box.obj", false);
	//_testObject2->GetTransform()->UpdatePosition(Vector3(0, 0, 0));
	//_testObject2->GetTransform()->UpdateEulerAngles(Vector3(-90, 180.0f, 180));
	//AddObject(_testObject2);
#endif
	AddObject(_testObject);

#if 0
	_light = new Object("Light");
	_light->GetTransform()->UpdateEulerAngles(Vector3(-60, -60, 0));
	_light->GetTransform()->UpdatePosition(Vector3(-1, 1.5,  12));

	SpotLight* light = _light->AddComponent<SpotLight>();
	light->SetLumen(150);
	light->SetRadius(10.0f);
	light->ActiveShadow(true);
	light->SetSpotAngleDegree(120.0f);
#elif 1
	_light = new Object("Light");
	_light->GetTransform()->UpdateEulerAngles(Vector3(315, 340, 0));
//	_light->GetTransform()->UpdateEulerAngles(Vector3(90, 0, 0));
	_light->GetTransform()->UpdatePosition(Vector3(0, 30, 0));

	DirectionalLight* light = _light->AddComponent<DirectionalLight>();
	light->SetProjectionSize(10);
	light->SetIntensity(1);
	light->SetUseAutoProjectionLocation(true);
	light->ActiveShadow(true);
#elif 0
	_light = new Object("Light");
	_light->GetTransform()->UpdateEulerAngles(Vector3(60, 60, 0));
	_light->GetTransform()->UpdatePosition(Vector3(-1, 1.5,  12));

	PointLight* light = _light->AddComponent<PointLight>();
	light->SetLumen(150);
	light->SetRadius(10.0f);
	light->ActiveShadow(true);
	light->GetShadow()->SetUnderScanSize(0.0f);
#endif

	AddObject(_light);
}

void TestScene::OnRenderPreview()
{
}

void TestScene::OnInput(const Device::Win32::Mouse& mouse, const  Device::Win32::Keyboard& keyboard)
{
	Transform* control = _light->GetTransform();
	float value = 1;

	if(keyboard.states['W'] == Win32::Keyboard::Type::Up)
	{
		Vector3 pos = control->GetLocalPosition();
		control->UpdatePosition(pos + Vector3(0, 0.1f, 0));
	}
	if(keyboard.states['A'] == Win32::Keyboard::Type::Up)
	{
		Vector3 pos = control->GetLocalPosition();
		control->UpdatePosition(pos + Vector3(-0.1f, 0, 0));
	}
	if(keyboard.states['S'] == Win32::Keyboard::Type::Up)
	{
		Vector3 pos = control->GetLocalPosition();
		control->UpdatePosition(pos + Vector3(0, -0.1f, 0));
	}
	if(keyboard.states['D'] == Win32::Keyboard::Type::Up)
	{
		Vector3 pos = control->GetLocalPosition();
		control->UpdatePosition(pos + Vector3(0.1f, 0, 0));
	}

	if(keyboard.states['T'] == Win32::Keyboard::Type::Up)
	{
		Vector3 pos = control->GetLocalPosition();
		control->UpdatePosition(pos + Vector3(0, 0, 0.1f));
	}
	if(keyboard.states['G'] == Win32::Keyboard::Type::Up)
	{
		Vector3 pos = control->GetLocalPosition();
		control->UpdatePosition(pos + Vector3(0, 0, -0.1f));
	}

	if(keyboard.states['U'] == Win32::Keyboard::Type::Up)
	{
		Vector3 e = control->GetLocalEulerAngle();
		control->UpdateEulerAngles(e + Vector3(5, 0, 0));
	}
	if(keyboard.states['J'] == Win32::Keyboard::Type::Up)
	{
		Vector3 e = control->GetLocalEulerAngle();
		control->UpdateEulerAngles(e + Vector3(-5, 0, 0));
	}
	if(keyboard.states['H'] == Win32::Keyboard::Type::Up)
	{
		Vector3 e = control->GetLocalEulerAngle();
		control->UpdateEulerAngles(e + Vector3(0, 5, 0));
	}
	if(keyboard.states['K'] == Win32::Keyboard::Type::Up)
	{
		Vector3 e = control->GetLocalEulerAngle();
		control->UpdateEulerAngles(e + Vector3(0, -5, 0));
	}

}

void TestScene::OnUpdate(float dt)
{
	//Transform* tf = _testObject->GetTransform();

	//Vector3 euler = tf->GetLocalEulerAngle();
	//tf->UpdateEulerAngles(euler - Vector3(0, 0.1f, 0));

	//Vector3 pos = tf->GetLocalPosition();
	//tf->UpdatePosition(pos - Vector3(0, 0.2f, 0));
}

void TestScene::OnRenderPost()
{

}

void TestScene::OnDestroy()
{

}<|endoftext|>


<commit_before>/*
 * DSP Multi-Signal Mixer Object
 * Copyright © 2009, Timothy Place
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTMultiMixer.h"
#ifdef TT_PLATFORM_WIN
#include <algorithm>
#endif

#define thisTTClass			TTMultiMixer
#define thisTTClassName		"multimixer"
#define thisTTClassTags		"audio, mixer, matrix"

TT_AUDIO_CONSTRUCTOR,
	mNumInputs(1),
	mNumOutputs(1),
	mGainMatrix(NULL),
	tempGainMatrix(NULL)
{
	TTObjectBaseInstantiate(kTTSym_matrix, (TTObjectBasePtr*)&mGainMatrix, 0);
	TTObjectBaseInstantiate(kTTSym_matrix, (TTObjectBasePtr*)&tempGainMatrix, 0);

	addAttribute(NumInputs, kTypeUInt16);
	addAttributeProperty(NumInputs,	readOnly, kTTBoolYes);
	addAttribute(NumOutputs, kTypeUInt16);
	addAttributeProperty(NumOutputs, readOnly, kTTBoolYes);

	addMessageWithArguments(setGain);
	addMessageWithArguments(setLinearGain);
	addMessageWithArguments(setMidiGain);
	//registerMessageWithArgument(updateMaxNumChannels);
	addMessage(clear);

	//setAttributeValue(TT("MaxNumChannels"), newMaxNumChannels);
	setProcessMethod(processAudio);
	mGainMatrix->setAttributeValue(TT("type"), TT("float64"));
	tempGainMatrix->setAttributeValue(TT("type"), TT("float64"));
	TTValue		v(1, 1); // we need to make the mGainMatrix at least 1x1 otherwise we have problems with adapting to tempGainMatrix
	mGainMatrix->setAttributeValue(TT("dimensions"), v);
	tempGainMatrix->setAttributeValue(TT("dimensions"), v);
	clear();
}

TTMultiMixer::~TTMultiMixer()
{
	TTObjectBaseRelease((TTObjectBasePtr*)&mGainMatrix);
	TTObjectBaseRelease((TTObjectBasePtr*)&tempGainMatrix);
}

// conceptually:
//	columns == inputs
//	rows == outputs

// TODO: the next two methods should never decrease their size

TTErr TTMultiMixer::setNumInputs(const TTUInt16 newValue)
{
	TTUInt16	numInputs = newValue;
	TTValue		v(numInputs, mNumOutputs);

	if (newValue != mNumInputs) {
		tempGainMatrix->adaptTo(mGainMatrix); //1. copy mGainMtrix to tempGainMatrix;
		TTMatrix::copy(*mGainMatrix, *tempGainMatrix);
		mNumInputs = numInputs;
		mGainMatrix->setAttributeValue(TT("dimensions"), v);
		clear();						//2. clear mGainMatrix
		restoreMatrix();				//3. element-wise copy tempGainMatrix content over to mGainMatrix
	}
	return kTTErrNone;
}

TTErr TTMultiMixer::setNumOutputs(const TTUInt16 newValue)
{
	TTUInt16	numOutputs = newValue;
	TTValue		v(mNumInputs, numOutputs);

	if (newValue != mNumOutputs) {
		tempGainMatrix->adaptTo(mGainMatrix); //1. copy mGainMtrix to tempGainMatrix;
		TTMatrix::copy(*mGainMatrix, *tempGainMatrix);
		mNumOutputs = newValue;
		mGainMatrix->setAttributeValue(TT("dimensions"), v);
		clear();						//2. clear mGainMatrix
		restoreMatrix();				//3. element-wise copy tempGainMatrix content over to mGainMatrix

	}
	return kTTErrNone;
}

TTErr TTMultiMixer::restoreMatrix()
{

	TTValue		v;
	TTFloat64	tempValue;
	TTUInt16	xx, yy;
	tempGainMatrix->getDimensions(v);
	v.get(0,xx);
	v.get(1,yy);
	TTLimit(xx,(TTUInt16) 1, mNumInputs); // in case xx or yy is greater than the current mGainMatrix ...
	TTLimit(yy,(TTUInt16) 1, mNumOutputs);
	for (TTUInt16 y=0; y < yy; y++) {
		for (TTUInt16 x=0; x < xx; x++) {
			tempGainMatrix->get2d(x, y, tempValue);
			mGainMatrix->set2d(x, y, tempValue);
		}
	}
	return kTTErrNone;
}

TTErr TTMultiMixer::clear()
{
	mGainMatrix->clear();
	return kTTErrNone;
}

TTErr TTMultiMixer::setGain(const TTValue& newValue, TTValue&)
{
	TTUInt16	x;
	TTUInt16	y;
	TTFloat64	gainValue;

	if (newValue.getSize() != 3)
		return kTTErrWrongNumValues;

	newValue.get(0, x);
	newValue.get(1, y);
	newValue.get(2, gainValue);
	checkMatrixSize(x,y);

	mGainMatrix->set2d(x, y, TTDecibelsToLinearGain(gainValue));
	return kTTErrNone;
}

TTErr TTMultiMixer::setLinearGain(const TTValue& newValue, TTValue&)
{
	TTUInt16	x;
	TTUInt16	y;
	TTFloat64	gainValue;

	if (newValue.getSize() != 3)
		return kTTErrWrongNumValues;

	newValue.get(0, x);
	newValue.get(1, y);
	newValue.get(2, gainValue);
	checkMatrixSize(x,y);

	mGainMatrix->set2d(x, y, gainValue);
	return kTTErrNone;
}

TTErr TTMultiMixer::setMidiGain(const TTValue& newValue, TTValue&e)
{
	TTUInt16	x;
	TTUInt16	y;
	TTFloat64	gainValue;

	if (newValue.getSize() != 3)
		return kTTErrWrongNumValues;

	newValue.get(0, x);
	newValue.get(1, y);
	newValue.get(2, gainValue);
	checkMatrixSize(x,y);

	mGainMatrix->set2d(x, y, TTMidiToLinearGain(gainValue));
	return kTTErrNone;
}

TTErr TTMultiMixer::checkMatrixSize(TTUInt16 x, TTUInt16 y)
//this function will resize mGainMatrix if necessary while preserving its content
{
	if (x > (mNumInputs-1)){
		if (y > (mNumOutputs-1))
			mNumOutputs = y+1;
		setNumInputs(x+1);
	}
	else{
		if (y > (mNumOutputs-1))
			setNumOutputs(y+1);
	}
	return kTTErrNone;
}

void TTMultiMixer::processOne(TTAudioSignal& in, TTAudioSignal& out, TTFloat64 gain)
{
	TTUInt16			vs, channel;
	TTSampleValuePtr	inSample, outSample;
	TTUInt16			numchannels = TTAudioSignal::getMinChannelCount(in, out);

	for (channel=0; channel<numchannels; channel++) {
		inSample = in.mSampleVectors[channel];
		outSample = out.mSampleVectors[channel];
		vs = in.getVectorSizeAsInt();

		while (vs--)
			*outSample++ += (*inSample++) * gain;
	}
}

/*	We are trying to calculate audio output from multiple audio inputs.
	So for each audio output:
		1. Start with a zero signal
		2. Then += each input signal, multiplied by its gain

	We may need to speed up this operation by iterating through the signals using direct access of the structs.
*/
TTErr TTMultiMixer::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{ //TODO: if mGainMatrix is sparse (i.e. it has a lot of zeros), we can do better than this algorithm which iterates through the entire matrix
#ifdef TT_PLATFORM_WIN
	TTUInt16 minChannelIn = min(mNumInputs,inputs->numAudioSignals);
#else
	TTUInt16 minChannelIn = std::min(mNumInputs,inputs->numAudioSignals);
#endif
	TTFloat64 gain;

	for (TTUInt16 y=0; y < outputs->numAudioSignals; y++) {
		TTAudioSignal&	out = outputs->getSignal(y);
		out.clear(); // zeroing output memory
		if (y < (mNumOutputs)){
			for (TTUInt16 x=0; x < minChannelIn; x++) {
				mGainMatrix->get2d(x, y, gain);
				if (gain){ //if the gain value is zero, just pass processOne
					TTAudioSignal&	in = inputs->getSignal(x);
					processOne(in, out, gain);
				}
			}
		}
	}
	return kTTErrNone;
}

<commit_msg>MathLib: removed two uses of kTTBoolYes, project now builds.<commit_after>/*
 * DSP Multi-Signal Mixer Object
 * Copyright © 2009, Timothy Place
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTMultiMixer.h"
#ifdef TT_PLATFORM_WIN
#include <algorithm>
#endif

#define thisTTClass			TTMultiMixer
#define thisTTClassName		"multimixer"
#define thisTTClassTags		"audio, mixer, matrix"

TT_AUDIO_CONSTRUCTOR,
	mNumInputs(1),
	mNumOutputs(1),
	mGainMatrix(NULL),
	tempGainMatrix(NULL)
{
	TTObjectBaseInstantiate(kTTSym_matrix, (TTObjectBasePtr*)&mGainMatrix, 0);
	TTObjectBaseInstantiate(kTTSym_matrix, (TTObjectBasePtr*)&tempGainMatrix, 0);

	addAttribute(NumInputs, kTypeUInt16);
	addAttributeProperty(NumInputs,	readOnly, TTValue(YES));
	addAttribute(NumOutputs, kTypeUInt16);
	addAttributeProperty(NumOutputs, readOnly, TTValue(YES));

	addMessageWithArguments(setGain);
	addMessageWithArguments(setLinearGain);
	addMessageWithArguments(setMidiGain);
	//registerMessageWithArgument(updateMaxNumChannels);
	addMessage(clear);

	//setAttributeValue(TT("MaxNumChannels"), newMaxNumChannels);
	setProcessMethod(processAudio);
	mGainMatrix->setAttributeValue(TT("type"), TT("float64"));
	tempGainMatrix->setAttributeValue(TT("type"), TT("float64"));
	TTValue		v(1, 1); // we need to make the mGainMatrix at least 1x1 otherwise we have problems with adapting to tempGainMatrix
	mGainMatrix->setAttributeValue(TT("dimensions"), v);
	tempGainMatrix->setAttributeValue(TT("dimensions"), v);
	clear();
}

TTMultiMixer::~TTMultiMixer()
{
	TTObjectBaseRelease((TTObjectBasePtr*)&mGainMatrix);
	TTObjectBaseRelease((TTObjectBasePtr*)&tempGainMatrix);
}

// conceptually:
//	columns == inputs
//	rows == outputs

// TODO: the next two methods should never decrease their size

TTErr TTMultiMixer::setNumInputs(const TTUInt16 newValue)
{
	TTUInt16	numInputs = newValue;
	TTValue		v(numInputs, mNumOutputs);

	if (newValue != mNumInputs) {
		tempGainMatrix->adaptTo(mGainMatrix); //1. copy mGainMtrix to tempGainMatrix;
		TTMatrix::copy(*mGainMatrix, *tempGainMatrix);
		mNumInputs = numInputs;
		mGainMatrix->setAttributeValue(TT("dimensions"), v);
		clear();						//2. clear mGainMatrix
		restoreMatrix();				//3. element-wise copy tempGainMatrix content over to mGainMatrix
	}
	return kTTErrNone;
}

TTErr TTMultiMixer::setNumOutputs(const TTUInt16 newValue)
{
	TTUInt16	numOutputs = newValue;
	TTValue		v(mNumInputs, numOutputs);

	if (newValue != mNumOutputs) {
		tempGainMatrix->adaptTo(mGainMatrix); //1. copy mGainMtrix to tempGainMatrix;
		TTMatrix::copy(*mGainMatrix, *tempGainMatrix);
		mNumOutputs = newValue;
		mGainMatrix->setAttributeValue(TT("dimensions"), v);
		clear();						//2. clear mGainMatrix
		restoreMatrix();				//3. element-wise copy tempGainMatrix content over to mGainMatrix

	}
	return kTTErrNone;
}

TTErr TTMultiMixer::restoreMatrix()
{

	TTValue		v;
	TTFloat64	tempValue;
	TTUInt16	xx, yy;
	tempGainMatrix->getDimensions(v);
	v.get(0,xx);
	v.get(1,yy);
	TTLimit(xx,(TTUInt16) 1, mNumInputs); // in case xx or yy is greater than the current mGainMatrix ...
	TTLimit(yy,(TTUInt16) 1, mNumOutputs);
	for (TTUInt16 y=0; y < yy; y++) {
		for (TTUInt16 x=0; x < xx; x++) {
			tempGainMatrix->get2d(x, y, tempValue);
			mGainMatrix->set2d(x, y, tempValue);
		}
	}
	return kTTErrNone;
}

TTErr TTMultiMixer::clear()
{
	mGainMatrix->clear();
	return kTTErrNone;
}

TTErr TTMultiMixer::setGain(const TTValue& newValue, TTValue&)
{
	TTUInt16	x;
	TTUInt16	y;
	TTFloat64	gainValue;

	if (newValue.getSize() != 3)
		return kTTErrWrongNumValues;

	newValue.get(0, x);
	newValue.get(1, y);
	newValue.get(2, gainValue);
	checkMatrixSize(x,y);

	mGainMatrix->set2d(x, y, TTDecibelsToLinearGain(gainValue));
	return kTTErrNone;
}

TTErr TTMultiMixer::setLinearGain(const TTValue& newValue, TTValue&)
{
	TTUInt16	x;
	TTUInt16	y;
	TTFloat64	gainValue;

	if (newValue.getSize() != 3)
		return kTTErrWrongNumValues;

	newValue.get(0, x);
	newValue.get(1, y);
	newValue.get(2, gainValue);
	checkMatrixSize(x,y);

	mGainMatrix->set2d(x, y, gainValue);
	return kTTErrNone;
}

TTErr TTMultiMixer::setMidiGain(const TTValue& newValue, TTValue&e)
{
	TTUInt16	x;
	TTUInt16	y;
	TTFloat64	gainValue;

	if (newValue.getSize() != 3)
		return kTTErrWrongNumValues;

	newValue.get(0, x);
	newValue.get(1, y);
	newValue.get(2, gainValue);
	checkMatrixSize(x,y);

	mGainMatrix->set2d(x, y, TTMidiToLinearGain(gainValue));
	return kTTErrNone;
}

TTErr TTMultiMixer::checkMatrixSize(TTUInt16 x, TTUInt16 y)
//this function will resize mGainMatrix if necessary while preserving its content
{
	if (x > (mNumInputs-1)){
		if (y > (mNumOutputs-1))
			mNumOutputs = y+1;
		setNumInputs(x+1);
	}
	else{
		if (y > (mNumOutputs-1))
			setNumOutputs(y+1);
	}
	return kTTErrNone;
}

void TTMultiMixer::processOne(TTAudioSignal& in, TTAudioSignal& out, TTFloat64 gain)
{
	TTUInt16			vs, channel;
	TTSampleValuePtr	inSample, outSample;
	TTUInt16			numchannels = TTAudioSignal::getMinChannelCount(in, out);

	for (channel=0; channel<numchannels; channel++) {
		inSample = in.mSampleVectors[channel];
		outSample = out.mSampleVectors[channel];
		vs = in.getVectorSizeAsInt();

		while (vs--)
			*outSample++ += (*inSample++) * gain;
	}
}

/*	We are trying to calculate audio output from multiple audio inputs.
	So for each audio output:
		1. Start with a zero signal
		2. Then += each input signal, multiplied by its gain

	We may need to speed up this operation by iterating through the signals using direct access of the structs.
*/
TTErr TTMultiMixer::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{ //TODO: if mGainMatrix is sparse (i.e. it has a lot of zeros), we can do better than this algorithm which iterates through the entire matrix
#ifdef TT_PLATFORM_WIN
	TTUInt16 minChannelIn = min(mNumInputs,inputs->numAudioSignals);
#else
	TTUInt16 minChannelIn = std::min(mNumInputs,inputs->numAudioSignals);
#endif
	TTFloat64 gain;

	for (TTUInt16 y=0; y < outputs->numAudioSignals; y++) {
		TTAudioSignal&	out = outputs->getSignal(y);
		out.clear(); // zeroing output memory
		if (y < (mNumOutputs)){
			for (TTUInt16 x=0; x < minChannelIn; x++) {
				mGainMatrix->get2d(x, y, gain);
				if (gain){ //if the gain value is zero, just pass processOne
					TTAudioSignal&	in = inputs->getSignal(x);
					processOne(in, out, gain);
				}
			}
		}
	}
	return kTTErrNone;
}

<|endoftext|>


<commit_before>/*
TidyEngine
Copyright (C) 2016 Jakob Sinclair

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

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
Contact the author at: jakob.sinclair99@gmail.com
*/

#include "core.hpp"
#include <GLFW/glfw3.h>
#include <FreeImage.h>
#include "shader.hpp"
#include "error.hpp"
#include "cache.hpp"
#include "config.hpp"

Core::Core()
{
	;
}

Core::~Core()
{
	;
}

void Core::Run()
{
        if (InitSubSystems() && Init()) {
                GameLoop();
        }
	Quit();
}

bool Core::InitSubSystems()
{
        if (glfwInit() == GL_FALSE)
                return false;

        FreeImage_Initialise();
        FreeImage_SetOutputMessage(FreeImageError);

	if(m_Screen.CreateWindow(1280, 720, "TidyEngine", 3, 3) != true) {
                printf("Error: glfw could not create window!\n");
                return false;
        } else {
                if (m_Screen.InitGL() == false) {
                        printf("Error: could not initialize OpenGL!\n");
                        return false;
                }
        }

        m_Render.LoadShaders("default", "shader.vert", "shader.frag",
        {"position", "color", "uv"});
        m_DrawSprite.Initialise(m_Render.GetShader("default"),
                        &m_Render.GetBatch());

        Resources.CreateTexture("default", "default.png");

        m_Input.Initialise(m_Screen.GetWindow());

        printf("TidyEngine Version: %d.%d\n",
               TidyEngine_VERSION_MAJOR, TidyEngine_VERSION_MINOR);

	return true;
}

void Core::GameLoop()
{
	printf("Main loop was entered.\n");
	m_Screen.GetWidth();
        while (!glfwWindowShouldClose(m_Screen.GetWindow())) {
                Update();
                DrawGame();
        }
        printf("Main loop was closed.\n");
}

void Core::Quit()
{
        glfwTerminate();
        FreeImage_DeInitialise();
}
<commit_msg>libTidyEngine: Added exception handling<commit_after>/*
TidyEngine
Copyright (C) 2016 Jakob Sinclair

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

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
Contact the author at: jakob.sinclair99@gmail.com
*/

#include "core.hpp"
#include <GLFW/glfw3.h>
#include <FreeImage.h>
#include "shader.hpp"
#include "error.hpp"
#include "cache.hpp"
#include "config.hpp"

Core::Core()
{
	;
}

Core::~Core()
{
	;
}

void Core::Run()
{
        if (InitSubSystems() && Init()) {
                GameLoop();
        }
	Quit();
}

bool Core::InitSubSystems()
{
        if (glfwInit() == GL_FALSE)
                return false;

        FreeImage_Initialise();
        FreeImage_SetOutputMessage(FreeImageError);

	if(m_Screen.CreateWindow(1280, 720, "TidyEngine", 3, 3) != true) {
                printf("Error: glfw could not create window!\n");
                return false;
        } else {
                if (m_Screen.InitGL() == false) {
                        printf("Error: could not initialize OpenGL!\n");
                        return false;
                }
        }

        try {
                m_Render.LoadShaders("default", "shader.vert", "shader.frag",
                {"position", "color", "uv"});
        }
        catch (std::exception &e) {
                printf("Error: Could not load default texture: default.png\n");
                return false;
        }
        m_DrawSprite.Initialise(m_Render.GetShader("default"),
                        &m_Render.GetBatch());

        try {
                Resources.CreateTexture("default", "default.png");
        }
        catch (std::exception &e) {
                printf("Error: Could not load default texture: default.png\n");
                return false;
        }

        m_Input.Initialise(m_Screen.GetWindow());

        printf("TidyEngine Version: %d.%d\n",
               TidyEngine_VERSION_MAJOR, TidyEngine_VERSION_MINOR);

	return true;
}

void Core::GameLoop()
{
	printf("Main loop was entered.\n");
	m_Screen.GetWidth();
        while (!glfwWindowShouldClose(m_Screen.GetWindow())) {
                Update();
                DrawGame();
        }
        printf("Main loop was closed.\n");
}

void Core::Quit()
{
        glfwTerminate();
        FreeImage_DeInitialise();
}
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.

#ifndef MIDDLEWARE_PARSLEY_HPP
#define MIDDLEWARE_PARSLEY_HPP

#include "json.hpp"
#include "middleware.hpp"

namespace middleware {

/**
 * @brief A vegan way to parse JSON Content in a response
 * @details TBC..
 *
 */
class Parsley : public server::Middleware {
public:
  /**
   *
   */
  virtual void process(server::Request_ptr req, server::Response_ptr, server::Next next) override;

private:
  /**
   *
   */
  bool has_json(server::Request_ptr req) const;
}; //< class Parsley

/**--v----------- Implementation Details -----------v--**/

inline void Parsley::process(server::Request_ptr req, server::Response_ptr, server::Next next) {
  if(not has_json(req)) return (*next)();

  // Request doesn't have JSON attribute
  if(not req->has_attribute<json::Json_doc>()) {
    // Create attribute
    auto json = std::make_shared<json::Json_doc>();

    // Access the document and parse the body
    json->doc().Parse(req->get_body().c_str());
    #ifdef VERBOSE_WEBSERVER
    printf("<Parsley> Parsed JSON data.\n");
    #endif

    // Add the json attribute to the request
    req->set_attribute(json);
  }

  return (*next)();
}

inline bool Parsley::has_json(server::Request_ptr req) const {
  auto c_type = http::header_fields::Entity::Content_Type;
  if(not req->has_header(c_type)) return false;
  return (req->header_value(c_type).find("application/json") != std::string::npos);
}

/**--^----------- Implementation Details -----------^--**/

} //< namespace middleware

#endif //< MIDDLEWARE_PARSLEY_HPP
<commit_msg>Server: Call to middleware no longer virtual + minor improvements<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.

#ifndef MIDDLEWARE_PARSLEY_HPP
#define MIDDLEWARE_PARSLEY_HPP

#include "json.hpp"
#include "middleware.hpp"

namespace middleware {

/**
 * @brief A vegan way to parse JSON Content in a response
 * @details TBC..
 *
 */
class Parsley : public server::Middleware {
public:

  server::Callback handler() override {
    return {this, &Parsley::process};
  }
  /**
   *
   */
  void process(server::Request_ptr req, server::Response_ptr, server::Next next);

private:
  /**
   *
   */
  bool has_json(const server::Request& req) const;
}; //< class Parsley

/**--v----------- Implementation Details -----------v--**/

inline void Parsley::process(server::Request_ptr req, server::Response_ptr, server::Next next) {

  // Request doesn't have JSON attribute
  if(has_json(*req) and not req->has_attribute<json::Json_doc>())
  {
    // Create attribute
    auto json = std::make_shared<json::Json_doc>();

    // Access the document and parse the body
    try {
      json->doc().Parse(req->get_body().c_str());
      #ifdef VERBOSE_WEBSERVER
      printf("<Parsley> Parsed JSON data.\n");
      #endif

      // Add the json attribute to the request
      req->set_attribute(std::move(json));
    }
    catch(const Assert_error& e) {
      printf("<Parsley> Parsing error.\n");
    }

  }

  return (*next)();
}

inline bool Parsley::has_json(const server::Request& req) const {
  auto c_type = http::header_fields::Entity::Content_Type;
  if(not req.has_header(c_type)) return false;
  return (req.header_value(c_type).find("application/json") != std::string::npos);
}

/**--^----------- Implementation Details -----------^--**/

} //< namespace middleware

#endif //< MIDDLEWARE_PARSLEY_HPP
<|endoftext|>