<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------

#include "platform/platform.h"
#include "T3D/physics/physx3/px3Collision.h"

#include "math/mPoint3.h"
#include "math/mMatrix.h"
#include "T3D/physics/physx3/px3.h"
#include "T3D/physics/physx3/px3Casts.h"
#include "T3D/physics/physx3/px3World.h"
#include "T3D/physics/physx3/px3Stream.h"

Px3Collision::Px3Collision()
{
}

Px3Collision::~Px3Collision()
{

	for ( U32 i=0; i < mColShapes.size(); i++ )
	{
		Px3CollisionDesc *desc = mColShapes[i];
		delete desc->pGeometry;
		// Delete the descriptor.
		delete desc;
	}

	mColShapes.clear();
}

void Px3Collision::addPlane( const PlaneF &plane )
{
	physx::PxVec3 pos = px3Cast<physx::PxVec3>(plane.getPosition());
	Px3CollisionDesc *desc = new Px3CollisionDesc;
   desc->pGeometry = new physx::PxPlaneGeometry();
   desc->pose = physx::PxTransform(pos, physx::PxQuat(physx::PxHalfPi, physx::PxVec3(0.0f, -1.0f, 0.0f)));
	mColShapes.push_back(desc);
}

void Px3Collision::addBox( const Point3F &halfWidth,const MatrixF &localXfm )
{
	Px3CollisionDesc *desc = new Px3CollisionDesc;
	desc->pGeometry = new physx::PxBoxGeometry(px3Cast<physx::PxVec3>(halfWidth));
	desc->pose = px3Cast<physx::PxTransform>(localXfm);
	mColShapes.push_back(desc);
}

void Px3Collision::addSphere(  F32 radius,
                              const MatrixF &localXfm )
{
	Px3CollisionDesc *desc = new Px3CollisionDesc;
	desc->pGeometry = new physx::PxSphereGeometry(radius);
	desc->pose = px3Cast<physx::PxTransform>(localXfm);
	mColShapes.push_back(desc);
}

void Px3Collision::addCapsule( F32 radius,
                              F32 height,
                              const MatrixF &localXfm )
{
	Px3CollisionDesc *desc = new Px3CollisionDesc;
	desc->pGeometry = new physx::PxCapsuleGeometry(radius,height*0.5);//uses half height
	desc->pose = px3Cast<physx::PxTransform>(localXfm);
	mColShapes.push_back(desc);
}

bool Px3Collision::addConvex(  const Point3F *points,
                              U32 count,
                              const MatrixF &localXfm )
{
	physx::PxCooking *cooking = Px3World::getCooking();
	physx::PxConvexMeshDesc convexDesc;
	convexDesc.points.data = points;
	convexDesc.points.stride = sizeof(Point3F);
	convexDesc.points.count = count;
	convexDesc.flags = physx::PxConvexFlag::eFLIPNORMALS|physx::PxConvexFlag::eCOMPUTE_CONVEX | physx::PxConvexFlag::eINFLATE_CONVEX;

	Px3MemOutStream stream;
	if(!cooking->cookConvexMesh(convexDesc,stream))
		return false;

	physx::PxConvexMesh* convexMesh;
	Px3MemInStream in(stream.getData(), stream.getSize());
	convexMesh = gPhysics3SDK->createConvexMesh(in);

	Px3CollisionDesc *desc = new Px3CollisionDesc;
   physx::PxVec3 scale = px3Cast<physx::PxVec3>(localXfm.getScale());
   physx::PxQuat rotation = px3Cast<physx::PxQuat>(QuatF(localXfm));
   physx::PxMeshScale meshScale(scale,rotation);
	desc->pGeometry = new physx::PxConvexMeshGeometry(convexMesh,meshScale);
	desc->pose = px3Cast<physx::PxTransform>(localXfm);
	mColShapes.push_back(desc);
	return true;
}

bool Px3Collision::addTriangleMesh(  const Point3F *vert,
                                    U32 vertCount,
                                    const U32 *index,
                                    U32 triCount,
                                    const MatrixF &localXfm )
{
	physx::PxCooking *cooking = Px3World::getCooking();
	physx::PxTriangleMeshDesc meshDesc;
	meshDesc.points.count = vertCount;
	meshDesc.points.data = vert;
	meshDesc.points.stride = sizeof(Point3F);

	meshDesc.triangles.count = triCount;
	meshDesc.triangles.data = index;
	meshDesc.triangles.stride = 3*sizeof(U32);
	meshDesc.flags = physx::PxMeshFlag::eFLIPNORMALS;

	Px3MemOutStream stream;
	if(!cooking->cookTriangleMesh(meshDesc,stream))
		return false;

	physx::PxTriangleMesh *mesh;
	Px3MemInStream in(stream.getData(), stream.getSize());
	mesh = gPhysics3SDK->createTriangleMesh(in);

	Px3CollisionDesc *desc = new Px3CollisionDesc;
	desc->pGeometry = new physx::PxTriangleMeshGeometry(mesh);
	desc->pose = px3Cast<physx::PxTransform>(localXfm);
	mColShapes.push_back(desc);
	return true;
}

bool Px3Collision::addHeightfield(   const U16 *heights,
                                    const bool *holes,
                                    U32 blockSize,
                                    F32 metersPerSample,
                                    const MatrixF &localXfm )
{
	const F32 heightScale = 0.03125f;
	physx::PxHeightFieldSample* samples = (physx::PxHeightFieldSample*) new physx::PxHeightFieldSample[blockSize*blockSize];
	memset(samples,0,blockSize*blockSize*sizeof(physx::PxHeightFieldSample));

	physx::PxHeightFieldDesc heightFieldDesc;
	heightFieldDesc.nbColumns = blockSize;
	heightFieldDesc.nbRows = blockSize;
	heightFieldDesc.thickness = -10.f;
	heightFieldDesc.convexEdgeThreshold = 0;
	heightFieldDesc.format = physx::PxHeightFieldFormat::eS16_TM;
	heightFieldDesc.samples.data = samples;
	heightFieldDesc.samples.stride = sizeof(physx::PxHeightFieldSample);

	physx::PxU8 *currentByte = (physx::PxU8*)heightFieldDesc.samples.data;
   for ( U32 row = 0; row < blockSize; row++ )
   {
      const U32 tess = ( row + 1 ) % 2;

      for ( U32 column = 0; column < blockSize; column++ )
      {
         physx::PxHeightFieldSample *currentSample = (physx::PxHeightFieldSample*)currentByte;

         U32 index = ( blockSize - row - 1 ) + ( column * blockSize );
         currentSample->height = (physx::PxI16)heights[ index ];

         if ( holes && holes[ getMax( (S32)index - 1, 0 ) ] )     // row index for holes adjusted so PhysX collision shape better matches rendered terrain
         {
            currentSample->materialIndex0 = physx::PxHeightFieldMaterial::eHOLE;
            currentSample->materialIndex1 = physx::PxHeightFieldMaterial::eHOLE;
         }
         else
         {
            currentSample->materialIndex0 = 0;
            currentSample->materialIndex1 = 0;
         }

		int flag = ( column + tess ) % 2;
		if(flag)
			currentSample->setTessFlag();
		else
			currentSample->clearTessFlag();

         currentByte += heightFieldDesc.samples.stride;
      }
   }

	physx::PxHeightField * hf = gPhysics3SDK->createHeightField(heightFieldDesc);
	physx::PxHeightFieldGeometry *geom = new physx::PxHeightFieldGeometry(hf,physx::PxMeshGeometryFlags(),heightScale,metersPerSample,metersPerSample);

	physx::PxTransform pose= physx::PxTransform(physx::PxQuat(Float_HalfPi, physx::PxVec3(1, 0, 0 )));
	physx::PxTransform pose1= physx::PxTransform(physx::PxQuat(Float_Pi, physx::PxVec3(0, 0, 1 )));
	physx::PxTransform pose2 = pose1 * pose;
	pose2.p = physx::PxVec3(( blockSize - 1 ) * metersPerSample, 0, 0 );
	Px3CollisionDesc *desc = new Px3CollisionDesc;
	desc->pGeometry = geom;
	desc->pose = pose2;

	mColShapes.push_back(desc);
	return true;
}
<commit_msg>- Fixed memory leak when creating terrain with physx 3<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------

#include "platform/platform.h"
#include "T3D/physics/physx3/px3Collision.h"

#include "math/mPoint3.h"
#include "math/mMatrix.h"
#include "T3D/physics/physx3/px3.h"
#include "T3D/physics/physx3/px3Casts.h"
#include "T3D/physics/physx3/px3World.h"
#include "T3D/physics/physx3/px3Stream.h"

Px3Collision::Px3Collision()
{
}

Px3Collision::~Px3Collision()
{

	for ( U32 i=0; i < mColShapes.size(); i++ )
	{
		Px3CollisionDesc *desc = mColShapes[i];
		delete desc->pGeometry;
		// Delete the descriptor.
		delete desc;
	}

	mColShapes.clear();
}

void Px3Collision::addPlane( const PlaneF &plane )
{
	physx::PxVec3 pos = px3Cast<physx::PxVec3>(plane.getPosition());
	Px3CollisionDesc *desc = new Px3CollisionDesc;
   desc->pGeometry = new physx::PxPlaneGeometry();
   desc->pose = physx::PxTransform(pos, physx::PxQuat(physx::PxHalfPi, physx::PxVec3(0.0f, -1.0f, 0.0f)));
	mColShapes.push_back(desc);
}

void Px3Collision::addBox( const Point3F &halfWidth,const MatrixF &localXfm )
{
	Px3CollisionDesc *desc = new Px3CollisionDesc;
	desc->pGeometry = new physx::PxBoxGeometry(px3Cast<physx::PxVec3>(halfWidth));
	desc->pose = px3Cast<physx::PxTransform>(localXfm);
	mColShapes.push_back(desc);
}

void Px3Collision::addSphere(  F32 radius,
                              const MatrixF &localXfm )
{
	Px3CollisionDesc *desc = new Px3CollisionDesc;
	desc->pGeometry = new physx::PxSphereGeometry(radius);
	desc->pose = px3Cast<physx::PxTransform>(localXfm);
	mColShapes.push_back(desc);
}

void Px3Collision::addCapsule( F32 radius,
                              F32 height,
                              const MatrixF &localXfm )
{
	Px3CollisionDesc *desc = new Px3CollisionDesc;
	desc->pGeometry = new physx::PxCapsuleGeometry(radius,height*0.5);//uses half height
	desc->pose = px3Cast<physx::PxTransform>(localXfm);
	mColShapes.push_back(desc);
}

bool Px3Collision::addConvex(  const Point3F *points,
                              U32 count,
                              const MatrixF &localXfm )
{
	physx::PxCooking *cooking = Px3World::getCooking();
	physx::PxConvexMeshDesc convexDesc;
	convexDesc.points.data = points;
	convexDesc.points.stride = sizeof(Point3F);
	convexDesc.points.count = count;
	convexDesc.flags = physx::PxConvexFlag::eFLIPNORMALS|physx::PxConvexFlag::eCOMPUTE_CONVEX | physx::PxConvexFlag::eINFLATE_CONVEX;

	Px3MemOutStream stream;
	if(!cooking->cookConvexMesh(convexDesc,stream))
		return false;

	physx::PxConvexMesh* convexMesh;
	Px3MemInStream in(stream.getData(), stream.getSize());
	convexMesh = gPhysics3SDK->createConvexMesh(in);

	Px3CollisionDesc *desc = new Px3CollisionDesc;
   physx::PxVec3 scale = px3Cast<physx::PxVec3>(localXfm.getScale());
   physx::PxQuat rotation = px3Cast<physx::PxQuat>(QuatF(localXfm));
   physx::PxMeshScale meshScale(scale,rotation);
	desc->pGeometry = new physx::PxConvexMeshGeometry(convexMesh,meshScale);
	desc->pose = px3Cast<physx::PxTransform>(localXfm);
	mColShapes.push_back(desc);
	return true;
}

bool Px3Collision::addTriangleMesh(  const Point3F *vert,
                                    U32 vertCount,
                                    const U32 *index,
                                    U32 triCount,
                                    const MatrixF &localXfm )
{
	physx::PxCooking *cooking = Px3World::getCooking();
	physx::PxTriangleMeshDesc meshDesc;
	meshDesc.points.count = vertCount;
	meshDesc.points.data = vert;
	meshDesc.points.stride = sizeof(Point3F);

	meshDesc.triangles.count = triCount;
	meshDesc.triangles.data = index;
	meshDesc.triangles.stride = 3*sizeof(U32);
	meshDesc.flags = physx::PxMeshFlag::eFLIPNORMALS;

	Px3MemOutStream stream;
	if(!cooking->cookTriangleMesh(meshDesc,stream))
		return false;

	physx::PxTriangleMesh *mesh;
	Px3MemInStream in(stream.getData(), stream.getSize());
	mesh = gPhysics3SDK->createTriangleMesh(in);

	Px3CollisionDesc *desc = new Px3CollisionDesc;
	desc->pGeometry = new physx::PxTriangleMeshGeometry(mesh);
	desc->pose = px3Cast<physx::PxTransform>(localXfm);
	mColShapes.push_back(desc);
	return true;
}

bool Px3Collision::addHeightfield(   const U16 *heights,
                                    const bool *holes,
                                    U32 blockSize,
                                    F32 metersPerSample,
                                    const MatrixF &localXfm )
{
	const F32 heightScale = 0.03125f;
	physx::PxHeightFieldSample* samples = (physx::PxHeightFieldSample*) new physx::PxHeightFieldSample[blockSize*blockSize];
	memset(samples,0,blockSize*blockSize*sizeof(physx::PxHeightFieldSample));

	physx::PxHeightFieldDesc heightFieldDesc;
	heightFieldDesc.nbColumns = blockSize;
	heightFieldDesc.nbRows = blockSize;
	heightFieldDesc.thickness = -10.f;
	heightFieldDesc.convexEdgeThreshold = 0;
	heightFieldDesc.format = physx::PxHeightFieldFormat::eS16_TM;
	heightFieldDesc.samples.data = samples;
	heightFieldDesc.samples.stride = sizeof(physx::PxHeightFieldSample);

	physx::PxU8 *currentByte = (physx::PxU8*)heightFieldDesc.samples.data;
   for ( U32 row = 0; row < blockSize; row++ )
   {
      const U32 tess = ( row + 1 ) % 2;

      for ( U32 column = 0; column < blockSize; column++ )
      {
         physx::PxHeightFieldSample *currentSample = (physx::PxHeightFieldSample*)currentByte;

         U32 index = ( blockSize - row - 1 ) + ( column * blockSize );
         currentSample->height = (physx::PxI16)heights[ index ];

         if ( holes && holes[ getMax( (S32)index - 1, 0 ) ] )     // row index for holes adjusted so PhysX collision shape better matches rendered terrain
         {
            currentSample->materialIndex0 = physx::PxHeightFieldMaterial::eHOLE;
            currentSample->materialIndex1 = physx::PxHeightFieldMaterial::eHOLE;
         }
         else
         {
            currentSample->materialIndex0 = 0;
            currentSample->materialIndex1 = 0;
         }

		int flag = ( column + tess ) % 2;
		if(flag)
			currentSample->clearTessFlag();
		else
			currentSample->setTessFlag();

         currentByte += heightFieldDesc.samples.stride;
      }
   }

	physx::PxHeightField * hf = gPhysics3SDK->createHeightField(heightFieldDesc);
	physx::PxHeightFieldGeometry *geom = new physx::PxHeightFieldGeometry(hf,physx::PxMeshGeometryFlags(),heightScale,metersPerSample,metersPerSample);

	physx::PxTransform pose= physx::PxTransform(physx::PxQuat(Float_HalfPi, physx::PxVec3(1, 0, 0 )));
	physx::PxTransform pose1= physx::PxTransform(physx::PxQuat(Float_Pi, physx::PxVec3(0, 0, 1 )));
	physx::PxTransform pose2 = pose1 * pose;
	pose2.p = physx::PxVec3(( blockSize - 1 ) * metersPerSample, 0, 0 );
	Px3CollisionDesc *desc = new Px3CollisionDesc;
	desc->pGeometry = geom;
	desc->pose = pose2;

	mColShapes.push_back(desc);

   SAFE_DELETE(samples);
	return true;
}
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Karoliina T. Salminen <karoliina.t.salminen@nokia.com>
**
** This file is part of duicontrolpanel.
**
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "dcpqmlwidget.h"

#include <MLabel>
#include <dcpdebug.h>
#include <QGraphicsLinearLayout>
#include <QDeclarativeError>
#include <QDeclarativeEngine>
#include <QDeclarativeComponent>
#include <QDeclarativeItem>
#include <MApplicationPage>
#include <QGraphicsSceneResizeEvent>
#include <QDebug>

DcpQmlWidget::DcpQmlWidget(const QString& qmlPath):
    m_Object (0),
    m_HandlesItsOwnWindow (false)

DcpQmlWidget::DcpQmlWidget(const QString& qmlPath)
{
    // for the error labels:
    new QGraphicsLinearLayout(Qt::Vertical, this);

    // get as much space as possible:
    setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding);

    // create the qml widget:
    QDeclarativeEngine *engine = new QDeclarativeEngine (this);
    QDeclarativeComponent component(engine, QUrl::fromLocalFile(qmlPath));
    m_Object =
        qobject_cast<QGraphicsObject *>(component.create());
    if (m_Object) {
        // all fine, make it visible
        m_Object->setParentItem (this);
        m_HandlesItsOwnWindow =
            QString(m_Object->metaObject()->className()).startsWith ("PageStackWindow_");

        if (handlesItsOwnWindow()) {
        } else {
            setPreferredSize (m_Object->boundingRect().size());
            enableAutoTitle();
        }
    } else {
        // error happened
        createErrorLabel (QString("Error loading %1").arg(qmlPath));
        foreach (QDeclarativeError error, component.errors()) {
            createErrorLabel (error.toString());
        }
    }
}

void DcpQmlWidget::resizeEvent ( QGraphicsSceneResizeEvent * event )
{
    if (!handlesItsOwnWindow()) return;

    // handle the size of the main m_Object (it is not a widget, so could
    // not put it into a layout)
    QDeclarativeItem* item = qobject_cast<QDeclarativeItem*>(m_Object);
    dcp_failfunc_unless (item);
    item->setSize (event->newSize());
}

void DcpQmlWidget::polishEvent ()
{
    if (!handlesItsOwnWindow()) return;

    // hide everything on the page (qml displays its window totally)
    QGraphicsWidget* item = this;
    MApplicationPage* page = 0;
    do {
        page = qobject_cast<MApplicationPage*>(item);
        item = item->parentWidget();
    } while (!page);
    dcp_failfunc_unless (page);

    page->setComponentsDisplayMode (MApplicationPage::AllComponents,
                                    MApplicationPageModel::Hide);
}

bool DcpQmlWidget::pagePans () const
{
    return !handlesItsOwnWindow();
}

bool DcpQmlWidget::handlesItsOwnWindow() const
{
    return m_HandlesItsOwnWindow;
}

void DcpQmlWidget::createErrorLabel(const QString& text)
{
    MLabel* label;

    label = new MLabel(this);
    label->setText(text);
    label->setWrapMode (QTextOption::WrapAtWordBoundaryOrAnywhere);
    label->setWordWrap (true);
    label->setStyleName ("CommonBodyTextInverted");
    ((QGraphicsLinearLayout*)(layout()))->addItem(label);

    DCP_WARNING(qPrintable(text));
}

void DcpQmlWidget::requestPage (int id)
{
    emit changeWidget (id);
}

<commit_msg>little merge mistake<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Karoliina T. Salminen <karoliina.t.salminen@nokia.com>
**
** This file is part of duicontrolpanel.
**
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "dcpqmlwidget.h"

#include <MLabel>
#include <dcpdebug.h>
#include <QGraphicsLinearLayout>
#include <QDeclarativeError>
#include <QDeclarativeEngine>
#include <QDeclarativeComponent>
#include <QDeclarativeItem>
#include <MApplicationPage>
#include <QGraphicsSceneResizeEvent>
#include <QDebug>

DcpQmlWidget::DcpQmlWidget(const QString& qmlPath):
    m_Object (0),
    m_HandlesItsOwnWindow (false)
{
    // for the error labels:
    new QGraphicsLinearLayout(Qt::Vertical, this);

    // get as much space as possible:
    setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding);

    // create the qml widget:
    QDeclarativeEngine *engine = new QDeclarativeEngine (this);
    QDeclarativeComponent component(engine, QUrl::fromLocalFile(qmlPath));
    m_Object =
        qobject_cast<QGraphicsObject *>(component.create());
    if (m_Object) {
        // all fine, make it visible
        m_Object->setParentItem (this);
        m_HandlesItsOwnWindow =
            QString(m_Object->metaObject()->className()).startsWith ("PageStackWindow_");

        if (handlesItsOwnWindow()) {
        } else {
            setPreferredSize (m_Object->boundingRect().size());
            enableAutoTitle();
        }
    } else {
        // error happened
        createErrorLabel (QString("Error loading %1").arg(qmlPath));
        foreach (QDeclarativeError error, component.errors()) {
            createErrorLabel (error.toString());
        }
    }
}

void DcpQmlWidget::resizeEvent ( QGraphicsSceneResizeEvent * event )
{
    if (!handlesItsOwnWindow()) return;

    // handle the size of the main m_Object (it is not a widget, so could
    // not put it into a layout)
    QDeclarativeItem* item = qobject_cast<QDeclarativeItem*>(m_Object);
    dcp_failfunc_unless (item);
    item->setSize (event->newSize());
}

void DcpQmlWidget::polishEvent ()
{
    if (!handlesItsOwnWindow()) return;

    // hide everything on the page (qml displays its window totally)
    QGraphicsWidget* item = this;
    MApplicationPage* page = 0;
    do {
        page = qobject_cast<MApplicationPage*>(item);
        item = item->parentWidget();
    } while (!page);
    dcp_failfunc_unless (page);

    page->setComponentsDisplayMode (MApplicationPage::AllComponents,
                                    MApplicationPageModel::Hide);
}

bool DcpQmlWidget::pagePans () const
{
    return !handlesItsOwnWindow();
}

bool DcpQmlWidget::handlesItsOwnWindow() const
{
    return m_HandlesItsOwnWindow;
}

void DcpQmlWidget::createErrorLabel(const QString& text)
{
    MLabel* label;

    label = new MLabel(this);
    label->setText(text);
    label->setWrapMode (QTextOption::WrapAtWordBoundaryOrAnywhere);
    label->setWordWrap (true);
    label->setStyleName ("CommonBodyTextInverted");
    ((QGraphicsLinearLayout*)(layout()))->addItem(label);

    DCP_WARNING(qPrintable(text));
}

void DcpQmlWidget::requestPage (int id)
{
    emit changeWidget (id);
}

<|endoftext|>


<commit_before>#include "fingerprint.h"

using namespace v8;
using v8::FunctionTemplate;

extern int initalized;

typedef struct __ENROLL_DATA__ {
    uv_async_t async;
    Nan::Persistent<Function> callback;
    unsigned char *fingerprint_data;
    size_t fingerprint_size;
    int result;
} ENROLL_DATA;

typedef struct __ENROLL_STOP__ {
    uv_async_t async;
    Nan::Persistent<Function> callback;
} ENROLL_STOP;

static const char *enroll_result_to_name (int result)
{
	switch (result) {
	case FP_ENROLL_COMPLETE:
		return "enroll-completed";
	case FP_ENROLL_FAIL:
		return "enroll-failed";
	case FP_ENROLL_PASS:
		return "enroll-stage-passed";
	case FP_ENROLL_RETRY:
		return "enroll-retry-scan";
	case FP_ENROLL_RETRY_TOO_SHORT:
		return "enroll-swipe-too-short";
	case FP_ENROLL_RETRY_CENTER_FINGER:
		return "enroll-finger-not-centered";
	case FP_ENROLL_RETRY_REMOVE_FINGER:
		return "enroll-remove-and-retry";
	default:
		return "enroll-unknown-error";
	}
}

void enroll_stopped_after(uv_handle_t* handle)
{
    ENROLL_STOP *data = container_of((uv_async_t *)handle, ENROLL_STOP, async);

    if(!data)
        return;

    delete data;
}

void report_enroll_stopped(uv_async_t *handle, int status)
{
    ENROLL_STOP *data = container_of(handle, ENROLL_STOP, async);
    Nan::HandleScope();

    if(!data)
        return;

    Nan::Callback callback(Nan::New<Function>(data->callback));
    callback.Call(0, NULL);

    uv_close((uv_handle_t*)&data->async, enroll_stopped_after);
}

static void enroll_stop_cb(struct fp_dev *dev, void *user_data)
{
    ENROLL_STOP *data = (ENROLL_STOP*)user_data;

    if(!data)
        return;

    uv_async_send(&data->async);
}

NAN_METHOD(enrollStop) {
    struct fp_dev *dev;
    bool ret = false;
    ENROLL_STOP *data;

    if(info.Length() != 2)
        return;

    dev = toFPDev(info[0]->ToNumber()->Value());
    if(initalized != 0 || dev == NULL)
        goto error;

    data = new ENROLL_STOP;
    data->callback.Reset(v8::Local<v8::Function>::Cast(info[1]));
    uv_async_init(uv_default_loop(), &data->async, report_enroll_stopped);
    ret = fp_async_enroll_stop(dev, enroll_stop_cb, data) == 0;
error:
    info.GetReturnValue().Set(Nan::New(ret));
    return;
}

void enroll_after(uv_handle_t* handle)
{
    ENROLL_DATA *enrollData = container_of((uv_async_t *)handle, ENROLL_DATA, async);

    if(!enrollData)
        return;

    if(enrollData->fingerprint_data)
        free(enrollData->fingerprint_data);

    enrollData->fingerprint_data = NULL;
    enrollData->fingerprint_size = 0;
    delete enrollData;
}

void report_enroll_progress(uv_async_t *handle, int status)
{
    ENROLL_DATA *enrollData = container_of(handle, ENROLL_DATA, async);
    Nan::HandleScope();

    if(!enrollData)
        return;

    printf("report enroll progress: result: %d\n", enrollData->result);

    Nan::Callback callback(Nan::New<Function>(enrollData->callback));
    Local<Value> argv[3];
    argv[0] = Nan::New(enrollData->result);
    argv[1] = Nan::New(enroll_result_to_name(enrollData->result)).ToLocalChecked();
    argv[2] = Nan::Null();

    if(enrollData->result == FP_ENROLL_COMPLETE)
        argv[2] = Nan::CopyBuffer((const char*)enrollData->fingerprint_data, enrollData->fingerprint_size).ToLocalChecked();

    callback.Call(3, argv);

    if(enrollData->result == FP_ENROLL_FAIL || enrollData->result == FP_ENROLL_COMPLETE) {
        uv_close((uv_handle_t*)&enrollData->async, enroll_after);
    }
}

static void enroll_stage_cb(struct fp_dev *dev, int result, struct fp_print_data *print, struct fp_img *img, void *user_data)
{
    ENROLL_DATA *enrollData = (ENROLL_DATA*)user_data;

    if(!enrollData || result < 0)
        return;

    enrollData->result = result;
    if(print && result == FP_ENROLL_COMPLETE)
        enrollData->fingerprint_size = fp_print_data_get_data(print, &enrollData->fingerprint_data);

    uv_async_send(&enrollData->async);

    if(img) fp_img_free(img);
    if(print) fp_print_data_free(print);
}

NAN_METHOD(enrollStart) {
    int r;
    struct fp_dev *dev;
    bool ret = false;
    ENROLL_DATA *enrollData;

    if(info.Length() != 2)
        return;

    dev = toFPDev(info[0]->ToNumber()->Value());
    if(initalized != 0 || dev == NULL)
        goto error;

    enrollData = new ENROLL_DATA;
    if(!enrollData)
        goto error;

    enrollData->fingerprint_data = NULL;
    enrollData->fingerprint_size = 0;
    enrollData->result = -1;
    uv_async_init(uv_default_loop(), &enrollData->async, report_enroll_progress);
    enrollData->callback.Reset(v8::Local<v8::Function>::Cast(info[1]));
    r = fp_async_enroll_start(dev, enroll_stage_cb, (void*)enrollData);
    if (r < 0 || r == FP_ENROLL_FAIL) {
        printf("Enroll failed with error %d\n", r);
        goto error;
    }

    ret = true;
error:
    info.GetReturnValue().Set(Nan::New(ret));
    return;
}
<commit_msg>compile with older uv<commit_after>#include "fingerprint.h"

using namespace v8;
using v8::FunctionTemplate;

extern int initalized;

typedef struct __ENROLL_DATA__ {
    uv_async_t async;
    Nan::Persistent<Function> callback;
    unsigned char *fingerprint_data;
    size_t fingerprint_size;
    int result;
} ENROLL_DATA;

typedef struct __ENROLL_STOP__ {
    uv_async_t async;
    Nan::Persistent<Function> callback;
} ENROLL_STOP;

static const char *enroll_result_to_name (int result)
{
	switch (result) {
	case FP_ENROLL_COMPLETE:
		return "enroll-completed";
	case FP_ENROLL_FAIL:
		return "enroll-failed";
	case FP_ENROLL_PASS:
		return "enroll-stage-passed";
	case FP_ENROLL_RETRY:
		return "enroll-retry-scan";
	case FP_ENROLL_RETRY_TOO_SHORT:
		return "enroll-swipe-too-short";
	case FP_ENROLL_RETRY_CENTER_FINGER:
		return "enroll-finger-not-centered";
	case FP_ENROLL_RETRY_REMOVE_FINGER:
		return "enroll-remove-and-retry";
	default:
		return "enroll-unknown-error";
	}
}

void enroll_stopped_after(uv_handle_t* handle)
{
    ENROLL_STOP *data = container_of((uv_async_t *)handle, ENROLL_STOP, async);

    if(!data)
        return;

    delete data;
}

#ifdef OLD_UV_RUN_SIGNATURE
void report_enroll_stopped(uv_async_t *handle, int status)
#else
void report_enroll_stopped(uv_async_t *handle)
#endif
{
    ENROLL_STOP *data = container_of(handle, ENROLL_STOP, async);
    Nan::HandleScope();

    if(!data)
        return;

    Nan::Callback callback(Nan::New<Function>(data->callback));
    callback.Call(0, NULL);

    uv_close((uv_handle_t*)&data->async, enroll_stopped_after);
}

static void enroll_stop_cb(struct fp_dev *dev, void *user_data)
{
    ENROLL_STOP *data = (ENROLL_STOP*)user_data;

    if(!data)
        return;

    uv_async_send(&data->async);
}

NAN_METHOD(enrollStop) {
    struct fp_dev *dev;
    bool ret = false;
    ENROLL_STOP *data;

    if(info.Length() != 2)
        return;

    dev = toFPDev(info[0]->ToNumber()->Value());
    if(initalized != 0 || dev == NULL)
        goto error;

    data = new ENROLL_STOP;
    data->callback.Reset(v8::Local<v8::Function>::Cast(info[1]));
    uv_async_init(uv_default_loop(), &data->async, report_enroll_stopped);
    ret = fp_async_enroll_stop(dev, enroll_stop_cb, data) == 0;
error:
    info.GetReturnValue().Set(Nan::New(ret));
    return;
}

void enroll_after(uv_handle_t* handle)
{
    ENROLL_DATA *enrollData = container_of((uv_async_t *)handle, ENROLL_DATA, async);

    if(!enrollData)
        return;

    if(enrollData->fingerprint_data)
        free(enrollData->fingerprint_data);

    enrollData->fingerprint_data = NULL;
    enrollData->fingerprint_size = 0;
    delete enrollData;
}

#ifdef OLD_UV_RUN_SIGNATURE
void report_enroll_progress(uv_async_t *handle, int status)
#else
void report_enroll_progress(uv_async_t *handle)
#endif
{
    ENROLL_DATA *enrollData = container_of(handle, ENROLL_DATA, async);
    Nan::HandleScope();

    if(!enrollData)
        return;

    printf("report enroll progress: result: %d\n", enrollData->result);

    Nan::Callback callback(Nan::New<Function>(enrollData->callback));
    Local<Value> argv[3];
    argv[0] = Nan::New(enrollData->result);
    argv[1] = Nan::New(enroll_result_to_name(enrollData->result)).ToLocalChecked();
    argv[2] = Nan::Null();

    if(enrollData->result == FP_ENROLL_COMPLETE)
        argv[2] = Nan::CopyBuffer((const char*)enrollData->fingerprint_data, enrollData->fingerprint_size).ToLocalChecked();

    callback.Call(3, argv);

    if(enrollData->result == FP_ENROLL_FAIL || enrollData->result == FP_ENROLL_COMPLETE) {
        uv_close((uv_handle_t*)&enrollData->async, enroll_after);
    }
}

static void enroll_stage_cb(struct fp_dev *dev, int result, struct fp_print_data *print, struct fp_img *img, void *user_data)
{
    ENROLL_DATA *enrollData = (ENROLL_DATA*)user_data;

    if(!enrollData || result < 0)
        return;

    enrollData->result = result;
    if(print && result == FP_ENROLL_COMPLETE)
        enrollData->fingerprint_size = fp_print_data_get_data(print, &enrollData->fingerprint_data);

    uv_async_send(&enrollData->async);

    if(img) fp_img_free(img);
    if(print) fp_print_data_free(print);
}

NAN_METHOD(enrollStart) {
    int r;
    struct fp_dev *dev;
    bool ret = false;
    ENROLL_DATA *enrollData;

    if(info.Length() != 2)
        return;

    dev = toFPDev(info[0]->ToNumber()->Value());
    if(initalized != 0 || dev == NULL)
        goto error;

    enrollData = new ENROLL_DATA;
    if(!enrollData)
        goto error;

    enrollData->fingerprint_data = NULL;
    enrollData->fingerprint_size = 0;
    enrollData->result = -1;
    uv_async_init(uv_default_loop(), &enrollData->async, report_enroll_progress);
    enrollData->callback.Reset(v8::Local<v8::Function>::Cast(info[1]));
    r = fp_async_enroll_start(dev, enroll_stage_cb, (void*)enrollData);
    if (r < 0 || r == FP_ENROLL_FAIL) {
        printf("Enroll failed with error %d\n", r);
        goto error;
    }

    ret = true;
error:
    info.GetReturnValue().Set(Nan::New(ret));
    return;
}
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2012 by INdT
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * @author Rodrigo Goncalves de Oliveira <rodrigo.goncalves@openbossa.org>
 * @author Roger Felipe Zanoni da Silva <roger.zanoni@openbossa.org>
 */

#include "entity.h"

#include "enums.h"
#include "scene.h"
#include "game.h"
#include "behavior.h"
#include "fixture.h"
#include "material.h"

Entity::Entity(Scene *parent)
    : Box2DBaseItem(parent)
    , m_updateInterval(0)
    , m_scene(0)
    , m_behavior(0)
    , m_body(0)
    , m_linearDamping(0.0f)
    , m_angularDamping(0.0f)
    , m_bodyType(Quasi::StaticBodyType)
    , m_bullet(false)
    , m_sleepingAllowed(true)
    , m_fixedRotation(false)
    , m_active(true)
    , m_sensorFixture(0)
{
    setTransformOrigin(Center);
    connect(this, SIGNAL(rotationChanged()), SLOT(onRotationChanged()));
}

Entity::~Entity()
{
    if (!m_world || !m_body)
        return;

#if QT_VERSION >= 0x050000
    QQuickItem *child;
#else
    QGraphicsItem *child;
#endif

    foreach (child, childItems())
        if (Fixture *fixture = dynamic_cast<Fixture *>(child))
            delete fixture;

    m_worldPtr->DestroyBody(m_body);
    m_body = 0;
}

void Entity::update(const int &delta)
{
    if ((m_updateInterval && m_updateTime.elapsed() >= m_updateInterval)
        || !m_updateInterval) {
        m_updateTime.restart();
        if (m_behavior) {
            m_behavior->setDelta(delta);
            m_behavior->setEntity(this);
            m_behavior->update(delta);
            m_behavior->setEntity(0);
        }
    }

#if QT_VERSION >= 0x050000
    QQuickItem *child;
#else
    QGraphicsItem *child;
#endif
    foreach (child, childItems())
        if (Entity *item = dynamic_cast<Entity *>(child))
            item->update(delta);
}

int Entity::updateInterval() const
{
    return m_updateInterval;
}

void Entity::setUpdateInterval(const int &updateInterval)
{
    if (m_updateInterval != updateInterval) {
        m_updateInterval = updateInterval;

        emit updateIntervalChanged();

        m_updateTime.restart();
    }
}

Scene *Entity::scene() const
{
    return m_scene;
}

void Entity::setScene(Scene *scene)
{
    m_scene = scene;
}

Game *Entity::game() const
{
    if (m_scene)
        return m_scene->game();

    return 0;
}

Behavior *Entity::behavior() const
{
    return m_behavior;
}

void Entity::setBehavior(Behavior *behavior)
{
    if (m_behavior == behavior)
        return;

    m_behavior = behavior;

    emit behaviorChanged();
}

void Entity::componentComplete()
{
    if (!m_initialized)
        initialize();
}

b2Body *Entity::body() const
{
    return m_body;
}

void Entity::onRotationChanged()
{
    if (!m_synchronizing && m_body) {
        m_body->SetTransform(m_body->GetPosition(),
                             (rotation() * 2 * b2_pi) / -360.0);
    }
}

/*
 * Shamelessly stolen from qml-box2d project at gitorious
 *
 * https://gitorious.org/qml-box2d/qml-box2d
 */
void Entity::initialize()
{
    if (m_initialized || !m_world)
        return;

    b2BodyDef bodyDef;
    bodyDef.type = static_cast<b2BodyType>(m_bodyType);
    bodyDef.position.Set((x() + width() / 2.0) / m_scaleRatio,
                         (-y() - height() / 2.0) / m_scaleRatio);

    bodyDef.angle = -(rotation() * (2 * b2_pi)) / 360.0;
    bodyDef.linearDamping = m_linearDamping;
    bodyDef.angularDamping = m_angularDamping;
    bodyDef.bullet = m_bullet;
    bodyDef.allowSleep = m_sleepingAllowed;
    bodyDef.fixedRotation = m_fixedRotation;

    m_body = m_worldPtr->CreateBody(&bodyDef);

    initializeFixtures();

    m_initialized = true;
}

qreal Entity::linearDamping() const
{
    return m_linearDamping;
}

void Entity::setLinearDamping(const qreal &linearDamping)
{
    if (m_linearDamping != linearDamping) {
        m_linearDamping = linearDamping;

        if (m_body)
            m_body->SetLinearDamping(linearDamping);

        emit linearDampingChanged();
    }
}

qreal Entity::angularDamping() const
{
    return m_angularDamping;
}

void Entity::setAngularDamping(const qreal &angularDamping)
{
    if (m_angularDamping != angularDamping) {
        m_angularDamping = angularDamping;

        if (m_body)
            m_body->SetAngularDamping(angularDamping);

        emit angularDampingChanged();
    }
}

Quasi::BodyType Entity::bodyType() const
{
    return m_bodyType;
}

void Entity::setBodyType(const Quasi::BodyType &bodyType)
{
    if (m_bodyType != bodyType) {
        m_bodyType = bodyType;

        if (m_body)
            m_body->SetType((b2BodyType)bodyType);

        emit bodyTypeChanged();
    }
}

bool Entity::bullet() const
{
    return m_bullet;
}

void Entity::setBullet(const bool &bullet)
{
    if (m_bullet != bullet) {
        m_bullet = bullet;

        if (m_body)
            m_body->SetBullet(bullet);

        emit bulletChanged();
    }
}

bool Entity::sleepingAllowed() const
{
    return m_sleepingAllowed;
}

void Entity::setSleepingAllowed(const bool &sleepingAllowed)
{
    if (m_sleepingAllowed != sleepingAllowed) {
        m_sleepingAllowed = sleepingAllowed;

        if (m_body)
            m_body->SetSleepingAllowed(sleepingAllowed);

        emit sleepingAllowedChanged();
    }
}

bool Entity::fixedRotation() const
{
    return m_fixedRotation;
}

void Entity::setFixedRotation(const bool &fixedRotation)
{
    if (m_fixedRotation != fixedRotation) {
        m_fixedRotation = fixedRotation;

        if (m_body)
            m_body->SetFixedRotation(fixedRotation);

        emit fixedRotationChanged();
    }
}

bool Entity::active() const
{
    return m_active;
}

void Entity::setActive(const bool &active)
{
    if (m_active != active) {
        m_active = active;

        if (m_body)
            m_body->SetActive(active);

        emit activeChanged();
    }
}

void Entity::applyTorque(const float &torque)
{
    if (m_body)
        m_body->ApplyTorque(torque);
}

void Entity::applyLinearImpulse(const QPointF &impulse, const QPointF &point)
{
    if (m_body) {
        m_body->ApplyLinearImpulse(b2Vec2(impulse.x() / m_scaleRatio,
                                          -impulse.y() / m_scaleRatio),
                                   b2Vec2(point.x() / m_scaleRatio,
                                          -point.y() / m_scaleRatio));
    }
}

void Entity::setLinearVelocity(const QPointF &velocity)
{
    if (m_body) {
        m_body->SetLinearVelocity(b2Vec2(velocity.x() / m_scaleRatio,
                                         -velocity.y() / m_scaleRatio));
    }
}

void Entity::setAngularVelocity(const float &velocity)
{
    if (m_body) {
        m_body->SetAngularVelocity(velocity);
    }
}

void Entity::geometryChanged(const QRectF &newGeometry,
                                const QRectF &oldGeometry)
{
    if (!m_synchronizing && m_body) {
        if (newGeometry.topLeft() != oldGeometry.topLeft()) {
            const QPointF pos = newGeometry.topLeft();

            m_body->SetTransform(b2Vec2((pos.x() + width() / 2.0) / m_scaleRatio,
                                        (-pos.y() - height() / 2.0) / m_scaleRatio),
                                 m_body->GetAngle());
        }
    }

#if QT_VERSION >= 0x050000
    QQuickItem::geometryChanged(newGeometry, oldGeometry);
#else
    QDeclarativeItem::geometryChanged(newGeometry, oldGeometry);
#endif
}

b2Vec2 Entity::b2TransformOrigin() const
{
    b2Vec2 vec;
    if (m_body)
        vec = m_body->GetPosition();

    return vec;
}

float Entity::b2Angle() const
{
    float32 angle = 0.0f;
    if (m_body)
        angle = m_body->GetAngle();
    return angle;
}

void Entity::initializeFixtures()
{
#if QT_VERSION >= 0x050000
    QQuickItem *item;
#else
    QGraphicsItem *item;
#endif

    bool createSensor = true;
    foreach (item, childItems()) {
        if (Fixture *fixture = dynamic_cast<Fixture *>(item)) {
            createSensor = false;
            fixture->setWorld(m_world);
            fixture->setBody(this);
            fixture->initialize();
        }
    }

    if (createSensor)
        createSensorFixture();
}

#if QT_VERSION >= 0x050000
void Entity::itemChange(ItemChange change, const ItemChangeData &data)
#else
QVariant Entity::itemChange(GraphicsItemChange change, const QVariant &value)
#endif
{
    if (isComponentComplete() && change == ItemChildAddedChange) {
#if QT_VERSION >= 0x050000
        QQuickItem *child = data.item;
#else
        QGraphicsItem *child = value.value<QGraphicsItem *>();
#endif
        if (Fixture *fixture = dynamic_cast<Fixture *>(child)) {
            destroySensorFixture();
            fixture->setWorld(m_world);
            fixture->setBody(this);
            fixture->initialize();
        }
    }

#if QT_VERSION >= 0x050000
    Box2DBaseItem::itemChange(change, data);
#else
    return Box2DBaseItem::itemChange(change, value);
#endif
}

void Entity::createSensorFixture()
{
    setBodyType(Quasi::DynamicBodyType);
    m_body->SetGravityScale(0);

    m_sensorFixture = new Fixture(this);
    m_sensorFixture->setMaterial(new Material(this));
    m_sensorFixture->setWidth(width());
    m_sensorFixture->setHeight(height());
    m_sensorFixture->setShapeItem(this);
    m_sensorFixture->setWorld(m_world);
    m_sensorFixture->setBody(this);
    m_sensorFixture->setSensor(true);
    m_sensorFixture->updateFixture();
}

void Entity::destroySensorFixture()
{
    if (!m_sensorFixture)
        return;

    m_sensorFixture->deleteLater();
    m_sensorFixture = 0;
}
<commit_msg>Fix declarative items initialization chain<commit_after>/**
 * Copyright (C) 2012 by INdT
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * @author Rodrigo Goncalves de Oliveira <rodrigo.goncalves@openbossa.org>
 * @author Roger Felipe Zanoni da Silva <roger.zanoni@openbossa.org>
 */

#include "entity.h"

#include "enums.h"
#include "scene.h"
#include "game.h"
#include "behavior.h"
#include "fixture.h"
#include "material.h"

Entity::Entity(Scene *parent)
    : Box2DBaseItem(parent)
    , m_updateInterval(0)
    , m_scene(0)
    , m_behavior(0)
    , m_body(0)
    , m_linearDamping(0.0f)
    , m_angularDamping(0.0f)
    , m_bodyType(Quasi::StaticBodyType)
    , m_bullet(false)
    , m_sleepingAllowed(true)
    , m_fixedRotation(false)
    , m_active(true)
    , m_sensorFixture(0)
{
    setTransformOrigin(Center);
    connect(this, SIGNAL(rotationChanged()), SLOT(onRotationChanged()));
}

Entity::~Entity()
{
    if (!m_world || !m_body)
        return;

#if QT_VERSION >= 0x050000
    QQuickItem *child;
#else
    QGraphicsItem *child;
#endif

    foreach (child, childItems())
        if (Fixture *fixture = dynamic_cast<Fixture *>(child))
            delete fixture;

    m_worldPtr->DestroyBody(m_body);
    m_body = 0;
}

void Entity::update(const int &delta)
{
    if ((m_updateInterval && m_updateTime.elapsed() >= m_updateInterval)
        || !m_updateInterval) {
        m_updateTime.restart();
        if (m_behavior) {
            m_behavior->setDelta(delta);
            m_behavior->setEntity(this);
            m_behavior->update(delta);
            m_behavior->setEntity(0);
        }
    }

#if QT_VERSION >= 0x050000
    QQuickItem *child;
#else
    QGraphicsItem *child;
#endif
    foreach (child, childItems())
        if (Entity *item = dynamic_cast<Entity *>(child))
            item->update(delta);
}

int Entity::updateInterval() const
{
    return m_updateInterval;
}

void Entity::setUpdateInterval(const int &updateInterval)
{
    if (m_updateInterval != updateInterval) {
        m_updateInterval = updateInterval;

        emit updateIntervalChanged();

        m_updateTime.restart();
    }
}

Scene *Entity::scene() const
{
    return m_scene;
}

void Entity::setScene(Scene *scene)
{
    m_scene = scene;
}

Game *Entity::game() const
{
    if (m_scene)
        return m_scene->game();

    return 0;
}

Behavior *Entity::behavior() const
{
    return m_behavior;
}

void Entity::setBehavior(Behavior *behavior)
{
    if (m_behavior == behavior)
        return;

    m_behavior = behavior;

    emit behaviorChanged();
}

void Entity::componentComplete()
{
    Box2DBaseItem::componentComplete();

    if (!m_initialized)
        initialize();
}

b2Body *Entity::body() const
{
    return m_body;
}

void Entity::onRotationChanged()
{
    if (!m_synchronizing && m_body) {
        m_body->SetTransform(m_body->GetPosition(),
                             (rotation() * 2 * b2_pi) / -360.0);
    }
}

/*
 * Shamelessly stolen from qml-box2d project at gitorious
 *
 * https://gitorious.org/qml-box2d/qml-box2d
 */
void Entity::initialize()
{
    if (m_initialized || !m_world)
        return;

    b2BodyDef bodyDef;
    bodyDef.type = static_cast<b2BodyType>(m_bodyType);
    bodyDef.position.Set((x() + width() / 2.0) / m_scaleRatio,
                         (-y() - height() / 2.0) / m_scaleRatio);

    bodyDef.angle = -(rotation() * (2 * b2_pi)) / 360.0;
    bodyDef.linearDamping = m_linearDamping;
    bodyDef.angularDamping = m_angularDamping;
    bodyDef.bullet = m_bullet;
    bodyDef.allowSleep = m_sleepingAllowed;
    bodyDef.fixedRotation = m_fixedRotation;

    m_body = m_worldPtr->CreateBody(&bodyDef);

    initializeFixtures();

    m_initialized = true;
}

qreal Entity::linearDamping() const
{
    return m_linearDamping;
}

void Entity::setLinearDamping(const qreal &linearDamping)
{
    if (m_linearDamping != linearDamping) {
        m_linearDamping = linearDamping;

        if (m_body)
            m_body->SetLinearDamping(linearDamping);

        emit linearDampingChanged();
    }
}

qreal Entity::angularDamping() const
{
    return m_angularDamping;
}

void Entity::setAngularDamping(const qreal &angularDamping)
{
    if (m_angularDamping != angularDamping) {
        m_angularDamping = angularDamping;

        if (m_body)
            m_body->SetAngularDamping(angularDamping);

        emit angularDampingChanged();
    }
}

Quasi::BodyType Entity::bodyType() const
{
    return m_bodyType;
}

void Entity::setBodyType(const Quasi::BodyType &bodyType)
{
    if (m_bodyType != bodyType) {
        m_bodyType = bodyType;

        if (m_body)
            m_body->SetType((b2BodyType)bodyType);

        emit bodyTypeChanged();
    }
}

bool Entity::bullet() const
{
    return m_bullet;
}

void Entity::setBullet(const bool &bullet)
{
    if (m_bullet != bullet) {
        m_bullet = bullet;

        if (m_body)
            m_body->SetBullet(bullet);

        emit bulletChanged();
    }
}

bool Entity::sleepingAllowed() const
{
    return m_sleepingAllowed;
}

void Entity::setSleepingAllowed(const bool &sleepingAllowed)
{
    if (m_sleepingAllowed != sleepingAllowed) {
        m_sleepingAllowed = sleepingAllowed;

        if (m_body)
            m_body->SetSleepingAllowed(sleepingAllowed);

        emit sleepingAllowedChanged();
    }
}

bool Entity::fixedRotation() const
{
    return m_fixedRotation;
}

void Entity::setFixedRotation(const bool &fixedRotation)
{
    if (m_fixedRotation != fixedRotation) {
        m_fixedRotation = fixedRotation;

        if (m_body)
            m_body->SetFixedRotation(fixedRotation);

        emit fixedRotationChanged();
    }
}

bool Entity::active() const
{
    return m_active;
}

void Entity::setActive(const bool &active)
{
    if (m_active != active) {
        m_active = active;

        if (m_body)
            m_body->SetActive(active);

        emit activeChanged();
    }
}

void Entity::applyTorque(const float &torque)
{
    if (m_body)
        m_body->ApplyTorque(torque);
}

void Entity::applyLinearImpulse(const QPointF &impulse, const QPointF &point)
{
    if (m_body) {
        m_body->ApplyLinearImpulse(b2Vec2(impulse.x() / m_scaleRatio,
                                          -impulse.y() / m_scaleRatio),
                                   b2Vec2(point.x() / m_scaleRatio,
                                          -point.y() / m_scaleRatio));
    }
}

void Entity::setLinearVelocity(const QPointF &velocity)
{
    if (m_body) {
        m_body->SetLinearVelocity(b2Vec2(velocity.x() / m_scaleRatio,
                                         -velocity.y() / m_scaleRatio));
    }
}

void Entity::setAngularVelocity(const float &velocity)
{
    if (m_body) {
        m_body->SetAngularVelocity(velocity);
    }
}

void Entity::geometryChanged(const QRectF &newGeometry,
                                const QRectF &oldGeometry)
{
    if (!m_synchronizing && m_body) {
        if (newGeometry.topLeft() != oldGeometry.topLeft()) {
            const QPointF pos = newGeometry.topLeft();

            m_body->SetTransform(b2Vec2((pos.x() + width() / 2.0) / m_scaleRatio,
                                        (-pos.y() - height() / 2.0) / m_scaleRatio),
                                 m_body->GetAngle());
        }
    }

#if QT_VERSION >= 0x050000
    QQuickItem::geometryChanged(newGeometry, oldGeometry);
#else
    QDeclarativeItem::geometryChanged(newGeometry, oldGeometry);
#endif
}

b2Vec2 Entity::b2TransformOrigin() const
{
    b2Vec2 vec;
    if (m_body)
        vec = m_body->GetPosition();

    return vec;
}

float Entity::b2Angle() const
{
    float32 angle = 0.0f;
    if (m_body)
        angle = m_body->GetAngle();
    return angle;
}

void Entity::initializeFixtures()
{
#if QT_VERSION >= 0x050000
    QQuickItem *item;
#else
    QGraphicsItem *item;
#endif

    bool createSensor = true;
    foreach (item, childItems()) {
        if (Fixture *fixture = dynamic_cast<Fixture *>(item)) {
            createSensor = false;
            fixture->setWorld(m_world);
            fixture->setBody(this);
            fixture->initialize();
        }
    }

    if (createSensor)
        createSensorFixture();
}

#if QT_VERSION >= 0x050000
void Entity::itemChange(ItemChange change, const ItemChangeData &data)
#else
QVariant Entity::itemChange(GraphicsItemChange change, const QVariant &value)
#endif
{
    if (isComponentComplete() && change == ItemChildAddedChange) {
#if QT_VERSION >= 0x050000
        QQuickItem *child = data.item;
#else
        QGraphicsItem *child = value.value<QGraphicsItem *>();
#endif
        if (Fixture *fixture = dynamic_cast<Fixture *>(child)) {
            destroySensorFixture();
            fixture->setWorld(m_world);
            fixture->setBody(this);
            fixture->initialize();
        }
    }

#if QT_VERSION >= 0x050000
    Box2DBaseItem::itemChange(change, data);
#else
    return Box2DBaseItem::itemChange(change, value);
#endif
}

void Entity::createSensorFixture()
{
    setBodyType(Quasi::DynamicBodyType);
    m_body->SetGravityScale(0);

    m_sensorFixture = new Fixture(this);
    m_sensorFixture->setMaterial(new Material(this));
    m_sensorFixture->setWidth(width());
    m_sensorFixture->setHeight(height());
    m_sensorFixture->setShapeItem(this);
    m_sensorFixture->setWorld(m_world);
    m_sensorFixture->setBody(this);
    m_sensorFixture->setSensor(true);
    m_sensorFixture->updateFixture();
}

void Entity::destroySensorFixture()
{
    if (!m_sensorFixture)
        return;

    m_sensorFixture->deleteLater();
    m_sensorFixture = 0;
}
<|endoftext|>


<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef ERRORS_HPP_
#define ERRORS_HPP_

#include <errno.h>
#include <signal.h>
#include <stdlib.h>

#ifndef DISABLE_BREAKPOINTS
#ifdef __linux__
#if defined __i386 || defined __x86_64
#define BREAKPOINT __asm__ volatile ("int3")
#else   /* not x86/amd64 */
#define BREAKPOINT (raise(SIGTRAP))
#endif  /* x86/amd64 */
#endif /* __linux__ */

#ifdef __MACH__
#define BREAKPOINT (raise(SIGTRAP))
#endif
#else /* Breakpoints Disabled */
#define BREAKPOINT
#endif /* DISABLE_BREAKPOINTS */

#define CT_ASSERT(e) do { enum { compile_time_assert_error = 1/(!!(e)) }; } while (0)

#ifndef NDEBUG
#define DEBUG_ONLY(...) __VA_ARGS__
#define DEBUG_ONLY_CODE(expr) do { expr; } while (0)
#else
#define DEBUG_ONLY(...)
#define DEBUG_ONLY_CODE(expr) ((void)(0))
#endif

#define NORETURN __attribute__((__noreturn__))

/* Accessors to errno.
 * Please access errno *only* through these access functions.
 * Accessing errno directly is unsafe in the context of
 * coroutines because compiler optimizations can interfer with TLS, which
 * might be used for errno.
 * See thread_local.hpp for a more detailed explanation of the issue. */
int get_errno();
void set_errno(int new_errno);
/* The following line can be useful for identifying illegal direct access in our
 * code. However it cannot be turned on in general because some system headers use
 * errno and don't compile with this. */
//#pragma GCC poison errno

/* Error handling
 *
 * There are several ways to report errors in RethinkDB:
 *  fail_due_to_user_error(msg, ...)    fail and report line number/stack trace. Should only be used when the user
 *                                      is at fault (e.g. provided wrong database file name) and it is reasonable to
 *                                      fail instead of handling the problem more gracefully.
 *
 *  The following macros are used only for the cases of programmer error checking. For the time being they are also used
 *  for system error checking (especially the *_err variants).
 *
 *  crash(msg, ...)                 always fails and reports line number and such. Never returns.
 *  crash_or_trap(msg, ...)         same as above, but traps into debugger if it is present instead of terminating.
 *                                  That means that it possibly can return, and one can continue stepping through the code in the debugger.
 *                                  All off the rassert/guarantee functions use crash_or_trap.
 *  rassert(cond)                   makes sure cond is true and is a no-op in release mode
 *  rassert(cond, msg, ...)         ditto, with additional message and possibly some arguments used for formatting
 *  rassert_err(cond)               same as rassert(cond), but also print errno error description
 *  rassert_err(cond, msg, ...)     same as rassert(cond, msg, ...), but also print errno error description
 *  guarantee(cond)                 same as rassert(cond), but the check is still done in release mode. Do not use for expensive checks!
 *  guarantee(cond, msg, ...)       same as rassert(cond, msg, ...), but the check is still done in release mode. Do not use for expensive checks!
 *  guarantee_err(cond)             same as guarantee(cond), but also print errno error description
 *  guarantee_err(cond, msg, ...)   same as guarantee(cond, msg, ...), but also print errno error description
 *  guarantee_xerr(cond, err, msg, ...) same as guarantee_err(cond, msg, ...), but also allows to specify errno as err argument
 *                                  (useful for async io functions, which return negated errno)
 *
 * The names rassert* are used instead of assert* because /usr/include/assert.h undefines assert macro and redefines it with its own version
 * every single time it gets included.
 */

#ifndef NDEBUG
#define DEBUG_VAR
#else
#define DEBUG_VAR __attribute__((unused))
#endif

#define UNUSED __attribute__((unused))

#define MUST_USE __attribute__((warn_unused_result))

#define fail_due_to_user_error(msg, ...) do {  \
        report_user_error(msg, ##__VA_ARGS__); \
        BREAKPOINT;                            \
        exit(EXIT_FAILURE);                    \
    } while (0)

#define crash(msg, ...) do {                                        \
        report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \
        BREAKPOINT; /* this used to be abort(), but it didn't cause VALGRIND to print a backtrace */ \
        abort();                                                    \
    } while (0)

#define crash_1_13_block

#define crash_or_trap(msg, ...) do {                                \
        report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \
        BREAKPOINT;                                                 \
    } while (0)

void report_fatal_error(const char*, int, const char*, ...) __attribute__((format (printf, 3, 4)));
void report_user_error(const char*, ...) __attribute__((format (printf, 1, 2)));

// Our usual crash() method does not work well in out-of-memory conditions, because
// it performs heap-allocations itself. Use `crash_oom()` instead for these cases.
void crash_oom();

// Possibly using buf to store characters, returns a pointer to a strerror-style error string.  This
// has the same contract as the GNU (char *)-returning strerror_r.  The return value is a pointer to
// a nul-terminated string, either equal to buf or pointing at a statically allocated string.
MUST_USE const char *errno_string_maybe_using_buffer(int errsv, char *buf, size_t buflen);

#define stringify(x) #x

#define format_assert_message(assert_type, cond) assert_type " failed: [" stringify(cond) "] "
#define guarantee(cond, msg...) do {    \
        if (!(cond)) {                  \
            crash_or_trap(format_assert_message("Guarantee", cond) msg); \
        }                               \
    } while (0)

#define guarantee_xerr(cond, err, msg, args...) do {                            \
        int guarantee_xerr_errsv = (err);                                       \
        if (!(cond)) {                                                          \
            if (guarantee_xerr_errsv == 0) {                                    \
                crash_or_trap(format_assert_message("Guarantee", cond) msg, ##args); \
            } else {                                                            \
                char guarantee_xerr_buf[250];                                      \
                const char *errstr = errno_string_maybe_using_buffer(guarantee_xerr_errsv, guarantee_xerr_buf, sizeof(guarantee_xerr_buf)); \
                crash_or_trap(format_assert_message("Guarantee", cond) " (errno %d - %s) " msg, guarantee_xerr_errsv, errstr, ##args); \
            }                                                                   \
        }                                                                       \
    } while (0)
#define guarantee_err(cond, msg, args...) guarantee_xerr(cond, get_errno(), msg, ##args)

#define unreachable(msg, ...) crash("Unreachable code: " msg, ##__VA_ARGS__)    // can't use crash_or_trap since code needs to depend on its noreturn property
#define not_implemented(msg, ...) crash_or_trap("Not implemented: " msg, ##__VA_ARGS__)

#ifdef NDEBUG
#define rassert(cond, msg...) ((void)(0))
#define rassert_err(cond, msg...) ((void)(0))
#else
#define rassert(cond, msg...) do {                                        \
        if (!(cond)) {                                                    \
            crash_or_trap(format_assert_message("Assertion", cond) msg);  \
        }                                                                 \
    } while (0)
#define rassert_err(cond, msg, args...) do {                                \
        int rassert_err_errsv = get_errno();                                      \
        if (!(cond)) {                                                      \
            if (rassert_err_errsv == 0) {                                   \
                crash_or_trap(format_assert_message("Assert", cond) msg);   \
            } else {                                                        \
                char rassert_err_buf[250];                                  \
                const char *errstr = errno_string_maybe_using_buffer(rassert_err_errsv, rassert_err_buf, sizeof(rassert_err_buf)); \
                crash_or_trap(format_assert_message("Assert", cond) " (errno %d - %s) " msg, rassert_err_errsv, errstr, ##args);  \
            }                                                               \
        }                                                                   \
    } while (0)
#endif

void install_generic_crash_handler();
void install_new_oom_handler();

// If you include errors.hpp before including a Boost library, then Boost assertion
// failures will be forwarded to the RethinkDB error mechanism.
#define BOOST_ENABLE_ASSERT_HANDLER
namespace boost {
void assertion_failed(char const * expr, char const * function, char const * file, long line);  // NOLINT(runtime/int)
}

#define DISABLE_COPYING(T)                      \
    T(const T&) = delete;                       \
    T& operator=(const T&) = delete

/* Put these after functions to indicate what they throw. In release mode, they
turn into noops so that the compiler doesn't have to generate exception-checking
code everywhere. If you need to add an exception specification for compatibility
with e.g. a virtual method, don't use these, or your code won't compile in
release mode. */
#ifdef NDEBUG
#define THROWS_NOTHING
#define THROWS_ONLY(...)
#else
#define THROWS_NOTHING throw ()
#define THROWS_ONLY(...) throw (__VA_ARGS__)
#endif

// This is a workaround for old versions of boost causing a compilation error
#include <boost/version.hpp> // NOLINT(build/include_order)
#if (BOOST_VERSION >= 104200) && (BOOST_VERSION <= 104399)
#include <boost/config.hpp> // NOLINT(build/include_order)
#undef BOOST_HAS_RVALUE_REFS
#endif

#ifdef __GNUC__
#define GNUC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif

/** RVALUE_THIS
 *
 * This macro is used to annotate methods that treat *this as an
 * rvalue reference. On compilers that support it, it expands to &&
 * and all uses of the method on non-rvlaue *this are reported as
 * errors.
 *
 * The supported compilers are clang >= 2.9 and gcc >= 4.8.1
 *
 **/
#if defined(__clang__)
#if __has_extension(cxx_rvalue_references)
#define RVALUE_THIS &&
#else
#define RVALUE_THIS
#endif
#elif __GNUC__ > 4 || (__GNUC__ == 4 && \
    (__GNUC_MINOR__ > 8 || (__GNUC_MINOR__ == 8 && \
                            __GNUC_PATCHLEVEL__ > 1)))
#define RVALUE_THIS &&
#else
#define RVALUE_THIS
#endif

#if defined(__clang__)
    #if !__has_extension(cxx_override_control)
        #define override
        #define final
    #endif
#elif GNUC_VERSION < 40700
    #define override
    #define final
#endif

#endif /* ERRORS_HPP_ */
<commit_msg>remove dead code<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef ERRORS_HPP_
#define ERRORS_HPP_

#include <errno.h>
#include <signal.h>
#include <stdlib.h>

#ifndef DISABLE_BREAKPOINTS
#ifdef __linux__
#if defined __i386 || defined __x86_64
#define BREAKPOINT __asm__ volatile ("int3")
#else   /* not x86/amd64 */
#define BREAKPOINT (raise(SIGTRAP))
#endif  /* x86/amd64 */
#endif /* __linux__ */

#ifdef __MACH__
#define BREAKPOINT (raise(SIGTRAP))
#endif
#else /* Breakpoints Disabled */
#define BREAKPOINT
#endif /* DISABLE_BREAKPOINTS */

#define CT_ASSERT(e) do { enum { compile_time_assert_error = 1/(!!(e)) }; } while (0)

#ifndef NDEBUG
#define DEBUG_ONLY(...) __VA_ARGS__
#define DEBUG_ONLY_CODE(expr) do { expr; } while (0)
#else
#define DEBUG_ONLY(...)
#define DEBUG_ONLY_CODE(expr) ((void)(0))
#endif

#define NORETURN __attribute__((__noreturn__))

/* Accessors to errno.
 * Please access errno *only* through these access functions.
 * Accessing errno directly is unsafe in the context of
 * coroutines because compiler optimizations can interfer with TLS, which
 * might be used for errno.
 * See thread_local.hpp for a more detailed explanation of the issue. */
int get_errno();
void set_errno(int new_errno);
/* The following line can be useful for identifying illegal direct access in our
 * code. However it cannot be turned on in general because some system headers use
 * errno and don't compile with this. */
//#pragma GCC poison errno

/* Error handling
 *
 * There are several ways to report errors in RethinkDB:
 *  fail_due_to_user_error(msg, ...)    fail and report line number/stack trace. Should only be used when the user
 *                                      is at fault (e.g. provided wrong database file name) and it is reasonable to
 *                                      fail instead of handling the problem more gracefully.
 *
 *  The following macros are used only for the cases of programmer error checking. For the time being they are also used
 *  for system error checking (especially the *_err variants).
 *
 *  crash(msg, ...)                 always fails and reports line number and such. Never returns.
 *  crash_or_trap(msg, ...)         same as above, but traps into debugger if it is present instead of terminating.
 *                                  That means that it possibly can return, and one can continue stepping through the code in the debugger.
 *                                  All off the rassert/guarantee functions use crash_or_trap.
 *  rassert(cond)                   makes sure cond is true and is a no-op in release mode
 *  rassert(cond, msg, ...)         ditto, with additional message and possibly some arguments used for formatting
 *  rassert_err(cond)               same as rassert(cond), but also print errno error description
 *  rassert_err(cond, msg, ...)     same as rassert(cond, msg, ...), but also print errno error description
 *  guarantee(cond)                 same as rassert(cond), but the check is still done in release mode. Do not use for expensive checks!
 *  guarantee(cond, msg, ...)       same as rassert(cond, msg, ...), but the check is still done in release mode. Do not use for expensive checks!
 *  guarantee_err(cond)             same as guarantee(cond), but also print errno error description
 *  guarantee_err(cond, msg, ...)   same as guarantee(cond, msg, ...), but also print errno error description
 *  guarantee_xerr(cond, err, msg, ...) same as guarantee_err(cond, msg, ...), but also allows to specify errno as err argument
 *                                  (useful for async io functions, which return negated errno)
 *
 * The names rassert* are used instead of assert* because /usr/include/assert.h undefines assert macro and redefines it with its own version
 * every single time it gets included.
 */

#ifndef NDEBUG
#define DEBUG_VAR
#else
#define DEBUG_VAR __attribute__((unused))
#endif

#define UNUSED __attribute__((unused))

#define MUST_USE __attribute__((warn_unused_result))

#define fail_due_to_user_error(msg, ...) do {  \
        report_user_error(msg, ##__VA_ARGS__); \
        BREAKPOINT;                            \
        exit(EXIT_FAILURE);                    \
    } while (0)

#define crash(msg, ...) do {                                        \
        report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \
        BREAKPOINT; /* this used to be abort(), but it didn't cause VALGRIND to print a backtrace */ \
        abort();                                                    \
    } while (0)

#define crash_or_trap(msg, ...) do {                                \
        report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \
        BREAKPOINT;                                                 \
    } while (0)

void report_fatal_error(const char*, int, const char*, ...) __attribute__((format (printf, 3, 4)));
void report_user_error(const char*, ...) __attribute__((format (printf, 1, 2)));

// Our usual crash() method does not work well in out-of-memory conditions, because
// it performs heap-allocations itself. Use `crash_oom()` instead for these cases.
void crash_oom();

// Possibly using buf to store characters, returns a pointer to a strerror-style error string.  This
// has the same contract as the GNU (char *)-returning strerror_r.  The return value is a pointer to
// a nul-terminated string, either equal to buf or pointing at a statically allocated string.
MUST_USE const char *errno_string_maybe_using_buffer(int errsv, char *buf, size_t buflen);

#define stringify(x) #x

#define format_assert_message(assert_type, cond) assert_type " failed: [" stringify(cond) "] "
#define guarantee(cond, msg...) do {    \
        if (!(cond)) {                  \
            crash_or_trap(format_assert_message("Guarantee", cond) msg); \
        }                               \
    } while (0)

#define guarantee_xerr(cond, err, msg, args...) do {                            \
        int guarantee_xerr_errsv = (err);                                       \
        if (!(cond)) {                                                          \
            if (guarantee_xerr_errsv == 0) {                                    \
                crash_or_trap(format_assert_message("Guarantee", cond) msg, ##args); \
            } else {                                                            \
                char guarantee_xerr_buf[250];                                      \
                const char *errstr = errno_string_maybe_using_buffer(guarantee_xerr_errsv, guarantee_xerr_buf, sizeof(guarantee_xerr_buf)); \
                crash_or_trap(format_assert_message("Guarantee", cond) " (errno %d - %s) " msg, guarantee_xerr_errsv, errstr, ##args); \
            }                                                                   \
        }                                                                       \
    } while (0)
#define guarantee_err(cond, msg, args...) guarantee_xerr(cond, get_errno(), msg, ##args)

#define unreachable(msg, ...) crash("Unreachable code: " msg, ##__VA_ARGS__)    // can't use crash_or_trap since code needs to depend on its noreturn property
#define not_implemented(msg, ...) crash_or_trap("Not implemented: " msg, ##__VA_ARGS__)

#ifdef NDEBUG
#define rassert(cond, msg...) ((void)(0))
#define rassert_err(cond, msg...) ((void)(0))
#else
#define rassert(cond, msg...) do {                                        \
        if (!(cond)) {                                                    \
            crash_or_trap(format_assert_message("Assertion", cond) msg);  \
        }                                                                 \
    } while (0)
#define rassert_err(cond, msg, args...) do {                                \
        int rassert_err_errsv = get_errno();                                      \
        if (!(cond)) {                                                      \
            if (rassert_err_errsv == 0) {                                   \
                crash_or_trap(format_assert_message("Assert", cond) msg);   \
            } else {                                                        \
                char rassert_err_buf[250];                                  \
                const char *errstr = errno_string_maybe_using_buffer(rassert_err_errsv, rassert_err_buf, sizeof(rassert_err_buf)); \
                crash_or_trap(format_assert_message("Assert", cond) " (errno %d - %s) " msg, rassert_err_errsv, errstr, ##args);  \
            }                                                               \
        }                                                                   \
    } while (0)
#endif

void install_generic_crash_handler();
void install_new_oom_handler();

// If you include errors.hpp before including a Boost library, then Boost assertion
// failures will be forwarded to the RethinkDB error mechanism.
#define BOOST_ENABLE_ASSERT_HANDLER
namespace boost {
void assertion_failed(char const * expr, char const * function, char const * file, long line);  // NOLINT(runtime/int)
}

#define DISABLE_COPYING(T)                      \
    T(const T&) = delete;                       \
    T& operator=(const T&) = delete

/* Put these after functions to indicate what they throw. In release mode, they
turn into noops so that the compiler doesn't have to generate exception-checking
code everywhere. If you need to add an exception specification for compatibility
with e.g. a virtual method, don't use these, or your code won't compile in
release mode. */
#ifdef NDEBUG
#define THROWS_NOTHING
#define THROWS_ONLY(...)
#else
#define THROWS_NOTHING throw ()
#define THROWS_ONLY(...) throw (__VA_ARGS__)
#endif

// This is a workaround for old versions of boost causing a compilation error
#include <boost/version.hpp> // NOLINT(build/include_order)
#if (BOOST_VERSION >= 104200) && (BOOST_VERSION <= 104399)
#include <boost/config.hpp> // NOLINT(build/include_order)
#undef BOOST_HAS_RVALUE_REFS
#endif

#ifdef __GNUC__
#define GNUC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif

/** RVALUE_THIS
 *
 * This macro is used to annotate methods that treat *this as an
 * rvalue reference. On compilers that support it, it expands to &&
 * and all uses of the method on non-rvlaue *this are reported as
 * errors.
 *
 * The supported compilers are clang >= 2.9 and gcc >= 4.8.1
 *
 **/
#if defined(__clang__)
#if __has_extension(cxx_rvalue_references)
#define RVALUE_THIS &&
#else
#define RVALUE_THIS
#endif
#elif __GNUC__ > 4 || (__GNUC__ == 4 && \
    (__GNUC_MINOR__ > 8 || (__GNUC_MINOR__ == 8 && \
                            __GNUC_PATCHLEVEL__ > 1)))
#define RVALUE_THIS &&
#else
#define RVALUE_THIS
#endif

#if defined(__clang__)
    #if !__has_extension(cxx_override_control)
        #define override
        #define final
    #endif
#elif GNUC_VERSION < 40700
    #define override
    #define final
#endif

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


<commit_before>#include <iostream>
#include <vector>
#include <cmath>
#include <data.h>
#include <constants.h>
#include <mesh.h>
#include <initialconditions.h>

using namespace std;

extern vector<node> n;
extern vector<element> e;
extern vector<type1> tp1;
extern vector<type2> tp2;
extern vector<type3> tp3;

void W(int i)
{
  tp1[i].W[0] = e[i].ro;

  tp1[i].W[1] = e[i].ro * e[i].u;

  tp1[i].W[2] = e[i].ro * e[i].v;

  tp1[i].W[3] = e[i].ro * e[i].et;
}

void Fc1(int i)
{
  double fenergyp, fenergym, fmassp, fmassm;

  double ML,MR;

  double VL, VR; //contravariant velocity of right state and left state

  double cL, cR; //speed of sound

  double roL, uL, vL, pL, etL;

  double roR, uR, vR, pR, etR;

  double vnx, vny;

  double Fp[4], Fm[4];

  roL = e[i].ro;
  uL = e[i].u;
  vL = e[i].v;
  pL = e[i].p;
  etL = e[i].et;

  for(int d = 0; d < 4; d++)
    {
      roR = e[e[i].neigh[d]].ro;
      uR = e[e[i].neigh[d]].u;
      vR = e[e[i].neigh[d]].v;
      pR = e[e[i].neigh[d]].p;
      etR = e[e[i].neigh[d]].et;

      vnx = e[i].vn[d].x;
      vny = e[i].vn[d].y;

      VL = vnx * uL + vny * vL;
      VR = vnx * uR + vny * vR;

      cL = sqrt(gama * pL / roL);
      cR = sqrt(gama * pR / roR);

      ML = VL / cL;
      MR = VR / cR;

      if(ML >= 1.)
        {
          Fp[0] = roL * VL;

          Fp[1] = roL * uL * VL + vnx * pL;

          Fp[2] = roL * vL * VL + vny * pL;

          Fp[3] = roL * (etL + pL / roL) * VL;

        }

      else if(abs(ML) < 1)
        {
          fmassp = roL * cL * pow((ML + 1), 2) / 4.;

          fenergyp = fmassp * ((pow(((gama - 1.) * VL + 2. * cL),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uL, 2) + pow(vL, 2) - pow(VL, 2)) / 2.);

          Fp[0] = fmassp;

          Fp[1] = fmassp * (vnx * (-VL + 2. * cL) / gama + uL);

          Fp[2] = fmassp * (vny * (-VL + 2. * cL) / gama + vL);

          Fp[3] = fenergyp;
        }

      else
        {
          Fp[0] = 0;

          Fp[1] = 0;

          Fp[2] = 0;

          Fp[3] = 0;
        }

      if(MR >= 1.)
        {
          Fm[0] = 0;

          Fm[1] = 0;

          Fm[2] = 0;

          Fm[3] = 0;
        }

      else if(abs(MR) < 1)
        {
          fmassm = -roR * cR * pow((MR - 1), 2) / 4.;

          fenergym = fmassm * ((pow(((gama - 1.) * VR - 2. * cR),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uR, 2) + pow(vR, 2) - pow(VR, 2)) / 2.);

          Fm[0] = fmassm;

          Fm[1] = fmassm * (vnx * (-VR - 2. * cR) / gama + uR);

          Fm[2] = fmassm * (vny * (-VR - 2. * cR) / gama + vR);

          Fm[3] = fenergym;
        }

      else
        {
          Fm[0] = roR * VR;

          Fm[1] = roR * uR * VR + vnx * pR;

          Fm[2] = roR * vR * VR + vny * pR;

          Fm[3] = roR * (etR + pR / roR) * VR;
        }

      for(int a = 0; a < 4; a++)
        tp1[i].Fc[d][a] = Fp[a] + Fm[a];
    }

}

void W3(int i, int t)
{
  if(t == 0)
    {
      tp3[i].W[0][t] = e[i].roprev;

      tp3[i].W[1][t] = e[i].roprev * e[i].uprev;

      tp3[i].W[2][t] = e[i].roprev * e[i].vprev;

      tp3[i].W[3][t] = e[i].roprev * e[i].etprev;
    }
  else if(t == 1)
    {
      tp3[i].W[0][t] = e[i].ro;

      tp3[i].W[1][t] = e[i].ro * e[i].u;

      tp3[i].W[2][t] = e[i].ro * e[i].v;

      tp3[i].W[3][t] = e[i].ro * e[i].et;
    }
  else if(t == 2)
    {
      tp3[i].W[0][t] = e[i].ronew;

      tp3[i].W[1][t] = e[i].ronew * e[i].unew;

      tp3[i].W[2][t] = e[i].ronew * e[i].vnew;

      tp3[i].W[3][t] = e[i].ronew * e[i].etnew;
    }

}

void Fc1new(int i)
{
  double fenergyp, fenergym, fmassp, fmassm;

  double ML,MR;

  double VL, VR; //contravariant velocity of right state and left state

  double cL, cR; //speed of sound

  double roL, uL, vL, pL, etL;

  double roR, uR, vR, pR, etR;

  double vnx, vny;

  double Fp[4], Fm[4];

  roL = e[i].ronew;
  uL = e[i].unew;
  vL = e[i].vnew;
  pL = e[i].pnew;
  etL = e[i].etnew;

  for(int d = 0; d < 4; d++)
    {
      roR = e[e[i].neigh[d]].ro;
      uR = e[e[i].neigh[d]].u;
      vR = e[e[i].neigh[d]].v;
      pR = e[e[i].neigh[d]].p;
      etR = e[e[i].neigh[d]].et;

      vnx = e[i].vn[d].x;
      vny = e[i].vn[d].y;

      VL = vnx * uL + vny * vL;
      VR = vnx * uR + vny * vR;

      cL = sqrt(gama * pL / roL);
      cR = sqrt(gama * pR / roR);

      ML = VL / cL;
      MR = VR / cR;

      if(ML >= 1.)
        {
          Fp[0] = roL * VL;

          Fp[1] = roL * uL * VL + vnx * pL;

          Fp[2] = roL * vL * VL + vny * pL;

          Fp[3] = roL * (etL + pL / roL) * VL;

        }

      else if(abs(ML) < 1)
        {
          fmassp = roL * cL * pow((ML + 1), 2) / 4.;

          fenergyp = fmassp * ((pow(((gama - 1.) * VL + 2. * cL),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uL, 2) + pow(vL, 2) - pow(VL, 2)) / 2.);

          Fp[0] = fmassp;

          Fp[1] = fmassp * (vnx * (-VL + 2. * cL) / gama + uL);

          Fp[2] = fmassp * (vny * (-VL + 2. * cL) / gama + vL);

          Fp[3] = fenergyp;
        }

      else
        {
          Fp[0] = 0;

          Fp[1] = 0;

          Fp[2] = 0;

          Fp[3] = 0;
        }

      if(MR >= 1.)
        {
          Fm[0] = 0;

          Fm[1] = 0;

          Fm[2] = 0;

          Fm[3] = 0;
        }

      else if(abs(MR) < 1)
        {
          fmassm = -roR * cR * pow((MR - 1), 2) / 4.;

          fenergym = fmassm * ((pow(((gama - 1.) * VR - 2. * cR),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uR, 2) + pow(vR, 2) - pow(VR, 2)) / 2.);

          Fm[0] = fmassm;

          Fm[1] = fmassm * (vnx * (-VR - 2. * cR) / gama + uR);

          Fm[2] = fmassm * (vny * (-VR - 2. * cR) / gama + vR);

          Fm[3] = fenergym;
        }

      else
        {
          Fm[0] = roR * VR;

          Fm[1] = roR * uR * VR + vnx * pR;

          Fm[2] = roR * vR * VR + vny * pR;

          Fm[3] = roR * (etR + pR / roR) * VR;
        }

      for(int a = 0; a < 4; a++)
        tp1[i].Fc[d][a] = Fp[a] + Fm[a];
    }

}

void Fc1new1(int i)
{

  double fenergyp, fenergym, fmassp, fmassm;

  double ML,MR;

  double VL, VR; //contravariant velocity of right state and left state

  double cL, cR; //speed of sound

  double roL, uL, vL, pL, etL;

  double roR, uR, vR, pR, etR;

  double vnx, vny;

  double Fp[4], Fm[4];

  roL = e[i].ronew;
  uL = e[i].unew;
  vL = e[i].vnew;
  pL = e[i].pnew;
  etL = e[i].etnew;

  for(int d = 0; d < 4; d++)
    {
      roR = e[e[i].neigh[d]].ronew;
      uR = e[e[i].neigh[d]].unew;
      vR = e[e[i].neigh[d]].vnew;
      pR = e[e[i].neigh[d]].pnew;
      etR = e[e[i].neigh[d]].etnew;

      vnx = e[i].vn[d].x;
      vny = e[i].vn[d].y;

      VL = vnx * uL + vny * vL;
      VR = vnx * uR + vny * vR;

      cL = sqrt(gama * pL / roL);
      cR = sqrt(gama * pR / roR);

      ML = VL / cL;
      MR = VR / cR;

      if(ML >= 1.)
        {
          Fp[0] = roL * VL;

          Fp[1] = roL * uL * VL + vnx * pL;

          Fp[2] = roL * vL * VL + vny * pL;

          Fp[3] = roL * (etL + pL / roL) * VL;

        }

      else if(abs(ML) < 1)
        {
          fmassp = roL * cL * pow((ML + 1), 2) / 4.;

          fenergyp = fmassp * ((pow(((gama - 1.) * VL + 2. * cL),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uL, 2) + pow(vL, 2) - pow(VL, 2)) / 2.);

          Fp[0] = fmassp;

          Fp[1] = fmassp * (vnx * (-VL + 2. * cL) / gama + uL);

          Fp[2] = fmassp * (vny * (-VL + 2. * cL) / gama + vL);

          Fp[3] = fenergyp;
        }

      else
        {
          Fp[0] = 0;

          Fp[1] = 0;

          Fp[2] = 0;

          Fp[3] = 0;
        }

      if(MR >= 1.)
        {
          Fm[0] = 0;

          Fm[1] = 0;

          Fm[2] = 0;

          Fm[3] = 0;
        }

      else if(abs(MR) < 1)
        {
          fmassm = -roR * cR * pow((MR - 1), 2) / 4.;

          fenergym = fmassm * ((pow(((gama - 1.) * VR - 2. * cR),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uR, 2) + pow(vR, 2) - pow(VR, 2)) / 2.);

          Fm[0] = fmassm;

          Fm[1] = fmassm * (vnx * (-VR - 2. * cR) / gama + uR);

          Fm[2] = fmassm * (vny * (-VR - 2. * cR) / gama + vR);

          Fm[3] = fenergym;
        }

      else
        {
          Fm[0] = roR * VR;

          Fm[1] = roR * uR * VR + vnx * pR;

          Fm[2] = roR * vR * VR + vny * pR;

          Fm[3] = roR * (etR + pR / roR) * VR;
        }

      for(int a = 0; a < 4; a++)
        tp1[i].Fc[d][a] = Fp[a] + Fm[a];
    }

}

void Fv1(int i)
{
  double ro, u, v, p, et, mu;

  double vnx, vny;

  double gradTx, gradTy, gradux, graduy, gradvx, gradvy, qx, qy;

  double taoxx, taoxy, taoyy;

  for(int d = 0; d < 4; d++)
    {
      vnx = e[i].vn[d].x;
      vny = e[i].vn[d].y;

      ro = (e[i].ro + e[e[i].neigh[d]].ro) / 2.;
      u = (e[i].u + e[e[i].neigh[d]].u) / 2.;
      v = (e[i].v + e[e[i].neigh[d]].v) / 2.;
      p = (e[i].ro + e[e[i].neigh[d]].p) / 2.;
      et = (e[i].et + e[e[i].neigh[d]].et) / 2.;
      mu = (e[i].mu + e[e[i].neigh[d]].mu) / 2.;

      gradux = (e[e[i].neigh[d]].u - e[i].u) / e[i].rm[d] * e[i].r[d].x / e[i].rm[d];

      graduy = (e[e[i].neigh[d]].u - e[i].u) / e[i].rm[d] * e[i].r[d].y / e[i].rm[d];

      gradvx = (e[e[i].neigh[d]].v - e[i].v) / e[i].rm[d] * e[i].r[d].x / e[i].rm[d];

      gradvy = (e[e[i].neigh[d]].v - e[i].v) / e[i].rm[d] * e[i].r[d].y / e[i].rm[d];

      gradTx = (e[e[i].neigh[d]].T - e[i].T) / e[i].rm[d] * e[i].r[d].x / e[i].rm[d];

      gradTy = (e[e[i].neigh[d]].T - e[i].T) / e[i].rm[d] * e[i].r[d].y / e[i].rm[d];

      taoxx = mu / Reinf * (4. / 3. * gradux - 2. / 3. * gradvy);

      taoxy = mu / Reinf * (graduy + gradvx);

      taoyy = mu / Reinf * (4. / 3. * gradvy - 2. / 3. * gradux);

      qx = mu / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTx;

      qy = mu / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTy;

      tp2[i].Fv[d][0] = 0;

      tp2[i].Fv[d][1] = vnx * taoxx + vny * taoxy;

      tp2[i].Fv[d][2] = vnx * taoxy + vny * taoyy;

      tp2[i].Fv[d][3] = vnx * (u * taoxx + v * taoxy + qx) + vny * (u * taoxy + v * taoyy + qy);

    }
}
<commit_msg>Delete fluxes.cpp<commit_after><|endoftext|>


<commit_before>//*********************************************************
//GLFONT.CPP -- glFont routines
//Copyright (c) 1998 Brad Fish
//See glFont.txt for terms of use
//November 10, 1998
//*********************************************************

#include <stdio.h>
#include <malloc.h>
#include <string.h>
extern "C" {
#include <GL/gl.h>
#include <GL/glu.h>
}
#include "glfont.h"

//*********************************************************
//Variables
//*********************************************************

//Current font
GLFONT *glFont;

//*********************************************************
//Functions
//*********************************************************
int glFontCreate (GLFONT *Font, char *FileName, int Tex)
{
	FILE *Input;
	char *TexBytes;
	int Num;

	//Open font file
	if ((Input = fopen(FileName, "rb")) == NULL)
		return FALSE;

	//Read glFont structure
	fread(Font, sizeof(GLFONT), 1, Input);

	//Save texture number
	Font->Tex = Tex;

	//Get number of characters
	Num = Font->IntEnd - Font->IntStart + 1;

	//Allocate memory for characters
	if ((Font->Char = (GLFONTCHAR *)malloc(
		sizeof(GLFONTCHAR) * Num)) == NULL)
		return FALSE;

	//Read glFont characters
	fread(Font->Char, sizeof(GLFONTCHAR), Num, Input);

	//Get texture size
	Num = Font->TexWidth * Font->TexHeight * 2;

	//Allocate memory for texture data
	if ((TexBytes = (char *)malloc(Num)) == NULL)
		return FALSE;

	//Read texture data
	fread(TexBytes, sizeof(char), Num, Input);

	//Set texture attributes
	glBindTexture(GL_TEXTURE_2D, Font->Tex);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
		GL_CLAMP);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
		GL_CLAMP);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
		GL_LINEAR);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
		GL_LINEAR);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,
		GL_MODULATE);

	//Create texture
	glTexImage2D(GL_TEXTURE_2D, 0, 2, Font->TexWidth,
		Font->TexHeight, 0, GL_LUMINANCE_ALPHA,
		GL_UNSIGNED_BYTE, (void *)TexBytes);

	//Clean up
	free(TexBytes);
	fclose(Input);

	//Return pointer to new font
	return TRUE;
}
//*********************************************************
void glFontDestroy (GLFONT *Font)
{
	//Free character memory
	free(Font->Char);
}
//*********************************************************
void glFontBegin (GLFONT *Font)
{
	//Save pointer to font structure
	if (Font->Char != NULL)
		glFont = Font;
	else
		glFont = NULL;

	//Bind to font texture
	glBindTexture(GL_TEXTURE_2D, Font->Tex);
}
//*********************************************************
void glFontEnd (void)
{
	//Font no longer current
	glFont = NULL;
}
//*********************************************************
void glFontTextOut (char *String, float x, float y,
	float z)
{
	int Length, i;
	GLFONTCHAR *Char;

	//Return if we don't have a valid glFont
	if (glFont == NULL)
		return;

	//Get length of string
	Length = strlen(String);

	//Begin rendering quads
	glBegin(GL_QUADS);

	//Loop through characters
	for (i = 0; i < Length; i++)
	{
		//Get pointer to glFont character
		Char = &glFont->Char[(int)String[i] -
			glFont->IntStart];

		//Specify vertices and texture coordinates
		glTexCoord2f(Char->tx1, Char->ty1);
		glVertex3f(x, y, z);
		glTexCoord2f(Char->tx1, Char->ty2);
		glVertex3f(x, y - Char->dy, z);
		glTexCoord2f(Char->tx2, Char->ty2);
		glVertex3f(x + Char->dx, y - Char->dy, z);
		glTexCoord2f(Char->tx2, Char->ty1);
		glVertex3f(x + Char->dx, y, z);

		//Move to next character
		x += Char->dx;
	}

	//Stop rendering quads
	glEnd();
}

int glFontTextSize( GLFONT *Font, char *String, float* width, float* height )
{
	int Length, i;
	GLFONTCHAR *Char;
	float x = 0.0f;
	float y = 0.0f;

	//Return if we don't have a valid glFont
	if (Font == NULL)
		return 0;

	//Get length of string
	Length = strlen(String);

	//Loop through characters
	for (i = 0; i < Length; i++)
	{
		//Get pointer to glFont character
		Char = &Font->Char[(int)String[i] -
			Font->IntStart];

		//Move to next character
		x += Char->dx;
		if(Char->dy > y)y = Char->dy;
	}

	*width = x;
	*height = y;

	return 1;
}

//*********************************************************

//End of file

<commit_msg>I made this compile on Visual Studio again.<commit_after>//*********************************************************
//GLFONT.CPP -- glFont routines
//Copyright (c) 1998 Brad Fish
//See glFont.txt for terms of use
//November 10, 1998
//*********************************************************
#ifdef WIN32
#include <windows.h>
#endif

#include <stdio.h>
#include <malloc.h>
#include <string.h>
extern "C" {
#include <GL/gl.h>
#ifdef WIN32
#include <GL/glu.h>
#else
#include <GL/glu.h>
#endif
}
#include "glfont.h"

//*********************************************************
//Variables
//*********************************************************

//Current font
GLFONT *glFont;

//*********************************************************
//Functions
//*********************************************************
int glFontCreate (GLFONT *Font, char *FileName, int Tex)
{
	FILE *Input;
	char *TexBytes;
	int Num;

	//Open font file
	if ((Input = fopen(FileName, "rb")) == NULL)
		return FALSE;

	//Read glFont structure
	fread(Font, sizeof(GLFONT), 1, Input);

	//Save texture number
	Font->Tex = Tex;

	//Get number of characters
	Num = Font->IntEnd - Font->IntStart + 1;

	//Allocate memory for characters
	if ((Font->Char = (GLFONTCHAR *)malloc(
		sizeof(GLFONTCHAR) * Num)) == NULL)
		return FALSE;

	//Read glFont characters
	fread(Font->Char, sizeof(GLFONTCHAR), Num, Input);

	//Get texture size
	Num = Font->TexWidth * Font->TexHeight * 2;

	//Allocate memory for texture data
	if ((TexBytes = (char *)malloc(Num)) == NULL)
		return FALSE;

	//Read texture data
	fread(TexBytes, sizeof(char), Num, Input);

	//Set texture attributes
	glBindTexture(GL_TEXTURE_2D, Font->Tex);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
		GL_CLAMP);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
		GL_CLAMP);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
		GL_LINEAR);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
		GL_LINEAR);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,
		GL_MODULATE);

	//Create texture
	glTexImage2D(GL_TEXTURE_2D, 0, 2, Font->TexWidth,
		Font->TexHeight, 0, GL_LUMINANCE_ALPHA,
		GL_UNSIGNED_BYTE, (void *)TexBytes);

	//Clean up
	free(TexBytes);
	fclose(Input);

	//Return pointer to new font
	return TRUE;
}
//*********************************************************
void glFontDestroy (GLFONT *Font)
{
	//Free character memory
	free(Font->Char);
}
//*********************************************************
void glFontBegin (GLFONT *Font)
{
	//Save pointer to font structure
	if (Font->Char != NULL)
		glFont = Font;
	else
		glFont = NULL;

	//Bind to font texture
	glBindTexture(GL_TEXTURE_2D, Font->Tex);
}
//*********************************************************
void glFontEnd (void)
{
	//Font no longer current
	glFont = NULL;
}
//*********************************************************
void glFontTextOut (char *String, float x, float y,
	float z)
{
	int Length, i;
	GLFONTCHAR *Char;

	//Return if we don't have a valid glFont
	if (glFont == NULL)
		return;

	//Get length of string
	Length = strlen(String);

	//Begin rendering quads
	glBegin(GL_QUADS);

	//Loop through characters
	for (i = 0; i < Length; i++)
	{
		//Get pointer to glFont character
		Char = &glFont->Char[(int)String[i] -
			glFont->IntStart];

		//Specify vertices and texture coordinates
		glTexCoord2f(Char->tx1, Char->ty1);
		glVertex3f(x, y, z);
		glTexCoord2f(Char->tx1, Char->ty2);
		glVertex3f(x, y - Char->dy, z);
		glTexCoord2f(Char->tx2, Char->ty2);
		glVertex3f(x + Char->dx, y - Char->dy, z);
		glTexCoord2f(Char->tx2, Char->ty1);
		glVertex3f(x + Char->dx, y, z);

		//Move to next character
		x += Char->dx;
	}

	//Stop rendering quads
	glEnd();
}

int glFontTextSize( GLFONT *Font, char *String, float* width, float* height )
{
	int Length, i;
	GLFONTCHAR *Char;
	float x = 0.0f;
	float y = 0.0f;

	//Return if we don't have a valid glFont
	if (Font == NULL)
		return 0;

	//Get length of string
	Length = strlen(String);

	//Loop through characters
	for (i = 0; i < Length; i++)
	{
		//Get pointer to glFont character
		Char = &Font->Char[(int)String[i] -
			Font->IntStart];

		//Move to next character
		x += Char->dx;
		if(Char->dy > y)y = Char->dy;
	}

	*width = x;
	*height = y;

	return 1;
}

//*********************************************************

//End of file

<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <serialport/serialport.h>

#define REPLY_SIZE 8
#define TIMEOUT 1000

char* itoa(int value, char* result, int base);

// This example opens the serial port and sends a request 'R' at 1Hz and waits for a reply.
int main(int argc, char** argv)
{
    ros::init(argc, argv, "example_node");
    ros::NodeHandle n;

    cereal::CerealPort device;
    char reply[REPLY_SIZE];

    // Change the next line according to your port name and baud rate
    try{ device.open("/dev/ttyAMA0", 38400); }
    catch(cereal::Exception& e)
    {
        ROS_FATAL("Failed to open the serial port!!!");
        ROS_BREAK();
    }
    ROS_INFO("The serial port is opened.");

    ros::Rate r(1);
    while(ros::ok())
    {
        // Send 'R' over the serial port
        //const char send[] = "\x00\x25";
        //or
        const char send[] = {0x00,0x25};
        device.write(send,2);
        // Get the reply, the last value is the timeout in ms
        try{ device.read(reply, REPLY_SIZE, TIMEOUT); }
        catch(cereal::TimeoutException& e)
        {
            ROS_ERROR("Timeout!");
        }
        ROS_INFO("Got this reply: %i,%i,%i,%i,%i,%i,%i,%i", reply[0], reply[1], reply[2],reply[3], reply[4], reply[5], reply[6], reply[7]);
        unsigned char speed_l;
        speed_l=255;
        const char send1[]={0x00,0x31,speed_l};
        //send[]={0x00,0x31,255};
        device.write(send1,3);

        ros::spinOnce();
        r.sleep();
    }
}

char* itoa(int value, char* result, int base) {
        // check that the base if valid
        if (base < 2 || base > 36) { *result = '\0'; return result; }

        char* ptr = result, *ptr1 = result, tmp_char;
        int tmp_value;

        do {
            tmp_value = value;
            value /= base;
            *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
        } while ( value );

        // Apply negative sign
        if (tmp_value < 0) *ptr++ = '-';
        *ptr-- = '\0';
        while(ptr1 < ptr) {
            tmp_char = *ptr;
            *ptr--= *ptr1;
            *ptr1++ = tmp_char;
        }
        return result;
}
<commit_msg>Update code<commit_after><|endoftext|>