<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dbmetadata.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2006-07-26 07:21:25 $
 *
 *  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 CONNECTIVITY_INC_CONNECTIVITY_DBMETADATA_HXX
#include <connectivity/dbmetadata.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif

/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
/** === end UNO includes === **/

#ifndef TOOLS_DIAGNOSE_EX_H
#include <tools/diagnose_ex.h>
#endif

//........................................................................
namespace dbtools
{
//........................................................................

    /** === begin UNO using === **/
    using ::com::sun::star::uno::Reference;
    using ::com::sun::star::sdbc::XConnection;
    using ::com::sun::star::sdbc::XConnection;
    using ::com::sun::star::sdbc::XDatabaseMetaData;
    using ::com::sun::star::lang::IllegalArgumentException;
    using ::com::sun::star::uno::Exception;
    using ::com::sun::star::uno::Any;
    using ::com::sun::star::container::XChild;
    using ::com::sun::star::uno::UNO_QUERY_THROW;
    using ::com::sun::star::beans::XPropertySet;
    using ::com::sun::star::uno::Sequence;
    using ::com::sun::star::beans::PropertyValue;
    /** === end UNO using === **/

    //====================================================================
    //= DatabaseMetaData_Impl
    //====================================================================
    struct DatabaseMetaData_Impl
    {
        Reference< XConnection >        xConnection;
        Reference< XDatabaseMetaData >  xConnectionMetaData;
    };

    //--------------------------------------------------------------------
    namespace
    {
        static void lcl_construct( DatabaseMetaData_Impl& _metaDataImpl, const Reference< XConnection >& _connection )
        {
            _metaDataImpl.xConnection = _connection;
            if ( !_metaDataImpl.xConnection.is() )
                return;

            _metaDataImpl.xConnectionMetaData = _connection->getMetaData();
            if ( !_metaDataImpl.xConnectionMetaData.is() )
                throw IllegalArgumentException();
        }

        static void lcl_checkConnected( DatabaseMetaData_Impl& _metaDataImpl )
        {
            if ( !_metaDataImpl.xConnection.is() )
                throwSQLException( "not connected", SQL_CONNECTION_DOES_NOT_EXIST, NULL );
        }

        static bool lcl_getDataSourceSetting( const sal_Char* _asciiName, const DatabaseMetaData_Impl& _metaData, Any& _out_setting )
        {
            try
            {
                Reference< XChild > connectionAsChild( _metaData.xConnection, UNO_QUERY_THROW );
                Reference< XPropertySet > dataSource( connectionAsChild->getParent(), UNO_QUERY_THROW );

                Sequence< PropertyValue > dataSourceSettings;
                OSL_VERIFY( dataSource->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Info" ) ) ) >>= dataSourceSettings );

                const PropertyValue* setting( dataSourceSettings.getConstArray() );
                const PropertyValue* settingEnd( setting + dataSourceSettings.getLength() );
                for ( ; setting != settingEnd; ++setting )
                {
                    if ( setting->Name.equalsAscii( _asciiName ) )
                    {
                        _out_setting = setting->Value;
                        return true;
                    }
                }
            }
            catch( const Exception& )
            {
                DBG_UNHANDLED_EXCEPTION();
            }
            return false;
        }
    }

    //====================================================================
    //= DatabaseMetaData
    //====================================================================
    //--------------------------------------------------------------------
    DatabaseMetaData::DatabaseMetaData()
        :m_pImpl( new DatabaseMetaData_Impl )
    {
    }

    //--------------------------------------------------------------------
    DatabaseMetaData::DatabaseMetaData( const Reference< XConnection >& _connection )
        :m_pImpl( new DatabaseMetaData_Impl )
    {
        lcl_construct( *m_pImpl, _connection );
    }

    //--------------------------------------------------------------------
    DatabaseMetaData::DatabaseMetaData( const DatabaseMetaData& _copyFrom )
        :m_pImpl( new DatabaseMetaData_Impl( *_copyFrom.m_pImpl ) )
    {
    }

    //--------------------------------------------------------------------
    DatabaseMetaData& DatabaseMetaData::operator=( const DatabaseMetaData& _copyFrom )
    {
        if ( this == &_copyFrom )
            return *this;

        m_pImpl.reset( new DatabaseMetaData_Impl( *_copyFrom.m_pImpl ) );
        return *this;
    }

    //--------------------------------------------------------------------
    DatabaseMetaData::~DatabaseMetaData()
    {
    }

    //--------------------------------------------------------------------
    bool DatabaseMetaData::isConnected() const
    {
        return m_pImpl->xConnection.is();
    }

    //--------------------------------------------------------------------
    bool SAL_CALL DatabaseMetaData::supportsSubqueriesInFrom() const
    {
        lcl_checkConnected( *m_pImpl );

        bool supportsSubQueries = false;
        try
        {
            sal_Int32 maxTablesInselect = m_pImpl->xConnectionMetaData->getMaxTablesInSelect();
            supportsSubQueries = ( maxTablesInselect > 1 ) || ( maxTablesInselect == 0 );
            // TODO: is there a better way to determine this? The above is not really true. More precise,
            // it's a *very* generous heuristics ...
        }
        catch( const Exception& )
        {
            DBG_UNHANDLED_EXCEPTION();
        }
        return supportsSubQueries;
    }

    //--------------------------------------------------------------------
    bool SAL_CALL DatabaseMetaData::restrictIdentifiersToSQL92() const
    {
        bool restrict( false );
        Any setting;
        if ( lcl_getDataSourceSetting( "EnableSQL92Check", *m_pImpl, setting ) )
            OSL_VERIFY( setting >>= restrict );
        return restrict;
    }

//........................................................................
} // namespace dbtools
//........................................................................

<commit_msg>INTEGRATION: CWS pchfix02 (1.3.32); FILE MERGED 2006/09/01 17:21:48 kaib 1.3.32.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dbmetadata.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 02:02:44 $
 *
 *  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_connectivity.hxx"

#ifndef CONNECTIVITY_INC_CONNECTIVITY_DBMETADATA_HXX
#include <connectivity/dbmetadata.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif

/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
/** === end UNO includes === **/

#ifndef TOOLS_DIAGNOSE_EX_H
#include <tools/diagnose_ex.h>
#endif

//........................................................................
namespace dbtools
{
//........................................................................

    /** === begin UNO using === **/
    using ::com::sun::star::uno::Reference;
    using ::com::sun::star::sdbc::XConnection;
    using ::com::sun::star::sdbc::XConnection;
    using ::com::sun::star::sdbc::XDatabaseMetaData;
    using ::com::sun::star::lang::IllegalArgumentException;
    using ::com::sun::star::uno::Exception;
    using ::com::sun::star::uno::Any;
    using ::com::sun::star::container::XChild;
    using ::com::sun::star::uno::UNO_QUERY_THROW;
    using ::com::sun::star::beans::XPropertySet;
    using ::com::sun::star::uno::Sequence;
    using ::com::sun::star::beans::PropertyValue;
    /** === end UNO using === **/

    //====================================================================
    //= DatabaseMetaData_Impl
    //====================================================================
    struct DatabaseMetaData_Impl
    {
        Reference< XConnection >        xConnection;
        Reference< XDatabaseMetaData >  xConnectionMetaData;
    };

    //--------------------------------------------------------------------
    namespace
    {
        static void lcl_construct( DatabaseMetaData_Impl& _metaDataImpl, const Reference< XConnection >& _connection )
        {
            _metaDataImpl.xConnection = _connection;
            if ( !_metaDataImpl.xConnection.is() )
                return;

            _metaDataImpl.xConnectionMetaData = _connection->getMetaData();
            if ( !_metaDataImpl.xConnectionMetaData.is() )
                throw IllegalArgumentException();
        }

        static void lcl_checkConnected( DatabaseMetaData_Impl& _metaDataImpl )
        {
            if ( !_metaDataImpl.xConnection.is() )
                throwSQLException( "not connected", SQL_CONNECTION_DOES_NOT_EXIST, NULL );
        }

        static bool lcl_getDataSourceSetting( const sal_Char* _asciiName, const DatabaseMetaData_Impl& _metaData, Any& _out_setting )
        {
            try
            {
                Reference< XChild > connectionAsChild( _metaData.xConnection, UNO_QUERY_THROW );
                Reference< XPropertySet > dataSource( connectionAsChild->getParent(), UNO_QUERY_THROW );

                Sequence< PropertyValue > dataSourceSettings;
                OSL_VERIFY( dataSource->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Info" ) ) ) >>= dataSourceSettings );

                const PropertyValue* setting( dataSourceSettings.getConstArray() );
                const PropertyValue* settingEnd( setting + dataSourceSettings.getLength() );
                for ( ; setting != settingEnd; ++setting )
                {
                    if ( setting->Name.equalsAscii( _asciiName ) )
                    {
                        _out_setting = setting->Value;
                        return true;
                    }
                }
            }
            catch( const Exception& )
            {
                DBG_UNHANDLED_EXCEPTION();
            }
            return false;
        }
    }

    //====================================================================
    //= DatabaseMetaData
    //====================================================================
    //--------------------------------------------------------------------
    DatabaseMetaData::DatabaseMetaData()
        :m_pImpl( new DatabaseMetaData_Impl )
    {
    }

    //--------------------------------------------------------------------
    DatabaseMetaData::DatabaseMetaData( const Reference< XConnection >& _connection )
        :m_pImpl( new DatabaseMetaData_Impl )
    {
        lcl_construct( *m_pImpl, _connection );
    }

    //--------------------------------------------------------------------
    DatabaseMetaData::DatabaseMetaData( const DatabaseMetaData& _copyFrom )
        :m_pImpl( new DatabaseMetaData_Impl( *_copyFrom.m_pImpl ) )
    {
    }

    //--------------------------------------------------------------------
    DatabaseMetaData& DatabaseMetaData::operator=( const DatabaseMetaData& _copyFrom )
    {
        if ( this == &_copyFrom )
            return *this;

        m_pImpl.reset( new DatabaseMetaData_Impl( *_copyFrom.m_pImpl ) );
        return *this;
    }

    //--------------------------------------------------------------------
    DatabaseMetaData::~DatabaseMetaData()
    {
    }

    //--------------------------------------------------------------------
    bool DatabaseMetaData::isConnected() const
    {
        return m_pImpl->xConnection.is();
    }

    //--------------------------------------------------------------------
    bool SAL_CALL DatabaseMetaData::supportsSubqueriesInFrom() const
    {
        lcl_checkConnected( *m_pImpl );

        bool supportsSubQueries = false;
        try
        {
            sal_Int32 maxTablesInselect = m_pImpl->xConnectionMetaData->getMaxTablesInSelect();
            supportsSubQueries = ( maxTablesInselect > 1 ) || ( maxTablesInselect == 0 );
            // TODO: is there a better way to determine this? The above is not really true. More precise,
            // it's a *very* generous heuristics ...
        }
        catch( const Exception& )
        {
            DBG_UNHANDLED_EXCEPTION();
        }
        return supportsSubQueries;
    }

    //--------------------------------------------------------------------
    bool SAL_CALL DatabaseMetaData::restrictIdentifiersToSQL92() const
    {
        bool restrict( false );
        Any setting;
        if ( lcl_getDataSourceSetting( "EnableSQL92Check", *m_pImpl, setting ) )
            OSL_VERIFY( setting >>= restrict );
        return restrict;
    }

//........................................................................
} // namespace dbtools
//........................................................................

<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
/*=========================================================================
 *
 *  Portions of this file are subject to the VTK Toolkit Version 3 copyright.
 *
 *  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
 *
 *  For complete copyright, license and disclaimer of warranty information
 *  please refer to the NOTICE file at the top of the ITK source tree.
 *
 *=========================================================================*/
#ifndef itkBSplineDecompositionImageFilter_hxx
#define itkBSplineDecompositionImageFilter_hxx
#include "itkBSplineDecompositionImageFilter.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkImageRegionIterator.h"
#include "itkProgressReporter.h"
#include "itkVector.h"

namespace itk
{
/**
 * Constructor
 */
template< typename TInputImage, typename TOutputImage >
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::BSplineDecompositionImageFilter()
{
  m_SplineOrder = 0;
  int SplineOrder = 3;
  m_Tolerance = 1e-10;   // Need some guidance on this one...what is reasonable?
  m_IteratorDirection = 0;
  this->SetSplineOrder(SplineOrder);
}

/**
 * Standard "PrintSelf" method
 */
template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::PrintSelf(
  std::ostream & os,
  Indent indent) const
{
  Superclass::PrintSelf(os, indent);
  os << indent << "Spline Order: " << m_SplineOrder << std::endl;
}

template< typename TInputImage, typename TOutputImage >
bool
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::DataToCoefficients1D()
{
  // See Unser, 1993, Part II, Equation 2.5,
  //   or Unser, 1999, Box 2. for an explanation.

  double c0 = 1.0;

  if ( m_DataLength[m_IteratorDirection] == 1 ) //Required by mirror boundaries
    {
    return false;
    }

  // Compute overall gain
  for ( int k = 0; k < m_NumberOfPoles; k++ )
    {
    // Note for cubic splines lambda = 6
    c0 = c0 * ( 1.0 - m_SplinePoles[k] ) * ( 1.0 - 1.0 / m_SplinePoles[k] );
    }

  // apply the gain
  for ( unsigned int n = 0; n < m_DataLength[m_IteratorDirection]; n++ )
    {
    m_Scratch[n] *= c0;
    }

  // loop over all poles
  for ( int k = 0; k < m_NumberOfPoles; k++ )
    {
    // causal initialization
    this->SetInitialCausalCoefficient(m_SplinePoles[k]);
    // causal recursion
    for ( unsigned int n = 1; n < m_DataLength[m_IteratorDirection]; n++ )
      {
      m_Scratch[n] += m_SplinePoles[k] * m_Scratch[n - 1];
      }

    // anticausal initialization
    this->SetInitialAntiCausalCoefficient(m_SplinePoles[k]);
    // anticausal recursion
    for ( int n = m_DataLength[m_IteratorDirection] - 2; 0 <= n; n-- )
      {
      m_Scratch[n] = m_SplinePoles[k] * ( m_Scratch[n + 1] - m_Scratch[n] );
      }
    }
  return true;
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::SetSplineOrder(unsigned int SplineOrder)
{
  if ( SplineOrder == m_SplineOrder )
    {
    return;
    }
  m_SplineOrder = SplineOrder;
  this->SetPoles();
  this->Modified();
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::SetPoles()
{
  /* See Unser, 1997. Part II, Table I for Pole values */
  // See also, Handbook of Medical Imaging, Processing and Analysis, Ed. Isaac
  // N. Bankman,
  //  2000, pg. 416.
  switch ( m_SplineOrder )
    {
    case 3:
      m_NumberOfPoles = 1;
      m_SplinePoles[0] = std::sqrt(3.0) - 2.0;
      break;
    case 0:
      m_NumberOfPoles = 0;
      break;
    case 1:
      m_NumberOfPoles = 0;
      break;
    case 2:
      m_NumberOfPoles = 1;
      m_SplinePoles[0] = std::sqrt(8.0) - 3.0;
      break;
    case 4:
      m_NumberOfPoles = 2;
      m_SplinePoles[0] = std::sqrt( 664.0 - std::sqrt(438976.0) ) + std::sqrt(304.0) - 19.0;
      m_SplinePoles[1] = std::sqrt( 664.0 + std::sqrt(438976.0) ) - std::sqrt(304.0) - 19.0;
      break;
    case 5:
      m_NumberOfPoles = 2;
      m_SplinePoles[0] = std::sqrt( 135.0 / 2.0 - std::sqrt(17745.0 / 4.0) ) + std::sqrt(105.0 / 4.0)
                         - 13.0 / 2.0;
      m_SplinePoles[1] = std::sqrt( 135.0 / 2.0 + std::sqrt(17745.0 / 4.0) ) - std::sqrt(105.0 / 4.0)
                         - 13.0 / 2.0;
      break;
    default:
      // SplineOrder not implemented yet.
      ExceptionObject err(__FILE__, __LINE__);
      err.SetLocation(ITK_LOCATION);
      err.SetDescription("SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet.");
      throw err;
      break;
    }
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::SetInitialCausalCoefficient(double z)
{
  /* beginning InitialCausalCoefficient */
  /* See Unser, 1999, Box 2 for explanation */
  CoeffType     sum;
  double        zn, z2n, iz;
  typename TInputImage::SizeValueType horizon;

  /* this initialization corresponds to mirror boundaries */
  horizon = m_DataLength[m_IteratorDirection];
  zn = z;
  if ( m_Tolerance > 0.0 )
    {
    horizon = (typename TInputImage::SizeValueType)
      std::ceil( std::log(m_Tolerance) / std::log( std::fabs(z) ) );
    }
  if ( horizon < m_DataLength[m_IteratorDirection] )
    {
    /* accelerated loop */
    sum = m_Scratch[0];   // verify this
    for ( unsigned int n = 1; n < horizon; n++ )
      {
      sum += zn * m_Scratch[n];
      zn *= z;
      }
    m_Scratch[0] = sum;
    }
  else
    {
    /* full loop */
    iz = 1.0 / z;
    z2n = std::pow( z, (double)( m_DataLength[m_IteratorDirection] - 1L ) );
    sum = m_Scratch[0] + z2n * m_Scratch[m_DataLength[m_IteratorDirection] - 1L];
    z2n *= z2n * iz;
    for ( unsigned int n = 1; n <= ( m_DataLength[m_IteratorDirection] - 2 ); n++ )
      {
      sum += ( zn + z2n ) * m_Scratch[n];
      zn *= z;
      z2n *= iz;
      }
    m_Scratch[0] = sum / ( 1.0 - zn * zn );
    }
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::SetInitialAntiCausalCoefficient(double z)
{
  // this initialization corresponds to mirror boundaries
  /* See Unser, 1999, Box 2 for explanation */
  //  Also see erratum at http://bigwww.epfl.ch/publications/unser9902.html
  m_Scratch[m_DataLength[m_IteratorDirection] - 1] =
    ( z / ( z * z - 1.0 ) )
    * ( z * m_Scratch[m_DataLength[m_IteratorDirection] - 2] + m_Scratch[m_DataLength[m_IteratorDirection] - 1] );
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::DataToCoefficientsND()
{
  OutputImagePointer output = this->GetOutput();

  Size< ImageDimension > size = output->GetBufferedRegion().GetSize();

  unsigned int count = output->GetBufferedRegion().GetNumberOfPixels() / size[0] * ImageDimension;

  ProgressReporter progress(this, 0, count, 10);

  // Initialize coeffient array
  this->CopyImageToImage();   // Coefficients are initialized to the input data

  for ( unsigned int n = 0; n < ImageDimension; n++ )
    {
    m_IteratorDirection = n;
    // Loop through each dimension

    // Initialize iterators
    OutputLinearIterator CIterator( output, output->GetBufferedRegion() );
    CIterator.SetDirection(m_IteratorDirection);
    // For each data vector
    while ( !CIterator.IsAtEnd() )
      {
      // Copy coefficients to scratch
      this->CopyCoefficientsToScratch(CIterator);

      // Perform 1D BSpline calculations
      this->DataToCoefficients1D();

      // Copy scratch back to coefficients.
      // Brings us back to the end of the line we were working on.
      CIterator.GoToBeginOfLine();
      this->CopyScratchToCoefficients(CIterator);   // m_Scratch = m_Image;
      CIterator.NextLine();
      progress.CompletedPixel();
      }
    }
}

/**
 * Copy the input image into the output image
 */
template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::CopyImageToImage()
{
  typedef ImageRegionConstIteratorWithIndex< TInputImage > InputIterator;
  typedef ImageRegionIterator< TOutputImage >              OutputIterator;
  typedef typename TOutputImage::PixelType                 OutputPixelType;

  InputIterator  inIt( this->GetInput(), this->GetInput()->GetBufferedRegion() );
  OutputIterator outIt( this->GetOutput(), this->GetOutput()->GetBufferedRegion() );

  inIt.GoToBegin();
  outIt.GoToBegin();

  while ( !outIt.IsAtEnd() )
    {
    outIt.Set( static_cast< OutputPixelType >( inIt.Get() ) );
    ++inIt;
    ++outIt;
    }
}

/**
 * Copy the scratch to one line of the output image
 */
template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::CopyScratchToCoefficients(OutputLinearIterator & Iter)
{
  typedef typename TOutputImage::PixelType OutputPixelType;
  typename TOutputImage::SizeValueType j = 0;
  while ( !Iter.IsAtEndOfLine() )
    {
    Iter.Set( static_cast< OutputPixelType >( m_Scratch[j] ) );
    ++Iter;
    ++j;
    }
}

/**
 * Copy one line of the output image to the scratch
 */
template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::CopyCoefficientsToScratch(OutputLinearIterator & Iter)
{
  typename TOutputImage::SizeValueType j = 0;

  while ( !Iter.IsAtEndOfLine() )
    {
    m_Scratch[j] = static_cast< CoeffType >( Iter.Get() );
    ++Iter;
    ++j;
    }
}

/**
 * GenerateInputRequestedRegion method.
 */
template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::GenerateInputRequestedRegion()
{
  // this filter requires the all of the input image to be in
  // the buffer
  InputImagePointer inputPtr = const_cast< TInputImage * >( this->GetInput() );

  if ( inputPtr )
    {
    inputPtr->SetRequestedRegionToLargestPossibleRegion();
    }
}

/**
 * EnlargeOutputRequestedRegion method.
 */
template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::EnlargeOutputRequestedRegion(
  DataObject *output)
{
  // this filter requires the all of the output image to be in
  // the buffer
  TOutputImage *imgData;

  imgData = dynamic_cast< TOutputImage * >( output );
  if ( imgData )
    {
    imgData->SetRequestedRegionToLargestPossibleRegion();
    }
}

/**
 * Generate data
 */
template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::GenerateData()
{
  // Allocate scratch memory
  InputImageConstPointer inputPtr = this->GetInput();

  m_DataLength = inputPtr->GetBufferedRegion().GetSize();

  typename TOutputImage::SizeValueType maxLength = 0;
  for ( unsigned int n = 0; n < ImageDimension; n++ )
    {
    if ( m_DataLength[n] > maxLength )
      {
      maxLength = m_DataLength[n];
      }
    }
  m_Scratch.resize(maxLength);

  // Allocate memory for output image
  OutputImagePointer outputPtr = this->GetOutput();
  outputPtr->SetBufferedRegion( outputPtr->GetRequestedRegion() );
  outputPtr->Allocate();

  // Calculate actual output
  this->DataToCoefficientsND();

  // Clean up
  m_Scratch.clear();
}
} // namespace itk

#endif
<commit_msg>ENH: Finish BSplineDecompositionImageFilter PrintSelf.<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
/*=========================================================================
 *
 *  Portions of this file are subject to the VTK Toolkit Version 3 copyright.
 *
 *  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
 *
 *  For complete copyright, license and disclaimer of warranty information
 *  please refer to the NOTICE file at the top of the ITK source tree.
 *
 *=========================================================================*/
#ifndef itkBSplineDecompositionImageFilter_hxx
#define itkBSplineDecompositionImageFilter_hxx
#include "itkBSplineDecompositionImageFilter.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkImageRegionIterator.h"
#include "itkProgressReporter.h"
#include "itkVector.h"

namespace itk
{
/**
 * Constructor
 */
template< typename TInputImage, typename TOutputImage >
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::BSplineDecompositionImageFilter()
{
  m_SplineOrder = 0;
  int SplineOrder = 3;
  m_Tolerance = 1e-10;   // Need some guidance on this one...what is reasonable?
  m_IteratorDirection = 0;
  this->SetSplineOrder(SplineOrder);
}

/**
 * Standard "PrintSelf" method
 */
template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::PrintSelf(
  std::ostream & os,
  Indent indent) const
{
  Superclass::PrintSelf(os, indent);

  os << indent << "Scratch: " << std::endl;
  for( unsigned int i = 0; i < m_Scratch.size(); ++i )
    {
    os << indent << "[" << i << "]: " << m_Scratch[i] << std::endl;
    }
  os << indent << "Data Length: " << m_DataLength << std::endl;
  os << indent << "Spline Order: " << m_SplineOrder << std::endl;
  os << indent << "Spline Poles: " << m_SplinePoles << std::endl;
  os << indent << "Number Of Poles: " << m_NumberOfPoles << std::endl;
  os << indent << "Tolerance: " << m_Tolerance << std::endl;
  os << indent << "Iterator Direction: " << m_IteratorDirection << std::endl;
}

template< typename TInputImage, typename TOutputImage >
bool
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::DataToCoefficients1D()
{
  // See Unser, 1993, Part II, Equation 2.5,
  //   or Unser, 1999, Box 2. for an explanation.

  double c0 = 1.0;

  if ( m_DataLength[m_IteratorDirection] == 1 ) //Required by mirror boundaries
    {
    return false;
    }

  // Compute overall gain
  for ( int k = 0; k < m_NumberOfPoles; k++ )
    {
    // Note for cubic splines lambda = 6
    c0 = c0 * ( 1.0 - m_SplinePoles[k] ) * ( 1.0 - 1.0 / m_SplinePoles[k] );
    }

  // apply the gain
  for ( unsigned int n = 0; n < m_DataLength[m_IteratorDirection]; n++ )
    {
    m_Scratch[n] *= c0;
    }

  // loop over all poles
  for ( int k = 0; k < m_NumberOfPoles; k++ )
    {
    // causal initialization
    this->SetInitialCausalCoefficient(m_SplinePoles[k]);
    // causal recursion
    for ( unsigned int n = 1; n < m_DataLength[m_IteratorDirection]; n++ )
      {
      m_Scratch[n] += m_SplinePoles[k] * m_Scratch[n - 1];
      }

    // anticausal initialization
    this->SetInitialAntiCausalCoefficient(m_SplinePoles[k]);
    // anticausal recursion
    for ( int n = m_DataLength[m_IteratorDirection] - 2; 0 <= n; n-- )
      {
      m_Scratch[n] = m_SplinePoles[k] * ( m_Scratch[n + 1] - m_Scratch[n] );
      }
    }
  return true;
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::SetSplineOrder(unsigned int SplineOrder)
{
  if ( SplineOrder == m_SplineOrder )
    {
    return;
    }
  m_SplineOrder = SplineOrder;
  this->SetPoles();
  this->Modified();
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::SetPoles()
{
  /* See Unser, 1997. Part II, Table I for Pole values */
  // See also, Handbook of Medical Imaging, Processing and Analysis, Ed. Isaac
  // N. Bankman,
  //  2000, pg. 416.
  switch ( m_SplineOrder )
    {
    case 3:
      m_NumberOfPoles = 1;
      m_SplinePoles[0] = std::sqrt(3.0) - 2.0;
      break;
    case 0:
      m_NumberOfPoles = 0;
      break;
    case 1:
      m_NumberOfPoles = 0;
      break;
    case 2:
      m_NumberOfPoles = 1;
      m_SplinePoles[0] = std::sqrt(8.0) - 3.0;
      break;
    case 4:
      m_NumberOfPoles = 2;
      m_SplinePoles[0] = std::sqrt( 664.0 - std::sqrt(438976.0) ) + std::sqrt(304.0) - 19.0;
      m_SplinePoles[1] = std::sqrt( 664.0 + std::sqrt(438976.0) ) - std::sqrt(304.0) - 19.0;
      break;
    case 5:
      m_NumberOfPoles = 2;
      m_SplinePoles[0] = std::sqrt( 135.0 / 2.0 - std::sqrt(17745.0 / 4.0) ) + std::sqrt(105.0 / 4.0)
                         - 13.0 / 2.0;
      m_SplinePoles[1] = std::sqrt( 135.0 / 2.0 + std::sqrt(17745.0 / 4.0) ) - std::sqrt(105.0 / 4.0)
                         - 13.0 / 2.0;
      break;
    default:
      // SplineOrder not implemented yet.
      ExceptionObject err(__FILE__, __LINE__);
      err.SetLocation(ITK_LOCATION);
      err.SetDescription("SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet.");
      throw err;
      break;
    }
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::SetInitialCausalCoefficient(double z)
{
  /* beginning InitialCausalCoefficient */
  /* See Unser, 1999, Box 2 for explanation */
  CoeffType     sum;
  double        zn, z2n, iz;
  typename TInputImage::SizeValueType horizon;

  /* this initialization corresponds to mirror boundaries */
  horizon = m_DataLength[m_IteratorDirection];
  zn = z;
  if ( m_Tolerance > 0.0 )
    {
    horizon = (typename TInputImage::SizeValueType)
      std::ceil( std::log(m_Tolerance) / std::log( std::fabs(z) ) );
    }
  if ( horizon < m_DataLength[m_IteratorDirection] )
    {
    /* accelerated loop */
    sum = m_Scratch[0];   // verify this
    for ( unsigned int n = 1; n < horizon; n++ )
      {
      sum += zn * m_Scratch[n];
      zn *= z;
      }
    m_Scratch[0] = sum;
    }
  else
    {
    /* full loop */
    iz = 1.0 / z;
    z2n = std::pow( z, (double)( m_DataLength[m_IteratorDirection] - 1L ) );
    sum = m_Scratch[0] + z2n * m_Scratch[m_DataLength[m_IteratorDirection] - 1L];
    z2n *= z2n * iz;
    for ( unsigned int n = 1; n <= ( m_DataLength[m_IteratorDirection] - 2 ); n++ )
      {
      sum += ( zn + z2n ) * m_Scratch[n];
      zn *= z;
      z2n *= iz;
      }
    m_Scratch[0] = sum / ( 1.0 - zn * zn );
    }
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::SetInitialAntiCausalCoefficient(double z)
{
  // this initialization corresponds to mirror boundaries
  /* See Unser, 1999, Box 2 for explanation */
  //  Also see erratum at http://bigwww.epfl.ch/publications/unser9902.html
  m_Scratch[m_DataLength[m_IteratorDirection] - 1] =
    ( z / ( z * z - 1.0 ) )
    * ( z * m_Scratch[m_DataLength[m_IteratorDirection] - 2] + m_Scratch[m_DataLength[m_IteratorDirection] - 1] );
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::DataToCoefficientsND()
{
  OutputImagePointer output = this->GetOutput();

  Size< ImageDimension > size = output->GetBufferedRegion().GetSize();

  unsigned int count = output->GetBufferedRegion().GetNumberOfPixels() / size[0] * ImageDimension;

  ProgressReporter progress(this, 0, count, 10);

  // Initialize coeffient array
  this->CopyImageToImage();   // Coefficients are initialized to the input data

  for ( unsigned int n = 0; n < ImageDimension; n++ )
    {
    m_IteratorDirection = n;
    // Loop through each dimension

    // Initialize iterators
    OutputLinearIterator CIterator( output, output->GetBufferedRegion() );
    CIterator.SetDirection(m_IteratorDirection);
    // For each data vector
    while ( !CIterator.IsAtEnd() )
      {
      // Copy coefficients to scratch
      this->CopyCoefficientsToScratch(CIterator);

      // Perform 1D BSpline calculations
      this->DataToCoefficients1D();

      // Copy scratch back to coefficients.
      // Brings us back to the end of the line we were working on.
      CIterator.GoToBeginOfLine();
      this->CopyScratchToCoefficients(CIterator);   // m_Scratch = m_Image;
      CIterator.NextLine();
      progress.CompletedPixel();
      }
    }
}

/**
 * Copy the input image into the output image
 */
template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::CopyImageToImage()
{
  typedef ImageRegionConstIteratorWithIndex< TInputImage > InputIterator;
  typedef ImageRegionIterator< TOutputImage >              OutputIterator;
  typedef typename TOutputImage::PixelType                 OutputPixelType;

  InputIterator  inIt( this->GetInput(), this->GetInput()->GetBufferedRegion() );
  OutputIterator outIt( this->GetOutput(), this->GetOutput()->GetBufferedRegion() );

  inIt.GoToBegin();
  outIt.GoToBegin();

  while ( !outIt.IsAtEnd() )
    {
    outIt.Set( static_cast< OutputPixelType >( inIt.Get() ) );
    ++inIt;
    ++outIt;
    }
}

/**
 * Copy the scratch to one line of the output image
 */
template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::CopyScratchToCoefficients(OutputLinearIterator & Iter)
{
  typedef typename TOutputImage::PixelType OutputPixelType;
  typename TOutputImage::SizeValueType j = 0;
  while ( !Iter.IsAtEndOfLine() )
    {
    Iter.Set( static_cast< OutputPixelType >( m_Scratch[j] ) );
    ++Iter;
    ++j;
    }
}

/**
 * Copy one line of the output image to the scratch
 */
template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::CopyCoefficientsToScratch(OutputLinearIterator & Iter)
{
  typename TOutputImage::SizeValueType j = 0;

  while ( !Iter.IsAtEndOfLine() )
    {
    m_Scratch[j] = static_cast< CoeffType >( Iter.Get() );
    ++Iter;
    ++j;
    }
}

/**
 * GenerateInputRequestedRegion method.
 */
template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::GenerateInputRequestedRegion()
{
  // this filter requires the all of the input image to be in
  // the buffer
  InputImagePointer inputPtr = const_cast< TInputImage * >( this->GetInput() );

  if ( inputPtr )
    {
    inputPtr->SetRequestedRegionToLargestPossibleRegion();
    }
}

/**
 * EnlargeOutputRequestedRegion method.
 */
template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::EnlargeOutputRequestedRegion(
  DataObject *output)
{
  // this filter requires the all of the output image to be in
  // the buffer
  TOutputImage *imgData;

  imgData = dynamic_cast< TOutputImage * >( output );
  if ( imgData )
    {
    imgData->SetRequestedRegionToLargestPossibleRegion();
    }
}

/**
 * Generate data
 */
template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::GenerateData()
{
  // Allocate scratch memory
  InputImageConstPointer inputPtr = this->GetInput();

  m_DataLength = inputPtr->GetBufferedRegion().GetSize();

  typename TOutputImage::SizeValueType maxLength = 0;
  for ( unsigned int n = 0; n < ImageDimension; n++ )
    {
    if ( m_DataLength[n] > maxLength )
      {
      maxLength = m_DataLength[n];
      }
    }
  m_Scratch.resize(maxLength);

  // Allocate memory for output image
  OutputImagePointer outputPtr = this->GetOutput();
  outputPtr->SetBufferedRegion( outputPtr->GetRequestedRegion() );
  outputPtr->Allocate();

  // Calculate actual output
  this->DataToCoefficientsND();

  // Clean up
  m_Scratch.clear();
}
} // namespace itk

#endif
<|endoftext|>


<commit_before>//#include <fenv.h>
#include <errno.h>

#include <Ogre.h>
#include <OgreArchiveFactory.h>

#ifdef NO_PLUGINS
#  include "OgreOctreePlugin.h"
#  include "OgreGLPlugin.h"
#  include "OgreParticleFXPlugin.h"
#  ifdef WIN32
#    include "OgreD3D9Plugin.h"
#  endif
#endif

#ifdef WIN32
#  include "win32/MouseDirectInput8.h"
#  include "win32/KeyboardDirectInput8.h"
#  include "win32/KeyboardWinAPI.h"
#else
#  include "linux/KeyboardX11.h"
#  include "linux/MouseX11.h"
#endif

#include "Grit.h"
#include "BackgroundMeshLoader.h"
#include "CentralisedLog.h"
#include "LuaParticleSystem.h"

CentralisedLog clog;

Grit *grit = NULL;

#include "console_colour.h"

int already_fatal = 0;

void app_fatal()
{
        if (!already_fatal) {
                already_fatal = 1;
                delete grit;
        }

        abort();
}

int main(int argc, const char **argv)
{

        try {

                Ogre::LogManager *lmgr = OGRE_NEW Ogre::LogManager();
                Ogre::Log *ogre_log = OGRE_NEW Ogre::Log("",false,true);
                ogre_log->addListener(&clog);
                lmgr->setDefaultLog(ogre_log);
                lmgr->setLogDetail(Ogre::LL_NORMAL);

                #ifdef FE_NOMASK_ENV
                //feenableexcept(FE_INVALID);
                //feenableexcept(FE_DIVBYZERO | FE_INVALID);
                #endif

                #ifdef NO_PLUGINS
                        Ogre::Root* ogre = OGRE_NEW Ogre::Root("","","");

                        Ogre::GLPlugin *gl = OGRE_NEW Ogre::GLPlugin();
                        ogre->installPlugin(gl);

                        Ogre::OctreePlugin *octree =
                                OGRE_NEW Ogre::OctreePlugin();
                        ogre->installPlugin(octree);

                        Ogre::ParticleFXPlugin *pfx =
                                OGRE_NEW Ogre::ParticleFXPlugin();
                        ogre->installPlugin(pfx);

                        #ifdef WIN32
                        Ogre::D3D9Plugin *d3d9 = OGRE_NEW Ogre::D3D9Plugin();
                        ogre->installPlugin(d3d9);
                        #endif
                #else
                        Ogre::Root* ogre = OGRE_NEW Ogre::Root("plugins.cfg","","");
                #endif

                BackgroundMeshLoader *bml = new BackgroundMeshLoader();

                #ifdef WIN32
                bool use_d3d9 = getenv("GRIT_GL")==NULL;
                bool use_dinput = getenv("GRIT_DINPUT")!=NULL;
                #else
                bool use_d3d9 = false;
                #endif

                bool use_vsync = getenv("GRIT_NOVSYNC")==NULL;
                bool use_fullscreen = getenv("GRIT_FULLSCREEN")!=NULL;

                if (use_d3d9) {
                        Ogre::RenderSystem *rs =
                                ogre->getRenderSystemByName("Direct3D9 Rendering Subsystem");
                        rs->setConfigOption("Allow NVPerfHUD","Yes");
                        //rs->setConfigOption("Anti aliasing","None");
                        rs->setConfigOption("Floating-point mode","Consistent");
                        rs->setConfigOption("Full Screen",use_fullscreen?"Yes":"No");
                        rs->setConfigOption("VSync",use_vsync?"Yes":"No");
                        rs->setConfigOption("Video Mode","800 x 600 @ 32-bit colour");
                        rs->setConfigOption("sRGB Gamma Conversion","No");
                        ogre->setRenderSystem(rs);
                } else {
                        Ogre::RenderSystem *rs =
                                ogre->getRenderSystemByName("OpenGL Rendering Subsystem");
                        rs->setConfigOption("FSAA","0");
                        rs->setConfigOption("Full Screen",use_fullscreen?"Yes":"No");
                        rs->setConfigOption("RTT Preferred Mode","FBO");
                        rs->setConfigOption("VSync",use_vsync?"Yes":"No");
                        rs->setConfigOption("Video Mode","800 x 600");
                        rs->setConfigOption("sRGB Gamma Conversion","No");
                        ogre->setRenderSystem(rs);
                }

                Ogre::RenderWindow *win = ogre->initialise(true,"Grit Game Window");

                size_t winid;
                win->getCustomAttribute("WINDOW", &winid);

                #ifdef WIN32
                Mouse *mouse = new MouseDirectInput8(winid);
                Keyboard *keyb = use_dinput ? (Keyboard *)new KeyboardDirectInput8(winid)
                                            : (Keyboard *)new KeyboardWinAPI(winid);
                HMODULE mod = GetModuleHandle(NULL);
                HICON icon = LoadIcon(mod,MAKEINTRESOURCE(111));
                SendMessage((HWND)winid, (UINT)WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) icon);
                SendMessage((HWND)winid, (UINT)WM_SETICON, (WPARAM) ICON_SMALL, (LPARAM) icon);
                #else
                Mouse *mouse = new MouseX11(winid);
                Keyboard *keyb = new KeyboardX11(winid);
                #endif

                Ogre::ParticleSystemManager::getSingleton()
                        .addAffectorFactory(new LuaParticleAffectorFactory());

                Ogre::ParticleSystemManager::getSingleton()
                        .addRendererFactory(new LuaParticleRendererFactory());

                new Grit(ogre,mouse,keyb,grit); // writes itself back to grit

                // now call out to lua

                grit->doMain(argc,argv);

                // lua returns - we quit

                bml->shutdown();

                delete grit;

                // ogre was deleted inside the grit destructor above

                delete bml;

                #ifdef NO_PLUGINS
                        OGRE_DELETE gl;
                        OGRE_DELETE octree;
                        OGRE_DELETE pfx;
                        #ifdef WIN32
                                OGRE_DELETE d3d9;
                        #endif
                #endif

        } catch( Ogre::Exception& e ) {
                std::cerr << "An exception has occured: "
                          << e.getFullDescription() << std::endl;
        }
        return EXIT_SUCCESS;
}

// vim: shiftwidth=8:tabstop=8:expandtab
<commit_msg>Turn off AA explicitly<commit_after>//#include <fenv.h>
#include <errno.h>

#include <Ogre.h>
#include <OgreArchiveFactory.h>

#ifdef NO_PLUGINS
#  include "OgreOctreePlugin.h"
#  include "OgreGLPlugin.h"
#  include "OgreParticleFXPlugin.h"
#  ifdef WIN32
#    include "OgreD3D9Plugin.h"
#  endif
#endif

#ifdef WIN32
#  include "win32/MouseDirectInput8.h"
#  include "win32/KeyboardDirectInput8.h"
#  include "win32/KeyboardWinAPI.h"
#else
#  include "linux/KeyboardX11.h"
#  include "linux/MouseX11.h"
#endif

#include "Grit.h"
#include "BackgroundMeshLoader.h"
#include "CentralisedLog.h"
#include "LuaParticleSystem.h"

CentralisedLog clog;

Grit *grit = NULL;

#include "console_colour.h"

int already_fatal = 0;

void app_fatal()
{
        if (!already_fatal) {
                already_fatal = 1;
                delete grit;
        }

        abort();
}

int main(int argc, const char **argv)
{

        try {

                Ogre::LogManager *lmgr = OGRE_NEW Ogre::LogManager();
                Ogre::Log *ogre_log = OGRE_NEW Ogre::Log("",false,true);
                ogre_log->addListener(&clog);
                lmgr->setDefaultLog(ogre_log);
                lmgr->setLogDetail(Ogre::LL_NORMAL);

                #ifdef FE_NOMASK_ENV
                //feenableexcept(FE_INVALID);
                //feenableexcept(FE_DIVBYZERO | FE_INVALID);
                #endif

                #ifdef NO_PLUGINS
                        Ogre::Root* ogre = OGRE_NEW Ogre::Root("","","");

                        Ogre::GLPlugin *gl = OGRE_NEW Ogre::GLPlugin();
                        ogre->installPlugin(gl);

                        Ogre::OctreePlugin *octree =
                                OGRE_NEW Ogre::OctreePlugin();
                        ogre->installPlugin(octree);

                        Ogre::ParticleFXPlugin *pfx =
                                OGRE_NEW Ogre::ParticleFXPlugin();
                        ogre->installPlugin(pfx);

                        #ifdef WIN32
                        Ogre::D3D9Plugin *d3d9 = OGRE_NEW Ogre::D3D9Plugin();
                        ogre->installPlugin(d3d9);
                        #endif
                #else
                        Ogre::Root* ogre = OGRE_NEW Ogre::Root("plugins.cfg","","");
                #endif

                BackgroundMeshLoader *bml = new BackgroundMeshLoader();

                #ifdef WIN32
                bool use_d3d9 = getenv("GRIT_GL")==NULL;
                bool use_dinput = getenv("GRIT_DINPUT")!=NULL;
                #else
                bool use_d3d9 = false;
                #endif

                bool use_vsync = getenv("GRIT_NOVSYNC")==NULL;
                bool use_fullscreen = getenv("GRIT_FULLSCREEN")!=NULL;

                if (use_d3d9) {
                        Ogre::RenderSystem *rs =
                                ogre->getRenderSystemByName("Direct3D9 Rendering Subsystem");
                        rs->setConfigOption("Allow NVPerfHUD","Yes");
                        rs->setConfigOption("FSAA","None");
                        rs->setConfigOption("Floating-point mode","Consistent");
                        rs->setConfigOption("Full Screen",use_fullscreen?"Yes":"No");
                        rs->setConfigOption("VSync",use_vsync?"Yes":"No");
                        rs->setConfigOption("Video Mode","800 x 600 @ 32-bit colour");
                        rs->setConfigOption("sRGB Gamma Conversion","No");
                        ogre->setRenderSystem(rs);
                } else {
                        Ogre::RenderSystem *rs =
                                ogre->getRenderSystemByName("OpenGL Rendering Subsystem");
                        rs->setConfigOption("FSAA","0");
                        rs->setConfigOption("Full Screen",use_fullscreen?"Yes":"No");
                        rs->setConfigOption("RTT Preferred Mode","FBO");
                        rs->setConfigOption("VSync",use_vsync?"Yes":"No");
                        rs->setConfigOption("Video Mode","800 x 600");
                        rs->setConfigOption("sRGB Gamma Conversion","No");
                        ogre->setRenderSystem(rs);
                }

                Ogre::RenderWindow *win = ogre->initialise(true,"Grit Game Window");

                size_t winid;
                win->getCustomAttribute("WINDOW", &winid);

                #ifdef WIN32
                Mouse *mouse = new MouseDirectInput8(winid);
                Keyboard *keyb = use_dinput ? (Keyboard *)new KeyboardDirectInput8(winid)
                                            : (Keyboard *)new KeyboardWinAPI(winid);
                HMODULE mod = GetModuleHandle(NULL);
                HICON icon = LoadIcon(mod,MAKEINTRESOURCE(111));
                SendMessage((HWND)winid, (UINT)WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) icon);
                SendMessage((HWND)winid, (UINT)WM_SETICON, (WPARAM) ICON_SMALL, (LPARAM) icon);
                #else
                Mouse *mouse = new MouseX11(winid);
                Keyboard *keyb = new KeyboardX11(winid);
                #endif

                Ogre::ParticleSystemManager::getSingleton()
                        .addAffectorFactory(new LuaParticleAffectorFactory());

                Ogre::ParticleSystemManager::getSingleton()
                        .addRendererFactory(new LuaParticleRendererFactory());

                new Grit(ogre,mouse,keyb,grit); // writes itself back to grit

                // now call out to lua

                grit->doMain(argc,argv);

                // lua returns - we quit

                bml->shutdown();

                delete grit;

                // ogre was deleted inside the grit destructor above

                delete bml;

                #ifdef NO_PLUGINS
                        OGRE_DELETE gl;
                        OGRE_DELETE octree;
                        OGRE_DELETE pfx;
                        #ifdef WIN32
                                OGRE_DELETE d3d9;
                        #endif
                #endif

        } catch( Ogre::Exception& e ) {
                std::cerr << "An exception has occured: "
                          << e.getFullDescription() << std::endl;
        }
        return EXIT_SUCCESS;
}

// vim: shiftwidth=8:tabstop=8:expandtab
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <assert.h>
#include <string.h>

#include <map>
#include <vector>

#include "webrtc/call.h"
#include "webrtc/common.h"
#include "webrtc/config.h"
#include "webrtc/modules/rtp_rtcp/interface/rtp_header_parser.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/rw_lock_wrapper.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/system_wrappers/interface/thread_annotations.h"
#include "webrtc/system_wrappers/interface/trace.h"
#include "webrtc/video/video_receive_stream.h"
#include "webrtc/video/video_send_stream.h"
#include "webrtc/video_engine/include/vie_base.h"
#include "webrtc/video_engine/include/vie_codec.h"
#include "webrtc/video_engine/include/vie_rtp_rtcp.h"

namespace webrtc {
const char* RtpExtension::kTOffset = "urn:ietf:params:rtp-hdrext:toffset";
const char* RtpExtension::kAbsSendTime =
    "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time";
namespace internal {

class CpuOveruseObserverProxy : public webrtc::CpuOveruseObserver {
 public:
  CpuOveruseObserverProxy(OveruseCallback* overuse_callback)
      : crit_(CriticalSectionWrapper::CreateCriticalSection()),
        overuse_callback_(overuse_callback) {
    assert(overuse_callback != NULL);
  }

  virtual ~CpuOveruseObserverProxy() {}

  virtual void OveruseDetected() OVERRIDE {
    CriticalSectionScoped lock(crit_.get());
    overuse_callback_->OnOveruse();
  }

  virtual void NormalUsage() OVERRIDE {
    CriticalSectionScoped lock(crit_.get());
    overuse_callback_->OnNormalUse();
  }

 private:
  const scoped_ptr<CriticalSectionWrapper> crit_;
  OveruseCallback* overuse_callback_ GUARDED_BY(crit_);
};

class Call : public webrtc::Call, public PacketReceiver {
 public:
  Call(webrtc::VideoEngine* video_engine, const Call::Config& config);
  virtual ~Call();

  virtual PacketReceiver* Receiver() OVERRIDE;

  virtual VideoSendStream* CreateVideoSendStream(
      const VideoSendStream::Config& config,
      const std::vector<VideoStream>& video_streams,
      const void* encoder_settings) OVERRIDE;

  virtual void DestroyVideoSendStream(webrtc::VideoSendStream* send_stream)
      OVERRIDE;

  virtual VideoReceiveStream* CreateVideoReceiveStream(
      const VideoReceiveStream::Config& config) OVERRIDE;

  virtual void DestroyVideoReceiveStream(
      webrtc::VideoReceiveStream* receive_stream) OVERRIDE;

  virtual uint32_t SendBitrateEstimate() OVERRIDE;
  virtual uint32_t ReceiveBitrateEstimate() OVERRIDE;

  virtual DeliveryStatus DeliverPacket(const uint8_t* packet,
                                       size_t length) OVERRIDE;

 private:
  DeliveryStatus DeliverRtcp(const uint8_t* packet, size_t length);
  DeliveryStatus DeliverRtp(const RTPHeader& header,
                            const uint8_t* packet,
                            size_t length);

  Call::Config config_;

  std::map<uint32_t, VideoReceiveStream*> receive_ssrcs_
      GUARDED_BY(receive_lock_);
  scoped_ptr<RWLockWrapper> receive_lock_;

  std::map<uint32_t, VideoSendStream*> send_ssrcs_ GUARDED_BY(send_lock_);
  scoped_ptr<RWLockWrapper> send_lock_;

  scoped_ptr<RtpHeaderParser> rtp_header_parser_;

  scoped_ptr<CpuOveruseObserverProxy> overuse_observer_proxy_;

  VideoSendStream::RtpStateMap suspended_send_ssrcs_;

  VideoEngine* video_engine_;
  ViERTP_RTCP* rtp_rtcp_;
  ViECodec* codec_;
  ViEBase* base_;
  int base_channel_id_;

  DISALLOW_COPY_AND_ASSIGN(Call);
};
}  // namespace internal

Call* Call::Create(const Call::Config& config) {
  VideoEngine* video_engine = config.webrtc_config != NULL
                                  ? VideoEngine::Create(*config.webrtc_config)
                                  : VideoEngine::Create();
  assert(video_engine != NULL);

  return new internal::Call(video_engine, config);
}

namespace internal {

const int kDefaultVideoStreamBitrateBps = 300000;

Call::Call(webrtc::VideoEngine* video_engine, const Call::Config& config)
    : config_(config),
      receive_lock_(RWLockWrapper::CreateRWLock()),
      send_lock_(RWLockWrapper::CreateRWLock()),
      rtp_header_parser_(RtpHeaderParser::Create()),
      video_engine_(video_engine),
      base_channel_id_(-1) {
  assert(video_engine != NULL);
  assert(config.send_transport != NULL);

  if (config.overuse_callback) {
    overuse_observer_proxy_.reset(
        new CpuOveruseObserverProxy(config.overuse_callback));
  }

  rtp_rtcp_ = ViERTP_RTCP::GetInterface(video_engine_);
  assert(rtp_rtcp_ != NULL);

  codec_ = ViECodec::GetInterface(video_engine_);
  assert(codec_ != NULL);

  // As a workaround for non-existing calls in the old API, create a base
  // channel used as default channel when creating send and receive streams.
  base_ = ViEBase::GetInterface(video_engine_);
  assert(base_ != NULL);

  base_->CreateChannel(base_channel_id_);
  assert(base_channel_id_ != -1);
}

Call::~Call() {
  base_->DeleteChannel(base_channel_id_);
  base_->Release();
  codec_->Release();
  rtp_rtcp_->Release();
  webrtc::VideoEngine::Delete(video_engine_);
}

PacketReceiver* Call::Receiver() { return this; }

VideoSendStream* Call::CreateVideoSendStream(
    const VideoSendStream::Config& config,
    const std::vector<VideoStream>& video_streams,
    const void* encoder_settings) {
  assert(config.rtp.ssrcs.size() > 0);

  // TODO(mflodman): Base the start bitrate on a current bandwidth estimate, if
  // the call has already started.
  VideoSendStream* send_stream = new VideoSendStream(
      config_.send_transport,
      overuse_observer_proxy_.get(),
      video_engine_,
      config,
      video_streams,
      encoder_settings,
      suspended_send_ssrcs_,
      base_channel_id_,
      config_.start_bitrate_bps != -1 ? config_.start_bitrate_bps
                                      : kDefaultVideoStreamBitrateBps);

  WriteLockScoped write_lock(*send_lock_);
  for (size_t i = 0; i < config.rtp.ssrcs.size(); ++i) {
    assert(send_ssrcs_.find(config.rtp.ssrcs[i]) == send_ssrcs_.end());
    send_ssrcs_[config.rtp.ssrcs[i]] = send_stream;
  }
  return send_stream;
}

void Call::DestroyVideoSendStream(webrtc::VideoSendStream* send_stream) {
  assert(send_stream != NULL);

  send_stream->Stop();

  VideoSendStream* send_stream_impl = NULL;
  {
    WriteLockScoped write_lock(*send_lock_);
    std::map<uint32_t, VideoSendStream*>::iterator it = send_ssrcs_.begin();
    while (it != send_ssrcs_.end()) {
      if (it->second == static_cast<VideoSendStream*>(send_stream)) {
        send_stream_impl = it->second;
        send_ssrcs_.erase(it++);
      } else {
        ++it;
      }
    }
  }

  VideoSendStream::RtpStateMap rtp_state = send_stream_impl->GetRtpStates();

  for (VideoSendStream::RtpStateMap::iterator it = rtp_state.begin();
       it != rtp_state.end();
       ++it) {
    suspended_send_ssrcs_[it->first] = it->second;
  }

  assert(send_stream_impl != NULL);
  delete send_stream_impl;
}

VideoReceiveStream* Call::CreateVideoReceiveStream(
    const VideoReceiveStream::Config& config) {
  VideoReceiveStream* receive_stream =
      new VideoReceiveStream(video_engine_,
                             config,
                             config_.send_transport,
                             config_.voice_engine,
                             base_channel_id_);

  WriteLockScoped write_lock(*receive_lock_);
  assert(receive_ssrcs_.find(config.rtp.remote_ssrc) == receive_ssrcs_.end());
  receive_ssrcs_[config.rtp.remote_ssrc] = receive_stream;
  // TODO(pbos): Configure different RTX payloads per receive payload.
  VideoReceiveStream::Config::Rtp::RtxMap::const_iterator it =
      config.rtp.rtx.begin();
  if (it != config.rtp.rtx.end())
    receive_ssrcs_[it->second.ssrc] = receive_stream;

  return receive_stream;
}

void Call::DestroyVideoReceiveStream(
    webrtc::VideoReceiveStream* receive_stream) {
  assert(receive_stream != NULL);

  VideoReceiveStream* receive_stream_impl = NULL;
  {
    WriteLockScoped write_lock(*receive_lock_);
    // Remove all ssrcs pointing to a receive stream. As RTX retransmits on a
    // separate SSRC there can be either one or two.
    std::map<uint32_t, VideoReceiveStream*>::iterator it =
        receive_ssrcs_.begin();
    while (it != receive_ssrcs_.end()) {
      if (it->second == static_cast<VideoReceiveStream*>(receive_stream)) {
        assert(receive_stream_impl == NULL ||
            receive_stream_impl == it->second);
        receive_stream_impl = it->second;
        receive_ssrcs_.erase(it++);
      } else {
        ++it;
      }
    }
  }

  assert(receive_stream_impl != NULL);
  delete receive_stream_impl;
}

uint32_t Call::SendBitrateEstimate() {
  // TODO(pbos): Return send-bitrate estimate
  return 0;
}

uint32_t Call::ReceiveBitrateEstimate() {
  // TODO(pbos): Return receive-bitrate estimate
  return 0;
}

Call::PacketReceiver::DeliveryStatus Call::DeliverRtcp(const uint8_t* packet,
                                                       size_t length) {
  // TODO(pbos): Figure out what channel needs it actually.
  //             Do NOT broadcast! Also make sure it's a valid packet.
  //             Return DELIVERY_UNKNOWN_SSRC if it can be determined that
  //             there's no receiver of the packet.
  bool rtcp_delivered = false;
  {
    ReadLockScoped read_lock(*receive_lock_);
    for (std::map<uint32_t, VideoReceiveStream*>::iterator it =
             receive_ssrcs_.begin();
         it != receive_ssrcs_.end();
         ++it) {
      if (it->second->DeliverRtcp(packet, length))
        rtcp_delivered = true;
    }
  }

  {
    ReadLockScoped read_lock(*send_lock_);
    for (std::map<uint32_t, VideoSendStream*>::iterator it =
             send_ssrcs_.begin();
         it != send_ssrcs_.end();
         ++it) {
      if (it->second->DeliverRtcp(packet, length))
        rtcp_delivered = true;
    }
  }
  return rtcp_delivered ? DELIVERY_OK : DELIVERY_PACKET_ERROR;
}

Call::PacketReceiver::DeliveryStatus Call::DeliverRtp(const RTPHeader& header,
                                                      const uint8_t* packet,
                                                      size_t length) {
  ReadLockScoped read_lock(*receive_lock_);
  std::map<uint32_t, VideoReceiveStream*>::iterator it =
      receive_ssrcs_.find(header.ssrc);

  if (it == receive_ssrcs_.end())
    return DELIVERY_UNKNOWN_SSRC;

  return it->second->DeliverRtp(static_cast<const uint8_t*>(packet), length)
             ? DELIVERY_OK
             : DELIVERY_PACKET_ERROR;
}

Call::PacketReceiver::DeliveryStatus Call::DeliverPacket(const uint8_t* packet,
                                                         size_t length) {
  // TODO(pbos): ExtensionMap if there are extensions.
  if (RtpHeaderParser::IsRtcp(packet, static_cast<int>(length)))
    return DeliverRtcp(packet, length);

  RTPHeader rtp_header;
  if (!rtp_header_parser_->Parse(packet, static_cast<int>(length), &rtp_header))
    return DELIVERY_PACKET_ERROR;

  return DeliverRtp(rtp_header, packet, length);
}

}  // namespace internal
}  // namespace webrtc
<commit_msg>Extract RTP-header SSRC inline in Call.<commit_after>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <assert.h>
#include <string.h>

#include <map>
#include <vector>

#include "webrtc/call.h"
#include "webrtc/common.h"
#include "webrtc/config.h"
#include "webrtc/modules/rtp_rtcp/interface/rtp_header_parser.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/rw_lock_wrapper.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/system_wrappers/interface/thread_annotations.h"
#include "webrtc/system_wrappers/interface/trace.h"
#include "webrtc/video/video_receive_stream.h"
#include "webrtc/video/video_send_stream.h"
#include "webrtc/video_engine/include/vie_base.h"
#include "webrtc/video_engine/include/vie_codec.h"
#include "webrtc/video_engine/include/vie_rtp_rtcp.h"

namespace webrtc {
const char* RtpExtension::kTOffset = "urn:ietf:params:rtp-hdrext:toffset";
const char* RtpExtension::kAbsSendTime =
    "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time";
namespace internal {

class CpuOveruseObserverProxy : public webrtc::CpuOveruseObserver {
 public:
  CpuOveruseObserverProxy(OveruseCallback* overuse_callback)
      : crit_(CriticalSectionWrapper::CreateCriticalSection()),
        overuse_callback_(overuse_callback) {
    assert(overuse_callback != NULL);
  }

  virtual ~CpuOveruseObserverProxy() {}

  virtual void OveruseDetected() OVERRIDE {
    CriticalSectionScoped lock(crit_.get());
    overuse_callback_->OnOveruse();
  }

  virtual void NormalUsage() OVERRIDE {
    CriticalSectionScoped lock(crit_.get());
    overuse_callback_->OnNormalUse();
  }

 private:
  const scoped_ptr<CriticalSectionWrapper> crit_;
  OveruseCallback* overuse_callback_ GUARDED_BY(crit_);
};

class Call : public webrtc::Call, public PacketReceiver {
 public:
  Call(webrtc::VideoEngine* video_engine, const Call::Config& config);
  virtual ~Call();

  virtual PacketReceiver* Receiver() OVERRIDE;

  virtual VideoSendStream* CreateVideoSendStream(
      const VideoSendStream::Config& config,
      const std::vector<VideoStream>& video_streams,
      const void* encoder_settings) OVERRIDE;

  virtual void DestroyVideoSendStream(webrtc::VideoSendStream* send_stream)
      OVERRIDE;

  virtual VideoReceiveStream* CreateVideoReceiveStream(
      const VideoReceiveStream::Config& config) OVERRIDE;

  virtual void DestroyVideoReceiveStream(
      webrtc::VideoReceiveStream* receive_stream) OVERRIDE;

  virtual uint32_t SendBitrateEstimate() OVERRIDE;
  virtual uint32_t ReceiveBitrateEstimate() OVERRIDE;

  virtual DeliveryStatus DeliverPacket(const uint8_t* packet,
                                       size_t length) OVERRIDE;

 private:
  DeliveryStatus DeliverRtcp(const uint8_t* packet, size_t length);
  DeliveryStatus DeliverRtp(const uint8_t* packet, size_t length);

  Call::Config config_;

  std::map<uint32_t, VideoReceiveStream*> receive_ssrcs_
      GUARDED_BY(receive_lock_);
  scoped_ptr<RWLockWrapper> receive_lock_;

  std::map<uint32_t, VideoSendStream*> send_ssrcs_ GUARDED_BY(send_lock_);
  scoped_ptr<RWLockWrapper> send_lock_;

  scoped_ptr<RtpHeaderParser> rtp_header_parser_;

  scoped_ptr<CpuOveruseObserverProxy> overuse_observer_proxy_;

  VideoSendStream::RtpStateMap suspended_send_ssrcs_;

  VideoEngine* video_engine_;
  ViERTP_RTCP* rtp_rtcp_;
  ViECodec* codec_;
  ViEBase* base_;
  int base_channel_id_;

  DISALLOW_COPY_AND_ASSIGN(Call);
};
}  // namespace internal

Call* Call::Create(const Call::Config& config) {
  VideoEngine* video_engine = config.webrtc_config != NULL
                                  ? VideoEngine::Create(*config.webrtc_config)
                                  : VideoEngine::Create();
  assert(video_engine != NULL);

  return new internal::Call(video_engine, config);
}

namespace internal {

const int kDefaultVideoStreamBitrateBps = 300000;

Call::Call(webrtc::VideoEngine* video_engine, const Call::Config& config)
    : config_(config),
      receive_lock_(RWLockWrapper::CreateRWLock()),
      send_lock_(RWLockWrapper::CreateRWLock()),
      rtp_header_parser_(RtpHeaderParser::Create()),
      video_engine_(video_engine),
      base_channel_id_(-1) {
  assert(video_engine != NULL);
  assert(config.send_transport != NULL);

  if (config.overuse_callback) {
    overuse_observer_proxy_.reset(
        new CpuOveruseObserverProxy(config.overuse_callback));
  }

  rtp_rtcp_ = ViERTP_RTCP::GetInterface(video_engine_);
  assert(rtp_rtcp_ != NULL);

  codec_ = ViECodec::GetInterface(video_engine_);
  assert(codec_ != NULL);

  // As a workaround for non-existing calls in the old API, create a base
  // channel used as default channel when creating send and receive streams.
  base_ = ViEBase::GetInterface(video_engine_);
  assert(base_ != NULL);

  base_->CreateChannel(base_channel_id_);
  assert(base_channel_id_ != -1);
}

Call::~Call() {
  base_->DeleteChannel(base_channel_id_);
  base_->Release();
  codec_->Release();
  rtp_rtcp_->Release();
  webrtc::VideoEngine::Delete(video_engine_);
}

PacketReceiver* Call::Receiver() { return this; }

VideoSendStream* Call::CreateVideoSendStream(
    const VideoSendStream::Config& config,
    const std::vector<VideoStream>& video_streams,
    const void* encoder_settings) {
  assert(config.rtp.ssrcs.size() > 0);

  // TODO(mflodman): Base the start bitrate on a current bandwidth estimate, if
  // the call has already started.
  VideoSendStream* send_stream = new VideoSendStream(
      config_.send_transport,
      overuse_observer_proxy_.get(),
      video_engine_,
      config,
      video_streams,
      encoder_settings,
      suspended_send_ssrcs_,
      base_channel_id_,
      config_.start_bitrate_bps != -1 ? config_.start_bitrate_bps
                                      : kDefaultVideoStreamBitrateBps);

  WriteLockScoped write_lock(*send_lock_);
  for (size_t i = 0; i < config.rtp.ssrcs.size(); ++i) {
    assert(send_ssrcs_.find(config.rtp.ssrcs[i]) == send_ssrcs_.end());
    send_ssrcs_[config.rtp.ssrcs[i]] = send_stream;
  }
  return send_stream;
}

void Call::DestroyVideoSendStream(webrtc::VideoSendStream* send_stream) {
  assert(send_stream != NULL);

  send_stream->Stop();

  VideoSendStream* send_stream_impl = NULL;
  {
    WriteLockScoped write_lock(*send_lock_);
    std::map<uint32_t, VideoSendStream*>::iterator it = send_ssrcs_.begin();
    while (it != send_ssrcs_.end()) {
      if (it->second == static_cast<VideoSendStream*>(send_stream)) {
        send_stream_impl = it->second;
        send_ssrcs_.erase(it++);
      } else {
        ++it;
      }
    }
  }

  VideoSendStream::RtpStateMap rtp_state = send_stream_impl->GetRtpStates();

  for (VideoSendStream::RtpStateMap::iterator it = rtp_state.begin();
       it != rtp_state.end();
       ++it) {
    suspended_send_ssrcs_[it->first] = it->second;
  }

  assert(send_stream_impl != NULL);
  delete send_stream_impl;
}

VideoReceiveStream* Call::CreateVideoReceiveStream(
    const VideoReceiveStream::Config& config) {
  VideoReceiveStream* receive_stream =
      new VideoReceiveStream(video_engine_,
                             config,
                             config_.send_transport,
                             config_.voice_engine,
                             base_channel_id_);

  WriteLockScoped write_lock(*receive_lock_);
  assert(receive_ssrcs_.find(config.rtp.remote_ssrc) == receive_ssrcs_.end());
  receive_ssrcs_[config.rtp.remote_ssrc] = receive_stream;
  // TODO(pbos): Configure different RTX payloads per receive payload.
  VideoReceiveStream::Config::Rtp::RtxMap::const_iterator it =
      config.rtp.rtx.begin();
  if (it != config.rtp.rtx.end())
    receive_ssrcs_[it->second.ssrc] = receive_stream;

  return receive_stream;
}

void Call::DestroyVideoReceiveStream(
    webrtc::VideoReceiveStream* receive_stream) {
  assert(receive_stream != NULL);

  VideoReceiveStream* receive_stream_impl = NULL;
  {
    WriteLockScoped write_lock(*receive_lock_);
    // Remove all ssrcs pointing to a receive stream. As RTX retransmits on a
    // separate SSRC there can be either one or two.
    std::map<uint32_t, VideoReceiveStream*>::iterator it =
        receive_ssrcs_.begin();
    while (it != receive_ssrcs_.end()) {
      if (it->second == static_cast<VideoReceiveStream*>(receive_stream)) {
        assert(receive_stream_impl == NULL ||
            receive_stream_impl == it->second);
        receive_stream_impl = it->second;
        receive_ssrcs_.erase(it++);
      } else {
        ++it;
      }
    }
  }

  assert(receive_stream_impl != NULL);
  delete receive_stream_impl;
}

uint32_t Call::SendBitrateEstimate() {
  // TODO(pbos): Return send-bitrate estimate
  return 0;
}

uint32_t Call::ReceiveBitrateEstimate() {
  // TODO(pbos): Return receive-bitrate estimate
  return 0;
}

PacketReceiver::DeliveryStatus Call::DeliverRtcp(const uint8_t* packet,
                                                       size_t length) {
  // TODO(pbos): Figure out what channel needs it actually.
  //             Do NOT broadcast! Also make sure it's a valid packet.
  //             Return DELIVERY_UNKNOWN_SSRC if it can be determined that
  //             there's no receiver of the packet.
  bool rtcp_delivered = false;
  {
    ReadLockScoped read_lock(*receive_lock_);
    for (std::map<uint32_t, VideoReceiveStream*>::iterator it =
             receive_ssrcs_.begin();
         it != receive_ssrcs_.end();
         ++it) {
      if (it->second->DeliverRtcp(packet, length))
        rtcp_delivered = true;
    }
  }

  {
    ReadLockScoped read_lock(*send_lock_);
    for (std::map<uint32_t, VideoSendStream*>::iterator it =
             send_ssrcs_.begin();
         it != send_ssrcs_.end();
         ++it) {
      if (it->second->DeliverRtcp(packet, length))
        rtcp_delivered = true;
    }
  }
  return rtcp_delivered ? DELIVERY_OK : DELIVERY_PACKET_ERROR;
}

PacketReceiver::DeliveryStatus Call::DeliverRtp(const uint8_t* packet,
                                                size_t length) {
  // Minimum RTP header size.
  if (length < 12)
    return DELIVERY_PACKET_ERROR;

  const uint8_t* ptr = &packet[8];
  uint32_t ssrc = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3] ;

  ReadLockScoped read_lock(*receive_lock_);
  std::map<uint32_t, VideoReceiveStream*>::iterator it =
      receive_ssrcs_.find(ssrc);

  if (it == receive_ssrcs_.end())
    return DELIVERY_UNKNOWN_SSRC;

  return it->second->DeliverRtp(packet, length) ? DELIVERY_OK
                                                : DELIVERY_PACKET_ERROR;
}

PacketReceiver::DeliveryStatus Call::DeliverPacket(const uint8_t* packet,
                                                   size_t length) {
  if (RtpHeaderParser::IsRtcp(packet, static_cast<int>(length)))
    return DeliverRtcp(packet, length);

  return DeliverRtp(packet, length);
}

}  // namespace internal
}  // namespace webrtc
<|endoftext|>


<commit_before>/*
 * Joey Button
 *
 *
 */

#include <stdio.h>
#include <opencv2/video/background_segm.hpp>
#include "opencv2/opencv.hpp"

// #include <iostream>
// #include <sstream>

using namespace cv;
using namespace std;
#define RADIUS 32

const char *win = "video";

void drawCircle(Mat img, Point center)
{
    int thickness = -1;
    int lineType = 8;

    circle( img,
            center,
            RADIUS,
            Scalar( 255, 255, 255 ),
            thickness,
            lineType);
}

void calcDir(Point *momentum, Point *pt, int height, int width){
      pt->x += momentum->x;
      pt->y += momentum->y;

      if (pt->y < height) {
           // Accelerate due to Gravity
          momentum->y += 1;
      } else {
          momentum->x = momentum->x *0.9;
          momentum->y = -(momentum->y * .5);   // bounce back up and halt it
          pt->y = height;
      }

      //off the top
      if (pt->y < RADIUS) {
            pt->y=RADIUS;
            momentum->y += 1;
            momentum->y = -(momentum->y * .5);
            momentum->x = momentum->x *0.9;
      }

      if (momentum->y * momentum->y <= 49 && pt->y > height){
          momentum->y = 0;
      }

}

int main()
{
    int cam = 0; // default camera
    VideoCapture cap(cam);
    if (!cap.isOpened()) {
        fprintf(stderr, "cannot open camera %d\n", cam);
        exit(1);
    }

    namedWindow(win, CV_WINDOW_AUTOSIZE);

    Mat fgMaskMOG; //fg mask generated by MOG method
    Mat inputFrame, outFrame;
    Mat circ;
    Point pt;

    BackgroundSubtractorMOG2 MOG;

    pt.x = 500;
    pt.y = 0;

    Point momentum;
    momentum.x = 0;
    momentum.y = 150;

    double count = 0;

    cap >> inputFrame;
    cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR);
    cvtColor(inputFrame, circ, CV_BGR2GRAY);

    int height = inputFrame.rows-2*RADIUS;
    int width = inputFrame.cols-2*RADIUS;

    while (++count) {
        cap >> inputFrame;

        calcDir(&momentum, &pt, height, width);

        MOG(inputFrame, fgMaskMOG);

        circ.setTo(Scalar(0,0,0));
        drawCircle(circ,pt);//for testing

        bitwise_and(circ, fgMaskMOG, circ);//THIS IS FOR CALCULATING INTERSECTION
        //anything white, in circ, is intersecting the ball to be drawn --
        //Change the momentum here

        if ( sum(circ)[0] > 10000.0)
          momentum.y -= 10;

        //EVERYTHING ABOVE THIS SHOULD BE CALCULATING WHERE TO DRAW

        //EVERYTHING BELOW THIS LINE SHOULD BE DRAWING THE outFrame
        outFrame.setTo(Scalar(0,0,0)); //set all of outFrame to be black

        drawCircle(fgMaskMOG,pt);//for testing
        imshow(win, fgMaskMOG);//for testing

        // drawCircle(outFrame,pt);//The real one
        // imshow(win, outFrame);//The real one

        if (waitKey(1) >= 0) // wait up to 30 msec
	        break;
    }

    return 0;
}

/*
    Mat BGRChannels[3];
    split(outFrame,BGRChannels); // split the BGR channesl
    BGRChannels[1]=Mat::zeros(outFrame.rows,outFrame.cols,CV_8UC1);// removing Green channel
    merge(BGRChannels,3,outFrame); // pack the image

    waitKey(0);
*/
<commit_msg>small mod<commit_after>/*
 * Joey Button
 *
 *
 */

#include <stdio.h>
#include <opencv2/video/background_segm.hpp>
#include "opencv2/opencv.hpp"

// #include <iostream>
// #include <sstream>

using namespace cv;
using namespace std;
#define RADIUS 32

const char *win = "video";

void drawCircle(Mat img, Point center)
{
    int thickness = -1;
    int lineType = 8;

    circle( img,
            center,
            RADIUS,
            Scalar( 255, 255, 255 ),
            thickness,
            lineType);
}

void calcDir(Point *momentum, Point *pt, int height, int width){
      pt->x += momentum->x;
      pt->y += momentum->y;

      if (pt->y < height) {
           // Accelerate due to Gravity
          momentum->y += 1;
      } else {
          momentum->x = momentum->x *0.9;
          momentum->y = -(momentum->y * .5);   // bounce back up and halt it
          pt->y = height;
      }

      //off the top
      if (pt->y < RADIUS) {
            pt->y=RADIUS;
            momentum->y += 1;
            momentum->y = -(momentum->y * .5);
            momentum->x = momentum->x *0.9;
      }

      if (momentum->y * momentum->y <= 49 && pt->y > height){
          momentum->y = 0;
      }

}

int main()
{
    int cam = 0; // default camera
    VideoCapture cap(cam);
    if (!cap.isOpened()) {
        fprintf(stderr, "cannot open camera %d\n", cam);
        exit(1);
    }

    namedWindow(win, CV_WINDOW_AUTOSIZE);

    Mat fgMaskMOG; //fg mask generated by MOG method
    Mat inputFrame, outFrame;
    Mat circ;
    Point pt;

    BackgroundSubtractorMOG2 MOG;

    pt.x = 500;
    pt.y = 0;

    Point momentum;
    momentum.x = 0;
    momentum.y = 150;

    double count = 0;

    cap >> inputFrame;
    cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR);
    cvtColor(inputFrame, circ, CV_BGR2GRAY);

    int height = inputFrame.rows-2*RADIUS;
    int width = inputFrame.cols-2*RADIUS;

    double overlap;

    while (++count) {
        cap >> inputFrame;

        calcDir(&momentum, &pt, height, width);

        MOG(inputFrame, fgMaskMOG);

        circ.setTo(Scalar(0,0,0));
        drawCircle(circ,pt);//for testing

        bitwise_and(circ, fgMaskMOG, circ);//THIS IS FOR CALCULATING INTERSECTION
        //anything white, in circ, is intersecting the ball to be drawn --
        //Change the momentum here

        overlap = sum(circ)[0];
        if ( overlap > 10000.0)
          momentum.y -= 10;

        //EVERYTHING ABOVE THIS SHOULD BE CALCULATING WHERE TO DRAW

        //EVERYTHING BELOW THIS LINE SHOULD BE DRAWING THE outFrame
        outFrame.setTo(Scalar(0,0,0)); //set all of outFrame to be black

        drawCircle(fgMaskMOG,pt);//for testing
        imshow(win, fgMaskMOG);//for testing

        // drawCircle(outFrame,pt);//The real one
        // imshow(win, outFrame);//The real one

        if (waitKey(1) >= 0) // wait up to 30 msec
	        break;
    }

    return 0;
}

/*
    Mat BGRChannels[3];
    split(outFrame,BGRChannels); // split the BGR channesl
    BGRChannels[1]=Mat::zeros(outFrame.rows,outFrame.cols,CV_8UC1);// removing Green channel
    merge(BGRChannels,3,outFrame); // pack the image

    waitKey(0);
*/
<|endoftext|>


<commit_before>// LGE codejam 2015
// 3. ... ...
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>

using namespace std;

int n, m;
set<int> in[20001];

void input() {
    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int a, b; cin >> a >> b;
        in[a].insert(b);
        in[b].insert(a);
    }
}

int common_friends(int a, int b) { // a != b
    std::vector<int> v(max(in[a].size(), in[b].size()));
    auto it = set_intersection(in[a].begin(), in[a].end(), in[b].begin(), in[b].end(), v.begin());
    return it - v.begin();
}

void solve() {
    int best(0);
    for (int a = 1; a <= n; a++) {
        if (in[a].size() <= best) continue;
        for (int b = a+1; b <= n; b++) {
            if (in[a].find(b) != in[a].end() || in[b].size() <= best) continue;
            best = max(best, common_friends(a, b));
        }
    }
    cout << best << endl;
}

void clear() {
    for (int i = 1; i <= n; i++) in[i].clear();
}

int main() {
    int tc;
    cin >> tc;
    while (tc--) {
        input();
        solve();
        clear();
    }
    return 0;
}
<commit_msg>improve performance : use vector instead of set<commit_after>// LGE codejam 2015
// 3. ... ...
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int n, m;
vector<int> in[20001];

void input() {
    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int a, b; cin >> a >> b;
        in[a].push_back(b);
        in[b].push_back(a);
    }
    for (int i = 1; i <= n; i++) sort(in[i].begin(), in[i].end());
}

int common_friends(int a, int b) { // a != b
    std::vector<int> v(max(in[a].size(), in[b].size()));
    auto it = set_intersection(in[a].begin(), in[a].end(), in[b].begin(), in[b].end(), v.begin());
    return it - v.begin();
}

void solve() {
    int best(0);
    for (int a = 1; a <= n; a++) {
        if (in[a].size() <= best) continue;
        for (int b = a+1; b <= n; b++) {
            if (in[b].size() <= best) continue;
            auto it = lower_bound(in[a].begin(), in[a].end(), b);
            if (it != in[a].end() && *it == b) continue;
            best = max(best, common_friends(a, b));
        }
    }
    cout << best << endl;
}

void clear() {
    for (int i = 1; i <= n; i++) in[i].clear();
}

int main() {
    int tc;
    cin >> tc;
    while (tc--) {
        input();
        solve();
        clear();
    }
    return 0;
}
<|endoftext|>


<commit_before>//== NullDerefChecker.cpp - Null dereference checker ------------*- C++ -*--==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This defines NullDerefChecker, a builtin check in GRExprEngine that performs
// checks for null pointers at loads and stores.
//
//===----------------------------------------------------------------------===//

#include "clang/Analysis/PathSensitive/Checkers/NullDerefChecker.h"
#include "clang/Analysis/PathSensitive/GRExprEngine.h"
#include "clang/Analysis/PathSensitive/BugReporter.h"

using namespace clang;

void *NullDerefChecker::getTag() {
  static int x = 0;
  return &x;
}

ExplodedNode *NullDerefChecker::CheckLocation(const Stmt *S, ExplodedNode *Pred,
                                              const GRState *state, SVal V,
                                              GRExprEngine &Eng) {
  Loc *LV = dyn_cast<Loc>(&V);

    // If the value is not a location, don't touch the node.
  if (!LV)
    return Pred;

  const GRState *NotNullState = state->Assume(*LV, true);
  const GRState *NullState = state->Assume(*LV, false);

  GRStmtNodeBuilder &Builder = Eng.getBuilder();
  BugReporter &BR = Eng.getBugReporter();

    // The explicit NULL case.
  if (NullState) {
      // Use the GDM to mark in the state what lval was null.
    const SVal *PersistentLV = Eng.getBasicVals().getPersistentSVal(*LV);
    NullState = NullState->set<GRState::NullDerefTag>(PersistentLV);

    ExplodedNode *N = Builder.generateNode(S, NullState, Pred,
                                           ProgramPoint::PostNullCheckFailedKind);
    if (N) {
      N->markAsSink();

      if (!NotNullState) { // Explicit null case.
        if (!BT)
          BT = new BuiltinBug(NULL, "Null dereference",
                              "Dereference of null pointer");

        EnhancedBugReport *R =
          new EnhancedBugReport(*BT, BT->getDescription().c_str(), N);

        R->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue,
                             bugreporter::GetDerefExpr(N));

        BR.EmitReport(R);

        return 0;
      } else // Implicit null case.
        ImplicitNullDerefNodes.push_back(N);
    }
  }

  if (!NotNullState)
    return 0;

  return Builder.generateNode(S, NotNullState, Pred,
                              ProgramPoint::PostLocationChecksSucceedKind);
}
<commit_msg>fix 80-col.<commit_after>//== NullDerefChecker.cpp - Null dereference checker ------------*- C++ -*--==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This defines NullDerefChecker, a builtin check in GRExprEngine that performs
// checks for null pointers at loads and stores.
//
//===----------------------------------------------------------------------===//

#include "clang/Analysis/PathSensitive/Checkers/NullDerefChecker.h"
#include "clang/Analysis/PathSensitive/GRExprEngine.h"
#include "clang/Analysis/PathSensitive/BugReporter.h"

using namespace clang;

void *NullDerefChecker::getTag() {
  static int x = 0;
  return &x;
}

ExplodedNode *NullDerefChecker::CheckLocation(const Stmt *S, ExplodedNode *Pred,
                                              const GRState *state, SVal V,
                                              GRExprEngine &Eng) {
  Loc *LV = dyn_cast<Loc>(&V);

    // If the value is not a location, don't touch the node.
  if (!LV)
    return Pred;

  const GRState *NotNullState = state->Assume(*LV, true);
  const GRState *NullState = state->Assume(*LV, false);

  GRStmtNodeBuilder &Builder = Eng.getBuilder();
  BugReporter &BR = Eng.getBugReporter();

    // The explicit NULL case.
  if (NullState) {
      // Use the GDM to mark in the state what lval was null.
    const SVal *PersistentLV = Eng.getBasicVals().getPersistentSVal(*LV);
    NullState = NullState->set<GRState::NullDerefTag>(PersistentLV);

    ExplodedNode *N = Builder.generateNode(S, NullState, Pred,
                                         ProgramPoint::PostNullCheckFailedKind);
    if (N) {
      N->markAsSink();

      if (!NotNullState) { // Explicit null case.
        if (!BT)
          BT = new BuiltinBug(NULL, "Null dereference",
                              "Dereference of null pointer");

        EnhancedBugReport *R =
          new EnhancedBugReport(*BT, BT->getDescription().c_str(), N);

        R->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue,
                             bugreporter::GetDerefExpr(N));

        BR.EmitReport(R);

        return 0;
      } else // Implicit null case.
        ImplicitNullDerefNodes.push_back(N);
    }
  }

  if (!NotNullState)
    return 0;

  return Builder.generateNode(S, NotNullState, Pred,
                              ProgramPoint::PostLocationChecksSucceedKind);
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ppapi/cpp/dev/buffer_dev.h"
#include "ppapi/cpp/dev/printing_dev.h"
#include "ppapi/cpp/image_data.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/rect.h"
#include "ppapi/utility/completion_callback_factory.h"

namespace {

const char pdf_data[] = "%PDF-1.4\r"
"%    \r"
"1 0 obj<</Type/FontDescriptor/FontBBox[-50 -207 1447 1000]/FontName/Verdana/Flags 32/StemV 92/CapHeight 734/XHeight 546/Ascent 1005/Descent -209/ItalicAngle 0/FontFamily(Verdana)/FontStretch/Normal/FontWeight 400>>\r"
"2 0 obj<</Type/Font/Subtype/TrueType/Encoding/UniCNS-UTF16-H/BaseFont/Verdana/Name/Verdana/FontDescriptor 1 0 R/FirstChar 72/LastChar 114/Widths[ 750 420 454 692 556 843 748 787 602 787 695 684 616 731 684 989 685 614 685 454 454 454 818 635 635 600 623 521 623 595 351 623 633 274 343 591 274 972 633 607 623 623 426]>>\r"
"4 0 obj<</Type/Page/Parent 3 0 R/MediaBox[0 0 612 792]/Contents 5 0 R/Resources<</ProcSet[/PDF/Text/ColorC]/Font<</N2 2 0 R>> >> >>endobj\r"
"5 0 obj<</Length 70>>stream\r"
"BT/N2 24 Tf 100 692 Td(Hello)Tj ET\r"
"BT/N2 24 Tf 200 692 Td(World)Tj ET\r"
"\r"
"endstream\r"
"endobj\r"
"3 0 obj<</Type/Pages/Kids[ 4 0 R]/Count 1>>endobj\r"
"6 0 obj<</Type/Catalog/Pages 3 0 R>>endobj\r"
"xref\r"
"0 7\r"
"0000000000 65535 f \r"
"0000000015 00000 n \r"
"0000000230 00000 n \r"
"0000000805 00000 n \r"
"0000000551 00000 n \r"
"0000000689 00000 n \r"
"0000000855 00000 n \r"
"trailer<</Size 7/Root 6 0 R>>\r"
"startxref\r"
"898\r"
"%%EOF";

}  // namespace

class MyInstance : public pp::Instance, public pp::Printing_Dev {
 public:
  explicit MyInstance(PP_Instance instance)
      : pp::Instance(instance),
        pp::Printing_Dev(this) {
  }
  virtual ~MyInstance() {}

  virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]) {
    return true;
  }

  virtual uint32_t QuerySupportedPrintOutputFormats() {
    return PP_PRINTOUTPUTFORMAT_PDF;
  }

  virtual int32_t PrintBegin(const PP_PrintSettings_Dev& print_settings) {
    return 1;
  }

  virtual pp::Resource PrintPages(
      const PP_PrintPageNumberRange_Dev* page_ranges,
      uint32_t page_range_count) {
    size_t pdf_len = strlen(pdf_data);
    pp::Buffer_Dev buffer(this, pdf_len);

    memcpy(buffer.data(), pdf_data, pdf_len);
    return buffer;
  }

  virtual void PrintEnd() {
  }

  virtual bool IsPrintScalingDisabled() {
    return true;
  }
};

class MyModule : public pp::Module {
 public:
  MyModule() : pp::Module() {}
  virtual ~MyModule() {}

  // Override CreateInstance to create your customized Instance object.
  virtual pp::Instance* CreateInstance(PP_Instance instance) {
    return new MyInstance(instance);
  }
};

namespace pp {

// Factory function for your specialization of the Module object.
Module* CreateModule() {
  return new MyModule();
}

}  // namespace pp

<commit_msg>Add string include to fix the build.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string.h>

#include "ppapi/cpp/dev/buffer_dev.h"
#include "ppapi/cpp/dev/printing_dev.h"
#include "ppapi/cpp/image_data.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/rect.h"
#include "ppapi/utility/completion_callback_factory.h"

namespace {

const char pdf_data[] = "%PDF-1.4\r"
"%    \r"
"1 0 obj<</Type/FontDescriptor/FontBBox[-50 -207 1447 1000]/FontName/Verdana/Flags 32/StemV 92/CapHeight 734/XHeight 546/Ascent 1005/Descent -209/ItalicAngle 0/FontFamily(Verdana)/FontStretch/Normal/FontWeight 400>>\r"
"2 0 obj<</Type/Font/Subtype/TrueType/Encoding/UniCNS-UTF16-H/BaseFont/Verdana/Name/Verdana/FontDescriptor 1 0 R/FirstChar 72/LastChar 114/Widths[ 750 420 454 692 556 843 748 787 602 787 695 684 616 731 684 989 685 614 685 454 454 454 818 635 635 600 623 521 623 595 351 623 633 274 343 591 274 972 633 607 623 623 426]>>\r"
"4 0 obj<</Type/Page/Parent 3 0 R/MediaBox[0 0 612 792]/Contents 5 0 R/Resources<</ProcSet[/PDF/Text/ColorC]/Font<</N2 2 0 R>> >> >>endobj\r"
"5 0 obj<</Length 70>>stream\r"
"BT/N2 24 Tf 100 692 Td(Hello)Tj ET\r"
"BT/N2 24 Tf 200 692 Td(World)Tj ET\r"
"\r"
"endstream\r"
"endobj\r"
"3 0 obj<</Type/Pages/Kids[ 4 0 R]/Count 1>>endobj\r"
"6 0 obj<</Type/Catalog/Pages 3 0 R>>endobj\r"
"xref\r"
"0 7\r"
"0000000000 65535 f \r"
"0000000015 00000 n \r"
"0000000230 00000 n \r"
"0000000805 00000 n \r"
"0000000551 00000 n \r"
"0000000689 00000 n \r"
"0000000855 00000 n \r"
"trailer<</Size 7/Root 6 0 R>>\r"
"startxref\r"
"898\r"
"%%EOF";

}  // namespace

class MyInstance : public pp::Instance, public pp::Printing_Dev {
 public:
  explicit MyInstance(PP_Instance instance)
      : pp::Instance(instance),
        pp::Printing_Dev(this) {
  }
  virtual ~MyInstance() {}

  virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]) {
    return true;
  }

  virtual uint32_t QuerySupportedPrintOutputFormats() {
    return PP_PRINTOUTPUTFORMAT_PDF;
  }

  virtual int32_t PrintBegin(const PP_PrintSettings_Dev& print_settings) {
    return 1;
  }

  virtual pp::Resource PrintPages(
      const PP_PrintPageNumberRange_Dev* page_ranges,
      uint32_t page_range_count) {
    size_t pdf_len = strlen(pdf_data);
    pp::Buffer_Dev buffer(this, pdf_len);

    memcpy(buffer.data(), pdf_data, pdf_len);
    return buffer;
  }

  virtual void PrintEnd() {
  }

  virtual bool IsPrintScalingDisabled() {
    return true;
  }
};

class MyModule : public pp::Module {
 public:
  MyModule() : pp::Module() {}
  virtual ~MyModule() {}

  // Override CreateInstance to create your customized Instance object.
  virtual pp::Instance* CreateInstance(PP_Instance instance) {
    return new MyInstance(instance);
  }
};

namespace pp {

// Factory function for your specialization of the Module object.
Module* CreateModule() {
  return new MyModule();
}

}  // namespace pp

<|endoftext|>


<commit_before>#include <libprecisegc/details/stack_map.hpp>

#include <cassert>
#include <utility>
#include <sys/mman.h>
#include <libprecisegc/details/gc_unsafe_scope.h>

namespace precisegc { namespace details {

stack_map::stack_map()
    : m_head(nullptr)
    , m_free_list(nullptr)
{}

stack_map::stack_map(stack_map&& other)
    : m_head(other.m_head)
    , m_free_list(other.m_free_list)
{}

stack_map::~stack_map()
{
    // We get memory leak here since we are not munmap our memory.
    // It wasn't fixed yet because memory management of stack_map will be refactored soon anyway.
}

stack_map& stack_map::operator=(stack_map&& other)
{
    stack_map(std::move(other)).swap(*this);
    return *this;
}

void stack_map::swap(stack_map& other)
{
    std::swap(m_head, other.m_head);
    std::swap(m_free_list, other.m_free_list);
}

void stack_map::insert(ptrs::gc_untyped_ptr* root)
{
    gc_unsafe_scope unsafe_scope;

    static const size_t PAGE_SIZE = 4096;
    static const size_t ELEM_PER_PAGE = PAGE_SIZE / sizeof(stack_map::element);

    if (m_free_list == nullptr) {
        element * data = (element *) mmap(nullptr, PAGE_SIZE, PROT_WRITE | PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
        assert(data != MAP_FAILED);
        for (int i = 0; i < ELEM_PER_PAGE; ++i) {
            data->next = m_free_list;
            m_free_list = data;
            data++;
        }
    }
    element *result = m_free_list;
    m_free_list = m_free_list->next;
    result->next = m_head;
    result->root = root;
    m_head = result;
}

void stack_map::remove(ptrs::gc_untyped_ptr* root)
{
    gc_unsafe_scope unsafe_scope;

    element* prev = nullptr;
    element* curr = m_head;
    while (curr && root != curr->root) {
        prev = curr;
        curr = curr->next;
    }
    assert(curr);

    element* next = curr->next;
    curr->next = m_free_list;
    m_free_list = curr;
    if (prev) {
        prev->next = next;
    } else {
        m_head = next;
    }
}

bool stack_map::contains(ptrs::gc_untyped_ptr* ptr)
{
    element* curr = m_head;
    while (curr && ptr != curr->root) {
        curr = curr->next;
    }
    return curr != nullptr;
}

stack_map::element* stack_map::head() const
{
    return m_head;
}

}}

<commit_msg>remove old file<commit_after><|endoftext|>