<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2020 Intel Corporation. All Rights Reserved.

//#cmake:add-file ../../../src/algo/depth-to-rgb-calibration/*.cpp

#ifndef BUILD_SHARED_LIBS
#include <easylogging++.h>
INITIALIZE_EASYLOGGINGPP
#endif

// We have our own main
#define NO_CATCH_CONFIG_MAIN
//#define CATCH_CONFIG_RUNNER

#include "d2rgb-common.h"

//INITIALIZE_EASYLOGGINGPP

template< typename T >
void read_binary_file( char const * dir, char const * bin, T * data )
{
    std::string filename = dir;
    filename += "\\";
    filename += bin;
    AC_LOG( DEBUG, "... " << filename );
    std::fstream f = std::fstream( filename, std::ios::in | std::ios::binary );
    if( ! f )
        throw std::runtime_error( "failed to read file:\n" + filename );
    f.seekg( 0, f.end );
    size_t cb = f.tellg();
    f.seekg( 0, f.beg );
    if( cb != sizeof( T ) )
        throw std::runtime_error( to_string()
            << "file size (" << cb << ") does not match data size (" << sizeof(T) << "): " << filename );
    std::vector< T > vec( cb / sizeof( T ));
    f.read( (char*) data, cb );
    f.close();
}

struct old_algo_calib
{
    algo::matrix_3x3 rot;
    algo::translation trans;
    double __fx, __fy, __ppx, __ppy;  // not in new calib!
    algo::k_matrix k_mat;
    int           width, height;
    rs2_distortion model;
    double         coeffs[5];

    operator algo::calib() const
    {
        algo::calib c;
        c.rot = rot;
        c.trans = trans;
        c.k_mat = k_mat;
        c.width = width;
        c.height = height;
        c.model = model;
        for( auto x = 0; x < 5; ++x )
            c.coeffs[x] = coeffs[x];
        return c;
    }
};

int main( int argc, char * argv[] )
{
    bool ok = true;
    // Each of the arguments is the path to a directory to simulate
    // We skip argv[0] which is the path to the executable
    // We don't complain if no arguments -- that's how we'll run as part of unit-testing
    for( int i = 1; i < argc; ++i )
    {
        try
        {
            char const * dir = argv[i];
            std::cout << "Processing: " << dir << " ..." << std::endl;

            algo::calib calibration;
            try
            {
                read_binary_file( dir, "rgb.calib", &calibration );
            }
            catch( std::exception const & e )
            {
                std::cout << "!! failed: " << e.what() << std::endl;
                old_algo_calib old_calibration;
                read_binary_file( dir, "rgb.calib", &old_calibration );
                calibration = old_calibration;
            }

            camera_params camera;
            camera.rgb = calibration.get_intrinsics();
            camera.extrinsics = calibration.get_extrinsics();
            algo::rs2_intrinsics_double d_intr;  // intrinsics written in double!
            read_binary_file( dir, "depth.intrinsics", &d_intr );
            camera.z = d_intr;
            read_binary_file( dir, "depth.units", &camera.z_units );
            read_binary_file( dir, "cal.info", &camera.cal_info );
            read_binary_file( dir, "cal.registers", &camera.cal_regs );
            read_binary_file( dir, "dsm.params", &camera.dsm_params );

            algo::optimizer cal;
            init_algo( cal, dir, "\\rgb.raw", "\\rgb_prev.raw", "\\ir.raw", "\\depth.raw", camera );

            std::string status;

            TRACE( "\n___\nis_scene_valid" );
            if( !cal.is_scene_valid() )
            {
                TRACE("NOT VALID\n");
                status += "SCENE_INVALID ";
            }

            TRACE( "\n___\noptimize" );
            size_t n_iteration = cal.optimize(
                []( algo::data_collect const & data )
                {
                } );

            TRACE( "\n___\nis_valid_results" );
            if( !cal.is_valid_results() )
            {
                TRACE("NOT VALID\n");
                status += "BAD_RESULT";
            }
            else
            {
                status += "SUCCESSFUL";
            }
            TRACE( "\n___\nRESULTS:" );

            auto intr = cal.get_calibration().get_intrinsics();
            auto extr = cal.get_calibration().get_extrinsics();
            AC_LOG( DEBUG, AC_D_PREC
                << "intr[ "
                << intr.width << "x" << intr.height
                << "  ppx: " << intr.ppx << ", ppy: " << intr.ppy << ", fx: " << intr.fx
                << ", fy: " << intr.fy << ", model: " << int( intr.model ) << " coeffs["
                << intr.coeffs[0] << ", " << intr.coeffs[1] << ", " << intr.coeffs[2]
                << ", " << intr.coeffs[3] << ", " << intr.coeffs[4] << "] ]" );
            AC_LOG( DEBUG, AC_D_PREC << "extr" << (rs2_extrinsics) extr );
            AC_LOG( DEBUG, AC_D_PREC << "dsm" << cal.get_dsm_params() );

            TRACE( "\n___\nVS:" );
            AC_LOG( DEBUG, AC_D_PREC << "dsm" << camera.dsm_params );

            TRACE( "\n___\nSTATUS: " + status );
        }
        catch( std::exception const & e )
        {
            std::cerr << "\n___\ncaught exception: " << e.what() << std::endl;
            ok = false;
        }
        catch( ... )
        {
            std::cerr << "\n___\ncaught unknown exception!" << std::endl;
            ok = false;
        }
    }

    return ! ok;
}

<commit_msg>update test-repro<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2020 Intel Corporation. All Rights Reserved.

//#cmake:add-file ../../../src/algo/depth-to-rgb-calibration/*.cpp

#ifndef BUILD_SHARED_LIBS
#include <easylogging++.h>
INITIALIZE_EASYLOGGINGPP
#endif

// We have our own main
#define NO_CATCH_CONFIG_MAIN
//#define CATCH_CONFIG_RUNNER

#include "d2rgb-common.h"

//INITIALIZE_EASYLOGGINGPP

template< typename T >
void read_binary_file( char const * dir, char const * bin, T * data )
{
    std::string filename = dir;
    filename += "\\";
    filename += bin;
    AC_LOG( DEBUG, "... " << filename );
    std::fstream f = std::fstream( filename, std::ios::in | std::ios::binary );
    if( ! f )
        throw std::runtime_error( "failed to read file:\n" + filename );
    f.seekg( 0, f.end );
    size_t cb = f.tellg();
    f.seekg( 0, f.beg );
    if( cb != sizeof( T ) )
        throw std::runtime_error( to_string()
            << "file size (" << cb << ") does not match data size (" << sizeof(T) << "): " << filename );
    std::vector< T > vec( cb / sizeof( T ));
    f.read( (char*) data, cb );
    f.close();
}

struct old_algo_calib
{
    algo::matrix_3x3 rot;
    algo::translation trans;
    double __fx, __fy, __ppx, __ppy;  // not in new calib!
    algo::k_matrix k_mat;
    int           width, height;
    rs2_distortion model;
    double         coeffs[5];

    operator algo::calib() const
    {
        algo::calib c;
        c.rot = rot;
        c.trans = trans;
        c.k_mat = k_mat;
        c.width = width;
        c.height = height;
        c.model = model;
        for( auto x = 0; x < 5; ++x )
            c.coeffs[x] = coeffs[x];
        return c;
    }
};

int main( int argc, char * argv[] )
{
    bool ok = true;
    // Each of the arguments is the path to a directory to simulate
    // We skip argv[0] which is the path to the executable
    // We don't complain if no arguments -- that's how we'll run as part of unit-testing
    for( int i = 1; i < argc; ++i )
    {
        try
        {
            char const * dir = argv[i];
            if( !strcmp( dir, "--version" ) )
            {
                // The build number is only available within Jenkins and so we have to hard-
                // code it ><
                std::cout << RS2_API_VERSION_STR << ".1973" << std::endl;
                continue;
            }
            std::cout << "Processing: " << dir << " ..." << std::endl;

            algo::calib calibration;
            try
            {
                read_binary_file( dir, "rgb.calib", &calibration );
            }
            catch( std::exception const & e )
            {
                std::cout << "!! failed: " << e.what() << std::endl;
                old_algo_calib old_calibration;
                read_binary_file( dir, "rgb.calib", &old_calibration );
                calibration = old_calibration;
            }

            camera_params camera;
            camera.rgb = calibration.get_intrinsics();
            camera.extrinsics = calibration.get_extrinsics();
            algo::rs2_intrinsics_double d_intr;  // intrinsics written in double!
            read_binary_file( dir, "depth.intrinsics", &d_intr );
            camera.z = d_intr;
            read_binary_file( dir, "depth.units", &camera.z_units );
            read_binary_file( dir, "cal.info", &camera.cal_info );
            read_binary_file( dir, "cal.registers", &camera.cal_regs );
            read_binary_file( dir, "dsm.params", &camera.dsm_params );

            algo::optimizer cal;
            init_algo( cal, dir, "\\rgb.raw", "\\rgb_prev.raw", "\\ir.raw", "\\depth.raw", camera );

            std::string status;

            TRACE( "\n___\nis_scene_valid" );
            if( !cal.is_scene_valid() )
            {
                TRACE("NOT VALID\n");
                status += "SCENE_INVALID ";
            }

            TRACE( "\n___\noptimize" );
            size_t n_iteration = cal.optimize(
                []( algo::data_collect const & data )
                {
                } );

            TRACE( "\n___\nis_valid_results" );
            if( !cal.is_valid_results() )
            {
                TRACE("NOT VALID\n");
                status += "BAD_RESULT";
            }
            else
            {
                status += "SUCCESSFUL";
            }
            TRACE( "\n___\nRESULTS:  (" << RS2_API_VERSION_STR << " build 1973)" );

            auto intr = cal.get_calibration().get_intrinsics();
            auto extr = cal.get_calibration().get_extrinsics();
            AC_LOG( DEBUG, AC_D_PREC
                << "intr[ "
                << intr.width << "x" << intr.height
                << "  ppx: " << intr.ppx << ", ppy: " << intr.ppy << ", fx: " << intr.fx
                << ", fy: " << intr.fy << ", model: " << int( intr.model ) << " coeffs["
                << intr.coeffs[0] << ", " << intr.coeffs[1] << ", " << intr.coeffs[2]
                << ", " << intr.coeffs[3] << ", " << intr.coeffs[4] << "] ]" );
            AC_LOG( DEBUG, AC_D_PREC << "extr" << (rs2_extrinsics) extr );
            AC_LOG( DEBUG, AC_D_PREC << "dsm" << cal.get_dsm_params() );

            TRACE( "\n___\nVS:" );
            AC_LOG( DEBUG, AC_D_PREC << "dsm" << camera.dsm_params );

            TRACE( "\n___\nSTATUS: " + status );
        }
        catch( std::exception const & e )
        {
            std::cerr << "\n___\ncaught exception: " << e.what() << std::endl;
            ok = false;
        }
        catch( ... )
        {
            std::cerr << "\n___\ncaught unknown exception!" << std::endl;
            ok = false;
        }
    }

    return ! ok;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sharedunocomponent.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 14:08:36 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef UNOTOOLS_INC_SHAREDUNOCOMPONENT_HXX
#include <unotools/sharedunocomponent.hxx>
#endif

#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCLOSEABLE_HPP_
#include <com/sun/star/util/XCloseable.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

//............................................................................
namespace utl
{
//............................................................................

    using ::com::sun::star::uno::XInterface;
    using ::com::sun::star::uno::Reference;
    using ::com::sun::star::uno::Exception;
    using ::com::sun::star::uno::UNO_QUERY;
    using ::com::sun::star::uno::RuntimeException;
    using ::com::sun::star::lang::XComponent;
    using ::com::sun::star::lang::EventObject;
    using ::com::sun::star::util::XCloseable;
    using ::com::sun::star::util::XCloseListener;
    using ::com::sun::star::util::CloseVetoException;

    //========================================================================
    //= DisposableComponent
    //========================================================================
    //------------------------------------------------------------------------
    DisposableComponent::DisposableComponent( const Reference< XInterface >& _rxComponent )
        :m_xComponent( _rxComponent, UNO_QUERY )
    {
        DBG_ASSERT( m_xComponent.is() || !_rxComponent.is(), "DisposableComponent::DisposableComponent: should be an XComponent!" );
    }

    //------------------------------------------------------------------------
    DisposableComponent::~DisposableComponent()
    {
        if ( m_xComponent.is() )
        {
            try
            {
                m_xComponent->dispose();
            }
            catch( const Exception& )
            {
                OSL_ENSURE( sal_False, "DisposableComponent::~DisposableComponent: caught an exception!" );
            }
            m_xComponent.clear();
        }
    }

    //========================================================================
    //= CloseableComponentImpl
    //========================================================================
    DBG_NAME( CloseableComponentImpl )
    typedef ::cppu::WeakImplHelper1 <   XCloseListener
                                    >   CloseableComponentImpl_Base;
    class CloseableComponentImpl : public CloseableComponentImpl_Base
    {
    private:
        Reference< XCloseable > m_xCloseable;

    public:
        CloseableComponentImpl( const Reference< XInterface >& _rxComponent );

        /** closes the component

            @nofail
        */
        void    nf_closeComponent();

    protected:
        virtual ~CloseableComponentImpl();

        // XCloseListener overridables
        virtual void SAL_CALL queryClosing( const EventObject& Source, ::sal_Bool GetsOwnership ) throw (CloseVetoException, RuntimeException);
        virtual void SAL_CALL notifyClosing( const EventObject& Source ) throw (RuntimeException);

        // XEventListener overridables
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);

    private:
        /** starts or stops being a CloseListener at the component

            Only to be called upon construction of the instance, or when the component
            is to be closed.

        @nofail
        */
        void    impl_nf_switchListening( bool _bListen );

    private:
        CloseableComponentImpl();                                           // never implemented
        CloseableComponentImpl( const CloseableComponentImpl& );            // never implemented
        CloseableComponentImpl& operator=( const CloseableComponentImpl& ); // never implemented
    };

    //------------------------------------------------------------------------
    CloseableComponentImpl::CloseableComponentImpl( const Reference< XInterface >& _rxComponent )
        :m_xCloseable( _rxComponent, UNO_QUERY )
    {
        DBG_CTOR( CloseableComponentImpl, NULL );
        DBG_ASSERT( m_xCloseable.is() || !_rxComponent.is(), "CloseableComponentImpl::CloseableComponentImpl: component is not an XCloseable!" );
        impl_nf_switchListening( true );
    }
    //------------------------------------------------------------------------
    CloseableComponentImpl::~CloseableComponentImpl()
    {
        nf_closeComponent();
        DBG_DTOR( CloseableComponentImpl, NULL );
    }

    //------------------------------------------------------------------------
    void CloseableComponentImpl::nf_closeComponent()
    {
        if ( !m_xCloseable.is() )
            // nothing to do
            return;

        // stop listening
        impl_nf_switchListening( false );

        // close
        try
        {
            m_xCloseable->close( sal_True );
        }
        catch( const CloseVetoException& ) { /* fine */ }
        catch( const Exception& )
        {
            OSL_ENSURE( sal_False, "CloseableComponentImpl::nf_closeComponent: caught an unexpected exception!" );
        }

        // reset
        m_xCloseable.clear();
    }

    //------------------------------------------------------------------------
    void CloseableComponentImpl::impl_nf_switchListening( bool _bListen )
    {
        if ( !m_xCloseable.is() )
            return;

        try
        {
            if ( _bListen )
                m_xCloseable->addCloseListener( this );
            else
                m_xCloseable->removeCloseListener( this );
        }
        catch( const Exception& )
        {
            OSL_ENSURE( sal_False, "CloseableComponentImpl::impl_nf_switchListening: caught an exception!" );
        }
    }

    //--------------------------------------------------------------------
    void SAL_CALL CloseableComponentImpl::queryClosing( const EventObject&
    #ifdef DBG_UTIL
    Source
    #endif
    , ::sal_Bool /*GetsOwnership*/ ) throw (CloseVetoException, RuntimeException)
    {
        // as long as we live, somebody wants to keep the object alive. So, veto the
        // closing
        DBG_ASSERT( Source.Source == m_xCloseable, "CloseableComponentImpl::queryClosing: where did this come from?" );
        throw CloseVetoException();
    }

    //--------------------------------------------------------------------
    void SAL_CALL CloseableComponentImpl::notifyClosing( const EventObject&
    #ifdef DBG_UTIL
    Source
    #endif
    ) throw (RuntimeException)
    {
        DBG_ASSERT( Source.Source == m_xCloseable, "CloseableComponentImpl::notifyClosing: where did this come from?" );

        // this should be unreachable: As long as we're a CloseListener, we veto the closing. If we're going
        // to close the component ourself, then we revoke ourself as listener *before* the close call. So,
        // if this here fires, something went definately wrong.
        DBG_ERROR( "CloseableComponentImpl::notifyClosing: unreachable!" );
    }

    //--------------------------------------------------------------------
    void SAL_CALL CloseableComponentImpl::disposing( const EventObject&
    #ifdef DBG_UTIL
    Source
    #endif
    ) throw (RuntimeException)
    {
        DBG_ASSERT( Source.Source == m_xCloseable, "CloseableComponentImpl::disposing: where did this come from?" );
        DBG_ERROR( "CloseableComponentImpl::disposing: unreachable!" );
            // same reasoning for this assertion as in ->notifyClosing
    }

    //========================================================================
    //= CloseableComponentImpl
    //========================================================================
    DBG_NAME( CloseableComponent )
    //------------------------------------------------------------------------
    CloseableComponent::CloseableComponent( const Reference< XInterface >& _rxComponent )
        :m_pImpl( new CloseableComponentImpl( _rxComponent ) )
    {
        DBG_CTOR( CloseableComponent, NULL );
    }

    //------------------------------------------------------------------------
    CloseableComponent::~CloseableComponent()
    {
        // close the component, deliver ownership to anybody who wants to veto the close
        m_pImpl->nf_closeComponent();
        DBG_DTOR( CloseableComponent, NULL );
    }

//............................................................................
}   // namespace utl
//............................................................................
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.16); FILE MERGED 2006/09/01 17:56:24 kaib 1.5.16.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sharedunocomponent.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 01:27:51 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_unotools.hxx"

#ifndef UNOTOOLS_INC_SHAREDUNOCOMPONENT_HXX
#include <unotools/sharedunocomponent.hxx>
#endif

#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCLOSEABLE_HPP_
#include <com/sun/star/util/XCloseable.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

//............................................................................
namespace utl
{
//............................................................................

    using ::com::sun::star::uno::XInterface;
    using ::com::sun::star::uno::Reference;
    using ::com::sun::star::uno::Exception;
    using ::com::sun::star::uno::UNO_QUERY;
    using ::com::sun::star::uno::RuntimeException;
    using ::com::sun::star::lang::XComponent;
    using ::com::sun::star::lang::EventObject;
    using ::com::sun::star::util::XCloseable;
    using ::com::sun::star::util::XCloseListener;
    using ::com::sun::star::util::CloseVetoException;

    //========================================================================
    //= DisposableComponent
    //========================================================================
    //------------------------------------------------------------------------
    DisposableComponent::DisposableComponent( const Reference< XInterface >& _rxComponent )
        :m_xComponent( _rxComponent, UNO_QUERY )
    {
        DBG_ASSERT( m_xComponent.is() || !_rxComponent.is(), "DisposableComponent::DisposableComponent: should be an XComponent!" );
    }

    //------------------------------------------------------------------------
    DisposableComponent::~DisposableComponent()
    {
        if ( m_xComponent.is() )
        {
            try
            {
                m_xComponent->dispose();
            }
            catch( const Exception& )
            {
                OSL_ENSURE( sal_False, "DisposableComponent::~DisposableComponent: caught an exception!" );
            }
            m_xComponent.clear();
        }
    }

    //========================================================================
    //= CloseableComponentImpl
    //========================================================================
    DBG_NAME( CloseableComponentImpl )
    typedef ::cppu::WeakImplHelper1 <   XCloseListener
                                    >   CloseableComponentImpl_Base;
    class CloseableComponentImpl : public CloseableComponentImpl_Base
    {
    private:
        Reference< XCloseable > m_xCloseable;

    public:
        CloseableComponentImpl( const Reference< XInterface >& _rxComponent );

        /** closes the component

            @nofail
        */
        void    nf_closeComponent();

    protected:
        virtual ~CloseableComponentImpl();

        // XCloseListener overridables
        virtual void SAL_CALL queryClosing( const EventObject& Source, ::sal_Bool GetsOwnership ) throw (CloseVetoException, RuntimeException);
        virtual void SAL_CALL notifyClosing( const EventObject& Source ) throw (RuntimeException);

        // XEventListener overridables
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);

    private:
        /** starts or stops being a CloseListener at the component

            Only to be called upon construction of the instance, or when the component
            is to be closed.

        @nofail
        */
        void    impl_nf_switchListening( bool _bListen );

    private:
        CloseableComponentImpl();                                           // never implemented
        CloseableComponentImpl( const CloseableComponentImpl& );            // never implemented
        CloseableComponentImpl& operator=( const CloseableComponentImpl& ); // never implemented
    };

    //------------------------------------------------------------------------
    CloseableComponentImpl::CloseableComponentImpl( const Reference< XInterface >& _rxComponent )
        :m_xCloseable( _rxComponent, UNO_QUERY )
    {
        DBG_CTOR( CloseableComponentImpl, NULL );
        DBG_ASSERT( m_xCloseable.is() || !_rxComponent.is(), "CloseableComponentImpl::CloseableComponentImpl: component is not an XCloseable!" );
        impl_nf_switchListening( true );
    }
    //------------------------------------------------------------------------
    CloseableComponentImpl::~CloseableComponentImpl()
    {
        nf_closeComponent();
        DBG_DTOR( CloseableComponentImpl, NULL );
    }

    //------------------------------------------------------------------------
    void CloseableComponentImpl::nf_closeComponent()
    {
        if ( !m_xCloseable.is() )
            // nothing to do
            return;

        // stop listening
        impl_nf_switchListening( false );

        // close
        try
        {
            m_xCloseable->close( sal_True );
        }
        catch( const CloseVetoException& ) { /* fine */ }
        catch( const Exception& )
        {
            OSL_ENSURE( sal_False, "CloseableComponentImpl::nf_closeComponent: caught an unexpected exception!" );
        }

        // reset
        m_xCloseable.clear();
    }

    //------------------------------------------------------------------------
    void CloseableComponentImpl::impl_nf_switchListening( bool _bListen )
    {
        if ( !m_xCloseable.is() )
            return;

        try
        {
            if ( _bListen )
                m_xCloseable->addCloseListener( this );
            else
                m_xCloseable->removeCloseListener( this );
        }
        catch( const Exception& )
        {
            OSL_ENSURE( sal_False, "CloseableComponentImpl::impl_nf_switchListening: caught an exception!" );
        }
    }

    //--------------------------------------------------------------------
    void SAL_CALL CloseableComponentImpl::queryClosing( const EventObject&
    #ifdef DBG_UTIL
    Source
    #endif
    , ::sal_Bool /*GetsOwnership*/ ) throw (CloseVetoException, RuntimeException)
    {
        // as long as we live, somebody wants to keep the object alive. So, veto the
        // closing
        DBG_ASSERT( Source.Source == m_xCloseable, "CloseableComponentImpl::queryClosing: where did this come from?" );
        throw CloseVetoException();
    }

    //--------------------------------------------------------------------
    void SAL_CALL CloseableComponentImpl::notifyClosing( const EventObject&
    #ifdef DBG_UTIL
    Source
    #endif
    ) throw (RuntimeException)
    {
        DBG_ASSERT( Source.Source == m_xCloseable, "CloseableComponentImpl::notifyClosing: where did this come from?" );

        // this should be unreachable: As long as we're a CloseListener, we veto the closing. If we're going
        // to close the component ourself, then we revoke ourself as listener *before* the close call. So,
        // if this here fires, something went definately wrong.
        DBG_ERROR( "CloseableComponentImpl::notifyClosing: unreachable!" );
    }

    //--------------------------------------------------------------------
    void SAL_CALL CloseableComponentImpl::disposing( const EventObject&
    #ifdef DBG_UTIL
    Source
    #endif
    ) throw (RuntimeException)
    {
        DBG_ASSERT( Source.Source == m_xCloseable, "CloseableComponentImpl::disposing: where did this come from?" );
        DBG_ERROR( "CloseableComponentImpl::disposing: unreachable!" );
            // same reasoning for this assertion as in ->notifyClosing
    }

    //========================================================================
    //= CloseableComponentImpl
    //========================================================================
    DBG_NAME( CloseableComponent )
    //------------------------------------------------------------------------
    CloseableComponent::CloseableComponent( const Reference< XInterface >& _rxComponent )
        :m_pImpl( new CloseableComponentImpl( _rxComponent ) )
    {
        DBG_CTOR( CloseableComponent, NULL );
    }

    //------------------------------------------------------------------------
    CloseableComponent::~CloseableComponent()
    {
        // close the component, deliver ownership to anybody who wants to veto the close
        m_pImpl->nf_closeComponent();
        DBG_DTOR( CloseableComponent, NULL );
    }

//............................................................................
}   // namespace utl
//............................................................................
<|endoftext|>


<commit_before>/** @file
 *
 * @ingroup dspFunctionLib
 *
 * @brief #TTFunction is a generalized function wrapper for Jamoma DSP
 *
 * @details All functions will map incoming values in the normalised range [0,1] to output values in the normalised range [0,1].
 *
 * @authors Tim Place, Trond Lossius
 *
 * @copyright Copyright © 2010 by Tim Place @n
 * This code is licensed under the terms of the "New BSD License" @n
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTFunction.h"

#define thisTTClass			TTFunction
#define thisTTClassName		"function"
#define thisTTClassTags		"dspFunctionLib, audio, processor"

TT_AUDIO_CONSTRUCTOR,
	mFunctionObject(NULL),
	mNumPoints(8192),
	mPadding(0)
{
	addAttributeWithSetter(Function,	kTypeSymbol);
	addAttributeWithSetter(NumPoints,	kTypeUInt32);
	addAttributeWithSetter(Mode,		kTypeSymbol);
	addAttributeWithSetter(Padding,		kTypeUInt32);

	addMessageWithArguments(getFunctions);

	setAttributeValue(TT("function"), TT("linear"));
	setAttributeValue(TT("mode"), TT("generate"));
}

TTFunction::~TTFunction()
{
	delete mFunctionObject;
}

TTErr TTFunction::setFunction(const TTValue& function)
{
	TTErr err;

	mFunction = function;
	err = TTObjectBaseInstantiate(mFunction, &mFunctionObject, mMaxNumChannels);
	if (!err)
		err = fill();
	return err;
}

TTErr TTFunction::fill()
{
	mLookupTable.assign(mNumPoints, 0.0);
	if (mFunctionObject) {
		TTInt32 numPoints = mNumPoints-(mPadding*2);

		TTLimitMin<TTInt32>(numPoints, 0);
		for (TTInt32 i=0; i<numPoints; i++)
			mFunctionObject->calculate(i/TTFloat64(numPoints), mLookupTable[i+mPadding]);
	}
	else
		mLookupTable.assign(mNumPoints, 0.0);

	return kTTErrNone;
}

TTErr TTFunction::setNumPoints(const TTValue& numPoints)
{
	return doSetNumPoints(numPoints);
}

TTErr TTFunction::doSetNumPoints(const TTUInt32 numPoints)
{
	mNumPoints = numPoints;
	mLookupTable.resize(mNumPoints);
	return fill();
}

TTErr TTFunction::setPadding(const TTValue& padding)
{
	mPadding = padding;
	return fill();
}

TTErr TTFunction::setMode(const TTValue& mode)
{
	mMode = mode;
	if (mMode == TT("apply")) {
		setProcessMethod(processApply);
		setCalculateMethod(lookupValue);
	}
	else if (mMode == TT("generate")) {
		setProcessMethod(processGenerate);
		setCalculateMethod(calculateValue);
	}
	else {
		setProcessMethod(processLookup);
		setCalculateMethod(lookupValue);
	}
	return kTTErrNone;
}

TTErr TTFunction::getFunctions(const TTValue&, TTValue& listOfWindowTypesToReturn)
{
	return TTGetRegisteredClassNamesForTags(listOfWindowTypesToReturn, TT("function"));
}

#if 0
#pragma mark -
#pragma mark Process Routines
#endif

inline TTErr TTFunction::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
	return mFunctionObject->calculate(x, y);
}

inline TTErr TTFunction::lookupValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
	y = mLookupTable[TTClip(x, 0.0, 1.0) * mNumPoints];
	return kTTErrNone;
}

TTErr TTFunction::processGenerate(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	return mFunctionObject->process(inputs, outputs);
}

TTErr TTFunction::processLookup(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TT_WRAP_CALCULATE_METHOD(lookupValue)
}

TTErr TTFunction::processApply(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TTAudioSignal&		in = inputs->getSignal(0);
	TTAudioSignal&		out = outputs->getSignal(0);
	TTUInt16			vs = in.getVectorSizeAsInt();
	TTSampleValuePtr	inSample;
	TTSampleValuePtr	outSample;
	TTUInt16			numChannels = TTAudioSignal::getMinChannelCount(in, out);
	TTUInt16			channel;

	// In 'apply' mode we automatically update the lookup table size to the vector size
	// This is slow, but hopefully only happens once (if ever)
	if (vs != mNumPoints)
		doSetNumPoints(vs);

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

		for (TTUInt32 i=0; i<vs; i++)
			*outSample++ = (*inSample++) * mLookupTable[i];
	}
	return kTTErrNone;
}

<commit_msg>replacing deprecated TTGetRegisteredClassNamesForTags with static TTObject method. see #244<commit_after>/** @file
 *
 * @ingroup dspFunctionLib
 *
 * @brief #TTFunction is a generalized function wrapper for Jamoma DSP
 *
 * @details All functions will map incoming values in the normalised range [0,1] to output values in the normalised range [0,1].
 *
 * @authors Tim Place, Trond Lossius
 *
 * @copyright Copyright © 2010 by Tim Place @n
 * This code is licensed under the terms of the "New BSD License" @n
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTFunction.h"

#define thisTTClass			TTFunction
#define thisTTClassName		"function"
#define thisTTClassTags		"dspFunctionLib, audio, processor"

TT_AUDIO_CONSTRUCTOR,
	mFunctionObject(NULL),
	mNumPoints(8192),
	mPadding(0)
{
	addAttributeWithSetter(Function,	kTypeSymbol);
	addAttributeWithSetter(NumPoints,	kTypeUInt32);
	addAttributeWithSetter(Mode,		kTypeSymbol);
	addAttributeWithSetter(Padding,		kTypeUInt32);

	addMessageWithArguments(getFunctions);

	setAttributeValue(TT("function"), TT("linear"));
	setAttributeValue(TT("mode"), TT("generate"));
}

TTFunction::~TTFunction()
{
	delete mFunctionObject;
}

TTErr TTFunction::setFunction(const TTValue& function)
{
	TTErr err;

	mFunction = function;
	err = TTObjectBaseInstantiate(mFunction, &mFunctionObject, mMaxNumChannels);
	if (!err)
		err = fill();
	return err;
}

TTErr TTFunction::fill()
{
	mLookupTable.assign(mNumPoints, 0.0);
	if (mFunctionObject) {
		TTInt32 numPoints = mNumPoints-(mPadding*2);

		TTLimitMin<TTInt32>(numPoints, 0);
		for (TTInt32 i=0; i<numPoints; i++)
			mFunctionObject->calculate(i/TTFloat64(numPoints), mLookupTable[i+mPadding]);
	}
	else
		mLookupTable.assign(mNumPoints, 0.0);

	return kTTErrNone;
}

TTErr TTFunction::setNumPoints(const TTValue& numPoints)
{
	return doSetNumPoints(numPoints);
}

TTErr TTFunction::doSetNumPoints(const TTUInt32 numPoints)
{
	mNumPoints = numPoints;
	mLookupTable.resize(mNumPoints);
	return fill();
}

TTErr TTFunction::setPadding(const TTValue& padding)
{
	mPadding = padding;
	return fill();
}

TTErr TTFunction::setMode(const TTValue& mode)
{
	mMode = mode;
	if (mMode == TT("apply")) {
		setProcessMethod(processApply);
		setCalculateMethod(lookupValue);
	}
	else if (mMode == TT("generate")) {
		setProcessMethod(processGenerate);
		setCalculateMethod(calculateValue);
	}
	else {
		setProcessMethod(processLookup);
		setCalculateMethod(lookupValue);
	}
	return kTTErrNone;
}

TTErr TTFunction::getFunctions(const TTValue&, TTValue& listOfWindowTypesToReturn)
{
	return TTObject::GetRegisteredClassNamesForTags(listOfWindowTypesToReturn, TT("function"));
}

#if 0
#pragma mark -
#pragma mark Process Routines
#endif

inline TTErr TTFunction::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
	return mFunctionObject->calculate(x, y);
}

inline TTErr TTFunction::lookupValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
	y = mLookupTable[TTClip(x, 0.0, 1.0) * mNumPoints];
	return kTTErrNone;
}

TTErr TTFunction::processGenerate(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	return mFunctionObject->process(inputs, outputs);
}

TTErr TTFunction::processLookup(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TT_WRAP_CALCULATE_METHOD(lookupValue)
}

TTErr TTFunction::processApply(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TTAudioSignal&		in = inputs->getSignal(0);
	TTAudioSignal&		out = outputs->getSignal(0);
	TTUInt16			vs = in.getVectorSizeAsInt();
	TTSampleValuePtr	inSample;
	TTSampleValuePtr	outSample;
	TTUInt16			numChannels = TTAudioSignal::getMinChannelCount(in, out);
	TTUInt16			channel;

	// In 'apply' mode we automatically update the lookup table size to the vector size
	// This is slow, but hopefully only happens once (if ever)
	if (vs != mNumPoints)
		doSetNumPoints(vs);

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

		for (TTUInt32 i=0; i<vs; i++)
			*outSample++ = (*inSample++) * mLookupTable[i];
	}
	return kTTErrNone;
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include <iostream>
#include <memory>
#include <string>

namespace use_after_destructor {

struct S {
  int* f;
  S(int i) {
    f = new int;
    *f = i;
  }

  // missing: operator= to copy the pointer. double delete can happen if
  // operator= is called

  ~S() { delete f; }
};

// destructor called at end of function, no issues
void normal_scope_destructor_ok() { S s(1); }

void nested_scope_destructor_ok() {
  { S s(1); }
}

int reinit_after_explicit_destructor_ok() {
  S s(1);
  s.~S();
  s = S(2);
  return *s.f;
}

int reinit_after_explicit_destructor2_bad() {
  S s(1);
  S s2(2);
  s.~S();
  s = s2; // operator=
  return *s.f;
  // [s2.f] is [s.f] so gets deleted twice
}

void placement_new_explicit_destructor_ok() {
  char buf[sizeof(S)];
  {
    S* s = new (buf) S(1);
    s->~S();
  }
  {
    // this use of [buf] shouldn't be flagged
    S* s = new (buf) S(2);
    s->~S();
  }
}

void double_destructor_bad() {
  S s(1);
  s.~S();
  // destructor will be called again after S goes out of scope, which is
  // undefined behavior
}

int use_after_destructor_bad() {
  S s(1);
  s.~S();
  int ret = *s.f;
  s = S{2};
  return ret;
}

// S::operator= doesn't copy resources correctly
void use_after_scope1_bad() {
  S s(1);
  {
    S tmp(2);
    s = tmp; // translated as operator=(s, tmp)
  } // destructor for tmp runs here
  // destructor for s here; second time the value held by s has been destructed
}

void FN_use_after_scope2_bad() {
  S s(1);
  {
    s = S(1);
  } // destructor runs here, but our frontend currently doesn't insert it
}

struct POD {
  int f;
};

// this code is ok since double-destructing POD struct is ok
void destruct_twice_ok() {
  POD p{1};
  {
    POD tmp{2};
    p = tmp;
  } // destructor for tmp
} // destructor for p runs here, but it's harmless

class Subclass : virtual POD {
  int* f;
  Subclass() { f = new int; }

  /** frontend code for this destructor will be:
   * ~Subclass:
   *  __infer_inner_destructor_~Subclass(this)
   *  __infer_inner_destructor_~POD(this)
   *
   * __infer_inner_destructor_~Subclass:
   *  delete f;
   *
   * We need to be careful not to warn that this has been double-destructed
   */
  ~Subclass() { delete f; }
};

void basic_placement_new_ok() {
  S* ptr = new S(1);
  S* tptr = new (ptr) S(1);
  tptr->~S();
  delete[] ptr;
}

int* destruct_pointer_contents_then_placement_new1_ok(S* s) {
  s->~S();
  new (s) S(1);
  return s->f;
}

int* destruct_pointer_contents_then_placement_new2_ok(S* s) {
  s->~S();
  new (&(s->f)) S(1);
  return s->f;
}

int* placement_new_aliasing1_bad() {
  S* s = new S(1);
  s->~S();
  auto alias = new (s) S(2);
  delete alias; // this deletes s too
  return s->f; // bad, accessing freed memory
}

int* placement_new_aliasing2_bad() {
  S* s = new S(1);
  s->~S();
  auto alias = new (s) S(2);
  delete s; // this deletes alias too
  return alias->f; // bad, accessing freed memory
}

int* placement_new_aliasing3_bad() {
  S* s = new S(1);
  s->~S();
  S* alias = s;
  auto alias_placement = new (s) S(2);
  delete s; // this deletes alias too
  return alias->f; // bad, accessing freed memory
}

void placement_new_non_var_ok() {
  struct M {
    S* s;
  } m;
  m.s = new S(1);
  m.s->~S();
  new (m.s) S(2);
  delete m.s;
}

void return_placement_new_ok() {
  auto mem = new S(1);
  return new (mem) S(2);
}

void destructor_in_loop_ok() {
  for (int i = 0; i < 10; i++) {
    S s(1);
  }
}

int FN_use_after_scope3_bad() {
  int* p;
  {
    int value = 3;
    p = &value;
  } // we do not know in the plugin that value is out of scope
  return *p;
}

struct C {
  C(int v) : f(v){};
  ~C();
  int f;
};

int use_after_scope4_bad() {
  C* pc;
  {
    C c(3);
    pc = &c;
  }
  return pc->f;
}

struct B {
  ~B();
};

struct A {
  ~A() { (void)*f; }
  const B* f;
};

void FN_destructor_order_bad() {
  A a;
  B b;
  a.f = &b;
}

struct A2 {
  ~A2() {}
  const B* f;
};

void destructor_order_empty_destructor_ok() {
  A2 a;
  B b;
  a.f = &b;
}

std::unique_ptr<A>* allocate_in_branch_ok(bool b) {
  std::unique_ptr<A> a1;
  std::unique_ptr<A> a2;
  std::unique_ptr<A>* a3 = &a1;

  if (b) {
    a2 = std::make_unique<A>(*a1);
    a3 = &a2;
  }

  // read a3
  const B* read = (*a3)->f;
}

std::string mk_string();

bool variable_init_ternary_ok(bool b) {
  // this can cause issues because of the way the frontend treatment of ternary
  // ?: interacts with the treatment of passing return values by reference as
  // parameters
  std::string newPath = b ? "" : mk_string();
}

void move_data(POD* from, POD* to);

struct Moveable {
  Moveable() = default;
  Moveable(const Moveable&) = delete; // not copyable

  // move constructor
  Moveable(Moveable&& that) noexcept { move_data(&that.data, &data); }

  Moveable& operator=(Moveable&& that) noexcept {
    this->~Moveable();
    ::new (this) Moveable(std::move(that));
    return *this;
  }

  ~Moveable() {}

  Moveable& operator=(const Moveable&) = delete;

  POD data;
};

void move_moveable_ok(Moveable& src) {
  Moveable x;
  x = std::move(src);
}

} // namespace use_after_destructor
<commit_msg>[pulse] fix temporaries test code<commit_after>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include <iostream>
#include <memory>
#include <string>

namespace use_after_destructor {

struct S {
  int* f;
  S(int i) {
    f = new int;
    *f = i;
  }

  // missing: operator= to copy the pointer. double delete can happen if
  // operator= is called

  ~S() { delete f; }

  void reinit(S s) {
    f = new int;
    *f = *(s.f);
  }
};

// destructor called at end of function, no issues
void normal_scope_destructor_ok() { S s(1); }

void nested_scope_destructor_ok() {
  { S s(1); }
}

int reinit_after_explicit_destructor_ok() {
  S s(1);
  s.~S();
  s.reinit(S(2));
  return *s.f;
}

int FN_reinit_after_explicit_destructor_bad() {
  S s(1);
  s.~S();
  s = S(2); // a temporary is created then operator= is called
  return *s.f;
}

int reinit_after_explicit_destructor2_bad() {
  S s(1);
  S s2(2);
  s.~S();
  s = s2; // operator=
  return *s.f;
  // [s2.f] is [s.f] so gets deleted twice
}

void placement_new_explicit_destructor_ok() {
  char buf[sizeof(S)];
  {
    S* s = new (buf) S(1);
    s->~S();
  }
  {
    // this use of [buf] shouldn't be flagged
    S* s = new (buf) S(2);
    s->~S();
  }
}

void double_destructor_bad() {
  S s(1);
  s.~S();
  // destructor will be called again after S goes out of scope, which is
  // undefined behavior
}

int use_after_destructor_bad() {
  S s(1);
  s.~S();
  int ret = *s.f;
  s = S{2};
  return ret;
}

// S::operator= doesn't copy resources correctly
void use_after_scope1_bad() {
  S s(1);
  {
    S tmp(2);
    s = tmp; // translated as operator=(s, tmp)
  } // destructor for tmp runs here
  // destructor for s here; second time the value held by s has been destructed
}

void FN_use_after_scope2_bad() {
  S s(1);
  {
    s = S(1);
  } // destructor runs here, but our frontend currently doesn't insert it
}

struct POD {
  int f;
};

// this code is ok since double-destructing POD struct is ok
void destruct_twice_ok() {
  POD p{1};
  {
    POD tmp{2};
    p = tmp;
  } // destructor for tmp
} // destructor for p runs here, but it's harmless

class Subclass : virtual POD {
  int* f;
  Subclass() { f = new int; }

  /** frontend code for this destructor will be:
   * ~Subclass:
   *  __infer_inner_destructor_~Subclass(this)
   *  __infer_inner_destructor_~POD(this)
   *
   * __infer_inner_destructor_~Subclass:
   *  delete f;
   *
   * We need to be careful not to warn that this has been double-destructed
   */
  ~Subclass() { delete f; }
};

void basic_placement_new_ok() {
  S* ptr = new S(1);
  S* tptr = new (ptr) S(1);
  tptr->~S();
  delete[] ptr;
}

int* destruct_pointer_contents_then_placement_new1_ok(S* s) {
  s->~S();
  new (s) S(1);
  return s->f;
}

int* destruct_pointer_contents_then_placement_new2_ok(S* s) {
  s->~S();
  new (&(s->f)) S(1);
  return s->f;
}

int* placement_new_aliasing1_bad() {
  S* s = new S(1);
  s->~S();
  auto alias = new (s) S(2);
  delete alias; // this deletes s too
  return s->f; // bad, accessing freed memory
}

int* placement_new_aliasing2_bad() {
  S* s = new S(1);
  s->~S();
  auto alias = new (s) S(2);
  delete s; // this deletes alias too
  return alias->f; // bad, accessing freed memory
}

int* placement_new_aliasing3_bad() {
  S* s = new S(1);
  s->~S();
  S* alias = s;
  auto alias_placement = new (s) S(2);
  delete s; // this deletes alias too
  return alias->f; // bad, accessing freed memory
}

void placement_new_non_var_ok() {
  struct M {
    S* s;
  } m;
  m.s = new S(1);
  m.s->~S();
  new (m.s) S(2);
  delete m.s;
}

void return_placement_new_ok() {
  auto mem = new S(1);
  return new (mem) S(2);
}

void destructor_in_loop_ok() {
  for (int i = 0; i < 10; i++) {
    S s(1);
  }
}

int FN_use_after_scope3_bad() {
  int* p;
  {
    int value = 3;
    p = &value;
  } // we do not know in the plugin that value is out of scope
  return *p;
}

struct C {
  C(int v) : f(v){};
  ~C();
  int f;
};

int use_after_scope4_bad() {
  C* pc;
  {
    C c(3);
    pc = &c;
  }
  return pc->f;
}

struct B {
  ~B();
};

struct A {
  ~A() { (void)*f; }
  const B* f;
};

void FN_destructor_order_bad() {
  A a;
  B b;
  a.f = &b;
}

struct A2 {
  ~A2() {}
  const B* f;
};

void destructor_order_empty_destructor_ok() {
  A2 a;
  B b;
  a.f = &b;
}

std::unique_ptr<A>* allocate_in_branch_ok(bool b) {
  std::unique_ptr<A> a1;
  std::unique_ptr<A> a2;
  std::unique_ptr<A>* a3 = &a1;

  if (b) {
    a2 = std::make_unique<A>(*a1);
    a3 = &a2;
  }

  // read a3
  const B* read = (*a3)->f;
}

std::string mk_string();

bool variable_init_ternary_ok(bool b) {
  // this can cause issues because of the way the frontend treatment of ternary
  // ?: interacts with the treatment of passing return values by reference as
  // parameters
  std::string newPath = b ? "" : mk_string();
}

void move_data(POD* from, POD* to);

struct Moveable {
  Moveable() = default;
  Moveable(const Moveable&) = delete; // not copyable

  // move constructor
  Moveable(Moveable&& that) noexcept { move_data(&that.data, &data); }

  Moveable& operator=(Moveable&& that) noexcept {
    this->~Moveable();
    ::new (this) Moveable(std::move(that));
    return *this;
  }

  ~Moveable() {}

  Moveable& operator=(const Moveable&) = delete;

  POD data;
};

void move_moveable_ok(Moveable& src) {
  Moveable x;
  x = std::move(src);
}

} // namespace use_after_destructor
<|endoftext|>


<commit_before>#pragma once

#include <algorithm>
#include <cassert>
#include <fstream>
#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>

namespace hip_impl {
inline const std::unordered_set<std::string>& amdgpu_targets() {  // The evolving list lives at:
    // https://www.llvm.org/docs/AMDGPUUsage.html#processors.
    static const std::unordered_set<std::string> r{"gfx701", "gfx801", "gfx802", "gfx803",
                                                   "gfx900", "gfx906", "gfx908"};

    return r;
}

inline const std::string& code_object_extension() {
    static const std::string r{".ffa"};

    return r;
}

inline const std::string& fat_binary_extension() {
    static const std::string r{".adipose"};

    return r;
}

inline bool file_exists(const std::string& path_to) {
    return static_cast<bool>(std::ifstream{path_to});
}

inline std::vector<std::string> tokenize_targets(
    const std::string&
        x) {  // TODO: move to regular expressions once we clarify the need to support
    //       ancient standard library implementations.
    if (x.empty()) return {};

    static constexpr const char valid_characters[] = "gfx0123456789,";

    if (x.find_first_not_of(valid_characters) != std::string::npos) {
        throw std::runtime_error{"Invalid target string: " + x};
    }

    std::vector<std::string> r;

    auto it = x.cbegin();
    do {
        auto it1 = std::find(it, x.cend(), ',');
        r.emplace_back(it, it1);

        if (it1 == x.cend()) break;

        it = ++it1;
    } while (true);

    return r;
}

inline void validate_targets(const std::vector<std::string>& x) {
    assert(!x.empty());

    for (auto&& t : x) {
        static const std::string digits{"0123456789"};
        static const std::string pre{"gfx"};

        if (t.find(pre) != 0 || t.find_first_not_of(digits, pre.size()) != std::string::npos) {
            throw std::runtime_error{"Invalid target: " + t};
        }

        if (amdgpu_targets().find(t) == amdgpu_targets().cend()) {
            std::cerr << "Warning: target " << t
                      << " has not been validated yet; it may be invalid." << std::endl;
        }
    }
}
}  // Namespace hip_impl.
<commit_msg>Correct parsing of target names and supported targets<commit_after>#pragma once

#include <algorithm>
#include <cassert>
#include <fstream>
#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>

namespace hip_impl {
inline const std::unordered_set<std::string>& amdgpu_targets() {  // The evolving list lives at:
    // https://www.llvm.org/docs/AMDGPUUsage.html#processors.
    static const std::unordered_set<std::string> r{
        "gfx700", "gfx701",  "gfx702",  "gfx703",  "gfx704",  "gfx705",
        "gfx801", "gfx802", "gfx803", "gfx805",  "gfx810",
        "gfx900",  "gfx902",  "gfx904",  "gfx906", "gfx908", "gfx909",
        "gfx1010", "gfx1011", "gfx1012", "gfx1030", "gfx1031", "gfx1032"};
    return r;
}

inline const std::string& code_object_extension() {
    static const std::string r{".ffa"};

    return r;
}

inline const std::string& fat_binary_extension() {
    static const std::string r{".adipose"};

    return r;
}

inline bool file_exists(const std::string& path_to) {
    return static_cast<bool>(std::ifstream{path_to});
}

inline std::vector<std::string> tokenize_targets(
    const std::string&
        x) {  // TODO: move to regular expressions once we clarify the need to support
    //       ancient standard library implementations.
    if (x.empty()) return {};

    static constexpr const char valid_characters[] = "0123456789abcdefghijklmnopqrstuvwxyz,";

    if (x.find_first_not_of(valid_characters) != std::string::npos) {
        throw std::runtime_error{"Invalid target string: " + x};
    }

    std::vector<std::string> r;

    auto it = x.cbegin();
    do {
        auto it1 = std::find(it, x.cend(), ',');
        r.emplace_back(it, it1);

        if (it1 == x.cend()) break;

        it = ++it1;
    } while (true);

    return r;
}

inline void validate_targets(const std::vector<std::string>& x) {
    assert(!x.empty());

    for (auto&& t : x) {
        static const std::string sufficies{"0123456789abcdefghijklmnopqrstuvwxyz"};
        static const std::string prefix{"gfx"};

        if (t.find(prefix) != 0 || t.find_first_not_of(sufficies, prefix.size()) != std::string::npos) {
            throw std::runtime_error{"Invalid target: " + t};
        }

        if (amdgpu_targets().find(t) == amdgpu_targets().cend()) {
            std::cerr << "Warning: target " << t
                      << " has not been validated yet; it may be invalid." << std::endl;
        }
    }
}
}  // Namespace hip_impl.
<|endoftext|>


<commit_before>#include "nanocv/tensor.h"
#include "nanocv/string.h"
#include "nanocv/tabulator.h"
#include "nanocv/measure.hpp"
#include "nanocv/math/conv2d.hpp"
#include "nanocv/math/corr2d.hpp"
#include "nanocv/math/conv3d.hpp"
#include "nanocv/math/random.hpp"
#include "nanocv/tensor/conv3d.hpp"
#include "nanocv/tensor/random.hpp"
#include <iostream>

using namespace ncv;

namespace
{
        template
        <
                typename top,
                typename ttensori,
                typename ttensork,
                typename ttensoro
        >
        size_t measure_output(const top& op,
                const ttensori& idata, const ttensork& kdata, ttensoro&& odata, const size_t trials = 16)
        {
                return ncv::measure_robustly_usec([&] ()
                {
                        math::conv3d_output(op, idata, kdata, odata);
                }, trials);
        }

        template
        <
                typename top,
                typename ttensori,
                typename ttensork,
                typename ttensoro
        >
        size_t measure_ginput(const top& op,
                ttensori&& idata, const ttensork& kdata, const ttensoro& odata, const size_t trials = 16)
        {
                return ncv::measure_robustly_usec([&] ()
                {
                        math::conv3d_ginput(op, idata, kdata, odata);
                }, trials);
        }

        template
        <
                typename top,
                typename ttensori,
                typename ttensork,
                typename ttensoro
        >
        size_t measure_gparam(const top& op,
                const ttensori& idata, ttensork&& kdata, const ttensoro& odata, const size_t trials = 16)
        {
                return ncv::measure_robustly_usec([&] ()
                {
                        math::conv3d_gparam(op, idata, kdata, odata);
                }, trials);
        }

        void test_config(int isize, int idims, int ksize, int odims,
                tabulator_t::row_t& row_output,
                tabulator_t::row_t& row_ginput,
                tabulator_t::row_t& row_gparam)
        {
                const int osize = isize - ksize + 1;
                const int kdims = odims * idims;

                random_t<scalar_t> rng(-1.0 / isize, 1.0 / isize);

                tensor_t idata(idims, isize, isize);
                tensor_t kdata(kdims, ksize, ksize);
                tensor_t odata(odims, osize, osize);

                tensor::set_random(idata, rng);
                tensor::set_random(kdata, rng);
                tensor::set_random(odata, rng);

                tensor_t idata_ret = idata;
                tensor_t kdata_ret = kdata;
                tensor_t odata_ret = odata;

                tensor::conv3d_t<tensor_t> conv3d;
                conv3d.reset(kdata, idims, odims);

                const size_t trials = 16;

                // output
                row_output << measure_output(math::conv2d_eig_t(), idata, kdata, odata_ret, trials);
                row_output << measure_output(math::conv2d_cpp_t(), idata, kdata, odata_ret, trials);
                row_output << measure_output(math::conv2d_dot_t(), idata, kdata, odata_ret, trials);
                row_output << measure_output(math::conv2d_mad_t(), idata, kdata, odata_ret, trials);
                row_output << measure_output(math::conv2d_dyn_t(), idata, kdata, odata_ret, trials);
                row_output << ncv::measure_robustly_usec([&] () { conv3d.output(idata, odata_ret); }, trials);

                // gradient wrt input
                row_ginput << measure_ginput(ncv::math::corr2d_egb_t(), idata_ret, kdata, odata, trials);
                row_ginput << measure_ginput(ncv::math::corr2d_egr_t(), idata_ret, kdata, odata, trials);
                row_ginput << measure_ginput(ncv::math::corr2d_cpp_t(), idata_ret, kdata, odata, trials);
                row_ginput << measure_ginput(ncv::math::corr2d_mdk_t(), idata_ret, kdata, odata, trials);
                row_ginput << measure_ginput(ncv::math::corr2d_mdo_t(), idata_ret, kdata, odata, trials);
                row_ginput << measure_ginput(ncv::math::corr2d_dyn_t(), idata_ret, kdata, odata, trials);
                row_ginput << ncv::measure_robustly_usec([&] () { conv3d.ginput(idata_ret, odata); }, trials);

                // gradient wrt parameters
                row_gparam << measure_gparam(math::conv2d_eig_t(), idata, kdata_ret, odata, trials);
                row_gparam << measure_gparam(math::conv2d_cpp_t(), idata, kdata_ret, odata, trials);
                row_gparam << measure_gparam(math::conv2d_dot_t(), idata, kdata_ret, odata, trials);
                row_gparam << measure_gparam(math::conv2d_mad_t(), idata, kdata_ret, odata, trials);
                row_gparam << measure_gparam(math::conv2d_dyn_t(), idata, kdata_ret, odata, trials);
                row_gparam << ncv::measure_robustly_usec([&] () { conv3d.gparam(idata, kdata_ret, odata); }, trials);
        }
}

int main(int, char* [])
{
        const int min_isize = 4;
        const int max_isize = 32;

        const int min_ksize = 3;
        const int max_ksize = 9;

        const int idims = 16;
        const int odims = 32;

        tabulator_t table_output("size\\output [us]");
        table_output.header()
                << "2D (eig)"
                << "2D (cpp)"
                << "2D (dot)"
                << "2D (mad)"
                << "2D (dyn)"
                << "3D (lin)";

        tabulator_t table_ginput("size\\ginput [us]");
        table_ginput.header()
                << "2D (egb)"
                << "2D (egr)"
                << "2D (cpp)"
                << "2D (mkd)"
                << "2D (mko)"
                << "2D (dyn)"
                << "3D (lin)";

        tabulator_t table_gparam("size\\gparam [us]");
        table_gparam.header()
                << "2D (eig)"
                << "2D (cpp)"
                << "2D (dot)"
                << "2D (mad)"
                << "2D (dyn)"
                << "3D (lin)";

        for (int isize = min_isize; isize <= max_isize; isize += 4)
        {
                table_output.clear();
                table_ginput.clear();
                table_gparam.clear();

                for (int ksize = min_ksize; ksize <= std::min(isize, max_ksize); ksize += 2)
                {
                        const int osize = isize - ksize + 1;

                        const string_t header =
                                "(" +
                                text::to_string(idims) + "x" +
                                text::to_string(isize) + "x" +
                                text::to_string(isize) + " @ " +
                                text::to_string(ksize) + "x" +
                                text::to_string(ksize) + " -> " +
                                text::to_string(odims) + "x" +
                                text::to_string(osize) + "x" +
                                text::to_string(osize) +
                                ")";

                        test_config(isize, idims, ksize, odims,
                                    table_output.append(header),
                                    table_ginput.append(header),
                                    table_gparam.append(header));
                }

                table_output.print(std::cout);
                table_ginput.print(std::cout);
                table_gparam.print(std::cout);

                std::cout << std::endl;
        }

	return EXIT_SUCCESS;
}

<commit_msg>also benchmark 3D convolutions using floats<commit_after>#include "nanocv/tensor.h"
#include "nanocv/string.h"
#include "nanocv/tabulator.h"
#include "nanocv/measure.hpp"
#include "nanocv/math/conv2d.hpp"
#include "nanocv/math/corr2d.hpp"
#include "nanocv/math/conv3d.hpp"
#include "nanocv/math/random.hpp"
#include "nanocv/tensor/conv3d.hpp"
#include "nanocv/tensor/random.hpp"
#include <iostream>

using namespace ncv;

namespace
{
        template
        <
                typename top,
                typename ttensori,
                typename ttensork,
                typename ttensoro
        >
        size_t measure_output(const top& op,
                const ttensori& idata, const ttensork& kdata, ttensoro&& odata, const size_t trials = 16)
        {
                return ncv::measure_robustly_usec([&] ()
                {
                        math::conv3d_output(op, idata, kdata, odata);
                }, trials);
        }

        template
        <
                typename top,
                typename ttensori,
                typename ttensork,
                typename ttensoro
        >
        size_t measure_ginput(const top& op,
                ttensori&& idata, const ttensork& kdata, const ttensoro& odata, const size_t trials = 16)
        {
                return ncv::measure_robustly_usec([&] ()
                {
                        math::conv3d_ginput(op, idata, kdata, odata);
                }, trials);
        }

        template
        <
                typename top,
                typename ttensori,
                typename ttensork,
                typename ttensoro
        >
        size_t measure_gparam(const top& op,
                const ttensori& idata, ttensork&& kdata, const ttensoro& odata, const size_t trials = 16)
        {
                return ncv::measure_robustly_usec([&] ()
                {
                        math::conv3d_gparam(op, idata, kdata, odata);
                }, trials);
        }

        void test_config(int isize, int idims, int ksize, int odims,
                tabulator_t::row_t& row_output,
                tabulator_t::row_t& row_ginput,
                tabulator_t::row_t& row_gparam)
        {
                const int osize = isize - ksize + 1;
                const int kdims = odims * idims;

                random_t<scalar_t> rng(-1.0 / isize, 1.0 / isize);

                tensor_t idata(idims, isize, isize);
                tensor_t kdata(kdims, ksize, ksize);
                tensor_t odata(odims, osize, osize);

                ltensor_t lidata(idims, isize, isize);
                ltensor_t lkdata(kdims, ksize, ksize);
                ltensor_t lodata(odims, osize, osize);

                tensor::set_random(idata, rng);
                tensor::set_random(kdata, rng);
                tensor::set_random(odata, rng);

                tensor::set_random(lidata, rng);
                tensor::set_random(lkdata, rng);
                tensor::set_random(lodata, rng);

                tensor_t idata_ret = idata;
                tensor_t kdata_ret = kdata;
                tensor_t odata_ret = odata;

                ltensor_t lidata_ret = lidata;
                ltensor_t lkdata_ret = lkdata;
                ltensor_t lodata_ret = lodata;

                tensor::conv3d_t<tensor_t> conv3d;
                conv3d.reset(kdata, idims, odims);

                tensor::conv3d_t<ltensor_t> lconv3d;
                lconv3d.reset(lkdata, idims, odims);

                const size_t trials = 16;

                // output
                row_output << measure_output(math::conv2d_eig_t(), idata, kdata, odata_ret, trials);
                row_output << measure_output(math::conv2d_cpp_t(), idata, kdata, odata_ret, trials);
                row_output << measure_output(math::conv2d_dot_t(), idata, kdata, odata_ret, trials);
                row_output << measure_output(math::conv2d_mad_t(), idata, kdata, odata_ret, trials);
                row_output << measure_output(math::conv2d_dyn_t(), idata, kdata, odata_ret, trials);
                row_output << ncv::measure_robustly_usec([&] () { conv3d.output(idata, odata_ret); }, trials);
                row_output << ncv::measure_robustly_usec([&] () { lconv3d.output(lidata, lodata_ret); }, trials);

                // gradient wrt input
                row_ginput << measure_ginput(ncv::math::corr2d_egb_t(), idata_ret, kdata, odata, trials);
                row_ginput << measure_ginput(ncv::math::corr2d_egr_t(), idata_ret, kdata, odata, trials);
                row_ginput << measure_ginput(ncv::math::corr2d_cpp_t(), idata_ret, kdata, odata, trials);
                row_ginput << measure_ginput(ncv::math::corr2d_mdk_t(), idata_ret, kdata, odata, trials);
                row_ginput << measure_ginput(ncv::math::corr2d_mdo_t(), idata_ret, kdata, odata, trials);
                row_ginput << measure_ginput(ncv::math::corr2d_dyn_t(), idata_ret, kdata, odata, trials);
                row_ginput << ncv::measure_robustly_usec([&] () { conv3d.ginput(idata_ret, odata); }, trials);
                row_ginput << ncv::measure_robustly_usec([&] () { lconv3d.ginput(lidata_ret, lodata); }, trials);

                // gradient wrt parameters
                row_gparam << measure_gparam(math::conv2d_eig_t(), idata, kdata_ret, odata, trials);
                row_gparam << measure_gparam(math::conv2d_cpp_t(), idata, kdata_ret, odata, trials);
                row_gparam << measure_gparam(math::conv2d_dot_t(), idata, kdata_ret, odata, trials);
                row_gparam << measure_gparam(math::conv2d_mad_t(), idata, kdata_ret, odata, trials);
                row_gparam << measure_gparam(math::conv2d_dyn_t(), idata, kdata_ret, odata, trials);
                row_gparam << ncv::measure_robustly_usec([&] () { conv3d.gparam(idata, kdata_ret, odata); }, trials);
                row_gparam << ncv::measure_robustly_usec([&] () { lconv3d.gparam(lidata, lkdata_ret, lodata); }, trials);
        }
}

int main(int, char* [])
{
        const int min_isize = 4;
        const int max_isize = 32;

        const int min_ksize = 3;
        const int max_ksize = 9;

        const int idims = 16;
        const int odims = 32;

        tabulator_t table_output("size\\output [us]");
        table_output.header()
                << "2D (eig)"
                << "2D (cpp)"
                << "2D (dot)"
                << "2D (mad)"
                << "2D (dyn)"
                << "3D (lin)"
                << "3D (l-lin)";

        tabulator_t table_ginput("size\\ginput [us]");
        table_ginput.header()
                << "2D (egb)"
                << "2D (egr)"
                << "2D (cpp)"
                << "2D (mkd)"
                << "2D (mko)"
                << "2D (dyn)"
                << "3D (lin)"
                << "3D (l-lin)";

        tabulator_t table_gparam("size\\gparam [us]");
        table_gparam.header()
                << "2D (eig)"
                << "2D (cpp)"
                << "2D (dot)"
                << "2D (mad)"
                << "2D (dyn)"
                << "3D (lin)"
                << "3D (l-lin)";

        for (int isize = min_isize; isize <= max_isize; isize += 4)
        {
                table_output.clear();
                table_ginput.clear();
                table_gparam.clear();

                for (int ksize = min_ksize; ksize <= std::min(isize, max_ksize); ksize += 2)
                {
                        const int osize = isize - ksize + 1;

                        const string_t header =
                                "(" +
                                text::to_string(idims) + "x" +
                                text::to_string(isize) + "x" +
                                text::to_string(isize) + " @ " +
                                text::to_string(ksize) + "x" +
                                text::to_string(ksize) + " -> " +
                                text::to_string(odims) + "x" +
                                text::to_string(osize) + "x" +
                                text::to_string(osize) +
                                ")";

                        test_config(isize, idims, ksize, odims,
                                    table_output.append(header),
                                    table_ginput.append(header),
                                    table_gparam.append(header));
                }

                table_output.print(std::cout);
                table_ginput.print(std::cout);
                table_gparam.print(std::cout);

                std::cout << std::endl;
        }

	return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/*
	This file is part of the E_MinSG library.
	Copyright (C) 2007-2013 Benjamin Eikel <benjamin@eikel.org>
	Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de>
	Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "ELibMinSG.h"

#include "Ext/ELibMinSGExt.h"

// --

#include "Core/Behaviours/E_AbstractBehaviour.h"
#include "Core/Behaviours/E_Behavior.h"
#include "Core/Behaviours/E_BehaviorStatus.h"
#include "Core/Behaviours/E_BehaviourManager.h"
#include "Core/Behaviours/E_ScriptedBehavior.h"
#include "Core/E_FrameContext.h"
#include "Core/E_RenderParam.h"
#include "Core/E_Statistics.h"
#include "Core/Nodes/E_Node.h"
#include "Core/Nodes/E_GroupNode.h"
#include "Core/Nodes/E_LightNode.h"
#include "Core/Nodes/E_ListNode.h"
#include "Core/Nodes/E_GeometryNode.h"
#include "Core/Nodes/E_AbstractCameraNode.h"
#include "Core/Nodes/E_CameraNode.h"
#include "Core/Nodes/E_CameraNodeOrtho.h"
#include "Core/States/E_AlphaTestState.h"
#include "Core/States/E_BlendingState.h"
#include "Core/States/E_CullFaceState.h"
#include "Core/States/E_GroupState.h"
#include "Core/States/E_LightingState.h"
#include "Core/States/E_MaterialState.h"
#include "Core/States/E_NodeRendererState.h"
#include "Core/States/E_PolygonModeState.h"
#include "Core/States/E_ShaderState.h"
#include "Core/States/E_ShaderUniformState.h"
#include "Core/States/E_State.h"
#include "Core/States/E_TextureState.h"
#include "Core/States/E_TransparencyRenderer.h"

#include "SceneManagement/E_ImportContext.h"
#include "SceneManagement/E_SceneManager.h"
#include "Helper/E_GraphVizOutput.h"
#include "Helper/E_StdNodeVisitors.h"

#include <EScript/Basics.h>
#include <EScript/StdObjects.h>

#include <E_Geometry/E_Matrix4x4.h>

// --
#include <MinSG/MinSG.h>
#include <MinSG/Helper/Helper.h>

#include <Rendering/Serialization/Serialization.h>
#include <Rendering/Texture/TextureUtils.h>
#include <Rendering/Texture/Texture.h>
#include <Rendering/MeshUtils/MeshUtils.h>

#include <E_Rendering/Texture/E_Texture.h>
#include <E_Rendering/Mesh/E_Mesh.h>
#include <E_Rendering/E_RenderingContext.h>

#include <E_Geometry/E_Box.h>

#include <E_Util/IO/E_FileLocator.h>
#include <Util/IO/FileName.h>
#include <Util/Macros.h>

#include <map>

namespace E_MinSG {

//! init classes and Members
void init(EScript::Namespace * globals) {

	using namespace EScript;

	Namespace * lib=new Namespace();
	declareConstant(globals,"MinSG",lib);

	// ----------
	// ---- Core
	E_RenderParam::init(*lib);
	E_Node::init(*lib);
	E_GroupNode::init(*lib);
	E_ListNode::init(*lib);
	E_GeometryNode::init(*lib);
	E_FrameContext::init(*lib);
	E_Behavior::init(*lib);
	E_AbstractBehaviour::init(*lib);
	E_AbstractCameraNode::init(*lib);
	E_BehaviourManager::init(*lib);
	E_BehaviorStatus::init(*lib);
	E_CameraNode::init(*lib);
	E_CameraNodeOrtho::init(*lib);
	E_State::init(*lib);
	E_LightingState::init(*lib);
	E_LightNode::init(*lib);
	E_ShaderState::init(*lib);
	E_ShaderUniformState::init(*lib);
	E_TextureState::init(*lib);
	E_BlendingState::init(*lib);
	E_CullFaceState::init(*lib);
	E_GroupState::init(*lib);
	E_AlphaTestState::init(*lib);
	E_PolygonModeState::init(*lib);
	E_MaterialState::init(*lib);
	E_NodeRendererState::init(*lib);
	E_ScriptedBehavior::init(*lib);
	E_Statistics::init(*lib);
	E_TransparencyRenderer::init(*lib);
	// ----------
	// ---- SceneManagement
	E_SceneManager::init(*lib);
	E_ImportContext::init(*lib);

	// ----------
	// ---- Helper

	//! [ESF] void MinSG.changeParentKeepTransformation(Node child, GroupNode newParent)
	ES_FUNCTION(lib,"changeParentKeepTransformation",2,2, {
		auto ep = parameter[1].toType<E_GroupNode>();
		MinSG::changeParentKeepTransformation(parameter[0].to<MinSG::Node*>(rt), ep ? **ep : nullptr);
		return nullptr;
	})

	//! [ESF] Box MinSG.combineNodesWorldBBs(Array nodes)
	ES_FUNCTION(lib,"combineNodesWorldBBs",1,1, {
		std::vector<MinSG::Node*> nodes;
		for(const auto & eNode : *assertType<EScript::Array>(rt,parameter[0]))
			nodes.push_back( **EScript::assertType<E_Node>(rt,eNode));
		return EScript::create( combineNodesWorldBBs(nodes) );
	})

	//! [ESF] void MinSG.destroy(Node)
	ES_FUNCTION(lib,"destroy",1,1, {
		MinSG::Node * n=parameter[0].to<MinSG::Node*>(rt);
		MinSG::destroy(n);
		return nullptr;
	})

	//! [ESF] void MinSG.initShaderState(ShaderState, Array vsFiles, Array gsFiles, Array fsFiles, [Shader::flag_t _usage], _Util::FileLocator )
	ES_FUNCTION(lib,"initShaderState",4,6, {
		MinSG::ShaderState * s=**EScript::assertType<E_ShaderState>(rt,parameter[0]);

		EScript::Collection * c;

		c = EScript::assertType<EScript::Collection>(rt,parameter[1]);
		std::vector<std::string> vsFiles;
		for(ERef<Iterator> iRef=c->getIterator(); !iRef->end() ;iRef->next()){
			ObjRef value=iRef->value();
			vsFiles.push_back(value.toString());
		}
		c = EScript::assertType<EScript::Collection>(rt,parameter[2]);
		std::vector<std::string> gsFiles;
		for(ERef<Iterator> iRef=c->getIterator(); !iRef->end() ;iRef->next()){
			ObjRef value=iRef->value();
			gsFiles.push_back(value.toString());
		}
		c = EScript::assertType<EScript::Collection>(rt,parameter[3]);
		std::vector<std::string> fsFiles;
		for(ERef<Iterator> iRef=c->getIterator(); !iRef->end() ;iRef->next()){
			ObjRef value=iRef->value();
			fsFiles.push_back(value.toString());
		}

		;
		if(parameter.count()>5){
			const Util::FileLocator searchPaths = parameter[5].to<const Util::FileLocator&>(rt);
			MinSG::initShaderState(s,vsFiles,gsFiles,fsFiles, parameter[4].toUInt(Rendering::Shader::USE_UNIFORMS | Rendering::Shader::USE_GL),searchPaths);
		}else{
			const Util::FileLocator searchPaths;
			MinSG::initShaderState(s,vsFiles,gsFiles,fsFiles, parameter[4].toUInt(Rendering::Shader::USE_UNIFORMS | Rendering::Shader::USE_GL),searchPaths);
		}

		return nullptr;
	})

	//! [ESF] MinSG.Node MinSG.loadModel(filename[,flags[,TransMat]])
	ES_FUNCTION(lib,"loadModel",1,3, {
		E_Geometry::E_Matrix4x4 *em=parameter[2].toType<E_Geometry::E_Matrix4x4>();
		Util::FileName file(parameter[0].toString());
		MinSG::Node * n=MinSG::loadModel(
			file,
			parameter[1].toUInt(0),
			em!=nullptr?&em->ref():nullptr
			);
		return EScript::create(n);
	})

	// ---------------------------------------------------------)

	// ----------
	// ---- Constants:
	declareConstant(lib,"VERSION",String::create(MINSG_VERSION));

	declareConstant(lib,"BOUNDING_BOXES",Number::create(MinSG::BOUNDING_BOXES));
	declareConstant(lib,"NO_GEOMETRY",Number::create(MinSG::NO_GEOMETRY));
	declareConstant(lib,"FRUSTUM_CULLING",Number::create(MinSG::FRUSTUM_CULLING));
	declareConstant(lib,"SHOW_META_OBJECTS",Number::create(MinSG::SHOW_META_OBJECTS));
	declareConstant(lib,"SHOW_COORD_SYSTEM",Number::create(MinSG::SHOW_COORD_SYSTEM));
	declareConstant(lib,"USE_WORLD_MATRIX",Number::create(MinSG::USE_WORLD_MATRIX));
	declareConstant(lib,"NO_STATES",Number::create(MinSG::NO_STATES));
	declareConstant(lib,"SKIP_RENDERER",Number::create(MinSG::SKIP_RENDERER));

	declareConstant(lib,"MESH_AUTO_CENTER",Number::create(MinSG::MESH_AUTO_CENTER));
	declareConstant(lib,"MESH_AUTO_CENTER_BOTTOM",Number::create(MinSG::MESH_AUTO_CENTER_BOTTOM));
	declareConstant(lib,"MESH_AUTO_SCALE",Number::create(MinSG::MESH_AUTO_SCALE));

	// Helper
	init_stdNodeVisitors(lib);
	GraphVizOutput::init(lib);

	// init extensions
	init_ext(globals,lib);
}

}
<commit_msg>Compile fix for Clang: Call constructor<commit_after>/*
	This file is part of the E_MinSG library.
	Copyright (C) 2007-2013 Benjamin Eikel <benjamin@eikel.org>
	Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de>
	Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "ELibMinSG.h"

#include "Ext/ELibMinSGExt.h"

// --

#include "Core/Behaviours/E_AbstractBehaviour.h"
#include "Core/Behaviours/E_Behavior.h"
#include "Core/Behaviours/E_BehaviorStatus.h"
#include "Core/Behaviours/E_BehaviourManager.h"
#include "Core/Behaviours/E_ScriptedBehavior.h"
#include "Core/E_FrameContext.h"
#include "Core/E_RenderParam.h"
#include "Core/E_Statistics.h"
#include "Core/Nodes/E_Node.h"
#include "Core/Nodes/E_GroupNode.h"
#include "Core/Nodes/E_LightNode.h"
#include "Core/Nodes/E_ListNode.h"
#include "Core/Nodes/E_GeometryNode.h"
#include "Core/Nodes/E_AbstractCameraNode.h"
#include "Core/Nodes/E_CameraNode.h"
#include "Core/Nodes/E_CameraNodeOrtho.h"
#include "Core/States/E_AlphaTestState.h"
#include "Core/States/E_BlendingState.h"
#include "Core/States/E_CullFaceState.h"
#include "Core/States/E_GroupState.h"
#include "Core/States/E_LightingState.h"
#include "Core/States/E_MaterialState.h"
#include "Core/States/E_NodeRendererState.h"
#include "Core/States/E_PolygonModeState.h"
#include "Core/States/E_ShaderState.h"
#include "Core/States/E_ShaderUniformState.h"
#include "Core/States/E_State.h"
#include "Core/States/E_TextureState.h"
#include "Core/States/E_TransparencyRenderer.h"

#include "SceneManagement/E_ImportContext.h"
#include "SceneManagement/E_SceneManager.h"
#include "Helper/E_GraphVizOutput.h"
#include "Helper/E_StdNodeVisitors.h"

#include <EScript/Basics.h>
#include <EScript/StdObjects.h>

#include <E_Geometry/E_Matrix4x4.h>

// --
#include <MinSG/MinSG.h>
#include <MinSG/Helper/Helper.h>

#include <Rendering/Serialization/Serialization.h>
#include <Rendering/Texture/TextureUtils.h>
#include <Rendering/Texture/Texture.h>
#include <Rendering/MeshUtils/MeshUtils.h>

#include <E_Rendering/Texture/E_Texture.h>
#include <E_Rendering/Mesh/E_Mesh.h>
#include <E_Rendering/E_RenderingContext.h>

#include <E_Geometry/E_Box.h>

#include <E_Util/IO/E_FileLocator.h>
#include <Util/IO/FileName.h>
#include <Util/Macros.h>

#include <map>

namespace E_MinSG {

//! init classes and Members
void init(EScript::Namespace * globals) {

	using namespace EScript;

	Namespace * lib=new Namespace();
	declareConstant(globals,"MinSG",lib);

	// ----------
	// ---- Core
	E_RenderParam::init(*lib);
	E_Node::init(*lib);
	E_GroupNode::init(*lib);
	E_ListNode::init(*lib);
	E_GeometryNode::init(*lib);
	E_FrameContext::init(*lib);
	E_Behavior::init(*lib);
	E_AbstractBehaviour::init(*lib);
	E_AbstractCameraNode::init(*lib);
	E_BehaviourManager::init(*lib);
	E_BehaviorStatus::init(*lib);
	E_CameraNode::init(*lib);
	E_CameraNodeOrtho::init(*lib);
	E_State::init(*lib);
	E_LightingState::init(*lib);
	E_LightNode::init(*lib);
	E_ShaderState::init(*lib);
	E_ShaderUniformState::init(*lib);
	E_TextureState::init(*lib);
	E_BlendingState::init(*lib);
	E_CullFaceState::init(*lib);
	E_GroupState::init(*lib);
	E_AlphaTestState::init(*lib);
	E_PolygonModeState::init(*lib);
	E_MaterialState::init(*lib);
	E_NodeRendererState::init(*lib);
	E_ScriptedBehavior::init(*lib);
	E_Statistics::init(*lib);
	E_TransparencyRenderer::init(*lib);
	// ----------
	// ---- SceneManagement
	E_SceneManager::init(*lib);
	E_ImportContext::init(*lib);

	// ----------
	// ---- Helper

	//! [ESF] void MinSG.changeParentKeepTransformation(Node child, GroupNode newParent)
	ES_FUNCTION(lib,"changeParentKeepTransformation",2,2, {
		auto ep = parameter[1].toType<E_GroupNode>();
		MinSG::changeParentKeepTransformation(parameter[0].to<MinSG::Node*>(rt), ep ? **ep : nullptr);
		return nullptr;
	})

	//! [ESF] Box MinSG.combineNodesWorldBBs(Array nodes)
	ES_FUNCTION(lib,"combineNodesWorldBBs",1,1, {
		std::vector<MinSG::Node*> nodes;
		for(const auto & eNode : *assertType<EScript::Array>(rt,parameter[0]))
			nodes.push_back( **EScript::assertType<E_Node>(rt,eNode));
		return EScript::create( combineNodesWorldBBs(nodes) );
	})

	//! [ESF] void MinSG.destroy(Node)
	ES_FUNCTION(lib,"destroy",1,1, {
		MinSG::Node * n=parameter[0].to<MinSG::Node*>(rt);
		MinSG::destroy(n);
		return nullptr;
	})

	//! [ESF] void MinSG.initShaderState(ShaderState, Array vsFiles, Array gsFiles, Array fsFiles, [Shader::flag_t _usage], _Util::FileLocator )
	ES_FUNCTION(lib,"initShaderState",4,6, {
		MinSG::ShaderState * s=**EScript::assertType<E_ShaderState>(rt,parameter[0]);

		EScript::Collection * c;

		c = EScript::assertType<EScript::Collection>(rt,parameter[1]);
		std::vector<std::string> vsFiles;
		for(ERef<Iterator> iRef=c->getIterator(); !iRef->end() ;iRef->next()){
			ObjRef value=iRef->value();
			vsFiles.push_back(value.toString());
		}
		c = EScript::assertType<EScript::Collection>(rt,parameter[2]);
		std::vector<std::string> gsFiles;
		for(ERef<Iterator> iRef=c->getIterator(); !iRef->end() ;iRef->next()){
			ObjRef value=iRef->value();
			gsFiles.push_back(value.toString());
		}
		c = EScript::assertType<EScript::Collection>(rt,parameter[3]);
		std::vector<std::string> fsFiles;
		for(ERef<Iterator> iRef=c->getIterator(); !iRef->end() ;iRef->next()){
			ObjRef value=iRef->value();
			fsFiles.push_back(value.toString());
		}

		;
		if(parameter.count()>5){
			const Util::FileLocator searchPaths = parameter[5].to<const Util::FileLocator&>(rt);
			MinSG::initShaderState(s,vsFiles,gsFiles,fsFiles, parameter[4].toUInt(Rendering::Shader::USE_UNIFORMS | Rendering::Shader::USE_GL),searchPaths);
		}else{
			MinSG::initShaderState(s,vsFiles,gsFiles,fsFiles, parameter[4].toUInt(Rendering::Shader::USE_UNIFORMS | Rendering::Shader::USE_GL), Util::FileLocator());
		}

		return nullptr;
	})

	//! [ESF] MinSG.Node MinSG.loadModel(filename[,flags[,TransMat]])
	ES_FUNCTION(lib,"loadModel",1,3, {
		E_Geometry::E_Matrix4x4 *em=parameter[2].toType<E_Geometry::E_Matrix4x4>();
		Util::FileName file(parameter[0].toString());
		MinSG::Node * n=MinSG::loadModel(
			file,
			parameter[1].toUInt(0),
			em!=nullptr?&em->ref():nullptr
			);
		return EScript::create(n);
	})

	// ---------------------------------------------------------)

	// ----------
	// ---- Constants:
	declareConstant(lib,"VERSION",String::create(MINSG_VERSION));

	declareConstant(lib,"BOUNDING_BOXES",Number::create(MinSG::BOUNDING_BOXES));
	declareConstant(lib,"NO_GEOMETRY",Number::create(MinSG::NO_GEOMETRY));
	declareConstant(lib,"FRUSTUM_CULLING",Number::create(MinSG::FRUSTUM_CULLING));
	declareConstant(lib,"SHOW_META_OBJECTS",Number::create(MinSG::SHOW_META_OBJECTS));
	declareConstant(lib,"SHOW_COORD_SYSTEM",Number::create(MinSG::SHOW_COORD_SYSTEM));
	declareConstant(lib,"USE_WORLD_MATRIX",Number::create(MinSG::USE_WORLD_MATRIX));
	declareConstant(lib,"NO_STATES",Number::create(MinSG::NO_STATES));
	declareConstant(lib,"SKIP_RENDERER",Number::create(MinSG::SKIP_RENDERER));

	declareConstant(lib,"MESH_AUTO_CENTER",Number::create(MinSG::MESH_AUTO_CENTER));
	declareConstant(lib,"MESH_AUTO_CENTER_BOTTOM",Number::create(MinSG::MESH_AUTO_CENTER_BOTTOM));
	declareConstant(lib,"MESH_AUTO_SCALE",Number::create(MinSG::MESH_AUTO_SCALE));

	// Helper
	init_stdNodeVisitors(lib);
	GraphVizOutput::init(lib);

	// init extensions
	init_ext(globals,lib);
}

}
<|endoftext|>