text
stringlengths 5
1.04M
|
|---|
/**********************************************************
DO NOT EDIT
This file was generated from stone specification "files"
Part of "Ardi - the organizer" project.
osoft4ardi@gmail.com
www.prokarpaty.net
***********************************************************/
#include "dropbox/files/FilesSaveCopyReferenceArg.h"
using namespace dropboxQt;
namespace dropboxQt{
namespace files{
///SaveCopyReferenceArg
SaveCopyReferenceArg::operator QJsonObject()const{
QJsonObject js;
this->toJson(js);
return js;
}
void SaveCopyReferenceArg::toJson(QJsonObject& js)const{
if(!m_copy_reference.isEmpty())
js["copy_reference"] = QString(m_copy_reference);
if(!m_path.isEmpty())
js["path"] = QString(m_path);
}
void SaveCopyReferenceArg::fromJson(const QJsonObject& js){
m_copy_reference = js["copy_reference"].toString();
m_path = js["path"].toString();
}
QString SaveCopyReferenceArg::toString(bool multiline)const
{
QJsonObject js;
toJson(js);
QJsonDocument doc(js);
QString s(doc.toJson(multiline ? QJsonDocument::Indented : QJsonDocument::Compact));
return s;
}
std::unique_ptr<SaveCopyReferenceArg> SaveCopyReferenceArg::factory::create(const QByteArray& data)
{
QJsonDocument doc = QJsonDocument::fromJson(data);
QJsonObject js = doc.object();
return create(js);
}
std::unique_ptr<SaveCopyReferenceArg> SaveCopyReferenceArg::factory::create(const QJsonObject& js)
{
std::unique_ptr<SaveCopyReferenceArg> rv;
rv = std::unique_ptr<SaveCopyReferenceArg>(new SaveCopyReferenceArg);
rv->fromJson(js);
return rv;
}
}//files
}//dropboxQt
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// TF Arrow
//
//=============================================================================
#include "cbase.h"
#include "tf_projectile_arrow.h"
#include "soundent.h"
#include "tf_fx.h"
#include "props.h"
#include "baseobject_shared.h"
#include "SpriteTrail.h"
#include "IEffects.h"
#include "te_effect_dispatch.h"
#include "collisionutils.h"
#include "bone_setup.h"
#include "decals.h"
#include "tf_player.h"
#include "tf_gamestats.h"
#include "tf_pumpkin_bomb.h"
#include "tf_weapon_shovel.h"
#include "player_vs_environment/tf_tank_boss.h"
#include "halloween/halloween_base_boss.h"
#include "halloween/merasmus/merasmus_trick_or_treat_prop.h"
#include "tf_logic_robot_destruction.h"
#include "tf_gamerules.h"
#include "bot/tf_bot.h"
#include "tf_weapon_medigun.h"
#include "soundenvelope.h"
//=============================================================================
//
// TF Arrow Projectile functions (Server specific).
//
#define ARROW_MODEL_GIB1 "models/weapons/w_models/w_arrow_gib1.mdl"
#define ARROW_MODEL_GIB2 "models/weapons/w_models/w_arrow_gib2.mdl"
#define ARROW_GRAVITY 0.3f
#define ARROW_THINK_CONTEXT "CTFProjectile_ArrowThink"
#define CLAW_TRAIL_RED "effects/repair_claw_trail_red.vmt"
#define CLAW_TRAIL_BLU "effects/repair_claw_trail_blue.vmt"
#define CLAW_GIB1 "models/weapons/w_models/w_repair_claw_gib1.mdl"
#define CLAW_GIB2 "models/weapons/w_models/w_repair_claw_gib2.mdl"
#define CLAW_REPAIR_EFFECT_BLU "repair_claw_heal_blue"
#define CLAW_REPAIR_EFFECT_RED "repair_claw_heal_red"
//-----------------------------------------------------------------------------
LINK_ENTITY_TO_CLASS( tf_projectile_arrow, CTFProjectile_Arrow );
PRECACHE_WEAPON_REGISTER( tf_projectile_arrow );
IMPLEMENT_NETWORKCLASS_ALIASED( TFProjectile_Arrow, DT_TFProjectile_Arrow )
BEGIN_NETWORK_TABLE( CTFProjectile_Arrow, DT_TFProjectile_Arrow )
SendPropBool( SENDINFO( m_bArrowAlight ) ),
SendPropBool( SENDINFO( m_bCritical ) ),
SendPropInt( SENDINFO( m_iProjectileType ) ),
END_NETWORK_TABLE()
BEGIN_DATADESC( CTFProjectile_Arrow )
DEFINE_THINKFUNC( ImpactThink ),
END_DATADESC()
//-----------------------------------------------------------------------------
LINK_ENTITY_TO_CLASS( tf_projectile_healing_bolt, CTFProjectile_HealingBolt );
PRECACHE_WEAPON_REGISTER( tf_projectile_healing_bolt );
IMPLEMENT_NETWORKCLASS_ALIASED( TFProjectile_HealingBolt, DT_TFProjectile_HealingBolt )
BEGIN_NETWORK_TABLE( CTFProjectile_HealingBolt, DT_TFProjectile_HealingBolt )
END_NETWORK_TABLE()
BEGIN_DATADESC( CTFProjectile_HealingBolt )
END_DATADESC()
//-----------------------------------------------------------------------------
LINK_ENTITY_TO_CLASS( tf_projectile_grapplinghook, CTFProjectile_GrapplingHook );
PRECACHE_WEAPON_REGISTER( tf_projectile_grapplinghook );
IMPLEMENT_NETWORKCLASS_ALIASED( TFProjectile_GrapplingHook, DT_TFProjectile_GrapplingHook )
BEGIN_NETWORK_TABLE( CTFProjectile_GrapplingHook, DT_TFProjectile_GrapplingHook )
END_NETWORK_TABLE()
BEGIN_DATADESC( CTFProjectile_GrapplingHook )
END_DATADESC()
//-----------------------------------------------------------------------------
// Purpose: Helper to set a grappling hook target on all healers of this player
//-----------------------------------------------------------------------------
static void SetMedicsGrapplingHookTarget( CTFPlayer *pTFPlayer, CBaseEntity *pGrappleTarget )
{
int i;
int iNumHealers = pTFPlayer->m_Shared.GetNumHealers();
for ( i = 0 ; i < iNumHealers ; i++ )
{
CTFPlayer *pMedic = ToTFPlayer( pTFPlayer->m_Shared.GetHealerByIndex( i ) );
// Only want medics who are directly healing us with their medigun, not e.g. AoE healers.
if ( pMedic && ToTFPlayer ( pMedic->MedicGetHealTarget() ) == pTFPlayer )
{
pMedic->SetGrapplingHookTarget( pGrappleTarget );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CTFProjectile_Arrow::CTFProjectile_Arrow()
{
m_flImpactTime = 0.0f;
m_flTrailLife = 0.f;
m_pTrail = NULL;
m_bStruckEnemy = false;
m_bArrowAlight = false;
m_iDeflected = 0;
m_bCritical = false;
m_flInitTime = 0;
m_bPenetrate = false;
m_iProjectileType = TF_PROJECTILE_ARROW;
m_iWeaponId = TF_WEAPON_COMPOUND_BOW;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CTFProjectile_Arrow::~CTFProjectile_Arrow()
{
m_HitEntities.Purge();
}
static const char* GetArrowEntityName( ProjectileType_t projectileType )
{
switch ( projectileType )
{
case TF_PROJECTILE_HEALING_BOLT:
case TF_PROJECTILE_FESTIVE_HEALING_BOLT:
#ifdef STAGING_ONLY
case TF_PROJECTILE_MILK_BOLT:
#endif
return "tf_projectile_healing_bolt";
case TF_PROJECTILE_GRAPPLINGHOOK:
return "tf_projectile_grapplinghook";
default:
return "tf_projectile_arrow";
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CTFProjectile_Arrow *CTFProjectile_Arrow::Create( const Vector &vecOrigin, const QAngle &vecAngles, const float fSpeed, const float fGravity, ProjectileType_t projectileType, CBaseEntity *pOwner, CBaseEntity *pScorer )
{
const char* pszArrowEntityName = GetArrowEntityName( projectileType );
CTFProjectile_Arrow *pArrow = static_cast<CTFProjectile_Arrow*>( CBaseEntity::Create( pszArrowEntityName, vecOrigin, vecAngles, pOwner ) );
if ( pArrow )
{
pArrow->InitArrow( vecAngles, fSpeed, fGravity, projectileType, pOwner, pScorer );
}
return pArrow;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::InitArrow( const QAngle &vecAngles, const float fSpeed, const float fGravity, ProjectileType_t projectileType, CBaseEntity *pOwner, CBaseEntity *pScorer )
{
// Initialize the owner.
SetOwnerEntity( pOwner );
// Set team.
ChangeTeam( pOwner->GetTeamNumber() );
// must override projectile type before Spawn for proper model
m_iProjectileType = projectileType;
// Spawn.
Spawn();
SetGravity( fGravity );
SetCritical( true );
// Setup the initial velocity.
Vector vecForward, vecRight, vecUp;
AngleVectors( vecAngles, &vecForward, &vecRight, &vecUp );
Vector vecVelocity = vecForward * fSpeed;
SetAbsVelocity( vecVelocity );
SetupInitialTransmittedGrenadeVelocity( vecVelocity );
// Setup the initial angles.
QAngle angles;
VectorAngles( vecVelocity, angles );
SetAbsAngles( angles );
// Save the scoring player.
SetScorer( pScorer );
// Create a trail.
CreateTrail();
// Add ourselves to the hit entities list so we dont shoot ourselves
m_HitEntities.AddToTail( pOwner->entindex() );
m_flInitTime = gpGlobals->curtime;
#ifdef STAGING_ONLY
if ( m_iProjectileType == TF_PROJECTILE_SNIPERBULLET )
{
CTFPlayer* pTFOwner = ToTFPlayer( pOwner );
m_bFiredWhileZoomed = ( pTFOwner && pTFOwner->m_Shared.InCond( TF_COND_ZOOMED ) );
}
else
#endif // STAGING_ONLY
{
m_bFiredWhileZoomed = false;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::Spawn()
{
if ( m_iProjectileType == TF_PROJECTILE_BUILDING_REPAIR_BOLT )
{
SetModel( g_pszArrowModels[MODEL_ARROW_BUILDING_REPAIR] );
m_iWeaponId = TF_WEAPON_SHOTGUN_BUILDING_RESCUE;
}
else if ( m_iProjectileType == TF_PROJECTILE_FESTIVE_ARROW )
{
SetModel( g_pszArrowModels[MODEL_FESTIVE_ARROW_REGULAR] );
}
else if ( m_iProjectileType == TF_PROJECTILE_HEALING_BOLT
#ifdef STAGING_ONLY
|| m_iProjectileType == TF_PROJECTILE_MILK_BOLT
#endif
) {
SetModel( g_pszArrowModels[MODEL_SYRINGE] );
SetModelScale( 3.0f );
}
else if ( m_iProjectileType == TF_PROJECTILE_FESTIVE_HEALING_BOLT )
{
SetModel( g_pszArrowModels[MODEL_FESTIVE_HEALING_BOLT] );
SetModelScale( 3.0f );
}
#ifdef STAGING_ONLY
else if ( m_iProjectileType == TF_PROJECTILE_SNIPERBULLET )
{
SetModel( g_pszArrowModels[MODEL_SYRINGE] );
//SetModelScale( 3.0f );
}
#endif // STAGING_ONLY
else if ( m_iProjectileType == TF_PROJECTILE_GRAPPLINGHOOK )
{
SetModel( g_pszArrowModels[MODEL_GRAPPLINGHOOK] );
}
else
{
SetModel( g_pszArrowModels[MODEL_ARROW_REGULAR] );
}
SetMoveType( MOVETYPE_FLYGRAVITY, MOVECOLLIDE_FLY_CUSTOM );
UTIL_SetSize( this, Vector( -1.0f, -1.0f, -1.0f ), Vector( 1.0f, 1.0f, 1.0f ) );
SetSolid( SOLID_BBOX );
SetCollisionGroup( TFCOLLISION_GROUP_ROCKETS );
AddEffects( EF_NOSHADOW );
AddFlag( FL_GRENADE );
SetTouch( &CTFProjectile_Arrow::ArrowTouch );
// Set team.
m_nSkin = GetArrowSkin();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::Precache()
{
int arrow_model = PrecacheModel( g_pszArrowModels[MODEL_ARROW_REGULAR] );
int claw_model = PrecacheModel( g_pszArrowModels[MODEL_ARROW_BUILDING_REPAIR] );
int festive_arrow_model = PrecacheModel( g_pszArrowModels[MODEL_FESTIVE_ARROW_REGULAR] );
PrecacheModel( g_pszArrowModels[MODEL_FESTIVE_HEALING_BOLT] );
PrecacheGibsForModel( arrow_model );
PrecacheGibsForModel( claw_model );
PrecacheGibsForModel( festive_arrow_model );
//PrecacheGibsForModel( festive_healing_arrow_model );
PrecacheModel( "effects/arrowtrail_red.vmt" );
PrecacheModel( "effects/arrowtrail_blu.vmt" );
PrecacheModel( "effects/healingtrail_red.vmt" );
PrecacheModel( "effects/healingtrail_blu.vmt" );
PrecacheModel( CLAW_TRAIL_RED );
PrecacheModel( CLAW_TRAIL_BLU );
PrecacheParticleSystem( CLAW_REPAIR_EFFECT_BLU );
PrecacheParticleSystem( CLAW_REPAIR_EFFECT_RED );
PrecacheScriptSound( "Weapon_Arrow.ImpactFlesh" );
PrecacheScriptSound( "Weapon_Arrow.ImpactMetal" );
PrecacheScriptSound( "Weapon_Arrow.ImpactWood" );
PrecacheScriptSound( "Weapon_Arrow.ImpactConcrete" );
PrecacheScriptSound( "Weapon_Arrow.Nearmiss" );
PrecacheScriptSound( "Weapon_Arrow.ImpactFleshCrossbowHeal" );
BaseClass::Precache();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::SetScorer( CBaseEntity *pScorer )
{
m_Scorer = pScorer;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CBasePlayer *CTFProjectile_Arrow::GetScorer( void )
{
return dynamic_cast<CBasePlayer *>( m_Scorer.Get() );
}
//-----------------------------------------------------------------------------
bool CTFProjectile_Arrow::CanHeadshot()
{
CBaseEntity *pOwner = GetScorer();
if ( pOwner == NULL )
return false;
if ( m_iProjectileType == TF_PROJECTILE_BUILDING_REPAIR_BOLT
|| m_iProjectileType == TF_PROJECTILE_HEALING_BOLT
|| m_iProjectileType == TF_PROJECTILE_FESTIVE_HEALING_BOLT
#ifdef STAGING_ONLY
|| m_iProjectileType == TF_PROJECTILE_MILK_BOLT
#endif
) {
return false;
}
#ifdef STAGING_ONLY
if ( m_iProjectileType == TF_PROJECTILE_SNIPERBULLET )
{
return m_bFiredWhileZoomed;
}
#endif // STAGING_ONLY
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Healing bolt damage.
//-----------------------------------------------------------------------------
float CTFProjectile_Arrow::GetDamage()
{
if ( m_iProjectileType == TF_PROJECTILE_HEALING_BOLT
|| m_iProjectileType == TF_PROJECTILE_FESTIVE_HEALING_BOLT
#ifdef STAGING_ONLY
|| m_iProjectileType == TF_PROJECTILE_MILK_BOLT
#endif
) {
float lifeTimeScale = RemapValClamped( gpGlobals->curtime - m_flInitTime, 0.0f, 0.6f, 0.5f, 1.0f );
return m_flDamage * lifeTimeScale;
}
return BaseClass::GetDamage();
}
//-----------------------------------------------------------------------------
// Purpose: Moves the arrow to a particular bbox.
//-----------------------------------------------------------------------------
bool CTFProjectile_Arrow::PositionArrowOnBone( mstudiobbox_t *pBox, CBaseAnimating *pOtherAnim )
{
CStudioHdr *pStudioHdr = pOtherAnim->GetModelPtr();
if ( !pStudioHdr )
return false;
mstudiohitboxset_t *set = pStudioHdr->pHitboxSet( pOtherAnim->GetHitboxSet() );
if ( !set )
return false;
if ( !set->numhitboxes ) // Target must have hit boxes.
return false;
if ( pBox->bone < 0 || pBox->bone >= pStudioHdr->numbones() ) // Bone index must be valid.
return false;
CBoneCache *pCache = pOtherAnim->GetBoneCache();
if ( !pCache )
return false;
matrix3x4_t *bone_matrix = pCache->GetCachedBone( pBox->bone );
if ( !bone_matrix )
return false;
Vector vecBoxAbsMins, vecBoxAbsMaxs;
TransformAABB( *bone_matrix, pBox->bbmin, pBox->bbmax, vecBoxAbsMins, vecBoxAbsMaxs );
// Adjust the arrow so it isn't exactly in the center of the box.
Vector position;
Vector vecDelta = vecBoxAbsMaxs - vecBoxAbsMins;
float frand = (float) rand() / VALVE_RAND_MAX;
position.x = vecBoxAbsMins.x + vecDelta.x*0.6f - vecDelta.x*frand*0.2f;
frand = (float) rand() / VALVE_RAND_MAX;
position.y = vecBoxAbsMins.y + vecDelta.y*0.6f - vecDelta.y*frand*0.2f;
frand = (float) rand() / VALVE_RAND_MAX;
position.z = vecBoxAbsMins.z + vecDelta.z*0.6f - vecDelta.z*frand*0.2f;
SetAbsOrigin( position );
return true;
}
//-----------------------------------------------------------------------------
// Purpose: This was written after PositionArrowOnBone, but the two might be mergable?
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::GetBoneAttachmentInfo( mstudiobbox_t *pBox, CBaseAnimating *pOtherAnim, Vector &bonePosition, QAngle &boneAngles, int &boneIndexAttached, int &physicsBoneIndex )
{
// Find a bone to stick to.
matrix3x4_t arrowWorldSpace;
MatrixCopy( EntityToWorldTransform(), arrowWorldSpace );
// Get the bone info so we can follow the bone.
boneIndexAttached = pBox->bone;
physicsBoneIndex = pOtherAnim->GetPhysicsBone( boneIndexAttached );
matrix3x4_t boneToWorld;
pOtherAnim->GetBoneTransform( boneIndexAttached, boneToWorld );
Vector attachedBonePos;
QAngle attachedBoneAngles;
pOtherAnim->GetBonePosition( boneIndexAttached, attachedBonePos, attachedBoneAngles );
// Transform my current position/orientation into the hit bone's space.
matrix3x4_t worldToBone, localMatrix;
MatrixInvert( boneToWorld, worldToBone );
ConcatTransforms( worldToBone, arrowWorldSpace, localMatrix );
MatrixAngles( localMatrix, boneAngles, bonePosition );
}
//-----------------------------------------------------------------------------
int CTFProjectile_Arrow::GetProjectileType ( void ) const
{
return m_iProjectileType;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CTFProjectile_Arrow::StrikeTarget( mstudiobbox_t *pBox, CBaseEntity *pOther )
{
if ( !pOther )
return false;
// Different path for arrows that heal friendly buildings.
if ( pOther->IsBaseObject() )
{
if ( OnArrowImpactObject( pOther ) )
{
return false;
}
}
// Block and break on invulnerable players
CTFPlayer *pTFPlayerOther = ToTFPlayer( pOther );
if ( pTFPlayerOther && pTFPlayerOther->m_Shared.IsInvulnerable() )
return false;
CBaseAnimating *pOtherAnim = dynamic_cast< CBaseAnimating* >(pOther);
if ( !pOtherAnim )
return false;
bool bBreakArrow = IsBreakable() && ( ( dynamic_cast< CTFTankBoss* >( pOther ) != NULL ) || ( dynamic_cast< CHalloweenBaseBoss* >( pOther ) != NULL ) );
// Position the arrow so its on the bone, within a reasonable region defined by the bbox.
if ( !m_bPenetrate && !bBreakArrow )
{
if ( !PositionArrowOnBone( pBox, pOtherAnim ) )
{
return false;
}
}
//
const Vector &vecOrigin = GetAbsOrigin();
Vector vecVelocity = GetAbsVelocity();
int nDamageCustom = 0;
bool bApplyEffect = true;
int nDamageType = GetDamageType();
// Are we a headshot?
bool bHeadshot = false;
if ( pBox->group == HITGROUP_HEAD && CanHeadshot() )
{
bHeadshot = true;
}
// Damage the entity we struck.
CBaseEntity *pAttacker = GetScorer();
if ( !pAttacker )
{
// likely not launched by a player
pAttacker = GetOwnerEntity();
}
if ( pAttacker )
{
// Check if we have the penetrate attribute. We don't want
// to strike the same target multiple times.
if ( m_bPenetrate )
{
// Don't strike the same target again
if ( m_HitEntities.Find( pOther->entindex() ) != m_HitEntities.InvalidIndex() )
{
bApplyEffect = false;
}
else
{
m_HitEntities.AddToTail( pOther->entindex() );
}
}
if ( !InSameTeam( pOther ) )
{
IScorer *pScorerInterface = dynamic_cast<IScorer*>( pAttacker );
if ( pScorerInterface )
{
pAttacker = pScorerInterface->GetScorer();
}
if ( m_bArrowAlight )
{
nDamageType |= DMG_IGNITE;
nDamageCustom = TF_DMG_CUSTOM_FLYINGBURN;
}
if ( bHeadshot )
{
nDamageType |= DMG_CRITICAL;
nDamageCustom = TF_DMG_CUSTOM_HEADSHOT;
}
if ( m_bCritical )
{
nDamageType |= DMG_CRITICAL;
}
#ifdef GAME_DLL
if ( TFGameRules()->IsPVEModeControlled( pAttacker ) )
{
// scenario bots cant crit (unless they always do)
CTFBot *bot = ToTFBot( pAttacker );
if ( !bot || !bot->HasAttribute( CTFBot::ALWAYS_CRIT ) )
{
nDamageType &= ~DMG_CRITICAL;
}
}
#endif
// Damage
if ( bApplyEffect )
{
// Apply Milk First so we can get health from this
if ( m_bApplyMilkOnHit && pOther->IsPlayer() )
{
CTFPlayer *pVictim = ToTFPlayer( pOther );
if ( pVictim && pVictim->m_Shared.CanBeDebuffed() && pVictim->CanGetWet() )
{
// duration is based on damage
float flDuration = RemapValClamped( GetDamage(), 25.0f, 75.0f, 6.0f, 10.0f );
pVictim->m_Shared.AddCond( TF_COND_MAD_MILK, flDuration, pAttacker );
pVictim->m_Shared.SetPeeAttacker( ToTFPlayer( pAttacker ) );
pVictim->SpeakConceptIfAllowed( MP_CONCEPT_JARATE_HIT );
}
}
CTakeDamageInfo info( this, pAttacker, m_hLauncher, vecVelocity, vecOrigin, GetDamage(), nDamageType, nDamageCustom );
pOther->TakeDamage( info );
// Play an impact sound.
ImpactSound( "Weapon_Arrow.ImpactFlesh", true );
}
}
else if ( pOther->IsPlayer() ) // Hit a team-mate.
{
// Heal
if ( bApplyEffect )
{
ImpactTeamPlayer( dynamic_cast<CTFPlayer*>( pOther ) );
}
}
}
if ( !m_bPenetrate && !bBreakArrow )
{
OnArrowImpact( pBox, pOther, pAttacker );
}
// Perform a blood mesh decal trace.
trace_t tr;
Vector start = vecOrigin - vecVelocity * gpGlobals->frametime;
Vector end = vecOrigin + vecVelocity * gpGlobals->frametime;
CTraceFilterCollisionArrows filter( this, GetOwnerEntity() );
UTIL_TraceLine( start, end, CONTENTS_HITBOX|CONTENTS_MONSTER|CONTENTS_SOLID, &filter, &tr );
UTIL_ImpactTrace( &tr, 0 );
// Break it?
if ( bBreakArrow )
{
return false;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::OnArrowImpact( mstudiobbox_t *pBox, CBaseEntity *pOther, CBaseEntity *pAttacker )
{
CBaseAnimating *pOtherAnim = dynamic_cast< CBaseAnimating* >(pOther);
if ( !pOtherAnim )
return;
const Vector &vecOrigin = GetAbsOrigin();
Vector vecVelocity = GetAbsVelocity();
Vector bonePosition = vec3_origin;
QAngle boneAngles = QAngle(0,0,0);
int boneIndexAttached = -1;
int physicsBoneIndex = -1;
GetBoneAttachmentInfo( pBox, pOtherAnim, bonePosition, boneAngles, boneIndexAttached, physicsBoneIndex );
bool bSendImpactMessage = true;
// Did we kill the target?
if ( !pOther->IsAlive() && pOther->IsPlayer() )
{
CTFPlayer *pTFPlayerOther = dynamic_cast<CTFPlayer*>(pOther);
if ( pTFPlayerOther && pTFPlayerOther->m_hRagdoll )
{
VectorNormalize( vecVelocity );
if ( CheckRagdollPinned( vecOrigin, vecVelocity, boneIndexAttached, physicsBoneIndex, pTFPlayerOther->m_hRagdoll, pBox->group, pTFPlayerOther->entindex() ) )
{
pTFPlayerOther->StopRagdollDeathAnim();
bSendImpactMessage = false;
}
}
}
// Notify relevant clients of an arrow impact.
if ( bSendImpactMessage )
{
IGameEvent * event = gameeventmanager->CreateEvent( "arrow_impact" );
if ( event )
{
event->SetInt( "attachedEntity", pOther->entindex() );
event->SetInt( "shooter", pAttacker ? pAttacker->entindex() : 0 );
event->SetInt( "attachedEntity", pOther->entindex() );
event->SetInt( "boneIndexAttached", boneIndexAttached );
event->SetFloat( "bonePositionX", bonePosition.x );
event->SetFloat( "bonePositionY", bonePosition.y );
event->SetFloat( "bonePositionZ", bonePosition.z );
event->SetFloat( "boneAnglesX", boneAngles.x );
event->SetFloat( "boneAnglesY", boneAngles.y );
event->SetFloat( "boneAnglesZ", boneAngles.z );
event->SetInt( "projectileType", GetProjectileType() );
gameeventmanager->FireEvent( event );
}
}
FadeOut( 3.0 );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CTFProjectile_Arrow::OnArrowImpactObject( CBaseEntity *pOther )
{
if ( InSameTeam( pOther ) )
{
BuildingHealingArrow( pOther );
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::ImpactThink( void )
{
}
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::BuildingHealingArrow( CBaseEntity *pOther )
{
// This arrow impacted a building
// If its a building on our team, heal it
if ( !pOther->IsBaseObject() )
return;
CBaseEntity *pAttacker = GetScorer();
if ( pAttacker == NULL )
return;
// if not on our team, forget about it
if ( GetTeamNumber() != pOther->GetTeamNumber() )
return;
int iArrowsHealBuildings = 0;
CALL_ATTRIB_HOOK_INT_ON_OTHER( pAttacker, iArrowsHealBuildings, arrow_heals_buildings );
if ( iArrowsHealBuildings == 0 )
return;
CBaseObject *pBuilding = dynamic_cast< CBaseObject * >( pOther );
if ( !pBuilding || !pBuilding->CanBeRepaired() || pBuilding->HasSapper() || pBuilding->IsPlasmaDisabled() || pBuilding->IsBuilding() || pBuilding->IsPlacing() )
return;
// if building is sheilded, reduce health gain
if ( pBuilding->GetShieldLevel() == SHIELD_NORMAL )
{
iArrowsHealBuildings *= SHIELD_NORMAL_VALUE;
}
float flNewHealth = MIN( pBuilding->GetMaxHealth(), (int)pBuilding->GetHealth() + iArrowsHealBuildings );
int iHealthAdded = (int)(flNewHealth - pBuilding->GetHealth());
if ( iHealthAdded > 0 )
{
pBuilding->SetHealth( flNewHealth );
IGameEvent * event = gameeventmanager->CreateEvent( "building_healed" );
if ( event )
{
// HLTV event priority, not transmitted
event->SetInt( "priority", 1 );
// Healed by another player.
event->SetInt( "building", pBuilding->entindex() );
event->SetInt( "healer", pAttacker->entindex() );
event->SetInt( "amount", iHealthAdded );
gameeventmanager->FireEvent( event );
}
const char *pParticleName = GetTeamNumber() == TF_TEAM_BLUE ? CLAW_REPAIR_EFFECT_BLU : CLAW_REPAIR_EFFECT_RED;
CPVSFilter filter( GetAbsOrigin() );
TE_TFParticleEffect( filter, 0.0, pParticleName, GetAbsOrigin(), vec3_angle );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CTFProjectile_Arrow::GetArrowSkin() const
{
int nTeam = GetTeamNumber();
if ( GetOwnerEntity() && GetOwnerEntity()->IsPlayer() )
{
CTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() );
if ( pOwner && pOwner->IsPlayerClass( TF_CLASS_SPY ) && pOwner->m_Shared.InCond( TF_COND_DISGUISED ) )
{
nTeam = pOwner->m_Shared.GetDisguiseTeam();
}
}
return ( nTeam == TF_TEAM_BLUE ) ? 1 : 0;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::OnArrowMissAllPlayers()
{
CTFPlayer* pOwner = ToTFPlayer( GetOwnerEntity() );
if( pOwner && pOwner->IsPlayerClass( TF_CLASS_SNIPER ) )
{
EconEntity_OnOwnerKillEaterEventNoPartner( assert_cast<CEconEntity *>( m_hLauncher.Get() ), pOwner, kKillEaterEvent_NEGATIVE_SniperShotsMissed );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::ArrowTouch( CBaseEntity *pOther )
{
// Safety net hack:
// We routinely introduce new entity types, and arrows
// are repeat-offenders at not getting along with them.
// If enough time goes by, just remove the arrow.
float flAliveTime = gpGlobals->curtime - m_flInitTime;
if ( flAliveTime >= 10.f )
{
Warning( "Arrow alive for %f3.2\n seconds", flAliveTime );
UTIL_Remove( this );
}
if ( m_bStruckEnemy || (GetMoveType() == MOVETYPE_NONE) )
return;
if ( !pOther )
return;
bool bShield = pOther->IsCombatItem() && !InSameTeam( pOther );
CTFPumpkinBomb *pPumpkinBomb = dynamic_cast< CTFPumpkinBomb * >( pOther );
if ( pOther->IsSolidFlagSet( FSOLID_TRIGGER | FSOLID_VOLUME_CONTENTS ) && !pPumpkinBomb && !bShield )
return;
// test against combat characters, which include players, engineer buildings, and NPCs
CBaseCombatCharacter *pOtherCombatCharacter = dynamic_cast< CBaseCombatCharacter * >( pOther );
if ( !pOtherCombatCharacter )
{
// It might be a track train with boss parented
pOtherCombatCharacter = dynamic_cast< CBaseCombatCharacter * >( pOther->FirstMoveChild() );
if ( pOtherCombatCharacter )
{
pOther = pOtherCombatCharacter;
}
}
CTFMerasmusTrickOrTreatProp *pMerasmusProp = dynamic_cast< CTFMerasmusTrickOrTreatProp* >( pOther );
CTFRobotDestruction_Robot *pRobot = dynamic_cast< CTFRobotDestruction_Robot* >( pOther );
if ( pOther->IsWorld() || ( !pOtherCombatCharacter && !pPumpkinBomb && !pMerasmusProp && !bShield && !pRobot ) )
{
// Check to see if we struck the skybox.
CheckSkyboxImpact( pOther );
// If we've only got 1 entity in the hit list (the attacker by default) and we've not been deflected
// then we can consider this arrow to have completely missed all players.
if( m_HitEntities.Count() == 1 && GetDeflected() == 0 )
{
OnArrowMissAllPlayers();
}
return;
}
CBaseAnimating *pAnimOther = dynamic_cast<CBaseAnimating*>(pOther);
CStudioHdr *pStudioHdr = NULL;
mstudiohitboxset_t *set = NULL;
if ( pAnimOther )
{
pStudioHdr = pAnimOther->GetModelPtr();
if ( pStudioHdr )
{
set = pStudioHdr->pHitboxSet( pAnimOther->GetHitboxSet() );
}
}
if ( !pAnimOther || !pStudioHdr || !set )
{
// Whatever we hit doesn't have hitboxes. Ignore it.
UTIL_Remove( this );
return;
}
// We struck the collision box of a player or a buildable object.
// Trace forward to see if we struck a hitbox.
CTraceFilterCollisionArrows filter( this, GetOwnerEntity() );
Vector start = GetAbsOrigin();
Vector vel = GetAbsVelocity();
trace_t tr;
UTIL_TraceLine( start, start + vel * gpGlobals->frametime, CONTENTS_HITBOX|CONTENTS_MONSTER|CONTENTS_SOLID, &filter, &tr );
// If we hit a hitbox, stop tracing.
mstudiobbox_t *closest_box = NULL;
if ( tr.m_pEnt && tr.m_pEnt->GetTeamNumber() != GetTeamNumber() )
{
// This means the arrow was true and was flying directly at a hitbox on the target.
// We'll attach to that hitbox.
closest_box = set->pHitbox( tr.hitbox );
}
if ( !closest_box )
{
// Locate the hitbox closest to our point of impact on the collision box.
Vector position, start, forward;
QAngle angles;
float closest_dist = 99999;
// Intense, but extremely accurate:
AngleVectors( GetAbsAngles(), &forward );
start = GetAbsOrigin() + forward*16;
for ( int i = 0; i < set->numhitboxes; i++ )
{
mstudiobbox_t *pbox = set->pHitbox( i );
pAnimOther->GetBonePosition( pbox->bone, position, angles );
Ray_t ray;
ray.Init( start, position );
trace_t tr;
IntersectRayWithBox( ray, position+pbox->bbmin, position+pbox->bbmax, 0.f, &tr );
float dist = tr.endpos.DistTo( start );
if ( dist < closest_dist )
{
closest_dist = dist;
closest_box = pbox;
}
}
}
if ( closest_box )
{
// See if we're supposed to stick in the target.
bool bStrike = StrikeTarget( closest_box, pOther );
if ( bStrike && !m_bPenetrate)
{
// If we're here, it means StrikeTarget() called FadeOut( 3.0 )
SetAbsOrigin( start );
}
if ( !bStrike || bShield )
{
BreakArrow();
}
// Slightly confusing. If we're here, the arrow stopped at the
// target and will fade or break. Setting this prevents the
// touch code from re-running during the delay.
if ( !m_bPenetrate )
{
m_bStruckEnemy = true;
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::CheckSkyboxImpact( CBaseEntity *pOther )
{
trace_t tr;
Vector velDir = GetAbsVelocity();
VectorNormalize( velDir );
Vector vecSpot = GetAbsOrigin() - velDir * 32;
UTIL_TraceLine( vecSpot, vecSpot + velDir * 64, MASK_SOLID, this, COLLISION_GROUP_DEBRIS, &tr );
if ( tr.fraction < 1.0 && tr.surface.flags & SURF_SKY )
{
// We hit the skybox, go away soon.
FadeOut( 3.f );
return;
}
if ( !pOther->IsWorld() )
{
BreakArrow();
}
else
{
CEffectData data;
data.m_vOrigin = tr.endpos;
data.m_vNormal = velDir;
data.m_nEntIndex = 0;/*tr.fraction != 1.0f;*/
data.m_nAttachmentIndex = 0;
data.m_nMaterial = 0;
data.m_fFlags = GetProjectileType();
data.m_nColor = GetArrowSkin();
DispatchEffect( "TFBoltImpact", data );
FadeOut( 3.f );
// Play an impact sound.
const char* pszSoundName = "Weapon_Arrow.ImpactMetal";
surfacedata_t *psurf = physprops->GetSurfaceData( tr.surface.surfaceProps );
if ( psurf )
{
switch ( psurf->game.material )
{
case CHAR_TEX_GRATE:
case CHAR_TEX_METAL:
pszSoundName = "Weapon_Arrow.ImpactMetal";
break;
case CHAR_TEX_CONCRETE:
pszSoundName = "Weapon_Arrow.ImpactConcrete";
break;
case CHAR_TEX_WOOD:
pszSoundName = "Weapon_Arrow.ImpactWood";
break;
}
}
ImpactSound( pszSoundName );
}
}
//-----------------------------------------------------------------------------
// Purpose: Plays an impact sound. Louder for the attacker.
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::ImpactSound( const char *pszSoundName, bool bLoudForAttacker )
{
CTFPlayer *pAttacker = ToTFPlayer( GetScorer() );
if ( !pAttacker )
return;
if ( bLoudForAttacker )
{
float soundlen = 0;
EmitSound_t params;
params.m_flSoundTime = 0;
params.m_pSoundName = pszSoundName;
params.m_pflSoundDuration = &soundlen;
CPASFilter filter( GetAbsOrigin() );
filter.RemoveRecipient( ToTFPlayer(pAttacker) );
EmitSound( filter, entindex(), params );
CSingleUserRecipientFilter attackerFilter( ToTFPlayer(pAttacker) );
EmitSound( attackerFilter, pAttacker->entindex(), params );
}
else
{
EmitSound( pszSoundName );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::BreakArrow()
{
FadeOut( 3.f );
CPVSFilter filter( GetAbsOrigin() );
UserMessageBegin( filter, "BreakModel" );
WRITE_SHORT( GetModelIndex() );
WRITE_VEC3COORD( GetAbsOrigin() );
WRITE_ANGLES( GetAbsAngles() );
WRITE_SHORT( m_nSkin );
MessageEnd();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CTFProjectile_Arrow::CheckRagdollPinned( const Vector &start, const Vector &vel, int boneIndexAttached, int physicsBoneIndex, CBaseEntity *pOther, int iHitGroup, int iVictim )
{
// Pin to the wall.
trace_t tr;
UTIL_TraceLine( start, start + vel * 125, MASK_BLOCKLOS, NULL, COLLISION_GROUP_NONE, &tr );
if ( tr.fraction != 1.0f && tr.DidHitWorld() )
{
CEffectData data;
data.m_vOrigin = tr.endpos;
data.m_vNormal = vel;
data.m_nEntIndex = pOther->entindex();
data.m_nAttachmentIndex = boneIndexAttached;
data.m_nMaterial = physicsBoneIndex;
data.m_nDamageType = iHitGroup;
data.m_nSurfaceProp = iVictim;
data.m_fFlags = GetProjectileType();
data.m_nColor = GetArrowSkin();
if ( GetScorer() )
{
data.m_nHitBox = GetScorer()->entindex();
}
DispatchEffect( "TFBoltImpact", data );
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::FadeOut( int iTime )
{
SetMoveType( MOVETYPE_NONE );
SetAbsVelocity( vec3_origin );
AddSolidFlags( FSOLID_NOT_SOLID );
AddEffects( EF_NODRAW );
// Start remove timer.
SetContextThink( &CTFProjectile_Arrow::RemoveThink, gpGlobals->curtime + iTime, "ARROW_REMOVE_THINK" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::RemoveThink( void )
{
UTIL_Remove( this );
}
//-----------------------------------------------------------------------------
const char *CTFProjectile_Arrow::GetTrailParticleName( void )
{
if ( m_iProjectileType == TF_PROJECTILE_BUILDING_REPAIR_BOLT )
{
return ( GetTeamNumber() == TF_TEAM_RED ) ? CLAW_TRAIL_RED : CLAW_TRAIL_BLU;
}
else if ( m_iProjectileType == TF_PROJECTILE_HEALING_BOLT || m_iProjectileType == TF_PROJECTILE_FESTIVE_HEALING_BOLT )
{
return ( GetTeamNumber() == TF_TEAM_RED ) ? "effects/healingtrail_red.vmt" : "effects/healingtrail_blu.vmt";
}
return ( GetTeamNumber() == TF_TEAM_RED ) ? "effects/arrowtrail_red.vmt" : "effects/arrowtrail_blu.vmt";
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::CreateTrail( void )
{
if ( IsDormant() )
return;
if ( !m_pTrail )
{
int width = 3;
switch ( m_iProjectileType )
{
case TF_PROJECTILE_BUILDING_REPAIR_BOLT:
width = 5;
break;
case TF_PROJECTILE_HEALING_BOLT:
case TF_PROJECTILE_FESTIVE_HEALING_BOLT:
case TF_PROJECTILE_GRAPPLINGHOOK:
#ifdef STAGING_ONLY
case TF_PROJECTILE_SNIPERBULLET:
#endif // STAGING_ONLY
return; // do not create arrow trail for healing bolt, use particle instead (client only)
}
const char *pTrailTeamName = GetTrailParticleName();
CSpriteTrail *pTempTrail = NULL;
pTempTrail = CSpriteTrail::SpriteTrailCreate( pTrailTeamName, GetAbsOrigin(), true );
pTempTrail->FollowEntity( this );
pTempTrail->SetTransparency( kRenderTransAlpha, 255, 255, 255, 255, kRenderFxNone );
pTempTrail->SetStartWidth( width );
pTempTrail->SetTextureResolution( 1.0f / ( 96.0f * 1.0f ) );
pTempTrail->SetLifeTime( 0.3 );
pTempTrail->TurnOn();
pTempTrail->SetAttachment( this, 0 );
m_pTrail = pTempTrail;
SetContextThink( &CTFProjectile_Arrow::RemoveTrail, gpGlobals->curtime + 3, "FadeTrail");
}
}
//-----------------------------------------------------------------------------
// Purpose: Fade and kill the trail
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::RemoveTrail( void )
{
if ( !m_pTrail )
return;
if ( m_pTrail )
{
if ( m_flTrailLife <= 0 )
{
UTIL_Remove( m_pTrail );
m_flTrailLife = 1.0f;
}
else
{
float fAlpha = 128 * m_flTrailLife;
CSpriteTrail *pTempTrail = dynamic_cast< CSpriteTrail*>( m_pTrail.Get() );
if ( pTempTrail )
{
pTempTrail->SetBrightness( int(fAlpha) );
}
m_flTrailLife = m_flTrailLife - 0.1f;
SetContextThink( &CTFProjectile_Arrow::RemoveTrail, gpGlobals->curtime + 0.05, "FadeTrail");
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::AdjustDamageDirection( const CTakeDamageInfo &info, Vector &dir, CBaseEntity *pEnt )
{
if ( pEnt )
{
dir = info.GetDamagePosition() - info.GetDamageForce() - pEnt->WorldSpaceCenter();
}
}
//-----------------------------------------------------------------------------
// Purpose: Arrow was deflected.
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::IncrementDeflected( void )
{
m_iDeflected++;
// Change trail color.
if ( m_pTrail )
{
UTIL_Remove( m_pTrail );
m_pTrail = NULL;
m_flTrailLife = 1.0f;
}
CreateTrail();
}
//-----------------------------------------------------------------------------
// Purpose: Arrow was deflected.
//-----------------------------------------------------------------------------
void CTFProjectile_Arrow::Deflected( CBaseEntity *pDeflectedBy, Vector &vecDir )
{
CTFPlayer *pTFDeflector = ToTFPlayer( pDeflectedBy );
if ( !pTFDeflector )
return;
ChangeTeam( pTFDeflector->GetTeamNumber() );
SetLauncher( pTFDeflector->GetActiveWeapon() );
CTFPlayer* pOldOwner = ToTFPlayer( GetOwnerEntity() );
SetOwnerEntity( pTFDeflector );
if ( pOldOwner )
{
pOldOwner->SpeakConceptIfAllowed( MP_CONCEPT_DEFLECTED, "projectile:1,victim:1" );
}
if ( pTFDeflector->m_Shared.IsCritBoosted() )
{
SetCritical( true );
}
CTFWeaponBase::SendObjectDeflectedEvent( pTFDeflector, pOldOwner, GetWeaponID(), this );
IncrementDeflected();
SetScorer( pTFDeflector );
// Purge our hit list so we can hit everyone again
m_HitEntities.Purge();
// Add ourselves so we dont hit ourselves
m_HitEntities.AddToTail( pTFDeflector->entindex() );
}
//-----------------------------------------------------------------------------
// Purpose: Setup function.
//-----------------------------------------------------------------------------
void CTFProjectile_HealingBolt::InitArrow( const QAngle &vecAngles, const float fSpeed, const float fGravity, ProjectileType_t projectileType, CBaseEntity *pOwner, CBaseEntity *pScorer )
{
BaseClass::InitArrow( vecAngles, fSpeed, fGravity, projectileType, pOwner, pScorer );
//SetNextThink( gpGlobals->curtime );
}
//-----------------------------------------------------------------------------
// Purpose: Healing bolt heal.
//-----------------------------------------------------------------------------
void CTFProjectile_HealingBolt::ImpactTeamPlayer( CTFPlayer *pOther )
{
if ( !pOther )
return;
#ifdef STAGING_ONLY
// Milk Arrows only heal teammates on special shot
if ( GetProjectileType() == TF_PROJECTILE_MILK_BOLT && !m_bApplyMilkOnHit )
return;
#endif
CTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() );
if ( !pOwner )
return;
// Don't heal players using a weapon that blocks healing
CTFWeaponBase *pWeapon = pOther->GetActiveTFWeapon();
if ( pWeapon )
{
int iBlockHealing = 0;
CALL_ATTRIB_HOOK_INT_ON_OTHER( pWeapon, iBlockHealing, weapon_blocks_healing );
if ( iBlockHealing )
return;
}
float flHealth = GetDamage() * 2.0f;
#ifdef STAGING_ONLY
// Milk Arrows give a resist bubble on hitting a teammate
if ( GetProjectileType() == TF_PROJECTILE_MILK_BOLT )
{
// use damage to scale time
float flResistDuration = RemapValClamped( flHealth, 0, 150, 1, 3 );
pOther->m_Shared.AddCond( TF_COND_MEDIGUN_UBER_BULLET_RESIST, flResistDuration, pOwner );
pOther->m_Shared.AddCond( TF_COND_MEDIGUN_UBER_BLAST_RESIST, flResistDuration, pOwner );
pOther->m_Shared.AddCond( TF_COND_MEDIGUN_UBER_FIRE_RESIST, flResistDuration, pOwner );
}
#endif
// Scale this if needed
CALL_ATTRIB_HOOK_FLOAT_ON_OTHER( pOther, flHealth, mult_healing_from_medics );
int iActualHealed = pOther->TakeHealth( flHealth, DMG_GENERIC );
if ( iActualHealed <= 0 )
return;
// Play an impact sound.
ImpactSound( "Weapon_Arrow.ImpactFleshCrossbowHeal" );
CTF_GameStats.Event_PlayerHealedOther( pOwner, flHealth );
IGameEvent * event = gameeventmanager->CreateEvent( "player_healed" );
if ( event )
{
// HLTV event priority, not transmitted
event->SetInt( "priority", 1 );
// Healed by another player.
event->SetInt( "patient", pOther->GetUserID() );
event->SetInt( "healer", pOwner->GetUserID() );
event->SetInt( "amount", flHealth );
gameeventmanager->FireEvent( event );
}
event = gameeventmanager->CreateEvent( "player_healonhit" );
if ( event )
{
event->SetInt( "amount", flHealth );
event->SetInt( "entindex", pOther->entindex() );
item_definition_index_t healingItemDef = INVALID_ITEM_DEF_INDEX;
if ( pWeapon && pWeapon->GetAttributeContainer() && pWeapon->GetAttributeContainer()->GetItem() )
{
healingItemDef = pWeapon->GetAttributeContainer()->GetItem()->GetItemDefIndex();
}
event->SetInt( "weapon_def_index", healingItemDef );
gameeventmanager->FireEvent( event );
}
event = gameeventmanager->CreateEvent( "crossbow_heal" );
if ( event )
{
event->SetInt( "healer", pOwner->GetUserID() );
event->SetInt( "target", pOther->GetUserID() );
event->SetInt( "amount", flHealth );
gameeventmanager->FireEvent( event );
}
// Give a litte bit of uber based on actual healing
// Give them a little bit of Uber
CWeaponMedigun *pMedigun = static_cast<CWeaponMedigun *>( pOwner->Weapon_OwnsThisID( TF_WEAPON_MEDIGUN ) );
if ( pMedigun )
{
// On Mediguns, per frame, the amount of uber added is based on
// Default heal rate is 24per second, we scale based on that and frametime
pMedigun->AddCharge( ( iActualHealed / 24.0f ) * gpGlobals->frametime );
}
pOther->m_Shared.AddCond( TF_COND_HEALTH_OVERHEALED, 1.2f );
EconEntity_OnOwnerKillEaterEvent_Batched( dynamic_cast<CEconEntity *>( GetLauncher() ), pOwner, pOther, kKillEaterEvent_AllyHealingDone, flHealth );
}
CTFProjectile_GrapplingHook::CTFProjectile_GrapplingHook()
: m_pImpactFleshSoundLoop( NULL )
{
}
//-----------------------------------------------------------------------------
// Purpose: Spawn
//-----------------------------------------------------------------------------
void CTFProjectile_GrapplingHook::Spawn()
{
BaseClass::Spawn();
SetMoveType( MOVETYPE_FLY, MOVECOLLIDE_FLY_CUSTOM );
}
void CTFProjectile_GrapplingHook::Precache()
{
BaseClass::Precache();
PrecacheModel( "models/weapons/c_models/c_grapple_proj/c_grapple_proj.mdl" );
PrecacheScriptSound( "WeaponGrapplingHook.ImpactFlesh" );
PrecacheScriptSound( "WeaponGrapplingHook.ImpactDefault" );
PrecacheScriptSound( "WeaponGrapplingHook.ImpactFleshLoop" );
}
//-----------------------------------------------------------------------------
// Purpose: Spawn
//-----------------------------------------------------------------------------
void CTFProjectile_GrapplingHook::UpdateOnRemove()
{
// clear hook target
CTFPlayer *pTFPlayer = ToTFPlayer( GetOwnerEntity() );
if ( pTFPlayer )
{
// Clear any healers grappling with us
SetMedicsGrapplingHookTarget( pTFPlayer, NULL );
pTFPlayer->SetGrapplingHookTarget( NULL );
pTFPlayer->m_Shared.RemoveCond( TF_COND_GRAPPLINGHOOK );
}
StopImpactFleshSoundLoop();
BaseClass::UpdateOnRemove();
}
//-----------------------------------------------------------------------------
// Purpose: Setup function.
//-----------------------------------------------------------------------------
void CTFProjectile_GrapplingHook::InitArrow( const QAngle &vecAngles, const float fSpeed, const float fGravity, ProjectileType_t projectileType, CBaseEntity *pOwner, CBaseEntity *pScorer )
{
BaseClass::InitArrow( vecAngles, fSpeed, fGravity, projectileType, pOwner, pScorer );
CTFPlayer *pTFPlayer = ToTFPlayer( pOwner );
if ( pTFPlayer )
{
pTFPlayer->m_Shared.AddCond( TF_COND_GRAPPLINGHOOK );
}
}
//-----------------------------------------------------------------------------
// Purpose: OnArrowImpact
//-----------------------------------------------------------------------------
void CTFProjectile_GrapplingHook::OnArrowImpact( mstudiobbox_t *pBox, CBaseEntity *pOther, CBaseEntity *pAttacker )
{
HookTarget( pOther );
}
//-----------------------------------------------------------------------------
// Purpose: OnArrowImpactObject
//-----------------------------------------------------------------------------
bool CTFProjectile_GrapplingHook::OnArrowImpactObject( CBaseEntity *pOther )
{
HookTarget( pOther );
return true;
}
//-----------------------------------------------------------------------------
// Purpose: CheckSkyboxImpact
//-----------------------------------------------------------------------------
void CTFProjectile_GrapplingHook::CheckSkyboxImpact( CBaseEntity *pOther )
{
trace_t tr;
Vector velDir = GetAbsVelocity();
VectorNormalize( velDir );
Vector vecSpot = GetAbsOrigin() - velDir * 32;
UTIL_TraceLine( vecSpot, vecSpot + velDir * 64, MASK_SOLID, this, COLLISION_GROUP_DEBRIS, &tr );
if ( tr.fraction < 1.0 && tr.surface.flags & SURF_SKY )
{
// We hit the skybox, go away soon.
FadeOut( 1.f );
return;
}
if ( !pOther->IsWorld() )
{
HookTarget( pOther );
}
else
{
HookTarget( pOther );
// rotate the hook model to be perpendicular to the world surface
Vector vUp;
AngleVectors( GetAbsAngles(), NULL, NULL, &vUp );
QAngle qNewAngles;
VectorAngles( -tr.plane.normal, vUp, qNewAngles );
SetAbsAngles( qNewAngles );
SetAbsOrigin( GetAbsOrigin() + 3.f * tr.plane.normal );
}
}
//-----------------------------------------------------------------------------
// Purpose: HookTarget
//-----------------------------------------------------------------------------
void CTFProjectile_GrapplingHook::HookTarget( CBaseEntity *pOther )
{
if ( !GetOwnerEntity() || !pOther )
return;
CTFPlayer *pTFPlayer = ToTFPlayer( GetOwnerEntity() );
if ( !pTFPlayer || pTFPlayer->GetGrapplingHookTarget() )
return;
CBaseEntity *pTarget = pOther->IsWorld() ? this : pOther;
const char *pszSoundName = NULL;
if ( pTarget->IsPlayer() )
{
pszSoundName = "WeaponGrapplingHook.ImpactFlesh";
}
else
{
pszSoundName = "WeaponGrapplingHook.ImpactDefault";
}
ImpactSound( pszSoundName );
pTFPlayer->SetGrapplingHookTarget( pTarget, true );
// Grapple any medics to us
SetMedicsGrapplingHookTarget( pTFPlayer, pTFPlayer );
// Stop moving!
if ( pOther->IsPlayer() )
{
FollowEntity( pOther, false );
StartImpactFleshSoundLoop();
}
else
SetMoveType( MOVETYPE_NONE );
SetContextThink( &CTFProjectile_GrapplingHook::HookLatchedThink, gpGlobals->curtime + 0.1f, "HookLatchedThink" );
}
//-----------------------------------------------------------------------------
// Purpose: HookLatchedThink
//-----------------------------------------------------------------------------
void CTFProjectile_GrapplingHook::HookLatchedThink()
{
// if owner is dead, remove the hook
CTFPlayer *pTFPlayer = ToTFPlayer( GetOwnerEntity() );
if ( !pTFPlayer || !pTFPlayer->IsAlive() )
{
UTIL_Remove( this );
return;
}
// if the target nolonger exist or target player is dead, remove the hook
CBaseEntity *pHookTarget = pTFPlayer->GetGrapplingHookTarget();
if ( !pHookTarget || ( pHookTarget->IsPlayer() && !pHookTarget->IsAlive() ) )
{
UTIL_Remove( this );
return;
}
SetContextThink( &CTFProjectile_GrapplingHook::HookLatchedThink, gpGlobals->curtime + 0.1f, "HookLatchedThink" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFProjectile_GrapplingHook::StartImpactFleshSoundLoop()
{
CSoundEnvelopeController &controller = CSoundEnvelopeController::GetController();
CPASAttenuationFilter filter( this );
m_pImpactFleshSoundLoop = controller.SoundCreate( filter, entindex(), "WeaponGrapplingHook.ImpactFleshLoop" );
controller.Play( m_pImpactFleshSoundLoop, 1.0, 100 );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFProjectile_GrapplingHook::StopImpactFleshSoundLoop()
{
if ( m_pImpactFleshSoundLoop )
{
CSoundEnvelopeController &controller = CSoundEnvelopeController::GetController();
controller.SoundDestroy( m_pImpactFleshSoundLoop );
m_pImpactFleshSoundLoop = NULL;
}
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/controls/progress_bar.h"
#include <algorithm>
#include <cmath>
#include <memory>
#include <string>
#include "base/check_op.h"
#include "base/i18n/number_formatting.h"
#include "cc/paint/paint_flags.h"
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/gfx/animation/linear_animation.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
// In DP, the amount to round the corners of the progress bar (both bg and
// fg, aka slice).
constexpr int kCornerRadius = 3;
constexpr int kSmallCornerRadius = 1;
// Adds a rectangle to the path. The corners will be rounded with regular corner
// radius if the progress bar height is larger than the regular corner radius.
// Otherwise the corners will be rounded with the small corner radius if there
// is room for it.
void AddPossiblyRoundRectToPath(const gfx::Rect& rectangle,
bool allow_round_corner,
SkPath* path) {
if (!allow_round_corner || rectangle.height() < kSmallCornerRadius) {
path->addRect(gfx::RectToSkRect(rectangle));
} else if (rectangle.height() < kCornerRadius) {
path->addRoundRect(gfx::RectToSkRect(rectangle), kSmallCornerRadius,
kSmallCornerRadius);
} else {
path->addRoundRect(gfx::RectToSkRect(rectangle), kCornerRadius,
kCornerRadius);
}
}
int RoundToPercent(double fractional_value) {
return static_cast<int>(fractional_value * 100);
}
} // namespace
ProgressBar::ProgressBar(int preferred_height, bool allow_round_corner)
: preferred_height_(preferred_height),
allow_round_corner_(allow_round_corner) {
SetFlipCanvasOnPaintForRTLUI(true);
}
ProgressBar::~ProgressBar() = default;
void ProgressBar::GetAccessibleNodeData(ui::AXNodeData* node_data) {
node_data->role = ax::mojom::Role::kProgressIndicator;
if (IsIndeterminate())
node_data->RemoveStringAttribute(ax::mojom::StringAttribute::kValue);
else
node_data->SetValue(base::FormatPercent(RoundToPercent(current_value_)));
}
gfx::Size ProgressBar::CalculatePreferredSize() const {
// The width will typically be ignored.
gfx::Size pref_size(1, preferred_height_);
gfx::Insets insets = GetInsets();
pref_size.Enlarge(insets.width(), insets.height());
return pref_size;
}
void ProgressBar::VisibilityChanged(View* starting_from, bool is_visible) {
MaybeNotifyAccessibilityValueChanged();
}
void ProgressBar::AddedToWidget() {
MaybeNotifyAccessibilityValueChanged();
}
void ProgressBar::OnPaint(gfx::Canvas* canvas) {
if (IsIndeterminate())
return OnPaintIndeterminate(canvas);
gfx::Rect content_bounds = GetContentsBounds();
// Draw background.
SkPath background_path;
AddPossiblyRoundRectToPath(content_bounds, allow_round_corner_,
&background_path);
cc::PaintFlags background_flags;
background_flags.setStyle(cc::PaintFlags::kFill_Style);
background_flags.setAntiAlias(true);
background_flags.setColor(GetBackgroundColor());
canvas->DrawPath(background_path, background_flags);
// Draw slice.
SkPath slice_path;
const int slice_width = static_cast<int>(
content_bounds.width() * std::min(current_value_, 1.0) + 0.5);
if (slice_width < 1)
return;
gfx::Rect slice_bounds = content_bounds;
slice_bounds.set_width(slice_width);
AddPossiblyRoundRectToPath(slice_bounds, allow_round_corner_, &slice_path);
cc::PaintFlags slice_flags;
slice_flags.setStyle(cc::PaintFlags::kFill_Style);
slice_flags.setAntiAlias(true);
slice_flags.setColor(GetForegroundColor());
canvas->DrawPath(slice_path, slice_flags);
}
double ProgressBar::GetValue() const {
return current_value_;
}
void ProgressBar::SetValue(double value) {
double adjusted_value = (value < 0.0 || value > 1.0) ? -1.0 : value;
if (adjusted_value == current_value_)
return;
current_value_ = adjusted_value;
if (IsIndeterminate()) {
indeterminate_bar_animation_ = std::make_unique<gfx::LinearAnimation>(this);
indeterminate_bar_animation_->SetDuration(base::Seconds(2));
indeterminate_bar_animation_->Start();
} else {
indeterminate_bar_animation_.reset();
OnPropertyChanged(¤t_value_, kPropertyEffectsPaint);
}
MaybeNotifyAccessibilityValueChanged();
}
SkColor ProgressBar::GetForegroundColor() const {
if (foreground_color_)
return foreground_color_.value();
return GetColorProvider()->GetColor(ui::kColorProgressBar);
}
void ProgressBar::SetForegroundColor(SkColor color) {
if (foreground_color_ == color)
return;
foreground_color_ = color;
OnPropertyChanged(&foreground_color_, kPropertyEffectsPaint);
}
SkColor ProgressBar::GetBackgroundColor() const {
return background_color_.value_or(
color_utils::BlendTowardMaxContrast(GetForegroundColor(), 0xCC));
}
void ProgressBar::SetBackgroundColor(SkColor color) {
if (background_color_ == color)
return;
background_color_ = color;
OnPropertyChanged(&background_color_, kPropertyEffectsPaint);
}
void ProgressBar::AnimationProgressed(const gfx::Animation* animation) {
DCHECK_EQ(animation, indeterminate_bar_animation_.get());
DCHECK(IsIndeterminate());
SchedulePaint();
}
void ProgressBar::AnimationEnded(const gfx::Animation* animation) {
DCHECK_EQ(animation, indeterminate_bar_animation_.get());
// Restarts animation.
if (IsIndeterminate())
indeterminate_bar_animation_->Start();
}
bool ProgressBar::IsIndeterminate() {
return current_value_ < 0.0;
}
void ProgressBar::OnPaintIndeterminate(gfx::Canvas* canvas) {
gfx::Rect content_bounds = GetContentsBounds();
// Draw background.
SkPath background_path;
AddPossiblyRoundRectToPath(content_bounds, allow_round_corner_,
&background_path);
cc::PaintFlags background_flags;
background_flags.setStyle(cc::PaintFlags::kFill_Style);
background_flags.setAntiAlias(true);
background_flags.setColor(GetBackgroundColor());
canvas->DrawPath(background_path, background_flags);
// Draw slice.
SkPath slice_path;
double time = indeterminate_bar_animation_->GetCurrentValue();
// The animation spec corresponds to the material design lite's parameter.
// (cf. https://github.com/google/material-design-lite/)
double bar1_left;
double bar1_width;
double bar2_left;
double bar2_width;
if (time < 0.50) {
bar1_left = time / 2;
bar1_width = time * 1.5;
bar2_left = 0;
bar2_width = 0;
} else if (time < 0.75) {
bar1_left = time * 3 - 1.25;
bar1_width = 0.75 - (time - 0.5) * 3;
bar2_left = 0;
bar2_width = time - 0.5;
} else {
bar1_left = 1;
bar1_width = 0;
bar2_left = (time - 0.75) * 4;
bar2_width = 0.25 - (time - 0.75);
}
int bar1_start_x = std::round(content_bounds.width() * bar1_left);
int bar1_end_x = std::round(content_bounds.width() *
std::min(1.0, bar1_left + bar1_width));
int bar2_start_x = std::round(content_bounds.width() * bar2_left);
int bar2_end_x = std::round(content_bounds.width() *
std::min(1.0, bar2_left + bar2_width));
gfx::Rect slice_bounds = content_bounds;
slice_bounds.set_x(content_bounds.x() + bar1_start_x);
slice_bounds.set_width(bar1_end_x - bar1_start_x);
AddPossiblyRoundRectToPath(slice_bounds, allow_round_corner_, &slice_path);
slice_bounds.set_x(content_bounds.x() + bar2_start_x);
slice_bounds.set_width(bar2_end_x - bar2_start_x);
AddPossiblyRoundRectToPath(slice_bounds, allow_round_corner_, &slice_path);
cc::PaintFlags slice_flags;
slice_flags.setStyle(cc::PaintFlags::kFill_Style);
slice_flags.setAntiAlias(true);
slice_flags.setColor(GetForegroundColor());
canvas->DrawPath(slice_path, slice_flags);
}
void ProgressBar::MaybeNotifyAccessibilityValueChanged() {
if (!GetWidget() || !GetWidget()->IsVisible() ||
RoundToPercent(current_value_) == last_announced_percentage_) {
return;
}
last_announced_percentage_ = RoundToPercent(current_value_);
NotifyAccessibilityEvent(ax::mojom::Event::kValueChanged, true);
}
BEGIN_METADATA(ProgressBar, View)
ADD_PROPERTY_METADATA(SkColor, ForegroundColor, ui::metadata::SkColorConverter)
ADD_PROPERTY_METADATA(SkColor, BackgroundColor, ui::metadata::SkColorConverter)
END_METADATA
} // namespace views
|
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/mlir/disc/disc_compiler.h"
#include <fstream>
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/CodeGen/CommandFlags.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Target/TargetMachine.h"
#include "mlir-hlo/Dialect/mhlo/transforms/passes.h"
#include "mlir/Conversion/AffineToStandard/AffineToStandard.h"
#include "mlir/Conversion/GPUToNVVM/GPUToNVVMPass.h"
#include "mlir/Conversion/GPUToROCDL/GPUToROCDLPass.h"
#include "mlir/Conversion/SCFToGPU/SCFToGPUPass.h"
#include "mlir/Conversion/SCFToStandard/SCFToStandard.h"
#include "mlir/Conversion/ShapeToStandard/ShapeToStandard.h" // from @llvm-project
#include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h"
#include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h"
#include "mlir/Dialect/GPU/Passes.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/MemRef/Transforms/Passes.h"
#include "mlir/Dialect/Shape/Transforms/Passes.h"
#include "mlir/Dialect/StandardOps/Transforms/Passes.h"
#include "mlir/Dialect/Tensor/Transforms/Passes.h"
#include "mlir/ExecutionEngine/ExecutionEngine.h"
#include "mlir/ExecutionEngine/OptUtils.h"
#include "mlir/IR/AsmState.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/MLIRContext.h" // from @llvm-project
#include "mlir/Parser.h" // from @llvm-project
#include "mlir/Pass/PassManager.h"
#include "mlir/Support/FileUtilities.h" // from @llvm-project
#include "mlir/Support/Timing.h" // from @llvm-project
#include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h" // from @llvm-project
#include "mlir/Target/LLVMIR/Dialect/NVVM/NVVMToLLVMIRTranslation.h" // from @llvm-project
#include "mlir/Target/LLVMIR/Dialect/ROCDL/ROCDLToLLVMIRTranslation.h" // from @llvm-project
#include "mlir/Target/LLVMIR/Export.h" // from @llvm-project
#include "mlir/Transforms/Passes.h"
#include "tensorflow/compiler/mlir/disc/disc_util.h"
#include "tensorflow/compiler/mlir/disc/transforms/codegen_utils.h"
#include "tensorflow/compiler/mlir/disc/transforms/passes.h"
#include "tensorflow/compiler/mlir/disc/transforms/placement_utils.h"
#include "tensorflow/compiler/mlir/disc/transforms/rewriters.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/compile_mlir_util.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"
#include "tensorflow/core/util/env_var.h"
using mlir::FuncOp;
namespace mlir {
namespace disc_ral {
namespace {
void DumpLLVMModule(llvm::Module* m) {
std::string str;
llvm::raw_string_ostream OS(str);
OS << *m;
OS.flush();
llvm::dbgs() << str << "\n";
}
LogicalResult RewriteLLVMModule(llvm::Module* m) {
auto& ctx = m->getContext();
auto result_type = llvm::Type::getVoidTy(ctx);
std::vector<llvm::Type*> arg_types;
arg_types.push_back(llvm::Type::getInt8Ty(ctx)->getPointerTo());
arg_types.push_back(llvm::Type::getInt8Ty(ctx)->getPointerTo());
arg_types.push_back(
llvm::Type::getInt8Ty(ctx)->getPointerTo()->getPointerTo());
auto func_type = llvm::FunctionType::get(result_type, arg_types, false);
auto ral_call = m->getOrInsertFunction("disc_ral_call", func_type);
llvm::Function* func = llvm::cast<llvm::Function>(ral_call.getCallee());
auto args = func->arg_begin();
auto ctx_struct = args++;
auto api_name = args++;
auto api_args = args;
auto block = llvm::BasicBlock::Create(ctx, "entry", func);
llvm::IRBuilder<> b(block);
auto typed_ctx_struct = b.CreateBitOrPointerCast(
ctx_struct, llvm::Type::getInt8Ty(ctx)->getPointerTo()->getPointerTo());
auto real_ctx = b.CreateLoad(typed_ctx_struct);
auto untyped_real_func = b.CreateConstGEP1_32(typed_ctx_struct, 1);
auto real_func = b.CreateLoad(b.CreateBitOrPointerCast(
untyped_real_func, func_type->getPointerTo()->getPointerTo()));
auto first_arg = b.CreateLoad(api_args);
auto untyped_first_arg = b.CreateBitOrPointerCast(
first_arg, llvm::Type::getInt8Ty(ctx)->getPointerTo()->getPointerTo());
b.CreateStore(real_ctx, untyped_first_arg);
b.CreateCall(func_type, real_func, {real_ctx, api_name, api_args});
b.CreateRetVoid();
return success();
}
std::unique_ptr<llvm::TargetMachine> GetTargetMachine(llvm::Module* module) {
auto tmBuilderOrError = llvm::orc::JITTargetMachineBuilder::detectHost();
if (!tmBuilderOrError) {
llvm::errs() << "Failed to create a JITTargetMachineBuilder for the host\n";
return nullptr;
}
auto tmOrError = tmBuilderOrError->createTargetMachine();
if (!tmOrError) {
llvm::errs() << "Failed to create a TargetMachine for the host\n";
return nullptr;
}
return std::move(*tmOrError);
}
} // namespace
CpuLoweringOptions::CpuLoweringOptions(bool init_from_env_vars) {
if (init_from_env_vars) {
initFromEnvVars();
}
}
void CpuLoweringOptions::initFromEnvVars() {
tensorflow::ReadInt64FromEnvVar("DISC_CPU_FAST_MATH_LEVEL", fast_math_level,
&fast_math_level);
tensorflow::ReadInt64FromEnvVar("DISC_CPU_VECTOR_WIDTH", vector_width,
&vector_width);
tensorflow::ReadBoolFromEnvVar("DISC_CPU_DISABLE_LOOP_UNROLL",
disable_loop_unroll, &disable_loop_unroll);
tensorflow::ReadBoolFromEnvVar("DISC_CPU_ASSUME_NO_BUFFER_ALIAS",
assume_no_buffer_alias,
&assume_no_buffer_alias);
tensorflow::ReadBoolFromEnvVar("DISC_CPU_ENABLE_MULTI_THREAD",
target_multi_threading,
&target_multi_threading);
}
LogicalResult LowerHLOToLLVM(ModuleOp m, const DISCLoweringOptions& options) {
DefaultTimingManager tm;
applyDefaultTimingManagerCLOptions(tm);
TimingScope timing = tm.getRootScope();
PassManager pm(m.getContext());
applyPassManagerCLOptions(pm);
pm.enableTiming(timing);
pm.getContext()->disableMultithreading();
// make sure some dependent dialects are loaded.
mlir::DialectRegistry registry;
mlir::registerLLVMDialectTranslation(registry);
mlir::registerNVVMDialectTranslation(registry);
mlir::registerROCDLDialectTranslation(registry);
m.getContext()->appendDialectRegistry(registry);
bool gpu_enabled = (options.mode == CodeGenMode::kGpuCentric);
auto printingFlags = OpPrintingFlags();
printingFlags.elideLargeElementsAttrs(16);
pm.enableIRPrinting(
/*shouldPrintBeforePass=*/nullptr,
/*shouldPrintAfterPass=*/
[](Pass* pass, Operation*) { return VLOG_IS_ON(1); },
/*printModuleScope=*/false,
/*printAfterOnlyOnChange=*/true,
/*printAfterOnlyOnFailure*/ false, llvm::dbgs(), printingFlags);
pm.addPass(mlir::createInlinerPass());
// TODO(disc): Lower HLO shape constraints instead of eliding them here.
pm.addNestedPass<FuncOp>(disc_ral::createDiscRemoveShapeConstraintsPass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
// TODO: pay attention if this pass brings side-effects on performance
// TODO(disc): this pass introduces `tensor.cast(int32_tensor) ->
// index_tensor`, which is illegal ir. Temporarily disable this pass.
// TODO(disc): implement another implicit broadcast simplifier pass.
// pm.addNestedPass<FuncOp>(mhlo::createBroadcastPropagationPass());
pm.addNestedPass<FuncOp>(createCSEPass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
// propagate some known shape information.
pm.addPass(disc_ral::createDiscShapeSimplifierPass());
pm.addNestedPass<FuncOp>(disc_ral::createDiscConvertTensorToStandardPass());
pm.addNestedPass<FuncOp>(disc_ral::createDiscConvertHloToStandardPass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addNestedPass<FuncOp>(createCSEPass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addNestedPass<FuncOp>(disc_ral::createDiscSplitLargeOpsPass());
pm.addNestedPass<FuncOp>(disc_ral::createDiscDotRewriterPass());
pm.addNestedPass<FuncOp>(disc_ral::createDiscConvRewriter());
pm.addNestedPass<FuncOp>(disc_ral::createDiscGpuConvPaddingLegalization());
if (gpu_enabled) {
pm.addNestedPass<FuncOp>(mhlo::createHloCanonicalizeReductionPass());
}
pm.addPass(disc_ral::createDiscMarkShapeCalcOpPass());
pm.addPass(disc_ral::createPlacerPass(gpu_enabled));
// Run CSE after placer pass to eliminate some redundant copies.
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addNestedPass<FuncOp>(createCSEPass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
// We currently do not support AMP in AICompiler side. If
// `TAO_MLIR_ENABLE_AMP` is set, we simply convert all gemm ops to fp16.
//
// This is a workaround for PyTorch. Some previous Torch version does
// not support AMP on torch script level. Therefore the exported IR is in
// the data type of FP32 instead, which makes DISC less likely to benefit
// in performance if the user's baseline is in FP16 mode.
bool enable_fp16 = false;
tensorflow::ReadBoolFromEnvVar("TAO_MLIR_ENABLE_AMP", false, &enable_fp16);
pm.addNestedPass<FuncOp>(
disc_ral::createDiscElementTypeConverterPass(enable_fp16));
// Create tie_shape ops to explicitly express dim size equality info.
pm.addPass(disc_ral::createDiscShapeSimplifierPass("main", true));
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addNestedPass<FuncOp>(createCSEPass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
// TODO(disc): remove this after fixing the bug in hlo-legalize-to-lhlo pass.
pm.addPass(createFuncBufferizePass());
pm.addPass(mhlo_disc::createDiscLegalizeToLhloPass());
pm.addPass(mhlo::createLegalizeToLhloPass());
// Convert shape to std. Community ```convert-shape-to-std``` pass
// lowers `shape.broadcast` using scf ops. However, our pass pipeline
// currently does not support scf well. Thus, we re-write our internal
// pass to lower shape ops to std dialect.
pm.addNestedPass<FuncOp>(disc_ral::createDiscConvertShapeToStandardPass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addNestedPass<FuncOp>(createCSEPass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addNestedPass<FuncOp>(lmhlo::createLegalizeTensorLoadOpPass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addNestedPass<FuncOp>(createTensorBufferizePass());
// bufferize std.constant ops that have tensor types.
pm.addNestedPass<FuncOp>(disc_ral::createDiscStdBufferizePass());
pm.addNestedPass<FuncOp>(createFinalizingBufferizePass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addNestedPass<FuncOp>(createCSEPass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addNestedPass<FuncOp>(disc_ral::createDiscMemrefCanonicalizerPass());
pm.addPass(disc_ral::createDiscAssignMemorySpacePass("main", gpu_enabled));
pm.addNestedPass<FuncOp>(createPromoteBuffersToStackPass(
[](Value alloc) { return IsSmallCpuAlloc(alloc); }));
// Enable stitch by default on CPU.
bool enable_stitch = !gpu_enabled;
tensorflow::ReadBoolFromEnvVar("DISC_ENABLE_STITCH", !gpu_enabled,
&enable_stitch);
pm.addNestedPass<FuncOp>(disc_ral::createDiscFusionPass(
gpu_enabled, enable_stitch ? "stitch" : "base"));
if (gpu_enabled) {
auto& gpu_options = options.gpu_info;
pm.addNestedPass<FuncOp>(
disc_ral::createDiscSpecializeFusionWithSpeculationPass(
gpu_options.cc_major, gpu_options.cc_minor));
} else {
pm.addNestedPass<FuncOp>(
disc_ral::createDiscSpecializeFusionWithSpeculationPass());
}
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addNestedPass<FuncOp>(createCSEPass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
if (enable_stitch) {
pm.addNestedPass<FuncOp>(disc_ral::createDiscStitchFusionPass());
}
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addNestedPass<FuncOp>(createCSEPass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addNestedPass<FuncOp>(createBufferDeallocationPass());
pm.addPass(disc_ral::createRalInjectExecutionContextPass());
pm.addNestedPass<FuncOp>(disc_ral::createDiscLowerToLibraryCallPass());
pm.addPass(disc_ral::createDiscConstToRALPass(options.metadata_file_path));
// CodeGen passes: lhlo -> gpu.launch_func
// TODO: move to aicompiler repo and add more schedules/op coverage
pm.addNestedPass<FuncOp>(
disc_ral::createDiscLhloLegalizeRootsToParallelLoopsPass());
// Converts `atomic_rmw` to `generic_atomic_rmw` when necessary to use CAS.
pm.addNestedPass<FuncOp>(createStdExpandOpsPass());
// Converts `atomic_rmw` to `generic_atomic_rmw` that is unhandled in
// `StdExpandOps` pass.
pm.addNestedPass<FuncOp>(
disc_ral::createDiscUnhandledAtomicRMWConverterPass());
pm.addNestedPass<FuncOp>(disc_ral::createDiscInputInlineFusionPass());
pm.addNestedPass<FuncOp>(memref::createFoldSubViewOpsPass());
// Flattern multi dim memref accesses to its 1D format to enable more
// opportunities for linearizeOp/delinearizeOp elimination.
pm.addNestedPass<FuncOp>(disc_ral::createDiscFlattenMemrefAccessPass());
// Not using community canonicalizer since it will erase single iteration
// parallel for loop, which is illegal on GPU backend. Parallel for loops are
// supposed to be executed on device side while community canonicalizer break
// this assumption.
SmallVector<std::string> disablePatterns = {
"{anonymous}::CollapseSingleIterationLoops",
"{anonymous}::RemoveEmptyParallelLoops",
"{anonymous}::MergeNestedParallelLoops"};
if (!gpu_enabled) {
disablePatterns.clear();
}
pm.addNestedPass<FuncOp>(
disc_ral::createDiscCanonicalizerPass(disablePatterns));
pm.addNestedPass<FuncOp>(createCSEPass());
pm.addNestedPass<FuncOp>(
disc_ral::createDiscCanonicalizerPass(disablePatterns));
pm.addNestedPass<FuncOp>(disc_ral::createDiscMemRefCSEPass());
// convert linearizeOp/delinearizeOp to std dialect.
pm.addNestedPass<FuncOp>(disc_ral::createDiscConvertShapeToStandardPass());
pm.addNestedPass<FuncOp>(
disc_ral::createDiscCanonicalizerPass(disablePatterns));
pm.addNestedPass<FuncOp>(createCSEPass());
pm.addNestedPass<FuncOp>(
disc_ral::createDiscCanonicalizerPass({disablePatterns}));
if (gpu_enabled) {
// Coalesce generated parallels to have 1d parallels.
// TODO: 2D parallel -> collapsing -> tiling process introduces div/rem/if
// ops which hurts performance. To optimize.
pm.addNestedPass<FuncOp>(disc_ral::createDiscParallelLoopCollapsingPass());
// TODO: adopt tileSize from attributes of speculation pass with a
// wrapper of the original ParallelLoopTilingPass
pm.addNestedPass<FuncOp>(
disc_ral::createParallelLoopTilingPass({256}, true));
pm.addNestedPass<FuncOp>(disc_ral::createMapParallelLoopsPass());
pm.addNestedPass<FuncOp>(createParallelLoopToGpuPass());
pm.addPass(createGpuKernelOutliningPass());
pm.addPass(disc_ral::createDiscAssignKernelNamePass());
} else {
if (options.cpu_options.target_multi_threading) {
pm.addNestedPass<FuncOp>(disc_ral::createDiscCpuMapParallelLoopPass());
pm.addPass(disc_ral::createDiscOutlineCpuKernelPass());
}
}
pm.addNestedPass<FuncOp>(lmhlo::createLhloFusionInlinerPass());
if (gpu_enabled) {
pm.addPass(disc_ral::createReviseGpuKernelOutliningPass());
// Device side codegen: gpu.module -> cubin
auto& kernelPm = pm.nest<mlir::gpu::GPUModuleOp>();
kernelPm.addPass(createLowerToCFGPass());
kernelPm.addPass(createLowerAffinePass());
kernelPm.addNestedPass<FuncOp>(createCanonicalizerPass());
kernelPm.addNestedPass<FuncOp>(createCSEPass());
kernelPm.addNestedPass<FuncOp>(createCanonicalizerPass());
kernelPm.addPass(createStripDebugInfoPass());
#if TENSORFLOW_USE_ROCM
kernelPm.addPass(disc_ral::createDiscLowerGpuOpsToROCDLOpsPass(
/*kDeriveIndexBitwidthFromDataLayout*/ 32));
#elif GOOGLE_CUDA
kernelPm.addPass(disc_ral::createDiscLowerGpuOpsToNVVMOpsPass(
/*kDeriveIndexBitwidthFromDataLayout*/ 32));
#endif
auto& gpu_options = options.gpu_info;
kernelPm.addPass(disc_ral::CreateDiscGpuKernelToBlobPass(
gpu_options.cc_major, gpu_options.cc_minor,
options.gpu_options.multi_cc_support,
options.gpu_options.multi_cc_support_dbg_ptx_only));
} else {
if (options.cpu_options.fast_math_level > 0) {
// Approximate Tanh using standard operations.
pm.addNestedPass<FuncOp>(
mhlo::createLegalizeTrigonometricToApproximationPass());
pm.addNestedPass<FuncOp>(disc_ral::createDiscMathApproximationPass());
}
}
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addNestedPass<FuncOp>(createCSEPass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addNestedPass<FuncOp>(disc_ral::createDiscRemoveDeadBufferPass());
pm.addPass(createLowerToCFGPass());
pm.addPass(createLowerAffinePass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addNestedPass<FuncOp>(createCSEPass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addPass(createStripDebugInfoPass());
// Host side codegen: std -> binary
pm.addPass(disc_ral::createDiscToLLVMPass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addNestedPass<FuncOp>(createCSEPass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
if (failed(pm.run(m))) return failure();
TimingScope outputTiming = timing.nest("Output");
return success();
}
LogicalResult ApplyCpuOptionsBeforeTranslatingToLLVM(
ModuleOp module, const DISCLoweringOptions& options) {
auto& cpuOptions = options.cpu_options;
if (cpuOptions.vector_width > 0) {
module.walk([&](LLVM::LLVMFuncOp op) {
MLIRContext* context = op.getContext();
auto optionName = StringAttr::get(context, "prefer-vector-width");
auto vectorWidthStr = llvm::Twine(cpuOptions.vector_width).str();
auto optionValue = StringAttr::get(context, vectorWidthStr);
auto optionEntry = ArrayAttr::get(context, {optionName, optionValue});
op->setAttr("passthrough", ArrayAttr::get(context, {optionEntry}));
});
if (VLOG_IS_ON(1)) {
llvm::dbgs() << "[[DISC DEBUG]] avx512 dump begin: \n"
<< module << "\ndump end\n";
}
}
if (cpuOptions.assume_no_buffer_alias) {
module.walk([&](LLVM::LLVMFuncOp op) {
if (!op->getAttrOfType<UnitAttr>(kCpuKernelFunc)) return;
OpBuilder b(op);
// The first arg is the ral context, thus we need to skip it.
for (int i = 1; i < op.getNumArguments(); ++i) {
if (!op.getArgument(i).getType().isa<LLVM::LLVMPointerType>()) continue;
op.setArgAttr(i, LLVM::LLVMDialect::getNoAliasAttrName(),
b.getUnitAttr());
}
});
if (VLOG_IS_ON(1)) {
llvm::dbgs() << "[[DISC DEBUG]] noalias dump begin: \n"
<< module << "\ndump end\n";
}
}
if (cpuOptions.disable_loop_unroll) {
module.walk([&](Operation* op) {
if (!isa<LLVM::BrOp, LLVM::CondBrOp>(op)) return;
OpBuilder opBuilder(op);
auto keyName = LLVM::LLVMDialect::getLoopOptionsAttrName();
LLVM::LoopOptionsAttrBuilder b;
b.setDisableUnroll(true);
auto valueAttr = LLVM::LoopOptionsAttr::get(op->getContext(), b);
SmallVector<NamedAttribute> namedAttrs;
namedAttrs.emplace_back(opBuilder.getNamedAttr(keyName, valueAttr));
auto dictAttr = DictionaryAttr::get(op->getContext(), namedAttrs);
op->setAttr(LLVM::LLVMDialect::getLoopAttrName(), dictAttr);
});
if (VLOG_IS_ON(1)) {
llvm::dbgs() << "[[DISC DEBUG]] no_unroll dump begin: \n"
<< module << "\ndump end\n";
}
}
if (cpuOptions.fast_math_level > 1) {
module.walk([&](Operation* op) {
auto fastmathFlagsInterface = dyn_cast<LLVM::FastmathFlagsInterface>(op);
if (!fastmathFlagsInterface) return;
LLVM::FastmathFlags fmf;
switch (cpuOptions.fast_math_level) {
case 4:
fmf = fmf | LLVM::FastmathFlags::ninf;
fmf = fmf | LLVM::FastmathFlags::arcp;
fmf = fmf | LLVM::FastmathFlags::contract;
fmf = fmf | LLVM::FastmathFlags::afn;
fmf = fmf | LLVM::FastmathFlags::fast;
case 3:
fmf = fmf | LLVM::FastmathFlags::nnan;
fmf = fmf | LLVM::FastmathFlags::nsz;
case 2:
fmf = fmf | LLVM::FastmathFlags::reassoc;
break;
default:
llvm::errs() << "[[DISC WARNING]] unknown fast_math_level value\n";
break;
}
op->setAttr("fastmathFlags", LLVM::FMFAttr::get(op->getContext(), fmf));
});
if (VLOG_IS_ON(1)) {
llvm::dbgs() << "[[DISC DEBUG]] fastmath dump begin: \n"
<< module << "\ndump end\n";
}
}
return success();
}
LogicalResult ApplyCpuOptionsAfterTranslatingToLLVM(
llvm::Module* module, const DISCLoweringOptions& options) {
// This is only a workaround for select inst. In MLIR LLVM, select inst is not
// a FastmathFlagsInterface op. We need this to do auto vectorization for
// reduce max op.
const auto& fast_math_level = options.cpu_options.fast_math_level;
if (fast_math_level > 1) {
llvm::FastMathFlags ffm;
switch (fast_math_level) {
case 4:
ffm.setNoInfs();
ffm.setAllowReciprocal();
ffm.setAllowContract();
ffm.setApproxFunc();
case 3:
ffm.setNoNaNs();
ffm.setNoSignedZeros();
case 2:
ffm.setAllowReassoc();
break;
default:
llvm::errs() << "[[DISC WARNING]] unknown fast_math_level value\n";
break;
}
for (auto&& func : module->getFunctionList()) {
for (auto&& bb : func.getBasicBlockList())
for (auto&& I : bb) {
if (!llvm::isa<llvm::SelectInst>(&I)) continue;
I.setFastMathFlags(ffm);
}
}
}
return success();
}
LogicalResult LowerLLVMToBinary(ModuleOp module,
const DISCLoweringOptions& options,
std::string& out) {
bool gpu_enabled = (options.mode == CodeGenMode::kGpuCentric);
if (!gpu_enabled &&
failed(ApplyCpuOptionsBeforeTranslatingToLLVM(module, options))) {
llvm::errs() << "failed to apply cpu options before translating to llvm\n";
return failure();
}
// Translate the module.
llvm::LLVMContext llvm_context;
mlir::registerLLVMDialectTranslation(*module->getContext());
std::unique_ptr<llvm::Module> llvm_module =
mlir::translateModuleToLLVMIR(module, llvm_context);
if (VLOG_IS_ON(1)) {
llvm::dbgs() << "before optimize llvm module:\n";
DumpLLVMModule(llvm_module.get());
}
std::unique_ptr<llvm::TargetMachine> tm = GetTargetMachine(llvm_module.get());
if (!tm) {
llvm::errs() << "create TargetMachine failed\n";
return failure();
}
if (!gpu_enabled && failed(ApplyCpuOptionsAfterTranslatingToLLVM(
llvm_module.get(), options))) {
llvm::errs() << "failed to apply cpu options after translating to llvm\n";
return failure();
}
if (failed(RewriteLLVMModule(llvm_module.get()))) {
llvm::errs() << "rewrite llvm module failed\n";
return failure();
}
auto transformer = mlir::makeOptimizingTransformer(
/*optLevel=*/3, /*sizeLevel=*/0, /*targetMachine=*/tm.get());
if (!transformer) {
llvm::errs() << "transformer create failed\n";
return failure();
}
if (transformer(llvm_module.get())) {
llvm::errs() << "apply transformer failed\n";
return failure();
}
if (VLOG_IS_ON(1)) {
llvm::dbgs() << "after optimize llvm module:\n";
DumpLLVMModule(llvm_module.get());
}
// Set up the output stream.
llvm::SmallString<8> outstr;
llvm::raw_svector_ostream ostream(outstr);
ostream.SetUnbuffered();
llvm::legacy::PassManager codegen_passes;
codegen_passes.add(new llvm::TargetLibraryInfoWrapperPass(
llvm::Triple(llvm_module->getTargetTriple())));
if (tm->addPassesToEmitFile(codegen_passes, ostream, nullptr,
llvm::CGFT_ObjectFile, false)) {
llvm::errs() << "Failed add passes to emit file\n";
return failure();
}
codegen_passes.run(*llvm_module);
out = ostream.str().str();
if (VLOG_IS_ON(2)) {
llvm::errs() << "binary str: " << out << "\n";
}
return success();
}
LogicalResult BinaryStrToSharedLibrary(const DISCLoweringOptions& options,
const std::string& binary) {
std::string object_filename = options.output_file_name + ".o";
// TODO: ONLY used for quick testing.
std::string cmd =
"gcc --shared -o " + options.output_file_name + " " + object_filename;
if (VLOG_IS_ON(1)) {
llvm::errs() << "object file to shared library command: " << cmd << "\n";
}
std::ofstream out(object_filename, std::ios::out | std::ios::binary);
out << binary;
out.close();
std::system(cmd.c_str());
std::remove(object_filename.c_str());
if (VLOG_IS_ON(1)) {
llvm::errs() << "save shared lib file to : " << options.output_file_name
<< "\n";
}
return success();
}
LogicalResult LowerHLOToSharedLibrary(ModuleOp m,
const DISCLoweringOptions& options) {
if (failed(LowerHLOToLLVM(m, options))) {
llvm::errs() << "lower hlo to llvm failed\n";
return failure();
}
std::string binary;
if (failed(LowerLLVMToBinary(m, options, binary))) {
llvm::errs() << "lower llvm to binary failed\n";
return failure();
}
if (failed(BinaryStrToSharedLibrary(options, binary))) {
llvm::errs() << "lower binary to shared library failed\n";
return failure();
}
return success();
}
} // namespace disc_ral
} // namespace mlir
namespace tensorflow {
Status ConvertTF2MlirHlo(mlir::ModuleOp module_op) {
mlir::PassManager tf2xla(module_op.getContext());
tf2xla.getContext()->disableMultithreading();
tf2xla.enableIRPrinting(
/*shouldPrintBeforePass=*/nullptr,
/*shouldPrintAfterPass=*/
[](mlir::Pass* pass, mlir::Operation*) { return VLOG_IS_ON(1); },
/*printModuleScope=*/false,
/*printAfterOnlyOnChange=*/true,
/*printAfterOnlyOnFailure*/ false, llvm::dbgs());
tf2xla.addPass(mlir::disc_ral::createReviseArgsForStaticRankPass());
mlir::SmallVector<std::unique_ptr<mlir::Pass>, 1> lower_passes;
lower_passes.emplace_back(mlir::disc_ral::createDiscLowerTfPass());
CreateConvertMlirToXlaHloPipeline(
tf2xla, "XLA_CPU_JIT",
/*prefer_tf2xla=*/false,
/*custom_legalization_passes=*/lower_passes);
// Make sure we catch any error reported by MLIR and forward it to the TF
// error reporting system. Report a generic error if pass manager failed
// without emitting a diagnostic.
mlir::StatusScopedDiagnosticHandler error_handler(module_op.getContext());
if (failed(tf2xla.run(module_op))) {
return error_handler.Combine(
errors::Internal("MLIR TF to XLA legalization failed"));
}
return Status::OK();
}
} // namespace tensorflow
|
#include "TeWidgetProperties.h"
#include "../TeEditorResManager.h"
#include "../TeEditorUtils.h"
#include "Resources/TeResourceManager.h"
#include "Resources/TeBuiltinResources.h"
#include "String/TeUnicode.h"
#include "Utility/TeFileSystem.h"
#include "Scene/TeSceneManager.h"
#include "Scene/TeSceneObject.h"
#include "Scene/TeTransform.h"
#include "Mesh/TeMesh.h"
#include "RenderAPI/TeSubMesh.h"
#include "Physics/TePhysicsMesh.h"
#include "Physics/TePhysicsHeightField.h"
#include "Importer/TeMeshImportOptions.h"
#include "Importer/TeTextureImportOptions.h"
#include "Scripting/TeScriptManager.h"
#include "Audio/TeAudioClip.h"
#include "Audio/TeAudioClipImportOptions.h"
#include "Components/TeCRenderable.h"
#include "Components/TeCCameraFlyer.h"
#include "Components/TeCCameraUI.h"
#include "Components/TeCCamera.h"
#include "Components/TeCSkybox.h"
#include "Components/TeCScript.h"
#include "Components/TeCLight.h"
#include "Components/TeCAnimation.h"
#include "Components/TeCBone.h"
#include "Components/TeCAudioListener.h"
#include "Components/TeCAudioSource.h"
#include "Components/TeCRigidBody.h"
#include "Components/TeCSoftBody.h"
#include "Components/TeCMeshSoftBody.h"
#include "Components/TeCEllipsoidSoftBody.h"
#include "Components/TeCRopeSoftBody.h"
#include "Components/TeCPatchSoftBody.h"
#include "Components/TeCBoxCollider.h"
#include "Components/TeCCapsuleCollider.h"
#include "Components/TeCConeCollider.h"
#include "Components/TeCCylinderCollider.h"
#include "Components/TeCMeshCollider.h"
#include "Components/TeCPlaneCollider.h"
#include "Components/TeCSphereCollider.h"
#include "Components/TeCHeightFieldCollider.h"
#include "Components/TeCJoint.h"
#include "Components/TeCConeTwistJoint.h"
#include "Components/TeCHingeJoint.h"
#include "Components/TeCD6Joint.h"
#include "Components/TeCSliderJoint.h"
#include "Components/TeCSphericalJoint.h"
#include "Components/TeCDecal.h"
#include "Physics/TePhysics.h"
#if defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wsign-compare"
#endif
namespace te
{
WidgetProperties::WidgetProperties()
: Widget(WidgetType::Properties)
, _selections(gEditor().GetSelectionData())
, _fileBrowser(gEditor().GetFileBrowser())
{
_title = PROPERTIES_TITLE;
_flags |= ImGuiWindowFlags_HorizontalScrollbar;
}
WidgetProperties::~WidgetProperties()
{ }
void WidgetProperties::Initialize()
{ }
void WidgetProperties::Update()
{
bool hasChanged = false;
if (_selections.ClickedComponent)
{
SPtr<GameObject> gameObject = std::static_pointer_cast<GameObject>(_selections.ClickedComponent);
if (ShowGameObjectInformation(gameObject))
hasChanged = true;
switch (_selections.ClickedComponent->GetCoreType())
{
case TID_CCamera:
{
if (ShowCCameraProperties())
hasChanged = true;
}
break;
case TID_CRenderable:
{
if (ShowCRenderableProperties())
hasChanged = true;
}
break;
case TID_CLight:
{
if (ShowCLightProperties())
hasChanged = true;
}
break;
case TID_CSkybox:
{
if (ShowCSkyboxProperties())
hasChanged = true;
}
break;
case TID_CCameraFlyer:
{
if (ShowCCameraFlyerProperties())
hasChanged = true;
}
break;
case TID_CCameraUI:
{
if (ShowCCameraUIProperties())
hasChanged = true;
}
break;
case TID_CScript:
{
if (ShowCScriptProperties())
hasChanged = true;
}
break;
case TID_CAnimation:
{
if (ShowCAnimationProperties())
hasChanged = true;
}
break;
case TID_CBone:
{
if (ShowCBoneProperties())
hasChanged = true;
}
break;
case TID_CAudioListener:
{
if (ShowCAudioListenerProperties())
hasChanged = true;
}
break;
case TID_CAudioSource:
{
if (ShowCAudioSourceProperties())
hasChanged = true;
}
break;
case TID_CRigidBody:
{
if (ShowCRigidBodyProperties())
hasChanged = true;
}
break;
case TID_CMeshSoftBody:
{
if (ShowCMeshSoftBodyProperties())
hasChanged = true;
}
break;
case TID_CEllipsoidSoftBody:
{
if (ShowCEllipsoidSoftBodyProperties())
hasChanged = true;
}
break;
case TID_CRopeSoftBody:
{
if (ShowCRopeSoftBodyProperties())
hasChanged = true;
}
break;
case TID_CPatchSoftBody:
{
if (ShowCPatchSoftBodyProperties())
hasChanged = true;
}
break;
case TID_CBoxCollider:
{
if (ShowCBoxColliderProperties())
hasChanged = true;
}
break;
case TID_CCapsuleCollider:
{
if (ShowCCapsuleColliderProperties())
hasChanged = true;
}
break;
case TID_CConeCollider:
{
if (ShowCConeColliderProperties())
hasChanged = true;
}
break;
case TID_CHeightFieldCollider:
{
if (ShowCHeightFieldColliderProperties())
hasChanged = true;
}
break;
case TID_CCylinderCollider:
{
if (ShowCCylinderColliderProperties())
hasChanged = true;
}
break;
case TID_CMeshCollider:
{
if (ShowCMeshColliderProperties())
hasChanged = true;
}
break;
case TID_CPlaneCollider:
{
if (ShowCPlaneColliderProperties())
hasChanged = true;
}
break;
case TID_CSphereCollider:
{
if (ShowCSphereColliderProperties())
hasChanged = true;
}
break;
case TID_CConeTwistJoint:
{
if (ShowCConeTwistJointProperties())
hasChanged = true;
}
break;
case TID_CD6Joint:
{
if (ShowCD6JointProperties())
hasChanged = true;
}
break;
case TID_CHingeJoint:
{
if (ShowCHingeJointProperties())
hasChanged = true;
}
break;
case TID_CSliderJoint:
{
if (ShowCSliderJointProperties())
hasChanged = true;
}
break;
case TID_CSphericalJoint:
{
if (ShowCSphericalJointProperties())
hasChanged = true;
}
break;
case TID_CDecal:
{
if (ShowCDecal())
hasChanged = true;
}
break;
default:
break;
}
}
else if (_selections.ClickedSceneObject)
{
if (ShowSceneObjectProperties())
hasChanged = true;
}
if (hasChanged)
{
gEditor().NeedsRedraw();
gEditor().GetSettings().State = Editor::EditorState::Modified;
}
}
void WidgetProperties::UpdateBackground()
{ }
bool WidgetProperties::ShowSceneObjectProperties()
{
bool hasChanged = false;
ObjectMobility mobility = _selections.ClickedSceneObject->GetMobility();
Transform transform = _selections.ClickedSceneObject->GetLocalTransform();
SPtr<GameObject> gameObject = std::static_pointer_cast<GameObject>(_selections.ClickedSceneObject);
if (ShowGameObjectInformation(gameObject))
hasChanged = true;
bool active = _selections.ClickedSceneObject->GetActive(true);
if (ImGuiExt::RenderOptionBool(active, "##scene_object_information_active_option", "Active"))
{
hasChanged = true;
_selections.ClickedSceneObject->SetActive(active);
}
if (ShowTransform(transform, mobility))
{
_selections.ClickedSceneObject->SetLocalTransform(transform);
_selections.ClickedSceneObject->SetMobility(mobility);
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowCCameraProperties()
{
bool hasChanged = false;
SPtr<CCamera> camera = std::static_pointer_cast<CCamera>(_selections.ClickedComponent);
ObjectMobility mobility = camera->GetInternal()->GetMobility();
Transform transform = camera->GetSceneObject()->GetTransform();
if (ShowTransform(transform, mobility))
{
camera->GetInternal()->SetMobility(mobility);
camera->GetSceneObject()->SetLocalTransform(transform);
hasChanged = true;
}
if (ImGui::CollapsingHeader("Rendering Camera", ImGuiTreeNodeFlags_DefaultOpen))
{
if (ShowCamera(camera))
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowCCameraFlyerProperties()
{
bool hasChanged = false;
SPtr<CCameraFlyer> camera = std::static_pointer_cast<CCameraFlyer>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Flying Camera", ImGuiTreeNodeFlags_DefaultOpen))
{
if (ShowCameraFlyer(camera))
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowCCameraUIProperties()
{
bool hasChanged = false;
SPtr<CCameraUI> camera = std::static_pointer_cast<CCameraUI>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Orbital Camera", ImGuiTreeNodeFlags_DefaultOpen))
{
if (ShowCamerUI(camera))
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowCLightProperties()
{
bool hasChanged = false;
SPtr<CLight> lightCO = std::static_pointer_cast<CLight>(_selections.ClickedComponent);
SPtr<Light> lightPtr = lightCO->GetInternal();
ObjectMobility mobility = lightPtr->GetMobility();
Transform transform = lightCO->GetSceneObject()->GetTransform();
if (ShowTransform(transform, mobility))
{
lightPtr->SetMobility(mobility);
lightCO->GetSceneObject()->SetLocalTransform(transform);
hasChanged = true;
}
if (ImGui::CollapsingHeader("Light", ImGuiTreeNodeFlags_DefaultOpen))
{
if (ShowLight(lightPtr))
hasChanged = true;
}
if (ImGui::CollapsingHeader("Shadow", ImGuiTreeNodeFlags_DefaultOpen))
{
if (ShowLightShadow(lightPtr))
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowCRenderableProperties()
{
bool hasChanged = false;
SPtr<CRenderable> renderableCO = std::static_pointer_cast<CRenderable>(_selections.ClickedComponent);
SPtr<Renderable> renderablePtr = renderableCO->GetInternal();
ObjectMobility mobility = renderablePtr->GetMobility();
Transform transform = renderableCO->GetSceneObject()->GetTransform();
if (ShowTransform(transform, mobility))
{
renderablePtr->SetMobility(mobility);
renderableCO->GetSceneObject()->SetLocalTransform(transform);
hasChanged = true;
}
if (ImGui::CollapsingHeader("Properties", ImGuiTreeNodeFlags_DefaultOpen))
{
if (ShowRenderableProperties(renderablePtr))
hasChanged = true;
}
if (renderablePtr->GetMesh())
{
if (ImGui::CollapsingHeader("SubMeshes", ImGuiTreeNodeFlags_DefaultOpen))
{
if (ShowRenderableSubMeshes(renderablePtr))
hasChanged = true;
}
}
return hasChanged;
}
bool WidgetProperties::ShowCScriptProperties()
{
bool hasChanged = false;
SPtr<CScript> script = std::static_pointer_cast<CScript>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Script", ImGuiTreeNodeFlags_DefaultOpen))
{
if (ShowScript(script))
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowCAnimationProperties()
{
bool hasChanged = false;
SPtr<CAnimation> animation = std::static_pointer_cast<CAnimation>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Animation", ImGuiTreeNodeFlags_DefaultOpen))
{
if (ShowAnimation(animation))
hasChanged = true;
}
if (animation->GetNumClips() > 0)
{
if (ShowAnimationClips(animation))
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowCBoneProperties()
{
bool hasChanged = false;
SPtr<CBone> bone = std::static_pointer_cast<CBone>(_selections.ClickedComponent);
ObjectMobility mobility = bone->GetSceneObject()->GetMobility();
Transform transform = bone->GetSceneObject()->GetTransform();
const float width = ImGui::GetWindowContentRegionWidth() - 120.0f;
if (ShowTransform(transform, mobility))
{
bone->GetSceneObject()->SetMobility(mobility);
bone->GetSceneObject()->SetLocalTransform(transform);
hasChanged = true;
}
if (ImGui::CollapsingHeader("Bone", ImGuiTreeNodeFlags_DefaultOpen))
{
HSceneObject currentSO = bone->GetSceneObject();
HRenderable renderable;
HAnimation animation;
while (!currentSO.Empty())
{
renderable = static_object_cast<CRenderable>(currentSO->GetComponent<CRenderable>());
animation = static_object_cast<CAnimation>(currentSO->GetComponent<CAnimation>());
if (!renderable.Empty() && !animation.Empty()) // If there is an animation and a renderable in the hierarchy
break;
if (currentSO == gEditor().GetSceneRoot())
break;
currentSO = currentSO->GetParent();
}
if (!renderable.Empty() && !animation.Empty())
{
if (renderable->GetMesh() && renderable->GetMesh()->GetSkeleton()) // if the renderable has a skeleton
{
ImGuiExt::ComboOptions<UINT32> bonesOptions;
SPtr<Skeleton> skeleton = renderable->GetMesh()->GetSkeleton();
UINT32 boneIndex = static_cast<UINT32>(-1);
bonesOptions.AddOption(static_cast<UINT32>(-1), "None");
for (UINT32 i = 0; i < skeleton->GetNumBones(); i++)
{
SkeletonBoneInfo boneInfo = skeleton->GetBoneInfo(i);
bonesOptions.AddOption(i, boneInfo.Name);
if (boneInfo.Name == bone->GetBoneName())
boneIndex = i;
}
if (ImGuiExt::RenderOptionCombo<UINT32>(&boneIndex, "##bone_name_option", "Mimicked bone", bonesOptions, width))
{
if (boneIndex != -1)
bone->SetBoneName(skeleton->GetBoneInfo(boneIndex).Name);
else
bone->SetBoneName("");
hasChanged = true;
}
}
}
}
return hasChanged;
}
bool WidgetProperties::ShowCAudioListenerProperties()
{
bool hasChanged = false;
SPtr<CAudioListener> audioListener = std::static_pointer_cast<CAudioListener>(_selections.ClickedComponent);
return hasChanged;
}
bool WidgetProperties::ShowCAudioSourceProperties()
{
bool hasChanged = false;
SPtr<CAudioSource> audioSource = std::static_pointer_cast<CAudioSource>(_selections.ClickedComponent);
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
HAudioClip clip = audioSource->GetClip();
if (ImGui::CollapsingHeader("Audio Source", ImGuiTreeNodeFlags_DefaultOpen))
{
ImGuiExt::ComboOptions<UUID> audioClipsOptions;
UUID emptyAudioClip = UUID(50, 0, 0, 0);
UUID loadAudioClip = UUID::EMPTY;
UUID audioClipUUID = (clip.IsLoaded()) ? clip->GetUUID() : emptyAudioClip;
EditorResManager::ResourcesContainer& container = EditorResManager::Instance().Get<AudioClip>();
// Play/Stop
{
ImGui::PushID("##audio_source_play_stop");
if (audioSource->GetState() == AudioSourceState::Playing)
{
if (ImGui::Button(ICON_FA_STOP " Stop", ImVec2(ImGui::GetWindowContentRegionWidth(), 25.0f)))
audioSource->Stop();
}
else
{
if (ImGui::Button(ICON_FA_PLAY " Play", ImVec2(ImGui::GetWindowContentRegionWidth(), 25.0f)))
audioSource->Play();
}
ImGui::PopID();
}
ImGui::Separator();
// Play3D
{
bool isPlay3D = audioSource->GetIsPlay3D();
if (ImGuiExt::RenderOptionBool(isPlay3D, "##audio_source_is_play_3d", "Play 3D"))
{
hasChanged = true;
audioSource->SetIsPlay3D(isPlay3D);
}
}
// IsLooping
{
bool isLooping = audioSource->GetIsLooping();
if (ImGuiExt::RenderOptionBool(isLooping, "##audio_source_is_looping", "Is looping"))
{
hasChanged = true;
audioSource->SetIsLooping(isLooping);
}
}
// PlayOnStart
{
bool playOnStart = audioSource->GetPlayOnStart();
if (ImGuiExt::RenderOptionBool(playOnStart, "##audio_source_play_on_start", "Play on start"))
{
hasChanged = true;
audioSource->SetPlayOnStart(playOnStart);
}
}
ImGui::Separator();
// current audio clip to use
{
for (auto& resource : container.Res)
audioClipsOptions.AddOption(resource.second->GetUUID(), resource.second->GetName());
audioClipsOptions.AddOption(emptyAudioClip, ICON_FA_TIMES_CIRCLE " No clip");
audioClipsOptions.AddOption(loadAudioClip, ICON_FA_FOLDER_OPEN " Load");
if (ImGuiExt::RenderOptionCombo<UUID>(&audioClipUUID, "##audio_clip_option", "Audio Clip", audioClipsOptions, width))
{
if (audioClipUUID == loadAudioClip)
{
_loadAudioClip = true;
}
else if (audioClipUUID == emptyAudioClip)
{
audioSource->SetClip(HAudioClip());
hasChanged = true;
}
else if (audioClipUUID != ((clip.IsLoaded()) ? clip->GetUUID() : emptyAudioClip))
{
audioSource->SetClip(gResourceManager().Load<AudioClip>(audioClipUUID));
hasChanged = true;
}
}
}
ImGui::Separator();
// Volume
{
float volume = audioSource->GetVolume();
if (ImGuiExt::RenderOptionFloat(volume, "##audio_source_volume", "Volume", 0.0f, 1.0f, width))
{
hasChanged = true;
audioSource->SetVolume(volume);
}
}
// Pitch
{
float pitch = audioSource->GetPitch();
if (ImGuiExt::RenderOptionFloat(pitch, "##audio_source_pitch", "Pitch", 0.0f, 8.0f, width))
{
hasChanged = true;
audioSource->SetPitch(pitch);
}
}
// MinDistance
{
float minDistance = audioSource->GetMinDistance();
if (ImGuiExt::RenderOptionFloat(minDistance, "##audio_source_min_distance", "Min distance", 0.0f, 100.0f, width))
{
hasChanged = true;
audioSource->SetMinDistance(minDistance);
}
}
// Attenuation
{
float attenuation = audioSource->GetAttenuation();
if (ImGuiExt::RenderOptionFloat(attenuation, "##audio_source_attenuation", "Attenuation", 0.0f, 100.0f, width))
{
hasChanged = true;
audioSource->SetAttenuation(attenuation);
}
}
}
if (ShowLoadAudioClip())
hasChanged = true;
return hasChanged;
}
bool WidgetProperties::ShowCSkyboxProperties()
{
bool hasChanged = false;
SPtr<CSkybox> skybox = std::static_pointer_cast<CSkybox>(_selections.ClickedComponent);
ObjectMobility mobility = skybox->GetInternal()->GetMobility();
Transform transform = skybox->GetInternal()->GetTransform();
if (ImGui::CollapsingHeader("Skybox", ImGuiTreeNodeFlags_DefaultOpen))
{
if (ShowSkybox(skybox->GetInternal()))
hasChanged = true;
}
if (ShowTransform(transform, mobility, true))
{
skybox->GetInternal()->SetMobility(mobility);
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowCRigidBodyProperties()
{
bool hasChanged = false;
SPtr<CRigidBody> rigidBody = std::static_pointer_cast<CRigidBody>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Rigid Body", ImGuiTreeNodeFlags_DefaultOpen))
{
if (ShowBody(rigidBody))
hasChanged = true;
ImGui::Separator();
// UseGravity
{
bool useGravity = rigidBody->GetUseGravity();
if (ImGuiExt::RenderOptionBool(useGravity, "##body_option_use_gravity", "Use Gravity"))
{
rigidBody->SetUseGravity(useGravity);
hasChanged = true;
}
}
ImGui::Separator();
// Center of mass
{
Vector3 centerOfMass = rigidBody->GetCenterOfMass();
if (ImGuiExt::RenderVector3(centerOfMass, "##body_option_center_of_mass", " Center of Mass", 60.0f))
{
rigidBody->SetCenterOfMass(centerOfMass);
hasChanged = true;
}
}
ImGui::Separator();
// Angular Factor
{
Vector3 angularFactor = rigidBody->GetAngularFactor();
if (ImGuiExt::RenderVector3(angularFactor, "##rigid_body_option_angular_factor", " Angular Factor", 60.0f))
{
rigidBody->SetAngularFactor(angularFactor);
hasChanged = true;
}
}
}
return hasChanged;
}
bool WidgetProperties::ShowCSoftBodyProperties()
{
bool hasChanged = false;
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
SPtr<CSoftBody> softBody = std::static_pointer_cast<CSoftBody>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Soft Body", ImGuiTreeNodeFlags_DefaultOpen))
{
// Scale
{
Vector3 scale = softBody->GetScale();
if (ImGuiExt::RenderVector3(scale, "##soft_body_option_scale", " Scale", 60.0f))
{
softBody->SetScale(scale);
hasChanged = true;
}
}
ImGui::Separator();
if (ShowBody(softBody))
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowCMeshSoftBodyProperties()
{
bool hasChanged = false;
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
SPtr<CMeshSoftBody> softBody = std::static_pointer_cast<CMeshSoftBody>(_selections.ClickedComponent);
HPhysicsMesh mesh = softBody->GetMesh();
if (ImGui::CollapsingHeader("Mesh Soft Body", ImGuiTreeNodeFlags_DefaultOpen))
{
// PhysicsMesh
{
ImGuiExt::ComboOptions<UUID> meshesOptions;
UUID emptyMesh = UUID(50, 0, 0, 0);
UUID loadPhysicsMesh = UUID::EMPTY;
UUID meshUUID = (mesh.IsLoaded()) ? mesh->GetUUID() : emptyMesh;
EditorResManager::ResourcesContainer& container = EditorResManager::Instance().Get<PhysicsMesh>();
// current PhysicsMesh to use
for (auto& resource : container.Res)
meshesOptions.AddOption(resource.second->GetUUID(), resource.second->GetName());
meshesOptions.AddOption(emptyMesh, ICON_FA_TIMES_CIRCLE " No Physic Mesh");
meshesOptions.AddOption(UUID::EMPTY, ICON_FA_FOLDER_OPEN " Load");
if (ImGuiExt::RenderOptionCombo<UUID>(&meshUUID, "##soft_mes_body_physic_mesh_option", "Physic Mesh", meshesOptions, width))
{
if (meshUUID == loadPhysicsMesh)
{
_loadPhysicsMesh = true;
}
else if (meshUUID == emptyMesh)
{
softBody->SetMesh(HPhysicsMesh());
hasChanged = true;
}
else if (meshUUID != ((mesh.IsLoaded()) ? mesh->GetUUID() : emptyMesh))
{
softBody->SetMesh(gResourceManager().Load<PhysicsMesh>(meshUUID));
hasChanged = true;
}
}
}
}
if (ShowCSoftBodyProperties())
hasChanged = true;
if (ShowLoadMesh())
hasChanged = true;
return hasChanged;
}
bool WidgetProperties::ShowCEllipsoidSoftBodyProperties()
{
bool hasChanged = false;
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
SPtr<CEllipsoidSoftBody> softBody = std::static_pointer_cast<CEllipsoidSoftBody>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Ellipsoid Soft Body", ImGuiTreeNodeFlags_DefaultOpen))
{
// center
{
Vector3 center = softBody->GetCenter();
if (ImGuiExt::RenderVector3(center, "##ellipsoid_soft_body_option_center", " Center", 20.0f))
{
softBody->SetCenter(center);
hasChanged = true;
}
}
ImGui::Separator();
// radius
{
Vector3 radius = softBody->GetRadius();
if (ImGuiExt::RenderVector3(radius, "##ellipsoid_soft_body_option_radius", " Radius", 20.0f))
{
softBody->SetRadius(radius);
hasChanged = true;
}
}
ImGui::Separator();
// resolution
{
UINT32 resolution = softBody->GetResolution();
if (ImGuiExt::RenderOptionInt<UINT32>(resolution, "##ellipsoid_soft_body_option_resolution", " Resolution", 1, 256, width))
{
softBody->SetResolution(resolution);
hasChanged = true;
}
}
ImGui::Separator();
}
if (ShowCSoftBodyProperties())
hasChanged = true;
return hasChanged;
}
bool WidgetProperties::ShowCRopeSoftBodyProperties()
{
bool hasChanged = false;
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
SPtr<CRopeSoftBody> softBody = std::static_pointer_cast<CRopeSoftBody>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Rope Soft Body", ImGuiTreeNodeFlags_DefaultOpen))
{
// TODO
}
if (ShowCSoftBodyProperties())
hasChanged = true;
return hasChanged;
}
bool WidgetProperties::ShowCPatchSoftBodyProperties()
{
bool hasChanged = false;
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
SPtr<CPatchSoftBody> softBody = std::static_pointer_cast<CPatchSoftBody>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Patch Soft Body", ImGuiTreeNodeFlags_DefaultOpen))
{
// Corners
{
Vector3 topLeft, topRight, bottomLeft, bottomRight;
softBody->GetCorners(topLeft, topRight, bottomLeft, bottomRight);
if (ImGuiExt::RenderVector3(topLeft, "##patch_soft_body_option_corners_top_left", " Top Left", 20.0f))
{
softBody->SetCorners(topLeft, topRight, bottomLeft, bottomRight);
hasChanged = true;
}
if (ImGuiExt::RenderVector3(topRight, "##patch_soft_body_option_corners_top_right", " Top Right", 20.0f))
{
softBody->SetCorners(topLeft, topRight, bottomLeft, bottomRight);
hasChanged = true;
}
if (ImGuiExt::RenderVector3(bottomLeft, "##patch_soft_body_option_corners_bottom_left", " Bottom Left", 20.0f))
{
softBody->SetCorners(topLeft, topRight, bottomLeft, bottomRight);
hasChanged = true;
}
if (ImGuiExt::RenderVector3(bottomRight, "##patch_soft_body_option_corners_bottom_right", " Bottom Right", 20.0f))
{
softBody->SetCorners(topLeft, topRight, bottomLeft, bottomRight);
hasChanged = true;
}
}
ImGui::Separator();
// Resolution
{
UINT32 resolutionX, resolutionY;
softBody->GetResolution(resolutionX, resolutionY);
if (ImGuiExt::RenderOptionInt<UINT32>(resolutionX, "##patch_soft_body_option_resolution_x", " Resolution X", 1, 256, width))
{
softBody->SetResolution(resolutionX, resolutionY);
hasChanged = true;
}
if (ImGuiExt::RenderOptionInt<UINT32>(resolutionY, "##patch_soft_body_option_resolution_Y", " Resolution Y", 1, 256, width))
{
softBody->SetResolution(resolutionX, resolutionY);
hasChanged = true;
}
}
ImGui::Separator();
}
if (ShowCSoftBodyProperties())
hasChanged = true;
return hasChanged;
}
bool WidgetProperties::ShowCBoxColliderProperties()
{
bool hasChanged = false;
SPtr<CBoxCollider> collider = std::static_pointer_cast<CBoxCollider>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Box Collider", ImGuiTreeNodeFlags_DefaultOpen))
{
// Extents
{
Vector3 extents = collider->GetExtents();
if (ImGuiExt::RenderVector3(extents, "##collider_option_extents", " Extents", 20.0f))
{
collider->SetExtents(extents);
hasChanged = true;
}
}
ImGui::Separator();
if (ShowCollider(collider))
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowCCapsuleColliderProperties()
{
bool hasChanged = false;
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
SPtr<CCapsuleCollider> collider = std::static_pointer_cast<CCapsuleCollider>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Capsule Collider", ImGuiTreeNodeFlags_DefaultOpen))
{
// Radius
{
float radius = collider->GetRadius();
if (ImGuiExt::RenderOptionFloat(radius, "##collider_option_radius", " Radius", 0.0f, 512.0f, width))
{
collider->SetRadius(radius);
hasChanged = true;
}
}
// Height
{
float height = collider->GetHeight();
if (ImGuiExt::RenderOptionFloat(height, "##collider_option_height", " Height", 0.0f, 512.0f, width))
{
collider->SetHeight(height);
hasChanged = true;
}
}
ImGui::Separator();
if (ShowCollider(collider))
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowCConeColliderProperties()
{
bool hasChanged = false;
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
SPtr<CConeCollider> collider = std::static_pointer_cast<CConeCollider>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Cone Collider", ImGuiTreeNodeFlags_DefaultOpen))
{
// Radius
{
float radius = collider->GetRadius();
if (ImGuiExt::RenderOptionFloat(radius, "##collider_option_radius", " Radius", 0.0f, 512.0f, width))
{
collider->SetRadius(radius);
hasChanged = true;
}
}
// Height
{
float height = collider->GetHeight();
if (ImGuiExt::RenderOptionFloat(height, "##collider_option_height", " Height", 0.0f, 512.0f, width))
{
collider->SetHeight(height);
hasChanged = true;
}
}
ImGui::Separator();
if (ShowCollider(collider))
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowCCylinderColliderProperties()
{
bool hasChanged = false;
SPtr<CCylinderCollider> collider = std::static_pointer_cast<CCylinderCollider>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Cylinder Collider", ImGuiTreeNodeFlags_DefaultOpen))
{
// Extents
{
Vector3 extents = collider->GetExtents();
if (ImGuiExt::RenderVector3(extents, "##collider_option_extents", " Extents", 20.0f))
{
collider->SetExtents(extents);
hasChanged = true;
}
}
ImGui::Separator();
if (ShowCollider(collider))
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowCMeshColliderProperties()
{
bool hasChanged = false;
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
SPtr<CMeshCollider> collider = std::static_pointer_cast<CMeshCollider>(_selections.ClickedComponent);
HPhysicsMesh mesh = collider->GetMesh();
if (ImGui::CollapsingHeader("Mesh Collider", ImGuiTreeNodeFlags_DefaultOpen))
{
// PhysicsMesh
{
ImGuiExt::ComboOptions<UUID> meshesOptions;
UUID emptyMesh = UUID(50, 0, 0, 0);
UUID loadPhysicsMesh = UUID::EMPTY;
UUID meshUUID = (mesh.IsLoaded()) ? mesh->GetUUID() : emptyMesh;
EditorResManager::ResourcesContainer& container = EditorResManager::Instance().Get<PhysicsMesh>();
// current PhysicsMesh to use
for (auto& resource : container.Res)
meshesOptions.AddOption(resource.second->GetUUID(), resource.second->GetName());
meshesOptions.AddOption(emptyMesh, ICON_FA_TIMES_CIRCLE " No Physic Mesh");
meshesOptions.AddOption(UUID::EMPTY, ICON_FA_FOLDER_OPEN " Load");
if (ImGuiExt::RenderOptionCombo<UUID>(&meshUUID, "##collider_physic_mesh_option", "Physic Mesh", meshesOptions, width))
{
if (meshUUID == loadPhysicsMesh)
{
_loadPhysicsMesh = true;
}
else if (meshUUID == emptyMesh)
{
collider->SetMesh(HPhysicsMesh());
hasChanged = true;
}
else if (meshUUID != ((mesh.IsLoaded()) ? mesh->GetUUID() : emptyMesh))
{
collider->SetMesh(gResourceManager().Load<PhysicsMesh>(meshUUID));
hasChanged = true;
}
}
}
ImGui::Separator();
// CollisionType
{
static ImGuiExt::ComboOptions<PhysicsMeshType> collisionTypeOptions;
if (collisionTypeOptions.Options.size() == 0)
{
collisionTypeOptions.AddOption(PhysicsMeshType::Triangle, "Triangle");
collisionTypeOptions.AddOption(PhysicsMeshType::Convex, "Convex");
}
PhysicsMeshType type = collider->GetCollisionType();
if (ImGuiExt::RenderOptionCombo<PhysicsMeshType>(&type, "##collider_physic_mesh_type_option", "Collision Type", collisionTypeOptions, width))
{
collider->SetCollisionType(type);
hasChanged = true;
}
}
ImGui::Separator();
if (ShowLoadMesh())
hasChanged = true;
if (ShowCollider(collider))
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowCPlaneColliderProperties()
{
bool hasChanged = false;
SPtr<CPlaneCollider> collider = std::static_pointer_cast<CPlaneCollider>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Plane Collider", ImGuiTreeNodeFlags_DefaultOpen))
{
// Normal
{
Vector3 normal = collider->GetNormal();
if (ImGuiExt::RenderVector3(normal, "##collider_option_normal", " Normal", 20.0f))
{
collider->SetNormal(normal);
hasChanged = true;
}
}
ImGui::Separator();
if (ShowCollider(collider))
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowCSphereColliderProperties()
{
bool hasChanged = false;
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
SPtr<CSphereCollider> collider = std::static_pointer_cast<CSphereCollider>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Sphere Collider", ImGuiTreeNodeFlags_DefaultOpen))
{
// Radius
{
float radius = collider->GetRadius();
if (ImGuiExt::RenderOptionFloat(radius, "##collider_option_radius", " Radius", 0.0f, 512.0f, width))
{
collider->SetRadius(radius);
hasChanged = true;
}
}
if (ShowCollider(collider))
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowCHeightFieldColliderProperties()
{
bool hasChanged = false;
float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
SPtr<CHeightFieldCollider> collider = std::static_pointer_cast<CHeightFieldCollider>(_selections.ClickedComponent);
HPhysicsHeightField heightField = collider->GetHeightField();
SPtr<Texture> texture = heightField.IsLoaded() ? heightField->GetTexture() : nullptr;
UINT8 flags = (UINT8)ImGuiExt::ComboOptionFlag::ShowTexture;
if (ImGui::CollapsingHeader("Terrain Collider", ImGuiTreeNodeFlags_DefaultOpen))
{
// Min Height
{
float minHeight = collider->GetMinHeight();
if (ImGuiExt::RenderOptionFloat(minHeight, "##collider_physic_min_height_option", "Min Height", -256.0f, 256.0f, width))
{
hasChanged = true;
collider->SetMinHeight(minHeight);
}
}
ImGui::Separator();
// Max Height
{
float maxHeight = collider->GetMaxHeight();
if (ImGuiExt::RenderOptionFloat(maxHeight, "##collider_physic_max_height_option", "Max Height", -256.0f, 256.0f, width))
{
hasChanged = true;
collider->SetMaxHeight(maxHeight);
}
}
ImGui::Separator();
// PhysicsHeightField
{
ImGuiExt::ComboOptions<UUID> texturesOptions;
UUID emptyTexture = UUID(50, 0, 0, 0);
UUID loadTexture = UUID::EMPTY;
UUID textureUUID = (texture) ? texture->GetUUID() : emptyTexture;
EditorResManager::ResourcesContainer& texContainer = EditorResManager::Instance().Get<Texture>();
// current texture to use as PhysicsHeightField
for (auto& resource : texContainer.Res)
{
HTexture tex = static_resource_cast<Texture>(resource.second);
if (tex.IsLoaded() && tex->GetProperties().GetTextureType() != TextureType::TEX_TYPE_CUBE_MAP)
{
texturesOptions.AddOption(resource.second->GetUUID(), resource.second->GetName(),
std::static_pointer_cast<Texture>(resource.second.GetInternalPtr()));
}
}
texturesOptions.AddOption(emptyTexture, ICON_FA_TIMES_CIRCLE " No HeightField");
texturesOptions.AddOption(UUID::EMPTY, ICON_FA_FOLDER_OPEN " Load");
if (texture && texture->GetProperties().GetTextureType() != TextureType::TEX_TYPE_CUBE_MAP)
{
ImGuiExt::RenderImage(texture, 3, Vector2(26.0f, 26.0f));
ImGui::SameLine();
ImVec2 cursor = ImGui::GetCursorPos();
cursor.x -= 5.0f;
ImGui::SetCursorPos(cursor);
width -= 26.0f;
}
if (ImGuiExt::RenderOptionCombo<UUID>(&textureUUID, "##collider_physic_height_field_option", "Height Field", texturesOptions, width, flags))
{
if (textureUUID == loadTexture)
{
// Load and create (if not exists) PhysicsHeightField associated to this texture
_loadHeightFieldTexture = true;
}
else if (textureUUID == emptyTexture)
{
collider->SetHeightField(HPhysicsHeightField());
hasChanged = true;
}
else if (textureUUID != ((heightField.IsLoaded()) ? texture->GetUUID() : emptyTexture))
{
// Find or create PhysicsHeightField associated to this texture
collider->SetHeightField(GetOrCreatePhysicsHightFieldFromTex(gResourceManager().Load<Texture>(textureUUID).GetInternalPtr()));
hasChanged = true;
}
}
}
ImGui::Separator();
if (ShowCollider(collider))
hasChanged = true;
if (ShowLoadHeightFieldTexture())
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowCConeTwistJointProperties()
{
bool hasChanged = false;
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
SPtr<CConeTwistJoint> joint = std::static_pointer_cast<CConeTwistJoint>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Twist Joint", ImGuiTreeNodeFlags_DefaultOpen))
{
// Damping
{
float damping = joint->GetDamping();
if (ImGuiExt::RenderOptionFloat(damping, "##joint_option_damping", "Damping", 0.0f, 8.0f, width))
{
hasChanged = true;
joint->SetDamping(damping);
}
}
ImGui::Separator();
// Limit Softness
{
float softnessLimit = joint->GetSoftnessLimit();
if (ImGuiExt::RenderOptionFloat(softnessLimit, "##joint_option_limit_softness", "Limit Softness", 0.0f, 1.0f, width))
{
hasChanged = true;
joint->SetSoftnessLimit(softnessLimit);
}
}
// Limit Bias
{
float biasLimit = joint->GetBiasLimit();
if (ImGuiExt::RenderOptionFloat(biasLimit, "##joint_option_limit_bias", "Limit Softness", 0.0f, 1.0f, width))
{
hasChanged = true;
joint->SetBiasLimit(biasLimit);
}
}
// Limit Relaxation
{
float relaxationLimit = joint->GetRelaxationLimit();
if (ImGuiExt::RenderOptionFloat(relaxationLimit, "##joint_option_limit_relaxation", "Limit Relaxation", 0.0f, 1.0f, width))
{
hasChanged = true;
joint->SetRelaxationLimit(relaxationLimit);
}
}
ImGui::Separator();
// Swing Span 1
{
float swingSpan = joint->GetSwingSpan1().ValueDegrees();
if (ImGuiExt::RenderOptionFloat(swingSpan, "##joint_option_swing_span_1", "Swing Span 1", 0.0f, 90.0f, width))
{
hasChanged = true;
joint->SetSwingSpan1(Degree(swingSpan));
}
}
// Swing Span 2
{
float swingSpan = joint->GetSwingSpan2().ValueDegrees();
if (ImGuiExt::RenderOptionFloat(swingSpan, "##joint_option_swing_span_2", "Swing Span 2", 0.0f, 90.0f, width))
{
hasChanged = true;
joint->SetSwingSpan2(Degree(swingSpan));
}
}
// Twist Span
{
float twistSpan = joint->GetTwistSpan().ValueDegrees();
if (ImGuiExt::RenderOptionFloat(twistSpan, "##joint_option_twist_span_2", "Twist Span", 0.0f, 360.0f, width))
{
hasChanged = true;
joint->SetTwistSpan(Degree(twistSpan));
}
}
ImGui::Separator();
// Max Motor Impulse
{
float maxMotorImpulse = joint->GetMaxMotorImpulse();
if (ImGuiExt::RenderOptionFloat(maxMotorImpulse, "##joint_option_max_motor_impulse", "Motor Impulse", 0.0f, 32.0f, width))
{
hasChanged = true;
joint->SetMaxMotorImpulse(maxMotorImpulse);
}
}
ImGui::Separator();
// Motor Enabled
{
bool motorEnabled = joint->GetMotorEnabled();
if (ImGuiExt::RenderOptionBool(motorEnabled, "##joint_option_motor_enabled", "Motor Enabled"))
{
hasChanged = true;
joint->SetMotorEnabled(motorEnabled);
}
}
ImGui::Separator();
// Angular Only
{
bool angularOnly = joint->GetAngularOnly();
if (ImGuiExt::RenderOptionBool(angularOnly, "##joint_option_angular_only", "Angular Only"))
{
hasChanged = true;
joint->SetAngularOnly(angularOnly);
}
}
}
if (ImGui::CollapsingHeader("Common", ImGuiTreeNodeFlags_DefaultOpen))
hasChanged = ShowJoint(joint);
return hasChanged;
}
bool WidgetProperties::ShowCD6JointProperties()
{
bool hasChanged = false;
const float width = ImGui::GetWindowContentRegionWidth() - 105.0f;
SPtr<CD6Joint> joint = std::static_pointer_cast<CD6Joint>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("D6 Joint", ImGuiTreeNodeFlags_DefaultOpen))
{
// Lower Lin Limit
{
float lowerLinLimit = joint->GetLowerLinLimit();
if (ImGuiExt::RenderOptionFloat(lowerLinLimit, "##joint_option_lower_lin_limit", "Lower Lin. Limit", 0.0f, 1.0f, width))
{
hasChanged = true;
joint->SetLowerLinLimit(lowerLinLimit);
}
}
// Upper Lin Limit
{
float upperLinLimit = joint->GetUpperLinLimit();
if (ImGuiExt::RenderOptionFloat(upperLinLimit, "##joint_option_upper_lin_limit", "Upper Lin. Limit", 0.0f, 1.0f, width))
{
hasChanged = true;
joint->SetUpperLinLimit(upperLinLimit);
}
}
// Lower Ang. Limit
{
float lowerAngLimit = joint->GetLowerAngLimit().ValueDegrees();
if (ImGuiExt::RenderOptionFloat(lowerAngLimit, "##joint_option_lower_ang_limit", "Lower Ang. Limit", 0.0f, 90.0f, width))
{
hasChanged = true;
joint->SetLowerAngLimit(Degree(lowerAngLimit));
}
}
// Upper Ang. Limit
{
float upperAngLimit = joint->GetUpperAngLimit().ValueDegrees();
if (ImGuiExt::RenderOptionFloat(upperAngLimit, "##joint_option_upper_ang_limit", "Upper Ang. Limit", 0.0f, 90.0f, width))
{
hasChanged = true;
joint->SetUpperAngLimit(Degree(upperAngLimit));
}
}
ImGui::Separator();
// Linear Stiffness
{
float linearStiffness = joint->GetLinearStiffness();
if (ImGuiExt::RenderOptionFloat(linearStiffness, "##joint_option_linear_stiffness", "Lin. Stiffness", 0.0f, 1.0f, width))
{
hasChanged = true;
joint->SetLinearStiffness(linearStiffness);
}
}
// Angular Stiffness
{
float angularStiffness = joint->GetAngularStiffness();
if (ImGuiExt::RenderOptionFloat(angularStiffness, "##joint_option_angular_stiffness", "Ang. Stiffness", 0.0f, 1.0f, width))
{
hasChanged = true;
joint->SetAngularStiffness(angularStiffness);
}
}
// Linear Damping
{
float linearDamping = joint->GetLinearDamping();
if (ImGuiExt::RenderOptionFloat(linearDamping, "##joint_option_linear_damping", "Lin. Damping", 0.0f, 1.0f, width))
{
hasChanged = true;
joint->SetLinearDamping(linearDamping);
}
}
// Angular Damping
{
float angularDamping = joint->GetAngularDamping();
if (ImGuiExt::RenderOptionFloat(angularDamping, "##joint_option_angular_stiffness", "Ang. Damping", 0.0f, 1.0f, width))
{
hasChanged = true;
joint->SetAngularDamping(angularDamping);
}
}
ImGui::Separator();
// Linear Spring
{
bool linearSpring = joint->GetLinearSpring();
if (ImGuiExt::RenderOptionBool(linearSpring, "##joint_option_linear_spring", "Lin. Spring"))
{
hasChanged = true;
joint->SetLinearSpring(linearSpring);
}
}
// Angular Spring
{
bool angularSpring = joint->GetAngularSpring();
if (ImGuiExt::RenderOptionBool(angularSpring, "##joint_option_linear_spring", "Ang. Spring"))
{
hasChanged = true;
joint->SetAngularSpring(angularSpring);
}
}
}
if (ImGui::CollapsingHeader("Common", ImGuiTreeNodeFlags_DefaultOpen))
hasChanged = ShowJoint(joint) ? true : hasChanged;
return hasChanged;
}
bool WidgetProperties::ShowCHingeJointProperties()
{
bool hasChanged = false;
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
SPtr<CHingeJoint> joint = std::static_pointer_cast<CHingeJoint>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Hinge Joint", ImGuiTreeNodeFlags_DefaultOpen))
{
// Softness Limit
{
float softnessLimit = joint->GetSoftnessLimit();
if (ImGuiExt::RenderOptionFloat(softnessLimit, "##joint_option_limit_softness", "Limit Softness", 0.0f, 1.0f, width))
{
hasChanged = true;
joint->SetSoftnessLimit(softnessLimit);
}
}
// Bias Limit
{
float biasLimit = joint->GetBiasLimit();
if (ImGuiExt::RenderOptionFloat(biasLimit, "##joint_option_limit_bias", "Bias Limit", 0.0f, 1.0f, width))
{
hasChanged = true;
joint->SetBiasLimit(biasLimit);
}
}
// Relaxation Limit
{
float biasLimit = joint->GetRelaxationLimit();
if (ImGuiExt::RenderOptionFloat(biasLimit, "##joint_option_limit_relaxation", "Relaxation Limit", 0.0f, 1.0f, width))
{
hasChanged = true;
joint->SetRelaxationLimit(biasLimit);
}
}
ImGui::Separator();
// High Limit
{
float highLimit = joint->GetHighLimit().ValueDegrees();
if (ImGuiExt::RenderOptionFloat(highLimit, "##joint_option_high_limit", "High Limit", 0.0f, 360.0f, width))
{
hasChanged = true;
joint->SetHighLimit(Degree(highLimit));
}
}
// Low Limit
{
float lowLimit = joint->GetLowLimit().ValueDegrees();
if (ImGuiExt::RenderOptionFloat(lowLimit, "##joint_option_low_limit", "Low Limit", 0.0f, 360.0f, width))
{
hasChanged = true;
joint->SetLowLimit(Degree(lowLimit));
}
}
ImGui::Separator();
// Max Motor Impulse
{
float maxMotorImpulse = joint->GetMaxMotorImpulse();
if (ImGuiExt::RenderOptionFloat(maxMotorImpulse, "##joint_option_max_motor_impulse", "Motor Impulse", 0.0f, 32.0f, width))
{
hasChanged = true;
joint->SetMaxMotorImpulse(maxMotorImpulse);
}
}
// Motor Velocity
{
float motorVelocity = joint->GetMotorVelocity();
if (ImGuiExt::RenderOptionFloat(motorVelocity, "##joint_option_motor_velocity", "Motor Velocity", 0.0f, 32.0f, width))
{
hasChanged = true;
joint->SetMotorVelocity(motorVelocity);
}
}
ImGui::Separator();
// Motor Enabled
{
bool motorEnabled = joint->GetMotorEnabled();
if (ImGuiExt::RenderOptionBool(motorEnabled, "##joint_option_motor_enabled", "Motor Enabled"))
{
hasChanged = true;
joint->SetMotorEnabled(motorEnabled);
}
}
ImGui::Separator();
// Angular Only
{
bool angularOnly = joint->GetAngularOnly();
if (ImGuiExt::RenderOptionBool(angularOnly, "##joint_option_angular_only", "Angular Only"))
{
hasChanged = true;
joint->SetAngularOnly(angularOnly);
}
}
}
if (ImGui::CollapsingHeader("Common", ImGuiTreeNodeFlags_DefaultOpen))
hasChanged = ShowJoint(joint) ? true : hasChanged;
return hasChanged;
}
bool WidgetProperties::ShowCSliderJointProperties()
{
bool hasChanged = false;
const float width = ImGui::GetWindowContentRegionWidth() - 165.0f;
SPtr<CSliderJoint> joint = std::static_pointer_cast<CSliderJoint>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Slider Joint", ImGuiTreeNodeFlags_DefaultOpen))
{
// Lower Lin Limit
{
float lowerLinLimit = joint->GetLowerLinLimit();
if (ImGuiExt::RenderOptionFloat(lowerLinLimit, "##joint_option_lower_lin_limit", "Lower Lin. Limit", 0.0f, 1.0f, width))
{
hasChanged = true;
joint->SetLowerLinLimit(lowerLinLimit);
}
}
// Upper Lin Limit
{
float upperLinLimit = joint->GetUpperLinLimit();
if (ImGuiExt::RenderOptionFloat(upperLinLimit, "##joint_option_upper_lin_limit", "Upper Lin. Limit", 0.0f, 1.0f, width))
{
hasChanged = true;
joint->SetUpperLinLimit(upperLinLimit);
}
}
// Lower Ang. Limit
{
float lowerAngLimit = joint->GetLowerAngLimit().ValueDegrees();
if (ImGuiExt::RenderOptionFloat(lowerAngLimit, "##joint_option_lower_ang_limit", "Lower Ang. Limit", 0.0f, 90.0f, width))
{
hasChanged = true;
joint->SetLowerAngLimit(Degree(lowerAngLimit));
}
}
// Upper Ang. Limit
{
float upperAngLimit = joint->GetUpperAngLimit().ValueDegrees();
if (ImGuiExt::RenderOptionFloat(upperAngLimit, "##joint_option_upper_ang_limit", "Upper Ang. Limit", 0.0f, 90.0f, width))
{
hasChanged = true;
joint->SetUpperAngLimit(Degree(upperAngLimit));
}
}
ImGui::Separator();
// Softness Dir Lin
{
float softnessDirLin = joint->GetSoftnessDirLin();
if (ImGuiExt::RenderOptionFloat(softnessDirLin, "##joint_option_softness_dir_lin", "Softness Dir. Lin.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetSoftnessDirLin(softnessDirLin);
}
}
// Restitution Dir Lin
{
float restitutionDirLin = joint->GetRestitutionDirLin();
if (ImGuiExt::RenderOptionFloat(restitutionDirLin, "##joint_option_restitution_dir_lin", "Restitution Dir. Lin.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetRestitutionDirLin(restitutionDirLin);
}
}
// Dampling Dir Lin
{
float dampingDirLin = joint->GetDampingDirLin();
if (ImGuiExt::RenderOptionFloat(dampingDirLin, "##joint_option_dampling_dir_lin", "Dampling Dir. Lin.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetDampingDirLin(dampingDirLin);
}
}
ImGui::Separator();
// Softness Dir Ang
{
float softnessDirAng = joint->GetSoftnessDirAng();
if (ImGuiExt::RenderOptionFloat(softnessDirAng, "##joint_option_softness_dir_ang", "Softness Dir. Ang.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetSoftnessDirAng(softnessDirAng);
}
}
// Restitution Dir Ang
{
float restitutionDirAng = joint->GetRestitutionDirAng();
if (ImGuiExt::RenderOptionFloat(restitutionDirAng, "##joint_option_resitution_dir_ang", "Resitution Dir. Ang.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetRestitutionDirAng(restitutionDirAng);
}
}
// Damping Dir Ang
{
float dampingDirAng = joint->GetDampingDirAng();
if (ImGuiExt::RenderOptionFloat(dampingDirAng, "##joint_option_damping_dir_ang", "Damping Dir. Ang.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetDampingDirAng(dampingDirAng);
}
}
ImGui::Separator();
// Softness Lim Lin
{
float softnessLimLin = joint->GetSoftnessLimLin();
if (ImGuiExt::RenderOptionFloat(softnessLimLin, "##joint_option_softness_lim_lin", "Softness Lim. Lin.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetSoftnessLimLin(softnessLimLin);
}
}
// Restitution Lim Lin
{
float restitutionLimLin = joint->GetRestitutionLimLin();
if (ImGuiExt::RenderOptionFloat(restitutionLimLin, "##joint_option_restitution_lim_lin", "Restitution Lim. Lin.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetRestitutionLimLin(restitutionLimLin);
}
}
// Damping Lim Lin
{
float dampingLimLin = joint->GetDampingLimLin();
if (ImGuiExt::RenderOptionFloat(dampingLimLin, "##joint_option_damping_lim_lin", "Damping Lim. Lin.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetDampingLimLin(dampingLimLin);
}
}
ImGui::Separator();
// Softness Lim Ang
{
float softnessLimAng = joint->GetSoftnessLimAng();
if (ImGuiExt::RenderOptionFloat(softnessLimAng, "##joint_option_softness_lim_ang", "Softness Lim. Ang.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetSoftnessLimAng(softnessLimAng);
}
}
// Restitution Lim Ang
{
float restitutionLimAng = joint->GetRestitutionLimAng();
if (ImGuiExt::RenderOptionFloat(restitutionLimAng, "##joint_option_restitution_lim_ang", "Restitution Lim. Ang.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetRestitutionLimAng(restitutionLimAng);
}
}
// Damping Lim Ang
{
float dampingLimAng = joint->GetDampingLimAng();
if (ImGuiExt::RenderOptionFloat(dampingLimAng, "##joint_option_damping_lim_ang", "Damping Lim. Ang.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetDampingLimAng(dampingLimAng);
}
}
ImGui::Separator();
// Softness Lim Ortho Lin
{
float softnessOrthoLin = joint->GetSoftnessOrthoLin();
if (ImGuiExt::RenderOptionFloat(softnessOrthoLin, "##joint_option_softness_lim_ortho_lin", "Softness Lim. Ortho Lin.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetSoftnessOrthoLin(softnessOrthoLin);
}
}
// Restitution Lim Ortho Lin
{
float restitutionOrthoLin = joint->GetRestitutionOrthoLin();
if (ImGuiExt::RenderOptionFloat(restitutionOrthoLin, "##joint_option_restitution_lim_ortho_lin", "Restitution Lim. Ortho Lin.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetRestitutionOrthoLin(restitutionOrthoLin);
}
}
// Damping Lim Ortho Lin
{
float dampingOrthoLin = joint->GetDampingOrthoLin();
if (ImGuiExt::RenderOptionFloat(dampingOrthoLin, "##joint_option_damping_lim_ortho_lin", "Damping Lim. Ortho Lin.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetDampingOrthoLin(dampingOrthoLin);
}
}
ImGui::Separator();
// Softness Lim Ortho Ang
{
float softnessOrthoAng = joint->GetSoftnessOrthoAng();
if (ImGuiExt::RenderOptionFloat(softnessOrthoAng, "##joint_option_softness_lim_ortho_ang", "Softness Lim. Ortho Ang.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetSoftnessOrthoAng(softnessOrthoAng);
}
}
// Restitution Lim Ortho Ang
{
float restitutionOrthoAng = joint->GetRestitutionOrthoAng();
if (ImGuiExt::RenderOptionFloat(restitutionOrthoAng, "##joint_option_restitution_lim_ortho_ang", "Restitution Lim. Ortho Ang.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetRestitutionOrthoAng(restitutionOrthoAng);
}
}
// Damping Lim Ortho Ang
{
float dampingOrthoAng = joint->GetDampingOrthoAng();
if (ImGuiExt::RenderOptionFloat(dampingOrthoAng, "##joint_option_damping_lim_ortho_ang", "Damping Lim. Ortho Ang.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetDampingOrthoAng(dampingOrthoAng);
}
}
ImGui::Separator();
// Target Lin Motor Velocity
{
float targetLinMotorVelocity = joint->GetTargetLinMotorVelocity();
if (ImGuiExt::RenderOptionFloat(targetLinMotorVelocity, "##joint_option_target_lin_motor_velocity", "Target Lin. Motor Vel.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetTargetLinMotorVelocity(targetLinMotorVelocity);
}
}
// Max Lin Motor Force
{
float maxLinMotorForce = joint->GetMaxLinMotorForce();
if (ImGuiExt::RenderOptionFloat(maxLinMotorForce, "##joint_option_target_max_lin_motor_force", "Max Lin. Motor Force", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetMaxLinMotorForce(maxLinMotorForce);
}
}
// Target Ang Motor Velocity
{
float targetAngMotorVelocity = joint->GetTargetAngMotorVelocity();
if (ImGuiExt::RenderOptionFloat(targetAngMotorVelocity, "##joint_option_target_max_lin_motor_force", "Target Ang. Motor Vel.", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetTargetAngMotorVelocity(targetAngMotorVelocity);
}
}
// Max Ang Motor Force
{
float maxAngMotorForce = joint->GetMaxAngMotorForce();
if (ImGuiExt::RenderOptionFloat(maxAngMotorForce, "##joint_option_target_max_ang_motor_force", "Max Ang. Motor Force", 0.0f, 4.0f, width))
{
hasChanged = true;
joint->SetMaxAngMotorForce(maxAngMotorForce);
}
}
ImGui::Separator();
// Power Lin Motor
{
bool poweredLinMotor = joint->GetPoweredLinMotor();
if (ImGuiExt::RenderOptionBool(poweredLinMotor, "##joint_option_powered_lin_motor", "Powered Lin. Motor"))
{
hasChanged = true;
joint->SetPoweredLinMotor(poweredLinMotor);
}
}
// Power Ang Motor
{
bool poweredAngMotor = joint->GetPoweredAngMotor();
if (ImGuiExt::RenderOptionBool(poweredAngMotor, "##joint_option_powered_ang_motor", "Powered Ang. Motor"))
{
hasChanged = true;
joint->SetPoweredAngMotor(poweredAngMotor);
}
}
ImGui::Separator();
}
if (ImGui::CollapsingHeader("Common", ImGuiTreeNodeFlags_DefaultOpen))
hasChanged = ShowJoint(joint) ? true : hasChanged;
return hasChanged;
}
bool WidgetProperties::ShowCSphericalJointProperties()
{
bool hasChanged = false;
SPtr<CSphericalJoint> joint = std::static_pointer_cast<CSphericalJoint>(_selections.ClickedComponent);
if (ImGui::CollapsingHeader("Spherical Joint", ImGuiTreeNodeFlags_DefaultOpen))
{
// Anchor Pivot Offset
{
Vector3 pivot = joint->GetOffsetPivot(JointBody::Anchor);
if (ImGuiExt::RenderVector3(pivot, "##joint_option_anchor_offset", " Anchor Pivot", 20.0f))
{
joint->SetOffsetPivot(JointBody::Anchor, pivot);
hasChanged = true;
}
}
// Anchor Pivot Offset
{
Vector3 pivot = joint->GetOffsetPivot(JointBody::Target);
if (ImGuiExt::RenderVector3(pivot, "##joint_option_target_offset", " Target Pivot", 20.0f))
{
joint->SetOffsetPivot(JointBody::Target, pivot);
hasChanged = true;
}
}
}
if (ImGui::CollapsingHeader("Common", ImGuiTreeNodeFlags_DefaultOpen))
hasChanged = ShowJoint(joint) ? true : hasChanged;
return hasChanged;
}
bool WidgetProperties::ShowCDecal()
{
bool hasChanged = false;
SPtr<CDecal> decalCO = std::static_pointer_cast<CDecal>(_selections.ClickedComponent);
SPtr<Decal> decalPtr = decalCO->GetInternal();
ObjectMobility mobility = decalPtr->GetMobility();
Transform transform = decalCO->GetSceneObject()->GetTransform();
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
if (ShowTransform(transform, mobility))
{
decalPtr->SetMobility(mobility);
decalCO->GetSceneObject()->SetLocalTransform(transform);
hasChanged = true;
}
if (ImGui::CollapsingHeader("Properties", ImGuiTreeNodeFlags_DefaultOpen))
{
// Size
{
Vector2 size = decalCO->GetSize();
if (ImGuiExt::RenderVector2(size, "##decal_size_option", " Size", 20.0f))
{
hasChanged = true;
decalCO->SetSize(size);
}
}
// Max distance
{
float maxDistance = decalCO->GetMaxDistance();
if (ImGuiExt::RenderOptionFloat(maxDistance, "##decal_max_distance_option", "Max Distance", 0.0f, 512.0f, width - 20.0f))
{
hasChanged = true;
decalCO->SetMaxDistance(maxDistance);
}
}
}
return hasChanged;
}
bool WidgetProperties::ShowTransform(Transform& transform, ObjectMobility& mobility, bool disableTransform)
{
bool hasChanged = false;
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
if (ImGui::CollapsingHeader("Transform", ImGuiTreeNodeFlags_DefaultOpen))
{
static ImGuiExt::ComboOptions<int> mobilityOptions;
if (mobilityOptions.Options.size() == 0)
{
mobilityOptions.AddOption((int)ObjectMobility::Movable, "Movable");
mobilityOptions.AddOption((int)ObjectMobility::Immovable, "Immovable");
mobilityOptions.AddOption((int)ObjectMobility::Static, "Static");
}
if (ImGuiExt::RenderOptionCombo<int>((int*)(&mobility), "##transform_mobility_option", "Mobility", mobilityOptions, width,
disableTransform ? (UINT8)ImGuiExt::ComboOptionFlag::Disable : 0))
hasChanged = true;
ImGui::Separator();
if (ImGuiExt::RenderTransform(transform, "transform_option", disableTransform))
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowGameObjectInformation(const SPtr<GameObject>& gameObject)
{
char inputName[256];
char inputUUID[64];
bool hasChanged = false;
String name = gameObject->GetName();
String uuid = gameObject->GetUUID().ToString();
const float widgetWidth = ImGui::GetWindowContentRegionWidth() - 100.0f;
if(name.length() < 256)
strcpy(inputName, name.c_str());
else
strcpy(inputName, name.substr(0,255).c_str());
strcpy(inputUUID, uuid.c_str());
if (ImGui::CollapsingHeader("Identification", ImGuiTreeNodeFlags_DefaultOpen))
{
ImGui::PushItemWidth(widgetWidth);
if (ImGui::InputText("Name", inputName, IM_ARRAYSIZE(inputName)))
{
gameObject->SetName(inputName);
hasChanged = true;
}
ImGui::Separator();
ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true);
ImGui::InputText("UUID", inputUUID, IM_ARRAYSIZE(inputUUID));
ImGui::PopItemFlag();
ImGui::PopItemWidth();
}
return hasChanged;
}
bool WidgetProperties::ShowCamera(SPtr<CCamera> camera)
{
bool hasChanged = false;
HCamera cameraHandle = camera;
auto& cameraSettings = camera->GetRenderSettings();
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
if (ImGui::CollapsingHeader("Graphics", ImGuiTreeNodeFlags_DefaultOpen))
{
if (ImGuiExt::RenderCameraGraphics(cameraHandle, cameraSettings, width))
hasChanged = true;
}
if (ImGuiExt::RenderCameraPostProcessing(cameraHandle, cameraSettings, width))
hasChanged = true;
if (hasChanged)
camera->SetRenderSettings(cameraSettings);
return hasChanged;
}
bool WidgetProperties::ShowCameraFlyer(SPtr<CCameraFlyer> cameraFlyer)
{
bool hasChanged = false;
Degree pitch = cameraFlyer->GetPitch();
Degree yaw = cameraFlyer->GetYaw();
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
float pitchAngle = pitch.ValueDegrees();
float yawAngle = yaw.ValueDegrees();
ImGuiExt::RenderOptionFloat(pitchAngle, "##camera_fliyer_pitch_option", "Current pitch", -180.0f, 180.0f, width, true);
ImGuiExt::RenderOptionFloat(yawAngle, "##camera_fliyer_yaw_option", "Current yaw", -180.0f, 180.0f, width, true);
return hasChanged;
}
bool WidgetProperties::ShowCamerUI(SPtr<CCameraUI> cameraUI)
{
bool hasChanged = false;
Vector3 target = cameraUI->GetTarget();
if (ImGuiExt::RenderVector3(target, "##camera_ui_target_option", " Target", 20.0f, false))
{
cameraUI->SetTarget(target);
hasChanged = true;
}
return hasChanged;
}
bool WidgetProperties::ShowLight(SPtr<Light> light)
{
bool hasChanged = false;
float attenuationRadius = light->GetAttenuationRadius();
float linearAttenuation = light->GetLinearAttenuation();
float quadraticAttenuation = light->GetQuadraticAttenuation();
float intensity = light->GetIntensity();
Degree spotAngle = light->GetSpotAngle();
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
// Color
{
Vector4 color = light->GetColor().GetAsVector4();
if (ImGuiExt::RenderColorRGBA(color, "##light_color_option", "Color", width))
{
hasChanged = true;
light->SetColor(Color(color));
}
}
ImGui::Separator();
if (light->GetType() != LightType::Directional)
{
// Attenuation radius
{
if (ImGuiExt::RenderOptionFloat(attenuationRadius, "##light_attenuation_radius_option", "Att. Radius", 0.0f, 5.0f, width))
{
hasChanged = true;
light->SetAttenuationRadius(attenuationRadius);
}
}
ImGui::Separator();
// Linear attenuation
{
if (ImGuiExt::RenderOptionFloat(linearAttenuation, "##light_linear_attenuation_option", "Linear att.", 0.0f, 1.0f, width))
{
hasChanged = true;
light->SetLinearAttenuation(linearAttenuation);
}
}
ImGui::Separator();
// quadratic attenuation
{
if (ImGuiExt::RenderOptionFloat(quadraticAttenuation, "##light_quadratic_attenuation_option", "Quadratic att.", 0.0f, 1.0f, width))
{
hasChanged = true;
light->SetQuadraticAttenuation(quadraticAttenuation);
}
}
ImGui::Separator();
}
// intensity
{
if (ImGuiExt::RenderOptionFloat(intensity, "##light_intensity_option", "Intensity", 0.0f, 16.0f, width))
{
hasChanged = true;
light->SetIntensity(intensity);
}
}
ImGui::Separator();
// Spot angle
if (light->GetType() == LightType::Spot)
{
{
float angle = spotAngle.ValueDegrees();
if (ImGuiExt::RenderOptionFloat(angle, "##light_spot_angle_option", "Spot angle", 0.0f, 179.0f, width))
{
hasChanged = true;
light->SetSpotAngle(Degree(angle));
}
}
}
return hasChanged;
}
bool WidgetProperties::ShowLightShadow(SPtr<Light> light)
{
bool hasChanged = false;
bool castShadows = light->GetCastShadows();
float shadowBias = light->GetShadowBias();
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
// Cast shadows
{
if (ImGuiExt::RenderOptionBool(castShadows, "##light_cast_shadows_option", "Cast shadows"))
{
hasChanged = true;
light->SetCastShadows(castShadows);
}
}
ImGui::Separator();
// Shadow bias
{
if (ImGuiExt::RenderOptionFloat(shadowBias, "##light_shadow_bias_option", "Shadow bias", 0.0f, 5.0f, width))
{
hasChanged = true;
light->SetShadowBias(shadowBias);
}
}
return hasChanged;
}
bool WidgetProperties::ShowRenderableProperties(SPtr<Renderable> renderable)
{
bool hasChanged = false;
const RenderableProperties& properties = renderable->GetProperties();
const SPtr<Mesh> mesh = renderable->GetMesh();
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
ImGuiExt::ComboOptions<UUID> meshesOptions;
UUID emptyMesh = UUID(50, 0, 0, 0);
UUID loadMesh = UUID::EMPTY;
UUID meshUUID = (mesh) ? mesh->GetUUID() : emptyMesh;
EditorResManager::ResourcesContainer& container = EditorResManager::Instance().Get<Mesh>();
// current mesh to use
{
for (auto& resource : container.Res)
meshesOptions.AddOption(resource.second->GetUUID(), resource.second->GetName());
meshesOptions.AddOption(emptyMesh, ICON_FA_TIMES_CIRCLE " No mesh");
meshesOptions.AddOption(UUID::EMPTY, ICON_FA_FOLDER_OPEN " Load");
if (ImGuiExt::RenderOptionCombo<UUID>(&meshUUID, "##meshes_option", "Mesh", meshesOptions, width))
{
if (meshUUID == loadMesh)
{
_loadMesh = true;
}
else if (meshUUID == emptyMesh)
{
renderable->SetMesh(nullptr);
renderable->ClearAllMaterials();
hasChanged = true;
}
else if (meshUUID != ((mesh) ? mesh->GetUUID() : emptyMesh))
{
renderable->SetMesh(gResourceManager().Load<Mesh>(meshUUID).GetInternalPtr());
renderable->ClearAllMaterials();
hasChanged = true;
// We check if a material exists on each subMesh. In this case, we apply the material on the renderable
for (UINT32 i = 0; i < renderable->GetMesh()->GetProperties().GetNumSubMeshes(); i++)
{
SubMesh& subMesh = renderable->GetMesh()->GetProperties().GetSubMesh(i);
if (subMesh.Mat.IsLoaded())
renderable->SetMaterial(i, subMesh.Mat.GetInternalPtr());
}
}
}
if (ShowLoadMesh())
hasChanged = true;
}
ImGui::Separator();
// velocity
{
bool writeVelocity = properties.WriteVelocity;
if (ImGuiExt::RenderOptionBool(writeVelocity, "##renderable_properties_velocity_option", "Write velocity"))
{
hasChanged = true;
renderable->SetWriteVelocity(writeVelocity);
}
}
ImGui::Separator();
// instancing
{
bool instancing = properties.Instancing;
if (ImGuiExt::RenderOptionBool(instancing, "##renderable_properties_instancing_option", "Instancing"))
{
hasChanged = true;
renderable->SetInstancing(instancing);
}
}
ImGui::Separator();
// can be merged
{
bool canBeMerged = properties.CanBeMerged;
if (ImGuiExt::RenderOptionBool(canBeMerged, "##renderable_properties_can_be_merged_option", "Merging"))
{
hasChanged = true;
renderable->SetCanBeMerged(canBeMerged);
}
}
ImGui::Separator();
// cast shadows
{
bool castShadows = properties.CastShadows;
if (ImGuiExt::RenderOptionBool(castShadows, "##renderable_properties_cast_shadows_option", "Cast shadows"))
{
hasChanged = true;
renderable->SetCastShadows(castShadows);
}
}
ImGui::Separator();
// receive shadows
{
bool receiveShadows = properties.ReceiveShadows;
if (ImGuiExt::RenderOptionBool(receiveShadows, "##renderable_properties_receive_shadows_option", "Receive shadows"))
{
hasChanged = true;
renderable->SetReceiveShadows(receiveShadows);
}
}
ImGui::Separator();
// cast lights
{
bool castLights = properties.CastLights;
if (ImGuiExt::RenderOptionBool(castLights, "##renderable_properties_cast_lights_option", "Cast lights"))
{
hasChanged = true;
renderable->SetCastLight(castLights);
}
}
ImGui::Separator();
// use for dynamic env mapping
{
bool useForDynamicEnvMapping = properties.UseForDynamicEnvMapping;
if (ImGuiExt::RenderOptionBool(useForDynamicEnvMapping, "##renderable_properties_dynamic_env_mapping_option", "Dynamic env mapping"))
{
hasChanged = true;
renderable->SetUseForDynamicEnvMapping(useForDynamicEnvMapping);
}
}
ImGui::Separator();
// cull distance factor
{
float cullDistanceFactor = properties.CullDistanceFactor;
if (ImGuiExt::RenderOptionFloat(cullDistanceFactor, "##renderable_properties_dynamic_env_mapping_option", "Cull dist. factor", 0.0f, 1.0f, width - 20.0f))
{
hasChanged = true;
renderable->SetCullDistanceFactor(cullDistanceFactor);
}
}
return hasChanged;
}
bool WidgetProperties::ShowRenderableSubMeshes(SPtr<Renderable> renderable)
{
bool hasChanged = false;
SPtr<Mesh> mesh = renderable->GetMesh();
ImGuiExt::ComboOptions<UUID> materialsOptions;
UUID emptyMaterial = UUID(50, 0, 0, 0);
MeshProperties& meshProperties = mesh->GetProperties();
const float width = ImGui::GetWindowContentRegionWidth() - 120.0f;
EditorResManager::ResourcesContainer& container = EditorResManager::Instance().Get<Material>();
for (auto& resource : container.Res)
materialsOptions.AddOption(resource.second->GetUUID(), resource.second->GetName());
materialsOptions.AddOption(emptyMaterial, ICON_FA_TIMES_CIRCLE " No material");
for (UINT32 i = 0; i < meshProperties.GetNumSubMeshes(); i++)
{
SPtr<Material> material = renderable->GetMaterial(i);
UUID materialUUID = (material) ? material->GetUUID() : emptyMaterial;
SubMesh& subMesh = meshProperties.GetSubMesh(i);
String title = subMesh.MaterialName;
String id = "##" + subMesh.MaterialName + ToString(i);
// current material to use
{
if (ImGuiExt::RenderOptionCombo<UUID>(&materialUUID, id.c_str(), title.c_str(), materialsOptions, width))
{
if (materialUUID == emptyMaterial)
{
renderable->SetMaterial(i, nullptr);
hasChanged = true;
}
else
{
renderable->SetMaterial(i, gResourceManager().Load<Material>(materialUUID).GetInternalPtr());
hasChanged = true;
}
}
}
}
return hasChanged;
}
bool WidgetProperties::ShowScript(SPtr<CScript> script)
{
bool hasChanged = false;
Vector<String> files;
Vector<String> directories;
Vector<String> identifiers;
ImGuiExt::ComboOptions<ScriptIdentifier> scriptsOptions;
const float width = ImGui::GetWindowContentRegionWidth() - 50.0f;
FileSystem::GetChildren(RAW_APP_ROOT + ScriptManager::LIBRARIES_PATH, files, directories, true);
// current script to use
{
for (auto& file : files)
{
if(file.length() > 4)
{
if(file.substr(file.length() - 4, 4) == ".cpp")
{
String fileName = file.substr(0, file.length() - 4);
ScriptIdentifier ident(fileName);
scriptsOptions.AddOption(ident, fileName);
identifiers.push_back(ident.Name);
}
}
}
const auto& scriptLibraries = gScriptManager().GetScriptLibraries();
for (auto& scriptLibrary : scriptLibraries)
{
if (std::find(identifiers.begin(), identifiers.end(), scriptLibrary.first.Name) == identifiers.end())
{
scriptsOptions.AddOption(scriptLibrary.first, scriptLibrary.first.Name);
identifiers.push_back(scriptLibrary.first.Name);
}
}
scriptsOptions.AddOption(ScriptIdentifier(""), ICON_FA_TIMES_CIRCLE " No script");
scriptsOptions.AddOption(ScriptIdentifier("_"), ICON_FA_FOLDER_OPEN " Load");
ScriptIdentifier previousScript(script->GetNativeScriptName(), script->GetNativeScriptPath());
ScriptIdentifier currentScript = previousScript;
if (ImGuiExt::RenderOptionCombo<ScriptIdentifier>(¤tScript, "##scripts_options", "Script", scriptsOptions, width))
{
if (currentScript.Name == "_")
{
_loadScript = true;
}
else if (currentScript.Name != previousScript.Name)
{
script->SetNativeScript(currentScript);
hasChanged = true;
}
}
}
if (ShowLoadScript())
hasChanged = true;
return hasChanged;
}
bool WidgetProperties::ShowAnimation(SPtr<CAnimation> animation)
{
bool hasChanged = false;
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
// cull
{
bool cull = animation->GetEnableCull();
if (ImGuiExt::RenderOptionBool(cull, "##animation_cull_option", "Culling"))
{
hasChanged = true;
animation->SetEnableCull(cull);
}
}
ImGui::Separator();
// speed
{
float speed = animation->GetSpeed();
if (ImGuiExt::RenderOptionFloat(speed, "##animation_speed_option", "Speed", 0.1f, 10.0f, width))
{
hasChanged = true;
animation->SetSpeed(speed);
}
}
ImGui::Separator();
// wrap mode
{
static ImGuiExt::ComboOptions<AnimWrapMode> wrapModeOptions;
if (wrapModeOptions.Options.size() == 0)
{
wrapModeOptions.AddOption(AnimWrapMode::Loop, "Loop");
wrapModeOptions.AddOption(AnimWrapMode::Clamp, "Clamp");
}
AnimWrapMode wrapMode = animation->GetWrapMode();
if (ImGuiExt::RenderOptionCombo<AnimWrapMode>(&wrapMode, "##animation_wrap_mode_option", "Wrap mode", wrapModeOptions, width))
{
hasChanged = true;
animation->SetWrapMode(wrapMode);
}
}
ImGui::Separator();
// bounds
{
AABox bounds = animation->GetBounds();
Vector3 minBound = bounds.GetMin();
Vector3 maxBound = bounds.GetMax();
if (ImGuiExt::RenderVector3(minBound, "##animation_min_bound_option", " Min bound", 40.0f))
{
bounds.SetMin(minBound);
animation->SetBounds(bounds);
hasChanged = true;
}
if (ImGuiExt::RenderVector3(maxBound, "##animation_max_bound_option", " Max bound", 40.0f))
{
bounds.SetMax(maxBound);
animation->SetBounds(bounds);
hasChanged = true;
}
}
return hasChanged;
}
bool WidgetProperties::ShowAnimationClips(SPtr<CAnimation> animation)
{
bool hasChanged = false;
char inputName[256];
UINT32 numClip = animation->GetNumClips();
const float widgetWidth = ImGui::GetWindowContentRegionWidth() - 100.0f;
for (UINT32 i = 0; i < numClip; i++)
{
HAnimationClip clip = animation->GetClip(i);
String name = clip->GetName();
ImGui::PushID((int)clip->GetInternalID());
if (ImGui::CollapsingHeader(name.c_str(), ImGuiTreeNodeFlags_DefaultOpen))
{
memset(&inputName, 0, 256);
if(name.length() < 256)
strcpy(inputName, name.c_str());
else
strcpy(inputName, name.substr(0,255).c_str());
ImGui::PushItemWidth(widgetWidth);
if (ImGui::InputText("Name", inputName, IM_ARRAYSIZE(inputName)))
{
clip->SetName(inputName);
hasChanged = true;
}
ImGui::PopItemWidth();
}
ImGui::PopID();
}
return hasChanged;
}
bool WidgetProperties::ShowSkybox(SPtr<Skybox> skybox)
{
bool hasChanged = false;
float brigtness = skybox->GetBrightness();
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
ImGuiExt::ComboOptions<UUID> texturesOptions;
UUID emptyTexture = UUID(50, 0, 0, 0);
UUID loadTexture = UUID::EMPTY;
UUID textureUUID = (skybox->GetTexture()) ? skybox->GetTexture()->GetUUID() : emptyTexture;
UUID irradianceuUUID = (skybox->GetIrradiance()) ? skybox->GetIrradiance()->GetUUID() : emptyTexture;
EditorResManager::ResourcesContainer& container = EditorResManager::Instance().Get<Texture>();
for (auto& resource : container.Res)
{
SPtr<Texture> texture = std::static_pointer_cast<Texture>(resource.second.GetInternalPtr());
if (texture->GetProperties().GetTextureType() == TextureType::TEX_TYPE_CUBE_MAP)
texturesOptions.AddOption(resource.second->GetUUID(), resource.second->GetName());
}
texturesOptions.AddOption(emptyTexture, ICON_FA_TIMES_CIRCLE " No texture");
texturesOptions.AddOption(UUID::EMPTY, ICON_FA_FOLDER_OPEN " Load");
// current texture to use
{
if (ImGuiExt::RenderOptionCombo<UUID>(&textureUUID, "##skybox_texture_option", "Texture", texturesOptions, width))
{
if (textureUUID == loadTexture)
{
_loadSkybox = true;
}
else if (textureUUID == emptyTexture)
{
skybox->SetTexture(nullptr);
hasChanged = true;
}
else
{
skybox->SetTexture(gResourceManager().Load<Texture>(textureUUID).GetInternalPtr());
hasChanged = true;
}
}
}
ImGui::Separator();
// current irradiance texture to use
{
if (ImGuiExt::RenderOptionCombo<UUID>(&irradianceuUUID, "##skybox_texture_irradiance_option", "Irradiance", texturesOptions, width))
{
if (irradianceuUUID == loadTexture)
{
_loadSkyboxIrradiance = true;
}
else if (irradianceuUUID == emptyTexture)
{
skybox->SetIrradiance(nullptr);
hasChanged = true;
}
else
{
skybox->SetIrradiance(gResourceManager().Load<Texture>(irradianceuUUID).GetInternalPtr());
hasChanged = true;
}
}
}
ImGui::Separator();
if (ImGuiExt::RenderOptionFloat(brigtness, "##skybox_option", "Brightness", 0.0f, 3.0f, width))
{
skybox->SetBrightness(brigtness);
hasChanged = true;
}
if (ShowLoadSkybox())
hasChanged = true;
return hasChanged;
}
bool WidgetProperties::ShowBody(SPtr<CBody> body)
{
bool hasChanged = false;
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
// Is Kinematic
{
bool isKinematic = body->GetIsKinematic();
if (ImGuiExt::RenderOptionBool(isKinematic, "##body_option_is_kinematic", "Is Kinematic"))
{
body->SetIsKinematic(isKinematic);
hasChanged = true;
}
}
ImGui::Separator();
// Is Trigger
{
bool isTrigger = body->GetIsTrigger();
if (ImGuiExt::RenderOptionBool(isTrigger, "##body_option_is_trigger", "Is trigger"))
{
body->SetIsTrigger(isTrigger);
hasChanged = true;
}
}
ImGui::Separator();
// Is Debug
{
bool isDebug = body->GetIsDebug();
if (ImGuiExt::RenderOptionBool(isDebug, "##body_option_is_debug", "Display Debug Info"))
{
body->SetIsDebug(isDebug);
hasChanged = true;
}
}
ImGui::Separator();
// Continuous Collision Detection (CCD)
{
UINT32 flags = (UINT32)body->GetFlags();
bool ccd = flags & (UINT32)BodyFlag::CCD;
if (ImGuiExt::RenderOptionBool(ccd, "##body_option_ccd", "Cont. Collision Detect."))
{
if (ccd)
flags |= (UINT32)BodyFlag::CCD;
else
flags &= ~(UINT32)BodyFlag::CCD;
body->SetFlags((BodyFlag)flags);
hasChanged = true;
}
}
ImGui::Separator();
// Collision report mode
{
static ImGuiExt::ComboOptions<CollisionReportMode> collisionModeOptions;
if (collisionModeOptions.Options.size() == 0)
{
collisionModeOptions.AddOption(CollisionReportMode::None, "Never");
collisionModeOptions.AddOption(CollisionReportMode::Report, "Report");
collisionModeOptions.AddOption(CollisionReportMode::ReportPersistent, "Report continuous");
}
CollisionReportMode collisionMode = body->GetCollisionReportMode();
if (ImGuiExt::RenderOptionCombo<CollisionReportMode>(&collisionMode,
"##body_option_collision_mode", "Collision report", collisionModeOptions, width))
{
body->SetCollisionReportMode(collisionMode);
hasChanged = true;
}
}
ImGui::Separator();
// Mass
{
float mass = body->GetMass();
if (ImGuiExt::RenderOptionFloat(mass, "##body_option_mass", "Mass", 0.0f, 512.0f, width))
{
body->SetMass(mass);
hasChanged = true;
}
}
ImGui::Separator();
// Friction
{
float friction = body->GetFriction();
if (ImGuiExt::RenderOptionFloat(friction, "##body_option_friction", "Friction", 0.0f, 8.0f, width))
{
body->SetFriction(friction);
hasChanged = true;
}
}
// Rolling friction
{
float rollingFriction = body->GetRollingFriction();
if (ImGuiExt::RenderOptionFloat(rollingFriction, "##body_option_rolling_friction", "Rolling Friction", 0.0f, 8.0f, width))
{
body->SetRollingFriction(rollingFriction);
hasChanged = true;
}
}
ImGui::Separator();
// Restitution
{
float restitution = body->GetRestitution();
if (ImGuiExt::RenderOptionFloat(restitution, "##body_option_restitution", "Restitution", 0.0f, 4.0f, width))
{
body->SetRestitution(restitution);
hasChanged = true;
}
}
ImGui::Separator();
// Velocity
{
Vector3 velocity = body->GetVelocity();
if (ImGuiExt::RenderVector3(velocity, "##body_option_velocity", " Velocity", 60.0f))
{
body->SetVelocity(velocity);
hasChanged = true;
}
}
// Angular velocity
{
Vector3 angularVelocity = body->GetAngularVelocity();
if (ImGuiExt::RenderVector3(angularVelocity, "##body_option_angular_velocity", " Angular Velocity", 60.0f))
{
body->SetAngularVelocity(angularVelocity);
hasChanged = true;
}
}
return hasChanged;
}
bool WidgetProperties::ShowCollider(SPtr<CCollider> collider)
{
bool hasChanged = false;
// Scale
{
Vector3 scale = collider->GetScale();
if (ImGuiExt::RenderVector3(scale, "##collider_option_scale", " Scale", 20.0f))
{
collider->SetScale(scale);
hasChanged = true;
}
}
// Center
{
Vector3 center = collider->GetCenter();
if (ImGuiExt::RenderVector3(center, "##collider_option_center", " Center", 20.0f))
{
collider->SetCenter(center);
hasChanged = true;
}
}
ImGui::Separator();
// Position
{
Vector3 position = collider->GetPosition();
if (ImGuiExt::RenderVector3(position, "##collider_option_position", " Position", 20.0f))
{
collider->SetPosition(position);
hasChanged = true;
}
}
// Rotation
{
Radian x, y, z;
collider->GetRotation().ToEulerAngles(x, y, z);
Vector3 rotation(x.ValueDegrees(), y.ValueDegrees(), z.ValueDegrees());
if (ImGuiExt::RenderVector3(rotation, "##collider_option_rotation", " Rotation", 20.0f))
{
Quaternion rot;
rot.FromEulerAngles(Radian(Degree(rotation.x)), Radian(Degree(rotation.y)), Radian(Degree(rotation.z)));
collider->SetRotation(rot);
hasChanged = true;
}
}
return hasChanged;
}
bool WidgetProperties::ShowJoint(SPtr<CJoint> joint)
{
bool hasChanged = false;
const float width = ImGui::GetWindowContentRegionWidth() - 100.0f;
Vector<HComponent> bodies = gEditor().GetSceneRoot()->GetComponents((UINT32)TID_CRigidBody, true);
ImGuiExt::ComboOptions<UUID> bodiesOptions;
UUID emptyBody = UUID(50, 0, 0, 0);
for (auto& body : bodies)
{
bodiesOptions.AddOption(body->GetUUID(), body->GetName());
}
bodiesOptions.AddOption(emptyBody, "No Body");
// Body Target
{
HRigidBody body = joint->GetBody(JointBody::Target);
UUID bodyUUID = (body) ? body->GetUUID() : emptyBody;
if (ImGuiExt::RenderOptionCombo<UUID>(&bodyUUID,
"##joint_option_target_body", "Target Body", bodiesOptions, width))
{
if (bodyUUID == emptyBody)
{
joint->SetBody(JointBody::Target, HRigidBody());
}
else
{
HComponent component = gEditor().GetSceneRoot()->GetComponent(bodyUUID, true);
joint->SetBody(JointBody::Target, static_object_cast<CRigidBody>(component));
}
hasChanged = true;
}
}
// Body Anchor
{
HRigidBody body = joint->GetBody(JointBody::Anchor);
UUID bodyUUID = (body) ? body->GetUUID() : emptyBody;
if (ImGuiExt::RenderOptionCombo<UUID>(&bodyUUID,
"##joint_option_anchor_body", "Anchor Body", bodiesOptions, width))
{
if (bodyUUID == emptyBody)
{
joint->SetBody(JointBody::Anchor, HRigidBody());
}
else
{
HComponent component = gEditor().GetSceneRoot()->GetComponent(bodyUUID, true);
joint->SetBody(JointBody::Anchor, static_object_cast<CRigidBody>(component));
}
hasChanged = true;
}
}
ImGui::Separator();
// Break Force
{
float breakForce = joint->GetBreakForce();
if (ImGuiExt::RenderOptionFloat(breakForce, "##joint_option_break_force", "Break Force", 0.0f, 65536.0f, width))
{
joint->SetBreakForce(breakForce);
hasChanged = true;
}
}
// Break Torque
{
float breakTorque = joint->GetBreakTorque();
if (ImGuiExt::RenderOptionFloat(breakTorque, "##joint_option_break_torque", "Break Torque", 0.0f, 65536.0f, width))
{
joint->SetBreakTorque(breakTorque);
hasChanged = true;
}
}
ImGui::Separator();
// Enable Collision
{
bool enableCollision = joint->GetEnableCollision();
if (ImGuiExt::RenderOptionBool(enableCollision, "##joint_option_enable_collision", "Enable Collision"))
{
joint->SetEnableCollision(enableCollision);
hasChanged = true;
}
}
ImGui::Separator();
// Is Broken
{
bool isBroken = joint->GetIsBroken();
if (ImGuiExt::RenderOptionBool(isBroken, "##joint_option_is_broken", "Is Broken"))
{
joint->SetIsBroken(isBroken);
hasChanged = true;
}
}
return hasChanged;
}
bool WidgetProperties::ShowLoadMesh()
{
bool meshLoaded = false;
if (_loadMesh || _loadPhysicsMesh)
ImGui::OpenPopup("Load Mesh");
if (_fileBrowser.ShowFileDialog("Load Mesh", ImGuiFileBrowser::DialogMode::OPEN, ImVec2(900, 450), true, ".obj,.dae,.fbx,.stl,.gltf"))
{
auto meshImportOptions = MeshImportOptions::Create();
meshImportOptions->ImportNormals = _fileBrowser.Data.MeshParam.ImportNormals;
meshImportOptions->ImportTangents = _fileBrowser.Data.MeshParam.ImportTangents;
meshImportOptions->ImportUVCoords = _fileBrowser.Data.MeshParam.ImportUVCoords;
meshImportOptions->ImportSkin = _fileBrowser.Data.MeshParam.ImportSkin;
meshImportOptions->ImportBlendShapes = _fileBrowser.Data.MeshParam.ImportBlendShapes;
meshImportOptions->ImportAnimations = _fileBrowser.Data.MeshParam.ImportAnimations;
meshImportOptions->ReduceKeyFrames = _fileBrowser.Data.MeshParam.ReduceKeyFrames;
meshImportOptions->ImportMaterials = _fileBrowser.Data.MeshParam.ImportMaterials;
meshImportOptions->ImportVertexColors = _fileBrowser.Data.MeshParam.ImportVertexColors;
meshImportOptions->ForceGenNormals = _fileBrowser.Data.MeshParam.ForceGenNormals;
meshImportOptions->GenSmoothNormals = _fileBrowser.Data.MeshParam.GenSmoothNormals;
meshImportOptions->ScaleSystemUnit = _fileBrowser.Data.MeshParam.ScaleSystemUnit;
meshImportOptions->ScaleFactor = _fileBrowser.Data.MeshParam.ScaleFactor;
meshImportOptions->ImportCollisionShape = _fileBrowser.Data.MeshParam.ImportCollisionShape;
meshImportOptions->CpuCached = false;
SPtr<MultiResource> resources = EditorResManager::Instance().LoadAll(_fileBrowser.Data.SelectedPath, meshImportOptions);
if (!resources->Empty())
{
for (auto& subRes : resources->Entries)
{
if (subRes.Name == "primary")
{
HMesh mesh = static_resource_cast<Mesh>(subRes.Res);
if (mesh.IsLoaded())
{
mesh->SetName(UTF8::FromANSI(_fileBrowser.Data.SelectedFileName));
EditorResManager::Instance().Add<Mesh>(mesh);
if (_selections.ClickedComponent->GetCoreType() == TID_CRenderable)
{
SPtr<CRenderable> renderable = std::static_pointer_cast<CRenderable>(_selections.ClickedComponent);
// We will try to set the material attach to this mesh (in fact one material per submesh), and create it before if not exist
renderable->SetMesh(mesh.GetInternalPtr());
meshLoaded = true;
if (meshImportOptions->ImportMaterials)
{
EditorUtils::ImportMeshMaterials(mesh);
for (UINT32 i = 0; i < mesh->GetProperties().GetNumSubMeshes(); i++)
{
SubMesh& subMesh = mesh->GetProperties().GetSubMesh(i);
if (subMesh.Mat.IsLoaded())
renderable->SetMaterial(i, subMesh.Mat.GetInternalPtr());
}
}
}
}
_loadMesh = false;
_loadPhysicsMesh = false;
}
else if (subRes.Name == "collision")
{
HPhysicsMesh physicsMesh = static_resource_cast<PhysicsMesh>(subRes.Res);
if (physicsMesh.IsLoaded())
{
EditorResManager::Instance().Add<PhysicsMesh>(physicsMesh);
if (_selections.ClickedComponent->GetCoreType() == TID_CMeshCollider)
{
SPtr<CMeshCollider> meshCollider = std::static_pointer_cast<CMeshCollider>(_selections.ClickedComponent);
meshCollider->SetMesh(physicsMesh);
meshLoaded = true;
}
else if (_selections.ClickedComponent->GetCoreType() == TID_CMeshSoftBody)
{
SPtr<CMeshSoftBody> softBody = std::static_pointer_cast<CMeshSoftBody>(_selections.ClickedComponent);
softBody->SetMesh(physicsMesh);
meshLoaded = true;
}
}
}
else
{
subRes.Res->SetPath(UTF8::FromANSI(_fileBrowser.Data.SelectedFileName));
}
}
}
}
else
{
if (_fileBrowser.Data.IsCancelled)
{
_loadMesh = false;
_loadPhysicsMesh = false;
}
}
return meshLoaded;
}
bool WidgetProperties::ShowLoadSkybox()
{
bool skyboxLoaded = false;
if (_loadSkybox || _loadSkyboxIrradiance)
ImGui::OpenPopup("Load Skybox Texture");
if (_fileBrowser.ShowFileDialog("Load Skybox Texture", ImGuiFileBrowser::DialogMode::OPEN, ImVec2(900, 450), false, ".png,.jpeg,.jpg.dds"))
{
auto textureSkyboxImportOptions = TextureImportOptions::Create();
textureSkyboxImportOptions->CubemapType = CubemapSourceType::Faces;
textureSkyboxImportOptions->IsCubemap = true;
textureSkyboxImportOptions->Format = Util::IsBigEndian() ? PF_RGBA8 : PF_BGRA8;
textureSkyboxImportOptions->CpuCached = _fileBrowser.Data.TexParam.CpuCached;
HTexture texture = EditorResManager::Instance().Load<Texture>(_fileBrowser.Data.SelectedPath, textureSkyboxImportOptions);
if (texture.IsLoaded())
{
texture->SetName(UTF8::FromANSI(_fileBrowser.Data.SelectedFileName));
EditorResManager::Instance().Add<Texture>(texture);
SPtr<CSkybox> skybox = std::static_pointer_cast<CSkybox>(_selections.ClickedComponent);
if(_loadSkybox)
skybox->SetTexture(texture.GetInternalPtr());
else
skybox->SetIrradiance(texture.GetInternalPtr());
skyboxLoaded = true;
}
_loadSkybox = false;
_loadSkyboxIrradiance = false;
}
else
{
if (_fileBrowser.Data.IsCancelled)
_loadSkybox = false;
}
return skyboxLoaded;
}
bool WidgetProperties::ShowLoadScript()
{
bool scriptLoaded = false;
if (_loadScript)
ImGui::OpenPopup("Load Script");
if (_fileBrowser.ShowFileDialog("Load Script", ImGuiFileBrowser::DialogMode::OPEN, ImVec2(900, 450), false, ".cpp"))
{
if (_selections.ClickedComponent && _selections.ClickedComponent->GetCoreType() == TID_CScript)
{
String fileName = _fileBrowser.Data.SelectedFileName;
fileName = fileName.substr(0, fileName.length() - 4);
SPtr<CScript> script = std::static_pointer_cast<CScript>(_selections.ClickedComponent);
script->SetNativeScript(fileName, _fileBrowser.Data.SelectedPath);
}
_loadScript = false;
}
else
{
if (_fileBrowser.Data.IsCancelled)
_loadScript = false;
}
return scriptLoaded;
}
bool WidgetProperties::ShowLoadAudioClip()
{
bool audioScriptLoaded = false;
if (_loadAudioClip)
ImGui::OpenPopup("Load Audio Clip");
if (_fileBrowser.ShowFileDialog("Load Audio Clip", ImGuiFileBrowser::DialogMode::OPEN, ImVec2(900, 450), true, ".ogg,.flac,.wav"))
{
auto audioClipImportOptions = AudioClipImportOptions::Create();
audioClipImportOptions->Is3D = _fileBrowser.Data.AudioParam.Is3D;
HAudioClip audioClip = EditorResManager::Instance().Load<AudioClip>(_fileBrowser.Data.SelectedPath, audioClipImportOptions);
if (audioClip.IsLoaded())
{
audioClip->SetName(UTF8::FromANSI(_fileBrowser.Data.SelectedFileName));
EditorResManager::Instance().Add<AudioClip>(audioClip);
SPtr<CAudioSource> audioSource = std::static_pointer_cast<CAudioSource>(_selections.ClickedComponent);
audioSource->SetClip(audioClip);
audioScriptLoaded = true;
}
_loadAudioClip = false;
}
else
{
if (_fileBrowser.Data.IsCancelled)
_loadAudioClip = false;
}
return audioScriptLoaded;
}
bool WidgetProperties::ShowLoadHeightFieldTexture()
{
bool heightFieldTextureLoaded = false;
if (_loadHeightFieldTexture)
ImGui::OpenPopup("Load Height Field Texture");
if (_fileBrowser.ShowFileDialog("Load Height Field Texture", ImGuiFileBrowser::DialogMode::OPEN, ImVec2(900, 450), true, ".png,.jpeg,.jpg.dds"))
{
auto textureImportOptions = TextureImportOptions::Create();
if (_fileBrowser.Data.TexParam.TexType != TextureType::TEX_TYPE_CUBE_MAP)
{
textureImportOptions->CpuCached = _fileBrowser.Data.TexParam.CpuCached;
textureImportOptions->GenerateMips = _fileBrowser.Data.TexParam.GenerateMips;
textureImportOptions->MaxMip = _fileBrowser.Data.TexParam.MaxMips;
textureImportOptions->Format = Util::IsBigEndian() ? PF_RGBA8 : PF_BGRA8;
HTexture texture = EditorResManager::Instance().Load<Texture>(_fileBrowser.Data.SelectedPath, textureImportOptions, true);
if (texture.IsLoaded())
{
texture->SetName(UTF8::FromANSI(_fileBrowser.Data.SelectedFileName));
EditorResManager::Instance().Add<Texture>(texture);
if (texture->GetProperties().GetTextureType() != TextureType::TEX_TYPE_CUBE_MAP)
{
SPtr<CHeightFieldCollider> heightFieldCollider = std::static_pointer_cast<CHeightFieldCollider>(_selections.ClickedComponent);
heightFieldCollider->SetHeightField(GetOrCreatePhysicsHightFieldFromTex(texture.GetInternalPtr()));
}
}
}
_loadHeightFieldTexture = false;
}
else
{
if (_fileBrowser.Data.IsCancelled)
_loadHeightFieldTexture = false;
}
return heightFieldTextureLoaded;
}
HPhysicsHeightField WidgetProperties::GetOrCreatePhysicsHightFieldFromTex(SPtr<Texture> texture)
{
if (!texture)
return HPhysicsHeightField();
EditorResManager::ResourcesContainer& HeightFieldContainer = EditorResManager::Instance().Get<PhysicsHeightField>();
for (auto& resource : HeightFieldContainer.Res)
{
HPhysicsHeightField heightField = static_resource_cast<PhysicsHeightField>(resource.second);
if (heightField->GetTexture() == texture)
return heightField;
}
HPhysicsHeightField physicsHeightField = PhysicsHeightField::Create(texture);
if (physicsHeightField.IsLoaded())
EditorResManager::Instance().Add<PhysicsHeightField>(physicsHeightField);
return physicsHeightField;
}
}
|
/*
*
* Copyright (C) 2000-2021, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: ofstd
*
* Author: Marco Eichelberg
*
* Purpose: Define classes for Semaphore, Mutex and Read/Write Lock
* as used by most multithread implementations
*
*
*/
#include "dcmtk/config/osconfig.h"
#define OFTEST_OFSTD_ONLY
#include "dcmtk/ofstd/oftest.h"
#include "dcmtk/ofstd/ofthread.h"
#include "dcmtk/ofstd/ofstring.h"
#include "dcmtk/ofstd/ofstd.h"
#include "dcmtk/ofstd/ofdiag.h"
#define BAILOUT(msg) do { \
OFCHECK_FAIL(msg); \
return; \
} while (0)
static OFMutex *mutex=NULL;
static volatile int mtx_var=0;
static volatile int mtx_cond1=0;
static volatile int mtx_cond2=0;
static volatile int mtx_cond3=0;
static const int wait_timeout = 100;
class MutexT1: public OFThread
{
public:
MutexT1(): OFThread() {}
~MutexT1() {}
virtual void run()
{
if (OFMutex::busy == mutex->trylock()) mtx_cond1=1; // trylock works
if (0 == mutex->lock())
{
mtx_var = 1;
OFStandard::milliSleep(wait_timeout); // since I've got the mutex, nobody should write to mtx_var
if ((mtx_var == 1)&&(0 == mutex->unlock())) mtx_cond2 = 1;
}
}
};
class MutexT2: public OFThread
{
public:
MutexT2(): OFThread() {}
~MutexT2() {}
virtual void run()
{
if (0 == mutex->lock())
{
mtx_var = 2;
OFStandard::milliSleep(wait_timeout); // since I've got the mutex, nobody should write to mtx_var
if ((mtx_var == 2)&&(0 == mutex->unlock())) mtx_cond3 = 1;
}
}
};
static void mutex_test()
{
OFString errmsg;
mutex = new OFMutex();
if ((!mutex)||(! mutex->initialized())) BAILOUT("creation of mutex failed");
OFMutex memory_barrier;
if (! memory_barrier.initialized()) BAILOUT("creation of mutex failed");
int condition = mutex->trylock();
if (condition)
{
mutex->errorstr(errmsg, condition);
errmsg = "mutex lock failed: " + errmsg;
BAILOUT(errmsg);
}
mtx_var = -1;
MutexT1 t1;
if (0 != t1.start()) BAILOUT("unable to create thread, mutex test failed");
MutexT2 t2;
if (0 != t2.start()) BAILOUT("unable to create thread, mutex test failed");
OFStandard::milliSleep(wait_timeout); // since I've got the mutex, nobody should write to mtx_var
memory_barrier.lock(); // locking the mutex acts as a (inefficient, but portable) memory barrier
memory_barrier.unlock();
if (mtx_var != -1) BAILOUT("mutex test failed");
int i=0;
while ((i++<10) && (!mtx_cond1))
{
memory_barrier.lock(); // locking the mutex acts as a (inefficient, but portable) memory barrier
memory_barrier.unlock();
OFStandard::milliSleep(wait_timeout);
}
if (!mtx_cond1) BAILOUT("mutex trylock test failed");
if (0 != (condition = mutex->unlock()))
{
mutex->errorstr(errmsg, condition);
errmsg = "mutex unlock failed: " + errmsg;
BAILOUT(errmsg);
}
while ((i++<10) && ((!mtx_cond2)||(!mtx_cond3)))
{
memory_barrier.lock(); // locking the mutex acts as a (inefficient, but portable) memory barrier
memory_barrier.unlock();
OFStandard::milliSleep(wait_timeout);
}
if ((!mtx_cond2) || (!mtx_cond3)) BAILOUT("mutex lock/unlock test failed");
if (0 != t1.join()) BAILOUT("unable to join thread, mutex test failed");
if (0 != t2.join()) BAILOUT("unable to join thread, mutex test failed");
delete mutex;
}
static OFSemaphore *semaphore=NULL;
static volatile int sem_cond1=0;
static volatile int sem_cond2=0;
static volatile int sem_cond3=0;
static volatile int sem_cond4=0;
class SemaT1: public OFThread
{
public:
SemaT1(): OFThread() {}
~SemaT1() {}
virtual void run()
{
if (0 == semaphore->wait())
{
sem_cond1 = 1; // acquired semaphore
mutex->lock();
mutex->unlock();
if (0== semaphore->post()) sem_cond2=1;
}
}
};
class SemaT2: public OFThread
{
public:
SemaT2(): OFThread() {}
~SemaT2() {}
virtual void run()
{
if (OFSemaphore::busy == semaphore->trywait())
{
if (0 == semaphore->wait()) // block on semaphore
{
sem_cond3 = 1; // acquired semaphore
if (0== semaphore->post()) sem_cond4=1;
}
}
else
{
sem_cond3 = 1; // acquired semaphore
if (0== semaphore->post()) sem_cond4=1;
}
}
};
static void semaphore_test()
{
OFString errmsg;
mutex = new OFMutex();
if ((!mutex)||(! mutex->initialized())) BAILOUT("creation of mutex failed");
semaphore = new OFSemaphore(2);
if ((!semaphore)||(! semaphore->initialized())) BAILOUT("creation of semaphore failed");
int condition = mutex->trylock();
if (condition)
{
mutex->errorstr(errmsg, condition);
errmsg = "mutex lock failed: " + errmsg;
BAILOUT(errmsg);
}
condition = semaphore->trywait();
if (condition)
{
semaphore->errorstr(errmsg, condition);
errmsg = "semaphore acquisition failed: " + errmsg;
BAILOUT(errmsg);
}
OFMutex memory_barrier;
if (! memory_barrier.initialized()) BAILOUT("creation of mutex failed");
SemaT1 t1;
if (0 != t1.start()) BAILOUT("unable to create thread, semaphore test failed");
int i=0;
while ((i++<10) && (!sem_cond1))
{
memory_barrier.lock(); // locking the mutex acts as a (inefficient, but portable) memory barrier
memory_barrier.unlock();
OFStandard::milliSleep(wait_timeout);
}
if (!sem_cond1) BAILOUT("semaphore lock/unlock test failed");
SemaT2 t2;
if (0 != t2.start()) BAILOUT("unable to create thread, semaphore test failed");
OFStandard::milliSleep(wait_timeout);
if (sem_cond3) BAILOUT("semaphore lock/unlock test failed"); // make sure T2 is really blocked
mutex->unlock();
i=0;
while ((i++<10) && ((!sem_cond2)||(!sem_cond3)||(!sem_cond4)))
{
memory_barrier.lock(); // locking the mutex acts as a (inefficient, but portable) memory barrier
memory_barrier.unlock();
OFStandard::milliSleep(wait_timeout);
}
if ((!sem_cond2)||(!sem_cond3)||(!sem_cond4)) BAILOUT("semaphore lock/unlock test failed: sem_cond2=" << sem_cond2 << ", sem_cond3=" << sem_cond3 << ", sem_cond4=" << sem_cond4);
if (0 != t1.join()) BAILOUT("unable to join thread, semaphore test failed");
if (0 != t2.join()) BAILOUT("unable to join thread, semaphore test failed");
delete mutex;
delete semaphore;
}
static OFReadWriteLock *rwlock=NULL;
static OFMutex *mutex2=NULL;
static volatile int rw_cond1=0;
static volatile int rw_cond2=0;
static volatile int rw_cond3=0;
static volatile int rw_cond4=0;
static volatile int rw_cond5=0;
static volatile int rw_cond6=0;
static volatile int rw_cond7=0;
class RWLockT2: public OFThread
{
public:
RWLockT2(): OFThread() {}
~RWLockT2() {}
virtual void run()
{
if ((0==mutex2->trylock())&&(OFReadWriteLock::busy == rwlock->trywrlock())) rw_cond5=1;
if (0 == rwlock->wrlock())
{
rw_cond6=1;
mutex2->unlock();
OFStandard::milliSleep(wait_timeout);
if (0==rwlock->wrunlock()) rw_cond7=1;
}
return;
}
};
class RWLockT1: public OFThread
{
private:
RWLockT2 &t2;
public:
#include DCMTK_DIAGNOSTIC_PUSH
#include DCMTK_DIAGNOSTIC_IGNORE_SHADOW
RWLockT1(RWLockT2 &t2) : OFThread(), t2(t2) {}
#include DCMTK_DIAGNOSTIC_POP
~RWLockT1() {}
virtual void run()
{
if (0 == rwlock->rdlock())
{
t2.start();
rw_cond1 = 1; // acquired read lock
mutex->lock();
mutex->unlock();
if (0== rwlock->rdunlock()) rw_cond2=1;
mutex2->lock();
mutex2->unlock();
if (OFReadWriteLock::busy == rwlock->tryrdlock()) rw_cond3=1;
if ((0 == rwlock->rdlock())&&(0==rwlock->rdunlock())) rw_cond4=1;
}
return;
}
};
static void rwlock_test()
{
OFString errmsg;
mutex = new OFMutex();
if ((!mutex)||(! mutex->initialized())) BAILOUT("creation of mutex failed");
mutex2 = new OFMutex();
if ((!mutex2)||(! mutex2->initialized())) BAILOUT("creation of mutex failed");
rwlock = new OFReadWriteLock();
if ((!rwlock)||(! rwlock->initialized())) BAILOUT("creation of read/write lock failed");
int condition = mutex->trylock();
if (condition)
{
mutex->errorstr(errmsg, condition);
errmsg = "mutex lock failed: " + errmsg;
BAILOUT(errmsg);
}
condition = rwlock->tryrdlock();
if (condition)
{
rwlock->errorstr(errmsg, condition);
errmsg = "read lock failed: " + errmsg;
BAILOUT(errmsg);
}
OFMutex memory_barrier;
if (! memory_barrier.initialized()) BAILOUT("creation of mutex failed");
RWLockT2 t2;
RWLockT1 t1(t2);
if (0 != t1.start()) BAILOUT("unable to create thread, read/write lock/unlock test failed");
int i=0;
while ((i++<10) && ((!rw_cond1)||(!rw_cond5)))
{
memory_barrier.lock(); // locking the mutex acts as a (inefficient, but portable) memory barrier
memory_barrier.unlock();
OFStandard::milliSleep(wait_timeout);
}
if ((!rw_cond1)||(!rw_cond5)) BAILOUT("read/write lock/unlock test failed");
condition = rwlock->rdunlock();
if (condition)
{
rwlock->errorstr(errmsg, condition);
errmsg = "read lock failed: " + errmsg;
BAILOUT(errmsg);
}
OFStandard::milliSleep(wait_timeout);
memory_barrier.lock(); // locking the mutex acts as a (inefficient, but portable) memory barrier
memory_barrier.unlock();
if (rw_cond6) BAILOUT("read/write lock/unlock test failed");
mutex->unlock();
i=0;
while ((i++<10) && ((!rw_cond2)||(!rw_cond3)||(!rw_cond4)||(!rw_cond5)||(!rw_cond6)||(!rw_cond7)))
{
memory_barrier.lock(); // locking the mutex acts as a (inefficient, but portable) memory barrier
memory_barrier.unlock();
OFStandard::milliSleep(wait_timeout);
}
if ((!rw_cond2)||(!rw_cond3)||(!rw_cond4)||(!rw_cond5)||(!rw_cond6)||(!rw_cond7)) BAILOUT("read/write lock/unlock test failed");
if (0 != t1.join()) BAILOUT("unable to join thread, read/write lock/unlock test failed");
if (0 != t2.join()) BAILOUT("unable to join thread, read/write lock/unlock test failed");
delete mutex;
delete mutex2;
delete rwlock;
}
class RWLockerT2: public OFThread
{
public:
RWLockerT2(): OFThread() {}
~RWLockerT2() {}
virtual void run()
{
OFReadWriteLocker locker(*rwlock);
if ((0==mutex2->trylock())&&(OFReadWriteLock::busy == locker.trywrlock())) rw_cond5=1;
if (0 == locker.wrlock())
{
rw_cond6=1;
mutex2->unlock();
OFStandard::milliSleep(wait_timeout);
// Explicite unlock(), check if this causes one unlock() too much
if (0==locker.unlock()) rw_cond7=1;
}
return;
}
};
class RWLockerT1: public OFThread
{
private:
RWLockerT2 &t2;
public:
#include DCMTK_DIAGNOSTIC_PUSH
#include DCMTK_DIAGNOSTIC_IGNORE_SHADOW
RWLockerT1(RWLockerT2 &t2): OFThread(), t2(t2) {}
#include DCMTK_DIAGNOSTIC_POP
~RWLockerT1() {}
virtual void run()
{
OFReadWriteLocker locker(*rwlock);
if (0 == locker.rdlock())
{
t2.start();
rw_cond1 = 1; // acquired read lock
mutex->lock();
mutex->unlock();
if (0== locker.unlock()) rw_cond2=1;
mutex2->lock();
mutex2->unlock();
if (OFReadWriteLock::busy == locker.tryrdlock()) rw_cond3=1;
if (0 == locker.rdlock()) rw_cond4=1;
// Implicit unlock() at the end
}
return;
}
};
static void rwlocker_test()
{
OFString errmsg;
// Reset global state
rwlock=NULL;
mutex2=NULL;
rw_cond1=0;
rw_cond2=0;
rw_cond3=0;
rw_cond4=0;
rw_cond5=0;
rw_cond6=0;
rw_cond7=0;
mutex = new OFMutex();
if ((!mutex)||(! mutex->initialized())) BAILOUT("creation of mutex failed");
mutex2 = new OFMutex();
if ((!mutex2)||(! mutex2->initialized())) BAILOUT("creation of mutex failed");
rwlock = new OFReadWriteLock();
if ((!rwlock)||(! rwlock->initialized())) BAILOUT("creation of read/write lock failed");
int condition = mutex->trylock();
if (condition)
{
mutex->errorstr(errmsg, condition);
errmsg = "mutex lock failed: " + errmsg;
BAILOUT(errmsg);
}
OFReadWriteLocker rwlockLocker(*rwlock);
condition = rwlockLocker.tryrdlock();
if (condition)
{
rwlock->errorstr(errmsg, condition);
errmsg = "read lock failed: " + errmsg;
BAILOUT(errmsg);
}
OFMutex memory_barrier;
if (! memory_barrier.initialized()) BAILOUT("creation of mutex failed");
RWLockerT2 t2;
RWLockerT1 t1(t2);
if (0 != t1.start()) BAILOUT("unable to create thread, read/write lock test failed");
int i=0;
while ((i++<10) && ((!rw_cond1)||(!rw_cond5)))
{
memory_barrier.lock(); // locking the mutex acts as a (inefficient, but portable) memory barrier
memory_barrier.unlock();
OFStandard::milliSleep(wait_timeout);
}
if ((!rw_cond1)||(!rw_cond5)) BAILOUT("read/write lock test failed");
condition = rwlockLocker.unlock();
if (condition)
{
rwlock->errorstr(errmsg, condition);
errmsg = "read lock failed: " + errmsg;
BAILOUT(errmsg);
}
OFStandard::milliSleep(wait_timeout);
memory_barrier.lock(); // locking the mutex acts as a (inefficient, but portable) memory barrier
memory_barrier.unlock();
if (rw_cond6) BAILOUT("read/write lock test failed");
mutex->unlock();
i=0;
while ((i++<10) && ((!rw_cond2)||(!rw_cond3)||(!rw_cond4)||(!rw_cond5)||(!rw_cond6)||(!rw_cond7)))
{
memory_barrier.lock(); // locking the mutex acts as a (inefficient, but portable) memory barrier
memory_barrier.unlock();
OFStandard::milliSleep(wait_timeout);
}
if ((!rw_cond2)||(!rw_cond3)||(!rw_cond4)||(!rw_cond5)||(!rw_cond6)||(!rw_cond7)) BAILOUT("read/write lock test failed");
if (0 != t1.join()) BAILOUT("unable to join thread, read/write lock test failed");
if (0 != t2.join()) BAILOUT("unable to join thread, read/write lock test failed");
delete mutex;
delete mutex2;
delete rwlock;
}
static OFThreadSpecificData *tsdata=NULL;
static volatile int tsd_cond1=0;
static volatile int tsd_cond2=0;
static volatile int tsd_cond3=0;
static volatile int tsd_cond4=0;
class TSDataT1: public OFThread
{
public:
TSDataT1(): OFThread() {}
~TSDataT1() {}
virtual void run()
{
if (0 == tsdata->set(this))
{
tsd_cond1 = 1; // acquired read lock
mutex->lock();
mutex->unlock();
void *result = NULL;
if (0== tsdata->get(result))
{
if (result == OFstatic_cast(void *, this)) tsd_cond3 = 1;
}
}
}
};
class TSDataT2: public OFThread
{
public:
TSDataT2(): OFThread() {}
~TSDataT2() {}
virtual void run()
{
if (0 == tsdata->set(this))
{
tsd_cond2 = 1; // acquired read lock
mutex2->lock();
mutex2->unlock();
void *result = NULL;
if (0== tsdata->get(result))
{
if (result == OFstatic_cast(void *, this)) tsd_cond4 = 1;
}
}
}
};
static void tsdata_test()
{
OFString errmsg;
mutex = new OFMutex();
if ((!mutex)||(! mutex->initialized())) BAILOUT("creation of mutex failed");
mutex2 = new OFMutex();
if ((!mutex2)||(! mutex2->initialized())) BAILOUT("creation of mutex failed");
tsdata = new OFThreadSpecificData();
if ((!tsdata)||(! tsdata->initialized())) BAILOUT("creation of thread specific data failed");
int condition = mutex->trylock();
if (condition)
{
mutex->errorstr(errmsg, condition);
errmsg = "mutex lock failed: " + errmsg;
BAILOUT(errmsg);
}
condition = mutex2->trylock();
if (condition)
{
mutex2->errorstr(errmsg, condition);
errmsg = "mutex lock failed: " + errmsg;
BAILOUT(errmsg);
}
OFMutex memory_barrier;
if (! memory_barrier.initialized()) BAILOUT("creation of mutex failed");
TSDataT1 t1;
if (0 != t1.start()) BAILOUT("unable to create thread, thread specific data test failed");
TSDataT2 t2;
if (0 != t2.start()) BAILOUT("unable to create thread, thread specific data test failed");
int i=0;
while ((i++<10) && ((!tsd_cond1)||(!tsd_cond2)))
{
memory_barrier.lock(); // locking the mutex acts as a (inefficient, but portable) memory barrier
memory_barrier.unlock();
OFStandard::milliSleep(wait_timeout);
}
if ((!tsd_cond1)||(!tsd_cond2)) BAILOUT("thread specific data write test failed");
condition = mutex->unlock();
if (condition)
{
mutex->errorstr(errmsg, condition);
errmsg = "mutex unlock failed: " + errmsg;
BAILOUT(errmsg);
}
condition = mutex2->unlock();
if (condition)
{
mutex2->errorstr(errmsg, condition);
errmsg = "mutex unlock failed: " + errmsg;
BAILOUT(errmsg);
}
i=0;
while ((i++<10) && ((!tsd_cond3)||(!tsd_cond4)))
{
memory_barrier.lock(); // locking the mutex acts as a (inefficient, but portable) memory barrier
memory_barrier.unlock();
OFStandard::milliSleep(wait_timeout);
}
if ((!tsd_cond3)||(!tsd_cond4)) BAILOUT("thread specific data read test failed");
if (0 != t1.join()) BAILOUT("unable to create thread, thread specific data test failed");
if (0 != t2.join()) BAILOUT("unable to create thread, thread specific data test failed");
delete mutex;
delete mutex2;
delete tsdata;
}
OFTEST(ofstd_thread)
{
// This makes sure tests are executed in the expected order
mutex_test();
semaphore_test(); // may assume that mutexes work correctly
rwlock_test(); // may assume that mutexes and semaphores work correctly
rwlocker_test(); // may assume that mutexes, semaphores and read/write locks work correctly
tsdata_test();
}
|
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "ptlightingengine.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/global/globaltypes.h"
#include "renderer/kernel/aov/aovcomponents.h"
#include "renderer/kernel/lighting/directlightingintegrator.h"
#include "renderer/kernel/lighting/imagebasedlighting.h"
#include "renderer/kernel/lighting/lightpathrecorder.h"
#include "renderer/kernel/lighting/lightpathstream.h"
#include "renderer/kernel/lighting/pathtracer.h"
#include "renderer/kernel/lighting/pathvertex.h"
#include "renderer/kernel/lighting/scatteringmode.h"
#include "renderer/kernel/lighting/volumelightingintegrator.h"
#include "renderer/kernel/shading/shadingcomponents.h"
#include "renderer/kernel/shading/shadingcontext.h"
#include "renderer/kernel/shading/shadingpoint.h"
#include "renderer/modeling/bsdf/bsdf.h"
#include "renderer/modeling/edf/edf.h"
#include "renderer/modeling/environment/environment.h"
#include "renderer/modeling/environmentedf/environmentedf.h"
#include "renderer/modeling/scene/scene.h"
#include "renderer/utility/spectrumclamp.h"
#include "renderer/utility/stochasticcast.h"
// appleseed.foundation headers.
#include "foundation/math/mis.h"
#include "foundation/math/population.h"
#include "foundation/math/vector.h"
#include "foundation/platform/types.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/statistics.h"
#include "foundation/utility/string.h"
// Standard headers.
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <limits>
#include <string>
// Forward declarations.
namespace renderer { class BackwardLightSampler; }
namespace renderer { class PixelContext; }
namespace renderer { class TextureCache; }
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// Path Tracing lighting engine.
//
// Implementation of Monte Carlo backward path tracing with and without next event estimation.
//
// Reference:
//
// http://citeseer.ist.psu.edu/344088.html
//
class PTLightingEngine
: public ILightingEngine
{
public:
PTLightingEngine(
const BackwardLightSampler& light_sampler,
LightPathRecorder& light_path_recorder,
const ParamArray& params)
: m_params(params)
, m_light_sampler(light_sampler)
, m_light_path_stream(
m_params.m_record_light_paths
? light_path_recorder.create_stream()
: nullptr)
, m_path_count(0)
, m_inf_volume_ray_warnings(0)
{
}
void release() override
{
delete this;
}
void print_settings() const override
{
RENDERER_LOG_INFO(
"unidirectional path tracer settings:\n"
" direct lighting %s\n"
" ibl %s\n"
" caustics %s\n"
" max bounces %s\n"
" max diffuse bounces %s\n"
" max glossy bounces %s\n"
" max specular bounces %s\n"
" max volume bounces %s\n"
" russian roulette start bounce %s\n"
" next event estimation %s\n"
" dl light samples %s\n"
" dl light threshold %s\n"
" ibl env samples %s\n"
" max ray intensity %s\n"
" volume distance samples %s\n"
" equiangular sampling %s\n"
" clamp roughness %s",
m_params.m_enable_dl ? "on" : "off",
m_params.m_enable_ibl ? "on" : "off",
m_params.m_enable_caustics ? "on" : "off",
m_params.m_max_bounces == ~size_t(0) ? "unlimited" : pretty_uint(m_params.m_max_bounces).c_str(),
m_params.m_max_diffuse_bounces == ~size_t(0) ? "unlimited" : pretty_uint(m_params.m_max_diffuse_bounces).c_str(),
m_params.m_max_glossy_bounces == ~size_t(0) ? "unlimited" : pretty_uint(m_params.m_max_glossy_bounces).c_str(),
m_params.m_max_specular_bounces == ~size_t(0) ? "unlimited" : pretty_uint(m_params.m_max_specular_bounces).c_str(),
m_params.m_max_volume_bounces == ~size_t(0) ? "unlimited" : pretty_uint(m_params.m_max_volume_bounces).c_str(),
m_params.m_rr_min_path_length == ~size_t(0) ? "unlimited" : pretty_uint(m_params.m_rr_min_path_length).c_str(),
m_params.m_next_event_estimation ? "on" : "off",
pretty_scalar(m_params.m_dl_light_sample_count).c_str(),
pretty_scalar(m_params.m_dl_low_light_threshold, 3).c_str(),
pretty_scalar(m_params.m_ibl_env_sample_count).c_str(),
m_params.m_has_max_ray_intensity ? pretty_scalar(m_params.m_max_ray_intensity).c_str() : "unlimited",
pretty_int(m_params.m_distance_sample_count).c_str(),
m_params.m_enable_equiangular_sampling ? "on" : "off",
m_params.m_clamp_roughness ? "on" : "off");
}
void compute_lighting(
SamplingContext& sampling_context,
const PixelContext& pixel_context,
const ShadingContext& shading_context,
const ShadingPoint& shading_point,
ShadingComponents& radiance, // output radiance, in W.sr^-1.m^-2
AOVComponents& components) override
{
if (m_light_path_stream)
{
m_light_path_stream->begin_path(
pixel_context,
shading_point.get_scene().get_active_camera(),
shading_point.get_ray().m_org);
}
if (m_params.m_next_event_estimation)
{
do_compute_lighting<PathVisitorNextEventEstimation, VolumeVisitorDistanceSampling>(
sampling_context,
shading_context,
shading_point,
radiance,
components);
}
else
{
do_compute_lighting<PathVisitorSimple, VolumeVisitorSimple>(
sampling_context,
shading_context,
shading_point,
radiance,
components);
}
if (m_light_path_stream)
m_light_path_stream->end_path();
}
template <typename PathVisitor, typename VolumeVisitor>
void do_compute_lighting(
SamplingContext& sampling_context,
const ShadingContext& shading_context,
const ShadingPoint& shading_point,
ShadingComponents& radiance, // output radiance, in W.sr^-1.m^-2
AOVComponents& components)
{
PathVisitor path_visitor(
m_params,
m_light_sampler,
sampling_context,
shading_context,
shading_point.get_scene(),
radiance,
components,
m_light_path_stream);
VolumeVisitor volume_visitor(
m_params,
m_light_sampler,
sampling_context,
shading_context,
shading_point.get_scene(),
radiance,
m_inf_volume_ray_warnings);
PathTracer<PathVisitor, VolumeVisitor, false> path_tracer( // false = not adjoint
path_visitor,
volume_visitor,
m_params.m_rr_min_path_length,
m_params.m_max_bounces == ~size_t(0) ? ~size_t(0) : m_params.m_max_bounces + 1,
m_params.m_max_diffuse_bounces == ~size_t(0) ? ~size_t(0) : m_params.m_max_diffuse_bounces + 1,
m_params.m_max_glossy_bounces,
m_params.m_max_specular_bounces,
m_params.m_max_volume_bounces,
m_params.m_clamp_roughness,
shading_context.get_max_iterations());
const size_t path_length =
path_tracer.trace(
sampling_context,
shading_context,
shading_point);
// Update statistics.
++m_path_count;
m_path_length.insert(path_length);
}
StatisticsVector get_statistics() const override
{
Statistics stats;
stats.insert("path count", m_path_count);
stats.insert("path length", m_path_length);
return StatisticsVector::make("path tracing statistics", stats);
}
private:
struct Parameters
{
const bool m_enable_dl; // is direct lighting enabled?
const bool m_enable_ibl; // is image-based lighting enabled?
const bool m_enable_caustics; // are caustics enabled?
const size_t m_max_bounces; // maximum number of bounces, ~0 for unlimited
const size_t m_max_diffuse_bounces; // maximum number of diffuse bounces, ~0 for unlimited
const size_t m_max_glossy_bounces; // maximum number of glossy bounces, ~0 for unlimited
const size_t m_max_specular_bounces; // maximum number of specular bounces, ~0 for unlimited
const size_t m_max_volume_bounces; // maximum number of volume scattering events, ~0 for unlimited
const bool m_clamp_roughness;
const size_t m_rr_min_path_length; // minimum path length before Russian Roulette kicks in, ~0 for unlimited
const bool m_next_event_estimation; // use next event estimation?
const float m_dl_light_sample_count; // number of light samples used to estimate direct illumination
const float m_dl_low_light_threshold; // light contribution threshold to disable shadow rays
const float m_ibl_env_sample_count; // number of environment samples used to estimate IBL
float m_rcp_dl_light_sample_count;
float m_rcp_ibl_env_sample_count;
const bool m_has_max_ray_intensity;
const float m_max_ray_intensity;
const size_t m_distance_sample_count; // number of distance samples for volume rendering
const bool m_enable_equiangular_sampling; // optimize for lights that are located outside volumes
const bool m_record_light_paths;
explicit Parameters(const ParamArray& params)
: m_enable_dl(params.get_optional<bool>("enable_dl", true))
, m_enable_ibl(params.get_optional<bool>("enable_ibl", true))
, m_enable_caustics(params.get_optional<bool>("enable_caustics", false))
, m_max_bounces(fixup_bounces(params.get_optional<int>("max_bounces", 8)))
, m_max_diffuse_bounces(fixup_bounces(params.get_optional<int>("max_diffuse_bounces", 3)))
, m_max_glossy_bounces(fixup_bounces(params.get_optional<int>("max_glossy_bounces", 8)))
, m_max_specular_bounces(fixup_bounces(params.get_optional<int>("max_specular_bounces", 8)))
, m_max_volume_bounces(fixup_bounces(params.get_optional<int>("max_volume_bounces", 8)))
, m_clamp_roughness(params.get_optional<bool>("clamp_roughness", false))
, m_rr_min_path_length(fixup_path_length(params.get_optional<size_t>("rr_min_path_length", 6)))
, m_next_event_estimation(params.get_optional<bool>("next_event_estimation", true))
, m_dl_light_sample_count(params.get_optional<float>("dl_light_samples", 1.0f))
, m_dl_low_light_threshold(params.get_optional<float>("dl_low_light_threshold", 0.0f))
, m_ibl_env_sample_count(params.get_optional<float>("ibl_env_samples", 1.0f))
, m_has_max_ray_intensity(params.strings().exist("max_ray_intensity"))
, m_max_ray_intensity(params.get_optional<float>("max_ray_intensity", 0.0f))
, m_distance_sample_count(params.get_optional<size_t>("volume_distance_samples", 2))
, m_enable_equiangular_sampling(!params.get_optional<bool>("optimize_for_lights_outside_volumes", false))
, m_record_light_paths(params.get_optional<bool>("record_light_paths", false))
{
// Precompute the reciprocal of the number of light samples.
m_rcp_dl_light_sample_count =
m_dl_light_sample_count > 0.0f && m_dl_light_sample_count < 1.0f
? 1.0f / m_dl_light_sample_count
: 0.0f;
// Precompute the reciprocal of the number of environment samples.
m_rcp_ibl_env_sample_count =
m_ibl_env_sample_count > 0.0f && m_ibl_env_sample_count < 1.0f
? 1.0f / m_ibl_env_sample_count
: 0.0f;
}
static size_t fixup_bounces(const int x)
{
return x == -1 ? ~size_t(0) : x;
}
static size_t fixup_path_length(const size_t x)
{
return x == 0 ? ~size_t(0) : x;
}
};
const Parameters m_params;
const BackwardLightSampler& m_light_sampler;
LightPathStream* m_light_path_stream;
uint64 m_path_count;
Population<uint64> m_path_length;
size_t m_inf_volume_ray_warnings;
static const size_t MaxInfVolumeRayWarnings = 5;
//
// Base path visitor.
//
class PathVisitorBase
{
public:
void on_first_diffuse_bounce(const PathVertex& vertex)
{
m_aov_components.m_albedo = vertex.m_albedo;
}
bool accept_scattering(
const ScatteringMode::Mode prev_mode,
const ScatteringMode::Mode next_mode)
{
assert(next_mode != ScatteringMode::None);
if (!m_params.m_enable_caustics)
{
// Don't follow paths leading to caustics.
if (ScatteringMode::has_diffuse_or_volume(prev_mode) &&
ScatteringMode::has_glossy_or_specular(next_mode))
return false;
// Ignore light emission after glossy-to-specular bounces to prevent another class of fireflies.
if (ScatteringMode::has_glossy(prev_mode) &&
ScatteringMode::has_specular(next_mode))
m_omit_emitted_light = true;
}
return true;
}
protected:
const Parameters& m_params;
const BackwardLightSampler& m_light_sampler;
SamplingContext& m_sampling_context;
const ShadingContext& m_shading_context;
const EnvironmentEDF* m_env_edf;
ShadingComponents& m_path_radiance;
AOVComponents& m_aov_components;
LightPathStream* m_light_path_stream;
bool m_omit_emitted_light;
PathVisitorBase(
const Parameters& params,
const BackwardLightSampler& light_sampler,
SamplingContext& sampling_context,
const ShadingContext& shading_context,
const Scene& scene,
ShadingComponents& path_radiance,
AOVComponents& components,
LightPathStream* light_path_stream)
: m_params(params)
, m_light_sampler(light_sampler)
, m_sampling_context(sampling_context)
, m_shading_context(shading_context)
, m_env_edf(scene.get_environment()->get_environment_edf())
, m_path_radiance(path_radiance)
, m_aov_components(components)
, m_light_path_stream(light_path_stream)
, m_omit_emitted_light(false)
{
}
};
//
// Path visitor without next event estimation.
//
class PathVisitorSimple
: public PathVisitorBase
{
public:
PathVisitorSimple(
const Parameters& params,
const BackwardLightSampler& light_sampler,
SamplingContext& sampling_context,
const ShadingContext& shading_context,
const Scene& scene,
ShadingComponents& path_radiance,
AOVComponents& components,
LightPathStream* light_path_stream)
: PathVisitorBase(
params,
light_sampler,
sampling_context,
shading_context,
scene,
path_radiance,
components,
light_path_stream)
{
}
void on_miss(const PathVertex& vertex)
{
assert(vertex.m_prev_mode != ScatteringMode::None);
// Can't look up the environment if there's no environment EDF.
if (m_env_edf == nullptr)
return;
// When IBL is disabled, the environment should still be reflected by glossy and specular surfaces.
if (!m_params.m_enable_ibl && vertex.m_prev_mode == ScatteringMode::Diffuse)
return;
// Evaluate the environment EDF.
Spectrum env_radiance(Spectrum::Illuminance);
float env_prob;
m_env_edf->evaluate(
m_shading_context,
-Vector3f(vertex.m_outgoing.get_value()),
env_radiance,
env_prob);
// Update path radiance.
env_radiance *= vertex.m_throughput;
m_path_radiance.add_emission(
vertex.m_path_length,
vertex.m_aov_mode,
env_radiance);
}
void on_hit(const PathVertex& vertex)
{
// Emitted light contribution.
if ((!m_omit_emitted_light || m_params.m_enable_caustics) &&
vertex.m_edf &&
vertex.m_cos_on > 0.0 &&
(vertex.m_path_length > 2 || m_params.m_enable_dl) &&
(vertex.m_path_length < 2 || (vertex.m_edf->get_flags() & EDF::CastIndirectLight)))
{
// Compute the emitted radiance.
Spectrum emitted_radiance(Spectrum::Illuminance);
vertex.compute_emitted_radiance(m_shading_context, emitted_radiance);
// Record light path event.
if (m_light_path_stream)
m_light_path_stream->hit_emitter(vertex, emitted_radiance);
// Apply path throughput.
emitted_radiance *= vertex.m_throughput;
// Update path radiance.
m_path_radiance.add_emission(
vertex.m_path_length,
vertex.m_aov_mode,
emitted_radiance);
}
else
{
// Record light path event.
if (m_light_path_stream)
m_light_path_stream->hit_reflector(vertex);
}
}
void on_scatter(PathVertex& vertex)
{
// When caustics are disabled, disable glossy and specular components after a diffuse or volume bounce.
// Note that accept_scattering() is later going to return false in this case.
const bool has_diffuse_or_volume_scattering =
vertex.m_prev_mode == ScatteringMode::Diffuse ||
vertex.m_prev_mode == ScatteringMode::Volume;
if (!m_params.m_enable_caustics && has_diffuse_or_volume_scattering)
vertex.m_scattering_modes &= ~(ScatteringMode::Glossy | ScatteringMode::Specular);
// Terminate the path if all scattering modes are disabled.
if (vertex.m_scattering_modes == ScatteringMode::None)
return;
}
};
//
// Path visitor with next event estimation.
//
class PathVisitorNextEventEstimation
: public PathVisitorBase
{
public:
PathVisitorNextEventEstimation(
const Parameters& params,
const BackwardLightSampler& light_sampler,
SamplingContext& sampling_context,
const ShadingContext& shading_context,
const Scene& scene,
ShadingComponents& path_radiance,
AOVComponents& components,
LightPathStream* light_path_stream)
: PathVisitorBase(
params,
light_sampler,
sampling_context,
shading_context,
scene,
path_radiance,
components,
light_path_stream)
, m_is_indirect_lighting(false)
{
}
void on_miss(const PathVertex& vertex)
{
assert(vertex.m_prev_mode != ScatteringMode::None);
// Can't look up the environment if there's no environment EDF.
if (m_env_edf == nullptr)
return;
// When IBL is disabled, the environment should still be reflected by glossy and specular surfaces.
if (!m_params.m_enable_ibl && vertex.m_prev_mode == ScatteringMode::Diffuse)
return;
// Evaluate the environment EDF.
Spectrum env_radiance(Spectrum::Illuminance);
float env_prob;
m_env_edf->evaluate(
m_shading_context,
-Vector3f(vertex.m_outgoing.get_value()),
env_radiance,
env_prob);
// This may happen for points of the environment map with infinite components,
// which are then excluded from importance sampling and thus have zero weight.
if (env_prob == 0.0)
return;
// Multiple importance sampling.
if (vertex.m_prev_mode != ScatteringMode::Specular)
{
assert(vertex.m_prev_prob > 0.0f);
const float env_sample_count = max(m_params.m_ibl_env_sample_count, 1.0f);
const float mis_weight =
mis_power2(
1.0f * vertex.m_prev_prob,
env_sample_count * env_prob);
env_radiance *= mis_weight;
}
// Apply path throughput.
env_radiance *= vertex.m_throughput;
// Optionally clamp secondary rays contribution.
if (m_params.m_has_max_ray_intensity && vertex.m_path_length > 1 && vertex.m_prev_mode != ScatteringMode::Specular)
clamp_contribution(env_radiance, m_params.m_max_ray_intensity);
// Update path radiance.
m_path_radiance.add_emission(
vertex.m_path_length,
vertex.m_aov_mode,
env_radiance);
}
void on_hit(const PathVertex& vertex)
{
// Emitted light contribution.
if ((!m_omit_emitted_light || m_params.m_enable_caustics) &&
vertex.m_edf &&
vertex.m_cos_on > 0.0 &&
(vertex.m_path_length > 2 || m_params.m_enable_dl) &&
(vertex.m_path_length < 2 || (vertex.m_edf->get_flags() & EDF::CastIndirectLight)))
{
// Compute the emitted radiance.
Spectrum emitted_radiance(0.0f);
add_emitted_light_contribution(vertex, emitted_radiance);
// Record light path event.
if (m_light_path_stream)
m_light_path_stream->hit_emitter(vertex, emitted_radiance);
// Apply path throughput.
emitted_radiance *= vertex.m_throughput;
// Optionally clamp secondary rays contribution.
if (m_params.m_has_max_ray_intensity && vertex.m_path_length > 1 && vertex.m_prev_mode != ScatteringMode::Specular)
clamp_contribution(emitted_radiance, m_params.m_max_ray_intensity);
// Update path radiance.
m_path_radiance.add_emission(
vertex.m_path_length,
vertex.m_aov_mode,
emitted_radiance);
}
else
{
// Record light path event.
if (m_light_path_stream)
m_light_path_stream->hit_reflector(vertex);
}
}
void on_scatter(PathVertex& vertex)
{
assert(vertex.m_scattering_modes != ScatteringMode::None);
// Any light contribution after a diffuse or glossy bounce is considered indirect.
if (ScatteringMode::has_diffuse_or_glossy_or_volume(vertex.m_prev_mode))
m_is_indirect_lighting = true;
// When caustics are disabled, disable glossy and specular components after a diffuse or volume bounce.
const bool has_diffuse_or_volume_scattering =
vertex.m_prev_mode == ScatteringMode::Diffuse ||
vertex.m_prev_mode == ScatteringMode::Volume;
if (!m_params.m_enable_caustics && has_diffuse_or_volume_scattering)
vertex.m_scattering_modes &= ~(ScatteringMode::Glossy | ScatteringMode::Specular);
// Terminate the path if all scattering modes are disabled.
if (vertex.m_scattering_modes == ScatteringMode::None)
return;
DirectShadingComponents vertex_radiance;
if (vertex.m_bssrdf == nullptr)
{
// If we have an OSL shader, we need to choose one of the closures and set
// its shading basis into the shading point for the DirectLightingIntegrator
// to use it.
if (m_params.m_enable_dl || m_params.m_enable_ibl)
{
const Material::RenderData& material_data =
vertex.m_shading_point->get_material()->get_render_data();
if (material_data.m_shader_group)
{
// todo: don't split if there's only one closure.
m_sampling_context.split_in_place(2, 1);
m_shading_context.choose_bsdf_closure_shading_basis(
*vertex.m_shading_point,
m_sampling_context.next2<Vector2f>());
}
}
}
// Direct lighting contribution.
if (m_params.m_enable_dl || vertex.m_path_length > 1)
{
if (vertex.m_bsdf)
{
add_direct_lighting_contribution_bsdf(
*vertex.m_shading_point,
vertex.m_outgoing,
*vertex.m_bsdf,
vertex.m_bsdf_data,
vertex.m_scattering_modes,
vertex_radiance,
m_light_path_stream);
}
}
// Image-based lighting contribution.
if (m_params.m_enable_ibl && m_env_edf)
{
if (vertex.m_bsdf)
{
add_image_based_lighting_contribution_bsdf(
*vertex.m_shading_point,
vertex.m_outgoing,
*vertex.m_bsdf,
vertex.m_bsdf_data,
vertex.m_scattering_modes,
vertex_radiance,
m_light_path_stream);
}
}
// Apply path throughput.
vertex_radiance *= vertex.m_throughput;
// Optionally clamp secondary rays contribution.
if (m_params.m_has_max_ray_intensity && vertex.m_path_length > 1 && vertex.m_prev_mode != ScatteringMode::Specular)
clamp_contribution(vertex_radiance, m_params.m_max_ray_intensity);
// Update path radiance.
m_path_radiance.add(
vertex.m_path_length,
vertex.m_aov_mode,
vertex_radiance);
}
private:
bool m_is_indirect_lighting;
void add_emitted_light_contribution(
const PathVertex& vertex,
Spectrum& vertex_radiance)
{
// Compute the emitted radiance.
Spectrum emitted_radiance(Spectrum::Illuminance);
vertex.compute_emitted_radiance(m_shading_context, emitted_radiance);
// Multiple importance sampling.
if (vertex.m_prev_mode != ScatteringMode::Specular)
{
const float light_sample_count = max(m_params.m_dl_light_sample_count, 1.0f);
const float mis_weight =
mis_power2(
1.0f * vertex.get_bsdf_prob_area(),
light_sample_count * vertex.get_light_prob_area(m_light_sampler));
emitted_radiance *= mis_weight;
}
// Add emitted light contribution.
vertex_radiance += emitted_radiance;
}
void add_direct_lighting_contribution_bsdf(
const ShadingPoint& shading_point,
const Dual3d& outgoing,
const BSDF& bsdf,
const void* bsdf_data,
const int scattering_modes,
DirectShadingComponents& vertex_radiance,
LightPathStream* light_path_stream)
{
DirectShadingComponents dl_radiance;
const size_t light_sample_count =
stochastic_cast<size_t>(
m_sampling_context,
m_params.m_dl_light_sample_count);
if (light_sample_count == 0)
return;
const BSDFSampler bsdf_sampler(
bsdf,
bsdf_data,
scattering_modes, // bsdf_sampling_modes (unused)
shading_point);
// This path will be extended via BSDF sampling: sample the lights only.
const DirectLightingIntegrator integrator(
m_shading_context,
m_light_sampler,
bsdf_sampler,
shading_point.get_time(),
scattering_modes, // light_sampling_modes
1, // material_sample_count
light_sample_count,
m_params.m_dl_low_light_threshold,
m_is_indirect_lighting);
integrator.compute_outgoing_radiance_light_sampling_low_variance(
m_sampling_context,
MISPower2,
outgoing,
dl_radiance,
light_path_stream);
// Divide by the sample count when this number is less than 1.
if (m_params.m_rcp_dl_light_sample_count > 0.0f)
dl_radiance *= m_params.m_rcp_dl_light_sample_count;
// Add direct lighting contribution.
vertex_radiance += dl_radiance;
}
void add_image_based_lighting_contribution_bsdf(
const ShadingPoint& shading_point,
const Dual3d& outgoing,
const BSDF& bsdf,
const void* bsdf_data,
const int scattering_modes,
DirectShadingComponents& vertex_radiance,
LightPathStream* light_path_stream)
{
DirectShadingComponents ibl_radiance;
const size_t env_sample_count =
stochastic_cast<size_t>(
m_sampling_context,
m_params.m_ibl_env_sample_count);
const BSDFSampler bsdf_sampler(
bsdf,
bsdf_data,
scattering_modes, // bsdf_sampling_modes (unused)
shading_point);
// This path will be extended via BSDF sampling: sample the environment only.
compute_ibl_environment_sampling(
m_sampling_context,
m_shading_context,
*m_env_edf,
outgoing,
bsdf_sampler,
scattering_modes,
1, // bsdf_sample_count
env_sample_count,
ibl_radiance,
light_path_stream);
// Divide by the sample count when this number is less than 1.
if (m_params.m_rcp_ibl_env_sample_count > 0.0f)
ibl_radiance *= m_params.m_rcp_ibl_env_sample_count;
// Add image-based lighting contribution.
vertex_radiance += ibl_radiance;
}
};
//
// Base volume visitor.
//
class VolumeVisitorBase
{
public:
bool accept_scattering(const ScatteringMode::Mode prev_mode)
{
return true;
}
void on_scatter(PathVertex& vertex)
{
// When caustics are disabled, disable glossy and specular components after a diffuse or volume bounce.
// Note that accept_scattering() is later going to return false in this case.
const bool has_diffuse_or_volume_scattering =
vertex.m_prev_mode == ScatteringMode::Diffuse ||
vertex.m_prev_mode == ScatteringMode::Volume;
if (!m_params.m_enable_caustics && has_diffuse_or_volume_scattering)
vertex.m_scattering_modes &= ~(ScatteringMode::Glossy | ScatteringMode::Specular);
}
protected:
const Parameters& m_params;
const BackwardLightSampler& m_light_sampler;
SamplingContext& m_sampling_context;
const ShadingContext& m_shading_context;
ShadingComponents& m_path_radiance;
const EnvironmentEDF* m_env_edf;
bool m_is_indirect_lighting;
size_t& m_inf_volume_ray_warnings;
VolumeVisitorBase(
const Parameters& params,
const BackwardLightSampler& light_sampler,
SamplingContext& sampling_context,
const ShadingContext& shading_context,
const Scene& scene,
ShadingComponents& path_radiance,
size_t& inf_volume_ray_warnings)
: m_params(params)
, m_light_sampler(light_sampler)
, m_sampling_context(sampling_context)
, m_shading_context(shading_context)
, m_path_radiance(path_radiance)
, m_env_edf(scene.get_environment()->get_environment_edf())
, m_is_indirect_lighting(false)
, m_inf_volume_ray_warnings(inf_volume_ray_warnings)
{
}
};
//
// Volume visitor without next event estimation.
//
class VolumeVisitorSimple
: public VolumeVisitorBase
{
public:
VolumeVisitorSimple(
const Parameters& params,
const BackwardLightSampler& light_sampler,
SamplingContext& sampling_context,
const ShadingContext& shading_context,
const Scene& scene,
ShadingComponents& path_radiance,
size_t& inf_volume_ray_warnings)
: VolumeVisitorBase(
params,
light_sampler,
sampling_context,
shading_context,
scene,
path_radiance,
inf_volume_ray_warnings)
{
}
void visit_ray(PathVertex& vertex, const ShadingRay& volume_ray)
{
// Any light contribution after a diffuse, glossy or volume bounce is considered indirect.
if (ScatteringMode::has_diffuse_or_glossy_or_volume(vertex.m_scattering_modes))
m_is_indirect_lighting = true;
}
};
//
// Volume visitor with next event estimation.
//
class VolumeVisitorDistanceSampling
: public VolumeVisitorBase
{
public:
VolumeVisitorDistanceSampling(
const Parameters& params,
const BackwardLightSampler& light_sampler,
SamplingContext& sampling_context,
const ShadingContext& shading_context,
const Scene& scene,
ShadingComponents& path_radiance,
size_t& inf_volume_ray_warnings)
: VolumeVisitorBase(
params,
light_sampler,
sampling_context,
shading_context,
scene,
path_radiance,
inf_volume_ray_warnings)
{
}
float sample_distance(
const ShadingRay& volume_ray,
const float extinction,
float& distance)
{
m_sampling_context.split_in_place(1, 1);
if (!volume_ray.is_finite())
{
// Sample distance.
distance = sample_exponential_distribution(
m_sampling_context.next2<float>(), extinction);
// Calculate PDF of this distance sample.
return exponential_distribution_pdf(distance, extinction);
}
else
{
// Sample distance.
const float ray_length = static_cast<float>(volume_ray.get_length());
distance = sample_exponential_distribution_on_segment(
m_sampling_context.next2<float>(), extinction, 0.0f, ray_length);
// Calculate PDF of this distance sample.
return exponential_distribution_on_segment_pdf(
distance, extinction, 0.0f, ray_length);
}
}
void visit_ray(PathVertex& vertex, const ShadingRay& volume_ray)
{
// Any light contribution after a diffuse, glossy or volume bounce is considered indirect.
if (ScatteringMode::has_diffuse_or_glossy_or_volume(vertex.m_scattering_modes))
m_is_indirect_lighting = true;
if (!volume_ray.is_finite())
{
if (m_inf_volume_ray_warnings < MaxInfVolumeRayWarnings)
RENDERER_LOG_WARNING("volume ray of infinite length encountered.");
else if (m_inf_volume_ray_warnings == MaxInfVolumeRayWarnings)
RENDERER_LOG_WARNING("more volume rays of infinite length found, "
"omitting warning messages for brevity.");
++m_inf_volume_ray_warnings;
}
const ShadingRay::Medium* medium = volume_ray.get_current_medium();
assert(medium != nullptr);
const Volume* volume = medium->get_volume();
assert(volume != nullptr);
const size_t light_sample_count =
stochastic_cast<size_t>(
m_sampling_context,
m_params.m_dl_light_sample_count);
VolumeLightingIntegrator integrator(
m_shading_context,
m_light_sampler,
*volume,
volume_ray,
vertex.m_volume_data,
*vertex.m_shading_point,
vertex.m_scattering_modes,
m_params.m_distance_sample_count,
light_sample_count,
m_params.m_dl_low_light_threshold,
m_is_indirect_lighting);
DirectShadingComponents radiance;
if (m_params.m_enable_equiangular_sampling)
{
integrator.compute_radiance_combined_sampling(
m_sampling_context,
MISPower2,
radiance);
}
else
{
integrator.compute_radiance_exponential_sampling(
m_sampling_context,
MISPower2,
radiance);
}
radiance *= vertex.m_throughput;
m_path_radiance.add(vertex.m_path_length, vertex.m_aov_mode, radiance);
}
};
};
}
//
// PTLightingEngineFactory class implementation.
//
Dictionary PTLightingEngineFactory::get_params_metadata()
{
Dictionary metadata;
metadata.dictionaries().insert(
"enable_dl",
Dictionary()
.insert("type", "bool")
.insert("default", "true")
.insert("label", "Enable Direct Lighting")
.insert("help", "Enable direct lighting"));
metadata.dictionaries().insert(
"enable_ibl",
Dictionary()
.insert("type", "bool")
.insert("default", "on")
.insert("label", "Enable IBL")
.insert("help", "Enable image-based lighting"));
metadata.dictionaries().insert(
"enable_caustics",
Dictionary()
.insert("type", "bool")
.insert("default", "false")
.insert("label", "Enable Caustics")
.insert("help", "Enable caustics"));
metadata.dictionaries().insert(
"max_bounces",
Dictionary()
.insert("type", "int")
.insert("default", "8")
.insert("unlimited", "true")
.insert("min", "0")
.insert("label", "Max Bounces")
.insert("help", "Maximum number of bounces"));
metadata.dictionaries().insert(
"max_diffuse_bounces",
Dictionary()
.insert("type", "int")
.insert("default", "3")
.insert("unlimited", "true")
.insert("min", "0")
.insert("label", "Max Diffuse Bounces")
.insert("help", "Maximum number of diffuse bounces"));
metadata.dictionaries().insert(
"max_glossy_bounces",
Dictionary()
.insert("type", "int")
.insert("default", "8")
.insert("unlimited", "true")
.insert("min", "0")
.insert("label", "Max Glossy Bounces")
.insert("help", "Maximum number of glossy bounces"));
metadata.dictionaries().insert(
"max_specular_bounces",
Dictionary()
.insert("type", "int")
.insert("default", "8")
.insert("unlimited", "true")
.insert("min", "0")
.insert("label", "Max Specular Bounces")
.insert("help", "Maximum number of specular bounces"));
metadata.dictionaries().insert(
"max_volume_bounces",
Dictionary()
.insert("type", "int")
.insert("default", "0")
.insert("unlimited", "false")
.insert("min", "0")
.insert("label", "Max Volume Bounces")
.insert("help", "Maximum number of volume scattering events (0 = single scattering)"));
metadata.dictionaries().insert(
"rr_min_path_length",
Dictionary()
.insert("type", "int")
.insert("default", "6")
.insert("min", "1")
.insert("label", "Russian Roulette Start Bounce")
.insert("help", "Consider pruning low contribution paths starting with this bounce"));
metadata.dictionaries().insert(
"next_event_estimation",
Dictionary()
.insert("type", "bool")
.insert("default", "true")
.insert("label", "Next Event Estimation")
.insert("help", "Explicitly connect path vertices to light sources to improve efficiency"));
metadata.dictionaries().insert(
"dl_light_samples",
Dictionary()
.insert("type", "float")
.insert("default", "1.0")
.insert("label", "Light Samples")
.insert("help", "Number of samples used to estimate direct lighting"));
metadata.dictionaries().insert(
"dl_low_light_threshold",
Dictionary()
.insert("type", "float")
.insert("default", "0.0")
.insert("label", "Low Light Threshold")
.insert("help", "Light contribution threshold to disable shadow rays"));
metadata.dictionaries().insert(
"ibl_env_samples",
Dictionary()
.insert("type", "float")
.insert("default", "1.0")
.insert("label", "IBL Samples")
.insert("help", "Number of samples used to estimate environment lighting"));
metadata.dictionaries().insert(
"clamp_roughness",
Dictionary()
.insert("type", "bool")
.insert("default", "false")
.insert("label", "Clamp BSDF roughness")
.insert("help", "Clamp BSDF roughness parameter to a maximum level to reduce fireflies in glossy reflections"));
metadata.dictionaries().insert(
"max_ray_intensity",
Dictionary()
.insert("type", "float")
.insert("default", "1.0")
.insert("unlimited", "true")
.insert("min", "0.0")
.insert("label", "Max Ray Intensity")
.insert("help", "Clamp intensity of rays (after the first bounce) to this value to reduce fireflies"));
metadata.dictionaries().insert(
"volume_distance_samples",
Dictionary()
.insert("type", "int")
.insert("default", "2")
.insert("unlimited", "true")
.insert("min", "1")
.insert("label", "Volume Distance Samples")
.insert("help", "Number of distance samples for volume rendering"));
metadata.dictionaries().insert(
"optimize_for_lights_outside_volumes",
Dictionary()
.insert("type", "bool")
.insert("default", "false")
.insert("label", "Optimize for Lights Outside Volumes")
.insert("help", "Optimize distance sampling for lights that are located outside volumes"));
metadata.dictionaries().insert(
"record_light_paths",
Dictionary()
.insert("type", "bool")
.insert("default", "false")
.insert("label", "Record Light Paths")
.insert("help", "Record light paths in memory to later allow visualizing them or saving them to disk"));
return metadata;
}
PTLightingEngineFactory::PTLightingEngineFactory(
const BackwardLightSampler& light_sampler,
LightPathRecorder& light_path_recorder,
const ParamArray& params)
: m_light_sampler(light_sampler)
, m_light_path_recorder(light_path_recorder)
, m_params(params)
{
}
void PTLightingEngineFactory::release()
{
delete this;
}
ILightingEngine* PTLightingEngineFactory::create()
{
return
new PTLightingEngine(
m_light_sampler,
m_light_path_recorder,
m_params);
}
} // namespace renderer
|
#include "OsmLogger.hpp"
#include "Eigen/Core"
#include <array>
#include <vector>
#include <set>
int main(void)
{
std::array<double, 2> arr{410, 420};
OsmLogger::instance().log(arr);
std::vector<double> vec{69, 402};
OsmLogger::instance().log(vec);
const Eigen::Vector3d pt(8800, 1, 2);
OsmLogger::instance().log(pt);
std::array<std::array<double,2>, 2> pts_arr{std::array<double,2>{11, 22}, std::array<double,2>{33, 44}};
OsmLogger::instance().log(pts_arr);
std::vector<Eigen::Vector3d> pts_vec{Eigen::Vector3d(77, 88, 0), Eigen::Vector3d(99, 11, 0)};
OsmLogger::instance().log(pts_vec);
OsmLogger::instance().osm_xml.save(std::cout);
return 0;
}
|
#pragma once
#include "SFML/Graphics.hpp"
#include <cstdio>
namespace gio
{
class Bullet
{
public:
Bullet(bool right);
void OnDraw(sf::RenderWindow& w, float timestep);
void OnEvent(sf::Event e);
void SetPosition(sf::Vector2f);
sf::Vector2f GetPosition() const;
private:
sf::RectangleShape body_ {};
float acceleration {50.f};
float position {};
float velocity {};
bool right_ = true;
};
} // namespace gio
|
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/tfrt/saved_model/saved_model.h"
#include <algorithm>
#include <cstddef>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/str_join.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "tensorflow/cc/saved_model/reader.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/import_model.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/tf_mlir_translate.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/upgrade_graph.h"
#include "tensorflow/compiler/mlir/tfrt/jit/tf_jitrt_request_context.h"
#include "tensorflow/compiler/mlir/tfrt/translate/import_model.h"
#include "tensorflow/compiler/mlir/tfrt/translate/tfrt_compile_options.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/core/common_runtime/function_def_utils.h"
#include "tensorflow/core/common_runtime/graph_constructor.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/gtl/cleanup.h"
#include "tensorflow/core/lib/monitoring/gauge.h"
#include "tensorflow/core/platform/enable_tf2_utils.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/path.h"
#include "tensorflow/core/profiler/lib/connected_traceme.h"
#include "tensorflow/core/profiler/lib/traceme.h"
#include "tensorflow/core/profiler/lib/traceme_encode.h"
#include "tensorflow/core/protobuf/meta_graph.pb.h"
#include "tensorflow/core/protobuf/rewriter_config.pb.h"
#include "tensorflow/core/runtime_fallback/kernel/kernel_fallback_execute_compat.h"
#include "tensorflow/core/runtime_fallback/util/tensor_util.h"
#include "tensorflow/core/tfrt/runtime/work_queue_interface.h"
#include "tensorflow/core/tfrt/saved_model/saved_model_import_input.h"
#include "tensorflow/core/tfrt/tpu/tpu_resources.h"
// TODO(b/200579737): using FunctionRegistry is simpler than the OSS trick.
#include "tensorflow/core/tfrt/graph_executor/graph_executor.h"
#include "tensorflow/core/tfrt/utils/error_util.h"
#include "tensorflow/core/tfrt/utils/fallback_tensor.h"
#include "tensorflow/core/tfrt/utils/tensor_util.h"
#include "tensorflow/core/tfrt/utils/utils.h"
#include "tfrt/bef_executor/bef_file.h" // from @tf_runtime
#include "tfrt/core_runtime/core_runtime.h" // from @tf_runtime
#include "tfrt/core_runtime/tensor_handle.h" // from @tf_runtime
#include "tfrt/host_context/async_dispatch.h" // from @tf_runtime
#include "tfrt/host_context/async_value.h" // from @tf_runtime
#include "tfrt/host_context/chain.h" // from @tf_runtime
#include "tfrt/host_context/concurrent_work_queue.h" // from @tf_runtime
#include "tfrt/host_context/execution_context.h" // from @tf_runtime
#include "tfrt/host_context/function.h" // from @tf_runtime
#include "tfrt/host_context/host_context.h" // from @tf_runtime
#include "tfrt/host_context/request_deadline_tracker.h" // from @tf_runtime
#include "tfrt/metrics/common_metrics.h" // from @tf_runtime
#include "tfrt/support/error_util.h" // from @tf_runtime
#include "tfrt/support/logging.h" // from @tf_runtime
#include "tfrt/support/ref_count.h" // from @tf_runtime
namespace tensorflow {
namespace tfrt_stub {
namespace {
constexpr absl::string_view kSignatureJoiningDelimiter = "+";
constexpr absl::string_view kTensorNameJoiningDelimiter = "-";
constexpr absl::string_view kArgumentTypeJoiningDelimiter = "^";
using SignatureMap = absl::flat_hash_map<std::string, internal::Signature>;
using ::tensorflow::SessionMetadata;
using ::tensorflow::StatusOr;
struct InitializersAndSignatures {
llvm::SmallVector<std::string, 4> initializers;
SignatureMap signature_map;
};
auto* saved_model_read_meta_graph_time_seconds =
tensorflow::monitoring::Gauge<int64_t, 1>::New(
"/tensorflow/tfrt/saved_model/read_meta_graph_time",
"Record the time of reading meta_graph from disk.", "model_name");
auto* saved_model_functionalization_time_seconds =
tensorflow::monitoring::Gauge<int64_t, 1>::New(
"/tensorflow/tfrt/saved_model/functionalization_time",
"Record the functionalization time for the savedmodel.", "model_name");
auto* saved_model_grappler_time_seconds =
tensorflow::monitoring::Gauge<int64_t, 1>::New(
"/tensorflow/tfrt/saved_model/grappler_time",
"Record the grappler time for the savedmodel.", "model_name");
auto* saved_model_import_time_seconds =
tensorflow::monitoring::Gauge<int64_t, 1>::New(
"/tensorflow/tfrt/saved_model/import_time",
"Record the MLIR import time for the savedmodel.", "model_name");
auto* saved_model_compile_time_seconds =
tensorflow::monitoring::Gauge<int64_t, 1>::New(
"/tensorflow/tfrt/saved_model/compile_time",
"Record the compilation time for the savedmodel.", "model_name");
auto* saved_model_init_time_seconds =
tensorflow::monitoring::Gauge<int64_t, 1>::New(
"/tensorflow/tfrt/saved_model/init_time",
"Record the initialization time for the savedmodel.", "model_name");
tensorflow::Tensor CreateScalarStringTensor(absl::string_view str) {
return tensorflow::Tensor(tensorflow::tstring(str));
}
// Create the tensor for the bound input, which can be a variable or an asset.
//
// TODO(chky): For V2 models, the bound input can also be a resource.
StatusOr<tensorflow::Tensor> CreateTensorFromBoundInput(
mlir::Operation* bound_input, absl::string_view saved_model_dir,
absl::flat_hash_map<std::string, tensorflow::Tensor>* variables) {
// Assets are files in the saved model directory. We pass their filenames to
// functions so that they can be used.
if (auto asset = llvm::dyn_cast<mlir::tf_saved_model::AssetOp>(bound_input)) {
// The filename in the asset is a relative path. So we prefix it with the
// directory path.
return CreateScalarStringTensor(
tensorflow::io::JoinPath(saved_model_dir, asset.filename().str()));
}
return tensorflow::errors::Internal(
"Failed to create captured tensors: unknown bound input type.");
}
StatusOr<SignatureMap> GetFunctionSignaturesFromTFSavedModelMLIR(
absl::string_view saved_model_dir, mlir::ModuleOp module) {
absl::flat_hash_map<std::string, tensorflow::Tensor> variables;
SignatureMap signatures;
tensorflow::StatusGroup status_group;
TF_RETURN_IF_ERROR(tensorflow::MapFunctionSignaturesFromTFSavedModelMLIR(
module, [&status_group, &variables, &signatures, saved_model_dir](
const tensorflow::TFRTSavedModelSignatureInfo& sig_info) {
auto& signature = signatures[std::string(sig_info.func_name)];
auto copy = [](llvm::ArrayRef<llvm::StringRef> src,
std::vector<std::string>* dst) {
transform(src, std::back_inserter(*dst),
[](llvm::StringRef x) { return x.str(); });
};
copy(sig_info.input_names, &signature.input_names);
copy(sig_info.output_names, &signature.output_names);
copy(sig_info.input_devices, &signature.input_devices);
DCHECK(signature.input_specs.empty());
signature.input_specs.reserve(sig_info.input_specs.size());
for (auto& spec : sig_info.input_specs) {
signature.input_specs.push_back(TensorSpec(spec.first, spec.second));
}
DCHECK(signature.output_specs.empty());
signature.output_specs.reserve(sig_info.output_specs.size());
for (auto& spec : sig_info.output_specs) {
signature.output_specs.push_back(TensorSpec(spec.first, spec.second));
}
for (auto* bound_input : sig_info.bound_inputs) {
auto statusor_capture = CreateTensorFromBoundInput(
bound_input, saved_model_dir, &variables);
if (!statusor_capture.ok()) {
status_group.Update(statusor_capture.status());
// Insert a random tensor in case of errors.
signature.captures.push_back(tensorflow::Tensor());
} else {
signature.captures.push_back(
std::move(statusor_capture).ValueOrDie());
}
}
}));
if (!status_group.ok()) return status_group.as_concatenated_status();
return signatures;
}
tensorflow::Status RunInitializers(
const InitializersAndSignatures& initializers_and_signatures,
const SessionMetadata& model_metadata, tfrt::BEFFile* bef_file,
const Runtime& runtime, tfrt::ResourceContext* resource_context,
const FallbackState& fallback_state) {
auto* host = runtime.core_runtime()->GetHostContext();
TF_ASSIGN_OR_RETURN(auto request_info,
SetUpRequestContext(/*run_options=*/{}, model_metadata,
host, runtime.work_queue(),
resource_context, fallback_state));
tfrt::ExecutionContext exec_ctx(request_info->tfrt_request_context);
// Run "_tfrt_fallback_init" first to initialize fallback-specific states. It
// is the special function created by compiler, which calls a sequence of
// tfrt_fallback_async.createop to create all fallback ops used in this BEF.
TF_RETURN_IF_ERROR(
RunRuntimeInitializer(exec_ctx, bef_file, "_tfrt_fallback_init"));
for (const auto& init : initializers_and_signatures.initializers) {
// TODO(b/184771263): Consider using `GraphExecutionRunOnFunction()`
// instead.
auto* func = bef_file->GetFunction(init);
assert(func);
const auto& signature = initializers_and_signatures.signature_map.at(init);
auto ready_chain = tfrt::GetReadyChain();
// The actual arguments are the concat of side-effect chain and assets.
llvm::SmallVector<tfrt::AsyncValue*, 1> arguments;
auto cleanup = tensorflow::gtl::MakeCleanup([&]() {
for (auto* argument : arguments) argument->DropRef();
});
arguments.push_back(ready_chain.release());
for (const auto& capture : signature.captures) {
arguments.push_back(
tfrt::MakeAvailableAsyncValueRef<FallbackTensor>(capture).release());
}
assert(arguments.size() == func->argument_types().size());
llvm::SmallVector<tfrt::RCReference<tfrt::AsyncValue>, 1> results;
results.resize(func->result_types().size());
assert(results.size() == 1);
func->Execute(exec_ctx, arguments, results);
// Wait for the function execution to finish, as well as the side-effects.
host->Await(results);
if (auto* error = results[0]->GetErrorIfPresent()) {
return CreateTfErrorStatus(*error);
}
}
// After we initialized all the resources in the original graph, we can run
// the "_tfrt_resource_init" function to set these resources in runtime
// states, so that later it can be efficiently retrieved without any locking.
TF_RETURN_IF_ERROR(
RunRuntimeInitializer(exec_ctx, bef_file, "_tfrt_resource_init"));
return tensorflow::Status::OK();
}
std::vector<std::string> FindNamesForValidSignatures(
const tensorflow::MetaGraphDef& meta_graph_def) {
std::vector<std::string> valid_signature_names;
auto is_dense_tensor_info = [](const auto& named_tensor_info) {
return !named_tensor_info.second.name().empty();
};
auto is_ref_type_tensor_info = [](const auto& named_tensor_info) {
return tensorflow::IsRefType(named_tensor_info.second.dtype());
};
for (const auto& iter : meta_graph_def.signature_def()) {
const auto& sig_key = iter.first;
const auto& signature = iter.second;
if (!std::all_of(signature.inputs().begin(), signature.inputs().end(),
is_dense_tensor_info) ||
!std::all_of(signature.outputs().begin(), signature.outputs().end(),
is_dense_tensor_info)) {
LOG(WARNING) << "Unsupported signature with non-dense tensors as "
"input/output. Name: "
<< sig_key << "; Signature: " << signature.DebugString();
continue;
}
if (std::any_of(signature.inputs().begin(), signature.inputs().end(),
is_ref_type_tensor_info) ||
std::any_of(signature.outputs().begin(), signature.outputs().end(),
is_ref_type_tensor_info)) {
LOG(WARNING) << "Unsupported signature with ref type tensors as "
"input/output. Name: "
<< sig_key << "; Signature: " << signature.DebugString();
continue;
}
valid_signature_names.push_back(sig_key);
}
return valid_signature_names;
}
StatusOr<mlir::OwningOpRef<mlir::ModuleOp>> ImportSavedModel(
mlir::MLIRContext* context, const tensorflow::MetaGraphDef& meta_graph_def,
const FallbackState& fallback_state, std::string saved_model_dir,
bool import_user_signatures, bool run_placer_grappler_on_functions) {
std::vector<std::string> signature_names;
if (import_user_signatures) {
signature_names = FindNamesForValidSignatures(meta_graph_def);
if (signature_names.empty())
LOG(WARNING) << "No valid signature found for model: " << saved_model_dir;
}
// TfrtSavedModelMLIRImportInput basically implements the graph processing
// logic (eg. Placer and Grappler) used in DirectSession, which apply graph
// transformations on each subgraphs (ie. signatures). It is reusing the
// code path in DirectSession to avoid problems caused by different behavior
// in a different code path. And it is injected to the MLIR importer so that
// the importer can import the transformed graph instead of the original
// graph.
TF_ASSIGN_OR_RETURN(auto import_input,
TfrtSavedModelMLIRImportInput::Create(
fallback_state, &meta_graph_def, /*debug_info=*/{},
run_placer_grappler_on_functions));
TF_ASSIGN_OR_RETURN(
auto module,
tensorflow::ConvertSavedModelV1ToMlirLite(
import_input,
/*exported_names=*/absl::MakeSpan(signature_names), context));
LOG(INFO) << "TFRT ImportSavedModel: Functionalization took "
<< absl::ToInt64Milliseconds(
import_input.GetFunctionalizationDuration())
<< " ms.";
LOG(INFO) << "TFRT ImportSavedModel: Grappler took "
<< absl::ToInt64Milliseconds(import_input.GetGrapplerDuration())
<< " ms.";
saved_model_functionalization_time_seconds->GetCell(saved_model_dir)
->Set(absl::ToInt64Seconds(import_input.GetFunctionalizationDuration()));
saved_model_grappler_time_seconds->GetCell(saved_model_dir)
->Set(absl::ToInt64Seconds(import_input.GetGrapplerDuration()));
return module;
}
StatusOr<InitializersAndSignatures> GetInitializersAndSignatures(
mlir::ModuleOp module, absl::string_view saved_model_dir) {
InitializersAndSignatures result;
TF_ASSIGN_OR_RETURN(
result.signature_map,
GetFunctionSignaturesFromTFSavedModelMLIR(saved_model_dir, module));
for (auto session_initializer_name :
mlir::tf_saved_model::GetSessionInitializerExportedName(module)) {
result.initializers.push_back(session_initializer_name.str());
}
return result;
}
tensorflow::Status InitSavedModel(
const InitializersAndSignatures& initializers_and_signatures,
tfrt::BEFFile* bef_file, const SavedModel::Options& options,
tfrt::ResourceContext* resource_context,
const FallbackState& fallback_state) {
TF_RETURN_IF_ERROR(
RunInitializers(initializers_and_signatures,
options.graph_execution_options.model_metadata, bef_file,
*options.graph_execution_options.runtime,
resource_context, fallback_state));
return tensorflow::Status::OK();
}
} // namespace
SavedModel::~SavedModel() {}
tfrt::HostContext* SavedModel::GetHostContext() const {
return runtime_->core_runtime()->GetHostContext();
}
std::unique_ptr<SavedModel> SavedModelImpl::LoadSavedModel(
Options options, absl::string_view saved_model_dir,
const std::unordered_set<std::string>& tags, tensorflow::Status* status) {
LOG(INFO) << "TFRT reading v1 savedmodel: " << saved_model_dir;
auto read_start_time = absl::Now();
tensorflow::MetaGraphDef meta_graph_def;
auto read_status = tensorflow::ReadMetaGraphDefFromSavedModel(
std::string(saved_model_dir), tags, &meta_graph_def);
if (!read_status.ok()) {
*status = read_status;
return nullptr;
}
auto read_meta_graph_duration = absl::Now() - read_start_time;
saved_model_read_meta_graph_time_seconds
->GetCell(std::string(saved_model_dir))
->Set(absl::ToInt64Seconds(read_meta_graph_duration));
LOG(INFO) << "TFRT finished reading meta graph. Took "
<< absl::ToInt64Milliseconds(read_meta_graph_duration) << " ms.";
return LoadSavedModel(std::move(options), saved_model_dir,
std::move(meta_graph_def), status);
}
namespace {
// Gets the signatures from `signature_defs` and inserts them into `signatures`.
void GetSignaturesFromSignatureDef(
SignatureMap& signatures,
const google::protobuf::Map<std::string, tensorflow::SignatureDef>& signature_defs,
const SavedModel::Options& options) {
for (const auto& p : signature_defs) {
const std::string& signature_name = p.first;
const tensorflow::SignatureDef& signature_def = p.second;
DCHECK(signatures.find(signature_name) == signatures.end());
auto& signature = signatures[signature_name];
signature.input_names.reserve(signature_def.inputs().size());
signature.input_specs.reserve(signature_def.inputs().size());
for (const auto& p : signature_def.inputs()) {
const std::string& input_tensor_name = p.first;
const tensorflow::TensorInfo& tensor_info = p.second;
signature.input_names.push_back(input_tensor_name);
signature.input_specs.push_back(
TensorSpec(tensor_info.dtype(), tensor_info.tensor_shape()));
}
signature.input_devices = std::vector<std::string>(
signature_def.inputs().size(),
options.graph_execution_options.compile_options.default_device);
signature.output_names.reserve(signature_def.outputs().size());
signature.output_specs.reserve(signature_def.outputs().size());
for (const auto& p : signature_def.outputs()) {
const std::string& output_tensor_name = p.first;
const tensorflow::TensorInfo& tensor_info = p.second;
signature.output_names.push_back(output_tensor_name);
signature.output_specs.push_back(
TensorSpec(tensor_info.dtype(), tensor_info.tensor_shape()));
}
}
}
} // namespace
std::unique_ptr<SavedModel> SavedModelImpl::LoadSavedModel(
Options options, absl::string_view saved_model_dir,
tensorflow::MetaGraphDef meta_graph_def, tensorflow::Status* status) {
LOG(INFO) << "TFRT loading v1 savedmodel: " << saved_model_dir;
tfrt::metrics::AddTFRTVersionMetric();
UpdateTpuTargetByBridgeCompatibility(options.graph_execution_options,
meta_graph_def.graph_def());
auto statusor_saved_model =
[&]() -> tensorflow::StatusOr<std::unique_ptr<SavedModel>> {
mlir::MLIRContext context;
// Step 1: Import saved model from a proto to an MLIR module.
auto import_start_time = absl::Now();
auto session_options =
CreateDefaultSessionOptions(options.graph_execution_options);
// Set optimize_for_static_graph to true since we won't extend the graph
// later. If optimize_for_static_graph is set to false, FallbackState will
// keep an extra unused copy of the graph, which unnecessarily consumes
// memory.
session_options.config.mutable_experimental()
->set_optimize_for_static_graph(true);
// Creating the fallback_state using the original function def library
// without applying placer or grappler, it is OK for now because it's only
// used for captured functions in certain tf.data ops
const auto& fdef_lib = meta_graph_def.graph_def().library();
TF_ASSIGN_OR_RETURN(auto fallback_state,
FallbackState::Create(session_options, fdef_lib));
TF_ASSIGN_OR_RETURN(
auto mlir_module,
ImportSavedModel(
&context, meta_graph_def, *fallback_state,
std::string(saved_model_dir),
/*import_user_signatures=*/!options.enable_lazy_loading,
options.graph_execution_options.run_placer_grappler_on_functions));
auto import_duration = absl::Now() - import_start_time;
saved_model_import_time_seconds->GetCell(std::string(saved_model_dir))
->Set(absl::ToInt64Seconds(import_duration));
LOG(INFO) << "TFRT finished importing savedmodel. Took "
<< absl::ToInt64Milliseconds(import_duration) << " ms.";
// Step 2: Compile the MLIR module from TF dialect to TFRT dialect (in BEF).
auto compile_start_time = absl::Now();
TF_ASSIGN_OR_RETURN(
auto initializers_and_signatures,
GetInitializersAndSignatures(mlir_module.get(), saved_model_dir));
// If lazy loading is enabled, the user signatures are not exported via MLIR
// module, so we need to get them from the proto.
// TODO(b/187228559): Unify the code paths for populating the signature map.
if (options.enable_lazy_loading) {
GetSignaturesFromSignatureDef(initializers_and_signatures.signature_map,
meta_graph_def.signature_def(), options);
}
tfrt::BefBuffer bef;
TF_RETURN_IF_ERROR(tensorflow::ConvertTfMlirToBef(
options.graph_execution_options.compile_options, mlir_module.get(),
&bef));
auto compile_duration = absl::Now() - compile_start_time;
saved_model_compile_time_seconds->GetCell(std::string(saved_model_dir))
->Set(absl::ToInt64Seconds(compile_duration));
LOG(INFO) << "TFRT finished compiling savedmodel. Took "
<< absl::ToInt64Milliseconds(compile_duration) << " ms.";
// Step 3: Initialize runtime states using special BEF functions.
auto init_start_time = absl::Now();
TF_ASSIGN_OR_RETURN(auto bef_file,
tfrt::CreateBefFileFromBefBuffer(
*options.graph_execution_options.runtime, bef));
auto tpu_model_resource = std::make_unique<tfrt::tpu::TpuModelResource>();
auto resource_context = CreateResourceContext(
*options.graph_execution_options.runtime, tpu_model_resource.get(),
options.graph_execution_options.compile_options.tpu_target);
TF_RETURN_IF_ERROR(InitSavedModel(initializers_and_signatures,
bef_file.get(), options,
resource_context.get(), *fallback_state));
auto init_duration = absl::Now() - init_start_time;
saved_model_init_time_seconds->GetCell(std::string(saved_model_dir))
->Set(absl::ToInt64Seconds(init_duration));
LOG(INFO) << "TFRT finished initializing savedmodel. Took "
<< absl::ToInt64Milliseconds(init_duration) << " ms.";
TF_ASSIGN_OR_RETURN(
auto graph_executor,
GraphExecutor::Create(options.graph_execution_options, *fallback_state,
tpu_model_resource.get(),
std::move(*meta_graph_def.mutable_graph_def())));
// Finally, create the saved model.
return {std::make_unique<SavedModelImpl>(
std::move(options), std::move(meta_graph_def), std::move(bef),
std::move(bef_file),
std::move(initializers_and_signatures.signature_map),
std::move(fallback_state), std::move(tpu_model_resource),
std::move(resource_context), std::move(graph_executor))};
}();
if (!statusor_saved_model.ok()) {
*status = statusor_saved_model.status();
return nullptr;
}
*status = tensorflow::Status::OK();
return std::move(statusor_saved_model).ValueOrDie();
}
SavedModelImpl::SavedModelImpl(
Options options, tensorflow::MetaGraphDef meta_graph_def,
tfrt::BefBuffer bef, tfrt::RCReference<tfrt::BEFFile> bef_file,
SignatureMap signatures, std::unique_ptr<FallbackState> fallback_state,
std::unique_ptr<tfrt::tpu::TpuModelResource> tpu_model_resource,
std::unique_ptr<tfrt::ResourceContext> resource_context,
std::unique_ptr<GraphExecutor> graph_executor)
: SavedModel(options.graph_execution_options.runtime),
options_(std::move(options)),
meta_graph_def_(std::move(meta_graph_def)),
bef_(std::move(bef)),
bef_file_(std::move(bef_file)),
req_deadline_tracker_(
options.graph_execution_options.runtime->core_runtime()
->GetHostContext()),
signatures_(std::move(signatures)),
fallback_state_(std::move(fallback_state)),
tpu_model_resource_(std::move(tpu_model_resource)),
resource_context_(std::move(resource_context)),
graph_executor_(std::move(graph_executor)) {}
SavedModelImpl::~SavedModelImpl() = default;
std::vector<std::string> SavedModelImpl::GetFunctionNames() const {
std::vector<std::string> result;
for (const auto& entry : signatures_) {
result.push_back(entry.first);
}
return result;
}
const tensorflow::MetaGraphDef& SavedModelImpl::GetMetaGraphDef() const {
return meta_graph_def_;
}
absl::optional<FunctionMetadata> SavedModelImpl::GetFunctionMetadata(
absl::string_view func_name) const {
auto iter = signatures_.find(func_name);
if (iter == signatures_.end()) return absl::nullopt;
return FunctionMetadata(&iter->second);
}
namespace {
tensorflow::Status IsInputSpecsCorrect(
absl::string_view name, const internal::Signature& signature,
absl::Span<const tensorflow::Tensor> inputs) {
TF_RET_CHECK(signature.input_specs.size() == inputs.size())
<< "signature " << name
<< " input size is wrong, expected: " << signature.input_specs.size()
<< ", actual: " << inputs.size();
for (size_t i = 0; i < inputs.size(); ++i) {
const auto& expected_input_spec = signature.input_specs[i];
TF_RET_CHECK(expected_input_spec.dtype == inputs[i].dtype())
<< "signature " << name
<< " input dtype is wrong, expected: " << expected_input_spec.dtype
<< ", actual: " << inputs[i].dtype();
TF_RET_CHECK(expected_input_spec.shape.IsCompatibleWith(inputs[i].shape()))
<< "signature " << name
<< " input shape is wrong, expected : " << expected_input_spec.shape
<< ", actual: " << inputs[i].shape();
}
return tensorflow::Status::OK();
}
} // namespace
tensorflow::Status SavedModelImpl::Run(
const RunOptions& run_options, absl::string_view name,
absl::Span<const tensorflow::Tensor> inputs,
std::vector<tensorflow::Tensor>* outputs) {
TF_RET_CHECK(outputs) << "outputs must be provided";
outputs->clear();
auto sig_iter = signatures_.find(name);
TF_RET_CHECK(sig_iter != signatures_.end())
<< "failed to find signature " << name << " in the graph";
if (run_options.validate_input_specs) {
TF_RETURN_IF_ERROR(IsInputSpecsCorrect(name, sig_iter->second, inputs));
}
std::vector<tensorflow::Tensor> captures;
for (const auto& capture : sig_iter->second.captures) {
captures.push_back(capture);
}
const tfrt::Function* func;
tfrt::ResourceContext* resource_context;
if (options_.enable_lazy_loading) {
// If lazy loading is enabled, no signature is loaded into `bef_file_`, so
// we need to find the BEF from the cache or create one.
TF_ASSIGN_OR_RETURN(const LoadingResult& loading_result,
GetOrCreateLoadingResult({std::string(name)}));
func = loading_result.bef_file->GetFunction(
tensorflow::kImportModelDefaultGraphFuncName);
resource_context = loading_result.resource_context.get();
} else {
func = bef_file_->GetFunction({name.data(), name.size()});
resource_context = resource_context_.get();
}
DCHECK(func);
return GraphExecutionRunOnFunction(options_.graph_execution_options,
run_options, name, *func, inputs, captures,
outputs, resource_context, runtime(),
*fallback_state_, req_deadline_tracker_);
}
struct SavedModelImpl::JoinedSignature {
// A unique name for the joined signature.
std::string name;
// The feed nodes for the corresponding inputs, but they might not be in the
// original order and if there are more than one original inputs mapped to the
// same feed node, only one is picked here.
tensorflow::GraphImportConfig::InputArrays input_nodes;
// The fetch nodes for the outputs, which should be in the original order.
std::vector<std::string> output_nodes;
// The target nodes that should be run but not returned as outputs.
std::vector<std::string> target_nodes;
};
tensorflow::Status SavedModelImpl::RunMultipleSignatures(
const RunOptions& run_options, absl::Span<const std::string> names,
absl::Span<const std::vector<tensorflow::Tensor>> multi_inputs,
std::vector<std::vector<tensorflow::Tensor>>* multi_outputs) {
TF_RET_CHECK(names.size() == multi_inputs.size())
<< "the sizes of names and inputs should be the same";
TF_RET_CHECK(multi_outputs) << "outputs must be provided";
multi_outputs->clear();
// Due to possible overlapping of feed nodes among user-specified inputs,
// `JoinSignatures()` will deduplicate against fetch tensor names and produce
// the desired inputs in a new order. The same dedup logic is used here to
// generate the flattened input values in the same order.
//
// Note that we don't need to do any deduplicating nor reordering for the
// fetch nodes.
//
// TODO(tfrt-devs): Consider refactoring JoinSignatures so that we don't have
// the implicit requirement that the same dedup logic must be used here and in
// JoinSignatures().
std::vector<std::pair<std::string /*tensor_name*/, tensorflow::Tensor>>
flat_inputs;
std::vector<std::string> flat_output_names;
absl::flat_hash_set<std::string> visited_feed_tensor_names;
const auto& signature_defs = meta_graph_def_.signature_def();
for (int i = 0; i < names.size(); ++i) {
const auto& signature_name = names[i];
const auto& input_tensors = multi_inputs[i];
auto sig_iter = signature_defs.find(signature_name);
// Early out if any signature can't be found.
TF_RET_CHECK(sig_iter != signature_defs.end())
<< "failed to find signature in the graph";
const auto& signature_def = sig_iter->second;
// `signatures_` keeps the user-specified input names that is in the same
// order as `input_tensors`.
const auto& signature = signatures_.at(signature_name);
const auto& input_names = signature.input_names;
TF_RETURN_IF_ERROR(
IsInputSpecsCorrect(signature_name, signature, input_tensors));
DCHECK(signature.captures.empty());
TF_RET_CHECK(input_tensors.size() == signature_def.inputs().size())
<< "Incorrect input size for signature: " << signature_name
<< ": expected " << signature_def.inputs().size() << ", but got "
<< input_tensors.size();
DCHECK_EQ(input_names.size(), signature_def.inputs().size());
// Then we find out the corresponding tensor names (ie.
// node_name:output_idx) for the inputs using the SignatureDef proto.
//
// TODO(tfrt-devs): Consider including tensor names in `signatures_` as
// well, so that only `signatures_` is used here.
for (int j = 0; j < input_tensors.size(); ++j) {
const auto& tensor_info = signature_def.inputs().at(input_names[j]);
// TODO(b/184675681): Support other encoding cases.
//
// TODO(b/184679394): Add unit test for this check.
TF_RET_CHECK(tensor_info.encoding_case() == tensorflow::TensorInfo::kName)
<< "Only dense tensor is supported, but got encoding case "
<< tensor_info.encoding_case();
const auto& tensor_name = tensor_info.name();
// Skip if we have visited the feed tensor. Otherwise, marked it as
// visited and put it in the `flat_inputs`. Note that the following code
// uses the same logic as in JoinSignatures() to deduplicate inputs with
// the feed tensor names, and generates the flat inputs in the same order.
if (visited_feed_tensor_names.contains(tensor_name)) continue;
visited_feed_tensor_names.insert(tensor_name);
flat_inputs.push_back(std::make_pair(tensor_name, input_tensors[j]));
}
for (const auto& output_key : signature.output_names) {
const auto& tensor_info = signature_def.outputs().at(output_key);
VLOG(1) << "Importing Signature Output: output_key = " << output_key
<< ", tensor_info = " << tensor_info.DebugString();
TF_RET_CHECK(tensor_info.encoding_case() == tensorflow::TensorInfo::kName)
<< "Only dense tensor is supported, but got encoding case "
<< tensor_info.encoding_case();
flat_output_names.push_back(tensor_info.name());
}
}
std::vector<tensorflow::Tensor> flat_outputs;
TF_RETURN_IF_ERROR(
graph_executor_->Run(run_options, flat_inputs, flat_output_names,
/*target_tensor_names=*/{}, &flat_outputs));
// The outputs of the compiled function are in the user-specified order,
// though they are flattened. So we just need to regroup the outputs for each
// signature using the number of outputs of it.
multi_outputs->resize(names.size());
auto cur = flat_outputs.begin();
for (size_t i = 0; i < names.size(); ++i) {
const auto& signature_name = names[i];
const size_t len = signature_defs.at(signature_name).outputs().size();
std::move(cur, cur + len, std::back_inserter(multi_outputs->at(i)));
cur += len;
DCHECK_LE(std::distance(flat_outputs.begin(), cur), flat_outputs.size());
}
return tensorflow::Status::OK();
}
tensorflow::StatusOr<mlir::OwningOpRef<mlir::ModuleOp>>
SavedModelImpl::ImportSubgraph(
mlir::MLIRContext* context,
const tensorflow::GraphImportConfig::InputArrays& input_nodes,
const std::vector<std::string>& output_nodes,
const std::vector<std::string>& target_nodes) {
tensorflow::GraphImportConfig graph_import_config;
graph_import_config.prune_unused_nodes = true;
graph_import_config.enable_shape_inference = false;
graph_import_config.inputs = input_nodes;
graph_import_config.outputs = output_nodes;
graph_import_config.control_outputs = target_nodes;
// Optimize the graph.
TF_ASSIGN_OR_RETURN(
auto optimization_result,
graph_executor_->graph_execution_state().CreateOptimizedGraph(
graph_import_config));
// Convert the optimized graph to an MLIR module.
return tensorflow::ConvertGraphToMlir(
*optimization_result.graph, /*debug_info=*/{},
optimization_result.graph->flib_def(), graph_import_config, context);
}
tensorflow::Status SavedModelImpl::RunByTensorNames(
const RunOptions& run_options,
absl::Span<const std::pair<std::string, tensorflow::Tensor>> inputs,
absl::Span<const std::string> output_tensor_names,
absl::Span<const std::string> target_node_names,
std::vector<tensorflow::Tensor>* outputs) {
// TODO(b/192498110): Validate input type.
return graph_executor_->Run(run_options, inputs, output_tensor_names,
target_node_names, outputs);
}
namespace {
using JoinedSignature = SavedModelImpl::JoinedSignature;
// Returns a joined signature with the signatures in `names`. For inputs, as
// their corresponding nodes may overlap, we deduplicate them by the nodes so
// the order of inputs for the joined signature would be different from the
// original order. For outputs, overlapping is fine so we only flatten it in the
// original order.
StatusOr<JoinedSignature> JoinSignatures(
absl::Span<const std::string> names, const SignatureMap& signature_map,
const tensorflow::protobuf::Map<std::string, tensorflow::SignatureDef>&
signature_def_map) {
// Join all the names, all the inputs, and all the outputs.
JoinedSignature joined_signature;
joined_signature.name = absl::StrJoin(names, kSignatureJoiningDelimiter);
// Keep the feed tensor names visited.
absl::flat_hash_set<std::string> visited_feed_tensor_names;
for (const auto& name : names) {
const auto& signature_def = signature_def_map.at(name);
// For inputs, we deduplicate possible overlapping feed nodes and create the
// new input array.
for (const auto& iter : signature_def.inputs()) {
const auto& tensor_info = iter.second;
// Skip if this feed node is already visited.
if (visited_feed_tensor_names.contains(tensor_info.name())) continue;
// Otherwise, we parse its tensor info and collect it for later
// compilation.
visited_feed_tensor_names.insert(tensor_info.name());
// TODO(b/184675681): Support other encoding cases.
//
// TODO(b/184679394): Add unit test for this check.
TF_RET_CHECK(tensor_info.encoding_case() == tensorflow::TensorInfo::kName)
<< "Only dense tensor is supported, but got encoding case "
<< tensor_info.encoding_case();
VLOG(1) << "Importing Signature Input: input_key = " << iter.first
<< ", tensor_info = " << tensor_info.DebugString();
tensorflow::ArrayInfo array_info;
array_info.imported_dtype = tensor_info.dtype();
if (tensor_info.has_tensor_shape()) {
array_info.shape = tensor_info.tensor_shape();
} else {
// If there is no tensor shape in the tensor info, conservatively set
// unknown_rank to true.
array_info.shape.set_unknown_rank(true);
}
joined_signature.input_nodes.insert(
std::pair<std::string, tensorflow::ArrayInfo>(tensor_info.name(),
std::move(array_info)));
}
// For outputs, we simply flatten them in the original order, as it is fine
// to have duplicated fetch nodes.
const internal::Signature& signature = signature_map.at(name);
for (const auto& output_key : signature.output_names) {
const auto& tensor_info = signature_def.outputs().at(output_key);
VLOG(1) << "Importing Signature Output: output_key = " << output_key
<< ", tensor_info = " << tensor_info.DebugString();
TF_RET_CHECK(tensor_info.encoding_case() == tensorflow::TensorInfo::kName)
<< "Only dense tensor is supported, but got encoding case "
<< tensor_info.encoding_case();
joined_signature.output_nodes.push_back(tensor_info.name());
}
}
return joined_signature;
}
} // namespace
// TODO(b/216379787): Reuse `GraphExecutor::LoadClientGraph()`.
StatusOr<std::reference_wrapper<const SavedModelImpl::LoadingResult>>
SavedModelImpl::LoadJoinedSignature(const JoinedSignature& joined_signature) {
// Step 1: Import the combined subgraph from proto to an MLIR module.
mlir::MLIRContext context;
TF_ASSIGN_OR_RETURN(auto module,
ImportSubgraph(&context, joined_signature.input_nodes,
joined_signature.output_nodes,
joined_signature.target_nodes));
// Step 2: Compile the MLIR module from TF dialect to TFRT dialect (in BEF).
auto loading_result = std::make_unique<LoadingResult>();
loading_result->name = joined_signature.name;
loading_result->resource_context = CreateResourceContext(
runtime(), tpu_model_resource_.get(),
options_.graph_execution_options.compile_options.tpu_target);
TF_RETURN_IF_ERROR(tensorflow::ConvertTfMlirToBef(
options_.graph_execution_options.compile_options, module.get(),
&loading_result->bef));
// Step 3: Initialize runtime states using special BEF functions.
TF_ASSIGN_OR_RETURN(
loading_result->bef_file,
tfrt::CreateBefFileFromBefBuffer(
*options_.graph_execution_options.runtime, loading_result->bef));
TF_RETURN_IF_ERROR(RunInitializers(
/*initializers_and_signatures=*/{},
options_.graph_execution_options.model_metadata,
loading_result->bef_file.get(), *options_.graph_execution_options.runtime,
loading_result->resource_context.get(), *fallback_state_));
// Store loading_result in cache.
const auto* loading_result_ptr = loading_result.get();
loading_result_cache_[joined_signature.name] = std::move(loading_result);
return {*loading_result_ptr};
}
StatusOr<std::reference_wrapper<const SavedModelImpl::LoadingResult>>
SavedModelImpl::GetOrCreateLoadingResult(absl::Span<const std::string> names) {
const auto joined_name = absl::StrJoin(names, kSignatureJoiningDelimiter);
tensorflow::mutex_lock l(loading_result_cache_mu_);
const auto iter = loading_result_cache_.find(joined_name);
if (iter != loading_result_cache_.end()) return {*iter->second};
TF_ASSIGN_OR_RETURN(
const auto joined_signature,
JoinSignatures(names, signatures_, meta_graph_def_.signature_def()));
return LoadJoinedSignature(joined_signature);
}
} // namespace tfrt_stub
} // namespace tensorflow
|
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/compiler-dispatcher/optimizing-compile-dispatcher.h"
#include "src/api/api-inl.h"
#include "src/base/atomic-utils.h"
#include "src/base/platform/semaphore.h"
#include "src/codegen/compiler.h"
#include "src/codegen/optimized-compilation-info.h"
#include "src/execution/isolate.h"
#include "src/handles/handles.h"
#include "src/objects/objects-inl.h"
#include "src/parsing/parse-info.h"
#include "test/unittests/test-helpers.h"
#include "test/unittests/test-utils.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace v8 {
namespace internal {
using OptimizingCompileDispatcherTest = TestWithNativeContext;
namespace {
class BlockingCompilationJob : public OptimizedCompilationJob {
public:
BlockingCompilationJob(Isolate* isolate, Handle<JSFunction> function)
: OptimizedCompilationJob(&info_, "BlockingCompilationJob",
State::kReadyToExecute),
shared_(function->shared(), isolate),
zone_(isolate->allocator(), ZONE_NAME),
info_(&zone_, isolate, shared_, function),
blocking_(false),
semaphore_(0) {}
~BlockingCompilationJob() override = default;
bool IsBlocking() const { return blocking_.Value(); }
void Signal() { semaphore_.Signal(); }
// OptimiziedCompilationJob implementation.
Status PrepareJobImpl(Isolate* isolate) override { UNREACHABLE(); }
Status ExecuteJobImpl() override {
blocking_.SetValue(true);
semaphore_.Wait();
blocking_.SetValue(false);
return SUCCEEDED;
}
Status FinalizeJobImpl(Isolate* isolate) override { return SUCCEEDED; }
private:
Handle<SharedFunctionInfo> shared_;
Zone zone_;
OptimizedCompilationInfo info_;
base::AtomicValue<bool> blocking_;
base::Semaphore semaphore_;
DISALLOW_COPY_AND_ASSIGN(BlockingCompilationJob);
};
} // namespace
TEST_F(OptimizingCompileDispatcherTest, Construct) {
OptimizingCompileDispatcher dispatcher(i_isolate());
ASSERT_TRUE(OptimizingCompileDispatcher::Enabled());
ASSERT_TRUE(dispatcher.IsQueueAvailable());
}
TEST_F(OptimizingCompileDispatcherTest, NonBlockingFlush) {
Handle<JSFunction> fun =
RunJS<JSFunction>("function f() { function g() {}; return g;}; f();");
IsCompiledScope is_compiled_scope;
ASSERT_TRUE(
Compiler::Compile(fun, Compiler::CLEAR_EXCEPTION, &is_compiled_scope));
BlockingCompilationJob* job = new BlockingCompilationJob(i_isolate(), fun);
OptimizingCompileDispatcher dispatcher(i_isolate());
ASSERT_TRUE(OptimizingCompileDispatcher::Enabled());
ASSERT_TRUE(dispatcher.IsQueueAvailable());
dispatcher.QueueForOptimization(job);
// Busy-wait for the job to run on a background thread.
while (!job->IsBlocking()) {
}
// Should not block.
dispatcher.Flush(BlockingBehavior::kDontBlock);
// Unblock the job & finish.
job->Signal();
dispatcher.Stop();
}
} // namespace internal
} // namespace v8
|
/*
* algorithm-bubblesort.cpp
*
* Created by Mateus Nunes de B Magalhaes on 3/14/17.
* Copyright © 2017 mateusnbm. All rights reserved.
*
*/
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include "bubblesort.h"
int main(int argc, const char * argv[]) {
int i;
int numbersCount = 10;
int *arr = (int *) malloc(numbersCount * sizeof(int));
srand((int)time(NULL));
/* Populate the array with random numbers. */
for (i = 0; i < numbersCount; i++) {
arr[i] = (rand() % numbersCount) + 1;
}
/* Print the unsorted array. */
printf("Unsorted array:\n");
for (i = 0; i < numbersCount; i++) {
printf("%i ", arr[i]);
}
printf("\n");
/* Sort the array using quicksort. */
bubblesort(arr, numbersCount);
/* Print the sorted array. */
printf("Sorted array:\n");
for (i = 0; i < numbersCount; i++) {
printf("%i ", arr[i]);
}
printf("\n");
/* Free the memory dynamically allocated. */
free(arr);
return 0;
}
|
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <jni.h>
#include <stdlib.h>
#include <android/log.h>
#include <android/native_window.h>
#include <android/native_window_jni.h>
#include <pthread.h>
extern "C" {
#ifdef __cplusplus
#define __STDC_CONSTANT_MACROS
#ifdef _STDINT_H
#undef _STDINT_H
#endif
#include <stdint.h>
#endif
#include <libavutil/samplefmt.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavformat/avio_internal.h>
#include <libavformat/internal.h>
#include <libavutil/channel_layout.h>
#include <libavutil/error.h>
#include <libavutil/opt.h>
#include <libswresample/swresample.h>
#include <libswscale/swscale.h>
#include <libavutil/imgutils.h>
}
#define OUTPUT_BUFFER_SIZE (1048576)
#define FFMPEG_DECODE_ONLY (1000)
#define TIME_UNSET (-9223372036854775807l)
#define LOG_TAG "ffmpeg_jni"
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, \
__VA_ARGS__))
#define LIBRARY_FUNC(RETURN_TYPE, NAME, ...) \
extern "C" { \
JNIEXPORT RETURN_TYPE \
Java_com_google_android_exoplayer2_ext_ffmpeg2_FfmpegLibrary_##NAME( \
JNIEnv *env, jobject thiz, ##__VA_ARGS__); \
} \
JNIEXPORT RETURN_TYPE \
Java_com_google_android_exoplayer2_ext_ffmpeg2_FfmpegLibrary_##NAME( \
JNIEnv *env, jobject thiz, ##__VA_ARGS__)
#define AUDIO_DECODER_FUNC(RETURN_TYPE, NAME, ...) \
extern "C" { \
JNIEXPORT RETURN_TYPE \
Java_com_google_android_exoplayer2_ext_ffmpeg2_FfmpegAudioDecoder_##NAME( \
JNIEnv *env, jobject thiz, ##__VA_ARGS__); \
} \
JNIEXPORT RETURN_TYPE \
Java_com_google_android_exoplayer2_ext_ffmpeg2_FfmpegAudioDecoder_##NAME( \
JNIEnv *env, jobject thiz, ##__VA_ARGS__)
#define FFMPEG_DEMUXER_FUNC(RETURN_TYPE, NAME, ...) \
extern "C" { \
JNIEXPORT RETURN_TYPE \
Java_com_google_android_exoplayer2_ext_ffmpeg2_FfmpegDemuxer_##NAME( \
JNIEnv *env, jobject thiz, ##__VA_ARGS__); \
} \
JNIEXPORT RETURN_TYPE \
Java_com_google_android_exoplayer2_ext_ffmpeg2_FfmpegDemuxer_##NAME( \
JNIEnv *env, jobject thiz, ##__VA_ARGS__)
#define VIDEO_DECODER_FUNC(RETURN_TYPE, NAME, ...) \
extern "C" { \
JNIEXPORT RETURN_TYPE \
Java_com_google_android_exoplayer2_ext_ffmpeg2_FfmpegVideoDecoder_##NAME( \
JNIEnv *env, jobject thiz, ##__VA_ARGS__); \
} \
JNIEXPORT RETURN_TYPE \
Java_com_google_android_exoplayer2_ext_ffmpeg2_FfmpegVideoDecoder_##NAME( \
JNIEnv *env, jobject thiz, ##__VA_ARGS__)
#define ERROR_STRING_BUFFER_LENGTH 256
#define MAX_FRAMES (32)
#define KEY_DECODING_PRIVATE_BASE (0x1000)
#define RESIZE_WIDTH (320)
// Output format corresponding to AudioFormat.ENCODING_PCM_16BIT.
static const AVSampleFormat OUTPUT_FORMAT_PCM_16BIT = AV_SAMPLE_FMT_S16;
// Output format corresponding to AudioFormat.ENCODING_PCM_FLOAT.
static const AVSampleFormat OUTPUT_FORMAT_PCM_FLOAT = AV_SAMPLE_FMT_FLT;
// LINT.IfChange
static const int AUDIO_DECODER_ERROR_INVALID_DATA = -1;
static const int AUDIO_DECODER_ERROR_OTHER = -2;
// LINT.ThenChange(../java/com/google/android/exoplayer2/ext/ffmpeg2/FfmpegAudioDecoder.java)
/**
* Returns the AVCodec with the specified name, or NULL if it is not available.
*/
AVCodec *getCodecByName(JNIEnv *env, jstring codecName);
/**
* Allocates and opens a new AVCodecContext for the specified codec, passing the
* provided extraData as initialization data for the decoder if it is non-NULL.
* Returns the created context.
*/
AVCodecContext *createContext(JNIEnv *env, AVCodec *codec, jbyteArray extraData,
jboolean outputFloat, jint rawSampleRate,
jint rawChannelCount);
/**
* Decodes the packet into the output buffer, returning the number of bytes
* written, or a negative AUDIO_DECODER_ERROR constant value in the case of an
* error.
*/
int decodePacket(AVCodecContext *context, AVPacket *packet,
uint8_t *outputBuffer, int outputSize);
/**
* Outputs a log message describing the avcodec error number.
*/
void logError(const char *functionName, int errorNumber);
/**
* Releases the specified context.
*/
void releaseContext(AVCodecContext *context);
int open_codec_context(int *stream_idx,
AVCodecContext **dec_ctx, AVFormatContext *fmt_ctx, enum AVMediaType type);
static JavaVM *jvm;
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
JNIEnv *env;
if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
jvm = vm;
av_register_all();
avcodec_register_all();
return JNI_VERSION_1_6;
}
LIBRARY_FUNC(jstring, ffmpegGetVersion) {
return env->NewStringUTF(LIBAVCODEC_IDENT);
}
LIBRARY_FUNC(jint, ffmpegGetInputBufferPaddingSize) {
return (jint) AV_INPUT_BUFFER_PADDING_SIZE;
}
LIBRARY_FUNC(jboolean, ffmpegHasDecoder, jstring codecName) {
return getCodecByName(env, codecName) != NULL;
}
AUDIO_DECODER_FUNC(jlong, ffmpegInitialize, jstring codecName,
jbyteArray extraData, jboolean outputFloat,
jint rawSampleRate, jint rawChannelCount) {
AVCodec *codec = getCodecByName(env, codecName);
if (!codec) {
LOGE("Codec not found.");
return 0L;
}
return (jlong) createContext(env, codec, extraData, outputFloat, rawSampleRate,
rawChannelCount);
}
AUDIO_DECODER_FUNC(jint, ffmpegDecode, jlong context, jobject inputData,
jint inputSize, jobject outputData, jint outputSize) {
if (!context) {
LOGE("Context must be non-NULL.");
return -1;
}
if (!inputData || !outputData) {
LOGE("Input and output buffers must be non-NULL.");
return -1;
}
if (inputSize < 0) {
LOGE("Invalid input buffer size: %d.", inputSize);
return -1;
}
if (outputSize < 0) {
LOGE("Invalid output buffer length: %d", outputSize);
return -1;
}
uint8_t *inputBuffer = (uint8_t *) env->GetDirectBufferAddress(inputData);
uint8_t *outputBuffer = (uint8_t *) env->GetDirectBufferAddress(outputData);
AVPacket packet;
av_init_packet(&packet);
packet.data = inputBuffer;
packet.size = inputSize;
return decodePacket((AVCodecContext *) context, &packet, outputBuffer,
outputSize);
}
AUDIO_DECODER_FUNC(jint, ffmpegGetChannelCount, jlong context) {
if (!context) {
LOGE("Context must be non-NULL.");
return -1;
}
return ((AVCodecContext *) context)->channels;
}
AUDIO_DECODER_FUNC(jint, ffmpegGetSampleRate, jlong context) {
if (!context) {
LOGE("Context must be non-NULL.");
return -1;
}
return ((AVCodecContext *) context)->sample_rate;
}
AUDIO_DECODER_FUNC(jlong, ffmpegReset, jlong jContext, jbyteArray extraData) {
AVCodecContext *context = (AVCodecContext *) jContext;
if (!context) {
LOGE("Tried to reset without a context.");
return 0L;
}
AVCodecID codecId = context->codec_id;
if (codecId == AV_CODEC_ID_TRUEHD) {
// Release and recreate the context if the codec is TrueHD.
// TODO: Figure out why flushing doesn't work for this codec.
releaseContext(context);
AVCodec *codec = avcodec_find_decoder(codecId);
if (!codec) {
LOGE("Unexpected error finding codec %d.", codecId);
return 0L;
}
jboolean outputFloat =
(jboolean) (context->request_sample_fmt == OUTPUT_FORMAT_PCM_FLOAT);
return (jlong) createContext(env, codec, extraData, outputFloat,
/* rawSampleRate= */ -1,
/* rawChannelCount= */ -1);
}
avcodec_flush_buffers(context);
return (jlong) context;
}
AUDIO_DECODER_FUNC(void, ffmpegRelease, jlong context) {
if (context) {
releaseContext((AVCodecContext *) context);
}
}
struct JniFrameBuffer {
friend class JniBufferManager;
//AVFrame* avFrame;
uint8_t *pointers[4];
int linesizes[4];
int width;
int height;
private:
int id;
int ref_count;
};
class JniBufferManager {
JniFrameBuffer *all_buffers[MAX_FRAMES];
int all_buffer_count = 0;
JniFrameBuffer *free_buffers[MAX_FRAMES];
int free_buffer_count = 0;
pthread_mutex_t mutex;
public:
JniBufferManager() { pthread_mutex_init(&mutex, NULL); }
~JniBufferManager() {
while (all_buffer_count--) {
if (all_buffers[all_buffer_count]->pointers[0] != NULL) {
av_freep(&all_buffers[all_buffer_count]->pointers[0]);
all_buffers[all_buffer_count]->pointers[0] = NULL;
}
}
}
int set_buffer(uint8_t *pointers[4], int linesizes[4], int w, int h) {
pthread_mutex_lock(&mutex);
JniFrameBuffer *out_buffer;
int ret = 0;
if (free_buffer_count) {
out_buffer = free_buffers[--free_buffer_count];
if (out_buffer->width != w || out_buffer->height != h) {
av_freep(&out_buffer->pointers[0]);
ret = av_image_alloc(out_buffer->pointers,
out_buffer->linesizes,
w,
h,
AV_PIX_FMT_YUV420P,
16);
out_buffer->width = w;
out_buffer->height = h;
}
} else {
out_buffer = new JniFrameBuffer();
out_buffer->id = all_buffer_count;
all_buffers[all_buffer_count++] = out_buffer;
out_buffer->width = w;
out_buffer->height = h;
//out_buffer->avFrame = av_frame_alloc();
ret =
av_image_alloc(out_buffer->pointers, out_buffer->linesizes, w, h, AV_PIX_FMT_YUV420P, 16);
}
int retVal = out_buffer->id;
if (ret < 0 || all_buffer_count >= MAX_FRAMES) {
LOGE("XXX JniBufferManager get_buffer OOM. all_buffer_count %d", all_buffer_count);
retVal = -1;
}
av_image_copy(out_buffer->pointers,
out_buffer->linesizes,
(const uint8_t **) pointers,
linesizes,
AV_PIX_FMT_YUV420P,
w,
h);
out_buffer->ref_count = 1;
pthread_mutex_unlock(&mutex);
return retVal;
}
JniFrameBuffer *get_buffer(int id) const {
if (id < 0 || id >= all_buffer_count) {
LOGE("JniBufferManager get_buffer invalid id %d.", id);
return NULL;
}
return all_buffers[id];
}
int release(int id) {
if (id < 0 || id >= all_buffer_count) {
LOGE("JniBufferManager release invalid id %d.", id);
return -1;
}
pthread_mutex_lock(&mutex);
JniFrameBuffer *buffer = all_buffers[id];
if (!buffer->ref_count) {
LOGE("JniBufferManager release, buffer already released.");
pthread_mutex_unlock(&mutex);
return -1;
}
if (!--buffer->ref_count) {
free_buffers[free_buffer_count++] = buffer;
}
pthread_mutex_unlock(&mutex);
return 0;
}
};
struct FfmpegCodec {
int stream_type;
AVCodecContext *dec_ctx; // libavcodec.a
int stream_idx;
bool needDecodingAudio;
struct SwsContext *img_convert_ctx;
AVFrame *convertFrame;
};
struct FFMKVDecoderImpl {
AVFormatContext *fmt_ctx; // libavformat.a
FfmpegCodec **codecs;
int video_stream_idx;
int audio_stream_idx;
AVPacket pkt;
jclass ffmpegPacketClass;
jmethodID ffmepgPacketSetMethod;
jclass ffmpegCustomIoClass;
jfieldID ffmpegCustomIoByteBuffer;
jmethodID ffmepgCustomIoReadMethod;
jmethodID ffmepgCustomIoSeekMethod;
jobject ffCustomIoObject;
uint8_t *tempBuffer;
uint8_t *pcmBuffer;
int pcmBufferSize;
JniBufferManager *bufferManager;
jmethodID initForYuvFrame;
jmethodID initForPrivateFrame;
jfieldID dataField;
jfieldID decoderPrivateField;
ANativeWindow *native_window;
jobject surface;
int width;
int height;
};
static int readForCustomIo(void *ptr, uint8_t *buffer, int bufferLength) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) ptr;
if (pImpl == NULL) {
return -1;
}
if (bufferLength == 0)
return 0;
int size = bufferLength > OUTPUT_BUFFER_SIZE ? OUTPUT_BUFFER_SIZE : bufferLength;
JNIEnv *env;
jvm->AttachCurrentThread(&env, NULL);
long readSize =
env->CallLongMethod(pImpl->ffCustomIoObject, pImpl->ffmepgCustomIoReadMethod, size);
if (readSize > 0) {
jobject
byteBuffer = env->GetObjectField(pImpl->ffCustomIoObject, pImpl->ffmpegCustomIoByteBuffer);
uint8_t *pt = (uint8_t *) env->GetDirectBufferAddress(byteBuffer);
memcpy(buffer, pt, (int) readSize);
}
return readSize;
}
static int64_t seekForCustomIo(void *ptr, int64_t pos, int whence) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) ptr;
if (pImpl == NULL) {
return -1;
}
JNIEnv *env;
jvm->AttachCurrentThread(&env, NULL);
jlong ret = env->CallLongMethod(pImpl->ffCustomIoObject,
pImpl->ffmepgCustomIoSeekMethod,
(jlong) pos,
(jint) whence);
return ret;
}
FFMKVDecoderImpl *createFFMKVDecoderImpl(JNIEnv *env, jobject customIo) {
FFMKVDecoderImpl *pImpl = new FFMKVDecoderImpl;
memset(pImpl, 0, sizeof(FFMKVDecoderImpl));
pImpl->bufferManager = new JniBufferManager();
pImpl->ffmpegPacketClass =
env->FindClass("com/google/android/exoplayer2/ext/ffmpeg2/FfmpegPacket");
pImpl->ffmepgPacketSetMethod =
env->GetMethodID(pImpl->ffmpegPacketClass, "set", "(ILjava/nio/ByteBuffer;JJI)V");
if (customIo != NULL) {
pImpl->ffCustomIoObject = env->NewGlobalRef(customIo);
pImpl->ffmpegCustomIoClass = env->GetObjectClass(pImpl->ffCustomIoObject);
pImpl->ffmpegCustomIoByteBuffer =
env->GetFieldID(pImpl->ffmpegCustomIoClass, "byteBuffer", "Ljava/nio/ByteBuffer;");
pImpl->ffmepgCustomIoReadMethod = env->GetMethodID(pImpl->ffmpegCustomIoClass, "read", "(I)J");
pImpl->ffmepgCustomIoSeekMethod = env->GetMethodID(pImpl->ffmpegCustomIoClass, "seek", "(JI)J");
pImpl->tempBuffer = (uint8_t *) av_malloc(OUTPUT_BUFFER_SIZE);
memset(pImpl->tempBuffer, 0, OUTPUT_BUFFER_SIZE);
}
pImpl->video_stream_idx = -1;
pImpl->audio_stream_idx = -1;
const jclass outputBufferClass = env->FindClass(
"com/google/android/exoplayer2/video/VideoDecoderOutputBuffer");
pImpl->initForYuvFrame = env->GetMethodID(outputBufferClass, "initForYuvFrame",
"(IIIII)Z");
pImpl->initForPrivateFrame =
env->GetMethodID(outputBufferClass, "initForPrivateFrame", "(II)V");
pImpl->dataField = env->GetFieldID(outputBufferClass, "data",
"Ljava/nio/ByteBuffer;");
pImpl->decoderPrivateField =
env->GetFieldID(outputBufferClass, "decoderPrivate", "I");
pImpl->native_window = NULL;
pImpl->surface = NULL;
// pImpl->needDecodingAudio = false;
pImpl->pcmBuffer = (uint8_t *) av_malloc(OUTPUT_BUFFER_SIZE);
pImpl->pcmBufferSize = OUTPUT_BUFFER_SIZE;
memset(pImpl->pcmBuffer, 0, pImpl->pcmBufferSize);
av_init_packet(&pImpl->pkt);
return pImpl;
}
FFMPEG_DEMUXER_FUNC(long, FfmpegDemuxerOpen, jstring path) {
FFMKVDecoderImpl *pImpl = createFFMKVDecoderImpl(env, NULL);
const char *pathChars = env->GetStringUTFChars(path, NULL);
if (avformat_open_input(&pImpl->fmt_ctx, pathChars, NULL, NULL) < 0) {
LOGE ("Could not open source file %s", pathChars);
env->ReleaseStringUTFChars(path, pathChars);
free(pImpl);
return 0;
}
env->ReleaseStringUTFChars(path, pathChars);
if (avformat_find_stream_info(pImpl->fmt_ctx, NULL) < 0) {
LOGE ("Could not find stream information");
avformat_close_input(&pImpl->fmt_ctx);
free(pImpl);
return 0;
}
pImpl->codecs = (FfmpegCodec **) av_malloc(pImpl->fmt_ctx->nb_streams * sizeof(FfmpegCodec));
memset(pImpl->codecs, 0, pImpl->fmt_ctx->nb_streams * sizeof(FfmpegCodec));
for (int i = 0; i < pImpl->fmt_ctx->nb_streams; i++) {
pImpl->codecs[i] = (FfmpegCodec *) av_malloc(sizeof(FfmpegCodec));
memset(pImpl->codecs[i], 0, sizeof(FfmpegCodec));
}
for (int i = 0; i < pImpl->fmt_ctx->nb_streams; i++) {
pImpl->codecs[i]->stream_type = -1;
}
return (jlong) pImpl;
}
FFMPEG_DEMUXER_FUNC(jlong, FfmpegDemuxerCustomOpen, jobject customIo) {
FFMKVDecoderImpl *pImpl = createFFMKVDecoderImpl(env, customIo);
long readLength = readForCustomIo(pImpl, pImpl->tempBuffer, OUTPUT_BUFFER_SIZE);
seekForCustomIo(pImpl, 0, SEEK_SET);
AVProbeData probeData;
probeData.buf = pImpl->tempBuffer; // Buffer must have AVPROBE_PADDING_SIZE.
probeData.buf_size = readLength;
probeData.filename = "";
pImpl->fmt_ctx = avformat_alloc_context();
AVIOContext *customIoCtx = avio_alloc_context(pImpl->tempBuffer,
readLength,
0,
pImpl,
readForCustomIo,
NULL,
seekForCustomIo);
pImpl->fmt_ctx->pb = customIoCtx;
pImpl->fmt_ctx->iformat = av_probe_input_format(&probeData, 1);
pImpl->fmt_ctx->flags = AVFMT_FLAG_CUSTOM_IO;
if (avformat_open_input(&pImpl->fmt_ctx, "", NULL, NULL) < 0) {
LOGE ("Could not open custom source file");
if (pImpl->fmt_ctx != NULL) {
avformat_free_context(pImpl->fmt_ctx);
}
free(pImpl);
return 0;
}
if (avformat_find_stream_info(pImpl->fmt_ctx, NULL) < 0) {
LOGE ("Could not find stream information");
avformat_close_input(&pImpl->fmt_ctx);
free(pImpl);
return 0;
}
pImpl->codecs = (FfmpegCodec **) av_malloc(pImpl->fmt_ctx->nb_streams * sizeof(FfmpegCodec));
memset(pImpl->codecs, 0, pImpl->fmt_ctx->nb_streams * sizeof(FfmpegCodec));
for (int i = 0; i < pImpl->fmt_ctx->nb_streams; i++) {
pImpl->codecs[i] = (FfmpegCodec *) av_malloc(sizeof(FfmpegCodec));
memset(pImpl->codecs[i], 0, sizeof(FfmpegCodec));
}
for (int i = 0; i < pImpl->fmt_ctx->nb_streams; i++) {
pImpl->codecs[i]->stream_type = -1;
}
return (jlong) pImpl;
}
FFMPEG_DEMUXER_FUNC(jint, FfmpegDemuxerGetStreamCount, jlong context) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) context;
if (pImpl == NULL)
return 0;
return pImpl->fmt_ctx->nb_streams;
}
FFMPEG_DEMUXER_FUNC(jint, FfmpegDemuxerGetStreamType, jlong context, jint index) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) context;
if (pImpl == NULL)
return 0;
return pImpl->fmt_ctx->streams[index]->codec->codec_type;
}
FFMPEG_DEMUXER_FUNC(jint, FfmpegDemuxerOpenStream, jlong context, jint index) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) context;
if (pImpl == NULL)
return -1;
int ret = 0;
AVDictionary *opts = NULL;
AVStream *st = pImpl->fmt_ctx->streams[index];
/* find decoder for the stream */
AVCodec *codec = avcodec_find_decoder(st->codecpar->codec_id);
if (!codec) {
LOGE("Failed to find %s codec\n",
av_get_media_type_string(pImpl->fmt_ctx->streams[index]->codec->codec_type));
return AVERROR(EINVAL);
}
/* Allocate a codec context for the decoder */
AVCodecContext *codecContext = avcodec_alloc_context3(codec);
if (!codecContext) {
LOGE("Failed to allocate the %s codec context\n",
av_get_media_type_string(pImpl->fmt_ctx->streams[index]->codec->codec_type));
return AVERROR(ENOMEM);
}
/* Copy codec parameters from input stream to output codec context */
if ((ret = avcodec_parameters_to_context(codecContext, st->codecpar)) < 0) {
LOGE("Failed to copy %s codec parameters to decoder context\n",
av_get_media_type_string(pImpl->fmt_ctx->streams[index]->codec->codec_type));
return ret;
}
/* Init the decoders */
if ((ret = avcodec_open2(codecContext, codec, &opts)) < 0) {
LOGE("Failed to open %s codec\n",
av_get_media_type_string(pImpl->fmt_ctx->streams[index]->codec->codec_type));
return ret;
}
pImpl->codecs[index]->dec_ctx = codecContext;
pImpl->codecs[index]->stream_idx = index;
pImpl->codecs[index]->stream_type = pImpl->fmt_ctx->streams[index]->codec->codec_type;
pImpl->codecs[index]->img_convert_ctx = NULL;
if (pImpl->fmt_ctx->streams[index]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
if (pImpl->video_stream_idx < 0) {
pImpl->video_stream_idx = index; // use only seek index
}
AVCodecContext *avCodecContext = pImpl->fmt_ctx->streams[index]->codec;
bool formatMiss = avCodecContext->pix_fmt != AV_PIX_FMT_YUV420P;
bool sizeMiss =
avCodecContext->bits_per_raw_sample != 0 && avCodecContext->bits_per_raw_sample != 8;
if (formatMiss || sizeMiss) {
int resizeHeight = avCodecContext->height * RESIZE_WIDTH / avCodecContext->width;
resizeHeight = (resizeHeight + 1) / 2 * 2;
pImpl->codecs[index]->img_convert_ctx =
sws_getCachedContext(pImpl->codecs[index]->img_convert_ctx,
avCodecContext->width, avCodecContext->height,
avCodecContext->pix_fmt, RESIZE_WIDTH, resizeHeight,
AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
pImpl->codecs[index]->convertFrame = av_frame_alloc();
av_image_alloc(pImpl->codecs[index]->convertFrame->data,
pImpl->codecs[index]->convertFrame->linesize,
RESIZE_WIDTH,
resizeHeight,
AV_PIX_FMT_YUV420P,
16);
pImpl->codecs[index]->convertFrame->width = RESIZE_WIDTH;
pImpl->codecs[index]->convertFrame->height = resizeHeight;
} else {
pImpl->codecs[index]->img_convert_ctx = NULL;
}
} else if (pImpl->fmt_ctx->streams[index]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
if (pImpl->audio_stream_idx < 0) {
pImpl->audio_stream_idx = index; // use only seek index
}
switch (codecContext->codec_id) {
case AV_CODEC_ID_AAC:
break;
default:
pImpl->codecs[index]->needDecodingAudio = true;
codecContext->request_sample_fmt = OUTPUT_FORMAT_PCM_16BIT;
break;
}
}
return ret;
}
FFMPEG_DEMUXER_FUNC(jlong, FfmpegDemuxerGetDuration, jlong context) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) context;
if (pImpl == NULL)
return -1;
return pImpl->fmt_ctx->duration;
}
FFMPEG_DEMUXER_FUNC(jstring, FfmpegDemuxerGetCodecId, jlong context, jint index) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) context;
if (pImpl == NULL)
return env->NewStringUTF("Unknown");
return env->NewStringUTF(avcodec_get_name(pImpl->codecs[index]->dec_ctx->codec_id));
}
FFMPEG_DEMUXER_FUNC(jint, FfmpegDemuxerGetAudioChannelCount, jlong context, jint index) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) context;
if (pImpl == NULL)
return 0;
return av_get_channel_layout_nb_channels(pImpl->codecs[index]->dec_ctx->channel_layout);
}
FFMPEG_DEMUXER_FUNC(jint, FfmpegDemuxerGetAudioSampleRate, jlong context, jint index) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) context;
if (pImpl == NULL)
return 0;
return pImpl->codecs[index]->dec_ctx->sample_rate;
}
FFMPEG_DEMUXER_FUNC(jint, FfmpegDemuxerGetVideoWidth, jlong context, jint index) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) context;
if (pImpl == NULL)
return 0;
return pImpl->codecs[index]->dec_ctx->width;
}
FFMPEG_DEMUXER_FUNC(jint, FfmpegDemuxerGetVideoHeight, jlong context, jint index) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) context;
if (pImpl == NULL)
return 0;
return pImpl->codecs[index]->dec_ctx->height;
}
static size_t GetSizeWidth(size_t x) {
size_t n = 1;
while (x > 127) {
++n;
x >>= 7;
}
return n;
}
static uint8_t *EncodeSize(uint8_t *dst, size_t x) {
while (x > 127) {
*dst++ = (x & 0x7f) | 0x80;
x >>= 7;
}
*dst++ = x;
return dst;
}
FFMPEG_DEMUXER_FUNC(jbyteArray, FfmpegDemuxerGetExtraData, jlong context, jint index) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) context;
if (pImpl == NULL)
return env->NewByteArray(0);
int count = 0;
if (pImpl->codecs[index]->dec_ctx->codec_id == AV_CODEC_ID_MPEG4
&& pImpl->codecs[index]->dec_ctx->extradata_size <= 0) {
jbyteArray ret = NULL;
while(true) {
int result = av_read_frame(pImpl->fmt_ctx, &pImpl->pkt);
if (result < 0) {
avformat_seek_file(pImpl->fmt_ctx,
index, INT64_MIN, 0, INT64_MAX, 0);
return env->NewByteArray(0);
}
size_t i = 0;
bool found = false;
while (i + 3 < pImpl->pkt.size) {
if (!memcmp("\x00\x00\x01\xb6",
pImpl->pkt.data + i, 4)) {
found = true;
break;
}
++i;
}
if (!found) {
av_free_packet(&pImpl->pkt);
if (count++ < 100) {
continue;
} else {
avformat_seek_file(pImpl->fmt_ctx,
index, INT64_MIN, 0, INT64_MAX, 0);
return env->NewByteArray(0);
}
}
ret = env->NewByteArray(i);
env->SetByteArrayRegion(ret,
0,
i,
(jbyte *)pImpl->pkt.data);
av_free_packet(&pImpl->pkt);
break;
}
avformat_seek_file(pImpl->fmt_ctx,
index, INT64_MIN, 0, INT64_MAX, 0);
if (ret == NULL) {
return env->NewByteArray(0);
}
return ret;
}
jbyteArray ret = env->NewByteArray(pImpl->codecs[index]->dec_ctx->extradata_size);
env->SetByteArrayRegion(ret,
0,
pImpl->codecs[index]->dec_ctx->extradata_size,
(jbyte *) pImpl->codecs[index]->dec_ctx->extradata);
return ret;
}
FfmpegCodec *getFfmpegCodec(FFMKVDecoderImpl *pImpl, int stream_index) {
return pImpl->codecs[stream_index];
}
FFMPEG_DEMUXER_FUNC(jint, FfmpegDemuxerReadPacket, jlong context, jobject ffmpegPacket) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) context;
if (pImpl == NULL)
return -1;
int ret = av_read_frame(pImpl->fmt_ctx, &pImpl->pkt);
if (ret < 0)
return ret;
AVPacket *pkt = &pImpl->pkt;
jlong pts = TIME_UNSET;
jlong dts = TIME_UNSET;
FfmpegCodec *ffmpegCodec = getFfmpegCodec(pImpl, pkt->stream_index);
switch (ffmpegCodec->stream_type) {
case AVMEDIA_TYPE_VIDEO: {
// jbyteArray data = env->NewByteArray(pkt->size);
// env->SetByteArrayRegion (data, 0, pkt->size, (jbyte *)pkt->data);
jobject data = env->NewDirectByteBuffer(pkt->data, pkt->size);
if (pkt->pts != AV_NOPTS_VALUE) {
pts = pkt->pts
* (av_q2d(pImpl->fmt_ctx->streams[pkt->stream_index]->time_base) * AV_TIME_BASE);
}
if (pkt->dts != AV_NOPTS_VALUE) {
dts = pkt->dts
* (av_q2d(pImpl->fmt_ctx->streams[pkt->stream_index]->time_base) * AV_TIME_BASE);
}
env->CallVoidMethod(ffmpegPacket,
pImpl->ffmepgPacketSetMethod,
pkt->stream_index,
data,
pts,
dts,
pkt->flags);
av_packet_unref(&pImpl->pkt);
}
break;
case AVMEDIA_TYPE_AUDIO: {
if (pkt->pts != AV_NOPTS_VALUE) {
pts = pkt->pts
* (av_q2d(pImpl->fmt_ctx->streams[pkt->stream_index]->time_base) * AV_TIME_BASE);
}
if (pkt->pts != AV_NOPTS_VALUE) {
dts = pkt->dts
* (av_q2d(pImpl->fmt_ctx->streams[pkt->stream_index]->time_base) * AV_TIME_BASE);
}
if (ffmpegCodec->needDecodingAudio) {
int outSize =
decodePacket(ffmpegCodec->dec_ctx, pkt, pImpl->pcmBuffer, pImpl->pcmBufferSize);
if (outSize > 0) {
// jbyteArray data = env->NewByteArray(outSize);
// env->SetByteArrayRegion (data, 0, outSize, (jbyte *) pImpl->pcmBuffer);
jobject data = env->NewDirectByteBuffer(pImpl->pcmBuffer, outSize);
env->CallVoidMethod(ffmpegPacket,
pImpl->ffmepgPacketSetMethod,
pkt->stream_index,
data,
pts,
dts,
pkt->flags);
} else {
ret = outSize;
}
} else {
// jbyteArray data = env->NewByteArray(pkt->size);
// env->SetByteArrayRegion (data, 0, pkt->size, (jbyte *)pkt->data);
jobject data = env->NewDirectByteBuffer(pkt->data, pkt->size);
env->CallVoidMethod(ffmpegPacket,
pImpl->ffmepgPacketSetMethod,
pkt->stream_index,
data,
pts,
dts,
pkt->flags);
av_packet_unref(&pImpl->pkt);
}
}
break;
case AVMEDIA_TYPE_UNKNOWN:
ret = -1;
break;
}
return ret;
}
FFMPEG_DEMUXER_FUNC(jint, FfmpegDemuxerSeekTo, jlong context, jlong seekTimeUs) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) context;
if (pImpl == NULL)
return -1;
int64_t seek_target = seekTimeUs;
if (pImpl->video_stream_idx >= 0) {
seek_target = av_rescale_q(seek_target, AV_TIME_BASE_Q,
pImpl->fmt_ctx->streams[pImpl->video_stream_idx]->time_base);
int error = avformat_seek_file(pImpl->fmt_ctx,
pImpl->video_stream_idx, INT64_MIN, seek_target, INT64_MAX, 0);
return error;
} else if (pImpl->audio_stream_idx >= 0) {
seek_target = av_rescale_q(seek_target, AV_TIME_BASE_Q,
pImpl->fmt_ctx->streams[pImpl->audio_stream_idx]->time_base);
int error = avformat_seek_file(pImpl->fmt_ctx,
pImpl->audio_stream_idx, INT64_MIN, seek_target, INT64_MAX, 0);
return error;
}
return -1;
}
FFMPEG_DEMUXER_FUNC(long, FfmpegDemuxerClose, jlong context) {
if (context) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) context;
if (pImpl->fmt_ctx != NULL) {
if (pImpl->codecs != NULL) {
for (int i = 0; i < pImpl->fmt_ctx->nb_streams; i++) {
if (pImpl->codecs[i] != NULL) {
if (pImpl->codecs[i]->dec_ctx != NULL) {
avcodec_free_context(&pImpl->codecs[i]->dec_ctx);
av_free(pImpl->codecs[i]);
}
if (pImpl->codecs[i]->img_convert_ctx != NULL) {
sws_freeContext(pImpl->codecs[i]->img_convert_ctx);
}
if (pImpl->codecs[i]->convertFrame != NULL) {
av_freep(&pImpl->codecs[i]->convertFrame->data[0]);
av_frame_free(&pImpl->codecs[i]->convertFrame);
}
}
}
}
avformat_close_input(&pImpl->fmt_ctx);
}
if (pImpl->ffCustomIoObject != NULL) {
env->DeleteGlobalRef(pImpl->ffCustomIoObject);
}
if (pImpl->pcmBuffer != NULL) {
av_free(pImpl->pcmBuffer);
}
if (pImpl->tempBuffer != NULL) {
av_free(pImpl->tempBuffer);
}
if (pImpl->bufferManager != NULL) {
free(pImpl->bufferManager);
}
delete pImpl;
}
}
VIDEO_DECODER_FUNC(jint,
FfmpegDecode,
jlong context,
jint streamIndex,
jobject encodedData,
jint length) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) context;
if (pImpl == NULL)
return -1;
uint8_t *inputBuffer = (uint8_t *) env->GetDirectBufferAddress(encodedData);
AVPacket packet;
av_init_packet(&packet);
packet.data = inputBuffer;
packet.size = length;
packet.stream_index = streamIndex;
int result = 0;
// Queue input data.
result = avcodec_send_packet(pImpl->codecs[streamIndex]->dec_ctx, &packet);
if (result) {
logError("avcodec_send_packet", result);
return result == AVERROR_INVALIDDATA ? AUDIO_DECODER_ERROR_INVALID_DATA
: AUDIO_DECODER_ERROR_OTHER;
}
return result;
}
VIDEO_DECODER_FUNC(jint,
FfmpegGetFrame,
jlong context,
jint streamIndex,
jobject jOutputBuffer,
jint outputMode) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) context;
if (pImpl == NULL)
return -1;
bool haveVideo = false;
int ret = 0;
while (ret >= 0) {
AVFrame *avFrame = NULL;
JniFrameBuffer *jfb = NULL;
AVFrame *outFrame = NULL;
avFrame = av_frame_alloc();
ret = avcodec_receive_frame(pImpl->codecs[streamIndex]->dec_ctx, avFrame);
if (ret < 0) {
// those two return values are special and mean there is no output
// frame available, but there were no errors during decoding
av_frame_free(&avFrame);
if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
return haveVideo ? 0 : FFMPEG_DECODE_ONLY;
LOGE ("Error during decoding (%s)\n", av_err2str(ret));
return ret;
}
haveVideo = true;
if (pImpl->codecs[streamIndex]->img_convert_ctx != NULL) {
// AVPicture avPicture;
int result =
sws_scale(pImpl->codecs[streamIndex]->img_convert_ctx,
avFrame->data,
avFrame->linesize,
0,
avFrame->height,
pImpl->codecs[streamIndex]->convertFrame->data,
pImpl->codecs[streamIndex]->convertFrame->linesize);
av_frame_free(&avFrame);
outFrame = pImpl->codecs[streamIndex]->convertFrame;
} else {
outFrame = avFrame;
}
if (outputMode == 0) { // kOutputModeYuv
jboolean initResult = env->CallBooleanMethod(
jOutputBuffer, pImpl->initForYuvFrame, outFrame->width, outFrame->height,
outFrame->linesize[0], outFrame->linesize[1], 0/*kColorspaceUnknown*/);
if (env->ExceptionCheck() || !initResult) {
return -1;
}
const jobject dataObject = env->GetObjectField(jOutputBuffer, pImpl->dataField);
jbyte *const data = reinterpret_cast<jbyte *>(env->GetDirectBufferAddress(dataObject));
const int32_t uvHeight = (outFrame->height + 1) / 2;
const uint64_t yLength = outFrame->linesize[0] * outFrame->height;
const uint64_t uLength = outFrame->linesize[1] * uvHeight;
const uint64_t vLength = outFrame->linesize[2] * uvHeight;
// TODO: This copy can be eliminated by using external frame
// buffers. This is insignificant for smaller videos but takes ~1.5ms
// for 1080p clips. So this should eventually be gotten rid of.
memcpy(data, outFrame->data[0], yLength);
memcpy(data + yLength, outFrame->data[1], uLength);
memcpy(data + yLength + uLength, outFrame->data[2], vLength);
av_frame_free(&outFrame);
} else if (outputMode == 1) { // kOutputModeSurfaceYuv
int frameId = pImpl->bufferManager->set_buffer(outFrame->data,
outFrame->linesize,
outFrame->width,
outFrame->height);
if (frameId < 0) {
return -1;
}
env->CallVoidMethod(jOutputBuffer,
pImpl->initForPrivateFrame,
outFrame->width,
outFrame->height);
if (pImpl->codecs[streamIndex]->img_convert_ctx == NULL) {
av_frame_free(&outFrame);
}
if (env->ExceptionCheck()) {
return -1;
}
env->SetIntField(jOutputBuffer, pImpl->decoderPrivateField,
frameId + KEY_DECODING_PRIVATE_BASE);
}
}
return 0;
}
static void acquire_native_window(FFMKVDecoderImpl *pImpl, JNIEnv *env, jobject new_surface) {
if (pImpl->surface != new_surface) {
if (pImpl->native_window) {
ANativeWindow_release(pImpl->native_window);
}
pImpl->native_window = ANativeWindow_fromSurface(env, new_surface);
pImpl->surface = new_surface;
}
}
constexpr int AlignTo16(int value) { return (value + 15) & (~15); }
VIDEO_DECODER_FUNC(jint,
FfmpegRenderFrame,
jlong context,
jint streamIndex,
jobject jSurface,
jobject jOutputBuffer) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) context;
if (pImpl == NULL)
return -1;
const int
id = env->GetIntField(jOutputBuffer, pImpl->decoderPrivateField) - KEY_DECODING_PRIVATE_BASE;
if (id < 0) {
return -1;
}
JniFrameBuffer *srcBuffer = pImpl->bufferManager->get_buffer(id);
if (srcBuffer == NULL)
return -1;
acquire_native_window(pImpl, env, jSurface);
if (pImpl->native_window == NULL || !srcBuffer) {
return 1;
}
static const int kImageFormatYV12 = 0x32315659;
if (pImpl->width != srcBuffer->width || pImpl->height != srcBuffer->height) {
ANativeWindow_setBuffersGeometry(pImpl->native_window, srcBuffer->width,
srcBuffer->height, kImageFormatYV12);
pImpl->width = srcBuffer->width;
pImpl->height = srcBuffer->height;
}
ANativeWindow_Buffer buffer;
int result = ANativeWindow_lock(pImpl->native_window, &buffer, NULL);
if (buffer.bits == NULL || result) {
return -1;
}
// Y
const size_t src_y_stride = srcBuffer->linesizes[0];
int stride = srcBuffer->width;
const uint8_t *src_base = srcBuffer->pointers[0];
uint8_t *dest_base = (uint8_t *) buffer.bits;
for (int y = 0; y < srcBuffer->height; y++) {
memcpy(dest_base, src_base, stride);
src_base += src_y_stride;
dest_base += buffer.stride;
}
const int y_plane_size =
buffer.stride * buffer.height;
const int32_t native_window_buffer_uv_height =
(buffer.height + 1) / 2;
const int native_window_buffer_uv_stride =
AlignTo16(buffer.stride / 2);
int harfHeight = srcBuffer->height / 2;
const int v_plane_height =
native_window_buffer_uv_height > harfHeight ? harfHeight : native_window_buffer_uv_height;
const uint8_t *src_base_v = srcBuffer->pointers[2];
uint8_t *dest_v_base = (uint8_t *) buffer.bits + y_plane_size;
for (int y = 0; y < v_plane_height; y++) {
memcpy(dest_v_base, src_base_v, stride);
src_base_v += srcBuffer->linesizes[2];
dest_v_base += native_window_buffer_uv_stride;
}
const int v_plane_size = v_plane_height * native_window_buffer_uv_stride;
uint8_t *dest_u_base = (uint8_t *) buffer.bits + y_plane_size + v_plane_size;
const uint8_t *src_base_u = srcBuffer->pointers[1];
for (int y = 0; y < v_plane_height; y++) {
memcpy(dest_u_base, src_base_u, stride);
src_base_u += srcBuffer->linesizes[1];
dest_u_base += native_window_buffer_uv_stride;
}
return ANativeWindow_unlockAndPost(pImpl->native_window);
}
VIDEO_DECODER_FUNC(void,
FfmpegReleaseFrame,
jlong context,
jint streamIndex,
jobject jOutputBuffer) {
FFMKVDecoderImpl *pImpl = (FFMKVDecoderImpl *) context;
if (pImpl == NULL)
return;
const int
id = env->GetIntField(jOutputBuffer, pImpl->decoderPrivateField) - KEY_DECODING_PRIVATE_BASE;
env->SetIntField(jOutputBuffer, pImpl->decoderPrivateField, -1);
pImpl->bufferManager->release(id);
}
AVCodec *getCodecByName(JNIEnv *env, jstring codecName) {
if (!codecName) {
return NULL;
}
const char *codecNameChars = env->GetStringUTFChars(codecName, NULL);
AVCodec *codec = avcodec_find_decoder_by_name(codecNameChars);
env->ReleaseStringUTFChars(codecName, codecNameChars);
return codec;
}
AVCodecContext *createContext(JNIEnv *env, AVCodec *codec, jbyteArray extraData,
jboolean outputFloat, jint rawSampleRate,
jint rawChannelCount) {
AVCodecContext *context = avcodec_alloc_context3(codec);
if (!context) {
LOGE("Failed to allocate context.");
return NULL;
}
context->request_sample_fmt =
outputFloat ? OUTPUT_FORMAT_PCM_FLOAT : OUTPUT_FORMAT_PCM_16BIT;
if (extraData) {
jsize size = env->GetArrayLength(extraData);
context->extradata_size = size;
context->extradata =
(uint8_t *) av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
if (!context->extradata) {
LOGE("Failed to allocate extradata.");
releaseContext(context);
return NULL;
}
env->GetByteArrayRegion(extraData, 0, size, (jbyte *) context->extradata);
}
if (context->codec_id == AV_CODEC_ID_PCM_MULAW ||
context->codec_id == AV_CODEC_ID_PCM_ALAW) {
context->sample_rate = rawSampleRate;
context->channels = rawChannelCount;
context->channel_layout = av_get_default_channel_layout(rawChannelCount);
}
context->err_recognition = AV_EF_IGNORE_ERR;
int result = avcodec_open2(context, codec, NULL);
if (result < 0) {
logError("avcodec_open2", result);
releaseContext(context);
return NULL;
}
return context;
}
int decodePacket(AVCodecContext *context, AVPacket *packet,
uint8_t *outputBuffer, int outputSize) {
int result = 0;
// Queue input data.
result = avcodec_send_packet(context, packet);
if (result) {
logError("avcodec_send_packet", result);
return result == AVERROR_INVALIDDATA ? AUDIO_DECODER_ERROR_INVALID_DATA
: AUDIO_DECODER_ERROR_OTHER;
}
// Dequeue output data until it runs out.
int outSize = 0;
while (true) {
AVFrame *frame = av_frame_alloc();
if (!frame) {
LOGE("Failed to allocate output frame.");
return -1;
}
result = avcodec_receive_frame(context, frame);
if (result) {
av_frame_free(&frame);
if (result == AVERROR(EAGAIN)) {
break;
}
logError("avcodec_receive_frame", result);
return result;
}
// Resample output.
AVSampleFormat sampleFormat = context->sample_fmt;
int channelCount = context->channels;
int channelLayout = context->channel_layout;
int sampleRate = context->sample_rate;
int sampleCount = frame->nb_samples;
int dataSize = av_samples_get_buffer_size(NULL, channelCount, sampleCount,
sampleFormat, 1);
SwrContext *resampleContext;
if (context->opaque) {
resampleContext = (SwrContext *) context->opaque;
} else {
resampleContext = swr_alloc();
av_opt_set_int(resampleContext, "in_channel_layout", channelLayout, 0);
av_opt_set_int(resampleContext, "out_channel_layout", channelLayout, 0);
av_opt_set_int(resampleContext, "in_sample_rate", sampleRate, 0);
av_opt_set_int(resampleContext, "out_sample_rate", sampleRate, 0);
av_opt_set_int(resampleContext, "in_sample_fmt", sampleFormat, 0);
// The output format is always the requested format.
av_opt_set_int(resampleContext, "out_sample_fmt",
context->request_sample_fmt, 0);
result = swr_init(resampleContext);
if (result < 0) {
logError("swr_init", result);
av_frame_free(&frame);
return -1;
}
context->opaque = resampleContext;
}
int inSampleSize = av_get_bytes_per_sample(sampleFormat);
int outSampleSize = av_get_bytes_per_sample(context->request_sample_fmt);
int outSamples = swr_get_out_samples(resampleContext, sampleCount);
int bufferOutSize = outSampleSize * channelCount * outSamples;
if (outSize + bufferOutSize > outputSize) {
LOGE("Output buffer size (%d) too small for output data (%d).",
outputSize, outSize + bufferOutSize);
av_frame_free(&frame);
return -1;
}
result = swr_convert(resampleContext, &outputBuffer, bufferOutSize,
(const uint8_t **) frame->data, frame->nb_samples);
av_frame_free(&frame);
if (result < 0) {
logError("swr_convert", result);
return result;
}
int available = swr_get_out_samples(resampleContext, 0);
if (available != 0) {
LOGE("Expected no samples remaining after resampling, but found %d.",
available);
return -1;
}
outputBuffer += bufferOutSize;
outSize += bufferOutSize;
}
return outSize;
}
void logError(const char *functionName, int errorNumber) {
char *buffer = (char *) malloc(ERROR_STRING_BUFFER_LENGTH * sizeof(char));
av_strerror(errorNumber, buffer, ERROR_STRING_BUFFER_LENGTH);
LOGE("Error in %s: %s", functionName, buffer);
free(buffer);
}
void releaseContext(AVCodecContext *context) {
if (!context) {
return;
}
SwrContext *swrContext;
if ((swrContext = (SwrContext *) context->opaque)) {
swr_free(&swrContext);
context->opaque = NULL;
}
avcodec_free_context(&context);
}
int open_codec_context(int *stream_idx,
AVCodecContext **dec_ctx, AVFormatContext *fmt_ctx, enum AVMediaType type) {
int ret, stream_index;
AVStream *st;
AVCodec *dec = NULL;
AVDictionary *opts = NULL;
ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
if (ret < 0) {
LOGE("Could not find %s stream'\n",
av_get_media_type_string(type));
return ret;
} else {
stream_index = ret;
st = fmt_ctx->streams[stream_index];
/* find decoder for the stream */
dec = avcodec_find_decoder(st->codecpar->codec_id);
if (!dec) {
LOGE("Failed to find %s codec\n",
av_get_media_type_string(type));
return AVERROR(EINVAL);
}
/* Allocate a codec context for the decoder */
*dec_ctx = avcodec_alloc_context3(dec);
if (!*dec_ctx) {
LOGE("Failed to allocate the %s codec context\n",
av_get_media_type_string(type));
return AVERROR(ENOMEM);
}
/* Copy codec parameters from input stream to output codec context */
if ((ret = avcodec_parameters_to_context(*dec_ctx, st->codecpar)) < 0) {
LOGE("Failed to copy %s codec parameters to decoder context\n",
av_get_media_type_string(type));
return ret;
}
/* Init the decoders */
if ((ret = avcodec_open2(*dec_ctx, dec, &opts)) < 0) {
LOGE("Failed to open %s codec\n",
av_get_media_type_string(type));
return ret;
}
*stream_idx = stream_index;
}
return 0;
}
|
#include <Magick++.h>
#include <napi.h>
#include <list>
using namespace std;
using namespace Magick;
Napi::Value Trump(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
try {
Napi::Object obj = info[0].As<Napi::Object>();
Napi::Buffer<char> data = obj.Get("data").As<Napi::Buffer<char>>();
string type = obj.Get("type").As<Napi::String>().Utf8Value();
int delay =
obj.Has("delay") ? obj.Get("delay").As<Napi::Number>().Int32Value() : 0;
Blob blob;
list<Image> frames;
list<Image> coalesced;
list<Image> mid;
Image watermark;
readImages(&frames, Blob(data.Data(), data.Length()));
watermark.read("./assets/images/trump.png");
coalesceImages(&coalesced, frames.begin(), frames.end());
for (Image &image : coalesced) {
Image watermark_new = watermark;
image.virtualPixelMethod(Magick::TransparentVirtualPixelMethod);
image.backgroundColor("none");
image.scale(Geometry("365x179!"));
double arguments[16] = {0, 0, 207, 268, 365, 0, 548, 271,
365, 179, 558, 450, 0, 179, 193, 450};
image.distort(Magick::PerspectiveDistortion, 16, arguments, true);
image.extent(Geometry("800x450"), Magick::CenterGravity);
watermark_new.composite(image, Geometry("-25+134"),
Magick::DstOverCompositeOp);
watermark_new.magick(type);
watermark_new.animationDelay(delay == 0 ? image.animationDelay() : delay);
watermark_new.gifDisposeMethod(Magick::BackgroundDispose);
mid.push_back(watermark_new);
}
optimizeTransparency(mid.begin(), mid.end());
if (type == "gif") {
for (Image &image : mid) {
image.quantizeDitherMethod(FloydSteinbergDitherMethod);
image.quantize();
}
}
writeImages(mid.begin(), mid.end(), &blob);
Napi::Object result = Napi::Object::New(env);
result.Set("data", Napi::Buffer<char>::Copy(env, (char *)blob.data(),
blob.length()));
result.Set("type", type);
return result;
} catch (Napi::Error const &err) {
throw err;
} catch (std::exception const &err) {
throw Napi::Error::New(env, err.what());
} catch (...) {
throw Napi::Error::New(env, "Unknown error");
}
}
|
//
// CPXOPF.cpp
// Gravity
//
// Created by Hassan Hijazi on Nov 17 2018
//
//
#include <stdio.h>
#include <PowerNet.h>
#include <gravity/solver.h>
using namespace std;
using namespace gravity;
int main (int argc, char * argv[])
{
string fname = string(prj_dir)+"/data_sets/Power/nesta_case5_pjm.m", mtype = "polar";
int output = 0;
bool relax = false;
double tol = 1e-6;
string log_level="0";
/** Read user options */
auto options = readOptions(argc, argv);
options.add_option("f", "file", "Input file name (def. ../../data_sets/Power/nesta_case5_pjm.m)", fname );
options.add_option("m", "model", "Complex Number Model: polar/rect (def. polar)", mtype );
/** parse the options and verify that all went well. If not, errors and help will be shown */
bool correct_parsing = options.parse_options(argc, argv);
if(!correct_parsing){
return EXIT_FAILURE;
}
fname = options["f"];
mtype = options["m"];
output = op::str2int(options["l"]);
bool has_help = op::str2bool(options["h"]);
/** show help */
if(has_help) {
options.show_help();
exit(0);
}
/* Start timer */
auto total_time_start = get_wall_time();
/* Construct Grid **/
PowerNet grid;
grid.readgrid(fname);
/** Sets */
auto nodes = indices(grid.nodes);
auto arcs = indices(grid.arcs);
auto gens = indices(grid.gens);
auto gen_nodes = grid.gens_per_node();
auto out_arcs = grid.out_arcs_per_node();
auto in_arcs = grid.in_arcs_per_node();
/* Grid Parameters */
unsigned nb_gen = grid.get_nb_active_gens();
unsigned nb_lines = grid.get_nb_active_arcs();
unsigned nb_buses = grid.get_nb_active_nodes();
/* Line properties */
auto Y = grid.Y.in(arcs);
/* Line charging */
auto Ych = grid.Ych.in(arcs);
/* Line limit */
auto S_max = grid.S_max.in(arcs);
/* Tap ratio */
auto T = grid.T.in(arcs);
/* Bus shunt */
auto Ysh = grid.Ysh.in(nodes);
/* Power Demand */
auto Sd = grid.Sd.in(nodes);
/* Generation Bounds */
auto Sg_min = grid.Sg_min.in(gens);
auto Sg_max = grid.Sg_max.in(gens);
/* Voltage Bounds */
auto V_min = grid.V_min.in(nodes);
auto V_max = grid.V_max.in(nodes);
/* Phase angle Bounds */
auto th_min = grid.th_min.in(arcs);
auto th_max = grid.th_max.in(arcs);
/* Generators' costs */
auto c0 = grid.c0.in(gens);
auto c1 = grid.c1.in(gens);
auto c2 = grid.c2.in(gens);
/* Reference Bus */
auto ref_bus = grid.ref_bus;
DebugOn("nb gens = " << nb_gen << endl);
DebugOn("nb lines = " << nb_lines << endl);
DebugOn("nb buses = " << nb_buses << endl);
PowerModelType pmt = ACPOL;
if(mtype=="rect") pmt = ACRECT;
bool polar = (pmt==ACPOL);
if (polar) {
DebugOn("Using polar model\n");
}
else {
DebugOn("Using rectangular model\n");
}
Model<Cpx> CPXOPF("CPX-OPF Model");
/** Variables */
/* Power generation variables */
var<Cpx> Sg("Sg", Sg_min, Sg_max);
CPXOPF.add(Sg.in(gens));
/* Power flow variables */
var<Cpx> S_from("S_from", -1*S_max,S_max);
var<Cpx> S_to("S_to", -1*S_max,S_max);
CPXOPF.add(S_from.in(arcs),S_to.in(arcs));
/** Voltage variables */
var<Cpx> V("V", V_min, V_max);
CPXOPF.add(V.in(nodes));
auto V_from = V.from(arcs);
auto V_to = V.to(arcs);
/** Construct the objective function */
auto obj = c1.tr()*real(Sg) + c2.tr()*pow(real(Sg),2) + sum(c0);
CPXOPF.min(obj);
/** Define constraints */
/* Ref Bus */
Constraint<Cpx> Ref_Bus("Ref_Bus");
Ref_Bus = imag(V)(ref_bus);
CPXOPF.add(Ref_Bus == 0);
/** KCL Flow conservation */
Constraint<Cpx> KCL("KCL");
KCL = sum(S_from, out_arcs) + sum(S_to, in_arcs) + Sd - sum(Sg, gen_nodes) + conj(Ysh)*sqrmag(V);
CPXOPF.add(KCL.in(nodes) == 0);
/** AC Power Flows */
Constraint<Cpx> Flow_From("Flow_From");
Flow_From = S_from - ((conj(Y)+conj(Ych))/sqrmag(T))*sqrmag(V_from) + (conj(Y)/T)*V_from*conj(V_to);
CPXOPF.add(Flow_From.in(arcs)==0);
Constraint<Cpx> Flow_To("Flow_To");
Flow_To = S_to - (conj(Y)+conj(Ych))*sqrmag(V_to) + (conj(Y)/conj(T))*conj(V_from)*V_to;
CPXOPF.add(Flow_To.in(arcs)==0);
/* Phase Angle Bounds constraints */
auto bus_pairs = grid.get_bus_pairs();
Constraint<Cpx> PAD_UB("PAD_UB");
PAD_UB = ang(V.from(bus_pairs)) - ang(V.to(bus_pairs));
PAD_UB -= th_max;
CPXOPF.add(PAD_UB.in(bus_pairs) <= 0);
Constraint<Cpx> PAD_LB("PAD_LB");
PAD_LB = ang(V.from(bus_pairs)) - ang(V.to(bus_pairs));
PAD_LB -= th_min;
CPXOPF.add(PAD_LB.in(bus_pairs) >= 0);
/* Thermal Limit Constraints */
Constraint<Cpx> Thermal_Limit_from("Thermal_Limit_from");
Thermal_Limit_from = sqrmag(S_from) - pow(S_max, 2);
CPXOPF.add(Thermal_Limit_from.in(arcs) <= 0);
Constraint<Cpx> Thermal_Limit_to("Thermal_Limit_to");
Thermal_Limit_to = sqrmag(S_to) - pow(S_max,2);
CPXOPF.add(Thermal_Limit_to.in(arcs) <= 0);
CPXOPF.print_symbolic();
CPXOPF.print();
return 0;
// solver<Cpx> OPF(CPXOPF,ipopt);
auto solver_time_start = get_wall_time();
// OPF.run(output, tol = 1e-6);
auto solver_time_end = get_wall_time();
auto total_time_end = get_wall_time();
auto solve_time = solver_time_end - solver_time_start;
auto total_time = total_time_end - total_time_start;
/* Uncomment line below to print expanded model */
/* CPXOPF.print(); */
/** Terminal output **/
string out = "DATA_OPF, " + grid._name + ", " + to_string(nb_buses) + ", " + to_string(nb_lines) +", " + to_string(CPXOPF.get_obj_val().real()) + ", " + to_string(-numeric_limits<double>::infinity()) + ", " + to_string(solve_time) + ", LocalOptimal, " + to_string(total_time);
DebugOn(out <<endl);
return 0;
}
|
/*
* gravity_compensation_node.cpp
*
* Created on: Nov 12, 2013
* Authors: Francisco Viña
* fevb <at> kth.se
*/
/* Copyright (c) 2013, Francisco Viña, CVAP, KTH
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of KTH nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL KTH BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <gravity_compensation/gravity_compensation.h>
#include <gravity_compensation/gravity_compensation_params.h>
#include <sensor_msgs/Imu.h>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Geometry>
#include <tf_conversions/tf_eigen.h>
#include <tf/transform_datatypes.h>
#include <tf/transform_broadcaster.h>
#include <eigen_conversions/eigen_msg.h>
#include <boost/thread.hpp>
class GravityCompensationNode
{
public:
ros::NodeHandle n_;
// subscribe to accelerometer (imu) readings
ros::Subscriber topicSub_imu_;
ros::Subscriber topicSub_ft_raw_;
ros::Publisher topicPub_ft_zeroed_;
ros::Publisher topicPub_ft_compensated_;
tf::TransformBroadcaster tf_br_;
GravityCompensationNode()
{
n_ = ros::NodeHandle("~");
m_g_comp_params = new GravityCompensationParams();
m_g_comp = NULL;
m_received_imu = false;
// subscribe to accelerometer topic and raw F/T sensor topic
topicSub_imu_ = n_.subscribe("imu", 1, &GravityCompensationNode::topicCallback_imu, this);
topicSub_ft_raw_ = n_.subscribe("ft_raw", 1, &GravityCompensationNode::topicCallback_ft_raw, this);
/// implementation of topics to publish
std::string ns;
if(n_.hasParam("ns"))
{
n_.getParam("ns", ns);
topicPub_ft_zeroed_ = n_.advertise<geometry_msgs::WrenchStamped> (ns+std::string("/ft_zeroed"), 1);
topicPub_ft_compensated_ = n_.advertise<geometry_msgs::WrenchStamped> (ns+std::string("/ft_compensated"), 1);
}
else
{
topicPub_ft_zeroed_ = n_.advertise<geometry_msgs::WrenchStamped> ("ft_zeroed", 1);
topicPub_ft_compensated_ = n_.advertise<geometry_msgs::WrenchStamped> ("ft_compensated", 1);
}
}
~GravityCompensationNode()
{
delete m_g_comp;
delete m_g_comp_params;
}
bool getROSParameters()
{
/// Get F/T sensor bias
XmlRpc::XmlRpcValue biasXmlRpc;
Eigen::Matrix<double, 6, 1> bias;
if (n_.hasParam("bias"))
{
n_.getParam("bias", biasXmlRpc);
}
else
{
ROS_ERROR("Parameter 'bias' not set, shutting down node...");
n_.shutdown();
return false;
}
if(biasXmlRpc.size()!=6)
{
ROS_ERROR("Invalid F/T bias parameter size (should be size 6), shutting down node");
n_.shutdown();
return false;
}
for (int i = 0; i < biasXmlRpc.size(); i++)
{
bias(i) = (double)biasXmlRpc[i];
}
// get the mass of the gripper
double gripper_mass;
if (n_.hasParam("gripper_mass"))
{
n_.getParam("gripper_mass", gripper_mass);
}
else
{
ROS_ERROR("Parameter 'gripper_mass' not available");
n_.shutdown();
return false;
}
if(gripper_mass<0.0)
{
ROS_ERROR("Parameter 'gripper_mass' < 0");
n_.shutdown();
return false;
}
// get the pose of the COM of the gripper
// we assume that it is fixed with respect to FT sensor frame
// first get the frame ID
tf::StampedTransform gripper_com;
std::string gripper_com_frame_id;
if (n_.hasParam("gripper_com_frame_id"))
{
n_.getParam("gripper_com_frame_id", gripper_com_frame_id);
}
else
{
ROS_ERROR("Parameter 'gripper_com_frame_id' not available");
n_.shutdown();
return false;
}
gripper_com.frame_id_ = gripper_com_frame_id;
// now get the CHILD frame ID
std::string gripper_com_child_frame_id;
if (n_.hasParam("gripper_com_child_frame_id"))
{
n_.getParam("gripper_com_child_frame_id", gripper_com_child_frame_id);
}
else
{
ROS_ERROR("Parameter 'gripper_com_child_frame_id' not available");
n_.shutdown();
return false;
}
gripper_com.child_frame_id_ = gripper_com_child_frame_id;
// now get the actual gripper COM pose
Eigen::Matrix<double, 6, 1> gripper_com_pose;
XmlRpc::XmlRpcValue gripper_com_pose_XmlRpc;
if (n_.hasParam("gripper_com_pose"))
{
n_.getParam("gripper_com_pose", gripper_com_pose_XmlRpc);
}
else
{
ROS_ERROR("Parameter 'gripper_com_pose' not set, shutting down node...");
n_.shutdown();
return false;
}
if(gripper_com_pose_XmlRpc.size()!=6)
{
ROS_ERROR("Invalid 'gripper_com_pose' parameter size (should be size 6), shutting down node");
n_.shutdown();
return false;
}
for(unsigned int i=0; i<gripper_com_pose_XmlRpc.size(); i++)
{
gripper_com_pose(i) = gripper_com_pose_XmlRpc[i];
}
tf::Vector3 p;
tf::vectorEigenToTF(gripper_com_pose.topRows(3), p);
tf::Quaternion q;
q.setRPY((double)gripper_com_pose(3),
(double)gripper_com_pose(4),
(double)gripper_com_pose(5));
gripper_com = tf::StampedTransform(tf::Transform(q, p),
ros::Time::now(),
gripper_com_frame_id,
gripper_com_child_frame_id);
// get the publish frequency for the gripper
// center of mass tf
n_.param("gripper_com_broadcast_frequency",
m_gripper_com_broadcast_frequency, 100.0);
m_g_comp_params->setBias(bias);
m_g_comp_params->setGripperMass(gripper_mass);
m_g_comp_params->setGripperCOM(gripper_com);
m_g_comp = new GravityCompensation(m_g_comp_params);
return true;
}
void topicCallback_imu(const sensor_msgs::Imu::ConstPtr &msg)
{
m_imu = *msg;
m_received_imu = true;
}
void topicCallback_ft_raw(const geometry_msgs::WrenchStamped::ConstPtr &msg)
{
static int error_msg_count=0;
if(!m_received_imu)
{
return;
}
if((ros::Time::now()-m_imu.header.stamp).toSec() > 0.1)
{
error_msg_count++;
if(error_msg_count % 10==0)
ROS_ERROR("Imu reading too old, not able to g-compensate ft measurement");
return;
}
geometry_msgs::WrenchStamped ft_zeroed;
m_g_comp->Zero(*msg, ft_zeroed);
topicPub_ft_zeroed_.publish(ft_zeroed);
geometry_msgs::WrenchStamped ft_compensated;
m_g_comp->Compensate(ft_zeroed, m_imu, ft_compensated);
topicPub_ft_compensated_.publish(ft_compensated);
}
// thread function for publishing the gripper center of mass transform
void publish_gripper_com_tf()
{
static ros::Rate gripper_com_broadcast_rate(m_gripper_com_broadcast_frequency);
try
{
while(ros::ok())
{
tf::StampedTransform gripper_com = m_g_comp_params->getGripperCOM();
gripper_com.stamp_ = ros::Time::now();
tf_br_.sendTransform(gripper_com);
gripper_com_broadcast_rate.sleep();
}
}
catch(boost::thread_interrupted&)
{
return;
}
}
private:
GravityCompensationParams *m_g_comp_params;
GravityCompensation *m_g_comp;
sensor_msgs::Imu m_imu;
bool m_received_imu;
double m_gripper_com_broadcast_frequency;
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "gravity_compensation");
GravityCompensationNode g_comp_node;
if(!g_comp_node.getROSParameters())
{
ROS_ERROR("Error getting ROS parameters");
return 0;
}
// loop frequency
double loop_rate_;
g_comp_node.n_.param("loop_rate", loop_rate_, 1000.0);
ros::Rate loop_rate(loop_rate_);
// add a thread for publishing the gripper COM transform frame
boost::thread t_tf(boost::bind(&GravityCompensationNode::publish_gripper_com_tf, &g_comp_node));
// ros::AsyncSpinner s(2);
// s.start();
while(ros::ok())
{
ros::spinOnce();
loop_rate.sleep();
}
t_tf.join();
return 0;
}
|
//===- InputFiles.cpp -----------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "InputFiles.h"
#include "Chunks.h"
#include "Config.h"
#include "DebugTypes.h"
#include "Driver.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "lld/Common/DWARF.h"
#include "lld/Common/ErrorHandler.h"
#include "lld/Common/Memory.h"
#include "llvm-c/lto.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/Twine.h"
#include "llvm/BinaryFormat/COFF.h"
#include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
#include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
#include "llvm/LTO/LTO.h"
#include "llvm/Object/Binary.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Target/TargetOptions.h"
#include <cstring>
#include <system_error>
#include <utility>
using namespace llvm;
using namespace llvm::COFF;
using namespace llvm::codeview;
using namespace llvm::object;
using namespace llvm::support::endian;
using llvm::Triple;
using llvm::support::ulittle32_t;
namespace lld {
// Returns the last element of a path, which is supposed to be a filename.
static StringRef getBasename(StringRef path) {
return sys::path::filename(path, sys::path::Style::windows);
}
// Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
std::string toString(const coff::InputFile *file) {
if (!file)
return "<internal>";
if (file->parentName.empty() || file->kind() == coff::InputFile::ImportKind)
return file->getName();
return (getBasename(file->parentName) + "(" + getBasename(file->getName()) +
")")
.str();
}
namespace coff {
std::vector<ObjFile *> ObjFile::instances;
std::vector<ImportFile *> ImportFile::instances;
std::vector<BitcodeFile *> BitcodeFile::instances;
/// Checks that Source is compatible with being a weak alias to Target.
/// If Source is Undefined and has no weak alias set, makes it a weak
/// alias to Target.
static void checkAndSetWeakAlias(SymbolTable *symtab, InputFile *f,
Symbol *source, Symbol *target) {
if (auto *u = dyn_cast<Undefined>(source)) {
if (u->weakAlias && u->weakAlias != target) {
// Weak aliases as produced by GCC are named in the form
// .weak.<weaksymbol>.<othersymbol>, where <othersymbol> is the name
// of another symbol emitted near the weak symbol.
// Just use the definition from the first object file that defined
// this weak symbol.
if (config->mingw)
return;
symtab->reportDuplicate(source, f);
}
u->weakAlias = target;
}
}
static bool ignoredSymbolName(StringRef name) {
return name == "@feat.00" || name == "@comp.id";
}
ArchiveFile::ArchiveFile(MemoryBufferRef m) : InputFile(ArchiveKind, m) {}
void ArchiveFile::parse() {
// Parse a MemoryBufferRef as an archive file.
file = CHECK(Archive::create(mb), this);
// Read the symbol table to construct Lazy objects.
for (const Archive::Symbol &sym : file->symbols())
symtab->addLazyArchive(this, sym);
}
// Returns a buffer pointing to a member file containing a given symbol.
void ArchiveFile::addMember(const Archive::Symbol &sym) {
const Archive::Child &c =
CHECK(sym.getMember(),
"could not get the member for symbol " + toCOFFString(sym));
// Return an empty buffer if we have already returned the same buffer.
if (!seen.insert(c.getChildOffset()).second)
return;
driver->enqueueArchiveMember(c, sym, getName());
}
std::vector<MemoryBufferRef> getArchiveMembers(Archive *file) {
std::vector<MemoryBufferRef> v;
Error err = Error::success();
for (const ErrorOr<Archive::Child> &cOrErr : file->children(err)) {
Archive::Child c =
CHECK(cOrErr,
file->getFileName() + ": could not get the child of the archive");
MemoryBufferRef mbref =
CHECK(c.getMemoryBufferRef(),
file->getFileName() +
": could not get the buffer for a child of the archive");
v.push_back(mbref);
}
if (err)
fatal(file->getFileName() +
": Archive::children failed: " + toString(std::move(err)));
return v;
}
void LazyObjFile::fetch() {
if (mb.getBuffer().empty())
return;
InputFile *file;
if (isBitcode(mb))
file = make<BitcodeFile>(mb, "", 0, std::move(symbols));
else
file = make<ObjFile>(mb, std::move(symbols));
mb = {};
symtab->addFile(file);
}
void LazyObjFile::parse() {
if (isBitcode(this->mb)) {
// Bitcode file.
std::unique_ptr<lto::InputFile> obj =
CHECK(lto::InputFile::create(this->mb), this);
for (const lto::InputFile::Symbol &sym : obj->symbols()) {
if (!sym.isUndefined())
symtab->addLazyObject(this, sym.getName());
}
return;
}
// Native object file.
std::unique_ptr<Binary> coffObjPtr = CHECK(createBinary(mb), this);
COFFObjectFile *coffObj = cast<COFFObjectFile>(coffObjPtr.get());
uint32_t numSymbols = coffObj->getNumberOfSymbols();
for (uint32_t i = 0; i < numSymbols; ++i) {
COFFSymbolRef coffSym = check(coffObj->getSymbol(i));
if (coffSym.isUndefined() || !coffSym.isExternal() ||
coffSym.isWeakExternal())
continue;
StringRef name;
coffObj->getSymbolName(coffSym, name);
if (coffSym.isAbsolute() && ignoredSymbolName(name))
continue;
symtab->addLazyObject(this, name);
i += coffSym.getNumberOfAuxSymbols();
}
}
void ObjFile::parse() {
// Parse a memory buffer as a COFF file.
std::unique_ptr<Binary> bin = CHECK(createBinary(mb), this);
if (auto *obj = dyn_cast<COFFObjectFile>(bin.get())) {
bin.release();
coffObj.reset(obj);
} else {
fatal(toString(this) + " is not a COFF file");
}
// Read section and symbol tables.
initializeChunks();
initializeSymbols();
initializeFlags();
initializeDependencies();
}
const coff_section* ObjFile::getSection(uint32_t i) {
const coff_section *sec;
if (auto ec = coffObj->getSection(i, sec))
fatal("getSection failed: #" + Twine(i) + ": " + ec.message());
return sec;
}
// We set SectionChunk pointers in the SparseChunks vector to this value
// temporarily to mark comdat sections as having an unknown resolution. As we
// walk the object file's symbol table, once we visit either a leader symbol or
// an associative section definition together with the parent comdat's leader,
// we set the pointer to either nullptr (to mark the section as discarded) or a
// valid SectionChunk for that section.
static SectionChunk *const pendingComdat = reinterpret_cast<SectionChunk *>(1);
void ObjFile::initializeChunks() {
uint32_t numSections = coffObj->getNumberOfSections();
chunks.reserve(numSections);
sparseChunks.resize(numSections + 1);
for (uint32_t i = 1; i < numSections + 1; ++i) {
const coff_section *sec = getSection(i);
if (sec->Characteristics & IMAGE_SCN_LNK_COMDAT)
sparseChunks[i] = pendingComdat;
else
sparseChunks[i] = readSection(i, nullptr, "");
}
}
SectionChunk *ObjFile::readSection(uint32_t sectionNumber,
const coff_aux_section_definition *def,
StringRef leaderName) {
const coff_section *sec = getSection(sectionNumber);
StringRef name;
if (Expected<StringRef> e = coffObj->getSectionName(sec))
name = *e;
else
fatal("getSectionName failed: #" + Twine(sectionNumber) + ": " +
toString(e.takeError()));
if (name == ".drectve") {
ArrayRef<uint8_t> data;
cantFail(coffObj->getSectionContents(sec, data));
directives = StringRef((const char *)data.data(), data.size());
return nullptr;
}
if (name == ".llvm_addrsig") {
addrsigSec = sec;
return nullptr;
}
// Object files may have DWARF debug info or MS CodeView debug info
// (or both).
//
// DWARF sections don't need any special handling from the perspective
// of the linker; they are just a data section containing relocations.
// We can just link them to complete debug info.
//
// CodeView needs linker support. We need to interpret debug info,
// and then write it to a separate .pdb file.
// Ignore DWARF debug info unless /debug is given.
if (!config->debug && name.startswith(".debug_"))
return nullptr;
if (sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
return nullptr;
auto *c = make<SectionChunk>(this, sec);
if (def)
c->checksum = def->CheckSum;
// CodeView sections are stored to a different vector because they are not
// linked in the regular manner.
if (c->isCodeView())
debugChunks.push_back(c);
else if (name == ".gfids$y")
guardFidChunks.push_back(c);
else if (name == ".gljmp$y")
guardLJmpChunks.push_back(c);
else if (name == ".sxdata")
sXDataChunks.push_back(c);
else if (config->tailMerge && sec->NumberOfRelocations == 0 &&
name == ".rdata" && leaderName.startswith("??_C@"))
// COFF sections that look like string literal sections (i.e. no
// relocations, in .rdata, leader symbol name matches the MSVC name mangling
// for string literals) are subject to string tail merging.
MergeChunk::addSection(c);
else if (name == ".rsrc" || name.startswith(".rsrc$"))
resourceChunks.push_back(c);
else
chunks.push_back(c);
return c;
}
void ObjFile::includeResourceChunks() {
chunks.insert(chunks.end(), resourceChunks.begin(), resourceChunks.end());
}
void ObjFile::readAssociativeDefinition(
COFFSymbolRef sym, const coff_aux_section_definition *def) {
readAssociativeDefinition(sym, def, def->getNumber(sym.isBigObj()));
}
void ObjFile::readAssociativeDefinition(COFFSymbolRef sym,
const coff_aux_section_definition *def,
uint32_t parentIndex) {
SectionChunk *parent = sparseChunks[parentIndex];
int32_t sectionNumber = sym.getSectionNumber();
auto diag = [&]() {
StringRef name, parentName;
coffObj->getSymbolName(sym, name);
const coff_section *parentSec = getSection(parentIndex);
if (Expected<StringRef> e = coffObj->getSectionName(parentSec))
parentName = *e;
error(toString(this) + ": associative comdat " + name + " (sec " +
Twine(sectionNumber) + ") has invalid reference to section " +
parentName + " (sec " + Twine(parentIndex) + ")");
};
if (parent == pendingComdat) {
// This can happen if an associative comdat refers to another associative
// comdat that appears after it (invalid per COFF spec) or to a section
// without any symbols.
diag();
return;
}
// Check whether the parent is prevailing. If it is, so are we, and we read
// the section; otherwise mark it as discarded.
if (parent) {
SectionChunk *c = readSection(sectionNumber, def, "");
sparseChunks[sectionNumber] = c;
if (c) {
c->selection = IMAGE_COMDAT_SELECT_ASSOCIATIVE;
parent->addAssociative(c);
}
} else {
sparseChunks[sectionNumber] = nullptr;
}
}
void ObjFile::recordPrevailingSymbolForMingw(
COFFSymbolRef sym, DenseMap<StringRef, uint32_t> &prevailingSectionMap) {
// For comdat symbols in executable sections, where this is the copy
// of the section chunk we actually include instead of discarding it,
// add the symbol to a map to allow using it for implicitly
// associating .[px]data$<func> sections to it.
int32_t sectionNumber = sym.getSectionNumber();
SectionChunk *sc = sparseChunks[sectionNumber];
if (sc && sc->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE) {
StringRef name;
coffObj->getSymbolName(sym, name);
if (getMachineType() == I386)
name.consume_front("_");
prevailingSectionMap[name] = sectionNumber;
}
}
void ObjFile::maybeAssociateSEHForMingw(
COFFSymbolRef sym, const coff_aux_section_definition *def,
const DenseMap<StringRef, uint32_t> &prevailingSectionMap) {
StringRef name;
coffObj->getSymbolName(sym, name);
if (name.consume_front(".pdata$") || name.consume_front(".xdata$") ||
name.consume_front(".eh_frame$")) {
// For MinGW, treat .[px]data$<func> and .eh_frame$<func> as implicitly
// associative to the symbol <func>.
auto parentSym = prevailingSectionMap.find(name);
if (parentSym != prevailingSectionMap.end())
readAssociativeDefinition(sym, def, parentSym->second);
}
}
Symbol *ObjFile::createRegular(COFFSymbolRef sym) {
SectionChunk *sc = sparseChunks[sym.getSectionNumber()];
if (sym.isExternal()) {
StringRef name;
coffObj->getSymbolName(sym, name);
if (sc)
return symtab->addRegular(this, name, sym.getGeneric(), sc,
sym.getValue());
// For MinGW symbols named .weak.* that point to a discarded section,
// don't create an Undefined symbol. If nothing ever refers to the symbol,
// everything should be fine. If something actually refers to the symbol
// (e.g. the undefined weak alias), linking will fail due to undefined
// references at the end.
if (config->mingw && name.startswith(".weak."))
return nullptr;
return symtab->addUndefined(name, this, false);
}
if (sc)
return make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,
/*IsExternal*/ false, sym.getGeneric(), sc);
return nullptr;
}
void ObjFile::initializeSymbols() {
uint32_t numSymbols = coffObj->getNumberOfSymbols();
symbols.resize(numSymbols);
SmallVector<std::pair<Symbol *, uint32_t>, 8> weakAliases;
std::vector<uint32_t> pendingIndexes;
pendingIndexes.reserve(numSymbols);
DenseMap<StringRef, uint32_t> prevailingSectionMap;
std::vector<const coff_aux_section_definition *> comdatDefs(
coffObj->getNumberOfSections() + 1);
for (uint32_t i = 0; i < numSymbols; ++i) {
COFFSymbolRef coffSym = check(coffObj->getSymbol(i));
bool prevailingComdat;
if (coffSym.isUndefined()) {
symbols[i] = createUndefined(coffSym);
} else if (coffSym.isWeakExternal()) {
symbols[i] = createUndefined(coffSym);
uint32_t tagIndex = coffSym.getAux<coff_aux_weak_external>()->TagIndex;
weakAliases.emplace_back(symbols[i], tagIndex);
} else if (Optional<Symbol *> optSym =
createDefined(coffSym, comdatDefs, prevailingComdat)) {
symbols[i] = *optSym;
if (config->mingw && prevailingComdat)
recordPrevailingSymbolForMingw(coffSym, prevailingSectionMap);
} else {
// createDefined() returns None if a symbol belongs to a section that
// was pending at the point when the symbol was read. This can happen in
// two cases:
// 1) section definition symbol for a comdat leader;
// 2) symbol belongs to a comdat section associated with another section.
// In both of these cases, we can expect the section to be resolved by
// the time we finish visiting the remaining symbols in the symbol
// table. So we postpone the handling of this symbol until that time.
pendingIndexes.push_back(i);
}
i += coffSym.getNumberOfAuxSymbols();
}
for (uint32_t i : pendingIndexes) {
COFFSymbolRef sym = check(coffObj->getSymbol(i));
if (const coff_aux_section_definition *def = sym.getSectionDefinition()) {
if (def->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
readAssociativeDefinition(sym, def);
else if (config->mingw)
maybeAssociateSEHForMingw(sym, def, prevailingSectionMap);
}
if (sparseChunks[sym.getSectionNumber()] == pendingComdat) {
StringRef name;
coffObj->getSymbolName(sym, name);
log("comdat section " + name +
" without leader and unassociated, discarding");
continue;
}
symbols[i] = createRegular(sym);
}
for (auto &kv : weakAliases) {
Symbol *sym = kv.first;
uint32_t idx = kv.second;
checkAndSetWeakAlias(symtab, this, sym, symbols[idx]);
}
}
Symbol *ObjFile::createUndefined(COFFSymbolRef sym) {
StringRef name;
coffObj->getSymbolName(sym, name);
return symtab->addUndefined(name, this, sym.isWeakExternal());
}
void ObjFile::handleComdatSelection(COFFSymbolRef sym, COMDATType &selection,
bool &prevailing, DefinedRegular *leader) {
if (prevailing)
return;
// There's already an existing comdat for this symbol: `Leader`.
// Use the comdats's selection field to determine if the new
// symbol in `Sym` should be discarded, produce a duplicate symbol
// error, etc.
SectionChunk *leaderChunk = nullptr;
COMDATType leaderSelection = IMAGE_COMDAT_SELECT_ANY;
if (leader->data) {
leaderChunk = leader->getChunk();
leaderSelection = leaderChunk->selection;
} else {
// FIXME: comdats from LTO files don't know their selection; treat them
// as "any".
selection = leaderSelection;
}
if ((selection == IMAGE_COMDAT_SELECT_ANY &&
leaderSelection == IMAGE_COMDAT_SELECT_LARGEST) ||
(selection == IMAGE_COMDAT_SELECT_LARGEST &&
leaderSelection == IMAGE_COMDAT_SELECT_ANY)) {
// cl.exe picks "any" for vftables when building with /GR- and
// "largest" when building with /GR. To be able to link object files
// compiled with each flag, "any" and "largest" are merged as "largest".
leaderSelection = selection = IMAGE_COMDAT_SELECT_LARGEST;
}
// Other than that, comdat selections must match. This is a bit more
// strict than link.exe which allows merging "any" and "largest" if "any"
// is the first symbol the linker sees, and it allows merging "largest"
// with everything (!) if "largest" is the first symbol the linker sees.
// Making this symmetric independent of which selection is seen first
// seems better though.
// (This behavior matches ModuleLinker::getComdatResult().)
if (selection != leaderSelection) {
log(("conflicting comdat type for " + toString(*leader) + ": " +
Twine((int)leaderSelection) + " in " + toString(leader->getFile()) +
" and " + Twine((int)selection) + " in " + toString(this))
.str());
symtab->reportDuplicate(leader, this);
return;
}
switch (selection) {
case IMAGE_COMDAT_SELECT_NODUPLICATES:
symtab->reportDuplicate(leader, this);
break;
case IMAGE_COMDAT_SELECT_ANY:
// Nothing to do.
break;
case IMAGE_COMDAT_SELECT_SAME_SIZE:
if (leaderChunk->getSize() != getSection(sym)->SizeOfRawData)
symtab->reportDuplicate(leader, this);
break;
case IMAGE_COMDAT_SELECT_EXACT_MATCH: {
SectionChunk newChunk(this, getSection(sym));
// link.exe only compares section contents here and doesn't complain
// if the two comdat sections have e.g. different alignment.
// Match that.
if (leaderChunk->getContents() != newChunk.getContents())
symtab->reportDuplicate(leader, this, &newChunk, sym.getValue());
break;
}
case IMAGE_COMDAT_SELECT_ASSOCIATIVE:
// createDefined() is never called for IMAGE_COMDAT_SELECT_ASSOCIATIVE.
// (This means lld-link doesn't produce duplicate symbol errors for
// associative comdats while link.exe does, but associate comdats
// are never extern in practice.)
llvm_unreachable("createDefined not called for associative comdats");
case IMAGE_COMDAT_SELECT_LARGEST:
if (leaderChunk->getSize() < getSection(sym)->SizeOfRawData) {
// Replace the existing comdat symbol with the new one.
StringRef name;
coffObj->getSymbolName(sym, name);
// FIXME: This is incorrect: With /opt:noref, the previous sections
// make it into the final executable as well. Correct handling would
// be to undo reading of the whole old section that's being replaced,
// or doing one pass that determines what the final largest comdat
// is for all IMAGE_COMDAT_SELECT_LARGEST comdats and then reading
// only the largest one.
replaceSymbol<DefinedRegular>(leader, this, name, /*IsCOMDAT*/ true,
/*IsExternal*/ true, sym.getGeneric(),
nullptr);
prevailing = true;
}
break;
case IMAGE_COMDAT_SELECT_NEWEST:
llvm_unreachable("should have been rejected earlier");
}
}
Optional<Symbol *> ObjFile::createDefined(
COFFSymbolRef sym,
std::vector<const coff_aux_section_definition *> &comdatDefs,
bool &prevailing) {
prevailing = false;
auto getName = [&]() {
StringRef s;
coffObj->getSymbolName(sym, s);
return s;
};
if (sym.isCommon()) {
auto *c = make<CommonChunk>(sym);
chunks.push_back(c);
return symtab->addCommon(this, getName(), sym.getValue(), sym.getGeneric(),
c);
}
if (sym.isAbsolute()) {
StringRef name = getName();
if (name == "@feat.00")
feat00Flags = sym.getValue();
// Skip special symbols.
if (ignoredSymbolName(name))
return nullptr;
if (sym.isExternal())
return symtab->addAbsolute(name, sym);
return make<DefinedAbsolute>(name, sym);
}
int32_t sectionNumber = sym.getSectionNumber();
if (sectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
return nullptr;
if (llvm::COFF::isReservedSectionNumber(sectionNumber))
fatal(toString(this) + ": " + getName() +
" should not refer to special section " + Twine(sectionNumber));
if ((uint32_t)sectionNumber >= sparseChunks.size())
fatal(toString(this) + ": " + getName() +
" should not refer to non-existent section " + Twine(sectionNumber));
// Comdat handling.
// A comdat symbol consists of two symbol table entries.
// The first symbol entry has the name of the section (e.g. .text), fixed
// values for the other fields, and one auxiliary record.
// The second symbol entry has the name of the comdat symbol, called the
// "comdat leader".
// When this function is called for the first symbol entry of a comdat,
// it sets comdatDefs and returns None, and when it's called for the second
// symbol entry it reads comdatDefs and then sets it back to nullptr.
// Handle comdat leader.
if (const coff_aux_section_definition *def = comdatDefs[sectionNumber]) {
comdatDefs[sectionNumber] = nullptr;
DefinedRegular *leader;
if (sym.isExternal()) {
std::tie(leader, prevailing) =
symtab->addComdat(this, getName(), sym.getGeneric());
} else {
leader = make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,
/*IsExternal*/ false, sym.getGeneric());
prevailing = true;
}
if (def->Selection < (int)IMAGE_COMDAT_SELECT_NODUPLICATES ||
// Intentionally ends at IMAGE_COMDAT_SELECT_LARGEST: link.exe
// doesn't understand IMAGE_COMDAT_SELECT_NEWEST either.
def->Selection > (int)IMAGE_COMDAT_SELECT_LARGEST) {
fatal("unknown comdat type " + std::to_string((int)def->Selection) +
" for " + getName() + " in " + toString(this));
}
COMDATType selection = (COMDATType)def->Selection;
if (leader->isCOMDAT)
handleComdatSelection(sym, selection, prevailing, leader);
if (prevailing) {
SectionChunk *c = readSection(sectionNumber, def, getName());
sparseChunks[sectionNumber] = c;
c->sym = cast<DefinedRegular>(leader);
c->selection = selection;
cast<DefinedRegular>(leader)->data = &c->repl;
} else {
sparseChunks[sectionNumber] = nullptr;
}
return leader;
}
// Prepare to handle the comdat leader symbol by setting the section's
// ComdatDefs pointer if we encounter a non-associative comdat.
if (sparseChunks[sectionNumber] == pendingComdat) {
if (const coff_aux_section_definition *def = sym.getSectionDefinition()) {
if (def->Selection != IMAGE_COMDAT_SELECT_ASSOCIATIVE)
comdatDefs[sectionNumber] = def;
}
return None;
}
return createRegular(sym);
}
MachineTypes ObjFile::getMachineType() {
if (coffObj)
return static_cast<MachineTypes>(coffObj->getMachine());
return IMAGE_FILE_MACHINE_UNKNOWN;
}
ArrayRef<uint8_t> ObjFile::getDebugSection(StringRef secName) {
if (SectionChunk *sec = SectionChunk::findByName(debugChunks, secName))
return sec->consumeDebugMagic();
return {};
}
// OBJ files systematically store critical information in a .debug$S stream,
// even if the TU was compiled with no debug info. At least two records are
// always there. S_OBJNAME stores a 32-bit signature, which is loaded into the
// PCHSignature member. S_COMPILE3 stores compile-time cmd-line flags. This is
// currently used to initialize the hotPatchable member.
void ObjFile::initializeFlags() {
ArrayRef<uint8_t> data = getDebugSection(".debug$S");
if (data.empty())
return;
DebugSubsectionArray subsections;
BinaryStreamReader reader(data, support::little);
ExitOnError exitOnErr;
exitOnErr(reader.readArray(subsections, data.size()));
for (const DebugSubsectionRecord &ss : subsections) {
if (ss.kind() != DebugSubsectionKind::Symbols)
continue;
unsigned offset = 0;
// Only parse the first two records. We are only looking for S_OBJNAME
// and S_COMPILE3, and they usually appear at the beginning of the
// stream.
for (unsigned i = 0; i < 2; ++i) {
Expected<CVSymbol> sym = readSymbolFromStream(ss.getRecordData(), offset);
if (!sym) {
consumeError(sym.takeError());
return;
}
if (sym->kind() == SymbolKind::S_COMPILE3) {
auto cs =
cantFail(SymbolDeserializer::deserializeAs<Compile3Sym>(sym.get()));
hotPatchable =
(cs.Flags & CompileSym3Flags::HotPatch) != CompileSym3Flags::None;
}
if (sym->kind() == SymbolKind::S_OBJNAME) {
auto objName = cantFail(SymbolDeserializer::deserializeAs<ObjNameSym>(
sym.get()));
pchSignature = objName.Signature;
}
offset += sym->length();
}
}
}
// Depending on the compilation flags, OBJs can refer to external files,
// necessary to merge this OBJ into the final PDB. We currently support two
// types of external files: Precomp/PCH OBJs, when compiling with /Yc and /Yu.
// And PDB type servers, when compiling with /Zi. This function extracts these
// dependencies and makes them available as a TpiSource interface (see
// DebugTypes.h). Both cases only happen with cl.exe: clang-cl produces regular
// output even with /Yc and /Yu and with /Zi.
void ObjFile::initializeDependencies() {
if (!config->debug)
return;
bool isPCH = false;
ArrayRef<uint8_t> data = getDebugSection(".debug$P");
if (!data.empty())
isPCH = true;
else
data = getDebugSection(".debug$T");
if (data.empty())
return;
CVTypeArray types;
BinaryStreamReader reader(data, support::little);
cantFail(reader.readArray(types, reader.getLength()));
CVTypeArray::Iterator firstType = types.begin();
if (firstType == types.end())
return;
// Remember the .debug$T or .debug$P section.
debugTypes = data;
if (isPCH) {
debugTypesObj = makePrecompSource(this);
return;
}
if (firstType->kind() == LF_TYPESERVER2) {
TypeServer2Record ts = cantFail(
TypeDeserializer::deserializeAs<TypeServer2Record>(firstType->data()));
debugTypesObj = makeUseTypeServerSource(this, &ts);
return;
}
if (firstType->kind() == LF_PRECOMP) {
PrecompRecord precomp = cantFail(
TypeDeserializer::deserializeAs<PrecompRecord>(firstType->data()));
debugTypesObj = makeUsePrecompSource(this, &precomp);
return;
}
debugTypesObj = makeTpiSource(this);
}
// Used only for DWARF debug info, which is not common (except in MinGW
// environments). This returns an optional pair of file name and line
// number for where the variable was defined.
Optional<std::pair<StringRef, uint32_t>>
ObjFile::getVariableLocation(StringRef var) {
if (!dwarf) {
dwarf = make<DWARFCache>(DWARFContext::create(*getCOFFObj()));
if (!dwarf)
return None;
}
if (config->machine == I386)
var.consume_front("_");
Optional<std::pair<std::string, unsigned>> ret = dwarf->getVariableLoc(var);
if (!ret)
return None;
return std::make_pair(saver.save(ret->first), ret->second);
}
// Used only for DWARF debug info, which is not common (except in MinGW
// environments).
Optional<DILineInfo> ObjFile::getDILineInfo(uint32_t offset,
uint32_t sectionIndex) {
if (!dwarf) {
dwarf = make<DWARFCache>(DWARFContext::create(*getCOFFObj()));
if (!dwarf)
return None;
}
return dwarf->getDILineInfo(offset, sectionIndex);
}
StringRef ltrim1(StringRef s, const char *chars) {
if (!s.empty() && strchr(chars, s[0]))
return s.substr(1);
return s;
}
void ImportFile::parse() {
const char *buf = mb.getBufferStart();
const auto *hdr = reinterpret_cast<const coff_import_header *>(buf);
// Check if the total size is valid.
if (mb.getBufferSize() != sizeof(*hdr) + hdr->SizeOfData)
fatal("broken import library");
// Read names and create an __imp_ symbol.
StringRef name = saver.save(StringRef(buf + sizeof(*hdr)));
StringRef impName = saver.save("__imp_" + name);
const char *nameStart = buf + sizeof(coff_import_header) + name.size() + 1;
dllName = StringRef(nameStart);
StringRef extName;
switch (hdr->getNameType()) {
case IMPORT_ORDINAL:
extName = "";
break;
case IMPORT_NAME:
extName = name;
break;
case IMPORT_NAME_NOPREFIX:
extName = ltrim1(name, "?@_");
break;
case IMPORT_NAME_UNDECORATE:
extName = ltrim1(name, "?@_");
extName = extName.substr(0, extName.find('@'));
break;
}
this->hdr = hdr;
externalName = extName;
impSym = symtab->addImportData(impName, this);
// If this was a duplicate, we logged an error but may continue;
// in this case, impSym is nullptr.
if (!impSym)
return;
if (hdr->getType() == llvm::COFF::IMPORT_CONST)
static_cast<void>(symtab->addImportData(name, this));
// If type is function, we need to create a thunk which jump to an
// address pointed by the __imp_ symbol. (This allows you to call
// DLL functions just like regular non-DLL functions.)
if (hdr->getType() == llvm::COFF::IMPORT_CODE)
thunkSym = symtab->addImportThunk(
name, cast_or_null<DefinedImportData>(impSym), hdr->Machine);
}
BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
uint64_t offsetInArchive)
: BitcodeFile(mb, archiveName, offsetInArchive, {}) {}
BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
uint64_t offsetInArchive,
std::vector<Symbol *> &&symbols)
: InputFile(BitcodeKind, mb), symbols(std::move(symbols)) {
std::string path = mb.getBufferIdentifier().str();
if (config->thinLTOIndexOnly)
path = replaceThinLTOSuffix(mb.getBufferIdentifier());
// ThinLTO assumes that all MemoryBufferRefs given to it have a unique
// name. If two archives define two members with the same name, this
// causes a collision which result in only one of the objects being taken
// into consideration at LTO time (which very likely causes undefined
// symbols later in the link stage). So we append file offset to make
// filename unique.
MemoryBufferRef mbref(
mb.getBuffer(),
saver.save(archiveName + path +
(archiveName.empty() ? "" : utostr(offsetInArchive))));
obj = check(lto::InputFile::create(mbref));
}
BitcodeFile::~BitcodeFile() = default;
void BitcodeFile::parse() {
std::vector<std::pair<Symbol *, bool>> comdat(obj->getComdatTable().size());
for (size_t i = 0; i != obj->getComdatTable().size(); ++i)
// FIXME: lto::InputFile doesn't keep enough data to do correct comdat
// selection handling.
comdat[i] = symtab->addComdat(this, saver.save(obj->getComdatTable()[i]));
for (const lto::InputFile::Symbol &objSym : obj->symbols()) {
StringRef symName = saver.save(objSym.getName());
int comdatIndex = objSym.getComdatIndex();
Symbol *sym;
if (objSym.isUndefined()) {
sym = symtab->addUndefined(symName, this, false);
} else if (objSym.isCommon()) {
sym = symtab->addCommon(this, symName, objSym.getCommonSize());
} else if (objSym.isWeak() && objSym.isIndirect()) {
// Weak external.
sym = symtab->addUndefined(symName, this, true);
std::string fallback = objSym.getCOFFWeakExternalFallback();
Symbol *alias = symtab->addUndefined(saver.save(fallback));
checkAndSetWeakAlias(symtab, this, sym, alias);
} else if (comdatIndex != -1) {
if (symName == obj->getComdatTable()[comdatIndex])
sym = comdat[comdatIndex].first;
else if (comdat[comdatIndex].second)
sym = symtab->addRegular(this, symName);
else
sym = symtab->addUndefined(symName, this, false);
} else {
sym = symtab->addRegular(this, symName);
}
symbols.push_back(sym);
if (objSym.isUsed())
config->gcroot.push_back(sym);
}
directives = obj->getCOFFLinkerOpts();
}
MachineTypes BitcodeFile::getMachineType() {
switch (Triple(obj->getTargetTriple()).getArch()) {
case Triple::x86_64:
return AMD64;
case Triple::x86:
return I386;
case Triple::arm:
return ARMNT;
case Triple::aarch64:
return ARM64;
default:
return IMAGE_FILE_MACHINE_UNKNOWN;
}
}
std::string replaceThinLTOSuffix(StringRef path) {
StringRef suffix = config->thinLTOObjectSuffixReplace.first;
StringRef repl = config->thinLTOObjectSuffixReplace.second;
if (path.consume_back(suffix))
return (path + repl).str();
return path;
}
} // namespace coff
} // namespace lld
|
#include <iostream>
#include <sstream>
#include <thread>
#include <vector>
#include <boost/test/unit_test.hpp>
#include <sudoku/solution_queue.h>
#include "util.h"
BOOST_AUTO_TEST_CASE(SolutionQueue_Constructor)
{
sudoku::SolutionQueue q(1);
}
BOOST_AUTO_TEST_CASE(SolutionQueue_PushAndPop_SingleThread)
{
sudoku::SolutionQueue q(2);
sudoku::SolutionQueue::Producer p(q);
sudoku::SolutionQueue::Consumer c(q);
// Sample solutions + metrics
std::vector<sudoku::CellValue> s1{1, 2, 3}, s2{4, 5, 6};
sudoku::Metrics m1, m2;
m1.totalGuesses = 123;
m2.totalGuesses = 456;
// Push some solutions
BOOST_REQUIRE(p.push(s1, m1));
BOOST_REQUIRE(p.push(s2, m2));
// Read the solutions
std::vector<sudoku::CellValue> solution;
sudoku::Metrics metrics;
BOOST_REQUIRE(c.pop(solution, metrics));
BOOST_REQUIRE_EQUAL(solution, s1);
BOOST_REQUIRE_EQUAL(metrics.totalGuesses, m1.totalGuesses);
BOOST_REQUIRE(c.pop(solution, metrics));
BOOST_REQUIRE_EQUAL(solution, s2);
BOOST_REQUIRE_EQUAL(metrics.totalGuesses, m2.totalGuesses);
}
BOOST_AUTO_TEST_CASE(SolutionQueue_ParallelProducers)
{
sudoku::SolutionQueue q(16);
sudoku::SolutionQueue::Consumer c(q);
std::vector<std::thread> threads;
const size_t numThreads = 4;
constexpr size_t numSolutionsPerThread = 10;
// Create threads
for (size_t i = 0; i < numThreads; ++i) {
sudoku::SolutionQueue::Producer p(q);
threads.emplace_back([i, p=std::move(p), numSolutionsPerThread]() mutable {
// Each thread computes many solutions.
// Thread 0: {0, 1, 2} ... {9, 10, 11}
// ...
// Thread 3: {30, 31, 32} ... {39, 40, 41}
for (size_t solutionNum = 0; solutionNum < numSolutionsPerThread; ++solutionNum) {
const sudoku::CellValue base = sudoku::castCellValue((numSolutionsPerThread * i) + solutionNum);
const sudoku::CellValue v1 = base;
const sudoku::CellValue v2 = base + 1;
const sudoku::CellValue v3 = base + 2;
std::vector<sudoku::CellValue> solution{ v1, v2, v3 };
sudoku::Metrics metrics;
metrics.totalGuesses = i;
if (!p.push(solution, metrics)) {
// Stop generating solutions
return;
}
}
return;
});
}
// Count solutions
size_t numSolutions = 0;
std::vector<sudoku::CellValue> solution;
sudoku::Metrics metrics;
while (c.pop(solution, metrics)) {
++numSolutions;
}
BOOST_CHECK_EQUAL(numSolutions, numThreads * numSolutionsPerThread);
for (auto& thread : threads) {
thread.join();
}
}
|
#include <stdexcept>
#include <sstream>
#include <limits.h>
#include "OnlineDB/EcalCondDB/interface/LMFSeqDat.h"
#include "OnlineDB/EcalCondDB/interface/DateHandler.h"
using namespace std;
using namespace oracle::occi;
LMFSeqDat::LMFSeqDat() : LMFUnique()
{
setClassName("LMFSeqDat");
m_runIOV = RunIOV();
m_intFields["seq_num"] = 0;
Tm t;
t = t.plusInfinity();
m_stringFields["seq_start"] = t.str();
m_stringFields["seq_stop"] = t.str();
m_intFields["vmin"] = 1;
m_intFields["vmax"] = 0;
}
LMFSeqDat::LMFSeqDat(EcalDBConnection *c) : LMFUnique(c) {
setClassName("LMFSeqDat");
m_runIOV = RunIOV();
m_intFields["seq_num"] = 0;
Tm t;
t = t.plusInfinity();
m_stringFields["seq_start"] = t.str();
m_stringFields["seq_stop"] = t.str();
m_intFields["vmin"] = 1;
m_intFields["vmax"] = 0;
}
LMFSeqDat::LMFSeqDat(oracle::occi::Environment* env,
oracle::occi::Connection* conn) : LMFUnique(env, conn) {
setClassName("LMFSeqDat");
m_runIOV = RunIOV();
m_intFields["seq_num"] = 0;
Tm t;
t = t.plusInfinity();
m_stringFields["seq_start"] = t.str();
m_stringFields["seq_stop"] = t.str();
m_intFields["vmin"] = 1;
m_intFields["vmax"] = 0;
}
LMFSeqDat::~LMFSeqDat()
{
}
Tm LMFSeqDat::getSequenceStop() const {
Tm t;
t.setToString(getString("seq_stop"));
return t;
}
RunIOV LMFSeqDat::getRunIOV() const
{
return m_runIOV;
}
LMFSeqDat& LMFSeqDat::setRunIOV(const RunIOV &iov)
{
if (iov != m_runIOV) {
m_ID = 0;
m_runIOV = iov;
}
return *this;
}
std::string LMFSeqDat::fetchIdSql(Statement *stmt)
{
int runIOVID = m_runIOV.getID();
if (!runIOVID) {
if (m_debug) {
std::cout << m_className << ": RunIOV not set" << endl;
}
return "";
}
if (m_debug) {
std::cout << "Run IOV ID: " << runIOVID << std::endl;
std::cout << "SEQ # : " << getSequenceNumber() << std::endl;
std::cout << "Versions : " << getVmin() << " - " << getVmax() << endl;
}
std::string sql = "SELECT SEQ_ID FROM CMS_ECAL_LASER_COND.LMF_SEQ_DAT "
"WHERE "
"RUN_IOV_ID = :1 AND "
"SEQ_NUM = :2 AND "
"VMIN = :3 ";
if (getVmax() > 0) {
sql += "AND VMAX = :4";
} else {
sql += "ORDER BY VMAX DESC";
}
stmt->setSQL(sql);
stmt->setInt(1, runIOVID);
stmt->setInt(2, getSequenceNumber());
stmt->setInt(3, getVmin());
if (getVmax() > 0) {
stmt->setInt(4, getVmax());
}
return sql;
}
std::string LMFSeqDat::setByIDSql(Statement *stmt, int id) {
std::string sql = "SELECT RUN_IOV_ID, SEQ_NUM, SEQ_START, SEQ_STOP, "
"VMIN, VMAX FROM CMS_ECAL_LASER_COND.LMF_SEQ_DAT WHERE SEQ_ID = :1";
stmt->setSQL(sql);
stmt->setInt(1, id);
return sql;
}
void LMFSeqDat::getParameters(ResultSet *rset) {
DateHandler dh(m_env, m_conn);
int runIOVID = rset->getInt(1);
setInt("seq_num", rset->getInt(2));
Date startDate = rset->getDate(3);
Date endDate = rset->getDate(4);
setInt("vmin", rset->getInt(5));
setInt("vmax", rset->getInt(6));
setString("seq_start", dh.dateToTm( startDate ).str());
setString("seq_stop", dh.dateToTm( endDate ).str());
m_runIOV.setConnection(m_env, m_conn);
m_runIOV.setByID(runIOVID);
}
bool LMFSeqDat::isValid() const {
bool ret = true;
if (getSequenceStart().isNull()) {
ret = false;
}
if ((getSequenceStop().str().length() > 0) &&
(getSequenceStop().microsTime() < getSequenceStart().microsTime())) {
ret = false;
}
if (getSequenceStop() == Tm().plusInfinity()) {
ret = false;
}
return ret;
}
std::string LMFSeqDat::writeDBSql(Statement *stmt)
{
// Validate the data, use infinity-till convention
DateHandler dh(m_env, m_conn);
if (!isValid()) {
dump();
throw(std::runtime_error("LMFSeqDat::writeDB: not valid"));
}
if (getSequenceStop().str().length() == 0) {
setSequenceStop(dh.getPlusInfTm());
}
int runIOVID = m_runIOV.getID();
if (runIOVID == 0) {
throw(std::runtime_error("LMFSeqDat::writeDB: RunIOV not set"));
}
std::string sp = sequencePostfix(getSequenceStart());
std::string sql = "INSERT INTO LMF_SEQ_DAT (SEQ_ID, RUN_IOV_ID, SEQ_NUM, "
"SEQ_START, SEQ_STOP, VMIN, VMAX) "
"VALUES (SEQ_ID_" + sp + "_SQ.NextVal, :1, :2, :3, :4, :5, :6)";
cout << sql << endl;
stmt->setSQL(sql);
stmt->setInt(1, runIOVID);
stmt->setInt(2, getSequenceNumber());
stmt->setDate(3, dh.tmToDate(getSequenceStart()));
stmt->setDate(4, dh.tmToDate(getSequenceStop()));
stmt->setInt(5, getVmin());
stmt->setInt(6, getVmax());
return sql;
}
void LMFSeqDat::fetchParentIDs()
noexcept(false)
{
// get the RunIOV
m_runIOV.setConnection(m_env, m_conn);
int runIOVID = m_runIOV.getID();
m_runIOV.setByID(runIOVID);
if (m_runIOV.getID() == 0) {
throw(std::runtime_error("LMFSeqDat: Given RunIOV does not exist in DB"));
}
}
std::map<int, LMFSeqDat> LMFSeqDat::fetchByRunIOV(std::string sql,
std::string method)
noexcept(false)
{
std::vector<std::string> pars;
return fetchByRunIOV(pars, sql, method);
}
std::map<int, LMFSeqDat> LMFSeqDat::fetchByRunIOV(int par,
std::string sql,
std::string method)
noexcept(false)
{
std::vector<std::string> pars;
std::stringstream ss;
ss << "I" << par;
pars.push_back(ss.str());
return fetchByRunIOV(pars, sql, method);
}
std::map<int, LMFSeqDat> LMFSeqDat::fetchByRunIOV(const std::vector<std::string>& pars,
std::string sql,
std::string method)
noexcept(false)
{
std::map<int, LMFSeqDat> l;
this->checkConnection();
try {
Statement *stmt = m_conn->createStatement();
stmt->setSQL(sql);
for (unsigned int i = 0; i < pars.size(); i++) {
if (pars[i][0] == 'I') {
stmt->setInt(i + 1, atoi(pars[i].c_str() + 1));
} else if (pars[i][0] == 'S') {
stmt->setString(i + 1, pars[i].c_str() + 1);
} else {
throw(std::runtime_error(m_className + "::" + method + ": " +
"Invalid type"));
}
}
ResultSet *rset = stmt->executeQuery();
while (rset->next() != 0) {
int seq_id = rset->getInt(1);
LMFSeqDat s;
s.setConnection(m_env, m_conn);
s.setByID(seq_id);
l[s.getSequenceNumber()] = s;
}
m_conn->terminateStatement(stmt);
} catch (SQLException &e) {
throw(std::runtime_error(m_className + "::" + method + ": " +
e.getMessage()));
}
return l;
}
LMFSeqDat LMFSeqDat::fetchLast() {
LMFSeqDat ret;
std::map<int, LMFSeqDat> m =
fetchByRunIOV("SELECT SEQ_ID FROM CMS_ECAL_LASER_COND.LMF_SEQ_DAT "
"WHERE SEQ_ID = "
"(SELECT MAX(SEQ_ID) FROM CMS_ECAL_LASER_COND.LMF_SEQ_DAT)",
"fetchLast");
if (m.size() > 0) {
ret = m.begin()->second;
}
return ret;
}
RunIOV LMFSeqDat::fetchLastRun() {
return fetchLast().getRunIOV();
}
std::map<int, LMFSeqDat> LMFSeqDat::fetchByRunIOV(RunIOV &iov) {
int runIOVID = iov.getID();
return fetchByRunIOV(runIOVID,
"SELECT SEQ_ID FROM CMS_ECAL_LASER_COND.LMF_SEQ_DAT "
"WHERE RUN_IOV_ID = :1",
"fetchByRunIOV");
}
std::map<int, LMFSeqDat> LMFSeqDat::fetchByRunIOV(RunIOV &iov,
const LMFColor &col) {
int runIOVID = iov.getID();
int colorId = col.getID();
std::vector<std::string> pars;
std::stringstream ss;
ss << "I" << runIOVID;
pars.push_back(ss.str());
ss.str(std::string());
ss << "I" << colorId;
pars.push_back(ss.str());
return fetchByRunIOV(pars,
"SELECT S.SEQ_ID FROM CMS_ECAL_LASER_COND.LMF_SEQ_DAT "
"S JOIN CMS_ECAL_LASER_COND.LMF_RUN_IOV R"
" ON S.SEQ_ID = R.SEQ_ID WHERE RUN_IOV_ID = :1 AND "
" COLOR_ID = :2",
"fetchByRunIOVAndColor");
}
std::map<int, LMFSeqDat> LMFSeqDat::fetchByRunNumber(int runno) {
return fetchByRunIOV(runno,
"SELECT SEQ_ID FROM CMS_ECAL_LASER_COND.LMF_SEQ_DAT D "
"JOIN CMS_ECAL_COND.RUN_IOV R ON "
"D.RUN_IOV_ID = R.IOV_ID WHERE RUN_NUM = :1",
"fetchByRunNumber");
}
LMFSeqDat LMFSeqDat::fetchByRunNumber(int runno, const Tm& taken_at) {
return fetchByRunNumber(runno, taken_at.str());
}
LMFSeqDat LMFSeqDat::fetchByRunNumber(int runno, std::string taken_at) {
std::map<int, LMFSeqDat> l;
std::vector<std::string> pars;
std::stringstream ss;
ss << "I" << runno;
pars.push_back(ss.str());
ss.str(std::string());
ss << "S" << taken_at;
pars.push_back(ss.str());
std::string q = "SELECT SEQ_ID FROM CMS_ECAL_LASER_COND.LMF_SEQ_DAT D "
"JOIN CMS_ECAL_COND.RUN_IOV R ON "
"D.RUN_IOV_ID = R.IOV_ID WHERE RUN_NUM = :1 AND "
"SEQ_START >= TO_DATE(:2, 'YYYY-MM-DD HH24:MI:SS') "
"AND SEQ_STOP <= TO_DATE(:2, 'YYYY-MM-DD HH24:MI:SS')";
l = fetchByRunIOV(pars, q, "fetchByRunNumberAt");
LMFSeqDat ret;
if (l.size() == 1) {
std::map<int, LMFSeqDat>::const_iterator x = l.begin();
ret = x->second;
} else if (l.size() > 1) {
std::cout << "WARNING: Your query returned more than one result. "
<< std::endl;
std::cout << " This was not expected. Please check the DB!!!"
<< std::endl;
std::cout << "Your query: " << std::endl << q << std::endl;
std::cout << "Your parameters: " << std::endl;
for (unsigned int i = 0; i < pars.size(); i++) {
std::cout << i << ": " << pars[i] << std::endl;
}
}
return ret;
}
|
#include "ImGuiLayer.h"
#include <imgui.h>
#include "Cuboid/Core/Application.h"
#include "glad/glad.h"
#include <imgui_impl_sdl.h>
#include <imgui_impl_opengl3.h>
#include <Cuboid/Renderer/RendererAPI.h>
#include <imgui_impl_dx11.h>
#include <Cuboid/Platform/DirectX/Renderer/D3DGraphicsContext.h>
#include <SDL.h>
#include <imgui_impl_win32.h>
#include "Cuboid/Platform/DirectX/InitializeD3Devices.h"
#include "ImGuiDock.h"
namespace Cuboid
{
ImGuiLayer::ImGuiLayer():
Layer("Imgui")
{
}
ImGuiLayer::~ImGuiLayer()
{
//TODO: Create shut down method
ImGui_ImplDX11_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
}
void ImGuiLayer::OnAttach()
{
IMGUI_CHECKVERSION();
Application& app = Application::Get();
ImGui::SetCurrentContext(ImGui::CreateContext());
ImGui::StyleColorsDark();
ImGuiIO& io = ImGui::GetIO();
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors;
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
ImGuiStyle& style = ImGui::GetStyle();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
style.WindowRounding = 0.0f;
style.Colors[ImGuiCol_WindowBg].w = 1.0f;
}
io.Fonts->AddFontFromFileTTF("res/fonts/DroidSans-Bold.ttf", 14.0f);
io.FontDefault = io.Fonts->AddFontFromFileTTF("res/fonts/DroidSans.ttf", 14.0f);
SetDarkThemeColors();
if(RendererAPI::GetAPI() == RendererAPI::API::Opengl) {
ImGui_ImplSDL2_InitForOpenGL(std::any_cast<SDL_Window*>(app.GetWindow().GetNativeWindow()),
app.GetWindow().GetGLContext());
ImGui_ImplOpenGL3_Init("#version 120");
}
else if (RendererAPI::GetAPI() == RendererAPI::API::DirectX)
{
ImGui_ImplWin32_EnableDpiAwareness();
ImGui_ImplWin32_Init(std::any_cast<HWND>(app.GetWindow().GetNativeWindow()));
ImGui_ImplDX11_Init(GraphicsEngine()->GetDevice().Get(), GraphicsEngine()->GetContext().Get());
}
io.DisplaySize = ImVec2((float)app.GetWindow().GetWidth(), (float)app.GetWindow().GetHeight());
}
void ImGuiLayer::OnDetach()
{
//TODO: Do some clean up here dawg
}
void ImGuiLayer::Begin()
{
Application& app = Application::Get();
if(RendererAPI::GetAPI() == RendererAPI::API::Opengl)
{
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(std::any_cast<SDL_Window*>(app.GetWindow().GetNativeWindow()));
} else if(RendererAPI::GetAPI() == RendererAPI::API::DirectX)
{
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
}
ImGui::NewFrame();
}
void ImGuiLayer::End()
{
Application& app = Application::Get();
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = ImVec2((float)app.GetWindow().GetWidth(),(float)app.GetWindow().GetHeight());
ImGui::Render();
if(RendererAPI::GetAPI() == RendererAPI::API::Opengl)
{
glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
SDL_Window* backup_current_window = SDL_GL_GetCurrentWindow();
SDL_GLContext backup_current_context = SDL_GL_GetCurrentContext();
SDL_GL_MakeCurrent(backup_current_window, backup_current_context);
}
}
else if (RendererAPI::GetAPI() == RendererAPI::API::DirectX)
{
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
}
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault();
}
}
void ImGuiLayer::OnImGuiRender()
{
}
void ImGuiLayer::OnEvent(Event& event)
{
if (m_bBlockImGuiEvents)
{
ImGuiIO& io = ImGui::GetIO();
event.Handled |= event.IsInCategory(EventCategoryMouse) & io.WantCaptureMouse;
event.Handled |= event.IsInCategory(EventCategoryKeyboard) & io.WantCaptureKeyboard;
}
}
void ImGuiLayer::SetDarkThemeColors()
{
auto& colors = ImGui::GetStyle().Colors;
colors[ImGuiCol_WindowBg] = ImVec4{ 0.1f, 0.105f, 0.11f, 1.0f };
//headers
colors[ImGuiCol_Header] = ImVec4{ 0.2f, 0.205f, 0.21f, 1.0f };
colors[ImGuiCol_HeaderHovered] = ImVec4{ 0.3f, 0.305f, 0.31f, 1.0f };
colors[ImGuiCol_HeaderActive] = ImVec4{ 0.15f, 0.150f, 0.151f, 1.0f };
//Buttons
colors[ImGuiCol_Button] = ImVec4{ 0.2f, 0.205f, 0.21f, 1.0f };
colors[ImGuiCol_ButtonHovered] = ImVec4{ 0.3f, 0.305f, 0.31f, 1.0f };
colors[ImGuiCol_ButtonActive] = ImVec4{ 0.15f, 0.150f, 0.151f, 1.0f };
//FrameBG
colors[ImGuiCol_FrameBg] = ImVec4{ 0.2f, 0.205f, 0.21f, 1.0f };
colors[ImGuiCol_FrameBgHovered] = ImVec4{ 0.3f, 0.305f, 0.31f, 1.0f };
colors[ImGuiCol_FrameBgActive] = ImVec4{ 0.15f, 0.150f, 0.151f, 1.0f };
//Tabs
colors[ImGuiCol_Tab] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f };
colors[ImGuiCol_TabHovered] = ImVec4{ 0.38f, 0.3805f, 0.381f, 1.0f };
colors[ImGuiCol_TabActive] = ImVec4{ 0.28f, 0.2805f, 0.281f, 1.0f };
colors[ImGuiCol_TabUnfocused] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f };
colors[ImGuiCol_TabUnfocused] = ImVec4{ 0.2f, 0.205f, 0.21f, 1.0f };
//docking
colors[ImGuiCol_DockingPreview] = colors[ImGuiCol_Header];
colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f);
//titles
colors[ImGuiCol_TitleBg] = ImVec4{ 0.1f, 0.1505f, 0.151f, 1.0f };
colors[ImGuiCol_TitleBgActive] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f };
colors[ImGuiCol_TitleBgCollapsed] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f };
}
}
|
/* ============================================================================
* Copyright (c) 2014 William Lenthe
* Copyright (c) 2014 DREAM3D Consortium
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of William Lenthe or any of the DREAM3D Consortium contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This code was partially written under United States Air Force Contract number
* FA8650-10-D-5210
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#include "ItkDiscreteGaussianBlur.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
#include <QtCore/QString>
#include "SIMPLib/FilterParameters/DataArraySelectionFilterParameter.h"
#include "SIMPLib/FilterParameters/StringFilterParameter.h"
#include "SIMPLib/FilterParameters/FloatFilterParameter.h"
#include "SIMPLib/FilterParameters/AbstractFilterParametersReader.h"
#include "SIMPLib/FilterParameters/LinkedBooleanFilterParameter.h"
#include "SIMPLib/FilterParameters/LinkedPathCreationFilterParameter.h"
#include "SIMPLib/FilterParameters/SeparatorFilterParameter.h"
#include "SIMPLib/Geometry/ImageGeom.h"
#include "SIMPLib/ITK/itkBridge.h"
#include "SIMPLib/DataContainers/DataContainerArray.h"
#include "SIMPLib/DataContainers/DataContainer.h"
#include "ImageProcessing/ImageProcessingConstants.h"
/* Create Enumerations to allow the created Attribute Arrays to take part in renaming */
enum createdPathID : RenameDataPath::DataID_t
{
DataArrayID30 = 30,
DataArrayID31 = 31,
};
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
ItkDiscreteGaussianBlur::ItkDiscreteGaussianBlur() = default;
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
ItkDiscreteGaussianBlur::~ItkDiscreteGaussianBlur() = default;
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ItkDiscreteGaussianBlur::setupFilterParameters()
{
FilterParameterVectorType parameters;
std::vector<QString> linkedProps;
linkedProps.push_back("NewCellArrayName");
parameters.push_back(SIMPL_NEW_LINKED_BOOL_FP("Save as New Array", SaveAsNewArray, FilterParameter::Category::Parameter, ItkDiscreteGaussianBlur, linkedProps));
parameters.push_back(SeparatorFilterParameter::Create("Cell Data", FilterParameter::Category::RequiredArray));
{
DataArraySelectionFilterParameter::RequirementType req = DataArraySelectionFilterParameter::CreateCategoryRequirement(SIMPL::TypeNames::UInt8, 1, AttributeMatrix::Category::Any);
parameters.push_back(SIMPL_NEW_DA_SELECTION_FP("Attribute Array to Blur", SelectedCellArrayPath, FilterParameter::Category::RequiredArray, ItkDiscreteGaussianBlur, req));
}
parameters.push_back(SeparatorFilterParameter::Create("Cell Data", FilterParameter::Category::CreatedArray));
parameters.push_back(
SIMPL_NEW_DA_WITH_LINKED_AM_FP("Blurred Array", NewCellArrayName, SelectedCellArrayPath, SelectedCellArrayPath, FilterParameter::Category::CreatedArray, ItkDiscreteGaussianBlur));
parameters.push_back(SIMPL_NEW_FLOAT_FP("Standard Deviation", Stdev, FilterParameter::Category::Parameter, ItkDiscreteGaussianBlur));
setFilterParameters(parameters);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ItkDiscreteGaussianBlur::readFilterParameters(AbstractFilterParametersReader* reader, int index)
{
reader->openFilterGroup(this, index);
setSelectedCellArrayPath( reader->readDataArrayPath( "SelectedCellArrayPath", getSelectedCellArrayPath() ) );
setNewCellArrayName( reader->readString( "NewCellArrayName", getNewCellArrayName() ) );
setSaveAsNewArray( reader->readValue( "SaveAsNewArray", getSaveAsNewArray() ) );
setStdev( reader->readValue( "Stdev", getStdev() ) );
reader->closeFilterGroup();
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ItkDiscreteGaussianBlur::initialize()
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ItkDiscreteGaussianBlur::dataCheck()
{
clearErrorCode();
clearWarningCode();
DataArrayPath tempPath;
std::vector<size_t> dims(1, 1);
m_SelectedCellArrayPtr = getDataContainerArray()->getPrereqArrayFromPath<DataArray<ImageProcessingConstants::DefaultPixelType>>(this, getSelectedCellArrayPath(), dims);
if(nullptr != m_SelectedCellArrayPtr.lock())
{ m_SelectedCellArray = m_SelectedCellArrayPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
if(getErrorCode() < 0)
{
return;
}
ImageGeom::Pointer image = getDataContainerArray()->getDataContainer(getSelectedCellArrayPath().getDataContainerName())->getPrereqGeometry<ImageGeom>(this);
if(getErrorCode() < 0 || nullptr == image.get())
{
return;
}
if(!m_SaveAsNewArray)
{
m_NewCellArrayName = "thisIsATempName";
}
tempPath.update(getSelectedCellArrayPath().getDataContainerName(), getSelectedCellArrayPath().getAttributeMatrixName(), getNewCellArrayName() );
m_NewCellArrayPtr = getDataContainerArray()->createNonPrereqArrayFromPath<DataArray<ImageProcessingConstants::DefaultPixelType>>(
this, tempPath, 0, dims, "", DataArrayID31);
if(nullptr != m_NewCellArrayPtr.lock())
{ m_NewCellArray = m_NewCellArrayPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ItkDiscreteGaussianBlur::execute()
{
//int err = 0;
dataCheck();
if(getErrorCode() < 0)
{
return;
}
DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getSelectedCellArrayPath().getDataContainerName());
QString attrMatName = getSelectedCellArrayPath().getAttributeMatrixName();
//wrap m_RawImageData as itk::image
ImageProcessingConstants::DefaultImageType::Pointer inputImage = ITKUtilitiesType::CreateItkWrapperForDataPointer(m, attrMatName, m_SelectedCellArray);
//create Gaussian blur filter
typedef itk::DiscreteGaussianImageFilter< ImageProcessingConstants::DefaultImageType, ImageProcessingConstants::FloatImageType > GaussianFilterType;
GaussianFilterType::Pointer gaussianFilter = GaussianFilterType::New();
gaussianFilter->SetInput(inputImage);
gaussianFilter->SetVariance(m_Stdev * m_Stdev);
//convert result back to uint8
typedef itk::RescaleIntensityImageFilter<ImageProcessingConstants::FloatImageType, ImageProcessingConstants::DefaultImageType> RescaleImageType;
RescaleImageType::Pointer rescaleFilter = RescaleImageType::New();
rescaleFilter->SetInput(gaussianFilter->GetOutput());
rescaleFilter->SetOutputMinimum(0);
rescaleFilter->SetOutputMaximum(255);
//have filter write to dream3d array instead of creating its own buffer
ITKUtilitiesType::SetITKFilterOutput(rescaleFilter->GetOutput(), m_NewCellArrayPtr.lock());
//execute filters
gaussianFilter->Update();
rescaleFilter->Update();
//array name changing/cleanup
if(!m_SaveAsNewArray)
{
AttributeMatrix::Pointer attrMat = m->getAttributeMatrix(m_SelectedCellArrayPath.getAttributeMatrixName());
attrMat->removeAttributeArray(m_SelectedCellArrayPath.getDataArrayName());
bool check = attrMat->renameAttributeArray(m_NewCellArrayName, m_SelectedCellArrayPath.getDataArrayName()) != 0u;
if(!check)
{
}
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
AbstractFilter::Pointer ItkDiscreteGaussianBlur::newFilterInstance(bool copyFilterParameters) const
{
ItkDiscreteGaussianBlur::Pointer filter = ItkDiscreteGaussianBlur::New();
if(copyFilterParameters)
{
copyFilterParameterInstanceVariables(filter.get());
}
return filter;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QString ItkDiscreteGaussianBlur::getCompiledLibraryName() const
{return ImageProcessingConstants::ImageProcessingBaseName;}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QString ItkDiscreteGaussianBlur::getGroupName() const
{return SIMPL::FilterGroups::Unsupported;}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QUuid ItkDiscreteGaussianBlur::getUuid() const
{
return QUuid("{73ad993e-a36e-5978-bda2-ccee69d36186}");
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QString ItkDiscreteGaussianBlur::getSubGroupName() const
{return "Misc";}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QString ItkDiscreteGaussianBlur::getHumanLabel() const
{ return "Discrete Gaussian Blur (ImageProcessing)"; }
// -----------------------------------------------------------------------------
ItkDiscreteGaussianBlur::Pointer ItkDiscreteGaussianBlur::NullPointer()
{
return Pointer(static_cast<Self*>(nullptr));
}
// -----------------------------------------------------------------------------
std::shared_ptr<ItkDiscreteGaussianBlur> ItkDiscreteGaussianBlur::New()
{
struct make_shared_enabler : public ItkDiscreteGaussianBlur
{
};
std::shared_ptr<make_shared_enabler> val = std::make_shared<make_shared_enabler>();
val->setupFilterParameters();
return val;
}
// -----------------------------------------------------------------------------
QString ItkDiscreteGaussianBlur::getNameOfClass() const
{
return QString("ItkDiscreteGaussianBlur");
}
// -----------------------------------------------------------------------------
QString ItkDiscreteGaussianBlur::ClassName()
{
return QString("ItkDiscreteGaussianBlur");
}
// -----------------------------------------------------------------------------
void ItkDiscreteGaussianBlur::setSelectedCellArrayPath(const DataArrayPath& value)
{
m_SelectedCellArrayPath = value;
}
// -----------------------------------------------------------------------------
DataArrayPath ItkDiscreteGaussianBlur::getSelectedCellArrayPath() const
{
return m_SelectedCellArrayPath;
}
// -----------------------------------------------------------------------------
void ItkDiscreteGaussianBlur::setNewCellArrayName(const QString& value)
{
m_NewCellArrayName = value;
}
// -----------------------------------------------------------------------------
QString ItkDiscreteGaussianBlur::getNewCellArrayName() const
{
return m_NewCellArrayName;
}
// -----------------------------------------------------------------------------
void ItkDiscreteGaussianBlur::setSaveAsNewArray(bool value)
{
m_SaveAsNewArray = value;
}
// -----------------------------------------------------------------------------
bool ItkDiscreteGaussianBlur::getSaveAsNewArray() const
{
return m_SaveAsNewArray;
}
// -----------------------------------------------------------------------------
void ItkDiscreteGaussianBlur::setStdev(float value)
{
m_Stdev = value;
}
// -----------------------------------------------------------------------------
float ItkDiscreteGaussianBlur::getStdev() const
{
return m_Stdev;
}
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __itkLevelSetContainerBase_hxx
#define __itkLevelSetContainerBase_hxx
#include "itkLevelSetContainerBase.h"
namespace itk
{
template< class TIdentifier, class TLevelSet >
LevelSetContainerBase< TIdentifier, TLevelSet >
::LevelSetContainerBase()
{
}
template< class TIdentifier, class TLevelSet >
LevelSetContainerBase< TIdentifier, TLevelSet >
::~LevelSetContainerBase()
{
}
template< class TIdentifier, class TLevelSet >
const typename
LevelSetContainerBase< TIdentifier, TLevelSet >::LevelSetContainerType&
LevelSetContainerBase< TIdentifier, TLevelSet >::GetContainer() const
{
return m_Container;
}
template< class TIdentifier, class TLevelSet >
void
LevelSetContainerBase< TIdentifier, TLevelSet >
::SetContainer(const LevelSetContainerType &iContainer)
{
m_Container = iContainer;
}
template< class TIdentifier, class TLevelSet >
typename LevelSetContainerBase< TIdentifier, TLevelSet >::Iterator
LevelSetContainerBase< TIdentifier, TLevelSet >::Begin()
{
return Iterator( m_Container.begin() );
}
template< class TIdentifier, class TLevelSet >
typename LevelSetContainerBase< TIdentifier, TLevelSet >::ConstIterator
LevelSetContainerBase< TIdentifier, TLevelSet >::Begin() const
{
return ConstIterator( m_Container.begin() );
}
template< class TIdentifier, class TLevelSet >
typename LevelSetContainerBase< TIdentifier, TLevelSet >::Iterator
LevelSetContainerBase< TIdentifier, TLevelSet >::End()
{
return Iterator( m_Container.end() );
}
template< class TIdentifier, class TLevelSet >
typename LevelSetContainerBase< TIdentifier, TLevelSet >::ConstIterator
LevelSetContainerBase< TIdentifier, TLevelSet >::End() const
{
return ConstIterator( m_Container.end() );
}
template< class TIdentifier, class TLevelSet >
typename LevelSetContainerBase< TIdentifier, TLevelSet >::LevelSetIdentifierType
LevelSetContainerBase< TIdentifier, TLevelSet >::Size() const
{
return static_cast< LevelSetIdentifierType >( m_Container.size() );
}
template< class TIdentifier, class TLevelSet >
typename LevelSetContainerBase< TIdentifier, TLevelSet >::LevelSetPointer
LevelSetContainerBase< TIdentifier, TLevelSet >
::GetLevelSet( const LevelSetIdentifierType& iId ) const
{
LevelSetContainerConstIteratorType it = m_Container.find( iId );
if( it != m_Container.end() )
{
return it->second;
}
else
{
return NULL;
}
}
template< class TIdentifier, class TLevelSet >
bool LevelSetContainerBase< TIdentifier, TLevelSet >
::AddLevelSet( const LevelSetIdentifierType& iId,
LevelSetType * iLevelSet,
const bool iForce )
{
if( iForce )
{
m_Container[iId] = iLevelSet;
this->Modified();
return true;
}
else
{
if( m_Container.empty() )
{
m_Container.insert( LevelSetPairType( iId, iLevelSet ) );
this->Modified();
return true;
}
else
{
LevelSetContainerIteratorType it = m_Container.find( iId );
if( it != m_Container.end() )
{
return false;
}
else
{
m_Container.insert( LevelSetPairType( iId, iLevelSet ) );
this->Modified();
return true;
}
}
}
}
template< class TIdentifier, class TLevelSet >
bool
LevelSetContainerBase< TIdentifier, TLevelSet >
::RemoveLevelSet( const LevelSetIdentifierType& iId )
{
LevelSetContainerIteratorType it = m_Container.find( iId );
if( it != m_Container.end() )
{
it->second = NULL;
m_Container.erase( it );
this->Modified();
return true;
}
else
{
return false;
}
}
}
#endif // __itkLevelSetContainerBase_hxx
|
#ifndef _ISOTROPIC_GAUSSIAN_TPP_
#define _ISOTROPIC_GAUSSIAN_TPP_
//--------------------------------------------------------------------------
template<class Point>
double IsotropicGaussian::
Eval(const Point &x, const Point &y, double lambda) const {
if (x.GetD() != y.GetD()) {
printf("IsotropicGaussian::Eval. Error: Point dimensions do not match. Return NAN.\n");
return NAN;
}
double r2 = x.Dist2(y);
double ret = s * exp(-r2/Square(sigma)/2.0);
if (r2 == 0.0) {
ret += lambda;
}
return ret;
}
#endif
|
// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Simon Ninon <simon.ninon@gmail.com>
//
// 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 "array_builder.hpp"
#include "bulk_string_builder.hpp"
#include "error_builder.hpp"
#include "integer_builder.hpp"
#include "reply_builder.hpp"
#include "simple_string_builder.hpp"
#include "error.hpp"
#include <gtest/gtest.h>
TEST(ReplyBuilder, WithNoData) {
cpp_redis::builders::reply_builder builder;
EXPECT_EQ(false, builder.reply_available());
}
TEST(ReplyBuilder, WithNotEnoughData) {
cpp_redis::builders::reply_builder builder;
builder << "*1\r\n";
EXPECT_EQ(false, builder.reply_available());
}
TEST(ReplyBuilder, WithPartOfEndSequence) {
cpp_redis::builders::reply_builder builder;
builder << "*1\r\n+hello\r";
EXPECT_EQ(false, builder.reply_available());
}
TEST(ReplyBuilder, WithAllInOneTime) {
cpp_redis::builders::reply_builder builder;
builder << "*4\r\n+simple_string\r\n-error\r\n:42\r\n$5\r\nhello\r\n";
EXPECT_EQ(true, builder.reply_available());
auto reply = builder.get_front();
EXPECT_TRUE(reply.is_array());
auto array = reply.as_array();
EXPECT_EQ(4U, array.size());
auto row_1 = array[0];
EXPECT_TRUE(row_1.is_simple_string());
EXPECT_EQ("simple_string", row_1.as_string());
auto row_2 = array[1];
EXPECT_TRUE(row_2.is_error());
EXPECT_EQ("error", row_2.as_string());
auto row_3 = array[2];
EXPECT_TRUE(row_3.is_integer());
EXPECT_EQ(42, row_3.as_integer());
auto row_4 = array[3];
EXPECT_TRUE(row_4.is_bulk_string());
EXPECT_EQ("hello", row_4.as_string());
}
TEST(ReplyBuilder, WithAllInMultipleTimes) {
cpp_redis::builders::reply_builder builder;
builder << "*4\r\n+simple_string\r";
builder << "\n-error\r\n:42\r\n";
;
builder << "$5\r\nhello\r\n";
EXPECT_EQ(true, builder.reply_available());
auto reply = builder.get_front();
EXPECT_TRUE(reply.is_array());
auto array = reply.as_array();
EXPECT_EQ(4U, array.size());
auto row_1 = array[0];
EXPECT_TRUE(row_1.is_simple_string());
EXPECT_EQ("simple_string", row_1.as_string());
auto row_2 = array[1];
EXPECT_TRUE(row_2.is_error());
EXPECT_EQ("error", row_2.as_string());
auto row_3 = array[2];
EXPECT_TRUE(row_3.is_integer());
EXPECT_EQ(42, row_3.as_integer());
auto row_4 = array[3];
EXPECT_TRUE(row_4.is_bulk_string());
EXPECT_EQ("hello", row_4.as_string());
}
|
//
// detail/task_io_service_thread_info.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2014 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_DETAIL_TASK_IO_SERVICE_THREAD_INFO_HPP
#define BOOST_ASIO_DETAIL_TASK_IO_SERVICE_THREAD_INFO_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/op_queue.hpp>
#include <boost/asio/detail/thread_info_base.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace detail {
class task_io_service;
class task_io_service_operation;
struct task_io_service_thread_info : public thread_info_base
{
op_queue<task_io_service_operation> private_op_queue;
long private_outstanding_work;
};
} // namespace detail
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // BOOST_ASIO_DETAIL_TASK_IO_SERVICE_THREAD_INFO_HPP
|
// @HEADER
// ***********************************************************************
//
// Panzer: A partial differential equation assembly
// engine for strongly coupled complex multiphysics systems
// Copyright (2011) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Roger P. Pawlowski (rppawlo@sandia.gov) and
// Eric C. Cyr (eccyr@sandia.gov)
// ***********************************************************************
// @HEADER
#ifndef PANZER_ASSEMBLY_ENGINE_IMPL_HPP
#define PANZER_ASSEMBLY_ENGINE_IMPL_HPP
#include "Phalanx_FieldManager.hpp"
#include "Panzer_FieldManagerBuilder.hpp"
#include "Panzer_AssemblyEngine_InArgs.hpp"
#include "Panzer_GlobalEvaluationDataContainer.hpp"
#include <sstream>
//===========================================================================
//===========================================================================
template <typename EvalT>
panzer::AssemblyEngine<EvalT>::
AssemblyEngine(const Teuchos::RCP<panzer::FieldManagerBuilder>& fmb,
const Teuchos::RCP<const panzer::LinearObjFactory<panzer::Traits> > & lof)
: m_field_manager_builder(fmb), m_lin_obj_factory(lof), countersInitialized_(false)
{
}
//===========================================================================
//===========================================================================
template <typename EvalT>
void panzer::AssemblyEngine<EvalT>::
evaluate(const panzer::AssemblyEngineInArgs& in, const EvaluationFlags flags)
{
typedef LinearObjContainer LOC;
// make sure this container gets a dirichlet adjustment
in.ghostedContainer_->setRequiresDirichletAdjustment(true);
GlobalEvaluationDataContainer gedc;
if ( flags.getValue() & EvaluationFlags::Initialize ) {
PANZER_FUNC_TIME_MONITOR_DIFF("panzer::AssemblyEngine::evaluate_gather("+PHX::print<EvalT>()+")", eval_gather);
in.fillGlobalEvaluationDataContainer(gedc);
gedc.initialize(); // make sure all ghosted data is ready to go
gedc.globalToGhost(LOC::X | LOC::DxDt);
// Push solution, x and dxdt into ghosted domain
m_lin_obj_factory->globalToGhostContainer(*in.container_,*in.ghostedContainer_,LOC::X | LOC::DxDt);
m_lin_obj_factory->beginFill(*in.ghostedContainer_);
}
// *********************
// Volumetric fill
// *********************
if ( flags.getValue() & EvaluationFlags::VolumetricFill) {
PANZER_FUNC_TIME_MONITOR_DIFF("panzer::AssemblyEngine::evaluate_volume("+PHX::print<EvalT>()+")", eval_vol);
this->evaluateVolume(in);
}
// *********************
// BC fill
// *********************
// NOTE: We have to split neumann and dirichlet bcs since dirichlet
// bcs overwrite equations where neumann sum into equations. Make
// sure all neumann are done before dirichlet.
if ( flags.getValue() & EvaluationFlags::BoundaryFill) {
{
PANZER_FUNC_TIME_MONITOR_DIFF("panzer::AssemblyEngine::evaluate_neumannbcs("+PHX::print<EvalT>()+")",eval_neumannbcs);
this->evaluateNeumannBCs(in);
}
{
PANZER_FUNC_TIME_MONITOR_DIFF("panzer::AssemblyEngine::evaluate_interfacebcs("+PHX::print<EvalT>()+")",eval_interfacebcs);
this->evaluateInterfaceBCs(in);
}
// Dirchlet conditions require a global matrix
{
PANZER_FUNC_TIME_MONITOR_DIFF("panzer::AssemblyEngine::evaluate_dirichletbcs("+PHX::print<EvalT>()+")",eval_dirichletbcs);
this->evaluateDirichletBCs(in);
}
{
PANZER_FUNC_TIME_MONITOR_DIFF("panzer::AssemblyEngine::evaluateDirichletCondition("+PHX::print<EvalT>()+")",eval_DirichletCondition);
this->evaluateDirichletCondition(in);
}
}
if ( flags.getValue() & EvaluationFlags::Scatter) {
PANZER_FUNC_TIME_MONITOR_DIFF("panzer::AssemblyEngine::evaluate_scatter("+PHX::print<EvalT>()+")",eval_scatter);
m_lin_obj_factory->ghostToGlobalContainer(*in.ghostedContainer_,*in.container_,LOC::F | LOC::Mat);
m_lin_obj_factory->beginFill(*in.container_);
gedc.ghostToGlobal(LOC::F | LOC::Mat);
m_lin_obj_factory->endFill(*in.container_);
m_lin_obj_factory->endFill(*in.ghostedContainer_);
}
return;
}
//===========================================================================
//===========================================================================
template <typename EvalT>
void panzer::AssemblyEngine<EvalT>::
evaluateVolume(const panzer::AssemblyEngineInArgs& in)
{
const std::vector< Teuchos::RCP< PHX::FieldManager<panzer::Traits> > > &
volume_field_managers = m_field_manager_builder->getVolumeFieldManagers();
const std::vector<WorksetDescriptor> & wkstDesc = m_field_manager_builder->getVolumeWorksetDescriptors();
Teuchos::RCP<panzer::WorksetContainer> wkstContainer = m_field_manager_builder->getWorksetContainer();
panzer::Traits::PED ped;
ped.gedc->addDataObject("Solution Gather Container",in.ghostedContainer_);
ped.gedc->addDataObject("Residual Scatter Container",in.ghostedContainer_);
ped.first_sensitivities_name = in.first_sensitivities_name;
ped.second_sensitivities_name = in.second_sensitivities_name;
in.fillGlobalEvaluationDataContainer(*(ped.gedc));
// Loop over volume field managers
for (std::size_t block = 0; block < volume_field_managers.size(); ++block) {
const WorksetDescriptor & wd = wkstDesc[block];
Teuchos::RCP< PHX::FieldManager<panzer::Traits> > fm = volume_field_managers[block];
std::vector<panzer::Workset>& w = *wkstContainer->getWorksets(wd);
fm->template preEvaluate<EvalT>(ped);
// Loop over worksets in this element block
for (std::size_t i = 0; i < w.size(); ++i) {
panzer::Workset& workset = w[i];
workset.alpha = in.alpha;
workset.beta = in.beta;
workset.time = in.time;
workset.step_size = in.step_size;
workset.stage_number = in.stage_number;
workset.gather_seeds = in.gather_seeds;
workset.evaluate_transient_terms = in.evaluate_transient_terms;
fm->template evaluateFields<EvalT>(workset);
}
// double s = 0.;
// double p = 0.;
// fm->template analyzeGraph<EvalT>(s,p);
// std::cout << "Analyze Graph: " << PHX::print<EvalT>() << ",b=" << block << ", s=" << s << ", p=" << p << std::endl;
fm->template postEvaluate<EvalT>(NULL);
}
}
//===========================================================================
//===========================================================================
template <typename EvalT>
void panzer::AssemblyEngine<EvalT>::
evaluateNeumannBCs(const panzer::AssemblyEngineInArgs& in)
{
this->evaluateBCs(panzer::BCT_Neumann, in);
}
//===========================================================================
//===========================================================================
template <typename EvalT>
void panzer::AssemblyEngine<EvalT>::
evaluateInterfaceBCs(const panzer::AssemblyEngineInArgs& in)
{
this->evaluateBCs(panzer::BCT_Interface, in);
}
//===========================================================================
//===========================================================================
template <typename EvalT>
Teuchos::RCP<panzer::LinearObjContainer> panzer::AssemblyEngine<EvalT>::
evaluateDirichletBCs(const panzer::AssemblyEngineInArgs& in)
{
typedef LinearObjContainer LOC;
if(!countersInitialized_) {
localCounter_ = m_lin_obj_factory->buildPrimitiveGhostedLinearObjContainer();
globalCounter_ = m_lin_obj_factory->buildPrimitiveLinearObjContainer();
summedGhostedCounter_ = m_lin_obj_factory->buildPrimitiveGhostedLinearObjContainer();
countersInitialized_ = true;
m_lin_obj_factory->initializeGhostedContainer(LinearObjContainer::F,*localCounter_); // store counter in F
m_lin_obj_factory->initializeContainer( LinearObjContainer::F,*globalCounter_); // store counter in X
m_lin_obj_factory->initializeGhostedContainer(LinearObjContainer::F,*summedGhostedCounter_); // store counter in X
}
{
localCounter_->initialize();
summedGhostedCounter_->initialize();
globalCounter_->initialize();
}
// apply dirichlet conditions, make sure to keep track of the local counter
this->evaluateBCs(panzer::BCT_Dirichlet, in,localCounter_);
// do communication to build summed ghosted counter for dirichlet conditions
{
m_lin_obj_factory->ghostToGlobalContainer(*localCounter_,*globalCounter_,LOC::F);
// Here we do the reduction across all processors so that the number of times
// a dirichlet condition is applied is summed into the global counter
m_lin_obj_factory->globalToGhostContainer(*globalCounter_,*summedGhostedCounter_,LOC::F);
// finally we move the summed global vector into a local ghosted vector
// so that the dirichlet conditions can be applied to both the ghosted
// right hand side and the ghosted matrix
}
panzer::GlobalEvaluationDataContainer gedc;
gedc.addDataObject("Residual Scatter Container",in.ghostedContainer_);
in.fillGlobalEvaluationDataContainer(gedc);
// adjust ghosted system for boundary conditions
for(GlobalEvaluationDataContainer::iterator itr=gedc.begin();itr!=gedc.end();itr++) {
if(itr->second->requiresDirichletAdjustment()) {
Teuchos::RCP<LinearObjContainer> loc = Teuchos::rcp_dynamic_cast<LinearObjContainer>(itr->second);
if(loc!=Teuchos::null) {
m_lin_obj_factory->adjustForDirichletConditions(*localCounter_,*summedGhostedCounter_,*loc);
}
else {
// GlobalEvaluationData_BCAdjustment here
}
}
}
return globalCounter_;
}
//===========================================================================
//===========================================================================
template <typename EvalT>
void panzer::AssemblyEngine<EvalT>::
evaluateBCs(const panzer::BCType bc_type,
const panzer::AssemblyEngineInArgs& in,
const Teuchos::RCP<LinearObjContainer> preEval_loc)
{
Teuchos::RCP<panzer::WorksetContainer> wkstContainer = m_field_manager_builder->getWorksetContainer();
panzer::Traits::PED ped;
ped.gedc->addDataObject("Dirichlet Counter",preEval_loc);
ped.gedc->addDataObject("Solution Gather Container",in.ghostedContainer_);
ped.gedc->addDataObject("Residual Scatter Container",in.ghostedContainer_);
ped.first_sensitivities_name = in.first_sensitivities_name;
ped.second_sensitivities_name = in.second_sensitivities_name;
in.fillGlobalEvaluationDataContainer(*(ped.gedc));
// this helps work around issues when constructing a mass
// matrix using an evaluation of only the transient terms.
// In particular, the terms associated with the dirichlet
// conditions.
double betaValue = in.beta; // default to the passed in beta
if(bc_type==panzer::BCT_Dirichlet && in.apply_dirichlet_beta) {
betaValue = in.dirichlet_beta;
}
{
const std::map<panzer::BC,
std::map<unsigned,PHX::FieldManager<panzer::Traits> >,
panzer::LessBC>& bc_field_managers =
m_field_manager_builder->getBCFieldManagers();
// Must do all neumann before all dirichlet so we need a double loop
// here over all bcs
typedef typename std::map<panzer::BC,
std::map<unsigned,PHX::FieldManager<panzer::Traits> >,
panzer::LessBC>::const_iterator bcfm_it_type;
// loop over bcs
for (bcfm_it_type bcfm_it = bc_field_managers.begin();
bcfm_it != bc_field_managers.end(); ++bcfm_it) {
const panzer::BC& bc = bcfm_it->first;
const std::map<unsigned,PHX::FieldManager<panzer::Traits> > bc_fm =
bcfm_it->second;
panzer::WorksetDescriptor desc = panzer::bcDescriptor(bc);
Teuchos::RCP<const std::map<unsigned,panzer::Workset> > bc_wkst_ptr = wkstContainer->getSideWorksets(desc);
TEUCHOS_TEST_FOR_EXCEPTION(bc_wkst_ptr == Teuchos::null, std::logic_error,
"Failed to find corresponding bc workset!");
const std::map<unsigned,panzer::Workset>& bc_wkst = *bc_wkst_ptr;
// Only process bcs of the appropriate type (neumann or dirichlet)
if (bc.bcType() == bc_type) {
std::ostringstream timerName;
timerName << "panzer::AssemblyEngine::evaluateBCs: " << bc.identifier();
#ifdef PANZER_TEUCHOS_TIME_MONITOR
auto timer1 = Teuchos::TimeMonitor::getNewTimer(timerName.str());
Teuchos::TimeMonitor tm1(*timer1);
#endif
// Loop over local faces
for (std::map<unsigned,PHX::FieldManager<panzer::Traits> >::const_iterator side = bc_fm.begin(); side != bc_fm.end(); ++side) {
std::ostringstream timerSideName;
timerSideName << "panzer::AssemblyEngine::evaluateBCs: " << bc.identifier() << ", side=" << side->first;
#ifdef PANZER_TEUCHOS_TIME_MONITOR
auto timer2 = Teuchos::TimeMonitor::getNewTimer(timerSideName.str());
Teuchos::TimeMonitor tm2(*timer2);
#endif
// extract field manager for this side
unsigned local_side_index = side->first;
PHX::FieldManager<panzer::Traits>& local_side_fm =
const_cast<PHX::FieldManager<panzer::Traits>& >(side->second);
// extract workset for this side: only one workset per face
std::map<unsigned,panzer::Workset>::const_iterator wkst_it =
bc_wkst.find(local_side_index);
TEUCHOS_TEST_FOR_EXCEPTION(wkst_it == bc_wkst.end(), std::logic_error,
"Failed to find corresponding bc workset side!");
panzer::Workset& workset =
const_cast<panzer::Workset&>(wkst_it->second);
// run prevaluate
local_side_fm.template preEvaluate<EvalT>(ped);
// build and evaluate fields for the workset: only one workset per face
workset.alpha = in.alpha;
workset.beta = betaValue;
workset.time = in.time;
workset.gather_seeds = in.gather_seeds;
workset.evaluate_transient_terms = in.evaluate_transient_terms;
local_side_fm.template evaluateFields<EvalT>(workset);
// run postevaluate for consistency
local_side_fm.template postEvaluate<EvalT>(NULL);
}
}
}
}
}
//===========================================================================
//===========================================================================
template <typename EvalT>
void panzer::AssemblyEngine<EvalT>::
evaluateDirichletCondition(const panzer::AssemblyEngineInArgs& in)
{
panzer::Workset workset;
panzer::Traits::PED ped;
ped.gedc->addDataObject("Ghosted Container",in.ghostedContainer_);
in.fillGlobalEvaluationDataContainer(*(ped.gedc));
const std::shared_ptr< PHX::FieldManager<panzer::Traits> > pfm = m_field_manager_builder->getDirichletFieldManager();
if( pfm == nullptr ) return;
pfm->template preEvaluate<EvalT>(ped);
workset.pivot_dirichlet = in.pivot_dirichlet;
pfm->template evaluateFields<EvalT>(workset);
pfm->template postEvaluate<EvalT>(NULL);
}
//===========================================================================
template <typename EvalT>
void panzer::AssemblyEngine<EvalT>::
evaluateNeumannCondition(const panzer::AssemblyEngineInArgs& in)
{
panzer::Workset workset;
panzer::Traits::PED ped;
ped.gedc->addDataObject("Ghosted Container",in.ghostedContainer_);
in.fillGlobalEvaluationDataContainer(*(ped.gedc));
const std::shared_ptr< PHX::FieldManager<panzer::Traits> > pfm = m_field_manager_builder->getNeumannFieldManager();
if( pfm ) {
pfm->template preEvaluate<EvalT>(ped);
pfm->template evaluateFields<EvalT>(workset);
pfm->template postEvaluate<EvalT>(NULL);
}
}
#endif
|
// Onut
#include <onut/Files.h>
#include <onut/Settings.h>
#include <onut/Strings.h>
#include <onut/Window.h>
#include <onut/Maths.h>
// STL
#include <algorithm>
#include <fstream>
#include <sstream>
#include <string.h>
// Third party
#if defined(WIN32)
#include <dirent/dirent.h>
#include <windows.h>
#include <shlobj.h>
#include <objbase.h>
#elif defined(__linux__) || defined(__APPLE__)
#include <dirent.h>
#endif
#include "tinyfiledialogs/tinyfiledialogs.h"
namespace onut
{
std::string findFile(const std::string& name, const std::string& lookIn, bool deepSearch)
{
DIR* dir;
struct dirent* ent;
if ((dir = opendir(lookIn.c_str())) != NULL)
{
while ((ent = readdir(dir)) != NULL)
{
if (!strcmp(ent->d_name, "."))
{
continue;
}
else if (!strcmp(ent->d_name, ".."))
{
continue;
}
if (name == ent->d_name)
{
auto ret = lookIn + "/" + ent->d_name;
closedir(dir);
return ret;
}
if (ent->d_type & DT_DIR && deepSearch)
{
auto ret = findFile(name, lookIn + "/" + ent->d_name);
if (!ret.empty())
{
closedir(dir);
return ret;
}
}
}
closedir(dir);
}
return "";
}
std::vector<std::string> findAllFiles(const std::string& lookIn, const std::string& extension, bool deepSearch)
{
std::vector<std::string> ret;
bool all = extension == "*";
auto upExt = toUpper(extension);
DIR* dir;
struct dirent* ent;
if ((dir = opendir(lookIn.c_str())) != NULL)
{
while ((ent = readdir(dir)) != NULL)
{
if (!strcmp(ent->d_name, "."))
{
continue;
}
else if (!strcmp(ent->d_name, ".."))
{
continue;
}
if (ent->d_type & DT_DIR)
{
if (deepSearch)
{
auto ret2 = findAllFiles(lookIn + "/" + ent->d_name, extension, deepSearch);
ret.insert(ret.end(), ret2.begin(), ret2.end());
}
}
else
{
if (all)
{
ret.push_back(lookIn + "/" + ent->d_name);
}
else if (toUpper(getExtension(ent->d_name)) == upExt)
{
ret.push_back(lookIn + "/" + ent->d_name);
}
}
}
closedir(dir);
}
return std::move(ret);
}
std::string getPath(const std::string& filename)
{
return filename.substr(0, filename.find_last_of("\\/"));
}
std::string getFilename(const std::string& path)
{
auto pos = path.find_last_of("\\/");
if (pos == std::string::npos) return path;
return path.substr(pos + 1);
}
std::string getFilenameWithoutExtension(const std::string& path)
{
auto filename = getFilename(path);
auto pos = filename.find_last_of('.');
if (pos == std::string::npos) return filename;
return filename.substr(0, pos);
}
std::string getExtension(const std::string& filename)
{
auto pos = filename.find_last_of('.');
if (pos == std::string::npos) return "";
return toUpper(filename.substr(pos + 1));
}
std::string getSavePath()
{
#if defined(WIN32)
PWSTR path = NULL;
HRESULT r;
auto gameName = oSettings->getGameName();
if (gameName.empty()) gameName = "onut";
r = SHGetKnownFolderPath(FOLDERID_RoamingAppData, KF_FLAG_CREATE, NULL, &path);
if (path != NULL)
{
auto ret = onut::utf16ToUtf8(path) + "/" + gameName + "/";
CreateDirectoryA(ret.c_str(), NULL);
CoTaskMemFree(path);
std::replace(ret.begin(), ret.end(), '\\', '/');
return ret;
}
return "./";
#else
return "./";
#endif
}
std::string makeRelativePath(const std::string& in_path, const std::string& in_relativeTo)
{
auto path = in_path;
if (path.size() >= 2 && path[0] == '.' && (path[1] == '\\' || path[1] == '/'))
path = path.substr(2);
std::replace(path.begin(), path.end(), '\\', '/');
auto pathSplit = splitString(path, '/');
auto relativeTo = in_relativeTo;
std::replace(relativeTo.begin(), relativeTo.end(), '\\', '/');
auto relativeSplit = splitString(relativeTo, '/');
while (pathSplit.size() && relativeSplit.size() && pathSplit.front() == relativeSplit.front())
{
pathSplit.erase(pathSplit.begin());
relativeSplit.erase(relativeSplit.begin());
}
std::stringstream ss;
bool bFirst = true;
for (auto& folder : relativeSplit)
{
if (!bFirst) ss << "/";
bFirst = false;
ss << "..";
}
for (auto& folder : pathSplit)
{
if (!bFirst) ss << "/";
bFirst = false;
ss << folder;
}
return std::move(ss.str());
}
std::vector<uint8_t> getFileData(const std::string& filename)
{
std::ifstream file(filename, std::ios::binary);
std::vector<uint8_t> data = { std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>() };
return std::move(data);
}
std::string getFileString(const std::string& filename)
{
auto data = getFileData(filename);
std::string str((const char* const)data.data(), data.size());
return std::move(str);
}
/*
std::string showOpenDialog(const std::string& caption, const FileTypes& extensions, const std::string& defaultFilename)
{
std::string pattern = "{";
pattern += "}";
auto pPath = tinyfd_openFileDialog(
"Browse Game",
defaultFilename.c_str(),
(int)extensions.size(),
NULL,
NULL,
0);
if (!pPath) return "";
return pPath;
}
std::string showSaveAsDialog(const std::string& caption, const FileTypes& extensions, const std::string& defaultFilename)
{
return "";
}
*/
std::string showOpenFolderDialog(const std::string& caption, const std::string& defaultPath)
{
auto pPath = tinyfd_selectFolderDialog(caption.c_str(), defaultPath.c_str());
if (!pPath) return "";
return pPath;
}
//char const * tinyfd_saveFileDialog(
// char const * const aTitle, /* "" */
// char const * const aDefaultPathAndFile, /* "" */
// int const aNumOfFilterPatterns, /* 0 */
// char const * const * const aFilterPatterns, /* NULL | {"*.jpg","*.png"} */
// char const * const aSingleFilterDescription); /* NULL | "text files" */
// /* returns NULL on cancel */
//char const * tinyfd_openFileDialog(
// char const * const aTitle, /* "" */
// char const * const aDefaultPathAndFile, /* "" */
// int const aNumOfFilterPatterns, /* 0 */
// char const * const * const aFilterPatterns, /* NULL {"*.jpg","*.png"} */
// char const * const aSingleFilterDescription, /* NULL | "image files" */
// int const aAllowMultipleSelects); /* 0 or 1 */
// /* in case of multiple files, the separator is | */
// /* returns NULL on cancel */
#if defined(WIN32)
bool fileExists(const std::string& filename)
{
WIN32_FIND_DATAA FindFileData;
HANDLE handle = FindFirstFileA(filename.c_str(), &FindFileData);
bool found = handle != INVALID_HANDLE_VALUE;
if (found)
{
//FindClose(&handle); this will crash
FindClose(handle);
}
return found;
}
std::string showOpenDialog(const std::string& caption, const FileTypes& extensions, const std::string& defaultFilename)
{
auto windowHandle = oWindow->getHandle();
char szFileName[MAX_PATH] = { 0 };
memcpy(szFileName, defaultFilename.c_str(), std::min(defaultFilename.size(), static_cast<size_t>(MAX_PATH - 1)));
OPENFILENAMEA ofn = { 0 };
ofn.lStructSize = sizeof(OPENFILENAMEA);
ofn.hwndOwner = windowHandle;
ofn.lStructSize = sizeof(ofn);
ofn.lpstrFile = szFileName;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR;
size_t totalCount = 0;
for (auto& fileType : extensions)
{
totalCount += fileType.typeName.size();
totalCount += fileType.extension.size();
}
char* szFilters = new char[21 + totalCount * 3 + 9 * extensions.size()];
size_t currentOffset = 0;
for (auto& fileType : extensions)
{
memcpy(szFilters + currentOffset, fileType.typeName.c_str(), fileType.typeName.size());
currentOffset += fileType.typeName.size();
memcpy(szFilters + currentOffset, " (*.", 4);
currentOffset += 4;
memcpy(szFilters + currentOffset, fileType.extension.c_str(), fileType.extension.size());
currentOffset += fileType.extension.size();
memcpy(szFilters + currentOffset, ")\0*.", 4);
currentOffset += 4;
memcpy(szFilters + currentOffset, fileType.extension.c_str(), fileType.extension.size());
currentOffset += fileType.extension.size();
memcpy(szFilters + currentOffset, "\0", 1);
currentOffset += 1;
}
memcpy(szFilters + currentOffset, "All Files (*.*)\0*.*\0\0", 21);
ofn.lpstrFilter = szFilters;
std::string defaultExtension = extensions[0].extension;
ofn.lpstrDefExt = defaultExtension.c_str();
ofn.lpstrTitle = caption.c_str();
// PNG Files (*.PNG)\0*.PNG\0All Files (*.*)\0*.*\0
GetOpenFileNameA(&ofn);
delete[] szFilters;
return ofn.lpstrFile;
}
std::string showSaveAsDialog(const std::string& caption, const FileTypes& extensions, const std::string& defaultFilename)
{
auto windowHandle = oWindow->getHandle();
char szFileName[MAX_PATH] = { 0 };
memcpy(szFileName, defaultFilename.c_str(), std::min(defaultFilename.size(), static_cast<size_t>(MAX_PATH - 1)));
OPENFILENAMEA ofn = { 0 };
ofn.lStructSize = sizeof(OPENFILENAMEA);
ofn.hwndOwner = windowHandle;
ofn.lStructSize = sizeof(ofn);
ofn.lpstrFile = szFileName;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR;
size_t totalCount = 0;
for (auto& fileType : extensions)
{
totalCount += fileType.typeName.size();
totalCount += fileType.extension.size();
}
char* szFilters = new char[21 + totalCount * 3 + 9 * extensions.size()];
size_t currentOffset = 0;
for (auto& fileType : extensions)
{
memcpy(szFilters + currentOffset, fileType.typeName.c_str(), fileType.typeName.size());
currentOffset += fileType.typeName.size();
memcpy(szFilters + currentOffset, " (*.", 4);
currentOffset += 4;
memcpy(szFilters + currentOffset, fileType.extension.c_str(), fileType.extension.size());
currentOffset += fileType.extension.size();
memcpy(szFilters + currentOffset, ")\0*.", 4);
currentOffset += 4;
memcpy(szFilters + currentOffset, fileType.extension.c_str(), fileType.extension.size());
currentOffset += fileType.extension.size();
memcpy(szFilters + currentOffset, "\0", 1);
currentOffset += 1;
}
memcpy(szFilters + currentOffset, "All Files (*.*)\0*.*\0\0", 21);
ofn.lpstrFilter = szFilters;
std::string defaultExtension = extensions[0].extension;
ofn.lpstrDefExt = defaultExtension.c_str();
ofn.lpstrTitle = caption.c_str();
// PNG Files (*.PNG)\0*.PNG\0All Files (*.*)\0*.*\0
GetSaveFileNameA(&ofn);
delete[] szFilters;
return ofn.lpstrFile;
}
#endif
bool createFolder(const std::string& fullPath)
{
#if defined(WIN32)
std::string withBackwardSlashes = fullPath;
onut::replace(withBackwardSlashes, "/", "\\");
return system(("mkdir " + withBackwardSlashes).c_str()) == 0;
#else
return system(("mkdir " + fullPath).c_str()) == 0;
#endif
}
bool copyFile(const std::string& from, const std::string& to)
{
#if defined(WIN32)
std::string withBackwardSlashes_from = from;
onut::replace(withBackwardSlashes_from, "/", "\\");
std::string withBackwardSlashes_to = to;
onut::replace(withBackwardSlashes_to, "/", "\\");
std::ifstream src(withBackwardSlashes_from, std::ios::binary);
std::ofstream dst(withBackwardSlashes_to, std::ios::binary);
if (!src.is_open() || !dst.is_open()) return false;
dst << src.rdbuf();
src.close();
dst.close();
return true;
#else
return system(("cp " + from + " " + to).c_str()) == 0;
#endif
}
bool createTextFile(const std::string& path, const std::string& content)
{
#if defined(WIN32)
std::string withBackwardSlashes = path;
onut::replace(withBackwardSlashes, "/", "\\");
std::ofstream dst(withBackwardSlashes, std::ios::binary);
if (!dst.is_open()) return false;
dst << content;
dst.close();
return true;
#else
std::ofstream dst(path, std::ios::binary);
if (!dst.is_open()) return false;
dst << content;
dst.close();
return true;
#endif
}
void showInExplorer(const std::string& path)
{
#if defined(WIN32)
system(("explorer " + path).c_str());
#elif defined(__APPLE__)
system(("open " + path).c_str());
#else
system(("xdg-open " + path).c_str());
#endif
}
void openFile(const std::string& path)
{
#if defined(WIN32)
ShellExecuteA(0, 0, path.c_str(), 0, 0 , SW_SHOW);
#endif
}
MessageBoxReturn showMessageBox(const std::string& title, const std::string& message, MessageBoxType type, MessageBoxLevel level)
{
const char* typeStr;
switch (type)
{
case MessageBoxType::Ok: typeStr = "ok"; break;
case MessageBoxType::OkCancel: typeStr = "okcancel"; break;
case MessageBoxType::YesNo: typeStr = "yesno"; break;
case MessageBoxType::YesNoCancel: typeStr = "yesnocancel"; break;
}
const char* iconStr;
switch (level)
{
case MessageBoxLevel::Info: iconStr = "info"; break;
case MessageBoxLevel::Warning: iconStr = "warning"; break;
case MessageBoxLevel::Error: iconStr = "error"; break;
case MessageBoxLevel::Question: iconStr = "question"; break;
}
auto ret = tinyfd_messageBox(
title.c_str(),
message.c_str(),
typeStr,
iconStr,
1);
return (MessageBoxReturn)ret;
}
void writeInt8(int8_t val, FILE* pFile)
{
fwrite(&val, sizeof(int8_t), 1, pFile);
}
void writeUInt8(uint8_t val, FILE* pFile)
{
fwrite(&val, sizeof(uint8_t), 1, pFile);
}
void writeInt16(int16_t val, FILE* pFile)
{
fwrite(&val, sizeof(int16_t), 1, pFile);
}
void writeUInt16(uint16_t val, FILE* pFile)
{
fwrite(&val, sizeof(uint16_t), 1, pFile);
}
void writeInt32(int32_t val, FILE* pFile)
{
fwrite(&val, sizeof(int32_t), 1, pFile);
}
void writeUInt32(uint32_t val, FILE* pFile)
{
fwrite(&val, sizeof(uint32_t), 1, pFile);
}
void writeInt64(int64_t val, FILE* pFile)
{
fwrite(&val, sizeof(int64_t), 1, pFile);
}
void writeUInt64(uint64_t val, FILE* pFile)
{
fwrite(&val, sizeof(uint64_t), 1, pFile);
}
void writeFloat(float val, FILE* pFile)
{
fwrite(&val, sizeof(float), 1, pFile);
}
void writeDouble(double val, FILE* pFile)
{
fwrite(&val, sizeof(double), 1, pFile);
}
void writeBool(bool val, FILE* pFile)
{
uint8_t vali = val ? 1 : 0;
fwrite(&vali, sizeof(uint8_t), 1, pFile);
}
void writeString(const std::string& val, FILE* pFile)
{
fwrite(val.c_str(), 1, val.size() + 1, pFile);
}
void writeVector2(const Vector2& val, FILE* pFile)
{
fwrite(&val, sizeof(float), 2, pFile);
}
void writeVector3(const Vector3& val, FILE* pFile)
{
fwrite(&val, sizeof(float), 3, pFile);
}
void writeVector4(const Vector4& val, FILE* pFile)
{
fwrite(&val, sizeof(float), 4, pFile);
}
void writeRect(const Rect& val, FILE* pFile)
{
fwrite(&val, sizeof(float), 4, pFile);
}
void writeiRect(const iRect& val, FILE* pFile)
{
writeInt32((int)val.left, pFile);
writeInt32((int)val.top, pFile);
writeInt32((int)val.right, pFile);
writeInt32((int)val.bottom, pFile);
}
void writePoint(const Point& val, FILE* pFile)
{
writeInt32((int)val.x, pFile);
writeInt32((int)val.y, pFile);
}
void writeColor(const Color& val, FILE* pFile)
{
fwrite(&val, sizeof(float), 4, pFile);
}
void writeMatrix(const Matrix& val, FILE* pFile)
{
fwrite(&val, sizeof(float), 16, pFile);
}
int8_t readInt8(FILE* pFile)
{
int8_t val;
fread(&val, sizeof(int8_t), 1, pFile);
return val;
}
uint8_t readUInt8(FILE* pFile)
{
uint8_t val;
fread(&val, sizeof(uint8_t), 1, pFile);
return val;
}
int16_t readInt16(FILE* pFile)
{
int16_t val;
fread(&val, sizeof(int16_t), 1, pFile);
return val;
}
uint16_t readUInt16(FILE* pFile)
{
uint16_t val;
fread(&val, sizeof(uint16_t), 1, pFile);
return val;
}
int32_t readInt32(FILE* pFile)
{
int32_t val;
fread(&val, sizeof(int32_t), 1, pFile);
return val;
}
uint32_t readUInt32(FILE* pFile)
{
uint32_t val;
fread(&val, sizeof(uint32_t), 1, pFile);
return val;
}
float readFloat(FILE* pFile)
{
float val;
fread(&val, sizeof(float), 1, pFile);
return val;
}
double readDouble(FILE* pFile)
{
double val;
fread(&val, sizeof(double), 1, pFile);
return val;
}
bool readBool(FILE* pFile)
{
uint8_t vali;
fread(&vali, sizeof(uint8_t), 1, pFile);
return vali ? true : false;
}
std::string readString(FILE* pFile)
{
std::string val;
char c;
do
{
auto readret = fread(&c, sizeof(c), 1, pFile);
if (feof(pFile)) break;
(void)readret;
if (c) val += c;
} while (c);
return val;
}
Vector2 readVector2(FILE* pFile)
{
Vector2 val;
fread(&val, sizeof(float), 2, pFile);
return val;
}
Vector3 readVector3(FILE* pFile)
{
Vector3 val;
fread(&val, sizeof(float), 3, pFile);
return val;
}
Vector4 readVector4(FILE* pFile)
{
Vector4 val;
fread(&val, sizeof(float), 4, pFile);
return val;
}
Rect readRect(FILE* pFile)
{
Rect val;
fread(&val, sizeof(float), 4, pFile);
return val;
}
iRect readiRect(FILE* pFile)
{
iRect val;
val.left = (int)readInt32(pFile);
val.top = (int)readInt32(pFile);
val.right = (int)readInt32(pFile);
val.bottom = (int)readInt32(pFile);
return val;
}
Point readPoint(FILE* pFile)
{
Point val;
val.x = (int)readInt32(pFile);
val.y = (int)readInt32(pFile);
return val;
}
Color readColor(FILE* pFile)
{
Color val;
fread(&val, sizeof(float), 4, pFile);
return val;
}
Matrix readMatrix(FILE* pFile)
{
Matrix val;
fread(&val, sizeof(float), 16, pFile);
return val;
}
}
|
#include "gps_imu_fixed_lag_fuser.h"
#include "gps_source.h"
#include "imu_source.h"
#include "nav/attitude.h"
#include "trigonometry.h"
int main()
{
// Create data sources.
GpsSource gps_src("../data/GPS_Data_0000.bin");
ImuSource imu_src("../data/IMU_Data_0000.bin");
// Skip GPS data before init_time.
const double init_time = 1485176340.0;
while (gps_src.nextTime() < init_time)
{
gps_src.pop();
}
// Skip IMU data before first remaining GPS measurement.
while (imu_src.nextTime() <= gps_src.nextTime())
{
imu_src.pop();
}
// Initialize fuser with first GPS measurement and (bad) guess on initial attitude.
GpsImuFixedLagFuser fuser(
gps_src.next(),
nav::Attitude(0.0, 0.0, trig::deg2rad(45.0)),
nav::Attitude(trig::deg2rad(10.0), trig::deg2rad(10.0), trig::deg2rad(180.0))
);
gps_src.pop();
// Run fuser.
while (gps_src.hasNext() || imu_src.hasNext())
{
if (imu_src.nextTime() < gps_src.nextTime())
{
fuser.addImuData(imu_src.next());
imu_src.pop();
}
else
{
fuser.addGpsData(gps_src.next());
gps_src.pop();
}
}
return EXIT_SUCCESS;
}
|
#ifndef COMMON_CURSOR_POSITION_CHANGED_HPP
#define COMMON_CURSOR_POSITION_CHANGED_HPP
#include "Event.hpp"
class CursorPositionChanged : public Event {
private:
double xPosition, yPosition;
public:
CursorPositionChanged (double xPosition, double yPosition);
EventType type();
double getXPosition();
double getYPosition();
};
#endif // COMMON_CURSOR_POSITION_CHANGED_HPP
|
// Copyright (C) 2018 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
#include <gtest/gtest.h>
#include <gmock/gmock-spec-builders.h>
#include "mkldnn_plugin/mkldnn_graph.h"
#include "mock_mkldnn_primitive.hpp"
#include "single_layer_common.hpp"
#include <mkldnn_plugin/mkldnn_extension_utils.h>
#include <mkldnn_plugin/mkldnn_extension_mngr.h>
#include "tests_common.hpp"
#include "../test_graph.hpp"
using namespace ::testing;
using namespace std;
using namespace mkldnn;
class MKLDNNGraphOptimizationTests: public TestsCommon {};
TEST_F(MKLDNNGraphOptimizationTests, TestNoFuseConvSumWithOneInput) {
std::string model = R"V0G0N(
<net name="AlexNet" version="2" batch="1">
<layers>
<layer name="data" type="Input" precision="FP32" id="0">
<output>
<port id="0">
<dim>1</dim>
<dim>3</dim>
<dim>5</dim>
<dim>5</dim>
</port>
</output>
</layer>
<layer name="conv1" type="Convolution" precision="FP32" id="1">
<convolution_data stride-x="1" stride-y="1" pad-x="0" pad-y="0" kernel-x="1" kernel-y="1" output="3" group="1"/>
<input>
<port id="1">
<dim>1</dim>
<dim>3</dim>
<dim>5</dim>
<dim>5</dim>
</port>
</input>
<output>
<port id="2">
<dim>1</dim>
<dim>3</dim>
<dim>5</dim>
<dim>5</dim>
</port>
</output>
<weights offset="0" size="36"/>
<biases offset="36" size="12"/>
</layer>
<layer name="res2a" type="Eltwise" precision="FP32" id="2">
<elementwise_data operation="sum"/>
<input>
<port id="3">
<dim>1</dim>
<dim>3</dim>
<dim>5</dim>
<dim>5</dim>
</port>
<port id="4">
<dim>1</dim>
<dim>3</dim>
<dim>5</dim>
<dim>5</dim>
</port>
</input>
<output>
<port id="5">
<dim>1</dim>
<dim>3</dim>
<dim>5</dim>
<dim>5</dim>
</port>
</output>
</layer>
</layers>
<edges>
<edge from-layer="0" from-port="0" to-layer="1" to-port="1"/>
<edge from-layer="0" from-port="0" to-layer="2" to-port="3"/>
<edge from-layer="1" from-port="2" to-layer="2" to-port="4"/>
</edges>
</net>
)V0G0N";
InferenceEngine::CNNNetReader net_reader;
ASSERT_NO_THROW(net_reader.ReadNetwork(model.data(), model.length()));
InferenceEngine::TBlob<uint8_t> *weights = new InferenceEngine::TBlob<uint8_t>(InferenceEngine::Precision::U8, InferenceEngine::C, {48});
weights->allocate();
float * data = weights->buffer();
fill_data((float *) weights->buffer(), weights->size() / sizeof(float));
InferenceEngine::TBlob<uint8_t>::Ptr weights_ptr = InferenceEngine::TBlob<uint8_t>::Ptr(weights);
net_reader.SetWeights(weights_ptr);
MKLDNNGraphTestClass graph;
ASSERT_NO_THROW(graph.CreateGraph(net_reader.getNetwork()));
bool fused = true;
auto& nodes = graph.getNodes();
for (auto &node : nodes) {
if (node->getType() == MKLDNNPlugin::Convolution) {
fused = false;
}
}
ASSERT_FALSE(fused);
}
TEST_F(MKLDNNGraphOptimizationTests, TestNoCrashForFuseConvSumAndInput) {
std::string model = R"V0G0N(
<net name="AlexNet" version="2" batch="1">
<layers>
<layer name="data" type="Input" precision="FP32" id="0">
<output>
<port id="0">
<dim>1</dim>
<dim>3</dim>
<dim>5</dim>
<dim>5</dim>
</port>
</output>
</layer>
<layer name="conv1" type="Convolution" precision="FP32" id="1">
<convolution_data stride-x="1" stride-y="1" pad-x="0" pad-y="0" kernel-x="1" kernel-y="1" output="3" group="1"/>
<input>
<port id="1">
<dim>1</dim>
<dim>3</dim>
<dim>5</dim>
<dim>5</dim>
</port>
</input>
<output>
<port id="2">
<dim>1</dim>
<dim>3</dim>
<dim>5</dim>
<dim>5</dim>
</port>
</output>
<weights offset="0" size="36"/>
<biases offset="36" size="12"/>
</layer>
<layer name="relu1" type="ReLU" precision="FP32" id="2">
<input>
<port id="1">
<dim>1</dim>
<dim>3</dim>
<dim>5</dim>
<dim>5</dim>
</port>
</input>
<output>
<port id="2">
<dim>1</dim>
<dim>3</dim>
<dim>5</dim>
<dim>5</dim>
</port>
</output>
</layer>
<layer name="res2a" type="Eltwise" precision="FP32" id="3">
<elementwise_data operation="sum"/>
<input>
<port id="3">
<dim>1</dim>
<dim>3</dim>
<dim>5</dim>
<dim>5</dim>
</port>
<port id="4">
<dim>1</dim>
<dim>3</dim>
<dim>5</dim>
<dim>5</dim>
</port>
</input>
<output>
<port id="5">
<dim>1</dim>
<dim>3</dim>
<dim>5</dim>
<dim>5</dim>
</port>
</output>
</layer>
</layers>
<edges>
<edge from-layer="0" from-port="0" to-layer="1" to-port="1"/>
<edge from-layer="0" from-port="0" to-layer="2" to-port="1"/>
<edge from-layer="1" from-port="2" to-layer="3" to-port="3"/>
<edge from-layer="2" from-port="2" to-layer="3" to-port="4"/>
</edges>
</net>
)V0G0N";
InferenceEngine::CNNNetReader net_reader;
ASSERT_NO_THROW(net_reader.ReadNetwork(model.data(), model.length()));
InferenceEngine::TBlob<uint8_t> *weights = new InferenceEngine::TBlob<uint8_t>(InferenceEngine::Precision::U8, InferenceEngine::C, {48});
weights->allocate();
float * data = weights->buffer();
fill_data((float *) weights->buffer(), weights->size() / sizeof(float));
InferenceEngine::TBlob<uint8_t>::Ptr weights_ptr = InferenceEngine::TBlob<uint8_t>::Ptr(weights);
net_reader.SetWeights(weights_ptr);
MKLDNNGraphTestClass graph;
ASSERT_NO_THROW(graph.CreateGraph(net_reader.getNetwork()));
bool fused = false;
auto& nodes = graph.getNodes();
for (auto &node : nodes) {
if (node->getType() == MKLDNNPlugin::Convolution_Sum) {
fused = true;
}
}
ASSERT_TRUE(fused);
}
namespace GraphOptimizationUtils {
using fake_ext_factory = std::function<InferenceEngine::ILayerImplFactory*(const InferenceEngine::CNNLayer *)>;
class FakeReLUImpl : public InferenceEngine::ILayerExecImpl {
public:
FakeReLUImpl(const InferenceEngine::CNNLayer *layer) {
cnnLayer = const_cast<InferenceEngine::CNNLayer *>(layer);
}
InferenceEngine::StatusCode getSupportedConfigurations(std::vector<InferenceEngine::LayerConfig>& conf, InferenceEngine::ResponseDesc *resp) noexcept override {
InferenceEngine::LayerConfig config;
config.dynBatchSupport = 0;
if (cnnLayer->outData.size() != 1 && cnnLayer->insData.size() != 1)
return InferenceEngine::GENERAL_ERROR;
InferenceEngine::DataConfig cfg;
cfg.constant = false;
cfg.inPlace = 0;
InferenceEngine::SizeVector order;
for(size_t i = 0; i < cnnLayer->outData[0]->getTensorDesc().getDims().size(); i++) {
order.push_back(i);
}
cfg.desc = InferenceEngine::TensorDesc(cnnLayer->outData[0]->getTensorDesc().getPrecision(),
cnnLayer->outData[0]->getTensorDesc().getDims(),
{cnnLayer->outData[0]->getTensorDesc().getDims(), order});
config.outConfs.push_back(cfg);
config.inConfs.push_back(cfg);
conf.push_back(config);
return InferenceEngine::OK;
}
InferenceEngine::StatusCode init(InferenceEngine::LayerConfig& config, InferenceEngine::ResponseDesc *resp) noexcept override {
if (config.dynBatchSupport)
return InferenceEngine::NOT_IMPLEMENTED;
for(auto input : config.inConfs) {
if (input.constant)
return InferenceEngine::GENERAL_ERROR;
}
for(auto output : config.outConfs) {
if (output.constant)
return InferenceEngine::GENERAL_ERROR;
}
return InferenceEngine::OK;
}
InferenceEngine::StatusCode execute(std::vector<InferenceEngine::Blob::Ptr>& inputs, std::vector<InferenceEngine::Blob::Ptr>& outputs, InferenceEngine::ResponseDesc *resp) noexcept override {
const float *src_data = inputs[0]->buffer();
float *dst_data = outputs[0]->buffer();
if (src_data != dst_data)
return InferenceEngine::GENERAL_ERROR;
return InferenceEngine::OK;
}
private:
InferenceEngine::CNNLayer* cnnLayer;
};
class FakeReLUFactory : public InferenceEngine::ILayerImplFactory {
public:
FakeReLUFactory(const InferenceEngine::CNNLayer *layer) {
cnnLayer = const_cast<InferenceEngine::CNNLayer *>(layer);
}
// set output shapes by input shapes.
InferenceEngine::StatusCode getShapes(const std::vector<InferenceEngine::TensorDesc>& inShapes, std::vector<InferenceEngine::TensorDesc>& outShapes, InferenceEngine::ResponseDesc *resp) noexcept override {
outShapes.push_back(inShapes[0]);
return InferenceEngine::OK;
}
// First implementation has more priority than next
InferenceEngine::StatusCode getImplementations(std::vector<InferenceEngine::ILayerImpl::Ptr>& impls, InferenceEngine::ResponseDesc *resp) noexcept override {
impls.push_back(InferenceEngine::ILayerImpl::Ptr(new FakeReLUImpl(cnnLayer)));
return InferenceEngine::OK;
}
private:
InferenceEngine::CNNLayer * cnnLayer;
};
class FakeFabric : public InferenceEngine::IExtension {
public:
FakeFabric() {
factories["ReLU"] = [](const InferenceEngine::CNNLayer * cnnLayer) -> InferenceEngine::ILayerImplFactory* { return new FakeReLUFactory(cnnLayer); };
}
virtual ~FakeFabric() {
factories.clear();
}
void GetVersion(const InferenceEngine::Version *&versionInfo) const noexcept override {}
void SetLogCallback(InferenceEngine::IErrorListener &listener) noexcept override {}
void Unload() noexcept override {}
void Release() noexcept override {
delete this;
}
InferenceEngine::StatusCode getPrimitiveTypes(char**& types, unsigned int& size, InferenceEngine::ResponseDesc* resp) noexcept override {
types = new char *[factories.size()];
size_t count = 0;
for (auto it = factories.begin(); it != factories.end(); it++, count ++) {
types[count] = new char[it->first.size() + 1];
std::copy(it->first.begin(), it->first.end(), types[count]);
types[count][it->first.size() ] = '\0';
}
return InferenceEngine::OK;
};
InferenceEngine::StatusCode getFactoryFor(InferenceEngine::ILayerImplFactory *&factory,
const InferenceEngine::CNNLayer *cnnLayer,
InferenceEngine::ResponseDesc *resp) noexcept override {
if (factories.find(cnnLayer->type) == factories.end()) {
std::string errorMsg = std::string("Factory for ") + cnnLayer->type + " wasn't found!";
errorMsg.copy(resp->msg, sizeof(resp->msg) - 1);
return InferenceEngine::NOT_FOUND;
}
factory = factories[cnnLayer->type](cnnLayer);
return InferenceEngine::OK;
}
InferenceEngine::StatusCode getShapeInferImpl(InferenceEngine::IShapeInferImpl::Ptr& impl, const char* type,
InferenceEngine::ResponseDesc* resp) noexcept override {
return InferenceEngine::NOT_IMPLEMENTED;
}
private:
std::map<std::string, fake_ext_factory> factories;
};
}
TEST_F(MKLDNNGraphOptimizationTests, TestNoFuseCustomActivation) {
std::string model = R"V0G0N(
<net name="AlexNet" version="2" batch="1">
<layers>
<layer name="data" type="Input" precision="FP32" id="0">
<output>
<port id="0">
<dim>1</dim>
<dim>3</dim>
<dim>227</dim>
<dim>227</dim>
</port>
</output>
</layer>
<layer name="conv1" type="Convolution" precision="FP32" id="1">
<convolution_data stride-x="4" stride-y="4" pad-x="0" pad-y="0" kernel-x="11" kernel-y="11" output="96" group="1"/>
<input>
<port id="1">
<dim>1</dim>
<dim>3</dim>
<dim>227</dim>
<dim>227</dim>
</port>
</input>
<output>
<port id="2">
<dim>1</dim>
<dim>96</dim>
<dim>55</dim>
<dim>55</dim>
</port>
</output>
<weights offset="0" size="139392"/>
<biases offset="139392" size="384"/>
</layer>
<layer name="relu1" type="ReLU" precision="FP32" id="2">
<input>
<port id="3">
<dim>1</dim>
<dim>96</dim>
<dim>55</dim>
<dim>55</dim>
</port>
</input>
<output>
<port id="4">
<dim>1</dim>
<dim>96</dim>
<dim>55</dim>
<dim>55</dim>
</port>
</output>
</layer>
</layers>
<edges>
<edge from-layer="0" from-port="0" to-layer="1" to-port="1"/>
<edge from-layer="1" from-port="2" to-layer="2" to-port="3"/>
</edges>
</net>
)V0G0N";
std::shared_ptr<InferenceEngine::IExtension> extension;
extension.reset(new GraphOptimizationUtils::FakeFabric());
MKLDNNPlugin::MKLDNNExtensionManager::Ptr extMgr(new MKLDNNPlugin::MKLDNNExtensionManager());
extMgr->AddExtension(extension);
InferenceEngine::CNNNetReader net_reader;
ASSERT_NO_THROW(net_reader.ReadNetwork(model.data(), model.length()));
InferenceEngine::TBlob<uint8_t> *weights = new InferenceEngine::TBlob<uint8_t>(InferenceEngine::Precision::U8, InferenceEngine::C, {139776});
weights->allocate();
float * data = weights->buffer();
fill_data((float *) weights->buffer(), weights->size() / sizeof(float));
InferenceEngine::TBlob<uint8_t>::Ptr weights_ptr = InferenceEngine::TBlob<uint8_t>::Ptr(weights);
net_reader.SetWeights(weights_ptr);
MKLDNNGraphTestClass graph;
ASSERT_NO_THROW(graph.CreateGraph(net_reader.getNetwork(), extMgr));
bool fused = true;
auto& nodes = graph.getNodes();
for (auto &node : nodes) {
if (node->getType() == MKLDNNPlugin::Convolution) {
fused = false;
}
}
ASSERT_FALSE(fused);
}
|
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
template<typename Signature>
struct bug210194_function_traits;
template<typename R, typename... ArgTypes>
struct bug210194_function_traits<R(ArgTypes...)> {
typedef R result_type;
};
template<typename T, typename U>
struct bug210194_same_type {
static const bool value = false;
};
template<typename T>
struct bug210194_same_type<T, T> {
static const bool value = true;
};
int bug210194_a0[bug210194_same_type<bug210194_function_traits<int()>::result_type, int>::value? 1 : -1];
int bug210194_a1[bug210194_same_type<bug210194_function_traits<int(float)>::result_type, int>::value? 1 : -1];
int bug210194_a2[bug210194_same_type<bug210194_function_traits<int(double, char)>::result_type, int>::value? 1 : -1];
|
// (C) Copyright 2003 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
// PlotApiDialog.cpp : implementation file
//
#include "stdafx.h"
#include "PlotApiDialog.h"
#include "AcPlPlotEngine.h"
#include "acplplotfactory.h"
#include "acplplotinfo.h"
#include "acplplotinfovalidator.h"
#include "axlock.h"
#include "AsdkPlotApiDialog.h"
// CPlotApiDialog dialog
IMPLEMENT_DYNAMIC(CPlotApiDialog, CDialog)
CPlotApiDialog::CPlotApiDialog(CWnd* pParent /*=NULL*/)
: CDialog(CPlotApiDialog::IDD, pParent)
, m_Scale(0)
, m_Landscape(FALSE)
, m_CurrentDevice(_T(""))
, pPSV(NULL)
, m_bFit(FALSE)
, m_Background(FALSE)
, m_bPlotToFile(FALSE)
, m_csFilename(_T(""))
,dwAppCF(0)
,dwAppObj(0)
,pPlotSink(NULL)
{
}
CPlotApiDialog::~CPlotApiDialog()
{
}
void CPlotApiDialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_DEVICES, m_Devices);
DDX_Control(pDX, IDC_MEDIA, m_Media);
DDX_Text(pDX, IDC_SCALE, m_Scale);
DDX_Check(pDX, IDC_LANDSCAPE, m_Landscape);
DDX_Check(pDX, IDC_FIT, m_bFit);
DDX_Check(pDX, IDC_BACKGROUND, m_Background);
DDX_Check(pDX, IDC_PLOTTOFILE, m_bPlotToFile);
DDX_Text(pDX, IDC_FILENAME, m_csFilename);
}
BEGIN_MESSAGE_MAP(CPlotApiDialog, CDialog)
ON_CBN_SELCHANGE(IDC_DEVICES, OnCbnSelchangeDevices)
ON_CBN_SELCHANGE(IDC_MEDIA, OnCbnSelchangeMedia)
ON_BN_CLICKED(IDC_PLOT, OnBnClickedPlot)
ON_WM_DESTROY()
ON_BN_CLICKED(IDC_PREVIEW, OnBnClickedPreview)
ON_BN_CLICKED(IDC_LANDSCAPE, OnBnClickedLandscape)
ON_BN_CLICKED(IDC_FIT, OnBnClickedFit)
ON_BN_CLICKED(IDC_BACKGROUND, OnBnClickedBackground)
ON_EN_CHANGE(IDC_SCALE, OnEnChangeScale)
ON_BN_CLICKED(IDC_PLOTTOFILE, OnBnClickedPlottofile)
ON_BN_CLICKED(IDCANCEL, OnBnClickedCancel)
END_MESSAGE_MAP()
// CPlotApiDialog message handlers
void CPlotApiDialog::OnCbnSelchangeDevices()
{
AcAxDocLock lock;
m_Devices.GetLBText(m_Devices.GetCurSel(),m_CurrentDevice);
Acad::ErrorStatus es=pPSV->setPlotCfgName(pPlotSettings,m_CurrentDevice);
pPSV->refreshLists(pPlotSettings);
RefreshMediaNames();
if(m_bFit)
CalcExtents();
// Determine the device capabilities regarding plotting to file.
// We'll enable or disable the ability to select plot-to-file depending
// on the devices capability.
AcPlPlotConfig *pPlotConfig = NULL;
const char *szLocaleName;
if(Acad::eOk == acplPlotConfigManagerPtr()->setCurrentConfig(pPlotConfig,m_CurrentDevice))
{
if(pPlotConfig->plotToFileCapability()!=AcPlPlotConfig::kPlotToFileAllowed)
{
if(pPlotConfig->plotToFileCapability()==AcPlPlotConfig::kNoPlotToFile)
{
m_bPlotToFile=FALSE;
CEdit *pEdit=(CEdit*)GetDlgItem(IDC_FILENAME);
pEdit->EnableWindow(FALSE);
}
else
{ // kMustPlotToFile
m_bPlotToFile=TRUE;
CEdit *pEdit=(CEdit*)GetDlgItem(IDC_FILENAME);
pEdit->EnableWindow(TRUE);
}
// Either way, disable the PLOTTOFILE check box.
CButton *pButton=(CButton*)GetDlgItem(IDC_PLOTTOFILE);
pButton->EnableWindow(FALSE);
}
else
{
CEdit *pEdit=(CEdit*)GetDlgItem(IDC_FILENAME);
pEdit->EnableWindow(TRUE);
CButton *pButton=(CButton*)GetDlgItem(IDC_PLOTTOFILE);
pButton->EnableWindow(TRUE);
}
}
UpdateData(FALSE);
}
void CPlotApiDialog::OnCbnSelchangeMedia()
{
AcAxDocLock lock;
m_Media.UpdateData();
m_Media.GetLBText(m_Media.GetCurSel(),m_CurrentMedia);
Acad::ErrorStatus es=pPSV->setCanonicalMediaName(pPlotSettings,m_CurrentMedia);
if(m_bFit)
CalcExtents();
}
void CPlotApiDialog::OnBnClickedPlot()
{
Acad::ErrorStatus es;
AcAxDocLock lock;
es=pPSV->setPlotType(pPlotSettings,AcDbPlotSettings::kExtents);
// Set the Scale...
if (m_bFit)
{
es = pPSV->setUseStandardScale(pPlotSettings,Adesk::kTrue);
es = pPSV->setStdScaleType(pPlotSettings,StdScaleType::kScaleToFit);
}
else // Choose to use this custom scale...
{
es=pPSV->setUseStandardScale(pPlotSettings,Adesk::kFalse);
es=pPSV->setCustomPrintScale(pPlotSettings,m_Scale,1);
}
// Specify that we want our plot centered by AutoCAD...
es=pPSV->setPlotCentered(pPlotSettings,true);
// Create a publish engine, and send the plot through...
AcPlPlotEngine* pEngine = NULL;
if(Acad::eOk==AcPlPlotFactory::createPublishEngine(pEngine))
{
// Here is the progress dialog for the current plot process...
AcPlPlotProgressDialog *pPlotProgDlg = acplCreatePlotProgressDialog(acedGetAcadFrame()->m_hWnd,false,1);
pPlotProgDlg->setPlotMsgString(AcPlPlotProgressDialog::PlotMSGIndex::kDialogTitle,"Plot API Progress");
pPlotProgDlg->setPlotMsgString(AcPlPlotProgressDialog::PlotMSGIndex::kCancelJobBtnMsg,"Cancel Job");
pPlotProgDlg->setPlotMsgString(AcPlPlotProgressDialog::PlotMSGIndex::kCancelSheetBtnMsg,"Cancel Sheet");
pPlotProgDlg->setPlotMsgString(AcPlPlotProgressDialog::PlotMSGIndex::kSheetSetProgressCaption,"Job Progress");
pPlotProgDlg->setPlotMsgString(AcPlPlotProgressDialog::PlotMSGIndex::kSheetProgressCaption,"Sheet Progress");
pPlotProgDlg->setPlotProgressRange(0,100);
pPlotProgDlg->onBeginPlot();
pPlotProgDlg->setIsVisible(true);
es = pEngine->beginPlot(pPlotProgDlg);
AcPlPlotPageInfo pageInfo;
AcPlPlotInfo plotInfo; // Used to describe how the plot is to be made
// First, set the layout to the specified layout (which is the current layout in this sample)
plotInfo.setLayout(layoutId);// This is required.
// Now, override the layout settings with the plot settings we have been populating
plotInfo.setOverrideSettings(pPlotSettings);
// We need to validate these settings.
AcPlPlotInfoValidator validator;
validator.setMediaMatchingPolicy(AcPlPlotInfoValidator::MatchingPolicy::kMatchEnabled);
es = validator.validate(plotInfo);
// Begin document. The version we call is dependent on the plot-to-file status.
const char *szDocName=acDocManager->curDocument()->fileName();
if(m_bPlotToFile)
es = pEngine->beginDocument(plotInfo, szDocName, NULL, 1, true, m_csFilename);
else
es = pEngine->beginDocument(plotInfo, szDocName);
// Follow through sending commands to the engine, and notifications to the progress dialog.
pPlotProgDlg->onBeginSheet();
pPlotProgDlg->setSheetProgressRange(0, 100);
pPlotProgDlg->setSheetProgressPos(0);
es = pEngine->beginPage(pageInfo, plotInfo, true);
es = pEngine->beginGenerateGraphics();
es = pEngine->endGenerateGraphics();
es = pEngine->endPage();
pPlotProgDlg->setSheetProgressPos(100);
pPlotProgDlg->onEndSheet();
pPlotProgDlg->setPlotProgressPos(100);
es = pEngine->endDocument();
es = pEngine->endPlot();
// Destroy the engine
pEngine->destroy();
pEngine = NULL;
// and the progress dialog.
pPlotProgDlg->destroy();
}
else
// Ensure the engine is not already busy...
AfxMessageBox("Plot Engine is Busy...");
}
void CPlotApiDialog::RefreshDevices(void)
{
// Set the list of available devices on the system
AcArray<const char*> deviceList;// Temporary device array
m_Devices.ResetContent();// Clear the Combo Box
pPSV->plotDeviceList(deviceList);// Fill the temporary array,
// and copy the Combo Box and mirror with the results.
for(int c=0;c<deviceList.length();c++)
m_Devices.AddString(deviceList[c]);
// Set the current selection to reflect the current output device.
const char* plotCfgchar;
pPlotSettings->getPlotCfgName(plotCfgchar);
m_Devices.SetCurSel(m_Devices.SelectString(0,plotCfgchar));
}
BOOL CPlotApiDialog::OnInitDialog()
{
CDialog::OnInitDialog();
CenterWindow(acedGetAcadDwgView());
// Setup the ARX pointer...
pPSV=(AcDbPlotSettingsValidator*)acdbHostApplicationServices()->plotSettingsValidator();
AcAxDocLock lock;
// Now get the active layout object. This will be stored in layoutId.
AcDbLayoutManager *pLayoutManager = acdbHostApplicationServices()->layoutManager();
AcDbObjectId btrId=pLayoutManager->getActiveLayoutBTRId();
AcDbBlockTableRecord *pBTR;
Acad::ErrorStatus es=acdbOpenObject(pBTR,btrId,AcDb::kForRead);
// We want to instantiate our custom AcDbPlotSettings object, and inherit the
// properties from the active layout.
layoutId=pBTR->getLayoutId();
AcDbLayout *pLayout=NULL;
acdbOpenObject(pLayout,layoutId,AcDb::kForRead);
pPlotSettings=new AcDbPlotSettings(pLayout->modelType());
pPlotSettings->copyFrom(pLayout);
pLayout->close();
pBTR->close();
// Set some initial default values for the controls on the form.
m_bFit=TRUE;
CEdit *pEdit=(CEdit*)GetDlgItem(IDC_SCALE);
pEdit->EnableWindow(FALSE);
m_csFilename="c:\\temp\\PlotApi.dwf";
pEdit=(CEdit*)GetDlgItem(IDC_FILENAME);
pEdit->EnableWindow(FALSE);
m_bPlotToFile=FALSE;
m_Landscape=FALSE;
pPSV->setPlotRotation(pPlotSettings,AcDbPlotSettings::k0degrees);
// Determine the current background plot setting.
struct resbuf res;
acedGetVar("BACKGROUNDPLOT",&res);
if(res.resval.rint)
m_Background=TRUE;
else
m_Background=FALSE;
// Update the dropdown lists...
RefreshDevices();
OnCbnSelchangeDevices();// Called to setup the plot-to-file capabilities for the default device.
RefreshMediaNames();
CalcExtents();// Calculate the scale the layout we be plotted to fit the selected page.
UpdateData(FALSE);
// Instantiate the IAsdkPlotNotifySink server
HRESULT hr=InitAutomation();
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CPlotApiDialog::OnDestroy()
{
CDialog::OnDestroy();
HRESULT hr=ExitAutomation();
delete pPlotSettings;
delete this;
}
void CPlotApiDialog::RefreshMediaNames()
{
AcArray<const char*> MediaList;
m_Media.ResetContent();
pPSV->canonicalMediaNameList(pPlotSettings,MediaList);
for(int c=0;c<MediaList.length();c++)
m_Media.AddString(MediaList[c]);
char *pCurName;
pPlotSettings->getCanonicalMediaName(pCurName);
m_Media.SetCurSel(m_Media.SelectString(0,(CString)pCurName));
}
void CPlotApiDialog::OnBnClickedPreview()
{
Acad::ErrorStatus es;
AcAxDocLock lock;
es=pPSV->setPlotType(pPlotSettings,AcDbPlotSettings::kExtents);
// Set the Scale...
if (m_bFit)
{
es = pPSV->setUseStandardScale(pPlotSettings,Adesk::kTrue);
es = pPSV->setStdScaleType(pPlotSettings,StdScaleType::kScaleToFit);
}
else // Choose to use this custom scale...
{
es=pPSV->setUseStandardScale(pPlotSettings,Adesk::kFalse);
es=pPSV->setCustomPrintScale(pPlotSettings,m_Scale,1);
}
es=pPSV->setPlotCentered(pPlotSettings,true);
acedGetAcadFrame()->ShowWindow(SW_SHOW);
acedGetAcadFrame()->SetFocus();
ShowWindow(SW_HIDE);
if(pPlotSink)
pPlotSink->put_Visible(FALSE);
AcPlPlotEngine* pEngine = NULL;
if(Acad::eOk==AcPlPlotFactory::createPreviewEngine(pEngine))
{
pEngine->beginPlot(NULL);
AcPlPlotPageInfo pageInfo;
AcPlPlotInfo plotInfo;
plotInfo.setLayout(layoutId);
plotInfo.setOverrideSettings(pPlotSettings);
AcPlPlotInfoValidator validator;
validator.setMediaMatchingPolicy(AcPlPlotInfoValidator::MatchingPolicy::kMatchEnabled);
es = validator.validate(plotInfo);
const char *szDocName=acDocManager->curDocument()->fileName();
es = pEngine->beginDocument(plotInfo, szDocName);
es = pEngine->beginPage(pageInfo, plotInfo, true);
es = pEngine->beginGenerateGraphics();
es = pEngine->endGenerateGraphics();
es = pEngine->endPage();
es = pEngine->endDocument();
es = pEngine->endPlot();
pEngine->destroy();
pEngine = NULL;
}
else
AfxMessageBox("Plot Engine is Busy...");
ShowWindow(SW_SHOW);
if(pPlotSink)
pPlotSink->put_Visible(TRUE);
}
void CPlotApiDialog::OnBnClickedLandscape()
{
UpdateData(TRUE);
AcAxDocLock lock;
if(m_Landscape)
Acad::ErrorStatus es=pPSV->setPlotRotation(pPlotSettings,AcDbPlotSettings::k90degrees);
else
Acad::ErrorStatus es=pPSV->setPlotRotation(pPlotSettings,AcDbPlotSettings::k0degrees);
CalcExtents();
}
void CPlotApiDialog::OnBnClickedFit()
{
UpdateData(TRUE);
CEdit *pEdit=(CEdit*)GetDlgItem(IDC_SCALE);
if(m_bFit)
{
pEdit->EnableWindow(FALSE);
CalcExtents();
}
else
pEdit->EnableWindow(TRUE);
}
void CPlotApiDialog::OnBnClickedBackground()
{
UpdateData(TRUE);
struct resbuf res;
res.resval.rint=(int)m_Background;
res.restype=RTSHORT;
acedSetVar("BACKGROUNDPLOT",&res);
}
void CPlotApiDialog::CalcExtents()
{
CEdit *pEdit=(CEdit*)GetDlgItem(IDC_SCALE);
if(m_bFit)
{
pEdit->EnableWindow(FALSE);
Acad::ErrorStatus es = pPSV->setUseStandardScale(pPlotSettings,Adesk::kTrue);
es = pPSV->setStdScaleType(pPlotSettings,StdScaleType::kScaleToFit);
es = pPSV->setPlotType(pPlotSettings,AcDbPlotSettings::kExtents);
es = pPSV->setPlotCentered(pPlotSettings,true);
double numerator,denominator;
es = pPlotSettings->getCustomPrintScale(numerator,denominator);
m_Scale = numerator/denominator;
UpdateData(FALSE);
}
else
pEdit->EnableWindow(TRUE);
UpdateData(FALSE);
}
void CPlotApiDialog::OnEnChangeScale()
{
UpdateData(TRUE);
}
void CPlotApiDialog::OnBnClickedPlottofile()
{
UpdateData(TRUE);
CEdit *pEdit=(CEdit*)GetDlgItem(IDC_FILENAME);
if(m_bPlotToFile)
pEdit->EnableWindow(TRUE);
else
pEdit->EnableWindow(FALSE);
}
void CPlotApiDialog::OnBnClickedCancel()
{
CDialog::OnCancel();
DestroyWindow();
}
HRESULT CPlotApiDialog::InitAutomation(void)
{
// This will instantiate the IAsdkPlotNotifySink object as the single active instance,
// assuming it has not already been added to the ROT.
HRESULT hr = OleInitialize(NULL);
if (FAILED(hr))
return hr;
CComPtr <IUnknown> pUnk;
if(GetActiveObject(CLSID_CPlotNotifySink,NULL,&pUnk)==S_OK)
return S_OK; // Only one active sink is necessary.
CComPtr<IClassFactory> pCF;
hr = DllGetClassObject(CLSID_CPlotNotifySink, IID_IClassFactory, (LPVOID*)&pCF);
if (FAILED(hr))
return hr;
hr = pCF->CreateInstance(NULL, IID_IAsdkPlotNotifySink, (LPVOID*)&pPlotSink);
if (FAILED(hr))
return hr;
hr=RegisterActiveObject(pPlotSink, CLSID_CPlotNotifySink, ACTIVEOBJECT_WEAK, &dwAppObj);
if (FAILED(hr))
return hr;
return CoLockObjectExternal(pPlotSink, TRUE, TRUE);
}
HRESULT CPlotApiDialog::ExitAutomation(void)
{
// Remove the active IAsdkPlotNotifySink server from the ROT.
HRESULT hr;
hr=CoLockObjectExternal(pPlotSink, FALSE,FALSE);
if (dwAppObj)
hr=RevokeActiveObject(dwAppObj, NULL);
OleUninitialize();
return S_OK;
}
|
/* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file testConcurrentBatchFilter.cpp
* @brief Unit tests for the Concurrent Batch Filter
* @author Stephen Williams (swilliams8@gatech.edu)
* @date Jan 5, 2013
*/
#include <gtsam_unstable/nonlinear/ConcurrentBatchFilter.h>
#include <gtsam/slam/PriorFactor.h>
#include <gtsam/slam/BetweenFactor.h>
#include <gtsam/nonlinear/ISAM2.h>
#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>
#include <gtsam/nonlinear/NonlinearFactorGraph.h>
#include <gtsam/nonlinear/LinearContainerFactor.h>
#include <gtsam/nonlinear/Values.h>
#include <gtsam/inference/Symbol.h>
#include <gtsam/inference/Ordering.h>
#include <gtsam/inference/Key.h>
#include <gtsam/inference/JunctionTree.h>
#include <gtsam/geometry/Pose3.h>
#include <gtsam/base/TestableAssertions.h>
#include <CppUnitLite/TestHarness.h>
using namespace std;
using namespace gtsam;
namespace {
// Set up initial pose, odometry difference, loop closure difference, and initialization errors
const Pose3 poseInitial;
const Pose3 poseOdometry( Rot3::RzRyRx(Vector3(0.05, 0.10, -0.75)), Point3(1.0, -0.25, 0.10) );
const Pose3 poseError( Rot3::RzRyRx(Vector3(0.01, 0.02, -0.1)), Point3(0.05, -0.05, 0.02) );
// Set up noise models for the factors
const SharedDiagonal noisePrior = noiseModel::Isotropic::Sigma(6, 0.10);
const SharedDiagonal noiseOdometery = noiseModel::Diagonal::Sigmas((Vector(6) << 0.1, 0.1, 0.1, 0.5, 0.5, 0.5).finished());
const SharedDiagonal noiseLoop = noiseModel::Diagonal::Sigmas((Vector(6) << 0.25, 0.25, 0.25, 1.0, 1.0, 1.0).finished());
/* ************************************************************************* */
Values BatchOptimize(const NonlinearFactorGraph& graph, const Values& theta, int maxIter = 100) {
// Create an L-M optimizer
LevenbergMarquardtParams parameters;
parameters.maxIterations = maxIter;
LevenbergMarquardtOptimizer optimizer(graph, theta, parameters);
Values result = optimizer.optimize();
return result;
}
/* ************************************************************************* */
NonlinearFactorGraph CalculateMarginals(const NonlinearFactorGraph& factorGraph, const Values& linPoint, const FastList<Key>& keysToMarginalize){
std::set<Key> KeysToKeep;
for(const Values::ConstKeyValuePair& key_value: linPoint) { // we cycle over all the keys of factorGraph
KeysToKeep.insert(key_value.key);
} // so far we are keeping all keys, but we want to delete the ones that we are going to marginalize
for(Key key: keysToMarginalize) {
KeysToKeep.erase(key);
} // we removed the keys that we have to marginalize
Ordering ordering;
for(Key key: keysToMarginalize) {
ordering.push_back(key);
} // the keys that we marginalize should be at the beginning in the ordering
for(Key key: KeysToKeep) {
ordering.push_back(key);
}
GaussianFactorGraph linearGraph = *factorGraph.linearize(linPoint);
GaussianFactorGraph marginal = *linearGraph.eliminatePartialMultifrontal(KeyVector(keysToMarginalize.begin(), keysToMarginalize.end()), EliminateCholesky).second;
NonlinearFactorGraph LinearContainerForGaussianMarginals;
for(const GaussianFactor::shared_ptr& factor: marginal) {
LinearContainerForGaussianMarginals.push_back(LinearContainerFactor(factor, linPoint));
}
return LinearContainerForGaussianMarginals;
}
} // end namespace
/* ************************************************************************* */
TEST( ConcurrentBatchFilter, equals )
{
// TODO: Test 'equals' more vigorously
// Create a Concurrent Batch Filter
LevenbergMarquardtParams parameters1;
ConcurrentBatchFilter filter1(parameters1);
// Create an identical Concurrent Batch Filter
LevenbergMarquardtParams parameters2;
ConcurrentBatchFilter filter2(parameters2);
// Create a different Concurrent Batch Filter
LevenbergMarquardtParams parameters3;
parameters3.maxIterations = 1;
ConcurrentBatchFilter filter3(parameters3);
CHECK(assert_equal(filter1, filter1));
CHECK(assert_equal(filter1, filter2));
// CHECK(assert_inequal(filter1, filter3));
}
/* ************************************************************************* */
TEST( ConcurrentBatchFilter, getFactors )
{
// Create a Concurrent Batch Filter
LevenbergMarquardtParams parameters;
ConcurrentBatchFilter filter(parameters);
// Expected graph is empty
NonlinearFactorGraph expected1;
// Get actual graph
NonlinearFactorGraph actual1 = filter.getFactors();
// Check
CHECK(assert_equal(expected1, actual1));
// Add some factors to the filter
NonlinearFactorGraph newFactors1;
newFactors1.push_back(PriorFactor<Pose3>(1, poseInitial, noisePrior));
newFactors1.push_back(BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery));
Values newValues1;
newValues1.insert(1, Pose3());
newValues1.insert(2, newValues1.at<Pose3>(1).compose(poseOdometry));
filter.update(newFactors1, newValues1);
// Expected graph
NonlinearFactorGraph expected2;
expected2.push_back(newFactors1);
// Get actual graph
NonlinearFactorGraph actual2 = filter.getFactors();
// Check
CHECK(assert_equal(expected2, actual2));
// Add some more factors to the filter
NonlinearFactorGraph newFactors2;
newFactors2.push_back(BetweenFactor<Pose3>(2, 3, poseOdometry, noiseOdometery));
newFactors2.push_back(BetweenFactor<Pose3>(3, 4, poseOdometry, noiseOdometery));
Values newValues2;
newValues2.insert(3, newValues1.at<Pose3>(2).compose(poseOdometry));
newValues2.insert(4, newValues2.at<Pose3>(3).compose(poseOdometry));
filter.update(newFactors2, newValues2);
// Expected graph
NonlinearFactorGraph expected3;
expected3.push_back(newFactors1);
expected3.push_back(newFactors2);
// Get actual graph
NonlinearFactorGraph actual3 = filter.getFactors();
// Check
CHECK(assert_equal(expected3, actual3));
}
/* ************************************************************************* */
TEST( ConcurrentBatchFilter, getLinearizationPoint )
{
// Create a Concurrent Batch Filter
LevenbergMarquardtParams parameters;
ConcurrentBatchFilter filter(parameters);
// Expected values is empty
Values expected1;
// Get Linearization Point
Values actual1 = filter.getLinearizationPoint();
// Check
CHECK(assert_equal(expected1, actual1));
// Add some factors to the filter
NonlinearFactorGraph newFactors1;
newFactors1.push_back(PriorFactor<Pose3>(1, poseInitial, noisePrior));
newFactors1.push_back(BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery));
Values newValues1;
newValues1.insert(1, Pose3());
newValues1.insert(2, newValues1.at<Pose3>(1).compose(poseOdometry));
filter.update(newFactors1, newValues1);
// Expected values is equivalent to the provided values only because the provided linearization points were optimal
Values expected2;
expected2.insert(newValues1);
// Get actual linearization point
Values actual2 = filter.getLinearizationPoint();
// Check
CHECK(assert_equal(expected2, actual2));
// Add some more factors to the filter
NonlinearFactorGraph newFactors2;
newFactors2.push_back(BetweenFactor<Pose3>(2, 3, poseOdometry, noiseOdometery));
newFactors2.push_back(BetweenFactor<Pose3>(3, 4, poseOdometry, noiseOdometery));
Values newValues2;
newValues2.insert(3, newValues1.at<Pose3>(2).compose(poseOdometry));
newValues2.insert(4, newValues2.at<Pose3>(3).compose(poseOdometry));
filter.update(newFactors2, newValues2);
// Expected values is equivalent to the provided values only because the provided linearization points were optimal
Values expected3;
expected3.insert(newValues1);
expected3.insert(newValues2);
// Get actual linearization point
Values actual3 = filter.getLinearizationPoint();
// Check
CHECK(assert_equal(expected3, actual3));
}
/* ************************************************************************* */
TEST( ConcurrentBatchFilter, getOrdering )
{
// TODO: Think about how to check ordering...
}
/* ************************************************************************* */
TEST( ConcurrentBatchFilter, getDelta )
{
// TODO: Think about how to check delta...
}
/* ************************************************************************* */
TEST( ConcurrentBatchFilter, calculateEstimate )
{
// Create a Concurrent Batch Filter
LevenbergMarquardtParams parameters;
ConcurrentBatchFilter filter(parameters);
// Expected values is empty
Values expected1;
// Get Linearization Point
Values actual1 = filter.calculateEstimate();
// Check
CHECK(assert_equal(expected1, actual1));
// Add some factors to the filter
NonlinearFactorGraph newFactors2;
newFactors2.push_back(PriorFactor<Pose3>(1, poseInitial, noisePrior));
newFactors2.push_back(BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery));
Values newValues2;
newValues2.insert(1, Pose3().compose(poseError));
newValues2.insert(2, newValues2.at<Pose3>(1).compose(poseOdometry).compose(poseError));
filter.update(newFactors2, newValues2);
// Expected values from full batch optimization
NonlinearFactorGraph allFactors2;
allFactors2.push_back(newFactors2);
Values allValues2;
allValues2.insert(newValues2);
Values expected2 = BatchOptimize(allFactors2, allValues2);
// Get actual linearization point
Values actual2 = filter.calculateEstimate();
// Check
CHECK(assert_equal(expected2, actual2, 1e-6));
// Add some more factors to the filter
NonlinearFactorGraph newFactors3;
newFactors3.push_back(BetweenFactor<Pose3>(2, 3, poseOdometry, noiseOdometery));
newFactors3.push_back(BetweenFactor<Pose3>(3, 4, poseOdometry, noiseOdometery));
Values newValues3;
newValues3.insert(3, newValues2.at<Pose3>(2).compose(poseOdometry).compose(poseError));
newValues3.insert(4, newValues3.at<Pose3>(3).compose(poseOdometry).compose(poseError));
filter.update(newFactors3, newValues3);
// Expected values from full batch optimization
NonlinearFactorGraph allFactors3;
allFactors3.push_back(newFactors2);
allFactors3.push_back(newFactors3);
Values allValues3;
allValues3.insert(newValues2);
allValues3.insert(newValues3);
Values expected3 = BatchOptimize(allFactors3, allValues3);
// Get actual linearization point
Values actual3 = filter.calculateEstimate();
// Check
CHECK(assert_equal(expected3, actual3, 1e-6));
// Also check the single-variable version
Pose3 expectedPose1 = expected3.at<Pose3>(1);
Pose3 expectedPose2 = expected3.at<Pose3>(2);
Pose3 expectedPose3 = expected3.at<Pose3>(3);
Pose3 expectedPose4 = expected3.at<Pose3>(4);
// Also check the single-variable version
Pose3 actualPose1 = filter.calculateEstimate<Pose3>(1);
Pose3 actualPose2 = filter.calculateEstimate<Pose3>(2);
Pose3 actualPose3 = filter.calculateEstimate<Pose3>(3);
Pose3 actualPose4 = filter.calculateEstimate<Pose3>(4);
// Check
CHECK(assert_equal(expectedPose1, actualPose1, 1e-6));
CHECK(assert_equal(expectedPose2, actualPose2, 1e-6));
CHECK(assert_equal(expectedPose3, actualPose3, 1e-6));
CHECK(assert_equal(expectedPose4, actualPose4, 1e-6));
}
/* ************************************************************************* */
TEST( ConcurrentBatchFilter, update_empty )
{
// Create a set of optimizer parameters
LevenbergMarquardtParams parameters;
ConcurrentBatchFilter filter(parameters);
// Call update
filter.update();
}
/* ************************************************************************* */
TEST( ConcurrentBatchFilter, update_multiple )
{
// Create a Concurrent Batch Filter
LevenbergMarquardtParams parameters;
ConcurrentBatchFilter filter(parameters);
// Expected values is empty
Values expected1;
// Get Linearization Point
Values actual1 = filter.calculateEstimate();
// Check
CHECK(assert_equal(expected1, actual1));
// Add some factors to the filter
NonlinearFactorGraph newFactors2;
newFactors2.push_back(PriorFactor<Pose3>(1, poseInitial, noisePrior));
newFactors2.push_back(BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery));
Values newValues2;
newValues2.insert(1, Pose3().compose(poseError));
newValues2.insert(2, newValues2.at<Pose3>(1).compose(poseOdometry).compose(poseError));
filter.update(newFactors2, newValues2);
// Expected values from full batch optimization
NonlinearFactorGraph allFactors2;
allFactors2.push_back(newFactors2);
Values allValues2;
allValues2.insert(newValues2);
Values expected2 = BatchOptimize(allFactors2, allValues2);
// Get actual linearization point
Values actual2 = filter.calculateEstimate();
// Check
CHECK(assert_equal(expected2, actual2, 1e-6));
// Add some more factors to the filter
NonlinearFactorGraph newFactors3;
newFactors3.push_back(BetweenFactor<Pose3>(2, 3, poseOdometry, noiseOdometery));
newFactors3.push_back(BetweenFactor<Pose3>(3, 4, poseOdometry, noiseOdometery));
Values newValues3;
newValues3.insert(3, newValues2.at<Pose3>(2).compose(poseOdometry).compose(poseError));
newValues3.insert(4, newValues3.at<Pose3>(3).compose(poseOdometry).compose(poseError));
filter.update(newFactors3, newValues3);
// Expected values from full batch optimization
NonlinearFactorGraph allFactors3;
allFactors3.push_back(newFactors2);
allFactors3.push_back(newFactors3);
Values allValues3;
allValues3.insert(newValues2);
allValues3.insert(newValues3);
Values expected3 = BatchOptimize(allFactors3, allValues3);
// Get actual linearization point
Values actual3 = filter.calculateEstimate();
// Check
CHECK(assert_equal(expected3, actual3, 1e-6));
}
/* ************************************************************************* */
TEST( ConcurrentBatchFilter, update_and_marginalize )
{
// Create a set of optimizer parameters
LevenbergMarquardtParams parameters;
ConcurrentBatchFilter filter(parameters);
// Add some factors to the filter
NonlinearFactorGraph newFactors;
newFactors.push_back(PriorFactor<Pose3>(1, poseInitial, noisePrior));
newFactors.push_back(BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery));
newFactors.push_back(BetweenFactor<Pose3>(2, 3, poseOdometry, noiseOdometery));
newFactors.push_back(BetweenFactor<Pose3>(3, 4, poseOdometry, noiseOdometery));
Values newValues;
newValues.insert(1, Pose3().compose(poseError));
newValues.insert(2, newValues.at<Pose3>(1).compose(poseOdometry).compose(poseError));
newValues.insert(3, newValues.at<Pose3>(2).compose(poseOdometry).compose(poseError));
newValues.insert(4, newValues.at<Pose3>(3).compose(poseOdometry).compose(poseError));
// Specify a subset of variables to marginalize/move to the smoother
FastList<Key> keysToMove;
keysToMove.push_back(1);
keysToMove.push_back(2);
// Update the filter
filter.update(newFactors, newValues, keysToMove);
// Calculate expected factor graph and values
Values optimalValues = BatchOptimize(newFactors, newValues);
NonlinearFactorGraph partialGraph;
partialGraph.emplace_shared<PriorFactor<Pose3> >(1, poseInitial, noisePrior);
partialGraph.emplace_shared<BetweenFactor<Pose3> >(1, 2, poseOdometry, noiseOdometery);
partialGraph.emplace_shared<BetweenFactor<Pose3> >(2, 3, poseOdometry, noiseOdometery);
Values partialValues;
partialValues.insert(1, optimalValues.at<Pose3>(1));
partialValues.insert(2, optimalValues.at<Pose3>(2));
partialValues.insert(3, optimalValues.at<Pose3>(3));
// Create an ordering
Ordering ordering;
ordering.push_back(1);
ordering.push_back(2);
ordering.push_back(3);
// Create the set of marginalizable variables
KeyVector linearIndices {1, 2};
GaussianFactorGraph linearPartialGraph = *partialGraph.linearize(partialValues);
GaussianFactorGraph result = *linearPartialGraph.eliminatePartialMultifrontal(linearIndices, EliminateCholesky).second;
NonlinearFactorGraph expectedGraph;
// These three lines create three empty factors in expectedGraph:
// this is done since the equal function in NonlinearFactorGraph also cares about the ordering of the factors
// and in the actualGraph produced by the HMF we first insert 5 nonlinear factors, then we delete 3 of them, by
// substituting them with a linear marginal
expectedGraph.push_back(NonlinearFactor::shared_ptr());
expectedGraph.push_back(NonlinearFactor::shared_ptr());
expectedGraph.push_back(NonlinearFactor::shared_ptr());
// ==========================================================
expectedGraph.emplace_shared<BetweenFactor<Pose3> >(3, 4, poseOdometry, noiseOdometery);
for(const GaussianFactor::shared_ptr& factor: result) {
expectedGraph.emplace_shared<LinearContainerFactor>(factor, partialValues);
}
// Get the actual factor graph and optimal point
NonlinearFactorGraph actualGraph = filter.getFactors();
Values actualValues = filter.calculateEstimate();
Values expectedValues = optimalValues;
// Check
for(Key key: keysToMove) {
expectedValues.erase(key);
}
CHECK(assert_equal(expectedValues, actualValues, 1e-6));
CHECK(assert_equal(expectedGraph, actualGraph, 1e-6));
}
/* ************************************************************************* */
TEST( ConcurrentBatchFilter, synchronize_0 )
{
// Create a set of optimizer parameters
LevenbergMarquardtParams parameters;
// Create a Concurrent Batch Filter
ConcurrentBatchFilter filter(parameters);
// Create empty containers *from* the smoother
NonlinearFactorGraph smootherSummarization;
Values smootherSeparatorValues;
// Create expected values from the filter. For the case where the filter is empty, the expected values are also empty
NonlinearFactorGraph expectedSmootherFactors, expectedFilterSummarization;
Values expectedSmootherValues, expectedFilterSeparatorValues;
// Synchronize
NonlinearFactorGraph actualSmootherFactors, actualFilterSummarization;
Values actualSmootherValues, actualFilterSeparatorValues;
filter.presync();
filter.synchronize(smootherSummarization, smootherSeparatorValues);
filter.getSmootherFactors(actualSmootherFactors, actualSmootherValues);
filter.getSummarizedFactors(actualFilterSummarization, actualFilterSeparatorValues);
filter.postsync();
// Check
CHECK(assert_equal(expectedSmootherFactors, actualSmootherFactors, 1e-6));
CHECK(assert_equal(expectedSmootherValues, actualSmootherValues, 1e-6));
CHECK(assert_equal(expectedFilterSummarization, actualFilterSummarization, 1e-6));
CHECK(assert_equal(expectedFilterSeparatorValues, actualFilterSeparatorValues, 1e-6));
}
/* ************************************************************************* */
TEST( ConcurrentBatchFilter, synchronize_1 )
{
// Create a set of optimizer parameters
LevenbergMarquardtParams parameters;
parameters.maxIterations = 1;
// Create a Concurrent Batch Filter
ConcurrentBatchFilter filter(parameters);
// Insert factors into the filter, but do not marginalize out any variables.
// The synchronization should still be empty
NonlinearFactorGraph newFactors;
newFactors.push_back(PriorFactor<Pose3>(1, poseInitial, noisePrior));
newFactors.push_back(BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery));
Values newValues;
newValues.insert(1, Pose3().compose(poseError));
newValues.insert(2, newValues.at<Pose3>(1).compose(poseOdometry).compose(poseError));
filter.update(newFactors, newValues);
// Create empty containers *from* the smoother
NonlinearFactorGraph smootherSummarization;
Values smootherSeparatorValues;
// Create expected values from the filter. For the case when nothing has been marginalized from the filter, the expected values are empty
NonlinearFactorGraph expectedSmootherFactors, expectedFilterSummarization;
Values expectedSmootherValues, expectedFilterSeparatorValues;
// Synchronize
NonlinearFactorGraph actualSmootherFactors, actualFilterSummarization;
Values actualSmootherValues, actualFilterSeparatorValues;
filter.presync();
filter.synchronize(smootherSummarization, smootherSeparatorValues);
filter.getSmootherFactors(actualSmootherFactors, actualSmootherValues);
filter.getSummarizedFactors(actualFilterSummarization, actualFilterSeparatorValues);
filter.postsync();
// Check
CHECK(assert_equal(expectedSmootherFactors, actualSmootherFactors, 1e-6));
CHECK(assert_equal(expectedSmootherValues, actualSmootherValues, 1e-6));
CHECK(assert_equal(expectedFilterSummarization, actualFilterSummarization, 1e-6));
CHECK(assert_equal(expectedFilterSeparatorValues, actualFilterSeparatorValues, 1e-6));
}
/* ************************************************************************* */
TEST( ConcurrentBatchFilter, synchronize_2 )
{
std::cout << "*********************** synchronize_2 ************************" << std::endl;
// Create a set of optimizer parameters
LevenbergMarquardtParams parameters;
//parameters.maxIterations = 1;
// Create a Concurrent Batch Filter
ConcurrentBatchFilter filter(parameters);
// Insert factors into the filter, and marginalize out one variable.
// There should not be information transmitted to the smoother from the filter
NonlinearFactorGraph newFactors;
NonlinearFactor::shared_ptr factor1(new PriorFactor<Pose3>(1, poseInitial, noisePrior));
NonlinearFactor::shared_ptr factor2(new BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery));
newFactors.push_back(factor1);
newFactors.push_back(factor2);
Values newValues;
Pose3 value1 = Pose3().compose(poseError);
Pose3 value2 = value1.compose(poseOdometry).compose(poseError);
newValues.insert(1, value1);
newValues.insert(2, value2);
FastList<Key> keysToMove;
keysToMove.push_back(1);
filter.update(newFactors, newValues, keysToMove);
// this will not work, as in the filter only remains node 2, while 1 was marginalized out
// Values optimalValues = filter.calculateEstimate();
Values optimalValues = BatchOptimize(newFactors, newValues);
// Create empty containers *from* the smoother
NonlinearFactorGraph smootherSummarization;
Values smootherSeparatorValues;
// Create expected values from the filter.
// The smoother factors include any factor adjacent to a marginalized variable
NonlinearFactorGraph expectedSmootherFactors;
expectedSmootherFactors.push_back(factor1);
expectedSmootherFactors.push_back(factor2);
Values expectedSmootherValues;
// We only pass linearization points for the marginalized variables
expectedSmootherValues.insert(1, optimalValues.at<Pose3>(1));
// The filter summarization is the remaining factors from marginalizing out the requested variable
// In the current example, after marginalizing out 1, the filter only contains the separator (2), with
// no nonlinear factor attached to it, therefore no filter summarization needs to be passed to the smoother
NonlinearFactorGraph expectedFilterSummarization;
Values expectedFilterSeparatorValues;
expectedFilterSeparatorValues.insert(2, optimalValues.at<Pose3>(2));
// Synchronize
NonlinearFactorGraph actualSmootherFactors, actualFilterSummarization;
Values actualSmootherValues, actualFilterSeparatorValues;
filter.presync();
filter.synchronize(smootherSummarization, smootherSeparatorValues);
filter.getSmootherFactors(actualSmootherFactors, actualSmootherValues);
filter.getSummarizedFactors(actualFilterSummarization, actualFilterSeparatorValues);
filter.postsync();
// Check
CHECK(assert_equal(expectedSmootherFactors, actualSmootherFactors, 1e-6));
CHECK(assert_equal(expectedSmootherValues, actualSmootherValues, 1e-6));
CHECK(assert_equal(expectedFilterSummarization, actualFilterSummarization, 1e-6));
CHECK(assert_equal(expectedFilterSeparatorValues, actualFilterSeparatorValues, 1e-6));
}
/* ************************************************************************* */
TEST( ConcurrentBatchFilter, synchronize_3 )
{
std::cout << "*********************** synchronize_3 ************************" << std::endl;
// Create a set of optimizer parameters
LevenbergMarquardtParams parameters;
//parameters.maxIterations = 1;
// Create a Concurrent Batch Filter
ConcurrentBatchFilter filter(parameters);
// Insert factors into the filter, and marginalize out one variable.
// There should not be information transmitted to the smoother from the filter
NonlinearFactorGraph newFactors;
NonlinearFactor::shared_ptr factor1(new PriorFactor<Pose3>(1, poseInitial, noisePrior));
NonlinearFactor::shared_ptr factor2(new BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery));
NonlinearFactor::shared_ptr factor3(new BetweenFactor<Pose3>(2, 3, poseOdometry, noiseOdometery));
newFactors.push_back(factor1);
newFactors.push_back(factor2);
newFactors.push_back(factor3);
Values newValues;
Pose3 value1 = Pose3().compose(poseError);
Pose3 value2 = value1.compose(poseOdometry).compose(poseError);
Pose3 value3 = value2.compose(poseOdometry).compose(poseError);
newValues.insert(1, value1);
newValues.insert(2, value2);
newValues.insert(3, value3);
FastList<Key> keysToMove;
keysToMove.push_back(1);
// we add factors to the filter while marginalizing node 1
filter.update(newFactors, newValues, keysToMove);
Values optimalValues = BatchOptimize(newFactors, newValues);
// In this example the smoother is empty
// Create empty containers *from* the smoother
NonlinearFactorGraph smootherSummarization;
Values smootherSeparatorValues;
// Create expected values from the filter.
// The smoother factors include any factor adjacent to a marginalized variable
NonlinearFactorGraph expectedSmootherFactors;
expectedSmootherFactors.push_back(factor1);
expectedSmootherFactors.push_back(factor2);
Values expectedSmootherValues;
// We only pass linearization points for the marginalized variables
expectedSmootherValues.insert(1, optimalValues.at<Pose3>(1));
// In the current example, after marginalizing out 1, the filter contains the separator 2 and node 3, with
// a nonlinear factor attached to them
// Why there is no summarization from filter ????
NonlinearFactorGraph expectedFilterSummarization;
Values expectedFilterSeparatorValues;
expectedFilterSeparatorValues.insert(2, optimalValues.at<Pose3>(2));
// ------------------------------------------------------------------------------
NonlinearFactorGraph partialGraph;
partialGraph.push_back(factor3);
Values partialValues;
partialValues.insert(2, optimalValues.at<Pose3>(2));
partialValues.insert(3, optimalValues.at<Pose3>(3));
FastList<Key> keysToMarginalize;
keysToMarginalize.push_back(3);
expectedFilterSummarization = CalculateMarginals(partialGraph, partialValues, keysToMarginalize);
// ------------------------------------------------------------------------------
// Synchronize
NonlinearFactorGraph actualSmootherFactors, actualFilterSummarization;
Values actualSmootherValues, actualFilterSeparatorValues;
filter.presync();
filter.synchronize(smootherSummarization, smootherSeparatorValues);
filter.getSmootherFactors(actualSmootherFactors, actualSmootherValues);
filter.getSummarizedFactors(actualFilterSummarization, actualFilterSeparatorValues);
filter.postsync();
// Check
CHECK(assert_equal(expectedSmootherFactors, actualSmootherFactors, 1e-6));
CHECK(assert_equal(expectedSmootherValues, actualSmootherValues, 1e-6));
CHECK(assert_equal(expectedFilterSummarization, actualFilterSummarization, 1e-6));
CHECK(assert_equal(expectedFilterSeparatorValues, actualFilterSeparatorValues, 1e-6));
}
/* ************************************************************************* */
TEST( ConcurrentBatchFilter, synchronize_4 )
{
// Create a set of optimizer parameters
LevenbergMarquardtParams parameters;
parameters.maxIterations = 1;
// Create a Concurrent Batch Filter
ConcurrentBatchFilter filter(parameters);
// Insert factors into the filter, and marginalize out one variable.
// There should not be information transmitted to the smoother from the filter
NonlinearFactorGraph newFactors;
NonlinearFactor::shared_ptr factor1(new PriorFactor<Pose3>(1, poseInitial, noisePrior));
NonlinearFactor::shared_ptr factor2(new BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery));
NonlinearFactor::shared_ptr factor3(new BetweenFactor<Pose3>(2, 3, poseOdometry, noiseOdometery));
newFactors.push_back(factor1);
newFactors.push_back(factor2);
newFactors.push_back(factor3);
Values newValues;
Pose3 value1 = Pose3().compose(poseError);
Pose3 value2 = value1.compose(poseOdometry).compose(poseError);
Pose3 value3 = value2.compose(poseOdometry).compose(poseError);
newValues.insert(1, value1);
newValues.insert(2, value2);
newValues.insert(3, value3);
FastList<Key> keysToMove;
keysToMove.push_back(1);
// we add factors to the filter while marginalizing node 1
filter.update(newFactors, newValues, keysToMove);
Values optimalValuesFilter = BatchOptimize(newFactors, newValues,1);
// In this example the smoother contains a between factor and a prior factor
// COMPUTE SUMMARIZATION ON THE SMOOTHER SIDE
NonlinearFactorGraph smootherSummarization;
Values smootherSeparatorValues;
// Create expected values from the filter.
// The smoother factors include any factor adjacent to a marginalized variable
NonlinearFactorGraph expectedSmootherFactors;
expectedSmootherFactors.push_back(factor1);
expectedSmootherFactors.push_back(factor2);
Values expectedSmootherValues;
// We only pass linearization points for the marginalized variables
expectedSmootherValues.insert(1, optimalValuesFilter.at<Pose3>(1));
// COMPUTE SUMMARIZATION ON THE FILTER SIDE
// In the current example, after marginalizing out 1, the filter contains the separator 2 and node 3, with
// a nonlinear factor attached to them
// Why there is no summarization from filter ????
NonlinearFactorGraph expectedFilterSummarization;
Values expectedFilterSeparatorValues;
expectedFilterSeparatorValues.insert(2, optimalValuesFilter.at<Pose3>(2));
// ------------------------------------------------------------------------------
NonlinearFactorGraph partialGraphFilter;
partialGraphFilter.push_back(factor3);
Values partialValuesFilter;
partialValuesFilter.insert(2, optimalValuesFilter.at<Pose3>(2));
partialValuesFilter.insert(3, optimalValuesFilter.at<Pose3>(3));
// Create an ordering
Ordering orderingFilter;
orderingFilter.push_back(3);
orderingFilter.push_back(2);
FastList<Key> keysToMarginalize;
keysToMarginalize.push_back(3);
expectedFilterSummarization = CalculateMarginals(partialGraphFilter, partialValuesFilter, keysToMarginalize);
// ------------------------------------------------------------------------------
// Synchronize
// This is only an information compression/exchange: to actually incorporate the info we should call update
NonlinearFactorGraph actualSmootherFactors, actualFilterSummarization;
Values actualSmootherValues, actualFilterSeparatorValues;
filter.presync();
filter.synchronize(smootherSummarization, smootherSeparatorValues);
filter.getSmootherFactors(actualSmootherFactors, actualSmootherValues);
filter.getSummarizedFactors(actualFilterSummarization, actualFilterSeparatorValues);
filter.postsync();
// Check
CHECK(assert_equal(expectedSmootherFactors, actualSmootherFactors, 1e-6));
CHECK(assert_equal(expectedSmootherValues, actualSmootherValues, 1e-6));
CHECK(assert_equal(expectedFilterSummarization, actualFilterSummarization, 1e-6));
CHECK(assert_equal(expectedFilterSeparatorValues, actualFilterSeparatorValues, 1e-6));
}
/* ************************************************************************* */
TEST( ConcurrentBatchFilter, synchronize_5 )
{
std::cout << "*********************** synchronize_5 ************************" << std::endl;
// Create a set of optimizer parameters
LevenbergMarquardtParams parameters;
parameters.maxIterations = 1;
// Create a Concurrent Batch Filter
ConcurrentBatchFilter filter(parameters);
// Insert factors into the filter, and marginalize out one variable.
// There should not be information transmitted to the smoother from the filter
NonlinearFactorGraph newFactors;
NonlinearFactor::shared_ptr factor1(new PriorFactor<Pose3>(1, poseInitial, noisePrior));
NonlinearFactor::shared_ptr factor2(new BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery));
NonlinearFactor::shared_ptr factor3(new PriorFactor<Pose3>(2, poseInitial, noisePrior));
NonlinearFactor::shared_ptr factor4(new BetweenFactor<Pose3>(2, 3, poseOdometry, noiseOdometery));
NonlinearFactor::shared_ptr factor5(new BetweenFactor<Pose3>(3, 4, poseOdometry, noiseOdometery));
newFactors.push_back(factor1);
newFactors.push_back(factor2);
newFactors.push_back(factor3);
newFactors.push_back(factor4);
newFactors.push_back(factor5);
Values newValues;
Pose3 value1 = Pose3().compose(poseError);
Pose3 value2 = value1.compose(poseOdometry).compose(poseError);
Pose3 value3 = value2.compose(poseOdometry).compose(poseError);
Pose3 value4 = value3.compose(poseOdometry).compose(poseError);
newValues.insert(1, value1);
newValues.insert(2, value2);
newValues.insert(3, value3);
newValues.insert(4, value4);
FastList<Key> keysToMove;
keysToMove.push_back(1);
// we add factors to the filter while marginalizing node 1
filter.update(newFactors, newValues, keysToMove);
// At the beginning the smoother is empty
NonlinearFactorGraph smootherSummarization;
Values smootherSeparatorValues;
// Synchronize
// This is only an information compression/exchange: to actually incorporate the info we should call update
NonlinearFactorGraph actualSmootherFactors, actualFilterSummarization;
Values actualSmootherValues, actualFilterSeparatorValues;
filter.presync();
filter.synchronize(smootherSummarization, smootherSeparatorValues);
filter.getSmootherFactors(actualSmootherFactors, actualSmootherValues);
filter.getSummarizedFactors(actualFilterSummarization, actualFilterSeparatorValues);
filter.postsync();
NonlinearFactorGraph expectedSmootherFactors;
expectedSmootherFactors.push_back(factor1);
expectedSmootherFactors.push_back(factor2);
Values optimalValues = BatchOptimize(newFactors, newValues, 1);
Values expectedSmootherValues;
// Pose3 cast is useless in this case (but we still put it as an example): values and graphs can handle generic
// geometric objects. You really need the <Pose3> when you need to fill in a Pose3 object with the .at()
expectedSmootherValues.insert(1,optimalValues.at<Pose3>(1));
// Check
CHECK(assert_equal(expectedSmootherFactors, actualSmootherFactors, 1e-6));
CHECK(assert_equal(expectedSmootherValues, actualSmootherValues, 1e-6));
// at this point the filter contains: nodes 2 3 4 and factors 3 4 5 + marginal on 2
Values optimalValues2 = BatchOptimize(filter.getFactors(),filter.getLinearizationPoint(),1);
FastList<Key> keysToMove2;
keysToMove2.push_back(2);
newFactors.resize(0);
newValues.clear();
// we add factors to the filter while marginalizing node 1
filter.update(newFactors, newValues, keysToMove2);
// At the beginning the smoother is empty
NonlinearFactorGraph smootherSummarization2;
Values smootherSeparatorValues2;
// ------------------------------------------------------------------------------
// We fake the computation of the smoother separator
// currently the smoother contains factor 1 and 2 and node 1 and 2
NonlinearFactorGraph partialGraph;
partialGraph.push_back(factor1);
partialGraph.push_back(factor2);
// we also assume that the smoother received an extra factor (e.g., a prior on 1)
partialGraph.push_back(factor1);
Values partialValues;
// Batch optimization updates all linearization points but the ones of the separator
// In this case, we start with no separator (everything is in the filter), therefore,
// we update all linearization point
partialValues.insert(2, optimalValues.at(2)); //<-- does not actually exist
//The linearization point of 1 is controlled by the smoother and
// we are artificially setting that to something different to what was in the filter
partialValues.insert(1, Pose3().compose(poseError.inverse()));
FastList<Key> keysToMarginalize;
keysToMarginalize.push_back(1);
smootherSummarization2 = CalculateMarginals(partialGraph, partialValues, keysToMarginalize);
smootherSeparatorValues2.insert(2, partialValues.at(2));
// ------------------------------------------------------------------------------
// Synchronize
// This is only an information compression/exchange: to actually incorporate the info we should call update
NonlinearFactorGraph actualSmootherFactors2, actualFilterSummarization2;
Values actualSmootherValues2, actualFilterSeparatorValues2;
filter.presync();
filter.synchronize(smootherSummarization2, smootherSeparatorValues2);
filter.getSmootherFactors(actualSmootherFactors2, actualSmootherValues2);
filter.getSummarizedFactors(actualFilterSummarization2, actualFilterSeparatorValues2);
filter.postsync();
NonlinearFactorGraph expectedSmootherFactors2;
expectedSmootherFactors2.push_back(factor3);
expectedSmootherFactors2.push_back(factor4);
Values expectedSmootherValues2;
expectedSmootherValues2.insert(2, optimalValues.at(2));
// Check
CHECK(assert_equal(expectedSmootherFactors2, actualSmootherFactors2, 1e-6));
CHECK(assert_equal(expectedSmootherValues2, actualSmootherValues2, 1e-6));
// In this example the smoother contains a between factor and a prior factor
// COMPUTE SUMMARIZATION ON THE FILTER SIDE
// ------------------------------------------------------------------------------
// This cannot be nonempty for the first call to synchronize
NonlinearFactorGraph partialGraphFilter;
partialGraphFilter.push_back(factor5);
Values partialValuesFilter;
partialValuesFilter.insert(3, optimalValues2.at(3));
partialValuesFilter.insert(4, optimalValues2.at(4));
FastList<Key> keysToMarginalize2;
keysToMarginalize2.push_back(4);
NonlinearFactorGraph expectedFilterSummarization2 = CalculateMarginals(partialGraphFilter, partialValuesFilter, keysToMarginalize2);
Values expectedFilterSeparatorValues2;
expectedFilterSeparatorValues2.insert(3, optimalValues2.at(3));
CHECK(assert_equal(expectedFilterSummarization2, actualFilterSummarization2, 1e-6));
CHECK(assert_equal(expectedFilterSeparatorValues2, actualFilterSeparatorValues2, 1e-6));
// Now we should check that the smooother summarization on the old separator is correctly propagated
// on the new separator by the filter
NonlinearFactorGraph partialGraphTransition;
partialGraphTransition.push_back(factor3);
partialGraphTransition.push_back(factor4);
partialGraphTransition.push_back(smootherSummarization2);
Values partialValuesTransition;
partialValuesTransition.insert(2,optimalValues.at(2));
partialValuesTransition.insert(3,optimalValues2.at(3));
FastList<Key> keysToMarginalize3;
keysToMarginalize3.push_back(2);
NonlinearFactorGraph expectedFilterGraph;
// The assert equal will check if the expected and the actual graphs are the same, taking into account
// orders of the factors, and empty factors:
// in the filter we originally had 5 factors, and by marginalizing 1 and 2 we got rid of factors 1 2 3 4,
// therefore in the expected Factor we should include 4 empty factors.
// Note that the unit test will fail also if we change the order of the factors, due to the definition of assert_equal
NonlinearFactor::shared_ptr factorEmpty;
expectedFilterGraph.push_back(factorEmpty);
expectedFilterGraph.push_back(factorEmpty);
expectedFilterGraph.push_back(factorEmpty);
expectedFilterGraph.push_back(factorEmpty);
expectedFilterGraph.push_back(factor5);
expectedFilterGraph.push_back(CalculateMarginals(partialGraphTransition, partialValuesTransition, keysToMarginalize3));
NonlinearFactorGraph actualFilterGraph;
actualFilterGraph = filter.getFactors();
CHECK(assert_equal(expectedFilterGraph, actualFilterGraph, 1e-6));
}
///* ************************************************************************* */
TEST( ConcurrentBatchFilter, CalculateMarginals_1 )
{
// We compare the manual computation of the linear marginals from a factor graph, with the function CalculateMarginals
NonlinearFactor::shared_ptr factor1(new PriorFactor<Pose3>(1, poseInitial, noisePrior));
NonlinearFactor::shared_ptr factor2(new BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery));
NonlinearFactor::shared_ptr factor3(new PriorFactor<Pose3>(2, poseInitial, noisePrior));
NonlinearFactor::shared_ptr factor4(new BetweenFactor<Pose3>(2, 3, poseOdometry, noiseOdometery));
NonlinearFactorGraph factorGraph;
factorGraph.push_back(factor1);
factorGraph.push_back(factor2);
factorGraph.push_back(factor3);
factorGraph.push_back(factor4);
Values newValues;
Pose3 value1 = Pose3().compose(poseError);
Pose3 value2 = value1.compose(poseOdometry).compose(poseError);
Pose3 value3 = value2.compose(poseOdometry).compose(poseError);
newValues.insert(1, value1);
newValues.insert(2, value2);
newValues.insert(3, value3);
// We first manually
// Create an ordering
Ordering ordering;
ordering.push_back(1);
ordering.push_back(2);
ordering.push_back(3);
GaussianFactorGraph linearFactorGraph = *factorGraph.linearize(newValues);
// Create the set of marginalizable variables
KeyVector linearIndices {1};
GaussianFactorGraph result = *linearFactorGraph.eliminatePartialMultifrontal(linearIndices, EliminateCholesky).second;
NonlinearFactorGraph expectedMarginals;
for(const GaussianFactor::shared_ptr& factor: result) {
expectedMarginals.push_back(LinearContainerFactor(factor, newValues));
}
FastList<Key> keysToMarginalize;
keysToMarginalize.push_back(1);
NonlinearFactorGraph actualMarginals;
actualMarginals = CalculateMarginals(factorGraph, newValues, keysToMarginalize);
// Check
CHECK(assert_equal(expectedMarginals, actualMarginals, 1e-6));
}
///* ************************************************************************* */
TEST( ConcurrentBatchFilter, CalculateMarginals_2 )
{
// We compare the manual computation of the linear marginals from a factor graph, with the function CalculateMarginals
NonlinearFactor::shared_ptr factor1(new PriorFactor<Pose3>(1, poseInitial, noisePrior));
NonlinearFactor::shared_ptr factor2(new BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery));
NonlinearFactor::shared_ptr factor3(new PriorFactor<Pose3>(2, poseInitial, noisePrior));
NonlinearFactor::shared_ptr factor4(new BetweenFactor<Pose3>(2, 3, poseOdometry, noiseOdometery));
NonlinearFactorGraph factorGraph;
factorGraph.push_back(factor1);
factorGraph.push_back(factor2);
factorGraph.push_back(factor3);
factorGraph.push_back(factor4);
Values newValues;
Pose3 value1 = Pose3().compose(poseError);
Pose3 value2 = value1.compose(poseOdometry).compose(poseError);
Pose3 value3 = value2.compose(poseOdometry).compose(poseError);
newValues.insert(1, value1);
newValues.insert(2, value2);
newValues.insert(3, value3);
// We first manually
// Create an ordering
Ordering ordering;
ordering.push_back(1);
ordering.push_back(2);
ordering.push_back(3);
GaussianFactorGraph linearFactorGraph = *factorGraph.linearize(newValues);
// Create the set of marginalizable variables
KeyVector linearIndices {1, 2};
GaussianFactorGraph result = *linearFactorGraph.eliminatePartialMultifrontal(linearIndices, EliminateCholesky).second;
NonlinearFactorGraph expectedMarginals;
for(const GaussianFactor::shared_ptr& factor: result) {
expectedMarginals.push_back(LinearContainerFactor(factor, newValues));
}
FastList<Key> keysToMarginalize;
keysToMarginalize.push_back(1);
keysToMarginalize.push_back(2);
NonlinearFactorGraph actualMarginals;
actualMarginals = CalculateMarginals(factorGraph, newValues, keysToMarginalize);
// Check
CHECK(assert_equal(expectedMarginals, actualMarginals, 1e-6));
}
///* ************************************************************************* */
TEST( ConcurrentBatchFilter, removeFactors_topology_1 )
{
std::cout << "*********************** removeFactors_topology_1 ************************" << std::endl;
// Create a set of optimizer parameters
LevenbergMarquardtParams parameters;
ConcurrentBatchFilter filter(parameters);
// Add some factors to the filter
NonlinearFactorGraph newFactors;
newFactors.push_back(PriorFactor<Pose3>(1, poseInitial, noisePrior));
newFactors.push_back(BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery));
newFactors.push_back(BetweenFactor<Pose3>(2, 3, poseOdometry, noiseOdometery));
newFactors.push_back(BetweenFactor<Pose3>(3, 4, poseOdometry, noiseOdometery));
newFactors.push_back(BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery));
Values newValues;
newValues.insert(1, Pose3().compose(poseError));
newValues.insert(2, newValues.at<Pose3>(1).compose(poseOdometry).compose(poseError));
newValues.insert(3, newValues.at<Pose3>(2).compose(poseOdometry).compose(poseError));
newValues.insert(4, newValues.at<Pose3>(3).compose(poseOdometry).compose(poseError));
// Specify a subset of variables to marginalize/move to the smoother
FastList<Key> keysToMove;
// Update the filter: add all factors
filter.update(newFactors, newValues, keysToMove);
// factor we want to remove
// NOTE: we can remove factors, paying attention that the remaining graph remains connected
// we remove a single factor, the number 1, which is a BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery);
std::vector<size_t> removeFactorIndices(1,1);
// Add no factors to the filter (we only want to test the removal)
NonlinearFactorGraph noFactors;
Values noValues;
filter.update(noFactors, noValues, keysToMove, removeFactorIndices);
NonlinearFactorGraph actualGraph = filter.getFactors();
NonlinearFactorGraph expectedGraph;
expectedGraph.emplace_shared<PriorFactor<Pose3> >(1, poseInitial, noisePrior);
// we removed this one: expectedGraph.emplace_shared<BetweenFactor<Pose3> >(1, 2, poseOdometry, noiseOdometery);
// we should add an empty one, so that the ordering and labeling of the factors is preserved
expectedGraph.push_back(NonlinearFactor::shared_ptr());
expectedGraph.emplace_shared<BetweenFactor<Pose3> >(2, 3, poseOdometry, noiseOdometery);
expectedGraph.emplace_shared<BetweenFactor<Pose3> >(3, 4, poseOdometry, noiseOdometery);
expectedGraph.emplace_shared<BetweenFactor<Pose3> >(1, 2, poseOdometry, noiseOdometery);
CHECK(assert_equal(expectedGraph, actualGraph, 1e-6));
}
///* ************************************************************************* */
TEST( ConcurrentBatchFilter, removeFactors_topology_2 )
{
std::cout << "*********************** removeFactors_topology_2 ************************" << std::endl;
// we try removing the last factor
// Create a set of optimizer parameters
LevenbergMarquardtParams parameters;
ConcurrentBatchFilter filter(parameters);
// Add some factors to the filter
NonlinearFactorGraph newFactors;
newFactors.push_back(PriorFactor<Pose3>(1, poseInitial, noisePrior));
newFactors.push_back(BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery));
newFactors.push_back(BetweenFactor<Pose3>(2, 3, poseOdometry, noiseOdometery));
newFactors.push_back(BetweenFactor<Pose3>(3, 4, poseOdometry, noiseOdometery));
newFactors.push_back(BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery));
Values newValues;
newValues.insert(1, Pose3().compose(poseError));
newValues.insert(2, newValues.at<Pose3>(1).compose(poseOdometry).compose(poseError));
newValues.insert(3, newValues.at<Pose3>(2).compose(poseOdometry).compose(poseError));
newValues.insert(4, newValues.at<Pose3>(3).compose(poseOdometry).compose(poseError));
// Specify a subset of variables to marginalize/move to the smoother
FastList<Key> keysToMove;
// Update the filter: add all factors
filter.update(newFactors, newValues, keysToMove);
// factor we want to remove
// NOTE: we can remove factors, paying attention that the remaining graph remains connected
// we remove a single factor, the number 1, which is a BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery);
std::vector<size_t> removeFactorIndices(1,4);
// Add no factors to the filter (we only want to test the removal)
NonlinearFactorGraph noFactors;
Values noValues;
filter.update(noFactors, noValues, keysToMove, removeFactorIndices);
NonlinearFactorGraph actualGraph = filter.getFactors();
NonlinearFactorGraph expectedGraph;
expectedGraph.emplace_shared<PriorFactor<Pose3> >(1, poseInitial, noisePrior);
expectedGraph.emplace_shared<BetweenFactor<Pose3> >(1, 2, poseOdometry, noiseOdometery);
expectedGraph.emplace_shared<BetweenFactor<Pose3> >(2, 3, poseOdometry, noiseOdometery);
expectedGraph.emplace_shared<BetweenFactor<Pose3> >(3, 4, poseOdometry, noiseOdometery);
// we removed this one: expectedGraph.emplace_shared<BetweenFactor<Pose3> >(1, 2, poseOdometry, noiseOdometery);
// we should add an empty one, so that the ordering and labeling of the factors is preserved
expectedGraph.push_back(NonlinearFactor::shared_ptr());
CHECK(assert_equal(expectedGraph, actualGraph, 1e-6));
}
///* ************************************************************************* */
TEST( ConcurrentBatchFilter, removeFactors_topology_3 )
{
std::cout << "*********************** removeFactors_topology_3 ************************" << std::endl;
// we try removing the first factor
// Create a set of optimizer parameters
LevenbergMarquardtParams parameters;
ConcurrentBatchFilter filter(parameters);
// Add some factors to the filter
NonlinearFactorGraph newFactors;
newFactors.push_back(PriorFactor<Pose3>(1, poseInitial, noisePrior));
newFactors.push_back(PriorFactor<Pose3>(1, poseInitial, noisePrior));
newFactors.push_back(BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery));
newFactors.push_back(BetweenFactor<Pose3>(2, 3, poseOdometry, noiseOdometery));
newFactors.push_back(BetweenFactor<Pose3>(3, 4, poseOdometry, noiseOdometery));
Values newValues;
newValues.insert(1, Pose3().compose(poseError));
newValues.insert(2, newValues.at<Pose3>(1).compose(poseOdometry).compose(poseError));
newValues.insert(3, newValues.at<Pose3>(2).compose(poseOdometry).compose(poseError));
newValues.insert(4, newValues.at<Pose3>(3).compose(poseOdometry).compose(poseError));
// Specify a subset of variables to marginalize/move to the smoother
FastList<Key> keysToMove;
// Update the filter: add all factors
filter.update(newFactors, newValues, keysToMove);
// factor we want to remove
// NOTE: we can remove factors, paying attention that the remaining graph remains connected
// we remove a single factor, the number 0, which is a BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery);
std::vector<size_t> removeFactorIndices(1,0);
// Add no factors to the filter (we only want to test the removal)
NonlinearFactorGraph noFactors;
Values noValues;
filter.update(noFactors, noValues, keysToMove, removeFactorIndices);
NonlinearFactorGraph actualGraph = filter.getFactors();
NonlinearFactorGraph expectedGraph;
// we should add an empty one, so that the ordering and labeling of the factors is preserved
expectedGraph.push_back(NonlinearFactor::shared_ptr());
expectedGraph.emplace_shared<PriorFactor<Pose3> >(1, poseInitial, noisePrior);
expectedGraph.emplace_shared<BetweenFactor<Pose3> >(1, 2, poseOdometry, noiseOdometery);
expectedGraph.emplace_shared<BetweenFactor<Pose3> >(2, 3, poseOdometry, noiseOdometery);
expectedGraph.emplace_shared<BetweenFactor<Pose3> >(3, 4, poseOdometry, noiseOdometery);
CHECK(assert_equal(expectedGraph, actualGraph, 1e-6));
}
///* ************************************************************************* */
TEST( ConcurrentBatchFilter, removeFactors_values )
{
std::cout << "*********************** removeFactors_values ************************" << std::endl;
// we try removing the last factor
// Create a set of optimizer parameters
LevenbergMarquardtParams parameters;
ConcurrentBatchFilter filter(parameters);
// Add some factors to the filter
NonlinearFactorGraph newFactors;
newFactors.emplace_shared<PriorFactor<Pose3> >(1, poseInitial, noisePrior);
newFactors.emplace_shared<BetweenFactor<Pose3> >(1, 2, poseOdometry, noiseOdometery);
newFactors.emplace_shared<BetweenFactor<Pose3> >(2, 3, poseOdometry, noiseOdometery);
newFactors.emplace_shared<BetweenFactor<Pose3> >(3, 4, poseOdometry, noiseOdometery);
newFactors.emplace_shared<BetweenFactor<Pose3> >(1, 2, poseOdometry, noiseOdometery);
Values newValues;
newValues.insert(1, Pose3().compose(poseError));
newValues.insert(2, newValues.at<Pose3>(1).compose(poseOdometry).compose(poseError));
newValues.insert(3, newValues.at<Pose3>(2).compose(poseOdometry).compose(poseError));
newValues.insert(4, newValues.at<Pose3>(3).compose(poseOdometry).compose(poseError));
// Specify a subset of variables to marginalize/move to the smoother
FastList<Key> keysToMove;
// Update the filter: add all factors
filter.update(newFactors, newValues, keysToMove);
// factor we want to remove
// NOTE: we can remove factors, paying attention that the remaining graph remains connected
// we remove a single factor, the number 4, which is a BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery);
std::vector<size_t> removeFactorIndices(1,4);
// Add no factors to the filter (we only want to test the removal)
NonlinearFactorGraph noFactors;
Values noValues;
filter.update(noFactors, noValues, keysToMove, removeFactorIndices);
NonlinearFactorGraph actualGraph = filter.getFactors();
Values actualValues = filter.calculateEstimate();
// note: factors are removed before the optimization
NonlinearFactorGraph expectedGraph;
expectedGraph.emplace_shared<PriorFactor<Pose3> >(1, poseInitial, noisePrior);
expectedGraph.emplace_shared<BetweenFactor<Pose3> >(1, 2, poseOdometry, noiseOdometery);
expectedGraph.emplace_shared<BetweenFactor<Pose3> >(2, 3, poseOdometry, noiseOdometery);
expectedGraph.emplace_shared<BetweenFactor<Pose3> >(3, 4, poseOdometry, noiseOdometery);
// we removed this one: expectedGraph.emplace_shared<BetweenFactor<Pose3> >(1, 2, poseOdometry, noiseOdometery);
// we should add an empty one, so that the ordering and labeling of the factors is preserved
expectedGraph.push_back(NonlinearFactor::shared_ptr());
// Calculate expected factor graph and values
Values expectedValues = BatchOptimize(expectedGraph, newValues);
CHECK(assert_equal(expectedGraph, actualGraph, 1e-6));
CHECK(assert_equal(expectedValues, actualValues, 1e-6));
}
///* ************************************************************************* */
//TEST( ConcurrentBatchFilter, synchronize_10 )
//{
// // Create a set of optimizer parameters
// LevenbergMarquardtParams parameters;
// parameters.maxIterations = 1;
//
// // Create a Concurrent Batch Filter
// ConcurrentBatchFilter filter(parameters);
//
// // Insert factors into the filter, and marginalize out several variables.
// // This test places several factors in the smoother side, while leaving
// // several factors on the filter side
//}
//
///* ************************************************************************* */
//TEST( ConcurrentBatchFilter, synchronize_11 )
//{
// // Create a set of optimizer parameters
// LevenbergMarquardtParams parameters;
// parameters.maxIterations = 1;
//
// // Create a Concurrent Batch Filter
// ConcurrentBatchFilter filter(parameters);
//
// // Insert factors into the filter, and marginalize out several variables.
//
// // Generate a non-empty smoother update, simulating synchronizing with a non-empty smoother
//}
/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr);}
/* ************************************************************************* */
|
// See LICENSE_CELLO file for license and copyright information
/// @file data_Data.cpp
/// @author James Bordner (jobordner@ucsd.edu)
/// @date 2013-03-10
/// @brief Implementation of Data class
#include "data.hpp"
//----------------------------------------------------------------------
Data::Data(int nx, int ny, int nz,
int num_field_data,
double xm, double xp,
double ym, double yp,
double zm, double zp,
FieldDescr * field_descr,
ParticleDescr * particle_descr) throw ()
: num_field_data_(num_field_data),
field_data_(),
particle_data_(),
flux_data_()
{
if (field_descr == nullptr)
field_descr = cello::field_descr();
if (particle_descr == nullptr)
particle_descr = cello::particle_descr();
// Initialize field data
field_data_.resize(num_field_data);
for (size_t i=0; i<field_data_.size(); i++) {
field_data_[i] = new FieldData (field_descr,nx,ny,nz);
}
// Initialize particle data
particle_data_ = new ParticleData;
particle_data_->allocate(particle_descr);
// Initialize flux data
flux_data_ = new FluxData;
lower_[0] = xm;
lower_[1] = ym;
lower_[2] = zm;
upper_[0] = xp;
upper_[1] = yp;
upper_[2] = zp;
}
//----------------------------------------------------------------------
Data::~Data() throw ()
{
// Deallocate field_data_[]
for (size_t i=0; i<field_data_.size(); i++) {
delete field_data_[i];
field_data_[i] = nullptr;
}
num_field_data_ = 0;
delete particle_data_;
particle_data_ = nullptr;
delete flux_data_;
flux_data_ = nullptr;
}
//----------------------------------------------------------------------
Data::Data(const Data & data) throw ()
/// @param data Object being copied
:
num_field_data_(data.num_field_data_)
{
copy_(data);
}
//----------------------------------------------------------------------
Data & Data::operator= (const Data & data) throw ()
/// @param data Source object of the assignment
/// @return The target assigned object
{
copy_(data);
return *this;
}
//----------------------------------------------------------------------
void Data::field_cell_faces (double * x, double * y, double * z,
int gx, int gy, int gz,
int cx, int cy, int cz) const
{
// cx, cy, and cz are expected to be 1 or 0. If its 0, then the
// position along the corresponding dimension are for cell centers
double hx,hy,hz;
field_cell_width (&hx,&hy,&hz);
double xm,ym,zm;
this->lower(&xm,&ym,&zm);
int nx,ny,nz;
field_data()->size(&nx,&ny,&nz);
int ixm = -gx;
int iym = -gy;
int izm = -gz;
int ixp = nx+gx+cx;
int iyp = ny+gy+cy;
int izp = nz+gz+cz;
double dx = (cx == 0) ? 0.5 : 0;
double dy = (cy == 0) ? 0.5 : 0;
double dz = (cz == 0) ? 0.5 : 0;
for (int ix=ixm; ix<ixp; ix++) x[ix-ixm] = xm + (ix+dx)*hx;
for (int iy=iym; iy<iyp; iy++) y[iy-iym] = ym + (iy+dy)*hy;
for (int iz=izm; iz<izp; iz++) z[iz-izm] = zm + (iz+dz)*hz;
}
//----------------------------------------------------------------------
void Data::field_cell_width
(double * hx,
double * hy,
double * hz) const
{
double xm,ym,zm;
this->lower(&xm,&ym,&zm);
double xp,yp,zp;
this->upper(&xp,&yp,&zp);
field_data()->cell_width(xm,xp,hx, ym,yp,hy, zm,zp,hz);
}
//----------------------------------------------------------------------
void Data::allocate () throw()
{
// allocate Block scalar storage
scalar_data_long_double_.allocate(cello::scalar_descr_long_double());
scalar_data_double_ .allocate(cello::scalar_descr_double());
scalar_data_int_ .allocate(cello::scalar_descr_int());
scalar_data_sync_ .allocate(cello::scalar_descr_sync());
scalar_data_void_ .allocate(cello::scalar_descr_void());
// allocate Block Field storage
for (size_t i=0; i<field_data_.size(); i++) {
field_data_[i]->set_history_(cello::field_descr());
field_data_[i]->allocate_permanent(cello::field_descr(),true);
}
// initialize Flux field list
}
//======================================================================
void Data::copy_(const Data & data) throw()
{
num_field_data_ = data.num_field_data_;
field_data_.resize(data.field_data_.size());
for (size_t i=0; i<field_data_.size(); i++) {
field_data_[i] = new FieldData (*(data.field_data_[i]));
}
particle_data_ = new ParticleData (*data.particle_data_);
flux_data_ = new FluxData (*data.flux_data_);
}
|
/****************************************************************************/
/*
For direct access (i.e. non sysfile) to pins SEL0..2 and RX_RESETPIN
see : https://www.iot-programmer.com/index.php/books/22-raspberry-pi-and-the-iot-in-c/chapters-raspberry-pi-and-the-iot-in-c/59-raspberry-pi-and-the-iot-in-c-memory-mapped-gpio?start=2
*/
volatile unsigned * map_peripherals(void) {
void *gpio_map;
int mem_fd;
/* open /dev/mem */
if ((mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0) {
perror("opening /dev/mem");
exit(-1);
}
/* mmap GPIO */
gpio_map = mmap(
NULL, //Any adddress in our space will do
BLOCK_SIZE, //Map length
PROT_READ|PROT_WRITE,// Enable reading & writting to mapped memory
MAP_SHARED, //Shared with other processes
mem_fd, //File to map
GPIO_BASE //Offset to GPIO peripheral
);
if (gpio_map == MAP_FAILED) {
perror("mmap(/dev/mem)");//errno also set!
exit(-1);
}
// Always use volatile pointer!
// gpio = (volatile unsigned *)gpio_map;
return (volatile unsigned *)gpio_map;
close(mem_fd); //No need to keep mem_fd open after mmap
} // end map_peripherals
/****************************************************************************/
/*
defines pin mode
pin = gpio pin, mode = 0|1|2
returns none
*/
void pinMode(int pin, int mode){
switch(mode){
case 0:
INP_GPIO(pin); // must use INP_GPIO before we can use OUT_GPIO
OUT_GPIO(pin);
break;
case 1:
INP_GPIO(pin);
GPIO_PULL = 0;
break;
case 2:
INP_GPIO(pin);
GPIO_PULL = 2;
break;
default:
INP_GPIO(pin);
GPIO_PULL = 0;
break;
}
/****************************************************************************/
// sets pull-up/float
usleep(10);
if (pin>= 32)
GPIO_PULLCLK1 = (1 << (pin % 32));
else
GPIO_PULLCLK0 = (1 << pin);
usleep(10);
GPIO_PULL = 0;
if (pin>= 32)
GPIO_PULLCLK1 = 0;
else
GPIO_PULLCLK0 = 0;
/****************************************************************************/
}// end pinMode(int pin, int mode)
/*
defines pin value
pin = gpio pin, value = 0|1
returns none
*/
void digitalWrite(int pin, int value){
switch(value){
case 0:
if (pin>= 32)
GPIO_CLR_EXT = (1 << (pin % 32));
else
GPIO_CLR = (1 << pin);
break;
case 1:
if (pin>= 32)
GPIO_SET_EXT = (1 << (pin % 32));
else
GPIO_SET = (1 << pin);
break;
default:
// no change
break;
}
} // end void digitalWrite(int pin, int mode)
/****************************************************************************/
/*
gets pin value
pin = gpio pin
returns 0|1
*/
int digitalRead(int pin){
if (GET_GPIO(pin)) // !=0 <-> bit is 1 <- port is HIGH=3.3V
return 1;
else // port is LOW=0V
return 0;
} // end void digitalRead(int pin)
/****************************************************************************/
int createInterruptFile(int pin, int edge){
int fdreturned;
char filename[255] ="";
char pinval[3]="";
FILE * fd;
sprintf(filename, "/sys/class/gpio/gpio%d",pin);
strcat(filename, "/edge");
if ((fd = fopen(filename, "r+")) == NULL) {
fd = fopen("/sys/class/gpio/export", "w");
sprintf(pinval, "%d",pin);
fprintf(fd, "%s", pinval);
fclose(fd);
sprintf(filename, "/sys/class/gpio/gpio%d", pin);
strcat(filename, "/edge");
fd = fopen(filename, "r+");
switch(edge){
case 0:
fprintf(fd, "falling");
break;
case 1:
fprintf(fd, "rising");
break;
default:
fprintf(fd, "falling");
break;
}
fclose(fd);
} else {
switch(edge){
case 0:
fprintf(fd, "falling");
break;
case 1:
fprintf(fd, "rising");
break;
default:
fprintf(fd, "falling");
break;
}
fclose(fd);
}
sprintf(filename, "/sys/class/gpio/gpio%d", pin);
strcat(filename, "/value");
if ((fdreturned = open(filename, O_RDONLY)) < 0) {
perror("value file: ");
return -1;
exit(EXIT_FAILURE);
} else {
return fdreturned;
}
}// end int createInterruptFile(int, int);
/****************************************************************************/
/*
Permit to select the mode we want to the LoRa pin
pin that are connected to the LoRa are in mu
*/
void hardwareSetup(int resetpin){
// pins init
pinMode(resetpin, INPUT);
// modules reset
pinMode(resetpin, OUTPUT);
digitalWrite(resetpin, HIGH);
usleep(50000);
pinMode(resetpin, INPUT);
usleep(50000);
}// end hardwareSetup(int, int, int, int);
/*
Reset all pin and unselect all mode
*/
void hardwareReset(){
// pins init
pinMode(TX_RESETPIN, INPUT);
// modules reset
pinMode(TX_RESETPIN, OUTPUT);
digitalWrite(TX_RESETPIN, LOW);
usleep(50000);
pinMode(TX_RESETPIN, INPUT);
usleep(50000);
// pins init
pinMode(RX_RESETPIN, INPUT);
// modules reset
pinMode(RX_RESETPIN, OUTPUT);
digitalWrite(RX_RESETPIN, LOW);
usleep(50000);
pinMode(RX_RESETPIN, INPUT);
usleep(50000);
}
/****************************************************************************/
/*
Write to a register using the SPI librairies
*/
void writeRegister(__u8 address, __u8 data) {
bitSet(address, 7); // Bit 7 set to write in registers
char buffer[2];
buffer[0]= address;
buffer[1]= data;
spi.transfer(SPI0, buffer, 2);
}// end writeRegister()
/****************************************************************************/
__u8 readRegister(__u8 address) {
bitClear(address, 7); // Bit 7 cleared to read from registers
char buffer[2];
buffer[0]= (char) address;
buffer[1]= (char) 0x55;
spi.transfer(SPI0, buffer, 2);
return (__u8) buffer[1];
}// end readRegister()
/****************************************************************************/
/*
Init the LoRa module
mode permit to diffentiate some register and value according to witch mode we want
*/
void initModule(int mode) {
// module in lora mode
writeRegister(REG_OP_MODE, FSK_SLEEP_MODE); // to change bit 7!!
writeRegister(REG_OP_MODE, LORA_SLEEP_MODE);
writeRegister(REG_OP_MODE, LORA_STANDBY_MODE); // to fill-in the fifo
usleep(100 * 1000);
writeRegister(REG_FIFO, 0x00);
if (mode == TX_MODE){
int pout = 0;
writeRegister(REG_PA_CONFIG, 0x80 | pout);
}else{
writeRegister(REG_PA_CONFIG, 0x01); // out=RFIO, Pout=0dBm
}
writeRegister(REG_PA_RAMP, 0x19); // low cons PLL TX&RX, 40us
writeRegister(REG_OCP, 0b00101011); //OCP enabled, 100mA
writeRegister(REG_LNA, 0b00100011); // max gain, BOOST on
writeRegister(REG_FIFO_ADDR_PTR, 0x00); // pointeur pour l'accès à la FIFO via SPI (read or write)
writeRegister(REG_FIFO_TX_BASE_ADDR, 0x80); // top half
writeRegister(REG_FIFO_RX_BASE_ADDR, 0x00); // bottom half
writeRegister(REG_IRQ_FLAGS_MASK, 0x00); // toutes IRQ actives
writeRegister(REG_IRQ_FLAGS, 0xff); // RAZ de toutes IRQ
// en mode Explicit Header, CRC enable ou disable n'a aucune importance pour RX, tout dépend de la config TX
//writeRegister(REG_MODEM_CONFIG1, 0b10001000); //BW=500k, CR=4/5, explicit header, CRC disable, LDRO disabled
//writeRegister(REG_MODEM_CONFIG1, 0b00001001); //BW=125k, CR=4/5, explicit header, CRC disable, LDRO enabled
//writeRegister(REG_MODEM_CONFIG1, 0b00100001); //BW=125k, CR=4/8, explicit header, CRC disable, LDRO enabled
writeRegister(REG_MODEM_CONFIG1, 0b00100011); //BW=125k, CR=4/8, explicit header, CRC enable, LDRO enabled
//writeRegister(REG_MODEM_CONFIG1, 0b10001010); //BW=500k, CR=4/5, explicit header, CRC enable, LDRO disabled
writeRegister(REG_MODEM_CONFIG2, 0b11000111); // SF=12, normal TX mode, AGC auto on, RX timeout MSB = 11
writeRegister(REG_SYMB_TIMEOUT_LSB, 0xff); // max timeout
writeRegister(REG_PREAMBLE_MSB_LORA, 0x00); // default value
writeRegister(REG_PREAMBLE_LSB_LORA, 0x08);
writeRegister(REG_MAX_PAYLOAD_LENGTH, 0x80); // half the FIFO
writeRegister(REG_HOP_PERIOD, 0x00); // freq hopping disabled
writeRegister(REG_DETECT_OPTIMIZE, 0xc3); // pour SF=12
writeRegister(REG_INVERT_IQ, 0x27); // default value, IQ not inverted
writeRegister(REG_DETECTION_THRESHOLD, 0x0A); // pour SF=12
writeRegister(REG_SYNC_WORD, 0x12); // default value
}
/****************************************************************************/
/*
Function that define an 32 bit value containing REG_FRF_MSB, REG_FRF_MID & REG_FRF_LSB
*/
void setChanHex(void){
// sets the 32 bit value containing the frequency value (REG_FRF_MSB, REG_FRF_MID & REG_FRF_LSB)
chanHex[0] = 0xD84CCC; // channel 10, freq = 865.20MHz
chanHex[1] = 0xD86000; // channel 11, freq = 865.50MHz
chanHex[2] = 0xD87333; // channel 12, freq = 865.80MHz
chanHex[3] = 0xD88666; // channel 13, freq = 866.10MHz
chanHex[4] = 0xD89999; // channel 14, freq = 866.40MHz
// Pour le projet on utilise ce channel
chanHex[5] = 0xD8ACCC; // channel 15, freq = 866.70MHz
chanHex[6] = 0xD8C000; // channel 16, freq = 867.00MHz
chanHex[7] = 0xD90000; // channel 16, freq = 868.00MHz
}
/****************************************************************************/
void setLoraChannel(int channel){
writeRegister(REG_FRF_LSB, chanHex[channel] & 0x000000ff);
writeRegister(REG_FRF_MID, (chanHex[channel] >> 8) & 0x000000ff);
writeRegister(REG_FRF_MSB, (chanHex[channel] >> 16) & 0x000000ff);
}
/****************************************************************************/
__u32 getLoraChannel(void){
__u32 channel;
channel = readRegister(REG_FRF_MSB)*65536 + readRegister(REG_FRF_MID)*256 + readRegister(REG_FRF_LSB);
return channel;
}
/****************************************************************************/
void printLoraChannelToStdout(__u32 channel){
switch(channel){
case 0xD84CCC:
fprintf(stdout,"channel 10, freq = 865.20MHz");
break;
case 0xD86000:
fprintf(stdout,"channel 11, freq = 865.50MHz");
break;
case 0xD87333:
fprintf(stdout,"channel 12, freq = 865.80MHz");
break;
case 0xD88666:
fprintf(stdout,"channel 13, freq = 866.10MHz");
break;
case 0xD89999:
fprintf(stdout,"channel 14, freq = 866.40MHz");
break;
case 0xD8ACCC:
fprintf(stdout,"channel 15, freq = 866.70MHz");
break;
case 0xD8C000:
fprintf(stdout,"channel 16, freq = 867.00MHz");
break;
case 0xD90000:
fprintf(stdout,"channel 17, freq = 868.00MHz");
break;
default:
fprintf(stdout,"!ERROR! unknown channel");
break;
}
fprintf(stdout,"\n");
}
/****************************************************************************/
void printLoraChannelToFile(__u32 channel, FILE * fd){
switch(channel){
case 0xD84CCC:
fprintf(fd,"channel 10, freq = 865.20MHz");
break;
case 0xD86000:
fprintf(fd,"channel 11, freq = 865.50MHz");
break;
case 0xD87333:
fprintf(fd,"channel 12, freq = 865.80MHz");
break;
case 0xD88666:
fprintf(fd,"channel 13, freq = 866.10MHz");
break;
case 0xD89999:
fprintf(fd,"channel 14, freq = 866.40MHz");
break;
case 0xD8ACCC:
fprintf(fd,"channel 15, freq = 866.70MHz");
break;
case 0xD8C000:
fprintf(fd,"channel 16, freq = 867.00MHz");
break;
case 0xD90000:
fprintf(fd,"channel 17, freq = 868.00MHz");
break;
default:
fprintf(fd,"!ERROR! unknown channel");
break;
}
}
/****************************************************************************/
void checkMessageLoRa(int rxindex){
int j;
int msgok = 1; // message received by default
struct timeval tstart, tcurr;
long delta;
__u8 regVal;
__u8 reg_val_table[255] = {0};
int rssi;
int nb_rec_bytes;
char filename[255] ="";
regVal = readRegister(REG_IRQ_FLAGS); // reads interruption flags
if(bitRead(regVal, 4) == 0x01){ // here, we have a valid header
lastMessageIndex[rxindex]++;
//Open the log file & index file of current channel
sprintf(filename, "/tmp/channel%2d.log",10+rxindex);
if ((fd_log = fopen(filename, "a+")) < 0) {
perror("log file:");
exit(EXIT_FAILURE);
}
sprintf(filename, "/tmp/channel%2d.index",10+rxindex);
if ((fd_index = fopen(filename, "w+")) < 0) {
perror("index file:");
exit(EXIT_FAILURE);
}
fprintf(fd_index,"%09u\n", lastMessageIndex[rxindex]);
fclose(fd_index);
fprintf(fd_log,"%09d: Valid header received on ", lastMessageIndex[rxindex]);
printLoraChannelToFile(getLoraChannel(), fd_log);
fprintf(fd_log,"\nTime stamp: ");
// reads and prints the time at which the event occured
//get_date(fd_log);
// Step 5a: waits for RXdone before timeout
if (!bitRead(regVal, 6)){
while ((!bitRead(regVal,6)) && (!bitRead(regVal,6))){
regVal = readRegister(REG_IRQ_FLAGS);
}
}
if (!bitRead(regVal,6)) msgok=0; // no message before timeout
if (msgok){
fprintf(fd_log,"****************** Message received on %d : %d ******************\n",10 +rxindex,lastMessageIndex[rxindex]);
fprintf(stdout,"****************** Message received on %d : %d ******************\n",10 +rxindex,lastMessageIndex[rxindex]);
// Step 5b: test CRC
if (bitRead(regVal, 5)){
fprintf(fd_log,"|------[+] !WARNING! Payload CRC error\n");
fprintf(stdout,"|------[+] !WARNING! Payload CRC error\n");
} else {
fprintf(fd_log,"|------[+] Payload CRC OK (INFO: test relevance depends on transmitter configuration)\n");
fprintf(stdout,"|------[+] Payload CRC OK (INFO: test relevance depends on transmitter configuration)\n");
}
nb_rec_bytes= readRegister(REG_RX_NB_BYTES);
fprintf(fd_log,"|------[+] Number of bytes received = %d\n", nb_rec_bytes);
fprintf(stdout,"|------[+] Number of bytes received = %d\n", nb_rec_bytes);
// step 6: get data
writeRegister(REG_FIFO_ADDR_PTR, readRegister(REG_FIFO_RX_CURRENT_ADDR)); //REG_FIFO_RX_CURRENT_ADDR -> FifoAddrPtr
for (j = 0; j < nb_rec_bytes; j++){
reg_val_table[j] = readRegister(REG_FIFO);
} // end for (j = 0; j < nb_rec_bytes; j++)
fprintf(fd_log, "|------[+] Message as hexa:");
fprintf(stdout, "|------[+] Message as hexa:");
for (j = 0; j < nb_rec_bytes; j++){
fprintf(fd_log, " %x |", reg_val_table[j]);
fprintf(stdout, " %x |", reg_val_table[j]);
} // end for (j = 0; j < nb_rec_bytes; j++)
fprintf(fd_log, "\n");
fprintf(stdout, "\n");
__u8 * msgTx = (__u8 *) malloc(BUFLEN);
client.sendToServer(reg_val_table,msgTx); // send a socket message
sendTxMessage(msgTx);
fprintf(fd_log, "\n");
fprintf(stdout, "\n");
} else {
fprintf(fd_log,"[+] ERROR: Valid header received but no message received before %d microseconds timeout\n", rxTimeout);
}// end if (msgok)
fclose(fd_log);
writeRegister(REG_IRQ_FLAGS, 0xff); // IRQ reset for this receiver anyway
} // end if(bitRead(reg_val, 4) == 0x01)
}// end getReceiver2(int rxindex, int rxTimeout)
/****************************************************************************/
/*
select mode (Tx ou Rx)
0 -> Rx
1 -> Tx */
void selectLoRaMode(int mode){
hardwareReset();
switch (mode){
case RX_MODE:
// modules reset
hardwareSetup(RX_RESETPIN); // RX_RESETPIN as input and resets the module
//initModule(RX_MODE); // initialize modules (TX & RX) but NOT the channel
setLoraChannel(RX_CHANNEL-10); // initialize the channel
rxConfig();
printLoraChannelToStdout(getLoraChannel());
fprintf(stdout,"\n");
break;
case TX_MODE:
// modules reset
hardwareSetup(TX_RESETPIN); // TX_RESETPIN as input and resets the module
initModule(TX_MODE);
setLoraChannel(TX_CHANNEL - 10); // initialize the channel
fprintf(stdout,"\n****************** SENDING MESSAGE ******************");
fprintf(stdout,"\n|------[+] TX configuration for ");printLoraChannelToStdout(getLoraChannel());
break;
default:
break;
}
}
void rxConfig(void){
fprintf(stdout,"[+] Configuration for RX mode... ");
// initModule() unmasks ALL interruptions by default
/*
writeRegister(REG_DIO_MAPPING1, 0x01); // DIO0=RxDone, DIO1=RxTimeout, DIO2=FhssChangeChannel, DIO3=ValidHeader
writeRegister(REG_DIO_MAPPING2, 0x00); // default values
writeRegister(REG_IRQ_FLAGS_MASK, 0x8f); // only Rxdone, CRC error , valid header enabled
*/
writeRegister(REG_IRQ_FLAGS, 0xff); // clears all IRQs
// datasheet step 1: FifoRxBaseDddress -> FifoAddrPtr
writeRegister(REG_FIFO_ADDR_PTR, readRegister(REG_FIFO_RX_BASE_ADDR));
//datasheet Step2: done in init
//datasheet Step3: RX continuous mode
writeRegister(REG_OP_MODE, LORA_RX_CONTINUOUS_MODE);
usleep(100 * 1000); // delay necessary to start oscillator & PLL (SLEEP -> other mode)
fprintf(stdout,"... done\n");
fprintf(stdout,"[+] Configuration completed, waiting for messages on : ");
}
void sendTxMessage(__u8 message[]) {
sleep(WAITING_CHANGE_MODE);
selectLoRaMode(TX_MODE);
int payloadLength = 13;
// datasheet step 1: loads the FIFO
writeRegister(REG_FIFO_ADDR_PTR, readRegister(REG_FIFO_TX_BASE_ADDR)); //FifoTxBaseDddress -> FifoAddrPtr
writeRegister(REG_PAYLOAD_LENGTH_LORA, payloadLength); // defines payload length
for (int i=0; i<payloadLength; i++){
writeRegister(REG_FIFO, message[i]);
}
fprintf(stdout,"|------[+] Configuration completed, transmitting message...\n");
//datasheet Step2: TX mode
writeRegister(REG_OP_MODE, LORA_TX_MODE);
usleep(100000); // delay necessary to start oscillator & PLL (SLEEP -> other mode)
//datasheet Step3: wait for TX completion
int status;
while((status = bitRead(readRegister(REG_IRQ_FLAGS),3)) == 0){
// fprintf(stdout,"reg_irq_flag = 0x%02x\n", status);
}
// reset of interruption
writeRegister(REG_IRQ_FLAGS, 0xff);
fprintf(stdout,"|------[+] TX completed\n\n");
selectLoRaMode(RX_MODE); //On retourne en Rx mode
}
|
/**
* @file
*/
#pragma once
#include "libbirch/external.hpp"
#include "libbirch/assert.hpp"
#include "libbirch/memory.hpp"
#include "libbirch/Atomic.hpp"
#include "libbirch/Init.hpp"
#include "libbirch/LabelPtr.hpp"
namespace libbirch {
class Label;
/**
* Base class providing reference counting, cycle breaking, and lazy deep
* copy support.
*
* @ingroup libbirch
*
* @attention A newly created object of type Any, or of a type derived from
* it, must be assigned to at least one Shared pointer in its lifetime to
* be correctly destroyed and deallocated. Furthermore, in order to work
* correctly with multiple inheritance, Any must be the *first* base class.
*/
class Any {
public:
using class_type_ = Any;
using this_type_ = Any;
/**
* Constructor.
*/
Any() :
label(root()),
sharedCount(0u),
memoCount(1u),
size(0u),
tid(get_thread_num()),
flags(0u) {
//
}
/**
* Special constructor for the root label.
*/
Any(int) :
label(nullptr),
sharedCount(0u),
memoCount(1u),
size(0u),
tid(0),
flags(0u) {
//
}
/**
* Copy constructor.
*/
Any(const Any& o) : Any() {
//
}
/**
* Destructor.
*/
virtual ~Any() {
assert(sharedCount.load() == 0u);
}
/**
* New operator.
*/
void* operator new(std::size_t size) {
return allocate(size);
}
/**
* Delete operator.
*/
void operator delete(void* ptr) {
auto o = static_cast<Any*>(ptr);
o->deallocate();
}
/**
* Assignment operator.
*/
Any& operator=(const Any&) {
return *this;
}
/**
* Finish the object.
*/
void finish(Label* label) {
if (!(flags.exchangeOr(FINISHED) & FINISHED)) {
finish_(label);
}
}
/**
* Freeze the object.
*/
void freeze() {
libbirch_assert_(isFinished());
if (!(flags.exchangeOr(FROZEN) & FROZEN)) {
if (sharedCount.load() == 1u) {
// ^ small optimization: isUnique() makes sense, but unnecessarily
// loads memoCount as well, which is unnecessary for a objects
// that are not frozen
flags.maskOr(FROZEN_UNIQUE);
}
freeze_();
}
}
/**
* Thaw the object.
*/
void thaw() {
flags.maskAnd(~BUFFERED);
}
/**
* Copy the object.
*
* @param label The new label.
*/
Any* copy(Label* label) {
auto o = copy_(label);
new (&o->label) decltype(o->label)(label);
o->sharedCount.store(0u);
o->memoCount.store(1u);
o->size = 0u;
o->tid = get_thread_num();
o->flags.store(0u);
return o;
}
/**
* Recycle the object. This can be used as an optimization in place of
* copy(), where only one pointer remains to the source object, and it would
* otherwise be copied and then destroyed; instead, the source object is
* modified for reuse.
*
* @param label The new label.
*/
void recycle(Label* label) {
this->label.replace(label);
this->flags.maskAnd(~(FINISHED|FROZEN|FROZEN_UNIQUE));
recycle_(label);
}
/**
* Mark the object.
*
* This performs the `MarkGray()` operation of @ref Bacon2001
* "Bacon & Rajan (2001)".
*/
void mark() {
if (!(flags.exchangeOr(MARKED) & MARKED)) {
flags.maskAnd(~(POSSIBLE_ROOT|BUFFERED|SCANNED|REACHED|COLLECTED));
label.mark();
mark_();
}
}
/**
* Scan the object.
*
* This performs the `Scan()` operation of @ref Bacon2001
* "Bacon & Rajan (2001)".
*/
void scan() {
if (!(flags.exchangeOr(SCANNED) & SCANNED)) {
flags.maskAnd(~MARKED); // unset for next time
if (numShared() > 0u) {
if (!(flags.exchangeOr(REACHED) & REACHED)) {
label.reach();
reach_();
}
} else {
label.scan();
scan_();
}
}
}
/**
* Reach the object.
*
* This performs the `ScanBlack()` operation of @ref Bacon2001
* "Bacon & Rajan (2001)".
*/
void reach() {
if (!(flags.exchangeOr(SCANNED) & SCANNED)) {
flags.maskAnd(~MARKED); // unset for next time
}
if (!(flags.exchangeOr(REACHED) & REACHED)) {
label.reach();
reach_();
}
}
/**
* Collect the object.
*
* This performs the `CollectWhite()` operation of @ref Bacon2001
* "Bacon & Rajan (2001)".
*/
void collect() {
auto old = flags.exchangeOr(COLLECTED);
if (!(old & COLLECTED) && !(old & REACHED)) {
register_unreachable(this);
label.collect();
collect_();
}
}
/**
* Destroy, but do not deallocate, the object.
*/
void destroy() {
assert(sharedCount.load() == 0u);
this->flags.maskOr(DESTROYED);
this->size = size_();
this->~Any();
}
/**
* Shared count.
*/
unsigned numShared() const {
return sharedCount.load();
}
/**
* Increment the shared count.
*/
void incShared() {
//flags.maskAnd(~POSSIBLE_ROOT);
// ^ any interleaving with decShared() switching on POSSIBLE_ROOT should
// not be problematic; having it on is never a correctness issue, only
// a performance issue, and as long as one thread can reach the object
// it is fine to be off
// ^ disabling this option improves performance on several examples
sharedCount.increment();
}
/**
* Decrement the shared count. This decrements the count; if the new count
* is nonzero, it registers the object as a possible root for cycle
* collection, or if the new count is zero, it destroys the object.
*/
void decShared() {
assert(numShared() > 0u);
/* if the count will reduce to nonzero, this is possibly the root of
* a cycle */
if (numShared() > 1u &&
!(flags.exchangeOr(BUFFERED|POSSIBLE_ROOT) & BUFFERED)) {
register_possible_root(this);
}
/* decrement */
if (--sharedCount == 0u) {
destroy();
decMemo();
}
}
/**
* Decrement the shared count with a known acyclic referent. This decrements
* the count, and if the new count is zero, it destroys the object. The
* caller asserts that the object is of acyclic type (@see is_acyclic), so
* that there is no need to register the object as a possible root for cycle
* collection.
*
* Acyclic objects occur in @ref Bacon2001 "Bacon & Rajan (2001)", where
* they are colored *green*.
*/
void decSharedAcyclic() {
assert(numShared() > 0u);
if (--sharedCount == 0u) {
destroy();
decMemo();
}
}
/**
* Decrement the shared count for an object that will remain reachable. The
* caller asserts that the object will remain reachable after the operation.
* The object will not be destroyed, and will not be registered as a
* possible root for cycle collection.
*/
void decSharedReachable() {
assert(numShared() > 0u);
sharedCount.decrement();
}
/**
* Memo count.
*/
unsigned numMemo() const {
return memoCount.load();
}
/**
* Increment the memo count.
*/
void incMemo() {
memoCount.increment();
}
/**
* Decrement the memo count.
*/
void decMemo() {
assert(memoCount.load() > 0u);
if (--memoCount == 0u) {
assert(numShared() == 0u);
deallocate();
}
}
/**
* Get the label assigned to the object.
*/
Label* getLabel() const {
return label.get();
}
/**
* Has the object been destroyed?
*/
bool isDestroyed() const {
return flags.load() & DESTROYED;
}
/**
* Is this object the possible root of a cycle?
*/
bool isPossibleRoot() const {
auto flags = this->flags.load();
return (flags & POSSIBLE_ROOT) && !(flags & DESTROYED);
}
/**
* Is there only one pointer (of any type) to this object?
*/
bool isUnique() const {
return numShared() == 1u && numMemo() == 1u;
}
/**
* Is the object finished?
*/
bool isFinished() const {
return flags.load() & FINISHED;
}
/**
* Is the object frozen?
*/
bool isFrozen() const {
return flags.load() & FROZEN;
}
/**
* Is the object frozen, and at the time of freezing, was there only one
* shared pointer to it?
*/
bool isFrozenUnique() const {
return flags.load() & FROZEN_UNIQUE;
}
private:
/**
* Deallocate the object. It should have previously been destroyed.
*/
void deallocate() {
assert(sharedCount.load() == 0u);
assert(memoCount.load() == 0u);
libbirch::deallocate(this, size, tid);
}
/**
* Label of the object.
*/
LabelPtr label;
/**
* Shared count.
*/
Atomic<unsigned> sharedCount;
/**
* Memo count, or, if the shared count is nonzero, one plus the memo count.
*/
Atomic<unsigned> memoCount;
/**
* Size of the object. This is initially set to zero. Upon destruction, it
* is set to the correct size with a virtual function call.
*/
unsigned size;
/**
* Id of the thread associated with the object. This is set immediately
* after allocation. It is used to return the allocation to the correct
* pool after use, even when returned by a different thread.
*/
int16_t tid;
/**
* Bitfield containing flags. These are, from least to most significant
* bits:
*
* - *finished*,
* - *frozen*,
* - *single reference when frozen*---
*
* ---these used for lazy deep copy operations as in @ref Murray2020
* "Murray (2020)"---then
*
* - *possible root*,
* - *buffered*,
* - *marked*,
* - *scanned*,
* - *reached*,
* - *collected*---
*
* ---these used for cycle collection as in @ref Bacon2001
* "Bacon & Rajan (2001)".
*
* The second group of flags take the place of the colors described in
* @ref Bacon2001 "Bacon & Rajan (2001)". The reason is to ensure that both
* the bookkeeping required during normal execution can be multithreaded,
* and likewise that the operations required during cycle collection can be
* multithreaded. The basic principle to ensure this is that flags can be
* safely set during normal execution (with atomic operations), but should
* only be unset with careful consideration of thread safety.
*
* Notwithstanding, the flags do map to colors in @ref Bacon2001
* "Bacon & Rajan (2001)":
*
* - *possible root* maps to *purple*,
* - *marked* maps to *gray*,
* - *scanned* and *reachable* together map to *black* (both on) or
* *white* (first on, second off),
* - *collected* is set once a white object has been destroyed.
*
* The use of these flags also resolves some thread safety issues that can
* otherwise exist during the scan operation, when coloring an object white
* (eligible for collection) then later recoloring it black (reachable); the
* sequencing of this coloring can become problematic with multiple threads.
*/
Atomic<uint16_t> flags;
/**
* Flags.
*/
enum Flag : uint16_t {
FINISHED = (1u << 0u),
FROZEN = (1u << 1u),
FROZEN_UNIQUE = (1u << 2u),
POSSIBLE_ROOT = (1u << 3u),
BUFFERED = (1u << 4u),
MARKED = (1u << 5u),
SCANNED = (1u << 6u),
REACHED = (1u << 7u),
COLLECTED = (1u << 8u),
DESTROYED = (1u << 9u)
};
public:
/**
* Get the class name.
*/
virtual const char* getClassName() const {
return "Any";
}
/**
* Size of the object.
*/
virtual unsigned size_() const {
return sizeof(*this);
}
/**
* Called internally by finish() to recurse into member variables.
*/
virtual void finish_(Label* label) = 0;
/**
* Called internally by freeze() to recurse into member variables.
*/
virtual void freeze_() = 0;
/**
* Called internally by copy() to ensure the most derived type is copied.
*/
virtual Any* copy_(Label* label) const = 0;
/**
* Called internally by recycle() to ensure the most derived type is
* recycled.
*/
virtual void recycle_(Label* label) = 0;
/**
* Called internally by mark() to recurse into member variables.
*/
virtual void mark_() = 0;
/**
* Called internally by scan() to recurse into member variables.
*/
virtual void scan_() = 0;
/**
* Called internally by reach() to recurse into member variables.
*/
virtual void reach_() = 0;
/**
* Called internally by collect() to recurse into member variables.
*/
virtual void collect_() = 0;
/**
* Accept a visitor across member variables.
*/
template<class Visitor>
void accept_(const Visitor& v) {
//
}
/**
* Type of members.
*/
using member_type_ = decltype(label);
};
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cms/Closeable.h>
using namespace cms;
////////////////////////////////////////////////////////////////////////////////
Closeable::~Closeable() {
}
|
// Copyright (c) 2018 Kai Luo <gluokai@gmail.com>. All rights reserved.
#include "re6/IterativeMatcher.h"
#include "re6/re.h"
#include <queue>
namespace re6 {
bool IterativeMatcher::Match() const {
// TODO: Make matching parallel
std::queue<State> worklist;
worklist.push({
.nfa_state = start_,
.slice = s_,
});
while (not worklist.empty()) {
State current = std::move(worklist.front());
worklist.pop();
if (current.slice.empty() && current.nfa_state == finish_) {
return true;
}
if (current.nfa_state->jump.count(EP)) {
for (auto t : current.nfa_state->jump[EP]) {
worklist.push({
.nfa_state = t,
.slice = current.slice,
});
}
}
if (not current.slice.empty() &&
current.nfa_state->jump.count(current.slice[0])) {
for (auto t : current.nfa_state->jump[current.slice[0]]) {
worklist.push({
.nfa_state = t,
.slice = current.slice.advance(),
});
}
}
}
return false;
}
} // namespace re6
|
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Wavi Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/wavi-config.h"
#endif
#include "bitcoingui.h"
#include "chainparams.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "intro.h"
#include "net.h"
#include "networkstyle.h"
#include "optionsmodel.h"
#include "platformstyle.h"
#include "splashscreen.h"
#include "utilitydialog.h"
#include "winshutdownmonitor.h"
#ifdef ENABLE_WALLET
#include "paymentserver.h"
#include "walletmodel.h"
#endif
#include "masternodeconfig.h"
#include "init.h"
#include "rpc/server.h"
#include "scheduler.h"
#include "ui_interface.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif
#include <stdint.h>
#include <boost/filesystem/operations.hpp>
#include <boost/thread.hpp>
#include <QApplication>
#include <QDebug>
#include <QLibraryInfo>
#include <QLocale>
#include <QMessageBox>
#include <QProcess>
#include <QSettings>
#include <QThread>
#include <QTimer>
#include <QTranslator>
#include <QSslConfiguration>
#if defined(QT_STATICPLUGIN)
#include <QtPlugin>
#if QT_VERSION < 0x050000
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#else
#if QT_VERSION < 0x050400
Q_IMPORT_PLUGIN(AccessibleFactory)
#endif
#if defined(QT_QPA_PLATFORM_XCB)
Q_IMPORT_PLUGIN(QXcbIntegrationPlugin);
#elif defined(QT_QPA_PLATFORM_WINDOWS)
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
#elif defined(QT_QPA_PLATFORM_COCOA)
Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin);
#endif
#endif
#endif
#if QT_VERSION < 0x050000
#include <QTextCodec>
#endif
// Declare meta types used for QMetaObject::invokeMethod
Q_DECLARE_METATYPE(bool*)
Q_DECLARE_METATYPE(CAmount)
static void InitMessage(const std::string &message)
{
LogPrintf("init message: %s\n", message);
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("wavi-core", psz).toStdString();
}
static QString GetLangTerritory()
{
QSettings settings;
// Get desired locale (e.g. "de_DE")
// 1) System default language
QString lang_territory = QLocale::system().name();
// 2) Language from QSettings
QString lang_territory_qsettings = settings.value("language", "").toString();
if(!lang_territory_qsettings.isEmpty())
lang_territory = lang_territory_qsettings;
// 3) -lang command line argument
lang_territory = QString::fromStdString(GetArg("-lang", lang_territory.toStdString()));
return lang_territory;
}
/** Set up translations */
static void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator)
{
// Remove old translators
QApplication::removeTranslator(&qtTranslatorBase);
QApplication::removeTranslator(&qtTranslator);
QApplication::removeTranslator(&translatorBase);
QApplication::removeTranslator(&translator);
// Get desired locale (e.g. "de_DE")
// 1) System default language
QString lang_territory = GetLangTerritory();
// Convert to "de" only by truncating "_DE"
QString lang = lang_territory;
lang.truncate(lang_territory.lastIndexOf('_'));
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
QApplication::installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
QApplication::installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in wavi.qrc)
if (translatorBase.load(lang, ":/translations/"))
QApplication::installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in wavi.qrc)
if (translator.load(lang_territory, ":/translations/"))
QApplication::installTranslator(&translator);
}
/* qDebug() message handler --> debug.log */
#if QT_VERSION < 0x050000
void DebugMessageHandler(QtMsgType type, const char *msg)
{
const char *category = (type == QtDebugMsg) ? "qt" : NULL;
LogPrint(category, "GUI: %s\n", msg);
}
#else
void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg)
{
Q_UNUSED(context);
const char *category = (type == QtDebugMsg) ? "qt" : NULL;
LogPrint(category, "GUI: %s\n", msg.toStdString());
}
#endif
/** Class encapsulating Wavi Core startup and shutdown.
* Allows running startup and shutdown in a different thread from the UI thread.
*/
class BitcoinCore: public QObject
{
Q_OBJECT
public:
explicit BitcoinCore();
public Q_SLOTS:
void initialize();
void shutdown();
void restart(QStringList args);
Q_SIGNALS:
void initializeResult(int retval);
void shutdownResult(int retval);
void runawayException(const QString &message);
private:
boost::thread_group threadGroup;
CScheduler scheduler;
/// Flag indicating a restart
bool execute_restart;
/// Pass fatal exception message to UI thread
void handleRunawayException(const std::exception *e);
};
/** Main Wavi application object */
class BitcoinApplication: public QApplication
{
Q_OBJECT
public:
explicit BitcoinApplication(int &argc, char **argv);
~BitcoinApplication();
#ifdef ENABLE_WALLET
/// Create payment server
void createPaymentServer();
#endif
/// parameter interaction/setup based on rules
void parameterSetup();
/// Create options model
void createOptionsModel(bool resetSettings);
/// Create main window
void createWindow(const NetworkStyle *networkStyle);
/// Create splash screen
void createSplashScreen(const NetworkStyle *networkStyle);
/// Request core initialization
void requestInitialize();
/// Request core shutdown
void requestShutdown();
/// Get process return value
int getReturnValue() { return returnValue; }
/// Get window identifier of QMainWindow (BitcoinGUI)
WId getMainWinId() const;
public Q_SLOTS:
void initializeResult(int retval);
void shutdownResult(int retval);
/// Handle runaway exceptions. Shows a message box with the problem and quits the program.
void handleRunawayException(const QString &message);
Q_SIGNALS:
void requestedInitialize();
void requestedRestart(QStringList args);
void requestedShutdown();
void stopThread();
void splashFinished(QWidget *window);
private:
QThread *coreThread;
OptionsModel *optionsModel;
ClientModel *clientModel;
BitcoinGUI *window;
QTimer *pollShutdownTimer;
#ifdef ENABLE_WALLET
PaymentServer* paymentServer;
WalletModel *walletModel;
#endif
int returnValue;
const PlatformStyle *platformStyle;
std::unique_ptr<QWidget> shutdownWindow;
void startThread();
};
#include "wavi.moc"
BitcoinCore::BitcoinCore():
QObject()
{
}
void BitcoinCore::handleRunawayException(const std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
Q_EMIT runawayException(QString::fromStdString(strMiscWarning));
}
void BitcoinCore::initialize()
{
execute_restart = true;
try
{
qDebug() << __func__ << ": Running AppInit2 in thread";
int rv = AppInit2(threadGroup, scheduler);
Q_EMIT initializeResult(rv);
} catch (const std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
}
void BitcoinCore::restart(QStringList args)
{
if(execute_restart) { // Only restart 1x, no matter how often a user clicks on a restart-button
execute_restart = false;
try
{
qDebug() << __func__ << ": Running Restart in thread";
threadGroup.interrupt_all();
threadGroup.join_all();
PrepareShutdown();
qDebug() << __func__ << ": Shutdown finished";
Q_EMIT shutdownResult(1);
CExplicitNetCleanup::callCleanup();
QProcess::startDetached(QApplication::applicationFilePath(), args);
qDebug() << __func__ << ": Restart initiated...";
QApplication::quit();
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
}
}
void BitcoinCore::shutdown()
{
try
{
qDebug() << __func__ << ": Running Shutdown in thread";
Interrupt(threadGroup);
threadGroup.join_all();
Shutdown();
qDebug() << __func__ << ": Shutdown finished";
Q_EMIT shutdownResult(1);
} catch (const std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
}
BitcoinApplication::BitcoinApplication(int &argc, char **argv):
QApplication(argc, argv),
coreThread(0),
optionsModel(0),
clientModel(0),
window(0),
pollShutdownTimer(0),
#ifdef ENABLE_WALLET
paymentServer(0),
walletModel(0),
#endif
returnValue(0)
{
setQuitOnLastWindowClosed(false);
// UI per-platform customization
// This must be done inside the BitcoinApplication constructor, or after it, because
// PlatformStyle::instantiate requires a QApplication
std::string platformName;
platformName = GetArg("-uiplatform", BitcoinGUI::DEFAULT_UIPLATFORM);
platformStyle = PlatformStyle::instantiate(QString::fromStdString(platformName));
if (!platformStyle) // Fall back to "other" if specified name not found
platformStyle = PlatformStyle::instantiate("other");
assert(platformStyle);
}
BitcoinApplication::~BitcoinApplication()
{
if(coreThread)
{
qDebug() << __func__ << ": Stopping thread";
Q_EMIT stopThread();
coreThread->wait();
qDebug() << __func__ << ": Stopped thread";
}
delete window;
window = 0;
#ifdef ENABLE_WALLET
delete paymentServer;
paymentServer = 0;
#endif
// Delete Qt-settings if user clicked on "Reset Options"
QSettings settings;
if(optionsModel && optionsModel->resetSettings){
settings.clear();
settings.sync();
}
delete optionsModel;
optionsModel = 0;
delete platformStyle;
platformStyle = 0;
}
#ifdef ENABLE_WALLET
void BitcoinApplication::createPaymentServer()
{
paymentServer = new PaymentServer(this);
}
#endif
void BitcoinApplication::createOptionsModel(bool resetSettings)
{
optionsModel = new OptionsModel(NULL, resetSettings);
}
void BitcoinApplication::createWindow(const NetworkStyle *networkStyle)
{
window = new BitcoinGUI(platformStyle, networkStyle, 0);
pollShutdownTimer = new QTimer(window);
connect(pollShutdownTimer, SIGNAL(timeout()), window, SLOT(detectShutdown()));
pollShutdownTimer->start(200);
}
void BitcoinApplication::createSplashScreen(const NetworkStyle *networkStyle)
{
SplashScreen *splash = new SplashScreen(0, networkStyle);
// We don't hold a direct pointer to the splash screen after creation, but the splash
// screen will take care of deleting itself when slotFinish happens.
splash->show();
connect(this, SIGNAL(splashFinished(QWidget*)), splash, SLOT(slotFinish(QWidget*)));
connect(this, SIGNAL(requestedShutdown()), splash, SLOT(close()));
}
void BitcoinApplication::startThread()
{
if(coreThread)
return;
coreThread = new QThread(this);
BitcoinCore *executor = new BitcoinCore();
executor->moveToThread(coreThread);
/* communication to and from thread */
connect(executor, SIGNAL(initializeResult(int)), this, SLOT(initializeResult(int)));
connect(executor, SIGNAL(shutdownResult(int)), this, SLOT(shutdownResult(int)));
connect(executor, SIGNAL(runawayException(QString)), this, SLOT(handleRunawayException(QString)));
connect(this, SIGNAL(requestedInitialize()), executor, SLOT(initialize()));
connect(this, SIGNAL(requestedShutdown()), executor, SLOT(shutdown()));
connect(window, SIGNAL(requestedRestart(QStringList)), executor, SLOT(restart(QStringList)));
/* make sure executor object is deleted in its own thread */
connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopThread()), coreThread, SLOT(quit()));
coreThread->start();
}
void BitcoinApplication::parameterSetup()
{
InitLogging();
InitParameterInteraction();
}
void BitcoinApplication::requestInitialize()
{
qDebug() << __func__ << ": Requesting initialize";
startThread();
Q_EMIT requestedInitialize();
}
void BitcoinApplication::requestShutdown()
{
// Show a simple window indicating shutdown status
// Do this first as some of the steps may take some time below,
// for example the RPC console may still be executing a command.
shutdownWindow.reset(ShutdownWindow::showShutdownWindow(window));
qDebug() << __func__ << ": Requesting shutdown";
startThread();
window->hide();
window->setClientModel(0);
pollShutdownTimer->stop();
#ifdef ENABLE_WALLET
window->removeAllWallets();
delete walletModel;
walletModel = 0;
#endif
delete clientModel;
clientModel = 0;
// Request shutdown from core thread
Q_EMIT requestedShutdown();
}
void BitcoinApplication::initializeResult(int retval)
{
qDebug() << __func__ << ": Initialization result: " << retval;
// Set exit result: 0 if successful, 1 if failure
returnValue = retval ? 0 : 1;
if(retval)
{
// Log this only after AppInit2 finishes, as then logging setup is guaranteed complete
qWarning() << "Platform customization:" << platformStyle->getName();
#ifdef ENABLE_WALLET
PaymentServer::LoadRootCAs();
paymentServer->setOptionsModel(optionsModel);
#endif
clientModel = new ClientModel(optionsModel);
window->setClientModel(clientModel);
#ifdef ENABLE_WALLET
if(pwalletMain)
{
walletModel = new WalletModel(platformStyle, pwalletMain, optionsModel);
window->addWallet(BitcoinGUI::DEFAULT_WALLET, walletModel);
window->setCurrentWallet(BitcoinGUI::DEFAULT_WALLET);
connect(walletModel, SIGNAL(coinsSent(CWallet*,SendCoinsRecipient,QByteArray)),
paymentServer, SLOT(fetchPaymentACK(CWallet*,const SendCoinsRecipient&,QByteArray)));
}
#endif
// If -min option passed, start window minimized.
if(GetBoolArg("-min", false))
{
window->showMinimized();
}
else
{
window->show();
}
Q_EMIT splashFinished(window);
#ifdef ENABLE_WALLET
// Now that initialization/startup is done, process any command-line
// wavi: URIs or payment requests:
connect(paymentServer, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),
window, SLOT(handlePaymentRequest(SendCoinsRecipient)));
connect(window, SIGNAL(receivedURI(QString)),
paymentServer, SLOT(handleURIOrFile(QString)));
connect(paymentServer, SIGNAL(message(QString,QString,unsigned int)),
window, SLOT(message(QString,QString,unsigned int)));
QTimer::singleShot(100, paymentServer, SLOT(uiReady()));
#endif
} else {
quit(); // Exit main loop
}
}
void BitcoinApplication::shutdownResult(int retval)
{
qDebug() << __func__ << ": Shutdown result: " << retval;
quit(); // Exit main loop after shutdown finished
}
void BitcoinApplication::handleRunawayException(const QString &message)
{
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Wavi Core can no longer continue safely and will quit.") + QString("\n\n") + message);
::exit(EXIT_FAILURE);
}
WId BitcoinApplication::getMainWinId() const
{
if (!window)
return 0;
return window->winId();
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
SetupEnvironment();
/// 1. Parse command-line options. These take precedence over anything else.
// Command-line options take precedence:
ParseParameters(argc, argv);
// Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory
/// 2. Basic Qt initialization (not dependent on parameters or configuration)
#if QT_VERSION < 0x050000
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
#endif
Q_INIT_RESOURCE(wavi);
Q_INIT_RESOURCE(wavi_locale);
BitcoinApplication app(argc, argv);
#if QT_VERSION > 0x050100
// Generate high-dpi pixmaps
QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif
#ifdef Q_OS_MAC
QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
#endif
#if QT_VERSION >= 0x050500
// Because of the POODLE attack it is recommended to disable SSLv3 (https://disablessl3.com/),
// so set SSL protocols to TLS1.0+.
QSslConfiguration sslconf = QSslConfiguration::defaultConfiguration();
sslconf.setProtocol(QSsl::TlsV1_0OrLater);
QSslConfiguration::setDefaultConfiguration(sslconf);
#endif
// Register meta types used for QMetaObject::invokeMethod
qRegisterMetaType< bool* >();
// Need to pass name here as CAmount is a typedef (see http://qt-project.org/doc/qt-5/qmetatype.html#qRegisterMetaType)
// IMPORTANT if it is no longer a typedef use the normal variant above
qRegisterMetaType< CAmount >("CAmount");
qRegisterMetaType< std::function<void(void)> >("std::function<void(void)>");
/// 3. Application identification
// must be set before OptionsModel is initialized or translations are loaded,
// as it is used to locate QSettings
QApplication::setOrganizationName(QAPP_ORG_NAME);
QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN);
QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT);
GUIUtil::SubstituteFonts(GetLangTerritory());
/// 4. Initialization of translations, so that intro dialog is in user's language
// Now that QSettings are accessible, initialize translations
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator);
translationInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help") || mapArgs.count("-version"))
{
HelpMessageDialog help(NULL, mapArgs.count("-version") ? HelpMessageDialog::about : HelpMessageDialog::cmdline);
help.showOrPrint();
return EXIT_SUCCESS;
}
/// 5. Now that settings and translations are available, ask user for data directory
// User language is set up: pick a data directory
Intro::pickDataDirectory();
/// 6. Determine availability of data directory and parse wavi.conf
/// - Do not call GetDataDir(true) before this step finishes
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
QMessageBox::critical(0, QObject::tr("Wavi Core"),
QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return EXIT_FAILURE;
}
try {
ReadConfigFile(mapArgs, mapMultiArgs);
} catch (const std::exception& e) {
QMessageBox::critical(0, QObject::tr("Wavi Core"),
QObject::tr("Error: Cannot parse configuration file: %1. Only use key=value syntax.").arg(e.what()));
return EXIT_FAILURE;
}
/// 7. Determine network (and switch to network specific options)
// - Do not call Params() before this step
// - Do this after parsing the configuration file, as the network can be switched there
// - QSettings() will use the new application name after this, resulting in network-specific settings
// - Needs to be done before createOptionsModel
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
try {
SelectParams(ChainNameFromCommandLine());
} catch(std::exception &e) {
QMessageBox::critical(0, QObject::tr("Wavi Core"), QObject::tr("Error: %1").arg(e.what()));
return EXIT_FAILURE;
}
#ifdef ENABLE_WALLET
// Parse URIs on command line -- this can affect Params()
PaymentServer::ipcParseCommandLine(argc, argv);
#endif
QScopedPointer<const NetworkStyle> networkStyle(NetworkStyle::instantiate(QString::fromStdString(Params().NetworkIDString())));
assert(!networkStyle.isNull());
// Allow for separate UI settings for testnets
// QApplication::setApplicationName(networkStyle->getAppName()); // moved to NetworkStyle::NetworkStyle
// Re-initialize translations after changing application name (language in network-specific settings can be different)
initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator);
#ifdef ENABLE_WALLET
/// 7a. parse masternode.conf
std::string strErr;
if(!masternodeConfig.read(strErr)) {
QMessageBox::critical(0, QObject::tr("Wavi Core"),
QObject::tr("Error reading masternode configuration file: %1").arg(strErr.c_str()));
return EXIT_FAILURE;
}
/// 8. URI IPC sending
// - Do this early as we don't want to bother initializing if we are just calling IPC
// - Do this *after* setting up the data directory, as the data directory hash is used in the name
// of the server.
// - Do this after creating app and setting up translations, so errors are
// translated properly.
if (PaymentServer::ipcSendCommandLine())
exit(EXIT_SUCCESS);
// Start up the payment server early, too, so impatient users that click on
// wavi: links repeatedly have their payment requests routed to this process:
app.createPaymentServer();
#endif
/// 9. Main GUI initialization
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
#if QT_VERSION < 0x050000
// Install qDebug() message handler to route to debug.log
qInstallMsgHandler(DebugMessageHandler);
#else
#if defined(Q_OS_WIN)
// Install global event filter for processing Windows session related Windows messages (WM_QUERYENDSESSION and WM_ENDSESSION)
qApp->installNativeEventFilter(new WinShutdownMonitor());
#endif
// Install qDebug() message handler to route to debug.log
qInstallMessageHandler(DebugMessageHandler);
#endif
// Allow parameter interaction before we create the options model
app.parameterSetup();
// Load GUI settings from QSettings
app.createOptionsModel(mapArgs.count("-resetguisettings") != 0);
// Subscribe to global signals from core
uiInterface.InitMessage.connect(InitMessage);
if (GetBoolArg("-splash", DEFAULT_SPLASHSCREEN) && !GetBoolArg("-min", false))
app.createSplashScreen(networkStyle.data());
try
{
app.createWindow(networkStyle.data());
app.requestInitialize();
#if defined(Q_OS_WIN) && QT_VERSION >= 0x050000
WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("Wavi Core didn't yet exit safely..."), (HWND)app.getMainWinId());
#endif
app.exec();
app.requestShutdown();
app.exec();
} catch (const std::exception& e) {
PrintExceptionContinue(&e, "Runaway exception");
app.handleRunawayException(QString::fromStdString(strMiscWarning));
} catch (...) {
PrintExceptionContinue(NULL, "Runaway exception");
app.handleRunawayException(QString::fromStdString(strMiscWarning));
}
return app.getReturnValue();
}
#endif // BITCOIN_QT_TEST
|
/* Generated by Cython 0.29.21 */
/* BEGIN: Cython Metadata
{
"distutils": {
"depends": [
"/n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h",
"/n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/core/include/numpy/ufuncobject.h"
],
"extra_compile_args": {
"cxx": [
"-Wno-unused-function",
"-Wno-write-strings"
]
},
"include_dirs": [
"/n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/core/include"
],
"language": "c++",
"name": "mmdet.ops.nms.soft_nms_cpu",
"sources": [
"mmdet/ops/nms/src/soft_nms_cpu.pyx"
]
},
"module_name": "mmdet.ops.nms.soft_nms_cpu"
}
END: Cython Metadata */
#define PY_SSIZE_T_CLEAN
#include "Python.h"
#ifndef Py_PYTHON_H
#error Python headers needed to compile C extensions, please install development version of Python.
#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000)
#error Cython requires Python 2.6+ or Python 3.3+.
#else
#define CYTHON_ABI "0_29_21"
#define CYTHON_HEX_VERSION 0x001D15F0
#define CYTHON_FUTURE_DIVISION 1
#include <stddef.h>
#ifndef offsetof
#define offsetof(type, member) ( (size_t) & ((type*)0) -> member )
#endif
#if !defined(WIN32) && !defined(MS_WINDOWS)
#ifndef __stdcall
#define __stdcall
#endif
#ifndef __cdecl
#define __cdecl
#endif
#ifndef __fastcall
#define __fastcall
#endif
#endif
#ifndef DL_IMPORT
#define DL_IMPORT(t) t
#endif
#ifndef DL_EXPORT
#define DL_EXPORT(t) t
#endif
#define __PYX_COMMA ,
#ifndef HAVE_LONG_LONG
#if PY_VERSION_HEX >= 0x02070000
#define HAVE_LONG_LONG
#endif
#endif
#ifndef PY_LONG_LONG
#define PY_LONG_LONG LONG_LONG
#endif
#ifndef Py_HUGE_VAL
#define Py_HUGE_VAL HUGE_VAL
#endif
#ifdef PYPY_VERSION
#define CYTHON_COMPILING_IN_PYPY 1
#define CYTHON_COMPILING_IN_PYSTON 0
#define CYTHON_COMPILING_IN_CPYTHON 0
#undef CYTHON_USE_TYPE_SLOTS
#define CYTHON_USE_TYPE_SLOTS 0
#undef CYTHON_USE_PYTYPE_LOOKUP
#define CYTHON_USE_PYTYPE_LOOKUP 0
#if PY_VERSION_HEX < 0x03050000
#undef CYTHON_USE_ASYNC_SLOTS
#define CYTHON_USE_ASYNC_SLOTS 0
#elif !defined(CYTHON_USE_ASYNC_SLOTS)
#define CYTHON_USE_ASYNC_SLOTS 1
#endif
#undef CYTHON_USE_PYLIST_INTERNALS
#define CYTHON_USE_PYLIST_INTERNALS 0
#undef CYTHON_USE_UNICODE_INTERNALS
#define CYTHON_USE_UNICODE_INTERNALS 0
#undef CYTHON_USE_UNICODE_WRITER
#define CYTHON_USE_UNICODE_WRITER 0
#undef CYTHON_USE_PYLONG_INTERNALS
#define CYTHON_USE_PYLONG_INTERNALS 0
#undef CYTHON_AVOID_BORROWED_REFS
#define CYTHON_AVOID_BORROWED_REFS 1
#undef CYTHON_ASSUME_SAFE_MACROS
#define CYTHON_ASSUME_SAFE_MACROS 0
#undef CYTHON_UNPACK_METHODS
#define CYTHON_UNPACK_METHODS 0
#undef CYTHON_FAST_THREAD_STATE
#define CYTHON_FAST_THREAD_STATE 0
#undef CYTHON_FAST_PYCALL
#define CYTHON_FAST_PYCALL 0
#undef CYTHON_PEP489_MULTI_PHASE_INIT
#define CYTHON_PEP489_MULTI_PHASE_INIT 0
#undef CYTHON_USE_TP_FINALIZE
#define CYTHON_USE_TP_FINALIZE 0
#undef CYTHON_USE_DICT_VERSIONS
#define CYTHON_USE_DICT_VERSIONS 0
#undef CYTHON_USE_EXC_INFO_STACK
#define CYTHON_USE_EXC_INFO_STACK 0
#elif defined(PYSTON_VERSION)
#define CYTHON_COMPILING_IN_PYPY 0
#define CYTHON_COMPILING_IN_PYSTON 1
#define CYTHON_COMPILING_IN_CPYTHON 0
#ifndef CYTHON_USE_TYPE_SLOTS
#define CYTHON_USE_TYPE_SLOTS 1
#endif
#undef CYTHON_USE_PYTYPE_LOOKUP
#define CYTHON_USE_PYTYPE_LOOKUP 0
#undef CYTHON_USE_ASYNC_SLOTS
#define CYTHON_USE_ASYNC_SLOTS 0
#undef CYTHON_USE_PYLIST_INTERNALS
#define CYTHON_USE_PYLIST_INTERNALS 0
#ifndef CYTHON_USE_UNICODE_INTERNALS
#define CYTHON_USE_UNICODE_INTERNALS 1
#endif
#undef CYTHON_USE_UNICODE_WRITER
#define CYTHON_USE_UNICODE_WRITER 0
#undef CYTHON_USE_PYLONG_INTERNALS
#define CYTHON_USE_PYLONG_INTERNALS 0
#ifndef CYTHON_AVOID_BORROWED_REFS
#define CYTHON_AVOID_BORROWED_REFS 0
#endif
#ifndef CYTHON_ASSUME_SAFE_MACROS
#define CYTHON_ASSUME_SAFE_MACROS 1
#endif
#ifndef CYTHON_UNPACK_METHODS
#define CYTHON_UNPACK_METHODS 1
#endif
#undef CYTHON_FAST_THREAD_STATE
#define CYTHON_FAST_THREAD_STATE 0
#undef CYTHON_FAST_PYCALL
#define CYTHON_FAST_PYCALL 0
#undef CYTHON_PEP489_MULTI_PHASE_INIT
#define CYTHON_PEP489_MULTI_PHASE_INIT 0
#undef CYTHON_USE_TP_FINALIZE
#define CYTHON_USE_TP_FINALIZE 0
#undef CYTHON_USE_DICT_VERSIONS
#define CYTHON_USE_DICT_VERSIONS 0
#undef CYTHON_USE_EXC_INFO_STACK
#define CYTHON_USE_EXC_INFO_STACK 0
#else
#define CYTHON_COMPILING_IN_PYPY 0
#define CYTHON_COMPILING_IN_PYSTON 0
#define CYTHON_COMPILING_IN_CPYTHON 1
#ifndef CYTHON_USE_TYPE_SLOTS
#define CYTHON_USE_TYPE_SLOTS 1
#endif
#if PY_VERSION_HEX < 0x02070000
#undef CYTHON_USE_PYTYPE_LOOKUP
#define CYTHON_USE_PYTYPE_LOOKUP 0
#elif !defined(CYTHON_USE_PYTYPE_LOOKUP)
#define CYTHON_USE_PYTYPE_LOOKUP 1
#endif
#if PY_MAJOR_VERSION < 3
#undef CYTHON_USE_ASYNC_SLOTS
#define CYTHON_USE_ASYNC_SLOTS 0
#elif !defined(CYTHON_USE_ASYNC_SLOTS)
#define CYTHON_USE_ASYNC_SLOTS 1
#endif
#if PY_VERSION_HEX < 0x02070000
#undef CYTHON_USE_PYLONG_INTERNALS
#define CYTHON_USE_PYLONG_INTERNALS 0
#elif !defined(CYTHON_USE_PYLONG_INTERNALS)
#define CYTHON_USE_PYLONG_INTERNALS 1
#endif
#ifndef CYTHON_USE_PYLIST_INTERNALS
#define CYTHON_USE_PYLIST_INTERNALS 1
#endif
#ifndef CYTHON_USE_UNICODE_INTERNALS
#define CYTHON_USE_UNICODE_INTERNALS 1
#endif
#if PY_VERSION_HEX < 0x030300F0
#undef CYTHON_USE_UNICODE_WRITER
#define CYTHON_USE_UNICODE_WRITER 0
#elif !defined(CYTHON_USE_UNICODE_WRITER)
#define CYTHON_USE_UNICODE_WRITER 1
#endif
#ifndef CYTHON_AVOID_BORROWED_REFS
#define CYTHON_AVOID_BORROWED_REFS 0
#endif
#ifndef CYTHON_ASSUME_SAFE_MACROS
#define CYTHON_ASSUME_SAFE_MACROS 1
#endif
#ifndef CYTHON_UNPACK_METHODS
#define CYTHON_UNPACK_METHODS 1
#endif
#ifndef CYTHON_FAST_THREAD_STATE
#define CYTHON_FAST_THREAD_STATE 1
#endif
#ifndef CYTHON_FAST_PYCALL
#define CYTHON_FAST_PYCALL 1
#endif
#ifndef CYTHON_PEP489_MULTI_PHASE_INIT
#define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000)
#endif
#ifndef CYTHON_USE_TP_FINALIZE
#define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1)
#endif
#ifndef CYTHON_USE_DICT_VERSIONS
#define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX >= 0x030600B1)
#endif
#ifndef CYTHON_USE_EXC_INFO_STACK
#define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3)
#endif
#endif
#if !defined(CYTHON_FAST_PYCCALL)
#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1)
#endif
#if CYTHON_USE_PYLONG_INTERNALS
#include "longintrepr.h"
#undef SHIFT
#undef BASE
#undef MASK
#ifdef SIZEOF_VOID_P
enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) };
#endif
#endif
#ifndef __has_attribute
#define __has_attribute(x) 0
#endif
#ifndef __has_cpp_attribute
#define __has_cpp_attribute(x) 0
#endif
#ifndef CYTHON_RESTRICT
#if defined(__GNUC__)
#define CYTHON_RESTRICT __restrict__
#elif defined(_MSC_VER) && _MSC_VER >= 1400
#define CYTHON_RESTRICT __restrict
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define CYTHON_RESTRICT restrict
#else
#define CYTHON_RESTRICT
#endif
#endif
#ifndef CYTHON_UNUSED
# if defined(__GNUC__)
# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
# define CYTHON_UNUSED __attribute__ ((__unused__))
# else
# define CYTHON_UNUSED
# endif
# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER))
# define CYTHON_UNUSED __attribute__ ((__unused__))
# else
# define CYTHON_UNUSED
# endif
#endif
#ifndef CYTHON_MAYBE_UNUSED_VAR
# if defined(__cplusplus)
template<class T> void CYTHON_MAYBE_UNUSED_VAR( const T& ) { }
# else
# define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x)
# endif
#endif
#ifndef CYTHON_NCP_UNUSED
# if CYTHON_COMPILING_IN_CPYTHON
# define CYTHON_NCP_UNUSED
# else
# define CYTHON_NCP_UNUSED CYTHON_UNUSED
# endif
#endif
#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None)
#ifdef _MSC_VER
#ifndef _MSC_STDINT_H_
#if _MSC_VER < 1300
typedef unsigned char uint8_t;
typedef unsigned int uint32_t;
#else
typedef unsigned __int8 uint8_t;
typedef unsigned __int32 uint32_t;
#endif
#endif
#else
#include <stdint.h>
#endif
#ifndef CYTHON_FALLTHROUGH
#if defined(__cplusplus) && __cplusplus >= 201103L
#if __has_cpp_attribute(fallthrough)
#define CYTHON_FALLTHROUGH [[fallthrough]]
#elif __has_cpp_attribute(clang::fallthrough)
#define CYTHON_FALLTHROUGH [[clang::fallthrough]]
#elif __has_cpp_attribute(gnu::fallthrough)
#define CYTHON_FALLTHROUGH [[gnu::fallthrough]]
#endif
#endif
#ifndef CYTHON_FALLTHROUGH
#if __has_attribute(fallthrough)
#define CYTHON_FALLTHROUGH __attribute__((fallthrough))
#else
#define CYTHON_FALLTHROUGH
#endif
#endif
#if defined(__clang__ ) && defined(__apple_build_version__)
#if __apple_build_version__ < 7000000
#undef CYTHON_FALLTHROUGH
#define CYTHON_FALLTHROUGH
#endif
#endif
#endif
#ifndef __cplusplus
#error "Cython files generated with the C++ option must be compiled with a C++ compiler."
#endif
#ifndef CYTHON_INLINE
#if defined(__clang__)
#define CYTHON_INLINE __inline__ __attribute__ ((__unused__))
#else
#define CYTHON_INLINE inline
#endif
#endif
template<typename T>
void __Pyx_call_destructor(T& x) {
x.~T();
}
template<typename T>
class __Pyx_FakeReference {
public:
__Pyx_FakeReference() : ptr(NULL) { }
__Pyx_FakeReference(const T& ref) : ptr(const_cast<T*>(&ref)) { }
T *operator->() { return ptr; }
T *operator&() { return ptr; }
operator T&() { return *ptr; }
template<typename U> bool operator ==(U other) { return *ptr == other; }
template<typename U> bool operator !=(U other) { return *ptr != other; }
private:
T *ptr;
};
#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag)
#define Py_OptimizeFlag 0
#endif
#define __PYX_BUILD_PY_SSIZE_T "n"
#define CYTHON_FORMAT_SSIZE_T "z"
#if PY_MAJOR_VERSION < 3
#define __Pyx_BUILTIN_MODULE_NAME "__builtin__"
#define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
#define __Pyx_DefaultClassType PyClass_Type
#else
#define __Pyx_BUILTIN_MODULE_NAME "builtins"
#if PY_VERSION_HEX >= 0x030800A4 && PY_VERSION_HEX < 0x030800B2
#define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
#else
#define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
#endif
#define __Pyx_DefaultClassType PyType_Type
#endif
#ifndef Py_TPFLAGS_CHECKTYPES
#define Py_TPFLAGS_CHECKTYPES 0
#endif
#ifndef Py_TPFLAGS_HAVE_INDEX
#define Py_TPFLAGS_HAVE_INDEX 0
#endif
#ifndef Py_TPFLAGS_HAVE_NEWBUFFER
#define Py_TPFLAGS_HAVE_NEWBUFFER 0
#endif
#ifndef Py_TPFLAGS_HAVE_FINALIZE
#define Py_TPFLAGS_HAVE_FINALIZE 0
#endif
#ifndef METH_STACKLESS
#define METH_STACKLESS 0
#endif
#if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL)
#ifndef METH_FASTCALL
#define METH_FASTCALL 0x80
#endif
typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs);
typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args,
Py_ssize_t nargs, PyObject *kwnames);
#else
#define __Pyx_PyCFunctionFast _PyCFunctionFast
#define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords
#endif
#if CYTHON_FAST_PYCCALL
#define __Pyx_PyFastCFunction_Check(func)\
((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS)))))
#else
#define __Pyx_PyFastCFunction_Check(func) 0
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc)
#define PyObject_Malloc(s) PyMem_Malloc(s)
#define PyObject_Free(p) PyMem_Free(p)
#define PyObject_Realloc(p) PyMem_Realloc(p)
#endif
#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1
#define PyMem_RawMalloc(n) PyMem_Malloc(n)
#define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n)
#define PyMem_RawFree(p) PyMem_Free(p)
#endif
#if CYTHON_COMPILING_IN_PYSTON
#define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co)
#define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno)
#else
#define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0)
#define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno)
#endif
#if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000
#define __Pyx_PyThreadState_Current PyThreadState_GET()
#elif PY_VERSION_HEX >= 0x03060000
#define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet()
#elif PY_VERSION_HEX >= 0x03000000
#define __Pyx_PyThreadState_Current PyThreadState_GET()
#else
#define __Pyx_PyThreadState_Current _PyThreadState_Current
#endif
#if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT)
#include "pythread.h"
#define Py_tss_NEEDS_INIT 0
typedef int Py_tss_t;
static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) {
*key = PyThread_create_key();
return 0;
}
static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) {
Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t));
*key = Py_tss_NEEDS_INIT;
return key;
}
static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) {
PyObject_Free(key);
}
static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) {
return *key != Py_tss_NEEDS_INIT;
}
static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) {
PyThread_delete_key(*key);
*key = Py_tss_NEEDS_INIT;
}
static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) {
return PyThread_set_key_value(*key, value);
}
static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) {
return PyThread_get_key_value(*key);
}
#endif
#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized)
#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n))
#else
#define __Pyx_PyDict_NewPresized(n) PyDict_New()
#endif
#if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION
#define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y)
#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y)
#else
#define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y)
#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y)
#endif
#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS
#define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash)
#else
#define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name)
#endif
#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND)
#define CYTHON_PEP393_ENABLED 1
#define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\
0 : _PyUnicode_Ready((PyObject *)(op)))
#define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u)
#define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i)
#define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u)
#define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u)
#define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u)
#define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i)
#define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch)
#if defined(PyUnicode_IS_READY) && defined(PyUnicode_GET_SIZE)
#define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u)))
#else
#define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u))
#endif
#else
#define CYTHON_PEP393_ENABLED 0
#define PyUnicode_1BYTE_KIND 1
#define PyUnicode_2BYTE_KIND 2
#define PyUnicode_4BYTE_KIND 4
#define __Pyx_PyUnicode_READY(op) (0)
#define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u)
#define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i]))
#define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111)
#define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE))
#define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u))
#define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i]))
#define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch)
#define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u))
#endif
#if CYTHON_COMPILING_IN_PYPY
#define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b)
#define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b)
#else
#define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b)
#define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\
PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b))
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains)
#define PyUnicode_Contains(u, s) PySequence_Contains(u, s)
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check)
#define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type)
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format)
#define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt)
#endif
#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b))
#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b))
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b)
#else
#define __Pyx_PyString_Format(a, b) PyString_Format(a, b)
#endif
#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII)
#define PyObject_ASCII(o) PyObject_Repr(o)
#endif
#if PY_MAJOR_VERSION >= 3
#define PyBaseString_Type PyUnicode_Type
#define PyStringObject PyUnicodeObject
#define PyString_Type PyUnicode_Type
#define PyString_Check PyUnicode_Check
#define PyString_CheckExact PyUnicode_CheckExact
#ifndef PyObject_Unicode
#define PyObject_Unicode PyObject_Str
#endif
#endif
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj)
#define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj)
#else
#define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj))
#define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj))
#endif
#ifndef PySet_CheckExact
#define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type)
#endif
#if PY_VERSION_HEX >= 0x030900A4
#define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt)
#define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size)
#else
#define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt)
#define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size)
#endif
#if CYTHON_ASSUME_SAFE_MACROS
#define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq)
#else
#define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq)
#endif
#if PY_MAJOR_VERSION >= 3
#define PyIntObject PyLongObject
#define PyInt_Type PyLong_Type
#define PyInt_Check(op) PyLong_Check(op)
#define PyInt_CheckExact(op) PyLong_CheckExact(op)
#define PyInt_FromString PyLong_FromString
#define PyInt_FromUnicode PyLong_FromUnicode
#define PyInt_FromLong PyLong_FromLong
#define PyInt_FromSize_t PyLong_FromSize_t
#define PyInt_FromSsize_t PyLong_FromSsize_t
#define PyInt_AsLong PyLong_AsLong
#define PyInt_AS_LONG PyLong_AS_LONG
#define PyInt_AsSsize_t PyLong_AsSsize_t
#define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask
#define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask
#define PyNumber_Int PyNumber_Long
#endif
#if PY_MAJOR_VERSION >= 3
#define PyBoolObject PyLongObject
#endif
#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY
#ifndef PyUnicode_InternFromString
#define PyUnicode_InternFromString(s) PyUnicode_FromString(s)
#endif
#endif
#if PY_VERSION_HEX < 0x030200A4
typedef long Py_hash_t;
#define __Pyx_PyInt_FromHash_t PyInt_FromLong
#define __Pyx_PyInt_AsHash_t PyInt_AsLong
#else
#define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t
#define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t
#endif
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyMethod_New(func, self, klass) ((self) ? ((void)(klass), PyMethod_New(func, self)) : __Pyx_NewRef(func))
#else
#define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass)
#endif
#if CYTHON_USE_ASYNC_SLOTS
#if PY_VERSION_HEX >= 0x030500B1
#define __Pyx_PyAsyncMethodsStruct PyAsyncMethods
#define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async)
#else
#define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved))
#endif
#else
#define __Pyx_PyType_AsAsync(obj) NULL
#endif
#ifndef __Pyx_PyAsyncMethodsStruct
typedef struct {
unaryfunc am_await;
unaryfunc am_aiter;
unaryfunc am_anext;
} __Pyx_PyAsyncMethodsStruct;
#endif
#if defined(WIN32) || defined(MS_WINDOWS)
#define _USE_MATH_DEFINES
#endif
#include <math.h>
#ifdef NAN
#define __PYX_NAN() ((float) NAN)
#else
static CYTHON_INLINE float __PYX_NAN() {
float value;
memset(&value, 0xFF, sizeof(value));
return value;
}
#endif
#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL)
#define __Pyx_truncl trunc
#else
#define __Pyx_truncl truncl
#endif
#define __PYX_MARK_ERR_POS(f_index, lineno) \
{ __pyx_filename = __pyx_f[f_index]; (void)__pyx_filename; __pyx_lineno = lineno; (void)__pyx_lineno; __pyx_clineno = __LINE__; (void)__pyx_clineno; }
#define __PYX_ERR(f_index, lineno, Ln_error) \
{ __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; }
#ifndef __PYX_EXTERN_C
#ifdef __cplusplus
#define __PYX_EXTERN_C extern "C"
#else
#define __PYX_EXTERN_C extern
#endif
#endif
#define __PYX_HAVE__mmdet__ops__nms__soft_nms_cpu
#define __PYX_HAVE_API__mmdet__ops__nms__soft_nms_cpu
/* Early includes */
#include <string.h>
#include <stdio.h>
#include "numpy/arrayobject.h"
#include "numpy/ufuncobject.h"
/* NumPy API declarations from "numpy/__init__.pxd" */
#ifdef _OPENMP
#include <omp.h>
#endif /* _OPENMP */
#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS)
#define CYTHON_WITHOUT_ASSERTIONS
#endif
typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding;
const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry;
#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0
#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0
#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8)
#define __PYX_DEFAULT_STRING_ENCODING ""
#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString
#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize
#define __Pyx_uchar_cast(c) ((unsigned char)c)
#define __Pyx_long_cast(x) ((long)x)
#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\
(sizeof(type) < sizeof(Py_ssize_t)) ||\
(sizeof(type) > sizeof(Py_ssize_t) &&\
likely(v < (type)PY_SSIZE_T_MAX ||\
v == (type)PY_SSIZE_T_MAX) &&\
(!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\
v == (type)PY_SSIZE_T_MIN))) ||\
(sizeof(type) == sizeof(Py_ssize_t) &&\
(is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\
v == (type)PY_SSIZE_T_MAX))) )
static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) {
return (size_t) i < (size_t) limit;
}
#if defined (__cplusplus) && __cplusplus >= 201103L
#include <cstdlib>
#define __Pyx_sst_abs(value) std::abs(value)
#elif SIZEOF_INT >= SIZEOF_SIZE_T
#define __Pyx_sst_abs(value) abs(value)
#elif SIZEOF_LONG >= SIZEOF_SIZE_T
#define __Pyx_sst_abs(value) labs(value)
#elif defined (_MSC_VER)
#define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value))
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define __Pyx_sst_abs(value) llabs(value)
#elif defined (__GNUC__)
#define __Pyx_sst_abs(value) __builtin_llabs(value)
#else
#define __Pyx_sst_abs(value) ((value<0) ? -value : value)
#endif
static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*);
static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length);
#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s))
#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l)
#define __Pyx_PyBytes_FromString PyBytes_FromString
#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize
static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*);
#if PY_MAJOR_VERSION < 3
#define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString
#define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize
#else
#define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString
#define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize
#endif
#define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s))
#define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s))
#define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s))
#define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s))
#define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s))
#define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s))
#define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s)
#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s)
#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s)
#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s)
#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s)
static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) {
const Py_UNICODE *u_end = u;
while (*u_end++) ;
return (size_t)(u_end - u - 1);
}
#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u))
#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode
#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode
#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj)
#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None)
static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b);
static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*);
static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*);
static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x);
#define __Pyx_PySequence_Tuple(obj)\
(likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj))
static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*);
static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t);
#if CYTHON_ASSUME_SAFE_MACROS
#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x))
#else
#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x)
#endif
#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x))
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x))
#else
#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x))
#endif
#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x))
#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
static int __Pyx_sys_getdefaultencoding_not_ascii;
static int __Pyx_init_sys_getdefaultencoding_params(void) {
PyObject* sys;
PyObject* default_encoding = NULL;
PyObject* ascii_chars_u = NULL;
PyObject* ascii_chars_b = NULL;
const char* default_encoding_c;
sys = PyImport_ImportModule("sys");
if (!sys) goto bad;
default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL);
Py_DECREF(sys);
if (!default_encoding) goto bad;
default_encoding_c = PyBytes_AsString(default_encoding);
if (!default_encoding_c) goto bad;
if (strcmp(default_encoding_c, "ascii") == 0) {
__Pyx_sys_getdefaultencoding_not_ascii = 0;
} else {
char ascii_chars[128];
int c;
for (c = 0; c < 128; c++) {
ascii_chars[c] = c;
}
__Pyx_sys_getdefaultencoding_not_ascii = 1;
ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL);
if (!ascii_chars_u) goto bad;
ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL);
if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) {
PyErr_Format(
PyExc_ValueError,
"This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.",
default_encoding_c);
goto bad;
}
Py_DECREF(ascii_chars_u);
Py_DECREF(ascii_chars_b);
}
Py_DECREF(default_encoding);
return 0;
bad:
Py_XDECREF(default_encoding);
Py_XDECREF(ascii_chars_u);
Py_XDECREF(ascii_chars_b);
return -1;
}
#endif
#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3
#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL)
#else
#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL)
#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT
static char* __PYX_DEFAULT_STRING_ENCODING;
static int __Pyx_init_sys_getdefaultencoding_params(void) {
PyObject* sys;
PyObject* default_encoding = NULL;
char* default_encoding_c;
sys = PyImport_ImportModule("sys");
if (!sys) goto bad;
default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL);
Py_DECREF(sys);
if (!default_encoding) goto bad;
default_encoding_c = PyBytes_AsString(default_encoding);
if (!default_encoding_c) goto bad;
__PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1);
if (!__PYX_DEFAULT_STRING_ENCODING) goto bad;
strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c);
Py_DECREF(default_encoding);
return 0;
bad:
Py_XDECREF(default_encoding);
return -1;
}
#endif
#endif
/* Test for GCC > 2.95 */
#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)))
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#else /* !__GNUC__ or GCC < 2.95 */
#define likely(x) (x)
#define unlikely(x) (x)
#endif /* __GNUC__ */
static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; }
static PyObject *__pyx_m = NULL;
static PyObject *__pyx_d;
static PyObject *__pyx_b;
static PyObject *__pyx_cython_runtime = NULL;
static PyObject *__pyx_empty_tuple;
static PyObject *__pyx_empty_bytes;
static PyObject *__pyx_empty_unicode;
static int __pyx_lineno;
static int __pyx_clineno = 0;
static const char * __pyx_cfilenm= __FILE__;
static const char *__pyx_filename;
/* Header.proto */
#if !defined(CYTHON_CCOMPLEX)
#if defined(__cplusplus)
#define CYTHON_CCOMPLEX 1
#elif defined(_Complex_I)
#define CYTHON_CCOMPLEX 1
#else
#define CYTHON_CCOMPLEX 0
#endif
#endif
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
#include <complex>
#else
#include <complex.h>
#endif
#endif
#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__)
#undef _Complex_I
#define _Complex_I 1.0fj
#endif
static const char *__pyx_f[] = {
"mmdet/ops/nms/src/soft_nms_cpu.pyx",
"__init__.pxd",
"type.pxd",
};
/* BufferFormatStructs.proto */
#define IS_UNSIGNED(type) (((type) -1) > 0)
struct __Pyx_StructField_;
#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0)
typedef struct {
const char* name;
struct __Pyx_StructField_* fields;
size_t size;
size_t arraysize[8];
int ndim;
char typegroup;
char is_unsigned;
int flags;
} __Pyx_TypeInfo;
typedef struct __Pyx_StructField_ {
__Pyx_TypeInfo* type;
const char* name;
size_t offset;
} __Pyx_StructField;
typedef struct {
__Pyx_StructField* field;
size_t parent_offset;
} __Pyx_BufFmt_StackElem;
typedef struct {
__Pyx_StructField root;
__Pyx_BufFmt_StackElem* head;
size_t fmt_offset;
size_t new_count, enc_count;
size_t struct_alignment;
int is_complex;
char enc_type;
char new_packmode;
char enc_packmode;
char is_valid_array;
} __Pyx_BufFmt_Context;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":689
* # in Cython to enable them only on the right systems.
*
* ctypedef npy_int8 int8_t # <<<<<<<<<<<<<<
* ctypedef npy_int16 int16_t
* ctypedef npy_int32 int32_t
*/
typedef npy_int8 __pyx_t_5numpy_int8_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":690
*
* ctypedef npy_int8 int8_t
* ctypedef npy_int16 int16_t # <<<<<<<<<<<<<<
* ctypedef npy_int32 int32_t
* ctypedef npy_int64 int64_t
*/
typedef npy_int16 __pyx_t_5numpy_int16_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":691
* ctypedef npy_int8 int8_t
* ctypedef npy_int16 int16_t
* ctypedef npy_int32 int32_t # <<<<<<<<<<<<<<
* ctypedef npy_int64 int64_t
* #ctypedef npy_int96 int96_t
*/
typedef npy_int32 __pyx_t_5numpy_int32_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":692
* ctypedef npy_int16 int16_t
* ctypedef npy_int32 int32_t
* ctypedef npy_int64 int64_t # <<<<<<<<<<<<<<
* #ctypedef npy_int96 int96_t
* #ctypedef npy_int128 int128_t
*/
typedef npy_int64 __pyx_t_5numpy_int64_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":696
* #ctypedef npy_int128 int128_t
*
* ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<<
* ctypedef npy_uint16 uint16_t
* ctypedef npy_uint32 uint32_t
*/
typedef npy_uint8 __pyx_t_5numpy_uint8_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":697
*
* ctypedef npy_uint8 uint8_t
* ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<<
* ctypedef npy_uint32 uint32_t
* ctypedef npy_uint64 uint64_t
*/
typedef npy_uint16 __pyx_t_5numpy_uint16_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":698
* ctypedef npy_uint8 uint8_t
* ctypedef npy_uint16 uint16_t
* ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<<
* ctypedef npy_uint64 uint64_t
* #ctypedef npy_uint96 uint96_t
*/
typedef npy_uint32 __pyx_t_5numpy_uint32_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":699
* ctypedef npy_uint16 uint16_t
* ctypedef npy_uint32 uint32_t
* ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<<
* #ctypedef npy_uint96 uint96_t
* #ctypedef npy_uint128 uint128_t
*/
typedef npy_uint64 __pyx_t_5numpy_uint64_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":703
* #ctypedef npy_uint128 uint128_t
*
* ctypedef npy_float32 float32_t # <<<<<<<<<<<<<<
* ctypedef npy_float64 float64_t
* #ctypedef npy_float80 float80_t
*/
typedef npy_float32 __pyx_t_5numpy_float32_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":704
*
* ctypedef npy_float32 float32_t
* ctypedef npy_float64 float64_t # <<<<<<<<<<<<<<
* #ctypedef npy_float80 float80_t
* #ctypedef npy_float128 float128_t
*/
typedef npy_float64 __pyx_t_5numpy_float64_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":713
* # The int types are mapped a bit surprising --
* # numpy.int corresponds to 'l' and numpy.long to 'q'
* ctypedef npy_long int_t # <<<<<<<<<<<<<<
* ctypedef npy_longlong long_t
* ctypedef npy_longlong longlong_t
*/
typedef npy_long __pyx_t_5numpy_int_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":714
* # numpy.int corresponds to 'l' and numpy.long to 'q'
* ctypedef npy_long int_t
* ctypedef npy_longlong long_t # <<<<<<<<<<<<<<
* ctypedef npy_longlong longlong_t
*
*/
typedef npy_longlong __pyx_t_5numpy_long_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":715
* ctypedef npy_long int_t
* ctypedef npy_longlong long_t
* ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<<
*
* ctypedef npy_ulong uint_t
*/
typedef npy_longlong __pyx_t_5numpy_longlong_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":717
* ctypedef npy_longlong longlong_t
*
* ctypedef npy_ulong uint_t # <<<<<<<<<<<<<<
* ctypedef npy_ulonglong ulong_t
* ctypedef npy_ulonglong ulonglong_t
*/
typedef npy_ulong __pyx_t_5numpy_uint_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":718
*
* ctypedef npy_ulong uint_t
* ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<<
* ctypedef npy_ulonglong ulonglong_t
*
*/
typedef npy_ulonglong __pyx_t_5numpy_ulong_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":719
* ctypedef npy_ulong uint_t
* ctypedef npy_ulonglong ulong_t
* ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<<
*
* ctypedef npy_intp intp_t
*/
typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":721
* ctypedef npy_ulonglong ulonglong_t
*
* ctypedef npy_intp intp_t # <<<<<<<<<<<<<<
* ctypedef npy_uintp uintp_t
*
*/
typedef npy_intp __pyx_t_5numpy_intp_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":722
*
* ctypedef npy_intp intp_t
* ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<<
*
* ctypedef npy_double float_t
*/
typedef npy_uintp __pyx_t_5numpy_uintp_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":724
* ctypedef npy_uintp uintp_t
*
* ctypedef npy_double float_t # <<<<<<<<<<<<<<
* ctypedef npy_double double_t
* ctypedef npy_longdouble longdouble_t
*/
typedef npy_double __pyx_t_5numpy_float_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":725
*
* ctypedef npy_double float_t
* ctypedef npy_double double_t # <<<<<<<<<<<<<<
* ctypedef npy_longdouble longdouble_t
*
*/
typedef npy_double __pyx_t_5numpy_double_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":726
* ctypedef npy_double float_t
* ctypedef npy_double double_t
* ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<<
*
* ctypedef npy_cfloat cfloat_t
*/
typedef npy_longdouble __pyx_t_5numpy_longdouble_t;
/* Declarations.proto */
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
typedef ::std::complex< float > __pyx_t_float_complex;
#else
typedef float _Complex __pyx_t_float_complex;
#endif
#else
typedef struct { float real, imag; } __pyx_t_float_complex;
#endif
static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float);
/* Declarations.proto */
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
typedef ::std::complex< double > __pyx_t_double_complex;
#else
typedef double _Complex __pyx_t_double_complex;
#endif
#else
typedef struct { double real, imag; } __pyx_t_double_complex;
#endif
static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double);
/*--- Type declarations ---*/
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":728
* ctypedef npy_longdouble longdouble_t
*
* ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<<
* ctypedef npy_cdouble cdouble_t
* ctypedef npy_clongdouble clongdouble_t
*/
typedef npy_cfloat __pyx_t_5numpy_cfloat_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":729
*
* ctypedef npy_cfloat cfloat_t
* ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<<
* ctypedef npy_clongdouble clongdouble_t
*
*/
typedef npy_cdouble __pyx_t_5numpy_cdouble_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":730
* ctypedef npy_cfloat cfloat_t
* ctypedef npy_cdouble cdouble_t
* ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<<
*
* ctypedef npy_cdouble complex_t
*/
typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":732
* ctypedef npy_clongdouble clongdouble_t
*
* ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<<
*
* cdef inline object PyArray_MultiIterNew1(a):
*/
typedef npy_cdouble __pyx_t_5numpy_complex_t;
/* --- Runtime support code (head) --- */
/* Refnanny.proto */
#ifndef CYTHON_REFNANNY
#define CYTHON_REFNANNY 0
#endif
#if CYTHON_REFNANNY
typedef struct {
void (*INCREF)(void*, PyObject*, int);
void (*DECREF)(void*, PyObject*, int);
void (*GOTREF)(void*, PyObject*, int);
void (*GIVEREF)(void*, PyObject*, int);
void* (*SetupContext)(const char*, int, const char*);
void (*FinishContext)(void**);
} __Pyx_RefNannyAPIStruct;
static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL;
static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname);
#define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL;
#ifdef WITH_THREAD
#define __Pyx_RefNannySetupContext(name, acquire_gil)\
if (acquire_gil) {\
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\
__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\
PyGILState_Release(__pyx_gilstate_save);\
} else {\
__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\
}
#else
#define __Pyx_RefNannySetupContext(name, acquire_gil)\
__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__)
#endif
#define __Pyx_RefNannyFinishContext()\
__Pyx_RefNanny->FinishContext(&__pyx_refnanny)
#define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0)
#define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0)
#define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0)
#define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0)
#else
#define __Pyx_RefNannyDeclarations
#define __Pyx_RefNannySetupContext(name, acquire_gil)
#define __Pyx_RefNannyFinishContext()
#define __Pyx_INCREF(r) Py_INCREF(r)
#define __Pyx_DECREF(r) Py_DECREF(r)
#define __Pyx_GOTREF(r)
#define __Pyx_GIVEREF(r)
#define __Pyx_XINCREF(r) Py_XINCREF(r)
#define __Pyx_XDECREF(r) Py_XDECREF(r)
#define __Pyx_XGOTREF(r)
#define __Pyx_XGIVEREF(r)
#endif
#define __Pyx_XDECREF_SET(r, v) do {\
PyObject *tmp = (PyObject *) r;\
r = v; __Pyx_XDECREF(tmp);\
} while (0)
#define __Pyx_DECREF_SET(r, v) do {\
PyObject *tmp = (PyObject *) r;\
r = v; __Pyx_DECREF(tmp);\
} while (0)
#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0)
#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0)
/* PyObjectGetAttrStr.proto */
#if CYTHON_USE_TYPE_SLOTS
static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name);
#else
#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n)
#endif
/* GetBuiltinName.proto */
static PyObject *__Pyx_GetBuiltinName(PyObject *name);
/* RaiseArgTupleInvalid.proto */
static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact,
Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found);
/* RaiseDoubleKeywords.proto */
static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name);
/* ParseKeywords.proto */
static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\
PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\
const char* function_name);
/* ArgTypeTest.proto */
#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\
((likely((Py_TYPE(obj) == type) | (none_allowed && (obj == Py_None)))) ? 1 :\
__Pyx__ArgTypeTest(obj, type, name, exact))
static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact);
/* IsLittleEndian.proto */
static CYTHON_INLINE int __Pyx_Is_Little_Endian(void);
/* BufferFormatCheck.proto */
static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts);
static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx,
__Pyx_BufFmt_StackElem* stack,
__Pyx_TypeInfo* type);
/* BufferGetAndValidate.proto */
#define __Pyx_GetBufferAndValidate(buf, obj, dtype, flags, nd, cast, stack)\
((obj == Py_None || obj == NULL) ?\
(__Pyx_ZeroBuffer(buf), 0) :\
__Pyx__GetBufferAndValidate(buf, obj, dtype, flags, nd, cast, stack))
static int __Pyx__GetBufferAndValidate(Py_buffer* buf, PyObject* obj,
__Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack);
static void __Pyx_ZeroBuffer(Py_buffer* buf);
static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info);
static Py_ssize_t __Pyx_minusones[] = { -1, -1, -1, -1, -1, -1, -1, -1 };
static Py_ssize_t __Pyx_zeros[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
/* PyFunctionFastCall.proto */
#if CYTHON_FAST_PYCALL
#define __Pyx_PyFunction_FastCall(func, args, nargs)\
__Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL)
#if 1 || PY_VERSION_HEX < 0x030600B1
static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs);
#else
#define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs)
#endif
#define __Pyx_BUILD_ASSERT_EXPR(cond)\
(sizeof(char [1 - 2*!(cond)]) - 1)
#ifndef Py_MEMBER_SIZE
#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member)
#endif
static size_t __pyx_pyframe_localsplus_offset = 0;
#include "frameobject.h"
#define __Pxy_PyFrame_Initialize_Offsets()\
((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\
(void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus)))
#define __Pyx_PyFrame_GetLocalsplus(frame)\
(assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset))
#endif
/* PyObjectCall.proto */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw);
#else
#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw)
#endif
/* PyObjectCallMethO.proto */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg);
#endif
/* PyObjectCallNoArg.proto */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func);
#else
#define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL)
#endif
/* PyCFunctionFastCall.proto */
#if CYTHON_FAST_PYCCALL
static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs);
#else
#define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL)
#endif
/* PyObjectCallOneArg.proto */
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg);
/* GetItemInt.proto */
#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\
(__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\
__Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\
(is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\
__Pyx_GetItemInt_Generic(o, to_py_func(i))))
#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\
(__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\
__Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\
(PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL))
static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i,
int wraparound, int boundscheck);
#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\
(__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\
__Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\
(PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL))
static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i,
int wraparound, int boundscheck);
static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j);
static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i,
int is_list, int wraparound, int boundscheck);
/* PyDictVersioning.proto */
#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS
#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1)
#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag)
#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\
(version_var) = __PYX_GET_DICT_VERSION(dict);\
(cache_var) = (value);
#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\
static PY_UINT64_T __pyx_dict_version = 0;\
static PyObject *__pyx_dict_cached_value = NULL;\
if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\
(VAR) = __pyx_dict_cached_value;\
} else {\
(VAR) = __pyx_dict_cached_value = (LOOKUP);\
__pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\
}\
}
static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj);
static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj);
static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version);
#else
#define __PYX_GET_DICT_VERSION(dict) (0)
#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)
#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP);
#endif
/* GetModuleGlobalName.proto */
#if CYTHON_USE_DICT_VERSIONS
#define __Pyx_GetModuleGlobalName(var, name) {\
static PY_UINT64_T __pyx_dict_version = 0;\
static PyObject *__pyx_dict_cached_value = NULL;\
(var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\
(likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\
__Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\
}
#define __Pyx_GetModuleGlobalNameUncached(var, name) {\
PY_UINT64_T __pyx_dict_version;\
PyObject *__pyx_dict_cached_value;\
(var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\
}
static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value);
#else
#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name)
#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name)
static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name);
#endif
/* PyObjectCall2Args.proto */
static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2);
/* ObjectGetItem.proto */
#if CYTHON_USE_TYPE_SLOTS
static CYTHON_INLINE PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key);
#else
#define __Pyx_PyObject_GetItem(obj, key) PyObject_GetItem(obj, key)
#endif
/* PyIntBinop.proto */
#if !CYTHON_COMPILING_IN_PYPY
static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check);
#else
#define __Pyx_PyInt_AddObjC(op1, op2, intval, inplace, zerodivision_check)\
(inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2))
#endif
/* SetItemInt.proto */
#define __Pyx_SetItemInt(o, i, v, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\
(__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\
__Pyx_SetItemInt_Fast(o, (Py_ssize_t)i, v, is_list, wraparound, boundscheck) :\
(is_list ? (PyErr_SetString(PyExc_IndexError, "list assignment index out of range"), -1) :\
__Pyx_SetItemInt_Generic(o, to_py_func(i), v)))
static int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v);
static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v,
int is_list, int wraparound, int boundscheck);
/* SliceObject.proto */
static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice(
PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop,
PyObject** py_start, PyObject** py_stop, PyObject** py_slice,
int has_cstart, int has_cstop, int wraparound);
/* PyThreadStateGet.proto */
#if CYTHON_FAST_THREAD_STATE
#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate;
#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current;
#define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type
#else
#define __Pyx_PyThreadState_declare
#define __Pyx_PyThreadState_assign
#define __Pyx_PyErr_Occurred() PyErr_Occurred()
#endif
/* PyErrFetchRestore.proto */
#if CYTHON_FAST_THREAD_STATE
#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL)
#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb)
#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb)
#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb)
#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb)
static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb);
static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb);
#if CYTHON_COMPILING_IN_CPYTHON
#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL))
#else
#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc)
#endif
#else
#define __Pyx_PyErr_Clear() PyErr_Clear()
#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc)
#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb)
#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb)
#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb)
#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb)
#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb)
#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb)
#endif
/* GetTopmostException.proto */
#if CYTHON_USE_EXC_INFO_STACK
static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate);
#endif
/* SaveResetException.proto */
#if CYTHON_FAST_THREAD_STATE
#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb)
static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb);
#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb)
static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb);
#else
#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb)
#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb)
#endif
/* PyErrExceptionMatches.proto */
#if CYTHON_FAST_THREAD_STATE
#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err)
static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err);
#else
#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err)
#endif
/* GetException.proto */
#if CYTHON_FAST_THREAD_STATE
#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb)
static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb);
#else
static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb);
#endif
/* RaiseException.proto */
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause);
/* TypeImport.proto */
#ifndef __PYX_HAVE_RT_ImportType_proto
#define __PYX_HAVE_RT_ImportType_proto
enum __Pyx_ImportType_CheckSize {
__Pyx_ImportType_CheckSize_Error = 0,
__Pyx_ImportType_CheckSize_Warn = 1,
__Pyx_ImportType_CheckSize_Ignore = 2
};
static PyTypeObject *__Pyx_ImportType(PyObject* module, const char *module_name, const char *class_name, size_t size, enum __Pyx_ImportType_CheckSize check_size);
#endif
/* Import.proto */
static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level);
/* CLineInTraceback.proto */
#ifdef CYTHON_CLINE_IN_TRACEBACK
#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0)
#else
static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line);
#endif
/* CodeObjectCache.proto */
typedef struct {
PyCodeObject* code_object;
int code_line;
} __Pyx_CodeObjectCacheEntry;
struct __Pyx_CodeObjectCache {
int count;
int max_count;
__Pyx_CodeObjectCacheEntry* entries;
};
static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL};
static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line);
static PyCodeObject *__pyx_find_code_object(int code_line);
static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object);
/* AddTraceback.proto */
static void __Pyx_AddTraceback(const char *funcname, int c_line,
int py_line, const char *filename);
/* BufferStructDeclare.proto */
typedef struct {
Py_ssize_t shape, strides, suboffsets;
} __Pyx_Buf_DimInfo;
typedef struct {
size_t refcount;
Py_buffer pybuffer;
} __Pyx_Buffer;
typedef struct {
__Pyx_Buffer *rcbuffer;
char *data;
__Pyx_Buf_DimInfo diminfo[8];
} __Pyx_LocalBuf_ND;
#if PY_MAJOR_VERSION < 3
static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags);
static void __Pyx_ReleaseBuffer(Py_buffer *view);
#else
#define __Pyx_GetBuffer PyObject_GetBuffer
#define __Pyx_ReleaseBuffer PyBuffer_Release
#endif
/* CIntToPy.proto */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value);
/* CIntToPy.proto */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value);
/* RealImag.proto */
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
#define __Pyx_CREAL(z) ((z).real())
#define __Pyx_CIMAG(z) ((z).imag())
#else
#define __Pyx_CREAL(z) (__real__(z))
#define __Pyx_CIMAG(z) (__imag__(z))
#endif
#else
#define __Pyx_CREAL(z) ((z).real)
#define __Pyx_CIMAG(z) ((z).imag)
#endif
#if defined(__cplusplus) && CYTHON_CCOMPLEX\
&& (defined(_WIN32) || defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 5 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4 )) || __cplusplus >= 201103)
#define __Pyx_SET_CREAL(z,x) ((z).real(x))
#define __Pyx_SET_CIMAG(z,y) ((z).imag(y))
#else
#define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x)
#define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y)
#endif
/* Arithmetic.proto */
#if CYTHON_CCOMPLEX
#define __Pyx_c_eq_float(a, b) ((a)==(b))
#define __Pyx_c_sum_float(a, b) ((a)+(b))
#define __Pyx_c_diff_float(a, b) ((a)-(b))
#define __Pyx_c_prod_float(a, b) ((a)*(b))
#define __Pyx_c_quot_float(a, b) ((a)/(b))
#define __Pyx_c_neg_float(a) (-(a))
#ifdef __cplusplus
#define __Pyx_c_is_zero_float(z) ((z)==(float)0)
#define __Pyx_c_conj_float(z) (::std::conj(z))
#if 1
#define __Pyx_c_abs_float(z) (::std::abs(z))
#define __Pyx_c_pow_float(a, b) (::std::pow(a, b))
#endif
#else
#define __Pyx_c_is_zero_float(z) ((z)==0)
#define __Pyx_c_conj_float(z) (conjf(z))
#if 1
#define __Pyx_c_abs_float(z) (cabsf(z))
#define __Pyx_c_pow_float(a, b) (cpowf(a, b))
#endif
#endif
#else
static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex, __pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex, __pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex, __pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex, __pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex, __pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex);
static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex);
#if 1
static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex, __pyx_t_float_complex);
#endif
#endif
/* Arithmetic.proto */
#if CYTHON_CCOMPLEX
#define __Pyx_c_eq_double(a, b) ((a)==(b))
#define __Pyx_c_sum_double(a, b) ((a)+(b))
#define __Pyx_c_diff_double(a, b) ((a)-(b))
#define __Pyx_c_prod_double(a, b) ((a)*(b))
#define __Pyx_c_quot_double(a, b) ((a)/(b))
#define __Pyx_c_neg_double(a) (-(a))
#ifdef __cplusplus
#define __Pyx_c_is_zero_double(z) ((z)==(double)0)
#define __Pyx_c_conj_double(z) (::std::conj(z))
#if 1
#define __Pyx_c_abs_double(z) (::std::abs(z))
#define __Pyx_c_pow_double(a, b) (::std::pow(a, b))
#endif
#else
#define __Pyx_c_is_zero_double(z) ((z)==0)
#define __Pyx_c_conj_double(z) (conj(z))
#if 1
#define __Pyx_c_abs_double(z) (cabs(z))
#define __Pyx_c_pow_double(a, b) (cpow(a, b))
#endif
#endif
#else
static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex, __pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex, __pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex, __pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex, __pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex, __pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex);
static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex);
#if 1
static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex, __pyx_t_double_complex);
#endif
#endif
/* CIntFromPy.proto */
static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *);
/* CIntFromPy.proto */
static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *);
/* CIntFromPy.proto */
static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *);
/* FastTypeChecks.proto */
#if CYTHON_COMPILING_IN_CPYTHON
#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type)
static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b);
static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type);
static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2);
#else
#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type)
#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type)
#define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2))
#endif
#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception)
/* CheckBinaryVersion.proto */
static int __Pyx_check_binary_version(void);
/* InitStrings.proto */
static int __Pyx_InitStrings(__Pyx_StringTabEntry *t);
/* Module declarations from 'cpython.buffer' */
/* Module declarations from 'libc.string' */
/* Module declarations from 'libc.stdio' */
/* Module declarations from '__builtin__' */
/* Module declarations from 'cpython.type' */
static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0;
/* Module declarations from 'cpython' */
/* Module declarations from 'cpython.object' */
/* Module declarations from 'cpython.ref' */
/* Module declarations from 'cpython.mem' */
/* Module declarations from 'numpy' */
/* Module declarations from 'numpy' */
static PyTypeObject *__pyx_ptype_5numpy_dtype = 0;
static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0;
static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0;
static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0;
static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0;
/* Module declarations from 'mmdet.ops.nms.soft_nms_cpu' */
static CYTHON_INLINE __pyx_t_5numpy_float32_t __pyx_f_5mmdet_3ops_3nms_12soft_nms_cpu_max(__pyx_t_5numpy_float32_t, __pyx_t_5numpy_float32_t); /*proto*/
static CYTHON_INLINE __pyx_t_5numpy_float32_t __pyx_f_5mmdet_3ops_3nms_12soft_nms_cpu_min(__pyx_t_5numpy_float32_t, __pyx_t_5numpy_float32_t); /*proto*/
static __Pyx_TypeInfo __Pyx_TypeInfo_float = { "float", NULL, sizeof(float), { 0 }, 0, 'R', 0, 0 };
#define __Pyx_MODULE_NAME "mmdet.ops.nms.soft_nms_cpu"
extern int __pyx_module_is_main_mmdet__ops__nms__soft_nms_cpu;
int __pyx_module_is_main_mmdet__ops__nms__soft_nms_cpu = 0;
/* Implementation of 'mmdet.ops.nms.soft_nms_cpu' */
static PyObject *__pyx_builtin_range;
static PyObject *__pyx_builtin_ImportError;
static const char __pyx_k_N[] = "N";
static const char __pyx_k_i[] = "i";
static const char __pyx_k_s[] = "s";
static const char __pyx_k_ih[] = "ih";
static const char __pyx_k_iw[] = "iw";
static const char __pyx_k_np[] = "np";
static const char __pyx_k_ov[] = "ov";
static const char __pyx_k_ti[] = "ti";
static const char __pyx_k_ts[] = "ts";
static const char __pyx_k_ua[] = "ua";
static const char __pyx_k_x1[] = "x1";
static const char __pyx_k_x2[] = "x2";
static const char __pyx_k_y1[] = "y1";
static const char __pyx_k_y2[] = "y2";
static const char __pyx_k_exp[] = "exp";
static const char __pyx_k_pos[] = "pos";
static const char __pyx_k_tx1[] = "tx1";
static const char __pyx_k_tx2[] = "tx2";
static const char __pyx_k_ty1[] = "ty1";
static const char __pyx_k_ty2[] = "ty2";
static const char __pyx_k_area[] = "area";
static const char __pyx_k_copy[] = "copy";
static const char __pyx_k_inds[] = "inds";
static const char __pyx_k_main[] = "__main__";
static const char __pyx_k_name[] = "__name__";
static const char __pyx_k_test[] = "__test__";
static const char __pyx_k_boxes[] = "boxes";
static const char __pyx_k_numpy[] = "numpy";
static const char __pyx_k_range[] = "range";
static const char __pyx_k_shape[] = "shape";
static const char __pyx_k_sigma[] = "sigma";
static const char __pyx_k_arange[] = "arange";
static const char __pyx_k_import[] = "__import__";
static const char __pyx_k_maxpos[] = "maxpos";
static const char __pyx_k_method[] = "method";
static const char __pyx_k_weight[] = "weight";
static const char __pyx_k_iou_thr[] = "iou_thr";
static const char __pyx_k_box_area[] = "box_area";
static const char __pyx_k_boxes_in[] = "boxes_in";
static const char __pyx_k_maxscore[] = "maxscore";
static const char __pyx_k_min_score[] = "min_score";
static const char __pyx_k_ImportError[] = "ImportError";
static const char __pyx_k_soft_nms_cpu[] = "soft_nms_cpu";
static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback";
static const char __pyx_k_mmdet_ops_nms_soft_nms_cpu[] = "mmdet.ops.nms.soft_nms_cpu";
static const char __pyx_k_numpy_core_multiarray_failed_to[] = "numpy.core.multiarray failed to import";
static const char __pyx_k_mmdet_ops_nms_src_soft_nms_cpu_p[] = "mmdet/ops/nms/src/soft_nms_cpu.pyx";
static const char __pyx_k_numpy_core_umath_failed_to_impor[] = "numpy.core.umath failed to import";
static PyObject *__pyx_n_s_ImportError;
static PyObject *__pyx_n_s_N;
static PyObject *__pyx_n_s_arange;
static PyObject *__pyx_n_s_area;
static PyObject *__pyx_n_s_box_area;
static PyObject *__pyx_n_s_boxes;
static PyObject *__pyx_n_s_boxes_in;
static PyObject *__pyx_n_s_cline_in_traceback;
static PyObject *__pyx_n_s_copy;
static PyObject *__pyx_n_s_exp;
static PyObject *__pyx_n_s_i;
static PyObject *__pyx_n_s_ih;
static PyObject *__pyx_n_s_import;
static PyObject *__pyx_n_s_inds;
static PyObject *__pyx_n_s_iou_thr;
static PyObject *__pyx_n_s_iw;
static PyObject *__pyx_n_s_main;
static PyObject *__pyx_n_s_maxpos;
static PyObject *__pyx_n_s_maxscore;
static PyObject *__pyx_n_s_method;
static PyObject *__pyx_n_s_min_score;
static PyObject *__pyx_n_s_mmdet_ops_nms_soft_nms_cpu;
static PyObject *__pyx_kp_s_mmdet_ops_nms_src_soft_nms_cpu_p;
static PyObject *__pyx_n_s_name;
static PyObject *__pyx_n_s_np;
static PyObject *__pyx_n_s_numpy;
static PyObject *__pyx_kp_u_numpy_core_multiarray_failed_to;
static PyObject *__pyx_kp_u_numpy_core_umath_failed_to_impor;
static PyObject *__pyx_n_s_ov;
static PyObject *__pyx_n_s_pos;
static PyObject *__pyx_n_s_range;
static PyObject *__pyx_n_s_s;
static PyObject *__pyx_n_s_shape;
static PyObject *__pyx_n_s_sigma;
static PyObject *__pyx_n_s_soft_nms_cpu;
static PyObject *__pyx_n_s_test;
static PyObject *__pyx_n_s_ti;
static PyObject *__pyx_n_s_ts;
static PyObject *__pyx_n_s_tx1;
static PyObject *__pyx_n_s_tx2;
static PyObject *__pyx_n_s_ty1;
static PyObject *__pyx_n_s_ty2;
static PyObject *__pyx_n_s_ua;
static PyObject *__pyx_n_s_weight;
static PyObject *__pyx_n_s_x1;
static PyObject *__pyx_n_s_x2;
static PyObject *__pyx_n_s_y1;
static PyObject *__pyx_n_s_y2;
static PyObject *__pyx_pf_5mmdet_3ops_3nms_12soft_nms_cpu_soft_nms_cpu(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_boxes_in, float __pyx_v_iou_thr, unsigned int __pyx_v_method, float __pyx_v_sigma, float __pyx_v_min_score); /* proto */
static PyObject *__pyx_int_0;
static PyObject *__pyx_int_1;
static PyObject *__pyx_int_2;
static PyObject *__pyx_int_3;
static PyObject *__pyx_int_4;
static PyObject *__pyx_tuple_;
static PyObject *__pyx_tuple__2;
static PyObject *__pyx_tuple__3;
static PyObject *__pyx_codeobj__4;
/* Late includes */
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":15
*
*
* cdef inline np.float32_t max(np.float32_t a, np.float32_t b): # <<<<<<<<<<<<<<
* return a if a >= b else b
*
*/
static CYTHON_INLINE __pyx_t_5numpy_float32_t __pyx_f_5mmdet_3ops_3nms_12soft_nms_cpu_max(__pyx_t_5numpy_float32_t __pyx_v_a, __pyx_t_5numpy_float32_t __pyx_v_b) {
__pyx_t_5numpy_float32_t __pyx_r;
__Pyx_RefNannyDeclarations
__pyx_t_5numpy_float32_t __pyx_t_1;
__Pyx_RefNannySetupContext("max", 0);
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":16
*
* cdef inline np.float32_t max(np.float32_t a, np.float32_t b):
* return a if a >= b else b # <<<<<<<<<<<<<<
*
* cdef inline np.float32_t min(np.float32_t a, np.float32_t b):
*/
if (((__pyx_v_a >= __pyx_v_b) != 0)) {
__pyx_t_1 = __pyx_v_a;
} else {
__pyx_t_1 = __pyx_v_b;
}
__pyx_r = __pyx_t_1;
goto __pyx_L0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":15
*
*
* cdef inline np.float32_t max(np.float32_t a, np.float32_t b): # <<<<<<<<<<<<<<
* return a if a >= b else b
*
*/
/* function exit code */
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":18
* return a if a >= b else b
*
* cdef inline np.float32_t min(np.float32_t a, np.float32_t b): # <<<<<<<<<<<<<<
* return a if a <= b else b
*
*/
static CYTHON_INLINE __pyx_t_5numpy_float32_t __pyx_f_5mmdet_3ops_3nms_12soft_nms_cpu_min(__pyx_t_5numpy_float32_t __pyx_v_a, __pyx_t_5numpy_float32_t __pyx_v_b) {
__pyx_t_5numpy_float32_t __pyx_r;
__Pyx_RefNannyDeclarations
__pyx_t_5numpy_float32_t __pyx_t_1;
__Pyx_RefNannySetupContext("min", 0);
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":19
*
* cdef inline np.float32_t min(np.float32_t a, np.float32_t b):
* return a if a <= b else b # <<<<<<<<<<<<<<
*
*
*/
if (((__pyx_v_a <= __pyx_v_b) != 0)) {
__pyx_t_1 = __pyx_v_a;
} else {
__pyx_t_1 = __pyx_v_b;
}
__pyx_r = __pyx_t_1;
goto __pyx_L0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":18
* return a if a >= b else b
*
* cdef inline np.float32_t min(np.float32_t a, np.float32_t b): # <<<<<<<<<<<<<<
* return a if a <= b else b
*
*/
/* function exit code */
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":22
*
*
* def soft_nms_cpu( # <<<<<<<<<<<<<<
* np.ndarray[float, ndim=2] boxes_in,
* float iou_thr,
*/
/* Python wrapper */
static PyObject *__pyx_pw_5mmdet_3ops_3nms_12soft_nms_cpu_1soft_nms_cpu(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static PyMethodDef __pyx_mdef_5mmdet_3ops_3nms_12soft_nms_cpu_1soft_nms_cpu = {"soft_nms_cpu", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_5mmdet_3ops_3nms_12soft_nms_cpu_1soft_nms_cpu, METH_VARARGS|METH_KEYWORDS, 0};
static PyObject *__pyx_pw_5mmdet_3ops_3nms_12soft_nms_cpu_1soft_nms_cpu(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
PyArrayObject *__pyx_v_boxes_in = 0;
float __pyx_v_iou_thr;
unsigned int __pyx_v_method;
float __pyx_v_sigma;
float __pyx_v_min_score;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("soft_nms_cpu (wrapper)", 0);
{
static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_boxes_in,&__pyx_n_s_iou_thr,&__pyx_n_s_method,&__pyx_n_s_sigma,&__pyx_n_s_min_score,0};
PyObject* values[5] = {0,0,0,0,0};
if (unlikely(__pyx_kwds)) {
Py_ssize_t kw_args;
const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
switch (pos_args) {
case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4);
CYTHON_FALLTHROUGH;
case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3);
CYTHON_FALLTHROUGH;
case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
CYTHON_FALLTHROUGH;
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
CYTHON_FALLTHROUGH;
case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
CYTHON_FALLTHROUGH;
case 0: break;
default: goto __pyx_L5_argtuple_error;
}
kw_args = PyDict_Size(__pyx_kwds);
switch (pos_args) {
case 0:
if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_boxes_in)) != 0)) kw_args--;
else goto __pyx_L5_argtuple_error;
CYTHON_FALLTHROUGH;
case 1:
if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_iou_thr)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("soft_nms_cpu", 0, 2, 5, 1); __PYX_ERR(0, 22, __pyx_L3_error)
}
CYTHON_FALLTHROUGH;
case 2:
if (kw_args > 0) {
PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_method);
if (value) { values[2] = value; kw_args--; }
}
CYTHON_FALLTHROUGH;
case 3:
if (kw_args > 0) {
PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_sigma);
if (value) { values[3] = value; kw_args--; }
}
CYTHON_FALLTHROUGH;
case 4:
if (kw_args > 0) {
PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_min_score);
if (value) { values[4] = value; kw_args--; }
}
}
if (unlikely(kw_args > 0)) {
if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "soft_nms_cpu") < 0)) __PYX_ERR(0, 22, __pyx_L3_error)
}
} else {
switch (PyTuple_GET_SIZE(__pyx_args)) {
case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4);
CYTHON_FALLTHROUGH;
case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3);
CYTHON_FALLTHROUGH;
case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
CYTHON_FALLTHROUGH;
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
break;
default: goto __pyx_L5_argtuple_error;
}
}
__pyx_v_boxes_in = ((PyArrayObject *)values[0]);
__pyx_v_iou_thr = __pyx_PyFloat_AsFloat(values[1]); if (unlikely((__pyx_v_iou_thr == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 24, __pyx_L3_error)
if (values[2]) {
__pyx_v_method = __Pyx_PyInt_As_unsigned_int(values[2]); if (unlikely((__pyx_v_method == (unsigned int)-1) && PyErr_Occurred())) __PYX_ERR(0, 25, __pyx_L3_error)
} else {
__pyx_v_method = ((unsigned int)1);
}
if (values[3]) {
__pyx_v_sigma = __pyx_PyFloat_AsFloat(values[3]); if (unlikely((__pyx_v_sigma == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 26, __pyx_L3_error)
} else {
__pyx_v_sigma = ((float)0.5);
}
if (values[4]) {
__pyx_v_min_score = __pyx_PyFloat_AsFloat(values[4]); if (unlikely((__pyx_v_min_score == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 27, __pyx_L3_error)
} else {
__pyx_v_min_score = ((float)0.001);
}
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L5_argtuple_error:;
__Pyx_RaiseArgtupleInvalid("soft_nms_cpu", 0, 2, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 22, __pyx_L3_error)
__pyx_L3_error:;
__Pyx_AddTraceback("mmdet.ops.nms.soft_nms_cpu.soft_nms_cpu", __pyx_clineno, __pyx_lineno, __pyx_filename);
__Pyx_RefNannyFinishContext();
return NULL;
__pyx_L4_argument_unpacking_done:;
if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_boxes_in), __pyx_ptype_5numpy_ndarray, 1, "boxes_in", 0))) __PYX_ERR(0, 23, __pyx_L1_error)
__pyx_r = __pyx_pf_5mmdet_3ops_3nms_12soft_nms_cpu_soft_nms_cpu(__pyx_self, __pyx_v_boxes_in, __pyx_v_iou_thr, __pyx_v_method, __pyx_v_sigma, __pyx_v_min_score);
/* function exit code */
goto __pyx_L0;
__pyx_L1_error:;
__pyx_r = NULL;
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_pf_5mmdet_3ops_3nms_12soft_nms_cpu_soft_nms_cpu(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_boxes_in, float __pyx_v_iou_thr, unsigned int __pyx_v_method, float __pyx_v_sigma, float __pyx_v_min_score) {
PyObject *__pyx_v_boxes = NULL;
int __pyx_v_N;
float __pyx_v_iw;
float __pyx_v_ih;
float __pyx_v_ua;
int __pyx_v_pos;
float __pyx_v_maxscore;
int __pyx_v_maxpos;
float __pyx_v_x1;
float __pyx_v_x2;
float __pyx_v_y1;
float __pyx_v_y2;
float __pyx_v_tx1;
float __pyx_v_tx2;
float __pyx_v_ty1;
float __pyx_v_ty2;
float __pyx_v_ts;
float __pyx_v_area;
float __pyx_v_weight;
float __pyx_v_ov;
PyObject *__pyx_v_inds = NULL;
PyObject *__pyx_v_i = NULL;
PyObject *__pyx_v_ti = NULL;
CYTHON_UNUSED PyObject *__pyx_v_s = NULL;
__Pyx_LocalBuf_ND __pyx_pybuffernd_boxes_in;
__Pyx_Buffer __pyx_pybuffer_boxes_in;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
int __pyx_t_4;
PyObject *__pyx_t_5 = NULL;
Py_ssize_t __pyx_t_6;
PyObject *(*__pyx_t_7)(PyObject *);
float __pyx_t_8;
int __pyx_t_9;
PyObject *__pyx_t_10 = NULL;
long __pyx_t_11;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("soft_nms_cpu", 0);
__pyx_pybuffer_boxes_in.pybuffer.buf = NULL;
__pyx_pybuffer_boxes_in.refcount = 0;
__pyx_pybuffernd_boxes_in.data = NULL;
__pyx_pybuffernd_boxes_in.rcbuffer = &__pyx_pybuffer_boxes_in;
{
__Pyx_BufFmt_StackElem __pyx_stack[1];
if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_boxes_in.rcbuffer->pybuffer, (PyObject*)__pyx_v_boxes_in, &__Pyx_TypeInfo_float, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) __PYX_ERR(0, 22, __pyx_L1_error)
}
__pyx_pybuffernd_boxes_in.diminfo[0].strides = __pyx_pybuffernd_boxes_in.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_boxes_in.diminfo[0].shape = __pyx_pybuffernd_boxes_in.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_boxes_in.diminfo[1].strides = __pyx_pybuffernd_boxes_in.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_boxes_in.diminfo[1].shape = __pyx_pybuffernd_boxes_in.rcbuffer->pybuffer.shape[1];
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":29
* float min_score=0.001,
* ):
* boxes = boxes_in.copy() # <<<<<<<<<<<<<<
* cdef int N = boxes.shape[0]
* cdef float iw, ih, box_area
*/
__pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_boxes_in), __pyx_n_s_copy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 29, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = NULL;
if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) {
__pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2);
if (likely(__pyx_t_3)) {
PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2);
__Pyx_INCREF(__pyx_t_3);
__Pyx_INCREF(function);
__Pyx_DECREF_SET(__pyx_t_2, function);
}
}
__pyx_t_1 = (__pyx_t_3) ? __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3) : __Pyx_PyObject_CallNoArg(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 29, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__pyx_v_boxes = __pyx_t_1;
__pyx_t_1 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":30
* ):
* boxes = boxes_in.copy()
* cdef int N = boxes.shape[0] # <<<<<<<<<<<<<<
* cdef float iw, ih, box_area
* cdef float ua
*/
__pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_boxes, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 30, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 30, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_4 = __Pyx_PyInt_As_int(__pyx_t_2); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 30, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__pyx_v_N = __pyx_t_4;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":33
* cdef float iw, ih, box_area
* cdef float ua
* cdef int pos = 0 # <<<<<<<<<<<<<<
* cdef float maxscore = 0
* cdef int maxpos = 0
*/
__pyx_v_pos = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":34
* cdef float ua
* cdef int pos = 0
* cdef float maxscore = 0 # <<<<<<<<<<<<<<
* cdef int maxpos = 0
* cdef float x1, x2, y1, y2, tx1, tx2, ty1, ty2, ts, area, weight, ov
*/
__pyx_v_maxscore = 0.0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":35
* cdef int pos = 0
* cdef float maxscore = 0
* cdef int maxpos = 0 # <<<<<<<<<<<<<<
* cdef float x1, x2, y1, y2, tx1, tx2, ty1, ty2, ts, area, weight, ov
* inds = np.arange(N)
*/
__pyx_v_maxpos = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":37
* cdef int maxpos = 0
* cdef float x1, x2, y1, y2, tx1, tx2, ty1, ty2, ts, area, weight, ov
* inds = np.arange(N) # <<<<<<<<<<<<<<
*
* for i in range(N):
*/
__Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_np); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 37, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_arange); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 37, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_N); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 37, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_5 = NULL;
if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) {
__pyx_t_5 = PyMethod_GET_SELF(__pyx_t_3);
if (likely(__pyx_t_5)) {
PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3);
__Pyx_INCREF(__pyx_t_5);
__Pyx_INCREF(function);
__Pyx_DECREF_SET(__pyx_t_3, function);
}
}
__pyx_t_2 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_5, __pyx_t_1) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_1);
__Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0;
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 37, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_inds = __pyx_t_2;
__pyx_t_2 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":39
* inds = np.arange(N)
*
* for i in range(N): # <<<<<<<<<<<<<<
* maxscore = boxes[i, 4]
* maxpos = i
*/
__pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_N); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 39, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_range, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 39, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
if (likely(PyList_CheckExact(__pyx_t_3)) || PyTuple_CheckExact(__pyx_t_3)) {
__pyx_t_2 = __pyx_t_3; __Pyx_INCREF(__pyx_t_2); __pyx_t_6 = 0;
__pyx_t_7 = NULL;
} else {
__pyx_t_6 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 39, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_7 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 39, __pyx_L1_error)
}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
for (;;) {
if (likely(!__pyx_t_7)) {
if (likely(PyList_CheckExact(__pyx_t_2))) {
if (__pyx_t_6 >= PyList_GET_SIZE(__pyx_t_2)) break;
#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS
__pyx_t_3 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_6); __Pyx_INCREF(__pyx_t_3); __pyx_t_6++; if (unlikely(0 < 0)) __PYX_ERR(0, 39, __pyx_L1_error)
#else
__pyx_t_3 = PySequence_ITEM(__pyx_t_2, __pyx_t_6); __pyx_t_6++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 39, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
#endif
} else {
if (__pyx_t_6 >= PyTuple_GET_SIZE(__pyx_t_2)) break;
#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS
__pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_6); __Pyx_INCREF(__pyx_t_3); __pyx_t_6++; if (unlikely(0 < 0)) __PYX_ERR(0, 39, __pyx_L1_error)
#else
__pyx_t_3 = PySequence_ITEM(__pyx_t_2, __pyx_t_6); __pyx_t_6++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 39, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
#endif
}
} else {
__pyx_t_3 = __pyx_t_7(__pyx_t_2);
if (unlikely(!__pyx_t_3)) {
PyObject* exc_type = PyErr_Occurred();
if (exc_type) {
if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear();
else __PYX_ERR(0, 39, __pyx_L1_error)
}
break;
}
__Pyx_GOTREF(__pyx_t_3);
}
__Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_3);
__pyx_t_3 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":40
*
* for i in range(N):
* maxscore = boxes[i, 4] # <<<<<<<<<<<<<<
* maxpos = i
*
*/
__pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 40, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_INCREF(__pyx_v_i);
__Pyx_GIVEREF(__pyx_v_i);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_i);
__Pyx_INCREF(__pyx_int_4);
__Pyx_GIVEREF(__pyx_int_4);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_4);
__pyx_t_1 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 40, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_8 = __pyx_PyFloat_AsFloat(__pyx_t_1); if (unlikely((__pyx_t_8 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 40, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_v_maxscore = __pyx_t_8;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":41
* for i in range(N):
* maxscore = boxes[i, 4]
* maxpos = i # <<<<<<<<<<<<<<
*
* tx1 = boxes[i, 0]
*/
__pyx_t_4 = __Pyx_PyInt_As_int(__pyx_v_i); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 41, __pyx_L1_error)
__pyx_v_maxpos = __pyx_t_4;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":43
* maxpos = i
*
* tx1 = boxes[i, 0] # <<<<<<<<<<<<<<
* ty1 = boxes[i, 1]
* tx2 = boxes[i, 2]
*/
__pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 43, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_INCREF(__pyx_v_i);
__Pyx_GIVEREF(__pyx_v_i);
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_i);
__Pyx_INCREF(__pyx_int_0);
__Pyx_GIVEREF(__pyx_int_0);
PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_0);
__pyx_t_3 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 43, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_8 = __pyx_PyFloat_AsFloat(__pyx_t_3); if (unlikely((__pyx_t_8 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 43, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_tx1 = __pyx_t_8;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":44
*
* tx1 = boxes[i, 0]
* ty1 = boxes[i, 1] # <<<<<<<<<<<<<<
* tx2 = boxes[i, 2]
* ty2 = boxes[i, 3]
*/
__pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 44, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_INCREF(__pyx_v_i);
__Pyx_GIVEREF(__pyx_v_i);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_i);
__Pyx_INCREF(__pyx_int_1);
__Pyx_GIVEREF(__pyx_int_1);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_1);
__pyx_t_1 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 44, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_8 = __pyx_PyFloat_AsFloat(__pyx_t_1); if (unlikely((__pyx_t_8 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 44, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_v_ty1 = __pyx_t_8;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":45
* tx1 = boxes[i, 0]
* ty1 = boxes[i, 1]
* tx2 = boxes[i, 2] # <<<<<<<<<<<<<<
* ty2 = boxes[i, 3]
* ts = boxes[i, 4]
*/
__pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 45, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_INCREF(__pyx_v_i);
__Pyx_GIVEREF(__pyx_v_i);
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_i);
__Pyx_INCREF(__pyx_int_2);
__Pyx_GIVEREF(__pyx_int_2);
PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_2);
__pyx_t_3 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 45, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_8 = __pyx_PyFloat_AsFloat(__pyx_t_3); if (unlikely((__pyx_t_8 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 45, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_tx2 = __pyx_t_8;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":46
* ty1 = boxes[i, 1]
* tx2 = boxes[i, 2]
* ty2 = boxes[i, 3] # <<<<<<<<<<<<<<
* ts = boxes[i, 4]
* ti = inds[i]
*/
__pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 46, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_INCREF(__pyx_v_i);
__Pyx_GIVEREF(__pyx_v_i);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_i);
__Pyx_INCREF(__pyx_int_3);
__Pyx_GIVEREF(__pyx_int_3);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_3);
__pyx_t_1 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 46, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_8 = __pyx_PyFloat_AsFloat(__pyx_t_1); if (unlikely((__pyx_t_8 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 46, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_v_ty2 = __pyx_t_8;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":47
* tx2 = boxes[i, 2]
* ty2 = boxes[i, 3]
* ts = boxes[i, 4] # <<<<<<<<<<<<<<
* ti = inds[i]
*
*/
__pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 47, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_INCREF(__pyx_v_i);
__Pyx_GIVEREF(__pyx_v_i);
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_i);
__Pyx_INCREF(__pyx_int_4);
__Pyx_GIVEREF(__pyx_int_4);
PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_4);
__pyx_t_3 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 47, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_8 = __pyx_PyFloat_AsFloat(__pyx_t_3); if (unlikely((__pyx_t_8 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 47, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_ts = __pyx_t_8;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":48
* ty2 = boxes[i, 3]
* ts = boxes[i, 4]
* ti = inds[i] # <<<<<<<<<<<<<<
*
* pos = i + 1
*/
__pyx_t_3 = __Pyx_PyObject_GetItem(__pyx_v_inds, __pyx_v_i); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 48, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_XDECREF_SET(__pyx_v_ti, __pyx_t_3);
__pyx_t_3 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":50
* ti = inds[i]
*
* pos = i + 1 # <<<<<<<<<<<<<<
* # get max box
* while pos < N:
*/
__pyx_t_3 = __Pyx_PyInt_AddObjC(__pyx_v_i, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 50, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 50, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_pos = __pyx_t_4;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":52
* pos = i + 1
* # get max box
* while pos < N: # <<<<<<<<<<<<<<
* if maxscore < boxes[pos, 4]:
* maxscore = boxes[pos, 4]
*/
while (1) {
__pyx_t_9 = ((__pyx_v_pos < __pyx_v_N) != 0);
if (!__pyx_t_9) break;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":53
* # get max box
* while pos < N:
* if maxscore < boxes[pos, 4]: # <<<<<<<<<<<<<<
* maxscore = boxes[pos, 4]
* maxpos = pos
*/
__pyx_t_3 = PyFloat_FromDouble(__pyx_v_maxscore); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 53, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_pos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 53, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 53, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GIVEREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1);
__Pyx_INCREF(__pyx_int_4);
__Pyx_GIVEREF(__pyx_int_4);
PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_4);
__pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_5); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 53, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_t_1, Py_LT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 53, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_9 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 53, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
if (__pyx_t_9) {
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":54
* while pos < N:
* if maxscore < boxes[pos, 4]:
* maxscore = boxes[pos, 4] # <<<<<<<<<<<<<<
* maxpos = pos
* pos = pos + 1
*/
__pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_pos); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 54, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 54, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_GIVEREF(__pyx_t_5);
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_5);
__Pyx_INCREF(__pyx_int_4);
__Pyx_GIVEREF(__pyx_int_4);
PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_4);
__pyx_t_5 = 0;
__pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 54, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_8 = __pyx_PyFloat_AsFloat(__pyx_t_5); if (unlikely((__pyx_t_8 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 54, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__pyx_v_maxscore = __pyx_t_8;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":55
* if maxscore < boxes[pos, 4]:
* maxscore = boxes[pos, 4]
* maxpos = pos # <<<<<<<<<<<<<<
* pos = pos + 1
*
*/
__pyx_v_maxpos = __pyx_v_pos;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":53
* # get max box
* while pos < N:
* if maxscore < boxes[pos, 4]: # <<<<<<<<<<<<<<
* maxscore = boxes[pos, 4]
* maxpos = pos
*/
}
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":56
* maxscore = boxes[pos, 4]
* maxpos = pos
* pos = pos + 1 # <<<<<<<<<<<<<<
*
* # add max box as a detection
*/
__pyx_v_pos = (__pyx_v_pos + 1);
}
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":59
*
* # add max box as a detection
* boxes[i, 0] = boxes[maxpos, 0] # <<<<<<<<<<<<<<
* boxes[i, 1] = boxes[maxpos, 1]
* boxes[i, 2] = boxes[maxpos, 2]
*/
__pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_maxpos); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 59, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 59, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_GIVEREF(__pyx_t_5);
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_5);
__Pyx_INCREF(__pyx_int_0);
__Pyx_GIVEREF(__pyx_int_0);
PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_0);
__pyx_t_5 = 0;
__pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 59, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 59, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_INCREF(__pyx_v_i);
__Pyx_GIVEREF(__pyx_v_i);
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_i);
__Pyx_INCREF(__pyx_int_0);
__Pyx_GIVEREF(__pyx_int_0);
PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_0);
if (unlikely(PyObject_SetItem(__pyx_v_boxes, __pyx_t_1, __pyx_t_5) < 0)) __PYX_ERR(0, 59, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":60
* # add max box as a detection
* boxes[i, 0] = boxes[maxpos, 0]
* boxes[i, 1] = boxes[maxpos, 1] # <<<<<<<<<<<<<<
* boxes[i, 2] = boxes[maxpos, 2]
* boxes[i, 3] = boxes[maxpos, 3]
*/
__pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_maxpos); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 60, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 60, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_GIVEREF(__pyx_t_5);
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_5);
__Pyx_INCREF(__pyx_int_1);
__Pyx_GIVEREF(__pyx_int_1);
PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_1);
__pyx_t_5 = 0;
__pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 60, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 60, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_INCREF(__pyx_v_i);
__Pyx_GIVEREF(__pyx_v_i);
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_i);
__Pyx_INCREF(__pyx_int_1);
__Pyx_GIVEREF(__pyx_int_1);
PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_1);
if (unlikely(PyObject_SetItem(__pyx_v_boxes, __pyx_t_1, __pyx_t_5) < 0)) __PYX_ERR(0, 60, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":61
* boxes[i, 0] = boxes[maxpos, 0]
* boxes[i, 1] = boxes[maxpos, 1]
* boxes[i, 2] = boxes[maxpos, 2] # <<<<<<<<<<<<<<
* boxes[i, 3] = boxes[maxpos, 3]
* boxes[i, 4] = boxes[maxpos, 4]
*/
__pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_maxpos); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 61, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 61, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_GIVEREF(__pyx_t_5);
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_5);
__Pyx_INCREF(__pyx_int_2);
__Pyx_GIVEREF(__pyx_int_2);
PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_2);
__pyx_t_5 = 0;
__pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 61, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 61, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_INCREF(__pyx_v_i);
__Pyx_GIVEREF(__pyx_v_i);
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_i);
__Pyx_INCREF(__pyx_int_2);
__Pyx_GIVEREF(__pyx_int_2);
PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_2);
if (unlikely(PyObject_SetItem(__pyx_v_boxes, __pyx_t_1, __pyx_t_5) < 0)) __PYX_ERR(0, 61, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":62
* boxes[i, 1] = boxes[maxpos, 1]
* boxes[i, 2] = boxes[maxpos, 2]
* boxes[i, 3] = boxes[maxpos, 3] # <<<<<<<<<<<<<<
* boxes[i, 4] = boxes[maxpos, 4]
* inds[i] = inds[maxpos]
*/
__pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_maxpos); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 62, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 62, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_GIVEREF(__pyx_t_5);
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_5);
__Pyx_INCREF(__pyx_int_3);
__Pyx_GIVEREF(__pyx_int_3);
PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_3);
__pyx_t_5 = 0;
__pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 62, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 62, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_INCREF(__pyx_v_i);
__Pyx_GIVEREF(__pyx_v_i);
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_i);
__Pyx_INCREF(__pyx_int_3);
__Pyx_GIVEREF(__pyx_int_3);
PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_3);
if (unlikely(PyObject_SetItem(__pyx_v_boxes, __pyx_t_1, __pyx_t_5) < 0)) __PYX_ERR(0, 62, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":63
* boxes[i, 2] = boxes[maxpos, 2]
* boxes[i, 3] = boxes[maxpos, 3]
* boxes[i, 4] = boxes[maxpos, 4] # <<<<<<<<<<<<<<
* inds[i] = inds[maxpos]
*
*/
__pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_maxpos); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 63, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 63, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_GIVEREF(__pyx_t_5);
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_5);
__Pyx_INCREF(__pyx_int_4);
__Pyx_GIVEREF(__pyx_int_4);
PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_4);
__pyx_t_5 = 0;
__pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 63, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 63, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_INCREF(__pyx_v_i);
__Pyx_GIVEREF(__pyx_v_i);
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_i);
__Pyx_INCREF(__pyx_int_4);
__Pyx_GIVEREF(__pyx_int_4);
PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_4);
if (unlikely(PyObject_SetItem(__pyx_v_boxes, __pyx_t_1, __pyx_t_5) < 0)) __PYX_ERR(0, 63, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":64
* boxes[i, 3] = boxes[maxpos, 3]
* boxes[i, 4] = boxes[maxpos, 4]
* inds[i] = inds[maxpos] # <<<<<<<<<<<<<<
*
* # swap ith box with position of max box
*/
__pyx_t_5 = __Pyx_GetItemInt(__pyx_v_inds, __pyx_v_maxpos, int, 1, __Pyx_PyInt_From_int, 0, 1, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 64, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
if (unlikely(PyObject_SetItem(__pyx_v_inds, __pyx_v_i, __pyx_t_5) < 0)) __PYX_ERR(0, 64, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":67
*
* # swap ith box with position of max box
* boxes[maxpos, 0] = tx1 # <<<<<<<<<<<<<<
* boxes[maxpos, 1] = ty1
* boxes[maxpos, 2] = tx2
*/
__pyx_t_5 = PyFloat_FromDouble(__pyx_v_tx1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 67, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_maxpos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 67, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 67, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_GIVEREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1);
__Pyx_INCREF(__pyx_int_0);
__Pyx_GIVEREF(__pyx_int_0);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0);
__pyx_t_1 = 0;
if (unlikely(PyObject_SetItem(__pyx_v_boxes, __pyx_t_3, __pyx_t_5) < 0)) __PYX_ERR(0, 67, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":68
* # swap ith box with position of max box
* boxes[maxpos, 0] = tx1
* boxes[maxpos, 1] = ty1 # <<<<<<<<<<<<<<
* boxes[maxpos, 2] = tx2
* boxes[maxpos, 3] = ty2
*/
__pyx_t_5 = PyFloat_FromDouble(__pyx_v_ty1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 68, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_maxpos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 68, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 68, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_GIVEREF(__pyx_t_3);
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_3);
__Pyx_INCREF(__pyx_int_1);
__Pyx_GIVEREF(__pyx_int_1);
PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_1);
__pyx_t_3 = 0;
if (unlikely(PyObject_SetItem(__pyx_v_boxes, __pyx_t_1, __pyx_t_5) < 0)) __PYX_ERR(0, 68, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":69
* boxes[maxpos, 0] = tx1
* boxes[maxpos, 1] = ty1
* boxes[maxpos, 2] = tx2 # <<<<<<<<<<<<<<
* boxes[maxpos, 3] = ty2
* boxes[maxpos, 4] = ts
*/
__pyx_t_5 = PyFloat_FromDouble(__pyx_v_tx2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 69, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_maxpos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 69, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 69, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_GIVEREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1);
__Pyx_INCREF(__pyx_int_2);
__Pyx_GIVEREF(__pyx_int_2);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_2);
__pyx_t_1 = 0;
if (unlikely(PyObject_SetItem(__pyx_v_boxes, __pyx_t_3, __pyx_t_5) < 0)) __PYX_ERR(0, 69, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":70
* boxes[maxpos, 1] = ty1
* boxes[maxpos, 2] = tx2
* boxes[maxpos, 3] = ty2 # <<<<<<<<<<<<<<
* boxes[maxpos, 4] = ts
* inds[maxpos] = ti
*/
__pyx_t_5 = PyFloat_FromDouble(__pyx_v_ty2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 70, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_maxpos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 70, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 70, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_GIVEREF(__pyx_t_3);
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_3);
__Pyx_INCREF(__pyx_int_3);
__Pyx_GIVEREF(__pyx_int_3);
PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_3);
__pyx_t_3 = 0;
if (unlikely(PyObject_SetItem(__pyx_v_boxes, __pyx_t_1, __pyx_t_5) < 0)) __PYX_ERR(0, 70, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":71
* boxes[maxpos, 2] = tx2
* boxes[maxpos, 3] = ty2
* boxes[maxpos, 4] = ts # <<<<<<<<<<<<<<
* inds[maxpos] = ti
*
*/
__pyx_t_5 = PyFloat_FromDouble(__pyx_v_ts); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 71, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_maxpos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 71, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 71, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_GIVEREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1);
__Pyx_INCREF(__pyx_int_4);
__Pyx_GIVEREF(__pyx_int_4);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_4);
__pyx_t_1 = 0;
if (unlikely(PyObject_SetItem(__pyx_v_boxes, __pyx_t_3, __pyx_t_5) < 0)) __PYX_ERR(0, 71, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":72
* boxes[maxpos, 3] = ty2
* boxes[maxpos, 4] = ts
* inds[maxpos] = ti # <<<<<<<<<<<<<<
*
* tx1 = boxes[i, 0]
*/
if (unlikely(__Pyx_SetItemInt(__pyx_v_inds, __pyx_v_maxpos, __pyx_v_ti, int, 1, __Pyx_PyInt_From_int, 0, 1, 0) < 0)) __PYX_ERR(0, 72, __pyx_L1_error)
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":74
* inds[maxpos] = ti
*
* tx1 = boxes[i, 0] # <<<<<<<<<<<<<<
* ty1 = boxes[i, 1]
* tx2 = boxes[i, 2]
*/
__pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 74, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_INCREF(__pyx_v_i);
__Pyx_GIVEREF(__pyx_v_i);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_i);
__Pyx_INCREF(__pyx_int_0);
__Pyx_GIVEREF(__pyx_int_0);
PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_0);
__pyx_t_3 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 74, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__pyx_t_8 = __pyx_PyFloat_AsFloat(__pyx_t_3); if (unlikely((__pyx_t_8 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 74, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_tx1 = __pyx_t_8;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":75
*
* tx1 = boxes[i, 0]
* ty1 = boxes[i, 1] # <<<<<<<<<<<<<<
* tx2 = boxes[i, 2]
* ty2 = boxes[i, 3]
*/
__pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 75, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_INCREF(__pyx_v_i);
__Pyx_GIVEREF(__pyx_v_i);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_i);
__Pyx_INCREF(__pyx_int_1);
__Pyx_GIVEREF(__pyx_int_1);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_1);
__pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 75, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_8 = __pyx_PyFloat_AsFloat(__pyx_t_5); if (unlikely((__pyx_t_8 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 75, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__pyx_v_ty1 = __pyx_t_8;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":76
* tx1 = boxes[i, 0]
* ty1 = boxes[i, 1]
* tx2 = boxes[i, 2] # <<<<<<<<<<<<<<
* ty2 = boxes[i, 3]
* ts = boxes[i, 4]
*/
__pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 76, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_INCREF(__pyx_v_i);
__Pyx_GIVEREF(__pyx_v_i);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_i);
__Pyx_INCREF(__pyx_int_2);
__Pyx_GIVEREF(__pyx_int_2);
PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_2);
__pyx_t_3 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 76, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__pyx_t_8 = __pyx_PyFloat_AsFloat(__pyx_t_3); if (unlikely((__pyx_t_8 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 76, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_tx2 = __pyx_t_8;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":77
* ty1 = boxes[i, 1]
* tx2 = boxes[i, 2]
* ty2 = boxes[i, 3] # <<<<<<<<<<<<<<
* ts = boxes[i, 4]
*
*/
__pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 77, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_INCREF(__pyx_v_i);
__Pyx_GIVEREF(__pyx_v_i);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_i);
__Pyx_INCREF(__pyx_int_3);
__Pyx_GIVEREF(__pyx_int_3);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_3);
__pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 77, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_8 = __pyx_PyFloat_AsFloat(__pyx_t_5); if (unlikely((__pyx_t_8 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 77, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__pyx_v_ty2 = __pyx_t_8;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":78
* tx2 = boxes[i, 2]
* ty2 = boxes[i, 3]
* ts = boxes[i, 4] # <<<<<<<<<<<<<<
*
* pos = i + 1
*/
__pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 78, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_INCREF(__pyx_v_i);
__Pyx_GIVEREF(__pyx_v_i);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_i);
__Pyx_INCREF(__pyx_int_4);
__Pyx_GIVEREF(__pyx_int_4);
PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_4);
__pyx_t_3 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 78, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__pyx_t_8 = __pyx_PyFloat_AsFloat(__pyx_t_3); if (unlikely((__pyx_t_8 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 78, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_ts = __pyx_t_8;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":80
* ts = boxes[i, 4]
*
* pos = i + 1 # <<<<<<<<<<<<<<
* # NMS iterations, note that N changes if detection boxes fall below
* # threshold
*/
__pyx_t_3 = __Pyx_PyInt_AddObjC(__pyx_v_i, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 80, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 80, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_pos = __pyx_t_4;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":83
* # NMS iterations, note that N changes if detection boxes fall below
* # threshold
* while pos < N: # <<<<<<<<<<<<<<
* x1 = boxes[pos, 0]
* y1 = boxes[pos, 1]
*/
while (1) {
__pyx_t_9 = ((__pyx_v_pos < __pyx_v_N) != 0);
if (!__pyx_t_9) break;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":84
* # threshold
* while pos < N:
* x1 = boxes[pos, 0] # <<<<<<<<<<<<<<
* y1 = boxes[pos, 1]
* x2 = boxes[pos, 2]
*/
__pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_pos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 84, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 84, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GIVEREF(__pyx_t_3);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3);
__Pyx_INCREF(__pyx_int_0);
__Pyx_GIVEREF(__pyx_int_0);
PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_0);
__pyx_t_3 = 0;
__pyx_t_3 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 84, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__pyx_t_8 = __pyx_PyFloat_AsFloat(__pyx_t_3); if (unlikely((__pyx_t_8 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 84, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_x1 = __pyx_t_8;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":85
* while pos < N:
* x1 = boxes[pos, 0]
* y1 = boxes[pos, 1] # <<<<<<<<<<<<<<
* x2 = boxes[pos, 2]
* y2 = boxes[pos, 3]
*/
__pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_pos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 85, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 85, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GIVEREF(__pyx_t_3);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3);
__Pyx_INCREF(__pyx_int_1);
__Pyx_GIVEREF(__pyx_int_1);
PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_1);
__pyx_t_3 = 0;
__pyx_t_3 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 85, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__pyx_t_8 = __pyx_PyFloat_AsFloat(__pyx_t_3); if (unlikely((__pyx_t_8 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 85, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_y1 = __pyx_t_8;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":86
* x1 = boxes[pos, 0]
* y1 = boxes[pos, 1]
* x2 = boxes[pos, 2] # <<<<<<<<<<<<<<
* y2 = boxes[pos, 3]
* s = boxes[pos, 4]
*/
__pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_pos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 86, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 86, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GIVEREF(__pyx_t_3);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3);
__Pyx_INCREF(__pyx_int_2);
__Pyx_GIVEREF(__pyx_int_2);
PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_2);
__pyx_t_3 = 0;
__pyx_t_3 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 86, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__pyx_t_8 = __pyx_PyFloat_AsFloat(__pyx_t_3); if (unlikely((__pyx_t_8 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 86, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_x2 = __pyx_t_8;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":87
* y1 = boxes[pos, 1]
* x2 = boxes[pos, 2]
* y2 = boxes[pos, 3] # <<<<<<<<<<<<<<
* s = boxes[pos, 4]
*
*/
__pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_pos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 87, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 87, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GIVEREF(__pyx_t_3);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3);
__Pyx_INCREF(__pyx_int_3);
__Pyx_GIVEREF(__pyx_int_3);
PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_3);
__pyx_t_3 = 0;
__pyx_t_3 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 87, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__pyx_t_8 = __pyx_PyFloat_AsFloat(__pyx_t_3); if (unlikely((__pyx_t_8 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 87, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_y2 = __pyx_t_8;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":88
* x2 = boxes[pos, 2]
* y2 = boxes[pos, 3]
* s = boxes[pos, 4] # <<<<<<<<<<<<<<
*
* area = (x2 - x1 + 1) * (y2 - y1 + 1)
*/
__pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_pos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 88, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 88, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GIVEREF(__pyx_t_3);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3);
__Pyx_INCREF(__pyx_int_4);
__Pyx_GIVEREF(__pyx_int_4);
PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_4);
__pyx_t_3 = 0;
__pyx_t_3 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 88, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__Pyx_XDECREF_SET(__pyx_v_s, __pyx_t_3);
__pyx_t_3 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":90
* s = boxes[pos, 4]
*
* area = (x2 - x1 + 1) * (y2 - y1 + 1) # <<<<<<<<<<<<<<
* iw = (min(tx2, x2) - max(tx1, x1) + 1)
* if iw > 0:
*/
__pyx_v_area = (((__pyx_v_x2 - __pyx_v_x1) + 1.0) * ((__pyx_v_y2 - __pyx_v_y1) + 1.0));
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":91
*
* area = (x2 - x1 + 1) * (y2 - y1 + 1)
* iw = (min(tx2, x2) - max(tx1, x1) + 1) # <<<<<<<<<<<<<<
* if iw > 0:
* ih = (min(ty2, y2) - max(ty1, y1) + 1)
*/
__pyx_v_iw = ((__pyx_f_5mmdet_3ops_3nms_12soft_nms_cpu_min(__pyx_v_tx2, __pyx_v_x2) - __pyx_f_5mmdet_3ops_3nms_12soft_nms_cpu_max(__pyx_v_tx1, __pyx_v_x1)) + 1.0);
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":92
* area = (x2 - x1 + 1) * (y2 - y1 + 1)
* iw = (min(tx2, x2) - max(tx1, x1) + 1)
* if iw > 0: # <<<<<<<<<<<<<<
* ih = (min(ty2, y2) - max(ty1, y1) + 1)
* if ih > 0:
*/
__pyx_t_9 = ((__pyx_v_iw > 0.0) != 0);
if (__pyx_t_9) {
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":93
* iw = (min(tx2, x2) - max(tx1, x1) + 1)
* if iw > 0:
* ih = (min(ty2, y2) - max(ty1, y1) + 1) # <<<<<<<<<<<<<<
* if ih > 0:
* ua = float((tx2 - tx1 + 1) * (ty2 - ty1 + 1) + area - iw * ih)
*/
__pyx_v_ih = ((__pyx_f_5mmdet_3ops_3nms_12soft_nms_cpu_min(__pyx_v_ty2, __pyx_v_y2) - __pyx_f_5mmdet_3ops_3nms_12soft_nms_cpu_max(__pyx_v_ty1, __pyx_v_y1)) + 1.0);
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":94
* if iw > 0:
* ih = (min(ty2, y2) - max(ty1, y1) + 1)
* if ih > 0: # <<<<<<<<<<<<<<
* ua = float((tx2 - tx1 + 1) * (ty2 - ty1 + 1) + area - iw * ih)
* ov = iw * ih / ua # iou between max box and detection box
*/
__pyx_t_9 = ((__pyx_v_ih > 0.0) != 0);
if (__pyx_t_9) {
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":95
* ih = (min(ty2, y2) - max(ty1, y1) + 1)
* if ih > 0:
* ua = float((tx2 - tx1 + 1) * (ty2 - ty1 + 1) + area - iw * ih) # <<<<<<<<<<<<<<
* ov = iw * ih / ua # iou between max box and detection box
*
*/
__pyx_v_ua = ((double)(((((__pyx_v_tx2 - __pyx_v_tx1) + 1.0) * ((__pyx_v_ty2 - __pyx_v_ty1) + 1.0)) + __pyx_v_area) - (__pyx_v_iw * __pyx_v_ih)));
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":96
* if ih > 0:
* ua = float((tx2 - tx1 + 1) * (ty2 - ty1 + 1) + area - iw * ih)
* ov = iw * ih / ua # iou between max box and detection box # <<<<<<<<<<<<<<
*
* if method == 1: # linear
*/
__pyx_t_8 = (__pyx_v_iw * __pyx_v_ih);
if (unlikely(__pyx_v_ua == 0)) {
PyErr_SetString(PyExc_ZeroDivisionError, "float division");
__PYX_ERR(0, 96, __pyx_L1_error)
}
__pyx_v_ov = (__pyx_t_8 / __pyx_v_ua);
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":98
* ov = iw * ih / ua # iou between max box and detection box
*
* if method == 1: # linear # <<<<<<<<<<<<<<
* if ov > iou_thr:
* weight = 1 - ov
*/
switch (__pyx_v_method) {
case 1:
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":99
*
* if method == 1: # linear
* if ov > iou_thr: # <<<<<<<<<<<<<<
* weight = 1 - ov
* else:
*/
__pyx_t_9 = ((__pyx_v_ov > __pyx_v_iou_thr) != 0);
if (__pyx_t_9) {
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":100
* if method == 1: # linear
* if ov > iou_thr:
* weight = 1 - ov # <<<<<<<<<<<<<<
* else:
* weight = 1
*/
__pyx_v_weight = (1.0 - __pyx_v_ov);
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":99
*
* if method == 1: # linear
* if ov > iou_thr: # <<<<<<<<<<<<<<
* weight = 1 - ov
* else:
*/
goto __pyx_L12;
}
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":102
* weight = 1 - ov
* else:
* weight = 1 # <<<<<<<<<<<<<<
* elif method == 2: # gaussian
* weight = np.exp(-(ov * ov) / sigma)
*/
/*else*/ {
__pyx_v_weight = 1.0;
}
__pyx_L12:;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":98
* ov = iw * ih / ua # iou between max box and detection box
*
* if method == 1: # linear # <<<<<<<<<<<<<<
* if ov > iou_thr:
* weight = 1 - ov
*/
break;
case 2:
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":104
* weight = 1
* elif method == 2: # gaussian
* weight = np.exp(-(ov * ov) / sigma) # <<<<<<<<<<<<<<
* else: # original NMS
* if ov > iou_thr:
*/
__Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_np); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 104, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_exp); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 104, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__pyx_t_8 = (-(__pyx_v_ov * __pyx_v_ov));
if (unlikely(__pyx_v_sigma == 0)) {
PyErr_SetString(PyExc_ZeroDivisionError, "float division");
__PYX_ERR(0, 104, __pyx_L1_error)
}
__pyx_t_5 = PyFloat_FromDouble((__pyx_t_8 / __pyx_v_sigma)); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 104, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_10 = NULL;
if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_1))) {
__pyx_t_10 = PyMethod_GET_SELF(__pyx_t_1);
if (likely(__pyx_t_10)) {
PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1);
__Pyx_INCREF(__pyx_t_10);
__Pyx_INCREF(function);
__Pyx_DECREF_SET(__pyx_t_1, function);
}
}
__pyx_t_3 = (__pyx_t_10) ? __Pyx_PyObject_Call2Args(__pyx_t_1, __pyx_t_10, __pyx_t_5) : __Pyx_PyObject_CallOneArg(__pyx_t_1, __pyx_t_5);
__Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0;
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 104, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_8 = __pyx_PyFloat_AsFloat(__pyx_t_3); if (unlikely((__pyx_t_8 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 104, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_weight = __pyx_t_8;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":103
* else:
* weight = 1
* elif method == 2: # gaussian # <<<<<<<<<<<<<<
* weight = np.exp(-(ov * ov) / sigma)
* else: # original NMS
*/
break;
default:
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":106
* weight = np.exp(-(ov * ov) / sigma)
* else: # original NMS
* if ov > iou_thr: # <<<<<<<<<<<<<<
* weight = 0
* else:
*/
__pyx_t_9 = ((__pyx_v_ov > __pyx_v_iou_thr) != 0);
if (__pyx_t_9) {
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":107
* else: # original NMS
* if ov > iou_thr:
* weight = 0 # <<<<<<<<<<<<<<
* else:
* weight = 1
*/
__pyx_v_weight = 0.0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":106
* weight = np.exp(-(ov * ov) / sigma)
* else: # original NMS
* if ov > iou_thr: # <<<<<<<<<<<<<<
* weight = 0
* else:
*/
goto __pyx_L13;
}
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":109
* weight = 0
* else:
* weight = 1 # <<<<<<<<<<<<<<
*
* boxes[pos, 4] = weight * boxes[pos, 4]
*/
/*else*/ {
__pyx_v_weight = 1.0;
}
__pyx_L13:;
break;
}
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":111
* weight = 1
*
* boxes[pos, 4] = weight * boxes[pos, 4] # <<<<<<<<<<<<<<
*
* # if box score falls below threshold, discard the box by
*/
__pyx_t_3 = PyFloat_FromDouble(__pyx_v_weight); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 111, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_pos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 111, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 111, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GIVEREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1);
__Pyx_INCREF(__pyx_int_4);
__Pyx_GIVEREF(__pyx_int_4);
PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_4);
__pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_5); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 111, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__pyx_t_5 = PyNumber_Multiply(__pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 111, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_pos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 111, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 111, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_GIVEREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1);
__Pyx_INCREF(__pyx_int_4);
__Pyx_GIVEREF(__pyx_int_4);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_4);
__pyx_t_1 = 0;
if (unlikely(PyObject_SetItem(__pyx_v_boxes, __pyx_t_3, __pyx_t_5) < 0)) __PYX_ERR(0, 111, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":115
* # if box score falls below threshold, discard the box by
* # swapping with last box update N
* if boxes[pos, 4] < min_score: # <<<<<<<<<<<<<<
* boxes[pos, 0] = boxes[N-1, 0]
* boxes[pos, 1] = boxes[N-1, 1]
*/
__pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_pos); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 115, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 115, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_GIVEREF(__pyx_t_5);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5);
__Pyx_INCREF(__pyx_int_4);
__Pyx_GIVEREF(__pyx_int_4);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_4);
__pyx_t_5 = 0;
__pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 115, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_3 = PyFloat_FromDouble(__pyx_v_min_score); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 115, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_1 = PyObject_RichCompare(__pyx_t_5, __pyx_t_3, Py_LT); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 115, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_9 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 115, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
if (__pyx_t_9) {
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":116
* # swapping with last box update N
* if boxes[pos, 4] < min_score:
* boxes[pos, 0] = boxes[N-1, 0] # <<<<<<<<<<<<<<
* boxes[pos, 1] = boxes[N-1, 1]
* boxes[pos, 2] = boxes[N-1, 2]
*/
__pyx_t_1 = __Pyx_PyInt_From_long((__pyx_v_N - 1)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 116, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 116, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_GIVEREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1);
__Pyx_INCREF(__pyx_int_0);
__Pyx_GIVEREF(__pyx_int_0);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0);
__pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 116, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_pos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 116, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 116, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GIVEREF(__pyx_t_3);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3);
__Pyx_INCREF(__pyx_int_0);
__Pyx_GIVEREF(__pyx_int_0);
PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_0);
__pyx_t_3 = 0;
if (unlikely(PyObject_SetItem(__pyx_v_boxes, __pyx_t_5, __pyx_t_1) < 0)) __PYX_ERR(0, 116, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":117
* if boxes[pos, 4] < min_score:
* boxes[pos, 0] = boxes[N-1, 0]
* boxes[pos, 1] = boxes[N-1, 1] # <<<<<<<<<<<<<<
* boxes[pos, 2] = boxes[N-1, 2]
* boxes[pos, 3] = boxes[N-1, 3]
*/
__pyx_t_1 = __Pyx_PyInt_From_long((__pyx_v_N - 1)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 117, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 117, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GIVEREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1);
__Pyx_INCREF(__pyx_int_1);
__Pyx_GIVEREF(__pyx_int_1);
PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_1);
__pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_5); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 117, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_pos); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 117, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 117, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_GIVEREF(__pyx_t_5);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5);
__Pyx_INCREF(__pyx_int_1);
__Pyx_GIVEREF(__pyx_int_1);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_1);
__pyx_t_5 = 0;
if (unlikely(PyObject_SetItem(__pyx_v_boxes, __pyx_t_3, __pyx_t_1) < 0)) __PYX_ERR(0, 117, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":118
* boxes[pos, 0] = boxes[N-1, 0]
* boxes[pos, 1] = boxes[N-1, 1]
* boxes[pos, 2] = boxes[N-1, 2] # <<<<<<<<<<<<<<
* boxes[pos, 3] = boxes[N-1, 3]
* boxes[pos, 4] = boxes[N-1, 4]
*/
__pyx_t_1 = __Pyx_PyInt_From_long((__pyx_v_N - 1)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 118, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 118, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_GIVEREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1);
__Pyx_INCREF(__pyx_int_2);
__Pyx_GIVEREF(__pyx_int_2);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_2);
__pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 118, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_pos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 118, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 118, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GIVEREF(__pyx_t_3);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3);
__Pyx_INCREF(__pyx_int_2);
__Pyx_GIVEREF(__pyx_int_2);
PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_2);
__pyx_t_3 = 0;
if (unlikely(PyObject_SetItem(__pyx_v_boxes, __pyx_t_5, __pyx_t_1) < 0)) __PYX_ERR(0, 118, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":119
* boxes[pos, 1] = boxes[N-1, 1]
* boxes[pos, 2] = boxes[N-1, 2]
* boxes[pos, 3] = boxes[N-1, 3] # <<<<<<<<<<<<<<
* boxes[pos, 4] = boxes[N-1, 4]
* inds[pos] = inds[N - 1]
*/
__pyx_t_1 = __Pyx_PyInt_From_long((__pyx_v_N - 1)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 119, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 119, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GIVEREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1);
__Pyx_INCREF(__pyx_int_3);
__Pyx_GIVEREF(__pyx_int_3);
PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_3);
__pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_5); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 119, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_pos); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 119, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 119, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_GIVEREF(__pyx_t_5);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5);
__Pyx_INCREF(__pyx_int_3);
__Pyx_GIVEREF(__pyx_int_3);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_3);
__pyx_t_5 = 0;
if (unlikely(PyObject_SetItem(__pyx_v_boxes, __pyx_t_3, __pyx_t_1) < 0)) __PYX_ERR(0, 119, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":120
* boxes[pos, 2] = boxes[N-1, 2]
* boxes[pos, 3] = boxes[N-1, 3]
* boxes[pos, 4] = boxes[N-1, 4] # <<<<<<<<<<<<<<
* inds[pos] = inds[N - 1]
* N = N - 1
*/
__pyx_t_1 = __Pyx_PyInt_From_long((__pyx_v_N - 1)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 120, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 120, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_GIVEREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1);
__Pyx_INCREF(__pyx_int_4);
__Pyx_GIVEREF(__pyx_int_4);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_4);
__pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyObject_GetItem(__pyx_v_boxes, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 120, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_pos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 120, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 120, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GIVEREF(__pyx_t_3);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3);
__Pyx_INCREF(__pyx_int_4);
__Pyx_GIVEREF(__pyx_int_4);
PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_4);
__pyx_t_3 = 0;
if (unlikely(PyObject_SetItem(__pyx_v_boxes, __pyx_t_5, __pyx_t_1) < 0)) __PYX_ERR(0, 120, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":121
* boxes[pos, 3] = boxes[N-1, 3]
* boxes[pos, 4] = boxes[N-1, 4]
* inds[pos] = inds[N - 1] # <<<<<<<<<<<<<<
* N = N - 1
* pos = pos - 1
*/
__pyx_t_11 = (__pyx_v_N - 1);
__pyx_t_1 = __Pyx_GetItemInt(__pyx_v_inds, __pyx_t_11, long, 1, __Pyx_PyInt_From_long, 0, 1, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 121, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
if (unlikely(__Pyx_SetItemInt(__pyx_v_inds, __pyx_v_pos, __pyx_t_1, int, 1, __Pyx_PyInt_From_int, 0, 1, 0) < 0)) __PYX_ERR(0, 121, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":122
* boxes[pos, 4] = boxes[N-1, 4]
* inds[pos] = inds[N - 1]
* N = N - 1 # <<<<<<<<<<<<<<
* pos = pos - 1
*
*/
__pyx_v_N = (__pyx_v_N - 1);
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":123
* inds[pos] = inds[N - 1]
* N = N - 1
* pos = pos - 1 # <<<<<<<<<<<<<<
*
* pos = pos + 1
*/
__pyx_v_pos = (__pyx_v_pos - 1);
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":115
* # if box score falls below threshold, discard the box by
* # swapping with last box update N
* if boxes[pos, 4] < min_score: # <<<<<<<<<<<<<<
* boxes[pos, 0] = boxes[N-1, 0]
* boxes[pos, 1] = boxes[N-1, 1]
*/
}
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":94
* if iw > 0:
* ih = (min(ty2, y2) - max(ty1, y1) + 1)
* if ih > 0: # <<<<<<<<<<<<<<
* ua = float((tx2 - tx1 + 1) * (ty2 - ty1 + 1) + area - iw * ih)
* ov = iw * ih / ua # iou between max box and detection box
*/
}
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":92
* area = (x2 - x1 + 1) * (y2 - y1 + 1)
* iw = (min(tx2, x2) - max(tx1, x1) + 1)
* if iw > 0: # <<<<<<<<<<<<<<
* ih = (min(ty2, y2) - max(ty1, y1) + 1)
* if ih > 0:
*/
}
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":125
* pos = pos - 1
*
* pos = pos + 1 # <<<<<<<<<<<<<<
*
* return boxes[:N], inds[:N]
*/
__pyx_v_pos = (__pyx_v_pos + 1);
}
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":39
* inds = np.arange(N)
*
* for i in range(N): # <<<<<<<<<<<<<<
* maxscore = boxes[i, 4]
* maxpos = i
*/
}
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":127
* pos = pos + 1
*
* return boxes[:N], inds[:N] # <<<<<<<<<<<<<<
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_2 = __Pyx_PyObject_GetSlice(__pyx_v_boxes, 0, __pyx_v_N, NULL, NULL, NULL, 0, 1, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 127, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_1 = __Pyx_PyObject_GetSlice(__pyx_v_inds, 0, __pyx_v_N, NULL, NULL, NULL, 0, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 127, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 127, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GIVEREF(__pyx_t_2);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2);
__Pyx_GIVEREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_1);
__pyx_t_2 = 0;
__pyx_t_1 = 0;
__pyx_r = __pyx_t_5;
__pyx_t_5 = 0;
goto __pyx_L0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":22
*
*
* def soft_nms_cpu( # <<<<<<<<<<<<<<
* np.ndarray[float, ndim=2] boxes_in,
* float iou_thr,
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_XDECREF(__pyx_t_5);
__Pyx_XDECREF(__pyx_t_10);
{ PyObject *__pyx_type, *__pyx_value, *__pyx_tb;
__Pyx_PyThreadState_declare
__Pyx_PyThreadState_assign
__Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb);
__Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_boxes_in.rcbuffer->pybuffer);
__Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);}
__Pyx_AddTraceback("mmdet.ops.nms.soft_nms_cpu.soft_nms_cpu", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
goto __pyx_L2;
__pyx_L0:;
__Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_boxes_in.rcbuffer->pybuffer);
__pyx_L2:;
__Pyx_XDECREF(__pyx_v_boxes);
__Pyx_XDECREF(__pyx_v_inds);
__Pyx_XDECREF(__pyx_v_i);
__Pyx_XDECREF(__pyx_v_ti);
__Pyx_XDECREF(__pyx_v_s);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":734
* ctypedef npy_cdouble complex_t
*
* cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(1, <void*>a)
*
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":735
*
* cdef inline object PyArray_MultiIterNew1(a):
* return PyArray_MultiIterNew(1, <void*>a) # <<<<<<<<<<<<<<
*
* cdef inline object PyArray_MultiIterNew2(a, b):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 735, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":734
* ctypedef npy_cdouble complex_t
*
* cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(1, <void*>a)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":737
* return PyArray_MultiIterNew(1, <void*>a)
*
* cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(2, <void*>a, <void*>b)
*
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":738
*
* cdef inline object PyArray_MultiIterNew2(a, b):
* return PyArray_MultiIterNew(2, <void*>a, <void*>b) # <<<<<<<<<<<<<<
*
* cdef inline object PyArray_MultiIterNew3(a, b, c):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 738, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":737
* return PyArray_MultiIterNew(1, <void*>a)
*
* cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(2, <void*>a, <void*>b)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":740
* return PyArray_MultiIterNew(2, <void*>a, <void*>b)
*
* cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
*
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":741
*
* cdef inline object PyArray_MultiIterNew3(a, b, c):
* return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) # <<<<<<<<<<<<<<
*
* cdef inline object PyArray_MultiIterNew4(a, b, c, d):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 741, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":740
* return PyArray_MultiIterNew(2, <void*>a, <void*>b)
*
* cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":743
* return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
*
* cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
*
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":744
*
* cdef inline object PyArray_MultiIterNew4(a, b, c, d):
* return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) # <<<<<<<<<<<<<<
*
* cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 744, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":743
* return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
*
* cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":746
* return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
*
* cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
*
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":747
*
* cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
* return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) # <<<<<<<<<<<<<<
*
* cdef inline tuple PyDataType_SHAPE(dtype d):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 747, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":746
* return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
*
* cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":749
* return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
*
* cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<<
* if PyDataType_HASSUBARRAY(d):
* return <tuple>d.subarray.shape
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyDataType_SHAPE(PyArray_Descr *__pyx_v_d) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
__Pyx_RefNannySetupContext("PyDataType_SHAPE", 0);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":750
*
* cdef inline tuple PyDataType_SHAPE(dtype d):
* if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<<
* return <tuple>d.subarray.shape
* else:
*/
__pyx_t_1 = (PyDataType_HASSUBARRAY(__pyx_v_d) != 0);
if (__pyx_t_1) {
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":751
* cdef inline tuple PyDataType_SHAPE(dtype d):
* if PyDataType_HASSUBARRAY(d):
* return <tuple>d.subarray.shape # <<<<<<<<<<<<<<
* else:
* return ()
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(((PyObject*)__pyx_v_d->subarray->shape));
__pyx_r = ((PyObject*)__pyx_v_d->subarray->shape);
goto __pyx_L0;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":750
*
* cdef inline tuple PyDataType_SHAPE(dtype d):
* if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<<
* return <tuple>d.subarray.shape
* else:
*/
}
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":753
* return <tuple>d.subarray.shape
* else:
* return () # <<<<<<<<<<<<<<
*
*
*/
/*else*/ {
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(__pyx_empty_tuple);
__pyx_r = __pyx_empty_tuple;
goto __pyx_L0;
}
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":749
* return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
*
* cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<<
* if PyDataType_HASSUBARRAY(d):
* return <tuple>d.subarray.shape
*/
/* function exit code */
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":868
* int _import_umath() except -1
*
* cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<<
* Py_INCREF(base) # important to do this before stealing the reference below!
* PyArray_SetBaseObject(arr, base)
*/
static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("set_array_base", 0);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":869
*
* cdef inline void set_array_base(ndarray arr, object base):
* Py_INCREF(base) # important to do this before stealing the reference below! # <<<<<<<<<<<<<<
* PyArray_SetBaseObject(arr, base)
*
*/
Py_INCREF(__pyx_v_base);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":870
* cdef inline void set_array_base(ndarray arr, object base):
* Py_INCREF(base) # important to do this before stealing the reference below!
* PyArray_SetBaseObject(arr, base) # <<<<<<<<<<<<<<
*
* cdef inline object get_array_base(ndarray arr):
*/
(void)(PyArray_SetBaseObject(__pyx_v_arr, __pyx_v_base));
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":868
* int _import_umath() except -1
*
* cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<<
* Py_INCREF(base) # important to do this before stealing the reference below!
* PyArray_SetBaseObject(arr, base)
*/
/* function exit code */
__Pyx_RefNannyFinishContext();
}
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":872
* PyArray_SetBaseObject(arr, base)
*
* cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<<
* base = PyArray_BASE(arr)
* if base is NULL:
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) {
PyObject *__pyx_v_base;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
__Pyx_RefNannySetupContext("get_array_base", 0);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":873
*
* cdef inline object get_array_base(ndarray arr):
* base = PyArray_BASE(arr) # <<<<<<<<<<<<<<
* if base is NULL:
* return None
*/
__pyx_v_base = PyArray_BASE(__pyx_v_arr);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":874
* cdef inline object get_array_base(ndarray arr):
* base = PyArray_BASE(arr)
* if base is NULL: # <<<<<<<<<<<<<<
* return None
* return <object>base
*/
__pyx_t_1 = ((__pyx_v_base == NULL) != 0);
if (__pyx_t_1) {
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":875
* base = PyArray_BASE(arr)
* if base is NULL:
* return None # <<<<<<<<<<<<<<
* return <object>base
*
*/
__Pyx_XDECREF(__pyx_r);
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":874
* cdef inline object get_array_base(ndarray arr):
* base = PyArray_BASE(arr)
* if base is NULL: # <<<<<<<<<<<<<<
* return None
* return <object>base
*/
}
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":876
* if base is NULL:
* return None
* return <object>base # <<<<<<<<<<<<<<
*
* # Versions of the import_* functions which are more suitable for
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(((PyObject *)__pyx_v_base));
__pyx_r = ((PyObject *)__pyx_v_base);
goto __pyx_L0;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":872
* PyArray_SetBaseObject(arr, base)
*
* cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<<
* base = PyArray_BASE(arr)
* if base is NULL:
*/
/* function exit code */
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":880
* # Versions of the import_* functions which are more suitable for
* # Cython code.
* cdef inline int import_array() except -1: # <<<<<<<<<<<<<<
* try:
* __pyx_import_array()
*/
static CYTHON_INLINE int __pyx_f_5numpy_import_array(void) {
int __pyx_r;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
int __pyx_t_4;
PyObject *__pyx_t_5 = NULL;
PyObject *__pyx_t_6 = NULL;
PyObject *__pyx_t_7 = NULL;
PyObject *__pyx_t_8 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("import_array", 0);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":881
* # Cython code.
* cdef inline int import_array() except -1:
* try: # <<<<<<<<<<<<<<
* __pyx_import_array()
* except Exception:
*/
{
__Pyx_PyThreadState_declare
__Pyx_PyThreadState_assign
__Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3);
__Pyx_XGOTREF(__pyx_t_1);
__Pyx_XGOTREF(__pyx_t_2);
__Pyx_XGOTREF(__pyx_t_3);
/*try:*/ {
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":882
* cdef inline int import_array() except -1:
* try:
* __pyx_import_array() # <<<<<<<<<<<<<<
* except Exception:
* raise ImportError("numpy.core.multiarray failed to import")
*/
__pyx_t_4 = _import_array(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 882, __pyx_L3_error)
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":881
* # Cython code.
* cdef inline int import_array() except -1:
* try: # <<<<<<<<<<<<<<
* __pyx_import_array()
* except Exception:
*/
}
__Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0;
__Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
goto __pyx_L8_try_end;
__pyx_L3_error:;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":883
* try:
* __pyx_import_array()
* except Exception: # <<<<<<<<<<<<<<
* raise ImportError("numpy.core.multiarray failed to import")
*
*/
__pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0])));
if (__pyx_t_4) {
__Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename);
if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 883, __pyx_L5_except_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GOTREF(__pyx_t_6);
__Pyx_GOTREF(__pyx_t_7);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":884
* __pyx_import_array()
* except Exception:
* raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<<
*
* cdef inline int import_umath() except -1:
*/
__pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 884, __pyx_L5_except_error)
__Pyx_GOTREF(__pyx_t_8);
__Pyx_Raise(__pyx_t_8, 0, 0, 0);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__PYX_ERR(1, 884, __pyx_L5_except_error)
}
goto __pyx_L5_except_error;
__pyx_L5_except_error:;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":881
* # Cython code.
* cdef inline int import_array() except -1:
* try: # <<<<<<<<<<<<<<
* __pyx_import_array()
* except Exception:
*/
__Pyx_XGIVEREF(__pyx_t_1);
__Pyx_XGIVEREF(__pyx_t_2);
__Pyx_XGIVEREF(__pyx_t_3);
__Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3);
goto __pyx_L1_error;
__pyx_L8_try_end:;
}
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":880
* # Versions of the import_* functions which are more suitable for
* # Cython code.
* cdef inline int import_array() except -1: # <<<<<<<<<<<<<<
* try:
* __pyx_import_array()
*/
/* function exit code */
__pyx_r = 0;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_5);
__Pyx_XDECREF(__pyx_t_6);
__Pyx_XDECREF(__pyx_t_7);
__Pyx_XDECREF(__pyx_t_8);
__Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = -1;
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":886
* raise ImportError("numpy.core.multiarray failed to import")
*
* cdef inline int import_umath() except -1: # <<<<<<<<<<<<<<
* try:
* _import_umath()
*/
static CYTHON_INLINE int __pyx_f_5numpy_import_umath(void) {
int __pyx_r;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
int __pyx_t_4;
PyObject *__pyx_t_5 = NULL;
PyObject *__pyx_t_6 = NULL;
PyObject *__pyx_t_7 = NULL;
PyObject *__pyx_t_8 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("import_umath", 0);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":887
*
* cdef inline int import_umath() except -1:
* try: # <<<<<<<<<<<<<<
* _import_umath()
* except Exception:
*/
{
__Pyx_PyThreadState_declare
__Pyx_PyThreadState_assign
__Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3);
__Pyx_XGOTREF(__pyx_t_1);
__Pyx_XGOTREF(__pyx_t_2);
__Pyx_XGOTREF(__pyx_t_3);
/*try:*/ {
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":888
* cdef inline int import_umath() except -1:
* try:
* _import_umath() # <<<<<<<<<<<<<<
* except Exception:
* raise ImportError("numpy.core.umath failed to import")
*/
__pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 888, __pyx_L3_error)
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":887
*
* cdef inline int import_umath() except -1:
* try: # <<<<<<<<<<<<<<
* _import_umath()
* except Exception:
*/
}
__Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0;
__Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
goto __pyx_L8_try_end;
__pyx_L3_error:;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":889
* try:
* _import_umath()
* except Exception: # <<<<<<<<<<<<<<
* raise ImportError("numpy.core.umath failed to import")
*
*/
__pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0])));
if (__pyx_t_4) {
__Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename);
if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 889, __pyx_L5_except_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GOTREF(__pyx_t_6);
__Pyx_GOTREF(__pyx_t_7);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":890
* _import_umath()
* except Exception:
* raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<<
*
* cdef inline int import_ufunc() except -1:
*/
__pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 890, __pyx_L5_except_error)
__Pyx_GOTREF(__pyx_t_8);
__Pyx_Raise(__pyx_t_8, 0, 0, 0);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__PYX_ERR(1, 890, __pyx_L5_except_error)
}
goto __pyx_L5_except_error;
__pyx_L5_except_error:;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":887
*
* cdef inline int import_umath() except -1:
* try: # <<<<<<<<<<<<<<
* _import_umath()
* except Exception:
*/
__Pyx_XGIVEREF(__pyx_t_1);
__Pyx_XGIVEREF(__pyx_t_2);
__Pyx_XGIVEREF(__pyx_t_3);
__Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3);
goto __pyx_L1_error;
__pyx_L8_try_end:;
}
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":886
* raise ImportError("numpy.core.multiarray failed to import")
*
* cdef inline int import_umath() except -1: # <<<<<<<<<<<<<<
* try:
* _import_umath()
*/
/* function exit code */
__pyx_r = 0;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_5);
__Pyx_XDECREF(__pyx_t_6);
__Pyx_XDECREF(__pyx_t_7);
__Pyx_XDECREF(__pyx_t_8);
__Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = -1;
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":892
* raise ImportError("numpy.core.umath failed to import")
*
* cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<<
* try:
* _import_umath()
*/
static CYTHON_INLINE int __pyx_f_5numpy_import_ufunc(void) {
int __pyx_r;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
int __pyx_t_4;
PyObject *__pyx_t_5 = NULL;
PyObject *__pyx_t_6 = NULL;
PyObject *__pyx_t_7 = NULL;
PyObject *__pyx_t_8 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("import_ufunc", 0);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":893
*
* cdef inline int import_ufunc() except -1:
* try: # <<<<<<<<<<<<<<
* _import_umath()
* except Exception:
*/
{
__Pyx_PyThreadState_declare
__Pyx_PyThreadState_assign
__Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3);
__Pyx_XGOTREF(__pyx_t_1);
__Pyx_XGOTREF(__pyx_t_2);
__Pyx_XGOTREF(__pyx_t_3);
/*try:*/ {
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":894
* cdef inline int import_ufunc() except -1:
* try:
* _import_umath() # <<<<<<<<<<<<<<
* except Exception:
* raise ImportError("numpy.core.umath failed to import")
*/
__pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 894, __pyx_L3_error)
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":893
*
* cdef inline int import_ufunc() except -1:
* try: # <<<<<<<<<<<<<<
* _import_umath()
* except Exception:
*/
}
__Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0;
__Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
goto __pyx_L8_try_end;
__pyx_L3_error:;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":895
* try:
* _import_umath()
* except Exception: # <<<<<<<<<<<<<<
* raise ImportError("numpy.core.umath failed to import")
*
*/
__pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0])));
if (__pyx_t_4) {
__Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename);
if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 895, __pyx_L5_except_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GOTREF(__pyx_t_6);
__Pyx_GOTREF(__pyx_t_7);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":896
* _import_umath()
* except Exception:
* raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<<
*
* cdef extern from *:
*/
__pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 896, __pyx_L5_except_error)
__Pyx_GOTREF(__pyx_t_8);
__Pyx_Raise(__pyx_t_8, 0, 0, 0);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__PYX_ERR(1, 896, __pyx_L5_except_error)
}
goto __pyx_L5_except_error;
__pyx_L5_except_error:;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":893
*
* cdef inline int import_ufunc() except -1:
* try: # <<<<<<<<<<<<<<
* _import_umath()
* except Exception:
*/
__Pyx_XGIVEREF(__pyx_t_1);
__Pyx_XGIVEREF(__pyx_t_2);
__Pyx_XGIVEREF(__pyx_t_3);
__Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3);
goto __pyx_L1_error;
__pyx_L8_try_end:;
}
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":892
* raise ImportError("numpy.core.umath failed to import")
*
* cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<<
* try:
* _import_umath()
*/
/* function exit code */
__pyx_r = 0;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_5);
__Pyx_XDECREF(__pyx_t_6);
__Pyx_XDECREF(__pyx_t_7);
__Pyx_XDECREF(__pyx_t_8);
__Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = -1;
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyMethodDef __pyx_methods[] = {
{0, 0, 0, 0}
};
#if PY_MAJOR_VERSION >= 3
#if CYTHON_PEP489_MULTI_PHASE_INIT
static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/
static int __pyx_pymod_exec_soft_nms_cpu(PyObject* module); /*proto*/
static PyModuleDef_Slot __pyx_moduledef_slots[] = {
{Py_mod_create, (void*)__pyx_pymod_create},
{Py_mod_exec, (void*)__pyx_pymod_exec_soft_nms_cpu},
{0, NULL}
};
#endif
static struct PyModuleDef __pyx_moduledef = {
PyModuleDef_HEAD_INIT,
"soft_nms_cpu",
0, /* m_doc */
#if CYTHON_PEP489_MULTI_PHASE_INIT
0, /* m_size */
#else
-1, /* m_size */
#endif
__pyx_methods /* m_methods */,
#if CYTHON_PEP489_MULTI_PHASE_INIT
__pyx_moduledef_slots, /* m_slots */
#else
NULL, /* m_reload */
#endif
NULL, /* m_traverse */
NULL, /* m_clear */
NULL /* m_free */
};
#endif
#ifndef CYTHON_SMALL_CODE
#if defined(__clang__)
#define CYTHON_SMALL_CODE
#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
#define CYTHON_SMALL_CODE __attribute__((cold))
#else
#define CYTHON_SMALL_CODE
#endif
#endif
static __Pyx_StringTabEntry __pyx_string_tab[] = {
{&__pyx_n_s_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1},
{&__pyx_n_s_N, __pyx_k_N, sizeof(__pyx_k_N), 0, 0, 1, 1},
{&__pyx_n_s_arange, __pyx_k_arange, sizeof(__pyx_k_arange), 0, 0, 1, 1},
{&__pyx_n_s_area, __pyx_k_area, sizeof(__pyx_k_area), 0, 0, 1, 1},
{&__pyx_n_s_box_area, __pyx_k_box_area, sizeof(__pyx_k_box_area), 0, 0, 1, 1},
{&__pyx_n_s_boxes, __pyx_k_boxes, sizeof(__pyx_k_boxes), 0, 0, 1, 1},
{&__pyx_n_s_boxes_in, __pyx_k_boxes_in, sizeof(__pyx_k_boxes_in), 0, 0, 1, 1},
{&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1},
{&__pyx_n_s_copy, __pyx_k_copy, sizeof(__pyx_k_copy), 0, 0, 1, 1},
{&__pyx_n_s_exp, __pyx_k_exp, sizeof(__pyx_k_exp), 0, 0, 1, 1},
{&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1},
{&__pyx_n_s_ih, __pyx_k_ih, sizeof(__pyx_k_ih), 0, 0, 1, 1},
{&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1},
{&__pyx_n_s_inds, __pyx_k_inds, sizeof(__pyx_k_inds), 0, 0, 1, 1},
{&__pyx_n_s_iou_thr, __pyx_k_iou_thr, sizeof(__pyx_k_iou_thr), 0, 0, 1, 1},
{&__pyx_n_s_iw, __pyx_k_iw, sizeof(__pyx_k_iw), 0, 0, 1, 1},
{&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1},
{&__pyx_n_s_maxpos, __pyx_k_maxpos, sizeof(__pyx_k_maxpos), 0, 0, 1, 1},
{&__pyx_n_s_maxscore, __pyx_k_maxscore, sizeof(__pyx_k_maxscore), 0, 0, 1, 1},
{&__pyx_n_s_method, __pyx_k_method, sizeof(__pyx_k_method), 0, 0, 1, 1},
{&__pyx_n_s_min_score, __pyx_k_min_score, sizeof(__pyx_k_min_score), 0, 0, 1, 1},
{&__pyx_n_s_mmdet_ops_nms_soft_nms_cpu, __pyx_k_mmdet_ops_nms_soft_nms_cpu, sizeof(__pyx_k_mmdet_ops_nms_soft_nms_cpu), 0, 0, 1, 1},
{&__pyx_kp_s_mmdet_ops_nms_src_soft_nms_cpu_p, __pyx_k_mmdet_ops_nms_src_soft_nms_cpu_p, sizeof(__pyx_k_mmdet_ops_nms_src_soft_nms_cpu_p), 0, 0, 1, 0},
{&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1},
{&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1},
{&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1},
{&__pyx_kp_u_numpy_core_multiarray_failed_to, __pyx_k_numpy_core_multiarray_failed_to, sizeof(__pyx_k_numpy_core_multiarray_failed_to), 0, 1, 0, 0},
{&__pyx_kp_u_numpy_core_umath_failed_to_impor, __pyx_k_numpy_core_umath_failed_to_impor, sizeof(__pyx_k_numpy_core_umath_failed_to_impor), 0, 1, 0, 0},
{&__pyx_n_s_ov, __pyx_k_ov, sizeof(__pyx_k_ov), 0, 0, 1, 1},
{&__pyx_n_s_pos, __pyx_k_pos, sizeof(__pyx_k_pos), 0, 0, 1, 1},
{&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1},
{&__pyx_n_s_s, __pyx_k_s, sizeof(__pyx_k_s), 0, 0, 1, 1},
{&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1},
{&__pyx_n_s_sigma, __pyx_k_sigma, sizeof(__pyx_k_sigma), 0, 0, 1, 1},
{&__pyx_n_s_soft_nms_cpu, __pyx_k_soft_nms_cpu, sizeof(__pyx_k_soft_nms_cpu), 0, 0, 1, 1},
{&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1},
{&__pyx_n_s_ti, __pyx_k_ti, sizeof(__pyx_k_ti), 0, 0, 1, 1},
{&__pyx_n_s_ts, __pyx_k_ts, sizeof(__pyx_k_ts), 0, 0, 1, 1},
{&__pyx_n_s_tx1, __pyx_k_tx1, sizeof(__pyx_k_tx1), 0, 0, 1, 1},
{&__pyx_n_s_tx2, __pyx_k_tx2, sizeof(__pyx_k_tx2), 0, 0, 1, 1},
{&__pyx_n_s_ty1, __pyx_k_ty1, sizeof(__pyx_k_ty1), 0, 0, 1, 1},
{&__pyx_n_s_ty2, __pyx_k_ty2, sizeof(__pyx_k_ty2), 0, 0, 1, 1},
{&__pyx_n_s_ua, __pyx_k_ua, sizeof(__pyx_k_ua), 0, 0, 1, 1},
{&__pyx_n_s_weight, __pyx_k_weight, sizeof(__pyx_k_weight), 0, 0, 1, 1},
{&__pyx_n_s_x1, __pyx_k_x1, sizeof(__pyx_k_x1), 0, 0, 1, 1},
{&__pyx_n_s_x2, __pyx_k_x2, sizeof(__pyx_k_x2), 0, 0, 1, 1},
{&__pyx_n_s_y1, __pyx_k_y1, sizeof(__pyx_k_y1), 0, 0, 1, 1},
{&__pyx_n_s_y2, __pyx_k_y2, sizeof(__pyx_k_y2), 0, 0, 1, 1},
{0, 0, 0, 0, 0, 0, 0}
};
static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) {
__pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 39, __pyx_L1_error)
__pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) __PYX_ERR(1, 884, __pyx_L1_error)
return 0;
__pyx_L1_error:;
return -1;
}
static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":884
* __pyx_import_array()
* except Exception:
* raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<<
*
* cdef inline int import_umath() except -1:
*/
__pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_numpy_core_multiarray_failed_to); if (unlikely(!__pyx_tuple_)) __PYX_ERR(1, 884, __pyx_L1_error)
__Pyx_GOTREF(__pyx_tuple_);
__Pyx_GIVEREF(__pyx_tuple_);
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":890
* _import_umath()
* except Exception:
* raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<<
*
* cdef inline int import_ufunc() except -1:
*/
__pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_numpy_core_umath_failed_to_impor); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(1, 890, __pyx_L1_error)
__Pyx_GOTREF(__pyx_tuple__2);
__Pyx_GIVEREF(__pyx_tuple__2);
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":22
*
*
* def soft_nms_cpu( # <<<<<<<<<<<<<<
* np.ndarray[float, ndim=2] boxes_in,
* float iou_thr,
*/
__pyx_tuple__3 = PyTuple_Pack(30, __pyx_n_s_boxes_in, __pyx_n_s_iou_thr, __pyx_n_s_method, __pyx_n_s_sigma, __pyx_n_s_min_score, __pyx_n_s_boxes, __pyx_n_s_N, __pyx_n_s_iw, __pyx_n_s_ih, __pyx_n_s_box_area, __pyx_n_s_ua, __pyx_n_s_pos, __pyx_n_s_maxscore, __pyx_n_s_maxpos, __pyx_n_s_x1, __pyx_n_s_x2, __pyx_n_s_y1, __pyx_n_s_y2, __pyx_n_s_tx1, __pyx_n_s_tx2, __pyx_n_s_ty1, __pyx_n_s_ty2, __pyx_n_s_ts, __pyx_n_s_area, __pyx_n_s_weight, __pyx_n_s_ov, __pyx_n_s_inds, __pyx_n_s_i, __pyx_n_s_ti, __pyx_n_s_s); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(0, 22, __pyx_L1_error)
__Pyx_GOTREF(__pyx_tuple__3);
__Pyx_GIVEREF(__pyx_tuple__3);
__pyx_codeobj__4 = (PyObject*)__Pyx_PyCode_New(5, 0, 30, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__3, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_mmdet_ops_nms_src_soft_nms_cpu_p, __pyx_n_s_soft_nms_cpu, 22, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__4)) __PYX_ERR(0, 22, __pyx_L1_error)
__Pyx_RefNannyFinishContext();
return 0;
__pyx_L1_error:;
__Pyx_RefNannyFinishContext();
return -1;
}
static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) {
if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error);
__pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error)
__pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) __PYX_ERR(0, 1, __pyx_L1_error)
__pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) __PYX_ERR(0, 1, __pyx_L1_error)
__pyx_int_3 = PyInt_FromLong(3); if (unlikely(!__pyx_int_3)) __PYX_ERR(0, 1, __pyx_L1_error)
__pyx_int_4 = PyInt_FromLong(4); if (unlikely(!__pyx_int_4)) __PYX_ERR(0, 1, __pyx_L1_error)
return 0;
__pyx_L1_error:;
return -1;
}
static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/
static int __Pyx_modinit_global_init_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0);
/*--- Global init code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
static int __Pyx_modinit_variable_export_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0);
/*--- Variable export code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
static int __Pyx_modinit_function_export_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0);
/*--- Function export code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
static int __Pyx_modinit_type_init_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0);
/*--- Type init code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
static int __Pyx_modinit_type_import_code(void) {
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0);
/*--- Type import code ---*/
__pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 9, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "type",
#if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000
sizeof(PyTypeObject),
#else
sizeof(PyHeapTypeObject),
#endif
__Pyx_ImportType_CheckSize_Warn);
if (!__pyx_ptype_7cpython_4type_type) __PYX_ERR(2, 9, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = PyImport_ImportModule("numpy"); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 199, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_ptype_5numpy_dtype = __Pyx_ImportType(__pyx_t_1, "numpy", "dtype", sizeof(PyArray_Descr), __Pyx_ImportType_CheckSize_Ignore);
if (!__pyx_ptype_5numpy_dtype) __PYX_ERR(1, 199, __pyx_L1_error)
__pyx_ptype_5numpy_flatiter = __Pyx_ImportType(__pyx_t_1, "numpy", "flatiter", sizeof(PyArrayIterObject), __Pyx_ImportType_CheckSize_Ignore);
if (!__pyx_ptype_5numpy_flatiter) __PYX_ERR(1, 222, __pyx_L1_error)
__pyx_ptype_5numpy_broadcast = __Pyx_ImportType(__pyx_t_1, "numpy", "broadcast", sizeof(PyArrayMultiIterObject), __Pyx_ImportType_CheckSize_Ignore);
if (!__pyx_ptype_5numpy_broadcast) __PYX_ERR(1, 226, __pyx_L1_error)
__pyx_ptype_5numpy_ndarray = __Pyx_ImportType(__pyx_t_1, "numpy", "ndarray", sizeof(PyArrayObject), __Pyx_ImportType_CheckSize_Ignore);
if (!__pyx_ptype_5numpy_ndarray) __PYX_ERR(1, 238, __pyx_L1_error)
__pyx_ptype_5numpy_ufunc = __Pyx_ImportType(__pyx_t_1, "numpy", "ufunc", sizeof(PyUFuncObject), __Pyx_ImportType_CheckSize_Ignore);
if (!__pyx_ptype_5numpy_ufunc) __PYX_ERR(1, 764, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_RefNannyFinishContext();
return 0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_RefNannyFinishContext();
return -1;
}
static int __Pyx_modinit_variable_import_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0);
/*--- Variable import code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
static int __Pyx_modinit_function_import_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0);
/*--- Function import code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
#ifndef CYTHON_NO_PYINIT_EXPORT
#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC
#elif PY_MAJOR_VERSION < 3
#ifdef __cplusplus
#define __Pyx_PyMODINIT_FUNC extern "C" void
#else
#define __Pyx_PyMODINIT_FUNC void
#endif
#else
#ifdef __cplusplus
#define __Pyx_PyMODINIT_FUNC extern "C" PyObject *
#else
#define __Pyx_PyMODINIT_FUNC PyObject *
#endif
#endif
#if PY_MAJOR_VERSION < 3
__Pyx_PyMODINIT_FUNC initsoft_nms_cpu(void) CYTHON_SMALL_CODE; /*proto*/
__Pyx_PyMODINIT_FUNC initsoft_nms_cpu(void)
#else
__Pyx_PyMODINIT_FUNC PyInit_soft_nms_cpu(void) CYTHON_SMALL_CODE; /*proto*/
__Pyx_PyMODINIT_FUNC PyInit_soft_nms_cpu(void)
#if CYTHON_PEP489_MULTI_PHASE_INIT
{
return PyModuleDef_Init(&__pyx_moduledef);
}
static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) {
#if PY_VERSION_HEX >= 0x030700A1
static PY_INT64_T main_interpreter_id = -1;
PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp);
if (main_interpreter_id == -1) {
main_interpreter_id = current_id;
return (unlikely(current_id == -1)) ? -1 : 0;
} else if (unlikely(main_interpreter_id != current_id))
#else
static PyInterpreterState *main_interpreter = NULL;
PyInterpreterState *current_interpreter = PyThreadState_Get()->interp;
if (!main_interpreter) {
main_interpreter = current_interpreter;
} else if (unlikely(main_interpreter != current_interpreter))
#endif
{
PyErr_SetString(
PyExc_ImportError,
"Interpreter change detected - this module can only be loaded into one interpreter per process.");
return -1;
}
return 0;
}
static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) {
PyObject *value = PyObject_GetAttrString(spec, from_name);
int result = 0;
if (likely(value)) {
if (allow_none || value != Py_None) {
result = PyDict_SetItemString(moddict, to_name, value);
}
Py_DECREF(value);
} else if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
PyErr_Clear();
} else {
result = -1;
}
return result;
}
static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) {
PyObject *module = NULL, *moddict, *modname;
if (__Pyx_check_single_interpreter())
return NULL;
if (__pyx_m)
return __Pyx_NewRef(__pyx_m);
modname = PyObject_GetAttrString(spec, "name");
if (unlikely(!modname)) goto bad;
module = PyModule_NewObject(modname);
Py_DECREF(modname);
if (unlikely(!module)) goto bad;
moddict = PyModule_GetDict(module);
if (unlikely(!moddict)) goto bad;
if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad;
if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad;
if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad;
if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad;
return module;
bad:
Py_XDECREF(module);
return NULL;
}
static CYTHON_SMALL_CODE int __pyx_pymod_exec_soft_nms_cpu(PyObject *__pyx_pyinit_module)
#endif
#endif
{
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannyDeclarations
#if CYTHON_PEP489_MULTI_PHASE_INIT
if (__pyx_m) {
if (__pyx_m == __pyx_pyinit_module) return 0;
PyErr_SetString(PyExc_RuntimeError, "Module 'soft_nms_cpu' has already been imported. Re-initialisation is not supported.");
return -1;
}
#elif PY_MAJOR_VERSION >= 3
if (__pyx_m) return __Pyx_NewRef(__pyx_m);
#endif
#if CYTHON_REFNANNY
__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny");
if (!__Pyx_RefNanny) {
PyErr_Clear();
__Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny");
if (!__Pyx_RefNanny)
Py_FatalError("failed to import 'refnanny' module");
}
#endif
__Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit_soft_nms_cpu(void)", 0);
if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#ifdef __Pxy_PyFrame_Initialize_Offsets
__Pxy_PyFrame_Initialize_Offsets();
#endif
__pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error)
__pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error)
__pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error)
#ifdef __Pyx_CyFunction_USED
if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
#ifdef __Pyx_FusedFunction_USED
if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
#ifdef __Pyx_Coroutine_USED
if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
#ifdef __Pyx_Generator_USED
if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
#ifdef __Pyx_AsyncGen_USED
if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
#ifdef __Pyx_StopAsyncIteration_USED
if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
/*--- Library function declarations ---*/
/*--- Threads initialization code ---*/
#if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS
#ifdef WITH_THREAD /* Python build with threading support? */
PyEval_InitThreads();
#endif
#endif
/*--- Module creation code ---*/
#if CYTHON_PEP489_MULTI_PHASE_INIT
__pyx_m = __pyx_pyinit_module;
Py_INCREF(__pyx_m);
#else
#if PY_MAJOR_VERSION < 3
__pyx_m = Py_InitModule4("soft_nms_cpu", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m);
#else
__pyx_m = PyModule_Create(&__pyx_moduledef);
#endif
if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
__pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error)
Py_INCREF(__pyx_d);
__pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error)
Py_INCREF(__pyx_b);
__pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error)
Py_INCREF(__pyx_cython_runtime);
if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error);
/*--- Initialize various global constants etc. ---*/
if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT)
if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
if (__pyx_module_is_main_mmdet__ops__nms__soft_nms_cpu) {
if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error)
}
#if PY_MAJOR_VERSION >= 3
{
PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error)
if (!PyDict_GetItemString(modules, "mmdet.ops.nms.soft_nms_cpu")) {
if (unlikely(PyDict_SetItemString(modules, "mmdet.ops.nms.soft_nms_cpu", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error)
}
}
#endif
/*--- Builtin init code ---*/
if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
/*--- Constants init code ---*/
if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
/*--- Global type/function init code ---*/
(void)__Pyx_modinit_global_init_code();
(void)__Pyx_modinit_variable_export_code();
(void)__Pyx_modinit_function_export_code();
(void)__Pyx_modinit_type_init_code();
if (unlikely(__Pyx_modinit_type_import_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error)
(void)__Pyx_modinit_variable_import_code();
(void)__Pyx_modinit_function_import_code();
/*--- Execution code ---*/
#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED)
if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":11
* # cython: language_level=3, boundscheck=False
*
* import numpy as np # <<<<<<<<<<<<<<
* cimport numpy as np
*
*/
__pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 11, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) __PYX_ERR(0, 11, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":22
*
*
* def soft_nms_cpu( # <<<<<<<<<<<<<<
* np.ndarray[float, ndim=2] boxes_in,
* float iou_thr,
*/
__pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_5mmdet_3ops_3nms_12soft_nms_cpu_1soft_nms_cpu, NULL, __pyx_n_s_mmdet_ops_nms_soft_nms_cpu); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 22, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_soft_nms_cpu, __pyx_t_1) < 0) __PYX_ERR(0, 22, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "mmdet/ops/nms/src/soft_nms_cpu.pyx":1
* # ---------------------------------------------------------- # <<<<<<<<<<<<<<
* # Soft-NMS: Improving Object Detection With One Line of Code
* # Copyright (c) University of Maryland, College Park
*/
__pyx_t_1 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "../../../../../../../../../../../../n/home09/achakravarthy/.conda/envs/sipmask/lib/python3.7/site-packages/numpy/__init__.pxd":892
* raise ImportError("numpy.core.umath failed to import")
*
* cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<<
* try:
* _import_umath()
*/
/*--- Wrapped vars code ---*/
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
if (__pyx_m) {
if (__pyx_d) {
__Pyx_AddTraceback("init mmdet.ops.nms.soft_nms_cpu", __pyx_clineno, __pyx_lineno, __pyx_filename);
}
Py_CLEAR(__pyx_m);
} else if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_ImportError, "init mmdet.ops.nms.soft_nms_cpu");
}
__pyx_L0:;
__Pyx_RefNannyFinishContext();
#if CYTHON_PEP489_MULTI_PHASE_INIT
return (__pyx_m != NULL) ? 0 : -1;
#elif PY_MAJOR_VERSION >= 3
return __pyx_m;
#else
return;
#endif
}
/* --- Runtime support code --- */
/* Refnanny */
#if CYTHON_REFNANNY
static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) {
PyObject *m = NULL, *p = NULL;
void *r = NULL;
m = PyImport_ImportModule(modname);
if (!m) goto end;
p = PyObject_GetAttrString(m, "RefNannyAPI");
if (!p) goto end;
r = PyLong_AsVoidPtr(p);
end:
Py_XDECREF(p);
Py_XDECREF(m);
return (__Pyx_RefNannyAPIStruct *)r;
}
#endif
/* PyObjectGetAttrStr */
#if CYTHON_USE_TYPE_SLOTS
static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) {
PyTypeObject* tp = Py_TYPE(obj);
if (likely(tp->tp_getattro))
return tp->tp_getattro(obj, attr_name);
#if PY_MAJOR_VERSION < 3
if (likely(tp->tp_getattr))
return tp->tp_getattr(obj, PyString_AS_STRING(attr_name));
#endif
return PyObject_GetAttr(obj, attr_name);
}
#endif
/* GetBuiltinName */
static PyObject *__Pyx_GetBuiltinName(PyObject *name) {
PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name);
if (unlikely(!result)) {
PyErr_Format(PyExc_NameError,
#if PY_MAJOR_VERSION >= 3
"name '%U' is not defined", name);
#else
"name '%.200s' is not defined", PyString_AS_STRING(name));
#endif
}
return result;
}
/* RaiseArgTupleInvalid */
static void __Pyx_RaiseArgtupleInvalid(
const char* func_name,
int exact,
Py_ssize_t num_min,
Py_ssize_t num_max,
Py_ssize_t num_found)
{
Py_ssize_t num_expected;
const char *more_or_less;
if (num_found < num_min) {
num_expected = num_min;
more_or_less = "at least";
} else {
num_expected = num_max;
more_or_less = "at most";
}
if (exact) {
more_or_less = "exactly";
}
PyErr_Format(PyExc_TypeError,
"%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)",
func_name, more_or_less, num_expected,
(num_expected == 1) ? "" : "s", num_found);
}
/* RaiseDoubleKeywords */
static void __Pyx_RaiseDoubleKeywordsError(
const char* func_name,
PyObject* kw_name)
{
PyErr_Format(PyExc_TypeError,
#if PY_MAJOR_VERSION >= 3
"%s() got multiple values for keyword argument '%U'", func_name, kw_name);
#else
"%s() got multiple values for keyword argument '%s'", func_name,
PyString_AsString(kw_name));
#endif
}
/* ParseKeywords */
static int __Pyx_ParseOptionalKeywords(
PyObject *kwds,
PyObject **argnames[],
PyObject *kwds2,
PyObject *values[],
Py_ssize_t num_pos_args,
const char* function_name)
{
PyObject *key = 0, *value = 0;
Py_ssize_t pos = 0;
PyObject*** name;
PyObject*** first_kw_arg = argnames + num_pos_args;
while (PyDict_Next(kwds, &pos, &key, &value)) {
name = first_kw_arg;
while (*name && (**name != key)) name++;
if (*name) {
values[name-argnames] = value;
continue;
}
name = first_kw_arg;
#if PY_MAJOR_VERSION < 3
if (likely(PyString_Check(key))) {
while (*name) {
if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key))
&& _PyString_Eq(**name, key)) {
values[name-argnames] = value;
break;
}
name++;
}
if (*name) continue;
else {
PyObject*** argname = argnames;
while (argname != first_kw_arg) {
if ((**argname == key) || (
(CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key))
&& _PyString_Eq(**argname, key))) {
goto arg_passed_twice;
}
argname++;
}
}
} else
#endif
if (likely(PyUnicode_Check(key))) {
while (*name) {
int cmp = (**name == key) ? 0 :
#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3
(__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 :
#endif
PyUnicode_Compare(**name, key);
if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad;
if (cmp == 0) {
values[name-argnames] = value;
break;
}
name++;
}
if (*name) continue;
else {
PyObject*** argname = argnames;
while (argname != first_kw_arg) {
int cmp = (**argname == key) ? 0 :
#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3
(__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 :
#endif
PyUnicode_Compare(**argname, key);
if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad;
if (cmp == 0) goto arg_passed_twice;
argname++;
}
}
} else
goto invalid_keyword_type;
if (kwds2) {
if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad;
} else {
goto invalid_keyword;
}
}
return 0;
arg_passed_twice:
__Pyx_RaiseDoubleKeywordsError(function_name, key);
goto bad;
invalid_keyword_type:
PyErr_Format(PyExc_TypeError,
"%.200s() keywords must be strings", function_name);
goto bad;
invalid_keyword:
PyErr_Format(PyExc_TypeError,
#if PY_MAJOR_VERSION < 3
"%.200s() got an unexpected keyword argument '%.200s'",
function_name, PyString_AsString(key));
#else
"%s() got an unexpected keyword argument '%U'",
function_name, key);
#endif
bad:
return -1;
}
/* ArgTypeTest */
static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact)
{
if (unlikely(!type)) {
PyErr_SetString(PyExc_SystemError, "Missing type object");
return 0;
}
else if (exact) {
#if PY_MAJOR_VERSION == 2
if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1;
#endif
}
else {
if (likely(__Pyx_TypeCheck(obj, type))) return 1;
}
PyErr_Format(PyExc_TypeError,
"Argument '%.200s' has incorrect type (expected %.200s, got %.200s)",
name, type->tp_name, Py_TYPE(obj)->tp_name);
return 0;
}
/* IsLittleEndian */
static CYTHON_INLINE int __Pyx_Is_Little_Endian(void)
{
union {
uint32_t u32;
uint8_t u8[4];
} S;
S.u32 = 0x01020304;
return S.u8[0] == 4;
}
/* BufferFormatCheck */
static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx,
__Pyx_BufFmt_StackElem* stack,
__Pyx_TypeInfo* type) {
stack[0].field = &ctx->root;
stack[0].parent_offset = 0;
ctx->root.type = type;
ctx->root.name = "buffer dtype";
ctx->root.offset = 0;
ctx->head = stack;
ctx->head->field = &ctx->root;
ctx->fmt_offset = 0;
ctx->head->parent_offset = 0;
ctx->new_packmode = '@';
ctx->enc_packmode = '@';
ctx->new_count = 1;
ctx->enc_count = 0;
ctx->enc_type = 0;
ctx->is_complex = 0;
ctx->is_valid_array = 0;
ctx->struct_alignment = 0;
while (type->typegroup == 'S') {
++ctx->head;
ctx->head->field = type->fields;
ctx->head->parent_offset = 0;
type = type->fields->type;
}
}
static int __Pyx_BufFmt_ParseNumber(const char** ts) {
int count;
const char* t = *ts;
if (*t < '0' || *t > '9') {
return -1;
} else {
count = *t++ - '0';
while (*t >= '0' && *t <= '9') {
count *= 10;
count += *t++ - '0';
}
}
*ts = t;
return count;
}
static int __Pyx_BufFmt_ExpectNumber(const char **ts) {
int number = __Pyx_BufFmt_ParseNumber(ts);
if (number == -1)
PyErr_Format(PyExc_ValueError,\
"Does not understand character buffer dtype format string ('%c')", **ts);
return number;
}
static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) {
PyErr_Format(PyExc_ValueError,
"Unexpected format string character: '%c'", ch);
}
static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) {
switch (ch) {
case '?': return "'bool'";
case 'c': return "'char'";
case 'b': return "'signed char'";
case 'B': return "'unsigned char'";
case 'h': return "'short'";
case 'H': return "'unsigned short'";
case 'i': return "'int'";
case 'I': return "'unsigned int'";
case 'l': return "'long'";
case 'L': return "'unsigned long'";
case 'q': return "'long long'";
case 'Q': return "'unsigned long long'";
case 'f': return (is_complex ? "'complex float'" : "'float'");
case 'd': return (is_complex ? "'complex double'" : "'double'");
case 'g': return (is_complex ? "'complex long double'" : "'long double'");
case 'T': return "a struct";
case 'O': return "Python object";
case 'P': return "a pointer";
case 's': case 'p': return "a string";
case 0: return "end";
default: return "unparseable format string";
}
}
static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) {
switch (ch) {
case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1;
case 'h': case 'H': return 2;
case 'i': case 'I': case 'l': case 'L': return 4;
case 'q': case 'Q': return 8;
case 'f': return (is_complex ? 8 : 4);
case 'd': return (is_complex ? 16 : 8);
case 'g': {
PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g')..");
return 0;
}
case 'O': case 'P': return sizeof(void*);
default:
__Pyx_BufFmt_RaiseUnexpectedChar(ch);
return 0;
}
}
static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) {
switch (ch) {
case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1;
case 'h': case 'H': return sizeof(short);
case 'i': case 'I': return sizeof(int);
case 'l': case 'L': return sizeof(long);
#ifdef HAVE_LONG_LONG
case 'q': case 'Q': return sizeof(PY_LONG_LONG);
#endif
case 'f': return sizeof(float) * (is_complex ? 2 : 1);
case 'd': return sizeof(double) * (is_complex ? 2 : 1);
case 'g': return sizeof(long double) * (is_complex ? 2 : 1);
case 'O': case 'P': return sizeof(void*);
default: {
__Pyx_BufFmt_RaiseUnexpectedChar(ch);
return 0;
}
}
}
typedef struct { char c; short x; } __Pyx_st_short;
typedef struct { char c; int x; } __Pyx_st_int;
typedef struct { char c; long x; } __Pyx_st_long;
typedef struct { char c; float x; } __Pyx_st_float;
typedef struct { char c; double x; } __Pyx_st_double;
typedef struct { char c; long double x; } __Pyx_st_longdouble;
typedef struct { char c; void *x; } __Pyx_st_void_p;
#ifdef HAVE_LONG_LONG
typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong;
#endif
static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) {
switch (ch) {
case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1;
case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short);
case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int);
case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long);
#ifdef HAVE_LONG_LONG
case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG);
#endif
case 'f': return sizeof(__Pyx_st_float) - sizeof(float);
case 'd': return sizeof(__Pyx_st_double) - sizeof(double);
case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double);
case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*);
default:
__Pyx_BufFmt_RaiseUnexpectedChar(ch);
return 0;
}
}
/* These are for computing the padding at the end of the struct to align
on the first member of the struct. This will probably the same as above,
but we don't have any guarantees.
*/
typedef struct { short x; char c; } __Pyx_pad_short;
typedef struct { int x; char c; } __Pyx_pad_int;
typedef struct { long x; char c; } __Pyx_pad_long;
typedef struct { float x; char c; } __Pyx_pad_float;
typedef struct { double x; char c; } __Pyx_pad_double;
typedef struct { long double x; char c; } __Pyx_pad_longdouble;
typedef struct { void *x; char c; } __Pyx_pad_void_p;
#ifdef HAVE_LONG_LONG
typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong;
#endif
static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) {
switch (ch) {
case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1;
case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short);
case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int);
case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long);
#ifdef HAVE_LONG_LONG
case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG);
#endif
case 'f': return sizeof(__Pyx_pad_float) - sizeof(float);
case 'd': return sizeof(__Pyx_pad_double) - sizeof(double);
case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double);
case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*);
default:
__Pyx_BufFmt_RaiseUnexpectedChar(ch);
return 0;
}
}
static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) {
switch (ch) {
case 'c':
return 'H';
case 'b': case 'h': case 'i':
case 'l': case 'q': case 's': case 'p':
return 'I';
case '?': case 'B': case 'H': case 'I': case 'L': case 'Q':
return 'U';
case 'f': case 'd': case 'g':
return (is_complex ? 'C' : 'R');
case 'O':
return 'O';
case 'P':
return 'P';
default: {
__Pyx_BufFmt_RaiseUnexpectedChar(ch);
return 0;
}
}
}
static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) {
if (ctx->head == NULL || ctx->head->field == &ctx->root) {
const char* expected;
const char* quote;
if (ctx->head == NULL) {
expected = "end";
quote = "";
} else {
expected = ctx->head->field->type->name;
quote = "'";
}
PyErr_Format(PyExc_ValueError,
"Buffer dtype mismatch, expected %s%s%s but got %s",
quote, expected, quote,
__Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex));
} else {
__Pyx_StructField* field = ctx->head->field;
__Pyx_StructField* parent = (ctx->head - 1)->field;
PyErr_Format(PyExc_ValueError,
"Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'",
field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex),
parent->type->name, field->name);
}
}
static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) {
char group;
size_t size, offset, arraysize = 1;
if (ctx->enc_type == 0) return 0;
if (ctx->head->field->type->arraysize[0]) {
int i, ndim = 0;
if (ctx->enc_type == 's' || ctx->enc_type == 'p') {
ctx->is_valid_array = ctx->head->field->type->ndim == 1;
ndim = 1;
if (ctx->enc_count != ctx->head->field->type->arraysize[0]) {
PyErr_Format(PyExc_ValueError,
"Expected a dimension of size %zu, got %zu",
ctx->head->field->type->arraysize[0], ctx->enc_count);
return -1;
}
}
if (!ctx->is_valid_array) {
PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d",
ctx->head->field->type->ndim, ndim);
return -1;
}
for (i = 0; i < ctx->head->field->type->ndim; i++) {
arraysize *= ctx->head->field->type->arraysize[i];
}
ctx->is_valid_array = 0;
ctx->enc_count = 1;
}
group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex);
do {
__Pyx_StructField* field = ctx->head->field;
__Pyx_TypeInfo* type = field->type;
if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') {
size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex);
} else {
size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex);
}
if (ctx->enc_packmode == '@') {
size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex);
size_t align_mod_offset;
if (align_at == 0) return -1;
align_mod_offset = ctx->fmt_offset % align_at;
if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset;
if (ctx->struct_alignment == 0)
ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type,
ctx->is_complex);
}
if (type->size != size || type->typegroup != group) {
if (type->typegroup == 'C' && type->fields != NULL) {
size_t parent_offset = ctx->head->parent_offset + field->offset;
++ctx->head;
ctx->head->field = type->fields;
ctx->head->parent_offset = parent_offset;
continue;
}
if ((type->typegroup == 'H' || group == 'H') && type->size == size) {
} else {
__Pyx_BufFmt_RaiseExpected(ctx);
return -1;
}
}
offset = ctx->head->parent_offset + field->offset;
if (ctx->fmt_offset != offset) {
PyErr_Format(PyExc_ValueError,
"Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected",
(Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset);
return -1;
}
ctx->fmt_offset += size;
if (arraysize)
ctx->fmt_offset += (arraysize - 1) * size;
--ctx->enc_count;
while (1) {
if (field == &ctx->root) {
ctx->head = NULL;
if (ctx->enc_count != 0) {
__Pyx_BufFmt_RaiseExpected(ctx);
return -1;
}
break;
}
ctx->head->field = ++field;
if (field->type == NULL) {
--ctx->head;
field = ctx->head->field;
continue;
} else if (field->type->typegroup == 'S') {
size_t parent_offset = ctx->head->parent_offset + field->offset;
if (field->type->fields->type == NULL) continue;
field = field->type->fields;
++ctx->head;
ctx->head->field = field;
ctx->head->parent_offset = parent_offset;
break;
} else {
break;
}
}
} while (ctx->enc_count);
ctx->enc_type = 0;
ctx->is_complex = 0;
return 0;
}
static PyObject *
__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp)
{
const char *ts = *tsp;
int i = 0, number, ndim;
++ts;
if (ctx->new_count != 1) {
PyErr_SetString(PyExc_ValueError,
"Cannot handle repeated arrays in format string");
return NULL;
}
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
ndim = ctx->head->field->type->ndim;
while (*ts && *ts != ')') {
switch (*ts) {
case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue;
default: break;
}
number = __Pyx_BufFmt_ExpectNumber(&ts);
if (number == -1) return NULL;
if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i])
return PyErr_Format(PyExc_ValueError,
"Expected a dimension of size %zu, got %d",
ctx->head->field->type->arraysize[i], number);
if (*ts != ',' && *ts != ')')
return PyErr_Format(PyExc_ValueError,
"Expected a comma in format string, got '%c'", *ts);
if (*ts == ',') ts++;
i++;
}
if (i != ndim)
return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d",
ctx->head->field->type->ndim, i);
if (!*ts) {
PyErr_SetString(PyExc_ValueError,
"Unexpected end of format string, expected ')'");
return NULL;
}
ctx->is_valid_array = 1;
ctx->new_count = 1;
*tsp = ++ts;
return Py_None;
}
static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) {
int got_Z = 0;
while (1) {
switch(*ts) {
case 0:
if (ctx->enc_type != 0 && ctx->head == NULL) {
__Pyx_BufFmt_RaiseExpected(ctx);
return NULL;
}
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
if (ctx->head != NULL) {
__Pyx_BufFmt_RaiseExpected(ctx);
return NULL;
}
return ts;
case ' ':
case '\r':
case '\n':
++ts;
break;
case '<':
if (!__Pyx_Is_Little_Endian()) {
PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler");
return NULL;
}
ctx->new_packmode = '=';
++ts;
break;
case '>':
case '!':
if (__Pyx_Is_Little_Endian()) {
PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler");
return NULL;
}
ctx->new_packmode = '=';
++ts;
break;
case '=':
case '@':
case '^':
ctx->new_packmode = *ts++;
break;
case 'T':
{
const char* ts_after_sub;
size_t i, struct_count = ctx->new_count;
size_t struct_alignment = ctx->struct_alignment;
ctx->new_count = 1;
++ts;
if (*ts != '{') {
PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'");
return NULL;
}
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
ctx->enc_type = 0;
ctx->enc_count = 0;
ctx->struct_alignment = 0;
++ts;
ts_after_sub = ts;
for (i = 0; i != struct_count; ++i) {
ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts);
if (!ts_after_sub) return NULL;
}
ts = ts_after_sub;
if (struct_alignment) ctx->struct_alignment = struct_alignment;
}
break;
case '}':
{
size_t alignment = ctx->struct_alignment;
++ts;
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
ctx->enc_type = 0;
if (alignment && ctx->fmt_offset % alignment) {
ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment);
}
}
return ts;
case 'x':
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
ctx->fmt_offset += ctx->new_count;
ctx->new_count = 1;
ctx->enc_count = 0;
ctx->enc_type = 0;
ctx->enc_packmode = ctx->new_packmode;
++ts;
break;
case 'Z':
got_Z = 1;
++ts;
if (*ts != 'f' && *ts != 'd' && *ts != 'g') {
__Pyx_BufFmt_RaiseUnexpectedChar('Z');
return NULL;
}
CYTHON_FALLTHROUGH;
case '?': case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I':
case 'l': case 'L': case 'q': case 'Q':
case 'f': case 'd': case 'g':
case 'O': case 'p':
if ((ctx->enc_type == *ts) && (got_Z == ctx->is_complex) &&
(ctx->enc_packmode == ctx->new_packmode) && (!ctx->is_valid_array)) {
ctx->enc_count += ctx->new_count;
ctx->new_count = 1;
got_Z = 0;
++ts;
break;
}
CYTHON_FALLTHROUGH;
case 's':
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
ctx->enc_count = ctx->new_count;
ctx->enc_packmode = ctx->new_packmode;
ctx->enc_type = *ts;
ctx->is_complex = got_Z;
++ts;
ctx->new_count = 1;
got_Z = 0;
break;
case ':':
++ts;
while(*ts != ':') ++ts;
++ts;
break;
case '(':
if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL;
break;
default:
{
int number = __Pyx_BufFmt_ExpectNumber(&ts);
if (number == -1) return NULL;
ctx->new_count = (size_t)number;
}
}
}
}
/* BufferGetAndValidate */
static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) {
if (unlikely(info->buf == NULL)) return;
if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL;
__Pyx_ReleaseBuffer(info);
}
static void __Pyx_ZeroBuffer(Py_buffer* buf) {
buf->buf = NULL;
buf->obj = NULL;
buf->strides = __Pyx_zeros;
buf->shape = __Pyx_zeros;
buf->suboffsets = __Pyx_minusones;
}
static int __Pyx__GetBufferAndValidate(
Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags,
int nd, int cast, __Pyx_BufFmt_StackElem* stack)
{
buf->buf = NULL;
if (unlikely(__Pyx_GetBuffer(obj, buf, flags) == -1)) {
__Pyx_ZeroBuffer(buf);
return -1;
}
if (unlikely(buf->ndim != nd)) {
PyErr_Format(PyExc_ValueError,
"Buffer has wrong number of dimensions (expected %d, got %d)",
nd, buf->ndim);
goto fail;
}
if (!cast) {
__Pyx_BufFmt_Context ctx;
__Pyx_BufFmt_Init(&ctx, stack, dtype);
if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail;
}
if (unlikely((size_t)buf->itemsize != dtype->size)) {
PyErr_Format(PyExc_ValueError,
"Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)",
buf->itemsize, (buf->itemsize > 1) ? "s" : "",
dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : "");
goto fail;
}
if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones;
return 0;
fail:;
__Pyx_SafeReleaseBuffer(buf);
return -1;
}
/* PyFunctionFastCall */
#if CYTHON_FAST_PYCALL
static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na,
PyObject *globals) {
PyFrameObject *f;
PyThreadState *tstate = __Pyx_PyThreadState_Current;
PyObject **fastlocals;
Py_ssize_t i;
PyObject *result;
assert(globals != NULL);
/* XXX Perhaps we should create a specialized
PyFrame_New() that doesn't take locals, but does
take builtins without sanity checking them.
*/
assert(tstate != NULL);
f = PyFrame_New(tstate, co, globals, NULL);
if (f == NULL) {
return NULL;
}
fastlocals = __Pyx_PyFrame_GetLocalsplus(f);
for (i = 0; i < na; i++) {
Py_INCREF(*args);
fastlocals[i] = *args++;
}
result = PyEval_EvalFrameEx(f,0);
++tstate->recursion_depth;
Py_DECREF(f);
--tstate->recursion_depth;
return result;
}
#if 1 || PY_VERSION_HEX < 0x030600B1
static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) {
PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
PyObject *globals = PyFunction_GET_GLOBALS(func);
PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
PyObject *closure;
#if PY_MAJOR_VERSION >= 3
PyObject *kwdefs;
#endif
PyObject *kwtuple, **k;
PyObject **d;
Py_ssize_t nd;
Py_ssize_t nk;
PyObject *result;
assert(kwargs == NULL || PyDict_Check(kwargs));
nk = kwargs ? PyDict_Size(kwargs) : 0;
if (Py_EnterRecursiveCall((char*)" while calling a Python object")) {
return NULL;
}
if (
#if PY_MAJOR_VERSION >= 3
co->co_kwonlyargcount == 0 &&
#endif
likely(kwargs == NULL || nk == 0) &&
co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
if (argdefs == NULL && co->co_argcount == nargs) {
result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals);
goto done;
}
else if (nargs == 0 && argdefs != NULL
&& co->co_argcount == Py_SIZE(argdefs)) {
/* function called with no arguments, but all parameters have
a default value: use default values as arguments .*/
args = &PyTuple_GET_ITEM(argdefs, 0);
result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals);
goto done;
}
}
if (kwargs != NULL) {
Py_ssize_t pos, i;
kwtuple = PyTuple_New(2 * nk);
if (kwtuple == NULL) {
result = NULL;
goto done;
}
k = &PyTuple_GET_ITEM(kwtuple, 0);
pos = i = 0;
while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) {
Py_INCREF(k[i]);
Py_INCREF(k[i+1]);
i += 2;
}
nk = i / 2;
}
else {
kwtuple = NULL;
k = NULL;
}
closure = PyFunction_GET_CLOSURE(func);
#if PY_MAJOR_VERSION >= 3
kwdefs = PyFunction_GET_KW_DEFAULTS(func);
#endif
if (argdefs != NULL) {
d = &PyTuple_GET_ITEM(argdefs, 0);
nd = Py_SIZE(argdefs);
}
else {
d = NULL;
nd = 0;
}
#if PY_MAJOR_VERSION >= 3
result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL,
args, (int)nargs,
k, (int)nk,
d, (int)nd, kwdefs, closure);
#else
result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL,
args, (int)nargs,
k, (int)nk,
d, (int)nd, closure);
#endif
Py_XDECREF(kwtuple);
done:
Py_LeaveRecursiveCall();
return result;
}
#endif
#endif
/* PyObjectCall */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) {
PyObject *result;
ternaryfunc call = func->ob_type->tp_call;
if (unlikely(!call))
return PyObject_Call(func, arg, kw);
if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object")))
return NULL;
result = (*call)(func, arg, kw);
Py_LeaveRecursiveCall();
if (unlikely(!result) && unlikely(!PyErr_Occurred())) {
PyErr_SetString(
PyExc_SystemError,
"NULL result without error in PyObject_Call");
}
return result;
}
#endif
/* PyObjectCallMethO */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) {
PyObject *self, *result;
PyCFunction cfunc;
cfunc = PyCFunction_GET_FUNCTION(func);
self = PyCFunction_GET_SELF(func);
if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object")))
return NULL;
result = cfunc(self, arg);
Py_LeaveRecursiveCall();
if (unlikely(!result) && unlikely(!PyErr_Occurred())) {
PyErr_SetString(
PyExc_SystemError,
"NULL result without error in PyObject_Call");
}
return result;
}
#endif
/* PyObjectCallNoArg */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) {
#if CYTHON_FAST_PYCALL
if (PyFunction_Check(func)) {
return __Pyx_PyFunction_FastCall(func, NULL, 0);
}
#endif
#ifdef __Pyx_CyFunction_USED
if (likely(PyCFunction_Check(func) || __Pyx_CyFunction_Check(func)))
#else
if (likely(PyCFunction_Check(func)))
#endif
{
if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) {
return __Pyx_PyObject_CallMethO(func, NULL);
}
}
return __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL);
}
#endif
/* PyCFunctionFastCall */
#if CYTHON_FAST_PYCCALL
static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) {
PyCFunctionObject *func = (PyCFunctionObject*)func_obj;
PyCFunction meth = PyCFunction_GET_FUNCTION(func);
PyObject *self = PyCFunction_GET_SELF(func);
int flags = PyCFunction_GET_FLAGS(func);
assert(PyCFunction_Check(func));
assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS)));
assert(nargs >= 0);
assert(nargs == 0 || args != NULL);
/* _PyCFunction_FastCallDict() must not be called with an exception set,
because it may clear it (directly or indirectly) and so the
caller loses its exception */
assert(!PyErr_Occurred());
if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) {
return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL);
} else {
return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs);
}
}
#endif
/* PyObjectCallOneArg */
#if CYTHON_COMPILING_IN_CPYTHON
static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) {
PyObject *result;
PyObject *args = PyTuple_New(1);
if (unlikely(!args)) return NULL;
Py_INCREF(arg);
PyTuple_SET_ITEM(args, 0, arg);
result = __Pyx_PyObject_Call(func, args, NULL);
Py_DECREF(args);
return result;
}
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) {
#if CYTHON_FAST_PYCALL
if (PyFunction_Check(func)) {
return __Pyx_PyFunction_FastCall(func, &arg, 1);
}
#endif
if (likely(PyCFunction_Check(func))) {
if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) {
return __Pyx_PyObject_CallMethO(func, arg);
#if CYTHON_FAST_PYCCALL
} else if (PyCFunction_GET_FLAGS(func) & METH_FASTCALL) {
return __Pyx_PyCFunction_FastCall(func, &arg, 1);
#endif
}
}
return __Pyx__PyObject_CallOneArg(func, arg);
}
#else
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) {
PyObject *result;
PyObject *args = PyTuple_Pack(1, arg);
if (unlikely(!args)) return NULL;
result = __Pyx_PyObject_Call(func, args, NULL);
Py_DECREF(args);
return result;
}
#endif
/* GetItemInt */
static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) {
PyObject *r;
if (!j) return NULL;
r = PyObject_GetItem(o, j);
Py_DECREF(j);
return r;
}
static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i,
CYTHON_NCP_UNUSED int wraparound,
CYTHON_NCP_UNUSED int boundscheck) {
#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS
Py_ssize_t wrapped_i = i;
if (wraparound & unlikely(i < 0)) {
wrapped_i += PyList_GET_SIZE(o);
}
if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) {
PyObject *r = PyList_GET_ITEM(o, wrapped_i);
Py_INCREF(r);
return r;
}
return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i));
#else
return PySequence_GetItem(o, i);
#endif
}
static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i,
CYTHON_NCP_UNUSED int wraparound,
CYTHON_NCP_UNUSED int boundscheck) {
#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS
Py_ssize_t wrapped_i = i;
if (wraparound & unlikely(i < 0)) {
wrapped_i += PyTuple_GET_SIZE(o);
}
if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) {
PyObject *r = PyTuple_GET_ITEM(o, wrapped_i);
Py_INCREF(r);
return r;
}
return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i));
#else
return PySequence_GetItem(o, i);
#endif
}
static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list,
CYTHON_NCP_UNUSED int wraparound,
CYTHON_NCP_UNUSED int boundscheck) {
#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS
if (is_list || PyList_CheckExact(o)) {
Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o);
if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) {
PyObject *r = PyList_GET_ITEM(o, n);
Py_INCREF(r);
return r;
}
}
else if (PyTuple_CheckExact(o)) {
Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o);
if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) {
PyObject *r = PyTuple_GET_ITEM(o, n);
Py_INCREF(r);
return r;
}
} else {
PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
if (likely(m && m->sq_item)) {
if (wraparound && unlikely(i < 0) && likely(m->sq_length)) {
Py_ssize_t l = m->sq_length(o);
if (likely(l >= 0)) {
i += l;
} else {
if (!PyErr_ExceptionMatches(PyExc_OverflowError))
return NULL;
PyErr_Clear();
}
}
return m->sq_item(o, i);
}
}
#else
if (is_list || PySequence_Check(o)) {
return PySequence_GetItem(o, i);
}
#endif
return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i));
}
/* PyDictVersioning */
#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS
static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) {
PyObject *dict = Py_TYPE(obj)->tp_dict;
return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0;
}
static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) {
PyObject **dictptr = NULL;
Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset;
if (offset) {
#if CYTHON_COMPILING_IN_CPYTHON
dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj);
#else
dictptr = _PyObject_GetDictPtr(obj);
#endif
}
return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0;
}
static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) {
PyObject *dict = Py_TYPE(obj)->tp_dict;
if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict)))
return 0;
return obj_dict_version == __Pyx_get_object_dict_version(obj);
}
#endif
/* GetModuleGlobalName */
#if CYTHON_USE_DICT_VERSIONS
static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value)
#else
static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name)
#endif
{
PyObject *result;
#if !CYTHON_AVOID_BORROWED_REFS
#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1
result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash);
__PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version)
if (likely(result)) {
return __Pyx_NewRef(result);
} else if (unlikely(PyErr_Occurred())) {
return NULL;
}
#else
result = PyDict_GetItem(__pyx_d, name);
__PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version)
if (likely(result)) {
return __Pyx_NewRef(result);
}
#endif
#else
result = PyObject_GetItem(__pyx_d, name);
__PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version)
if (likely(result)) {
return __Pyx_NewRef(result);
}
PyErr_Clear();
#endif
return __Pyx_GetBuiltinName(name);
}
/* PyObjectCall2Args */
static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) {
PyObject *args, *result = NULL;
#if CYTHON_FAST_PYCALL
if (PyFunction_Check(function)) {
PyObject *args[2] = {arg1, arg2};
return __Pyx_PyFunction_FastCall(function, args, 2);
}
#endif
#if CYTHON_FAST_PYCCALL
if (__Pyx_PyFastCFunction_Check(function)) {
PyObject *args[2] = {arg1, arg2};
return __Pyx_PyCFunction_FastCall(function, args, 2);
}
#endif
args = PyTuple_New(2);
if (unlikely(!args)) goto done;
Py_INCREF(arg1);
PyTuple_SET_ITEM(args, 0, arg1);
Py_INCREF(arg2);
PyTuple_SET_ITEM(args, 1, arg2);
Py_INCREF(function);
result = __Pyx_PyObject_Call(function, args, NULL);
Py_DECREF(args);
Py_DECREF(function);
done:
return result;
}
/* ObjectGetItem */
#if CYTHON_USE_TYPE_SLOTS
static PyObject *__Pyx_PyObject_GetIndex(PyObject *obj, PyObject* index) {
PyObject *runerr;
Py_ssize_t key_value;
PySequenceMethods *m = Py_TYPE(obj)->tp_as_sequence;
if (unlikely(!(m && m->sq_item))) {
PyErr_Format(PyExc_TypeError, "'%.200s' object is not subscriptable", Py_TYPE(obj)->tp_name);
return NULL;
}
key_value = __Pyx_PyIndex_AsSsize_t(index);
if (likely(key_value != -1 || !(runerr = PyErr_Occurred()))) {
return __Pyx_GetItemInt_Fast(obj, key_value, 0, 1, 1);
}
if (PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) {
PyErr_Clear();
PyErr_Format(PyExc_IndexError, "cannot fit '%.200s' into an index-sized integer", Py_TYPE(index)->tp_name);
}
return NULL;
}
static PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key) {
PyMappingMethods *m = Py_TYPE(obj)->tp_as_mapping;
if (likely(m && m->mp_subscript)) {
return m->mp_subscript(obj, key);
}
return __Pyx_PyObject_GetIndex(obj, key);
}
#endif
/* PyIntBinop */
#if !CYTHON_COMPILING_IN_PYPY
static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, int inplace, int zerodivision_check) {
(void)inplace;
(void)zerodivision_check;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_CheckExact(op1))) {
const long b = intval;
long x;
long a = PyInt_AS_LONG(op1);
x = (long)((unsigned long)a + b);
if (likely((x^a) >= 0 || (x^b) >= 0))
return PyInt_FromLong(x);
return PyLong_Type.tp_as_number->nb_add(op1, op2);
}
#endif
#if CYTHON_USE_PYLONG_INTERNALS
if (likely(PyLong_CheckExact(op1))) {
const long b = intval;
long a, x;
#ifdef HAVE_LONG_LONG
const PY_LONG_LONG llb = intval;
PY_LONG_LONG lla, llx;
#endif
const digit* digits = ((PyLongObject*)op1)->ob_digit;
const Py_ssize_t size = Py_SIZE(op1);
if (likely(__Pyx_sst_abs(size) <= 1)) {
a = likely(size) ? digits[0] : 0;
if (size == -1) a = -a;
} else {
switch (size) {
case -2:
if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]));
break;
#ifdef HAVE_LONG_LONG
} else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) {
lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0]));
goto long_long;
#endif
}
CYTHON_FALLTHROUGH;
case 2:
if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]));
break;
#ifdef HAVE_LONG_LONG
} else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) {
lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0]));
goto long_long;
#endif
}
CYTHON_FALLTHROUGH;
case -3:
if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]));
break;
#ifdef HAVE_LONG_LONG
} else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) {
lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0]));
goto long_long;
#endif
}
CYTHON_FALLTHROUGH;
case 3:
if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]));
break;
#ifdef HAVE_LONG_LONG
} else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) {
lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0]));
goto long_long;
#endif
}
CYTHON_FALLTHROUGH;
case -4:
if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) {
a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]));
break;
#ifdef HAVE_LONG_LONG
} else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) {
lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0]));
goto long_long;
#endif
}
CYTHON_FALLTHROUGH;
case 4:
if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) {
a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]));
break;
#ifdef HAVE_LONG_LONG
} else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) {
lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0]));
goto long_long;
#endif
}
CYTHON_FALLTHROUGH;
default: return PyLong_Type.tp_as_number->nb_add(op1, op2);
}
}
x = a + b;
return PyLong_FromLong(x);
#ifdef HAVE_LONG_LONG
long_long:
llx = lla + llb;
return PyLong_FromLongLong(llx);
#endif
}
#endif
if (PyFloat_CheckExact(op1)) {
const long b = intval;
double a = PyFloat_AS_DOUBLE(op1);
double result;
PyFPE_START_PROTECT("add", return NULL)
result = ((double)a) + (double)b;
PyFPE_END_PROTECT(result)
return PyFloat_FromDouble(result);
}
return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2);
}
#endif
/* SetItemInt */
static int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) {
int r;
if (!j) return -1;
r = PyObject_SetItem(o, j, v);
Py_DECREF(j);
return r;
}
static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, int is_list,
CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) {
#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS
if (is_list || PyList_CheckExact(o)) {
Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o));
if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o)))) {
PyObject* old = PyList_GET_ITEM(o, n);
Py_INCREF(v);
PyList_SET_ITEM(o, n, v);
Py_DECREF(old);
return 1;
}
} else {
PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
if (likely(m && m->sq_ass_item)) {
if (wraparound && unlikely(i < 0) && likely(m->sq_length)) {
Py_ssize_t l = m->sq_length(o);
if (likely(l >= 0)) {
i += l;
} else {
if (!PyErr_ExceptionMatches(PyExc_OverflowError))
return -1;
PyErr_Clear();
}
}
return m->sq_ass_item(o, i, v);
}
}
#else
#if CYTHON_COMPILING_IN_PYPY
if (is_list || (PySequence_Check(o) && !PyDict_Check(o)))
#else
if (is_list || PySequence_Check(o))
#endif
{
return PySequence_SetItem(o, i, v);
}
#endif
return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v);
}
/* SliceObject */
static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice(PyObject* obj,
Py_ssize_t cstart, Py_ssize_t cstop,
PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice,
int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) {
#if CYTHON_USE_TYPE_SLOTS
PyMappingMethods* mp;
#if PY_MAJOR_VERSION < 3
PySequenceMethods* ms = Py_TYPE(obj)->tp_as_sequence;
if (likely(ms && ms->sq_slice)) {
if (!has_cstart) {
if (_py_start && (*_py_start != Py_None)) {
cstart = __Pyx_PyIndex_AsSsize_t(*_py_start);
if ((cstart == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad;
} else
cstart = 0;
}
if (!has_cstop) {
if (_py_stop && (*_py_stop != Py_None)) {
cstop = __Pyx_PyIndex_AsSsize_t(*_py_stop);
if ((cstop == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad;
} else
cstop = PY_SSIZE_T_MAX;
}
if (wraparound && unlikely((cstart < 0) | (cstop < 0)) && likely(ms->sq_length)) {
Py_ssize_t l = ms->sq_length(obj);
if (likely(l >= 0)) {
if (cstop < 0) {
cstop += l;
if (cstop < 0) cstop = 0;
}
if (cstart < 0) {
cstart += l;
if (cstart < 0) cstart = 0;
}
} else {
if (!PyErr_ExceptionMatches(PyExc_OverflowError))
goto bad;
PyErr_Clear();
}
}
return ms->sq_slice(obj, cstart, cstop);
}
#endif
mp = Py_TYPE(obj)->tp_as_mapping;
if (likely(mp && mp->mp_subscript))
#endif
{
PyObject* result;
PyObject *py_slice, *py_start, *py_stop;
if (_py_slice) {
py_slice = *_py_slice;
} else {
PyObject* owned_start = NULL;
PyObject* owned_stop = NULL;
if (_py_start) {
py_start = *_py_start;
} else {
if (has_cstart) {
owned_start = py_start = PyInt_FromSsize_t(cstart);
if (unlikely(!py_start)) goto bad;
} else
py_start = Py_None;
}
if (_py_stop) {
py_stop = *_py_stop;
} else {
if (has_cstop) {
owned_stop = py_stop = PyInt_FromSsize_t(cstop);
if (unlikely(!py_stop)) {
Py_XDECREF(owned_start);
goto bad;
}
} else
py_stop = Py_None;
}
py_slice = PySlice_New(py_start, py_stop, Py_None);
Py_XDECREF(owned_start);
Py_XDECREF(owned_stop);
if (unlikely(!py_slice)) goto bad;
}
#if CYTHON_USE_TYPE_SLOTS
result = mp->mp_subscript(obj, py_slice);
#else
result = PyObject_GetItem(obj, py_slice);
#endif
if (!_py_slice) {
Py_DECREF(py_slice);
}
return result;
}
PyErr_Format(PyExc_TypeError,
"'%.200s' object is unsliceable", Py_TYPE(obj)->tp_name);
bad:
return NULL;
}
/* PyErrFetchRestore */
#if CYTHON_FAST_THREAD_STATE
static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) {
PyObject *tmp_type, *tmp_value, *tmp_tb;
tmp_type = tstate->curexc_type;
tmp_value = tstate->curexc_value;
tmp_tb = tstate->curexc_traceback;
tstate->curexc_type = type;
tstate->curexc_value = value;
tstate->curexc_traceback = tb;
Py_XDECREF(tmp_type);
Py_XDECREF(tmp_value);
Py_XDECREF(tmp_tb);
}
static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) {
*type = tstate->curexc_type;
*value = tstate->curexc_value;
*tb = tstate->curexc_traceback;
tstate->curexc_type = 0;
tstate->curexc_value = 0;
tstate->curexc_traceback = 0;
}
#endif
/* GetTopmostException */
#if CYTHON_USE_EXC_INFO_STACK
static _PyErr_StackItem *
__Pyx_PyErr_GetTopmostException(PyThreadState *tstate)
{
_PyErr_StackItem *exc_info = tstate->exc_info;
while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) &&
exc_info->previous_item != NULL)
{
exc_info = exc_info->previous_item;
}
return exc_info;
}
#endif
/* SaveResetException */
#if CYTHON_FAST_THREAD_STATE
static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) {
#if CYTHON_USE_EXC_INFO_STACK
_PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate);
*type = exc_info->exc_type;
*value = exc_info->exc_value;
*tb = exc_info->exc_traceback;
#else
*type = tstate->exc_type;
*value = tstate->exc_value;
*tb = tstate->exc_traceback;
#endif
Py_XINCREF(*type);
Py_XINCREF(*value);
Py_XINCREF(*tb);
}
static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) {
PyObject *tmp_type, *tmp_value, *tmp_tb;
#if CYTHON_USE_EXC_INFO_STACK
_PyErr_StackItem *exc_info = tstate->exc_info;
tmp_type = exc_info->exc_type;
tmp_value = exc_info->exc_value;
tmp_tb = exc_info->exc_traceback;
exc_info->exc_type = type;
exc_info->exc_value = value;
exc_info->exc_traceback = tb;
#else
tmp_type = tstate->exc_type;
tmp_value = tstate->exc_value;
tmp_tb = tstate->exc_traceback;
tstate->exc_type = type;
tstate->exc_value = value;
tstate->exc_traceback = tb;
#endif
Py_XDECREF(tmp_type);
Py_XDECREF(tmp_value);
Py_XDECREF(tmp_tb);
}
#endif
/* PyErrExceptionMatches */
#if CYTHON_FAST_THREAD_STATE
static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) {
Py_ssize_t i, n;
n = PyTuple_GET_SIZE(tuple);
#if PY_MAJOR_VERSION >= 3
for (i=0; i<n; i++) {
if (exc_type == PyTuple_GET_ITEM(tuple, i)) return 1;
}
#endif
for (i=0; i<n; i++) {
if (__Pyx_PyErr_GivenExceptionMatches(exc_type, PyTuple_GET_ITEM(tuple, i))) return 1;
}
return 0;
}
static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err) {
PyObject *exc_type = tstate->curexc_type;
if (exc_type == err) return 1;
if (unlikely(!exc_type)) return 0;
if (unlikely(PyTuple_Check(err)))
return __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err);
return __Pyx_PyErr_GivenExceptionMatches(exc_type, err);
}
#endif
/* GetException */
#if CYTHON_FAST_THREAD_STATE
static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb)
#else
static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb)
#endif
{
PyObject *local_type, *local_value, *local_tb;
#if CYTHON_FAST_THREAD_STATE
PyObject *tmp_type, *tmp_value, *tmp_tb;
local_type = tstate->curexc_type;
local_value = tstate->curexc_value;
local_tb = tstate->curexc_traceback;
tstate->curexc_type = 0;
tstate->curexc_value = 0;
tstate->curexc_traceback = 0;
#else
PyErr_Fetch(&local_type, &local_value, &local_tb);
#endif
PyErr_NormalizeException(&local_type, &local_value, &local_tb);
#if CYTHON_FAST_THREAD_STATE
if (unlikely(tstate->curexc_type))
#else
if (unlikely(PyErr_Occurred()))
#endif
goto bad;
#if PY_MAJOR_VERSION >= 3
if (local_tb) {
if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0))
goto bad;
}
#endif
Py_XINCREF(local_tb);
Py_XINCREF(local_type);
Py_XINCREF(local_value);
*type = local_type;
*value = local_value;
*tb = local_tb;
#if CYTHON_FAST_THREAD_STATE
#if CYTHON_USE_EXC_INFO_STACK
{
_PyErr_StackItem *exc_info = tstate->exc_info;
tmp_type = exc_info->exc_type;
tmp_value = exc_info->exc_value;
tmp_tb = exc_info->exc_traceback;
exc_info->exc_type = local_type;
exc_info->exc_value = local_value;
exc_info->exc_traceback = local_tb;
}
#else
tmp_type = tstate->exc_type;
tmp_value = tstate->exc_value;
tmp_tb = tstate->exc_traceback;
tstate->exc_type = local_type;
tstate->exc_value = local_value;
tstate->exc_traceback = local_tb;
#endif
Py_XDECREF(tmp_type);
Py_XDECREF(tmp_value);
Py_XDECREF(tmp_tb);
#else
PyErr_SetExcInfo(local_type, local_value, local_tb);
#endif
return 0;
bad:
*type = 0;
*value = 0;
*tb = 0;
Py_XDECREF(local_type);
Py_XDECREF(local_value);
Py_XDECREF(local_tb);
return -1;
}
/* RaiseException */
#if PY_MAJOR_VERSION < 3
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb,
CYTHON_UNUSED PyObject *cause) {
__Pyx_PyThreadState_declare
Py_XINCREF(type);
if (!value || value == Py_None)
value = NULL;
else
Py_INCREF(value);
if (!tb || tb == Py_None)
tb = NULL;
else {
Py_INCREF(tb);
if (!PyTraceBack_Check(tb)) {
PyErr_SetString(PyExc_TypeError,
"raise: arg 3 must be a traceback or None");
goto raise_error;
}
}
if (PyType_Check(type)) {
#if CYTHON_COMPILING_IN_PYPY
if (!value) {
Py_INCREF(Py_None);
value = Py_None;
}
#endif
PyErr_NormalizeException(&type, &value, &tb);
} else {
if (value) {
PyErr_SetString(PyExc_TypeError,
"instance exception may not have a separate value");
goto raise_error;
}
value = type;
type = (PyObject*) Py_TYPE(type);
Py_INCREF(type);
if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) {
PyErr_SetString(PyExc_TypeError,
"raise: exception class must be a subclass of BaseException");
goto raise_error;
}
}
__Pyx_PyThreadState_assign
__Pyx_ErrRestore(type, value, tb);
return;
raise_error:
Py_XDECREF(value);
Py_XDECREF(type);
Py_XDECREF(tb);
return;
}
#else
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) {
PyObject* owned_instance = NULL;
if (tb == Py_None) {
tb = 0;
} else if (tb && !PyTraceBack_Check(tb)) {
PyErr_SetString(PyExc_TypeError,
"raise: arg 3 must be a traceback or None");
goto bad;
}
if (value == Py_None)
value = 0;
if (PyExceptionInstance_Check(type)) {
if (value) {
PyErr_SetString(PyExc_TypeError,
"instance exception may not have a separate value");
goto bad;
}
value = type;
type = (PyObject*) Py_TYPE(value);
} else if (PyExceptionClass_Check(type)) {
PyObject *instance_class = NULL;
if (value && PyExceptionInstance_Check(value)) {
instance_class = (PyObject*) Py_TYPE(value);
if (instance_class != type) {
int is_subclass = PyObject_IsSubclass(instance_class, type);
if (!is_subclass) {
instance_class = NULL;
} else if (unlikely(is_subclass == -1)) {
goto bad;
} else {
type = instance_class;
}
}
}
if (!instance_class) {
PyObject *args;
if (!value)
args = PyTuple_New(0);
else if (PyTuple_Check(value)) {
Py_INCREF(value);
args = value;
} else
args = PyTuple_Pack(1, value);
if (!args)
goto bad;
owned_instance = PyObject_Call(type, args, NULL);
Py_DECREF(args);
if (!owned_instance)
goto bad;
value = owned_instance;
if (!PyExceptionInstance_Check(value)) {
PyErr_Format(PyExc_TypeError,
"calling %R should have returned an instance of "
"BaseException, not %R",
type, Py_TYPE(value));
goto bad;
}
}
} else {
PyErr_SetString(PyExc_TypeError,
"raise: exception class must be a subclass of BaseException");
goto bad;
}
if (cause) {
PyObject *fixed_cause;
if (cause == Py_None) {
fixed_cause = NULL;
} else if (PyExceptionClass_Check(cause)) {
fixed_cause = PyObject_CallObject(cause, NULL);
if (fixed_cause == NULL)
goto bad;
} else if (PyExceptionInstance_Check(cause)) {
fixed_cause = cause;
Py_INCREF(fixed_cause);
} else {
PyErr_SetString(PyExc_TypeError,
"exception causes must derive from "
"BaseException");
goto bad;
}
PyException_SetCause(value, fixed_cause);
}
PyErr_SetObject(type, value);
if (tb) {
#if CYTHON_COMPILING_IN_PYPY
PyObject *tmp_type, *tmp_value, *tmp_tb;
PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb);
Py_INCREF(tb);
PyErr_Restore(tmp_type, tmp_value, tb);
Py_XDECREF(tmp_tb);
#else
PyThreadState *tstate = __Pyx_PyThreadState_Current;
PyObject* tmp_tb = tstate->curexc_traceback;
if (tb != tmp_tb) {
Py_INCREF(tb);
tstate->curexc_traceback = tb;
Py_XDECREF(tmp_tb);
}
#endif
}
bad:
Py_XDECREF(owned_instance);
return;
}
#endif
/* TypeImport */
#ifndef __PYX_HAVE_RT_ImportType
#define __PYX_HAVE_RT_ImportType
static PyTypeObject *__Pyx_ImportType(PyObject *module, const char *module_name, const char *class_name,
size_t size, enum __Pyx_ImportType_CheckSize check_size)
{
PyObject *result = 0;
char warning[200];
Py_ssize_t basicsize;
#ifdef Py_LIMITED_API
PyObject *py_basicsize;
#endif
result = PyObject_GetAttrString(module, class_name);
if (!result)
goto bad;
if (!PyType_Check(result)) {
PyErr_Format(PyExc_TypeError,
"%.200s.%.200s is not a type object",
module_name, class_name);
goto bad;
}
#ifndef Py_LIMITED_API
basicsize = ((PyTypeObject *)result)->tp_basicsize;
#else
py_basicsize = PyObject_GetAttrString(result, "__basicsize__");
if (!py_basicsize)
goto bad;
basicsize = PyLong_AsSsize_t(py_basicsize);
Py_DECREF(py_basicsize);
py_basicsize = 0;
if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred())
goto bad;
#endif
if ((size_t)basicsize < size) {
PyErr_Format(PyExc_ValueError,
"%.200s.%.200s size changed, may indicate binary incompatibility. "
"Expected %zd from C header, got %zd from PyObject",
module_name, class_name, size, basicsize);
goto bad;
}
if (check_size == __Pyx_ImportType_CheckSize_Error && (size_t)basicsize != size) {
PyErr_Format(PyExc_ValueError,
"%.200s.%.200s size changed, may indicate binary incompatibility. "
"Expected %zd from C header, got %zd from PyObject",
module_name, class_name, size, basicsize);
goto bad;
}
else if (check_size == __Pyx_ImportType_CheckSize_Warn && (size_t)basicsize > size) {
PyOS_snprintf(warning, sizeof(warning),
"%s.%s size changed, may indicate binary incompatibility. "
"Expected %zd from C header, got %zd from PyObject",
module_name, class_name, size, basicsize);
if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad;
}
return (PyTypeObject *)result;
bad:
Py_XDECREF(result);
return NULL;
}
#endif
/* Import */
static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) {
PyObject *empty_list = 0;
PyObject *module = 0;
PyObject *global_dict = 0;
PyObject *empty_dict = 0;
PyObject *list;
#if PY_MAJOR_VERSION < 3
PyObject *py_import;
py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import);
if (!py_import)
goto bad;
#endif
if (from_list)
list = from_list;
else {
empty_list = PyList_New(0);
if (!empty_list)
goto bad;
list = empty_list;
}
global_dict = PyModule_GetDict(__pyx_m);
if (!global_dict)
goto bad;
empty_dict = PyDict_New();
if (!empty_dict)
goto bad;
{
#if PY_MAJOR_VERSION >= 3
if (level == -1) {
if ((1) && (strchr(__Pyx_MODULE_NAME, '.'))) {
module = PyImport_ImportModuleLevelObject(
name, global_dict, empty_dict, list, 1);
if (!module) {
if (!PyErr_ExceptionMatches(PyExc_ImportError))
goto bad;
PyErr_Clear();
}
}
level = 0;
}
#endif
if (!module) {
#if PY_MAJOR_VERSION < 3
PyObject *py_level = PyInt_FromLong(level);
if (!py_level)
goto bad;
module = PyObject_CallFunctionObjArgs(py_import,
name, global_dict, empty_dict, list, py_level, (PyObject *)NULL);
Py_DECREF(py_level);
#else
module = PyImport_ImportModuleLevelObject(
name, global_dict, empty_dict, list, level);
#endif
}
}
bad:
#if PY_MAJOR_VERSION < 3
Py_XDECREF(py_import);
#endif
Py_XDECREF(empty_list);
Py_XDECREF(empty_dict);
return module;
}
/* CLineInTraceback */
#ifndef CYTHON_CLINE_IN_TRACEBACK
static int __Pyx_CLineForTraceback(CYTHON_NCP_UNUSED PyThreadState *tstate, int c_line) {
PyObject *use_cline;
PyObject *ptype, *pvalue, *ptraceback;
#if CYTHON_COMPILING_IN_CPYTHON
PyObject **cython_runtime_dict;
#endif
if (unlikely(!__pyx_cython_runtime)) {
return c_line;
}
__Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback);
#if CYTHON_COMPILING_IN_CPYTHON
cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime);
if (likely(cython_runtime_dict)) {
__PYX_PY_DICT_LOOKUP_IF_MODIFIED(
use_cline, *cython_runtime_dict,
__Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback))
} else
#endif
{
PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback);
if (use_cline_obj) {
use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True;
Py_DECREF(use_cline_obj);
} else {
PyErr_Clear();
use_cline = NULL;
}
}
if (!use_cline) {
c_line = 0;
PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False);
}
else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) {
c_line = 0;
}
__Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback);
return c_line;
}
#endif
/* CodeObjectCache */
static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) {
int start = 0, mid = 0, end = count - 1;
if (end >= 0 && code_line > entries[end].code_line) {
return count;
}
while (start < end) {
mid = start + (end - start) / 2;
if (code_line < entries[mid].code_line) {
end = mid;
} else if (code_line > entries[mid].code_line) {
start = mid + 1;
} else {
return mid;
}
}
if (code_line <= entries[mid].code_line) {
return mid;
} else {
return mid + 1;
}
}
static PyCodeObject *__pyx_find_code_object(int code_line) {
PyCodeObject* code_object;
int pos;
if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) {
return NULL;
}
pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line);
if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) {
return NULL;
}
code_object = __pyx_code_cache.entries[pos].code_object;
Py_INCREF(code_object);
return code_object;
}
static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) {
int pos, i;
__Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries;
if (unlikely(!code_line)) {
return;
}
if (unlikely(!entries)) {
entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry));
if (likely(entries)) {
__pyx_code_cache.entries = entries;
__pyx_code_cache.max_count = 64;
__pyx_code_cache.count = 1;
entries[0].code_line = code_line;
entries[0].code_object = code_object;
Py_INCREF(code_object);
}
return;
}
pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line);
if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) {
PyCodeObject* tmp = entries[pos].code_object;
entries[pos].code_object = code_object;
Py_DECREF(tmp);
return;
}
if (__pyx_code_cache.count == __pyx_code_cache.max_count) {
int new_max = __pyx_code_cache.max_count + 64;
entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc(
__pyx_code_cache.entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry));
if (unlikely(!entries)) {
return;
}
__pyx_code_cache.entries = entries;
__pyx_code_cache.max_count = new_max;
}
for (i=__pyx_code_cache.count; i>pos; i--) {
entries[i] = entries[i-1];
}
entries[pos].code_line = code_line;
entries[pos].code_object = code_object;
__pyx_code_cache.count++;
Py_INCREF(code_object);
}
/* AddTraceback */
#include "compile.h"
#include "frameobject.h"
#include "traceback.h"
static PyCodeObject* __Pyx_CreateCodeObjectForTraceback(
const char *funcname, int c_line,
int py_line, const char *filename) {
PyCodeObject *py_code = 0;
PyObject *py_srcfile = 0;
PyObject *py_funcname = 0;
#if PY_MAJOR_VERSION < 3
py_srcfile = PyString_FromString(filename);
#else
py_srcfile = PyUnicode_FromString(filename);
#endif
if (!py_srcfile) goto bad;
if (c_line) {
#if PY_MAJOR_VERSION < 3
py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line);
#else
py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line);
#endif
}
else {
#if PY_MAJOR_VERSION < 3
py_funcname = PyString_FromString(funcname);
#else
py_funcname = PyUnicode_FromString(funcname);
#endif
}
if (!py_funcname) goto bad;
py_code = __Pyx_PyCode_New(
0,
0,
0,
0,
0,
__pyx_empty_bytes, /*PyObject *code,*/
__pyx_empty_tuple, /*PyObject *consts,*/
__pyx_empty_tuple, /*PyObject *names,*/
__pyx_empty_tuple, /*PyObject *varnames,*/
__pyx_empty_tuple, /*PyObject *freevars,*/
__pyx_empty_tuple, /*PyObject *cellvars,*/
py_srcfile, /*PyObject *filename,*/
py_funcname, /*PyObject *name,*/
py_line,
__pyx_empty_bytes /*PyObject *lnotab*/
);
Py_DECREF(py_srcfile);
Py_DECREF(py_funcname);
return py_code;
bad:
Py_XDECREF(py_srcfile);
Py_XDECREF(py_funcname);
return NULL;
}
static void __Pyx_AddTraceback(const char *funcname, int c_line,
int py_line, const char *filename) {
PyCodeObject *py_code = 0;
PyFrameObject *py_frame = 0;
PyThreadState *tstate = __Pyx_PyThreadState_Current;
if (c_line) {
c_line = __Pyx_CLineForTraceback(tstate, c_line);
}
py_code = __pyx_find_code_object(c_line ? -c_line : py_line);
if (!py_code) {
py_code = __Pyx_CreateCodeObjectForTraceback(
funcname, c_line, py_line, filename);
if (!py_code) goto bad;
__pyx_insert_code_object(c_line ? -c_line : py_line, py_code);
}
py_frame = PyFrame_New(
tstate, /*PyThreadState *tstate,*/
py_code, /*PyCodeObject *code,*/
__pyx_d, /*PyObject *globals,*/
0 /*PyObject *locals*/
);
if (!py_frame) goto bad;
__Pyx_PyFrame_SetLineNumber(py_frame, py_line);
PyTraceBack_Here(py_frame);
bad:
Py_XDECREF(py_code);
Py_XDECREF(py_frame);
}
#if PY_MAJOR_VERSION < 3
static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) {
if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags);
PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name);
return -1;
}
static void __Pyx_ReleaseBuffer(Py_buffer *view) {
PyObject *obj = view->obj;
if (!obj) return;
if (PyObject_CheckBuffer(obj)) {
PyBuffer_Release(view);
return;
}
if ((0)) {}
view->obj = NULL;
Py_DECREF(obj);
}
#endif
/* CIntFromPyVerify */
#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\
__PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0)
#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\
__PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1)
#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\
{\
func_type value = func_value;\
if (sizeof(target_type) < sizeof(func_type)) {\
if (unlikely(value != (func_type) (target_type) value)) {\
func_type zero = 0;\
if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\
return (target_type) -1;\
if (is_unsigned && unlikely(value < zero))\
goto raise_neg_overflow;\
else\
goto raise_overflow;\
}\
}\
return (target_type) value;\
}
/* CIntToPy */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) {
const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0;
const int is_unsigned = neg_one > const_zero;
if (is_unsigned) {
if (sizeof(long) < sizeof(long)) {
return PyInt_FromLong((long) value);
} else if (sizeof(long) <= sizeof(unsigned long)) {
return PyLong_FromUnsignedLong((unsigned long) value);
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) {
return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value);
#endif
}
} else {
if (sizeof(long) <= sizeof(long)) {
return PyInt_FromLong((long) value);
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(PY_LONG_LONG)) {
return PyLong_FromLongLong((PY_LONG_LONG) value);
#endif
}
}
{
int one = 1; int little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&value;
return _PyLong_FromByteArray(bytes, sizeof(long),
little, !is_unsigned);
}
}
/* CIntToPy */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) {
const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0;
const int is_unsigned = neg_one > const_zero;
if (is_unsigned) {
if (sizeof(int) < sizeof(long)) {
return PyInt_FromLong((long) value);
} else if (sizeof(int) <= sizeof(unsigned long)) {
return PyLong_FromUnsignedLong((unsigned long) value);
#ifdef HAVE_LONG_LONG
} else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) {
return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value);
#endif
}
} else {
if (sizeof(int) <= sizeof(long)) {
return PyInt_FromLong((long) value);
#ifdef HAVE_LONG_LONG
} else if (sizeof(int) <= sizeof(PY_LONG_LONG)) {
return PyLong_FromLongLong((PY_LONG_LONG) value);
#endif
}
}
{
int one = 1; int little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&value;
return _PyLong_FromByteArray(bytes, sizeof(int),
little, !is_unsigned);
}
}
/* Declarations */
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) {
return ::std::complex< float >(x, y);
}
#else
static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) {
return x + y*(__pyx_t_float_complex)_Complex_I;
}
#endif
#else
static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) {
__pyx_t_float_complex z;
z.real = x;
z.imag = y;
return z;
}
#endif
/* Arithmetic */
#if CYTHON_CCOMPLEX
#else
static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex a, __pyx_t_float_complex b) {
return (a.real == b.real) && (a.imag == b.imag);
}
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex a, __pyx_t_float_complex b) {
__pyx_t_float_complex z;
z.real = a.real + b.real;
z.imag = a.imag + b.imag;
return z;
}
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex a, __pyx_t_float_complex b) {
__pyx_t_float_complex z;
z.real = a.real - b.real;
z.imag = a.imag - b.imag;
return z;
}
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex a, __pyx_t_float_complex b) {
__pyx_t_float_complex z;
z.real = a.real * b.real - a.imag * b.imag;
z.imag = a.real * b.imag + a.imag * b.real;
return z;
}
#if 1
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) {
if (b.imag == 0) {
return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real);
} else if (fabsf(b.real) >= fabsf(b.imag)) {
if (b.real == 0 && b.imag == 0) {
return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.imag);
} else {
float r = b.imag / b.real;
float s = (float)(1.0) / (b.real + b.imag * r);
return __pyx_t_float_complex_from_parts(
(a.real + a.imag * r) * s, (a.imag - a.real * r) * s);
}
} else {
float r = b.real / b.imag;
float s = (float)(1.0) / (b.imag + b.real * r);
return __pyx_t_float_complex_from_parts(
(a.real * r + a.imag) * s, (a.imag * r - a.real) * s);
}
}
#else
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) {
if (b.imag == 0) {
return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real);
} else {
float denom = b.real * b.real + b.imag * b.imag;
return __pyx_t_float_complex_from_parts(
(a.real * b.real + a.imag * b.imag) / denom,
(a.imag * b.real - a.real * b.imag) / denom);
}
}
#endif
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex a) {
__pyx_t_float_complex z;
z.real = -a.real;
z.imag = -a.imag;
return z;
}
static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex a) {
return (a.real == 0) && (a.imag == 0);
}
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex a) {
__pyx_t_float_complex z;
z.real = a.real;
z.imag = -a.imag;
return z;
}
#if 1
static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex z) {
#if !defined(HAVE_HYPOT) || defined(_MSC_VER)
return sqrtf(z.real*z.real + z.imag*z.imag);
#else
return hypotf(z.real, z.imag);
#endif
}
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex a, __pyx_t_float_complex b) {
__pyx_t_float_complex z;
float r, lnr, theta, z_r, z_theta;
if (b.imag == 0 && b.real == (int)b.real) {
if (b.real < 0) {
float denom = a.real * a.real + a.imag * a.imag;
a.real = a.real / denom;
a.imag = -a.imag / denom;
b.real = -b.real;
}
switch ((int)b.real) {
case 0:
z.real = 1;
z.imag = 0;
return z;
case 1:
return a;
case 2:
return __Pyx_c_prod_float(a, a);
case 3:
z = __Pyx_c_prod_float(a, a);
return __Pyx_c_prod_float(z, a);
case 4:
z = __Pyx_c_prod_float(a, a);
return __Pyx_c_prod_float(z, z);
}
}
if (a.imag == 0) {
if (a.real == 0) {
return a;
} else if (b.imag == 0) {
z.real = powf(a.real, b.real);
z.imag = 0;
return z;
} else if (a.real > 0) {
r = a.real;
theta = 0;
} else {
r = -a.real;
theta = atan2f(0.0, -1.0);
}
} else {
r = __Pyx_c_abs_float(a);
theta = atan2f(a.imag, a.real);
}
lnr = logf(r);
z_r = expf(lnr * b.real - theta * b.imag);
z_theta = theta * b.real + lnr * b.imag;
z.real = z_r * cosf(z_theta);
z.imag = z_r * sinf(z_theta);
return z;
}
#endif
#endif
/* Declarations */
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) {
return ::std::complex< double >(x, y);
}
#else
static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) {
return x + y*(__pyx_t_double_complex)_Complex_I;
}
#endif
#else
static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) {
__pyx_t_double_complex z;
z.real = x;
z.imag = y;
return z;
}
#endif
/* Arithmetic */
#if CYTHON_CCOMPLEX
#else
static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex a, __pyx_t_double_complex b) {
return (a.real == b.real) && (a.imag == b.imag);
}
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex a, __pyx_t_double_complex b) {
__pyx_t_double_complex z;
z.real = a.real + b.real;
z.imag = a.imag + b.imag;
return z;
}
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex a, __pyx_t_double_complex b) {
__pyx_t_double_complex z;
z.real = a.real - b.real;
z.imag = a.imag - b.imag;
return z;
}
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex a, __pyx_t_double_complex b) {
__pyx_t_double_complex z;
z.real = a.real * b.real - a.imag * b.imag;
z.imag = a.real * b.imag + a.imag * b.real;
return z;
}
#if 1
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) {
if (b.imag == 0) {
return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real);
} else if (fabs(b.real) >= fabs(b.imag)) {
if (b.real == 0 && b.imag == 0) {
return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.imag);
} else {
double r = b.imag / b.real;
double s = (double)(1.0) / (b.real + b.imag * r);
return __pyx_t_double_complex_from_parts(
(a.real + a.imag * r) * s, (a.imag - a.real * r) * s);
}
} else {
double r = b.real / b.imag;
double s = (double)(1.0) / (b.imag + b.real * r);
return __pyx_t_double_complex_from_parts(
(a.real * r + a.imag) * s, (a.imag * r - a.real) * s);
}
}
#else
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) {
if (b.imag == 0) {
return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real);
} else {
double denom = b.real * b.real + b.imag * b.imag;
return __pyx_t_double_complex_from_parts(
(a.real * b.real + a.imag * b.imag) / denom,
(a.imag * b.real - a.real * b.imag) / denom);
}
}
#endif
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex a) {
__pyx_t_double_complex z;
z.real = -a.real;
z.imag = -a.imag;
return z;
}
static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex a) {
return (a.real == 0) && (a.imag == 0);
}
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex a) {
__pyx_t_double_complex z;
z.real = a.real;
z.imag = -a.imag;
return z;
}
#if 1
static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex z) {
#if !defined(HAVE_HYPOT) || defined(_MSC_VER)
return sqrt(z.real*z.real + z.imag*z.imag);
#else
return hypot(z.real, z.imag);
#endif
}
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex a, __pyx_t_double_complex b) {
__pyx_t_double_complex z;
double r, lnr, theta, z_r, z_theta;
if (b.imag == 0 && b.real == (int)b.real) {
if (b.real < 0) {
double denom = a.real * a.real + a.imag * a.imag;
a.real = a.real / denom;
a.imag = -a.imag / denom;
b.real = -b.real;
}
switch ((int)b.real) {
case 0:
z.real = 1;
z.imag = 0;
return z;
case 1:
return a;
case 2:
return __Pyx_c_prod_double(a, a);
case 3:
z = __Pyx_c_prod_double(a, a);
return __Pyx_c_prod_double(z, a);
case 4:
z = __Pyx_c_prod_double(a, a);
return __Pyx_c_prod_double(z, z);
}
}
if (a.imag == 0) {
if (a.real == 0) {
return a;
} else if (b.imag == 0) {
z.real = pow(a.real, b.real);
z.imag = 0;
return z;
} else if (a.real > 0) {
r = a.real;
theta = 0;
} else {
r = -a.real;
theta = atan2(0.0, -1.0);
}
} else {
r = __Pyx_c_abs_double(a);
theta = atan2(a.imag, a.real);
}
lnr = log(r);
z_r = exp(lnr * b.real - theta * b.imag);
z_theta = theta * b.real + lnr * b.imag;
z.real = z_r * cos(z_theta);
z.imag = z_r * sin(z_theta);
return z;
}
#endif
#endif
/* CIntFromPy */
static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *x) {
const unsigned int neg_one = (unsigned int) ((unsigned int) 0 - (unsigned int) 1), const_zero = (unsigned int) 0;
const int is_unsigned = neg_one > const_zero;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_Check(x))) {
if (sizeof(unsigned int) < sizeof(long)) {
__PYX_VERIFY_RETURN_INT(unsigned int, long, PyInt_AS_LONG(x))
} else {
long val = PyInt_AS_LONG(x);
if (is_unsigned && unlikely(val < 0)) {
goto raise_neg_overflow;
}
return (unsigned int) val;
}
} else
#endif
if (likely(PyLong_Check(x))) {
if (is_unsigned) {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (unsigned int) 0;
case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, digits[0])
case 2:
if (8 * sizeof(unsigned int) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(unsigned int) >= 2 * PyLong_SHIFT) {
return (unsigned int) (((((unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]));
}
}
break;
case 3:
if (8 * sizeof(unsigned int) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(unsigned int) >= 3 * PyLong_SHIFT) {
return (unsigned int) (((((((unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]));
}
}
break;
case 4:
if (8 * sizeof(unsigned int) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(unsigned int) >= 4 * PyLong_SHIFT) {
return (unsigned int) (((((((((unsigned int)digits[3]) << PyLong_SHIFT) | (unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]));
}
}
break;
}
#endif
#if CYTHON_COMPILING_IN_CPYTHON
if (unlikely(Py_SIZE(x) < 0)) {
goto raise_neg_overflow;
}
#else
{
int result = PyObject_RichCompareBool(x, Py_False, Py_LT);
if (unlikely(result < 0))
return (unsigned int) -1;
if (unlikely(result == 1))
goto raise_neg_overflow;
}
#endif
if (sizeof(unsigned int) <= sizeof(unsigned long)) {
__PYX_VERIFY_RETURN_INT_EXC(unsigned int, unsigned long, PyLong_AsUnsignedLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(unsigned int) <= sizeof(unsigned PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(unsigned int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x))
#endif
}
} else {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (unsigned int) 0;
case -1: __PYX_VERIFY_RETURN_INT(unsigned int, sdigit, (sdigit) (-(sdigit)digits[0]))
case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, +digits[0])
case -2:
if (8 * sizeof(unsigned int) - 1 > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(unsigned int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(unsigned int) - 1 > 2 * PyLong_SHIFT) {
return (unsigned int) (((unsigned int)-1)*(((((unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])));
}
}
break;
case 2:
if (8 * sizeof(unsigned int) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(unsigned int) - 1 > 2 * PyLong_SHIFT) {
return (unsigned int) ((((((unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])));
}
}
break;
case -3:
if (8 * sizeof(unsigned int) - 1 > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(unsigned int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(unsigned int) - 1 > 3 * PyLong_SHIFT) {
return (unsigned int) (((unsigned int)-1)*(((((((unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])));
}
}
break;
case 3:
if (8 * sizeof(unsigned int) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(unsigned int) - 1 > 3 * PyLong_SHIFT) {
return (unsigned int) ((((((((unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])));
}
}
break;
case -4:
if (8 * sizeof(unsigned int) - 1 > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(unsigned int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(unsigned int) - 1 > 4 * PyLong_SHIFT) {
return (unsigned int) (((unsigned int)-1)*(((((((((unsigned int)digits[3]) << PyLong_SHIFT) | (unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])));
}
}
break;
case 4:
if (8 * sizeof(unsigned int) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(unsigned int) - 1 > 4 * PyLong_SHIFT) {
return (unsigned int) ((((((((((unsigned int)digits[3]) << PyLong_SHIFT) | (unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])));
}
}
break;
}
#endif
if (sizeof(unsigned int) <= sizeof(long)) {
__PYX_VERIFY_RETURN_INT_EXC(unsigned int, long, PyLong_AsLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(unsigned int) <= sizeof(PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(unsigned int, PY_LONG_LONG, PyLong_AsLongLong(x))
#endif
}
}
{
#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray)
PyErr_SetString(PyExc_RuntimeError,
"_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers");
#else
unsigned int val;
PyObject *v = __Pyx_PyNumber_IntOrLong(x);
#if PY_MAJOR_VERSION < 3
if (likely(v) && !PyLong_Check(v)) {
PyObject *tmp = v;
v = PyNumber_Long(tmp);
Py_DECREF(tmp);
}
#endif
if (likely(v)) {
int one = 1; int is_little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&val;
int ret = _PyLong_AsByteArray((PyLongObject *)v,
bytes, sizeof(val),
is_little, !is_unsigned);
Py_DECREF(v);
if (likely(!ret))
return val;
}
#endif
return (unsigned int) -1;
}
} else {
unsigned int val;
PyObject *tmp = __Pyx_PyNumber_IntOrLong(x);
if (!tmp) return (unsigned int) -1;
val = __Pyx_PyInt_As_unsigned_int(tmp);
Py_DECREF(tmp);
return val;
}
raise_overflow:
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to unsigned int");
return (unsigned int) -1;
raise_neg_overflow:
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to unsigned int");
return (unsigned int) -1;
}
/* CIntFromPy */
static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) {
const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0;
const int is_unsigned = neg_one > const_zero;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_Check(x))) {
if (sizeof(int) < sizeof(long)) {
__PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x))
} else {
long val = PyInt_AS_LONG(x);
if (is_unsigned && unlikely(val < 0)) {
goto raise_neg_overflow;
}
return (int) val;
}
} else
#endif
if (likely(PyLong_Check(x))) {
if (is_unsigned) {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (int) 0;
case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0])
case 2:
if (8 * sizeof(int) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) {
return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
}
}
break;
case 3:
if (8 * sizeof(int) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) {
return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
}
}
break;
case 4:
if (8 * sizeof(int) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) {
return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
}
}
break;
}
#endif
#if CYTHON_COMPILING_IN_CPYTHON
if (unlikely(Py_SIZE(x) < 0)) {
goto raise_neg_overflow;
}
#else
{
int result = PyObject_RichCompareBool(x, Py_False, Py_LT);
if (unlikely(result < 0))
return (int) -1;
if (unlikely(result == 1))
goto raise_neg_overflow;
}
#endif
if (sizeof(int) <= sizeof(unsigned long)) {
__PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x))
#endif
}
} else {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (int) 0;
case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0]))
case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0])
case -2:
if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case 2:
if (8 * sizeof(int) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case -3:
if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case 3:
if (8 * sizeof(int) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case -4:
if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) {
return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case 4:
if (8 * sizeof(int) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) {
return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
}
#endif
if (sizeof(int) <= sizeof(long)) {
__PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(int) <= sizeof(PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x))
#endif
}
}
{
#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray)
PyErr_SetString(PyExc_RuntimeError,
"_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers");
#else
int val;
PyObject *v = __Pyx_PyNumber_IntOrLong(x);
#if PY_MAJOR_VERSION < 3
if (likely(v) && !PyLong_Check(v)) {
PyObject *tmp = v;
v = PyNumber_Long(tmp);
Py_DECREF(tmp);
}
#endif
if (likely(v)) {
int one = 1; int is_little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&val;
int ret = _PyLong_AsByteArray((PyLongObject *)v,
bytes, sizeof(val),
is_little, !is_unsigned);
Py_DECREF(v);
if (likely(!ret))
return val;
}
#endif
return (int) -1;
}
} else {
int val;
PyObject *tmp = __Pyx_PyNumber_IntOrLong(x);
if (!tmp) return (int) -1;
val = __Pyx_PyInt_As_int(tmp);
Py_DECREF(tmp);
return val;
}
raise_overflow:
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to int");
return (int) -1;
raise_neg_overflow:
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to int");
return (int) -1;
}
/* CIntFromPy */
static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) {
const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0;
const int is_unsigned = neg_one > const_zero;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_Check(x))) {
if (sizeof(long) < sizeof(long)) {
__PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x))
} else {
long val = PyInt_AS_LONG(x);
if (is_unsigned && unlikely(val < 0)) {
goto raise_neg_overflow;
}
return (long) val;
}
} else
#endif
if (likely(PyLong_Check(x))) {
if (is_unsigned) {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (long) 0;
case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0])
case 2:
if (8 * sizeof(long) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) {
return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
}
}
break;
case 3:
if (8 * sizeof(long) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) {
return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
}
}
break;
case 4:
if (8 * sizeof(long) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) {
return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
}
}
break;
}
#endif
#if CYTHON_COMPILING_IN_CPYTHON
if (unlikely(Py_SIZE(x) < 0)) {
goto raise_neg_overflow;
}
#else
{
int result = PyObject_RichCompareBool(x, Py_False, Py_LT);
if (unlikely(result < 0))
return (long) -1;
if (unlikely(result == 1))
goto raise_neg_overflow;
}
#endif
if (sizeof(long) <= sizeof(unsigned long)) {
__PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x))
#endif
}
} else {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (long) 0;
case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0]))
case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0])
case -2:
if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case 2:
if (8 * sizeof(long) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case -3:
if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case 3:
if (8 * sizeof(long) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case -4:
if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) {
return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case 4:
if (8 * sizeof(long) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) {
return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
}
#endif
if (sizeof(long) <= sizeof(long)) {
__PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x))
#endif
}
}
{
#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray)
PyErr_SetString(PyExc_RuntimeError,
"_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers");
#else
long val;
PyObject *v = __Pyx_PyNumber_IntOrLong(x);
#if PY_MAJOR_VERSION < 3
if (likely(v) && !PyLong_Check(v)) {
PyObject *tmp = v;
v = PyNumber_Long(tmp);
Py_DECREF(tmp);
}
#endif
if (likely(v)) {
int one = 1; int is_little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&val;
int ret = _PyLong_AsByteArray((PyLongObject *)v,
bytes, sizeof(val),
is_little, !is_unsigned);
Py_DECREF(v);
if (likely(!ret))
return val;
}
#endif
return (long) -1;
}
} else {
long val;
PyObject *tmp = __Pyx_PyNumber_IntOrLong(x);
if (!tmp) return (long) -1;
val = __Pyx_PyInt_As_long(tmp);
Py_DECREF(tmp);
return val;
}
raise_overflow:
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to long");
return (long) -1;
raise_neg_overflow:
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to long");
return (long) -1;
}
/* FastTypeChecks */
#if CYTHON_COMPILING_IN_CPYTHON
static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) {
while (a) {
a = a->tp_base;
if (a == b)
return 1;
}
return b == &PyBaseObject_Type;
}
static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) {
PyObject *mro;
if (a == b) return 1;
mro = a->tp_mro;
if (likely(mro)) {
Py_ssize_t i, n;
n = PyTuple_GET_SIZE(mro);
for (i = 0; i < n; i++) {
if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
return 1;
}
return 0;
}
return __Pyx_InBases(a, b);
}
#if PY_MAJOR_VERSION == 2
static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) {
PyObject *exception, *value, *tb;
int res;
__Pyx_PyThreadState_declare
__Pyx_PyThreadState_assign
__Pyx_ErrFetch(&exception, &value, &tb);
res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0;
if (unlikely(res == -1)) {
PyErr_WriteUnraisable(err);
res = 0;
}
if (!res) {
res = PyObject_IsSubclass(err, exc_type2);
if (unlikely(res == -1)) {
PyErr_WriteUnraisable(err);
res = 0;
}
}
__Pyx_ErrRestore(exception, value, tb);
return res;
}
#else
static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) {
int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0;
if (!res) {
res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2);
}
return res;
}
#endif
static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) {
Py_ssize_t i, n;
assert(PyExceptionClass_Check(exc_type));
n = PyTuple_GET_SIZE(tuple);
#if PY_MAJOR_VERSION >= 3
for (i=0; i<n; i++) {
if (exc_type == PyTuple_GET_ITEM(tuple, i)) return 1;
}
#endif
for (i=0; i<n; i++) {
PyObject *t = PyTuple_GET_ITEM(tuple, i);
#if PY_MAJOR_VERSION < 3
if (likely(exc_type == t)) return 1;
#endif
if (likely(PyExceptionClass_Check(t))) {
if (__Pyx_inner_PyErr_GivenExceptionMatches2(exc_type, NULL, t)) return 1;
} else {
}
}
return 0;
}
static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject* exc_type) {
if (likely(err == exc_type)) return 1;
if (likely(PyExceptionClass_Check(err))) {
if (likely(PyExceptionClass_Check(exc_type))) {
return __Pyx_inner_PyErr_GivenExceptionMatches2(err, NULL, exc_type);
} else if (likely(PyTuple_Check(exc_type))) {
return __Pyx_PyErr_GivenExceptionMatchesTuple(err, exc_type);
} else {
}
}
return PyErr_GivenExceptionMatches(err, exc_type);
}
static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *exc_type1, PyObject *exc_type2) {
assert(PyExceptionClass_Check(exc_type1));
assert(PyExceptionClass_Check(exc_type2));
if (likely(err == exc_type1 || err == exc_type2)) return 1;
if (likely(PyExceptionClass_Check(err))) {
return __Pyx_inner_PyErr_GivenExceptionMatches2(err, exc_type1, exc_type2);
}
return (PyErr_GivenExceptionMatches(err, exc_type1) || PyErr_GivenExceptionMatches(err, exc_type2));
}
#endif
/* CheckBinaryVersion */
static int __Pyx_check_binary_version(void) {
char ctversion[4], rtversion[4];
PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION);
PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion());
if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) {
char message[200];
PyOS_snprintf(message, sizeof(message),
"compiletime version %s of module '%.100s' "
"does not match runtime version %s",
ctversion, __Pyx_MODULE_NAME, rtversion);
return PyErr_WarnEx(NULL, message, 1);
}
return 0;
}
/* InitStrings */
static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) {
while (t->p) {
#if PY_MAJOR_VERSION < 3
if (t->is_unicode) {
*t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL);
} else if (t->intern) {
*t->p = PyString_InternFromString(t->s);
} else {
*t->p = PyString_FromStringAndSize(t->s, t->n - 1);
}
#else
if (t->is_unicode | t->is_str) {
if (t->intern) {
*t->p = PyUnicode_InternFromString(t->s);
} else if (t->encoding) {
*t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL);
} else {
*t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1);
}
} else {
*t->p = PyBytes_FromStringAndSize(t->s, t->n - 1);
}
#endif
if (!*t->p)
return -1;
if (PyObject_Hash(*t->p) == -1)
return -1;
++t;
}
return 0;
}
static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) {
return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str));
}
static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) {
Py_ssize_t ignore;
return __Pyx_PyObject_AsStringAndSize(o, &ignore);
}
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT
#if !CYTHON_PEP393_ENABLED
static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) {
char* defenc_c;
PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL);
if (!defenc) return NULL;
defenc_c = PyBytes_AS_STRING(defenc);
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
{
char* end = defenc_c + PyBytes_GET_SIZE(defenc);
char* c;
for (c = defenc_c; c < end; c++) {
if ((unsigned char) (*c) >= 128) {
PyUnicode_AsASCIIString(o);
return NULL;
}
}
}
#endif
*length = PyBytes_GET_SIZE(defenc);
return defenc_c;
}
#else
static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) {
if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL;
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
if (likely(PyUnicode_IS_ASCII(o))) {
*length = PyUnicode_GET_LENGTH(o);
return PyUnicode_AsUTF8(o);
} else {
PyUnicode_AsASCIIString(o);
return NULL;
}
#else
return PyUnicode_AsUTF8AndSize(o, length);
#endif
}
#endif
#endif
static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) {
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT
if (
#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
__Pyx_sys_getdefaultencoding_not_ascii &&
#endif
PyUnicode_Check(o)) {
return __Pyx_PyUnicode_AsStringAndSize(o, length);
} else
#endif
#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))
if (PyByteArray_Check(o)) {
*length = PyByteArray_GET_SIZE(o);
return PyByteArray_AS_STRING(o);
} else
#endif
{
char* result;
int r = PyBytes_AsStringAndSize(o, &result, length);
if (unlikely(r < 0)) {
return NULL;
} else {
return result;
}
}
}
static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) {
int is_true = x == Py_True;
if (is_true | (x == Py_False) | (x == Py_None)) return is_true;
else return PyObject_IsTrue(x);
}
static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) {
int retval;
if (unlikely(!x)) return -1;
retval = __Pyx_PyObject_IsTrue(x);
Py_DECREF(x);
return retval;
}
static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) {
#if PY_MAJOR_VERSION >= 3
if (PyLong_Check(result)) {
if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
"__int__ returned non-int (type %.200s). "
"The ability to return an instance of a strict subclass of int "
"is deprecated, and may be removed in a future version of Python.",
Py_TYPE(result)->tp_name)) {
Py_DECREF(result);
return NULL;
}
return result;
}
#endif
PyErr_Format(PyExc_TypeError,
"__%.4s__ returned non-%.4s (type %.200s)",
type_name, type_name, Py_TYPE(result)->tp_name);
Py_DECREF(result);
return NULL;
}
static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) {
#if CYTHON_USE_TYPE_SLOTS
PyNumberMethods *m;
#endif
const char *name = NULL;
PyObject *res = NULL;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_Check(x) || PyLong_Check(x)))
#else
if (likely(PyLong_Check(x)))
#endif
return __Pyx_NewRef(x);
#if CYTHON_USE_TYPE_SLOTS
m = Py_TYPE(x)->tp_as_number;
#if PY_MAJOR_VERSION < 3
if (m && m->nb_int) {
name = "int";
res = m->nb_int(x);
}
else if (m && m->nb_long) {
name = "long";
res = m->nb_long(x);
}
#else
if (likely(m && m->nb_int)) {
name = "int";
res = m->nb_int(x);
}
#endif
#else
if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) {
res = PyNumber_Int(x);
}
#endif
if (likely(res)) {
#if PY_MAJOR_VERSION < 3
if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) {
#else
if (unlikely(!PyLong_CheckExact(res))) {
#endif
return __Pyx_PyNumber_IntOrLongWrongResultType(res, name);
}
}
else if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError,
"an integer is required");
}
return res;
}
static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) {
Py_ssize_t ival;
PyObject *x;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_CheckExact(b))) {
if (sizeof(Py_ssize_t) >= sizeof(long))
return PyInt_AS_LONG(b);
else
return PyInt_AsSsize_t(b);
}
#endif
if (likely(PyLong_CheckExact(b))) {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)b)->ob_digit;
const Py_ssize_t size = Py_SIZE(b);
if (likely(__Pyx_sst_abs(size) <= 1)) {
ival = likely(size) ? digits[0] : 0;
if (size == -1) ival = -ival;
return ival;
} else {
switch (size) {
case 2:
if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) {
return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case -2:
if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) {
return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case 3:
if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) {
return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case -3:
if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) {
return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case 4:
if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) {
return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case -4:
if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) {
return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
}
}
#endif
return PyLong_AsSsize_t(b);
}
x = PyNumber_Index(b);
if (!x) return -1;
ival = PyInt_AsSsize_t(x);
Py_DECREF(x);
return ival;
}
static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) {
return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False);
}
static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) {
return PyInt_FromSize_t(ival);
}
#endif /* Py_PYTHON_H */
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
IOSAudioBuffer.cpp: Unreal IOSAudio buffer interface object.
=============================================================================*/
/*------------------------------------------------------------------------------------
Includes
------------------------------------------------------------------------------------*/
#include "IOSAudioDevice.h"
#include "AudioEffect.h"
#include "Engine.h"
#include "IAudioFormat.h"
/*------------------------------------------------------------------------------------
FIOSAudioSoundBuffer
------------------------------------------------------------------------------------*/
FIOSAudioSoundBuffer::FIOSAudioSoundBuffer(FIOSAudioDevice* InAudioDevice, ESoundFormat InSoundFormat):
FSoundBuffer(InAudioDevice),
SoundFormat(InSoundFormat),
SampleData(NULL),
SampleRate(0),
CompressedBlockSize(0),
UncompressedBlockSize(0),
BufferSize(0)
{
;
}
FIOSAudioSoundBuffer::~FIOSAudioSoundBuffer(void)
{
if (bAllocationInPermanentPool)
{
UE_LOG(LogIOSAudio, Fatal, TEXT("Can't free resource '%s' as it was allocated in permanent pool."), *ResourceName);
}
FMemory::Free(SampleData);
SampleData = NULL;
}
int32 FIOSAudioSoundBuffer::GetSize(void)
{
int32 TotalSize = 0;
switch (SoundFormat)
{
case SoundFormat_LPCM:
case SoundFormat_ADPCM:
TotalSize = BufferSize;
break;
}
return TotalSize;
}
FIOSAudioSoundBuffer* FIOSAudioSoundBuffer::CreateNativeBuffer(FIOSAudioDevice* IOSAudioDevice, USoundWave* InWave)
{
FWaveModInfo WaveInfo;
InWave->InitAudioResource(IOSAudioDevice->GetRuntimeFormat(InWave));
if (!InWave->ResourceData || InWave->ResourceSize <= 0 || !WaveInfo.ReadWaveInfo(InWave->ResourceData, InWave->ResourceSize))
{
InWave->RemoveAudioResource();
return NULL;
}
uint32 UncompressedBlockSize = 0;
uint32 CompressedBlockSize = 0;
const uint32 PreambleSize = 7;
const uint32 BlockSize = *WaveInfo.pBlockAlign;
switch (*WaveInfo.pFormatTag)
{
case SoundFormat_ADPCM:
// (BlockSize - PreambleSize) * 2 (samples per byte) + 2 (preamble samples)
UncompressedBlockSize = (2 + (BlockSize - PreambleSize) * 2) * sizeof(int16);
CompressedBlockSize = BlockSize;
if ((WaveInfo.SampleDataSize % CompressedBlockSize) != 0)
{
InWave->RemoveAudioResource();
return NULL;
}
break;
case SoundFormat_LPCM:
break;
}
// Create new buffer
FIOSAudioSoundBuffer* Buffer = new FIOSAudioSoundBuffer(IOSAudioDevice, static_cast<ESoundFormat>(*WaveInfo.pFormatTag));
Buffer->NumChannels = InWave->NumChannels;
Buffer->SampleRate = InWave->SampleRate;
Buffer->UncompressedBlockSize = UncompressedBlockSize;
Buffer->CompressedBlockSize = CompressedBlockSize;
Buffer->BufferSize = WaveInfo.SampleDataSize;
Buffer->SampleData = static_cast<int16*>(FMemory::Malloc(Buffer->BufferSize));
FMemory::Memcpy(Buffer->SampleData, WaveInfo.SampleDataStart, Buffer->BufferSize);
FAudioDeviceManager* AudioDeviceManager = GEngine->GetAudioDeviceManager();
check(AudioDeviceManager != nullptr);
AudioDeviceManager->TrackResource(InWave, Buffer);
InWave->RemoveAudioResource();
return Buffer;
}
FIOSAudioSoundBuffer* FIOSAudioSoundBuffer::Init(FIOSAudioDevice* IOSAudioDevice, USoundWave* InWave)
{
// Can't create a buffer without any source data
if (InWave == NULL || InWave->NumChannels == 0)
{
return NULL;
}
FAudioDeviceManager* AudioDeviceManager = GEngine->GetAudioDeviceManager();
FIOSAudioSoundBuffer *Buffer = NULL;
switch (static_cast<EDecompressionType>(InWave->DecompressionType))
{
case DTYPE_Setup:
// Has circumvented pre-cache mechanism - pre-cache now
IOSAudioDevice->Precache(InWave, true, false);
// Recall this function with new decompression type
return Init(IOSAudioDevice, InWave);
case DTYPE_Native:
if (InWave->ResourceID)
{
Buffer = static_cast<FIOSAudioSoundBuffer*>(AudioDeviceManager->WaveBufferMap.FindRef(InWave->ResourceID));
}
if (!Buffer)
{
Buffer = CreateNativeBuffer(IOSAudioDevice, InWave);
}
break;
case DTYPE_Invalid:
case DTYPE_Preview:
case DTYPE_Procedural:
case DTYPE_RealTime:
default:
// Invalid will be set if the wave cannot be played
break;
}
return Buffer;
}
|
#ifndef V9990_HH
#define V9990_HH
#include "MSXDevice.hh"
#include "Schedulable.hh"
#include "VideoSystemChangeListener.hh"
#include "IRQHelper.hh"
#include "V9990DisplayTiming.hh"
#include "V9990ModeEnum.hh"
#include "SimpleDebuggable.hh"
#include "Clock.hh"
#include "serialize_meta.hh"
#include "openmsx.hh"
#include "one_of.hh"
#include "outer.hh"
#include "unreachable.hh"
#include <memory>
namespace openmsx {
class PostProcessor;
class Display;
class V9990VRAM;
class V9990CmdEngine;
class V9990Renderer;
/** Implementation of the Yamaha V9990 VDP as used in the GFX9000
* cartridge by Sunrise.
*/
class V9990 final : public MSXDevice, private VideoSystemChangeListener
{
public:
explicit V9990(const DeviceConfig& config);
~V9990() override;
// MSXDevice interface:
void powerUp(EmuTime::param time) override;
void reset(EmuTime::param time) override;
[[nodiscard]] byte readIO(word port, EmuTime::param time) override;
[[nodiscard]] byte peekIO(word port, EmuTime::param time) const override;
void writeIO(word port, byte value, EmuTime::param time) override;
/** Used by Video9000 to be able to couple the VDP and V9990 output.
* Can return nullptr in case of renderer=none. This value can change
* over the lifetime of the V9990 object (on renderer switch).
*/
[[nodiscard]] PostProcessor* getPostProcessor() const;
/** Obtain a reference to the V9990's VRAM
*/
[[nodiscard]] inline V9990VRAM& getVRAM() {
return *vram;
}
/** Get interlace status.
* @return True iff interlace is enabled.
*/
[[nodiscard]] inline bool isInterlaced() const {
return interlaced;
}
/** Get even/odd page alternation status.
* @return True iff even/odd page alternation is enabled.
*/
[[nodiscard]] inline bool isEvenOddEnabled() const {
return (regs[SCREEN_MODE_1] & 0x04) != 0;
}
/** Is the even or odd field being displayed?
* @return True iff the odd lines should be displayed.
*/
[[nodiscard]] inline bool getEvenOdd() const {
return (status & 0x02) != 0;
}
/** Is the display enabled?
* Note this is simpler than the V99x8 version. Probably ok
* because V9990 doesn't have the same overscan trick (?)
* @return true iff enabled
*/
[[nodiscard]] inline bool isDisplayEnabled() const {
return isDisplayArea && displayEnabled;
}
/** Are sprites (cursors) enabled?
* @return true iff enabled
*/
[[nodiscard]] inline bool spritesEnabled() const {
return !(regs[CONTROL] & 0x40);
}
/** Get palette offset.
* Result is between [0..15] (this represents a logical number
* between [0..63] with lowest two bits always 0).
* @return palette offset
*/
[[nodiscard]] inline byte getPaletteOffset() const {
return (regs[PALETTE_CONTROL] & 0x0F);
}
/** Get palette entry
* @param[in] index The palette index
* ys is only true iff
* - bit 5 (YSE) in R#8 is set
* - there is an external video source set
* - the YS bit in the palette-entry is set
*/
struct GetPaletteResult {
byte r, g, b;
bool ys;
};
[[nodiscard]] GetPaletteResult getPalette(int index) const;
/** Get the number of elapsed UC ticks in this frame.
* @param time Point in emulated time.
* @return Number of UC ticks.
*/
[[nodiscard]] inline int getUCTicksThisFrame(EmuTime::param time) const {
return frameStartTime.getTicksTill_fast(time);
}
/** Is PAL timing active?
* This setting is fixed at start of frame.
* @return True if PAL timing, false if NTSC timing.
*/
[[nodiscard]] inline bool isPalTiming() const {
return palTiming;
}
/** Returns true iff in overscan mode
*/
[[nodiscard]] inline bool isOverScan() const {
return mode == one_of(B0, B2, B4);
}
/** Should this frame be superimposed?
* This is a combination of bit 5 (YSE) in R#8 and the presence of an
* external video source (see setExternalVideoSource()). Though
* because this property only changes once per frame we can't directly
* calculate it like that.
*/
[[nodiscard]] inline bool isSuperimposing() const {
return superimposing;
}
/** Is there an external video source available to superimpose on. */
void setExternalVideoSource(bool enable) {
externalVideoSource = enable;
}
/** In overscan mode the cursor position is still specified with
* 'normal' (non-overscan) y-coordinates. This method returns the
* offset between those two coord-systems.
*/
[[nodiscard]] inline unsigned getCursorYOffset() const {
// TODO vertical set-adjust may or may not influence this,
// need to investigate that.
if (!isOverScan()) return 0;
return isPalTiming()
? V9990DisplayTiming::displayPAL_MCLK .border1
: V9990DisplayTiming::displayNTSC_MCLK.border1;
}
/** Convert UC ticks to V9990 pixel position on a line
* @param ticks Nr of UC Ticks
* @param mode Display mode
* @return Pixel position
* TODO: Move this to V9990DisplayTiming??
*/
[[nodiscard]] static inline int UCtoX(int ticks, V9990DisplayMode mode) {
int x;
ticks = ticks % V9990DisplayTiming::UC_TICKS_PER_LINE;
switch (mode) {
case P1: x = ticks / 8; break;
case P2: x = ticks / 4; break;
case B0: x = ticks /12; break;
case B1: x = ticks / 8; break;
case B2: x = ticks / 6; break;
case B3: x = ticks / 4; break;
case B4: x = ticks / 3; break;
case B5: x = 1; break;
case B6: x = 1; break;
case B7: x = ticks / 2; break;
default: x = 1;
}
return x;
}
/** Return the current display mode
*/
[[nodiscard]] inline V9990DisplayMode getDisplayMode() const {
return mode;
}
/** Return the current color mode
*/
V9990ColorMode getColorMode() const;
/** Return the amount of bits per pixels.
* Result is only meaningful for Bx modes.
* @return Bpp 0 -> 2bpp
* 1 -> 4bpp
* 2 -> 8bpp
* 3 -> 16bpp
*/
[[nodiscard]] inline unsigned getColorDepth() const {
return regs[SCREEN_MODE_0] & 0x03;
}
/** Return the current back drop color
* @return Index the color palette
*/
[[nodiscard]] inline byte getBackDropColor() const {
return regs[BACK_DROP_COLOR];
}
/** Returns the X scroll offset for screen A of P1 and other modes
*/
[[nodiscard]] inline unsigned getScrollAX() const {
return regs[SCROLL_CONTROL_AX0] + 8 * regs[SCROLL_CONTROL_AX1];
}
/** Returns the Y scroll offset for screen A of P1 and other modes
*/
[[nodiscard]] inline unsigned getScrollAY() const {
return regs[SCROLL_CONTROL_AY0] + 256 * scrollAYHigh;
}
/** Returns the X scroll offset for screen B of P1 mode
*/
[[nodiscard]] inline unsigned getScrollBX() const {
return regs[SCROLL_CONTROL_BX0] + 8 * regs[SCROLL_CONTROL_BX1];
}
/** Returns the Y scroll offset for screen B of P1 mode
*/
[[nodiscard]] inline unsigned getScrollBY() const {
return regs[SCROLL_CONTROL_BY0] + 256 * scrollBYHigh;
}
/** Returns the vertical roll mask
*/
[[nodiscard]] inline unsigned getRollMask(unsigned maxMask) const {
static unsigned rollMasks[4] = {
0xFFFF, // no rolling (use maxMask)
0x00FF,
0x01FF,
0x00FF // TODO check this (undocumented)
};
unsigned t = regs[SCROLL_CONTROL_AY1] >> 6;
return t ? rollMasks[t] : maxMask;
}
/** Return the image width
*/
[[nodiscard]] inline unsigned getImageWidth() const {
switch (regs[SCREEN_MODE_0] & 0xC0) {
case 0x00: // P1
return 256;
case 0x40: // P2
return 512;
case 0x80: // Bx
default: // standby TODO check this
return (256 << ((regs[SCREEN_MODE_0] & 0x0C) >> 2));
}
}
/** Return the display width
*/
[[nodiscard]] inline unsigned getLineWidth() const {
switch (getDisplayMode()) {
case B0: return 213;
case P1: case B1: return 320;
case B2: return 426;
case P2: case B3: return 640;
case B4: return 853;
case B5: case B6: return 1; // not supported
case B7: return 1280;
default:
UNREACHABLE; return 0;
}
}
/** Command execution ready
*/
inline void cmdReady() {
raiseIRQ(CMD_IRQ);
}
/** Return the sprite pattern table base address
*/
[[nodiscard]] inline int getSpritePatternAddress(V9990DisplayMode m) const {
switch (m) {
case P1:
return (int(regs[SPRITE_PATTERN_ADDRESS] & 0x0E) << 14);
case P2:
return (int(regs[SPRITE_PATTERN_ADDRESS] & 0x0F) << 15);
default:
return 0;
}
}
/** return sprite palette offset
*/
[[nodiscard]] inline byte getSpritePaletteOffset() const {
return regs[SPRITE_PALETTE_CONTROL] << 2;
}
/** Get horizontal display timings
*/
[[nodiscard]] inline const V9990DisplayPeriod& getHorizontalTiming() const {
return *horTiming;
}
/** Get the number of VDP clockticks between the start of the line and
* the end of the left border.
*/
[[nodiscard]] inline int getLeftBorder() const {
return horTiming->blank + horTiming->border1 +
(((regs[DISPLAY_ADJUST] & 0x0F) ^ 7) - 8) * 8;
}
/** Get the number of VDP clockticks between the start of the line and
* the end of the right border.
*/
[[nodiscard]] inline int getRightBorder() const {
return getLeftBorder() + horTiming->display;
}
/** Get vertical display timings
*/
[[nodiscard]] inline const V9990DisplayPeriod& getVerticalTiming() const {
return *verTiming;
}
[[nodiscard]] inline int getTopBorder() const {
return verTiming->blank + verTiming->border1 +
(((regs[DISPLAY_ADJUST] >> 4) ^ 7) - 8);
}
[[nodiscard]] inline int getBottomBorder() const {
return getTopBorder() + verTiming->display;
}
[[nodiscard]] inline unsigned getPriorityControlX() const {
unsigned t = regs[PRIORITY_CONTROL] & 0x03;
return (t == 0) ? 256 : t << 6;
}
[[nodiscard]] inline unsigned getPriorityControlY() const {
unsigned t = regs[PRIORITY_CONTROL] & 0x0C;
return (t == 0) ? 256 : t << 4;
}
template<typename Archive>
void serialize(Archive& ar, unsigned version);
private:
// VideoSystemChangeListener interface:
void preVideoSystemChange() noexcept override;
void postVideoSystemChange() noexcept override;
// Scheduler stuff
struct SyncBase : Schedulable {
explicit SyncBase(V9990& v9990) : Schedulable(v9990.getScheduler()) {}
using Schedulable::setSyncPoint;
using Schedulable::removeSyncPoint;
protected:
~SyncBase() = default;
};
struct SyncVSync final : SyncBase {
explicit SyncVSync(V9990& v9990) : SyncBase(v9990) {}
void executeUntil(EmuTime::param time) override {
auto& v9990 = OUTER(V9990, syncVSync);
v9990.execVSync(time);
}
} syncVSync;
struct SyncDisplayStart final : SyncBase {
explicit SyncDisplayStart(V9990& v9990) : SyncBase(v9990) {}
void executeUntil(EmuTime::param time) override {
auto& v9990 = OUTER(V9990, syncDisplayStart);
v9990.execDisplayStart(time);
}
} syncDisplayStart;
struct SyncVScan final : SyncBase {
explicit SyncVScan(V9990& v9990) : SyncBase(v9990) {}
void executeUntil(EmuTime::param time) override {
auto& v9990 = OUTER(V9990, syncVScan);
v9990.execVScan(time);
}
} syncVScan;
struct SyncHScan final : SyncBase {
explicit SyncHScan(V9990& v9990) : SyncBase(v9990) {}
void executeUntil(EmuTime::param /*time*/) override {
auto& v9990 = OUTER(V9990, syncHScan);
v9990.execHScan();
}
} syncHScan;
struct SyncSetMode final : SyncBase {
explicit SyncSetMode(V9990& v9990) : SyncBase(v9990) {}
void executeUntil(EmuTime::param time) override {
auto& v9990 = OUTER(V9990, syncSetMode);
v9990.execSetMode(time);
}
} syncSetMode;
struct SyncCmdEnd final : SyncBase {
explicit SyncCmdEnd(V9990& v9990) : SyncBase(v9990) {}
void executeUntil(EmuTime::param time) override {
auto& v9990 = OUTER(V9990, syncCmdEnd);
v9990.execCheckCmdEnd(time);
}
} syncCmdEnd;
void execVSync(EmuTime::param time);
void execDisplayStart(EmuTime::param time);
void execVScan(EmuTime::param time);
void execHScan();
void execSetMode(EmuTime::param time);
void execCheckCmdEnd(EmuTime::param time);
// --- types ------------------------------------------------------
/** IRQ types
*/
enum IRQType {
VER_IRQ = 1,
HOR_IRQ = 2,
CMD_IRQ = 4
};
/** I/O Ports
*/
enum PortId {
VRAM_DATA = 0,
PALETTE_DATA,
COMMAND_DATA,
REGISTER_DATA,
REGISTER_SELECT,
STATUS,
INTERRUPT_FLAG,
SYSTEM_CONTROL,
KANJI_ROM_0,
KANJI_ROM_1,
KANJI_ROM_2,
KANJI_ROM_3,
RESERVED_0,
RESERVED_1,
RESERVED_2,
RESERVED_3
};
/** Registers
*/
enum RegisterId {
VRAM_WRITE_ADDRESS_0 = 0,
VRAM_WRITE_ADDRESS_1,
VRAM_WRITE_ADDRESS_2,
VRAM_READ_ADDRESS_0,
VRAM_READ_ADDRESS_1,
VRAM_READ_ADDRESS_2,
SCREEN_MODE_0,
SCREEN_MODE_1,
CONTROL,
INTERRUPT_0,
INTERRUPT_1,
INTERRUPT_2,
INTERRUPT_3,
PALETTE_CONTROL,
PALETTE_POINTER,
BACK_DROP_COLOR,
DISPLAY_ADJUST,
SCROLL_CONTROL_AY0,
SCROLL_CONTROL_AY1,
SCROLL_CONTROL_AX0,
SCROLL_CONTROL_AX1,
SCROLL_CONTROL_BY0,
SCROLL_CONTROL_BY1,
SCROLL_CONTROL_BX0,
SCROLL_CONTROL_BX1,
SPRITE_PATTERN_ADDRESS,
LCD_CONTROL,
PRIORITY_CONTROL,
SPRITE_PALETTE_CONTROL,
CMD_PARAM_SRC_ADDRESS_0 = 32,
CMD_PARAM_SRC_ADDRESS_1,
CMD_PARAM_SRC_ADDRESS_2,
CMD_PARAM_SRC_ADDRESS_3,
CMD_PARAM_DEST_ADDRESS_0,
CMD_PARAM_DEST_ADDRESS_1,
CMD_PARAM_DEST_ADDRESS_2,
CMD_PARAM_DEST_ADDRESS_3,
CMD_PARAM_SIZE_0,
CMD_PARAM_SIZE_1,
CMD_PARAM_SIZE_2,
CMD_PARAM_SIZE_3,
CMD_PARAM_ARGUMENT,
CMD_PARAM_LOGOP,
CMD_PARAM_WRITE_MASK_0,
CMD_PARAM_WRITE_MASK_1,
CMD_PARAM_FONT_COLOR_FC0,
CMD_PARAM_FONT_COLOR_FC1,
CMD_PARAM_FONT_COLOR_BC0,
CMD_PARAM_FONT_COLOR_BC1,
CMD_PARAM_OPCODE,
CMD_PARAM_BORDER_X_0,
CMD_PARAM_BORDER_X_1
};
// --- members ----------------------------------------------------
struct RegDebug final : SimpleDebuggable {
explicit RegDebug(V9990& v9990);
[[nodiscard]] byte read(unsigned address) override;
void write(unsigned address, byte value, EmuTime::param time) override;
} v9990RegDebug;
struct PalDebug final : SimpleDebuggable {
explicit PalDebug(V9990& v9990);
[[nodiscard]] byte read(unsigned address) override;
void write(unsigned address, byte value, EmuTime::param time) override;
} v9990PalDebug;
IRQHelper irq;
Display& display;
/** VRAM
*/
std::unique_ptr<V9990VRAM> vram;
unsigned vramReadPtr, vramWritePtr;
byte vramReadBuffer;
/** Command Engine
*/
std::unique_ptr<V9990CmdEngine> cmdEngine;
/** Renderer
*/
std::unique_ptr<V9990Renderer> renderer;
/** Emulation time when this frame was started (VSYNC)
*/
Clock<V9990DisplayTiming::UC_TICKS_PER_SECOND> frameStartTime;
/** Time of the last set HSCAN sync point
*/
EmuTime hScanSyncTime;
/** Display timings
*/
const V9990DisplayPeriod* horTiming;
const V9990DisplayPeriod* verTiming;
/** Store display mode because it's queried a lot
*/
V9990DisplayMode mode;
/** Palette
*/
byte palette[0x100];
/** Status port (P#5)
*/
byte status;
/** Interrupt flag (P#6)
*/
byte pendingIRQs;
/** Registers
*/
byte regs[0x40];
byte regSelect;
/** Is PAL timing active? False means NTSC timing
*/
bool palTiming;
/** Is interlace active?
* @see isInterlaced.
*/
bool interlaced;
/** Is the current scan position inside the display area?
*/
bool isDisplayArea;
/** Is display enabled. Note that this is not always the same as bit 7
* of the CONTROL register because the display enable status change
* only takes place at the start of the next frame.
* Note: on V99x8, display enable takes effect the next line
*/
bool displayEnabled;
/** Changing high byte of vertical scroll registers only takes effect
* at the start of the next page. These members hold the current
* value of the scroll value.
* note: writing the low byte has effect immediately (or at the next
* line, TODO investigate this). But the effect is not the same
* as on V99x8, see V9990PixelRenderer::updateScrollAYLow() for
* details.
*/
byte scrollAYHigh;
byte scrollBYHigh;
/** Corresponds to bit 1 in the System Control Port.
* When this is true, all registers are held in the 'power ON reset'
* state, so writes to registers are ignored.
*/
bool systemReset;
/** Is there an external video source availble to superimpose on?
* In 32bpp we could just always output an alpha channel. But in
* 16bpp we only want to output the special color-key when later
* it will be replaced by a pixel from the external video source. */
bool externalVideoSource;
/** Combination of 'externalVideoSource' and R#8 bit 5 (YSE). This
* variable only changes once per frame, so we can't directly
* calculate it from the two former states. */
bool superimposing;
// --- methods ----------------------------------------------------
void setHorizontalTiming();
void setVerticalTiming();
[[nodiscard]] V9990ColorMode getColorMode(byte pal_ctrl) const;
/** Get VRAM read or write address from V9990 registers
* @param base VRAM_READ_ADDRESS_0 or VRAM_WRITE_ADDRESS_0
* @returns VRAM read or write address
*/
[[nodiscard]] inline unsigned getVRAMAddr(RegisterId base) const;
/** set VRAM read or write address into V9990 registers
* @param base VRAM_READ_ADDRESS_0 or VRAM_WRITE_ADDRESS_0
* @param addr Address to set
*/
inline void setVRAMAddr(RegisterId base, unsigned addr);
/** Read V9990 register value
* @param reg Register to read from
* @param time Moment in emulated time to read register
* @returns Register value
*/
[[nodiscard]] byte readRegister(byte reg, EmuTime::param time) const;
/** Write V9990 register value
* @param reg Register to write to
* @param val Value to write
* @param time Moment in emulated time to write register
*/
void writeRegister(byte reg, byte val, EmuTime::param time);
/** Write V9990 palette register
* @param reg Register to write to
* @param val Value to write
* @param time Moment in emulated time to write register
*/
void writePaletteRegister(byte reg, byte val, EmuTime::param time);
/** Schedule a sync point at the start of the next line
*/
void syncAtNextLine(SyncBase& type, EmuTime::param time);
/** Create a new renderer.
* @param time Moment in emulated time to create the renderer
*/
void createRenderer(EmuTime::param time);
/** Start a new frame.
* @param time Moment in emulated time to start the frame
*/
void frameStart(EmuTime::param time);
/** Raise an IRQ
* @param irqType Type of IRQ
*/
void raiseIRQ(IRQType irqType);
/** Precalculate the display mode
*/
void calcDisplayMode();
/** Calculate the moment in time the next line interrupt will occur
* @param time The current time
* @result Timestamp for next hor irq
*/
void scheduleHscan(EmuTime::param time);
/** Estimate when the current (if any) command will finish.
*/
void scheduleCmdEnd(EmuTime::param time);
};
SERIALIZE_CLASS_VERSION(V9990, 5);
} // namespace openmsx
#endif
|
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtCore/QtCore>
#include <QtGui/QtGui>
#include <private/qguiapplication_p.h>
#include <qpa/qplatformintegration.h>
#include <QtWidgets/QApplication>
#include <QtOpenGL/QtOpenGL>
#include "tst_qglthreads.h"
#ifndef QT_OPENGL_ES_2
#include <QtGui/QOpenGLFunctions_1_0>
#endif
#define RUNNING_TIME 5000
tst_QGLThreads::tst_QGLThreads(QObject *parent)
: QObject(parent)
{
}
/*
swapInThread
The purpose of this testcase is to verify that it is possible to do rendering into
a GL context from the GUI thread, then swap the contents in from a background thread.
The usecase for this is to have the background thread do the waiting for vertical
sync while the GUI thread is idle.
Currently the locking is handled directly in the paintEvent(). For the actual usecase
in Qt, the locking is done in the windowsurface before starting any drawing while
unlocking is done after all drawing has been done.
*/
class SwapThread : public QThread
{
Q_OBJECT
public:
SwapThread(QGLWidget *widget)
: m_context(widget->context())
, m_swapTriggered(false)
{
moveToThread(this);
}
void run() {
QTime time;
time.start();
while (time.elapsed() < RUNNING_TIME) {
lock();
waitForReadyToSwap();
m_context->makeCurrent();
m_context->swapBuffers();
m_context->doneCurrent();
m_context->moveToThread(qApp->thread());
signalSwapDone();
unlock();
}
m_swapTriggered = false;
}
void lock() { m_mutex.lock(); }
void unlock() { m_mutex.unlock(); }
void waitForSwapDone() { if (m_swapTriggered) m_swapDone.wait(&m_mutex); }
void waitForReadyToSwap() { if (!m_swapTriggered) m_readyToSwap.wait(&m_mutex); }
void signalReadyToSwap()
{
if (!isRunning())
return;
m_readyToSwap.wakeAll();
m_swapTriggered = true;
}
void signalSwapDone()
{
m_swapTriggered = false;
m_swapDone.wakeAll();
}
private:
QGLContext *m_context;
QMutex m_mutex;
QWaitCondition m_readyToSwap;
QWaitCondition m_swapDone;
bool m_swapTriggered;
};
class ForegroundWidget : public QGLWidget
{
public:
ForegroundWidget(const QGLFormat &format)
: QGLWidget(format), m_thread(0)
{
setAutoBufferSwap(false);
}
void paintEvent(QPaintEvent *)
{
m_thread->lock();
m_thread->waitForSwapDone();
makeCurrent();
QPainter p(this);
p.fillRect(rect(), QColor(rand() % 256, rand() % 256, rand() % 256));
p.setPen(Qt::red);
p.setFont(QFont("SansSerif", 24));
p.drawText(rect(), Qt::AlignCenter, "This is an autotest");
p.end();
doneCurrent();
if (m_thread->isRunning()) {
context()->moveToThread(m_thread);
m_thread->signalReadyToSwap();
}
m_thread->unlock();
update();
}
void setThread(SwapThread *thread) {
m_thread = thread;
}
SwapThread *m_thread;
};
void tst_QGLThreads::swapInThread()
{
if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL))
QSKIP("No platformsupport for ThreadedOpenGL");
QGLFormat format;
format.setSwapInterval(1);
ForegroundWidget widget(format);
SwapThread thread(&widget);
widget.setThread(&thread);
widget.show();
QVERIFY(QTest::qWaitForWindowExposed(&widget));
thread.start();
while (thread.isRunning()) {
qApp->processEvents();
}
widget.hide();
QVERIFY(true);
}
/*
textureUploadInThread
The purpose of this testcase is to verify that doing texture uploads in a background
thread is possible and that it works.
*/
class CreateAndUploadThread : public QThread
{
Q_OBJECT
public:
CreateAndUploadThread(QGLWidget *shareWidget, QSemaphore *semaphore)
: m_semaphore(semaphore)
{
m_gl = new QGLWidget(0, shareWidget);
moveToThread(this);
}
void moveContextToThread()
{
m_gl->context()->moveToThread(this);
}
~CreateAndUploadThread()
{
delete m_gl;
}
void run() {
m_gl->makeCurrent();
QTime time;
time.start();
while (time.elapsed() < RUNNING_TIME) {
int width = 400;
int height = 300;
QImage image(width, height, QImage::Format_RGB32);
QPainter p(&image);
p.fillRect(image.rect(), QColor(rand() % 256, rand() % 256, rand() % 256));
p.setPen(Qt::red);
p.setFont(QFont("SansSerif", 24));
p.drawText(image.rect(), Qt::AlignCenter, "This is an autotest");
p.end();
m_gl->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, QGLContext::InternalBindOption);
m_semaphore->acquire(1);
createdAndUploaded(image);
}
}
signals:
void createdAndUploaded(const QImage &image);
private:
QGLWidget *m_gl;
QSemaphore *m_semaphore;
};
class TextureDisplay : public QGLWidget
{
Q_OBJECT
public:
TextureDisplay(QSemaphore *semaphore)
: m_semaphore(semaphore)
{
}
void paintEvent(QPaintEvent *) {
QPainter p(this);
for (int i=0; i<m_images.size(); ++i) {
p.drawImage(m_positions.at(i), m_images.at(i));
m_positions[i] += QPoint(1, 1);
}
update();
}
public slots:
void receiveImage(const QImage &image) {
m_images << image;
m_positions << QPoint(-rand() % width() / 2, -rand() % height() / 2);
m_semaphore->release(1);
if (m_images.size() > 100) {
m_images.takeFirst();
m_positions.takeFirst();
}
}
private:
QList <QImage> m_images;
QList <QPoint> m_positions;
QSemaphore *m_semaphore;
};
void tst_QGLThreads::textureUploadInThread()
{
if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL))
QSKIP("No platformsupport for ThreadedOpenGL");
// prevent producer thread from queuing up too many images
QSemaphore semaphore(100);
TextureDisplay display(&semaphore);
CreateAndUploadThread thread(&display, &semaphore);
connect(&thread, SIGNAL(createdAndUploaded(QImage)), &display, SLOT(receiveImage(QImage)));
display.show();
QVERIFY(QTest::qWaitForWindowActive(&display));
thread.moveContextToThread();
thread.start();
while (thread.isRunning()) {
qApp->processEvents();
}
QVERIFY(true);
}
/*
renderInThread
This test sets up a scene and renders it in a different thread.
For simplicity, the scene is simply a bunch of rectangles, but
if that works, we're in good shape..
*/
static inline float qrandom() { return (rand() % 100) / 100.f; }
void renderAScene(int w, int h)
{
QOpenGLFunctions *funcs = QOpenGLContext::currentContext()->functions();
if (QOpenGLContext::currentContext()->isOpenGLES()) {
Q_UNUSED(w);
Q_UNUSED(h);
QGLShaderProgram program;
program.addShaderFromSourceCode(QGLShader::Vertex, "attribute highp vec2 pos; void main() { gl_Position = vec4(pos.xy, 1.0, 1.0); }");
program.addShaderFromSourceCode(QGLShader::Fragment, "uniform lowp vec4 color; void main() { gl_FragColor = color; }");
program.bindAttributeLocation("pos", 0);
program.bind();
funcs->glEnableVertexAttribArray(0);
for (int i=0; i<1000; ++i) {
GLfloat pos[] = {
(rand() % 100) / 100.f,
(rand() % 100) / 100.f,
(rand() % 100) / 100.f,
(rand() % 100) / 100.f,
(rand() % 100) / 100.f,
(rand() % 100) / 100.f
};
funcs->glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, pos);
funcs->glDrawArrays(GL_TRIANGLE_STRIP, 0, 3);
}
} else {
#ifndef QT_OPENGL_ES_2
QOpenGLFunctions_1_0 *gl1funcs = QOpenGLContext::currentContext()->versionFunctions<QOpenGLFunctions_1_0>();
gl1funcs->initializeOpenGLFunctions();
gl1funcs->glViewport(0, 0, w, h);
gl1funcs->glMatrixMode(GL_PROJECTION);
gl1funcs->glLoadIdentity();
gl1funcs->glFrustum(0, w, h, 0, 1, 100);
gl1funcs->glTranslated(0, 0, -1);
gl1funcs->glMatrixMode(GL_MODELVIEW);
gl1funcs->glLoadIdentity();
for (int i=0;i<1000; ++i) {
gl1funcs->glBegin(GL_TRIANGLES);
gl1funcs->glColor3f(qrandom(), qrandom(), qrandom());
gl1funcs->glVertex2f(qrandom() * w, qrandom() * h);
gl1funcs->glColor3f(qrandom(), qrandom(), qrandom());
gl1funcs->glVertex2f(qrandom() * w, qrandom() * h);
gl1funcs->glColor3f(qrandom(), qrandom(), qrandom());
gl1funcs->glVertex2f(qrandom() * w, qrandom() * h);
gl1funcs->glEnd();
}
#endif
}
}
class ThreadSafeGLWidget : public QGLWidget
{
public:
ThreadSafeGLWidget(QWidget *parent = 0) : QGLWidget(parent) {}
void paintEvent(QPaintEvent *)
{
// ignored as we're anyway swapping as fast as we can
};
void resizeEvent(QResizeEvent *e)
{
mutex.lock();
newSize = e->size();
mutex.unlock();
};
QMutex mutex;
QSize newSize;
};
class SceneRenderingThread : public QThread
{
Q_OBJECT
public:
SceneRenderingThread(ThreadSafeGLWidget *widget)
: m_widget(widget)
{
moveToThread(this);
m_size = widget->size();
}
void run() {
QTime time;
time.start();
failure = false;
while (time.elapsed() < RUNNING_TIME && !failure) {
m_widget->makeCurrent();
m_widget->mutex.lock();
QSize s = m_widget->newSize;
m_widget->mutex.unlock();
QOpenGLFunctions *funcs = QOpenGLContext::currentContext()->functions();
if (s != m_size) {
funcs->glViewport(0, 0, s.width(), s.height());
}
if (QGLContext::currentContext() != m_widget->context()) {
failure = true;
break;
}
funcs->glClear(GL_COLOR_BUFFER_BIT);
int w = m_widget->width();
int h = m_widget->height();
renderAScene(w, h);
int color;
funcs->glReadPixels(w / 2, h / 2, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &color);
m_widget->swapBuffers();
}
m_widget->doneCurrent();
}
bool failure;
private:
ThreadSafeGLWidget *m_widget;
QSize m_size;
};
void tst_QGLThreads::renderInThread_data()
{
QTest::addColumn<bool>("resize");
QTest::addColumn<bool>("update");
QTest::newRow("basic") << false << false;
QTest::newRow("with-resize") << true << false;
QTest::newRow("with-update") << false << true;
QTest::newRow("with-resize-and-update") << true << true;
}
void tst_QGLThreads::renderInThread()
{
if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL))
QSKIP("No platformsupport for ThreadedOpenGL");
QFETCH(bool, resize);
QFETCH(bool, update);
ThreadSafeGLWidget widget;
widget.resize(200, 200);
SceneRenderingThread thread(&widget);
widget.show();
QVERIFY(QTest::qWaitForWindowExposed(&widget));
widget.doneCurrent();
widget.context()->moveToThread(&thread);
thread.start();
int value = 10;
while (thread.isRunning()) {
if (resize)
widget.resize(200 + value, 200 + value);
if (update)
widget.update(100 + value, 100 + value, 20, 20);
qApp->processEvents();
value = -value;
QThread::msleep(100);
}
QVERIFY(!thread.failure);
}
class Device
{
public:
virtual ~Device() {}
virtual QPaintDevice *realPaintDevice() = 0;
virtual void prepareDevice() {}
virtual void moveToThread(QThread *) {}
};
class GLWidgetWrapper : public Device
{
public:
GLWidgetWrapper() {
widget.resize(150, 150);
widget.show();
QTest::qWaitForWindowExposed(&widget);
widget.doneCurrent();
}
QPaintDevice *realPaintDevice() { return &widget; }
void moveToThread(QThread *thread) { widget.context()->moveToThread(thread); }
ThreadSafeGLWidget widget;
};
class PixmapWrapper : public Device
{
public:
PixmapWrapper() { pixmap = new QPixmap(512, 512); }
~PixmapWrapper() { delete pixmap; }
QPaintDevice *realPaintDevice() { return pixmap; }
QPixmap *pixmap;
};
class PixelBufferWrapper : public Device
{
public:
PixelBufferWrapper() { pbuffer = new QGLPixelBuffer(512, 512); }
~PixelBufferWrapper() { delete pbuffer; }
QPaintDevice *realPaintDevice() { return pbuffer; }
void moveToThread(QThread *thread) { pbuffer->context()->moveToThread(thread); }
QGLPixelBuffer *pbuffer;
};
class FrameBufferObjectWrapper : public Device
{
public:
FrameBufferObjectWrapper() {
widget.makeCurrent();
fbo = new QGLFramebufferObject(512, 512);
widget.doneCurrent();
}
~FrameBufferObjectWrapper() { delete fbo; }
QPaintDevice *realPaintDevice() { return fbo; }
void prepareDevice() { widget.makeCurrent(); }
void moveToThread(QThread *thread) { widget.context()->moveToThread(thread); }
ThreadSafeGLWidget widget;
QGLFramebufferObject *fbo;
};
class ThreadPainter : public QObject
{
Q_OBJECT
public:
ThreadPainter(Device *pd) : device(pd), fail(true) {
pixmap = QPixmap(40, 40);
pixmap.fill(Qt::green);
QPainter p(&pixmap);
p.drawLine(0, 0, 40, 40);
p.drawLine(0, 40, 40, 0);
}
public slots:
void draw() {
bool beginFailed = false;
QTime time;
time.start();
int rotAngle = 10;
device->prepareDevice();
QPaintDevice *paintDevice = device->realPaintDevice();
QSize s(paintDevice->width(), paintDevice->height());
while (time.elapsed() < RUNNING_TIME) {
QPainter p;
if (!p.begin(paintDevice)) {
beginFailed = true;
break;
}
p.translate(s.width()/2, s.height()/2);
p.rotate(rotAngle);
p.translate(-s.width()/2, -s.height()/2);
p.fillRect(0, 0, s.width(), s.height(), Qt::red);
QRect rect(QPoint(0, 0), s);
p.drawPixmap(10, 10, pixmap);
p.drawTiledPixmap(50, 50, 100, 100, pixmap);
p.drawText(rect.center(), "This is a piece of text");
p.end();
rotAngle += 2;
QThread::msleep(20);
}
device->moveToThread(qApp->thread());
fail = beginFailed;
QThread::currentThread()->quit();
}
bool failed() { return fail; }
private:
QPixmap pixmap;
Device *device;
bool fail;
};
template <class T>
class PaintThreadManager
{
public:
PaintThreadManager(int count) : numThreads(count)
{
for (int i=0; i<numThreads; ++i)
devices.append(new T);
// Wait until resize events are processed on the internal
// QGLWidgets of the buffers to suppress errors
// about makeCurrent() from the wrong thread.
QCoreApplication::processEvents();
for (int i=0; i<numThreads; ++i) {
devices.append(new T);
threads.append(new QThread);
painters.append(new ThreadPainter(devices.at(i)));
painters.at(i)->moveToThread(threads.at(i));
painters.at(i)->connect(threads.at(i), SIGNAL(started()), painters.at(i), SLOT(draw()));
devices.at(i)->moveToThread(threads.at(i));
}
}
~PaintThreadManager() {
qDeleteAll(threads);
qDeleteAll(painters);
qDeleteAll(devices);
}
void start() {
for (int i=0; i<numThreads; ++i)
threads.at(i)->start();
}
bool areRunning() {
bool running = false;
for (int i=0; i<numThreads; ++i){
if (threads.at(i)->isRunning())
running = true;
}
return running;
}
bool failed() {
for (int i=0; i<numThreads; ++i) {
if (painters.at(i)->failed())
return true;
}
return false;
}
private:
QList<QThread *> threads;
QList<Device *> devices;
QList<ThreadPainter *> painters;
int numThreads;
};
/*
This test uses QPainter to draw onto different QGLWidgets in
different threads at the same time. The ThreadSafeGLWidget is
necessary to handle paint and resize events that might come from
the main thread at any time while the test is running. The resize
and paint events would cause makeCurrent() calls to be issued from
within the QGLWidget while the widget's context was current in
another thread, which would cause errors.
*/
void tst_QGLThreads::painterOnGLWidgetInThread()
{
if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL))
QSKIP("No platformsupport for ThreadedOpenGL");
if (!((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_0) ||
(QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_ES_Version_2_0))) {
QSKIP("The OpenGL based threaded QPainter tests requires OpenGL/ES 2.0.");
}
PaintThreadManager<GLWidgetWrapper> painterThreads(5);
painterThreads.start();
while (painterThreads.areRunning()) {
qApp->processEvents();
QThread::msleep(100);
}
QVERIFY(!painterThreads.failed());
}
/*
This test uses QPainter to draw onto different QPixmaps in
different threads at the same time.
*/
void tst_QGLThreads::painterOnPixmapInThread()
{
if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL)
|| !QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedPixmaps))
QSKIP("No platformsupport for ThreadedOpenGL or ThreadedPixmaps");
#ifdef Q_DEAD_CODE_FROM_QT4_X11
QSKIP("Drawing text in threads onto X11 drawables currently crashes on some X11 servers.");
#endif
PaintThreadManager<PixmapWrapper> painterThreads(5);
painterThreads.start();
while (painterThreads.areRunning()) {
qApp->processEvents();
QThread::msleep(100);
}
QVERIFY(!painterThreads.failed());
}
/* This test uses QPainter to draw onto different QGLPixelBuffer
objects in different threads at the same time.
*/
void tst_QGLThreads::painterOnPboInThread()
{
if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL))
QSKIP("No platformsupport for ThreadedOpenGL");
if (!((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_0) ||
(QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_ES_Version_2_0))) {
QSKIP("The OpenGL based threaded QPainter tests requires OpenGL/ES 2.0.");
}
if (!QGLPixelBuffer::hasOpenGLPbuffers()) {
QSKIP("This system doesn't support pbuffers.");
}
PaintThreadManager<PixelBufferWrapper> painterThreads(5);
painterThreads.start();
while (painterThreads.areRunning()) {
qApp->processEvents();
QThread::msleep(100);
}
QVERIFY(!painterThreads.failed());
}
/* This test uses QPainter to draw onto different
QGLFramebufferObjects (bound in a QGLWidget's context) in different
threads at the same time.
*/
void tst_QGLThreads::painterOnFboInThread()
{
if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL))
QSKIP("No platformsupport for ThreadedOpenGL");
if (!((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_0) ||
(QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_ES_Version_2_0))) {
QSKIP("The OpenGL based threaded QPainter tests requires OpenGL/ES 2.0.");
}
if (!QGLFramebufferObject::hasOpenGLFramebufferObjects()) {
QSKIP("This system doesn't support framebuffer objects.");
}
PaintThreadManager<FrameBufferObjectWrapper> painterThreads(5);
painterThreads.start();
while (painterThreads.areRunning()) {
qApp->processEvents();
QThread::msleep(100);
}
QVERIFY(!painterThreads.failed());
}
int main(int argc, char **argv)
{
QApplication::setAttribute(Qt::AA_X11InitThreads);
QApplication app(argc, argv);
QTEST_DISABLE_KEYPAD_NAVIGATION \
tst_QGLThreads tc;
return QTest::qExec(&tc, argc, argv);
}
#include "tst_qglthreads.moc"
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "parquet/stream_reader.h"
#include <fcntl.h>
#include <gtest/gtest.h>
#include <chrono>
#include <ctime>
#include <memory>
#include <utility>
#include "arrow/io/api.h"
#include "parquet/exception.h"
#include "parquet/test_util.h"
namespace parquet {
namespace test {
template <typename T>
using optional = StreamReader::optional<T>;
using arrow::util::nullopt;
struct TestData {
static void init() { std::time(&ts_offset_); }
static constexpr int num_rows = 2000;
static std::string GetString(const int i) { return "Str #" + std::to_string(i); }
static bool GetBool(const int i) { return i % 7 < 3; }
static char GetChar(const int i) { return i & 1 ? 'M' : 'F'; }
static std::array<char, 4> GetCharArray(const int i) {
return {'X', 'Y', 'Z', char('A' + i % 26)};
}
static int8_t GetInt8(const int i) { return static_cast<int8_t>((i % 256) - 128); }
static uint16_t GetUInt16(const int i) { return static_cast<uint16_t>(i); }
static int32_t GetInt32(const int i) { return 3 * i - 17; }
static uint64_t GetUInt64(const int i) { return (1ull << 40) + i * i + 101; }
static float GetFloat(const int i) { return 3.1415926535897f * i; }
static double GetDouble(const int i) { return 6.62607004e-34 * 3e8 * i; }
static std::chrono::microseconds GetChronoMicroseconds(const int i) {
return std::chrono::microseconds{(ts_offset_ + 3 * i) * 1000000ull + i};
}
static optional<bool> GetOptBool(const int i) {
if (i % 11 == 0) {
return nullopt;
}
return i % 7 < 3;
}
static optional<char> GetOptChar(const int i) {
if ((i + 1) % 11 == 1) {
return nullopt;
}
return i & 1 ? 'M' : 'F';
}
static optional<std::array<char, 4>> GetOptCharArray(const int i) {
if ((i + 2) % 11 == 1) {
return nullopt;
}
return std::array<char, 4>{{'X', 'Y', 'Z', char('A' + i % 26)}};
}
static optional<int8_t> GetOptInt8(const int i) {
if ((i + 3) % 11 == 1) {
return nullopt;
}
return static_cast<int8_t>((i % 256) - 128);
}
static optional<uint16_t> GetOptUInt16(const int i) {
if ((i + 4) % 11 == 1) {
return nullopt;
}
return static_cast<uint16_t>(i);
}
static optional<int32_t> GetOptInt32(const int i) {
if ((i + 5) % 11 == 1) {
return nullopt;
}
return 3 * i - 17;
}
static optional<uint64_t> GetOptUInt64(const int i) {
if ((i + 6) % 11 == 1) {
return nullopt;
}
return (1ull << 40) + i * i + 101;
}
static optional<std::string> GetOptString(const int i) {
if (i % 5 == 0) {
return nullopt;
}
return "Str #" + std::to_string(i);
}
static optional<float> GetOptFloat(const int i) {
if ((i + 1) % 3 == 0) {
return nullopt;
}
return 2.718281828459045f * i;
}
static optional<double> GetOptDouble(const int i) {
if ((i + 2) % 3 == 0) {
return nullopt;
}
return 6.62607004e-34 * 3e8 * i;
}
static optional<std::chrono::microseconds> GetOptChronoMicroseconds(const int i) {
if ((i + 2) % 7 == 0) {
return nullopt;
}
return std::chrono::microseconds{(ts_offset_ + 3 * i) * 1000000ull + i};
}
private:
static std::time_t ts_offset_;
};
std::time_t TestData::ts_offset_;
constexpr int TestData::num_rows;
class TestStreamReader : public ::testing::Test {
public:
TestStreamReader() { createTestFile(); }
protected:
const char* GetDataFile() const { return "stream_reader_test.parquet"; }
void SetUp() {
PARQUET_ASSIGN_OR_THROW(auto infile, arrow::io::ReadableFile::Open(GetDataFile()));
auto file_reader = parquet::ParquetFileReader::Open(infile);
reader_ = StreamReader{std::move(file_reader)};
}
void TearDown() { reader_ = StreamReader{}; }
std::shared_ptr<schema::GroupNode> GetSchema() {
schema::NodeVector fields;
fields.push_back(schema::PrimitiveNode::Make("bool_field", Repetition::REQUIRED,
Type::BOOLEAN, ConvertedType::NONE));
fields.push_back(schema::PrimitiveNode::Make("string_field", Repetition::REQUIRED,
Type::BYTE_ARRAY, ConvertedType::UTF8));
fields.push_back(schema::PrimitiveNode::Make("char_field", Repetition::REQUIRED,
Type::FIXED_LEN_BYTE_ARRAY,
ConvertedType::NONE, 1));
fields.push_back(schema::PrimitiveNode::Make("char[4]_field", Repetition::REQUIRED,
Type::FIXED_LEN_BYTE_ARRAY,
ConvertedType::NONE, 4));
fields.push_back(schema::PrimitiveNode::Make("int8_field", Repetition::REQUIRED,
Type::INT32, ConvertedType::INT_8));
fields.push_back(schema::PrimitiveNode::Make("uint16_field", Repetition::REQUIRED,
Type::INT32, ConvertedType::UINT_16));
fields.push_back(schema::PrimitiveNode::Make("int32_field", Repetition::REQUIRED,
Type::INT32, ConvertedType::INT_32));
fields.push_back(schema::PrimitiveNode::Make("uint64_field", Repetition::REQUIRED,
Type::INT64, ConvertedType::UINT_64));
fields.push_back(schema::PrimitiveNode::Make("chrono_microseconds_field",
Repetition::REQUIRED, Type::INT64,
ConvertedType::TIMESTAMP_MICROS));
fields.push_back(schema::PrimitiveNode::Make("float_field", Repetition::REQUIRED,
Type::FLOAT, ConvertedType::NONE));
fields.push_back(schema::PrimitiveNode::Make("double_field", Repetition::REQUIRED,
Type::DOUBLE, ConvertedType::NONE));
return std::static_pointer_cast<schema::GroupNode>(
schema::GroupNode::Make("schema", Repetition::REQUIRED, fields));
}
void createTestFile() {
PARQUET_ASSIGN_OR_THROW(auto outfile,
arrow::io::FileOutputStream::Open(GetDataFile()));
auto file_writer = ParquetFileWriter::Open(outfile, GetSchema());
StreamWriter os{std::move(file_writer)};
TestData::init();
for (auto i = 0; i < TestData::num_rows; ++i) {
os << TestData::GetBool(i);
os << TestData::GetString(i);
os << TestData::GetChar(i);
os << TestData::GetCharArray(i);
os << TestData::GetInt8(i);
os << TestData::GetUInt16(i);
os << TestData::GetInt32(i);
os << TestData::GetUInt64(i);
os << TestData::GetChronoMicroseconds(i);
os << TestData::GetFloat(i);
os << TestData::GetDouble(i);
os << EndRow;
}
}
StreamReader reader_;
};
TEST_F(TestStreamReader, DefaultConstructed) {
StreamReader os;
int i;
std::string s;
// N.B. Default constructor objects are not usable.
EXPECT_THROW(os >> i, ParquetException);
EXPECT_THROW(os >> s, ParquetException);
EXPECT_THROW(os >> EndRow, ParquetException);
EXPECT_EQ(true, os.eof());
EXPECT_EQ(0, os.current_column());
EXPECT_EQ(0, os.current_row());
EXPECT_EQ(0, os.num_columns());
EXPECT_EQ(0, os.num_rows());
// Skipping columns and rows is allowed.
//
EXPECT_EQ(0, os.SkipColumns(100));
EXPECT_EQ(0, os.SkipRows(100));
}
TEST_F(TestStreamReader, TypeChecking) {
bool b;
std::string s;
std::array<char, 4> char_array;
char c;
int8_t int8;
int16_t int16;
uint16_t uint16;
int32_t int32;
int64_t int64;
uint64_t uint64;
std::chrono::microseconds ts_us;
float f;
double d;
std::string str;
EXPECT_THROW(reader_ >> int8, ParquetException);
EXPECT_NO_THROW(reader_ >> b);
EXPECT_THROW(reader_ >> c, ParquetException);
EXPECT_NO_THROW(reader_ >> s);
EXPECT_THROW(reader_ >> s, ParquetException);
EXPECT_NO_THROW(reader_ >> c);
EXPECT_THROW(reader_ >> s, ParquetException);
EXPECT_NO_THROW(reader_ >> char_array);
EXPECT_THROW(reader_ >> int16, ParquetException);
EXPECT_NO_THROW(reader_ >> int8);
EXPECT_THROW(reader_ >> int16, ParquetException);
EXPECT_NO_THROW(reader_ >> uint16);
EXPECT_THROW(reader_ >> int64, ParquetException);
EXPECT_NO_THROW(reader_ >> int32);
EXPECT_THROW(reader_ >> int64, ParquetException);
EXPECT_NO_THROW(reader_ >> uint64);
EXPECT_THROW(reader_ >> uint64, ParquetException);
EXPECT_NO_THROW(reader_ >> ts_us);
EXPECT_THROW(reader_ >> d, ParquetException);
EXPECT_NO_THROW(reader_ >> f);
EXPECT_THROW(reader_ >> f, ParquetException);
EXPECT_NO_THROW(reader_ >> d);
EXPECT_NO_THROW(reader_ >> EndRow);
}
TEST_F(TestStreamReader, ValueChecking) {
bool b;
std::string str;
std::array<char, 4> char_array;
char c;
int8_t int8;
uint16_t uint16;
int32_t int32;
uint64_t uint64;
std::chrono::microseconds ts_us;
float f;
double d;
int i;
for (i = 0; !reader_.eof(); ++i) {
EXPECT_EQ(i, reader_.current_row());
reader_ >> b;
reader_ >> str;
reader_ >> c;
reader_ >> char_array;
reader_ >> int8;
reader_ >> uint16;
reader_ >> int32;
reader_ >> uint64;
reader_ >> ts_us;
reader_ >> f;
reader_ >> d;
reader_ >> EndRow;
EXPECT_EQ(b, TestData::GetBool(i)) << "index: " << i;
EXPECT_EQ(str, TestData::GetString(i)) << "index: " << i;
EXPECT_EQ(c, TestData::GetChar(i)) << "index: " << i;
EXPECT_EQ(char_array, TestData::GetCharArray(i)) << "index: " << i;
EXPECT_EQ(int8, TestData::GetInt8(i)) << "index: " << i;
EXPECT_EQ(uint16, TestData::GetUInt16(i)) << "index: " << i;
EXPECT_EQ(int32, TestData::GetInt32(i)) << "index: " << i;
EXPECT_EQ(uint64, TestData::GetUInt64(i)) << "index: " << i;
EXPECT_EQ(ts_us, TestData::GetChronoMicroseconds(i)) << "index: " << i;
EXPECT_FLOAT_EQ(f, TestData::GetFloat(i)) << "index: " << i;
EXPECT_DOUBLE_EQ(d, TestData::GetDouble(i)) << "index: " << i;
}
EXPECT_EQ(reader_.current_row(), TestData::num_rows);
EXPECT_EQ(reader_.num_rows(), TestData::num_rows);
EXPECT_EQ(i, TestData::num_rows);
}
TEST_F(TestStreamReader, ReadRequiredFieldAsOptionalField) {
/* Test that required fields can be read using optional types.
This can be useful if a schema is changed such that a field which
was optional is changed to be required. Applications can continue
to read the field as if it were still optional.
*/
optional<bool> opt_bool;
optional<std::string> opt_string;
optional<std::array<char, 4>> opt_char_array;
optional<char> opt_char;
optional<int8_t> opt_int8;
optional<uint16_t> opt_uint16;
optional<int32_t> opt_int32;
optional<uint64_t> opt_uint64;
optional<std::chrono::microseconds> opt_ts_us;
optional<float> opt_float;
optional<double> opt_double;
int i;
for (i = 0; !reader_.eof(); ++i) {
EXPECT_EQ(i, reader_.current_row());
reader_ >> opt_bool;
reader_ >> opt_string;
reader_ >> opt_char;
reader_ >> opt_char_array;
reader_ >> opt_int8;
reader_ >> opt_uint16;
reader_ >> opt_int32;
reader_ >> opt_uint64;
reader_ >> opt_ts_us;
reader_ >> opt_float;
reader_ >> opt_double;
reader_ >> EndRow;
EXPECT_EQ(*opt_bool, TestData::GetBool(i)) << "index: " << i;
EXPECT_EQ(*opt_string, TestData::GetString(i)) << "index: " << i;
EXPECT_EQ(*opt_char, TestData::GetChar(i)) << "index: " << i;
EXPECT_EQ(*opt_char_array, TestData::GetCharArray(i)) << "index: " << i;
EXPECT_EQ(*opt_int8, TestData::GetInt8(i)) << "index: " << i;
EXPECT_EQ(*opt_uint16, TestData::GetUInt16(i)) << "index: " << i;
EXPECT_EQ(*opt_int32, TestData::GetInt32(i)) << "index: " << i;
EXPECT_EQ(*opt_uint64, TestData::GetUInt64(i)) << "index: " << i;
EXPECT_EQ(*opt_ts_us, TestData::GetChronoMicroseconds(i)) << "index: " << i;
EXPECT_FLOAT_EQ(*opt_float, TestData::GetFloat(i)) << "index: " << i;
EXPECT_DOUBLE_EQ(*opt_double, TestData::GetDouble(i)) << "index: " << i;
}
EXPECT_EQ(reader_.current_row(), TestData::num_rows);
EXPECT_EQ(reader_.num_rows(), TestData::num_rows);
EXPECT_EQ(i, TestData::num_rows);
}
TEST_F(TestStreamReader, SkipRows) {
// Skipping zero and negative number of rows is ok.
//
EXPECT_EQ(0, reader_.SkipRows(0));
EXPECT_EQ(0, reader_.SkipRows(-100));
EXPECT_EQ(false, reader_.eof());
EXPECT_EQ(0, reader_.current_row());
EXPECT_EQ(TestData::num_rows, reader_.num_rows());
const int iter_num_rows_to_read = 3;
const int iter_num_rows_to_skip = 13;
int num_rows_read = 0;
int i = 0;
int num_iterations;
for (num_iterations = 0; !reader_.eof(); ++num_iterations) {
// Each iteration of this loop reads some rows (iter_num_rows_to_read
// are read) and then skips some rows (iter_num_rows_to_skip will be
// skipped).
// The loop variable i is the current row being read.
// Loop variable j is used just to count the number of rows to
// read.
bool b;
std::string s;
std::array<char, 4> char_array;
char c;
int8_t int8;
uint16_t uint16;
int32_t int32;
uint64_t uint64;
std::chrono::microseconds ts_us;
float f;
double d;
std::string str;
for (int j = 0; !reader_.eof() && (j < iter_num_rows_to_read); ++i, ++j) {
EXPECT_EQ(i, reader_.current_row());
reader_ >> b;
reader_ >> s;
reader_ >> c;
reader_ >> char_array;
reader_ >> int8;
reader_ >> uint16;
// Not allowed to skip row once reading columns has started.
EXPECT_THROW(reader_.SkipRows(1), ParquetException);
reader_ >> int32;
reader_ >> uint64;
reader_ >> ts_us;
reader_ >> f;
reader_ >> d;
reader_ >> EndRow;
num_rows_read += 1;
EXPECT_EQ(b, TestData::GetBool(i));
EXPECT_EQ(s, TestData::GetString(i));
EXPECT_EQ(c, TestData::GetChar(i));
EXPECT_EQ(char_array, TestData::GetCharArray(i));
EXPECT_EQ(int8, TestData::GetInt8(i));
EXPECT_EQ(uint16, TestData::GetUInt16(i));
EXPECT_EQ(int32, TestData::GetInt32(i));
EXPECT_EQ(uint64, TestData::GetUInt64(i));
EXPECT_EQ(ts_us, TestData::GetChronoMicroseconds(i));
EXPECT_FLOAT_EQ(f, TestData::GetFloat(i));
EXPECT_DOUBLE_EQ(d, TestData::GetDouble(i));
}
EXPECT_EQ(iter_num_rows_to_skip, reader_.SkipRows(iter_num_rows_to_skip));
i += iter_num_rows_to_skip;
}
EXPECT_EQ(TestData::num_rows, reader_.current_row());
EXPECT_EQ(num_rows_read, num_iterations * iter_num_rows_to_read);
// Skipping rows at eof is allowed.
//
EXPECT_EQ(0, reader_.SkipRows(100));
}
TEST_F(TestStreamReader, SkipAllRows) {
EXPECT_EQ(false, reader_.eof());
EXPECT_EQ(0, reader_.current_row());
EXPECT_EQ(reader_.num_rows(), reader_.SkipRows(2 * reader_.num_rows()));
EXPECT_EQ(true, reader_.eof());
EXPECT_EQ(reader_.num_rows(), reader_.current_row());
}
TEST_F(TestStreamReader, SkipColumns) {
bool b;
std::string s;
std::array<char, 4> char_array;
char c;
int8_t int8;
uint16_t uint16;
int32_t int32;
uint64_t uint64;
std::chrono::microseconds ts_us;
float f;
double d;
std::string str;
int i;
// Skipping zero and negative number of columns is ok.
//
EXPECT_EQ(0, reader_.SkipColumns(0));
EXPECT_EQ(0, reader_.SkipColumns(-100));
for (i = 0; !reader_.eof(); ++i) {
EXPECT_EQ(i, reader_.current_row());
EXPECT_EQ(0, reader_.current_column());
// Skip all columns every 31 rows.
if (i % 31 == 0) {
EXPECT_EQ(reader_.num_columns(), reader_.SkipColumns(reader_.num_columns()))
<< "index: " << i;
EXPECT_EQ(reader_.num_columns(), reader_.current_column()) << "index: " << i;
reader_ >> EndRow;
continue;
}
reader_ >> b;
EXPECT_EQ(b, TestData::GetBool(i)) << "index: " << i;
EXPECT_EQ(1, reader_.current_column()) << "index: " << i;
// Skip the next column every 3 rows.
if (i % 3 == 0) {
EXPECT_EQ(1, reader_.SkipColumns(1)) << "index: " << i;
} else {
reader_ >> s;
EXPECT_EQ(s, TestData::GetString(i)) << "index: " << i;
}
EXPECT_EQ(2, reader_.current_column()) << "index: " << i;
reader_ >> c;
EXPECT_EQ(c, TestData::GetChar(i)) << "index: " << i;
EXPECT_EQ(3, reader_.current_column()) << "index: " << i;
reader_ >> char_array;
EXPECT_EQ(char_array, TestData::GetCharArray(i)) << "index: " << i;
EXPECT_EQ(4, reader_.current_column()) << "index: " << i;
reader_ >> int8;
EXPECT_EQ(int8, TestData::GetInt8(i)) << "index: " << i;
EXPECT_EQ(5, reader_.current_column()) << "index: " << i;
// Skip the next 3 columns every 7 rows.
if (i % 7 == 0) {
EXPECT_EQ(3, reader_.SkipColumns(3)) << "index: " << i;
} else {
reader_ >> uint16;
EXPECT_EQ(uint16, TestData::GetUInt16(i)) << "index: " << i;
EXPECT_EQ(6, reader_.current_column()) << "index: " << i;
reader_ >> int32;
EXPECT_EQ(int32, TestData::GetInt32(i)) << "index: " << i;
EXPECT_EQ(7, reader_.current_column()) << "index: " << i;
reader_ >> uint64;
EXPECT_EQ(uint64, TestData::GetUInt64(i)) << "index: " << i;
}
EXPECT_EQ(8, reader_.current_column());
reader_ >> ts_us;
EXPECT_EQ(ts_us, TestData::GetChronoMicroseconds(i)) << "index: " << i;
EXPECT_EQ(9, reader_.current_column()) << "index: " << i;
// Skip 301 columns (i.e. all remaining) every 11 rows.
if (i % 11 == 0) {
EXPECT_EQ(2, reader_.SkipColumns(301)) << "index: " << i;
} else {
reader_ >> f;
EXPECT_FLOAT_EQ(f, TestData::GetFloat(i)) << "index: " << i;
EXPECT_EQ(10, reader_.current_column()) << "index: " << i;
reader_ >> d;
EXPECT_DOUBLE_EQ(d, TestData::GetDouble(i)) << "index: " << i;
}
EXPECT_EQ(11, reader_.current_column()) << "index: " << i;
reader_ >> EndRow;
}
EXPECT_EQ(i, TestData::num_rows);
EXPECT_EQ(reader_.current_row(), TestData::num_rows);
// Skipping columns at eof is allowed.
//
EXPECT_EQ(0, reader_.SkipColumns(100));
}
class TestOptionalFields : public ::testing::Test {
public:
TestOptionalFields() { createTestFile(); }
protected:
const char* GetDataFile() const { return "stream_reader_test_optional_fields.parquet"; }
void SetUp() {
PARQUET_ASSIGN_OR_THROW(auto infile, arrow::io::ReadableFile::Open(GetDataFile()));
auto file_reader = ParquetFileReader::Open(infile);
reader_ = StreamReader{std::move(file_reader)};
}
void TearDown() { reader_ = StreamReader{}; }
std::shared_ptr<schema::GroupNode> GetSchema() {
schema::NodeVector fields;
fields.push_back(schema::PrimitiveNode::Make("bool_field", Repetition::OPTIONAL,
Type::BOOLEAN, ConvertedType::NONE));
fields.push_back(schema::PrimitiveNode::Make("string_field", Repetition::OPTIONAL,
Type::BYTE_ARRAY, ConvertedType::UTF8));
fields.push_back(schema::PrimitiveNode::Make("char_field", Repetition::OPTIONAL,
Type::FIXED_LEN_BYTE_ARRAY,
ConvertedType::NONE, 1));
fields.push_back(schema::PrimitiveNode::Make("char[4]_field", Repetition::OPTIONAL,
Type::FIXED_LEN_BYTE_ARRAY,
ConvertedType::NONE, 4));
fields.push_back(schema::PrimitiveNode::Make("int8_field", Repetition::OPTIONAL,
Type::INT32, ConvertedType::INT_8));
fields.push_back(schema::PrimitiveNode::Make("uint16_field", Repetition::OPTIONAL,
Type::INT32, ConvertedType::UINT_16));
fields.push_back(schema::PrimitiveNode::Make("int32_field", Repetition::OPTIONAL,
Type::INT32, ConvertedType::INT_32));
fields.push_back(schema::PrimitiveNode::Make("uint64_field", Repetition::OPTIONAL,
Type::INT64, ConvertedType::UINT_64));
fields.push_back(schema::PrimitiveNode::Make("chrono_microseconds_field",
Repetition::OPTIONAL, Type::INT64,
ConvertedType::TIMESTAMP_MICROS));
fields.push_back(schema::PrimitiveNode::Make("float_field", Repetition::OPTIONAL,
Type::FLOAT, ConvertedType::NONE));
fields.push_back(schema::PrimitiveNode::Make("double_field", Repetition::OPTIONAL,
Type::DOUBLE, ConvertedType::NONE));
return std::static_pointer_cast<schema::GroupNode>(
schema::GroupNode::Make("schema", Repetition::REQUIRED, fields));
}
void createTestFile() {
PARQUET_ASSIGN_OR_THROW(auto outfile,
arrow::io::FileOutputStream::Open(GetDataFile()));
StreamWriter os{ParquetFileWriter::Open(outfile, GetSchema())};
TestData::init();
for (auto i = 0; i < TestData::num_rows; ++i) {
os << TestData::GetOptBool(i);
os << TestData::GetOptString(i);
os << TestData::GetOptChar(i);
os << TestData::GetOptCharArray(i);
os << TestData::GetOptInt8(i);
os << TestData::GetOptUInt16(i);
os << TestData::GetOptInt32(i);
os << TestData::GetOptUInt64(i);
os << TestData::GetOptChronoMicroseconds(i);
os << TestData::GetOptFloat(i);
os << TestData::GetOptDouble(i);
os << EndRow;
}
}
StreamReader reader_;
};
TEST_F(TestOptionalFields, ValueChecking) {
optional<bool> opt_bool;
optional<std::string> opt_string;
optional<std::array<char, 4>> opt_char_array;
optional<char> opt_char;
optional<int8_t> opt_int8;
optional<uint16_t> opt_uint16;
optional<int32_t> opt_int32;
optional<uint64_t> opt_uint64;
optional<std::chrono::microseconds> opt_ts_us;
optional<float> opt_float;
optional<double> opt_double;
int i;
for (i = 0; !reader_.eof(); ++i) {
EXPECT_EQ(i, reader_.current_row());
reader_ >> opt_bool;
reader_ >> opt_string;
reader_ >> opt_char;
reader_ >> opt_char_array;
reader_ >> opt_int8;
reader_ >> opt_uint16;
reader_ >> opt_int32;
reader_ >> opt_uint64;
reader_ >> opt_ts_us;
reader_ >> opt_float;
reader_ >> opt_double;
reader_ >> EndRow;
EXPECT_EQ(opt_bool, TestData::GetOptBool(i)) << "index: " << i;
EXPECT_EQ(opt_string, TestData::GetOptString(i)) << "index: " << i;
EXPECT_EQ(opt_char, TestData::GetOptChar(i)) << "index: " << i;
EXPECT_EQ(opt_char_array, TestData::GetOptCharArray(i)) << "index: " << i;
EXPECT_EQ(opt_int8, TestData::GetOptInt8(i)) << "index: " << i;
EXPECT_EQ(opt_uint16, TestData::GetOptUInt16(i)) << "index: " << i;
EXPECT_EQ(opt_int32, TestData::GetOptInt32(i)) << "index: " << i;
EXPECT_EQ(opt_uint64, TestData::GetOptUInt64(i)) << "index: " << i;
EXPECT_EQ(opt_ts_us, TestData::GetOptChronoMicroseconds(i)) << "index: " << i;
if (opt_float && TestData::GetOptFloat(i)) {
EXPECT_FLOAT_EQ(*opt_float, *TestData::GetOptFloat(i)) << "index: " << i;
} else {
EXPECT_EQ(opt_float, TestData::GetOptFloat(i)) << "index: " << i;
}
if (opt_double && TestData::GetOptDouble(i)) {
EXPECT_DOUBLE_EQ(*opt_double, *TestData::GetOptDouble(i)) << "index: " << i;
} else {
EXPECT_EQ(opt_double, TestData::GetOptDouble(i)) << "index: " << i;
}
}
EXPECT_EQ(reader_.current_row(), TestData::num_rows);
EXPECT_EQ(reader_.num_rows(), TestData::num_rows);
EXPECT_EQ(i, TestData::num_rows);
}
TEST_F(TestOptionalFields, ReadOptionalFieldAsRequiredField) {
/* Test that optional fields can be read using non-optional types
_provided_ that the optional value is available.
This can be useful if a schema is changed such that a required
field beomes optional. Applications can continue reading the
field as if it were mandatory and do not need to be changed if the
field value is always provided.
Of course if the optional value is not present, then the read will
fail by throwing an exception. This is also tested below.
*/
bool b;
std::string s;
std::array<char, 4> char_array;
char c;
int8_t int8;
uint16_t uint16;
int32_t int32;
uint64_t uint64;
std::chrono::microseconds ts_us;
float f;
double d;
std::string str;
int i;
for (i = 0; !reader_.eof(); ++i) {
EXPECT_EQ(i, reader_.current_row());
if (TestData::GetOptBool(i)) {
reader_ >> b;
EXPECT_EQ(b, *TestData::GetOptBool(i)) << "index: " << i;
} else {
EXPECT_THROW(reader_ >> b, ParquetException) << "index: " << i;
}
if (TestData::GetOptString(i)) {
reader_ >> s;
EXPECT_EQ(s, *TestData::GetOptString(i)) << "index: " << i;
} else {
EXPECT_THROW(reader_ >> s, ParquetException) << "index: " << i;
}
if (TestData::GetOptChar(i)) {
reader_ >> c;
EXPECT_EQ(c, *TestData::GetOptChar(i)) << "index: " << i;
} else {
EXPECT_THROW(reader_ >> c, ParquetException) << "index: " << i;
}
if (TestData::GetOptCharArray(i)) {
reader_ >> char_array;
EXPECT_EQ(char_array, *TestData::GetOptCharArray(i)) << "index: " << i;
} else {
EXPECT_THROW(reader_ >> char_array, ParquetException) << "index: " << i;
}
if (TestData::GetOptInt8(i)) {
reader_ >> int8;
EXPECT_EQ(int8, *TestData::GetOptInt8(i)) << "index: " << i;
} else {
EXPECT_THROW(reader_ >> int8, ParquetException) << "index: " << i;
}
if (TestData::GetOptUInt16(i)) {
reader_ >> uint16;
EXPECT_EQ(uint16, *TestData::GetOptUInt16(i)) << "index: " << i;
} else {
EXPECT_THROW(reader_ >> uint16, ParquetException) << "index: " << i;
}
if (TestData::GetOptInt32(i)) {
reader_ >> int32;
EXPECT_EQ(int32, *TestData::GetOptInt32(i)) << "index: " << i;
} else {
EXPECT_THROW(reader_ >> int32, ParquetException) << "index: " << i;
}
if (TestData::GetOptUInt64(i)) {
reader_ >> uint64;
EXPECT_EQ(uint64, *TestData::GetOptUInt64(i)) << "index: " << i;
} else {
EXPECT_THROW(reader_ >> uint64, ParquetException) << "index: " << i;
}
if (TestData::GetOptChronoMicroseconds(i)) {
reader_ >> ts_us;
EXPECT_EQ(ts_us, *TestData::GetOptChronoMicroseconds(i)) << "index: " << i;
} else {
EXPECT_THROW(reader_ >> ts_us, ParquetException) << "index: " << i;
}
if (TestData::GetOptFloat(i)) {
reader_ >> f;
EXPECT_EQ(f, *TestData::GetOptFloat(i)) << "index: " << i;
} else {
EXPECT_THROW(reader_ >> f, ParquetException) << "index: " << i;
}
if (TestData::GetOptDouble(i)) {
reader_ >> d;
EXPECT_EQ(d, *TestData::GetOptDouble(i)) << "index: " << i;
} else {
EXPECT_THROW(reader_ >> d, ParquetException) << "index: " << i;
}
reader_ >> EndRow;
}
}
class TestReadingDataFiles : public ::testing::Test {
protected:
std::string GetDataFile(const std::string& filename) const {
return std::string(get_data_dir()) + "/" + filename;
}
};
TEST_F(TestReadingDataFiles, AllTypesPlain) {
PARQUET_ASSIGN_OR_THROW(
auto infile, arrow::io::ReadableFile::Open(GetDataFile("alltypes_plain.parquet")));
auto file_reader = ParquetFileReader::Open(infile);
auto reader = StreamReader{std::move(file_reader)};
int32_t c0;
bool c1;
int32_t c2;
int32_t c3;
int32_t c4;
int64_t c5;
float c6;
double c7;
std::string c8;
std::string c9;
const char* expected_date_str[] = {"03/01/09", "03/01/09", "04/01/09", "04/01/09",
"02/01/09", "02/01/09", "01/01/09", "01/01/09"};
int i;
for (i = 0; !reader.eof(); ++i) {
reader >> c0 >> c1 >> c2 >> c3 >> c4 >> c5;
reader >> c6 >> c7;
reader >> c8 >> c9;
reader.SkipColumns(1); // Skip column with unsupported 96-bit type
reader >> EndRow;
EXPECT_EQ(c1, (i & 1) == 0);
EXPECT_EQ(c2, i & 1);
EXPECT_EQ(c3, i & 1);
EXPECT_EQ(c4, i & 1);
EXPECT_EQ(c5, i & 1 ? 10 : 0);
EXPECT_FLOAT_EQ(c6, i & 1 ? 1.1f : 0.f);
EXPECT_DOUBLE_EQ(c7, i & 1 ? 10.1 : 0.);
ASSERT_LT(static_cast<std::size_t>(i),
sizeof(expected_date_str) / sizeof(expected_date_str[0]));
EXPECT_EQ(c8, expected_date_str[i]);
EXPECT_EQ(c9, i & 1 ? "1" : "0");
}
EXPECT_EQ(i, sizeof(expected_date_str) / sizeof(expected_date_str[0]));
}
TEST_F(TestReadingDataFiles, Int32Decimal) {
PARQUET_ASSIGN_OR_THROW(
auto infile, arrow::io::ReadableFile::Open(GetDataFile("int32_decimal.parquet")));
auto file_reader = ParquetFileReader::Open(infile);
auto reader = StreamReader{std::move(file_reader)};
int32_t x;
int i;
for (i = 1; !reader.eof(); ++i) {
reader >> x >> EndRow;
EXPECT_EQ(x, i * 100);
}
EXPECT_EQ(i, 25);
}
TEST_F(TestReadingDataFiles, Int64Decimal) {
PARQUET_ASSIGN_OR_THROW(
auto infile, arrow::io::ReadableFile::Open(GetDataFile("int64_decimal.parquet")));
auto file_reader = ParquetFileReader::Open(infile);
auto reader = StreamReader{std::move(file_reader)};
int64_t x;
int i;
for (i = 1; !reader.eof(); ++i) {
reader >> x >> EndRow;
EXPECT_EQ(x, i * 100);
}
EXPECT_EQ(i, 25);
}
} // namespace test
} // namespace parquet
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.h"
#include <errno.h>
#include <fcntl.h>
#include <linux/net.h>
#include <sched.h>
#include <signal.h>
#include <stdint.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include "base/logging.h"
#include "base/macros.h"
#include "base/synchronization/synchronization_buildflags.h"
#include "build/build_config.h"
#include "sandbox/linux/bpf_dsl/bpf_dsl.h"
#include "sandbox/linux/bpf_dsl/seccomp_macros.h"
#include "sandbox/linux/seccomp-bpf-helpers/sigsys_handlers.h"
#include "sandbox/linux/seccomp-bpf/sandbox_bpf.h"
#include "sandbox/linux/system_headers/linux_futex.h"
#include "sandbox/linux/system_headers/linux_syscalls.h"
#include "sandbox/linux/system_headers/linux_time.h"
// PNaCl toolchain does not provide sys/ioctl.h and sys/ptrace.h headers.
#if !defined(OS_NACL_NONSFI)
#include <sys/ioctl.h>
#include <sys/ptrace.h>
#if defined(OS_LINUX) && !defined(OS_CHROMEOS) && !defined(__arm__) && \
!defined(__aarch64__) && !defined(PTRACE_GET_THREAD_AREA)
// Also include asm/ptrace-abi.h since ptrace.h in older libc (for instance
// the one in Ubuntu 16.04 LTS) is missing PTRACE_GET_THREAD_AREA.
// asm/ptrace-abi.h doesn't exist on arm32 and PTRACE_GET_THREAD_AREA isn't
// defined on aarch64, so don't try to include this on those platforms.
#include <asm/ptrace-abi.h>
#endif
#endif // !OS_NACL_NONSFI
#if defined(OS_ANDROID)
#if !defined(F_DUPFD_CLOEXEC)
#define F_DUPFD_CLOEXEC (F_LINUX_SPECIFIC_BASE + 6)
#endif
#if !defined(PR_SET_TIMERSLACK)
#define PR_SET_TIMERSLACK 29
#endif
// https://android.googlesource.com/platform/bionic/+/lollipop-release/libc/private/bionic_prctl.h
#if !defined(PR_SET_VMA)
#define PR_SET_VMA 0x53564d41
#endif
#ifndef PR_SET_PTRACER
#define PR_SET_PTRACER 0x59616d61
#endif
#endif // defined(OS_ANDROID)
#if defined(__arm__) && !defined(MAP_STACK)
#define MAP_STACK 0x20000 // Daisy build environment has old headers.
#endif
#if defined(__mips__) && !defined(MAP_STACK)
#define MAP_STACK 0x40000
#endif
namespace {
inline bool IsArchitectureX86_64() {
#if defined(__x86_64__)
return true;
#else
return false;
#endif
}
inline bool IsArchitectureI386() {
#if defined(__i386__)
return true;
#else
return false;
#endif
}
inline bool IsAndroid() {
#if defined(OS_ANDROID)
return true;
#else
return false;
#endif
}
inline bool IsArchitectureMips() {
#if defined(__mips__)
return true;
#else
return false;
#endif
}
// Ubuntu's version of glibc has a race condition in sem_post that can cause
// it to call futex(2) with bogus op arguments. To workaround this, we need
// to allow those futex(2) calls to fail with EINVAL, instead of crashing the
// process. See crbug.com/598471.
inline bool IsBuggyGlibcSemPost() {
#if defined(LIBC_GLIBC) && !defined(OS_CHROMEOS)
return true;
#else
return false;
#endif
}
} // namespace.
#define CASES SANDBOX_BPF_DSL_CASES
using sandbox::bpf_dsl::Allow;
using sandbox::bpf_dsl::Arg;
using sandbox::bpf_dsl::BoolExpr;
using sandbox::bpf_dsl::Error;
using sandbox::bpf_dsl::If;
using sandbox::bpf_dsl::ResultExpr;
namespace sandbox {
#if !defined(OS_NACL_NONSFI)
// Allow Glibc's and Android pthread creation flags, crash on any other
// thread creation attempts and EPERM attempts to use neither
// CLONE_VM nor CLONE_THREAD (all fork implementations), unless CLONE_VFORK is
// present (as in newer versions of posix_spawn).
ResultExpr RestrictCloneToThreadsAndEPERMFork() {
const Arg<unsigned long> flags(0);
// TODO(mdempsky): Extend DSL to support (flags & ~mask1) == mask2.
const uint64_t kAndroidCloneMask = CLONE_VM | CLONE_FS | CLONE_FILES |
CLONE_SIGHAND | CLONE_THREAD |
CLONE_SYSVSEM;
const uint64_t kObsoleteAndroidCloneMask = kAndroidCloneMask | CLONE_DETACHED;
const uint64_t kGlibcPthreadFlags =
CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD |
CLONE_SYSVSEM | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID;
const BoolExpr glibc_test = flags == kGlibcPthreadFlags;
const BoolExpr android_test =
AnyOf(flags == kAndroidCloneMask, flags == kObsoleteAndroidCloneMask,
flags == kGlibcPthreadFlags);
// The following two flags are the two important flags in any vfork-emulating
// clone call. EPERM any clone call that contains both of them.
const uint64_t kImportantCloneVforkFlags = CLONE_VFORK | CLONE_VM;
const BoolExpr is_fork_or_clone_vfork =
AnyOf((flags & (CLONE_VM | CLONE_THREAD)) == 0,
(flags & kImportantCloneVforkFlags) == kImportantCloneVforkFlags);
return If(IsAndroid() ? android_test : glibc_test, Allow())
.ElseIf(is_fork_or_clone_vfork, Error(EPERM))
.Else(CrashSIGSYSClone());
}
ResultExpr RestrictPrctl() {
// Will need to add seccomp compositing in the future. PR_SET_PTRACER is
// used by breakpad but not needed anymore.
const Arg<int> option(0);
return Switch(option)
.CASES((PR_GET_NAME, PR_SET_NAME, PR_GET_DUMPABLE, PR_SET_DUMPABLE
#if defined(OS_ANDROID)
, PR_SET_VMA, PR_SET_PTRACER, PR_SET_TIMERSLACK
, PR_GET_NO_NEW_PRIVS
// Enable PR_SET_TIMERSLACK_PID, an Android custom prctl which is used in:
// https://android.googlesource.com/platform/system/core/+/lollipop-release/libcutils/sched_policy.c.
// Depending on the Android kernel version, this prctl may have different
// values. Since we don't know the correct value for the running kernel, we must
// allow them all.
//
// The effect is:
// On 3.14 kernels, this allows PR_SET_TIMERSLACK_PID and 43 and 127 (invalid
// prctls which will return EINVAL)
// On 3.18 kernels, this allows PR_SET_TIMERSLACK_PID, PR_SET_THP_DISABLE, and
// 127 (invalid).
// On 4.1 kernels and up, this allows PR_SET_TIMERSLACK_PID, PR_SET_THP_DISABLE,
// and PR_MPX_ENABLE_MANAGEMENT.
// https://android.googlesource.com/kernel/common/+/android-3.14/include/uapi/linux/prctl.h
#define PR_SET_TIMERSLACK_PID_1 41
// https://android.googlesource.com/kernel/common/+/android-3.18/include/uapi/linux/prctl.h
#define PR_SET_TIMERSLACK_PID_2 43
// https://android.googlesource.com/kernel/common/+/android-4.1/include/uapi/linux/prctl.h and up
#define PR_SET_TIMERSLACK_PID_3 127
, PR_SET_TIMERSLACK_PID_1
, PR_SET_TIMERSLACK_PID_2
, PR_SET_TIMERSLACK_PID_3
#endif // defined(OS_ANDROID)
),
Allow())
.Default(CrashSIGSYSPrctl());
}
ResultExpr RestrictIoctl() {
const Arg<int> request(1);
return Switch(request).CASES((TCGETS, FIONREAD), Allow()).Default(
CrashSIGSYSIoctl());
}
ResultExpr RestrictMmapFlags() {
// The flags you see are actually the allowed ones, and the variable is a
// "denied" mask because of the negation operator.
// Significantly, we don't permit MAP_HUGETLB, or the newer flags such as
// MAP_POPULATE.
// TODO(davidung), remove MAP_DENYWRITE with updated Tegra libraries.
const uint64_t kAllowedMask = MAP_SHARED | MAP_PRIVATE | MAP_ANONYMOUS |
MAP_STACK | MAP_NORESERVE | MAP_FIXED |
MAP_DENYWRITE;
const Arg<int> flags(3);
return If((flags & ~kAllowedMask) == 0, Allow()).Else(CrashSIGSYS());
}
ResultExpr RestrictMprotectFlags() {
// The flags you see are actually the allowed ones, and the variable is a
// "denied" mask because of the negation operator.
// Significantly, we don't permit weird undocumented flags such as
// PROT_GROWSDOWN.
const uint64_t kAllowedMask = PROT_READ | PROT_WRITE | PROT_EXEC;
const Arg<int> prot(2);
return If((prot & ~kAllowedMask) == 0, Allow()).Else(CrashSIGSYS());
}
ResultExpr RestrictFcntlCommands() {
// We also restrict the flags in F_SETFL. We don't want to permit flags with
// a history of trouble such as O_DIRECT. The flags you see are actually the
// allowed ones, and the variable is a "denied" mask because of the negation
// operator.
// Glibc overrides the kernel's O_LARGEFILE value. Account for this.
uint64_t kOLargeFileFlag = O_LARGEFILE;
if (IsArchitectureX86_64() || IsArchitectureI386() || IsArchitectureMips())
kOLargeFileFlag = 0100000;
const Arg<int> cmd(1);
const Arg<long> long_arg(2);
const uint64_t kAllowedMask = O_ACCMODE | O_APPEND | O_NONBLOCK | O_SYNC |
kOLargeFileFlag | O_CLOEXEC | O_NOATIME;
return Switch(cmd)
.CASES((F_GETFL,
F_GETFD,
F_SETFD,
F_SETLK,
F_SETLKW,
F_GETLK,
F_DUPFD,
F_DUPFD_CLOEXEC),
Allow())
.Case(F_SETFL,
If((long_arg & ~kAllowedMask) == 0, Allow()).Else(CrashSIGSYS()))
.Default(CrashSIGSYS());
}
#if defined(__i386__) || defined(__mips__)
ResultExpr RestrictSocketcallCommand() {
// Unfortunately, we are unable to restrict the first parameter to
// socketpair(2). Whilst initially sounding bad, it's noteworthy that very
// few protocols actually support socketpair(2). The scary call that we're
// worried about, socket(2), remains blocked.
const Arg<int> call(0);
return Switch(call)
.CASES((SYS_SOCKETPAIR,
SYS_SHUTDOWN,
SYS_RECV,
SYS_SEND,
SYS_RECVFROM,
SYS_SENDTO,
SYS_RECVMSG,
SYS_SENDMSG),
Allow())
.Default(Error(EPERM));
}
#endif
ResultExpr RestrictKillTarget(pid_t target_pid, int sysno) {
switch (sysno) {
case __NR_kill:
case __NR_tgkill: {
const Arg<pid_t> pid(0);
return If(pid == target_pid, Allow()).Else(CrashSIGSYSKill());
}
case __NR_tkill:
return CrashSIGSYSKill();
default:
NOTREACHED();
return CrashSIGSYS();
}
}
ResultExpr RestrictFutex() {
const uint64_t kAllowedFutexFlags = FUTEX_PRIVATE_FLAG | FUTEX_CLOCK_REALTIME;
const Arg<int> op(1);
return Switch(op & ~kAllowedFutexFlags)
.CASES((FUTEX_WAIT, FUTEX_WAKE, FUTEX_REQUEUE, FUTEX_CMP_REQUEUE,
#if BUILDFLAG(ENABLE_MUTEX_PRIORITY_INHERITANCE)
// Enable priority-inheritance operations.
FUTEX_LOCK_PI, FUTEX_UNLOCK_PI, FUTEX_TRYLOCK_PI,
FUTEX_WAIT_REQUEUE_PI, FUTEX_CMP_REQUEUE_PI,
#endif // BUILDFLAG(ENABLE_MUTEX_PRIORITY_INHERITANCE)
FUTEX_WAKE_OP, FUTEX_WAIT_BITSET, FUTEX_WAKE_BITSET),
Allow())
.Default(IsBuggyGlibcSemPost() ? Error(EINVAL) : CrashSIGSYSFutex());
}
ResultExpr RestrictGetSetpriority(pid_t target_pid) {
const Arg<int> which(0);
const Arg<int> who(1);
return If(which == PRIO_PROCESS,
Switch(who).CASES((0, target_pid), Allow()).Default(Error(EPERM)))
.Else(CrashSIGSYS());
}
ResultExpr RestrictSchedTarget(pid_t target_pid, int sysno) {
switch (sysno) {
case __NR_sched_getaffinity:
case __NR_sched_getattr:
case __NR_sched_getparam:
case __NR_sched_getscheduler:
case __NR_sched_rr_get_interval:
case __NR_sched_setaffinity:
case __NR_sched_setattr:
case __NR_sched_setparam:
case __NR_sched_setscheduler: {
const Arg<pid_t> pid(0);
return Switch(pid)
.CASES((0, target_pid), Allow())
.Default(RewriteSchedSIGSYS());
}
default:
NOTREACHED();
return CrashSIGSYS();
}
}
ResultExpr RestrictPrlimit64(pid_t target_pid) {
const Arg<pid_t> pid(0);
return Switch(pid).CASES((0, target_pid), Allow()).Default(CrashSIGSYS());
}
ResultExpr RestrictGetrusage() {
const Arg<int> who(0);
return If(AnyOf(who == RUSAGE_SELF, who == RUSAGE_THREAD), Allow())
.Else(CrashSIGSYS());
}
#endif // !defined(OS_NACL_NONSFI)
ResultExpr RestrictClockID() {
static_assert(4 == sizeof(clockid_t), "clockid_t is not 32bit");
const Arg<clockid_t> clockid(0);
// Clock IDs < 0 are per pid/tid or are clockfds.
const unsigned int kIsPidBit = 1u<<31;
return
If((clockid & kIsPidBit) == 0,
Switch(clockid).CASES((
CLOCK_BOOTTIME,
CLOCK_MONOTONIC,
CLOCK_MONOTONIC_COARSE,
CLOCK_MONOTONIC_RAW,
CLOCK_PROCESS_CPUTIME_ID,
CLOCK_REALTIME,
CLOCK_REALTIME_COARSE,
CLOCK_THREAD_CPUTIME_ID),
Allow())
.Default(CrashSIGSYS()))
#if defined(OS_ANDROID)
// Allow per-pid and per-tid clocks.
.ElseIf((clockid & CPUCLOCK_CLOCK_MASK) != CLOCKFD, Allow())
#endif
.Else(CrashSIGSYS());
}
#if !defined(GRND_NONBLOCK)
#define GRND_NONBLOCK 1
#endif
ResultExpr RestrictGetRandom() {
const Arg<unsigned int> flags(2);
const unsigned int kGoodFlags = GRND_NONBLOCK;
return If((flags & ~kGoodFlags) == 0, Allow()).Else(CrashSIGSYS());
}
ResultExpr RestrictPrlimit(pid_t target_pid) {
const Arg<pid_t> pid(0);
// Only allow operations for the current process.
return If(AnyOf(pid == 0, pid == target_pid), Allow()).Else(Error(EPERM));
}
ResultExpr RestrictPrlimitToGetrlimit(pid_t target_pid) {
const Arg<pid_t> pid(0);
const Arg<uintptr_t> new_limit(2);
// Only allow operations for the current process, and only with |new_limit|
// set to null.
return If(AllOf(new_limit == 0, AnyOf(pid == 0, pid == target_pid)), Allow())
.Else(Error(EPERM));
}
#if !defined(OS_NACL_NONSFI)
ResultExpr RestrictPtrace() {
const Arg<int> request(0);
return Switch(request).CASES((
#if !defined(__aarch64__)
PTRACE_GETREGS,
PTRACE_GETFPREGS,
PTRACE_GET_THREAD_AREA,
#endif
#if defined(__arm__)
PTRACE_GETVFPREGS,
#endif
PTRACE_GETREGSET,
PTRACE_PEEKDATA,
PTRACE_ATTACH,
PTRACE_DETACH),
Allow())
.Default(CrashSIGSYSPtrace());
}
#endif // defined(OS_NACL_NONSFI)
} // namespace sandbox.
|
//--------------------------------------------------------------------
// DebugWPrintf - implementation
// Copyright (C) Microsoft Corporation, 2001
//
// Created by: Duncan Bryce (duncanb), 11-11-2001
//
// Various print routines
//
#include "pch.h"
typedef BOOLEAN (WINAPI * SetThreadUILanguageFunc)(DWORD dwReserved);
extern HINSTANCE g_hThisModule;
HANDLE g_hStdout = NULL;
BOOL g_bSetLocale = FALSE;
SetThreadUILanguageFunc g_pfnSetThreadUILanguage = NULL;
//--------------------------------------------------------------------
void DebugWPrintf_(const WCHAR * wszFormat, ...)
{
WCHAR wszBuf[1024];
va_list vlArgs;
va_start(vlArgs, wszFormat);
_vsnwprintf(wszBuf, 1024, wszFormat, vlArgs);
va_end(vlArgs);
OutputDebugStringW(wszBuf);
}
//--------------------------------------------------------------------
HRESULT MySetThreadUILanguage(DWORD dwParam)
{
HMODULE hKernel32Dll = NULL;
HRESULT hr;
if (NULL == g_pfnSetThreadUILanguage) {
hKernel32Dll = LoadLibraryW(L"kernel32.dll");
if (NULL == hKernel32Dll) {
_JumpLastError(hr, error, "LoadLibraryW");
}
g_pfnSetThreadUILanguage = (SetThreadUILanguageFunc)GetProcAddress(hKernel32Dll, "SetThreadUILanguage");
if (NULL == g_pfnSetThreadUILanguage) {
_JumpLastError(hr, error, "GetProcAddress");
}
}
g_pfnSetThreadUILanguage(dwParam);
hr = S_OK;
error:
if (NULL != hKernel32Dll) {
FreeLibrary(hKernel32Dll);
}
return hr;
}
//--------------------------------------------------------------------
HRESULT InitializeConsoleOutput() {
HRESULT hr;
g_hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
if (INVALID_HANDLE_VALUE == g_hStdout) {
_JumpLastError(hr, error, "GetStdHandle");
}
hr = MySetThreadUILanguage(0);
_JumpIfError(hr, error, "MySetThreadUILanguage");
hr = S_OK;
error:
return S_OK;
}
//--------------------------------------------------------------------
BOOL FileIsConsole(
HANDLE fp
)
{
DWORD htype;
htype = GetFileType(fp);
htype &= ~FILE_TYPE_REMOTE;
return htype == FILE_TYPE_CHAR;
}
//--------------------------------------------------------------------
HRESULT MyWriteConsole(
HANDLE fp,
LPWSTR lpBuffer,
DWORD cchBuffer
)
{
HRESULT hr;
LPSTR lpAnsiBuffer = NULL;
//
// Jump through hoops for output because:
//
// 1. printf() family chokes on international output (stops
// printing when it hits an unrecognized character)
//
// 2. WriteConsole() works great on international output but
// fails if the handle has been redirected (i.e., when the
// output is piped to a file)
//
// 3. WriteFile() works great when output is piped to a file
// but only knows about bytes, so Unicode characters are
// printed as two Ansi characters.
//
if (FileIsConsole(fp))
{
hr = WriteConsole(fp, lpBuffer, cchBuffer, &cchBuffer, NULL);
_JumpIfError(hr, error, "WriteConsole");
}
else
{
lpAnsiBuffer = (LPSTR) LocalAlloc(LPTR, cchBuffer * sizeof(WCHAR));
_JumpIfOutOfMemory(hr, error, lpAnsiBuffer);
cchBuffer = WideCharToMultiByte(CP_OEMCP,
0,
lpBuffer,
cchBuffer,
lpAnsiBuffer,
cchBuffer * sizeof(WCHAR),
NULL,
NULL);
if (cchBuffer != 0)
{
if (!WriteFile(fp, lpAnsiBuffer, cchBuffer, &cchBuffer, NULL))
{
hr = GetLastError();
_JumpError(hr, error, "WriteFile");
}
}
else
{
hr = GetLastError();
_JumpError(hr, error, "WideCharToMultiByte");
}
}
hr = S_OK;
error:
if (NULL != lpAnsiBuffer)
LocalFree(lpAnsiBuffer);
return hr;
}
//--------------------------------------------------------------------
VOID DisplayMsg(DWORD dwSource, DWORD dwMsgId, ... )
{
DWORD dwBytesWritten;
DWORD dwLen;
LPWSTR pwszDisplayBuffer = NULL;
va_list ap;
va_start(ap, dwMsgId);
dwLen = FormatMessageW(dwSource | FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL,
dwMsgId,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&pwszDisplayBuffer,
0,
&ap);
if (dwLen && pwszDisplayBuffer) {
MyWriteConsole(g_hStdout, pwszDisplayBuffer, dwLen);
}
if (NULL != pwszDisplayBuffer) { LocalFree(pwszDisplayBuffer); }
va_end(ap);
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include "base58.h"
#include "bitcoinrpc.h"
#include "txdb.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "wallet.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", scriptPubKey.ToString()));
if (fIncludeHex)
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
{
out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
{
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("time", (boost::int64_t)tx.nTime));
entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime));
Array vin;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
Object in;
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else
{
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n));
Object o;
o.push_back(Pair("asm", txin.scriptSig.ToString()));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
}
in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
Array vout;
for (unsigned int i = 0; i < tx.vout.size(); i++)
{
const CTxOut& txout = tx.vout[i];
Object out;
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("n", (boost::int64_t)i));
Object o;
ScriptPubKeyToJSON(txout.scriptPubKey, o, false);
out.push_back(Pair("scriptPubKey", o));
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (hashBlock != 0)
{
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
{
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
entry.push_back(Pair("time", (boost::int64_t)pindex->nTime));
entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime));
}
else
entry.push_back(Pair("confirmations", 0));
}
}
}
Value getrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction <txid> [verbose=0]\n"
"If verbose=0, returns a string that is\n"
"serialized, hex-encoded data for <txid>.\n"
"If verbose is non-zero, returns an Object\n"
"with information about <txid>.");
uint256 hash;
hash.SetHex(params[0].get_str());
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(hash, tx, hashBlock))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
string strHex = HexStr(ssTx.begin(), ssTx.end());
if (!fVerbose)
return strHex;
Object result;
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
Value listunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n"
"Returns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filtered to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}");
RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CBitcoinAddress> setAddress;
if (params.size() > 2)
{
Array inputs = params[2].get_array();
BOOST_FOREACH(Value& input, inputs)
{
CBitcoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Neexcash address: ")+input.get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str());
setAddress.insert(address);
}
}
Array results;
vector<COutput> vecOutputs;
pwalletMain->AvailableCoins(vecOutputs, false);
BOOST_FOREACH(const COutput& out, vecOutputs)
{
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if(setAddress.size())
{
CTxDestination address;
if(!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
int64_t nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
Object entry;
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
{
entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address]));
}
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations",out.nDepth));
results.push_back(entry);
}
return results;
}
Value createrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n"
"Create a transaction spending given inputs\n"
"(array of objects containing transaction id and output number),\n"
"sending to given address(es).\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.");
RPCTypeCheck(params, list_of(array_type)(obj_type));
Array inputs = params[0].get_array();
Object sendTo = params[1].get_obj();
CTransaction rawTx;
BOOST_FOREACH(Value& input, inputs)
{
const Object& o = input.get_obj();
const Value& txid_v = find_value(o, "txid");
if (txid_v.type() != str_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
string txid = txid_v.get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
CTxIn in(COutPoint(uint256(txid), nOutput));
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Neexcash address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64_t nAmount = AmountFromValue(s.value_);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << rawTx;
return HexStr(ss.begin(), ss.end());
}
Value decoderawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction <hex string>\n"
"Return a JSON object representing the serialized, hex-encoded transaction.");
RPCTypeCheck(params, list_of(str_type));
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
Object result;
TxToJSON(tx, 0, result);
return result;
}
Value decodescript(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decodescript <hex string>\n"
"Decode a hex-encoded script.");
RPCTypeCheck(params, list_of(str_type));
Object r;
CScript script;
if (params[0].get_str().size() > 0){
vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
script = CScript(scriptData.begin(), scriptData.end());
} else {
// Empty scripts are valid
}
ScriptPubKeyToJSON(script, r, false);
r.push_back(Pair("p2sh", CBitcoinAddress(script.GetID()).ToString()));
return r;
}
Value signrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n"
"Sign inputs for raw transaction (serialized, hex-encoded).\n"
"Second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the blockchain.\n"
"Third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
"Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n"
"ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n"
"Returns json object with keys:\n"
" hex : raw transaction with signature(s) (hex-encoded string)\n"
" complete : 1 if transaction has a complete set of signature (0 if not)"
+ HelpRequiringPassphrase());
RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CTransaction> txVariants;
while (!ssData.empty())
{
try {
CTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CTransaction mergedTx(txVariants[0]);
bool fComplete = true;
// Fetch previous transactions (inputs):
map<COutPoint, CScript> mapPrevOut;
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
{
CTransaction tempTx;
MapPrevTx mapPrevTx;
CTxDB txdb("r");
map<uint256, CTxIndex> unused;
bool fInvalid;
// FetchInputs aborts on failure, so we go one at a time.
tempTx.vin.push_back(mergedTx.vin[i]);
tempTx.FetchInputs(txdb, unused, false, false, mapPrevTx, fInvalid);
// Copy results into mapPrevOut:
BOOST_FOREACH(const CTxIn& txin, tempTx.vin)
{
const uint256& prevHash = txin.prevout.hash;
if (mapPrevTx.count(prevHash) && mapPrevTx[prevHash].second.vout.size()>txin.prevout.n)
mapPrevOut[txin.prevout] = mapPrevTx[prevHash].second.vout[txin.prevout.n].scriptPubKey;
}
}
// Add previous txouts given in the RPC call:
if (params.size() > 1 && params[1].type() != null_type)
{
Array prevTxs = params[1].get_array();
BOOST_FOREACH(Value& p, prevTxs)
{
if (p.type() != obj_type)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
Object prevOut = p.get_obj();
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
string txidHex = find_value(prevOut, "txid").get_str();
if (!IsHex(txidHex))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "txid must be hexadecimal");
uint256 txid;
txid.SetHex(txidHex);
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
string pkHex = find_value(prevOut, "scriptPubKey").get_str();
if (!IsHex(pkHex))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "scriptPubKey must be hexadecimal");
vector<unsigned char> pkData(ParseHex(pkHex));
CScript scriptPubKey(pkData.begin(), pkData.end());
COutPoint outpoint(txid, nOut);
if (mapPrevOut.count(outpoint))
{
// Complain if scriptPubKey doesn't match
if (mapPrevOut[outpoint] != scriptPubKey)
{
string err("Previous output scriptPubKey mismatch:\n");
err = err + mapPrevOut[outpoint].ToString() + "\nvs:\n"+
scriptPubKey.ToString();
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
}
else
mapPrevOut[outpoint] = scriptPubKey;
}
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && params[2].type() != null_type)
{
fGivenKeys = true;
Array keys = params[2].get_array();
BOOST_FOREACH(Value k, keys)
{
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,"Invalid private key");
CKey key;
bool fCompressed;
CSecret secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
tempKeystore.AddKey(key);
}
}
else
EnsureWalletIsUnlocked();
const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain);
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && params[3].type() != null_type)
{
static map<string, int> mapSigHashValues =
boost::assign::map_list_of
(string("ALL"), int(SIGHASH_ALL))
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
(string("NONE"), int(SIGHASH_NONE))
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
(string("SINGLE"), int(SIGHASH_SINGLE))
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
;
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
{
CTxIn& txin = mergedTx.vin[i];
if (mapPrevOut.count(txin.prevout) == 0)
{
fComplete = false;
continue;
}
const CScript& prevPubKey = mapPrevOut[txin.prevout];
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH(const CTransaction& txv, txVariants)
{
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, 0))
fComplete = false;
}
Object result;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << mergedTx;
result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end())));
result.push_back(Pair("complete", fComplete));
return result;
}
Value sendrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"sendrawtransaction <hex string>\n"
"Submits raw transaction (serialized, hex-encoded) to local node and network.");
RPCTypeCheck(params, list_of(str_type));
// parse hex string from parameter
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
// deserialize binary data stream
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
uint256 hashTx = tx.GetHash();
// See if the transaction is already in a block
// or in the memory pool:
CTransaction existingTx;
uint256 hashBlock = 0;
if (GetTransaction(hashTx, existingTx, hashBlock))
{
if (hashBlock != 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("transaction already in block ")+hashBlock.GetHex());
// Not in block, but already in the memory pool; will drop
// through to re-relay it.
}
else
{
// push to local node
CTxDB txdb("r");
if (!tx.AcceptToMemoryPool(txdb))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected");
SyncWithWallets(tx, NULL, true);
}
RelayTransaction(tx, hashTx);
return hashTx.GetHex();
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "gtest/gtest.h"
#include "test/providers/provider_test_utils.h"
#include "Featurizers/RobustScalerFeaturizer.h"
namespace onnxruntime {
namespace test {
TEST(FeaturizersTests, RobustScalerTransformer_default_with_centering) {
OpTester test("RobustScalerTransformer", 1, onnxruntime::kMSFeaturizersDomain);
// Add state input
test.AddInput<uint8_t>("State", {12}, {1, 0, 0, 0, 0, 0, 160, 64, 0, 0, 128, 64});
// We are adding a scalar Tensor in this instance
test.AddInput<int8_t>("?1", {5}, {1, 3, 5, 7, 9});
// Expected output.
test.AddOutput<float>("?2", {5}, {-1.0f,-0.5f, 0.0f, 0.5f, 1.0f});
test.Run(OpTester::ExpectResult::kExpectSuccess);
}
TEST(FeaturizersTests, RobustScalarTransformer_default_no_centering) {
OpTester test("RobustScalerTransformer", 1, onnxruntime::kMSFeaturizersDomain);
// Add state input
test.AddInput<uint8_t>("State", {12}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 64});
// We are adding a scalar Tensor in this instance
test.AddInput<int8_t>("?1", {5}, {1, 3, 5, 7, 9});
// Expected output.
test.AddOutput<float>("?2", {5}, {0.25f, 0.75f, 1.25f, 1.75f, 2.25f});
test.Run(OpTester::ExpectResult::kExpectSuccess);
}
TEST(FeaturizersTests, RobustScalerTransformer_default_no_centering_zero_scale) {
OpTester test("RobustScalerTransformer", 1, onnxruntime::kMSFeaturizersDomain);
// Add state input
test.AddInput<uint8_t>("State", {12}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0});
// We are adding a scalar Tensor in this instance
test.AddInput<int8_t>("?1", {3}, {10, 10, 10});
// Expected output.
test.AddOutput<float>("?2", {3}, {10.f, 10.f, 10.f});
test.Run(OpTester::ExpectResult::kExpectSuccess);
}
TEST(FeaturizersTests, RobustScalarTransformer_default_with_centering_no_scaling) {
OpTester test("RobustScalerTransformer", 1, onnxruntime::kMSFeaturizersDomain);
// Add state input
test.AddInput<uint8_t>("State", {12}, {1, 0, 0, 0, 0, 0, 160, 64, 0, 0, 128, 63});
// We are adding a scalar Tensor in this instance
test.AddInput<int8_t>("?1", {5}, {1, 3, 5, 7, 9});
// Expected output.
test.AddOutput<float>("?2", {5}, {-4.f, -2.f, 0.f, 2.f, 4.f});
test.Run(OpTester::ExpectResult::kExpectSuccess);
}
TEST(FeaturizersTests, RobustScalerTransformer_default_with_centering_custom_scaling) {
OpTester test("RobustScalerTransformer", 1, onnxruntime::kMSFeaturizersDomain);
// Add state input
test.AddInput<uint8_t>("State", {12}, {1, 0, 0, 0, 0, 0, 160, 64, 0, 0, 0, 65});
// We are adding a scalar Tensor in this instance
test.AddInput<int8_t>("?1", {5}, {1, 3, 5, 7, 9});
// Expected output.
test.AddOutput<float>("?2", {5}, {-0.5f, -0.25f, 0.f, 0.25f, 0.5f});
test.Run(OpTester::ExpectResult::kExpectSuccess);
}
TEST(FeaturizersTests, RobustScalerTransformer_default_no_centering_custom_scaling) {
OpTester test("RobustScalerTransformer", 1, onnxruntime::kMSFeaturizersDomain);
// Add state input
test.AddInput<uint8_t>("State", {12}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65});
// We are adding a scalar Tensor in this instance
test.AddInput<int8_t>("?1", {5}, {1, 3, 5, 7, 9});
// Expected output.
test.AddOutput<float>("?2", {5}, {0.125f, 0.375f, 0.625f, 0.875f, 1.125f});
test.Run(OpTester::ExpectResult::kExpectSuccess);
}
}
}
|
//==================================================================================================
/*
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
*/
//==================================================================================================
#include <eve/function/cos.hpp>
#include <eve/module/real/math/detail/constant/rempio2_limits.hpp>
#include "producers.hpp"
#include <cmath>
TTS_CASE_TPL("wide random check on cos", EVE_TYPE)
{
auto std_cos = [](auto e) -> EVE_VALUE { return std::cos(double(e)); };
auto l = eve::detail::Rempio2_limit(eve::medium_type(), eve::as<EVE_VALUE>());
eve::uniform_prng<EVE_VALUE> p(-l, l);
TTS_RANGE_CHECK_WITH(p, std_cos, eve::medium(eve::cos), 0.5);
}
|
//
// Base3DOverlay.cpp
// interface/src/ui/overlays
//
// Copyright 2014 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "Base3DOverlay.h"
#include <RegisteredMetaTypes.h>
#include <SharedUtil.h>
#include "Application.h"
const bool DEFAULT_IS_SOLID = false;
const bool DEFAULT_IS_DASHED_LINE = false;
Base3DOverlay::Base3DOverlay() :
SpatiallyNestable(NestableType::Overlay, QUuid::createUuid()),
_isSolid(DEFAULT_IS_SOLID),
_isDashedLine(DEFAULT_IS_DASHED_LINE),
_ignoreRayIntersection(false),
_drawInFront(false),
_drawHUDLayer(false)
{
}
Base3DOverlay::Base3DOverlay(const Base3DOverlay* base3DOverlay) :
Overlay(base3DOverlay),
SpatiallyNestable(NestableType::Overlay, QUuid::createUuid()),
_isSolid(base3DOverlay->_isSolid),
_isDashedLine(base3DOverlay->_isDashedLine),
_ignoreRayIntersection(base3DOverlay->_ignoreRayIntersection),
_drawInFront(base3DOverlay->_drawInFront),
_drawHUDLayer(base3DOverlay->_drawHUDLayer),
_isGrabbable(base3DOverlay->_isGrabbable)
{
setTransform(base3DOverlay->getTransform());
}
QVariantMap convertOverlayLocationFromScriptSemantics(const QVariantMap& properties, bool scalesWithParent) {
// the position and rotation in _transform are relative to the parent (aka local). The versions coming from
// scripts are in world-frame, unless localPosition or localRotation are used. Patch up the properties
// so that "position" and "rotation" are relative-to-parent values.
QVariantMap result = properties;
QUuid parentID = result["parentID"].isValid() ? QUuid(result["parentID"].toString()) : QUuid();
int parentJointIndex = result["parentJointIndex"].isValid() ? result["parentJointIndex"].toInt() : -1;
bool success;
// make "position" and "orientation" be relative-to-parent
if (result["localPosition"].isValid()) {
result["position"] = result["localPosition"];
} else if (result["position"].isValid()) {
glm::vec3 localPosition = SpatiallyNestable::worldToLocal(vec3FromVariant(result["position"]),
parentID, parentJointIndex, scalesWithParent, success);
if (success) {
result["position"] = vec3toVariant(localPosition);
}
}
if (result["localOrientation"].isValid()) {
result["orientation"] = result["localOrientation"];
} else if (result["orientation"].isValid()) {
glm::quat localOrientation = SpatiallyNestable::worldToLocal(quatFromVariant(result["orientation"]),
parentID, parentJointIndex, scalesWithParent, success);
if (success) {
result["orientation"] = quatToVariant(localOrientation);
}
}
return result;
}
void Base3DOverlay::setProperties(const QVariantMap& originalProperties) {
QVariantMap properties = originalProperties;
if (properties["name"].isValid()) {
setName(properties["name"].toString());
}
// carry over some legacy keys
if (!properties["position"].isValid() && !properties["localPosition"].isValid()) {
if (properties["p1"].isValid()) {
properties["position"] = properties["p1"];
} else if (properties["point"].isValid()) {
properties["position"] = properties["point"];
} else if (properties["start"].isValid()) {
properties["position"] = properties["start"];
}
}
if (!properties["orientation"].isValid() && properties["rotation"].isValid()) {
properties["orientation"] = properties["rotation"];
}
if (!properties["localOrientation"].isValid() && properties["localRotation"].isValid()) {
properties["localOrientation"] = properties["localRotation"];
}
// All of parentID, parentJointIndex, position, orientation are needed to make sense of any of them.
// If any of these changed, pull any missing properties from the overlay.
if (properties["parentID"].isValid() || properties["parentJointIndex"].isValid() ||
properties["position"].isValid() || properties["localPosition"].isValid() ||
properties["orientation"].isValid() || properties["localOrientation"].isValid()) {
if (!properties["parentID"].isValid()) {
properties["parentID"] = getParentID();
}
if (!properties["parentJointIndex"].isValid()) {
properties["parentJointIndex"] = getParentJointIndex();
}
if (!properties["position"].isValid() && !properties["localPosition"].isValid()) {
properties["position"] = vec3toVariant(getWorldPosition());
}
if (!properties["orientation"].isValid() && !properties["localOrientation"].isValid()) {
properties["orientation"] = quatToVariant(getWorldOrientation());
}
}
properties = convertOverlayLocationFromScriptSemantics(properties, getScalesWithParent());
Overlay::setProperties(properties);
bool needRenderItemUpdate = false;
auto drawInFront = properties["drawInFront"];
if (drawInFront.isValid()) {
bool value = drawInFront.toBool();
setDrawInFront(value);
needRenderItemUpdate = true;
}
auto drawHUDLayer = properties["drawHUDLayer"];
if (drawHUDLayer.isValid()) {
bool value = drawHUDLayer.toBool();
setDrawHUDLayer(value);
needRenderItemUpdate = true;
}
auto isGrabbable = properties["grabbable"];
if (isGrabbable.isValid()) {
setIsGrabbable(isGrabbable.toBool());
}
if (properties["position"].isValid()) {
setLocalPosition(vec3FromVariant(properties["position"]));
needRenderItemUpdate = true;
}
if (properties["orientation"].isValid()) {
setLocalOrientation(quatFromVariant(properties["orientation"]));
needRenderItemUpdate = true;
}
if (properties["isSolid"].isValid()) {
setIsSolid(properties["isSolid"].toBool());
}
if (properties["isFilled"].isValid()) {
setIsSolid(properties["isSolid"].toBool());
}
if (properties["isWire"].isValid()) {
setIsSolid(!properties["isWire"].toBool());
}
if (properties["solid"].isValid()) {
setIsSolid(properties["solid"].toBool());
}
if (properties["filled"].isValid()) {
setIsSolid(properties["filled"].toBool());
}
if (properties["wire"].isValid()) {
setIsSolid(!properties["wire"].toBool());
}
if (properties["isDashedLine"].isValid()) {
setIsDashedLine(properties["isDashedLine"].toBool());
}
if (properties["dashed"].isValid()) {
setIsDashedLine(properties["dashed"].toBool());
}
if (properties["ignoreRayIntersection"].isValid()) {
setIgnoreRayIntersection(properties["ignoreRayIntersection"].toBool());
}
if (properties["parentID"].isValid()) {
setParentID(QUuid(properties["parentID"].toString()));
bool success;
getParentPointer(success); // call this to hook-up the parent's back-pointers to its child overlays
needRenderItemUpdate = true;
}
if (properties["parentJointIndex"].isValid()) {
setParentJointIndex(properties["parentJointIndex"].toInt());
needRenderItemUpdate = true;
}
// Communicate changes to the renderItem if needed
if (needRenderItemUpdate) {
auto itemID = getRenderItemID();
if (render::Item::isValidID(itemID)) {
render::ScenePointer scene = qApp->getMain3DScene();
render::Transaction transaction;
transaction.updateItem(itemID);
scene->enqueueTransaction(transaction);
}
}
}
// JSDoc for copying to @typedefs of overlay types that inherit Base3DOverlay.
/**jsdoc
* @property {string} name="" - A friendly name for the overlay.
* @property {Vec3} position - The position of the overlay center. Synonyms: <code>p1</code>, <code>point</code>, and
* <code>start</code>.
* @property {Vec3} localPosition - The local position of the overlay relative to its parent if the overlay has a
* <code>parentID</code> set, otherwise the same value as <code>position</code>.
* @property {Quat} rotation - The orientation of the overlay. Synonym: <code>orientation</code>.
* @property {Quat} localRotation - The orientation of the overlay relative to its parent if the overlay has a
* <code>parentID</code> set, otherwise the same value as <code>rotation</code>.
* @property {boolean} isSolid=false - Synonyms: <ode>solid</code>, <code>isFilled</code>, and <code>filled</code>.
* Antonyms: <code>isWire</code> and <code>wire</code>.
* @property {boolean} isDashedLine=false - If <code>true</code>, a dashed line is drawn on the overlay's edges. Synonym:
* <code>dashed</code>.
* @property {boolean} ignoreRayIntersection=false - If <code>true</code>,
* {@link Overlays.findRayIntersection|findRayIntersection} ignores the overlay.
* @property {boolean} drawInFront=false - If <code>true</code>, the overlay is rendered in front of other overlays that don't
* have <code>drawInFront</code> set to <code>true</code>, and in front of entities.
* @property {boolean} grabbable=false - Signal to grabbing scripts whether or not this overlay can be grabbed.
* @property {Uuid} parentID=null - The avatar, entity, or overlay that the overlay is parented to.
* @property {number} parentJointIndex=65535 - Integer value specifying the skeleton joint that the overlay is attached to if
* <code>parentID</code> is an avatar skeleton. A value of <code>65535</code> means "no joint".
*/
QVariant Base3DOverlay::getProperty(const QString& property) {
if (property == "name") {
return _name;
}
if (property == "position" || property == "start" || property == "p1" || property == "point") {
return vec3toVariant(getWorldPosition());
}
if (property == "localPosition") {
return vec3toVariant(getLocalPosition());
}
if (property == "rotation" || property == "orientation") {
return quatToVariant(getWorldOrientation());
}
if (property == "localRotation" || property == "localOrientation") {
return quatToVariant(getLocalOrientation());
}
if (property == "isSolid" || property == "isFilled" || property == "solid" || property == "filled") {
return _isSolid;
}
if (property == "isWire" || property == "wire") {
return !_isSolid;
}
if (property == "isDashedLine" || property == "dashed") {
return _isDashedLine;
}
if (property == "ignoreRayIntersection") {
return _ignoreRayIntersection;
}
if (property == "drawInFront") {
return _drawInFront;
}
if (property == "grabbable") {
return _isGrabbable;
}
if (property == "parentID") {
return getParentID();
}
if (property == "parentJointIndex") {
return getParentJointIndex();
}
return Overlay::getProperty(property);
}
bool Base3DOverlay::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction,
float& distance, BoxFace& face, glm::vec3& surfaceNormal) {
return false;
}
void Base3DOverlay::locationChanged(bool tellPhysics) {
SpatiallyNestable::locationChanged(tellPhysics);
// Force the actual update of the render transform through the notify call
notifyRenderVariableChange();
}
void Base3DOverlay::parentDeleted() {
qApp->getOverlays().deleteOverlay(getOverlayID());
}
void Base3DOverlay::update(float duration) {
// In Base3DOverlay, if its location or bound changed, the renderTrasnformDirty flag is true.
// then the correct transform used for rendering is computed in the update transaction and assigned.
if (_renderVariableDirty) {
auto itemID = getRenderItemID();
if (render::Item::isValidID(itemID)) {
// Capture the render transform value in game loop before
auto latestTransform = evalRenderTransform();
bool latestVisible = getVisible();
_renderVariableDirty = false;
render::ScenePointer scene = qApp->getMain3DScene();
render::Transaction transaction;
transaction.updateItem<Overlay>(itemID, [latestTransform, latestVisible](Overlay& data) {
auto overlay3D = dynamic_cast<Base3DOverlay*>(&data);
if (overlay3D) {
// TODO: overlays need to communicate all relavent render properties through transactions
overlay3D->setRenderTransform(latestTransform);
overlay3D->setRenderVisible(latestVisible);
}
});
scene->enqueueTransaction(transaction);
}
}
}
void Base3DOverlay::notifyRenderVariableChange() const {
_renderVariableDirty = true;
}
Transform Base3DOverlay::evalRenderTransform() {
return getTransform();
}
void Base3DOverlay::setRenderTransform(const Transform& transform) {
_renderTransform = transform;
}
void Base3DOverlay::setRenderVisible(bool visible) {
_renderVisible = visible;
}
SpatialParentTree* Base3DOverlay::getParentTree() const {
auto entityTreeRenderer = qApp->getEntities();
EntityTreePointer entityTree = entityTreeRenderer ? entityTreeRenderer->getTree() : nullptr;
return entityTree.get();
}
void Base3DOverlay::setVisible(bool visible) {
Parent::setVisible(visible);
notifyRenderVariableChange();
}
|
#include <iostream>
using namespace std;
// Guessing the number game
int main()
{
// this program finds that the user selects from 1 to 8
char answer;
cout<<"pick a number from 1 to 8." << endl;
cout<<"its is less than 5 ? (y|n):";
cin>>answer;
if(answer == 'y')
{
cout<<"is it less than 3? (y|n):";
cin>>answer;
if(answer == 'y')
{
cout<<"is it less than 2 ? (y|n):";
cin>>answer;
if(answer == 'y')
cout<<"Your number is 1 "<<endl;
else cout<< "your number is 2"<<endl;
}
else
{
cout<<"is it less than 4 ? (y|n):";
cin>>answer;
if(answer == 'y')
cout<<"Your number is 3 "<<endl;
else cout<< "your number is 4"<<endl;
}
}
else
{
cout<<"is it less than 7 ? (y|n):";
cin>>answer;
if(answer == 'y')
{
cout<<"is it less than 6 ? (y|n): "<<endl;
cin>>answer;
if(answer == 'y')
cout<<"Your number is 5 "<<endl;
else cout<< "your number is 6"<<endl;
}
else
{
cout<<"is it less than 8 ? (y|n):";
cin>>answer;
if(answer == 'y')
cout<<"Your number is 7 "<<endl;
else cout<< "your number is 8"<<endl;
}
}
}
|
//#####################################################################
// Copyright 2009, Avi Robinson-Mosher, Craig Schroeder.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
// Class UNIFORM_INTERIOR_ITERATOR_CELL
//#####################################################################
#include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_CELL.h>
#include <PhysBAM_Tools/Grids_Uniform_Arrays/ARRAYS_ND.h>
#include <PhysBAM_Dynamics/Coupled_Evolution/UNIFORM_COLLISION_AWARE_ITERATOR_FACE_INFO.h>
#include <PhysBAM_Dynamics/Coupled_Evolution/UNIFORM_INTERIOR_ITERATOR_CELL.h>
using namespace PhysBAM;
//#####################################################################
// Function UNIFORM_INTERIOR_ITERATOR_CELL
//#####################################################################
template<class TV> UNIFORM_INTERIOR_ITERATOR_CELL<TV>::
UNIFORM_INTERIOR_ITERATOR_CELL(const UNIFORM_COLLISION_AWARE_ITERATOR_FACE_INFO<TV>& info,const int number_of_ghost_cells_input,
const typename GRID<TV>::REGION& region_type_input,const int side_input)
:BASE(info.grid,number_of_ghost_cells_input,region_type_input,side_input),outside_fluid(*info.outside_fluid)
{
}
//#####################################################################
template class UNIFORM_INTERIOR_ITERATOR_CELL<VECTOR<float,1> >;
template class UNIFORM_INTERIOR_ITERATOR_CELL<VECTOR<float,2> >;
template class UNIFORM_INTERIOR_ITERATOR_CELL<VECTOR<float,3> >;
#ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT
template class UNIFORM_INTERIOR_ITERATOR_CELL<VECTOR<double,1> >;
template class UNIFORM_INTERIOR_ITERATOR_CELL<VECTOR<double,2> >;
template class UNIFORM_INTERIOR_ITERATOR_CELL<VECTOR<double,3> >;
#endif
|
#ifndef ASLAM_BACKEND_COMPRESSED_COLUMN_JACOBIAN_TRANSPOSE_BUILDER_HPP
#define ASLAM_BACKEND_COMPRESSED_COLUMN_JACOBIAN_TRANSPOSE_BUILDER_HPP
#include "JacobianBuilder.hpp"
#include "CompressedColumnMatrix.hpp"
namespace aslam {
namespace backend {
/**
* \class CompressedColumnJacobianTransposeBuilder
*
* Multithreaded code for building \f$ \mathbf J^T \f$ from the list of errors.
*/
template<typename INDEX_T = int>
class CompressedColumnJacobianTransposeBuilder {
public:
/// \brief the index type of the matrix
typedef INDEX_T index_t;
CompressedColumnJacobianTransposeBuilder();
virtual ~CompressedColumnJacobianTransposeBuilder();
/// \brief initialize the internal structure of the matrix.
///
/// This function assumes that all the design variables in the DV container are active
/// and that the container is sorted by order of block index such that dv[i]->blockIndex() == i
///
virtual void initMatrixStructure(const std::vector<DesignVariable*>& dvs, const std::vector<ErrorTerm*>& errors);
/// \brief build the large, sparse internal Jacobian matrix from the error terms.
virtual void buildSystem(size_t nThreads, bool useMEstimator);
/// \brief Get a view of the transpose of the Jacobian as a cholmod sparse matrix.
virtual cholmod_sparse getJacobianTransposeView();
/// \brief Get a const version of the compressed column matrix.
CompressedColumnMatrix<index_t> & J_transpose();
/// \brief Get a const version of the compressed column matrix.
const CompressedColumnMatrix<index_t> & J_transpose() const;
private:
/// \brief a function to be run by a single thread.
void evaluateJacobians(int threadId, int startIdx, int endIdx, bool useMEstimator);
/// \brief The transpose of the Jacobian matrix has better cache coherency.
CompressedColumnMatrix<index_t> _J_transpose;
/// \brief The Jacobian, transposed, transposed.
boost::shared_ptr<cholmod_sparse> _J;
/// \brief is the structure initialized
bool _isInitialized;
struct Evaluator {
void set(const JacobianColumnPointer& j, ErrorTerm* e, size_t er) {
jcp = j;
errorTerm = e;
eRow = er;
}
JacobianColumnPointer jcp;
size_t eRow;
ErrorTerm* errorTerm;
};
/// \brief An array parallel to the error term array that maps error terms to parts of the Jacobian.
std::vector<Evaluator> _jacobianPointers;
/// \brief have we built the Jacobian from the transpose?
bool _isJacobianBuiltFromJacobianTranspose;
template<typename MEMBER_FUNCTION_PTR>
void setupThreadedJob(MEMBER_FUNCTION_PTR ptr, size_t nThreads, bool useMEstimator);
};
} // namespace backend
} // namespace aslam
#include "implementation/CompressedColumnJacobianTransposeBuilder.hpp"
#endif /* ASLAM_BACKEND_COMPRESSED_COLUMN_JACOBIAN_TRANSPOSE_BUILDER_HPP */
|
/*
* Copyright 2017 MapD Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "LockMgr.h"
#include "QueryEngine/JsonAccessors.h"
#include "Fragmenter/InsertOrderFragmenter.h"
namespace Lock_Namespace {
using namespace rapidjson;
void getTableNames(std::map<std::string, bool>& tableNames, const std::string query_ra) {
rapidjson::Document query_ast;
query_ast.Parse(query_ra.c_str());
CHECK(!query_ast.HasParseError());
CHECK(query_ast.IsObject());
getTableNames(tableNames, query_ast);
}
void getTableNames(std::map<std::string, bool>& tableNames, const Value& value) {
if (value.IsArray()) {
for (SizeType i = 0; i < value.Size(); ++i)
getTableNames(tableNames, value[i]);
return;
} else if (value.IsObject()) {
for (auto mit = value.MemberBegin(); mit != value.MemberEnd(); ++mit)
getTableNames(tableNames, mit->value);
} else
return;
if (value.FindMember("rels") == value.MemberEnd())
return;
const auto& rels = value["rels"];
CHECK(rels.IsArray());
for (SizeType i = 0; i < rels.Size(); ++i) {
const auto& rel = rels[i];
const auto& relop = json_str(rel["relOp"]);
if (rel.FindMember("table") != rel.MemberEnd())
if ("EnumerableTableScan" == relop || "LogicalTableModify" == relop) {
const auto t = rel["table"].GetArray();
CHECK(t[1].IsString());
tableNames[t[1].GetString()] |= "LogicalTableModify" == relop;
}
}
}
ChunkKey getTableChunkKey(const Catalog_Namespace::Catalog& cat, const std::string& tableName) {
if (const auto tdp = cat.getMetadataForTable(tableName)) {
const auto fragmenter = dynamic_cast<Fragmenter_Namespace::InsertOrderFragmenter*>(tdp->fragmenter);
CHECK(fragmenter);
return fragmenter->getChunkKeyPrefix();
} else
throw std::runtime_error("Table " + tableName + " does not exist.");
}
std::string parse_to_ra(const Catalog_Namespace::Catalog& cat,
const std::string& query_str,
const Catalog_Namespace::SessionInfo& session_info) {
return cat.get_calciteMgr().process(session_info, query_str, false, false).plan_result;
}
}
|
/*
* Copyright (c) 2010-2016, MIT Probabilistic Computing Project
*
* Lead Developers: Dan Lovell and Jay Baxter
* Authors: Dan Lovell, Baxter Eaves, Jay Baxter, Vikash Mansinghka
* Research Leads: Vikash Mansinghka, Patrick Shafto
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ContinuousComponentModel.h"
using namespace std;
ContinuousComponentModel::ContinuousComponentModel(const CM_Hypers &in_hypers)
{
count = 0;
score = 0;
p_hypers = &in_hypers;
hyper_r = get(*p_hypers, string("r"));
hyper_nu = get(*p_hypers, string("nu"));
hyper_s = get(*p_hypers, string("s"));
hyper_mu = get(*p_hypers, string("mu"));
init_suffstats();
set_log_Z_0();
}
ContinuousComponentModel::ContinuousComponentModel(const CM_Hypers &in_hypers,
int COUNT, double SUM_X, double SUM_X_SQ)
{
count = COUNT;
sum_x = SUM_X;
sum_x_squared = SUM_X_SQ;
p_hypers = &in_hypers;
hyper_r = get(*p_hypers, string("r"));
hyper_nu = get(*p_hypers, string("nu"));
hyper_s = get(*p_hypers, string("s"));
hyper_mu = get(*p_hypers, string("mu"));
set_log_Z_0();
score = calc_marginal_logp();
}
void ContinuousComponentModel::get_hyper_doubles(double &r, double &nu,
double &s, double &mu) const
{
r = hyper_r;
nu = hyper_nu;
s = hyper_s;
mu = hyper_mu;
}
double ContinuousComponentModel::calc_marginal_logp() const
{
double r, nu, s, mu;
int count;
double sum_x, sum_x_squared;
get_hyper_doubles(r, nu, s, mu);
get_suffstats(count, sum_x, sum_x_squared);
numerics::update_continuous_hypers(count, sum_x, sum_x_squared, r, nu, s, mu);
return numerics::calc_continuous_logp(count, r, nu, s, log_Z_0);
}
double ContinuousComponentModel::calc_element_predictive_logp(
double element) const
{
if (isnan(element)) {
return 0;
}
double r, nu, s, mu;
int count;
double sum_x, sum_x_squared;
get_hyper_doubles(r, nu, s, mu);
get_suffstats(count, sum_x, sum_x_squared);
//
numerics::insert_to_continuous_suffstats(count, sum_x, sum_x_squared, element);
numerics::update_continuous_hypers(count, sum_x, sum_x_squared, r, nu, s, mu);
double logp_prime = numerics::calc_continuous_logp(count, r, nu, s, log_Z_0);
return logp_prime - score;
}
double ContinuousComponentModel::calc_element_predictive_logp_constrained(
double element, const vector<double> &constraints) const
{
if (isnan(element)) {
return 0;
}
double r, nu, s, mu;
int count;
double sum_x, sum_x_squared;
get_hyper_doubles(r, nu, s, mu);
get_suffstats(count, sum_x, sum_x_squared);
//
int num_constraints = (int) constraints.size();
for (int constraint_idx = 0; constraint_idx < num_constraints;
constraint_idx++) {
double constraint = constraints[constraint_idx];
numerics::insert_to_continuous_suffstats(count, sum_x, sum_x_squared,
constraint);
}
numerics::update_continuous_hypers(count, sum_x, sum_x_squared, r, nu, s, mu);
double baseline = numerics::calc_continuous_logp(count, r, nu, s, log_Z_0);
//
get_hyper_doubles(r, nu, s, mu);
numerics::insert_to_continuous_suffstats(count, sum_x, sum_x_squared, element);
numerics::update_continuous_hypers(count, sum_x, sum_x_squared, r, nu, s, mu);
double updated = numerics::calc_continuous_logp(count, r, nu, s, log_Z_0);
double predictive_logp = updated - baseline;
return predictive_logp;
}
vector<double> ContinuousComponentModel::calc_hyper_conditionals(
const string &which_hyper, const vector<double> &hyper_grid) const
{
double r, nu, s, mu;
int count;
double sum_x, sum_x_squared;
get_hyper_doubles(r, nu, s, mu);
get_suffstats(count, sum_x, sum_x_squared);
if (which_hyper == "r") {
return numerics::calc_continuous_r_conditionals(hyper_grid, count, sum_x,
sum_x_squared, nu, s, mu);
} else if (which_hyper == "nu") {
return numerics::calc_continuous_nu_conditionals(hyper_grid, count, sum_x,
sum_x_squared, r, s, mu);
} else if (which_hyper == "s") {
return numerics::calc_continuous_s_conditionals(hyper_grid, count, sum_x,
sum_x_squared, r, nu, mu);
} else if (which_hyper == "mu") {
return numerics::calc_continuous_mu_conditionals(hyper_grid, count, sum_x,
sum_x_squared, r, nu, s);
} else {
// error condition
vector<double> error;
return error;
}
}
double ContinuousComponentModel::insert_element(double element)
{
if (isnan(element)) {
return 0;
}
double score_0 = score;
numerics::insert_to_continuous_suffstats(count, sum_x, sum_x_squared, element);
score = calc_marginal_logp();
double delta_score = score - score_0;
return delta_score;
}
double ContinuousComponentModel::remove_element(double element)
{
if (isnan(element)) {
return 0;
}
double score_0 = score;
numerics::remove_from_continuous_suffstats(count, sum_x, sum_x_squared,
element);
score = calc_marginal_logp();
double delta_score = score - score_0;
return delta_score;
}
double ContinuousComponentModel::incorporate_hyper_update()
{
hyper_r = get(*p_hypers, (string) "r");
hyper_nu = get(*p_hypers, (string) "nu");
hyper_s = get(*p_hypers, (string) "s");
hyper_mu = get(*p_hypers, (string) "mu");
double score_0 = score;
// hypers[which_hyper] = value; // set by owner of hypers object
set_log_Z_0();
score = calc_marginal_logp();
double score_delta = score - score_0;
return score_delta;
}
void ContinuousComponentModel::set_log_Z_0()
{
double r, nu, s, mu;
get_hyper_doubles(r, nu, s, mu);
log_Z_0 = numerics::calc_continuous_logp(0, r, nu, s, 0);
}
void ContinuousComponentModel::init_suffstats()
{
sum_x = 0.;
sum_x_squared = 0.;
}
void ContinuousComponentModel::get_suffstats(int &count_out, double &sum_x_out,
double &sum_x_squared_out) const
{
count_out = count;
sum_x_out = sum_x;
sum_x_squared_out = sum_x_squared;
}
double ContinuousComponentModel::get_draw(int random_seed) const
{
vector<double> constraints;
return get_draw_constrained(random_seed, constraints);
}
double ContinuousComponentModel::get_draw_constrained(int random_seed,
const vector<double> &constraints) const
{
// get modified suffstats
double r, nu, s, mu;
int count;
double sum_x, sum_x_squared;
get_hyper_doubles(r, nu, s, mu);
get_suffstats(count, sum_x, sum_x_squared);
int num_constraints = (int) constraints.size();
for (int constraint_idx = 0; constraint_idx < num_constraints;
constraint_idx++) {
double constraint = constraints[constraint_idx];
numerics::insert_to_continuous_suffstats(count, sum_x, sum_x_squared,
constraint);
}
numerics::update_continuous_hypers(count, sum_x, sum_x_squared, r, nu, s, mu);
// http://www.cs.ubc.ca/~murphyk/Teaching/CS340-Fall07/reading/NG.pdf
// http://www.stats.ox.ac.uk/~teh/research/notes/GaussianInverseGamma.pdf
//
double student_t_draw = RandomNumberGenerator(random_seed).student_t(nu);
double coeff = sqrt((s * (r + 1)) / (nu * r));
double draw = student_t_draw * coeff + mu;
return draw;
}
// For simple predictive probability
double ContinuousComponentModel::get_predictive_cdf(double element,
const vector<double> &constraints) const
{
// XXX Requires computing the Student's t-distribution CDF, which
// involves incomplete beta integrals, which are a pain. But
// nothing uses this right now, so it's not really an issue.
return -HUGE_VAL;
}
map<string, double> ContinuousComponentModel::_get_suffstats() const
{
map<string, double> suffstats;
suffstats["sum_x"] = sum_x;
suffstats["sum_x_squared"] = sum_x_squared;
return suffstats;
}
map<string, double> ContinuousComponentModel::get_hypers() const
{
map<string, double> hypers;
hypers["r"] = hyper_r;
hypers["s"] = hyper_s;
hypers["nu"] = hyper_nu;
hypers["mu"] = hyper_mu;
return hypers;
}
|
// Copyright (c) 2007-2016 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
/// \file parallel/algorithms/for_loop_induction.hpp
#if !defined(HPX_PARALLEL_ALGORITHM_FOR_LOOP_INDUCTION_MAR_05_2016_0305PM)
#define HPX_PARALLEL_ALGORITHM_FOR_LOOP_INDUCTION_MAR_05_2016_0305PM
#include <hpx/config.hpp>
#include <hpx/util/decay.hpp>
#include <hpx/parallel/algorithms/detail/predicates.hpp>
#include <hpx/parallel/config/inline_namespace.hpp>
#include <cstddef>
#include <cstdlib>
#include <type_traits>
#include <utility>
namespace hpx { namespace parallel { HPX_INLINE_NAMESPACE(v2)
{
namespace detail
{
/// \cond NOINTERNAL
///////////////////////////////////////////////////////////////////////
template <typename T>
struct induction_helper
{
induction_helper(T var) HPX_NOEXCEPT
: var_(var), curr_(var)
{}
HPX_HOST_DEVICE
void init_iteration(std::size_t index) HPX_NOEXCEPT
{
curr_ = parallel::v1::detail::next(var_, index);
}
HPX_HOST_DEVICE
T const& iteration_value() const HPX_NOEXCEPT
{
return curr_;
}
HPX_HOST_DEVICE
void next_iteration() HPX_NOEXCEPT
{
++curr_;
}
HPX_HOST_DEVICE
void exit_iteration(std::size_t /*index*/) HPX_NOEXCEPT
{
}
private:
typename std::decay<T>::type var_;
T curr_;
};
template <typename T>
struct induction_helper<T&>
{
induction_helper(T& var) HPX_NOEXCEPT
: live_out_var_(var), var_(var), curr_(var)
{}
HPX_HOST_DEVICE
void init_iteration(std::size_t index) HPX_NOEXCEPT
{
curr_ = parallel::v1::detail::next(var_, index);
}
HPX_HOST_DEVICE
T const& iteration_value() const HPX_NOEXCEPT
{
return curr_;
}
HPX_HOST_DEVICE
void next_iteration() HPX_NOEXCEPT
{
++curr_;
}
HPX_HOST_DEVICE
void exit_iteration(std::size_t index) HPX_NOEXCEPT
{
live_out_var_ = parallel::v1::detail::next(
live_out_var_, index);
}
private:
T& live_out_var_;
T var_;
T curr_;
};
///////////////////////////////////////////////////////////////////////
template <typename T>
struct induction_stride_helper
{
induction_stride_helper(T var, std::size_t stride) HPX_NOEXCEPT
: var_(var), curr_(var), stride_(stride)
{}
HPX_HOST_DEVICE
void init_iteration(std::size_t index) HPX_NOEXCEPT
{
curr_ = parallel::v1::detail::next(var_, stride_*index);
}
HPX_HOST_DEVICE
T const& iteration_value() const HPX_NOEXCEPT
{
return curr_;
}
HPX_HOST_DEVICE
void next_iteration() HPX_NOEXCEPT
{
curr_ = parallel::v1::detail::next(curr_, stride_);
}
HPX_HOST_DEVICE
void exit_iteration(std::size_t /*index*/) HPX_NOEXCEPT
{
}
private:
typename std::decay<T>::type var_;
T curr_;
std::size_t stride_;
};
template <typename T>
struct induction_stride_helper<T&>
{
induction_stride_helper(T& var, std::size_t stride) HPX_NOEXCEPT
: live_out_var_(var), var_(var), curr_(var), stride_(stride)
{}
HPX_HOST_DEVICE
void init_iteration(std::size_t index) HPX_NOEXCEPT
{
curr_ = parallel::v1::detail::next(var_, stride_*index);
}
HPX_HOST_DEVICE
T const& iteration_value() const HPX_NOEXCEPT
{
return curr_;
}
HPX_HOST_DEVICE
void next_iteration() HPX_NOEXCEPT
{
curr_ = parallel::v1::detail::next(curr_, stride_);
}
HPX_HOST_DEVICE
void exit_iteration(std::size_t index) HPX_NOEXCEPT
{
live_out_var_ = parallel::v1::detail::next(
live_out_var_, stride_*index);
}
private:
T& live_out_var_;
T var_;
T curr_;
std::size_t stride_;
};
/// \endcond
}
/// The function template returns an induction object of unspecified type
/// having a value type and encapsulating an initial value \a value of that
/// type and, optionally, a stride.
///
/// For each element in the input range, a looping algorithm over input
/// sequence \a S computes an induction value from an induction variable
/// and ordinal position \a p within \a S by the formula
/// i + p * stride if a stride was specified or i + p otherwise.
/// This induction value is passed to the element access function.
///
/// If the \a value argument to \a induction is a non-const lvalue, then
/// that lvalue becomes the live-out object for the returned induction
/// object. For each induction object that has a live-out object, the
/// looping algorithm assigns the value of i + n * stride to the live-out
/// object upon return, where \a n is the number of elements in the input
/// range.
///
/// \tparam T The value type to be used by the induction object.
///
/// \param value [in] The initial value to use for the induction object
/// \param stride [in] The (optional) stride to use for the induction
/// object (default: 1)
///
/// \returns This returns an induction object with value type \a T, initial
/// value \a value, and (if specified) stride \a stride. If \a T
/// is an lvalue of non-const type, \a value is used as the live-out
/// object for the induction object; otherwise there is no live-out
/// object.
///
template <typename T>
HPX_FORCEINLINE detail::induction_stride_helper<T>
induction(T && value, std::size_t stride)
{
return detail::induction_stride_helper<T>(std::forward<T>(value), stride);
}
/// \cond NOINTERNAL
template <typename T>
HPX_FORCEINLINE detail::induction_helper<T>
induction(T && value)
{
return detail::induction_helper<T>(std::forward<T>(value));
}
/// \endcond
}}}
#endif
|
/*
Copyright (c) 2021 NetFoundry, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "catch2/catch.hpp"
#include <ziti/model_support.h>
#define States(XX,...)\
XX(Good, __VA_ARGS__) \
XX(Bad, __VA_ARGS__) \
XX(Ugly, __VA_ARGS__)
DECLARE_ENUM(State, States)
IMPL_ENUM(State, States)
TEST_CASE("test enum", "[model]") {
State good = States.value_of("Good");
CHECK(State_Unknown == 0);
CHECK(good == States.Good);
CHECK_THAT(States.name(good), Catch::Matches("Good"));
}
#define ModelWithEnum(XX, ...) \
XX(name, string, none, name, __VA_ARGS__) \
XX(state, State, none, state, __VA_ARGS__)
DECLARE_MODEL(FooWithEnum, ModelWithEnum)
IMPL_MODEL(FooWithEnum, ModelWithEnum)
TEST_CASE("parse enum", "[model]") {
const char *json = R"({
"name": "this is a name",
"state": "Ugly"
})";
FooWithEnum f1;
REQUIRE(parse_FooWithEnum(&f1, json, strlen(json)) == strlen(json));
CHECK_THAT(f1.name, Catch::Equals("this is a name"));
CHECK(f1.state == States.Ugly);
}
TEST_CASE("parse null enum", "[model]") {
const char *json = R"({
"name": "this is a name",
"state": null
})";
FooWithEnum f1;
REQUIRE(parse_FooWithEnum(&f1, json, strlen(json)) == strlen(json));
CHECK_THAT(f1.name, Catch::Equals("this is a name"));
CHECK(f1.state == 0);
}
TEST_CASE("default enum", "[model]") {
FooWithEnum f = {0};
f.name = (char *) "awesome foo";
CHECK(f.state == State_Unknown);
char *json = FooWithEnum_to_json(&f, 0, nullptr);
REQUIRE(json);
REQUIRE_THAT(json, Catch::Contains("\"state\":null"));
FooWithEnum f2;
REQUIRE(parse_FooWithEnum(&f2, json, strlen(json)) == strlen(json));
CHECK(f2.state == State_Unknown);
free(json);
}
TEST_CASE("enum to json", "[model]") {
FooWithEnum f = {0};
f.name = (char *) "awesome foo";
f.state = States.Bad;/**
* Declares [Enum] with given [Values]
*/
char *json = FooWithEnum_to_json(&f, 0, nullptr);
REQUIRE(json);
REQUIRE_THAT(json, Catch::Contains("\"state\":\"Bad\""));
free(json);
}
TEST_CASE("enum compare", "[model]") {
FooWithEnum f1,f2;
f1.name = (char*)"awesome";
f2.name = f1.name;
f1.state = States.Bad;
f2.state = States.Bad;
CHECK(cmp_FooWithEnum(&f1, &f2) == 0);
f2.state = States.Good;
CHECK(cmp_FooWithEnum(&f1, &f2) > 0);
CHECK(cmp_FooWithEnum(&f2, &f1) < 0);
}
#define ModelWithEnumArray(XX, ...) \
XX(name, string, none, name, __VA_ARGS__) \
XX(states, State, array, states, __VA_ARGS__)
DECLARE_MODEL(FooWithEnumArray, ModelWithEnumArray)
IMPL_MODEL(FooWithEnumArray, ModelWithEnumArray)
TEST_CASE("parse enum array", "[model]") {
const char *json = R"({
"name": "this is a name",
"states": ["Ugly", "Bad"]
})";
FooWithEnumArray f1;
REQUIRE(parse_FooWithEnumArray(&f1, json, strlen(json)) == strlen(json));
CHECK_THAT(f1.name, Catch::Equals("this is a name"));
CHECK(*f1.states[0] == States.Ugly);
CHECK(*f1.states[1] == States.Bad);
CHECK(f1.states[2] == nullptr);
size_t json_len;
auto js = FooWithEnumArray_to_json(&f1, 0, &json_len);
CHECK_THAT(js, Catch::Contains(R"("states":["Ugly","Bad"])"));
free_FooWithEnumArray(&f1);
}
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <string>
// template<> struct char_traits<char16_t>
// static size_t length(const char_type* s);
#include <string>
#include <cassert>
#include "test_macros.h"
int main()
{
#ifndef _LIBCPP_HAS_NO_UNICODE_CHARS
#if TEST_STD_VER >= 11
assert(std::char_traits<char16_t>::length(u"") == 0);
assert(std::char_traits<char16_t>::length(u"a") == 1);
assert(std::char_traits<char16_t>::length(u"aa") == 2);
assert(std::char_traits<char16_t>::length(u"aaa") == 3);
assert(std::char_traits<char16_t>::length(u"aaaa") == 4);
#endif
#endif // _LIBCPP_HAS_NO_UNICODE_CHARS
}
|
#ifndef gh_detail_stream_future_status_hpp
#define gh_detail_stream_future_status_hpp
#include <future>
#include <iostream>
// Technically reopening the std:: namespace is a violation of the standard, I think that is Okay in tests.
namespace std {
/// Define a streaming operator to use in tests.
inline std::ostream& operator<<(std::ostream& os, std::future_status x) {
switch(x) {
case std::future_status::timeout:
return os << "[timeout]";
case std::future_status::ready:
return os << "[ready]";
case std::future_status::deferred:
return os << "[deferred]";
}
throw std::runtime_error("unknown std::future_status");
}
} // namespace std
#endif // gh_detail_stream_future_status_hpp
|
#include<iostream>
using namespace std;
int main()
{
int n, i, arr[50], j, temp;
cout<<"Enter the Size (max. 50): ";
cin>>n;
cout<<"Enter "<<n<<" Numbers: ";
for(i=0; i<n; i++)
cin>>arr[i];
cout<<"\nSorting the Array using Bubble Sort Technique..\n";
for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(arr[j]>arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
cout<<"\nArray Sorted Successfully!\n";
cout<<"\nThe New Array is: \n";
for(i=0; i<n; i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}
|
/**
* Copyright (c) 2020 ZxyKira
* All rights reserved.
*
* SPDX-License-Identifier: MIT
*/
#ifndef MCUF_D6412968_F88E_43C3_9B72_FA8611376187
#define MCUF_D6412968_F88E_43C3_9B72_FA8611376187
/* ****************************************************************************************
* Include
*/
#include "Object.hpp"
/* ****************************************************************************************
* Namespace
*/
namespace mcuf{
namespace lang{
class Pointer;
}
}
/* ****************************************************************************************
* Class Pointer
*/
class mcuf::lang::Pointer :
public mcuf::lang::Object{
/* **************************************************************************************
* Subclass
*/
/* **************************************************************************************
* Variable <Public>
*/
/* **************************************************************************************
* Variable <Protected>
*/
/* **************************************************************************************
* Variable <Private>
*/
private: uint8_t* mPointer;
/* **************************************************************************************
* Abstract method <Public>
*/
/* **************************************************************************************
* Abstract method <Protected>
*/
/* **************************************************************************************
* Construct Method
*/
/**
* Construct a null pointer.
*/
public: Pointer(void);
/**
* Construct a pointer.
*
* @param pointer pointer.
*/
public: Pointer(void* pointer);
/**
* Construct a pointer.
*
* @param pointer pointer at value.
*/
public: Pointer(uint32_t pointer);
/**
* Disconstruct.
*/
public: virtual ~Pointer() = default;
/* **************************************************************************************
* Operator Method
*/
/**
* Operator equal
*/
public: void* operator=(void* pointer);
/* **************************************************************************************
* Public Method <Static>
*/
/**
*
*/
public: static Pointer nullPointer(void);
/* **************************************************************************************
* Public Method <Override>
*/
/* **************************************************************************************
* Public Method
*/
/**
*
*/
public: Pointer getPointer(void);
/**
*
*/
public: Pointer getPointer(uint32_t offset);
/**
*
*/
public: uint32_t getValue(void);
/**
*
*/
public: bool isNull(void);
/**
*
*/
public: void* pointer(void);
/**
*
*/
public: void* pointer(uint32_t offset);
/* **************************************************************************************
* Protected Method <Static>
*/
/* **************************************************************************************
* Protected Method <Override>
*/
/* **************************************************************************************
* Protected Method
*/
/* **************************************************************************************
* Private Method <Static>
*/
/* **************************************************************************************
* Private Method <Override>
*/
/* **************************************************************************************
* Private Method
*/
};
/* *****************************************************************************************
* End of file
*/
#endif/* MCUF_D6412968_F88E_43C3_9B72_FA8611376187 */
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkDataReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkDataReader.h"
#include "vtkBitArray.h"
#include "vtkByteSwap.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkCharArray.h"
#include "vtkDataArrayRange.h"
#include "vtkDoubleArray.h"
#include "vtkErrorCode.h"
#include "vtkFieldData.h"
#include "vtkFloatArray.h"
#include "vtkGraph.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationDoubleKey.h"
#include "vtkInformationDoubleVectorKey.h"
#include "vtkInformationIdTypeKey.h"
#include "vtkInformationIntegerKey.h"
#include "vtkInformationIntegerVectorKey.h"
#include "vtkInformationKeyLookup.h"
#include "vtkInformationStringKey.h"
#include "vtkInformationStringVectorKey.h"
#include "vtkInformationUnsignedLongKey.h"
#include "vtkInformationVector.h"
#include "vtkIntArray.h"
#include "vtkLegacyReaderVersion.h"
#include "vtkLongArray.h"
#include "vtkLookupTable.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPointSet.h"
#include "vtkRectilinearGrid.h"
#include "vtkShortArray.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkTypeInt64Array.h"
#include "vtkTypeUInt64Array.h"
#include "vtkUnicodeStringArray.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnsignedIntArray.h"
#include "vtkUnsignedLongArray.h"
#include "vtkUnsignedShortArray.h"
#include "vtkVariantArray.h"
#include "vtksys/FStream.hxx"
#include <vtksys/SystemTools.hxx>
#include <algorithm>
#include <cctype>
#include <sstream>
#include <vector>
// I need a safe way to read a line of arbitrary length. It exists on
// some platforms but not others so I'm afraid I have to write it
// myself.
// This function is also defined in Infovis/vtkDelimitedTextReader.cxx,
// so it would be nice to put this in a common file.
static int my_getline(istream& stream, vtkStdString& output, char delim = '\n');
vtkStandardNewMacro(vtkDataReader);
vtkCxxSetObjectMacro(vtkDataReader, InputArray, vtkCharArray);
// this undef is required on the hp. vtkMutexLock ends up including
// /usr/include/dce/cma_ux.h which has the gall to #define read as cma_read
#ifdef read
#undef read
#endif
// Construct object.
vtkDataReader::vtkDataReader()
{
this->FileType = VTK_ASCII;
this->ScalarsName = nullptr;
this->VectorsName = nullptr;
this->TensorsName = nullptr;
this->NormalsName = nullptr;
this->TCoordsName = nullptr;
this->LookupTableName = nullptr;
this->FieldDataName = nullptr;
this->ScalarLut = nullptr;
this->InputString = nullptr;
this->InputStringLength = 0;
this->InputStringPos = 0;
this->ReadFromInputString = 0;
this->IS = nullptr;
this->Header = nullptr;
this->InputArray = nullptr;
this->NumberOfScalarsInFile = 0;
this->ScalarsNameInFile = nullptr;
this->ScalarsNameAllocSize = 0;
this->NumberOfVectorsInFile = 0;
this->VectorsNameInFile = nullptr;
this->VectorsNameAllocSize = 0;
this->NumberOfTensorsInFile = 0;
this->TensorsNameInFile = nullptr;
this->TensorsNameAllocSize = 0;
this->NumberOfTCoordsInFile = 0;
this->TCoordsNameInFile = nullptr;
this->TCoordsNameAllocSize = 0;
this->NumberOfNormalsInFile = 0;
this->NormalsNameInFile = nullptr;
this->NormalsNameAllocSize = 0;
this->NumberOfFieldDataInFile = 0;
this->FieldDataNameInFile = nullptr;
this->FieldDataNameAllocSize = 0;
this->ReadAllScalars = 0;
this->ReadAllVectors = 0;
this->ReadAllNormals = 0;
this->ReadAllTensors = 0;
this->ReadAllColorScalars = 0;
this->ReadAllTCoords = 0;
this->ReadAllFields = 0;
this->FileMajorVersion = 0;
this->FileMinorVersion = 0;
this->SetNumberOfInputPorts(0);
this->SetNumberOfOutputPorts(1);
}
vtkDataReader::~vtkDataReader()
{
delete[] this->ScalarsName;
delete[] this->VectorsName;
delete[] this->TensorsName;
delete[] this->NormalsName;
delete[] this->TCoordsName;
delete[] this->LookupTableName;
delete[] this->FieldDataName;
delete[] this->ScalarLut;
delete[] this->InputString;
delete[] this->Header;
this->SetInputArray(nullptr);
this->InitializeCharacteristics();
delete this->IS;
}
void vtkDataReader::SetFileName(const char* fname)
{
if (this->GetNumberOfFileNames() == 1 && this->GetFileName(0) && fname &&
strcmp(this->GetFileName(0), fname) == 0)
{
return;
}
this->ClearFileNames();
if (fname)
{
this->AddFileName(fname);
}
this->Modified();
}
const char* vtkDataReader::GetFileName() const
{
if (this->GetNumberOfFileNames() < 1)
{
return nullptr;
}
return this->vtkSimpleReader::GetFileName(0);
}
int vtkDataReader::ReadTimeDependentMetaData(int timestep, vtkInformation* metadata)
{
if (this->ReadFromInputString)
{
return this->ReadMetaDataSimple(std::string(), metadata);
}
return this->Superclass::ReadTimeDependentMetaData(timestep, metadata);
}
int vtkDataReader::ReadMesh(
int piece, int npieces, int nghosts, int timestep, vtkDataObject* output)
{
// Not a parallel reader. Cannot handle anything other than the first piece,
// which will have everything.
if (piece > 0)
{
return 1;
}
if (this->ReadFromInputString)
{
return this->ReadMeshSimple(std::string(), output);
}
return this->Superclass::ReadMesh(piece, npieces, nghosts, timestep, output);
}
void vtkDataReader::SetInputString(const char* in)
{
int len = 0;
if (in != nullptr)
{
len = static_cast<int>(strlen(in));
}
this->SetInputString(in, len);
}
void vtkDataReader::SetBinaryInputString(const char* in, int len)
{
this->SetInputString(in, len);
}
void vtkDataReader::SetInputString(const char* in, int len)
{
if (this->Debug)
{
vtkDebugMacro(<< "SetInputString len: " << len << " in: " << (in ? in : "(null)"));
}
if (this->InputString && in && strncmp(in, this->InputString, len) == 0)
{
return;
}
delete[] this->InputString;
if (in && len > 0)
{
// Add a nullptr terminator so that GetInputString
// callers (from wrapped languages) get a valid
// C string in *ALL* cases...
//
this->InputString = new char[len + 1];
memcpy(this->InputString, in, len);
this->InputString[len] = 0;
this->InputStringLength = len;
}
else
{
this->InputString = nullptr;
this->InputStringLength = 0;
}
this->Modified();
}
// Internal function to read in a line up to 256 characters.
// Returns zero if there was an error.
int vtkDataReader::ReadLine(char result[256])
{
this->IS->getline(result, 256);
if (this->IS->fail())
{
if (this->IS->eof())
{
return 0;
}
if (this->IS->gcount() == 255)
{
// Read 256 chars; ignoring the rest of the line.
this->IS->clear();
this->IS->ignore(VTK_INT_MAX, '\n');
}
}
// remove '\r', if present.
size_t slen = strlen(result);
if (slen > 0 && result[slen - 1] == '\r')
{
result[slen - 1] = '\0';
}
return 1;
}
// Internal function to read in a string up to 256 characters.
// Returns zero if there was an error.
int vtkDataReader::ReadString(char result[256])
{
this->IS->width(256);
*this->IS >> result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
// Internal function to read in an integer value.
// Returns zero if there was an error.
int vtkDataReader::Read(char* result)
{
int intData;
*this->IS >> intData;
if (this->IS->fail())
{
return 0;
}
*result = (char)intData;
return 1;
}
int vtkDataReader::Read(unsigned char* result)
{
int intData;
*this->IS >> intData;
if (this->IS->fail())
{
return 0;
}
*result = (unsigned char)intData;
return 1;
}
int vtkDataReader::Read(short* result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(unsigned short* result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(int* result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(unsigned int* result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(long* result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(unsigned long* result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(long long* result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(unsigned long long* result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(float* result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(double* result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
size_t vtkDataReader::Peek(char* str, size_t n)
{
if (n == 0)
{
return 0;
}
this->IS->read(str, n);
std::streamsize len = this->IS->gcount();
if (!*this->IS)
{
this->IS->clear();
}
this->IS->seekg(-len, std::ios_base::cur);
return len;
}
// Open a vtk data file. Returns zero if error.
int vtkDataReader::OpenVTKFile(const char* fname)
{
// Save current locale settings and set standard one to
// avoid locale issues - for instance with the decimal separator.
this->CurrentLocale = std::locale::global(std::locale::classic());
if (!fname && this->GetNumberOfFileNames() > 0)
{
fname = this->GetFileName(0);
}
this->CurrentFileName = fname ? fname : std::string();
if (this->IS != nullptr)
{
this->CloseVTKFile();
}
if (this->ReadFromInputString)
{
if (this->InputArray)
{
vtkDebugMacro(<< "Reading from InputArray");
std::string str(this->InputArray->GetPointer(0),
static_cast<size_t>(
this->InputArray->GetNumberOfTuples() * this->InputArray->GetNumberOfComponents()));
this->IS = new std::istringstream(str);
return 1;
}
else if (this->InputString)
{
vtkDebugMacro(<< "Reading from InputString");
std::string str(this->InputString, this->InputStringLength);
this->IS = new std::istringstream(str);
return 1;
}
}
else
{
vtkDebugMacro(<< "Opening vtk file");
if (!fname || (strlen(fname) == 0))
{
vtkErrorMacro(<< "No file specified!");
this->SetErrorCode(vtkErrorCode::NoFileNameError);
return 0;
}
// first make sure the file exists, this prevents an empty file from
// being created on older compilers
vtksys::SystemTools::Stat_t fs;
if (vtksys::SystemTools::Stat(fname, &fs) != 0)
{
vtkErrorMacro(<< "Unable to open file: " << fname);
this->SetErrorCode(vtkErrorCode::CannotOpenFileError);
return 0;
}
this->IS = new vtksys::ifstream(fname, ios::in | ios::binary);
if (this->IS->fail())
{
vtkErrorMacro(<< "Unable to open file: " << fname);
delete this->IS;
this->IS = nullptr;
this->SetErrorCode(vtkErrorCode::CannotOpenFileError);
return 0;
}
return 1;
}
return 0;
}
// Read the header of a vtk data file. Returns 0 if error.
int vtkDataReader::ReadHeader(const char* fname)
{
if (!fname && this->GetNumberOfFileNames() > 0)
{
fname = this->GetFileName(0);
}
char line[256];
vtkDebugMacro(<< "Reading vtk file header");
//
// read header
//
if (!this->ReadLine(line))
{
vtkErrorMacro(<< "Premature EOF reading first line! "
<< " for file: " << (fname ? fname : "(Null FileName)"));
this->SetErrorCode(vtkErrorCode::PrematureEndOfFileError);
return 0;
}
const int VERSION_PREFIX_LENGTH = 22;
if (strncmp("# vtk DataFile Version", line, VERSION_PREFIX_LENGTH))
{
vtkErrorMacro(<< "Unrecognized file type: " << line
<< " for file: " << (fname ? fname : "(Null FileName)"));
this->SetErrorCode(vtkErrorCode::UnrecognizedFileTypeError);
return 0;
}
if (sscanf(line + VERSION_PREFIX_LENGTH, "%d.%d", &this->FileMajorVersion,
&this->FileMinorVersion) != 2)
{
vtkWarningMacro(<< "Cannot read file version: " << line
<< " for file: " << (fname ? fname : "(Null FileName)"));
this->FileMajorVersion = 0;
this->FileMinorVersion = 0;
}
if (this->FileMajorVersion > vtkLegacyReaderMajorVersion ||
(this->FileMajorVersion == vtkLegacyReaderMajorVersion &&
this->FileMinorVersion > vtkLegacyReaderMinorVersion))
{
// newer file than the reader version
vtkWarningMacro(<< "Reading file version: " << this->FileMajorVersion << "."
<< this->FileMinorVersion << " with older reader version "
<< vtkLegacyReaderMajorVersion << "." << vtkLegacyReaderMinorVersion);
}
//
// read title
//
if (!this->ReadLine(line))
{
vtkErrorMacro(<< "Premature EOF reading title! "
<< " for file: " << (fname ? fname : "(Null FileName)"));
this->SetErrorCode(vtkErrorCode::PrematureEndOfFileError);
return 0;
}
delete[] this->Header;
this->Header = new char[strlen(line) + 1];
strcpy(this->Header, line);
vtkDebugMacro(<< "Reading vtk file entitled: " << line);
//
// read type
//
if (!this->ReadString(line))
{
vtkErrorMacro(<< "Premature EOF reading file type!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
this->SetErrorCode(vtkErrorCode::PrematureEndOfFileError);
return 0;
}
if (!strncmp(this->LowerCase(line), "ascii", 5))
{
this->FileType = VTK_ASCII;
}
else if (!strncmp(line, "binary", 6))
{
this->FileType = VTK_BINARY;
}
else
{
vtkErrorMacro(<< "Unrecognized file type: " << line
<< " for file: " << (fname ? fname : "(Null FileName)"));
this->FileType = 0;
this->SetErrorCode(vtkErrorCode::UnrecognizedFileTypeError);
return 0;
}
// if this is a binary file we need to make sure that we opened it
// as a binary file.
if (this->FileType == VTK_BINARY && this->ReadFromInputString == 0)
{
vtkDebugMacro(<< "Opening vtk file as binary");
delete this->IS;
this->IS = nullptr;
#ifdef _WIN32
this->IS = new vtksys::ifstream(fname, ios::in | ios::binary);
#else
this->IS = new vtksys::ifstream(fname, ios::in);
#endif
if (this->IS->fail())
{
vtkErrorMacro(<< "Unable to open file: " << fname);
delete this->IS;
this->IS = nullptr;
this->SetErrorCode(vtkErrorCode::CannotOpenFileError);
return 0;
}
// read up to the same point in the file
this->ReadLine(line);
this->ReadLine(line);
this->ReadString(line);
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5 * (1.0 - progress));
return 1;
}
int vtkDataReader::IsFileValid(const char* dstype)
{
char line[1024];
if (!dstype)
{
return 0;
}
if (!this->OpenVTKFile() || !this->ReadHeader())
{
this->CloseVTKFile();
return 0;
}
if (!this->ReadString(line))
{
vtkErrorMacro(<< "Data file ends prematurely!");
this->CloseVTKFile();
this->SetErrorCode(vtkErrorCode::PrematureEndOfFileError);
return 0;
}
if (!strncmp(this->LowerCase(line), "dataset", (unsigned long)7))
{
if (!this->ReadString(line))
{
vtkErrorMacro(<< "Data file ends prematurely!");
this->CloseVTKFile();
this->SetErrorCode(vtkErrorCode::PrematureEndOfFileError);
return 0;
}
if (strncmp(this->LowerCase(line), dstype, strlen(dstype)))
{
this->CloseVTKFile();
return 0;
}
// everything looks good
this->CloseVTKFile();
return 1;
}
this->CloseVTKFile();
return 0;
}
// Read the cell data of a vtk data file. The number of cells (from the
// dataset) must match the number of cells defined in cell attributes (unless
// no geometry was defined).
int vtkDataReader::ReadCellData(vtkDataSet* ds, vtkIdType numCells)
{
char line[256];
vtkDataSetAttributes* a = ds->GetCellData();
vtkDebugMacro(<< "Reading vtk cell data");
//
// Read keywords until end-of-file
//
while (this->ReadString(line))
{
//
// read scalar data
//
if (!strncmp(this->LowerCase(line), "scalars", 7))
{
if (!this->ReadScalarData(a, numCells))
{
return 0;
}
}
//
// read vector data
//
else if (!strncmp(line, "vectors", 7))
{
if (!this->ReadVectorData(a, numCells))
{
return 0;
}
}
//
// read 3x2 symmetric tensor data
//
else if (!strncmp(line, "tensors6", 8))
{
if (!this->ReadTensorData(a, numCells, 6))
{
return 0;
}
}
//
// read 3x3 tensor data
//
else if (!strncmp(line, "tensors", 7))
{
if (!this->ReadTensorData(a, numCells))
{
return 0;
}
}
//
// read normals data
//
else if (!strncmp(line, "normals", 7))
{
if (!this->ReadNormalData(a, numCells))
{
return 0;
}
}
//
// read texture coordinates data
//
else if (!strncmp(line, "texture_coordinates", 19))
{
if (!this->ReadTCoordsData(a, numCells))
{
return 0;
}
}
//
// read the global id data
//
else if (!strncmp(line, "global_ids", 10))
{
if (!this->ReadGlobalIds(a, numCells))
{
return 0;
}
}
//
// read the pedigree id data
//
else if (!strncmp(line, "pedigree_ids", 12))
{
if (!this->ReadPedigreeIds(a, numCells))
{
return 0;
}
}
//
// read color scalars data
//
else if (!strncmp(line, "color_scalars", 13))
{
if (!this->ReadCoScalarData(a, numCells))
{
return 0;
}
}
//
// read lookup table. Associate with scalar data.
//
else if (!strncmp(line, "lookup_table", 12))
{
if (!this->ReadLutData(a))
{
return 0;
}
}
//
// read field of data
//
else if (!strncmp(line, "field", 5))
{
vtkFieldData* f;
if (!(f = this->ReadFieldData(CELL_DATA)))
{
return 0;
}
for (int i = 0; i < f->GetNumberOfArrays(); i++)
{
a->AddArray(f->GetAbstractArray(i));
}
f->Delete();
}
//
// maybe bumped into point data
//
else if (!strncmp(line, "point_data", 10))
{
vtkIdType npts;
if (!this->Read(&npts))
{
vtkErrorMacro(<< "Cannot read point data!");
return 0;
}
this->ReadPointData(ds, npts);
}
else
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Unsupported cell attribute type: " << line
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
}
return 1;
}
// Read the point data of a vtk data file. The number of points (from the
// dataset) must match the number of points defined in point attributes (unless
// no geometry was defined).
int vtkDataReader::ReadPointData(vtkDataSet* ds, vtkIdType numPts)
{
char line[256];
vtkDataSetAttributes* a = ds->GetPointData();
vtkDebugMacro(<< "Reading vtk point data");
//
// Read keywords until end-of-file
//
while (this->ReadString(line))
{
//
// read scalar data
//
if (!strncmp(this->LowerCase(line), "scalars", 7))
{
if (!this->ReadScalarData(a, numPts))
{
return 0;
}
}
//
// read vector data
//
else if (!strncmp(line, "vectors", 7))
{
if (!this->ReadVectorData(a, numPts))
{
return 0;
}
}
//
// read 3x2 symmetric tensor data
//
else if (!strncmp(line, "tensors6", 8))
{
if (!this->ReadTensorData(a, numPts, 6))
{
return 0;
}
}
//
// read 3x3 tensor data
//
else if (!strncmp(line, "tensors", 7))
{
if (!this->ReadTensorData(a, numPts))
{
return 0;
}
}
//
// read normals data
//
else if (!strncmp(line, "normals", 7))
{
if (!this->ReadNormalData(a, numPts))
{
return 0;
}
}
//
// read texture coordinates data
//
else if (!strncmp(line, "texture_coordinates", 19))
{
if (!this->ReadTCoordsData(a, numPts))
{
return 0;
}
}
//
// read the global id data
//
else if (!strncmp(line, "global_ids", 10))
{
if (!this->ReadGlobalIds(a, numPts))
{
return 0;
}
}
//
// read the pedigree id data
//
else if (!strncmp(line, "pedigree_ids", 12))
{
if (!this->ReadPedigreeIds(a, numPts))
{
return 0;
}
}
//
// read the edge flags data
//
else if (!strncmp(line, "edge_flags", 10))
{
if (!this->ReadEdgeFlags(a, numPts))
{
return 0;
}
}
//
// read color scalars data
//
else if (!strncmp(line, "color_scalars", 13))
{
if (!this->ReadCoScalarData(a, numPts))
{
return 0;
}
}
//
// read lookup table. Associate with scalar data.
//
else if (!strncmp(line, "lookup_table", 12))
{
if (!this->ReadLutData(a))
{
return 0;
}
}
//
// read field of data
//
else if (!strncmp(line, "field", 5))
{
vtkFieldData* f;
if (!(f = this->ReadFieldData(POINT_DATA)))
{
return 0;
}
for (int i = 0; i < f->GetNumberOfArrays(); i++)
{
a->AddArray(f->GetAbstractArray(i));
}
f->Delete();
}
//
// maybe bumped into cell data
//
else if (!strncmp(line, "cell_data", 9))
{
vtkIdType ncells;
if (!this->Read(&ncells))
{
vtkErrorMacro(<< "Cannot read cell data!");
return 0;
}
this->ReadCellData(ds, ncells);
}
else
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Unsupported point attribute type: " << line
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
}
return 1;
}
// Read the vertex data of a vtk data file. The number of vertices (from the
// graph) must match the number of vertices defined in vertex attributes (unless
// no geometry was defined).
int vtkDataReader::ReadVertexData(vtkGraph* g, vtkIdType numVertices)
{
char line[256];
vtkDataSetAttributes* a = g->GetVertexData();
vtkDebugMacro(<< "Reading vtk vertex data");
//
// Read keywords until end-of-file
//
while (this->ReadString(line))
{
//
// read scalar data
//
if (!strncmp(this->LowerCase(line), "scalars", 7))
{
if (!this->ReadScalarData(a, numVertices))
{
return 0;
}
}
//
// read vector data
//
else if (!strncmp(line, "vectors", 7))
{
if (!this->ReadVectorData(a, numVertices))
{
return 0;
}
}
//
// read 3x2 symmetric tensor data
//
else if (!strncmp(line, "tensors6", 8))
{
if (!this->ReadTensorData(a, numVertices, 6))
{
return 0;
}
}
//
// read 3x3 tensor data
//
else if (!strncmp(line, "tensors", 7))
{
if (!this->ReadTensorData(a, numVertices))
{
return 0;
}
}
//
// read normals data
//
else if (!strncmp(line, "normals", 7))
{
if (!this->ReadNormalData(a, numVertices))
{
return 0;
}
}
//
// read texture coordinates data
//
else if (!strncmp(line, "texture_coordinates", 19))
{
if (!this->ReadTCoordsData(a, numVertices))
{
return 0;
}
}
//
// read the global id data
//
else if (!strncmp(line, "global_ids", 10))
{
if (!this->ReadGlobalIds(a, numVertices))
{
return 0;
}
}
//
// read the pedigree id data
//
else if (!strncmp(line, "pedigree_ids", 12))
{
if (!this->ReadPedigreeIds(a, numVertices))
{
return 0;
}
}
//
// read color scalars data
//
else if (!strncmp(line, "color_scalars", 13))
{
if (!this->ReadCoScalarData(a, numVertices))
{
return 0;
}
}
//
// read lookup table. Associate with scalar data.
//
else if (!strncmp(line, "lookup_table", 12))
{
if (!this->ReadLutData(a))
{
return 0;
}
}
//
// read field of data
//
else if (!strncmp(line, "field", 5))
{
vtkFieldData* f;
if (!(f = this->ReadFieldData()))
{
return 0;
}
for (int i = 0; i < f->GetNumberOfArrays(); i++)
{
a->AddArray(f->GetAbstractArray(i));
}
f->Delete();
}
//
// maybe bumped into edge data
//
else if (!strncmp(line, "edge_data", 10))
{
vtkIdType npts;
if (!this->Read(&npts))
{
vtkErrorMacro(<< "Cannot read point data!");
return 0;
}
this->ReadEdgeData(g, npts);
}
else
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Unsupported vertex attribute type: " << line
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
}
return 1;
}
// Read the edge data of a vtk data file. The number of edges (from the
// graph) must match the number of edges defined in edge attributes (unless
// no geometry was defined).
int vtkDataReader::ReadEdgeData(vtkGraph* g, vtkIdType numEdges)
{
char line[256];
vtkDataSetAttributes* a = g->GetEdgeData();
vtkDebugMacro(<< "Reading vtk edge data");
//
// Read keywords until end-of-file
//
while (this->ReadString(line))
{
//
// read scalar data
//
if (!strncmp(this->LowerCase(line), "scalars", 7))
{
if (!this->ReadScalarData(a, numEdges))
{
return 0;
}
}
//
// read vector data
//
else if (!strncmp(line, "vectors", 7))
{
if (!this->ReadVectorData(a, numEdges))
{
return 0;
}
}
//
// read 3x2 symmetric tensor data
//
else if (!strncmp(line, "tensors6", 8))
{
if (!this->ReadTensorData(a, numEdges, 6))
{
return 0;
}
}
//
// read 3x3 tensor data
//
else if (!strncmp(line, "tensors", 7))
{
if (!this->ReadTensorData(a, numEdges))
{
return 0;
}
}
//
// read normals data
//
else if (!strncmp(line, "normals", 7))
{
if (!this->ReadNormalData(a, numEdges))
{
return 0;
}
}
//
// read texture coordinates data
//
else if (!strncmp(line, "texture_coordinates", 19))
{
if (!this->ReadTCoordsData(a, numEdges))
{
return 0;
}
}
//
// read the global id data
//
else if (!strncmp(line, "global_ids", 10))
{
if (!this->ReadGlobalIds(a, numEdges))
{
return 0;
}
}
//
// read the pedigree id data
//
else if (!strncmp(line, "pedigree_ids", 12))
{
if (!this->ReadPedigreeIds(a, numEdges))
{
return 0;
}
}
//
// read color scalars data
//
else if (!strncmp(line, "color_scalars", 13))
{
if (!this->ReadCoScalarData(a, numEdges))
{
return 0;
}
}
//
// read lookup table. Associate with scalar data.
//
else if (!strncmp(line, "lookup_table", 12))
{
if (!this->ReadLutData(a))
{
return 0;
}
}
//
// read field of data
//
else if (!strncmp(line, "field", 5))
{
vtkFieldData* f;
if (!(f = this->ReadFieldData()))
{
return 0;
}
for (int i = 0; i < f->GetNumberOfArrays(); i++)
{
a->AddArray(f->GetAbstractArray(i));
}
f->Delete();
}
//
// maybe bumped into vertex data
//
else if (!strncmp(line, "vertex_data", 10))
{
vtkIdType npts;
if (!this->Read(&npts))
{
vtkErrorMacro(<< "Cannot read vertex data!");
return 0;
}
this->ReadVertexData(g, npts);
}
else
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Unsupported vertex attribute type: " << line
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
}
return 1;
}
// Read the row data of a vtk data file.
int vtkDataReader::ReadRowData(vtkTable* t, vtkIdType numEdges)
{
char line[256];
vtkDataSetAttributes* a = t->GetRowData();
vtkDebugMacro(<< "Reading vtk row data");
//
// Read keywords until end-of-file
//
while (this->ReadString(line))
{
//
// read scalar data
//
if (!strncmp(this->LowerCase(line), "scalars", 7))
{
if (!this->ReadScalarData(a, numEdges))
{
return 0;
}
}
//
// read vector data
//
else if (!strncmp(line, "vectors", 7))
{
if (!this->ReadVectorData(a, numEdges))
{
return 0;
}
}
//
// read 3x2 symmetric tensor data
//
else if (!strncmp(line, "tensors6", 8))
{
if (!this->ReadTensorData(a, numEdges, 6))
{
return 0;
}
}
//
// read 3x3 tensor data
//
else if (!strncmp(line, "tensors", 7))
{
if (!this->ReadTensorData(a, numEdges))
{
return 0;
}
}
//
// read normals data
//
else if (!strncmp(line, "normals", 7))
{
if (!this->ReadNormalData(a, numEdges))
{
return 0;
}
}
//
// read texture coordinates data
//
else if (!strncmp(line, "texture_coordinates", 19))
{
if (!this->ReadTCoordsData(a, numEdges))
{
return 0;
}
}
//
// read the global id data
//
else if (!strncmp(line, "global_ids", 10))
{
if (!this->ReadGlobalIds(a, numEdges))
{
return 0;
}
}
//
// read the pedigree id data
//
else if (!strncmp(line, "pedigree_ids", 12))
{
if (!this->ReadPedigreeIds(a, numEdges))
{
return 0;
}
}
//
// read color scalars data
//
else if (!strncmp(line, "color_scalars", 13))
{
if (!this->ReadCoScalarData(a, numEdges))
{
return 0;
}
}
//
// read lookup table. Associate with scalar data.
//
else if (!strncmp(line, "lookup_table", 12))
{
if (!this->ReadLutData(a))
{
return 0;
}
}
//
// read field of data
//
else if (!strncmp(line, "field", 5))
{
vtkFieldData* f;
if (!(f = this->ReadFieldData()))
{
return 0;
}
for (int i = 0; i < f->GetNumberOfArrays(); i++)
{
a->AddArray(f->GetAbstractArray(i));
}
f->Delete();
}
else
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Unsupported row attribute type: " << line
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
}
return 1;
}
// General templated function to read data of various types.
template <class T>
int vtkReadBinaryData(istream* IS, T* data, vtkIdType numTuples, vtkIdType numComp)
{
if (numTuples == 0 || numComp == 0)
{
// nothing to read here.
return 1;
}
char line[256];
// suck up newline
IS->getline(line, 256);
IS->read((char*)data, sizeof(T) * numComp * numTuples);
if (IS->eof())
{
vtkGenericWarningMacro(<< "Error reading binary data!");
return 0;
}
return 1;
}
// General templated function to read data of various types.
template <class T>
int vtkReadASCIIData(vtkDataReader* self, T* data, vtkIdType numTuples, vtkIdType numComp)
{
vtkIdType i, j;
for (i = 0; i < numTuples; i++)
{
for (j = 0; j < numComp; j++)
{
if (!self->Read(data++))
{
vtkGenericWarningMacro(<< "Error reading ascii data. Possible mismatch of "
"datasize with declaration.");
return 0;
}
}
}
return 1;
}
// Description:
// Read data array. Return pointer to array object if successful read;
// otherwise return nullptr. Note: this method instantiates a reference counted
// object with initial count of one; proper protocol is for you to assign
// the data object and then invoke Delete() it to restore proper reference
// count.
vtkAbstractArray* vtkDataReader::ReadArray(
const char* dataType, vtkIdType numTuples, vtkIdType numComp)
{
char* type = strdup(dataType);
type = this->LowerCase(type);
vtkAbstractArray* array;
if (!strncmp(type, "bit", 3))
{
array = vtkBitArray::New();
array->SetNumberOfComponents(numComp);
if (numTuples != 0 && numComp != 0)
{
unsigned char* ptr = ((vtkBitArray*)array)->WritePointer(0, numTuples * numComp);
if (this->FileType == VTK_BINARY)
{
char line[256];
this->IS->getline(line, 256);
this->IS->read((char*)ptr, sizeof(unsigned char) * (numTuples * numComp + 7) / 8);
if (this->IS->eof())
{
vtkErrorMacro(<< "Error reading binary bit array!");
free(type);
array->Delete();
return nullptr;
}
}
else
{
vtkIdType b;
for (vtkIdType i = 0; i < numTuples; i++)
{
for (vtkIdType j = 0; j < numComp; j++)
{
if (!this->Read(&b))
{
vtkErrorMacro("Error reading ascii bit array! tuple: " << i << ", component: " << j);
free(type);
array->Delete();
return nullptr;
}
else
{
((vtkBitArray*)array)->SetValue(i * numComp + j, b);
}
}
}
}
}
}
else if (!strcmp(type, "char") || !strcmp(type, "signed_char"))
{
array = vtkCharArray::New();
array->SetNumberOfComponents(numComp);
char* ptr = ((vtkCharArray*)array)->WritePointer(0, numTuples * numComp);
if (this->FileType == VTK_BINARY)
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if (!strncmp(type, "unsigned_char", 13))
{
array = vtkUnsignedCharArray::New();
array->SetNumberOfComponents(numComp);
unsigned char* ptr = ((vtkUnsignedCharArray*)array)->WritePointer(0, numTuples * numComp);
if (this->FileType == VTK_BINARY)
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if (!strncmp(type, "short", 5))
{
array = vtkShortArray::New();
array->SetNumberOfComponents(numComp);
short* ptr = ((vtkShortArray*)array)->WritePointer(0, numTuples * numComp);
if (this->FileType == VTK_BINARY)
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap2BERange(ptr, numTuples * numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if (!strncmp(type, "unsigned_short", 14))
{
array = vtkUnsignedShortArray::New();
array->SetNumberOfComponents(numComp);
unsigned short* ptr = ((vtkUnsignedShortArray*)array)->WritePointer(0, numTuples * numComp);
if (this->FileType == VTK_BINARY)
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap2BERange((short*)ptr, numTuples * numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if (!strncmp(type, "vtkidtype", 9))
{
// currently writing vtkIdType as int.
array = vtkIdTypeArray::New();
array->SetNumberOfComponents(numComp);
std::vector<int> buffer(numTuples * numComp);
if (this->FileType == VTK_BINARY)
{
vtkReadBinaryData(this->IS, buffer.data(), numTuples, numComp);
vtkByteSwap::Swap4BERange(buffer.data(), numTuples * numComp);
}
else
{
vtkReadASCIIData(this, buffer.data(), numTuples, numComp);
}
vtkIdType* ptr2 = ((vtkIdTypeArray*)array)->WritePointer(0, numTuples * numComp);
for (vtkIdType idx = 0; idx < numTuples * numComp; idx++)
{
ptr2[idx] = buffer[idx];
}
}
else if (!strncmp(type, "int", 3))
{
array = vtkIntArray::New();
array->SetNumberOfComponents(numComp);
int* ptr = ((vtkIntArray*)array)->WritePointer(0, numTuples * numComp);
if (this->FileType == VTK_BINARY)
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap4BERange(ptr, numTuples * numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if (!strncmp(type, "unsigned_int", 12))
{
array = vtkUnsignedIntArray::New();
array->SetNumberOfComponents(numComp);
unsigned int* ptr = ((vtkUnsignedIntArray*)array)->WritePointer(0, numTuples * numComp);
if (this->FileType == VTK_BINARY)
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap4BERange((int*)ptr, numTuples * numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if (!strncmp(type, "long", 4))
{
// vtkDataWriter does not write "long" data anymore
// as data size is not certain
// we keep this for retro compatibility
array = vtkLongArray::New();
array->SetNumberOfComponents(numComp);
long* ptr = ((vtkLongArray*)array)->WritePointer(0, numTuples * numComp);
if (this->FileType == VTK_BINARY)
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
#if VTK_SIZEOF_LONG == 4
vtkByteSwap::Swap4BERange(ptr, numTuples * numComp);
#else // VTK_SIZEOF_LONG == 8
vtkByteSwap::Swap8BERange(ptr, numTuples * numComp);
#endif
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if (!strncmp(type, "unsigned_long", 13))
{
array = vtkUnsignedLongArray::New();
array->SetNumberOfComponents(numComp);
unsigned long* ptr = ((vtkUnsignedLongArray*)array)->WritePointer(0, numTuples * numComp);
if (this->FileType == VTK_BINARY)
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
#if VTK_SIZEOF_LONG == 4
vtkByteSwap::Swap4BERange(ptr, numTuples * numComp);
#else // VTK_SIZEOF_LONG == 8
vtkByteSwap::Swap8BERange(ptr, numTuples * numComp);
#endif
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if (!strncmp(type, "vtktypeint64", 12))
{
array = vtkTypeInt64Array::New();
array->SetNumberOfComponents(numComp);
vtkTypeInt64* ptr = ((vtkTypeInt64Array*)array)->WritePointer(0, numTuples * numComp);
if (this->FileType == VTK_BINARY)
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap8BERange(ptr, numTuples * numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if (!strncmp(type, "vtktypeuint64", 13))
{
array = vtkTypeUInt64Array::New();
array->SetNumberOfComponents(numComp);
vtkTypeUInt64* ptr = ((vtkTypeUInt64Array*)array)->WritePointer(0, numTuples * numComp);
if (this->FileType == VTK_BINARY)
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap8BERange(ptr, numTuples * numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if (!strncmp(type, "float", 5))
{
array = vtkFloatArray::New();
array->SetNumberOfComponents(numComp);
float* ptr = ((vtkFloatArray*)array)->WritePointer(0, numTuples * numComp);
if (this->FileType == VTK_BINARY)
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap4BERange(ptr, numTuples * numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if (!strncmp(type, "double", 6))
{
array = vtkDoubleArray::New();
array->SetNumberOfComponents(numComp);
double* ptr = ((vtkDoubleArray*)array)->WritePointer(0, numTuples * numComp);
if (this->FileType == VTK_BINARY)
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap8BERange(ptr, numTuples * numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if (!strncmp(type, "string", 6))
{
array = vtkStringArray::New();
array->SetNumberOfComponents(numComp);
if (this->FileType == VTK_BINARY)
{
// read in newline
char line[256];
IS->getline(line, 256);
for (vtkIdType i = 0; i < numTuples; i++)
{
for (vtkIdType j = 0; j < numComp; j++)
{
vtkTypeUInt8 firstByte;
vtkTypeUInt8 headerType;
vtkStdString::size_type stringLength;
firstByte = IS->peek();
headerType = firstByte >> 6;
if (headerType == 3)
{
vtkTypeUInt8 length = IS->get();
length <<= 2;
length >>= 2;
stringLength = length;
}
else if (headerType == 2)
{
vtkTypeUInt16 length;
IS->read(reinterpret_cast<char*>(&length), 2);
vtkByteSwap::Swap2BE(&length);
length <<= 2;
length >>= 2;
stringLength = length;
}
else if (headerType == 1)
{
vtkTypeUInt32 length;
IS->read(reinterpret_cast<char*>(&length), 4);
vtkByteSwap::Swap4BE(&length);
length <<= 2;
length >>= 2;
stringLength = length;
}
else
{
vtkTypeUInt64 length;
IS->read(reinterpret_cast<char*>(&length), 8);
vtkByteSwap::Swap4BE(&length);
stringLength = length;
}
std::vector<char> str(stringLength);
IS->read(str.data(), stringLength);
vtkStdString s(str.data(), stringLength);
((vtkStringArray*)array)->InsertNextValue(s);
}
}
}
else
{
// read in newline
vtkStdString s;
my_getline(*(this->IS), s);
for (vtkIdType i = 0; i < numTuples; i++)
{
for (vtkIdType j = 0; j < numComp; j++)
{
my_getline(*(this->IS), s);
int length = static_cast<int>(s.length());
std::vector<char> decoded(length + 1);
int decodedLength = this->DecodeString(decoded.data(), s.c_str());
vtkStdString decodedStr(decoded.data(), decodedLength);
((vtkStringArray*)array)->InsertNextValue(decodedStr);
}
}
}
}
else if (!strncmp(type, "utf8_string", 11))
{
array = vtkUnicodeStringArray::New();
array->SetNumberOfComponents(numComp);
if (this->FileType == VTK_BINARY)
{
// read in newline
char line[256];
IS->getline(line, 256);
for (vtkIdType i = 0; i < numTuples; i++)
{
for (vtkIdType j = 0; j < numComp; j++)
{
vtkTypeUInt8 firstByte;
vtkTypeUInt8 headerType;
vtkStdString::size_type stringLength;
firstByte = IS->peek();
headerType = firstByte >> 6;
if (headerType == 3)
{
vtkTypeUInt8 length = IS->get();
length <<= 2;
length >>= 2;
stringLength = length;
}
else if (headerType == 2)
{
vtkTypeUInt16 length;
IS->read(reinterpret_cast<char*>(&length), 2);
vtkByteSwap::Swap2BE(&length);
length <<= 2;
length >>= 2;
stringLength = length;
}
else if (headerType == 1)
{
vtkTypeUInt32 length;
IS->read(reinterpret_cast<char*>(&length), 4);
vtkByteSwap::Swap4BE(&length);
length <<= 2;
length >>= 2;
stringLength = length;
}
else
{
vtkTypeUInt64 length;
IS->read(reinterpret_cast<char*>(&length), 8);
vtkByteSwap::Swap4BE(&length);
stringLength = length;
}
std::vector<char> str(stringLength);
IS->read(str.data(), stringLength);
vtkUnicodeString s = vtkUnicodeString::from_utf8(str.data(), str.data() + stringLength);
((vtkUnicodeStringArray*)array)->InsertNextValue(s);
}
}
}
else
{
// read in newline
vtkStdString s;
my_getline(*(this->IS), s);
for (vtkIdType i = 0; i < numTuples; i++)
{
for (vtkIdType j = 0; j < numComp; j++)
{
my_getline(*(this->IS), s);
int length = static_cast<int>(s.length());
std::vector<char> decoded(length + 1);
int decodedLength = this->DecodeString(decoded.data(), s.c_str());
vtkUnicodeString decodedStr =
vtkUnicodeString::from_utf8(decoded.data(), decoded.data() + decodedLength);
((vtkUnicodeStringArray*)array)->InsertNextValue(decodedStr);
}
}
}
}
else if (!strncmp(type, "variant", 7))
{
array = vtkVariantArray::New();
array->SetNumberOfComponents(numComp);
for (vtkIdType i = 0; i < numTuples; i++)
{
for (vtkIdType j = 0; j < numComp; j++)
{
int t;
vtkStdString str;
*(this->IS) >> t >> str;
std::vector<char> decoded(str.length() + 1);
int decodedLength = this->DecodeString(decoded.data(), str.c_str());
vtkStdString decodedStr(decoded.data(), decodedLength);
vtkVariant sv(decodedStr);
vtkVariant v;
switch (t)
{
case VTK_CHAR:
v = sv.ToChar();
break;
case VTK_SIGNED_CHAR:
v = sv.ToSignedChar();
break;
case VTK_UNSIGNED_CHAR:
v = sv.ToUnsignedChar();
break;
case VTK_SHORT:
v = sv.ToShort();
break;
case VTK_UNSIGNED_SHORT:
v = sv.ToUnsignedShort();
break;
case VTK_INT:
v = sv.ToInt();
break;
case VTK_UNSIGNED_INT:
v = sv.ToUnsignedInt();
break;
case VTK_LONG:
v = sv.ToLong();
break;
case VTK_UNSIGNED_LONG:
v = sv.ToUnsignedLong();
break;
case VTK_FLOAT:
v = sv.ToFloat();
break;
case VTK_DOUBLE:
v = sv.ToDouble();
break;
case VTK_LONG_LONG:
v = sv.ToLongLong();
break;
case VTK_UNSIGNED_LONG_LONG:
v = sv.ToUnsignedLongLong();
break;
case VTK_STRING:
v = sv.ToString();
break;
default:
vtkErrorMacro("Unknown variant type " << t);
}
((vtkVariantArray*)array)->InsertNextValue(v);
}
}
}
else
{
vtkErrorMacro(<< "Unsupported data type: " << type);
free(type);
return nullptr;
}
free(type);
// Pop off any blank lines, these get added occasionally by the writer
// when the data is a certain length:
bool readyToCheckMetaData = false;
char line[256];
size_t peekSize = this->Peek(line, 256);
bool hasNewData = false;
do
{
hasNewData = false;
// Strip leading whitespace, check for newlines:
for (size_t i = 0; i < peekSize; ++i)
{
switch (line[i])
{
case ' ':
continue;
case '\r':
continue;
case '\n':
// pop line, peek at next
if (!this->ReadLine(line))
{
return array;
}
peekSize = this->Peek(line, 256);
hasNewData = true;
i = peekSize; // Break outer loop
if (peekSize == 0) // EOF
{
return array;
}
break;
default: // Made it past all of the whitespace.
readyToCheckMetaData = true;
i = peekSize; // Break outer loop
break;
}
}
}
// The only time peekSize will be less than 256 (the requested size)
// is if the end of file was reached or an error occurred. Break this
// outermost loop if we are past the whitespace (readyToCheckMetaData)
// or the peekSize hit the end of file but wasn't read in during this
// time through the loop. This handles the case of files that end in
// whitespace without a trailing newline.
while (!readyToCheckMetaData && (peekSize == 256 || hasNewData));
// Peek at the next line to see if there's any array metadata:
if (this->Peek(line, 8) < 8) // looking for "metadata"
{
return array; // EOF?
}
this->LowerCase(&line[0], 8);
if (strncmp(line, "metadata", 8) != 0)
{ // No metadata
return array;
}
// Pop off the meta data line:
if (!this->ReadLine(line))
{
return array;
}
this->LowerCase(line, 256);
assert("sanity check" && strncmp(line, "metadata", 8) == 0);
while (this->ReadLine(line))
{
this->LowerCase(line, 256);
// Blank line indicates end of metadata:
if (strlen(line) == 0)
{
break;
}
if (strncmp(line, "component_names", 15) == 0)
{
char decoded[256];
for (int i = 0; i < numComp; ++i)
{
if (!this->ReadLine(line))
{
vtkErrorMacro(
"Error reading component name " << i << " for array '" << array->GetName() << "'.");
continue;
}
this->DecodeString(decoded, line);
array->SetComponentName(static_cast<vtkIdType>(i), decoded);
}
continue;
}
if (strncmp(line, "information", 11) == 0)
{
int numKeys;
if (sscanf(line, "information %d", &numKeys) != 1)
{
vtkWarningMacro("Invalid information header: " << line);
continue;
}
vtkInformation* info = array->GetInformation();
this->ReadInformation(info, numKeys);
continue;
}
}
return array;
}
// Read point coordinates. Return 0 if error.
int vtkDataReader::ReadPointCoordinates(vtkPointSet* ps, vtkIdType numPts)
{
char line[256];
vtkDataArray* data;
if (!this->ReadString(line))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Cannot read points type!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
data = vtkArrayDownCast<vtkDataArray>(this->ReadArray(line, numPts, 3));
if (data != nullptr)
{
vtkPoints* points = vtkPoints::New();
points->SetData(data);
data->Delete();
ps->SetPoints(points);
points->Delete();
}
else
{
return 0;
}
vtkDebugMacro(<< "Read " << ps->GetNumberOfPoints() << " points");
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5 * (1.0 - progress));
return 1;
}
// Read point coordinates. Return 0 if error.
int vtkDataReader::ReadPointCoordinates(vtkGraph* g, vtkIdType numPts)
{
char line[256];
vtkDataArray* data;
if (!this->ReadString(line))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Cannot read points type!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
data = vtkArrayDownCast<vtkDataArray>(this->ReadArray(line, numPts, 3));
if (data != nullptr)
{
vtkPoints* points = vtkPoints::New();
points->SetData(data);
data->Delete();
g->SetPoints(points);
points->Delete();
}
else
{
return 0;
}
vtkDebugMacro(<< "Read " << g->GetNumberOfVertices() << " points");
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5 * (1.0 - progress));
return 1;
}
// Read the coordinates for a rectilinear grid. The axes parameter specifies
// which coordinate axes (0,1,2) is being read.
int vtkDataReader::ReadCoordinates(vtkRectilinearGrid* rg, int axes, int numCoords)
{
char line[256];
vtkDataArray* data;
if (!this->ReadString(line))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Cannot read coordinates type!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
data = vtkArrayDownCast<vtkDataArray>(this->ReadArray(line, numCoords, 1));
if (!data)
{
return 0;
}
if (axes == 0)
{
rg->SetXCoordinates(data);
}
else if (axes == 1)
{
rg->SetYCoordinates(data);
}
else
{
rg->SetZCoordinates(data);
}
vtkDebugMacro(<< "Read " << data->GetNumberOfTuples() << " coordinates");
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5 * (1.0 - progress));
data->Delete();
return 1;
}
// Read scalar point attributes. Return 0 if error.
int vtkDataReader::ReadScalarData(vtkDataSetAttributes* a, vtkIdType numPts)
{
char line[256], name[256], key[256], tableName[256];
int skipScalar = 0;
vtkDataArray* data;
int numComp = 1;
char buffer[1024];
if (!(this->ReadString(buffer) && this->ReadString(line)))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Cannot read scalar header!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
this->DecodeString(name, buffer);
if (!this->ReadString(key))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Cannot read scalar header!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
// the next string could be an integer number of components or a lookup table
if (strcmp(this->LowerCase(key), "lookup_table"))
{
numComp = atoi(key);
if (numComp < 1 || !this->ReadString(key))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Cannot read scalar header!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
}
if (strcmp(this->LowerCase(key), "lookup_table"))
{
vtkErrorMacro(<< "Lookup table must be specified with scalar.\n"
<< "Use \"LOOKUP_TABLE default\" to use default table.");
return 0;
}
if (!this->ReadString(tableName))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Cannot read scalar header!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
// See whether scalar has been already read or scalar name (if specified)
// matches name in file.
//
if (a->GetScalars() != nullptr || (this->ScalarsName && strcmp(name, this->ScalarsName)))
{
skipScalar = 1;
}
else
{
this->SetScalarLut(tableName); // may be "default"
}
// Read the data
data = vtkArrayDownCast<vtkDataArray>(this->ReadArray(line, numPts, numComp));
if (data != nullptr)
{
data->SetName(name);
if (!skipScalar)
{
a->SetScalars(data);
}
else if (this->ReadAllScalars)
{
a->AddArray(data);
}
data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5 * (1.0 - progress));
return 1;
}
// Read vector point attributes. Return 0 if error.
int vtkDataReader::ReadVectorData(vtkDataSetAttributes* a, vtkIdType numPts)
{
int skipVector = 0;
char line[256], name[256];
vtkDataArray* data;
char buffer[1024];
if (!(this->ReadString(buffer) && this->ReadString(line)))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Cannot read vector data!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
this->DecodeString(name, buffer);
//
// See whether vector has been already read or vector name (if specified)
// matches name in file.
//
if (a->GetVectors() != nullptr || (this->VectorsName && strcmp(name, this->VectorsName)))
{
skipVector = 1;
}
data = vtkArrayDownCast<vtkDataArray>(this->ReadArray(line, numPts, 3));
if (data != nullptr)
{
data->SetName(name);
if (!skipVector)
{
a->SetVectors(data);
}
else if (this->ReadAllVectors)
{
a->AddArray(data);
}
data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5 * (1.0 - progress));
return 1;
}
// Read normal point attributes. Return 0 if error.
int vtkDataReader::ReadNormalData(vtkDataSetAttributes* a, vtkIdType numPts)
{
int skipNormal = 0;
char line[256], name[256];
vtkDataArray* data;
char buffer[1024];
if (!(this->ReadString(buffer) && this->ReadString(line)))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Cannot read normal data!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
this->DecodeString(name, buffer);
//
// See whether normal has been already read or normal name (if specified)
// matches name in file.
//
if (a->GetNormals() != nullptr || (this->NormalsName && strcmp(name, this->NormalsName)))
{
skipNormal = 1;
}
data = vtkArrayDownCast<vtkDataArray>(this->ReadArray(line, numPts, 3));
if (data != nullptr)
{
data->SetName(name);
if (!skipNormal)
{
a->SetNormals(data);
}
else if (this->ReadAllNormals)
{
a->AddArray(data);
}
data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5 * (1.0 - progress));
return 1;
}
// Read tensor point attributes. Return 0 if error.
int vtkDataReader::ReadTensorData(vtkDataSetAttributes* a, vtkIdType numPts, vtkIdType numComp)
{
int skipTensor = 0;
char line[256], name[256];
vtkDataArray* data;
char buffer[1024];
if (!(this->ReadString(buffer) && this->ReadString(line)))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Cannot read tensor data!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
this->DecodeString(name, buffer);
//
// See whether tensor has been already read or tensor name (if specified)
// matches name in file.
//
if (a->GetTensors() != nullptr || (this->TensorsName && strcmp(name, this->TensorsName)))
{
skipTensor = 1;
}
data = vtkArrayDownCast<vtkDataArray>(this->ReadArray(line, numPts, numComp));
if (data != nullptr)
{
data->SetName(name);
if (!skipTensor)
{
a->SetTensors(data);
}
else if (this->ReadAllTensors)
{
a->AddArray(data);
}
data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5 * (1.0 - progress));
return 1;
}
// Read color scalar point attributes. Return 0 if error.
int vtkDataReader::ReadCoScalarData(vtkDataSetAttributes* a, vtkIdType numPts)
{
int i, j, idx, numComp = 0, skipScalar = 0;
char name[256];
char buffer[1024];
if (!(this->ReadString(buffer) && this->Read(&numComp)))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Cannot read color scalar data!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
this->DecodeString(name, buffer);
//
// See whether scalar has been already read or scalar name (if specified)
// matches name in file.
//
if (a->GetScalars() != nullptr || (this->ScalarsName && strcmp(name, this->ScalarsName)))
{
skipScalar = 1;
}
// handle binary different from ASCII since they are stored
// in a different format float versus uchar
if (this->FileType == VTK_BINARY)
{
vtkUnsignedCharArray* data;
char type[14] = "unsigned_char";
data = (vtkUnsignedCharArray*)this->ReadArray(type, numPts, numComp);
if (data != nullptr)
{
data->SetName(name);
if (!skipScalar)
{
a->SetScalars(data);
}
else if (this->ReadAllColorScalars)
{
a->AddArray(data);
}
data->Delete();
}
else
{
return 0;
}
}
else
{
vtkFloatArray* data;
char type[6] = "float";
data = (vtkFloatArray*)this->ReadArray(type, numPts, numComp);
if (data != nullptr)
{
if (!skipScalar || this->ReadAllColorScalars)
{
vtkUnsignedCharArray* scalars = vtkUnsignedCharArray::New();
scalars->SetNumberOfComponents(numComp);
scalars->SetNumberOfTuples(numPts);
scalars->SetName(name);
for (i = 0; i < numPts; i++)
{
for (j = 0; j < numComp; j++)
{
idx = i * numComp + j;
scalars->SetValue(idx, (unsigned char)(255.0 * data->GetValue(idx) + 0.5));
}
}
if (!skipScalar)
{
a->SetScalars(scalars);
}
else if (this->ReadAllColorScalars)
{
a->AddArray(scalars);
}
scalars->Delete();
}
data->Delete();
}
else
{
return 0;
}
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5 * (1.0 - progress));
return 1;
}
// Read texture coordinates point attributes. Return 0 if error.
int vtkDataReader::ReadTCoordsData(vtkDataSetAttributes* a, vtkIdType numPts)
{
int dim = 0;
int skipTCoord = 0;
char line[256], name[256];
vtkDataArray* data;
char buffer[1024];
if (!(this->ReadString(buffer) && this->Read(&dim) && this->ReadString(line)))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Cannot read texture data!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
this->DecodeString(name, buffer);
if (dim < 1 || dim > 3)
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Unsupported texture coordinates dimension: " << dim
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
//
// See whether texture coords have been already read or texture coords name
// (if specified) matches name in file.
//
if (a->GetTCoords() != nullptr || (this->TCoordsName && strcmp(name, this->TCoordsName)))
{
skipTCoord = 1;
}
data = vtkArrayDownCast<vtkDataArray>(this->ReadArray(line, numPts, dim));
if (data != nullptr)
{
data->SetName(name);
if (!skipTCoord)
{
a->SetTCoords(data);
}
else if (this->ReadAllTCoords)
{
a->AddArray(data);
}
data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5 * (1.0 - progress));
return 1;
}
// Read texture coordinates point attributes. Return 0 if error.
int vtkDataReader::ReadGlobalIds(vtkDataSetAttributes* a, vtkIdType numPts)
{
int skipGlobalIds = 0;
char line[256], name[256];
vtkDataArray* data;
char buffer[1024];
if (!(this->ReadString(buffer) && this->ReadString(line)))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Cannot read global id data"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
this->DecodeString(name, buffer);
//
// See whether global ids have been already read
//
if (a->GetGlobalIds() != nullptr)
{
skipGlobalIds = 1;
}
data = vtkArrayDownCast<vtkDataArray>(this->ReadArray(line, numPts, 1));
if (data != nullptr)
{
data->SetName(name);
if (!skipGlobalIds)
{
a->SetGlobalIds(data);
}
data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5 * (1.0 - progress));
return 1;
}
// Read pedigree ids. Return 0 if error.
int vtkDataReader::ReadPedigreeIds(vtkDataSetAttributes* a, vtkIdType numPts)
{
int skipPedigreeIds = 0;
char line[256], name[256];
vtkAbstractArray* data;
char buffer[1024];
if (!(this->ReadString(buffer) && this->ReadString(line)))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Cannot read global id data"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
this->DecodeString(name, buffer);
//
// See whether pedigree ids have been already read
//
if (a->GetPedigreeIds() != nullptr)
{
skipPedigreeIds = 1;
}
data = this->ReadArray(line, numPts, 1);
if (data != nullptr)
{
data->SetName(name);
if (!skipPedigreeIds)
{
a->SetPedigreeIds(data);
}
data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5 * (1.0 - progress));
return 1;
}
// Read edge flags. Return 0 if error.
int vtkDataReader::ReadEdgeFlags(vtkDataSetAttributes* a, vtkIdType numPts)
{
int skipEdgeFlags = 0;
char line[256], name[256];
vtkAbstractArray* data;
char buffer[1024];
if (!(this->ReadString(buffer) && this->ReadString(line)))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Cannot read edge flags data"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
this->DecodeString(name, buffer);
//
// See whether edge flags have been already read
//
if (a->GetAttribute(vtkDataSetAttributes::EDGEFLAG) != nullptr)
{
skipEdgeFlags = 1;
}
data = this->ReadArray(line, numPts, 1);
if (data != nullptr)
{
data->SetName(name);
if (!skipEdgeFlags)
{
a->SetAttribute(data, vtkDataSetAttributes::EDGEFLAG);
}
data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5 * (1.0 - progress));
return 1;
}
int vtkDataReader::ReadInformation(vtkInformation* info, vtkIdType numKeys)
{
// Assuming that the opening INFORMATION line has been read.
char line[256];
char name[256];
char location[256];
for (int keyIdx = 0; keyIdx < numKeys; ++keyIdx)
{
do
{
if (!this->ReadLine(line))
{
vtkErrorMacro("Unexpected EOF while parsing INFORMATION section.");
return 0;
}
} while (strlen(line) == 0); // Skip empty lines
if (strncmp("NAME ", line, 5) == 0)
{ // New key
if (sscanf(line, "NAME %s LOCATION %s", name, location) != 2)
{
vtkWarningMacro("Invalid line in information specification: " << line);
continue;
}
vtkInformationKey* key = vtkInformationKeyLookup::Find(name, location);
if (!key)
{
vtkWarningMacro("Could not locate key "
<< location << "::" << name << ". Is the module in which it is defined linked?");
continue;
}
vtkInformationDoubleKey* dKey = nullptr;
vtkInformationDoubleVectorKey* dvKey = nullptr;
vtkInformationIdTypeKey* idKey = nullptr;
vtkInformationIntegerKey* iKey = nullptr;
vtkInformationIntegerVectorKey* ivKey = nullptr;
vtkInformationStringKey* sKey = nullptr;
vtkInformationStringVectorKey* svKey = nullptr;
vtkInformationUnsignedLongKey* ulKey = nullptr;
if ((dKey = vtkInformationDoubleKey::SafeDownCast(key)))
{
double value;
if (!this->ReadString(line) || strncmp("DATA", line, 4) != 0 || !this->Read(&value))
{
vtkWarningMacro("Malformed data block for key " << location << "::" << name << ".");
continue;
}
// Pop off the trailing newline:
this->ReadLine(line);
info->Set(dKey, value);
continue;
}
else if ((dvKey = vtkInformationDoubleVectorKey::SafeDownCast(key)))
{
int length;
if (!this->ReadString(line) || strncmp("DATA", line, 4) != 0 || !this->Read(&length))
{
vtkWarningMacro("Malformed data block for key " << location << "::" << name << ".");
continue;
}
if (length == 0)
{
info->Set(dvKey, nullptr, 0);
continue;
}
std::vector<double> values;
values.reserve(length);
for (int i = 0; i < length; ++i)
{
double value;
if (!this->Read(&value))
{
vtkWarningMacro("Malformed data block for key " << location << "::" << name << ".");
break;
}
values.push_back(value);
}
if (values.size() == static_cast<size_t>(length))
{
info->Set(dvKey, &values[0], length);
}
// Pop off the trailing newline:
this->ReadLine(line);
continue;
}
else if ((idKey = vtkInformationIdTypeKey::SafeDownCast(key)))
{
vtkIdType value;
if (!this->ReadString(line) || strncmp("DATA", line, 4) != 0 || !this->Read(&value))
{
vtkWarningMacro("Malformed data block for key " << location << "::" << name << ".");
continue;
}
// Pop off the trailing newline:
this->ReadLine(line);
info->Set(idKey, value);
continue;
}
else if ((iKey = vtkInformationIntegerKey::SafeDownCast(key)))
{
int value;
if (!this->ReadString(line) || strncmp("DATA", line, 4) != 0 || !this->Read(&value))
{
vtkWarningMacro("Malformed data block for key " << location << "::" << name << ".");
continue;
}
// Pop off the trailing newline:
this->ReadLine(line);
info->Set(iKey, value);
continue;
}
else if ((ivKey = vtkInformationIntegerVectorKey::SafeDownCast(key)))
{
int length;
if (!this->ReadString(line) || strncmp("DATA", line, 4) != 0 || !this->Read(&length))
{
vtkWarningMacro("Malformed data block for key " << location << "::" << name << ".");
continue;
}
if (length == 0)
{
info->Set(ivKey, nullptr, 0);
continue;
}
std::vector<int> values;
values.reserve(length);
for (int i = 0; i < length; ++i)
{
int value;
if (!this->Read(&value))
{
vtkWarningMacro("Malformed data block for key " << location << "::" << name << ".");
break;
}
values.push_back(value);
}
if (values.size() == static_cast<size_t>(length))
{
info->Set(ivKey, &values[0], length);
}
// Pop off the trailing newline:
this->ReadLine(line);
continue;
}
else if ((sKey = vtkInformationStringKey::SafeDownCast(key)))
{
if (!this->ReadLine(line))
{
vtkWarningMacro("Unexpected EOF while parsing key " << location << "::" << name << ".");
continue;
}
char value[256];
if (sscanf(line, "DATA %s", value) != 1)
{
vtkWarningMacro("Malformed data block for key " << location << "::" << name << ".");
continue;
}
char decoded[256];
this->DecodeString(decoded, value);
info->Set(sKey, decoded);
}
else if ((svKey = vtkInformationStringVectorKey::SafeDownCast(key)))
{
int length;
if (!this->ReadString(line) || strncmp("DATA", line, 4) != 0 || !this->Read(&length))
{
vtkWarningMacro("Malformed data block for key " << location << "::" << name << ".");
continue;
}
// Pop off the trailing newline:
this->ReadLine(line);
if (length == 0)
{
info->Set(svKey, nullptr, 0);
continue;
}
// Just build the string vector information by appending, as these
// don't really implement the RequiredLength feature like the other
// vector keys.
bool success = true;
for (int i = 0; i < length; ++i)
{
char value[256];
if (!this->ReadLine(value))
{
vtkWarningMacro("Malformed data block for key " << location << "::" << name << ".");
success = false;
break;
}
char decoded[256];
this->DecodeString(decoded, value);
info->Append(svKey, decoded);
}
if (!success)
{
info->Remove(svKey);
}
continue;
}
else if ((ulKey = vtkInformationUnsignedLongKey::SafeDownCast(key)))
{
unsigned long value;
if (!this->ReadString(line) || strncmp("DATA", line, 4) != 0 || !this->Read(&value))
{
vtkWarningMacro("Malformed data block for key " << location << "::" << name << ".");
continue;
}
// Pop off the trailing newline:
this->ReadLine(line);
info->Set(ulKey, value);
continue;
}
else
{
vtkWarningMacro("Could not deserialize information with key "
<< key->GetLocation() << "::" << key->GetName()
<< ": "
"key type '"
<< key->GetClassName() << "' is not serializable.");
continue;
}
}
else
{
vtkWarningMacro("Ignoring line in INFORMATION block: " << line);
}
}
return 1;
}
// Read lookup table. Return 0 if error.
int vtkDataReader::ReadLutData(vtkDataSetAttributes* a)
{
int i;
int size = 0, skipTable = 0;
vtkLookupTable* lut;
unsigned char* ptr;
char line[256], name[256];
if (!(this->ReadString(name) && this->Read(&size)))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Cannot read lookup table data!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
if (a->GetScalars() == nullptr ||
(this->LookupTableName && strcmp(name, this->LookupTableName)) ||
(this->ScalarLut && strcmp(name, this->ScalarLut)))
{
skipTable = 1;
}
lut = vtkLookupTable::New();
lut->Allocate(size);
ptr = lut->WritePointer(0, size);
if (this->FileType == VTK_BINARY)
{
// suck up newline
this->IS->getline(line, 256);
this->IS->read((char*)ptr, sizeof(unsigned char) * 4 * size);
if (this->IS->eof())
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Error reading binary lookup table!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
}
else // ascii
{
float rgba[4];
for (i = 0; i < size; i++)
{
if (!(this->Read(rgba) && this->Read(rgba + 1) && this->Read(rgba + 2) &&
this->Read(rgba + 3)))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Error reading lookup table!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
lut->SetTableValue(i, rgba[0], rgba[1], rgba[2], rgba[3]);
}
}
if (!skipTable)
{
a->GetScalars()->SetLookupTable(lut);
}
lut->Delete();
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5 * (1.0 - progress));
return 1;
}
int vtkDataReader::ReadCells(vtkSmartPointer<vtkCellArray>& cellArray)
{
vtkIdType offsetsSize{ 0 };
vtkIdType connSize{ 0 };
char buffer[256];
if (!(this->Read(&offsetsSize) && this->Read(&connSize)))
{
vtkErrorMacro("Error while reading cell array header.");
this->CloseVTKFile();
return 0;
}
if (offsetsSize < 1)
{
cellArray = vtkSmartPointer<vtkCellArray>::New();
return 1;
}
if (!this->ReadString(buffer) || // "offsets"
(strcmp(this->LowerCase(buffer, 256), "offsets") != 0) || !this->ReadString(buffer)) // datatype
{
vtkErrorMacro("Error reading cell array offset header.");
this->CloseVTKFile();
return 0;
}
this->LowerCase(buffer, 256);
auto offsets = vtk::TakeSmartPointer(this->ReadArray(buffer, offsetsSize, 1));
if (!offsets)
{
vtkErrorMacro("Error reading cell array offset data.");
this->CloseVTKFile();
return 0;
}
if (!this->ReadString(buffer) || // "connectivity"
(strcmp(this->LowerCase(buffer, 256), "connectivity") != 0) ||
!this->ReadString(buffer)) // datatype
{
vtkErrorMacro("Error reading cell array connectivity header.");
this->CloseVTKFile();
return 0;
}
this->LowerCase(buffer, 256);
auto conn = vtk::TakeSmartPointer(this->ReadArray(buffer, connSize, 1));
if (!conn)
{
vtkErrorMacro("Error reading cell array connectivity data.");
this->CloseVTKFile();
return 0;
}
// Check that they are the indicated types and add them to the cell array:
auto* offDA = vtkArrayDownCast<vtkDataArray>(offsets.Get());
auto* connDA = vtkArrayDownCast<vtkDataArray>(conn.Get());
if (!offDA || !connDA)
{
vtkErrorMacro("Offsets and connectivity arrays must subclass vtkDataArray.");
this->CloseVTKFile();
return 0;
}
cellArray = vtkSmartPointer<vtkCellArray>::New();
bool succ = cellArray->SetData(offDA, connDA);
if (!succ)
{ // SetData logs error for us
cellArray = nullptr;
this->CloseVTKFile();
return 0;
}
return 1;
}
// Read lookup table. Return 0 if error.
int vtkDataReader::ReadCellsLegacy(vtkIdType size, int* data)
{
char line[256];
int i;
if (this->FileType == VTK_BINARY)
{
// suck up newline
this->IS->getline(line, 256);
this->IS->read((char*)data, sizeof(int) * size);
if (this->IS->eof())
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Error reading binary cell data!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
vtkByteSwap::Swap4BERange(data, size);
}
else // ascii
{
for (i = 0; i < size; i++)
{
if (!this->Read(data + i))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Error reading ascii cell data!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
}
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5 * (1.0 - progress));
return 1;
}
int vtkDataReader::ReadCellsLegacy(vtkIdType size, int* data, int skip1, int read2, int skip3)
{
char line[256];
int i, numCellPts, junk, *tmp, *pTmp;
std::vector<int> tmpStorage;
if (this->FileType == VTK_BINARY)
{
// suck up newline
this->IS->getline(line, 256);
// first read all the cells as one chunk (each cell has different length).
if (skip1 == 0 && skip3 == 0)
{
tmp = data;
}
else
{
tmpStorage.resize(size);
tmp = tmpStorage.data();
}
this->IS->read((char*)tmp, sizeof(int) * size);
if (this->IS->eof())
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Error reading binary cell data!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
vtkByteSwap::Swap4BERange(tmp, size);
if (tmp == data)
{
return 1;
}
// skip cells before the piece
pTmp = tmp;
while (skip1 > 0)
{
// the first value is the number of point ids
// skip these plus one for the number itself.
pTmp += *pTmp + 1;
--skip1;
}
// copy the cells in the piece
// (ok, I am getting criptic with the loops and increments ...)
while (read2 > 0)
{
// the first value is the number of point ids
*data++ = i = *pTmp++;
while (i-- > 0)
{
*data++ = *pTmp++;
}
--read2;
}
}
else // ascii
{
// skip cells before the piece
for (i = 0; i < skip1; i++)
{
if (!this->Read(&numCellPts))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Error reading ascii cell data!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
while (numCellPts-- > 0)
{
this->Read(&junk);
}
}
// read the cells in the piece
for (i = 0; i < read2; i++)
{
if (!this->Read(data))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Error reading ascii cell data!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
numCellPts = *data++;
while (numCellPts-- > 0)
{
this->Read(data++);
}
}
// skip cells after the piece
for (i = 0; i < skip3; i++)
{
if (!this->Read(&numCellPts))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Error reading ascii cell data!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return 0;
}
while (numCellPts-- > 0)
{
this->Read(&junk);
}
}
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5 * (1.0 - progress));
return 1;
}
void vtkDataReader::ConvertGhostLevelsToGhostType(FieldType fieldType, vtkAbstractArray* data) const
{
vtkUnsignedCharArray* ucData = vtkArrayDownCast<vtkUnsignedCharArray>(data);
const char* name = data->GetName();
int numComp = data->GetNumberOfComponents();
if (this->FileMajorVersion < 4 && ucData && numComp == 1 &&
(fieldType == CELL_DATA || fieldType == POINT_DATA) && !strcmp(name, "vtkGhostLevels"))
{
// convert ghost levels to ghost type
unsigned char* ghosts = ucData->GetPointer(0);
// only CELL_DATA or POINT_DATA are possible at this point.
unsigned char newValue = vtkDataSetAttributes::DUPLICATEPOINT;
if (fieldType == CELL_DATA)
{
newValue = vtkDataSetAttributes::DUPLICATECELL;
}
vtkIdType numTuples = ucData->GetNumberOfTuples();
for (int i = 0; i < numTuples; ++i)
{
if (ghosts[i] > 0)
{
ghosts[i] = newValue;
}
}
data->SetName(vtkDataSetAttributes::GhostArrayName());
}
}
vtkFieldData* vtkDataReader::ReadFieldData(FieldType fieldType)
{
int i, numArrays = 0, skipField = 0;
vtkFieldData* f;
char name[256], type[256];
vtkIdType numComp, numTuples;
vtkAbstractArray* data;
if (!(this->ReadString(name) && this->Read(&numArrays)))
{
const char* fname = this->CurrentFileName.c_str();
vtkErrorMacro(<< "Cannot read field header!"
<< " for file: " << (fname ? fname : "(Null FileName)"));
return nullptr;
}
// See whether field data name (if specified)
if ((this->FieldDataName && strcmp(name, this->FieldDataName)))
{
skipField = 1;
}
f = vtkFieldData::New();
f->AllocateArrays(numArrays);
// Read the number of arrays specified
for (i = 0; i < numArrays; i++)
{
char buffer[1024];
this->ReadString(buffer);
if (strcmp(buffer, "NULL_ARRAY") == 0)
{
continue;
}
this->DecodeString(name, buffer);
this->Read(&numComp);
this->Read(&numTuples);
this->ReadString(type);
data = this->ReadArray(type, numTuples, numComp);
if (data != nullptr)
{
if (!skipField || this->ReadAllFields)
{
data->SetName(name);
this->ConvertGhostLevelsToGhostType(fieldType, data);
f->AddArray(data);
}
data->Delete();
}
else
{
f->Delete();
return nullptr;
}
}
if (skipField && !this->ReadAllFields)
{
f->Delete();
return nullptr;
}
else
{
return f;
}
}
char* vtkDataReader::LowerCase(char* str, const size_t len)
{
size_t i;
char* s;
for (i = 0, s = str; *s != '\0' && i < len; s++, i++)
{
*s = tolower(*s);
}
return str;
}
// Close a vtk file.
void vtkDataReader::CloseVTKFile()
{
vtkDebugMacro(<< "Closing vtk file");
// Restore the previous locale settings
std::locale::global(this->CurrentLocale);
delete this->IS;
this->IS = nullptr;
}
void vtkDataReader::InitializeCharacteristics()
{
int i;
// Release any old stuff first
if (this->ScalarsNameInFile)
{
for (i = 0; i < this->NumberOfScalarsInFile; i++)
{
delete[] this->ScalarsNameInFile[i];
}
this->NumberOfScalarsInFile = 0;
delete[] this->ScalarsNameInFile;
this->ScalarsNameInFile = nullptr;
}
if (this->VectorsNameInFile)
{
for (i = 0; i < this->NumberOfVectorsInFile; i++)
{
delete[] this->VectorsNameInFile[i];
}
this->NumberOfVectorsInFile = 0;
delete[] this->VectorsNameInFile;
this->VectorsNameInFile = nullptr;
}
if (this->TensorsNameInFile)
{
for (i = 0; i < this->NumberOfTensorsInFile; i++)
{
delete[] this->TensorsNameInFile[i];
}
this->NumberOfTensorsInFile = 0;
delete[] this->TensorsNameInFile;
this->TensorsNameInFile = nullptr;
}
if (this->NormalsNameInFile)
{
for (i = 0; i < this->NumberOfNormalsInFile; i++)
{
delete[] this->NormalsNameInFile[i];
}
this->NumberOfNormalsInFile = 0;
delete[] this->NormalsNameInFile;
this->NormalsNameInFile = nullptr;
}
if (this->TCoordsNameInFile)
{
for (i = 0; i < this->NumberOfTCoordsInFile; i++)
{
delete[] this->TCoordsNameInFile[i];
}
this->NumberOfTCoordsInFile = 0;
delete[] this->TCoordsNameInFile;
this->TCoordsNameInFile = nullptr;
}
if (this->FieldDataNameInFile)
{
for (i = 0; i < this->NumberOfFieldDataInFile; i++)
{
delete[] this->FieldDataNameInFile[i];
}
this->NumberOfFieldDataInFile = 0;
delete[] this->FieldDataNameInFile;
this->FieldDataNameInFile = nullptr;
}
}
// read entire file, storing important characteristics
int vtkDataReader::CharacterizeFile()
{
if (this->CharacteristicsTime > this->MTime)
{
return 1;
}
this->InitializeCharacteristics();
this->CharacteristicsTime.Modified();
// Open the file
if (!this->OpenVTKFile() || !this->ReadHeader())
{
this->CloseVTKFile();
return 0;
}
char line[256];
while (this->ReadLine(line))
{
this->CheckFor("scalars", line, this->NumberOfScalarsInFile, this->ScalarsNameInFile,
this->ScalarsNameAllocSize);
this->CheckFor("vectors", line, this->NumberOfVectorsInFile, this->VectorsNameInFile,
this->VectorsNameAllocSize);
this->CheckFor("tensors", line, this->NumberOfTensorsInFile, this->TensorsNameInFile,
this->TensorsNameAllocSize);
this->CheckFor("normals", line, this->NumberOfNormalsInFile, this->NormalsNameInFile,
this->NormalsNameAllocSize);
this->CheckFor("tcoords", line, this->NumberOfTCoordsInFile, this->TCoordsNameInFile,
this->TCoordsNameAllocSize);
this->CheckFor("field", line, this->NumberOfFieldDataInFile, this->FieldDataNameInFile,
this->FieldDataNameAllocSize);
}
this->CloseVTKFile();
return 1;
}
void vtkDataReader::CheckFor(const char* name, char* line, int& num, char**& array, int& allocSize)
{
if (!strncmp(this->LowerCase(line, strlen(name)), name, strlen(name)))
{
int i;
int newAllocSize;
char** newArray;
// update numbers
num++;
if (!array)
{
allocSize = 25;
array = new char*[allocSize];
for (i = 0; i < allocSize; i++)
{
array[i] = nullptr;
}
}
else if (num >= allocSize)
{
newAllocSize = 2 * num;
newArray = new char*[newAllocSize];
for (i = 0; i < allocSize; i++)
{
newArray[i] = array[i];
}
for (i = allocSize; i < newAllocSize; i++)
{
newArray[i] = nullptr;
}
allocSize = newAllocSize;
delete[] array;
array = newArray;
}
// enter the name
char nameOfAttribute[256];
sscanf(line, "%*s %s", nameOfAttribute);
if (*nameOfAttribute)
{
array[num - 1] = new char[strlen(nameOfAttribute) + 1];
strcpy(array[num - 1], nameOfAttribute);
}
} // found one
}
const char* vtkDataReader::GetScalarsNameInFile(int i)
{
this->CharacterizeFile();
if (!this->ScalarsNameInFile || i < 0 || i >= this->NumberOfScalarsInFile)
{
return nullptr;
}
else
{
return this->ScalarsNameInFile[i];
}
}
const char* vtkDataReader::GetVectorsNameInFile(int i)
{
this->CharacterizeFile();
if (!this->VectorsNameInFile || i < 0 || i >= this->NumberOfVectorsInFile)
{
return nullptr;
}
else
{
return this->VectorsNameInFile[i];
}
}
const char* vtkDataReader::GetTensorsNameInFile(int i)
{
this->CharacterizeFile();
if (!this->TensorsNameInFile || i < 0 || i >= this->NumberOfTensorsInFile)
{
return nullptr;
}
else
{
return this->TensorsNameInFile[i];
}
}
const char* vtkDataReader::GetNormalsNameInFile(int i)
{
this->CharacterizeFile();
if (!this->NormalsNameInFile || i < 0 || i >= this->NumberOfNormalsInFile)
{
return nullptr;
}
else
{
return this->NormalsNameInFile[i];
}
}
const char* vtkDataReader::GetTCoordsNameInFile(int i)
{
this->CharacterizeFile();
if (!this->TCoordsNameInFile || i < 0 || i >= this->NumberOfTCoordsInFile)
{
return nullptr;
}
else
{
return this->TCoordsNameInFile[i];
}
}
const char* vtkDataReader::GetFieldDataNameInFile(int i)
{
this->CharacterizeFile();
if (!this->FieldDataNameInFile || i < 0 || i >= this->NumberOfFieldDataInFile)
{
return nullptr;
}
else
{
return this->FieldDataNameInFile[i];
}
}
vtkTypeBool vtkDataReader::ProcessRequest(
vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector)
{
// generate the data
if (request->Has(vtkDemandDrivenPipeline::REQUEST_DATA()))
{
return this->RequestData(request, inputVector, outputVector);
}
if (request->Has(vtkStreamingDemandDrivenPipeline::REQUEST_UPDATE_EXTENT()))
{
return this->RequestUpdateExtent(request, inputVector, outputVector);
}
// execute information
if (request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION()))
{
return this->RequestInformation(request, inputVector, outputVector);
}
return this->Superclass::ProcessRequest(request, inputVector, outputVector);
}
void vtkDataReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
if (this->FileType == VTK_BINARY)
{
os << indent << "File Type: BINARY\n";
}
else
{
os << indent << "File Type: ASCII\n";
}
if (this->Header)
{
os << indent << "Header: " << this->Header << "\n";
}
else
{
os << indent << "Header: (None)\n";
}
os << indent << "ReadFromInputString: " << (this->ReadFromInputString ? "On\n" : "Off\n");
if (this->InputString)
{
os << indent << "Input String: " << this->InputString << "\n";
}
else
{
os << indent << "Input String: (None)\n";
}
if (this->InputArray)
{
os << indent << "Input Array: "
<< "\n";
this->InputArray->PrintSelf(os, indent.GetNextIndent());
}
else
{
os << indent << "Input String: (None)\n";
}
os << indent << "Input String Length: " << this->InputStringLength << endl;
if (this->ScalarsName)
{
os << indent << "Scalars Name: " << this->ScalarsName << "\n";
}
else
{
os << indent << "Scalars Name: (None)\n";
}
os << indent << "ReadAllScalars: " << (this->ReadAllScalars ? "On" : "Off") << "\n";
if (this->VectorsName)
{
os << indent << "Vectors Name: " << this->VectorsName << "\n";
}
else
{
os << indent << "Vectors Name: (None)\n";
}
os << indent << "ReadAllVectors: " << (this->ReadAllVectors ? "On" : "Off") << "\n";
if (this->NormalsName)
{
os << indent << "Normals Name: " << this->NormalsName << "\n";
}
else
{
os << indent << "Normals Name: (None)\n";
}
os << indent << "ReadAllNormals: " << (this->ReadAllNormals ? "On" : "Off") << "\n";
if (this->TensorsName)
{
os << indent << "Tensors Name: " << this->TensorsName << "\n";
}
else
{
os << indent << "Tensors Name: (None)\n";
}
os << indent << "ReadAllTensors: " << (this->ReadAllTensors ? "On" : "Off") << "\n";
if (this->TCoordsName)
{
os << indent << "Texture Coords Name: " << this->TCoordsName << "\n";
}
else
{
os << indent << "Texture Coordinates Name: (None)\n";
}
os << indent << "ReadAllTCoords: " << (this->ReadAllTCoords ? "On" : "Off") << "\n";
if (this->LookupTableName)
{
os << indent << "Lookup Table Name: " << this->LookupTableName << "\n";
}
else
{
os << indent << "Lookup Table Name: (None)\n";
}
os << indent << "ReadAllColorScalars: " << (this->ReadAllColorScalars ? "On" : "Off") << "\n";
if (this->FieldDataName)
{
os << indent << "Field Data Name: " << this->FieldDataName << "\n";
}
else
{
os << indent << "Field Data Name: (None)\n";
}
os << indent << "ReadAllFields: " << (this->ReadAllFields ? "On" : "Off") << "\n";
os << indent << "InputStringLength: " << this->InputStringLength << endl;
}
int vtkDataReader::ReadDataSetData(vtkDataSet* vtkNotUsed(ds))
{
return 0;
}
int vtkDataReader::DecodeString(char* resname, const char* name)
{
if (!resname || !name)
{
return 0;
}
std::ostringstream str;
size_t cc = 0;
unsigned int ch;
size_t len = strlen(name);
size_t reslen = 0;
char buffer[10] = "0x";
while (name[cc])
{
if (name[cc] == '%')
{
if (cc <= (len - 3))
{
buffer[2] = name[cc + 1];
buffer[3] = name[cc + 2];
buffer[4] = 0;
sscanf(buffer, "%x", &ch);
str << static_cast<char>(ch);
cc += 2;
reslen++;
}
}
else
{
str << name[cc];
reslen++;
}
cc++;
}
strncpy(resname, str.str().c_str(), reslen + 1);
resname[reslen] = 0;
return static_cast<int>(reslen);
}
static int my_getline(istream& in, vtkStdString& out, char delimiter)
{
out = vtkStdString();
unsigned int numCharactersRead = 0;
int nextValue = 0;
while ((nextValue = in.get()) != EOF && numCharactersRead < out.max_size())
{
++numCharactersRead;
char downcast = static_cast<char>(nextValue);
if (downcast != delimiter)
{
out += downcast;
}
else
{
return numCharactersRead;
}
}
return numCharactersRead;
}
//----------------------------------------------------------------------------
void vtkDataReader::SetScalarLut(const char* sl)
{
if (!this->ScalarLut && !sl)
{
return;
}
if (this->ScalarLut && sl && (strcmp(this->ScalarLut, sl)) == 0)
{
return;
}
delete[] this->ScalarLut;
this->ScalarLut = nullptr;
if (sl)
{
size_t n = strlen(sl) + 1;
char* cp1 = new char[n];
const char* cp2 = sl;
this->ScalarLut = cp1;
do
{
*cp1++ = *cp2++;
} while (--n);
}
}
|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "assembler_x86_64.h"
#include "base/casts.h"
#include "entrypoints/quick/quick_entrypoints.h"
#include "memory_region.h"
#include "thread.h"
namespace art {
namespace x86_64 {
std::ostream& operator<<(std::ostream& os, const CpuRegister& reg) {
return os << reg.AsRegister();
}
std::ostream& operator<<(std::ostream& os, const XmmRegister& reg) {
return os << reg.AsFloatRegister();
}
std::ostream& operator<<(std::ostream& os, const X87Register& reg) {
return os << "ST" << static_cast<int>(reg);
}
std::ostream& operator<<(std::ostream& os, const Address& addr) {
switch (addr.mod()) {
case 0:
if (addr.rm() != RSP || addr.cpu_index().AsRegister() == RSP) {
return os << "(%" << addr.cpu_rm() << ")";
} else if (addr.base() == RBP) {
return os << static_cast<int>(addr.disp32()) << "(,%" << addr.cpu_index()
<< "," << (1 << addr.scale()) << ")";
}
return os << "(%" << addr.cpu_base() << ",%"
<< addr.cpu_index() << "," << (1 << addr.scale()) << ")";
case 1:
if (addr.rm() != RSP || addr.cpu_index().AsRegister() == RSP) {
return os << static_cast<int>(addr.disp8()) << "(%" << addr.cpu_rm() << ")";
}
return os << static_cast<int>(addr.disp8()) << "(%" << addr.cpu_base() << ",%"
<< addr.cpu_index() << "," << (1 << addr.scale()) << ")";
case 2:
if (addr.rm() != RSP || addr.cpu_index().AsRegister() == RSP) {
return os << static_cast<int>(addr.disp32()) << "(%" << addr.cpu_rm() << ")";
}
return os << static_cast<int>(addr.disp32()) << "(%" << addr.cpu_base() << ",%"
<< addr.cpu_index() << "," << (1 << addr.scale()) << ")";
default:
return os << "<address?>";
}
}
void X86_64Assembler::call(CpuRegister reg) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg);
EmitUint8(0xFF);
EmitRegisterOperand(2, reg.LowBits());
}
void X86_64Assembler::call(const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(address);
EmitUint8(0xFF);
EmitOperand(2, address);
}
void X86_64Assembler::call(Label* label) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xE8);
static const int kSize = 5;
// Offset by one because we already have emitted the opcode.
EmitLabel(label, kSize - 1);
}
void X86_64Assembler::pushq(CpuRegister reg) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg);
EmitUint8(0x50 + reg.LowBits());
}
void X86_64Assembler::pushq(const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(address);
EmitUint8(0xFF);
EmitOperand(6, address);
}
void X86_64Assembler::pushq(const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
CHECK(imm.is_int32()); // pushq only supports 32b immediate.
if (imm.is_int8()) {
EmitUint8(0x6A);
EmitUint8(imm.value() & 0xFF);
} else {
EmitUint8(0x68);
EmitImmediate(imm);
}
}
void X86_64Assembler::popq(CpuRegister reg) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg);
EmitUint8(0x58 + reg.LowBits());
}
void X86_64Assembler::popq(const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(address);
EmitUint8(0x8F);
EmitOperand(0, address);
}
void X86_64Assembler::movq(CpuRegister dst, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
if (imm.is_int32()) {
// 32 bit. Note: sign-extends.
EmitRex64(dst);
EmitUint8(0xC7);
EmitRegisterOperand(0, dst.LowBits());
EmitInt32(static_cast<int32_t>(imm.value()));
} else {
EmitRex64(dst);
EmitUint8(0xB8 + dst.LowBits());
EmitInt64(imm.value());
}
}
void X86_64Assembler::movl(CpuRegister dst, const Immediate& imm) {
CHECK(imm.is_int32());
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst);
EmitUint8(0xB8 + dst.LowBits());
EmitImmediate(imm);
}
void X86_64Assembler::movq(const Address& dst, const Immediate& imm) {
CHECK(imm.is_int32());
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst);
EmitUint8(0xC7);
EmitOperand(0, dst);
EmitImmediate(imm);
}
void X86_64Assembler::movq(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
// 0x89 is movq r/m64 <- r64, with op1 in r/m and op2 in reg: so reverse EmitRex64
EmitRex64(src, dst);
EmitUint8(0x89);
EmitRegisterOperand(src.LowBits(), dst.LowBits());
}
void X86_64Assembler::movl(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x8B);
EmitRegisterOperand(dst.LowBits(), src.LowBits());
}
void X86_64Assembler::movq(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst, src);
EmitUint8(0x8B);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::movl(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x8B);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::movq(const Address& dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(src, dst);
EmitUint8(0x89);
EmitOperand(src.LowBits(), dst);
}
void X86_64Assembler::movl(const Address& dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(src, dst);
EmitUint8(0x89);
EmitOperand(src.LowBits(), dst);
}
void X86_64Assembler::movl(const Address& dst, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst);
EmitUint8(0xC7);
EmitOperand(0, dst);
EmitImmediate(imm);
}
void X86_64Assembler::movntl(const Address& dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(src, dst);
EmitUint8(0x0F);
EmitUint8(0xC3);
EmitOperand(src.LowBits(), dst);
}
void X86_64Assembler::movntq(const Address& dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(src, dst);
EmitUint8(0x0F);
EmitUint8(0xC3);
EmitOperand(src.LowBits(), dst);
}
void X86_64Assembler::cmov(Condition c, CpuRegister dst, CpuRegister src) {
cmov(c, dst, src, true);
}
void X86_64Assembler::cmov(Condition c, CpuRegister dst, CpuRegister src, bool is64bit) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex(false, is64bit, dst.NeedsRex(), false, src.NeedsRex());
EmitUint8(0x0F);
EmitUint8(0x40 + c);
EmitRegisterOperand(dst.LowBits(), src.LowBits());
}
void X86_64Assembler::cmov(Condition c, CpuRegister dst, const Address& src, bool is64bit) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
if (is64bit) {
EmitRex64(dst, src);
} else {
EmitOptionalRex32(dst, src);
}
EmitUint8(0x0F);
EmitUint8(0x40 + c);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::movzxb(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalByteRegNormalizingRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xB6);
EmitRegisterOperand(dst.LowBits(), src.LowBits());
}
void X86_64Assembler::movzxb(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
// Byte register is only in the source register form, so we don't use
// EmitOptionalByteRegNormalizingRex32(dst, src);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xB6);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::movsxb(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalByteRegNormalizingRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xBE);
EmitRegisterOperand(dst.LowBits(), src.LowBits());
}
void X86_64Assembler::movsxb(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
// Byte register is only in the source register form, so we don't use
// EmitOptionalByteRegNormalizingRex32(dst, src);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xBE);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::movb(CpuRegister /*dst*/, const Address& /*src*/) {
LOG(FATAL) << "Use movzxb or movsxb instead.";
}
void X86_64Assembler::movb(const Address& dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalByteRegNormalizingRex32(src, dst);
EmitUint8(0x88);
EmitOperand(src.LowBits(), dst);
}
void X86_64Assembler::movb(const Address& dst, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst);
EmitUint8(0xC6);
EmitOperand(Register::RAX, dst);
CHECK(imm.is_int8());
EmitUint8(imm.value() & 0xFF);
}
void X86_64Assembler::movzxw(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xB7);
EmitRegisterOperand(dst.LowBits(), src.LowBits());
}
void X86_64Assembler::movzxw(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xB7);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::movsxw(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xBF);
EmitRegisterOperand(dst.LowBits(), src.LowBits());
}
void X86_64Assembler::movsxw(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xBF);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::movw(CpuRegister /*dst*/, const Address& /*src*/) {
LOG(FATAL) << "Use movzxw or movsxw instead.";
}
void X86_64Assembler::movw(const Address& dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOperandSizeOverride();
EmitOptionalRex32(src, dst);
EmitUint8(0x89);
EmitOperand(src.LowBits(), dst);
}
void X86_64Assembler::movw(const Address& dst, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOperandSizeOverride();
EmitOptionalRex32(dst);
EmitUint8(0xC7);
EmitOperand(Register::RAX, dst);
CHECK(imm.is_uint16() || imm.is_int16());
EmitUint8(imm.value() & 0xFF);
EmitUint8(imm.value() >> 8);
}
void X86_64Assembler::leaq(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst, src);
EmitUint8(0x8D);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::leal(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x8D);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::movaps(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x28);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::movaps(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x28);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::movups(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x10);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::movaps(const Address& dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(src, dst);
EmitUint8(0x0F);
EmitUint8(0x29);
EmitOperand(src.LowBits(), dst);
}
void X86_64Assembler::movups(const Address& dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(src, dst);
EmitUint8(0x0F);
EmitUint8(0x11);
EmitOperand(src.LowBits(), dst);
}
void X86_64Assembler::movss(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x10);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::movss(const Address& dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(src, dst);
EmitUint8(0x0F);
EmitUint8(0x11);
EmitOperand(src.LowBits(), dst);
}
void X86_64Assembler::movss(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(src, dst); // Movss is MR encoding instead of the usual RM.
EmitUint8(0x0F);
EmitUint8(0x11);
EmitXmmRegisterOperand(src.LowBits(), dst);
}
void X86_64Assembler::movsxd(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst, src);
EmitUint8(0x63);
EmitRegisterOperand(dst.LowBits(), src.LowBits());
}
void X86_64Assembler::movsxd(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst, src);
EmitUint8(0x63);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::movd(XmmRegister dst, CpuRegister src) {
movd(dst, src, true);
}
void X86_64Assembler::movd(CpuRegister dst, XmmRegister src) {
movd(dst, src, true);
}
void X86_64Assembler::movd(XmmRegister dst, CpuRegister src, bool is64bit) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex(false, is64bit, dst.NeedsRex(), false, src.NeedsRex());
EmitUint8(0x0F);
EmitUint8(0x6E);
EmitOperand(dst.LowBits(), Operand(src));
}
void X86_64Assembler::movd(CpuRegister dst, XmmRegister src, bool is64bit) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex(false, is64bit, src.NeedsRex(), false, dst.NeedsRex());
EmitUint8(0x0F);
EmitUint8(0x7E);
EmitOperand(src.LowBits(), Operand(dst));
}
void X86_64Assembler::addss(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x58);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::addss(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x58);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::subss(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5C);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::subss(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5C);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::mulss(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x59);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::mulss(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x59);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::divss(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5E);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::divss(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5E);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::addps(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x58);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::subps(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5C);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::mulps(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x59);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::divps(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5E);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::flds(const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xD9);
EmitOperand(0, src);
}
void X86_64Assembler::fsts(const Address& dst) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xD9);
EmitOperand(2, dst);
}
void X86_64Assembler::fstps(const Address& dst) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xD9);
EmitOperand(3, dst);
}
void X86_64Assembler::movapd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x28);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::movapd(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x28);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::movupd(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x10);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::movapd(const Address& dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(src, dst);
EmitUint8(0x0F);
EmitUint8(0x29);
EmitOperand(src.LowBits(), dst);
}
void X86_64Assembler::movupd(const Address& dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(src, dst);
EmitUint8(0x0F);
EmitUint8(0x11);
EmitOperand(src.LowBits(), dst);
}
void X86_64Assembler::movsd(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x10);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::movsd(const Address& dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitOptionalRex32(src, dst);
EmitUint8(0x0F);
EmitUint8(0x11);
EmitOperand(src.LowBits(), dst);
}
void X86_64Assembler::movsd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitOptionalRex32(src, dst); // Movsd is MR encoding instead of the usual RM.
EmitUint8(0x0F);
EmitUint8(0x11);
EmitXmmRegisterOperand(src.LowBits(), dst);
}
void X86_64Assembler::addsd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x58);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::addsd(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x58);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::subsd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5C);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::subsd(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5C);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::mulsd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x59);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::mulsd(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x59);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::divsd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5E);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::divsd(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5E);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::addpd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x58);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::subpd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5C);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::mulpd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x59);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::divpd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5E);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::movdqa(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x6F);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::movdqa(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x6F);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::movdqu(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x6F);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::movdqa(const Address& dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(src, dst);
EmitUint8(0x0F);
EmitUint8(0x7F);
EmitOperand(src.LowBits(), dst);
}
void X86_64Assembler::movdqu(const Address& dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(src, dst);
EmitUint8(0x0F);
EmitUint8(0x7F);
EmitOperand(src.LowBits(), dst);
}
void X86_64Assembler::paddb(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xFC);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::psubb(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xF8);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::paddw(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xFD);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::psubw(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xF9);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pmullw(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xD5);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::paddd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xFE);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::psubd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xFA);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pmulld(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x38);
EmitUint8(0x40);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::paddq(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xD4);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::psubq(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xFB);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::cvtsi2ss(XmmRegister dst, CpuRegister src) {
cvtsi2ss(dst, src, false);
}
void X86_64Assembler::cvtsi2ss(XmmRegister dst, CpuRegister src, bool is64bit) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
if (is64bit) {
// Emit a REX.W prefix if the operand size is 64 bits.
EmitRex64(dst, src);
} else {
EmitOptionalRex32(dst, src);
}
EmitUint8(0x0F);
EmitUint8(0x2A);
EmitOperand(dst.LowBits(), Operand(src));
}
void X86_64Assembler::cvtsi2ss(XmmRegister dst, const Address& src, bool is64bit) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
if (is64bit) {
// Emit a REX.W prefix if the operand size is 64 bits.
EmitRex64(dst, src);
} else {
EmitOptionalRex32(dst, src);
}
EmitUint8(0x0F);
EmitUint8(0x2A);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::cvtsi2sd(XmmRegister dst, CpuRegister src) {
cvtsi2sd(dst, src, false);
}
void X86_64Assembler::cvtsi2sd(XmmRegister dst, CpuRegister src, bool is64bit) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
if (is64bit) {
// Emit a REX.W prefix if the operand size is 64 bits.
EmitRex64(dst, src);
} else {
EmitOptionalRex32(dst, src);
}
EmitUint8(0x0F);
EmitUint8(0x2A);
EmitOperand(dst.LowBits(), Operand(src));
}
void X86_64Assembler::cvtsi2sd(XmmRegister dst, const Address& src, bool is64bit) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
if (is64bit) {
// Emit a REX.W prefix if the operand size is 64 bits.
EmitRex64(dst, src);
} else {
EmitOptionalRex32(dst, src);
}
EmitUint8(0x0F);
EmitUint8(0x2A);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::cvtss2si(CpuRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x2D);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::cvtss2sd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5A);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::cvtss2sd(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5A);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::cvtsd2si(CpuRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x2D);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::cvttss2si(CpuRegister dst, XmmRegister src) {
cvttss2si(dst, src, false);
}
void X86_64Assembler::cvttss2si(CpuRegister dst, XmmRegister src, bool is64bit) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
if (is64bit) {
// Emit a REX.W prefix if the operand size is 64 bits.
EmitRex64(dst, src);
} else {
EmitOptionalRex32(dst, src);
}
EmitUint8(0x0F);
EmitUint8(0x2C);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::cvttsd2si(CpuRegister dst, XmmRegister src) {
cvttsd2si(dst, src, false);
}
void X86_64Assembler::cvttsd2si(CpuRegister dst, XmmRegister src, bool is64bit) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
if (is64bit) {
// Emit a REX.W prefix if the operand size is 64 bits.
EmitRex64(dst, src);
} else {
EmitOptionalRex32(dst, src);
}
EmitUint8(0x0F);
EmitUint8(0x2C);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::cvtsd2ss(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5A);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::cvtsd2ss(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5A);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::cvtdq2ps(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5B);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::cvtdq2pd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xE6);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::comiss(XmmRegister a, XmmRegister b) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(a, b);
EmitUint8(0x0F);
EmitUint8(0x2F);
EmitXmmRegisterOperand(a.LowBits(), b);
}
void X86_64Assembler::comiss(XmmRegister a, const Address& b) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(a, b);
EmitUint8(0x0F);
EmitUint8(0x2F);
EmitOperand(a.LowBits(), b);
}
void X86_64Assembler::comisd(XmmRegister a, XmmRegister b) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(a, b);
EmitUint8(0x0F);
EmitUint8(0x2F);
EmitXmmRegisterOperand(a.LowBits(), b);
}
void X86_64Assembler::comisd(XmmRegister a, const Address& b) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(a, b);
EmitUint8(0x0F);
EmitUint8(0x2F);
EmitOperand(a.LowBits(), b);
}
void X86_64Assembler::ucomiss(XmmRegister a, XmmRegister b) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(a, b);
EmitUint8(0x0F);
EmitUint8(0x2E);
EmitXmmRegisterOperand(a.LowBits(), b);
}
void X86_64Assembler::ucomiss(XmmRegister a, const Address& b) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(a, b);
EmitUint8(0x0F);
EmitUint8(0x2E);
EmitOperand(a.LowBits(), b);
}
void X86_64Assembler::ucomisd(XmmRegister a, XmmRegister b) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(a, b);
EmitUint8(0x0F);
EmitUint8(0x2E);
EmitXmmRegisterOperand(a.LowBits(), b);
}
void X86_64Assembler::ucomisd(XmmRegister a, const Address& b) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(a, b);
EmitUint8(0x0F);
EmitUint8(0x2E);
EmitOperand(a.LowBits(), b);
}
void X86_64Assembler::roundsd(XmmRegister dst, XmmRegister src, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x3A);
EmitUint8(0x0B);
EmitXmmRegisterOperand(dst.LowBits(), src);
EmitUint8(imm.value());
}
void X86_64Assembler::roundss(XmmRegister dst, XmmRegister src, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x3A);
EmitUint8(0x0A);
EmitXmmRegisterOperand(dst.LowBits(), src);
EmitUint8(imm.value());
}
void X86_64Assembler::sqrtsd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x51);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::sqrtss(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x51);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::xorpd(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x57);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::xorpd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x57);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::xorps(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x57);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::xorps(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x57);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pxor(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xEF);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::andpd(XmmRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x54);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::andpd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x54);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::andps(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x54);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pand(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xDB);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::andnpd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x55);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::andnps(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x55);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pandn(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xDF);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::orpd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x56);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::orps(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x56);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::por(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xEB);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pavgb(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xE0);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pavgw(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xE3);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::psadbw(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xF6);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pmaddwd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xF5);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::phaddw(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x38);
EmitUint8(0x01);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::phaddd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x38);
EmitUint8(0x02);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::haddps(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x7C);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::haddpd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x7C);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::phsubw(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x38);
EmitUint8(0x05);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::phsubd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x38);
EmitUint8(0x06);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::hsubps(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x7D);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::hsubpd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x7D);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pminsb(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x38);
EmitUint8(0x38);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pmaxsb(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x38);
EmitUint8(0x3C);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pminsw(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xEA);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pmaxsw(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xEE);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pminsd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x38);
EmitUint8(0x39);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pmaxsd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x38);
EmitUint8(0x3D);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pminub(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xDA);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pmaxub(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xDE);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pminuw(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x38);
EmitUint8(0x3A);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pmaxuw(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x38);
EmitUint8(0x3E);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pminud(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x38);
EmitUint8(0x3B);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pmaxud(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x38);
EmitUint8(0x3F);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::minps(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5D);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::maxps(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5F);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::minpd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5D);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::maxpd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x5F);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pcmpeqb(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x74);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pcmpeqw(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x75);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pcmpeqd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x76);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pcmpeqq(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x38);
EmitUint8(0x29);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pcmpgtb(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x64);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pcmpgtw(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x65);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pcmpgtd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x66);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::pcmpgtq(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x38);
EmitUint8(0x37);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::shufpd(XmmRegister dst, XmmRegister src, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xC6);
EmitXmmRegisterOperand(dst.LowBits(), src);
EmitUint8(imm.value());
}
void X86_64Assembler::shufps(XmmRegister dst, XmmRegister src, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xC6);
EmitXmmRegisterOperand(dst.LowBits(), src);
EmitUint8(imm.value());
}
void X86_64Assembler::pshufd(XmmRegister dst, XmmRegister src, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x70);
EmitXmmRegisterOperand(dst.LowBits(), src);
EmitUint8(imm.value());
}
void X86_64Assembler::punpcklbw(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x60);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::punpcklwd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x61);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::punpckldq(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x62);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::punpcklqdq(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x6C);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::punpckhbw(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x68);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::punpckhwd(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x69);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::punpckhdq(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x6A);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::punpckhqdq(XmmRegister dst, XmmRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0x6D);
EmitXmmRegisterOperand(dst.LowBits(), src);
}
void X86_64Assembler::psllw(XmmRegister reg, const Immediate& shift_count) {
DCHECK(shift_count.is_uint8());
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex(false, false, false, false, reg.NeedsRex());
EmitUint8(0x0F);
EmitUint8(0x71);
EmitXmmRegisterOperand(6, reg);
EmitUint8(shift_count.value());
}
void X86_64Assembler::pslld(XmmRegister reg, const Immediate& shift_count) {
DCHECK(shift_count.is_uint8());
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex(false, false, false, false, reg.NeedsRex());
EmitUint8(0x0F);
EmitUint8(0x72);
EmitXmmRegisterOperand(6, reg);
EmitUint8(shift_count.value());
}
void X86_64Assembler::psllq(XmmRegister reg, const Immediate& shift_count) {
DCHECK(shift_count.is_uint8());
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex(false, false, false, false, reg.NeedsRex());
EmitUint8(0x0F);
EmitUint8(0x73);
EmitXmmRegisterOperand(6, reg);
EmitUint8(shift_count.value());
}
void X86_64Assembler::psraw(XmmRegister reg, const Immediate& shift_count) {
DCHECK(shift_count.is_uint8());
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex(false, false, false, false, reg.NeedsRex());
EmitUint8(0x0F);
EmitUint8(0x71);
EmitXmmRegisterOperand(4, reg);
EmitUint8(shift_count.value());
}
void X86_64Assembler::psrad(XmmRegister reg, const Immediate& shift_count) {
DCHECK(shift_count.is_uint8());
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex(false, false, false, false, reg.NeedsRex());
EmitUint8(0x0F);
EmitUint8(0x72);
EmitXmmRegisterOperand(4, reg);
EmitUint8(shift_count.value());
}
void X86_64Assembler::psrlw(XmmRegister reg, const Immediate& shift_count) {
DCHECK(shift_count.is_uint8());
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex(false, false, false, false, reg.NeedsRex());
EmitUint8(0x0F);
EmitUint8(0x71);
EmitXmmRegisterOperand(2, reg);
EmitUint8(shift_count.value());
}
void X86_64Assembler::psrld(XmmRegister reg, const Immediate& shift_count) {
DCHECK(shift_count.is_uint8());
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex(false, false, false, false, reg.NeedsRex());
EmitUint8(0x0F);
EmitUint8(0x72);
EmitXmmRegisterOperand(2, reg);
EmitUint8(shift_count.value());
}
void X86_64Assembler::psrlq(XmmRegister reg, const Immediate& shift_count) {
DCHECK(shift_count.is_uint8());
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex(false, false, false, false, reg.NeedsRex());
EmitUint8(0x0F);
EmitUint8(0x73);
EmitXmmRegisterOperand(2, reg);
EmitUint8(shift_count.value());
}
void X86_64Assembler::psrldq(XmmRegister reg, const Immediate& shift_count) {
DCHECK(shift_count.is_uint8());
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitOptionalRex(false, false, false, false, reg.NeedsRex());
EmitUint8(0x0F);
EmitUint8(0x73);
EmitXmmRegisterOperand(3, reg);
EmitUint8(shift_count.value());
}
void X86_64Assembler::fldl(const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xDD);
EmitOperand(0, src);
}
void X86_64Assembler::fstl(const Address& dst) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xDD);
EmitOperand(2, dst);
}
void X86_64Assembler::fstpl(const Address& dst) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xDD);
EmitOperand(3, dst);
}
void X86_64Assembler::fstsw() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x9B);
EmitUint8(0xDF);
EmitUint8(0xE0);
}
void X86_64Assembler::fnstcw(const Address& dst) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xD9);
EmitOperand(7, dst);
}
void X86_64Assembler::fldcw(const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xD9);
EmitOperand(5, src);
}
void X86_64Assembler::fistpl(const Address& dst) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xDF);
EmitOperand(7, dst);
}
void X86_64Assembler::fistps(const Address& dst) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xDB);
EmitOperand(3, dst);
}
void X86_64Assembler::fildl(const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xDF);
EmitOperand(5, src);
}
void X86_64Assembler::filds(const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xDB);
EmitOperand(0, src);
}
void X86_64Assembler::fincstp() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xD9);
EmitUint8(0xF7);
}
void X86_64Assembler::ffree(const Immediate& index) {
CHECK_LT(index.value(), 7);
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xDD);
EmitUint8(0xC0 + index.value());
}
void X86_64Assembler::fsin() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xD9);
EmitUint8(0xFE);
}
void X86_64Assembler::fcos() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xD9);
EmitUint8(0xFF);
}
void X86_64Assembler::fptan() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xD9);
EmitUint8(0xF2);
}
void X86_64Assembler::fucompp() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xDA);
EmitUint8(0xE9);
}
void X86_64Assembler::fprem() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xD9);
EmitUint8(0xF8);
}
void X86_64Assembler::xchgl(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
// There is a short version for rax.
// It's a bit awkward, as CpuRegister has a const field, so assignment and thus swapping doesn't
// work.
const bool src_rax = src.AsRegister() == RAX;
const bool dst_rax = dst.AsRegister() == RAX;
if (src_rax || dst_rax) {
EmitOptionalRex32(src_rax ? dst : src);
EmitUint8(0x90 + (src_rax ? dst.LowBits() : src.LowBits()));
return;
}
// General case.
EmitOptionalRex32(src, dst);
EmitUint8(0x87);
EmitRegisterOperand(src.LowBits(), dst.LowBits());
}
void X86_64Assembler::xchgq(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
// There is a short version for rax.
// It's a bit awkward, as CpuRegister has a const field, so assignment and thus swapping doesn't
// work.
const bool src_rax = src.AsRegister() == RAX;
const bool dst_rax = dst.AsRegister() == RAX;
if (src_rax || dst_rax) {
// If src == target, emit a nop instead.
if (src_rax && dst_rax) {
EmitUint8(0x90);
} else {
EmitRex64(src_rax ? dst : src);
EmitUint8(0x90 + (src_rax ? dst.LowBits() : src.LowBits()));
}
return;
}
// General case.
EmitRex64(src, dst);
EmitUint8(0x87);
EmitRegisterOperand(src.LowBits(), dst.LowBits());
}
void X86_64Assembler::xchgl(CpuRegister reg, const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg, address);
EmitUint8(0x87);
EmitOperand(reg.LowBits(), address);
}
void X86_64Assembler::cmpb(const Address& address, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
CHECK(imm.is_int32());
EmitOptionalRex32(address);
EmitUint8(0x80);
EmitOperand(7, address);
EmitUint8(imm.value() & 0xFF);
}
void X86_64Assembler::cmpw(const Address& address, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
CHECK(imm.is_int32());
EmitOperandSizeOverride();
EmitOptionalRex32(address);
EmitComplex(7, address, imm, /* is_16_op */ true);
}
void X86_64Assembler::cmpl(CpuRegister reg, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
CHECK(imm.is_int32());
EmitOptionalRex32(reg);
EmitComplex(7, Operand(reg), imm);
}
void X86_64Assembler::cmpl(CpuRegister reg0, CpuRegister reg1) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg0, reg1);
EmitUint8(0x3B);
EmitOperand(reg0.LowBits(), Operand(reg1));
}
void X86_64Assembler::cmpl(CpuRegister reg, const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg, address);
EmitUint8(0x3B);
EmitOperand(reg.LowBits(), address);
}
void X86_64Assembler::cmpl(const Address& address, CpuRegister reg) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg, address);
EmitUint8(0x39);
EmitOperand(reg.LowBits(), address);
}
void X86_64Assembler::cmpl(const Address& address, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
CHECK(imm.is_int32());
EmitOptionalRex32(address);
EmitComplex(7, address, imm);
}
void X86_64Assembler::cmpq(CpuRegister reg0, CpuRegister reg1) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(reg0, reg1);
EmitUint8(0x3B);
EmitOperand(reg0.LowBits(), Operand(reg1));
}
void X86_64Assembler::cmpq(CpuRegister reg, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
CHECK(imm.is_int32()); // cmpq only supports 32b immediate.
EmitRex64(reg);
EmitComplex(7, Operand(reg), imm);
}
void X86_64Assembler::cmpq(CpuRegister reg, const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(reg, address);
EmitUint8(0x3B);
EmitOperand(reg.LowBits(), address);
}
void X86_64Assembler::cmpq(const Address& address, const Immediate& imm) {
CHECK(imm.is_int32()); // cmpq only supports 32b immediate.
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(address);
EmitComplex(7, address, imm);
}
void X86_64Assembler::addl(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x03);
EmitRegisterOperand(dst.LowBits(), src.LowBits());
}
void X86_64Assembler::addl(CpuRegister reg, const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg, address);
EmitUint8(0x03);
EmitOperand(reg.LowBits(), address);
}
void X86_64Assembler::testl(CpuRegister reg1, CpuRegister reg2) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg1, reg2);
EmitUint8(0x85);
EmitRegisterOperand(reg1.LowBits(), reg2.LowBits());
}
void X86_64Assembler::testl(CpuRegister reg, const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg, address);
EmitUint8(0x85);
EmitOperand(reg.LowBits(), address);
}
void X86_64Assembler::testl(CpuRegister reg, const Immediate& immediate) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
// For registers that have a byte variant (RAX, RBX, RCX, and RDX)
// we only test the byte CpuRegister to keep the encoding short.
if (immediate.is_uint8() && reg.AsRegister() < 4) {
// Use zero-extended 8-bit immediate.
if (reg.AsRegister() == RAX) {
EmitUint8(0xA8);
} else {
EmitUint8(0xF6);
EmitUint8(0xC0 + reg.AsRegister());
}
EmitUint8(immediate.value() & 0xFF);
} else if (reg.AsRegister() == RAX) {
// Use short form if the destination is RAX.
EmitUint8(0xA9);
EmitImmediate(immediate);
} else {
EmitOptionalRex32(reg);
EmitUint8(0xF7);
EmitOperand(0, Operand(reg));
EmitImmediate(immediate);
}
}
void X86_64Assembler::testq(CpuRegister reg1, CpuRegister reg2) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(reg1, reg2);
EmitUint8(0x85);
EmitRegisterOperand(reg1.LowBits(), reg2.LowBits());
}
void X86_64Assembler::testq(CpuRegister reg, const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(reg, address);
EmitUint8(0x85);
EmitOperand(reg.LowBits(), address);
}
void X86_64Assembler::testb(const Address& dst, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst);
EmitUint8(0xF6);
EmitOperand(Register::RAX, dst);
CHECK(imm.is_int8());
EmitUint8(imm.value() & 0xFF);
}
void X86_64Assembler::testl(const Address& dst, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst);
EmitUint8(0xF7);
EmitOperand(0, dst);
EmitImmediate(imm);
}
void X86_64Assembler::andl(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x23);
EmitOperand(dst.LowBits(), Operand(src));
}
void X86_64Assembler::andl(CpuRegister reg, const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg, address);
EmitUint8(0x23);
EmitOperand(reg.LowBits(), address);
}
void X86_64Assembler::andl(CpuRegister dst, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst);
EmitComplex(4, Operand(dst), imm);
}
void X86_64Assembler::andq(CpuRegister reg, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
CHECK(imm.is_int32()); // andq only supports 32b immediate.
EmitRex64(reg);
EmitComplex(4, Operand(reg), imm);
}
void X86_64Assembler::andq(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst, src);
EmitUint8(0x23);
EmitOperand(dst.LowBits(), Operand(src));
}
void X86_64Assembler::andq(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst, src);
EmitUint8(0x23);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::orl(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0B);
EmitOperand(dst.LowBits(), Operand(src));
}
void X86_64Assembler::orl(CpuRegister reg, const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg, address);
EmitUint8(0x0B);
EmitOperand(reg.LowBits(), address);
}
void X86_64Assembler::orl(CpuRegister dst, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst);
EmitComplex(1, Operand(dst), imm);
}
void X86_64Assembler::orq(CpuRegister dst, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
CHECK(imm.is_int32()); // orq only supports 32b immediate.
EmitRex64(dst);
EmitComplex(1, Operand(dst), imm);
}
void X86_64Assembler::orq(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst, src);
EmitUint8(0x0B);
EmitOperand(dst.LowBits(), Operand(src));
}
void X86_64Assembler::orq(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst, src);
EmitUint8(0x0B);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::xorl(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x33);
EmitOperand(dst.LowBits(), Operand(src));
}
void X86_64Assembler::xorl(CpuRegister reg, const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg, address);
EmitUint8(0x33);
EmitOperand(reg.LowBits(), address);
}
void X86_64Assembler::xorl(CpuRegister dst, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst);
EmitComplex(6, Operand(dst), imm);
}
void X86_64Assembler::xorq(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst, src);
EmitUint8(0x33);
EmitOperand(dst.LowBits(), Operand(src));
}
void X86_64Assembler::xorq(CpuRegister dst, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
CHECK(imm.is_int32()); // xorq only supports 32b immediate.
EmitRex64(dst);
EmitComplex(6, Operand(dst), imm);
}
void X86_64Assembler::xorq(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst, src);
EmitUint8(0x33);
EmitOperand(dst.LowBits(), src);
}
#if 0
void X86_64Assembler::rex(bool force, bool w, Register* r, Register* x, Register* b) {
// REX.WRXB
// W - 64-bit operand
// R - MODRM.reg
// X - SIB.index
// B - MODRM.rm/SIB.base
uint8_t rex = force ? 0x40 : 0;
if (w) {
rex |= 0x48; // REX.W000
}
if (r != nullptr && *r >= Register::R8 && *r < Register::kNumberOfCpuRegisters) {
rex |= 0x44; // REX.0R00
*r = static_cast<Register>(*r - 8);
}
if (x != nullptr && *x >= Register::R8 && *x < Register::kNumberOfCpuRegisters) {
rex |= 0x42; // REX.00X0
*x = static_cast<Register>(*x - 8);
}
if (b != nullptr && *b >= Register::R8 && *b < Register::kNumberOfCpuRegisters) {
rex |= 0x41; // REX.000B
*b = static_cast<Register>(*b - 8);
}
if (rex != 0) {
EmitUint8(rex);
}
}
void X86_64Assembler::rex_reg_mem(bool force, bool w, Register* dst, const Address& mem) {
// REX.WRXB
// W - 64-bit operand
// R - MODRM.reg
// X - SIB.index
// B - MODRM.rm/SIB.base
uint8_t rex = mem->rex();
if (force) {
rex |= 0x40; // REX.0000
}
if (w) {
rex |= 0x48; // REX.W000
}
if (dst != nullptr && *dst >= Register::R8 && *dst < Register::kNumberOfCpuRegisters) {
rex |= 0x44; // REX.0R00
*dst = static_cast<Register>(*dst - 8);
}
if (rex != 0) {
EmitUint8(rex);
}
}
void rex_mem_reg(bool force, bool w, Address* mem, Register* src);
#endif
void X86_64Assembler::addl(CpuRegister reg, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg);
EmitComplex(0, Operand(reg), imm);
}
void X86_64Assembler::addq(CpuRegister reg, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
CHECK(imm.is_int32()); // addq only supports 32b immediate.
EmitRex64(reg);
EmitComplex(0, Operand(reg), imm);
}
void X86_64Assembler::addq(CpuRegister dst, const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst, address);
EmitUint8(0x03);
EmitOperand(dst.LowBits(), address);
}
void X86_64Assembler::addq(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
// 0x01 is addq r/m64 <- r/m64 + r64, with op1 in r/m and op2 in reg: so reverse EmitRex64
EmitRex64(src, dst);
EmitUint8(0x01);
EmitRegisterOperand(src.LowBits(), dst.LowBits());
}
void X86_64Assembler::addl(const Address& address, CpuRegister reg) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg, address);
EmitUint8(0x01);
EmitOperand(reg.LowBits(), address);
}
void X86_64Assembler::addl(const Address& address, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(address);
EmitComplex(0, address, imm);
}
void X86_64Assembler::addw(const Address& address, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
CHECK(imm.is_uint16() || imm.is_int16()) << imm.value();
EmitUint8(0x66);
EmitOptionalRex32(address);
EmitComplex(0, address, imm, /* is_16_op */ true);
}
void X86_64Assembler::subl(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x2B);
EmitOperand(dst.LowBits(), Operand(src));
}
void X86_64Assembler::subl(CpuRegister reg, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg);
EmitComplex(5, Operand(reg), imm);
}
void X86_64Assembler::subq(CpuRegister reg, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
CHECK(imm.is_int32()); // subq only supports 32b immediate.
EmitRex64(reg);
EmitComplex(5, Operand(reg), imm);
}
void X86_64Assembler::subq(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst, src);
EmitUint8(0x2B);
EmitRegisterOperand(dst.LowBits(), src.LowBits());
}
void X86_64Assembler::subq(CpuRegister reg, const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(reg, address);
EmitUint8(0x2B);
EmitOperand(reg.LowBits() & 7, address);
}
void X86_64Assembler::subl(CpuRegister reg, const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg, address);
EmitUint8(0x2B);
EmitOperand(reg.LowBits(), address);
}
void X86_64Assembler::cdq() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x99);
}
void X86_64Assembler::cqo() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64();
EmitUint8(0x99);
}
void X86_64Assembler::idivl(CpuRegister reg) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg);
EmitUint8(0xF7);
EmitUint8(0xF8 | reg.LowBits());
}
void X86_64Assembler::idivq(CpuRegister reg) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(reg);
EmitUint8(0xF7);
EmitUint8(0xF8 | reg.LowBits());
}
void X86_64Assembler::imull(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xAF);
EmitOperand(dst.LowBits(), Operand(src));
}
void X86_64Assembler::imull(CpuRegister dst, CpuRegister src, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
CHECK(imm.is_int32()); // imull only supports 32b immediate.
EmitOptionalRex32(dst, src);
// See whether imm can be represented as a sign-extended 8bit value.
int32_t v32 = static_cast<int32_t>(imm.value());
if (IsInt<8>(v32)) {
// Sign-extension works.
EmitUint8(0x6B);
EmitOperand(dst.LowBits(), Operand(src));
EmitUint8(static_cast<uint8_t>(v32 & 0xFF));
} else {
// Not representable, use full immediate.
EmitUint8(0x69);
EmitOperand(dst.LowBits(), Operand(src));
EmitImmediate(imm);
}
}
void X86_64Assembler::imull(CpuRegister reg, const Immediate& imm) {
imull(reg, reg, imm);
}
void X86_64Assembler::imull(CpuRegister reg, const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg, address);
EmitUint8(0x0F);
EmitUint8(0xAF);
EmitOperand(reg.LowBits(), address);
}
void X86_64Assembler::imulq(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst, src);
EmitUint8(0x0F);
EmitUint8(0xAF);
EmitRegisterOperand(dst.LowBits(), src.LowBits());
}
void X86_64Assembler::imulq(CpuRegister reg, const Immediate& imm) {
imulq(reg, reg, imm);
}
void X86_64Assembler::imulq(CpuRegister dst, CpuRegister reg, const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
CHECK(imm.is_int32()); // imulq only supports 32b immediate.
EmitRex64(dst, reg);
// See whether imm can be represented as a sign-extended 8bit value.
int64_t v64 = imm.value();
if (IsInt<8>(v64)) {
// Sign-extension works.
EmitUint8(0x6B);
EmitOperand(dst.LowBits(), Operand(reg));
EmitUint8(static_cast<uint8_t>(v64 & 0xFF));
} else {
// Not representable, use full immediate.
EmitUint8(0x69);
EmitOperand(dst.LowBits(), Operand(reg));
EmitImmediate(imm);
}
}
void X86_64Assembler::imulq(CpuRegister reg, const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(reg, address);
EmitUint8(0x0F);
EmitUint8(0xAF);
EmitOperand(reg.LowBits(), address);
}
void X86_64Assembler::imull(CpuRegister reg) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg);
EmitUint8(0xF7);
EmitOperand(5, Operand(reg));
}
void X86_64Assembler::imulq(CpuRegister reg) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(reg);
EmitUint8(0xF7);
EmitOperand(5, Operand(reg));
}
void X86_64Assembler::imull(const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(address);
EmitUint8(0xF7);
EmitOperand(5, address);
}
void X86_64Assembler::mull(CpuRegister reg) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg);
EmitUint8(0xF7);
EmitOperand(4, Operand(reg));
}
void X86_64Assembler::mull(const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(address);
EmitUint8(0xF7);
EmitOperand(4, address);
}
void X86_64Assembler::shll(CpuRegister reg, const Immediate& imm) {
EmitGenericShift(false, 4, reg, imm);
}
void X86_64Assembler::shlq(CpuRegister reg, const Immediate& imm) {
EmitGenericShift(true, 4, reg, imm);
}
void X86_64Assembler::shll(CpuRegister operand, CpuRegister shifter) {
EmitGenericShift(false, 4, operand, shifter);
}
void X86_64Assembler::shlq(CpuRegister operand, CpuRegister shifter) {
EmitGenericShift(true, 4, operand, shifter);
}
void X86_64Assembler::shrl(CpuRegister reg, const Immediate& imm) {
EmitGenericShift(false, 5, reg, imm);
}
void X86_64Assembler::shrq(CpuRegister reg, const Immediate& imm) {
EmitGenericShift(true, 5, reg, imm);
}
void X86_64Assembler::shrl(CpuRegister operand, CpuRegister shifter) {
EmitGenericShift(false, 5, operand, shifter);
}
void X86_64Assembler::shrq(CpuRegister operand, CpuRegister shifter) {
EmitGenericShift(true, 5, operand, shifter);
}
void X86_64Assembler::sarl(CpuRegister reg, const Immediate& imm) {
EmitGenericShift(false, 7, reg, imm);
}
void X86_64Assembler::sarl(CpuRegister operand, CpuRegister shifter) {
EmitGenericShift(false, 7, operand, shifter);
}
void X86_64Assembler::sarq(CpuRegister reg, const Immediate& imm) {
EmitGenericShift(true, 7, reg, imm);
}
void X86_64Assembler::sarq(CpuRegister operand, CpuRegister shifter) {
EmitGenericShift(true, 7, operand, shifter);
}
void X86_64Assembler::roll(CpuRegister reg, const Immediate& imm) {
EmitGenericShift(false, 0, reg, imm);
}
void X86_64Assembler::roll(CpuRegister operand, CpuRegister shifter) {
EmitGenericShift(false, 0, operand, shifter);
}
void X86_64Assembler::rorl(CpuRegister reg, const Immediate& imm) {
EmitGenericShift(false, 1, reg, imm);
}
void X86_64Assembler::rorl(CpuRegister operand, CpuRegister shifter) {
EmitGenericShift(false, 1, operand, shifter);
}
void X86_64Assembler::rolq(CpuRegister reg, const Immediate& imm) {
EmitGenericShift(true, 0, reg, imm);
}
void X86_64Assembler::rolq(CpuRegister operand, CpuRegister shifter) {
EmitGenericShift(true, 0, operand, shifter);
}
void X86_64Assembler::rorq(CpuRegister reg, const Immediate& imm) {
EmitGenericShift(true, 1, reg, imm);
}
void X86_64Assembler::rorq(CpuRegister operand, CpuRegister shifter) {
EmitGenericShift(true, 1, operand, shifter);
}
void X86_64Assembler::negl(CpuRegister reg) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg);
EmitUint8(0xF7);
EmitOperand(3, Operand(reg));
}
void X86_64Assembler::negq(CpuRegister reg) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(reg);
EmitUint8(0xF7);
EmitOperand(3, Operand(reg));
}
void X86_64Assembler::notl(CpuRegister reg) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg);
EmitUint8(0xF7);
EmitUint8(0xD0 | reg.LowBits());
}
void X86_64Assembler::notq(CpuRegister reg) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(reg);
EmitUint8(0xF7);
EmitOperand(2, Operand(reg));
}
void X86_64Assembler::enter(const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xC8);
CHECK(imm.is_uint16()) << imm.value();
EmitUint8(imm.value() & 0xFF);
EmitUint8((imm.value() >> 8) & 0xFF);
EmitUint8(0x00);
}
void X86_64Assembler::leave() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xC9);
}
void X86_64Assembler::ret() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xC3);
}
void X86_64Assembler::ret(const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xC2);
CHECK(imm.is_uint16());
EmitUint8(imm.value() & 0xFF);
EmitUint8((imm.value() >> 8) & 0xFF);
}
void X86_64Assembler::nop() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x90);
}
void X86_64Assembler::int3() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xCC);
}
void X86_64Assembler::hlt() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF4);
}
void X86_64Assembler::j(Condition condition, Label* label) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
if (label->IsBound()) {
static const int kShortSize = 2;
static const int kLongSize = 6;
int offset = label->Position() - buffer_.Size();
CHECK_LE(offset, 0);
if (IsInt<8>(offset - kShortSize)) {
EmitUint8(0x70 + condition);
EmitUint8((offset - kShortSize) & 0xFF);
} else {
EmitUint8(0x0F);
EmitUint8(0x80 + condition);
EmitInt32(offset - kLongSize);
}
} else {
EmitUint8(0x0F);
EmitUint8(0x80 + condition);
EmitLabelLink(label);
}
}
void X86_64Assembler::j(Condition condition, NearLabel* label) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
if (label->IsBound()) {
static const int kShortSize = 2;
int offset = label->Position() - buffer_.Size();
CHECK_LE(offset, 0);
CHECK(IsInt<8>(offset - kShortSize));
EmitUint8(0x70 + condition);
EmitUint8((offset - kShortSize) & 0xFF);
} else {
EmitUint8(0x70 + condition);
EmitLabelLink(label);
}
}
void X86_64Assembler::jrcxz(NearLabel* label) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
if (label->IsBound()) {
static const int kShortSize = 2;
int offset = label->Position() - buffer_.Size();
CHECK_LE(offset, 0);
CHECK(IsInt<8>(offset - kShortSize));
EmitUint8(0xE3);
EmitUint8((offset - kShortSize) & 0xFF);
} else {
EmitUint8(0xE3);
EmitLabelLink(label);
}
}
void X86_64Assembler::jmp(CpuRegister reg) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg);
EmitUint8(0xFF);
EmitRegisterOperand(4, reg.LowBits());
}
void X86_64Assembler::jmp(const Address& address) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(address);
EmitUint8(0xFF);
EmitOperand(4, address);
}
void X86_64Assembler::jmp(Label* label) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
if (label->IsBound()) {
static const int kShortSize = 2;
static const int kLongSize = 5;
int offset = label->Position() - buffer_.Size();
CHECK_LE(offset, 0);
if (IsInt<8>(offset - kShortSize)) {
EmitUint8(0xEB);
EmitUint8((offset - kShortSize) & 0xFF);
} else {
EmitUint8(0xE9);
EmitInt32(offset - kLongSize);
}
} else {
EmitUint8(0xE9);
EmitLabelLink(label);
}
}
void X86_64Assembler::jmp(NearLabel* label) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
if (label->IsBound()) {
static const int kShortSize = 2;
int offset = label->Position() - buffer_.Size();
CHECK_LE(offset, 0);
CHECK(IsInt<8>(offset - kShortSize));
EmitUint8(0xEB);
EmitUint8((offset - kShortSize) & 0xFF);
} else {
EmitUint8(0xEB);
EmitLabelLink(label);
}
}
void X86_64Assembler::rep_movsw() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitUint8(0xF3);
EmitUint8(0xA5);
}
X86_64Assembler* X86_64Assembler::lock() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF0);
return this;
}
void X86_64Assembler::cmpxchgl(const Address& address, CpuRegister reg) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(reg, address);
EmitUint8(0x0F);
EmitUint8(0xB1);
EmitOperand(reg.LowBits(), address);
}
void X86_64Assembler::cmpxchgq(const Address& address, CpuRegister reg) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(reg, address);
EmitUint8(0x0F);
EmitUint8(0xB1);
EmitOperand(reg.LowBits(), address);
}
void X86_64Assembler::mfence() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x0F);
EmitUint8(0xAE);
EmitUint8(0xF0);
}
X86_64Assembler* X86_64Assembler::gs() {
// TODO: gs is a prefix and not an instruction
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x65);
return this;
}
void X86_64Assembler::AddImmediate(CpuRegister reg, const Immediate& imm) {
int value = imm.value();
if (value != 0) {
if (value > 0) {
addl(reg, imm);
} else {
subl(reg, Immediate(value));
}
}
}
void X86_64Assembler::setcc(Condition condition, CpuRegister dst) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
// RSP, RBP, RDI, RSI need rex prefix (else the pattern encodes ah/bh/ch/dh).
if (dst.NeedsRex() || dst.AsRegister() > 3) {
EmitOptionalRex(true, false, false, false, dst.NeedsRex());
}
EmitUint8(0x0F);
EmitUint8(0x90 + condition);
EmitUint8(0xC0 + dst.LowBits());
}
void X86_64Assembler::bswapl(CpuRegister dst) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex(false, false, false, false, dst.NeedsRex());
EmitUint8(0x0F);
EmitUint8(0xC8 + dst.LowBits());
}
void X86_64Assembler::bswapq(CpuRegister dst) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex(false, true, false, false, dst.NeedsRex());
EmitUint8(0x0F);
EmitUint8(0xC8 + dst.LowBits());
}
void X86_64Assembler::bsfl(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xBC);
EmitRegisterOperand(dst.LowBits(), src.LowBits());
}
void X86_64Assembler::bsfl(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xBC);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::bsfq(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst, src);
EmitUint8(0x0F);
EmitUint8(0xBC);
EmitRegisterOperand(dst.LowBits(), src.LowBits());
}
void X86_64Assembler::bsfq(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst, src);
EmitUint8(0x0F);
EmitUint8(0xBC);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::bsrl(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xBD);
EmitRegisterOperand(dst.LowBits(), src.LowBits());
}
void X86_64Assembler::bsrl(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xBD);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::bsrq(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst, src);
EmitUint8(0x0F);
EmitUint8(0xBD);
EmitRegisterOperand(dst.LowBits(), src.LowBits());
}
void X86_64Assembler::bsrq(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitRex64(dst, src);
EmitUint8(0x0F);
EmitUint8(0xBD);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::popcntl(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xB8);
EmitRegisterOperand(dst.LowBits(), src.LowBits());
}
void X86_64Assembler::popcntl(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitOptionalRex32(dst, src);
EmitUint8(0x0F);
EmitUint8(0xB8);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::popcntq(CpuRegister dst, CpuRegister src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitRex64(dst, src);
EmitUint8(0x0F);
EmitUint8(0xB8);
EmitRegisterOperand(dst.LowBits(), src.LowBits());
}
void X86_64Assembler::popcntq(CpuRegister dst, const Address& src) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitRex64(dst, src);
EmitUint8(0x0F);
EmitUint8(0xB8);
EmitOperand(dst.LowBits(), src);
}
void X86_64Assembler::repne_scasb() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF2);
EmitUint8(0xAE);
}
void X86_64Assembler::repne_scasw() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitUint8(0xF2);
EmitUint8(0xAF);
}
void X86_64Assembler::repe_cmpsw() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0x66);
EmitUint8(0xF3);
EmitUint8(0xA7);
}
void X86_64Assembler::repe_cmpsl() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitUint8(0xA7);
}
void X86_64Assembler::repe_cmpsq() {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitUint8(0xF3);
EmitRex64();
EmitUint8(0xA7);
}
void X86_64Assembler::LoadDoubleConstant(XmmRegister dst, double value) {
// TODO: Need to have a code constants table.
int64_t constant = bit_cast<int64_t, double>(value);
pushq(Immediate(High32Bits(constant)));
pushq(Immediate(Low32Bits(constant)));
movsd(dst, Address(CpuRegister(RSP), 0));
addq(CpuRegister(RSP), Immediate(2 * sizeof(intptr_t)));
}
void X86_64Assembler::Align(int alignment, int offset) {
CHECK(IsPowerOfTwo(alignment));
// Emit nop instruction until the real position is aligned.
while (((offset + buffer_.GetPosition()) & (alignment-1)) != 0) {
nop();
}
}
void X86_64Assembler::Bind(Label* label) {
int bound = buffer_.Size();
CHECK(!label->IsBound()); // Labels can only be bound once.
while (label->IsLinked()) {
int position = label->LinkPosition();
int next = buffer_.Load<int32_t>(position);
buffer_.Store<int32_t>(position, bound - (position + 4));
label->position_ = next;
}
label->BindTo(bound);
}
void X86_64Assembler::Bind(NearLabel* label) {
int bound = buffer_.Size();
CHECK(!label->IsBound()); // Labels can only be bound once.
while (label->IsLinked()) {
int position = label->LinkPosition();
uint8_t delta = buffer_.Load<uint8_t>(position);
int offset = bound - (position + 1);
CHECK(IsInt<8>(offset));
buffer_.Store<int8_t>(position, offset);
label->position_ = delta != 0u ? label->position_ - delta : 0;
}
label->BindTo(bound);
}
void X86_64Assembler::EmitOperand(uint8_t reg_or_opcode, const Operand& operand) {
CHECK_GE(reg_or_opcode, 0);
CHECK_LT(reg_or_opcode, 8);
const int length = operand.length_;
CHECK_GT(length, 0);
// Emit the ModRM byte updated with the given reg value.
CHECK_EQ(operand.encoding_[0] & 0x38, 0);
EmitUint8(operand.encoding_[0] + (reg_or_opcode << 3));
// Emit the rest of the encoded operand.
for (int i = 1; i < length; i++) {
EmitUint8(operand.encoding_[i]);
}
AssemblerFixup* fixup = operand.GetFixup();
if (fixup != nullptr) {
EmitFixup(fixup);
}
}
void X86_64Assembler::EmitImmediate(const Immediate& imm, bool is_16_op) {
if (is_16_op) {
EmitUint8(imm.value() & 0xFF);
EmitUint8(imm.value() >> 8);
} else if (imm.is_int32()) {
EmitInt32(static_cast<int32_t>(imm.value()));
} else {
EmitInt64(imm.value());
}
}
void X86_64Assembler::EmitComplex(uint8_t reg_or_opcode,
const Operand& operand,
const Immediate& immediate,
bool is_16_op) {
CHECK_GE(reg_or_opcode, 0);
CHECK_LT(reg_or_opcode, 8);
if (immediate.is_int8()) {
// Use sign-extended 8-bit immediate.
EmitUint8(0x83);
EmitOperand(reg_or_opcode, operand);
EmitUint8(immediate.value() & 0xFF);
} else if (operand.IsRegister(CpuRegister(RAX))) {
// Use short form if the destination is eax.
EmitUint8(0x05 + (reg_or_opcode << 3));
EmitImmediate(immediate, is_16_op);
} else {
EmitUint8(0x81);
EmitOperand(reg_or_opcode, operand);
EmitImmediate(immediate, is_16_op);
}
}
void X86_64Assembler::EmitLabel(Label* label, int instruction_size) {
if (label->IsBound()) {
int offset = label->Position() - buffer_.Size();
CHECK_LE(offset, 0);
EmitInt32(offset - instruction_size);
} else {
EmitLabelLink(label);
}
}
void X86_64Assembler::EmitLabelLink(Label* label) {
CHECK(!label->IsBound());
int position = buffer_.Size();
EmitInt32(label->position_);
label->LinkTo(position);
}
void X86_64Assembler::EmitLabelLink(NearLabel* label) {
CHECK(!label->IsBound());
int position = buffer_.Size();
if (label->IsLinked()) {
// Save the delta in the byte that we have to play with.
uint32_t delta = position - label->LinkPosition();
CHECK(IsUint<8>(delta));
EmitUint8(delta & 0xFF);
} else {
EmitUint8(0);
}
label->LinkTo(position);
}
void X86_64Assembler::EmitGenericShift(bool wide,
int reg_or_opcode,
CpuRegister reg,
const Immediate& imm) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
CHECK(imm.is_int8());
if (wide) {
EmitRex64(reg);
} else {
EmitOptionalRex32(reg);
}
if (imm.value() == 1) {
EmitUint8(0xD1);
EmitOperand(reg_or_opcode, Operand(reg));
} else {
EmitUint8(0xC1);
EmitOperand(reg_or_opcode, Operand(reg));
EmitUint8(imm.value() & 0xFF);
}
}
void X86_64Assembler::EmitGenericShift(bool wide,
int reg_or_opcode,
CpuRegister operand,
CpuRegister shifter) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
CHECK_EQ(shifter.AsRegister(), RCX);
if (wide) {
EmitRex64(operand);
} else {
EmitOptionalRex32(operand);
}
EmitUint8(0xD3);
EmitOperand(reg_or_opcode, Operand(operand));
}
void X86_64Assembler::EmitOptionalRex(bool force, bool w, bool r, bool x, bool b) {
// REX.WRXB
// W - 64-bit operand
// R - MODRM.reg
// X - SIB.index
// B - MODRM.rm/SIB.base
uint8_t rex = force ? 0x40 : 0;
if (w) {
rex |= 0x48; // REX.W000
}
if (r) {
rex |= 0x44; // REX.0R00
}
if (x) {
rex |= 0x42; // REX.00X0
}
if (b) {
rex |= 0x41; // REX.000B
}
if (rex != 0) {
EmitUint8(rex);
}
}
void X86_64Assembler::EmitOptionalRex32(CpuRegister reg) {
EmitOptionalRex(false, false, false, false, reg.NeedsRex());
}
void X86_64Assembler::EmitOptionalRex32(CpuRegister dst, CpuRegister src) {
EmitOptionalRex(false, false, dst.NeedsRex(), false, src.NeedsRex());
}
void X86_64Assembler::EmitOptionalRex32(XmmRegister dst, XmmRegister src) {
EmitOptionalRex(false, false, dst.NeedsRex(), false, src.NeedsRex());
}
void X86_64Assembler::EmitOptionalRex32(CpuRegister dst, XmmRegister src) {
EmitOptionalRex(false, false, dst.NeedsRex(), false, src.NeedsRex());
}
void X86_64Assembler::EmitOptionalRex32(XmmRegister dst, CpuRegister src) {
EmitOptionalRex(false, false, dst.NeedsRex(), false, src.NeedsRex());
}
void X86_64Assembler::EmitOptionalRex32(const Operand& operand) {
uint8_t rex = operand.rex();
if (rex != 0) {
EmitUint8(rex);
}
}
void X86_64Assembler::EmitOptionalRex32(CpuRegister dst, const Operand& operand) {
uint8_t rex = operand.rex();
if (dst.NeedsRex()) {
rex |= 0x44; // REX.0R00
}
if (rex != 0) {
EmitUint8(rex);
}
}
void X86_64Assembler::EmitOptionalRex32(XmmRegister dst, const Operand& operand) {
uint8_t rex = operand.rex();
if (dst.NeedsRex()) {
rex |= 0x44; // REX.0R00
}
if (rex != 0) {
EmitUint8(rex);
}
}
void X86_64Assembler::EmitRex64() {
EmitOptionalRex(false, true, false, false, false);
}
void X86_64Assembler::EmitRex64(CpuRegister reg) {
EmitOptionalRex(false, true, false, false, reg.NeedsRex());
}
void X86_64Assembler::EmitRex64(const Operand& operand) {
uint8_t rex = operand.rex();
rex |= 0x48; // REX.W000
EmitUint8(rex);
}
void X86_64Assembler::EmitRex64(CpuRegister dst, CpuRegister src) {
EmitOptionalRex(false, true, dst.NeedsRex(), false, src.NeedsRex());
}
void X86_64Assembler::EmitRex64(XmmRegister dst, CpuRegister src) {
EmitOptionalRex(false, true, dst.NeedsRex(), false, src.NeedsRex());
}
void X86_64Assembler::EmitRex64(CpuRegister dst, XmmRegister src) {
EmitOptionalRex(false, true, dst.NeedsRex(), false, src.NeedsRex());
}
void X86_64Assembler::EmitRex64(CpuRegister dst, const Operand& operand) {
uint8_t rex = 0x48 | operand.rex(); // REX.W000
if (dst.NeedsRex()) {
rex |= 0x44; // REX.0R00
}
EmitUint8(rex);
}
void X86_64Assembler::EmitRex64(XmmRegister dst, const Operand& operand) {
uint8_t rex = 0x48 | operand.rex(); // REX.W000
if (dst.NeedsRex()) {
rex |= 0x44; // REX.0R00
}
EmitUint8(rex);
}
void X86_64Assembler::EmitOptionalByteRegNormalizingRex32(CpuRegister dst, CpuRegister src) {
// For src, SPL, BPL, SIL, DIL need the rex prefix.
bool force = src.AsRegister() > 3;
EmitOptionalRex(force, false, dst.NeedsRex(), false, src.NeedsRex());
}
void X86_64Assembler::EmitOptionalByteRegNormalizingRex32(CpuRegister dst, const Operand& operand) {
uint8_t rex = operand.rex();
// For dst, SPL, BPL, SIL, DIL need the rex prefix.
bool force = dst.AsRegister() > 3;
if (force) {
rex |= 0x40; // REX.0000
}
if (dst.NeedsRex()) {
rex |= 0x44; // REX.0R00
}
if (rex != 0) {
EmitUint8(rex);
}
}
void X86_64Assembler::AddConstantArea() {
ArrayRef<const int32_t> area = constant_area_.GetBuffer();
for (size_t i = 0, e = area.size(); i < e; i++) {
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
EmitInt32(area[i]);
}
}
size_t ConstantArea::AppendInt32(int32_t v) {
size_t result = buffer_.size() * elem_size_;
buffer_.push_back(v);
return result;
}
size_t ConstantArea::AddInt32(int32_t v) {
// Look for an existing match.
for (size_t i = 0, e = buffer_.size(); i < e; i++) {
if (v == buffer_[i]) {
return i * elem_size_;
}
}
// Didn't match anything.
return AppendInt32(v);
}
size_t ConstantArea::AddInt64(int64_t v) {
int32_t v_low = v;
int32_t v_high = v >> 32;
if (buffer_.size() > 1) {
// Ensure we don't pass the end of the buffer.
for (size_t i = 0, e = buffer_.size() - 1; i < e; i++) {
if (v_low == buffer_[i] && v_high == buffer_[i + 1]) {
return i * elem_size_;
}
}
}
// Didn't match anything.
size_t result = buffer_.size() * elem_size_;
buffer_.push_back(v_low);
buffer_.push_back(v_high);
return result;
}
size_t ConstantArea::AddDouble(double v) {
// Treat the value as a 64-bit integer value.
return AddInt64(bit_cast<int64_t, double>(v));
}
size_t ConstantArea::AddFloat(float v) {
// Treat the value as a 32-bit integer value.
return AddInt32(bit_cast<int32_t, float>(v));
}
} // namespace x86_64
} // namespace art
|
#include <bits/stdc++.h>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
vector<string> split(const string &);
/*
* Complete the 'miniMaxSum' function below.
*
* The function accepts INTEGER_ARRAY arr as parameter.
*/
void miniMaxSum(vector<int> arr) {
for(int i = 0; i < 5; ++i) {
for(int j = 0; j < 4 - i; ++j) {
if(arr[j] > arr[j + 1]) {
int tmp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = tmp;
}
}
}
unsigned int min = 0;
for(int i = 0; i < 4; ++i) {
min += arr[i];
}
unsigned int max = 0;
for(int i = 1; i < 5; ++i) {
max += arr[i];
}
cout << min << ' ' << max;
}
int main()
{
string arr_temp_temp;
getline(cin, arr_temp_temp);
vector<string> arr_temp = split(rtrim(arr_temp_temp));
vector<int> arr(5);
for (int i = 0; i < 5; i++) {
int arr_item = stoi(arr_temp[i]);
arr[i] = arr_item;
}
miniMaxSum(arr);
return 0;
}
string ltrim(const string &str) {
string s(str);
s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
);
return s;
}
string rtrim(const string &str) {
string s(str);
s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
s.end()
);
return s;
}
vector<string> split(const string &str) {
vector<string> tokens;
string::size_type start = 0;
string::size_type end = 0;
while ((end = str.find(" ", start)) != string::npos) {
tokens.push_back(str.substr(start, end - start));
start = end + 1;
}
tokens.push_back(str.substr(start));
return tokens;
}
|
// -------------------------------------------------------------------------------------------------
// Copyright 2017 - NumScale SAS
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
// -------------------------------------------------------------------------------------------------
/// bench for functor logical_notor in scalar mode for std::uint64_t type with no decorator (regular call).
#include <simd_bench.hpp>
#include <boost/simd/function/logical_notor.hpp>
namespace nsb = ns::bench;
namespace bs = boost::simd;
DEFINE_BENCH_MAIN()
{
using T = std::uint64_t;
run<T>(bs::logical_notor, nsbg::rand<T>(-10, 10), nsbg::rand<T>(-10, 10));
}
|
// Copyright surrealwaffle 2018 - 2020.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <cstddef> // offsetof
#include <sentinel/types.hpp>
#include <sentinel/tags/generic.hpp>
namespace sentinel { namespace tags {
struct collision_model {
static constexpr signature tag_signature = make_signature("coll");
flags_long flags;
index_short indirect_damage_material;
struct pathfinding_sphere;
struct {
real maximum_vitality;
real system_shock;
int32 PAD0[13];
fraction friendly_damage_resistance;
int32 PAD1[10];
tag_reference<void> localized_damage_effect;
fraction area_damage_effect_threshold;
tag_reference<void> area_damage_effect;
real damaged_threshold;
tag_reference<void> damaged_effect;
tag_reference<void> depleted_effect;
real destroyed_threshold;
tag_reference<void> destroyed_effect;
} body;
static_assert(sizeof(body) == 0xC4);
struct {
real maximum_vitality;
int16 PAD0;
enum_short material_type;
int32 PAD1[6];
enum_short failure_function;
fraction failure_threshold;
fraction failing_shield_leak;
int32 PAD2[4];
real minimum_stun_damage;
real stun_time;
real recharge_time;
int32 PAD3[28];
real damaged_threshold;
tag_reference<void> damaged_effect;
tag_reference<void> depleted_effect;
tag_reference<void> recharging_effect;
} shield;
static_assert(sizeof(shield) == 0xEC);
int32 PAD0[31];
tag_block<void> materials;
tag_block<void> regions;
tag_block<void> modifiers;
int32 PAD1[4];
struct {
real_bounds box[3]; // bounds: x, y, z in that order
tag_block<pathfinding_sphere> spheres;
} pathfinding;
tag_block<void> nodes;
}; static_assert(sizeof(collision_model) == 0x298);
struct collision_model::pathfinding_sphere {
index_short node;
int32 unknown00[3];
position3d center;
real radius;
}; static_assert(sizeof(collision_model::pathfinding_sphere) == 0x20);
static_assert(offsetof(collision_model, materials) == 0x234);
static_assert(offsetof(collision_model, pathfinding) == 0x268);
} } // namespace sentinel::tags
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/zlib/google/zip_reader.h"
#include <utility>
#include "base/bind.h"
#include "base/files/file.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "third_party/zlib/google/zip_internal.h"
#if defined(USE_SYSTEM_MINIZIP)
#include <minizip/unzip.h>
#else
#include "third_party/zlib/contrib/minizip/unzip.h"
#if defined(OS_WIN)
#include "third_party/zlib/contrib/minizip/iowin32.h"
#endif // defined(OS_WIN)
#endif // defined(USE_SYSTEM_MINIZIP)
namespace zip {
namespace {
// FilePathWriterDelegate ------------------------------------------------------
// A writer delegate that writes a file at a given path.
class FilePathWriterDelegate : public WriterDelegate {
public:
explicit FilePathWriterDelegate(const base::FilePath& output_file_path);
~FilePathWriterDelegate() override;
// WriterDelegate methods:
// Creates the output file and any necessary intermediate directories.
bool PrepareOutput() override;
// Writes |num_bytes| bytes of |data| to the file, returning false if not all
// bytes could be written.
bool WriteBytes(const char* data, int num_bytes) override;
private:
base::FilePath output_file_path_;
base::File file_;
DISALLOW_COPY_AND_ASSIGN(FilePathWriterDelegate);
};
FilePathWriterDelegate::FilePathWriterDelegate(
const base::FilePath& output_file_path)
: output_file_path_(output_file_path) {
}
FilePathWriterDelegate::~FilePathWriterDelegate() {
}
bool FilePathWriterDelegate::PrepareOutput() {
// We can't rely on parent directory entries being specified in the
// zip, so we make sure they are created.
if (!base::CreateDirectory(output_file_path_.DirName()))
return false;
file_.Initialize(output_file_path_,
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
return file_.IsValid();
}
bool FilePathWriterDelegate::WriteBytes(const char* data, int num_bytes) {
return num_bytes == file_.WriteAtCurrentPos(data, num_bytes);
}
// StringWriterDelegate --------------------------------------------------------
// A writer delegate that writes no more than |max_read_bytes| to a given
// std::string.
class StringWriterDelegate : public WriterDelegate {
public:
StringWriterDelegate(size_t max_read_bytes, std::string* output);
~StringWriterDelegate() override;
// WriterDelegate methods:
// Returns true.
bool PrepareOutput() override;
// Appends |num_bytes| bytes from |data| to the output string. Returns false
// if |num_bytes| will cause the string to exceed |max_read_bytes|.
bool WriteBytes(const char* data, int num_bytes) override;
private:
size_t max_read_bytes_;
std::string* output_;
DISALLOW_COPY_AND_ASSIGN(StringWriterDelegate);
};
StringWriterDelegate::StringWriterDelegate(size_t max_read_bytes,
std::string* output)
: max_read_bytes_(max_read_bytes),
output_(output) {
}
StringWriterDelegate::~StringWriterDelegate() {
}
bool StringWriterDelegate::PrepareOutput() {
return true;
}
bool StringWriterDelegate::WriteBytes(const char* data, int num_bytes) {
if (output_->size() + num_bytes > max_read_bytes_)
return false;
output_->append(data, num_bytes);
return true;
}
} // namespace
// TODO(satorux): The implementation assumes that file names in zip files
// are encoded in UTF-8. This is true for zip files created by Zip()
// function in zip.h, but not true for user-supplied random zip files.
ZipReader::EntryInfo::EntryInfo(const std::string& file_name_in_zip,
const unz_file_info& raw_file_info)
: file_path_(base::FilePath::FromUTF8Unsafe(file_name_in_zip)),
is_directory_(false) {
original_size_ = raw_file_info.uncompressed_size;
// Directory entries in zip files end with "/".
is_directory_ = base::EndsWith(file_name_in_zip, "/",
base::CompareCase::INSENSITIVE_ASCII);
// Check the file name here for directory traversal issues.
is_unsafe_ = file_path_.ReferencesParent();
// We also consider that the file name is unsafe, if it's invalid UTF-8.
base::string16 file_name_utf16;
if (!base::UTF8ToUTF16(file_name_in_zip.data(), file_name_in_zip.size(),
&file_name_utf16)) {
is_unsafe_ = true;
}
// We also consider that the file name is unsafe, if it's absolute.
// On Windows, IsAbsolute() returns false for paths starting with "/".
if (file_path_.IsAbsolute() ||
base::StartsWith(file_name_in_zip, "/",
base::CompareCase::INSENSITIVE_ASCII))
is_unsafe_ = true;
// Construct the last modified time. The timezone info is not present in
// zip files, so we construct the time as local time.
base::Time::Exploded exploded_time = {}; // Zero-clear.
exploded_time.year = raw_file_info.tmu_date.tm_year;
// The month in zip file is 0-based, whereas ours is 1-based.
exploded_time.month = raw_file_info.tmu_date.tm_mon + 1;
exploded_time.day_of_month = raw_file_info.tmu_date.tm_mday;
exploded_time.hour = raw_file_info.tmu_date.tm_hour;
exploded_time.minute = raw_file_info.tmu_date.tm_min;
exploded_time.second = raw_file_info.tmu_date.tm_sec;
exploded_time.millisecond = 0;
if (!base::Time::FromLocalExploded(exploded_time, &last_modified_))
last_modified_ = base::Time::UnixEpoch();
}
ZipReader::ZipReader()
: weak_ptr_factory_(this) {
Reset();
}
ZipReader::~ZipReader() {
Close();
}
bool ZipReader::Open(const base::FilePath& zip_file_path) {
DCHECK(!zip_file_);
// Use of "Unsafe" function does not look good, but there is no way to do
// this safely on Linux. See file_util.h for details.
zip_file_ = internal::OpenForUnzipping(zip_file_path.AsUTF8Unsafe());
if (!zip_file_) {
return false;
}
return OpenInternal();
}
bool ZipReader::OpenFromPlatformFile(base::PlatformFile zip_fd) {
DCHECK(!zip_file_);
#if defined(OS_POSIX)
zip_file_ = internal::OpenFdForUnzipping(zip_fd);
#elif defined(OS_WIN)
zip_file_ = internal::OpenHandleForUnzipping(zip_fd);
#endif
if (!zip_file_) {
return false;
}
return OpenInternal();
}
bool ZipReader::OpenFromString(const std::string& data) {
zip_file_ = internal::PrepareMemoryForUnzipping(data);
if (!zip_file_)
return false;
return OpenInternal();
}
void ZipReader::Close() {
if (zip_file_) {
unzClose(zip_file_);
}
Reset();
}
bool ZipReader::HasMore() {
return !reached_end_;
}
bool ZipReader::AdvanceToNextEntry() {
DCHECK(zip_file_);
// Should not go further if we already reached the end.
if (reached_end_)
return false;
unz_file_pos position = {};
if (unzGetFilePos(zip_file_, &position) != UNZ_OK)
return false;
const int current_entry_index = position.num_of_file;
// If we are currently at the last entry, then the next position is the
// end of the zip file, so mark that we reached the end.
if (current_entry_index + 1 == num_entries_) {
reached_end_ = true;
} else {
DCHECK_LT(current_entry_index + 1, num_entries_);
if (unzGoToNextFile(zip_file_) != UNZ_OK) {
return false;
}
}
current_entry_info_.reset();
return true;
}
bool ZipReader::OpenCurrentEntryInZip() {
DCHECK(zip_file_);
unz_file_info raw_file_info = {};
char raw_file_name_in_zip[internal::kZipMaxPath] = {};
const int result = unzGetCurrentFileInfo(zip_file_,
&raw_file_info,
raw_file_name_in_zip,
sizeof(raw_file_name_in_zip) - 1,
NULL, // extraField.
0, // extraFieldBufferSize.
NULL, // szComment.
0); // commentBufferSize.
if (result != UNZ_OK)
return false;
if (raw_file_name_in_zip[0] == '\0')
return false;
current_entry_info_.reset(
new EntryInfo(raw_file_name_in_zip, raw_file_info));
return true;
}
bool ZipReader::LocateAndOpenEntry(const base::FilePath& path_in_zip) {
DCHECK(zip_file_);
current_entry_info_.reset();
reached_end_ = false;
const int kDefaultCaseSensivityOfOS = 0;
const int result = unzLocateFile(zip_file_,
path_in_zip.AsUTF8Unsafe().c_str(),
kDefaultCaseSensivityOfOS);
if (result != UNZ_OK)
return false;
// Then Open the entry.
return OpenCurrentEntryInZip();
}
bool ZipReader::ExtractCurrentEntry(WriterDelegate* delegate) const {
DCHECK(zip_file_);
const int open_result = unzOpenCurrentFile(zip_file_);
if (open_result != UNZ_OK)
return false;
if (!delegate->PrepareOutput())
return false;
bool success = true; // This becomes false when something bad happens.
std::unique_ptr<char[]> buf(new char[internal::kZipBufSize]);
while (true) {
const int num_bytes_read = unzReadCurrentFile(zip_file_, buf.get(),
internal::kZipBufSize);
if (num_bytes_read == 0) {
// Reached the end of the file.
break;
} else if (num_bytes_read < 0) {
// If num_bytes_read < 0, then it's a specific UNZ_* error code.
success = false;
break;
} else if (num_bytes_read > 0) {
// Some data is read.
if (!delegate->WriteBytes(buf.get(), num_bytes_read)) {
success = false;
break;
}
}
}
unzCloseCurrentFile(zip_file_);
return success;
}
bool ZipReader::ExtractCurrentEntryToFilePath(
const base::FilePath& output_file_path) const {
DCHECK(zip_file_);
// If this is a directory, just create it and return.
if (current_entry_info()->is_directory())
return base::CreateDirectory(output_file_path);
bool success = false;
{
FilePathWriterDelegate writer(output_file_path);
success = ExtractCurrentEntry(&writer);
}
if (success &&
current_entry_info()->last_modified() != base::Time::UnixEpoch()) {
base::TouchFile(output_file_path,
base::Time::Now(),
current_entry_info()->last_modified());
}
return success;
}
void ZipReader::ExtractCurrentEntryToFilePathAsync(
const base::FilePath& output_file_path,
const SuccessCallback& success_callback,
const FailureCallback& failure_callback,
const ProgressCallback& progress_callback) {
DCHECK(zip_file_);
DCHECK(current_entry_info_.get());
// If this is a directory, just create it and return.
if (current_entry_info()->is_directory()) {
if (base::CreateDirectory(output_file_path)) {
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, success_callback);
} else {
DVLOG(1) << "Unzip failed: unable to create directory.";
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, failure_callback);
}
return;
}
if (unzOpenCurrentFile(zip_file_) != UNZ_OK) {
DVLOG(1) << "Unzip failed: unable to open current zip entry.";
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, failure_callback);
return;
}
base::FilePath output_dir_path = output_file_path.DirName();
if (!base::CreateDirectory(output_dir_path)) {
DVLOG(1) << "Unzip failed: unable to create containing directory.";
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, failure_callback);
return;
}
const int flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE;
base::File output_file(output_file_path, flags);
if (!output_file.IsValid()) {
DVLOG(1) << "Unzip failed: unable to create platform file at "
<< output_file_path.value();
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, failure_callback);
return;
}
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&ZipReader::ExtractChunk, weak_ptr_factory_.GetWeakPtr(),
Passed(std::move(output_file)), success_callback,
failure_callback, progress_callback, 0 /* initial offset */));
}
bool ZipReader::ExtractCurrentEntryIntoDirectory(
const base::FilePath& output_directory_path) const {
DCHECK(current_entry_info_.get());
base::FilePath output_file_path = output_directory_path.Append(
current_entry_info()->file_path());
return ExtractCurrentEntryToFilePath(output_file_path);
}
bool ZipReader::ExtractCurrentEntryToFile(base::File* file) const {
DCHECK(zip_file_);
// If this is a directory, there's nothing to extract to the file, so return
// false.
if (current_entry_info()->is_directory())
return false;
FileWriterDelegate writer(file);
return ExtractCurrentEntry(&writer);
}
bool ZipReader::ExtractCurrentEntryToString(size_t max_read_bytes,
std::string* output) const {
DCHECK(output);
DCHECK(zip_file_);
DCHECK_NE(0U, max_read_bytes);
if (current_entry_info()->is_directory()) {
output->clear();
return true;
}
// The original_size() is the best hint for the real size, so it saves
// doing reallocations for the common case when the uncompressed size is
// correct. However, we need to assume that the uncompressed size could be
// incorrect therefore this function needs to read as much data as possible.
std::string contents;
contents.reserve(
static_cast<size_t>(std::min(static_cast<int64_t>(max_read_bytes),
current_entry_info()->original_size())));
StringWriterDelegate writer(max_read_bytes, &contents);
if (!ExtractCurrentEntry(&writer))
return false;
output->swap(contents);
return true;
}
bool ZipReader::OpenInternal() {
DCHECK(zip_file_);
unz_global_info zip_info = {}; // Zero-clear.
if (unzGetGlobalInfo(zip_file_, &zip_info) != UNZ_OK) {
return false;
}
num_entries_ = zip_info.number_entry;
if (num_entries_ < 0)
return false;
// We are already at the end if the zip file is empty.
reached_end_ = (num_entries_ == 0);
return true;
}
void ZipReader::Reset() {
zip_file_ = NULL;
num_entries_ = 0;
reached_end_ = false;
current_entry_info_.reset();
}
void ZipReader::ExtractChunk(base::File output_file,
const SuccessCallback& success_callback,
const FailureCallback& failure_callback,
const ProgressCallback& progress_callback,
const int64_t offset) {
char buffer[internal::kZipBufSize];
const int num_bytes_read = unzReadCurrentFile(zip_file_,
buffer,
internal::kZipBufSize);
if (num_bytes_read == 0) {
unzCloseCurrentFile(zip_file_);
success_callback.Run();
} else if (num_bytes_read < 0) {
DVLOG(1) << "Unzip failed: error while reading zipfile "
<< "(" << num_bytes_read << ")";
failure_callback.Run();
} else {
if (num_bytes_read != output_file.Write(offset, buffer, num_bytes_read)) {
DVLOG(1) << "Unzip failed: unable to write all bytes to target.";
failure_callback.Run();
return;
}
int64_t current_progress = offset + num_bytes_read;
progress_callback.Run(current_progress);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&ZipReader::ExtractChunk, weak_ptr_factory_.GetWeakPtr(),
Passed(std::move(output_file)), success_callback,
failure_callback, progress_callback, current_progress));
}
}
// FileWriterDelegate ----------------------------------------------------------
FileWriterDelegate::FileWriterDelegate(base::File* file)
: file_(file),
file_length_(0) {
}
FileWriterDelegate::~FileWriterDelegate() {
if (!file_->SetLength(file_length_)) {
DPLOG(ERROR) << "Failed updating length of written file";
}
}
bool FileWriterDelegate::PrepareOutput() {
return file_->Seek(base::File::FROM_BEGIN, 0) >= 0;
}
bool FileWriterDelegate::WriteBytes(const char* data, int num_bytes) {
int bytes_written = file_->WriteAtCurrentPos(data, num_bytes);
if (bytes_written > 0)
file_length_ += bytes_written;
return bytes_written == num_bytes;
}
} // namespace zip
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/codestar/model/DisassociateTeamMemberRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::CodeStar::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DisassociateTeamMemberRequest::DisassociateTeamMemberRequest() :
m_projectIdHasBeenSet(false),
m_userArnHasBeenSet(false)
{
}
Aws::String DisassociateTeamMemberRequest::SerializePayload() const
{
JsonValue payload;
if(m_projectIdHasBeenSet)
{
payload.WithString("projectId", m_projectId);
}
if(m_userArnHasBeenSet)
{
payload.WithString("userArn", m_userArn);
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection DisassociateTeamMemberRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "CodeStar_20170419.DisassociateTeamMember"));
return headers;
}
|
/***************************************************//**
* @file OBPGetSaturationExchange.cpp
* @date March 2016
* @author Ocean Optics, Inc.
*
* LICENSE:
*
* SeaBreeze Copyright (C) 2016, Ocean Optics Inc
*
* 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 "common/globals.h"
#include "vendors/OceanOptics/protocols/obp/exchanges/OBPGetSaturationExchange.h"
#include "vendors/OceanOptics/protocols/obp/constants/OBPMessageTypes.h"
#include "vendors/OceanOptics/protocols/obp/hints/OBPControlHint.h"
#include <vector>
using namespace seabreeze;
using namespace seabreeze::oceanBinaryProtocol;
using namespace std;
OBPGetSaturationExchange::OBPGetSaturationExchange() {
this->messageType = OBPMessageTypes::OBP_GET_SATURATION_LEVEL;
this->hints->push_back(new OBPControlHint());
this->payload.resize(0);
}
OBPGetSaturationExchange::~OBPGetSaturationExchange() {
}
unsigned int OBPGetSaturationExchange::querySaturationLevel(
TransferHelper *helper) throw (ProtocolException) {
unsigned int saturation;
vector<byte> *result;
result = this->queryDevice(helper);
if(NULL == result || result->size() < 4) {
if(NULL != result) {
delete result;
}
throw ProtocolException("Got a short read when querying saturation level.");
}
saturation = ( ((*result)[0] & 0x00FF)
| (((*result)[1] & 0x00FF) << 8)
| (((*result)[2] & 0x00FF) << 16)
| (((*result)[3] & 0x00FF) << 24));
delete result;
return saturation;
}
|
//
// VulkanBackend.cpp
// MNN
//
// Created by MNN on 2019/01/31.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include "backend/vulkan/backend/VulkanBackend.hpp"
#include <mutex>
#include "core/Execution.hpp"
#include "core/Macro.h"
#include <MNN/Tensor.hpp>
#include "core/TensorUtils.hpp"
#include "core/SizeComputer.hpp"
#include "backend/vulkan/component/VulkanDevice.hpp"
#include "backend/vulkan/execution/VulkanImageConverter.hpp"
#include "backend/vulkan/component/VulkanInstance.hpp"
#include "backend/vulkan/execution/VulkanBasicExecution.hpp"
//#define MNN_OPEN_TIME_TRACE
#include <MNN/AutoTime.hpp>
#ifdef MNN_USE_NEON
#include <arm_neon.h>
#endif
namespace MNN {
static std::map<OpType, VulkanBackend::Creator*>* gCreator = nullptr;
// Creator
static inline std::map<OpType, VulkanBackend::Creator*>* getCreatorMap() {
if (nullptr == gCreator) {
gCreator = new std::map<OpType, VulkanBackend::Creator*>();
}
return gCreator;
}
static void _copyBufferToTensor(const Tensor* dest, const VulkanBuffer* source) {
auto sourcePtr = source->map();
auto dataType = dest->getType();
//TODO: Support other kind of dataType
MNN_ASSERT(dataType.bits == 32);
::memcpy(dest->host<float>(), sourcePtr, dest->size());
source->unmap();
}
static int _getAlignSize(const Tensor* tensor) {
auto format = TensorUtils::getDescribe(tensor)->dimensionFormat;
auto elementSize = tensor->elementSize();
// [TODO] Find a better way
if (format == MNN_DATA_FORMAT_NCHW) {
if (tensor->dimensions() >= 2) {
elementSize = elementSize / tensor->channel() * ALIGN_UP4(tensor->channel());
}
} else if (format == MNN_DATA_FORMAT_NHWC) {
if (tensor->dimensions() >= 3) {
elementSize = elementSize / tensor->channel() * ALIGN_UP4(tensor->channel());
}
}
return elementSize;
}
static void _copyTensorToBuffer(const Tensor* source, const VulkanBuffer* dest) {
auto destPtr = dest->map();
auto dataType = source->getType();
//TODO: Support other kind of dataType
MNN_ASSERT(dataType.bits == 32);
::memcpy(destPtr, source->host<float>(), source->size());
dest->unmap();
}
VulkanTensor::VulkanTensor(const Tensor* shape, const VulkanMemoryPool& pool, bool forceBuffer, bool seperate) {
auto format = TensorUtils::getDescribe(shape)->dimensionFormat;
if (MNN_DATA_FORMAT_NC4HW4 == format && !forceBuffer) {
mImage = std::make_shared<VulkanImage>(pool, seperate,
std::vector<int>{
std::max(shape->width(), 1),
std::max(shape->height(), 1),
UP_DIV(shape->channel(), 4) * shape->batch(),
},
shape->getType());
} else {
// Compute Shader don't support uint8 / int8 / float16 / uint64, all use int32/float32
mBuffer = std::make_shared<VulkanBuffer>(pool, seperate, _getAlignSize(shape) * sizeof(float));
}
}
void VulkanTensor::release() {
if (nullptr != mBuffer.get()) {
mBuffer->release();
}
if (nullptr != mImage.get()) {
mImage->release();
}
}
uint64_t VulkanTensor::deviceId() {
if (mImage.get()) {
return reinterpret_cast<uint64_t>(mImage->view());
} else {
return reinterpret_cast<uint64_t>(mBuffer->buffer());
}
}
std::pair<float, bool> VulkanBackend::onMeasure(const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs, const MNN::Op* op) {
auto creator = getCreatorMap();
auto iter = creator->find(op->type());
if (iter == creator->end()) {
return std::make_pair(0.0f, false);
}
auto flops = SizeComputer::computeFlops(op, inputs, outputs);
const float defaultScheduleCost = 0.001f;
return std::make_pair(defaultScheduleCost + flops / 1024.0f / mFlops * 1000.0f, true);
}
VulkanBackend::VulkanBackend(const MNNVulkanContext* context, bool direct) : Backend(MNN_FORWARD_VULKAN), mDirect(direct) {
if (NULL != context) {
mInstance = std::make_shared<VulkanInstance>(context->pInstance);
mDevice = std::make_shared<VulkanDevice>(mInstance, context->pPhysicalDevice, context->pDevice,
context->iQueueFamilyIndex, context->pQueue);
} else {
mInstance = std::make_shared<VulkanInstance>();
mDevice = std::make_shared<VulkanDevice>(mInstance);
}
auto& dev = device();
mCmdPool = std::make_shared<VulkanCommandPool>(dev);
mFence = std::make_shared<VulkanFence>(dev);
if (!direct) {
mCmdBuffer.reset(mCmdPool->allocBuffer());
}
//GFlops, Test by mobilenet v1's ms
static std::map<std::string, float> gFlopsMap {
{"Mali-T860", 6.83f},
{"Mali-T880", 6.83f},
{"Mali-G51", 6.83f},
{"Mali-G52", 6.83f},
{"Mali-G71", 31.61f},
{"Mali-G72", 31.61f},
{"Mali-G76", 31.61f},
{"Adreno (TM) 505", 3.19f},
{"Adreno (TM) 506", 4.74f},
{"Adreno (TM) 512", 14.23f},
{"Adreno (TM) 530", 25.40f},
{"Adreno (TM) 540", 42.74f},
{"Adreno (TM) 615", 16.77f},
{"Adreno (TM) 616", 18.77f},
{"Adreno (TM) 618", 18.77f},
{"Adreno (TM) 630", 42.74f},
{"Adreno (TM) 640", 42.74f},
};
mFlops = 4.0f;//Default set as 4G, it will be larger than single-core cpu
std::string deviceName = dev.proty().deviceName;
//FUNC_PRINT_ALL(deviceName.c_str(), s);
if (gFlopsMap.find(deviceName)!=gFlopsMap.end()) {
mFlops = gFlopsMap[deviceName];
}
//FUNC_PRINT_ALL(mFlops, f);
if (deviceName.find("Mali") != std::string::npos) {
mGpuType = MALI;
} else if (deviceName.find("Adreno") != std::string::npos) {
mGpuType = ADRENO;
}
mMemoryPool = std::make_shared<VulkanMemoryPool>(dev);
mDynamicMemoryPool = std::make_shared<VulkanMemoryPool>(dev);
mSampler = std::make_shared<VulkanSampler>(dev, VK_FILTER_NEAREST, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER);
mPipelineFactory = std::make_shared<VulkanPipelineFactory>(dev);
}
VulkanBackend::~VulkanBackend() {
/*keep release order*/
mCmdBuffer = nullptr;
mPipelineFactory = nullptr;
mSampler = nullptr;
mStaticeBuffers.clear();
mAllBuffers.clear();
mHostBuffer = nullptr;
mCmdBuffers.clear();
mFence = nullptr;
mConverters.clear();
mDynamicMemoryPool = nullptr;
mMemoryPool = nullptr;
mCmdPool = nullptr;
mDevice = nullptr;
mInstance = nullptr;
}
void VulkanBackend::pushCommand(VkCommandBuffer buffer) const {
mCmdBuffers.emplace_back(buffer);
}
const VulkanPipeline* VulkanBackend::getPipeline(const std::string& key, const std::vector<VkDescriptorType>& types,
const std::vector<uint32_t>& localSize) const {
return mPipelineFactory->getPipeline(key, types, localSize);
}
bool VulkanBackend::_supportImageSize(const Tensor* MTensor) {
if (UP_DIV(MTensor->channel(), 4) * MTensor->batch() > device().proty().limits.maxImageDimension3D) {
return false;
}
return true;
}
void VulkanBackend::onResizeBegin() {
if (!mDirect) {
mCmdBuffer->begin(0);
}
}
void VulkanBackend::onResizeEnd() {
if (!mDirect) {
mCmdBuffer->end();
}
}
bool VulkanBackend::onAcquireBuffer(const Tensor* tensor, StorageType storageType) {
auto MTensor = const_cast<Tensor*>(tensor);
auto format = TensorUtils::getDescribe(MTensor)->dimensionFormat;
bool forceBuffer = false;
if (MNN_DATA_FORMAT_NC4HW4 == format) {
if (!_supportImageSize(MTensor)) {
// forceBuffer = true;
MNN_PRINT("Force Use Buffer because then Tensor is too Large: %d, %d, %d, %d\n", MTensor->width(),
MTensor->height(), MTensor->channel(), MTensor->batch());
forceBuffer = true;
}
}
if (Backend::STATIC == storageType) {
auto newBuffer = std::make_shared<VulkanTensor>(MTensor, getMemoryPool(), forceBuffer);
MTensor->buffer().device = newBuffer->deviceId();
mStaticeBuffers.insert(std::make_pair(MTensor->buffer().device, newBuffer));
} else {
bool seperate = storageType == Backend::DYNAMIC_SEPERATE;
auto newBuffer = std::make_shared<VulkanTensor>(MTensor, getDynamicMemoryPool(), forceBuffer, seperate);
MTensor->buffer().device = newBuffer->deviceId();
mAllBuffers.insert(std::make_pair(MTensor->buffer().device, newBuffer));
}
return true;
}
bool VulkanBackend::onReleaseBuffer(const Tensor* tensor, StorageType storageType) {
auto buffer = (tensor->deviceId());
if (Backend::DYNAMIC == storageType) {
auto iter = mAllBuffers.find(buffer);
MNN_ASSERT(iter != mAllBuffers.end());
iter->second->release();
}
if (Backend::STATIC == storageType) {
auto iter = mStaticeBuffers.find(buffer);
MNN_ASSERT(iter != mStaticeBuffers.end());
mStaticeBuffers.erase(iter);
}
return true;
}
bool VulkanBackend::onClearBuffer() {
mMemoryPool->clear();
mDynamicMemoryPool->clear();
mAllBuffers.clear();
return true;
}
Execution* VulkanBackend::onCreate(const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs,
const MNN::Op* op) {
auto creator = getCreatorMap();
auto iter = creator->find(op->type());
if (iter == creator->end()) {
MNN_PRINT("Vulkan don't support %d, %s: %s\n", op->type(), EnumNameOpType(op->type()),
op->name()->c_str());
return nullptr;
}
bool valid = true;
for (auto t : inputs) {
if (TensorUtils::getDescribe(t)->dimensionFormat == MNN_DATA_FORMAT_NC4HW4 && !_supportImageSize(t)) {
valid = false;
break;
}
}
for (auto t : outputs) {
if (TensorUtils::getDescribe(t)->dimensionFormat == MNN_DATA_FORMAT_NC4HW4 && !_supportImageSize(t)) {
valid = false;
break;
}
}
if (!valid) {
MNN_ERROR("Vulkan don't support for %s, type=%s, Tensor not support\n", op->name()->c_str(), EnumNameOpType(op->type()));
return nullptr;
}
auto originExecution = (VulkanBasicExecution*)iter->second->onCreate(inputs, outputs, op, this);
if (nullptr == originExecution) {
MNN_ERROR("Vulkan don't support for %s, type=%s, Special case\n", op->name()->c_str(), EnumNameOpType(op->type()));
return nullptr;
}
if (mDirect) {
return new VulkanBasicExecutionDirect(std::shared_ptr<VulkanBasicExecution>(originExecution));
}
return new VulkanBasicExecutionInDirect(std::shared_ptr<VulkanBasicExecution>(originExecution));
}
void VulkanBackend::onExecuteBegin() const {
if (!mDirect) {
mCmdBuffers.push_back(mCmdBuffer->get());
}
// FUNC_PRINT_ALL(mDynamicMemoryPool->computeSize(), f);
}
void VulkanBackend::onExecuteEnd() const {
_finish();
}
void VulkanBackend::_finish() const {
if (mCmdBuffers.empty()) {
return;
}
VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.pNext = nullptr,
.waitSemaphoreCount = 0,
.pWaitSemaphores = nullptr,
.pWaitDstStageMask = nullptr,
.commandBufferCount = (uint32_t)mCmdBuffers.size(),
.pCommandBuffers = mCmdBuffers.data(),
.signalSemaphoreCount = 0,
.pSignalSemaphores = nullptr};
auto fenceReal = mFence->get();
mFence->reset();
CALL_VK(vkQueueSubmit(device().acquireDefaultDevQueue(), 1, &submit_info, fenceReal));
mCmdBuffers.clear();
auto res = mFence->wait();
MNN_VK_CHECK(res);
}
const VulkanDevice& VulkanBackend::device() const {
return (*mDevice);
}
void VulkanBackend::onCopyBuffer(const Tensor* srcTensor, const Tensor* dstTensor) const {
AUTOTIME;
if (srcTensor->host<float>() != nullptr) {
_finish();
auto size = _getAlignSize(srcTensor) * 4;
// host->gpu
_allocHostBuffer(size);
_copyTensorToBuffer(srcTensor, mHostBuffer.get());
auto format = TensorUtils::getDescribe(srcTensor)->dimensionFormat;
auto key = std::make_tuple(dstTensor, true, format);
auto iter = mConverters.find(key);
if (iter == mConverters.end()) {
auto converter = std::make_shared<VulkanImageConverter>(this);
std::shared_ptr<VulkanCommandPool::Buffer> convertorBuffer(
const_cast<VulkanCommandPool::Buffer*>(mCmdPool->allocBuffer()));
convertorBuffer->begin(0);
converter->encodeBufferToTensor(mHostBuffer->buffer(), dstTensor, mHostBuffer->size(), 0,
TensorUtils::getDescribe(srcTensor)->dimensionFormat,
convertorBuffer.get());
convertorBuffer->end();
mConverters.insert(std::make_pair(key, std::make_pair(converter, convertorBuffer)));
iter = mConverters.find(key);
}
mCmdBuffers.push_back(iter->second.second->get());
} else {
// gpu->host
auto size = _getAlignSize(dstTensor) * 4;
_finish();
_allocHostBuffer(size);
auto format = TensorUtils::getDescribe(dstTensor)->dimensionFormat;
auto key = std::make_tuple(srcTensor, false, format);
auto iter = mConverters.find(key);
if (iter == mConverters.end()) {
auto converter = std::make_shared<VulkanImageConverter>(this);
std::shared_ptr<VulkanCommandPool::Buffer> convertorBuffer(
const_cast<VulkanCommandPool::Buffer*>(mCmdPool->allocBuffer()));
convertorBuffer->begin(0);
converter->encodeTensorToBuffer(srcTensor, mHostBuffer->buffer(), mHostBuffer->size(), 0,
TensorUtils::getDescribe(dstTensor)->dimensionFormat,
convertorBuffer.get());
convertorBuffer->end();
mConverters.insert(std::make_pair(key, std::make_pair(converter, convertorBuffer)));
iter = mConverters.find(key);
}
mCmdBuffers.push_back(iter->second.second->get());
_finish();
_copyBufferToTensor(dstTensor, mHostBuffer.get());
}
}
const VulkanTensor* VulkanBackend::findTensor(uint64_t deviceId) const {
auto iter = mAllBuffers.find(deviceId);
if (iter != mAllBuffers.end()) {
return iter->second.get();
}
return nullptr;
}
void VulkanBackend::_allocHostBuffer(size_t size) const {
if (mHostBuffer.get() == nullptr || mHostBuffer->size() < size) {
mHostBuffer =
std::make_shared<VulkanBuffer>(getMemoryPool(), false, size, nullptr, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
VK_SHARING_MODE_EXCLUSIVE, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
mConverters.clear();
}
}
bool VulkanBackend::addCreator(OpType t, Creator* c) {
auto allKind = getCreatorMap();
allKind->insert(std::make_pair(t, c));
return true;
}
void VulkanBackend::copyBufferToImage(const VulkanBuffer* buffer, const VulkanImage* image) const {
std::vector<int> dimVector = image->dims();
if (image->format() != VK_FORMAT_R16G16B16A16_SFLOAT) {
VkBufferImageCopy copyRegions;
::memset(©Regions, 0, sizeof(copyRegions));
copyRegions.imageOffset.x = 0;
copyRegions.imageOffset.y = 0;
copyRegions.imageOffset.z = 0;
copyRegions.imageExtent.depth = image->depth();
copyRegions.imageExtent.height = image->height();
copyRegions.imageExtent.width = image->width();
copyRegions.imageSubresource.layerCount = 1;
copyRegions.imageSubresource.mipLevel = 0;
copyRegions.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copyRegions.imageSubresource.baseArrayLayer = 0;
std::unique_ptr<VulkanCommandPool::Buffer> cmdbuffer(
const_cast<VulkanCommandPool::Buffer*>(mCmdPool->allocBuffer()));
cmdbuffer->begin(0);
vkCmdCopyBufferToImage(cmdbuffer->get(), buffer->buffer(), image->get(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1, ©Regions);
cmdbuffer->end();
mCmdPool->submitAndWait(cmdbuffer->get());
}
const VulkanPipeline* transformPipeline = nullptr;
std::vector<VkDescriptorType> types{VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER};
int localX = 16;
int localY = 16;
int localZ = 1;
switch (dimVector.size()) {
case 1:
transformPipeline = getPipeline("glsl_buffer2Image1D_comp",
/*glsl_buffer2Image1D_comp, glsl_buffer2Image1D_comp_len,*/ types);
localX = 256;
localY = 1;
break;
case 2:
transformPipeline = getPipeline("glsl_buffer2Image2D_comp",
/*glsl_buffer2Image2D_comp, glsl_buffer2Image2D_comp_len,*/ types);
break;
case 3:
transformPipeline = getPipeline("glsl_buffer2Image3D_comp",
/*glsl_buffer2Image3D_comp, glsl_buffer2Image3D_comp_len,*/ types);
break;
default:
break;
}
std::unique_ptr<VulkanPipeline::DescriptorSet> sets(transformPipeline->createSet());
auto constBuffer = std::make_shared<VulkanBuffer>(getMemoryPool(), false, dimVector.size() * sizeof(int),
dimVector.data(), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);
sets->writeImage(image->view(), mSampler->get(), VK_IMAGE_LAYOUT_GENERAL, 0);
sets->writeBuffer(buffer->buffer(), 1, buffer->size());
sets->writeBuffer(constBuffer->buffer(), 2, constBuffer->size());
std::unique_ptr<VulkanCommandPool::Buffer> cmdbuffer(
const_cast<VulkanCommandPool::Buffer*>(mCmdPool->allocBuffer()));
cmdbuffer->begin(0);
transformPipeline->bind(cmdbuffer->get(), sets->get());
vkCmdDispatch(cmdbuffer->get(), UP_DIV(image->width(), localX), UP_DIV(image->height(), localY),
UP_DIV(image->depth(), localZ));
cmdbuffer->end();
mCmdPool->submitAndWait(cmdbuffer->get());
}
static bool _testVulkan() {
// std::make_unique need c++14
std::unique_ptr<VulkanInstance> instance(new VulkanInstance());
if (nullptr == instance) {
MNN_ERROR("Invalide device for support vulkan\n");
return false;
}
if (!instance->success()) {
MNN_ERROR("Invalide device for support vulkan\n");
return false;
}
if (!instance->supportVulkan()) {
MNN_ERROR("Invalide device for support vulkan\n");
return false;
}
return true;
}
// –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
// Backend Register
// –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
class VulkanBackendCreator : public BackendCreator {
virtual Backend* onCreate(const Backend::Info& info) const {
MNNVulkanContext* context = nullptr;
if (nullptr != info.user && nullptr != info.user->sharedContext) {
MNN_PRINT("Use user's vulkan context\n");
context = static_cast<MNNVulkanContext*>(info.user->sharedContext);
}
bool direct = true;
if (Backend::Info::INDIRECT == info.mode) {
direct = false;
}
auto backend = new VulkanBackend(context, direct);
if (!backend->success()) {
delete backend;
return nullptr;
}
return backend;
}
virtual bool onValid(Backend::Info& info) const {
return true;
}
};
static bool gResistor = []() {
if (InitVulkan()) {
if (_testVulkan()) {
MNNInsertExtraBackendCreator(MNN_FORWARD_VULKAN, new VulkanBackendCreator);
}
return true;
}
return false;
}();
} // namespace MNN
|
#include "IPC_TCP_Server.h"
//Comment out to get the console window (use for debugging)
#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup")
int main(void)
{
TCP_Server *app(nullptr);
try
{
app = new TCP_Server();
}
catch (...)
{
return 1;
}
app->Run();
delete app;
return 0;
}
|
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <limits>
#include "whoop.hpp"
#include "bellman-ford.hpp"
//Bellman-Ford algorithm w/o negative cycle check
int main(int argc, char** argv)
{
using namespace whoop;
static const int starting_node = 0;
VecIn connections_v("connections_v");
VecIn connections_i("connections_i");
TensorIn connections_j("connections_j");
VecOut distances("distances");
int kNumDstsL0 = 5;
int kNumDstsL1 = 2;
int kNumSrcsL0 = 5;
int kNumSrcsL1 = 2;
whoop::AddOption(&kNumDstsL0, "num_dsts_0,d", "Size of L0 dst tile.");
whoop::AddOption(&kNumDstsL1, "num_dsts_1,d", "Size of L1 dst tile.");
whoop::AddOption(&kNumSrcsL0, "num_srcs_0,s", "Size of L0 src tile.");
whoop::AddOption(&kNumSrcsL1, "num_srcs_1,s", "Size of L1 src tile.");
whoop::Init(argc, argv);
int kNumNodes = connections_i.Size() - 1;
int kNumEdges = connections_v.Size();
assert(connections_v.Size() == connections_j.Size(0));
assert(kNumNodes % (kNumDstsL0 * kNumDstsL1) == 0);
assert(kNumNodes % (kNumSrcsL0 * kNumSrcsL1) == 0);
const int kNumDstsL2 = kNumNodes / (kNumDstsL1 * kNumDstsL0);
const int kNumSrcsL2 = kNumNodes / (kNumSrcsL1 * kNumSrcsL0);
distances.Resize(kNumNodes);
// Initialize to MAX_INT.
for (int x = 0; x < kNumNodes; x++)
{
distances.At(x) = std::numeric_limits<int>::max() / 2;
}
distances.At(starting_node) = 0;
TensorPort distances2(&distances);
whoop::T(0) << "Number of Nodes: " << kNumNodes << whoop::EndT;
whoop::T(0) << "Number of Edges: " << kNumEdges << whoop::EndT;
Tensor connections_i_d0({kNumNodes + 1, kNumDstsL2 * kNumDstsL1}, 0, "connections_i_d0");
whoop::T(0) << "Beginning to tile the Index matrix into (" << kNumDstsL2 << " x " << kNumDstsL1 << ") tiles of max size: " << kNumDstsL0 << whoop::EndT;
TileCompressedTensor2D(kNumDstsL0, (kNumDstsL2 * kNumDstsL1), connections_i, connections_j, connections_i_d0);
whoop::T(0) << "Done." << whoop::EndT;
/*
whoop::T(0) << "Beginning to tile the Index matrix into " << kNumDstsL1 << " tiles of max size: " << kNumDstsL0 << whoop::EndT;
// Fill in connections_i_d0 version.
for (int s = 0; s < kNumNodes; s++)
{
// Everything starts out with the base number
for (int x = 0; x < (kNumDstsL2 * kNumDstsL1); x++)
{
connections_i_d0.At({s, x}) = connections_i.At(s);
}
// Now divide the points into tiles based on actual index.
int d1_cur = 0;
for (int di = connections_i.At(s); di < connections_i.At(s + 1); di++)
{
// Get the original, actual index.
int d = connections_j.At({di, 0});
// Figure out what tile it belongs to.
d1_cur = d / kNumDstsL0;
connections_i_d0.At({s, d1_cur + 1})++;
}
// Fill in all the rest of the entries with the last number
// (meaning they have no entries)
for (int d1 = d1_cur; d1 < (kNumDstsL2 * kNumDstsL1); d1++)
{
connections_i_d0.At({s, d1 + 1}) = connections_i_d0.At({s, d1_cur + 1});
}
}
// Set the last entries by hand. These are just the end limits.
for (int x = 0; x < (kNumDstsL2 * kNumDstsL1); x++)
{
connections_i_d0.At({kNumNodes, x}) = connections_i.At(kNumNodes);
}
*/
whoop::T(0) << "Done." << whoop::EndT;
// Short-form variable names
static const int V = kNumNodes;
const int D0 = kNumDstsL0;
const int D1 = kNumDstsL1;
const int D2 = kNumDstsL2;
const int S0 = kNumSrcsL0;
const int S1 = kNumSrcsL1;
const int S2 = kNumSrcsL2;
Var i("i");
Var s("s");
Var d("d");
Var di0("di0");
Var di0_start("di0_start");
Var di0_end("di0_end");
Var d1("d1");
Var d2("d2");
Var s0("s0");
Var s1("s1");
Var s2("s2");
t_for(i, 0, V);
{
t_for(s2, 0, S2);
{
distances.AddTileLevel(D1 * D0);
distances2.AddTileLevel(S1 * S0);
t_for(d2, 0, D2);
{
t_for(s1, 0, S1);
{
distances.AddTileLevel(D0);
distances2.AddTileLevel(S0);
t_for(d1, 0, D1);
{
t_for(s0, 0, S0);
{
connections_v.AddTileLevel(1);
connections_j.AddTileLevel(1);
connections_i_d0.AddTileLevel(2);
distances.AddTileLevel(1);
distances2.AddTileLevel(1);
s = (s2 * S1 * S0) + (s1 * S0) + s0;
di0_start = connections_i_d0[s][d2 * D1 + d1];
w_if(d1 != (D2 * D1) - 1);
{
di0_end = connections_i_d0[s][d2 * D1 + d1 + 1];
}
w_else();
{
di0_end = connections_i_d0[s+1][0];
}
end();
t_for(di0, di0_start, di0_end);
{
d = connections_j[di0][0];
w_if (distances[d] > (distances2[s] + connections_v[di0]));
{
distances[d] = distances2[s] + connections_v[di0];
}
end();
}
end();
}
end();
}
end();
}
end();
}
end();
}
end();
}
end();
std::cout << "RUNNING..." << std::endl;
whoop::Run();
std::cout << "DONE." << std::endl;
for (int v = 0; v < V; v++)
{
whoop::T(1) << "Distances " << v << " = " << distances.At(v) << whoop::EndT;
}
whoop::Done();
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Linq.Expressions.Interpreter.Instruction
#include "System/Linq/Expressions/Interpreter/Instruction.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Linq::Expressions::Interpreter
namespace System::Linq::Expressions::Interpreter {
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Type
class Type;
}
// Completed forward declares
// Type namespace: System.Linq.Expressions.Interpreter
namespace System::Linq::Expressions::Interpreter {
// Forward declaring type: GreaterThanOrEqualInstruction
class GreaterThanOrEqualInstruction;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction);
DEFINE_IL2CPP_ARG_TYPE(::System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction*, "System.Linq.Expressions.Interpreter", "GreaterThanOrEqualInstruction");
// Type namespace: System.Linq.Expressions.Interpreter
namespace System::Linq::Expressions::Interpreter {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: System.Linq.Expressions.Interpreter.GreaterThanOrEqualInstruction
// [TokenAttribute] Offset: FFFFFFFF
class GreaterThanOrEqualInstruction : public ::System::Linq::Expressions::Interpreter::Instruction {
public:
// Nested type: ::System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::GreaterThanOrEqualSByte
class GreaterThanOrEqualSByte;
// Nested type: ::System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::GreaterThanOrEqualInt16
class GreaterThanOrEqualInt16;
// Nested type: ::System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::GreaterThanOrEqualChar
class GreaterThanOrEqualChar;
// Nested type: ::System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::GreaterThanOrEqualInt32
class GreaterThanOrEqualInt32;
// Nested type: ::System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::GreaterThanOrEqualInt64
class GreaterThanOrEqualInt64;
// Nested type: ::System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::GreaterThanOrEqualByte
class GreaterThanOrEqualByte;
// Nested type: ::System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::GreaterThanOrEqualUInt16
class GreaterThanOrEqualUInt16;
// Nested type: ::System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::GreaterThanOrEqualUInt32
class GreaterThanOrEqualUInt32;
// Nested type: ::System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::GreaterThanOrEqualUInt64
class GreaterThanOrEqualUInt64;
// Nested type: ::System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::GreaterThanOrEqualSingle
class GreaterThanOrEqualSingle;
// Nested type: ::System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::GreaterThanOrEqualDouble
class GreaterThanOrEqualDouble;
public:
// private readonly System.Object _nullValue
// Size: 0x8
// Offset: 0x10
::Il2CppObject* nullValue;
// Field size check
static_assert(sizeof(::Il2CppObject*) == 0x8);
public:
// Creating conversion operator: operator ::Il2CppObject*
constexpr operator ::Il2CppObject*() const noexcept {
return nullValue;
}
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_SByte
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_SByte();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_SByte
static void _set_s_SByte(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_Int16
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_Int16();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_Int16
static void _set_s_Int16(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_Char
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_Char();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_Char
static void _set_s_Char(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_Int32
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_Int32();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_Int32
static void _set_s_Int32(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_Int64
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_Int64();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_Int64
static void _set_s_Int64(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_Byte
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_Byte();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_Byte
static void _set_s_Byte(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_UInt16
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_UInt16();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_UInt16
static void _set_s_UInt16(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_UInt32
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_UInt32();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_UInt32
static void _set_s_UInt32(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_UInt64
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_UInt64();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_UInt64
static void _set_s_UInt64(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_Single
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_Single();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_Single
static void _set_s_Single(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_Double
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_Double();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_Double
static void _set_s_Double(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullSByte
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_liftedToNullSByte();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullSByte
static void _set_s_liftedToNullSByte(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullInt16
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_liftedToNullInt16();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullInt16
static void _set_s_liftedToNullInt16(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullChar
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_liftedToNullChar();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullChar
static void _set_s_liftedToNullChar(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullInt32
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_liftedToNullInt32();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullInt32
static void _set_s_liftedToNullInt32(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullInt64
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_liftedToNullInt64();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullInt64
static void _set_s_liftedToNullInt64(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullByte
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_liftedToNullByte();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullByte
static void _set_s_liftedToNullByte(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullUInt16
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_liftedToNullUInt16();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullUInt16
static void _set_s_liftedToNullUInt16(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullUInt32
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_liftedToNullUInt32();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullUInt32
static void _set_s_liftedToNullUInt32(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullUInt64
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_liftedToNullUInt64();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullUInt64
static void _set_s_liftedToNullUInt64(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullSingle
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_liftedToNullSingle();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullSingle
static void _set_s_liftedToNullSingle(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullDouble
static ::System::Linq::Expressions::Interpreter::Instruction* _get_s_liftedToNullDouble();
// Set static field: static private System.Linq.Expressions.Interpreter.Instruction s_liftedToNullDouble
static void _set_s_liftedToNullDouble(::System::Linq::Expressions::Interpreter::Instruction* value);
// Get instance field reference: private readonly System.Object _nullValue
[[deprecated("Use field access instead!")]] ::Il2CppObject*& dyn__nullValue();
// private System.Void .ctor(System.Object nullValue)
// Offset: 0xF15EA4
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static GreaterThanOrEqualInstruction* New_ctor(::Il2CppObject* nullValue) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<GreaterThanOrEqualInstruction*, creationType>(nullValue)));
}
// static public System.Linq.Expressions.Interpreter.Instruction Create(System.Type type, System.Boolean liftedToNull)
// Offset: 0xF15ED0
static ::System::Linq::Expressions::Interpreter::Instruction* Create(::System::Type* type, bool liftedToNull);
// public override System.Int32 get_ConsumedStack()
// Offset: 0xF15E50
// Implemented from: System.Linq.Expressions.Interpreter.Instruction
// Base method: System.Int32 Instruction::get_ConsumedStack()
int get_ConsumedStack();
// public override System.Int32 get_ProducedStack()
// Offset: 0xF15E58
// Implemented from: System.Linq.Expressions.Interpreter.Instruction
// Base method: System.Int32 Instruction::get_ProducedStack()
int get_ProducedStack();
// public override System.String get_InstructionName()
// Offset: 0xF15E60
// Implemented from: System.Linq.Expressions.Interpreter.Instruction
// Base method: System.String Instruction::get_InstructionName()
::StringW get_InstructionName();
}; // System.Linq.Expressions.Interpreter.GreaterThanOrEqualInstruction
#pragma pack(pop)
static check_size<sizeof(GreaterThanOrEqualInstruction), 16 + sizeof(::Il2CppObject*)> __System_Linq_Expressions_Interpreter_GreaterThanOrEqualInstructionSizeCheck;
static_assert(sizeof(GreaterThanOrEqualInstruction) == 0x18);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::Create
// Il2CppName: Create
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Linq::Expressions::Interpreter::Instruction* (*)(::System::Type*, bool)>(&System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::Create)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
static auto* liftedToNull = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction*), "Create", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type, liftedToNull});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::get_ConsumedStack
// Il2CppName: get_ConsumedStack
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::*)()>(&System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::get_ConsumedStack)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction*), "get_ConsumedStack", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::get_ProducedStack
// Il2CppName: get_ProducedStack
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::*)()>(&System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::get_ProducedStack)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction*), "get_ProducedStack", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::get_InstructionName
// Il2CppName: get_InstructionName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::*)()>(&System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction::get_InstructionName)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::GreaterThanOrEqualInstruction*), "get_InstructionName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
|
#ifdef PEGASUS_OS_FREEBSD
#ifndef __UNIX_DNSGENERALSETTINGDATA_PRIVATE_H
#define __UNIX_DNSGENERALSETTINGDATA_PRIVATE_H
#endif
#endif
|
// $Id$
#include "ace/Local_Tokens.h"
#if defined (ACE_HAS_TOKENS_LIBRARY)
#include "ace/Thread.h"
#include "ace/Token_Manager.h"
#include "ace/OS_NS_unistd.h"
#if !defined (__ACE_INLINE__)
#include "ace/Local_Tokens.inl"
#endif /* __ACE_INLINE__ */
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
void
ACE_Tokens::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_Tokens::dump");
ACELIB_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Tokens::dump:\n")
ACE_TEXT (" reference_cont_ = %d\n")
ACE_TEXT (" token_name_ = %s\n"),
reference_count_, token_name_));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("waiters_\n")));
this->waiters_.dump ();
ACELIB_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
ACE_Tokens::ACE_Tokens (void)
: visited_ (0),
reference_count_ (0)
{
ACE_TRACE ("ACE_Tokens::ACE_Tokens");
}
ACE_Tokens::~ACE_Tokens (void)
{
}
void
ACE_Tokens::make_owner (ACE_TPQ_Entry *caller)
{
this->waiters_.remove (caller);
this->waiters_.enqueue (caller, 0);
}
ACE_Token_Proxy_Queue *
ACE_Tokens::waiters ()
{
ACE_TRACE ("ACE_Tokens::waiters");
return &this->waiters_;
}
int
ACE_Tokens::no_of_waiters ()
{
ACE_TRACE ("ACE_Tokens::no_of_waiters");
return this->waiters_.size ();
}
#if defined (ACE_LACKS_INLINE_FUNCTIONS)
ACE_Null_Token::ACE_Null_Token (void)
{
}
ACE_Null_Token::~ACE_Null_Token (void)
{
}
#endif /* ACE_LACKS_INLINE_FUNCTIONS */
void
ACE_TPQ_Entry::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_TPQ_Entry::dump");
ACELIB_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
ACELIB_DEBUG ((LM_DEBUG,
ACE_TEXT ("ACE_TPQ_Entry::dump:\n")
ACE_TEXT (" nesting_level_ = %d\n")
ACE_TEXT (" client_id_ = %s\n"),
nesting_level_,
client_id_));
if (next_ != 0)
{
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("next:.\n")));
next_->dump ();
}
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_TPQ_Entry::dump end.\n")));
ACELIB_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
ACE_TPQ_Entry::ACE_TPQ_Entry (const ACE_Token_Proxy *new_proxy,
const ACE_TCHAR *client_id)
: cond_var_ (lock_),
next_ (0),
// This const typecast is safe.
proxy_ ((ACE_Token_Proxy *) new_proxy),
nesting_level_ (0),
sleep_hook_ (0)
{
ACE_TRACE ("ACE_TPQ_Entry::ACE_TPQ_Entry");
if (client_id != 0)
this->client_id (client_id);
else
{
// Just make sure we have enough space.
ACE_TCHAR host_name[MAXHOSTNAMELEN];
ACE_TCHAR name[(sizeof host_name / sizeof (ACE_TCHAR)) + 256];
ACE_OS::hostname (host_name, sizeof host_name);
ACE_thread_t thread_id = ACE_Thread::self ();
// The cast is an attempt to get this to compile (and run,
// hopefully) regardless of the type of ACE_thread_t.
ACE_OS::sprintf (name,
ACE_TEXT ("/%s/%u/%lu"),
host_name,
static_cast<u_int> (ACE_OS::getpid ()),
*reinterpret_cast<u_long *> (&thread_id));
this->client_id (name);
}
}
ACE_TPQ_Entry::ACE_TPQ_Entry (void)
: cond_var_ (lock_),
proxy_ (0),
nesting_level_ (0),
sleep_hook_ (0)
{
ACE_TRACE ("ACE_TPQ_Entry::ACE_TPQ_Entry null const.");
}
ACE_TPQ_Entry::ACE_TPQ_Entry (const ACE_TPQ_Entry &rhs)
: cond_var_ (lock_)
{
ACE_TRACE ("ACE_TPQ_Entry::ACE_TPQ_Entry copy const.");
*this = rhs;
}
ACE_TPQ_Entry::~ACE_TPQ_Entry (void)
{
ACE_TRACE ("ACE_TPQ_Entry::~ACE_TPQ_Entry");
}
void
ACE_TPQ_Entry::operator= (const ACE_TPQ_Entry& rhs)
{
ACE_TRACE ("ACE_TPQ_Entry::operator=");
if (&rhs == this)
return;
this->proxy_ = rhs.proxy ();
this->nesting_level_ = rhs.nesting_level ();
this->client_id (rhs.client_id ());
this->sleep_hook_ = rhs.sleep_hook ();
}
void
ACE_TPQ_Entry::client_id (const ACE_TCHAR *id)
{
ACE_TRACE ("ACE_TPQ_Entry::client_id");
if (id == 0)
return;
ACE_OS::strsncpy (this->client_id_,
(ACE_TCHAR *) id,
ACE_MAXCLIENTIDLEN);
}
ACE_TSS_TPQ_Entry::~ACE_TSS_TPQ_Entry (void)
{
}
void
ACE_TSS_TPQ_Entry::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_TSS_TPQ_Entry::dump");
ACELIB_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_TSS_TPQ_Entry::dump:\n")
ACE_TEXT (" client_id_ = %s\n"),
client_id_ == 0 ? ACE_TEXT ("0") : client_id_));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("base:\n")));
ACE_TPQ_ENTRY::dump ();
ACELIB_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
ACE_TSS_TPQ_Entry::ACE_TSS_TPQ_Entry (const ACE_Token_Proxy *proxy,
const ACE_TCHAR *client_id)
: proxy_ (proxy),
client_id_ (client_id)
{
ACE_TRACE ("ACE_TSS_TPQ_Entry::ACE_TSS_TPQ_Entry");
}
ACE_TPQ_Entry *
ACE_TSS_TPQ_Entry::make_TSS_TYPE (void) const
{
ACE_TRACE ("ACE_TSS_TPQ_Entry::make_TSS_TYPE");
ACE_TPQ_Entry *temp;
ACE_NEW_RETURN (temp,
ACE_TPQ_Entry (this->proxy_,
this->client_id_),
0);
return temp;
}
ACE_TSS_TPQ_Entry::operator ACE_TPQ_Entry * (void)
{
#if !defined (ACE_NO_TSS_TOKENS)
return (ACE_TPQ_Entry *) (*((ACE_TSS<ACE_TPQ_Entry> *) this));
#else
// Not sure this is the right thing to do, but it seems to work.
// The base class ALSO has a proxy_ and client_id_ members (weird?)
// which don't get initialised. The following two lines make this
// the same as the subclass, so that the slicing works .
ACE_TPQ_ENTRY::proxy ((ACE_Token_Proxy *)(this->proxy_));
ACE_TPQ_ENTRY::client_id (this->client_id_);
return (ACE_TPQ_Entry *) this;;
#endif /* !ACE_NO_TSS_TOKENS */
}
ACE_TPQ_Iterator::ACE_TPQ_Iterator (ACE_Token_Proxy_Queue &q)
: current_ (q.head_)
{
ACE_TRACE ("ACE_TPQ_Iterator::ACE_TPQ_Iterator");
}
int
ACE_TPQ_Iterator::next (ACE_TPQ_Entry *&next_item)
{
ACE_TRACE ("ACE_TPQ_Iterator::next");
next_item = this->current_;
return current_ != 0;
}
int
ACE_TPQ_Iterator::done (void) const
{
ACE_TRACE ("ACE_TPQ_Iterator::done");
return this->current_ == 0;
}
void
ACE_TPQ_Iterator::advance (void)
{
ACE_TRACE ("ACE_TPQ_Iterator::advance");
if (current_ != 0)
this->current_ = this->current_->next_;
}
void
ACE_TPQ_Iterator::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_TPQ_Iterator::dump");
ACELIB_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_TPQ_Iterator::dump:\n")
ACE_TEXT (" current_ = %d\n"),
(long) this->current_));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("head_ and tail_\n")));
ACELIB_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
void
ACE_Token_Proxy_Queue::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_Token_Proxy_Queue::dump");
ACELIB_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Token_Proxy_Queue::dump:\n")
ACE_TEXT (" size_ = %d\n"),
size_));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("head_ and tail_\n")));
if (this->head_ != 0)
this->head_->dump ();
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Token_Proxy_Queue::dump end.\n")));
ACELIB_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
ACE_Token_Proxy_Queue::ACE_Token_Proxy_Queue (void)
: head_ (0),
tail_ (0),
size_ (0)
{
ACE_TRACE ("ACE_Token_Proxy_Queue::ACE_Token_Proxy_Queue");
}
void
ACE_Token_Proxy_Queue::enqueue (ACE_TPQ_Entry *tpq,
int position)
{
ACE_TRACE ("ACE_Token_Proxy_Queue::enqueue");
tpq->next_ = 0;
++this->size_;
if (this->head_ == 0)
{
// make tpq the entire list
this->head_ = this->tail_ = tpq;
return;
}
if (position == 0)
{
// make head of list
tpq->next_ = this->head_;
this->head_ = tpq;
return;
}
if (position == -1)
{
// stick at back of list
this->tail_->next_ = tpq;
this->tail_ = tpq;
return;
}
// walk through list to insertion point
ACE_TPQ_Entry *temp = head_;
for (int x = position;
x > 1;
--x)
{
// end of queue?
if (temp->next_ == 0)
break;
// advance pointer
else
temp = temp->next_;
}
// insert new tpq after temp
tpq->next_ = temp->next_;
temp->next_ = tpq;
}
void
ACE_Token_Proxy_Queue::dequeue (void)
{
ACE_TRACE ("ACE_Token_Proxy_Queue::dequeue");
if (head_ == 0)
return;
ACE_TPQ_Entry *temp = this->head_;
this->head_ = this->head_->next_;
temp->next_ = 0;
--this->size_;
if (this->head_ == 0 && this->size_ != 0)
ACELIB_ERROR ((LM_ERROR,
ACE_TEXT ("incorrect size = %d\n"),
this->size_));
}
/*
int
ACE_Token_Proxy_Queue::member (const ACE_TCHAR *id)
{
ACE_TRACE ("ACE_Token_Proxy_Queue::member");
for (ACE_TPQ_Entry *temp = this->head_;
temp != 0;
temp = temp->next_)
if (ACE_OS::strcmp (temp->client_id (), id) == 0)
// We found it!
return 1;
// We didn't find it :-(
return 0;
}
*/
void
ACE_Token_Proxy_Queue::remove (const ACE_TPQ_Entry *remove_me)
{
ACE_TRACE ("ACE_Token_Proxy_Queue::remove");
// sanity
if ((remove_me == 0) || (this->head_ == 0))
return;
// is it the head?
if (this->head_ == remove_me) // pointer comparison.
{
this->head_ = this->head_->next_;
if (this->head_ == 0)
this->tail_ = 0;
--this->size_;
return;
}
ACE_TPQ_Entry *temp = this->head_;
ACE_TPQ_Entry *previous = 0;
// is it in the middle or tail?
while (temp != 0)
{
if (temp == remove_me)
{
// previous should never be null since the first if
// conditional should always be false
previous->next_ = temp->next_;
// is it the tail?
if (this->tail_ == temp)
this->tail_ = previous;
--this->size_;
return;
}
previous = temp;
temp = temp->next_;
}
// it wasn't in the list.
return;
}
void
ACE_Mutex_Token::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_Mutex_Token::dump");
ACELIB_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Mutex_Token::dump:\n")));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("lock_\n")));
lock_.dump ();
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("base:\n")));
ACE_Tokens::dump ();
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Mutex_Token::dump end.\n")));
ACELIB_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
ACE_Mutex_Token::ACE_Mutex_Token (const ACE_TCHAR *name)
{
ACE_TRACE ("ACE_Mutex_Token::ACE_Mutex_Token");
ACE_OS::strsncpy (this->token_name_,
name,
ACE_MAXTOKENNAMELEN);
}
ACE_Mutex_Token::~ACE_Mutex_Token (void)
{
ACE_TRACE ("ACE_Mutex_Token::~ACE_Mutex_Token");
}
int
ACE_Mutex_Token::acquire (ACE_TPQ_Entry *caller,
int ignore_deadlock,
int notify)
{
ACE_TRACE ("ACE_Mutex_Token::acquire");
// We need to acquire two locks. This one to ensure that only one
// thread uses this token at a time.
ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon1, this->lock_, -1);
// This one to ensure an atomic transaction across all tokens. Note
// that this order is crucial too. It's resource coloring for other
// threads which may be calling this same token.
ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon2, ACE_Token_Manager::instance ()->mutex (), -1);
// Does _anyone_ own the token?
if (this->owner () == 0)
{
// there are no waiters, so queue as the first waiter (the owner.)
this->waiters_.enqueue (caller, -1);
return 0; // success
}
// Does the caller already own it?
if (this->is_owner (caller->client_id ()))
{
// Recursive acquisition.
caller->nesting_level (1);
return 0; // success
}
// Check for deadlock.
if (!ignore_deadlock
&& ACE_Token_Manager::instance ()->check_deadlock (caller->proxy ()) == 1)
{
errno = EDEADLK;
ACE_RETURN (-1);
}
// Someone owns it. Sorry, you're getting queued up at the end of
// the waiter queue.
this->waiters_.enqueue (caller, -1);
if (notify)
this->owner ()->call_sleep_hook ();
errno = EWOULDBLOCK;
ACE_RETURN (-1);
ACE_NOTREACHED (return -1);
}
int
ACE_Mutex_Token::tryacquire (ACE_TPQ_Entry *caller)
{
ACE_TRACE ("ACE_Mutex_Token::tryacquire");
// We need to acquire two locks. This one to ensure that only one
// thread uses this token at a time.
ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon1, this->lock_, -1);
// This one to ensure an atomic transaction across all tokens. Note
// that this order is crucial too. It's resource coloring for other
// threads which may be calling this same token.
ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon2, ACE_Token_Manager::instance ()->mutex (), -1);
// Does _anyone_ own the token?
if (this->owner () == 0)
{
this->waiters_.enqueue (caller, -1);
return 0; // success
}
// Does the caller already own it?
if (this->is_owner (caller->client_id ()))
{
// recursive acquisition
caller->nesting_level (1);
return 0; // success
}
else
// Someone owns it. Fail.
{
errno = EWOULDBLOCK;
ACE_RETURN (-1);
}
ACE_NOTREACHED (return -1);
}
int
ACE_Mutex_Token::renew (ACE_TPQ_Entry *caller,
int requeue_position)
{
ACE_TRACE ("ACE_Mutex_Token::renew");
ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_, -1);
// Verify that the caller is the owner.
if (this->is_owner (caller->client_id ()) == 0)
{
errno = EACCES;
ACE_RETURN (-1);
}
// The caller is the owner, so check to see if there are any
// waiters. If not, we just keep the token. == 1 means that there
// is only the owner.
if (this->waiters_.size () == 1 || requeue_position == 0)
return 0;
// Requeue the caller.
this->waiters_.dequeue ();
this->waiters_.enqueue (caller, requeue_position);
// Notify new owner.
if (this->owner () != 0)
this->owner ()->proxy ()->token_acquired (this->owner ());
// Tell the caller that the operation would block.
errno = EWOULDBLOCK;
ACE_RETURN (-1);
ACE_NOTREACHED (return -1);
}
// Release the current holder of the token (which had
// better be the caller's thread!).
int
ACE_Mutex_Token::release (ACE_TPQ_Entry *caller)
{
ACE_TRACE ("ACE_Mutex_Token::release");
ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_, -1);
// Does anyone own the token?
if (this->owner () == 0)
{
errno = EACCES;
ACE_RETURN (-1);
}
// Is the caller the owner.
if (this->is_owner (caller->client_id ()))
{
// Check the nesting level.
if (caller->nesting_level () > 0)
caller->nesting_level (-1);
else
{
this->waiters_.dequeue ();
// Notify new owner.
if (this->owner () != 0)
this->owner ()->proxy ()->token_acquired (this->owner ());
}
}
else
this->remove (caller);
return 0;
}
int
ACE_Mutex_Token::owners (OWNER_STACK &stack,
const ACE_TCHAR *id)
{
ACE_TRACE ("ACE_Mutex_Token::owners");
if (this->owner () != 0)
{
stack.push (this->owner ());
// If an <id> is specified, return whether it is the owner being
// returned.
if (id != 0)
return this->owner ()->equal_client_id (id);
}
return 0;
}
int
ACE_Mutex_Token::is_waiting_for (const ACE_TCHAR *id)
{
ACE_TRACE ("ACE_Mutex_Token::is_waiting_for");
// If there is no owner, or <id> is the owner, return false.
if ((this->owner () == 0) || this->is_owner (id))
return 0;
// Step through each waiter looking for <id>.
ACE_TPQ_Iterator iterator (waiters_);
iterator.advance ();
for (ACE_TPQ_Entry *temp = 0;
iterator.next (temp) != 0;
iterator.advance ())
{
if (temp->equal_client_id (id))
return 1;
}
return 0;
}
int
ACE_Mutex_Token::is_owner (const ACE_TCHAR *id)
{
ACE_TRACE ("ACE_Mutex_Token::is_owner");
// If there is an owner, return whether it is <id>.
if ((this->owner () != 0) &&
this->owner ()->equal_client_id (id))
return 1;
else
return 0;
}
int
ACE_Mutex_Token::type (void) const
{
ACE_TRACE ("ACE_Mutex_Token::type");
return (int) ACE_Tokens::MUTEX;
}
// ************************************************************
int
ACE_RW_Token::type (void) const
{
ACE_TRACE ("ACE_RW_Token::type");
return (int) ACE_Tokens::RWLOCK;
}
void
ACE_RW_Token::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_RW_Token::dump");
ACELIB_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_RW_Token::dump:\n")
ACE_TEXT ("num_writers_ = %d\n"), num_writers_));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("lock_\n")));
this->lock_.dump ();
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("base:\n")));
ACE_Tokens::dump ();
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_RW_Token::dump end.\n")));
ACELIB_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
ACE_RW_Token::ACE_RW_Token (const ACE_TCHAR *name)
: num_writers_ (0)
{
ACE_TRACE ("ACE_RW_Token::ACE_RW_Token");
ACE_OS::strsncpy (this->token_name_,
name,
ACE_MAXTOKENNAMELEN);
}
ACE_RW_Token::~ACE_RW_Token (void)
{
ACE_TRACE ("ACE_RW_Token::~ACE_RW_Token");
}
int
ACE_RW_Token::acquire (ACE_TPQ_Entry *caller,
int ignore_deadlock,
int notify)
{
ACE_TRACE ("ACE_RW_Token::acquire");
// We need to acquire two locks. This one to ensure that only one
// thread uses this token at a time.
ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon1, this->lock_, -1);
// This one to ensure an atomic transaction across all tokens. Note
// that this order is crucial too. It's resource coloring for other
// threads which may be calling this same token.
ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon2, ACE_Token_Manager::instance ()->mutex (), -1);
if (caller->proxy ()->type () == ACE_RW_Token::WRITER)
this->num_writers_++;
// Does _anyone_ own the token?
if (this->owner () == 0)
{
// There are no waiters, so queue as the first waiter (the owner).
this->waiters_.enqueue (caller, -1);
return 0;
}
// Check for recursive acquisition.
if (this->is_owner (caller->client_id ()))
{
caller->nesting_level (1);
return 0; // Success.
}
// Reader.
if (caller->proxy ()->type () == ACE_RW_Token::READER)
{
// Are there any writers?
if (this->num_writers_ == 0)
{
// Queue the caller at the end of the queue.
this->waiters_.enqueue (caller, -1);
return 0;
}
// Else failure.
}
// Failure code.
// Check for deadlock.
if (!ignore_deadlock &&
ACE_Token_Manager::instance ()->check_deadlock (caller->proxy ()) == 1)
{
if (caller->proxy ()->type () == ACE_RW_Token::WRITER)
this->num_writers_--;
errno = EDEADLK;
ACE_RETURN (-1);
}
// Queue the caller at the end of the queue.
this->waiters_.enqueue (caller, -1);
if (notify)
{
// If it's a writer, just notify it.
if (this->owner ()->proxy ()->type () == ACE_RW_Token::WRITER)
this->owner ()->call_sleep_hook ();
else
{
// Call back all reader owners.
ACE_TPQ_Entry *temp = this->owner ();
do
{
temp->call_sleep_hook ();
temp = temp->next_;
}
while (temp != 0 &&
temp->proxy ()->type () == ACE_RW_Token::READER);
}
}
errno = EWOULDBLOCK;
ACE_RETURN (-1);
ACE_NOTREACHED (return -1);
}
int
ACE_RW_Token::tryacquire (ACE_TPQ_Entry *caller)
{
ACE_TRACE ("ACE_RW_Token::tryacquire");
// We need to acquire two locks. This one to ensure that only one
// thread uses this token at a time.
ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon1, this->lock_, -1);
// This one to ensure an atomic transaction across all tokens. Note
// that this order is crucial too. It's resource coloring for other
// threads which may be calling this same token.
ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon2, ACE_Token_Manager::instance ()->mutex (), -1);
if (caller->proxy ()->type () == ACE_RW_Token::WRITER)
{
this->num_writers_++;
}
// Does _anyone_ own the token?
if (this->owner () == 0)
{
// There are no waiters, so queue as the first waiter (the owner).
this->waiters_.enqueue (caller, -1);
return 0;
}
// Check for recursive acquisition.
if (this->is_owner (caller->client_id ()))
{
caller->nesting_level (1);
return 0; // Success.
}
// Reader.
if (caller->proxy ()->type () == ACE_RW_Token::READER)
{
// Are there any writers?
if (this->num_writers_ == 0)
{
// queue the caller at the end of the queue.
this->waiters_.enqueue (caller, -1);
return 0;
}
// Else, fail.
}
else // Writer.
// We're going to fail, so decrement the num_writers.
{
this->num_writers_--;
}
errno = EWOULDBLOCK;
ACE_RETURN (-1);
ACE_NOTREACHED (return -1);
}
int
ACE_RW_Token::renew (ACE_TPQ_Entry *caller,
int requeue_position)
{
ACE_TRACE ("ACE_RW_Token::renew");
ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_, -1);
// Werify that the caller is the owner
if (this->is_owner (caller->client_id ()) == 0)
{
errno = EACCES;
ACE_RETURN (-1);
}
// The caller is the owner, so check to see if there are any
// waiters. If not, we just keep the token.
if (this->waiters_.size () == 1 || requeue_position == 0)
return 0;
// There are waiters, so remove the caller.
this->remove (caller);
// Requeue the caller.
this->waiters_.enqueue (caller, requeue_position);
if (caller->proxy ()->type () == ACE_RW_Token::READER)
{
// If the caller got queued before any writers, the caller is
// still the owner.
if (this->is_owner (caller->client_id ()))
return 0; // success
// else fallthrough and return would block.
}
// Writers will always have to block since waiters_.size () == 1 or
// requeue_position == 0.
// Get a new owner.
this->notify_new_owner (caller);
// Tell the caller that the operation would block.
errno = EWOULDBLOCK;
ACE_RETURN (-1);
ACE_NOTREACHED (return -1);
}
int
ACE_RW_Token::release (ACE_TPQ_Entry *caller)
{
ACE_TRACE ("ACE_RW_Token::release");
ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_, -1);
// Check for errors.
if ((this->owner () == 0) ||
(this->is_owner (caller->client_id ()) == 0))
{
errno = EACCES;
ACE_RETURN (-1);
}
if (caller->proxy ()->type () == ACE_RW_Token::WRITER)
num_writers_--;
// Recursive release.
if (caller->nesting_level () > 0)
{
caller->nesting_level (-1);
return 0;
}
// Remove the caller and notify the new owner(s).
this->remove (caller);
this->notify_new_owner (caller);
return 0;
}
void
ACE_RW_Token::notify_new_owner (ACE_TPQ_Entry *old_owner)
{
ACE_TRACE ("ACE_RW_Token::notify_new_owner");
if (this->owner () == 0)
return;
if (this->owner ()->proxy ()->type () == ACE_RW_Token::READER)
{
if (old_owner->proxy ()->type () == ACE_RW_Token::READER)
// the owners already know that they're owners
return;
// The current owner is a reader and the previous owner was a
// writer, so notify all waiting readers up to the first writer.
// call back all reader owners.
ACE_TPQ_Iterator iterator (waiters_);
for (ACE_TPQ_Entry *temp = 0;
iterator.next (temp) != 0;
iterator.advance ())
{
if (temp->proxy ()->type () == WRITER)
// We've gone through all the readers.
break;
temp->proxy ()->token_acquired (temp);
}
}
else // writer
this->owner ()->proxy ()->token_acquired (this->owner ());
}
int
ACE_RW_Token::owners (OWNER_STACK &stack,
const ACE_TCHAR *id)
{
ACE_TRACE ("ACE_RW_Token::owners");
if (this->owner () == 0)
return 0;
int id_is_owner = 0;
// The first waiter is a writer, so there is only one owner.
if (this->owner ()->proxy ()->type () == WRITER)
{
stack.push (this->owner ());
// If an <id> is specified, return whether it is the owner being
// returned.
if ((id != 0) &&
(ACE_OS::strcmp (id, this->owner ()->client_id ()) == 0))
id_is_owner = 1;
}
// The first waiter is a reader, so there can be multiple owning
// readers.
else
{
ACE_TPQ_Iterator iterator (waiters_);
for (ACE_TPQ_Entry *temp = 0;
iterator.next (temp) != 0;
iterator.advance ())
{
if (temp->proxy ()->type () == WRITER)
// We've gone through all the readers.
break;
stack.push (temp);
if (!id_is_owner && (id != 0) &&
(ACE_OS::strcmp (id, temp->client_id ()) == 0))
id_is_owner = 1;
}
}
return id_is_owner;
}
int
ACE_RW_Token::is_waiting_for (const ACE_TCHAR *id)
{
ACE_TRACE ("ACE_RW_Token::is_waiting_for");
// If there is no owner, or <id> is the owner, return false.
if ((this->owner () == 0) ||
this->is_owner (id))
return 0;
// Step through each waiter looking for <id>.
ACE_TPQ_Iterator iterator (waiters_);
iterator.advance ();
for (ACE_TPQ_Entry *temp = 0;
iterator.next (temp) != 0;
iterator.advance ())
{
if (temp->equal_client_id (id))
return 1;
}
return 0;
}
int
ACE_RW_Token::is_owner (const ACE_TCHAR *id)
{
ACE_TRACE ("ACE_RW_Token::is_owner");
// If there is no owner, return false.
if (this->owner () == 0)
return 0;
// A writer owns us.
if (this->owner ()->proxy ()->type () == ACE_RW_Token::WRITER)
return this->owner ()->equal_client_id (id);
// Readers own us.
// Step through each owning reader looking for <id>.
ACE_TPQ_Iterator iterator (waiters_);
for (ACE_TPQ_Entry *temp = 0;
iterator.next (temp) != 0;
iterator.advance ())
{
if (temp->proxy ()->type () != ACE_RW_Token::READER)
break;
if (temp->equal_client_id (id))
return 1;
}
return 0;
}
void
ACE_Token_Proxy::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_Token_Proxy::dump");
ACELIB_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Token_Proxy::dump:\n")
ACE_TEXT (" type = %d\n")
ACE_TEXT (" ignore_deadlock_ = %d\n")
ACE_TEXT (" debug_ = %d\n"),
(int) this->type (), ignore_deadlock_, debug_));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("mutex_, and waiter_\n")));
if (this->token_ != 0)
this->token_->dump ();
this->waiter_.dump ();
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Token_Proxy::dump end.\n")));
ACELIB_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
const ACE_TCHAR *
ACE_Token_Proxy::client_id (void) const
{
ACE_TRACE ("ACE_Token_Proxy::client_id");
// Thread-specific.
const ACE_TPQ_Entry *temp = this->waiter_.operator->();
const ACE_TCHAR *id = temp->client_id ();
if (id == 0)
return ACE_TEXT ("ERROR NO CLIENT ID");
else
return id;
}
void
ACE_Token_Proxy::client_id (const ACE_TCHAR *client_id)
{
ACE_TRACE ("ACE_Token_Proxy::client_id");
this->waiter_->client_id (client_id);
}
const ACE_TCHAR *
ACE_Token_Proxy::owner_id (void)
{
ACE_TRACE ("ACE_Token_Proxy::owner_id");
return this->token_->owner_id ();
}
const ACE_TCHAR *
ACE_Token_Proxy::name (void) const
{
ACE_TRACE ("ACE_Token_Proxy::name");
return this->token_->name ();
}
#if defined (ACE_WIN32_VC8)
# pragma warning (push)
# pragma warning (disable:4355) /* Use of 'this' in initializer list */
#endif
ACE_Token_Proxy::ACE_Token_Proxy (void)
: token_ (0),
waiter_ (this, 0)
{
ACE_TRACE ("ACE_Token_Proxy::ACE_Token_Proxy");
}
// Notice the token_ (0). Do *not* copy the token pointer. This must
// be obtained through the token manager. Also, we don't copy any
// waiter info. A copied Proxy does *not* inherit client_id.
ACE_Token_Proxy::ACE_Token_Proxy (const ACE_Token_Proxy &)
: token_ (0),
waiter_ (this, 0)
{
ACE_TRACE ("ACE_Token_Proxy::ACE_Token_Proxy");
}
#if defined (ACE_WIN32_VC8)
# pragma warning (pop)
#endif
// @@ should I do a mutex_->release ()?
ACE_Token_Proxy::~ACE_Token_Proxy (void)
{
ACE_TRACE ("ACE_Token_Proxy::~ACE_Token_Proxy");
if (token_ != 0)
// notify token manager that we are done with it so it can
// free it if necessary
ACE_Token_Manager::instance ()->release_token (token_);
}
int
ACE_Token_Proxy::open (const ACE_TCHAR *token_name,
int ignore_deadlock,
int debug)
{
ACE_TRACE ("ACE_Token_Proxy::open");
// Store some parameters.
this->ignore_deadlock_ = ignore_deadlock;
this->debug_ = debug;
// Used in case a name was not specified.
ACE_TCHAR name[BUFSIZ];
// We must have a name.
if (token_name == 0)
{
ACE_OS::sprintf (name, ACE_TEXT ("token %lx"),
reinterpret_cast<long> (this));
token_name = name;
}
// Get or create the underlying token. The Token Manager will call
// us back to set token_.
ACE_Token_Manager::instance ()->get_token (this, token_name);
// Check for failed get or failed new.
if (this->token_ == 0)
{
errno = ENOMEM;
ACELIB_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("Can't allocate mutex")), -1);
}
return 0;
}
int
ACE_Token_Proxy::acquire (int notify,
void (*sleep_hook)(void *),
ACE_Synch_Options &options)
{
ACE_TRACE ("ACE_Token_Proxy::acquire");
if (this->token_ == 0)
{
errno = ENOENT;
ACELIB_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("Not open.\n")), -1);
}
// Make sure no one calls our token_acquired until we have a chance
// to sleep first! If after we call an EWOULDBLOCK
// mutex_->acquire() below, but before we enter handle_options to
// wait on the cond_var, a thread tries to give take us off the
// waiter queue and signal us, IT WILL FIRST HAVE TO ACQUIRE THIS
// cond_var.mutex (). _This_ is why we acquire it.
this->waiter_->cond_var_.mutex ().acquire ();
this->waiter_->sleep_hook (sleep_hook);
if (this->token_->acquire (this->waiter_, this->ignore_deadlock_, notify) == -1)
// acquire failed
{
switch (errno)
{
case EDEADLK :
if (!ignore_deadlock_)
{
waiter_->cond_var_.mutex ().release ();
errno = EDEADLK;
ACE_RETURN (-1);
}
// Else, fallthrough and block!
case EWOULDBLOCK :
if (this->debug_)
ACELIB_DEBUG ((LM_DEBUG,
ACE_TEXT ("(%t) waiting for %s, owner is %s, ")
ACE_TEXT ("total waiters == %d\n"),
this->name (),
this->token_->owner_id (),
token_->no_of_waiters ()));
// no error, but would block, if error, return error (-1),
// otherwise, return whether we called the holder or not.
int return_value;
if (this->handle_options (options,
waiter_->cond_var_) == -1)
return_value = -1;
else
return_value = notify == 1;
errno = EWOULDBLOCK;
ACE_RETURN (return_value);
default :
waiter_->cond_var_.mutex ().release ();
ACELIB_ERROR_RETURN ((LM_ERROR,
ACE_TEXT ("%p\n"),
ACE_TEXT ("Token Proxy acquire.")),
-1);
}
}
else
// we have the token
{
if (debug_)
ACELIB_DEBUG ((LM_DEBUG,
ACE_TEXT ("(%t) acquired %s\n"),
this->name ()));
waiter_->cond_var_.mutex ().release ();
}
return 0;
}
int
ACE_Token_Proxy::tryacquire (void (*sleep_hook)(void *))
{
ACE_TRACE ("ACE_Token_Proxy::tryacquire");
if (this->token_ == 0)
{
errno = ENOENT;
ACELIB_ERROR_RETURN ((LM_ERROR,
ACE_TEXT ("Not open.\n")),
-1);
}
this->waiter_->sleep_hook (sleep_hook);
return this->token_->tryacquire (waiter_);
}
int
ACE_Token_Proxy::renew (int requeue_position,
ACE_Synch_Options &options)
{
ACE_TRACE ("ACE_Token_Proxy::renew");
if (this->token_ == 0)
{
errno = ENOENT;
ACELIB_ERROR_RETURN ((LM_ERROR,
ACE_TEXT ("Not open.\n")),
-1);
}
// Make sure no one calls our token_acquired until we have a chance
// to sleep first!
this->waiter_->cond_var_.mutex ().acquire ();
if (this->token_->renew (this->waiter_, requeue_position) == -1)
{
// check for error
if (errno != EWOULDBLOCK)
ACELIB_ERROR_RETURN ((LM_ERROR,
ACE_TEXT ("%p renew failed\n"), ACE_TEXT ("ACE_Token_Proxy")), -1);
if (this->debug_)
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) renew blocking for %s, owner is %s\n"),
this->name (),
token_->owner_id ()));
// no error, but would block, so block or return
return this->handle_options (options, waiter_->cond_var_);
}
else
// we have the token
{
if (this->debug_)
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) renewed %s\n"),
this->name ()));
waiter_->cond_var_.mutex ().release ();
return 0;
}
}
int
ACE_Token_Proxy::handle_options (ACE_Synch_Options &options,
ACE_TOKEN_CONST::COND_VAR &cv)
{
// Some operation failed with EWOULDBLOCK.
ACE_TRACE ("ACE_Token_Proxy::handle_options");
if (options[ACE_Synch_Options::USE_REACTOR] == 1)
// Asynchronous.
{
// Save/restore errno.
ACE_Errno_Guard error (errno);
cv.mutex ().release ();
ACE_RETURN (-1);
}
else
// Synchronous.
{
// Block on condition variable.
while (cv.wait ((ACE_Time_Value *) options.time_value ()) == -1)
{
// Note, this should obey whatever thread-specific
// interrupt policy is currently in place...
if (errno == EINTR)
continue;
// We come here if a timeout occurs or some serious
// ACE_Condition object error.
cv.mutex ().release ();
ACELIB_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("condition variable wait")
ACE_TEXT (" bombed.")), -1);
}
if (this->debug_)
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) unblocking %s.\n"),
this->client_id ()));
cv.mutex ().release ();
return 0; // operation succeeded
}
}
int
ACE_Token_Proxy::release (ACE_Synch_Options &)
{
ACE_TRACE ("ACE_Token_Proxy::release");
if (this->token_ == 0)
{
errno = ENOENT;
if (debug_)
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("Must open before releasing.\n")));
ACE_RETURN (-1);
}
if (this->token_->release (waiter_) != 0)
{
// Release failed.
this->token_->remove (this->waiter_);
if (debug_)
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) %p.\n"), ACE_TEXT ("release failed")));
return -1;
}
else
{
if (this->debug_)
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) released %s, owner is %s\n"),
this->name (),
token_->owner_id ()));
return 0;
}
}
int
ACE_Token_Proxy::remove (ACE_Synch_Options &)
{
ACE_TRACE ("ACE_Token_Proxy::remove");
return 0;
}
void
ACE_Token_Proxy::sleep_hook (void)
{
ACE_TRACE ("ACE_Token_Proxy::sleep_hook");
// Somebody wants our token! (Let'em wait...)
return;
}
void
ACE_Token_Proxy::token_acquired (ACE_TPQ_Entry *e)
{
ACE_TRACE ("ACE_Token_Proxy::token_acquired");
e->cond_var_.mutex ().acquire ();
// We've been taken off the waiters list and given the token!
// This implementation signals the internal condition
// variable. Thus, if asynchronous acquires are used, this must be
// overriden to do something more useful!
e->cond_var_.signal ();
e->cond_var_.mutex ().release ();
return;
}
int
ACE_Token_Proxy::type (void) const
{
ACE_TRACE ("ACE_Token_Proxy::type");
return 0;
}
int
ACE_Token_Proxy::acquire_read (int notify,
void (*sleep_hook)(void *),
ACE_Synch_Options &options)
{
return this->acquire (notify,
sleep_hook,
options);
}
int
ACE_Token_Proxy::acquire_write (int notify,
void (*sleep_hook)(void *),
ACE_Synch_Options &options)
{
return this->acquire (notify,
sleep_hook,
options);
}
int
ACE_Token_Proxy::tryacquire_read (void (*sleep_hook)(void *))
{
return this->tryacquire (sleep_hook);
}
int
ACE_Token_Proxy::tryacquire_write (void (*sleep_hook)(void *))
{
return this->tryacquire (sleep_hook);
}
ACE_Token_Name::ACE_Token_Name (const ACE_TCHAR *token_name)
{
ACE_TRACE ("ACE_Token_Name::ACE_Token_Name");
this->name (token_name);
}
ACE_Token_Name::ACE_Token_Name (const ACE_Token_Name &rhs)
{
ACE_TRACE ("ACE_Token_Name::ACE_Token_Name");
this->name (rhs.name ());
}
ACE_Token_Name::~ACE_Token_Name ()
{
ACE_TRACE ("ACE_Token_Name::~ACE_Token_Name");
}
void
ACE_Token_Name::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_Token_Name::dump");
ACELIB_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Token_Name::dump:\n")
ACE_TEXT (" token_name_ = %s\n"),
token_name_ == 0 ? ACE_TEXT ("no name") : token_name_));
ACELIB_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
// ************************************************************
ACE_Token_Proxy *
ACE_Local_Mutex::clone (void) const
{
ACE_Token_Proxy *temp = 0;
ACE_NEW_RETURN (temp,
ACE_Local_Mutex (token_->name (),
ignore_deadlock_,
debug_),
0);
return temp;
}
ACE_Tokens *
ACE_Local_Mutex::create_token (const ACE_TCHAR *name)
{
ACE_Tokens *temp = 0;
ACE_NEW_RETURN (temp,
ACE_Mutex_Token (name),
0);
return temp;
}
ACE_Local_Mutex::~ACE_Local_Mutex (void)
{
}
// ************************************************************
ACE_Local_RLock::~ACE_Local_RLock (void)
{
}
ACE_Tokens *
ACE_Local_RLock::create_token (const ACE_TCHAR *name)
{
ACE_Tokens *temp = 0;
ACE_NEW_RETURN (temp,
ACE_RW_Token (name),
0);
return temp;
}
int
ACE_Local_RLock::type (void) const
{
return ACE_RW_Token::READER;
}
ACE_Token_Proxy *
ACE_Local_RLock::clone (void) const
{
ACE_Token_Proxy *temp = 0;
ACE_NEW_RETURN (temp,
ACE_Local_RLock (token_->name (),
ignore_deadlock_,
debug_),
0);
return temp;
}
// ************************************************************
ACE_Local_WLock::~ACE_Local_WLock (void)
{
}
ACE_Tokens *
ACE_Local_WLock::create_token (const ACE_TCHAR *name)
{
ACE_Tokens *temp = 0;
ACE_NEW_RETURN (temp,
ACE_RW_Token (name),
0);
return temp;
}
int
ACE_Local_WLock::type (void) const
{
return ACE_RW_Token::WRITER;
}
ACE_Token_Proxy *
ACE_Local_WLock::clone (void) const
{
ACE_Token_Proxy *temp = 0;
ACE_NEW_RETURN (temp,
ACE_Local_WLock (token_->name (),
ignore_deadlock_,
debug_),
0);
return temp;
}
ACE_END_VERSIONED_NAMESPACE_DECL
#endif /* ACE_HAS_TOKENS_LIBRARY */
|
/**
* Copyright (C) 2016 Turi
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
#ifndef GRAPHLAB_SFRAME_QUERY_MANAGER_PROJECT_HPP
#define GRAPHLAB_SFRAME_QUERY_MANAGER_PROJECT_HPP
#include <flexible_type/flexible_type.hpp>
#include <sframe_query_engine/operators/operator.hpp>
#include <sframe_query_engine/execution/query_context.hpp>
#include <sframe_query_engine/operators/operator_properties.hpp>
namespace graphlab {
namespace query_eval {
/**
* A "project" operator will project the input source to a subset
* of indices.
*/
template <>
struct operator_impl<planner_node_type::PROJECT_NODE> : public query_operator {
public:
inline planner_node_type type() const { return planner_node_type::PROJECT_NODE; }
static std::string name() { return "project"; }
static query_operator_attributes attributes() {
query_operator_attributes ret;
ret.attribute_bitfield = query_operator_attributes::LINEAR;
ret.num_inputs = 1;
return ret;
}
inline operator_impl(const std::vector<size_t>& indices): m_indices(indices) {
ASSERT_GT(m_indices.size(), 0);
};
inline std::string print() const {
std::stringstream str_indices;
for (size_t i : m_indices) str_indices << i << " ";
return name() + "(" + str_indices.str() + ")";
}
inline std::shared_ptr<query_operator> clone() const {
return std::make_shared<operator_impl>(*this);
}
inline void execute(query_context& context) {
while (1) {
auto rows = context.get_next(0);
if (rows == nullptr)
break;
auto out = context.get_output_buffer();
auto& rows_columns = rows->cget_columns();
auto& out_columns = out->get_columns();
out_columns.clear();
for (size_t i = 0;i < m_indices.size(); ++i) {
DASSERT_LT(i, m_indices.size());
out_columns.push_back(rows_columns[m_indices[i]]);
}
context.emit(out);
}
};
static std::shared_ptr<planner_node> make_planner_node(
std::shared_ptr<planner_node> input,
const std::vector<size_t>& indices) {
DASSERT_FALSE(indices.empty());
std::vector<flexible_type> flex_indices(indices.begin(), indices.end());
#ifndef NDEBUG
size_t num_columns = infer_planner_node_num_output_columns(input);
for(size_t col_idx : indices)
DASSERT_LT(col_idx, num_columns);
#endif
return planner_node::make_shared(planner_node_type::PROJECT_NODE,
{{"indices", flex_indices}},
std::map<std::string, any>(),
{input});
}
static std::shared_ptr<query_operator> from_planner_node(
std::shared_ptr<planner_node> pnode) {
ASSERT_EQ((int)pnode->operator_type, (int)planner_node_type::PROJECT_NODE);
ASSERT_TRUE(pnode->operator_parameters.count("indices"));
auto flex_indices = pnode->operator_parameters.at("indices").get<flex_list>();
std::vector<size_t> indices(flex_indices.begin(), flex_indices.end());
return std::make_shared<operator_impl>(indices);
}
static std::vector<flex_type_enum> infer_type(
std::shared_ptr<planner_node> pnode) {
ASSERT_EQ((int)pnode->operator_type,
(int)planner_node_type::PROJECT_NODE);
auto input_type = infer_planner_node_type(pnode->inputs[0]);
auto flex_indices = pnode->operator_parameters.at("indices").get<flex_list>();
std::vector<flex_type_enum> ret;
for (auto i: flex_indices) {
ret.push_back(input_type[i.get<flex_int>()]);
}
return ret;
}
static int64_t infer_length(std::shared_ptr<planner_node> pnode) {
ASSERT_EQ((int)pnode->operator_type, (int)planner_node_type::PROJECT_NODE);
return infer_planner_node_length(pnode->inputs[0]);
}
static std::string repr(std::shared_ptr<planner_node> pnode, pnode_tagger& ) {
ASSERT_EQ((int)pnode->operator_type, (int)planner_node_type::PROJECT_NODE);
ASSERT_TRUE(pnode->operator_parameters.count("indices"));
auto flex_indices = pnode->operator_parameters["indices"].get<flex_list>();
std::ostringstream out;
out << "PR(";
if(flex_indices.size() > 0) {
// Now, make subsequent numbers the same
std::vector<std::vector<size_t> > groups{ {flex_indices[0]} };
for(size_t i = 1; i < flex_indices.size();++i) {
if(flex_indices[i] == groups.back().back() + 1)
groups.back().push_back(size_t(flex_indices[i]));
else
groups.push_back({flex_indices[i]});
}
bool is_first = true;
for(const std::vector<size_t>& grp : groups) {
if(!is_first)
out << ",";
is_first = false;
switch(grp.size()) {
case 1:
out << grp[0];
break;
case 2:
out << grp[0] << ',' << grp[1];
break;
case 3:
out << grp[0] << ',' << grp[1] << ',' << grp[2];
break;
default:
out << grp.front() << ",...," << grp.back();
break;
}
}
}
out << ')';
return out.str();
}
private:
std::vector<size_t> m_indices;
};
typedef operator_impl<planner_node_type::PROJECT_NODE> op_project;
} // query_eval
} // graphlab
#endif // GRAPHLAB_SFRAME_QUERY_MANAGER_PROJECT_HPP
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkDICOMTagsOfInterestService.h"
#include "mitkDICOMTagHelper.h"
#include "usModuleContext.h"
#include "usGetModuleContext.h"
#include "mitkIPropertyDescriptions.h"
#include "mitkIPropertyPersistence.h"
#include "mitkTemporoSpatialStringProperty.h"
mitk::IPropertyDescriptions*
GetDescriptionsService()
{
mitk::IPropertyDescriptions* result = nullptr;
std::vector<us::ServiceReference<mitk::IPropertyDescriptions> > descriptionRegisters = us::GetModuleContext()->GetServiceReferences<mitk::IPropertyDescriptions>();
if (!descriptionRegisters.empty())
{
if (descriptionRegisters.size() > 1)
{
MITK_WARN << "Multiple property description services found. Using just one.";
}
result = us::GetModuleContext()->GetService<mitk::IPropertyDescriptions>(descriptionRegisters.front());
}
return result;
};
mitk::IPropertyPersistence*
GetPersistenceService()
{
mitk::IPropertyPersistence* result = nullptr;
std::vector<us::ServiceReference<mitk::IPropertyPersistence> > persRegisters = us::GetModuleContext()->GetServiceReferences<mitk::IPropertyPersistence>();
if (!persRegisters.empty())
{
if (persRegisters.size() > 1)
{
MITK_WARN << "Multiple property description services found. Using just one.";
}
result = us::GetModuleContext()->GetService<mitk::IPropertyPersistence>(persRegisters.front());
}
return result;
};
mitk::DICOMTagsOfInterestService::
DICOMTagsOfInterestService()
{
};
mitk::DICOMTagsOfInterestService::
~DICOMTagsOfInterestService()
{
};
void
mitk::DICOMTagsOfInterestService::
AddTagOfInterest(const DICOMTag& tag, bool makePersistant)
{
MutexHolder lock(m_Lock);
std::string propName = mitk::GeneratPropertyNameForDICOMTag(tag);
this->m_TagMap.insert(std::make_pair(propName, tag));
this->m_PersMap[propName] = makePersistant; //this must be changed even if the propname already exists.
this->m_KnownTags.insert(propName);
mitk::IPropertyDescriptions* descriptionSrv = GetDescriptionsService();
if (descriptionSrv)
{
descriptionSrv->AddDescription(propName, "DICOM tag: " + tag.GetName());
}
mitk::IPropertyPersistence* persSrv = GetPersistenceService();
if (persSrv)
{
std::string key = propName;
std::replace(key.begin(), key.end(), '.', '_');
PropertyPersistenceInfo::Pointer info = PropertyPersistenceInfo::New(key);
info->SetDeserializationFunction(mitk::PropertyPersistenceDeserialization::deserializeJSONToTemporoSpatialStringProperty);
info->SetSerializationFunction(mitk::PropertyPersistenceSerialization::serializeTemporoSpatialStringPropertyToJSON);
persSrv->AddInfo(propName, info);
}
};
mitk::DICOMTagsOfInterestService::DICOMTagMapType
mitk::DICOMTagsOfInterestService::
GetTagsOfInterest() const
{
MutexHolder lock(m_Lock);
DICOMTagMapType result;
for (auto tag : this->m_TagMap)
{
InternalTagSetType::const_iterator finding = this->m_KnownTags.find(tag.first);
if (finding == this->m_KnownTags.cend())
{
mitkThrow() << "Invalid status. Tag is missing in the known tag set. Problematic tag:" << tag.first;
}
result.insert(std::make_pair(finding->c_str(), tag.second));
}
return result;
};
bool
mitk::DICOMTagsOfInterestService::
HasTag(const DICOMTag& tag) const
{
std::string propName = mitk::GeneratPropertyNameForDICOMTag(tag);
return this->m_TagMap.find(propName) != this->m_TagMap.cend();
};
void
mitk::DICOMTagsOfInterestService::
RemoveTag(const DICOMTag& tag)
{
MutexHolder lock(m_Lock);
std::string propName = mitk::GeneratPropertyNameForDICOMTag(tag);
this->m_PersMap.erase(propName);
this->m_TagMap.erase(propName);
mitk::IPropertyDescriptions* descriptionSrv = GetDescriptionsService();
if (descriptionSrv && descriptionSrv->HasDescription(propName))
{
descriptionSrv->RemoveDescription(propName);
}
mitk::IPropertyPersistence* persSrv = GetPersistenceService();
if (persSrv && persSrv->HasInfos(propName))
{
persSrv->RemoveInfos(propName);
}
};
void
mitk::DICOMTagsOfInterestService::
RemoveAllTags()
{
MutexHolder lock(m_Lock);
this->m_PersMap.clear();
this->m_TagMap.clear();
};
|
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#line 2 "src/decompile/cpp/slghscan.cc"
#line 4 "src/decompile/cpp/slghscan.cc"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 37
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/* end standard C headers. */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
#ifdef __cplusplus
/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST
#else /* ! __cplusplus */
/* C99 requires __STDC__ to be defined as 1. */
#if defined (__STDC__)
#define YY_USE_CONST
#endif /* defined (__STDC__) */
#endif /* ! __cplusplus */
#ifdef YY_USE_CONST
#define yyconst const
#else
#define yyconst
#endif
/* Returned upon end-of-file. */
#define YY_NULL 0
/* Promotes a possibly negative, possibly signed char to an unsigned
* integer for use as an array index. If the signed char is negative,
* we want to instead treat it as an 8-bit unsigned char, hence the
* double cast.
*/
#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN (yy_start) = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START (((yy_start) - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE yyrestart(yyin )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#define YY_BUF_SIZE 16384
#endif
/* The state buf must be large enough to hold one state per character in the main buffer.
*/
#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
extern yy_size_t yyleng;
extern FILE *yyin, *yyout;
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
#define YY_LESS_LINENO(n)
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
*yy_cp = (yy_hold_char); \
YY_RESTORE_YY_MORE_OFFSET \
(yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
#define unput(c) yyunput( c, (yytext_ptr) )
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
{
FILE *yy_input_file;
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
yy_size_t yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
yy_size_t yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
/* Stack of input buffers. */
static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*
* Returns the top of the stack, or NULL.
*/
#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
? (yy_buffer_stack)[(yy_buffer_stack_top)] \
: NULL)
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
/* yy_hold_char holds the character lost when yytext is formed. */
static char yy_hold_char;
static yy_size_t yy_n_chars; /* number of characters read into yy_ch_buf */
yy_size_t yyleng;
/* Points to current character in buffer. */
static char *yy_c_buf_p = (char *) 0;
static int yy_init = 0; /* whether we need to initialize */
static int yy_start = 0; /* start state number */
/* Flag which is used to allow yywrap()'s to do buffer switches
* instead of setting up a fresh yyin. A bit of a hack ...
*/
static int yy_did_buffer_switch_on_eof;
void yyrestart (FILE *input_file );
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer );
YY_BUFFER_STATE yy_create_buffer (FILE *file,int size );
void yy_delete_buffer (YY_BUFFER_STATE b );
void yy_flush_buffer (YY_BUFFER_STATE b );
void yypush_buffer_state (YY_BUFFER_STATE new_buffer );
void yypop_buffer_state (void );
static void yyensure_buffer_stack (void );
static void yy_load_buffer_state (void );
static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file );
#define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER )
YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size );
YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str );
YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,yy_size_t len );
void *yyalloc (yy_size_t );
void *yyrealloc (void *,yy_size_t );
void yyfree (void * );
#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
typedef unsigned char YY_CHAR;
FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0;
typedef int yy_state_type;
extern int yylineno;
int yylineno = 1;
extern char *yytext;
#define yytext_ptr yytext
static yy_state_type yy_get_previous_state (void );
static yy_state_type yy_try_NUL_trans (yy_state_type current_state );
static int yy_get_next_buffer (void );
static void yy_fatal_error (yyconst char msg[] );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
*/
#define YY_DO_BEFORE_ACTION \
(yytext_ptr) = yy_bp; \
yyleng = (size_t) (yy_cp - yy_bp); \
(yy_hold_char) = *yy_cp; \
*yy_cp = '\0'; \
(yy_c_buf_p) = yy_cp;
#define YY_NUM_RULES 164
#define YY_END_OF_BUFFER 165
/* This struct is not used in this scanner,
but its presence is necessary. */
struct yy_trans_info
{
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
static yyconst flex_int16_t yy_accept[527] =
{ 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 165, 14, 7, 8, 6, 14,
3, 13, 4, 13, 13, 13, 13, 5, 1, 58,
56, 57, 58, 50, 58, 25, 51, 52, 52, 26,
51, 51, 51, 51, 51, 51, 51, 51, 51, 51,
51, 51, 51, 51, 51, 23, 22, 20, 21, 22,
17, 19, 18, 15, 68, 66, 67, 61, 68, 61,
64, 62, 64, 59, 96, 94, 95, 96, 89, 96,
85, 88, 90, 91, 91, 88, 88, 90, 83, 84,
87, 90, 90, 71, 86, 69, 161, 159, 160, 153,
154, 161, 153, 153, 155, 156, 156, 153, 153, 153,
153, 155, 155, 155, 155, 155, 155, 155, 155, 155,
155, 155, 155, 155, 155, 155, 153, 99, 97, 164,
164, 163, 162, 7, 6, 0, 13, 13, 13, 13,
13, 1, 1, 56, 0, 55, 50, 0, 51, 0,
0, 52, 51, 51, 51, 51, 51, 51, 51, 51,
51, 51, 51, 51, 51, 51, 51, 51, 51, 51,
51, 23, 23, 20, 0, 19, 15, 15, 66, 0,
65, 0, 64, 63, 59, 59, 94, 76, 89, 0,
0, 0, 0, 90, 90, 0, 0, 91, 75, 77,
78, 74, 90, 90, 69, 69, 159, 106, 154, 0,
101, 155, 0, 0, 156, 104, 107, 105, 108, 103,
102, 155, 155, 155, 155, 155, 155, 155, 155, 155,
0, 118, 116, 117, 119, 122, 0, 123, 155, 155,
144, 155, 155, 155, 155, 155, 155, 155, 110, 109,
112, 113, 155, 155, 155, 155, 155, 155, 100, 97,
97, 0, 163, 162, 162, 0, 13, 13, 13, 13,
0, 54, 53, 51, 41, 51, 51, 38, 51, 51,
37, 51, 51, 51, 51, 51, 51, 51, 51, 51,
51, 51, 51, 51, 51, 51, 0, 0, 0, 0,
80, 0, 82, 93, 92, 90, 90, 0, 158, 157,
133, 155, 155, 155, 155, 155, 155, 155, 155, 155,
121, 124, 120, 125, 155, 155, 155, 155, 132, 155,
155, 155, 155, 114, 115, 111, 155, 155, 155, 155,
155, 155, 2, 0, 13, 13, 13, 12, 24, 0,
51, 51, 51, 51, 51, 51, 51, 51, 51, 51,
51, 51, 51, 43, 51, 51, 28, 51, 51, 51,
16, 0, 60, 0, 70, 0, 79, 81, 90, 90,
98, 0, 155, 155, 146, 155, 135, 155, 155, 155,
155, 155, 155, 145, 155, 155, 155, 155, 155, 155,
155, 155, 129, 134, 155, 126, 13, 13, 9, 51,
51, 51, 51, 51, 51, 46, 51, 51, 51, 51,
51, 51, 27, 32, 51, 51, 51, 90, 90, 155,
151, 127, 141, 155, 155, 155, 155, 136, 155, 152,
155, 155, 155, 137, 155, 155, 140, 11, 10, 51,
51, 51, 51, 39, 42, 36, 45, 51, 51, 51,
35, 47, 51, 51, 90, 72, 128, 155, 155, 150,
155, 155, 155, 155, 147, 155, 130, 51, 51, 33,
30, 49, 51, 51, 51, 51, 90, 155, 155, 155,
155, 155, 155, 131, 51, 34, 51, 51, 51, 44,
90, 155, 155, 155, 155, 155, 143, 40, 29, 51,
48, 73, 155, 148, 155, 138, 142, 51, 149, 155,
51, 139, 51, 51, 31, 0
} ;
static yyconst flex_int32_t yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
2, 1, 2, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 2, 4, 5, 6, 7, 8, 9, 1, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 21, 21, 21, 21, 21, 21, 22, 23, 24,
25, 26, 27, 28, 29, 29, 29, 29, 29, 29,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
31, 1, 32, 33, 34, 1, 35, 36, 37, 38,
39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, 52, 53, 54, 55, 56, 57, 58,
59, 60, 61, 62, 63, 64, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1
} ;
static yyconst flex_int32_t yy_meta[65] =
{ 0,
1, 1, 2, 1, 1, 1, 1, 1, 1, 1,
3, 1, 1, 1, 1, 4, 1, 5, 5, 5,
5, 1, 1, 1, 1, 1, 1, 1, 5, 4,
1, 1, 1, 4, 5, 5, 5, 5, 5, 5,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
1, 1, 1, 1
} ;
static yyconst flex_int16_t yy_base[564] =
{ 0,
0, 897, 64, 896, 128, 895, 192, 894, 256, 893,
320, 892, 0, 382, 919, 926, 916, 926, 0, 907,
926, 0, 926, 862, 876, 879, 870, 926, 909, 926,
909, 926, 905, 0, 899, 926, 0, 350, 369, 926,
862, 864, 857, 866, 856, 864, 859, 356, 861, 863,
357, 350, 345, 864, 849, 894, 926, 894, 926, 885,
926, 0, 926, 891, 926, 891, 926, 926, 887, 881,
0, 926, 837, 886, 926, 886, 926, 862, 0, 385,
926, 926, 870, 361, 393, 374, 376, 0, 926, 926,
926, 839, 836, 926, 926, 880, 926, 880, 926, 856,
0, 870, 926, 870, 0, 367, 397, 382, 853, 396,
844, 840, 374, 389, 836, 816, 423, 824, 397, 823,
391, 822, 393, 436, 818, 830, 806, 926, 864, 926,
863, 926, 862, 862, 0, 0, 0, 809, 822, 824,
806, 856, 926, 856, 852, 851, 0, 0, 0, 432,
0, 436, 812, 392, 806, 421, 815, 794, 797, 803,
809, 808, 798, 799, 804, 411, 809, 798, 792, 413,
789, 837, 926, 837, 0, 0, 835, 926, 835, 831,
830, 0, 0, 0, 831, 926, 831, 926, 0, 0,
784, 779, 781, 813, 0, 445, 0, 458, 926, 926,
926, 926, 779, 784, 823, 926, 823, 926, 0, 0,
926, 0, 448, 0, 462, 926, 926, 926, 926, 926,
926, 771, 771, 779, 422, 778, 771, 770, 772, 767,
791, 926, 926, 926, 926, 790, 789, 788, 763, 757,
0, 756, 772, 760, 750, 756, 751, 749, 926, 926,
778, 459, 753, 766, 742, 747, 743, 739, 926, 793,
926, 792, 926, 791, 926, 782, 757, 748, 738, 747,
777, 470, 0, 746, 0, 734, 731, 0, 749, 740,
0, 728, 742, 734, 726, 740, 743, 733, 727, 735,
736, 733, 732, 715, 726, 730, 756, 755, 754, 726,
926, 711, 0, 472, 0, 726, 714, 749, 474, 0,
0, 707, 712, 711, 704, 709, 705, 700, 717, 702,
926, 926, 926, 926, 451, 701, 729, 713, 0, 698,
709, 690, 696, 926, 926, 926, 691, 690, 687, 686,
691, 684, 926, 726, 699, 687, 685, 0, 926, 722,
684, 696, 691, 674, 693, 681, 673, 676, 685, 684,
669, 668, 681, 0, 680, 670, 0, 678, 681, 662,
926, 703, 926, 702, 926, 701, 926, 926, 676, 660,
926, 698, 659, 669, 0, 647, 0, 659, 651, 644,
650, 647, 648, 0, 659, 652, 661, 647, 643, 656,
641, 640, 0, 0, 654, 0, 648, 650, 0, 641,
639, 628, 639, 636, 644, 0, 625, 627, 631, 629,
624, 639, 0, 0, 623, 639, 631, 627, 626, 614,
0, 0, 0, 634, 616, 614, 647, 0, 620, 0,
621, 609, 615, 0, 613, 602, 0, 0, 0, 621,
618, 604, 603, 0, 0, 0, 0, 606, 620, 615,
0, 0, 607, 592, 598, 0, 0, 595, 603, 0,
608, 598, 607, 597, 0, 587, 0, 595, 603, 0,
0, 0, 604, 588, 600, 599, 598, 593, 586, 588,
598, 595, 577, 0, 576, 0, 590, 594, 574, 0,
572, 579, 570, 574, 518, 506, 0, 0, 0, 476,
0, 0, 474, 0, 464, 0, 0, 448, 0, 443,
461, 0, 458, 455, 0, 926, 500, 505, 510, 512,
517, 522, 527, 529, 534, 536, 541, 546, 548, 553,
558, 560, 565, 570, 572, 577, 582, 587, 589, 591,
465, 593, 595, 597, 426, 599, 404, 602, 605, 608,
611, 614, 617
} ;
static yyconst flex_int16_t yy_def[564] =
{ 0,
526, 1, 526, 3, 526, 5, 526, 7, 526, 9,
526, 11, 527, 528, 526, 526, 526, 526, 529, 526,
526, 530, 526, 530, 530, 530, 530, 526, 531, 526,
526, 526, 532, 533, 526, 526, 534, 526, 526, 526,
534, 534, 534, 534, 534, 534, 534, 534, 534, 534,
534, 534, 534, 534, 534, 535, 526, 526, 526, 526,
526, 536, 526, 537, 526, 526, 526, 526, 538, 526,
539, 526, 539, 540, 526, 526, 526, 526, 541, 526,
526, 526, 542, 526, 526, 526, 526, 542, 526, 526,
526, 542, 542, 526, 526, 543, 526, 526, 526, 526,
544, 526, 526, 526, 545, 526, 526, 526, 526, 526,
526, 545, 545, 545, 545, 545, 545, 545, 545, 545,
545, 545, 545, 545, 545, 545, 526, 526, 546, 526,
547, 526, 548, 526, 529, 549, 530, 530, 530, 530,
530, 531, 526, 526, 532, 526, 533, 550, 534, 526,
551, 526, 534, 534, 534, 534, 534, 534, 534, 534,
534, 534, 534, 534, 534, 534, 534, 534, 534, 534,
534, 535, 526, 526, 552, 536, 537, 526, 526, 538,
526, 553, 539, 539, 540, 526, 526, 526, 541, 554,
526, 526, 526, 542, 542, 526, 555, 526, 526, 526,
526, 526, 542, 542, 543, 526, 526, 526, 544, 556,
526, 545, 526, 557, 526, 526, 526, 526, 526, 526,
526, 545, 545, 545, 545, 545, 545, 545, 545, 545,
526, 526, 526, 526, 526, 526, 526, 526, 545, 545,
545, 545, 545, 545, 545, 545, 545, 545, 526, 526,
526, 526, 545, 545, 545, 545, 545, 545, 526, 546,
526, 547, 526, 548, 526, 558, 530, 530, 530, 530,
559, 526, 551, 534, 534, 534, 534, 534, 534, 534,
534, 534, 534, 534, 534, 534, 534, 534, 534, 534,
534, 534, 534, 534, 534, 534, 560, 561, 562, 526,
526, 526, 542, 526, 555, 542, 542, 563, 526, 557,
545, 545, 545, 545, 545, 545, 545, 545, 545, 545,
526, 526, 526, 526, 545, 545, 545, 545, 545, 545,
545, 545, 545, 526, 526, 526, 545, 545, 545, 545,
545, 545, 526, 558, 530, 530, 530, 530, 526, 559,
534, 534, 534, 534, 534, 534, 534, 534, 534, 534,
534, 534, 534, 534, 534, 534, 534, 534, 534, 534,
526, 560, 526, 561, 526, 562, 526, 526, 542, 542,
526, 563, 545, 545, 545, 545, 545, 545, 545, 545,
545, 545, 545, 545, 545, 545, 545, 545, 545, 545,
545, 545, 545, 545, 545, 545, 530, 530, 530, 534,
534, 534, 534, 534, 534, 534, 534, 534, 534, 534,
534, 534, 534, 534, 534, 534, 534, 542, 542, 545,
545, 545, 545, 545, 545, 545, 545, 545, 545, 545,
545, 545, 545, 545, 545, 545, 545, 530, 530, 534,
534, 534, 534, 534, 534, 534, 534, 534, 534, 534,
534, 534, 534, 534, 542, 542, 545, 545, 545, 545,
545, 545, 545, 545, 545, 545, 545, 534, 534, 534,
534, 534, 534, 534, 534, 534, 542, 545, 545, 545,
545, 545, 545, 545, 534, 534, 534, 534, 534, 534,
542, 545, 545, 545, 545, 545, 545, 534, 534, 534,
534, 542, 545, 545, 545, 545, 545, 534, 545, 545,
534, 545, 534, 534, 534, 0, 526, 526, 526, 526,
526, 526, 526, 526, 526, 526, 526, 526, 526, 526,
526, 526, 526, 526, 526, 526, 526, 526, 526, 526,
526, 526, 526, 526, 526, 526, 526, 526, 526, 526,
526, 526, 526
} ;
static yyconst flex_int16_t yy_nxt[991] =
{ 0,
16, 17, 18, 16, 16, 19, 20, 16, 16, 21,
21, 16, 16, 21, 21, 22, 16, 16, 16, 16,
16, 23, 16, 16, 16, 16, 16, 16, 22, 22,
16, 16, 16, 22, 24, 22, 22, 25, 22, 22,
22, 22, 22, 22, 22, 22, 26, 22, 22, 22,
22, 22, 22, 22, 22, 22, 27, 22, 22, 22,
28, 16, 16, 16, 30, 31, 32, 30, 33, 34,
35, 30, 30, 36, 36, 30, 30, 36, 30, 37,
30, 38, 39, 39, 39, 36, 40, 30, 36, 30,
30, 30, 37, 37, 36, 36, 30, 37, 41, 42,
43, 44, 45, 37, 37, 46, 37, 37, 37, 47,
37, 48, 49, 50, 37, 51, 52, 53, 37, 54,
55, 37, 37, 37, 30, 30, 30, 30, 57, 58,
59, 57, 57, 57, 60, 57, 57, 61, 61, 57,
57, 61, 57, 62, 57, 57, 57, 57, 57, 57,
57, 57, 57, 57, 57, 57, 62, 62, 57, 57,
57, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 63, 57,
57, 57, 65, 66, 67, 68, 69, 68, 70, 68,
68, 68, 68, 68, 68, 68, 68, 71, 68, 68,
68, 68, 68, 68, 68, 68, 68, 68, 68, 68,
71, 71, 68, 68, 72, 71, 71, 71, 71, 71,
71, 71, 71, 71, 73, 71, 71, 71, 71, 71,
71, 71, 71, 71, 71, 71, 71, 71, 71, 71,
71, 71, 68, 68, 68, 68, 75, 76, 77, 78,
75, 79, 80, 75, 81, 82, 82, 82, 82, 82,
82, 83, 82, 84, 85, 85, 85, 82, 82, 86,
82, 87, 75, 75, 88, 88, 89, 90, 91, 88,
88, 88, 88, 88, 88, 88, 92, 88, 88, 88,
88, 88, 88, 88, 88, 88, 88, 88, 88, 88,
93, 88, 88, 88, 88, 88, 94, 95, 75, 82,
97, 98, 99, 100, 97, 101, 102, 103, 104, 103,
103, 103, 103, 103, 103, 105, 103, 106, 107, 107,
107, 103, 103, 108, 109, 110, 97, 97, 105, 105,
103, 103, 111, 105, 112, 113, 114, 115, 116, 117,
118, 105, 119, 105, 105, 120, 105, 121, 105, 122,
105, 123, 124, 125, 105, 105, 105, 105, 105, 126,
97, 127, 128, 103, 132, 150, 152, 152, 152, 152,
160, 164, 166, 168, 190, 165, 196, 199, 200, 167,
201, 202, 213, 169, 161, 216, 217, 151, 310, 133,
198, 198, 198, 198, 215, 215, 215, 215, 197, 191,
219, 220, 223, 225, 214, 244, 231, 226, 224, 245,
305, 247, 275, 192, 232, 233, 241, 234, 227, 235,
228, 248, 193, 249, 242, 276, 236, 237, 238, 272,
272, 289, 250, 152, 152, 152, 152, 278, 294, 251,
279, 252, 304, 304, 295, 309, 309, 314, 239, 273,
290, 253, 254, 315, 255, 198, 198, 198, 198, 215,
215, 215, 215, 335, 336, 392, 256, 272, 272, 304,
304, 309, 309, 525, 524, 523, 522, 521, 520, 393,
130, 130, 130, 130, 130, 131, 131, 131, 131, 131,
135, 519, 135, 135, 135, 137, 137, 142, 142, 142,
142, 142, 145, 145, 145, 145, 145, 147, 518, 147,
147, 147, 149, 149, 172, 172, 172, 172, 172, 176,
176, 177, 177, 177, 177, 177, 180, 180, 180, 180,
180, 183, 183, 185, 185, 185, 185, 185, 189, 517,
189, 189, 189, 195, 195, 205, 205, 205, 205, 205,
209, 516, 209, 209, 209, 212, 212, 260, 260, 260,
260, 260, 262, 262, 262, 262, 262, 264, 264, 264,
264, 264, 266, 266, 271, 271, 297, 297, 298, 298,
299, 299, 308, 308, 344, 344, 344, 350, 350, 350,
372, 372, 372, 374, 374, 374, 376, 376, 376, 382,
382, 382, 515, 514, 513, 512, 511, 510, 509, 508,
507, 506, 505, 504, 503, 502, 501, 500, 499, 498,
497, 496, 495, 494, 493, 492, 491, 490, 489, 488,
487, 486, 485, 484, 483, 482, 481, 480, 479, 478,
477, 476, 475, 474, 473, 472, 471, 470, 469, 468,
467, 466, 465, 464, 463, 462, 461, 460, 459, 458,
457, 456, 455, 454, 453, 452, 451, 450, 449, 448,
447, 446, 445, 444, 443, 442, 441, 440, 439, 438,
437, 436, 435, 434, 433, 432, 431, 430, 381, 429,
428, 375, 373, 371, 427, 426, 425, 424, 423, 422,
421, 420, 419, 418, 417, 416, 415, 414, 413, 412,
411, 410, 349, 409, 408, 407, 343, 406, 405, 404,
403, 402, 401, 400, 399, 398, 397, 396, 395, 394,
391, 390, 389, 388, 387, 386, 385, 384, 383, 381,
380, 379, 378, 377, 375, 373, 371, 370, 369, 368,
367, 366, 365, 364, 363, 362, 361, 360, 359, 358,
357, 356, 355, 354, 353, 352, 351, 349, 348, 347,
346, 345, 343, 265, 263, 261, 342, 341, 340, 339,
338, 337, 334, 333, 332, 331, 330, 329, 328, 327,
326, 325, 324, 323, 322, 321, 320, 319, 318, 317,
316, 313, 312, 311, 207, 206, 307, 306, 303, 302,
301, 300, 187, 186, 180, 181, 179, 178, 174, 173,
296, 293, 292, 291, 288, 287, 286, 285, 284, 283,
282, 281, 280, 277, 274, 145, 146, 144, 143, 270,
269, 268, 267, 134, 265, 263, 261, 259, 258, 257,
246, 243, 240, 230, 229, 222, 221, 218, 211, 210,
208, 207, 206, 204, 203, 194, 188, 187, 186, 184,
182, 181, 179, 178, 175, 174, 173, 171, 170, 163,
162, 159, 158, 157, 156, 155, 154, 153, 148, 146,
144, 143, 141, 140, 139, 138, 136, 134, 526, 129,
96, 74, 64, 56, 29, 15, 526, 526, 526, 526,
526, 526, 526, 526, 526, 526, 526, 526, 526, 526,
526, 526, 526, 526, 526, 526, 526, 526, 526, 526,
526, 526, 526, 526, 526, 526, 526, 526, 526, 526,
526, 526, 526, 526, 526, 526, 526, 526, 526, 526,
526, 526, 526, 526, 526, 526, 526, 526, 526, 526,
526, 526, 526, 526, 526, 526, 526, 526, 526, 526
} ;
static yyconst flex_int16_t yy_chk[991] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 14, 38, 39, 39, 39, 39,
48, 51, 52, 53, 80, 51, 84, 86, 86, 52,
87, 87, 106, 53, 48, 108, 108, 38, 557, 14,
85, 85, 85, 85, 107, 107, 107, 107, 84, 80,
110, 110, 113, 114, 106, 121, 117, 114, 113, 121,
555, 123, 154, 80, 117, 117, 119, 117, 114, 117,
114, 123, 80, 124, 119, 154, 117, 117, 117, 150,
150, 166, 124, 152, 152, 152, 152, 156, 170, 124,
156, 124, 196, 196, 170, 213, 213, 225, 117, 551,
166, 124, 124, 225, 124, 198, 198, 198, 198, 215,
215, 215, 215, 252, 252, 325, 124, 272, 272, 304,
304, 309, 309, 524, 523, 521, 520, 518, 515, 325,
527, 527, 527, 527, 527, 528, 528, 528, 528, 528,
529, 513, 529, 529, 529, 530, 530, 531, 531, 531,
531, 531, 532, 532, 532, 532, 532, 533, 510, 533,
533, 533, 534, 534, 535, 535, 535, 535, 535, 536,
536, 537, 537, 537, 537, 537, 538, 538, 538, 538,
538, 539, 539, 540, 540, 540, 540, 540, 541, 506,
541, 541, 541, 542, 542, 543, 543, 543, 543, 543,
544, 505, 544, 544, 544, 545, 545, 546, 546, 546,
546, 546, 547, 547, 547, 547, 547, 548, 548, 548,
548, 548, 549, 549, 550, 550, 552, 552, 553, 553,
554, 554, 556, 556, 558, 558, 558, 559, 559, 559,
560, 560, 560, 561, 561, 561, 562, 562, 562, 563,
563, 563, 504, 503, 502, 501, 499, 498, 497, 495,
493, 492, 491, 490, 489, 488, 487, 486, 485, 484,
483, 479, 478, 476, 474, 473, 472, 471, 469, 468,
465, 464, 463, 460, 459, 458, 453, 452, 451, 450,
446, 445, 443, 442, 441, 439, 437, 436, 435, 434,
430, 429, 428, 427, 426, 425, 422, 421, 420, 419,
418, 417, 415, 414, 413, 412, 411, 410, 408, 407,
405, 402, 401, 400, 399, 398, 397, 396, 395, 393,
392, 391, 390, 389, 388, 386, 384, 383, 382, 380,
379, 376, 374, 372, 370, 369, 368, 366, 365, 363,
362, 361, 360, 359, 358, 357, 356, 355, 354, 353,
352, 351, 350, 347, 346, 345, 344, 342, 341, 340,
339, 338, 337, 333, 332, 331, 330, 328, 327, 326,
320, 319, 318, 317, 316, 315, 314, 313, 312, 308,
307, 306, 302, 300, 299, 298, 297, 296, 295, 294,
293, 292, 291, 290, 289, 288, 287, 286, 285, 284,
283, 282, 280, 279, 277, 276, 274, 271, 270, 269,
268, 267, 266, 264, 262, 260, 258, 257, 256, 255,
254, 253, 251, 248, 247, 246, 245, 244, 243, 242,
240, 239, 238, 237, 236, 231, 230, 229, 228, 227,
226, 224, 223, 222, 207, 205, 204, 203, 194, 193,
192, 191, 187, 185, 181, 180, 179, 177, 174, 172,
171, 169, 168, 167, 165, 164, 163, 162, 161, 160,
159, 158, 157, 155, 153, 146, 145, 144, 142, 141,
140, 139, 138, 134, 133, 131, 129, 127, 126, 125,
122, 120, 118, 116, 115, 112, 111, 109, 104, 102,
100, 98, 96, 93, 92, 83, 78, 76, 74, 73,
70, 69, 66, 64, 60, 58, 56, 55, 54, 50,
49, 47, 46, 45, 44, 43, 42, 41, 35, 33,
31, 29, 27, 26, 25, 24, 20, 17, 15, 12,
10, 8, 6, 4, 2, 526, 526, 526, 526, 526,
526, 526, 526, 526, 526, 526, 526, 526, 526, 526,
526, 526, 526, 526, 526, 526, 526, 526, 526, 526,
526, 526, 526, 526, 526, 526, 526, 526, 526, 526,
526, 526, 526, 526, 526, 526, 526, 526, 526, 526,
526, 526, 526, 526, 526, 526, 526, 526, 526, 526,
526, 526, 526, 526, 526, 526, 526, 526, 526, 526
} ;
static yy_state_type yy_last_accepting_state;
static char *yy_last_accepting_cpos;
extern int yy_flex_debug;
int yy_flex_debug = 0;
/* The intent behind this definition is that it'll catch
* any uses of REJECT which flex missed.
*/
#define REJECT reject_used_but_not_detected
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
char *yytext;
#line 1 "src/decompile/cpp/slghscan.l"
/* ###
* IP: GHIDRA
* NOTE: flex skeletons are NOT bound by flex's BSD license
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#line 18 "src/decompile/cpp/slghscan.l"
#include "slgh_compile.hh"
#include "slghparse.hh"
#define yywrap() 1
#define YY_SKIP_YYWRAP
/* If we are building don't include unistd.h */
/* flex provides us with this macro for turning it off */
#ifdef _WIN32
#define YY_NO_UNISTD_H
static int isatty (int fildes) { return 0; }
#endif
struct FileStreamState {
YY_BUFFER_STATE lastbuffer; // Last lex buffer corresponding to the stream
FILE *file; // The NEW file stream
};
extern SleighCompile *slgh;
int4 last_preproc; // lex state before last preprocessing erasure
int4 actionon; // whether '&' '|' and '^' are treated as actionon in pattern section
int4 withsection = 0; // whether we are between the 'with' keyword and its open brace '{'
vector<FileStreamState> filebuffers;
vector<int4> ifstack;
int4 negative_if = -1;
void preproc_error(const string &err)
{
slgh->reportError((const Location *)0, err);
cerr << "Terminating due to error in preprocessing" << endl;
exit(1);
}
void check_to_endofline(istream &s)
{ // Make sure there is nothing to the end of the line
s >> ws;
if (!s.eof())
if (s.peek() != '#')
preproc_error("Extra characters in preprocessor directive");
}
string read_identifier(istream &s)
{ // Read a proper identifier from the stream
s >> ws; // Skip any whitespace
string res;
while(!s.eof()) {
char tok = s.peek();
if (isalnum(tok) || (tok == '_')) {
s >> tok;
res += tok;
}
else
break;
}
return res;
}
void preprocess_string(istream &s,string &res)
{ // Grab string surrounded by double quotes from stream or call preprocess_error
int4 val;
s >> ws; // Skip any whitespace
val = s.get();
if (val != '\"')
preproc_error("Expecting double quoted string");
val = s.get();
while((val != '\"')&&(val>=0)) {
res += (char)val;
val = s.get();
}
if (val != '\"')
preproc_error("Missing terminating double quote");
}
extern int4 preprocess_if(istream &s); // Forward declaration for recursion
int4 read_defined_operator(istream &s)
{ // We have seen a -defined- keyword in an if or elif
// Read macro name used as input, return 1 if it is defined
char tok = ' ';
string macroname;
s >> ws >> tok;
if (tok != '(')
preproc_error("Badly formed \"defined\" operator");
macroname = read_identifier(s);
int4 res = slgh->getPreprocValue(macroname,macroname) ? 1 : 0;
s >> ws >> tok;
if (tok != ')')
preproc_error("Badly formed \"defined\" operator");
return res;
}
int4 read_boolean_clause(istream &s)
{ // We have seen an if or elif
// return 1 if condition is true or else 0
s >> ws;
if (s.peek()=='(') { // Parenthetical expression spawns recursion
int4 val = s.get();
int4 res = preprocess_if(s);
s >> ws;
val = s.get();
if (val != ')')
preproc_error("Unbalanced parentheses");
return res;
}
// Otherwise we must have a normal comparison operator
string lhs,rhs,comp;
if (s.peek()=='\"') // Read left-hand side string
preprocess_string(s,lhs);
else {
lhs = read_identifier(s);
if (lhs == "defined")
return read_defined_operator(s);
if (!slgh->getPreprocValue(lhs,lhs))
preproc_error("Could not find preprocessor macro "+lhs);
}
char tok;
s >> tok; // Read comparison symbol
comp += tok;
s >> tok;
comp += tok;
s >> ws;
if (s.peek()=='\"') // Read right-hand side string
preprocess_string(s,rhs);
else {
rhs = read_identifier(s);
if (!slgh->getPreprocValue(rhs,rhs))
preproc_error("Could not find preprocessor macro "+rhs);
}
if (comp == "==")
return (lhs == rhs) ? 1 : 0;
else if (comp=="!=")
return (lhs != rhs) ? 1 : 0;
else
preproc_error("Syntax error in condition");
return 0;
}
int4 preprocess_if(istream &s)
{
int4 res = read_boolean_clause(s);
s >> ws;
while((!s.eof())&&(s.peek()!=')')) {
string boolop;
char tok;
s >> tok;
boolop += tok;
s >> tok;
boolop += tok;
int4 res2 = read_boolean_clause(s);
if (boolop == "&&")
res = res & res2;
else if (boolop == "||")
res = res | res2;
else if (boolop == "^^")
res = res ^ res2;
else
preproc_error("Syntax error in expression");
s >> ws;
}
return res;
}
void expand_preprocmacros(string &str)
{
string::size_type pos;
string::size_type lastpos = 0;
pos = str.find("$(",lastpos);
if (pos == string::npos)
return;
string res;
for(;;) {
if (pos == string::npos) {
res += str.substr(lastpos);
str = res;
return;
}
else {
res += str.substr(lastpos,(pos-lastpos));
string::size_type endpos = str.find(')',pos+2);
if (endpos == string::npos) {
preproc_error("Unterminated macro in string");
break;
}
string macro = str.substr(pos+2, endpos - (pos+2));
string value;
if (!slgh->getPreprocValue(macro,value)) {
preproc_error("Unknown preprocessing macro "+macro);
break;
}
res += value;
lastpos = endpos + 1;
}
pos = str.find("$(",lastpos);
}
}
int4 preprocess(int4 cur_state,int4 blank_state)
{
string str(yytext);
string::size_type pos = str.find('#');
if (pos != string::npos)
str.erase(pos);
istringstream s(str);
string type;
if (cur_state != blank_state)
last_preproc = cur_state;
s.get(); // Skip the preprocessor marker
s >> type;
if (type == "include") {
if (negative_if == -1) { // Not in the middle of a false if clause
filebuffers.push_back(FileStreamState()); // Save state of current file
filebuffers.back().lastbuffer = YY_CURRENT_BUFFER;
filebuffers.back().file = (FILE *)0;
s >> ws;
string fname;
preprocess_string(s,fname);
expand_preprocmacros(fname);
slgh->parseFromNewFile(fname);
fname = slgh->grabCurrentFilePath();
yyin = fopen(fname.c_str(),"r");
if (yyin == (FILE *)0)
preproc_error("Could not open included file "+fname);
filebuffers.back().file = yyin;
yy_switch_to_buffer(yy_create_buffer(yyin,YY_BUF_SIZE) );
check_to_endofline(s);
}
}
else if (type == "define") {
if (negative_if == -1) {
string varname;
string value;
varname = read_identifier(s); // Get name of variable being defined
s >> ws;
if (s.peek() == '\"')
preprocess_string(s,value);
else
value = read_identifier(s);
if (varname.size()==0)
preproc_error("Error in preprocessor definition");
slgh->setPreprocValue(varname,value);
check_to_endofline(s);
}
}
else if (type == "undef") {
if (negative_if == -1) {
string varname;
varname = read_identifier(s); // Name of variable to undefine
if (varname.size()==0)
preproc_error("Error in preprocessor undef");
slgh->undefinePreprocValue(varname);
check_to_endofline(s);
}
}
else if (type=="ifdef") {
string varname;
varname = read_identifier(s);
if (varname.size()==0)
preproc_error("Error in preprocessor ifdef");
string value;
int4 truth = (slgh->getPreprocValue(varname,value)) ? 1 : 0;
ifstack.push_back(truth);
check_to_endofline(s);
}
else if (type=="ifndef") {
string varname;
varname = read_identifier(s);
if (varname.size()==0)
preproc_error("Error in preprocessor ifndef");
string value;
int4 truth = (slgh->getPreprocValue(varname,value)) ? 0 : 1; // flipped from ifdef
ifstack.push_back(truth);
check_to_endofline(s);
}
else if (type=="if") {
int4 truth = preprocess_if(s);
if (!s.eof())
preproc_error("Unbalanced parentheses");
ifstack.push_back(truth);
}
else if (type=="elif") {
if (ifstack.empty())
preproc_error("elif without preceding if");
if ((ifstack.back()&2)!=0) // We have already seen an else clause
preproc_error("elif follows else");
if ((ifstack.back()&4)!=0) // We have already seen a true elif clause
ifstack.back() = 4; // don't include any other elif clause
else if ((ifstack.back()&1)!=0) // Last clause was a true if
ifstack.back() = 4; // don't include this elif
else {
int4 truth = preprocess_if(s);
if (!s.eof())
preproc_error("Unbalanced parentheses");
if (truth==0)
ifstack.back() = 0;
else
ifstack.back() = 5;
}
}
else if (type=="endif") {
if (ifstack.empty())
preproc_error("preprocessing endif without matching if");
ifstack.pop_back();
check_to_endofline(s);
}
else if (type=="else") {
if (ifstack.empty())
preproc_error("preprocessing else without matching if");
if ((ifstack.back()&2)!=0)
preproc_error("second else for one if");
if ((ifstack.back()&4)!=0) // Seen a true elif clause before
ifstack.back() = 6;
else if (ifstack.back()==0)
ifstack.back() = 3;
else
ifstack.back() = 2;
check_to_endofline(s);
}
else
preproc_error("Unknown preprocessing directive: "+type);
if (negative_if >= 0) { // We were in a false state
if (negative_if+1 < ifstack.size())
return blank_state; // false state is still deep in stack
else // false state is popped off or is current and changed
negative_if = -1;
}
if (ifstack.empty()) return last_preproc;
if ((ifstack.back()&1)==0) {
negative_if = ifstack.size()-1;
return blank_state;
}
return last_preproc;
}
void preproc_macroexpand(void)
{
filebuffers.push_back(FileStreamState());
filebuffers.back().lastbuffer = YY_CURRENT_BUFFER;
filebuffers.back().file = (FILE *)0;
string macro(yytext);
macro.erase(0,2);
macro.erase(macro.size()-1,1);
string value;
if (!slgh->getPreprocValue(macro,value))
preproc_error("Unknown preprocessing macro "+macro);
yy_switch_to_buffer(yy_scan_string(value.c_str() ) );
slgh->parsePreprocMacro();
}
int4 find_symbol(void) {
string * newstring = new string(yytext);
SleighSymbol *sym = slgh->findSymbol(*newstring);
if (sym == (SleighSymbol *)0) {
yylval.str = newstring;
return STRING;
}
delete newstring;
switch(sym->getType()) {
case SleighSymbol::section_symbol:
yylval.sectionsym = (SectionSymbol *)sym;
return SECTIONSYM;
case SleighSymbol::space_symbol:
yylval.spacesym = (SpaceSymbol *)sym;
return SPACESYM;
case SleighSymbol::token_symbol:
yylval.tokensym = (TokenSymbol *)sym;
return TOKENSYM;
case SleighSymbol::userop_symbol:
yylval.useropsym = (UserOpSymbol *)sym;
return USEROPSYM;
case SleighSymbol::value_symbol:
yylval.valuesym = (ValueSymbol *)sym;
return VALUESYM;
case SleighSymbol::valuemap_symbol:
yylval.valuemapsym = (ValueMapSymbol *)sym;
return VALUEMAPSYM;
case SleighSymbol::name_symbol:
yylval.namesym = (NameSymbol *)sym;
return NAMESYM;
case SleighSymbol::varnode_symbol:
yylval.varsym = (VarnodeSymbol *)sym;
return VARSYM;
case SleighSymbol::bitrange_symbol:
yylval.bitsym = (BitrangeSymbol *)sym;
return BITSYM;
case SleighSymbol::varnodelist_symbol:
yylval.varlistsym = (VarnodeListSymbol *)sym;
return VARLISTSYM;
case SleighSymbol::operand_symbol:
yylval.operandsym = (OperandSymbol *)sym;
return OPERANDSYM;
case SleighSymbol::start_symbol:
yylval.startsym = (StartSymbol *)sym;
return STARTSYM;
case SleighSymbol::end_symbol:
yylval.endsym = (EndSymbol *)sym;
return ENDSYM;
case SleighSymbol::subtable_symbol:
yylval.subtablesym = (SubtableSymbol *)sym;
return SUBTABLESYM;
case SleighSymbol::macro_symbol:
yylval.macrosym = (MacroSymbol *)sym;
return MACROSYM;
case SleighSymbol::label_symbol:
yylval.labelsym = (LabelSymbol *)sym;
return LABELSYM;
case SleighSymbol::epsilon_symbol:
yylval.specsym = (SpecificSymbol *)sym;
return SPECSYM;
case SleighSymbol::context_symbol:
yylval.contextsym = (ContextSymbol *)sym;
return CONTEXTSYM;
case SleighSymbol::dummy_symbol:
break;
}
return -1; // Should never reach here
}
int4 scan_number(char *numtext,YYSTYPE *lval,bool signednum)
{
uintb val;
if (numtext[0] == '0' && numtext[1] == 'b') {
val = 0;
numtext += 2;
while ((*numtext) != 0) {
val <<= 1;
if (*numtext == '1') {
val |= 1;
}
++numtext;
}
} else {
istringstream s(numtext);
s.unsetf(ios::dec | ios::hex | ios::oct);
s >> val;
if (!s)
return BADINTEGER;
}
if (signednum) {
lval->big = new intb(val);
return INTB;
}
lval->i = new uintb(val);
return INTEGER;
}
#line 1335 "src/decompile/cpp/slghscan.cc"
#define INITIAL 0
#define defblock 1
#define macroblock 2
#define print 3
#define pattern 4
#define sem 5
#define preproc 6
#ifndef YY_NO_UNISTD_H
/* Special case for "unistd.h", since it is non-ANSI. We include it way
* down here because we want the user's section 1 to have been scanned first.
* The user has a chance to override it with an option.
*/
#include <unistd.h>
#endif
#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void *
#endif
static int yy_init_globals (void );
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int yylex_destroy (void );
int yyget_debug (void );
void yyset_debug (int debug_flag );
YY_EXTRA_TYPE yyget_extra (void );
void yyset_extra (YY_EXTRA_TYPE user_defined );
FILE *yyget_in (void );
void yyset_in (FILE * in_str );
FILE *yyget_out (void );
void yyset_out (FILE * out_str );
yy_size_t yyget_leng (void );
char *yyget_text (void );
int yyget_lineno (void );
void yyset_lineno (int line_number );
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int yywrap (void );
#else
extern int yywrap (void );
#endif
#endif
static void yyunput (int c,char *buf_ptr );
#ifndef yytext_ptr
static void yy_flex_strncpy (char *,yyconst char *,int );
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * );
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void );
#else
static int input (void );
#endif
#endif
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#define YY_READ_BUF_SIZE 8192
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0)
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
size_t n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
if ( c == '\n' ) \
buf[n++] = (char) c; \
if ( c == EOF && ferror( yyin ) ) \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
result = n; \
} \
else \
{ \
errno=0; \
while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
break; \
} \
errno=0; \
clearerr(yyin); \
} \
}\
\
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
#endif
/* end tables serialization structures and prototypes */
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int yylex (void);
#define YY_DECL int yylex (void)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK break;
#endif
#define YY_RULE_SETUP \
if ( yyleng > 0 ) \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = \
(yytext[yyleng - 1] == '\n'); \
YY_USER_ACTION
/** The main scanner function which does all the work.
*/
YY_DECL
{
register yy_state_type yy_current_state;
register char *yy_cp, *yy_bp;
register int yy_act;
#line 490 "src/decompile/cpp/slghscan.l"
#line 1529 "src/decompile/cpp/slghscan.cc"
if ( !(yy_init) )
{
(yy_init) = 1;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
if ( ! (yy_start) )
(yy_start) = 1; /* first start state */
if ( ! yyin )
yyin = stdin;
if ( ! yyout )
yyout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE );
}
yy_load_buffer_state( );
}
while ( 1 ) /* loops until end-of-file is reached */
{
yy_cp = (yy_c_buf_p);
/* Support of yytext. */
*yy_cp = (yy_hold_char);
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
yy_current_state = (yy_start);
yy_current_state += YY_AT_BOL();
yy_match:
do
{
register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 527 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
++yy_cp;
}
while ( yy_base[yy_current_state] != 926 );
yy_find_action:
yy_act = yy_accept[yy_current_state];
if ( yy_act == 0 )
{ /* have to back up */
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
yy_act = yy_accept[yy_current_state];
}
YY_DO_BEFORE_ACTION;
do_action: /* This label is used only to access EOF actions. */
switch ( yy_act )
{ /* beginning of action switch */
case 0: /* must back up */
/* undo the effects of YY_DO_BEFORE_ACTION */
*yy_cp = (yy_hold_char);
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
goto yy_find_action;
case 1:
/* rule 1 can match eol */
YY_RULE_SETUP
#line 492 "src/decompile/cpp/slghscan.l"
{ slgh->nextLine(); BEGIN( preprocess(INITIAL,preproc) ); }
YY_BREAK
case 2:
YY_RULE_SETUP
#line 493 "src/decompile/cpp/slghscan.l"
{ preproc_macroexpand(); }
YY_BREAK
case 3:
YY_RULE_SETUP
#line 494 "src/decompile/cpp/slghscan.l"
{ yylval.ch = yytext[0]; return yytext[0]; }
YY_BREAK
case 4:
YY_RULE_SETUP
#line 495 "src/decompile/cpp/slghscan.l"
{ BEGIN(print); slgh->calcContextLayout(); yylval.ch = yytext[0]; return yytext[0]; }
YY_BREAK
case 5:
YY_RULE_SETUP
#line 496 "src/decompile/cpp/slghscan.l"
{ BEGIN(sem); yylval.ch = yytext[0]; return yytext[0]; }
YY_BREAK
case 6:
YY_RULE_SETUP
#line 497 "src/decompile/cpp/slghscan.l"
YY_BREAK
case 7:
YY_RULE_SETUP
#line 498 "src/decompile/cpp/slghscan.l"
YY_BREAK
case 8:
/* rule 8 can match eol */
YY_RULE_SETUP
#line 499 "src/decompile/cpp/slghscan.l"
{ slgh->nextLine(); }
YY_BREAK
case 9:
YY_RULE_SETUP
#line 500 "src/decompile/cpp/slghscan.l"
{ BEGIN(macroblock); return MACRO_KEY; }
YY_BREAK
case 10:
YY_RULE_SETUP
#line 501 "src/decompile/cpp/slghscan.l"
{ BEGIN(defblock); return DEFINE_KEY; }
YY_BREAK
case 11:
YY_RULE_SETUP
#line 502 "src/decompile/cpp/slghscan.l"
{ BEGIN(defblock); slgh->calcContextLayout(); return ATTACH_KEY; }
YY_BREAK
case 12:
YY_RULE_SETUP
#line 503 "src/decompile/cpp/slghscan.l"
{ BEGIN(pattern); withsection = 1; slgh->calcContextLayout(); return WITH_KEY; }
YY_BREAK
case 13:
YY_RULE_SETUP
#line 504 "src/decompile/cpp/slghscan.l"
{ return find_symbol(); }
YY_BREAK
case 14:
YY_RULE_SETUP
#line 505 "src/decompile/cpp/slghscan.l"
{ return yytext[0]; }
YY_BREAK
case 15:
/* rule 15 can match eol */
YY_RULE_SETUP
#line 507 "src/decompile/cpp/slghscan.l"
{ slgh->nextLine(); BEGIN( preprocess(macroblock,preproc) ); }
YY_BREAK
case 16:
YY_RULE_SETUP
#line 508 "src/decompile/cpp/slghscan.l"
{ preproc_macroexpand(); }
YY_BREAK
case 17:
YY_RULE_SETUP
#line 509 "src/decompile/cpp/slghscan.l"
{ yylval.ch = yytext[0]; return yytext[0]; }
YY_BREAK
case 18:
YY_RULE_SETUP
#line 510 "src/decompile/cpp/slghscan.l"
{ BEGIN(sem); return yytext[0]; }
YY_BREAK
case 19:
YY_RULE_SETUP
#line 511 "src/decompile/cpp/slghscan.l"
{ yylval.str = new string(yytext); return STRING; }
YY_BREAK
case 20:
YY_RULE_SETUP
#line 512 "src/decompile/cpp/slghscan.l"
YY_BREAK
case 21:
/* rule 21 can match eol */
YY_RULE_SETUP
#line 513 "src/decompile/cpp/slghscan.l"
{ slgh->nextLine(); }
YY_BREAK
case 22:
YY_RULE_SETUP
#line 514 "src/decompile/cpp/slghscan.l"
{ return yytext[0]; }
YY_BREAK
case 23:
/* rule 23 can match eol */
YY_RULE_SETUP
#line 516 "src/decompile/cpp/slghscan.l"
{ slgh->nextLine(); BEGIN( preprocess(defblock,preproc) ); }
YY_BREAK
case 24:
YY_RULE_SETUP
#line 517 "src/decompile/cpp/slghscan.l"
{ preproc_macroexpand(); }
YY_BREAK
case 25:
YY_RULE_SETUP
#line 518 "src/decompile/cpp/slghscan.l"
{ yylval.ch = yytext[0]; return yytext[0]; }
YY_BREAK
case 26:
YY_RULE_SETUP
#line 519 "src/decompile/cpp/slghscan.l"
{ BEGIN(INITIAL); yylval.ch = yytext[0]; return yytext[0]; }
YY_BREAK
case 27:
YY_RULE_SETUP
#line 520 "src/decompile/cpp/slghscan.l"
{ return SPACE_KEY; }
YY_BREAK
case 28:
YY_RULE_SETUP
#line 521 "src/decompile/cpp/slghscan.l"
{ return TYPE_KEY; }
YY_BREAK
case 29:
YY_RULE_SETUP
#line 522 "src/decompile/cpp/slghscan.l"
{ return RAM_KEY; }
YY_BREAK
case 30:
YY_RULE_SETUP
#line 523 "src/decompile/cpp/slghscan.l"
{ return DEFAULT_KEY; }
YY_BREAK
case 31:
YY_RULE_SETUP
#line 524 "src/decompile/cpp/slghscan.l"
{ return REGISTER_KEY; }
YY_BREAK
case 32:
YY_RULE_SETUP
#line 525 "src/decompile/cpp/slghscan.l"
{ return TOKEN_KEY; }
YY_BREAK
case 33:
YY_RULE_SETUP
#line 526 "src/decompile/cpp/slghscan.l"
{ return CONTEXT_KEY; }
YY_BREAK
case 34:
YY_RULE_SETUP
#line 527 "src/decompile/cpp/slghscan.l"
{ return BITRANGE_KEY; }
YY_BREAK
case 35:
YY_RULE_SETUP
#line 528 "src/decompile/cpp/slghscan.l"
{ return SIGNED_KEY; }
YY_BREAK
case 36:
YY_RULE_SETUP
#line 529 "src/decompile/cpp/slghscan.l"
{ return NOFLOW_KEY; }
YY_BREAK
case 37:
YY_RULE_SETUP
#line 530 "src/decompile/cpp/slghscan.l"
{ return HEX_KEY; }
YY_BREAK
case 38:
YY_RULE_SETUP
#line 531 "src/decompile/cpp/slghscan.l"
{ return DEC_KEY; }
YY_BREAK
case 39:
YY_RULE_SETUP
#line 532 "src/decompile/cpp/slghscan.l"
{ return ENDIAN_KEY; }
YY_BREAK
case 40:
YY_RULE_SETUP
#line 533 "src/decompile/cpp/slghscan.l"
{ return ALIGN_KEY; }
YY_BREAK
case 41:
YY_RULE_SETUP
#line 534 "src/decompile/cpp/slghscan.l"
{ return BIG_KEY; }
YY_BREAK
case 42:
YY_RULE_SETUP
#line 535 "src/decompile/cpp/slghscan.l"
{ return LITTLE_KEY; }
YY_BREAK
case 43:
YY_RULE_SETUP
#line 536 "src/decompile/cpp/slghscan.l"
{ return SIZE_KEY; }
YY_BREAK
case 44:
YY_RULE_SETUP
#line 537 "src/decompile/cpp/slghscan.l"
{ return WORDSIZE_KEY; }
YY_BREAK
case 45:
YY_RULE_SETUP
#line 538 "src/decompile/cpp/slghscan.l"
{ return OFFSET_KEY; }
YY_BREAK
case 46:
YY_RULE_SETUP
#line 539 "src/decompile/cpp/slghscan.l"
{ return NAMES_KEY; }
YY_BREAK
case 47:
YY_RULE_SETUP
#line 540 "src/decompile/cpp/slghscan.l"
{ return VALUES_KEY; }
YY_BREAK
case 48:
YY_RULE_SETUP
#line 541 "src/decompile/cpp/slghscan.l"
{ return VARIABLES_KEY; }
YY_BREAK
case 49:
YY_RULE_SETUP
#line 542 "src/decompile/cpp/slghscan.l"
{ return PCODEOP_KEY; }
YY_BREAK
case 50:
YY_RULE_SETUP
#line 543 "src/decompile/cpp/slghscan.l"
YY_BREAK
case 51:
YY_RULE_SETUP
#line 544 "src/decompile/cpp/slghscan.l"
{ return find_symbol(); }
YY_BREAK
case 52:
YY_RULE_SETUP
#line 545 "src/decompile/cpp/slghscan.l"
{ return scan_number(yytext,&yylval,false); }
YY_BREAK
case 53:
YY_RULE_SETUP
#line 546 "src/decompile/cpp/slghscan.l"
{ return scan_number(yytext,&yylval,false); }
YY_BREAK
case 54:
YY_RULE_SETUP
#line 547 "src/decompile/cpp/slghscan.l"
{ return scan_number(yytext,&yylval,false); }
YY_BREAK
case 55:
/* rule 55 can match eol */
YY_RULE_SETUP
#line 548 "src/decompile/cpp/slghscan.l"
{ yylval.str = new string(yytext+1,strlen(yytext)-2); return STRING; }
YY_BREAK
case 56:
YY_RULE_SETUP
#line 549 "src/decompile/cpp/slghscan.l"
YY_BREAK
case 57:
/* rule 57 can match eol */
YY_RULE_SETUP
#line 550 "src/decompile/cpp/slghscan.l"
{ slgh->nextLine(); }
YY_BREAK
case 58:
YY_RULE_SETUP
#line 551 "src/decompile/cpp/slghscan.l"
{ return yytext[0]; }
YY_BREAK
case 59:
/* rule 59 can match eol */
YY_RULE_SETUP
#line 554 "src/decompile/cpp/slghscan.l"
{ slgh->nextLine(); BEGIN( preprocess(print,preproc) ); }
YY_BREAK
case 60:
YY_RULE_SETUP
#line 555 "src/decompile/cpp/slghscan.l"
{ preproc_macroexpand(); }
YY_BREAK
case 61:
YY_RULE_SETUP
#line 556 "src/decompile/cpp/slghscan.l"
{ yylval.ch = yytext[0]; return CHAR; }
YY_BREAK
case 62:
YY_RULE_SETUP
#line 557 "src/decompile/cpp/slghscan.l"
{ yylval.ch = '^'; return '^'; }
YY_BREAK
case 63:
YY_RULE_SETUP
#line 558 "src/decompile/cpp/slghscan.l"
{ BEGIN(pattern); actionon=0; return IS_KEY; }
YY_BREAK
case 64:
YY_RULE_SETUP
#line 559 "src/decompile/cpp/slghscan.l"
{ yylval.str = new string(yytext); return SYMBOLSTRING; }
YY_BREAK
case 65:
/* rule 65 can match eol */
YY_RULE_SETUP
#line 560 "src/decompile/cpp/slghscan.l"
{ yylval.str = new string(yytext+1,strlen(yytext)-2); return STRING; }
YY_BREAK
case 66:
YY_RULE_SETUP
#line 561 "src/decompile/cpp/slghscan.l"
{ yylval.ch = ' '; return ' '; }
YY_BREAK
case 67:
/* rule 67 can match eol */
YY_RULE_SETUP
#line 562 "src/decompile/cpp/slghscan.l"
{ slgh->nextLine(); return ' '; }
YY_BREAK
case 68:
YY_RULE_SETUP
#line 563 "src/decompile/cpp/slghscan.l"
{ return yytext[0]; }
YY_BREAK
case 69:
/* rule 69 can match eol */
YY_RULE_SETUP
#line 565 "src/decompile/cpp/slghscan.l"
{ slgh->nextLine(); BEGIN( preprocess(pattern,preproc) ); }
YY_BREAK
case 70:
YY_RULE_SETUP
#line 566 "src/decompile/cpp/slghscan.l"
{ preproc_macroexpand(); }
YY_BREAK
case 71:
YY_RULE_SETUP
#line 567 "src/decompile/cpp/slghscan.l"
{ BEGIN((withsection==1) ? INITIAL:sem); withsection=0; yylval.ch = yytext[0]; return yytext[0]; }
YY_BREAK
case 72:
YY_RULE_SETUP
#line 568 "src/decompile/cpp/slghscan.l"
{ BEGIN(INITIAL); return OP_UNIMPL; }
YY_BREAK
case 73:
YY_RULE_SETUP
#line 569 "src/decompile/cpp/slghscan.l"
{ return GLOBALSET_KEY; }
YY_BREAK
case 74:
YY_RULE_SETUP
#line 570 "src/decompile/cpp/slghscan.l"
{ return OP_RIGHT; }
YY_BREAK
case 75:
YY_RULE_SETUP
#line 571 "src/decompile/cpp/slghscan.l"
{ return OP_LEFT; }
YY_BREAK
case 76:
YY_RULE_SETUP
#line 572 "src/decompile/cpp/slghscan.l"
{ return OP_NOTEQUAL; }
YY_BREAK
case 77:
YY_RULE_SETUP
#line 573 "src/decompile/cpp/slghscan.l"
{ return OP_LESSEQUAL; }
YY_BREAK
case 78:
YY_RULE_SETUP
#line 574 "src/decompile/cpp/slghscan.l"
{ return OP_GREATEQUAL; }
YY_BREAK
case 79:
YY_RULE_SETUP
#line 575 "src/decompile/cpp/slghscan.l"
{ return OP_AND; }
YY_BREAK
case 80:
YY_RULE_SETUP
#line 576 "src/decompile/cpp/slghscan.l"
{ return OP_OR; }
YY_BREAK
case 81:
YY_RULE_SETUP
#line 577 "src/decompile/cpp/slghscan.l"
{ return OP_XOR; }
YY_BREAK
case 82:
YY_RULE_SETUP
#line 578 "src/decompile/cpp/slghscan.l"
{ return ELLIPSIS_KEY; }
YY_BREAK
case 83:
YY_RULE_SETUP
#line 579 "src/decompile/cpp/slghscan.l"
{ actionon = 1; yylval.ch = yytext[0]; return yytext[0]; }
YY_BREAK
case 84:
YY_RULE_SETUP
#line 580 "src/decompile/cpp/slghscan.l"
{ actionon = 0; yylval.ch = yytext[0]; return yytext[0]; }
YY_BREAK
case 85:
YY_RULE_SETUP
#line 581 "src/decompile/cpp/slghscan.l"
{ yylval.ch = yytext[0]; return (actionon==0) ? yytext[0] : OP_AND; }
YY_BREAK
case 86:
YY_RULE_SETUP
#line 582 "src/decompile/cpp/slghscan.l"
{ yylval.ch = yytext[0]; return (actionon==0) ? yytext[0] : OP_OR; }
YY_BREAK
case 87:
YY_RULE_SETUP
#line 583 "src/decompile/cpp/slghscan.l"
{ return OP_XOR; }
YY_BREAK
case 88:
YY_RULE_SETUP
#line 584 "src/decompile/cpp/slghscan.l"
{ yylval.ch = yytext[0]; return yytext[0]; }
YY_BREAK
case 89:
YY_RULE_SETUP
#line 585 "src/decompile/cpp/slghscan.l"
YY_BREAK
case 90:
YY_RULE_SETUP
#line 586 "src/decompile/cpp/slghscan.l"
{ return find_symbol(); }
YY_BREAK
case 91:
YY_RULE_SETUP
#line 587 "src/decompile/cpp/slghscan.l"
{ return scan_number(yytext,&yylval,true); }
YY_BREAK
case 92:
YY_RULE_SETUP
#line 588 "src/decompile/cpp/slghscan.l"
{ return scan_number(yytext,&yylval,true); }
YY_BREAK
case 93:
YY_RULE_SETUP
#line 589 "src/decompile/cpp/slghscan.l"
{ return scan_number(yytext,&yylval,true); }
YY_BREAK
case 94:
YY_RULE_SETUP
#line 590 "src/decompile/cpp/slghscan.l"
YY_BREAK
case 95:
/* rule 95 can match eol */
YY_RULE_SETUP
#line 591 "src/decompile/cpp/slghscan.l"
{ slgh->nextLine(); }
YY_BREAK
case 96:
YY_RULE_SETUP
#line 592 "src/decompile/cpp/slghscan.l"
{ return yytext[0]; }
YY_BREAK
case 97:
/* rule 97 can match eol */
YY_RULE_SETUP
#line 594 "src/decompile/cpp/slghscan.l"
{ slgh->nextLine(); BEGIN( preprocess(sem,preproc) ); }
YY_BREAK
case 98:
YY_RULE_SETUP
#line 595 "src/decompile/cpp/slghscan.l"
{ preproc_macroexpand(); }
YY_BREAK
case 99:
YY_RULE_SETUP
#line 596 "src/decompile/cpp/slghscan.l"
{ BEGIN(INITIAL); yylval.ch = yytext[0]; return yytext[0]; }
YY_BREAK
case 100:
YY_RULE_SETUP
#line 597 "src/decompile/cpp/slghscan.l"
{ return OP_BOOL_OR; }
YY_BREAK
case 101:
YY_RULE_SETUP
#line 598 "src/decompile/cpp/slghscan.l"
{ return OP_BOOL_AND; }
YY_BREAK
case 102:
YY_RULE_SETUP
#line 599 "src/decompile/cpp/slghscan.l"
{ return OP_BOOL_XOR; }
YY_BREAK
case 103:
YY_RULE_SETUP
#line 600 "src/decompile/cpp/slghscan.l"
{ return OP_RIGHT; }
YY_BREAK
case 104:
YY_RULE_SETUP
#line 601 "src/decompile/cpp/slghscan.l"
{ return OP_LEFT; }
YY_BREAK
case 105:
YY_RULE_SETUP
#line 602 "src/decompile/cpp/slghscan.l"
{ return OP_EQUAL; }
YY_BREAK
case 106:
YY_RULE_SETUP
#line 603 "src/decompile/cpp/slghscan.l"
{ return OP_NOTEQUAL; }
YY_BREAK
case 107:
YY_RULE_SETUP
#line 604 "src/decompile/cpp/slghscan.l"
{ return OP_LESSEQUAL; }
YY_BREAK
case 108:
YY_RULE_SETUP
#line 605 "src/decompile/cpp/slghscan.l"
{ return OP_GREATEQUAL; }
YY_BREAK
case 109:
YY_RULE_SETUP
#line 606 "src/decompile/cpp/slghscan.l"
{ return OP_SDIV; }
YY_BREAK
case 110:
YY_RULE_SETUP
#line 607 "src/decompile/cpp/slghscan.l"
{ return OP_SREM; }
YY_BREAK
case 111:
YY_RULE_SETUP
#line 608 "src/decompile/cpp/slghscan.l"
{ return OP_SRIGHT; }
YY_BREAK
case 112:
YY_RULE_SETUP
#line 609 "src/decompile/cpp/slghscan.l"
{ return OP_SLESS; }
YY_BREAK
case 113:
YY_RULE_SETUP
#line 610 "src/decompile/cpp/slghscan.l"
{ return OP_SGREAT; }
YY_BREAK
case 114:
YY_RULE_SETUP
#line 611 "src/decompile/cpp/slghscan.l"
{ return OP_SLESSEQUAL; }
YY_BREAK
case 115:
YY_RULE_SETUP
#line 612 "src/decompile/cpp/slghscan.l"
{ return OP_SGREATEQUAL; }
YY_BREAK
case 116:
YY_RULE_SETUP
#line 613 "src/decompile/cpp/slghscan.l"
{ return OP_FADD; }
YY_BREAK
case 117:
YY_RULE_SETUP
#line 614 "src/decompile/cpp/slghscan.l"
{ return OP_FSUB; }
YY_BREAK
case 118:
YY_RULE_SETUP
#line 615 "src/decompile/cpp/slghscan.l"
{ return OP_FMULT; }
YY_BREAK
case 119:
YY_RULE_SETUP
#line 616 "src/decompile/cpp/slghscan.l"
{ return OP_FDIV; }
YY_BREAK
case 120:
YY_RULE_SETUP
#line 617 "src/decompile/cpp/slghscan.l"
{ return OP_FEQUAL; }
YY_BREAK
case 121:
YY_RULE_SETUP
#line 618 "src/decompile/cpp/slghscan.l"
{ return OP_FNOTEQUAL; }
YY_BREAK
case 122:
YY_RULE_SETUP
#line 619 "src/decompile/cpp/slghscan.l"
{ return OP_FLESS; }
YY_BREAK
case 123:
YY_RULE_SETUP
#line 620 "src/decompile/cpp/slghscan.l"
{ return OP_FGREAT; }
YY_BREAK
case 124:
YY_RULE_SETUP
#line 621 "src/decompile/cpp/slghscan.l"
{ return OP_FLESSEQUAL; }
YY_BREAK
case 125:
YY_RULE_SETUP
#line 622 "src/decompile/cpp/slghscan.l"
{ return OP_FGREATEQUAL; }
YY_BREAK
case 126:
YY_RULE_SETUP
#line 623 "src/decompile/cpp/slghscan.l"
{ return OP_ZEXT; }
YY_BREAK
case 127:
YY_RULE_SETUP
#line 624 "src/decompile/cpp/slghscan.l"
{ return OP_CARRY; }
YY_BREAK
case 128:
YY_RULE_SETUP
#line 625 "src/decompile/cpp/slghscan.l"
{ return OP_BORROW; }
YY_BREAK
case 129:
YY_RULE_SETUP
#line 626 "src/decompile/cpp/slghscan.l"
{ return OP_SEXT; }
YY_BREAK
case 130:
YY_RULE_SETUP
#line 627 "src/decompile/cpp/slghscan.l"
{ return OP_SCARRY; }
YY_BREAK
case 131:
YY_RULE_SETUP
#line 628 "src/decompile/cpp/slghscan.l"
{ return OP_SBORROW; }
YY_BREAK
case 132:
YY_RULE_SETUP
#line 629 "src/decompile/cpp/slghscan.l"
{ return OP_NAN; }
YY_BREAK
case 133:
YY_RULE_SETUP
#line 630 "src/decompile/cpp/slghscan.l"
{ return OP_ABS; }
YY_BREAK
case 134:
YY_RULE_SETUP
#line 631 "src/decompile/cpp/slghscan.l"
{ return OP_SQRT; }
YY_BREAK
case 135:
YY_RULE_SETUP
#line 632 "src/decompile/cpp/slghscan.l"
{ return OP_CEIL; }
YY_BREAK
case 136:
YY_RULE_SETUP
#line 633 "src/decompile/cpp/slghscan.l"
{ return OP_FLOOR; }
YY_BREAK
case 137:
YY_RULE_SETUP
#line 634 "src/decompile/cpp/slghscan.l"
{ return OP_ROUND; }
YY_BREAK
case 138:
YY_RULE_SETUP
#line 635 "src/decompile/cpp/slghscan.l"
{ return OP_INT2FLOAT; }
YY_BREAK
case 139:
YY_RULE_SETUP
#line 636 "src/decompile/cpp/slghscan.l"
{ return OP_FLOAT2FLOAT; }
YY_BREAK
case 140:
YY_RULE_SETUP
#line 637 "src/decompile/cpp/slghscan.l"
{ return OP_TRUNC; }
YY_BREAK
case 141:
YY_RULE_SETUP
#line 638 "src/decompile/cpp/slghscan.l"
{ return OP_CPOOLREF; }
YY_BREAK
case 142:
YY_RULE_SETUP
#line 639 "src/decompile/cpp/slghscan.l"
{ return OP_NEW; }
YY_BREAK
case 143:
YY_RULE_SETUP
#line 640 "src/decompile/cpp/slghscan.l"
{ return OP_POPCOUNT; }
YY_BREAK
case 144:
YY_RULE_SETUP
#line 641 "src/decompile/cpp/slghscan.l"
{ return IF_KEY; }
YY_BREAK
case 145:
YY_RULE_SETUP
#line 642 "src/decompile/cpp/slghscan.l"
{ return GOTO_KEY; }
YY_BREAK
case 146:
YY_RULE_SETUP
#line 643 "src/decompile/cpp/slghscan.l"
{ return CALL_KEY; }
YY_BREAK
case 147:
YY_RULE_SETUP
#line 644 "src/decompile/cpp/slghscan.l"
{ return RETURN_KEY; }
YY_BREAK
case 148:
YY_RULE_SETUP
#line 645 "src/decompile/cpp/slghscan.l"
{ return DELAYSLOT_KEY; }
YY_BREAK
case 149:
YY_RULE_SETUP
#line 646 "src/decompile/cpp/slghscan.l"
{ return CROSSBUILD_KEY; }
YY_BREAK
case 150:
YY_RULE_SETUP
#line 647 "src/decompile/cpp/slghscan.l"
{ return EXPORT_KEY; }
YY_BREAK
case 151:
YY_RULE_SETUP
#line 648 "src/decompile/cpp/slghscan.l"
{ return BUILD_KEY; }
YY_BREAK
case 152:
YY_RULE_SETUP
#line 649 "src/decompile/cpp/slghscan.l"
{ return LOCAL_KEY; }
YY_BREAK
case 153:
YY_RULE_SETUP
#line 650 "src/decompile/cpp/slghscan.l"
{ yylval.ch = yytext[0]; return yytext[0]; }
YY_BREAK
case 154:
YY_RULE_SETUP
#line 651 "src/decompile/cpp/slghscan.l"
YY_BREAK
case 155:
YY_RULE_SETUP
#line 652 "src/decompile/cpp/slghscan.l"
{ return find_symbol(); }
YY_BREAK
case 156:
YY_RULE_SETUP
#line 653 "src/decompile/cpp/slghscan.l"
{ return scan_number(yytext,&yylval,false); }
YY_BREAK
case 157:
YY_RULE_SETUP
#line 654 "src/decompile/cpp/slghscan.l"
{ return scan_number(yytext,&yylval,false); }
YY_BREAK
case 158:
YY_RULE_SETUP
#line 655 "src/decompile/cpp/slghscan.l"
{ return scan_number(yytext,&yylval,false); }
YY_BREAK
case 159:
YY_RULE_SETUP
#line 656 "src/decompile/cpp/slghscan.l"
YY_BREAK
case 160:
/* rule 160 can match eol */
YY_RULE_SETUP
#line 657 "src/decompile/cpp/slghscan.l"
{ slgh->nextLine(); }
YY_BREAK
case 161:
YY_RULE_SETUP
#line 658 "src/decompile/cpp/slghscan.l"
{ return yytext[0]; }
YY_BREAK
case 162:
/* rule 162 can match eol */
YY_RULE_SETUP
#line 660 "src/decompile/cpp/slghscan.l"
{ slgh->nextLine(); BEGIN( preprocess(preproc,preproc) ); }
YY_BREAK
case 163:
/* rule 163 can match eol */
YY_RULE_SETUP
#line 661 "src/decompile/cpp/slghscan.l"
{ slgh->nextLine(); }
YY_BREAK
case YY_STATE_EOF(INITIAL):
case YY_STATE_EOF(defblock):
case YY_STATE_EOF(macroblock):
case YY_STATE_EOF(print):
case YY_STATE_EOF(pattern):
case YY_STATE_EOF(sem):
case YY_STATE_EOF(preproc):
#line 663 "src/decompile/cpp/slghscan.l"
{ yy_delete_buffer(YY_CURRENT_BUFFER );
if (filebuffers.empty())
yyterminate();
yy_switch_to_buffer(filebuffers.back().lastbuffer );
FILE *curfile = filebuffers.back().file;
if (curfile != (FILE *)0)
fclose(curfile);
filebuffers.pop_back();
slgh->parseFileFinished();
}
YY_BREAK
case 164:
YY_RULE_SETUP
#line 673 "src/decompile/cpp/slghscan.l"
ECHO;
YY_BREAK
#line 2468 "src/decompile/cpp/slghscan.cc"
case YY_END_OF_BUFFER:
{
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = (yy_hold_char);
YY_RESTORE_YY_MORE_OFFSET
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
{
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
* yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
{ /* This was really a NUL. */
yy_state_type yy_next_state;
(yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans( yy_current_state );
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
if ( yy_next_state )
{
/* Consume the NUL. */
yy_cp = ++(yy_c_buf_p);
yy_current_state = yy_next_state;
goto yy_match;
}
else
{
yy_cp = (yy_c_buf_p);
goto yy_find_action;
}
}
else switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_END_OF_FILE:
{
(yy_did_buffer_switch_on_eof) = 0;
if ( yywrap( ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* yytext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
(yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else
{
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) =
(yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
(yy_c_buf_p) =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR(
"fatal flex scanner internal error--no action found" );
} /* end of action switch */
} /* end of scanning one token */
} /* end of yylex */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
static int yy_get_next_buffer (void)
{
register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
register char *source = (yytext_ptr);
register int number_to_move, i;
int ret_val;
if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
YY_FATAL_ERROR(
"fatal flex scanner internal error--end of buffer missed" );
if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
{ /* Don't try to fill the buffer, so this is an EOF. */
if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
{
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else
{
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1;
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;
else
{
yy_size_t num_to_read =
YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
while ( num_to_read <= 0 )
{ /* Not enough room in the buffer - grow it. */
/* just a shorter name for the current buffer */
YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE;
int yy_c_buf_p_offset =
(int) ((yy_c_buf_p) - b->yy_ch_buf);
if ( b->yy_is_our_buffer )
{
yy_size_t new_size = b->yy_buf_size * 2;
if ( new_size <= 0 )
b->yy_buf_size += b->yy_buf_size / 8;
else
b->yy_buf_size *= 2;
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 );
}
else
/* Can't grow it, we don't own it. */
b->yy_ch_buf = 0;
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR(
"fatal error - scanner input buffer overflow" );
(yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset];
num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
number_to_move - 1;
}
if ( num_to_read > YY_READ_BUF_SIZE )
num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
(yy_n_chars), num_to_read );
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
if ( (yy_n_chars) == 0 )
{
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
yyrestart(yyin );
}
else
{
ret_val = EOB_ACT_LAST_MATCH;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1);
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
}
(yy_n_chars) += number_to_move;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
(yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
static yy_state_type yy_get_previous_state (void)
{
register yy_state_type yy_current_state;
register char *yy_cp;
yy_current_state = (yy_start);
yy_current_state += YY_AT_BOL();
for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
{
register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 527 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state )
{
register int yy_is_jam;
register char *yy_cp = (yy_c_buf_p);
register YY_CHAR yy_c = 1;
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 527 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
yy_is_jam = (yy_current_state == 526);
return yy_is_jam ? 0 : yy_current_state;
}
static void yyunput (int c, register char * yy_bp )
{
register char *yy_cp;
yy_cp = (yy_c_buf_p);
/* undo effects of setting up yytext */
*yy_cp = (yy_hold_char);
if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
{ /* need to shift things up to make room */
/* +2 for EOB chars. */
register yy_size_t number_to_move = (yy_n_chars) + 2;
register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
register char *source =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
*--dest = *--source;
yy_cp += (int) (dest - source);
yy_bp += (int) (dest - source);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
YY_FATAL_ERROR( "flex scanner push-back overflow" );
}
*--yy_cp = (char) c;
(yytext_ptr) = yy_bp;
(yy_hold_char) = *yy_cp;
(yy_c_buf_p) = yy_cp;
}
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void)
#else
static int input (void)
#endif
{
int c;
*(yy_c_buf_p) = (yy_hold_char);
if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
{
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
/* This was really a NUL. */
*(yy_c_buf_p) = '\0';
else
{ /* need more input */
yy_size_t offset = (yy_c_buf_p) - (yytext_ptr);
++(yy_c_buf_p);
switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
yyrestart(yyin );
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
if ( yywrap( ) )
return EOF;
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput();
#else
return input();
#endif
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) = (yytext_ptr) + offset;
break;
}
}
}
c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */
*(yy_c_buf_p) = '\0'; /* preserve yytext */
(yy_hold_char) = *++(yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = (c == '\n');
return c;
}
#endif /* ifndef YY_NO_INPUT */
/** Immediately switch to a different input stream.
* @param input_file A readable stream.
*
* @note This function does not reset the start condition to @c INITIAL .
*/
void yyrestart (FILE * input_file )
{
if ( ! YY_CURRENT_BUFFER ){
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE );
}
yy_init_buffer(YY_CURRENT_BUFFER,input_file );
yy_load_buffer_state( );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
*
*/
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer )
{
/* TODO. We should be able to replace this entire function body
* with
* yypop_buffer_state();
* yypush_buffer_state(new_buffer);
*/
yyensure_buffer_stack ();
if ( YY_CURRENT_BUFFER == new_buffer )
return;
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
yy_load_buffer_state( );
/* We don't actually know whether we did this switch during
* EOF (yywrap()) processing, but the only time this flag
* is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
(yy_did_buffer_switch_on_eof) = 1;
}
static void yy_load_buffer_state (void)
{
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
(yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
(yy_hold_char) = *(yy_c_buf_p);
}
/** Allocate and initialize an input buffer state.
* @param file A readable stream.
* @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
*
* @return the allocated buffer state.
*/
YY_BUFFER_STATE yy_create_buffer (FILE * file, int size )
{
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 );
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
yy_init_buffer(b,file );
return b;
}
/** Destroy the buffer.
* @param b a buffer created with yy_create_buffer()
*
*/
void yy_delete_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
yyfree((void *) b->yy_ch_buf );
yyfree((void *) b );
}
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
* such as during a yyrestart() or at EOF.
*/
static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file )
{
int oerrno = errno;
yy_flush_buffer(b );
b->yy_input_file = file;
b->yy_fill_buffer = 1;
/* If b is the current buffer, then yy_init_buffer was _probably_
* called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
b->yy_bs_lineno = 1;
b->yy_bs_column = 0;
}
b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
errno = oerrno;
}
/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
*
*/
void yy_flush_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
yy_load_buffer_state( );
}
/** Pushes the new state onto the stack. The new state becomes
* the current state. This function will allocate the stack
* if necessary.
* @param new_buffer The new state.
*
*/
void yypush_buffer_state (YY_BUFFER_STATE new_buffer )
{
if (new_buffer == NULL)
return;
yyensure_buffer_stack();
/* This block is copied from yy_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
/* Only push if top exists. Otherwise, replace top. */
if (YY_CURRENT_BUFFER)
(yy_buffer_stack_top)++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
/* copied from yy_switch_to_buffer. */
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
/** Removes and deletes the top of the stack, if present.
* The next element becomes the new top.
*
*/
void yypop_buffer_state (void)
{
if (!YY_CURRENT_BUFFER)
return;
yy_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
if ((yy_buffer_stack_top) > 0)
--(yy_buffer_stack_top);
if (YY_CURRENT_BUFFER) {
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
}
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
static void yyensure_buffer_stack (void)
{
yy_size_t num_to_alloc;
if (!(yy_buffer_stack)) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1;
(yy_buffer_stack) = (struct yy_buffer_state**)yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
(yy_buffer_stack_top) = 0;
return;
}
if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){
/* Increase the buffer to prepare for a possible push. */
int grow_size = 8 /* arbitrary grow size */;
num_to_alloc = (yy_buffer_stack_max) + grow_size;
(yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc
((yy_buffer_stack),
num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
}
}
/** Setup the input buffer state to scan directly from a user-specified character buffer.
* @param base the character buffer
* @param size the size in bytes of the character buffer
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size )
{
YY_BUFFER_STATE b;
if ( size < 2 ||
base[size-2] != YY_END_OF_BUFFER_CHAR ||
base[size-1] != YY_END_OF_BUFFER_CHAR )
/* They forgot to leave room for the EOB's. */
return 0;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = 0;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
yy_switch_to_buffer(b );
return b;
}
/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
*
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
* yy_scan_bytes() instead.
*/
YY_BUFFER_STATE yy_scan_string (yyconst char * yystr )
{
return yy_scan_bytes(yystr,strlen(yystr) );
}
/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param yybytes the byte buffer to scan
* @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len )
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
int i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = _yybytes_len + 2;
buf = (char *) yyalloc(n );
if ( ! buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
b = yy_scan_buffer(buf,n );
if ( ! b )
YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
static void yy_fatal_error (yyconst char* msg )
{
(void) fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
yytext[yyleng] = (yy_hold_char); \
(yy_c_buf_p) = yytext + yyless_macro_arg; \
(yy_hold_char) = *(yy_c_buf_p); \
*(yy_c_buf_p) = '\0'; \
yyleng = yyless_macro_arg; \
} \
while ( 0 )
/* Accessor methods (get/set functions) to struct members. */
/** Get the current line number.
*
*/
int yyget_lineno (void)
{
return yylineno;
}
/** Get the input stream.
*
*/
FILE *yyget_in (void)
{
return yyin;
}
/** Get the output stream.
*
*/
FILE *yyget_out (void)
{
return yyout;
}
/** Get the length of the current token.
*
*/
yy_size_t yyget_leng (void)
{
return yyleng;
}
/** Get the current token.
*
*/
char *yyget_text (void)
{
return yytext;
}
/** Set the current line number.
* @param line_number
*
*/
void yyset_lineno (int line_number )
{
yylineno = line_number;
}
/** Set the input stream. This does not discard the current
* input buffer.
* @param in_str A readable stream.
*
* @see yy_switch_to_buffer
*/
void yyset_in (FILE * in_str )
{
yyin = in_str ;
}
void yyset_out (FILE * out_str )
{
yyout = out_str ;
}
int yyget_debug (void)
{
return yy_flex_debug;
}
void yyset_debug (int bdebug )
{
yy_flex_debug = bdebug ;
}
static int yy_init_globals (void)
{
/* Initialization is the same as for the non-reentrant scanner.
* This function is called from yylex_destroy(), so don't allocate here.
*/
(yy_buffer_stack) = 0;
(yy_buffer_stack_top) = 0;
(yy_buffer_stack_max) = 0;
(yy_c_buf_p) = (char *) 0;
(yy_init) = 0;
(yy_start) = 0;
/* Defined in main.c */
#ifdef YY_STDINIT
yyin = stdin;
yyout = stdout;
#else
yyin = (FILE *) 0;
yyout = (FILE *) 0;
#endif
/* For future reference: Set errno on error, since we are called by
* yylex_init()
*/
return 0;
}
/* yylex_destroy is for both reentrant and non-reentrant scanners. */
int yylex_destroy (void)
{
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
yy_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
yypop_buffer_state();
}
/* Destroy the stack itself. */
yyfree((yy_buffer_stack) );
(yy_buffer_stack) = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* yylex() is called, initialization will occur. */
yy_init_globals( );
return 0;
}
/*
* Internal utility routines.
*/
#ifndef yytext_ptr
static void yy_flex_strncpy (char* s1, yyconst char * s2, int n )
{
register int i;
for ( i = 0; i < n; ++i )
s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * s )
{
register int n;
for ( n = 0; s[n]; ++n )
;
return n;
}
#endif
void *yyalloc (yy_size_t size )
{
return (void *) malloc( size );
}
void *yyrealloc (void * ptr, yy_size_t size )
{
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return (void *) realloc( (char *) ptr, size );
}
void yyfree (void * ptr )
{
free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
#line 673 "src/decompile/cpp/slghscan.l"
|
#ifndef STLPLUS_PRINT_LIST
#define STLPLUS_PRINT_LIST
////////////////////////////////////////////////////////////////////////////////
// Author: Andy Rushton
// Copyright: (c) Southampton University 1999-2004
// (c) Andy Rushton 2004 onwards
// License: BSD License, see ../docs/license.html
// Generate a string representation of a list
////////////////////////////////////////////////////////////////////////////////
#include "strings_fixes.hpp"
#include <string>
#include <iostream>
#include <list>
namespace stlplus
{
template<typename T, typename S>
void print_list(std::ostream& device,
const std::list<T>& values,
S print_fn,
const std::string& separator = ",");
} // end namespace stlplus
#include "print_list.tpp"
#endif
|
/*
* Copyright 2018-2021 Membrane Software <author@membranesoftware.com> https://membranesoftware.com
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "Config.h"
#include <stdlib.h>
#include "App.h"
#include "Log.h"
#include "OsUtil.h"
#include "StdString.h"
#include "StringList.h"
#include "Resource.h"
#include "SpriteGroup.h"
#include "AgentControl.h"
#include "Button.h"
#include "ComboBox.h"
#include "SystemInterface.h"
#include "RecordStore.h"
#include "HashMap.h"
#include "Ui.h"
#include "UiConfiguration.h"
#include "UiText.h"
#include "Toolbar.h"
#include "Menu.h"
#include "CardView.h"
#include "Toggle.h"
#include "Chip.h"
#include "ActionWindow.h"
#include "IconCardWindow.h"
#include "TaskWindow.h"
#include "ServerWindow.h"
#include "HelpWindow.h"
#include "AgentConfigurationWindow.h"
#include "AdminSecretWindow.h"
#include "ServerAdminUi.h"
ServerAdminUi::ServerAdminUi (const StdString &agentId, const StdString &agentDisplayName)
: Ui ()
, agentId (agentId)
, agentDisplayName (agentDisplayName)
, lockButton (NULL)
, adminSecretWindow (NULL)
, taskCount (0)
{
}
ServerAdminUi::~ServerAdminUi () {
}
StdString ServerAdminUi::getSpritePath () {
return (StdString ("ui/ServerAdminUi/sprite"));
}
Widget *ServerAdminUi::createBreadcrumbWidget () {
return (new Chip (UiConfiguration::instance->fonts[UiConfiguration::CaptionFont]->truncatedText (agentDisplayName, ((float) App::instance->windowWidth) * 0.5f, Font::DotTruncateSuffix), UiConfiguration::instance->coreSprites.getSprite (UiConfiguration::SettingsBoxButtonSprite)));
}
void ServerAdminUi::setHelpWindowContent (HelpWindow *helpWindow) {
helpWindow->setHelpText (UiText::instance->getText (UiTextString::ServerAdminUiHelpTitle), UiText::instance->getText (UiTextString::ServerAdminUiHelpText));
helpWindow->addAction (UiText::instance->getText (UiTextString::ServerAdminUiHelpAction1Text));
helpWindow->addAction (UiText::instance->getText (UiTextString::ServerAdminUiHelpAction2Text), UiText::instance->getText (UiTextString::LearnMore).capitalized (), App::getHelpUrl ("server-passwords"));
helpWindow->addTopicLink (UiText::instance->getText (UiTextString::SearchForHelp).capitalized (), App::getHelpUrl (""));
}
int ServerAdminUi::doLoad () {
cardView->setRowHeader (ServerAdminUi::TaskRow, createRowHeaderPanel (UiText::instance->getText (UiTextString::Tasks).capitalized ()));
cardView->setRowHeader (ServerAdminUi::ServerPasswordsRow, createRowHeaderPanel (UiText::instance->getText (UiTextString::ServerPasswords).capitalized ()));
adminSecretWindow = new AdminSecretWindow ();
adminSecretWindow->addButtonClickCallback = Widget::EventCallbackContext (ServerAdminUi::adminSecretAddButtonClicked, this);
adminSecretWindow->expandStateChangeCallback = Widget::EventCallbackContext (ServerAdminUi::cardExpandStateChanged, this);
adminSecretWindow->setExpanded (false);
cardView->addItem (adminSecretWindow, StdString (""), ServerAdminUi::ServerPasswordsRow);
App::instance->shouldSyncRecordStore = true;
return (OsUtil::Result::Success);
}
void ServerAdminUi::doUnload () {
emptyTaskWindow.clear ();
}
void ServerAdminUi::doAddSecondaryToolbarItems (Toolbar *toolbar) {
lockButton = new Button (sprites.getSprite (ServerAdminUi::LockButtonSprite));
lockButton->mouseClickCallback = Widget::EventCallbackContext (ServerAdminUi::lockButtonClicked, this);
lockButton->setInverseColor (true);
lockButton->setMouseHoverTooltip (UiText::instance->getText (UiTextString::ServerAdminUiLockTooltip), Widget::LeftAlignment);
toolbar->addRightItem (lockButton);
}
void ServerAdminUi::doResume () {
App::instance->setNextBackgroundTexturePath ("ui/ServerAdminUi/bg");
AgentControl::instance->connectLinkClient (agentId);
}
void ServerAdminUi::doPause () {
AgentControl::instance->disconnectLinkClient (agentId);
}
void ServerAdminUi::doUpdate (int msElapsed) {
emptyTaskWindow.compact ();
}
void ServerAdminUi::handleLinkClientConnect (const StdString &agentId) {
AgentControl::instance->writeLinkCommand (App::instance->createCommand (SystemInterface::Command_ReadTasks), agentId);
}
void ServerAdminUi::doSyncRecordStore () {
Json *record, *params;
ServerWindow *serverwindow;
AgentConfigurationWindow *configwindow;
IconCardWindow *iconcardwindow;
if (! cardView->contains (agentId)) {
record = RecordStore::instance->findRecord (agentId, SystemInterface::CommandId_AgentStatus);
if (record) {
serverwindow = new ServerWindow (agentId);
serverwindow->expandStateChangeCallback = Widget::EventCallbackContext (ServerAdminUi::cardExpandStateChanged, this);
serverwindow->statusChangeCallback = Widget::EventCallbackContext (ServerAdminUi::serverStatusChanged, this);
serverwindow->setExpanded (true, true);
cardView->addItem (serverwindow, agentId, ServerAdminUi::ServerRow);
configwindow = new AgentConfigurationWindow (agentId);
configwindow->expandStateChangeCallback = Widget::EventCallbackContext (ServerAdminUi::cardExpandStateChanged, this);
cardView->addItem (configwindow, StdString (""), ServerAdminUi::ServerRow);
configwindow->loadConfiguration ();
}
}
watchIdList.clear ();
taskCount = 0;
RecordStore::instance->processCommandRecords (SystemInterface::CommandId_TaskItem, ServerAdminUi::processTaskItem, this);
if (! watchIdList.empty ()) {
params = new Json ();
params->set ("taskIds", &watchIdList);
AgentControl::instance->writeLinkCommand (App::instance->createCommand (SystemInterface::Command_WatchTasks, params), agentId);
}
iconcardwindow = (IconCardWindow *) emptyTaskWindow.widget;
if (taskCount > 0) {
if (iconcardwindow) {
cardView->removeItem (iconcardwindow->itemId);
emptyTaskWindow.clear ();
}
}
else {
if (! iconcardwindow) {
iconcardwindow = new IconCardWindow (UiConfiguration::instance->coreSprites.getSprite (UiConfiguration::InfoIconSprite), UiText::instance->getText (UiTextString::ServerAdminUiEmptyTaskListTitle), StdString (""), UiText::instance->getText (UiTextString::ServerAdminUiEmptyTaskListText));
emptyTaskWindow.assign (iconcardwindow);
iconcardwindow->itemId.assign (cardView->getAvailableItemId ());
cardView->addItem (iconcardwindow, iconcardwindow->itemId, ServerAdminUi::TaskRow);
}
}
cardView->syncRecordStore ();
cardView->refresh ();
}
void ServerAdminUi::processTaskItem (void *uiPtr, Json *record, const StdString &recordId) {
ServerAdminUi *ui;
TaskWindow *window;
ui = (ServerAdminUi *) uiPtr;
if (ui->agentId.equals (SystemInterface::instance->getCommandAgentId (record))) {
++(ui->taskCount);
if (! ui->cardView->contains (recordId)) {
window = new TaskWindow (recordId);
ui->cardView->addItem (window, recordId, ServerAdminUi::TaskRow);
ui->watchIdList.push_back (recordId);
}
}
}
void ServerAdminUi::cardExpandStateChanged (void *uiPtr, Widget *widgetPtr) {
ServerAdminUi *ui;
ui = (ServerAdminUi *) uiPtr;
ui->clearPopupWidgets ();
ui->cardView->refresh ();
}
void ServerAdminUi::serverStatusChanged (void *uiPtr, Widget *widgetPtr) {
ServerAdminUi *ui;
ui = (ServerAdminUi *) uiPtr;
ui->cardView->refresh ();
}
void ServerAdminUi::adminSecretAddButtonClicked (void *uiPtr, Widget *widgetPtr) {
ServerAdminUi *ui;
AdminSecretWindow *target;
ActionWindow *action;
ui = (ServerAdminUi *) uiPtr;
target = (AdminSecretWindow *) widgetPtr;
if (ui->clearActionPopup (widgetPtr, ServerAdminUi::adminSecretAddButtonClicked)) {
return;
}
action = target->createAddActionWindow ();
action->closeCallback = Widget::EventCallbackContext (ServerAdminUi::adminSecretAddActionClosed, ui);
ui->showActionPopup (action, widgetPtr, ServerAdminUi::adminSecretAddButtonClicked, widgetPtr->getScreenRect (), Ui::RightOfAlignment, Ui::BottomEdgeAlignment);
}
void ServerAdminUi::adminSecretAddActionClosed (void *uiPtr, Widget *widgetPtr) {
ServerAdminUi *ui;
ActionWindow *action;
AdminSecretWindow *target;
ui = (ServerAdminUi *) uiPtr;
action = (ActionWindow *) widgetPtr;
if (! action->isConfirmed) {
return;
}
target = AdminSecretWindow::castWidget (ui->actionTarget.widget);
if (! target) {
return;
}
target->addItem (action);
ui->cardView->refresh ();
}
void ServerAdminUi::lockButtonClicked (void *uiPtr, Widget *widgetPtr) {
ServerAdminUi *ui;
ActionWindow *action;
ComboBox *combobox;
StringList items;
StringList::iterator i, end;
int listindex;
ui = (ServerAdminUi *) uiPtr;
if (ui->clearActionPopup (widgetPtr, ServerAdminUi::lockButtonClicked)) {
return;
}
action = new ActionWindow ();
action->setInverseColor (true);
action->setDropShadow (true, UiConfiguration::instance->dropShadowColor, UiConfiguration::instance->dropShadowWidth);
action->setTitleText (UiText::instance->getText (UiTextString::SetAdminPassword).capitalized ());
action->setConfirmTooltipText (UiText::instance->getText (UiTextString::Apply).capitalized ());
action->closeCallback = Widget::EventCallbackContext (ServerAdminUi::setAdminPasswordActionClosed, ui);
AgentControl::instance->getAdminSecretNames (&items);
combobox = new ComboBox ();
combobox->addItem (StdString (" "), StdString (""));
combobox->addItem (UiText::instance->getText (UiTextString::ServerAdminUiEmptyAdminPasswordText), StdString ("-1"));
if (! items.empty ()) {
listindex = 0;
i = items.begin ();
end = items.end ();
while (i != end) {
combobox->addItem (*i, StdString::createSprintf ("%i", listindex));
++listindex;
++i;
}
}
action->addOption (UiText::instance->getText (UiTextString::Password).capitalized (), combobox, UiText::instance->getText (UiTextString::ServerAdminUiAdminPasswordDescription));
action->setOptionNotEmptyString (UiText::instance->getText (UiTextString::Password).capitalized ());
ui->showActionPopup (action, widgetPtr, ServerAdminUi::lockButtonClicked, widgetPtr->getScreenRect (), Ui::RightEdgeAlignment, Ui::TopOfAlignment);
}
void ServerAdminUi::setAdminPasswordActionClosed (void *uiPtr, Widget *widgetPtr) {
ServerAdminUi *ui;
ActionWindow *action;
Json *params;
StdString adminsecret;
int result, secretindex;
ui = (ServerAdminUi *) uiPtr;
action = (ActionWindow *) widgetPtr;
if (! action->isConfirmed) {
return;
}
ui->lastSecretIndex = action->getStringValue (UiText::instance->getText (UiTextString::Password).capitalized (), "");
if (ui->lastSecretIndex.empty ()) {
return;
}
if (! ui->lastSecretIndex.parseInt (&secretindex)) {
return;
}
adminsecret = AgentControl::instance->getAdminSecretValue (secretindex);
params = new Json ();
params->set ("secret", adminsecret);
ui->retain ();
result = AgentControl::instance->invokeCommand (ui->agentId, App::instance->createCommand (SystemInterface::Command_SetAdminSecret, params), ServerAdminUi::setAdminSecretComplete, ui);
if (result != OsUtil::Result::Success) {
App::instance->uiStack.showSnackbar (UiText::instance->getText (UiTextString::InternalError));
ui->release ();
}
}
void ServerAdminUi::setAdminSecretComplete (void *uiPtr, int invokeResult, const StdString &invokeHostname, int invokeTcpPort, const StdString &agentId, Json *invokeCommand, Json *responseCommand) {
ServerAdminUi *ui;
StdString val;
int secretindex;
ui = (ServerAdminUi *) uiPtr;
if (responseCommand && (SystemInterface::instance->getCommandId (responseCommand) == SystemInterface::CommandId_CommandResult) && SystemInterface::instance->getCommandBooleanParam (responseCommand, "success", false)) {
val.assign (ui->lastSecretIndex);
ui->lastSecretIndex.assign ("");
if (! val.parseInt (&secretindex)) {
secretindex = -1;
}
AgentControl::instance->setAgentAuthorization (agentId, secretindex);
App::instance->uiStack.showSnackbar (UiText::instance->getText (UiTextString::ServerAdminUiSetPasswordCompleteMessage));
}
else {
App::instance->uiStack.showSnackbar (UiText::instance->getText (UiTextString::InternalError));
}
ui->release ();
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "rpcserver.h"
#include "init.h"
#include "net.h"
#include "netbase.h"
#include "timedata.h"
#include "util.h"
#include "wallet.h"
#include "walletdb.h"
using namespace std;
using namespace json_spirit;
int64_t nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
static void accountingDeprecationCheck()
{
if (!GetBoolArg("-enableaccounts", false))
throw runtime_error(
"Accounting API is deprecated and will be removed in future.\n"
"It can easily result in negative or odd balances if misused or misunderstood, which has happened in the field.\n"
"If you still want to enable it, add to your config file enableaccounts=1\n");
if (GetBoolArg("-staking", true))
throw runtime_error("If you want to use accounting API, staking must be disabled, add to your config file staking=0\n");
}
std::string HelpRequiringPassphrase()
{
return pwalletMain && pwalletMain->IsCrypted()
? "\nrequires wallet passphrase to be set with walletpassphrase first"
: "";
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if (fWalletUnlockStakingOnly)
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Wallet is unlocked for staking only.");
}
void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
int confirms = wtx.GetDepthInMainChain();
entry.push_back(Pair("confirmations", confirms));
if (wtx.IsCoinBase() || wtx.IsCoinStake())
entry.push_back(Pair("generated", true));
if (confirms > 0)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", (int64_t)(mapBlockIndex[wtx.hashBlock]->nTime)));
}
entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
entry.push_back(Pair("time", (int64_t)wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const Value& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
Value getnewpubkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewpubkey [account]\n"
"Returns new public key for coinbase generation.");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
return HexStr(newKey.begin(), newKey.end());
}
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress [account]\n"
"Returns a new CO2COIN address for receiving payments. "
"If [account] is specified, it is added to the address book "
"so payments received with the address will be credited to [account].");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey;
scriptPubKey.SetDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount);
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
Value getaccountaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress <account>\n"
"Returns the current CO2COIN address for receiving payments to this account.");
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
Value ret;
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount <co2coinaddress> <account>\n"
"Sets the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CO2COIN address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
string strOldAccount = pwalletMain->mapAddressBook[address.Get()];
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBookName(address.Get(), strAccount);
return Value::null;
}
Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount <co2coinaddress>\n"
"Returns the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CO2COIN address");
string strAccount;
map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
strAccount = (*mi).second;
return strAccount;
}
Value getaddressesbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount <account>\n"
"Returns the list of addresses for the given account.");
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
Array ret;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
Value sendtoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress <co2coinaddress> <amount> [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.000001"
+ HelpRequiringPassphrase());
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CO2COIN address");
// Amount
int64_t nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value listaddressgroupings(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listaddressgroupings\n"
"Lists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions");
Array jsonGroupings;
map<CTxDestination, int64_t> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
{
Array jsonGrouping;
BOOST_FOREACH(CTxDestination address, grouping)
{
Array addressInfo;
addressInfo.push_back(CBitcoinAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
LOCK(pwalletMain->cs_wallet);
if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
Value signmessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage <co2coinaddress> <message>\n"
"Sign a message with the private key of an address");
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress <co2coinaddress> [minconf=1]\n"
"Returns the total amount received by <co2coinaddress> in transactions with at least [minconf] confirmations.");
// Bitcoin address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
CScript scriptPubKey;
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CO2COIN address");
scriptPubKey.SetDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
int64_t nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !IsFinalTx(wtx))
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook)
{
const CTxDestination& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
setAddress.insert(address);
}
}
Value getreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount <account> [minconf=1]\n"
"Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
accountingDeprecationCheck();
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress;
GetAccountAddresses(strAccount, setAddress);
// Tally
int64_t nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !IsFinalTx(wtx))
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
int64_t GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
{
int64_t nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!IsFinalTx(wtx) || wtx.GetDepthInMainChain() < 0)
continue;
int64_t nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0)
nBalance += nReceived;
nBalance -= nSent + nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
int64_t GetAccountBalance(const string& strAccount, int nMinDepth)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth);
}
Value getbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getbalance [account] [minconf=1]\n"
"If [account] is not specified, returns the server's total available balance.\n"
"If [account] is specified, returns the balance in the account.");
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and getbalance '*' 0 should return the same number.
int64_t nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsTrusted())
continue;
int64_t allFee;
string strSentAccount;
list<pair<CTxDestination, int64_t> > listReceived;
list<pair<CTxDestination, int64_t> > listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount);
if (wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived)
nBalance += r.second;
}
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listSent)
nBalance -= r.second;
nBalance -= allFee;
}
return ValueFromAmount(nBalance);
}
accountingDeprecationCheck();
string strAccount = AccountFromValue(params[0]);
int64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
return ValueFromAmount(nBalance);
}
Value movecmd(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
"Move from one account in your wallet to another.");
accountingDeprecationCheck();
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
int64_t nAmount = AmountFromValue(params[2]);
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64_t nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
Value sendfrom(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom <fromaccount> <toco2coinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.000001"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CO2COIN address");
int64_t nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
int64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value sendmany(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
"amounts are double-precision floating point numbers"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
Object sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<CBitcoinAddress> setAddress;
vector<pair<CScript, int64_t> > vecSend;
int64_t totalAmount = 0;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid CO2COIN address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64_t nAmount = AmountFromValue(s.value_);
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
EnsureWalletIsUnlocked();
// Check funds
int64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
int64_t nFeeRequired = 0;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
if (!fCreated)
{
if (totalAmount + nFeeRequired > pwalletMain->GetBalance())
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction creation failed");
}
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
Value addmultisigaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
{
string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
"Add a nrequired-to-sign multisignature address to the wallet\"\n"
"each key is a CO2COIN address or hex-encoded public key\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %u keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CPubKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
// Case 1: Bitcoin address and we have full public key:
CBitcoinAddress address(ks);
if (pwalletMain && address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key",ks));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s",ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
// Case 2: hex public key
else if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
// Construct using pay-to-script-hash:
CScript inner;
inner.SetMultisig(nRequired, pubkeys);
CScriptID innerID = inner.GetID();
if (!pwalletMain->AddCScript(inner))
throw runtime_error("AddCScript() failed");
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
Value addredeemscript(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
{
string msg = "addredeemscript <redeemScript> [account]\n"
"Add a P2SH address with a specified redeemScript to the wallet.\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Construct using pay-to-script-hash:
vector<unsigned char> innerData = ParseHexV(params[0], "redeemScript");
CScript inner(innerData.begin(), innerData.end());
CScriptID innerID = inner.GetID();
if (!pwalletMain->AddCScript(inner))
throw runtime_error("AddCScript() failed");
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
struct tallyitem
{
int64_t nAmount;
int nConf;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
}
};
Value ListReceived(const Array& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !IsFinalTx(wtx))
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
}
}
// Reply
Array ret;
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
int64_t nAmount = 0;
int nConf = std::numeric_limits<int>::max();
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
}
else
{
Object obj;
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
int64_t nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
Object obj;
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
return ret;
}
Value listreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaddress [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include addresses that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"address\" : receiving address\n"
" \"account\" : the account of the receiving address\n"
" \"amount\" : total amount received by the address\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, false);
}
Value listreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaccount [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include accounts that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"account\" : the account of the receiving addresses\n"
" \"amount\" : total amount received by addresses with this account\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
accountingDeprecationCheck();
return ListReceived(params, true);
}
static void MaybePushAddress(Object & entry, const CTxDestination &dest)
{
CBitcoinAddress addr;
if (addr.Set(dest))
entry.push_back(Pair("address", addr.ToString()));
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
{
int64_t nFee;
string strSentAccount;
list<pair<CTxDestination, int64_t> > listReceived;
list<pair<CTxDestination, int64_t> > listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
bool fAllAccounts = (strAccount == string("*"));
// Sent
if ((!wtx.IsCoinStake()) && (!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent)
{
Object entry;
entry.push_back(Pair("account", strSentAccount));
MaybePushAddress(entry, s.first);
entry.push_back(Pair("category", "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
bool stop = false;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.first))
account = pwalletMain->mapAddressBook[r.first];
if (fAllAccounts || (account == strAccount))
{
Object entry;
entry.push_back(Pair("account", account));
MaybePushAddress(entry, r.first);
if (wtx.IsCoinBase() || wtx.IsCoinStake())
{
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
}
else
{
entry.push_back(Pair("category", "receive"));
}
if (!wtx.IsCoinStake())
entry.push_back(Pair("amount", ValueFromAmount(r.second)));
else
{
entry.push_back(Pair("amount", ValueFromAmount(-nFee)));
stop = true; // only one coinstake output
}
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
if (stop)
break;
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
Object entry;
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", (int64_t)acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
Value listtransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listtransactions [account] [count=10] [from=0]\n"
"Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
Array ret;
std::list<CAccountingEntry> acentries;
CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
Array::iterator first = ret.begin();
std::advance(first, nFrom);
Array::iterator last = ret.begin();
std::advance(last, nFrom+nCount);
if (last != ret.end()) ret.erase(last, ret.end());
if (first != ret.begin()) ret.erase(ret.begin(), first);
std::reverse(ret.begin(), ret.end()); // Return oldest to newest
return ret;
}
Value listaccounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"listaccounts [minconf=1]\n"
"Returns Object that has account names as keys, account balances as values.");
accountingDeprecationCheck();
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
map<string, int64_t> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first)) // This address belongs to me
mapAccountBalances[entry.second] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
int64_t nFee;
string strSentAccount;
list<pair<CTxDestination, int64_t> > listReceived;
list<pair<CTxDestination, int64_t> > listSent;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < 0)
continue;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent)
mapAccountBalances[strSentAccount] -= s.second;
if (nDepth >= nMinDepth && wtx.GetBlocksToMaturity() == 0)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.first))
mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
else
mapAccountBalances[""] += r.second;
}
}
list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret;
BOOST_FOREACH(const PAIRTYPE(string, int64_t)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
Value listsinceblock(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listsinceblock [blockhash] [target-confirmations]\n"
"Get all transactions in blocks since block [blockhash], or all transactions if omitted");
CBlockIndex *pindex = NULL;
int target_confirms = 1;
if (params.size() > 0)
{
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
pindex = CBlockLocator(blockId).GetBlockIndex();
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1;
Array transactions;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain() < depth)
ListTransactions(tx, "*", 0, true, transactions);
}
uint256 lastblock;
if (target_confirms == 1)
{
lastblock = hashBestChain;
}
else
{
int target_height = pindexBest->nHeight + 1 - target_confirms;
CBlockIndex *block;
for (block = pindexBest;
block && block->nHeight > target_height;
block = block->pprev) { }
lastblock = block ? block->GetBlockHash() : 0;
}
Object ret;
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
Value gettransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"gettransaction <txid>\n"
"Get detailed information about <txid>");
uint256 hash;
hash.SetHex(params[0].get_str());
Object entry;
if (pwalletMain->mapWallet.count(hash))
{
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
TxToJSON(wtx, 0, entry);
int64_t nCredit = wtx.GetCredit();
int64_t nDebit = wtx.GetDebit();
int64_t nNet = nCredit - nDebit;
int64_t nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe())
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
Array details;
ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details);
entry.push_back(Pair("details", details));
}
else
{
CTransaction tx;
uint256 hashBlock = 0;
if (GetTransaction(hash, tx, hashBlock))
{
TxToJSON(tx, 0, entry);
if (hashBlock == 0)
entry.push_back(Pair("confirmations", 0));
else
{
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
else
entry.push_back(Pair("confirmations", 0));
}
}
}
else
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
}
return entry;
}
Value backupwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet <destination>\n"
"Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return Value::null;
}
Value keypoolrefill(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"keypoolrefill [new-size]\n"
"Fills the keypool."
+ HelpRequiringPassphrase());
unsigned int nSize = max(GetArg("-keypool", 100), (int64_t)0);
if (params.size() > 0) {
if (params[0].get_int() < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size");
nSize = (unsigned int) params[0].get_int();
}
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool(nSize);
if (pwalletMain->GetKeyPoolSize() < nSize)
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return Value::null;
}
static void LockWallet(CWallet* pWallet)
{
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = 0;
pWallet->Lock();
}
Value walletpassphrase(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3))
throw runtime_error(
"walletpassphrase <passphrase> <timeout> [stakingonly]\n"
"Stores the wallet decryption key in memory for <timeout> seconds.\n"
"if [stakingonly] is true sending functions are disabled.");
if (fHelp)
return true;
if (!fServer)
throw JSONRPCError(RPC_SERVER_NOT_STARTED, "Error: RPC server was not started, use server=1 to change this.");
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() > 0)
{
if (!pwalletMain->Unlock(strWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
}
else
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
pwalletMain->TopUpKeyPool();
int64_t nSleepTime = params[1].get_int64();
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = GetTime() + nSleepTime;
RPCRunLater("lockwallet", boost::bind(LockWallet, pwalletMain), nSleepTime);
// ppcoin: if user OS account compromised prevent trivial sendmoney commands
if (params.size() > 2)
fWalletUnlockStakingOnly = params[2].get_bool();
else
fWalletUnlockStakingOnly = false;
return Value::null;
}
Value walletpassphrasechange(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return Value::null;
}
Value walletlock(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"Removes the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return Value::null;
}
Value encryptwallet(const Array& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; CO2COIN server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
// ppcoin: reserve balance from being staked for network protection
Value reservebalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"reservebalance [<reserve> [amount]]\n"
"<reserve> is true or false to turn balance reserve on or off.\n"
"<amount> is a real and rounded to cent.\n"
"Set reserve amount not participating in network protection.\n"
"If no parameters provided current setting is printed.\n");
if (params.size() > 0)
{
bool fReserve = params[0].get_bool();
if (fReserve)
{
if (params.size() == 1)
throw runtime_error("must provide amount to reserve balance.\n");
int64_t nAmount = AmountFromValue(params[1]);
nAmount = (nAmount / CENT) * CENT; // round to cent
if (nAmount < 0)
throw runtime_error("amount cannot be negative.\n");
nReserveBalance = nAmount;
}
else
{
if (params.size() > 1)
throw runtime_error("cannot specify amount to turn off reserve.\n");
nReserveBalance = 0;
}
}
Object result;
result.push_back(Pair("reserve", (nReserveBalance > 0)));
result.push_back(Pair("amount", ValueFromAmount(nReserveBalance)));
return result;
}
// ppcoin: check wallet integrity
Value checkwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"checkwallet\n"
"Check wallet for integrity.\n");
int nMismatchSpent;
int64_t nBalanceInQuestion;
pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion, true);
Object result;
if (nMismatchSpent == 0)
result.push_back(Pair("wallet check passed", true));
else
{
result.push_back(Pair("mismatched spent coins", nMismatchSpent));
result.push_back(Pair("amount in question", ValueFromAmount(nBalanceInQuestion)));
}
return result;
}
// ppcoin: repair wallet
Value repairwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"repairwallet\n"
"Repair wallet if checkwallet reports any problem.\n");
int nMismatchSpent;
int64_t nBalanceInQuestion;
pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion);
Object result;
if (nMismatchSpent == 0)
result.push_back(Pair("wallet check passed", true));
else
{
result.push_back(Pair("mismatched spent coins", nMismatchSpent));
result.push_back(Pair("amount affected by repair", ValueFromAmount(nBalanceInQuestion)));
}
return result;
}
// NovaCoin: resend unconfirmed wallet transactions
Value resendtx(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"resendtx\n"
"Re-send unconfirmed transactions.\n"
);
ResendWalletTransactions(true);
return Value::null;
}
// ppcoin: make a public-private key pair
Value makekeypair(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"makekeypair [prefix]\n"
"Make a public/private key pair.\n"
"[prefix] is optional preferred prefix for the public key.\n");
string strPrefix = "";
if (params.size() > 0)
strPrefix = params[0].get_str();
CKey key;
key.MakeNewKey(false);
CPrivKey vchPrivKey = key.GetPrivKey();
Object result;
result.push_back(Pair("PrivateKey", HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end())));
result.push_back(Pair("PublicKey", HexStr(key.GetPubKey())));
return result;
}
Value settxfee(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE)
throw runtime_error(
"settxfee <amount>\n"
"<amount> is a real and is rounded to the nearest 0.01");
nTransactionFee = AmountFromValue(params[0]);
nTransactionFee = (nTransactionFee / CENT) * CENT; // round to cent
return true;
}
|
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_browser_view.h"
#include <vector>
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/browser.h"
#include "shell/browser/native_browser_view.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "ui/gfx/geometry/rect.h"
namespace gin {
template <>
struct Converter<electron::AutoResizeFlags> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::AutoResizeFlags* auto_resize_flags) {
gin_helper::Dictionary params;
if (!ConvertFromV8(isolate, val, ¶ms)) {
return false;
}
uint8_t flags = 0;
bool width = false;
if (params.Get("width", &width) && width) {
flags |= electron::kAutoResizeWidth;
}
bool height = false;
if (params.Get("height", &height) && height) {
flags |= electron::kAutoResizeHeight;
}
bool horizontal = false;
if (params.Get("horizontal", &horizontal) && horizontal) {
flags |= electron::kAutoResizeHorizontal;
}
bool vertical = false;
if (params.Get("vertical", &vertical) && vertical) {
flags |= electron::kAutoResizeVertical;
}
*auto_resize_flags = static_cast<electron::AutoResizeFlags>(flags);
return true;
}
};
} // namespace gin
namespace {
int32_t GetNextId() {
static int32_t next_id = 1;
return next_id++;
}
} // namespace
namespace electron {
namespace api {
gin::WrapperInfo BrowserView::kWrapperInfo = {gin::kEmbedderNativeGin};
BrowserView::BrowserView(gin::Arguments* args,
const gin_helper::Dictionary& options)
: id_(GetNextId()) {
v8::Isolate* isolate = args->isolate();
gin_helper::Dictionary web_preferences =
gin::Dictionary::CreateEmpty(isolate);
options.Get(options::kWebPreferences, &web_preferences);
web_preferences.Set("type", "browserView");
v8::Local<v8::Value> value;
// Copy the webContents option to webPreferences. This is only used internally
// to implement nativeWindowOpen option.
if (options.Get("webContents", &value)) {
web_preferences.SetHidden("webContents", value);
}
auto web_contents =
WebContents::CreateFromWebPreferences(args->isolate(), web_preferences);
web_contents_.Reset(isolate, web_contents.ToV8());
api_web_contents_ = web_contents.get();
api_web_contents_->AddObserver(this);
Observe(web_contents->web_contents());
view_.reset(
NativeBrowserView::Create(api_web_contents_->inspectable_web_contents()));
}
void BrowserView::SetOwnerWindow(NativeWindow* window) {
// Ensure WebContents and BrowserView owner windows are in sync.
if (web_contents())
web_contents()->SetOwnerWindow(window);
owner_window_ = window ? window->GetWeakPtr() : nullptr;
}
BrowserView::~BrowserView() {
if (web_contents()) { // destroy() called without closing WebContents
web_contents()->RemoveObserver(this);
web_contents()->Destroy();
}
}
void BrowserView::WebContentsDestroyed() {
api_web_contents_ = nullptr;
web_contents_.Reset();
Unpin();
}
void BrowserView::OnDraggableRegionsUpdated(
const std::vector<mojom::DraggableRegionPtr>& regions) {
view_->UpdateDraggableRegions(regions);
}
// static
gin::Handle<BrowserView> BrowserView::New(gin_helper::ErrorThrower thrower,
gin::Arguments* args) {
if (!Browser::Get()->is_ready()) {
thrower.ThrowError("Cannot create BrowserView before app is ready");
return gin::Handle<BrowserView>();
}
gin::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate());
args->GetNext(&options);
auto handle =
gin::CreateHandle(args->isolate(), new BrowserView(args, options));
handle->Pin(args->isolate());
return handle;
}
void BrowserView::SetAutoResize(AutoResizeFlags flags) {
view_->SetAutoResizeFlags(flags);
}
void BrowserView::SetBounds(const gfx::Rect& bounds) {
view_->SetBounds(bounds);
}
gfx::Rect BrowserView::GetBounds() {
return view_->GetBounds();
}
void BrowserView::SetBackgroundColor(const std::string& color_name) {
if (!web_contents())
return;
auto* wc = web_contents()->web_contents();
wc->SetPageBaseBackgroundColor(ParseHexColor(color_name));
}
v8::Local<v8::Value> BrowserView::GetWebContents(v8::Isolate* isolate) {
if (web_contents_.IsEmpty()) {
return v8::Null(isolate);
}
return v8::Local<v8::Value>::New(isolate, web_contents_);
}
// static
v8::Local<v8::ObjectTemplate> BrowserView::FillObjectTemplate(
v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
return gin::ObjectTemplateBuilder(isolate, "BrowserView", templ)
.SetMethod("setAutoResize", &BrowserView::SetAutoResize)
.SetMethod("setBounds", &BrowserView::SetBounds)
.SetMethod("getBounds", &BrowserView::GetBounds)
.SetMethod("setBackgroundColor", &BrowserView::SetBackgroundColor)
.SetProperty("webContents", &BrowserView::GetWebContents)
.Build();
}
} // namespace api
} // namespace electron
namespace {
using electron::api::BrowserView;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("BrowserView", BrowserView::GetConstructor(context));
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_browser_view, Initialize)
|
//
// VRODiffuseIrradianceTest.cpp
// ViroKit
//
// Created by Raj Advani on 1/18/18.
// Copyright © 2018 Viro Media. All rights reserved.
//
// 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 "VRODiffuseIrradianceTest.h"
#include "VROTestUtil.h"
#include "VROCompress.h"
#include "VROSphere.h"
VRODiffuseIrradianceTest::VRODiffuseIrradianceTest() :
VRORendererTest(VRORendererTestType::PBRDirect) {
_angle = 0;
_textureIndex = 0;
}
VRODiffuseIrradianceTest::~VRODiffuseIrradianceTest() {
}
void VRODiffuseIrradianceTest::build(std::shared_ptr<VRORenderer> renderer,
std::shared_ptr<VROFrameSynchronizer> frameSynchronizer,
std::shared_ptr<VRODriver> driver) {
_sceneController = std::make_shared<VROARSceneController>();
std::shared_ptr<VROScene> scene = _sceneController->getScene();
std::shared_ptr<VROPortal> rootNode = scene->getRootNode();
rootNode->setPosition({0, 0, 0});
nextEnvironment();
VROVector3f lightPositions[] = {
VROVector3f(-10, 10, 10),
VROVector3f( 10, 10, 10),
VROVector3f(-10, -10, 10),
VROVector3f( 10, -10, 10),
};
float intensity = 300;
VROVector3f lightColors[] = {
VROVector3f(1, 1, 1),
VROVector3f(1, 1, 1),
VROVector3f(1, 1, 1),
VROVector3f(1, 1, 1),
};
int rows = 7;
int columns = 7;
float spacing = 2.5;
std::shared_ptr<VRONode> sphereContainerNode = std::make_shared<VRONode>();
// Render an array of spheres, varying roughness and metalness
for (int row = 0; row < rows; ++row) {
float radius = 1;
float metalness = (float) row / (float) rows;
for (int col = 0; col < columns; ++col) {
// Clamp the roughness to [0.05, 1.0] as perfectly smooth surfaces (roughness of 0.0)
// tend to look off on direct lighting
float roughness = VROMathClamp((float) col / (float) columns, 0.05, 1.0);
std::shared_ptr<VROSphere> sphere = VROSphere::createSphere(radius, 20, 20, true);
const std::shared_ptr<VROMaterial> &material = sphere->getMaterials().front();
material->getDiffuse().setColor({ 0.5, 0.5, 0.5, 1.0 });
material->getRoughness().setColor({ roughness, 1.0, 1.0, 1.0 });
material->getMetalness().setColor({ metalness, 1.0, 1.0, 1.0 });
material->getAmbientOcclusion().setColor({ 1.0, 1.0, 1.0, 1.0 });
material->setLightingModel(VROLightingModel::PhysicallyBased);
std::shared_ptr<VRONode> sphereNode = std::make_shared<VRONode>();
sphereNode->setPosition({ (float)(col - (columns / 2)) * spacing,
(float)(row - (rows / 2)) * spacing,
0.0f });
sphereNode->setGeometry(sphere);
sphereContainerNode->addChildNode(sphereNode);
}
}
rootNode->addChildNode(sphereContainerNode);
_eventDelegate = std::make_shared<VROIBLEventDelegate>(scene, this);
_eventDelegate->setEnabledEvent(VROEventDelegate::EventAction::OnClick, true);
sphereContainerNode->setEventDelegate(_eventDelegate);
// Render the light sources as spheres as well
for (unsigned int i = 0; i < sizeof(lightPositions) / sizeof(lightPositions[0]); ++i) {
std::shared_ptr<VROLight> light = std::make_shared<VROLight>(VROLightType::Omni);
light->setColor(lightColors[i]);
light->setPosition(lightPositions[i]);
light->setAttenuationStartDistance(20);
light->setAttenuationEndDistance(30);
light->setIntensity(intensity);
rootNode->addLight(light);
}
std::shared_ptr<VRONodeCamera> camera = std::make_shared<VRONodeCamera>();
std::shared_ptr<VRONode> cameraNode = std::make_shared<VRONode>();
cameraNode->setPosition({ 0, 0, 20 }); // 9 is good for VR, for for Scene we push further back
cameraNode->setCamera(camera);
rootNode->addChildNode(cameraNode);
std::shared_ptr<VROAction> action = VROAction::perpetualPerFrameAction([this] (VRONode *const node, float seconds) {
_angle += .0015;
node->setRotation({ 0, _angle, 0});
return true;
});
//sphereContainerNode->runAction(action);
_pointOfView = cameraNode;
}
void VRODiffuseIrradianceTest::nextEnvironment() {
std::shared_ptr<VROTexture> environment;
if (_textureIndex == 0) {
environment = VROTestUtil::loadRadianceHDRTexture("san_giuseppe_bridge_1k");
} else if (_textureIndex == 1) {
environment = VROTestUtil::loadRadianceHDRTexture("ibl_newport_loft");
} else if (_textureIndex == 2) {
environment = VROTestUtil::loadRadianceHDRTexture("ibl_ridgecrest_road");
} else if (_textureIndex == 3) {
environment = VROTestUtil::loadRadianceHDRTexture("ibl_wooden_door");
} else if (_textureIndex == 4) {
environment = VROTestUtil::loadRadianceHDRTexture("ibl_mans_outside");
}
std::shared_ptr<VROScene> scene = _sceneController->getScene();
scene->getRootNode()->setLightingEnvironment(environment);
scene->getRootNode()->setBackgroundSphere(environment);
_textureIndex = (_textureIndex + 1) % 5;
}
void VROIBLEventDelegate::onClick(int source, std::shared_ptr<VRONode> node, ClickState clickState,
std::vector<float> position) {
if (clickState != Clicked) {
return;
}
_test->nextEnvironment();
}
|
// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/extensions/browser/xwalk_extension_function_handler.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "xwalk/extensions/common/xwalk_external_instance.h"
namespace xwalk {
namespace extensions {
XWalkExtensionFunctionInfo::XWalkExtensionFunctionInfo(
const std::string& name,
std::unique_ptr<base::ListValue> arguments,
const PostResultCallback& post_result_cb)
: name_(name),
arguments_(std::move(arguments)),
post_result_cb_(post_result_cb) {}
XWalkExtensionFunctionInfo::~XWalkExtensionFunctionInfo() {}
XWalkExtensionFunctionHandler::XWalkExtensionFunctionHandler(
XWalkExtensionInstance* instance)
: instance_(instance),
weak_factory_(this) {}
XWalkExtensionFunctionHandler::~XWalkExtensionFunctionHandler() {}
void XWalkExtensionFunctionHandler::HandleMessage(std::unique_ptr<base::Value> msg) {
base::ListValue* args;
if (!msg->GetAsList(&args) || args->GetSize() < 2) {
// FIXME(tmpsantos): This warning could be better if the Context had a
// pointer to the Extension. We could tell what extension sent the
// invalid message.
LOG(WARNING) << "Invalid number of arguments.";
return;
}
// The first parameter stands for the function signature.
std::string function_name;
if (!args->GetString(0, &function_name)) {
LOG(WARNING) << "The function name is not a string.";
return;
}
// The second parameter stands for callback id, the remaining
// ones are the function arguments.
std::string callback_id;
if (!args->GetString(1, &callback_id)) {
LOG(WARNING) << "The callback id is not a string.";
return;
}
// We reuse args to pass the extra arguments to the handler, so remove
// function_name and callback_id from it.
args->Remove(0, NULL);
args->Remove(0, NULL);
std::unique_ptr<XWalkExtensionFunctionInfo> info(
new XWalkExtensionFunctionInfo(
function_name,
base::WrapUnique(static_cast<base::ListValue*>(msg.release())),
base::Bind(&XWalkExtensionFunctionHandler::DispatchResult,
weak_factory_.GetWeakPtr(),
base::ThreadTaskRunnerHandle::IsSet()
? base::ThreadTaskRunnerHandle::Get()
: nullptr,
callback_id)));
if (!HandleFunction(std::move(info))) {
DLOG(WARNING) << "Function not registered: " << function_name;
return;
}
}
bool XWalkExtensionFunctionHandler::HandleFunction(
std::unique_ptr<XWalkExtensionFunctionInfo> info) {
FunctionHandlerMap::iterator iter = handlers_.find(info->name());
if (iter == handlers_.end())
return false;
iter->second.Run(std::move(info));
return true;
}
// static
void XWalkExtensionFunctionHandler::DispatchResult(
const base::WeakPtr<XWalkExtensionFunctionHandler>& handler,
scoped_refptr<base::SingleThreadTaskRunner> client_task_runner,
const std::string& callback_id,
std::unique_ptr<base::ListValue> result) {
DCHECK(result);
// The client_task_runner.get() call is to support using this class on a
// thread without a message loop.
if (client_task_runner.get() &&
!client_task_runner->BelongsToCurrentThread()) {
client_task_runner->PostTask(FROM_HERE,
base::Bind(&XWalkExtensionFunctionHandler::DispatchResult,
handler,
client_task_runner,
callback_id,
base::Passed(&result)));
return;
}
if (callback_id.empty()) {
DLOG(WARNING) << "Sending a reply with an empty callback id has no"
"practical effect. This code can be optimized by not creating "
"and not posting the result.";
return;
}
// Prepend the callback id to the list, so the handlers
// on the JavaScript side know which callback should be evoked.
result->Insert(0, base::MakeUnique<base::Value>(callback_id));
if (handler)
handler->PostMessageToInstance(std::move(result));
}
void XWalkExtensionFunctionHandler::PostMessageToInstance(
std::unique_ptr<base::Value> msg) {
instance_->PostMessageToJS(std::move(msg));
}
} // namespace extensions
} // namespace xwalk
|
#pragma data_seg(".shader")
const char* post =
"#version 130\n"
"uniform sampler2D f;"
"out vec4 v;"
"float t(float f)"
"{"
"return fract(sin(dot(f,12.9898))*43758.5);"
"}"
"void main()"
"{"
"v=vec4(0);"
"for(int s=0;s<25;s++)"
"{"
"vec2 i=gl_FragCoord.xy/vec2(1280,720);"
"float d=t(float(s+dot(i,i))),o=t(float(1-s+dot(i,i)));"
"vec2 m=.01*(-1+2*vec2(d,o));"
"v+=vec4(textureLod(f,i,(.3+.7*d)*texture(f,(1+m)*i).w*8).xyz,1);"
"}"
"v/=vec4(25);"
"}";
|
#include "Runtime/Character/CAdditiveBodyState.hpp"
#include "Runtime/CStateManager.hpp"
#include "Runtime/Character/CBodyController.hpp"
#include "Runtime/Character/CAnimTreeNode.hpp"
#include "Runtime/Character/CPASDatabase.hpp"
#include "Runtime/Character/CPASAnimParmData.hpp"
namespace urde {
void CABSAim::Start(CBodyController& bc, CStateManager& mgr) {
// const CBCAdditiveAimCmd* cmd =
// static_cast<const CBCAdditiveAimCmd*>(bc.GetCommandMgr().GetCmd(EBodyStateCmd::AdditiveAim));
const CPASAnimState* aimState = bc.GetPASDatabase().GetAnimState(22);
// Left, Right, Up, Down
for (int i = 0; i < 4; ++i) {
CPASAnimParmData parms(22, CPASAnimParm::FromEnum(i));
std::pair<float, s32> best = bc.GetPASDatabase().FindBestAnimation(parms, *mgr.GetActiveRandom(), -1);
x8_anims[i] = best.second;
x18_angles[i] = zeus::degToRad(aimState->GetAnimParmData(x8_anims[i], 1).GetReal32Value());
}
const CAnimData& animData = *bc.GetOwner().GetModelData()->GetAnimationData();
x28_hWeight = -animData.GetAdditiveAnimationWeight(x8_anims[0]);
x28_hWeight += animData.GetAdditiveAnimationWeight(x8_anims[1]);
x30_vWeight = -animData.GetAdditiveAnimationWeight(x8_anims[2]);
x30_vWeight += animData.GetAdditiveAnimationWeight(x8_anims[3]);
x4_needsIdle = false;
if (bc.GetCommandMgr().GetCmd(EBodyStateCmd::AdditiveIdle))
x4_needsIdle = true;
}
pas::EAnimationState CABSAim::GetBodyStateTransition(float dt, CBodyController& bc) const {
if (bc.GetCommandMgr().GetCmd(EBodyStateCmd::AdditiveReaction))
return pas::EAnimationState::AdditiveReaction;
if (bc.GetCommandMgr().GetCmd(EBodyStateCmd::AdditiveFlinch))
return pas::EAnimationState::AdditiveFlinch;
if (bc.GetCommandMgr().GetCmd(EBodyStateCmd::AdditiveIdle) || x4_needsIdle)
return pas::EAnimationState::AdditiveIdle;
return pas::EAnimationState::Invalid;
}
pas::EAnimationState CABSAim::UpdateBody(float dt, CBodyController& bc, CStateManager& mgr) {
const pas::EAnimationState st = GetBodyStateTransition(dt, bc);
if (st == pas::EAnimationState::Invalid) {
const zeus::CVector3f& target = bc.GetCommandMgr().GetAdditiveTargetVector();
if (target.canBeNormalized()) {
CAnimData& animData = *bc.GetOwner().GetModelData()->GetAnimationData();
float hAngle = zeus::clamp(-x18_angles[0], std::atan2(target.x(), target.y()), x18_angles[1]);
hAngle *= 0.63661975f;
hAngle = zeus::clamp(-3.f, (hAngle - x28_hWeight) * 0.25f / dt, 3.f);
x2c_hWeightVel += dt * zeus::clamp(-10.f, (hAngle - x2c_hWeightVel) / dt, 10.f);
float hypotenuse = std::sqrt(target.y() * target.y() + target.x() * target.x());
float vAngle = zeus::clamp(-x18_angles[3], std::atan2(target.z(), hypotenuse), x18_angles[2]);
vAngle *= 0.63661975f;
vAngle = zeus::clamp(-3.f, (vAngle - x30_vWeight) * 0.25f / dt, 3.f);
x34_vWeightVel += dt * zeus::clamp(-10.f, (vAngle - x34_vWeightVel) / dt, 10.f);
float newHWeight = dt * x2c_hWeightVel + x28_hWeight;
if (newHWeight != x28_hWeight) {
if (std::fabs(x28_hWeight) > 0.f && x28_hWeight * newHWeight <= 0.f)
animData.DelAdditiveAnimation(x8_anims[x28_hWeight < 0.f ? 0 : 1]);
float absWeight = std::fabs(newHWeight);
if (absWeight > 0.f)
animData.AddAdditiveAnimation(x8_anims[newHWeight < 0.f ? 0 : 1], absWeight, false, false);
}
float newVWeight = dt * x34_vWeightVel + x30_vWeight;
if (newVWeight != x30_vWeight) {
if (std::fabs(x30_vWeight) > 0.f && x30_vWeight * newVWeight <= 0.f)
animData.DelAdditiveAnimation(x8_anims[x30_vWeight > 0.f ? 2 : 3]);
float absWeight = std::fabs(newVWeight);
if (absWeight > 0.f)
animData.AddAdditiveAnimation(x8_anims[newVWeight > 0.f ? 2 : 3], absWeight, false, false);
}
x28_hWeight = newHWeight;
x30_vWeight = newVWeight;
}
}
return st;
}
void CABSAim::Shutdown(CBodyController& bc) {
CAnimData& animData = *bc.GetOwner().GetModelData()->GetAnimationData();
if (x28_hWeight != 0.f)
animData.DelAdditiveAnimation(x8_anims[x28_hWeight < 0.f ? 0 : 1]);
if (x30_vWeight != 0.f)
animData.DelAdditiveAnimation(x8_anims[x30_vWeight > 0.f ? 2 : 3]);
}
void CABSFlinch::Start(CBodyController& bc, CStateManager& mgr) {
const CBCAdditiveFlinchCmd* cmd =
static_cast<const CBCAdditiveFlinchCmd*>(bc.GetCommandMgr().GetCmd(EBodyStateCmd::AdditiveFlinch));
x4_weight = cmd->GetWeight();
CPASAnimParmData parms(23);
std::pair<float, s32> best = bc.GetPASDatabase().FindBestAnimation(parms, *mgr.GetActiveRandom(), -1);
x8_anim = best.second;
CAnimData& animData = *bc.GetOwner().GetModelData()->GetAnimationData();
animData.AddAdditiveAnimation(x8_anim, x4_weight, false, true);
}
pas::EAnimationState CABSFlinch::GetBodyStateTransition(float dt, CBodyController& bc) const {
if (bc.GetCommandMgr().GetCmd(EBodyStateCmd::AdditiveReaction))
return pas::EAnimationState::AdditiveReaction;
return pas::EAnimationState::Invalid;
}
pas::EAnimationState CABSFlinch::UpdateBody(float dt, CBodyController& bc, CStateManager& mgr) {
const pas::EAnimationState st = GetBodyStateTransition(dt, bc);
if (st == pas::EAnimationState::Invalid) {
CAnimData& animData = *bc.GetOwner().GetModelData()->GetAnimationData();
CCharAnimTime rem = animData.GetAdditiveAnimationTree(x8_anim)->VGetTimeRemaining();
if (std::fabs(rem.GetSeconds()) < 0.00001f)
return pas::EAnimationState::AdditiveIdle;
}
return st;
}
pas::EAnimationState CABSIdle::GetBodyStateTransition(float dt, CBodyController& bc) const {
if (bc.GetCommandMgr().GetCmd(EBodyStateCmd::AdditiveReaction))
return pas::EAnimationState::AdditiveReaction;
if (bc.GetCommandMgr().GetCmd(EBodyStateCmd::AdditiveFlinch))
return pas::EAnimationState::AdditiveFlinch;
if (bc.GetCommandMgr().GetCmd(EBodyStateCmd::AdditiveAim))
return pas::EAnimationState::AdditiveAim;
return pas::EAnimationState::Invalid;
}
pas::EAnimationState CABSIdle::UpdateBody(float dt, CBodyController& bc, CStateManager& mgr) {
return GetBodyStateTransition(dt, bc);
}
void CABSReaction::Start(CBodyController& bc, CStateManager& mgr) {
const CBCAdditiveReactionCmd* cmd =
static_cast<const CBCAdditiveReactionCmd*>(bc.GetCommandMgr().GetCmd(EBodyStateCmd::AdditiveReaction));
x4_weight = cmd->GetWeight();
xc_type = cmd->GetType();
x10_active = cmd->GetIsActive();
CPASAnimParmData parms(24, CPASAnimParm::FromEnum(s32(xc_type)));
std::pair<float, s32> best = bc.GetPASDatabase().FindBestAnimation(parms, *mgr.GetActiveRandom(), -1);
x8_anim = best.second;
if (x8_anim != -1) {
CAnimData& animData = *bc.GetOwner().GetModelData()->GetAnimationData();
animData.AddAdditiveAnimation(x8_anim, x4_weight, x10_active, false);
}
}
pas::EAnimationState CABSReaction::GetBodyStateTransition(float dt, CBodyController& bc) const {
if (bc.GetCommandMgr().GetCmd(EBodyStateCmd::AdditiveReaction) && xc_type == pas::EAdditiveReactionType::IceBreakout)
return pas::EAnimationState::AdditiveReaction;
return pas::EAnimationState::Invalid;
}
pas::EAnimationState CABSReaction::UpdateBody(float dt, CBodyController& bc, CStateManager& mgr) {
const pas::EAnimationState st = GetBodyStateTransition(dt, bc);
if (st == pas::EAnimationState::Invalid) {
if (x8_anim == -1)
return pas::EAnimationState::AdditiveIdle;
CAnimData& animData = *bc.GetOwner().GetModelData()->GetAnimationData();
if (x10_active) {
if (bc.GetCommandMgr().GetCmd(EBodyStateCmd::StopReaction)) {
StopAnimation(bc);
bc.GetOwner().RemoveEmitter();
return pas::EAnimationState::AdditiveIdle;
}
} else {
if (animData.IsAdditiveAnimationAdded(x8_anim)) {
CCharAnimTime rem = animData.GetAdditiveAnimationTree(x8_anim)->VGetTimeRemaining();
if (std::fabs(rem.GetSeconds()) < 0.00001f) {
StopAnimation(bc);
return pas::EAnimationState::AdditiveIdle;
}
} else {
return pas::EAnimationState::AdditiveIdle;
}
}
}
return st;
}
void CABSReaction::StopAnimation(CBodyController& bc) {
if (x8_anim != -1) {
CAnimData& animData = *bc.GetOwner().GetModelData()->GetAnimationData();
animData.DelAdditiveAnimation(x8_anim);
x8_anim = -1;
}
}
} // namespace urde
|
// Copyright (c) 2001-2011 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(BOOST_SPIRIT_KARMA_AUTO_NOV_29_2009_0339PM)
#define BOOST_SPIRIT_KARMA_AUTO_NOV_29_2009_0339PM
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/spirit/home/support/common_terminals.hpp>
#include <boost/spirit/home/support/info.hpp>
#include <boost/spirit/home/support/container.hpp>
#include <boost/spirit/home/support/assert_msg.hpp>
#include <boost/spirit/home/support/detail/hold_any.hpp>
#include <boost/spirit/home/karma/domain.hpp>
#include <boost/spirit/home/karma/meta_compiler.hpp>
#include <boost/spirit/home/karma/delimit_out.hpp>
#include <boost/spirit/home/karma/generator.hpp>
#include <boost/spirit/home/karma/auto/create_generator.hpp>
#include <boost/mpl/bool.hpp>
///////////////////////////////////////////////////////////////////////////////
namespace boost { namespace spirit
{
///////////////////////////////////////////////////////////////////////////
// Enablers
///////////////////////////////////////////////////////////////////////////
template <>
struct use_terminal<karma::domain, tag::auto_> // enables auto_
: mpl::true_ {};
template <typename A0>
struct use_terminal<karma::domain // enables auto_(...)
, terminal_ex<tag::auto_, fusion::vector1<A0> >
> : mpl::true_ {};
template <> // enables auto_(f)
struct use_lazy_terminal<
karma::domain, tag::auto_, 1 /*arity*/
> : mpl::true_ {};
}}
///////////////////////////////////////////////////////////////////////////////
namespace boost { namespace spirit { namespace karma
{
#ifndef BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
using spirit::auto_;
#endif
using spirit::auto_type;
///////////////////////////////////////////////////////////////////////////
template <typename Modifiers>
struct auto_generator
: generator<auto_generator<Modifiers> >
{
typedef mpl::int_<generator_properties::all_properties> properties;
template <typename Context, typename Unused>
struct attribute
{
typedef spirit::basic_hold_any<char> type;
};
auto_generator(Modifiers const& modifiers)
: modifiers_(modifiers) {}
// auto_generator has an attached attribute
template <
typename OutputIterator, typename Context, typename Delimiter
, typename Attribute>
bool generate(OutputIterator& sink, Context& context
, Delimiter const& d, Attribute const& attr) const
{
return compile<karma::domain>(create_generator<Attribute>(), modifiers_)
.generate(sink, context, d, attr);
}
// this auto_generator has no attribute attached, it needs to have been
// initialized from a value/variable
template <typename OutputIterator, typename Context
, typename Delimiter>
static bool
generate(OutputIterator&, Context&, Delimiter const&, unused_type)
{
// It is not possible (doesn't make sense) to use auto_ generators
// without providing any attribute, as the generator doesn't 'know'
// what to output. The following assertion fires if this situation
// is detected in your code.
BOOST_SPIRIT_ASSERT_FAIL(OutputIterator, auto_not_usable_without_attribute, ());
return false;
}
template <typename Context>
info what(Context& /*context*/) const
{
return info("auto_");
}
Modifiers modifiers_;
};
///////////////////////////////////////////////////////////////////////////
template <typename T, typename Modifiers>
struct lit_auto_generator
: generator<lit_auto_generator<T, Modifiers> >
{
typedef mpl::int_<generator_properties::all_properties> properties;
template <typename Context, typename Unused>
struct attribute
{
typedef unused_type type;
};
lit_auto_generator(typename add_reference<T>::type t, Modifiers const& modifiers)
: t_(t)
, generator_(compile<karma::domain>(create_generator<T>(), modifiers))
{}
// auto_generator has an attached attribute
template <
typename OutputIterator, typename Context, typename Delimiter
, typename Attribute>
bool generate(OutputIterator& sink, Context& context
, Delimiter const& d, Attribute const&) const
{
return generator_.generate(sink, context, d, t_);
}
template <typename Context>
info what(Context& /*context*/) const
{
return info("auto_");
}
typedef typename spirit::result_of::create_generator<T>::type
generator_type;
typedef typename spirit::result_of::compile<
karma::domain, generator_type, Modifiers>::type generator_impl_type;
T t_;
generator_impl_type generator_;
private:
// silence MSVC warning C4512: assignment operator could not be generated
lit_auto_generator& operator= (lit_auto_generator const&);
};
///////////////////////////////////////////////////////////////////////////
// Generator generators: make_xxx function (objects)
///////////////////////////////////////////////////////////////////////////
// auto_
template <typename Modifiers>
struct make_primitive<tag::auto_, Modifiers>
{
typedef auto_generator<Modifiers> result_type;
result_type operator()(unused_type, Modifiers const& modifiers) const
{
return result_type(modifiers);
}
};
// auto_(...)
template <typename Modifiers, typename A0>
struct make_primitive<
terminal_ex<tag::auto_, fusion::vector1<A0> >, Modifiers>
{
typedef typename add_const<A0>::type const_attribute;
typedef lit_auto_generator<const_attribute, Modifiers> result_type;
template <typename Terminal>
result_type operator()(Terminal const& term, Modifiers const& modifiers) const
{
return result_type(fusion::at_c<0>(term.args), modifiers);
}
};
}}}
#endif
|
#include "testtlrucache.h"
#include "mere/cache/tlrucache.hpp"
void TestTLRUCache::initTestCase()
{
}
void TestTLRUCache::cleanupTestCase()
{
}
void TestTLRUCache::testset()
{
}
void TestTLRUCache::testevict()
{
}
|
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.
Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.
Solution :
class Solution {
public:
int mySqrt(int x) {
if(x<2)
return x;
long long int res;
long long int start = 1;
long long int end = x/2;
while(start<=end)
{
long long int mid = start + (end-start)/2;
if(mid*mid==x)
return mid;
else if(mid*mid<x)
{
start = mid+1;
res = mid;
}
else
end = mid-1;
}
return res;
}
};
|
///////////////////////////////////////////////////////////////////////////////
///
/// Authors: Joshua Davis
/// Copyright 2015, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#pragma once
namespace Zero
{
class HeightMap;
class UpdateEvent;
//-------------------------------------------------------------------HeightMapDebugDrawer
/// Helper class to draw information about a height map. Currently draws
/// triangles and is used by other debug helper classes.
class HeightMapDebugDrawer : public Component
{
public:
ZilchDeclareType(HeightMapDebugDrawer, TypeCopyMode::ReferenceType);
HeightMapDebugDrawer();
void Serialize(Serializer& stream) override;
void Initialize(CogInitializer& initializer) override;
void DebugDraw() override;
void DrawPatch(IntVec2Param patchIndex);
void DrawCell(IntVec2Param patchIndex, IntVec2Param cellIndex, bool skippedCell);
void DrawRayProjection(Vec3Param start, Vec3Param dir, float maxT);
void DrawAabbProjection(const Aabb& aabb);
bool mDrawTriangles;
real mDrawOffset;
HeightMap* mMap;
Transform* mTransform;
};
//-------------------------------------------------------------------HeightMapAabbChecker
/// Helper class to debug iterating over all triangles within an aabb. Uses the aabb of
/// the current object to test against the height-map specified by the given cogpath property.
class HeightMapAabbChecker : public Component
{
public:
ZilchDeclareType(HeightMapAabbChecker, TypeCopyMode::ReferenceType);
HeightMapAabbChecker();
void Serialize(Serializer& stream) override;
void Initialize(CogInitializer& initializer) override;
void OnAllObjectsCreated(CogInitializer& initializer) override;
void OnFrameUpdate(UpdateEvent* e);
void Draw();
CogPath mHeightMapPath;
bool mDrawHeightMap;
bool mSkipNonCollidingCells;
};
}//namespace Zero
|
// Copyright (C) 2009, 2016 Tim Blechmann
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_LOCKFREE_PREFIX_HPP_INCLUDED
#define BOOST_LOCKFREE_PREFIX_HPP_INCLUDED
/* this file defines the following macros:
BOOST_LOCKFREE_CACHELINE_BYTES: size of a cache line
BOOST_LOCKFREE_PTR_COMPRESSION: use tag/pointer compression to utilize parts
of the virtual address space as tag (at least 16bit)
*/
// PowerPC caches support 128-byte cache lines.
#if defined(powerpc) || defined(__powerpc__) || defined(__ppc__)
#define BOOST_LOCKFREE_CACHELINE_BYTES 128
#else
#define BOOST_LOCKFREE_CACHELINE_BYTES 64
#endif
#include <boost/predef.h>
#ifdef BOOST_ARCH_X86_64
#define BOOST_LOCKFREE_PTR_COMPRESSION 1
#endif
#endif /* BOOST_LOCKFREE_PREFIX_HPP_INCLUDED */
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/policy/core/common/schema_registry.h"
#include "base/logging.h"
#include "extensions/features/features.h"
namespace policy {
SchemaRegistry::Observer::~Observer() {}
SchemaRegistry::InternalObserver::~InternalObserver() {}
SchemaRegistry::SchemaRegistry() : schema_map_(new SchemaMap) {
for (int i = 0; i < POLICY_DOMAIN_SIZE; ++i)
domains_ready_[i] = false;
#if !BUILDFLAG(ENABLE_EXTENSIONS)
SetExtensionsDomainsReady();
#endif
}
SchemaRegistry::~SchemaRegistry() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
for (auto& observer : internal_observers_)
observer.OnSchemaRegistryShuttingDown(this);
}
void SchemaRegistry::RegisterComponent(const PolicyNamespace& ns,
const Schema& schema) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
ComponentMap map;
map[ns.component_id] = schema;
RegisterComponents(ns.domain, map);
}
void SchemaRegistry::RegisterComponents(PolicyDomain domain,
const ComponentMap& components) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Don't issue notifications if nothing is being registered.
if (components.empty())
return;
// Assume that a schema was updated if the namespace was already registered
// before.
DomainMap map(schema_map_->GetDomains());
for (ComponentMap::const_iterator it = components.begin();
it != components.end(); ++it) {
map[domain][it->first] = it->second;
}
schema_map_ = new SchemaMap(map);
Notify(true);
}
void SchemaRegistry::UnregisterComponent(const PolicyNamespace& ns) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DomainMap map(schema_map_->GetDomains());
if (map[ns.domain].erase(ns.component_id) != 0) {
schema_map_ = new SchemaMap(map);
Notify(false);
} else {
NOTREACHED();
}
}
bool SchemaRegistry::IsReady() const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
for (int i = 0; i < POLICY_DOMAIN_SIZE; ++i) {
if (!domains_ready_[i])
return false;
}
return true;
}
void SchemaRegistry::SetDomainReady(PolicyDomain domain) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (domains_ready_[domain])
return;
domains_ready_[domain] = true;
if (IsReady()) {
for (auto& observer : observers_)
observer.OnSchemaRegistryReady();
}
}
void SchemaRegistry::SetAllDomainsReady() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
for (int i = 0; i < POLICY_DOMAIN_SIZE; ++i)
SetDomainReady(static_cast<PolicyDomain>(i));
}
void SchemaRegistry::SetExtensionsDomainsReady() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
SetDomainReady(POLICY_DOMAIN_EXTENSIONS);
SetDomainReady(POLICY_DOMAIN_SIGNIN_EXTENSIONS);
}
void SchemaRegistry::AddObserver(Observer* observer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
observers_.AddObserver(observer);
}
void SchemaRegistry::RemoveObserver(Observer* observer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
observers_.RemoveObserver(observer);
}
void SchemaRegistry::AddInternalObserver(InternalObserver* observer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
internal_observers_.AddObserver(observer);
}
void SchemaRegistry::RemoveInternalObserver(InternalObserver* observer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
internal_observers_.RemoveObserver(observer);
}
void SchemaRegistry::Notify(bool has_new_schemas) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
for (auto& observer : observers_)
observer.OnSchemaRegistryUpdated(has_new_schemas);
}
CombinedSchemaRegistry::CombinedSchemaRegistry()
: own_schema_map_(new SchemaMap) {
// The combined registry is always ready, since it can always start tracking
// another registry that is not ready yet and going from "ready" to "not
// ready" is not allowed.
SetAllDomainsReady();
}
CombinedSchemaRegistry::~CombinedSchemaRegistry() {}
void CombinedSchemaRegistry::Track(SchemaRegistry* registry) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
registries_.insert(registry);
registry->AddObserver(this);
registry->AddInternalObserver(this);
// Recombine the maps only if the |registry| has any components other than
// POLICY_DOMAIN_CHROME.
if (registry->schema_map()->HasComponents())
Combine(true);
}
void CombinedSchemaRegistry::RegisterComponents(
PolicyDomain domain,
const ComponentMap& components) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DomainMap map(own_schema_map_->GetDomains());
for (ComponentMap::const_iterator it = components.begin();
it != components.end(); ++it) {
map[domain][it->first] = it->second;
}
own_schema_map_ = new SchemaMap(map);
Combine(true);
}
void CombinedSchemaRegistry::UnregisterComponent(const PolicyNamespace& ns) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DomainMap map(own_schema_map_->GetDomains());
if (map[ns.domain].erase(ns.component_id) != 0) {
own_schema_map_ = new SchemaMap(map);
Combine(false);
} else {
NOTREACHED();
}
}
void CombinedSchemaRegistry::OnSchemaRegistryUpdated(bool has_new_schemas) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
Combine(has_new_schemas);
}
void CombinedSchemaRegistry::OnSchemaRegistryShuttingDown(
SchemaRegistry* registry) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
registry->RemoveObserver(this);
registry->RemoveInternalObserver(this);
if (registries_.erase(registry) != 0) {
if (registry->schema_map()->HasComponents())
Combine(false);
} else {
NOTREACHED();
}
}
void CombinedSchemaRegistry::Combine(bool has_new_schemas) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// If two registries publish a Schema for the same component then it's
// undefined which version gets in the combined registry.
//
// The common case is that both registries want policy for the same component,
// and the Schemas should be the same; in that case this makes no difference.
//
// But if the Schemas are different then one of the components is out of date.
// In that case the policy loaded will be valid only for one of them, until
// the outdated components are updated. This is a known limitation of the
// way policies are loaded currently, but isn't a problem worth fixing for
// the time being.
DomainMap map(own_schema_map_->GetDomains());
for (std::set<SchemaRegistry*>::const_iterator reg_it = registries_.begin();
reg_it != registries_.end(); ++reg_it) {
const DomainMap& reg_domain_map = (*reg_it)->schema_map()->GetDomains();
for (DomainMap::const_iterator domain_it = reg_domain_map.begin();
domain_it != reg_domain_map.end(); ++domain_it) {
const ComponentMap& reg_component_map = domain_it->second;
for (ComponentMap::const_iterator comp_it = reg_component_map.begin();
comp_it != reg_component_map.end(); ++comp_it) {
map[domain_it->first][comp_it->first] = comp_it->second;
}
}
}
schema_map_ = new SchemaMap(map);
Notify(has_new_schemas);
}
ForwardingSchemaRegistry::ForwardingSchemaRegistry(SchemaRegistry* wrapped)
: wrapped_(wrapped) {
schema_map_ = wrapped_->schema_map();
wrapped_->AddObserver(this);
wrapped_->AddInternalObserver(this);
UpdateReadiness();
}
ForwardingSchemaRegistry::~ForwardingSchemaRegistry() {
if (wrapped_) {
wrapped_->RemoveObserver(this);
wrapped_->RemoveInternalObserver(this);
}
}
void ForwardingSchemaRegistry::RegisterComponents(
PolicyDomain domain,
const ComponentMap& components) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// POLICY_DOMAIN_CHROME is skipped to avoid spurious updates when a new
// Profile is created. If the ForwardingSchemaRegistry is used outside
// device-level accounts then this should become configurable.
if (wrapped_ && domain != POLICY_DOMAIN_CHROME)
wrapped_->RegisterComponents(domain, components);
// Ignore otherwise.
}
void ForwardingSchemaRegistry::UnregisterComponent(const PolicyNamespace& ns) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (wrapped_)
wrapped_->UnregisterComponent(ns);
// Ignore otherwise.
}
void ForwardingSchemaRegistry::OnSchemaRegistryUpdated(bool has_new_schemas) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
schema_map_ = wrapped_->schema_map();
Notify(has_new_schemas);
}
void ForwardingSchemaRegistry::OnSchemaRegistryReady() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
UpdateReadiness();
}
void ForwardingSchemaRegistry::OnSchemaRegistryShuttingDown(
SchemaRegistry* registry) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK_EQ(wrapped_, registry);
wrapped_->RemoveObserver(this);
wrapped_->RemoveInternalObserver(this);
wrapped_ = NULL;
// Keep serving the same |schema_map_|.
}
void ForwardingSchemaRegistry::UpdateReadiness() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (wrapped_->IsReady())
SetAllDomainsReady();
}
} // namespace policy
|
/**
* Autogenerated by Thrift for src/module.thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated @nocommit
*/
#pragma once
#include "thrift/compiler/test/fixtures/basic-annotations/gen-cpp2/module_types.h"
#include <thrift/lib/cpp2/gen/module_types_tcc.h>
namespace cpp2 {
} // cpp2
namespace std {
} // std
namespace apache {
namespace thrift {
namespace detail {
template <>
struct TccStructTraits<::cpp2::MyStructNestedAnnotation> {
static void translateFieldName(
folly::StringPiece _fname,
int16_t& fid,
apache::thrift::protocol::TType& _ftype) noexcept;
};
template <>
struct TccStructTraits<::cpp2::MyStruct> {
static void translateFieldName(
folly::StringPiece _fname,
int16_t& fid,
apache::thrift::protocol::TType& _ftype) noexcept;
};
template <>
struct TccStructTraits<::cpp2::SecretStruct> {
static void translateFieldName(
folly::StringPiece _fname,
int16_t& fid,
apache::thrift::protocol::TType& _ftype) noexcept;
};
} // namespace detail
} // namespace thrift
} // namespace apache
namespace cpp2 {
template <class Protocol_>
void MyStructNestedAnnotation::readNoXfer(Protocol_* iprot) {
apache::thrift::detail::ProtocolReaderStructReadState<Protocol_> _readState;
_readState.readStructBegin(iprot);
using apache::thrift::TProtocolException;
THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN
if (UNLIKELY(!_readState.advanceToNextField(
iprot,
0,
1,
apache::thrift::protocol::T_STRING))) {
goto _loop;
}
_readField_name:
{
::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::readWithContext(*iprot, this->name, _readState);
}
this->__isset.name = true;
if (UNLIKELY(!_readState.advanceToNextField(
iprot,
1,
0,
apache::thrift::protocol::T_STOP))) {
goto _loop;
}
THRIFT_IGNORE_ISSET_USE_WARNING_END
_end:
_readState.readStructEnd(iprot);
return;
_loop:
_readState.afterAdvanceFailure(iprot);
if (_readState.atStop()) {
goto _end;
}
if (iprot->kUsesFieldNames()) {
_readState.template fillFieldTraitsFromName<apache::thrift::detail::TccStructTraits<MyStructNestedAnnotation>>();
}
switch (_readState.fieldId) {
case 1:
{
if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_STRING))) {
goto _readField_name;
} else {
goto _skip;
}
}
default:
{
_skip:
_readState.skip(iprot);
_readState.readFieldEnd(iprot);
_readState.readFieldBeginNoInline(iprot);
goto _loop;
}
}
}
template <class Protocol_>
uint32_t MyStructNestedAnnotation::serializedSize(Protocol_ const* prot_) const {
THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN
uint32_t xfer = 0;
xfer += prot_->serializedStructSize("MyStructNestedAnnotation");
{
xfer += prot_->serializedFieldSize("name", apache::thrift::protocol::T_STRING, 1);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->name);
}
xfer += prot_->serializedSizeStop();
return xfer;
THRIFT_IGNORE_ISSET_USE_WARNING_END
}
template <class Protocol_>
uint32_t MyStructNestedAnnotation::serializedSizeZC(Protocol_ const* prot_) const {
THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN
uint32_t xfer = 0;
xfer += prot_->serializedStructSize("MyStructNestedAnnotation");
{
xfer += prot_->serializedFieldSize("name", apache::thrift::protocol::T_STRING, 1);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->name);
}
xfer += prot_->serializedSizeStop();
return xfer;
THRIFT_IGNORE_ISSET_USE_WARNING_END
}
template <class Protocol_>
uint32_t MyStructNestedAnnotation::write(Protocol_* prot_) const {
THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN
uint32_t xfer = 0;
xfer += prot_->writeStructBegin("MyStructNestedAnnotation");
bool previousFieldHasValue = true;
{
constexpr int16_t kPrevFieldId = 0;
xfer += ::apache::thrift::detail::writeFieldBegin<apache::thrift::protocol::T_STRING, 1, kPrevFieldId>(*prot_, "name", previousFieldHasValue);
previousFieldHasValue = true;
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::write(*prot_, this->name);
xfer += prot_->writeFieldEnd();
}
xfer += prot_->writeFieldStop();
xfer += prot_->writeStructEnd();
return xfer;
THRIFT_IGNORE_ISSET_USE_WARNING_END
}
extern template void MyStructNestedAnnotation::readNoXfer<>(apache::thrift::BinaryProtocolReader*);
extern template uint32_t MyStructNestedAnnotation::write<>(apache::thrift::BinaryProtocolWriter*) const;
extern template uint32_t MyStructNestedAnnotation::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const;
extern template uint32_t MyStructNestedAnnotation::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const;
extern template void MyStructNestedAnnotation::readNoXfer<>(apache::thrift::CompactProtocolReader*);
extern template uint32_t MyStructNestedAnnotation::write<>(apache::thrift::CompactProtocolWriter*) const;
extern template uint32_t MyStructNestedAnnotation::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const;
extern template uint32_t MyStructNestedAnnotation::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const;
} // cpp2
namespace cpp2 {
template <class Protocol_>
void MyStruct::readNoXfer(Protocol_* iprot) {
apache::thrift::detail::ProtocolReaderStructReadState<Protocol_> _readState;
_readState.readStructBegin(iprot);
using apache::thrift::TProtocolException;
THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN
if (UNLIKELY(!_readState.advanceToNextField(
iprot,
0,
1,
apache::thrift::protocol::T_I64))) {
goto _loop;
}
_readField_majorVer:
{
::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, ::std::int64_t>::readWithContext(*iprot, this->majorVer, _readState);
}
this->__isset.majorVer = true;
if (UNLIKELY(!_readState.advanceToNextField(
iprot,
1,
2,
apache::thrift::protocol::T_STRING))) {
goto _loop;
}
_readField_package:
{
::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::readWithContext(*iprot, this->package, _readState);
}
this->__isset.package = true;
if (UNLIKELY(!_readState.advanceToNextField(
iprot,
2,
3,
apache::thrift::protocol::T_STRING))) {
goto _loop;
}
_readField_annotation_with_quote:
{
::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::readWithContext(*iprot, this->annotation_with_quote, _readState);
}
this->__isset.annotation_with_quote = true;
if (UNLIKELY(!_readState.advanceToNextField(
iprot,
3,
4,
apache::thrift::protocol::T_STRING))) {
goto _loop;
}
_readField_class_:
{
::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::readWithContext(*iprot, this->class_, _readState);
}
this->__isset.class_ = true;
if (UNLIKELY(!_readState.advanceToNextField(
iprot,
4,
5,
apache::thrift::protocol::T_STRING))) {
goto _loop;
}
_readField_annotation_with_trailing_comma:
{
::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::readWithContext(*iprot, this->annotation_with_trailing_comma, _readState);
}
this->__isset.annotation_with_trailing_comma = true;
if (UNLIKELY(!_readState.advanceToNextField(
iprot,
5,
6,
apache::thrift::protocol::T_STRING))) {
goto _loop;
}
_readField_empty_annotations:
{
::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::readWithContext(*iprot, this->empty_annotations, _readState);
}
this->__isset.empty_annotations = true;
if (UNLIKELY(!_readState.advanceToNextField(
iprot,
6,
0,
apache::thrift::protocol::T_STOP))) {
goto _loop;
}
THRIFT_IGNORE_ISSET_USE_WARNING_END
_end:
_readState.readStructEnd(iprot);
return;
_loop:
_readState.afterAdvanceFailure(iprot);
if (_readState.atStop()) {
goto _end;
}
if (iprot->kUsesFieldNames()) {
_readState.template fillFieldTraitsFromName<apache::thrift::detail::TccStructTraits<MyStruct>>();
}
switch (_readState.fieldId) {
case 1:
{
if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_I64))) {
goto _readField_majorVer;
} else {
goto _skip;
}
}
case 2:
{
if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_STRING))) {
goto _readField_package;
} else {
goto _skip;
}
}
case 3:
{
if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_STRING))) {
goto _readField_annotation_with_quote;
} else {
goto _skip;
}
}
case 4:
{
if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_STRING))) {
goto _readField_class_;
} else {
goto _skip;
}
}
case 5:
{
if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_STRING))) {
goto _readField_annotation_with_trailing_comma;
} else {
goto _skip;
}
}
case 6:
{
if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_STRING))) {
goto _readField_empty_annotations;
} else {
goto _skip;
}
}
default:
{
_skip:
_readState.skip(iprot);
_readState.readFieldEnd(iprot);
_readState.readFieldBeginNoInline(iprot);
goto _loop;
}
}
}
template <class Protocol_>
uint32_t MyStruct::serializedSize(Protocol_ const* prot_) const {
THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN
uint32_t xfer = 0;
xfer += prot_->serializedStructSize("MyStruct");
{
xfer += prot_->serializedFieldSize("major", apache::thrift::protocol::T_I64, 1);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, ::std::int64_t>::serializedSize<false>(*prot_, this->majorVer);
}
{
xfer += prot_->serializedFieldSize("package", apache::thrift::protocol::T_STRING, 2);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->package);
}
{
xfer += prot_->serializedFieldSize("annotation_with_quote", apache::thrift::protocol::T_STRING, 3);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->annotation_with_quote);
}
{
xfer += prot_->serializedFieldSize("class_", apache::thrift::protocol::T_STRING, 4);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->class_);
}
{
xfer += prot_->serializedFieldSize("annotation_with_trailing_comma", apache::thrift::protocol::T_STRING, 5);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->annotation_with_trailing_comma);
}
{
xfer += prot_->serializedFieldSize("empty_annotations", apache::thrift::protocol::T_STRING, 6);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->empty_annotations);
}
xfer += prot_->serializedSizeStop();
return xfer;
THRIFT_IGNORE_ISSET_USE_WARNING_END
}
template <class Protocol_>
uint32_t MyStruct::serializedSizeZC(Protocol_ const* prot_) const {
THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN
uint32_t xfer = 0;
xfer += prot_->serializedStructSize("MyStruct");
{
xfer += prot_->serializedFieldSize("major", apache::thrift::protocol::T_I64, 1);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, ::std::int64_t>::serializedSize<false>(*prot_, this->majorVer);
}
{
xfer += prot_->serializedFieldSize("package", apache::thrift::protocol::T_STRING, 2);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->package);
}
{
xfer += prot_->serializedFieldSize("annotation_with_quote", apache::thrift::protocol::T_STRING, 3);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->annotation_with_quote);
}
{
xfer += prot_->serializedFieldSize("class_", apache::thrift::protocol::T_STRING, 4);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->class_);
}
{
xfer += prot_->serializedFieldSize("annotation_with_trailing_comma", apache::thrift::protocol::T_STRING, 5);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->annotation_with_trailing_comma);
}
{
xfer += prot_->serializedFieldSize("empty_annotations", apache::thrift::protocol::T_STRING, 6);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->empty_annotations);
}
xfer += prot_->serializedSizeStop();
return xfer;
THRIFT_IGNORE_ISSET_USE_WARNING_END
}
template <class Protocol_>
uint32_t MyStruct::write(Protocol_* prot_) const {
THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN
uint32_t xfer = 0;
xfer += prot_->writeStructBegin("MyStruct");
bool previousFieldHasValue = true;
{
constexpr int16_t kPrevFieldId = 0;
xfer += ::apache::thrift::detail::writeFieldBegin<apache::thrift::protocol::T_I64, 1, kPrevFieldId>(*prot_, "major", previousFieldHasValue);
previousFieldHasValue = true;
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, ::std::int64_t>::write(*prot_, this->majorVer);
xfer += prot_->writeFieldEnd();
}
{
constexpr int16_t kPrevFieldId = 1;
xfer += ::apache::thrift::detail::writeFieldBegin<apache::thrift::protocol::T_STRING, 2, kPrevFieldId>(*prot_, "package", previousFieldHasValue);
previousFieldHasValue = true;
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::write(*prot_, this->package);
xfer += prot_->writeFieldEnd();
}
{
constexpr int16_t kPrevFieldId = 2;
xfer += ::apache::thrift::detail::writeFieldBegin<apache::thrift::protocol::T_STRING, 3, kPrevFieldId>(*prot_, "annotation_with_quote", previousFieldHasValue);
previousFieldHasValue = true;
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::write(*prot_, this->annotation_with_quote);
xfer += prot_->writeFieldEnd();
}
{
constexpr int16_t kPrevFieldId = 3;
xfer += ::apache::thrift::detail::writeFieldBegin<apache::thrift::protocol::T_STRING, 4, kPrevFieldId>(*prot_, "class_", previousFieldHasValue);
previousFieldHasValue = true;
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::write(*prot_, this->class_);
xfer += prot_->writeFieldEnd();
}
{
constexpr int16_t kPrevFieldId = 4;
xfer += ::apache::thrift::detail::writeFieldBegin<apache::thrift::protocol::T_STRING, 5, kPrevFieldId>(*prot_, "annotation_with_trailing_comma", previousFieldHasValue);
previousFieldHasValue = true;
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::write(*prot_, this->annotation_with_trailing_comma);
xfer += prot_->writeFieldEnd();
}
{
constexpr int16_t kPrevFieldId = 5;
xfer += ::apache::thrift::detail::writeFieldBegin<apache::thrift::protocol::T_STRING, 6, kPrevFieldId>(*prot_, "empty_annotations", previousFieldHasValue);
previousFieldHasValue = true;
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::write(*prot_, this->empty_annotations);
xfer += prot_->writeFieldEnd();
}
xfer += prot_->writeFieldStop();
xfer += prot_->writeStructEnd();
return xfer;
THRIFT_IGNORE_ISSET_USE_WARNING_END
}
extern template void MyStruct::readNoXfer<>(apache::thrift::BinaryProtocolReader*);
extern template uint32_t MyStruct::write<>(apache::thrift::BinaryProtocolWriter*) const;
extern template uint32_t MyStruct::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const;
extern template uint32_t MyStruct::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const;
extern template void MyStruct::readNoXfer<>(apache::thrift::CompactProtocolReader*);
extern template uint32_t MyStruct::write<>(apache::thrift::CompactProtocolWriter*) const;
extern template uint32_t MyStruct::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const;
extern template uint32_t MyStruct::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const;
} // cpp2
namespace cpp2 {
template <class Protocol_>
void SecretStruct::readNoXfer(Protocol_* iprot) {
apache::thrift::detail::ProtocolReaderStructReadState<Protocol_> _readState;
_readState.readStructBegin(iprot);
using apache::thrift::TProtocolException;
THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN
if (UNLIKELY(!_readState.advanceToNextField(
iprot,
0,
1,
apache::thrift::protocol::T_I64))) {
goto _loop;
}
_readField_id:
{
::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, ::std::int64_t>::readWithContext(*iprot, this->id, _readState);
}
this->__isset.id = true;
if (UNLIKELY(!_readState.advanceToNextField(
iprot,
1,
2,
apache::thrift::protocol::T_STRING))) {
goto _loop;
}
_readField_password:
{
::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::readWithContext(*iprot, this->password, _readState);
}
this->__isset.password = true;
if (UNLIKELY(!_readState.advanceToNextField(
iprot,
2,
0,
apache::thrift::protocol::T_STOP))) {
goto _loop;
}
THRIFT_IGNORE_ISSET_USE_WARNING_END
_end:
_readState.readStructEnd(iprot);
return;
_loop:
_readState.afterAdvanceFailure(iprot);
if (_readState.atStop()) {
goto _end;
}
if (iprot->kUsesFieldNames()) {
_readState.template fillFieldTraitsFromName<apache::thrift::detail::TccStructTraits<SecretStruct>>();
}
switch (_readState.fieldId) {
case 1:
{
if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_I64))) {
goto _readField_id;
} else {
goto _skip;
}
}
case 2:
{
if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_STRING))) {
goto _readField_password;
} else {
goto _skip;
}
}
default:
{
_skip:
_readState.skip(iprot);
_readState.readFieldEnd(iprot);
_readState.readFieldBeginNoInline(iprot);
goto _loop;
}
}
}
template <class Protocol_>
uint32_t SecretStruct::serializedSize(Protocol_ const* prot_) const {
THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN
uint32_t xfer = 0;
xfer += prot_->serializedStructSize("SecretStruct");
{
xfer += prot_->serializedFieldSize("id", apache::thrift::protocol::T_I64, 1);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, ::std::int64_t>::serializedSize<false>(*prot_, this->id);
}
{
xfer += prot_->serializedFieldSize("password", apache::thrift::protocol::T_STRING, 2);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->password);
}
xfer += prot_->serializedSizeStop();
return xfer;
THRIFT_IGNORE_ISSET_USE_WARNING_END
}
template <class Protocol_>
uint32_t SecretStruct::serializedSizeZC(Protocol_ const* prot_) const {
THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN
uint32_t xfer = 0;
xfer += prot_->serializedStructSize("SecretStruct");
{
xfer += prot_->serializedFieldSize("id", apache::thrift::protocol::T_I64, 1);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, ::std::int64_t>::serializedSize<false>(*prot_, this->id);
}
{
xfer += prot_->serializedFieldSize("password", apache::thrift::protocol::T_STRING, 2);
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->password);
}
xfer += prot_->serializedSizeStop();
return xfer;
THRIFT_IGNORE_ISSET_USE_WARNING_END
}
template <class Protocol_>
uint32_t SecretStruct::write(Protocol_* prot_) const {
THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN
uint32_t xfer = 0;
xfer += prot_->writeStructBegin("SecretStruct");
bool previousFieldHasValue = true;
{
constexpr int16_t kPrevFieldId = 0;
xfer += ::apache::thrift::detail::writeFieldBegin<apache::thrift::protocol::T_I64, 1, kPrevFieldId>(*prot_, "id", previousFieldHasValue);
previousFieldHasValue = true;
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, ::std::int64_t>::write(*prot_, this->id);
xfer += prot_->writeFieldEnd();
}
{
constexpr int16_t kPrevFieldId = 1;
xfer += ::apache::thrift::detail::writeFieldBegin<apache::thrift::protocol::T_STRING, 2, kPrevFieldId>(*prot_, "password", previousFieldHasValue);
previousFieldHasValue = true;
xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::write(*prot_, this->password);
xfer += prot_->writeFieldEnd();
}
xfer += prot_->writeFieldStop();
xfer += prot_->writeStructEnd();
return xfer;
THRIFT_IGNORE_ISSET_USE_WARNING_END
}
extern template void SecretStruct::readNoXfer<>(apache::thrift::BinaryProtocolReader*);
extern template uint32_t SecretStruct::write<>(apache::thrift::BinaryProtocolWriter*) const;
extern template uint32_t SecretStruct::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const;
extern template uint32_t SecretStruct::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const;
extern template void SecretStruct::readNoXfer<>(apache::thrift::CompactProtocolReader*);
extern template uint32_t SecretStruct::write<>(apache::thrift::CompactProtocolWriter*) const;
extern template uint32_t SecretStruct::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const;
extern template uint32_t SecretStruct::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const;
} // cpp2
|
// Copyright 2018-present MongoDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "helpers.hpp"
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/test_util/catch.hh>
#include <mongocxx/instance.hpp>
#include <mongocxx/options/replace.hpp>
namespace {
using namespace bsoncxx::builder::basic;
using namespace mongocxx;
TEST_CASE("replace opts", "[replace][option]") {
instance::current();
options::replace repl;
auto collation = make_document(kvp("locale", "en_US"));
CHECK_OPTIONAL_ARGUMENT(repl, bypass_document_validation, true);
CHECK_OPTIONAL_ARGUMENT(repl, collation, collation.view());
CHECK_OPTIONAL_ARGUMENT(repl, upsert, true);
CHECK_OPTIONAL_ARGUMENT(repl, write_concern, write_concern{});
}
} // namespace
|
// Copyright (C) Ipion Software GmbH 1999-2000. All rights reserved.
#ifndef _IVP_POINT_HASH_INCLUDED
#define _IVP_POINT_HASH_INCLUDED
#ifndef WIN32
# pragma interface
#endif
#ifndef _IVP_VHASH_INCLUDED
# include "ivu_vhash.hxx"
#endif
class IVP_Poly_Point;
class IVP_point_hash: protected IVP_VHash
{
protected:
IVP_BOOL compare(void *elem0, void *elem1) const;
int point_to_index(IVP_Poly_Point *point);
public:
void add_point(IVP_Poly_Point *point){
add_elem( point, point_to_index(point));
};
IVP_Poly_Point *remove_point(IVP_Poly_Point *point){
return (IVP_Poly_Point *)remove_elem( point, point_to_index(point));
};
IVP_Poly_Point *find_point(IVP_Poly_Point *point){
return (IVP_Poly_Point *)find_elem( point, point_to_index(point));
};
int len() const { return IVP_VHash::len();};
IVP_Poly_Point *element_at(int i) const { return (IVP_Poly_Point *)elems[i].elem;};
~IVP_point_hash();
IVP_point_hash(int init_size):IVP_VHash(init_size){;};
void print() const { IVP_VHash::print();};
};
class IVP_I_Point_VHash: protected IVP_VHash
{
protected:
IVP_BOOL compare(void *elem0, void *elem1) const;
int point_to_index(IVP_U_Point *point);
public:
void add_point(IVP_U_Point *point){
add_elem( point, point_to_index(point));
};
IVP_U_Point *remove_point(IVP_U_Point *point){
return (IVP_U_Point *)remove_elem( point, point_to_index(point));
};
IVP_U_Point *find_point(IVP_U_Point *point){
return (IVP_U_Point *)find_elem( point, point_to_index(point));
};
int len() const { return IVP_VHash::len();};
IVP_U_Point *element_at(int i) const { return (IVP_U_Point *)elems[i].elem;};
~IVP_I_Point_VHash();
IVP_I_Point_VHash(int init_size):IVP_VHash(init_size){;};
void print() const { IVP_VHash::print();};
};
#endif
|
/******************************************************************************
*
* Project: OpenGIS Simple Features Reference Implementation
* Purpose: The OGRFeature class implementation.
* Author: Frank Warmerdam, warmerda@home.com
*
******************************************************************************
* Copyright (c) 1999, Les Technologies SoftMap Inc.
* Copyright (c) 2008-2013, Even Rouault <even dot rouault at mines-paris dot org>
*
* 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 "ogr_feature.h"
#include <errno.h>
#include <new>
#include <vector>
#include "cpl_time.h"
#include "ogr_api.h"
#include "ogr_p.h"
CPL_CVSID("$Id$");
/************************************************************************/
/* OGRFeature() */
/************************************************************************/
/**
* \brief Constructor
*
* Note that the OGRFeature will increment the reference count of it's
* defining OGRFeatureDefn. Destruction of the OGRFeatureDefn before
* destruction of all OGRFeatures that depend on it is likely to result in
* a crash.
*
* This method is the same as the C function OGR_F_Create().
*
* @param poDefnIn feature class (layer) definition to which the feature will
* adhere.
*/
OGRFeature::OGRFeature( OGRFeatureDefn * poDefnIn ) :
nFID(OGRNullFID),
poDefn(poDefnIn),
m_pszNativeData(NULL),
m_pszNativeMediaType(NULL),
m_pszStyleString(NULL),
m_poStyleTable(NULL),
m_pszTmpFieldValue(NULL)
{
poDefnIn->Reference();
// Allocate array of fields and initialize them to the unset special value
pauFields = static_cast<OGRField *>(
VSI_MALLOC_VERBOSE( poDefn->GetFieldCount() * sizeof(OGRField) ) );
papoGeometries = static_cast<OGRGeometry **>(
VSI_CALLOC_VERBOSE( poDefn->GetGeomFieldCount(),
sizeof(OGRGeometry*) ) );
if( pauFields != NULL )
{
for( int i = 0; i < poDefn->GetFieldCount(); i++ )
{
pauFields[i].Set.nMarker1 = OGRUnsetMarker;
pauFields[i].Set.nMarker2 = OGRUnsetMarker;
}
}
}
/************************************************************************/
/* OGR_F_Create() */
/************************************************************************/
/**
* \brief Feature factory.
*
* Note that the OGRFeature will increment the reference count of it's
* defining OGRFeatureDefn. Destruction of the OGRFeatureDefn before
* destruction of all OGRFeatures that depend on it is likely to result in
* a crash.
*
* This function is the same as the C++ method OGRFeature::OGRFeature().
*
* @param hDefn handle to the feature class (layer) definition to
* which the feature will adhere.
*
* @return an handle to the new feature object with null fields and
* no geometry, or, starting with GDAL 2.1, NULL in case out of memory situation.
*/
OGRFeatureH OGR_F_Create( OGRFeatureDefnH hDefn )
{
VALIDATE_POINTER1( hDefn, "OGR_F_Create", NULL );
return (OGRFeatureH) OGRFeature::CreateFeature( (OGRFeatureDefn*) hDefn );
}
/************************************************************************/
/* ~OGRFeature() */
/************************************************************************/
OGRFeature::~OGRFeature()
{
int nFieldcount = ( pauFields != NULL ) ? poDefn->GetFieldCount() : 0;
for( int i = 0; i < nFieldcount; i++ )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn(i);
if( !IsFieldSet(i) )
continue;
switch( poFDefn->GetType() )
{
case OFTString:
if( pauFields[i].String != NULL )
VSIFree( pauFields[i].String );
break;
case OFTBinary:
if( pauFields[i].Binary.paData != NULL )
VSIFree( pauFields[i].Binary.paData );
break;
case OFTStringList:
CSLDestroy( pauFields[i].StringList.paList );
break;
case OFTIntegerList:
case OFTInteger64List:
case OFTRealList:
CPLFree( pauFields[i].IntegerList.paList );
break;
default:
// should add support for wide strings.
break;
}
}
int nGeomFieldCount = (papoGeometries != NULL) ? poDefn->GetGeomFieldCount() : 0;
for( int i = 0; i < nGeomFieldCount; i++ )
{
delete papoGeometries[i];
}
poDefn->Release();
CPLFree( pauFields );
CPLFree( papoGeometries );
CPLFree(m_pszStyleString);
CPLFree(m_pszTmpFieldValue);
CPLFree( m_pszNativeData );
CPLFree( m_pszNativeMediaType );
}
/************************************************************************/
/* OGR_F_Destroy() */
/************************************************************************/
/**
* \brief Destroy feature
*
* The feature is deleted, but within the context of the GDAL/OGR heap.
* This is necessary when higher level applications use GDAL/OGR from a
* DLL and they want to delete a feature created within the DLL. If the
* delete is done in the calling application the memory will be freed onto
* the application heap which is inappropriate.
*
* This function is the same as the C++ method OGRFeature::DestroyFeature().
*
* @param hFeat handle to the feature to destroy.
*/
void OGR_F_Destroy( OGRFeatureH hFeat )
{
delete (OGRFeature *) hFeat;
}
/************************************************************************/
/* CreateFeature() */
/************************************************************************/
/**
* \brief Feature factory.
*
* This is essentially a feature factory, useful for
* applications creating features but wanting to ensure they
* are created out of the OGR/GDAL heap.
*
* This method is the same as the C function OGR_F_Create().
*
* @param poDefn Feature definition defining schema.
*
* @return new feature object with null fields and no geometry, or, starting with
* GDAL 2.1, NULL in case of out of memory situation. May be
* deleted with DestroyFeature().
*/
OGRFeature *OGRFeature::CreateFeature( OGRFeatureDefn *poDefn )
{
OGRFeature* poFeature = new (std::nothrow) OGRFeature( poDefn );
if( poFeature == NULL )
return NULL;
if( (poFeature->pauFields == NULL && poDefn->GetFieldCount() != 0) ||
(poFeature->papoGeometries == NULL && poDefn->GetGeomFieldCount() != 0) )
{
delete poFeature;
return NULL;
}
return poFeature;
}
/************************************************************************/
/* DestroyFeature() */
/************************************************************************/
/**
* \brief Destroy feature
*
* The feature is deleted, but within the context of the GDAL/OGR heap.
* This is necessary when higher level applications use GDAL/OGR from a
* DLL and they want to delete a feature created within the DLL. If the
* delete is done in the calling application the memory will be freed onto
* the application heap which is inappropriate.
*
* This method is the same as the C function OGR_F_Destroy().
*
* @param poFeature the feature to delete.
*/
void OGRFeature::DestroyFeature( OGRFeature *poFeature )
{
delete poFeature;
}
/************************************************************************/
/* GetDefnRef() */
/************************************************************************/
/**
* \fn OGRFeatureDefn *OGRFeature::GetDefnRef();
*
* \brief Fetch feature definition.
*
* This method is the same as the C function OGR_F_GetDefnRef().
*
* @return a reference to the feature definition object.
*/
/************************************************************************/
/* OGR_F_GetDefnRef() */
/************************************************************************/
/**
* \brief Fetch feature definition.
*
* This function is the same as the C++ method OGRFeature::GetDefnRef().
*
* @param hFeat handle to the feature to get the feature definition from.
*
* @return an handle to the feature definition object on which feature
* depends.
*/
OGRFeatureDefnH OGR_F_GetDefnRef( OGRFeatureH hFeat )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetDefnRef", NULL );
return (OGRFeatureDefnH) ((OGRFeature *) hFeat)->GetDefnRef();
}
/************************************************************************/
/* SetGeometryDirectly() */
/************************************************************************/
/**
* \brief Set feature geometry.
*
* This method updates the features geometry, and operate exactly as
* SetGeometry(), except that this method assumes ownership of the
* passed geometry (even in case of failure of that function).
*
* This method is the same as the C function OGR_F_SetGeometryDirectly().
*
* @param poGeomIn new geometry to apply to feature. Passing NULL value here
* is correct and it will result in deallocation of currently assigned geometry
* without assigning new one.
*
* @return OGRERR_NONE if successful, or OGR_UNSUPPORTED_GEOMETRY_TYPE if
* the geometry type is illegal for the OGRFeatureDefn (checking not yet
* implemented).
*/
OGRErr OGRFeature::SetGeometryDirectly( OGRGeometry * poGeomIn )
{
if( GetGeomFieldCount() > 0 )
return SetGeomFieldDirectly(0, poGeomIn);
else
{
delete poGeomIn;
return OGRERR_FAILURE;
}
}
/************************************************************************/
/* OGR_F_SetGeometryDirectly() */
/************************************************************************/
/**
* \brief Set feature geometry.
*
* This function updates the features geometry, and operate exactly as
* SetGeometry(), except that this function assumes ownership of the
* passed geometry (even in case of failure of that function).
*
* This function is the same as the C++ method
* OGRFeature::SetGeometryDirectly.
*
* @param hFeat handle to the feature on which to apply the geometry.
* @param hGeom handle to the new geometry to apply to feature.
*
* @return OGRERR_NONE if successful, or OGR_UNSUPPORTED_GEOMETRY_TYPE if
* the geometry type is illegal for the OGRFeatureDefn (checking not yet
* implemented).
*/
OGRErr OGR_F_SetGeometryDirectly( OGRFeatureH hFeat, OGRGeometryH hGeom )
{
VALIDATE_POINTER1( hFeat, "OGR_F_SetGeometryDirectly", OGRERR_FAILURE );
return ((OGRFeature *) hFeat)->SetGeometryDirectly((OGRGeometry *) hGeom);
}
/************************************************************************/
/* SetGeometry() */
/************************************************************************/
/**
* \brief Set feature geometry.
*
* This method updates the features geometry, and operate exactly as
* SetGeometryDirectly(), except that this method does not assume ownership
* of the passed geometry, but instead makes a copy of it.
*
* This method is the same as the C function OGR_F_SetGeometry().
*
* @param poGeomIn new geometry to apply to feature. Passing NULL value here
* is correct and it will result in deallocation of currently assigned geometry
* without assigning new one.
*
* @return OGRERR_NONE if successful, or OGR_UNSUPPORTED_GEOMETRY_TYPE if
* the geometry type is illegal for the OGRFeatureDefn (checking not yet
* implemented).
*/
OGRErr OGRFeature::SetGeometry( const OGRGeometry * poGeomIn )
{
if( GetGeomFieldCount() < 1 )
return OGRERR_FAILURE;
return SetGeomField(0, poGeomIn);
}
/************************************************************************/
/* OGR_F_SetGeometry() */
/************************************************************************/
/**
* \brief Set feature geometry.
*
* This function updates the features geometry, and operate exactly as
* SetGeometryDirectly(), except that this function does not assume ownership
* of the passed geometry, but instead makes a copy of it.
*
* This function is the same as the C++ OGRFeature::SetGeometry().
*
* @param hFeat handle to the feature on which new geometry is applied to.
* @param hGeom handle to the new geometry to apply to feature.
*
* @return OGRERR_NONE if successful, or OGR_UNSUPPORTED_GEOMETRY_TYPE if
* the geometry type is illegal for the OGRFeatureDefn (checking not yet
* implemented).
*/
OGRErr OGR_F_SetGeometry( OGRFeatureH hFeat, OGRGeometryH hGeom )
{
VALIDATE_POINTER1( hFeat, "OGR_F_SetGeometry", OGRERR_FAILURE );
return ((OGRFeature *) hFeat)->SetGeometry((OGRGeometry *) hGeom);
}
/************************************************************************/
/* StealGeometry() */
/************************************************************************/
/**
* \brief Take away ownership of geometry.
*
* Fetch the geometry from this feature, and clear the reference to the
* geometry on the feature. This is a mechanism for the application to
* take over ownership of the geometry from the feature without copying.
* Sort of an inverse to SetGeometryDirectly().
*
* After this call the OGRFeature will have a NULL geometry.
*
* @return the pointer to the geometry.
*/
OGRGeometry *OGRFeature::StealGeometry()
{
if( GetGeomFieldCount() > 0 )
{
OGRGeometry *poReturn = papoGeometries[0];
papoGeometries[0] = NULL;
return poReturn;
}
else
return NULL;
}
/**
* \brief Take away ownership of geometry.
*
* Fetch the geometry from this feature, and clear the reference to the
* geometry on the feature. This is a mechanism for the application to
* take over ownership of the geometry from the feature without copying.
* Sort of an inverse to SetGeometryDirectly().
*
* After this call the OGRFeature will have a NULL geometry.
*
* @param iGeomField index of the geometry field.
*
* @return the pointer to the geometry.
*/
OGRGeometry *OGRFeature::StealGeometry(int iGeomField)
{
if( iGeomField >= 0 && iGeomField < GetGeomFieldCount() )
{
OGRGeometry *poReturn = papoGeometries[iGeomField];
papoGeometries[iGeomField] = NULL;
return poReturn;
}
else
return NULL;
}
/************************************************************************/
/* OGR_F_StealGeometry() */
/************************************************************************/
/**
* \brief Take away ownership of geometry.
*
* Fetch the geometry from this feature, and clear the reference to the
* geometry on the feature. This is a mechanism for the application to
* take over ownership of the geometry from the feature without copying.
* Sort of an inverse to OGR_FSetGeometryDirectly().
*
* After this call the OGRFeature will have a NULL geometry.
*
* @return the pointer to the geometry.
*/
OGRGeometryH OGR_F_StealGeometry( OGRFeatureH hFeat )
{
VALIDATE_POINTER1( hFeat, "OGR_F_StealGeometry", NULL );
return (OGRGeometryH) ((OGRFeature *) hFeat)->StealGeometry();
}
/************************************************************************/
/* GetGeometryRef() */
/************************************************************************/
/**
* \fn OGRGeometry *OGRFeature::GetGeometryRef();
*
* \brief Fetch pointer to feature geometry.
*
* This method is the same as the C function OGR_F_GetGeometryRef().
*
* Starting with GDAL 1.11, this is equivalent to calling
* OGRFeature::GetGeomFieldRef(0).
*
* @return pointer to internal feature geometry. This object should
* not be modified.
*/
OGRGeometry *OGRFeature::GetGeometryRef()
{
if( GetGeomFieldCount() > 0 )
return GetGeomFieldRef(0);
else
return NULL;
}
/************************************************************************/
/* OGR_F_GetGeometryRef() */
/************************************************************************/
/**
* \brief Fetch an handle to feature geometry.
*
* This function is the same as the C++ method OGRFeature::GetGeometryRef().
*
* @param hFeat handle to the feature to get geometry from.
* @return an handle to internal feature geometry. This object should
* not be modified.
*/
OGRGeometryH OGR_F_GetGeometryRef( OGRFeatureH hFeat )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetGeometryRef", NULL );
OGRFeature* poFeature = (OGRFeature *) hFeat;
OGRGeometry* poGeom = poFeature->GetGeometryRef();
if( !OGRGetNonLinearGeometriesEnabledFlag() && poGeom != NULL &&
OGR_GT_IsNonLinear(poGeom->getGeometryType()) )
{
OGRwkbGeometryType eTargetType = OGR_GT_GetLinear(poGeom->getGeometryType());
poGeom = OGRGeometryFactory::forceTo(poFeature->StealGeometry(), eTargetType);
poFeature->SetGeomFieldDirectly(0, poGeom);
poGeom = poFeature->GetGeometryRef();
}
return (OGRGeometryH)poGeom;
}
/************************************************************************/
/* GetGeomFieldRef() */
/************************************************************************/
/**
* \brief Fetch pointer to feature geometry.
*
* This method is the same as the C function OGR_F_GetGeomFieldRef().
*
* @param iField geometry field to get.
*
* @return pointer to internal feature geometry. This object should
* not be modified.
*
* @since GDAL 1.11
*/
OGRGeometry *OGRFeature::GetGeomFieldRef(int iField)
{
if( iField < 0 || iField >= GetGeomFieldCount() )
return NULL;
else
return papoGeometries[iField];
}
/************************************************************************/
/* GetGeomFieldRef() */
/************************************************************************/
/**
* \brief Fetch pointer to feature geometry.
*
* @param pszFName name of geometry field to get.
*
* @return pointer to internal feature geometry. This object should
* not be modified.
*
* @since GDAL 1.11
*/
OGRGeometry *OGRFeature::GetGeomFieldRef(const char* pszFName)
{
int iField = GetGeomFieldIndex(pszFName);
if( iField < 0 )
return NULL;
else
return papoGeometries[iField];
}
/************************************************************************/
/* OGR_F_GetGeomFieldRef() */
/************************************************************************/
/**
* \brief Fetch an handle to feature geometry.
*
* This function is the same as the C++ method OGRFeature::GetGeomFieldRef().
*
* @param hFeat handle to the feature to get geometry from.
* @param iField geometry field to get.
* @return an handle to internal feature geometry. This object should
* not be modified.
*
* @since GDAL 1.11
*/
OGRGeometryH OGR_F_GetGeomFieldRef( OGRFeatureH hFeat, int iField )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetGeomFieldRef", NULL );
OGRFeature* poFeature = (OGRFeature *) hFeat;
OGRGeometry* poGeom = poFeature->GetGeomFieldRef(iField);
if( !OGRGetNonLinearGeometriesEnabledFlag() && poGeom != NULL &&
OGR_GT_IsNonLinear(poGeom->getGeometryType()) )
{
OGRwkbGeometryType eTargetType = OGR_GT_GetLinear(poGeom->getGeometryType());
poGeom = OGRGeometryFactory::forceTo(poFeature->StealGeometry(iField), eTargetType);
poFeature->SetGeomFieldDirectly(iField, poGeom);
poGeom = poFeature->GetGeomFieldRef(iField);
}
return (OGRGeometryH)poGeom;
}
/************************************************************************/
/* SetGeomFieldDirectly() */
/************************************************************************/
/**
* \brief Set feature geometry of a specified geometry field.
*
* This method updates the features geometry, and operate exactly as
* SetGeomField(), except that this method assumes ownership of the
* passed geometry (even in case of failure of that function).
*
* This method is the same as the C function OGR_F_SetGeomFieldDirectly().
*
* @param iField geometry field to set.
* @param poGeomIn new geometry to apply to feature. Passing NULL value here
* is correct and it will result in deallocation of currently assigned geometry
* without assigning new one.
*
* @return OGRERR_NONE if successful, or OGRERR_FAILURE if the index is invalid,
* or OGRERR_UNSUPPORTED_GEOMETRY_TYPE if the geometry type is illegal for the
* OGRFeatureDefn (checking not yet implemented).
*
* @since GDAL 1.11
*/
OGRErr OGRFeature::SetGeomFieldDirectly( int iField, OGRGeometry * poGeomIn )
{
if( iField < 0 || iField >= GetGeomFieldCount() )
{
delete poGeomIn;
return OGRERR_FAILURE;
}
/*
// (Verify the type) and set/unset flags.
OGRwkbGeometryType eMyGeomType = poDefn->GetGeomFieldDefn(iField)->GetType();
if( eMyGeomType != wkbUnknown )
{
OGRwkbGeometryType eGeomInType = poGeomIn->getGeometryType();
This leads to segfaults in tests probably because issues with simple vs multi geometries
if( wkbFlatten(eGeomInType) != wkbFlatten(eMyGeomType) )
{
delete poGeomIn;
return OGRERR_UNSUPPORTED_GEOMETRY_TYPE;
}
if( wkbHasZ(eMyGeomType) && !wkbHasZ(eGeomInType) )
{
poGeomIn->set3D(TRUE);
}
else if( !wkbHasZ(eMyGeomType) && wkbHasZ(eGeomInType) )
{
poGeomIn->set3D(FALSE);
}
if( wkbHasM(eMyGeomType) && !wkbHasM(eGeomInType) )
{
poGeomIn->setMeasured(TRUE);
}
else if( !wkbHasM(eMyGeomType) && wkbHasM(eGeomInType) )
{
poGeomIn->setMeasured(FALSE);
}
}
*/
if( papoGeometries[iField] != poGeomIn )
{
delete papoGeometries[iField];
papoGeometries[iField] = poGeomIn;
}
return OGRERR_NONE;
}
/************************************************************************/
/* OGR_F_SetGeomFieldDirectly() */
/************************************************************************/
/**
* \brief Set feature geometry of a specified geometry field.
*
* This function updates the features geometry, and operate exactly as
* SetGeomField(), except that this function assumes ownership of the
* passed geometry (even in case of failure of that function).
*
* This function is the same as the C++ method
* OGRFeature::SetGeomFieldDirectly.
*
* @param hFeat handle to the feature on which to apply the geometry.
* @param iField geometry field to set.
* @param hGeom handle to the new geometry to apply to feature.
*
* @return OGRERR_NONE if successful, or OGRERR_FAILURE if the index is invalid,
* or OGR_UNSUPPORTED_GEOMETRY_TYPE if the geometry type is illegal for the
* OGRFeatureDefn (checking not yet implemented).
*
* @since GDAL 1.11
*/
OGRErr OGR_F_SetGeomFieldDirectly( OGRFeatureH hFeat, int iField,
OGRGeometryH hGeom )
{
VALIDATE_POINTER1( hFeat, "OGR_F_SetGeomFieldDirectly", OGRERR_FAILURE );
return ((OGRFeature *) hFeat)->SetGeomFieldDirectly(iField,
(OGRGeometry *) hGeom);
}
/************************************************************************/
/* SetGeomField() */
/************************************************************************/
/**
* \brief Set feature geometry of a specified geometry field.
*
* This method updates the features geometry, and operate exactly as
* SetGeomFieldDirectly(), except that this method does not assume ownership
* of the passed geometry, but instead makes a copy of it.
*
* This method is the same as the C function OGR_F_SetGeomField().
*
* @param iField geometry field to set.
* @param poGeomIn new geometry to apply to feature. Passing NULL value here
* is correct and it will result in deallocation of currently assigned geometry
* without assigning new one.
*
* @return OGRERR_NONE if successful, or OGRERR_FAILURE if the index is invalid,
* or OGR_UNSUPPORTED_GEOMETRY_TYPE if the geometry type is illegal for the
* OGRFeatureDefn (checking not yet implemented).
*
* @since GDAL 1.11
*/
OGRErr OGRFeature::SetGeomField( int iField, const OGRGeometry * poGeomIn )
{
if( iField < 0 || iField >= GetGeomFieldCount() )
return OGRERR_FAILURE;
if( papoGeometries[iField] != poGeomIn )
{
delete papoGeometries[iField];
if( poGeomIn != NULL )
papoGeometries[iField] = poGeomIn->clone();
else
papoGeometries[iField] = NULL;
}
// I should be verifying that the geometry matches the defn's type.
return OGRERR_NONE;
}
/************************************************************************/
/* OGR_F_SetGeomField() */
/************************************************************************/
/**
* \brief Set feature geometry of a specified geometry field.
*
* This function updates the features geometry, and operate exactly as
* SetGeometryDirectly(), except that this function does not assume ownership
* of the passed geometry, but instead makes a copy of it.
*
* This function is the same as the C++ OGRFeature::SetGeomField().
*
* @param hFeat handle to the feature on which new geometry is applied to.
* @param iField geometry field to set.
* @param hGeom handle to the new geometry to apply to feature.
*
* @return OGRERR_NONE if successful, or OGR_UNSUPPORTED_GEOMETRY_TYPE if
* the geometry type is illegal for the OGRFeatureDefn (checking not yet
* implemented).
*/
OGRErr OGR_F_SetGeomField( OGRFeatureH hFeat, int iField, OGRGeometryH hGeom )
{
VALIDATE_POINTER1( hFeat, "OGR_F_SetGeomField", OGRERR_FAILURE );
return ((OGRFeature *) hFeat)->SetGeomField(iField, (OGRGeometry *) hGeom);
}
/************************************************************************/
/* Clone() */
/************************************************************************/
/**
* \brief Duplicate feature.
*
* The newly created feature is owned by the caller, and will have it's own
* reference to the OGRFeatureDefn.
*
* This method is the same as the C function OGR_F_Clone().
*
* @return new feature, exactly matching this feature. Or, starting with GDAL 2.1,
* NULL in case of out of memory situation.
*/
OGRFeature *OGRFeature::Clone()
{
OGRFeature *poNew = CreateFeature( poDefn );
if( poNew == NULL )
return NULL;
for( int i = 0; i < poDefn->GetFieldCount(); i++ )
{
if( !poNew->SetFieldInternal( i, pauFields + i ) )
{
delete poNew;
return NULL;
}
}
for( int i = 0; i < poDefn->GetGeomFieldCount(); i++ )
{
if( papoGeometries[i] != NULL )
{
poNew->papoGeometries[i] = papoGeometries[i]->clone();
if( poNew->papoGeometries[i] == NULL )
{
delete poNew;
return NULL;
}
}
}
if( m_pszStyleString != NULL )
{
poNew->m_pszStyleString = VSI_STRDUP_VERBOSE(m_pszStyleString);
if( poNew->m_pszStyleString == NULL )
{
delete poNew;
return NULL;
}
}
poNew->SetFID( GetFID() );
if( m_pszNativeData != NULL )
{
poNew->m_pszNativeData = VSI_STRDUP_VERBOSE(m_pszNativeData);
if( poNew->m_pszNativeData == NULL )
{
delete poNew;
return NULL;
}
}
if( m_pszNativeMediaType != NULL )
{
poNew->m_pszNativeMediaType = VSI_STRDUP_VERBOSE(m_pszNativeMediaType);
if( poNew->m_pszNativeMediaType == NULL )
{
delete poNew;
return NULL;
}
}
return poNew;
}
/************************************************************************/
/* OGR_F_Clone() */
/************************************************************************/
/**
* \brief Duplicate feature.
*
* The newly created feature is owned by the caller, and will have it's own
* reference to the OGRFeatureDefn.
*
* This function is the same as the C++ method OGRFeature::Clone().
*
* @param hFeat handle to the feature to clone.
* @return an handle to the new feature, exactly matching this feature.
*/
OGRFeatureH OGR_F_Clone( OGRFeatureH hFeat )
{
VALIDATE_POINTER1( hFeat, "OGR_F_Clone", NULL );
return (OGRFeatureH) ((OGRFeature *) hFeat)->Clone();
}
/************************************************************************/
/* GetFieldCount() */
/************************************************************************/
/**
* \fn int OGRFeature::GetFieldCount() const;
*
* \brief Fetch number of fields on this feature.
* This will always be the same
* as the field count for the OGRFeatureDefn.
*
* This method is the same as the C function OGR_F_GetFieldCount().
*
* @return count of fields.
*/
/************************************************************************/
/* OGR_F_GetFieldCount() */
/************************************************************************/
/**
* \brief Fetch number of fields on this feature
* This will always be the same
* as the field count for the OGRFeatureDefn.
*
* This function is the same as the C++ method OGRFeature::GetFieldCount().
*
* @param hFeat handle to the feature to get the fields count from.
* @return count of fields.
*/
int OGR_F_GetFieldCount( OGRFeatureH hFeat )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetFieldCount", 0 );
return ((OGRFeature *) hFeat)->GetFieldCount();
}
/************************************************************************/
/* GetFieldDefnRef() */
/************************************************************************/
/**
* \fn OGRFieldDefn *OGRFeature::GetFieldDefnRef( int iField ) const;
*
* \brief Fetch definition for this field.
*
* This method is the same as the C function OGR_F_GetFieldDefnRef().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
*
* @return the field definition (from the OGRFeatureDefn). This is an
* internal reference, and should not be deleted or modified.
*/
/************************************************************************/
/* OGR_F_GetFieldDefnRef() */
/************************************************************************/
/**
* \brief Fetch definition for this field.
*
* This function is the same as the C++ method OGRFeature::GetFieldDefnRef().
*
* @param hFeat handle to the feature on which the field is found.
* @param i the field to fetch, from 0 to GetFieldCount()-1.
*
* @return an handle to the field definition (from the OGRFeatureDefn).
* This is an internal reference, and should not be deleted or modified.
*/
OGRFieldDefnH OGR_F_GetFieldDefnRef( OGRFeatureH hFeat, int i )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetFieldDefnRef", NULL );
if( i < 0 || i >= ((OGRFeature *) hFeat)->GetFieldCount() )
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid index : %d", i);
return NULL;
}
return (OGRFieldDefnH) ((OGRFeature *) hFeat)->GetFieldDefnRef(i);
}
/************************************************************************/
/* GetFieldIndex() */
/************************************************************************/
/**
* \fn int OGRFeature::GetFieldIndex( const char * pszName );
*
* \brief Fetch the field index given field name.
*
* This is a cover for the OGRFeatureDefn::GetFieldIndex() method.
*
* This method is the same as the C function OGR_F_GetFieldIndex().
*
* @param pszName the name of the field to search for.
*
* @return the field index, or -1 if no matching field is found.
*/
/************************************************************************/
/* OGR_F_GetFieldIndex() */
/************************************************************************/
/**
* \brief Fetch the field index given field name.
*
* This is a cover for the OGRFeatureDefn::GetFieldIndex() method.
*
* This function is the same as the C++ method OGRFeature::GetFieldIndex().
*
* @param hFeat handle to the feature on which the field is found.
* @param pszName the name of the field to search for.
*
* @return the field index, or -1 if no matching field is found.
*/
int OGR_F_GetFieldIndex( OGRFeatureH hFeat, const char *pszName )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetFieldIndex", 0 );
return ((OGRFeature *) hFeat)->GetFieldIndex( pszName );
}
/************************************************************************/
/* GetGeomFieldCount() */
/************************************************************************/
/**
* \fn int OGRFeature::GetGeomFieldCount() const;
*
* \brief Fetch number of geometry fields on this feature.
* This will always be the same
* as the geometry field count for the OGRFeatureDefn.
*
* This method is the same as the C function OGR_F_GetGeomFieldCount().
*
* @return count of geometry fields.
*
* @since GDAL 1.11
*/
/************************************************************************/
/* OGR_F_GetGeomFieldCount() */
/************************************************************************/
/**
* \brief Fetch number of geometry fields on this feature
* This will always be the same
* as the geometry field count for the OGRFeatureDefn.
*
* This function is the same as the C++ method OGRFeature::GetGeomFieldCount().
*
* @param hFeat handle to the feature to get the geometry fields count from.
* @return count of geometry fields.
*
* @since GDAL 1.11
*/
int OGR_F_GetGeomFieldCount( OGRFeatureH hFeat )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetGeomFieldCount", 0 );
return ((OGRFeature *) hFeat)->GetGeomFieldCount();
}
/************************************************************************/
/* GetGeomFieldDefnRef() */
/************************************************************************/
/**
* \fn OGRGeomFieldDefn *OGRFeature::GetGeomFieldDefnRef( int iGeomField );
*
* \brief Fetch definition for this geometry field.
*
* This method is the same as the C function OGR_F_GetGeomFieldDefnRef().
*
* @param iGeomField the field to fetch, from 0 to GetGeomFieldCount()-1.
*
* @return the field definition (from the OGRFeatureDefn). This is an
* internal reference, and should not be deleted or modified.
*
* @since GDAL 1.11
*/
/************************************************************************/
/* OGR_F_GetGeomFieldDefnRef() */
/************************************************************************/
/**
* \brief Fetch definition for this geometry field.
*
* This function is the same as the C++ method OGRFeature::GetGeomFieldDefnRef().
*
* @param hFeat handle to the feature on which the field is found.
* @param i the field to fetch, from 0 to GetGeomFieldCount()-1.
*
* @return an handle to the field definition (from the OGRFeatureDefn).
* This is an internal reference, and should not be deleted or modified.
*
* @since GDAL 1.11
*/
OGRGeomFieldDefnH OGR_F_GetGeomFieldDefnRef( OGRFeatureH hFeat, int i )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetGeomFieldDefnRef", NULL );
return (OGRGeomFieldDefnH) ((OGRFeature *) hFeat)->GetGeomFieldDefnRef(i);
}
/************************************************************************/
/* GetGeomFieldIndex() */
/************************************************************************/
/**
* \fn int OGRFeature::GetGeomFieldIndex( const char * pszName );
*
* \brief Fetch the geometry field index given geometry field name.
*
* This is a cover for the OGRFeatureDefn::GetGeomFieldIndex() method.
*
* This method is the same as the C function OGR_F_GetGeomFieldIndex().
*
* @param pszName the name of the geometry field to search for.
*
* @return the geometry field index, or -1 if no matching geometry field is found.
*
* @since GDAL 1.11
*/
/************************************************************************/
/* OGR_F_GetGeomFieldIndex() */
/************************************************************************/
/**
* \brief Fetch the geometry field index given geometry field name.
*
* This is a cover for the OGRFeatureDefn::GetGeomFieldIndex() method.
*
* This function is the same as the C++ method OGRFeature::GetGeomFieldIndex().
*
* @param hFeat handle to the feature on which the geometry field is found.
* @param pszName the name of the geometry field to search for.
*
* @return the geometry field index, or -1 if no matching geometry field is found.
*
* @since GDAL 1.11
*/
int OGR_F_GetGeomFieldIndex( OGRFeatureH hFeat, const char *pszName )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetGeomFieldIndex", 0 );
return ((OGRFeature *) hFeat)->GetGeomFieldIndex( pszName );
}
/************************************************************************/
/* IsFieldSet() */
/************************************************************************/
/**
* \brief Test if a field has ever been assigned a value or not.
*
* This method is the same as the C function OGR_F_IsFieldSet().
*
* @param iField the field to test.
*
* @return TRUE if the field has been set, otherwise false.
*/
int OGRFeature::IsFieldSet( int iField )
{
int iSpecialField = iField - poDefn->GetFieldCount();
if (iSpecialField >= 0)
{
// special field value accessors
switch (iSpecialField)
{
case SPF_FID:
return ((OGRFeature *)this)->GetFID() != OGRNullFID;
case SPF_OGR_GEOM_WKT:
case SPF_OGR_GEOMETRY:
return GetGeomFieldCount() > 0 && papoGeometries[0] != NULL;
case SPF_OGR_STYLE:
return ((OGRFeature *)this)->GetStyleString() != NULL;
case SPF_OGR_GEOM_AREA:
if( GetGeomFieldCount() == 0 || papoGeometries[0] == NULL )
return FALSE;
return OGR_G_Area((OGRGeometryH)papoGeometries[0]) != 0.0;
default:
return FALSE;
}
}
else
{
return pauFields[iField].Set.nMarker1 != OGRUnsetMarker
|| pauFields[iField].Set.nMarker2 != OGRUnsetMarker;
}
}
/************************************************************************/
/* OGR_F_IsFieldSet() */
/************************************************************************/
/**
* \brief Test if a field has ever been assigned a value or not.
*
* This function is the same as the C++ method OGRFeature::IsFieldSet().
*
* @param hFeat handle to the feature on which the field is.
* @param iField the field to test.
*
* @return TRUE if the field has been set, otherwise false.
*/
int OGR_F_IsFieldSet( OGRFeatureH hFeat, int iField )
{
VALIDATE_POINTER1( hFeat, "OGR_F_IsFieldSet", 0 );
OGRFeature* poFeature = (OGRFeature* )hFeat;
if (iField < 0 || iField >= poFeature->GetFieldCount())
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid index : %d", iField);
return FALSE;
}
return poFeature->IsFieldSet( iField );
}
/************************************************************************/
/* UnsetField() */
/************************************************************************/
/**
* \brief Clear a field, marking it as unset.
*
* This method is the same as the C function OGR_F_UnsetField().
*
* @param iField the field to unset.
*/
void OGRFeature::UnsetField( int iField )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL || !IsFieldSet(iField) )
return;
switch( poFDefn->GetType() )
{
case OFTRealList:
case OFTIntegerList:
case OFTInteger64List:
CPLFree( pauFields[iField].IntegerList.paList );
break;
case OFTStringList:
CSLDestroy( pauFields[iField].StringList.paList );
break;
case OFTString:
CPLFree( pauFields[iField].String );
break;
case OFTBinary:
CPLFree( pauFields[iField].Binary.paData );
break;
default:
break;
}
pauFields[iField].Set.nMarker1 = OGRUnsetMarker;
pauFields[iField].Set.nMarker2 = OGRUnsetMarker;
}
/************************************************************************/
/* OGR_F_UnsetField() */
/************************************************************************/
/**
* \brief Clear a field, marking it as unset.
*
* This function is the same as the C++ method OGRFeature::UnsetField().
*
* @param hFeat handle to the feature on which the field is.
* @param iField the field to unset.
*/
void OGR_F_UnsetField( OGRFeatureH hFeat, int iField )
{
VALIDATE_POINTER0( hFeat, "OGR_F_UnsetField" );
((OGRFeature *) hFeat)->UnsetField( iField );
}
/************************************************************************/
/* GetRawFieldRef() */
/************************************************************************/
/**
* \fn OGRField *OGRFeature::GetRawFieldRef( int iField );
*
* \brief Fetch a pointer to the internal field value given the index.
*
* This method is the same as the C function OGR_F_GetRawFieldRef().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
*
* @return the returned pointer is to an internal data structure, and should
* not be freed, or modified.
*/
/************************************************************************/
/* OGR_F_GetRawFieldRef() */
/************************************************************************/
/**
* \brief Fetch an handle to the internal field value given the index.
*
* This function is the same as the C++ method OGRFeature::GetRawFieldRef().
*
* @param hFeat handle to the feature on which field is found.
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
*
* @return the returned handle is to an internal data structure, and should
* not be freed, or modified.
*/
OGRField *OGR_F_GetRawFieldRef( OGRFeatureH hFeat, int iField )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetRawFieldRef", NULL );
return ((OGRFeature *)hFeat)->GetRawFieldRef( iField );
}
/************************************************************************/
/* GetFieldAsInteger() */
/************************************************************************/
/**
* \fn OGRFeature::GetFieldAsInteger( const char* pszFName )
* \brief Fetch field value as integer.
*
* OFTString features will be translated using atoi(). OFTReal fields
* will be cast to integer. OFTInteger64 are demoted to 32 bit, with
* clamping if out-of-range. Other field types, or errors will result in
* a return value of zero.
*
* @param pszFName the name of the field to fetch.
*
* @return the field value.
*/
/**
* \brief Fetch field value as integer.
*
* OFTString features will be translated using atoi(). OFTReal fields
* will be cast to integer. OFTInteger64 are demoted to 32 bit, with
* clamping if out-of-range. Other field types, or errors will result in
* a return value of zero.
*
* This method is the same as the C function OGR_F_GetFieldAsInteger().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
*
* @return the field value.
*/
int OGRFeature::GetFieldAsInteger( int iField )
{
int iSpecialField = iField - poDefn->GetFieldCount();
if (iSpecialField >= 0)
{
// special field value accessors
switch (iSpecialField)
{
case SPF_FID:
{
int nVal = (nFID > INT_MAX) ? INT_MAX :
(nFID < INT_MIN) ? INT_MIN : (int) nFID;
if( (GIntBig)nVal != nFID )
{
CPLError( CE_Warning, CPLE_AppDefined,
"Integer overflow occurred when trying to return "
"64bit integer. Use GetFieldAsInteger64() instead" );
}
return nVal;
}
case SPF_OGR_GEOM_AREA:
if( GetGeomFieldCount() == 0 || papoGeometries[0] == NULL )
return 0;
return (int)OGR_G_Area((OGRGeometryH)papoGeometries[0]);
default:
return 0;
}
}
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL )
return 0;
if( !IsFieldSet(iField) )
return 0;
OGRFieldType eType = poFDefn->GetType();
if( eType == OFTInteger )
return pauFields[iField].Integer;
else if( eType == OFTInteger64 )
{
GIntBig nVal64 = pauFields[iField].Integer64;
int nVal = (nVal64 > INT_MAX) ? INT_MAX :
(nVal64 < INT_MIN) ? INT_MIN : (int) nVal64;
if( (GIntBig)nVal != nVal64 )
{
CPLError( CE_Warning, CPLE_AppDefined,
"Integer overflow occurred when trying to return 64bit "
"integer. Use GetFieldAsInteger64() instead");
}
return nVal;
}
else if( eType == OFTReal )
return (int) pauFields[iField].Real;
else if( eType == OFTString )
{
if( pauFields[iField].String == NULL )
return 0;
else
return atoi(pauFields[iField].String);
}
else
return 0;
}
/************************************************************************/
/* OGR_F_GetFieldAsInteger() */
/************************************************************************/
/**
* \brief Fetch field value as integer.
*
* OFTString features will be translated using atoi(). OFTReal fields
* will be cast to integer. Other field types, or errors will result in
* a return value of zero.
*
* This function is the same as the C++ method OGRFeature::GetFieldAsInteger().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
*
* @return the field value.
*/
int OGR_F_GetFieldAsInteger( OGRFeatureH hFeat, int iField )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetFieldAsInteger", 0 );
return ((OGRFeature *)hFeat)->GetFieldAsInteger(iField);
}
/************************************************************************/
/* GetFieldAsInteger64() */
/************************************************************************/
/**
* \fn OGRFeature::GetFieldAsInteger64( const char* pszFName )
* \brief Fetch field value as integer 64 bit.
*
* OFTInteger are promoted to 64 bit.
* OFTString features will be translated using CPLAtoGIntBig(). OFTReal fields
* will be cast to integer. Other field types, or errors will result in
* a return value of zero.
*
* @param pszFName the name of the field to fetch.
*
* @return the field value.
*/
/**
* \brief Fetch field value as integer 64 bit.
*
* OFTInteger are promoted to 64 bit.
* OFTString features will be translated using CPLAtoGIntBig(). OFTReal fields
* will be cast to integer. Other field types, or errors will result in
* a return value of zero.
*
* This method is the same as the C function OGR_F_GetFieldAsInteger64().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
*
* @return the field value.
* @since GDAL 2.0
*/
GIntBig OGRFeature::GetFieldAsInteger64( int iField )
{
int iSpecialField = iField - poDefn->GetFieldCount();
if (iSpecialField >= 0)
{
// special field value accessors
switch (iSpecialField)
{
case SPF_FID:
return nFID;
case SPF_OGR_GEOM_AREA:
if( GetGeomFieldCount() == 0 || papoGeometries[0] == NULL )
return 0;
return (int)OGR_G_Area((OGRGeometryH)papoGeometries[0]);
default:
return 0;
}
}
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL )
return 0;
if( !IsFieldSet(iField) )
return 0;
OGRFieldType eType = poFDefn->GetType();
if( eType == OFTInteger )
return (GIntBig) pauFields[iField].Integer;
else if( eType == OFTInteger64 )
return pauFields[iField].Integer64;
else if( eType == OFTReal )
return (GIntBig) pauFields[iField].Real;
else if( eType == OFTString )
{
if( pauFields[iField].String == NULL )
return 0;
else
{
return CPLAtoGIntBigEx(pauFields[iField].String, TRUE, NULL);
}
}
else
return 0;
}
/************************************************************************/
/* OGR_F_GetFieldAsInteger64() */
/************************************************************************/
/**
* \brief Fetch field value as integer 64 bit.
*
* OFTInteger are promoted to 64 bit.
* OFTString features will be translated using CPLAtoGIntBig(). OFTReal fields
* will be cast to integer. Other field types, or errors will result in
* a return value of zero.
*
* This function is the same as the C++ method OGRFeature::GetFieldAsInteger64().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
*
* @return the field value.
* @since GDAL 2.0
*/
GIntBig OGR_F_GetFieldAsInteger64( OGRFeatureH hFeat, int iField )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetFieldAsInteger64", 0 );
return ((OGRFeature *)hFeat)->GetFieldAsInteger64(iField);
}
/************************************************************************/
/* GetFieldAsDouble() */
/************************************************************************/
/**
* \fn OGRFeature::GetFieldAsDouble( const char* pszFName )
* \brief Fetch field value as a double.
*
* OFTString features will be translated using CPLAtof(). OFTInteger and OFTInteger64 fields
* will be cast to double. Other field types, or errors will result in
* a return value of zero.
*
* @param pszFName the name of the field to fetch.
*
* @return the field value.
*/
/**
* \brief Fetch field value as a double.
*
* OFTString features will be translated using CPLAtof(). OFTInteger and OFTInteger64 fields
* will be cast to double. Other field types, or errors will result in
* a return value of zero.
*
* This method is the same as the C function OGR_F_GetFieldAsDouble().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
*
* @return the field value.
*/
double OGRFeature::GetFieldAsDouble( int iField )
{
int iSpecialField = iField - poDefn->GetFieldCount();
if (iSpecialField >= 0)
{
// special field value accessors
switch (iSpecialField)
{
case SPF_FID:
return (double)GetFID();
case SPF_OGR_GEOM_AREA:
if( GetGeomFieldCount() == 0 || papoGeometries[0] == NULL )
return 0.0;
return OGR_G_Area((OGRGeometryH)papoGeometries[0]);
default:
return 0.0;
}
}
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL )
return 0.0;
if( !IsFieldSet(iField) )
return 0.0;
OGRFieldType eType = poFDefn->GetType();
if( eType == OFTReal )
return pauFields[iField].Real;
else if( eType == OFTInteger )
return pauFields[iField].Integer;
else if( eType == OFTInteger64 )
return (double) pauFields[iField].Integer64;
else if( eType == OFTString )
{
if( pauFields[iField].String == NULL )
return 0;
else
return CPLAtof(pauFields[iField].String);
}
else
return 0.0;
}
/************************************************************************/
/* OGR_F_GetFieldAsDouble() */
/************************************************************************/
/**
* \brief Fetch field value as a double.
*
* OFTString features will be translated using CPLAtof(). OFTInteger fields
* will be cast to double. Other field types, or errors will result in
* a return value of zero.
*
* This function is the same as the C++ method OGRFeature::GetFieldAsDouble().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
*
* @return the field value.
*/
double OGR_F_GetFieldAsDouble( OGRFeatureH hFeat, int iField )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetFieldAsDouble", 0 );
return ((OGRFeature *)hFeat)->GetFieldAsDouble(iField);
}
/************************************************************************/
/* OGRFeatureFormatDateTimeBuffer() */
/************************************************************************/
#define TEMP_BUFFER_SIZE 80
static void OGRFeatureFormatDateTimeBuffer(char szTempBuffer[TEMP_BUFFER_SIZE],
int nYear, int nMonth, int nDay,
int nHour, int nMinute, float fSecond,
int nTZFlag )
{
int ms = OGR_GET_MS(fSecond);
if( ms != 0 )
snprintf( szTempBuffer, TEMP_BUFFER_SIZE,
"%04d/%02d/%02d %02d:%02d:%06.3f",
nYear,
nMonth,
nDay,
nHour,
nMinute,
fSecond );
else /* default format */
snprintf( szTempBuffer, TEMP_BUFFER_SIZE,
"%04d/%02d/%02d %02d:%02d:%02d",
nYear,
nMonth,
nDay,
nHour,
nMinute,
(int)fSecond );
if( nTZFlag > 1 )
{
int nOffset = (nTZFlag - 100) * 15;
int nHours = (int) (nOffset / 60); // round towards zero
int nMinutes = ABS(nOffset - nHours * 60);
if( nOffset < 0 )
{
strcat( szTempBuffer, "-" );
nHours = ABS(nHours);
}
else
strcat( szTempBuffer, "+" );
if( nMinutes == 0 )
snprintf( szTempBuffer+strlen(szTempBuffer),
TEMP_BUFFER_SIZE-strlen(szTempBuffer), "%02d", nHours );
else
snprintf( szTempBuffer+strlen(szTempBuffer),
TEMP_BUFFER_SIZE-strlen(szTempBuffer), "%02d%02d", nHours, nMinutes );
}
}
/************************************************************************/
/* GetFieldAsString() */
/************************************************************************/
/**
* \fn OGRFeature::GetFieldAsString( const char* pszFName )
* \brief Fetch field value as a string.
*
* OFTReal and OFTInteger fields will be translated to string using
* sprintf(), but not necessarily using the established formatting rules.
* Other field types, or errors will result in a return value of zero.
*
* @param pszFName the name of the field to fetch.
*
* @return the field value. This string is internal, and should not be
* modified, or freed. Its lifetime may be very brief.
*/
/**
* \brief Fetch field value as a string.
*
* OFTReal and OFTInteger fields will be translated to string using
* sprintf(), but not necessarily using the established formatting rules.
* Other field types, or errors will result in a return value of zero.
*
* This method is the same as the C function OGR_F_GetFieldAsString().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
*
* @return the field value. This string is internal, and should not be
* modified, or freed. Its lifetime may be very brief.
*/
const char *OGRFeature::GetFieldAsString( int iField )
{
char szTempBuffer[TEMP_BUFFER_SIZE];
CPLFree(m_pszTmpFieldValue);
m_pszTmpFieldValue = NULL;
int iSpecialField = iField - poDefn->GetFieldCount();
if (iSpecialField >= 0)
{
// special field value accessors
switch (iSpecialField)
{
case SPF_FID:
snprintf( szTempBuffer, TEMP_BUFFER_SIZE, CPL_FRMT_GIB, GetFID() );
m_pszTmpFieldValue = VSI_STRDUP_VERBOSE( szTempBuffer );
if( m_pszTmpFieldValue == NULL )
return "";
return m_pszTmpFieldValue;
case SPF_OGR_GEOMETRY:
if( GetGeomFieldCount() > 0 && papoGeometries[0] != NULL )
return papoGeometries[0]->getGeometryName();
else
return "";
case SPF_OGR_STYLE:
if( GetStyleString() == NULL )
return "";
else
return GetStyleString();
case SPF_OGR_GEOM_WKT:
{
if( GetGeomFieldCount() == 0 || papoGeometries[0] == NULL )
return "";
if (papoGeometries[0]->exportToWkt( &m_pszTmpFieldValue ) == OGRERR_NONE )
return m_pszTmpFieldValue;
else
return "";
}
case SPF_OGR_GEOM_AREA:
if( GetGeomFieldCount() == 0 || papoGeometries[0] == NULL )
return "";
CPLsnprintf( szTempBuffer, TEMP_BUFFER_SIZE, "%.16g",
OGR_G_Area((OGRGeometryH)papoGeometries[0]) );
m_pszTmpFieldValue = VSI_STRDUP_VERBOSE( szTempBuffer );
if( m_pszTmpFieldValue == NULL )
return "";
return m_pszTmpFieldValue;
default:
return "";
}
}
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL )
return "";
if( !IsFieldSet(iField) )
return "";
OGRFieldType eType = poFDefn->GetType();
if( eType == OFTString )
{
if( pauFields[iField].String == NULL )
return "";
else
return pauFields[iField].String;
}
else if( eType == OFTInteger )
{
snprintf( szTempBuffer, TEMP_BUFFER_SIZE,
"%d", pauFields[iField].Integer );
m_pszTmpFieldValue = VSI_STRDUP_VERBOSE( szTempBuffer );
if( m_pszTmpFieldValue == NULL )
return "";
return m_pszTmpFieldValue;
}
else if( eType == OFTInteger64 )
{
snprintf( szTempBuffer, TEMP_BUFFER_SIZE,
CPL_FRMT_GIB, pauFields[iField].Integer64 );
m_pszTmpFieldValue = VSI_STRDUP_VERBOSE( szTempBuffer );
if( m_pszTmpFieldValue == NULL )
return "";
return m_pszTmpFieldValue;
}
else if( eType == OFTReal )
{
char szFormat[64];
if( poFDefn->GetWidth() != 0 )
{
snprintf( szFormat, sizeof(szFormat), "%%.%df",
poFDefn->GetPrecision() );
}
else
strcpy( szFormat, "%.15g" );
CPLsnprintf( szTempBuffer, TEMP_BUFFER_SIZE,
szFormat, pauFields[iField].Real );
m_pszTmpFieldValue = VSI_STRDUP_VERBOSE( szTempBuffer );
if( m_pszTmpFieldValue == NULL )
return "";
return m_pszTmpFieldValue;
}
else if( eType == OFTDateTime )
{
OGRFeatureFormatDateTimeBuffer(szTempBuffer,
pauFields[iField].Date.Year,
pauFields[iField].Date.Month,
pauFields[iField].Date.Day,
pauFields[iField].Date.Hour,
pauFields[iField].Date.Minute,
pauFields[iField].Date.Second,
pauFields[iField].Date.TZFlag );
m_pszTmpFieldValue = VSI_STRDUP_VERBOSE( szTempBuffer );
if( m_pszTmpFieldValue == NULL )
return "";
return m_pszTmpFieldValue;
}
else if( eType == OFTDate )
{
snprintf( szTempBuffer, TEMP_BUFFER_SIZE, "%04d/%02d/%02d",
pauFields[iField].Date.Year,
pauFields[iField].Date.Month,
pauFields[iField].Date.Day );
m_pszTmpFieldValue = VSI_STRDUP_VERBOSE( szTempBuffer );
if( m_pszTmpFieldValue == NULL )
return "";
return m_pszTmpFieldValue;
}
else if( eType == OFTTime )
{
int ms = OGR_GET_MS(pauFields[iField].Date.Second);
if( ms != 0 )
snprintf( szTempBuffer, TEMP_BUFFER_SIZE, "%02d:%02d:%06.3f",
pauFields[iField].Date.Hour,
pauFields[iField].Date.Minute,
pauFields[iField].Date.Second );
else
snprintf( szTempBuffer, TEMP_BUFFER_SIZE, "%02d:%02d:%02d",
pauFields[iField].Date.Hour,
pauFields[iField].Date.Minute,
(int)pauFields[iField].Date.Second );
m_pszTmpFieldValue = VSI_STRDUP_VERBOSE( szTempBuffer );
if( m_pszTmpFieldValue == NULL )
return "";
return m_pszTmpFieldValue;
}
else if( eType == OFTIntegerList )
{
char szItem[32];
int nCount = pauFields[iField].IntegerList.nCount;
snprintf( szTempBuffer, TEMP_BUFFER_SIZE, "(%d:", nCount );
int i = 0; // Used after for.
for( ; i < nCount; i++ )
{
snprintf( szItem, sizeof(szItem), "%d",
pauFields[iField].IntegerList.paList[i] );
if( strlen(szTempBuffer) + strlen(szItem) + 6
>= sizeof(szTempBuffer) )
{
break;
}
if( i > 0 )
strcat( szTempBuffer, "," );
strcat( szTempBuffer, szItem );
}
if( i < nCount )
strcat( szTempBuffer, ",...)" );
else
strcat( szTempBuffer, ")" );
m_pszTmpFieldValue = VSI_STRDUP_VERBOSE( szTempBuffer );
if( m_pszTmpFieldValue == NULL )
return "";
return m_pszTmpFieldValue;
}
else if( eType == OFTInteger64List )
{
char szItem[32];
int nCount = pauFields[iField].Integer64List.nCount;
snprintf( szTempBuffer, TEMP_BUFFER_SIZE, "(%d:", nCount );
int i = 0; // Used after for.
for( ; i < nCount; i++ )
{
snprintf( szItem, sizeof(szItem), CPL_FRMT_GIB,
pauFields[iField].Integer64List.paList[i] );
if( strlen(szTempBuffer) + strlen(szItem) + 6
>= sizeof(szTempBuffer) )
{
break;
}
if( i > 0 )
strcat( szTempBuffer, "," );
strcat( szTempBuffer, szItem );
}
if( i < nCount )
strcat( szTempBuffer, ",...)" );
else
strcat( szTempBuffer, ")" );
m_pszTmpFieldValue = VSI_STRDUP_VERBOSE( szTempBuffer );
if( m_pszTmpFieldValue == NULL )
return "";
return m_pszTmpFieldValue;
}
else if( eType == OFTRealList )
{
char szItem[40];
char szFormat[64];
int nCount = pauFields[iField].RealList.nCount;
if( poFDefn->GetWidth() != 0 )
{
snprintf( szFormat, sizeof(szFormat), "%%%d.%df",
poFDefn->GetWidth(), poFDefn->GetPrecision() );
}
else
strcpy( szFormat, "%.16g" );
snprintf( szTempBuffer, TEMP_BUFFER_SIZE, "(%d:", nCount );
int i = 0; // Used after for.
for( ; i < nCount; i++ )
{
CPLsnprintf( szItem, sizeof(szItem), szFormat,
pauFields[iField].RealList.paList[i] );
if( strlen(szTempBuffer) + strlen(szItem) + 6
>= sizeof(szTempBuffer) )
{
break;
}
if( i > 0 )
strcat( szTempBuffer, "," );
strcat( szTempBuffer, szItem );
}
if( i < nCount )
strcat( szTempBuffer, ",...)" );
else
strcat( szTempBuffer, ")" );
m_pszTmpFieldValue = VSI_STRDUP_VERBOSE( szTempBuffer );
if( m_pszTmpFieldValue == NULL )
return "";
return m_pszTmpFieldValue;
}
else if( eType == OFTStringList )
{
int nCount = pauFields[iField].StringList.nCount;
snprintf( szTempBuffer, TEMP_BUFFER_SIZE, "(%d:", nCount );
int i = 0; // Used after for.
for( ; i < nCount; i++ )
{
const char *pszItem = pauFields[iField].StringList.paList[i];
if( strlen(szTempBuffer) + strlen(pszItem) + 6
>= sizeof(szTempBuffer) )
{
break;
}
if( i > 0 )
strcat( szTempBuffer, "," );
strcat( szTempBuffer, pszItem );
}
if( i < nCount )
strcat( szTempBuffer, ",...)" );
else
strcat( szTempBuffer, ")" );
m_pszTmpFieldValue = VSI_STRDUP_VERBOSE( szTempBuffer );
if( m_pszTmpFieldValue == NULL )
return "";
return m_pszTmpFieldValue;
}
else if( eType == OFTBinary )
{
int nCount = pauFields[iField].Binary.nCount;
if( nCount > (int) sizeof(szTempBuffer) / 2 - 4 )
nCount = sizeof(szTempBuffer) / 2 - 4;
char *pszHex =
CPLBinaryToHex( nCount, pauFields[iField].Binary.paData );
memcpy( szTempBuffer, pszHex, 2 * nCount );
szTempBuffer[nCount*2] = '\0';
if( nCount < pauFields[iField].Binary.nCount )
strcat( szTempBuffer, "..." );
CPLFree( pszHex );
m_pszTmpFieldValue = VSI_STRDUP_VERBOSE( szTempBuffer );
if( m_pszTmpFieldValue == NULL )
return "";
return m_pszTmpFieldValue;
}
else
return "";
}
/************************************************************************/
/* OGR_F_GetFieldAsString() */
/************************************************************************/
/**
* \brief Fetch field value as a string.
*
* OFTReal and OFTInteger fields will be translated to string using
* sprintf(), but not necessarily using the established formatting rules.
* Other field types, or errors will result in a return value of zero.
*
* This function is the same as the C++ method OGRFeature::GetFieldAsString().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
*
* @return the field value. This string is internal, and should not be
* modified, or freed. Its lifetime may be very brief.
*/
const char *OGR_F_GetFieldAsString( OGRFeatureH hFeat, int iField )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetFieldAsString", NULL );
return ((OGRFeature *)hFeat)->GetFieldAsString(iField);
}
/************************************************************************/
/* GetFieldAsIntegerList() */
/************************************************************************/
/**
* \fn OGRFeature::GetFieldAsIntegerList( const char* pszFName, int *pnCount )
* \brief Fetch field value as a list of integers.
*
* Currently this method only works for OFTIntegerList fields.
* @param pszFName the name of the field to fetch.
* @param pnCount an integer to put the list count (number of integers) into.
*
* @return the field value. This list is internal, and should not be
* modified, or freed. Its lifetime may be very brief. If *pnCount is zero
* on return the returned pointer may be NULL or non-NULL.
* OFTReal and OFTInteger fields will be translated to string using
* sprintf(), but not necessarily using the established formatting rules.
* Other field types, or errors will result in a return value of zero.
*/
/**
* \brief Fetch field value as a list of integers.
*
* Currently this method only works for OFTIntegerList fields.
*
* This method is the same as the C function OGR_F_GetFieldAsIntegerList().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param pnCount an integer to put the list count (number of integers) into.
*
* @return the field value. This list is internal, and should not be
* modified, or freed. Its lifetime may be very brief. If *pnCount is zero
* on return the returned pointer may be NULL or non-NULL.
*/
const int *OGRFeature::GetFieldAsIntegerList( int iField, int *pnCount )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn != NULL && IsFieldSet(iField) &&
poFDefn->GetType() == OFTIntegerList )
{
if( pnCount != NULL )
*pnCount = pauFields[iField].IntegerList.nCount;
return pauFields[iField].IntegerList.paList;
}
else
{
if( pnCount != NULL )
*pnCount = 0;
return NULL;
}
}
/************************************************************************/
/* OGR_F_GetFieldAsIntegerList() */
/************************************************************************/
/**
* \brief Fetch field value as a list of integers.
*
* Currently this function only works for OFTIntegerList fields.
*
* This function is the same as the C++ method
* OGRFeature::GetFieldAsIntegerList().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param pnCount an integer to put the list count (number of integers) into.
*
* @return the field value. This list is internal, and should not be
* modified, or freed. Its lifetime may be very brief. If *pnCount is zero
* on return the returned pointer may be NULL or non-NULL.
*/
const int *OGR_F_GetFieldAsIntegerList( OGRFeatureH hFeat, int iField,
int *pnCount )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetFieldAsIntegerList", NULL );
return ((OGRFeature *)hFeat)->GetFieldAsIntegerList(iField, pnCount);
}
/************************************************************************/
/* GetFieldAsInteger64List() */
/************************************************************************/
/**
* \fn OGRFeature::GetFieldAsInteger64List( const char* pszFName, int *pnCount )
* \brief Fetch field value as a list of 64 bit integers.
*
* Currently this method only works for OFTInteger64List fields.
* @param pszFName the name of the field to fetch.
* @param pnCount an integer to put the list count (number of integers) into.
*
* @return the field value. This list is internal, and should not be
* modified, or freed. Its lifetime may be very brief. If *pnCount is zero
* on return the returned pointer may be NULL or non-NULL.
* @since GDAL 2.0
*/
/**
* \brief Fetch field value as a list of 64 bit integers.
*
* Currently this method only works for OFTInteger64List fields.
*
* This method is the same as the C function OGR_F_GetFieldAsInteger64List().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param pnCount an integer to put the list count (number of integers) into.
*
* @return the field value. This list is internal, and should not be
* modified, or freed. Its lifetime may be very brief. If *pnCount is zero
* on return the returned pointer may be NULL or non-NULL.
* @since GDAL 2.0
*/
const GIntBig *OGRFeature::GetFieldAsInteger64List( int iField, int *pnCount )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn != NULL && IsFieldSet(iField) &&
poFDefn->GetType() == OFTInteger64List )
{
if( pnCount != NULL )
*pnCount = pauFields[iField].Integer64List.nCount;
return pauFields[iField].Integer64List.paList;
}
else
{
if( pnCount != NULL )
*pnCount = 0;
return NULL;
}
}
/************************************************************************/
/* OGR_F_GetFieldAsInteger64List() */
/************************************************************************/
/**
* \brief Fetch field value as a list of 64 bit integers.
*
* Currently this function only works for OFTInteger64List fields.
*
* This function is the same as the C++ method
* OGRFeature::GetFieldAsInteger64List().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param pnCount an integer to put the list count (number of integers) into.
*
* @return the field value. This list is internal, and should not be
* modified, or freed. Its lifetime may be very brief. If *pnCount is zero
* on return the returned pointer may be NULL or non-NULL.
* @since GDAL 2.0
*/
const GIntBig *OGR_F_GetFieldAsInteger64List( OGRFeatureH hFeat, int iField,
int *pnCount )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetFieldAsInteger64List", NULL );
return ((OGRFeature *)hFeat)->GetFieldAsInteger64List(iField, pnCount);
}
/************************************************************************/
/* GetFieldAsDoubleList() */
/************************************************************************/
/**
* \fn OGRFeature::GetFieldAsDoubleList( const char* pszFName, int *pnCount )
* \brief Fetch field value as a list of doubles.
*
* Currently this method only works for OFTRealList fields.
* @param pszFName the name of the field to fetch.
* @param pnCount an integer to put the list count (number of doubles) into.
*
* @return the field value. This list is internal, and should not be
* modified, or freed. Its lifetime may be very brief. If *pnCount is zero
* on return the returned pointer may be NULL or non-NULL.
*/
/**
* \brief Fetch field value as a list of doubles.
*
* Currently this method only works for OFTRealList fields.
*
* This method is the same as the C function OGR_F_GetFieldAsDoubleList().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param pnCount an integer to put the list count (number of doubles) into.
*
* @return the field value. This list is internal, and should not be
* modified, or freed. Its lifetime may be very brief. If *pnCount is zero
* on return the returned pointer may be NULL or non-NULL.
*/
const double *OGRFeature::GetFieldAsDoubleList( int iField, int *pnCount )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn != NULL && IsFieldSet(iField) &&
poFDefn->GetType() == OFTRealList )
{
if( pnCount != NULL )
*pnCount = pauFields[iField].RealList.nCount;
return pauFields[iField].RealList.paList;
}
else
{
if( pnCount != NULL )
*pnCount = 0;
return NULL;
}
}
/************************************************************************/
/* OGR_F_GetFieldAsDoubleList() */
/************************************************************************/
/**
* \brief Fetch field value as a list of doubles.
*
* Currently this function only works for OFTRealList fields.
*
* This function is the same as the C++ method
* OGRFeature::GetFieldAsDoubleList().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param pnCount an integer to put the list count (number of doubles) into.
*
* @return the field value. This list is internal, and should not be
* modified, or freed. Its lifetime may be very brief. If *pnCount is zero
* on return the returned pointer may be NULL or non-NULL.
*/
const double *OGR_F_GetFieldAsDoubleList( OGRFeatureH hFeat, int iField,
int *pnCount )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetFieldAsDoubleList", NULL );
return ((OGRFeature *)hFeat)->GetFieldAsDoubleList(iField, pnCount);
}
/************************************************************************/
/* GetFieldAsStringList() */
/************************************************************************/
/**
* \fn OGRFeature::GetFieldAsStringList( const char* pszFName )
* \brief Fetch field value as a list of strings.
*
* Currently this method only works for OFTStringList fields.
*
* The returned list is terminated by a NULL pointer. The number of
* elements can also be calculated using CSLCount().
*
* @param pszFName the name of the field to fetch.
*
* @return the field value. This list is internal, and should not be
* modified, or freed. Its lifetime may be very brief.
*/
/**
* \brief Fetch field value as a list of strings.
*
* Currently this method only works for OFTStringList fields.
*
* The returned list is terminated by a NULL pointer. The number of
* elements can also be calculated using CSLCount().
*
* This method is the same as the C function OGR_F_GetFieldAsStringList().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
*
* @return the field value. This list is internal, and should not be
* modified, or freed. Its lifetime may be very brief.
*/
char **OGRFeature::GetFieldAsStringList( int iField )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL )
return NULL;
if( !IsFieldSet(iField) )
return NULL;
if( poFDefn->GetType() == OFTStringList )
{
return pauFields[iField].StringList.paList;
}
else
{
return NULL;
}
}
/************************************************************************/
/* OGR_F_GetFieldAsStringList() */
/************************************************************************/
/**
* \brief Fetch field value as a list of strings.
*
* Currently this method only works for OFTStringList fields.
*
* The returned list is terminated by a NULL pointer. The number of
* elements can also be calculated using CSLCount().
*
* This function is the same as the C++ method
* OGRFeature::GetFieldAsStringList().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
*
* @return the field value. This list is internal, and should not be
* modified, or freed. Its lifetime may be very brief.
*/
char **OGR_F_GetFieldAsStringList( OGRFeatureH hFeat, int iField )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetFieldAsStringList", NULL );
return ((OGRFeature *)hFeat)->GetFieldAsStringList(iField);
}
/************************************************************************/
/* GetFieldAsBinary() */
/************************************************************************/
/**
* \brief Fetch field value as binary data.
*
* This method only works for OFTBinary and OFTString fields.
*
* This method is the same as the C function OGR_F_GetFieldAsBinary().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param pnBytes location to put the number of bytes returned.
*
* @return the field value. This data is internal, and should not be
* modified, or freed. Its lifetime may be very brief.
*/
GByte *OGRFeature::GetFieldAsBinary( int iField, int *pnBytes )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
*pnBytes = 0;
if( poFDefn == NULL )
return NULL;
if( !IsFieldSet(iField) )
return NULL;
if( poFDefn->GetType() == OFTBinary )
{
*pnBytes = pauFields[iField].Binary.nCount;
return pauFields[iField].Binary.paData;
}
else if( poFDefn->GetType() == OFTString )
{
*pnBytes = (int)strlen(pauFields[iField].String);
return (GByte*)pauFields[iField].String;
}
else
{
return NULL;
}
}
/************************************************************************/
/* OGR_F_GetFieldAsBinary() */
/************************************************************************/
/**
* \brief Fetch field value as binary.
*
* This method only works for OFTBinary and OFTString fields.
*
* This function is the same as the C++ method
* OGRFeature::GetFieldAsBinary().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param pnBytes location to place count of bytes returned.
*
* @return the field value. This list is internal, and should not be
* modified, or freed. Its lifetime may be very brief.
*/
GByte *OGR_F_GetFieldAsBinary( OGRFeatureH hFeat, int iField, int *pnBytes )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetFieldAsBinary", NULL );
VALIDATE_POINTER1( pnBytes, "OGR_F_GetFieldAsBinary", NULL );
return ((OGRFeature *)hFeat)->GetFieldAsBinary(iField,pnBytes);
}
/************************************************************************/
/* GetFieldAsDateTime() */
/************************************************************************/
/**
* \brief Fetch field value as date and time.
*
* Currently this method only works for OFTDate, OFTTime and OFTDateTime fields.
*
* This method is the same as the C function OGR_F_GetFieldAsDateTime().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param pnYear (including century)
* @param pnMonth (1-12)
* @param pnDay (1-31)
* @param pnHour (0-23)
* @param pnMinute (0-59)
* @param pfSecond (0-59 with millisecond accuracy)
* @param pnTZFlag (0=unknown, 1=localtime, 100=GMT, see data model for details)
*
* @return TRUE on success or FALSE on failure.
*/
int OGRFeature::GetFieldAsDateTime( int iField,
int *pnYear, int *pnMonth, int *pnDay,
int *pnHour, int *pnMinute, float *pfSecond,
int *pnTZFlag )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL )
return FALSE;
if( !IsFieldSet(iField) )
return FALSE;
if( poFDefn->GetType() == OFTDate
|| poFDefn->GetType() == OFTTime
|| poFDefn->GetType() == OFTDateTime )
{
if( pnYear )
*pnYear = pauFields[iField].Date.Year;
if( pnMonth )
*pnMonth = pauFields[iField].Date.Month;
if( pnDay )
*pnDay = pauFields[iField].Date.Day;
if( pnHour )
*pnHour = pauFields[iField].Date.Hour;
if( pnMinute )
*pnMinute = pauFields[iField].Date.Minute;
if( pfSecond )
*pfSecond = pauFields[iField].Date.Second;
if( pnTZFlag )
*pnTZFlag = pauFields[iField].Date.TZFlag;
return TRUE;
}
else
{
return FALSE;
}
}
/**
* \brief Fetch field value as date and time.
*
* Currently this method only works for OFTDate, OFTTime and OFTDateTime fields.
*
* This method is the same as the C function OGR_F_GetFieldAsDateTime().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param pnYear (including century)
* @param pnMonth (1-12)
* @param pnDay (1-31)
* @param pnHour (0-23)
* @param pnMinute (0-59)
* @param pnSecond (0-59)
* @param pnTZFlag (0=unknown, 1=localtime, 100=GMT, see data model for details)
*
* @return TRUE on success or FALSE on failure.
*/
int OGRFeature::GetFieldAsDateTime( int iField,
int *pnYear, int *pnMonth, int *pnDay,
int *pnHour, int *pnMinute, int *pnSecond,
int *pnTZFlag )
{
float fSecond = 0.0f;
const bool bRet = CPL_TO_BOOL(
GetFieldAsDateTime( iField, pnYear, pnMonth, pnDay, pnHour, pnMinute,
&fSecond, pnTZFlag));
if( bRet && pnSecond ) *pnSecond = static_cast<int>(fSecond);
return bRet;
}
/************************************************************************/
/* OGR_F_GetFieldAsDateTime() */
/************************************************************************/
/**
* \brief Fetch field value as date and time.
*
* Currently this method only works for OFTDate, OFTTime and OFTDateTime fields.
*
* This function is the same as the C++ method
* OGRFeature::GetFieldAsDateTime().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param pnYear (including century)
* @param pnMonth (1-12)
* @param pnDay (1-31)
* @param pnHour (0-23)
* @param pnMinute (0-59)
* @param pnSecond (0-59)
* @param pnTZFlag (0=unknown, 1=localtime, 100=GMT, see data model for details)
*
* @return TRUE on success or FALSE on failure.
*
* @see Use OGR_F_GetFieldAsDateTimeEx() for second with millisecond accuracy.
*/
int OGR_F_GetFieldAsDateTime( OGRFeatureH hFeat, int iField,
int *pnYear, int *pnMonth, int *pnDay,
int *pnHour, int *pnMinute, int *pnSecond,
int *pnTZFlag )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetFieldAsDateTime", 0 );
float fSecond = 0.0f;
const bool bRet = CPL_TO_BOOL(reinterpret_cast<OGRFeature *>(hFeat)->
GetFieldAsDateTime( iField,
pnYear, pnMonth, pnDay,
pnHour, pnMinute,&fSecond,
pnTZFlag ));
if( bRet && pnSecond ) *pnSecond = static_cast<int>(fSecond);
return bRet;
}
/************************************************************************/
/* OGR_F_GetFieldAsDateTimeEx() */
/************************************************************************/
/**
* \brief Fetch field value as date and time.
*
* Currently this method only works for OFTDate, OFTTime and OFTDateTime fields.
*
* This function is the same as the C++ method
* OGRFeature::GetFieldAsDateTime().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param pnYear (including century)
* @param pnMonth (1-12)
* @param pnDay (1-31)
* @param pnHour (0-23)
* @param pnMinute (0-59)
* @param pfSecond (0-59 with millisecond accuracy)
* @param pnTZFlag (0=unknown, 1=localtime, 100=GMT, see data model for details)
*
* @return TRUE on success or FALSE on failure.
* @since GDAL 2.0
*/
int OGR_F_GetFieldAsDateTimeEx( OGRFeatureH hFeat, int iField,
int *pnYear, int *pnMonth, int *pnDay,
int *pnHour, int *pnMinute, float *pfSecond,
int *pnTZFlag )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetFieldAsDateTimeEx", 0 );
return ((OGRFeature *)hFeat)->GetFieldAsDateTime( iField,
pnYear, pnMonth, pnDay,
pnHour, pnMinute,pfSecond,
pnTZFlag );
}
/************************************************************************/
/* OGRFeatureGetIntegerValue() */
/************************************************************************/
static int OGRFeatureGetIntegerValue(OGRFieldDefn *poFDefn, int nValue)
{
if( poFDefn->GetSubType() == OFSTBoolean && nValue != 0 && nValue != 1 )
{
CPLError(CE_Warning, CPLE_AppDefined,
"Only 0 or 1 should be passed for a OFSTBoolean subtype. "
"Considering this non-zero value as 1.");
nValue = 1;
}
else if( poFDefn->GetSubType() == OFSTInt16 )
{
if( nValue < -32768 )
{
CPLError(CE_Warning, CPLE_AppDefined,
"Out-of-range value for a OFSTInt16 subtype. "
"Considering this value as -32768.");
nValue = -32768;
}
else if( nValue > 32767 )
{
CPLError(CE_Warning, CPLE_AppDefined,
"Out-of-range value for a OFSTInt16 subtype. "
"Considering this value as 32767.");
nValue = 32767;
}
}
return nValue;
}
/************************************************************************/
/* SetField() */
/************************************************************************/
/**
* \fn OGRFeature::SetField( const char* pszFName, int nValue )
* \brief Set field to integer value.
* OFTInteger, OFTInteger64 and OFTReal fields will be set directly. OFTString fields
* will be assigned a string representation of the value, but not necessarily
* taking into account formatting constraints on this field. Other field
* types may be unaffected.
*
* @param pszFName the name of the field to set.
* @param nValue the value to assign.
*/
/**
* \brief Set field to integer value.
*
* OFTInteger, OFTInteger64 and OFTReal fields will be set directly. OFTString fields
* will be assigned a string representation of the value, but not necessarily
* taking into account formatting constraints on this field. Other field
* types may be unaffected.
*
* This method is the same as the C function OGR_F_SetFieldInteger().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param nValue the value to assign.
*/
void OGRFeature::SetField( int iField, int nValue )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL )
return;
OGRFieldType eType = poFDefn->GetType();
if( eType == OFTInteger )
{
pauFields[iField].Integer = OGRFeatureGetIntegerValue(poFDefn, nValue);
pauFields[iField].Set.nMarker2 = 0;
}
else if( eType == OFTInteger64 )
{
pauFields[iField].Integer64 = OGRFeatureGetIntegerValue(poFDefn, nValue);
}
else if( eType == OFTReal )
{
pauFields[iField].Real = nValue;
}
else if( eType == OFTIntegerList )
{
SetField( iField, 1, &nValue );
}
else if( eType == OFTInteger64List )
{
GIntBig nVal64 = nValue;
SetField( iField, 1, &nVal64 );
}
else if( eType == OFTRealList )
{
double dfValue = nValue;
SetField( iField, 1, &dfValue );
}
else if( eType == OFTString )
{
char szTempBuffer[64];
snprintf( szTempBuffer, sizeof(szTempBuffer), "%d", nValue );
if( IsFieldSet( iField) )
CPLFree( pauFields[iField].String );
pauFields[iField].String = VSI_STRDUP_VERBOSE( szTempBuffer );
if( pauFields[iField].String == NULL )
{
pauFields[iField].Set.nMarker1 = OGRUnsetMarker;
pauFields[iField].Set.nMarker2 = OGRUnsetMarker;
}
}
else if( eType == OFTStringList )
{
char szTempBuffer[64];
snprintf( szTempBuffer, sizeof(szTempBuffer), "%d", nValue );
char *apszValues[2];
apszValues[0] = szTempBuffer;
apszValues[1] = NULL;
SetField( iField, apszValues);
}
else
{
/* do nothing for other field types */
}
}
/************************************************************************/
/* OGR_F_SetFieldInteger() */
/************************************************************************/
/**
* \brief Set field to integer value.
*
* OFTInteger, OFTInteger64 and OFTReal fields will be set directly. OFTString fields
* will be assigned a string representation of the value, but not necessarily
* taking into account formatting constraints on this field. Other field
* types may be unaffected.
*
* This function is the same as the C++ method OGRFeature::SetField().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param nValue the value to assign.
*/
void OGR_F_SetFieldInteger( OGRFeatureH hFeat, int iField, int nValue )
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetFieldInteger" );
((OGRFeature *)hFeat)->SetField( iField, nValue );
}
/************************************************************************/
/* SetField() */
/************************************************************************/
/**
* \fn OGRFeature::SetField( const char* pszFName, GIntBig nValue )
* \brief Set field to 64 bit integer value.
* OFTInteger, OFTInteger64 and OFTReal fields will be set directly. OFTString fields
* will be assigned a string representation of the value, but not necessarily
* taking into account formatting constraints on this field. Other field
* types may be unaffected.
*
* @param pszFName the name of the field to set.
* @param nValue the value to assign.
*/
/**
* \brief Set field to 64 bit integer value.
*
* OFTInteger, OFTInteger64 and OFTReal fields will be set directly. OFTString fields
* will be assigned a string representation of the value, but not necessarily
* taking into account formatting constraints on this field. Other field
* types may be unaffected.
*
* This method is the same as the C function OGR_F_SetFieldInteger64().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param nValue the value to assign.
* @since GDAL 2.0
*/
void OGRFeature::SetField( int iField, GIntBig nValue )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL )
return;
OGRFieldType eType = poFDefn->GetType();
if( eType == OFTInteger )
{
int nVal32 = (nValue < INT_MIN ) ? INT_MIN :
(nValue > INT_MAX) ? INT_MAX : (int)nValue;
if( (GIntBig)nVal32 != nValue )
{
CPLError( CE_Warning, CPLE_AppDefined,
"Integer overflow occurred when trying to set "
"32bit field." );
}
SetField(iField, nVal32);
}
else if( eType == OFTInteger64 )
{
pauFields[iField].Integer64 = nValue;
}
else if( eType == OFTReal )
{
pauFields[iField].Real = (double) nValue;
}
else if( eType == OFTIntegerList )
{
int nVal32 = (nValue < INT_MIN ) ? INT_MIN :
(nValue > INT_MAX) ? INT_MAX : (int)nValue;
if( (GIntBig)nVal32 != nValue )
{
CPLError( CE_Warning, CPLE_AppDefined,
"Integer overflow occurred when trying to set "
"32bit field." );
}
SetField( iField, 1, &nVal32 );
}
else if( eType == OFTInteger64List )
{
SetField( iField, 1, &nValue );
}
else if( eType == OFTRealList )
{
double dfValue = (double) nValue;
SetField( iField, 1, &dfValue );
}
else if( eType == OFTString )
{
char szTempBuffer[64];
snprintf( szTempBuffer, sizeof(szTempBuffer), CPL_FRMT_GIB, nValue );
if( IsFieldSet( iField) )
CPLFree( pauFields[iField].String );
pauFields[iField].String = VSI_STRDUP_VERBOSE( szTempBuffer );
if( pauFields[iField].String == NULL )
{
pauFields[iField].Set.nMarker1 = OGRUnsetMarker;
pauFields[iField].Set.nMarker2 = OGRUnsetMarker;
}
}
else if( eType == OFTStringList )
{
char szTempBuffer[64];
snprintf( szTempBuffer, sizeof(szTempBuffer), CPL_FRMT_GIB, nValue );
char *apszValues[2];
apszValues[0] = szTempBuffer;
apszValues[1] = NULL;
SetField( iField, apszValues);
}
else
{
/* do nothing for other field types */
}
}
/************************************************************************/
/* OGR_F_SetFieldInteger64() */
/************************************************************************/
/**
* \brief Set field to 64 bit integer value.
*
* OFTInteger, OFTInteger64 and OFTReal fields will be set directly. OFTString fields
* will be assigned a string representation of the value, but not necessarily
* taking into account formatting constraints on this field. Other field
* types may be unaffected.
*
* This function is the same as the C++ method OGRFeature::SetField().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param nValue the value to assign.
* @since GDAL 2.0
*/
void OGR_F_SetFieldInteger64( OGRFeatureH hFeat, int iField, GIntBig nValue )
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetFieldInteger64" );
((OGRFeature *)hFeat)->SetField( iField, nValue );
}
/************************************************************************/
/* SetField() */
/************************************************************************/
/**
* \fn OGRFeature::SetField( const char* pszFName, double dfValue )
* \brief Set field to double value.
*
* OFTInteger, OFTInteger64 and OFTReal fields will be set directly. OFTString fields
* will be assigned a string representation of the value, but not necessarily
* taking into account formatting constraints on this field. Other field
* types may be unaffected.
*
* @param pszFName the name of the field to set.
* @param dfValue the value to assign.
*/
/**
* \brief Set field to double value.
*
* OFTInteger, OFTInteger64 and OFTReal fields will be set directly. OFTString fields
* will be assigned a string representation of the value, but not necessarily
* taking into account formatting constraints on this field. Other field
* types may be unaffected.
*
* This method is the same as the C function OGR_F_SetFieldDouble().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param dfValue the value to assign.
*/
void OGRFeature::SetField( int iField, double dfValue )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL )
return;
OGRFieldType eType = poFDefn->GetType();
if( eType == OFTReal )
{
/*if( poFDefn->GetSubType() == OFSTFloat32 && dfValue != (double)(float)dfValue )
{
CPLError(CE_Warning, CPLE_AppDefined,
"Passed value cannot be exactly representing as a single-precision floating point value.");
dfValue = (double)(float)dfValue;
}*/
pauFields[iField].Real = dfValue;
}
else if( eType == OFTInteger )
{
pauFields[iField].Integer = (int) dfValue;
pauFields[iField].Set.nMarker2 = 0;
}
else if( eType == OFTInteger64 )
{
pauFields[iField].Integer64 = (GIntBig) dfValue;
}
else if( eType == OFTRealList )
{
SetField( iField, 1, &dfValue );
}
else if( eType == OFTIntegerList )
{
int nValue = (int) dfValue;
SetField( iField, 1, &nValue );
}
else if( eType == OFTInteger64List )
{
GIntBig nValue = (GIntBig) dfValue;
SetField( iField, 1, &nValue );
}
else if( eType == OFTString )
{
char szTempBuffer[128];
CPLsnprintf( szTempBuffer, sizeof(szTempBuffer), "%.16g", dfValue );
if( IsFieldSet( iField) )
CPLFree( pauFields[iField].String );
pauFields[iField].String = VSI_STRDUP_VERBOSE( szTempBuffer );
if( pauFields[iField].String == NULL )
{
pauFields[iField].Set.nMarker1 = OGRUnsetMarker;
pauFields[iField].Set.nMarker2 = OGRUnsetMarker;
}
}
else if( eType == OFTStringList )
{
char szTempBuffer[64];
CPLsnprintf( szTempBuffer, sizeof(szTempBuffer), "%.16g", dfValue );
char *apszValues[2] = {szTempBuffer, NULL};
SetField( iField, apszValues);
}
else
{
/* do nothing for other field types */
}
}
/************************************************************************/
/* OGR_F_SetFieldDouble() */
/************************************************************************/
/**
* \brief Set field to double value.
*
* OFTInteger, OFTInteger64 and OFTReal fields will be set directly. OFTString fields
* will be assigned a string representation of the value, but not necessarily
* taking into account formatting constraints on this field. Other field
* types may be unaffected.
*
* This function is the same as the C++ method OGRFeature::SetField().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param dfValue the value to assign.
*/
void OGR_F_SetFieldDouble( OGRFeatureH hFeat, int iField, double dfValue )
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetFieldDouble" );
((OGRFeature *)hFeat)->SetField( iField, dfValue );
}
/************************************************************************/
/* SetField() */
/************************************************************************/
/**
* \fn OGRFeature::SetField( const char* pszFName, const char * pszValue )
* \brief Set field to string value.
*
* OFTInteger fields will be set based on an atoi() conversion of the string.
* OFTInteger64 fields will be set based on an CPLAtoGIntBig() conversion of the string.
* OFTReal fields will be set based on an CPLAtof() conversion of the string.
* Other field types may be unaffected.
*
* @param pszFName the name of the field to set.
* @param pszValue the value to assign.
*/
/**
* \brief Set field to string value.
*
* OFTInteger fields will be set based on an atoi() conversion of the string.
* OFTInteger64 fields will be set based on an CPLAtoGIntBig() conversion of the string.
* OFTReal fields will be set based on an CPLAtof() conversion of the string.
* Other field types may be unaffected.
*
* This method is the same as the C function OGR_F_SetFieldString().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param pszValue the value to assign.
*/
void OGRFeature::SetField( int iField, const char * pszValue )
{
static int bWarn = -1;
if( bWarn < 0 )
bWarn = CPLTestBool( CPLGetConfigOption( "OGR_SETFIELD_NUMERIC_WARNING",
"YES" ) );
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL )
return;
char *pszLast = NULL;
OGRFieldType eType = poFDefn->GetType();
if( eType == OFTString )
{
if( IsFieldSet(iField) )
CPLFree( pauFields[iField].String );
pauFields[iField].String = VSI_STRDUP_VERBOSE( pszValue ? pszValue : "" );
if( pauFields[iField].String == NULL )
{
pauFields[iField].Set.nMarker1 = OGRUnsetMarker;
pauFields[iField].Set.nMarker2 = OGRUnsetMarker;
}
}
else if( eType == OFTInteger )
{
errno = 0; /* As allowed by C standard, some systems like MSVC doesn't reset errno */
long nVal = strtol(pszValue, &pszLast, 10);
nVal = OGRFeatureGetIntegerValue(poFDefn, (int)nVal);
pauFields[iField].Integer = (nVal > INT_MAX) ? INT_MAX : (nVal < INT_MIN) ? INT_MIN : (int) nVal;
if( bWarn && (errno == ERANGE || nVal != (long)pauFields[iField].Integer || !pszLast || *pszLast ) )
CPLError(CE_Warning, CPLE_AppDefined,
"Value '%s' of field %s.%s parsed incompletely to integer %d.",
pszValue, poDefn->GetName(), poFDefn->GetNameRef(), pauFields[iField].Integer );
pauFields[iField].Set.nMarker2 = OGRUnsetMarker;
}
else if( eType == OFTInteger64 )
{
pauFields[iField].Integer64 = CPLAtoGIntBigEx(pszValue, bWarn, NULL);
}
else if( eType == OFTReal )
{
pauFields[iField].Real = CPLStrtod(pszValue, &pszLast);
if( bWarn && ( !pszLast || *pszLast ) )
CPLError(CE_Warning, CPLE_AppDefined,
"Value '%s' of field %s.%s parsed incompletely to real %.16g.",
pszValue, poDefn->GetName(), poFDefn->GetNameRef(), pauFields[iField].Real );
}
else if( eType == OFTDate
|| eType == OFTTime
|| eType == OFTDateTime )
{
OGRField sWrkField;
if( OGRParseDate( pszValue, &sWrkField, 0 ) )
memcpy( pauFields+iField, &sWrkField, sizeof(sWrkField));
}
else if( eType == OFTIntegerList
|| eType == OFTInteger64List
|| eType == OFTRealList )
{
char **papszValueList = NULL;
if( pszValue[0] == '(' && strchr(pszValue,':') != NULL )
{
papszValueList = CSLTokenizeString2(
pszValue, ",:()", 0 );
}
if( papszValueList == NULL || *papszValueList == NULL
|| atoi(papszValueList[0]) != CSLCount(papszValueList)-1 )
{
/* do nothing - the count does not match entries */
}
else if( eType == OFTIntegerList )
{
int nCount = atoi(papszValueList[0]);
std::vector<int> anValues;
if( nCount == CSLCount(papszValueList)-1 )
{
for( int i = 0; i < nCount; i++ )
{
errno = 0; /* As allowed by C standard, some systems like MSVC doesn't reset errno */
int nVal = atoi(papszValueList[i+1]);
if( errno == ERANGE )
{
CPLError(CE_Warning, CPLE_AppDefined,
"32 bit integer overflow when converting %s",
pszValue);
}
anValues.push_back( nVal );
}
SetField( iField, nCount, &(anValues[0]) );
}
}
else if( eType == OFTInteger64List )
{
int nCount = atoi(papszValueList[0]);
std::vector<GIntBig> anValues;
if( nCount == CSLCount(papszValueList)-1 )
{
for( int i = 0; i < nCount; i++ )
{
GIntBig nVal = CPLAtoGIntBigEx(papszValueList[i+1], TRUE, NULL);
anValues.push_back( nVal );
}
SetField( iField, nCount, &(anValues[0]) );
}
}
else if( eType == OFTRealList )
{
int nCount = atoi(papszValueList[0]);
std::vector<double> adfValues;
if( nCount == CSLCount(papszValueList)-1 )
{
for( int i = 0; i < nCount; i++ )
adfValues.push_back( CPLAtof(papszValueList[i+1]) );
SetField( iField, nCount, &(adfValues[0]) );
}
}
CSLDestroy(papszValueList);
}
else if ( eType == OFTStringList )
{
if( pszValue && *pszValue )
{
if( pszValue[0] == '(' && strchr(pszValue,':') != NULL &&
pszValue[strlen(pszValue)-1] == ')' )
{
char** papszValueList = CSLTokenizeString2(
pszValue, ",:()", 0 );
int nCount = atoi(papszValueList[0]);
std::vector<char*> aosValues;
if( nCount == CSLCount(papszValueList)-1 )
{
for( int i = 0; i < nCount; i++ )
aosValues.push_back( papszValueList[i+1] );
aosValues.push_back( NULL );
SetField( iField, &(aosValues[0]) );
}
CSLDestroy(papszValueList);
}
else
{
const char *papszValues[2] = { pszValue, NULL };
SetField( iField, (char **) papszValues );
}
}
}
else
{
/* do nothing for other field types */;
}
}
/************************************************************************/
/* OGR_F_SetFieldString() */
/************************************************************************/
/**
* \brief Set field to string value.
*
* OFTInteger fields will be set based on an atoi() conversion of the string.
* OFTInteger64 fields will be set based on an CPLAtoGIntBig() conversion of the string.
* OFTReal fields will be set based on an CPLAtof() conversion of the string.
* Other field types may be unaffected.
*
* This function is the same as the C++ method OGRFeature::SetField().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param pszValue the value to assign.
*/
void OGR_F_SetFieldString( OGRFeatureH hFeat, int iField, const char *pszValue)
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetFieldString" );
((OGRFeature *)hFeat)->SetField( iField, pszValue );
}
/************************************************************************/
/* SetField() */
/************************************************************************/
/**
* \fn OGRFeature::SetField( const char* pszFName, int nCount, int *panValues )
* \brief Set field to list of integers value.
*
* This method currently on has an effect of OFTIntegerList, OFTInteger64List
* and OFTRealList fields.
*
* @param pszFName the name of the field to set.
* @param nCount the number of values in the list being assigned.
* @param panValues the values to assign.
*/
/**
* \brief Set field to list of integers value.
*
* This method currently on has an effect of OFTIntegerList, OFTInteger64List
* and OFTRealList fields.
*
* This method is the same as the C function OGR_F_SetFieldIntegerList().
*
* @param iField the field to set, from 0 to GetFieldCount()-1.
* @param nCount the number of values in the list being assigned.
* @param panValues the values to assign.
*/
void OGRFeature::SetField( int iField, int nCount, int *panValues )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL )
return;
OGRFieldType eType = poFDefn->GetType();
if( eType == OFTIntegerList )
{
OGRField uField;
int *panValuesMod = NULL;
if( poFDefn->GetSubType() == OFSTBoolean || poFDefn->GetSubType() == OFSTInt16 )
{
for( int i = 0; i < nCount; i++ )
{
int nVal = OGRFeatureGetIntegerValue(poFDefn, panValues[i]);
if( panValues[i] != nVal )
{
if( panValuesMod == NULL )
{
panValuesMod = static_cast<int *>(
VSI_MALLOC_VERBOSE(nCount * sizeof(int)) );
if( panValuesMod == NULL )
return;
memcpy(panValuesMod, panValues, nCount * sizeof(int));
}
panValuesMod[i] = nVal;
}
}
}
uField.IntegerList.nCount = nCount;
uField.Set.nMarker2 = 0;
uField.IntegerList.paList = panValuesMod ? panValuesMod : panValues;
SetField( iField, &uField );
CPLFree(panValuesMod);
}
else if( eType == OFTInteger64List )
{
std::vector<GIntBig> anValues;
for( int i = 0; i < nCount; i++ )
anValues.push_back( panValues[i] );
SetField( iField, nCount, &anValues[0] );
}
else if( eType == OFTRealList )
{
std::vector<double> adfValues;
for( int i = 0; i < nCount; i++ )
adfValues.push_back( (double) panValues[i] );
SetField( iField, nCount, &adfValues[0] );
}
else if( (eType == OFTInteger ||
eType == OFTInteger64 ||
eType == OFTReal)
&& nCount == 1 )
{
SetField( iField, panValues[0] );
}
else if( eType == OFTStringList )
{
char** papszValues = static_cast<char **>(
VSI_MALLOC_VERBOSE((nCount+1) * sizeof(char*)) );
if( papszValues == NULL )
return;
for( int i = 0; i < nCount; i++ )
papszValues[i] = VSI_STRDUP_VERBOSE(CPLSPrintf("%d", panValues[i]));
papszValues[nCount] = NULL;
SetField( iField, papszValues);
CSLDestroy(papszValues);
}
}
/************************************************************************/
/* OGR_F_SetFieldIntegerList() */
/************************************************************************/
/**
* \brief Set field to list of integers value.
*
* This function currently on has an effect of OFTIntegerList, OFTInteger64List
* and OFTRealList fields.
*
* This function is the same as the C++ method OGRFeature::SetField().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to set, from 0 to GetFieldCount()-1.
* @param nCount the number of values in the list being assigned.
* @param panValues the values to assign.
*/
void OGR_F_SetFieldIntegerList( OGRFeatureH hFeat, int iField,
int nCount, int *panValues )
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetFieldIntegerList" );
((OGRFeature *)hFeat)->SetField( iField, nCount, panValues );
}
/************************************************************************/
/* SetField() */
/************************************************************************/
/**
* \fn OGRFeature::SetField( const char* pszFName, int nCount, const GIntBig *panValues )
* \brief Set field to list of 64 bit integers value.
*
* This method currently on has an effect of OFTIntegerList, OFTInteger64List
* and OFTRealList fields.
*
* @param pszFName the name of the field to set.
* @param nCount the number of values in the list being assigned.
* @param panValues the values to assign.
*/
/**
* \brief Set field to list of 64 bit integers value.
*
* This method currently on has an effect of OFTIntegerList, OFTInteger64List
* and OFTRealList fields.
*
* This method is the same as the C function OGR_F_SetFieldIntege64rList().
*
* @param iField the field to set, from 0 to GetFieldCount()-1.
* @param nCount the number of values in the list being assigned.
* @param panValues the values to assign.
* @since GDAL 2.0
*/
void OGRFeature::SetField( int iField, int nCount, const GIntBig *panValues )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL )
return;
OGRFieldType eType = poFDefn->GetType();
if( eType == OFTIntegerList )
{
std::vector<int> anValues;
for( int i = 0; i < nCount; i++ )
{
GIntBig nValue = panValues[i];
int nVal32 = (nValue < INT_MIN ) ? INT_MIN :
(nValue > INT_MAX) ? INT_MAX : (int)nValue;
if( (GIntBig)nVal32 != nValue )
{
CPLError( CE_Warning, CPLE_AppDefined,
"Integer overflow occurred when trying to set "
"32bit field." );
}
anValues.push_back( nVal32 );
}
SetField( iField, nCount, &anValues[0] );
}
else if( eType == OFTInteger64List )
{
OGRField uField;
uField.Integer64List.nCount = nCount;
uField.Set.nMarker2 = 0;
uField.Integer64List.paList = (GIntBig*) panValues;
SetField( iField, &uField );
}
else if( eType == OFTRealList )
{
std::vector<double> adfValues;
for( int i = 0; i < nCount; i++ )
adfValues.push_back( (double) panValues[i] );
SetField( iField, nCount, &adfValues[0] );
}
else if( (eType == OFTInteger ||
eType == OFTInteger64 ||
eType == OFTReal)
&& nCount == 1 )
{
SetField( iField, panValues[0] );
}
else if( eType == OFTStringList )
{
char** papszValues = static_cast<char **>(
VSI_MALLOC_VERBOSE((nCount+1) * sizeof(char*)) );
if( papszValues == NULL )
return;
for( int i = 0; i < nCount; i++ )
papszValues[i] = VSI_STRDUP_VERBOSE(CPLSPrintf(CPL_FRMT_GIB, panValues[i]));
papszValues[nCount] = NULL;
SetField( iField, papszValues);
CSLDestroy(papszValues);
}
}
/************************************************************************/
/* OGR_F_SetFieldInteger64List() */
/************************************************************************/
/**
* \brief Set field to list of 64 bit integers value.
*
* This function currently on has an effect of OFTIntegerList, OFTInteger64List
* and OFTRealList fields.
*
* This function is the same as the C++ method OGRFeature::SetField().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to set, from 0 to GetFieldCount()-1.
* @param nCount the number of values in the list being assigned.
* @param panValues the values to assign.
* @since GDAL 2.0
*/
void OGR_F_SetFieldInteger64List( OGRFeatureH hFeat, int iField,
int nCount, const GIntBig *panValues )
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetFieldInteger64List" );
((OGRFeature *)hFeat)->SetField( iField, nCount, panValues );
}
/************************************************************************/
/* SetField() */
/************************************************************************/
/**
* \fn OGRFeature::SetField( const char* pszFName, int nCount, double * padfValues )
* \brief Set field to list of doubles value.
*
* This method currently on has an effect of OFTIntegerList, OFTInteger64List,
* OFTRealList fields.
*
* @param pszFName the name of the field to set.
* @param nCount the number of values in the list being assigned.
* @param padfValues the values to assign.
*/
/**
* \brief Set field to list of doubles value.
*
* This method currently on has an effect of OFTIntegerList, OFTInteger64List,
* OFTRealList fields.
*
* This method is the same as the C function OGR_F_SetFieldDoubleList().
*
* @param iField the field to set, from 0 to GetFieldCount()-1.
* @param nCount the number of values in the list being assigned.
* @param padfValues the values to assign.
*/
void OGRFeature::SetField( int iField, int nCount, double * padfValues )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL )
return;
OGRFieldType eType = poFDefn->GetType();
if( eType == OFTRealList )
{
OGRField uField;
uField.RealList.nCount = nCount;
uField.Set.nMarker2 = 0;
uField.RealList.paList = padfValues;
SetField( iField, &uField );
}
else if( eType == OFTIntegerList )
{
std::vector<int> anValues;
for( int i = 0; i < nCount; i++ )
anValues.push_back( (int) padfValues[i] );
SetField( iField, nCount, &anValues[0] );
}
else if( eType == OFTInteger64List )
{
std::vector<GIntBig> anValues;
for( int i = 0; i < nCount; i++ )
anValues.push_back( (GIntBig) padfValues[i] );
SetField( iField, nCount, &anValues[0] );
}
else if( (eType == OFTInteger ||
eType == OFTInteger64 ||
eType == OFTReal)
&& nCount == 1 )
{
SetField( iField, padfValues[0] );
}
else if( eType == OFTStringList )
{
char** papszValues = static_cast<char **>(
VSI_MALLOC_VERBOSE((nCount+1) * sizeof(char*)) );
if( papszValues == NULL )
return;
for( int i = 0; i < nCount; i++ )
papszValues[i] = VSI_STRDUP_VERBOSE(CPLSPrintf("%.16g", padfValues[i]));
papszValues[nCount] = NULL;
SetField( iField, papszValues);
CSLDestroy(papszValues);
}
}
/************************************************************************/
/* OGR_F_SetFieldDoubleList() */
/************************************************************************/
/**
* \brief Set field to list of doubles value.
*
* This function currently on has an effect of OFTIntegerList, OFTInteger64List,
* OFTRealList fields.
*
* This function is the same as the C++ method OGRFeature::SetField().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to set, from 0 to GetFieldCount()-1.
* @param nCount the number of values in the list being assigned.
* @param padfValues the values to assign.
*/
void OGR_F_SetFieldDoubleList( OGRFeatureH hFeat, int iField,
int nCount, double *padfValues )
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetFieldDoubleList" );
((OGRFeature *)hFeat)->SetField( iField, nCount, padfValues );
}
/************************************************************************/
/* SetField() */
/************************************************************************/
/**
* \fn OGRFeature::SetField( const char* pszFName, char ** papszValues )
* \brief Set field to list of strings value.
*
* This method currently on has an effect of OFTStringList fields.
*
* @param pszFName the name of the field to set.
* @param papszValues the values to assign.
*/
/**
* \brief Set field to list of strings value.
*
* This method currently on has an effect of OFTStringList fields.
*
* This method is the same as the C function OGR_F_SetFieldStringList().
*
* @param iField the field to set, from 0 to GetFieldCount()-1.
* @param papszValues the values to assign.
*/
void OGRFeature::SetField( int iField, char ** papszValues )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL )
return;
OGRFieldType eType = poFDefn->GetType();
if( eType == OFTStringList )
{
OGRField uField;
uField.StringList.nCount = CSLCount(papszValues);
uField.Set.nMarker2 = 0;
uField.StringList.paList = papszValues;
SetField( iField, &uField );
}
else if( eType == OFTIntegerList )
{
int nValues = CSLCount(papszValues);
int* panValues = static_cast<int *>(
VSI_MALLOC_VERBOSE(nValues * sizeof(int)) );
if( panValues == NULL )
return;
for( int i = 0; i < nValues; i++ )
{
errno = 0; /* As allowed by C standard, some systems like MSVC doesn't reset errno */
int nVal = atoi(papszValues[i]);
if( errno == ERANGE )
{
CPLError(CE_Warning, CPLE_AppDefined,
"32 bit integer overflow when converting %s",
papszValues[i]);
if( papszValues[i][0] == '-' )
nVal = INT_MIN;
else
nVal = INT_MAX;
}
panValues[i] = nVal;
}
SetField( iField, nValues, panValues );
CPLFree(panValues);
}
else if( eType == OFTInteger64List )
{
int nValues = CSLCount(papszValues);
GIntBig* panValues = static_cast<GIntBig *>(
VSI_MALLOC_VERBOSE(nValues * sizeof(GIntBig)) );
if( panValues == NULL )
return;
for( int i = 0; i < nValues; i++ )
{
panValues[i] = CPLAtoGIntBigEx(papszValues[i], TRUE, NULL);
}
SetField( iField, nValues, panValues );
CPLFree(panValues);
}
else if( eType == OFTRealList )
{
int nValues = CSLCount(papszValues);
double* padfValues = static_cast<double *>(
VSI_MALLOC_VERBOSE(nValues * sizeof(double)) );
if( padfValues == NULL )
return;
for( int i = 0; i < nValues; i++ )
{
padfValues[i] = CPLAtof(papszValues[i]);
}
SetField( iField, nValues, padfValues );
CPLFree(padfValues);
}
}
/************************************************************************/
/* OGR_F_SetFieldStringList() */
/************************************************************************/
/**
* \brief Set field to list of strings value.
*
* This function currently on has an effect of OFTStringList fields.
*
* This function is the same as the C++ method OGRFeature::SetField().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to set, from 0 to GetFieldCount()-1.
* @param papszValues the values to assign.
*/
void OGR_F_SetFieldStringList( OGRFeatureH hFeat, int iField,
char ** papszValues )
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetFieldStringList" );
((OGRFeature *)hFeat)->SetField( iField, papszValues );
}
/************************************************************************/
/* SetField() */
/************************************************************************/
/**
* \brief Set field to binary data.
*
* This method currently on has an effect of OFTBinary fields.
*
* This method is the same as the C function OGR_F_SetFieldBinary().
*
* @param iField the field to set, from 0 to GetFieldCount()-1.
* @param nBytes bytes of data being set.
* @param pabyData the raw data being applied.
*/
void OGRFeature::SetField( int iField, int nBytes, GByte *pabyData )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL )
return;
OGRFieldType eType = poFDefn->GetType();
if( eType == OFTBinary )
{
OGRField uField;
uField.Binary.nCount = nBytes;
uField.Set.nMarker2 = 0;
uField.Binary.paData = pabyData;
SetField( iField, &uField );
}
else if( eType == OFTString || eType == OFTStringList )
{
char* pszStr = static_cast<char *>( VSI_MALLOC_VERBOSE(nBytes + 1) );
if( pszStr == NULL )
return;
memcpy(pszStr, pabyData, nBytes);
pszStr[nBytes] = 0;
SetField( iField, pszStr );
CPLFree( pszStr);
}
}
/************************************************************************/
/* OGR_F_SetFieldBinary() */
/************************************************************************/
/**
* \brief Set field to binary data.
*
* This function currently on has an effect of OFTBinary fields.
*
* This function is the same as the C++ method OGRFeature::SetField().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to set, from 0 to GetFieldCount()-1.
* @param nBytes the number of bytes in pabyData array.
* @param pabyData the data to apply.
*/
void OGR_F_SetFieldBinary( OGRFeatureH hFeat, int iField,
int nBytes, GByte *pabyData )
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetFieldBinary" );
((OGRFeature *)hFeat)->SetField( iField, nBytes, pabyData );
}
/************************************************************************/
/* SetField() */
/************************************************************************/
/**
* \fn OGRFeature::SetField( const char* pszFName, int nYear, int nMonth, int nDay,
* int nHour, int nMinute, float fSecond,
* int nTZFlag )
* \brief Set field to date.
*
* This method currently only has an effect for OFTDate, OFTTime and OFTDateTime
* fields.
*
* @param pszFName the name of the field to set.
* @param nYear (including century)
* @param nMonth (1-12)
* @param nDay (1-31)
* @param nHour (0-23)
* @param nMinute (0-59)
* @param fSecond (0-59, with millisecond accuracy)
* @param nTZFlag (0=unknown, 1=localtime, 100=GMT, see data model for details)
*/
/**
* \brief Set field to date.
*
* This method currently only has an effect for OFTDate, OFTTime and OFTDateTime
* fields.
*
* This method is the same as the C function OGR_F_SetFieldDateTime().
*
* @param iField the field to set, from 0 to GetFieldCount()-1.
* @param nYear (including century)
* @param nMonth (1-12)
* @param nDay (1-31)
* @param nHour (0-23)
* @param nMinute (0-59)
* @param fSecond (0-59, with millisecond accuracy)
* @param nTZFlag (0=unknown, 1=localtime, 100=GMT, see data model for details)
*/
void OGRFeature::SetField( int iField, int nYear, int nMonth, int nDay,
int nHour, int nMinute, float fSecond,
int nTZFlag )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL )
return;
OGRFieldType eType = poFDefn->GetType();
if( eType == OFTDate
|| eType == OFTTime
|| eType == OFTDateTime )
{
if( (GInt16)nYear != nYear )
{
CPLError(CE_Failure, CPLE_NotSupported,
"Years < -32768 or > 32767 are not supported");
return;
}
pauFields[iField].Date.Year = (GInt16)nYear;
pauFields[iField].Date.Month = (GByte)nMonth;
pauFields[iField].Date.Day = (GByte)nDay;
pauFields[iField].Date.Hour = (GByte)nHour;
pauFields[iField].Date.Minute = (GByte)nMinute;
pauFields[iField].Date.Second = fSecond;
pauFields[iField].Date.TZFlag = (GByte)nTZFlag;
}
else if( eType == OFTString || eType == OFTStringList )
{
char szTempBuffer[TEMP_BUFFER_SIZE];
OGRFeatureFormatDateTimeBuffer(szTempBuffer,
nYear,
nMonth,
nDay,
nHour,
nMinute,
fSecond,
nTZFlag);
SetField( iField, szTempBuffer );
}
}
/************************************************************************/
/* OGR_F_SetFieldDateTime() */
/************************************************************************/
/**
* \brief Set field to datetime.
*
* This method currently only has an effect for OFTDate, OFTTime and OFTDateTime
* fields.
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to set, from 0 to GetFieldCount()-1.
* @param nYear (including century)
* @param nMonth (1-12)
* @param nDay (1-31)
* @param nHour (0-23)
* @param nMinute (0-59)
* @param nSecond (0-59)
* @param nTZFlag (0=unknown, 1=localtime, 100=GMT, see data model for details)
*
* @see Use OGR_F_SetFieldDateTimeEx() for second with millisecond accuracy.
*/
void OGR_F_SetFieldDateTime( OGRFeatureH hFeat, int iField,
int nYear, int nMonth, int nDay,
int nHour, int nMinute, int nSecond,
int nTZFlag )
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetFieldDateTime" );
((OGRFeature *)hFeat)->SetField( iField, nYear, nMonth, nDay,
nHour, nMinute, static_cast<float>(nSecond), nTZFlag );
}
/************************************************************************/
/* OGR_F_SetFieldDateTimeEx() */
/************************************************************************/
/**
* \brief Set field to datetime.
*
* This method currently only has an effect for OFTDate, OFTTime and OFTDateTime
* fields.
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to set, from 0 to GetFieldCount()-1.
* @param nYear (including century)
* @param nMonth (1-12)
* @param nDay (1-31)
* @param nHour (0-23)
* @param nMinute (0-59)
* @param fSecond (0-59, with millisecond accuracy)
* @param nTZFlag (0=unknown, 1=localtime, 100=GMT, see data model for details)
*
* @since GDAL 2.0
*/
void OGR_F_SetFieldDateTimeEx( OGRFeatureH hFeat, int iField,
int nYear, int nMonth, int nDay,
int nHour, int nMinute, float fSecond,
int nTZFlag )
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetFieldDateTimeEx" );
((OGRFeature *)hFeat)->SetField( iField, nYear, nMonth, nDay,
nHour, nMinute, fSecond, nTZFlag );
}
/************************************************************************/
/* SetField() */
/************************************************************************/
/**
* \fn OGRFeature::SetField( const char* pszFName, OGRField * puValue )
* \brief Set field.
*
* The passed value OGRField must be of exactly the same type as the
* target field, or an application crash may occur. The passed value
* is copied, and will not be affected. It remains the responsibility of
* the caller.
* @param pszFName the name of the field to set.
* @param puValue the value to assign.
*/
/**
* \brief Set field.
*
* The passed value OGRField must be of exactly the same type as the
* target field, or an application crash may occur. The passed value
* is copied, and will not be affected. It remains the responsibility of
* the caller.
*
* This method is the same as the C function OGR_F_SetFieldRaw().
*
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param puValue the value to assign.
*/
void OGRFeature::SetField( int iField, OGRField * puValue )
{
SetFieldInternal( iField, puValue );
}
bool OGRFeature::SetFieldInternal( int iField, OGRField * puValue )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn( iField );
if( poFDefn == NULL )
return false;
if( poFDefn->GetType() == OFTInteger )
{
pauFields[iField] = *puValue;
}
else if( poFDefn->GetType() == OFTInteger64 )
{
pauFields[iField] = *puValue;
}
else if( poFDefn->GetType() == OFTInteger64 )
{
pauFields[iField] = *puValue;
}
else if( poFDefn->GetType() == OFTReal )
{
pauFields[iField] = *puValue;
}
else if( poFDefn->GetType() == OFTString )
{
if( IsFieldSet( iField ) )
CPLFree( pauFields[iField].String );
if( puValue->String == NULL )
pauFields[iField].String = NULL;
else if( puValue->Set.nMarker1 == OGRUnsetMarker
&& puValue->Set.nMarker2 == OGRUnsetMarker )
pauFields[iField] = *puValue;
else
{
pauFields[iField].String = VSI_STRDUP_VERBOSE( puValue->String );
if( pauFields[iField].String == NULL )
{
pauFields[iField].Set.nMarker1 = OGRUnsetMarker;
pauFields[iField].Set.nMarker2 = OGRUnsetMarker;
return false;
}
}
}
else if( poFDefn->GetType() == OFTDate
|| poFDefn->GetType() == OFTTime
|| poFDefn->GetType() == OFTDateTime )
{
memcpy( pauFields+iField, puValue, sizeof(OGRField) );
}
else if( poFDefn->GetType() == OFTIntegerList )
{
int nCount = puValue->IntegerList.nCount;
if( IsFieldSet( iField ) )
CPLFree( pauFields[iField].IntegerList.paList );
if( puValue->Set.nMarker1 == OGRUnsetMarker
&& puValue->Set.nMarker2 == OGRUnsetMarker )
{
pauFields[iField] = *puValue;
}
else
{
pauFields[iField].IntegerList.paList =
static_cast<int *>( VSI_MALLOC_VERBOSE(sizeof(int) * nCount) );
if( pauFields[iField].IntegerList.paList == NULL )
{
pauFields[iField].Set.nMarker1 = OGRUnsetMarker;
pauFields[iField].Set.nMarker2 = OGRUnsetMarker;
return false;
}
memcpy( pauFields[iField].IntegerList.paList,
puValue->IntegerList.paList,
sizeof(int) * nCount );
pauFields[iField].IntegerList.nCount = nCount;
}
}
else if( poFDefn->GetType() == OFTInteger64List )
{
int nCount = puValue->Integer64List.nCount;
if( IsFieldSet( iField ) )
CPLFree( pauFields[iField].Integer64List.paList );
if( puValue->Set.nMarker1 == OGRUnsetMarker
&& puValue->Set.nMarker2 == OGRUnsetMarker )
{
pauFields[iField] = *puValue;
}
else
{
pauFields[iField].Integer64List.paList = static_cast<GIntBig *>(
VSI_MALLOC_VERBOSE(sizeof(GIntBig) * nCount) );
if( pauFields[iField].Integer64List.paList == NULL )
{
pauFields[iField].Set.nMarker1 = OGRUnsetMarker;
pauFields[iField].Set.nMarker2 = OGRUnsetMarker;
return false;
}
memcpy( pauFields[iField].Integer64List.paList,
puValue->Integer64List.paList,
sizeof(GIntBig) * nCount );
pauFields[iField].Integer64List.nCount = nCount;
}
}
else if( poFDefn->GetType() == OFTRealList )
{
int nCount = puValue->RealList.nCount;
if( IsFieldSet( iField ) )
CPLFree( pauFields[iField].RealList.paList );
if( puValue->Set.nMarker1 == OGRUnsetMarker
&& puValue->Set.nMarker2 == OGRUnsetMarker )
{
pauFields[iField] = *puValue;
}
else
{
pauFields[iField].RealList.paList = static_cast<double *>(
VSI_MALLOC_VERBOSE(sizeof(double) * nCount) );
if( pauFields[iField].RealList.paList == NULL )
{
pauFields[iField].Set.nMarker1 = OGRUnsetMarker;
pauFields[iField].Set.nMarker2 = OGRUnsetMarker;
return false;
}
memcpy( pauFields[iField].RealList.paList,
puValue->RealList.paList,
sizeof(double) * nCount );
pauFields[iField].RealList.nCount = nCount;
}
}
else if( poFDefn->GetType() == OFTStringList )
{
if( IsFieldSet( iField ) )
CSLDestroy( pauFields[iField].StringList.paList );
if( puValue->Set.nMarker1 == OGRUnsetMarker
&& puValue->Set.nMarker2 == OGRUnsetMarker )
{
pauFields[iField] = *puValue;
}
else
{
char** papszNewList = NULL;
for( char** papszIter = puValue->StringList.paList;
papszIter != NULL && *papszIter != NULL;
++papszIter )
{
char** papszNewList2 = CSLAddStringMayFail(papszNewList, *papszIter);
if( papszNewList2 == NULL )
{
CSLDestroy(papszNewList);
pauFields[iField].Set.nMarker1 = OGRUnsetMarker;
pauFields[iField].Set.nMarker2 = OGRUnsetMarker;
return false;
}
papszNewList = papszNewList2;
}
pauFields[iField].StringList.paList = papszNewList;
pauFields[iField].StringList.nCount = puValue->StringList.nCount;
CPLAssert( CSLCount(puValue->StringList.paList)
== puValue->StringList.nCount );
}
}
else if( poFDefn->GetType() == OFTBinary )
{
if( IsFieldSet( iField ) )
CPLFree( pauFields[iField].Binary.paData );
if( puValue->Set.nMarker1 == OGRUnsetMarker
&& puValue->Set.nMarker2 == OGRUnsetMarker )
{
pauFields[iField] = *puValue;
}
else
{
pauFields[iField].Binary.paData = static_cast<GByte *>(
VSI_MALLOC_VERBOSE(puValue->Binary.nCount) );
if( pauFields[iField].Binary.paData == NULL )
{
pauFields[iField].Set.nMarker1 = OGRUnsetMarker;
pauFields[iField].Set.nMarker2 = OGRUnsetMarker;
return false;
}
memcpy( pauFields[iField].Binary.paData,
puValue->Binary.paData,
puValue->Binary.nCount );
pauFields[iField].Binary.nCount = puValue->Binary.nCount;
}
}
else
{
/* do nothing for other field types */
}
return true;
}
/************************************************************************/
/* OGR_F_SetFieldRaw() */
/************************************************************************/
/**
* \brief Set field.
*
* The passed value OGRField must be of exactly the same type as the
* target field, or an application crash may occur. The passed value
* is copied, and will not be affected. It remains the responsibility of
* the caller.
*
* This function is the same as the C++ method OGRFeature::SetField().
*
* @param hFeat handle to the feature that owned the field.
* @param iField the field to fetch, from 0 to GetFieldCount()-1.
* @param psValue handle on the value to assign.
*/
void OGR_F_SetFieldRaw( OGRFeatureH hFeat, int iField, OGRField *psValue )
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetFieldRaw" );
((OGRFeature *)hFeat)->SetField( iField, psValue );
}
/************************************************************************/
/* DumpReadable() */
/************************************************************************/
/**
* \brief Dump this feature in a human readable form.
*
* This dumps the attributes, and geometry; however, it doesn't definition
* information (other than field types and names), nor does it report the
* geometry spatial reference system.
*
* A few options can be defined to change the default dump :
* <ul>
* <li>DISPLAY_FIELDS=NO : to hide the dump of the attributes</li>
* <li>DISPLAY_STYLE=NO : to hide the dump of the style string</li>
* <li>DISPLAY_GEOMETRY=NO : to hide the dump of the geometry</li>
* <li>DISPLAY_GEOMETRY=SUMMARY : to get only a summary of the geometry</li>
* </ul>
*
* This method is the same as the C function OGR_F_DumpReadable().
*
* @param fpOut the stream to write to, such as stdout. If NULL stdout will
* be used.
* @param papszOptions NULL terminated list of options (may be NULL)
*/
void OGRFeature::DumpReadable( FILE * fpOut, char** papszOptions )
{
if( fpOut == NULL )
fpOut = stdout;
fprintf( fpOut, "OGRFeature(%s):" CPL_FRMT_GIB "\n", poDefn->GetName(), GetFID() );
const char* pszDisplayFields =
CSLFetchNameValue(papszOptions, "DISPLAY_FIELDS");
if( pszDisplayFields == NULL || CPLTestBool(pszDisplayFields) )
{
for( int iField = 0; iField < GetFieldCount(); iField++ )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn(iField);
const char* pszType = (poFDefn->GetSubType() != OFSTNone) ?
CPLSPrintf("%s(%s)",
poFDefn->GetFieldTypeName( poFDefn->GetType() ),
poFDefn->GetFieldSubTypeName(poFDefn->GetSubType())) :
poFDefn->GetFieldTypeName( poFDefn->GetType() );
fprintf( fpOut, " %s (%s) = ",
poFDefn->GetNameRef(),
pszType );
if( IsFieldSet( iField ) )
fprintf( fpOut, "%s\n", GetFieldAsString( iField ) );
else
fprintf( fpOut, "(null)\n" );
}
}
if( GetStyleString() != NULL )
{
const char* pszDisplayStyle =
CSLFetchNameValue(papszOptions, "DISPLAY_STYLE");
if( pszDisplayStyle == NULL || CPLTestBool(pszDisplayStyle) )
{
fprintf( fpOut, " Style = %s\n", GetStyleString() );
}
}
int nGeomFieldCount = GetGeomFieldCount();
if( nGeomFieldCount > 0 )
{
const char* pszDisplayGeometry =
CSLFetchNameValue(papszOptions, "DISPLAY_GEOMETRY");
if ( ! (pszDisplayGeometry != NULL && EQUAL(pszDisplayGeometry, "NO") ) )
{
for( int iField = 0; iField < nGeomFieldCount; iField++ )
{
OGRGeomFieldDefn *poFDefn = poDefn->GetGeomFieldDefn(iField);
if( papoGeometries[iField] != NULL )
{
fprintf( fpOut, " " );
if( strlen(poFDefn->GetNameRef()) > 0 && GetGeomFieldCount() > 1 )
fprintf( fpOut, "%s = ", poFDefn->GetNameRef() );
papoGeometries[iField]->dumpReadable( fpOut, "", papszOptions );
}
}
}
}
fprintf( fpOut, "\n" );
}
/************************************************************************/
/* OGR_F_DumpReadable() */
/************************************************************************/
/**
* \brief Dump this feature in a human readable form.
*
* This dumps the attributes, and geometry; however, it doesn't definition
* information (other than field types and names), nor does it report the
* geometry spatial reference system.
*
* This function is the same as the C++ method OGRFeature::DumpReadable().
*
* @param hFeat handle to the feature to dump.
* @param fpOut the stream to write to, such as strout.
*/
void OGR_F_DumpReadable( OGRFeatureH hFeat, FILE *fpOut )
{
VALIDATE_POINTER0( hFeat, "OGR_F_DumpReadable" );
((OGRFeature *) hFeat)->DumpReadable( fpOut );
}
/************************************************************************/
/* GetFID() */
/************************************************************************/
/**
* \fn GIntBig OGRFeature::GetFID() const;
*
* \brief Get feature identifier.
*
* This method is the same as the C function OGR_F_GetFID().
* Note: since GDAL 2.0, this method returns a GIntBig (previously a long)
*
* @return feature id or OGRNullFID if none has been assigned.
*/
/************************************************************************/
/* OGR_F_GetFID() */
/************************************************************************/
/**
* \brief Get feature identifier.
*
* This function is the same as the C++ method OGRFeature::GetFID().
* Note: since GDAL 2.0, this method returns a GIntBig (previously a long)
*
* @param hFeat handle to the feature from which to get the feature
* identifier.
* @return feature id or OGRNullFID if none has been assigned.
*/
GIntBig OGR_F_GetFID( OGRFeatureH hFeat )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetFID", 0 );
return ((OGRFeature *) hFeat)->GetFID();
}
/************************************************************************/
/* SetFID() */
/************************************************************************/
/**
* \brief Set the feature identifier.
*
* For specific types of features this operation may fail on illegal
* features ids. Generally it always succeeds. Feature ids should be
* greater than or equal to zero, with the exception of OGRNullFID (-1)
* indicating that the feature id is unknown.
*
* This method is the same as the C function OGR_F_SetFID().
*
* @param nFIDIn the new feature identifier value to assign.
*
* @return On success OGRERR_NONE, or on failure some other value.
*/
OGRErr OGRFeature::SetFID( GIntBig nFIDIn )
{
nFID = nFIDIn;
return OGRERR_NONE;
}
/************************************************************************/
/* OGR_F_SetFID() */
/************************************************************************/
/**
* \brief Set the feature identifier.
*
* For specific types of features this operation may fail on illegal
* features ids. Generally it always succeeds. Feature ids should be
* greater than or equal to zero, with the exception of OGRNullFID (-1)
* indicating that the feature id is unknown.
*
* This function is the same as the C++ method OGRFeature::SetFID().
*
* @param hFeat handle to the feature to set the feature id to.
* @param nFID the new feature identifier value to assign.
*
* @return On success OGRERR_NONE, or on failure some other value.
*/
OGRErr OGR_F_SetFID( OGRFeatureH hFeat, GIntBig nFID )
{
VALIDATE_POINTER1( hFeat, "OGR_F_SetFID", OGRERR_FAILURE );
return ((OGRFeature *) hFeat)->SetFID(nFID);
}
/************************************************************************/
/* Equal() */
/************************************************************************/
/**
* \brief Test if two features are the same.
*
* Two features are considered equal if the share them (pointer equality)
* same OGRFeatureDefn, have the same field values, and the same geometry
* (as tested by OGRGeometry::Equal()) as well as the same feature id.
*
* This method is the same as the C function OGR_F_Equal().
*
* @param poFeature the other feature to test this one against.
*
* @return TRUE if they are equal, otherwise FALSE.
*/
OGRBoolean OGRFeature::Equal( OGRFeature * poFeature )
{
if( poFeature == this )
return TRUE;
if( GetFID() != poFeature->GetFID() )
return FALSE;
if( GetDefnRef() != poFeature->GetDefnRef() )
return FALSE;
int nFields = GetDefnRef()->GetFieldCount();
for( int i = 0; i < nFields; i++ )
{
if( IsFieldSet(i) != poFeature->IsFieldSet(i) )
return FALSE;
if( !IsFieldSet(i) )
continue;
switch (GetDefnRef()->GetFieldDefn(i)->GetType() )
{
case OFTInteger:
if( GetFieldAsInteger(i) !=
poFeature->GetFieldAsInteger(i) )
return FALSE;
break;
case OFTInteger64:
if( GetFieldAsInteger64(i) !=
poFeature->GetFieldAsInteger64(i) )
return FALSE;
break;
case OFTReal:
if( GetFieldAsDouble(i) !=
poFeature->GetFieldAsDouble(i) )
return FALSE;
break;
case OFTString:
if ( strcmp(GetFieldAsString(i),
poFeature->GetFieldAsString(i)) != 0 )
return FALSE;
break;
case OFTIntegerList:
{
int nCount1, nCount2;
const int* pnList1 = GetFieldAsIntegerList(i, &nCount1);
const int* pnList2 =
poFeature->GetFieldAsIntegerList(i, &nCount2);
if( nCount1 != nCount2 )
return FALSE;
for( int j = 0; j < nCount1; j++ )
{
if( pnList1[j] != pnList2[j] )
return FALSE;
}
break;
}
case OFTInteger64List:
{
int nCount1, nCount2;
const GIntBig* pnList1 = GetFieldAsInteger64List(i, &nCount1);
const GIntBig* pnList2 =
poFeature->GetFieldAsInteger64List(i, &nCount2);
if( nCount1 != nCount2 )
return FALSE;
for( int j = 0; j < nCount1; j++ )
{
if( pnList1[j] != pnList2[j] )
return FALSE;
}
break;
}
case OFTRealList:
{
int nCount1, nCount2;
const double* padfList1 =
GetFieldAsDoubleList(i, &nCount1);
const double* padfList2 =
poFeature->GetFieldAsDoubleList(i, &nCount2);
if( nCount1 != nCount2 )
return FALSE;
for( int j = 0; j < nCount1; j++ )
{
if( padfList1[j] != padfList2[j] )
return FALSE;
}
break;
}
case OFTStringList:
{
int nCount1, nCount2;
char** papszList1 = GetFieldAsStringList(i);
char** papszList2 = poFeature->GetFieldAsStringList(i);
nCount1 = CSLCount(papszList1);
nCount2 = CSLCount(papszList2);
if( nCount1 != nCount2 )
return FALSE;
for( int j = 0; j < nCount1; j++ )
{
if( strcmp(papszList1[j], papszList2[j]) != 0 )
return FALSE;
}
break;
}
case OFTTime:
case OFTDate:
case OFTDateTime:
{
int nYear1, nMonth1, nDay1, nHour1,
nMinute1, nTZFlag1;
int nYear2, nMonth2, nDay2, nHour2,
nMinute2, nTZFlag2;
float fSecond1, fSecond2;
GetFieldAsDateTime(i, &nYear1, &nMonth1, &nDay1,
&nHour1, &nMinute1, &fSecond1, &nTZFlag1);
poFeature->GetFieldAsDateTime(i, &nYear2, &nMonth2, &nDay2,
&nHour2, &nMinute2, &fSecond2, &nTZFlag2);
if( !(nYear1 == nYear2 && nMonth1 == nMonth2 &&
nDay1 == nDay2 && nHour1 == nHour2 &&
nMinute1 == nMinute2 && fSecond1 == fSecond2 &&
nTZFlag1 == nTZFlag2) )
return FALSE;
break;
}
case OFTBinary:
{
int nCount1, nCount2;
GByte* pabyData1 = GetFieldAsBinary(i, &nCount1);
GByte* pabyData2 = poFeature->GetFieldAsBinary(i, &nCount2);
if( nCount1 != nCount2 )
return FALSE;
if( memcmp(pabyData1, pabyData2, nCount1) != 0 )
return FALSE;
break;
}
default:
if( strcmp(GetFieldAsString(i),
poFeature->GetFieldAsString(i)) != 0 )
return FALSE;
break;
}
}
int nGeomFieldCount = GetGeomFieldCount();
for( int i = 0; i < nGeomFieldCount; i++ )
{
OGRGeometry* poThisGeom = GetGeomFieldRef(i);
OGRGeometry* poOtherGeom = poFeature->GetGeomFieldRef(i);
if( poThisGeom == NULL && poOtherGeom != NULL )
return FALSE;
if( poThisGeom != NULL && poOtherGeom == NULL )
return FALSE;
if( poThisGeom != NULL && poOtherGeom != NULL
&& (!poThisGeom->Equals( poOtherGeom ) ) )
return FALSE;
}
return TRUE;
}
/************************************************************************/
/* OGR_F_Equal() */
/************************************************************************/
/**
* \brief Test if two features are the same.
*
* Two features are considered equal if the share them (handle equality)
* same OGRFeatureDefn, have the same field values, and the same geometry
* (as tested by OGR_G_Equal()) as well as the same feature id.
*
* This function is the same as the C++ method OGRFeature::Equal().
*
* @param hFeat handle to one of the feature.
* @param hOtherFeat handle to the other feature to test this one against.
*
* @return TRUE if they are equal, otherwise FALSE.
*/
int OGR_F_Equal( OGRFeatureH hFeat, OGRFeatureH hOtherFeat )
{
VALIDATE_POINTER1( hFeat, "OGR_F_Equal", 0 );
VALIDATE_POINTER1( hOtherFeat, "OGR_F_Equal", 0 );
return ((OGRFeature *) hFeat)->Equal( (OGRFeature *) hOtherFeat );
}
/************************************************************************/
/* SetFrom() */
/************************************************************************/
/**
* \brief Set one feature from another.
*
* Overwrite the contents of this feature from the geometry and attributes
* of another. The poSrcFeature does not need to have the same
* OGRFeatureDefn. Field values are copied by corresponding field names.
* Field types do not have to exactly match. SetField() method conversion
* rules will be applied as needed.
*
* This method is the same as the C function OGR_F_SetFrom().
*
* @param poSrcFeature the feature from which geometry, and field values will
* be copied.
*
* @param bForgiving TRUE if the operation should continue despite lacking
* output fields matching some of the source fields.
*
* @return OGRERR_NONE if the operation succeeds, even if some values are
* not transferred, otherwise an error code.
*/
OGRErr OGRFeature::SetFrom( OGRFeature * poSrcFeature, int bForgiving )
{
/* -------------------------------------------------------------------- */
/* Retrieve the field ids by name. */
/* -------------------------------------------------------------------- */
int *panMap = static_cast<int *>(
VSI_MALLOC_VERBOSE( sizeof(int) * poSrcFeature->GetFieldCount() ) );
if( panMap == NULL )
return OGRERR_FAILURE;
for( int iField = 0; iField < poSrcFeature->GetFieldCount(); iField++ )
{
panMap[iField] = GetFieldIndex(
poSrcFeature->GetFieldDefnRef(iField)->GetNameRef() );
if( panMap[iField] == -1 )
{
if( bForgiving )
continue;
else
{
VSIFree(panMap);
return OGRERR_FAILURE;
}
}
}
const OGRErr eErr = SetFrom( poSrcFeature, panMap, bForgiving );
VSIFree(panMap);
return eErr;
}
/************************************************************************/
/* OGR_F_SetFrom() */
/************************************************************************/
/**
* \brief Set one feature from another.
*
* Overwrite the contents of this feature from the geometry and attributes
* of another. The hOtherFeature does not need to have the same
* OGRFeatureDefn. Field values are copied by corresponding field names.
* Field types do not have to exactly match. OGR_F_SetField*() function
* conversion rules will be applied as needed.
*
* This function is the same as the C++ method OGRFeature::SetFrom().
*
* @param hFeat handle to the feature to set to.
* @param hOtherFeat handle to the feature from which geometry,
* and field values will be copied.
*
* @param bForgiving TRUE if the operation should continue despite lacking
* output fields matching some of the source fields.
*
* @return OGRERR_NONE if the operation succeeds, even if some values are
* not transferred, otherwise an error code.
*/
OGRErr OGR_F_SetFrom( OGRFeatureH hFeat, OGRFeatureH hOtherFeat,
int bForgiving )
{
VALIDATE_POINTER1( hFeat, "OGR_F_SetFrom", OGRERR_FAILURE );
VALIDATE_POINTER1( hOtherFeat, "OGR_F_SetFrom", OGRERR_FAILURE );
return ((OGRFeature *) hFeat)->SetFrom( (OGRFeature *) hOtherFeat,
bForgiving );
}
/************************************************************************/
/* SetFrom() */
/************************************************************************/
/**
* \brief Set one feature from another.
*
* Overwrite the contents of this feature from the geometry and attributes
* of another. The poSrcFeature does not need to have the same
* OGRFeatureDefn. Field values are copied according to the provided indices
* map. Field types do not have to exactly match. SetField() method
* conversion rules will be applied as needed. This is more efficient than
* OGR_F_SetFrom() in that this doesn't lookup the fields by their names.
* Particularly useful when the field names don't match.
*
* This method is the same as the C function OGR_F_SetFromWithMap().
*
* @param poSrcFeature the feature from which geometry, and field values will
* be copied.
*
* @param panMap Array of the indices of the feature's fields
* stored at the corresponding index of the source feature's fields. A value of
* -1 should be used to ignore the source's field. The array should not be NULL
* and be as long as the number of fields in the source feature.
*
* @param bForgiving TRUE if the operation should continue despite lacking
* output fields matching some of the source fields.
*
* @return OGRERR_NONE if the operation succeeds, even if some values are
* not transferred, otherwise an error code.
*/
OGRErr OGRFeature::SetFrom( OGRFeature * poSrcFeature, int *panMap ,
int bForgiving )
{
OGRErr eErr;
if( poSrcFeature == this )
return OGRERR_FAILURE;
SetFID( OGRNullFID );
/* -------------------------------------------------------------------- */
/* Set the geometry. */
/* -------------------------------------------------------------------- */
if( GetGeomFieldCount() == 1 )
{
OGRGeomFieldDefn* poGFieldDefn = GetGeomFieldDefnRef(0);
int iSrc = poSrcFeature->GetGeomFieldIndex(
poGFieldDefn->GetNameRef());
if( iSrc >= 0 )
SetGeomField( 0, poSrcFeature->GetGeomFieldRef(iSrc) );
else
/* whatever the geometry field names are. For backward compatibility */
SetGeomField( 0, poSrcFeature->GetGeomFieldRef(0) );
}
else
{
for( int i = 0; i < GetGeomFieldCount(); i++ )
{
OGRGeomFieldDefn* poGFieldDefn = GetGeomFieldDefnRef(i);
int iSrc = poSrcFeature->GetGeomFieldIndex(
poGFieldDefn->GetNameRef());
if( iSrc >= 0 )
SetGeomField( i, poSrcFeature->GetGeomFieldRef(iSrc) );
else
SetGeomField( i, NULL );
}
}
/* -------------------------------------------------------------------- */
/* Copy feature style string. */
/* -------------------------------------------------------------------- */
SetStyleString( poSrcFeature->GetStyleString() );
/* -------------------------------------------------------------------- */
/* Copy native data. */
/* -------------------------------------------------------------------- */
SetNativeData( poSrcFeature->GetNativeData() );
SetNativeMediaType( poSrcFeature->GetNativeMediaType() );
/* -------------------------------------------------------------------- */
/* Set the fields by name. */
/* -------------------------------------------------------------------- */
eErr = SetFieldsFrom( poSrcFeature, panMap, bForgiving );
if( eErr != OGRERR_NONE )
return eErr;
return OGRERR_NONE;
}
/************************************************************************/
/* OGR_F_SetFromWithMap() */
/************************************************************************/
/**
* \brief Set one feature from another.
*
* Overwrite the contents of this feature from the geometry and attributes
* of another. The hOtherFeature does not need to have the same
* OGRFeatureDefn. Field values are copied according to the provided indices
* map. Field types do not have to exactly match. OGR_F_SetField*() function
* conversion rules will be applied as needed. This is more efficient than
* OGR_F_SetFrom() in that this doesn't lookup the fields by their names.
* Particularly useful when the field names don't match.
*
* This function is the same as the C++ method OGRFeature::SetFrom().
*
* @param hFeat handle to the feature to set to.
* @param hOtherFeat handle to the feature from which geometry,
* and field values will be copied.
*
* @param panMap Array of the indices of the destination feature's fields
* stored at the corresponding index of the source feature's fields. A value of
* -1 should be used to ignore the source's field. The array should not be NULL
* and be as long as the number of fields in the source feature.
*
* @param bForgiving TRUE if the operation should continue despite lacking
* output fields matching some of the source fields.
*
* @return OGRERR_NONE if the operation succeeds, even if some values are
* not transferred, otherwise an error code.
*/
OGRErr OGR_F_SetFromWithMap( OGRFeatureH hFeat, OGRFeatureH hOtherFeat,
int bForgiving, int *panMap )
{
VALIDATE_POINTER1( hFeat, "OGR_F_SetFrom", OGRERR_FAILURE );
VALIDATE_POINTER1( hOtherFeat, "OGR_F_SetFrom", OGRERR_FAILURE );
VALIDATE_POINTER1( panMap, "OGR_F_SetFrom", OGRERR_FAILURE);
return ((OGRFeature *) hFeat)->SetFrom( (OGRFeature *) hOtherFeat,
panMap, bForgiving );
}
/************************************************************************/
/* SetFieldsFrom() */
/************************************************************************/
/**
* \brief Set fields from another feature.
*
* Overwrite the fields of this feature from the attributes of
* another. The FID and the style string are not set. The poSrcFeature
* does not need to have the same OGRFeatureDefn. Field values are
* copied according to the provided indices map. Field types do not
* have to exactly match. SetField() method conversion rules will be
* applied as needed. This is more efficient than OGR_F_SetFrom() in
* that this doesn't lookup the fields by their names. Particularly
* useful when the field names don't match.
*
* @param poSrcFeature the feature from which geometry, and field values will
* be copied.
*
* @param panMap Array of the indices of the feature's fields
* stored at the corresponding index of the source feature's fields. A value of
* -1 should be used to ignore the source's field. The array should not be NULL
* and be as long as the number of fields in the source feature.
*
* @param bForgiving TRUE if the operation should continue despite lacking
* output fields matching some of the source fields.
*
* @return OGRERR_NONE if the operation succeeds, even if some values are
* not transferred, otherwise an error code.
*/
OGRErr OGRFeature::SetFieldsFrom( OGRFeature * poSrcFeature, int *panMap ,
int bForgiving )
{
int iDstField;
for( int iField = 0; iField < poSrcFeature->GetFieldCount(); iField++ )
{
iDstField = panMap[iField];
if( iDstField < 0 )
continue;
if( GetFieldCount() <= iDstField )
return OGRERR_FAILURE;
if( !poSrcFeature->IsFieldSet(iField) )
{
UnsetField( iDstField );
continue;
}
switch( poSrcFeature->GetFieldDefnRef(iField)->GetType() )
{
case OFTInteger:
SetField( iDstField, poSrcFeature->GetFieldAsInteger( iField ) );
break;
case OFTInteger64:
SetField( iDstField, poSrcFeature->GetFieldAsInteger64( iField ) );
break;
case OFTReal:
SetField( iDstField, poSrcFeature->GetFieldAsDouble( iField ) );
break;
case OFTString:
SetField( iDstField, poSrcFeature->GetFieldAsString( iField ) );
break;
case OFTIntegerList:
{
if (GetFieldDefnRef(iDstField)->GetType() == OFTString)
{
SetField( iDstField, poSrcFeature->GetFieldAsString(iField) );
}
else
{
int nCount;
const int *panValues = poSrcFeature->GetFieldAsIntegerList( iField, &nCount);
SetField( iDstField, nCount, (int*) panValues );
}
}
break;
case OFTInteger64List:
{
if (GetFieldDefnRef(iDstField)->GetType() == OFTString)
{
SetField( iDstField, poSrcFeature->GetFieldAsString(iField) );
}
else
{
int nCount;
const GIntBig *panValues = poSrcFeature->GetFieldAsInteger64List( iField, &nCount);
SetField( iDstField, nCount, panValues );
}
}
break;
case OFTRealList:
{
if (GetFieldDefnRef(iDstField)->GetType() == OFTString)
{
SetField( iDstField, poSrcFeature->GetFieldAsString(iField) );
}
else
{
int nCount;
const double *padfValues = poSrcFeature->GetFieldAsDoubleList( iField, &nCount);
SetField( iDstField, nCount, (double*) padfValues );
}
}
break;
case OFTDate:
case OFTDateTime:
case OFTTime:
{
OGRFieldType eDstFieldType = GetFieldDefnRef(iDstField)->GetType();
if (eDstFieldType == OFTDate ||
eDstFieldType == OFTTime ||
eDstFieldType == OFTDateTime )
{
SetField( iDstField, poSrcFeature->GetRawFieldRef( iField ) );
}
else if( eDstFieldType == OFTString ||
eDstFieldType == OFTStringList )
{
SetField( iDstField, poSrcFeature->GetFieldAsString( iField ) );
}
else if( !bForgiving )
return OGRERR_FAILURE;
break;
}
default:
{
OGRFieldType eDstFieldType = GetFieldDefnRef(iDstField)->GetType();
if( poSrcFeature->GetFieldDefnRef(iField)->GetType() == eDstFieldType )
{
SetField( iDstField, poSrcFeature->GetRawFieldRef(iField) );
}
else if (eDstFieldType == OFTString ||
eDstFieldType == OFTStringList )
{
SetField( iDstField, poSrcFeature->GetFieldAsString( iField ) );
}
else if( !bForgiving )
return OGRERR_FAILURE;
break;
}
}
}
return OGRERR_NONE;
}
/************************************************************************/
/* GetStyleString() */
/************************************************************************/
/**
* \brief Fetch style string for this feature.
*
* Set the OGR Feature Style Specification for details on the format of
* this string, and ogr_featurestyle.h for services available to parse it.
*
* This method is the same as the C function OGR_F_GetStyleString().
*
* @return a reference to a representation in string format, or NULL if
* there isn't one.
*/
const char *OGRFeature::GetStyleString()
{
int iStyleFieldIndex;
if (m_pszStyleString)
return m_pszStyleString;
iStyleFieldIndex = GetFieldIndex("OGR_STYLE");
if (iStyleFieldIndex >= 0)
return GetFieldAsString(iStyleFieldIndex);
return NULL;
}
/************************************************************************/
/* OGR_F_GetStyleString() */
/************************************************************************/
/**
* \brief Fetch style string for this feature.
*
* Set the OGR Feature Style Specification for details on the format of
* this string, and ogr_featurestyle.h for services available to parse it.
*
* This function is the same as the C++ method OGRFeature::GetStyleString().
*
* @param hFeat handle to the feature to get the style from.
* @return a reference to a representation in string format, or NULL if
* there isn't one.
*/
const char *OGR_F_GetStyleString( OGRFeatureH hFeat )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetStyleString", NULL );
return ((OGRFeature *)hFeat)->GetStyleString();
}
/************************************************************************/
/* SetStyleString() */
/************************************************************************/
/**
* \brief Set feature style string.
* This method operate exactly as
* OGRFeature::SetStyleStringDirectly() except that it does not assume
* ownership of the passed string, but instead makes a copy of it.
*
* This method is the same as the C function OGR_F_SetStyleString().
*
* @param pszString the style string to apply to this feature, cannot be NULL.
*/
void OGRFeature::SetStyleString(const char *pszString)
{
if (m_pszStyleString)
{
CPLFree(m_pszStyleString);
m_pszStyleString = NULL;
}
if( pszString )
m_pszStyleString = VSI_STRDUP_VERBOSE(pszString);
}
/************************************************************************/
/* OGR_F_SetStyleString() */
/************************************************************************/
/**
* \brief Set feature style string.
* This method operate exactly as
* OGR_F_SetStyleStringDirectly() except that it does not assume ownership
* of the passed string, but instead makes a copy of it.
*
* This function is the same as the C++ method OGRFeature::SetStyleString().
*
* @param hFeat handle to the feature to set style to.
* @param pszStyle the style string to apply to this feature, cannot be NULL.
*/
void OGR_F_SetStyleString( OGRFeatureH hFeat, const char *pszStyle )
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetStyleString" );
((OGRFeature *)hFeat)->SetStyleString( pszStyle );
}
/************************************************************************/
/* SetStyleStringDirectly() */
/************************************************************************/
/**
* \brief Set feature style string.
* This method operate exactly as
* OGRFeature::SetStyleString() except that it assumes ownership of the passed
* string.
*
* This method is the same as the C function OGR_F_SetStyleStringDirectly().
*
* @param pszString the style string to apply to this feature, cannot be NULL.
*/
void OGRFeature::SetStyleStringDirectly(char *pszString)
{
if (m_pszStyleString)
CPLFree(m_pszStyleString);
m_pszStyleString = pszString;
}
/************************************************************************/
/* OGR_F_SetStyleStringDirectly() */
/************************************************************************/
/**
* \brief Set feature style string.
* This method operate exactly as
* OGR_F_SetStyleString() except that it assumes ownership of the passed
* string.
*
* This function is the same as the C++ method
* OGRFeature::SetStyleStringDirectly().
*
* @param hFeat handle to the feature to set style to.
* @param pszStyle the style string to apply to this feature, cannot be NULL.
*/
void OGR_F_SetStyleStringDirectly( OGRFeatureH hFeat, char *pszStyle )
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetStyleStringDirectly" );
((OGRFeature *)hFeat)->SetStyleStringDirectly( pszStyle );
}
//************************************************************************/
/* SetStyleTable() */
/************************************************************************/
/** Set style table.
* @param poStyleTable new style table (will be cloned)
*/
void OGRFeature::SetStyleTable(OGRStyleTable *poStyleTable)
{
if ( m_poStyleTable )
delete m_poStyleTable;
m_poStyleTable = ( poStyleTable ) ? poStyleTable->Clone() : NULL;
}
//************************************************************************/
/* SetStyleTableDirectly() */
/************************************************************************/
/** Set style table.
* @param poStyleTable new style table (ownership transferred to the object)
*/
void OGRFeature::SetStyleTableDirectly(OGRStyleTable *poStyleTable)
{
if ( m_poStyleTable )
delete m_poStyleTable;
m_poStyleTable = poStyleTable;
}
//! @cond Doxygen_Suppress
/************************************************************************/
/* RemapFields() */
/* */
/* This is used to transform a feature "in place" from one */
/* feature defn to another with minimum work. */
/************************************************************************/
OGRErr OGRFeature::RemapFields( OGRFeatureDefn *poNewDefn,
int *panRemapSource )
{
if( poNewDefn == NULL )
poNewDefn = poDefn;
OGRField *pauNewFields = static_cast<OGRField *>(
CPLCalloc( poNewDefn->GetFieldCount(), sizeof(OGRField) ) );
for( int iDstField = 0; iDstField < poDefn->GetFieldCount(); iDstField++ )
{
if( panRemapSource[iDstField] == -1 )
{
pauNewFields[iDstField].Set.nMarker1 = OGRUnsetMarker;
pauNewFields[iDstField].Set.nMarker2 = OGRUnsetMarker;
}
else
{
memcpy( pauNewFields + iDstField,
pauFields + panRemapSource[iDstField],
sizeof(OGRField) );
}
}
/*
** We really should be freeing memory for old columns that
** are no longer present. We don't for now because it is a bit messy
** and would take too long to test.
*/
/* -------------------------------------------------------------------- */
/* Apply new definition and fields. */
/* -------------------------------------------------------------------- */
CPLFree( pauFields );
pauFields = pauNewFields;
poDefn = poNewDefn;
return OGRERR_NONE;
}
/************************************************************************/
/* RemapGeomFields() */
/* */
/* This is used to transform a feature "in place" from one */
/* feature defn to another with minimum work. */
/************************************************************************/
OGRErr OGRFeature::RemapGeomFields( OGRFeatureDefn *poNewDefn,
int *panRemapSource )
{
if( poNewDefn == NULL )
poNewDefn = poDefn;
OGRGeometry** papoNewGeomFields = static_cast<OGRGeometry **>(
CPLCalloc( poNewDefn->GetGeomFieldCount(), sizeof(OGRGeometry*) ) );
for( int iDstField = 0;
iDstField < poDefn->GetGeomFieldCount();
iDstField++ )
{
if( panRemapSource[iDstField] == -1 )
{
papoNewGeomFields[iDstField] = NULL;
}
else
{
papoNewGeomFields[iDstField] =
papoGeometries[panRemapSource[iDstField]];
}
}
/*
** We really should be freeing memory for old columns that
** are no longer present. We don't for now because it is a bit messy
** and would take too long to test.
*/
/* -------------------------------------------------------------------- */
/* Apply new definition and fields. */
/* -------------------------------------------------------------------- */
CPLFree( papoGeometries );
papoGeometries = papoNewGeomFields;
poDefn = poNewDefn;
return OGRERR_NONE;
}
//! @endcond
/************************************************************************/
/* OGR_F_GetStyleTable() */
/************************************************************************/
OGRStyleTableH OGR_F_GetStyleTable( OGRFeatureH hFeat )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetStyleTable", NULL );
return (OGRStyleTableH) ((OGRFeature *) hFeat)->GetStyleTable( );
}
/************************************************************************/
/* OGR_F_SetStyleTableDirectly() */
/************************************************************************/
void OGR_F_SetStyleTableDirectly( OGRFeatureH hFeat,
OGRStyleTableH hStyleTable )
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetStyleTableDirectly" );
((OGRFeature *) hFeat)->SetStyleTableDirectly( (OGRStyleTable *) hStyleTable);
}
/************************************************************************/
/* OGR_F_SetStyleTable() */
/************************************************************************/
void OGR_F_SetStyleTable( OGRFeatureH hFeat,
OGRStyleTableH hStyleTable )
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetStyleTable" );
VALIDATE_POINTER0( hStyleTable, "OGR_F_SetStyleTable" );
((OGRFeature *) hFeat)->SetStyleTable( (OGRStyleTable *) hStyleTable);
}
/************************************************************************/
/* FillUnsetWithDefault() */
/************************************************************************/
/**
* \brief Fill unset fields with default values that might be defined.
*
* This method is the same as the C function OGR_F_FillUnsetWithDefault().
*
* @param bNotNullableOnly if we should fill only unset fields with a not-null
* constraint.
* @param papszOptions unused currently. Must be set to NULL.
* @since GDAL 2.0
*/
void OGRFeature::FillUnsetWithDefault( int bNotNullableOnly,
CPL_UNUSED char** papszOptions)
{
int nFieldCount = poDefn->GetFieldCount();
for(int i = 0; i < nFieldCount; i ++ )
{
if( IsFieldSet(i) )
continue;
if( bNotNullableOnly && poDefn->GetFieldDefn(i)->IsNullable() )
continue;
const char* pszDefault = poDefn->GetFieldDefn(i)->GetDefault();
OGRFieldType eType = poDefn->GetFieldDefn(i)->GetType();
if( pszDefault != NULL )
{
if( eType == OFTDate || eType == OFTTime || eType == OFTDateTime )
{
if( STARTS_WITH_CI(pszDefault, "CURRENT") )
{
time_t t = time(NULL);
struct tm brokendown;
CPLUnixTimeToYMDHMS(t, &brokendown);
SetField(i, brokendown.tm_year + 1900,
brokendown.tm_mon + 1,
brokendown.tm_mday,
brokendown.tm_hour,
brokendown.tm_min,
static_cast<float>(brokendown.tm_sec),
100 );
}
else
{
int nYear, nMonth, nDay, nHour, nMinute;
float fSecond;
if( sscanf(pszDefault, "'%d/%d/%d %d:%d:%f'",
&nYear, &nMonth, &nDay,
&nHour, &nMinute, &fSecond) == 6 )
{
SetField(i, nYear, nMonth, nDay, nHour, nMinute,
fSecond, 100 );
}
}
}
else if( eType == OFTString &&
pszDefault[0] == '\'' &&
pszDefault[strlen(pszDefault)-1] == '\'' )
{
CPLString osDefault(pszDefault + 1);
osDefault.resize(osDefault.size()-1);
char* pszTmp = CPLUnescapeString(osDefault, NULL, CPLES_SQL);
SetField(i, pszTmp);
CPLFree(pszTmp);
}
else
SetField(i, pszDefault);
}
}
}
/************************************************************************/
/* OGR_F_FillUnsetWithDefault() */
/************************************************************************/
/**
* \brief Fill unset fields with default values that might be defined.
*
* This function is the same as the C++ method OGRFeature::FillUnsetWithDefault().
*
* @param hFeat handle to the feature.
* @param bNotNullableOnly if we should fill only unset fields with a not-null
* constraint.
* @param papszOptions unused currently. Must be set to NULL.
* @since GDAL 2.0
*/
void OGR_F_FillUnsetWithDefault( OGRFeatureH hFeat,
int bNotNullableOnly,
char** papszOptions )
{
VALIDATE_POINTER0( hFeat, "OGR_F_FillUnsetWithDefault" );
((OGRFeature *) hFeat)->FillUnsetWithDefault( bNotNullableOnly, papszOptions );
}
/************************************************************************/
/* Validate() */
/************************************************************************/
/**
* \brief Validate that a feature meets constraints of its schema.
*
* The scope of test is specified with the nValidateFlags parameter.
*
* Regarding OGR_F_VAL_WIDTH, the test is done assuming the string width must
* be interpreted as the number of UTF-8 characters. Some drivers might interpret
* the width as the number of bytes instead. So this test is rather conservative
* (if it fails, then it will fail for all interpretations).
*
* This method is the same as the C function OGR_F_Validate().
*
* @param nValidateFlags OGR_F_VAL_ALL or combination of OGR_F_VAL_NULL,
* OGR_F_VAL_GEOM_TYPE, OGR_F_VAL_WIDTH and OGR_F_VAL_ALLOW_NULL_WHEN_DEFAULT,
* OGR_F_VAL_ALLOW_DIFFERENT_GEOM_DIM
* with '|' operator
* @param bEmitError TRUE if a CPLError() must be emitted when a check fails
* @return TRUE if all enabled validation tests pass.
* @since GDAL 2.0
*/
int OGRFeature::Validate( int nValidateFlags, int bEmitError )
{
bool bRet = true;
int nGeomFieldCount = poDefn->GetGeomFieldCount();
for( int i = 0; i < nGeomFieldCount; i++ )
{
if( (nValidateFlags & OGR_F_VAL_NULL) &&
!poDefn->GetGeomFieldDefn(i)->IsNullable() &&
GetGeomFieldRef(i) == NULL )
{
bRet = false;
if( bEmitError )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Geometry field %s has a NULL content which is not allowed",
poDefn->GetGeomFieldDefn(i)->GetNameRef());
}
}
if( (nValidateFlags & OGR_F_VAL_GEOM_TYPE) &&
poDefn->GetGeomFieldDefn(i)->GetType() != wkbUnknown )
{
OGRGeometry* poGeom = GetGeomFieldRef(i);
if( poGeom != NULL )
{
OGRwkbGeometryType eType = poDefn->GetGeomFieldDefn(i)->GetType();
OGRwkbGeometryType eFType = poGeom->getGeometryType();
if( (nValidateFlags & OGR_F_VAL_ALLOW_DIFFERENT_GEOM_DIM) &&
(wkbFlatten(eFType) == wkbFlatten(eType) ||
wkbFlatten(eType) == wkbUnknown) )
{
/* ok */
}
else if( (eType == wkbSetZ(wkbUnknown) && !wkbHasZ(eFType)) ||
(eType != wkbSetZ(wkbUnknown) && eFType != eType) )
{
bRet = false;
if( bEmitError )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Geometry field %s has a %s geometry whereas %s is expected",
poDefn->GetGeomFieldDefn(i)->GetNameRef(),
OGRGeometryTypeToName(eFType),
OGRGeometryTypeToName(eType));
}
}
}
}
}
int nFieldCount = poDefn->GetFieldCount();
for( int i = 0; i < nFieldCount; i++ )
{
if( (nValidateFlags & OGR_F_VAL_NULL) &&
!poDefn->GetFieldDefn(i)->IsNullable() &&
!IsFieldSet(i) &&
(!(nValidateFlags & OGR_F_VAL_ALLOW_NULL_WHEN_DEFAULT) ||
poDefn->GetFieldDefn(i)->GetDefault() == NULL))
{
bRet = false;
if( bEmitError )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Field %s has a NULL content which is not allowed",
poDefn->GetFieldDefn(i)->GetNameRef());
}
}
if( (nValidateFlags & OGR_F_VAL_WIDTH) &&
poDefn->GetFieldDefn(i)->GetWidth() > 0 &&
poDefn->GetFieldDefn(i)->GetType() == OFTString &&
IsFieldSet(i) &&
CPLIsUTF8(GetFieldAsString(i), -1) &&
CPLStrlenUTF8(GetFieldAsString(i)) > poDefn->GetFieldDefn(i)->GetWidth())
{
bRet = false;
if( bEmitError )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Field %s has a %d UTF-8 characters whereas a maximum of %d is allowed",
poDefn->GetFieldDefn(i)->GetNameRef(),
CPLStrlenUTF8(GetFieldAsString(i)),
poDefn->GetFieldDefn(i)->GetWidth());
}
}
}
return bRet;
}
/************************************************************************/
/* OGR_F_Validate() */
/************************************************************************/
/**
* \brief Validate that a feature meets constraints of its schema.
*
* The scope of test is specified with the nValidateFlags parameter.
*
* Regarding OGR_F_VAL_WIDTH, the test is done assuming the string width must
* be interpreted as the number of UTF-8 characters. Some drivers might interpret
* the width as the number of bytes instead. So this test is rather conservative
* (if it fails, then it will fail for all interpretations).
*
* This function is the same as the C++ method
* OGRFeature::Validate().
*
* @param hFeat handle to the feature to validate.
* @param nValidateFlags OGR_F_VAL_ALL or combination of OGR_F_VAL_NULL,
* OGR_F_VAL_GEOM_TYPE, OGR_F_VAL_WIDTH and OGR_F_VAL_ALLOW_NULL_WHEN_DEFAULT
* with '|' operator
* @param bEmitError TRUE if a CPLError() must be emitted when a check fails
* @return TRUE if all enabled validation tests pass.
* @since GDAL 2.0
*/
int OGR_F_Validate( OGRFeatureH hFeat, int nValidateFlags, int bEmitError )
{
VALIDATE_POINTER1( hFeat, "OGR_F_Validate", FALSE );
return ((OGRFeature *) hFeat)->Validate( nValidateFlags, bEmitError );
}
/************************************************************************/
/* GetNativeData() */
/************************************************************************/
/**
* \fn const char* OGRFeature::GetNativeData() const;
*
* \brief Returns the native data for the feature.
*
* The native data is the representation in a "natural" form that comes from
* the driver that created this feature, or that is aimed at an output driver.
* The native data may be in different format, which is indicated by
* GetNativeMediaType().
*
* Note that most drivers do not support storing the native data in the feature
* object, and if they do, generally the NATIVE_DATA open option must be passed
* at dataset opening.
*
* The "native data" does not imply it is something more performant or powerful than
* what can be obtained with the rest of the API, but it may be useful in
* round-tripping scenarios where some characteristics of the underlying format
* are not captured otherwise by the OGR abstraction.
*
* This function is the same as the C function
* OGR_F_GetNativeData().
*
* @return a string with the native data, or NULL if there is none.
* @since GDAL 2.1
*
* @see https://trac.osgeo.org/gdal/wiki/rfc60_improved_roundtripping_in_ogr
*/
/************************************************************************/
/* , OGR_F_GetNativeData() */
/************************************************************************/
/**
* \brief Returns the native data for the feature.
*
* The native data is the representation in a "natural" form that comes from
* the driver that created this feature, or that is aimed at an output driver.
* The native data may be in different format, which is indicated by
* OGR_F_GetNativeMediaType().
*
* Note that most drivers do not support storing the native data in the feature
* object, and if they do, generally the NATIVE_DATA open option must be passed
* at dataset opening.
*
* The "native data" does not imply it is something more performant or powerful than
* what can be obtained with the rest of the API, but it may be useful in
* round-tripping scenarios where some characteristics of the underlying format
* are not captured otherwise by the OGR abstraction.
*
* This function is the same as the C++ method
* OGRFeature::GetNativeData().
*
* @param hFeat handle to the feature.
* @return a string with the native data, or NULL if there is none.
* @since GDAL 2.1
*
* @see https://trac.osgeo.org/gdal/wiki/rfc60_improved_roundtripping_in_ogr
*/
const char *OGR_F_GetNativeData( OGRFeatureH hFeat )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetNativeData", NULL );
return ((const OGRFeature *) hFeat)->GetNativeData();
}
/************************************************************************/
/* GetNativeMediaType() */
/************************************************************************/
/**
* \fn const char* OGRFeature::GetNativeMediaType() const;
*
* \brief Returns the native media type for the feature.
*
* The native media type is the identifier for the format of the native data.
* It follows the IANA RFC 2045 (see https://en.wikipedia.org/wiki/Media_type),
* e.g. "application/vnd.geo+json" for JSon.
*
* This function is the same as the C function
* OGR_F_GetNativeMediaType().
*
* @return a string with the native media type, or NULL if there is none.
* @since GDAL 2.1
*
* @see https://trac.osgeo.org/gdal/wiki/rfc60_improved_roundtripping_in_ogr
*/
/************************************************************************/
/* OGR_F_GetNativeMediaType() */
/************************************************************************/
/**
* \brief Returns the native media type for the feature.
*
* The native media type is the identifier for the format of the native data.
* It follows the IANA RFC 2045 (see https://en.wikipedia.org/wiki/Media_type),
* e.g. "application/vnd.geo+json" for JSon.
*
* This function is the same as the C function
* OGR_F_GetNativeMediaType().
*
* @param hFeat handle to the feature.
* @return a string with the native media type, or NULL if there is none.
* @since GDAL 2.1
*
* @see https://trac.osgeo.org/gdal/wiki/rfc60_improved_roundtripping_in_ogr
*/
const char *OGR_F_GetNativeMediaType( OGRFeatureH hFeat )
{
VALIDATE_POINTER1( hFeat, "OGR_F_GetNativeMediaType", NULL );
return ((const OGRFeature *) hFeat)->GetNativeMediaType();
}
/************************************************************************/
/* , SetNativeData() */
/************************************************************************/
/**
* \brief Sets the native data for the feature.
*
* The native data is the representation in a "natural" form that comes from
* the driver that created this feature, or that is aimed at an output driver.
* The native data may be in different format, which is indicated by
* GetNativeMediaType().
*
* This function is the same as the C function
* OGR_F_SetNativeData().
*
* @param pszNativeData a string with the native data, or NULL if there is none.
* @since GDAL 2.1
*
* @see https://trac.osgeo.org/gdal/wiki/rfc60_improved_roundtripping_in_ogr
*/
void OGRFeature::SetNativeData( const char* pszNativeData )
{
CPLFree( m_pszNativeData );
m_pszNativeData = ( pszNativeData ) ? VSI_STRDUP_VERBOSE( pszNativeData ) : NULL;
}
/************************************************************************/
/* , OGR_F_SetNativeData() */
/************************************************************************/
/**
* \brief Sets the native data for the feature.
*
* The native data is the representation in a "natural" form that comes from
* the driver that created this feature, or that is aimed at an output driver.
* The native data may be in different format, which is indicated by
* OGR_F_GetNativeMediaType().
*
* This function is the same as the C++ method
* OGRFeature::SetNativeData().
*
* @param hFeat handle to the feature.
* @param pszNativeData a string with the native data, or NULL if there is none.
* @since GDAL 2.1
*
* @see https://trac.osgeo.org/gdal/wiki/rfc60_improved_roundtripping_in_ogr
*/
void OGR_F_SetNativeData( OGRFeatureH hFeat, const char* pszNativeData )
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetNativeData" );
((OGRFeature *) hFeat)->SetNativeData(pszNativeData);
}
/************************************************************************/
/* , SetNativeMediaType() */
/************************************************************************/
/**
* \brief Sets the native media type for the feature.
*
* The native media type is the identifier for the format of the native data.
* It follows the IANA RFC 2045 (see https://en.wikipedia.org/wiki/Media_type),
* e.g. "application/vnd.geo+json" for JSon.
*
* This function is the same as the C function
* OGR_F_SetNativeMediaType().
*
* @param pszNativeMediaType a string with the native media type, or NULL if there is none.
* @since GDAL 2.1
*
* @see https://trac.osgeo.org/gdal/wiki/rfc60_improved_roundtripping_in_ogr
*/
void OGRFeature::SetNativeMediaType( const char* pszNativeMediaType )
{
CPLFree( m_pszNativeMediaType );
m_pszNativeMediaType = ( pszNativeMediaType ) ? VSI_STRDUP_VERBOSE( pszNativeMediaType ) : NULL;
}
/************************************************************************/
/* , OGR_F_SetNativeMediaType() */
/************************************************************************/
/**
* \brief Sets the native media type for the feature.
*
* The native media type is the identifier for the format of the native data.
* It follows the IANA RFC 2045 (see https://en.wikipedia.org/wiki/Media_type),
* e.g. "application/vnd.geo+json" for JSon.
*
* This function is the same as the C++ method
* OGRFeature::SetNativeMediaType().
*
* @param hFeat handle to the feature.
* @param pszNativeMediaType a string with the native media type, or NULL if there is none.
* @since GDAL 2.1
*
* @see https://trac.osgeo.org/gdal/wiki/rfc60_improved_roundtripping_in_ogr
*/
void OGR_F_SetNativeMediaType( OGRFeatureH hFeat, const char* pszNativeMediaType )
{
VALIDATE_POINTER0( hFeat, "OGR_F_SetNativeMediaType" );
((OGRFeature *) hFeat)->SetNativeMediaType(pszNativeMediaType);
}
|
#include "../../include/valve/hl1bspasset.h"
#include "../../include/valve/hl1bspinstance.h"
#define STB_RECT_PACK_IMPLEMENTATION
#include "../../include/stb/stb_rect_pack.h"
#include <iostream>
#include <sstream>
#include <GL/glextl.h>
#include <glm/gtc/type_ptr.hpp>
using namespace valve::hl1;
BspAsset::BspAsset(DataFileLocator& locator, DataFileLoader& loader)
: Asset(locator, loader)
{ }
BspAsset::~BspAsset()
{ }
bool BspAsset::Load(const std::string &filename)
{
Array<byte>& data = this->_loader(filename);
this->_header = (tBSPHeader*)data.data;
this->LoadLump(data, this->_planeData, HL1_BSP_PLANELUMP);
this->LoadLump(data, this->_textureData, HL1_BSP_TEXTURELUMP);
this->LoadLump(data, this->_verticesData, HL1_BSP_VERTEXLUMP);
this->LoadLump(data, this->_nodeData, HL1_BSP_NODELUMP);
this->LoadLump(data, this->_texinfoData, HL1_BSP_TEXINFOLUMP);
this->LoadLump(data, this->_faceData, HL1_BSP_FACELUMP);
this->LoadLump(data, this->_lightingData, HL1_BSP_LIGHTINGLUMP);
this->LoadLump(data, this->_clipnodeData, HL1_BSP_CLIPNODELUMP);
this->LoadLump(data, this->_leafData, HL1_BSP_LEAFLUMP);
this->LoadLump(data, this->_marksurfaceData, HL1_BSP_MARKSURFACELUMP);
this->LoadLump(data, this->_edgeData, HL1_BSP_EDGELUMP);
this->LoadLump(data, this->_surfedgeData, HL1_BSP_SURFEDGELUMP);
this->LoadLump(data, this->_modelData, HL1_BSP_MODELLUMP);
Array<byte> entityData;
if (this->LoadLump(data, entityData, HL1_BSP_ENTITYLUMP))
this->_entities = BspAsset::LoadEntities(entityData);
Array<byte> visibilityData;
if (this->LoadLump(data, visibilityData, HL1_BSP_VISIBILITYLUMP))
this->_visLeafs = BspAsset::LoadVisLeafs(visibilityData, this->_leafData, this->_modelData);
std::vector<WadAsset*> wads;
tBSPEntity* worldspawn = this->FindEntityByClassname("worldspawn");
if (worldspawn != nullptr)
wads = WadAsset::LoadWads(worldspawn->keyvalues["wad"], filename);
this->LoadTextures(this->_va.Textures(), wads);
WadAsset::UnloadWads(wads);
std::vector<tVertex> vertices;
this->LoadFacesWithLightmaps(this->_va.Faces(), this->_va.Lightmaps(), vertices);
this->_va.LoadVertices(vertices);
this->LoadModels();
return true;
}
std::vector<sBSPEntity> BspAsset::LoadEntities(const Array<byte>& entityData)
{
const byte* itr = entityData.data;
const byte* end = entityData.data + entityData.count;
std::string key, value;
std::vector<tBSPEntity> entities;
while (itr[0] == '{')
{
tBSPEntity entity;
itr++; // skip the bracket
while (itr[0] <= ' ' && itr != end) itr++; // skip all space characters
while (itr[0] != '}')
{
key = "";
value = "";
itr++; // skip the quote
while (itr[0] != '\"' && itr != end) key += (*itr++);
itr++; // skip the quote
while (itr[0] <= ' ' && itr != end) itr++; // skip all space characters
itr++; // skip the quote
while (itr[0] != '\"' && itr != end) value += (*itr++);
if (key == "classname") entity.classname = value;
entity.keyvalues.insert(std::make_pair(key, value));
itr++; // skip the quote
while (itr[0] <= ' ' && itr != end) itr++; // skip all space characters
}
entities.push_back(entity);
while (itr[0] != '{' && itr != end) itr++; // skip to the next entity
}
return entities;
}
tBSPEntity* BspAsset::FindEntityByClassname(const std::string& classname)
{
for (std::vector<tBSPEntity>::iterator i = this->_entities.begin(); i != this->_entities.end(); ++i)
{
tBSPEntity* e = &(*i);
if (e->classname == classname)
return e;
}
return nullptr;
}
std::vector<tBSPVisLeaf> BspAsset::LoadVisLeafs(const Array<byte>& visdata, const Array<tBSPLeaf>& leafs, const Array<tBSPModel>& models)
{
std::vector<tBSPVisLeaf> visLeafs = std::vector<tBSPVisLeaf>(leafs.count);
for (int i = 0; i < leafs.count; i++)
{
visLeafs[i].leafs = 0;
visLeafs[i].leafCount = 0;
int visOffset = leafs[i].visofs;
for (int j = 1; j < models[0].visLeafs; visOffset++)
{
if (visdata[visOffset] == 0)
{
visOffset++;
j += (visdata[visOffset]<<3);
}
else
{
for (byte bit = 1; bit; bit<<=1, j++)
{
if (visdata[visOffset] & bit)
visLeafs[i].leafCount++;
}
}
}
if (visLeafs[i].leafCount > 0)
{
visLeafs[i].leafs = new int[visLeafs[i].leafCount];
if (visLeafs[i].leafs == 0)
return visLeafs;
}
}
for (int i = 0; i < leafs.count; i++)
{
int visOffset = leafs[i].visofs;
int index = 0;
for (int j = 1; j < models[0].visLeafs; visOffset++)
{
if (visdata[visOffset] == 0)
{
visOffset++;
j += (visdata[visOffset]<<3);
}
else
{
for (byte bit = 1; bit; bit<<=1, j++)
{
if (visdata[visOffset] & bit)
{
visLeafs[i].leafs[index++] = j;
}
}
}
}
}
return visLeafs;
}
bool BspAsset::LoadFacesWithLightmaps(std::vector<tFace>& faces, std::vector<Texture*>& lightmaps, std::vector<tVertex>& vertices)
{
// Temporary lightmap array for each face, these will be packed into an atlas later
Array<Texture> lightMaps;
// Allocate the arrays for faces and lightmaps
lightMaps.Allocate(this->_faceData.count);
std::vector<stbrp_rect> rects;
for (int f = 0; f < this->_faceData.count; f++)
{
tBSPFace& in = this->_faceData[f];
tBSPMipTexHeader* mip = this->GetMiptex(this->_texinfoData[in.texinfo].miptexIndex);
tFace out;
out.firstVertex = vertices.size();
out.vertexCount = in.edgeCount;
out.flags = this->_texinfoData[in.texinfo].flags;
out.texture = this->_texinfoData[in.texinfo].miptexIndex;
out.lightmap = f;
out.plane = glm::vec4(
this->_planeData[in.planeIndex].normal[0],
this->_planeData[in.planeIndex].normal[1],
this->_planeData[in.planeIndex].normal[2],
this->_planeData[in.planeIndex].distance
);
// Flip face normal when side == 1
if (in.side == 1)
{
out.plane[0] = -out.plane[0];
out.plane[1] = -out.plane[1];
out.plane[2] = -out.plane[2];
out.plane[3] = -out.plane[3];
}
// Calculate and grab the lightmap buffer
float min[2], max[2];
this->CalculateSurfaceExtents(in, min, max);
// Skip the lightmaps for faces with special flags
if (out.flags == 0)
{
if (this->LoadLightmap(in, lightMaps[f], min, max))
{
stbrp_rect rect;
rect.id = f;
rect.w = lightMaps[f].Width() + 2;
rect.h = lightMaps[f].Height() + 2;
rects.push_back(rect);
}
}
float lw = float(lightMaps[f].Width());
float lh = float(lightMaps[f].Height());
float halfsizew = (min[0] + max[0]) / 2.0f;
float halfsizeh = (min[1] + max[1]) / 2.0f;
// Create a vertex list for this face
for (int e = 0; e < in.edgeCount; e++)
{
tVertex v;
// Get the edge index
int ei = this->_surfedgeData[in.firstEdge + e];
// Determine the vertex based on the edge index
v.position = this->_verticesData[this->_edgeData[ei < 0 ? -ei : ei].vertex[ei < 0 ? 1 : 0]].point;
// Copy the normal from the plane
v.normal = glm::vec3(out.plane);
// Reset the bone so its not used
v.bone = -1;
tBSPTexInfo& ti = this->_texinfoData[in.texinfo];
float s = glm::dot(v.position, glm::vec3(ti.vecs[0][0], ti.vecs[0][1], ti.vecs[0][2])) + ti.vecs[0][3];
float t = glm::dot(v.position, glm::vec3(ti.vecs[1][0], ti.vecs[1][1], ti.vecs[1][2])) + ti.vecs[1][3];
// Calculate the texture texcoords
v.texcoords[0] = glm::vec2(s / float(mip->width), t / float(mip->height));
// Calculate the lightmap texcoords
v.texcoords[1] = glm::vec2(((lw / 2.0f) + (s - halfsizew) / 16.0f) / lw, ((lh / 2.0f) + (t - halfsizeh) / 16.0f) / lh);
vertices.push_back(v);
}
faces.push_back(out);
}
// Activate TEXTURE1 for lightmaps from each face
glActiveTexture(GL_TEXTURE1);
glEnable(GL_TEXTURE_2D);
// Pack the lightmaps into an atlas
while (rects.size() > 0)
{
// Setup one atlas texture (for now)
Texture* atlas = new Texture();
atlas->SetDimentions(512, 512, 3);
atlas->Fill(glm::vec4(0.0f, 0.0f, 0.0f, 0.0f));
// pack the lightmap rects into one atlas
stbrp_context context = { 0 };
Array<stbrp_node> nodes(rects.size());
stbrp_init_target(&context, atlas->Width(), atlas->Height(), nodes, rects.size());
stbrp_pack_rects(&context, (stbrp_rect*)&rects[0], rects.size());
std::vector<stbrp_rect> nextrects;
for (auto rect = rects.begin(); rect != rects.end(); rect++)
{
// a reference to the loaded lightmapfrom the rect
Texture& lm = lightMaps[faces[(*rect).id].lightmap];
if ((*rect).was_packed)
{
// Copy the lightmap texture into the atlas
atlas->FillAtPosition(lm, glm::vec2((*rect).x + 1, (*rect).y + 1), true);
for (int vertexIndex = 0; vertexIndex < faces[(*rect).id].vertexCount; vertexIndex++)
{
// Recalculate the lightmap texcoords for the atlas
glm::vec2& vec = vertices[faces[(*rect).id].firstVertex + vertexIndex].texcoords[1];
vec.s = float((*rect).x + 1 + (float(lm.Width()) * vec.s)) / atlas->Width();
vec.t = float((*rect).y + 1 + (float(lm.Height()) * vec.t)) / atlas->Height();
}
// Make sure we will use the (correct) atlas when we render
faces[(*rect).id].lightmap = lightmaps.size();
}
else
{
// When the lightmap was not packed into the atlas, we try for a next atlas
nextrects.push_back(*rect);
}
}
// upload the atlas with all its lightmap textures
atlas->UploadToGl();
lightmaps.push_back(atlas);
rects = nextrects;
}
// cleanup the temporary lightmap array
lightMaps.Delete();
return true;
}
bool BspAsset::LoadTextures(std::vector<Texture*>& textures, const std::vector<WadAsset*>& wads)
{
Array<int> textureTable(int(*this->_textureData.data), (int*)(this->_textureData.data + sizeof(int)));
// Activate TEXTURE0 for the regular texture
glActiveTexture(GL_TEXTURE0);
glEnable(GL_TEXTURE_2D);
for (int t = 0; t < int(*this->_textureData.data); t++)
{
const unsigned char* textureData = this->_textureData.data + textureTable[t];
tBSPMipTexHeader* miptex = (tBSPMipTexHeader*)textureData;
Texture* tex = new Texture();
tex->SetName(miptex->name);
if (miptex->offsets[0] == 0)
{
for (std::vector<WadAsset*>::const_iterator i = wads.cbegin(); i != wads.cend(); ++i)
{
WadAsset* wad = *i;
textureData = wad->LumpData(wad->IndexOf(miptex->name));
if (textureData != nullptr)
break;
}
}
if (textureData != nullptr)
{
miptex = (tBSPMipTexHeader*)textureData;
int s = miptex->width * miptex->height;
int bpp = 4;
int paletteOffset = miptex->offsets[0] + s + (s/4) + (s/16) + (s/64) + sizeof(short);
// Get the miptex data and palette
const unsigned char* source0 = textureData + miptex->offsets[0];
const unsigned char* palette = textureData + paletteOffset;
unsigned char* destination = new unsigned char[s * bpp];
unsigned char r, g, b, a;
for (int i = 0; i < s; i++)
{
r = palette[source0[i]*3];
g = palette[source0[i]*3+1];
b = palette[source0[i]*3+2];
a = 255;
// Do we need a transparent pixel
if (tex->Name()[0] == '{' && source0[i] == 255)
r = g = b = a = 0;
destination[i*4 + 0] = r;
destination[i*4 + 1] = g;
destination[i*4 + 2] = b;
destination[i*4 + 3] = a;
}
tex->SetData(miptex->width, miptex->height, bpp, destination);
delete []destination;
}
else
{
std::cout << "Texture \"" << miptex->name << "\" not found" << std::endl;
tex->DefaultTexture();
}
tex->UploadToGl();
textures.push_back(tex);
}
glBindTexture(GL_TEXTURE_2D, 0); // Unbind texture
return true;
}
tBSPMipTexHeader* BspAsset::GetMiptex(int index)
{
tBSPMipTexOffsetTable* bspMiptexTable = (tBSPMipTexOffsetTable*)this->_textureData.data;
if (index >= 0 && bspMiptexTable->miptexCount > index)
return (tBSPMipTexHeader*)(this->_textureData.data + bspMiptexTable->offsets[index]);
return 0;
}
int BspAsset::FaceFlags(int index)
{
if (index >= 0 && this->_va.Faces().size() > index)
return this->_va.Faces()[index].flags;
return -1;
}
//
// the following computations are based on:
// PolyEngine (c) Alexey Goloshubin and Quake I source by id Software
//
void BspAsset::CalculateSurfaceExtents(const tBSPFace& in, float min[2], float max[2]) const
{
const tBSPTexInfo* t = &this->_texinfoData[in.texinfo];
min[0] = min[1] = 999999;
max[0] = max[1] = -999999;
for (int i = 0; i < in.edgeCount; i++)
{
const tBSPVertex* v;
int e = this->_surfedgeData[in.firstEdge + i];
if (e >= 0)
v = &this->_verticesData[this->_edgeData[e].vertex[0]];
else
v = &this->_verticesData[this->_edgeData[-e].vertex[1]];
for (int j = 0; j < 2; j++)
{
int val = v->point[0] * t->vecs[j][0] + v->point[1] * t->vecs[j][1] + v->point[2] * t->vecs[j][2] +t->vecs[j][3];
if (val < min[j]) min[j] = val;
if (val > max[j]) max[j] = val;
}
}
}
bool BspAsset::LoadLightmap(const tBSPFace& in, Texture& out, float min[2], float max[2])
{
// compute lightmap size
int size[2];
for (int c = 0; c < 2; c++)
{
float tmin = floorf(min[c] / 16.0f);
float tmax = ceilf(max[c] / 16.0f);
size[c] = (int) (tmax - tmin);
}
out.SetData(size[0] + 1, size[1] + 1, 3, this->_lightingData.data + in.lightOffset, false);
return true;
}
bool BspAsset::LoadModels()
{
this->_models.Allocate(this->_modelData.count);
for (int m = 0; m < this->_modelData.count; m++)
{
this->_models[m].position = this->_modelData[m].origin;
this->_models[m].firstFace = this->_modelData[m].firstFace;
this->_models[m].faceCount = this->_modelData[m].faceCount;
}
return true;
}
void BspAsset::RenderFaces(const std::set<unsigned short>& visibleFaces)
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
this->_va.RenderFaces(visibleFaces);
}
|
/**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/dbwebserver.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/stats/snapshots.h"
#include "mongo/util/mongoutils/html.h"
namespace mongo {
namespace {
using namespace html;
using std::auto_ptr;
using std::fixed;
using std::setprecision;
using std::string;
using std::stringstream;
class WriteLockStatus : public WebStatusPlugin {
public:
WriteLockStatus()
: WebStatusPlugin("write lock", 51, "% time in write lock, by 4 sec periods") {}
virtual void init() {}
virtual void run(OperationContext* txn, stringstream& ss) {
ss << "<a "
"href=\"http://dochub.mongodb.org/core/concurrency\" "
"title=\"snapshot: was the db in the write lock when this page was generated?\">";
ss << "write locked now:</a> " << (txn->lockState()->isW() ? "true" : "false") << "\n";
}
} writeLockStatus;
class DBTopStatus : public WebStatusPlugin {
public:
DBTopStatus() : WebStatusPlugin("dbtop", 50, "(occurrences|percent of elapsed)") {}
void display(stringstream& ss, double elapsed, const Top::UsageData& usage) {
ss << "<td>";
ss << usage.count;
ss << "</td><td>";
double per = 100 * ((double)usage.time) / elapsed;
if (per == (int)per)
ss << (int)per;
else
ss << setprecision(1) << fixed << per;
ss << '%';
ss << "</td>";
}
void display(stringstream& ss,
double elapsed,
const string& ns,
const Top::CollectionData& data) {
if (ns != "TOTAL" && data.total.count == 0)
return;
ss << "<tr><th>" << html::escape(ns) << "</th>";
display(ss, elapsed, data.total);
display(ss, elapsed, data.readLock);
display(ss, elapsed, data.writeLock);
display(ss, elapsed, data.queries);
display(ss, elapsed, data.getmore);
display(ss, elapsed, data.insert);
display(ss, elapsed, data.update);
display(ss, elapsed, data.remove);
ss << "</tr>\n";
}
void run(OperationContext* txn, stringstream& ss) {
auto_ptr<SnapshotDelta> delta = statsSnapshots.computeDelta();
if (!delta.get())
return;
ss << "<table border=1 cellpadding=2 cellspacing=0>";
ss << "<tr align='left'><th>";
ss << a("http://dochub.mongodb.org/core/whatisanamespace", "namespace")
<< "NS</a></th>"
"<th colspan=2>total</th>"
"<th colspan=2>Reads</th>"
"<th colspan=2>Writes</th>"
"<th colspan=2>Queries</th>"
"<th colspan=2>GetMores</th>"
"<th colspan=2>Inserts</th>"
"<th colspan=2>Updates</th>"
"<th colspan=2>Removes</th>";
ss << "</tr>\n";
Top::UsageMap usage = delta->collectionUsageDiff();
for (Top::UsageMap::const_iterator i = usage.begin(); i != usage.end(); ++i) {
display(ss, (double)delta->elapsed(), i->first, i->second);
}
ss << "</table>";
}
virtual void init() {}
} dbtopStatus;
} // namespace
} // namespace mongo
|
#include "system.h"
#include <unistd.h>
#include <cstddef>
#include <set>
#include <string>
#include <vector>
#include "linux_parser.h"
#include "process.h"
#include "processor.h"
using std::set;
using std::size_t;
using std::string;
using std::vector;
// TODO: Return the system's CPU
Processor& System::Cpu() { return cpu_; }
// TODO: Return a container composed of the system's processes
vector<Process>& System::Processes() { return processes_; }
// DONE: Return the system's kernel identifier (string)
std::string System::Kernel() { return LinuxParser::Kernel(); }
// DONE: Return the system's memory utilization
float System::MemoryUtilization() {
// This implementation uses the formula:
// Used Mem = (MemTotal-(MemFree + Buffers + Cached))/MemTotal <- not in
// percentage as that is handled by ncurses_display.cpp
// Cached=Cached + SReclaimable - Shmem
float mem_utilization{0.0}, total_cached{0.0};
LinuxParser::Memory memory = LinuxParser::MemoryUtilization();
// 0 1 2 3 4 5
//"MemTotal", "MemFree", "Buffers", "Cached", "Shmem","SReclaimable"
total_cached = memory.values[MemType::kCached_] +
memory.values[MemType::kSReclaimable_] -
memory.values[MemType::kShmem_];
mem_utilization = (memory.values[MemType::kMemTotal_] -
(memory.values[MemType::kMemFree_] +
memory.values[MemType::kBuffers_] + total_cached)) /
memory.values[MemType::kMemTotal_];
return mem_utilization;
}
// DONE: Return the operating system name
std::string System::OperatingSystem() { return LinuxParser::OperatingSystem(); }
// DONE: Return the number of processes actively running on the system
int System::RunningProcesses() { return LinuxParser::RunningProcesses(); }
// DONE: Return the total number of processes on the system
int System::TotalProcesses() { return LinuxParser::TotalProcesses(); }
// DONE: Return the number of seconds since the system started running
long System::UpTime() { return LinuxParser::UpTime(); }
|
#if !defined(TARGET_RASPBERRY_PI)
#include "EngineGLFW.h"
GLuint EngineGLFW::g_FontTexture = 0;
unsigned int EngineGLFW::g_VaoHandle = 0;
void EngineGLFW::setup()
{
if(isSetup) return;
ImGuiIO& io = ImGui::GetIO();
io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB;
io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;
io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
if(ofIsGLProgrammableRenderer())
{
io.RenderDrawListsFn = programmableRenderDrawLists;
}
else
{
io.RenderDrawListsFn = fixedRenderDrawLists;
}
io.SetClipboardTextFn = &BaseEngine::setClipboardString;
io.GetClipboardTextFn = &BaseEngine::getClipboardString;
createDeviceObjects();
// Override listeners
ofAddListener(ofEvents().mousePressed, this, &EngineGLFW::onMousePressed);
ofAddListener(ofEvents().mouseReleased, this, &EngineGLFW::onMouseReleased);
ofAddListener(ofEvents().keyReleased, this, &EngineGLFW::onKeyReleased);
// BaseEngine listeners
ofAddListener(ofEvents().keyPressed, (BaseEngine*)this, &BaseEngine::onKeyPressed);
ofAddListener(ofEvents().mouseScrolled, (BaseEngine*)this, &BaseEngine::onMouseScrolled);
ofAddListener(ofEvents().windowResized, (BaseEngine*)this, &BaseEngine::onWindowResized);
isSetup = true;
}
void EngineGLFW::exit()
{
if(!isSetup) return;
// Override listeners
ofRemoveListener(ofEvents().mousePressed, this, &EngineGLFW::onMousePressed);
ofRemoveListener(ofEvents().mouseReleased, this, &EngineGLFW::onMouseReleased);
ofRemoveListener(ofEvents().keyReleased, this, &EngineGLFW::onKeyReleased);
// Base class listeners
ofRemoveListener(ofEvents().keyPressed, (BaseEngine*)this, &BaseEngine::onKeyPressed);
ofRemoveListener(ofEvents().mouseScrolled, (BaseEngine*)this, &BaseEngine::onMouseScrolled);
ofRemoveListener(ofEvents().windowResized, (BaseEngine*)this, &BaseEngine::onWindowResized);
invalidateDeviceObjects();
isSetup = false;
}
void remapToGLFWConvention(int& button)
{
switch (button)
{
case 0 :
{
break;
}
case 1:
{
button = 2;
break;
}
case 2:
{
button = 1;
break;
}
}
}
void EngineGLFW::onMousePressed(ofMouseEventArgs& event)
{
int button = event.button;
if(button >= 0 && button < 5)
{
remapToGLFWConvention(button);
ImGuiIO& io = ImGui::GetIO();
io.MouseDown[button] = true;
}
}
void EngineGLFW::onMouseReleased(ofMouseEventArgs& event)
{
int button = event.button;
if(button >= 0 && button < 5)
{
remapToGLFWConvention(button);
ImGuiIO& io = ImGui::GetIO();
io.MouseDown[button] = false;
}
}
void EngineGLFW::programmableRenderDrawLists(ImDrawData * draw_data)
{
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
ImGuiIO& io = ImGui::GetIO();
int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
if (fb_width == 0 || fb_height == 0)
return;
draw_data->ScaleClipRects(io.DisplayFramebufferScale);
// Backup GL state
GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src);
GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst);
GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb);
GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
glActiveTexture(GL_TEXTURE0);
// Setup viewport, orthographic projection matrix
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
const float ortho_projection[4][4] =
{
{ 2.0f / io.DisplaySize.x, 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f / -io.DisplaySize.y, 0.0f, 0.0f },
{ 0.0f, 0.0f, -1.0f, 0.0f },
{ -1.0f, 1.0f, 0.0f, 1.0f },
};
glUseProgram(g_ShaderHandle);
glUniform1i(g_AttribLocationTex, 0);
glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
glBindVertexArray(g_VaoHandle);
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
const ImDrawIdx* idx_buffer_offset = 0;
glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.size() * sizeof(ImDrawVert), (GLvoid*)&cmd_list->VtxBuffer.front(), GL_STREAM_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx), (GLvoid*)&cmd_list->IdxBuffer.front(), GL_STREAM_DRAW);
for (const ImDrawCmd* pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++)
{
if (pcmd->UserCallback)
{
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
}
idx_buffer_offset += pcmd->ElemCount;
}
}
// Restore modified GL state
glUseProgram(last_program);
glBindTexture(GL_TEXTURE_2D, last_texture);
glBindVertexArray(last_vertex_array);
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
glBlendFunc(last_blend_src, last_blend_dst);
if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
}
void EngineGLFW::fixedRenderDrawLists(ImDrawData * draw_data)
{
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
ImGuiIO& io = ImGui::GetIO();
int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
if (fb_width == 0 || fb_height == 0)
return;
draw_data->ScaleClipRects(io.DisplayFramebufferScale);
// We are using the OpenGL fixed pipeline to make the example code simpler to read!
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnable(GL_TEXTURE_2D);
//glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context
// Setup viewport, orthographic projection matrix
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
// Render command lists
#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
const unsigned char* vtx_buffer = (const unsigned char*)&cmd_list->VtxBuffer.front();
const ImDrawIdx* idx_buffer = &cmd_list->IdxBuffer.front();
glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, pos)));
glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, uv)));
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, col)));
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback)
{
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer);
}
idx_buffer += pcmd->ElemCount;
}
}
#undef OFFSETOF
// Restore modified state
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glBindTexture(GL_TEXTURE_2D, last_texture);
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glPopAttrib();
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
}
void EngineGLFW::onKeyReleased(ofKeyEventArgs& event)
{
int key = event.keycode;
ImGuiIO& io = ImGui::GetIO();
io.KeysDown[key] = false;
io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL];
io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT];
io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT];
if(key < GLFW_KEY_ESCAPE)
{
io.AddInputCharacter((unsigned short)event.codepoint);
}
}
bool EngineGLFW::createDeviceObjects()
{
if(ofIsGLProgrammableRenderer())
{
// Backup GL state
GLint last_array_buffer, last_vertex_array;
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
const GLchar *vertex_shader =
"#version 330\n"
"uniform mat4 ProjMtx;\n"
"in vec2 Position;\n"
"in vec2 UV;\n"
"in vec4 Color;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* fragment_shader =
"#version 330\n"
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n"
"}\n";
g_ShaderHandle = glCreateProgram();
g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(g_VertHandle, 1, &vertex_shader, 0);
glShaderSource(g_FragHandle, 1, &fragment_shader, 0);
glCompileShader(g_VertHandle);
glCompileShader(g_FragHandle);
glAttachShader(g_ShaderHandle, g_VertHandle);
glAttachShader(g_ShaderHandle, g_FragHandle);
glLinkProgram(g_ShaderHandle);
g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position");
g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV");
g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color");
glGenBuffers(1, &g_VboHandle);
glGenBuffers(1, &g_ElementsHandle);
glGenVertexArrays(1, &g_VaoHandle);
glBindVertexArray(g_VaoHandle);
glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
glEnableVertexAttribArray(g_AttribLocationPosition);
glEnableVertexAttribArray(g_AttribLocationUV);
glEnableVertexAttribArray(g_AttribLocationColor);
#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
#undef OFFSETOF
createFontsTexture();
// Restore modified GL state
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
glBindVertexArray(last_vertex_array);
return true;
}
else
{
createFontsTexture();
return true;
}
}
bool EngineGLFW::createFontsTexture()
{
// Build texture atlas
ImGuiIO& io = ImGui::GetIO();
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader.
// Backup GL state
GLint last_texture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
// Upload texture to graphics system
glGenTextures(1, &g_FontTexture);
glBindTexture(GL_TEXTURE_2D, g_FontTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
// Store our identifier
io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
// Restore state
glBindTexture(GL_TEXTURE_2D, last_texture);
return true;
}
void EngineGLFW::invalidateDeviceObjects()
{
if (ofIsGLProgrammableRenderer()) {
if (g_VaoHandle) glDeleteVertexArrays(1, &g_VaoHandle);
if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle);
if (g_ElementsHandle) glDeleteBuffers(1, &g_ElementsHandle);
g_VaoHandle = g_VboHandle = g_ElementsHandle = 0;
glDetachShader(g_ShaderHandle, g_VertHandle);
glDeleteShader(g_VertHandle);
g_VertHandle = 0;
glDetachShader(g_ShaderHandle, g_FragHandle);
glDeleteShader(g_FragHandle);
g_FragHandle = 0;
glDeleteProgram(g_ShaderHandle);
g_ShaderHandle = 0;
}
if (g_FontTexture)
{
glDeleteTextures(1, &g_FontTexture);
ImGui::GetIO().Fonts->TexID = 0;
g_FontTexture = 0;
}
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.