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

#ifndef _SD_ACCESSIBILITY_ACCESSIBLE_PAGE_SHAPE_HXX
#include "AccessiblePageShape.hxx"
#endif

#ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_SHAPE_INFO_HXX
#include <svx/AccessibleShapeInfo.hxx>
#endif

#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLE_ROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLE_STATE_TYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPEDESCRIPTOR_HPP_
#include <com/sun/star/drawing/XShapeDescriptor.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XMASTERPAGETARGET_HPP_
#include <com/sun/star/drawing/XMasterPageTarget.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::accessibility;
using ::com::sun::star::uno::Reference;

namespace accessibility {

//=====  internal  ============================================================

AccessiblePageShape::AccessiblePageShape (
    const uno::Reference<drawing::XDrawPage>& rxPage,
    const uno::Reference<XAccessible>& rxParent,
    const AccessibleShapeTreeInfo& rShapeTreeInfo,
    long nIndex)
    : AccessibleShape (AccessibleShapeInfo (NULL, rxParent, nIndex), rShapeTreeInfo),
      mxPage (rxPage)
{
    // The main part of the initialization is done in the init method which
    // has to be called from this constructor's caller.
}

AccessiblePageShape::~AccessiblePageShape (void)
{
    OSL_TRACE ("~AccessiblePageShape");
}

void AccessiblePageShape::Init (void)
{
    AccessibleShape::Init ();
}

//=====  XAccessibleContext  ==================================================

sal_Int32 SAL_CALL
       AccessiblePageShape::getAccessibleChildCount (void)
    throw ()
{
    return 0;
}

/** Forward the request to the shape.  Return the requested shape or throw
    an exception for a wrong index.
*/
uno::Reference<XAccessible> SAL_CALL
    AccessiblePageShape::getAccessibleChild (long nIndex)
    throw (::com::sun::star::uno::RuntimeException)
{
    throw lang::IndexOutOfBoundsException (
        ::rtl::OUString::createFromAscii ("page shape has no children"),
        static_cast<uno::XWeak*>(this));
}

//=====  XAccessibleComponent  ================================================

awt::Rectangle SAL_CALL AccessiblePageShape::getBounds (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    ThrowIfDisposed ();

    awt::Rectangle aBoundingBox;

    uno::Reference<beans::XPropertySet> xSet (mxPage, uno::UNO_QUERY);
    if (xSet.is())
    {
        uno::Any aValue;
        awt::Point aPosition;
        awt::Size aSize;

        aValue = xSet->getPropertyValue (
            OUString (RTL_CONSTASCII_USTRINGPARAM("BorderLeft")));
        aValue >>= aBoundingBox.X;
        aValue = xSet->getPropertyValue (
            OUString (RTL_CONSTASCII_USTRINGPARAM("BorderTop")));
        aValue >>= aBoundingBox.Y;

        aValue = xSet->getPropertyValue (
            OUString (RTL_CONSTASCII_USTRINGPARAM("Width")));
        aValue >>= aBoundingBox.Width;
        aValue = xSet->getPropertyValue (
            OUString (RTL_CONSTASCII_USTRINGPARAM("Height")));
        aValue >>= aBoundingBox.Height;
    }

    // Transform coordinates from internal to pixel.
    ::Size aPixelSize = maShapeTreeInfo.GetViewForwarder()->LogicToPixel (
        ::Size (aBoundingBox.Width, aBoundingBox.Height));
    ::Point aPixelPosition = maShapeTreeInfo.GetViewForwarder()->LogicToPixel (
        ::Point (aBoundingBox.X, aBoundingBox.Y));

    // Clip the shape's bounding box with the bounding box of its parent.
    Reference<XAccessibleComponent> xParentComponent (
        getAccessibleParent(), uno::UNO_QUERY);
    if (xParentComponent.is())
    {
        // Make the coordinates relative to the parent.
        awt::Point aParentLocation (xParentComponent->getLocationOnScreen());
        int x = aPixelPosition.getX() - aParentLocation.X;
        int y = aPixelPosition.getY() - aParentLocation.Y;

        // Clip with parent (with coordinates relative to itself).
        ::Rectangle aBBox (
            x, y, x + aPixelSize.getWidth(), y + aPixelSize.getHeight());
        awt::Size aParentSize (xParentComponent->getSize());
        ::Rectangle aParentBBox (0,0, aParentSize.Width, aParentSize.Height);
        aBBox = aBBox.GetIntersection (aParentBBox);
        aBoundingBox = awt::Rectangle (
            aBBox.getX(),
            aBBox.getY(),
            aBBox.getWidth(),
            aBBox.getHeight());
    }
    else
        aBoundingBox = awt::Rectangle (
            aPixelPosition.getX(), aPixelPosition.getY(),
            aPixelSize.getWidth(), aPixelSize.getHeight());

    return aBoundingBox;
}

sal_Int32 SAL_CALL AccessiblePageShape::getForeground (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    ThrowIfDisposed ();
    sal_Int32 nColor (0x0ffffffL);

    try
    {
        uno::Reference<beans::XPropertySet> aSet (mxPage, uno::UNO_QUERY);
        if (aSet.is())
        {
            uno::Any aColor;
            aColor = aSet->getPropertyValue (OUString::createFromAscii ("LineColor"));
            aColor >>= nColor;
        }
    }
    catch (::com::sun::star::beans::UnknownPropertyException)
    {
        // Ignore exception and return default color.
    }
    return nColor;
}

/** Extract the background color from the Background property of eithe the
    draw page or its master page.
*/
sal_Int32 SAL_CALL AccessiblePageShape::getBackground (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    ThrowIfDisposed ();
    sal_Int32 nColor (0x01020ffL);

    try
    {
        uno::Reference<beans::XPropertySet> xSet (mxPage, uno::UNO_QUERY);
        if (xSet.is())
        {
            uno::Any aBGSet;
            aBGSet = xSet->getPropertyValue (
                OUString (RTL_CONSTASCII_USTRINGPARAM("Background")));
            Reference<beans::XPropertySet> xBGSet (aBGSet, uno::UNO_QUERY);
            if ( ! xBGSet.is())
            {
                // Draw page has no Background property.  Try the master
                // page instead.
                Reference<drawing::XMasterPageTarget> xTarget (mxPage, uno::UNO_QUERY);
                if (xTarget.is())
                {
                    xSet = Reference<beans::XPropertySet> (xTarget->getMasterPage(),
                        uno::UNO_QUERY);
                    aBGSet = xSet->getPropertyValue (
                        OUString (RTL_CONSTASCII_USTRINGPARAM("Background")));
                    xBGSet = Reference<beans::XPropertySet> (aBGSet, uno::UNO_QUERY);
                }
            }
            // Fetch the fill color.  Has to be extended to cope with
            // gradients, hashes, and bitmaps.
            if (xBGSet.is())
            {
                uno::Any aColor;
                aColor = xBGSet->getPropertyValue (OUString::createFromAscii ("FillColor"));
                aColor >>= nColor;
            }
            else
                OSL_TRACE ("no Background property in page");
        }
    }
    catch (::com::sun::star::beans::UnknownPropertyException)
    {
        OSL_TRACE ("caught excption due to unknown property");
        // Ignore exception and return default color.
    }
    return nColor;
}

//=====  XServiceInfo  ========================================================

::rtl::OUString SAL_CALL
    AccessiblePageShape::getImplementationName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    ThrowIfDisposed ();
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AccessiblePageShape"));
}

::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
    AccessiblePageShape::getSupportedServiceNames (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return AccessibleShape::getSupportedServiceNames();
}

//=====  lang::XEventListener  ================================================

void SAL_CALL
    AccessiblePageShape::disposing (const ::com::sun::star::lang::EventObject& aEvent)
    throw (::com::sun::star::uno::RuntimeException)
{
    AccessibleShape::disposing (aEvent);
}

//=====  XComponent  ==========================================================

void AccessiblePageShape::dispose (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    OSL_TRACE ("AccessiblePageShape::dispose");

    // Unregister listeners.
    Reference<lang::XComponent> xComponent (mxShape, uno::UNO_QUERY);
    if (xComponent.is())
        xComponent->removeEventListener (this);

    // Cleanup.
    mxShape = NULL;

    // Call base classes.
    AccessibleContextBase::dispose ();
}

//=====  protected internal  ==================================================

::rtl::OUString
    AccessiblePageShape::CreateAccessibleBaseName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("PageShape"));
}

::rtl::OUString
    AccessiblePageShape::CreateAccessibleName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return CreateAccessibleBaseName();
}

::rtl::OUString
    AccessiblePageShape::CreateAccessibleDescription (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("Page Shape"));
}

} // end of namespace accessibility
<commit_msg>INTEGRATION: CWS impress78 (1.11.84); FILE MERGED 2005/12/15 16:42:37 af 1.11.84.1: #i57918# Added guard against missing shape tree info.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AccessiblePageShape.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: obo $ $Date: 2006-01-19 12:50:03 $
 *
 *  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 _SD_ACCESSIBILITY_ACCESSIBLE_PAGE_SHAPE_HXX
#include "AccessiblePageShape.hxx"
#endif

#ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_SHAPE_INFO_HXX
#include <svx/AccessibleShapeInfo.hxx>
#endif

#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLE_ROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLE_STATE_TYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPEDESCRIPTOR_HPP_
#include <com/sun/star/drawing/XShapeDescriptor.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XMASTERPAGETARGET_HPP_
#include <com/sun/star/drawing/XMasterPageTarget.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::accessibility;
using ::com::sun::star::uno::Reference;

namespace accessibility {

//=====  internal  ============================================================

AccessiblePageShape::AccessiblePageShape (
    const uno::Reference<drawing::XDrawPage>& rxPage,
    const uno::Reference<XAccessible>& rxParent,
    const AccessibleShapeTreeInfo& rShapeTreeInfo,
    long nIndex)
    : AccessibleShape (AccessibleShapeInfo (NULL, rxParent, nIndex), rShapeTreeInfo),
      mxPage (rxPage)
{
    // The main part of the initialization is done in the init method which
    // has to be called from this constructor's caller.
}

AccessiblePageShape::~AccessiblePageShape (void)
{
    OSL_TRACE ("~AccessiblePageShape");
}

void AccessiblePageShape::Init (void)
{
    AccessibleShape::Init ();
}

//=====  XAccessibleContext  ==================================================

sal_Int32 SAL_CALL
       AccessiblePageShape::getAccessibleChildCount (void)
    throw ()
{
    return 0;
}

/** Forward the request to the shape.  Return the requested shape or throw
    an exception for a wrong index.
*/
uno::Reference<XAccessible> SAL_CALL
    AccessiblePageShape::getAccessibleChild (long nIndex)
    throw (::com::sun::star::uno::RuntimeException)
{
    throw lang::IndexOutOfBoundsException (
        ::rtl::OUString::createFromAscii ("page shape has no children"),
        static_cast<uno::XWeak*>(this));
}

//=====  XAccessibleComponent  ================================================

awt::Rectangle SAL_CALL AccessiblePageShape::getBounds (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    ThrowIfDisposed ();

    awt::Rectangle aBoundingBox;

    if (maShapeTreeInfo.GetViewForwarder() != NULL)
    {
        uno::Reference<beans::XPropertySet> xSet (mxPage, uno::UNO_QUERY);
        if (xSet.is())
        {
            uno::Any aValue;
            awt::Point aPosition;
            awt::Size aSize;

            aValue = xSet->getPropertyValue (
                OUString (RTL_CONSTASCII_USTRINGPARAM("BorderLeft")));
            aValue >>= aBoundingBox.X;
            aValue = xSet->getPropertyValue (
                OUString (RTL_CONSTASCII_USTRINGPARAM("BorderTop")));
            aValue >>= aBoundingBox.Y;

            aValue = xSet->getPropertyValue (
                OUString (RTL_CONSTASCII_USTRINGPARAM("Width")));
            aValue >>= aBoundingBox.Width;
            aValue = xSet->getPropertyValue (
                OUString (RTL_CONSTASCII_USTRINGPARAM("Height")));
            aValue >>= aBoundingBox.Height;
        }

        // Transform coordinates from internal to pixel.
        ::Size aPixelSize = maShapeTreeInfo.GetViewForwarder()->LogicToPixel (
            ::Size (aBoundingBox.Width, aBoundingBox.Height));
        ::Point aPixelPosition = maShapeTreeInfo.GetViewForwarder()->LogicToPixel (
            ::Point (aBoundingBox.X, aBoundingBox.Y));

        // Clip the shape's bounding box with the bounding box of its parent.
        Reference<XAccessibleComponent> xParentComponent (
            getAccessibleParent(), uno::UNO_QUERY);
        if (xParentComponent.is())
        {
            // Make the coordinates relative to the parent.
            awt::Point aParentLocation (xParentComponent->getLocationOnScreen());
            int x = aPixelPosition.getX() - aParentLocation.X;
            int y = aPixelPosition.getY() - aParentLocation.Y;

            // Clip with parent (with coordinates relative to itself).
            ::Rectangle aBBox (
                x, y, x + aPixelSize.getWidth(), y + aPixelSize.getHeight());
            awt::Size aParentSize (xParentComponent->getSize());
            ::Rectangle aParentBBox (0,0, aParentSize.Width, aParentSize.Height);
            aBBox = aBBox.GetIntersection (aParentBBox);
            aBoundingBox = awt::Rectangle (
                aBBox.getX(),
                aBBox.getY(),
                aBBox.getWidth(),
                aBBox.getHeight());
        }
        else
            aBoundingBox = awt::Rectangle (
                aPixelPosition.getX(), aPixelPosition.getY(),
                aPixelSize.getWidth(), aPixelSize.getHeight());
    }

    return aBoundingBox;
}

sal_Int32 SAL_CALL AccessiblePageShape::getForeground (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    ThrowIfDisposed ();
    sal_Int32 nColor (0x0ffffffL);

    try
    {
        uno::Reference<beans::XPropertySet> aSet (mxPage, uno::UNO_QUERY);
        if (aSet.is())
        {
            uno::Any aColor;
            aColor = aSet->getPropertyValue (OUString::createFromAscii ("LineColor"));
            aColor >>= nColor;
        }
    }
    catch (::com::sun::star::beans::UnknownPropertyException)
    {
        // Ignore exception and return default color.
    }
    return nColor;
}

/** Extract the background color from the Background property of eithe the
    draw page or its master page.
*/
sal_Int32 SAL_CALL AccessiblePageShape::getBackground (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    ThrowIfDisposed ();
    sal_Int32 nColor (0x01020ffL);

    try
    {
        uno::Reference<beans::XPropertySet> xSet (mxPage, uno::UNO_QUERY);
        if (xSet.is())
        {
            uno::Any aBGSet;
            aBGSet = xSet->getPropertyValue (
                OUString (RTL_CONSTASCII_USTRINGPARAM("Background")));
            Reference<beans::XPropertySet> xBGSet (aBGSet, uno::UNO_QUERY);
            if ( ! xBGSet.is())
            {
                // Draw page has no Background property.  Try the master
                // page instead.
                Reference<drawing::XMasterPageTarget> xTarget (mxPage, uno::UNO_QUERY);
                if (xTarget.is())
                {
                    xSet = Reference<beans::XPropertySet> (xTarget->getMasterPage(),
                        uno::UNO_QUERY);
                    aBGSet = xSet->getPropertyValue (
                        OUString (RTL_CONSTASCII_USTRINGPARAM("Background")));
                    xBGSet = Reference<beans::XPropertySet> (aBGSet, uno::UNO_QUERY);
                }
            }
            // Fetch the fill color.  Has to be extended to cope with
            // gradients, hashes, and bitmaps.
            if (xBGSet.is())
            {
                uno::Any aColor;
                aColor = xBGSet->getPropertyValue (OUString::createFromAscii ("FillColor"));
                aColor >>= nColor;
            }
            else
                OSL_TRACE ("no Background property in page");
        }
    }
    catch (::com::sun::star::beans::UnknownPropertyException)
    {
        OSL_TRACE ("caught excption due to unknown property");
        // Ignore exception and return default color.
    }
    return nColor;
}

//=====  XServiceInfo  ========================================================

::rtl::OUString SAL_CALL
    AccessiblePageShape::getImplementationName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    ThrowIfDisposed ();
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AccessiblePageShape"));
}

::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
    AccessiblePageShape::getSupportedServiceNames (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return AccessibleShape::getSupportedServiceNames();
}

//=====  lang::XEventListener  ================================================

void SAL_CALL
    AccessiblePageShape::disposing (const ::com::sun::star::lang::EventObject& aEvent)
    throw (::com::sun::star::uno::RuntimeException)
{
    AccessibleShape::disposing (aEvent);
}

//=====  XComponent  ==========================================================

void AccessiblePageShape::dispose (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    OSL_TRACE ("AccessiblePageShape::dispose");

    // Unregister listeners.
    Reference<lang::XComponent> xComponent (mxShape, uno::UNO_QUERY);
    if (xComponent.is())
        xComponent->removeEventListener (this);

    // Cleanup.
    mxShape = NULL;

    // Call base classes.
    AccessibleContextBase::dispose ();
}

//=====  protected internal  ==================================================

::rtl::OUString
    AccessiblePageShape::CreateAccessibleBaseName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("PageShape"));
}

::rtl::OUString
    AccessiblePageShape::CreateAccessibleName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return CreateAccessibleBaseName();
}

::rtl::OUString
    AccessiblePageShape::CreateAccessibleDescription (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("Page Shape"));
}

} // end of namespace accessibility
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkSphericalDirectionEncoder.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkSphericalDirectionEncoder.h"
#include "vtkObjectFactory.h"

#include "vtkMath.h"
#include "vtkTransform.h"

vtkCxxRevisionMacro(vtkSphericalDirectionEncoder, "1.3");
vtkStandardNewMacro(vtkSphericalDirectionEncoder);

float vtkSphericalDirectionEncoder::DecodedGradientTable[65536*3];
int   vtkSphericalDirectionEncoder::DecodedGradientTableInitialized = 0;

// Construct the object. Initialize the index table which will be
// used to map the normal into a patch on the recursively subdivided
// sphere.
vtkSphericalDirectionEncoder::vtkSphericalDirectionEncoder()
{
  this->InitializeDecodedGradientTable();
}

// Destruct a vtkSphericalDirectionEncoder - free up any memory used
vtkSphericalDirectionEncoder::~vtkSphericalDirectionEncoder()
{
}

// Encode n into a 2 byte value. The first byte will be theta - the
// rotation angle around the z axis. The second (high order) byte is
// phi - the elevation of the vector. 256 values are used for theta,
// but only 255 values for phi, leaving room for a "zero normal" code
int vtkSphericalDirectionEncoder::GetEncodedDirection( float n[3] )
{
  if ( n[0] == 0.0 && n[1] == 0.0 && n[2] == 0.0 )
    {
    return ( 255*256 );
    }

  float theta, phi;

  theta = (vtkMath::RadiansToDegrees())*atan2( n[1], n[0] );
  theta = (theta<0.0)?(theta+360.0):(theta);
  theta = (theta>=360.0)?(theta-360.0):(theta);

  phi = (vtkMath::RadiansToDegrees())*asin( n[2] );
  phi = (phi > 90.5)?(phi-360):(phi);

  int lowByte, highByte;

  lowByte  = static_cast<int>(theta * 255.0 / 359.0 + 0.5);
  highByte = static_cast<int>((phi+90.0) * 254.0 / 180.0 + 0.5);

  lowByte = (lowByte<0)?(0):(lowByte);
  lowByte = (lowByte>255)?(255):(lowByte);

  highByte = (highByte<0)?(0):(highByte);
  highByte = (highByte>254)?(254):(highByte);

  return (lowByte + highByte*256);
}

float *vtkSphericalDirectionEncoder::GetDecodedGradient( int value )
{
  return &(vtkSphericalDirectionEncoder::DecodedGradientTable[value*3]);
}

// This is the table that maps the encoded gradient back into
// a float triple.
void vtkSphericalDirectionEncoder::InitializeDecodedGradientTable()
{
  if ( vtkSphericalDirectionEncoder::DecodedGradientTableInitialized )
    {
    return;
    }

  float theta, phi;
  int   i, j;

  vtkTransform *transformPhi = vtkTransform::New();
  vtkTransform *transformTheta = vtkTransform::New();

  float v1[3] = {1,0,0};
  float v2[3], v3[3];

  float *ptr = vtkSphericalDirectionEncoder::DecodedGradientTable;

  for ( j = 0; j < 256; j++ )
    {
    phi = -89.5 + j * (179.0 / 254.0 );

      transformPhi->Identity();
      transformPhi->RotateY( -phi );
      transformPhi->TransformPoint( v1, v2 );

    for ( i = 0; i < 256; i++ )
      {
      if ( j < 255 )
        {
        theta = i * (359.0 / 255.0);

        transformTheta->Identity();
        transformTheta->RotateZ( theta );
        transformTheta->TransformPoint( v2, v3 );
        }
      else
        {
        v3[0] = 0.0;
        v3[1] = 0.0;
        v3[2] = 0.0;
        }

      *(ptr++) = v3[0];
      *(ptr++) = v3[1];
      *(ptr++) = v3[2];
      }
    }

  transformPhi->Delete();
  transformTheta->Delete();

  vtkSphericalDirectionEncoder::DecodedGradientTableInitialized = 1;
}

// Print the vtkSphericalDirectionEncoder
void vtkSphericalDirectionEncoder::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Number of encoded directions: " <<
    this->GetNumberOfEncodedDirections() << endl;
}

<commit_msg>BUG: on some systems atan2 did not handle a zero denominator<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkSphericalDirectionEncoder.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkSphericalDirectionEncoder.h"
#include "vtkObjectFactory.h"

#include "vtkMath.h"
#include "vtkTransform.h"

vtkCxxRevisionMacro(vtkSphericalDirectionEncoder, "1.4");
vtkStandardNewMacro(vtkSphericalDirectionEncoder);

float vtkSphericalDirectionEncoder::DecodedGradientTable[65536*3];
int   vtkSphericalDirectionEncoder::DecodedGradientTableInitialized = 0;

// Construct the object. Initialize the index table which will be
// used to map the normal into a patch on the recursively subdivided
// sphere.
vtkSphericalDirectionEncoder::vtkSphericalDirectionEncoder()
{
  this->InitializeDecodedGradientTable();
}

// Destruct a vtkSphericalDirectionEncoder - free up any memory used
vtkSphericalDirectionEncoder::~vtkSphericalDirectionEncoder()
{
}

// Encode n into a 2 byte value. The first byte will be theta - the
// rotation angle around the z axis. The second (high order) byte is
// phi - the elevation of the vector. 256 values are used for theta,
// but only 255 values for phi, leaving room for a "zero normal" code
int vtkSphericalDirectionEncoder::GetEncodedDirection( float n[3] )
{
  if ( n[0] == 0.0 && n[1] == 0.0 && n[2] == 0.0 )
    {
    return ( 255*256 );
    }

  float theta, phi;

  // Need to handle this separately since some atan2 implementations
  // don't handle a zero denominator
  if ( n[0] == 0 )
    {
    theta = (n[1]>0)?(90.0):(270.0);
    }
  else
    {
    theta = (vtkMath::RadiansToDegrees())*atan2( n[1], n[0] );
    theta = (theta<0.0)?(theta+360.0):(theta);
    theta = (theta>=360.0)?(theta-360.0):(theta);
    }

  phi = (vtkMath::RadiansToDegrees())*asin( n[2] );
  phi = (phi > 90.5)?(phi-360):(phi);

  int lowByte, highByte;

  lowByte  = static_cast<int>(theta * 255.0 / 359.0 + 0.5);
  highByte = static_cast<int>((phi+90.0) * 254.0 / 180.0 + 0.5);

  lowByte = (lowByte<0)?(0):(lowByte);
  lowByte = (lowByte>255)?(255):(lowByte);

  highByte = (highByte<0)?(0):(highByte);
  highByte = (highByte>254)?(254):(highByte);

  return (lowByte + highByte*256);
}

float *vtkSphericalDirectionEncoder::GetDecodedGradient( int value )
{
  return &(vtkSphericalDirectionEncoder::DecodedGradientTable[value*3]);
}

// This is the table that maps the encoded gradient back into
// a float triple.
void vtkSphericalDirectionEncoder::InitializeDecodedGradientTable()
{
  if ( vtkSphericalDirectionEncoder::DecodedGradientTableInitialized )
    {
    return;
    }

  float theta, phi;
  int   i, j;

  vtkTransform *transformPhi = vtkTransform::New();
  vtkTransform *transformTheta = vtkTransform::New();

  float v1[3] = {1,0,0};
  float v2[3], v3[3];

  float *ptr = vtkSphericalDirectionEncoder::DecodedGradientTable;

  for ( j = 0; j < 256; j++ )
    {
    phi = -89.5 + j * (179.0 / 254.0 );

      transformPhi->Identity();
      transformPhi->RotateY( -phi );
      transformPhi->TransformPoint( v1, v2 );

    for ( i = 0; i < 256; i++ )
      {
      if ( j < 255 )
        {
        theta = i * (359.0 / 255.0);

        transformTheta->Identity();
        transformTheta->RotateZ( theta );
        transformTheta->TransformPoint( v2, v3 );
        }
      else
        {
        v3[0] = 0.0;
        v3[1] = 0.0;
        v3[2] = 0.0;
        }

      *(ptr++) = v3[0];
      *(ptr++) = v3[1];
      *(ptr++) = v3[2];
      }
    }

  transformPhi->Delete();
  transformTheta->Delete();

  vtkSphericalDirectionEncoder::DecodedGradientTableInitialized = 1;
}

// Print the vtkSphericalDirectionEncoder
void vtkSphericalDirectionEncoder::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Number of encoded directions: " <<
    this->GetNumberOfEncodedDirections() << endl;
}

<|endoftext|>


<commit_before>/*
 * info.cpp
 *
 *  Created on: Nov 22, 2012
 *      Author: partio
 */

#include "info.h"
#include <limits> // for std::numeric_limits<size_t>::max();
#include <boost/lexical_cast.hpp>
#include "plugin_factory.h"
#include "logger_factory.h"

#define HIMAN_AUXILIARY_INCLUDE

#include "neons.h"

#undef HIMAN_AUXILIARY_INCLUDE

using namespace std;
using namespace himan;

info::info()
	: itsLevelIterator(new level_iter())
	, itsTimeIterator(new time_iter())
	, itsParamIterator(new param_iter())
	, itsDimensionMatrix(new matrix_t())
{
    Init();
    itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("info"));

}

info::~info() {}

info::info(const info& other)
	// Iterators are COPIED
	: itsLevelIterator(new level_iter(*other.itsLevelIterator))
	, itsTimeIterator(new time_iter(*other.itsTimeIterator))
	, itsParamIterator(new param_iter(*other.itsParamIterator))
{
	/* START GLOBAL CONFIGURATION OPTIONS */

	itsProjection = other.itsProjection;
	itsOrientation = other.itsOrientation;
	itsScanningMode = other.itsScanningMode;

	itsBottomLeft = other.itsBottomLeft;
	itsTopRight = other.itsTopRight;
	itsSouthPole = other.itsSouthPole;

	itsUVRelativeToGrid = other.itsUVRelativeToGrid;
	itsNi = other.itsNi;
	itsNj = other.itsNj;

	itsDi = other.itsDi;
	itsDj = other.itsDj;

	/* END GLOBAL CONFIGURATION OPTIONS */

	// Data backend is SHARED
	itsDimensionMatrix = other.itsDimensionMatrix;

	itsLocationIndex = other.itsLocationIndex;

	itsProducer = other.itsProducer;

	itsOriginDateTime = other.itsOriginDateTime;

	itsStepSizeOverOneByte = other.itsStepSizeOverOneByte;

	itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("info"));
}

void info::Init()
{

    itsProjection = kUnknownProjection;
    itsScanningMode = kUnknownScanningMode;

//    itsAB = std::vector<double>;

    itsBottomLeft = point(kHPMissingFloat, kHPMissingFloat);
    itsTopRight = point(kHPMissingFloat, kHPMissingFloat);
    itsSouthPole = point(kHPMissingFloat, kHPMissingFloat);

    itsOrientation = kHPMissingFloat;
    itsStepSizeOverOneByte = false;
    itsUVRelativeToGrid = false;

    itsNi = 0;
    itsNj = 0;

    itsDi = kHPMissingFloat;
    itsDj = kHPMissingFloat;
}

std::ostream& info::Write(std::ostream& file) const
{

    file << "<" << ClassName() << " " << Version() << ">" << endl;

    file << "__itsProjection__ " << itsProjection << endl;

    file << itsBottomLeft;
    file << itsTopRight;
    file << itsSouthPole;

    file << "__itsOrientation__ " << itsOrientation << endl;
    file << "__itsNi__ " << itsNi << endl;
    file << "__itsNj__ " << itsNj << endl;
    file << "__itsDi__ " << itsDi << endl;
    file << "__itsDi__ " << itsDj << endl;

    file << "__itsUVRelativeToGrid__ " << itsUVRelativeToGrid << endl;

    file << "__itsScanningMode__ " << itsScanningMode << endl;

    file << itsProducer;

    if (itsParamIterator)
    {
    	file << *itsParamIterator;
    }

    if (itsLevelIterator)
    {
    	file << *itsLevelIterator;
    }

    if (itsTimeIterator)
    {
    	file << *itsTimeIterator;
    }

    return file;
}

void info::Create()
{
    itsDimensionMatrix = shared_ptr<matrix_t> (new matrix_t(itsTimeIterator->Size(), itsLevelIterator->Size(), itsParamIterator->Size()));
    Reset();

    while (NextTime())
    {
        ResetLevel();

        while (NextLevel())
        {
            ResetParam();

            while (NextParam())
                // Create empty placeholders
            {
            	Grid(shared_ptr<grid> (new grid(itsScanningMode, itsUVRelativeToGrid, itsProjection, itsBottomLeft, itsTopRight, itsSouthPole, itsOrientation)));
            	Grid()->Data()->Resize(itsNi,itsNj);

            	if (itsDi != kHPMissingFloat && itsDj != kHPMissingFloat)
            	{
            		Grid()->Di(itsDi);
            		Grid()->Dj(itsDj);
            	}
            }
        }
    }

}

void info::Create(shared_ptr<grid> baseGrid)
{

    itsDimensionMatrix = shared_ptr<matrix_t> (new matrix_t(itsTimeIterator->Size(), itsLevelIterator->Size(), itsParamIterator->Size()));
    Reset();

    while (NextTime())
    {
        ResetLevel();

        while (NextLevel())
        {
            ResetParam();

            while (NextParam())
                // Create empty placeholders
            {
            	Grid(shared_ptr<grid> (new grid(*baseGrid)));
            }
        }
    }

}

const producer& info::Producer() const
{
    return itsProducer;
}

void info::Producer(long theFmiProducerId)
{
    itsProducer = producer(theFmiProducerId);
}

void info::Producer(const producer& theProducer)
{
    itsProducer = theProducer;
}

void info::ParamIterator(const param_iter& theParamIterator)
{
    itsParamIterator = shared_ptr<param_iter> (new param_iter(theParamIterator));
}

void info::Params(const vector<param>& theParams)
{
    itsParamIterator = shared_ptr<param_iter> (new param_iter(theParams));
}

void info::LevelIterator(const level_iter& theLevelIterator)
{
    itsLevelIterator = shared_ptr<level_iter> (new level_iter(theLevelIterator));
}

void info::Levels(const vector<level>& theLevels)
{
    itsLevelIterator = shared_ptr<level_iter> (new level_iter(theLevels));
}

void info::TimeIterator(const time_iter& theTimeIterator)
{
    itsTimeIterator = shared_ptr<time_iter> (new time_iter(theTimeIterator));
}

void info::Times(const vector<forecast_time>& theTimes)
{
    itsTimeIterator = shared_ptr<time_iter> (new time_iter(theTimes));
}

raw_time info::OriginDateTime() const
{
    return itsOriginDateTime;
}

void info::OriginDateTime(const string& theOriginDateTime, const string& theTimeMask)
{
    itsOriginDateTime = raw_time(theOriginDateTime, theTimeMask);
}

bool info::Param(const param& theRequestedParam)
{
    return itsParamIterator->Set(theRequestedParam);
}

bool info::NextParam()
{
    return itsParamIterator->Next();
}

void info::ResetParam()
{
    itsParamIterator->Reset();
}

bool info::FirstParam()
{
    return itsParamIterator->First();
}

size_t info::ParamIndex() const
{
    return itsParamIterator->Index();
}

void info::ParamIndex(size_t theParamIndex)
{
    itsParamIterator->Set(theParamIndex);
}

param& info::Param() const
{
    return itsParamIterator->At();
}

size_t info::SizeParams() const
{
	return itsParamIterator->Size();
}

param& info::PeakParam(size_t theIndex) const
{
	return itsParamIterator->At(theIndex);
}

bool info::NextLevel()
{
    return itsLevelIterator->Next();
}

bool info::PreviousLevel()
{
    return itsLevelIterator->Previous();
}

bool info::LastLevel()
{
    return itsLevelIterator->Last();
}

void info::First()
{
    FirstLevel();
    FirstParam();
    FirstTime();
    FirstLocation();
}

void info::Reset()
{
    ResetLevel();
    ResetParam();
    ResetTime();
    ResetLocation();
}

void info::ResetLevel()
{
    itsLevelIterator->Reset();
}

bool info::FirstLevel()
{
    return itsLevelIterator->First();
}

size_t info::LevelIndex() const
{
    return itsLevelIterator->Index();
}

void info::LevelIndex(size_t theLevelIndex)
{
    itsLevelIterator->Set(theLevelIndex);
}

bool info::Level(const level& theLevel)
{
    return itsLevelIterator->Set(theLevel);
}

level& info::Level() const
{
    return itsLevelIterator->At();
}

size_t info::SizeLevels() const
{
	return itsLevelIterator->Size();
}

level& info::PeakLevel(size_t theIndex) const
{
	return itsLevelIterator->At(theIndex);
}

bool info::NextTime()
{
    return itsTimeIterator->Next();
}

bool info::LastTime()
{
    return itsTimeIterator->Last();
}

void info::ResetTime()
{
    itsTimeIterator->Reset();
}

bool info::FirstTime()
{
    return itsTimeIterator->First();
}

bool info::PreviousTime()
{
    return itsTimeIterator->Previous();
}

size_t info::TimeIndex() const
{
    return itsTimeIterator->Index();
}

void info::TimeIndex(size_t theTimeIndex)
{
    itsTimeIterator->Set(theTimeIndex);
}

bool info::Time(const forecast_time& theTime)
{
    return itsTimeIterator->Set(theTime);
}

forecast_time& info::Time() const
{
    return itsTimeIterator->At();
}

size_t info::SizeTimes() const
{
	return itsTimeIterator->Size();
}

forecast_time& info::PeakTime(size_t theIndex) const
{
	return itsTimeIterator->At(theIndex);
}

bool info::NextLocation()
{
    if (itsLocationIndex == kIteratorResetValue)
    {
        itsLocationIndex = 0;    // ResetLocation() has been called before this function
    }

    else
    {
        itsLocationIndex++;
    }

    size_t locationSize = Grid()->Data()->Size();

    if (itsLocationIndex >= locationSize)
    {
        itsLocationIndex = (locationSize == 0) ? 0 : locationSize - 1;

        return false;
    }

    return true;

}

bool info::PreviousLocation()
{

    size_t locationSize = Grid()->Data()->Size();

    if (itsLocationIndex == kIteratorResetValue)
    {
        itsLocationIndex = (locationSize == 0) ? 0 : locationSize - 1;   // ResetLocation() has been called before this function
    }

    else
    {
        if (itsLocationIndex == 0)
        {
            itsLocationIndex = (locationSize == 0) ? 0 : locationSize - 1;
            return false;
        }
        itsLocationIndex--;
    }

    return true;

}

bool info::LastLocation()
{
    itsLocationIndex = Grid()->Data()->Size() - 1;

    return true;
}

void info::ResetLocation()
{
    itsLocationIndex = kIteratorResetValue;
}

bool info::FirstLocation()
{
    ResetLocation();

    return NextLocation();
}

size_t info::LocationIndex() const
{
    return itsLocationIndex;
}

void info::LocationIndex(size_t theLocationIndex)
{
    itsLocationIndex = theLocationIndex;
}

shared_ptr<grid> info::Grid() const
{
    return itsDimensionMatrix->At(TimeIndex(), LevelIndex(), ParamIndex());
}

shared_ptr<grid> info::Grid(size_t timeIndex, size_t levelIndex, size_t paramIndex) const
{
    return itsDimensionMatrix->At(timeIndex, levelIndex, paramIndex);
}

shared_ptr<d_matrix_t> info::Data() const
{
	return Grid()->Data();
}

void info::Data(shared_ptr<matrix_t> m)
{
    itsDimensionMatrix = m;
}

void info::Grid(shared_ptr<grid> d)
{
    itsDimensionMatrix->At(TimeIndex(), LevelIndex(), ParamIndex()) = d;
}

bool info::Value(double theValue)
{
    return Grid()->Data()->Set(itsLocationIndex, theValue) ;
}

double info::Value() const
{
    return Grid()->Data()->At(itsLocationIndex);
}

size_t info::Ni() const
{
    return Grid()->Data()->SizeX();
}

size_t info::Nj() const
{
    return Grid()->Data()->SizeY();
}

double info::Di() const
{
	return Grid()->Di();
}

double info::Dj() const
{
	return Grid()->Dj();
}

bool info::StepSizeOverOneByte() const
{
	return itsStepSizeOverOneByte;
}

void info::StepSizeOverOneByte(bool theStepSizeOverOneByte)
{
	itsStepSizeOverOneByte = theStepSizeOverOneByte;
}
<commit_msg>Better output for cout<commit_after>/*
 * info.cpp
 *
 *  Created on: Nov 22, 2012
 *      Author: partio
 */

#include "info.h"
#include <limits> // for std::numeric_limits<size_t>::max();
#include <boost/lexical_cast.hpp>
#include "plugin_factory.h"
#include "logger_factory.h"

#define HIMAN_AUXILIARY_INCLUDE

#include "neons.h"

#undef HIMAN_AUXILIARY_INCLUDE

using namespace std;
using namespace himan;

info::info()
	: itsLevelIterator(new level_iter())
	, itsTimeIterator(new time_iter())
	, itsParamIterator(new param_iter())
	, itsDimensionMatrix(new matrix_t())
{
    Init();
    itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("info"));

}

info::~info() {}

info::info(const info& other)
	// Iterators are COPIED
	: itsLevelIterator(new level_iter(*other.itsLevelIterator))
	, itsTimeIterator(new time_iter(*other.itsTimeIterator))
	, itsParamIterator(new param_iter(*other.itsParamIterator))
{
	/* START GLOBAL CONFIGURATION OPTIONS */

	itsProjection = other.itsProjection;
	itsOrientation = other.itsOrientation;
	itsScanningMode = other.itsScanningMode;

	itsBottomLeft = other.itsBottomLeft;
	itsTopRight = other.itsTopRight;
	itsSouthPole = other.itsSouthPole;

	itsUVRelativeToGrid = other.itsUVRelativeToGrid;
	itsNi = other.itsNi;
	itsNj = other.itsNj;

	itsDi = other.itsDi;
	itsDj = other.itsDj;

	/* END GLOBAL CONFIGURATION OPTIONS */

	// Data backend is SHARED
	itsDimensionMatrix = other.itsDimensionMatrix;

	itsLocationIndex = other.itsLocationIndex;

	itsProducer = other.itsProducer;

	itsOriginDateTime = other.itsOriginDateTime;

	itsStepSizeOverOneByte = other.itsStepSizeOverOneByte;

	itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("info"));
}

void info::Init()
{

    itsProjection = kUnknownProjection;
    itsScanningMode = kUnknownScanningMode;

//    itsAB = std::vector<double>;

    itsBottomLeft = point(kHPMissingFloat, kHPMissingFloat);
    itsTopRight = point(kHPMissingFloat, kHPMissingFloat);
    itsSouthPole = point(kHPMissingFloat, kHPMissingFloat);

    itsOrientation = kHPMissingFloat;
    itsStepSizeOverOneByte = false;
    itsUVRelativeToGrid = false;

    itsNi = 0;
    itsNj = 0;

    itsDi = kHPMissingFloat;
    itsDj = kHPMissingFloat;
}

std::ostream& info::Write(std::ostream& file) const
{

    file << "<" << ClassName() << " " << Version() << ">" << endl;

    file << itsProducer;

    if (itsParamIterator)
    {
    	file << *itsParamIterator;
    }

    if (itsLevelIterator)
    {
    	file << *itsLevelIterator;
    }

    if (itsTimeIterator)
    {
    	file << *itsTimeIterator;
    }

	for (size_t i = 0; i < itsDimensionMatrix->Size(); i++)
	{
		file << *itsDimensionMatrix->At(i);
	}

    return file;
}

void info::Create()
{
    itsDimensionMatrix = shared_ptr<matrix_t> (new matrix_t(itsTimeIterator->Size(), itsLevelIterator->Size(), itsParamIterator->Size()));
    Reset();

    while (NextTime())
    {
        ResetLevel();

        while (NextLevel())
        {
            ResetParam();

            while (NextParam())
                // Create empty placeholders
            {
            	Grid(shared_ptr<grid> (new grid(itsScanningMode, itsUVRelativeToGrid, itsProjection, itsBottomLeft, itsTopRight, itsSouthPole, itsOrientation)));
            	Grid()->Data()->Resize(itsNi,itsNj);

            	if (itsDi != kHPMissingFloat && itsDj != kHPMissingFloat)
            	{
            		Grid()->Di(itsDi);
            		Grid()->Dj(itsDj);
            	}
            }
        }
    }

}

void info::Create(shared_ptr<grid> baseGrid)
{

    itsDimensionMatrix = shared_ptr<matrix_t> (new matrix_t(itsTimeIterator->Size(), itsLevelIterator->Size(), itsParamIterator->Size()));
    Reset();

    while (NextTime())
    {
        ResetLevel();

        while (NextLevel())
        {
            ResetParam();

            while (NextParam())
                // Create empty placeholders
            {
            	Grid(shared_ptr<grid> (new grid(*baseGrid)));
            }
        }
    }

}

const producer& info::Producer() const
{
    return itsProducer;
}

void info::Producer(long theFmiProducerId)
{
    itsProducer = producer(theFmiProducerId);
}

void info::Producer(const producer& theProducer)
{
    itsProducer = theProducer;
}

void info::ParamIterator(const param_iter& theParamIterator)
{
    itsParamIterator = shared_ptr<param_iter> (new param_iter(theParamIterator));
}

void info::Params(const vector<param>& theParams)
{
    itsParamIterator = shared_ptr<param_iter> (new param_iter(theParams));
}

void info::LevelIterator(const level_iter& theLevelIterator)
{
    itsLevelIterator = shared_ptr<level_iter> (new level_iter(theLevelIterator));
}

void info::Levels(const vector<level>& theLevels)
{
    itsLevelIterator = shared_ptr<level_iter> (new level_iter(theLevels));
}

void info::TimeIterator(const time_iter& theTimeIterator)
{
    itsTimeIterator = shared_ptr<time_iter> (new time_iter(theTimeIterator));
}

void info::Times(const vector<forecast_time>& theTimes)
{
    itsTimeIterator = shared_ptr<time_iter> (new time_iter(theTimes));
}

raw_time info::OriginDateTime() const
{
    return itsOriginDateTime;
}

void info::OriginDateTime(const string& theOriginDateTime, const string& theTimeMask)
{
    itsOriginDateTime = raw_time(theOriginDateTime, theTimeMask);
}

bool info::Param(const param& theRequestedParam)
{
    return itsParamIterator->Set(theRequestedParam);
}

bool info::NextParam()
{
    return itsParamIterator->Next();
}

void info::ResetParam()
{
    itsParamIterator->Reset();
}

bool info::FirstParam()
{
    return itsParamIterator->First();
}

size_t info::ParamIndex() const
{
    return itsParamIterator->Index();
}

void info::ParamIndex(size_t theParamIndex)
{
    itsParamIterator->Set(theParamIndex);
}

param& info::Param() const
{
    return itsParamIterator->At();
}

size_t info::SizeParams() const
{
	return itsParamIterator->Size();
}

param& info::PeakParam(size_t theIndex) const
{
	return itsParamIterator->At(theIndex);
}

bool info::NextLevel()
{
    return itsLevelIterator->Next();
}

bool info::PreviousLevel()
{
    return itsLevelIterator->Previous();
}

bool info::LastLevel()
{
    return itsLevelIterator->Last();
}

void info::First()
{
    FirstLevel();
    FirstParam();
    FirstTime();
    FirstLocation();
}

void info::Reset()
{
    ResetLevel();
    ResetParam();
    ResetTime();
    ResetLocation();
}

void info::ResetLevel()
{
    itsLevelIterator->Reset();
}

bool info::FirstLevel()
{
    return itsLevelIterator->First();
}

size_t info::LevelIndex() const
{
    return itsLevelIterator->Index();
}

void info::LevelIndex(size_t theLevelIndex)
{
    itsLevelIterator->Set(theLevelIndex);
}

bool info::Level(const level& theLevel)
{
    return itsLevelIterator->Set(theLevel);
}

level& info::Level() const
{
    return itsLevelIterator->At();
}

size_t info::SizeLevels() const
{
	return itsLevelIterator->Size();
}

level& info::PeakLevel(size_t theIndex) const
{
	return itsLevelIterator->At(theIndex);
}

bool info::NextTime()
{
    return itsTimeIterator->Next();
}

bool info::LastTime()
{
    return itsTimeIterator->Last();
}

void info::ResetTime()
{
    itsTimeIterator->Reset();
}

bool info::FirstTime()
{
    return itsTimeIterator->First();
}

bool info::PreviousTime()
{
    return itsTimeIterator->Previous();
}

size_t info::TimeIndex() const
{
    return itsTimeIterator->Index();
}

void info::TimeIndex(size_t theTimeIndex)
{
    itsTimeIterator->Set(theTimeIndex);
}

bool info::Time(const forecast_time& theTime)
{
    return itsTimeIterator->Set(theTime);
}

forecast_time& info::Time() const
{
    return itsTimeIterator->At();
}

size_t info::SizeTimes() const
{
	return itsTimeIterator->Size();
}

forecast_time& info::PeakTime(size_t theIndex) const
{
	return itsTimeIterator->At(theIndex);
}

bool info::NextLocation()
{
    if (itsLocationIndex == kIteratorResetValue)
    {
        itsLocationIndex = 0;    // ResetLocation() has been called before this function
    }

    else
    {
        itsLocationIndex++;
    }

    size_t locationSize = Grid()->Data()->Size();

    if (itsLocationIndex >= locationSize)
    {
        itsLocationIndex = (locationSize == 0) ? 0 : locationSize - 1;

        return false;
    }

    return true;

}

bool info::PreviousLocation()
{

    size_t locationSize = Grid()->Data()->Size();

    if (itsLocationIndex == kIteratorResetValue)
    {
        itsLocationIndex = (locationSize == 0) ? 0 : locationSize - 1;   // ResetLocation() has been called before this function
    }

    else
    {
        if (itsLocationIndex == 0)
        {
            itsLocationIndex = (locationSize == 0) ? 0 : locationSize - 1;
            return false;
        }
        itsLocationIndex--;
    }

    return true;

}

bool info::LastLocation()
{
    itsLocationIndex = Grid()->Data()->Size() - 1;

    return true;
}

void info::ResetLocation()
{
    itsLocationIndex = kIteratorResetValue;
}

bool info::FirstLocation()
{
    ResetLocation();

    return NextLocation();
}

size_t info::LocationIndex() const
{
    return itsLocationIndex;
}

void info::LocationIndex(size_t theLocationIndex)
{
    itsLocationIndex = theLocationIndex;
}

shared_ptr<grid> info::Grid() const
{
    return itsDimensionMatrix->At(TimeIndex(), LevelIndex(), ParamIndex());
}

shared_ptr<grid> info::Grid(size_t timeIndex, size_t levelIndex, size_t paramIndex) const
{
    return itsDimensionMatrix->At(timeIndex, levelIndex, paramIndex);
}

shared_ptr<d_matrix_t> info::Data() const
{
	return Grid()->Data();
}

void info::Data(shared_ptr<matrix_t> m)
{
    itsDimensionMatrix = m;
}

void info::Grid(shared_ptr<grid> d)
{
    itsDimensionMatrix->At(TimeIndex(), LevelIndex(), ParamIndex()) = d;
}

bool info::Value(double theValue)
{
    return Grid()->Data()->Set(itsLocationIndex, theValue) ;
}

double info::Value() const
{
    return Grid()->Data()->At(itsLocationIndex);
}

size_t info::Ni() const
{
    return Grid()->Data()->SizeX();
}

size_t info::Nj() const
{
    return Grid()->Data()->SizeY();
}

double info::Di() const
{
	return Grid()->Di();
}

double info::Dj() const
{
	return Grid()->Dj();
}

bool info::StepSizeOverOneByte() const
{
	return itsStepSizeOverOneByte;
}

void info::StepSizeOverOneByte(bool theStepSizeOverOneByte)
{
	itsStepSizeOverOneByte = theStepSizeOverOneByte;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: inputsequencechecker_th.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: er $ $Date: 2002-03-26 17:07:06 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <inputsequencechecker_th.hxx>
#include <wtt.h>

using namespace rtl;

namespace com { namespace sun { namespace star { namespace i18n {

InputSequenceChecker_th::InputSequenceChecker_th()
{
    serviceName = "com.sun.star.i18n.InputSequenceChecker_th";
}

InputSequenceChecker_th::~InputSequenceChecker_th()
{
}

/* Table for Thai Cell Manipulation */
sal_Char _TAC_celltype_inputcheck[17][17] = {
/* Cn */ /*  0,   1,   2,   3,   4,   5,   6,   7,   8,   9,   A,   B,   C,   D,   E,   F       */
/* Cn-1 00 */   'X', 'A', 'A', 'A', 'A', 'A', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* 10 */   'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* 20 */   'X', 'A', 'A', 'A', 'A', 'S', 'A', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C',
     /* 30 */   'X', 'S', 'A', 'S', 'S', 'S', 'S', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* 40 */   'X', 'S', 'A', 'S', 'A', 'S', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* 50 */   'X', 'A', 'A', 'A', 'A', 'S', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* 60 */   'X', 'A', 'A', 'A', 'S', 'A', 'S', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* 70 */   'X', 'A', 'A', 'A', 'A', 'S', 'A', 'R', 'R', 'R', 'C', 'C', 'R', 'R', 'R', 'R', 'R',
     /* 80 */   'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'C', 'R', 'R', 'R', 'R', 'R', 'R',
     /* 90 */   'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* A0 */   'X', 'A', 'A', 'A', 'A', 'A', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* B0 */   'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* C0 */   'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* D0 */   'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* E0 */   'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'C', 'C', 'R', 'R', 'R', 'R', 'R',
     /* F0 */   'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'C', 'R', 'R', 'R', 'R', 'R', 'R',
        'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'C', 'R', 'C', 'R', 'R', 'R', 'R'
};

sal_Bool _TAC_Composible[3][5] = {
        /*  'A',    'C',        'S',        'R',        'X'   */
/* Mode 0 */    {sal_True,  sal_True,   sal_True,   sal_True,   sal_True}, // PASSTHROUGH = 0
/* Mode 1 */    {sal_True,  sal_True,   sal_True,   sal_False,      sal_True}, // BASIC = 1
/* Mode 2 */    {sal_True,  sal_True,   sal_False,      sal_False,      sal_True}  // STRICT = 2
};

sal_Bool SAL_CALL
InputSequenceChecker_th::checkInputSequence(const OUString& Text, sal_Int32 nStartPos,
    sal_Unicode inputChar, sal_Int16 inputCheckMode) throw(com::sun::star::uno::RuntimeException)
{
    sal_Int16  composible_class;
    sal_Unicode currentChar = Text[nStartPos];
    switch (_TAC_celltype_inputcheck[getCharType(currentChar)][getCharType(inputChar)]) {
        case 'A': composible_class = 0; break;
        case 'C': composible_class = 1; break;
        case 'S': composible_class = 2; break;
        case 'R': composible_class = 3; break;
        case 'X': composible_class = 4; break;
        default:  composible_class = 0;
    }
    return (_TAC_Composible[inputCheckMode][composible_class]);
}

} } } }
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.244); FILE MERGED 2005/09/05 17:47:45 rt 1.2.244.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: inputsequencechecker_th.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 17:17:48 $
 *
 *  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
 *
 ************************************************************************/

#include <inputsequencechecker_th.hxx>
#include <wtt.h>

using namespace rtl;

namespace com { namespace sun { namespace star { namespace i18n {

InputSequenceChecker_th::InputSequenceChecker_th()
{
    serviceName = "com.sun.star.i18n.InputSequenceChecker_th";
}

InputSequenceChecker_th::~InputSequenceChecker_th()
{
}

/* Table for Thai Cell Manipulation */
sal_Char _TAC_celltype_inputcheck[17][17] = {
/* Cn */ /*  0,   1,   2,   3,   4,   5,   6,   7,   8,   9,   A,   B,   C,   D,   E,   F       */
/* Cn-1 00 */   'X', 'A', 'A', 'A', 'A', 'A', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* 10 */   'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* 20 */   'X', 'A', 'A', 'A', 'A', 'S', 'A', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C',
     /* 30 */   'X', 'S', 'A', 'S', 'S', 'S', 'S', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* 40 */   'X', 'S', 'A', 'S', 'A', 'S', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* 50 */   'X', 'A', 'A', 'A', 'A', 'S', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* 60 */   'X', 'A', 'A', 'A', 'S', 'A', 'S', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* 70 */   'X', 'A', 'A', 'A', 'A', 'S', 'A', 'R', 'R', 'R', 'C', 'C', 'R', 'R', 'R', 'R', 'R',
     /* 80 */   'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'C', 'R', 'R', 'R', 'R', 'R', 'R',
     /* 90 */   'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* A0 */   'X', 'A', 'A', 'A', 'A', 'A', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* B0 */   'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* C0 */   'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* D0 */   'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R',
     /* E0 */   'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'C', 'C', 'R', 'R', 'R', 'R', 'R',
     /* F0 */   'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'C', 'R', 'R', 'R', 'R', 'R', 'R',
        'X', 'A', 'A', 'A', 'S', 'S', 'A', 'R', 'R', 'R', 'C', 'R', 'C', 'R', 'R', 'R', 'R'
};

sal_Bool _TAC_Composible[3][5] = {
        /*  'A',    'C',        'S',        'R',        'X'   */
/* Mode 0 */    {sal_True,  sal_True,   sal_True,   sal_True,   sal_True}, // PASSTHROUGH = 0
/* Mode 1 */    {sal_True,  sal_True,   sal_True,   sal_False,      sal_True}, // BASIC = 1
/* Mode 2 */    {sal_True,  sal_True,   sal_False,      sal_False,      sal_True}  // STRICT = 2
};

sal_Bool SAL_CALL
InputSequenceChecker_th::checkInputSequence(const OUString& Text, sal_Int32 nStartPos,
    sal_Unicode inputChar, sal_Int16 inputCheckMode) throw(com::sun::star::uno::RuntimeException)
{
    sal_Int16  composible_class;
    sal_Unicode currentChar = Text[nStartPos];
    switch (_TAC_celltype_inputcheck[getCharType(currentChar)][getCharType(inputChar)]) {
        case 'A': composible_class = 0; break;
        case 'C': composible_class = 1; break;
        case 'S': composible_class = 2; break;
        case 'R': composible_class = 3; break;
        case 'X': composible_class = 4; break;
        default:  composible_class = 0;
    }
    return (_TAC_Composible[inputCheckMode][composible_class]);
}

} } } }
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Cloudius Systems, Ltd.
 */

#ifndef FILE_DESC_HH_
#define FILE_DESC_HH_

#include "sstring.hh"
#include <sys/types.h>
#include <unistd.h>
#include <assert.h>
#include <utility>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/eventfd.h>
#include <sys/timerfd.h>
#include <sys/signalfd.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <signal.h>
#include <system_error>
#include <boost/optional.hpp>
#include <pthread.h>

inline void throw_system_error_on(bool condition);

template <typename T>
inline void throw_kernel_error(T r);

class file_desc {
    int _fd;
public:
    file_desc() = delete;
    file_desc(const file_desc&) = delete;
    file_desc(file_desc&& x) : _fd(x._fd) { x._fd = -1; }
    ~file_desc() { if (_fd != -1) { ::close(_fd); } }
    void operator=(const file_desc&) = delete;
    file_desc& operator=(file_desc&& x) {
        if (this != &x) {
            std::swap(_fd, x._fd);
            if (x._fd != -1) {
                x.close();
            }
        }
        return *this;
    }
    void close() {
        assert(_fd != -1);
        auto r = ::close(_fd);
        throw_system_error_on(r == -1);
        _fd = -1;
    }
    int get() const { return _fd; }
    static file_desc open(sstring name, int flags, mode_t mode = 0) {
        int fd = ::open(name.c_str(), flags, mode);
        throw_system_error_on(fd == -1);
        return file_desc(fd);
    }
    static file_desc socket(int family, int type, int protocol = 0) {
        int fd = ::socket(family, type, protocol);
        throw_system_error_on(fd == -1);
        return file_desc(fd);
    }
    static file_desc eventfd(unsigned initval, int flags) {
        int fd = ::eventfd(initval, flags);
        throw_system_error_on(fd == -1);
        return file_desc(fd);
    }
    static file_desc epoll_create(int flags = 0) {
        int fd = ::epoll_create1(flags);
        throw_system_error_on(fd == -1);
        return file_desc(fd);
    }
    static file_desc timerfd_create(int clockid, int flags) {
        int fd = ::timerfd_create(clockid, flags);
        throw_system_error_on(fd == -1);
        return file_desc(fd);
    }
    static file_desc signalfd(const sigset_t& mask, int flags) {
        int fd = ::signalfd(-1, &mask, flags);
        throw_system_error_on(fd == -1);
        return file_desc(fd);
    }
    file_desc dup() const {
        int fd = ::dup(get());
        throw_system_error_on(fd == -1);
        return file_desc(fd);
    }
    file_desc accept(sockaddr& sa, socklen_t& sl, int flags = 0) {
        auto ret = ::accept4(_fd, &sa, &sl, flags);
        throw_system_error_on(ret == -1);
        return file_desc(ret);
    }
    int ioctl(int request) {
        return ioctl(request, 0);
    }
    int ioctl(int request, int value) {
        int r = ::ioctl(_fd, request, value);
        throw_system_error_on(r == -1);
        return r;
    }
    int ioctl(int request, unsigned int value) {
        int r = ::ioctl(_fd, request, value);
        throw_system_error_on(r == -1);
        return r;
    }
    template <class X>
    int ioctl(int request, X& data) {
        int r = ::ioctl(_fd, request, &data);
        throw_system_error_on(r == -1);
        return r;
    }
    template <class X>
    int ioctl(int request, X&& data) {
        int r = ::ioctl(_fd, request, &data);
        throw_system_error_on(r == -1);
        return r;
    }
    template <class X>
    int setsockopt(int level, int optname, X& data) {
        int r = ::setsockopt(_fd, level, optname, &data, sizeof(data));
        throw_system_error_on(r == -1);
        return r;
    }
    int setsockopt(int level, int optname, const char* data) {
        int r = ::setsockopt(_fd, level, optname, data, strlen(data) + 1);
        throw_system_error_on(r == -1);
        return r;
    }
    boost::optional<size_t> read(void* buffer, size_t len) {
        auto r = ::read(_fd, buffer, len);
        if (r == -1 && errno == EAGAIN) {
            return {};
        }
        throw_system_error_on(r == -1);
        return { size_t(r) };
    }
    boost::optional<ssize_t> recv(void* buffer, size_t len, int flags) {
        auto r = ::recv(_fd, buffer, len, flags);
        if (r == -1 && errno == EAGAIN) {
            return {};
        }
        throw_system_error_on(r == -1);
        return { r };
    }
    boost::optional<size_t> recvmsg(msghdr* mh, int flags) {
        auto r = ::recvmsg(_fd, mh, flags);
        if (r == -1 && errno == EAGAIN) {
            return {};
        }
        throw_system_error_on(r == -1);
        return { size_t(r) };
    }
    boost::optional<size_t> send(const void* buffer, size_t len, int flags) {
        auto r = ::send(_fd, buffer, len, flags);
        if (r == -1 && errno == EAGAIN) {
            return {};
        }
        throw_system_error_on(r == -1);
        return { size_t(r) };
    }
    void bind(sockaddr& sa, socklen_t sl) {
        auto r = ::bind(_fd, &sa, sl);
        throw_system_error_on(r == -1);
    }
    void listen(int backlog) {
        auto fd = ::listen(_fd, backlog);
        throw_system_error_on(fd == -1);
    }
    boost::optional<size_t> write(const void* buf, size_t len) {
        auto r = ::write(_fd, buf, len);
        if (r == -1 && errno == EAGAIN) {
            return {};
        }
        throw_system_error_on(r == -1);
        return { size_t(r) };
    }
    void timerfd_settime(int flags, const itimerspec& its) {
        auto r = ::timerfd_settime(_fd, flags, &its, NULL);
        throw_system_error_on(r == -1);
    }
private:
    file_desc(int fd) : _fd(fd) {}
 };

class posix_thread {
    std::function<void ()> _func;
    pthread_t _pthread;
private:
    static void* start_routine(void* arg) {
        auto zis = reinterpret_cast<posix_thread*>(arg);
        zis->_func();
        return nullptr;
    }
public:
    posix_thread(std::function<void ()> func) : _func(func) {
        auto r = pthread_create(&_pthread, nullptr,
                    &posix_thread::start_routine, this);
        if (r) {
            throw std::system_error(r, std::system_category());
        }
    }
    void join() {
        pthread_join(_pthread, NULL);
    }
};

inline
void throw_system_error_on(bool condition) {
    if (condition) {
        throw std::system_error(errno, std::system_category());
    }
}

template <typename T>
inline
void throw_kernel_error(T r) {
    static_assert(std::is_signed<T>::value, "kernel error variables must be signed");
    if (r < 0) {
        throw std::system_error(-r, std::system_category());
    }
}

inline
sigset_t make_sigset_mask(int signo) {
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, signo);
    return set;
}

#endif /* FILE_DESC_HH_ */
<commit_msg>posix: support std::move()ing a posix_thread<commit_after>/*
 * Copyright (C) 2014 Cloudius Systems, Ltd.
 */

#ifndef FILE_DESC_HH_
#define FILE_DESC_HH_

#include "sstring.hh"
#include <sys/types.h>
#include <unistd.h>
#include <assert.h>
#include <utility>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/eventfd.h>
#include <sys/timerfd.h>
#include <sys/signalfd.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <signal.h>
#include <system_error>
#include <boost/optional.hpp>
#include <pthread.h>
#include <memory>

inline void throw_system_error_on(bool condition);

template <typename T>
inline void throw_kernel_error(T r);

class file_desc {
    int _fd;
public:
    file_desc() = delete;
    file_desc(const file_desc&) = delete;
    file_desc(file_desc&& x) : _fd(x._fd) { x._fd = -1; }
    ~file_desc() { if (_fd != -1) { ::close(_fd); } }
    void operator=(const file_desc&) = delete;
    file_desc& operator=(file_desc&& x) {
        if (this != &x) {
            std::swap(_fd, x._fd);
            if (x._fd != -1) {
                x.close();
            }
        }
        return *this;
    }
    void close() {
        assert(_fd != -1);
        auto r = ::close(_fd);
        throw_system_error_on(r == -1);
        _fd = -1;
    }
    int get() const { return _fd; }
    static file_desc open(sstring name, int flags, mode_t mode = 0) {
        int fd = ::open(name.c_str(), flags, mode);
        throw_system_error_on(fd == -1);
        return file_desc(fd);
    }
    static file_desc socket(int family, int type, int protocol = 0) {
        int fd = ::socket(family, type, protocol);
        throw_system_error_on(fd == -1);
        return file_desc(fd);
    }
    static file_desc eventfd(unsigned initval, int flags) {
        int fd = ::eventfd(initval, flags);
        throw_system_error_on(fd == -1);
        return file_desc(fd);
    }
    static file_desc epoll_create(int flags = 0) {
        int fd = ::epoll_create1(flags);
        throw_system_error_on(fd == -1);
        return file_desc(fd);
    }
    static file_desc timerfd_create(int clockid, int flags) {
        int fd = ::timerfd_create(clockid, flags);
        throw_system_error_on(fd == -1);
        return file_desc(fd);
    }
    static file_desc signalfd(const sigset_t& mask, int flags) {
        int fd = ::signalfd(-1, &mask, flags);
        throw_system_error_on(fd == -1);
        return file_desc(fd);
    }
    file_desc dup() const {
        int fd = ::dup(get());
        throw_system_error_on(fd == -1);
        return file_desc(fd);
    }
    file_desc accept(sockaddr& sa, socklen_t& sl, int flags = 0) {
        auto ret = ::accept4(_fd, &sa, &sl, flags);
        throw_system_error_on(ret == -1);
        return file_desc(ret);
    }
    int ioctl(int request) {
        return ioctl(request, 0);
    }
    int ioctl(int request, int value) {
        int r = ::ioctl(_fd, request, value);
        throw_system_error_on(r == -1);
        return r;
    }
    int ioctl(int request, unsigned int value) {
        int r = ::ioctl(_fd, request, value);
        throw_system_error_on(r == -1);
        return r;
    }
    template <class X>
    int ioctl(int request, X& data) {
        int r = ::ioctl(_fd, request, &data);
        throw_system_error_on(r == -1);
        return r;
    }
    template <class X>
    int ioctl(int request, X&& data) {
        int r = ::ioctl(_fd, request, &data);
        throw_system_error_on(r == -1);
        return r;
    }
    template <class X>
    int setsockopt(int level, int optname, X& data) {
        int r = ::setsockopt(_fd, level, optname, &data, sizeof(data));
        throw_system_error_on(r == -1);
        return r;
    }
    int setsockopt(int level, int optname, const char* data) {
        int r = ::setsockopt(_fd, level, optname, data, strlen(data) + 1);
        throw_system_error_on(r == -1);
        return r;
    }
    boost::optional<size_t> read(void* buffer, size_t len) {
        auto r = ::read(_fd, buffer, len);
        if (r == -1 && errno == EAGAIN) {
            return {};
        }
        throw_system_error_on(r == -1);
        return { size_t(r) };
    }
    boost::optional<ssize_t> recv(void* buffer, size_t len, int flags) {
        auto r = ::recv(_fd, buffer, len, flags);
        if (r == -1 && errno == EAGAIN) {
            return {};
        }
        throw_system_error_on(r == -1);
        return { r };
    }
    boost::optional<size_t> recvmsg(msghdr* mh, int flags) {
        auto r = ::recvmsg(_fd, mh, flags);
        if (r == -1 && errno == EAGAIN) {
            return {};
        }
        throw_system_error_on(r == -1);
        return { size_t(r) };
    }
    boost::optional<size_t> send(const void* buffer, size_t len, int flags) {
        auto r = ::send(_fd, buffer, len, flags);
        if (r == -1 && errno == EAGAIN) {
            return {};
        }
        throw_system_error_on(r == -1);
        return { size_t(r) };
    }
    void bind(sockaddr& sa, socklen_t sl) {
        auto r = ::bind(_fd, &sa, sl);
        throw_system_error_on(r == -1);
    }
    void listen(int backlog) {
        auto fd = ::listen(_fd, backlog);
        throw_system_error_on(fd == -1);
    }
    boost::optional<size_t> write(const void* buf, size_t len) {
        auto r = ::write(_fd, buf, len);
        if (r == -1 && errno == EAGAIN) {
            return {};
        }
        throw_system_error_on(r == -1);
        return { size_t(r) };
    }
    void timerfd_settime(int flags, const itimerspec& its) {
        auto r = ::timerfd_settime(_fd, flags, &its, NULL);
        throw_system_error_on(r == -1);
    }
private:
    file_desc(int fd) : _fd(fd) {}
 };

class posix_thread {
    // must allocate, since this class is moveable
    std::unique_ptr<std::function<void ()>> _func;
    pthread_t _pthread;
    bool _valid = true;
private:
    static void* start_routine(void* arg) {
        auto pfunc = reinterpret_cast<std::function<void ()>*>(arg);
        (*pfunc)();
        return nullptr;
    }
public:
    posix_thread(std::function<void ()> func) : _func(std::make_unique<std::function<void ()>>(std::move(func))) {
        auto r = pthread_create(&_pthread, nullptr,
                    &posix_thread::start_routine, _func.get());
        if (r) {
            throw std::system_error(r, std::system_category());
        }
    }
    posix_thread(posix_thread&& x)
        : _func(std::move(x._func)), _pthread(x._pthread), _valid(x._valid) {
        x._valid = false;
    }
    ~posix_thread() {
        assert(!_valid);
    }
    void join() {
        assert(_valid);
        pthread_join(_pthread, NULL);
        _valid = false;
    }
};

inline
void throw_system_error_on(bool condition) {
    if (condition) {
        throw std::system_error(errno, std::system_category());
    }
}

template <typename T>
inline
void throw_kernel_error(T r) {
    static_assert(std::is_signed<T>::value, "kernel error variables must be signed");
    if (r < 0) {
        throw std::system_error(-r, std::system_category());
    }
}

inline
sigset_t make_sigset_mask(int signo) {
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, signo);
    return set;
}

#endif /* FILE_DESC_HH_ */
<|endoftext|>


<commit_before>#pragma once

#include "EigenTools.hpp"

typedef struct
{
	double R[9];							// Rotation
	double t[3];							// Translation
	double f;								// Focal length
	double init_f;							// Initial focal length from EXIF
	double k[2];							// Undistortion parameters
	double k_inv[6];		// Inverse undistortion parameters
} camera_params_t;

struct ECamera
{
	ECamera()
		: m_focal_length(0.0)
		, m_R(Mat3::Identity())
		, m_t(Vec3::Zero())
		, m_k(Vec2::Zero())
	{}

	double	m_focal_length;		// Focal length in pixels
	Mat3	m_R;
	Vec3	m_t;
	Vec2	m_k;				// Undistortion parameters

	Mat3 GetIntrinsics() const;

	EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
};

Vec2 SfmProjectFinal(const Vec3 &p, const ECamera &cam);

Vec2 SfmProjectRD(const Vec3 &p, const ECamera &cam);

#include "vector.h"
#include "matrix.h"

// Refine the position of a single camera
void RefineCamera(int num_points, v3_t *points, v2_t *projs, camera_params_t *camera, bool adjust_focal);
<commit_msg>minor formatting<commit_after>#pragma once

#include "EigenTools.hpp"

typedef struct
{
	double R[9];		// Rotation
	double t[3];		// Translation
	double f;			// Focal length
	double init_f;		// Initial focal length from EXIF
	double k[2];		// Undistortion parameters
	double k_inv[6];	// Inverse undistortion parameters
} camera_params_t;

struct ECamera
{
	ECamera()
		: m_focal_length(0.0)
		, m_R(Mat3::Identity())
		, m_t(Vec3::Zero())
		, m_k(Vec2::Zero())
	{}

	double	m_focal_length;		// Focal length in pixels
	Mat3	m_R;
	Vec3	m_t;
	Vec2	m_k;				// Undistortion parameters

	Mat3 GetIntrinsics() const;

	EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
};

Vec2 SfmProjectFinal(const Vec3 &p, const ECamera &cam);

Vec2 SfmProjectRD(const Vec3 &p, const ECamera &cam);

#include "vector.h"
#include "matrix.h"

// Refine the position of a single camera
void RefineCamera(int num_points, v3_t *points, v2_t *projs, camera_params_t *camera, bool adjust_focal);
<|endoftext|>


<commit_before>#include "dreal/contractor/contractor_status.h"

#include <utility>

#include "dreal/util/assert.h"

using std::move;
using std::unordered_set;
using std::vector;

namespace dreal {

ContractorStatus::ContractorStatus(Box box, const int branching_point)
    : box_{move(box)},
      branching_point_{branching_point},
      output_{ibex::BitSet::empty(box_.size())} {
  DREAL_ASSERT(box_.size() > 0);
  DREAL_ASSERT(branching_point_ >= -1 && branching_point_ < box_.size());
}

const Box& ContractorStatus::box() const { return box_; }

Box& ContractorStatus::mutable_box() { return box_; }

int ContractorStatus::branching_point() const { return branching_point_; }

int& ContractorStatus::mutable_branching_point() { return branching_point_; }

const ibex::BitSet& ContractorStatus::output() const { return output_; }

ibex::BitSet& ContractorStatus::mutable_output() { return output_; }

void ContractorStatus::AddUsedConstraint(const Formula& f) {
  if (box_.empty()) {
    unsat_witness_.insert(f);
  } else {
    used_constraints_.insert(f);
  }
}

void ContractorStatus::AddUsedConstraint(const vector<Formula>& formulas) {
  if (box_.empty()) {
    unsat_witness_.insert(formulas.begin(), formulas.end());
  } else {
    used_constraints_.insert(formulas.begin(), formulas.end());
  }
}

unordered_set<Formula, hash_value<Formula>> GenerateExplanation(
    unordered_set<Formula, hash_value<Formula>> explanation,
    const unordered_set<Formula, hash_value<Formula>>& used_constraints) {
  bool keep_going = true;
  while (keep_going) {
    keep_going = false;
    for (const Formula& f_i : explanation) {
      const Variables variables_in_f_i{f_i.GetFreeVariables()};
      for (const Formula& f_j : used_constraints) {
        if (explanation.count(f_j) > 0) {
          continue;
        }
        if (HaveIntersection(variables_in_f_i, f_j.GetFreeVariables())) {
          explanation.insert(f_j);
          keep_going = true;
        }
      }
    }
  }
  return explanation;
}

unordered_set<Formula, hash_value<Formula>> ContractorStatus::Explanation()
    const {
  DREAL_ASSERT(!unsat_witness_.empty());
  return GenerateExplanation(unsat_witness_, used_constraints_);
}

ContractorStatus& ContractorStatus::InplaceJoin(
    const ContractorStatus& contractor_status) {
  box_.InplaceUnion(contractor_status.box());
  output_ |= contractor_status.output();
  used_constraints_.insert(contractor_status.used_constraints_.begin(),
                           contractor_status.used_constraints_.end());
  return *this;
}

ContractorStatus Join(ContractorStatus contractor_status1,
                      const ContractorStatus& contractor_status2) {
  // This function updates `contractor_status1`, which is passed by value, and
  // returns it.
  return contractor_status1.InplaceJoin(contractor_status2);
}

}  // namespace dreal
<commit_msg>fix(contractor/contractor_status): Handle unsat_witness_ in InplaceJoin<commit_after>#include "dreal/contractor/contractor_status.h"

#include <utility>

#include "dreal/util/assert.h"

using std::move;
using std::unordered_set;
using std::vector;

namespace dreal {

ContractorStatus::ContractorStatus(Box box, const int branching_point)
    : box_{move(box)},
      branching_point_{branching_point},
      output_{ibex::BitSet::empty(box_.size())} {
  DREAL_ASSERT(box_.size() > 0);
  DREAL_ASSERT(branching_point_ >= -1 && branching_point_ < box_.size());
}

const Box& ContractorStatus::box() const { return box_; }

Box& ContractorStatus::mutable_box() { return box_; }

int ContractorStatus::branching_point() const { return branching_point_; }

int& ContractorStatus::mutable_branching_point() { return branching_point_; }

const ibex::BitSet& ContractorStatus::output() const { return output_; }

ibex::BitSet& ContractorStatus::mutable_output() { return output_; }

void ContractorStatus::AddUsedConstraint(const Formula& f) {
  if (box_.empty()) {
    unsat_witness_.insert(f);
  } else {
    used_constraints_.insert(f);
  }
}

void ContractorStatus::AddUsedConstraint(const vector<Formula>& formulas) {
  if (box_.empty()) {
    unsat_witness_.insert(formulas.begin(), formulas.end());
  } else {
    used_constraints_.insert(formulas.begin(), formulas.end());
  }
}

unordered_set<Formula, hash_value<Formula>> GenerateExplanation(
    unordered_set<Formula, hash_value<Formula>> explanation,
    const unordered_set<Formula, hash_value<Formula>>& used_constraints) {
  bool keep_going = true;
  while (keep_going) {
    keep_going = false;
    for (const Formula& f_i : explanation) {
      const Variables variables_in_f_i{f_i.GetFreeVariables()};
      for (const Formula& f_j : used_constraints) {
        if (explanation.count(f_j) > 0) {
          continue;
        }
        if (HaveIntersection(variables_in_f_i, f_j.GetFreeVariables())) {
          explanation.insert(f_j);
          keep_going = true;
        }
      }
    }
  }
  return explanation;
}

unordered_set<Formula, hash_value<Formula>> ContractorStatus::Explanation()
    const {
  DREAL_ASSERT(!unsat_witness_.empty());
  return GenerateExplanation(unsat_witness_, used_constraints_);
}

ContractorStatus& ContractorStatus::InplaceJoin(
    const ContractorStatus& contractor_status) {
  box_.InplaceUnion(contractor_status.box());
  output_ |= contractor_status.output();
  unsat_witness_.insert(contractor_status.unsat_witness_.begin(),
                        contractor_status.unsat_witness_.end());
  used_constraints_.insert(contractor_status.used_constraints_.begin(),
                           contractor_status.used_constraints_.end());
  return *this;
}

ContractorStatus Join(ContractorStatus contractor_status1,
                      const ContractorStatus& contractor_status2) {
  // This function updates `contractor_status1`, which is passed by value, and
  // returns it.
  return contractor_status1.InplaceJoin(contractor_status2);
}

}  // namespace dreal
<|endoftext|>


<commit_before>/*
 * This file is part of `et engine`
 * Copyright 2009-2014 by Sergey Reznik
 * Please, do not modify content without approval.
 *
 */

#include <et/core/et.h>

#if (ET_PLATFORM_WIN)

#define PASS_TO_OUTPUTS(FUNC)		for (Output::Pointer output : logOutputs) \
									{ \
										va_list args; \
										va_start(args, format); \
										output->FUNC(format, args); \
										va_end(args); \
									}

using namespace et;
using namespace log;

static std::vector<Output::Pointer> logOutputs;

void et::log::addOutput(Output::Pointer ptr)
{
	logOutputs.push_back(ptr);
}

void et::log::removeOutput(Output::Pointer ptr)
{
	logOutputs.erase(std::remove_if(logOutputs.begin(), logOutputs.end(),
		[ptr](Output::Pointer out) { return out == ptr; }), logOutputs.end());
}

void et::log::debug(const char* format, ...) { PASS_TO_OUTPUTS(debug) }
void et::log::info(const char* format, ...) { PASS_TO_OUTPUTS(info) }
void et::log::warning(const char* format, ...) { PASS_TO_OUTPUTS(warning) }
void et::log::error(const char* format, ...) { PASS_TO_OUTPUTS(error) }

ConsoleOutput::ConsoleOutput() :
	FileOutput(stdout)
{
}

void ConsoleOutput::debug(const char* fmt, va_list args)
{
	FileOutput::debug(fmt, args);
}

void ConsoleOutput::info(const char* fmt, va_list args)
{
	FileOutput::info(fmt, args);
}

void ConsoleOutput::warning(const char* fmt, va_list args)
{
	FileOutput::warning(fmt, args);
}

void ConsoleOutput::error(const char* fmt, va_list args)
{
	FileOutput::error(fmt, args);
}

FileOutput::FileOutput(FILE* file) : _file(file)
{
	if (file == nullptr)
	{
		_file = stdout;
		fprintf(_file, "Invalid file was provided to FileOutput, output will be redirected to console.");
	}
}

FileOutput::FileOutput(const std::string& filename)
{
	_file = fopen(filename.c_str(), "w");
	if (_file == nullptr)
	{
		printf("Unable to open %s for writing, output will be redirected to console.", filename.c_str());
		_file = stdout;
	}
}

FileOutput::~FileOutput()
{
	if ((_file != nullptr) && (_file != stdout))
	{
		fflush(_file);
		fclose(_file);
	}
}

void FileOutput::debug(const char* format, va_list args)
{
#if (ET_DEBUG)
	info(format, args);
#endif
}

void FileOutput::info(const char* format, va_list args)
{
	vfprintf(_file, format, args);
	fprintf(_file, "\n");
	fflush(_file);
}

void FileOutput::warning(const char* format, va_list args)
{
	fprintf(_file, "WARNING: ");
	info(format, args);
}

void FileOutput::error(const char* format, va_list args)
{
	fprintf(_file, "ERROR: ");
	info(format, args);
}

#endif // ET_PLATFORM_WIN
<commit_msg>ConsoleOutput in Windows now uses OutputDebugString<commit_after>/*
 * This file is part of `et engine`
 * Copyright 2009-2014 by Sergey Reznik
 * Please, do not modify content without approval.
 *
 */

#include <et/core/et.h>

#if (ET_PLATFORM_WIN)

#define PASS_TO_OUTPUTS(FUNC)		for (Output::Pointer output : logOutputs) \
									{ \
										va_list args; \
										va_start(args, format); \
										output->FUNC(format, args); \
										va_end(args); \
									}

using namespace et;
using namespace log;

static std::vector<Output::Pointer> logOutputs;

void et::log::addOutput(Output::Pointer ptr)
{
	logOutputs.push_back(ptr);
}

void et::log::removeOutput(Output::Pointer ptr)
{
	logOutputs.erase(std::remove_if(logOutputs.begin(), logOutputs.end(),
		[ptr](Output::Pointer out) { return out == ptr; }), logOutputs.end());
}

void et::log::debug(const char* format, ...) { PASS_TO_OUTPUTS(debug) }
void et::log::info(const char* format, ...) { PASS_TO_OUTPUTS(info) }
void et::log::warning(const char* format, ...) { PASS_TO_OUTPUTS(warning) }
void et::log::error(const char* format, ...) { PASS_TO_OUTPUTS(error) }

ConsoleOutput::ConsoleOutput() :
	FileOutput(stdout)
{
}

void ConsoleOutput::debug(const char* format, va_list args)
{
#if (ET_DEBUG)
	info(format, args);
#endif
}

void ConsoleOutput::info(const char* format, va_list args)
{
	static char storage[2048] = {};
	int pos = vsnprintf(storage, 2048, format, args);
	storage[pos++] = '\n';
	storage[pos++] = 0;
	OutputDebugString(storage);
}

void ConsoleOutput::warning(const char* fmt, va_list args)
{
	OutputDebugString("WARNING: ");
	info(fmt, args);
}

void ConsoleOutput::error(const char* fmt, va_list args)
{
	OutputDebugString("ERROR: ");
	info(fmt, args);
}

FileOutput::FileOutput(FILE* file) :
	_file(file)
{
	if (file == nullptr)
	{
		_file = stdout;
		fprintf(_file, "Invalid file was provided to FileOutput, output will be redirected to console.");
	}
}

FileOutput::FileOutput(const std::string& filename)
{
	_file = fopen(filename.c_str(), "w");
	if (_file == nullptr)
	{
		printf("Unable to open %s for writing, output will be redirected to console.", filename.c_str());
		_file = stdout;
	}
}

FileOutput::~FileOutput()
{
	if ((_file != nullptr) && (_file != stdout))
	{
		fflush(_file);
		fclose(_file);
	}
}

void FileOutput::debug(const char* format, va_list args)
{
#if (ET_DEBUG)
	info(format, args);
#endif
}

void FileOutput::info(const char* format, va_list args)
{
	fprintf(_file, format, args);
	fprintf(_file, "\n");
	fflush(_file);
}

void FileOutput::warning(const char* format, va_list args)
{
	fprintf(_file, "WARNING: ");
	info(format, args);
}

void FileOutput::error(const char* format, va_list args)
{
	fprintf(_file, "ERROR: ");
	info(format, args);
}

#endif // ET_PLATFORM_WIN
<|endoftext|>


<commit_before><commit_msg>Suppress gcc9 warnings in THStack (#3925)<commit_after><|endoftext|>