<commit_before>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

#pragma once

#if !defined(RXCPP_RX_NOTIFICATION_HPP)
#define RXCPP_RX_NOTIFICATION_HPP

#include "rx-includes.hpp"

namespace rxcpp {

namespace notifications {

class subscription
{
    long s;
    long u;

public:
    explicit inline subscription(long s)
        : s(s), u(std::numeric_limits<long>::max()) {
    }
    inline subscription(long s, long u)
        : s(s), u(u) {
    }
    inline long subscribe() const {
        return s;
    }
    inline long unsubscribe() const {
        return u;
    }
};

inline bool operator == (subscription lhs, subscription rhs) {
    return lhs.subscribe() == rhs.subscribe() && lhs.unsubscribe() == rhs.unsubscribe();
}

inline std::ostream& operator<< (std::ostream& out, const subscription& s) {
    out << s.subscribe() << "-" << s.unsubscribe();
    return out;
}

namespace detail {

template<typename T>
struct notification_base
    : public std::enable_shared_from_this<notification_base<T>>
{
    typedef subscriber<T> observer_type;
    typedef std::shared_ptr<notification_base<T>> type;

    virtual ~notification_base() {}

    virtual void out(std::ostream& out) const =0;
    virtual bool equals(const type& other) const = 0;
    virtual void accept(const observer_type& o) const =0;
};

template<class T>
std::ostream& operator<< (std::ostream& out, const std::vector<T>& v);

template<class T>
auto to_stream(std::ostream& os, const T& t, int, int)
    -> decltype(os << t) {
    return      os << t;
}

#if RXCPP_USE_RTTI
template<class T>
std::ostream& to_stream(std::ostream& os, const T&, int, ...) {
    return os << "< " << typeid(T).name() << " does not support ostream>";
}
#endif

template<class T>
std::ostream& to_stream(std::ostream& os, const T&, ...) {
    return os << "<the value does not support ostream>";
}

template<class T>
inline std::ostream& ostreamvector (std::ostream& os, const std::vector<T>& v) {
    os << "[";
    bool emit = false;
    for(auto& i : v) {
        if (emit) {
            os << ", ";
        } else {
            emit = true;
        }
        to_stream(os, i, 0, 0);
    }
    os << "]";
    return os;
}

template<class T>
inline std::ostream& operator<< (std::ostream& os, const std::vector<T>& v) {
    return ostreamvector(os, v);
}

template<class T>
auto equals(const T& lhs, const T& rhs, int)
    -> decltype(bool(lhs == rhs)) {
    return lhs == rhs;
}

template<class T>
bool equals(const T&, const T&, ...) {
    throw std::runtime_error("value does not support equality tests");
    return false;
}

}

template<typename T>
struct notification
{
    typedef typename detail::notification_base<T>::type type;
    typedef typename detail::notification_base<T>::observer_type observer_type;

private:
    typedef detail::notification_base<T> base;

    struct on_next_notification : public base {
        on_next_notification(T value) : value(std::move(value)) {
        }
        on_next_notification(const on_next_notification& o) : value(o.value) {}
        on_next_notification(const on_next_notification&& o) : value(std::move(o.value)) {}
        on_next_notification& operator=(on_next_notification o) { value = std::move(o.value); return *this; }
        virtual void out(std::ostream& os) const {
            os << "on_next( ";
            detail::to_stream(os, value, 0, 0);
            os << ")";
        }
        virtual bool equals(const typename base::type& other) const {
            bool result = false;
            other->accept(make_subscriber<T>(make_observer_dynamic<T>([this, &result](T v) {
                    result = detail::equals(this->value, v, 0);
                })));
            return result;
        }
        virtual void accept(const typename base::observer_type& o) const {
            o.on_next(value);
        }
        const T value;
    };

    struct on_error_notification : public base {
        on_error_notification(std::exception_ptr ep) : ep(ep) {
        }
        on_error_notification(const on_error_notification& o) : ep(o.ep) {}
        on_error_notification(const on_error_notification&& o) : ep(std::move(o.ep)) {}
        on_error_notification& operator=(on_error_notification o) { ep = std::move(o.ep); return *this; }
        virtual void out(std::ostream& os) const {
            os << "on_error(";
            try {
                std::rethrow_exception(ep);
            } catch (const std::exception& e) {
                os << e.what();
            } catch (...) {
                os << "<not derived from std::exception>";
            }
            os << ")";
        }
        virtual bool equals(const typename base::type& other) const {
            bool result = false;
            // not trying to compare exceptions
            other->accept(make_subscriber<T>(make_observer_dynamic<T>([](T){}, [&result](std::exception_ptr){
                result = true;
            })));
            return result;
        }
        virtual void accept(const typename base::observer_type& o) const {
            o.on_error(ep);
        }
        const std::exception_ptr ep;
    };

    struct on_completed_notification : public base {
        on_completed_notification() {
        }
        virtual void out(std::ostream& os) const {
            os << "on_completed()";
        }
        virtual bool equals(const typename base::type& other) const {
            bool result = false;
            other->accept(make_subscriber<T>(make_observer_dynamic<T>([](T){}, [&result](){
                result = true;
            })));
            return result;
        }
        virtual void accept(const typename base::observer_type& o) const {
            o.on_completed();
        }
    };

    struct exception_tag {};

    template<typename Exception>
    static
    type make_on_error(exception_tag&&, Exception&& e) {
        std::exception_ptr ep;
        try {
            throw std::forward<Exception>(e);
        }
        catch (...) {
            ep = std::current_exception();
        }
        return std::make_shared<on_error_notification>(ep);
    }

    struct exception_ptr_tag {};

    static
    type make_on_error(exception_ptr_tag&&, std::exception_ptr ep) {
        return std::make_shared<on_error_notification>(ep);
    }

public:
    template<typename U>
    static type on_next(U value) {
        return std::make_shared<on_next_notification>(std::move(value));
    }

    static type on_completed() {
        return std::make_shared<on_completed_notification>();
    }

    template<typename Exception>
    static type on_error(Exception&& e) {
        return make_on_error(typename std::conditional<
            std::is_same<rxu::decay_t<Exception>, std::exception_ptr>::value,
                exception_ptr_tag, exception_tag>::type(),
            std::forward<Exception>(e));
    }
};

template<class T>
bool operator == (const std::shared_ptr<detail::notification_base<T>>& lhs, const std::shared_ptr<detail::notification_base<T>>& rhs) {
    if (!lhs && !rhs) {return true;}
    if (!lhs || !rhs) {return false;}
    return lhs->equals(rhs);
}

template<class T>
std::ostream& operator<< (std::ostream& os, const std::shared_ptr<detail::notification_base<T>>& n) {
    n->out(os);
    return os;
}

template<class T>
class recorded
{
    long t;
    T v;
public:
    recorded(long t, T v)
        : t(t), v(v) {
    }
    long time() const {
        return t;
    }
    const T& value() const {
        return v;
    }
};

template<class T>
bool operator == (recorded<T> lhs, recorded<T> rhs) {
    return lhs.time() == rhs.time() && lhs.value() == rhs.value();
}

template<class T>
std::ostream& operator<< (std::ostream& out, const recorded<T>& r) {
    out << "@" << r.time() << "-" << r.value();
    return out;
}

}
namespace rxn=notifications;

}

inline std::ostream& operator<< (std::ostream& out, const std::vector<rxcpp::notifications::subscription>& vs) {
    return rxcpp::notifications::detail::ostreamvector(out, vs);
}
template<class T>
inline std::ostream& operator<< (std::ostream& out, const std::vector<rxcpp::notifications::recorded<T>>& vr) {
    return rxcpp::notifications::detail::ostreamvector(out, vr);
}

#endif
<commit_msg>Removed naming conflict with Qt's emit define<commit_after>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

#pragma once

#if !defined(RXCPP_RX_NOTIFICATION_HPP)
#define RXCPP_RX_NOTIFICATION_HPP

#include "rx-includes.hpp"

namespace rxcpp {

namespace notifications {

class subscription
{
    long s;
    long u;

public:
    explicit inline subscription(long s)
        : s(s), u(std::numeric_limits<long>::max()) {
    }
    inline subscription(long s, long u)
        : s(s), u(u) {
    }
    inline long subscribe() const {
        return s;
    }
    inline long unsubscribe() const {
        return u;
    }
};

inline bool operator == (subscription lhs, subscription rhs) {
    return lhs.subscribe() == rhs.subscribe() && lhs.unsubscribe() == rhs.unsubscribe();
}

inline std::ostream& operator<< (std::ostream& out, const subscription& s) {
    out << s.subscribe() << "-" << s.unsubscribe();
    return out;
}

namespace detail {

template<typename T>
struct notification_base
    : public std::enable_shared_from_this<notification_base<T>>
{
    typedef subscriber<T> observer_type;
    typedef std::shared_ptr<notification_base<T>> type;

    virtual ~notification_base() {}

    virtual void out(std::ostream& out) const =0;
    virtual bool equals(const type& other) const = 0;
    virtual void accept(const observer_type& o) const =0;
};

template<class T>
std::ostream& operator<< (std::ostream& out, const std::vector<T>& v);

template<class T>
auto to_stream(std::ostream& os, const T& t, int, int)
    -> decltype(os << t) {
    return      os << t;
}

#if RXCPP_USE_RTTI
template<class T>
std::ostream& to_stream(std::ostream& os, const T&, int, ...) {
    return os << "< " << typeid(T).name() << " does not support ostream>";
}
#endif

template<class T>
std::ostream& to_stream(std::ostream& os, const T&, ...) {
    return os << "<the value does not support ostream>";
}

template<class T>
inline std::ostream& ostreamvector (std::ostream& os, const std::vector<T>& v) {
    os << "[";
    bool doemit = false;
    for(auto& i : v) {
        if (doemit) {
            os << ", ";
        } else {
            doemit = true;
        }
        to_stream(os, i, 0, 0);
    }
    os << "]";
    return os;
}

template<class T>
inline std::ostream& operator<< (std::ostream& os, const std::vector<T>& v) {
    return ostreamvector(os, v);
}

template<class T>
auto equals(const T& lhs, const T& rhs, int)
    -> decltype(bool(lhs == rhs)) {
    return lhs == rhs;
}

template<class T>
bool equals(const T&, const T&, ...) {
    throw std::runtime_error("value does not support equality tests");
    return false;
}

}

template<typename T>
struct notification
{
    typedef typename detail::notification_base<T>::type type;
    typedef typename detail::notification_base<T>::observer_type observer_type;

private:
    typedef detail::notification_base<T> base;

    struct on_next_notification : public base {
        on_next_notification(T value) : value(std::move(value)) {
        }
        on_next_notification(const on_next_notification& o) : value(o.value) {}
        on_next_notification(const on_next_notification&& o) : value(std::move(o.value)) {}
        on_next_notification& operator=(on_next_notification o) { value = std::move(o.value); return *this; }
        virtual void out(std::ostream& os) const {
            os << "on_next( ";
            detail::to_stream(os, value, 0, 0);
            os << ")";
        }
        virtual bool equals(const typename base::type& other) const {
            bool result = false;
            other->accept(make_subscriber<T>(make_observer_dynamic<T>([this, &result](T v) {
                    result = detail::equals(this->value, v, 0);
                })));
            return result;
        }
        virtual void accept(const typename base::observer_type& o) const {
            o.on_next(value);
        }
        const T value;
    };

    struct on_error_notification : public base {
        on_error_notification(std::exception_ptr ep) : ep(ep) {
        }
        on_error_notification(const on_error_notification& o) : ep(o.ep) {}
        on_error_notification(const on_error_notification&& o) : ep(std::move(o.ep)) {}
        on_error_notification& operator=(on_error_notification o) { ep = std::move(o.ep); return *this; }
        virtual void out(std::ostream& os) const {
            os << "on_error(";
            try {
                std::rethrow_exception(ep);
            } catch (const std::exception& e) {
                os << e.what();
            } catch (...) {
                os << "<not derived from std::exception>";
            }
            os << ")";
        }
        virtual bool equals(const typename base::type& other) const {
            bool result = false;
            // not trying to compare exceptions
            other->accept(make_subscriber<T>(make_observer_dynamic<T>([](T){}, [&result](std::exception_ptr){
                result = true;
            })));
            return result;
        }
        virtual void accept(const typename base::observer_type& o) const {
            o.on_error(ep);
        }
        const std::exception_ptr ep;
    };

    struct on_completed_notification : public base {
        on_completed_notification() {
        }
        virtual void out(std::ostream& os) const {
            os << "on_completed()";
        }
        virtual bool equals(const typename base::type& other) const {
            bool result = false;
            other->accept(make_subscriber<T>(make_observer_dynamic<T>([](T){}, [&result](){
                result = true;
            })));
            return result;
        }
        virtual void accept(const typename base::observer_type& o) const {
            o.on_completed();
        }
    };

    struct exception_tag {};

    template<typename Exception>
    static
    type make_on_error(exception_tag&&, Exception&& e) {
        std::exception_ptr ep;
        try {
            throw std::forward<Exception>(e);
        }
        catch (...) {
            ep = std::current_exception();
        }
        return std::make_shared<on_error_notification>(ep);
    }

    struct exception_ptr_tag {};

    static
    type make_on_error(exception_ptr_tag&&, std::exception_ptr ep) {
        return std::make_shared<on_error_notification>(ep);
    }

public:
    template<typename U>
    static type on_next(U value) {
        return std::make_shared<on_next_notification>(std::move(value));
    }

    static type on_completed() {
        return std::make_shared<on_completed_notification>();
    }

    template<typename Exception>
    static type on_error(Exception&& e) {
        return make_on_error(typename std::conditional<
            std::is_same<rxu::decay_t<Exception>, std::exception_ptr>::value,
                exception_ptr_tag, exception_tag>::type(),
            std::forward<Exception>(e));
    }
};

template<class T>
bool operator == (const std::shared_ptr<detail::notification_base<T>>& lhs, const std::shared_ptr<detail::notification_base<T>>& rhs) {
    if (!lhs && !rhs) {return true;}
    if (!lhs || !rhs) {return false;}
    return lhs->equals(rhs);
}

template<class T>
std::ostream& operator<< (std::ostream& os, const std::shared_ptr<detail::notification_base<T>>& n) {
    n->out(os);
    return os;
}

template<class T>
class recorded
{
    long t;
    T v;
public:
    recorded(long t, T v)
        : t(t), v(v) {
    }
    long time() const {
        return t;
    }
    const T& value() const {
        return v;
    }
};

template<class T>
bool operator == (recorded<T> lhs, recorded<T> rhs) {
    return lhs.time() == rhs.time() && lhs.value() == rhs.value();
}

template<class T>
std::ostream& operator<< (std::ostream& out, const recorded<T>& r) {
    out << "@" << r.time() << "-" << r.value();
    return out;
}

}
namespace rxn=notifications;

}

inline std::ostream& operator<< (std::ostream& out, const std::vector<rxcpp::notifications::subscription>& vs) {
    return rxcpp::notifications::detail::ostreamvector(out, vs);
}
template<class T>
inline std::ostream& operator<< (std::ostream& out, const std::vector<rxcpp::notifications::recorded<T>>& vr) {
    return rxcpp::notifications::detail::ostreamvector(out, vr);
}

#endif
<|endoftext|>


<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 "SamplePlugin.h"
#include "VolumeCSG.h"

#include "OgreVolumeCSGSource.h"
#include "OgreVolumeCacheSource.h"
#include "OgreVolumeTextureSource.h"
#include "OgreVolumeMeshBuilder.h"
#include "OgreMath.h"

using namespace Ogre;
using namespace OgreBites;
using namespace Ogre::Volume;

void Sample_VolumeCSG::setupContent(void)
{
    setupControls();
    setupShaderGenerator();
    Real size = (Real)31.0;
    Vector3 to(size);

    // Light
    Light* directionalLight0 = mSceneMgr->createLight("directionalLight0");
    directionalLight0->setType(Light::LT_DIRECTIONAL);
    directionalLight0->setDirection(Vector3((Real)1, (Real)-1, (Real)1));
    directionalLight0->setDiffuseColour((Real)1, (Real)0.98, (Real)0.73);
    directionalLight0->setSpecularColour((Real)0.1, (Real)0.1, (Real)0.1);

    // Spheres
    CSGSphereSource sphere1((Real)5.0, Vector3((Real)5.5));
    CSGSphereSource sphere2((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)5.5));
    CSGSphereSource sphere3((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)25.5));
    CSGSphereSource sphere4((Real)5.0, Vector3((Real)5.5, (Real)5.5, (Real)25.5));

    // Cubes
    Real halfWidth = (Real)(2.5 / 2.0);
    CSGCubeSource cube1(Vector3((Real)5.5 - halfWidth), Vector3((Real)25.5 + halfWidth, (Real)5.5 + halfWidth, (Real)25.5 + halfWidth));
    CSGCubeSource cube2(Vector3((Real)5.5 + halfWidth, (Real)0.0, (Real)5.5 + halfWidth), Vector3((Real)25.5 - halfWidth, to.y, (Real)25.5 - halfWidth));
    CSGDifferenceSource difference1(&cube1, &cube2);

    // Inner rounded cube
    Real innerHalfWidth = (Real)(7.0 / 2.0);
    Vector3 center((Real)15.5, (Real)5.5, (Real)15.5);
    CSGCubeSource cube3(center - innerHalfWidth, center + innerHalfWidth);
    CSGSphereSource sphere5(innerHalfWidth + (Real)0.75, center);
    CSGIntersectionSource intersection1(&cube3, &sphere5);

    // A plane with noise
    CSGPlaneSource plane1((Real)1.0, Vector3::UNIT_Y);
    Real frequencies[] = {(Real)1.01, (Real)0.48};
    Real amplitudes[] = {(Real)0.25, (Real)0.5};
    CSGNoiseSource noise1(&plane1, frequencies, amplitudes, 2, 100);

    // Combine everything
    CSGUnionSource union1(&sphere1, &sphere2);
    CSGUnionSource union2(&union1, &sphere3);
    CSGUnionSource union3(&union2, &sphere4);
    CSGUnionSource union4(&union3, &difference1);
    CSGUnionSource union5(&union4, &intersection1);
    CSGUnionSource union6(&union5, &noise1);
    Source *src = &union6;

    mVolumeRoot = OGRE_NEW Chunk();
    SceneNode *volumeRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("VolumeParent");

    ChunkParameters parameters;
    parameters.sceneManager = mSceneMgr;
    parameters.src = src;
    parameters.baseError = (Real)0.25;

    mVolumeRoot->load(volumeRootNode, Vector3::ZERO, to, 1, &parameters);

    mVolumeRoot->setMaterial("Ogre/RTShader/TriplanarTexturing");

    // Camera
    mCamera->setPosition(to + (Real)7.5);
    mCamera->lookAt(center + (Real)11.0);
    mCamera->setNearClipDistance((Real)0.5);

    mRotation = (Real)0.0;

}

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

void Sample_VolumeCSG::setupControls(void)
{
    mTrayMgr->showCursor();
#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS
        setDragLook(true);
#endif
    mCameraMan->setStyle(OgreBites::CS_MANUAL);
    mCameraMan->setTopSpeed((Real)25.0);
    // make room for the volume
    mTrayMgr->showLogo(TL_TOPRIGHT);
    mTrayMgr->showFrameStats(TL_TOPRIGHT);
    mTrayMgr->toggleAdvancedFrameStats();
}

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

void Sample_VolumeCSG::setupShaderGenerator()
{
    RTShader::ShaderGenerator* mGen = RTShader::ShaderGenerator::getSingletonPtr();

    RTShader::RenderState* pMainRenderState =
        mGen->createOrRetrieveRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first;
    pMainRenderState->reset();

    mGen->invalidateScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);

    // Make this viewport work with shader generator scheme.
    mViewport->setMaterialScheme(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);
}

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

void Sample_VolumeCSG::cleanupContent(void)
{
    OGRE_DELETE mVolumeRoot;
    mVolumeRoot = 0;
}

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

Sample_VolumeCSG::Sample_VolumeCSG(void) : mVolumeRoot(0), mHideAll(false)
{
    mInfo["Title"] = "Volume CSG and RTSS triplanar texturing";
    mInfo["Description"] = "Demonstrates a volumetric CSG scene, showing sphere, cube, plane, union, difference and intersection. The triplanar texturing is generated by the RTSS.";
    mInfo["Thumbnail"] = "thumb_volumecsg.png";
    mInfo["Category"] = "Geometry";
}

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

bool Sample_VolumeCSG::keyPressed(const OIS::KeyEvent& evt)
{
    if (evt.key == OIS::KC_H)
    {
        if (mHideAll)
        {
            mTrayMgr->showAll();
        }
        else
        {
            mTrayMgr->hideAll();
        }
        mHideAll = !mHideAll;
    }
    return SdkSample::keyPressed(evt);
}

bool Sample_VolumeCSG::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
    Vector3 center((Real)15.5, (Real)5.5, (Real)15.5);
    mRotation += Radian(evt.timeSinceLastFrame * (Real)0.5);
    Real r = (Real)35.0;
    mCamera->setPosition(
        Math::Sin(mRotation) * r + center.x,
        (Real)15.0 + center.y,
        Math::Cos(mRotation) * r + center.z
    );
    mCamera->lookAt(center);
    return SdkSample::frameRenderingQueued(evt);
}

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

void Sample_VolumeCSG::_shutdown()
{
    RTShader::RenderState* pMainRenderState =
        RTShader::ShaderGenerator::getSingleton().createOrRetrieveRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first;
    pMainRenderState->reset();

    SdkSample::_shutdown();
}

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

#ifndef OGRE_STATIC_LIB

SamplePlugin* sp;
Sample* s;

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

extern "C" _OgreSampleExport void dllStartPlugin()
{
    s = new Sample_VolumeCSG();
    sp = OGRE_NEW SamplePlugin(s->getInfo()["Title"] + " Sample");
    sp->addSample(s);
    Root::getSingleton().installPlugin(sp);
}

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

extern "C" _OgreSampleExport void dllStopPlugin()
{
    Root::getSingleton().uninstallPlugin(sp);
    OGRE_DELETE sp;
    delete s;
}

#endif
<commit_msg>Volume Rendering: Shortened the sample label of the CSG demo so it no longer breaks the UI.<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 "SamplePlugin.h"
#include "VolumeCSG.h"

#include "OgreVolumeCSGSource.h"
#include "OgreVolumeCacheSource.h"
#include "OgreVolumeTextureSource.h"
#include "OgreVolumeMeshBuilder.h"
#include "OgreMath.h"

using namespace Ogre;
using namespace OgreBites;
using namespace Ogre::Volume;

void Sample_VolumeCSG::setupContent(void)
{
    setupControls();
    setupShaderGenerator();
    Real size = (Real)31.0;
    Vector3 to(size);

    // Light
    Light* directionalLight0 = mSceneMgr->createLight("directionalLight0");
    directionalLight0->setType(Light::LT_DIRECTIONAL);
    directionalLight0->setDirection(Vector3((Real)1, (Real)-1, (Real)1));
    directionalLight0->setDiffuseColour((Real)1, (Real)0.98, (Real)0.73);
    directionalLight0->setSpecularColour((Real)0.1, (Real)0.1, (Real)0.1);

    // Spheres
    CSGSphereSource sphere1((Real)5.0, Vector3((Real)5.5));
    CSGSphereSource sphere2((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)5.5));
    CSGSphereSource sphere3((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)25.5));
    CSGSphereSource sphere4((Real)5.0, Vector3((Real)5.5, (Real)5.5, (Real)25.5));

    // Cubes
    Real halfWidth = (Real)(2.5 / 2.0);
    CSGCubeSource cube1(Vector3((Real)5.5 - halfWidth), Vector3((Real)25.5 + halfWidth, (Real)5.5 + halfWidth, (Real)25.5 + halfWidth));
    CSGCubeSource cube2(Vector3((Real)5.5 + halfWidth, (Real)0.0, (Real)5.5 + halfWidth), Vector3((Real)25.5 - halfWidth, to.y, (Real)25.5 - halfWidth));
    CSGDifferenceSource difference1(&cube1, &cube2);

    // Inner rounded cube
    Real innerHalfWidth = (Real)(7.0 / 2.0);
    Vector3 center((Real)15.5, (Real)5.5, (Real)15.5);
    CSGCubeSource cube3(center - innerHalfWidth, center + innerHalfWidth);
    CSGSphereSource sphere5(innerHalfWidth + (Real)0.75, center);
    CSGIntersectionSource intersection1(&cube3, &sphere5);

    // A plane with noise
    CSGPlaneSource plane1((Real)1.0, Vector3::UNIT_Y);
    Real frequencies[] = {(Real)1.01, (Real)0.48};
    Real amplitudes[] = {(Real)0.25, (Real)0.5};
    CSGNoiseSource noise1(&plane1, frequencies, amplitudes, 2, 100);

    // Combine everything
    CSGUnionSource union1(&sphere1, &sphere2);
    CSGUnionSource union2(&union1, &sphere3);
    CSGUnionSource union3(&union2, &sphere4);
    CSGUnionSource union4(&union3, &difference1);
    CSGUnionSource union5(&union4, &intersection1);
    CSGUnionSource union6(&union5, &noise1);
    Source *src = &union6;

    mVolumeRoot = OGRE_NEW Chunk();
    SceneNode *volumeRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("VolumeParent");

    ChunkParameters parameters;
    parameters.sceneManager = mSceneMgr;
    parameters.src = src;
    parameters.baseError = (Real)0.25;

    mVolumeRoot->load(volumeRootNode, Vector3::ZERO, to, 1, &parameters);

    mVolumeRoot->setMaterial("Ogre/RTShader/TriplanarTexturing");

    // Camera
    mCamera->setPosition(to + (Real)7.5);
    mCamera->lookAt(center + (Real)11.0);
    mCamera->setNearClipDistance((Real)0.5);

    mRotation = (Real)0.0;

}

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

void Sample_VolumeCSG::setupControls(void)
{
    mTrayMgr->showCursor();
#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS
        setDragLook(true);
#endif
    mCameraMan->setStyle(OgreBites::CS_MANUAL);
    mCameraMan->setTopSpeed((Real)25.0);
    // make room for the volume
    mTrayMgr->showLogo(TL_TOPRIGHT);
    mTrayMgr->showFrameStats(TL_TOPRIGHT);
    mTrayMgr->toggleAdvancedFrameStats();
}

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

void Sample_VolumeCSG::setupShaderGenerator()
{
    RTShader::ShaderGenerator* mGen = RTShader::ShaderGenerator::getSingletonPtr();

    RTShader::RenderState* pMainRenderState =
        mGen->createOrRetrieveRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first;
    pMainRenderState->reset();

    mGen->invalidateScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);

    // Make this viewport work with shader generator scheme.
    mViewport->setMaterialScheme(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);
}

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

void Sample_VolumeCSG::cleanupContent(void)
{
    OGRE_DELETE mVolumeRoot;
    mVolumeRoot = 0;
}

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

Sample_VolumeCSG::Sample_VolumeCSG(void) : mVolumeRoot(0), mHideAll(false)
{
    mInfo["Title"] = "Volume CSG";
    mInfo["Description"] = "Demonstrates a volumetric constructive solid geometry scene, showing sphere, cube, plane, union, difference and intersection. The triplanar texturing is generated by the RTSS.";
    mInfo["Thumbnail"] = "thumb_volumecsg.png";
    mInfo["Category"] = "Geometry";
}

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

bool Sample_VolumeCSG::keyPressed(const OIS::KeyEvent& evt)
{
    if (evt.key == OIS::KC_H)
    {
        if (mHideAll)
        {
            mTrayMgr->showAll();
        }
        else
        {
            mTrayMgr->hideAll();
        }
        mHideAll = !mHideAll;
    }
    return SdkSample::keyPressed(evt);
}

bool Sample_VolumeCSG::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
    Vector3 center((Real)15.5, (Real)5.5, (Real)15.5);
    mRotation += Radian(evt.timeSinceLastFrame * (Real)0.5);
    Real r = (Real)35.0;
    mCamera->setPosition(
        Math::Sin(mRotation) * r + center.x,
        (Real)15.0 + center.y,
        Math::Cos(mRotation) * r + center.z
    );
    mCamera->lookAt(center);
    return SdkSample::frameRenderingQueued(evt);
}

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

void Sample_VolumeCSG::_shutdown()
{
    RTShader::RenderState* pMainRenderState =
        RTShader::ShaderGenerator::getSingleton().createOrRetrieveRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first;
    pMainRenderState->reset();

    SdkSample::_shutdown();
}

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

#ifndef OGRE_STATIC_LIB

SamplePlugin* sp;
Sample* s;

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

extern "C" _OgreSampleExport void dllStartPlugin()
{
    s = new Sample_VolumeCSG();
    sp = OGRE_NEW SamplePlugin(s->getInfo()["Title"] + " Sample");
    sp->addSample(s);
    Root::getSingleton().installPlugin(sp);
}

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

extern "C" _OgreSampleExport void dllStopPlugin()
{
    Root::getSingleton().uninstallPlugin(sp);
    OGRE_DELETE sp;
    delete s;
}

#endif
<|endoftext|>


<commit_before>/*  Copyright (c) MediaArea.net SARL. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can
 *  be found in the License.html file in the root of the source tree.
 */

//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_DSF_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Audio/File_Dsf.h"
using namespace ZenLib;
using namespace std;
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Infos
//***************************************************************************

//---------------------------------------------------------------------------
static const size_t DSF_FormatID_Size=1;
static const char*  DSF_FormatID[DSF_FormatID_Size]=
{
    "DSD",
};

//---------------------------------------------------------------------------
static const size_t DSF_ChannelType_Size=8;
static const char*  DSF_ChannelType[DSF_ChannelType_Size]=
{
    "",
    "Front: C",
    "Front: L R",
    "Front: L C R",
    "Front: L C R, LFE",
    "Front: L R, Side: L R",
    "Front: L C R, Side: L R",
    "Front: L C R, Side: L R, LFE",
};
static const char*  DSF_ChannelType_ChannelLayout[DSF_ChannelType_Size] =
{
    "",
    "C",
    "L R",
    "L R C",
    "L R C LFE",
    "L R Ls Rs",
    "L R C Ls Rs",
    "L R C Ls Rs LFE",
};

//***************************************************************************
// Constants
//***************************************************************************

//---------------------------------------------------------------------------
namespace Elements
{
    const int64u data = 0x64617461;
    const int64u DSD_ = 0x44534420;
    const int64u fmt_ = 0x666D7420;
}

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
File_Dsf::File_Dsf()
:File__Analyze(), File__Tags_Helper()
{
    //File__Tags_Helper
    Base=this;

    //Configuration
    ParserName="Dsf";
    #if MEDIAINFO_EVENTS
        //ParserIDs[0]=MediaInfo_Parser_Dsf;
        StreamIDs_Width[0]=0;
    #endif //MEDIAINFO_EVENTS
    MustSynchronize=true;
    DataMustAlwaysBeComplete=false;
}

//---------------------------------------------------------------------------
void File_Dsf::Streams_Accept()
{
    Fill(Stream_General, 0, General_Format, "DSF");
    File__Tags_Helper::Stream_Prepare(Stream_Audio);
}

//---------------------------------------------------------------------------
void File_Dsf::Streams_Finish()
{
    int64u SamplingRate=Retrieve(Stream_Audio, 0, Audio_SamplingRate).To_int64u();
    for (int64u Multiplier=64; Multiplier<=512; Multiplier*=2)
    {
        int64u BaseFrequency=SamplingRate/Multiplier;
        if (BaseFrequency==48000 || BaseFrequency==44100)
        {
            Fill(Stream_Audio, 0, Audio_Format_Commercial_IfAny, __T("DSD")+Ztring::ToZtring(Multiplier));
            break;
        }
    }

    //Tags
    File__Tags_Helper::Streams_Fill();
}

//***************************************************************************
// Buffer - File header
//***************************************************************************

//---------------------------------------------------------------------------
bool File_Dsf::FileHeader_Begin()
{
    //Must have enough buffer for having header
    if (Buffer_Size<4)
        return false; //Must wait for more data

    if (Buffer[0]!=0x44 //"DSD "
     || Buffer[1]!=0x53
     || Buffer[2]!=0x44
     || Buffer[3]!=0x20)
    {
        File__Tags_Helper::Reject();
        return false;
    }

    //Temp
    Metadata=(int64u)-1;

    File__Tags_Helper::Accept();
    return true;
}

//***************************************************************************
// Buffer - Synchro
//***************************************************************************

//---------------------------------------------------------------------------
bool File_Dsf::Synched_Test()
{
    if (File_Offset+Buffer_Offset==Metadata)
    {
        //Tags
        if (!File__Tags_Helper::Synched_Test())
            return false;
    }

    return true;
}

//***************************************************************************
// Buffer - Per element
//***************************************************************************

//---------------------------------------------------------------------------
void File_Dsf::Header_Parse()
{
    //Parsing
    int64u Size;
    int32u Name;
    Get_C4 (Name,                                               "Name");
    Get_L8 (Size,                                               "Size");

    //Coherency check
    if (File_Offset+Buffer_Offset+Size>File_Size)
    {
        Size=File_Size-(File_Offset+Buffer_Offset);
        if (Element_Level<=2) //Incoherencies info only at the top level chunk
            Fill(Stream_General, 0, "IsTruncated", "Yes");
    }

    Header_Fill_Code(Name, Ztring().From_CC4(Name));
    Header_Fill_Size(Size);
}

//***************************************************************************
// Elements
//***************************************************************************

//---------------------------------------------------------------------------
void File_Dsf::Data_Parse()
{
    //Parsing
    DATA_BEGIN
    ATOM_PARTIAL(data)
    ATOM(DSD_)
    ATOM(fmt_)
    DATA_END
}

//***************************************************************************
// Elements
//***************************************************************************

//---------------------------------------------------------------------------
void File_Dsf::data()
{
    //Parsing
    Skip_XX(Element_TotalSize_Get(),                            "sample data");

    //Filling
    Fill(Stream_Audio, 0, Audio_StreamSize, Element_TotalSize_Get());
}

//---------------------------------------------------------------------------
void File_Dsf::DSD_()
{
    //Parsing
    int64u FileSize;
    Get_L8 (FileSize,                                           "Total file size");
    Get_L8 (Metadata,                                           "Pointer to Metadata chunk");

    if (FileSize!=File_Size)
        Fill(Stream_General, 0, "Truncated", "Yes");
}

//---------------------------------------------------------------------------
void File_Dsf::fmt_()
{
    //Parsing
    int64u Count;
    int32u Version, FormatID, ChannelType, Num, Frequency, Bits;
    Get_L4 (Version,                                            "Format version");
    Get_L4 (FormatID,                                           "Format ID");
    Get_L4 (ChannelType,                                        "Channel Type");
    Get_L4 (Num,                                                "Channel num");
    Get_L4 (Frequency,                                          "Sampling frequency");
    Get_L4 (Bits,                                               "Bits per sample");
    Get_L8 (Count,                                              "Sample count");
    Skip_L4(                                                    "Block size per channel");
    Skip_L4(                                                    "Reserved");

    FILLING_BEGIN();
        Fill(Stream_General, 0, General_Format_Version, __T("Version ")+Ztring::ToZtring(Version));
        if (FormatID<DSF_FormatID_Size)
            Fill(Stream_Audio, 0, Audio_Format, DSF_FormatID[FormatID]);
        else
            Fill(Stream_Audio, 0, Audio_Format, FormatID);
        if (FormatID<DSF_ChannelType_Size)
        {
            Fill(Stream_Audio, 0, Audio_ChannelPositions, DSF_ChannelType[ChannelType]);
            Fill(Stream_Audio, 0, Audio_ChannelLayout, DSF_ChannelType_ChannelLayout[ChannelType]);
        }
        else
        {
            Fill(Stream_Audio, 0, Audio_ChannelPositions, ChannelType);
            Fill(Stream_Audio, 0, Audio_ChannelLayout, ChannelType);
        }
        Fill(Stream_Audio, 0, Audio_Channel_s_, Num);
        Fill(Stream_Audio, 0, Audio_SamplingRate, Frequency);
        switch (Bits)
        {
            case 1 : Fill(Stream_Audio, 0, Audio_Format_Settings, "Little"); Fill(Stream_Audio, 0, Audio_Format_Settings_Endianness, "Little"); break;
            case 8 : Fill(Stream_Audio, 0, Audio_Format_Settings, "Big"); Fill(Stream_Audio, 0, Audio_Format_Settings_Endianness, "Big"); break;
            default:;
        }
        Fill(Stream_Audio, 0, Audio_SamplingCount, Count);
    FILLING_END();
}

//---------------------------------------------------------------------------
} //NameSpace

#endif //MEDIAINFO_DSF_YES

<commit_msg>Fix out of bound access in File_Dsf::fmt_ (SF#1152)<commit_after>/*  Copyright (c) MediaArea.net SARL. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can
 *  be found in the License.html file in the root of the source tree.
 */

//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_DSF_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Audio/File_Dsf.h"
using namespace ZenLib;
using namespace std;
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Infos
//***************************************************************************

//---------------------------------------------------------------------------
static const size_t DSF_FormatID_Size=1;
static const char*  DSF_FormatID[DSF_FormatID_Size]=
{
    "DSD",
};

//---------------------------------------------------------------------------
static const size_t DSF_ChannelType_Size=8;
static const char*  DSF_ChannelType[DSF_ChannelType_Size]=
{
    "",
    "Front: C",
    "Front: L R",
    "Front: L C R",
    "Front: L C R, LFE",
    "Front: L R, Side: L R",
    "Front: L C R, Side: L R",
    "Front: L C R, Side: L R, LFE",
};
static const char*  DSF_ChannelType_ChannelLayout[DSF_ChannelType_Size] =
{
    "",
    "C",
    "L R",
    "L R C",
    "L R C LFE",
    "L R Ls Rs",
    "L R C Ls Rs",
    "L R C Ls Rs LFE",
};

//***************************************************************************
// Constants
//***************************************************************************

//---------------------------------------------------------------------------
namespace Elements
{
    const int64u data = 0x64617461;
    const int64u DSD_ = 0x44534420;
    const int64u fmt_ = 0x666D7420;
}

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
File_Dsf::File_Dsf()
:File__Analyze(), File__Tags_Helper()
{
    //File__Tags_Helper
    Base=this;

    //Configuration
    ParserName="Dsf";
    #if MEDIAINFO_EVENTS
        //ParserIDs[0]=MediaInfo_Parser_Dsf;
        StreamIDs_Width[0]=0;
    #endif //MEDIAINFO_EVENTS
    MustSynchronize=true;
    DataMustAlwaysBeComplete=false;
}

//---------------------------------------------------------------------------
void File_Dsf::Streams_Accept()
{
    Fill(Stream_General, 0, General_Format, "DSF");
    File__Tags_Helper::Stream_Prepare(Stream_Audio);
}

//---------------------------------------------------------------------------
void File_Dsf::Streams_Finish()
{
    int64u SamplingRate=Retrieve(Stream_Audio, 0, Audio_SamplingRate).To_int64u();
    for (int64u Multiplier=64; Multiplier<=512; Multiplier*=2)
    {
        int64u BaseFrequency=SamplingRate/Multiplier;
        if (BaseFrequency==48000 || BaseFrequency==44100)
        {
            Fill(Stream_Audio, 0, Audio_Format_Commercial_IfAny, __T("DSD")+Ztring::ToZtring(Multiplier));
            break;
        }
    }

    //Tags
    File__Tags_Helper::Streams_Fill();
}

//***************************************************************************
// Buffer - File header
//***************************************************************************

//---------------------------------------------------------------------------
bool File_Dsf::FileHeader_Begin()
{
    //Must have enough buffer for having header
    if (Buffer_Size<4)
        return false; //Must wait for more data

    if (Buffer[0]!=0x44 //"DSD "
     || Buffer[1]!=0x53
     || Buffer[2]!=0x44
     || Buffer[3]!=0x20)
    {
        File__Tags_Helper::Reject();
        return false;
    }

    //Temp
    Metadata=(int64u)-1;

    File__Tags_Helper::Accept();
    return true;
}

//***************************************************************************
// Buffer - Synchro
//***************************************************************************

//---------------------------------------------------------------------------
bool File_Dsf::Synched_Test()
{
    if (File_Offset+Buffer_Offset==Metadata)
    {
        //Tags
        if (!File__Tags_Helper::Synched_Test())
            return false;
    }

    return true;
}

//***************************************************************************
// Buffer - Per element
//***************************************************************************

//---------------------------------------------------------------------------
void File_Dsf::Header_Parse()
{
    //Parsing
    int64u Size;
    int32u Name;
    Get_C4 (Name,                                               "Name");
    Get_L8 (Size,                                               "Size");

    //Coherency check
    if (File_Offset+Buffer_Offset+Size>File_Size)
    {
        Size=File_Size-(File_Offset+Buffer_Offset);
        if (Element_Level<=2) //Incoherencies info only at the top level chunk
            Fill(Stream_General, 0, "IsTruncated", "Yes");
    }

    Header_Fill_Code(Name, Ztring().From_CC4(Name));
    Header_Fill_Size(Size);
}

//***************************************************************************
// Elements
//***************************************************************************

//---------------------------------------------------------------------------
void File_Dsf::Data_Parse()
{
    //Parsing
    DATA_BEGIN
    ATOM_PARTIAL(data)
    ATOM(DSD_)
    ATOM(fmt_)
    DATA_END
}

//***************************************************************************
// Elements
//***************************************************************************

//---------------------------------------------------------------------------
void File_Dsf::data()
{
    //Parsing
    Skip_XX(Element_TotalSize_Get(),                            "sample data");

    //Filling
    Fill(Stream_Audio, 0, Audio_StreamSize, Element_TotalSize_Get());
}

//---------------------------------------------------------------------------
void File_Dsf::DSD_()
{
    //Parsing
    int64u FileSize;
    Get_L8 (FileSize,                                           "Total file size");
    Get_L8 (Metadata,                                           "Pointer to Metadata chunk");

    if (FileSize!=File_Size)
        Fill(Stream_General, 0, "Truncated", "Yes");
}

//---------------------------------------------------------------------------
void File_Dsf::fmt_()
{
    //Parsing
    int64u Count;
    int32u Version, FormatID, ChannelType, Num, Frequency, Bits;
    Get_L4 (Version,                                            "Format version");
    Get_L4 (FormatID,                                           "Format ID");
    Get_L4 (ChannelType,                                        "Channel Type");
    Get_L4 (Num,                                                "Channel num");
    Get_L4 (Frequency,                                          "Sampling frequency");
    Get_L4 (Bits,                                               "Bits per sample");
    Get_L8 (Count,                                              "Sample count");
    Skip_L4(                                                    "Block size per channel");
    Skip_L4(                                                    "Reserved");

    FILLING_BEGIN();
        Fill(Stream_General, 0, General_Format_Version, __T("Version ")+Ztring::ToZtring(Version));
        if (FormatID<DSF_FormatID_Size)
            Fill(Stream_Audio, 0, Audio_Format, DSF_FormatID[FormatID]);
        else
            Fill(Stream_Audio, 0, Audio_Format, FormatID);
        if (ChannelType<DSF_ChannelType_Size)
        {
            Fill(Stream_Audio, 0, Audio_ChannelPositions, DSF_ChannelType[ChannelType]);
            Fill(Stream_Audio, 0, Audio_ChannelLayout, DSF_ChannelType_ChannelLayout[ChannelType]);
        }
        else
        {
            Fill(Stream_Audio, 0, Audio_ChannelPositions, ChannelType);
            Fill(Stream_Audio, 0, Audio_ChannelLayout, ChannelType);
        }
        Fill(Stream_Audio, 0, Audio_Channel_s_, Num);
        Fill(Stream_Audio, 0, Audio_SamplingRate, Frequency);
        switch (Bits)
        {
            case 1 : Fill(Stream_Audio, 0, Audio_Format_Settings, "Little"); Fill(Stream_Audio, 0, Audio_Format_Settings_Endianness, "Little"); break;
            case 8 : Fill(Stream_Audio, 0, Audio_Format_Settings, "Big"); Fill(Stream_Audio, 0, Audio_Format_Settings_Endianness, "Big"); break;
            default:;
        }
        Fill(Stream_Audio, 0, Audio_SamplingCount, Count);
    FILLING_END();
}

//---------------------------------------------------------------------------
} //NameSpace

#endif //MEDIAINFO_DSF_YES

<|endoftext|>


<commit_before>#include "Extensions.hpp"
#include <Math/Rect.hpp>
#include <Math/Vector.hpp>
#include <Script/ScriptExtensions.hpp>
#include <Util/ResourceManager.hpp>

#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/Shader.hpp>
#include <SFML/Window/Mouse.hpp>

#include <angelscript.h>

#include <iostream>
#include <cassert>

namespace
{
    typedef Util::Resource<sf::Shader, std::string> Shader_t;

    void draw_shader(const sf::Drawable& draw, Shader_t* shader, sf::RenderTarget& target)
    {
        target.draw(draw, &(**shader));
    }

    void draw(const sf::Drawable& draw, sf::RenderTarget* target)
    {
        target->draw(draw);
    }
    sf::View* getView(sf::RenderTarget* target)
    {
        return const_cast<sf::View*>(&target->getView());
    }
    Math::Vector2 getMouse(sf::RenderTarget* target)
    {
        sf::RenderWindow* wind = static_cast<sf::RenderWindow*>(target);
        if (!wind)
        {
            std::cerr << "Null window pointer passed" << std::endl;
            return Math::Vector2();
        }
        return sf::Mouse::getPosition(*wind);
    }
    Math::Vector2 getSize(sf::RenderTarget* target)
    {
        return target->getSize();
    }
    Math::Rect getViewport(const sf::View& view, sf::RenderTarget* target)
    {
        return target->getViewport(view);
    }
    Math::Vector2 mapCoordsToPixel(const Math::Vector2& vec, sf::RenderTarget* target)
    {
        return target->mapCoordsToPixel(vec);
    }
    Math::Vector2 mapCoordsToPixel_view(const Math::Vector2& vec, const sf::View& view, sf::RenderTarget* target)
    {
        return target->mapCoordsToPixel(vec, view);
    }
    Math::Vector2 mapPixelToCoords(const Math::Vector2& vec, sf::RenderTarget* target)
    {
        return target->mapPixelToCoords(vec);
    }
    Math::Vector2 mapPixelToCoords_view(const Math::Vector2& vec, const sf::View& view, sf::RenderTarget* target)
    {
        return target->mapPixelToCoords(vec, view);
    }

    bool Reg()
    {
        Script::ScriptExtensions::AddExtension([](asIScriptEngine* eng) {
            int r = 0;

            r = eng->RegisterObjectType("Renderer", 0, asOBJ_REF | asOBJ_NOCOUNT);

            r = eng->RegisterObjectMethod("Renderer", "View& get_DefaultView()", asMETHOD(sf::RenderTarget, getDefaultView), asCALL_THISCALL); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "Vec2 get_MousePos()", asFUNCTION(getMouse), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "Vec2 get_Size()", asFUNCTION(getSize), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "View@ get_View()", asFUNCTION(getView), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "void set_View(View&in)", asMETHOD(sf::RenderTarget, setView), asCALL_THISCALL); assert(r >= 0);

            r = eng->RegisterObjectMethod("Renderer", "Rect GetViewport(View&in)", asFUNCTION(getViewport), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "Vec2 CoordsToPixel(Vec2&in)", asFUNCTION(mapCoordsToPixel), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "Vec2 CoordsToPixel(Vec2&in,View&in)", asFUNCTION(mapCoordsToPixel_view), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "Vec2 PixelToCoords(Vec2&in)", asFUNCTION(mapPixelToCoords), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "Vec2 PixelToCoords(Vec2&in,View&in)", asFUNCTION(mapPixelToCoords_view), asCALL_CDECL_OBJLAST); assert(r >= 0);

            r = eng->RegisterObjectMethod("Renderer", "void Clear(Color&in)", asMETHOD(sf::RenderTarget, clear), asCALL_THISCALL); assert(r >= 0);

            r = eng->RegisterObjectMethod("Renderer", "void Draw(Sprite&in)", asFUNCTION(draw), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "void Draw(Text&in)", asFUNCTION(draw), asCALL_CDECL_OBJLAST); assert(r >= 0);

            r = eng->RegisterObjectMethod("Renderer", "void Draw(Sprite&in,Shader@)", asFUNCTION(draw_shader), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "void Draw(Text&in,Shader@)", asFUNCTION(draw_shader), asCALL_CDECL_OBJLAST); assert(r >= 0);
        }, 5);

        return true;
    }

}

bool Script::SFML::Extensions::RenderTarget = Reg();
<commit_msg>Testing with dynamic_cast<commit_after>#include "Extensions.hpp"
#include <Math/Rect.hpp>
#include <Math/Vector.hpp>
#include <Script/ScriptExtensions.hpp>
#include <Util/ResourceManager.hpp>

#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/Shader.hpp>
#include <SFML/Window/Mouse.hpp>

#include <angelscript.h>

#include <iostream>
#include <cassert>

namespace
{
    typedef Util::Resource<sf::Shader, std::string> Shader_t;

    void draw_shader(const sf::Drawable& draw, Shader_t* shader, sf::RenderTarget& target)
    {
        target.draw(draw, &(**shader));
    }

    void draw(const sf::Drawable& draw, sf::RenderTarget* target)
    {
        target->draw(draw);
    }
    sf::View* getView(sf::RenderTarget* target)
    {
        return const_cast<sf::View*>(&target->getView());
    }
    Math::Vector2 getMouse(sf::RenderTarget* target)
    {
        sf::RenderWindow* wind = dynamic_cast<sf::RenderWindow*>(target);
        if (!wind)
        {
            std::cerr << "Null window pointer passed" << std::endl;
            return Math::Vector2();
        }

        return sf::Mouse::getPosition(*wind);
    }
    Math::Vector2 getSize(sf::RenderTarget* target)
    {
        return target->getSize();
    }
    Math::Rect getViewport(const sf::View& view, sf::RenderTarget* target)
    {
        return target->getViewport(view);
    }
    Math::Vector2 mapCoordsToPixel(const Math::Vector2& vec, sf::RenderTarget* target)
    {
        return target->mapCoordsToPixel(vec);
    }
    Math::Vector2 mapCoordsToPixel_view(const Math::Vector2& vec, const sf::View& view, sf::RenderTarget* target)
    {
        return target->mapCoordsToPixel(vec, view);
    }
    Math::Vector2 mapPixelToCoords(const Math::Vector2& vec, sf::RenderTarget* target)
    {
        return target->mapPixelToCoords(vec);
    }
    Math::Vector2 mapPixelToCoords_view(const Math::Vector2& vec, const sf::View& view, sf::RenderTarget* target)
    {
        return target->mapPixelToCoords(vec, view);
    }

    bool Reg()
    {
        Script::ScriptExtensions::AddExtension([](asIScriptEngine* eng) {
            int r = 0;

            r = eng->RegisterObjectType("Renderer", 0, asOBJ_REF | asOBJ_NOCOUNT);

            r = eng->RegisterObjectMethod("Renderer", "View& get_DefaultView()", asMETHOD(sf::RenderTarget, getDefaultView), asCALL_THISCALL); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "Vec2 get_MousePos()", asFUNCTION(getMouse), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "Vec2 get_Size()", asFUNCTION(getSize), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "View@ get_View()", asFUNCTION(getView), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "void set_View(View&in)", asMETHOD(sf::RenderTarget, setView), asCALL_THISCALL); assert(r >= 0);

            r = eng->RegisterObjectMethod("Renderer", "Rect GetViewport(View&in)", asFUNCTION(getViewport), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "Vec2 CoordsToPixel(Vec2&in)", asFUNCTION(mapCoordsToPixel), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "Vec2 CoordsToPixel(Vec2&in,View&in)", asFUNCTION(mapCoordsToPixel_view), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "Vec2 PixelToCoords(Vec2&in)", asFUNCTION(mapPixelToCoords), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "Vec2 PixelToCoords(Vec2&in,View&in)", asFUNCTION(mapPixelToCoords_view), asCALL_CDECL_OBJLAST); assert(r >= 0);

            r = eng->RegisterObjectMethod("Renderer", "void Clear(Color&in)", asMETHOD(sf::RenderTarget, clear), asCALL_THISCALL); assert(r >= 0);

            r = eng->RegisterObjectMethod("Renderer", "void Draw(Sprite&in)", asFUNCTION(draw), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "void Draw(Text&in)", asFUNCTION(draw), asCALL_CDECL_OBJLAST); assert(r >= 0);

            r = eng->RegisterObjectMethod("Renderer", "void Draw(Sprite&in,Shader@)", asFUNCTION(draw_shader), asCALL_CDECL_OBJLAST); assert(r >= 0);
            r = eng->RegisterObjectMethod("Renderer", "void Draw(Text&in,Shader@)", asFUNCTION(draw_shader), asCALL_CDECL_OBJLAST); assert(r >= 0);
        }, 5);

        return true;
    }

}

bool Script::SFML::Extensions::RenderTarget = Reg();
<|endoftext|>


<commit_before>//
// Copyright (c) 2008-2020 the Urho3D project.
//
// 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 "../Precompiled.h"

#include "../Core/Context.h"
#include "../Graphics/Camera.h"
#include "../Graphics/Graphics.h"
#include "../Graphics/Renderer.h"
#include "../Graphics/RenderPath.h"
#include "../Graphics/RenderSurface.h"
#include "../Graphics/View.h"
#include "../Graphics/Viewport.h"
#include "../RenderPipeline/RenderPipeline.h"
#include "../Resource/ResourceCache.h"
#include "../Resource/XMLFile.h"
#include "../Scene/Scene.h"

#include "../DebugNew.h"

namespace Urho3D
{

Viewport::Viewport(Context* context) :
    Object(context),
    rect_(IntRect::ZERO),
    drawDebug_(true)
{
    SetRenderPath((RenderPath*)nullptr);
}

Viewport::Viewport(Context* context, Scene* scene, Camera* camera, RenderPath* renderPath) :
    Object(context),
    scene_(scene),
    camera_(camera),
    rect_(IntRect::ZERO),
    drawDebug_(true)
{
    SetRenderPath(renderPath);
}

Viewport::Viewport(Context* context, Scene* scene, Camera* camera, const IntRect& rect, RenderPath* renderPath) :   // NOLINT(modernize-pass-by-value)
    Object(context),
    scene_(scene),
    camera_(camera),
    rect_(rect),
    drawDebug_(true)
{
    SetRenderPath(renderPath);
}

Viewport::~Viewport() = default;

void Viewport::RegisterObject(Context* context)
{
    context->RegisterFactory<Viewport>();
}

void Viewport::SetScene(Scene* scene)
{
    scene_ = scene;
}

void Viewport::SetCamera(Camera* camera)
{
    camera_ = camera;
}

void Viewport::SetCullCamera(Camera* camera)
{
    cullCamera_ = camera;
}

void Viewport::SetRect(const IntRect& rect)
{
    rect_ = rect;
}

void Viewport::SetDrawDebug(bool enable)
{
    drawDebug_ = enable;
}

void Viewport::SetRenderPath(RenderPath* renderPath)
{
    if (renderPath)
        renderPath_ = renderPath;
    else
    {
        auto* renderer = GetSubsystem<Renderer>();
        if (renderer)
            renderPath_ = renderer->GetDefaultRenderPath();
    }
}

bool Viewport::SetRenderPath(XMLFile* file)
{
    SharedPtr<RenderPath> newRenderPath(new RenderPath());
    if (newRenderPath->Load(file))
    {
        renderPath_ = newRenderPath;
        return true;
    }
    return false;
}

Scene* Viewport::GetScene() const
{
    return scene_;
}

Camera* Viewport::GetCamera() const
{
    return camera_;
}

IntRect Viewport::GetEffectiveRect(RenderSurface* renderTarget) const
{
    const IntVector2 renderTargetSize = RenderSurface::GetSize(GetSubsystem<Graphics>(), renderTarget);

    if (rect_ == IntRect::ZERO)
    {
        // Return render target dimensions if viewport rectangle is not defined
        return { IntVector2::ZERO, renderTargetSize };
    }
    else
    {
        // Validate and return viewport rectangle
        IntRect rect;
        rect.left_ = Clamp(rect_.left_, 0, renderTargetSize.x_ - 1);
        rect.top_ = Clamp(rect_.top_, 0, renderTargetSize.y_ - 1);
        rect.right_ = Clamp(rect_.right_, rect.left_ + 1, renderTargetSize.x_);
        rect.bottom_ = Clamp(rect_.bottom_, rect.top_ + 1, renderTargetSize.y_);
        return rect;
    }
}

Camera* Viewport::GetCullCamera() const
{
    return cullCamera_;
}

View* Viewport::GetView() const
{
    return view_;
}

RenderPipelineView* Viewport::GetRenderPipelineView() const
{
    if (renderPipelineComponent_ && renderPipelineComponent_->GetScene() == scene_)
        return renderPipeline_;
    return nullptr;
}

RenderPath* Viewport::GetRenderPath() const
{
    return renderPath_;
}

Ray Viewport::GetScreenRay(int x, int y) const
{
    if (!camera_)
        return Ray();

    float screenX;
    float screenY;

    if (rect_ == IntRect::ZERO)
    {
        auto* graphics = GetSubsystem<Graphics>();
        screenX = (float)x / (float)graphics->GetWidth();
        screenY = (float)y / (float)graphics->GetHeight();
    }
    else
    {
        screenX = float(x - rect_.left_) / (float)rect_.Width();
        screenY = float(y - rect_.top_) / (float)rect_.Height();
    }

    return camera_->GetScreenRay(screenX, screenY);
}

IntVector2 Viewport::WorldToScreenPoint(const Vector3& worldPos) const
{
    if (!camera_)
        return IntVector2::ZERO;

    Vector2 screenPoint = camera_->WorldToScreenPoint(worldPos);

    int x;
    int y;
    if (rect_ == IntRect::ZERO)
    {
        /// \todo This is incorrect if the viewport is used on a texture rendertarget instead of the backbuffer, as it may have different dimensions.
        auto* graphics = GetSubsystem<Graphics>();
        x = (int)(screenPoint.x_ * graphics->GetWidth());
        y = (int)(screenPoint.y_ * graphics->GetHeight());
    }
    else
    {
        x = (int)(rect_.left_ + screenPoint.x_ * rect_.Width());
        y = (int)(rect_.top_ + screenPoint.y_ * rect_.Height());
    }

    return IntVector2(x, y);
}

Vector3 Viewport::ScreenToWorldPoint(int x, int y, float depth) const
{
    if (!camera_)
        return Vector3::ZERO;

    float screenX;
    float screenY;

    if (rect_ == IntRect::ZERO)
    {
        /// \todo This is incorrect if the viewport is used on a texture rendertarget instead of the backbuffer, as it may have different dimensions.
        auto* graphics = GetSubsystem<Graphics>();
        screenX = (float)x / (float)graphics->GetWidth();
        screenY = (float)y / (float)graphics->GetHeight();
    }
    else
    {
        screenX = float(x - rect_.left_) / (float)rect_.Width();
        screenY = float(y - rect_.top_) / (float)rect_.Height();
    }

    return camera_->ScreenToWorldPoint(Vector3(screenX, screenY, depth));
}

void Viewport::AllocateView()
{
#if !defined(URHO3D_D3D9) && !defined(URHO3D_LEGACY_RENDERER)
    if (!GetRenderPipelineView())
    {
        renderPipelineComponent_ = nullptr;
        renderPipeline_ = nullptr;
    }

    if (!renderPipelineComponent_ && scene_)
    {
        renderPipelineComponent_ = scene_->GetDerivedComponent<RenderPipeline>();
        if (!renderPipelineComponent_)
            renderPipelineComponent_ = scene_->CreateComponent<RenderPipeline>();
    }

    if (!renderPipeline_ && renderPipelineComponent_)
        renderPipeline_ = renderPipelineComponent_->Instantiate();
#endif

    if (!renderPipeline_)
        view_ = MakeShared<View>(context_);
}

}
<commit_msg>Fix rendering on first start.<commit_after>//
// Copyright (c) 2008-2020 the Urho3D project.
//
// 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 "../Precompiled.h"

#include "../Core/Context.h"
#include "../Graphics/Camera.h"
#include "../Graphics/Graphics.h"
#include "../Graphics/Renderer.h"
#include "../Graphics/RenderPath.h"
#include "../Graphics/RenderSurface.h"
#include "../Graphics/View.h"
#include "../Graphics/Viewport.h"
#include "../RenderPipeline/RenderPipeline.h"
#include "../Resource/ResourceCache.h"
#include "../Resource/XMLFile.h"
#include "../Scene/Scene.h"

#include "../DebugNew.h"

namespace Urho3D
{

Viewport::Viewport(Context* context) :
    Object(context),
    rect_(IntRect::ZERO),
    drawDebug_(true)
{
    SetRenderPath((RenderPath*)nullptr);
}

Viewport::Viewport(Context* context, Scene* scene, Camera* camera, RenderPath* renderPath) :
    Object(context),
    scene_(scene),
    camera_(camera),
    rect_(IntRect::ZERO),
    drawDebug_(true)
{
    SetRenderPath(renderPath);
}

Viewport::Viewport(Context* context, Scene* scene, Camera* camera, const IntRect& rect, RenderPath* renderPath) :   // NOLINT(modernize-pass-by-value)
    Object(context),
    scene_(scene),
    camera_(camera),
    rect_(rect),
    drawDebug_(true)
{
    SetRenderPath(renderPath);
}

Viewport::~Viewport() = default;

void Viewport::RegisterObject(Context* context)
{
    context->RegisterFactory<Viewport>();
}

void Viewport::SetScene(Scene* scene)
{
#if !defined(URHO3D_D3D9) && !defined(URHO3D_LEGACY_RENDERER)
    if (!!scene_ != !!scene)
    {
        renderPipeline_ = nullptr;
        view_ = nullptr;
    }
#endif

    scene_ = scene;
}

void Viewport::SetCamera(Camera* camera)
{
    camera_ = camera;
}

void Viewport::SetCullCamera(Camera* camera)
{
    cullCamera_ = camera;
}

void Viewport::SetRect(const IntRect& rect)
{
    rect_ = rect;
}

void Viewport::SetDrawDebug(bool enable)
{
    drawDebug_ = enable;
}

void Viewport::SetRenderPath(RenderPath* renderPath)
{
    if (renderPath)
        renderPath_ = renderPath;
    else
    {
        auto* renderer = GetSubsystem<Renderer>();
        if (renderer)
            renderPath_ = renderer->GetDefaultRenderPath();
    }
}

bool Viewport::SetRenderPath(XMLFile* file)
{
    SharedPtr<RenderPath> newRenderPath(new RenderPath());
    if (newRenderPath->Load(file))
    {
        renderPath_ = newRenderPath;
        return true;
    }
    return false;
}

Scene* Viewport::GetScene() const
{
    return scene_;
}

Camera* Viewport::GetCamera() const
{
    return camera_;
}

IntRect Viewport::GetEffectiveRect(RenderSurface* renderTarget) const
{
    const IntVector2 renderTargetSize = RenderSurface::GetSize(GetSubsystem<Graphics>(), renderTarget);

    if (rect_ == IntRect::ZERO)
    {
        // Return render target dimensions if viewport rectangle is not defined
        return { IntVector2::ZERO, renderTargetSize };
    }
    else
    {
        // Validate and return viewport rectangle
        IntRect rect;
        rect.left_ = Clamp(rect_.left_, 0, renderTargetSize.x_ - 1);
        rect.top_ = Clamp(rect_.top_, 0, renderTargetSize.y_ - 1);
        rect.right_ = Clamp(rect_.right_, rect.left_ + 1, renderTargetSize.x_);
        rect.bottom_ = Clamp(rect_.bottom_, rect.top_ + 1, renderTargetSize.y_);
        return rect;
    }
}

Camera* Viewport::GetCullCamera() const
{
    return cullCamera_;
}

View* Viewport::GetView() const
{
    return view_;
}

RenderPipelineView* Viewport::GetRenderPipelineView() const
{
    if (renderPipelineComponent_ && renderPipelineComponent_->GetScene() == scene_)
        return renderPipeline_;
    return nullptr;
}

RenderPath* Viewport::GetRenderPath() const
{
    return renderPath_;
}

Ray Viewport::GetScreenRay(int x, int y) const
{
    if (!camera_)
        return Ray();

    float screenX;
    float screenY;

    if (rect_ == IntRect::ZERO)
    {
        auto* graphics = GetSubsystem<Graphics>();
        screenX = (float)x / (float)graphics->GetWidth();
        screenY = (float)y / (float)graphics->GetHeight();
    }
    else
    {
        screenX = float(x - rect_.left_) / (float)rect_.Width();
        screenY = float(y - rect_.top_) / (float)rect_.Height();
    }

    return camera_->GetScreenRay(screenX, screenY);
}

IntVector2 Viewport::WorldToScreenPoint(const Vector3& worldPos) const
{
    if (!camera_)
        return IntVector2::ZERO;

    Vector2 screenPoint = camera_->WorldToScreenPoint(worldPos);

    int x;
    int y;
    if (rect_ == IntRect::ZERO)
    {
        /// \todo This is incorrect if the viewport is used on a texture rendertarget instead of the backbuffer, as it may have different dimensions.
        auto* graphics = GetSubsystem<Graphics>();
        x = (int)(screenPoint.x_ * graphics->GetWidth());
        y = (int)(screenPoint.y_ * graphics->GetHeight());
    }
    else
    {
        x = (int)(rect_.left_ + screenPoint.x_ * rect_.Width());
        y = (int)(rect_.top_ + screenPoint.y_ * rect_.Height());
    }

    return IntVector2(x, y);
}

Vector3 Viewport::ScreenToWorldPoint(int x, int y, float depth) const
{
    if (!camera_)
        return Vector3::ZERO;

    float screenX;
    float screenY;

    if (rect_ == IntRect::ZERO)
    {
        /// \todo This is incorrect if the viewport is used on a texture rendertarget instead of the backbuffer, as it may have different dimensions.
        auto* graphics = GetSubsystem<Graphics>();
        screenX = (float)x / (float)graphics->GetWidth();
        screenY = (float)y / (float)graphics->GetHeight();
    }
    else
    {
        screenX = float(x - rect_.left_) / (float)rect_.Width();
        screenY = float(y - rect_.top_) / (float)rect_.Height();
    }

    return camera_->ScreenToWorldPoint(Vector3(screenX, screenY, depth));
}

void Viewport::AllocateView()
{
#if !defined(URHO3D_D3D9) && !defined(URHO3D_LEGACY_RENDERER)
    if (!GetRenderPipelineView())
    {
        renderPipelineComponent_ = nullptr;
        renderPipeline_ = nullptr;
    }

    if (!renderPipelineComponent_ && scene_)
    {
        renderPipelineComponent_ = scene_->GetDerivedComponent<RenderPipeline>();
        if (!renderPipelineComponent_)
            renderPipelineComponent_ = scene_->CreateComponent<RenderPipeline>();
    }

    if (!renderPipeline_ && renderPipelineComponent_)
        renderPipeline_ = renderPipelineComponent_->Instantiate();
#endif

    if (!renderPipeline_)
        view_ = MakeShared<View>(context_);
}

}
<|endoftext|>


<commit_before>#include <jni.h>
#include <cassert>
#include <android/native_window.h>
#include <android/native_window_jni.h>
#include "PathUtils.h"
#include "../AppConfig.h"
#include "../DiskUtils.h"
#include "../PS2VM.h"
#include "../PS2VM_Preferences.h"
#include "../gs/GSH_Null.h"
#include "NativeShared.h"
#include "GSH_OpenGLAndroid.h"
#include "PH_Android.h"
#include "StatsManager.h"

CPS2VM* g_virtualMachine = nullptr;

extern "C" JNIEXPORT void JNICALL Java_com_virtualapplications_play_NativeInterop_setFilesDirPath(JNIEnv* env, jobject obj, jstring dirPathString)
{
	auto dirPath = env->GetStringUTFChars(dirPathString, 0);
	Framework::PathUtils::SetFilesDirPath(dirPath);
	env->ReleaseStringUTFChars(dirPathString, dirPath);
}

extern "C" JNIEXPORT void JNICALL Java_com_virtualapplications_play_NativeInterop_createVirtualMachine(JNIEnv* env, jobject obj)
{
	assert(g_virtualMachine == nullptr);
	g_virtualMachine = new CPS2VM();
	g_virtualMachine->Initialize();
	g_virtualMachine->CreatePadHandler(CPH_Android::GetFactoryFunction());
}

extern "C" JNIEXPORT jboolean JNICALL Java_com_virtualapplications_play_NativeInterop_isVirtualMachineCreated(JNIEnv* env, jobject obj)
{
	return (g_virtualMachine != nullptr);
}

extern "C" JNIEXPORT jboolean JNICALL Java_com_virtualapplications_play_NativeInterop_isVirtualMachineRunning(JNIEnv* env, jobject obj)
{
	if(g_virtualMachine == nullptr) return false;
	return g_virtualMachine->GetStatus() == CVirtualMachine::RUNNING;
}

extern "C" JNIEXPORT void JNICALL Java_com_virtualapplications_play_NativeInterop_resumeVirtualMachine(JNIEnv* env, jobject obj)
{
	assert(g_virtualMachine != nullptr);
	if(g_virtualMachine == nullptr) return;
	g_virtualMachine->Resume();
}

extern "C" JNIEXPORT void JNICALL Java_com_virtualapplications_play_NativeInterop_pauseVirtualMachine(JNIEnv* env, jobject obj)
{
	assert(g_virtualMachine != nullptr);
	if(g_virtualMachine == nullptr) return;
	g_virtualMachine->Pause();
}

extern "C" JNIEXPORT void JNICALL Java_com_virtualapplications_play_NativeInterop_loadElf(JNIEnv* env, jobject obj, jstring selectedFilePath)
{
	assert(g_virtualMachine != nullptr);
	g_virtualMachine->Pause();
	g_virtualMachine->Reset();
	try
	{
		g_virtualMachine->m_ee->m_os->BootFromFile(GetStringFromJstring(env, selectedFilePath).c_str());
	}
	catch(const std::exception& exception)
	{
		jclass exceptionClass = env->FindClass("java/lang/Exception");
		env->ThrowNew(exceptionClass, exception.what());
	}
}

extern "C" JNIEXPORT void JNICALL Java_com_virtualapplications_play_NativeInterop_bootDiskImage(JNIEnv* env, jobject obj, jstring selectedFilePath)
{
	assert(g_virtualMachine != nullptr);
	CAppConfig::GetInstance().SetPreferenceString(PS2VM_CDROM0PATH, GetStringFromJstring(env, selectedFilePath).c_str());
	g_virtualMachine->Pause();
	g_virtualMachine->Reset();
	try
	{
		g_virtualMachine->m_ee->m_os->BootFromCDROM(CPS2OS::ArgumentList());
	}
	catch(const std::exception& exception)
	{
		jclass exceptionClass = env->FindClass("java/lang/Exception");
		env->ThrowNew(exceptionClass, exception.what());
	}
}

extern "C" JNIEXPORT void JNICALL Java_com_virtualapplications_play_NativeInterop_setupGsHandler(JNIEnv* env, jobject obj, jobject surface)
{
	auto nativeWindow = ANativeWindow_fromSurface(env, surface);
	auto gsHandler = g_virtualMachine->GetGSHandler();
	if(gsHandler == nullptr)
	{
		g_virtualMachine->CreateGSHandler(CGSH_OpenGLAndroid::GetFactoryFunction(nativeWindow));
		g_virtualMachine->m_ee->m_gs->OnNewFrame.connect(
			boost::bind(&CStatsManager::OnNewFrame, &CStatsManager::GetInstance(), _1));
	}
	else
	{
		static_cast<CGSH_OpenGLAndroid*>(gsHandler)->SetWindow(nativeWindow);
	}
}

extern "C" JNIEXPORT jstring JNICALL Java_com_virtualapplications_play_NativeInterop_getDiskId(JNIEnv* env, jobject obj, jstring diskImagePath)
{
	std::string diskId;
	bool succeeded = DiskUtils::TryGetDiskId(GetStringFromJstring(env, diskImagePath).c_str(), &diskId);
	if(!succeeded)
	{
		jclass exceptionClass = env->FindClass("java/lang/Exception");
		env->ThrowNew(exceptionClass, "Failed to obtain disk id.");
		return 0;
	}
	jstring result = env->NewStringUTF(diskId.c_str());
	return result;
}
<commit_msg>getDiskId will return null instead of throwing an exception.<commit_after>#include <jni.h>
#include <cassert>
#include <android/native_window.h>
#include <android/native_window_jni.h>
#include "PathUtils.h"
#include "../AppConfig.h"
#include "../DiskUtils.h"
#include "../PS2VM.h"
#include "../PS2VM_Preferences.h"
#include "../gs/GSH_Null.h"
#include "NativeShared.h"
#include "GSH_OpenGLAndroid.h"
#include "PH_Android.h"
#include "StatsManager.h"

CPS2VM* g_virtualMachine = nullptr;

extern "C" JNIEXPORT void JNICALL Java_com_virtualapplications_play_NativeInterop_setFilesDirPath(JNIEnv* env, jobject obj, jstring dirPathString)
{
	auto dirPath = env->GetStringUTFChars(dirPathString, 0);
	Framework::PathUtils::SetFilesDirPath(dirPath);
	env->ReleaseStringUTFChars(dirPathString, dirPath);
}

extern "C" JNIEXPORT void JNICALL Java_com_virtualapplications_play_NativeInterop_createVirtualMachine(JNIEnv* env, jobject obj)
{
	assert(g_virtualMachine == nullptr);
	g_virtualMachine = new CPS2VM();
	g_virtualMachine->Initialize();
	g_virtualMachine->CreatePadHandler(CPH_Android::GetFactoryFunction());
}

extern "C" JNIEXPORT jboolean JNICALL Java_com_virtualapplications_play_NativeInterop_isVirtualMachineCreated(JNIEnv* env, jobject obj)
{
	return (g_virtualMachine != nullptr);
}

extern "C" JNIEXPORT jboolean JNICALL Java_com_virtualapplications_play_NativeInterop_isVirtualMachineRunning(JNIEnv* env, jobject obj)
{
	if(g_virtualMachine == nullptr) return false;
	return g_virtualMachine->GetStatus() == CVirtualMachine::RUNNING;
}

extern "C" JNIEXPORT void JNICALL Java_com_virtualapplications_play_NativeInterop_resumeVirtualMachine(JNIEnv* env, jobject obj)
{
	assert(g_virtualMachine != nullptr);
	if(g_virtualMachine == nullptr) return;
	g_virtualMachine->Resume();
}

extern "C" JNIEXPORT void JNICALL Java_com_virtualapplications_play_NativeInterop_pauseVirtualMachine(JNIEnv* env, jobject obj)
{
	assert(g_virtualMachine != nullptr);
	if(g_virtualMachine == nullptr) return;
	g_virtualMachine->Pause();
}

extern "C" JNIEXPORT void JNICALL Java_com_virtualapplications_play_NativeInterop_loadElf(JNIEnv* env, jobject obj, jstring selectedFilePath)
{
	assert(g_virtualMachine != nullptr);
	g_virtualMachine->Pause();
	g_virtualMachine->Reset();
	try
	{
		g_virtualMachine->m_ee->m_os->BootFromFile(GetStringFromJstring(env, selectedFilePath).c_str());
	}
	catch(const std::exception& exception)
	{
		jclass exceptionClass = env->FindClass("java/lang/Exception");
		env->ThrowNew(exceptionClass, exception.what());
	}
}

extern "C" JNIEXPORT void JNICALL Java_com_virtualapplications_play_NativeInterop_bootDiskImage(JNIEnv* env, jobject obj, jstring selectedFilePath)
{
	assert(g_virtualMachine != nullptr);
	CAppConfig::GetInstance().SetPreferenceString(PS2VM_CDROM0PATH, GetStringFromJstring(env, selectedFilePath).c_str());
	g_virtualMachine->Pause();
	g_virtualMachine->Reset();
	try
	{
		g_virtualMachine->m_ee->m_os->BootFromCDROM(CPS2OS::ArgumentList());
	}
	catch(const std::exception& exception)
	{
		jclass exceptionClass = env->FindClass("java/lang/Exception");
		env->ThrowNew(exceptionClass, exception.what());
	}
}

extern "C" JNIEXPORT void JNICALL Java_com_virtualapplications_play_NativeInterop_setupGsHandler(JNIEnv* env, jobject obj, jobject surface)
{
	auto nativeWindow = ANativeWindow_fromSurface(env, surface);
	auto gsHandler = g_virtualMachine->GetGSHandler();
	if(gsHandler == nullptr)
	{
		g_virtualMachine->CreateGSHandler(CGSH_OpenGLAndroid::GetFactoryFunction(nativeWindow));
		g_virtualMachine->m_ee->m_gs->OnNewFrame.connect(
			boost::bind(&CStatsManager::OnNewFrame, &CStatsManager::GetInstance(), _1));
	}
	else
	{
		static_cast<CGSH_OpenGLAndroid*>(gsHandler)->SetWindow(nativeWindow);
	}
}

extern "C" JNIEXPORT jstring JNICALL Java_com_virtualapplications_play_NativeInterop_getDiskId(JNIEnv* env, jobject obj, jstring diskImagePath)
{
	std::string diskId;
	bool succeeded = DiskUtils::TryGetDiskId(GetStringFromJstring(env, diskImagePath).c_str(), &diskId);
	if(!succeeded)
	{
		return NULL;
	}
	jstring result = env->NewStringUTF(diskId.c_str());
	return result;
}
<|endoftext|>


<commit_before>#include "Filepath.h"

//[TODO]
//Add case sensitivity on windows.
// Probably using the SHGetFileInfo - SHGetFileInfoW functions.
//Where should i check this though...?
namespace star
{
#ifdef DESKTOP
tstring Filepath::m_AssetsRoot = EMPTY_STRING;
#endif

	Filepath::Filepath()
		: m_Path(EMPTY_STRING)
		, m_File(EMPTY_STRING)
	{

	}

	Filepath::Filepath(const tstring & full_path)
		: m_Path(EMPTY_STRING)
		, m_File(EMPTY_STRING)
	{
		auto index = full_path.find_last_of('/');
		if(index == tstring::npos)
		{
			index = full_path.find_last_of('\\');
		}
		if(index != tstring::npos)
		{
			m_Path = full_path.substr(0,index);
			m_File = full_path.substr(index, full_path.length() - index);
		}
		else
		{
			m_File = full_path;
		}
	}

	Filepath::Filepath(const tstring & path, const tstring & file)
		: m_Path(path)
		, m_File(file)
	{

	}

	Filepath::Filepath(const Filepath & yRef)
		: m_Path(yRef.m_Path)
		, m_File(yRef.m_File)
	{

	}

	Filepath::~Filepath()
	{

	}

	const Filepath & Filepath::operator=(const Filepath & yRef)
	{
		m_Path = yRef.m_Path;
		m_File = yRef.m_File;
		return *this;
	}

	bool Filepath::operator==(const Filepath & yRef)
	{
		return m_Path == yRef.m_Path && m_File == yRef.m_File;
	}

	const tstring & Filepath::GetPath() const
	{
		return m_Path;
	}

	const tstring & Filepath::GetFile() const
	{
		return m_File;
	}

	tstring Filepath::GetName() const
	{
		tstring name(m_File);
		auto index(name.find_last_of(_T(".")));
		return name.substr(0, index);
	}

	tstring Filepath::GetExtension() const
	{
		tstring extension(m_File);
		auto index(extension.find_last_of(_T(".")));
		return extension.substr(index, extension.size() - index);
	}

	tstring Filepath::GetFullPath() const
	{
		tstring full_path(EMPTY_STRING);
#ifdef DESKTOP
		full_path = m_AssetsRoot;
#endif
		full_path += m_Path + m_File;
		return full_path;
	}

#ifdef DESKTOP
	void Filepath::SetAssetsRoot(const tstring & root)
	{
		m_AssetsRoot = root;
	}
#endif
}<commit_msg>Extended a comment in FilePath, for future references<commit_after>#include "Filepath.h"

//[TODO]
//Add case sensitivity on windows.
// Probably using the SHGetFileInfo - SHGetFileInfoW functions.
// Where should i check this though...?
// http://stackoverflow.com/questions/74451/getting-actual-file-name-with-proper-casing-on-windows
namespace star
{
#ifdef DESKTOP
tstring Filepath::m_AssetsRoot = EMPTY_STRING;
#endif

	Filepath::Filepath()
		: m_Path(EMPTY_STRING)
		, m_File(EMPTY_STRING)
	{

	}

	Filepath::Filepath(const tstring & full_path)
		: m_Path(EMPTY_STRING)
		, m_File(EMPTY_STRING)
	{
		auto index = full_path.find_last_of('/');
		if(index == tstring::npos)
		{
			index = full_path.find_last_of('\\');
		}
		if(index != tstring::npos)
		{
			m_Path = full_path.substr(0,index);
			m_File = full_path.substr(index, full_path.length() - index);
		}
		else
		{
			m_File = full_path;
		}
	}

	Filepath::Filepath(const tstring & path, const tstring & file)
		: m_Path(path)
		, m_File(file)
	{

	}

	Filepath::Filepath(const Filepath & yRef)
		: m_Path(yRef.m_Path)
		, m_File(yRef.m_File)
	{

	}

	Filepath::~Filepath()
	{

	}

	const Filepath & Filepath::operator=(const Filepath & yRef)
	{
		m_Path = yRef.m_Path;
		m_File = yRef.m_File;
		return *this;
	}

	bool Filepath::operator==(const Filepath & yRef)
	{
		return m_Path == yRef.m_Path && m_File == yRef.m_File;
	}

	const tstring & Filepath::GetPath() const
	{
		return m_Path;
	}

	const tstring & Filepath::GetFile() const
	{
		return m_File;
	}

	tstring Filepath::GetName() const
	{
		tstring name(m_File);
		auto index(name.find_last_of(_T(".")));
		return name.substr(0, index);
	}

	tstring Filepath::GetExtension() const
	{
		tstring extension(m_File);
		auto index(extension.find_last_of(_T(".")));
		return extension.substr(index, extension.size() - index);
	}

	tstring Filepath::GetFullPath() const
	{
		tstring full_path(EMPTY_STRING);
#ifdef DESKTOP
		full_path = m_AssetsRoot;
#endif
		full_path += m_Path + m_File;
		return full_path;
	}

#ifdef DESKTOP
	void Filepath::SetAssetsRoot(const tstring & root)
	{
		m_AssetsRoot = root;
	}
#endif
}<|endoftext|>


<commit_before>#include "Globals.h"
#include "Application.h"
#include "ModuleSceneIntro.h"
#include"GameObject.h"
#include"Component.h"
#include"Mesh.h"
#include"Transform.h"

ModuleSceneIntro::ModuleSceneIntro(bool start_enabled) : Module(start_enabled)
{
}

ModuleSceneIntro::~ModuleSceneIntro()
{}

// Load assets
bool ModuleSceneIntro::Start()
{
	bool ret = true;

	GLfloat LightModelAmbient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
	glLightModelfv(GL_LIGHT_MODEL_AMBIENT, LightModelAmbient);
	lights[0].ref = GL_LIGHT0;
	lights[0].ambient.Set(0.5f, 0.5f, 0.5f, 1.0f);
	lights[0].diffuse.Set(.5f, .5f, 0.5f, 1.0f);
	lights[0].SetPos(1.0f, 0.0f, 2.5f);
	lights[0].Init();

	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);
	lights[0].Active(true);
	glEnable(GL_LIGHTING);
	glEnable(GL_COLOR_MATERIAL);

	world_texture = new Texture_Engine();
	world_texture->Create(nullptr, App->window->win_width, App->window->win_height);
	std::string path_temp = "E:\\CITM\\3ero VJ\\Game-Engine-Unreal\\StartingEngine\\Game\\Data\\BakerHouse.fbx";
	std::string path_temp2 = "E:\\CITM\\3ero VJ\\Game-Engine-Unreal\\StartingEngine\\Game\\Data\\Baker_house.png";
	Material* temp = nullptr;

	root_gameobject = CreateNewGameObjects("root", true, nullptr, Tag_Object_Enum::root_tag, false);
	root_gameobject->Childrens_GameObject_Vect.push_back(CreateNewGameObjects("geometry1", true, root_gameobject, Tag_Object_Enum::no_obj_tag, false));
	root_gameobject->Childrens_GameObject_Vect[0]->AddNewTransform(float3(10,15,1), float3(0, 0, 0), Quat(1,0,0,0));
	temp = root_gameobject->Childrens_GameObject_Vect[0]->AddNewMaterial(path_temp2.c_str(),path_temp.c_str());
	root_gameobject->Childrens_GameObject_Vect[0]->AddNewMesh(path_temp.c_str(), temp);

	return ret;
}

update_status ModuleSceneIntro::PreUpdate(float dt)
{
	world_texture->Bind();

	return UPDATE_CONTINUE;
}

// Update
update_status ModuleSceneIntro::Update(float dt)
{

	for (int i = 0; i < root_gameobject->Childrens_GameObject_Vect.size(); i++) {
		root_gameobject->Childrens_GameObject_Vect[i]->Update();
	}

	glLineWidth(5.0f);
	glBegin(GL_LINES);
	glColor3f(0, 1, 0);
	glVertex3f(0.f, 0.f, 0.f);
	glVertex3f(0.f, 3.f, 0.f);

	glEnd();
	glColor3f(1, 1, 1);

	glLineWidth(5.0f);
	glBegin(GL_LINES);
	glColor3f(1, 0, 0);
	glVertex3f(0.f, 0.f, 0.f);
	glVertex3f(3.f, 0.f, 0.f);

	glEnd();
	glColor3f(1, 1, 1);

	glLineWidth(5.0f);
	glBegin(GL_LINES);
	glColor3f(0, 0, 1);
	glVertex3f(0.f, 0.f, 0.f);
	glVertex3f(0.f, 0.f, 3.f);

	glEnd();
	glColor3f(1, 1, 1);

//	 light 0 on cam pos
	lights[0].SetPos(App->camera->Position.x, App->camera->Position.y, App->camera->Position.z);

	for(uint i = 0; i < MAX_LIGHTS; ++i)
	lights[i].Render();

	return UPDATE_CONTINUE;
}

void ModuleSceneIntro::OnCollision(PhysBody3D* body1, PhysBody3D* body2)
{

}

update_status ModuleSceneIntro::PostUpdate(float dt)
{

	return UPDATE_CONTINUE;
}

bool ModuleSceneIntro::Gui_Engine_Modules(float dt)
{
	return true;
}

bool ModuleSceneIntro::CleanUp()
{

	return true;
}

GameObject * ModuleSceneIntro::CreateNewGameObjects(const char * name, bool active, GameObject* parent, Tag_Object_Enum tag_temp, bool static_s)
{

	std::string name_f = name;

	GameObject* n_gameobject = new GameObject(name_f, parent, active, tag_temp, static_s);

	return n_gameobject;
}

<commit_msg>fixed path to relative<commit_after>#include "Globals.h"
#include "Application.h"
#include "ModuleSceneIntro.h"
#include"GameObject.h"
#include"Component.h"
#include"Mesh.h"
#include"Transform.h"

ModuleSceneIntro::ModuleSceneIntro(bool start_enabled) : Module(start_enabled)
{
}

ModuleSceneIntro::~ModuleSceneIntro()
{}

// Load assets
bool ModuleSceneIntro::Start()
{
	bool ret = true;

	GLfloat LightModelAmbient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
	glLightModelfv(GL_LIGHT_MODEL_AMBIENT, LightModelAmbient);
	lights[0].ref = GL_LIGHT0;
	lights[0].ambient.Set(0.5f, 0.5f, 0.5f, 1.0f);
	lights[0].diffuse.Set(.5f, .5f, 0.5f, 1.0f);
	lights[0].SetPos(1.0f, 0.0f, 2.5f);
	lights[0].Init();

	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);
	lights[0].Active(true);
	glEnable(GL_LIGHTING);
	glEnable(GL_COLOR_MATERIAL);

	world_texture = new Texture_Engine();
	world_texture->Create(nullptr, App->window->win_width, App->window->win_height);
	std::string path_temp = "..\\Game\\Data\\BakerHouse.fbx";
	std::string path_temp2 = "..\\Game\\Data\\Baker_house.png";
	Material* temp = nullptr;

	root_gameobject = CreateNewGameObjects("root", true, nullptr, Tag_Object_Enum::root_tag, false);
	root_gameobject->Childrens_GameObject_Vect.push_back(CreateNewGameObjects("geometry1", true, root_gameobject, Tag_Object_Enum::no_obj_tag, false));
	root_gameobject->Childrens_GameObject_Vect[0]->AddNewTransform(float3(10,15,1), float3(0, 0, 0), Quat(1,0,0,0));
	temp = root_gameobject->Childrens_GameObject_Vect[0]->AddNewMaterial(path_temp2.c_str(),path_temp.c_str());
	root_gameobject->Childrens_GameObject_Vect[0]->AddNewMesh(path_temp.c_str(), temp);

	return ret;
}

update_status ModuleSceneIntro::PreUpdate(float dt)
{
	world_texture->Bind();

	return UPDATE_CONTINUE;
}

// Update
update_status ModuleSceneIntro::Update(float dt)
{

	for (int i = 0; i < root_gameobject->Childrens_GameObject_Vect.size(); i++) {
		root_gameobject->Childrens_GameObject_Vect[i]->Update();
	}

	glLineWidth(5.0f);
	glBegin(GL_LINES);
	glColor3f(0, 1, 0);
	glVertex3f(0.f, 0.f, 0.f);
	glVertex3f(0.f, 3.f, 0.f);

	glEnd();
	glColor3f(1, 1, 1);

	glLineWidth(5.0f);
	glBegin(GL_LINES);
	glColor3f(1, 0, 0);
	glVertex3f(0.f, 0.f, 0.f);
	glVertex3f(3.f, 0.f, 0.f);

	glEnd();
	glColor3f(1, 1, 1);

	glLineWidth(5.0f);
	glBegin(GL_LINES);
	glColor3f(0, 0, 1);
	glVertex3f(0.f, 0.f, 0.f);
	glVertex3f(0.f, 0.f, 3.f);

	glEnd();
	glColor3f(1, 1, 1);

//	 light 0 on cam pos
	lights[0].SetPos(App->camera->Position.x, App->camera->Position.y, App->camera->Position.z);

	for(uint i = 0; i < MAX_LIGHTS; ++i)
	lights[i].Render();

	return UPDATE_CONTINUE;
}

void ModuleSceneIntro::OnCollision(PhysBody3D* body1, PhysBody3D* body2)
{

}

update_status ModuleSceneIntro::PostUpdate(float dt)
{

	return UPDATE_CONTINUE;
}

bool ModuleSceneIntro::Gui_Engine_Modules(float dt)
{
	return true;
}

bool ModuleSceneIntro::CleanUp()
{

	return true;
}

GameObject * ModuleSceneIntro::CreateNewGameObjects(const char * name, bool active, GameObject* parent, Tag_Object_Enum tag_temp, bool static_s)
{

	std::string name_f = name;

	GameObject* n_gameobject = new GameObject(name_f, parent, active, tag_temp, static_s);

	return n_gameobject;
}

<|endoftext|>


<commit_before>#include <unistd.h> //for read()

struct FLV_Pack {
  int len;
  int buf;
  char * data;
};//FLV_Pack

char FLVHeader[13];

//reads full length from a file descriptor
void Magic_Read(char * buf, int len, int file){
  int i = 0;
  while (i < len) i += read(file, buf, len-i);
}

//reads a FLV header and checks for correctness
//returns true if everything is alright, false otherwise
bool FLV_Readheader(){
  fread(FLVHeader,1,13,stdin);
  if (FLVHeader[0] != 'F') return false;
  if (FLVHeader[1] != 'L') return false;
  if (FLVHeader[2] != 'V') return false;
  if (FLVHeader[8] != 0x09) return false;
  if (FLVHeader[9] != 0) return false;
  if (FLVHeader[10] != 0) return false;
  if (FLVHeader[11] != 0) return false;
  if (FLVHeader[12] != 0) return false;
  return true;
}//FLV_Readheader

//gets a packet, storing in given FLV_Pack pointer.
//will assign pointer if null
//resizes FLV_Pack data field bigger if data doesn't fit
// (does not auto-shrink for speed!)
void FLV_GetPacket(FLV_Pack *& p){
  if (!p){p = (FLV_Pack*)calloc(1, sizeof(FLV_Pack));}
  if (p->buf < 15){p->data = (char*)realloc(p->data, 15); p->buf = 15;}
  fread(p->data,1,11,stdin);
  p->len = p->data[3] + 15;
  p->len += (p->data[2] << 8);
  p->len += (p->data[1] << 16);
  if (p->buf < p->len){p->data = (char*)realloc(p->data, p->len);p->buf = p->len;}
  fread(p->data+11,1,p->len-11,stdin);
}//FLV_GetPacket
<commit_msg>Stabiliteitsfixes en in theorie werkende H.264 en AAC, maar je weet maar nooit...<commit_after>#include <unistd.h> //for read()

struct FLV_Pack {
  int len;
  int buf;
  bool isKeyframe;
  char * data;
};//FLV_Pack

char FLVHeader[13];

//reads full length from a file descriptor
void Magic_Read(char * buf, int len, int file){
  int i = 0;
  while (i < len) i += read(file, buf, len-i);
}

//reads a FLV header and checks for correctness
//returns true if everything is alright, false otherwise
bool FLV_Readheader(){
  fread(FLVHeader,1,13,stdin);
  if (FLVHeader[0] != 'F') return false;
  if (FLVHeader[1] != 'L') return false;
  if (FLVHeader[2] != 'V') return false;
  if (FLVHeader[8] != 0x09) return false;
  if (FLVHeader[9] != 0) return false;
  if (FLVHeader[10] != 0) return false;
  if (FLVHeader[11] != 0) return false;
  if (FLVHeader[12] != 0) return false;
  return true;
}//FLV_Readheader

//gets a packet, storing in given FLV_Pack pointer.
//will assign pointer if null
//resizes FLV_Pack data field bigger if data doesn't fit
// (does not auto-shrink for speed!)
void FLV_GetPacket(FLV_Pack *& p){
  if (!p){p = (FLV_Pack*)calloc(1, sizeof(FLV_Pack));}
  if (p->buf < 15){p->data = (char*)realloc(p->data, 15); p->buf = 15;}
  fread(p->data,1,11,stdin);
  p->len = p->data[3] + 15;
  p->len += (p->data[2] << 8);
  p->len += (p->data[1] << 16);
  if (p->buf < p->len){p->data = (char*)realloc(p->data, p->len);p->buf = p->len;}
  fread(p->data+11,1,p->len-11,stdin);
  p->isKeyframe = false;
  if ((p->data[0] == 0x09) && (((p->data[11] & 0xf0) >> 4) == 1)){p->isKeyframe = true;}
}//FLV_GetPacket
<|endoftext|>